diff --git a/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md b/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md index d69510908..0bea1ec06 100644 --- a/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md +++ b/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md @@ -7,7 +7,7 @@ - docs 保存产品设计、原理、用法、API 与使用边界;rulebook 保存修改要求;四个标准 SKILL.md 保存工作流;records 保存计划、决策和证据。 - [598 项迁移清单](../plans/docs-agent-migration.json) 覆盖全部基线文件;72 份原始附件哈希不变;[434 页审查登记](../plans/docs-agent-page-review.json) 覆盖全量分类、链接、包含和迁移发现。 - 246 个实际项目均有唯一同名入口,测试与 fixture 页统一位于 development/testing;59 个长入口按完整 API 章节拆分,Native .Api 分片仍由原入口纳入覆盖。 -- [规则登记](../../rulebook/coverage.json) 保留 241 条原规则和 26 个补充来源章节,形成 58 个完整加载单元。根 AGENTS 为 3268 字节;每阶段包含根指令并受 16 KiB 预算约束,不截断规则。 +- 规则登记(`.agents/rulebook/coverage.json`) 保留 241 条原规则和 26 个补充来源章节,形成 58 个完整加载单元。根 AGENTS 为 3268 字节;每阶段包含根指令并受 16 KiB 预算约束,不截断规则。 - 规则、skill 与记录不进入默认 docs 查询;记录修改不进入 Native 配方或全部测试的政策输入。未知可执行 Agent 输入仍保守扩大验证范围。 - 引擎运行逻辑、公开产品 API、第三方、生成绑定和相邻仓库未修改。 diff --git a/.agents/records/acceptance/README.md b/.agents/records/acceptance/README.md index 0d488c646..385c96a38 100644 --- a/.agents/records/acceptance/README.md +++ b/.agents/records/acceptance/README.md @@ -1,36 +1,37 @@ # Acceptance records -- [CI/CD test ownership](cicd-test-migration.md) and [CI/CD performance](cicd-performance.md): test ownership, hosted certification and matched latency measurements. +[Records](../README.md) · [Open work](../open-items.md) · [Current acceptance](../acceptance/current.md) + +Each record establishes only its stated inputs, commit, environment and execution scope. Historical passes do not certify current inputs. Preserve original attachment bytes; the migration inventory separately identifies historical attachment links unavailable from Git. +Start from [current acceptance](current.md). Data files, probes and attachment directories sit beside the record that cites them. + +## Summarized records + +- [CI/CD test ownership](cicd-test-migration.md) and [CI/CD performance](cicd-performance.md): test ownership, hosted certification and matched latency measurements. - [Source certificate normalization](SOURCE_CERTIFICATE_NORMALIZATION_2026_11_13.md): real aggregate memory failure, shared input tables, exact input preservation and bounded imports. - [Full matrix and actual draft release](FULL_MATRIX_AND_DRAFT_RELEASE_2026_11_13.md): both extended platform jobs, ten warm samples, 1,000-cycle product journeys, exact-artifact draft upload and protected cleanup. - - [Script example receipt integration](CI_43191512147.md): 334 successful macOS checks followed by a reproduced report-format failure, real compiler/receipt regression and strict surface identities. - - [Documentation input compatibility](DOCUMENTATION_INPUT_COMPATIBILITY_2026_11_12.md): per-owner source/example provenance, authenticated baseline import, precise compatibility rejection and current query observations. - - [Static validation ownership and rule-source batching](STATIC_VALIDATION_SCOPE_2026_11_12.md): shared discovery, preserved conservative fallbacks, actual rule-loading samples and hosted Docs projection results. - - [Windows success and macOS follow-up](CI_43164720103.md): actual platform results, physical temporary roots, target-scoped examples and the remaining incremental certification gap. - - [Independent documentation merge gate](DOCUMENTATION_PAIRING_GATE_2026_11_12.md): exact merged Docs evidence, candidate-race rejection and explicit protected activation prerequisites. - - [Windows CI diagnosis and follow-up](CI_43067538817.md): real passing workloads, metadata/script failures, read-only capture, test scope and external setup. - - [Explicit documentation source certificates](DOCUMENTATION_SOURCE_CERTIFICATES_2026_11_12.md): authenticated preparation, complete reference coverage, read-only evidence and observed test latency. - - [Documentation publication receipts](DOCUMENTATION_PUBLICATION_RECEIPTS_2026_11_12.md): reconciled source/content correspondence for artifact-only promotion. - [Missing source capture execution](CI_MISSING_REFERENCE_CAPTURE_2026_11_12.md): independent execution, prepared capture and retained blocked certification. - [Canonical documentation cutover](DOCUMENTATION_LEGACY_CUTOVER_2026_11_12.md): physical legacy removal and preserved regression responsibilities. - -[Records](../README.md) · [Open work](../open-items.md) · [Current acceptance](../acceptance/current.md) - - [Logo, default font icons and attribution](LOGO_BRANDING_2026_11_07.md): outlined icons, v2 artwork and removal of embedded images; current and original evidence are recorded separately. - -Each record establishes only its stated inputs, commit, environment and execution scope. Historical passes do not certify current inputs. Preserve original attachment bytes; the migration inventory separately identifies historical attachment links unavailable from Git. - - [English migration CI candidate 42934085309](CI_42934085309.md): actual macOS failures, partial passing evidence, timing attribution and Windows runner communication loss. +- [Previous documentation and agent information-architecture acceptance](DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md) +## Index + +- [AI_PIPELINE_CI_CLOSURE_2026_11_06.md](AI_PIPELINE_CI_CLOSURE_2026_11_06.md) +- [API_DRAFT_PIPELINE_2026_11_13.md](API_DRAFT_PIPELINE_2026_11_13.md) +- [API_ELEMENT_PAGES_2026_11_14.md](API_ELEMENT_PAGES_2026_11_14.md) +- [API_GENERIC_NAMES_2026_11_14.md](API_GENERIC_NAMES_2026_11_14.md) +- [API_READING_LAYOUT_2026_11_14.md](API_READING_LAYOUT_2026_11_14.md) - [ARCHITECTURE_BGCS_CORE_REUSE_2026_10_21.md](ARCHITECTURE_BGCS_CORE_REUSE_2026_10_21.md) - [ATOMIC_FILE_PUBLICATION_ACCEPTANCE_2026_10_29.md](ATOMIC_FILE_PUBLICATION_ACCEPTANCE_2026_10_29.md) - [BGCS301_BROWSER_AGGREGATE_ABI.md](BGCS301_BROWSER_AGGREGATE_ABI.md) @@ -42,10 +43,24 @@ Each record establishes only its stated inputs, commit, environment and executio - [BUILD_COST_TOOL_HOST_DISK_CLOSURE_ACCEPTANCE.md](BUILD_COST_TOOL_HOST_DISK_CLOSURE_ACCEPTANCE.md) - [BUILD_ENTRY_CACHE_WIKI_REFINEMENT_ACCEPTANCE.md](BUILD_ENTRY_CACHE_WIKI_REFINEMENT_ACCEPTANCE.md) - [BUILD_ENTRY_CACHE_WIKI_REMEDIATION_2026_10_12.md](BUILD_ENTRY_CACHE_WIKI_REMEDIATION_2026_10_12.md) +- [CI_DOCUMENTATION_CANDIDATES_2026_11_11.md](CI_DOCUMENTATION_CANDIDATES_2026_11_11.md) +- [CI_NATIVE_PREFLIGHT_2026_11_11.md](CI_NATIVE_PREFLIGHT_2026_11_11.md) +- [CI_SHARED_DOCUMENTATION_CONTEXT_2026_11_12.md](CI_SHARED_DOCUMENTATION_CONTEXT_2026_11_12.md) - [CURRENT_ARCHITECTURE_REVIEW_2026_10_12.md](CURRENT_ARCHITECTURE_REVIEW_2026_10_12.md) - [CURRENT_ENGINE_OPEN_ITEMS_2026_10_15.md](CURRENT_ENGINE_OPEN_ITEMS_2026_10_15.md) - [CURRENT_FRAMEWORK_REVIEW_2026_10_14.md](CURRENT_FRAMEWORK_REVIEW_2026_10_14.md) - [DISK_CLEANUP_20261013.md](DISK_CLEANUP_20261013.md) +- [DOCUMENTATION_API_PREREQUISITES_2026_11_11.md](DOCUMENTATION_API_PREREQUISITES_2026_11_11.md) +- [DOCUMENTATION_DISPOSITIONS_2026_11_11.md](DOCUMENTATION_DISPOSITIONS_2026_11_11.md) +- [DOCUMENTATION_EVIDENCE_RELAY_2026_11_12.md](DOCUMENTATION_EVIDENCE_RELAY_2026_11_12.md) +- [DOCUMENTATION_EXAMPLE_EVIDENCE_2026_11_12.md](DOCUMENTATION_EXAMPLE_EVIDENCE_2026_11_12.md) +- [DOCUMENTATION_HISTORY_PRESERVATION_2026_11_11.md](DOCUMENTATION_HISTORY_PRESERVATION_2026_11_11.md) +- [DOCUMENTATION_QUERY_PREPARATION.md](DOCUMENTATION_QUERY_PREPARATION.md) +- [DOCUMENTATION_REFERENCE_SNAPSHOTS_2026_11_11.md](DOCUMENTATION_REFERENCE_SNAPSHOTS_2026_11_11.md) +- [DOCUMENTATION_RULE_AUTHORITY_2026_11_12.md](DOCUMENTATION_RULE_AUTHORITY_2026_11_12.md) +- [DOCUMENTATION_SCRIPT_SURFACES_2026_11_13.md](DOCUMENTATION_SCRIPT_SURFACES_2026_11_13.md) +- [DOCUMENTATION_SOURCE_COMPARISON_2026_11_11.md](DOCUMENTATION_SOURCE_COMPARISON_2026_11_11.md) +- [DOCUMENTATION_WRITER_CONCURRENCY.md](DOCUMENTATION_WRITER_CONCURRENCY.md) - [EDITOR_DEFAULT_LAYOUT_ACCEPTANCE_2026_10_29.md](EDITOR_DEFAULT_LAYOUT_ACCEPTANCE_2026_10_29.md) - [EDITOR_UI_ACCEPTANCE_2026_10_27.md](EDITOR_UI_ACCEPTANCE_2026_10_27.md) - [EDITOR_UI_CAPTURE_TAIL_ACCEPTANCE_2026_10_30.md](EDITOR_UI_CAPTURE_TAIL_ACCEPTANCE_2026_10_30.md) @@ -57,6 +72,7 @@ Each record establishes only its stated inputs, commit, environment and executio - [EDITOR_UI_SCRIPT_PUBLICATION_ACCEPTANCE_2026_10_30.md](EDITOR_UI_SCRIPT_PUBLICATION_ACCEPTANCE_2026_10_30.md) - [EDITOR_UI_SNAPSHOT_ACCEPTANCE_2026_10_29.md](EDITOR_UI_SNAPSHOT_ACCEPTANCE_2026_10_29.md) - [ENTRY_PROJECT_BUILD_SIMPLIFICATION_ACCEPTANCE.md](ENTRY_PROJECT_BUILD_SIMPLIFICATION_ACCEPTANCE.md) +- [EXTERNAL_DOCUMENTATION_VALIDATION_2026_11_11.md](EXTERNAL_DOCUMENTATION_VALIDATION_2026_11_11.md) - [FINAL_PLATFORM_RELOAD_NUGET_ACCEPTANCE.md](FINAL_PLATFORM_RELOAD_NUGET_ACCEPTANCE.md) - [FULL_ENGINE_AUDIT_2026_10_24.md](FULL_ENGINE_AUDIT_2026_10_24.md) - [ISSUE58_DYNAMIC_MODAL_ACCEPTANCE.md](ISSUE58_DYNAMIC_MODAL_ACCEPTANCE.md) @@ -70,13 +86,13 @@ Each record establishes only its stated inputs, commit, environment and executio - [NET10_BGCS3_PROGRESS_2026_10_20.md](NET10_BGCS3_PROGRESS_2026_10_20.md) - [NET10_CSHARP14.md](NET10_CSHARP14.md) - [NET10_NON_BGCS_ACCEPTANCE_2026_10_18.md](NET10_NON_BGCS_ACCEPTANCE_2026_10_18.md) +- [OWNED_CACHE_RETIREMENT_2026_11_11.md](OWNED_CACHE_RETIREMENT_2026_11_11.md) - [PLATFORM_OWNERSHIP_CACHE_ACCEPTANCE_2026_10_22.md](PLATFORM_OWNERSHIP_CACHE_ACCEPTANCE_2026_10_22.md) - [PLATFORM_OWNERSHIP_CACHE_FILE_TREE_2026_10_22.md](PLATFORM_OWNERSHIP_CACHE_FILE_TREE_2026_10_22.md) - [PLUGIN_EVENTS_IDENTITY_ACCEPTANCE_2026_10_22.md](PLUGIN_EVENTS_IDENTITY_ACCEPTANCE_2026_10_22.md) +- [PR83_DOCUMENTATION_SCOPE_2026_11_16.md](PR83_DOCUMENTATION_SCOPE_2026_11_16.md) - [PRIORITY_FIX_ACCEPTANCE_2026_10_25.md](PRIORITY_FIX_ACCEPTANCE_2026_10_25.md) - [REPOSITORY_HYGIENE_ACCEPTANCE_2026_10_25.md](REPOSITORY_HYGIENE_ACCEPTANCE_2026_10_25.md) - [STANDARD_NUGET_RESTORE_ACCEPTANCE_2026_10_26.md](STANDARD_NUGET_RESTORE_ACCEPTANCE_2026_10_26.md) +- [VALIDATION_PROGRESS_2026_11_11.md](VALIDATION_PROGRESS_2026_11_11.md) - [WINDOWS_VULKAN_EXIT_FAILURE_2026_10_20.md](WINDOWS_VULKAN_EXIT_FAILURE_2026_10_20.md) -- [current.md](current.md) - -- [Previous documentation and agent information-architecture acceptance](DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md) diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md new file mode 100644 index 000000000..cf6b679c2 --- /dev/null +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -0,0 +1,85 @@ +# C# code style rulebook + +[Decisions](README.md) · [Rule authority](../../rulebook/csharp-style/README.md) + +The user reviewed a complete audit of the handwritten C# source, revised the proposed rules on 2026-11-21 and approved one detailed style authority for humans and agents. The [C# code style rulebook](../../rulebook/csharp-style/README.md) is that authority for names and layout. The [coding rules](../../rulebook/coding.md) keep design, error-handling, resource and change-management requirements. + +## Registration + +The rulebook is a new authority, not a translation. Its complete text was committed first; the rule registry pins the preface and each chapter to that immutable source revision by section index and hash. Every chapter is one complete unit below the staged-read budget, and `.cs` paths select all of them. + +Changing a rule requires committing the new chapter text, then updating that unit's `source` and `sourceHash` in the registry. Updating a hash without a committed source is not a rule change. + +## Approved replacements + +These clauses of the existing coding rules contradicted the approved rulebook. Each replacement is a substantive amendment, not a translation. Original source hashes and translation mappings remain unchanged in the registry; one amendment hash binds each active line to this decision. + +| Unit | Replaced clause | Active clause | Rule | +| --- | --- | --- | --- | +| `naming` | Namespaces match the directory hierarchy by default. | A namespace equals the assembly name of its owning project; directories add no segments. | N-02 | +| `naming` | Constants use `C_` or clearly meaningful readonly static names. | Constants use `C_`; static readonly fields use unprefixed UPPER_SNAKE. | NM-07, NM-08 | +| `csharp-standard-1` | Namespaces follow their owning directory or project convention. | Namespaces follow their owning project. | N-02 | +| `csharp-standard-2` | Example `targetId`. | Example `targetID`. | NM-13 | +| `csharp-standard-2` | Static readonly members use clear semantic names such as `DefaultOptions`. | Static readonly fields use unprefixed UPPER_SNAKE such as `DEFAULT_OPTIONS`. | NM-08 | +| `csharp-standard-4` | Example parameter `commandId` (three lines). | Example parameter `commandID`. | NM-13 | + +All other clauses of those units remain in force. Where a general clause and a rulebook rule cover the same subject, the rulebook rule is the detailed form. + +## Interpretations + +The rulebook resolves these points where the approved revisions allowed more than one reading: + +- Conditional-expression continuations align with the condition; call-chain continuations indent four spaces. +- Every empty method, constructor and lambda body is `{}`; property patterns keep `{ }`. +- A multi-line header of `if`, `for`, `foreach`, `while`, `using`, `lock` and `fixed` closes with `) {`. +- Only an `if` without `else` whose statement fits on the same line may omit braces. +- Additional `where` clauses align with the first. +- A multi-line collection expression may open with `[` directly before its first element. +- Two-letter acronyms are lowercase at the start of a camelCase name and uppercase elsewhere. +- Column alignment is recommended from four consecutive declarations of one type. + +## Consequences + +Formatting and renaming are separate changes: formatting-only changes preserve syntax tokens, and acronym or field renames that touch public members are API changes. `.editorconfig` and the style validator express the naming table of the rulebook. + +## Tooling status + +`InnoEngine.Build style check|fix ROOT` checks handwritten C# against the rulebook by rule ID and applies the automatic fixes; the architecture validator runs the same engine. A layout fix keeps the token sequence, a reorder keeps the token multiset, and a rewrite is rejected unless the result parses. + +The engine currently enforces these rules. A finding is reported under the first ID of its group. + +| Reported ID | Also covers | +| --- | --- | +| F-01, F-02, F-03, F-04, F-05 | | +| N-01, N-03, N-04, N-05 | N-06 | +| NM-01 to NM-13 | | +| T-01, T-02, T-03, T-04 | | +| M-02, M-03, M-04, M-05 | | +| O-01 | O-02 | +| B-01, B-04, B-05, B-07 | B-06, B-08 | +| B-03 | T-06 | +| B-09 | M-01 | +| P-01, P-02, P-03 | | +| A-01, A-02 | A-03 | +| W-01, W-03, W-04, W-05 | W-02 | +| I-01, I-02, I-05 | I-03, I-04 | +| S-03, S-04 | | +| E-01, E-03, E-04, E-05, E-06, E-07, E-08, E-09, E-10, E-11, E-12 | | +| D-02, D-05, D-06 | D-04 | + +Every other rule is not yet checked by the tool and is enforced in review: N-02, T-05, T-07, T-08, B-02, A-04, S-01, S-02, E-02, all X rules, D-03 and all TS rules. The compiler enforces D-01 through `CS1591`. The checks for N-05, E-04 and E-08 read syntax only: N-05 recognizes a qualified name by its root namespace, E-04 reports a negated `is null` and leaves `==` comparisons to review because an overloaded operator is not visible in syntax, and E-08 knows the members that the same type declaration declares. The naming check reads syntax only: it trusts the names of overrides, interface implementations, native interop declarations and serialized members, and it exempts test methods from the `Async` suffix. `.editorconfig` states the same naming table for editors. + +These checks read syntax only and report the part of a rule that syntax decides: + +| ID | Reported | Left to review | +| --- | --- | --- | +| F-02 | A file that declares no type named like it, a primary type that is not first, and a second top-level type other than an enum, a delegate or a positional record. `Type.Part.cs` is named after `Type`. | Whether the companion is used only by the primary type. | +| M-02 | A block body that is one `return`, call, assignment or `throw`; a constructor with an expression body. | A body that holds a comment or a directive. | +| P-03 | A `CancellationToken` parameter of a declaration that is not named `cancellationToken` or is not the last parameter. | A required token that precedes optional or `params` parameters, and lambda parameters. | +| W-04 | A line break directly before or after `=`; the fix joins the lines. | | +| I-02 | A declaration typed as an array or `List` (or a `var` local) whose value is `new[] {}`, `new T[] {}`, `Array.Empty()` or a `List` creation without constructor arguments. | A creation without a target type: a call receiver, an inferred generic argument, an anonymous-type member. | +| E-05 | A hand-written `if` that throws `ArgumentNullException` for the tested name, and `?? throw new ArgumentNullException(nameof(x))` on a parameter in a statement of a block body. | Expression bodies and initializers, range checks, custom messages. | +| E-06 | `new()` as an argument, a collection element, an operand, a branch or a local initializer. | | +| E-09 | `string.Format` with a literal format and `string.Concat` with two or more arguments. | A format that is itself a value, and `string.Concat` of one sequence. | +| E-12 | A `using` statement with a declaration that ends its block; the fix writes the declaration. | A `using` statement over an expression, and one whose names collide with a sibling scope. | +| D-06 | `#region`, `#endregion`, `#nullable` and `/* */` block comments. | Comment language, markers, commented-out code and unexplained `#pragma`. | diff --git a/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md new file mode 100644 index 000000000..142c6679c --- /dev/null +++ b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md @@ -0,0 +1,11 @@ +# Human commit attribution + +[Decisions](README.md) · [Rule authority](../../rulebook/delivery.md) + +On 2026-11-21 the user replaced the delivery clause that named one person as the required Git author and committer. The requirement is a principle, not an identity: a human vouches for every commit. + +The active clause requires the Git author and committer to be the human contributor responsible for the commit, and forbids any agent, bot or application identity as author, committer, `Co-authored-by` or any other attribution. It applies to every contributor and every tool, so the rule no longer needs to change when contributors do. + +This is a substantive approved amendment, not an English translation. The original source hash and translation mapping remain unchanged in the rule registry; one amendment hash binds the active wording to this decision. The requirement to create pull requests with the GitHub account authorized by the user, and all other delivery obligations, remain in force. + +An agent whose environment adds its own attribution does not commit; it hands the change to an environment that commits solely in the responsible human's name. diff --git a/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md new file mode 100644 index 000000000..ef76fc330 --- /dev/null +++ b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md @@ -0,0 +1,17 @@ +# Plain Markdown rules + +[Decisions](README.md) · [Rulebook](../../rulebook/README.md) + +On 2026-11-21 the user retired the rule registry. It was built to prove a one-time migration and translation, and it had become the mechanism for every later rule change: a changed sentence needed a registry amendment, a recomputed hash and a decision record, and a new rule file needed two commits. + +- Rules are plain Markdown. Each rule file states its own `paths` and `tags` in front matter; there is no central registry and no dependency list. +- A human merges every rule change through a pull request. That review replaces hash locking. +- `coverage.json`, its source identities, line hashes, translation mappings, amendments and approved-addition markers are removed without an archive or a compatibility path. Git history keeps them. +- The rule script selects files and checks front matter, the size limits and the routing examples. It needs no Git history and prints a file list instead of rule bodies. +- One topic per file within 16 KiB. The C# code style became one file per chapter; the Editor and Build and Native domains became directories; sections that former dependencies always loaded together now share a file. +- Paths are whole-path globs instead of unanchored regular expressions. Names such as `State` or `assets` outside their owners no longer select Editor state or identity rules. Editor state now applies to all Editor sources and tests, Editor UI to the presentation and panel directories, and identity rules also to references, extensibility reload and core identity. +- InnoEngine.Docs owns its rule files with the same front matter. The engine script reads them only from an explicit `-DocsRoot`. + +Earlier decision records describe changes in registry terms. Their rule text remains in force; the registry mechanics no longer apply. + +The same change removed environment-specific guidance: the local output drive, a platform sound path and a personal name used as an example. diff --git a/.agents/records/decisions/README.md b/.agents/records/decisions/README.md index 2ecab0349..a7f1dc623 100644 --- a/.agents/records/decisions/README.md +++ b/.agents/records/decisions/README.md @@ -4,4 +4,19 @@ Record durable reasons, constraints and tradeoffs, with links to the current authoritative mechanism. Ordinary style adjustments, mechanical moves and local fixes do not require decision records. Move superseded designs to history rather than duplicating them as current rules. +## Rule authority + +- [Plain Markdown rules](PLAIN_MARKDOWN_RULES.md): rule files declare their own paths and tags; the hash registry is retired and a human merges every rule change. - [English rule preservation](ENGLISH_RULE_PRESERVATION.md): original rule identities, clause correspondence, reviewed meaning and explicitly approved ownership/language changes. +- [C# code style rulebook](CSHARP_STYLE_RULEBOOK.md): the detailed style authority, its registration and the coding clauses it replaced. +- [Root test ownership](ROOT_TEST_OWNERSHIP.md): one root tests boundary replacing backend-local test ownership. + +## Delivery + +- [Human commit attribution](HUMAN_COMMIT_ATTRIBUTION.md): a human vouches for every commit; no agent, bot or application attribution. + +## Documentation and API + +- [API draft rule amendment](API_DRAFT_RULE_AMENDMENT.md) with its [clause changes](API_DRAFT_RULE_CHANGES.json): the draft/main API workflow. +- [API author metadata rule amendment](API_AUTHOR_METADATA_RULE_AMENDMENT.md) with its [clause changes](API_AUTHOR_METADATA_RULE_CHANGES.json): named prose ownership per API element. +- [API scope clause changes](API_SCOPE_RULE_CHANGES.json): the Engine API ownership boundary. diff --git a/.agents/rulebook/README.md b/.agents/rulebook/README.md index 023edeba5..81a4fd3ff 100644 --- a/.agents/rulebook/README.md +++ b/.agents/rulebook/README.md @@ -2,28 +2,47 @@ This directory owns requirements for changing the engine. Product design, mechanisms, usage and contracts belong to [InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs). Task progress and historical evidence belong to [records](../records/README.md). Humans and agents follow the same requirements. -Run `tests/ci/Test-AgentRules.ps1 -Paths -ShowInstructions` from the engine root to discover complete units. Add explicit units with `-Rules`, behavior tags with `-Behaviors`, and read stages with `-Stage`. [coverage.json](coverage.json) is the sole registry of authorities, sources, applicability and required relationships. +## Read the rules for a change -Behavior tags describe the work: for example, `new-boundary`, `public-api`, `ownership`, `serialization`, `reload`, `native`, `documentation`, `rules`, `skills`, `records` and `delivery`. Multiple paths, tags and dependencies may select one unit. Its complete body appears once with all selection reasons. +Run `pwsh tests/ci/Test-AgentRules.ps1 -Paths ` from the engine root. It lists the rule files that apply to those paths; read each listed file completely. Add `-Tags` for the kind of work and `-Rules` for a specific file. A rule ID is the file path under this directory without `.md`, for example `coding` or `csharp-style/03-naming`. -| Responsibility | Authority | +Tags describe the work: for example, `new-boundary`, `public-api`, `ownership`, `serialization`, `reload`, `native`, `documentation`, `rules`, `skills`, `records` and `delivery`. + +| Responsibility | Rules | | --- | --- | -| Architecture, boundaries, reuse and project ownership | [Architecture](architecture.md) | +| Architecture, boundaries, reuse and ownership | [Architecture](architecture.md) | +| Retired compatibility layers and schema versions | [No legacy compatibility](no-legacy.md) | +| Directories, solutions and project files | [Solutions and projects](projects.md) | | Naming, XML, formatting, exceptions and concurrency | [Coding](coding.md) | -| Documentation, API, examples and content ownership | [Docs authority](https://github.com/Wolfiora/InnoEngine.Docs/blob/docs-modernization/.agents/rulebook/documentation.md); load with an explicit `-DocsRoot` | +| C# names, layout, line breaks and idioms, with examples | [C# code style](csharp-style/README.md) | +| Documentation, API, examples and content ownership | [Documentation](documentation.md), owned by InnoEngine.Docs | | Tests, compilation, completion and review | [Validation](validation.md) | | Commits, PRs and notifications | [Delivery](delivery.md) | -| Editor | [Editor](domains/editor.md) | +| Editor | [Projects](domains/editor/projects.md), [state](domains/editor/state.md) and [UI](domains/editor/ui.md) | | Identity, Missing and reload | [Identity and reload](domains/identity-reload.md) | | Scripting | [Scripting](domains/scripting.md) | | Plugins | [Plugins](domains/plugins.md) | | Rendering and frames | [Rendering](domains/rendering.md) | -| Builds, Native and platforms | [Build and Native](domains/build-native.md) | +| Builds, Native and platforms | [Hosts](domains/build-native/hosts.md), [platform products](domains/build-native/platform-products.md) and [backend integration](domains/build-native/backend-integration.md) | + +## Add or change a rule + +Rules are plain Markdown. Edit a file or add a new one, then open a pull request; a human merges it. Record a lasting decision in [decisions](../records/decisions/README.md) when its reason will matter later. -Load complete sections. Combining units into a file does not require every task to load that whole file. The checker retains all 241 original rule mappings and supplemental source requirements. Updating a target hash is not semantic preservation. +Every rule file starts with front matter that states when it applies: -English translations retain their original Git source identities and register every nonblank source/target line, including headings, examples and nested requirements. Original numbered clauses link to their English targets. The [translation review](../records/decisions/ENGLISH_RULE_PRESERVATION.md) records reviewed obligations and any interpretation. Automated coverage detects omissions and unregistered changes; the implementing owner remains responsible for semantic equivalence. Units not yet translated retain exact source-text verification. +```markdown +--- +paths: ["src/services/rendering/**", "tests/rendering/**"] +tags: [rendering] +--- +# Rendering +``` -Explicitly approved additional requirements may follow `` in an existing unit. Register the approval and the addition's SHA-256 in `approvedAddition`, using LF line endings and trimmed outer whitespace. The loader checks the original body or its reviewed translation separately, checks the addition, then emits both completely. This mechanism permits additions only; it does not authorize deleting or weakening existing rules. +- `paths` lists repository-relative globs that match the whole path. `**/` spans directories and `*` stays inside one name. Matching is case-sensitive. +- `tags` lists the work tags that select the file. +- Declare at least one of the two, each as a one-line list. +- Keep one topic per file and every file within 16 KiB. Split a larger topic into a directory. +- When routing changes, add a path that must select the file and one that must not to the [routing examples](../../tests/ci/Test-AgentRules.examples.json). -Explicit user-approved clause replacements use `translation.amendments`, each identifying the ordinal, original translated hash, new active hash, approval and decision record. Original provenance and translation mappings remain intact. The loader rejects unmapped, duplicate, altered or undocumented amendments; this mechanism does not infer approval from a hash update. +Run the script without arguments to check every rule file, the root instruction size and the routing examples. diff --git a/.agents/rulebook/architecture.md b/.agents/rulebook/architecture.md index 9ab200991..2dc4f832d 100644 --- a/.agents/rulebook/architecture.md +++ b/.agents/rulebook/architecture.md @@ -1,52 +1,18 @@ +--- +tags: [architecture, new-boundary, ownership, public-api, encapsulation, core-reuse, style] +--- # Architecture -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 1. Project style - Preserve the repository's consistent readability and extensibility. - Prioritize clear layering, explicit boundaries and low coupling. - Write all new comments in English by default, especially public API documentation. - - - ## 4. Encapsulation and responsibility - Expose the minimum necessary public API. - Prefer composition over inheritance. - Decouple through registries, factories and abstract interfaces. - - - - -## 10. Directory boundaries -- `src/foundation`: Core, extension catalogs, types and generation contracts. -- `src/content`: Assets, References, Scene and Animation. -- `src/services`: backend-neutral domain contracts and runtime services. -- `src/runtime`: Runtime, deployment, generators, Plugins and authoring-time scripting workflows. -- `src/adapters`: neutral SPIs, open Provider/Catalog contracts and Core Events input implementations. -- `backends/`: shared backend runtime, native code and build recipes; each component has one source owner. Component tests belong to `tests/backends/`. -- `platforms/`: system and SDK integration, explicit targets, thin Editor/Player entries, layouts and Support Packs. A platform must not reference another platform. -- `src/composition`: default engine, Shell, Player and Editor composition entries. -- `entry`: the two lightweight development entries and current-host routing. Other production layers must not reference it. `Inno.Packages.props` pins NuGet versions for the BGCS package family; no source-dependency entry is provided. -- `build`, `tools`, `tests`: neutral unified builds, concrete distribution registration, validation libraries and tests. All engine-owned tests, fixtures and test support belong to the root `tests` tree; upstream tests inside `extern` retain their upstream owner. Production projects must not reference test projects or test support. -- Place new files in directories matching the existing layers and responsibilities wherever possible. - - - - -## 15. No legacy compatibility or schema versions -- InnoEngine is a personal engine whose current source and current Project data evolve together. New or changed features do not support old files, schemas, fields, cache directories, namespaces, APIs or serialization layouts. Do not add fallback readers, migrations, compatibility aliases, former IDs, deprecated wrappers or dual writes for them. -- Persistence models, Attributes, Importers, Build Processors, History, Workspaces, Scenes, Prefabs, Asset metadata, Catalogs and script manifests must not introduce legacy-adaptation fields such as `version`, `schemaVersion`, `formatVersion` or `formerVersion`. When a format changes, update the current writer, reader, tests, documentation and Project data directly. Old data may be explicitly invalidated and regenerated. -- Do not reserve migration branches for hypothetical future compatibility. Only an explicit user request to import a particular old format permits a one-time converter with a clear boundary. Conversion logic must not enter normal runtime paths. -- Update all callers when deleting or refactoring an API. Do not retain old overloads, namespace facades, forwarding types or `[Obsolete]` compatibility layers unless the user explicitly requests them. -- These rules permit runtime identities required for current correctness, including TypeCache/Assembly generations, concurrency revisions, change counters, content hashes, artifact fingerprints, MVIDs, job-handle generations and strict magic/headers used only to reject damaged or incorrect input formats. They must not become mechanisms for reading multiple legacy schema generations. -- When reviewing or cleaning implementations named `version`, `legacy`, `migration`, `compatibility`, `former` or `deprecated`, first determine whether they serve only old data/APIs. If so, remove them together with their tests and documentation rather than extending them. - - - ## 21. Architecture, language frontends and third-party boundaries - Architectural clarity, dependency direction, responsibility and low coupling take precedence over every feature, performance goal and development convenience. Define the owning layer, public contracts, lifecycle and failure boundary before any feature or extension. Do not trade these for temporary direct connections, leaked implementation names, global singletons or convenient cross-layer calls. - General source assets in services and asset layers are inert text or byte carriers. Unless a language is explicitly an engine public standard, core importers, runtime services and script contracts must not parse, infer or depend on third-party syntax, or implicitly select semantics from the current backend or a filename. @@ -57,23 +23,25 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Backend-neutral low-level public APIs for source plugins are permitted and necessary. Minimal public exposure means the smallest stable surface needed for external plugin composition, not only gameplay-level APIs. Plugin-author APIs must explicitly enter script export manifests. Backend SPIs, native bridges, concrete implementations and third-party handles remain unexported. - Explicitly define ownership and lifetimes on frame hot paths. Do not unconditionally copy all geometry, indices or texture pixels every frame, or encode the same data again for each draw command. Prefer generation-scoped stable handles, incremental resource updates/releases, persistent GPU caches, and pooled or owned buffers with explicit release protocols. Optimization must not expose unsafe borrowed native memory through public layers. - New systems and boundary changes must also update architecture-validator project classification, solution ownership, dependency rules, native-consumption rules, scripting allowlists and public documentation. They are not complete until repository architecture validation passes. - - - ## 22. Reuse foundational capabilities - Before adding events, identity, serialization, mathematics, diagnostics or other foundational capabilities, check for existing contracts in `Inno.Core`. Prefer using or wrapping them directly. Do not build parallel management systems in upper layers such as UI, Canvas or plugins. - UI and plugin event subscription, dispatch and lifetimes reuse `Inno.Core.Events`. Domains may define their own event types and adapters, but must not replace core event management with another queue, listener registry or event bus. - - - -## 26. Solutions and project files +## 1. Design and responsibility + +- Prioritize architectural clarity, dependency direction, ownership, encapsulation and low coupling. +- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning project. +- Public APIs expose the smallest complete contracts needed for external composition. Prefer composition and supply dependencies through constructor parameters or explicit composition entries. +- Check existing repository events, identity, serialization, mathematics and diagnostics first. Reuse them and avoid parallel management systems. +- Interfaces or base classes express extension behavior; immutable discovery metadata is declared once. Replaceable boundaries isolate platforms, storage, compilers and presentation. +- Separate implementation from persistence protocols. Persistent data uses stable identities and neutral values; explicit lifetimes manage runtime objects, delegates and type references. +- Shared mechanisms, concrete backends, platform-system integration, product composition and build distributions each own their source. Shared mechanisms must not select concrete platforms or products. +- A build host describes only the tool execution environment. Requests explicitly select runtime target, CPU, ABI and managed deployment; do not infer them from host facts. +- One backend owns a third-party component's runtime, Native facade, binding configuration and build recipe. Platform products select them through capabilities and frozen descriptions. + +## Splitting responsibilities and changing boundaries + +Large owners may use partial files for independently understandable responsibilities, while fields, construction and the single lifecycle remain in the primary file. Move members and verify syntax tokens/order first; change behavior/performance separately. Public DTO filenames match their primary type, and closely related enums remain in the owning protocol. Do not create parallel event, identity or Undo managers merely to shorten files. -- Solution Folders represent actual architectural responsibilities. Remove empty groups containing neither valid projects nor Solution Items. Avoid unnecessary single-project wrapper groups for small project collections. -- Authored projects under `entry`, `src`, `backends`, `platforms`, `build`, `tools` and `tests` belong in the Solution, including binding-generation extensions and test fixtures. Exclude `obj`, `artifacts` and independent third-party projects in extern. A project without incoming ProjectReferences is not necessarily unused: check host entries, MSBuild tool calls and generator configuration before removing it. -- Use two-space indentation in `.csproj`, `.props` and `.targets`, blank lines between top-level responsibility blocks, one property per line in long property lists, and `/` in relative ProjectReference paths. -- Merge adjacent reference groups only when their conditions and reference visibility match. Do not reorder Imports, Properties or Targets, or change conditions, metadata or evaluation order. Preserve Editor public/implementation reference boundaries. -- Detailed rules are in `.agents/rulebook/coding.md`. After reorganization, verify valid XML, Solution project identities and configurations, then run affected builds and architecture validation. -- After phases of long builds or acceptance, clean this operation's obsolete tool snapshots, private load directories and test-browser profiles, and check free disk space. Before cleanup, verify the explicit owner, resolved absolute paths, symbolic links and active processes. Retain current artifacts and acceptance logs; do not clean user or SDK global caches. Logical sizes of hardlinked/compressed files do not establish physically reclaimed space. - +Public-contract changes update every consumer, reference visibility, script manifest, Stable ID, documentation, success/failure/boundary test and architecture gate. Record ownership, cancellation, thread affinity and final release for read streams, background tasks, snapshots, scratch, native callbacks and device resources. Performance conclusions require measurements; unmeasured values remain unknown. diff --git a/.agents/rulebook/coding.md b/.agents/rulebook/coding.md index d88269b74..7888e4bbd 100644 --- a/.agents/rulebook/coding.md +++ b/.agents/rulebook/coding.md @@ -1,22 +1,19 @@ +--- +paths: ["**/*.cs"] +tags: [naming, members, xml, errors, formatting, identity-naming, csharp-standard, public-api, ownership, documentation] +--- # Coding -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 2. Naming - Match filenames to their primary type. -- By default, match namespaces to directory hierarchy. `src/composition/editor` uses the project-level namespace rules in section 13. +- A namespace equals the assembly name of its owning project; directories inside a project do not add namespace segments. `src/composition/editor` uses the project-level namespace rules in section 13. - Use PascalCase for type names. - Prefix interfaces with I. - Use meaningful camelCase for member parameters. - Prefix private fields with m_. -- Constants use a C_ prefix, such as C_MAX_COUNT, or clearly meaningful readonly static names. +- Constants use a C_ prefix, such as C_MAX_COUNT. Static readonly fields use UPPER_SNAKE names without a prefix, such as DEFAULT_OPTIONS. - Keep existing Unity-style API names, such as transform, scene, active and name, consistent with surrounding code. - - - ## 3. Member organization - Group class members by access level and role, preferably near the top, in this order: 1. Constants (const / static) @@ -27,10 +24,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena 6. Private methods and utilities - Keep members of the same scope and type together where possible instead of scattering them through a class. - Public members come before restricted members. - - - ## 5. Comments must be English - All externally visible public members and protected members overridable by external derived types must have complete English XML documentation: - Types and members have a meaningful summary that does not merely repeat their names. @@ -42,26 +36,17 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Also document important internal APIs when their behavioral impact warrants it. - Chinese source comments are prohibited. Avoid leaving temporary comments such as TODO indefinitely. - Complex logic may have comments written as complete, concise English sentences. - - - ## 6. Error handling - Validate arguments first: use ArgumentNullException.ThrowIfNull and clear ArgumentException messages. - Distinguish safe failure from exceptional failure. - Report explicit exception information at important boundaries. - - - ## 7. Transform and Identity naming clarity - Align with upper-layer semantics and preserve the existing API naming style. - Avoid local names that collide with properties and cause shadowing or readability conflicts. - Keep internal caches consistent after property updates; avoid the unnecessary cost of repeated complete recomputation. - - - ## 23. Source readability and formatting - Use one clear alias for the same type within a file; do not alternate facade aliases for the same call. XML documentation describes current real members. Give each member one meaningful summary and remove descriptions of deleted members. - Readability is a continuous requirement for all handwritten source in InnoEngine, Canvas and Rendering2D. Generated bindings and third-party extern source are outside manual formatting. Formatting changes must preserve execution order, initialization order, public contracts, serialized data, diagnostics and user experience. @@ -83,58 +68,31 @@ public void AAA( // Method body. } ``` - - - # C# development requirements These requirements apply to handwritten C# source. Generated code and third-party source follow their generation protocols or upstream standards. Repository domain protocols and product-publication policies are supplied by their respective architecture documents. - - - - -## 1. Design and responsibility -- Prioritize architectural clarity, dependency direction, ownership, encapsulation and low coupling. -- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning directory or project convention. -- Public APIs expose the smallest complete contracts needed for external composition. Prefer composition and supply dependencies through constructor parameters or explicit composition entries. -- Check existing repository events, identity, serialization, mathematics and diagnostics first. Reuse them and avoid parallel management systems. -- Interfaces or base classes express extension behavior; immutable discovery metadata is declared once. Replaceable boundaries isolate platforms, storage, compilers and presentation. -- Separate implementation from persistence protocols. Persistent data uses stable identities and neutral values; explicit lifetimes manage runtime objects, delegates and type references. -- Shared mechanisms, concrete backends, platform-system integration, product composition and build distributions each own their source. Shared mechanisms must not select concrete platforms or products. -- A build host describes only the tool execution environment. Requests explicitly select runtime target, CPU, ABI and managed deployment; do not infer them from host facts. -- One backend owns a third-party component's runtime, Native facade, binding configuration and build recipe. Platform products select them through capabilities and frozen descriptions. - - - - ## 2. Naming | Element | Rule | Examples | | --- | --- | --- | | Types, methods, enum members | PascalCase | GenerationRequest, TryResolve, Borrowed | | Interfaces | I prefix | IOutputTransaction | -| Properties, parameters, locals | camelCase | targetId, outputDirectory | +| Properties, parameters, locals | camelCase | targetID, outputDirectory | | Private fields | m_ prefix | m_generation | | Constants | C_ prefix | C_MAX_COUNT | -| Static readonly members | Clear semantic names | DefaultOptions | +| Static readonly fields | UPPER_SNAKE without a prefix | DEFAULT_OPTIONS | - External interface implementations, overrides, special CLR members and external protocol signatures follow their contracts. - The corresponding generator configuration declares generated binding names. - Names convey meaning, units and ownership. Avoid abbreviations, meaningless helper names and local-variable shadowing. - Source property names and serialized wire names are declared separately. Naming refactors must not accidentally change data protocols. - - - ## 3. Member organization Group constants/static members, fields, constructors, public members, protected/internal members and private implementation in that order. Keep members of the same scope/type together and separate responsibilities with blank lines. - - - ## 4. Declarations and formatting - Keep zero/single-parameter functions and short expressions on one line when they fit a reasonable width. @@ -154,32 +112,24 @@ internal sealed class CommandSet private readonly Dictionary m_commands = new(StringComparer.Ordinal); internal void Register( - string commandId, + string commandID, Action command ) { - ArgumentException.ThrowIfNullOrWhiteSpace(commandId); + ArgumentException.ThrowIfNullOrWhiteSpace(commandID); ArgumentNullException.ThrowIfNull(command); - m_commands.Add(commandId, command); + m_commands.Add(commandID, command); } } ``` - - - ## 5. Using directives and compilation - Explicitly declare ordinary using directives in every file. - Global usings, implicit imports and MSBuild Using items are prohibited. - Enable nullable. Restrict unsafe code to actual interop boundaries and define buffer, pointer and resource lifetimes. - Resolve compilation targets and SDKs from project declarations. Caches do not replace correctness checks. - - - Handwritten C# must not use `global::` qualified names. Resolve conflicts with explicit ordinary using directives, clear file-level using type/namespace aliases or local renaming. Keep one alias per target rather than repeating fully qualified names at each use. Generated code, generator output templates and tests verifying that output follow their generation protocol; do not rewrite their qualified names to satisfy handwritten style rules. - - - ## 6. Documentation and comments - Source comments use English and explain reasons, constraints, ownership or lifetimes. @@ -189,10 +139,7 @@ internal sealed class CommandSet - Overrides and interface implementations may use inheritdoc; document additional constraints locally. - Template comments that merely restate names are prohibited. Use readable expanded XML tags. - XML-emitting projects treat CS1572, CS1573 and CS1591 as compilation errors. - - - ## 7. Validation, exceptions and transactions - Validate arguments first with ArgumentNullException.ThrowIfNull and clear ArgumentException messages. @@ -200,10 +147,7 @@ internal sealed class CommandSet - Fully prepare and validate candidates before atomic publication; failure retains last-good state. - Do not swallow critical exceptions, treat unsupported capabilities as success or use silent fallbacks. - API changes update current callers, documentation and tests and remove superseded paths. Format changes follow the owning product's current protocol. - - - ## 8. Resources, asynchronous work and concurrency - Identify the creator, owner, using thread, borrowing period, releaser and final release order. @@ -212,58 +156,10 @@ internal sealed class CommandSet - Callback exceptions must not cross unmanaged boundaries. After unregistration or cancellation, ensure callbacks no longer access released owners. - An explicit host manages shared process state. Avoid anonymous global state and global service locators. - Stop new work before retiring generation resources and verifying release. Preserve an explicit fault state on failure. - - - ## 9. Performance - Define hot-path caches, ownership and invalidation conditions. - Avoid per-frame complete scans, geometry/texture copies and duplicate command encoding. - Prefer incremental updates, stable handles, persistent resource caches and pooled buffers with explicit release protocols. - Do not expose borrowed native memory or expand public APIs for performance. - - - - -## 10. Tests and acceptance - -- Use real public contracts and replaceable public boundaries. -- InternalsVisibleTo, test backdoors, reflection bypasses and widening internal visibility for tests are prohibited. -- Cover real success, failure, cancellation, boundary and lifecycle behavior. Do not write tests that merely repeat the implementation. -- Native calls, AOT, trimming and platform support require actual artifact evidence. -- Report build, test, SDK, host and device status separately. Unexecuted checks are not passes. - - - - -## 11. Change management - -- Formatting-only changes preserve syntax tokens, execution order, contracts and diagnostics. -- Validate naming, responsibility and behavior changes separately from pure formatting. -- Public API, reference-boundary and generation-protocol changes also update consumers, indexes, examples and architecture checks. -- Before completion, ensure the target scope compiles and record validation commands, results and remaining limitations. - - - - -## 12. Solution and MSBuild readability - -- Solution Folders express actual responsibility layers. Remove groups without projects or valid Solution Items. Small repositories do not need extra categories wrapping single projects. -- Include all authored source projects in the Solution, including binding-generation extensions and test fixtures; exclude generated artifacts and third-party projects. Before declaring a project without incoming references obsolete, check host entries, MSBuild tool calls and generation configuration. -- Use two-space indentation and LF in `.csproj`, `.props` and `.targets`, with one blank line between top-level responsibility blocks. Do not mix tabs and spaces. -- Keep simple declarations on one line. Put long attribute lists after the element name, one attribute per line. Do not split attribute values in ways that change paths, conditions or commands. -- Use `/` in relative ProjectReference paths. Group implementation dependencies separately from public-signature dependencies according to project rules. Do not mechanically merge groups with different conditions, visibility or responsibilities. -- Remove empty PropertyGroup/ItemGroup elements with no attributes, content or comments. Merge adjacent reference groups only when conditions and visibility match and no intervening evaluation step exists. -- MSBuild evaluates in order. Formatting-only cleanup verifies property values, conditions, metadata, Imports, Targets and effective project-reference order. General XML sorting is not safe project reorganization. -- Preserve actual platform conditions and SDK/toolchain constraints. Formatting platform projects must not move those concerns into neutral business layers. - - - - -## Splitting responsibilities and changing boundaries - -Large owners may use partial files for independently understandable responsibilities, while fields, construction and the single lifecycle remain in the primary file. Move members and verify syntax tokens/order first; change behavior/performance separately. Public DTO filenames match their primary type, and closely related enums remain in the owning protocol. Do not create parallel event, identity or Undo managers merely to shorten files. - -Public-contract changes update every consumer, reference visibility, script manifest, Stable ID, documentation, success/failure/boundary test and architecture gate. Record ownership, cancellation, thread affinity and final release for read streams, background tasks, snapshots, scratch, native callbacks and device resources. Performance conclusions require measurements; unmeasured values remain unknown. - diff --git a/.agents/rulebook/coverage.json b/.agents/rulebook/coverage.json deleted file mode 100644 index 40f1aec7c..000000000 --- a/.agents/rulebook/coverage.json +++ /dev/null @@ -1,7807 +0,0 @@ -{ - "baseline": "7f56dd64bd29231351f5441c18877b0c3ad3229b", - "rootBudgetBytes": 8192, - "taskBudgetBytes": 16384, - "rules": [ - { - "id": "1.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "0438048c6c19d09a17302f8833d072eee0bc1dbbea42ef63792c8e182acdd9b6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "619bdc60de5e116996897c86ebd06284331a38e36dec8f1362e53616f9ad7fef" - }, - { - "id": "1.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "7548a57f38c92debf7c5fbb29b5f477132cd9dc587bb166ecafd996d2529e745", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "2acbd5f71f6e0b3a57bc47e5611f6422106ff61340977f67f89962f3a49b77a3" - }, - { - "id": "1.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "4c955118aec3a46bfc2136417987f168069fe06a1991534daeea48f6e032490b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "99e629ab7c8595b0bb3bffb29440446cbd1b4e3a4f272d58b784a1eb0855581a" - }, - { - "id": "2.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "23ed7825005c55de7bab25a13ad15e4d6f9003fa963e9dc6c8f83f25aa156aba", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "ec60fa8773db69f2d94c5e28c5901b9ce970d29f6002af8e2da7079b5b4b0b56" - }, - { - "id": "2.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "7146fd46302f8cb642df8c5543f331a66155d896ac1e73a902b4225731cefb22", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b" - }, - { - "id": "2.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "1254fc0af71afb409b4898cd71bc434108cda6aff826f68e79fed35a059b7a43", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "a68bfd544c316dd8bd4140f7eaa5a16ce35adb1d0d0afcc885249f509ede18b4" - }, - { - "id": "2.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "c7d1597e6822b378b28cff3f9a6360068544ad29df7f7118e736d012ffb58230", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "e65985a0124327bb5ac46f97c457fd9c8b6678a6df1abf6ed312f65deeaf708e" - }, - { - "id": "2.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "de1e8fc2ce15a3e73e3f8a940abf54b6279a7d557154acb8298b5e688b8d82b0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "c1fb02fbe518037ebdb862c96b2a42034e86f230c99fea894caee80f23f2290f" - }, - { - "id": "2.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "00238457aa080323c071fbab13a30fba20d564883baf55386c4e2b878f67da94", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "7eb5975ceb7bb9091a8d1b602e78a93e5bd4e2406777c26d8596810568640a99" - }, - { - "id": "2.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "4dd1a89dc1b7a7b4354e70948fc01c4ae5993733201c0ff5bf7f4713a5abefcd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351" - }, - { - "id": "2.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "779100086672741a3bd94e2b881aa35d8217edd739afdd017731e3983cff3a3f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "aa807bb8015d7800fe77d0bada936898d50c066e8adb761d41f493812f0c4453" - }, - { - "id": "3.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "155b573531fa878aa6c0186be8cb195d0df3cdcfeb74ae9ef7426d4de92344b9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "fe50f60ab778c20cc0d21a6ad0822b8d1d74fb9878eca124ed11172b8171c8ee" - }, - { - "id": "3.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "42c62c7d7814e5d5233bdf69c66252172ddb30d91cadd2d789f390959fac14ed", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "84739f16c81513c858158016ff5eb127eb0a32313a8f8e08611418c8062fa91c" - }, - { - "id": "3.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "6a0621716390e0c953ed9eed37545093931c0c1eaf280210e4c8312a6981ac9e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "26bf77b12ee406168444733e6cda0634672562df93b7fe79929b10b2572f16b4" - }, - { - "id": "4.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b41c9ac4a02994caca07eae9f9f88b1a04a54588576dc83b210317d72f54f76f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "61d23811216ed1dce965f002ac5cc7b1d8b9548eb5a048459f4c103a7d9f6e4e" - }, - { - "id": "4.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "c99a1440e54ed1f02f47977ef854a48b8e3ba1ad66f80b02acea7285a1ac5bc3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "4b9c7f47bf61bc389e0925ac64026e38a90b588f4e47155d88dea7256d216eaf" - }, - { - "id": "4.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "da4c375502ff67444749d190568441619c09ceecf1a2cb8afffb691b326f9bca", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "31b9db7d408e5d0fcd307fd1b9574f67716e904f53a9ca7f51475058312b360a" - }, - { - "id": "5.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "6b3170a223fbeeaa9708f03854dd47d7601bcc74996a78b9d7ec626f11fbc9d1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "beac146b517f48ed476a18e9aa7f2fdab6820f3b4fe0541a84f7260f58c8c9d7" - }, - { - "id": "5.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "53a79b0ffff61e3c64fadd0822b5eaf64d9d86c64f03abc4f10662923ebec648", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "2d5ddf314df4b45cfc643bbb67ee8f27f0d473a331e3430a7c21efe94762a9bf" - }, - { - "id": "5.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "230cd76be9c06b7b0154b24b64777add074d6436884be6cba68c8ebd6ebd887c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "88c9235f5140174c3ba6859d2daea92448b59fd05a49db081cf9cbda38dd7a90" - }, - { - "id": "5.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "0771e910c76a4d4fe8240049d51a9777a9ca6d429b972d2b7f37c3915cfa24f6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "ead7747e86c87d719e3f7d10f04baf07c58081893fc8eef642e3667041e763e1" - }, - { - "id": "5.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "59a8922dc82b328b1745c0f3b91fc0db931b0eb3fd0e3c26fdf6b18bd3f38ced", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "7a58317c4532181f9281b4245b89cf89416e5c7f789ba0d4a89909ba300d0c4b" - }, - { - "id": "6.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "0980b1aadfe2ac68f2408411a4c8faa47d4827bfcab4626fa364d341f1c740fa", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "b00524a3be4313da355adf562e233fc3f040313649c6608e091bae13d0eaf4e2" - }, - { - "id": "6.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "76b50f93158d312ca2fdf09d100930fdac90a842695d5d71982bc1e62d47187c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "397927257f1a6166ae6e517a14b27d64adeaf1f1114445342e8eece6f6e4f56b" - }, - { - "id": "6.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "4976e70e627ac2a6a257fa2480583a521c47ebccadf5a58e480b1da5512e369a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "454b07214dc2ad21ecf0626da999dc93ac75863293ff9267ba6186a0c05aba58" - }, - { - "id": "7.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "5b08d747721d1fff4043b5b4cdcc9ff5a2012f5b2dc38d6cc15d1005115c3458", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "2713b77ce0dc27d740dee0e57723fa3d23d3d680decd110a02a647f3cc645fc7" - }, - { - "id": "7.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "4ade080ca04bd3a8af8c5cc2a079c0d7c576063df419672c0beec9f8e88c58eb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "d420312b557f9c342f653da36246a2d21c4e3207e3da9a3a40b6a3fc64e40659" - }, - { - "id": "7.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "714ca4b88d20ad2f599c3e8c7287cb819db79eeaef3377ce67c9590515568ca8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "2804cc91a2b24bc15e9da3dd4221dcb713b9ff097b7122029bebd75b0825201c" - }, - { - "id": "8.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-8", - "path": ".agents/rulebook/validation.md", - "originalHash": "4d36e33d8774770bda3087a17e046899067d6245b693c62d5c23b8d497390701", - "disposition": "superseded-by-approved-plan", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "tests" - }, - { - "id": "8.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-8", - "path": ".agents/rulebook/validation.md", - "originalHash": "ee26061ccd340d9dcb274ba8facee84e6cbf1fae4cdd67df149028fe8e6ba697", - "disposition": "superseded-by-approved-plan", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "tests" - }, - { - "id": "9.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-9", - "path": ".agents/rulebook/validation.md", - "originalHash": "a743bcef487abea16b872c402957ae77f7060eb95df7e2a912abd615215f0cef", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "compilation", - "translatedHash": "a204c03670687042691bbfb56ba3981bc162bc516a14e05a589db9328b1873e5" - }, - { - "id": "9.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-9", - "path": ".agents/rulebook/validation.md", - "originalHash": "191eedc7864cd1a54ce09fdaec1018a177b1364934c04d1d7b6ea850f6d3e6ad", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "compilation", - "translatedHash": "19960351775059c13c3bf2ccb3ce451bba20e8cc0c16fd74b00724eec00db7b2" - }, - { - "id": "10.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "5f0ecb345e2161c7505f72636b3869f4b2f5d36c854a4cdf080a365154dced3b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "93b916cb653dafbe1ac6b1541318c6d2a99b4ded5430651fb234f09c1180d095" - }, - { - "id": "10.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "cf4346c90282c6ab53c2e461e575b9d72eb07351721701f75db9577cf9736121", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "d885e29cfc85d40947d57fd971a252a8188390c7c2c1c0a3882343cc277292d6" - }, - { - "id": "10.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "68be7e5cbe335410234b361ddc9a1d2a470d52a2efeec1cc51df20b1104df9fb", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "a58db9c776f2a269ddc19ae2b0dca051b7decf63ddec38627a5e85c24084dc6f" - }, - { - "id": "10.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "baf67bc8327069fca81f39fdd43a48c48942ad117e14c21a07d5d3ac3a2cf785", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "b8797541d6389bd1e41e1ce9fe2ebdd00c5a5de4f3f052d127e1deeb1bb6bc4e" - }, - { - "id": "10.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "826058d66069113fdd2ddf34145f9a3cfcd007cbf94058820e4b16c739492a7e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "860205ee7cc7104f0b7870e716ce87c6a55794010451e58d244618cb4e1fe81f" - }, - { - "id": "10.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "994b998db615f982f3bec7be1d89e09f1c23f503c0919cc3d6e206713b2bd91e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc" - }, - { - "id": "10.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "aa4a2e04b024bba81ec11150d13eac13d2e640c7e908177c8e7a9d3a6221572e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "c850a0f9751d00ab4c72006c8412ca36f84e9eb97cd16a42fbf7f99db8b6988c" - }, - { - "id": "10.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "3725c7f1220801b602870d097eb30b8101fe29c3d0f0dbcc25b9706b3d7b9ffd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "d284c4be4bd867dacb5232fe688e3d342ce37b8b27ae0538532b06e56c76bf60" - }, - { - "id": "10.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "22e3056d5cffccb699ab9f877c922098768541bf4f1f38f09d241ab128799ef9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "75206b141137df2f81699e6643bc8e496c70b9d89b394e01bb93017a3caa0538" - }, - { - "id": "10.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b44cca91ac82e75c8eebc27fb13765fd4b7e7a77a7a8df68c6aae6f9b4d66e05", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b" - }, - { - "id": "10.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "163b6b3e30a395ad2deb4ac88fa58052e5b17073729b41c31e1b56f91a2606a3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "f1e2390738b878c94984a774ba27f7ce1dfe9304624b4f14238b10ee17ad9d29" - }, - { - "id": "11.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "96ccf044ebe34361538ac4c3dac0fd3d2b7c9db5ad532b3e7837d04945d57363", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "9c171f3383ff9da15e8face978be93b8e1da13d5696517f201fd2e639cab8733", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "1dc0296ec2118708e1a75334f08d993e5b18f50ac371cd911d5862dfed847932", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "cc08880907c077e40ef8bdc501254fbbe9022842760fac1e7e32a52c0ca6f3af", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "f3f7debbcd9b552b379d4bfeea8312c3c6d9a4c55564db4ba8005f7a6e461d16", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "f69c49e7f0c709879f599f30063db2086b783e60971508865aff02748a194ae0", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "2568dc23c50d9799f22535715a1d496259248c52318d5280129d71d928a350af", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "a77e7aac30183eb14f83cc9c085ab9821dec19ae63f8bd6eafffaa48aaaa758b", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "5534ff06531b8f0e4dcede3a7409924a894a57e11848043c894a891cc226419e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "f85f2d2ad085f23b258020732abb8034becd84c5964ae41c00d977df176afe47", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "d84e481c7e94dccb3d7646f58403de71f291ddf796eb607f6762b5a8cd1d077a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "8495ee4427e26bb8a6ee37d6de19f92de7513ef9419398bcb4cf6e86a8a61b5e", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "8905a7d3ff5e3dc12c838f074a7eed0664d76a6695e44ff5a1f99d4f6b60f4a8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "5ae53f3449101c75753f1d4f1a259267adf4ce383492782fcd10de7c815f3de6", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "0e1d603608acd5aa204278ec1a5b69fc0e271ede6c8edb77edf667a1b3868b9b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "2cc05fd8785c66d75571462f5888b9990c8720bf6f6a402708e0b83cb784f6dc", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "06dbaecfd67f1807ce241fa928a76e1b9da9fc66c5e19457f8ee84e843d95c44", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "3d9951ef1257c276f5d3a96b0e7c482bc8986fe597fdd2e990c73d1cf1e36282", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "f91ef9d6d4abc6129c4ed63429a5786c8f63324d43544bc62422f4d51bd17cd9", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "58fad6bddd9ff0a3400450ce71641e40827a76bbdb53c19e0e035ebd21926bb9", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "12.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "5d9f37c482d7ed2d1831728bfe868cdf0ef116cf3dfda5a68ac0be5491c6b44d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "dad28a5daedf52b61db2aed9d3ee23a1195f76b283bed2b140c76fa8048f7aea" - }, - { - "id": "12.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "5c9522580d5b894b7597f4f96ac9128b92e6635bc21fdf7fef209f33a09f14ac", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "d973ef9f713818aae14881414686d10cbcdd0dd9db99b0daa45e5311cebda0e1" - }, - { - "id": "12.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "500bf61050900845ef55695ad3920e9d6904499db3ac32b4ee13cd9a227c05c3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "79c5afbb8bd7d50ad8ea5fa3561c5320206c852540c066b10d1fb0c351a8babc" - }, - { - "id": "12.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "e7c01c6e4c8764cf658d961174e881c4c70cf317597643d35d9cd070e60d0633", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "dde5503206d60a43d01f0e7e4f22a8d95446f67d34511ead3712b206d1a3f2c4" - }, - { - "id": "12.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "94120d8bac9df2ed991b33100188f9a5785ac28cbd4ebc93c9649c31f8f4e937", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "d529ef789e2aaa8e38f60f4ac198a46e4facdf0bdabd1ed9562e558aa9df4ffe" - }, - { - "id": "12.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "7ed60e2fe34199e32bf4156299913bd1058fde36733c1eed362fc55a1adeb8f9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "31b99354bfac665554a4395877403af5c4688d106fa52c7d6085d3b4d6549dbc" - }, - { - "id": "12.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "9d8ee25f4a083113ca0e53db9a1482d7a74aef76bd1b87fb9841bea819143dd1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "cf7311aa118331bb6e7cc9e1f371bf80521521a657088acd450f70c31d5c0c68" - }, - { - "id": "13.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "9443cafc9093dae4fd32a2c037d02de87486add1e4cc1b52377cd1f94a125619", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "b5559064539f4b6b66250bfdf2e6d88dc318169e195c3b687e0735829633031b" - }, - { - "id": "13.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "4f5e5aed6897ace5c4b6cbfdb87904d6a6a8929cd0df981f479cee26ffd96743", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "39faedb7db5aab968faf5d85d5e00e3ce311a714928a0c0e187c7219ffed2d10" - }, - { - "id": "13.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "84cc6095ce04a31a8beeb1661912a58b8de562db0624475248f755b77a0e20e9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "dd03d5a1ab0cc5f3b2c34f8f04f1763797fd42d79621c86ffef90dfceafc926b" - }, - { - "id": "13.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5fe6ec264db83e6748ca0ae5daa13968f80aac8d6d005ee4e2ded8e32199491d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "32d84d8fac657689afe63348ff0f5e41562769c11bd91a1d17e2beaf27850d97" - }, - { - "id": "13.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "bb394f03ce7c3962d38eb892f3240eeca07f7582563dfaaa56a128c5f9956757", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "fa2bf21fbe0202b247506afd72d2cafb390661d703060b1b1e56c2afb4dfc095" - }, - { - "id": "13.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "f03c8af813a56eea5cf54f57b7a6cbe268261de47a5d1c06c63facc942081797", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "96288472fe332b65829a9c6502eede3ddfdf9708aded8e000a855062d2261bcc" - }, - { - "id": "13.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ea83c11a5783a0e4674ddbf18b0bd8d13ae741d859ba8d18ad3ac2d57309dead", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "3f91286809466021084655a592bad37b159faca5722312122300f29dfed86e38" - }, - { - "id": "14.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "802beca59c3c5542e350400d5553b4376e4fd603b93289346cddac56db95287f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f1564be509a447142575c7444c71599d53f5e20b9a4c805c358575d5d13bcc78" - }, - { - "id": "14.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ab15e73721074f5f58250e7e325e01403f065f8bf3ef26057fd9d4c287a2871f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "790f7c69224b7ea64c5a0a1373b7a14b082c74ae3549aae36a6c28604ded12a8" - }, - { - "id": "14.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "4ab9e48bd4ad307a8eaf797efe07f0383ca83d3cf7a28f5f5c976ffcc21b71ec", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "5d944a27c3f73de2bd90576fdb16ec02ec43f96f87f011b13b9e4be7fcb33077" - }, - { - "id": "14.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "f439cf9fc6e91c8205613454bef02d000df1f466bce557863dcdb89daa5467ea", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "db8e4b6285cbc3f2db01c93c779205af7e79d0d183558548ddfa6b23eff5cc43" - }, - { - "id": "14.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5e625d5ffdba8dc2fa694a43c0e2d06993f973f21f2582fa12e3613ea1f4bd6f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "25300dddd17b788ff48a0592f39143241cfad86a73aa8d589947f59dc8630714" - }, - { - "id": "14.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "8f1386ba061db6235bb1f467ac5ff571974533e5ce32362da4692176d8f1d544", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "65fb119594d3e326fc2bb92d94600560f43a866c2118677e28721cf475b735ff" - }, - { - "id": "14.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "c886a65a41f603a5bea7387efe60e2af979dbdd589945ec485b82c5473f3d972", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "481ee912c2eb7d1469ccfa29593223c284a5cfee137eeed7e0e00ae3db19c177" - }, - { - "id": "14.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "11a421a9a00cf21080803c70bc4740cc226479a4c9adb1f5592e82eebd5e8550", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "cae6ec6b47f8f1ce871a5663c92db9336433bb4b8b91b33c12be418d81e42a83" - }, - { - "id": "14.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "80fd966faab70b6d56473c56b0bbffeaca4831ee75830e7195a4a7f8fc46262b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "1c9714e407adcaa31fb97d2a9f3cac2df6f9bfa0e90fdf14d43bd4a7b08da6f5" - }, - { - "id": "14.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "6d61fb5dcecd2a282ec55c91f551fbf012adce132bdae2589a134bfeadd3d70d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "a47795754591c1f7d048d40fe777c5ea13139d09d90f5ed5975b87947c1ececd" - }, - { - "id": "14.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "1e309e4880134bdf98872c3601eb16261a30b08ce818ce2919acb47877ffd8ed", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "45b8afb771f26069f27b34ba44bdbd20205c2326d0b51f2e7726138dbe758a8a" - }, - { - "id": "14.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "89047a47e41186f278ab244de7f51ef84f5a4fc8e33999fa99e84eda365a4b1c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "6788b28fc30cfdf61c3bfcc1908275d0fefb87d4d7dfc090048307bf5a0eada3" - }, - { - "id": "14.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ced6359a37b15683302c590a140cf9f9c5b8ce14a4583b80ab64082e9a164735", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "9da5caecada51f64b5e3aee43cbca9a0211a16a9d8d53ba8579e7d66d8e7635e" - }, - { - "id": "14.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "aa037a2eb62bc515463abef944986e311e5889fa1ee4bc031884fb591c405d61", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f0e84b1b52daa6d016be5554dc787ce3d317b8a661ab91fc2fed8c3507dc1ece" - }, - { - "id": "14.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "38878299c8a97469089022a237b2896e3699d76cff0af54d8c2a21e8a68f453c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "8084285b098674b7da1c0d669a65e729be5d82a42ef0ae513f99e065b5a02a04" - }, - { - "id": "14.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "d17b7484e2d5247bc6ed1dc891fa65149977f5d341c2079801f746c646c97843", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "79e84e819e757a783d8c88259ec68709db4c48ed616162650ff5d9f9b2b8c9ae" - }, - { - "id": "14.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "b8459066a743985e3556a91a0e8e30de69fbc32d33d2de7aa13e127e635f14ad", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f25581ebde68849f22ca41e7f5740243e79236682060ba13ecd38681383d33d5" - }, - { - "id": "15.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "ca3db635c67a5e06af1fc552d2d14673df5219117c438670b2bb80261308e997", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "5598f61c60c7e528aa02dddc381a65b16b9c29b41dd113d1e7a205ed1c3cd834" - }, - { - "id": "15.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "cd95d65721a19bed59819a9dfb3218039fbf58ce5532b9516c3db44984c7d452", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "308cdac10ffa559063cfb6e676b0aafdd0aa0827d8f0daab0a80ed7c832f9ee5" - }, - { - "id": "15.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "e42ad938b23b8d9430521e0e67abcefb208494d08e4c19a53d5a45acd4e0d76b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "79de0f9bd4ab824161b9dce0d0a277e5424cbeababd377095c2eb9d60e0fcd70" - }, - { - "id": "15.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "2b8f8939ec19c4de68cd0c8460a2366d20cdd71d6049839e54eb77572fd9cb28", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "2b64330331a1ee8039cbf370adf831b23896ac47b39d1ac2c7d4517f146d36b8" - }, - { - "id": "15.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "2126318b976262755e90da066ca6efa95c95318fbafd150e1eff03f6b1d8578c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "c7468bc8577b9e9f5bdb1c9b7d59dbe4b1acdea283c247666e84d11e0d5b5c02" - }, - { - "id": "15.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "5586fdaa422ec00e446f3499402e7672a9cd07466802b5c0d8e9cf8b2e2665cc", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "c77319428a2d92e4f9b97d80f76706cb83559b267cf2b10d12a8530e19fa264c" - }, - { - "id": "16.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-16", - "path": ".agents/rulebook/delivery.md", - "originalHash": "1df3e0e0a5f191314228a4d5be1242bd096be2fa118a256e29d168b2a59bd9f1", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "notification", - "translatedHash": "ef7e4415eaa30f14c183aa9ce389d8c2205d0001ba92c481a2655185b09fa200" - }, - { - "id": "16.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-16", - "path": ".agents/rulebook/delivery.md", - "originalHash": "8b74dc6c1bcb5502e35ce4ba58d7ca4be4828fb387862bb479937ba101029a76", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "notification", - "translatedHash": "13791b5add506d7d6991f492648a2a86e0ebfebb703646ce47857557dbc3eea9" - }, - { - "id": "17.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "ee5e8af526141af2cb7ee6ab91b439e48d714da2c1f8e832da7553ef22c503a6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "c4b79e930d63306c74e4971ee30aebe894d8a63c1e1c8c63a548637e1ce2e098" - }, - { - "id": "17.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "656c7f1ead45a3c2d3163ae94c6f0c49657a07676f798b0615deb70769a5103e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "6884e80117b1b268d6ccc90625c90b76fc1f7cef3d809241e60103628fdfedf3" - }, - { - "id": "17.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "1ea202115e8e050c1713a7233da99ad2bc40b4dd94cb29d5cbf5e7061bdec892", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "41a700e5ca6457dfb3b993750452ad8f61e764fe78b965cb510408f3ffdda786" - }, - { - "id": "17.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "db8d1cd54f08743dd4298fd3d5411a31e8444aadbb26a42dcd8b3f5b27a8fd63", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "916437cbafc25fe06d0bdee7041d760172ae5fffbe54dadb1c5ba54c8d54c3f5" - }, - { - "id": "17.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "71eadeb9ec2aa3ec64d0f246f13251317f05bb6bbcc44f1aeab3f5433d01d2ac", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "ae883035d12008e913974ca35a0867231c2088c1a8ae62901566f021cc18ccdb" - }, - { - "id": "17.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "f899f36c3b77d92fcc886d9b7d293b9881feeca684e86924773830af0b4b372f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "303882022ebcf8c451e2066059ec9db1d0750ae31690e8e0d4be4eebf569e768" - }, - { - "id": "17.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "6cbbcfde884e75e96c1efa01bc4eba9521b988dd0539a50971e71a34c7a6717a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "8f1bcb3b34247ece9e813fb2629cf73ca156a91a65b48d8d01d0bf42754d0440" - }, - { - "id": "17.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "7ede213dd1659d4ad6f51ee6eb413609ada0db844ff03f38311bef69b2e77cb1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "f55f5fbf29d1d956319ce9c0290eb74dc8066464aaeb19aa047d0af2ad95bac3" - }, - { - "id": "17.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "0e9ff540e001733230ba91a68544e1305ee617702ac64afa50608e05971e14db", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "5b4a800ce70b35064669ae0b2cc88c49d8a2a282717b0e150359a383f9da6b3e" - }, - { - "id": "18.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "e1ea473d5024366f6c1b634551d461d2271cc9699cf1c765b2be393c8e947494", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "49bc313818af030b0fb0001db9b11ac40d82d4d250cb2f240f66a19e8d58f4c7" - }, - { - "id": "18.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "010d03f20e88a10ca3465d22b36ea51f9495938372834fb019c236ce8bb9a67b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "cd74fc9db1ac9ad8552ddc1026da2e047d767fbae0750b4229c026d14a8ffebc" - }, - { - "id": "18.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "0a74219bb93287684baac21ff83548cae7bcb14e0e7fd53284e1763a11b6e548", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "33ca94517dcd97e912d8078690047eda94c1769221a3516a076975e2091de14d" - }, - { - "id": "18.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "af5f687faf8913e068718e3a73cba0003d520121aeeb249479f62505f3aaf3a6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "4fabe28f2f6f87bed92709444d8db01eeeb6eb9fe3e1eb1104b6411c0bc46d94" - }, - { - "id": "18.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "c46d6878522f11987318a6a509d56e72b4f6681e98af45cff3623657630d9959", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "a4e8d4fe297362f0912a6310926344416859262af97417f26fef4c422161f6e1" - }, - { - "id": "18.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "ad39665d09837ad8d1e4f78c284b97d4277c68a2d44ae4442a1185d9b8a3b896", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "be4aa6279247bea1bc60e5e3ea8b0d38a9cfbbc1e5c3b9fcb841fa604d787564" - }, - { - "id": "18.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "f4ab19400c0702d8da6092df70ecdb4c75293f97205663411aa847c3c325963c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "264796708436b8d5574b48bfe1033bc1fe45698ca89141352d21041b53261234" - }, - { - "id": "18.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "6397690af4b51494ac9f83bde6b137aca3326fdd6aa74bab0dc42d93490a2d21", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "3a363df664fe8edde37d6e6d62ffe0566dc1fe90376c61aa869a2bbcc410b6bf" - }, - { - "id": "19.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "b8e41433b5af0edc8f9e61054e6ac81c6aa2cacd0d90bbdbab1fb3b889c54bbd", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "50c049e7626af91e85a48625b352767356976794cd70460159a9f031323708ec" - }, - { - "id": "19.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "73e27ca28caa6f4e6c6f7cd1fe54ca2dc8e49e2ba15490ce7c5b1068354f8c71", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "cbbe4d856b6f17019688e721d7ce90667d36df2a59ccae9ff90325f50d4cab04" - }, - { - "id": "19.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "cde43bdde3090f6b7947886e50001b552d09d461f5ff40a0914968e988446ca2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "9a46ff44b37d46c5a25c290b7730653dce6d57495aa98b26f22c1a3adb89f498" - }, - { - "id": "19.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "49c25780621007dcc71be5f2e2b4f4b002de2b0a9d96c40e81d193604c75f2ab", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "8d7d2cb58e7e0d01d42d1a49fbdb9c521b8fcfc7a503400100a292cd4be941c3" - }, - { - "id": "19.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "c9950b8ac4190e36f1941ec0d592853ba28171f1c75724002906cf5eb1bb4b4d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "3325bd1c35ba13ea900f2a1d311afdfb36ccf2c97187043c7151b25336d5d56f" - }, - { - "id": "19.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "24a6745290c0969a46d0461042c788fabc2e4d0d0b69b3d355aebe16f7de0e92", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "ff823b2f21dc4d5d21e106aaffbf5c5651ae2d918e50e4280055927da58a197c" - }, - { - "id": "19.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "38808df39142443fd505e2cadbcb49dadb6cbc8e876d68b23fdf516472173de4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "3628b29e12c796edde653461ce6b6c68ea22d00eaefefcee55cdd72e00887879" - }, - { - "id": "20.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "d04589d0ce99484f813001832e92a2f8411d2d1a4bc64aaff8175fa1e1475e0b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "96e1a4c1f7b1276a60dded704ccb43f726c58f86c99b06fb62c81a191ec78d1f" - }, - { - "id": "20.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "975f6da00e76191fdb166d04c732a9d0acc77828f65b1d270c6aa94bd0b0d07a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "99cd52450ef209e62d9b1df287979ed26fd21732f487649198a6d2e68cf53902" - }, - { - "id": "20.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "5c2f32dc18a4142ae2b41e7f0191688430deb3942f8d653c058ca5fb09ae9380", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "ce9dd22d95b882852ac19d5bdc44feb0d4b1a7b622ff2ee54226edb48d07135e" - }, - { - "id": "20.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "811e0a9fda7f7c75556ae181360e3af2a2c4a57ddf60a74bab1d17eabed0b896", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "43793c651d33494c2fca6270495afddf406398e15f21897b5e5d0c78b92c20e4" - }, - { - "id": "20.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "92829893c198c28c5c8f6d5fb3542e80f592ee4c6b362826cc9965d23506bb79", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "82d65edcf81d1ebab2f7445cfa727c37a2fa6515c7e8401499ea049bb1fc0471" - }, - { - "id": "20.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "63e109baa64f062a988a244a78754cf21234b8d3478124c99a0f3a5b131a4f3d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "643d446e16b807fb946ce67a8e30bb8fa902dadda34e6209c76b922fe1724b38" - }, - { - "id": "20.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "da38afa634e638869a4aa17188dd56e7762b25c0d33026205f91a9df4fee53ee", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "7c4e21bb14ba0d418ef4bda4c9d861566f4440aec7dc9e80491f2cb49cae9cfe" - }, - { - "id": "20.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "54c7a14b2e0f3011f82089ee72b14d27f8963883d6ee166fcbc0e6deda1414d2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "4f660e19e473ed31e64beb070c3f3e2ed7c4954a7492677ec27b73e09942e56f" - }, - { - "id": "20.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "1b7d6605e20bbfa15843a42196d806ce2b1d06b97b9c7d678304cc474ed022c2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "0ede328f6a2f73b21505f069bdfa56c0a8aeb2f9e8ad69d91e25353f6b21e25d" - }, - { - "id": "20.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "9117cdcf7615cfaa27c12cdb1a27b762440a39595a279414c42e876acdc60e25", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "ca4b44218ee5981e939f63225dbac05eb2c2bee9092f5f1a107e566e209d9919" - }, - { - "id": "21.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "0ee4a1381219a58a864b2d34e63490bc76b41a6d3a91f162d10b545296301eb4", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "601a49a2801a6609c14b3059e972139dc73c4cab54e7fa4c3e551173232c74b8" - }, - { - "id": "21.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b8fcd9e15d3ebd1fe14864d7337caf534fe5be36043c761b9da98aaf817f10ff", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "4dd627fa435109d5532f0aec4b4e087503378c5a03ca4d8f80f15bb80429ba4c" - }, - { - "id": "21.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "3ae787b3f7492f78c4d175c1afeb3440f337470bc957514fd541e334ca7a6791", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "bd95a93492c285b77af96ddb96b379bac6adae61891528a4f9c58b13d03ed6c5" - }, - { - "id": "21.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "f0646b2f9c636d6649ae60527b2a3171e98f1667369d7bca95825102773f09f3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "5e83c73b6bb8440c2039d7b0961b946b8efb122076a9a319cb6299aae81fda5f" - }, - { - "id": "21.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "fc03e6bc382adbe5a20029ffbb9d84bf52481670141c960b6ee9daa7188efc37", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "fd5c6a6cde29106b250246e87a8cefac8b065e49e2324c313da280b1adcbc103" - }, - { - "id": "21.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "114ac52f6a6a08e00af88d925c557453cc899572151d6638fe5e6b485b98d7f1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "eeddbcb38d649a9925df85e272adfd61bb5d3224bd09379256550f2c5d670cbf" - }, - { - "id": "21.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "1f55a6c4e2413d61a0c260b94b1379c3ba5381dd3fddb553d5068f8784585b6d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "ce369b79a7e86ba1ec735801712b3209da7406c2eb97567c9b2da689ff960c09" - }, - { - "id": "21.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "10a2bfdf68c81051d2f8b0fbab24495a609c1771531462fbf9868e9bef0bc320", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "1282710a648b2c4ce6f358c0d742353f9d0411f2cb038224d986a2ef48115f44" - }, - { - "id": "21.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "bab9bd3ed3aa17a1a152fa893a422014284ab69be0c24b7aa6576647c333335b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "078b288e1bfce8f69a0336108fed302b9640b776b8264c532755cc10f562f2f2" - }, - { - "id": "22.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-22", - "path": ".agents/rulebook/architecture.md", - "originalHash": "6fa5cc593dbe1d5fe96ff5e177c49a6b4feecd18f9cec91e80e7dcbec482cef8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "core-reuse", - "translatedHash": "3a0267e4d2d341ec997e02e6c0ce7d2bab535e93cb4c478da1a6b8bf2f059d6c" - }, - { - "id": "22.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-22", - "path": ".agents/rulebook/architecture.md", - "originalHash": "43025970366c56e171047fa7cc31fb9ad071cd667dfba68297c36756f02e73cb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "core-reuse", - "translatedHash": "5f82bceb744a6fb021aea81059457bf115a54f4b388adb979bde1db0755d10f9" - }, - { - "id": "23.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "a7180c7b2a595dffc271bbf430dad6da72ac8dbabaa7a713ac746d3be7bdcbd9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "2e5009668d2b80970bc549bfd3b689fb956a9cbc8f6e46a17a8a993088ce1b4c" - }, - { - "id": "23.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "31891a8a828b1709293b0f1f3d81067b15c1e35e0a9e8b2f6ef6149a56f0c635", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "e46c450ce7289e844808b05542a5405de9c3cc5223da703962351a2e8977ed03" - }, - { - "id": "23.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "95e12ed427e31ee89b53ebdd3551f8b671bb56c5d8d85a7c141127c989abfcda", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "9259801cd440e5cc5b6b5cd2fed583eedacd34d58d7996ce25a85593eb4737f3" - }, - { - "id": "23.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "8338542136dae7aa818b9446f5050658f3e1e89402c0c97e9d4f5abcc8b7d0cd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "e1769de8f4cfb3964abe3c2337c13ebc543581c165c1db1b9602c1b1daed3002" - }, - { - "id": "23.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "41874671f58ef7bc6285d79b4539b0d61ea6e5787d16732d3e2493d84b043ba2", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0037d6a15be093a1b084de5f680f593450f1e932905c775bb4f8822fdb307be5" - }, - { - "id": "23.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "19ef285a86c7baaf07c63b9a8fc5cd74742cfdc2048821333f3cf14a22acb7c9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0d0d8f06fb572349230c1faca233dc503361e135e9adb9d3b429d3f973601201" - }, - { - "id": "23.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "e37bcae5aa76b76e6688c78103d6163a25fc73ed080c760964579585038c086c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "26d1fd9f48b300d262bf87e7122e38c49037aef35b791538082963a728ebab00" - }, - { - "id": "23.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "00ab8e1bf5ec15ca8c2df55c202cfcd4172b471b8fb6ee80cfa15a58bcbaf1bc", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0bac228dd3b888345ff647461b01c6ad677caf65942c708d325d28739e3058d0" - }, - { - "id": "24.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "a78da5ad23986a44349374372658a6557ee2d9976628b07e933721594fc468fb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "10244dc31c8640f6338ea9fda49ed04d9b88f275d78a5d1ac0d9921647a6fc24" - }, - { - "id": "24.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ff8188e23b8af5d3991c935b771b773a59598b7babf864d5b944150c0e013e27", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "a945b0383eb161ec90c28bcac8c42671649e0075ea4cfac4a64896aeaa1025e0" - }, - { - "id": "24.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "d2f1efe96013a971a0f435d8592204bebbe86ec48abb5f4bb537ad6b12f3e7d4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "9a17d7b49fd799e072b6a9bc74ac804bab28a0b409d5c94355753fc174b07947" - }, - { - "id": "24.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "3376fbba35db3b14186fad6856628170c46b5ea568ec4da85d68e13a360df83e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "2f686f33426418cf4f0f9eec5367effccd701e63d4c694cb7d6d15db75ced0da" - }, - { - "id": "24.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "102fc73957d8dcc7555e9f021d87b707da29f344e4b6715357256318c6944ead", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "8f0b47e959d0ede256c2c32cee6900ec3bf5e3d1a4b12238517767a4eff4a805" - }, - { - "id": "24.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "9aa7299366b57f5a1b1b5ca963563c742683e3fb6380dacb2af72d6e1d99fc1d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "7cfd8c31799dd63abed0ed504917ff8314fcb6d63f452138228af79921b580e7" - }, - { - "id": "24.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "a60a708374ddcfa25bb62fbd311ec7a8bb959a60e3d74fc03ccb28777eefae77", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "426d40ba0085d6926ea69ecd5ef43299ae49bc34da5f6f6b5e5ca9dcdca8e08c" - }, - { - "id": "25.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b19118c564bf7869a979959cb5942e88df5ab3a54f541061adb140aa316ba10c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "6f3541d92930adac22f939113bedc1be29b6dcd0b0256d342d4426a1cd3f31dc" - }, - { - "id": "25.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "c7c3e1e13e6ec6f3600f6355d31a4a8d755f43369274baf9acfbe21440e8a0d6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "48ac069968aebbff6d00744c92c6b5c1c47cd81503c31164b1e49962a34a6394" - }, - { - "id": "25.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "2ce9b85e57802b8c2a31c4cc3d0c8235b69068b7d46a7e5277978472f4de88d7", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "5ca44339f245dfdeecb8cb02b274bd3d830327330c73814987e11c93f2429800" - }, - { - "id": "25.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "8b73963b3c9f46a9705c77b3a0a00ab19c234e26eaffd223d6fc0b2e932f603a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "00aae0b2ecff9452b6ed1bddfb1dc00a6b0aa126dafb52b3b2b71fabf3b7a72b" - }, - { - "id": "25.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "df22738791386899274f61f777a931262733f8a48f1744208c042fea57880d80", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "4ae5ee3546730297ce1e27aeddf37b00703842a3fa13f3780e65e520c495016f" - }, - { - "id": "25.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b2d018fd842124e7109ad0973e6e907e908ea05c3d29d2ff0bbde4cc7abc8e4e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "5e19b875c132a28b4329330254028c2514adafa89b1721a0836adc7bb523bbcb" - }, - { - "id": "25.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "224ccdec3ed83d364b31ccbc614ca441b1dc8b66d1985e44e5c5d615342d7a67", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "bb30e559aad2e6a87f7859cfcb4defc3eecb0d2f2b8071011d4a10db773697e2" - }, - { - "id": "26.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "bb60b33ba54c7336e9799166c01b4052d126a112d4722915e3904b66fc4b5ab0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "0483b55fccc5f6d01514232acd1f02e3f183882b5577f3b00d9926260bd982a6" - }, - { - "id": "26.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "96c711350d8ff162324062dfb4b49240d44be6a667a5fd42a42bf590c3a5e3ef", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "795bb85622bc01870e1e65eccb18705c1218060ae36969d3b6b356499e658d40" - }, - { - "id": "26.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "fac2752dd3f41f02a5029638af0b428b76cd57c54b1e806d7075b11720f6e4d3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "8db8f6984ea6d97e8089f27c6d194ed044c67bdf33f61d890a137fdba29101fe" - }, - { - "id": "26.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "24eb6050ce21ea7ff4821e7c8829d4beeed5e4ffa67e27dbff16f278a535ae78", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "58bd97d696b2fb242b9115ed807e9f25c231ee908b2d99a46b3187d29e8747ee" - }, - { - "id": "26.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "73642ccb128fdfa44c92f79efe6cfa8da42c7c16b4fc99e21e64f6ddac3c47ef", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "ea5a66ec42e2b16e5433a1bb9ac555169660b9be567d296b7ad8fb6425c98c19" - }, - { - "id": "26.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "25a9c3360ddadcf3681147ed90c1d86a63205a903b3dddde86992c1866b32e79", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "7ddcc1494b4e535474a0bd52ebe4f29e8063b9a84fa51409a8618a561e7dea15" - }, - { - "id": "27.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "9cc6e95f7ea461fd696de07ce76f8797c96ed41f0433e310e1af26582805b22b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "a3c3d40432341948da3425111919483a71dd9a670453a779ce14988de2c86b27" - }, - { - "id": "27.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "7603640023e8356e822dbdca1f0bce8573039862e61d8e8926b0acd6611b9494", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "799b62a6394cc3d00628d0011a636ee7132d70faf3b87a2ad91dd2ebbb26fe6b" - }, - { - "id": "27.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "aa8f68717a46b2a24105079cfff00c2955062fc80da10d8005ef3611bd7d997d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "b275fdd63312c343487ef5900b754569044bdefa162e7984ff45a3ec6ac9d121" - }, - { - "id": "27.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "b95630e0b3deb0b2d09de1f2ce037457354b9e319ebd2f39c8106174275eb320", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "e6801a9f0117cbeb680dfcda3d3becfa769e2dfa867fa33426faea40f37d2ae8" - }, - { - "id": "27.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "8e6c8256ca3966575e246bf2c4986d105214afbb19a069bbf83c3e0b40de379d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "e3eb98850d4fc6b9d1f10314f59ff960d02fcc31805fb8c1806e4871da6a2cee" - }, - { - "id": "27.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "2c398b51c32d526e1b9337797dc9d7a06302c34f25f22fb2806075bca491c99a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "7abc730bed80f7182f50a2fa2d800ec1a7ff4c7f93c10603a7f9db78d1ecf0a7" - }, - { - "id": "27.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "1eda47cd0c85d1ffa678dd58baa94224f78967bdd53aeb22c46f5b551bb403f8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "5295573eccd283d7ebe32cbc6a81a9d7de00cc5c69053fd80c864f87ba200db1" - }, - { - "id": "27.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "ee7ed4698848793ab73e52bd3e73fd8c709f75028df195bbe876b70e0f648a28", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "1ebf3f605999863b058ea2e0842296ae13c048c5c2913da0e05fab43b2a207d3" - }, - { - "id": "28.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "bbd068ddf45b8a55440546f88432f08f1bc7a2b94ed6aca1d4f72c53a59c15f8", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1ccc62336920d8d206c660bb69253fc729a50009f5183994d8f51e997f81a733" - }, - { - "id": "28.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "38365fab9c07d85ea81c40cd0d181f0549b781dea9c48bdfeb0559a24a02c607", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "e07c444e54ad0706b8d60f18ea4251134de8da429be5becd82f620b34e9cf3c3" - }, - { - "id": "28.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1e3f7d9acc0b4f337cc02dc2fe79d66ccda45221c943c14cf71f91de709ad989", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "d4e895af3df576a50c336831087da0154a6a61c49435523ab21d1c38719aab82" - }, - { - "id": "28.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "e584940bd16fa8ff45182ea7674910860e3a03209a16703f1b06a98866620b01", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "f298d49d33a65277f5984042f0db3612a2ca869dade024d0d9f35414d598feb2" - }, - { - "id": "28.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a1d364c82b7a1c3cb16f56bd1aae66832cb7b15706a9a2c5206ba3fdaa79a886", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "cc05be97176ef293898bc6e19032c1d524212f4072c437cde90d72971f79b18a" - }, - { - "id": "28.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "875e20eacd91a77fba60d63920f357e4e7d1a3e3ae2c1f9f830da1fd8b8000a7", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "df72d5380faf70912ec865e14811a77f0fc2549269872aa8bd9b47989cbdeb9f" - }, - { - "id": "28.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "6af5d2f1a1c1f5083c4e8da9c181963e99d54ea38a9563da8747ea5fbcaab5e0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "6adab6f1f34ef19fdd6e7b53cebc19f7c644791c9b9c3ae1dd3832d18570fdfb" - }, - { - "id": "28.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "dbfa9fbd4fa122d1eb9ea53bd5d523239d856d17a436e8df8616730f411e6a95", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "6ec84e13d26475f76db8a7cb32da00e07c29c3c112810af53e982217410c0065" - }, - { - "id": "28.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "c02df2b6b87a837d2297dead8bd588d68b1e0b158f265aa2f720331fb975487a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "cc2c00b11df385e07035448fffcf8d681df96acd8382ec0e1558f5d61ed8f0f3" - }, - { - "id": "28.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "91e9b473ace4cf03421e9e288264dbc1c14ede8d85b92a96436ade4f1831095b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "e51ebcaf4adffa66818e1fd80078f4b77797905a7bc1b34cf6e2be8289b159e9" - }, - { - "id": "28.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a80250da185512ce2c8cd8d97ae37f7e29f823e844cfb499659b0e89502d3ae3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "4b3ba100cd3a0a89254d79cdd4d493856dfa800f804636a44ba8849cdd82d4ca" - }, - { - "id": "28.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "627102228e1d72789f8c8c31687375dbeedb3e7c275a879eeed503ceaf1203d6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "ba4580a371549e2c475316965ddc62910ef7c48a76d4ed19937b4ad6ff97d989" - }, - { - "id": "28.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "86fc3f18e3017b563ef8b55f15576986538a7e01dc9f61b869e698a24ee7cbfa", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1d6604b2c73f03940f77f447e9dd42a9bfec9ef056d70190985378c7ee76d2bf" - }, - { - "id": "28.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a5945bfa41a6b678b345609c3fb7753aa2aa3a183b9ebc7d11427caeaa0ab25c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "38ad850bf1f51ee335adcf4b28bac58eb15636a54d7d90b2d5ce1d04ba4e0ebe" - }, - { - "id": "28.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a4e99ab18a653cd24bc57f0d7df13d1dfb5778cdbf0a59aee49002ac93b77915", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "999168f0eebea40a7f0a0c41fdb26eea4b45a29e467ae42450117a3c18e769bc" - }, - { - "id": "28.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "0afee409eaa98d08d8e1a0334b61183523ae221b3f3b86f59d9607e0babec762", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "7e606e087f9376f10f2fb4cb2ab487372c83fb64d3f39fcce62806b806b80028" - }, - { - "id": "28.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "09969edea363049274eb103b0f3ed28431ee6c029070d88a2de8e287f5f0ceeb", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "8e56582f7971f183cf862b5dfa4b238440064196565221baad83cc0a096c76d5" - }, - { - "id": "28.18", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "066a20c7fa263bec6fb1bf35b123412cdc19b984fe121365b77d5eb4e8bd7fe2", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "770fb60453044c83021640675b4db0b4b0d66d24e76025e3bae9c3022b1fb3c2" - }, - { - "id": "28.19", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "f6b7f455387f2ffe8b272441fe9ccd7c6fb793a640332c7889ec4b963ceec35f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "a5d16ebffec8484bdd8e48ddf07eb6f9010296c0d3d03506894434e5ad90b20a" - }, - { - "id": "28.20", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "96a1de39674aff5c38eee8057c697e37d7b1a34051133b3471bb96ff56933c6c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "80284b4568ad4e28bf6d275ef21ccd35b92160cbad4d4832749532bd55caf1a1" - }, - { - "id": "28.21", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "2530d325d5dbe1448fda7a6e246d71380bddcb95a48162a33cf8950573e8b381", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "01c97c9490d373912aa39f72eb12078aefb786893fdf19d8d1f867575b37aea4" - }, - { - "id": "28.22", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "85f424ca1b9c5b3d21b925ef469a1a515c31f2ed651a82a92a208258f55e961a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1e1554ca14b8f1c1c792b2ecc51e5a22d04b4db18e731de88befcee8d23444bd" - }, - { - "id": "28.23", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1121c4faa7c7e120a90135449a220ec60b622d7831ad68c2c621d96fc0e7efcd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "dc1b482f4aab5734dd96ca96d2d3831385aae7c4886d7cd76388459e689bae4f" - }, - { - "id": "28.24", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b61c0f0e7f3be551ed431b43a76b62991a811b2b51bafee0af5ebdb39d320a59", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "f1bd1a5d08935b55441ccf2c4708d8841d92a9f5a6b80a5698e1a47d1519fb25" - }, - { - "id": "28.25", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1193087c674adcad2e28e80da089bca39d1bb083e175c00c46e3bfac2e21f07a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "7f8759274527c9b1b1ead5bf64427baf9aec1dcb42e3902fac73ab250ff7ff03" - }, - { - "id": "28.26", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "780f84046cc74eea6834fe6397421a5e76f32bc030c29b2d0a7e66ac18155bb1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "af63d3d2ab4dd248aea2c3f8eb82cec97a485bc066d80430c680c7c87c5da3f8" - }, - { - "id": "29.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1184ebc811c53110f9b93a156ddbfe721a06e84ff561b7b170de4b8a4f09c7d1", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "fe2f86b126dc556658b3d98510c367c9b0d0e1cdadbbde575b452615d2dd5b9f" - }, - { - "id": "29.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "24e7a817f0f579805afd40f5ed16f6c767153b6ebd44dacee9c627313443d019", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "8bc7f52cde6311fb50418b498c44debfbd02a9e5072a2002d3c4ce6f78133a06" - }, - { - "id": "29.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "930fcd222b949ce695b267388f8203bd798c04c174217146304ffc68ac90e511", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "ad3910305ee11b6cc3c301f641715d36d27bf349ea279be1690f4137dd73b6d7" - }, - { - "id": "29.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "464eade4d3d14b2b800c761c2c5e26c77a22a4351b5ceebcd1f112dd3cfdfc2a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "229dcf70819f94d7a8291b75d8cbfdb623e6c6e39b36db4f37726d8c1fb43f8f" - }, - { - "id": "29.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "47a490a8d8506b2fb25cf4e48407c8654b2cbc143c272e53e509ecaeb52dbbb5", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "452e40de8c98a748c939e30115ca9962a497cb38c20ebc931cbc691240e59ecd" - }, - { - "id": "29.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "77c7d40f8caca628be02ac2147345e04132df08185765da27e5d6e823ac61f1c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "88fe122ded5a5662f59de6cb274cf44aeea96fd79acea3c3d8ddb8160b0f9882" - }, - { - "id": "29.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "dca2a1bf003d9c82f5c57956cc315bd20cfe11d5c9c52caf2aa2c3c06a6ac852", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "49a91d8ef3552a254e865b8629a5e296fbbdd3f9808a30932cb3af1179682abc" - }, - { - "id": "29.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1ea3f833bf68f4009d0a8baf5b54744de3b51c97d38370e47e41a34bc31a0f96", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "94d8980e98c8bce72f4cc50106880b725f8a4dc62f9fefa0d08047bd816c451c" - }, - { - "id": "29.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "db9846f1d6d8462e20d840a76c3fd2271e2cb1c171ab6a3c3dab8373c31d5e6b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "6d5a1d919c9a6d1c0ab3d783e344175cabaf1b7696b2280051dee36b64204ec3" - }, - { - "id": "29.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "4417ce20429062015905ffbe98b19a0d31908960f6d5863c80c27fd2b7644ea3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "c932db0ddc349b2623393bc3be6ecee78b5b949dd6ffbe790994736f0caf7aa4" - }, - { - "id": "29.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "167343d8d3372823fd6a5c09a919f63b5bd1524b4cb1b6229f516f4eb6a7044f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "93cd250c40b90c2dac1407b7622fa51b291b959f2576e2a09d48fc04c2ae4a7b" - }, - { - "id": "29.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "d03b95720e5346978f818d1cee320f8eb0576eb915431635b925dd83b318f5bd", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "fa6f1d36700726347605104c6b97cce1e94833efd072d50b39f17d96687c380c" - }, - { - "id": "29.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "d8360e8265f5088a3def25af85805151c7aebd7a508d09cc919f19f5e24d666b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "c718e498d894d8502a6e4f66a5896eaa1683c6fcf81cb18d27e39a9007126bd3" - }, - { - "id": "30.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "3e0df150e5273f71eff27bbbc8671a331f09cb12a5c07a96c8e861a64bf28ae3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "d2de9e4e7dead46bed8bdd02cd62f88fd8a4dc7fd5919fe7c35246dd42a47c46" - }, - { - "id": "30.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "1d25bc7acfa0735c58e3814dca382bf3234a0e7d965325e173bd88a903c14af4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "718c54731d8094e34a332a646726fcabb768aff145338555d967fe2fe537e775" - }, - { - "id": "30.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "4c780ef5b65a99dad550c107a7c514591d3e2812ddff8d00cd308978579b15be", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "b5af8f7f7c5b556b5030eedeb74b12ba7c0b47abdb819ac3d06dcfc7bb4ff51a" - }, - { - "id": "30.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "009ca6574de647708b05c24de08073f8af6183a5c3b7fc0abbcf5fb23fe9ed39", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "e15d9eec2ecc8ba2bc85a5115eff36f54181b0a457f730082de4439fa5bbf59a" - }, - { - "id": "30.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "33c44f2b873bacb7822af7718aedd66c8967bd7cc3e1ac6f8a193caa4013a663", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "cc2046e1746a60a30a83b59a2278a35c7b918fbe41cf4de4fbd22232463c3344" - }, - { - "id": "30.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "e3dbaacfefac2daa3eef9aba4b6d0d9656b068941246544f122f5ac40e767e6d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "16c75b1f4fd6c9e3ad3b1188a4b78c09a27e30fad55ceb9e0c7dd25b94d55285" - }, - { - "id": "31.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "3b1ecfb344235b63cb4015fa1548529093f605c5673ae454bc1660106d7b3d3a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "b67c64583f6b8dfc7eb0706a3cdf820e5e138fce3dc57b6957775ace596f9df0" - }, - { - "id": "31.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "e5bc32830644660581c3286a3d352fcf4828b676c91c116afa23e08b48f00c85", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "68b629f0d9e3d314f21508e9a2e2267ddc9cf87d80f08c64b7fe80154fd67b25" - }, - { - "id": "31.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "5101467f70d294ab413e4befbd85c00c6717a855cf3fbee0aa1b24c48467f2c6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "2c0cb58de507485b88f08d2823a84dbdb3ae16fcaedba435b7ce4ac6843873f4" - }, - { - "id": "31.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "f67f47be3449ea304ec5c3279342840557c75efccf63bdcc783df37d2d974053", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8" - }, - { - "id": "31.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "de6a01673254e95d66beda0153ba848d3f808fb9e3164e41d4561dfe6d07aed2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "faacd093eb7499bf0665183a078ed48662b8b4e6e81a754b834705c231dc08c4" - }, - { - "id": "32.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "1df2bd9d01c7611d9916939771fdd2becb76f37d10cbfa4d1542ee2c8f938eca", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "22fd6af1bb890a7d27b23d959b8504b5db470e401d2b581c63ba038f4c957914", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "22e9cf2e6c3a92b4655ca67b49479f7a54525bf1d3f59e904c1fb91168a97175", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "c6f50e26701141e063be238e81bb9c0fbf0c60e1a49bc1925e71e59b51cbb97c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "87015c79749cfa3edcc9f013455858720122b3f2df306b9f507fd634e1fe53a5", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "cfa03efef9d5ec20da6ca65f90d6761a38e59891d567887476cc392e0b32b09d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "616d978818c8ea9234ef6765a405f2099a74021ea0a5b43f6b6e72c965516b22", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5e7b3322365eeb3a3a454a09842e63914b9c1ed22fb330012dbb026612372641", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "0ec49656b2d037e60ea3b07ae7d8ca86fa67f996e8395e7baf375163b28e47ed", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "e425b5e45991d571e96373a3315bf81929ff0b8984a0dcb5c1ade024fe38f965", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "74cbd2228ca2f4aa825d56f3716cad9b10b6def5eeeaf1b9923bd511f2986ffe", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "26c8b3a4f5b3d5912f20cf6fd304de30470a8a81618e5a441ed1e497762bba27", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ecbde133185bbf5cf11dcd67eef943701bd229a987d8201b48f769e1adc2bbec", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "0a616cb021da2aca735b276f89b6bc78090c19fdcbec1ec83cbef96e2bd7023b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "7306cf65c6b8dcd323bb97ad664f248e95f7da3934d6414041f959dd2649908b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "8f22deaf3629f8fccb357421384db74be421c8e9a05a672ebb22409ada07cf5f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "fbbbb0cd6acaf286fbde2fd4e51abe04c768ecf13ab67d53d313d47d1ba054ea", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.18", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ed3692df56697465796d1e95ae805068eabf4418cf8e9ec3ed5327607578d4a4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - } - ], - "units": [ - { - "id": "style", - "path": ".agents/rulebook/architecture.md", - "anchor": "style", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/style.md", - "sourceHash": "c92daaba3fab8ddd29a07e2f41f68108dabc168f285256d0c8dab2ae8bd61ea0", - "requires": [], - "paths": [], - "tags": [ - "style" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0e2214dc4aedf0d4b00f1e7a6d0729343611cb5ffc8ef8b8ad153ef8755e8826", - "targetHash": "a54583ae86207c636bb8c0e702652683096299c4b22f2b1a86ac3fd1f05c86a1" - }, - { - "ordinal": 2, - "sourceHash": "0438048c6c19d09a17302f8833d072eee0bc1dbbea42ef63792c8e182acdd9b6", - "targetHash": "619bdc60de5e116996897c86ebd06284331a38e36dec8f1362e53616f9ad7fef" - }, - { - "ordinal": 3, - "sourceHash": "7548a57f38c92debf7c5fbb29b5f477132cd9dc587bb166ecafd996d2529e745", - "targetHash": "2acbd5f71f6e0b3a57bc47e5611f6422106ff61340977f67f89962f3a49b77a3" - }, - { - "ordinal": 4, - "sourceHash": "4c955118aec3a46bfc2136417987f168069fe06a1991534daeea48f6e032490b", - "targetHash": "99e629ab7c8595b0bb3bffb29440446cbd1b4e3a4f272d58b784a1eb0855581a" - } - ] - } - }, - { - "id": "encapsulation", - "path": ".agents/rulebook/architecture.md", - "anchor": "encapsulation", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/encapsulation.md", - "sourceHash": "ad4eda770415dc6f4a543bd0724f31d6652f88baae3e7ed8d6c2cdce9b845e81", - "requires": [], - "paths": [], - "tags": [ - "encapsulation", - "new-boundary", - "public-api" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "21c4ee238927515fe775b303abdd8b7d2c087f71aebd8e2585058e42c09fca84", - "targetHash": "b1ff182ee1efb760ecd40ea10fa1df91ff9262cb2c609b9ce028f747a2ca3ad8" - }, - { - "ordinal": 2, - "sourceHash": "b41c9ac4a02994caca07eae9f9f88b1a04a54588576dc83b210317d72f54f76f", - "targetHash": "61d23811216ed1dce965f002ac5cc7b1d8b9548eb5a048459f4c103a7d9f6e4e" - }, - { - "ordinal": 3, - "sourceHash": "c99a1440e54ed1f02f47977ef854a48b8e3ba1ad66f80b02acea7285a1ac5bc3", - "targetHash": "4b9c7f47bf61bc389e0925ac64026e38a90b588f4e47155d88dea7256d216eaf" - }, - { - "ordinal": 4, - "sourceHash": "da4c375502ff67444749d190568441619c09ceecf1a2cb8afffb691b326f9bca", - "targetHash": "31b9db7d408e5d0fcd307fd1b9574f67716e904f53a9ca7f51475058312b360a" - } - ] - } - }, - { - "id": "directories", - "path": ".agents/rulebook/architecture.md", - "anchor": "directories", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/directories.md", - "sourceHash": "9190caf277e7690896e060164a74a6b92ca99e1714dc48dc95fb37fcfe6bf524", - "requires": [], - "paths": [], - "tags": [ - "directories", - "new-boundary" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "3384c9ea100daae62385d0fc5cedd92e11d5df4992b2360b1f6e87ff1f833efc", - "targetHash": "8c36723587c0454b397357de2571e3e2437f21947df7a74d9cb87a2a43bb5e4e" - }, - { - "ordinal": 2, - "sourceHash": "5f0ecb345e2161c7505f72636b3869f4b2f5d36c854a4cdf080a365154dced3b", - "targetHash": "93b916cb653dafbe1ac6b1541318c6d2a99b4ded5430651fb234f09c1180d095" - }, - { - "ordinal": 3, - "sourceHash": "cf4346c90282c6ab53c2e461e575b9d72eb07351721701f75db9577cf9736121", - "targetHash": "d885e29cfc85d40947d57fd971a252a8188390c7c2c1c0a3882343cc277292d6" - }, - { - "ordinal": 4, - "sourceHash": "68be7e5cbe335410234b361ddc9a1d2a470d52a2efeec1cc51df20b1104df9fb", - "targetHash": "a58db9c776f2a269ddc19ae2b0dca051b7decf63ddec38627a5e85c24084dc6f" - }, - { - "ordinal": 5, - "sourceHash": "baf67bc8327069fca81f39fdd43a48c48942ad117e14c21a07d5d3ac3a2cf785", - "targetHash": "b8797541d6389bd1e41e1ce9fe2ebdd00c5a5de4f3f052d127e1deeb1bb6bc4e" - }, - { - "ordinal": 6, - "sourceHash": "826058d66069113fdd2ddf34145f9a3cfcd007cbf94058820e4b16c739492a7e", - "targetHash": "860205ee7cc7104f0b7870e716ce87c6a55794010451e58d244618cb4e1fe81f" - }, - { - "ordinal": 7, - "sourceHash": "994b998db615f982f3bec7be1d89e09f1c23f503c0919cc3d6e206713b2bd91e", - "targetHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc" - }, - { - "ordinal": 8, - "sourceHash": "aa4a2e04b024bba81ec11150d13eac13d2e640c7e908177c8e7a9d3a6221572e", - "targetHash": "c850a0f9751d00ab4c72006c8412ca36f84e9eb97cd16a42fbf7f99db8b6988c" - }, - { - "ordinal": 9, - "sourceHash": "3725c7f1220801b602870d097eb30b8101fe29c3d0f0dbcc25b9706b3d7b9ffd", - "targetHash": "d284c4be4bd867dacb5232fe688e3d342ce37b8b27ae0538532b06e56c76bf60" - }, - { - "ordinal": 10, - "sourceHash": "22e3056d5cffccb699ab9f877c922098768541bf4f1f38f09d241ab128799ef9", - "targetHash": "75206b141137df2f81699e6643bc8e496c70b9d89b394e01bb93017a3caa0538" - }, - { - "ordinal": 11, - "sourceHash": "b44cca91ac82e75c8eebc27fb13765fd4b7e7a77a7a8df68c6aae6f9b4d66e05", - "targetHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b" - }, - { - "ordinal": 12, - "sourceHash": "163b6b3e30a395ad2deb4ac88fa58052e5b17073729b41c31e1b56f91a2606a3", - "targetHash": "f1e2390738b878c94984a774ba27f7ce1dfe9304624b4f14238b10ee17ad9d29" - } - ], - "amendments": [ - { - "ordinal": 7, - "previousHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc", - "currentHash": "fc58ad6c6d4b1439f732c3ffa8f9c16635d7ea95771f5f98a5139d87dbe2c23c", - "approval": "User-approved InnoEngine CI/CD, platform ownership and testing refactor plan, sections 4.1 and 4.8", - "review": ".agents/records/decisions/ROOT_TEST_OWNERSHIP.md" - }, - { - "ordinal": 11, - "previousHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b", - "currentHash": "5df2b1554553a9db29feabf4ab466bc948597f06ba9a5f7f0c4c6e0d305faf0f", - "approval": "User-approved InnoEngine CI/CD, platform ownership and testing refactor plan, sections 4.1 and 4.8", - "review": ".agents/records/decisions/ROOT_TEST_OWNERSHIP.md" - } - ] - } - }, - { - "id": "no-legacy", - "path": ".agents/rulebook/architecture.md", - "anchor": "no-legacy", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/no-legacy.md", - "sourceHash": "35f95260d922e900c047f140671b4805f65fd755f4e086822c2a50b8ba1ec3b1", - "requires": [], - "paths": [], - "tags": [ - "no-legacy", - "new-boundary" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a2da8bd11d5151d3ff856399dd88c86cfc2e4a3bf66cfaa095b39183a90f5536", - "targetHash": "91d7b048836348b136a12a876a8aab4149b9137d2593c659883ebeaab0b888e5" - }, - { - "ordinal": 2, - "sourceHash": "ca3db635c67a5e06af1fc552d2d14673df5219117c438670b2bb80261308e997", - "targetHash": "5598f61c60c7e528aa02dddc381a65b16b9c29b41dd113d1e7a205ed1c3cd834" - }, - { - "ordinal": 3, - "sourceHash": "cd95d65721a19bed59819a9dfb3218039fbf58ce5532b9516c3db44984c7d452", - "targetHash": "308cdac10ffa559063cfb6e676b0aafdd0aa0827d8f0daab0a80ed7c832f9ee5" - }, - { - "ordinal": 4, - "sourceHash": "e42ad938b23b8d9430521e0e67abcefb208494d08e4c19a53d5a45acd4e0d76b", - "targetHash": "79de0f9bd4ab824161b9dce0d0a277e5424cbeababd377095c2eb9d60e0fcd70" - }, - { - "ordinal": 5, - "sourceHash": "2b8f8939ec19c4de68cd0c8460a2366d20cdd71d6049839e54eb77572fd9cb28", - "targetHash": "2b64330331a1ee8039cbf370adf831b23896ac47b39d1ac2c7d4517f146d36b8" - }, - { - "ordinal": 6, - "sourceHash": "2126318b976262755e90da066ca6efa95c95318fbafd150e1eff03f6b1d8578c", - "targetHash": "c7468bc8577b9e9f5bdb1c9b7d59dbe4b1acdea283c247666e84d11e0d5b5c02" - }, - { - "ordinal": 7, - "sourceHash": "5586fdaa422ec00e446f3499402e7672a9cd07466802b5c0d8e9cf8b2e2665cc", - "targetHash": "c77319428a2d92e4f9b97d80f76706cb83559b267cf2b10d12a8530e19fa264c" - } - ] - } - }, - { - "id": "architecture", - "path": ".agents/rulebook/architecture.md", - "anchor": "architecture", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/architecture.md", - "sourceHash": "f67344b2282dc9dfa2850382f5e398fb0e3fff0727d274e523231ae25532756c", - "requires": [ - "csharp-standard-1", - "csharp-standard-13" - ], - "paths": [], - "tags": [ - "architecture", - "new-boundary", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1d0e28ee4c9fa6b7570ea77acc93de9df2171ad572be65d1ab3150def8ff1719", - "targetHash": "ea65daf30a811da2ec7dc7dedd847b681176f502810a4eeab08ec0810c491e4d" - }, - { - "ordinal": 2, - "sourceHash": "0ee4a1381219a58a864b2d34e63490bc76b41a6d3a91f162d10b545296301eb4", - "targetHash": "601a49a2801a6609c14b3059e972139dc73c4cab54e7fa4c3e551173232c74b8" - }, - { - "ordinal": 3, - "sourceHash": "b8fcd9e15d3ebd1fe14864d7337caf534fe5be36043c761b9da98aaf817f10ff", - "targetHash": "4dd627fa435109d5532f0aec4b4e087503378c5a03ca4d8f80f15bb80429ba4c" - }, - { - "ordinal": 4, - "sourceHash": "3ae787b3f7492f78c4d175c1afeb3440f337470bc957514fd541e334ca7a6791", - "targetHash": "bd95a93492c285b77af96ddb96b379bac6adae61891528a4f9c58b13d03ed6c5" - }, - { - "ordinal": 5, - "sourceHash": "f0646b2f9c636d6649ae60527b2a3171e98f1667369d7bca95825102773f09f3", - "targetHash": "5e83c73b6bb8440c2039d7b0961b946b8efb122076a9a319cb6299aae81fda5f" - }, - { - "ordinal": 6, - "sourceHash": "fc03e6bc382adbe5a20029ffbb9d84bf52481670141c960b6ee9daa7188efc37", - "targetHash": "fd5c6a6cde29106b250246e87a8cefac8b065e49e2324c313da280b1adcbc103" - }, - { - "ordinal": 7, - "sourceHash": "114ac52f6a6a08e00af88d925c557453cc899572151d6638fe5e6b485b98d7f1", - "targetHash": "eeddbcb38d649a9925df85e272adfd61bb5d3224bd09379256550f2c5d670cbf" - }, - { - "ordinal": 8, - "sourceHash": "1f55a6c4e2413d61a0c260b94b1379c3ba5381dd3fddb553d5068f8784585b6d", - "targetHash": "ce369b79a7e86ba1ec735801712b3209da7406c2eb97567c9b2da689ff960c09" - }, - { - "ordinal": 9, - "sourceHash": "10a2bfdf68c81051d2f8b0fbab24495a609c1771531462fbf9868e9bef0bc320", - "targetHash": "1282710a648b2c4ce6f358c0d742353f9d0411f2cb038224d986a2ef48115f44" - }, - { - "ordinal": 10, - "sourceHash": "bab9bd3ed3aa17a1a152fa893a422014284ab69be0c24b7aa6576647c333335b", - "targetHash": "078b288e1bfce8f69a0336108fed302b9640b776b8264c532755cc10f562f2f2" - } - ] - } - }, - { - "id": "core-reuse", - "path": ".agents/rulebook/architecture.md", - "anchor": "core-reuse", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/core-reuse.md", - "sourceHash": "81f1f41f250d478973221b4e118e33d2a2a63e38dffcf4fe0eb1f0e541382b22", - "requires": [], - "paths": [], - "tags": [ - "core-reuse", - "new-boundary", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1d1f7d4337cb7b3557772df8bd5c15ffa860c75c2437d323fd40a229bc7e0efc", - "targetHash": "5110ab1c16365bf82455f7973b4d4d795f677f395ae9f9df7fd052958fd6b57e" - }, - { - "ordinal": 2, - "sourceHash": "6fa5cc593dbe1d5fe96ff5e177c49a6b4feecd18f9cec91e80e7dcbec482cef8", - "targetHash": "3a0267e4d2d341ec997e02e6c0ce7d2bab535e93cb4c478da1a6b8bf2f059d6c" - }, - { - "ordinal": 3, - "sourceHash": "43025970366c56e171047fa7cc31fb9ad071cd667dfba68297c36756f02e73cb", - "targetHash": "5f82bceb744a6fb021aea81059457bf115a54f4b388adb979bde1db0755d10f9" - } - ] - } - }, - { - "id": "solution", - "path": ".agents/rulebook/architecture.md", - "anchor": "solution", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/solution.md", - "sourceHash": "20387390e2515fcecb193685b6832b6c072b6f9ac77528104274a70a01961346", - "requires": [ - "csharp-standard-12" - ], - "paths": [], - "tags": [ - "solution" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "4065ae4b625383e39bdc3924fc4a77e9eb8858b53a3ae6ae65343eba51e5ab7b", - "targetHash": "30135c42cba5ba64d85f4bed5b342cfc6fb42aaa9b2ecfcd95c6ec654a76629a" - }, - { - "ordinal": 2, - "sourceHash": "bb60b33ba54c7336e9799166c01b4052d126a112d4722915e3904b66fc4b5ab0", - "targetHash": "0483b55fccc5f6d01514232acd1f02e3f183882b5577f3b00d9926260bd982a6" - }, - { - "ordinal": 3, - "sourceHash": "96c711350d8ff162324062dfb4b49240d44be6a667a5fd42a42bf590c3a5e3ef", - "targetHash": "795bb85622bc01870e1e65eccb18705c1218060ae36969d3b6b356499e658d40" - }, - { - "ordinal": 4, - "sourceHash": "fac2752dd3f41f02a5029638af0b428b76cd57c54b1e806d7075b11720f6e4d3", - "targetHash": "8db8f6984ea6d97e8089f27c6d194ed044c67bdf33f61d890a137fdba29101fe" - }, - { - "ordinal": 5, - "sourceHash": "24eb6050ce21ea7ff4821e7c8829d4beeed5e4ffa67e27dbff16f278a535ae78", - "targetHash": "58bd97d696b2fb242b9115ed807e9f25c231ee908b2d99a46b3187d29e8747ee" - }, - { - "ordinal": 6, - "sourceHash": "557d3320b8ef8a82bfa2902a8aebd9d3645b7084fef20ec6932baa3c00b35c77", - "targetHash": "ea5a66ec42e2b16e5433a1bb9ac555169660b9be567d296b7ad8fb6425c98c19" - }, - { - "ordinal": 7, - "sourceHash": "25a9c3360ddadcf3681147ed90c1d86a63205a903b3dddde86992c1866b32e79", - "targetHash": "7ddcc1494b4e535474a0bd52ebe4f29e8063b9a84fa51409a8618a561e7dea15" - } - ] - } - }, - { - "id": "naming", - "path": ".agents/rulebook/coding.md", - "anchor": "naming", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/naming.md", - "sourceHash": "ac51c466873569f50b4d319ede1e533d53ae6eaa4cf2ef63709b37dc80e20f30", - "requires": [ - "csharp-standard-2" - ], - "paths": [], - "tags": [ - "naming" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a2ecd34c1a38ff4e0cdb6b62b29b72798eca5e7d8200ecee596a0810ef2cdb97", - "targetHash": "c03ed48491913faf71c543a24a31ffca134b16b52e0474d4e89d7e6e14477ead" - }, - { - "ordinal": 2, - "sourceHash": "23ed7825005c55de7bab25a13ad15e4d6f9003fa963e9dc6c8f83f25aa156aba", - "targetHash": "ec60fa8773db69f2d94c5e28c5901b9ce970d29f6002af8e2da7079b5b4b0b56" - }, - { - "ordinal": 3, - "sourceHash": "7146fd46302f8cb642df8c5543f331a66155d896ac1e73a902b4225731cefb22", - "targetHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b" - }, - { - "ordinal": 4, - "sourceHash": "1254fc0af71afb409b4898cd71bc434108cda6aff826f68e79fed35a059b7a43", - "targetHash": "a68bfd544c316dd8bd4140f7eaa5a16ce35adb1d0d0afcc885249f509ede18b4" - }, - { - "ordinal": 5, - "sourceHash": "c7d1597e6822b378b28cff3f9a6360068544ad29df7f7118e736d012ffb58230", - "targetHash": "e65985a0124327bb5ac46f97c457fd9c8b6678a6df1abf6ed312f65deeaf708e" - }, - { - "ordinal": 6, - "sourceHash": "de1e8fc2ce15a3e73e3f8a940abf54b6279a7d557154acb8298b5e688b8d82b0", - "targetHash": "c1fb02fbe518037ebdb862c96b2a42034e86f230c99fea894caee80f23f2290f" - }, - { - "ordinal": 7, - "sourceHash": "00238457aa080323c071fbab13a30fba20d564883baf55386c4e2b878f67da94", - "targetHash": "7eb5975ceb7bb9091a8d1b602e78a93e5bd4e2406777c26d8596810568640a99" - }, - { - "ordinal": 8, - "sourceHash": "4dd1a89dc1b7a7b4354e70948fc01c4ae5993733201c0ff5bf7f4713a5abefcd", - "targetHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351" - }, - { - "ordinal": 9, - "sourceHash": "779100086672741a3bd94e2b881aa35d8217edd739afdd017731e3983cff3a3f", - "targetHash": "aa807bb8015d7800fe77d0bada936898d50c066e8adb761d41f493812f0c4453" - } - ] - } - }, - { - "id": "members", - "path": ".agents/rulebook/coding.md", - "anchor": "members", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/members.md", - "sourceHash": "c2d7dcf9f01fd35785f5ca48ddab736ef338c05d6c3a831b979fa9ddacf6feca", - "requires": [ - "csharp-standard-3" - ], - "paths": [], - "tags": [ - "members" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "aeb83b2e3122df1174d2c41aea66196c503afe2be00362b0bb36455d2c95f535", - "targetHash": "085917a9e331374bdbffe0ab1b23a54a59b4a786efbd15cb1e6211b58ae5e819" - }, - { - "ordinal": 2, - "sourceHash": "155b573531fa878aa6c0186be8cb195d0df3cdcfeb74ae9ef7426d4de92344b9", - "targetHash": "fe50f60ab778c20cc0d21a6ad0822b8d1d74fb9878eca124ed11172b8171c8ee" - }, - { - "ordinal": 3, - "sourceHash": "21745673b0f5b00b93e217086d16c7cfb6032c6072c4a8a21d105e98b157afce", - "targetHash": "ff288d2db1925c5d45c15b8e615ae98de4fd532318df01077cd63da01c538e42" - }, - { - "ordinal": 4, - "sourceHash": "1013fa4a85db1b26be138b031f945ea3898e6408263acc3f8fea609270dbc4e5", - "targetHash": "974c2d1b934e4a8bf03e45c29cd7986379f5004432d6b221abf110ab1a0086dc" - }, - { - "ordinal": 5, - "sourceHash": "2be3e9229479242eb71723a3dc5b8fd0db9c7c77bfc06734362afb2177fef038", - "targetHash": "699a9572ad5560136fa23325e5c7463536eb0183ee14165e6cbe882dd9ad841e" - }, - { - "ordinal": 6, - "sourceHash": "15180fb47b019f533b39b45e4a634ef50ef086c781beb94a9d1171104d4f5fb6", - "targetHash": "5cf1e4657f622cfc45de3ab16fff72f5aa3633d483405f433ab89b3c0ae93d41" - }, - { - "ordinal": 7, - "sourceHash": "c00132896f827af44bcf3278f821645a1f0abe390cfaf5937bca68de30091b17", - "targetHash": "662c636b28489a240e62e4e4ff0eb0bf67ccc2b9f8b94ed461cd2ea88fa8bfec" - }, - { - "ordinal": 8, - "sourceHash": "96bac172645be96150f5d526df8293fb2e45ace5d28f1aa833e97cb8a3207b8a", - "targetHash": "23eca0ed30fbc3112f9912c8000b3a7e6f84dc4e30995e7618d995520476968f" - }, - { - "ordinal": 9, - "sourceHash": "42c62c7d7814e5d5233bdf69c66252172ddb30d91cadd2d789f390959fac14ed", - "targetHash": "84739f16c81513c858158016ff5eb127eb0a32313a8f8e08611418c8062fa91c" - }, - { - "ordinal": 10, - "sourceHash": "6a0621716390e0c953ed9eed37545093931c0c1eaf280210e4c8312a6981ac9e", - "targetHash": "26bf77b12ee406168444733e6cda0634672562df93b7fe79929b10b2572f16b4" - } - ] - } - }, - { - "id": "xml", - "path": ".agents/rulebook/coding.md", - "anchor": "xml", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/xml.md", - "sourceHash": "393dd0ea6825ded193ef10f1d6b114980d329af7a8c4bb4413a73b23e5aa54c3", - "requires": [ - "csharp-standard-6" - ], - "paths": [], - "tags": [ - "xml", - "public-api", - "documentation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7a3b010f1f556a0a4785fa2e0690d44e293735d9be73d684a173591be07c5793", - "targetHash": "7e1614602f9fe181223680359ab1f5bd48a8eb13c3df4636a7aa391e35d523fb" - }, - { - "ordinal": 2, - "sourceHash": "6b3170a223fbeeaa9708f03854dd47d7601bcc74996a78b9d7ec626f11fbc9d1", - "targetHash": "beac146b517f48ed476a18e9aa7f2fdab6820f3b4fe0541a84f7260f58c8c9d7" - }, - { - "ordinal": 3, - "sourceHash": "d612096e688a5c09d76a1b76f752ad16fb46152762b19175c5d3cd60ebec09df", - "targetHash": "c41cdb59a1d92c4bf77c05f55c2a0f4e8b120e04c75c0bfe4b4ed9114c2dbee0" - }, - { - "ordinal": 4, - "sourceHash": "7f1ffd3ababd147eefcbf539f98b37a7b1f72c71d90bbf1fb67063aaedfbd7ea", - "targetHash": "8d3a7e677d859685df4887afe75f337b6580c13a1f6d0ad8fad977762e900b50" - }, - { - "ordinal": 5, - "sourceHash": "8506f6d7df6456cc94e41eb26b73a779e56f702613304ca390a1ef7335a3a459", - "targetHash": "081c51b97a049870a642efb380e6f0c8f7f599f345b23bd7374ca3451eda903a" - }, - { - "ordinal": 6, - "sourceHash": "e1028d8d116d4bdf5be75dfb3ddbdb695cb8ed7635b7fa715004fe6a57545d75", - "targetHash": "db70458ea56d2cf1058f3dfdb653e179190cece63fcc31eeb175e8eb0d60cf17" - }, - { - "ordinal": 7, - "sourceHash": "d7c0d0b86975a71c9a0e05f68035490cd17dee25a52f1ee0de47b8f3e516984a", - "targetHash": "948a3d51f81a8080165a9873f3047e95d622f66af4c5f026f680691ffd35958b" - }, - { - "ordinal": 8, - "sourceHash": "53a79b0ffff61e3c64fadd0822b5eaf64d9d86c64f03abc4f10662923ebec648", - "targetHash": "2d5ddf314df4b45cfc643bbb67ee8f27f0d473a331e3430a7c21efe94762a9bf" - }, - { - "ordinal": 9, - "sourceHash": "230cd76be9c06b7b0154b24b64777add074d6436884be6cba68c8ebd6ebd887c", - "targetHash": "88c9235f5140174c3ba6859d2daea92448b59fd05a49db081cf9cbda38dd7a90" - }, - { - "ordinal": 10, - "sourceHash": "0771e910c76a4d4fe8240049d51a9777a9ca6d429b972d2b7f37c3915cfa24f6", - "targetHash": "ead7747e86c87d719e3f7d10f04baf07c58081893fc8eef642e3667041e763e1" - }, - { - "ordinal": 11, - "sourceHash": "59a8922dc82b328b1745c0f3b91fc0db931b0eb3fd0e3c26fdf6b18bd3f38ced", - "targetHash": "7a58317c4532181f9281b4245b89cf89416e5c7f789ba0d4a89909ba300d0c4b" - } - ] - } - }, - { - "id": "errors", - "path": ".agents/rulebook/coding.md", - "anchor": "errors", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/errors.md", - "sourceHash": "30704c6cf70560a9fc721937bcdfd23a425314b3023129c0d49d3fa310b051b1", - "requires": [ - "csharp-standard-7", - "csharp-standard-8" - ], - "paths": [], - "tags": [ - "errors", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "6282b05e7b7c40379cabb5455a04cc3cc13d17b37590554705a48af0d4f9c168", - "targetHash": "f633ab87a742f490f6844c5a76ade2c82788cf7614cf8940efc494ece6359aec" - }, - { - "ordinal": 2, - "sourceHash": "0980b1aadfe2ac68f2408411a4c8faa47d4827bfcab4626fa364d341f1c740fa", - "targetHash": "b00524a3be4313da355adf562e233fc3f040313649c6608e091bae13d0eaf4e2" - }, - { - "ordinal": 3, - "sourceHash": "76b50f93158d312ca2fdf09d100930fdac90a842695d5d71982bc1e62d47187c", - "targetHash": "397927257f1a6166ae6e517a14b27d64adeaf1f1114445342e8eece6f6e4f56b" - }, - { - "ordinal": 4, - "sourceHash": "4976e70e627ac2a6a257fa2480583a521c47ebccadf5a58e480b1da5512e369a", - "targetHash": "454b07214dc2ad21ecf0626da999dc93ac75863293ff9267ba6186a0c05aba58" - } - ] - } - }, - { - "id": "identity-naming", - "path": ".agents/rulebook/coding.md", - "anchor": "identity-naming", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/identity-naming.md", - "sourceHash": "200622c79a19914f1fc0a446f45ef0435af2fd895cc21f3eae3e8d04caf8943e", - "requires": [], - "paths": [], - "tags": [ - "identity-naming" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "94f2925d0a44f1b14240ee545aee5a3bd93c870898c4c93a12080cfb8de69f8d", - "targetHash": "2bcd9bb11b125445662ce6cb27bf034526113842a3865910a96d7abc9580c79c" - }, - { - "ordinal": 2, - "sourceHash": "5b08d747721d1fff4043b5b4cdcc9ff5a2012f5b2dc38d6cc15d1005115c3458", - "targetHash": "2713b77ce0dc27d740dee0e57723fa3d23d3d680decd110a02a647f3cc645fc7" - }, - { - "ordinal": 3, - "sourceHash": "4ade080ca04bd3a8af8c5cc2a079c0d7c576063df419672c0beec9f8e88c58eb", - "targetHash": "d420312b557f9c342f653da36246a2d21c4e3207e3da9a3a40b6a3fc64e40659" - }, - { - "ordinal": 4, - "sourceHash": "714ca4b88d20ad2f599c3e8c7287cb819db79eeaef3377ce67c9590515568ca8", - "targetHash": "2804cc91a2b24bc15e9da3dd4221dcb713b9ff097b7122029bebd75b0825201c" - } - ] - } - }, - { - "id": "formatting", - "path": ".agents/rulebook/coding.md", - "anchor": "formatting", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/formatting.md", - "sourceHash": "a1ea00ddad629daac88c8803b1f3bcac004a281b7ba86d761467118270ccb4d2", - "requires": [ - "csharp-standard-4" - ], - "paths": [], - "tags": [ - "formatting" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "15ffb0266967a20a678fa44d3a1a861394fd38c234e1994ac49f3c842d4a9377", - "targetHash": "cb43e57656d394eecb667b5a91bf099d57955790fcb3ec79047c13c41c087a9f" - }, - { - "ordinal": 2, - "sourceHash": "a7180c7b2a595dffc271bbf430dad6da72ac8dbabaa7a713ac746d3be7bdcbd9", - "targetHash": "2e5009668d2b80970bc549bfd3b689fb956a9cbc8f6e46a17a8a993088ce1b4c" - }, - { - "ordinal": 3, - "sourceHash": "31891a8a828b1709293b0f1f3d81067b15c1e35e0a9e8b2f6ef6149a56f0c635", - "targetHash": "e46c450ce7289e844808b05542a5405de9c3cc5223da703962351a2e8977ed03" - }, - { - "ordinal": 4, - "sourceHash": "95e12ed427e31ee89b53ebdd3551f8b671bb56c5d8d85a7c141127c989abfcda", - "targetHash": "9259801cd440e5cc5b6b5cd2fed583eedacd34d58d7996ce25a85593eb4737f3" - }, - { - "ordinal": 5, - "sourceHash": "8338542136dae7aa818b9446f5050658f3e1e89402c0c97e9d4f5abcc8b7d0cd", - "targetHash": "e1769de8f4cfb3964abe3c2337c13ebc543581c165c1db1b9602c1b1daed3002" - }, - { - "ordinal": 6, - "sourceHash": "41874671f58ef7bc6285d79b4539b0d61ea6e5787d16732d3e2493d84b043ba2", - "targetHash": "0037d6a15be093a1b084de5f680f593450f1e932905c775bb4f8822fdb307be5" - }, - { - "ordinal": 7, - "sourceHash": "19ef285a86c7baaf07c63b9a8fc5cd74742cfdc2048821333f3cf14a22acb7c9", - "targetHash": "0d0d8f06fb572349230c1faca233dc503361e135e9adb9d3b429d3f973601201" - }, - { - "ordinal": 8, - "sourceHash": "e37bcae5aa76b76e6688c78103d6163a25fc73ed080c760964579585038c086c", - "targetHash": "26d1fd9f48b300d262bf87e7122e38c49037aef35b791538082963a728ebab00" - }, - { - "ordinal": 9, - "sourceHash": "00ab8e1bf5ec15ca8c2df55c202cfcd4172b471b8fb6ee80cfa15a58bcbaf1bc", - "targetHash": "0bac228dd3b888345ff647461b01c6ad677caf65942c708d325d28739e3058d0" - }, - { - "ordinal": 10, - "sourceHash": "71d91f2dd249257949dd61c65bcc8ce6de0858dd093b4ce579a994233d78b1b1", - "targetHash": "9a29e75e154d9dc75e58f929fab1f2395c4421445636ba3ba09c02ffecf3eb58" - }, - { - "ordinal": 11, - "sourceHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b", - "targetHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b" - }, - { - "ordinal": 12, - "sourceHash": "220a360337c27b13b8b71061abce48e28d1e15b2be35f926d7b5073d2469bab6", - "targetHash": "220a360337c27b13b8b71061abce48e28d1e15b2be35f926d7b5073d2469bab6" - }, - { - "ordinal": 13, - "sourceHash": "bd72eb58404a8ec9c955888629d584dd75f8fc9c16ec823e28b7c8b33582f20a", - "targetHash": "bd72eb58404a8ec9c955888629d584dd75f8fc9c16ec823e28b7c8b33582f20a" - }, - { - "ordinal": 14, - "sourceHash": "292a1cee656bf17bbba7105dd15078649bbea67e2c0595da61ecdf76cd982017", - "targetHash": "292a1cee656bf17bbba7105dd15078649bbea67e2c0595da61ecdf76cd982017" - }, - { - "ordinal": 15, - "sourceHash": "abfa59370983ca52fbab3823eb970ba6f336b6cdb702d15fb183e6cdcb5e4661", - "targetHash": "abfa59370983ca52fbab3823eb970ba6f336b6cdb702d15fb183e6cdcb5e4661" - }, - { - "ordinal": 16, - "sourceHash": "d726209c4b79b93a897f315bfe110bb25769be2eb1743210c8240ba3db71845a", - "targetHash": "d726209c4b79b93a897f315bfe110bb25769be2eb1743210c8240ba3db71845a" - }, - { - "ordinal": 17, - "sourceHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2", - "targetHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2" - }, - { - "ordinal": 18, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - } - ] - } - }, - { - "id": "wiki", - "path": ".agents/rulebook/documentation.md", - "anchor": "wiki", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/wiki.md", - "sourceHash": "f133fa3bf600afe23b9f9c689e2ec6dba577a8bb40e2d0b4e103ea03e33dad86", - "requires": [ - "documentation-standard-0", - "documentation-standard-1", - "documentation-standard-2", - "documentation-standard-3", - "documentation-standard-4", - "documentation-standard-5", - "documentation-standard-6" - ], - "paths": [], - "tags": [ - "wiki", - "public-api", - "documentation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "29dd21456d3528c0aad4b35e725528a51737d4655ded222cd7ca16ec0559ab25", - "targetHash": "b7f909e062f751affaff3e8cd4d7c98ea53a3cbc8f37a17959e3b0640fdc57a9" - }, - { - "ordinal": 2, - "sourceHash": "96ccf044ebe34361538ac4c3dac0fd3d2b7c9db5ad532b3e7837d04945d57363", - "targetHash": "9c171f3383ff9da15e8face978be93b8e1da13d5696517f201fd2e639cab8733" - }, - { - "ordinal": 3, - "sourceHash": "824b508de366ea12fd61e4d9654921f3caebb1bd6a482c8bfc82949010f8bb31", - "targetHash": "cc08880907c077e40ef8bdc501254fbbe9022842760fac1e7e32a52c0ca6f3af" - }, - { - "ordinal": 4, - "sourceHash": "103c5e61c0f120534a56a37d455c285452c869f8e2ce24a72806cd9a1ad4f16b", - "targetHash": "f69c49e7f0c709879f599f30063db2086b783e60971508865aff02748a194ae0" - }, - { - "ordinal": 5, - "sourceHash": "2568dc23c50d9799f22535715a1d496259248c52318d5280129d71d928a350af", - "targetHash": "a77e7aac30183eb14f83cc9c085ab9821dec19ae63f8bd6eafffaa48aaaa758b" - }, - { - "ordinal": 6, - "sourceHash": "5534ff06531b8f0e4dcede3a7409924a894a57e11848043c894a891cc226419e", - "targetHash": "f85f2d2ad085f23b258020732abb8034becd84c5964ae41c00d977df176afe47" - }, - { - "ordinal": 7, - "sourceHash": "d84e481c7e94dccb3d7646f58403de71f291ddf796eb607f6762b5a8cd1d077a", - "targetHash": "8495ee4427e26bb8a6ee37d6de19f92de7513ef9419398bcb4cf6e86a8a61b5e" - }, - { - "ordinal": 8, - "sourceHash": "8905a7d3ff5e3dc12c838f074a7eed0664d76a6695e44ff5a1f99d4f6b60f4a8", - "targetHash": "5ae53f3449101c75753f1d4f1a259267adf4ce383492782fcd10de7c815f3de6" - }, - { - "ordinal": 9, - "sourceHash": "0e1d603608acd5aa204278ec1a5b69fc0e271ede6c8edb77edf667a1b3868b9b", - "targetHash": "2cc05fd8785c66d75571462f5888b9990c8720bf6f6a402708e0b83cb784f6dc" - }, - { - "ordinal": 10, - "sourceHash": "06dbaecfd67f1807ce241fa928a76e1b9da9fc66c5e19457f8ee84e843d95c44", - "targetHash": "3d9951ef1257c276f5d3a96b0e7c482bc8986fe597fdd2e990c73d1cf1e36282" - }, - { - "ordinal": 11, - "sourceHash": "f91ef9d6d4abc6129c4ed63429a5786c8f63324d43544bc62422f4d51bd17cd9", - "targetHash": "58fad6bddd9ff0a3400450ce71641e40827a76bbdb53c19e0e035ebd21926bb9" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "tests", - "path": ".agents/rulebook/validation.md", - "anchor": "tests", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/tests.md", - "sourceHash": "08acc77e48825494e38da726f62129622ae84b2624c745fb3e3665ab6475f5a3", - "requires": [ - "csharp-standard-10" - ], - "paths": [], - "tags": [ - "tests" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c666816f0894af76a5be080782b59d8a8c0d15a85d4a6d1e8fa88159085ba12a", - "targetHash": "71d8db9a48a6b37684c19e104a5c612b12efeb672a315213569cf409397341fc" - }, - { - "ordinal": 2, - "sourceHash": "e1b8470579451b60155c666adec815c504850c61de7a9b4fc16c94d61d46a3a7", - "targetHash": "c34aa9c4c84ed97426154ff61d3e1bce0628f3cdb7cf039c5b889c4f2ae1e82d" - }, - { - "ordinal": 3, - "sourceHash": "30a3e74ba432a5d41617670f4d683c3fe3cbb6f17af87327fe243715539ad60f", - "targetHash": "0080a897667020bb6af2025af6f10bff06651ab19251c850ebd8189bfa6ff76f" - } - ] - } - }, - { - "id": "compilation", - "path": ".agents/rulebook/validation.md", - "anchor": "compilation", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/compilation.md", - "sourceHash": "1eee0e7df80eff706cfb890d9af48b5b0d4da8ea26ea6e16172d750369af3cdb", - "requires": [], - "paths": [], - "tags": [ - "compilation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "41e7c3bb71db905e291e0d73dc660314ac65945b98be0d6044e25bca9f7dcb76", - "targetHash": "1ba3e574076477aa95f3fed742515edd4e22378d7041dabc7dd72e1ba6de8ac8" - }, - { - "ordinal": 2, - "sourceHash": "a743bcef487abea16b872c402957ae77f7060eb95df7e2a912abd615215f0cef", - "targetHash": "a204c03670687042691bbfb56ba3981bc162bc516a14e05a589db9328b1873e5" - }, - { - "ordinal": 3, - "sourceHash": "191eedc7864cd1a54ce09fdaec1018a177b1364934c04d1d7b6ea850f6d3e6ad", - "targetHash": "19960351775059c13c3bf2ccb3ce451bba20e8cc0c16fd74b00724eec00db7b2" - } - ] - } - }, - { - "id": "completion", - "path": ".agents/rulebook/validation.md", - "anchor": "completion", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/completion.md", - "sourceHash": "4dac1cd4f65641310d3e2d43ff402c91b56ab43868072cf219154ec861a8f391", - "requires": [], - "paths": [], - "tags": [ - "completion", - "new-boundary", - "rules", - "skills" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "cf73b7afc8d1c43a34e8307a65608c81b99129538e169bbc882aa89d02987956", - "targetHash": "e93bddd549b254c29da36a58d11863f98ac962467bfb6f59e5f8d84997bff161" - }, - { - "ordinal": 2, - "sourceHash": "b8e41433b5af0edc8f9e61054e6ac81c6aa2cacd0d90bbdbab1fb3b889c54bbd", - "targetHash": "50c049e7626af91e85a48625b352767356976794cd70460159a9f031323708ec" - }, - { - "ordinal": 3, - "sourceHash": "73e27ca28caa6f4e6c6f7cd1fe54ca2dc8e49e2ba15490ce7c5b1068354f8c71", - "targetHash": "cbbe4d856b6f17019688e721d7ce90667d36df2a59ccae9ff90325f50d4cab04" - }, - { - "ordinal": 4, - "sourceHash": "cde43bdde3090f6b7947886e50001b552d09d461f5ff40a0914968e988446ca2", - "targetHash": "9a46ff44b37d46c5a25c290b7730653dce6d57495aa98b26f22c1a3adb89f498" - }, - { - "ordinal": 5, - "sourceHash": "49c25780621007dcc71be5f2e2b4f4b002de2b0a9d96c40e81d193604c75f2ab", - "targetHash": "8d7d2cb58e7e0d01d42d1a49fbdb9c521b8fcfc7a503400100a292cd4be941c3" - }, - { - "ordinal": 6, - "sourceHash": "c9950b8ac4190e36f1941ec0d592853ba28171f1c75724002906cf5eb1bb4b4d", - "targetHash": "3325bd1c35ba13ea900f2a1d311afdfb36ccf2c97187043c7151b25336d5d56f" - }, - { - "ordinal": 7, - "sourceHash": "24a6745290c0969a46d0461042c788fabc2e4d0d0b69b3d355aebe16f7de0e92", - "targetHash": "ff823b2f21dc4d5d21e106aaffbf5c5651ae2d918e50e4280055927da58a197c" - }, - { - "ordinal": 8, - "sourceHash": "38808df39142443fd505e2cadbcb49dadb6cbc8e876d68b23fdf516472173de4", - "targetHash": "3628b29e12c796edde653461ce6b6c68ea22d00eaefefcee55cdd72e00887879" - } - ] - } - }, - { - "id": "review", - "path": ".agents/rulebook/validation.md", - "anchor": "review", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/review.md", - "sourceHash": "d50c80da5e8711ba64a368e4702b72a6bcfd74cfa244dc5be4841e431909a14a", - "requires": [ - "csharp-standard-11" - ], - "paths": [], - "tags": [ - "review", - "public-api", - "ownership", - "delivery", - "rules", - "skills", - "records" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e59fde7855e2854f5bb618dfe8f567e384bf2f4b7aea0374309af9a63f6295ae", - "targetHash": "2b380866737ba2ae9bb35b5bb74e64335a375297476a298b8b2d3819cef64f1b" - }, - { - "ordinal": 2, - "sourceHash": "3e0df150e5273f71eff27bbbc8671a331f09cb12a5c07a96c8e861a64bf28ae3", - "targetHash": "d2de9e4e7dead46bed8bdd02cd62f88fd8a4dc7fd5919fe7c35246dd42a47c46" - }, - { - "ordinal": 3, - "sourceHash": "1d25bc7acfa0735c58e3814dca382bf3234a0e7d965325e173bd88a903c14af4", - "targetHash": "718c54731d8094e34a332a646726fcabb768aff145338555d967fe2fe537e775" - }, - { - "ordinal": 4, - "sourceHash": "4c780ef5b65a99dad550c107a7c514591d3e2812ddff8d00cd308978579b15be", - "targetHash": "b5af8f7f7c5b556b5030eedeb74b12ba7c0b47abdb819ac3d06dcfc7bb4ff51a" - }, - { - "ordinal": 5, - "sourceHash": "009ca6574de647708b05c24de08073f8af6183a5c3b7fc0abbcf5fb23fe9ed39", - "targetHash": "e15d9eec2ecc8ba2bc85a5115eff36f54181b0a457f730082de4439fa5bbf59a" - }, - { - "ordinal": 6, - "sourceHash": "33c44f2b873bacb7822af7718aedd66c8967bd7cc3e1ac6f8a193caa4013a663", - "targetHash": "cc2046e1746a60a30a83b59a2278a35c7b918fbe41cf4de4fbd22232463c3344" - }, - { - "ordinal": 7, - "sourceHash": "e3dbaacfefac2daa3eef9aba4b6d0d9656b068941246544f122f5ac40e767e6d", - "targetHash": "16c75b1f4fd6c9e3ad3b1188a4b78c09a27e30fad55ceb9e0c7dd25b94d55285" - } - ] - } - }, - { - "id": "delivery", - "path": ".agents/rulebook/delivery.md", - "anchor": "delivery", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/delivery.md", - "sourceHash": "2885f4b1c8b1e7df776974fe199eb1434472042809972ed3be880e06ec65896f", - "requires": [], - "paths": [], - "tags": [ - "delivery" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "b86e8824d8bca39066e9cf7f6cf8ed191231dbe4a6d1402aff14debe8a722ab7", - "targetHash": "75bdf71fe20e4ae0db067be100a3c2d383faca67c136eb364f1a1ad67737da39" - }, - { - "ordinal": 2, - "sourceHash": "3b1ecfb344235b63cb4015fa1548529093f605c5673ae454bc1660106d7b3d3a", - "targetHash": "b67c64583f6b8dfc7eb0706a3cdf820e5e138fce3dc57b6957775ace596f9df0" - }, - { - "ordinal": 3, - "sourceHash": "e5bc32830644660581c3286a3d352fcf4828b676c91c116afa23e08b48f00c85", - "targetHash": "68b629f0d9e3d314f21508e9a2e2267ddc9cf87d80f08c64b7fe80154fd67b25" - }, - { - "ordinal": 4, - "sourceHash": "5101467f70d294ab413e4befbd85c00c6717a855cf3fbee0aa1b24c48467f2c6", - "targetHash": "2c0cb58de507485b88f08d2823a84dbdb3ae16fcaedba435b7ce4ac6843873f4" - }, - { - "ordinal": 5, - "sourceHash": "f67f47be3449ea304ec5c3279342840557c75efccf63bdcc783df37d2d974053", - "targetHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8" - }, - { - "ordinal": 6, - "sourceHash": "de6a01673254e95d66beda0153ba848d3f808fb9e3164e41d4561dfe6d07aed2", - "targetHash": "faacd093eb7499bf0665183a078ed48662b8b4e6e81a754b834705c231dc08c4" - } - ] - } - }, - { - "id": "notification", - "path": ".agents/rulebook/delivery.md", - "anchor": "notification", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/notification.md", - "sourceHash": "fb194215eb09cff4767222c9ba6d7c40d67ca7605f4f5a8acfeaa0927e65b3ff", - "requires": [], - "paths": [], - "tags": [ - "notification", - "delivery" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "79f37f44bc331d7924d62bf9f4247230ba284ce9399f74f9b8dedb52232bb557", - "targetHash": "a2ddcd88b762633cba624f02b97aeb0c95f4d4d7f35811fc44683ae8b46d6b0e" - }, - { - "ordinal": 2, - "sourceHash": "1df3e0e0a5f191314228a4d5be1242bd096be2fa118a256e29d168b2a59bd9f1", - "targetHash": "ef7e4415eaa30f14c183aa9ce389d8c2205d0001ba92c481a2655185b09fa200" - }, - { - "ordinal": 3, - "sourceHash": "8b74dc6c1bcb5502e35ce4ba58d7ca4be4828fb387862bb479937ba101029a76", - "targetHash": "13791b5add506d7d6991f492648a2a86e0ebfebb703646ce47857557dbc3eea9" - } - ] - } - }, - { - "id": "editor-projects", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-projects", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-projects.md", - "sourceHash": "d9d573caae906f0630b035ec9a3bfa54a80a3c50599f7e7c5cef9341b5a60077", - "requires": [], - "paths": [], - "tags": [ - "editor-projects" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e96d1c62c661cb5454c99143fb5f1a6cc8fd33daf956ec7a820ef4b755e71c7b", - "targetHash": "10d2588f823c1749153de1f3e501e661e1b4ca29c4e20fd176f84957f3f8e96a" - }, - { - "ordinal": 2, - "sourceHash": "9443cafc9093dae4fd32a2c037d02de87486add1e4cc1b52377cd1f94a125619", - "targetHash": "b5559064539f4b6b66250bfdf2e6d88dc318169e195c3b687e0735829633031b" - }, - { - "ordinal": 3, - "sourceHash": "4f5e5aed6897ace5c4b6cbfdb87904d6a6a8929cd0df981f479cee26ffd96743", - "targetHash": "39faedb7db5aab968faf5d85d5e00e3ce311a714928a0c0e187c7219ffed2d10" - }, - { - "ordinal": 4, - "sourceHash": "84cc6095ce04a31a8beeb1661912a58b8de562db0624475248f755b77a0e20e9", - "targetHash": "dd03d5a1ab0cc5f3b2c34f8f04f1763797fd42d79621c86ffef90dfceafc926b" - }, - { - "ordinal": 5, - "sourceHash": "5fe6ec264db83e6748ca0ae5daa13968f80aac8d6d005ee4e2ded8e32199491d", - "targetHash": "32d84d8fac657689afe63348ff0f5e41562769c11bd91a1d17e2beaf27850d97" - }, - { - "ordinal": 6, - "sourceHash": "bb394f03ce7c3962d38eb892f3240eeca07f7582563dfaaa56a128c5f9956757", - "targetHash": "fa2bf21fbe0202b247506afd72d2cafb390661d703060b1b1e56c2afb4dfc095" - }, - { - "ordinal": 7, - "sourceHash": "f03c8af813a56eea5cf54f57b7a6cbe268261de47a5d1c06c63facc942081797", - "targetHash": "96288472fe332b65829a9c6502eede3ddfdf9708aded8e000a855062d2261bcc" - }, - { - "ordinal": 8, - "sourceHash": "ea83c11a5783a0e4674ddbf18b0bd8d13ae741d859ba8d18ad3ac2d57309dead", - "targetHash": "3f91286809466021084655a592bad37b159faca5722312122300f29dfed86e38" - } - ] - } - }, - { - "id": "editor-state", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-state", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-state.md", - "sourceHash": "e72034747237a4a58c7793a1089a9edeffca5f3d5928f44421d622ea64cabc57", - "requires": [], - "paths": [], - "tags": [ - "editor-state" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "21913b4af529f3333c80fce2614de58bcee1cee8301d3a6965c3f557b10a4afa", - "targetHash": "b60c90ea3d239c0efad54377f869482807600201f2b530e5a717c685c69afad6" - }, - { - "ordinal": 2, - "sourceHash": "802beca59c3c5542e350400d5553b4376e4fd603b93289346cddac56db95287f", - "targetHash": "f1564be509a447142575c7444c71599d53f5e20b9a4c805c358575d5d13bcc78" - }, - { - "ordinal": 3, - "sourceHash": "ab15e73721074f5f58250e7e325e01403f065f8bf3ef26057fd9d4c287a2871f", - "targetHash": "790f7c69224b7ea64c5a0a1373b7a14b082c74ae3549aae36a6c28604ded12a8" - }, - { - "ordinal": 4, - "sourceHash": "4ab9e48bd4ad307a8eaf797efe07f0383ca83d3cf7a28f5f5c976ffcc21b71ec", - "targetHash": "5d944a27c3f73de2bd90576fdb16ec02ec43f96f87f011b13b9e4be7fcb33077" - }, - { - "ordinal": 5, - "sourceHash": "f439cf9fc6e91c8205613454bef02d000df1f466bce557863dcdb89daa5467ea", - "targetHash": "db8e4b6285cbc3f2db01c93c779205af7e79d0d183558548ddfa6b23eff5cc43" - }, - { - "ordinal": 6, - "sourceHash": "5e625d5ffdba8dc2fa694a43c0e2d06993f973f21f2582fa12e3613ea1f4bd6f", - "targetHash": "25300dddd17b788ff48a0592f39143241cfad86a73aa8d589947f59dc8630714" - }, - { - "ordinal": 7, - "sourceHash": "8f1386ba061db6235bb1f467ac5ff571974533e5ce32362da4692176d8f1d544", - "targetHash": "65fb119594d3e326fc2bb92d94600560f43a866c2118677e28721cf475b735ff" - }, - { - "ordinal": 8, - "sourceHash": "c886a65a41f603a5bea7387efe60e2af979dbdd589945ec485b82c5473f3d972", - "targetHash": "481ee912c2eb7d1469ccfa29593223c284a5cfee137eeed7e0e00ae3db19c177" - }, - { - "ordinal": 9, - "sourceHash": "11a421a9a00cf21080803c70bc4740cc226479a4c9adb1f5592e82eebd5e8550", - "targetHash": "cae6ec6b47f8f1ce871a5663c92db9336433bb4b8b91b33c12be418d81e42a83" - }, - { - "ordinal": 10, - "sourceHash": "80fd966faab70b6d56473c56b0bbffeaca4831ee75830e7195a4a7f8fc46262b", - "targetHash": "1c9714e407adcaa31fb97d2a9f3cac2df6f9bfa0e90fdf14d43bd4a7b08da6f5" - }, - { - "ordinal": 11, - "sourceHash": "6d61fb5dcecd2a282ec55c91f551fbf012adce132bdae2589a134bfeadd3d70d", - "targetHash": "a47795754591c1f7d048d40fe777c5ea13139d09d90f5ed5975b87947c1ececd" - }, - { - "ordinal": 12, - "sourceHash": "1e309e4880134bdf98872c3601eb16261a30b08ce818ce2919acb47877ffd8ed", - "targetHash": "45b8afb771f26069f27b34ba44bdbd20205c2326d0b51f2e7726138dbe758a8a" - }, - { - "ordinal": 13, - "sourceHash": "89047a47e41186f278ab244de7f51ef84f5a4fc8e33999fa99e84eda365a4b1c", - "targetHash": "6788b28fc30cfdf61c3bfcc1908275d0fefb87d4d7dfc090048307bf5a0eada3" - }, - { - "ordinal": 14, - "sourceHash": "ced6359a37b15683302c590a140cf9f9c5b8ce14a4583b80ab64082e9a164735", - "targetHash": "9da5caecada51f64b5e3aee43cbca9a0211a16a9d8d53ba8579e7d66d8e7635e" - }, - { - "ordinal": 15, - "sourceHash": "aa037a2eb62bc515463abef944986e311e5889fa1ee4bc031884fb591c405d61", - "targetHash": "f0e84b1b52daa6d016be5554dc787ce3d317b8a661ab91fc2fed8c3507dc1ece" - }, - { - "ordinal": 16, - "sourceHash": "38878299c8a97469089022a237b2896e3699d76cff0af54d8c2a21e8a68f453c", - "targetHash": "8084285b098674b7da1c0d669a65e729be5d82a42ef0ae513f99e065b5a02a04" - }, - { - "ordinal": 17, - "sourceHash": "d17b7484e2d5247bc6ed1dc891fa65149977f5d341c2079801f746c646c97843", - "targetHash": "79e84e819e757a783d8c88259ec68709db4c48ed616162650ff5d9f9b2b8c9ae" - }, - { - "ordinal": 18, - "sourceHash": "b8459066a743985e3556a91a0e8e30de69fbc32d33d2de7aa13e127e635f14ad", - "targetHash": "f25581ebde68849f22ca41e7f5740243e79236682060ba13ecd38681383d33d5" - } - ] - } - }, - { - "id": "editor-layout", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-layout", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-layout.md", - "sourceHash": "5efec2d08af93248bdcb799473c0feffedb7252e6b79e21dd4e817a891853635", - "requires": [], - "paths": [], - "tags": [ - "editor-layout" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0cc5f006ef001013725d7dfc893c2e4a3316801789d35046c34165d263d1ca74", - "targetHash": "b3d8d55da1736c8f726d1e953bc299dc44b4a601b75d871e860290eac0f5b761" - }, - { - "ordinal": 2, - "sourceHash": "a78da5ad23986a44349374372658a6557ee2d9976628b07e933721594fc468fb", - "targetHash": "10244dc31c8640f6338ea9fda49ed04d9b88f275d78a5d1ac0d9921647a6fc24" - }, - { - "ordinal": 3, - "sourceHash": "ff8188e23b8af5d3991c935b771b773a59598b7babf864d5b944150c0e013e27", - "targetHash": "a945b0383eb161ec90c28bcac8c42671649e0075ea4cfac4a64896aeaa1025e0" - }, - { - "ordinal": 4, - "sourceHash": "d2f1efe96013a971a0f435d8592204bebbe86ec48abb5f4bb537ad6b12f3e7d4", - "targetHash": "9a17d7b49fd799e072b6a9bc74ac804bab28a0b409d5c94355753fc174b07947" - }, - { - "ordinal": 5, - "sourceHash": "3376fbba35db3b14186fad6856628170c46b5ea568ec4da85d68e13a360df83e", - "targetHash": "2f686f33426418cf4f0f9eec5367effccd701e63d4c694cb7d6d15db75ced0da" - }, - { - "ordinal": 6, - "sourceHash": "102fc73957d8dcc7555e9f021d87b707da29f344e4b6715357256318c6944ead", - "targetHash": "8f0b47e959d0ede256c2c32cee6900ec3bf5e3d1a4b12238517767a4eff4a805" - }, - { - "ordinal": 7, - "sourceHash": "9aa7299366b57f5a1b1b5ca963563c742683e3fb6380dacb2af72d6e1d99fc1d", - "targetHash": "7cfd8c31799dd63abed0ed504917ff8314fcb6d63f452138228af79921b580e7" - }, - { - "ordinal": 8, - "sourceHash": "a60a708374ddcfa25bb62fbd311ec7a8bb959a60e3d74fc03ccb28777eefae77", - "targetHash": "426d40ba0085d6926ea69ecd5ef43299ae49bc34da5f6f6b5e5ca9dcdca8e08c" - } - ] - } - }, - { - "id": "editor-acceptance", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-acceptance", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-acceptance.md", - "sourceHash": "90c48174dc83e59f7a4c41cb0fb050b7f66ca7f9ee1f3754e0080e2a2e4b0681", - "requires": [ - "editor-standard-9", - "editor-standard-10" - ], - "paths": [], - "tags": [ - "editor-acceptance" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review" - }, - { - "id": "identity-reload", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-reload", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/identity-reload.md", - "sourceHash": "444b49c1e3ce53936fee718115595fdf49d01ac03ba1f2b51555f4700b4cc2d9", - "requires": [ - "identity-standard-12", - "identity-standard-13", - "identity-standard-14" - ], - "paths": [], - "tags": [ - "identity-reload", - "serialization", - "reload" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7efd6f55cdc573ede6dbd3da88c1e062e81a9d08206e8eb6a08d33cf391c8744", - "targetHash": "461d9cd3c4b4965f945d82df383799cef81636ca050fec38fa4cc4fe823090e3" - }, - { - "ordinal": 2, - "sourceHash": "d04589d0ce99484f813001832e92a2f8411d2d1a4bc64aaff8175fa1e1475e0b", - "targetHash": "96e1a4c1f7b1276a60dded704ccb43f726c58f86c99b06fb62c81a191ec78d1f" - }, - { - "ordinal": 3, - "sourceHash": "975f6da00e76191fdb166d04c732a9d0acc77828f65b1d270c6aa94bd0b0d07a", - "targetHash": "99cd52450ef209e62d9b1df287979ed26fd21732f487649198a6d2e68cf53902" - }, - { - "ordinal": 4, - "sourceHash": "5c2f32dc18a4142ae2b41e7f0191688430deb3942f8d653c058ca5fb09ae9380", - "targetHash": "ce9dd22d95b882852ac19d5bdc44feb0d4b1a7b622ff2ee54226edb48d07135e" - }, - { - "ordinal": 5, - "sourceHash": "811e0a9fda7f7c75556ae181360e3af2a2c4a57ddf60a74bab1d17eabed0b896", - "targetHash": "43793c651d33494c2fca6270495afddf406398e15f21897b5e5d0c78b92c20e4" - }, - { - "ordinal": 6, - "sourceHash": "92829893c198c28c5c8f6d5fb3542e80f592ee4c6b362826cc9965d23506bb79", - "targetHash": "82d65edcf81d1ebab2f7445cfa727c37a2fa6515c7e8401499ea049bb1fc0471" - }, - { - "ordinal": 7, - "sourceHash": "63e109baa64f062a988a244a78754cf21234b8d3478124c99a0f3a5b131a4f3d", - "targetHash": "643d446e16b807fb946ce67a8e30bb8fa902dadda34e6209c76b922fe1724b38" - }, - { - "ordinal": 8, - "sourceHash": "da38afa634e638869a4aa17188dd56e7762b25c0d33026205f91a9df4fee53ee", - "targetHash": "7c4e21bb14ba0d418ef4bda4c9d861566f4440aec7dc9e80491f2cb49cae9cfe" - }, - { - "ordinal": 9, - "sourceHash": "54c7a14b2e0f3011f82089ee72b14d27f8963883d6ee166fcbc0e6deda1414d2", - "targetHash": "4f660e19e473ed31e64beb070c3f3e2ed7c4954a7492677ec27b73e09942e56f" - }, - { - "ordinal": 10, - "sourceHash": "1b7d6605e20bbfa15843a42196d806ce2b1d06b97b9c7d678304cc474ed022c2", - "targetHash": "0ede328f6a2f73b21505f069bdfa56c0a8aeb2f9e8ad69d91e25353f6b21e25d" - }, - { - "ordinal": 11, - "sourceHash": "036d942ebff4f22a51c0b0ccd9addc19f374304a7554e9992a545162b92395ae", - "targetHash": "ca4b44218ee5981e939f63225dbac05eb2c2bee9092f5f1a107e566e209d9919" - } - ] - } - }, - { - "id": "scripting", - "path": ".agents/rulebook/domains/scripting.md", - "anchor": "scripting", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/scripting.md", - "sourceHash": "80e8df6fc099479be2c0ff32979713e750ae82d3bfdb4eabf93ed80cdf3400f1", - "requires": [], - "paths": [], - "tags": [ - "scripting" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "ae7fac91b32b5c7a54822bd463c7e8c24ed5b911311cccf18ee32bf9e57c3bf5", - "targetHash": "5435c2ae2dfba123581a5d70711c3a7174ba2d5130abc7d3439d270ac1b1e273" - }, - { - "ordinal": 2, - "sourceHash": "5d9f37c482d7ed2d1831728bfe868cdf0ef116cf3dfda5a68ac0be5491c6b44d", - "targetHash": "dad28a5daedf52b61db2aed9d3ee23a1195f76b283bed2b140c76fa8048f7aea" - }, - { - "ordinal": 3, - "sourceHash": "5c9522580d5b894b7597f4f96ac9128b92e6635bc21fdf7fef209f33a09f14ac", - "targetHash": "d973ef9f713818aae14881414686d10cbcdd0dd9db99b0daa45e5311cebda0e1" - }, - { - "ordinal": 4, - "sourceHash": "500bf61050900845ef55695ad3920e9d6904499db3ac32b4ee13cd9a227c05c3", - "targetHash": "79c5afbb8bd7d50ad8ea5fa3561c5320206c852540c066b10d1fb0c351a8babc" - }, - { - "ordinal": 5, - "sourceHash": "e7c01c6e4c8764cf658d961174e881c4c70cf317597643d35d9cd070e60d0633", - "targetHash": "dde5503206d60a43d01f0e7e4f22a8d95446f67d34511ead3712b206d1a3f2c4" - }, - { - "ordinal": 6, - "sourceHash": "94120d8bac9df2ed991b33100188f9a5785ac28cbd4ebc93c9649c31f8f4e937", - "targetHash": "d529ef789e2aaa8e38f60f4ac198a46e4facdf0bdabd1ed9562e558aa9df4ffe" - }, - { - "ordinal": 7, - "sourceHash": "7ed60e2fe34199e32bf4156299913bd1058fde36733c1eed362fc55a1adeb8f9", - "targetHash": "31b99354bfac665554a4395877403af5c4688d106fa52c7d6085d3b4d6549dbc" - }, - { - "ordinal": 8, - "sourceHash": "9d8ee25f4a083113ca0e53db9a1482d7a74aef76bd1b87fb9841bea819143dd1", - "targetHash": "cf7311aa118331bb6e7cc9e1f371bf80521521a657088acd450f70c31d5c0c68" - } - ] - } - }, - { - "id": "plugins", - "path": ".agents/rulebook/domains/plugins.md", - "anchor": "plugins", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/plugins.md", - "sourceHash": "534004fd37921a54e1c0f376836cbdfd1aa6ecfe3fa6a1633b2138e4f582cf08", - "requires": [], - "paths": [], - "tags": [ - "plugins" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0b7e6492b31100a32d590ab3a41be5463038d17404f53edce4c5657a8d9ebc5b", - "targetHash": "060489b1b5249dc793a82e452dd1bd8cb61f901ccce63c81a79d3e0506115a97" - }, - { - "ordinal": 2, - "sourceHash": "e1ea473d5024366f6c1b634551d461d2271cc9699cf1c765b2be393c8e947494", - "targetHash": "49bc313818af030b0fb0001db9b11ac40d82d4d250cb2f240f66a19e8d58f4c7" - }, - { - "ordinal": 3, - "sourceHash": "010d03f20e88a10ca3465d22b36ea51f9495938372834fb019c236ce8bb9a67b", - "targetHash": "cd74fc9db1ac9ad8552ddc1026da2e047d767fbae0750b4229c026d14a8ffebc" - }, - { - "ordinal": 4, - "sourceHash": "0a74219bb93287684baac21ff83548cae7bcb14e0e7fd53284e1763a11b6e548", - "targetHash": "33ca94517dcd97e912d8078690047eda94c1769221a3516a076975e2091de14d" - }, - { - "ordinal": 5, - "sourceHash": "af5f687faf8913e068718e3a73cba0003d520121aeeb249479f62505f3aaf3a6", - "targetHash": "4fabe28f2f6f87bed92709444d8db01eeeb6eb9fe3e1eb1104b6411c0bc46d94" - }, - { - "ordinal": 6, - "sourceHash": "c46d6878522f11987318a6a509d56e72b4f6681e98af45cff3623657630d9959", - "targetHash": "a4e8d4fe297362f0912a6310926344416859262af97417f26fef4c422161f6e1" - }, - { - "ordinal": 7, - "sourceHash": "ad39665d09837ad8d1e4f78c284b97d4277c68a2d44ae4442a1185d9b8a3b896", - "targetHash": "be4aa6279247bea1bc60e5e3ea8b0d38a9cfbbc1e5c3b9fcb841fa604d787564" - }, - { - "ordinal": 8, - "sourceHash": "f4ab19400c0702d8da6092df70ecdb4c75293f97205663411aa847c3c325963c", - "targetHash": "264796708436b8d5574b48bfe1033bc1fe45698ca89141352d21041b53261234" - }, - { - "ordinal": 9, - "sourceHash": "6397690af4b51494ac9f83bde6b137aca3326fdd6aa74bab0dc42d93490a2d21", - "targetHash": "3a363df664fe8edde37d6e6d62ffe0566dc1fe90376c61aa869a2bbcc410b6bf" - } - ] - } - }, - { - "id": "rendering", - "path": ".agents/rulebook/domains/rendering.md", - "anchor": "rendering", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/rendering.md", - "sourceHash": "3ce1ddba07e09326bbda59b5ea8fc931e767d0698f14871d5d3178c0432ed78a", - "requires": [], - "paths": [], - "tags": [ - "rendering" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5932ea2fb64b334a2f80454b87bae12abbc4f754261284548020c888ab21f19d", - "targetHash": "2daee5dc2000d60570098fa21495cc91b822bc6ea9375919f518aaeba72e0ae2" - }, - { - "ordinal": 2, - "sourceHash": "ee5e8af526141af2cb7ee6ab91b439e48d714da2c1f8e832da7553ef22c503a6", - "targetHash": "c4b79e930d63306c74e4971ee30aebe894d8a63c1e1c8c63a548637e1ce2e098" - }, - { - "ordinal": 3, - "sourceHash": "656c7f1ead45a3c2d3163ae94c6f0c49657a07676f798b0615deb70769a5103e", - "targetHash": "6884e80117b1b268d6ccc90625c90b76fc1f7cef3d809241e60103628fdfedf3" - }, - { - "ordinal": 4, - "sourceHash": "1ea202115e8e050c1713a7233da99ad2bc40b4dd94cb29d5cbf5e7061bdec892", - "targetHash": "41a700e5ca6457dfb3b993750452ad8f61e764fe78b965cb510408f3ffdda786" - }, - { - "ordinal": 5, - "sourceHash": "db8d1cd54f08743dd4298fd3d5411a31e8444aadbb26a42dcd8b3f5b27a8fd63", - "targetHash": "916437cbafc25fe06d0bdee7041d760172ae5fffbe54dadb1c5ba54c8d54c3f5" - }, - { - "ordinal": 6, - "sourceHash": "71eadeb9ec2aa3ec64d0f246f13251317f05bb6bbcc44f1aeab3f5433d01d2ac", - "targetHash": "ae883035d12008e913974ca35a0867231c2088c1a8ae62901566f021cc18ccdb" - }, - { - "ordinal": 7, - "sourceHash": "f899f36c3b77d92fcc886d9b7d293b9881feeca684e86924773830af0b4b372f", - "targetHash": "303882022ebcf8c451e2066059ec9db1d0750ae31690e8e0d4be4eebf569e768" - }, - { - "ordinal": 8, - "sourceHash": "6cbbcfde884e75e96c1efa01bc4eba9521b988dd0539a50971e71a34c7a6717a", - "targetHash": "8f1bcb3b34247ece9e813fb2629cf73ca156a91a65b48d8d01d0bf42754d0440" - }, - { - "ordinal": 9, - "sourceHash": "7ede213dd1659d4ad6f51ee6eb413609ada0db844ff03f38311bef69b2e77cb1", - "targetHash": "f55f5fbf29d1d956319ce9c0290eb74dc8066464aaeb19aa047d0af2ad95bac3" - }, - { - "ordinal": 10, - "sourceHash": "0e9ff540e001733230ba91a68544e1305ee617702ac64afa50608e05971e14db", - "targetHash": "5b4a800ce70b35064669ae0b2cc88c49d8a2a282717b0e150359a383f9da6b3e" - } - ] - } - }, - { - "id": "content-frame", - "path": ".agents/rulebook/domains/rendering.md", - "anchor": "content-frame", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/content-frame.md", - "sourceHash": "2497480b3fccd8e6cd5151273000b4e58403d7564490ed0fa416c020ab55c3bb", - "requires": [], - "paths": [], - "tags": [ - "content-frame" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "b828af239b13805714c4ff0893b3ac805dcbe968cbddc152e9b83a7fba2df93c", - "targetHash": "9d3d49609e700b227a88cf6d080046723da6080ddd5603ed1ac6124a55ca927a" - }, - { - "ordinal": 2, - "sourceHash": "9cc6e95f7ea461fd696de07ce76f8797c96ed41f0433e310e1af26582805b22b", - "targetHash": "a3c3d40432341948da3425111919483a71dd9a670453a779ce14988de2c86b27" - }, - { - "ordinal": 3, - "sourceHash": "7603640023e8356e822dbdca1f0bce8573039862e61d8e8926b0acd6611b9494", - "targetHash": "799b62a6394cc3d00628d0011a636ee7132d70faf3b87a2ad91dd2ebbb26fe6b" - }, - { - "ordinal": 4, - "sourceHash": "aa8f68717a46b2a24105079cfff00c2955062fc80da10d8005ef3611bd7d997d", - "targetHash": "b275fdd63312c343487ef5900b754569044bdefa162e7984ff45a3ec6ac9d121" - }, - { - "ordinal": 5, - "sourceHash": "b95630e0b3deb0b2d09de1f2ce037457354b9e319ebd2f39c8106174275eb320", - "targetHash": "e6801a9f0117cbeb680dfcda3d3becfa769e2dfa867fa33426faea40f37d2ae8" - }, - { - "ordinal": 6, - "sourceHash": "8e6c8256ca3966575e246bf2c4986d105214afbb19a069bbf83c3e0b40de379d", - "targetHash": "e3eb98850d4fc6b9d1f10314f59ff960d02fcc31805fb8c1806e4871da6a2cee" - }, - { - "ordinal": 7, - "sourceHash": "2c398b51c32d526e1b9337797dc9d7a06302c34f25f22fb2806075bca491c99a", - "targetHash": "7abc730bed80f7182f50a2fa2d800ec1a7ff4c7f93c10603a7f9db78d1ecf0a7" - }, - { - "ordinal": 8, - "sourceHash": "1eda47cd0c85d1ffa678dd58baa94224f78967bdd53aeb22c46f5b551bb403f8", - "targetHash": "5295573eccd283d7ebe32cbc6a81a9d7de00cc5c69053fd80c864f87ba200db1" - }, - { - "ordinal": 9, - "sourceHash": "ee7ed4698848793ab73e52bd3e73fd8c709f75028df195bbe876b70e0f648a28", - "targetHash": "1ebf3f605999863b058ea2e0842296ae13c048c5c2913da0e05fab43b2a207d3" - } - ] - } - }, - { - "id": "build-host", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "build-host", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/build-host.md", - "sourceHash": "cdffaedc391e3a93d30493d9b9313e68b9b4cce51909986ad08d9854fb83b5d5", - "requires": [], - "paths": [], - "tags": [ - "build-host", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "f6321c47ec82e2ff39f1ca03bedcc8dd4ecb43acb812077b709241a61ecbc40d", - "targetHash": "5dd7f241116e94ec54013b739e2fc8b0b889bd2e08dcf2f3df1d6dd3e3db8da1" - }, - { - "ordinal": 2, - "sourceHash": "b19118c564bf7869a979959cb5942e88df5ab3a54f541061adb140aa316ba10c", - "targetHash": "6f3541d92930adac22f939113bedc1be29b6dcd0b0256d342d4426a1cd3f31dc" - }, - { - "ordinal": 3, - "sourceHash": "c7c3e1e13e6ec6f3600f6355d31a4a8d755f43369274baf9acfbe21440e8a0d6", - "targetHash": "48ac069968aebbff6d00744c92c6b5c1c47cd81503c31164b1e49962a34a6394" - }, - { - "ordinal": 4, - "sourceHash": "2ce9b85e57802b8c2a31c4cc3d0c8235b69068b7d46a7e5277978472f4de88d7", - "targetHash": "5ca44339f245dfdeecb8cb02b274bd3d830327330c73814987e11c93f2429800" - }, - { - "ordinal": 5, - "sourceHash": "8b73963b3c9f46a9705c77b3a0a00ab19c234e26eaffd223d6fc0b2e932f603a", - "targetHash": "00aae0b2ecff9452b6ed1bddfb1dc00a6b0aa126dafb52b3b2b71fabf3b7a72b" - }, - { - "ordinal": 6, - "sourceHash": "df22738791386899274f61f777a931262733f8a48f1744208c042fea57880d80", - "targetHash": "4ae5ee3546730297ce1e27aeddf37b00703842a3fa13f3780e65e520c495016f" - }, - { - "ordinal": 7, - "sourceHash": "b2d018fd842124e7109ad0973e6e907e908ea05c3d29d2ff0bbde4cc7abc8e4e", - "targetHash": "5e19b875c132a28b4329330254028c2514adafa89b1721a0836adc7bb523bbcb" - }, - { - "ordinal": 8, - "sourceHash": "224ccdec3ed83d364b31ccbc614ca441b1dc8b66d1985e44e5c5d615342d7a67", - "targetHash": "bb30e559aad2e6a87f7859cfcb4defc3eecb0d2f2b8071011d4a10db773697e2" - } - ] - } - }, - { - "id": "platform-products", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "platform-products", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/platform-products.md", - "sourceHash": "2944ea52876d78948249d82531ccd4e288b06747115d925e3dd82fe97984a24e", - "requires": [], - "paths": [], - "tags": [ - "platform-products", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e4a5c69d79d1b3df103fccdd30a962295bcbaa9abcd77f19244d699c651fc8a3", - "targetHash": "283faab72abcd7c6e59e24926ed39bc73668e8cf3d3e9476350c1b3f834b3165" - }, - { - "ordinal": 2, - "sourceHash": "bbd068ddf45b8a55440546f88432f08f1bc7a2b94ed6aca1d4f72c53a59c15f8", - "targetHash": "1ccc62336920d8d206c660bb69253fc729a50009f5183994d8f51e997f81a733" - }, - { - "ordinal": 3, - "sourceHash": "38365fab9c07d85ea81c40cd0d181f0549b781dea9c48bdfeb0559a24a02c607", - "targetHash": "e07c444e54ad0706b8d60f18ea4251134de8da429be5becd82f620b34e9cf3c3" - }, - { - "ordinal": 4, - "sourceHash": "1e3f7d9acc0b4f337cc02dc2fe79d66ccda45221c943c14cf71f91de709ad989", - "targetHash": "d4e895af3df576a50c336831087da0154a6a61c49435523ab21d1c38719aab82" - }, - { - "ordinal": 5, - "sourceHash": "e584940bd16fa8ff45182ea7674910860e3a03209a16703f1b06a98866620b01", - "targetHash": "f298d49d33a65277f5984042f0db3612a2ca869dade024d0d9f35414d598feb2" - }, - { - "ordinal": 6, - "sourceHash": "a1d364c82b7a1c3cb16f56bd1aae66832cb7b15706a9a2c5206ba3fdaa79a886", - "targetHash": "cc05be97176ef293898bc6e19032c1d524212f4072c437cde90d72971f79b18a" - }, - { - "ordinal": 7, - "sourceHash": "875e20eacd91a77fba60d63920f357e4e7d1a3e3ae2c1f9f830da1fd8b8000a7", - "targetHash": "df72d5380faf70912ec865e14811a77f0fc2549269872aa8bd9b47989cbdeb9f" - }, - { - "ordinal": 8, - "sourceHash": "6af5d2f1a1c1f5083c4e8da9c181963e99d54ea38a9563da8747ea5fbcaab5e0", - "targetHash": "6adab6f1f34ef19fdd6e7b53cebc19f7c644791c9b9c3ae1dd3832d18570fdfb" - }, - { - "ordinal": 9, - "sourceHash": "dbfa9fbd4fa122d1eb9ea53bd5d523239d856d17a436e8df8616730f411e6a95", - "targetHash": "6ec84e13d26475f76db8a7cb32da00e07c29c3c112810af53e982217410c0065" - }, - { - "ordinal": 10, - "sourceHash": "c02df2b6b87a837d2297dead8bd588d68b1e0b158f265aa2f720331fb975487a", - "targetHash": "cc2c00b11df385e07035448fffcf8d681df96acd8382ec0e1558f5d61ed8f0f3" - }, - { - "ordinal": 11, - "sourceHash": "91e9b473ace4cf03421e9e288264dbc1c14ede8d85b92a96436ade4f1831095b", - "targetHash": "e51ebcaf4adffa66818e1fd80078f4b77797905a7bc1b34cf6e2be8289b159e9" - }, - { - "ordinal": 12, - "sourceHash": "a80250da185512ce2c8cd8d97ae37f7e29f823e844cfb499659b0e89502d3ae3", - "targetHash": "4b3ba100cd3a0a89254d79cdd4d493856dfa800f804636a44ba8849cdd82d4ca" - }, - { - "ordinal": 13, - "sourceHash": "627102228e1d72789f8c8c31687375dbeedb3e7c275a879eeed503ceaf1203d6", - "targetHash": "ba4580a371549e2c475316965ddc62910ef7c48a76d4ed19937b4ad6ff97d989" - }, - { - "ordinal": 14, - "sourceHash": "86fc3f18e3017b563ef8b55f15576986538a7e01dc9f61b869e698a24ee7cbfa", - "targetHash": "1d6604b2c73f03940f77f447e9dd42a9bfec9ef056d70190985378c7ee76d2bf" - }, - { - "ordinal": 15, - "sourceHash": "a5945bfa41a6b678b345609c3fb7753aa2aa3a183b9ebc7d11427caeaa0ab25c", - "targetHash": "38ad850bf1f51ee335adcf4b28bac58eb15636a54d7d90b2d5ce1d04ba4e0ebe" - }, - { - "ordinal": 16, - "sourceHash": "a4e99ab18a653cd24bc57f0d7df13d1dfb5778cdbf0a59aee49002ac93b77915", - "targetHash": "999168f0eebea40a7f0a0c41fdb26eea4b45a29e467ae42450117a3c18e769bc" - }, - { - "ordinal": 17, - "sourceHash": "0afee409eaa98d08d8e1a0334b61183523ae221b3f3b86f59d9607e0babec762", - "targetHash": "7e606e087f9376f10f2fb4cb2ab487372c83fb64d3f39fcce62806b806b80028" - }, - { - "ordinal": 18, - "sourceHash": "09969edea363049274eb103b0f3ed28431ee6c029070d88a2de8e287f5f0ceeb", - "targetHash": "8e56582f7971f183cf862b5dfa4b238440064196565221baad83cc0a096c76d5" - }, - { - "ordinal": 19, - "sourceHash": "066a20c7fa263bec6fb1bf35b123412cdc19b984fe121365b77d5eb4e8bd7fe2", - "targetHash": "770fb60453044c83021640675b4db0b4b0d66d24e76025e3bae9c3022b1fb3c2" - }, - { - "ordinal": 20, - "sourceHash": "f6b7f455387f2ffe8b272441fe9ccd7c6fb793a640332c7889ec4b963ceec35f", - "targetHash": "a5d16ebffec8484bdd8e48ddf07eb6f9010296c0d3d03506894434e5ad90b20a" - }, - { - "ordinal": 21, - "sourceHash": "96a1de39674aff5c38eee8057c697e37d7b1a34051133b3471bb96ff56933c6c", - "targetHash": "80284b4568ad4e28bf6d275ef21ccd35b92160cbad4d4832749532bd55caf1a1" - }, - { - "ordinal": 22, - "sourceHash": "2530d325d5dbe1448fda7a6e246d71380bddcb95a48162a33cf8950573e8b381", - "targetHash": "01c97c9490d373912aa39f72eb12078aefb786893fdf19d8d1f867575b37aea4" - }, - { - "ordinal": 23, - "sourceHash": "85f424ca1b9c5b3d21b925ef469a1a515c31f2ed651a82a92a208258f55e961a", - "targetHash": "1e1554ca14b8f1c1c792b2ecc51e5a22d04b4db18e731de88befcee8d23444bd" - }, - { - "ordinal": 24, - "sourceHash": "1121c4faa7c7e120a90135449a220ec60b622d7831ad68c2c621d96fc0e7efcd", - "targetHash": "dc1b482f4aab5734dd96ca96d2d3831385aae7c4886d7cd76388459e689bae4f" - }, - { - "ordinal": 25, - "sourceHash": "b61c0f0e7f3be551ed431b43a76b62991a811b2b51bafee0af5ebdb39d320a59", - "targetHash": "f1bd1a5d08935b55441ccf2c4708d8841d92a9f5a6b80a5698e1a47d1519fb25" - }, - { - "ordinal": 26, - "sourceHash": "1193087c674adcad2e28e80da089bca39d1bb083e175c00c46e3bfac2e21f07a", - "targetHash": "7f8759274527c9b1b1ead5bf64427baf9aec1dcb42e3902fac73ab250ff7ff03" - }, - { - "ordinal": 27, - "sourceHash": "780f84046cc74eea6834fe6397421a5e76f32bc030c29b2d0a7e66ac18155bb1", - "targetHash": "af63d3d2ab4dd248aea2c3f8eb82cec97a485bc066d80430c680c7c87c5da3f8" - } - ] - } - }, - { - "id": "backend-build", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "backend-build", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/backend-build.md", - "sourceHash": "0148f6f69bbb6ba3463ae4341dd1f406496948fe9fa5bd4ec8156be0b2db35a6", - "requires": [], - "paths": [], - "tags": [ - "backend-build", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0b0c54c567bd05ce35312c32ae5d319d22543f554671f078b2bf33bfb7bec768", - "targetHash": "5c94c310b27e6a9df124ef8dd9d80d81ce0b2337516f75634906f6613f916fcc" - }, - { - "ordinal": 2, - "sourceHash": "1184ebc811c53110f9b93a156ddbfe721a06e84ff561b7b170de4b8a4f09c7d1", - "targetHash": "fe2f86b126dc556658b3d98510c367c9b0d0e1cdadbbde575b452615d2dd5b9f" - }, - { - "ordinal": 3, - "sourceHash": "24e7a817f0f579805afd40f5ed16f6c767153b6ebd44dacee9c627313443d019", - "targetHash": "8bc7f52cde6311fb50418b498c44debfbd02a9e5072a2002d3c4ce6f78133a06" - }, - { - "ordinal": 4, - "sourceHash": "930fcd222b949ce695b267388f8203bd798c04c174217146304ffc68ac90e511", - "targetHash": "ad3910305ee11b6cc3c301f641715d36d27bf349ea279be1690f4137dd73b6d7" - }, - { - "ordinal": 5, - "sourceHash": "464eade4d3d14b2b800c761c2c5e26c77a22a4351b5ceebcd1f112dd3cfdfc2a", - "targetHash": "229dcf70819f94d7a8291b75d8cbfdb623e6c6e39b36db4f37726d8c1fb43f8f" - }, - { - "ordinal": 6, - "sourceHash": "47a490a8d8506b2fb25cf4e48407c8654b2cbc143c272e53e509ecaeb52dbbb5", - "targetHash": "452e40de8c98a748c939e30115ca9962a497cb38c20ebc931cbc691240e59ecd" - }, - { - "ordinal": 7, - "sourceHash": "77c7d40f8caca628be02ac2147345e04132df08185765da27e5d6e823ac61f1c", - "targetHash": "88fe122ded5a5662f59de6cb274cf44aeea96fd79acea3c3d8ddb8160b0f9882" - }, - { - "ordinal": 8, - "sourceHash": "dca2a1bf003d9c82f5c57956cc315bd20cfe11d5c9c52caf2aa2c3c06a6ac852", - "targetHash": "49a91d8ef3552a254e865b8629a5e296fbbdd3f9808a30932cb3af1179682abc" - }, - { - "ordinal": 9, - "sourceHash": "1ea3f833bf68f4009d0a8baf5b54744de3b51c97d38370e47e41a34bc31a0f96", - "targetHash": "94d8980e98c8bce72f4cc50106880b725f8a4dc62f9fefa0d08047bd816c451c" - }, - { - "ordinal": 10, - "sourceHash": "db9846f1d6d8462e20d840a76c3fd2271e2cb1c171ab6a3c3dab8373c31d5e6b", - "targetHash": "6d5a1d919c9a6d1c0ab3d783e344175cabaf1b7696b2280051dee36b64204ec3" - }, - { - "ordinal": 11, - "sourceHash": "4417ce20429062015905ffbe98b19a0d31908960f6d5863c80c27fd2b7644ea3", - "targetHash": "c932db0ddc349b2623393bc3be6ecee78b5b949dd6ffbe790994736f0caf7aa4" - }, - { - "ordinal": 12, - "sourceHash": "167343d8d3372823fd6a5c09a919f63b5bd1524b4cb1b6229f516f4eb6a7044f", - "targetHash": "93cd250c40b90c2dac1407b7622fa51b291b959f2576e2a09d48fc04c2ae4a7b" - }, - { - "ordinal": 13, - "sourceHash": "d03b95720e5346978f818d1cee320f8eb0576eb915431635b925dd83b318f5bd", - "targetHash": "fa6f1d36700726347605104c6b97cce1e94833efd072d50b39f17d96687c380c" - }, - { - "ordinal": 14, - "sourceHash": "d8360e8265f5088a3def25af85805151c7aebd7a508d09cc919f19f5e24d666b", - "targetHash": "c718e498d894d8502a6e4f66a5896eaa1683c6fcf81cb18d27e39a9007126bd3" - } - ] - } - }, - { - "id": "csharp-standard-0", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-0", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 0, - "sourceHash": "1ae167521e9170f3f63e3f8945bdb849e260d44c79aa523435df060da55077ab", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c59de057b27b99349948ddfcd688fc59906fa79587ce29428c2787f948f0fd2", - "targetHash": "9c3e7f891fe5b00f62469b1bbb2543dbb748fd248b39b051c6d9c657c1a274c3" - }, - { - "ordinal": 2, - "sourceHash": "2cbe9059c50549861b8ece9ad35ec1bd5c87886fc01da521d2bbc9d73c39132c", - "targetHash": "a1736a899605f9dbe302d2891ebd2d871f84c5448be3624cf7a130be9bb38d7e" - } - ] - } - }, - { - "id": "csharp-standard-1", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-1", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 1, - "sourceHash": "e6bb6be83dda2765ee0b7f4147efe8d179357e106fa40a77b666d79b6f7764d0", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "6ee4ceec96bb3b6021f4893cd90edd04e72e3f2a46c786e8c934a3aed28745ba", - "targetHash": "c3b767fc362bc09f11a826fc31139b772fff0314e8ec76b496a93913ba19836e" - }, - { - "ordinal": 2, - "sourceHash": "888b98a8bcffd2623bb63ec661c3cd24dbad4c62c070b538d82f2fa31b4fc7a3", - "targetHash": "64e2901909af165f76cab1149c9729bf5bcd046394d18b8453443d6789927cf3" - }, - { - "ordinal": 3, - "sourceHash": "4bfd2941b7773db394a6e661183b975a55a81a195a7f4c0b7f5cf23ab8d46908", - "targetHash": "805254701ebf725180887414b642cf5e776d5259d41745703749de26000d1622" - }, - { - "ordinal": 4, - "sourceHash": "b9e40ee1518b1f41589718f6deff2b2b2e0a34fa42a35852c61f2468ab94e9ab", - "targetHash": "b3bd1bce40cf14e041e29ad28d4f6fe7736feb5f574892f12db012d2aaf36fed" - }, - { - "ordinal": 5, - "sourceHash": "357681e6e42d804f722960eeeef8732b5b052faa63e9e30343b0ce9007005768", - "targetHash": "6f707239dafc252e4194421f344ead08c03e7600efc08da7138a3011285c712c" - }, - { - "ordinal": 6, - "sourceHash": "e49798a40cb8b13ff6773073397a318a21e0bf1377c6626dcb52f0d0dffb12c7", - "targetHash": "54d5f693ea07a0cc986c422d463ce2630b3944b65e9f48dc7bad2268b8477b0b" - }, - { - "ordinal": 7, - "sourceHash": "6e973c36089850c8e3825c98e606a7fd2478bf31ad160f14ab3cc8a5bc7190ec", - "targetHash": "830f24ed78a6178f864b21c4382c777d4b584f754c4040a62980f1142cc347e9" - }, - { - "ordinal": 8, - "sourceHash": "35029df979fea84e4c4c21691c32bb5d52bd2bb0694d7b66bfdcfc4330d08bca", - "targetHash": "de628dddce646380f858186a822e5cf0f6dec0b9b81a13b3e3567e2f8b2ca8d8" - }, - { - "ordinal": 9, - "sourceHash": "efa3f684a3deb795b6859bb7bbb45378f93375ca97b48a9eac2bf112ec4c9b45", - "targetHash": "efb6880f1350a328c366a5f3476e3614b3c2cfb94200a6bebafb7d73d10f6a2e" - }, - { - "ordinal": 10, - "sourceHash": "36132fa3b63f3460abdb38ffba3fa44c161e713f1778bc7098b5035f0d0d4979", - "targetHash": "76828e0fe061b761c00c0afee82e308909dc0a93a5dc7fc75218d37362c2b61b" - } - ] - } - }, - { - "id": "csharp-standard-2", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-2", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 2, - "sourceHash": "cd7faf5c94f1eaf2ce951777b9dbc7220c57528b38bfe38f1b47ae1cb18470ec", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "2a1db15f2cf52f0f95bc16796ed368d13d5838d938507cc3ff64e3e1233d4aeb", - "targetHash": "c03ed48491913faf71c543a24a31ffca134b16b52e0474d4e89d7e6e14477ead" - }, - { - "ordinal": 2, - "sourceHash": "bdf2562bd82aeca96c2e749eae7385269480302e400cf043a29caed25ab7a013", - "targetHash": "7033c5e9966f88a09eef43b70046fcaba63af49c2d66f2c555172631ffbb0483" - }, - { - "ordinal": 3, - "sourceHash": "b8ec48555607bc6202126c5db642f11cf898151fb6f2aa19d2e28aea19d7e532", - "targetHash": "b8ec48555607bc6202126c5db642f11cf898151fb6f2aa19d2e28aea19d7e532" - }, - { - "ordinal": 4, - "sourceHash": "8c142212a767f020c0c49c9fa73da04642b8a45cc773ce37b88c16f5b12135be", - "targetHash": "9bd93d6d6eddb2c2c5f3dcdabf0cea833ca4a75ae0d1db7c7811d2ada13c5a17" - }, - { - "ordinal": 5, - "sourceHash": "53f170c754c5ea5453b8cb79d9019b84a7fb5939925733b1a510b0eb7cdbb890", - "targetHash": "d0bf6bef623f2c3066f21253b127d345da2bb450060e83cbe718209afc8dbe99" - }, - { - "ordinal": 6, - "sourceHash": "f2387cfd9284c5446d0273c02585de39adb41f5a87724febef62afaff75e7f80", - "targetHash": "56d0aaa53ebcc644f9ff8e3084a166d11bab6d2d309f039f6d2845eec14c08d5" - }, - { - "ordinal": 7, - "sourceHash": "b836ebbeb1d666671b5b0828c56021c81ee90969fe7cfabbf2a1864dd60a8142", - "targetHash": "8ff1928b68a5ea3677710c81ba93f0d11865b2a89e4033debaaee5eedea8998d" - }, - { - "ordinal": 8, - "sourceHash": "797dd7a782adab46721f3bafbad4449d81309d115bad776e8dcfe4245a68f91b", - "targetHash": "918169dc34a2e6b2624075a83435d358d9e647db5c6a49afb18c74dd1138fa30" - }, - { - "ordinal": 9, - "sourceHash": "6fe5493740a39c129e316e6b968189f6a0fca8e9eaeb33f67f87363162772025", - "targetHash": "516b102cbcd19e64756bad14c8f563fbdee107f8603527b1a32fac07a90781a0" - }, - { - "ordinal": 10, - "sourceHash": "21b1cc15fb6a6b576235cf883e1c564c05d1bb3cbc8dc4521b5a197cf1da9c92", - "targetHash": "948e70960b87fad036e3c3cc3bd3be41ef6483e5d6700881294c16057f3e003e" - }, - { - "ordinal": 11, - "sourceHash": "6138673c0e4ba945c4e799b186de33e5a3fbaf717b943b50f09bab13a92b3ce1", - "targetHash": "507463a0be7e145d3f1c01bdc6e848ba6aba319421cd7348f0638211896c5e68" - }, - { - "ordinal": 12, - "sourceHash": "f3605ef5c893175dea12dc1d5fec5be85610daa8dff0216a97141fb38237f3e4", - "targetHash": "b780ea7e5182b22d9f876df497d2b7bd18c9352e3204e88572905ffd8a352666" - }, - { - "ordinal": 13, - "sourceHash": "f664f1d02435ef0cc33073dc7e99243f89fa35f277f14670d35d1d1fa60652bd", - "targetHash": "326a3d166f7f239af5e4343769a8bd7cdc16df6eaba52a089ed215e726ead1f4" - } - ] - } - }, - { - "id": "csharp-standard-3", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-3", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 3, - "sourceHash": "75f0a926f0b06b60c211588ca953b239d229e9967fcca8f7cc8a27be8091a3e7", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1c05e9d5a84367951b498cf424b39205dc042ca24765082f22c146b3cd2e0f5e", - "targetHash": "085917a9e331374bdbffe0ab1b23a54a59b4a786efbd15cb1e6211b58ae5e819" - }, - { - "ordinal": 2, - "sourceHash": "b7fac7e1f5d412eb64b7953d09480a04c5ce1e256a675068988567fb44008f2b", - "targetHash": "4eb75ae22ebc4298fd09b3b02348405d6a87de46539040119f92bf9e32025676" - } - ] - } - }, - { - "id": "csharp-standard-4", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-4", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 4, - "sourceHash": "30b69ca4a4f4788914691f57fbf66ea5f84a89b41b4d123b57f3c294e926deb8", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0e76f3ec6ab88ecacea8579a89e848cac5555e3d7b546b734c8a20628db371ce", - "targetHash": "4a2da7db79ead93d57d95876f924519b97cd1cff017efa8aff275b8024f8e034" - }, - { - "ordinal": 2, - "sourceHash": "2ee4f49742f6165c3cbc004f70d87949fba5945273f77a4257992799bae9ff3d", - "targetHash": "24a130c6bd5708b80471b734547ee13a8384ec0da55c2e130e750a6b8e2333f8" - }, - { - "ordinal": 3, - "sourceHash": "7b781b0b3e782bf4608ac199db45d88f618981d240b45e0c85d94357c52dd401", - "targetHash": "c3143d67c5398ea03b77854dc74b687f15c3a0840f7c2f85433dd035ff4e9bcc" - }, - { - "ordinal": 4, - "sourceHash": "ec46d88bee70f83eb0dc91ce75626ee524818848362c23cd4a48f318b96ec0de", - "targetHash": "7243e5afe7052dc0ffa66bb70f6a022f0a7979fced37c737e47b754ae4602997" - }, - { - "ordinal": 5, - "sourceHash": "7b401a21c5881f5e4633f28ed91ef6ebbc3f6a90fb11de9c49d4d6a54cc867d0", - "targetHash": "382cbf673499ba493964ec4d57a581dab6fdad314136a81da37ef4a355655aee" - }, - { - "ordinal": 6, - "sourceHash": "3efb123634905ffca53f8592c946d99019a174281756210be994ba742c6adb19", - "targetHash": "6551c78cd40bda9a80cd187bfe51a45cb00adc39cba8029ce0a9965a5f027b91" - }, - { - "ordinal": 7, - "sourceHash": "274a3245c966d81da7150fb9cd7810a513ea70eb0239d0ea8a27669c752d11a5", - "targetHash": "ce05cd5e1e3172c2ad00e82cdd7851d56ba1f89370c557651b8b9016f164d09a" - }, - { - "ordinal": 8, - "sourceHash": "603ccd47e936b6aded57cc5163f0905d06bff9a8ac7f683caf5bb9c70e8d6ce7", - "targetHash": "8bffc74725c719931ade1768d30efaed8656cbb09aec835d951a61bfe8bb5efe" - }, - { - "ordinal": 9, - "sourceHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b", - "targetHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b" - }, - { - "ordinal": 10, - "sourceHash": "f622329f717c750ffc8fe0c409c66fa73310880df12ffbe59e4c61894c82f979", - "targetHash": "f622329f717c750ffc8fe0c409c66fa73310880df12ffbe59e4c61894c82f979" - }, - { - "ordinal": 11, - "sourceHash": "914a3311bff3058d48f38512053c30becd2c879d3fce2c49685b0860271b0957", - "targetHash": "914a3311bff3058d48f38512053c30becd2c879d3fce2c49685b0860271b0957" - }, - { - "ordinal": 12, - "sourceHash": "d10cd75e7bd08a8208c43ce168bebe074524bbffe48afc9d71dde27c2e493403", - "targetHash": "d10cd75e7bd08a8208c43ce168bebe074524bbffe48afc9d71dde27c2e493403" - }, - { - "ordinal": 13, - "sourceHash": "021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96", - "targetHash": "021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96" - }, - { - "ordinal": 14, - "sourceHash": "0ac850e1c2f83e6715c147d174c7a1cf26eda3641174777c64df44750429116a", - "targetHash": "0ac850e1c2f83e6715c147d174c7a1cf26eda3641174777c64df44750429116a" - }, - { - "ordinal": 15, - "sourceHash": "72228e1f698045d5aeeb03d7bfc662ab8dc7fb72d9aa4886b289c16f48dd0dc3", - "targetHash": "72228e1f698045d5aeeb03d7bfc662ab8dc7fb72d9aa4886b289c16f48dd0dc3" - }, - { - "ordinal": 16, - "sourceHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b", - "targetHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b" - }, - { - "ordinal": 17, - "sourceHash": "d90b324832055af883f20cc746cf7b7f5058bb4e8da84be3d4d21110df0be2f2", - "targetHash": "d90b324832055af883f20cc746cf7b7f5058bb4e8da84be3d4d21110df0be2f2" - }, - { - "ordinal": 18, - "sourceHash": "e4f59d270c7614ec7acd35091e519264454f5fa7b53f83e87f8646d59095736a", - "targetHash": "e4f59d270c7614ec7acd35091e519264454f5fa7b53f83e87f8646d59095736a" - }, - { - "ordinal": 19, - "sourceHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54", - "targetHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54" - }, - { - "ordinal": 20, - "sourceHash": "263d2b59db8ede9334d008264c0886d9038cc330bdc872c4e92300d558ec3df5", - "targetHash": "263d2b59db8ede9334d008264c0886d9038cc330bdc872c4e92300d558ec3df5" - }, - { - "ordinal": 21, - "sourceHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7", - "targetHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7" - }, - { - "ordinal": 22, - "sourceHash": "28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af", - "targetHash": "28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af" - }, - { - "ordinal": 23, - "sourceHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2", - "targetHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2" - }, - { - "ordinal": 24, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - } - ] - } - }, - { - "id": "csharp-standard-5", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-5", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 5, - "sourceHash": "ace556d3813740e6a4e788f488e34cb5fc4442a4b15f50db0349e7effaffc237", - "approvedAddition": { - "approval": "User request on 2026-11-08: prohibit global:: in handwritten C# and record the rule in coding.md.", - "hash": "11daf5b535242c204be26f40eebc86a38ae7449501f035ab867d8d5416cce465", - "translation": { - "language": "en", - "source": "a31375a5f01a9523edce97b54a0055fdde92c067:.agents/rulebook/coding.md", - "approval": "User-approved English modernization; original addition obligation unchanged", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "11daf5b535242c204be26f40eebc86a38ae7449501f035ab867d8d5416cce465", - "targetHash": "650503dd2742a9729f9656bce96b02aa7be14c4cd444e1ec66980b112cec23e6" - } - ] - } - }, - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "fbdca3db6661bced81495cda5ab5cbae231a4b5bf041af1e5e5db5db097bcf51", - "targetHash": "1d66628f237692fd7eb91aa99b97689102ec1e66f351fbb47239255603c2ba22" - }, - { - "ordinal": 2, - "sourceHash": "fc3d8f40ca5efadb2e73ba60e9fa39d574e9e5ca26f5ba3bd5a3bf632bb8e9be", - "targetHash": "6febeef0a913a94c550bd0adc41f2319ad1b81cdc9a9f9484a69607679731f01" - }, - { - "ordinal": 3, - "sourceHash": "17689d3c29320cec885899230bf2de2bb068e4b999dd65a6a71f73cb56c27b95", - "targetHash": "a2da9948d1f1df8239206ffd810b15b5d281518b56270f6789431e7907d286bd" - }, - { - "ordinal": 4, - "sourceHash": "609c51fe9f58dfc022b8b46ccb07d81ff7b50198fbd437d6d5264a992dee2e8d", - "targetHash": "8c4ad7175c28810e07380f44f456cbdaf70d3a0ffbc67c7dc46814570b963f64" - }, - { - "ordinal": 5, - "sourceHash": "9a10ed4f1319e1f1c9e5f49254d8543c84b4a88ea1eb56d24ec09085cee00bb5", - "targetHash": "cac9e75375e991ba6f79925bd252e37a77e23f64349d7438ad732e8aa75441b2" - } - ] - } - }, - { - "id": "csharp-standard-6", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-6", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 6, - "sourceHash": "9513894db97113c26aa081c3cd9d382cdf0ee4676d5c15cb127e0c54103d6194", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "28df84f81a5dfe455793038b671cb6954bda75c1ba6c3db0f4fe70c099f0be9a", - "targetHash": "dbfc49026f38704b938dfa5e4ee6d27265d8d0d3c5949e11cb1fc88e11e634fd" - }, - { - "ordinal": 2, - "sourceHash": "808fef544f6eeb0692319a5307f51c9e3d94da9a0e44f481cd7a9d16b8977410", - "targetHash": "5fd8e3d6275ee4949ad3fddf759091bb26f7934569be267ad0e9bc4915ff21b4" - }, - { - "ordinal": 3, - "sourceHash": "8280fb67fa4af7ea095815754ead7fa4bad07e0c3729b1ed0f9321ea5cd0356a", - "targetHash": "508202489b9d14acb588f15af344c6cc8e321dd6614c6892df8db70ec1a5edd5" - }, - { - "ordinal": 4, - "sourceHash": "39192fce16e032f167aee1ed11ad7dec675f603262a30f8147b1a82a5016553c", - "targetHash": "c85850ef42775ee52c6317810c7c4f632f88d9e4da7b7918f10fc5346438d924" - }, - { - "ordinal": 5, - "sourceHash": "3bea06883794548590673be3eed3dd909fef101220e5e3dc0ace842b07ac71a9", - "targetHash": "9e7e606d78a67bd8faaaaa0107c0bf3aa011dccbbb0797def4b8c429974f52bd" - }, - { - "ordinal": 6, - "sourceHash": "b094db2f3bc93173e6e7a9c067a5d34538d49bec0c02917dde5f0053d6a24e6f", - "targetHash": "b375e2dce7a8d47cc7f5eba34fe45329f01d66abc7c950910c5fe4663bf892eb" - }, - { - "ordinal": 7, - "sourceHash": "7e3eecabc11656d7e5abfc6dc3011b78a1ac5f14fc012cccd8f4e30f6cc411fc", - "targetHash": "8e83f08594761e24aea8de252a64d011c5a80b5cfd2bbfbdfd63950f1bb52631" - }, - { - "ordinal": 8, - "sourceHash": "cedc1d7fcc2fec17fbc1e0b3bad7a1f563457dddf5c6e838b339c69846ea48b2", - "targetHash": "6e1d70097b436467ad7b11e9c030a1c66e44341e42424f1a1122ad39456a1b3d" - } - ] - } - }, - { - "id": "csharp-standard-7", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-7", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 7, - "sourceHash": "d2f70bc4ab9ed29686da1c043ffd9630fc160b4ad5259a2dc48ea698e90b56c7", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a0be6f683d72d53b7dbdb50f1ea58c120ae27921bab335e18dc4f0cf2a0ae759", - "targetHash": "20b6887d47f797c8cda7f622c4eb5ed19cd240fc6b5a010993024525911fb2eb" - }, - { - "ordinal": 2, - "sourceHash": "439ae488bcad7c90069d1ba1573168d46b2bbd3db295423faa4526dd316114fb", - "targetHash": "9e9a4898d4cabe4380e34343c28a1952c39d28d1a0d91adc874d96be9a323ba7" - }, - { - "ordinal": 3, - "sourceHash": "895935c86d3690478a0b128d60d8c75beeaa42b5ae0a90f9f2611293ae16b5ac", - "targetHash": "6172e1fc7d4ffd1f8824660c37c26c3eb5e5b4f5217b9b59e42af22d0d0b033d" - }, - { - "ordinal": 4, - "sourceHash": "543a61005388c162a545099c929ce8cc0bfb8f57dddfb6db3a5629009ee0c4ab", - "targetHash": "30c3fcad6f1d5853aaafea7b6bb38938613b1079cd89d04e401bc74e371fa4f4" - }, - { - "ordinal": 5, - "sourceHash": "af90858955c2025436dea38d3968a317354062610603afcea883900f13b00671", - "targetHash": "f86f503a20af95d32ed0a1c1cfd2c1ec38de12a517287269669a92fdb41381ed" - }, - { - "ordinal": 6, - "sourceHash": "d86060325fb1e93c57affac20326b65e3a7b7bae570d0768322fecba214c7d76", - "targetHash": "978dbe01188d211a623edaab5207e0b392ce678db45f0a3cd99820dac69d456c" - } - ] - } - }, - { - "id": "csharp-standard-8", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-8", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 8, - "sourceHash": "d59caf636e6d1a2614a542203c5d2e502d47299ad9b434c12083afa1642b0020", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5a3060e58c3176f0ad032bcf05c2a61a6e6a1100771e62224af05cdba9a9c35d", - "targetHash": "97a965239f9b9cb2d4a2928ad1266593ea14dd80ffd7c6cf72ad08bd752f9812" - }, - { - "ordinal": 2, - "sourceHash": "820e84a3e882c755dfef876948ca415d23dab182a0ed8bdb8780bb9af5985322", - "targetHash": "c4b93d73d5f678510d0b71a9e0aa6c132047d2a659603d56c710c7008c9266e7" - }, - { - "ordinal": 3, - "sourceHash": "e4031dca31bf985203ae2dc7eb0be455441aa84a163bcdfaa4fa80cc849d7ce8", - "targetHash": "71ee4ef1f14d78af5b5d1dd0dc818e0e810fd2303c27146d8b504a47847aa075" - }, - { - "ordinal": 4, - "sourceHash": "8a23e7a0fc35d7915d1dee1d92499e98b1d625fed50dde8907e0f1db41b98146", - "targetHash": "cb94773c52926d4a30066f41eebf25a52db646ab74384e3d673a7fe5269d9a2d" - }, - { - "ordinal": 5, - "sourceHash": "cee15864cd70f7788fcf2fc10b2992d12538c0738963d2ee7d39b0dc03c38751", - "targetHash": "56585f625eade9a3997dfd2cd253202e1074fb7a07da09ea9ceb5f7db3b99481" - }, - { - "ordinal": 6, - "sourceHash": "4aa10716eaa5a957775b3381cd6c89235bd9d93bbc44889b797388f7f947e362", - "targetHash": "42a086ec659e97e860628d94db20f02bc6ca99bd7e146a7fd97f465bb538dc9d" - }, - { - "ordinal": 7, - "sourceHash": "1917b9a45ffbb5a811b8fc2c0bd8d175000437f4abe2fb023ee5c7978fa74fa9", - "targetHash": "ecc11744af3860cf39bfdd0445ab85bd6a08d1a7e36bdabf1732ebd787f95d89" - } - ] - } - }, - { - "id": "csharp-standard-9", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-9", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 9, - "sourceHash": "264a7aa49566628811332c607f0a852dfa14135e8319c3945e20e8f7bd7f1425", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "46701af87ced263bc9ba88b638e831be8ab548a125880e9da94da358420927ff", - "targetHash": "374d39163bb3453b09ef9a8aff3458c199626c053c37cc4bd7d1118996553dfd" - }, - { - "ordinal": 2, - "sourceHash": "09bb496a44962878b1968f10d1c2ffd7b1ae2180a179e310511f7e126d32ffb9", - "targetHash": "245170dac1c6e605793a3e5f1a0f783c7da5e7b3dc7911bdb4af8a1c3e5ff2d2" - }, - { - "ordinal": 3, - "sourceHash": "d6d85ea546d42ff6228e5eae5091f92f53430e4d226d2a2c710b25e2ca89ec40", - "targetHash": "f2cf8678e0d35bb701ae3de1abff76f47b3a8a1a4103697a8b0b6fbea1424bc3" - }, - { - "ordinal": 4, - "sourceHash": "dd9c8dbb7c46aa487e28832506b06a9d60d935bf168752a6d7b614cb4411bddf", - "targetHash": "0511a208309a0ada60d6a1f824d360043b4f06a2d1b3d282e69936a4e8e95726" - }, - { - "ordinal": 5, - "sourceHash": "6b1d171d2c1a30f944d6761a9f7c704e648aa5695d6693904c7d66cfd54a979f", - "targetHash": "ac9ffd7becab6e3b5f8f1387c411d716f80fbfa855b37d300aa8058ee1d9f734" - } - ] - } - }, - { - "id": "csharp-standard-10", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-10", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 10, - "sourceHash": "8e9915979f7d691ef5b067c80bcbf944331135f4d4073e1e90db7fd6b5cddbce", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "8727ea6ef780080d7aaf1e686b97ae9c27cbc77c6738bf40b3dc90734f08499a", - "targetHash": "2414828088d78c4c1db1edcc3f14b4d337ee3775544a8d52b5572e9dbcdc16a7" - }, - { - "ordinal": 2, - "sourceHash": "6bf5070507e2c81f797dca6bbdc175dc084fb3dff82f4904e5690b352bef406a", - "targetHash": "3ddf6d9facb84fe0e55c53e7efdbfb68f49aa7196e95ee1926be2afab2aa4f0a" - }, - { - "ordinal": 3, - "sourceHash": "9d95106a201cd6f93d7038e125693d3d332b7f3a9e43ddb13dd7382ed19359bd", - "targetHash": "16a31eb9f1c0d61bb7da2f3f559bc8476b226ec5f56ef0ce62c522dcf044760a" - }, - { - "ordinal": 4, - "sourceHash": "cbf14ae59bb4d7d1af66ed784d042431cf68249374af00b5a27e944c615fc8a2", - "targetHash": "9e967b6413a72ea84ab0916612ae5a774159301d92f7621a2ebe143d1c8dd793" - }, - { - "ordinal": 5, - "sourceHash": "3a058cc62e35dc737f7064017cdf2be132ea48e2e890540a62e22883d2ff0552", - "targetHash": "3fb2d4c98b5b1a933d87dec7fc5640eeb61d21ead07b183d2724e80b4dbaa66c" - }, - { - "ordinal": 6, - "sourceHash": "6a1aa914078b5971014d6d53a29225406e536c34075e6c38f8fa5ea664712f9f", - "targetHash": "ffd3073f7bb56d6e85c581ef3f1324bbfc28e05e738356b10532a372b15e7130" - } - ] - } - }, - { - "id": "csharp-standard-11", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-11", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 11, - "sourceHash": "594831b9bba1df40656233274f526cd7462d02baef33d61b47a401ca3b77cf42", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c390f8074d8045a88ec9c80245ad8917901d74200e1e0ac86d29314aeda5bae5", - "targetHash": "6c24e27d56a00fecffe47a3438882019ed6257cb69e7e45adec87e3ec61f545d" - }, - { - "ordinal": 2, - "sourceHash": "a82d7df0d23579b739375a0ebb94c728f1c9e52fe70a28993cc9b1cbec588dbd", - "targetHash": "94b519aa68b716ba1a3cb0245777b6f9cd6bd493b714276b74233243af170509" - }, - { - "ordinal": 3, - "sourceHash": "78f38c229d8a58637157daa7e1e9495f2c5370725b207e80990992a830ab2d78", - "targetHash": "836785d545bb812a24c82f0782178d41aba1012a1eaac86af97d5beeefa9cf10" - }, - { - "ordinal": 4, - "sourceHash": "4d7bfdea52a075ad764ad61e829998d15cb043024df34a553588139cf220f614", - "targetHash": "493ed144d74bd63118eeb76ee47011d562e6fa31b7dc8661d92e797060539a81" - }, - { - "ordinal": 5, - "sourceHash": "1abf05950ed4306d0f04641f8440751c8ce59124b7a985559eb4fb27df47d360", - "targetHash": "b0eb9b00dd364555cd55569bce2b769ba5918a225284ae93a904f48f14f4900c" - } - ] - } - }, - { - "id": "csharp-standard-12", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-12", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 12, - "sourceHash": "ec9f401d7f7c23a50e563ee86d16a3a852ddb58c3c595ba4b6be4619650627f4", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "67a8e3894c349182da7fb29e4abf36e61b9c93819ab04d5200faec4d5855a8b7", - "targetHash": "7dee3f6b7aa992240115ac1f48c28f2cf3602e483345d3c341bda23e443db508" - }, - { - "ordinal": 2, - "sourceHash": "22d9b218bba744ff2523a49dc07bec67e477329787f5bd09541188302a191b00", - "targetHash": "2bc40cffd8c5cbfc1ee12d7bd57fd2d2dd148b4d3e7629a388960a73a701a146" - }, - { - "ordinal": 3, - "sourceHash": "a9908bebb4829633ed2362e2542a418a8c3653f6b1903416d949e79e3039dcca", - "targetHash": "0179901db9208077def1353dd6f20501968fca7a2ef4c5b9b6b74ff18926be2a" - }, - { - "ordinal": 4, - "sourceHash": "d2b82519aca9fdb58ccb243cc529de4007ff9d2974258306d39614c10d2b765b", - "targetHash": "89a0be93616b990368b9b70310ecfeee95829843e488f281c5dbb78c20874883" - }, - { - "ordinal": 5, - "sourceHash": "c68852cc4067cac36b6b87a5f9aff6ef036ab886916a9bb4ff2f0cbc9c8728af", - "targetHash": "e7362ad4e73f04dd63d35bc01d358e3684e7a70a7fd058822e6fd28b395af24b" - }, - { - "ordinal": 6, - "sourceHash": "76fc467dc8eade03577e3a109c96302a5f77b5c2933c44bdc3371d429d31f5ca", - "targetHash": "b2e3c0757d797d93b4d779037d211b10eb4f7abdae9e807d9566efdea5a6c215" - }, - { - "ordinal": 7, - "sourceHash": "9acba233e90d643b858cc8e6830fb17437888a1af533b51859584817b8ce8eaa", - "targetHash": "39e8ce468554d0e68d510364db43502aadf1df6fdfac109faa2bf7932c859cf9" - }, - { - "ordinal": 8, - "sourceHash": "33e0aed50227158e1f6a8aec7a1fd8b49c9dadf0209d7a87113402edb25b3674", - "targetHash": "bf09a964b4030f20eb08d660514796ed4134477001ab149845ecc4804fdac696" - }, - { - "ordinal": 9, - "sourceHash": "af73502abd2e29fd481d7b17de471abeed43dd517b649126994301d5be6df770", - "targetHash": "947326cd21100e3a028a48637d83b38a41e746521a2e82720a8b77c57d688112" - } - ] - } - }, - { - "id": "csharp-standard-13", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-13", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 13, - "sourceHash": "b52fbd3c7d57be9738c521c668ba64a2493bc01d6b44c8100f9d3fd75a8b08d4", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "d75b96d35705577c153ef7e83211a9e108cb6b23b349d2c3214af1eddb0620e2", - "targetHash": "029ff0cbfc2449fbf83e64b5417e96fa07ef32576eb5c2107c5c66679fe78112" - }, - { - "ordinal": 2, - "sourceHash": "ed9d423a413c1b8457d9c1fb5632a4df807e941b8a25c1e4e401429b7e05f242", - "targetHash": "e4bbf6abd499436019554d319f4b0834fb4b2eba164893b6c6f12a53713b5360" - }, - { - "ordinal": 3, - "sourceHash": "197344a969f727c21e8e0593ba064020bc18ca030a1a46ce90d3c60287cf09b4", - "targetHash": "866d72c6ce11cc5b02052ac52ee11b6010cc8133e37a15641152aeffad55106f" - } - ] - } - }, - { - "id": "documentation-standard-0", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-0", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 0, - "sourceHash": "2b3f30679024db5d9b1d07ff1086179e79654d12aeb7d585f9101d857c7c5cd5", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "d40f3ce7191cebf3bc675fb594a4d8b0d29a638d2e3382dd7d0e48a1d2741b90", - "targetHash": "bfb5d3ff9b354b0c01a9916b2cb23dcdedc0b077c6b0d8dffed2e5e906d3a8f3" - }, - { - "ordinal": 2, - "sourceHash": "c14e2113564984dc2fd1f306c11ca7e8eea93037ba33f2798edcf342c142bf51", - "targetHash": "dda0f207813397cbcdea5e62ef2cd2b77966ef0dffe4e57ecaf350d2808a57b9" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-1", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-1", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 1, - "sourceHash": "6b05a0ec83b508519b83132ffd74c35db7f53ebd1d955367afd966333a3e9c30", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1490aa516834dc13b8bcbff59e07e23e8800a65f5823162c78be02baadf71534", - "targetHash": "086594ddf0a6b3e662adbe5773987abd6fc5575bface84163f26fd0e9b1f2ab6" - }, - { - "ordinal": 2, - "sourceHash": "3ad78594488a55898157dd4797129137e2d9490d878880ac4ab400db68dc1b2c", - "targetHash": "25268c99b4275a51af3324a645d483d8bbd0dedd5c810415914d7ed2b2eec177" - }, - { - "ordinal": 3, - "sourceHash": "b0821299063f116b6132c9ee23659cba0b6f3254f9104e69e33cf9677e07203d", - "targetHash": "e1af2f77ce196b8f5a834d718bbc3f9d88fb453093a3af100638f904cfb5a213" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-2", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-2", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 2, - "sourceHash": "652d09619bf30978b0061ed778331dd33c9154f3ce49c509f05b128e6fd909fa", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved named API authors, editable description overrides and tool-maintained contracts (2026-11-16)", - "review": ".agents/records/decisions/API_AUTHOR_METADATA_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c75987175eb7af167bb6d11e6ff2694bdaa7e8b0de11cb2c8c4244fd129cd12f", - "targetHash": "2ea15628c7ef541beceed02a0f14c90aed483d196a1d3578f6823c1756abcdac" - }, - { - "ordinal": 2, - "sourceHash": "136d19292806db2f5054d6c1bd11df0679805d5c21fd298c3815a20498a801bf", - "targetHash": "176898b6017d0a25a8e4a64a6c03d4072bf6c4b1d5a4455945606435dba7eaf2" - }, - { - "ordinal": 3, - "sourceHash": "3b0b7137ff392ff0bf8bd7d13053824b6d85875abc0d96b90518329f42bc5a8d", - "targetHash": "8af5f7bad6857a615a9093d57f808ef733dfa4f39fae7b13284a926035759c84" - }, - { - "ordinal": 4, - "sourceHash": "9e87bff673c6b685be8d82a195390ebaaed9455c58fe9e215c1c0ec736653930", - "targetHash": "7422c46f261edc4d8da8e4ae471f53322d791f6bbf8bb2fbe9f0917cfd085944" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-3", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-3", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 3, - "sourceHash": "d50017b48c0e71a1ce5f026d029ffb6ee93a88d8d018a5f002118d88aa00314c", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "32ca6ef85f16922dea70bd0df1c91600b78c3f3b25d6ba933c480a3f7660b64a", - "targetHash": "0d19ab46319785768005536313f02bd3b9b779aaed82eeac5bf7a7f796ad3ef1" - }, - { - "ordinal": 2, - "sourceHash": "b3c3173b9e01c60896c1d8663b98cfe7912069446dd380db236e5a0f56be743d", - "targetHash": "fe81134cac575566520515b6a628b674e81ad37d4444b8ea9520b158c804cb0b" - }, - { - "ordinal": 3, - "sourceHash": "aaa9eb0ee1c76bec522e75eb80314defee804c0ec89088a73b0fce1c0bf9b9ae", - "targetHash": "82f4a2988289b8be37d30fd4962f80666458697ad5f5e82f98d6abae24266ff3" - }, - { - "ordinal": 4, - "sourceHash": "7eb1b49b258e57073a3bef9842e0ec5335e5aaa38778b3b4c76cb0f9a7770af7", - "targetHash": "e3339f0925f02590dd58073983a32a6af2284a7a95f9e4d69f7f2b0b106392ad" - }, - { - "ordinal": 5, - "sourceHash": "0bbd408781d09bfc0d64c6f2a6df025088bae87dbd29ddb62361b6950f17b73a", - "targetHash": "34dfc71a9367f078b9002bfd06eb995d65163794c66949947e08512052c0d6e7" - }, - { - "ordinal": 6, - "sourceHash": "ca0d12775c803373493ae4a660f8a9bc2e270f87ee07dc3aae8c5b11012e1948", - "targetHash": "682c848319352ffed13444f5f62ba034c7d635a0109a0b1fdc3d87819589bb91" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-4", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-4", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 4, - "sourceHash": "b4e203ad58328e392684d984491729c023a8643bb8daf527e3c1431dfa495196", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "582f4d8d820f9789c0759812e43f499e78d55389cee09ec843a3760f6aed5cb5", - "targetHash": "793761fe962922ec048d78b5f4d412834858b2891394a7084d7136587afeaab1" - }, - { - "ordinal": 2, - "sourceHash": "82d25bfdf970603898c23530491d9ac39565466989ebe6100984e1033f9249a3", - "targetHash": "de748bade3a4c1bf762baab60b169a655241d9e6c17c4037d8bc6e331ea10fbd" - }, - { - "ordinal": 3, - "sourceHash": "b8ce7eb8b2e27687c7efb77ed24f530c539b8fde25d71d0f42d1a395eaf45cb3", - "targetHash": "43aa30aea59b4f89b0abd187ff612529af822af3aafb1d91e1772cb840146f72" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-5", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-5", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 5, - "sourceHash": "d17e16a584ffa310b40873a100b302ae616e77495c262be03a8d6c9a14565b66", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "11202eb25b2d933c909c1e250f7f0c27c8984ed7eb906cec3a7ea1fe48521f38", - "targetHash": "7a1e9d36126ed9af0639496f1877a6dc30dce5af1fd2766f2c94a18f6e4e5f30" - }, - { - "ordinal": 2, - "sourceHash": "9582c6a1e89590bebf7a314b634ae5e0ad35ff98d0d750b5f68ae3e44016e448", - "targetHash": "546b13605ada9ad14e78010fe2d6dde5ad44c3007df3172ec6a51d382951f46c" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-6", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-6", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 6, - "sourceHash": "e4755ac95fa67c8079c901ee495f1f523c103f3a0f2d7bf419a9e2760367a8f2", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7d1a463d62b40dc279f0bcbb2dda6de62d2bdc39fbe1fdab514604c19afbcf46", - "targetHash": "bdb7ffe98f4ab63e001c1e5a0250358ecbe82e6b5ac71d39e91c816df99554e7" - }, - { - "ordinal": 2, - "sourceHash": "74fa08a7c5cc7a9aec4a1272ad757e830dc7f82446cf7fdb993502ae84ffcc89", - "targetHash": "f0c899a46a7abff68879c7aa0f4dd5417c90b6c2526d818131978ed15e559e69" - }, - { - "ordinal": 3, - "sourceHash": "a86daf878310539249a382b48f28d4fe3b31268843ca189c2234e597b47d7105", - "targetHash": "39b3af164ffdf99c152f46819e2419258b0d6c50d46a7cf91f7e9bed921f7735" - }, - { - "ordinal": 4, - "sourceHash": "6c7b0020590849ccd7372ced6bec75da43ab66d7cbe801784c796e42b65ed3be", - "targetHash": "a7bf7dadaa989f736b8125232199994636753916bcb00b00b4f52e2eb06ab916" - }, - { - "ordinal": 5, - "sourceHash": "572982ca2711b2329ac43f26715debbe332f66f9da0c002ad1ecbef2f4cf74c2", - "targetHash": "75b551e961d6e6b78d8396f4ebd554a7ced350b1d1c11f4b2a6f20fc544a1366" - }, - { - "ordinal": 6, - "sourceHash": "a9ca4f5ff5cefd378615f369f1872e4145ecafa56f49de0e0819da0394886a4a", - "targetHash": "f63c773829fb474f8dc34e9b7196c88ef8c65a4e8f7154a38f3e17bb30fb940d" - }, - { - "ordinal": 7, - "sourceHash": "9e6859773c8903f1faabbec92a00af4d43fbb98a75318b4a6698497aba77ea04", - "targetHash": "7930567cddc3fbbc030746f99b6e73f44a3ae3a30c1d5704215e24bbbcbc4671" - }, - { - "ordinal": 8, - "sourceHash": "5b0a1e6316db48e961ae73b98b9edae1108ef3c22bbcfded5f9160ad077e4e6b", - "targetHash": "d2a5c84282697f34e56aadfe92dd982430035cf22d664d2b2798e81cf2caf626" - }, - { - "ordinal": 9, - "sourceHash": "683c506dd23c61a8865fcc8f1fb27bbcd47b571dac371fbfc4fa52e9246581d0", - "targetHash": "4dc89cc8dbc3629f9a068baae136a9839275a2679ce40eb640bed285ea0ef365" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "editor-standard-9", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-standard-9", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "sourceSection": 9, - "sourceHash": "4c27d71eeeb375245a649934a3e280a722687d62110e88c0ca371ea607dade70", - "requires": [], - "paths": [], - "tags": [ - "editor-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5af98fc5b27946f97187c485b563377c31523556261a5d2346fb8f09a29d2799", - "targetHash": "fa23fd44069153ae245075f69cd2d116dd324260c576d5a72b8e64c4cce943cb" - }, - { - "ordinal": 2, - "sourceHash": "e717be6d5789b75e8ce9724168fb8971c064679e6bf305b4657422a6628f54b7", - "targetHash": "7fd65ebce34528e4ca1598cbff466ba08bfa9deb93776e1d733cb191b72dbea9" - }, - { - "ordinal": 3, - "sourceHash": "adeb7ebcfafb194e366c14d212168c1a5633539633a7eab2cd86d3781f4f1759", - "targetHash": "87d7b4a837c8a2dc7dd0b777f4eccdb1134d0c7ef7a8c9a0deb9866abac18e5e" - }, - { - "ordinal": 4, - "sourceHash": "eac23233cbb4786fdae140082b570cc12e764a48ef1e733700b4b1bd22759191", - "targetHash": "a2871f5a9803c9d3e0c79679ad168ba003919989ec2a89c391666dd1a17f76ee" - }, - { - "ordinal": 5, - "sourceHash": "a664f27eb75c84c851228c926669120b741f02b72d2a7453588e638cdb3d0d3b", - "targetHash": "a419dd1995ce54e54488816847bb232ce673cee425fb6d34473be2ac5419821a" - }, - { - "ordinal": 6, - "sourceHash": "26e63d5c69c966096cfbfbd0a0344fdd888ac3f0f7a952e40c339ff0b14903c9", - "targetHash": "db0b23498dfc1f364cf1a7863d16794a67af9dc33d261a57644d6084907baa60" - }, - { - "ordinal": 7, - "sourceHash": "5d9634441c3bfab383b60433d289f61c0b98f8ae0d5198e803a65646e7bc83ca", - "targetHash": "6335d97df8a916f7c17a96c968312734fedb7571c388356748251ed838c4e4db" - }, - { - "ordinal": 8, - "sourceHash": "fa5277e42773bb18e65ac6dcaaa84e3aca868f550fe1cc91c4a3f4dd35304604", - "targetHash": "efcb36d339f46b11a8300001c41a0be5ad1bfb7d0ce799f6ba825652d6ff3f00" - } - ] - } - }, - { - "id": "editor-standard-10", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-standard-10", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "sourceSection": 10, - "sourceHash": "7c051be2869f46bd2beac2d5dacfd75da8afb5b39047d02955d8c4bea5fcb475", - "requires": [], - "paths": [], - "tags": [ - "editor-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c7f0fc7ede41cbd678aa63129f224e66b66798813dbeb627b8d5445064d89d1", - "targetHash": "8c475aa3008a17c3b04e9c6bdd360b8ee1ed13fc04c2e90e4ca945ae9211b16e" - }, - { - "ordinal": 2, - "sourceHash": "27f5731a0a5e6300a028317ae933dc693e81d6a513748732dc3894f2454306ac", - "targetHash": "a74ad8c29936557f40687f1e5afcaa578a45a9f695a767af818dd764cd7776c3" - }, - { - "ordinal": 3, - "sourceHash": "cb59ebd9f3f8ceec16bcb3db3bf03ae9b3225d90e6b110ba46e11a8b0da4cf43", - "targetHash": "563026fb39be04a8a7620b98daaff86e87d2c2ffbc4003eeed2bad09d3fa0e91" - }, - { - "ordinal": 4, - "sourceHash": "a738608b6f36855f4a4e0ac506656159da8122aa195dbb035cd509bfc99ebe4f", - "targetHash": "fb974820251d971ebeae65d596af0d1fb09fa46009538ddd9a296093ad47f725" - }, - { - "ordinal": 5, - "sourceHash": "126c515920613f1a133b2d8bea796af15c7880f146e43061eb755d972e5a8cec", - "targetHash": "e23e4974bbccc05a4bde3885b3e0cb7f74ebc5d3b9c2790b5908a81b84b642da" - }, - { - "ordinal": 6, - "sourceHash": "0387b218d3e368b207621ec75610231f308a1f8635d497840f260baddb707a40", - "targetHash": "5785c31ba9c268ed8948f437a00e66f1c8242ea90cb3882fa0136f2d294dc24c" - }, - { - "ordinal": 7, - "sourceHash": "80f00da15617b31fdcec378d9e38c64a682359355b3f3a6992f1fc85c1da45f6", - "targetHash": "7c275c2732c7b1f8d3a1ccaf146cb07ed9f62cbe817d598c3aaa76692a1abfe9" - }, - { - "ordinal": 8, - "sourceHash": "1933c293314efdc4770be33e561aad8c17619280f1d022a6d8c5ae68a85bb420", - "targetHash": "45cdb5335658bc92f8c6efd9c779018cdc2c95702baf1671ca9612e2c57633ed" - }, - { - "ordinal": 9, - "sourceHash": "0c174ab5ae307ead9852705a9cef5562be2eeaa41f5d19ae1a38dcec1d0c1b15", - "targetHash": "d5d87e25f5cf3360f97dcc04cec0c8360c14149bb3959e123989c1b35ecfa72d" - }, - { - "ordinal": 10, - "sourceHash": "3219506ec257d9873272709f5f0391df074edf5faad9c5ffea530d8d408672d7", - "targetHash": "4e61230cf5c5564db81131acbbedc835f91c5dc7c5c53028aabdc381cfc20e31" - }, - { - "ordinal": 11, - "sourceHash": "3701e24bc7049221695ba62bebd6c39e0a8d8b5f88e3f8d75d6830f22df23f00", - "targetHash": "53c7cd04856398d348b8880b0ea0a86e3c4e2be3e4f5d59a57da9fe290ccc7dc" - } - ] - } - }, - { - "id": "identity-standard-12", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-12", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 12, - "sourceHash": "c04a13c50f3dfe682a2b41855e42100b349db014d40a7a06530c0b3ee4dd6779", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c5ea9f5d15d225b698f982b3db4b7d83fa4f3c8640e97f4698bf5181b2a6cda", - "targetHash": "eb11f4b9d27b79b45bb4e736120814109c26e3183d3fc2663550008271354aeb" - }, - { - "ordinal": 2, - "sourceHash": "c816a06c4a8be6d812578b6f7383cbf8dee59b91225444f8d590c9fbd7c0701e", - "targetHash": "edf62c7da90bb4ac368c0eb9aa7836ef688e87fe4121b53b2a2a5bf560f3b33a" - }, - { - "ordinal": 3, - "sourceHash": "b9d2f3b86842dae33a41867b197836afe6233c4241829e1204b3848f508dfb3d", - "targetHash": "6f06cff5253ced9abe30a33f6a2289b114867c6a1d833aacd60c9f078e9d73de" - }, - { - "ordinal": 4, - "sourceHash": "050fd62a5c1de4d1d901303d6aa89ea5555acefb49640f67e6d33f18efd8676a", - "targetHash": "2af2caa9ddee739bacb662a9da9be5808dc27cff7db5aa6d871a6c2dbee8b92a" - }, - { - "ordinal": 5, - "sourceHash": "ad4fafc213ed296ebdb6c0f7951ba5bee9c20b2d8c36e931174f69cb268754a0", - "targetHash": "77bd1af2dd50b9811ee9a43b8fa89b78214a702f05f2e05671579b287140b839" - }, - { - "ordinal": 6, - "sourceHash": "0366bdf3d76726d6b207a0895ce5cdceab1476e0716bb4f77483ae5b8c2fc6be", - "targetHash": "407623152ef87ea249c2e6a6b1d73a7594155903c6b0deabb1152d687ea00363" - }, - { - "ordinal": 7, - "sourceHash": "839ac57e01a117bf8b9f9115fcc63b68cdb48a227cf8f7da9c1da75c1b6bc792", - "targetHash": "b1be478f727cbb95f56154f35988d3c1bdff3bd8052bc2b4e49dc5fd73f81316" - }, - { - "ordinal": 8, - "sourceHash": "23292ba0a0bd516469687f53b6cbf8a084e1e894da78103eecd697ddef20d0f2", - "targetHash": "32c267afbe380e5b790d4262e221dfdf60b96b49e74d7a2e2cc9ac897c0880a5" - }, - { - "ordinal": 9, - "sourceHash": "0ca89e6798245ba4d58d1ddafbdefae6dfa475a5ec3ae0731e85a2614ab1428e", - "targetHash": "c98316cffcb8d38ebffb7f3fa83931223dd430e36623c0b2eb5084c3bed2ceec" - }, - { - "ordinal": 10, - "sourceHash": "4a9430fac11ba3904d0df22cfe6d6236ffa3e75c17d4580529d5309b43221412", - "targetHash": "d1a826dba8450aa3875725dd824cfc603b648142da6156c6f754f3930eb970d1" - }, - { - "ordinal": 11, - "sourceHash": "425536a1d8ec21ca9166d6d955545547c278c57c1b856ee726fef42f2dcba724", - "targetHash": "cf51c14d13ee05e86fcfa183611564a97ea7e62bc736671feec8dbc2bb9f234c" - }, - { - "ordinal": 12, - "sourceHash": "b2ae179032fdd003eeec23502dde2fe85b0ec8c940cdf3325d9d2011f1996d39", - "targetHash": "f0cda63fca605ec854c588ad13773864383df3bdb7fa3615acc7a652401b288c" - }, - { - "ordinal": 13, - "sourceHash": "30cd85d0831091e93eeecae70e77f41fa71b5d51e10d7ba09e5f3d137f4e35c0", - "targetHash": "e0cb3f486f36dafdaa1af82c873edabc66594166cf01222174212c225e9870c6" - }, - { - "ordinal": 14, - "sourceHash": "8965297f5daa9c1ed2ddb4ea9da55733de7e760843f0ead75acf3ee5ed96dff3", - "targetHash": "feb7abcfe22b598e3403569e7da1b986a91255b421645cc68b2ce721e56c1097" - }, - { - "ordinal": 15, - "sourceHash": "5ad2da98723f1a021b09ae6b718fa20466a9a4562f3441bf085156641d69302a", - "targetHash": "2f91feccc5de9a2f71268e187151f6141ccf2fbfffab0f3f1a1aa3df89e47688" - } - ] - } - }, - { - "id": "identity-standard-13", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-13", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 13, - "sourceHash": "52493148de955847cbea6609f0c895bfdefe5008ba5cbd50a6283a5664cac692", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "2d5d7e2789f297edbf3431970c66f4895d44a6ba990657615c61668b3e3c3230", - "targetHash": "4a9909a8648625c07cc29fca118c1eb68e2ebd471093d018537ab1a77dcf1ada" - }, - { - "ordinal": 2, - "sourceHash": "121c3630353bfa5ef6e5eec92867689bcf301155caa15d5d7d3a0def0cdf0c83", - "targetHash": "121c3630353bfa5ef6e5eec92867689bcf301155caa15d5d7d3a0def0cdf0c83" - }, - { - "ordinal": 3, - "sourceHash": "7f4691ce35276b1ab3344d5fafd462bef2c1168e87b5ce2f658212c5e3c46764", - "targetHash": "e84459a6b63dfd8935786b6d6ac2d3d46231268b78721514ce19a34b0bad6dc2" - }, - { - "ordinal": 4, - "sourceHash": "310728c2e9b7e5045fc21bdbd258950a29e16f3e4333b41bca9e18e1d75429ec", - "targetHash": "aeb2e4b1813c86971cb5ec22701e78cfe5a7265db39b4badf6fb12f761b5048f" - }, - { - "ordinal": 5, - "sourceHash": "294874ede85f308d3a57cdc5c61c4a8d58f883db8396573db69d37f2fce3fdc6", - "targetHash": "111f4a5e339808d2ef2ba90e52e18c4bdcad56cb34407c5d1b2f598ff9da20cb" - }, - { - "ordinal": 6, - "sourceHash": "b5a54418a805c5d19628b3bb41620ae7984aff74707011b0ff7b26817619a9f7", - "targetHash": "ebc11ba5eb3869ba2e92c60f26a8ed56ba63d5976815d276cf29a0594236fe56" - }, - { - "ordinal": 7, - "sourceHash": "7d6268ef94d331e07152a34feaec74d997d2591fc3bcf0859ad7441c97124672", - "targetHash": "25d354aca3c2968421169defb0070c4807ee7eea23265d2094302c6c83da1f02" - }, - { - "ordinal": 8, - "sourceHash": "3e7172a4a728597dd8cb9ab3d95502a6e6aa04b14387428d0412c1dc194afd3f", - "targetHash": "3e7172a4a728597dd8cb9ab3d95502a6e6aa04b14387428d0412c1dc194afd3f" - }, - { - "ordinal": 9, - "sourceHash": "b1e8c4885217c846af9e269228df9a91b681e9842c03f619cb79459f768ba8a2", - "targetHash": "0ec8b03880b690e25ececf4d4eafd5d87218a55cbd3267e95b339b16da6864c8" - }, - { - "ordinal": 10, - "sourceHash": "11693d0aa493bf2b38a8ba48cecf90c8da625b5303761d4eb1023fee5a8dc20d", - "targetHash": "a567b2b46121035e43203a571dc9cfa163686da28807c480e91d94b2ed594de8" - }, - { - "ordinal": 11, - "sourceHash": "067f6a4b5afaf0f316fccd7118d272cfeab684c39eae99f082e8e8e8c5c5b752", - "targetHash": "4c4894d90154253b9bc02bdf06d74e1ef73bb73604ec6927b9f44c6852456948" - }, - { - "ordinal": 12, - "sourceHash": "39d9e1dcc09b54a0b7501746d1153790ed7d02e86acbb9c30581120a3f9cc9b9", - "targetHash": "9bedabda2ade55f06ae87212a403a2026199d5d4b2646e3db1a6b417bbb01043" - }, - { - "ordinal": 13, - "sourceHash": "2448e92a9031555d4baf576686eb804b35b3ca8b678217e4a6a2dc43741062ff", - "targetHash": "91efd14b79286c2b2764ae164684a4a463cbcb19804d82a236e5e43c3ecd2b1c" - }, - { - "ordinal": 14, - "sourceHash": "b9cef8bf99cd4bd9293438f3d1baf3a101e7d78992112f2bdda74956c32c7c4c", - "targetHash": "ef83b11427026a6cd408313dcc87e2223516202e5e874b8e200bcb2581077278" - }, - { - "ordinal": 15, - "sourceHash": "a0659b75c00466135f6ba3e21d24e832f9899f98807e0480992fc30569d0268d", - "targetHash": "54b1807fe77912fe4778e593cad96559e31346a291e43c48fff24e8993e9fc00" - }, - { - "ordinal": 16, - "sourceHash": "b4a313791c1fbca2c1410d1d5b1190af4087723ec1b6c1c4ba776298d6dd6228", - "targetHash": "b4a313791c1fbca2c1410d1d5b1190af4087723ec1b6c1c4ba776298d6dd6228" - }, - { - "ordinal": 17, - "sourceHash": "dc676b42859915c826f8bbaef6511998f7aedbd6e332565faeda17fc33ec6320", - "targetHash": "dc676b42859915c826f8bbaef6511998f7aedbd6e332565faeda17fc33ec6320" - }, - { - "ordinal": 18, - "sourceHash": "926eeba6058ff5b18954fc1a5707376a2670dfb439ee5b00660e2dc6cb6716f5", - "targetHash": "926eeba6058ff5b18954fc1a5707376a2670dfb439ee5b00660e2dc6cb6716f5" - }, - { - "ordinal": 19, - "sourceHash": "87a08ffe9a6f80e34a71c7691fddda770a89a4c249637d50683f5fd9534ee360", - "targetHash": "87a08ffe9a6f80e34a71c7691fddda770a89a4c249637d50683f5fd9534ee360" - }, - { - "ordinal": 20, - "sourceHash": "f783399583a877391438dfa759912922fec0c63faa2024e8d1481138653d12b8", - "targetHash": "f783399583a877391438dfa759912922fec0c63faa2024e8d1481138653d12b8" - }, - { - "ordinal": 21, - "sourceHash": "06969734222d809a6bfa8531289fc6a29de47247e8fdd6fa94e2fd64b1546eb1", - "targetHash": "06969734222d809a6bfa8531289fc6a29de47247e8fdd6fa94e2fd64b1546eb1" - }, - { - "ordinal": 22, - "sourceHash": "85b028d477ba8186e3a1a1e86aa949f9cc514ec0e1b6da2eec77f94033a6ce8c", - "targetHash": "85b028d477ba8186e3a1a1e86aa949f9cc514ec0e1b6da2eec77f94033a6ce8c" - }, - { - "ordinal": 23, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - }, - { - "ordinal": 24, - "sourceHash": "03a8f641293904182090dd83b0a17a3dfc171f6cd2c15957da45a8b076878181", - "targetHash": "1303393cadec1612b995355e5a40bc2d3a9b8ac2580f533e44b02a4089293f43" - }, - { - "ordinal": 25, - "sourceHash": "6d188a3a6b6f3ef3e9b54b90bbe8644afbb67a687a79793cc6478b78603aa4f5", - "targetHash": "09912f1d65e2e610cfc42c00d91a3b6f4f85d9fdc7df631b83322a3e096e1500" - }, - { - "ordinal": 26, - "sourceHash": "1c72b28b05f6ffc0914a1a90674cdd0045c93ebef464fc64ac56f22468e3e786", - "targetHash": "200de7b94ffea3c65e469bc80592ad6aef00823ce6417b42a8bb000d66a49625" - }, - { - "ordinal": 27, - "sourceHash": "00b254fb327db3f20efe1a71793957730f23bc28137eb8b7d84ac13642973c58", - "targetHash": "4a82ef9729ac15aa5d830ea8363c60cb18ea4105c259f0a956afcd2b2c8aded7" - }, - { - "ordinal": 28, - "sourceHash": "68ad0d01f982e6f258cac64e466967775b67fb658f5c4803fe83fdb4f89fa4a7", - "targetHash": "d7c285ced0bd38d6306e187158110f4435e2f9d65439a738c674e77e05ea84f9" - }, - { - "ordinal": 29, - "sourceHash": "ab54461d0f419b5a54b388ee2f8ae558aa50522b1b7409733a40e249482815fd", - "targetHash": "749d441b3e4bf1282bb0eba1ba8c894c075748520d8e9819b5922a0d5b8cd8b3" - }, - { - "ordinal": 30, - "sourceHash": "a92c88c9f2d32dcfc7079078c6f520dcd494093bf77d7718aaed6b8c05aea81f", - "targetHash": "1cc12481c05844706b89f202b2c0abea50fd58196f8e42738478767fb8be7107" - }, - { - "ordinal": 31, - "sourceHash": "383d635bd2c50f69f8402d18ff659964e3542968acf4a696767b7e14567c2560", - "targetHash": "383d635bd2c50f69f8402d18ff659964e3542968acf4a696767b7e14567c2560" - }, - { - "ordinal": 32, - "sourceHash": "4420df8991446fc486e7a15201beac3670db325f891d3406ef68de47b8ae9175", - "targetHash": "e8cb10a4cfa091f65833f4e557d3bd0a948b42ad05bafbf520cf64f900a1f6ce" - }, - { - "ordinal": 33, - "sourceHash": "dc394083646ddca9b59bc602979b82c9a7601e58443ed3178f62685b913e9bfd", - "targetHash": "adbe063776c0c7581a8fb0350ec7b34363b05ee21dc2bccbb4e4d0da8ca3255c" - }, - { - "ordinal": 34, - "sourceHash": "107c645619abff8e4c7bab6e8dcdc509eb523116e0645b9edcefe32c24a85664", - "targetHash": "f8c3e071c5d109730dbed376c09d86717dbae2f116fb7c8409edbb685914dfd5" - }, - { - "ordinal": 35, - "sourceHash": "9c1ff26b58f1aaed263ff9c98b59b8caf9be4ca1e8f0d93c86bc1beac7a8f0d5", - "targetHash": "0594ec9f6fcf6b9421151b7408c86fd959b392e50aaf51201501f188d11679ff" - }, - { - "ordinal": 36, - "sourceHash": "8604d20bfd06096c3800ad1d302f3332768f2ec2dd5793a424a9ef8848da2478", - "targetHash": "da578b5f559f8e63531ac1f9c1c7c0a3d8b1c63f3bd37a4cb5ca2ef5aaade878" - }, - { - "ordinal": 37, - "sourceHash": "3efae27b85314dbccde928e8d3d71d8422709e3d27c4c4c645a31c3afcd245e6", - "targetHash": "e05965b4a4f34a9e91ce0af5cd091dd952e1626b1e996b358c866f6c5b43841e" - }, - { - "ordinal": 38, - "sourceHash": "ad5c2ad9efab6172d1e2f263d289676a177762baf550116294df1b2e774a807f", - "targetHash": "e6fbeb18d3c8250d44fad79efe44f8444474637ab3a57daaec81e3431bb370f1" - }, - { - "ordinal": 39, - "sourceHash": "a132d925134321e599d9d68386a39ade207c5503c74771527b229bad355d3750", - "targetHash": "a132d925134321e599d9d68386a39ade207c5503c74771527b229bad355d3750" - }, - { - "ordinal": 40, - "sourceHash": "dafc8e4178e8bc68d10c60e30fe31d5948545d193dae91f7c268d88dfd73eb3f", - "targetHash": "4f3d9ee0de38fe960cc014e3815d3a490431d298024b58691fd64d72e1a53f47" - }, - { - "ordinal": 41, - "sourceHash": "b9b88b4903de2a4accb4e7da6473959549b95d551f0696cc93f0f6a2e471404f", - "targetHash": "bbac5c3d97ddc122d55990238d81f83ad58064be0fb5ed550cc5e0918d773d7e" - }, - { - "ordinal": 42, - "sourceHash": "98352764e4558c4c9f1739549f460ee16a5dda5eceaef4822f74f5c19fc12e92", - "targetHash": "d2f49afd9d4d5d48812f5b1ec10e27c0ef47e71b77aeafe832cc65d91d2b158e" - }, - { - "ordinal": 43, - "sourceHash": "1d48b746a8b9e9fa2d48acb1a9534ce39920a78d0e1bd86c318b4644dc1df800", - "targetHash": "a5df5ad75cab8084f01adb5892e6bee37d44252c268378904d3f2e8a5dc49b25" - }, - { - "ordinal": 44, - "sourceHash": "f3567ea7df9e453b4acbb77fdd07e4a51dcdff58b296cefc59da16e09cc6558a", - "targetHash": "6f6e4a48bea92ec1aaf81c62c3b046e3e91c9443a311913d7cca92da5371a902" - }, - { - "ordinal": 45, - "sourceHash": "76b5d63c88fbc109ac4dfd2ef13b245d508d9f9c087d7f0f25306813cec8571a", - "targetHash": "d3b7e0955f44f49b0861b496a4a0f9566c2528cbfd69416aaab81fb98aeedf24" - }, - { - "ordinal": 46, - "sourceHash": "8868b837dc0ce140e59552d8ea9da27f6e547cd5c6e3ea230dba383183ea809b", - "targetHash": "2cea3a29070d526beba0ae632a20eff47dcd8b6371cdbf56d3343e01a26110c8" - }, - { - "ordinal": 47, - "sourceHash": "b43c2af4e54526ac8aa49e43f8052e982e12c879d495e25e489769c0a2fe6d38", - "targetHash": "74b669208c873e54245e57f53da423d6cf8d8bde2d064ff8fc2ae69eca7b383c" - } - ] - } - }, - { - "id": "identity-standard-14", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-14", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 14, - "sourceHash": "b04c5ad7493811978bc460e2dfe6f77919b7024e230bb0f8fc2afff0f790ebeb", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "44bdb92c728dc030c682de99ff55c7bc2d3d706281979361e7371da1cd2ebaa3", - "targetHash": "daf36302d83833a011268b63658437a5369ec3880cfeb7fd46f6507b405ee6c8" - }, - { - "ordinal": 2, - "sourceHash": "f544a9fdbe99713a38cdea11f261d92f159d385ab391e56f4ba63ff0f894bb33", - "targetHash": "e9240abee48d7f0b44e532ca09189d067de00eb65291e0f93b5dc5139b899457" - }, - { - "ordinal": 3, - "sourceHash": "a44c25b5b54146e969cf15d3c187987f9973af96a0e6b44a690f9c9b97c68549", - "targetHash": "8d749a1372a89f5cb497a3a9719c7109b3a6430bafeffbc964ee2f158cd77291" - } - ] - } - } - ], - "routes": [ - { - "pattern": "\\.cs$", - "units": [ - "naming", - "members", - "xml", - "errors", - "formatting", - "csharp-standard-0", - "csharp-standard-5", - "csharp-standard-8", - "csharp-standard-9" - ] - }, - { - "pattern": "(\\.csproj$|\\.slnx?$|\\.props$|\\.targets$)", - "units": [ - "solution", - "directories" - ] - }, - { - "pattern": "(^tests/|/tests/)", - "units": [ - "tests", - "compilation", - "review" - ] - }, - { - "pattern": "(scripting|ScriptingApi)", - "units": [ - "scripting", - "identity-reload" - ] - }, - { - "pattern": "(plugins|identity|scene|assets)", - "units": [ - "identity-reload" - ] - }, - { - "pattern": "plugins", - "units": [ - "plugins", - "no-legacy" - ] - }, - { - "pattern": "composition/editor", - "units": [ - "editor-projects" - ] - }, - { - "pattern": "(editor/.+(presentation|panels)|ImGui)", - "units": [ - "editor-layout", - "editor-acceptance" - ] - }, - { - "pattern": "(History|Workspace|State)", - "units": [ - "editor-state" - ] - }, - { - "pattern": "rendering", - "units": [ - "rendering", - "content-frame" - ] - }, - { - "pattern": "^(build/|backends/|platforms/|\\.github/|Directory\\.(Build|Solution)\\.(props|targets)$)", - "units": [ - "build-host", - "platform-products", - "backend-build" - ] - }, - { - "pattern": "^(AGENTS\\.md$|CONTRIBUTING\\.md$|\\.agents/(rulebook|skills)/)", - "units": [ - "completion", - "review" - ] - }, - { - "pattern": "^\\.agents/records/", - "units": [ - "review" - ] - } - ], - "supplementalSources": [ - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 0, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-0", - "hash": "1ae167521e9170f3f63e3f8945bdb849e260d44c79aa523435df060da55077ab" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 1, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-1", - "hash": "e6bb6be83dda2765ee0b7f4147efe8d179357e106fa40a77b666d79b6f7764d0" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 2, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-2", - "hash": "cd7faf5c94f1eaf2ce951777b9dbc7220c57528b38bfe38f1b47ae1cb18470ec" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 3, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-3", - "hash": "75f0a926f0b06b60c211588ca953b239d229e9967fcca8f7cc8a27be8091a3e7" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 4, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-4", - "hash": "30b69ca4a4f4788914691f57fbf66ea5f84a89b41b4d123b57f3c294e926deb8" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 5, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-5", - "hash": "ace556d3813740e6a4e788f488e34cb5fc4442a4b15f50db0349e7effaffc237" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 6, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-6", - "hash": "9513894db97113c26aa081c3cd9d382cdf0ee4676d5c15cb127e0c54103d6194" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 7, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-7", - "hash": "d2f70bc4ab9ed29686da1c043ffd9630fc160b4ad5259a2dc48ea698e90b56c7" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 8, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-8", - "hash": "d59caf636e6d1a2614a542203c5d2e502d47299ad9b434c12083afa1642b0020" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 9, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-9", - "hash": "264a7aa49566628811332c607f0a852dfa14135e8319c3945e20e8f7bd7f1425" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 10, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-10", - "hash": "8e9915979f7d691ef5b067c80bcbf944331135f4d4073e1e90db7fd6b5cddbce" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 11, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-11", - "hash": "594831b9bba1df40656233274f526cd7462d02baef33d61b47a401ca3b77cf42" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 12, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-12", - "hash": "ec9f401d7f7c23a50e563ee86d16a3a852ddb58c3c595ba4b6be4619650627f4" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 13, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-13", - "hash": "b52fbd3c7d57be9738c521c668ba64a2493bc01d6b44c8100f9d3fd75a8b08d4" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 0, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-0", - "hash": "2b3f30679024db5d9b1d07ff1086179e79654d12aeb7d585f9101d857c7c5cd5", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 1, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-1", - "hash": "6b05a0ec83b508519b83132ffd74c35db7f53ebd1d955367afd966333a3e9c30", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 2, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-2", - "hash": "652d09619bf30978b0061ed778331dd33c9154f3ce49c509f05b128e6fd909fa", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 3, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-3", - "hash": "d50017b48c0e71a1ce5f026d029ffb6ee93a88d8d018a5f002118d88aa00314c", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 4, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-4", - "hash": "b4e203ad58328e392684d984491729c023a8643bb8daf527e3c1431dfa495196", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 5, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-5", - "hash": "d17e16a584ffa310b40873a100b302ae616e77495c262be03a8d6c9a14565b66", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 6, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-6", - "hash": "e4755ac95fa67c8079c901ee495f1f523c103f3a0f2d7bf419a9e2760367a8f2", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "section": 9, - "target": ".agents/rulebook/domains/editor.md", - "unit": "editor-standard-9", - "hash": "4c27d71eeeb375245a649934a3e280a722687d62110e88c0ca371ea607dade70" - }, - { - "source": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "section": 10, - "target": ".agents/rulebook/domains/editor.md", - "unit": "editor-standard-10", - "hash": "7c051be2869f46bd2beac2d5dacfd75da8afb5b39047d02955d8c4bea5fcb475" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 12, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-12", - "hash": "c04a13c50f3dfe682a2b41855e42100b349db014d40a7a06530c0b3ee4dd6779" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 13, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-13", - "hash": "52493148de955847cbea6609f0c895bfdefe5008ba5cbd50a6283a5664cac692" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 14, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-14", - "hash": "b04c5ad7493811978bc460e2dfe6f77919b7024e230bb0f8fc2afff0f790ebeb" - } - ], - "migrationBaseline": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b", - "pathReplacements": [ - { - "old": "`docs/core`", - "current": "`docs/modules/core`" - }, - { - "old": "`docs/assets`", - "current": "`docs/modules/assets`" - }, - { - "old": "`docs/engine`", - "current": "`docs/modules/runtime`" - }, - { - "old": "`docs/rendering`", - "current": "`docs/modules/rendering`" - }, - { - "old": "`docs/editor`", - "current": "`docs/modules/editor`" - }, - { - "old": "docs/core/Inno.Extensibility.Types.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Types.md" - }, - { - "old": "`records/`", - "current": "`.agents/records/`" - }, - { - "old": "docs/testing/Inno.Assets.Pipeline.DuplicateImporterFixture.md", - "current": "docs/development/testing/Inno.Assets.Pipeline.DuplicateImporterFixture.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.Invalid.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.Invalid.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestDependency.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestDependency.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.V1.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.V1.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.V2.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.V2.md" - }, - { - "old": "docs/testing/Inno.Rendering.Runtime.Reload.TestModule.md", - "current": "docs/development/testing/Inno.Rendering.Runtime.Reload.TestModule.md" - }, - { - "old": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "current": "docs/architecture/identity-and-reload.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.TestAssemblyA.md", - "current": "docs/development/testing/Inno.Extensibility.Types.TestAssemblyA.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.TestAssemblyB.md", - "current": "docs/development/testing/Inno.Extensibility.Types.TestAssemblyB.md" - }, - { - "old": "docs/testing/Inno.Adapter.Content.FileSystem.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Content.FileSystem.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Assets.Authoring.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Assets.Authoring.Tests.md" - }, - { - "old": "docs/architecture/NATIVE_BUILD_PLATFORM_OWNERSHIP.md", - "current": "docs/architecture/platform-and-products.md" - }, - { - "old": "docs/architecture/DEVELOPMENT_ENTRY_ARCHITECTURE.md", - "current": "docs/development/entry/README.md" - }, - { - "old": "docs/architecture/PLATFORM_RUNTIME_ARCHITECTURE.md", - "current": "docs/architecture/platform-and-products.md" - }, - { - "old": "docs/rendering/Inno.Adapter.Rendering.Authoring.md", - "current": "docs/modules/rendering/Inno.Adapter.Rendering.Authoring.md" - }, - { - "old": "docs/testing/Inno.Adapter.Audio.MiniAudio.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Audio.MiniAudio.Tests.md" - }, - { - "old": "docs/testing/Inno.Build.NativePerformance.Tests.md", - "current": "docs/development/testing/Inno.Build.NativePerformance.Tests.md" - }, - { - "old": "docs/architecture/ENGINE_ARCHITECTURE_OVERVIEW.md", - "current": "docs/architecture/overview.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Catalogs.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Catalogs.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Assets.Authoring.md", - "current": "docs/modules/rendering/Inno.Rendering.Assets.Authoring.md" - }, - { - "old": "docs/testing/Inno.Adapter.Rendering.Bgfx.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Rendering.Bgfx.Tests.md" - }, - { - "old": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Modules.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Modules.md" - }, - { - "old": "docs/testing/Inno.Adapter.Platform.Sdl3.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Platform.Sdl3.Tests.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.Tests.md" - }, - { - "old": "docs/core/Inno.Core.Serialization.Generators.md", - "current": "docs/modules/core/Inno.Core.Serialization.Generators.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Reload.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Reload.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Reload.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Reload.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Architecture.Tests.md", - "current": "docs/development/testing/Inno.Tooling.Architecture.Tests.md" - }, - { - "old": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "current": "docs/architecture/editor-ui.md" - }, - { - "old": "docs/build/Inno.Build.Distribution.Standard.md", - "current": "docs/development/build/Inno.Build.Distribution.Standard.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Types.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Types.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Shaders.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Shaders.Tests.md" - }, - { - "old": "docs/runtime/Inno.Adapter.Authoring.Default.md", - "current": "docs/modules/runtime/Inno.Adapter.Authoring.Default.md" - }, - { - "old": "docs/testing/Inno.Editor.Interactions.Tests.md", - "current": "docs/development/testing/Inno.Editor.Interactions.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Presentation.Tests.md", - "current": "docs/development/testing/Inno.Editor.Presentation.Tests.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Types.Tests.md" - }, - { - "old": "docs/architecture/BUILD_CACHE_ARCHITECTURE.md", - "current": "docs/architecture/build-and-cache.md" - }, - { - "old": "docs/architecture/PLATFORM_EXTENSION_GUIDE.md", - "current": "docs/development/adding-platform.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.ShaderEditor.md", - "current": "docs/modules/editor/Inno.Editor.Panel.ShaderEditor.md" - }, - { - "old": "docs/testing/Inno.Core.Serialization.Tests.md", - "current": "docs/development/testing/Inno.Core.Serialization.Tests.md" - }, - { - "old": "docs/testing/Inno.Runtime.Generators.Tests.md", - "current": "docs/development/testing/Inno.Runtime.Generators.Tests.md" - }, - { - "old": "docs/testing/Inno.Scripting.Compiler.Tests.md", - "current": "docs/development/testing/Inno.Scripting.Compiler.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Validation.Tests.md", - "current": "docs/development/testing/Inno.Tooling.Validation.Tests.md" - }, - { - "old": "docs/architecture/WEB_PLAYER_ARCHITECTURE.md", - "current": "docs/architecture/web-player.md" - }, - { - "old": "docs/architecture/rules/editor-acceptance.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/platform-products.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.FileBrowser.md", - "current": "docs/modules/editor/Inno.Editor.Panel.FileBrowser.md" - }, - { - "old": "docs/testing/Inno.Editor.Inspection.Tests.md", - "current": "docs/development/testing/Inno.Editor.Inspection.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Scene.Reload.TestModule.md", - "current": "docs/development/testing/Inno.Scene.Reload.TestModule.md" - }, - { - "old": "docs/testing/Inno.Testing.Processes.Tests.md", - "current": "docs/development/testing/Inno.Testing.Processes.Tests.md" - }, - { - "old": "docs/architecture/DOCUMENTATION_STANDARD.md", - "current": ".agents/rulebook/documentation.md" - }, - { - "old": "docs/architecture/EDITOR_UI_ARCHITECTURE.md", - "current": "docs/architecture/editor-ui.md" - }, - { - "old": "docs/testing/Inno.Build.Toolchains.Tests.md", - "current": "docs/development/testing/Inno.Build.Toolchains.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Collections.Tests.md", - "current": "docs/development/testing/Inno.Core.Collections.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Diagnostics.Tests.md", - "current": "docs/development/testing/Inno.Core.Diagnostics.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Mathematics.Tests.md", - "current": "docs/development/testing/Inno.Core.Mathematics.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Scripting.Tests.md", - "current": "docs/development/testing/Inno.Editor.Scripting.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.MiniAudio.Tests.md", - "current": "docs/development/testing/Inno.Native.MiniAudio.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Assets.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Assets.Tests.md" - }, - { - "old": "docs/architecture/rules/editor-projects.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/identity-naming.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/identity-reload.md", - "current": ".agents/rulebook/domains/identity-reload.md" - }, - { - "old": "docs/build/Inno.Build.Products.Standard.md", - "current": "docs/development/build/Inno.Build.Products.Standard.md" - }, - { - "old": "docs/build/Inno.Build.SupportPacks.Core.md", - "current": "docs/development/build/Inno.Build.SupportPacks.Core.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Hierarchy.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Hierarchy.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Inspector.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Inspector.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.SceneView.md", - "current": "docs/modules/editor/Inno.Editor.Panel.SceneView.md" - }, - { - "old": "docs/testing/Inno.Assets.Pipeline.Tests.md", - "current": "docs/development/testing/Inno.Assets.Pipeline.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Coroutines.Tests.md", - "current": "docs/development/testing/Inno.Core.Coroutines.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.PlayMode.Tests.md", - "current": "docs/development/testing/Inno.Editor.PlayMode.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.ImGuizmo.Tests.md", - "current": "docs/development/testing/Inno.Native.ImGuizmo.Tests.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.GameView.md", - "current": "docs/modules/editor/Inno.Editor.Panel.GameView.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Settings.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Settings.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Compiler.md", - "current": "docs/modules/scripting/Inno.Scripting.Compiler.md" - }, - { - "old": "docs/testing/Inno.Core.Execution.Tests.md", - "current": "docs/development/testing/Inno.Core.Execution.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Hosting.Tests.md", - "current": "docs/development/testing/Inno.Editor.Hosting.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Architecture.md", - "current": "docs/development/tooling/Inno.Tooling.Architecture.md" - }, - { - "old": "docs/animation/Inno.Animation.Runtime.md", - "current": "docs/modules/animation/Inno.Animation.Runtime.md" - }, - { - "old": "docs/architecture/rules/backend-build.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/architecture/rules/content-frame.md", - "current": ".agents/rulebook/domains/rendering.md" - }, - { - "old": "docs/architecture/rules/editor-layout.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/encapsulation.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Logging.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Logging.md" - }, - { - "old": "docs/editor/Inno.Editor.Shaders.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Shaders.ImGui.md" - }, - { - "old": "docs/rendering/Inno.Adapter.Rendering.md", - "current": "docs/modules/rendering/Inno.Adapter.Rendering.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Runtime.md", - "current": "docs/modules/rendering/Inno.Rendering.Runtime.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Shaders.md", - "current": "docs/modules/rendering/Inno.Rendering.Shaders.md" - }, - { - "old": "docs/testing/Inno.Audio.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Audio.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Identity.Tests.md", - "current": "docs/development/testing/Inno.Core.Identity.Tests.md" - }, - { - "old": "docs/animation/Inno.Animation.Assets.md", - "current": "docs/modules/animation/Inno.Animation.Assets.md" - }, - { - "old": "docs/architecture/CURRENT_ACCEPTANCE.md", - "current": ".agents/records/acceptance/current.md" - }, - { - "old": "docs/architecture/rules/architecture.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/editor-state.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/notification.md", - "current": ".agents/rulebook/delivery.md" - }, - { - "old": "docs/editor/Inno.Editor.Assets.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Assets.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Interactions.md", - "current": "docs/modules/editor/Inno.Editor.Interactions.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Assets.md", - "current": "docs/modules/rendering/Inno.Rendering.Assets.md" - }, - { - "old": "docs/runtime/Inno.Runtime.Generators.md", - "current": "docs/modules/runtime/Inno.Runtime.Generators.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Reload.md", - "current": "docs/modules/scripting/Inno.Scripting.Reload.md" - }, - { - "old": "docs/testing/Inno.Audio.Assets.Tests.md", - "current": "docs/development/testing/Inno.Audio.Assets.Tests.md" - }, - { - "old": "docs/testing/Inno.Content.CacheProbe.md", - "current": "docs/development/testing/Inno.Content.CacheProbe.md" - }, - { - "old": "docs/testing/Inno.Core.Logging.Tests.md", - "current": "docs/development/testing/Inno.Core.Logging.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Audio.Tests.md", - "current": "docs/development/testing/Inno.Editor.Audio.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Graph.Tests.md", - "current": "docs/development/testing/Inno.Editor.Graph.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.ImGui.Tests.md", - "current": "docs/development/testing/Inno.Editor.ImGui.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.ImGui.Tests.md", - "current": "docs/development/testing/Inno.Native.ImGui.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Validation.md", - "current": "docs/development/tooling/Inno.Tooling.Validation.md" - }, - { - "old": "docs/architecture/rules/compilation.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/architecture/rules/directories.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/editor/Inno.Editor.Annotations.md", - "current": "docs/modules/editor/Inno.Editor.Annotations.md" - }, - { - "old": "docs/editor/Inno.Editor.Diagnostics.md", - "current": "docs/modules/editor/Inno.Editor.Diagnostics.md" - }, - { - "old": "docs/editor/Inno.Editor.Graph.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Graph.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Stats.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Stats.md" - }, - { - "old": "docs/plugins/Inno.Plugins.Authoring.md", - "current": "docs/modules/plugins/Inno.Plugins.Authoring.md" - }, - { - "old": "docs/runtime/Inno.Runtime.Contracts.md", - "current": "docs/modules/runtime/Inno.Runtime.Contracts.md" - }, - { - "old": "docs/testing/Inno.Core.Events.Tests.md", - "current": "docs/development/testing/Inno.Core.Events.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Graphs.Tests.md", - "current": "docs/development/testing/Inno.Core.Graphs.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Layers.Tests.md", - "current": "docs/development/testing/Inno.Core.Layers.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.Bgfx.Tests.md", - "current": "docs/development/testing/Inno.Native.Bgfx.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.Sdl3.Tests.md", - "current": "docs/development/testing/Inno.Native.Sdl3.Tests.md" - }, - { - "old": "docs/testing/Inno.Testing.Processes.md", - "current": "docs/development/testing/Inno.Testing.Processes.md" - }, - { - "old": "docs/ui/Inno.Adapter.UI.RmlUi.Tests.md", - "current": "docs/development/testing/Inno.Adapter.UI.RmlUi.Tests.md" - }, - { - "old": "docs/architecture/rules/build-host.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/architecture/rules/completion.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/architecture/rules/core-reuse.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/formatting.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/editor/Inno.Editor.Inspection.md", - "current": "docs/modules/editor/Inno.Editor.Inspection.md" - }, - { - "old": "docs/testing/Inno.References.Tests.md", - "current": "docs/development/testing/Inno.References.Tests.md" - }, - { - "old": "docs/architecture/rules/no-legacy.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/rendering.md", - "current": ".agents/rulebook/domains/rendering.md" - }, - { - "old": "docs/architecture/rules/scripting.md", - "current": ".agents/rulebook/domains/scripting.md" - }, - { - "old": "docs/build/Inno.Build.Composition.md", - "current": "docs/development/build/Inno.Build.Composition.md" - }, - { - "old": "docs/build/Inno.Build.TaskHosting.md", - "current": "docs/development/build/Inno.Build.TaskHosting.md" - }, - { - "old": "docs/core/Inno.Core.Serialization.md", - "current": "docs/modules/core/Inno.Core.Serialization.md" - }, - { - "old": "docs/editor/Inno.Editor.Exporting.md", - "current": "docs/modules/editor/Inno.Editor.Exporting.md" - }, - { - "old": "docs/editor/Inno.Editor.Rendering.md", - "current": "docs/modules/editor/Inno.Editor.Rendering.md" - }, - { - "old": "docs/editor/Inno.Editor.Scripting.md", - "current": "docs/modules/editor/Inno.Editor.Scripting.md" - }, - { - "old": "docs/editor/Inno.Editor.Workbench.md", - "current": "docs/modules/editor/Inno.Editor.Workbench.md" - }, - { - "old": "docs/runtime/Inno.Adapter.Default.md", - "current": "docs/modules/runtime/Inno.Adapter.Default.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Api.md", - "current": "docs/modules/scripting/Inno.Scripting.Api.md" - }, - { - "old": "docs/storage/Inno.Adapter.Storage.md", - "current": "docs/modules/storage/Inno.Adapter.Storage.md" - }, - { - "old": "docs/storage/Inno.Storage.Runtime.md", - "current": "docs/modules/storage/Inno.Storage.Runtime.md" - }, - { - "old": "docs/testing/Inno.Animation.Tests.md", - "current": "docs/development/testing/Inno.Animation.Tests.md" - }, - { - "old": "docs/testing/Inno.Content.Testing.md", - "current": "docs/development/testing/Inno.Content.Testing.md" - }, - { - "old": "docs/testing/Inno.Core.Jobs.Tests.md", - "current": "docs/development/testing/Inno.Core.Jobs.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Tests.md" - }, - { - "old": "docs/architecture/CURRENT_ISSUES.md", - "current": ".agents/records/open-items.md" - }, - { - "old": "docs/architecture/rules/delivery.md", - "current": ".agents/rulebook/delivery.md" - }, - { - "old": "docs/architecture/rules/solution.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/assets/Inno.Assets.Pipeline.md", - "current": "docs/modules/assets/Inno.Assets.Pipeline.md" - }, - { - "old": "docs/build/DEPENDENCY_SUBMISSION.md", - "current": "docs/development/build/DEPENDENCY_SUBMISSION.md" - }, - { - "old": "docs/build/Inno.Build.Toolchains.md", - "current": "docs/development/build/Inno.Build.Toolchains.md" - }, - { - "old": "docs/editor/Inno.Editor.PlayMode.md", - "current": "docs/modules/editor/Inno.Editor.PlayMode.md" - }, - { - "old": "docs/editor/Inno.Editor.Settings.md", - "current": "docs/modules/editor/Inno.Editor.Settings.md" - }, - { - "old": "docs/runtime/Inno.Engine.Default.md", - "current": "docs/modules/runtime/Inno.Engine.Default.md" - }, - { - "old": "docs/runtime/Inno.Player.Runtime.md", - "current": "docs/modules/runtime/Inno.Player.Runtime.md" - }, - { - "old": "docs/testing/Inno.Testing.Source.md", - "current": "docs/development/testing/Inno.Testing.Source.md" - }, - { - "old": "docs/architecture/rules/members.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/plugins.md", - "current": ".agents/rulebook/domains/plugins.md" - }, - { - "old": "docs/core/Inno.Core.Collections.md", - "current": "docs/modules/core/Inno.Core.Collections.md" - }, - { - "old": "docs/core/Inno.Core.Diagnostics.md", - "current": "docs/modules/core/Inno.Core.Diagnostics.md" - }, - { - "old": "docs/core/Inno.Core.Mathematics.md", - "current": "docs/modules/core/Inno.Core.Mathematics.md" - }, - { - "old": "docs/editor/Inno.Editor.Hosting.md", - "current": "docs/modules/editor/Inno.Editor.Hosting.md" - }, - { - "old": "docs/editor/Inno.Editor.Shaders.md", - "current": "docs/modules/editor/Inno.Editor.Shaders.md" - }, - { - "old": "docs/references/Inno.References.md", - "current": "docs/modules/references/Inno.References.md" - }, - { - "old": "docs/testing/Inno.Content.Tests.md", - "current": "docs/development/testing/Inno.Content.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.IO.Tests.md", - "current": "docs/development/testing/Inno.Core.IO.Tests.md" - }, - { - "old": "docs/testing/Inno.Plugins.Tests.md", - "current": "docs/development/testing/Inno.Plugins.Tests.md" - }, - { - "old": "docs/testing/Inno.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Storage.Tests.md", - "current": "docs/development/testing/Inno.Storage.Tests.md" - }, - { - "old": "docs/architecture/rules/README.md", - "current": ".agents/rulebook/README.md" - }, - { - "old": "docs/architecture/rules/errors.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/naming.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/review.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/build/Inno.Build.Bindings.md", - "current": "docs/development/build/Inno.Build.Bindings.md" - }, - { - "old": "docs/core/Inno.Core.Coroutines.md", - "current": "docs/modules/core/Inno.Core.Coroutines.md" - }, - { - "old": "docs/editor/Inno.Editor.Assets.md", - "current": "docs/modules/editor/Inno.Editor.Assets.md" - }, - { - "old": "docs/testing/Inno.Assets.Tests.md", - "current": "docs/development/testing/Inno.Assets.Tests.md" - }, - { - "old": "docs/animation/Inno.Animation.md", - "current": "docs/modules/animation/Inno.Animation.md" - }, - { - "old": "docs/architecture/rules/style.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/tests.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/audio/Inno.Adapter.Audio.md", - "current": "docs/modules/audio/Inno.Adapter.Audio.md" - }, - { - "old": "docs/audio/Inno.Audio.Runtime.md", - "current": "docs/modules/audio/Inno.Audio.Runtime.md" - }, - { - "old": "docs/build/Inno.Build.Managed.md", - "current": "docs/development/build/Inno.Build.Managed.md" - }, - { - "old": "docs/core/Inno.Core.Execution.md", - "current": "docs/modules/core/Inno.Core.Execution.md" - }, - { - "old": "docs/editor/Inno.Editor.Audio.md", - "current": "docs/modules/editor/Inno.Editor.Audio.md" - }, - { - "old": "docs/editor/Inno.Editor.Graph.md", - "current": "docs/modules/editor/Inno.Editor.Graph.md" - }, - { - "old": "docs/editor/Inno.Editor.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Scene.md", - "current": "docs/modules/editor/Inno.Editor.Scene.md" - }, - { - "old": "docs/input/Inno.Adapter.Input.md", - "current": "docs/modules/input/Inno.Adapter.Input.md" - }, - { - "old": "docs/input/Inno.Input.Runtime.md", - "current": "docs/modules/input/Inno.Input.Runtime.md" - }, - { - "old": "docs/native/BindingGeneration.md", - "current": "docs/development/native-bindings.md" - }, - { - "old": "docs/rendering/Inno.Rendering.md", - "current": "docs/modules/rendering/Inno.Rendering.md" - }, - { - "old": "docs/testing/Inno.Audio.Tests.md", - "current": "docs/development/testing/Inno.Audio.Tests.md" - }, - { - "old": "docs/testing/Inno.Build.Tests.md", - "current": "docs/development/testing/Inno.Build.Tests.md" - }, - { - "old": "docs/testing/Inno.Input.Tests.md", - "current": "docs/development/testing/Inno.Input.Tests.md" - }, - { - "old": "docs/testing/Inno.Scene.Tests.md", - "current": "docs/development/testing/Inno.Scene.Tests.md" - }, - { - "old": "docs/architecture/rules/wiki.md", - "current": ".agents/rulebook/documentation.md" - }, - { - "old": "docs/audio/Inno.Audio.Assets.md", - "current": "docs/modules/audio/Inno.Audio.Assets.md" - }, - { - "old": "docs/core/Inno.Core.Identity.md", - "current": "docs/modules/core/Inno.Core.Identity.md" - }, - { - "old": "docs/core/Inno.Core.Settings.md", - "current": "docs/modules/core/Inno.Core.Settings.md" - }, - { - "old": "docs/editor/Inno.Editor.Core.md", - "current": "docs/modules/editor/Inno.Editor.Core.md" - }, - { - "old": "docs/entry/InnoEngine.Editor.md", - "current": "docs/development/entry/InnoEngine.Editor.md" - }, - { - "old": "docs/scene/Inno.Scene.Assets.md", - "current": "docs/modules/scene/Inno.Scene.Assets.md" - }, - { - "old": "docs/architecture/rules/xml.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/build/Inno.Build.Tasks.md", - "current": "docs/development/build/Inno.Build.Tasks.md" - }, - { - "old": "docs/core/Inno.Core.Logging.md", - "current": "docs/modules/core/Inno.Core.Logging.md" - }, - { - "old": "docs/entry/InnoEngine.Build.md", - "current": "docs/development/entry/InnoEngine.Build.md" - }, - { - "old": "docs/text/Inno.Adapter.Text.md", - "current": "docs/modules/text/Inno.Adapter.Text.md" - }, - { - "old": "docs/text/Inno.Text.Runtime.md", - "current": "docs/modules/text/Inno.Text.Runtime.md" - }, - { - "old": "docs/core/Inno.Core.Events.md", - "current": "docs/modules/core/Inno.Core.Events.md" - }, - { - "old": "docs/core/Inno.Core.Graphs.md", - "current": "docs/modules/core/Inno.Core.Graphs.md" - }, - { - "old": "docs/core/Inno.Core.Layers.md", - "current": "docs/modules/core/Inno.Core.Layers.md" - }, - { - "old": "docs/text/Inno.Text.Assets.md", - "current": "docs/modules/text/Inno.Text.Assets.md" - }, - { - "old": "docs/build/Inno.Build.Cli.md", - "current": "docs/development/build/Inno.Build.Cli.md" - }, - { - "old": "docs/core/Inno.Core.Input.md", - "current": "docs/modules/core/Inno.Core.Input.md" - }, - { - "old": "docs/extensibility/README.md", - "current": "docs/modules/extensibility/README.md" - }, - { - "old": "docs/plugins/Inno.Plugins.md", - "current": "docs/modules/plugins/Inno.Plugins.md" - }, - { - "old": "docs/runtime/Inno.Adapter.md", - "current": "docs/modules/runtime/Inno.Adapter.md" - }, - { - "old": "docs/runtime/Inno.Runtime.md", - "current": "docs/modules/runtime/Inno.Runtime.md" - }, - { - "old": "docs/storage/Inno.Storage.md", - "current": "docs/modules/storage/Inno.Storage.md" - }, - { - "old": "docs/text/Inno.Text.Tests.md", - "current": "docs/development/testing/Inno.Text.Tests.md" - }, - { - "old": "docs/assets/Inno.Content.md", - "current": "docs/modules/assets/Inno.Content.md" - }, - { - "old": "docs/core/Inno.Core.Jobs.md", - "current": "docs/modules/core/Inno.Core.Jobs.md" - }, - { - "old": "docs/assets/Inno.Assets.md", - "current": "docs/modules/assets/Inno.Assets.md" - }, - { - "old": "docs/runtime/Inno.Shell.md", - "current": "docs/modules/runtime/Inno.Shell.md" - }, - { - "old": "docs/ui/Inno.Adapter.UI.md", - "current": "docs/modules/ui/Inno.Adapter.UI.md" - }, - { - "old": "docs/ui/Inno.UI.Runtime.md", - "current": "docs/modules/ui/Inno.UI.Runtime.md" - }, - { - "old": "docs/core/Inno.Core.IO.md", - "current": "docs/modules/core/Inno.Core.IO.md" - }, - { - "old": "docs/references/README.md", - "current": "docs/modules/references/README.md" - }, - { - "old": "docs/ui/Inno.UI.Assets.md", - "current": "docs/modules/ui/Inno.UI.Assets.md" - }, - { - "old": "docs/animation/README.md", - "current": "docs/modules/animation/README.md" - }, - { - "old": "docs/audio/Inno.Audio.md", - "current": "docs/modules/audio/Inno.Audio.md" - }, - { - "old": "docs/build/Inno.Build.md", - "current": "docs/development/build/Inno.Build.md" - }, - { - "old": "docs/input/Inno.Input.md", - "current": "docs/modules/input/Inno.Input.md" - }, - { - "old": "docs/rendering/README.md", - "current": "docs/modules/rendering/README.md" - }, - { - "old": "docs/scene/Inno.Scene.md", - "current": "docs/modules/scene/Inno.Scene.md" - }, - { - "old": "docs/scripting/README.md", - "current": "docs/modules/scripting/README.md" - }, - { - "old": "docs/ui/Inno.UI.Tests.md", - "current": "docs/development/testing/Inno.UI.Tests.md" - }, - { - "old": "docs/plugins/README.md", - "current": "docs/modules/plugins/README.md" - }, - { - "old": "docs/runtime/README.md", - "current": "docs/modules/runtime/README.md" - }, - { - "old": "docs/storage/README.md", - "current": "docs/modules/storage/README.md" - }, - { - "old": "docs/testing/README.md", - "current": "docs/development/testing/README.md" - }, - { - "old": "docs/text/Inno.Text.md", - "current": "docs/modules/text/Inno.Text.md" - }, - { - "old": "docs/tooling/README.md", - "current": "docs/development/tooling/README.md" - }, - { - "old": "docs/assets/README.md", - "current": "docs/modules/assets/README.md" - }, - { - "old": "docs/editor/README.md", - "current": "docs/modules/editor/README.md" - }, - { - "old": "docs/native/README.md", - "current": "docs/development/README.md" - }, - { - "old": "docs/audio/README.md", - "current": "docs/modules/audio/README.md" - }, - { - "old": "docs/build/README.md", - "current": "docs/development/build/README.md" - }, - { - "old": "docs/entry/README.md", - "current": "docs/development/building.md" - }, - { - "old": "docs/input/README.md", - "current": "docs/modules/input/README.md" - }, - { - "old": "docs/scene/README.md", - "current": "docs/modules/scene/README.md" - }, - { - "old": "docs/core/README.md", - "current": "docs/modules/core/README.md" - }, - { - "old": "docs/text/README.md", - "current": "docs/modules/text/README.md" - }, - { - "old": "docs/ui/Inno.UI.md", - "current": "docs/modules/ui/Inno.UI.md" - }, - { - "old": "docs/ui/README.md", - "current": "docs/modules/ui/README.md" - } - ] -} diff --git a/.agents/rulebook/csharp-style/01-files.md b/.agents/rulebook/csharp-style/01-files.md new file mode 100644 index 000000000..4327e62a3 --- /dev/null +++ b/.agents/rulebook/csharp-style/01-files.md @@ -0,0 +1,130 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 1. Files and physical layout + +## F-01 Encoding, line endings and indentation + +- UTF-8 without a byte order mark. +- LF line endings. +- Four spaces per indentation level. Never use tab characters. +- No trailing whitespace. +- The file ends with exactly one newline. +- At most one consecutive blank line. + +In the next two blocks `→` is a tab, `·` is a space and `¶` is a newline. + +```text +····private int m_count;¶ +}¶ +``` + +Avoid (tab indentation, trailing whitespace, extra blank line at the end of the file): + +```text +→private int m_count;··¶ +}¶ +¶ +``` + +## F-02 One top-level type per file, named after the type + +- The file name is the PascalCase name of its primary type: `EventDispatcher.cs` contains `EventDispatcher`. +- Generic arity is not part of the file name: `Pool` lives in `Pool.cs`. +- Additional files of a `partial` type are named `Type.Part.cs`. +- A small, tightly coupled contract (an enum, delegate or parameter record used only by the primary type) may share the file. The primary type comes first. + +```text +Inno.Core.Events/ + EventDispatcher.cs class EventDispatcher + EventDispatcher.Observation.cs partial class EventDispatcher + IEventSink.cs interface IEventSink +``` + +## F-03 File structure + +A file contains, in this order: the using directives, one blank line, the file-scoped namespace, one blank line, the types. There is no file header comment, no license banner and no leading blank line. + +```csharp +using System; +using System.Collections.Generic; + +namespace Inno.Core.Events; + +/// +/// Dispatches events to registered sinks. +/// +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +Avoid (no blank line after the namespace): + +```csharp +namespace Inno.Core.Events; +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +## F-04 Line width + +- Aim for 120 columns or fewer. 140 columns is the hard limit. +- Only an unsplittable string literal (a path, a URL, one diagnostic sentence) may exceed the hard limit. +- Do not split a name, a modifier list or a short expression body merely to shorten a line. + +```csharp +// 107 columns: stays on one line. +public bool isMissing => m_source is null || !m_source.exists || m_source.generation != m_owner.generation; + +// 145 columns on one line: break it by meaning. +throw new InvalidOperationException( + $"The importer '{importer.name}' produced no result for '{path}' while generation {generation} was active." +); +``` + +Avoid (a short declaration split for no reason): + +```csharp +public bool isMissing + => m_source is null; +``` + +## F-05 Indentation and alignment of continuation lines + +Prefer alignment over a fixed indent. + +- **Operator continuation.** When an expression is broken at an operator (`&&`, `||`, `??`, `+`, `?`, `:`, `or`, `and`, …), each continuation line begins with the operator and aligns with the first operand of that expression. +- **Fallback.** When alignment would push a line past the hard limit, indent the continuation lines four spaces from the start of the statement instead. +- **Delimited lists.** The contents of a broken parameter list, argument list, initializer or collection are indented four spaces from the line that opens them. The closing delimiter, when it is on its own line, aligns with the first token of the opening line. +- **Call chains, wrapped `=>` and clauses.** A wrapped `.Member(...)` link, a wrapped expression-body `=>`, and a wrapped `where` or constructor-initializer clause are indented four spaces from the start of the statement or declaration. + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +return left.order != right.order + || left.layer != right.layer; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; + +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .ToList(); +``` + +Avoid (operator continuation indented by a fixed amount instead of aligned): + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; +``` diff --git a/.agents/rulebook/csharp-style/02-namespaces.md b/.agents/rulebook/csharp-style/02-namespaces.md new file mode 100644 index 000000000..7ad80e597 --- /dev/null +++ b/.agents/rulebook/csharp-style/02-namespaces.md @@ -0,0 +1,163 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 2. Namespaces and using directives + +## N-01 File-scoped namespaces + +Use `namespace X;`. A file declares exactly one namespace. + +```csharp +namespace Inno.Core.Events; + +public sealed class EventDispatcher +{ + private int m_generation; +} +``` + +Avoid: + +```csharp +namespace Inno.Core.Events +{ + public sealed class EventDispatcher + { + private int m_generation; + } +} +``` + +## N-02 The namespace is the project name + +The namespace starts with `Inno`, uses PascalCase segments and equals the assembly name of the owning project. Directories inside a project organize files; they do not add namespace segments. + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline; +``` + +Avoid: + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline.Importing; +``` + +The one registered exception is `Inno.Editor.ImGui/Widgets`, which uses `Inno.Editor.ImGui.ImGuiWidget`. + +## N-03 Placement and kinds of using directives + +- All using directives are at the top of the file, outside the namespace. +- `global using`, implicit usings and MSBuild `Using` items are prohibited. Handwritten code never uses `global::`. +- `using static` is reserved for pure function containers such as math helpers. + +```csharp +using System; +using Inno.Core.Events; + +namespace Inno.Rendering; +``` + +Avoid: + +```csharp +global using System; + +namespace Inno.Rendering; + +using Inno.Core.Events; + +public sealed class Renderer +{ + private readonly global::Inno.Core.Events.EventDispatcher m_dispatcher = new(); +} +``` + +## N-04 Order of using directives + +Using directives form up to three groups, in this order, separated by exactly one blank line: + +1. Namespace usings. +2. `using static` directives. +3. Alias usings. + +Inside the namespace group the order is: + +1. `System` and `System.*`. +2. Everything else that is not `Inno` (third-party and framework packages). +3. `Inno` and `Inno.*`. + +Each tier is sorted alphabetically (ordinal). There are no blank lines inside a group. Static usings follow the same three tiers; aliases are sorted by alias name. + +```csharp +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis; +using Xunit; +using Inno.Core.Events; +using Inno.Core.Identity; + +using static System.MathF; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (`Inno` before third-party namespaces, a blank line inside the namespace group, an alias among the namespace usings, no blank line between kinds): + +```csharp +using Inno.Core.Events; +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using Xunit; + +using System; +using System.Collections.Generic; +using static System.MathF; +``` + +## N-05 No fully qualified names at the point of use + +Import a type with a using directive and refer to it by its short name. When two names collide, declare one alias at the top of the file and use only that alias throughout the file. + +```csharp +using System.IO; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static AssetEvent Deleted(string path) => new(path, WatcherChangeTypes.Deleted); +} +``` + +Avoid: + +```csharp +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static Inno.Assets.Pipeline.AssetChangedEvent Deleted(string path) + => new(path, System.IO.WatcherChangeTypes.Deleted); +} +``` + +## N-06 Alias names + +An alias is PascalCase, names the role the type plays in this file and differs from the short name of its target. One target has one alias per file. + +```csharp +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (the alias repeats the target name, and a second alias names the same target): + +```csharp +using Sdl3Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +using Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` diff --git a/.agents/rulebook/csharp-style/03-naming.md b/.agents/rulebook/csharp-style/03-naming.md new file mode 100644 index 000000000..f60039e0b --- /dev/null +++ b/.agents/rulebook/csharp-style/03-naming.md @@ -0,0 +1,383 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, naming] +--- +# 3. Naming + +## Summary + +| Element | Rule | Example | +| --- | --- | --- | +| Namespace segment | PascalCase | `Inno.Core.Events` | +| Class, struct, record, enum, delegate | PascalCase | `RenderGraph`, `AssetHandle` | +| Interface | `I` + PascalCase | `IEventSink` | +| Type parameter | `T` or `T` + PascalCase | `T`, `TSource` | +| Method, local function | PascalCase | `TryResolve`, `CreateBuffer` | +| Property, indexer | camelCase | `transform`, `isMissing` | +| Event | camelCase | `redrawRequested` | +| Constant (`const`, including local constants) | `C_` + UPPER_SNAKE | `C_MAX_COUNT` | +| `static readonly` field (any accessibility) | UPPER_SNAKE | `DEFAULT_OPTIONS`, `RED` | +| Private static mutable field | `s_` + camelCase | `s_nextID` | +| Private or protected instance field | `m_` + camelCase | `m_generation` | +| Internal or public instance field | camelCase | `latestSucceeded` | +| Enum member | PascalCase | `Borrowed` | +| Parameter, local variable, tuple element | camelCase | `outputDirectory` | +| Two-letter acronym | Upper case in PascalCase positions | `AssetID`, `IOStatus`, `UIScale` | +| Test class and test method | `XxxTests`, PascalCase sentence | `DispatchAfterDisposeThrows` | + +## NM-01 Type names + +A type name is a PascalCase noun or noun phrase. The suffix follows the role: `Attribute`, `Exception`, `EventArgs`, `Tests`, and `Extensions` for a class that holds extension methods. An abstract class has no `Base` or `Abstract` affix. + +```csharp +public sealed class InspectorMessageAttribute : Attribute; + +public static class PathExtensions +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public sealed class InspectorMessage : Attribute; + +public static class PathHelpers +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDropBase; +``` + +## NM-02 Interfaces and type parameters + +An interface name starts with `I`. No other type starts with `I` followed by an upper-case letter. Use `T` when there is a single, obvious type parameter; otherwise use `T` plus a description. + +```csharp +public interface IAssetImporter + where TAsset : class +{ + TAsset Import(string path); +} + +public sealed class Pool; +``` + +Avoid: + +```csharp +public interface AssetImporter + where Asset : class +{ + Asset Import(string path); +} +``` + +## NM-03 Method names + +A method name is PascalCase and starts with a verb. These prefixes have fixed meanings: + +- `Try*` returns `bool`, does not throw on failure and returns its result through an `out` parameter. +- `Is*`, `Has*` and `Can*` return `bool` and have no side effects. +- `Create*` builds a new object that the caller owns. +- `Get*` reads existing state without side effects. +- `*Async` returns `Task` or `ValueTask` (NM-04). + +```csharp +public bool TryResolve( + AssetID id, + out AssetHandle handle +) => m_handles.TryGetValue(id, out handle); +``` + +Avoid (`Try*` that does not return `bool`): + +```csharp +public AssetHandle? TryResolve(AssetID id) => m_handles.GetValueOrDefault(id); +``` + +## NM-04 Asynchronous methods end with `Async` + +A method that returns `Task`, `Task`, `ValueTask` or `ValueTask` ends with `Async`. Overrides and interface implementations follow their contract. xUnit test methods do not take the suffix. + +```csharp +public async Task CompileAsync( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async Task Compile( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +## NM-05 Properties and indexers are camelCase + +Every property is camelCase, whatever its accessibility. A `bool` property starts with `is`, `has` or `can`, or is a past participle that states a condition, such as `disposed`. + +```csharp +public Transform transform { get; } +public bool isMissing => m_source is null; +public int count { get; private set; } +``` + +Avoid: + +```csharp +public Transform Transform { get; } +public bool Missing => m_source is null; +public int Count { get; private set; } +``` + +## NM-06 Instance fields + +- A private or protected instance field is `m_` + camelCase, whether or not it is `readonly`. +- An internal or public instance field is camelCase without a prefix. Such fields appear only in frame-local workspaces, interop structs and math types. +- One declaration declares one field. + +```csharp +public sealed class RenderQueue +{ + private readonly List m_items = []; + private int m_generation; +} + +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid: + +```csharp +public sealed class RenderQueue +{ + private readonly List _items = []; + private int generation, frameIndex; +} +``` + +## NM-07 Constants + +Every `const` is `C_` + UPPER_SNAKE: private, internal and public constants, and constants local to a method. + +```csharp +public sealed class SceneFile +{ + public const string C_DEFAULT_EXTENSION = ".iscene"; + private const int C_MAX_COUNT = 64; + + public void Flush() + { + const int C_BATCH_SIZE = 256; + Write(C_BATCH_SIZE); + } +} +``` + +Avoid: + +```csharp +public sealed class SceneFile +{ + public const string DefaultExtension = ".iscene"; + private const int MAX_COUNT = 64; + + public void Flush() + { + const int batchSize = 256; + Write(batchSize); + } +} +``` + +## NM-08 `static readonly` fields + +Every `static readonly` field is UPPER_SNAKE without any prefix, whatever its accessibility. The `C_` prefix is reserved for `const`. + +```csharp +public readonly struct Color +{ + public static readonly Color RED = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions SERIALIZER_OPTIONS = new(JsonSerializerDefaults.Web); +} +``` + +Avoid: + +```csharp +public readonly struct Color +{ + public static readonly Color Red = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions S_SERIALIZER_OPTIONS = new(); + private static readonly JsonSerializerOptions s_serializerOptions = new(); + private static readonly JsonSerializerOptions C_SERIALIZER_OPTIONS = new(); +} +``` + +## NM-09 Static mutable fields + +A private static mutable field is `s_` + camelCase. Product code does not declare non-private static mutable fields; shared process state belongs to an explicit host. + +```csharp +public sealed class HandleAllocator +{ + private static int s_nextID; +} +``` + +Avoid: + +```csharp +public sealed class HandleAllocator +{ + private static int m_nextID; + public static int nextID; +} +``` + +## NM-10 Events + +An event is camelCase, like a property. Name it with a past participle or as `xxxChanged` / `xxxRequested`. Its delegate type is a nullable `Action` or `Action<...>`. + +```csharp +public event Action? redrawRequested; +public event Action? assetReloaded; +``` + +Avoid: + +```csharp +public event Action? RedrawRequested; +public event EventHandler? OnRedraw; +``` + +## NM-11 Enums + +- A single-value enum has a singular name. A `[Flags]` enum has a plural name or ends with `Flags`. +- Members are PascalCase and never start with an underscore. +- `[Flags]` values are written as `1 << n`, with `None = 0`. Combined values are expressed with member names. +- One member per line, no trailing comma, no blank lines between members. + +```csharp +public enum EditorPlayModeState +{ + Editing, + Compiling, + Playing +} + +[Flags] +public enum EditorViewportNavigationCapabilities +{ + None = 0, + Orbit = 1 << 0, + Pan = 1 << 1, + Zoom = 1 << 2, + All = Orbit | Pan | Zoom +} +``` + +Avoid: + +```csharp +[Flags] +public enum EditorViewportNavigationCapability +{ + None = 0, + Orbit = 1, + Pan = 0x2, + Zoom = 4, +} +``` + +## NM-12 Parameters, local variables and tuple elements + +Use camelCase and whole words. Do not use Hungarian prefixes. Do not give a local variable or a parameter the name of a property of the same type, except for constructor parameters (E-08). + +| Situation | Name | +| --- | --- | +| `CancellationToken` parameter | `cancellationToken` | +| Default `catch` variable | `exception` | +| Unused lambda parameter | `_` | +| Loop index | `i`, `j`, `index` | +| Coordinate or component | `x`, `y`, `z`, `w` | + +Apart from this table, do not use one- or two-character names. `id` and `io` are whole words and are allowed. + +```csharp +public async Task SaveAsync( + Stream destination, + CancellationToken cancellationToken +) { + (int width, int height) size = Measure(); + foreach (AssetEntry entry in m_entries) + { + await entry.WriteAsync(destination, size, cancellationToken).ConfigureAwait(false); + } +} +``` + +Avoid: + +```csharp +public async Task SaveAsync( + Stream dst, + CancellationToken token +) { + (int Width, int Height) sz = Measure(); + foreach (AssetEntry e in m_entries) + { + await e.WriteAsync(dst, sz, token).ConfigureAwait(false); + } +} +``` + +## NM-13 Acronyms + +- A two-letter acronym is upper case wherever a PascalCase word would start: `ID`, `IO`, `UI`. This includes `ID`: write `AssetID`, `persistentID`, `GetID`, never `AssetId`. +- A plural keeps the acronym upper case and adds a lower-case `s`: `sourceIDs`, `GetAssetIDs`. +- An acronym of three or more letters is written as an ordinary word: `Json`, `Http`, `Ktx`, `Sdl`. +- When an acronym starts a camelCase identifier, the whole acronym is lower case: `id`, `ioStatus`, `uiScale`. +- In UPPER_SNAKE names every word is upper case: `C_MAX_ID`. + +```csharp +public sealed class JsonAssetWriter +{ + public AssetID persistentID { get; } + public IOStatus ioStatus { get; } + public float uiScale { get; set; } + + public AssetID GetID(string id) => m_ids[id]; +} +``` + +Avoid: + +```csharp +public sealed class JSONAssetWriter +{ + public AssetId persistentId { get; } + public IoStatus IOStatus { get; } + public float UIScale { get; set; } + + public AssetId GetId(string ID) => m_ids[ID]; +} +``` diff --git a/.agents/rulebook/csharp-style/04-types.md b/.agents/rulebook/csharp-style/04-types.md new file mode 100644 index 000000000..3e4e32c8f --- /dev/null +++ b/.agents/rulebook/csharp-style/04-types.md @@ -0,0 +1,234 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 4. Type declarations + +## T-01 Write every access modifier + +Every type and every member states its accessibility, including each file of a `partial` type. Interface members do not write `public`. + +```csharp +internal sealed partial class AssetLoader +{ + private int m_generation; +} + +public interface IEventSink +{ + void Publish(EventRecord record); +} +``` + +Avoid: + +```csharp +sealed partial class AssetLoader +{ + int m_generation; +} +``` + +## T-02 Modifier order + +Accessibility, then `static`, `extern`, `new`, then `virtual` / `abstract` / `sealed` / `override`, then `readonly`, `unsafe`, `required`, `volatile`, `async`, `partial`. + +```csharp +public static readonly Color RED = FromBytes(255, 0, 0); + +private static async Task RunAsync() +{ + await Task.Yield(); + Publish(); +} + +public sealed override string ToString() => name; + +public override readonly int GetHashCode() => m_value; + +internal static unsafe partial class NativeMethods; +``` + +Avoid: + +```csharp +public readonly override int GetHashCode() => m_value; + +static private int s_count; +``` + +## T-03 Classes are sealed by default + +Every class is `static`, `abstract` or `sealed`. Leave a class open only when it is a designed extension point, and document the derivation contract in its XML documentation. Nested private classes are sealed too. + +```csharp +public sealed class EventDispatcher; + +internal static class PathUtility +{ + internal static string Normalize(string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public class EventDispatcher; +``` + +## T-04 Records + +- A reference-type data contract is a `sealed record` with positional parameters, ending in `;`. +- A small value type is a `readonly record struct`. +- Positional parameters are properties, so they are camelCase. + +```csharp +public sealed record AssetChangedEvent( + string path, + WatcherChangeTypes change +); + +public readonly record struct AssetID(Guid value); +``` + +Avoid: + +```csharp +public record AssetChangedEvent(string Path, WatcherChangeTypes Change); + +public record struct AssetID(Guid value); +``` + +## T-05 Structs + +A struct is `readonly` by default. Use a mutable struct only for interop layouts and math types that are assigned field by field; its fields are public and camelCase. + +```csharp +public readonly struct FrameRange +{ + public int start { get; } + public int count { get; } +} + +[StructLayout(LayoutKind.Sequential)] +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid (a mutable struct that is not an interop or math type): + +```csharp +public struct FrameRange +{ + public int start { get; set; } + public int count { get; set; } +} +``` + +## T-06 Base lists and generic constraints on types + +- The base list stays on the line of the type name. +- Each `where` clause of a type is on its own line, indented four spaces. The opening brace stays on its own line. + +```csharp +public abstract class EditorDrop : EditorDrop + where TSource : IdentityObject + where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +Avoid: + +```csharp +public abstract class EditorDrop + : EditorDrop where TSource : IdentityObject where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +## T-07 Primary constructors + +- A record uses a primary constructor. A record whose constructor validates or normalizes its arguments uses an ordinary constructor, and a record populated through `init` or `required` properties declares none. +- A class or struct may use a primary constructor to receive its dependencies. When it does, it uses the parameters directly and does not copy them into `m_` fields. +- Use an ordinary constructor with `m_` fields when arguments need validation or the fields must be `readonly`. +- Primary constructor parameters follow P-01. A base list follows the closing parenthesis as `) : Base`, with the opening brace on its own line. Without a base list the type body starts with `) {`. + +```csharp +internal sealed class TogglePlayModeAction(EditorPlayMode playMode) : EditorAction +{ + protected override bool CanExecute() => playMode.state != EditorPlayModeState.Compiling; +} + +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) : IGenerationChange +{ + public void Apply() => migration.Transfer(runtimeSession); +} + +internal sealed class FrameScope( + RenderGraph graph, + int frameIndex +) { + public bool isFirst => frameIndex == 0; + + public void Begin() => graph.BeginFrame(frameIndex); +} +``` + +Avoid (base list on a separate line, parameters copied into fields): + +```csharp +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) + : IGenerationChange +{ + private readonly RuntimeSession m_runtimeSession = runtimeSession; + private readonly ISceneReloadStateTransfer m_migration = migration; +} +``` + +## T-08 Nested types + +A nested type is placed at the end of its containing type. Nest a type only when the containing type is its only user. + +```csharp +public sealed class AssetCache +{ + private readonly Dictionary m_entries = []; + + public int count => m_entries.Count; + + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } +} +``` + +Avoid (the nested type comes first): + +```csharp +public sealed class AssetCache +{ + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } + + private readonly Dictionary m_entries = []; +} +``` diff --git a/.agents/rulebook/csharp-style/05-members.md b/.agents/rulebook/csharp-style/05-members.md new file mode 100644 index 000000000..47021a8b5 --- /dev/null +++ b/.agents/rulebook/csharp-style/05-members.md @@ -0,0 +1,192 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 5. Member declarations + +## M-01 Property forms + +- An auto-property is written on one line: `{ get; }`, `{ get; set; }`, `{ get; init; }`, `{ get; private set; }`. +- A read-only computed property uses an expression body. +- A property whose accessors contain logic is expanded: the braces are on their own lines, an accessor with a single expression uses `=>`, an accessor with statements uses a block. + +```csharp +public string name { get; } +public int count { get; private set; } +public bool isEmpty => m_items.Count == 0; + +public float scale +{ + get => m_scale; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + m_scale = value; + } +} +``` + +Avoid: + +```csharp +public bool isEmpty { get { return m_items.Count == 0; } } +public float scale { get => m_scale; set => m_scale = value; } +``` + +## M-02 Expression-bodied members + +- A method, property, indexer or operator whose body is one expression (one `return`, one call or one assignment) uses an expression body. +- A body with control flow, several statements or `try` uses a block. +- A constructor always uses a block body. + +```csharp +public override string ToString() => $"{name} ({count})"; + +public static bool operator ==( + Color left, + Color right +) => left.Equals(right); + +public RenderQueue(int capacity) +{ + m_items = new List(capacity); +} +``` + +Avoid: + +```csharp +public override string ToString() +{ + return $"{name} ({count})"; +} + +public RenderQueue(int capacity) => m_items = new List(capacity); +``` + +## M-03 Placement of `=>` in expression-bodied members + +1. When the whole member fits on one line, `=> expression` stays on the declaration line. +2. After a multi-line parameter list, the body starts on the line of the closing parenthesis: `) => expression`. When the expression is a call, an object creation or a collection that does not fit, break inside it (A-02). +3. When the signature is on one line and the body does not fit after it, move `=>` to the next line, indented four spaces. +4. After a wrapped `=>`, a brace-delimited expression (a `switch` expression, an object initializer or a `with` expression) puts its braces on their own lines at the column of the declaration, with its contents indented four spaces from the declaration. +5. After a wrapped `=>`, a call or object creation that must break follows A-02 relative to the `=>` line, and operator continuation lines align with the first operand (F-05). +6. `=>` never ends a line with the expression on the next line, and never stands alone on a line. + +```csharp +public bool isMissing => m_source is null; + +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); + +public static Color Lerp( + Color from, + Color to, + float amount +) => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount +); + +protected override EditorActionState Query(EditorActionContext context) + => playMode.state switch +{ + EditorPlayModeState.Editing => new EditorActionState(true, true), + EditorPlayModeState.Playing => new EditorActionState(true, false), + _ => EditorActionState.DISABLED +}; + +internal bool IsActiveFor(object? target) + => m_isActive + && m_activeTarget is not null + && m_activeTarget.Matches(m_activeInteractions, target); + +protected override EditorActionState Describe(EditorActionContext context) + => new EditorActionState( + isVisible: context.selection.count > 0, + isEnabled: playMode.state == EditorPlayModeState.Editing, + displayName: "Duplicate Selection" + ); +``` + +Avoid (`=>` left at the end of the line, braces indented under the wrapped `=>`, closing parenthesis left on the last argument): + +```csharp +protected override EditorActionState Query(EditorActionContext context) => + playMode.state switch + { + EditorPlayModeState.Editing => new EditorActionState(true, true), + _ => EditorActionState.DISABLED + }; + +public static Color Lerp( + Color from, + Color to, + float amount +) + => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount); +``` + +## M-04 Field and property initializers + +- A field or property initializer uses a target-typed expression so the type is written once: `= new(...)` or `= []`. +- One declaration declares one field or one local variable. + +```csharp +private readonly Dictionary m_commands = new(StringComparer.Ordinal); +private readonly List m_items = []; + +public IReadOnlyList tags { get; init; } = []; +``` + +Avoid: + +```csharp +private readonly Dictionary m_commands = new Dictionary(StringComparer.Ordinal); +private readonly List m_items = new List(); +``` + +## M-05 Attributes + +- Each attribute is on its own line above the declaration. One pair of brackets holds one attribute. +- Omit the `Attribute` suffix. Omit empty parentheses. +- An attribute on a parameter stays on the line of the parameter. +- Attribute arguments break like any other argument list (A-02). + +```csharp +[Fact] +[Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty] +public float speed { get; set; } + +public bool TryRead( + string key, + [NotNullWhen(true)] out string? value +) => m_values.TryGetValue(key, out value); +``` + +Avoid: + +```csharp +[Fact, Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty()] public float speed { get; set; } +``` diff --git a/.agents/rulebook/csharp-style/06-member-order.md b/.agents/rulebook/csharp-style/06-member-order.md new file mode 100644 index 000000000..b217ccccc --- /dev/null +++ b/.agents/rulebook/csharp-style/06-member-order.md @@ -0,0 +1,123 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, members] +--- +# 6. Member order + +## O-01 Group order + +Members of a type appear in these groups, in this order, with one blank line between groups: + +1. Constants (`const`). +2. Static fields: `static readonly` first, then static mutable. +3. Instance fields: `readonly` first, then mutable. +4. Constructors. +5. Public members. +6. Protected and internal members. +7. Private members. +8. Nested types. + +Inside groups 5, 6 and 7 the order is: properties, events, instance methods, static methods. An explicit interface implementation follows the public members of the interface it implements. + +```csharp +public sealed class RenderQueue : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + + private static readonly RenderItemComparer COMPARER = new(); + + private readonly List m_items; + private bool m_disposed; + + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + public int count => m_items.Count; + + public event Action? flushed; + + public void Enqueue(RenderItem item) + { + ObjectDisposedException.ThrowIf(m_disposed, this); + m_items.Add(item); + } + + public void Dispose() + { + m_items.Clear(); + m_disposed = true; + } + + internal void Sort() => m_items.Sort(COMPARER); + + private void NotifyFlushed() => flushed?.Invoke(); + + private sealed class RenderItemComparer : IComparer + { + public int Compare( + RenderItem left, + RenderItem right + ) => left.order.CompareTo(right.order); + } +} +``` + +Avoid (a private method before the public members, fields after the constructor): + +```csharp +public sealed class RenderQueue +{ + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + private void NotifyFlushed() => flushed?.Invoke(); + + private readonly List m_items; + + public int count => m_items.Count; + + private const int C_INITIAL_CAPACITY = 64; +} +``` + +## O-02 Keep related members together + +Members of the same accessibility and kind are contiguous. Overloads are adjacent and ordered from fewest to most parameters. + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} + +public void Clear() => m_items.Clear(); + +private void Submit(RenderItem item) => m_items.Add(item); +``` + +Avoid (overloads separated, a private method between public methods): + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +private void Submit(RenderItem item) => m_items.Add(item); + +public void Clear() => m_items.Clear(); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} +``` diff --git a/.agents/rulebook/csharp-style/07-braces.md b/.agents/rulebook/csharp-style/07-braces.md new file mode 100644 index 000000000..b0a39f07e --- /dev/null +++ b/.agents/rulebook/csharp-style/07-braces.md @@ -0,0 +1,396 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 7. Braces and blocks + +## B-01 Braces are on their own lines + +The opening brace of a type, a method body, an accessor, a control statement, a lambda block, an object or collection initializer and a `switch` expression is on its own line, aligned with the start of the construct. The closing brace is on its own line, aligned with the opening brace. + +The only places where an opening brace shares a line with other code are: + +- `) {` after a multi-line parameter list or a multi-line statement header (B-02). +- A single-line construct: an auto-property, a short initializer, a property pattern, a compact guard (B-05). +- An empty body `{}` (B-07). + +```csharp +public void Flush() +{ + foreach (RenderItem item in m_items) + { + Draw(item); + m_drawn++; + } + + try + { + Present(); + } + catch (DeviceLostException exception) + { + m_log.Error(exception.Message); + throw; + } + finally + { + m_items.Clear(); + } +} +``` + +Avoid: + +```csharp +public void Flush() { + foreach (RenderItem item in m_items) { + Draw(item); + } + + try { Present(); } + catch (DeviceLostException) { throw; } + finally { m_items.Clear(); } +} +``` + +## B-02 `) {` after a multi-line parameter list or statement header + +When a parameter list is expanded over several lines (P-01) and the body follows it directly, the opening brace shares the line of the closing parenthesis: `) {`. The closing brace aligns with the start of the declaration. This applies to methods, constructors, local functions, operators and primary constructors without a base list. The same form closes a control statement whose header spans several lines (W-05). + +```csharp +internal void Register( + string commandID, + Action command +) { + ArgumentException.ThrowIfNullOrWhiteSpace(commandID); + ArgumentNullException.ThrowIfNull(command); + m_commands.Add(commandID, command); +} +``` + +Avoid (brace on its own line after a multi-line parameter list, several parameters on one line): + +```csharp +internal void Register( + string commandID, + Action command +) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +internal void Unregister(string commandID, Action command) +{ + m_commands.Remove(commandID); + m_dirty = true; +} +``` + +## B-03 Clauses between `)` and the body + +A constructor initializer (`: base(...)`, `: this(...)`) or a `where` clause sits between the parameter list and the body. + +- After a multi-line parameter list, the clause follows the closing parenthesis on the same line: `) : this(...)` or `) where T : class`. The opening brace is then on its own line. +- After a single-line signature, the clause is on the next line, indented four spaces. The opening brace is on its own line. +- Additional `where` clauses each take their own line, aligned with the first `where`. + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) + : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class +{ + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} + +public TTarget Convert( + TSource source, + bool required +) where TSource : IdentityObject + where TTarget : class +{ + object converted = ConvertCore(source, typeof(TTarget), required); + return (TTarget)converted; +} + +public T Find(string id) + where T : class +{ + object found = FindCore(typeof(T), id); + return (T)found; +} +``` + +Avoid (clause on its own line after a multi-line parameter list, clause on the signature line of a single-line signature, `) {` after a clause): + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) + : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class { + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} +``` + +## B-04 Lambda bodies + +- **Expression body that fits:** `x => expression` on one line. +- **Block body:** `=>` ends the line; the braces are on their own lines, aligned with the start of the statement that contains the lambda. The closing brace is followed directly by `)`, `,` or `;`. This holds when the lambda has a multi-line parameter list too: `) =>`, then the brace on the next line. +- **Expression body that is a call or object creation and does not fit:** the call starts on the `=>` line and breaks inside its parentheses (A-02). +- **Any other expression body that does not fit:** wrap it in parentheses. `(` follows `=>`, the expression is indented four spaces, and `)` is on its own line. + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +entries.Sort(( + left, + right +) => +{ + int byName = string.CompareOrdinal(left.name, right.name); + return byName != 0 ? byName : left.order.CompareTo(right.order); +}); + +IEnumerable blended = pairs.Select(pair => new Color( + pair.from.r + (pair.to.r - pair.from.r) * amount, + pair.from.g + (pair.to.g - pair.from.g) * amount, + pair.from.b + (pair.to.b - pair.from.b) * amount +)); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid (brace on the `=>` line, block squeezed onto one line, expression body moved to the next line without parentheses): + +```csharp +m_dispatcher.Subscribe(entry => { + m_pending.Add(entry); + m_dirty = true; +}); + +m_dispatcher.Subscribe(entry => { m_pending.Add(entry); m_dirty = true; }); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## B-05 Control statement bodies always use braces + +1. The body of `if`, `else`, `for`, `foreach`, `while`, `do`, `using`, `lock` and `fixed` is always enclosed in braces, each brace on its own line. +2. One compact form is permitted where it reads better: an `if` without `else` whose body is a single short statement may be written entirely on one line, `if (condition) statement;`. Use it for guard clauses and keep a run of adjacent guards in the same form. +3. A body on the next line without braces is never allowed. +4. Stacked `using` or `fixed` headers that share one braced body are the only headers that may follow each other without braces in between. + +```csharp +if (m_disposed) +{ + return; +} + +while (reader.Read()) +{ + Process(reader.current); +} + +foreach (RenderItem item in m_items) +{ + if (item is null) continue; + if (!item.isVisible) continue; + + Draw(item); +} + +fixed (byte* source = input) +fixed (byte* target = output) +{ + Copy(source, target, length); +} +``` + +Avoid: + +```csharp +if (m_disposed) + return; + +foreach (RenderItem item in m_items) + Draw(item); + +foreach (AssetEntry entry in m_entries) + if (entry.isMissing) + missing.Add(entry); + +foreach (RenderItem item in m_items) Draw(item); +``` + +## B-06 `if` / `else` chains + +Every branch of an `if … else if … else` chain uses braces. The compact one-line form (B-05) is not used when the `if` has an `else`. + +```csharp +if (state == EditorPlayModeState.Editing) +{ + EnterPlayMode(); +} +else if (state == EditorPlayModeState.Playing) +{ + ExitPlayMode(); +} +else +{ + m_log.Warning("Play mode is changing."); +} +``` + +Avoid: + +```csharp +if (state == EditorPlayModeState.Editing) EnterPlayMode(); +else ExitPlayMode(); + +if (state == EditorPlayModeState.Editing) + EnterPlayMode(); +else +{ + m_log.Warning("Play mode is already active."); + ExitPlayMode(); +} +``` + +## B-07 Empty bodies + +- An empty type ends with a semicolon and has no braces. +- An empty method, constructor, accessor, local function or lambda body is `{}`, with no space inside, on the line where the header ends. +- An empty `catch` block is not empty: it contains a comment that explains why the exception is ignored (X-04). +- A property pattern that matches any non-null value is written `{ }`. + +```csharp +public sealed class EmptyPayload; + +public interface IMarker; + +protected virtual void OnActivated() {} + +public NullSink( + string name, + int capacity +) {} + +public NamedSink(string name) + : base(name) {} +``` + +Inside a method: + +```csharp +Action noop = () => {}; + +if (value is { } resolved) +{ + Use(resolved); +} +``` + +Avoid: + +```csharp +public sealed class EmptyPayload +{ +} + +public sealed class OtherPayload { } + +protected virtual void OnActivated() +{ +} + +protected virtual void OnDeactivated() { } +``` + +## B-08 `else`, `catch`, `finally` and `while` + +`else`, `catch` and `finally` start a new line after the closing brace. The `while` of a `do … while` loop starts a new line too. + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} +while (read > 0); +``` + +Avoid: + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} while (read > 0); +``` + +## B-09 One statement per line + +A line holds one statement. The statement after a `case` label starts on the next line. Nothing follows an opening brace on its line. The compact guard of B-05 is the only construct in which a statement shares the line of its header. + +```csharp +switch (key) +{ + case KeyCode.Left: + cursor--; + break; + case KeyCode.Right: + cursor++; + break; +} +``` + +Avoid: + +```csharp +switch (key) +{ + case KeyCode.Left: cursor--; break; + case KeyCode.Right: cursor++; break; +} + +x = 0; y = 0; +``` diff --git a/.agents/rulebook/csharp-style/08-parameters.md b/.agents/rulebook/csharp-style/08-parameters.md new file mode 100644 index 000000000..80fc8736c --- /dev/null +++ b/.agents/rulebook/csharp-style/08-parameters.md @@ -0,0 +1,293 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 8. Parameter and argument lists + +## P-01 Parameter lists: one line for zero or one parameter, fully expanded for two or more + +A declaration with two or more parameters breaks after the opening parenthesis, puts each parameter on its own line indented four spaces, and puts the closing parenthesis on its own line aligned with the start of the declaration. A declaration with zero or one parameter stays on one line. + +This applies to methods, constructors, local functions, delegates, operators, primary constructors and lambdas. + +```csharp +public void Clear() => m_commands.Clear(); + +public void Remove(string commandID) => m_commands.Remove(commandID); + +public void Register( + string commandID, + Action command +) { + m_commands.Add(commandID, command); + m_dirty = true; +} + +public delegate void AssetCallback( + AssetID id, + AssetHandle handle +); +``` + +Local functions and lambdas follow the same rule: + +```csharp +void Visit( + Node node, + int depth +) { + m_visited.Add(node); + m_depths[node] = depth; +} + +bool duplicate = updated.Where(( + _, + candidateIndex +) => candidateIndex != index).Any(); +``` + +Avoid: + +```csharp +public void Register(string commandID, Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register(string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register( + string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +bool duplicate = updated.Where((_, candidateIndex) => candidateIndex != index).Any(); +``` + +## P-02 What follows the closing parenthesis of a multi-line parameter list + +| Followed by | Form | +| --- | --- | +| Block body | `) {` | +| Empty body | `) {}` | +| Expression body | `) => expression;` — when the expression must break, it breaks inside its own delimiters: `) => new(` … `);` | +| No body (interface, abstract, delegate, record) | `);` | +| Constructor initializer | `) : base(...)` or `) : this(...)`, opening brace on its own line | +| `where` clause | `) where T : class`, opening brace on its own line | +| Base list of a primary constructor | `) : Base`, opening brace on its own line | +| Lambda body | `) =>`, then the expression, or the opening brace on its own line | + +```csharp +public interface IAssetStore +{ + Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ); +} + +public sealed class NullAssetStore : IAssetStore +{ + public NullAssetStore( + string name, + int capacity + ) {} + + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) => Task.FromResult(AssetHandle.MISSING); +} +``` + +Avoid: + +```csharp +public sealed class NullAssetStore : IAssetStore +{ + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) + => Task.FromResult(AssetHandle.MISSING); +} +``` + +## P-03 Parameter details + +- A default value is written `= value`, with one space on each side of `=`. +- `this`, `ref`, `out`, `in` and `params` are separated from the type by one space. +- `CancellationToken cancellationToken` is always the last parameter. + +```csharp +public Task LoadAsync( + AssetID id, + bool required = true, + CancellationToken cancellationToken = default +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +Avoid: + +```csharp +public Task LoadAsync( + CancellationToken cancellationToken, + AssetID id, + bool required=true +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +## A-01 Argument lists stay on one line when they fit + +The arguments of a call, an object creation or a constructor initializer stay on one line whenever the whole statement fits within the line width. + +```csharp +m_commands.Add(commandID, command); +var buffer = new VertexBuffer(device, capacity, VertexLayout.DEFAULT); +``` + +Avoid (a short call broken for no reason): + +```csharp +m_commands.Add( + commandID, + command +); +``` + +## A-02 Broken argument lists: one argument per line, closing parenthesis on its own line + +When an argument list does not fit on one line: + +- The opening parenthesis ends its line. +- Each argument is on its own line, indented four spaces from the line that contains the opening parenthesis. +- The closing parenthesis is on its own line, aligned with the start of the line that contains the opening parenthesis. Whatever follows the call — `;`, `.Next(...)`, `,` or an outer closing delimiter — follows that parenthesis. +- Nested calls apply the same rule one level deeper. + +This holds for every call, including `new`, `throw new`, `await`, `return`, attribute arguments and constructor initializers. + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken +).ConfigureAwait(false); + +throw new ArgumentException( + $"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode) +); + +var result = new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); + +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); +``` + +Avoid (closing parenthesis left on the last argument, first argument left on the opening line, several arguments packed on a line, arguments aligned with the parenthesis): + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken).ConfigureAwait(false); + +return await m_textureCompiler.CompileKtxAsync(encoded, + texture.slot.colorSpace, cancellationToken).ConfigureAwait(false); + +throw new ArgumentException($"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode)); +``` + +## A-03 Hugging a single multi-line argument + +When exactly one argument spans several lines, and that argument is a lambda, an object initializer, an anonymous object or a collection expression, the arguments may all start on the line of the opening parenthesis. The multi-line argument is laid out by its own rule, and the closing parenthesis follows its closing delimiter. + +When two or more arguments span several lines, expand the list (A-02). + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +Task task = Task.Run(() => +{ + Compile(source); + Publish(source); +}, cancellationToken); + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +scheduler.Schedule( + () => + { + Compile(source); + Publish(source); + }, + exception => + { + m_log.Error(exception.Message); + m_failed = true; + } +); +``` + +Avoid (two multi-line arguments hugged together): + +```csharp +scheduler.Schedule(() => +{ + Compile(source); + Publish(source); +}, exception => +{ + m_log.Error(exception.Message); + m_failed = true; +}); +``` + +## A-04 Named arguments + +A named argument is written `name: value`, with no space before the colon and one space after it. Name adjacent `bool` or numeric literal arguments whose meaning is not obvious from the call. + +```csharp +var state = new EditorActionState(true, true, displayName: "Enter Play Mode"); +window.Resize(width: 1280, height: 720); +``` + +Avoid: + +```csharp +window.Resize(width : 1280, height:720); +texture.Update(true, false, 0, 4); +``` diff --git a/.agents/rulebook/csharp-style/09-line-breaks.md b/.agents/rulebook/csharp-style/09-line-breaks.md new file mode 100644 index 000000000..753016f2e --- /dev/null +++ b/.agents/rulebook/csharp-style/09-line-breaks.md @@ -0,0 +1,142 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 9. Line breaks + +## W-01 Binary operators lead the continuation line + +When an expression breaks at `&&`, `||`, `??`, `+`, `-`, `|` or another binary operator, the operator starts the next line. Continuation lines align with the first operand (F-05). + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +string message = "The asset database could not be opened because " + + "another editor instance holds the workspace lock."; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; +``` + +Avoid: + +```csharp +bool changed = previous.width != current.width || + previous.height != current.height; +``` + +## W-02 Conditional expressions + +A conditional expression stays on one line when it fits. Otherwise `?` and `:` each start a line, aligned with the condition (F-05). Do not nest conditional expressions; use a `switch` expression or an `if` statement. + +```csharp +int order = byName != 0 ? byName : left.order.CompareTo(right.order); + +ShaderCompilationResult result = pending.IsCompletedSuccessfully + ? pending.Result + : new ShaderCompilationResult(null, diagnostics); +``` + +Avoid: + +```csharp +ShaderCompilationResult result = pending.IsCompletedSuccessfully ? + pending.Result : + new ShaderCompilationResult(null, diagnostics); + +string label = count == 0 ? "none" : count == 1 ? "one" : "many"; +``` + +## W-03 Call chains + +A call chain stays on one line when it fits. Otherwise the first link stays on the statement line and every following `.` (or `?.`) starts a line, indented four spaces from the start of the statement. + +```csharp +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .OrderBy(static name => name, StringComparer.Ordinal) + .ToList(); +``` + +Avoid: + +```csharp +List names = m_entries.Where(static entry => !entry.isMissing). + Select(static entry => entry.displayName). + ToList(); +``` + +## W-04 Assignments and arrows + +- Never break a line directly before or after `=`. Keep the start of the right-hand side on the line of the `=` and break inside it: after an opening parenthesis (A-02), before an operator (W-01) or before a `.` (W-03). The only exception is the opening bracket of a multi-line collection expression, which takes its own line (I-03). +- A lambda `=>` always ends its line when the body moves down; the body then follows B-04. An expression body that is not a call is wrapped in parentheses. +- The `=>` of a `switch` expression arm stays on the line of the arm. +- The `=>` of an expression-bodied member follows M-03. + +```csharp +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +string intermediate = + scoped.GetNativeBuildRoot(componentDescriptor, configuration, targetArchitecture); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## W-05 Multi-line conditions and statement headers + +- `is` stays on the line of its left operand. `or` and `and` start their continuation lines. +- When the parenthesized header of `if`, `else if`, `while`, `for`, `foreach`, `switch`, `lock`, `using` or `fixed` spans several lines, its closing parenthesis is on its own line, aligned with the keyword, and the opening brace follows it: `) {`. This mirrors the multi-line parameter list (B-02). + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace +) { + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode) +) { + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +} + +foreach (KeyValuePair dependency in HostDependencyManifest + .GetInnoRuntimeAssemblies(roots) + .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) +) { + Enqueue(dependency.Key, dependency.Value); +} +``` + +Avoid: + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace) +{ + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode)) + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +``` diff --git a/.agents/rulebook/csharp-style/10-initializers.md b/.agents/rulebook/csharp-style/10-initializers.md new file mode 100644 index 000000000..0f23ac963 --- /dev/null +++ b/.agents/rulebook/csharp-style/10-initializers.md @@ -0,0 +1,150 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 10. Initializers and collections + +## I-01 Object initializers + +- A short initializer stays on one line with one space inside each brace: `new Foo { a = 1 }`. +- Otherwise the opening brace is on its own line, aligned with the start of the statement; each member is on its own line, indented four spaces; the closing brace is on its own line. +- Omit the empty `()` when an initializer is present. +- `with` expressions and anonymous objects follow the same rule. + +```csharp +var options = new JsonSerializerOptions { WriteIndented = true }; + +var request = new GameBuildRequest +{ + profile = profile, + outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release +}; + +RenderSettings updated = settings with +{ + exposure = 1.5f, + toneMapping = ToneMapping.Aces +}; +``` + +Avoid: + +```csharp +var request = new GameBuildRequest() { + profile = profile, outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release, +}; +``` + +## I-02 Collections use collection expressions + +- Arrays, `List`, spans and immutable collections are written as collection expressions: `[a, b]`, `[]`, `[.. source]`. +- A spread operator is followed by one space: `[.. source, extra]`. +- Use `new T(...)` when a constructor argument (a capacity, a comparer) is needed, and `new T[n]` for a fixed-size buffer. +- Do not write `new[] { ... }`, `new T[] { ... }`, `new List { ... }` or `Array.Empty()`. + +```csharp +List items = []; +string[] extensions = [".png", ".jpg", ".ktx"]; +List all = [.. builtIn, .. custom, "fallback"]; +var byName = new Dictionary(StringComparer.Ordinal); +var buffer = new byte[C_BUFFER_SIZE]; +``` + +Avoid: + +```csharp +List items = new List(); +string[] extensions = new[] { ".png", ".jpg", ".ktx" }; +List all = [..builtIn, ..custom, "fallback"]; +string[] none = Array.Empty(); +``` + +## I-03 Multi-line collection expressions + +- With two or more elements that do not fit on one line: one element per line, indented four spaces, and the closing bracket on its own line. +- As the value of a declaration or assignment, the opening bracket is on its own line, aligned with the start of the statement, like the brace of an object initializer. +- As an argument, the opening bracket follows the opening parenthesis or the preceding argument (A-03). +- A single element that itself spans several lines hugs the brackets: `[new X(` … `)]`. + +```csharp +string[] searchPaths = +[ + Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), + Path.Combine(root, "Library", "Imported") +]; + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); +``` + +Avoid: + +```csharp +string[] searchPaths = [Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), Path.Combine(root, "Library", "Imported")]; + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message)]); +``` + +## I-04 `switch` expressions + +`value switch` is on one line; the opening brace is on its own line; each arm is on its own line with its `=>`; the discard arm is last. + +```csharp +string label = state switch +{ + EditorPlayModeState.Editing => "Enter Play Mode", + EditorPlayModeState.Compiling => "Compiling", + EditorPlayModeState.Playing => "Exit Play Mode", + _ => throw new ArgumentOutOfRangeException(nameof(state)) +}; +``` + +Avoid: + +```csharp +string label = state switch { EditorPlayModeState.Editing => "Enter", _ => "Exit", }; +``` + +## I-05 No trailing commas + +The last item of an object initializer, a collection, an enum, a `switch` expression or an anonymous object is not followed by a comma. + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces +} +``` + +Avoid: + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces, +} +``` diff --git a/.agents/rulebook/csharp-style/11-spacing.md b/.agents/rulebook/csharp-style/11-spacing.md new file mode 100644 index 000000000..d4503f52f --- /dev/null +++ b/.agents/rulebook/csharp-style/11-spacing.md @@ -0,0 +1,184 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 11. Spacing and blank lines + +## S-01 Spaces + +| Position | Rule | Example | +| --- | --- | --- | +| Control keyword and `(` | One space | `if (x)`, `foreach (T item in items)` | +| Method name, `typeof`, `nameof`, `default` and `(` | No space | `Draw(item)`, `typeof(int)` | +| `new` and `(` or `[` | No space | `new()`, `new[]` | +| Inside parentheses and brackets | No space | `Add(a, b)`, `items[0]` | +| Before an index bracket | No space | `items[0]` | +| Comma | None before, one after | `Add(a, b)` | +| Semicolon in `for` | None before, one after | `for (int i = 0; i < n; i++)` | +| Binary operators, assignment, `=>`, `??`, `?:` | One on each side | `a + b`, `x => x.id` | +| Unary operators | Attached to the operand | `!ready`, `-value`, `i++` | +| After a cast | No space | `(float)count` | +| Member access `.`, `?.`, `->` | No space | `entry?.name` | +| Inside generic angle brackets | No space | `Dictionary` | +| Nullable `?` and pointer `*` | Attached to the type | `string?`, `byte* data` | +| Range `..` | No space | `span[1..^1]` | +| Spread `..` | One space after | `[.. items]` | +| Inside single-line braces with content | One on each side | `{ get; }`, `new T { a = 1 }`, `is { }` | +| Empty body | No space inside | `{}` | +| Before `{` on the same line | One space | `) {`, `() {}` | +| Colon of a base list, constraint or initializer | One on each side | `class A : B`, `where T : class` | +| Colon of a named argument or attribute target | None before, one after | `width: 1280`, `[assembly: X]` | + +```csharp +if (ready) +{ + float ratio = (float)count / total; + int first = items[0]; + Draw(item, ratio, first); +} +``` + +Avoid: + +```csharp +if(ready) +{ + float ratio = (float) count/total; + int first = items [0]; + Draw( item,ratio , first ); +} +``` + +## S-02 Column alignment + +- When more than three consecutive `const` declarations, or more than three consecutive `static readonly` declarations, have the same type, aligning their `=` signs in a column is recommended. It is not required. +- A numeric matrix or lookup table may align its elements in columns. +- Everywhere else, use a single space between tokens. Do not column-align local variables, assignments, parameters or comments. + +```csharp +private const int C_WIDTH = 1280; +private const int C_HEIGHT = 720; +private const int C_REFRESH_RATE = 60; +private const int C_MIN_SIZE = 16; + +public static readonly Color RED = FromBytes(255, 0, 0); +public static readonly Color GREEN = FromBytes(0, 255, 0); +public static readonly Color BLUE = FromBytes(0, 0, 255); +public static readonly Color WHITE = FromBytes(255, 255, 255); + +private static readonly float[] IDENTITY = +[ + 1f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, + 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 1f +]; +``` + +Avoid (alignment of local variables and trailing comments): + +```csharp +int width = 1280; +string title = "Scene"; // window title +float refreshRate = 60f; // hertz +``` + +## S-03 Blank lines between members + +- Methods, constructors, members with documentation comments and multi-line properties are separated by one blank line. +- Fields, constants and single-line properties of the same group that have no documentation comments are written consecutively. +- Different groups (O-01) are separated by one blank line. +- Enum members are not separated by blank lines, even when they have documentation comments. +- Types are separated by one blank line. + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + private const int C_MAX_SIZE = 16384; + + private readonly RenderTarget m_target; + private int m_width; + private int m_height; + + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + + /// + /// Gets the current height in pixels. + /// + public int height => m_height; + + internal bool isDirty { get; set; } + internal int generation { get; set; } +} +``` + +Avoid: + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + + private const int C_MAX_SIZE = 16384; + private readonly RenderTarget m_target; + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + internal bool isDirty { get; set; } + +} +``` + +## S-04 Blank lines inside method bodies + +- Separate processing phases (validation, preparation, execution, completion) with one blank line. Do not add blank lines mechanically. +- The argument validation at the start of a method (a run of `ThrowIf*` calls and guards) is contiguous and followed by one blank line. +- A local function is preceded by one blank line and placed at the end of the method body. +- No blank line follows an opening brace or precedes a closing brace. Never leave two consecutive blank lines. + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentNullException.ThrowIfNull(options); + ObjectDisposedException.ThrowIf(m_disposed, this); + + AssetSource source = OpenSource(path); + ImportPlan plan = BuildPlan(source, options); + + AssetHandle handle = Execute(plan); + m_handles.Add(handle.id, handle); + return handle; + + ImportPlan BuildPlan( + AssetSource target, + ImportOptions settings + ) => new(target, settings); +} +``` + +Avoid: + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + + ArgumentException.ThrowIfNullOrWhiteSpace(path); + + ArgumentNullException.ThrowIfNull(options); + AssetSource source = OpenSource(path); + + + return Execute(BuildPlan(source, options)); + +} +``` diff --git a/.agents/rulebook/csharp-style/12-idioms.md b/.agents/rulebook/csharp-style/12-idioms.md new file mode 100644 index 000000000..b7f0d4375 --- /dev/null +++ b/.agents/rulebook/csharp-style/12-idioms.md @@ -0,0 +1,364 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 12. Types and expression idioms + +## E-01 Local variables state their type; `var` only with `new T(...)` + +- A local variable declares its type: `T x = expression;`. +- Use `var` when the right-hand side is `new T(...)` or `new T[...]`, where the type is visible on the same line. +- An anonymous type requires `var`. +- A local variable does not use `T x = new(...)`; that form is for fields and properties (M-04). +- A collection expression needs a target type, so the declaration states it: `List names = [];`. + +```csharp +AssetEntry entry = m_entries[index]; +int count = entry.dependencies.Count; +string name = entry.displayName; +var builder = new StringBuilder(capacity); +var buffer = new byte[C_BUFFER_SIZE]; +List names = []; +var projection = new { entry.id, entry.displayName }; +``` + +Avoid: + +```csharp +var entry = m_entries[index]; +var count = entry.dependencies.Count; +StringBuilder builder = new(capacity); +StringBuilder other = new StringBuilder(capacity); +``` + +## E-02 `foreach`, `for`, `using`, `out` and deconstruction state their types + +```csharp +foreach (AssetEntry entry in m_entries) +{ + Visit(entry); +} + +foreach ((string key, AssetEntry value) in m_byName) +{ + Visit(value); +} + +for (int i = 0; i < count; i++) +{ + Visit(m_entries[i]); +} + +using Stream stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out AssetEntry? found)) +{ + Visit(found); +} +``` + +Avoid: + +```csharp +foreach (var entry in m_entries) +{ + Visit(entry); +} + +using var stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out var found)) +{ + Visit(found); +} +``` + +## E-03 Built-in types use keywords + +Write `int`, `string`, `float`, `object`, `nint` and `nuint`, not `Int32`, `String`, `IntPtr` or `UIntPtr`. Access static members through the keyword as well. + +```csharp +nint handle = nint.Zero; +bool empty = string.IsNullOrWhiteSpace(name); +float largest = float.MaxValue; +``` + +Avoid: + +```csharp +IntPtr handle = IntPtr.Zero; +bool empty = String.IsNullOrWhiteSpace(name); +Single largest = Single.MaxValue; +``` + +## E-04 Null checks use patterns + +Use `is null` and `is not null`. Use `is { } x` or `is T x` to test and capture at once. Do not write `== null` or `!= null`. + +```csharp +if (m_source is null) return; + +if (m_owner is not null) +{ + m_owner.Release(); +} + +if (TryFind(id) is { } entry) +{ + Visit(entry); +} +``` + +Avoid: + +```csharp +if (m_source == null) return; + +if (!(m_owner is null)) +{ + m_owner.Release(); +} +``` + +## E-05 Argument validation + +Validation comes first in a method, in parameter order, and uses the `ThrowIf*` helpers. Do not write `?? throw new ArgumentNullException(...)`. + +```csharp +public Viewport( + RenderTarget target, + string name, + int width +) { + ArgumentNullException.ThrowIfNull(target); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + + m_target = target; + m_width = width; + this.name = name; +} +``` + +Avoid: + +```csharp +public Viewport( + RenderTarget target, + string name +) { + m_target = target ?? throw new ArgumentNullException(nameof(target)); + if (name == null) + { + throw new ArgumentNullException("name"); + } +} +``` + +## E-06 Object creation + +- A local variable: `var x = new T(...)` (E-01). +- A field or property initializer: `= new(...)` (M-04). +- A member that directly returns a new object of its declared return type may use `new(...)`. +- An argument, or a creation inside a larger expression, writes the type: `new T(...)`. + +```csharp +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); +``` + +```csharp +var item = new RenderItem(mesh, material); +queue.Enqueue(new RenderItem(mesh, material)); +``` + +Avoid: + +```csharp +RenderItem item = new(mesh, material); +queue.Enqueue(new(mesh, material)); +``` + +## E-07 Common values + +| Meaning | Write | Not | +| --- | --- | --- | +| Empty string | `string.Empty` | `""` | +| Default value | `default` | `default(T)`, unless the type cannot be inferred | +| Empty collection | `[]` | `new List()`, `Array.Empty()` | +| Negation | `!ready` | `ready == false` | +| Non-nullable `bool` test | `if (ready)` | `if (ready == true)` | +| Nullable `bool?` test | `if (flag == true)` | `if (flag ?? false)` | +| Conversion | `(T)value` | `value as T` without a following null check | +| Type test with capture | `value is T typed` | `as` followed by a null check | +| Delegate invocation | `handler?.Invoke(args)` | a null check followed by a call | +| Rethrow | `throw;` | `throw exception;` | +| Infinite loop | `while (true)` | `for (;;)` | +| Current time | `DateTime.UtcNow`, `DateTimeOffset.UtcNow` | `DateTime.Now` | + +```csharp +string label = string.Empty; +Color color = default; +flushed?.Invoke(); +if (value is AssetEntry typed) +{ + Visit(typed); +} +``` + +Avoid: + +```csharp +string label = ""; +Color color = default(Color); +if (flushed != null) +{ + flushed.Invoke(); +} + +AssetEntry typed = value as AssetEntry; +if (typed != null) +{ + Visit(typed); +} +``` + +## E-08 `this.` + +- Inside a constructor, every assignment to an instance member that is not an `m_` field goes through `this.`: `this.name = name;`, `this.count = 0;`. This holds whether or not a parameter has the same name. +- Outside constructors, do not write `this.` unless it is needed to disambiguate. +- Apart from constructor parameters, a parameter or local variable does not take the name of a property of the same type. + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + m_createdUtc = DateTime.UtcNow; + this.profile = profile; + this.outputDirectory = outputDirectory; + this.isIncremental = true; +} + +public BuildProfile profile { get; } +public string outputDirectory { get; } +public bool isIncremental { get; private set; } + +public string Describe() => $"{profile.name} -> {outputDirectory}"; +``` + +Avoid (`isIncremental` assigned without `this.` in the constructor, `this.` outside the constructor): + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + this.profile = profile; + this.outputDirectory = outputDirectory; + isIncremental = true; +} + +public string Describe() => $"{this.profile.name} -> {this.outputDirectory}"; +``` + +## E-09 Strings + +- Build strings from values with interpolation, `$"..."`. Do not use `string.Format` or `string.Concat`. +- Split a long message with `+` at the start of the continuation line (W-01). Use a raw string literal, `"""`, for multi-line text. +- Comparison, lookup, sorting and dictionaries state `StringComparison.Ordinal` / `StringComparer.Ordinal` or the `OrdinalIgnoreCase` variants. +- Change case with `ToLowerInvariant()` / `ToUpperInvariant()` and format with `CultureInfo.InvariantCulture`. +- Refer to identifiers with `nameof(...)`. +- Test external input with `string.IsNullOrWhiteSpace`, and use `string.IsNullOrEmpty` only when whitespace is meaningful. + +```csharp +string message = $"The asset '{path}' could not be imported: {reason}"; +bool same = string.Equals(left, right, StringComparison.Ordinal); +var index = new Dictionary(StringComparer.OrdinalIgnoreCase); +throw new ArgumentException("The path must be relative.", nameof(path)); +``` + +Avoid: + +```csharp +string message = string.Format("The asset '{0}' could not be imported: {1}", path, reason); +bool same = left.ToLower() == right.ToLower(); +throw new ArgumentException("The path must be relative.", "path"); +``` + +## E-10 Numeric literals + +- `float`: write an integral value as `1f` and a fractional value as `1.5f`. Do not write `1.0f` or `1.50f`. +- Suffixes: `f`, `d`, `m` and `u` are lower case; `L` and `UL` are upper case. +- Hexadecimal: the `0x` prefix is lower case, the digits are upper case, and long values are grouped by four digits with `_`. +- Large decimal values are grouped by three digits with `_`. + +```csharp +float half = 0.5f; +float one = 1f; +uint mask = 0xFF00_00FFu; +long ticks = 10_000_000L; +``` + +Avoid: + +```csharp +float one = 1.0f; +float ratio = 1.50f; +uint mask = 0xff0000ffU; +long ticks = 10000000l; +``` + +## E-11 Lambdas + +- One parameter has no parentheses: `x => ...`. No parameters: `() => ...`. Two or more parameters are expanded (P-01). +- Parameters have meaningful names. An unused parameter is `_`. +- A lambda that captures neither a local variable nor `this` is `static`. +- A single-expression body uses the expression form; several statements use a block (B-04). +- When an expression body does not fit on the line of the lambda, it is wrapped in parentheses, unless it is a call or object creation, which breaks inside its own parentheses (B-04). +- Do not use anonymous methods (`delegate { }`). + +```csharp +entries.RemoveAll(static entry => entry.isMissing); +entries.RemoveAll(entry => entry.generation < m_generation); +button.clicked += () => m_log.Info("Clicked."); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +entries.RemoveAll((entry) => entry.isMissing); +entries.RemoveAll(x => x.isMissing); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## E-12 `using` declarations + +Use a `using` declaration when the resource lives until the end of the enclosing block. Use a `using` statement with a block only when the resource must be released earlier. + +```csharp +using Stream stream = lease.OpenRead(); +using var reader = new StreamReader(stream); +return reader.ReadToEnd(); +``` + +Avoid (a block that ends where the method ends): + +```csharp +using (Stream stream = lease.OpenRead()) +{ + using (var reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } +} +``` diff --git a/.agents/rulebook/csharp-style/13-control-flow.md b/.agents/rulebook/csharp-style/13-control-flow.md new file mode 100644 index 000000000..8e4fe0d4c --- /dev/null +++ b/.agents/rulebook/csharp-style/13-control-flow.md @@ -0,0 +1,178 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 13. Control flow, exceptions and asynchronous code + +## X-01 Guard clauses return early + +Handle invalid and boundary cases first and leave with `return`, `throw` or `continue`. The main path is not nested inside `else`. Guards may use the compact form of B-05. + +```csharp +public void Draw(RenderItem item) +{ + if (m_disposed) return; + if (!item.isVisible) return; + + Submit(item); + m_drawn++; +} +``` + +Avoid: + +```csharp +public void Draw(RenderItem item) +{ + if (!m_disposed) + { + if (item.isVisible) + { + Submit(item); + m_drawn++; + } + } +} +``` + +## X-02 `switch` + +- Use a `switch` expression to map a value to a value (I-04). +- Use a `switch` statement when the branches execute statements. `case` is indented four spaces from `switch`, and the statements four spaces from `case`. Each label is on its own line. `default` is last. Add braces to a section only when it declares local variables that would otherwise collide. + +```csharp +switch (command.kind) +{ + case CommandKind.Draw: + case CommandKind.DrawIndexed: + Submit(command); + break; + case CommandKind.Clear: + Clear(command.color); + break; + default: + throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +} +``` + +Avoid: + +```csharp +switch (command.kind) +{ +case CommandKind.Draw: case CommandKind.DrawIndexed: + Submit(command); break; +default: throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +case CommandKind.Clear: + Clear(command.color); + break; +} +``` + +## X-03 Exception types and messages + +| Situation | Exception | +| --- | --- | +| An argument is `null` | `ArgumentNullException`, through `ThrowIfNull` | +| An argument value is invalid | `ArgumentException`, `ArgumentOutOfRangeException` | +| The object state does not allow the operation | `InvalidOperationException` | +| The object has been disposed | `ObjectDisposedException`, through `ThrowIf` | +| Input data is malformed | `InvalidDataException` | +| The platform or backend does not support the operation | `NotSupportedException` | + +A message is a complete English sentence that includes the offending value. Parameter names use `nameof`. A `throw` whose arguments do not fit on one line breaks like any other call (A-02). + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported." +); +``` + +Avoid: + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported."); + +throw new Exception("bad version"); +``` + +## X-04 `catch` + +- Catch the specific type that can be handled. When catching `Exception`, filter with `when` or rethrow with `throw;` after handling. +- A handler at a failure boundary may catch `Exception` without a filter or a rethrow when it records the failure: it logs it, reports it as a diagnostic, stores it in a result or aggregates it for a later throw. +- The variable is named `exception` by default. A name that states the role, such as `cleanupFailure`, is allowed when the exception is stored or aggregated. Omit the variable when it is not used. +- A bare `catch` without a type is only for "clean up, then rethrow". +- A `catch` block that deliberately ignores an exception contains a comment that says why. + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch (IOException) +{ + // The scratch directory is retried by the next retirement pass. +} + +try +{ + Publish(candidate); +} +catch (Exception exception) when (exception is not OperationCanceledException) +{ + m_log.Error($"Publication failed: {exception.Message}"); + throw; +} +``` + +Avoid: + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch {} + +try +{ + Publish(candidate); +} +catch (Exception ex) +{ + throw ex; +} +``` + +## X-05 Asynchronous code + +- Return `Task` or `ValueTask`. Never write `async void`. +- The method name ends with `Async` (NM-04). `CancellationToken cancellationToken` is the last parameter and is passed down to every asynchronous call. +- In product code (`src`, `build`, `backends`, `platforms`, `tools`, `entry`) every `await` ends with `.ConfigureAwait(false)`. Test code does not use `ConfigureAwait`. +- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. A member whose synchronous signature is fixed by a contract may wait at that boundary (see Exceptions). Test code awaits instead: the test method returns `async Task`. +- On a broken `await` call, `.ConfigureAwait(false)` follows the closing parenthesis on its line. + +```csharp +public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken +) { + await using Stream stream = await m_storage.OpenAsync(id, cancellationToken).ConfigureAwait(false); + return await m_reader.ReadAsync( + stream, + id, + cancellationToken + ).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async void Load(AssetID id) +{ + Stream stream = m_storage.OpenAsync(id, CancellationToken.None).Result; + await m_reader.ReadAsync(stream, id, CancellationToken.None); +} +``` diff --git a/.agents/rulebook/csharp-style/14-comments.md b/.agents/rulebook/csharp-style/14-comments.md new file mode 100644 index 000000000..345545119 --- /dev/null +++ b/.agents/rulebook/csharp-style/14-comments.md @@ -0,0 +1,192 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, xml] +--- +# 14. Comments and XML documentation + +## D-01 Which members need XML documentation + +Every externally visible public member, and every protected member that an external type can override, has complete English XML documentation. Important internal APIs are documented as well. Private members and test code do not need documentation. + +```csharp +/// +/// Stores render items until the next flush. +/// +public sealed class RenderQueue +{ + private readonly List m_items = []; + + /// + /// Gets the number of queued items. + /// + public int count => m_items.Count; + + private void Trim() => m_items.TrimExcess(); +} +``` + +Avoid (a public type and a public property without documentation): + +```csharp +public sealed class RenderQueue +{ + public int count => m_items.Count; +} +``` + +## D-02 Tags are expanded, one element per block + +- The start tag, the content and the end tag are on separate lines. `///` is followed by one space. A documentation block has no empty `///` lines. +- Tag order: `summary`, `typeparam`, `param` (in signature order), `returns`, `exception`, `remarks`. +- Every content block starts with a capital letter and ends with a period. +- Wrap long content at complete semantic boundaries. + +```csharp +/// +/// Resolves a loaded asset by its persistent identity. +/// +/// +/// The asset type expected by the caller. +/// +/// +/// The persistent identity of the asset. +/// +/// +/// Receives the asset when this method returns ; +/// otherwise . +/// +/// +/// when the asset is loaded and has the requested type; +/// otherwise . +/// +/// +/// The loader has been disposed. +/// +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +Avoid: + +```csharp +/// Resolves an asset +/// the asset +/// the id +/// true if found +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +## D-03 Wording of summaries + +| Member | Starts with | Example | +| --- | --- | --- | +| Read-only property | `Gets` | `Gets the current width in pixels.` | +| Writable property | `Gets or sets` | `Gets or sets the clear color.` | +| `bool` property | `Gets a value indicating whether` | `Gets a value indicating whether the asset is missing.` | +| Method | A third-person verb | `Creates`, `Releases`, `Determines whether`, `Attempts to` | +| Constructor | `Initializes a new instance of` or `Creates` | `Creates a dispatcher bound to the given hub.` | +| Type | A third-person verb or a noun phrase | `Identifies`, `Describes`, `Provides`, `Represents` | +| Event | `Occurs when` | `Occurs when the platform requests a redraw.` | + +A summary describes real behavior. It does not restate the member name. + +```csharp +/// +/// Gets the current width of the viewport in pixels. +/// +public int width => m_width; +``` + +Avoid: + +```csharp +/// +/// The width. +/// +public int width => m_width; +``` + +## D-04 References inside documentation + +- A type or member: ``. A parameter: ``. A type parameter: ``. +- A keyword: ``, ``, ``. +- A self-closing tag has no space before `/>`. +- An override or interface implementation uses `/// ` and documents any additional constraint locally with `remarks` or `exception`. + +```csharp +/// +public override string ToString() => name; +``` + +Avoid: + +```csharp +/// +/// Returns null if id is not found. See AssetLoader. +/// +/// +public override string ToString() => name; +``` + +## D-05 `//` comments + +- A comment explains a reason, a constraint, ownership or a lifetime. It does not restate the code. +- A comment is on its own line, above the code it explains, at the indentation of that code. Do not write trailing comments. +- `//` is followed by one space. The comment is a complete English sentence that starts with a capital letter and ends with a period. + +```csharp +// The native window must outlive the swap chain, so it is released last. +m_swapChain.Dispose(); +m_window.Dispose(); +``` + +Avoid: + +```csharp +m_swapChain.Dispose(); // dispose swap chain +//release window +m_window.Dispose(); +``` + +## D-06 Prohibited comments and directives + +- Comments in any language other than English. +- `TODO`, `FIXME` or `HACK` markers left in place indefinitely. +- Commented-out code. +- Separator lines, banner comments and `/* */` block comments. +- `#region` and `#endregion`. +- `#nullable` inside a file, and `#pragma warning disable` without a comment that states the reason. + +`#if`, `#elif`, `#else` and `#endif` start at column 0. Conditional symbols are UPPER_SNAKE with the `INNO_` prefix, except `DEBUG`. + +```csharp +#if INNO_HOST_WINDOWS_X64 + private const string C_LIBRARY_NAME = "bgfx.dll"; +#elif INNO_HOST_MACOS_ARM64 + private const string C_LIBRARY_NAME = "libbgfx.dylib"; +#endif +``` + +Avoid: + +```csharp +#region Constants + // ---------- library ---------- + // TODO: revisit + // private const string C_OLD_NAME = "bgfx_old.dll"; + private const string C_LIBRARY_NAME = "bgfx.dll"; /* windows */ +#endregion +``` diff --git a/.agents/rulebook/csharp-style/15-tests.md b/.agents/rulebook/csharp-style/15-tests.md new file mode 100644 index 000000000..cc4a41d8e --- /dev/null +++ b/.agents/rulebook/csharp-style/15-tests.md @@ -0,0 +1,137 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 15. Tests + +## TS-01 Structure + +- Tests use xUnit. A test class is `public sealed class XxxTests` in `XxxTests.cs`, in the namespace of the test project. +- A test method is `public`, returns `void` or `async Task`, and carries `[Fact]`, or `[Theory]` with `[InlineData]`. +- Test classes and test methods do not need XML documentation. +- Fixtures and test doubles follow the same naming and layout rules as product code. A nested test double is `private sealed` and placed at the end of the test class. + +```csharp +using System; +using Xunit; +using Inno.Core.Events; + +namespace Inno.Core.Events.Tests; + +public sealed class EventDispatcherTests +{ + [Fact] + public void NewDispatcherHasNoSinks() + { + var dispatcher = new EventDispatcher(); + + Assert.Empty(dispatcher.sinks); + } + + private sealed class RecordingSink : IEventSink + { + public int published { get; private set; } + + public void Publish(EventRecord record) => published++; + } +} +``` + +Avoid: + +```csharp +public class EventDispatcherTest +{ + [Fact] + void NewDispatcherHasNoSinks() {} +} +``` + +## TS-02 Test method names + +A test method name is a PascalCase statement of what happens under which condition. It has no underscores, no `Async` suffix and no `Test` prefix or suffix. + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void DispatchAfterDisposeThrowsObjectDisposedException() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + + Assert.Throws(() => dispatcher.Dispatch(new EventRecord())); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonPositiveCapacityIsRejected(int capacity) + => Assert.Throws(() => new EventDispatcher(capacity)); + + [Fact] + public async Task PendingEventsAreDeliveredBeforeShutdownCompletes() + { + var dispatcher = new EventDispatcher(); + List received = []; + dispatcher.dispatched += received.Add; + + dispatcher.Dispatch(new EventRecord()); + await dispatcher.ShutdownAsync(CancellationToken.None); + + Assert.Single(received); + } +} +``` + +Avoid: + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void Dispatch_AfterDispose_Throws() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + } + + [Fact] + public async Task TestShutdownAsync() + { + var dispatcher = new EventDispatcher(); + await dispatcher.ShutdownAsync(CancellationToken.None).ConfigureAwait(false); + } +} +``` + +## TS-03 Assertions and layout + +- Separate the arrange, act and assert phases with one blank line. A very short test may omit the separation. +- `Assert.Equal(expected, actual)`: the expected value comes first. +- Source text used as test data (generator inputs and expected outputs) is data, not code; this rulebook does not apply to it. + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + + viewport.Resize(width: 1280, height: 720); + + Assert.Equal(1280, viewport.width); + Assert.Equal(720, viewport.height); +} +``` + +Avoid (actual value first, phases not separated): + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + viewport.Resize(width: 1280, height: 720); + Assert.Equal(viewport.width, 1280); +} +``` diff --git a/.agents/rulebook/csharp-style/16-exceptions.md b/.agents/rulebook/csharp-style/16-exceptions.md new file mode 100644 index 000000000..d2696943f --- /dev/null +++ b/.agents/rulebook/csharp-style/16-exceptions.md @@ -0,0 +1,27 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 16. Exceptions + +The following cases follow an external contract. Do not rename or reformat them to satisfy this rulebook. + +| Case | What it keeps | Example | +| --- | --- | --- | +| Generated code and third-party sources | Everything | `extern/`, `**/Generated/*.cs`, `` files | +| MSBuild task parameters | PascalCase property names bound by MSBuild | `public string OutputPath { get; set; }` | +| Overrides and interface implementations | The name declared by the base type or interface | `Stream.CanRead`, `IEnumerator.Current` | +| Special CLR members | Names required by the language or runtime | operators, `GetEnumerator`, `Deconstruct`, `Dispose` | +| Native interop signatures | Field names, enum values and imported function names from the native header | `SDL_Event`, bgfx enums | +| Serialized wire names | The persisted key. The engine serializer and reflection-based JSON models write the member name as the key, so a serialized member keeps the name stored in existing assets, scenes, settings and manifests | `AssetMeta.persistentId`, `PluginManifest.pluginId` | +| Third-party product names | The spelling used by the product | `RmlUi`, `ImGui`, `MiniAudio` | +| Keyboard and input code enums | Single-letter and digit members | `KeyCode.A`, `KeyCode.F1` | +| Numeric matrices and lookup tables | Several elements per line, column alignment (S-02) | a 4×4 matrix literal | +| Unsplittable string literals | Length beyond the line width (F-04) | paths, URLs | +| Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | +| Source text used as test data | Its own formatting (TS-03) | | +| Serialized value types | Property setters that the serializer writes, so the record struct is not `readonly` (T-04) | `AssetPath`, `ShaderPropertyID` | +| Synchronous contract boundaries | A blocking wait on an asynchronous result inside a member whose synchronous signature is fixed (X-05) | MSBuild `Execute`, `Dispose`, `Main`, a synchronous interface member or public API over an asynchronous implementation | +| Overloaded equality operators | `== null` and `!= null` where the type defines the result of the comparison (E-04) | `EngineObject`, whose destroyed instances compare equal to `null` | + +Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. diff --git a/.agents/rulebook/csharp-style/17-example.md b/.agents/rulebook/csharp-style/17-example.md new file mode 100644 index 000000000..5f20396a3 --- /dev/null +++ b/.agents/rulebook/csharp-style/17-example.md @@ -0,0 +1,209 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 17. Reference example + +One file that applies the rules together. + +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Core.Identity; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline; + +/// +/// Caches loaded assets and reloads them when their sources change. +/// +public sealed class AssetCache : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + private const int C_MAX_ATTEMPT_COUNT = 3; + + private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(50); + + private readonly Dictionary m_entries = new(C_INITIAL_CAPACITY); + private readonly IAssetStore m_store; + private readonly ILogSink m_log; + private int m_generation; + private bool m_disposed; + + /// + /// Creates a cache that reads asset content from the given store. + /// + /// + /// The store that provides asset content. + /// + /// + /// The sink that receives reload diagnostics. + /// + /// + /// The diagnostic name of the cache. + /// + /// + /// is empty or consists only of white space. + /// + public AssetCache( + IAssetStore store, + ILogSink log, + string name + ) { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(log); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + + m_store = store; + m_log = log; + this.name = name; + this.isEnabled = true; + } + + /// + /// Gets the diagnostic name of the cache. + /// + public string name { get; } + + /// + /// Gets a value indicating whether the cache accepts source changes. + /// + public bool isEnabled { get; private set; } + + /// + /// Gets the number of cached assets. + /// + public int count => m_entries.Count; + + /// + /// Occurs when a cached asset has been reloaded from its source. + /// + public event Action? assetReloaded; + + /// + /// Attempts to find a cached asset that is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// Receives the cached handle when this method returns ; + /// otherwise . + /// + /// + /// when a current entry exists; otherwise . + /// + public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out AssetHandle? handle + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + + if (m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation + && !entry.handle.isMissing + ) { + handle = entry.handle; + return true; + } + + handle = null; + return false; + } + + /// + /// Loads an asset, reusing the cached handle when it is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// A token that cancels the load. + /// + /// + /// The loaded asset handle. + /// + /// + /// The store could not provide the asset after every attempt. + /// + public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) { + if (TryResolve(id, out AssetHandle? cached)) return cached; + + for (int attempt = 1; attempt <= C_MAX_ATTEMPT_COUNT; attempt++) + { + try + { + AssetHandle handle = await m_store.LoadAsync(id, cancellationToken).ConfigureAwait(false); + m_entries[id] = new Entry(handle, m_generation); + return handle; + } + catch (IOException exception) when (attempt < C_MAX_ATTEMPT_COUNT) + { + m_log.Warning($"Loading asset '{id}' failed on attempt {attempt}: {exception.Message}"); + await Task.Delay(RETRY_DELAY, cancellationToken).ConfigureAwait(false); + } + } + + throw new InvalidDataException( + $"The asset '{id}' could not be loaded from store '{m_store.name}' after {C_MAX_ATTEMPT_COUNT} attempts." + ); + } + + /// + /// Applies source changes and invalidates the affected entries. + /// + /// + /// The source changes reported by the watcher. + /// + public void ApplySourceChanges(IReadOnlyList changes) + { + ArgumentNullException.ThrowIfNull(changes); + if (!isEnabled) return; + + m_generation++; + foreach (AssetEvent change in changes) + { + if (!m_store.TryGetID(change.path, out AssetID id)) continue; + + string action = change.change switch + { + WatcherChangeTypes.Deleted => "removed", + WatcherChangeTypes.Renamed => "renamed", + _ => "changed" + }; + m_log.Info($"Asset '{id}' was {action}."); + + m_entries.Remove(id); + assetReloaded?.Invoke(id); + } + } + + /// + public void Dispose() + { + if (m_disposed) return; + + // Entries only borrow their handles, so the store releases the content. + m_entries.Clear(); + m_disposed = true; + } + + internal bool IsCurrent(AssetID id) + => m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation; + + private sealed record Entry( + AssetHandle handle, + int generation + ); +} +``` diff --git a/.agents/rulebook/csharp-style/README.md b/.agents/rulebook/csharp-style/README.md new file mode 100644 index 000000000..ef07c5eb3 --- /dev/null +++ b/.agents/rulebook/csharp-style/README.md @@ -0,0 +1,36 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# InnoEngine C# code style + +This rulebook defines how handwritten C# in InnoEngine is named, laid out and written. It applies to every handwritten `.cs` file in the repository, including tests and tools. Third-party sources under `extern/`, generated files (`**/Generated/*.cs` and files carrying an `` header) and the cases listed in [section 16](16-exceptions.md) are out of scope. + +The [coding rules](../coding.md) own design, error-handling, resource and change-management requirements. This rulebook is the detailed authority for names and layout. + +- Every rule has an ID such as `B-05`. Cite the ID in reviews and commit messages. +- Each rule states the requirement first, then shows a compliant example. A block introduced by **Avoid** shows what the rule forbids. +- "Must", "always" and "never" are requirements. "Prefer" and "recommended" describe the default; deviate only when the default hurts readability. +- External contracts take precedence over this rulebook: interface implementations, overrides, MSBuild task parameters, serialized names and native interop signatures keep the names their contract requires (see [section 16](16-exceptions.md)). +- Formatting changes and renames are separate changes. A formatting-only change must not alter names, logic, execution order or public contracts. Renaming a public member is an API change. +- Automatic formatters must preserve these rules. Do not apply a formatter whose output differs from this rulebook. + +Contents + +1. [Files and physical layout](01-files.md) +2. [Namespaces and using directives](02-namespaces.md) +3. [Naming](03-naming.md) +4. [Type declarations](04-types.md) +5. [Member declarations](05-members.md) +6. [Member order](06-member-order.md) +7. [Braces and blocks](07-braces.md) +8. [Parameter and argument lists](08-parameters.md) +9. [Line breaks](09-line-breaks.md) +10. [Initializers and collections](10-initializers.md) +11. [Spacing and blank lines](11-spacing.md) +12. [Types and expression idioms](12-idioms.md) +13. [Control flow, exceptions and asynchronous code](13-control-flow.md) +14. [Comments and XML documentation](14-comments.md) +15. [Tests](15-tests.md) +16. [Exceptions](16-exceptions.md) +17. [Reference example](17-example.md) diff --git a/.agents/rulebook/delivery.md b/.agents/rulebook/delivery.md index b96c5e3ae..53a706fcb 100644 --- a/.agents/rulebook/delivery.md +++ b/.agents/rulebook/delivery.md @@ -1,21 +1,16 @@ +--- +tags: [delivery, notification] +--- # Delivery -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 31. Issues and pull requests - When creating or updating a repository issue or pull request, use a `type(scope): description` title. Both the title and body must be entirely in English. - Issues must distinguish reproduced defects from risks awaiting verification, and state the responsible owner, reproduction conditions, actual result, expected result and executable acceptance criteria. Search existing issues before submission to avoid duplicates. - Pull request bodies must explain the problem, final behavior and actual verification against the complete difference from the target branch, and identify checks that were not run. Search existing PRs before creation. Never describe partial acceptance as a passed complete matrix. -- Use `Aaron Liao ` for both Git author and committer. Do not use a Codex/bot identity or add any `Co-authored-by` attribution. Create pull requests with the GitHub account authorized by the user. +- A human vouches for every commit: its Git author and committer are the human contributor responsible for it. No agent, bot or application identity may appear as author, committer, `Co-authored-by` or any other attribution. Create pull requests with the GitHub account authorized by the user. - Reproduce BGCS defects independently through public APIs and identify them explicitly. Do not modify BGCS source, packages or binaries, or manually edit generated output to bypass defects. - - - ## 16. Completion sound -- By default, play `/System/Library/Sounds/Glass.aiff` before waiting for a design decision that changes scope, after completing the final design, and after completing the requested code or file operations and their necessary validation. The user need not repeat this request for each task. +- By default, play the local system notification sound before waiting for a design decision that changes scope, after completing the final design, and after completing the requested code or file operations and their necessary validation. The user need not repeat this request for each task. - If the environment cannot access audio, state in the final result that the sound could not be played. Do not play it when the user explicitly requests silence. - diff --git a/.agents/rulebook/documentation.md b/.agents/rulebook/documentation.md new file mode 100644 index 000000000..74bc18adb --- /dev/null +++ b/.agents/rulebook/documentation.md @@ -0,0 +1,8 @@ +--- +tags: [documentation, wiki, public-api] +--- +# Documentation + +[InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs) owns the rules for documentation, API prose, examples and content ownership: the [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) on `main`, the published branch; [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) holds unpublished changes. + +Run the rule script again with `-DocsRoot `. It then also selects from the rule files of that checkout and lists them with the `docs/` prefix. It never guesses a sibling path or downloads the rules. diff --git a/.agents/rulebook/domains/build-native/backend-integration.md b/.agents/rulebook/domains/build-native/backend-integration.md new file mode 100644 index 000000000..52279580a --- /dev/null +++ b/.agents/rulebook/domains/build-native/backend-integration.md @@ -0,0 +1,22 @@ +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [backend-build, native] +--- +# Backend integration + +## 29. Backend integration and generation cost + +- Shared SDL window creation and focus reading have one backend owner; platform integrations handle actual SDK differences only. Shared BGFX Devices receive borrowed surfaces through IBgfxSurfaceIntegration and maintain no named-platform/ABI allowlist. Default catalogs receive explicit rendering factories. +- Closing additional windows first unregisters interaction, then retires renderer surfaces. Release native windows only after rendering confirms framebuffer-destruction commands were processed. Native callbacks neither wait for nor advance frames. Final drain occurs only on the owner thread, outside a frame and without an active graph/encoder; failure retains dependency owners. Task completion is not a general GPU fence. +- Component Bindings/bindings.props solely owns Native generation definitions shared by MSBuild and library calls. Toolchains depend only on INativeBindingGenerator; Inno.Build.Bindings owns concrete BGCS workflows, and Tasks map parameters/cancellation/logging only. A product closure requests one complete binding batch. Managed consumers retain Native-selected fingerprints and each component's Static/Shared request. Dynamic-initialization switches consume actual linkage only at Native compilation boundaries, never inferred from platform names or hosts. +- Binding configuration path variables expand only from the operation's frozen Native SDK environment. Direct libraries and MSBuild share target resolution. Do not mutate process environments or temporary PATH values to expose SDKs to generators. Missing configuration fails before candidate creation. +- Product binding selection belongs to that product's SDK intermediate directory and remains after Build/Publish for content-identical reuse. Only Native binding projects import it; transient selection files must not become common-domain compilation inputs. Identical content does not rewrite timestamps; changes replace atomically; product cleanup retires the file. Native Publish still verifies the current managed compilation's closure, fingerprints and source. Retaining a selection file does not hold a generation-cache read lease; actual consumers acquire independent protection. +- Revalidate freshness initially, after batch locks/generation and after each Native lock/compilation. Deduplicate complete content reads only within one explicit phase, never across waits/execution. Copy mutable source to freeze it; hardlinks do not make mutable input immutable. +- Cold CMake producers use the common executor to freeze recipe-declared workspace inputs. Browser aggregate component includes, bridges and arguments resolve into the same copied tree. Warm hits do not copy. External SDKs and outputs retain their own locations and owners; do not misroute outputs by replacing the entire repository root in strings. +- Task runtimes reuse only successful immutable publications within one IBuildEngine4 Build lifetime and the same complete request identity. Registries store BCL data only, never SDK owners, leases or private-ALC types. Each actual load boundary retains an independent owner; failures/cancellation are not cached. Core.IO leases coordinate shared restore writes, yielding/reacquiring MSBuild nodes while waiting and retaining lock files. +- Independent concurrent managed builds use explicit SDK ArtifactsPath values for separate bin/obj owners. Common rules must not override that output selection. Actual product Restore graphs select NuGet Runtime assets; content-addressed Native caches share through their own leases. Ordinary IDE bin/obj belongs to one active build; two independent processes writing the same paths is not supported concurrency. +- Neutral and product requests within one SDK graph also isolate actual outputs. With ArtifactsPath, select an ArtifactsProjectName containing product inputs before SDK default paths are established, preserving SDK configuration/TFM/RID pivots and explicit caller settings. Before building, the development Editor entry uses existing owned restore for its selected product's complete reference closure. It cannot rely on later platform-child restores to satisfy direct or SDK-added transitive references. +- Owned NuGet Restore uses standard ExcludeRestorePackageImports=true. Compilation uses a separate evaluation configuration including restored imports. A cached ProjectInstance must not carry old package content items into new assembly outputs. Package-name exceptions, patched NuGet imports and cache deletion must not conceal mixed artifacts. +- NuGet dependencies use ordinary csproj PackageReferences and SDK Restore. Do not enable, generate or commit dependency lockfiles, or maintain per-project/host/RID/AOT/trimming lock inventories and naming schemes. Official declarations own package versions; BGCS retains its unified exact version. Consumers read actual SDK-evaluated assets/package content. CI performs ordinary restore and verifies builds, package identities and source hygiene. Custom dependency resolvers, clearing real SDK properties and ignore rules must not replace the correct flow. Core IO leases for concurrency, process ownership and atomic publication are not dependency locking and must remain. + +- Engine-managed build SDK working caches and coordination locks belong inside the corresponding artifacts/obj or explicit output owner. Do not retain global ignore rules or validation exemptions for retired cache locations in source directories. Before removing old project directories, verify current project/restore graphs, Git ownership, symlinks, active processes and complete file inventories. Ordinary runtime locks retain existing owner-retirement protocols. Historical configuration on an old remote branch is not an untracked current-branch file; do not delete manifests across branches or rewrite history to fabricate cleanup. diff --git a/.agents/rulebook/domains/build-native/hosts.md b/.agents/rulebook/domains/build-native/hosts.md new file mode 100644 index 000000000..4e9d5516b --- /dev/null +++ b/.agents/rulebook/domains/build-native/hosts.md @@ -0,0 +1,15 @@ +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [build-host, native] +--- +# Hosts and unified builds + +## 25. Hosts, platform targets and unified builds + +- Shared Foundation, Shell and Player Runtime do not detect capabilities with OperatingSystem.IsBrowser. Platform entries inject frame scheduling, module activation, storage, logging and threading policy. Input uses the same Core Events entry. +- Each Native component has one project, separating common BGCS declarations from target profiles. The host single file is Generated/Bindings.cs; target managed output is artifacts/bindings////Generated/Bindings.cs. CMake intermediates remain in the owning toolchain's obj/native. Different targets and generation identities must not overwrite each other's output. +- BGCS-generated ABI carriers have explicit marshalling. Common MSBuild rules enable DisableRuntimeMarshalling for every binding component. Do not let the runtime reinterpret declarations or duplicate assembly attributes in components. Acceptance checks actual parameters, returns and callbacks, not merely sizeof. +- Cpp2C target bridges use artifacts/bindings////Native and share staging validation and atomic commit with the managed single file. They must not overwrite host Native/Generated. Target toolchains read the current request's generation description and select the bridge through CMake parameters. Emscripten SDK/Cache/Node/Python selection follows the target project's MSBuild workload; do not guess the highest installed package version. +- Development executable projects are only entry's InnoEngine.Editor and InnoEngine.Build. Inno.Build.Cli is a shared application library. Component toolchains, Shader compilation, Support Pack transactions and architecture validation remain composed libraries; MSBuild uses thin Task adapters. +- Ordinary Editor IDE/MSBuild Build and Publish prepare the current configuration's entire native closure through the same Native toolchain and deployment contracts. Failed builds must not report runnable output. Runtime Loaders load explicitly deployed files only; they do not build, probe repository caches or support old symbols. Preserve content-identical deployed files rather than recopying or replacing loaded DLLs. +- Support Pack core registers targets through IPlayerSupportPackSource and IPlayerSupportPackValidator, without concrete platform branches. Inno.Build.Composition accepts neutral binding contributions only. Built-in targets, managed deployments, Support Packs and product-component closures register only in Inno.Build.Distribution.Standard. Editor, CLI and MSBuild inject host context and consume the same immutable distribution. General Build libraries must not reference that composition library or Editor in reverse. Validate requested targets and managed-deployment capabilities before Support Pack provision or external tool execution; do not perform expensive preparation before rejecting unsupported combinations. diff --git a/.agents/rulebook/domains/build-native.md b/.agents/rulebook/domains/build-native/platform-products.md similarity index 51% rename from .agents/rulebook/domains/build-native.md rename to .agents/rulebook/domains/build-native/platform-products.md index 637a57986..01ad56fc6 100644 --- a/.agents/rulebook/domains/build-native.md +++ b/.agents/rulebook/domains/build-native/platform-products.md @@ -1,22 +1,9 @@ -# Build and Native +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [platform-products, native] +--- +# Platform products -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - -## 25. Hosts, platform targets and unified builds - -- Shared Foundation, Shell and Player Runtime do not detect capabilities with OperatingSystem.IsBrowser. Platform entries inject frame scheduling, module activation, storage, logging and threading policy. Input uses the same Core Events entry. -- Each Native component has one project, separating common BGCS declarations from target profiles. The host single file is Generated/Bindings.cs; target managed output is artifacts/bindings////Generated/Bindings.cs. CMake intermediates remain in the owning toolchain's obj/native. Different targets and generation identities must not overwrite each other's output. -- BGCS-generated ABI carriers have explicit marshalling. Common MSBuild rules enable DisableRuntimeMarshalling for every binding component. Do not let the runtime reinterpret declarations or duplicate assembly attributes in components. Acceptance checks actual parameters, returns and callbacks, not merely sizeof. -- Cpp2C target bridges use artifacts/bindings////Native and share staging validation and atomic commit with the managed single file. They must not overwrite host Native/Generated. Target toolchains read the current request's generation description and select the bridge through CMake parameters. Emscripten SDK/Cache/Node/Python selection follows the target project's MSBuild workload; do not guess the highest installed package version. -- Development executable projects are only entry's InnoEngine.Editor and InnoEngine.Build. Inno.Build.Cli is a shared application library. Component toolchains, Shader compilation, Support Pack transactions and architecture validation remain composed libraries; MSBuild uses thin Task adapters. -- Ordinary Editor IDE/MSBuild Build and Publish prepare the current configuration's entire native closure through the same Native toolchain and deployment contracts. Failed builds must not report runnable output. Runtime Loaders load explicitly deployed files only; they do not build, probe repository caches or support old symbols. Preserve content-identical deployed files rather than recopying or replacing loaded DLLs. -- Support Pack core registers targets through IPlayerSupportPackSource and IPlayerSupportPackValidator, without concrete platform branches. Inno.Build.Composition accepts neutral binding contributions only. Built-in targets, managed deployments, Support Packs and product-component closures register only in Inno.Build.Distribution.Standard. Editor, CLI and MSBuild inject host context and consume the same immutable distribution. General Build libraries must not reference that composition library or Editor in reverse. Validate requested targets and managed-deployment capabilities before Support Pack provision or external tool execution; do not perform expensive preparation before rejecting unsupported combinations. - - - - ## 28. Platforms, shared backends and product composition - Organize shared code by responsibility, system/SDK integration by platform, builds by explicit targets including architecture and ABI, and Editor/Player by product composition. Desktop is not a target. Declare tool host, runtime target, product and managed deployment separately. @@ -48,24 +35,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - ImGui viewport position and logical size coordinate through platform events and ImGui getter/setter protocols. Drawable-metrics synchronization must not overwrite requested position/size or generate Move/Resize requests, avoiding feedback that interferes with dragging. - Both entries use ordinary ProjectReferences and direct public calls. Do not restore prebuilt Editor receipts, CLI-started workers, runtime child MSBuild or shared .run mechanisms. Only an entry may lift Solution build suppression for its own conditional product references; this does not bring other host products into default builds. - - - - -## 29. Backend integration and generation cost - -- Shared SDL window creation and focus reading have one backend owner; platform integrations handle actual SDK differences only. Shared BGFX Devices receive borrowed surfaces through IBgfxSurfaceIntegration and maintain no named-platform/ABI allowlist. Default catalogs receive explicit rendering factories. -- Closing additional windows first unregisters interaction, then retires renderer surfaces. Release native windows only after rendering confirms framebuffer-destruction commands were processed. Native callbacks neither wait for nor advance frames. Final drain occurs only on the owner thread, outside a frame and without an active graph/encoder; failure retains dependency owners. Task completion is not a general GPU fence. -- Component Bindings/bindings.props solely owns Native generation definitions shared by MSBuild and library calls. Toolchains depend only on INativeBindingGenerator; Inno.Build.Bindings owns concrete BGCS workflows, and Tasks map parameters/cancellation/logging only. A product closure requests one complete binding batch. Managed consumers retain Native-selected fingerprints and each component's Static/Shared request. Dynamic-initialization switches consume actual linkage only at Native compilation boundaries, never inferred from platform names or hosts. -- Binding configuration path variables expand only from the operation's frozen Native SDK environment. Direct libraries and MSBuild share target resolution. Do not mutate process environments or temporary PATH values to expose SDKs to generators. Missing configuration fails before candidate creation. -- Product binding selection belongs to that product's SDK intermediate directory and remains after Build/Publish for content-identical reuse. Only Native binding projects import it; transient selection files must not become common-domain compilation inputs. Identical content does not rewrite timestamps; changes replace atomically; product cleanup retires the file. Native Publish still verifies the current managed compilation's closure, fingerprints and source. Retaining a selection file does not hold a generation-cache read lease; actual consumers acquire independent protection. -- Revalidate freshness initially, after batch locks/generation and after each Native lock/compilation. Deduplicate complete content reads only within one explicit phase, never across waits/execution. Copy mutable source to freeze it; hardlinks do not make mutable input immutable. -- Cold CMake producers use the common executor to freeze recipe-declared workspace inputs. Browser aggregate component includes, bridges and arguments resolve into the same copied tree. Warm hits do not copy. External SDKs and outputs retain their own locations and owners; do not misroute outputs by replacing the entire repository root in strings. -- Task runtimes reuse only successful immutable publications within one IBuildEngine4 Build lifetime and the same complete request identity. Registries store BCL data only, never SDK owners, leases or private-ALC types. Each actual load boundary retains an independent owner; failures/cancellation are not cached. Core.IO leases coordinate shared restore writes, yielding/reacquiring MSBuild nodes while waiting and retaining lock files. -- Independent concurrent managed builds use explicit SDK ArtifactsPath values for separate bin/obj owners. Common rules must not override that output selection. Actual product Restore graphs select NuGet Runtime assets; content-addressed Native caches share through their own leases. Ordinary IDE bin/obj belongs to one active build; two independent processes writing the same paths is not supported concurrency. -- Neutral and product requests within one SDK graph also isolate actual outputs. With ArtifactsPath, select an ArtifactsProjectName containing product inputs before SDK default paths are established, preserving SDK configuration/TFM/RID pivots and explicit caller settings. Before building, the development Editor entry uses existing owned restore for its selected product's complete reference closure. It cannot rely on later platform-child restores to satisfy direct or SDK-added transitive references. -- Owned NuGet Restore uses standard ExcludeRestorePackageImports=true. Compilation uses a separate evaluation configuration including restored imports. A cached ProjectInstance must not carry old package content items into new assembly outputs. Package-name exceptions, patched NuGet imports and cache deletion must not conceal mixed artifacts. -- NuGet dependencies use ordinary csproj PackageReferences and SDK Restore. Do not enable, generate or commit dependency lockfiles, or maintain per-project/host/RID/AOT/trimming lock inventories and naming schemes. Official declarations own package versions; BGCS retains its unified exact version. Consumers read actual SDK-evaluated assets/package content. CI performs ordinary restore and verifies builds, package identities and source hygiene. Custom dependency resolvers, clearing real SDK properties and ignore rules must not replace the correct flow. Core IO leases for concurrency, process ownership and atomic publication are not dependency locking and must remain. - -- Engine-managed build SDK working caches and coordination locks belong inside the corresponding artifacts/obj or explicit output owner. Do not retain global ignore rules or validation exemptions for retired cache locations in source directories. Before removing old project directories, verify current project/restore graphs, Git ownership, symlinks, active processes and complete file inventories. Ordinary runtime locks retain existing owner-retirement protocols. Historical configuration on an old remote branch is not an untracked current-branch file; do not delete manifests across branches or rewrite history to fabricate cleanup. - diff --git a/.agents/rulebook/domains/editor/projects.md b/.agents/rulebook/domains/editor/projects.md new file mode 100644 index 000000000..b73b06bee --- /dev/null +++ b/.agents/rulebook/domains/editor/projects.md @@ -0,0 +1,14 @@ +--- +paths: ["src/composition/editor/**"] +tags: [editor-projects] +--- +# Editor projects + +## 13. Editor projects and reference boundaries +- Business source in each project under `src/composition/editor` uses a namespace exactly matching its csproj/assembly name. Feature directories organize files without adding namespace segments. For example, types under Inno.Editor.Inspection/PropertyDrawing still use namespace Inno.Editor.Inspection. +- Reusable InspectionDrawers, PropertyDrawers, Registries and serialized-property renderers belong to Inno.Editor.Inspection. Business Panels implement specific Drawers in their own projects and must not reference Inno.Editor.Panel.Inspector merely to extend inspection presentation. +- The sole namespace exception is Inno.Editor.ImGui/Widgets: all its types use namespace Inno.Editor.ImGui.ImGuiWidget. +- Inno.Editor.ImGui/Widgets contains only ImGuiWidget.*.cs files. Each widget's presentation, options, results and private state belong together in ImGuiWidget..cs. Do not create separate Widget helper files. +- Organize Editor project directories by independently understandable capabilities, such as Interactions, Documents, Zoom and PropertyDrawing. Do not mechanically scatter one feature's Actions, Menus, DragDrop, Runtime and Presentation into tiny type-role directories. Ambiguous Internal directories are prohibited; C# declarations, not directory names, express accessibility. +- Group Editor csproj ProjectReferences by public API boundary: the first ItemGroup contains only implementation dependencies absent from all public/protected APIs, each with PrivateAssets="compile"; the second contains only dependencies actually exposed through public signatures, base classes or interfaces. Remove unused references. +- Determine public reference visibility from actual API signatures, not merely runtime assembly use. Recheck the groups after changing public types, base classes, parameters, returns or properties. diff --git a/.agents/rulebook/domains/editor/state.md b/.agents/rulebook/domains/editor/state.md new file mode 100644 index 000000000..a4fed0c30 --- /dev/null +++ b/.agents/rulebook/domains/editor/state.md @@ -0,0 +1,24 @@ +--- +paths: ["src/composition/editor/**", "tests/editor/**"] +tags: [editor-state] +--- +# Editor state + +## 14. Editor History and Workspace state +- Reversible Editor data changes use EditorInteractions.history. Do not keep another Undo stack in a Panel or treat a simple inverse Action as the general model. +- Feature Modules apply the domain change first, then record it with RecordApplied(name, EditorHistoryChange). History payloads contain only stable protocol kinds, persistent IDs, Stable Type IDs, paths, indexes, scalars and neutral serialized bytes. They must not capture runtime objects, Plugin Types, extension instances or collectible-ALC delegates. +- Every reload-safe protocol declares [EditorHistoryHandler(kind)]. Handler Query only checks current-generation availability; Apply rolls back partial modifications on failure. Its Registry participates in candidate construction and atomic switching with the other Editor Registries. +- RecordValue, delegate-based Execute and derived EditorHistoryOperation are permitted only for Host-only compatibility workflows. These runtime-bound entries are truncated when extension generations change and must not serve EditorScripts or long-lived Scene/Asset records. +- Stable mergeKeys apply only to continuous input for the same logical value. Do not merge boolean toggles, creation, deletion or ordering. Use BeginTransaction for multiple steps, with each child independently atomic. +- Failed Undo/Redo leaves the operation on its original stack without moving pointers or overwriting new state. New operations release the Redo branch. Evicted/cleared operations release their files, objects and Plugin-generation references. +- EditorHistoryOptions automatically spills large payloads to /Library/Editor/History. Entry, resident-byte and disk-byte budgets all constrain History. Its cache does not enter editor.ini, Asset metadata or Scene serialization. +- Pure workflows such as saving, opening and selection do not enter data Undo by default. Record only the data portion when they actually modify Project data. +- Cross-startup Project semantic state belongs directly to Modules/Panels. Their Attributes require stable, globally unique IDs, and protected Capture(EditorState)/Restore(EditorState) hooks participate in persistence. Extensions use only Get/Set on the parameter object, without exposing JSON implementations in public/protected APIs. Types that do not override Capture do not enter state IO. Do not restore separate Workspace interfaces, readers/writers or second state IDs. Persistent values must be neutral and resolvable again. +- editor.ini is the unified readable Project-level Editor settings document. Standard ImGui sections store layout; each Module/Panel uses [InnoEditor][Module.] or [InnoEditor][Panel.]; Panel switches use [InnoEditor][Panels]. Do not wrap the entire Workspace in Base64 or one opaque payload. Do not persist Undo stacks, dirty Scene content, runtime references or compilation intermediate state. +- The standard Host's embedded resource supplies a new Project's default layout. Core receives a neutral initial document and reuses Core IO atomic writing. Initialize only when the file does not exist; do not overwrite an existing or deliberately empty editor.ini. Templates contain no example Scenes, Asset IDs, Plugin state, Selection, History or temporary popups. +- Editor Selection is transient interaction state for the current session and must not enter editor.ini. Workspace may save independently meaningful navigation positions, open documents and active documents. Startup must not automatically restore Asset, Scene, GameObject, Component or System selection. +- Normal Editor shutdown captures every stateful Module/Panel, then the latest ImGui layout, then forces one atomic write of the complete editor.ini before stopping Modules or unloading Scenes. Throttled runtime saves remain allowed but do not replace shutdown saving. +- All Editor Scene edits use Inno.Editor.Scene.SceneEdits. Ordinary properties store only one property's bytes; Components/Systems store element identity/type/index/state; GameObject deletion stores the minimal subtree; hierarchy changes store only affected placements. Do not serialize or restore an entire Scene for small edits. +- Module/Panel restoration tolerates missing Assets, damaged payloads and script types not yet present in TypeCache. Do not destroy the current editable state before the candidate is fully prepared. +- A stateful Module/Panel must successfully complete protected Restore once before Capture may overwrite its disk section. Extension Registry refresh may reenter during startup/script activation. The restoration coordinator weakly tracks restoring/restored state per instance, prevents reentrant callbacks and does not assume an instance retained in a new snapshot has already been restored. +- Scene Workspace restoration distinguishes an actually missing source file from an Asset Source Index awaiting its first reconciliation. If physical source still exists, retain pending Scene setup and retry. Do not overwrite Project settings with a temporarily empty runtime Scene collection. Editor permits no loaded Scenes; restoration, startup and deletion of the last Scene must not implicitly create an Untitled Scene. diff --git a/.agents/rulebook/domains/editor.md b/.agents/rulebook/domains/editor/ui.md similarity index 63% rename from .agents/rulebook/domains/editor.md rename to .agents/rulebook/domains/editor/ui.md index 8f3945c5c..6b29982fc 100644 --- a/.agents/rulebook/domains/editor.md +++ b/.agents/rulebook/domains/editor/ui.md @@ -1,43 +1,9 @@ -# Editor - -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - -## 13. Editor projects and reference boundaries -- Business source in each project under `src/composition/editor` uses a namespace exactly matching its csproj/assembly name. Feature directories organize files without adding namespace segments. For example, types under Inno.Editor.Inspection/PropertyDrawing still use namespace Inno.Editor.Inspection. -- Reusable InspectionDrawers, PropertyDrawers, Registries and serialized-property renderers belong to Inno.Editor.Inspection. Business Panels implement specific Drawers in their own projects and must not reference Inno.Editor.Panel.Inspector merely to extend inspection presentation. -- The sole namespace exception is Inno.Editor.ImGui/Widgets: all its types use namespace Inno.Editor.ImGui.ImGuiWidget. -- Inno.Editor.ImGui/Widgets contains only ImGuiWidget.*.cs files. Each widget's presentation, options, results and private state belong together in ImGuiWidget..cs. Do not create separate Widget helper files. -- Organize Editor project directories by independently understandable capabilities, such as Interactions, Documents, Zoom and PropertyDrawing. Do not mechanically scatter one feature's Actions, Menus, DragDrop, Runtime and Presentation into tiny type-role directories. Ambiguous Internal directories are prohibited; C# declarations, not directory names, express accessibility. -- Group Editor csproj ProjectReferences by public API boundary: the first ItemGroup contains only implementation dependencies absent from all public/protected APIs, each with PrivateAssets="compile"; the second contains only dependencies actually exposed through public signatures, base classes or interfaces. Remove unused references. -- Determine public reference visibility from actual API signatures, not merely runtime assembly use. Recheck the groups after changing public types, base classes, parameters, returns or properties. - - - - -## 14. Editor History and Workspace state -- Reversible Editor data changes use EditorInteractions.history. Do not keep another Undo stack in a Panel or treat a simple inverse Action as the general model. -- Feature Modules apply the domain change first, then record it with RecordApplied(name, EditorHistoryChange). History payloads contain only stable protocol kinds, persistent IDs, Stable Type IDs, paths, indexes, scalars and neutral serialized bytes. They must not capture runtime objects, Plugin Types, extension instances or collectible-ALC delegates. -- Every reload-safe protocol declares [EditorHistoryHandler(kind)]. Handler Query only checks current-generation availability; Apply rolls back partial modifications on failure. Its Registry participates in candidate construction and atomic switching with the other Editor Registries. -- RecordValue, delegate-based Execute and derived EditorHistoryOperation are permitted only for Host-only compatibility workflows. These runtime-bound entries are truncated when extension generations change and must not serve EditorScripts or long-lived Scene/Asset records. -- Stable mergeKeys apply only to continuous input for the same logical value. Do not merge boolean toggles, creation, deletion or ordering. Use BeginTransaction for multiple steps, with each child independently atomic. -- Failed Undo/Redo leaves the operation on its original stack without moving pointers or overwriting new state. New operations release the Redo branch. Evicted/cleared operations release their files, objects and Plugin-generation references. -- EditorHistoryOptions automatically spills large payloads to /Library/Editor/History. Entry, resident-byte and disk-byte budgets all constrain History. Its cache does not enter editor.ini, Asset metadata or Scene serialization. -- Pure workflows such as saving, opening and selection do not enter data Undo by default. Record only the data portion when they actually modify Project data. -- Cross-startup Project semantic state belongs directly to Modules/Panels. Their Attributes require stable, globally unique IDs, and protected Capture(EditorState)/Restore(EditorState) hooks participate in persistence. Extensions use only Get/Set on the parameter object, without exposing JSON implementations in public/protected APIs. Types that do not override Capture do not enter state IO. Do not restore separate Workspace interfaces, readers/writers or second state IDs. Persistent values must be neutral and resolvable again. -- editor.ini is the unified readable Project-level Editor settings document. Standard ImGui sections store layout; each Module/Panel uses [InnoEditor][Module.] or [InnoEditor][Panel.]; Panel switches use [InnoEditor][Panels]. Do not wrap the entire Workspace in Base64 or one opaque payload. Do not persist Undo stacks, dirty Scene content, runtime references or compilation intermediate state. -- The standard Host's embedded resource supplies a new Project's default layout. Core receives a neutral initial document and reuses Core IO atomic writing. Initialize only when the file does not exist; do not overwrite an existing or deliberately empty editor.ini. Templates contain no example Scenes, Asset IDs, Plugin state, Selection, History or temporary popups. -- Editor Selection is transient interaction state for the current session and must not enter editor.ini. Workspace may save independently meaningful navigation positions, open documents and active documents. Startup must not automatically restore Asset, Scene, GameObject, Component or System selection. -- Normal Editor shutdown captures every stateful Module/Panel, then the latest ImGui layout, then forces one atomic write of the complete editor.ini before stopping Modules or unloading Scenes. Throttled runtime saves remain allowed but do not replace shutdown saving. -- All Editor Scene edits use Inno.Editor.Scene.SceneEdits. Ordinary properties store only one property's bytes; Components/Systems store element identity/type/index/state; GameObject deletion stores the minimal subtree; hierarchy changes store only affected placements. Do not serialize or restore an entire Scene for small edits. -- Module/Panel restoration tolerates missing Assets, damaged payloads and script types not yet present in TypeCache. Do not destroy the current editable state before the candidate is fully prepared. -- A stateful Module/Panel must successfully complete protected Restore once before Capture may overwrite its disk section. Extension Registry refresh may reenter during startup/script activation. The restoration coordinator weakly tracks restoring/restored state per instance, prevents reentrant callbacks and does not assume an instance retained in a new snapshot has already been restored. -- Scene Workspace restoration distinguishes an actually missing source file from an Asset Source Index awaiting its first reconciliation. If physical source still exists, retain pending Scene setup and retry. Do not overwrite Project settings with a temporarily empty runtime Scene collection. Editor permits no loaded Scenes; restoration, startup and deletion of the last Scene must not implicitly create an Untitled Scene. - - - - +--- +paths: ["src/composition/editor/presentation/**", "src/composition/editor/panels/**", "**/*ImGui*", "**/*ImGui*/**"] +tags: [editor-layout, editor-acceptance, editor-standard] +--- +# Editor UI + ## 24. Editor forms and scrolling - Each visible region has one scrolling owner. Parent Panel/Modal, layout Child and content Child must not produce scrollbars in the same direction for the same content. A parent hosting a fill-area scrollable Child disables the corresponding scrolling. @@ -47,14 +13,11 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Align Popup size constraints to pixels at the Widget boundary: floor upper bounds and ceil required content sizes to prevent false overflow when ImGui truncates fractional padding. Regressions cover fractional zoom such as 85%, 90% and 110%, not only integer/half-integer padding. Do not conceal failures with NoScrollbar. - Custom hit regions check both rectangle containment and whether their owning ImGui window is the currently interactive foreground window. Floating windows, Popups and Modals must block underlying Panel close actions, canvas gestures and game input. Platform events still use Inno.Core.Events; ImGui determines visible-UI hits/focus only. Play Sessions have an independent Input backend receiving events filtered by Game View focus policy, without a second event bus. - Tree-row disclosure controls, text and overlay buttons each own an independent hit region. Native TreeNodes must not cover custom text using full-row SpanFullWidth/AllowOverlap. Regressions cover prior hover and same-frame move/press, text double-click, arrow expansion and overlay buttons. Clicking must not require an extra hover frame. - - - ## 32. Editor UI ownership and acceptance - Domain editing in `features` must remain independent from native UI, Panels and Workbench. Panels compose feature APIs; they do not reference other Panels. Reusable controls belong to the session-owned ImGui adapter, and generic Graph presentation cannot depend on Shader semantics. -- Every interactive host owns one `EditorUiSession`. Transient widget/menu state belongs to its session and stable presentation owner. Native drawing borrows cannot survive their frame, window, context or owner thread. `current` is only a synchronous scoped accessor, never a global state owner. +- Every interactive host owns one `EditorUISession`. Transient widget/menu state belongs to its session and stable presentation owner. Native drawing borrows cannot survive their frame, window, context or owner thread. `current` is only a synchronous scoped accessor, never a global state owner. - Continuous Inspector and viewport edits use one `EditorEditGesture` over `EditorInteractions.history`. Each sample records immediately; Escape rolls back the same transaction. Save, commands and generation changes finish the gesture before their own operation. No feature may delay History publication behind a separate UI-active flag. - Selection, deferred commands and cross-frame tools resolve identities through Core Identity. Batch operations validate the complete selection, normalize overlapping roots and roll back atomically. Mixed, Missing, read-only and unassigned states remain distinct. - Final delivery must evaluate architecture, organization, state/lifetime cleanliness, abstraction, reuse, visual consistency, extensibility, interaction, Undo/Redo, menu clarity and component granularity individually. Each evaluation must identify actual evidence, limitations and remaining improvements; directory changes and interface counts alone are insufficient. @@ -65,7 +28,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - The formal script SDK host references the actual exported API owners directly, including reusable presentation libraries when required. It must not use concrete Panels as transitive dependency carriers for asset, shader or graph authoring APIs. - Session-owned zoom and density requests commit through the presentation preparation phase after selecting the owned context and display metrics, before native frame creation. Repeated preparation during the same drawing frame cannot publish a new metric snapshot. Standalone metrics remain usable without native UI. - Presentation preparation, drawing and publication form one owned operation. Reentry and retirement during that operation must fail before releasing resources. A callback failure ends only its owned native frame, preserves the original failure and never publishes partial draw data; it must not clear another context's stacks or lower native assertions. -- Native presentation fixtures must create and enter an `EditorUiSession`, explicitly compose their feature/presentation owners, and resolve the exact service under test. Asynchronous shutdown fixtures must retry the public Pending retirement protocol until owned cleanup completes; they cannot rely on continuation timing or remove resource-release assertions. +- Native presentation fixtures must create and enter an `EditorUISession`, explicitly compose their feature/presentation owners, and resolve the exact service under test. Asynchronous shutdown fixtures must retry the public Pending retirement protocol until owned cleanup completes; they cannot rely on continuation timing or remove resource-release assertions. - Presentation input snapshots expose physical Core modifier semantics. Reverse native shortcut normalization at the presentation boundary using the owned context configuration; do not interpret normalized Control/Super flags as physical keys or add shared-layer OS detection. Native input fixtures explicitly select their conventions and cover both modifier policies and native modes. - Content-sized modals prepare one coherent frame snapshot and measure it before opening. Explicitly sized resizable windows prepare after current native input establishes their content bounds. Never invoke arbitrary drawing callbacks twice for measurement or rely on the previous message height. @@ -73,10 +36,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Workflow progress and cancellation are bound to the original owner and operation identity. Late callbacks cannot overwrite a newer request or a cancellation state, and progress presentation cannot weaken publication or generation retirement. - CI and local acceptance must follow the actual changed owners. Use scoped Editor verification for bounded UI changes; retain full verification for build, platform, backend, SDK, shared runtime or unknown owners. Record omitted checks explicitly and never bypass production validation to shorten CI. - - - ## Delivery and acceptance Changes update source, callers, project references, public XML, documentation and applicable tests together. Use real public contracts and replaceable boundaries, without IVT, private reflection or test backdoors. @@ -89,13 +49,10 @@ Acceptance orchestration obtains actual Native target, tool target and product p Distinguish native-borrow verification from pure value conversion according to actual contracts. Every EditorDrawList operation validates its original window, frame, Context and thread. Color conversion retains existing Session/Context/thread admission. Verify saturation, rounding and nonfinite color behavior against the actual native oracle; ordinary numeric equality does not establish agreement at every boundary. -EditorUiInput Control/Super values mean physical modifiers, not native controls' internal shortcut normalization. The presentation boundary reconstructs them from the current Context's keyboard configuration. List selection reuses those snapshot semantics; platforms still choose primary modifiers through EditorKeyboardPolicy. Native text controls retain that Context's input conventions. Tests explicitly declare their keyboard configuration and cover Control/Super combined with both native modes rather than relying on runner defaults. +EditorUIInput Control/Super values mean physical modifiers, not native controls' internal shortcut normalization. The presentation boundary reconstructs them from the current Context's keyboard configuration. List selection reuses those snapshot semantics; platforms still choose primary modifiers through EditorKeyboardPolicy. Native text controls retain that Context's input conventions. Tests explicitly declare their keyboard configuration and cover Control/Super combined with both native modes rather than relying on runner defaults. Final reports separately assess architecture, organization, state/lifetimes, abstraction, reuse, style, extensibility, interaction, Undo/Redo, menus and granularity, with evidence and limitations for each. Neat directories, test counts or successful startup do not replace visual/input acceptance, repeated reload, resource convergence and paired performance measurements. - - - ## Dynamic Modal state and size - Window size, wrapping and drawing use one snapshot for the current frame, never the previous message's height. @@ -112,4 +69,3 @@ Engine CI selects checks from the complete Git change set and actual SDK depende Inno.Tooling.Validation is the sole plan owner and does not weaken production-build integrity. Moves cover old and new owners; PRs use actual merge candidates and merge bases; local plans include staged, unstaged and untracked files. Record selection reasons and exclusions. A bounded pass is not a complete product/device matrix pass. Unavailable required environments, missing results and empty required tests fail or block. Cheap architecture rules remain repository-wide. Prepare compilation metadata and documentation examples from actual dependencies, sharing the batch graph across architecture, tests and documentation. Impact analysis includes project references, imports, source, resources and generated inputs. Text similarity cannot declare SDK/TFM/shared-build changes irrelevant. Log directories, reports, commits/pushes and session recovery do not justify repeated acceptance. Reuse only deterministic evidence with matching inputs, tools, environments and artifacts. - diff --git a/.agents/rulebook/domains/identity-reload.md b/.agents/rulebook/domains/identity-reload.md index 750465ce8..c4b7d5c3b 100644 --- a/.agents/rulebook/domains/identity-reload.md +++ b/.agents/rulebook/domains/identity-reload.md @@ -1,11 +1,11 @@ +--- +paths: ["src/content/assets/**", "src/content/scene/**", "src/content/references/**", "src/foundation/core/Inno.Core.Identity/**", "src/foundation/extensibility/Inno.Extensibility.Reload/**", "tests/assets/**", "tests/scene/**", "src/runtime/plugins/**", "tests/plugins/**", "src/foundation/scripting/**", "src/runtime/scripting/**", "tests/scripting/**", "**/*ScriptingApi*"] +tags: [identity-reload, serialization, reload, identity-standard] +--- # Identity and reload -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 20. Identity, Missing, references and reload -- Resolve live objects through `Inno.Core.Identity` when crossing UI, callback, queue, frame, Scene, Asset, Scripting or Plugin-generation boundaries. Use `Identity.runtimeId` for transient resolution within the current domain. Persistence, History and cross-generation restoration store only `Identity.persistentId`. Runtime IDs must never enter Scenes, Prefabs, Asset metadata, Settings, Plugin manifests or History. +- Resolve live objects through `Inno.Core.Identity` when crossing UI, callback, queue, frame, Scene, Asset, Scripting or Plugin-generation boundaries. Use `Identity.runtimeID` for transient resolution within the current domain. Persistence, History and cross-generation restoration store only `Identity.persistentID`. Runtime IDs must never enter Scenes, Prefabs, Asset metadata, Settings, Plugin manifests or History. - Stable Type IDs, semantic IDs such as Plugin/Feature/Importer IDs, Artifact keys and generation handles retain separate meanings and must not be confused with object Identity. Domain secondary indexes may map paths/semantic keys to persistent IDs or immutable records, but cannot become another authority for live objects across generations. - An Editor ImGui DragDrop native payload contains the source identity's runtime ID. Do not use a random token to look up a managed source object. Preview and Delivery both resolve again through the correct `IdentityAllocator` and verify the generation. Convert to persistent ID when recording a Drop on disk or in History. - When an Asset, Script Type, Plugin, Importer, Component/System, Graph node, Settings contribution or extension is temporarily unavailable, preserve its Missing state: original persistent ID, Stable ID, structural position, property bytes, dependencies and neutral extension state. APIs and UI must strictly distinguish Missing from null/Unassigned. @@ -15,10 +15,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Scripting, Plugin, Asset type, Serializer and extension generations participate in the shared candidate transaction. Successful retirement of old collectible ALCs requires Full GC → `GC.WaitForPendingFinalizers()` → Full GC and weak monitors confirming every context is unreachable. Before that barrier completes, reload must not report Success or permit another reload, Play, Build or Export. - An unload-verification timeout causes an explicit exception and Faulted state. Never clear still-Pending monitors and continue. Failures identify module/domain/scope/generation. A Faulted process cannot continue generation transactions and requires a full Host restart. Tests cover old-generation strong references from statics, events, tasks, threads, AsyncLocal, GCHandle, native callbacks and Editor transient state. - The full specification, target APIs, current gaps and test matrix are in the selected InnoEngine.Docs snapshot's `content/en/architecture/identity-and-recovery.md` and linked source validation records. Reconcile those authorities when changing Identity, Scripting, Plugins, Assets, Scene, Editor Interactions/History or any collectible extension. - - - ## 12. Required architecture checks Once they can be implemented reliably with low false-positive rates, the Architecture Tool must check at least: @@ -37,10 +34,7 @@ Once they can be implemented reliably with low false-positive rates, the Archite 12. Secondary indexes map domain keys only to identities/immutable records, never becoming live-object authorities across generations. Use Roslyn/metadata analysis for rules requiring C# type and field understanding. Keyword scans that misclassify contentVersion, list indexes or backend handles do not replace semantic checks. - - - ## 13. Test matrix ### 13.1 Identity @@ -101,13 +95,9 @@ Also verify: - Success is published only after every monitor is Completed. - Shadow generation storage is cleaned after success. - Shutdown aggregates and reports still-Pending/Faulted generations instead of silently exiting. - - - ## 14. Acceptance and change requirements Changes to identity, resolvers, Missing or reload must run the preceding matrix and update domain callers and shutdown order together. A count of passing tests does not replace evidence of cross-domain production transactions, failure compensation and old-ALC unreachability. Maintain current execution status in [current acceptance](../../records/acceptance/current.md) and [open items](../../records/open-items.md). This page does not maintain a second progress ledger or historical test count. - diff --git a/.agents/rulebook/domains/plugins.md b/.agents/rulebook/domains/plugins.md index 7eaf1e689..3895d21e8 100644 --- a/.agents/rulebook/domains/plugins.md +++ b/.agents/rulebook/domains/plugins.md @@ -1,9 +1,9 @@ +--- +paths: ["src/runtime/plugins/**", "tests/plugins/**"] +tags: [plugins] +--- # Plugins -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 18. Plugin and structured-content boundaries - The Project root has sibling `Plugins` and `Assets` directories. `Assets` is the sole official writable authoring source. Export an entire Project directly to `.iplugin` with File > Export as Plugin; do not create a PluginDefinitionAsset or a second package-authoring asset. `Plugins/*.iplugin` is the sole installation source. Folder Plugins, `.zip` Plugins and other extensions are unsupported. Fully validate installed packages and mount them as read-only Asset Sources in the existing Asset Catalog, Importer, dependency graph and Artifact flow. Do not create a Plugin-specific asset database. - File Browser and all Asset mutation APIs must treat installed `.iplugin` content as logically read-only. External replacement of an `.iplugin` updates installed content and starts a candidate transaction; it grants no Editor write permission. `Library/Plugins` always remains a noneditable, fully rebuildable cache. @@ -13,4 +13,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Plugin extensions must reuse existing AssemblyDomain.InnoPlugin, collectible ALC, TypeCache, TypeRegistry and candidate transactions. Persistent state must not retain Plugin Types, instances or delegates. - All structured assets, Graphs, Plugin manifests and Project Settings must use ISerializable, SerializableProperty, Serialization Converters and SerializationManager. Only inherently textual content, such as C#, Shader source/includes and ordinary documentation, may remain text. Do not create separate JSON persistence paths for Rendering, Plugins or Settings. - Plugins may contribute assets, Shaders, Pipelines, Importers, Components, Editor extensions, settings and gameplay code together. Manifests must not maintain per-domain type lists. Stable attributes and TypeRegistry continue to discover concrete extensions automatically. - diff --git a/.agents/rulebook/domains/rendering.md b/.agents/rulebook/domains/rendering.md index 1caf393d9..eeafa8cf5 100644 --- a/.agents/rulebook/domains/rendering.md +++ b/.agents/rulebook/domains/rendering.md @@ -1,9 +1,9 @@ +--- +paths: ["src/services/rendering/**", "src/adapters/rendering/**", "tests/rendering/**"] +tags: [rendering, content-frame] +--- # Rendering -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 17. Rendering boundaries - Rendering's public design must satisfy cross-platform support, API usability, flexible extension and low coupling together. Implementation convenience does not justify sacrificing any of them. - Only `Inno.Adapter.Rendering.Bgfx`, BGFX build toolchains and the corresponding native tests may reference `Inno.Native.Bgfx`. BGFX handles, View IDs, native pointers and BGFX enums must not appear in other projects' public/protected APIs. @@ -14,10 +14,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Project script extensions may use only backend-neutral Rendering APIs. Isolate extension failures. Activate successful candidates atomically only at frame-safe points, retaining last-good Pipelines, Shaders and GPU resources. - Rendering Core provides graphics mechanisms only. It must not embed 2D, 2.5D, 3D, PBR, Forward, Deferred, Light, Shadow, Camera, MeshRenderer or any concrete rendering worldview. All concrete rendering models must be composable from scratch through Project scripts or Plugins. - Shaders, Techniques, Materials and Pipelines compose through open Stable ID contracts. The core must not maintain closed lists of Pass Tags, Render Paths, resource semantics or quality settings. - - - ## 27. Content, rendering layers and frame ownership - `Inno.Content` depends only on necessary Foundation contracts and unifies logical ContentKeys, Pack indexes, read budgets and read-only leases. Shared Player, Runtime Session and AssetDatabase code does not read deployment files or create physical directories. Concrete content sources own files, HTTP, caches and owned streams. Asset consumption reuses `ArtifactLease.OpenRead()`; each opened stream holds an independent pin. @@ -28,4 +25,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Rebuild Contributor snapshots only when registration changes, and freeze them at frame start. Clear extension references from private scratch on normal frames, failures and retirement. Graph Validate performs analysis only; final Compile performs complete resource allocation exactly once. Mutation rollback restores both graph and validation state. Do not modify an accepted pass. - Native recipes declare their actual input closure and tool identities. Share the initial input scan within an operation, retaining necessary revalidation after waiting for a lease and before publication. An unrelated assembly MVID cannot replace a component recipe identity. Unify Task bootstrapping and isolate target properties. Content-identical native deployment must not copy files, replace loaded DLLs or update mtimes. - Shared compilation of a Task's complete execution closure uses Core IO leases to coordinate cross-process writes and releases MSBuild nodes while waiting. The minimal bootstrap publisher uses operation-private intermediate state. Existing immutable-publication and reader protocols then manage loading and retirement. - diff --git a/.agents/rulebook/domains/scripting.md b/.agents/rulebook/domains/scripting.md index 9fa19d005..fc18c8c55 100644 --- a/.agents/rulebook/domains/scripting.md +++ b/.agents/rulebook/domains/scripting.md @@ -1,9 +1,9 @@ +--- +paths: ["src/foundation/scripting/**", "src/runtime/scripting/**", "tests/scripting/**", "**/*ScriptingApi*"] +tags: [scripting] +--- # Scripting -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 12. Scripting API manifests - Each project participating in the script API has exactly one `Properties/ScriptingApi.cs`. Do not scatter export attributes through business source or centralize them in a manifest project that depends back on every module. - Export each type explicitly with `ScriptingApiExport`. Do not restore metadata/property mechanisms that expose an assembly's entire public API. @@ -12,4 +12,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Runtime compilation and IDE projects must use the same trimmed reference assemblies. Verify both paths after changing a manifest. - Compilation-wide/global usings are completely prohibited, including handwritten directives, MSBuild `Using` items, implicit imports and metadata injection. Every source and script file must explicitly declare its own ordinary `using` directives. - Scripts must use logical namespaces, such as `using InnoEngine.Scene;`, and must not directly use implementation-side `Inno.*` namespaces. - diff --git a/.agents/rulebook/no-legacy.md b/.agents/rulebook/no-legacy.md new file mode 100644 index 000000000..5917e1f56 --- /dev/null +++ b/.agents/rulebook/no-legacy.md @@ -0,0 +1,13 @@ +--- +paths: ["src/runtime/plugins/**", "tests/plugins/**"] +tags: [no-legacy, new-boundary] +--- +# No legacy compatibility + +## 15. No legacy compatibility or schema versions +- InnoEngine is a personal engine whose current source and current Project data evolve together. New or changed features do not support old files, schemas, fields, cache directories, namespaces, APIs or serialization layouts. Do not add fallback readers, migrations, compatibility aliases, former IDs, deprecated wrappers or dual writes for them. +- Persistence models, Attributes, Importers, Build Processors, History, Workspaces, Scenes, Prefabs, Asset metadata, Catalogs and script manifests must not introduce legacy-adaptation fields such as `version`, `schemaVersion`, `formatVersion` or `formerVersion`. When a format changes, update the current writer, reader, tests, documentation and Project data directly. Old data may be explicitly invalidated and regenerated. +- Do not reserve migration branches for hypothetical future compatibility. Only an explicit user request to import a particular old format permits a one-time converter with a clear boundary. Conversion logic must not enter normal runtime paths. +- Update all callers when deleting or refactoring an API. Do not retain old overloads, namespace facades, forwarding types or `[Obsolete]` compatibility layers unless the user explicitly requests them. +- These rules permit runtime identities required for current correctness, including TypeCache/Assembly generations, concurrency revisions, change counters, content hashes, artifact fingerprints, MVIDs, job-handle generations and strict magic/headers used only to reject damaged or incorrect input formats. They must not become mechanisms for reading multiple legacy schema generations. +- When reviewing or cleaning implementations named `version`, `legacy`, `migration`, `compatibility`, `former` or `deprecated`, first determine whether they serve only old data/APIs. If so, remove them together with their tests and documentation rather than extending them. diff --git a/.agents/rulebook/projects.md b/.agents/rulebook/projects.md new file mode 100644 index 000000000..21efc3f38 --- /dev/null +++ b/.agents/rulebook/projects.md @@ -0,0 +1,38 @@ +--- +paths: ["**/*.csproj", "**/*.sln", "**/*.slnx", "**/*.props", "**/*.targets"] +tags: [solution, directories, new-boundary] +--- +# Solutions and projects + +## 10. Directory boundaries +- `src/foundation`: Core, extension catalogs, types and generation contracts. +- `src/content`: Assets, References, Scene and Animation. +- `src/services`: backend-neutral domain contracts and runtime services. +- `src/runtime`: Runtime, deployment, generators, Plugins and authoring-time scripting workflows. +- `src/adapters`: neutral SPIs, open Provider/Catalog contracts and Core Events input implementations. +- `backends/`: shared backend runtime, native code and build recipes; each component has one source owner. Component tests belong to `tests/backends/`. +- `platforms/`: system and SDK integration, explicit targets, thin Editor/Player entries, layouts and Support Packs. A platform must not reference another platform. +- `src/composition`: default engine, Shell, Player and Editor composition entries. +- `entry`: the two lightweight development entries and current-host routing. Other production layers must not reference it. `Inno.Packages.props` pins NuGet versions for the BGCS package family; no source-dependency entry is provided. +- `build`, `tools`, `tests`: neutral unified builds, concrete distribution registration, validation libraries and tests. All engine-owned tests, fixtures and test support belong to the root `tests` tree; upstream tests inside `extern` retain their upstream owner. Production projects must not reference test projects or test support. +- Place new files in directories matching the existing layers and responsibilities wherever possible. + +## 26. Solutions and project files + +- Solution Folders represent actual architectural responsibilities. Remove empty groups containing neither valid projects nor Solution Items. Avoid unnecessary single-project wrapper groups for small project collections. +- Authored projects under `entry`, `src`, `backends`, `platforms`, `build`, `tools` and `tests` belong in the Solution, including binding-generation extensions and test fixtures. Exclude `obj`, `artifacts` and independent third-party projects in extern. A project without incoming ProjectReferences is not necessarily unused: check host entries, MSBuild tool calls and generator configuration before removing it. +- Use two-space indentation in `.csproj`, `.props` and `.targets`, blank lines between top-level responsibility blocks, one property per line in long property lists, and `/` in relative ProjectReference paths. +- Merge adjacent reference groups only when their conditions and reference visibility match. Do not reorder Imports, Properties or Targets, or change conditions, metadata or evaluation order. Preserve Editor public/implementation reference boundaries. +- Detailed rules are in `.agents/rulebook/coding.md`. After reorganization, verify valid XML, Solution project identities and configurations, then run affected builds and architecture validation. +- After phases of long builds or acceptance, clean this operation's obsolete tool snapshots, private load directories and test-browser profiles, and check free disk space. Before cleanup, verify the explicit owner, resolved absolute paths, symbolic links and active processes. Retain current artifacts and acceptance logs; do not clean user or SDK global caches. Logical sizes of hardlinked/compressed files do not establish physically reclaimed space. + +## 12. Solution and MSBuild readability + +- Solution Folders express actual responsibility layers. Remove groups without projects or valid Solution Items. Small repositories do not need extra categories wrapping single projects. +- Include all authored source projects in the Solution, including binding-generation extensions and test fixtures; exclude generated artifacts and third-party projects. Before declaring a project without incoming references obsolete, check host entries, MSBuild tool calls and generation configuration. +- Use two-space indentation and LF in `.csproj`, `.props` and `.targets`, with one blank line between top-level responsibility blocks. Do not mix tabs and spaces. +- Keep simple declarations on one line. Put long attribute lists after the element name, one attribute per line. Do not split attribute values in ways that change paths, conditions or commands. +- Use `/` in relative ProjectReference paths. Group implementation dependencies separately from public-signature dependencies according to project rules. Do not mechanically merge groups with different conditions, visibility or responsibilities. +- Remove empty PropertyGroup/ItemGroup elements with no attributes, content or comments. Merge adjacent reference groups only when conditions and visibility match and no intervening evaluation step exists. +- MSBuild evaluates in order. Formatting-only cleanup verifies property values, conditions, metadata, Imports, Targets and effective project-reference order. General XML sorting is not safe project reorganization. +- Preserve actual platform conditions and SDK/toolchain constraints. Formatting platform projects must not move those concerns into neutral business layers. diff --git a/.agents/rulebook/validation.md b/.agents/rulebook/validation.md index 5a49f35ef..273fedc2f 100644 --- a/.agents/rulebook/validation.md +++ b/.agents/rulebook/validation.md @@ -1,24 +1,26 @@ +--- +paths: ["tests/**", "**/tests/**", "AGENTS.md", "CONTRIBUTING.md", ".agents/**"] +tags: [tests, compilation, completion, review, new-boundary, public-api, ownership, delivery, rules, skills, records] +--- # Validation -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 8. Test boundaries - Changes to regression, public-contract and validation-tool tests required by the task are permitted. Preserve existing assertions and failure scenarios. Unrelated test rewrites, weaker assertions, production entry points only for tests, InternalsVisibleTo and reflection bypasses are prohibited. - Select tests from the actual impact graph, behavioral contracts and execution prerequisites. Test filters must not conceal native build dependencies. - - - ## 9. Compilation safety - Before ending a conversation, do not leave visible compilation errors introduced within the changed target scope, including non-test code. - Explicitly identify potential compilation risks in the delivery description. - - - +## 10. Tests and acceptance + +- Use real public contracts and replaceable public boundaries. +- InternalsVisibleTo, test backdoors, reflection bypasses and widening internal visibility for tests are prohibited. +- Cover real success, failure, cancellation, boundary and lifecycle behavior. Do not write tests that merely repeat the implementation. +- Native calls, AOT, trimming and platform support require actual artifact evidence. +- Report build, test, SDK, host and device status separately. Unexecuted checks are not passes. + ## 19. Completion requirements for new systems - Define clear assembly/domain boundaries and minimal public entry points before implementing UI or platform adapters. Isolate platforms, storage, compilers and presentation behind replaceable contracts. Do not accumulate temporary workflows in Panel, Application or static utility classes. - Prefer explicit base classes or interfaces for extension discovery. When inheritance or an interface completely identifies an extension and no additional declaration data is required, do not add a parameterless marker Attribute. Attributes carry parameters or explicitly optional semantics that type relationships cannot express, such as stable IDs, ordering, scope and multiple-instance permission. Never make inheritance and a parameterless Attribute two registration conditions that must be synchronized. @@ -27,10 +29,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Keep public APIs small and complete. Do not ask users to create companion assets, repeat manifests or change unrelated callers for information the engine can reliably derive. Explain each new public API's necessity and stable semantics in the delivery description. - InternalsVisibleTo, test backdoors, reflection bypasses and widening internal member visibility to simplify tests are strictly prohibited. Test behavior through real public contracts and replaceable public boundaries only. - Classify new projects and feature files by responsibility; match each filename to its primary type. A file contains closely related contracts or implementation only. Avoid ambiguous helper/internal directories and giant files containing unrelated types. - - - ## 30. Semantic review and delivery - Do not create or retain Agent.md, AGENTS.md or case variants in the BindGen-CS repository. Engine agent requirements belong only in the engine's own rules. @@ -39,4 +38,10 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Verify extensibility through real callers, replaceable boundaries and applicable validation. Explain from actual code which owners must change to add a backend or platform. Unexecuted tests and abstract declarations are not evidence. - Every final delivery must briefly state this review's findings, actual validation evidence and unresolved or unavailable work. If verification is incomplete, say so; do not claim perfection or that everything passed. - Before ending execution, reconcile the issue's actual resolution criteria, all approved implementation and acceptance requirements, architectural clarity, foundational reuse and new regressions. When actionable work remains, update the remaining execution plan and continue automatically without requesting repeated approval. Deliver only after all applicable work is complete or external blockers that cannot be resolved independently are explicitly recorded. Stage progress or passing CI does not establish completion of the entire plan. - + +## 11. Change management + +- Formatting-only changes preserve syntax tokens, execution order, contracts and diagnostics. +- Validate naming, responsibility and behavior changes separately from pure formatting. +- Public API, reference-boundary and generation-protocol changes also update consumers, indexes, examples and architecture checks. +- Before completion, ensure the target scope compiles and record validation commands, results and remaining limitations. diff --git a/.agents/skills/inno-api-docs/SKILL.md b/.agents/skills/inno-api-docs/SKILL.md index 918faedfc..eba181be9 100644 --- a/.agents/skills/inno-api-docs/SKILL.md +++ b/.agents/skills/inno-api-docs/SKILL.md @@ -3,7 +3,7 @@ name: inno-api-docs description: Maintain InnoEngine design, usage, API XML and examples against actual public and protected contracts. --- -Select applicable `wiki` and `xml` units through the rule loader with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) have one authority in that checkout. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. +Select the `wiki` and `xml` tags through the rule script with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) have one authority in that checkout; `main` is published and [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) is unpublished. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. Use Build `docs search/read/symbol` against a prepared snapshot to locate task guidance, the authoritative project entry and exact qualified symbols. Read necessary associated contracts and explicit continuations. Search excerpts and API markers are not complete contracts or matching source verification evidence. diff --git a/.agents/skills/inno-change/SKILL.md b/.agents/skills/inno-change/SKILL.md index b4775a9bc..50b6d3cd8 100644 --- a/.agents/skills/inno-change/SKILL.md +++ b/.agents/skills/inno-change/SKILL.md @@ -3,12 +3,10 @@ name: inno-change description: Scope an InnoEngine implementation by actual owners, behavior changes, applicable rules and finite acceptance. --- -Confirm the branch, workspace changes and implementing owner; protect other sessions. Run `tests/ci/Test-AgentRules.ps1` from the engine root to select complete rule units by repository-relative paths and behavior tags. The [rulebook](../../rulebook/README.md) is their sole authority. +Confirm the branch, workspace changes and implementing owner; protect other sessions. Run `tests/ci/Test-AgentRules.ps1` from the engine root to select rule files by repository-relative paths and work tags. The [rulebook](../../rulebook/README.md) is their sole authority. When task guidance or an API contract is needed, select a prepared documentation snapshot. Use Build `docs search/read/symbol`, then verify relevant source and actual project relationships. Reuse loaded content while its identity and scope remain unchanged. Refresh after relevant edits; a query never creates a Docs candidate or certifies source API correctness. Identify behavior changes, lifecycle obligations, failure rollback, required callers and finite acceptance. Reuse existing Core mechanisms. Keep task context to owners, rules, documentation/source entry points, decisions and verification reasons. Ordinary local changes do not require another whole-engine audit. Use `validate plan` for check selection; do not keep a skill-specific test list. A private presentation change still needs relevant behavior and lifecycle coverage; unrelated product obligations need an actual dependency or behavior reason. Maintain API XML in the engine; master-to-draft synchronization owns generated reference updates. Change the Docs Manual only when usage guidance changes, from its `draft` baseline. Update the existing [record](../../records/README.md) with scope, decisions, input identity, valid evidence, blockers and next action; track unrelated improvements separately. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. diff --git a/.agents/skills/inno-delivery/SKILL.md b/.agents/skills/inno-delivery/SKILL.md index a811da138..e93eb87f4 100644 --- a/.agents/skills/inno-delivery/SKILL.md +++ b/.agents/skills/inno-delivery/SKILL.md @@ -3,12 +3,10 @@ name: inno-delivery description: Review InnoEngine semantic risks and matching evidence, then prepare accurate issues or pull requests and diagnose CI failures. --- -Select `delivery`, `review` and `notification` units through the rule loader; use the [delivery rules](../../rulebook/delivery.md). Review changed dependency directions, input authority, rollback, concurrency and resource retirement. Directory neatness and test counts do not prove correctness. +Select the `delivery`, `review` and `notification` tags through the rule script; use the [delivery rules](../../rulebook/delivery.md). Review changed dependency directions, input authority, rollback, concurrency and resource retirement. Directory neatness and test counts do not prove correctness. Reconcile the approved plan and every required result with current inputs. Distinguish missing implementation, unexecuted acceptance and external blockers. Report final behavior, actual checks, outstanding work and necessary action. Use English `type(scope): description` issue/PR titles and English bodies. Never promote historical evidence to a current pass. Report API synchronization, Docs validation, manual editorial work and website deployment separately. API export tracks an exact master input; Docs can publish its already selected API version without waiting for a newer unrelated engine CI run. Draft previews never deploy. Only a human Docs `draft` to `main` merge authorizes automatic site deployment. Do not automatically merge either repository's PRs or formally publish an engine release. An authorized draft engine release uses the same verified product artifacts without rebuilding. Diagnose the first CI failure before retrying; preserve its evidence and the retry reason. Commit identity, pushes, publishing and external communication follow the delivery rules and existing user authorization. Local staged acceptance does not itself authorize a large remote matrix. Clean only owned temporary output through registered ownership and reading protections; retain useful caches, active readers and first-failure diagnostics. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. diff --git a/.agents/skills/inno-verify/SKILL.md b/.agents/skills/inno-verify/SKILL.md index ec9ade8f7..2d98acc4a 100644 --- a/.agents/skills/inno-verify/SKILL.md +++ b/.agents/skills/inno-verify/SKILL.md @@ -3,7 +3,7 @@ name: inno-verify description: Plan and execute bounded InnoEngine validation; diagnose failures and reconcile evidence with current inputs. --- -Load applicable units from the [validation rules](../../rulebook/validation.md) through the rule selector. Use Build `validate plan/run/full/evidence`; inspect owners, reasons, environments, prerequisite artifacts and exclusions. The planner owns the check inventory. +Load the [validation rules](../../rulebook/validation.md) through the rule script. Use Build `validate plan/run/full/evidence`; inspect owners, reasons, environments, prerequisite artifacts and exclusions. The planner owns the check inventory. Check evidence identities before executing missing or invalid work. Commits, pushes, report edits and session recovery are not reasons to repeat valid checks. Record the exact invalidating input. Preserve the first failure and retry reason; do not rerun until a run happens to turn green. Unknown owners, empty required discovery, skipped jobs and unavailable environments are not passes. Device, performance, stress and lifecycle checks follow their actual obligations. @@ -12,5 +12,3 @@ Block work whose prerequisites failed; continue independent work when input inte Ordinary engine verification does not require a paired Docs candidate. Independent API extraction verifies complete source/XML/projection facts; Docs validation checks its selected API version and examples. `API editorial coverage` warnings are neutral and never substitute for or block these checks. Keep a tool crash, corrupt data, missing environment and an editorial reminder distinct. Write statuses, exact input identities, failure causes, fixes and outstanding evidence to the existing [acceptance record](../../records/acceptance/README.md). Respect an explicitly local acceptance boundary; retain the unexecuted matrix as outstanding work. Historical evidence is not current certification. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. diff --git a/.editorconfig b/.editorconfig index 9b7881294..2d213f4c6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,6 +13,8 @@ indent_size = 2 [*.cs] indent_style = space indent_size = 4 +# F-04: aim for 120 columns; 140 is the hard limit checked by 'InnoEngine.Build style'. +max_line_length = 140 # Method and lambda bodies keep the opening brace with the closing parameter list. csharp_new_line_before_open_brace = types, properties, accessors, anonymous_types, control_blocks, object_collection_array_initializers csharp_using_directive_placement = outside_namespace:warning @@ -23,40 +25,183 @@ dotnet_diagnostic.CS1573.severity = warning dotnet_diagnostic.CS1591.severity = warning dotnet_diagnostic.IDE0005.severity = warning -dotnet_naming_rule.properties_are_camel_case.symbols = properties -dotnet_naming_rule.properties_are_camel_case.style = camel_case -dotnet_naming_rule.properties_are_camel_case.severity = warning -dotnet_naming_symbols.properties.applicable_kinds = property -dotnet_naming_style.camel_case.capitalization = camel_case +# N-01: file-scoped namespaces. +csharp_style_namespace_declarations = file_scoped +dotnet_diagnostic.IDE0161.severity = warning +# T-01: every type and member states its accessibility. +dotnet_style_require_accessibility_modifiers = for_non_interface_members +dotnet_diagnostic.IDE0040.severity = warning +# T-02: modifier order. +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async,partial +dotnet_diagnostic.IDE0036.severity = warning +# T-05: structs are readonly when they can be. +csharp_style_prefer_readonly_struct = true +dotnet_diagnostic.IDE0250.severity = warning +# M-02: one expression is an expression body; constructors use a block. +csharp_style_expression_bodied_methods = true +csharp_style_expression_bodied_properties = true +csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_operators = true +csharp_style_expression_bodied_accessors = true +csharp_style_expression_bodied_local_functions = true +csharp_style_expression_bodied_lambdas = true +csharp_style_expression_bodied_constructors = false +dotnet_diagnostic.IDE0021.severity = warning +dotnet_diagnostic.IDE0022.severity = warning +dotnet_diagnostic.IDE0023.severity = warning +dotnet_diagnostic.IDE0024.severity = warning +dotnet_diagnostic.IDE0025.severity = warning +dotnet_diagnostic.IDE0026.severity = warning +dotnet_diagnostic.IDE0027.severity = warning +dotnet_diagnostic.IDE0053.severity = warning +dotnet_diagnostic.IDE0061.severity = warning +# I-02: collections use collection expressions. +dotnet_style_prefer_collection_expression = when_types_exactly_match +dotnet_diagnostic.IDE0028.severity = warning +dotnet_diagnostic.IDE0300.severity = warning +dotnet_diagnostic.IDE0301.severity = warning +dotnet_diagnostic.IDE0302.severity = warning +dotnet_diagnostic.IDE0303.severity = warning +dotnet_diagnostic.IDE0304.severity = warning +dotnet_diagnostic.IDE0305.severity = warning +# E-01, E-02: locals state their type. 'var' with 'new T(...)' is checked by 'InnoEngine.Build style'. +csharp_style_var_for_built_in_types = false +csharp_style_var_when_type_is_apparent = true +csharp_style_var_elsewhere = false +dotnet_diagnostic.IDE0008.severity = warning +# E-03: built-in types use keywords. +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true +dotnet_diagnostic.IDE0049.severity = warning +# E-04: null checks use patterns. +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +csharp_style_prefer_not_pattern = true +dotnet_diagnostic.IDE0041.severity = warning +dotnet_diagnostic.IDE0083.severity = warning +# E-07: common values. +csharp_prefer_simple_default_expression = true +csharp_style_pattern_matching_over_as_with_null_check = true +csharp_style_pattern_matching_over_is_with_cast_check = true +csharp_style_conditional_delegate_call = true +dotnet_diagnostic.IDE0034.severity = warning +dotnet_diagnostic.IDE0019.severity = warning +dotnet_diagnostic.IDE0020.severity = warning +dotnet_diagnostic.IDE0038.severity = warning +dotnet_diagnostic.IDE1005.severity = warning +dotnet_diagnostic.IDE0100.severity = warning +dotnet_diagnostic.CA2200.severity = suggestion +# E-05: argument validation uses the ThrowIf helpers. +dotnet_diagnostic.CA1510.severity = suggestion +dotnet_diagnostic.CA1511.severity = suggestion +dotnet_diagnostic.CA1512.severity = suggestion +dotnet_diagnostic.CA1513.severity = suggestion +# E-09: identifiers use nameof; string operations state their comparison and culture. +dotnet_diagnostic.CA1507.severity = suggestion +dotnet_diagnostic.CA1304.severity = suggestion +dotnet_diagnostic.CA1305.severity = suggestion +dotnet_diagnostic.CA1307.severity = suggestion +dotnet_diagnostic.CA1309.severity = suggestion +dotnet_diagnostic.CA1310.severity = suggestion +dotnet_diagnostic.CA1311.severity = suggestion +# E-11: lambdas that capture nothing are static. +csharp_prefer_static_anonymous_function = true +dotnet_diagnostic.IDE0320.severity = warning +# E-12: using declarations. +csharp_prefer_simple_using_statement = true +dotnet_diagnostic.IDE0063.severity = warning +# T-03: internal classes without derived types are sealed. +dotnet_diagnostic.CA1852.severity = suggestion +# X-05: asynchronous code. +dotnet_diagnostic.CA2007.severity = suggestion +dotnet_diagnostic.CA2016.severity = suggestion -dotnet_naming_rule.private_fields_have_owner_prefix.symbols = private_fields -dotnet_naming_rule.private_fields_have_owner_prefix.style = owner_field -dotnet_naming_rule.private_fields_have_owner_prefix.severity = warning -dotnet_naming_symbols.private_fields.applicable_kinds = field -dotnet_naming_symbols.private_fields.applicable_accessibilities = private +# NM-01 to NM-12: the naming table. 'InnoEngine.Build style' checks the same table, the acronyms of NM-13 and the +# exceptions for contract names. NM-04 is checked only there because test methods take no 'Async' suffix. +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_naming_style.camel_case.capitalization = camel_case +dotnet_naming_style.interface_name.required_prefix = I +dotnet_naming_style.interface_name.capitalization = pascal_case +dotnet_naming_style.type_parameter_name.required_prefix = T +dotnet_naming_style.type_parameter_name.capitalization = pascal_case dotnet_naming_style.owner_field.required_prefix = m_ dotnet_naming_style.owner_field.capitalization = camel_case +dotnet_naming_style.static_field.required_prefix = s_ +dotnet_naming_style.static_field.capitalization = camel_case +dotnet_naming_style.constant_name.required_prefix = C_ +dotnet_naming_style.constant_name.capitalization = all_upper +dotnet_naming_style.constant_name.word_separator = _ +dotnet_naming_style.upper_snake.capitalization = all_upper +dotnet_naming_style.upper_snake.word_separator = _ + +# NM-01: types. +dotnet_naming_rule.types_are_pascal_case.symbols = types +dotnet_naming_rule.types_are_pascal_case.style = pascal_case +dotnet_naming_rule.types_are_pascal_case.severity = warning +dotnet_naming_symbols.types.applicable_kinds = class, struct, enum, delegate + +# NM-02: interfaces and type parameters. +dotnet_naming_rule.interfaces_start_with_i.symbols = interfaces +dotnet_naming_rule.interfaces_start_with_i.style = interface_name +dotnet_naming_rule.interfaces_start_with_i.severity = warning +dotnet_naming_symbols.interfaces.applicable_kinds = interface + +dotnet_naming_rule.type_parameters_start_with_t.symbols = type_parameters +dotnet_naming_rule.type_parameters_start_with_t.style = type_parameter_name +dotnet_naming_rule.type_parameters_start_with_t.severity = warning +dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter -# More specific modifier rules take precedence over the private-field rule. +# NM-03: methods and local functions. +dotnet_naming_rule.methods_are_pascal_case.symbols = methods +dotnet_naming_rule.methods_are_pascal_case.style = pascal_case +dotnet_naming_rule.methods_are_pascal_case.severity = warning +dotnet_naming_symbols.methods.applicable_kinds = method, local_function + +# NM-05 and NM-10: properties and events. +dotnet_naming_rule.properties_are_camel_case.symbols = properties +dotnet_naming_rule.properties_are_camel_case.style = camel_case +dotnet_naming_rule.properties_are_camel_case.severity = warning +dotnet_naming_symbols.properties.applicable_kinds = property, event + +# NM-07: constants, including local constants. dotnet_naming_rule.constants_have_constant_prefix.symbols = constants dotnet_naming_rule.constants_have_constant_prefix.style = constant_name dotnet_naming_rule.constants_have_constant_prefix.severity = warning -dotnet_naming_symbols.constants.applicable_kinds = field +dotnet_naming_symbols.constants.applicable_kinds = field, local dotnet_naming_symbols.constants.required_modifiers = const -dotnet_naming_style.constant_name.required_prefix = C_ -dotnet_naming_style.constant_name.capitalization = all_upper -dotnet_naming_rule.static_readonly_fields_have_semantic_names.symbols = static_readonly_fields -dotnet_naming_rule.static_readonly_fields_have_semantic_names.style = pascal_case -dotnet_naming_rule.static_readonly_fields_have_semantic_names.severity = warning +# NM-08: static readonly fields. +dotnet_naming_rule.static_readonly_fields_are_upper_snake.symbols = static_readonly_fields +dotnet_naming_rule.static_readonly_fields_are_upper_snake.style = upper_snake +dotnet_naming_rule.static_readonly_fields_are_upper_snake.severity = warning dotnet_naming_symbols.static_readonly_fields.applicable_kinds = field dotnet_naming_symbols.static_readonly_fields.required_modifiers = static, readonly -dotnet_naming_rule.types_are_pascal_case.symbols = types -dotnet_naming_rule.types_are_pascal_case.style = pascal_case -dotnet_naming_rule.types_are_pascal_case.severity = warning -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum, delegate -dotnet_naming_style.pascal_case.capitalization = pascal_case +# NM-09: private static mutable fields. +dotnet_naming_rule.private_static_fields_have_static_prefix.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_have_static_prefix.style = static_field +dotnet_naming_rule.private_static_fields_have_static_prefix.severity = warning +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +# NM-06: instance fields. +dotnet_naming_rule.owned_fields_have_owner_prefix.symbols = owned_fields +dotnet_naming_rule.owned_fields_have_owner_prefix.style = owner_field +dotnet_naming_rule.owned_fields_have_owner_prefix.severity = warning +dotnet_naming_symbols.owned_fields.applicable_kinds = field +dotnet_naming_symbols.owned_fields.applicable_accessibilities = private, protected, private_protected + +dotnet_naming_rule.shared_fields_are_camel_case.symbols = shared_fields +dotnet_naming_rule.shared_fields_are_camel_case.style = camel_case +dotnet_naming_rule.shared_fields_are_camel_case.severity = warning +dotnet_naming_symbols.shared_fields.applicable_kinds = field +dotnet_naming_symbols.shared_fields.applicable_accessibilities = public, internal, protected_internal + +# NM-12: parameters and local variables. +dotnet_naming_rule.locals_are_camel_case.symbols = locals +dotnet_naming_rule.locals_are_camel_case.style = camel_case +dotnet_naming_rule.locals_are_camel_case.severity = warning +dotnet_naming_symbols.locals.applicable_kinds = parameter, local [**/Generated/*.cs] generated_code = true diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..a35fdd1eb --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,16 @@ +# style(csharp): apply the rulebook layout to all handwritten C# +9a88abf2030410838978c6a1be82c7612e99d9d8 +# style(csharp): apply the rulebook typing, null-check and qualification rules +29c9414af2d944067c9875f9400a2b0ea14464c0 +# style(csharp): apply the rulebook modifier, sealing and member order rules +95b7effa3934cdbf46d86b6f41389c1492b39b3f +# Rename non-public symbols to the rulebook naming +8de047da96764ca00db11c73f622bbcddbd8c8de +# C# public symbol renames to the rulebook naming +c46af2ba7e19ca3a69f2ab46bdb4aa8d17d70bec +# Rename test methods and remaining members to the naming table +49f33b29104df851a5ed5ad7cea453c68d527dc4 +# Apply the remaining mechanical rulebook rules +dce88f2ec6c70c91cdd7c9a9dcabd30e8d431a4d +# Keep one top-level type per file +840d139fa9e9be55c8d9c370caca105b22b96e2b diff --git a/.gitattributes b/.gitattributes index 375b2ba2a..798584fc0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ -# Keep authored MSBuild files consistent on every checkout host. +# Keep authored C# and MSBuild files consistent on every checkout host. +*.cs text eol=lf *.csproj text eol=lf *.props text eol=lf *.targets text eol=lf diff --git a/.gitignore b/.gitignore index 9fc4472b7..1142e00d5 100644 --- a/.gitignore +++ b/.gitignore @@ -151,7 +151,6 @@ _TeamCity* # Coverlet is a free, cross platform Code Coverage Tool coverage*.json -!.agents/rulebook/coverage.json coverage*.xml coverage*.info diff --git a/AGENTS.md b/AGENTS.md index 33bd14305..59d0c78ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,8 +5,8 @@ Architecture, responsibility, dependency direction, low coupling and resource ow ## Start a task 1. Confirm the branch, workspace changes, owner, behavioral scope and finite acceptance. Protect other sessions. Adjacent repositories are read-only unless explicitly authorized; InnoEngine.Docs owns product documentation. -2. Run `tests/ci/Test-AgentRules.ps1 -Paths -ShowInstructions` from the engine root. Absolute paths are also accepted. Add behavior tags with `-Behaviors` or explicit units with `-Rules`; the [rule registry](.agents/rulebook/coverage.json) is the sole routing authority. Documentation rules require `-DocsRoot `; the loader never guesses or downloads their authority. Do not depend on a client discovering nested instructions. -3. Read all selected complete units, their sources and reasons. If the combination exceeds 16 KiB, read every reported `-Stage` in sequence; never truncate or skip requirements. Root instructions have an 8 KiB hard limit. Use `new-boundary` for new boundaries and `delivery` for delivery work. +2. Run `tests/ci/Test-AgentRules.ps1 -Paths ` from the engine root. Absolute paths are also accepted. Add work tags with `-Tags` or explicit rule files with `-Rules`; each rule file declares its own paths and tags. Documentation rules require `-DocsRoot `; the script never guesses or downloads their authority. Do not depend on a client discovering nested instructions. +3. Read every listed rule file completely; never truncate or skip requirements. A rule file has a 16 KiB limit and root instructions an 8 KiB hard limit. Use `new-boundary` for new boundaries and `delivery` for delivery work. 4. When documentation is needed, select an explicit Docs snapshot. Build `docs index --docs-root ` prepares it; `docs search/read/symbol` query the published snapshot. Reuse loaded rules and documentation while their identities and scope remain unchanged. Refresh after relevant edits. Never guess sibling paths, silently compile during a query or require a Docs candidate for an ordinary engine task. ## Task workflows @@ -22,10 +22,10 @@ Skills describe workflows; they do not replace rules or maintain test lists. Def - [InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs) owns Manual, tutorials and authored API prose. The engine owns C# declarations, XML, actual script projection and query tooling. API changes maintain XML here; master exports flow to Docs `draft`. Manual changes use a Docs branch based on `draft`. No paired engine/Docs PR metadata is required. - Engine API includes public and externally usable protected C# contracts only from `src/` and `build/`, excluding declared tests and fixtures. All other roots are outside Engine API. Scripting uses actual projections and declared Scope. Platform implementation guides are excluded; shared capability limits and engine functional acceptance remain required. API prose is XML-managed unless its individual type/member has a nonempty author name in `source` other than `xml`; declarations follow source facts. Editorial gaps warn without blocking. Only a human `draft` to `main` release merge may publish the site. -- The [rulebook](.agents/rulebook/README.md) owns development requirements. Human contributors use the same rules through [CONTRIBUTING](CONTRIBUTING.md). +- The [rulebook](.agents/rulebook/README.md) owns development requirements as plain Markdown; rules change through a pull request that a human merges. Human contributors use the same rules through [CONTRIBUTING](CONTRIBUTING.md). - [Records](.agents/records/README.md) hold necessary plans, lasting decisions and acceptance. A handoff retains scope, decisions, input identity, valid evidence, blockers and next action. Do not load historical records by default. - Complete all applicable behavior, callers, references, XML, documentation and validation in the approved task. Record unrelated improvements separately. Required regression, contract and tooling tests may change; unrelated rewrites, weaker assertions, reflection bypasses and test-only production visibility remain prohibited. - Evidence must match current inputs. Missing, skipped or unavailable checks are not passes. Commits, pushes, report edits and session recovery do not by themselves invalidate evidence. Reconcile the approved plan and report unfinished acceptance and external blockers accurately; continue actionable work. -- Reuse stable build directories by workspace, configuration and target; keep logs separate. Local output uses explicit C-drive owners. Clean only owned temporary artifacts through the existing lease, registry and retirement protocols. Protect other sessions, active readers, useful caches and first failures. Remote delivery follows user authorization and delivery rules. +- Reuse stable build directories by workspace, configuration and target; keep logs separate. Clean only owned temporary artifacts through the existing lease, registry and retirement protocols. Protect other sessions, active readers, useful caches and first failures. Remote delivery follows user authorization and delivery rules. Documentation CI uses incremental draft checks and complete release-candidate checks. API export preflight and owner/context reuse are independent of engine functional acceptance. Read the Docs README for current event and artifact boundaries. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 987e5b3db..aca294b50 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,7 @@ Before implementation, identify the owner, observable behavior and finite accept For an API change, maintain its source XML and run the applicable engine checks. After a human merge to `master`, independent API export synchronizes eligible C# contracts and actual script projections into the Docs repository's persistent `draft` branch. This does not wait for unrelated full-engine acceptance. Backend, extern, test and fixture API references are excluded; their necessary engine tests remain. -Maintain tutorials and Manual changes separately in Docs, starting from `draft`. API types and members each have their own Markdown: `source: xml` (including an absent marker) is synchronized; `source: FLwolfy` preserves that symbol's prose. Generated declarations remain authoritative. Incomplete manual explanations produce non-blocking editorial warnings. A human merges Docs `draft` into `main` to publish the validated website. Engine PRs do not require paired Docs metadata. +Maintain tutorials and Manual changes separately in Docs, starting from `draft`. API types and members each have their own Markdown: `source: xml` (including an absent marker) is synchronized; `source: ` preserves that symbol's prose. Generated declarations remain authoritative. Incomplete manual explanations produce non-blocking editorial warnings. A human merges Docs `draft` into `main` to publish the validated website. Engine PRs do not require paired Docs metadata. Keep implementation and acceptance records in [.agents/records](.agents/records/README.md). Write active guidance and contributions in English; preserve historical evidence in its original form. Delivery must distinguish checks actually executed from work still outstanding. diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs index fb1ea281f..34df2eca1 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs @@ -1,15 +1,15 @@ -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; using System; -using System.Threading; using System.IO; using System.Linq; +using System.Threading; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Extensibility.Modules; @@ -46,6 +46,12 @@ public static class ShaderArtifactBuilder /// /// The artifact destination, replaced atomically after successful compilation. /// + /// + /// The host-selected executable distribution, or null for the application's deployed tools. + /// + /// + /// Cancels import and native compilation before replacing the destination artifact. + /// /// /// Import or shader compilation fails. /// @@ -61,12 +67,6 @@ public static class ShaderArtifactBuilder /// /// Import, copying, verification or compilation was canceled before publication. /// - /// - /// The host-selected executable distribution, or null for the application's deployed tools. - /// - /// - /// Cancels import and native compilation before replacing the destination artifact. - /// public static void Compile( ShaderBuildInputs inputs, ProcessOwnedDirectory workspace, @@ -105,6 +105,12 @@ public static void Compile( /// /// The device artifact destination, atomically replaced after successful compilation. /// + /// + /// The host-selected executable distribution, or null for the application's deployed tools. + /// + /// + /// Cancels import and native compilation before replacing the destination artifact. + /// /// /// A required shader path or output path is blank. /// @@ -120,12 +126,6 @@ public static void Compile( /// /// Import, copying, verification or compilation was canceled before publication. /// - /// - /// The host-selected executable distribution, or null for the application's deployed tools. - /// - /// - /// Cancels import and native compilation before replacing the destination artifact. - /// public static void CompileGraphicsProgram( ShaderBuildInputs inputs, ProcessOwnedDirectory workspace, @@ -139,10 +139,12 @@ public static void CompileGraphicsProgram( ArgumentException.ThrowIfNullOrWhiteSpace(outputFile); RenderShaderArtifact artifact = CompileArtifact(inputs, workspace, shaderPath, platform, backend, tools, cancellationToken); if (artifact.passes.Count != 1 || artifact.passes[0].programKind != ShaderProgramKind.Raster) + { throw new InvalidDataException("A device graphics program requires exactly one raster pass."); + } RenderShaderPassArtifact pass = artifact.passes[0]; RenderShaderBindingDescriptor[] bindings = pass.shaderInterface.bindings.Select(static binding => new RenderShaderBindingDescriptor( - new RenderBindingId(binding.id.value), + new RenderBindingID(binding.id.value), binding.bindingKind switch { ShaderPropertyBindingKind.Uniform => RenderShaderBindingKind.Uniform, @@ -155,11 +157,15 @@ public static void CompileGraphicsProgram( uniformType: binding.type == ShaderPropertyType.Matrix4x4 ? RenderUniformType.Matrix4x4 : RenderUniformType.Vector4, count: binding.arrayCount, storageAccess: binding.storageAccess, - nativeName: binding.nativeName)).ToArray(); + nativeName: binding.nativeName + )).ToArray(); var descriptor = new GraphicsPipelineDescriptor( pass.stages.Single(static stage => stage.stage == ShaderStage.Vertex).bytes.Span, pass.stages.Single(static stage => stage.stage == ShaderStage.Fragment).bytes.Span, - bindings, null, pass.rasterState); + bindings, + null, + pass.rasterState + ); byte[] payload = GraphicsProgramArtifactCodec.Encode(descriptor); inputs.VerifyUnchanged(cancellationToken); AtomicFile.WriteAllBytes(Path.GetFullPath(outputFile), payload); @@ -179,7 +185,9 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(shaderPath); string scratch = workspace.directory; if (!Directory.Exists(scratch) || Directory.EnumerateFileSystemEntries(scratch).Any()) + { throw new InvalidOperationException("Shader compilation requires a fresh, retained operation directory."); + } string assetRoot = inputs.Materialize(scratch, cancellationToken); var identities = new IdentityAllocator(); using IDisposable identityScope = identities.EnterScope(); @@ -187,25 +195,48 @@ CancellationToken cancellationToken using IDisposable diagnosticScope = diagnostics.EnterScope(); diagnostics.RegisterSink(new DiagnosticOutput()); using var logs = new LogRouter(); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderArtifactBuilder).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderArtifactBuilder).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - using var assets = new AssetPipeline(modules, types, serialization, identities, diagnostics, logs, - new() { assetRoot = Path.GetFullPath(assetRoot), libraryRoot = Path.Combine(scratch, "Library") }); + using var assets = new AssetPipeline( + modules, + types, + serialization, + identities, + diagnostics, + logs, + new AssetPipelineOptions() { assetRoot = Path.GetFullPath(assetRoot), libraryRoot = Path.Combine(scratch, "Library") } + ); AssetPath path = AssetPath.Project(shaderPath); // A fresh source import must succeed. An earlier build artifact never masks current source errors. if (!assets.Import(path)) + { throw new InvalidDataException($"Shader source '{path}' failed to import."); + } ShaderAsset shader = assets.Load(path); GraphicsCapabilities capabilities = platform.Resolve(backend).capabilities; var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform, tools)); ShaderCompileTarget target = compiler.CreateTarget(capabilities); - ShaderCompilationResult result = compiler.CompileGraphAsync(shader, target, RenderShaderVariant.empty, - types, serialization, AssetSerializationContext.Create(assets), assets, cancellationToken).AsTask().GetAwaiter().GetResult(); + ShaderCompilationResult result = compiler.CompileGraphAsync( + shader, + target, + RenderShaderVariant.empty, + types, + serialization, + AssetSerializationContext.Create(assets), + assets, + cancellationToken + ).AsTask().GetAwaiter().GetResult(); foreach (ShaderDiagnostic diagnostic in result.diagnostics) + { Console.Error.WriteLine($"{diagnostic.code}: {diagnostic.message}"); + } if (!result.succeeded || result.artifact is null) + { throw new InvalidDataException("Shader compilation failed; the output was not replaced."); + } Console.WriteLine($"Compiled {path}: {result.artifact.passes.Count} passes, {target.key}"); inputs.VerifyUnchanged(cancellationToken); return result.artifact.CreateRuntimeArtifact(); @@ -222,15 +253,20 @@ private sealed class DiagnosticOutput : IDiagnosticSink public void Replace(DiagnosticReport report) { foreach (Diagnostic diagnostic in report.diagnostics) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { Console.Error.WriteLine($"{diagnostic.code}: {diagnostic.message}"); + } + } } + /// /// Ignores report removal because console output retains no diagnostic state. /// /// /// The diagnostic source whose report was removed. /// - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs index 96eecf5cc..518bf704c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs @@ -31,7 +31,7 @@ CancellationToken cancellationToken m_sourceRoot = sourceRoot; m_files = inventory.files; m_directories = inventory.directories; - fingerprint = ComputeFingerprint(inventory, cancellationToken); + this.fingerprint = ComputeFingerprint(inventory, cancellationToken); } /// @@ -39,6 +39,30 @@ CancellationToken cancellationToken /// public string fingerprint { get; } + /// + /// Rechecks the complete current inventory and bytes against this operation's captured identity. + /// + /// + /// Cancels discovery and complete content verification. + /// + /// + /// A source or permanent metadata file was added, removed or changed. + /// + /// + /// The source tree cannot be safely inspected or read. + /// + /// + /// Verification was canceled. + /// + public void VerifyUnchanged(CancellationToken cancellationToken = default) + { + string actual = ComputeFingerprint(Discover(m_sourceRoot, cancellationToken), cancellationToken); + if (!string.Equals(actual, fingerprint, StringComparison.Ordinal)) + { + throw new InvalidDataException("Shader authoring inputs changed during compilation; the candidate cannot be published."); + } + } + /// /// Captures permanent authoring files and their import metadata without consuming temporary publications. /// @@ -69,28 +93,6 @@ public static ShaderBuildInputs Capture( return new ShaderBuildInputs(root, Discover(root, cancellationToken), cancellationToken); } - /// - /// Rechecks the complete current inventory and bytes against this operation's captured identity. - /// - /// - /// Cancels discovery and complete content verification. - /// - /// - /// A source or permanent metadata file was added, removed or changed. - /// - /// - /// The source tree cannot be safely inspected or read. - /// - /// - /// Verification was canceled. - /// - public void VerifyUnchanged(CancellationToken cancellationToken = default) - { - string actual = ComputeFingerprint(Discover(m_sourceRoot, cancellationToken), cancellationToken); - if (!string.Equals(actual, fingerprint, StringComparison.Ordinal)) - throw new InvalidDataException("Shader authoring inputs changed during compilation; the candidate cannot be published."); - } - internal string Materialize( string operationDirectory, CancellationToken cancellationToken @@ -112,11 +114,15 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(copy)!); using (var reading = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var writing = new FileStream(copy, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { reading.CopyToAsync(writing, cancellationToken).GetAwaiter().GetResult(); + } copies.Add(new NativeBuildInput(input.logicalPath, copy)); } if (ComputeFingerprint(new Inventory([.. copies], m_directories), cancellationToken) != fingerprint) + { throw new InvalidDataException("Shader inputs changed while copying the frozen compilation tree."); + } VerifyUnchanged(cancellationToken); return destination; } @@ -125,14 +131,19 @@ private static string ComputeFingerprint( Inventory inventory, CancellationToken cancellationToken ) => NativeBuildFingerprint.Create( - inventory.directories.Select(static path => "shader-directory/" + path), inventory.files, cancellationToken); + inventory.directories.Select(static path => "shader-directory/" + path), + inventory.files, + cancellationToken + ); private static Inventory Discover( string root, CancellationToken cancellationToken ) { if (!Directory.Exists(root)) + { throw new DirectoryNotFoundException($"Shader authoring root '{root}' does not exist."); + } var pending = new Stack(); List files = []; List directories = []; @@ -146,23 +157,31 @@ CancellationToken cancellationToken foreach (string child in Directory.EnumerateDirectories(directory)) { if (!policy.IsIgnored(Path.GetRelativePath(root, child), isDirectory: true)) + { pending.Push(child); + } } foreach (string path in Directory.EnumerateFiles(directory)) { cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(root, path).Replace('\\', '/'); if (AtomicFile.IsCandidatePath(relative)) + { continue; + } bool metadata = relative.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase); if (!metadata && policy.IsIgnored(relative, isDirectory: false)) + { continue; + } PathBoundary.RequireUnlinkedPath(root, path); files.Add(new NativeBuildInput("shader-source/" + relative, path)); } } - return new Inventory(files.OrderBy(static input => input.logicalPath, StringComparer.Ordinal).ToArray(), - directories.Order(StringComparer.Ordinal).ToArray()); + return new Inventory( + files.OrderBy(static input => input.logicalPath, StringComparer.Ordinal).ToArray(), + directories.Order(StringComparer.Ordinal).ToArray() + ); } private sealed record Inventory( diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs index 4c95ed410..fbb56ddfc 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs @@ -25,15 +25,16 @@ public sealed class BgfxAuthoringProvider : RenderingAuthoringBackendProvider public BgfxAuthoringProvider( BgfxShaderTargetProfile target, ToolRunner? tools = null - ) : base(RenderingBackendId.bgfx) { + ) : base(RenderingBackendID.bgfx) + { ArgumentNullException.ThrowIfNull(target); m_target = target; m_tools = tools; } - /// + /// public override IShaderCompilerToolchain CreateShaderCompilerToolchain() => new BgfxShadercToolchain(m_target, m_tools); - /// + /// public override ITextureTargetCompiler CreateTextureTargetCompiler() => new BgfxTextureTargetCompiler(m_tools); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs index 953ef8900..58274c935 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs @@ -7,8 +7,8 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; -using Inno.Rendering; using Inno.Extensibility.Types; +using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -63,26 +63,33 @@ ToolRunner tools ) { ArgumentNullException.ThrowIfNull(assets); ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(backends); ArgumentNullException.ThrowIfNull(tools); m_tools = tools; GraphicsApi[] snapshot = backends.Distinct().ToArray(); if (snapshot.Length == 0) + { throw new ArgumentException("At least one Player graphics backend is required.", nameof(backends)); - if (snapshot.Contains(GraphicsApi.Noop)) + } + if (snapshot.Contains(GraphicsApi.noop)) + { throw new ArgumentException("A deployable Player cannot target the Noop graphics backend.", nameof(backends)); + } m_assets = assets; - m_types = types ?? throw new ArgumentNullException(nameof(types)); + m_types = types; m_serialization = serialization; ArgumentNullException.ThrowIfNull(platform); foreach (GraphicsApi backend in snapshot) + { platform.Resolve(backend); + } m_platform = platform; m_backends = snapshot; } - /// - public BuildTargetId target => new(m_platform.id); + /// + public BuildTargetID target => new(m_platform.id); /// /// Captures the active Asset generation and compiles every required runtime variant. @@ -109,7 +116,9 @@ public async ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); if (context.profile.target != target) + { throw new ArgumentException("The content context target does not match the compiler.", nameof(context)); + } ContentSnapshot snapshot = CaptureSnapshot(); string outputRoot = Path.GetFullPath(context.outputDirectory); Directory.CreateDirectory(outputRoot); @@ -120,39 +129,47 @@ public async ValueTask CompileAsync( ShaderCompileTarget target = shaderCompiler.CreateTarget( capabilities, optimize: true, - debugInformation: false); + debugInformation: false + ); foreach (ShaderInput shader in snapshot.shaders) { foreach (RenderShaderVariant variant in shader.variants.OrderBy(static value => value.value, StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); - ShaderCompilationResult result = await shaderCompiler.CompileGraphAsync( + ShaderCompilationResult result = await shaderCompiler + .CompileGraphAsync( shader.asset, target, variant, - m_types, m_serialization, AssetSerializationContext.Create(m_assets), m_assets, - cancellationToken) + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + m_assets, + cancellationToken + ) .ConfigureAwait(false); if (!result.succeeded) { string diagnostics = string.Join( Environment.NewLine, - result.diagnostics.Select(static value => $"[{value.code}] {value.message}")); + result.diagnostics.Select(static value => $"[{value.code}] {value.message}") + ); throw new InvalidOperationException( - $"Shader '{shader.asset.assetPath}' failed target compilation for '{backend}':{Environment.NewLine}" + - diagnostics); + $"Shader '{shader.asset.assetPath}' failed target compilation for '{backend}':{Environment.NewLine}" + + diagnostics + ); } string destination = ResolveOutput( outputRoot, - RenderTargetArtifactPath.GetShaderPath( - shader.asset.identity.persistentId, - backend, - variant)); + RenderTargetArtifactPath.GetShaderPath(shader.asset.identity.persistentID, backend, variant) + ); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - await File.WriteAllBytesAsync( + await File + .WriteAllBytesAsync( destination, RenderShaderArtifactCodec.Encode(result.artifact!.CreateRuntimeArtifact()), - cancellationToken) + cancellationToken + ) .ConfigureAwait(false); } } @@ -164,19 +181,15 @@ await File.WriteAllBytesAsync( cancellationToken.ThrowIfCancellationRequested(); byte[] bytes; using (ArtifactLease source = m_assets.AcquireArtifact( - texture.reference.assetId, - texture.reference.slot.sourceOutputName)) - { + texture.reference.assetID, + texture.reference.slot.sourceOutputName + )) { using Stream encoded = source.OpenRead(); - bytes = await textureCompiler.CompileKtxAsync( - encoded, - texture.reference.slot.colorSpace, - cancellationToken) + bytes = await textureCompiler + .CompileKtxAsync(encoded, texture.reference.slot.colorSpace, cancellationToken) .ConfigureAwait(false); } - string destination = ResolveOutput( - outputRoot, - RenderTargetArtifactPath.GetTexturePath(texture.reference)); + string destination = ResolveOutput(outputRoot, RenderTargetArtifactPath.GetTexturePath(texture.reference)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); await File.WriteAllBytesAsync(destination, bytes, cancellationToken).ConfigureAwait(false); } @@ -185,31 +198,40 @@ await File.WriteAllBytesAsync( private ContentSnapshot CaptureSnapshot() { if (!m_assets.isInitialized) + { throw new InvalidOperationException("BGFX target compilation requires an active authoring Asset database."); - Dictionary mounts = m_assets.sourceMounts.ToDictionary( - static mount => mount.id); + } + Dictionary mounts = m_assets.sourceMounts.ToDictionary( + static mount => mount.id + ); var shaders = new Dictionary(); var textures = new Dictionary(); - var materialVariants = new List<(ShaderAsset shader, RenderShaderVariant variant)>(); + List<(ShaderAsset shader, RenderShaderVariant variant)> materialVariants = []; AssetFileEntry[] entries = m_assets.GetFileSystemEntries(includeDirectories: false) .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) .ToArray(); foreach (AssetFileEntry entry in entries) { if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) || assetType is null) + { continue; + } if (typeof(MaterialAsset).IsAssignableFrom(assetType)) { MaterialAsset material = m_assets.Load(entry.assetPath); if (material.shader is not null) + { materialVariants.Add((material.shader, RenderShaderVariant.FromMaterial(material))); + } } if (typeof(ShaderAsset).IsAssignableFrom(assetType)) { ShaderAsset shader = m_assets.Load(entry.assetPath); // Passless graphs are reusable authoring nodes, not executable shaders. if (shader.definition is { passes.Length: > 0 }) + { AddShader(shaders, mounts, shader, RenderShaderVariant.empty); + } } if (typeof(IRenderTextureArtifactSource).IsAssignableFrom(assetType)) { @@ -218,13 +240,16 @@ private ContentSnapshot CaptureSnapshot() } } foreach ((ShaderAsset shader, RenderShaderVariant variant) in materialVariants) + { AddShader(shaders, mounts, shader, variant); + } return new ContentSnapshot( - shaders.Values.OrderBy(static value => value.asset.identity.persistentId).ToArray(), + shaders.Values.OrderBy(static value => value.asset.identity.persistentID).ToArray(), textures.Values - .OrderBy(static value => value.reference.assetId) + .OrderBy(static value => value.reference.assetID) .ThenBy(static value => value.reference.slot.id, StringComparer.Ordinal) - .ToArray()); + .ToArray() + ); } private static void AddTextures( @@ -232,7 +257,9 @@ private static void AddTextures( AssetObject asset ) { if (asset is not IRenderTextureArtifactSource source) + { return; + } Guid id = RequireIdentity(asset); var slots = new HashSet(StringComparer.Ordinal); foreach (RenderTextureArtifactSlot slot in source.textureArtifacts) @@ -240,12 +267,14 @@ AssetObject asset if (string.IsNullOrWhiteSpace(slot.id) || string.IsNullOrWhiteSpace(slot.sourceOutputName)) { throw new InvalidOperationException( - $"Texture source asset '{asset.assetPath}' declares an invalid artifact slot."); + $"Texture source asset '{asset.assetPath}' declares an invalid artifact slot." + ); } if (!slots.Add(slot.id)) { throw new InvalidOperationException( - $"Texture source asset '{asset.assetPath}' declares duplicate slot '{slot.id}'."); + $"Texture source asset '{asset.assetPath}' declares duplicate slot '{slot.id}'." + ); } var reference = new RenderTextureArtifactReference(id, asset.contentVersion, slot); textures.Add(new TextureArtifactKey(id, slot.id), new TextureInput(reference)); @@ -254,7 +283,7 @@ AssetObject asset private static void AddShader( IDictionary shaders, - IReadOnlyDictionary mounts, + IReadOnlyDictionary mounts, ShaderAsset shader, RenderShaderVariant variant ) { @@ -270,18 +299,22 @@ RenderShaderVariant variant private static Guid RequireIdentity(AssetObject asset) { - Guid id = asset.identity.persistentId; + Guid id = asset.identity.persistentID; if (id == Guid.Empty) + { throw new InvalidOperationException($"Runtime asset '{asset.assetPath}' has no persistent identity."); + } return id; } private static void RequireMount( - IReadOnlyDictionary mounts, + IReadOnlyDictionary mounts, AssetPath path ) { if (!mounts.ContainsKey(path.source)) + { throw new InvalidOperationException($"Asset source mount '{path.source}' is not active."); + } } private static string ResolveOutput( @@ -291,10 +324,12 @@ string relativePath string result = Path.GetFullPath(Path.Combine(root, relativePath)); string prefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar; StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; if (!result.StartsWith(prefix, comparison)) + { throw new InvalidOperationException("A target artifact path escaped its staging directory."); + } return result; } @@ -315,8 +350,8 @@ internal ShaderInput(ShaderAsset asset) } private readonly record struct TextureArtifactKey( - Guid assetId, - string slotId + Guid assetID, + string slotID ); private sealed record TextureInput(RenderTextureArtifactReference reference); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs index f8cef1c0e..f196cb95f 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs @@ -54,16 +54,18 @@ public BgfxShaderCompilerProfile( ArgumentException.ThrowIfNullOrWhiteSpace(fragmentProfile); ArgumentNullException.ThrowIfNull(computeProfile); string[] snapshot = defines?.ToArray() ?? []; - if (snapshot.Any(string.IsNullOrWhiteSpace) || capabilities.backend == GraphicsApi.Noop - || capabilities.Supports(GraphicsCapability.Compute) != !string.IsNullOrWhiteSpace(computeProfile)) + if (snapshot.Any(string.IsNullOrWhiteSpace) || capabilities.backend == GraphicsApi.noop + || capabilities.Supports(GraphicsCapability.Compute) != !string.IsNullOrWhiteSpace(computeProfile) + ) { throw new ArgumentException("A shader profile requires valid defines, a renderer and consistent compute support."); + } this.capabilities = capabilities; this.shadercPlatform = shadercPlatform; this.vertexProfile = vertexProfile; this.fragmentProfile = fragmentProfile; this.computeProfile = computeProfile; this.defines = Array.AsReadOnly(snapshot); - key = CreateKey(capabilities); + this.key = CreateKey(capabilities); } /// @@ -101,7 +103,8 @@ public BgfxShaderCompilerProfile( /// public string key { get; } - internal string GetStageProfile(ShaderStage stage) => stage switch + internal string GetStageProfile(ShaderStage stage) + => stage switch { ShaderStage.Vertex => vertexProfile, ShaderStage.Fragment => fragmentProfile, @@ -121,7 +124,9 @@ internal string CreateKey(GraphicsCapabilities requested) writer.Write(computeProfile); writer.Write(defines.Count); foreach (string define in defines) + { writer.Write(define); + } writer.Write(requested.backend.value); writer.Write((int)requested.features); writer.Write(requested.limits.maxViews); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs index 40b3b48ba..d23e8876c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs @@ -32,10 +32,16 @@ IEnumerable renderers ArgumentNullException.ThrowIfNull(renderers); var snapshot = new Dictionary(); foreach (BgfxShaderCompilerProfile renderer in renderers) + { if (renderer is null || !snapshot.TryAdd(renderer.capabilities.backend, renderer)) + { throw new ArgumentException("Shader renderers must be non-null and unique.", nameof(renderers)); + } + } if (snapshot.Count == 0) + { throw new ArgumentException("A shader target requires at least one renderer.", nameof(renderers)); + } this.id = id; m_renderers = new ReadOnlyDictionary(snapshot); } @@ -58,15 +64,18 @@ IEnumerable renderers /// The target has no configuration for this API. /// public BgfxShaderCompilerProfile Resolve(GraphicsApi backend) - => m_renderers.TryGetValue(backend, out BgfxShaderCompilerProfile? renderer) ? renderer - : throw new NotSupportedException($"Shader target '{id}' has no renderer profile for '{backend}'."); + => m_renderers.TryGetValue(backend, out BgfxShaderCompilerProfile? renderer) + ? renderer + : throw new NotSupportedException($"Shader target '{id}' has no renderer profile for '{backend}'."); internal BgfxShaderCompilerProfile Resolve(GraphicsCapabilities capabilities) { ArgumentNullException.ThrowIfNull(capabilities); BgfxShaderCompilerProfile renderer = Resolve(capabilities.backend); if (capabilities.Supports(GraphicsCapability.Compute) && renderer.computeProfile.Length == 0) + { throw new NotSupportedException($"Shader target '{id}' does not support compute."); + } return renderer; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs index 52bc89b15..67c03d827 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Rendering.Assets; using Inno.Rendering; +using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -73,35 +73,33 @@ CancellationToken cancellationToken { throw new ArgumentException( $"Shader target '{target.profileKey}' does not belong to this BGFX toolchain.", - nameof(target)); + nameof(target) + ); } string temporaryDirectory = Path.Combine( Path.GetTempPath(), "InnoEngine", "Shaderc", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(temporaryDirectory); try { string sourcePath = Path.Combine(temporaryDirectory, "stage.sc"); string outputPath = Path.Combine(temporaryDirectory, "stage.bin"); string bgfxShaderInclude = ResolveBgfxShaderInclude(); - File.Copy( - bgfxShaderInclude, - Path.Combine(temporaryDirectory, "bgfx_shader.sh"), - overwrite: true); + File.Copy(bgfxShaderInclude, Path.Combine(temporaryDirectory, "bgfx_shader.sh"), overwrite: true); File.Copy( Path.Combine( Path.GetDirectoryName(bgfxShaderInclude) - ?? throw new InvalidOperationException("BGFX shader include has no parent directory."), - "bgfx_compute.sh"), + ?? throw new InvalidOperationException("BGFX shader include has no parent directory."), + "bgfx_compute.sh" + ), Path.Combine(temporaryDirectory, "bgfx_compute.sh"), - overwrite: true); - await File.WriteAllTextAsync( - sourcePath, - source, - cancellationToken).ConfigureAwait(false); + overwrite: true + ); + await File.WriteAllTextAsync(sourcePath, source, cancellationToken).ConfigureAwait(false); List arguments = [ @@ -121,10 +119,7 @@ await File.WriteAllTextAsync( if (stage != ShaderStage.Compute && varying is not null) { string varyingPath = Path.Combine(temporaryDirectory, "varying.def.sc"); - await File.WriteAllTextAsync( - varyingPath, - varying, - cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync(varyingPath, varying, cancellationToken).ConfigureAwait(false); arguments.Add("--varyingdef"); arguments.Add(varyingPath); } @@ -142,40 +137,41 @@ await File.WriteAllTextAsync( } if (target.debugInformation) + { arguments.Add("--debug"); + } arguments.Add("--keepcomments"); ToolRunResult result = await m_tools.RunAsync( BgfxTool.Shaderc, arguments, temporaryDirectory, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); byte[]? bytes = result.succeeded && File.Exists(outputPath) - ? await File.ReadAllBytesAsync(outputPath, cancellationToken).ConfigureAwait(false) - : null; - return new BgfxShadercResult( - bytes, - result.exitCode, - result.standardOutput, - result.standardError); + ? await File.ReadAllBytesAsync(outputPath, cancellationToken).ConfigureAwait(false) + : null; + return new BgfxShadercResult(bytes, result.exitCode, result.standardOutput, result.standardError); } finally { if (Directory.Exists(temporaryDirectory)) + { Directory.Delete(temporaryDirectory, recursive: true); + } } } + private string ResolveBgfxShaderInclude() => m_tools.ResolveShaderInclude("bgfx_shader.sh"); + private static string ToShadercStage(ShaderStage stage) => stage switch - { - ShaderStage.Vertex => "vertex", - ShaderStage.Fragment => "fragment", - ShaderStage.Compute => "compute", - _ => throw new ArgumentOutOfRangeException(nameof(stage), stage, "A single shader stage is required.") - }; - - private string ResolveBgfxShaderInclude() => m_tools.ResolveShaderInclude("bgfx_shader.sh"); + { + ShaderStage.Vertex => "vertex", + ShaderStage.Fragment => "fragment", + ShaderStage.Compute => "compute", + _ => throw new ArgumentOutOfRangeException(nameof(stage), stage, "A single shader stage is required.") + }; } internal sealed record BgfxShadercResult( diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs index 744d4dd26..8e8b147f6 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs @@ -18,9 +18,8 @@ public static class BgfxTargetCapabilities /// /// The immutable offline validation profile for the selected target. /// - public static GraphicsCapabilities Create( - GraphicsApi backend - ) { + public static GraphicsCapabilities Create(GraphicsApi backend) + { GraphicsCapability features = Enum.GetValues() .Aggregate(GraphicsCapability.None, static ( current, @@ -30,16 +29,16 @@ GraphicsApi backend return new GraphicsCapabilities( backend, features, - new GraphicsLimits(256, 8, 16384, 16), + new GraphicsLimits(256, 8, 16_384, 16), formats, formats, formats, formats, - originBottomLeft: backend == GraphicsApi.OpenGL || backend == GraphicsApi.OpenGLES, - homogeneousDepth: backend == GraphicsApi.OpenGL || backend == GraphicsApi.OpenGLES, + originBottomLeft: backend == GraphicsApi.openGL || backend == GraphicsApi.openGLES, + homogeneousDepth: backend == GraphicsApi.openGL || backend == GraphicsApi.openGLES, formats, formats, - formats); + formats + ); } - } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs index 9f21dc2fe..bcc46fba1 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs @@ -22,7 +22,10 @@ public sealed class BgfxTextureTargetCompiler : ITextureTargetCompiler /// /// The selected tool runner, or null for application-deployed tools. /// - public BgfxTextureTargetCompiler(ToolRunner? tools = null) => m_tools = tools ?? new ToolRunner(); + public BgfxTextureTargetCompiler(ToolRunner? tools = null) + { + m_tools = tools ?? new ToolRunner(); + } /// /// Compiles the supplied source into a validated runtime artifact. @@ -46,58 +49,78 @@ public async ValueTask CompileKtxAsync( ) { ArgumentNullException.ThrowIfNull(source); if (!source.CanRead) + { throw new ArgumentException("Texture compilation requires readable encoded input.", nameof(source)); + } cancellationToken.ThrowIfCancellationRequested(); string temporaryDirectory = Path.Combine( Path.GetTempPath(), "InnoEngine", "Texturec", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(temporaryDirectory); try { string sourcePath = Path.Combine(temporaryDirectory, "source.image"); - await using (FileStream inputFile = new(sourcePath, FileMode.CreateNew, FileAccess.Write, - FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (var inputFile = new FileStream( + sourcePath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { await source.CopyToAsync(inputFile, cancellationToken).ConfigureAwait(false); } string outputPath = Path.Combine(temporaryDirectory, "texture.ktx"); - var arguments = new List - { - "-f", Path.GetFullPath(sourcePath), - "-o", outputPath, - "-t", "RGBA8", + List arguments = + [ + "-f", + Path.GetFullPath(sourcePath), + "-o", + outputPath, + "-t", + "RGBA8", "--mips", "--validate" - }; + ]; if (colorSpace == TextureColorSpace.Linear) + { arguments.Add("--linear"); + } ToolRunResult result = await m_tools.RunAsync( BgfxTool.Texturec, arguments, temporaryDirectory, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); if (!result.succeeded || !File.Exists(outputPath)) { string diagnostics = string.Join( Environment.NewLine, - new[] { result.standardOutput, result.standardError }); + new[] { result.standardOutput, result.standardError } + ); throw new InvalidOperationException( - $"texturec rejected the encoded input with exit code {result.exitCode}: {diagnostics}"); + $"texturec rejected the encoded input with exit code {result.exitCode}: {diagnostics}" + ); } byte[] artifact = await File.ReadAllBytesAsync(outputPath, cancellationToken) .ConfigureAwait(false); if (artifact.Length == 0) + { throw new InvalidOperationException("texturec produced an empty artifact."); + } return artifact; } finally { if (Directory.Exists(temporaryDirectory)) + { Directory.Delete(temporaryDirectory, recursive: true); + } } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs index a6675ad87..84e771d07 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs @@ -47,4 +47,3 @@ string standardError /// public bool succeeded => exitCode == 0; } - diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs index 158d19498..19bce6caf 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs @@ -26,7 +26,10 @@ public sealed class ToolRunner /// /// Explicit execution path policy, or null for physical execution. /// - public ToolRunner(IToolchainWorkspaceProvider? workspaces = null) => m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); + public ToolRunner(IToolchainWorkspaceProvider? workspaces = null) + { + m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); + } /// /// Freezes executables selected and validated by the host's toolchain operation. @@ -55,14 +58,23 @@ public ToolRunner( ArgumentNullException.ThrowIfNull(executables); ArgumentException.ThrowIfNullOrWhiteSpace(includesDirectory); if (!Path.IsPathFullyQualified(includesDirectory) || !Directory.Exists(includesDirectory)) + { throw new ArgumentException("The selected shader include directory must exist at an absolute path.", nameof(includesDirectory)); + } Dictionary snapshot = []; foreach ((BgfxTool tool, string path) in executables) { if (!Enum.IsDefined(tool) || !Path.IsPathFullyQualified(path)) - throw new ArgumentException("A tool runner requires supported identities and absolute executable paths.", nameof(executables)); + { + throw new ArgumentException( + "A tool runner requires supported identities and absolute executable paths.", + nameof(executables) + ); + } if (!File.Exists(path)) + { throw new FileNotFoundException("A selected BGFX executable is unavailable.", path); + } snapshot.Add(tool, Path.GetFullPath(path)); } m_executables = new ReadOnlyDictionary(snapshot); @@ -88,8 +100,7 @@ public ToolRunResult Run( BgfxTool tool, IReadOnlyList arguments, string? workingDirectory = null - ) - => RunAsync(tool, arguments, workingDirectory).AsTask().GetAwaiter().GetResult(); + ) => RunAsync(tool, arguments, workingDirectory).AsTask().GetAwaiter().GetResult(); /// /// Runs the external tool asynchronously and captures its complete process outcome. @@ -128,7 +139,9 @@ public async ValueTask RunAsync( cancellationToken.ThrowIfCancellationRequested(); string toolPath = ResolveToolPath(tool); using ToolchainWorkingDirectory execution = await m_workspaces.OpenAsync( - Path.GetDirectoryName(toolPath)!, cancellationToken).ConfigureAwait(false); + Path.GetDirectoryName(toolPath)!, + cancellationToken + ).ConfigureAwait(false); var startInfo = new ProcessStartInfo { FileName = Path.Combine(execution.toolPath, Path.GetFileName(toolPath)), @@ -145,7 +158,7 @@ public async ValueTask RunAsync( } using Process process = Process.Start(startInfo) - ?? throw new InvalidOperationException($"Failed to start tool: {toolPath}"); + ?? throw new InvalidOperationException($"Failed to start tool: {toolPath}"); Task standardOutput = process.StandardOutput.ReadToEndAsync(); Task standardError = process.StandardError.ReadToEndAsync(); try @@ -154,14 +167,17 @@ public async ValueTask RunAsync( return new ToolRunResult( process.ExitCode, await standardOutput.ConfigureAwait(false), - await standardError.ConfigureAwait(false)); + await standardError.ConfigureAwait(false) + ); } catch { try { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } } catch (InvalidOperationException) when (process.HasExited) { @@ -172,7 +188,7 @@ await standardOutput.ConfigureAwait(false), { await Task.WhenAll(standardOutput, standardError).ConfigureAwait(false); } - catch + catch (Exception) { // Observe both readers before preserving the original operation failure. } @@ -183,7 +199,9 @@ await standardOutput.ConfigureAwait(false), internal string ResolveShaderInclude(string name) { if (name is not ("bgfx_shader.sh" or "bgfx_compute.sh")) + { throw new ArgumentException("The shader include is not part of this backend's declared tool product.", nameof(name)); + } string path = m_includesDirectory is null ? NativeDllLoader.FindNativeFile(name) : Path.Combine(m_includesDirectory, name); return File.Exists(path) ? path : throw new FileNotFoundException("A selected shader include is unavailable.", path); } @@ -191,10 +209,12 @@ internal string ResolveShaderInclude(string name) private string ResolveToolPath(BgfxTool tool) { if (m_executables is not null) + { return m_executables.TryGetValue(tool, out string? executable) - ? executable : throw new FileNotFoundException($"The selected distribution has no '{tool}' executable."); + ? executable + : throw new FileNotFoundException($"The selected distribution has no '{tool}' executable."); + } string name = tool.ToString().ToLowerInvariant(); return NativeDllLoader.FindNativeFile(name); } - } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs index 59aa412b8..c2c086a66 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs @@ -10,9 +10,13 @@ internal sealed partial class BgfxShaderIrGenerator private bool EmitControlFlow(ShaderIrInstruction instruction) { if (instruction.operation is not (ShaderIrOperation.Branch or ShaderIrOperation.Loop)) + { return false; + } foreach (ShaderIrValue output in instruction.outputs) + { m_body.Append(" ").Append(Declaration(output.type, NewLocal(output))).AppendLine(";"); + } if (instruction.operation == ShaderIrOperation.Branch) { m_body.Append(" if (").Append(Value(instruction.inputs[0])).AppendLine(") {"); @@ -26,14 +30,32 @@ private bool EmitControlFlow(ShaderIrInstruction instruction) } for (int index = 0; index < instruction.outputs.Count; index++) + { Assign(m_body, instruction.outputs[index].type, Value(instruction.outputs[index]), Value(instruction.inputs[index + 1])); + } ShaderIrBlock region = instruction.regions[0]; - ShaderIrInstruction iteration = region.instructions.Single(static value => value.operation == ShaderIrOperation.RegionInput && value.inputName == "iteration"); + ShaderIrInstruction iteration = region.instructions.Single( + static value => value.operation == ShaderIrOperation.RegionInput && value.inputName == "iteration" + ); string counter = NewLocal(iteration.outputs[0]); - m_body.Append(" for (uint ").Append(counter).Append(" = 0u; ").Append(counter).Append(" < ") - .Append(Value(instruction.inputs[0])).Append("; ++").Append(counter).AppendLine(") {"); - ShaderIrInstruction[] carried = region.instructions.Where(static value => value.operation == ShaderIrOperation.RegionInput && value.inputName!.StartsWith("state.", StringComparison.Ordinal)) - .OrderBy(static value => value.inputName, StringComparer.Ordinal).ToArray(); + m_body.Append(" for (uint ") + .Append(counter) + .Append(" = 0u; ") + .Append(counter) + .Append(" < ") + .Append(Value(instruction.inputs[0])) + .Append("; ++") + .Append(counter) + .AppendLine(") {"); + ShaderIrInstruction[] carried = region.instructions + .Where( + static value => ( + value.operation == ShaderIrOperation.RegionInput + && value.inputName!.StartsWith("state.", StringComparison.Ordinal) + ) + ) + .OrderBy(static value => value.inputName, StringComparer.Ordinal) + .ToArray(); for (int index = 0; index < carried.Length; index++) { ShaderIrValue parameter = carried[index].outputs[0]; @@ -52,8 +74,12 @@ private bool EmitControlFlow(ShaderIrInstruction instruction) private void EmitRegion(ShaderIrBlock region) { foreach (ShaderIrInstruction instruction in region.instructions) + { if (instruction.operation != ShaderIrOperation.RegionInput) + { EmitInstruction(instruction); + } + } } private void AssignRegionOutputs( @@ -61,8 +87,10 @@ private void AssignRegionOutputs( int regionIndex = 0 ) { int index = 0; - foreach (KeyValuePair pair in instruction.regions[regionIndex].outputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - { + foreach (KeyValuePair pair in instruction.regions[regionIndex].outputs.OrderBy( + static pair => pair.Key, + StringComparer.Ordinal + )) { ShaderIrValue output = instruction.outputs[index++]; Assign(m_body, output.type, Value(output), Value(pair.Value)); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs index 3a9e6bb64..405b70c91 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs @@ -16,7 +16,9 @@ string name ShaderStorageType storage = input.type.storage!; string access = storage.access switch { - RenderStorageAccess.Read => "RO", RenderStorageAccess.Write => "WO", RenderStorageAccess.ReadWrite => "RW", + RenderStorageAccess.Read => "RO", + RenderStorageAccess.Write => "WO", + RenderStorageAccess.ReadWrite => "RW", _ => throw Error("Unsupported storage access.") }; if (!storage.isImage) @@ -25,29 +27,58 @@ string name // packing cannot be inferred safely; structured layouts need explicit target packing first. string element = storage.valueType.id; if (storage.valueType.elementType is not null || storage.valueType.fields.Count != 0 - || element is not ("float" or "float2" or "float4" or "int" or "int2" or "int4" or "uint" or "uint2" or "uint4")) - throw Error("BGFX storage buffer elements require 32-bit scalars, two-component or four-component vectors with an explicit runtime stride."); - text.Append("BUFFER_").Append(access).Append('(').Append(name).Append(", ") - .Append(TypeName(storage.valueType)).Append(", ").Append(input.location).AppendLine(");"); + || element is not ("float" or "float2" or "float4" or "int" or "int2" or "int4" or "uint" or "uint2" or "uint4") + ) { + throw Error( + "BGFX storage buffer elements require 32-bit scalars, two-component or four-component vectors with an explicit runtime stride." + ); + } + text.Append("BUFFER_") + .Append(access) + .Append('(') + .Append(name) + .Append(", ") + .Append(TypeName(storage.valueType)) + .Append(", ") + .Append(input.location) + .AppendLine(");"); return; } string shape = storage.dimension == RenderTextureDimension.Texture3D ? "3D" : storage.array ? "2D_ARRAY" : "2D"; string format = storage.format switch { - RenderTextureFormat.R8 => "r8", RenderTextureFormat.RG8 => "rg8", RenderTextureFormat.RGBA8 => "rgba8", - RenderTextureFormat.RGBA16Float => "rgba16f", RenderTextureFormat.R32Float => "r32f", - RenderTextureFormat.RGB10A2 => "rgb10_a2", RenderTextureFormat.RG11B10Float => "r11f_g11f_b10f", + RenderTextureFormat.R8 => "r8", + RenderTextureFormat.RG8 => "rg8", + RenderTextureFormat.RGBA8 => "rgba8", + RenderTextureFormat.RGBA16Float => "rgba16f", + RenderTextureFormat.R32Float => "r32f", + RenderTextureFormat.RGB10A2 => "rgb10_a2", + RenderTextureFormat.RG11B10Float => "r11f_g11f_b10f", _ => throw Error("The storage image format has no BGFX SC representation.") }; - text.Append("IMAGE").Append(shape).Append('_').Append(access).Append('(').Append(name).Append(", ") - .Append(format).Append(", ").Append(input.location).AppendLine(");"); + text.Append("IMAGE") + .Append(shape) + .Append('_') + .Append(access) + .Append('(') + .Append(name) + .Append(", ") + .Append(format) + .Append(", ") + .Append(input.location) + .AppendLine(");"); } private bool EmitResourceInstruction(ShaderIrInstruction instruction) { if (instruction.operation is not (ShaderIrOperation.TextureSample or ShaderIrOperation.TextureSampleLevel - or ShaderIrOperation.StorageLoad or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard)) + or ShaderIrOperation.StorageLoad + or ShaderIrOperation.StorageStore + or ShaderIrOperation.StorageAtomicAdd + or ShaderIrOperation.Discard) + ) { return false; + } string[] operands = instruction.inputs.Select(Value).ToArray(); string? result = null; if (instruction.outputs.Count != 0) @@ -62,28 +93,44 @@ private bool EmitResourceInstruction(ShaderIrInstruction instruction) case ShaderIrOperation.TextureSampleLevel: string function = instruction.inputs[0].type.id switch { - "sampled-texture2d" => "texture2D", "sampled-texture2d-array" => "texture2DArray", - "sampled-texture3d" => "texture3D", "sampled-texture-cube" => "textureCube", + "sampled-texture2d" => "texture2D", + "sampled-texture2d-array" => "texture2DArray", + "sampled-texture3d" => "texture3D", + "sampled-texture-cube" => "textureCube", _ => throw Error("Unsupported sampled texture shape.") }; if (instruction.operation == ShaderIrOperation.TextureSampleLevel) + { function += "Lod"; + } Assign(m_body, instruction.outputs[0].type, result!, function + "(" + string.Join(", ", operands) + ")"); break; case ShaderIrOperation.StorageLoad: string load = instruction.inputs[0].type.storage!.isImage - ? $"imageLoad({operands[0]}, {operands[1]})" : $"{operands[0]}[{operands[1]}]"; + ? $"imageLoad({operands[0]}, {operands[1]})" + : $"{operands[0]}[{operands[1]}]"; Assign(m_body, instruction.outputs[0].type, result!, load); break; case ShaderIrOperation.StorageStore: if (instruction.inputs[0].type.storage!.isImage) + { m_body.Append(" imageStore(").AppendJoin(", ", operands).AppendLine(");"); + } else + { Assign(m_body, instruction.inputs[2].type, $"{operands[0]}[{operands[1]}]", operands[2]); + } break; case ShaderIrOperation.StorageAtomicAdd: - m_body.Append(" atomicFetchAndAdd(").Append(operands[0]).Append('[').Append(operands[1]).Append("], ") - .Append(operands[2]).Append(", ").Append(result).AppendLine(");"); + m_body.Append(" atomicFetchAndAdd(") + .Append(operands[0]) + .Append('[') + .Append(operands[1]) + .Append("], ") + .Append(operands[2]) + .Append(", ") + .Append(result) + .AppendLine(");"); break; case ShaderIrOperation.Discard: m_body.Append(" if (").Append(operands[0]).AppendLine(") { discard; }"); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs index b09d1bf63..a5da3bc7b 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs @@ -13,39 +13,65 @@ internal sealed partial class BgfxShaderIrGenerator { private string EmitModule(ShaderSourceImplementationAnalysis implementation) { - if (implementation.languageId != "inno.shader-language.bgfx-sc") - throw new BgfxSourceSyntaxException($"BGFX SC generation cannot embed language '{implementation.languageId}'.", new(implementation.sourcePath, 1, 1)); + if (implementation.languageID != "inno.shader-language.bgfx-sc") + { + throw new BgfxSourceSyntaxException( + $"BGFX SC generation cannot embed language '{implementation.languageID}'.", + new ShaderSourcePosition(implementation.sourcePath, 1, 1) + ); + } ShaderSourceRequest request = implementation.CreateSourceRequest(); List tokens = new BgfxSourcePreprocessor(request).Process(); var parser = new BgfxSourceDeclarationParser(tokens, request); ShaderSourceFunction parsed = parser.Parse(); if (!parsed.HasSameInterface(implementation.analysis.function!)) + { Fail("The frozen source interface differs from its analyzed snapshot."); + } string prefix = "inno_module_" + implementation.contentHash.ToLowerInvariant() + "_"; - var symbols = parser.globals.ToDictionary(static value => value, value => prefix + value, StringComparer.Ordinal); + Dictionary symbols = parser.globals.ToDictionary( + static value => value, + value => prefix + value, + StringComparer.Ordinal + ); // Shaderc injects varying macros before function declarations. Isolate module-local names // that collide with those generated bindings, including exported function parameters. foreach (string varying in stage.inputs.Where(static input => input.kind == ShaderIrInputKind.Varying) .Select(static input => VaryingName(input.semantic, input.location)) - .Concat(stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Varying) - .Select(static output => VaryingName(output.semantic, output.location)))) + .Concat( + stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Varying) + .Select(static output => VaryingName(output.semantic, output.location)) + ) + ) { symbols.TryAdd(varying, prefix + varying); + } foreach ((string name, ShaderSourceType type) in parser.types) { if (type.elementType is not null) - throw new BgfxSourceSyntaxException("BGFX SC does not support array typedef declarations; declare fixed arrays at their use sites.", new(implementation.sourcePath, 1, 1)); + { + throw new BgfxSourceSyntaxException( + "BGFX SC does not support array typedef declarations; declare fixed arrays at their use sites.", + new ShaderSourcePosition(implementation.sourcePath, 1, 1) + ); + } symbols.Add(name, TypeName(type)); } var removed = new HashSet(); foreach ((int start, int end) in parser.typeDeclarations) + { for (int index = start; index < end; index++) + { removed.Add(index); + } + } ShaderSourcePosition? position = null; string previous = string.Empty; for (int index = 0; index < tokens.Count; index++) { if (removed.Contains(index)) + { continue; + } BgfxSourceToken token = tokens[index]; if (position?.assetPath != token.position.assetPath || position?.line != token.position.line) { @@ -57,7 +83,9 @@ private string EmitModule(ShaderSourceImplementationAnalysis implementation) } string text = token.text; if (previous != "." && symbols.TryGetValue(text, out string? replacement)) + { text = replacement; + } m_modules.Append(text).Append(' '); previous = token.text; } @@ -68,49 +96,86 @@ private string EmitModule(ShaderSourceImplementationAnalysis implementation) private string TypeName(ShaderSourceType type) { if (type.elementType is not null) + { return TypeName(type.elementType); + } if (type.fields.Count != 0) { string name = "InnoType_" + Hash(TypeKey(type)); if (!m_structures.TryGetValue(name, out ShaderSourceType? previous)) { m_structures.Add(name, type); - var declaration = new StringBuilder("struct ").Append(name).AppendLine(" {"); + StringBuilder declaration = new StringBuilder("struct ").Append(name).AppendLine(" {"); foreach (ShaderSourceField field in type.fields) + { declaration.Append(" ").Append(Declaration(field.type, FieldName(field.name))).AppendLine(";"); + } m_types.Append(declaration).AppendLine("};"); } else if (!previous.IsEquivalentTo(type)) + { Fail("A generated structure identity collided."); + } return name; } if (type.id is "void" or "float" or "int" or "uint" or "bool") + { return type.id; + } if (type.id == "sampled-texture2d") + { return "sampler2D"; + } if (type.id == "sampled-texture2d-array") + { return "sampler2DArray"; + } if (type.id == "sampled-texture3d") + { return "sampler3D"; + } if (type.id == "sampled-texture-cube") + { return "samplerCube"; + } if (IsMatrix(type)) { if (type.id[5] == type.id[7]) + { return "mat" + type.id[5]; + } string name = "inno_mat" + type.id[5..]; if (m_matrices.Add(name)) { m_types.AppendLine("#if BGFX_SHADER_LANGUAGE_GLSL").Append("#define ").Append(name).Append(" mat").AppendLine(type.id[5..]); - m_types.AppendLine("#elif BGFX_SHADER_MATRIX_COLUMN_MAJOR").Append("#define ").Append(name).Append(" float").AppendLine(type.id[5..]); - m_types.AppendLine("#else").Append("#define ").Append(name).Append(" float").Append(type.id[7]).Append('x').Append(type.id[5]).AppendLine(); + m_types + .AppendLine("#elif BGFX_SHADER_MATRIX_COLUMN_MAJOR") + .Append("#define ") + .Append(name) + .Append(" float") + .AppendLine(type.id[5..]); + m_types + .AppendLine("#else") + .Append("#define ") + .Append(name) + .Append(" float") + .Append(type.id[7]) + .Append('x') + .Append(type.id[5]) + .AppendLine(); m_types.AppendLine("#endif"); } return name; } foreach ((string prefix, string native) in new[] { ("float", "vec"), ("int", "ivec"), ("uint", "uvec"), ("bool", "bvec") }) - if (type.id.Length == prefix.Length + 1 && type.id.StartsWith(prefix, StringComparison.Ordinal) && type.id[^1] is >= '2' and <= '4') + { + if (type.id.Length == prefix.Length + 1 + && type.id.StartsWith(prefix, StringComparison.Ordinal) + && type.id[^1] is >= '2' and <= '4' + ) { return native + type.id[^1]; + } + } throw Error($"BGFX SC cannot represent IR value type '{type.id}'."); } @@ -136,10 +201,14 @@ string source if (type.elementType is not null) { for (int index = 0; index < type.elementCount; index++) + { Assign(text, type.elementType, $"{destination}[{index}]", $"{source}[{index}]"); + } } else + { text.Append(" ").Append(destination).Append(" = ").Append(source).AppendLine(";"); + } } private string NewLocal(ShaderIrValue value) @@ -150,16 +219,21 @@ private string NewLocal(ShaderIrValue value) } private string Value(ShaderIrValue value) => m_values[value.index]; + private static string Binary( ShaderIrOperation operation, string left, string right ) => operation switch { - ShaderIrOperation.Add => $"({left} + {right})", ShaderIrOperation.Subtract => $"({left} - {right})", - ShaderIrOperation.Multiply => $"({left} * {right})", ShaderIrOperation.Divide => $"({left} / {right})", - ShaderIrOperation.Minimum => $"min({left}, {right})", ShaderIrOperation.Maximum => $"max({left}, {right})", - ShaderIrOperation.Equal => $"({left} == {right})", ShaderIrOperation.LessThan => $"({left} < {right})", + ShaderIrOperation.Add => $"({left} + {right})", + ShaderIrOperation.Subtract => $"({left} - {right})", + ShaderIrOperation.Multiply => $"({left} * {right})", + ShaderIrOperation.Divide => $"({left} / {right})", + ShaderIrOperation.Minimum => $"min({left}, {right})", + ShaderIrOperation.Maximum => $"max({left}, {right})", + ShaderIrOperation.Equal => $"({left} == {right})", + ShaderIrOperation.LessThan => $"({left} < {right})", _ => throw Error($"Unsupported typed operation '{operation}'.") }; @@ -182,8 +256,10 @@ private static string FloatLiteral(float value) } private static string TypeKey(ShaderSourceType type) - => type.elementType is not null ? $"{type.id.Length}:{type.id}[{type.elementCount}]{TypeKey(type.elementType)}" - : $"{type.id.Length}:{type.id}" + string.Concat(type.fields.Select(field => $"{field.name.Length}:{field.name}{TypeKey(field.type)}")); + => type.elementType is not null + ? $"{type.id.Length}:{type.id}[{type.elementCount}]{TypeKey(type.elementType)}" + : $"{type.id.Length}:{type.id}" + + string.Concat(type.fields.Select(field => $"{field.name.Length}:{field.name}{TypeKey(field.type)}")); private static string Hash(string text) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text))); @@ -193,7 +269,7 @@ string id ) { // BGFX UniformRef stores only 63 visible bytes. Base32 preserves all 256 hash bits // while producing a valid SC identifier that fits that native reflection contract. - const string alphabet = "abcdefghijklmnopqrstuvwxyz234567"; + const string C_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"; byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(id)); var result = new StringBuilder(prefix, 59); uint bits = 0; @@ -205,32 +281,49 @@ string id while (count >= 5) { count -= 5; - result.Append(alphabet[(int)((bits >> count) & 31)]); + result.Append(C_ALPHABET[(int)((bits >> count) & 31)]); } } if (count != 0) - result.Append(alphabet[(int)((bits << (5 - count)) & 31)]); + { + result.Append(C_ALPHABET[(int)((bits << (5 - count)) & 31)]); + } return result.ToString(); } + private static string MatrixElement( string matrix, int column, int row ) => $"inno_matrix_element({matrix},{column},{row})"; + private static bool IsMatrix(ShaderSourceType type) - => type.id.Length == 8 && type.id.StartsWith("float", StringComparison.Ordinal) && type.id[5] is >= '2' and <= '4' && type.id[6] == 'x' && type.id[7] is >= '2' and <= '4'; + => type.id.Length == 8 + && type.id.StartsWith("float", StringComparison.Ordinal) + && type.id[5] is >= '2' and <= '4' + && type.id[6] == 'x' + && type.id[7] is >= '2' and <= '4'; private static string FieldName(string name) { - if (name.Length == 0 || !(char.IsAsciiLetter(name[0]) || name[0] == '_') || name.Any(static c => !char.IsAsciiLetterOrDigit(c) && c != '_')) + if (name.Length == 0 + || !(char.IsAsciiLetter(name[0]) || name[0] == '_') + || name.Any(static c => !char.IsAsciiLetterOrDigit(c) && c != '_') + ) { throw Error("BGFX SC structure field names must be identifiers."); + } return name; } - private static string AttributeName(ShaderIrStageInput input) => (input.semantic, input.location) switch + private static string AttributeName(ShaderIrStageInput input) + => (input.semantic, input.location) switch { - ("position", 0) => "a_position", ("normal", 0) => "a_normal", ("tangent", 0) => "a_tangent", ("bitangent", 0) => "a_bitangent", - ("indices", 0) => "a_indices", ("weight", 0) => "a_weight", + ("position", 0) => "a_position", + ("normal", 0) => "a_normal", + ("tangent", 0) => "a_tangent", + ("bitangent", 0) => "a_bitangent", + ("indices", 0) => "a_indices", + ("weight", 0) => "a_weight", ("color", >= 0 and <= 3) => "a_color" + input.location, ("texcoord", >= 0 and <= 7) => "a_texcoord" + input.location, ("instance-data", >= 0 and <= 4) => "i_data" + input.location, @@ -242,8 +335,12 @@ private static string Semantic( int location ) => (semantic, location) switch { - ("position", 0) => "POSITION", ("normal", 0) => "NORMAL", ("tangent", 0) => "TANGENT", ("bitangent", 0) => "BITANGENT", - ("indices", 0) => "BLENDINDICES", ("weight", 0) => "BLENDWEIGHT", + ("position", 0) => "POSITION", + ("normal", 0) => "NORMAL", + ("tangent", 0) => "TANGENT", + ("bitangent", 0) => "BITANGENT", + ("indices", 0) => "BLENDINDICES", + ("weight", 0) => "BLENDWEIGHT", ("texcoord", >= 0 and <= 15) => "TEXCOORD" + location, ("color", >= 0 and <= 3) => "COLOR" + location, ("instance-data", >= 0 and <= 4) => "TEXCOORD" + (7 - location), @@ -255,7 +352,9 @@ private static string VaryingName( int location ) { if (semantic is not ("texcoord" or "color")) + { throw Error($"BGFX cannot interpolate semantic '{semantic}'."); + } _ = Semantic(semantic, location); return "v_" + semantic + location; } @@ -278,6 +377,7 @@ ShaderStage kind _ => throw Error($"BGFX has no '{semantic}' builtin for stage '{kind}'.") }; - private static BgfxSourceSyntaxException Error(string message) => new(message, new("inno-generated-stage", 1, 1)); + private static BgfxSourceSyntaxException Error(string message) => new(message, new ShaderSourcePosition("inno-generated-stage", 1, 1)); + private static void Fail(string message) => throw Error(message); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs index c7339b24e..2d0bc2dad 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs @@ -1,23 +1,13 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; -using System.Security.Cryptography; using System.Text; using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; -internal sealed record BgfxGeneratedStage( - string source, - string varying, - IReadOnlyList bindings, - IReadOnlyList sourcePositions -); - // SC spelling, hardware semantics and module symbol isolation belong only to this adapter. internal sealed partial class BgfxShaderIrGenerator(ShaderIrStage stage) { @@ -39,8 +29,8 @@ internal BgfxGeneratedStage Generate() varying.AppendLine("// Generated stage interface; an empty declaration set is intentional."); var declarations = new StringBuilder(); var stageInputs = new Dictionary(StringComparer.Ordinal); - var inputNames = new List(); - var outputNames = new List(); + List inputNames = []; + List outputNames = []; foreach (ShaderIrStageInput input in stage.inputs.OrderBy(static input => input.id, StringComparer.Ordinal)) { string name; @@ -49,65 +39,101 @@ internal BgfxGeneratedStage Generate() case ShaderIrInputKind.VertexAttribute: name = AttributeName(input); inputNames.Add(name); - varying.Append(Declaration(input.type, name)).Append(" : ").Append(Semantic(input.semantic, input.location)).AppendLine(";"); + varying + .Append(Declaration(input.type, name)) + .Append(" : ") + .Append(Semantic(input.semantic, input.location)) + .AppendLine(";"); break; case ShaderIrInputKind.Varying: name = VaryingName(input.semantic, input.location); inputNames.Add(name); - varying.Append(Declaration(input.type, name)).Append(" : ").Append(Semantic(input.semantic, input.location)).AppendLine(";"); + varying + .Append(Declaration(input.type, name)) + .Append(" : ") + .Append(Semantic(input.semantic, input.location)) + .AppendLine(";"); break; case ShaderIrInputKind.Uniform: name = BindingName("u_inno_", input.id); bool packed = input.type.id is "float" or "float2" or "float3"; - if (!packed && input.type.id is not ("float4" or "float3x3" or "float4x4") && input.type.elementType?.id is not ("float4" or "float3x3" or "float4x4")) - Fail("BGFX uniform layout requires vec4, mat3 or mat4 storage (or fixed arrays); lower scalar/vector parameters through explicit layout components."); - declarations.Append("uniform ").Append(Declaration(packed ? ShaderSourceType.Atomic("float4") : input.type, name)).AppendLine(";"); - m_bindings.Add(new(input.id, name, input.location)); + if (!packed + && input.type.id is not ("float4" or "float3x3" or "float4x4") + && input.type.elementType?.id is not ("float4" or "float3x3" or "float4x4") + ) { + Fail( + "BGFX uniform layout requires vec4, mat3 or mat4 storage (or fixed arrays); lower scalar/vector parameters through explicit layout components." + ); + } + declarations + .Append("uniform ") + .Append(Declaration(packed ? ShaderSourceType.Atomic("float4") : input.type, name)) + .AppendLine(";"); + m_bindings.Add(new ShaderStageBinding(input.id, name, input.location)); if (packed) + { name += input.type.id switch { "float" => ".x", "float2" => ".xy", _ => ".xyz" }; + } break; case ShaderIrInputKind.SampledTexture: name = BindingName("s_inno_", input.id); string macro = input.type.id switch { - "sampled-texture2d" => "SAMPLER2D", "sampled-texture2d-array" => "SAMPLER2DARRAY", - "sampled-texture3d" => "SAMPLER3D", "sampled-texture-cube" => "SAMPLERCUBE", + "sampled-texture2d" => "SAMPLER2D", + "sampled-texture2d-array" => "SAMPLER2DARRAY", + "sampled-texture3d" => "SAMPLER3D", + "sampled-texture-cube" => "SAMPLERCUBE", _ => throw Error($"Unsupported sampled resource '{input.type.id}'.") }; declarations.Append(macro).Append('(').Append(name).Append(", ").Append(input.location).AppendLine(");"); - m_bindings.Add(new(input.id, name, input.location)); + m_bindings.Add(new ShaderStageBinding(input.id, name, input.location)); break; case ShaderIrInputKind.Builtin: (name, string type) = Builtin(input.semantic, stage.stage); if (!input.type.IsEquivalentTo(ShaderSourceType.Atomic(type))) + { Fail($"Builtin '{input.semantic}' requires {type}, not {input.type.id}."); + } break; case ShaderIrInputKind.Storage: name = BindingName("r_inno_", input.id); EmitStorageDeclaration(declarations, input, name); - m_bindings.Add(new(input.id, name, input.location)); + m_bindings.Add(new ShaderStageBinding(input.id, name, input.location)); break; - default: throw Error("Unsupported stage input kind."); + default: + throw Error("Unsupported stage input kind."); } stageInputs.Add(input.id, name); } foreach (ShaderIrStageOutput output in stage.outputs) + { if (output.kind == ShaderIrOutputKind.Varying) { string name = VaryingName(output.semantic, output.location); outputNames.Add(name); - varying.Append(Declaration(stage.body.outputs[output.id].type, name)).Append(" : ") - .Append(Semantic(output.semantic, output.location)).AppendLine(";"); + varying.Append(Declaration(stage.body.outputs[output.id].type, name)) + .Append(" : ") + .Append(Semantic(output.semantic, output.location)) + .AppendLine(";"); } + } if (inputNames.Count != 0) + { header.Append("$input ").AppendJoin(", ", inputNames.Order(StringComparer.Ordinal)).AppendLine(); + } if (outputNames.Count != 0) + { header.Append("$output ").AppendJoin(", ", outputNames.Order(StringComparer.Ordinal)).AppendLine(); + } header.AppendLine("#include "); DeclareFragmentOutputs(header); - header.AppendLine("#if BGFX_SHADER_MATRIX_COLUMN_MAJOR\n#define inno_matrix_element(m,c,r) ((m)[c][r])\n#else\n#define inno_matrix_element(m,c,r) ((m)[r][c])\n#endif"); + header.AppendLine( + "#if BGFX_SHADER_MATRIX_COLUMN_MAJOR\n#define inno_matrix_element(m,c,r) ((m)[c][r])\n#else\n#define inno_matrix_element(m,c,r) ((m)[r][c])\n#endif" + ); if (stage.stage == ShaderStage.Compute) + { header.AppendLine("#include "); + } foreach (ShaderIrInstruction instruction in stage.body.instructions) { if (instruction.operation == ShaderIrOperation.Input) @@ -124,17 +150,28 @@ internal BgfxGeneratedStage Generate() ShaderIrOutputKind.ClipPosition => "gl_Position", ShaderIrOutputKind.Varying => VaryingName(output.semantic, output.location), ShaderIrOutputKind.Depth => "gl_FragDepth", - ShaderIrOutputKind.Color => stage.outputs.Count(static value => value.kind == ShaderIrOutputKind.Color) == 1 && output.location == 0 - ? "gl_FragColor" : $"inno_fragment_color_{output.location}", + ShaderIrOutputKind.Color => stage.outputs.Count(static value => value.kind == ShaderIrOutputKind.Color) == 1 + && output.location == 0 + ? "gl_FragColor" + : $"inno_fragment_color_{output.location}", _ => throw Error("Unsupported stage output.") }; ShaderIrValue value = stage.body.outputs[output.id]; Assign(m_body, value.type, destination, Value(value)); } - var source = new StringBuilder().Append(header).Append(m_types).Append(declarations).Append(m_modules); + StringBuilder source = new StringBuilder().Append(header).Append(m_types).Append(declarations).Append(m_modules); source.AppendLine("#line 1 \"inno-generated-stage\""); if (stage.stage == ShaderStage.Compute) - source.Append("NUM_THREADS(").Append(stage.threadsX).Append(", ").Append(stage.threadsY).Append(", ").Append(stage.threadsZ).AppendLine(")"); + { + source + .Append("NUM_THREADS(") + .Append(stage.threadsX) + .Append(", ") + .Append(stage.threadsY) + .Append(", ") + .Append(stage.threadsZ) + .AppendLine(")"); + } source.AppendLine("void main() {").Append(m_body).AppendLine("}"); return new(source.ToString(), varying.ToString(), m_bindings.AsReadOnly(), m_sourcePositions.AsReadOnly()); } @@ -142,20 +179,33 @@ internal BgfxGeneratedStage Generate() private void DeclareFragmentOutputs(StringBuilder header) { ShaderIrStageOutput[] colors = stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Color) - .OrderBy(static output => output.location).ToArray(); + .OrderBy(static output => output.location) + .ToArray(); if (colors.Length == 0 || colors.Length == 1 && colors[0].location == 0) + { return; + } // Shaderc passes modern desktop GLSL through without lowering its deprecated MRT builtins. // Explicit locations also preserve sparse output slots; other dialects retain shaderc's lowering. header.AppendLine("#if BGFX_SHADER_LANGUAGE_GLSL >= 400 && !BGFX_SHADER_LANGUAGE_ESSL"); foreach (ShaderIrStageOutput color in colors) - header.Append("layout(location = ").Append(color.location).Append(") out vec4 inno_fragment_color_") - .Append(color.location).AppendLine(";"); + { + header.Append("layout(location = ") + .Append(color.location) + .Append(") out vec4 inno_fragment_color_") + .Append(color.location) + .AppendLine(";"); + } header.AppendLine("#else"); foreach (ShaderIrStageOutput color in colors) - header.Append("#define inno_fragment_color_").Append(color.location).Append(" gl_FragData[") - .Append(color.location).AppendLine("]"); + { + header.Append("#define inno_fragment_color_") + .Append(color.location) + .Append(" gl_FragData[") + .Append(color.location) + .AppendLine("]"); + } header.AppendLine("#endif"); } @@ -167,9 +217,13 @@ private void EmitInstruction(ShaderIrInstruction instruction) return; } if (EmitControlFlow(instruction)) + { return; + } if (EmitResourceInstruction(instruction)) + { return; + } ShaderIrValue output = instruction.outputs[0]; string name = NewLocal(output); m_body.Append(" ").Append(Declaration(output.type, name)).AppendLine(";"); @@ -181,22 +235,45 @@ private void EmitInstruction(ShaderIrInstruction instruction) break; case ShaderIrOperation.Construct: if (output.type.elementType is not null) + { for (int index = 0; index < operands.Length; index++) + { Assign(m_body, output.type.elementType, $"{name}[{index}]", operands[index]); + } + } else if (output.type.fields.Count != 0) + { for (int index = 0; index < operands.Length; index++) - Assign(m_body, output.type.fields[index].type, name + "." + FieldName(output.type.fields[index].name), operands[index]); + { + Assign( + m_body, + output.type.fields[index].type, + name + "." + FieldName(output.type.fields[index].name), + operands[index] + ); + } + } else if (IsMatrix(output.type)) { int columns = output.type.id[5] - '0'; int rows = output.type.id[7] - '0'; for (int column = 0; column < columns; column++) + { for (int row = 0; row < rows; row++) - Assign(m_body, ShaderSourceType.Atomic("float"), - MatrixElement(name, column, row), operands[column * rows + row]); + { + Assign( + m_body, + ShaderSourceType.Atomic("float"), + MatrixElement(name, column, row), + operands[column * rows + row] + ); + } + } } else + { Assign(m_body, output.type, name, TypeName(output.type) + "(" + string.Join(", ", operands) + ")"); + } break; case ShaderIrOperation.Extract: ShaderSourceType aggregate = instruction.inputs[0].type; @@ -204,11 +281,19 @@ private void EmitInstruction(ShaderIrInstruction instruction) { int rows = aggregate.id[7] - '0'; for (int row = 0; row < rows; row++) - Assign(m_body, ShaderSourceType.Atomic("float"), $"{name}[{row}]", - MatrixElement(operands[0], instruction.memberIndex, row)); + { + Assign( + m_body, + ShaderSourceType.Atomic("float"), + $"{name}[{row}]", + MatrixElement(operands[0], instruction.memberIndex, row) + ); + } break; } - string suffix = aggregate.fields.Count != 0 ? "." + FieldName(aggregate.fields[instruction.memberIndex].name) : $"[{instruction.memberIndex}]"; + string suffix = aggregate.fields.Count != 0 + ? "." + FieldName(aggregate.fields[instruction.memberIndex].name) + : $"[{instruction.memberIndex}]"; Assign(m_body, output.type, name, operands[0] + suffix); break; case ShaderIrOperation.Select: @@ -224,14 +309,26 @@ private void EmitInstruction(ShaderIrInstruction instruction) int columns = output.type.id[5] - '0'; int rows = output.type.id[7] - '0'; for (int column = 0; column < columns; column++) + { for (int row = 0; row < rows; row++) { - Assign(m_body, ShaderSourceType.Atomic("float"), MatrixElement(name, column, row), - Binary(instruction.operation, MatrixElement(operands[0], column, row), MatrixElement(operands[1], column, row))); + Assign( + m_body, + ShaderSourceType.Atomic("float"), + MatrixElement(name, column, row), + Binary( + instruction.operation, + MatrixElement(operands[0], column, row), + MatrixElement(operands[1], column, row) + ) + ); } + } } else + { Assign(m_body, output.type, name, Binary(instruction.operation, operands[0], operands[1])); + } break; } } @@ -248,24 +345,41 @@ private void EmitCall(ShaderIrInstruction instruction) int inputIndex = 0; int outputIndex = function.returnType.id == "void" ? 0 : 1; foreach (ShaderIrValue output in instruction.outputs) + { m_body.Append(" ").Append(Declaration(output.type, NewLocal(output))).AppendLine(";"); - var arguments = new List(); + } + List arguments = []; foreach (ShaderSourceParameter parameter in function.parameters) { if (parameter.direction == ShaderSourceParameterDirection.Input) + { arguments.Add(Value(instruction.inputs[inputIndex++])); + } else { string output = Value(instruction.outputs[outputIndex++]); if (parameter.direction == ShaderSourceParameterDirection.InputOutput) + { Assign(m_body, parameter.type, output, Value(instruction.inputs[inputIndex++])); + } arguments.Add(output); } } string call = functionName + "(" + string.Join(", ", arguments) + ")"; if (function.returnType.id == "void") + { m_body.Append(" ").Append(call).AppendLine(";"); + } else + { Assign(m_body, function.returnType, Value(instruction.outputs[0]), call); + } } } + +internal sealed record BgfxGeneratedStage( + string source, + string varying, + IReadOnlyList bindings, + IReadOnlyList sourcePositions +); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs index 7ae8901aa..e6dfee9a1 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs @@ -6,8 +6,8 @@ using System.Text; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -16,22 +16,12 @@ namespace Inno.Build.Toolchains.Bgfx.Tools; /// public sealed partial class BgfxShadercToolchain { - // The shader binary's uniform tags belong to its wire format. Offline compilation - // does not load or require the renderer's native binding assembly. - private enum ShaderUniformType : byte - { - Sampler = 0, - Vec4 = 2, - Mat3 = 3, - Mat4 = 4 - } - private static byte[] NormalizeGlslUniformTable( byte[] binary, ShaderIrStage stage, IReadOnlyList bindings ) { - HashSet activeNames = ReadReflectedUniformNames(binary, GraphicsApi.OpenGL); + HashSet activeNames = ReadReflectedUniformNames(binary, GraphicsApi.openGL); ushort count = BinaryPrimitives.ReadUInt16LittleEndian(binary.AsSpan(C_SHADER_BINARY_HEADER_SIZE)); int offset = C_SHADER_BINARY_HEADER_SIZE + sizeof(ushort); var records = new Dictionary(StringComparer.Ordinal); @@ -42,7 +32,9 @@ IReadOnlyList bindings string name = Encoding.UTF8.GetString(binary, offset, nameLength); offset += nameLength + C_SHADER_UNIFORM_METADATA_SIZE; if (activeNames.Contains(name)) + { records.Add(name, binary.AsSpan(start, offset - start).ToArray()); + } } // Shaderc's line scanner stops at layout-qualified declarations. Complete its metadata @@ -51,18 +43,24 @@ IReadOnlyList bindings { ShaderIrStageInput input = stage.inputs.Single(value => value.id == binding.id); if (input.kind != ShaderIrInputKind.Storage && !records.ContainsKey(binding.nativeName)) + { records.Add(binding.nativeName, EncodeGlslUniform(input, binding.nativeName)); + } } if (records.Count > ushort.MaxValue) + { throw new InvalidDataException("The compiled GLSL uniform table exceeds the BGFX binary limit."); + } using var output = new MemoryStream(); output.Write(binary.AsSpan(0, C_SHADER_BINARY_HEADER_SIZE)); Span encodedCount = stackalloc byte[sizeof(ushort)]; BinaryPrimitives.WriteUInt16LittleEndian(encodedCount, (ushort)records.Count); output.Write(encodedCount); foreach (byte[] record in records.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Value)) + { output.Write(record); + } output.Write(binary.AsSpan(offset)); return output.ToArray(); } @@ -73,20 +71,22 @@ string nativeName ) { byte[] name = Encoding.UTF8.GetBytes(nativeName); int count = input.type.elementType is null ? 1 : input.type.elementCount; - string typeId = input.type.elementType?.id ?? input.type.id; + string typeID = input.type.elementType?.id ?? input.type.id; ShaderUniformType type = input.kind == ShaderIrInputKind.SampledTexture ? ShaderUniformType.Sampler - : typeId switch + : typeID switch { "float" or "float2" or "float3" or "float4" => ShaderUniformType.Vec4, "float3x3" => ShaderUniformType.Mat3, "float4x4" => ShaderUniformType.Mat4, - _ => throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' has unsupported storage '{typeId}'.") + _ => throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' has unsupported storage '{typeID}'.") }; if (name.Length == 0 || name.Length > byte.MaxValue || count <= 0 || count > byte.MaxValue) + { throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' exceeds the BGFX binary limits."); + } int registerCount = count * (type == ShaderUniformType.Mat3 ? 3 : type == ShaderUniformType.Mat4 ? 4 : 1); - byte[] record = new byte[1 + name.Length + C_SHADER_UNIFORM_METADATA_SIZE]; + var record = new byte[1 + name.Length + C_SHADER_UNIFORM_METADATA_SIZE]; record[0] = (byte)name.Length; name.CopyTo(record, 1); Span metadata = record.AsSpan(1 + name.Length); @@ -95,4 +95,14 @@ string nativeName BinaryPrimitives.WriteUInt16LittleEndian(metadata[4..], (ushort)registerCount); return record; } + + // The shader binary's uniform tags belong to its wire format. Offline compilation + // does not load or require the renderer's native binding assembly. + private enum ShaderUniformType : byte + { + Sampler = 0, + Vec4 = 2, + Mat3 = 3, + Mat4 = 4 + } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs index 763cde291..64b37d269 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs @@ -10,8 +10,8 @@ using Inno.Core.Diagnostics; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -23,18 +23,18 @@ public sealed partial class BgfxShadercToolchain private const byte C_SHADER_BINARY_VERSION = 11; private const int C_SHADER_BINARY_HEADER_SIZE = 12; private const int C_SHADER_UNIFORM_METADATA_SIZE = 10; - private static readonly UTF8Encoding S_GLSL_ENCODING = new(false, true); - private static readonly IReadOnlyList s_languages = Array.AsReadOnly(new[] { "inno.shader-language.bgfx-sc" }); + private static readonly UTF8Encoding GLSL_ENCODING = new(false, true); + private static readonly IReadOnlyList LANGUAGES = Array.AsReadOnly(["inno.shader-language.bgfx-sc"]); /// /// Gets shader source languages accepted by this toolchain. /// - public IReadOnlyList supportedSourceLanguages => s_languages; + public IReadOnlyList supportedSourceLanguages => LANGUAGES; /// /// Gets the implementation id text used by the current instance. /// - public string implementationId => "bgfx"; + public string implementationID => "bgfx"; /// /// Compiles the supplied source into a validated runtime artifact. @@ -64,16 +64,41 @@ CancellationToken cancellationToken } catch (BgfxSourceSyntaxException failure) { - return new([], [], [new("BGFX_IR_GENERATION", DiagnosticSeverity.Error, failure.Message, failure.position)]); + return new( + [], + [], + [new ShaderSourceDiagnostic("BGFX_IR_GENERATION", DiagnosticSeverity.Error, failure.Message, failure.position)] + ); } - BgfxShadercResult native = await RunCompilerAsync(generated.source, generated.varying, request.stage.stage, - request.target, cancellationToken).ConfigureAwait(false); + BgfxShadercResult native = await RunCompilerAsync( + generated.source, + generated.varying, + request.stage.stage, + request.target, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - List diagnostics = ParseDiagnostics(native, generated.sourcePositions, new("inno-generated-stage", 0, 0)); - if (native.exitCode != 0 || native.bytes is null || native.bytes.Length == 0 || diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - { + List diagnostics = ParseDiagnostics( + native, + generated.sourcePositions, + new ShaderSourcePosition("inno-generated-stage", 0, 0) + ); + if (native.exitCode != 0 + || native.bytes is null + || native.bytes.Length == 0 + || diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error) + ) { if (!diagnostics.Any(static diagnostic => diagnostic.severity == DiagnosticSeverity.Error)) - diagnostics.Add(new("BGFX_SHADER_COMPILE_FAILED", DiagnosticSeverity.Error, $"BGFX shaderc exited with code {native.exitCode} without a usable binary.", new("inno-generated-stage", 0, 0))); + { + diagnostics.Add( + new ShaderSourceDiagnostic( + "BGFX_SHADER_COMPILE_FAILED", + DiagnosticSeverity.Error, + $"BGFX shaderc exited with code {native.exitCode} without a usable binary.", + new ShaderSourcePosition("inno-generated-stage", 0, 0) + ) + ); + } return new([], generated.bindings, diagnostics); } IReadOnlyList reflectedBindings; @@ -85,14 +110,22 @@ CancellationToken cancellationToken ShaderIrStageInput input = request.stage.inputs.Single(value => value.id == binding.id); return input.kind == ShaderIrInputKind.Storage || reflectedNames.Contains(binding.nativeName); }).ToArray(); - if (request.target.capabilities.backend == GraphicsApi.OpenGL - || request.target.capabilities.backend == GraphicsApi.OpenGLES) + if (request.target.capabilities.backend == GraphicsApi.openGL + || request.target.capabilities.backend == GraphicsApi.openGLES + ) { native = native with { bytes = NormalizeGlslUniformTable(native.bytes, request.stage, reflectedBindings) }; + } } catch (InvalidDataException failure) { - diagnostics.Add(new("BGFX_SHADER_REFLECTION", DiagnosticSeverity.Error, failure.Message, - new("inno-generated-stage", 0, 0))); + diagnostics.Add( + new ShaderSourceDiagnostic( + "BGFX_SHADER_REFLECTION", + DiagnosticSeverity.Error, + failure.Message, + new ShaderSourcePosition("inno-generated-stage", 0, 0) + ) + ); return new([], [], diagnostics); } return new(native.bytes, reflectedBindings, diagnostics); @@ -103,13 +136,20 @@ private static HashSet ReadReflectedUniformNames( GraphicsApi backend ) { if (binary.Length < C_SHADER_BINARY_HEADER_SIZE + sizeof(ushort)) + { throw new InvalidDataException("BGFX shaderc returned a truncated shader binary header."); + } if (binary[1] != (byte)'S' || binary[2] != (byte)'H' - || binary[0] is not ((byte)'V' or (byte)'F' or (byte)'C')) + || binary[0] is not ((byte)'V' or (byte)'F' or (byte)'C') + ) { throw new InvalidDataException("BGFX shaderc returned an unrecognized shader binary."); + } if (binary[3] != C_SHADER_BINARY_VERSION) + { throw new InvalidDataException( - $"BGFX shader binary version {binary[3]} does not match the bundled reader version {C_SHADER_BINARY_VERSION}."); + $"BGFX shader binary version {binary[3]} does not match the bundled reader version {C_SHADER_BINARY_VERSION}." + ); + } int offset = C_SHADER_BINARY_HEADER_SIZE; ushort count = BinaryPrimitives.ReadUInt16LittleEndian(binary.Slice(offset, sizeof(ushort))); @@ -122,10 +162,12 @@ GraphicsApi backend RequireBinaryRange(binary, offset, nameLength + C_SHADER_UNIFORM_METADATA_SIZE); string name = Encoding.UTF8.GetString(binary.Slice(offset, nameLength)); if (string.IsNullOrWhiteSpace(name) || !result.Add(name)) + { throw new InvalidDataException("BGFX shader binary contains an invalid reflected uniform table."); + } offset += nameLength + C_SHADER_UNIFORM_METADATA_SIZE; } - if (backend == GraphicsApi.OpenGL || backend == GraphicsApi.OpenGLES) + if (backend == GraphicsApi.openGL || backend == GraphicsApi.openGLES) { result.Clear(); ReadCompiledGlslUniformNames(binary[offset..], result); @@ -140,17 +182,22 @@ HashSet names RequireBinaryRange(payload, 0, sizeof(uint)); uint length = BinaryPrimitives.ReadUInt32LittleEndian(payload); if (length > int.MaxValue - sizeof(uint) - 1) + { throw new InvalidDataException("BGFX shaderc returned an invalid GLSL payload length."); + } RequireBinaryRange(payload, sizeof(uint), (int)length + 1); if (payload[sizeof(uint) + (int)length] != 0) + { throw new InvalidDataException("BGFX shaderc returned an unterminated GLSL payload."); + } List tokens; try { - string source = S_GLSL_ENCODING.GetString(payload.Slice(sizeof(uint), (int)length)); + string source = GLSL_ENCODING.GetString(payload.Slice(sizeof(uint), (int)length)); tokens = BgfxSourceLexer.Tokenize(new ShaderSourceFile("bgfx-compiled-stage", source)) - .Where(static token => token.text != "\n").ToList(); + .Where(static token => token.text != "\n") + .ToList(); } catch (Exception failure) when (failure is DecoderFallbackException or BgfxSourceSyntaxException) { @@ -161,7 +208,9 @@ HashSet names foreach (BgfxSourceToken token in tokens) { if (token.isIdentifier) + { identifierCounts[token.text] = identifierCounts.GetValueOrDefault(token.text) + 1; + } } // Desktop GLSL can retain layout qualifiers that shaderc's uniform table scanner does not recognize. @@ -169,15 +218,19 @@ HashSet names for (int index = 0; index < tokens.Count; index++) { if (tokens[index].text != "uniform") + { continue; + } int typeIndex = index + 1; if (typeIndex < tokens.Count && tokens[typeIndex].text is "lowp" or "mediump" or "highp") + { typeIndex++; + } int nameIndex = typeIndex + 1; if (nameIndex + 1 < tokens.Count && tokens[nameIndex].isIdentifier && identifierCounts[tokens[nameIndex].text] > 1 - && tokens[nameIndex + 1].text is ";" or "[") - { + && tokens[nameIndex + 1].text is ";" or "[" + ) { names.Add(tokens[nameIndex].text); } } @@ -189,7 +242,9 @@ private static void RequireBinaryRange( int length ) { if (length < 0 || offset < 0 || offset > binary.Length - length) + { throw new InvalidDataException("BGFX shaderc returned a truncated reflected uniform table."); + } } private static List ParseDiagnostics( @@ -197,33 +252,51 @@ private static List ParseDiagnostics( IReadOnlyList sourcePositions, ShaderSourcePosition fallback ) { - var diagnostics = new List(); - string[] lines = (native.standardOutput + "\n" + native.standardError).Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + List diagnostics = []; + string[] lines = (native.standardOutput + "\n" + native.standardError).Split( + '\n', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ); var sourceMap = new Dictionary(); foreach (string line in lines) { Match excerpt = SourceExcerptPattern().Match(line); if (!excerpt.Success || !int.TryParse(excerpt.Groups["line"].Value, out int physicalLine) - || !int.TryParse(excerpt.Groups["marker"].Value, out int marker)) + || !int.TryParse(excerpt.Groups["marker"].Value, out int marker) + ) { continue; + } if (marker >= 0 && marker < sourcePositions.Count) + { sourceMap[physicalLine] = sourcePositions[marker]; + } } foreach (string line in lines) { if (line == "Code:" || line == "---") + { continue; - DiagnosticSeverity severity = ErrorSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Error - : WarningSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Warning : DiagnosticSeverity.Info; + } + DiagnosticSeverity severity = ErrorSeverityPattern().IsMatch(line) + ? DiagnosticSeverity.Error + : WarningSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Warning : DiagnosticSeverity.Info; Match match = SourceDiagnosticPattern().Match(line); ShaderSourcePosition position = fallback; if (match.Success && int.TryParse(match.Groups["line"].Value, out int sourceLine)) { _ = int.TryParse(match.Groups["column"].Value, out int column); - position = sourceMap.TryGetValue(sourceLine, out ShaderSourcePosition original) ? original - : new(fallback.assetPath, sourceLine, column); + position = sourceMap.TryGetValue(sourceLine, out ShaderSourcePosition original) + ? original + : new ShaderSourcePosition(fallback.assetPath, sourceLine, column); } - diagnostics.Add(new(severity == DiagnosticSeverity.Warning ? "BGFX_SHADER_WARNING" : "BGFX_SHADER_DIAGNOSTIC", severity, line, position)); + diagnostics.Add( + new ShaderSourceDiagnostic( + severity == DiagnosticSeverity.Warning ? "BGFX_SHADER_WARNING" : "BGFX_SHADER_DIAGNOSTIC", + severity, + line, + position + ) + ); } return diagnostics; } @@ -233,47 +306,88 @@ private static void ValidateCapabilities( GraphicsCapabilities capabilities ) { if (stage.stage == ShaderStage.Compute) + { Require(GraphicsCapability.Compute); + } foreach (ShaderIrStageInput input in stage.inputs) { if (input.kind == ShaderIrInputKind.VertexAttribute && input.semantic == "instance-data") + { Require(GraphicsCapability.Instancing); + } if (input.kind == ShaderIrInputKind.Builtin && input.semantic == "vertex-id") + { Require(GraphicsCapability.ProceduralDraw); + } if (input.type.id == "sampled-texture2d-array") + { Require(GraphicsCapability.Texture2DArray); + } if (input.type.id == "sampled-texture3d") + { Require(GraphicsCapability.Texture3D); + } if (input.type.storage is ShaderStorageType storage) { if (stage.stage != ShaderStage.Compute) - throw new BgfxSourceSyntaxException("The BGFX runtime contract exposes storage bindings only for compute passes.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + "The BGFX runtime contract exposes storage bindings only for compute passes.", + new ShaderSourcePosition("inno-generated-stage", 1, 1) + ); + } Require(storage.isImage ? GraphicsCapability.StorageTexture : GraphicsCapability.StorageBuffer); if (input.location >= capabilities.limits.maxComputeBindings) - throw new BgfxSourceSyntaxException("A storage binding exceeds the target compute binding limit.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + "A storage binding exceeds the target compute binding limit.", + new ShaderSourcePosition("inno-generated-stage", 1, 1) + ); + } if (storage.isImage) { if (storage.array) + { Require(GraphicsCapability.Texture2DArray); + } if (storage.dimension == RenderTextureDimension.Texture3D) + { Require(GraphicsCapability.Texture3D); + } if (!capabilities.SupportsStorage(storage.format!.Value, storage.access)) - throw new BgfxSourceSyntaxException($"Storage format '{storage.format}' does not support '{storage.access}' on this target.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"Storage format '{storage.format}' does not support '{storage.access}' on this target.", + new ShaderSourcePosition("inno-generated-stage", 1, 1) + ); + } } } } foreach (ShaderIrStageOutput output in stage.outputs) { if (output.kind == ShaderIrOutputKind.Depth) + { Require(GraphicsCapability.FragmentDepth); + } if (output.kind == ShaderIrOutputKind.Color && output.location >= capabilities.limits.maxColorAttachments) - throw new BgfxSourceSyntaxException($"Color attachment {output.location} exceeds the target limit {capabilities.limits.maxColorAttachments}.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"Color attachment {output.location} exceeds the target limit {capabilities.limits.maxColorAttachments}.", + new ShaderSourcePosition("inno-generated-stage", 1, 1) + ); + } } return; void Require(GraphicsCapability capability) { if (!capabilities.Supports(capability)) - throw new BgfxSourceSyntaxException($"The stage requires unsupported capability '{capability}'.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"The stage requires unsupported capability '{capability}'.", + new ShaderSourcePosition("inno-generated-stage", 1, 1) + ); + } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs index 5d439459b..7be20e818 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs @@ -11,10 +11,14 @@ internal sealed class BgfxPreprocessorExpression(IReadOnlyList internal long Evaluate() { if (tokens.Count == 0) + { throw new InvalidOperationException("A preprocessing expression is empty."); + } long value = Conditional(true); if (m_offset != tokens.Count) + { Fail("Unexpected token in integer constant expression."); + } return value; } @@ -22,10 +26,14 @@ private long Conditional(bool evaluate) { long condition = Binary(1, evaluate); if (!Match("?")) + { return condition; + } long whenTrue = Conditional(evaluate && condition != 0); if (!Match(":")) + { Fail("Expected ':' in conditional expression."); + } long whenFalse = Conditional(evaluate && condition == 0); return condition != 0 ? whenTrue : whenFalse; } @@ -40,7 +48,9 @@ bool evaluate string operation = tokens[m_offset].text; int precedence = Precedence(operation); if (precedence < minimum) + { break; + } m_offset++; bool evaluateRight = evaluate && !(operation == "&&" && left == 0 || operation == "||" && left != 0); long right = Binary(precedence + 1, evaluateRight); @@ -50,17 +60,27 @@ bool evaluate continue; } if (operation is "/" or "%" && right == 0) + { Fail("Division by zero in integer constant expression."); + } left = operation switch { "||" => left != 0 || right != 0 ? 1 : 0, "&&" => left != 0 && right != 0 ? 1 : 0, - "|" => left | right, "^" => left ^ right, "&" => left & right, - "==" => left == right ? 1 : 0, "!=" => left != right ? 1 : 0, - "<" => left < right ? 1 : 0, ">" => left > right ? 1 : 0, - "<=" => left <= right ? 1 : 0, ">=" => left >= right ? 1 : 0, - "<<" => left << (int)right, ">>" => left >> (int)right, - "+" => unchecked(left + right), "-" => unchecked(left - right), "*" => unchecked(left * right), + "|" => left | right, + "^" => left ^ right, + "&" => left & right, + "==" => left == right ? 1 : 0, + "!=" => left != right ? 1 : 0, + "<" => left < right ? 1 : 0, + ">" => left > right ? 1 : 0, + "<=" => left <= right ? 1 : 0, + ">=" => left >= right ? 1 : 0, + "<<" => left << (int)right, + ">>" => left >> (int)right, + "+" => unchecked(left + right), + "-" => unchecked(left - right), + "*" => unchecked(left * right), "/" => left == long.MinValue && right == -1 ? long.MinValue : left / right, "%" => left == long.MinValue && right == -1 ? 0 : left % right, _ => throw new InvalidOperationException("Unknown preprocessing operation.") @@ -72,34 +92,54 @@ bool evaluate private long Unary(bool evaluate) { if (Match("!")) + { return Unary(evaluate) == 0 ? 1 : 0; + } if (Match("~")) + { return ~Unary(evaluate); + } if (Match("-")) + { return unchecked(-Unary(evaluate)); + } if (Match("+")) + { return Unary(evaluate); + } if (Match("(")) { long value = Conditional(evaluate); if (!Match(")")) + { Fail("Expected ')' in constant expression."); + } return value; } if (m_offset >= tokens.Count) + { Fail("Expected an integer expression."); + } BgfxSourceToken token = tokens[m_offset++]; if (token.isIdentifier) + { return 0; + } string number = token.text.TrimEnd('u', 'U', 'l', 'L'); try { if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { return unchecked((long)ulong.Parse(number.AsSpan(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture)); + } if (number.Length > 1 && number[0] == '0') + { return Convert.ToInt64(number, 8); + } if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out long parsed)) + { return parsed; + } } catch (Exception exception) when (exception is FormatException or OverflowException or ArgumentException) { } throw new BgfxSourceSyntaxException($"'{token.text}' is not an integer constant.", token.position); @@ -108,7 +148,9 @@ private long Unary(bool evaluate) private bool Match(string value) { if (m_offset >= tokens.Count || tokens[m_offset].text != value) + { return false; + } m_offset++; return true; } @@ -116,11 +158,19 @@ private bool Match(string value) private void Fail(string message) => throw new BgfxSourceSyntaxException(message, tokens[Math.Clamp(m_offset, 0, tokens.Count - 1)].position); - private static int Precedence(string operation) => operation switch + private static int Precedence(string operation) + => operation switch { - "||" => 1, "&&" => 2, "|" => 3, "^" => 4, "&" => 5, - "==" or "!=" => 6, "<" or ">" or "<=" or ">=" => 7, - "<<" or ">>" => 8, "+" or "-" => 9, "*" or "/" or "%" => 10, + "||" => 1, + "&&" => 2, + "|" => 3, + "^" => 4, + "&" => 5, + "==" or "!=" => 6, + "<" or ">" or "<=" or ">=" => 7, + "<<" or ">>" => 8, + "+" or "-" => 9, + "*" or "/" or "%" => 10, _ => 0 }; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs index 0b09608db..c2c1aa6f8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; using Inno.Core.Diagnostics; using Inno.Rendering.Shaders; @@ -15,7 +13,7 @@ public sealed class BgfxShaderSourceFrontend : IShaderSourceFrontend /// /// Gets the language id text used by the current instance. /// - public string languageId => "inno.shader-language.bgfx-sc"; + public string languageID => "inno.shader-language.bgfx-sc"; /// /// Analyzes source text and returns validated output with diagnostics. @@ -38,346 +36,11 @@ public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) } catch (BgfxSourceSyntaxException failure) { - return new(null, preprocessor.dependencies, - [new ShaderSourceDiagnostic("SHADER_SOURCE_INTERFACE", DiagnosticSeverity.Error, failure.Message, failure.position)]); + return new( + null, + preprocessor.dependencies, + [new ShaderSourceDiagnostic("SHADER_SOURCE_INTERFACE", DiagnosticSeverity.Error, failure.Message, failure.position)] + ); } } } - -internal sealed class BgfxSourceDeclarationParser( - List tokens, - ShaderSourceRequest request -) { - private readonly Dictionary m_types = new(StringComparer.Ordinal); - private readonly Dictionary m_constants = new(StringComparer.Ordinal); - private readonly List m_exports = []; - private readonly List<(IReadOnlyList parameters, List body)> m_bodies = []; - private int m_offset; - internal IReadOnlyDictionary types => m_types; - internal HashSet globals { get; } = new(StringComparer.Ordinal); - internal List<(int start, int end)> typeDeclarations { get; } = []; - - internal ShaderSourceFunction Parse() - { - while (m_offset < tokens.Count) - { - if (Match(";")) - continue; - int declarationStart = m_offset; - if (Peek("struct")) - { - ReadStructure(); - typeDeclarations.Add((declarationStart, m_offset)); - continue; - } - bool alias = Match("typedef"); - bool constant = false; - while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) - constant |= tokens[m_offset++].text == "const"; - ShaderSourceType type = ReadType(); - BgfxSourceToken name = ReadIdentifier(); - if (Match("(")) - { - if (alias) - Fail("Function typedefs are not source module value types.", name); - List parameters = ReadParameters(); - if (name.text == "main") - Fail("A source module cannot declare main(); shader entries are generated from graph outputs.", name); - globals.Add(name.text); - if (Match(";")) - continue; - Require("{"); - m_bodies.Add((parameters, ReadBody())); - if (name.text == request.entryPoint) - { - if (!StringComparer.Ordinal.Equals(name.position.assetPath, request.source.assetPath)) - Fail("The exported function must be declared in its selected source file, not an include.", name); - m_exports.Add(new(name.text, type, parameters, name.position)); - } - continue; - } - type = ReadArray(type); - if (alias) - { - if (!m_types.TryAdd(name.text, type)) - Fail($"Type '{name.text}' is already declared.", name); - Require(";"); - typeDeclarations.Add((declarationStart, m_offset)); - continue; - } - if (!constant) - Fail("Module globals must be constants; stage inputs and resource bindings belong to the graph target.", name); - globals.Add(name.text); - if (Match("=")) - { - List initializer = ReadUntilSemicolon(); - if (type.id is "int" or "uint") - m_constants[name.text] = EvaluateInteger(initializer, name); - } - else - Require(";"); - } - if (m_exports.Count != 1) - throw new BgfxSourceSyntaxException(m_exports.Count == 0 - ? $"Source does not define the selected public function '{request.entryPoint}'." - : $"Public function '{request.entryPoint}' is overloaded or defined more than once; select an unambiguous export.", - new(request.source.assetPath, 1, 1)); - ValidateExplicitInterfaces(); - return m_exports[0]; - } - - private List ReadParameters() - { - var parameters = new List(); - if (Match(")")) - return parameters; - if (Peek("void") && m_offset + 1 < tokens.Count && tokens[m_offset + 1].text == ")") - { - m_offset += 2; - return parameters; - } - do - { - ShaderSourceParameterDirection direction = ShaderSourceParameterDirection.Input; - bool directionAssigned = false; - while (m_offset < tokens.Count) - { - BgfxSourceToken qualifier = tokens[m_offset]; - if (qualifier.text is "in" or "out" or "inout") - { - if (directionAssigned) - Fail("A parameter has more than one direction qualifier.", qualifier); - directionAssigned = true; - direction = qualifier.text switch - { - "out" => ShaderSourceParameterDirection.Output, - "inout" => ShaderSourceParameterDirection.InputOutput, - _ => ShaderSourceParameterDirection.Input - }; - m_offset++; - } - else if (IsQualifier(qualifier.text)) - m_offset++; - else - break; - } - ShaderSourceType type = ReadType(); - BgfxSourceToken name = ReadIdentifier(); - if (type.id == "void") - Fail("A parameter cannot have void type.", name); - type = ReadArray(type); - if (parameters.Any(parameter => parameter.name == name.text)) - Fail("Duplicate public parameter name.", name); - parameters.Add(new(name.text, type, direction)); - } while (Match(",")); - Require(")"); - return parameters; - } - - private void ReadStructure() - { - Require("struct"); - BgfxSourceToken name = ReadIdentifier(); - Require("{"); - var fields = new List(); - while (!Match("}")) - { - while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) - m_offset++; - ShaderSourceType type = ReadType(); - if (type.id == "void") - Fail("A structure field cannot have void type.", name); - do - { - BgfxSourceToken field = ReadIdentifier(); - ShaderSourceType fieldType = ReadArray(type); - if (fields.Any(existing => existing.name == field.text)) - Fail("Duplicate structure member name.", field); - fields.Add(new(field.text, fieldType)); - } while (Match(",")); - Require(";"); - } - Require(";"); - if (fields.Count == 0) - Fail("A structure requires at least one field.", name); - if (!m_types.TryAdd(name.text, ShaderSourceType.Structure("struct:" + name.text, fields))) - Fail($"Type '{name.text}' is already declared.", name); - } - - private ShaderSourceType ReadType() - { - BgfxSourceToken token = ReadIdentifier(); - if (m_types.TryGetValue(token.text, out ShaderSourceType? declared)) - return declared; - string? canonical = token.text switch - { - "void" or "bool" or "int" or "uint" or "float" or "double" => token.text, - "half" => "float16", - "vec2" or "float2" => "float2", "vec3" or "float3" => "float3", "vec4" or "float4" => "float4", - "ivec2" or "int2" => "int2", "ivec3" or "int3" => "int3", "ivec4" or "int4" => "int4", - "uvec2" or "uint2" => "uint2", "uvec3" or "uint3" => "uint3", "uvec4" or "uint4" => "uint4", - "bvec2" or "bool2" => "bool2", "bvec3" or "bool3" => "bool3", "bvec4" or "bool4" => "bool4", - "mat2" or "float2x2" => "float2x2", "mat3" or "float3x3" => "float3x3", "mat4" or "float4x4" => "float4x4", - "sampler2D" or "BgfxSampler2D" => "sampled-texture2d", - "sampler2DArray" or "BgfxSampler2DArray" => "sampled-texture2d-array", - "sampler3D" or "BgfxSampler3D" => "sampled-texture3d", - "samplerCube" or "BgfxSamplerCube" => "sampled-texture-cube", - _ => null - }; - if (canonical is null) - Fail($"Unsupported or undeclared source type '{token.text}'.", token); - return ShaderSourceType.Atomic(canonical!); - } - - private ShaderSourceType ReadArray(ShaderSourceType element) - { - var lengths = new List(); - while (Match("[")) - { - BgfxSourceToken start = Current(); - if (element.id == "void") - Fail("An array cannot contain void values.", start); - var expression = new List(); - while (!Match("]")) - expression.Add(Next()); - long count = EvaluateInteger(expression, start); - if (count <= 0 || count > int.MaxValue) - Fail("Function interface arrays require a positive, fixed 32-bit length.", start); - lengths.Add((int)count); - } - for (int i = lengths.Count - 1; i >= 0; i--) - element = ShaderSourceType.ArrayOf(element, lengths[i]); - return element; - } - - private long EvaluateInteger( - List expression, - BgfxSourceToken location - ) { - if (expression.Count == 0) - Fail("Expected a fixed integer expression.", location); - var values = new List(); - foreach (BgfxSourceToken token in expression) - { - if (!token.isIdentifier) - { - values.Add(token); - continue; - } - if (!m_constants.TryGetValue(token.text, out long constant)) - Fail($"Unresolved array constant '{token.text}'.", token); - values.Add(new("(", token.position)); - foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize(new(token.position.assetPath, - constant.ToString(CultureInfo.InvariantCulture)))) - values.Add(literal with { position = token.position }); - values.Add(new(")", token.position)); - } - return new BgfxPreprocessorExpression(values).Evaluate(); - } - - private List ReadUntilSemicolon() - { - var result = new List(); - int braces = 0; - int parentheses = 0; - while (true) - { - BgfxSourceToken token = Next(); - if (token.text == ";" && braces == 0 && parentheses == 0) - return result; - if (token.text == "{") - braces++; - if (token.text == "}") - braces--; - if (token.text == "(") - parentheses++; - if (token.text == ")") - parentheses--; - result.Add(token); - } - } - - private List ReadBody() - { - var body = new List(); - int nesting = 1; - while (nesting != 0) - { - BgfxSourceToken token = Next(); - if (token.text == "{") - nesting++; - if (token.text == "}") - nesting--; - body.Add(token); - } - return body; - } - - private void ValidateExplicitInterfaces() - { - foreach ((IReadOnlyList parameters, List body) in m_bodies) - { - var explicitNames = new HashSet(parameters.Select(static value => value.name), StringComparer.Ordinal); - explicitNames.UnionWith(globals); - for (int index = 0; index < body.Count; index++) - { - BgfxSourceToken token = body[index]; - if (index != 0 && body[index - 1].text == ".") - continue; - if (!explicitNames.Contains(token.text) && IsImplicitStageName(token.text)) - Fail($"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", token); - } - } - } - - private static bool IsImplicitStageName(string name) - => name.StartsWith("gl_", StringComparison.Ordinal) || name.StartsWith("inno_", StringComparison.Ordinal) - || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) - || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) - || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) - || name.StartsWith("a_color", StringComparison.Ordinal) - || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" - or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" - or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; - - private BgfxSourceToken ReadIdentifier() - { - BgfxSourceToken token = Next(); - if (!token.isIdentifier) - Fail($"Expected an identifier, found '{token.text}'.", token); - return token; - } - - private BgfxSourceToken Current() - { - if (m_offset >= tokens.Count) - throw new BgfxSourceSyntaxException("Unexpected end of source declaration.", tokens.Count == 0 - ? new(request.source.assetPath, 1, 1) : tokens[^1].position); - return tokens[m_offset]; - } - - private BgfxSourceToken Next() - { - BgfxSourceToken token = Current(); - m_offset++; - return token; - } - private bool Peek(string value) => m_offset < tokens.Count && tokens[m_offset].text == value; - private bool Match(string value) - { - if (!Peek(value)) - return false; - m_offset++; - return true; - } - private void Require(string value) - { - if (!Match(value)) - Fail($"Expected '{value}'.", Current()); - } - private static bool IsQualifier(string value) => value is "const" or "static" or "inline" or "highp" or "mediump" or "lowp"; - private static void Fail( - string message, - BgfxSourceToken token - ) => throw new BgfxSourceSyntaxException(message, token.position); -} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs new file mode 100644 index 000000000..0a1fce5d8 --- /dev/null +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs @@ -0,0 +1,459 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Inno.Rendering.Shaders; + +namespace Inno.Build.Toolchains.Bgfx.Tools; + +internal sealed class BgfxSourceDeclarationParser( + List tokens, + ShaderSourceRequest request +) { + private readonly Dictionary m_types = new(StringComparer.Ordinal); + private readonly Dictionary m_constants = new(StringComparer.Ordinal); + private readonly List m_exports = []; + private readonly List<(IReadOnlyList parameters, List body)> m_bodies = []; + private int m_offset; + internal IReadOnlyDictionary types => m_types; + internal HashSet globals { get; } = new(StringComparer.Ordinal); + internal List<(int start, int end)> typeDeclarations { get; } = []; + + internal ShaderSourceFunction Parse() + { + while (m_offset < tokens.Count) + { + if (Match(";")) + { + continue; + } + int declarationStart = m_offset; + if (Peek("struct")) + { + ReadStructure(); + typeDeclarations.Add((declarationStart, m_offset)); + continue; + } + bool alias = Match("typedef"); + bool constant = false; + while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { + constant |= tokens[m_offset++].text == "const"; + } + ShaderSourceType type = ReadType(); + BgfxSourceToken name = ReadIdentifier(); + if (Match("(")) + { + if (alias) + { + Fail("Function typedefs are not source module value types.", name); + } + List parameters = ReadParameters(); + if (name.text == "main") + { + Fail("A source module cannot declare main(); shader entries are generated from graph outputs.", name); + } + globals.Add(name.text); + if (Match(";")) + { + continue; + } + Require("{"); + m_bodies.Add((parameters, ReadBody())); + if (name.text == request.entryPoint) + { + if (!StringComparer.Ordinal.Equals(name.position.assetPath, request.source.assetPath)) + { + Fail("The exported function must be declared in its selected source file, not an include.", name); + } + m_exports.Add(new ShaderSourceFunction(name.text, type, parameters, name.position)); + } + continue; + } + type = ReadArray(type); + if (alias) + { + if (!m_types.TryAdd(name.text, type)) + { + Fail($"Type '{name.text}' is already declared.", name); + } + Require(";"); + typeDeclarations.Add((declarationStart, m_offset)); + continue; + } + if (!constant) + { + Fail("Module globals must be constants; stage inputs and resource bindings belong to the graph target.", name); + } + globals.Add(name.text); + if (Match("=")) + { + List initializer = ReadUntilSemicolon(); + if (type.id is "int" or "uint") + { + m_constants[name.text] = EvaluateInteger(initializer, name); + } + } + else + { + Require(";"); + } + } + if (m_exports.Count != 1) + { + throw new BgfxSourceSyntaxException( + m_exports.Count == 0 + ? $"Source does not define the selected public function '{request.entryPoint}'." + : $"Public function '{request.entryPoint}' is overloaded or defined more than once; select an unambiguous export.", + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ); + } + ValidateExplicitInterfaces(); + return m_exports[0]; + } + + private List ReadParameters() + { + List parameters = []; + if (Match(")")) + { + return parameters; + } + if (Peek("void") && m_offset + 1 < tokens.Count && tokens[m_offset + 1].text == ")") + { + m_offset += 2; + return parameters; + } + do + { + ShaderSourceParameterDirection direction = ShaderSourceParameterDirection.Input; + bool directionAssigned = false; + while (m_offset < tokens.Count) + { + BgfxSourceToken qualifier = tokens[m_offset]; + if (qualifier.text is "in" or "out" or "inout") + { + if (directionAssigned) + { + Fail("A parameter has more than one direction qualifier.", qualifier); + } + directionAssigned = true; + direction = qualifier.text switch + { + "out" => ShaderSourceParameterDirection.Output, + "inout" => ShaderSourceParameterDirection.InputOutput, + _ => ShaderSourceParameterDirection.Input + }; + m_offset++; + } + else if (IsQualifier(qualifier.text)) + { + m_offset++; + } + else + { + break; + } + } + ShaderSourceType type = ReadType(); + BgfxSourceToken name = ReadIdentifier(); + if (type.id == "void") + { + Fail("A parameter cannot have void type.", name); + } + type = ReadArray(type); + if (parameters.Any(parameter => parameter.name == name.text)) + { + Fail("Duplicate public parameter name.", name); + } + parameters.Add(new ShaderSourceParameter(name.text, type, direction)); + } + while (Match(",")); + Require(")"); + return parameters; + } + + private void ReadStructure() + { + Require("struct"); + BgfxSourceToken name = ReadIdentifier(); + Require("{"); + List fields = []; + while (!Match("}")) + { + while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { + m_offset++; + } + ShaderSourceType type = ReadType(); + if (type.id == "void") + { + Fail("A structure field cannot have void type.", name); + } + do + { + BgfxSourceToken field = ReadIdentifier(); + ShaderSourceType fieldType = ReadArray(type); + if (fields.Any(existing => existing.name == field.text)) + { + Fail("Duplicate structure member name.", field); + } + fields.Add(new ShaderSourceField(field.text, fieldType)); + } + while (Match(",")); + Require(";"); + } + Require(";"); + if (fields.Count == 0) + { + Fail("A structure requires at least one field.", name); + } + if (!m_types.TryAdd(name.text, ShaderSourceType.Structure("struct:" + name.text, fields))) + { + Fail($"Type '{name.text}' is already declared.", name); + } + } + + private ShaderSourceType ReadType() + { + BgfxSourceToken token = ReadIdentifier(); + if (m_types.TryGetValue(token.text, out ShaderSourceType? declared)) + { + return declared; + } + string? canonical = token.text switch + { + "void" or "bool" or "int" or "uint" or "float" or "double" => token.text, + "half" => "float16", + "vec2" or "float2" => "float2", + "vec3" or "float3" => "float3", + "vec4" or "float4" => "float4", + "ivec2" or "int2" => "int2", + "ivec3" or "int3" => "int3", + "ivec4" or "int4" => "int4", + "uvec2" or "uint2" => "uint2", + "uvec3" or "uint3" => "uint3", + "uvec4" or "uint4" => "uint4", + "bvec2" or "bool2" => "bool2", + "bvec3" or "bool3" => "bool3", + "bvec4" or "bool4" => "bool4", + "mat2" or "float2x2" => "float2x2", + "mat3" or "float3x3" => "float3x3", + "mat4" or "float4x4" => "float4x4", + "sampler2D" or "BgfxSampler2D" => "sampled-texture2d", + "sampler2DArray" or "BgfxSampler2DArray" => "sampled-texture2d-array", + "sampler3D" or "BgfxSampler3D" => "sampled-texture3d", + "samplerCube" or "BgfxSamplerCube" => "sampled-texture-cube", + _ => null + }; + if (canonical is null) + { + Fail($"Unsupported or undeclared source type '{token.text}'.", token); + } + return ShaderSourceType.Atomic(canonical!); + } + + private ShaderSourceType ReadArray(ShaderSourceType element) + { + List lengths = []; + while (Match("[")) + { + BgfxSourceToken start = Current(); + if (element.id == "void") + { + Fail("An array cannot contain void values.", start); + } + List expression = []; + while (!Match("]")) + { + expression.Add(Next()); + } + long count = EvaluateInteger(expression, start); + if (count <= 0 || count > int.MaxValue) + { + Fail("Function interface arrays require a positive, fixed 32-bit length.", start); + } + lengths.Add((int)count); + } + for (int i = lengths.Count - 1; i >= 0; i--) + { + element = ShaderSourceType.ArrayOf(element, lengths[i]); + } + return element; + } + + private long EvaluateInteger( + List expression, + BgfxSourceToken location + ) { + if (expression.Count == 0) + { + Fail("Expected a fixed integer expression.", location); + } + List values = []; + foreach (BgfxSourceToken token in expression) + { + if (!token.isIdentifier) + { + values.Add(token); + continue; + } + if (!m_constants.TryGetValue(token.text, out long constant)) + { + Fail($"Unresolved array constant '{token.text}'.", token); + } + values.Add(new BgfxSourceToken("(", token.position)); + foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize( + new ShaderSourceFile(token.position.assetPath, constant.ToString(CultureInfo.InvariantCulture)) + )) { + values.Add(literal with { position = token.position }); + } + values.Add(new BgfxSourceToken(")", token.position)); + } + return new BgfxPreprocessorExpression(values).Evaluate(); + } + + private List ReadUntilSemicolon() + { + List result = []; + int braces = 0; + int parentheses = 0; + while (true) + { + BgfxSourceToken token = Next(); + if (token.text == ";" && braces == 0 && parentheses == 0) + { + return result; + } + if (token.text == "{") + { + braces++; + } + if (token.text == "}") + { + braces--; + } + if (token.text == "(") + { + parentheses++; + } + if (token.text == ")") + { + parentheses--; + } + result.Add(token); + } + } + + private List ReadBody() + { + List body = []; + int nesting = 1; + while (nesting != 0) + { + BgfxSourceToken token = Next(); + if (token.text == "{") + { + nesting++; + } + if (token.text == "}") + { + nesting--; + } + body.Add(token); + } + return body; + } + + private void ValidateExplicitInterfaces() + { + foreach ((IReadOnlyList parameters, List body) in m_bodies) + { + var explicitNames = new HashSet(parameters.Select(static value => value.name), StringComparer.Ordinal); + explicitNames.UnionWith(globals); + for (int index = 0; index < body.Count; index++) + { + BgfxSourceToken token = body[index]; + if (index != 0 && body[index - 1].text == ".") + { + continue; + } + if (!explicitNames.Contains(token.text) && IsImplicitStageName(token.text)) + { + Fail( + $"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", + token + ); + } + } + } + } + + private BgfxSourceToken ReadIdentifier() + { + BgfxSourceToken token = Next(); + if (!token.isIdentifier) + { + Fail($"Expected an identifier, found '{token.text}'.", token); + } + return token; + } + + private BgfxSourceToken Current() + { + if (m_offset >= tokens.Count) + { + throw new BgfxSourceSyntaxException( + "Unexpected end of source declaration.", + tokens.Count == 0 + ? new ShaderSourcePosition(request.source.assetPath, 1, 1) + : tokens[^1].position + ); + } + return tokens[m_offset]; + } + + private BgfxSourceToken Next() + { + BgfxSourceToken token = Current(); + m_offset++; + return token; + } + + private bool Peek(string value) => m_offset < tokens.Count && tokens[m_offset].text == value; + + private bool Match(string value) + { + if (!Peek(value)) + { + return false; + } + m_offset++; + return true; + } + + private void Require(string value) + { + if (!Match(value)) + { + Fail($"Expected '{value}'.", Current()); + } + } + + private static bool IsImplicitStageName(string name) + => name.StartsWith("gl_", StringComparison.Ordinal) || name.StartsWith("inno_", StringComparison.Ordinal) + || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) + || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) + || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) + || name.StartsWith("a_color", StringComparison.Ordinal) + || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" + or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" + or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; + + private static bool IsQualifier(string value) => value is "const" or "static" or "inline" or "highp" or "mediump" or "lowp"; + + private static void Fail( + string message, + BgfxSourceToken token + ) => throw new BgfxSourceSyntaxException(message, token.position); +} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs index 4308aa649..e77b4980d 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs @@ -1,29 +1,13 @@ -using System; using System.Collections.Generic; using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; -internal readonly record struct BgfxSourceToken( - string text, - ShaderSourcePosition position -) { - internal bool isIdentifier => text.Length != 0 && (char.IsLetter(text[0]) || text[0] == '_'); -} - -internal sealed class BgfxSourceSyntaxException( - string message, - ShaderSourcePosition position -) : Exception(message) -{ - internal ShaderSourcePosition position { get; } = position; -} - internal static class BgfxSourceLexer { internal static List Tokenize(ShaderSourceFile source) { - var tokens = new List(); + List tokens = []; string text = source.text; int line = 1; int column = 1; @@ -35,48 +19,67 @@ internal static List Tokenize(ShaderSourceFile source) { Advance(); if (offset < text.Length && text[offset] == '\r') + { Advance(); + } if (offset < text.Length && text[offset] == '\n') + { Advance(); + } continue; } if (char.IsWhiteSpace(current)) { if (current == '\n') - tokens.Add(new("\n", new(source.assetPath, line, column))); + { + tokens.Add(new BgfxSourceToken("\n", new ShaderSourcePosition(source.assetPath, line, column))); + } Advance(); continue; } if (current == '/' && offset + 1 < text.Length && text[offset + 1] == '/') { while (offset < text.Length && text[offset] != '\n') + { Advance(); + } continue; } var position = new ShaderSourcePosition(source.assetPath, line, column); if (current == '/' && offset + 1 < text.Length && text[offset + 1] == '*') { - Advance(); Advance(); + Advance(); + Advance(); bool closed = false; while (offset < text.Length) { if (text[offset] == '*' && offset + 1 < text.Length && text[offset + 1] == '/') { - Advance(); Advance(); closed = true; break; + Advance(); + Advance(); + closed = true; + break; } if (text[offset] == '\n') - tokens.Add(new("\n", new(source.assetPath, line, column))); + { + tokens.Add(new BgfxSourceToken("\n", new ShaderSourcePosition(source.assetPath, line, column))); + } Advance(); } if (!closed) + { throw new BgfxSourceSyntaxException("Unterminated block comment.", position); + } continue; } int start = offset; if (char.IsLetter(current) || current == '_') { do - Advance(); while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '_')); + { + Advance(); + } + while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '_')); } else if (char.IsDigit(current) || (current == '.' && offset + 1 < text.Length && char.IsDigit(text[offset + 1]))) { @@ -87,8 +90,11 @@ internal static List Tokenize(ShaderSourceFile source) Advance(); bool exponent = hexadecimal ? previous is 'p' or 'P' : previous is 'e' or 'E'; if (exponent && offset < text.Length && text[offset] is '+' or '-') + { Advance(); - } while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '.')); + } + } + while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '.')); } else if (current is '"' or '\'') { @@ -104,12 +110,18 @@ internal static List Tokenize(ShaderSourceFile source) break; } if (character == '\\' && offset < text.Length) + { Advance(); + } else if (character == '\n') + { throw new BgfxSourceSyntaxException("Unterminated string literal.", position); + } } if (!closed) + { throw new BgfxSourceSyntaxException("Unterminated string literal.", position); + } } else { @@ -119,10 +131,12 @@ internal static List Tokenize(ShaderSourceFile source) char second = text[offset]; Advance(); if (current == second && current is '<' or '>' && offset < text.Length && text[offset] == '=') + { Advance(); + } } } - tokens.Add(new(text[start..offset], position)); + tokens.Add(new BgfxSourceToken(text[start..offset], position)); } return tokens; @@ -134,15 +148,23 @@ void Advance() column = 1; } else + { column++; + } } } private static bool IsPair( char first, char second - ) - => (first, second) is ('&', '&') or ('|', '|') or ('=', '=') or ('!', '=') or ('<', '=') or ('>', '=') - or ('<', '<') or ('>', '>') or ('#', '#') or ('+', '+') or ('-', '-') or ('+', '=') or ('-', '=') - or ('*', '=') or ('/', '=') or ('&', '=') or ('|', '=') or ('^', '=') or ('%', '='); + ) => (first, second) is ('&', '&') or ('|', '|') or ('=', '=') or ('!', '=') or ('<', '=') or ('>', '=') + or ('<', '<') or ('>', '>') or ('#', '#') or ('+', '+') or ('-', '-') or ('+', '=') or ('-', '=') + or ('*', '=') or ('/', '=') or ('&', '=') or ('|', '=') or ('^', '=') or ('%', '='); +} + +internal readonly record struct BgfxSourceToken( + string text, + ShaderSourcePosition position +) { + internal bool isIdentifier => text.Length != 0 && (char.IsLetter(text[0]) || text[0] == '_'); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs index e8acfc1ae..144e400fb 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs @@ -11,7 +11,7 @@ namespace Inno.Build.Toolchains.Bgfx.Tools; internal sealed class BgfxSourcePreprocessor(ShaderSourceRequest request) { private const int C_MAX_DEPTH = 128; - private const int C_MAX_TOKENS = 1000000; + private const int C_MAX_TOKENS = 1_000_000; private readonly Dictionary m_macros = new(StringComparer.Ordinal); private readonly HashSet m_dependencies = new(StringComparer.Ordinal); private readonly HashSet m_once = new(StringComparer.Ordinal); @@ -23,8 +23,8 @@ internal List Process() { foreach ((string name, string value) in request.defines) { - List replacement = BgfxSourceLexer.Tokenize(new(request.source.assetPath, value)); - m_macros.Add(name, new(null, replacement.Where(static token => token.text != "\n").ToArray())); + List replacement = BgfxSourceLexer.Tokenize(new ShaderSourceFile(request.source.assetPath, value)); + m_macros.Add(name, new Macro(null, replacement.Where(static token => token.text != "\n").ToArray())); } return ProcessFile(request.source, 0); } @@ -34,33 +34,50 @@ private List ProcessFile( int depth ) { if (m_once.Contains(source.assetPath)) + { return []; + } if (depth >= C_MAX_DEPTH) - throw new BgfxSourceSyntaxException("Shader include depth exceeded; check for an unguarded include cycle.", new(source.assetPath, 1, 1)); + { + throw new BgfxSourceSyntaxException( + "Shader include depth exceeded; check for an unguarded include cycle.", + new ShaderSourcePosition(source.assetPath, 1, 1) + ); + } List input = BgfxSourceLexer.Tokenize(source); - var output = new List(); - var pending = new List(); + List output = []; + List pending = []; var conditions = new Stack(); bool active = true; for (int index = 0; index < input.Count;) { int start = index; while (index < input.Count && input[index].text != "\n") + { index++; + } List line = input.GetRange(start, index - start); if (index < input.Count) + { index++; + } if (line.Count == 0) + { continue; + } if (line[0].text != "#") { if (active) + { pending.AddRange(line); + } continue; } Flush(); if (line.Count < 2) + { continue; + } BgfxSourceToken directive = line[1]; List arguments = line.GetRange(2, line.Count - 2); switch (directive.text) @@ -70,17 +87,22 @@ int depth case "ifndef": { if (directive.text != "if" && (arguments.Count != 1 || !arguments[0].isIdentifier)) + { Fail("Expected one macro name after conditional directive.", directive); - bool selected = active && (directive.text == "if" ? Evaluate(arguments, directive) : - m_macros.ContainsKey(arguments[0].text) == (directive.text == "ifdef")); - conditions.Push(new(active, selected, false)); + } + bool selected = active && (directive.text == "if" + ? Evaluate(arguments, directive) + : m_macros.ContainsKey(arguments[0].text) == (directive.text == "ifdef")); + conditions.Push(new Conditional(active, selected, false)); active = selected; break; } case "elif": { if (conditions.Count == 0 || conditions.Peek().hasElse) + { Fail("Unexpected #elif.", directive); + } Conditional branch = conditions.Pop(); active = branch.parentActive && !branch.taken && Evaluate(arguments, directive); conditions.Push(branch with { taken = branch.taken || active }); @@ -89,7 +111,9 @@ int depth case "else": { if (arguments.Count != 0 || conditions.Count == 0 || conditions.Peek().hasElse) + { Fail("Unexpected #else.", directive); + } Conditional branch = conditions.Pop(); active = branch.parentActive && !branch.taken; conditions.Push(branch with { taken = true, hasElse = true }); @@ -97,12 +121,16 @@ int depth } case "endif": if (arguments.Count != 0 || conditions.Count == 0) + { Fail("Unexpected #endif.", directive); + } active = conditions.Pop().parentActive; break; default: if (active) + { ApplyDirective(); + } break; } @@ -110,10 +138,14 @@ void ApplyDirective() { switch (directive.text) { - case "define": Define(arguments, directive); break; + case "define": + Define(arguments, directive); + break; case "undef": if (arguments.Count != 1 || !arguments[0].isIdentifier) + { Fail("Expected one macro name after #undef.", directive); + } m_macros.Remove(arguments[0].text); break; case "include": @@ -121,9 +153,13 @@ void ApplyDirective() List expanded = Expand(arguments, [], 0); string include; if (expanded.Count == 1 && expanded[0].text.StartsWith('"') && expanded[0].text.EndsWith('"')) + { include = expanded[0].text[1..^1]; + } else if (expanded.Count > 2 && expanded[0].text == "<" && expanded[^1].text == ">") + { include = string.Concat(expanded.Skip(1).Take(expanded.Count - 2).Select(static token => token.text)); + } else { Fail("Expected a quoted or bracketed include path.", directive); @@ -138,7 +174,10 @@ void ApplyDirective() failure is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException && RetirementPendingException.Find(failure) is null) { - throw new BgfxSourceSyntaxException($"Cannot resolve include '{include}': {failure.Message}", directive.position); + throw new BgfxSourceSyntaxException( + $"Cannot resolve include '{include}': {failure.Message}", + directive.position + ); } ArgumentNullException.ThrowIfNull(dependency); ArgumentException.ThrowIfNullOrWhiteSpace(dependency.assetPath); @@ -149,24 +188,36 @@ failure is IOException or UnauthorizedAccessException or InvalidOperationExcepti } case "pragma": if (arguments.Count == 1 && arguments[0].text == "once") + { m_once.Add(source.assetPath); + } else + { Fail("Unsupported module pragma; stage configuration belongs to the graph target.", directive); + } + break; + case "error": + Fail(string.Join(" ", arguments.Select(static token => token.text)), directive); + break; + default: + Fail($"Unsupported module preprocessor directive '#{directive.text}'.", directive); break; - case "error": Fail(string.Join(" ", arguments.Select(static token => token.text)), directive); break; - default: Fail($"Unsupported module preprocessor directive '#{directive.text}'.", directive); break; } } } Flush(); if (conditions.Count != 0) - throw new BgfxSourceSyntaxException("Unterminated preprocessor conditional.", new(source.assetPath, 1, 1)); + { + throw new BgfxSourceSyntaxException("Unterminated preprocessor conditional.", new ShaderSourcePosition(source.assetPath, 1, 1)); + } return output; void Flush() { if (pending.Count == 0) + { return; + } output.AddRange(Expand(pending, [], 0)); pending.Clear(); } @@ -177,8 +228,10 @@ private bool Evaluate( BgfxSourceToken directive ) { if (input.Count == 0) + { Fail("Expected a preprocessor expression.", directive); - var replaced = new List(); + } + List replaced = []; for (int i = 0; i < input.Count; i++) { BgfxSourceToken token = input[i]; @@ -189,17 +242,25 @@ BgfxSourceToken directive } bool parenthesized = i + 1 < input.Count && input[i + 1].text == "("; if (parenthesized) + { i++; + } if (++i >= input.Count || !input[i].isIdentifier) + { Fail("Expected a macro identifier after defined.", token); + } bool defined = m_macros.ContainsKey(input[i].text); if (parenthesized && (++i >= input.Count || input[i].text != ")")) + { Fail("Expected ')' after defined.", token); - replaced.Add(new(defined ? "1" : "0", token.position)); + } + replaced.Add(new BgfxSourceToken(defined ? "1" : "0", token.position)); } List expanded = Expand(replaced, [], 0); if (expanded.Count == 0) + { Fail("Preprocessor expression expanded to no tokens.", directive); + } return new BgfxPreprocessorExpression(expanded).Evaluate() != 0; } @@ -208,43 +269,59 @@ private void Define( BgfxSourceToken directive ) { if (arguments.Count == 0 || !arguments[0].isIdentifier) + { Fail("Expected a macro identifier after #define.", directive); + } BgfxSourceToken name = arguments[0]; int offset = 1; string[]? parameters = null; - if (offset < arguments.Count && arguments[offset].text == "(" && - arguments[offset].position.line == name.position.line && - arguments[offset].position.column == name.position.column + name.text.Length) - { + if (offset < arguments.Count && arguments[offset].text == "(" + && arguments[offset].position.line == name.position.line + && arguments[offset].position.column == name.position.column + name.text.Length + ) { offset++; - var names = new List(); + List names = []; while (offset < arguments.Count && arguments[offset].text != ")") { if (!arguments[offset].isIdentifier) + { Fail("Expected a named macro parameter.", arguments[offset]); + } string parameter = arguments[offset++].text; if (names.Contains(parameter, StringComparer.Ordinal)) + { Fail("Duplicate macro parameter.", name); + } names.Add(parameter); if (offset < arguments.Count && arguments[offset].text == ",") { offset++; if (offset >= arguments.Count || arguments[offset].text == ")") + { Fail("A macro parameter is missing after ','.", name); + } } else if (offset < arguments.Count && arguments[offset].text != ")") + { Fail("Expected ',' or ')' in macro declaration.", arguments[offset]); + } } if (offset >= arguments.Count) + { Fail("Unterminated macro parameter list.", name); + } offset++; parameters = names.ToArray(); } var macro = new Macro(parameters, arguments.Skip(offset).ToArray()); - if (m_macros.TryGetValue(name.text, out Macro? previous) && - (!SameParameters(previous.parameters, parameters) || - !previous.replacement.Select(static token => token.text).SequenceEqual(macro.replacement.Select(static token => token.text)))) + if (m_macros.TryGetValue(name.text, out Macro? previous) + && (!SameParameters(previous.parameters, parameters) + || !previous.replacement + .Select(static token => token.text) + .SequenceEqual(macro.replacement.Select(static token => token.text))) + ) { Fail($"Conflicting macro definition '{name.text}'.", name); + } m_macros[name.text] = macro; } @@ -254,23 +331,27 @@ private List Expand( int depth ) { if (depth >= C_MAX_DEPTH && tokens.Count != 0) + { Fail("Shader macro expansion exceeded its depth budget.", tokens[0]); - var pending = tokens.Select(token => new ExpansionToken(token, disabled)).ToList(); - var result = new List(); + } + List pending = tokens.Select(token => new ExpansionToken(token, disabled)).ToList(); + List result = []; for (int i = 0; i < pending.Count; i++) { ExpansionToken current = pending[i]; BgfxSourceToken token = current.token; if (++m_emittedTokens > C_MAX_TOKENS) + { Fail("Shader source expansion exceeded its token budget.", token); + } if (token.text == "__LINE__") { - result.Add(new(token.position.line.ToString(CultureInfo.InvariantCulture), token.position)); + result.Add(new BgfxSourceToken(token.position.line.ToString(CultureInfo.InvariantCulture), token.position)); continue; } if (token.text == "__FILE__") { - result.Add(new('"' + token.position.assetPath + '"', token.position)); + result.Add(new BgfxSourceToken('"' + token.position.assetPath + '"', token.position)); continue; } if (!m_macros.TryGetValue(token.text, out Macro? macro) || current.disabled.Contains(token.text)) @@ -288,14 +369,16 @@ int depth continue; } i += 2; - var arguments = new List>(); - var argument = new List(); + List> arguments = []; + List argument = []; int nesting = 0; for (; i < pending.Count; i++) { BgfxSourceToken next = pending[i].token; if (next.text == ")" && nesting == 0) + { break; + } if (next.text == "," && nesting == 0) { arguments.Add(argument); @@ -303,26 +386,40 @@ int depth continue; } if (next.text == "(") + { nesting++; + } if (next.text == ")") + { nesting--; + } argument.Add(next); } if (i >= pending.Count) + { Fail("Unterminated function-like macro invocation.", token); + } if (argument.Count != 0 || arguments.Count != 0 || macro.parameters.Length != 0) + { arguments.Add(argument); + } if (arguments.Count != macro.parameters.Length) + { Fail($"Macro '{token.text}' has an incorrect argument count.", token); + } replacement = Substitute(macro, arguments, token, current.disabled, depth); } else + { replacement = Paste(replacement, token); + } // Rescan replacement tokens together with the following input. An alias may expand to // a function-like macro whose '(' was not part of the alias replacement list. var nestedDisabled = new HashSet(current.disabled, StringComparer.Ordinal) { token.text }; if (nestedDisabled.Count >= C_MAX_DEPTH) + { Fail("Shader macro expansion exceeded its depth budget.", token); + } pending.RemoveRange(start, i - start + 1); pending.InsertRange(start, replacement.Select(value => new ExpansionToken(value, nestedDisabled))); i = start - 1; @@ -337,7 +434,7 @@ private List Substitute( HashSet disabled, int depth ) { - var substituted = new List(); + List substituted = []; for (int index = 0; index < macro.replacement.Length; index++) { BgfxSourceToken item = macro.replacement[index]; @@ -345,10 +442,13 @@ int depth { int parameter = Array.IndexOf(macro.parameters!, macro.replacement[++index].text); if (parameter < 0) + { Fail("Stringification requires a macro parameter.", item); + } string literal = string.Join(" ", arguments[parameter].Select(static value => value.text)) - .Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal); - substituted.Add(new('"' + literal + '"', invocation.position)); + .Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal); + substituted.Add(new BgfxSourceToken('"' + literal + '"', invocation.position)); continue; } int parameterIndex = Array.IndexOf(macro.parameters!, item.text); @@ -357,12 +457,16 @@ int depth substituted.Add(item); continue; } - bool pasted = index > 0 && macro.replacement[index - 1].text == "##" || - index + 1 < macro.replacement.Length && macro.replacement[index + 1].text == "##"; + bool pasted = index > 0 && macro.replacement[index - 1].text == "##" + || index + 1 < macro.replacement.Length && macro.replacement[index + 1].text == "##"; if (pasted && arguments[parameterIndex].Count == 0) - substituted.Add(new(string.Empty, invocation.position)); + { + substituted.Add(new BgfxSourceToken(string.Empty, invocation.position)); + } else + { substituted.AddRange(pasted ? arguments[parameterIndex] : Expand(arguments[parameterIndex], disabled, depth + 1)); + } } return Paste(substituted, invocation); } @@ -371,7 +475,7 @@ private static List Paste( List substituted, BgfxSourceToken invocation ) { - var output = new List(); + List output = []; for (int i = 0; i < substituted.Count; i++) { if (substituted[i].text != "##") @@ -380,11 +484,15 @@ BgfxSourceToken invocation continue; } if (output.Count == 0 || i + 1 >= substituted.Count) + { Fail("Token pasting requires two nonempty operands.", invocation); + } string combined = output[^1].text + substituted[++i].text; - List joined = BgfxSourceLexer.Tokenize(new(invocation.position.assetPath, combined)); + List joined = BgfxSourceLexer.Tokenize(new ShaderSourceFile(invocation.position.assetPath, combined)); if (combined.Length > 0 && joined.Count != 1) + { Fail("Token pasting did not produce one preprocessing token.", invocation); + } output[^1] = new(combined, invocation.position); } output.RemoveAll(static token => token.text.Length == 0); @@ -394,8 +502,7 @@ BgfxSourceToken invocation private static bool SameParameters( string[]? first, string[]? second - ) - => first is null ? second is null : second is not null && first.SequenceEqual(second); + ) => first is null ? second is null : second is not null && first.SequenceEqual(second); private static void Fail( string message, @@ -406,10 +513,12 @@ private sealed record Macro( string[]? parameters, BgfxSourceToken[] replacement ); + private sealed record ExpansionToken( BgfxSourceToken token, HashSet disabled ); + private readonly record struct Conditional( bool parentActive, bool taken, diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs new file mode 100644 index 000000000..9e654a655 --- /dev/null +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs @@ -0,0 +1,12 @@ +using System; +using Inno.Rendering.Shaders; + +namespace Inno.Build.Toolchains.Bgfx.Tools; + +internal sealed class BgfxSourceSyntaxException( + string message, + ShaderSourcePosition position +) : Exception(message) +{ + internal ShaderSourcePosition position { get; } = position; +} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs index 43588096e..11eb6689b 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -19,16 +20,25 @@ CancellationToken cancellationToken ) { context.RequireBindings(request.component); string definition = Path.Combine(request.component.GetToolchainRoot(context.engineRoot), "Native", "SharedBindings"); - string build = await NativeCMakeExecutor.BuildAsync(context, request.component, definition, - "inno_bgfx_binding", request.bindingCmakeArguments, cancellationToken).ConfigureAwait(false); - string archive = NativeCMakeExecutor.FindOutput(context, build, - "inno_bgfx_binding" + context.RequireToolchain().linkPlan.GetFileExtension(NativeLibraryKind.Static)); - var linking = profile.CreateBindingLinkSettings(archive); + string build = await NativeCMakeExecutor.BuildAsync( + context, + request.component, + definition, + "inno_bgfx_binding", + request.bindingCmakeArguments, + cancellationToken + ).ConfigureAwait(false); + string archive = NativeCMakeExecutor.FindOutput( + context, + build, + "inno_bgfx_binding" + context.RequireToolchain().linkPlan.GetFileExtension(NativeLibraryKind.Static) + ); + (string reference, IReadOnlyList arguments) linking = profile.CreateBindingLinkSettings(archive); string script = Path.Combine(context.GetNativeBuildRoot(request.component), "BindingProject.lua"); string text = "dofile(" + Literal(Path.Combine(source, "scripts", "genie.lua")) + ")\n" - + "project \"bgfx-shared-lib\"\nconfiguration {}\n" - + "links { " + Literal(linking.reference) + " }\n" - + "linkoptions { " + string.Join(", ", linking.arguments.Select(Literal)) + " }\n"; + + "project \"bgfx-shared-lib\"\nconfiguration {}\n" + + "links { " + Literal(linking.reference) + " }\n" + + "linkoptions { " + string.Join(", ", linking.arguments.Select(Literal)) + " }\n"; AtomicFile.WriteAllBytes(script, Encoding.UTF8.GetBytes(text)); return script; } @@ -36,11 +46,15 @@ CancellationToken cancellationToken private static string Literal(string value) { if (value.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new InvalidDataException("A GENie input path cannot contain control characters."); + } string portable = value.Replace('\\', '/'); string delimiter = "="; while (portable.Contains("]" + delimiter + "]", StringComparison.Ordinal)) + { delimiter += "="; + } return "[" + delimiter + "[" + portable + "]" + delimiter + "]"; } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs index a5dec743e..03f7da023 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs @@ -5,25 +5,30 @@ internal static class BgfxBuildConstants /// /// The output product dir name value used as part of this type's public representation. /// - public const string OUTPUT_PRODUCT_DIR_NAME = "bgfx"; + public const string C_OUTPUT_PRODUCT_DIR_NAME = "bgfx"; + /// /// The output dll name value used as part of this type's public representation. /// - public const string OUTPUT_DLL_NAME = "bgfx-shared-lib"; + public const string C_OUTPUT_DLL_NAME = "bgfx-shared-lib"; + /// /// The bgfx dir name value used as part of this type's public representation. /// - public const string BGFX_DIR_NAME = "bgfx"; + public const string C_BGFX_DIR_NAME = "bgfx"; + /// /// The bx dir name value used as part of this type's public representation. /// - public const string BX_DIR_NAME = "bx"; + public const string C_BX_DIR_NAME = "bx"; + /// /// The bimg dir name value used as part of this type's public representation. /// - public const string BIMG_DIR_NAME = "bimg"; + public const string C_BIMG_DIR_NAME = "bimg"; + /// /// The build dir name value used as part of this type's public representation. /// - public const string BUILD_DIR_NAME = ".build"; + public const string C_BUILD_DIR_NAME = ".build"; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs index 50b520c2b..79432a64f 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs @@ -32,7 +32,9 @@ IEnumerable arguments ArgumentNullException.ThrowIfNull(arguments); string[] snapshot = arguments.ToArray(); if (snapshot.Any(static value => value is null)) + { throw new ArgumentException("Invocation arguments cannot be null.", nameof(arguments)); + } this.tool = tool; this.arguments = Array.AsReadOnly(snapshot); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs index 792f439d8..f8b69aedf 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs @@ -14,45 +14,64 @@ bool includeTools ArgumentNullException.ThrowIfNull(operation); NativeToolchainSelection initial = operation.RequireToolchain(); ArgumentNullException.ThrowIfNull(profile); - if (profile.targetId != initial.targetId) + if (profile.targetID != initial.targetID) + { throw new ArgumentException("The BGFX profile does not match the frozen toolchain target.", nameof(profile)); - context = operation.WithToolchain(profile.SelectTools(operation, includeTools)); - component = includeTools ? BgfxToolsBuild.componentDescriptor : BgfxNativeBuild.componentDescriptor; + } + this.context = operation.WithToolchain(profile.SelectTools(operation, includeTools)); + this.component = includeTools ? BgfxToolsBuild.componentDescriptor : BgfxNativeBuild.componentDescriptor; NativeComponentBuildOptions options = context.RequireComponentOptions(component); if (options.libraryKind != NativeLibraryKind.Shared || options.cmakeArguments.Count != 0) + { throw new NotSupportedException("The standalone graphics recipe requires shared linkage and its explicit generation profile."); - artifactToken = profile.artifactPathToken; + } + this.artifactToken = profile.artifactPathToken; ArgumentException.ThrowIfNullOrWhiteSpace(artifactToken); string[] arguments = profile.generatorArguments?.ToArray() - ?? throw new ArgumentException("The BGFX profile has no generator arguments.", nameof(profile)); + ?? throw new ArgumentException("The BGFX profile has no generator arguments.", nameof(profile)); if (arguments.Length == 0 || arguments.Any(static value => value is null)) + { throw new ArgumentException("The BGFX profile requires assigned generator arguments.", nameof(profile)); - generatorArguments = includeTools ? ["--with-shared-lib", "--with-tools", .. arguments] - : ["--with-shared-lib", .. arguments]; - bindingCmakeArguments = includeTools ? [] : profile.bindingCmakeArguments.ToArray(); - invocation = profile.CreateBuildInvocation(context, includeTools) - ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); + } + this.generatorArguments = includeTools + ? ["--with-shared-lib", "--with-tools", .. arguments] + : ["--with-shared-lib", .. arguments]; + this.bindingCmakeArguments = includeTools ? [] : profile.bindingCmakeArguments.ToArray(); + this.invocation = profile.CreateBuildInvocation(context, includeTools) + ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); NativeToolchainSelection tools = context.RequireToolchain(); - compiler = tools.ResolveExecutable(invocation.tool); - externalDirectory = Path.Combine(context.engineRoot, "extern"); + this.compiler = tools.ResolveExecutable(invocation.tool); + this.externalDirectory = Path.Combine(context.engineRoot, "extern"); string bgfx = Path.Combine(externalDirectory, "bgfx"); string bx = Path.Combine(externalDirectory, "bx"); string bimg = Path.Combine(externalDirectory, "bimg"); BgfxBuildUtils.ValidateSubmodules(bgfx, bx, bimg); - genie = tools.ResolveExecutable("genie"); - string[] declarations = ["artifact=" + artifactToken, + this.genie = tools.ResolveExecutable("genie"); + string[] declarations = + [ + "artifact=" + artifactToken, .. generatorArguments.Select(static value => "generate=" + value), .. bindingCmakeArguments.Select(static value => "bridge=" + value), - "compiler=" + compiler, .. invocation.arguments.Select(static value => "compile=" + value)]; + "compiler=" + compiler, + .. invocation.arguments.Select(static value => "compile=" + value) + ]; string implementation = component.GetToolchainRoot(context.engineRoot); - recipe = NativeBuildRecipe.CreateForComponent(context, component, - includeTools ? "bgfx-tools" : "bgfx", tools.targetId, - new[] { bgfx, bx, bimg, genie }.Concat(includeTools ? [] : - [Path.Combine(implementation, "Native", "SharedBindings", "CMakeLists.txt")]), declarations, + this.recipe = NativeBuildRecipe.CreateForComponent( + context, + component, + includeTools ? "bgfx-tools" : "bgfx", + tools.targetID, + new[] { bgfx, bx, bimg, genie }.Concat( + includeTools + ? [] + : [Path.Combine(implementation, "Native", "SharedBindings", "CMakeLists.txt")] + ), + declarations, new[] { "BgfxBuildConstants.cs", "BgfxBuildInvocation.cs", "BgfxBuildRequest.cs", "BgfxBuildSession.cs", "BgfxBuildUtils.cs", "BgfxNativeBuild.cs", "BgfxNativeBuildProfile.cs", "BgfxToolsBuild.cs" } .Concat(includeTools ? [] : ["BgfxBindingProject.cs"]) - .Select(file => Path.Combine(implementation, file))); + .Select(file => Path.Combine(implementation, file)) + ); } internal NativeBuildContext context { get; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs index 7c093fb59..dec72545a 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs @@ -22,8 +22,13 @@ CancellationToken cancellationToken @scoped, output, token - ) => { - NativeCMakeSource snapshot = await NativeCMakeExecutor.PrepareSourceAsync(scoped, request.component, token).ConfigureAwait(false); + ) => + { + NativeCMakeSource snapshot = await NativeCMakeExecutor.PrepareSourceAsync( + scoped, + request.component, + token + ).ConfigureAwait(false); string source = snapshot.ResolvePath(Path.Combine(request.externalDirectory, "bgfx")); string[] generatorArguments = request.generatorArguments; if (!includeTools) @@ -32,20 +37,46 @@ CancellationToken cancellationToken generatorArguments = ["--file=" + script, .. generatorArguments]; } await ToolchainEnvironment.RunAsync(scoped, request.genie, generatorArguments, source, token).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(scoped, request.compiler, request.invocation.arguments, source, token).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + scoped, + request.compiler, + request.invocation.arguments, + source, + token + ).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (includeTools) + { CopyTools(source, output, request.artifactToken, scoped); + } else - BuildArtifactCopier.CopyArtifacts(source, output, scoped.configuration, - new(".build", ["bgfx-shared-lib"], [scoped.RequireToolchain().sharedLibraryExtension], - [request.artifactToken], ToolchainEnvironment.NormalizeOutputName)); - }, cancellationToken, describeOutputs: ( + { + BuildArtifactCopier.CopyArtifacts( + source, + output, + scoped.configuration, + new BuildArtifactOptions( + ".build", + ["bgfx-shared-lib"], + [scoped.RequireToolchain().sharedLibraryExtension], + [request.artifactToken], + ToolchainEnvironment.NormalizeOutputName + ) + ); + } + }, + describeOutputs: ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories) - .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, - includeTools ? NativeArtifactRole.SupportFile : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + .Select(file => new NativeArtifact( + Path.GetRelativePath(output, file), + file, + includeTools ? NativeArtifactRole.SupportFile : NativeArtifactRole.SharedLibrary + )) + .ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } private static void CopyTools( @@ -61,17 +92,26 @@ NativeBuildContext context foreach (string name in new[] { "shaderc", "texturec", "geometryc", "geometryv", "texturev" }) { string[] candidates = Directory.EnumerateFiles(build, name + suffix + extension, SearchOption.AllDirectories) - .Where(file => file.Replace('\\', '/').Contains(artifactToken, StringComparison.Ordinal)).ToArray(); + .Where(file => file.Replace('\\', '/').Contains(artifactToken, StringComparison.Ordinal)) + .ToArray(); if (candidates.Length != 1) - throw new FileNotFoundException($"Expected one '{name}' tool for {context.RequireToolchain().targetId}/{configuration}; found {candidates.Length}."); + { + throw new FileNotFoundException( + $"Expected one '{name}' tool for {context.RequireToolchain().targetID}/{configuration}; found {candidates.Length}." + ); + } string destination = Path.Combine(output, name + extension); File.Copy(candidates[0], destination); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(candidates[0])); + } } string includes = Path.Combine(output, "includes"); Directory.CreateDirectory(includes); foreach (string name in new[] { "bgfx_shader.sh", "bgfx_compute.sh" }) + { File.Copy(Path.Combine(source, "src", name), Path.Combine(includes, name)); + } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs index 81efe79f3..320a960b4 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs @@ -24,13 +24,15 @@ string bimgDir if (!Directory.Exists(bgfxDir)) { throw new DirectoryNotFoundException( - $"bgfx submodule not found at {bgfxDir}. Please initialize submodules before running this tool."); + $"bgfx submodule not found at {bgfxDir}. Please initialize submodules before running this tool." + ); } if (!Directory.Exists(bxDir) || !Directory.Exists(bimgDir)) { throw new DirectoryNotFoundException( - $"bx/bimg submodules not found next to bgfx. Expected {bxDir} and {bimgDir}."); + $"bx/bimg submodules not found next to bgfx. Expected {bxDir} and {bimgDir}." + ); } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs index 5e04e1438..f40cbbad2 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs @@ -19,8 +19,10 @@ public static class BgfxNativeBuild new NativeStaticBuildDefinition( "backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/Native/StaticLibraries.cmake", ["extern/bgfx", "extern/bx", "extern/bimg"], - ["bgfxRelease", "bxRelease", "bimgRelease", "bimg_decodeRelease"]), - bindingDefinition: "backends/Bgfx/native/Inno.Native.Bgfx/Bindings/bindings.props"); + ["bgfxRelease", "bxRelease", "bimgRelease", "bimg_decodeRelease"] + ), + bindingDefinition: "backends/Bgfx/native/Inno.Native.Bgfx/Bindings/bindings.props" + ); /// /// Builds and installs graphics artifacts using explicit platform-owned SDK configuration. @@ -28,12 +30,6 @@ public static class BgfxNativeBuild /// /// The checkout and configuration whose sources and outputs belong to this operation. /// - /// - /// The configuration is not debug or release. - /// - /// - /// A native build process fails. - /// /// /// The platform-owned project generation, SDK invocation and output selection. /// @@ -43,6 +39,12 @@ public static class BgfxNativeBuild /// /// The validated product with an exact graphics library or offline-tool output closure. /// + /// + /// The configuration is not debug or release. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuildProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuildProfile.cs index db2f8352f..f6df8cc79 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuildProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuildProfile.cs @@ -8,27 +8,10 @@ namespace Inno.Build.Toolchains.Bgfx; /// public abstract class BgfxNativeBuildProfile { - /// - /// Adds the integration's explicit generator executable and its configuration inputs before preparation. - /// - /// - /// The requested target, checkout and already selected platform SDK. - /// - /// - /// Whether this request builds offline tools, which do not compile a runtime binding bridge. - /// - /// - /// A frozen selection declaring the generator and all existing SDK commands. - /// - public abstract NativeToolchainSelection SelectTools( - NativeBuildContext context, - bool includeTools - ); - /// /// Gets the exact native target accepted by this configuration. /// - public abstract string targetId { get; } + public abstract string targetID { get; } /// /// Gets ordered vendor project-generation arguments, excluding shared component options. @@ -46,6 +29,23 @@ bool includeTools /// public abstract IReadOnlyList bindingCmakeArguments { get; } + /// + /// Adds the integration's explicit generator executable and its configuration inputs before preparation. + /// + /// + /// The requested target, checkout and already selected platform SDK. + /// + /// + /// Whether this request builds offline tools, which do not compile a runtime binding bridge. + /// + /// + /// A frozen selection declaring the generator and all existing SDK commands. + /// + public abstract NativeToolchainSelection SelectTools( + NativeBuildContext context, + bool includeTools + ); + /// /// Formats bridge dependency and retention requirements for the platform's GENie generator. /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs index 5e64d75fc..71cbe3463 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs @@ -15,7 +15,8 @@ public static class BgfxToolsBuild public static NativeComponentDescriptor componentDescriptor { get; } = new( "bgfx-tools", BgfxNativeBuild.componentDescriptor.nativeProject, - BgfxNativeBuild.componentDescriptor.toolchainProject); + BgfxNativeBuild.componentDescriptor.toolchainProject + ); /// /// Builds and installs graphics artifacts using explicit platform-owned SDK configuration. @@ -23,12 +24,6 @@ public static class BgfxToolsBuild /// /// The checkout and configuration whose sources and outputs belong to this operation. /// - /// - /// The configuration is not debug or release. - /// - /// - /// A native build process fails. - /// /// /// The platform-owned project generation, SDK invocation and output selection. /// @@ -38,6 +33,12 @@ public static class BgfxToolsBuild /// /// The validated product with an exact graphics library or offline-tool output closure. /// + /// + /// The configuration is not debug or release. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// diff --git a/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs b/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs index 0ea70134f..73b5e66f6 100644 --- a/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs +++ b/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs @@ -8,9 +8,9 @@ namespace Inno.Native.Bgfx; public static unsafe partial class bgfx { #if DEBUG - internal const string LibName = "bgfx-shared-lib-debug"; + internal const string C_LIB_NAME = "bgfx-shared-lib-debug"; #else - internal const string LibName = "bgfx-shared-lib-release"; + internal const string C_LIB_NAME = "bgfx-shared-lib-release"; #endif static bgfx() @@ -20,7 +20,7 @@ static bgfx() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs new file mode 100644 index 000000000..56c8a9609 --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs @@ -0,0 +1,10 @@ +namespace Inno.Adapter.Rendering.Bgfx; + +internal enum BgfxBufferKind +{ + Vertex, + Index, + DynamicVertex, + DynamicIndex, + Indirect +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs similarity index 54% rename from backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs rename to backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs index 406ff73bd..f46ad024e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs @@ -1,19 +1,8 @@ -using System; -using System.Collections.Generic; using Inno.Native.Bgfx; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -internal enum BgfxBufferKind -{ - Vertex, - Index, - DynamicVertex, - DynamicIndex, - Indirect -} - internal sealed class BgfxBufferResource { private BgfxBufferResource( @@ -34,18 +23,22 @@ ushort nativeIndex /// Gets the backend-neutral descriptor used to validate and recreate this resource. /// public RenderBufferDescriptor descriptor { get; } + /// /// Gets the optional vertex layout required by this resource or pipeline. /// public RenderVertexLayout? vertexLayout { get; } + /// /// Gets the element width used by this index buffer. /// public RenderIndexFormat indexFormat { get; } + /// /// Gets the operation kind that determines how this value is interpreted. /// public BgfxBufferKind kind { get; } + /// /// Gets the BGFX dynamic-buffer index used by deferred destruction. /// @@ -70,8 +63,7 @@ public static BgfxBufferResource FromVertex( RenderBufferDescriptor descriptor, RenderVertexLayout? layout, bgfx.VertexBufferHandle handle - ) - => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.Vertex, handle.idx); + ) => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.Vertex, handle.idx); /// /// Creates the target representation from the supplied index value. @@ -92,8 +84,7 @@ public static BgfxBufferResource FromIndex( RenderBufferDescriptor descriptor, RenderIndexFormat format, bgfx.IndexBufferHandle handle - ) - => new(descriptor, null, format, BgfxBufferKind.Index, handle.idx); + ) => new(descriptor, null, format, BgfxBufferKind.Index, handle.idx); /// /// Creates the target representation from the supplied dynamic vertex value. @@ -114,8 +105,7 @@ public static BgfxBufferResource FromDynamicVertex( RenderBufferDescriptor descriptor, RenderVertexLayout? layout, bgfx.DynamicVertexBufferHandle handle - ) - => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.DynamicVertex, handle.idx); + ) => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.DynamicVertex, handle.idx); /// /// Creates the target representation from the supplied dynamic index value. @@ -136,8 +126,7 @@ public static BgfxBufferResource FromDynamicIndex( RenderBufferDescriptor descriptor, RenderIndexFormat format, bgfx.DynamicIndexBufferHandle handle - ) - => new(descriptor, null, format, BgfxBufferKind.DynamicIndex, handle.idx); + ) => new(descriptor, null, format, BgfxBufferKind.DynamicIndex, handle.idx); /// /// Creates the target representation from the supplied indirect value. @@ -154,100 +143,5 @@ bgfx.DynamicIndexBufferHandle handle public static BgfxBufferResource FromIndirect( RenderBufferDescriptor descriptor, bgfx.IndirectBufferHandle handle - ) - => new(descriptor, null, RenderIndexFormat.UInt32, BgfxBufferKind.Indirect, handle.idx); -} - -internal sealed class BgfxShaderBindingResource -{ - /// - /// Creates a validated bgfx shader binding resource instance. - /// - /// - /// The descriptor consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The uniform consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. - /// - public BgfxShaderBindingResource( - RenderShaderBindingDescriptor descriptor, - bgfx.UniformHandle uniform - ) { - this.descriptor = descriptor; - this.uniform = uniform; - } - - /// - /// Gets the backend-neutral descriptor used to validate and recreate this resource. - /// - public RenderShaderBindingDescriptor descriptor { get; } - /// - /// Gets the BGFX uniform handle backing this shader binding. - /// - public bgfx.UniformHandle uniform { get; } -} - -internal sealed class BgfxPipelineResource -{ - /// - /// Creates a validated bgfx pipeline resource instance. - /// - /// - /// The program consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The bindings consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The vertex layout consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The vertex layout handle consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The raster state consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// Whether compute behavior is enabled while bgfx pipeline resource executes. - /// - public BgfxPipelineResource( - bgfx.ProgramHandle program, - IReadOnlyDictionary bindings, - RenderVertexLayout? vertexLayout, - bgfx.VertexLayoutHandle vertexLayoutHandle, - RenderRasterState? rasterState, - bool compute - ) { - this.program = program; - this.bindings = bindings; - this.vertexLayout = vertexLayout; - this.vertexLayoutHandle = vertexLayoutHandle; - this.rasterState = rasterState; - this.compute = compute; - } - - /// - /// Gets the linked BGFX shader program owned by this pipeline resource. - /// - public bgfx.ProgramHandle program { get; } - /// - /// Gets the immutable lookup of stable binding IDs to BGFX uniform resources. - /// - public IReadOnlyDictionary bindings { get; } - /// - /// Gets the optional vertex layout required by this resource or pipeline. - /// - public RenderVertexLayout? vertexLayout { get; } - /// - /// Gets the BGFX vertex-layout handle owned by this pipeline resource. - /// - public bgfx.VertexLayoutHandle vertexLayoutHandle { get; } - /// - /// Gets the optional rasterization state encoded by this pipeline. - /// - public RenderRasterState? rasterState { get; } - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool compute { get; } + ) => new(descriptor, null, RenderIndexFormat.UInt32, BgfxBufferKind.Indirect, handle.idx); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs index 67ce627a1..ee9e2ed6e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs @@ -127,24 +127,24 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) bgfx.TextureFormat nativeFormat = ToNativeFormat(format); bgfx.CapsFormatFlags formatCaps = (bgfx.CapsFormatFlags)caps->formats[(int)nativeFormat]; bgfx.CapsFormatFlags sampledFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.Texture2dSrgb - : bgfx.CapsFormatFlags.Texture2d; + ? bgfx.CapsFormatFlags.Texture2dSrgb + : bgfx.CapsFormatFlags.Texture2d; if ((formatCaps & sampledFlag) != 0) { sampled.Add(format); } bgfx.CapsFormatFlags sampled3DFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.Texture3dSrgb - : bgfx.CapsFormatFlags.Texture3d; + ? bgfx.CapsFormatFlags.Texture3dSrgb + : bgfx.CapsFormatFlags.Texture3d; if ((formatCaps & sampled3DFlag) != 0) { sampled3D.Add(format); } bgfx.CapsFormatFlags sampledCubeFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.TextureCubeSrgb - : bgfx.CapsFormatFlags.TextureCube; + ? bgfx.CapsFormatFlags.TextureCubeSrgb + : bgfx.CapsFormatFlags.TextureCube; if ((formatCaps & sampledCubeFlag) != 0) { sampledCube.Add(format); @@ -178,7 +178,8 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) checked((int)caps->limits.maxViews), checked((int)caps->limits.maxFBAttachments), checked((int)caps->limits.maxTextureSize), - checked((int)caps->limits.maxComputeBindings)), + checked((int)caps->limits.maxComputeBindings) + ), sampled, renderTargets, storageRead, @@ -187,7 +188,8 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) caps->homogeneousDepth != 0, sampled3D, sampledCube, - multisampleRenderTargets); + multisampleRenderTargets + ); } /// @@ -201,22 +203,38 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) /// public static bgfx.RendererType ToNativeRenderer(GraphicsApi backend) { - if (backend == GraphicsApi.Noop) + if (backend == GraphicsApi.noop) + { return bgfx.RendererType.Noop; - if (backend == GraphicsApi.Direct3D11) + } + if (backend == GraphicsApi.direct3D11) + { return bgfx.RendererType.Direct3d11; - if (backend == GraphicsApi.Direct3D12) + } + if (backend == GraphicsApi.direct3D12) + { return bgfx.RendererType.Direct3d12; - if (backend == GraphicsApi.Metal) + } + if (backend == GraphicsApi.metal) + { return bgfx.RendererType.Metal; - if (backend == GraphicsApi.Vulkan) + } + if (backend == GraphicsApi.vulkan) + { return bgfx.RendererType.Vulkan; - if (backend == GraphicsApi.OpenGL) + } + if (backend == GraphicsApi.openGL) + { return bgfx.RendererType.OpenGL; - if (backend == GraphicsApi.OpenGLES) + } + if (backend == GraphicsApi.openGLES) + { return bgfx.RendererType.OpenGLES; - if (backend == GraphicsApi.WebGPU) + } + if (backend == GraphicsApi.webGPU) + { return bgfx.RendererType.WebGPU; + } throw new NotSupportedException($"BGFX does not support graphics backend '{backend}'."); } @@ -231,17 +249,17 @@ public static bgfx.RendererType ToNativeRenderer(GraphicsApi backend) /// public static GraphicsApi ToGraphicsApi(bgfx.RendererType backend) => backend switch - { - bgfx.RendererType.Noop => GraphicsApi.Noop, - bgfx.RendererType.Direct3d11 => GraphicsApi.Direct3D11, - bgfx.RendererType.Direct3d12 => GraphicsApi.Direct3D12, - bgfx.RendererType.Metal => GraphicsApi.Metal, - bgfx.RendererType.Vulkan => GraphicsApi.Vulkan, - bgfx.RendererType.OpenGL => GraphicsApi.OpenGL, - bgfx.RendererType.OpenGLES => GraphicsApi.OpenGLES, - bgfx.RendererType.WebGPU => GraphicsApi.WebGPU, - _ => throw new NotSupportedException($"BGFX renderer '{backend}' has no public Rendering.Core mapping.") - }; + { + bgfx.RendererType.Noop => GraphicsApi.noop, + bgfx.RendererType.Direct3d11 => GraphicsApi.direct3D11, + bgfx.RendererType.Direct3d12 => GraphicsApi.direct3D12, + bgfx.RendererType.Metal => GraphicsApi.metal, + bgfx.RendererType.Vulkan => GraphicsApi.vulkan, + bgfx.RendererType.OpenGL => GraphicsApi.openGL, + bgfx.RendererType.OpenGLES => GraphicsApi.openGLES, + bgfx.RendererType.WebGPU => GraphicsApi.webGPU, + _ => throw new NotSupportedException($"BGFX renderer '{backend}' has no public Rendering.Core mapping.") + }; /// /// Converts this value to its native format representation. @@ -254,17 +272,17 @@ public static GraphicsApi ToGraphicsApi(bgfx.RendererType backend) /// public static bgfx.TextureFormat ToNativeFormat(RenderTextureFormat format) => format switch - { - RenderTextureFormat.R8 => bgfx.TextureFormat.R8, - RenderTextureFormat.RG8 => bgfx.TextureFormat.RG8, - RenderTextureFormat.RGBA8 => bgfx.TextureFormat.RGBA8, - RenderTextureFormat.RGBA8Srgb => bgfx.TextureFormat.RGBA8, - RenderTextureFormat.RGB10A2 => bgfx.TextureFormat.RGB10A2, - RenderTextureFormat.RG11B10Float => bgfx.TextureFormat.RG11B10F, - RenderTextureFormat.RGBA16Float => bgfx.TextureFormat.RGBA16F, - RenderTextureFormat.R32Float => bgfx.TextureFormat.R32f, - RenderTextureFormat.Depth24Stencil8 => bgfx.TextureFormat.D24s8, - RenderTextureFormat.Depth32Float => bgfx.TextureFormat.D32f, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; + { + RenderTextureFormat.R8 => bgfx.TextureFormat.R8, + RenderTextureFormat.RG8 => bgfx.TextureFormat.RG8, + RenderTextureFormat.RGBA8 => bgfx.TextureFormat.RGBA8, + RenderTextureFormat.RGBA8Srgb => bgfx.TextureFormat.RGBA8, + RenderTextureFormat.RGB10A2 => bgfx.TextureFormat.RGB10A2, + RenderTextureFormat.RG11B10Float => bgfx.TextureFormat.RG11B10F, + RenderTextureFormat.RGBA16Float => bgfx.TextureFormat.RGBA16F, + RenderTextureFormat.R32Float => bgfx.TextureFormat.R32f, + RenderTextureFormat.Depth24Stencil8 => bgfx.TextureFormat.D24s8, + RenderTextureFormat.Depth32Float => bgfx.TextureFormat.D32f, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs index ee42f1596..2c5311dd0 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Binds the graphics pipeline used by subsequent draw commands. /// @@ -58,11 +57,10 @@ public override void BindComputePipeline(ComputePipelineHandle pipeline) /// The sampler consumed by bind texture; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, RenderSamplerState sampler - ) - => BindTexture(binding, m_device.ResolveTexture(texture), sampler); + ) => BindTexture(binding, m_device.ResolveTexture(texture), sampler); /// /// Binds a texture resource to the requested shader binding. @@ -77,11 +75,10 @@ RenderSamplerState sampler /// The sampler consumed by bind texture; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, RenderSamplerState sampler - ) - => BindTexture(binding, m_device.ResolveTexture(texture), sampler); + ) => BindTexture(binding, m_device.ResolveTexture(texture), sampler); /// /// Binds a writable texture resource to the requested shader binding. @@ -96,15 +93,15 @@ RenderSamplerState sampler /// The mip level consumed by bind storage texture; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, int mipLevel = 0 - ) - => BindStorageTexture( - binding, - m_device.ResolveTexture(texture), - m_device.ResolveTextureDescriptor(texture), - mipLevel); + ) => BindStorageTexture( + binding, + m_device.ResolveTexture(texture), + m_device.ResolveTextureDescriptor(texture), + mipLevel + ); /// /// Binds a writable texture resource to the requested shader binding. @@ -119,15 +116,15 @@ public override void BindStorageTexture( /// The mip level consumed by bind storage texture; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, int mipLevel = 0 - ) - => BindStorageTexture( - binding, - m_device.ResolveTexture(texture), - m_device.ResolveTextureDescriptor(texture), - mipLevel); + ) => BindStorageTexture( + binding, + m_device.ResolveTexture(texture), + m_device.ResolveTextureDescriptor(texture), + mipLevel + ); /// /// Binds a buffer resource to the requested shader binding. @@ -139,10 +136,9 @@ public override void BindStorageTexture( /// The buffer consumed by bind buffer; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, RenderBufferHandle buffer - ) - => BindBuffer(binding, m_device.ResolveBuffer(buffer)); + ) => BindBuffer(binding, m_device.ResolveBuffer(buffer)); /// /// Binds a buffer resource to the requested shader binding. @@ -154,10 +150,9 @@ RenderBufferHandle buffer /// The buffer consumed by bind buffer; ownership remains with the caller unless explicitly stated otherwise. /// public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, PersistentBufferHandle buffer - ) - => BindBuffer(binding, m_device.ResolveBuffer(buffer)); + ) => BindBuffer(binding, m_device.ResolveBuffer(buffer)); /// /// Updates the uniform state and applies the resulting invariants. @@ -169,7 +164,7 @@ PersistentBufferHandle buffer /// The concrete value read or transformed by this operation. /// public override void SetUniform( - RenderBindingId binding, + RenderBindingID binding, ReadOnlySpan value ) { BgfxShaderBindingResource resource = ResolveBinding(binding, RenderShaderBindingKind.Uniform); @@ -185,7 +180,8 @@ ReadOnlySpan value { throw new ArgumentException( $"Uniform '{binding.value}' requires exactly {expectedSize} bytes.", - nameof(value)); + nameof(value) + ); } fixed (byte* data = value) @@ -194,12 +190,13 @@ ReadOnlySpan value m_encoder, resource.uniform, data, - checked((ushort)resource.descriptor.count)); + checked((ushort)resource.descriptor.count) + ); } } private void BindTexture( - RenderBindingId binding, + RenderBindingID binding, bgfx.TextureHandle texture, RenderSamplerState sampler ) { @@ -209,11 +206,12 @@ RenderSamplerState sampler checked((byte)resource.descriptor.slot), resource.uniform, texture, - SamplerFlags(sampler)); + SamplerFlags(sampler) + ); } private void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, bgfx.TextureHandle texture, RenderTextureDescriptor descriptor, int mipLevel @@ -221,22 +219,22 @@ int mipLevel BgfxShaderBindingResource resource = ResolveBinding(binding, RenderShaderBindingKind.StorageTexture); if (!m_device.capabilities.Supports(GraphicsCapability.StorageTexture)) { - throw new NotSupportedException( - "The active graphics backend does not support shader storage textures."); + throw new NotSupportedException("The active graphics backend does not support shader storage textures."); } if ((descriptor.usage & RenderTextureUsage.Storage) == 0) { throw new ArgumentException( $"Texture bound to '{binding.value}' was not created for storage access.", - nameof(descriptor)); + nameof(descriptor) + ); } ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); - if (mipLevel >= descriptor.mipCount) - throw new ArgumentOutOfRangeException(nameof(mipLevel)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(mipLevel, descriptor.mipCount); if (!m_device.capabilities.SupportsStorage(descriptor.format, resource.descriptor.storageAccess)) { throw new NotSupportedException( - $"Texture format '{descriptor.format}' does not support {resource.descriptor.storageAccess} storage access."); + $"Texture format '{descriptor.format}' does not support {resource.descriptor.storageAccess} storage access." + ); } BgfxNativeCalls.EncoderSetImage( @@ -245,11 +243,12 @@ int mipLevel texture, checked((byte)mipLevel), StorageAccess(resource.descriptor.storageAccess), - BgfxCapabilityMapper.ToNativeFormat(descriptor.format)); + BgfxCapabilityMapper.ToNativeFormat(descriptor.format) + ); } private void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, BgfxBufferResource buffer ) { BgfxShaderBindingResource resource = ResolveBinding(binding, RenderShaderBindingKind.StorageBuffer); @@ -257,7 +256,8 @@ BgfxBufferResource buffer { throw new ArgumentException( $"Buffer bound to '{binding.value}' was not created for storage access.", - nameof(buffer)); + nameof(buffer) + ); } byte slot = checked((byte)resource.descriptor.slot); @@ -269,35 +269,40 @@ BgfxBufferResource buffer m_encoder, slot, new bgfx.VertexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.Index: BgfxNativeCalls.EncoderSetComputeIndexBuffer( m_encoder, slot, new bgfx.IndexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.DynamicVertex: BgfxNativeCalls.EncoderSetComputeDynamicVertexBuffer( m_encoder, slot, new bgfx.DynamicVertexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.DynamicIndex: BgfxNativeCalls.EncoderSetComputeDynamicIndexBuffer( m_encoder, slot, new bgfx.DynamicIndexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.Indirect: BgfxNativeCalls.EncoderSetComputeIndirectBuffer( m_encoder, slot, new bgfx.IndirectBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; default: throw new ArgumentOutOfRangeException(nameof(buffer)); @@ -305,7 +310,7 @@ BgfxBufferResource buffer } private BgfxShaderBindingResource ResolveBinding( - RenderBindingId binding, + RenderBindingID binding, RenderShaderBindingKind requiredKind ) { if (!binding.isValid) @@ -314,22 +319,23 @@ RenderShaderBindingKind requiredKind } BgfxPipelineResource pipeline = m_pipeline - ?? throw new InvalidOperationException("A pipeline must be bound before shader resources."); + ?? throw new InvalidOperationException("A pipeline must be bound before shader resources."); if (!pipeline.bindings.TryGetValue(binding.value, out BgfxShaderBindingResource? resource)) { throw new ArgumentException( $"Pipeline does not declare shader binding '{binding.value}'.", - nameof(binding)); + nameof(binding) + ); } if (resource.descriptor.kind != requiredKind) { throw new ArgumentException( $"Shader binding '{binding.value}' is {resource.descriptor.kind}, not {requiredKind}.", - nameof(binding)); + nameof(binding) + ); } return resource; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs index b6d059149..e28b9c9f0 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Dispatches compute work using the supplied thread-group dimensions. /// @@ -31,12 +30,13 @@ public override void Dispatch( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(groupCountZ); BgfxNativeCalls.EncoderDispatch( m_encoder, - m_viewId, + m_viewID, pipeline.program, checked((uint)groupCountX), checked((uint)groupCountY), checked((uint)groupCountZ), - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDispatch(); } @@ -56,8 +56,7 @@ public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); /// /// Dispatches compute work using dimensions read from the supplied indirect buffer. @@ -75,8 +74,7 @@ public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); private void DispatchIndirect( BgfxBufferResource buffer, @@ -87,13 +85,13 @@ int commandCount ValidateIndirect(buffer, firstCommand, commandCount); BgfxNativeCalls.EncoderDispatchIndirect( m_encoder, - m_viewId, + m_viewID, pipeline.program, new bgfx.IndirectBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstCommand), checked((uint)commandCount), - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDispatch(commandCount); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs index 216e730ac..3c9880717 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Renders the value presentation for the current editor frame. /// @@ -26,7 +25,8 @@ public override void Draw( if (m_vertexBuffer is null) { throw new InvalidOperationException( - "A direct non-procedural draw requires a bound vertex buffer. Use DrawProcedural explicitly otherwise."); + "A direct non-procedural draw requires a bound vertex buffer. Use DrawProcedural explicitly otherwise." + ); } SetVertexBuffer(pipeline, m_vertexBuffer, m_firstVertex, vertexCount); @@ -49,8 +49,7 @@ public override void DrawProcedural( BgfxPipelineResource pipeline = RequireGraphicsPipeline(); if (!m_device.capabilities.Supports(GraphicsCapability.ProceduralDraw)) { - throw new NotSupportedException( - "The active graphics backend does not support procedural vertex-ID draws."); + throw new NotSupportedException("The active graphics backend does not support procedural vertex-ID draws."); } ValidateDrawCounts(vertexCount, instanceCount); bgfx.Raw.encoder_set_vertex_count(m_encoder, checked((uint)vertexCount)); @@ -86,7 +85,8 @@ public override void DrawIndexed( pipeline, m_vertexBuffer, m_firstVertex, - m_vertexBuffer.descriptor.elementCount - m_firstVertex); + m_vertexBuffer.descriptor.elementCount - m_firstVertex + ); SetIndexBuffer(m_indexBuffer, m_firstIndex, indexCount); Submit(pipeline, instanceCount); } @@ -107,8 +107,7 @@ public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); /// /// Renders the indirect presentation for the current editor frame. @@ -126,8 +125,7 @@ public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); private void DrawIndirect( BgfxBufferResource buffer, @@ -142,30 +140,30 @@ int commandCount pipeline, m_vertexBuffer, m_firstVertex, - m_vertexBuffer.descriptor.elementCount - m_firstVertex); + m_vertexBuffer.descriptor.elementCount - m_firstVertex + ); } else if (!m_device.capabilities.Supports(GraphicsCapability.ProceduralDraw)) { throw new NotSupportedException( - "An indirect draw without a vertex buffer requires procedural draw capability."); + "An indirect draw without a vertex buffer requires procedural draw capability." + ); } if (m_indexBuffer is not null) { - SetIndexBuffer( - m_indexBuffer, - m_firstIndex, - m_indexBuffer.descriptor.elementCount - m_firstIndex); + SetIndexBuffer(m_indexBuffer, m_firstIndex, m_indexBuffer.descriptor.elementCount - m_firstIndex); } SetDrawState(pipeline); BgfxNativeCalls.EncoderSubmitIndirect( m_encoder, - m_viewId, + m_viewID, pipeline.program, new bgfx.IndirectBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstCommand), checked((uint)commandCount), 0, - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDraw(commandCount); m_instanceDataBound = false; } @@ -175,12 +173,15 @@ private void Submit( int instanceCount ) { if (instanceCount > 1 && !m_device.capabilities.Supports(GraphicsCapability.Instancing)) + { throw new NotSupportedException("The active graphics backend does not support instancing."); + } if (m_instanceDataBound && instanceCount != 1) { throw new ArgumentException( "A draw with bound instance data must use the bound instance count.", - nameof(instanceCount)); + nameof(instanceCount) + ); } if (!m_instanceDataBound && instanceCount > 1) { @@ -188,12 +189,7 @@ int instanceCount } SetDrawState(pipeline); - BgfxNativeCalls.EncoderSubmit( - m_encoder, - m_viewId, - pipeline.program, - 0, - checked((byte)bgfx.DiscardFlags.All)); + BgfxNativeCalls.EncoderSubmit(m_encoder, m_viewID, pipeline.program, 0, checked((byte)bgfx.DiscardFlags.All)); m_device.RecordDraw(); m_instanceDataBound = false; } @@ -210,7 +206,7 @@ private void SetDrawState(BgfxPipelineResource pipeline) bgfx.Raw.encoder_set_stencil( m_encoder, StencilFlags(m_stencilState, m_stencilState.front), - StencilFlags(m_stencilState, m_stencilState.back)); + StencilFlags(m_stencilState, m_stencilState.back) + ); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs index b22197715..df16ef262 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Binds a vertex buffer and its first vertex for subsequent draws. /// @@ -20,8 +19,7 @@ internal sealed unsafe partial class BgfxCommandEncoder public override void BindVertexBuffer( RenderBufferHandle buffer, int firstVertex = 0 - ) - => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); + ) => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); /// /// Binds a vertex buffer and its first vertex for subsequent draws. @@ -35,8 +33,7 @@ public override void BindVertexBuffer( public override void BindVertexBuffer( PersistentBufferHandle buffer, int firstVertex = 0 - ) - => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); + ) => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); /// /// Binds an index buffer and its first index for subsequent indexed draws. @@ -50,8 +47,7 @@ public override void BindVertexBuffer( public override void BindIndexBuffer( RenderBufferHandle buffer, int firstIndex = 0 - ) - => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); + ) => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); /// /// Binds an index buffer and its first index for subsequent indexed draws. @@ -65,8 +61,7 @@ public override void BindIndexBuffer( public override void BindIndexBuffer( PersistentBufferHandle buffer, int firstIndex = 0 - ) - => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); + ) => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); /// /// Binds per-instance data for subsequent instanced draws. @@ -84,8 +79,7 @@ public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, int instanceCount - ) - => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); + ) => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); /// /// Binds per-instance data for subsequent instanced draws. @@ -103,8 +97,7 @@ public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, int instanceCount - ) - => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); + ) => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); private void BindVertexBuffer( BgfxBufferResource buffer, @@ -116,10 +109,7 @@ int firstVertex throw new ArgumentException("The buffer was not created for vertex input.", nameof(buffer)); } - if (firstVertex >= buffer.descriptor.elementCount) - { - throw new ArgumentOutOfRangeException(nameof(firstVertex)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(firstVertex, buffer.descriptor.elementCount); m_vertexBuffer = buffer; m_firstVertex = firstVertex; @@ -135,10 +125,7 @@ int firstIndex throw new ArgumentException("The buffer was not created for index input.", nameof(buffer)); } - if (firstIndex >= buffer.descriptor.elementCount) - { - throw new ArgumentOutOfRangeException(nameof(firstIndex)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(firstIndex, buffer.descriptor.elementCount); m_indexBuffer = buffer; m_firstIndex = firstIndex; @@ -150,7 +137,9 @@ private void BindInstanceBuffer( int instanceCount ) { if (!m_device.capabilities.Supports(GraphicsCapability.Instancing)) + { throw new NotSupportedException("The active graphics backend does not support instancing."); + } ArgumentOutOfRangeException.ThrowIfNegative(firstInstance); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(instanceCount); ValidateRange(firstInstance, instanceCount, buffer.descriptor.elementCount, nameof(instanceCount)); @@ -161,14 +150,16 @@ int instanceCount m_encoder, new bgfx.VertexBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstInstance), - checked((uint)instanceCount)); + checked((uint)instanceCount) + ); break; case BgfxBufferKind.DynamicVertex: BgfxNativeCalls.EncoderSetInstanceDataFromDynamicVertexBuffer( m_encoder, new bgfx.DynamicVertexBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstInstance), - checked((uint)instanceCount)); + checked((uint)instanceCount) + ); break; default: throw new ArgumentException("Instance data requires a vertex-compatible buffer.", nameof(buffer)); @@ -186,7 +177,8 @@ int vertexCount if (pipeline.vertexLayout is null || !pipeline.vertexLayoutHandle.Valid) { throw new InvalidOperationException( - "A graphics pipeline with procedural vertices cannot bind a vertex buffer."); + "A graphics pipeline with procedural vertices cannot bind a vertex buffer." + ); } if (buffer.vertexLayout is not null && !buffer.vertexLayout.Equals(pipeline.vertexLayout)) @@ -198,7 +190,7 @@ int vertexCount uint count = checked((uint)vertexCount); if (buffer.kind == BgfxBufferKind.Vertex) { - bgfx.VertexBufferHandle handle = new() { idx = buffer.nativeIndex }; + var handle = new bgfx.VertexBufferHandle() { idx = buffer.nativeIndex }; if (buffer.vertexLayout is null) { BgfxNativeCalls.EncoderSetVertexBufferWithLayout( @@ -207,7 +199,8 @@ int vertexCount handle, first, count, - pipeline.vertexLayoutHandle); + pipeline.vertexLayoutHandle + ); } else { @@ -219,7 +212,7 @@ int vertexCount if (buffer.kind == BgfxBufferKind.DynamicVertex) { - bgfx.DynamicVertexBufferHandle handle = new() { idx = buffer.nativeIndex }; + var handle = new bgfx.DynamicVertexBufferHandle() { idx = buffer.nativeIndex }; if (buffer.vertexLayout is null) { BgfxNativeCalls.EncoderSetDynamicVertexBufferWithLayout( @@ -228,7 +221,8 @@ int vertexCount handle, first, count, - pipeline.vertexLayoutHandle); + pipeline.vertexLayoutHandle + ); } else { @@ -255,7 +249,8 @@ int indexCount m_encoder, new bgfx.IndexBufferHandle { idx = buffer.nativeIndex }, first, - count); + count + ); return; } @@ -265,11 +260,11 @@ int indexCount m_encoder, new bgfx.DynamicIndexBufferHandle { idx = buffer.nativeIndex }, first, - count); + count + ); return; } throw new InvalidOperationException("The bound resource is not an index buffer."); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs index 416630d57..ed7fc9d92 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Updates the transform state and applies the resulting invariants. /// @@ -38,10 +37,11 @@ public override void SetRasterState(RenderRasterState state) ArgumentNullException.ThrowIfNull(state); _ = RequireGraphicsPipeline(); if (state.blend.alphaToCoverage - && !m_device.capabilities.Supports(GraphicsCapability.AlphaToCoverage)) - { + && !m_device.capabilities.Supports(GraphicsCapability.AlphaToCoverage) + ) { throw new NotSupportedException( - "The active graphics backend does not support alpha-to-coverage rasterization."); + "The active graphics backend does not support alpha-to-coverage rasterization." + ); } m_rasterState = state; } @@ -58,8 +58,7 @@ public override void SetStencil(RenderStencilState state) _ = RequireGraphicsPipeline(); if (state.enabled && state.writeMask != byte.MaxValue) { - throw new NotSupportedException( - "BGFX does not expose an independent dynamic stencil write mask."); + throw new NotSupportedException("BGFX does not expose an independent dynamic stencil write mask."); } m_stencilState = state; } @@ -90,11 +89,12 @@ int height ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); bgfx.set_view_rect( - m_viewId, + m_viewID, checked((ushort)x), checked((ushort)y), checked((ushort)width), - checked((ushort)height)); + checked((ushort)height) + ); } /// @@ -127,7 +127,8 @@ int height checked((ushort)x), checked((ushort)y), checked((ushort)width), - checked((ushort)height)); + checked((ushort)height) + ); } private static ulong RasterState(RenderRasterState state) @@ -192,7 +193,9 @@ private static ulong RasterState(RenderRasterState state) } if (state.blend.alphaToCoverage) + { flags |= bgfx.StateFlags.BlendAlphaToCoverage; + } if (state.multisampling) { @@ -214,12 +217,12 @@ private static ulong RasterState(RenderRasterState state) private static bgfx.Access StorageAccess(RenderStorageAccess access) => access switch - { - RenderStorageAccess.Read => bgfx.Access.Read, - RenderStorageAccess.Write => bgfx.Access.Write, - RenderStorageAccess.ReadWrite => bgfx.Access.ReadWrite, - _ => throw new ArgumentOutOfRangeException(nameof(access)) - }; + { + RenderStorageAccess.Read => bgfx.Access.Read, + RenderStorageAccess.Write => bgfx.Access.Write, + RenderStorageAccess.ReadWrite => bgfx.Access.ReadWrite, + _ => throw new ArgumentOutOfRangeException(nameof(access)) + }; private static uint SamplerFlags(RenderSamplerState state) { @@ -228,7 +231,7 @@ private static uint SamplerFlags(RenderSamplerState state) RenderSamplerFilter.Point => bgfx.SamplerFlags.Point, RenderSamplerFilter.Linear => bgfx.SamplerFlags.None, RenderSamplerFilter.Anisotropic => bgfx.SamplerFlags.MinAnisotropic - | bgfx.SamplerFlags.MagAnisotropic, + | bgfx.SamplerFlags.MagAnisotropic, _ => throw new ArgumentOutOfRangeException(nameof(state)) }; flags |= AddressFlags(state.addressU, 'U'); @@ -240,21 +243,20 @@ private static uint SamplerFlags(RenderSamplerState state) private static bgfx.SamplerFlags AddressFlags( RenderSamplerAddressMode mode, char axis - ) - => (axis, mode) switch - { - (_, RenderSamplerAddressMode.Repeat) => bgfx.SamplerFlags.None, - ('U', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.UMirror, - ('U', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.UClamp, - ('U', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.UBorder, - ('V', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.VMirror, - ('V', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.VClamp, - ('V', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.VBorder, - ('W', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.WMirror, - ('W', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.WClamp, - ('W', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.WBorder, - _ => throw new ArgumentOutOfRangeException(nameof(mode)) - }; + ) => (axis, mode) switch + { + (_, RenderSamplerAddressMode.Repeat) => bgfx.SamplerFlags.None, + ('U', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.UMirror, + ('U', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.UClamp, + ('U', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.UBorder, + ('V', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.VMirror, + ('V', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.VClamp, + ('V', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.VBorder, + ('W', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.WMirror, + ('W', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.WClamp, + ('W', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.WBorder, + _ => throw new ArgumentOutOfRangeException(nameof(mode)) + }; private static uint StencilFlags( RenderStencilState state, @@ -314,8 +316,8 @@ private static ulong BlendFunction(RenderBlendState state) ulong alphaSource = (ulong)BlendFactor(state.alphaSource); ulong alphaDestination = (ulong)BlendFactor(state.alphaDestination); return colorSource - | (colorDestination << 4) - | ((alphaSource | (alphaDestination << 4)) << 8); + | (colorDestination << 4) + | ((alphaSource | (alphaDestination << 4)) << 8); } private static ulong BlendEquation(RenderBlendState state) @@ -325,34 +327,33 @@ private static ulong BlendEquation(RenderBlendState state) return color | (alpha << 3); } - private static bgfx.StateFlags BlendFactor(RenderBlendFactor factor) - => factor switch - { - RenderBlendFactor.Zero => bgfx.StateFlags.BlendZero, - RenderBlendFactor.One => bgfx.StateFlags.BlendOne, - RenderBlendFactor.SourceColor => bgfx.StateFlags.BlendSrcColor, - RenderBlendFactor.InverseSourceColor => bgfx.StateFlags.BlendInvSrcColor, - RenderBlendFactor.SourceAlpha => bgfx.StateFlags.BlendSrcAlpha, - RenderBlendFactor.InverseSourceAlpha => bgfx.StateFlags.BlendInvSrcAlpha, - RenderBlendFactor.DestinationAlpha => bgfx.StateFlags.BlendDstAlpha, - RenderBlendFactor.InverseDestinationAlpha => bgfx.StateFlags.BlendInvDstAlpha, - RenderBlendFactor.DestinationColor => bgfx.StateFlags.BlendDstColor, - RenderBlendFactor.InverseDestinationColor => bgfx.StateFlags.BlendInvDstColor, - RenderBlendFactor.SourceAlphaSaturate => bgfx.StateFlags.BlendSrcAlphaSat, - RenderBlendFactor.Constant => bgfx.StateFlags.BlendFactor, - RenderBlendFactor.InverseConstant => bgfx.StateFlags.BlendInvFactor, - _ => throw new ArgumentOutOfRangeException(nameof(factor)) - }; - private static bgfx.StateFlags BlendEquation(RenderBlendEquation equation) => equation switch - { - RenderBlendEquation.Add => bgfx.StateFlags.BlendEquationAdd, - RenderBlendEquation.Subtract => bgfx.StateFlags.BlendEquationSub, - RenderBlendEquation.ReverseSubtract => bgfx.StateFlags.BlendEquationRevsub, - RenderBlendEquation.Minimum => bgfx.StateFlags.BlendEquationMin, - RenderBlendEquation.Maximum => bgfx.StateFlags.BlendEquationMax, - _ => throw new ArgumentOutOfRangeException(nameof(equation)) - }; + { + RenderBlendEquation.Add => bgfx.StateFlags.BlendEquationAdd, + RenderBlendEquation.Subtract => bgfx.StateFlags.BlendEquationSub, + RenderBlendEquation.ReverseSubtract => bgfx.StateFlags.BlendEquationRevsub, + RenderBlendEquation.Minimum => bgfx.StateFlags.BlendEquationMin, + RenderBlendEquation.Maximum => bgfx.StateFlags.BlendEquationMax, + _ => throw new ArgumentOutOfRangeException(nameof(equation)) + }; + private static bgfx.StateFlags BlendFactor(RenderBlendFactor factor) + => factor switch + { + RenderBlendFactor.Zero => bgfx.StateFlags.BlendZero, + RenderBlendFactor.One => bgfx.StateFlags.BlendOne, + RenderBlendFactor.SourceColor => bgfx.StateFlags.BlendSrcColor, + RenderBlendFactor.InverseSourceColor => bgfx.StateFlags.BlendInvSrcColor, + RenderBlendFactor.SourceAlpha => bgfx.StateFlags.BlendSrcAlpha, + RenderBlendFactor.InverseSourceAlpha => bgfx.StateFlags.BlendInvSrcAlpha, + RenderBlendFactor.DestinationAlpha => bgfx.StateFlags.BlendDstAlpha, + RenderBlendFactor.InverseDestinationAlpha => bgfx.StateFlags.BlendInvDstAlpha, + RenderBlendFactor.DestinationColor => bgfx.StateFlags.BlendDstColor, + RenderBlendFactor.InverseDestinationColor => bgfx.StateFlags.BlendInvDstColor, + RenderBlendFactor.SourceAlphaSaturate => bgfx.StateFlags.BlendSrcAlphaSat, + RenderBlendFactor.Constant => bgfx.StateFlags.BlendFactor, + RenderBlendFactor.InverseConstant => bgfx.StateFlags.BlendInvFactor, + _ => throw new ArgumentOutOfRangeException(nameof(factor)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs index b5740f697..1c99cd909 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Copies texture without transferring ownership of the source state. /// @@ -36,7 +35,7 @@ RenderTextureHandle destination { BgfxNativeCalls.EncoderBlit( m_encoder, - m_viewId, + m_viewID, destinationTexture, checked((byte)mipLevel), 0, @@ -49,7 +48,8 @@ RenderTextureHandle destination checked((ushort)layer), width, height, - 1); + 1 + ); } } } @@ -83,13 +83,13 @@ RenderTextureRegion destinationRegion ValidateTextureCopyFormats(sourceDescriptor, destinationDescriptor); if (sourceRegion.width != destinationRegion.width || sourceRegion.height != destinationRegion.height - || sourceRegion.depth != destinationRegion.depth) - { + || sourceRegion.depth != destinationRegion.depth + ) { throw new ArgumentException("BGFX blit source and destination extents must match."); } BgfxNativeCalls.EncoderBlit( m_encoder, - m_viewId, + m_viewID, m_device.ResolveTexture(destination), checked((byte)destinationRegion.mip), checked((ushort)destinationRegion.x), @@ -102,7 +102,8 @@ RenderTextureRegion destinationRegion checked((ushort)sourceRegion.layer), checked((ushort)sourceRegion.width), checked((ushort)sourceRegion.height), - checked((ushort)sourceRegion.depth)); + checked((ushort)sourceRegion.depth) + ); } /// @@ -121,7 +122,7 @@ RenderBufferHandle destination _ = source; _ = destination; throw new NotSupportedException( - "BGFX has no general buffer-copy command; use a Plugin compute pass on supported devices."); + "BGFX has no general buffer-copy command; use a Plugin compute pass on supported devices." + ); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs index 18c541572..2c25fcb28 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - private void RequireTextureBlit() { if (!m_device.capabilities.Supports(GraphicsCapability.TextureBlit)) @@ -16,6 +15,44 @@ private void RequireTextureBlit() } } + private void ValidateIndirect( + BgfxBufferResource buffer, + int firstCommand, + int commandCount + ) { + if (!m_device.capabilities.Supports(GraphicsCapability.Indirect)) + { + throw new NotSupportedException("The active graphics backend does not support indirect commands."); + } + ArgumentOutOfRangeException.ThrowIfNegative(firstCommand); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(commandCount); + ValidateRange(firstCommand, commandCount, buffer.descriptor.elementCount, nameof(commandCount)); + if (buffer.kind != BgfxBufferKind.Indirect) + { + throw new ArgumentException("The buffer was not created for indirect commands.", nameof(buffer)); + } + } + + private BgfxPipelineResource RequireGraphicsPipeline() + { + if (m_pipeline is null || m_pipeline.compute) + { + throw new InvalidOperationException("A graphics pipeline must be bound before drawing."); + } + + return m_pipeline; + } + + private BgfxPipelineResource RequireComputePipeline() + { + if (m_pipeline is null || !m_pipeline.compute) + { + throw new InvalidOperationException("A compute pipeline must be bound before dispatch."); + } + + return m_pipeline; + } + private static void ValidateCompleteTextureCopy( RenderTextureDescriptor source, RenderTextureDescriptor destination @@ -26,10 +63,11 @@ RenderTextureDescriptor destination || source.depth != destination.depth || source.dimension != destination.dimension || source.mipCount != destination.mipCount - || source.arrayLayers != destination.arrayLayers) - { + || source.arrayLayers != destination.arrayLayers + ) { throw new ArgumentException( - "A complete texture copy requires equal dimensions, mip counts, and array layers."); + "A complete texture copy requires equal dimensions, mip counts, and array layers." + ); } } @@ -48,10 +86,9 @@ RenderTextureDescriptor destination } if ((source.usage & RenderTextureUsage.CopySource) == 0 - || (destination.usage & RenderTextureUsage.CopyDestination) == 0) - { - throw new ArgumentException( - "Texture copies require CopySource and CopyDestination usage respectively."); + || (destination.usage & RenderTextureUsage.CopyDestination) == 0 + ) { + throw new ArgumentException("Texture copies require CopySource and CopyDestination usage respectively."); } } @@ -69,46 +106,12 @@ string parameterName int mipHeight = Math.Max(1, descriptor.height >> region.mip); if (region.x > mipWidth - region.width || region.y > mipHeight - region.height - || region.layer > descriptor.GetSubresourceLayerCount(region.mip) - region.depth) - { + || region.layer > descriptor.GetSubresourceLayerCount(region.mip) - region.depth + ) { throw new ArgumentOutOfRangeException(parameterName, "Texture region is outside the descriptor."); } } - private void ValidateIndirect( - BgfxBufferResource buffer, - int firstCommand, - int commandCount - ) { - if (!m_device.capabilities.Supports(GraphicsCapability.Indirect)) - throw new NotSupportedException("The active graphics backend does not support indirect commands."); - ArgumentOutOfRangeException.ThrowIfNegative(firstCommand); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(commandCount); - ValidateRange(firstCommand, commandCount, buffer.descriptor.elementCount, nameof(commandCount)); - if (buffer.kind != BgfxBufferKind.Indirect) - throw new ArgumentException("The buffer was not created for indirect commands.", nameof(buffer)); - } - - private BgfxPipelineResource RequireGraphicsPipeline() - { - if (m_pipeline is null || m_pipeline.compute) - { - throw new InvalidOperationException("A graphics pipeline must be bound before drawing."); - } - - return m_pipeline; - } - - private BgfxPipelineResource RequireComputePipeline() - { - if (m_pipeline is null || !m_pipeline.compute) - { - throw new InvalidOperationException("A compute pipeline must be bound before dispatch."); - } - - return m_pipeline; - } - private static void ValidateDrawCounts( int primitiveCount, int instanceCount @@ -127,8 +130,8 @@ string parameterName { throw new ArgumentOutOfRangeException( parameterName, - $"Requested range [{first}, {first + count}) exceeds buffer element count {available}."); + $"Requested range [{first}, {first + count}) exceeds buffer element count {available}." + ); } } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs index eac84650e..b054c2104 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs @@ -8,7 +8,7 @@ internal sealed unsafe partial class BgfxCommandEncoder : RenderCommandEncoder { private readonly BgfxDevice m_device; private readonly bgfx.Encoder* m_encoder; - private readonly ushort m_viewId; + private readonly ushort m_viewID; private BgfxPipelineResource? m_pipeline; private BgfxBufferResource? m_vertexBuffer; @@ -28,17 +28,16 @@ internal sealed unsafe partial class BgfxCommandEncoder : RenderCommandEncoder /// /// The encoder consumed by bgfx command encoder; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The view id consumed by bgfx command encoder; ownership remains with the caller unless explicitly stated otherwise. /// public BgfxCommandEncoder( BgfxDevice device, bgfx.Encoder* encoder, - ushort viewId + ushort viewID ) { m_device = device; m_encoder = encoder; - m_viewId = viewId; + m_viewID = viewID; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs index 668989b2a..02066f248 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; /// public sealed class BgfxCompositionProgramProvider : IRenderLayerCompositionProgramProvider { - private static readonly RenderBindingId S_TEXTURE = new("s_tex"); + private static readonly RenderBindingID TEXTURE = new("s_tex"); /// /// Loads the BGFX target program matching the active device renderer. @@ -61,31 +61,46 @@ RenderVertexLayout vertexLayout Assembly assembly = typeof(BgfxCompositionProgramProvider).Assembly; string suffix = "." + capabilities.backend.value; string[] resources = assembly.GetManifestResourceNames() - .Where(name => name.StartsWith($"Inno.BgfxShaders.{programName}.", StringComparison.Ordinal) - && name.EndsWith(suffix, StringComparison.Ordinal)) + .Where(name => ( + name.StartsWith($"Inno.BgfxShaders.{programName}.", StringComparison.Ordinal) + && name.EndsWith(suffix, StringComparison.Ordinal) + )) .ToArray(); if (resources.Length != 1) + { throw new InvalidDataException( - $"The BGFX adapter requires exactly one {programName} shader for '{capabilities.backend}'; found {resources.Length}."); + $"The BGFX adapter requires exactly one {programName} shader for '{capabilities.backend}'; found {resources.Length}." + ); + } using Stream source = assembly.GetManifestResourceStream(resources[0]) - ?? throw new InvalidDataException($"The BGFX adapter cannot read {programName} shader '{resources[0]}'."); + ?? throw new InvalidDataException($"The BGFX adapter cannot read {programName} shader '{resources[0]}'."); using var bytes = new MemoryStream(); source.CopyTo(bytes); GraphicsPipelineDescriptor program = GraphicsProgramArtifactCodec.Decode(bytes.ToArray(), vertexLayout); RenderShaderBindingDescriptor binding = program.bindings.Single(); if (binding.id.value != "s_tex" || binding.kind != RenderShaderBindingKind.Texture - || binding.slot != 0) + || binding.slot != 0 + ) { throw new InvalidDataException($"The BGFX {programName} shader must expose s_tex at slot zero."); + } RenderRasterState authored = program.rasterState; var raster = new RenderRasterState( - RenderCullMode.None, authored.frontFace, RenderDepthCompare.Always, - depthWrite: false, blend, - authored.colorWriteMask, authored.multisampling, authored.topology); + RenderCullMode.None, + authored.frontFace, + RenderDepthCompare.Always, + depthWrite: false, + blend, + authored.colorWriteMask, + authored.multisampling, + authored.topology + ); return new GraphicsPipelineDescriptor( program.vertexShader.Span, program.fragmentShader.Span, - [new(S_TEXTURE, RenderShaderBindingKind.Texture, slot: 0, nativeName: binding.nativeName)], - vertexLayout, raster); + [new RenderShaderBindingDescriptor(TEXTURE, RenderShaderBindingKind.Texture, slot: 0, nativeName: binding.nativeName)], + vertexLayout, + raster + ); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs index 5ea197b42..bb8f135fd 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs @@ -1,20 +1,20 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { private void ConfigureViewTarget( - ushort viewId, + ushort viewID, CompiledRenderPass pass ) { int width = m_backbufferWidth; @@ -29,20 +29,20 @@ CompiledRenderPass pass BgfxWindowSurfaceResource surface = ResolveSurface(pass.surface); width = surface.width; height = surface.height; - bgfx.set_view_frame_buffer(viewId, surface.frameBuffer); + bgfx.set_view_frame_buffer(viewID, surface.frameBuffer); } else if (pass.attachments.Count != 0) { bgfx.FrameBufferHandle cachedFrameBuffer = FindCachedFrameBuffer(pass); if (cachedFrameBuffer.Valid) { - bgfx.set_view_frame_buffer(viewId, cachedFrameBuffer); + bgfx.set_view_frame_buffer(viewID, cachedFrameBuffer); } else { RetireSupersededFrameBuffer(pass.name); bgfx.Attachment* attachments = stackalloc bgfx.Attachment[pass.attachments.Count]; - GraphAttachmentSignature[] signature = new GraphAttachmentSignature[pass.attachments.Count]; + var signature = new GraphAttachmentSignature[pass.attachments.Count]; for (int index = 0; index < pass.attachments.Count; index++) { CompiledRenderAttachment attachment = pass.attachments[index]; @@ -52,7 +52,8 @@ CompiledRenderPass pass attachment.slot, attachment.isDepth, attachment.mipLevel, - attachment.arrayLayer); + attachment.arrayLayer + ); BgfxNativeCalls.AttachmentInit( &attachments[index], nativeTexture, @@ -60,26 +61,26 @@ CompiledRenderPass pass checked((ushort)attachment.arrayLayer), 1, checked((ushort)attachment.mipLevel), - (byte)bgfx.ResolveFlags.None); + (byte)bgfx.ResolveFlags.None + ); } bgfx.FrameBufferHandle frameBuffer = BgfxNativeCalls.CreateFrameBufferFromAttachment( checked((byte)pass.attachments.Count), attachments, - 0); + 0 + ); if (!frameBuffer.Valid) { throw new InvalidOperationException($"BGFX could not create framebuffer for pass '{pass.name}'."); } m_transientFrameBufferAllocationCount++; - m_graphFrameBufferCache.Add(new CachedGraphFrameBuffer( - frameBuffer, - pass.name, - signature, - m_submissionSequence)); + m_graphFrameBufferCache.Add( + new CachedGraphFrameBuffer(frameBuffer, pass.name, signature, m_submissionSequence) + ); m_graphFrameBuffers.Add(frameBuffer); - bgfx.set_view_frame_buffer(viewId, frameBuffer); + bgfx.set_view_frame_buffer(viewID, frameBuffer); } ApplyAttachmentState( @@ -89,27 +90,22 @@ CompiledRenderPass pass ref clearFlags, ref clearColor, ref clearDepth, - ref clearStencil); + ref clearStencil + ); } else { - bgfx.set_view_frame_buffer(viewId, new bgfx.FrameBufferHandle { idx = ushort.MaxValue }); + bgfx.set_view_frame_buffer(viewID, new bgfx.FrameBufferHandle { idx = ushort.MaxValue }); } - if (pass.clearsPresentationTarget) { clearFlags |= bgfx.ClearFlags.Color; clearColor = PackColor(pass.presentationClearColor); } - bgfx.set_view_rect( - viewId, - 0, - 0, - checked((ushort)width), - checked((ushort)height)); - bgfx.set_view_clear(viewId, (ushort)clearFlags, clearColor, clearDepth, clearStencil); + bgfx.set_view_rect(viewID, 0, 0, checked((ushort)width), checked((ushort)height)); + bgfx.set_view_clear(viewID, (ushort)clearFlags, clearColor, clearDepth, clearStencil); } private bgfx.FrameBufferHandle FindCachedFrameBuffer(CompiledRenderPass pass) @@ -118,7 +114,9 @@ private bgfx.FrameBufferHandle FindCachedFrameBuffer(CompiledRenderPass pass) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[cacheIndex]; if (cached.attachments.Length != pass.attachments.Count) + { continue; + } bool matches = true; for (int attachmentIndex = 0; attachmentIndex < pass.attachments.Count; attachmentIndex++) @@ -130,15 +128,17 @@ private bgfx.FrameBufferHandle FindCachedFrameBuffer(CompiledRenderPass pass) || signature.slot != attachment.slot || signature.isDepth != attachment.isDepth || signature.mipLevel != attachment.mipLevel - || signature.arrayLayer != attachment.arrayLayer) - { + || signature.arrayLayer != attachment.arrayLayer + ) { matches = false; break; } } if (!matches) + { continue; + } cached.lastUsedSubmission = m_submissionSequence; return cached.handle; @@ -153,8 +153,8 @@ private void RetireSupersededFrameBuffer(string passName) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!string.Equals(cached.passName, passName, StringComparison.Ordinal) - || cached.lastUsedSubmission == m_submissionSequence) - { + || cached.lastUsedSubmission == m_submissionSequence + ) { continue; } @@ -187,7 +187,9 @@ ref byte clearStencil { clearFlags |= bgfx.ClearFlags.Depth; if (descriptor.format == RenderTextureFormat.Depth24Stencil8) + { clearFlags |= bgfx.ClearFlags.Stencil; + } clearDepth = attachment.clearDepth; clearStencil = attachment.clearStencil; } @@ -201,8 +203,8 @@ ref byte clearStencil if (attachment.storeAction == RenderStoreAction.Discard) { clearFlags |= attachment.isDepth - ? bgfx.ClearFlags.DiscardDepth - : ColorDiscardFlag(attachment.slot); + ? bgfx.ClearFlags.DiscardDepth + : ColorDiscardFlag(attachment.slot); } } } @@ -213,12 +215,28 @@ private void RemoveCachedFrameBuffersReferencing(ushort textureIndex) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!cached.ContainsTexture(textureIndex)) + { continue; + } EnqueueDestroy(DeferredResource.ForFrameBuffer(cached.handle)); m_graphFrameBufferCache.RemoveAt(index); } } + private static bgfx.ClearFlags ColorDiscardFlag(int slot) + => slot switch + { + 0 => bgfx.ClearFlags.DiscardColor0, + 1 => bgfx.ClearFlags.DiscardColor1, + 2 => bgfx.ClearFlags.DiscardColor2, + 3 => bgfx.ClearFlags.DiscardColor3, + 4 => bgfx.ClearFlags.DiscardColor4, + 5 => bgfx.ClearFlags.DiscardColor5, + 6 => bgfx.ClearFlags.DiscardColor6, + 7 => bgfx.ClearFlags.DiscardColor7, + _ => throw new ArgumentOutOfRangeException(nameof(slot)) + }; + private readonly record struct GraphAttachmentSignature( ushort textureIndex, int slot, @@ -243,25 +261,12 @@ internal bool ContainsTexture(ushort textureIndex) foreach (GraphAttachmentSignature attachment in attachments) { if (attachment.textureIndex == textureIndex) + { return true; + } } return false; } } - - private static bgfx.ClearFlags ColorDiscardFlag(int slot) - => slot switch - { - 0 => bgfx.ClearFlags.DiscardColor0, - 1 => bgfx.ClearFlags.DiscardColor1, - 2 => bgfx.ClearFlags.DiscardColor2, - 3 => bgfx.ClearFlags.DiscardColor3, - 4 => bgfx.ClearFlags.DiscardColor4, - 5 => bgfx.ClearFlags.DiscardColor5, - 6 => bgfx.ClearFlags.DiscardColor6, - 7 => bgfx.ClearFlags.DiscardColor7, - _ => throw new ArgumentOutOfRangeException(nameof(slot)) - }; - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs index bafa4f3fd..66a67d70d 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Begins a frame-scoped operation and makes queued work visible. @@ -46,13 +46,14 @@ public void BeginFrame() if (m_resetPending) { m_resetPending = false; - if (capabilities.backend != GraphicsApi.Noop) + if (capabilities.backend != GraphicsApi.noop) { bgfx.reset( checked((uint)m_backbufferWidth), checked((uint)m_backbufferHeight), m_resetFlags, - bgfx.TextureFormat.Count); + bgfx.TextureFormat.Count + ); } } @@ -92,12 +93,12 @@ public uint EndFrame() throw new InvalidOperationException("No BGFX frame is open."); } - if (m_activeGraph is not null || m_activeEncoder != null) + if (m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException("All render graphs and encoders must end before BGFX frame submission."); } - if (m_nextViewId == 0) + if (m_nextViewID == 0) { bgfx.touch(0); } @@ -124,9 +125,13 @@ public void SetPrimaryPresentationSize(RenderPresentationSize? size) EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); if (size is RenderPresentationSize assigned && !assigned.isValid) + { throw new ArgumentException("A primary presentation extent must have positive pixel dimensions.", nameof(size)); + } if (size.HasValue && !m_hasPrimarySurface) + { throw new NotSupportedException("A windowless BGFX device has no primary presentation surface."); + } m_pendingPresentationSize = size; m_presentationUpdatePending = true; } @@ -143,22 +148,23 @@ public void SetVerticalSync(bool enabled) EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); uint next = enabled - ? m_resetFlags | (uint)bgfx.ResetFlags.Vsync - : m_resetFlags & ~(uint)bgfx.ResetFlags.Vsync; + ? m_resetFlags | (uint)bgfx.ResetFlags.Vsync + : m_resetFlags & ~(uint)bgfx.ResetFlags.Vsync; if (next == m_resetFlags) + { return; + } m_resetFlags = next; m_resetPending = true; } private void ResetPreviousViews() { - for (int viewIndex = 0; viewIndex < m_nextViewId; viewIndex++) + for (int viewIndex = 0; viewIndex < m_nextViewID; viewIndex++) { bgfx.reset_view(checked((ushort)viewIndex)); } - m_nextViewId = 0; + m_nextViewID = 0; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs index 0177acbc6..229eccc6a 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Begins recording commands for one validated compiled render graph. @@ -29,16 +29,17 @@ public void BeginGraph(CompiledRenderGraph graph) } int requestedViews = graph.passes.Count; - if (requestedViews > capabilities.limits.maxViews - m_nextViewId) + if (requestedViews > capabilities.limits.maxViews - m_nextViewID) { throw new InvalidOperationException( - $"Frame requires at least {m_nextViewId + requestedViews} views, " + $"Frame requires at least {m_nextViewID + requestedViews} views, " + $"but the device supports {capabilities.limits.maxViews}. " - + "Reduce active cameras, viewports, or render passes."); + + "Reduce active cameras, viewports, or render passes." + ); } m_activeGraph = graph; - m_activeGraphViewBase = m_nextViewId; + m_activeGraphViewBase = m_nextViewID; m_graphTextures.Clear(); m_transientTextureSlots.Clear(); m_transientTextureSlotDescriptors.Clear(); @@ -67,17 +68,15 @@ public void BeginGraph(CompiledRenderGraph graph) if (!m_transientTextureSlots.TryGetValue(texture.physicalSlot, out nativeTexture)) { - nativeTexture = AcquireTransientTexture( - texture.descriptor, - texture.name, - texture.physicalSlot); + nativeTexture = AcquireTransientTexture(texture.descriptor, texture.name, texture.physicalSlot); m_transientTextureSlots.Add(texture.physicalSlot, nativeTexture); m_transientTextureSlotDescriptors.Add(texture.physicalSlot, texture.descriptor); } else if (!m_transientTextureSlotDescriptors[texture.physicalSlot].Equals(texture.descriptor)) { throw new InvalidOperationException( - $"Render-graph physical texture slot {texture.physicalSlot} aliases incompatible descriptors."); + $"Render-graph physical texture slot {texture.physicalSlot} aliases incompatible descriptors." + ); } } @@ -95,10 +94,11 @@ public void BeginGraph(CompiledRenderGraph graph) bgfx.Raw.set_view_order( checked((ushort)m_activeGraphViewBase), checked((ushort)graph.passes.Count), - order); + order + ); } - m_nextViewId += requestedViews; + m_nextViewID += requestedViews; } catch { @@ -120,32 +120,33 @@ public void BeginGraph(CompiledRenderGraph graph) public RenderCommandEncoder BeginPass(CompiledRenderPass pass) { ArgumentNullException.ThrowIfNull(pass); - if (m_activeGraph is null || m_activeEncoder != null) + if (m_activeGraph is null || m_activeEncoder is not null) { throw new InvalidOperationException("Pass execution is outside a valid BGFX graph scope."); } - ushort viewId = checked((ushort)(m_activeGraphViewBase + pass.viewIndex)); + ushort viewID = checked((ushort)(m_activeGraphViewBase + pass.viewIndex)); int viewNameLength = Encoding.UTF8.GetByteCount(pass.name); Span viewNameBytes = viewNameLength < 256 - ? stackalloc byte[256] : new byte[checked(viewNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(viewNameLength + 1)]; Encoding.UTF8.GetBytes(pass.name, viewNameBytes); viewNameBytes[viewNameLength] = 0; fixed (byte* viewNamePointer = viewNameBytes) { - bgfx.Raw.set_view_name(viewId, (sbyte*)viewNamePointer, viewNameLength); + bgfx.Raw.set_view_name(viewID, (sbyte*)viewNamePointer, viewNameLength); } - bgfx.set_view_mode(viewId, bgfx.ViewMode.Sequential); - ApplyViewTransform(viewId, pass.viewTransform); - ConfigureViewTarget(viewId, pass); + bgfx.set_view_mode(viewID, bgfx.ViewMode.Sequential); + ApplyViewTransform(viewID, pass.viewTransform); + ConfigureViewTarget(viewID, pass); m_activeEncoder = bgfx.Raw.encoder_begin(0); - if (m_activeEncoder == null) + if (m_activeEncoder is null) { throw new InvalidOperationException($"BGFX could not acquire an encoder for pass '{pass.name}'."); } - bgfx.Raw.encoder_touch(m_activeEncoder, viewId); - return new BgfxCommandEncoder(this, m_activeEncoder, viewId); + bgfx.Raw.encoder_touch(m_activeEncoder, viewID); + return new BgfxCommandEncoder(this, m_activeEncoder, viewID); } /// @@ -157,7 +158,7 @@ public RenderCommandEncoder BeginPass(CompiledRenderPass pass) public void EndPass(CompiledRenderPass pass) { ArgumentNullException.ThrowIfNull(pass); - if (m_activeEncoder == null) + if (m_activeEncoder is null) { throw new InvalidOperationException("No BGFX encoder is active."); } @@ -175,7 +176,7 @@ public void EndPass(CompiledRenderPass pass) public void EndGraph(CompiledRenderGraph graph) { ArgumentNullException.ThrowIfNull(graph); - if (!ReferenceEquals(m_activeGraph, graph) || m_activeEncoder != null) + if (!ReferenceEquals(m_activeGraph, graph) || m_activeEncoder is not null) { throw new InvalidOperationException("BGFX graph cleanup does not match the active graph state."); } @@ -188,13 +189,23 @@ public void EndGraph(CompiledRenderGraph graph) m_activeGraphViewBase = 0; } + private void ReleasePreparedGraphResources() + { + ReturnTransientGraphResources(); + m_graphFrameBuffers.Clear(); + m_graphTextures.Clear(); + m_graphBuffers.Clear(); + m_activeGraph = null; + m_activeGraphViewBase = 0; + } + private static void ApplyViewTransform( - ushort viewId, + ushort viewID, RenderViewTransform? transform ) { if (transform is null) { - bgfx.Raw.set_view_transform(viewId, null, null); + bgfx.Raw.set_view_transform(viewID, null, null); return; } @@ -203,18 +214,7 @@ private static void ApplyViewTransform( fixed (float* viewPointer = view) fixed (float* projectionPointer = projection) { - bgfx.Raw.set_view_transform(viewId, viewPointer, projectionPointer); + bgfx.Raw.set_view_transform(viewID, viewPointer, projectionPointer); } } - - private void ReleasePreparedGraphResources() - { - ReturnTransientGraphResources(); - m_graphFrameBuffers.Clear(); - m_graphTextures.Clear(); - m_graphBuffers.Clear(); - m_activeGraph = null; - m_activeGraphViewBase = 0; - } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs index 2eee672e2..5514585d4 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Schedules asynchronous texture readback into caller-provided destination storage. @@ -33,16 +33,19 @@ public RenderTextureReadbackHandle BeginTextureReadback( ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ValidatePersistentHandle(texture); if (!capabilities.Supports(GraphicsCapability.TextureReadback)) + { throw new NotSupportedException("The active BGFX renderer does not support texture readback."); + } if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if ((descriptor.usage & RenderTextureUsage.Readback) == 0) + { throw new ArgumentException("Texture was not created for readback.", nameof(texture)); - if (mipLevel >= descriptor.mipCount) - throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(mipLevel, descriptor.mipCount); int width = Math.Max(1, descriptor.width >> mipLevel); int height = Math.Max(1, descriptor.height >> mipLevel); int layers = descriptor.GetSubresourceLayerCount(mipLevel); @@ -59,7 +62,7 @@ public RenderTextureReadbackHandle BeginTextureReadback( NativeMemory.Free(data); throw; } - ulong id = m_nextReadbackId++; + ulong id = m_nextReadbackID++; m_textureReadbacks.Add( id, new PendingTextureReadback( @@ -68,7 +71,9 @@ public RenderTextureReadbackHandle BeginTextureReadback( rowPitch, byteCount, (nint)data, - checked(m_submissionSequence + unchecked(readyFrame - m_backendFrame)))); + checked(m_submissionSequence + unchecked(readyFrame - m_backendFrame)) + ) + ); return CreateRenderTextureReadbackHandle(id, generation); } @@ -91,22 +96,24 @@ out RenderTextureReadbackResult? result EnsureFrameSafetyPoint(); ValidateReadbackHandle(readback); if (!m_textureReadbacks.TryGetValue(GetHandleIdentity(readback).value, out PendingTextureReadback? pending)) + { throw new ArgumentException("Texture readback is not active on this device.", nameof(readback)); + } result = null; if (m_submissionSequence < pending.readySubmission) + { return false; + } m_textureReadbacks.Remove(GetHandleIdentity(readback).value); try { if (pending.canceled) + { return false; - byte[] bytes = new byte[pending.byteCount]; + } + var bytes = new byte[pending.byteCount]; Marshal.Copy(pending.data, bytes, 0, bytes.Length); - result = new RenderTextureReadbackResult( - pending.descriptor, - pending.mipLevel, - pending.rowPitch, - bytes); + result = new RenderTextureReadbackResult(pending.descriptor, pending.mipLevel, pending.rowPitch, bytes); return true; } finally @@ -126,7 +133,9 @@ public void CancelTextureReadback(RenderTextureReadbackHandle readback) EnsureFrameSafetyPoint(); ValidateReadbackHandle(readback); if (m_textureReadbacks.TryGetValue(GetHandleIdentity(readback).value, out PendingTextureReadback? pending)) + { pending.canceled = true; + } } private void ProcessCanceledReadbacks() @@ -134,7 +143,9 @@ private void ProcessCanceledReadbacks() foreach ((ulong id, PendingTextureReadback pending) in m_textureReadbacks.ToArray()) { if (!pending.canceled || m_submissionSequence < pending.readySubmission) + { continue; + } NativeMemory.Free((void*)pending.data); m_textureReadbacks.Remove(id); } @@ -143,7 +154,9 @@ private void ProcessCanceledReadbacks() private void ValidateReadbackHandle(RenderTextureReadbackHandle readback) { if (!readback.isValid || GetHandleIdentity(readback).generation != generation) + { throw new ArgumentException("Texture readback belongs to another device generation.", nameof(readback)); + } } private sealed class PendingTextureReadback( @@ -162,5 +175,4 @@ ulong readySubmission internal ulong readySubmission { get; } = readySubmission; internal bool canceled { get; set; } } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs index 6db2cf4a8..9c3868a6f 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs @@ -49,11 +49,12 @@ string name { throw new ArgumentException( $"Initial buffer data must contain exactly {expectedSize} bytes.", - nameof(initialData)); + nameof(initialData) + ); } BgfxBufferResource resource = CreateNativeBuffer(descriptor, initialData, name); - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_persistentBuffers.Add(id, resource); return CreatePersistentBufferHandle(id, generation); } @@ -104,7 +105,8 @@ public void UpdateBuffer( if (resource.kind == BgfxBufferKind.Indirect) { throw new NotSupportedException( - "BGFX indirect command buffers are populated by compute shaders, not CPU updates."); + "BGFX indirect command buffers are populated by compute shaders, not CPU updates." + ); } if ((resource.descriptor.usage & RenderBufferUsage.Dynamic) == 0) { @@ -129,13 +131,15 @@ public void UpdateBuffer( BgfxNativeCalls.UpdateDynamicVertexBuffer( new bgfx.DynamicVertexBufferHandle { idx = resource.nativeIndex }, checked((uint)startElement), - memory); + memory + ); break; case BgfxBufferKind.DynamicIndex: BgfxNativeCalls.UpdateDynamicIndexBuffer( new bgfx.DynamicIndexBufferHandle { idx = resource.nativeIndex }, checked((uint)startElement), - memory); + memory + ); break; default: throw new InvalidOperationException("A Dynamic descriptor resolved to an immutable BGFX buffer."); @@ -162,7 +166,7 @@ string name ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); BgfxPipelineResource resource = CreateGraphicsPipelineResource(descriptor, name); - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_graphicsPipelines.Add(id, resource); return CreateGraphicsPipelineHandle(id, generation); } @@ -214,7 +218,7 @@ string name } BgfxPipelineResource resource = CreateComputePipelineResource(descriptor, name); - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_computePipelines.Add(id, resource); return CreateComputePipelineHandle(id, generation); } @@ -263,8 +267,8 @@ internal BgfxBufferResource ResolveBuffer(RenderBufferHandle buffer) { if (m_activeGraph is null || GetHandleIdentity(buffer).generation != m_activeGraph.generation - || !m_graphBuffers.TryGetValue(GetHandleIdentity(buffer).index, out BgfxBufferResource? resource)) - { + || !m_graphBuffers.TryGetValue(GetHandleIdentity(buffer).index, out BgfxBufferResource? resource) + ) { throw new ArgumentException("Buffer is not active in the current BGFX graph.", nameof(buffer)); } @@ -317,7 +321,8 @@ private void PrepareGraphBuffers(CompiledRenderGraph graph) if (!resource.descriptor.Equals(buffer.descriptor)) { throw new InvalidOperationException( - $"Imported buffer '{buffer.name}' does not match its persistent descriptor."); + $"Imported buffer '{buffer.name}' does not match its persistent descriptor." + ); } } else @@ -335,7 +340,8 @@ private void PrepareGraphBuffers(CompiledRenderGraph graph) else if (!resource.descriptor.Equals(buffer.descriptor)) { throw new InvalidOperationException( - $"Render-graph physical buffer slot {buffer.physicalSlot} aliases incompatible descriptors."); + $"Render-graph physical buffer slot {buffer.physicalSlot} aliases incompatible descriptors." + ); } } @@ -350,18 +356,20 @@ string name ) { RenderBufferDescriptor buffer = descriptor.buffer; if ((buffer.usage & RenderBufferUsage.Indirect) != 0 - && (buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0) - { + && (buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0 + ) { if (!capabilities.Supports(GraphicsCapability.Indirect)) + { throw new NotSupportedException("The active backend does not support indirect command buffers."); + } if (!initialData.IsEmpty) { throw new ArgumentException( "BGFX indirect buffers cannot be initialized from CPU data.", - nameof(initialData)); + nameof(initialData) + ); } - bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer( - checked((uint)buffer.elementCount)); + bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer(checked((uint)buffer.elementCount)); EnsureValid(indirect.Valid, name); return BgfxBufferResource.FromIndirect(buffer, indirect); } @@ -369,8 +377,8 @@ string name bool dynamic = (buffer.usage & (RenderBufferUsage.Dynamic | RenderBufferUsage.Storage)) != 0; if (indexBuffer && descriptor.indexFormat == RenderIndexFormat.UInt32 - && !capabilities.Supports(GraphicsCapability.Index32)) - { + && !capabilities.Supports(GraphicsCapability.Index32) + ) { throw new NotSupportedException("The active backend does not support unsigned 32-bit indices."); } ValidateVertexLayoutCapabilities(descriptor.vertexLayout); @@ -387,7 +395,8 @@ string name { bgfx.DynamicIndexBufferHandle handle = bgfx.create_dynamic_index_buffer( checked((uint)buffer.elementCount), - flags); + flags + ); EnsureValid(handle.Valid, name); if (!initialData.IsEmpty) { @@ -401,7 +410,8 @@ string name EnsureValid(staticHandle.Valid, name); int indexBufferNameLength = Encoding.UTF8.GetByteCount(name); Span indexBufferNameBytes = indexBufferNameLength < 256 - ? stackalloc byte[256] : new byte[checked(indexBufferNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(indexBufferNameLength + 1)]; Encoding.UTF8.GetBytes(name, indexBufferNameBytes); indexBufferNameBytes[indexBufferNameLength] = 0; fixed (byte* indexBufferNamePointer = indexBufferNameBytes) @@ -415,19 +425,19 @@ string name bool storageBuffer = (buffer.usage & RenderBufferUsage.Storage) != 0; if (!vertexBuffer && !storageBuffer) { - throw new NotSupportedException( - "BGFX persistent buffers must be vertex, index, or storage resources."); + throw new NotSupportedException("BGFX persistent buffers must be vertex, index, or storage resources."); } bgfx.VertexLayout nativeLayout = descriptor.vertexLayout is null - ? CreateSkippedLayout(buffer.elementStride) - : CreateNativeLayout(descriptor.vertexLayout); + ? CreateSkippedLayout(buffer.elementStride) + : CreateNativeLayout(descriptor.vertexLayout); if (initialData.IsEmpty || dynamic) { bgfx.DynamicVertexBufferHandle handle = BgfxNativeCalls.CreateDynamicVertexBuffer( checked((uint)buffer.elementCount), &nativeLayout, - flags); + flags + ); EnsureValid(handle.Valid, name); if (!initialData.IsEmpty) { @@ -441,7 +451,8 @@ string name EnsureValid(vertexHandle.Valid, name); int vertexBufferNameLength = Encoding.UTF8.GetByteCount(name); Span vertexBufferNameBytes = vertexBufferNameLength < 256 - ? stackalloc byte[256] : new byte[checked(vertexBufferNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(vertexBufferNameLength + 1)]; Encoding.UTF8.GetBytes(name, vertexBufferNameBytes); vertexBufferNameBytes[vertexBufferNameLength] = 0; fixed (byte* vertexBufferNamePointer = vertexBufferNameBytes) @@ -454,12 +465,13 @@ string name private BgfxBufferResource CreateTransientBuffer(RenderBufferDescriptor descriptor) { if ((descriptor.usage & RenderBufferUsage.Indirect) != 0 - && (descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0) - { + && (descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0 + ) { if (!capabilities.Supports(GraphicsCapability.Indirect)) + { throw new NotSupportedException("The active backend does not support indirect command buffers."); - bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer( - checked((uint)descriptor.elementCount)); + } + bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer(checked((uint)descriptor.elementCount)); EnsureValid(indirect.Valid, "transient indirect buffer"); return BgfxBufferResource.FromIndirect(descriptor, indirect); } @@ -472,28 +484,29 @@ private BgfxBufferResource CreateTransientBuffer(RenderBufferDescriptor descript _ => throw new NotSupportedException("Transient index buffers require a two- or four-byte stride.") }; if (format == RenderIndexFormat.UInt32 - && !capabilities.Supports(GraphicsCapability.Index32)) - { + && !capabilities.Supports(GraphicsCapability.Index32) + ) { throw new NotSupportedException("The active backend does not support unsigned 32-bit indices."); } bgfx.DynamicIndexBufferHandle index = bgfx.create_dynamic_index_buffer( checked((uint)descriptor.elementCount), - BufferFlags(descriptor, format)); + BufferFlags(descriptor, format) + ); EnsureValid(index.Valid, "transient index buffer"); return BgfxBufferResource.FromDynamicIndex(descriptor, format, index); } if ((descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Storage)) == 0) { - throw new NotSupportedException( - "BGFX transient buffers must be vertex, index, or storage resources."); + throw new NotSupportedException("BGFX transient buffers must be vertex, index, or storage resources."); } bgfx.VertexLayout layout = CreateSkippedLayout(descriptor.elementStride); bgfx.DynamicVertexBufferHandle vertex = BgfxNativeCalls.CreateDynamicVertexBuffer( checked((uint)descriptor.elementCount), &layout, - BufferFlags(descriptor, RenderIndexFormat.UInt32)); + BufferFlags(descriptor, RenderIndexFormat.UInt32) + ); EnsureValid(vertex.Valid, "transient vertex or storage buffer"); return BgfxBufferResource.FromDynamicVertex(descriptor, null, vertex); } @@ -506,8 +519,8 @@ int physicalSlot { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (pooled.physicalSlot != physicalSlot - || !pooled.resource.descriptor.Equals(descriptor)) - { + || !pooled.resource.descriptor.Equals(descriptor) + ) { continue; } m_transientBufferPool.RemoveAt(index); @@ -518,7 +531,9 @@ int physicalSlot { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (!pooled.resource.descriptor.Equals(descriptor)) + { continue; + } m_transientBufferPool.RemoveAt(index); return pooled.resource; } @@ -543,8 +558,7 @@ string name vertexShader = CreateShader(descriptor.vertexShader.Span, $"{name}.Vertex"); fragmentShader = CreateShader(descriptor.fragmentShader.Span, $"{name}.Fragment"); Dictionary reflected = ReflectShaders(vertexShader, fragmentShader); - IReadOnlyDictionary bindings = - ValidateReflectedBindings(descriptor.bindings, reflected); + IReadOnlyDictionary bindings = ValidateReflectedBindings(descriptor.bindings, reflected); program = bgfx.create_program(vertexShader, fragmentShader, true); EnsureValid(program.Valid, name); @@ -562,7 +576,8 @@ string name descriptor.vertexLayout, layoutHandle, descriptor.rasterState, - false); + false + ); } catch { @@ -586,21 +601,25 @@ string name private void ValidateVertexLayoutCapabilities(RenderVertexLayout? layout) { if (layout is null) + { return; + } foreach (RenderVertexAttribute attribute in layout.attributes) { if (attribute.format is RenderVertexFormat.Half2 or RenderVertexFormat.Half4 - && !capabilities.Supports(GraphicsCapability.VertexAttributeHalf)) - { + && !capabilities.Supports(GraphicsCapability.VertexAttributeHalf) + ) { throw new NotSupportedException( - "The active backend does not support half-precision vertex attributes."); + "The active backend does not support half-precision vertex attributes." + ); } if (attribute.format == RenderVertexFormat.UInt10Normalized4 - && !capabilities.Supports(GraphicsCapability.VertexAttributeUInt10)) - { + && !capabilities.Supports(GraphicsCapability.VertexAttributeUInt10) + ) { throw new NotSupportedException( - "The active backend does not support packed 10:10:10:2 vertex attributes."); + "The active backend does not support packed 10:10:10:2 vertex attributes." + ); } } } @@ -608,10 +627,9 @@ private void ValidateVertexLayoutCapabilities(RenderVertexLayout? layout) private void ValidateRasterStateCapabilities(RenderRasterState state) { if (state.blend.alphaToCoverage - && !capabilities.Supports(GraphicsCapability.AlphaToCoverage)) - { - throw new NotSupportedException( - "The active backend does not support alpha-to-coverage rasterization."); + && !capabilities.Supports(GraphicsCapability.AlphaToCoverage) + ) { + throw new NotSupportedException("The active backend does not support alpha-to-coverage rasterization."); } } @@ -626,18 +644,11 @@ string name { computeShader = CreateShader(descriptor.computeShader.Span, $"{name}.Compute"); Dictionary reflected = ReflectShaders(computeShader); - IReadOnlyDictionary bindings = - ValidateReflectedBindings(descriptor.bindings, reflected); + IReadOnlyDictionary bindings = ValidateReflectedBindings(descriptor.bindings, reflected); program = bgfx.create_compute_program(computeShader, true); EnsureValid(program.Valid, name); computeShader = InvalidShader(); - return new BgfxPipelineResource( - program, - bindings, - null, - InvalidVertexLayout(), - null, - true); + return new BgfxPipelineResource(program, bindings, null, InvalidVertexLayout(), null, true); } catch { @@ -652,97 +663,6 @@ string name } } - private static IReadOnlyDictionary ValidateReflectedBindings( - IReadOnlyList declaredBindings, - IReadOnlyDictionary reflected - ) { - Dictionary declared = declaredBindings - .ToDictionary(static value => value.nativeName, StringComparer.Ordinal); - foreach ((string name, ReflectedUniform uniform) in reflected) - { - if (!declared.TryGetValue(name, out RenderShaderBindingDescriptor? binding) - || binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture) - { - throw new InvalidOperationException( - $"Shader reflection contains undeclared uniform '{name}'."); - } - - bgfx.UniformType expectedType = binding.kind == RenderShaderBindingKind.Texture - ? bgfx.UniformType.Sampler - : ToNativeUniformType(binding.uniformType); - if (uniform.type != expectedType || uniform.count != binding.count) - { - throw new InvalidOperationException( - $"Shader binding '{name}' reflected as {uniform.type}[{uniform.count}] but the manifest requires " - + $"{expectedType}[{binding.count}]."); - } - } - - Dictionary result = new(StringComparer.Ordinal); - foreach (RenderShaderBindingDescriptor binding in declaredBindings) - { - if (binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture) - { - result.Add(binding.id.value, new BgfxShaderBindingResource(binding, InvalidUniform())); - continue; - } - - if (!reflected.TryGetValue(binding.nativeName, out ReflectedUniform uniform)) - { - throw new InvalidOperationException( - $"Shader manifest binding '{binding.id.value}' is absent from compiled reflection."); - } - - result.Add(binding.id.value, new BgfxShaderBindingResource(binding, uniform.handle)); - } - - return result; - } - - private static Dictionary ReflectShaders(params bgfx.ShaderHandle[] shaders) - { - Dictionary result = new(StringComparer.Ordinal); - foreach (bgfx.ShaderHandle shader in shaders) - { - ushort count = BgfxNativeCalls.GetShaderUniforms(shader, null, 0); - if (count == 0) - { - continue; - } - - bgfx.UniformHandle[] uniforms = new bgfx.UniformHandle[count]; - fixed (bgfx.UniformHandle* handles = uniforms) - { - ushort written = BgfxNativeCalls.GetShaderUniforms(shader, handles, count); - for (int index = 0; index < written; index++) - { - bgfx.UniformInfo info = default; - BgfxNativeCalls.GetUniformInfo(uniforms[index], &info); - string name = UniformName(info); - ReflectedUniform reflected = new(uniforms[index], info.type, info.num); - if (result.TryGetValue(name, out ReflectedUniform current) - && (current.type != reflected.type || current.count != reflected.count)) - { - throw new InvalidOperationException( - $"Shader stages disagree about reflected binding '{name}'."); - } - - result[name] = reflected; - } - } - } - - return result; - } - - private static string UniformName(bgfx.UniformInfo info) - { - ReadOnlySpan nativeName = info.name; - ReadOnlySpan name = MemoryMarshal.AsBytes(nativeName); - int terminator = name.IndexOf((byte)0); - return Encoding.UTF8.GetString(terminator >= 0 ? name[..terminator] : name); - } - private bgfx.ShaderHandle CreateShader( ReadOnlySpan binary, string name @@ -752,7 +672,8 @@ string name EnsureValid(shader.Valid, name); int shaderNameLength = Encoding.UTF8.GetByteCount(name); Span shaderNameBytes = shaderNameLength < 256 - ? stackalloc byte[256] : new byte[checked(shaderNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(shaderNameLength + 1)]; Encoding.UTF8.GetBytes(name, shaderNameBytes); shaderNameBytes[shaderNameLength] = 0; fixed (byte* shaderNamePointer = shaderNameBytes) @@ -777,7 +698,8 @@ private bgfx.VertexLayout CreateNativeLayout(RenderVertexLayout layout) count, type, normalized ? (byte)1 : (byte)0, - asInteger ? (byte)1 : (byte)0); + asInteger ? (byte)1 : (byte)0 + ); currentOffset = checked(attribute.byteOffset + attribute.byteSize); } @@ -787,26 +709,13 @@ private bgfx.VertexLayout CreateNativeLayout(RenderVertexLayout layout) if (native.stride != layout.stride) { throw new InvalidOperationException( - $"BGFX produced vertex stride {native.stride}, expected {layout.stride}."); + $"BGFX produced vertex stride {native.stride}, expected {layout.stride}." + ); } return native; } - private static void AddVertexLayoutPadding( - bgfx.VertexLayout* layout, - int byteCount - ) { - if (byteCount < 0) - throw new InvalidOperationException("A resolved vertex layout cannot contain overlapping attributes."); - while (byteCount != 0) - { - byte chunk = checked((byte)Math.Min(byteCount, byte.MaxValue)); - bgfx.Raw.vertex_layout_skip(layout, chunk); - byteCount -= chunk; - } - } - private bgfx.VertexLayout CreateSkippedLayout(int stride) { bgfx.VertexLayout native = default; @@ -823,60 +732,6 @@ private bgfx.VertexLayout CreateSkippedLayout(int stride) return native; } - private static (byte count, bgfx.AttribType type, bool normalized, bool asInteger) AttributeFormat(RenderVertexFormat format) - => format switch - { - RenderVertexFormat.Float1 => (1, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float2 => (2, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float3 => (3, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float4 => (4, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Half2 => (2, bgfx.AttribType.Half, false, false), - RenderVertexFormat.Half4 => (4, bgfx.AttribType.Half, false, false), - RenderVertexFormat.UInt8Normalized2 => (2, bgfx.AttribType.Uint8, true, false), - RenderVertexFormat.UInt8Normalized4 => (4, bgfx.AttribType.Uint8, true, false), - RenderVertexFormat.UInt8Integer2 => (2, bgfx.AttribType.Uint8, false, true), - RenderVertexFormat.UInt8Integer4 => (4, bgfx.AttribType.Uint8, false, true), - RenderVertexFormat.UInt10Normalized4 => (4, bgfx.AttribType.Uint10, true, false), - RenderVertexFormat.Int16Normalized2 => (2, bgfx.AttribType.Int16, true, false), - RenderVertexFormat.Int16Normalized4 => (4, bgfx.AttribType.Int16, true, false), - RenderVertexFormat.Int16Integer2 => (2, bgfx.AttribType.Int16, false, true), - RenderVertexFormat.Int16Integer4 => (4, bgfx.AttribType.Int16, false, true), - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; - - private static bgfx.Attrib ToNativeAttribute(RenderVertexSemantic semantic) - => semantic switch - { - RenderVertexSemantic.Position => bgfx.Attrib.Position, - RenderVertexSemantic.Normal => bgfx.Attrib.Normal, - RenderVertexSemantic.Tangent => bgfx.Attrib.Tangent, - RenderVertexSemantic.Bitangent => bgfx.Attrib.Bitangent, - RenderVertexSemantic.Color0 => bgfx.Attrib.Color0, - RenderVertexSemantic.Color1 => bgfx.Attrib.Color1, - RenderVertexSemantic.Color2 => bgfx.Attrib.Color2, - RenderVertexSemantic.Color3 => bgfx.Attrib.Color3, - RenderVertexSemantic.TextureCoordinate0 => bgfx.Attrib.TexCoord0, - RenderVertexSemantic.TextureCoordinate1 => bgfx.Attrib.TexCoord1, - RenderVertexSemantic.TextureCoordinate2 => bgfx.Attrib.TexCoord2, - RenderVertexSemantic.TextureCoordinate3 => bgfx.Attrib.TexCoord3, - RenderVertexSemantic.TextureCoordinate4 => bgfx.Attrib.TexCoord4, - RenderVertexSemantic.TextureCoordinate5 => bgfx.Attrib.TexCoord5, - RenderVertexSemantic.TextureCoordinate6 => bgfx.Attrib.TexCoord6, - RenderVertexSemantic.TextureCoordinate7 => bgfx.Attrib.TexCoord7, - RenderVertexSemantic.BlendIndices => bgfx.Attrib.Indices, - RenderVertexSemantic.BlendWeights => bgfx.Attrib.Weight, - _ => throw new ArgumentOutOfRangeException(nameof(semantic)) - }; - - private static bgfx.UniformType ToNativeUniformType(RenderUniformType type) - => type switch - { - RenderUniformType.Vector4 => bgfx.UniformType.Vec4, - RenderUniformType.Matrix3x3 => bgfx.UniformType.Mat3, - RenderUniformType.Matrix4x4 => bgfx.UniformType.Mat4, - _ => throw new ArgumentOutOfRangeException(nameof(type)) - }; - private void ValidateBindingSlots( IReadOnlyList bindings, bool allowStorageResources @@ -885,34 +740,40 @@ bool allowStorageResources foreach (RenderShaderBindingDescriptor binding in bindings) { if (binding.kind is RenderShaderBindingKind.Texture - or RenderShaderBindingKind.StorageTexture - or RenderShaderBindingKind.StorageBuffer - && binding.slot > byte.MaxValue) - { + or RenderShaderBindingKind.StorageTexture + or RenderShaderBindingKind.StorageBuffer + && binding.slot > byte.MaxValue + ) { throw new ArgumentOutOfRangeException( nameof(bindings), - $"Binding '{binding.id.value}' slot exceeds the BGFX byte-sized stage range."); + $"Binding '{binding.id.value}' slot exceeds the BGFX byte-sized stage range." + ); } if (binding.kind is not (RenderShaderBindingKind.StorageTexture or RenderShaderBindingKind.StorageBuffer)) + { continue; + } if (!allowStorageResources) { throw new NotSupportedException( - $"BGFX graphics pipelines cannot bind storage resource '{binding.id.value}'."); + $"BGFX graphics pipelines cannot bind storage resource '{binding.id.value}'." + ); } if (!storageSlots.Add(binding.slot)) { throw new ArgumentException( $"Storage binding slot {binding.slot} is declared more than once.", - nameof(bindings)); + nameof(bindings) + ); } GraphicsCapability required = binding.kind == RenderShaderBindingKind.StorageTexture - ? GraphicsCapability.StorageTexture - : GraphicsCapability.StorageBuffer; + ? GraphicsCapability.StorageTexture + : GraphicsCapability.StorageBuffer; if (!capabilities.Supports(required)) { throw new NotSupportedException( - $"The active backend does not support {binding.kind} binding '{binding.id.value}'."); + $"The active backend does not support {binding.kind} binding '{binding.id.value}'." + ); } } @@ -921,10 +782,198 @@ or RenderShaderBindingKind.StorageBuffer { throw new NotSupportedException( $"Pipeline requires {storageCount} storage bindings, but the device supports " - + $"{capabilities.limits.maxComputeBindings}."); + + $"{capabilities.limits.maxComputeBindings}." + ); + } + } + + private void ValidatePersistentHandle(PersistentBufferHandle buffer) + { + if (!buffer.isValid || GetHandleIdentity(buffer).generation != generation) + { + throw new ArgumentException("Buffer handle belongs to another device generation.", nameof(buffer)); + } + } + + private void ValidatePersistentHandle(GraphicsPipelineHandle pipeline) + { + if (!pipeline.isValid || GetHandleIdentity(pipeline).generation != generation) + { + throw new ArgumentException("Graphics pipeline belongs to another device generation.", nameof(pipeline)); + } + } + + private void ValidatePersistentHandle(ComputePipelineHandle pipeline) + { + if (!pipeline.isValid || GetHandleIdentity(pipeline).generation != generation) + { + throw new ArgumentException("Compute pipeline belongs to another device generation.", nameof(pipeline)); } } + private static IReadOnlyDictionary ValidateReflectedBindings( + IReadOnlyList declaredBindings, + IReadOnlyDictionary reflected + ) { + Dictionary declared = declaredBindings + .ToDictionary(static value => value.nativeName, StringComparer.Ordinal); + foreach ((string name, ReflectedUniform uniform) in reflected) + { + if (!declared.TryGetValue(name, out RenderShaderBindingDescriptor? binding) + || binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture + ) { + throw new InvalidOperationException($"Shader reflection contains undeclared uniform '{name}'."); + } + + bgfx.UniformType expectedType = binding.kind == RenderShaderBindingKind.Texture + ? bgfx.UniformType.Sampler + : ToNativeUniformType(binding.uniformType); + if (uniform.type != expectedType || uniform.count != binding.count) + { + throw new InvalidOperationException( + $"Shader binding '{name}' reflected as {uniform.type}[{uniform.count}] but the manifest requires " + + $"{expectedType}[{binding.count}]." + ); + } + } + + var result = new Dictionary(StringComparer.Ordinal); + foreach (RenderShaderBindingDescriptor binding in declaredBindings) + { + if (binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture) + { + result.Add(binding.id.value, new BgfxShaderBindingResource(binding, InvalidUniform())); + continue; + } + + if (!reflected.TryGetValue(binding.nativeName, out ReflectedUniform uniform)) + { + throw new InvalidOperationException( + $"Shader manifest binding '{binding.id.value}' is absent from compiled reflection." + ); + } + + result.Add(binding.id.value, new BgfxShaderBindingResource(binding, uniform.handle)); + } + + return result; + } + + private static Dictionary ReflectShaders(params bgfx.ShaderHandle[] shaders) + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (bgfx.ShaderHandle shader in shaders) + { + ushort count = BgfxNativeCalls.GetShaderUniforms(shader, null, 0); + if (count == 0) + { + continue; + } + + var uniforms = new bgfx.UniformHandle[count]; + fixed (bgfx.UniformHandle* handles = uniforms) + { + ushort written = BgfxNativeCalls.GetShaderUniforms(shader, handles, count); + for (int index = 0; index < written; index++) + { + bgfx.UniformInfo info = default; + BgfxNativeCalls.GetUniformInfo(uniforms[index], &info); + string name = UniformName(info); + var reflected = new ReflectedUniform(uniforms[index], info.type, info.num); + if (result.TryGetValue(name, out ReflectedUniform current) + && (current.type != reflected.type || current.count != reflected.count) + ) { + throw new InvalidOperationException( + $"Shader stages disagree about reflected binding '{name}'." + ); + } + + result[name] = reflected; + } + } + } + + return result; + } + + private static string UniformName(bgfx.UniformInfo info) + { + ReadOnlySpan nativeName = info.name; + ReadOnlySpan name = MemoryMarshal.AsBytes(nativeName); + int terminator = name.IndexOf((byte)0); + return Encoding.UTF8.GetString(terminator >= 0 ? name[..terminator] : name); + } + + private static void AddVertexLayoutPadding( + bgfx.VertexLayout* layout, + int byteCount + ) { + if (byteCount < 0) + { + throw new InvalidOperationException("A resolved vertex layout cannot contain overlapping attributes."); + } + while (byteCount != 0) + { + byte chunk = checked((byte)Math.Min(byteCount, byte.MaxValue)); + bgfx.Raw.vertex_layout_skip(layout, chunk); + byteCount -= chunk; + } + } + + private static (byte count, bgfx.AttribType type, bool normalized, bool asInteger) AttributeFormat(RenderVertexFormat format) + => format switch + { + RenderVertexFormat.Float1 => (1, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float2 => (2, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float3 => (3, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float4 => (4, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Half2 => (2, bgfx.AttribType.Half, false, false), + RenderVertexFormat.Half4 => (4, bgfx.AttribType.Half, false, false), + RenderVertexFormat.UInt8Normalized2 => (2, bgfx.AttribType.Uint8, true, false), + RenderVertexFormat.UInt8Normalized4 => (4, bgfx.AttribType.Uint8, true, false), + RenderVertexFormat.UInt8Integer2 => (2, bgfx.AttribType.Uint8, false, true), + RenderVertexFormat.UInt8Integer4 => (4, bgfx.AttribType.Uint8, false, true), + RenderVertexFormat.UInt10Normalized4 => (4, bgfx.AttribType.Uint10, true, false), + RenderVertexFormat.Int16Normalized2 => (2, bgfx.AttribType.Int16, true, false), + RenderVertexFormat.Int16Normalized4 => (4, bgfx.AttribType.Int16, true, false), + RenderVertexFormat.Int16Integer2 => (2, bgfx.AttribType.Int16, false, true), + RenderVertexFormat.Int16Integer4 => (4, bgfx.AttribType.Int16, false, true), + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; + + private static bgfx.Attrib ToNativeAttribute(RenderVertexSemantic semantic) + => semantic switch + { + RenderVertexSemantic.Position => bgfx.Attrib.Position, + RenderVertexSemantic.Normal => bgfx.Attrib.Normal, + RenderVertexSemantic.Tangent => bgfx.Attrib.Tangent, + RenderVertexSemantic.Bitangent => bgfx.Attrib.Bitangent, + RenderVertexSemantic.Color0 => bgfx.Attrib.Color0, + RenderVertexSemantic.Color1 => bgfx.Attrib.Color1, + RenderVertexSemantic.Color2 => bgfx.Attrib.Color2, + RenderVertexSemantic.Color3 => bgfx.Attrib.Color3, + RenderVertexSemantic.TextureCoordinate0 => bgfx.Attrib.TexCoord0, + RenderVertexSemantic.TextureCoordinate1 => bgfx.Attrib.TexCoord1, + RenderVertexSemantic.TextureCoordinate2 => bgfx.Attrib.TexCoord2, + RenderVertexSemantic.TextureCoordinate3 => bgfx.Attrib.TexCoord3, + RenderVertexSemantic.TextureCoordinate4 => bgfx.Attrib.TexCoord4, + RenderVertexSemantic.TextureCoordinate5 => bgfx.Attrib.TexCoord5, + RenderVertexSemantic.TextureCoordinate6 => bgfx.Attrib.TexCoord6, + RenderVertexSemantic.TextureCoordinate7 => bgfx.Attrib.TexCoord7, + RenderVertexSemantic.BlendIndices => bgfx.Attrib.Indices, + RenderVertexSemantic.BlendWeights => bgfx.Attrib.Weight, + _ => throw new ArgumentOutOfRangeException(nameof(semantic)) + }; + + private static bgfx.UniformType ToNativeUniformType(RenderUniformType type) + => type switch + { + RenderUniformType.Vector4 => bgfx.UniformType.Vec4, + RenderUniformType.Matrix3x3 => bgfx.UniformType.Mat3, + RenderUniformType.Matrix4x4 => bgfx.UniformType.Mat4, + _ => throw new ArgumentOutOfRangeException(nameof(type)) + }; + private static ushort BufferFlags( RenderBufferDescriptor descriptor, RenderIndexFormat indexFormat @@ -1007,30 +1056,6 @@ private static void DestroyPipelineImmediately(BgfxPipelineResource pipeline) } } - private void ValidatePersistentHandle(PersistentBufferHandle buffer) - { - if (!buffer.isValid || GetHandleIdentity(buffer).generation != generation) - { - throw new ArgumentException("Buffer handle belongs to another device generation.", nameof(buffer)); - } - } - - private void ValidatePersistentHandle(GraphicsPipelineHandle pipeline) - { - if (!pipeline.isValid || GetHandleIdentity(pipeline).generation != generation) - { - throw new ArgumentException("Graphics pipeline belongs to another device generation.", nameof(pipeline)); - } - } - - private void ValidatePersistentHandle(ComputePipelineHandle pipeline) - { - if (!pipeline.isValid || GetHandleIdentity(pipeline).generation != generation) - { - throw new ArgumentException("Compute pipeline belongs to another device generation.", nameof(pipeline)); - } - } - private static bgfx.ShaderHandle InvalidShader() => new() { idx = ushort.MaxValue }; private static bgfx.ProgramHandle InvalidProgram() => new() { idx = ushort.MaxValue }; diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs index c3a82bc1f..88195d3cc 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Shuts down BGFX after releasing all active and queued backend resources. @@ -28,7 +28,7 @@ public void Dispose() } EnsureApiThread(); - if (m_activeEncoder != null || m_activeGraph is not null) + if (m_activeEncoder is not null || m_activeGraph is not null) { throw new InvalidOperationException("Cannot dispose BGFX while a render graph or encoder is active."); } @@ -45,7 +45,9 @@ public void Dispose() surface.retirement.pending.Add(surface.frameBuffer); surface.retirement.closing = true; if (!m_surfaceRetirements.Contains(surface.retirement)) + { m_surfaceRetirements.Add(surface.retirement); + } } m_windowSurfaces.Clear(); DrainWindowSurfaceRetirements(); @@ -107,7 +109,9 @@ public void Dispose() finally { foreach (PendingTextureReadback pending in m_textureReadbacks.Values) + { NativeMemory.Free((void*)pending.data); + } m_textureReadbacks.Clear(); m_disposed = true; generation = 0; @@ -115,14 +119,18 @@ public void Dispose() } if (closureFailure is not null) + { throw new InvalidOperationException(closureFailure); + } } private void EnqueueDestroy(DeferredResource resource) - => m_deferredResources.Add(resource with - { - eligibleSubmission = checked(m_submissionSequence + (ulong)m_deferredDestroyFrames) - }); + => m_deferredResources.Add( + resource with + { + eligibleSubmission = checked(m_submissionSequence + (ulong)m_deferredDestroyFrames) + } + ); private void EnqueuePipelineDestroy(BgfxPipelineResource pipeline) => EnqueueDestroy(DeferredResource.ForProgram(pipeline.program)); @@ -197,7 +205,7 @@ private void DrainDeferredResourcesForShutdown() private string? GetManagedResourceClosureFailure() { - if (m_activeEncoder != null + if (m_activeEncoder is not null || m_activeGraph is not null || m_graphFrameBuffers.Count != 0 || m_graphTextures.Count != 0 @@ -215,8 +223,8 @@ private void DrainDeferredResourcesForShutdown() || m_computePipelines.Count != 0 || m_windowSurfaces.Count != 0 || m_surfaceRetirements.Count != 0 - || m_deferredResources.Count != 0) - { + || m_deferredResources.Count != 0 + ) { return "BGFX shutdown detected a non-empty managed resource ownership graph."; } @@ -274,15 +282,19 @@ public static DeferredResource ForFrameBuffer(bgfx.FrameBufferHandle frameBuffer /// The validated deferred resource that represents the completed operation. /// public static DeferredResource ForBuffer(BgfxBufferResource buffer) - => new(buffer.kind switch - { - BgfxBufferKind.Vertex => DeferredResourceKind.VertexBuffer, - BgfxBufferKind.Index => DeferredResourceKind.IndexBuffer, - BgfxBufferKind.DynamicVertex => DeferredResourceKind.DynamicVertexBuffer, - BgfxBufferKind.DynamicIndex => DeferredResourceKind.DynamicIndexBuffer, - BgfxBufferKind.Indirect => DeferredResourceKind.IndirectBuffer, - _ => throw new ArgumentOutOfRangeException(nameof(buffer)) - }, buffer.nativeIndex, 0); + => new( + buffer.kind switch + { + BgfxBufferKind.Vertex => DeferredResourceKind.VertexBuffer, + BgfxBufferKind.Index => DeferredResourceKind.IndexBuffer, + BgfxBufferKind.DynamicVertex => DeferredResourceKind.DynamicVertexBuffer, + BgfxBufferKind.DynamicIndex => DeferredResourceKind.DynamicIndexBuffer, + BgfxBufferKind.Indirect => DeferredResourceKind.IndirectBuffer, + _ => throw new ArgumentOutOfRangeException(nameof(buffer)) + }, + buffer.nativeIndex, + 0 + ); /// /// Creates a deferred resource record for the supplied program handle. @@ -307,5 +319,4 @@ public static DeferredResource ForBuffer(BgfxBufferResource buffer) public static DeferredResource ForVertexLayout(bgfx.VertexLayoutHandle layout) => new(DeferredResourceKind.VertexLayout, layout.idx, 0); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs index 95a0f51dd..ceb3565df 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs @@ -1,8 +1,8 @@ -using System.Threading.Tasks; -using Inno.Core.Execution; -using Inno.Adapter.Platform; using System; using System.Collections.Generic; +using System.Threading.Tasks; +using Inno.Adapter.Platform; +using Inno.Core.Execution; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -53,13 +53,17 @@ string name IBgfxSurfaceIntegration integration = m_surfaceIntegration ?? throw new NotSupportedException("Additional BGFX windows require an explicit surface integration."); if (!integration.supportsAdditionalSurfaces) + { throw new NotSupportedException("The selected host does not support additional window surfaces."); + } BgfxSurfaceDescriptor descriptor = BgfxSurfaceBinding.Validate( - integration.Resolve(nativeHandles, BgfxSurfaceRole.Additional)); + integration.Resolve(nativeHandles, BgfxSurfaceRole.Additional) + ); if (!capabilities.Supports(GraphicsCapability.SwapChain)) { throw new NotSupportedException( - "The active graphics backend does not support additional presentation surfaces."); + "The active graphics backend does not support additional presentation surfaces." + ); } bgfx.FrameBufferHandle frameBuffer = CreateNativeWindowSurface(descriptor, width, height); @@ -68,7 +72,7 @@ string name throw new InvalidOperationException($"BGFX could not create detached window surface '{name}'."); } - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_windowSurfaces.Add(id, new BgfxWindowSurfaceResource(frameBuffer, width, height, descriptor, name)); return CreateRenderSurfaceHandle(id, generation); } @@ -89,8 +93,8 @@ public bool WindowSurfaceIsSrgb(RenderSurfaceHandle surface) { _ = ResolveSurface(surface); return backbufferIsSrgb - && capabilities.backend != GraphicsApi.Direct3D11 - && capabilities.backend != GraphicsApi.Direct3D12; + && capabilities.backend != GraphicsApi.direct3D11 + && capabilities.backend != GraphicsApi.direct3D12; } /// @@ -134,7 +138,9 @@ int height resource.height = height; resource.retirement.pending.Add(previous); if (!m_surfaceRetirements.Contains(resource.retirement)) + { m_surfaceRetirements.Add(resource.retirement); + } } /// @@ -153,7 +159,7 @@ int height /// /// The caller is not the API thread or a graph or encoder is active. /// - public Task RetireWindowSurface(RenderSurfaceHandle surface) + public Task RetireWindowSurfaceAsync(RenderSurfaceHandle surface) { EnsureSurfaceSafetyPoint(); BgfxWindowSurfaceResource resource = ResolveSurface(surface); @@ -161,38 +167,48 @@ public Task RetireWindowSurface(RenderSurfaceHandle surface) resource.retirement.pending.Add(resource.frameBuffer); resource.retirement.closing = true; if (!m_surfaceRetirements.Contains(resource.retirement)) + { m_surfaceRetirements.Add(resource.retirement); + } return resource.retirement.completion.Task; } /// /// Advances complete discard frames until all requested window retirements have been acknowledged. /// - /// - /// Call only on the API thread with no open frame, graph, encoder or native UI callback. - /// A failed drain retains the device and the borrowed native windows. - /// Presentation may advance while the primary window remains borrowed by the device. - /// /// /// The caller is not at a closed-frame API-thread safety point. /// /// /// The bounded retirement deadline expired; dependent owners must remain alive. /// + /// + /// Call only on the API thread with no open frame, graph, encoder or native UI callback. + /// A failed drain retains the device and the borrowed native windows. + /// Presentation may advance while the primary window remains borrowed by the device. + /// public void DrainWindowSurfaceRetirements() { EnsureSurfaceSafetyPoint(); if (m_frameOpen) + { throw new InvalidOperationException("Window retirement draining requires a closed render frame."); + } if (!HasClosingSurface()) + { return; + } m_surfaceRetirementBarrier ??= new RetirementBarrier("BGFX window surfaces"); m_surfaceRetirementBarrier.Wait(() => { SubmitRetirementFrame(); foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) + { if (retirement.closing) + { throw new RetirementPendingException("BGFX has not acknowledged window destruction.", retirement.failure); + } + } }); m_surfaceRetirementBarrier = null; } @@ -200,17 +216,19 @@ public void DrainWindowSurfaceRetirements() private bool HasClosingSurface() { foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) + { if (retirement.closing) + { return true; + } + } return false; } - private void SubmitRetirementFrame() - { + private void SubmitRetirementFrame() => // Complete the backend frame, including command-buffer submission and frame-credit return. // A nonpresenting flush does not provide that completion boundary on every renderer. SubmitNativeFrame(bgfx.FrameFlags.Discard); - } private uint SubmitNativeFrame(bgfx.FrameFlags flags) { @@ -218,13 +236,19 @@ private uint SubmitNativeFrame(bgfx.FrameFlags flags) foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) { if (retirement.failure is not null) + { throw new RetirementPendingException("A window framebuffer could not retire.", retirement.failure); + } try { foreach (bgfx.FrameBufferHandle frameBuffer in retirement.pending) + { bgfx.destroy_frame_buffer(frameBuffer); + } if (retirement.pending.Count > 0) + { retirement.lastSubmission = submission; + } retirement.pending.Clear(); } catch (Exception failure) @@ -258,26 +282,18 @@ private uint SubmitNativeFrame(bgfx.FrameFlags flags) { BgfxSurfaceRetirement retirement = m_surfaceRetirements[index]; if (retirement.lastSubmission > acknowledged) + { continue; + } if (retirement.closing) + { retirement.completion.TrySetResult(); + } m_surfaceRetirements.RemoveAt(index); } return frame; } - private static bgfx.FrameBufferHandle CreateNativeWindowSurface( - BgfxSurfaceDescriptor descriptor, - int width, - int height - ) - => BgfxNativeCalls.CreateFrameBufferFromNwh( - descriptor.windowHandle.ToPointer(), - checked((ushort)width), - checked((ushort)height), - bgfx.TextureFormat.BGRA8, - bgfx.TextureFormat.D24s8); - private BgfxWindowSurfaceResource ResolveSurface(RenderSurfaceHandle surface) { ValidatePersistentHandle(surface); @@ -293,13 +309,26 @@ private void EnsureSurfaceSafetyPoint() { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_activeGraph is not null || m_activeEncoder != null) + if (m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException( - "Window surface changes require an API-thread point outside graph execution."); + "Window surface changes require an API-thread point outside graph execution." + ); } } + private static bgfx.FrameBufferHandle CreateNativeWindowSurface( + BgfxSurfaceDescriptor descriptor, + int width, + int height + ) => BgfxNativeCalls.CreateFrameBufferFromNwh( + descriptor.windowHandle.ToPointer(), + checked((ushort)width), + checked((ushort)height), + bgfx.TextureFormat.BGRA8, + bgfx.TextureFormat.D24s8 + ); + private sealed class BgfxWindowSurfaceResource { /// @@ -338,22 +367,27 @@ string name /// Gets the BGFX framebuffer owned by this presentation surface. /// public bgfx.FrameBufferHandle frameBuffer { get; set; } - internal BgfxSurfaceRetirement retirement { get; } = new(); + /// /// Gets the scalar measurement or identity associated with the current state. /// public int width { get; set; } + /// /// Gets the scalar measurement or identity associated with the current state. /// public int height { get; set; } + /// /// Gets the platform-native window and display handles used to create the surface. /// public BgfxSurfaceDescriptor descriptor { get; } + /// /// Gets the human-readable name used for presentation and diagnostics. /// public string name { get; } + + internal BgfxSurfaceRetirement retirement { get; } = new(); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs index fd1f14751..27495a694 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Creates a texture using this implementation's validated inputs. @@ -40,14 +40,15 @@ string name int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) { BgfxNativeCalls.SetTextureName(nativeTexture, (sbyte*)textureNamePointer, textureNameLength); } - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_persistentTextures.Add(id, nativeTexture); m_persistentTextureDescriptors.Add(id, descriptor); return CreatePersistentTextureHandle(id, generation); @@ -100,7 +101,8 @@ string name memory, sRgb ? (ulong)bgfx.TextureFlags.Srgb : 0, 0, - &info); + &info + ); if (!nativeTexture.Valid) { throw new InvalidOperationException($"BGFX could not create encoded texture '{name}'."); @@ -108,14 +110,15 @@ string name int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) { BgfxNativeCalls.SetTextureName(nativeTexture, (sbyte*)textureNamePointer, textureNameLength); } - ulong id = m_nextPersistentId++; + ulong id = m_nextPersistentID++; m_persistentTextures.Add(id, nativeTexture); return CreatePersistentTextureHandle(id, generation); } @@ -146,14 +149,14 @@ public void UpdateTexture( ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); ValidatePersistentHandle(texture); if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if (mipLevel >= descriptor.mipCount - || arrayLayer >= descriptor.GetSubresourceLayerCount(mipLevel)) - { + || arrayLayer >= descriptor.GetSubresourceLayerCount(mipLevel) + ) { throw new ArgumentOutOfRangeException(nameof(mipLevel), "Texture subresource is outside the descriptor."); } @@ -164,7 +167,8 @@ public void UpdateTexture( { throw new ArgumentException( $"Texture update requires exactly {expectedSize} tightly packed bytes.", - nameof(data)); + nameof(data) + ); } bgfx.Memory* memory; @@ -185,7 +189,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), memory, - ushort.MaxValue); + ushort.MaxValue + ); break; case RenderTextureDimension.Texture3D: BgfxNativeCalls.UpdateTexture3d( @@ -197,7 +202,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), 1, - memory); + memory + ); break; case RenderTextureDimension.Cube: BgfxNativeCalls.UpdateTextureCube( @@ -210,7 +216,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), memory, - ushort.MaxValue); + ushort.MaxValue + ); break; default: throw new ArgumentOutOfRangeException(nameof(descriptor)); @@ -237,26 +244,29 @@ ReadOnlySpan data EnsureFrameSafetyPoint(); ValidatePersistentHandle(texture); if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if (region.mip >= descriptor.mipCount) + { throw new ArgumentOutOfRangeException(nameof(region), "Texture mip is outside its descriptor."); + } int mipWidth = Math.Max(1, descriptor.width >> region.mip); int mipHeight = Math.Max(1, descriptor.height >> region.mip); int layerCount = descriptor.GetSubresourceLayerCount(region.mip); - if (region.x + region.width > mipWidth || - region.y + region.height > mipHeight || - region.layer + region.depth > layerCount) - { + if (region.x + region.width > mipWidth + || region.y + region.height > mipHeight + || region.layer + region.depth > layerCount + ) { throw new ArgumentOutOfRangeException(nameof(region), "Texture update region is outside its descriptor."); } if (descriptor.dimension != RenderTextureDimension.Texture3D && region.depth != 1) { throw new ArgumentException( "Two-dimensional and cubemap updates address exactly one layer or face.", - nameof(region)); + nameof(region) + ); } int rowPitch = checked(region.width * BytesPerPixel(descriptor.format)); int expectedSize = checked(rowPitch * region.height * region.depth); @@ -264,12 +274,15 @@ ReadOnlySpan data { throw new ArgumentException( $"Texture region update requires exactly {expectedSize} tightly packed bytes.", - nameof(data)); + nameof(data) + ); } bgfx.Memory* memory; fixed (byte* pointer = data) + { memory = bgfx.Raw.copy(pointer, checked((uint)data.Length)); + } switch (descriptor.dimension) { case RenderTextureDimension.Texture2D: @@ -282,7 +295,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), memory, - checked((ushort)rowPitch)); + checked((ushort)rowPitch) + ); break; case RenderTextureDimension.Texture3D: BgfxNativeCalls.UpdateTexture3d( @@ -294,7 +308,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), checked((ushort)region.depth), - memory); + memory + ); break; case RenderTextureDimension.Cube: BgfxNativeCalls.UpdateTextureCube( @@ -307,7 +322,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), memory, - checked((ushort)rowPitch)); + checked((ushort)rowPitch) + ); break; default: throw new ArgumentOutOfRangeException(nameof(descriptor)); @@ -339,8 +355,8 @@ internal bgfx.TextureHandle ResolveTexture(RenderTextureHandle texture) { if (m_activeGraph is null || GetHandleIdentity(texture).generation != m_activeGraph.generation - || !m_graphTextures.TryGetValue(GetHandleIdentity(texture).index, out bgfx.TextureHandle nativeTexture)) - { + || !m_graphTextures.TryGetValue(GetHandleIdentity(texture).index, out bgfx.TextureHandle nativeTexture) + ) { throw new ArgumentException("Texture is not active in the current BGFX graph.", nameof(texture)); } @@ -361,88 +377,93 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto { if (descriptor.width > capabilities.limits.maxTextureSize || descriptor.height > capabilities.limits.maxTextureSize - || descriptor.depth > capabilities.limits.maxTextureSize) - { - throw new NotSupportedException( - "The texture descriptor exceeds the active backend extent limit."); + || descriptor.depth > capabilities.limits.maxTextureSize + ) { + throw new NotSupportedException("The texture descriptor exceeds the active backend extent limit."); } if (!capabilities.SupportsSampled(descriptor.format, descriptor.dimension) - && (descriptor.usage & RenderTextureUsage.Sampled) != 0) - { + && (descriptor.usage & RenderTextureUsage.Sampled) != 0 + ) { throw new NotSupportedException( - $"The active graphics backend cannot sample {descriptor.dimension} textures in format '{descriptor.format}'."); + $"The active graphics backend cannot sample {descriptor.dimension} textures in format '{descriptor.format}'." + ); } if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 - && !capabilities.SupportsRenderTarget(descriptor.format)) - { + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + && !capabilities.SupportsRenderTarget(descriptor.format) + ) { throw new NotSupportedException( - $"The active graphics backend cannot attach texture format '{descriptor.format}'."); + $"The active graphics backend cannot attach texture format '{descriptor.format}'." + ); } if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 && descriptor.sampleCount > 1 - && !capabilities.SupportsMultisampleRenderTarget(descriptor.format)) - { + && !capabilities.SupportsMultisampleRenderTarget(descriptor.format) + ) { throw new NotSupportedException( - $"The active graphics backend cannot multisample texture format '{descriptor.format}'."); + $"The active graphics backend cannot multisample texture format '{descriptor.format}'." + ); } if ((descriptor.usage & RenderTextureUsage.Storage) != 0 && (!capabilities.Supports(GraphicsCapability.Compute) || !capabilities.Supports(GraphicsCapability.StorageTexture) || (!capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Read) - && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write)))) - { + && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write))) + ) { throw new NotSupportedException( - $"The active graphics backend cannot use texture format '{descriptor.format}' for storage access."); + $"The active graphics backend cannot use texture format '{descriptor.format}' for storage access." + ); } if ((descriptor.usage & RenderTextureUsage.Readback) != 0) { if (!capabilities.Supports(GraphicsCapability.TextureReadback)) - throw new NotSupportedException("The active graphics backend does not support texture readback."); - if (descriptor.sampleCount != 1 || - (descriptor.usage & (RenderTextureUsage.ColorAttachment | - RenderTextureUsage.DepthStencilAttachment | - RenderTextureUsage.Storage)) != 0) { + throw new NotSupportedException("The active graphics backend does not support texture readback."); + } + if (descriptor.sampleCount != 1 + || (descriptor.usage & (RenderTextureUsage.ColorAttachment + | RenderTextureUsage.DepthStencilAttachment + | RenderTextureUsage.Storage)) != 0 + ) { throw new ArgumentException( "Readback textures must be single-sampled transfer resources, not attachments or storage images.", - nameof(descriptor)); + nameof(descriptor) + ); } } if (descriptor.dimension == RenderTextureDimension.Texture2D && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.Texture2DArray)) - { + && !capabilities.Supports(GraphicsCapability.Texture2DArray) + ) { throw new NotSupportedException( - "The active graphics backend does not support two-dimensional texture arrays."); + "The active graphics backend does not support two-dimensional texture arrays." + ); } if (descriptor.dimension == RenderTextureDimension.Texture3D - && !capabilities.Supports(GraphicsCapability.Texture3D)) - { - throw new NotSupportedException( - "The active graphics backend does not support three-dimensional textures."); + && !capabilities.Supports(GraphicsCapability.Texture3D) + ) { + throw new NotSupportedException("The active graphics backend does not support three-dimensional textures."); } if (descriptor.dimension == RenderTextureDimension.Cube && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.TextureCubeArray)) - { - throw new NotSupportedException( - "The active graphics backend does not support cubemap texture arrays."); + && !capabilities.Supports(GraphicsCapability.TextureCubeArray) + ) { + throw new NotSupportedException("The active graphics backend does not support cubemap texture arrays."); } bgfx.TextureFlags flags = bgfx.TextureFlags.None; if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0) - { + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + ) { flags |= descriptor.sampleCount switch { 1 => bgfx.TextureFlags.Rt, @@ -484,7 +505,8 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), RenderTextureDimension.Texture3D => BgfxNativeCalls.CreateTexture3d( checked((ushort)descriptor.width), checked((ushort)descriptor.height), @@ -493,7 +515,8 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), RenderTextureDimension.Cube => BgfxNativeCalls.CreateTextureCube( checked((ushort)descriptor.width), descriptor.mipCount > 1 ? (byte)1 : (byte)0, @@ -501,22 +524,22 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), _ => throw new ArgumentOutOfRangeException(nameof(descriptor)) }; } private static int BytesPerPixel(RenderTextureFormat format) => format switch - { - RenderTextureFormat.R8 => 1, - RenderTextureFormat.RG8 => 2, - RenderTextureFormat.RGBA8 or RenderTextureFormat.RGBA8Srgb - or RenderTextureFormat.RGB10A2 or RenderTextureFormat.RG11B10Float - or RenderTextureFormat.R32Float or RenderTextureFormat.Depth24Stencil8 - or RenderTextureFormat.Depth32Float => 4, - RenderTextureFormat.RGBA16Float => 8, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; - + { + RenderTextureFormat.R8 => 1, + RenderTextureFormat.RG8 => 2, + RenderTextureFormat.RGBA8 or RenderTextureFormat.RGBA8Srgb + or RenderTextureFormat.RGB10A2 or RenderTextureFormat.RG11B10Float + or RenderTextureFormat.R32Float or RenderTextureFormat.Depth24Stencil8 + or RenderTextureFormat.Depth32Float => 4, + RenderTextureFormat.RGBA16Float => 8, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs index 3d5f4c9c1..2c2dbc18a 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { private bgfx.TextureHandle AcquireTransientTexture( RenderTextureDescriptor descriptor, @@ -22,7 +22,9 @@ int physicalSlot { PooledTransientTexture pooled = m_transientTexturePool[index]; if (pooled.physicalSlot != physicalSlot || !pooled.descriptor.Equals(descriptor)) + { continue; + } m_transientTexturePool.RemoveAt(index); return pooled.handle; } @@ -31,17 +33,22 @@ int physicalSlot { PooledTransientTexture pooled = m_transientTexturePool[index]; if (!pooled.descriptor.Equals(descriptor)) + { continue; + } m_transientTexturePool.RemoveAt(index); return pooled.handle; } bgfx.TextureHandle texture = CreateNativeTexture(descriptor); if (!texture.Valid) + { throw new InvalidOperationException($"BGFX could not allocate transient texture '{name}'."); + } int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) @@ -56,15 +63,15 @@ private void ReturnTransientGraphResources() { foreach ((int slot, bgfx.TextureHandle texture) in m_transientTextureSlots) { - m_transientTexturePool.Add(new PooledTransientTexture( - m_transientTextureSlotDescriptors[slot], - texture, - m_submissionSequence, - slot)); + m_transientTexturePool.Add( + new PooledTransientTexture(m_transientTextureSlotDescriptors[slot], texture, m_submissionSequence, slot) + ); } foreach ((int slot, BgfxBufferResource buffer) in m_transientBufferSlots) + { m_transientBufferPool.Add(new PooledTransientBuffer(buffer, m_submissionSequence, slot)); + } m_transientTextureSlots.Clear(); m_transientTextureSlotDescriptors.Clear(); @@ -77,7 +84,9 @@ private void TrimTransientResourceCaches() { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!CacheEntryExpired(cached.lastUsedSubmission)) + { continue; + } EnqueueDestroy(DeferredResource.ForFrameBuffer(cached.handle)); m_graphFrameBufferCache.RemoveAt(index); } @@ -86,7 +95,9 @@ private void TrimTransientResourceCaches() { PooledTransientTexture pooled = m_transientTexturePool[index]; if (!CacheEntryExpired(pooled.lastUsedSubmission)) + { continue; + } RemoveCachedFrameBuffersReferencing(pooled.handle.idx); EnqueueDestroy(DeferredResource.ForTexture(pooled.handle)); m_transientTexturePool.RemoveAt(index); @@ -96,13 +107,16 @@ private void TrimTransientResourceCaches() { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (!CacheEntryExpired(pooled.lastUsedSubmission)) + { continue; + } EnqueueDestroy(DeferredResource.ForBuffer(pooled.resource)); m_transientBufferPool.RemoveAt(index); } } - private bool CacheEntryExpired(ulong lastUsedSubmission) => m_submissionSequence - lastUsedSubmission > C_TRANSIENT_CACHE_RETENTION_FRAMES; + private bool CacheEntryExpired(ulong lastUsedSubmission) + => m_submissionSequence - lastUsedSubmission > C_TRANSIENT_CACHE_RETENTION_FRAMES; private readonly record struct PooledTransientTexture( RenderTextureDescriptor descriptor, @@ -116,5 +130,4 @@ private readonly record struct PooledTransientBuffer( ulong lastUsedSubmission, int physicalSlot ); - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs index 511ae2e90..a8e285cef 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs @@ -1,9 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; +using Inno.Adapter.Platform; +using Inno.Core.Execution; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -20,12 +21,10 @@ public sealed unsafe partial class BgfxDevice : RenderDevice, IRenderDevice, IRe private static int s_nextGeneration; private readonly BgfxProcessDeviceLease m_processLease; - private readonly int m_apiThreadId; + private readonly int m_apiThreadID; private readonly int m_deferredDestroyFrames; private readonly bool m_hasPrimarySurface; private readonly List m_surfaceRetirements = []; - private Inno.Core.Execution.RetirementBarrier? m_surfaceRetirementBarrier; - private ulong m_submissionSequence; private readonly IBgfxSurfaceIntegration? m_surfaceIntegration; private readonly Dictionary m_persistentTextures = []; private readonly Dictionary m_persistentTextureDescriptors = []; @@ -37,18 +36,20 @@ public sealed unsafe partial class BgfxDevice : RenderDevice, IRenderDevice, IRe private readonly List m_transientTexturePool = []; private readonly List m_graphFrameBuffers = []; private readonly List m_graphFrameBufferCache = []; + private RetirementBarrier? m_surfaceRetirementBarrier; + private ulong m_submissionSequence; private uint m_resetFlags; private bool m_resetPending; private CompiledRenderGraph? m_activeGraph; private bgfx.Encoder* m_activeEncoder; - private ulong m_nextPersistentId = 1; - private ulong m_nextReadbackId = 1; + private ulong m_nextPersistentID = 1; + private ulong m_nextReadbackID = 1; private uint m_backendFrame; private int m_activeGraphViewBase; private int m_backbufferWidth; private int m_backbufferHeight; - private int m_nextViewId; + private int m_nextViewID; private RenderPresentationSize? m_pendingPresentationSize; private bool m_presentationUpdatePending; private int m_drawCount; @@ -73,31 +74,38 @@ public sealed unsafe partial class BgfxDevice : RenderDevice, IRenderDevice, IRe public BgfxDevice(BgfxDeviceOptions options) { ArgumentNullException.ThrowIfNull(options); - PlatformNativeHandles nativeHandles = options.window is null ? default - : options.window is INativeWindowSurface surface ? surface.nativeHandles - : throw new NotSupportedException("BGFX requires a window that implements INativeWindowSurface."); + PlatformNativeHandles nativeHandles = options.window is null + ? default + : options.window is INativeWindowSurface surface + ? surface.nativeHandles + : throw new NotSupportedException("BGFX requires a window that implements INativeWindowSurface."); m_surfaceIntegration = options.surfaceIntegration; - BgfxSurfaceDescriptor primarySurface = options.window is null ? default - : BgfxSurfaceBinding.Validate((m_surfaceIntegration - ?? throw new ArgumentException("A windowed BGFX device requires an explicit surface integration.", nameof(options))) - .Resolve(nativeHandles, BgfxSurfaceRole.Primary)); - m_apiThreadId = Environment.CurrentManagedThreadId; + BgfxSurfaceDescriptor primarySurface = options.window is null + ? default + : BgfxSurfaceBinding.Validate( + (m_surfaceIntegration + ?? throw new ArgumentException("A windowed BGFX device requires an explicit surface integration.", nameof(options))) + .Resolve(nativeHandles, BgfxSurfaceRole.Primary) + ); + m_apiThreadID = Environment.CurrentManagedThreadId; m_deferredDestroyFrames = options.deferredDestroyFrames; m_hasPrimarySurface = options.window is not null; int pixelWidth = options.backbufferWidth; int pixelHeight = options.backbufferHeight; - primaryPresentationSize = m_hasPrimarySurface && pixelWidth > 0 && pixelHeight > 0 - ? new RenderPresentationSize(pixelWidth, pixelHeight) : null; + this.primaryPresentationSize = m_hasPrimarySurface && pixelWidth > 0 && pixelHeight > 0 + ? new RenderPresentationSize(pixelWidth, pixelHeight) + : null; m_backbufferWidth = Math.Max(1, pixelWidth); m_backbufferHeight = Math.Max(1, pixelHeight); m_resetFlags = (uint)( (options.verticalSync ? bgfx.ResetFlags.Vsync : bgfx.ResetFlags.None) | (options.sRgbBackbuffer && (!m_hasPrimarySurface || primarySurface.supportsSrgbReset) - ? bgfx.ResetFlags.SrgbBackbuffer - : bgfx.ResetFlags.None)); + ? bgfx.ResetFlags.SrgbBackbuffer + : bgfx.ResetFlags.None)); bgfx.RendererType? preferredRenderer = options.preferredBackend is GraphicsApi backend - ? BgfxCapabilityMapper.ToNativeRenderer(backend) : null; + ? BgfxCapabilityMapper.ToNativeRenderer(backend) + : null; m_processLease = BgfxProcessDeviceLease.Acquire(options.forceSingleThreaded); bool nativeInitialized = false; try @@ -111,10 +119,14 @@ public BgfxDevice(BgfxDeviceOptions options) bgfx.Init init; bgfx.Raw.init_ctor(&init); if (preferredRenderer.HasValue) + { init.type = preferredRenderer.Value; + } if (options.window is not null) + { BgfxSurfaceBinding.Apply(ref init, primarySurface); + } init.resolution.width = checked((uint)m_backbufferWidth); init.resolution.height = checked((uint)m_backbufferHeight); init.resolution.reset = m_resetFlags; @@ -124,18 +136,20 @@ public BgfxDevice(BgfxDeviceOptions options) } nativeInitialized = true; - generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); + this.generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); if (generation == 0) { - generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); + this.generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); } - capabilities = BgfxCapabilityMapper.FromNative(bgfx.Raw.get_caps()); + this.capabilities = BgfxCapabilityMapper.FromNative(bgfx.Raw.get_caps()); } catch { if (nativeInitialized) + { bgfx.shutdown(); + } m_processLease.Dispose(); throw; } @@ -159,8 +173,9 @@ public BgfxDevice(BgfxDeviceOptions options) /// /// Gets whether both the selected host and active renderer permit additional window surfaces. /// - public bool supportsAdditionalSurfaces => m_surfaceIntegration?.supportsAdditionalSurfaces == true - && capabilities.Supports(GraphicsCapability.SwapChain); + public bool supportsAdditionalSurfaces + => m_surfaceIntegration?.supportsAdditionalSurfaces == true + && capabilities.Supports(GraphicsCapability.SwapChain); /// /// Gets the generation identity that owns this value. @@ -186,8 +201,12 @@ public RenderDeviceAllocationCounters? allocationCounters { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - return new RenderDeviceAllocationCounters(generation, m_transientTextureAllocationCount, - m_transientBufferAllocationCount, m_transientFrameBufferAllocationCount); + return new RenderDeviceAllocationCounters( + generation, + m_transientTextureAllocationCount, + m_transientBufferAllocationCount, + m_transientFrameBufferAllocationCount + ); } } @@ -196,7 +215,7 @@ public RenderDeviceAllocationCounters? allocationCounters /// public uint backendFrame => m_backendFrame; - internal int allocatedViewCount => m_nextViewId; + internal int allocatedViewCount => m_nextViewID; internal void RecordDraw(int count = 1) => Interlocked.Add(ref m_drawCount, count); @@ -222,7 +241,7 @@ private void EnsureFrameSafetyPoint() { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - if (!m_frameOpen || m_activeGraph is not null || m_activeEncoder != null) + if (!m_frameOpen || m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException("Operation requires an open frame before graph execution."); } @@ -230,7 +249,7 @@ private void EnsureFrameSafetyPoint() private void EnsureApiThread() { - if (Environment.CurrentManagedThreadId != m_apiThreadId) + if (Environment.CurrentManagedThreadId != m_apiThreadID) { throw new InvalidOperationException("BGFX API operations must run on the device API thread."); } @@ -244,5 +263,4 @@ private static uint PackColor(RenderClearColor color) byte a = (byte)(Math.Clamp(color.a, 0f, 1f) * 255f); return ((uint)r << 24) | ((uint)g << 16) | ((uint)b << 8) | a; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs index 8f2622ada..ee78b7bce 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs @@ -36,8 +36,8 @@ public int backbufferWidth { get => window?.pixelWidth ?? m_backbufferWidth; set => m_backbufferWidth = value > 0 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } /// @@ -47,8 +47,8 @@ public int backbufferHeight { get => window?.pixelHeight ?? m_backbufferHeight; set => m_backbufferHeight = value > 0 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } /// @@ -77,7 +77,7 @@ public int deferredDestroyFrames { get => m_deferredDestroyFrames; set => m_deferredDestroyFrames = value >= 1 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs index 68b37a220..422217bf2 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs @@ -15,9 +15,7 @@ internal static void AttachmentInit( ushort numLayers, ushort mip, byte resolve - ) { - bgfx.Raw.attachment_init(attachment, &handle, access, layer, numLayers, mip, resolve); - } + ) => bgfx.Raw.attachment_init(attachment, &handle, access, layer, numLayers, mip, resolve); internal static bgfx.DynamicVertexBufferHandle CreateDynamicVertexBuffer( uint count, @@ -60,7 +58,8 @@ ushort flags return result; } - internal static bgfx.ShaderHandle CreateShader(bgfx.Memory* memory) { + internal static bgfx.ShaderHandle CreateShader(bgfx.Memory* memory) + { bgfx.ShaderHandle result = default; bgfx.Raw.create_shader(memory, &result); return result; @@ -131,7 +130,8 @@ ushort flags return result; } - internal static bgfx.VertexLayoutHandle CreateVertexLayout(bgfx.VertexLayout* layout) { + internal static bgfx.VertexLayoutHandle CreateVertexLayout(bgfx.VertexLayout* layout) + { bgfx.VertexLayoutHandle result = default; bgfx.Raw.create_vertex_layout(layout, &result); return result; @@ -153,24 +153,23 @@ internal static void EncoderBlit( ushort width, ushort height, ushort depth - ) { - bgfx.Raw.encoder_blit( - encoder, - id, - &dst, - dstMip, - dstX, - dstY, - dstZ, - &src, - srcMip, - srcX, - srcY, - srcZ, - width, - height, - depth); - } + ) => bgfx.Raw.encoder_blit( + encoder, + id, + &dst, + dstMip, + dstX, + dstY, + dstZ, + &src, + srcMip, + srcX, + srcY, + srcZ, + width, + height, + depth + ); internal static void EncoderDispatch( bgfx.Encoder* encoder, @@ -180,9 +179,7 @@ internal static void EncoderDispatch( uint numY, uint numZ, byte flags - ) { - bgfx.Raw.encoder_dispatch(encoder, id, &program, numX, numY, numZ, flags); - } + ) => bgfx.Raw.encoder_dispatch(encoder, id, &program, numX, numY, numZ, flags); internal static void EncoderDispatchIndirect( bgfx.Encoder* encoder, @@ -192,63 +189,49 @@ internal static void EncoderDispatchIndirect( uint start, uint count, byte flags - ) { - bgfx.Raw.encoder_dispatch_indirect(encoder, id, &program, &indirectHandle, start, count, flags); - } + ) => bgfx.Raw.encoder_dispatch_indirect(encoder, id, &program, &indirectHandle, start, count, flags); internal static void EncoderSetComputeDynamicIndexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.DynamicIndexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_dynamic_index_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_dynamic_index_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeDynamicVertexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.DynamicVertexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_dynamic_vertex_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_dynamic_vertex_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeIndexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.IndexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_index_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_index_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeIndirectBuffer( bgfx.Encoder* encoder, byte stage, bgfx.IndirectBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_indirect_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_indirect_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeVertexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.VertexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_vertex_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_vertex_buffer(encoder, stage, &handle, access); internal static void EncoderSetDynamicIndexBuffer( bgfx.Encoder* encoder, bgfx.DynamicIndexBufferHandle handle, uint firstIndex, uint numIndices - ) { - bgfx.Raw.encoder_set_dynamic_index_buffer(encoder, &handle, firstIndex, numIndices); - } + ) => bgfx.Raw.encoder_set_dynamic_index_buffer(encoder, &handle, firstIndex, numIndices); internal static void EncoderSetDynamicVertexBuffer( bgfx.Encoder* encoder, @@ -256,9 +239,7 @@ internal static void EncoderSetDynamicVertexBuffer( bgfx.DynamicVertexBufferHandle handle, uint startVertex, uint numVertices - ) { - bgfx.Raw.encoder_set_dynamic_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); - } + ) => bgfx.Raw.encoder_set_dynamic_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); internal static void EncoderSetDynamicVertexBufferWithLayout( bgfx.Encoder* encoder, @@ -267,15 +248,14 @@ internal static void EncoderSetDynamicVertexBufferWithLayout( uint startVertex, uint numVertices, bgfx.VertexLayoutHandle layoutHandle - ) { - bgfx.Raw.encoder_set_dynamic_vertex_buffer_with_layout( - encoder, - stream, - &handle, - startVertex, - numVertices, - &layoutHandle); - } + ) => bgfx.Raw.encoder_set_dynamic_vertex_buffer_with_layout( + encoder, + stream, + &handle, + startVertex, + numVertices, + &layoutHandle + ); internal static void EncoderSetImage( bgfx.Encoder* encoder, @@ -284,36 +264,28 @@ internal static void EncoderSetImage( byte mip, bgfx.Access access, bgfx.TextureFormat format - ) { - bgfx.Raw.encoder_set_image(encoder, stage, &handle, mip, access, format); - } + ) => bgfx.Raw.encoder_set_image(encoder, stage, &handle, mip, access, format); internal static void EncoderSetIndexBuffer( bgfx.Encoder* encoder, bgfx.IndexBufferHandle handle, uint firstIndex, uint numIndices - ) { - bgfx.Raw.encoder_set_index_buffer(encoder, &handle, firstIndex, numIndices); - } + ) => bgfx.Raw.encoder_set_index_buffer(encoder, &handle, firstIndex, numIndices); internal static void EncoderSetInstanceDataFromDynamicVertexBuffer( bgfx.Encoder* encoder, bgfx.DynamicVertexBufferHandle handle, uint startVertex, uint count - ) { - bgfx.Raw.encoder_set_instance_data_from_dynamic_vertex_buffer(encoder, &handle, startVertex, count); - } + ) => bgfx.Raw.encoder_set_instance_data_from_dynamic_vertex_buffer(encoder, &handle, startVertex, count); internal static void EncoderSetInstanceDataFromVertexBuffer( bgfx.Encoder* encoder, bgfx.VertexBufferHandle handle, uint startVertex, uint count - ) { - bgfx.Raw.encoder_set_instance_data_from_vertex_buffer(encoder, &handle, startVertex, count); - } + ) => bgfx.Raw.encoder_set_instance_data_from_vertex_buffer(encoder, &handle, startVertex, count); internal static void EncoderSetTexture( bgfx.Encoder* encoder, @@ -321,18 +293,14 @@ internal static void EncoderSetTexture( bgfx.UniformHandle sampler, bgfx.TextureHandle handle, uint flags - ) { - bgfx.Raw.encoder_set_texture(encoder, stage, &sampler, &handle, flags); - } + ) => bgfx.Raw.encoder_set_texture(encoder, stage, &sampler, &handle, flags); internal static void EncoderSetUniform( bgfx.Encoder* encoder, bgfx.UniformHandle handle, void* value, ushort count - ) { - bgfx.Raw.encoder_set_uniform(encoder, &handle, value, count); - } + ) => bgfx.Raw.encoder_set_uniform(encoder, &handle, value, count); internal static void EncoderSetVertexBuffer( bgfx.Encoder* encoder, @@ -340,9 +308,7 @@ internal static void EncoderSetVertexBuffer( bgfx.VertexBufferHandle handle, uint startVertex, uint numVertices - ) { - bgfx.Raw.encoder_set_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); - } + ) => bgfx.Raw.encoder_set_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); internal static void EncoderSetVertexBufferWithLayout( bgfx.Encoder* encoder, @@ -351,15 +317,14 @@ internal static void EncoderSetVertexBufferWithLayout( uint startVertex, uint numVertices, bgfx.VertexLayoutHandle layoutHandle - ) { - bgfx.Raw.encoder_set_vertex_buffer_with_layout( - encoder, - stream, - &handle, - startVertex, - numVertices, - &layoutHandle); - } + ) => bgfx.Raw.encoder_set_vertex_buffer_with_layout( + encoder, + stream, + &handle, + startVertex, + numVertices, + &layoutHandle + ); internal static void EncoderSubmit( bgfx.Encoder* encoder, @@ -367,9 +332,7 @@ internal static void EncoderSubmit( bgfx.ProgramHandle program, uint depth, byte flags - ) { - bgfx.Raw.encoder_submit(encoder, id, &program, depth, flags); - } + ) => bgfx.Raw.encoder_submit(encoder, id, &program, depth, flags); internal static void EncoderSubmitIndirect( bgfx.Encoder* encoder, @@ -380,80 +343,60 @@ internal static void EncoderSubmitIndirect( uint count, uint depth, byte flags - ) { - bgfx.Raw.encoder_submit_indirect(encoder, id, &program, &indirectHandle, start, count, depth, flags); - } + ) => bgfx.Raw.encoder_submit_indirect(encoder, id, &program, &indirectHandle, start, count, depth, flags); internal static ushort GetShaderUniforms( bgfx.ShaderHandle handle, bgfx.UniformHandle* uniforms, ushort max - ) { - return bgfx.Raw.get_shader_uniforms(&handle, uniforms, max); - } + ) => bgfx.Raw.get_shader_uniforms(&handle, uniforms, max); internal static void GetUniformInfo( bgfx.UniformHandle handle, bgfx.UniformInfo* info - ) { - bgfx.Raw.get_uniform_info(&handle, info); - } + ) => bgfx.Raw.get_uniform_info(&handle, info); internal static uint ReadTexture( bgfx.TextureHandle handle, void* data, byte mip - ) { - return bgfx.Raw.read_texture(&handle, data, mip); - } + ) => bgfx.Raw.read_texture(&handle, data, mip); internal static void SetIndexBufferName( bgfx.IndexBufferHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_index_buffer_name(&handle, name, len); - } + ) => bgfx.Raw.set_index_buffer_name(&handle, name, len); internal static void SetShaderName( bgfx.ShaderHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_shader_name(&handle, name, len); - } + ) => bgfx.Raw.set_shader_name(&handle, name, len); internal static void SetTextureName( bgfx.TextureHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_texture_name(&handle, name, len); - } + ) => bgfx.Raw.set_texture_name(&handle, name, len); internal static void SetVertexBufferName( bgfx.VertexBufferHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_vertex_buffer_name(&handle, name, len); - } + ) => bgfx.Raw.set_vertex_buffer_name(&handle, name, len); internal static void UpdateDynamicIndexBuffer( bgfx.DynamicIndexBufferHandle handle, uint startIndex, bgfx.Memory* memory - ) { - bgfx.Raw.update_dynamic_index_buffer(&handle, startIndex, memory); - } + ) => bgfx.Raw.update_dynamic_index_buffer(&handle, startIndex, memory); internal static void UpdateDynamicVertexBuffer( bgfx.DynamicVertexBufferHandle handle, uint startVertex, bgfx.Memory* memory - ) { - bgfx.Raw.update_dynamic_vertex_buffer(&handle, startVertex, memory); - } + ) => bgfx.Raw.update_dynamic_vertex_buffer(&handle, startVertex, memory); internal static void UpdateTexture2d( bgfx.TextureHandle handle, @@ -465,9 +408,7 @@ internal static void UpdateTexture2d( ushort height, bgfx.Memory* memory, ushort pitch - ) { - bgfx.Raw.update_texture_2d(&handle, layer, mip, x, y, width, height, memory, pitch); - } + ) => bgfx.Raw.update_texture_2d(&handle, layer, mip, x, y, width, height, memory, pitch); internal static void UpdateTexture3d( bgfx.TextureHandle handle, @@ -479,9 +420,7 @@ internal static void UpdateTexture3d( ushort height, ushort depth, bgfx.Memory* memory - ) { - bgfx.Raw.update_texture_3d(&handle, mip, x, y, z, width, height, depth, memory); - } + ) => bgfx.Raw.update_texture_3d(&handle, mip, x, y, z, width, height, depth, memory); internal static void UpdateTextureCube( bgfx.TextureHandle handle, @@ -494,8 +433,5 @@ internal static void UpdateTextureCube( ushort height, bgfx.Memory* memory, ushort pitch - ) { - bgfx.Raw.update_texture_cube(&handle, layer, side, mip, x, y, width, height, memory, pitch); - } - + ) => bgfx.Raw.update_texture_cube(&handle, layer, side, mip, x, y, width, height, memory, pitch); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs new file mode 100644 index 000000000..a01645d1c --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using Inno.Native.Bgfx; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx; + +internal sealed class BgfxPipelineResource +{ + /// + /// Creates a validated bgfx pipeline resource instance. + /// + /// + /// The program consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The bindings consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The vertex layout consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The vertex layout handle consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The raster state consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// Whether compute behavior is enabled while bgfx pipeline resource executes. + /// + public BgfxPipelineResource( + bgfx.ProgramHandle program, + IReadOnlyDictionary bindings, + RenderVertexLayout? vertexLayout, + bgfx.VertexLayoutHandle vertexLayoutHandle, + RenderRasterState? rasterState, + bool compute + ) { + this.program = program; + this.bindings = bindings; + this.vertexLayout = vertexLayout; + this.vertexLayoutHandle = vertexLayoutHandle; + this.rasterState = rasterState; + this.compute = compute; + } + + /// + /// Gets the linked BGFX shader program owned by this pipeline resource. + /// + public bgfx.ProgramHandle program { get; } + + /// + /// Gets the immutable lookup of stable binding IDs to BGFX uniform resources. + /// + public IReadOnlyDictionary bindings { get; } + + /// + /// Gets the optional vertex layout required by this resource or pipeline. + /// + public RenderVertexLayout? vertexLayout { get; } + + /// + /// Gets the BGFX vertex-layout handle owned by this pipeline resource. + /// + public bgfx.VertexLayoutHandle vertexLayoutHandle { get; } + + /// + /// Gets the optional rasterization state encoded by this pipeline. + /// + public RenderRasterState? rasterState { get; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool compute { get; } +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs index 39bc1a651..9c421bb0d 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs @@ -7,7 +7,7 @@ namespace Inno.Adapter.Rendering.Bgfx; /// internal sealed class BgfxProcessDeviceLease : IDisposable { - private static readonly object S_SYNC = new(); + private static readonly object SYNC = new(); private static BgfxProcessDeviceLease? s_active; private static bool s_singleThreadedRuntimeConsumed; @@ -19,48 +19,59 @@ private BgfxProcessDeviceLease(bool singleThreaded) m_singleThreaded = singleThreaded; } - internal static BgfxProcessDeviceLease Acquire(bool singleThreaded) + /// + /// Releases active ownership after native shutdown; a consumed inline runtime remains unavailable. + /// + public void Dispose() { - lock (S_SYNC) + lock (SYNC) { - if (s_active is not null) - throw new InvalidOperationException("Only one BGFX device may own the native process runtime."); - if (s_singleThreadedRuntimeConsumed) + if (m_disposed) { - throw new InvalidOperationException( - "BGFX cannot be initialized again after this process entered single-threaded mode."); + return; } - - var lease = new BgfxProcessDeviceLease(singleThreaded); - s_active = lease; - return lease; + if (!ReferenceEquals(s_active, this)) + { + throw new InvalidOperationException("BGFX process leases must be released by their owner."); + } + m_disposed = true; + s_active = null; } } internal void MarkSingleThreadedEntered() { - lock (S_SYNC) + lock (SYNC) { if (!ReferenceEquals(s_active, this) || m_disposed) + { throw new InvalidOperationException("The BGFX process lease is not active."); + } if (m_singleThreaded) + { s_singleThreadedRuntimeConsumed = true; + } } } - /// - /// Releases active ownership after native shutdown; a consumed inline runtime remains unavailable. - /// - public void Dispose() + internal static BgfxProcessDeviceLease Acquire(bool singleThreaded) { - lock (S_SYNC) + lock (SYNC) { - if (m_disposed) - return; - if (!ReferenceEquals(s_active, this)) - throw new InvalidOperationException("BGFX process leases must be released by their owner."); - m_disposed = true; - s_active = null; + if (s_active is not null) + { + throw new InvalidOperationException("Only one BGFX device may own the native process runtime."); + } + if (s_singleThreadedRuntimeConsumed) + { + throw new InvalidOperationException( + "BGFX cannot be initialized again after this process entered single-threaded mode." + ); + } + + var lease = new BgfxProcessDeviceLease(singleThreaded); + s_active = lease; + return lease; } } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs index 2b6dad31e..bd9e6f1d9 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs @@ -19,13 +19,14 @@ public sealed class BgfxRenderingBackendProvider : RenderingBackendProvider /// /// The integration is null. /// - public BgfxRenderingBackendProvider(IBgfxSurfaceIntegration surfaceIntegration) : base(RenderingBackendId.bgfx) + public BgfxRenderingBackendProvider(IBgfxSurfaceIntegration surfaceIntegration) + : base(RenderingBackendID.bgfx) { ArgumentNullException.ThrowIfNull(surfaceIntegration); m_surfaceIntegration = surfaceIntegration; } - /// + /// public override IRenderDevice CreateDevice(RenderingBackendOptions options) { ArgumentNullException.ThrowIfNull(options); @@ -40,7 +41,7 @@ public override IRenderDevice CreateDevice(RenderingBackendOptions options) }); } - /// + /// public override IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider() => new BgfxCompositionProgramProvider(); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs new file mode 100644 index 000000000..099478c28 --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs @@ -0,0 +1,34 @@ +using Inno.Native.Bgfx; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx; + +internal sealed class BgfxShaderBindingResource +{ + /// + /// Creates a validated bgfx shader binding resource instance. + /// + /// + /// The descriptor consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The uniform consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. + /// + public BgfxShaderBindingResource( + RenderShaderBindingDescriptor descriptor, + bgfx.UniformHandle uniform + ) { + this.descriptor = descriptor; + this.uniform = uniform; + } + + /// + /// Gets the backend-neutral descriptor used to validate and recreate this resource. + /// + public RenderShaderBindingDescriptor descriptor { get; } + + /// + /// Gets the BGFX uniform handle backing this shader binding. + /// + public bgfx.UniformHandle uniform { get; } +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs index 088076ca9..42f0935be 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs @@ -8,7 +8,9 @@ internal static unsafe class BgfxSurfaceBinding internal static BgfxSurfaceDescriptor Validate(BgfxSurfaceDescriptor descriptor) { if (descriptor.windowHandle == 0) + { throw new ArgumentException("The surface integration returned an invalid window descriptor."); + } return descriptor; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs index 9f765203a..76f30fc09 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs @@ -32,7 +32,9 @@ public BgfxSurfaceDescriptor( bool supportsSrgbReset ) { if (windowHandle == 0) + { throw new ArgumentException("A live borrowed window value is required.", nameof(windowHandle)); + } this.windowHandle = windowHandle; this.displayHandle = displayHandle; this.supportsSrgbReset = supportsSrgbReset; diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs index 55706669b..7a95e7a2f 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs @@ -2,21 +2,6 @@ namespace Inno.Adapter.Rendering.Bgfx; -/// -/// Identifies how a borrowed window is used by a BGFX device, independently of its system ABI. -/// -public enum BgfxSurfaceRole -{ - /// - /// The primary window supplied before device initialization. - /// - Primary, - /// - /// An additional window whose framebuffer is owned by an active device generation. - /// - Additional -} - /// /// Resolves an explicitly selected host's borrowed surface handles for the shared BGFX backend. /// @@ -54,3 +39,18 @@ BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ); } + +/// +/// Identifies how a borrowed window is used by a BGFX device, independently of its system ABI. +/// +public enum BgfxSurfaceRole +{ + /// + /// The primary window supplied before device initialization. + /// + Primary, + /// + /// An additional window whose framebuffer is owned by an active device generation. + /// + Additional +} diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs index 9b7d104d9..b97aeb1df 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs @@ -41,21 +41,32 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: true, aheadOfTime: false, nativeStaticLinking: false); + this.capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: true, + aheadOfTime: false, + nativeStaticLinking: false + ); } - /// - public ManagedDeploymentId id => ManagedDeploymentId.coreClr; + /// + public ManagedDeploymentID id => ManagedDeploymentID.coreClr; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, ["SelfContained=true", "PublishSingleFile=true", "PublishTrimmed=true", "TrimMode=full", - "IncludeNativeLibrariesForSelfExtract=true"], cancellationToken); + "IncludeNativeLibrariesForSelfExtract=true"], + cancellationToken + ); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs index 0d648da59..2007356c1 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs @@ -41,20 +41,31 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + this.capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); } - /// - public ManagedDeploymentId id => ManagedDeploymentId.nativeAot; + /// + public ManagedDeploymentID id => ManagedDeploymentID.nativeAot; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, - ["SelfContained=true", "PublishAot=true", "PublishTrimmed=true", "TrimMode=full"], cancellationToken); + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, + ["SelfContained=true", "PublishAot=true", "PublishTrimmed=true", "TrimMode=full"], + cancellationToken + ); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs index 70dae8148..e7173ca2a 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs @@ -10,7 +10,7 @@ namespace Inno.Build.Managed.DotNet; internal static class DotNetDeploymentPublisher { internal static async ValueTask PublishAsync( - ManagedDeploymentId id, + ManagedDeploymentID id, ManagedDeploymentCapabilities capabilities, string hostPath, IToolchainWorkspaceProvider workspaces, @@ -20,10 +20,17 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(request); if (!capabilities.runtimeIdentifiers.Contains(request.runtimeIdentifier, StringComparer.Ordinal)) + { throw new InvalidOperationException($"Managed deployment '{id}' does not support '{request.runtimeIdentifier}'."); - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(hostPath, - request.projectPath, cancellationToken).ConfigureAwait(false); - return await DotNetPublishExecutor.PublishAsync(new DotNetPublishRequest(sdk, - id, request, properties, workspaces), cancellationToken).ConfigureAwait(false); + } + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( + hostPath, + request.projectPath, + cancellationToken + ).ConfigureAwait(false); + return await DotNetPublishExecutor.PublishAsync( + new DotNetPublishRequest(sdk, id, request, properties, workspaces), + cancellationToken + ).ConfigureAwait(false); } } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs index c2ce40e67..089ad6b91 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs @@ -18,48 +18,87 @@ CancellationToken cancellationToken ) { ManagedDeploymentRequest publication = request.publication; if (!Directory.Exists(publication.codeInputDirectory)) + { throw new DirectoryNotFoundException("The frozen managed code input directory is absent."); + } if (Directory.Exists(publication.outputDirectory) - && Directory.EnumerateFileSystemEntries(publication.outputDirectory).Any()) + && Directory.EnumerateFileSystemEntries(publication.outputDirectory).Any() + ) { throw new InvalidOperationException("Managed publication requires an empty staging directory."); + } Directory.CreateDirectory(publication.logDirectory); - await File.WriteAllTextAsync(Path.Combine(publication.logDirectory, "managed-sdk.txt"), - request.sdk.sdkIdentity, cancellationToken).ConfigureAwait(false); - await File.WriteAllTextAsync(Path.Combine(publication.logDirectory, "managed-cli.txt"), - request.sdk.cliPath, cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(publication.logDirectory, "managed-sdk.txt"), + request.sdk.sdkIdentity, + cancellationToken + ).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(publication.logDirectory, "managed-cli.txt"), + request.sdk.cliPath, + cancellationToken + ).ConfigureAwait(false); string physicalProjectDirectory = Path.GetDirectoryName(publication.projectPath)!; using ToolchainWorkingDirectory workspace = await request.workspaces.OpenAsync( - physicalProjectDirectory, cancellationToken).ConfigureAwait(false); - await File.WriteAllLinesAsync(Path.Combine(publication.logDirectory, "managed-working-directory.txt"), - [physicalProjectDirectory, workspace.toolPath], cancellationToken).ConfigureAwait(false); - var arguments = new List - { - request.sdk.cliPath, "publish", Path.Combine(workspace.toolPath, Path.GetFileName(publication.projectPath)), - "--disable-build-servers", "-m:1", "-nodeReuse:false", - "--configuration", "Release", "--runtime", publication.runtimeIdentifier, - "--output", publication.outputDirectory, "--nologo", - "-p:DebugType=None", "-p:DebugSymbols=false", - "-p:TreatWarningsAsErrors=true", "-p:TrimmerSingleWarn=false", + physicalProjectDirectory, + cancellationToken + ).ConfigureAwait(false); + await File.WriteAllLinesAsync( + Path.Combine(publication.logDirectory, "managed-working-directory.txt"), + [physicalProjectDirectory, workspace.toolPath], + cancellationToken + ).ConfigureAwait(false); + List arguments = + [ + request.sdk.cliPath, + "publish", + Path.Combine(workspace.toolPath, Path.GetFileName(publication.projectPath)), + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--configuration", + "Release", + "--runtime", + publication.runtimeIdentifier, + "--output", + publication.outputDirectory, + "--nologo", + "-p:DebugType=None", + "-p:DebugSymbols=false", + "-p:TreatWarningsAsErrors=true", + "-p:TrimmerSingleWarn=false", "-p:InnoGameManagedRoot=" + publication.codeInputDirectory - }; + ]; arguments.AddRange(request.properties.Select(static property => "-p:" + property)); await using var output = new TailLogWriter(Path.Combine(publication.logDirectory, "managed-output.log")); await using var error = new TailLogWriter(Path.Combine(publication.logDirectory, "managed-error.log")); try { - await ToolchainEnvironment.RunAsync(request.sdk.hostPath, arguments, - workspace.toolPath, cancellationToken, - DotNetSdkEnvironment.Create(request.sdk.hostPath), output, error).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + request.sdk.hostPath, + arguments, + workspace.toolPath, + DotNetSdkEnvironment.Create(request.sdk.hostPath), + output, + error, + cancellationToken + ).ConfigureAwait(false); } catch (InvalidOperationException exception) { - throw new InvalidOperationException($"Managed deployment '{request.deployment}' failed." - + Environment.NewLine + output.tail + Environment.NewLine + error.tail, exception); + throw new InvalidOperationException( + $"Managed deployment '{request.deployment}' failed." + + Environment.NewLine + output.tail + Environment.NewLine + error.tail, + exception + ); } if (!Directory.Exists(publication.outputDirectory)) + { throw new InvalidOperationException("The managed publisher produced no output directory."); + } string[] files = Directory.EnumerateFiles(publication.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(publication.outputDirectory, file)).Order(StringComparer.Ordinal).ToArray(); + .Select(file => Path.GetRelativePath(publication.outputDirectory, file)) + .Order(StringComparer.Ordinal) + .ToArray(); return new ManagedDeploymentResult(request.deployment, publication.outputDirectory, request.sdk.sdkIdentity, files); } @@ -68,25 +107,32 @@ private sealed class TailLogWriter : TextWriter private readonly StreamWriter m_log; private readonly Queue m_tail = new(); - internal TailLogWriter(string path) => m_log = new StreamWriter(path, append: false); - - internal string tail => string.Join(Environment.NewLine, m_tail); + internal TailLogWriter(string path) + { + m_log = new StreamWriter(path, append: false); + } - /// + /// public override Encoding Encoding => Encoding.UTF8; - /// + /// public override async Task WriteLineAsync(string? value) { await m_log.WriteLineAsync(value).ConfigureAwait(false); if (value is null) + { return; + } m_tail.Enqueue(value.Length <= 4096 ? value : value[..4096]); if (m_tail.Count > 100) + { m_tail.Dequeue(); + } } - /// + /// public override ValueTask DisposeAsync() => m_log.DisposeAsync(); + + internal string tail => string.Join(Environment.NewLine, m_tail); } } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishRequest.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishRequest.cs index e873b27f5..a09dab047 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishRequest.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishRequest.cs @@ -6,7 +6,7 @@ namespace Inno.Build.Managed.DotNet; internal sealed record DotNetPublishRequest( DotNetSdkDescriptor sdk, - ManagedDeploymentId deployment, + ManagedDeploymentID deployment, ManagedDeploymentRequest publication, IReadOnlyList properties, IToolchainWorkspaceProvider workspaces diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs index 6c2ea9f80..fcc657bd9 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs @@ -21,15 +21,15 @@ public sealed class MonoWasmDeploymentCompiler : IManagedDeploymentCompiler /// /// The .NET executable whose project resolution selects the matching WebAssembly workload. /// - /// - /// Whether managed code is compiled ahead of browser execution. - /// /// /// The platform-contributed managed targets authorized for this implementation. /// /// /// The explicit host execution path provider. /// + /// + /// Whether managed code is compiled ahead of browser execution. + /// /// /// The SDK host is empty or runtime targets are empty, unassigned, or repeated. /// @@ -47,21 +47,36 @@ bool aheadOfTime m_hostPath = hostPath; m_workspaces = workspaces; m_aheadOfTime = aheadOfTime; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: false, aheadOfTime: aheadOfTime, nativeStaticLinking: true); + this.capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: false, + aheadOfTime: aheadOfTime, + nativeStaticLinking: true + ); } - /// - public ManagedDeploymentId id => m_aheadOfTime ? ManagedDeploymentId.monoWasmAot : ManagedDeploymentId.monoWasm; + /// + public ManagedDeploymentID id => m_aheadOfTime ? ManagedDeploymentID.monoWasmAot : ManagedDeploymentID.monoWasm; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, - ["WasmBuildNative=true", "PublishTrimmed=true", "TrimMode=full", - "RunAOTCompilation=" + (m_aheadOfTime ? "true" : "false")], cancellationToken); + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, + [ + "WasmBuildNative=true", + "PublishTrimmed=true", + "TrimMode=full", + "RunAOTCompilation=" + (m_aheadOfTime ? "true" : "false") + ], + cancellationToken + ); } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs index 46fc8986a..2bcf35cc5 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; -using System.Reflection; using System.Linq; +using System.Reflection; using System.Runtime.ExceptionServices; -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Adapter.Modules.DotNet; @@ -14,29 +13,39 @@ namespace Inno.Adapter.Modules.DotNet; /// public sealed class ReflectionTypeCatalogSource : ITypeCatalogSource { - /// + /// public IReadOnlyList GetTypes(Assembly assembly) { ArgumentNullException.ThrowIfNull(assembly); return assembly.GetTypes(); } - /// + /// public TypeCatalogMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); - var ancestors = new List(); + List ancestors = []; for (Type? current = type.BaseType; current is not null && current != typeof(object); current = current.BaseType) + { ancestors.Add(current); - return new TypeCatalogMetadata(type, ancestors, type.GetInterfaces(), + } + return new TypeCatalogMetadata( + type, + ancestors, + type.GetInterfaces(), type.GetCustomAttributes(inherit: false).OfType().ToArray(), type.GetCustomAttributes(inherit: true).OfType().ToArray(), type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) - .Where(static method => !method.IsGenericMethod && method.GetParameters().Length == 0 && - method.GetBaseDefinition().DeclaringType != method.DeclaringType) - .Select(static method => (method.Name, method.GetBaseDefinition().DeclaringType!)).ToArray()); + .Where(static method => ( + !method.IsGenericMethod && method.GetParameters().Length == 0 + && method.GetBaseDefinition().DeclaringType != method.DeclaringType + )) + .Select(static method => (method.Name, method.GetBaseDefinition().DeclaringType!)) + .ToArray() + ); } - /// + + /// public Type? ConstructGenericType( Type definition, IReadOnlyList arguments @@ -44,10 +53,14 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!definition.IsGenericTypeDefinition) + { throw new ArgumentException("The declaration must be a generic type definition.", nameof(definition)); - if (arguments.Count != definition.GetGenericArguments().Length || - arguments.Any(static argument => argument is null || argument.ContainsGenericParameters)) + } + if (arguments.Count != definition.GetGenericArguments().Length + || arguments.Any(static argument => argument is null || argument.ContainsGenericParameters) + ) { throw new ArgumentException("The complete closed type argument set is required.", nameof(arguments)); + } try { return definition.MakeGenericType(arguments.ToArray()); @@ -58,23 +71,27 @@ IReadOnlyList arguments } } - /// + /// public bool CanCreateInstance(Type type) { ArgumentNullException.ThrowIfNull(type); - return !type.IsAbstract && !type.ContainsGenericParameters && - (type.IsValueType || type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, Type.EmptyTypes, modifiers: null) is not null); + return !type.IsAbstract && !type.ContainsGenericParameters + && (type.IsValueType || type.GetConstructor( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is not null); } - /// + /// public object CreateInstance(Type type) { ArgumentNullException.ThrowIfNull(type); try { return Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException($"Type '{type}' did not produce an instance."); + ?? throw new InvalidOperationException($"Type '{type}' did not produce an instance."); } catch (TargetInvocationException exception) when (exception.InnerException is not null) { diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs index 1fd54dcef..dd0602de9 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs @@ -36,49 +36,61 @@ public DotNetAssemblyCatalogSource(params Assembly[] roots) { ArgumentNullException.ThrowIfNull(roots); if (roots.Length == 0) + { throw new ArgumentException("At least one composition root is required.", nameof(roots)); + } m_roots = roots.Distinct().ToArray(); m_hostLoadContext = AssemblyLoadContext.GetLoadContext(m_roots[0])!; - if (m_roots.Any(assembly => - AssemblyLoadContext.GetLoadContext(assembly) != m_hostLoadContext)) + if (m_roots.Any(assembly => AssemblyLoadContext.GetLoadContext(assembly) != m_hostLoadContext)) + { throw new ArgumentException("Composition roots must share one load context.", nameof(roots)); + } PreloadInnoHostDependencies(); AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded; } - /// + /// public event Action? changed; - /// + /// public IReadOnlyList GetAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); lock (m_ownedAssemblies) - return m_ownedAssemblies.Where(static assembly => - assembly.TryGetInnoAssemblyClassification(out AssemblyDomain domain, out _) && - domain == AssemblyDomain.InnoInternal).ToArray(); + { + return m_ownedAssemblies.Where(static assembly => ( + assembly.TryGetInnoAssemblyClassification(out AssemblyDomain domain, out _) + && domain == AssemblyDomain.InnoInternal + )).ToArray(); + } } - /// + /// public IReadOnlyList GetSharedAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); lock (m_ownedAssemblies) - return m_ownedAssemblies.Concat(AppDomain.CurrentDomain.GetAssemblies() - .Where(IsTrustedFrameworkAssembly)).Distinct().ToArray(); + { + return m_ownedAssemblies.Concat( + AppDomain.CurrentDomain.GetAssemblies() + .Where(IsTrustedFrameworkAssembly) + ).Distinct().ToArray(); + } } - /// + /// public bool IsFrameworkReference(string assemblyName) => m_trustedPlatformAssemblies.Contains(assemblyName); - /// + /// public bool IsFrameworkAssembly(Assembly assembly) => IsTrustedFrameworkAssembly(assembly); - /// + /// public void Dispose() { if (m_disposed) + { return; + } AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded; changed = null; m_ownedAssemblies.Clear(); @@ -92,12 +104,16 @@ AssemblyLoadEventArgs args // Discovery remains the explicit composition closure. New assemblies become visible only // when referenced by a root; arbitrary assemblies in the process never enter the catalog. if (AssemblyLoadContext.GetLoadContext(args.LoadedAssembly) != m_hostLoadContext) + { return; + } int previousCount; lock (m_ownedAssemblies) { if (m_disposed || m_discovering) + { return; + } previousCount = m_ownedAssemblies.Count; m_discovering = true; try @@ -109,7 +125,9 @@ AssemblyLoadEventArgs args m_discovering = false; } if (m_ownedAssemblies.Count == previousCount) + { return; + } } changed?.Invoke(); } @@ -118,7 +136,9 @@ private void PreloadInnoHostDependencies() { Assembly[] roots = m_roots; if (roots.Length == 0) + { return; + } var visited = new HashSet(StringComparer.OrdinalIgnoreCase); var pending = new Queue(); @@ -126,21 +146,28 @@ private void PreloadInnoHostDependencies() { string rootName = root.GetName().Name ?? string.Empty; if (!string.IsNullOrEmpty(rootName)) + { visited.Add(rootName); + } m_ownedAssemblies.Add(root); pending.Enqueue(root); } foreach (KeyValuePair dependency in HostDependencyManifest.GetInnoRuntimeAssemblies(roots) - .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase)) + .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) + ) { TryEnqueueHostAssembly(new AssemblyName(dependency.Key), visited, pending, dependency.Value); + } while (pending.Count > 0) { Assembly assembly = pending.Dequeue(); foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) + { TryEnqueueHostAssembly(reference, visited, pending); + } } } + private void TryEnqueueHostAssembly( AssemblyName assemblyName, ISet visited, @@ -149,32 +176,40 @@ private void TryEnqueueHostAssembly( ) { string name = assemblyName.Name ?? string.Empty; if (!name.StartsWith("Inno.", StringComparison.Ordinal) || !visited.Add(name)) + { return; + } Assembly assembly = manifestPath is null - ? m_hostLoadContext.LoadFromAssemblyName(assemblyName) - : m_hostLoadContext.LoadFromAssemblyPath(manifestPath); + ? m_hostLoadContext.LoadFromAssemblyName(assemblyName) + : m_hostLoadContext.LoadFromAssemblyPath(manifestPath); lock (m_ownedAssemblies) + { m_ownedAssemblies.Add(assembly); + } pending.Enqueue(assembly); } + private static HashSet GetTrustedPlatformAssemblyNames() { string paths = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string ?? string.Empty; return paths.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) - .Select(Path.GetFileNameWithoutExtension).OfType() + .Select(Path.GetFileNameWithoutExtension) + .OfType() .ToHashSet(StringComparer.OrdinalIgnoreCase); } private static bool IsTrustedFrameworkAssembly(Assembly assembly) { if (AssemblyLoadContext.GetLoadContext(assembly) != AssemblyLoadContext.Default) + { return false; + } AssemblyName identity = assembly.GetName(); string name = identity.Name ?? string.Empty; if (!name.StartsWith("System.", StringComparison.Ordinal) && !name.StartsWith("Microsoft.Win32.", StringComparison.Ordinal) - && name is not ("System" or "netstandard" or "mscorlib")) - { + && name is not ("System" or "netstandard" or "mscorlib") + ) { return false; } string token = Convert.ToHexString(identity.GetPublicKeyToken() ?? []); diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs index 8e721ac88..469af21c0 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -32,7 +33,7 @@ public sealed class DotNetModuleSource : IModuleSource /// /// Gets or sets additional managed assemblies loaded into the same context. /// - public IReadOnlyList preloadAssemblyPaths { get; init; } = Array.Empty(); + public IReadOnlyList preloadAssemblyPaths { get; init; } = []; /// /// Gets stable module names whose exported assemblies may satisfy this module's managed dependencies. @@ -41,7 +42,7 @@ public sealed class DotNetModuleSource : IModuleSource /// Dependencies are explicit for every module. An empty collection declares that the module has no /// upstream module dependencies; the host never infers dependencies from process-wide active state. /// - public IReadOnlyList upstreamModuleNames { get; init; } = Array.Empty(); + public IReadOnlyList upstreamModuleNames { get; init; } = []; /// /// Gets or sets whether the module load context supports cooperative unloading. @@ -65,44 +66,47 @@ public sealed class DotNetModuleSource : IModuleSource /// This is used when one plugin generation contains both runtime and editor-only assemblies. /// Names not present in the map use . /// - public IReadOnlyDictionary assemblyScopes { get; init; } = - new Dictionary(StringComparer.OrdinalIgnoreCase); + public IReadOnlyDictionary assemblyScopes { get; init; } = new Dictionary( + StringComparer.OrdinalIgnoreCase + ); - /// + /// public IReadOnlyList GetAssemblyNames() { var names = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string path in new[] { mainAssemblyPath }.Concat(preloadAssemblyPaths)) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { throw new FileNotFoundException("A module assembly does not exist.", path); + } string name = AssemblyName.GetAssemblyName(path).Name - ?? throw new InvalidDataException($"Assembly '{path}' has no simple name."); + ?? throw new InvalidDataException($"Assembly '{path}' has no simple name."); if (!names.Add(name)) + { throw new InvalidDataException($"Module contains duplicate assembly name '{name}'."); + } } return names.OrderBy(static name => name, StringComparer.Ordinal).ToArray(); } - private bool HasRequestedClassification( - Assembly assembly, - AssemblyScope requestedScope - ) => assembly.GetInnoAssemblyDomain() == domain && assembly.GetInnoAssemblyScope() == requestedScope; - - /// + /// public ModuleCatalogContribution Prepare(ModuleSourceContext context) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(artifactRootDirectory); if (!Path.IsPathFullyQualified(artifactRootDirectory)) + { throw new ArgumentException("Dynamic module storage requires an absolute adapter-owned root.", nameof(artifactRootDirectory)); + } DotNetModuleSource request = this; _ = GetAssemblyNames(); string generationDirectory = Path.Combine( artifactRootDirectory, SanitizePathSegment(request.moduleName), - context.generation.ToString(System.Globalization.CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N")); + context.generation.ToString(CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(generationDirectory); string[] sourcePaths = new[] { request.mainAssemblyPath } @@ -115,9 +119,11 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) foreach (string sourcePath in sourcePaths) { string assemblyName = AssemblyName.GetAssemblyName(sourcePath).Name - ?? throw new InvalidOperationException($"Assembly '{sourcePath}' has no simple name."); + ?? throw new InvalidOperationException($"Assembly '{sourcePath}' has no simple name."); if (shadowPathsByName.ContainsKey(assemblyName)) + { throw new InvalidOperationException($"Module contains duplicate assembly name '{assemblyName}'."); + } string shadowPath = CopyAssemblyArtifacts(sourcePath, generationDirectory, assemblyName); shadowPathsByName.Add(assemblyName, shadowPath); explicitShadowPaths.Add(shadowPath); @@ -133,13 +139,15 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) IReadOnlyDictionary sharedAssemblies = BuildSharedAssemblies( request, context, - shadowPathsByName.Keys); + shadowPathsByName.Keys + ); var loadContext = new ModuleLoadContext( $"{request.moduleName}#{context.generation}", mainShadowPath, request.collectible, sharedAssemblies, - shadowPathsByName.Values); + shadowPathsByName.Values + ); try { @@ -151,10 +159,12 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) { string name = AssemblyName.GetAssemblyName(shadowPath).Name ?? string.Empty; if (assemblies.Any(assembly => string.Equals( - assembly.GetName().Name, - name, - StringComparison.OrdinalIgnoreCase))) + assembly.GetName().Name, + name, + StringComparison.OrdinalIgnoreCase + ))) { continue; + } assemblies.Add(loadContext.LoadFromAssemblyPath(shadowPath)); } @@ -164,11 +174,12 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) { string simpleName = assembly.GetName().Name ?? string.Empty; AssemblyScope assemblyScope = request.assemblyScopes.GetValueOrDefault(simpleName, request.scope); - if (request.domain == AssemblyDomain.InnoScripting && - (!HasRequestedClassification(assembly, assemblyScope))) - { + if (request.domain == AssemblyDomain.InnoScripting + && (!HasRequestedClassification(assembly, assemblyScope)) + ) { throw new InvalidDataException( - $"Script assembly '{simpleName}' does not declare its requested domain and scope metadata."); + $"Script assembly '{simpleName}' does not declare its requested domain and scope metadata." + ); } loadedScopes.Add(assembly, assemblyScope); } @@ -179,12 +190,21 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) loadedScopes, sharedAssemblies, context.upstreamModules, - context.plannedAssemblies); + context.plannedAssemblies + ); return new ModuleCatalogContribution( - moduleName, domain, scope, loadedAssemblies, loadedScopes, - new DotNetModuleLifetime(loadContext, generationDirectory, - $"{moduleName} ({domain}/{scope}, generation {context.generation})")); + moduleName, + domain, + scope, + loadedAssemblies, + loadedScopes, + new DotNetModuleLifetime( + loadContext, + generationDirectory, + $"{moduleName} ({domain}/{scope}, generation {context.generation})" + ) + ); } catch { @@ -196,14 +216,19 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) } throw; } - } + + private bool HasRequestedClassification( + Assembly assembly, + AssemblyScope requestedScope + ) => assembly.GetInnoAssemblyDomain() == domain && assembly.GetInnoAssemblyScope() == requestedScope; + private static IReadOnlyDictionary BuildSharedAssemblies( DotNetModuleSource request, ModuleSourceContext context, IEnumerable ownedNames ) { - var result = context.host.GetSharedAssemblies() + Dictionary result = context.host.GetSharedAssemblies() .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); var owned = new HashSet(ownedNames, StringComparer.OrdinalIgnoreCase); @@ -212,7 +237,8 @@ IEnumerable ownedNames if (result.ContainsKey(ownedName)) { throw new InvalidDataException( - $"Module assembly '{ownedName}' duplicates an assembly already shared by the host context."); + $"Module assembly '{ownedName}' duplicates an assembly already shared by the host context." + ); } } @@ -220,18 +246,21 @@ IEnumerable ownedNames { foreach (Assembly assembly in upstream.assemblies) { - if (request.scope == AssemblyScope.Runtime && - upstream.assemblyScopes[assembly] == AssemblyScope.Editor) - { + if (request.scope == AssemblyScope.Runtime + && upstream.assemblyScopes[assembly] == AssemblyScope.Editor + ) { continue; } string name = assembly.GetName().Name ?? string.Empty; if (owned.Contains(name) || !result.TryAdd(name, assembly)) + { throw new InvalidDataException($"Reload graph contains duplicate managed assembly name '{name}'."); + } } } return result; } + private static void ValidateLoadedModule( DotNetModuleSource request, ModuleSourceContext context, @@ -241,23 +270,27 @@ private static void ValidateLoadedModule( IReadOnlyList upstreamModules, IReadOnlyDictionary plannedAssemblies ) { - var ownByName = assemblies.ToDictionary( + Dictionary ownByName = assemblies.ToDictionary( static assembly => assembly.GetName().Name ?? string.Empty, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); ValidateOwnedDependencyGraph(ownByName); - var forbiddenDownstreamNames = context.activeModules - .Where(module => request.domain == AssemblyDomain.InnoPlugin + HashSet forbiddenDownstreamNames = context.activeModules + .Where(module => ( + request.domain == AssemblyDomain.InnoPlugin ? module.domain == AssemblyDomain.InnoScripting - : request.scope == AssemblyScope.Runtime && module.scope == AssemblyScope.Editor) + : request.scope == AssemblyScope.Runtime && module.scope == AssemblyScope.Editor + )) .SelectMany(static module => module.assemblies) .Select(static assembly => assembly.GetName().Name ?? string.Empty) .ToHashSet(StringComparer.OrdinalIgnoreCase); - var upstreamByName = upstreamModules + Dictionary upstreamByName = upstreamModules .SelectMany(module => module.assemblies.Select(assembly => (module, assembly))) .ToDictionary( static pair => pair.assembly.GetName().Name ?? string.Empty, static pair => pair, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); foreach (Assembly assembly in assemblies) { @@ -267,90 +300,104 @@ IReadOnlyDictionary plannedAssemblies string name = reference.Name ?? string.Empty; if (ownByName.TryGetValue(name, out Assembly? ownedDependency)) { - if (sourceScope == AssemblyScope.Runtime && - assemblyScopes[ownedDependency] == AssemblyScope.Editor) - { + if (sourceScope == AssemblyScope.Runtime + && assemblyScopes[ownedDependency] == AssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } continue; } if (forbiddenDownstreamNames.Contains(name)) { throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' has a forbidden downstream reference to '{name}'."); + $"Assembly '{assembly.GetName().Name}' has a forbidden downstream reference to '{name}'." + ); } - if (upstreamByName.TryGetValue(name, out var upstream)) + if (upstreamByName.TryGetValue(name, out (ModuleCatalogContribution module, Assembly assembly) upstream)) { - if (sourceScope == AssemblyScope.Runtime && - upstream.module.assemblyScopes[upstream.assembly] == AssemblyScope.Editor) - { + if (sourceScope == AssemblyScope.Runtime + && upstream.module.assemblyScopes[upstream.assembly] == AssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } continue; } if (plannedAssemblies.TryGetValue(name, out ModuleAssemblyDescriptor planned)) { - if (request.domain == AssemblyDomain.InnoPlugin && - planned.domain == AssemblyDomain.InnoScripting) - { + if (request.domain == AssemblyDomain.InnoPlugin + && planned.domain == AssemblyDomain.InnoScripting + ) { throw new InvalidDataException( - $"Plugin assembly '{assembly.GetName().Name}' cannot reference project script assembly '{name}'."); + $"Plugin assembly '{assembly.GetName().Name}' cannot reference project script assembly '{name}'." + ); } if (sourceScope == AssemblyScope.Runtime && planned.scope == AssemblyScope.Editor) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' has an unavailable downstream reference to '{name}'."); + $"Assembly '{assembly.GetName().Name}' has an unavailable downstream reference to '{name}'." + ); } if (context.host.IsFrameworkReference(name) || (sharedAssemblies.TryGetValue(name, out Assembly? platformAssembly) - && context.host.IsFrameworkAssembly(platformAssembly))) + && context.host.IsFrameworkAssembly(platformAssembly)) + ) { continue; + } if (sharedAssemblies.TryGetValue(name, out Assembly? sharedAssembly)) { if (sharedAssembly.GetInnoAssemblyDomain() != AssemblyDomain.InnoInternal) { throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' can only share BCL or InnoInternal contracts, not '{name}'."); + $"Assembly '{assembly.GetName().Name}' can only share BCL or InnoInternal contracts, not '{name}'." + ); } if (sourceScope == AssemblyScope.Runtime && sharedAssembly.GetInnoAssemblyScope() == AssemblyScope.Editor) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor contract '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor contract '{name}'." + ); } continue; } throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' references unavailable assembly '{name}'. " + - "Include the dependency in its module or load an InnoInternal contract in the host."); + $"Assembly '{assembly.GetName().Name}' references unavailable assembly '{name}'. " + + "Include the dependency in its module or load an InnoInternal contract in the host." + ); } } } + private static void ValidateOwnedDependencyGraph(IReadOnlyDictionary assemblies) { - var graph = new DependencyGraph( - StringComparer.OrdinalIgnoreCase, - StringComparer.Ordinal); + var graph = new DependencyGraph(StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal); foreach (string name in assemblies.Keys) + { graph.AddNode(name); + } foreach ((string name, Assembly assembly) in assemblies) { foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) { if (reference.Name is string dependency && assemblies.ContainsKey(dependency)) + { graph.AddDependency(name, dependency); + } } } if (graph.TryFindCycle(out IReadOnlyList cycle)) { - throw new InvalidDataException( - $"Module assembly reference cycle: {string.Join(" -> ", cycle)}."); + throw new InvalidDataException($"Module assembly reference cycle: {string.Join(" -> ", cycle)}."); } } + private static string CopyAssemblyArtifacts( string sourcePath, string destinationDirectory, @@ -360,12 +407,17 @@ string assemblyName File.Copy(sourcePath, destinationPath, overwrite: true); string sourcePdb = Path.ChangeExtension(sourcePath, ".pdb"); if (File.Exists(sourcePdb)) + { File.Copy(sourcePdb, Path.Combine(destinationDirectory, Path.GetFileName(sourcePdb)), overwrite: true); + } string sourceDeps = Path.ChangeExtension(sourcePath, ".deps.json"); if (File.Exists(sourceDeps)) + { File.Copy(sourceDeps, Path.Combine(destinationDirectory, Path.GetFileName(sourceDeps)), overwrite: true); + } return destinationPath; } + private static string SanitizePathSegment(string value) { char[] invalid = Path.GetInvalidFileNameChars(); diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs index 33918ecd0..372a9b9f1 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs @@ -16,7 +16,9 @@ internal static IReadOnlyDictionary GetInnoRuntimeAssemblies(IRe var names = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string dependencyFile in GetDependencyFiles(rootAssemblies)) + { ReadRuntimeAssemblyNames(dependencyFile, names); + } return names; } @@ -29,10 +31,14 @@ private static IReadOnlyList GetDependencyFiles(IReadOnlyList { string location = rootAssembly.Location; if (string.IsNullOrWhiteSpace(location)) + { continue; + } string dependencyFile = Path.ChangeExtension(location, ".deps.json"); if (File.Exists(dependencyFile)) + { paths.Add(Path.GetFullPath(dependencyFile)); + } } return paths.ToArray(); } @@ -46,24 +52,30 @@ IDictionary names using FileStream stream = File.OpenRead(dependencyFile); using JsonDocument document = JsonDocument.Parse(stream); if (!document.RootElement.TryGetProperty("targets", out JsonElement targets)) + { return; + } foreach (JsonProperty target in targets.EnumerateObject()) { foreach (JsonProperty library in target.Value.EnumerateObject()) { if (!library.Value.TryGetProperty("runtime", out JsonElement runtime)) + { continue; + } foreach (JsonProperty asset in runtime.EnumerateObject()) { string fileName = Path.GetFileName(asset.Name); - if (!fileName.StartsWith("Inno.", StringComparison.Ordinal) || - !fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) - { + if (!fileName.StartsWith("Inno.", StringComparison.Ordinal) + || !fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ) { continue; } - names.TryAdd(Path.GetFileNameWithoutExtension(fileName), - Path.Combine(Path.GetDirectoryName(dependencyFile)!, fileName)); + names.TryAdd( + Path.GetFileNameWithoutExtension(fileName), + Path.Combine(Path.GetDirectoryName(dependencyFile)!, fileName) + ); } } } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs index ec5e12f52..94217d203 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs @@ -11,8 +11,8 @@ namespace Inno.Adapter.Modules.DotNet; internal sealed class ModuleLoadContext : AssemblyLoadContext { private readonly AssemblyDependencyResolver m_resolver; - private IReadOnlyDictionary m_sharedAssemblies; private readonly IReadOnlyDictionary m_moduleAssemblyPaths; + private IReadOnlyDictionary m_sharedAssemblies; internal ModuleLoadContext( string name, @@ -20,17 +20,19 @@ internal ModuleLoadContext( bool collectible, IReadOnlyDictionary sharedAssemblies, IEnumerable moduleAssemblyPaths - ) - : base(name, collectible) + ) : base(name, collectible) { m_resolver = new AssemblyDependencyResolver(mainAssemblyPath); m_sharedAssemblies = sharedAssemblies; m_moduleAssemblyPaths = moduleAssemblyPaths.ToDictionary( - static path => AssemblyName.GetAssemblyName(path).Name - ?? throw new InvalidOperationException($"Assembly '{path}' has no simple name."), + static path => ( + AssemblyName.GetAssemblyName(path).Name + ?? throw new InvalidOperationException($"Assembly '{path}' has no simple name.") + ), static path => path, - StringComparer.OrdinalIgnoreCase); - Unloading += ReleaseSharedAssemblies; + StringComparer.OrdinalIgnoreCase + ); + this.Unloading += ReleaseSharedAssemblies; } /// @@ -51,18 +53,33 @@ IEnumerable moduleAssemblyPaths return sharedAssembly; } if (m_moduleAssemblyPaths.TryGetValue(simpleName, out string? modulePath)) + { return LoadFromAssemblyPath(modulePath); + } return null; } - private static void ReleaseSharedAssemblies(AssemblyLoadContext context) + /// + /// Loads a native dependency through the module's isolated resolution policy. + /// + /// + /// The unmanaged dll name text validated by the load unmanaged dll operation. + /// + /// + /// The validated int ptr that represents the completed operation. + /// + protected override nint LoadUnmanagedDll(string unmanagedDllName) { + string? dependencyPath = m_resolver.ResolveUnmanagedDllToPath(unmanagedDllName); + return dependencyPath is null ? nint.Zero : LoadUnmanagedDllFromPath(dependencyPath); + } + + private static void ReleaseSharedAssemblies(AssemblyLoadContext context) => // The runtime retains an unloading context until its loader allocator can retire. Keeping // another collectible assembly in this resolver can turn cross-context generic dependencies // into a retention cycle, even after every engine registry has released its generation. ((ModuleLoadContext)context).m_sharedAssemblies = FrozenDictionary.Empty; - } private static void ValidateSharedIdentity( AssemblyName requested, @@ -73,29 +90,15 @@ AssemblyName shared string sharedCulture = shared.CultureName ?? string.Empty; byte[] requestedToken = requested.GetPublicKeyToken() ?? []; byte[] sharedToken = shared.GetPublicKeyToken() ?? []; - if (versionMatches && - string.Equals(requestedCulture, sharedCulture, StringComparison.OrdinalIgnoreCase) && - requestedToken.SequenceEqual(sharedToken)) - { + if (versionMatches + && string.Equals(requestedCulture, sharedCulture, StringComparison.OrdinalIgnoreCase) + && requestedToken.SequenceEqual(sharedToken) + ) { return; } throw new FileLoadException( - $"Module dependency '{requested.FullName}' is incompatible with shared engine assembly '{shared.FullName}'."); - } - - /// - /// Loads a native dependency through the module's isolated resolution policy. - /// - /// - /// The unmanaged dll name text validated by the load unmanaged dll operation. - /// - /// - /// The validated int ptr that represents the completed operation. - /// - protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) - { - string? dependencyPath = m_resolver.ResolveUnmanagedDllToPath(unmanagedDllName); - return dependencyPath is null ? IntPtr.Zero : LoadUnmanagedDllFromPath(dependencyPath); + $"Module dependency '{requested.FullName}' is incompatible with shared engine assembly '{shared.FullName}'." + ); } } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs index 97ba213ab..3c129d28c 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs @@ -6,22 +6,6 @@ namespace Inno.Adapter.Modules.DotNet; -/// -/// Describes whether a collectible load context is still reachable. -/// -internal enum AssemblyUnloadStatus -{ - /// - /// At least one runtime reference still keeps the load context alive. - /// - Pending, - - /// - /// The load context is no longer reachable, or the module was not collectible. - /// - Completed -} - /// /// Observes cooperative unload completion without retaining the old load context. /// @@ -31,8 +15,15 @@ internal sealed class AssemblyUnloadMonitor : IAssemblyUnloadProbe private readonly WeakReference? m_loadContext; private readonly string? m_shadowDirectory; private readonly AssemblyUnloadMonitor[]? m_children; - private bool m_isShadowDirectoryCleaned; private readonly string m_description; + private bool m_isShadowDirectoryCleaned; + + internal AssemblyUnloadMonitor(IReadOnlyList children) + { + ArgumentNullException.ThrowIfNull(children); + m_children = children.ToArray(); + m_description = string.Join(", ", m_children.Select(static child => child.description)); + } internal AssemblyUnloadMonitor( WeakReference? loadContext, @@ -44,13 +35,6 @@ internal AssemblyUnloadMonitor( m_description = description ?? "non-collectible assembly generation"; } - internal AssemblyUnloadMonitor(IReadOnlyList children) - { - ArgumentNullException.ThrowIfNull(children); - m_children = children.ToArray(); - m_description = string.Join(", ", m_children.Select(static child => child.description)); - } - /// /// Gets a stable diagnostic description of the retired assembly generation. /// @@ -69,37 +53,47 @@ public AssemblyUnloadStatus status get { if (m_children is not null) + { return m_children.All(static child => child.isCompleted) - ? AssemblyUnloadStatus.Completed - : AssemblyUnloadStatus.Pending; + ? AssemblyUnloadStatus.Completed + : AssemblyUnloadStatus.Pending; + } if (m_loadContext is not null && m_loadContext.IsAlive) + { return AssemblyUnloadStatus.Pending; + } return TryCleanupShadowDirectory() - ? AssemblyUnloadStatus.Completed - : AssemblyUnloadStatus.Pending; + ? AssemblyUnloadStatus.Completed + : AssemblyUnloadStatus.Pending; } } internal bool TryCleanupShadowDirectory() { if (m_children is not null) + { return m_children.All(static child => child.TryCleanupShadowDirectory()); + } if (m_loadContext is not null && m_loadContext.IsAlive) + { return false; + } lock (m_sync) { if (m_isShadowDirectoryCleaned) + { return true; + } try { if (!string.IsNullOrWhiteSpace(m_shadowDirectory) && Directory.Exists(m_shadowDirectory)) { Directory.Delete(m_shadowDirectory, recursive: true); string? moduleDirectory = Path.GetDirectoryName(m_shadowDirectory); - if (!string.IsNullOrWhiteSpace(moduleDirectory) && - Directory.Exists(moduleDirectory) && - !Directory.EnumerateFileSystemEntries(moduleDirectory).Any()) - { + if (!string.IsNullOrWhiteSpace(moduleDirectory) + && Directory.Exists(moduleDirectory) + && !Directory.EnumerateFileSystemEntries(moduleDirectory).Any() + ) { Directory.Delete(moduleDirectory); } } @@ -117,3 +111,18 @@ internal bool TryCleanupShadowDirectory() } } } + +/// +/// Describes whether a collectible load context is still reachable. +/// +internal enum AssemblyUnloadStatus +{ + /// + /// At least one runtime reference still keeps the load context alive. + /// + Pending, + /// + /// The load context is no longer reachable, or the module was not collectible. + /// + Completed +} diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs index 7e10c3d4e..55c9211e9 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs @@ -7,9 +7,9 @@ namespace Inno.Adapter.Modules.DotNet; internal sealed class DotNetModuleLifetime : IModuleLifetime { - private AssemblyLoadContext? m_loadContext; private readonly string m_shadowDirectory; private readonly string m_description; + private AssemblyLoadContext? m_loadContext; private IAssemblyUnloadProbe? m_retirement; internal DotNetModuleLifetime( @@ -22,11 +22,13 @@ string description m_description = description; } - /// + /// public IAssemblyUnloadProbe BeginRetirement() { if (m_retirement is not null) + { return m_retirement; + } var reference = new WeakReference(m_loadContext!, trackResurrection: false); m_loadContext!.Unload(); m_loadContext = null; diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs index 7e0f882d7..ee40eb648 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; @@ -38,9 +37,9 @@ out Type elementType } Type candidateElementType = candidate.GetGenericArguments()[0]; - if (candidateElementType.IsGenericType && - candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) - { + if (candidateElementType.IsGenericType + && candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) + ) { continue; } @@ -98,7 +97,7 @@ out Type valueType internal static List EnumerateSequence(object? sequence) { - var values = new List(); + List values = []; if (sequence is not IEnumerable enumerable) { return values; @@ -186,7 +185,8 @@ internal static object BuildSequence( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, listType, - typeof(IEnumerable<>).MakeGenericType(elementType)); + typeof(IEnumerable<>).MakeGenericType(elementType) + ); if (constructor is not null) { return constructor.Invoke([list]); @@ -201,7 +201,7 @@ internal static object BuildSequence( if (!targetType.IsAbstract && ResolveSequenceAddMethod(targetType, elementType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); for (int i = 0; i < values.Count; i++) { addMethod.Invoke(instance, [values[i]]); @@ -211,7 +211,8 @@ internal static object BuildSequence( } throw new InvalidOperationException( - $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)."); + $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)." + ); } internal static object BuildMap( @@ -233,7 +234,8 @@ internal static object BuildMap( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, pairListType, - typeof(IEnumerable<>).MakeGenericType(pairType)); + typeof(IEnumerable<>).MakeGenericType(pairType) + ); if (constructor is not null) { return constructor.Invoke([pairList]); @@ -248,7 +250,7 @@ internal static object BuildMap( if (!targetType.IsAbstract && ResolveMapAddMethod(targetType, keyType, valueType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; @@ -259,7 +261,8 @@ internal static object BuildMap( } throw new InvalidOperationException( - $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)."); + $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)." + ); } private static object BuildTypedList( @@ -284,9 +287,7 @@ private static object BuildTypedDictionary( for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; - dictionary.Add( - entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), - entry.Value); + dictionary.Add(entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), entry.Value); } return dictionary; @@ -312,7 +313,8 @@ private static object BuildTypedKeyValueList( params Type[] candidateArgumentTypes ) { ConstructorInfo[] constructors = targetType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); @@ -336,15 +338,14 @@ params Type[] candidateArgumentTypes private static MethodInfo? FindFactory( Type targetType, Type argumentType - ) { - return targetType - .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => - (method.Name == "CreateRange" || method.Name == "Create") && - targetType.IsAssignableFrom(method.ReturnType) && - method.GetParameters().Length == 1 && - method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType)); - } + ) => targetType + .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); private static MethodInfo? ResolveSequenceAddMethod( Type targetType, @@ -355,7 +356,8 @@ Type elementType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [elementType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -363,8 +365,8 @@ Type elementType Type collectionInterface = typeof(ICollection<>).MakeGenericType(elementType); return collectionInterface.IsAssignableFrom(targetType) - ? collectionInterface.GetMethod("Add", [elementType]) - : null; + ? collectionInterface.GetMethod("Add", [elementType]) + : null; } private static MethodInfo? ResolveMapAddMethod( @@ -377,7 +379,8 @@ Type valueType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [keyType, valueType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -385,8 +388,8 @@ Type valueType Type dictionaryInterface = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); return dictionaryInterface.IsAssignableFrom(targetType) - ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) - : null; + ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) + : null; } private static IEnumerable EnumerateSelfAndInterfaces(Type type) diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs index c691ff3a3..9c6eb6733 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs @@ -3,36 +3,42 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; internal static class ReflectionObjectMetadata { - private const BindingFlags C_DECLARED_MEMBERS = - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Instance + | BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.DeclaredOnly; - private static readonly ConditionalWeakTable S_MEMBERS = new(); - private static readonly ConditionalWeakTable S_RESTORE_HOOKS = new(); + private static readonly ConditionalWeakTable MEMBERS = new(); + private static readonly ConditionalWeakTable RESTORE_HOOKS = new(); internal static SerializationMemberMetadata[] GetSerializableMembers(Type type) { ArgumentNullException.ThrowIfNull(type); - return S_MEMBERS.GetValue(type, static value => new MembersBox(BuildSerializableMembers(value))).members; + return MEMBERS.GetValue(type, static value => new MembersBox(BuildSerializableMembers(value))).members; } internal static Action? CreateRestoreHandler(Type type) { MethodInfo[] hooks = GetRestoreHooks(type); if (hooks.Length == 0) + { return null; + } return ( value, context - ) => { + ) => + { foreach (MethodInfo hook in hooks) + { hook.Invoke(value, hook.GetParameters().Length == 0 ? null : [context]); + } }; } @@ -40,7 +46,9 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti { var hierarchy = new List(8); for (Type? current = runtimeType; current is not null && current != typeof(object); current = current.BaseType) + { hierarchy.Add(current); + } hierarchy.Reverse(); var members = new List(32); @@ -56,22 +64,25 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti for (int i = 0; i < declaredMembers.Length; i++) { MemberInfo declaredMember = declaredMembers[i]; - SerializablePropertyAttribute? attribute = - declaredMember.GetCustomAttribute(inherit: true); + SerializablePropertyAttribute? attribute = declaredMember.GetCustomAttribute(inherit: true); if (attribute is null) + { continue; + } SerializationMemberMetadata member = declaredMember switch { FieldInfo field => CreateFieldMember(runtimeType, field, attribute.propertyVisibility), PropertyInfo property => CreatePropertyMember(runtimeType, property, attribute.propertyVisibility), _ => throw new InvalidOperationException( - $"Serializable member '{runtimeType.FullName}.{declaredMember.Name}' must be a field or property.") + $"Serializable member '{runtimeType.FullName}.{declaredMember.Name}' must be a field or property." + ) }; if (!names.Add(member.name)) { throw new InvalidOperationException( - $"Serializable type '{runtimeType.FullName}' declares duplicate serialized key '{member.name}' in its inheritance hierarchy."); + $"Serializable type '{runtimeType.FullName}' declares duplicate serialized key '{member.name}' in its inheritance hierarchy." + ); } members.Add(member); @@ -82,10 +93,8 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti } private static int GetSerializableOrder(MemberInfo member) - { - return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; - } + => member.GetCustomAttribute(inherit: true)?.order + ?? int.MaxValue; private static SerializationMemberMetadata CreateFieldMember( Type runtimeType, @@ -97,7 +106,8 @@ PropertyVisibility visibility if (requiresWrite && field.IsInitOnly) { throw new InvalidOperationException( - $"Serializable field '{runtimeType.FullName}.{field.Name}' must be writable for visibility '{visibility}'."); + $"Serializable field '{runtimeType.FullName}.{field.Name}' must be writable for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -105,7 +115,8 @@ PropertyVisibility visibility field.FieldType, visibility, requiresRead ? field.GetValue : null, - requiresWrite ? field.SetValue : null); + requiresWrite ? field.SetValue : null + ); } private static SerializationMemberMetadata CreatePropertyMember( @@ -114,7 +125,9 @@ private static SerializationMemberMetadata CreatePropertyMember( PropertyVisibility visibility ) { if (property.GetIndexParameters().Length != 0) + { throw new InvalidOperationException($"Serializable property '{runtimeType.FullName}.{property.Name}' cannot be an indexer."); + } bool requiresRead = RequiresRead(visibility); bool requiresWrite = RequiresWrite(visibility); @@ -123,12 +136,14 @@ PropertyVisibility visibility if (requiresRead && getter is null) { throw new InvalidOperationException( - $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'."); + $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'." + ); } if (requiresWrite && setter is null) { throw new InvalidOperationException( - $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'."); + $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -136,21 +151,20 @@ PropertyVisibility visibility property.PropertyType, visibility, getter is null ? null : property.GetValue, - setter is null ? null : property.SetValue); + setter is null ? null : property.SetValue + ); } private static MethodInfo[] GetRestoreHooks(Type runtimeType) - { - return S_RESTORE_HOOKS.GetValue( - runtimeType, - static value => new RestoreHooksBox(BuildRestoreHooks(value))).hooks; - } + => RESTORE_HOOKS.GetValue(runtimeType, static value => new RestoreHooksBox(BuildRestoreHooks(value))).hooks; private static MethodInfo[] BuildRestoreHooks(Type runtimeType) { var hierarchy = new List(8); for (Type? current = runtimeType; current is not null && current != typeof(object); current = current.BaseType) + { hierarchy.Add(current); + } hierarchy.Reverse(); var hooks = new List(hierarchy.Count); @@ -163,20 +177,24 @@ private static MethodInfo[] BuildRestoreHooks(Type runtimeType) if (declaredHooks.Length > 1) { throw new InvalidOperationException( - $"Serializable type '{hierarchy[i].FullName}' declares more than one OnSerializableRestored method."); + $"Serializable type '{hierarchy[i].FullName}' declares more than one OnSerializableRestored method." + ); } if (declaredHooks.Length == 0) + { continue; + } MethodInfo hook = declaredHooks[0]; ParameterInfo[] parameters = hook.GetParameters(); - bool validParameters = parameters.Length == 0 || - parameters.Length == 1 && parameters[0].ParameterType == typeof(SerializationContext); + bool validParameters = parameters.Length == 0 + || parameters.Length == 1 && parameters[0].ParameterType == typeof(SerializationContext); if (hook.IsStatic || hook.IsVirtual || hook.ReturnType != typeof(void) || !validParameters) { throw new InvalidOperationException( - $"Restore callback '{hierarchy[i].FullName}.{hook.Name}' must be a non-static, non-virtual void method " + - "with either no parameters or one SerializationContext parameter."); + $"Restore callback '{hierarchy[i].FullName}.{hook.Name}' must be a non-static, non-virtual void method " + + "with either no parameters or one SerializationContext parameter." + ); } hooks.Add(hook); @@ -192,5 +210,6 @@ private static bool RequiresWrite(PropertyVisibility visibility) => (visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0; private sealed record MembersBox(SerializationMemberMetadata[] members); + private sealed record RestoreHooksBox(MethodInfo[] hooks); } diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs index ebcb8b18e..ac4fee674 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs @@ -3,44 +3,47 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; internal static class ReflectionStructMetadata { - private const BindingFlags C_MEMBERS = - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private const BindingFlags C_MEMBERS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - private static readonly ConditionalWeakTable S_CACHE = new(); + private static readonly ConditionalWeakTable CACHE = new(); internal static SerializationMemberMetadata[] GetMembers(Type structType) - { - return S_CACHE.GetValue(structType, static type => new MembersBox(BuildMembers(type))).members; - } + => CACHE.GetValue(structType, static type => new MembersBox(BuildMembers(type))).members; internal static bool HasPureFieldAccess( Type type, SerializationTypeMetadata metadata ) { if (!type.IsValueType || metadata.requiresConverter || metadata.collection is not null || metadata.members.Count == 0) + { return false; + } foreach (SerializationMemberMetadata member in metadata.members) { if ((member.visibility & PropertyVisibility.Serialize) == 0) continue; FieldInfo? field = type.GetField(member.name, C_MEMBERS); - if (field is null || field.FieldType != member.type || - !(field.FieldType.IsPrimitive && field.FieldType != typeof(IntPtr) && field.FieldType != typeof(UIntPtr) && field.FieldType != typeof(char) - || field.FieldType == typeof(decimal) || field.FieldType == typeof(System.Guid) || field.FieldType == typeof(string))) + if (field is null || field.FieldType != member.type + || !(field.FieldType.IsPrimitive + && field.FieldType != typeof(nint) + && field.FieldType != typeof(nuint) + && field.FieldType != typeof(char) + || field.FieldType == typeof(decimal) || field.FieldType == typeof(Guid) || field.FieldType == typeof(string)) + ) { return false; + } } return true; } private static SerializationMemberMetadata[] BuildMembers(Type structType) { - var members = new List(); + List members = []; var names = new HashSet(StringComparer.Ordinal); MemberInfo[] candidates = structType .GetMembers(C_MEMBERS) @@ -56,11 +59,14 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) _ => null }; if (member is null) + { continue; + } if (!names.Add(member.name)) { throw new InvalidOperationException( - $"Struct '{structType.FullName}' declares duplicate serialized key '{member.name}'."); + $"Struct '{structType.FullName}' declares duplicate serialized key '{member.name}'." + ); } members.Add(member); } @@ -68,37 +74,40 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) if (members.Count == 0) { throw new InvalidOperationException( - $"Struct '{structType.FullName}' has no public writable data members. Register a SerializationConverter<{structType.Name}>."); + $"Struct '{structType.FullName}' has no public writable data members. Register a SerializationConverter<{structType.Name}>." + ); } return [.. members]; } private static int GetSerializableOrder(MemberInfo member) - { - return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; - } + => member.GetCustomAttribute(inherit: true)?.order + ?? int.MaxValue; private static SerializationMemberMetadata? TryCreateField( Type structType, FieldInfo field ) { if (field.IsStatic) + { return null; + } - SerializablePropertyAttribute? attribute = - field.GetCustomAttribute(inherit: true); + SerializablePropertyAttribute? attribute = field.GetCustomAttribute(inherit: true); bool isDefaultMember = field.IsPublic && !field.IsInitOnly; if (attribute is null && !isDefaultMember) + { return null; + } PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; bool requiresWrite = (visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0; if (requiresWrite && field.IsInitOnly) { throw new InvalidOperationException( - $"Struct field '{structType.FullName}.{field.Name}' must be writable for visibility '{visibility}'."); + $"Struct field '{structType.FullName}.{field.Name}' must be writable for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -106,7 +115,8 @@ FieldInfo field field.FieldType, visibility, field.GetValue, - field.IsInitOnly ? null : field.SetValue); + field.IsInitOnly ? null : field.SetValue + ); } private static SerializationMemberMetadata? TryCreateProperty( @@ -114,15 +124,18 @@ FieldInfo field PropertyInfo property ) { if (property.GetIndexParameters().Length != 0) + { return null; + } - SerializablePropertyAttribute? attribute = - property.GetCustomAttribute(inherit: true); + SerializablePropertyAttribute? attribute = property.GetCustomAttribute(inherit: true); MethodInfo? getter = property.GetGetMethod(nonPublic: true); MethodInfo? setter = property.GetSetMethod(nonPublic: true); bool isDefaultMember = getter?.IsPublic == true && setter?.IsPublic == true; if (attribute is null && !isDefaultMember) + { return null; + } PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; bool requiresRead = (visibility & (PropertyVisibility.Serialize | PropertyVisibility.RuntimeGet)) != 0; @@ -130,12 +143,14 @@ PropertyInfo property if (requiresRead && getter is null) { throw new InvalidOperationException( - $"Struct property '{structType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'."); + $"Struct property '{structType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'." + ); } if (requiresWrite && setter is null) { throw new InvalidOperationException( - $"Struct property '{structType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'."); + $"Struct property '{structType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -143,7 +158,8 @@ PropertyInfo property property.PropertyType, visibility, getter is null ? null : property.GetValue, - setter is null ? null : property.SetValue); + setter is null ? null : property.SetValue + ); } private sealed record MembersBox(SerializationMemberMetadata[] members); diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs index b9223c45c..647f69345 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs @@ -14,7 +14,7 @@ public sealed class ReflectionSerializationMetadataSource : ISerializationMetada { private readonly ConditionalWeakTable m_metadata = new(); - /// + /// public SerializationTypeMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); @@ -26,55 +26,84 @@ private static SerializationTypeMetadata BuildMetadata(Type type) SerializationCollectionMetadata? collection = null; if (ReflectionCollectionMetadata.TryGetMapTypes(type, out Type keyType, out Type valueType)) { - collection = new SerializationCollectionMetadata(valueType, keyType, null, + collection = new SerializationCollectionMetadata( + valueType, + keyType, + null, entries => ReflectionCollectionMetadata.BuildMap(type, keyType, valueType, entries), - value => ReflectionCollectionMetadata.TryEnumerateMap(value, type, out List> entries) - ? entries : throw new InvalidOperationException($"Map '{type}' cannot be enumerated.")); + value => ( + ReflectionCollectionMetadata.TryEnumerateMap(value, type, out List> entries) + ? entries + : throw new InvalidOperationException($"Map '{type}' cannot be enumerated.") + ) + ); } else if (ReflectionCollectionMetadata.TryGetSequenceElementType(type, out Type elementType)) { - collection = new SerializationCollectionMetadata(elementType, null, - values => ReflectionCollectionMetadata.BuildSequence(type, elementType, values), null, null); + collection = new SerializationCollectionMetadata( + elementType, + null, + values => ReflectionCollectionMetadata.BuildSequence(type, elementType, values), + null, + null + ); } IReadOnlyList members = typeof(ISerializable).IsAssignableFrom(type) - ? ReflectionObjectMetadata.GetSerializableMembers(type) - : type.IsValueType && !type.IsPrimitive && !type.IsEnum && type != typeof(Guid) - && type != typeof(decimal) ? ReflectionStructMetadata.GetMembers(type) : []; + ? ReflectionObjectMetadata.GetSerializableMembers(type) + : type.IsValueType && !type.IsPrimitive && !type.IsEnum && type != typeof(Guid) + && type != typeof(decimal) ? ReflectionStructMetadata.GetMembers(type) : []; Func? factory = !type.IsAbstract && !type.IsInterface && !type.ContainsGenericParameters - && (type.IsValueType || type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, Type.EmptyTypes, modifiers: null) is not null) ? () => CreateInstance(type) : null; - var metadata = new SerializationTypeMetadata(type, members, factory, + && (type.IsValueType || type.GetConstructor( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is not null) ? () => CreateInstance(type) : null; + var metadata = new SerializationTypeMetadata( + type, + members, + factory, typeof(ISerializable).IsAssignableFrom(type) ? ReflectionObjectMetadata.CreateRestoreHandler(type) : null, - collection, type.IsDefined(typeof(RequiresSerializationConverterAttribute), inherit: true)); + collection, + type.IsDefined(typeof(RequiresSerializationConverterAttribute), inherit: true) + ); if (ReflectionStructMetadata.HasPureFieldAccess(type, metadata)) + { metadata = metadata.WithPureFieldAccess(); + } SerializationRevisionAttribute? revision = type.GetCustomAttribute(inherit: false); if (revision is null) + { return metadata; + } foreach (SerializationMemberMetadata member in metadata.members) - if (string.Equals(member.name, revision.memberName, StringComparison.Ordinal) && - (member.visibility & PropertyVisibility.Serialize) != 0) - { + { + if (string.Equals(member.name, revision.memberName, StringComparison.Ordinal) + && (member.visibility & PropertyVisibility.Serialize) != 0 + ) { throw new InvalidOperationException( - $"Capture revision '{type.FullName}.{revision.memberName}' must not be serialized."); + $"Capture revision '{type.FullName}.{revision.memberName}' must not be serialized." + ); } - const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - FieldInfo? field = type.GetField(revision.memberName, flags); + } + const BindingFlags C_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + FieldInfo? field = type.GetField(revision.memberName, C_FLAGS); if (field is not null && !field.IsStatic && (field.FieldType == typeof(ulong) || field.FieldType == typeof(ulong?))) { Func readField = field.GetValue; return metadata.WithCaptureRevision(value => ReadCaptureRevision(value, readField)); } - PropertyInfo? property = type.GetProperty(revision.memberName, flags); - if (property is not null && property.GetIndexParameters().Length == 0 && - property.GetGetMethod(true) is { IsStatic: false } - && (property.PropertyType == typeof(ulong) || property.PropertyType == typeof(ulong?))) - { + PropertyInfo? property = type.GetProperty(revision.memberName, C_FLAGS); + if (property is not null && property.GetIndexParameters().Length == 0 + && property.GetGetMethod(true) is { IsStatic: false } + && (property.PropertyType == typeof(ulong) || property.PropertyType == typeof(ulong?)) + ) { Func readProperty = property.GetValue; return metadata.WithCaptureRevision(value => ReadCaptureRevision(value, readProperty)); } throw new InvalidOperationException( - $"Capture revision '{type.FullName}.{revision.memberName}' must be a readable ulong or nullable ulong instance member."); + $"Capture revision '{type.FullName}.{revision.memberName}' must be a readable ulong or nullable ulong instance member." + ); } private static object CreateInstance(Type type) @@ -82,7 +111,7 @@ private static object CreateInstance(Type type) try { return Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException($"Serialization type '{type}' did not produce an instance."); + ?? throw new InvalidOperationException($"Serialization type '{type}' did not produce an instance."); } catch (TargetInvocationException exception) when (exception.InnerException is not null) { diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs index e42302c76..2cc3f606f 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Security.Cryptography; +using System.Threading; using Inno.Content; using Inno.Core.IO; @@ -53,11 +54,17 @@ private Stream OpenPinned(ContentEntry entry) FileStream? input = null; try { - input = new FileStream(ContentCacheValidator.Resolve(m_root, entry.key), - FileMode.Open, FileAccess.Read, FileShare.Read); + input = new FileStream( + ContentCacheValidator.Resolve(m_root, entry.key), + FileMode.Open, + FileAccess.Read, + FileShare.Read + ); if (input.Length != entry.length - || !StringComparer.Ordinal.Equals(Convert.ToHexString(SHA256.HashData(input)), entry.contentHash)) + || !StringComparer.Ordinal.Equals(Convert.ToHexString(SHA256.HashData(input)), entry.contentHash) + ) { throw new InvalidDataException($"Cached content '{entry.key}' changed after preparation."); + } input.Position = 0; return new GenerationReadStream(input, ReleasePin); } @@ -88,53 +95,63 @@ Action release m_release = release; } - /// + /// public override bool CanRead => m_release is not null; - /// + + /// public override bool CanSeek => m_release is not null; - /// + + /// public override bool CanWrite => false; - /// + + /// public override long Length => m_input.Length; - /// + + /// public override long Position { get => m_input.Position; set => m_input.Position = value; } - /// + /// + public override int Read(Span buffer) => m_input.Read(buffer); + + /// public override int Read( byte[] buffer, int offset, int count ) => m_input.Read(buffer, offset, count); - /// - public override int Read(Span buffer) => m_input.Read(buffer); - /// + + /// public override int ReadByte() => m_input.ReadByte(); - /// + + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); - /// + + /// public override void Flush() => throw new NotSupportedException(); - /// + + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) { - Action? release = System.Threading.Interlocked.Exchange(ref m_release, null); + Action? release = Interlocked.Exchange(ref m_release, null); if (release is not null) { try diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs index 68fcd5760..b6fbf48f3 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.IO; using System.Text; using System.Threading; @@ -28,36 +29,53 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(output)!); using ContentReadLease lease = source.Acquire(entry.key); using Stream input = lease.OpenRead(); - await using FileStream destination = new(output, FileMode.CreateNew, FileAccess.Write, - FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + await using var destination = new FileStream( + output, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + ); long remaining = entry.length; - byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(128 * 1024); + byte[] buffer = ArrayPool.Shared.Rent(128 * 1024); try { while (remaining > 0) { - int read = await input.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, remaining)), - cancellationToken).ConfigureAwait(false); + int read = await input.ReadAsync( + buffer.AsMemory(0, (int)Math.Min(buffer.Length, remaining)), + cancellationToken + ).ConfigureAwait(false); if (read == 0) + { throw new InvalidDataException($"Content '{entry.key}' ended before its indexed length."); + } await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); remaining -= read; } if (input.ReadByte() != -1) + { throw new InvalidDataException($"Content '{entry.key}' exceeded its indexed length."); + } await destination.FlushAsync(cancellationToken).ConfigureAwait(false); destination.Flush(flushToDisk: true); } finally { - System.Buffers.ArrayPool.Shared.Return(buffer); + ArrayPool.Shared.Return(buffer); } } if (!ContentCacheValidator.Validate(candidate, source.index, cancellationToken)) - throw new InvalidDataException("The prepared content generation failed complete validation."); - using (await FileLease.AcquireAsync(Path.Combine(cache, "leases", generation + ".lock"), - TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) { + throw new InvalidDataException("The prepared content generation failed complete validation."); + } + using (await FileLease.AcquireAsync( + Path.Combine(cache, "leases", generation + ".lock"), + TimeSpan.Zero, + cancellationToken + ).ConfigureAwait(false) + ) { AtomicDirectory.Publish(candidate, target, cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); @@ -67,7 +85,9 @@ CancellationToken cancellationToken finally { if (Directory.Exists(candidate)) + { Directory.Delete(candidate, recursive: true); + } } } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs index 547760526..abc37053b 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs @@ -18,19 +18,26 @@ string current { string name = Path.GetFileName(directory); if (name == current) + { continue; + } try { if (!Guid.TryParseExact(name, "N", out _)) + { throw new IOException("An unrecognized directory cannot be retired as a cache generation."); + } PathBoundary.RequireUnlinkedPath(cache, directory); string lockPath = PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", name + ".lock")); if (!File.Exists(lockPath)) + { throw new IOException("The generation lease is missing; existing reader ownership cannot be proven."); - using FileLease lease = await FileLease.AcquireAsync(lockPath, - TimeSpan.Zero).ConfigureAwait(false); + } + using FileLease lease = await FileLease.AcquireAsync(lockPath, TimeSpan.Zero).ConfigureAwait(false); foreach (string file in PathBoundary.EnumerateFiles(directory)) + { _ = file; + } Directory.Delete(directory, recursive: true); } catch (TimeoutException) diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs index f95462ea8..0ebf1ce6e 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs @@ -17,17 +17,21 @@ internal static bool Validate( CancellationToken cancellationToken ) { if (!Directory.Exists(root) || (File.GetAttributes(root) & FileAttributes.ReparsePoint) != 0) + { return false; - HashSet files = new(StringComparer.Ordinal); - HashSet directories = new(StringComparer.Ordinal); + } + var files = new HashSet(StringComparer.Ordinal); + var directories = new HashSet(StringComparer.Ordinal); foreach (ContentEntry entry in index.entries) { string key = entry.key.value!; files.Add(key); for (int separator = key.IndexOf('/'); separator >= 0; separator = key.IndexOf('/', separator + 1)) + { directories.Add(key[..separator]); + } } - Stack pending = new(); + var pending = new Stack(); pending.Push(root); while (pending.TryPop(out string? directory)) { @@ -36,32 +40,44 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReparsePoint) != 0) + { return false; + } string key = Path.GetRelativePath(root, path).Replace('\\', '/'); if ((attributes & FileAttributes.Directory) != 0) { if (!directories.Remove(key)) + { return false; + } pending.Push(path); continue; } if (!files.Remove(key)) + { return false; + } } } if (files.Count != 0 || directories.Count != 0) + { return false; + } foreach (ContentEntry entry in index.entries) { cancellationToken.ThrowIfCancellationRequested(); try { - using FileStream input = new(Resolve(root, entry.key), FileMode.Open, FileAccess.Read, FileShare.Read); + using var input = new FileStream(Resolve(root, entry.key), FileMode.Open, FileAccess.Read, FileShare.Read); if (input.Length != entry.length) + { return false; + } string hash = ComputeHash(input, cancellationToken); if (!string.Equals(hash, entry.contentHash, StringComparison.Ordinal)) + { return false; + } } catch (FileNotFoundException) { diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs index 417f15a99..b5293dcf2 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs @@ -26,11 +26,15 @@ public FileContentCacheOptions( ) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationCacheRoot); if (!Path.IsPathFullyQualified(applicationCacheRoot)) + { throw new ArgumentException("Content caches require an absolute host-selected root.", nameof(applicationCacheRoot)); + } this.applicationCacheRoot = Path.GetFullPath(applicationCacheRoot); this.lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); if (this.lockTimeout < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(lockTimeout)); + } } /// diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs index 63688d57e..7e0b5bbec 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs @@ -75,25 +75,44 @@ public async ValueTask PrepareAsync( ArgumentNullException.ThrowIfNull(pack); ArgumentNullException.ThrowIfNull(serialization); if (!scope.isValid) + { throw new ArgumentException("Content preparation requires an application namespace.", nameof(scope)); + } cancellationToken.ThrowIfCancellationRequested(); - var stream = new FileStream(Path.Combine(m_contentDirectory, pack.fileName), - FileMode.Open, FileAccess.Read, FileShare.Read); + var stream = new FileStream( + Path.Combine(m_contentDirectory, pack.fileName), + FileMode.Open, + FileAccess.Read, + FileShare.Read + ); PackContentStore? source = null; try { - source = await Task.Run(() => ContentPackReader.Open(stream, pack, serialization, - m_limits, cancellationToken), CancellationToken.None).ConfigureAwait(false); - return await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(Path.Combine(m_cacheRoot, scope.value!)), cancellationToken) + source = await Task.Run(() => ContentPackReader.Open( + stream, + pack, + serialization, + m_limits, + cancellationToken + ), CancellationToken.None).ConfigureAwait(false); + return await FileContentPreparation + .PrepareAsync( + source, + new FileContentCacheOptions(Path.Combine(m_cacheRoot, scope.value!)), + cancellationToken + ) .ConfigureAwait(false); } finally { if (source is not null) + { source.Dispose(); + } else + { stream.Dispose(); + } } } @@ -121,15 +140,27 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(fileName); if (fileName is "." or ".." || fileName.IndexOfAny(['/', '\\', ':']) >= 0) + { throw new ArgumentException("A deployment document requires a single portable filename.", nameof(fileName)); - using var stream = new FileStream(Path.Combine(m_contentDirectory, fileName), - FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous); + } + using var stream = new FileStream( + Path.Combine(m_contentDirectory, fileName), + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 4096, + FileOptions.Asynchronous + ); if (stream.Length is <= 0 or > C_METADATA_LIMIT) + { throw new InvalidDataException($"Deployment metadata '{fileName}' exceeds its document budget."); - byte[] bytes = new byte[checked((int)stream.Length)]; + } + var bytes = new byte[checked((int)stream.Length)]; await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false); if (stream.ReadByte() != -1) + { throw new InvalidDataException($"Deployment metadata '{fileName}' changed during acquisition."); + } return bytes; } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs index d404531a1..a785bac70 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -47,26 +48,43 @@ public static async ValueTask PrepareAsync( string cache = Path.Combine(options.applicationCacheRoot, "Content", source.descriptor.contentHash); PathBoundary.RequireUnlinkedPath(options.applicationCacheRoot, cache); PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "install.lock")); - using FileLease writer = await FileLease.AcquireAsync(Path.Combine(cache, "install.lock"), - options.lockTimeout, cancellationToken).ConfigureAwait(false); + using FileLease writer = await FileLease.AcquireAsync( + Path.Combine(cache, "install.lock"), + options.lockTimeout, + cancellationToken + ).ConfigureAwait(false); foreach (string entry in new[] { "generations", "staging", "leases", "current" }) + { PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, entry)); + } Directory.CreateDirectory(Path.Combine(cache, "generations")); string? current = ReadCurrent(cache); bool valid = current is not null - && File.Exists(PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", current + ".lock"))) - && await Task.Run(() => ContentCacheValidator.Validate( - Path.Combine(cache, "generations", current), source.index, cancellationToken), cancellationToken).ConfigureAwait(false); + && File.Exists(PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", current + ".lock"))) + && await Task.Run(() => ContentCacheValidator.Validate( + Path.Combine(cache, "generations", current), + source.index, + cancellationToken + ), cancellationToken).ConfigureAwait(false); if (!valid) + { current = await ContentCachePublication.PublishAsync(cache, source, cancellationToken).ConfigureAwait(false); - FileLease reader = await FileLease.AcquireSharedAsync(Path.Combine(cache, "leases", current + ".lock"), - options.lockTimeout, cancellationToken).ConfigureAwait(false); + } + FileLease reader = await FileLease.AcquireSharedAsync( + Path.Combine(cache, "leases", current + ".lock"), + options.lockTimeout, + cancellationToken + ).ConfigureAwait(false); try { - var diagnostics = await ContentCacheRetirement.RetireAsync(cache, current!).ConfigureAwait(false); + IReadOnlyList diagnostics = await ContentCacheRetirement.RetireAsync(cache, current!).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - return new FileContentStore(source.descriptor, source.index, - new ContentCacheGeneration(Path.Combine(cache, "generations", current!), reader), diagnostics); + return new FileContentStore( + source.descriptor, + source.index, + new ContentCacheGeneration(Path.Combine(cache, "generations", current!), reader), + diagnostics + ); } catch { @@ -81,7 +99,9 @@ public static async ValueTask PrepareAsync( try { if (new FileInfo(pointer).Length != 32) + { return null; + } string value = File.ReadAllText(pointer); return Guid.TryParseExact(value, "N", out _) ? value : null; } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs index 670c43e51..672713e18 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs @@ -25,10 +25,10 @@ IReadOnlyList retirementDiagnostics this.retirementDiagnostics = retirementDiagnostics; } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } /// @@ -36,14 +36,16 @@ IReadOnlyList retirementDiagnostics /// public IReadOnlyList retirementDiagnostics { get; } - /// + /// public ContentReadLease Acquire(ContentKey key) { lock (m_sync) { ContentCacheGeneration generation = m_generation ?? throw new ObjectDisposedException(nameof(FileContentStore)); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException($"Content '{key}' does not exist in pack '{descriptor.contentHash}'."); + } return generation.Acquire(entry!); } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs index ed51ff744..e790be8fd 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs @@ -4,9 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - -using Inno.Storage; using Inno.Core.IO; +using Inno.Storage; namespace Inno.Adapter.Storage.FileSystem; @@ -97,8 +96,8 @@ public async ValueTask ExistsAsync( ThrowIfDisposed(); ValidateExistingPath(path, includeLeaf: true); return File.Exists(path) - ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) - : null; + ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) + : null; } finally { @@ -132,15 +131,13 @@ public async ValueTask WriteAsync( { ThrowIfDisposed(); string directory = Path.GetDirectoryName(path) - ?? throw new IOException("A storage key did not resolve to a parent directory."); + ?? throw new IOException("A storage key did not resolve to a parent directory."); ValidateExistingPath(directory, includeLeaf: true); Directory.CreateDirectory(directory); ValidateExistingPath(directory, includeLeaf: true); ValidateExistingPath(path, includeLeaf: true); - string temporaryPath = Path.Combine( - directory, - $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + string temporaryPath = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); try { await using (var stream = new FileStream( @@ -149,8 +146,8 @@ public async ValueTask WriteAsync( FileAccess.Write, FileShare.None, 4096, - FileOptions.Asynchronous | FileOptions.WriteThrough)) - { + FileOptions.Asynchronous | FileOptions.WriteThrough + )) { await stream.WriteAsync(value, cancellationToken).ConfigureAwait(false); stream.Flush(flushToDisk: true); } @@ -160,7 +157,9 @@ public async ValueTask WriteAsync( finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } finally @@ -192,7 +191,9 @@ public async ValueTask DeleteAsync( ThrowIfDisposed(); ValidateExistingPath(path, includeLeaf: true); if (!File.Exists(path)) + { return false; + } File.Delete(path); return true; } @@ -222,15 +223,16 @@ public async ValueTask> ListAsync( try { ThrowIfDisposed(); - var values = new List(); + List values = []; EnumerateDirectory(new DirectoryInfo(m_root), values, cancellationToken); IEnumerable filtered = values; if (prefix is { } requestedPrefix) { string prefixValue = requestedPrefix.value; - filtered = filtered.Where(candidate => + filtered = filtered.Where(candidate => ( string.Equals(candidate.value, prefixValue, StringComparison.Ordinal) - || candidate.value.StartsWith(prefixValue + "/", StringComparison.Ordinal)); + || candidate.value.StartsWith(prefixValue + "/", StringComparison.Ordinal) + )); } return filtered .OrderBy(static key => key.value, StringComparer.Ordinal) @@ -276,7 +278,9 @@ CancellationToken cancellationToken continue; } if (entry is not FileInfo) + { continue; + } string relative = Path.GetRelativePath(m_root, entry.FullName) .Replace(Path.DirectorySeparatorChar, '/'); values.Add(new StorageKey(relative)); @@ -287,10 +291,10 @@ private string Resolve(StorageKey key) { ThrowIfDisposed(); if (!key.isValid) + { throw new ArgumentException("A valid storage key is required.", nameof(key)); - return PathBoundary.Resolve( - m_root, - key.value.Replace('/', Path.DirectorySeparatorChar)); + } + return PathBoundary.Resolve(m_root, key.value.Replace('/', Path.DirectorySeparatorChar)); } private void ValidateExistingPath( @@ -301,25 +305,34 @@ bool includeLeaf string current = m_root; string[] segments = relative.Split( [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], - StringSplitOptions.RemoveEmptyEntries); + StringSplitOptions.RemoveEmptyEntries + ); int length = includeLeaf ? segments.Length : Math.Max(0, segments.Length - 1); for (int index = 0; index < length; index++) { current = Path.Combine(current, segments[index]); if (Directory.Exists(current)) + { RejectLink(new DirectoryInfo(current)); + } else if (File.Exists(current)) + { RejectLink(new FileInfo(current)); + } else + { break; + } } } + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); + private static void RejectLink(FileSystemInfo entry) { if (entry.LinkTarget is not null || (entry.Attributes & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Storage sandbox path '{entry.FullName}' contains a symbolic link or reparse point."); + } } - - private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs index 2a86af323..4b1a3383d 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs @@ -20,20 +20,24 @@ public sealed class FileSystemStorageBackendProvider : StorageBackendProvider /// /// The root is absent or not fully qualified. /// - public FileSystemStorageBackendProvider(string rootDirectory) : base(StorageBackendId.fileSystem) + public FileSystemStorageBackendProvider(string rootDirectory) + : base(StorageBackendID.fileSystem) { ArgumentException.ThrowIfNullOrWhiteSpace(rootDirectory); if (!Path.IsPathFullyQualified(rootDirectory)) + { throw new ArgumentException("A filesystem storage provider requires an absolute host root.", nameof(rootDirectory)); + } m_rootDirectory = Path.GetFullPath(rootDirectory); } - /// + /// public override IApplicationStorage CreateStorage(StorageScope scope) { if (!scope.isValid) + { throw new ArgumentException("Storage requires an assigned application namespace.", nameof(scope)); + } return new FileSystemApplicationStorage(Path.Combine(m_rootDirectory, scope.value!, "Storage")); } } - diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs index 7069f3487..82b0cdc67 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs @@ -11,19 +11,25 @@ internal static string Prepare( string cimguiDirectory ) { string source = File.ReadAllText(Path.Combine(cimguiDirectory, "imgui", "imgui.cpp")); - source = ReplaceOnce(source, + source = ReplaceOnce( + source, "ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size);", - "// Keep one continuous backing surface under the title and body. Independently anti-aliased shared edges leak the window behind them.\n" + - " ImRect bg_rect(window->DockIsActive ? window->Pos + ImVec2(0, window->TitleBarHeight) : window->Pos, window->Pos + window->Size);"); - source = ReplaceOnce(source, + "// Keep one continuous backing surface under the title and body. Independently anti-aliased shared edges leak the window behind them.\n" + + " ImRect bg_rect(window->DockIsActive ? window->Pos + ImVec2(0, window->TitleBarHeight) : window->Pos, window->Pos + window->Size);" + ); + source = ReplaceOnce( + source, "bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom;", - "bg_rounding_flags = ImDrawFlags_RoundCornersAll;"); + "bg_rounding_flags = ImDrawFlags_RoundCornersAll;" + ); string directory = Path.Combine(context.GetNativeBuildRoot(ImGuiToolchain.componentDescriptor), "Source"); Directory.CreateDirectory(directory); string output = Path.Combine(directory, "imgui.cpp"); if (!File.Exists(output) || File.ReadAllText(output) != source) + { File.WriteAllText(output, source); + } return output; } @@ -34,7 +40,11 @@ string replacement ) { int index = source.IndexOf(expected, StringComparison.Ordinal); if (index < 0 || source.IndexOf(expected, index + expected.Length, StringComparison.Ordinal) >= 0) - throw new InvalidOperationException("The cimgui window-background source no longer matches its validated overlay. Review the upstream change before building."); - return string.Concat(source.AsSpan(0, index), replacement, source.AsSpan(index + expected.Length)); + { + throw new InvalidOperationException( + "The cimgui window-background source no longer matches its validated overlay. Review the upstream change before building." + ); + } + return $"{source.AsSpan(0, index)}{replacement}{source.AsSpan(index + expected.Length)}"; } } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs index 7598713b1..e6cf5b642 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs @@ -19,7 +19,8 @@ public static class ImGuiToolchain "cimgui", "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj", "backends/ImGui/build/Inno.Build.Toolchains.ImGui/Inno.Build.Toolchains.ImGui.csproj", - bindingDefinition: "backends/ImGui/native/Inno.Native.ImGui/Bindings/bindings.props"); + bindingDefinition: "backends/ImGui/native/Inno.Native.ImGui/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -48,18 +49,34 @@ public static async Task BuildAsync( string upstream = Path.Combine(context.engineRoot, "extern", "cimgui"); string[] arguments = ["-DINNO_CIMGUI_SOURCE_DIR=" + upstream, "-DBUILD_SHARED_LIBS=ON", "-DCIMGUI_VARGS0=ON"]; NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync(scoped, componentDescriptor, token).ConfigureAwait(false); + ) => + { + NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync( + scoped, + componentDescriptor, + token + ).ConfigureAwait(false); string windowSource = CimguiSourceOverlay.Prepare(scoped, sources.ResolvePath(upstream)); - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - componentDescriptor.GetToolchainRoot(scoped.engineRoot), "cimgui", - [.. arguments, "-DINNO_IMGUI_WINDOW_SOURCE=" + windowSource], token).ConfigureAwait(false); - string library = NativeCMakeExecutor.FindOutput(scoped, build, "*cimgui-" + scoped.configuration + selection.sharedLibraryExtension); + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + componentDescriptor.GetToolchainRoot(scoped.engineRoot), + "cimgui", + [.. arguments, "-DINNO_IMGUI_WINDOW_SOURCE=" + windowSource], + token + ).ConfigureAwait(false); + string library = NativeCMakeExecutor.FindOutput( + scoped, + build, + "*cimgui-" + scoped.configuration + selection.sharedLibraryExtension + ); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); if (selection.linkPlan.importLibraryExtension is string importExtension) @@ -69,14 +86,21 @@ public static async Task BuildAsync( Directory.CreateDirectory(link); File.Copy(import, Path.Combine(link, Path.GetFileName(import))); } - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -102,14 +126,25 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) + { throw new NotSupportedException("This presentation recipe supports shared linkage only."); + } string source = componentDescriptor.GetToolchainRoot(context.engineRoot); string upstream = Path.Combine(context.engineRoot, "extern", "cimgui"); string adapter = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, - "cimgui", selection.targetId, [upstream, Path.Combine(source, "CMakeLists.txt"), - Path.Combine(adapter, "ImGuiPlatformCallbacks.h"), Path.Combine(adapter, "ImGuiPlatformCallbacks.cpp")], + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "cimgui", + selection.targetID, + [ + upstream, + Path.Combine(source, "CMakeLists.txt"), + Path.Combine(adapter, "ImGuiPlatformCallbacks.h"), + Path.Combine(adapter, "ImGuiPlatformCallbacks.cpp") + ], ["-DINNO_CIMGUI_SOURCE_DIR=" + upstream, "-DBUILD_SHARED_LIBS=ON", "-DCIMGUI_VARGS0=ON", "window-source=continuous-background"], - [Path.Combine(source, "CimguiSourceOverlay.cs"), Path.Combine(source, "ImGuiToolchain.cs")]); + [Path.Combine(source, "CimguiSourceOverlay.cs"), Path.Combine(source, "ImGuiToolchain.cs")] + ); } } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs index f750af78e..94fce3694 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs @@ -5,29 +5,35 @@ internal static class CImguizmoBuildConstants /// /// The output product dir name value used as part of this type's public representation. /// - public const string OUTPUT_PRODUCT_DIR_NAME = "cimguizmo"; + public const string C_OUTPUT_PRODUCT_DIR_NAME = "cimguizmo"; + /// /// The output dll name value used as part of this type's public representation. /// - public const string OUTPUT_DLL_NAME = "libcimguizmo"; + public const string C_OUTPUT_DLL_NAME = "libcimguizmo"; + /// /// The cimgui dir name value used as part of this type's public representation. /// - public const string CIMGUI_DIR_NAME = "cimgui"; + public const string C_CIMGUI_DIR_NAME = "cimgui"; + /// /// The cimguizmo dir name value used as part of this type's public representation. /// - public const string CIMGUIZMO_DIR_NAME = "cimguizmo"; + public const string C_CIMGUIZMO_DIR_NAME = "cimguizmo"; + /// /// The cimguimo cpp file value used as part of this type's public representation. /// - public const string CIMGUIMO_CPP_FILE = "cimguizmo.cpp"; + public const string C_CIMGUIMO_CPP_FILE = "cimguizmo.cpp"; + /// /// The imguizmo cpp file value used as part of this type's public representation. /// - public const string IMGUIZMO_CPP_FILE = "ImGuizmo.cpp"; + public const string C_IMGUIZMO_CPP_FILE = "ImGuizmo.cpp"; + /// /// The imguizmo dir name value used as part of this type's public representation. /// - public const string IMGUIZMO_DIR_NAME = "ImGuizmo"; + public const string C_IMGUIZMO_DIR_NAME = "ImGuizmo"; } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs index c5dff87c8..0f2a02931 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs @@ -21,26 +21,28 @@ string cimguiDir if (!Directory.Exists(cimguizmoDir)) { throw new DirectoryNotFoundException( - $"cimguizmo source not found at {cimguizmoDir}. Place the cimguizmo repository in extern/cimguizmo before running this tool."); + $"cimguizmo source not found at {cimguizmoDir}. Place the cimguizmo repository in extern/cimguizmo before running this tool." + ); } if (!Directory.Exists(cimguiDir)) { throw new DirectoryNotFoundException( - $"cimgui source not found at {cimguiDir}. Place the cimgui repository in extern/cimgui before running this tool."); + $"cimgui source not found at {cimguiDir}. Place the cimgui repository in extern/cimgui before running this tool." + ); } - var cimguizmoCpp = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.CIMGUIMO_CPP_FILE); + string cimguizmoCpp = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.C_CIMGUIMO_CPP_FILE); if (!File.Exists(cimguizmoCpp)) { - throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.CIMGUIMO_CPP_FILE}: {cimguizmoCpp}"); + throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.C_CIMGUIMO_CPP_FILE}: {cimguizmoCpp}"); } - var imguizmoDir = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.IMGUIZMO_DIR_NAME); - var imguizmoCpp = Path.Combine(imguizmoDir, CImguizmoBuildConstants.IMGUIZMO_CPP_FILE); + string imguizmoDir = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.C_IMGUIZMO_DIR_NAME); + string imguizmoCpp = Path.Combine(imguizmoDir, CImguizmoBuildConstants.C_IMGUIZMO_CPP_FILE); if (!File.Exists(imguizmoCpp)) { - throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.IMGUIZMO_CPP_FILE}: {imguizmoCpp}"); + throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.C_IMGUIZMO_CPP_FILE}: {imguizmoCpp}"); } } } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs index ad2acb80a..c369b9dec 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.ImGuizmo; @@ -20,7 +19,8 @@ public static class ImGuizmoToolchain "cimguizmo", "backends/ImGui/native/Inno.Native.ImGuizmo/Inno.Native.ImGuizmo.csproj", "backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/Inno.Build.Toolchains.ImGuizmo.csproj", - bindingDefinition: "backends/ImGui/native/Inno.Native.ImGuizmo/Bindings/bindings.props"); + bindingDefinition: "backends/ImGui/native/Inno.Native.ImGuizmo/Bindings/bindings.props" + ); /// /// Builds and installs the component for the explicitly selected native target. @@ -31,18 +31,18 @@ public static class ImGuizmoToolchain /// /// The matching published ImGui product providing the native link dependency. /// - /// - /// The configuration is invalid. - /// - /// - /// A native build process fails. - /// /// /// Cancels child processes and prevents artifact installation after cancellation. /// /// /// The validated gizmo library linked against the explicitly supplied ImGui product. /// + /// + /// The configuration is invalid. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// @@ -55,13 +55,18 @@ public static async Task BuildAsync( ArgumentNullException.ThrowIfNull(imGui); NativeToolchainSelection selection = context.RequireToolchain(); NativeBuildRecipe sourceRecipe = CreateRecipe(context); - if (imGui.component != "cimgui" || imGui.targetId != selection.targetId) + if (imGui.component != "cimgui" || imGui.targetID != selection.targetID) + { throw new ArgumentException("The supplied ImGui product does not match this gizmo target.", nameof(imGui)); + } NativeArtifactRole role = imGui.artifacts.Any(static artifact => artifact.role == NativeArtifactRole.ImportLibrary) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary; + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary; string[] libraries = imGui.artifacts.Where(artifact => artifact.role == role).Select(static artifact => artifact.file).ToArray(); if (libraries.Length != 1) + { throw new InvalidOperationException("The ImGui product must provide exactly one link library."); + } string cimguiDir = Path.Combine(context.engineRoot, "extern", "cimgui"); NativeBuildRecipe recipe = BindImGui(context, sourceRecipe, imGui); return await NativeArtifactPublisher.PublishAsync( @@ -71,24 +76,38 @@ public static async Task BuildAsync( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - componentDescriptor.GetToolchainRoot(scoped.engineRoot), "cimguizmo", - ["-DINNO_CIMGUI_SOURCE_DIR=" + cimguiDir, - "-DINNO_CIMGUI_LIBRARY=" + libraries[0]], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + componentDescriptor.GetToolchainRoot(scoped.engineRoot), + "cimguizmo", + [ + "-DINNO_CIMGUI_SOURCE_DIR=" + cimguiDir, + "-DINNO_CIMGUI_LIBRARY=" + libraries[0] + ], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*cimguizmo" + selection.sharedLibraryExtension); string name = "libcimguizmo-" + scoped.configuration + selection.sharedLibraryExtension; File.Copy(library, Path.Combine(output, name)); token.ThrowIfCancellationRequested(); - - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -114,15 +133,26 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) + { throw new NotSupportedException("This presentation recipe supports shared linkage only."); + } string source = componentDescriptor.GetToolchainRoot(context.engineRoot); string upstream = Path.Combine(context.engineRoot, "extern", "cimguizmo"); string imGui = Path.Combine(context.engineRoot, "extern", "cimgui"); CImguizmoBuildUtils.ValidateSource(upstream, imGui); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, - "cimguizmo", selection.targetId, [upstream, imGui, Path.Combine(source, "CMakeLists.txt")], - ["dependency=cimgui"], [Path.Combine(source, "CImguizmoBuildConstants.cs"), - Path.Combine(source, "CImguizmoBuildUtils.cs"), Path.Combine(source, "ImGuizmoToolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "cimguizmo", + selection.targetID, + [upstream, imGui, Path.Combine(source, "CMakeLists.txt")], + ["dependency=cimgui"], + [ + Path.Combine(source, "CImguizmoBuildConstants.cs"), + Path.Combine(source, "CImguizmoBuildUtils.cs"), + Path.Combine(source, "ImGuizmoToolchain.cs") + ] + ); } /// @@ -155,13 +185,18 @@ NativeBuildProduct imGui ArgumentNullException.ThrowIfNull(sourceRecipe); ArgumentNullException.ThrowIfNull(imGui); NativeToolchainSelection selection = context.RequireToolchain(); - if (imGui.component != "cimgui" || imGui.targetId != selection.targetId) + if (imGui.component != "cimgui" || imGui.targetID != selection.targetID) + { throw new ArgumentException("The supplied ImGui product does not match this gizmo target.", nameof(imGui)); + } NativeArtifactRole role = imGui.artifacts.Any(static artifact => artifact.role == NativeArtifactRole.ImportLibrary) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary; + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary; string[] libraries = imGui.artifacts.Where(artifact => artifact.role == role).Select(static artifact => artifact.file).ToArray(); if (libraries.Length != 1) + { throw new InvalidOperationException("The ImGui product must provide exactly one link library."); + } return sourceRecipe.WithDependency(NativeBuildInput.FromPath(context.engineRoot, libraries[0]), imGui.fingerprint); } } diff --git a/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs b/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs index bd67e9dca..83475b5d2 100644 --- a/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs +++ b/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs @@ -8,9 +8,9 @@ namespace Inno.Native.ImGui; public static unsafe partial class ImGui { #if DEBUG - internal const string LibName = "libcimgui-debug"; + internal const string C_LIB_NAME = "libcimgui-debug"; #else - internal const string LibName = "libcimgui-release"; + internal const string C_LIB_NAME = "libcimgui-release"; #endif static ImGui() @@ -20,7 +20,7 @@ static ImGui() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs index 690080979..fa7e51acb 100644 --- a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs +++ b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs @@ -18,7 +18,7 @@ INativeModuleProvider dependency m_dependency = dependency; } - /// + /// public bool TryGetExport( string name, out nint address @@ -38,7 +38,9 @@ public void Dispose() lock (m_gate) { if (m_closing) + { return; + } m_closing = true; // A failed API unload is terminal; its dependency must remain retained for process lifetime. m_api.Dispose(); diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs index 9bee115a5..ffc385409 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs @@ -1,13 +1,14 @@ -using System.Threading.Tasks; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Linq; using System.Numerics; -using Inno.Native.ImGui; +using System.Threading.Tasks; using Inno.Adapter.Presentation.ImGui; using Inno.Adapter.Rendering.Bgfx; +using Inno.Native.ImGui; using Inno.Rendering; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -22,22 +23,26 @@ public sealed unsafe class BgfxImGuiRenderer : IPlatformImGuiRenderer, IRenderFr private const int C_INITIAL_VERTEX_CAPACITY = 4096; private const int C_INITIAL_INDEX_CAPACITY = 8192; - private static readonly RenderBindingId S_TEXTURE_BINDING = new("s_tex"); - private static readonly RenderBindingId S_OUTPUT_ENCODING = new("outputEncoding"); - private static readonly byte[] S_LINEAR_OUTPUT = new byte[16]; - private static readonly byte[] S_ENCODED_OUTPUT = CreateOutputEncoding(); - private static readonly RenderPhaseId S_USER_INTERFACE_PHASE = new("inno.imgui.compose"); - private static readonly RenderClearColor S_PRESENTATION_CLEAR_COLOR = new( + private static readonly RenderBindingID TEXTURE_BINDING = new("s_tex"); + private static readonly RenderBindingID OUTPUT_ENCODING = new("outputEncoding"); + private static readonly byte[] LINEAR_OUTPUT = new byte[16]; + private static readonly byte[] ENCODED_OUTPUT = CreateOutputEncoding(); + private static readonly RenderPhaseID USER_INTERFACE_PHASE = new("inno.imgui.compose"); + + private static readonly RenderClearColor PRESENTATION_CLEAR_COLOR = new( SrgbToLinear(0.08f), SrgbToLinear(0.08f), SrgbToLinear(0.09f), - 1f); - private static readonly RenderVertexLayout S_VERTEX_LAYOUT = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + 1f + ); + + private static readonly RenderVertexLayout VERTEX_LAYOUT = new( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); private readonly object m_sync = new(); private readonly IRenderDevice m_device; @@ -85,14 +90,14 @@ GraphicsPipelineDescriptor pipelineDescriptor ValidatePipelineDescriptor(pipelineDescriptor); m_device = device; m_bgfxDevice = device as BgfxDevice - ?? throw new NotSupportedException("The BGFX ImGui renderer requires an Inno.Adapter.Rendering.Bgfx device."); + ?? throw new NotSupportedException("The BGFX ImGui renderer requires an Inno.Adapter.Rendering.Bgfx device."); m_pendingPipelineDescriptor = pipelineDescriptor; } /// /// Gets the exact interleaved vertex layout required by the built-in ImGui shaders. /// - public static RenderVertexLayout vertexLayout => S_VERTEX_LAYOUT; + public static RenderVertexLayout vertexLayout => VERTEX_LAYOUT; /// /// Gets the last recoverable shader replacement error while the last-good pipeline remains active. @@ -104,7 +109,7 @@ GraphicsPipelineDescriptor pipelineDescriptor /// public bool supportsViewports => m_bgfxDevice.supportsAdditionalSurfaces; - /// + /// public bool supportsVertexOffsets => true; /// @@ -177,7 +182,7 @@ public bool UnregisterTexture(ImGuiTextureHandle texture) /// /// The draw data consumed by render main; ownership remains with the caller unless explicitly stated otherwise. /// - public void RenderMain(IntPtr drawData) + public void RenderMain(nint drawData) { lock (m_sync) { @@ -209,8 +214,10 @@ int pixelHeight lock (m_sync) { if (m_mainPacket is not null - && (m_mainPacket.pixelWidth != pixelWidth || m_mainPacket.pixelHeight != pixelHeight)) + && (m_mainPacket.pixelWidth != pixelWidth || m_mainPacket.pixelHeight != pixelHeight) + ) { m_mainPacket = null; + } } } @@ -226,9 +233,9 @@ public void CreateViewport(PlatformImGuiViewportTarget target) lock (m_sync) { ObjectDisposedException.ThrowIf(m_disposeRequested, this); - if (!m_viewports.TryAdd(target.viewportId, new ViewportState(target))) + if (!m_viewports.TryAdd(target.viewportID, new ViewportState(target))) { - throw new ArgumentException($"Viewport {target.viewportId} is already registered.", nameof(target)); + throw new ArgumentException($"Viewport {target.viewportID} is already registered.", nameof(target)); } } } @@ -244,7 +251,7 @@ public void ResizeViewport(PlatformImGuiViewportTarget target) ArgumentNullException.ThrowIfNull(target); lock (m_sync) { - if (m_viewports.TryGetValue(target.viewportId, out ViewportState? state)) + if (m_viewports.TryGetValue(target.viewportID, out ViewportState? state)) { state.target = target; state.resizePending = true; @@ -263,18 +270,18 @@ public void ResizeViewport(PlatformImGuiViewportTarget target) /// public void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData + nint drawData ) { ArgumentNullException.ThrowIfNull(target); lock (m_sync) { - if (m_disposeRequested || !m_viewports.TryGetValue(target.viewportId, out ViewportState? state)) + if (m_disposeRequested || !m_viewports.TryGetValue(target.viewportID, out ViewportState? state)) { return; } state.target = target; - state.packet = CaptureDrawData(drawData, target.viewportId, state.surface); + state.packet = CaptureDrawData(drawData, target.viewportID, state.surface); } } @@ -284,10 +291,7 @@ IntPtr drawData /// /// The existing target that receives the validated result. /// - public void PresentViewport(PlatformImGuiViewportTarget target) - { - ArgumentNullException.ThrowIfNull(target); - } + public void PresentViewport(PlatformImGuiViewportTarget target) => ArgumentNullException.ThrowIfNull(target); /// /// Destroys the auxiliary viewport and releases its rendering resources. @@ -298,24 +302,25 @@ public void PresentViewport(PlatformImGuiViewportTarget target) /// /// Completion of render-thread window release, or an already completed task for an unallocated viewport. /// - public Task RetireViewport(PlatformImGuiViewportTarget target) + public Task RetireViewportAsync(PlatformImGuiViewportTarget target) { ArgumentNullException.ThrowIfNull(target); lock (m_sync) { - if (m_viewports.TryGetValue(target.viewportId, out ViewportState? state)) + if (m_viewports.TryGetValue(target.viewportID, out ViewportState? state)) { Task retirement = state.surface.isValid - ? m_bgfxDevice.RetireWindowSurface(state.surface) : Task.CompletedTask; - m_viewports.Remove(target.viewportId); - m_framePackets = m_framePackets.Where(packet => packet.viewportId != target.viewportId).ToArray(); + ? m_bgfxDevice.RetireWindowSurfaceAsync(state.surface) + : Task.CompletedTask; + m_viewports.Remove(target.viewportID); + m_framePackets = m_framePackets.Where(packet => packet.viewportID != target.viewportID).ToArray(); return retirement; } } return Task.CompletedTask; } - /// + /// public void DrainViewportRetirements() => m_bgfxDevice.DrainWindowSurfaceRetirements(); /// @@ -353,7 +358,9 @@ public void PrepareFrame(ulong frameIndex) } } if (needsOutputTransfer) + { PreparePresentationQuad(); + } PrepareTextures(); PrepareDrawPackets(); } @@ -383,39 +390,65 @@ ulong frameIndex foreach (PreparedPacket packet in m_framePackets) { - if (packet.viewportId == 0 && !m_device.primaryPresentationSize.HasValue) + if (packet.viewportID == 0 && !m_device.primaryPresentationSize.HasValue) + { continue; - string name = packet.viewportId == 0 ? "ImGui/Main" : $"ImGui/Viewport/{packet.viewportId}"; + } + string name = packet.viewportID == 0 ? "ImGui/Main" : $"ImGui/Viewport/{packet.viewportID}"; bool needsOutputTransfer = packet.surface.isValid - ? !m_bgfxDevice.WindowSurfaceIsSrgb(packet.surface) - : !m_bgfxDevice.backbufferIsSrgb; - RasterPassBuilder pass = graph.AddRasterPass(name, S_USER_INTERFACE_PHASE, packet, ExecutePacket); + ? !m_bgfxDevice.WindowSurfaceIsSrgb(packet.surface) + : !m_bgfxDevice.backbufferIsSrgb; + RasterPassBuilder pass = graph.AddRasterPass(name, USER_INTERFACE_PHASE, packet, ExecutePacket); pass.SetViewTransform(Identity(), Orthographic(packet.displayPosition, packet.displaySize)); if (needsOutputTransfer) { - RenderTextureHandle composed = graph.CreateTexture($"{name}/LinearComposition", - new RenderTextureDescriptor(packet.pixelWidth, packet.pixelHeight, + RenderTextureHandle composed = graph.CreateTexture( + $"{name}/LinearComposition", + new RenderTextureDescriptor( + packet.pixelWidth, + packet.pixelHeight, RenderTextureFormat.RGBA8Srgb, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - pass.UseColorAttachment(composed, 0, RenderLoadAction.Clear, RenderStoreAction.Store, - S_PRESENTATION_CLEAR_COLOR); - var presentation = new PresentationPacket(packet.surface, composed, - packet.pixelWidth, packet.pixelHeight, packet.pipeline, - m_presentationVertices, m_presentationIndices); - RasterPassBuilder output = graph.AddRasterPass($"{name}/Present", S_USER_INTERFACE_PHASE, - presentation, ExecutePresentationPacket); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + pass.UseColorAttachment( + composed, + 0, + RenderLoadAction.Clear, + RenderStoreAction.Store, + PRESENTATION_CLEAR_COLOR + ); + var presentation = new PresentationPacket( + packet.surface, + composed, + packet.pixelWidth, + packet.pixelHeight, + packet.pipeline, + m_presentationVertices, + m_presentationIndices + ); + RasterPassBuilder output = graph.AddRasterPass( + $"{name}/Present", + USER_INTERFACE_PHASE, + presentation, + ExecutePresentationPacket + ); output.SetViewTransform(Identity(), Identity()) .ClearPresentationTarget(default) .HasSideEffect(); output.ReadTexture(composed); if (packet.surface.isValid) + { output.UseSurface(packet.surface); + } } else { - pass.ClearPresentationTarget(S_PRESENTATION_CLEAR_COLOR).HasSideEffect(); + pass.ClearPresentationTarget(PRESENTATION_CLEAR_COLOR).HasSideEffect(); if (packet.surface.isValid) + { pass.UseSurface(packet.surface); + } } } } @@ -429,8 +462,10 @@ public void Dispose() lock (m_sync) { m_disposeRequested = true; - foreach (uint viewportId in m_viewports.Keys.ToArray()) - _ = RetireViewport(m_viewports[viewportId].target); + foreach (uint viewportID in m_viewports.Keys.ToArray()) + { + _ = RetireViewportAsync(m_viewports[viewportID].target); + } m_mainPacket = null; m_framePackets = []; } @@ -448,7 +483,8 @@ private void PreparePipeline() { GraphicsPipelineHandle candidate = m_device.CreateGraphicsPipeline( m_pendingPipelineDescriptor, - "ImGui Pipeline"); + "ImGui Pipeline" + ); GraphicsPipelineHandle previous = m_pipeline; m_pipeline = candidate; m_pendingPipelineDescriptor = null; @@ -468,28 +504,37 @@ private void PreparePipeline() private void PreparePresentationQuad() { if (m_presentationVertices.isValid) + { return; + } PersistentBufferHandle vertices = default; PersistentBufferHandle indices = default; try { vertices = m_device.CreateBuffer( - new PersistentBufferDescriptor(new RenderBufferDescriptor(4, C_VERTEX_STRIDE, RenderBufferUsage.Vertex), S_VERTEX_LAYOUT), + new PersistentBufferDescriptor(new RenderBufferDescriptor(4, C_VERTEX_STRIDE, RenderBufferUsage.Vertex), VERTEX_LAYOUT), CreatePresentationVertices(m_device.capabilities.originBottomLeft), - "ImGui Presentation Vertices"); + "ImGui Presentation Vertices" + ); indices = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(6, C_INDEX_STRIDE, RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16), + indexFormat: RenderIndexFormat.UInt16 + ), [0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0], - "ImGui Presentation Indices"); + "ImGui Presentation Indices" + ); } catch { if (indices.isValid) + { m_device.DestroyBuffer(indices); + } if (vertices.isValid) + { m_device.DestroyBuffer(vertices); + } throw; } m_presentationVertices = vertices; @@ -506,7 +551,8 @@ private void PrepareSurfaces() state.target.nativeHandles, state.target.width, state.target.height, - $"ImGui Viewport {state.target.viewportId}"); + $"ImGui Viewport {state.target.viewportID}" + ); state.resizePending = false; } else if (state.resizePending) @@ -539,15 +585,16 @@ private void PrepareTextures() PersistentTextureHandle texture; if (m_ownedTextures.TryGetValue(token, out OwnedTexture? current) && current.width == upload.width - && current.height == upload.height) - { + && current.height == upload.height + ) { texture = current.handle; } else { texture = m_device.CreateTexture( new RenderTextureDescriptor(upload.width, upload.height, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled), - $"ImGui Texture {token}"); + $"ImGui Texture {token}" + ); if (current is not null) { m_device.DestroyTexture(current.handle); @@ -572,7 +619,7 @@ private void PrepareDrawPackets() m_mainPacket = null; } - foreach (ViewportState state in m_viewports.Values.OrderBy(static value => value.target.viewportId)) + foreach (ViewportState state in m_viewports.Values.OrderBy(static value => value.target.viewportID)) { if (state.packet is not null) { @@ -590,8 +637,8 @@ private void PrepareDrawPackets() } EnsureDynamicBuffers(vertexCount, indexCount); - byte[] vertices = new byte[checked(vertexCount * C_VERTEX_STRIDE)]; - byte[] indices = new byte[checked(indexCount * C_INDEX_STRIDE)]; + var vertices = new byte[checked(vertexCount * C_VERTEX_STRIDE)]; + var indices = new byte[checked(indexCount * C_INDEX_STRIDE)]; List prepared = []; int vertexBase = 0; int indexBase = 0; @@ -604,29 +651,35 @@ private void PrepareDrawPackets() { if (m_textures.TryGetValue(command.textureToken, out PersistentTextureHandle texture)) { - commands.Add(new PreparedDrawCommand( - command.clipX, - command.clipY, - command.clipWidth, - command.clipHeight, - vertexBase + command.firstVertex, - indexBase + command.firstIndex, - command.indexCount, - texture)); + commands.Add( + new PreparedDrawCommand( + command.clipX, + command.clipY, + command.clipWidth, + command.clipHeight, + vertexBase + command.firstVertex, + indexBase + command.firstIndex, + command.indexCount, + texture + ) + ); } } - prepared.Add(new PreparedPacket( - packet.viewportId, - packet.surface, - packet.displayPosition, - packet.displaySize, - packet.pixelWidth, - packet.pixelHeight, - commands, - m_pipeline, - m_vertexBuffer, - m_indexBuffer)); + prepared.Add( + new PreparedPacket( + packet.viewportID, + packet.surface, + packet.displayPosition, + packet.displaySize, + packet.pixelWidth, + packet.pixelHeight, + commands, + m_pipeline, + m_vertexBuffer, + m_indexBuffer + ) + ); vertexBase += packet.vertices.Length / C_VERTEX_STRIDE; indexBase += packet.indices.Length / C_INDEX_STRIDE; } @@ -646,9 +699,11 @@ int indexCount PersistentBufferHandle replacement = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, C_VERTEX_STRIDE, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), - S_VERTEX_LAYOUT), - ReadOnlySpan.Empty, - "ImGui Vertices"); + VERTEX_LAYOUT + ), + [], + "ImGui Vertices" + ); if (m_vertexBuffer.isValid) { m_device.DestroyBuffer(m_vertexBuffer); @@ -664,9 +719,11 @@ int indexCount PersistentBufferHandle replacement = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, C_INDEX_STRIDE, RenderBufferUsage.Index | RenderBufferUsage.Dynamic), - indexFormat: RenderIndexFormat.UInt16), - ReadOnlySpan.Empty, - "ImGui Indices"); + indexFormat: RenderIndexFormat.UInt16 + ), + [], + "ImGui Indices" + ); if (m_indexBuffer.isValid) { m_device.DestroyBuffer(m_indexBuffer); @@ -678,33 +735,35 @@ int indexCount } private DrawPacket? CaptureDrawData( - IntPtr address, - uint viewportId, + nint address, + uint viewportID, RenderSurfaceHandle surface ) { - if (address == IntPtr.Zero) + if (address == nint.Zero) { return null; } - var drawData = (ImDrawData*)address; + ImDrawData* drawData = (ImDrawData*)address; if (drawData->Valid == 0 || drawData->TotalVtxCount <= 0 || drawData->TotalIdxCount <= 0) { return null; } - Vector2 clipScale = new(drawData->FramebufferScale.X, drawData->FramebufferScale.Y); + var clipScale = new Vector2(drawData->FramebufferScale.X, drawData->FramebufferScale.Y); int pixelWidth = checked((int)MathF.Round(drawData->DisplaySize.X * clipScale.X)); int pixelHeight = checked((int)MathF.Round(drawData->DisplaySize.Y * clipScale.Y)); if (pixelWidth <= 0 || pixelHeight <= 0) + { return null; + } ProcessTextureRequests(drawData); - byte[] vertices = new byte[checked(drawData->TotalVtxCount * C_VERTEX_STRIDE)]; - byte[] indices = new byte[checked(drawData->TotalIdxCount * C_INDEX_STRIDE)]; + var vertices = new byte[checked(drawData->TotalVtxCount * C_VERTEX_STRIDE)]; + var indices = new byte[checked(drawData->TotalIdxCount * C_INDEX_STRIDE)]; List commands = []; int vertexBase = 0; int indexBase = 0; - Vector2 clipOffset = new(drawData->DisplayPos.X, drawData->DisplayPos.Y); + var clipOffset = new Vector2(drawData->DisplayPos.X, drawData->DisplayPos.Y); for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; @@ -718,7 +777,7 @@ RenderSurfaceHandle surface for (int commandIndex = 0; commandIndex < drawList->CmdBuffer.Size; commandIndex++) { ImDrawCmd command = drawList->CmdBuffer.Data[commandIndex]; - if (command.UserCallback != null || command.ElemCount == 0) + if (command.UserCallback is not null || command.ElemCount == 0) { continue; } @@ -733,15 +792,18 @@ RenderSurfaceHandle surface continue; } - commands.Add(new CapturedDrawCommand( - clipX, - clipY, - clipRight - clipX, - clipBottom - clipY, - checked(vertexBase + (int)command.VtxOffset), - checked(indexBase + (int)command.IdxOffset), - checked((int)command.ElemCount), - ImGuiNative.Raw.GetTexID(&command))); + commands.Add( + new CapturedDrawCommand( + clipX, + clipY, + clipRight - clipX, + clipBottom - clipY, + checked(vertexBase + (int)command.VtxOffset), + checked(indexBase + (int)command.IdxOffset), + checked((int)command.ElemCount), + ImGuiNative.Raw.GetTexID(&command) + ) + ); } vertexBase += listVertexCount; @@ -749,7 +811,7 @@ RenderSurfaceHandle surface } return new DrawPacket( - viewportId, + viewportID, surface, new Vector2(drawData->DisplayPos.X, drawData->DisplayPos.Y), new Vector2(drawData->DisplaySize.X, drawData->DisplaySize.Y), @@ -757,12 +819,13 @@ RenderSurfaceHandle surface pixelHeight, vertices, indices, - commands); + commands + ); } private void ProcessTextureRequests(ImDrawData* drawData) { - var textures = drawData->Textures; + ImVectorImTextureDataPtr* textures = drawData->Textures; if (textures is null) { return; @@ -771,7 +834,7 @@ private void ProcessTextureRequests(ImDrawData* drawData) for (int index = 0; index < textures->Size; index++) { ImTextureData* textureData = textures->Data[index]; - if (textureData == null) + if (textureData is null) { continue; } @@ -793,8 +856,8 @@ private void ProcessTextureRequests(ImDrawData* drawData) if (textureData->Status is not (ImTextureStatus.WantCreate or ImTextureStatus.WantUpdates) || textureData->Pixels is null || textureData->Width <= 0 - || textureData->Height <= 0) - { + || textureData->Height <= 0 + ) { continue; } @@ -808,18 +871,69 @@ private void ProcessTextureRequests(ImDrawData* drawData) m_pendingTextureUploads[token] = new TextureUpload( textureData->Width, textureData->Height, - CopyTexturePixels(textureData)); + CopyTexturePixels(textureData) + ); ImGuiNative.Raw.SetStatus(textureData, ImTextureStatus.Ok); } } + private void ReleaseDeviceResources() + { + foreach (OwnedTexture texture in m_ownedTextures.Values) + { + m_device.DestroyTexture(texture.handle); + } + + if (m_vertexBuffer.isValid) + { + m_device.DestroyBuffer(m_vertexBuffer); + } + + if (m_indexBuffer.isValid) + { + m_device.DestroyBuffer(m_indexBuffer); + } + + if (m_presentationIndices.isValid) + { + m_device.DestroyBuffer(m_presentationIndices); + } + if (m_presentationVertices.isValid) + { + m_device.DestroyBuffer(m_presentationVertices); + } + + if (m_pipeline.isValid) + { + m_device.DestroyGraphicsPipeline(m_pipeline); + } + + m_ownedTextures.Clear(); + m_textures.Clear(); + m_vertexBuffer = default; + m_indexBuffer = default; + m_presentationVertices = default; + m_presentationIndices = default; + m_pipeline = default; + } + + private ulong AllocateTextureToken() + { + if (m_nextTextureToken == 0) + { + throw new InvalidOperationException("ImGui texture token space was exhausted."); + } + + return m_nextTextureToken++; + } + private static byte[] CopyTexturePixels(ImTextureData* textureData) { int sourcePitch = ImGuiNative.Raw.GetPitch(textureData); if (textureData->Format == ImTextureFormat.Rgba32) { int rowBytes = checked(textureData->Width * 4); - byte[] result = new byte[checked(rowBytes * textureData->Height)]; + var result = new byte[checked(rowBytes * textureData->Height)]; for (int y = 0; y < textureData->Height; y++) { new ReadOnlySpan(textureData->Pixels + (y * sourcePitch), rowBytes) @@ -829,7 +943,7 @@ private static byte[] CopyTexturePixels(ImTextureData* textureData) return result; } - byte[] expanded = new byte[checked(textureData->Width * textureData->Height * 4)]; + var expanded = new byte[checked(textureData->Width * textureData->Height * 4)]; for (int y = 0; y < textureData->Height; y++) { byte* source = textureData->Pixels + (y * sourcePitch); @@ -851,13 +965,13 @@ private static void ExecutePacket( RenderPassContext context ) { context.commands.BindGraphicsPipeline(packet.pipeline); - context.commands.SetUniform(S_OUTPUT_ENCODING, S_LINEAR_OUTPUT); + context.commands.SetUniform(OUTPUT_ENCODING, LINEAR_OUTPUT); foreach (PreparedDrawCommand command in packet.commands) { context.commands.SetScissor(command.clipX, command.clipY, command.clipWidth, command.clipHeight); context.commands.BindVertexBuffer(packet.vertexBuffer, command.firstVertex); context.commands.BindIndexBuffer(packet.indexBuffer, command.firstIndex); - context.commands.BindTexture(S_TEXTURE_BINDING, command.texture); + context.commands.BindTexture(TEXTURE_BINDING, command.texture); context.commands.DrawIndexed(command.indexCount); } } @@ -869,75 +983,35 @@ RenderPassContext context context.commands.SetViewport(0, 0, packet.width, packet.height); context.commands.SetScissor(0, 0, packet.width, packet.height); context.commands.BindGraphicsPipeline(packet.pipeline); - context.commands.SetUniform(S_OUTPUT_ENCODING, S_ENCODED_OUTPUT); + context.commands.SetUniform(OUTPUT_ENCODING, ENCODED_OUTPUT); context.commands.BindVertexBuffer(packet.vertices); context.commands.BindIndexBuffer(packet.indices); - context.commands.BindTexture(S_TEXTURE_BINDING, packet.source); + context.commands.BindTexture(TEXTURE_BINDING, packet.source); context.commands.DrawIndexed(6); } - private void ReleaseDeviceResources() - { - foreach (OwnedTexture texture in m_ownedTextures.Values) - { - m_device.DestroyTexture(texture.handle); - } - - if (m_vertexBuffer.isValid) - { - m_device.DestroyBuffer(m_vertexBuffer); - } - - if (m_indexBuffer.isValid) - { - m_device.DestroyBuffer(m_indexBuffer); - } - - if (m_presentationIndices.isValid) - m_device.DestroyBuffer(m_presentationIndices); - if (m_presentationVertices.isValid) - m_device.DestroyBuffer(m_presentationVertices); - - if (m_pipeline.isValid) - { - m_device.DestroyGraphicsPipeline(m_pipeline); - } - - m_ownedTextures.Clear(); - m_textures.Clear(); - m_vertexBuffer = default; - m_indexBuffer = default; - m_presentationVertices = default; - m_presentationIndices = default; - m_pipeline = default; - } - - private ulong AllocateTextureToken() - { - if (m_nextTextureToken == 0) - { - throw new InvalidOperationException("ImGui texture token space was exhausted."); - } - - return m_nextTextureToken++; - } - private static void ValidatePipelineDescriptor(GraphicsPipelineDescriptor descriptor) { - if (descriptor.vertexLayout is null || !descriptor.vertexLayout.Equals(S_VERTEX_LAYOUT)) + if (descriptor.vertexLayout is null || !descriptor.vertexLayout.Equals(VERTEX_LAYOUT)) { throw new ArgumentException("ImGui pipeline vertex layout must be Position2, UV2, ColorRGBA8.", nameof(descriptor)); } RenderShaderBindingDescriptor? texture = descriptor.bindings.SingleOrDefault( - static value => value.id == S_TEXTURE_BINDING); + static value => value.id == TEXTURE_BINDING + ); if (texture is null || texture.kind != RenderShaderBindingKind.Texture || texture.slot != 0) + { throw new ArgumentException("ImGui pipeline must declare texture binding 's_tex' at slot zero.", nameof(descriptor)); + } RenderShaderBindingDescriptor? outputEncoding = descriptor.bindings.SingleOrDefault( - static value => value.id == S_OUTPUT_ENCODING); + static value => value.id == OUTPUT_ENCODING + ); if (descriptor.bindings.Count != 2 || outputEncoding is null - || outputEncoding.kind != RenderShaderBindingKind.Uniform) + || outputEncoding.kind != RenderShaderBindingKind.Uniform + ) { throw new ArgumentException("ImGui pipeline must declare its outputEncoding render-pass uniform.", nameof(descriptor)); + } } private static int GrowCapacity( @@ -955,14 +1029,14 @@ int minimum private static byte[] CreateOutputEncoding() { - byte[] data = new byte[16]; + var data = new byte[16]; BinaryPrimitives.WriteSingleLittleEndian(data, 1f); return data; } private static byte[] CreatePresentationVertices(bool originBottomLeft) { - byte[] data = new byte[4 * C_VERTEX_STRIDE]; + var data = new byte[4 * C_VERTEX_STRIDE]; float top = originBottomLeft ? 1f : 0f; float bottom = originBottomLeft ? 0f : 1f; WriteVertex(0, -1f, 1f, 0f, top); @@ -989,12 +1063,11 @@ float v private static float SrgbToLinear(float value) => value <= 0.04045f - ? value / 12.92f - : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); + ? value / 12.92f + : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); private static float[] Identity() - => - [ + => [ 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, @@ -1011,10 +1084,22 @@ Vector2 size float bottom = position.Y + size.Y; return [ - 2f / (right - left), 0f, 0f, 0f, - 0f, 2f / (top - bottom), 0f, 0f, - 0f, 0f, 1f, 0f, - (right + left) / (left - right), (top + bottom) / (bottom - top), 0f, 1f + 2f / (right - left), + 0f, + 0f, + 0f, + 0f, + 2f / (top - bottom), + 0f, + 0f, + 0f, + 0f, + 1f, + 0f, + (right + left) / (left - right), + (top + bottom) / (bottom - top), + 0f, + 1f ]; } @@ -1026,19 +1111,26 @@ private sealed class ViewportState /// /// The existing target that receives the validated result. /// - public ViewportState(PlatformImGuiViewportTarget target) => this.target = target; + public ViewportState(PlatformImGuiViewportTarget target) + { + this.target = target; + } + /// /// Gets the platform viewport whose render resources are tracked by this state. /// public PlatformImGuiViewportTarget target { get; set; } + /// /// Gets the presentation surface targeted by this render pass. /// public RenderSurfaceHandle surface { get; set; } + /// /// Gets the most recently prepared immutable draw packet, or null before preparation. /// public DrawPacket? packet { get; set; } + /// /// Gets whether the caller-visible condition represented by this property is satisfied. /// @@ -1050,11 +1142,13 @@ private sealed record OwnedTexture( int width, int height ); + private sealed record TextureUpload( int width, int height, byte[] pixels ); + private sealed record CapturedDrawCommand( int clipX, int clipY, @@ -1078,7 +1172,7 @@ PersistentTextureHandle texture ); private sealed record DrawPacket( - uint viewportId, + uint viewportID, RenderSurfaceHandle initialSurface, Vector2 displayPosition, Vector2 displaySize, @@ -1095,7 +1189,7 @@ IReadOnlyList commands } private sealed record PreparedPacket( - uint viewportId, + uint viewportID, RenderSurfaceHandle surface, Vector2 displayPosition, Vector2 displaySize, diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs index 9dc86416b..0827f63ac 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using Inno.Rendering; @@ -26,17 +27,21 @@ public static GraphicsPipelineDescriptor Load(GraphicsApi api) { string resource = $"Inno.BuiltInShaders.ImGui.{api}"; using Stream source = typeof(BgfxImGuiShaderArtifacts).Assembly.GetManifestResourceStream(resource) - ?? throw new InvalidDataException($"Missing precompiled ImGui shader '{resource}'. Rebuild or repair the adapter installation; runtime source compilation is not supported."); + ?? throw new InvalidDataException( + $"Missing precompiled ImGui shader '{resource}'. Rebuild or repair the adapter installation; runtime source compilation is not supported." + ); using var bytes = new MemoryStream(); source.CopyTo(bytes); GraphicsPipelineDescriptor program = GraphicsProgramArtifactCodec.Decode(bytes.ToArray(), BgfxImGuiRenderer.vertexLayout); - var bindings = program.bindings; + IReadOnlyList bindings = program.bindings; RenderShaderBindingDescriptor? texture = bindings.SingleOrDefault(static binding => binding.id.value == "s_tex"); RenderShaderBindingDescriptor? outputEncoding = bindings.SingleOrDefault(static binding => binding.id.value == "outputEncoding"); if (bindings.Count != 2 || texture is null || texture.kind != RenderShaderBindingKind.Texture || texture.slot != 0 || outputEncoding is null - || outputEncoding.kind != RenderShaderBindingKind.Uniform) + || outputEncoding.kind != RenderShaderBindingKind.Uniform + ) { throw new InvalidDataException("The built-in ImGui graph must expose s_tex and the outputEncoding render-pass uniform."); + } return program; } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs index 25dfe8b2e..57a94ed2e 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation; using Inno.Adapter.Presentation.ImGui; @@ -22,11 +21,13 @@ ImGuiInteractionOptions interaction ) { ArgumentNullException.ThrowIfNull(options); m_application = options.platformApplication as Sdl3PlatformApplication - ?? throw new NotSupportedException( - "The built-in ImGui presentation requires the selected platform adapter to support SDL3 integration."); + ?? throw new NotSupportedException( + "The built-in ImGui presentation requires the selected platform adapter to support SDL3 integration." + ); m_window = options.window as Sdl3PlatformWindow - ?? throw new NotSupportedException( - "The built-in ImGui presentation requires a window created by the selected SDL3 platform adapter."); + ?? throw new NotSupportedException( + "The built-in ImGui presentation requires a window created by the selected SDL3 platform adapter." + ); GraphicsPipelineDescriptor pipeline = BgfxImGuiShaderArtifacts.Load(options.renderDevice.capabilities.backend); m_renderer = new BgfxImGuiRenderer(options.renderDevice, pipeline); @@ -36,7 +37,8 @@ ImGuiInteractionOptions interaction m_window, ToImGuiFlags(options.features), interaction, - m_renderer); + m_renderer + ); } catch { @@ -47,18 +49,17 @@ ImGuiInteractionOptions interaction void IPresentationContext.SetLayoutFile(string? filePath) => m_context.SetIniFile(filePath); - bool IPresentationContext.TryGetWindowId( - uint viewportId, - out uint windowId - ) => m_context.TryGetWindowId(viewportId, out windowId); + bool IPresentationContext.TryGetWindowID( + uint viewportID, + out uint windowID + ) => m_context.TryGetWindowID(viewportID, out windowID); void IPresentationContext.LoadLayout(string? settings) => m_context.LoadIniSettings(settings); bool IPresentationContext.TryCaptureLayout( out string settings, bool force - ) - => m_context.TryCaptureIniSettings(out settings, force); + ) => m_context.TryCaptureIniSettings(out settings, force); void IPresentationContext.RenderFrame( Action drawFrame, @@ -79,7 +80,9 @@ void IPresentationContext.DrawImage( Vector2 size ) { if (!texture.isValid) + { throw new ArgumentException("The presentation texture handle is invalid.", nameof(texture)); + } m_context.DrawImage(new ImGuiTextureHandle(texture.value), size); } @@ -88,27 +91,33 @@ Vector2 size void IRenderFrameGraphContributor.AddRenderPasses( RenderGraphBuilder graph, ulong frameIndex - ) - => m_renderer.AddRenderPasses(graph, frameIndex); + ) => m_renderer.AddRenderPasses(graph, frameIndex); void IDisposable.Dispose() { if (m_disposed) + { return; + } m_application.DestroyImGuiContext(m_window); m_disposed = true; } - private static ImGuiContextFlags ToImGuiFlags(PresentationFeatures features) { ImGuiContextFlags result = ImGuiContextFlags.None; if ((features & PresentationFeatures.MultipleWindows) != 0) + { result |= ImGuiContextFlags.EnableViewports; + } if ((features & PresentationFeatures.Docking) != 0) + { result |= ImGuiContextFlags.EnableDocking; + } if ((features & PresentationFeatures.SmoothResize) != 0) + { result |= ImGuiContextFlags.EnableSmoothResize; + } return result; } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs index 6dd1bc408..18807b16b 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs @@ -19,13 +19,14 @@ public sealed class ImGuiPresentationProvider : PresentationBackendProvider /// /// Interaction configuration is absent. /// - public ImGuiPresentationProvider(ImGuiInteractionOptions interaction) : base(PresentationBackendId.imGui) + public ImGuiPresentationProvider(ImGuiInteractionOptions interaction) + : base(PresentationBackendID.imGui) { ArgumentNullException.ThrowIfNull(interaction); m_interaction = interaction; } - /// + /// public override IPresentationContext CreateContext(PresentationBackendOptions options) => new ImGuiPresentationContext(options, m_interaction); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs index 77fba39da..62a66c8bf 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs @@ -1,87 +1,8 @@ -using System.Threading.Tasks; -using Inno.Adapter.Platform; using System; -using Inno.Platform; +using System.Threading.Tasks; namespace Inno.Adapter.Presentation.ImGui; -/// -/// Identifies a backend-owned texture through an opaque ImGui token instead of a native graphics handle. -/// -public readonly record struct ImGuiTextureHandle -{ - /// - /// Creates an opaque texture token allocated by an ImGui presentation backend. - /// - /// - /// Non-zero backend token. - /// - public ImGuiTextureHandle(ulong value) - { - if (value == 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } - - this.value = value; - } - - /// - /// Gets the opaque token consumed only by the active ImGui backend. - /// - public ulong value { get; } - - /// - /// Gets whether this token identifies a registered texture. - /// - public bool isValid => value != 0; -} - -/// -/// Describes one detached ImGui viewport without exposing SDL or graphics-backend handles. -/// -public sealed class PlatformImGuiViewportTarget -{ - internal PlatformImGuiViewportTarget( - uint viewportId, - uint windowId, - PlatformNativeHandles nativeHandles, - int width, - int height - ) { - this.viewportId = viewportId; - this.windowId = windowId; - this.nativeHandles = nativeHandles; - this.width = width; - this.height = height; - } - - /// - /// Gets the stable Dear ImGui viewport identity. - /// - public uint viewportId { get; } - - /// - /// Gets the platform window identity. - /// - public uint windowId { get; } - - /// - /// Gets backend-neutral native-window integration handles. - /// - public PlatformNativeHandles nativeHandles { get; } - - /// - /// Gets the current framebuffer width. - /// - public int width { get; internal set; } - - /// - /// Gets the current framebuffer height. - /// - public int height { get; internal set; } -} - /// /// Presents ImGui draw data through a replaceable renderer while platform input and windows stay shared. /// @@ -103,7 +24,7 @@ public interface IPlatformImGuiRenderer : IDisposable /// /// Opaque native ImDrawData pointer valid for the current frame. /// - void RenderMain(IntPtr drawData); + void RenderMain(nint drawData); /// /// Synchronizes the primary drawable after a platform resize. @@ -146,7 +67,7 @@ int pixelHeight /// void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData + nint drawData ); /// @@ -169,7 +90,7 @@ IntPtr drawData /// /// Native callbacks may request retirement but must not wait or advance rendering. /// - Task RetireViewport(PlatformImGuiViewportTarget target); + Task RetireViewportAsync(PlatformImGuiViewportTarget target); /// /// Drains requested retirements at a closed-frame owner-thread point outside native UI callbacks. diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs index 173c67c00..ab8a2a2cc 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs @@ -24,7 +24,9 @@ public ImGuiInteractionOptions( int horizontalWheelDirection ) { if (horizontalWheelDirection is not (1 or -1)) + { throw new ArgumentOutOfRangeException(nameof(horizontalWheelDirection), "Wheel direction must be one or minus one."); + } this.commandKeyBehavior = commandKeyBehavior; this.horizontalWheelDirection = horizontalWheelDirection; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs new file mode 100644 index 000000000..776cee9c3 --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs @@ -0,0 +1,32 @@ +using System; + +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Identifies a backend-owned texture through an opaque ImGui token instead of a native graphics handle. +/// +public readonly record struct ImGuiTextureHandle +{ + /// + /// Creates an opaque texture token allocated by an ImGui presentation backend. + /// + /// + /// Non-zero backend token. + /// + public ImGuiTextureHandle(ulong value) + { + ArgumentOutOfRangeException.ThrowIfZero(value); + + this.value = value; + } + + /// + /// Gets the opaque token consumed only by the active ImGui backend. + /// + public ulong value { get; } + + /// + /// Gets whether this token identifies a registered texture. + /// + public bool isValid => value != 0; +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiContext.Api.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiContext.Api.cs index a5de98426..2ad509a1a 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiContext.Api.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiContext.Api.cs @@ -11,10 +11,10 @@ public sealed partial class PlatformImGuiContext : IDisposable /// /// Resolves the SDL window currently owned by an ImGui viewport. /// - /// + /// /// The ImGui viewport identity. /// - /// + /// /// The SDL window identity when available. /// /// @@ -23,9 +23,9 @@ public sealed partial class PlatformImGuiContext : IDisposable /// /// Thrown after the presentation context has been disposed. /// - public partial bool TryGetWindowId( - uint viewportId, - out uint windowId + public partial bool TryGetWindowID( + uint viewportID, + out uint windowID ); /// @@ -109,7 +109,7 @@ public partial bool TryCaptureIniSettings( /// /// A callback failed and its owned native frame also failed to retire. /// - public partial IntPtr RenderFrame( + public partial nint RenderFrame( Action drawFrame, Action? prepareFrame = null ); diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs new file mode 100644 index 000000000..904eacace --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs @@ -0,0 +1,48 @@ +using Inno.Adapter.Platform; + +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Describes one detached ImGui viewport without exposing SDL or graphics-backend handles. +/// +public sealed class PlatformImGuiViewportTarget +{ + internal PlatformImGuiViewportTarget( + uint viewportID, + uint windowID, + PlatformNativeHandles nativeHandles, + int width, + int height + ) { + this.viewportID = viewportID; + this.windowID = windowID; + this.nativeHandles = nativeHandles; + this.width = width; + this.height = height; + } + + /// + /// Gets the stable Dear ImGui viewport identity. + /// + public uint viewportID { get; } + + /// + /// Gets the platform window identity. + /// + public uint windowID { get; } + + /// + /// Gets backend-neutral native-window integration handles. + /// + public PlatformNativeHandles nativeHandles { get; } + + /// + /// Gets the current framebuffer width. + /// + public int width { get; internal set; } + + /// + /// Gets the current framebuffer height. + /// + public int height { get; internal set; } +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs index 397a835d5..75c2bd3c6 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using Inno.Adapter.Platform.Sdl3; using Inno.Native.Sdl3; @@ -13,70 +12,7 @@ namespace Inno.Adapter.Presentation.ImGui; /// public static class Sdl3PlatformApplicationImGuiExtensions { - private sealed class ImGuiState : ISdl3ApplicationExtension - { - private readonly Sdl3PlatformApplication m_application; - private IDisposable? m_registration; - private bool m_isRetiring; - - internal ImGuiState(Sdl3PlatformApplication application) - { - m_application = application; - } - - internal Dictionary contexts { get; } = []; - internal bool isRetiring => m_isRetiring; - - internal void Register() - { - m_registration = m_application.RegisterExtension(this); - } - - internal void Release( - uint windowId, - PlatformImGuiContext context - ) { - if (!contexts.TryGetValue(windowId, out PlatformImGuiContext? registered) || !ReferenceEquals(registered, context)) - throw new InvalidOperationException("The retired ImGui context no longer owns its application registration."); - contexts.Remove(windowId); - } - - void ISdl3ApplicationExtension.ProcessNativeEvent( - Sdl3PlatformApplication application, - scoped ReadOnlySpan nativeEventData - ) { - if (nativeEventData.Length < Marshal.SizeOf()) - { - return; - } - - SDLEvent sdlEvent = MemoryMarshal.Read(nativeEventData); - foreach (PlatformImGuiContext context in contexts.Values) - context.ProcessEvent(ref sdlEvent); - } - - void ISdl3ApplicationExtension.PrepareLiveResizeWindow( - Sdl3PlatformApplication application, - uint windowId - ) { - foreach (PlatformImGuiContext context in contexts.Values) - context.PrepareLiveResizeWindow(windowId); - } - - void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication application) - { - m_isRetiring = true; - var retiring = new PlatformImGuiContext[contexts.Count]; - contexts.Values.CopyTo(retiring, 0); - foreach (PlatformImGuiContext context in retiring) - context.Dispose(); - s_states.Remove(application); - m_registration?.Dispose(); - m_registration = null; - } - } - - private static readonly ConditionalWeakTable s_states = new(); + private static readonly ConditionalWeakTable STATES = new(); /// /// Creates one ImGui context and transfers the supplied renderer ownership only after successful creation. @@ -87,12 +23,12 @@ void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication ap /// /// Target platform window. /// - /// - /// Explicit immutable keyboard and wheel conventions supplied by the product. - /// /// /// ImGui context feature flags. /// + /// + /// Explicit immutable keyboard and wheel conventions supplied by the product. + /// /// /// Optional presentation backend; ownership transfers on success and remains with the caller on failure. /// @@ -120,23 +56,39 @@ public static PlatformImGuiContext CreateImGuiContext( ArgumentNullException.ThrowIfNull(interaction); if (window.isClosed) + { throw new InvalidOperationException("Cannot create an ImGui context for a closed window."); + } bool registered = false; foreach (Sdl3PlatformWindow candidate in application.GetWindows()) + { registered |= ReferenceEquals(candidate, window); + } if (!registered) + { throw new ArgumentException("The window must belong to the supplied SDL application.", nameof(window)); + } - ImGuiState state = s_states.GetValue(application, CreateState); + ImGuiState state = STATES.GetValue(application, CreateState); if (state.isRetiring) + { throw new InvalidOperationException("The application presentation state is retiring and cannot create another context."); - if (state.contexts.ContainsKey(window.windowId)) + } + if (state.contexts.ContainsKey(window.windowID)) + { throw new InvalidOperationException("This window already owns an ImGui context."); + } - uint windowId = window.windowId; - var context = new PlatformImGuiContext(application, window, contextFlags, interaction, renderer, - retired => state.Release(windowId, retired)); - state.contexts[windowId] = context; + uint windowID = window.windowID; + var context = new PlatformImGuiContext( + application, + window, + contextFlags, + interaction, + renderer, + retired => state.Release(windowID, retired) + ); + state.contexts[windowID] = context; return context; } @@ -162,10 +114,14 @@ Sdl3PlatformWindow window ArgumentNullException.ThrowIfNull(application); ArgumentNullException.ThrowIfNull(window); - if (!s_states.TryGetValue(application, out ImGuiState? state)) + if (!STATES.TryGetValue(application, out ImGuiState? state)) + { return; - if (!state.contexts.TryGetValue(window.windowId, out PlatformImGuiContext? context)) + } + if (!state.contexts.TryGetValue(window.windowID, out PlatformImGuiContext? context)) + { return; + } context.Dispose(); } @@ -175,4 +131,72 @@ private static ImGuiState CreateState(Sdl3PlatformApplication application) state.Register(); return state; } + + private sealed class ImGuiState : ISdl3ApplicationExtension + { + private readonly Sdl3PlatformApplication m_application; + private IDisposable? m_registration; + private bool m_isRetiring; + + internal ImGuiState(Sdl3PlatformApplication application) + { + m_application = application; + } + + void ISdl3ApplicationExtension.ProcessNativeEvent( + Sdl3PlatformApplication application, + scoped ReadOnlySpan nativeEventData + ) { + if (nativeEventData.Length < Marshal.SizeOf()) + { + return; + } + + SDLEvent sdlEvent = MemoryMarshal.Read(nativeEventData); + foreach (PlatformImGuiContext context in contexts.Values) + { + context.ProcessEvent(ref sdlEvent); + } + } + + void ISdl3ApplicationExtension.PrepareLiveResizeWindow( + Sdl3PlatformApplication application, + uint windowID + ) { + foreach (PlatformImGuiContext context in contexts.Values) + { + context.PrepareLiveResizeWindow(windowID); + } + } + + void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication application) + { + m_isRetiring = true; + var retiring = new PlatformImGuiContext[contexts.Count]; + contexts.Values.CopyTo(retiring, 0); + foreach (PlatformImGuiContext context in retiring) + { + context.Dispose(); + } + STATES.Remove(application); + m_registration?.Dispose(); + m_registration = null; + } + + internal Dictionary contexts { get; } = []; + internal bool isRetiring => m_isRetiring; + + internal void Register() => m_registration = m_application.RegisterExtension(this); + + internal void Release( + uint windowID, + PlatformImGuiContext context + ) { + if (!contexts.TryGetValue(windowID, out PlatformImGuiContext? registered) || !ReferenceEquals(registered, context)) + { + throw new InvalidOperationException("The retired ImGui context no longer owns its application registration."); + } + contexts.Remove(windowID); + } + } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs index f2bd51f32..fee99168e 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; using Inno.Native.ImGui; using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -13,11 +14,60 @@ namespace Inno.Adapter.Presentation.ImGui; /// public sealed unsafe partial class PlatformImGuiContext { - private static readonly object S_CLIPBOARD_CONTEXT_SYNC = new(); - private static readonly Dictionary S_CLIPBOARD_CONTEXTS = []; + private static readonly object CLIPBOARD_CONTEXT_SYNC = new(); + private static readonly Dictionary CLIPBOARD_CONTEXTS = []; private nint m_clipboardText; + private sbyte* GetClipboardText() + { + ReleaseClipboardText(); + if (SDL.Raw.HasClipboardText() == 0) + { + return null; + } + // SDL transfers this allocation to the caller; retain it until the next request or context shutdown. + m_clipboardText = (nint)SDL.Raw.GetClipboardText(); + return (sbyte*)m_clipboardText; + } + + private void RegisterClipboardCallbacks() + { + lock (CLIPBOARD_CONTEXT_SYNC) + { + CLIPBOARD_CONTEXTS.Add((nuint)m_context, this); + } + ImGuiPlatformIO* platformIO = ImGuiNative.Raw.GetPlatformIO(); + platformIO->PlatformGetClipboardTextFn = &PlatformGetClipboardTextCallback; + platformIO->PlatformSetClipboardTextFn = &PlatformSetClipboardTextCallback; + } + + private void UnregisterClipboardCallbacks() + { + ImGuiPlatformIO* platformIO = ImGuiNative.Raw.GetPlatformIO(); + platformIO->PlatformGetClipboardTextFn = null; + platformIO->PlatformSetClipboardTextFn = null; + lock (CLIPBOARD_CONTEXT_SYNC) + { + nuint contextKey = (nuint)m_context; + if (CLIPBOARD_CONTEXTS.GetValueOrDefault(contextKey) == this) + { + CLIPBOARD_CONTEXTS.Remove(contextKey); + } + } + ReleaseClipboardText(); + } + + private void ReleaseClipboardText() + { + if (m_clipboardText == 0) + { + return; + } + SDL.Raw.Free((void*)m_clipboardText); + m_clipboardText = 0; + } + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static sbyte* PlatformGetClipboardTextCallback(ImGuiNativeContext* context) { @@ -26,8 +76,9 @@ public sealed unsafe partial class PlatformImGuiContext PlatformImGuiContext? owner = FindClipboardContext(context); return owner is null ? null : owner.GetClipboardText(); } - catch + catch (Exception) { + // An exception must not unwind into native code. Null reports that no text is available. return null; } } @@ -39,10 +90,12 @@ private static void PlatformSetClipboardTextCallback( ) { try { - if (text != null && FindClipboardContext(context) is not null) + if (text is not null && FindClipboardContext(context) is not null) + { _ = SDL.Raw.SetClipboardText(text); + } } - catch + catch (Exception) { // Exceptions must not cross Dear ImGui's unmanaged callback boundary. } @@ -50,50 +103,13 @@ private static void PlatformSetClipboardTextCallback( private static PlatformImGuiContext? FindClipboardContext(ImGuiNativeContext* context) { - if (context == null) - return null; - lock (S_CLIPBOARD_CONTEXT_SYNC) - return S_CLIPBOARD_CONTEXTS.GetValueOrDefault((nuint)context); - } - - private sbyte* GetClipboardText() - { - ReleaseClipboardText(); - if (SDL.Raw.HasClipboardText() == 0) + if (context is null) + { return null; - // SDL transfers this allocation to the caller; retain it until the next request or context shutdown. - m_clipboardText = (nint)SDL.Raw.GetClipboardText(); - return (sbyte*)m_clipboardText; - } - - private void RegisterClipboardCallbacks() - { - lock (S_CLIPBOARD_CONTEXT_SYNC) - S_CLIPBOARD_CONTEXTS.Add((nuint)m_context, this); - ImGuiPlatformIO* platformIo = ImGuiNative.Raw.GetPlatformIO(); - platformIo->PlatformGetClipboardTextFn = &PlatformGetClipboardTextCallback; - platformIo->PlatformSetClipboardTextFn = &PlatformSetClipboardTextCallback; - } - - private void UnregisterClipboardCallbacks() - { - ImGuiPlatformIO* platformIo = ImGuiNative.Raw.GetPlatformIO(); - platformIo->PlatformGetClipboardTextFn = null; - platformIo->PlatformSetClipboardTextFn = null; - lock (S_CLIPBOARD_CONTEXT_SYNC) + } + lock (CLIPBOARD_CONTEXT_SYNC) { - nuint contextKey = (nuint)m_context; - if (S_CLIPBOARD_CONTEXTS.GetValueOrDefault(contextKey) == this) - S_CLIPBOARD_CONTEXTS.Remove(contextKey); + return CLIPBOARD_CONTEXTS.GetValueOrDefault((nuint)context); } - ReleaseClipboardText(); - } - - private void ReleaseClipboardText() - { - if (m_clipboardText == 0) - return; - SDL.Raw.Free((void*)m_clipboardText); - m_clipboardText = 0; } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs index 1564bf3d6..24df1fd5b 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs @@ -5,10 +5,10 @@ using System.Numerics; using System.Runtime.InteropServices; using System.Text; - using Inno.Adapter.Platform.Sdl3; -using Inno.Native.Sdl3; using Inno.Native.ImGui; +using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -18,15 +18,15 @@ namespace Inno.Adapter.Presentation.ImGui; /// public sealed unsafe partial class PlatformImGuiContext { - private const float DEFAULT_KEY_REPEAT_DELAY_SECONDS = 0.275f; - private const float DEFAULT_KEY_REPEAT_RATE_SECONDS = 0.050f; - private const float DEFAULT_FONT_SIZE_PIXELS = 16.0f; - private const float DEFAULT_ICON_SIZE_PIXELS = 14.0f; - private const float DEFAULT_MOUSE_SCROLLING_UNITS = 0.3f; - private const string DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Fonts"; - private const string DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Icons"; - private const string DEFAULT_FONT_FILE_NAME = "JetBrainsMono-Regular.ttf"; - private const double LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS = 0.25; + private const float C_DEFAULT_KEY_REPEAT_DELAY_SECONDS = 0.275f; + private const float C_DEFAULT_KEY_REPEAT_RATE_SECONDS = 0.05f; + private const float C_DEFAULT_FONT_SIZE_PIXELS = 16f; + private const float C_DEFAULT_ICON_SIZE_PIXELS = 14f; + private const float C_DEFAULT_MOUSE_SCROLLING_UNITS = 0.3f; + private const string C_DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Fonts"; + private const string C_DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Icons"; + private const string C_DEFAULT_FONT_FILE_NAME = "JetBrainsMono-Regular.ttf"; + private const double C_LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS = 0.25; private readonly ImGuiInteractionOptions m_interaction; private readonly Sdl3PlatformWindow m_window; @@ -34,21 +34,20 @@ public sealed unsafe partial class PlatformImGuiContext private readonly PlatformImGuiViewportBackend? m_viewports; private readonly IPlatformImGuiRenderer m_renderer; private readonly Dictionary m_cursors = []; - private readonly HashSet m_pendingLiveResizeWindowIds = []; + private readonly HashSet m_pendingLiveResizeWindowIDs = []; private readonly Stopwatch m_frameTimer = Stopwatch.StartNew(); - + private readonly bool m_enableSmoothResize; private ImGuiMouseCursor m_currentCursor = ImGuiMouseCursor.None; private SDLWindow* m_textInputWindow = null; private TimeSpan m_lastFrameTime; private TimeSpan m_lastLiveResizeLockTime; private Action? m_releaseRegistration; - private IntPtr m_iniFilename; - private uint m_liveResizeLockedWindowId; - private uint m_mousePendingLeaveWindowId; - private uint m_mouseWindowId; + private nint m_iniFilename; + private uint m_liveResizeLockedWindowID; + private uint m_mousePendingLeaveWindowID; + private uint m_mouseWindowID; private int m_mouseButtonsDown; private int m_mousePendingLeaveFrame; - private readonly bool m_enableSmoothResize; private bool m_hasStartedFrame; private bool m_isFrameActive; private bool m_isFrameOperationActive; @@ -63,9 +62,10 @@ internal PlatformImGuiContext( IPlatformImGuiRenderer? renderer, Action releaseRegistration ) { - m_releaseRegistration = releaseRegistration ?? throw new ArgumentNullException(nameof(releaseRegistration)); - var enableViewports = (contextFlags & ImGuiContextFlags.EnableViewports) != 0; - var enableDocking = (contextFlags & ImGuiContextFlags.EnableDocking) != 0; + ArgumentNullException.ThrowIfNull(releaseRegistration); + m_releaseRegistration = releaseRegistration; + bool enableViewports = (contextFlags & ImGuiContextFlags.EnableViewports) != 0; + bool enableDocking = (contextFlags & ImGuiContextFlags.EnableDocking) != 0; m_enableSmoothResize = (contextFlags & ImGuiContextFlags.EnableSmoothResize) != 0; m_interaction = interaction; @@ -75,13 +75,13 @@ Action releaseRegistration try { - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); // SDL cannot reliably identify the viewport beneath a transient NoInputs viewport while // docking, and the official SDL backend disables this capability on macOS. Let Dear ImGui // use its viewport heuristic instead of publishing incorrect hovered viewport identities. io->BackendFlags |= (int)ImGuiBackendFlags.HasMouseCursors - | (int)ImGuiBackendFlags.HasSetMousePos - | (int)ImGuiBackendFlags.RendererHasTextures; + | (int)ImGuiBackendFlags.HasSetMousePos + | (int)ImGuiBackendFlags.RendererHasTextures; io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; if (enableDocking) @@ -107,7 +107,9 @@ Action releaseRegistration UpdateDisplayMetrics(io); m_renderer = renderer ?? new PlatformImGuiSdlRenderer(window); if (m_renderer.supportsVertexOffsets) + { io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasVtxOffset; + } m_viewports = enableViewports ? new PlatformImGuiViewportBackend(application, window, m_renderer) : null; RegisterClipboardCallbacks(); } @@ -117,7 +119,9 @@ Action releaseRegistration ImGuiFont.UnregisterContext(m_context); ImGuiNative.Raw.DestroyContext(m_context); if (renderer is null) + { m_renderer?.Dispose(); + } throw; } } @@ -125,10 +129,10 @@ Action releaseRegistration /// /// Resolves the SDL window currently owned by an ImGui viewport. /// - /// + /// /// The ImGui viewport identity. /// - /// + /// /// The SDL window identity when available. /// /// @@ -137,20 +141,22 @@ Action releaseRegistration /// /// Thrown after the presentation context has been disposed. /// - public partial bool TryGetWindowId( - uint viewportId, - out uint windowId + public partial bool TryGetWindowID( + uint viewportID, + out uint windowID ) { ObjectDisposedException.ThrowIf(m_disposed, this); ImGuiNative.Raw.SetCurrentContext(m_context); - if (viewportId == ImGuiNative.Raw.GetMainViewport()->ID) + if (viewportID == ImGuiNative.Raw.GetMainViewport()->ID) { - windowId = m_window.windowId; + windowID = m_window.windowID; return true; } - if (m_viewports is not null && m_viewports.TryGetWindowId(viewportId, out windowId)) + if (m_viewports is not null && m_viewports.TryGetWindowID(viewportID, out windowID)) + { return true; - windowId = 0; + } + windowID = 0; return false; } @@ -164,25 +170,29 @@ public partial void SetIniFile(string? filePath) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("The ImGui layout file must be configured before the first frame."); + } ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); - if (m_iniFilename != IntPtr.Zero) + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + if (m_iniFilename != nint.Zero) { Marshal.FreeCoTaskMem(m_iniFilename); - m_iniFilename = IntPtr.Zero; + m_iniFilename = nint.Zero; } if (string.IsNullOrWhiteSpace(filePath)) { - SetIniFilename(io, IntPtr.Zero); + SetIniFilename(io, nint.Zero); return; } string fullPath = Path.GetFullPath(filePath); string? directory = Path.GetDirectoryName(fullPath); if (!string.IsNullOrWhiteSpace(directory)) + { Directory.CreateDirectory(directory); + } m_iniFilename = Marshal.StringToCoTaskMemUTF8(fullPath); SetIniFilename(io, m_iniFilename); } @@ -197,14 +207,20 @@ public partial void LoadIniSettings(string? settings) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("ImGui layout settings must be loaded before the first frame."); + } if (string.IsNullOrEmpty(settings)) + { return; + } ImGuiNative.Raw.SetCurrentContext(m_context); byte[] encoded = Encoding.UTF8.GetBytes(settings); fixed (byte* data = encoded) + { ImGuiNative.Raw.LoadIniSettingsFromMemory((sbyte*)data, (uint)encoded.Length); + } } /// @@ -239,11 +255,7 @@ Vector2 uv1 uv1 = Vector2.One; } - ImGuiNative.Image( - new ImTextureRef { TexID = texture.value }, - size, - uv0, - uv1); + ImGuiNative.Image(new ImTextureRef { TexID = texture.value }, size, uv0, uv1); } /// @@ -276,12 +288,6 @@ bool force return true; } - private static void ConfigureKeyRepeat(ImGuiIO* io) - { - io->KeyRepeatDelay = DEFAULT_KEY_REPEAT_DELAY_SECONDS; - io->KeyRepeatRate = DEFAULT_KEY_REPEAT_RATE_SECONDS; - } - /// /// Registers or replaces a context-owned text face before the first frame, merging only the bundled icons. /// @@ -301,200 +307,161 @@ float fontSizePixels ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("Font styles must be registered before the first ImGui frame."); + } ImGuiFont.ValidateStyle(style); ArgumentException.ThrowIfNullOrWhiteSpace(filePath); if (!float.IsFinite(fontSizePixels) || fontSizePixels <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSizePixels)); + } string fullPath = Path.GetFullPath(filePath); if (!File.Exists(fullPath)) + { throw new FileNotFoundException("The font file does not exist.", fullPath); + } ImGuiNative.Raw.SetCurrentContext(m_context); ImGuiIO* io = ImGuiNative.Raw.GetIO(); ImFont* loadedFont = LoadFont(io->Fonts, fullPath, fontSizePixels); - if (loadedFont == null) + if (loadedFont is null) + { throw new InvalidOperationException($"Could not load the font '{fullPath}'."); + } ResolveFontPaths(out _, out List iconFontPaths); MergeIconFontsIntoCurrentBaseFont(io->Fonts, iconFontPaths); ImGuiFont.RegisterStyle(m_context, style, (nint)loadedFont); if (style == ImGuiFontStyle.Regular) + { io->FontDefault = loadedFont; + } } - private static void ConfigureFonts( - ImGuiNativeContext* context, - ImGuiIO* io + /// + /// Records frame rendering for the current frame. + /// + /// + /// The callback invoked by render frame within the operation's owned lifetime. + /// + /// + /// Optional callback invoked with the owned context before native frame creation. + /// + /// + /// Borrowed native draw data for the completed frame, valid until the next frame or retirement. + /// + public partial nint RenderFrame( + Action drawFrame, + Action? prepareFrame ) { - var fonts = io->Fonts; - ImGuiNative.Raw.Clear(fonts); - - ResolveFontPaths(out var fontPaths, out var iconFontPaths); - var styleFonts = new Dictionary(); - ImFont* defaultFont = null; - var preferredIndex = FindPreferredFontIndex(fontPaths); - for (var i = 0; i < fontPaths.Count; i++) + ArgumentNullException.ThrowIfNull(drawFrame); + ObjectDisposedException.ThrowIf(m_disposed, this); + if (m_isFrameOperationActive || m_isFrameActive) { - ImFont* loadedFont = LoadFont(fonts, fontPaths[i], DEFAULT_FONT_SIZE_PIXELS); - if (loadedFont == null) - { - continue; - } + throw new InvalidOperationException("An ImGui frame cannot be reentered."); + } - MergeIconFontsIntoCurrentBaseFont(fonts, iconFontPaths); - styleFonts[GetFontStyle(fontPaths[i])] = (nint)loadedFont; - if (i == preferredIndex) + TimeSpan now = m_frameTimer.Elapsed; + float deltaSeconds = (float)(now - m_lastFrameTime).TotalSeconds; + m_lastFrameTime = now; + + m_isFrameOperationActive = true; + try + { + SynchronizePendingLiveResizeWindows(); + BeginFrame(deltaSeconds, prepareFrame); + drawFrame(); + return EndFrame(); + } + catch (Exception failure) + { + try { - defaultFont = loadedFont; + AbortNativeFrame(); } - else if (defaultFont == null) + catch (Exception cleanupFailure) { - defaultFont = loadedFont; + throw new AggregateException("Presentation failed and its native frame could not retire.", failure, cleanupFailure); } + throw; } - - if (defaultFont == null) + finally { - defaultFont = LoadDefaultFont(fonts); - if (defaultFont != null) - { - MergeIconFontsIntoCurrentBaseFont(fonts, iconFontPaths); - } + m_isFrameActive = false; + m_isFrameOperationActive = false; } - - io->FontDefault = defaultFont; - if (defaultFont != null && !styleFonts.ContainsKey(ImGuiFontStyle.Regular)) - styleFonts[ImGuiFontStyle.Regular] = (nint)defaultFont; - ImGuiFont.RegisterContext(context, styleFonts); - } - - private static ImGuiFontStyle GetFontStyle(string fontPath) - { - string name = Path.GetFileNameWithoutExtension(fontPath); - bool bold = name.Contains("Bold", StringComparison.OrdinalIgnoreCase); - bool italic = name.Contains("Italic", StringComparison.OrdinalIgnoreCase); - return (bold ? ImGuiFontStyle.Bold : ImGuiFontStyle.Regular) | - (italic ? ImGuiFontStyle.Italic : ImGuiFontStyle.Regular); } - private static int FindPreferredFontIndex(List fontPaths) + /// + /// Retires the context and its owned resources after the current frame operation has completed. + /// + /// + /// A frame operation still owns the context; the caller must retry after that operation completes. + /// + /// + /// Successful retirement removes this context's application registration and releases its borrowed font data. + /// Pending or failed retirement preserves both registration and ownership for a subsequent retry. + /// + public partial void Dispose() { - if (fontPaths.Count == 0 || string.IsNullOrWhiteSpace(DEFAULT_FONT_FILE_NAME)) - { - return -1; - } - - for (var i = 0; i < fontPaths.Count; i++) + if (m_disposed) { - var fileName = Path.GetFileName(fontPaths[i]); - if (fileName.Equals(DEFAULT_FONT_FILE_NAME, StringComparison.OrdinalIgnoreCase)) - { - return i; - } + return; } - return -1; - } - - private static void ResolveFontPaths( - out List baseFonts, - out List iconFonts - ) { - baseFonts = new List(); - iconFonts = new List(); - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - - foreach (var fontDirectory in ResolveAssetDirectories(DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH)) + if (m_isFrameOperationActive) { - CollectFontFiles(fontDirectory, baseFonts, seen, includeSubdirectories: false); + throw new InvalidOperationException("A presentation context cannot retire during its frame operation."); } - foreach (var iconDirectory in ResolveAssetDirectories(DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH)) + ImGuiNative.Raw.SetCurrentContext(m_context); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + UnregisterClipboardCallbacks(); + if (m_textInputActive) { - CollectFontFiles(iconDirectory, iconFonts, seen, includeSubdirectories: false); + SDLWindow* textInputWindow = m_textInputWindow is null ? m_window.GetSdlWindow() : m_textInputWindow; + _ = SDL.Raw.StopTextInput(textInputWindow); + m_textInputWindow = null; + m_textInputActive = false; } - baseFonts.Sort(StringComparer.OrdinalIgnoreCase); - iconFonts.Sort(StringComparer.OrdinalIgnoreCase); - } - - private static List ResolveAssetDirectories(string relativePath) - { - var directories = new List(); - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var candidates = new[] - { - Path.Combine(AppContext.BaseDirectory, relativePath), - Path.Combine(Path.GetDirectoryName(typeof(PlatformImGuiContext).Assembly.Location) ?? string.Empty, relativePath) - }; + _ = SDL.CaptureMouse(false); + m_mouseButtonsDown = 0; + m_mouseWindowID = 0; + m_mousePendingLeaveFrame = 0; + m_pendingLiveResizeWindowIDs.Clear(); - foreach (var candidate in candidates) + if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0) { - if (string.IsNullOrWhiteSpace(candidate)) - { - continue; - } - - var fullPath = Path.GetFullPath(candidate); - if (Directory.Exists(fullPath) && seen.Add(fullPath)) - { - directories.Add(fullPath); - } + ImGuiNative.DestroyPlatformWindows(); } - return directories; - } + m_viewports?.Dispose(); + m_renderer.DrainViewportRetirements(); - private static void CollectFontFiles( - string directory, - List output, - HashSet seen, - bool includeSubdirectories - ) { - var searchOption = includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - var fontFiles = Directory.GetFiles(directory, "*.*", searchOption); - foreach (var fontFile in fontFiles) + foreach (nint cursor in m_cursors.Values) { - var extension = Path.GetExtension(fontFile); - if (!extension.Equals(".ttf", StringComparison.OrdinalIgnoreCase) - && !extension.Equals(".otf", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - var fullPath = Path.GetFullPath(fontFile); - if (seen.Add(fullPath)) + if (cursor != 0) { - output.Add(fullPath); + SDL.Raw.DestroyCursor((SDLCursor*)cursor); } } - } - - private static unsafe void MergeIconFontsIntoCurrentBaseFont( - ImFontAtlas* fonts, - List iconFontPaths - ) { - if (iconFontPaths.Count == 0) - { - return; - } - for (var index = 0; index < iconFontPaths.Count; index++) + m_cursors.Clear(); + m_renderer.Dispose(); + ImGuiFont.UnregisterContext(m_context); + ImGuiNative.Raw.DestroyContext(m_context); + if (m_iniFilename != nint.Zero) { - ImFontConfig* mergeConfig = ImGuiNative.Raw.ImFontConfig(); - mergeConfig->MergeMode = 1; - mergeConfig->PixelSnapH = 1; - try - { - _ = LoadFont(fonts, iconFontPaths[index], DEFAULT_ICON_SIZE_PIXELS, mergeConfig); - } - finally - { - ImGuiNative.Raw.Destroy(mergeConfig); - } + Marshal.FreeCoTaskMem(m_iniFilename); + m_iniFilename = nint.Zero; } + m_disposed = true; + Action? releaseRegistration = m_releaseRegistration; + m_releaseRegistration = null; + releaseRegistration?.Invoke(this); } internal void ProcessEvent(ref SDLEvent sdlEvent) @@ -505,31 +472,33 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) } ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); - var eventType = (SDLEventType)sdlEvent.Type; + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + SDLEventType eventType = (SDLEventType)sdlEvent.Type; - if (!TryGetWindowId(ref sdlEvent, out var eventWindowId)) + if (!TryGetWindowID(ref sdlEvent, out uint eventWindowID)) { m_viewports?.ProcessEvent(ref sdlEvent, 0); return; } - if (eventWindowId != m_window.windowId && (m_viewports == null || !m_viewports.OwnsWindow(eventWindowId))) + if (eventWindowID != m_window.windowID && (m_viewports is null || !m_viewports.OwnsWindow(eventWindowID))) { return; } if (m_enableSmoothResize) - RefreshLiveResizeHoverLock(eventType, eventWindowId, ref sdlEvent); + { + RefreshLiveResizeHoverLock(eventType, eventWindowID, ref sdlEvent); + } - m_viewports?.ProcessEvent(ref sdlEvent, eventWindowId); + m_viewports?.ProcessEvent(ref sdlEvent, eventWindowID); switch (eventType) { case SDLEventType.KeyDown: case SDLEventType.KeyUp: { - var down = eventType == SDLEventType.KeyDown; + bool down = eventType == SDLEventType.KeyDown; if (down && sdlEvent.Key.Repeat != 0) { // Keep key-repeat timing driven by ImGui (io->KeyRepeatDelay/KeyRepeatRate). @@ -538,32 +507,36 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) UpdateKeyModifiers(io, (SDLKeymod)sdlEvent.Key.Mod); - var key = TranslateKey(sdlEvent.Key.Scancode); + ImGuiKey key = TranslateKey(sdlEvent.Key.Scancode); if (key != ImGuiKey.None) { ImGuiNative.Raw.AddKeyEvent(io, key, down ? (byte)1 : (byte)0); - ImGuiNative.Raw.SetKeyEventNativeData(io, key, (int)sdlEvent.Key.Key, (int)sdlEvent.Key.Scancode, (int)sdlEvent.Key.Scancode); + ImGuiNative.Raw.SetKeyEventNativeData( + io, + key, + (int)sdlEvent.Key.Key, + (int)sdlEvent.Key.Scancode, + (int)sdlEvent.Key.Scancode + ); } break; } case SDLEventType.TextInput: { - if (sdlEvent.Text.Text != null) + if (sdlEvent.Text.Text is not null) + { ImGuiNative.Raw.AddInputCharactersUTF8(io, sdlEvent.Text.Text); + } break; } case SDLEventType.MouseMotion: { - m_mouseWindowId = eventWindowId; + m_mouseWindowID = eventWindowID; m_mousePendingLeaveFrame = 0; - m_mousePendingLeaveWindowId = 0; - Vector2 mousePosition = GetEventMousePosition( - io, - eventWindowId, - sdlEvent.Motion.X, - sdlEvent.Motion.Y); + m_mousePendingLeaveWindowID = 0; + Vector2 mousePosition = GetEventMousePosition(io, eventWindowID, sdlEvent.Motion.X, sdlEvent.Motion.Y); ImGuiNative.Raw.AddMousePosEvent(io, mousePosition.X, mousePosition.Y); break; } @@ -576,9 +549,13 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) { int mask = 1 << button; if (down) + { m_mouseButtonsDown |= mask; + } else + { m_mouseButtonsDown &= ~mask; + } ImGuiNative.Raw.AddMouseButtonEvent(io, button, down ? (byte)1 : (byte)0); // Docking can destroy the source viewport before SDL emits MouseUp. Capturing // the mouse keeps the complete press/release sequence inside this application. @@ -589,14 +566,16 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.MouseWheel: { - var wheelX = sdlEvent.Wheel.X; - var wheelY = sdlEvent.Wheel.Y; + float wheelX = sdlEvent.Wheel.X; + float wheelY = sdlEvent.Wheel.Y; wheelX *= m_interaction.horizontalWheelDirection; - ImGuiNative.Raw.AddMouseWheelEvent(io, - wheelX * DEFAULT_MOUSE_SCROLLING_UNITS, - wheelY * DEFAULT_MOUSE_SCROLLING_UNITS); + ImGuiNative.Raw.AddMouseWheelEvent( + io, + wheelX * C_DEFAULT_MOUSE_SCROLLING_UNITS, + wheelY * C_DEFAULT_MOUSE_SCROLLING_UNITS + ); break; } @@ -609,18 +588,18 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) break; case SDLEventType.WindowMouseEnter: - m_mouseWindowId = eventWindowId; + m_mouseWindowID = eventWindowID; m_mousePendingLeaveFrame = 0; - m_mousePendingLeaveWindowId = 0; + m_mousePendingLeaveWindowID = 0; break; case SDLEventType.WindowMouseLeave: // SDL may deliver Leave before Enter while crossing viewport windows. Defer the // reset so a matching Enter or Motion event can cancel it without breaking drag. - if (m_mouseWindowId == eventWindowId) + if (m_mouseWindowID == eventWindowID) { m_mousePendingLeaveFrame = ImGuiNative.GetFrameCount() + 1; - m_mousePendingLeaveWindowId = eventWindowId; + m_mousePendingLeaveWindowID = eventWindowID; } break; @@ -628,7 +607,7 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.WindowDisplayScaleChanged: case SDLEventType.WindowResized: case SDLEventType.WindowPixelSizeChanged: - m_viewports?.SynchronizeWindow(eventWindowId); + m_viewports?.SynchronizeWindow(eventWindowID); UpdateDisplayMetrics(io); break; @@ -638,82 +617,32 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) } } - internal void PrepareLiveResizeWindow(uint windowId) + internal void PrepareLiveResizeWindow(uint windowID) { if (m_disposed || !m_enableSmoothResize) { return; } - var ownsMainWindow = windowId == m_window.windowId; - var ownsViewportWindow = m_viewports?.OwnsWindow(windowId) == true; + bool ownsMainWindow = windowID == m_window.windowID; + bool ownsViewportWindow = m_viewports?.OwnsWindow(windowID) == true; if (!ownsMainWindow && !ownsViewportWindow) { return; } - m_pendingLiveResizeWindowIds.Add(windowId); - var now = m_frameTimer.Elapsed; - m_liveResizeLockedWindowId = windowId; + m_pendingLiveResizeWindowIDs.Add(windowID); + TimeSpan now = m_frameTimer.Elapsed; + m_liveResizeLockedWindowID = windowID; m_lastLiveResizeLockTime = now; } - /// - /// Records frame rendering for the current frame. - /// - /// - /// The callback invoked by render frame within the operation's owned lifetime. - /// - /// - /// Optional callback invoked with the owned context before native frame creation. - /// - /// - /// Borrowed native draw data for the completed frame, valid until the next frame or retirement. - /// - public partial IntPtr RenderFrame( - Action drawFrame, - Action? prepareFrame - ) { - ArgumentNullException.ThrowIfNull(drawFrame); - ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_isFrameOperationActive || m_isFrameActive) - throw new InvalidOperationException("An ImGui frame cannot be reentered."); - - var now = m_frameTimer.Elapsed; - var deltaSeconds = (float)(now - m_lastFrameTime).TotalSeconds; - m_lastFrameTime = now; - - m_isFrameOperationActive = true; - try + private void AbortNativeFrame() + { + if (m_disposed || m_context->WithinFrameScope == 0) { - SynchronizePendingLiveResizeWindows(); - BeginFrame(deltaSeconds, prepareFrame); - drawFrame(); - return EndFrame(); - } - catch (Exception failure) - { - try - { - AbortNativeFrame(); - } - catch (Exception cleanupFailure) - { - throw new AggregateException("Presentation failed and its native frame could not retire.", failure, cleanupFailure); - } - throw; - } - finally - { - m_isFrameActive = false; - m_isFrameOperationActive = false; - } - } - - private void AbortNativeFrame() - { - if (m_disposed || m_context->WithinFrameScope == 0) return; + } ImGuiNativeContext* previous = ImGuiNative.Raw.GetCurrentContext(); ImGuiNative.Raw.SetCurrentContext(m_context); try @@ -723,7 +652,9 @@ private void AbortNativeFrame() finally { if (previous != m_context) + { ImGuiNative.Raw.SetCurrentContext(previous); + } } } @@ -731,16 +662,13 @@ private void BeginFrame( float deltaTimeSeconds, Action? prepareFrame ) { - if (m_disposed) - { - throw new ObjectDisposedException(nameof(PlatformImGuiContext)); - } + ObjectDisposedException.ThrowIf(m_disposed, this); ImGuiNative.Raw.SetCurrentContext(m_context); m_viewports?.ProcessRetirements(); m_hasStartedFrame = true; - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); io->MouseDrawCursor = 0; UpdateDisplayMetrics(io); io->DeltaTime = deltaTimeSeconds > 0f ? deltaTimeSeconds : (1f / 60f); @@ -756,23 +684,20 @@ private void BeginFrame( ImGuiNative.NewFrame(); // During live resize, prevent the main viewport from hosting other windows. - var mainViewport = ImGuiNative.Raw.GetMainViewport(); - if (m_liveResizeLockedWindowId != 0 + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); + if (m_liveResizeLockedWindowID != 0 && (io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0 - && mainViewport != null) - { + && mainViewport is not null + ) { mainViewport->Flags &= ~(int)ImGuiViewportFlags.CanHostOtherWindows; } } - private IntPtr EndFrame() + private nint EndFrame() { - if (m_disposed) - { - throw new ObjectDisposedException(nameof(PlatformImGuiContext)); - } + ObjectDisposedException.ThrowIf(m_disposed, this); - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); try { @@ -782,7 +707,7 @@ private IntPtr EndFrame() ImGuiNative.Render(); io->MouseDrawCursor = 0; - var drawData = ImGuiNative.Raw.GetDrawData(); + ImDrawData* drawData = ImGuiNative.Raw.GetDrawData(); m_renderer.RenderMain(GetDrawDataAddress(drawData)); if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0) { @@ -801,126 +726,58 @@ private IntPtr EndFrame() private void RefreshLiveResizeHoverLock( SDLEventType eventType, - uint eventWindowId, + uint eventWindowID, ref SDLEvent sdlEvent ) { - if (m_liveResizeLockedWindowId == 0) + if (m_liveResizeLockedWindowID == 0) { return; } float mouseX = 0f; float mouseY = 0f; - var mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); + SDLMouseButtonFlags mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); if ((mouseButtons & SDLMouseButtonFlags.Left) == 0) { - m_liveResizeLockedWindowId = 0; + m_liveResizeLockedWindowID = 0; return; } - var now = m_frameTimer.Elapsed; - if (eventType == SDLEventType.WindowExposed && eventWindowId == m_liveResizeLockedWindowId) + TimeSpan now = m_frameTimer.Elapsed; + if (eventType == SDLEventType.WindowExposed && eventWindowID == m_liveResizeLockedWindowID) { m_lastLiveResizeLockTime = now; } - if ((now - m_lastLiveResizeLockTime).TotalSeconds > LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS) + if ((now - m_lastLiveResizeLockTime).TotalSeconds > C_LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS) { - m_liveResizeLockedWindowId = 0; + m_liveResizeLockedWindowID = 0; return; } if (eventType == SDLEventType.WindowExposed - && eventWindowId == m_liveResizeLockedWindowId - && sdlEvent.Window.Data1 == 0) - { - m_liveResizeLockedWindowId = 0; + && eventWindowID == m_liveResizeLockedWindowID + && sdlEvent.Window.Data1 == 0 + ) { + m_liveResizeLockedWindowID = 0; return; } if (eventType == SDLEventType.MouseButtonUp && sdlEvent.Button.Button == SDL.Constants.SDL_BUTTON_LEFT) { - m_liveResizeLockedWindowId = 0; - } - } - - /// - /// Retires the context and its owned resources after the current frame operation has completed. - /// - /// - /// Successful retirement removes this context's application registration and releases its borrowed font data. - /// Pending or failed retirement preserves both registration and ownership for a subsequent retry. - /// - /// - /// A frame operation still owns the context; the caller must retry after that operation completes. - /// - public partial void Dispose() - { - if (m_disposed) - { - return; - } - - if (m_isFrameOperationActive) - throw new InvalidOperationException("A presentation context cannot retire during its frame operation."); - - ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); - UnregisterClipboardCallbacks(); - if (m_textInputActive) - { - var textInputWindow = m_textInputWindow == null ? m_window.GetSdlWindow() : m_textInputWindow; - _ = SDL.Raw.StopTextInput(textInputWindow); - m_textInputWindow = null; - m_textInputActive = false; - } - - _ = SDL.CaptureMouse(false); - m_mouseButtonsDown = 0; - m_mouseWindowId = 0; - m_mousePendingLeaveFrame = 0; - m_pendingLiveResizeWindowIds.Clear(); - - if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0) - { - ImGuiNative.DestroyPlatformWindows(); - } - - m_viewports?.Dispose(); - m_renderer.DrainViewportRetirements(); - - foreach (var cursor in m_cursors.Values) - { - if (cursor != 0) - { - SDL.Raw.DestroyCursor((SDLCursor*)cursor); - } - } - - m_cursors.Clear(); - m_renderer.Dispose(); - ImGuiFont.UnregisterContext(m_context); - ImGuiNative.Raw.DestroyContext(m_context); - if (m_iniFilename != IntPtr.Zero) - { - Marshal.FreeCoTaskMem(m_iniFilename); - m_iniFilename = IntPtr.Zero; + m_liveResizeLockedWindowID = 0; } - m_disposed = true; - Action? releaseRegistration = m_releaseRegistration; - m_releaseRegistration = null; - releaseRegistration?.Invoke(this); } private void UpdateDisplayMetrics(ImGuiIO* io) { - var windowWidth = 0; - var windowHeight = 0; + int windowWidth = 0; + int windowHeight = 0; SDLWindow* sdlWindow = m_window.GetSdlWindow(); SDL.Raw.GetWindowSize(sdlWindow, &windowWidth, &windowHeight); - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; SDL.Raw.GetWindowSizeInPixels(sdlWindow, &pixelWidth, &pixelHeight); io->DisplaySize = new ImVec2C { X = windowWidth, Y = windowHeight }; @@ -941,12 +798,12 @@ private void UpdateDisplayMetrics(ImGuiIO* io) private void UpdateTextInputState(ImGuiIO* io) { - var targetWindow = ResolveTextInputWindow(); + SDLWindow* targetWindow = ResolveTextInputWindow(); if (io->WantTextInput != 0) { if (!m_textInputActive || m_textInputWindow != targetWindow) { - if (m_textInputActive && m_textInputWindow != null) + if (m_textInputActive && m_textInputWindow is not null) { _ = SDL.Raw.StopTextInput(m_textInputWindow); } @@ -958,48 +815,23 @@ private void UpdateTextInputState(ImGuiIO* io) } else if (m_textInputActive) { - var textInputWindow = m_textInputWindow == null ? targetWindow : m_textInputWindow; + SDLWindow* textInputWindow = m_textInputWindow is null ? targetWindow : m_textInputWindow; _ = SDL.Raw.StopTextInput(textInputWindow); m_textInputWindow = null; m_textInputActive = false; } } - private static unsafe void SetIniFilename( - ImGuiIO* io, - IntPtr fileName - ) { - io->IniFilename = (sbyte*)fileName; - } - - private static unsafe ImFont* LoadFont( - ImFontAtlas* fonts, - string filePath, - float fontSizePixels, - ImFontConfig* config = null - ) { - int length = Encoding.UTF8.GetByteCount(filePath); - Span encoded = length < 1024 ? stackalloc byte[1024] : new byte[checked(length + 1)]; - Encoding.UTF8.GetBytes(filePath, encoded); - encoded[length] = 0; - fixed (byte* filename = encoded) - return ImGuiNative.Raw.AddFontFromFileTTF(fonts, (sbyte*)filename, fontSizePixels, config, null); - } - - private static unsafe ImFont* LoadDefaultFont(ImFontAtlas* fonts) => ImGuiNative.Raw.AddFontDefault(fonts, null); - - private static unsafe IntPtr GetDrawDataAddress(ImDrawData* drawData) => (nint)drawData; - private SDLWindow* ResolveTextInputWindow() { - var keyboardFocus = SDL.Raw.GetKeyboardFocus(); - if (keyboardFocus == null) + SDLWindow* keyboardFocus = SDL.Raw.GetKeyboardFocus(); + if (keyboardFocus is null) { return m_window.GetSdlWindow(); } - var focusedWindowId = SDL.Raw.GetWindowId(keyboardFocus); - if (focusedWindowId == m_window.windowId || (m_viewports != null && m_viewports.OwnsWindow(focusedWindowId))) + uint focusedWindowID = SDL.Raw.GetWindowId(keyboardFocus); + if (focusedWindowID == m_window.windowID || (m_viewports is not null && m_viewports.OwnsWindow(focusedWindowID))) { return keyboardFocus; } @@ -1007,30 +839,18 @@ IntPtr fileName return m_window.GetSdlWindow(); } - private static void UpdateMouseData( - ImGuiIO* io, - SDLWindow* window - ) { - // Mouse position is fed from SDL mouse events (per-window coordinates). - // Polling here would overwrite secondary viewport coordinates with the wrong window space. - if (io->WantSetMousePos != 0) - { - SDL.Raw.WarpMouseInWindow(window, io->MousePos.X, io->MousePos.Y); - } - } - private void SynchronizePendingLiveResizeWindows() { - if (m_pendingLiveResizeWindowIds.Count == 0) + if (m_pendingLiveResizeWindowIDs.Count == 0) { return; } - uint[] windowIds = [.. m_pendingLiveResizeWindowIds]; - m_pendingLiveResizeWindowIds.Clear(); - foreach (uint windowId in windowIds) + uint[] windowIDs = [.. m_pendingLiveResizeWindowIDs]; + m_pendingLiveResizeWindowIDs.Clear(); + foreach (uint windowID in windowIDs) { - if (windowId == m_window.windowId) + if (windowID == m_window.windowID) { int pixelWidth = 0; int pixelHeight = 0; @@ -1038,14 +858,18 @@ private void SynchronizePendingLiveResizeWindows() m_renderer.SynchronizeMainOutput(pixelWidth, pixelHeight); } else - m_viewports?.SynchronizeWindow(windowId); + { + m_viewports?.SynchronizeWindow(windowID); + } } } private void ReconcileMouseButtons(ImGuiIO* io) { if (m_mouseButtonsDown == 0) + { return; + } float mouseX = 0f; float mouseY = 0f; @@ -1062,11 +886,15 @@ private void ReconcileMouseButtons(ImGuiIO* io) { int trackedMask = 1 << button; if ((m_mouseButtonsDown & trackedMask) == 0) + { continue; + } SDLMouseButtonFlags sdlMask = (SDLMouseButtonFlags)(1u << (sdlButtons[button] - 1)); if ((currentButtons & sdlMask) != 0) + { continue; + } // Recover when a destroyed viewport prevented the corresponding MouseUp event from // reaching the event queue. Without this release ImGui keeps its active drag forever. @@ -1075,57 +903,35 @@ private void ReconcileMouseButtons(ImGuiIO* io) } if (m_mouseButtonsDown == 0) - _ = SDL.CaptureMouse(false); - } - - private static Vector2 GetEventMousePosition( - ImGuiIO* io, - uint windowId, - float localX, - float localY - ) { - Vector2 position = new(localX, localY); - if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) == 0) - { - return position; - } - - SDLWindow* window = SDL.Raw.GetWindowFromId(windowId); - if (window == null) { - return position; + _ = SDL.CaptureMouse(false); } - - var windowX = 0; - var windowY = 0; - _ = SDL.Raw.GetWindowPosition(window, &windowX, &windowY); - return position + new Vector2(windowX, windowY); } private void FlushPendingMouseLeave(ImGuiIO* io) { if (!ShouldFlushPendingMouseLeave( - m_mousePendingLeaveFrame, - ImGuiNative.GetFrameCount(), - m_mouseButtonsDown, - m_mousePendingLeaveWindowId, - m_liveResizeLockedWindowId)) - { + m_mousePendingLeaveFrame, + ImGuiNative.GetFrameCount(), + m_mouseButtonsDown, + m_mousePendingLeaveWindowID, + m_liveResizeLockedWindowID + )) { return; } - m_mouseWindowId = 0; + m_mouseWindowID = 0; m_mousePendingLeaveFrame = 0; - m_mousePendingLeaveWindowId = 0; + m_mousePendingLeaveWindowID = 0; ImGuiNative.Raw.AddMousePosEvent(io, -float.MaxValue, -float.MaxValue); } private void ReleaseCompletedLiveResizeHoverLock() { - if (m_liveResizeLockedWindowId == 0 || - (m_frameTimer.Elapsed - m_lastLiveResizeLockTime).TotalSeconds <= - LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS) - { + if (m_liveResizeLockedWindowID == 0 + || (m_frameTimer.Elapsed - m_lastLiveResizeLockTime).TotalSeconds + <= C_LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS + ) { return; } @@ -1133,20 +939,9 @@ private void ReleaseCompletedLiveResizeHoverLock() float mouseY = 0f; SDLMouseButtonFlags mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); if ((mouseButtons & SDLMouseButtonFlags.Left) == 0) - m_liveResizeLockedWindowId = 0; - } - - private static bool ShouldFlushPendingMouseLeave( - int pendingFrame, - int currentFrame, - int mouseButtonsDown, - uint pendingWindowId, - uint liveResizeLockedWindowId - ) { - if (pendingFrame == 0 || mouseButtonsDown != 0 || currentFrame < pendingFrame) - return false; - - return liveResizeLockedWindowId == 0 || pendingWindowId != liveResizeLockedWindowId; + { + m_liveResizeLockedWindowID = 0; + } } private void UpdateMouseCursor(ImGuiIO* io) @@ -1156,7 +951,7 @@ private void UpdateMouseCursor(ImGuiIO* io) return; } - var imguiCursor = (ImGuiMouseCursor)ImGuiNative.GetMouseCursor(); + ImGuiMouseCursor imguiCursor = (ImGuiMouseCursor)ImGuiNative.GetMouseCursor(); if (imguiCursor == ImGuiMouseCursor.None || io->MouseDrawCursor != 0) { _ = SDL.HideCursor(); @@ -1164,8 +959,8 @@ private void UpdateMouseCursor(ImGuiIO* io) return; } - var sdlCursor = GetOrCreateCursor(imguiCursor); - if (sdlCursor != null && m_currentCursor != imguiCursor) + SDLCursor* sdlCursor = GetOrCreateCursor(imguiCursor); + if (sdlCursor is not null && m_currentCursor != imguiCursor) { _ = SDL.Raw.SetCursor(sdlCursor); m_currentCursor = imguiCursor; @@ -1176,12 +971,12 @@ private void UpdateMouseCursor(ImGuiIO* io) private SDLCursor* GetOrCreateCursor(ImGuiMouseCursor cursor) { - if (m_cursors.TryGetValue(cursor, out var cachedCursor)) + if (m_cursors.TryGetValue(cursor, out nint cachedCursor)) { return (SDLCursor*)cachedCursor; } - var sdlCursorType = cursor switch + SDLSystemCursor sdlCursorType = cursor switch { ImGuiMouseCursor.Arrow => SDLSystemCursor.Default, ImGuiMouseCursor.TextInput => SDLSystemCursor.Text, @@ -1197,11 +992,268 @@ private void UpdateMouseCursor(ImGuiIO* io) _ => SDLSystemCursor.Default }; - var createdCursor = SDL.Raw.CreateSystemCursor(sdlCursorType); + SDLCursor* createdCursor = SDL.Raw.CreateSystemCursor(sdlCursorType); m_cursors[cursor] = (nint)createdCursor; return createdCursor; } + private static void ConfigureKeyRepeat(ImGuiIO* io) + { + io->KeyRepeatDelay = C_DEFAULT_KEY_REPEAT_DELAY_SECONDS; + io->KeyRepeatRate = C_DEFAULT_KEY_REPEAT_RATE_SECONDS; + } + + private static void ConfigureFonts( + ImGuiNativeContext* context, + ImGuiIO* io + ) { + ImFontAtlas* fonts = io->Fonts; + ImGuiNative.Raw.Clear(fonts); + + ResolveFontPaths(out List fontPaths, out List iconFontPaths); + var styleFonts = new Dictionary(); + ImFont* defaultFont = null; + int preferredIndex = FindPreferredFontIndex(fontPaths); + for (int i = 0; i < fontPaths.Count; i++) + { + ImFont* loadedFont = LoadFont(fonts, fontPaths[i], C_DEFAULT_FONT_SIZE_PIXELS); + if (loadedFont is null) + { + continue; + } + + MergeIconFontsIntoCurrentBaseFont(fonts, iconFontPaths); + styleFonts[GetFontStyle(fontPaths[i])] = (nint)loadedFont; + if (i == preferredIndex) + { + defaultFont = loadedFont; + } + else if (defaultFont is null) + { + defaultFont = loadedFont; + } + } + + if (defaultFont is null) + { + defaultFont = LoadDefaultFont(fonts); + if (defaultFont is not null) + { + MergeIconFontsIntoCurrentBaseFont(fonts, iconFontPaths); + } + } + + io->FontDefault = defaultFont; + if (defaultFont is not null && !styleFonts.ContainsKey(ImGuiFontStyle.Regular)) + { + styleFonts[ImGuiFontStyle.Regular] = (nint)defaultFont; + } + ImGuiFont.RegisterContext(context, styleFonts); + } + + private static ImGuiFontStyle GetFontStyle(string fontPath) + { + string name = Path.GetFileNameWithoutExtension(fontPath); + bool bold = name.Contains("Bold", StringComparison.OrdinalIgnoreCase); + bool italic = name.Contains("Italic", StringComparison.OrdinalIgnoreCase); + return (bold ? ImGuiFontStyle.Bold : ImGuiFontStyle.Regular) + | (italic ? ImGuiFontStyle.Italic : ImGuiFontStyle.Regular); + } + + private static int FindPreferredFontIndex(List fontPaths) + { + if (fontPaths.Count == 0 || string.IsNullOrWhiteSpace(C_DEFAULT_FONT_FILE_NAME)) + { + return -1; + } + + for (int i = 0; i < fontPaths.Count; i++) + { + string fileName = Path.GetFileName(fontPaths[i]); + if (fileName.Equals(C_DEFAULT_FONT_FILE_NAME, StringComparison.OrdinalIgnoreCase)) + { + return i; + } + } + + return -1; + } + + private static void ResolveFontPaths( + out List baseFonts, + out List iconFonts + ) { + baseFonts = []; + iconFonts = []; + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (string fontDirectory in ResolveAssetDirectories(C_DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH)) + { + CollectFontFiles(fontDirectory, baseFonts, seen, includeSubdirectories: false); + } + + foreach (string iconDirectory in ResolveAssetDirectories(C_DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH)) + { + CollectFontFiles(iconDirectory, iconFonts, seen, includeSubdirectories: false); + } + + baseFonts.Sort(StringComparer.OrdinalIgnoreCase); + iconFonts.Sort(StringComparer.OrdinalIgnoreCase); + } + + private static List ResolveAssetDirectories(string relativePath) + { + List directories = []; + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + string[] candidates = + [ + Path.Combine(AppContext.BaseDirectory, relativePath), + Path.Combine(Path.GetDirectoryName(typeof(PlatformImGuiContext).Assembly.Location) ?? string.Empty, relativePath) + ]; + + foreach (string candidate in candidates) + { + if (string.IsNullOrWhiteSpace(candidate)) + { + continue; + } + + string fullPath = Path.GetFullPath(candidate); + if (Directory.Exists(fullPath) && seen.Add(fullPath)) + { + directories.Add(fullPath); + } + } + + return directories; + } + + private static void CollectFontFiles( + string directory, + List output, + HashSet seen, + bool includeSubdirectories + ) { + SearchOption searchOption = includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + string[] fontFiles = Directory.GetFiles(directory, "*.*", searchOption); + foreach (string fontFile in fontFiles) + { + string extension = Path.GetExtension(fontFile); + if (!extension.Equals(".ttf", StringComparison.OrdinalIgnoreCase) + && !extension.Equals(".otf", StringComparison.OrdinalIgnoreCase) + ) { + continue; + } + + string fullPath = Path.GetFullPath(fontFile); + if (seen.Add(fullPath)) + { + output.Add(fullPath); + } + } + } + + private static unsafe void MergeIconFontsIntoCurrentBaseFont( + ImFontAtlas* fonts, + List iconFontPaths + ) { + if (iconFontPaths.Count == 0) + { + return; + } + + for (int index = 0; index < iconFontPaths.Count; index++) + { + ImFontConfig* mergeConfig = ImGuiNative.Raw.ImFontConfig(); + mergeConfig->MergeMode = 1; + mergeConfig->PixelSnapH = 1; + try + { + _ = LoadFont(fonts, iconFontPaths[index], C_DEFAULT_ICON_SIZE_PIXELS, mergeConfig); + } + finally + { + ImGuiNative.Raw.Destroy(mergeConfig); + } + } + } + + private static unsafe void SetIniFilename( + ImGuiIO* io, + nint fileName + ) => io->IniFilename = (sbyte*)fileName; + + private static unsafe ImFont* LoadFont( + ImFontAtlas* fonts, + string filePath, + float fontSizePixels, + ImFontConfig* config = null + ) { + int length = Encoding.UTF8.GetByteCount(filePath); + Span encoded = length < 1024 ? stackalloc byte[1024] : new byte[checked(length + 1)]; + Encoding.UTF8.GetBytes(filePath, encoded); + encoded[length] = 0; + fixed (byte* filename = encoded) + { + return ImGuiNative.Raw.AddFontFromFileTTF(fonts, (sbyte*)filename, fontSizePixels, config, null); + } + } + + private static unsafe ImFont* LoadDefaultFont(ImFontAtlas* fonts) => ImGuiNative.Raw.AddFontDefault(fonts, null); + + private static unsafe nint GetDrawDataAddress(ImDrawData* drawData) => (nint)drawData; + + private static void UpdateMouseData( + ImGuiIO* io, + SDLWindow* window + ) { + // Mouse position is fed from SDL mouse events (per-window coordinates). + // Polling here would overwrite secondary viewport coordinates with the wrong window space. + if (io->WantSetMousePos != 0) + { + SDL.Raw.WarpMouseInWindow(window, io->MousePos.X, io->MousePos.Y); + } + } + + private static Vector2 GetEventMousePosition( + ImGuiIO* io, + uint windowID, + float localX, + float localY + ) { + var position = new Vector2(localX, localY); + if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) == 0) + { + return position; + } + + SDLWindow* window = SDL.Raw.GetWindowFromId(windowID); + if (window is null) + { + return position; + } + + int windowX = 0; + int windowY = 0; + _ = SDL.Raw.GetWindowPosition(window, &windowX, &windowY); + return position + new Vector2(windowX, windowY); + } + + private static bool ShouldFlushPendingMouseLeave( + int pendingFrame, + int currentFrame, + int mouseButtonsDown, + uint pendingWindowID, + uint liveResizeLockedWindowID + ) { + if (pendingFrame == 0 || mouseButtonsDown != 0 || currentFrame < pendingFrame) + { + return false; + } + + return liveResizeLockedWindowID == 0 || pendingWindowID != liveResizeLockedWindowID; + } + private static bool TryTranslateMouseButton( byte sdlButton, out int imguiButton @@ -1240,145 +1292,143 @@ SDLKeymod modifiers } private static ImGuiKey TranslateKey(SDLScancode scancode) + => scancode switch { - return scancode switch - { - SDLScancode.Tab => ImGuiKey.Tab, - SDLScancode.Left => ImGuiKey.LeftArrow, - SDLScancode.Right => ImGuiKey.RightArrow, - SDLScancode.Up => ImGuiKey.UpArrow, - SDLScancode.Down => ImGuiKey.DownArrow, - SDLScancode.Pageup => ImGuiKey.PageUp, - SDLScancode.Pagedown => ImGuiKey.PageDown, - SDLScancode.Home => ImGuiKey.Home, - SDLScancode.End => ImGuiKey.End, - SDLScancode.Insert => ImGuiKey.Insert, - SDLScancode.Delete => ImGuiKey.Delete, - SDLScancode.Backspace => ImGuiKey.Backspace, - SDLScancode.Space => ImGuiKey.Space, - SDLScancode.Return => ImGuiKey.Enter, - SDLScancode.Escape => ImGuiKey.Escape, - SDLScancode.Apostrophe => ImGuiKey.Apostrophe, - SDLScancode.Comma => ImGuiKey.Comma, - SDLScancode.Minus => ImGuiKey.Minus, - SDLScancode.Period => ImGuiKey.Period, - SDLScancode.Slash => ImGuiKey.Slash, - SDLScancode.Semicolon => ImGuiKey.Semicolon, - SDLScancode.Equals => ImGuiKey.Equal, - SDLScancode.Leftbracket => ImGuiKey.LeftBracket, - SDLScancode.Backslash => ImGuiKey.Backslash, - SDLScancode.Rightbracket => ImGuiKey.RightBracket, - SDLScancode.Grave => ImGuiKey.GraveAccent, - SDLScancode.Capslock => ImGuiKey.CapsLock, - SDLScancode.Scrolllock => ImGuiKey.ScrollLock, - SDLScancode.Numlockclear => ImGuiKey.NumLock, - SDLScancode.Printscreen => ImGuiKey.PrintScreen, - SDLScancode.Pause => ImGuiKey.Pause, - SDLScancode.Kp0 => ImGuiKey.Keypad0, - SDLScancode.Kp1 => ImGuiKey.Keypad1, - SDLScancode.Kp2 => ImGuiKey.Keypad2, - SDLScancode.Kp3 => ImGuiKey.Keypad3, - SDLScancode.Kp4 => ImGuiKey.Keypad4, - SDLScancode.Kp5 => ImGuiKey.Keypad5, - SDLScancode.Kp6 => ImGuiKey.Keypad6, - SDLScancode.Kp7 => ImGuiKey.Keypad7, - SDLScancode.Kp8 => ImGuiKey.Keypad8, - SDLScancode.Kp9 => ImGuiKey.Keypad9, - SDLScancode.KpPeriod => ImGuiKey.KeypadDecimal, - SDLScancode.KpDivide => ImGuiKey.KeypadDivide, - SDLScancode.KpMultiply => ImGuiKey.KeypadMultiply, - SDLScancode.KpMinus => ImGuiKey.KeypadSubtract, - SDLScancode.KpPlus => ImGuiKey.KeypadAdd, - SDLScancode.KpEnter => ImGuiKey.KeypadEnter, - SDLScancode.KpEquals => ImGuiKey.KeypadEqual, - SDLScancode.Lctrl => ImGuiKey.LeftCtrl, - SDLScancode.Lshift => ImGuiKey.LeftShift, - SDLScancode.Lalt => ImGuiKey.LeftAlt, - SDLScancode.Lgui => ImGuiKey.LeftSuper, - SDLScancode.Rctrl => ImGuiKey.RightCtrl, - SDLScancode.Rshift => ImGuiKey.RightShift, - SDLScancode.Ralt => ImGuiKey.RightAlt, - SDLScancode.Rgui => ImGuiKey.RightSuper, - SDLScancode.Menu => ImGuiKey.Menu, - SDLScancode._0 => ImGuiKey._0, - SDLScancode._1 => ImGuiKey._1, - SDLScancode._2 => ImGuiKey._2, - SDLScancode._3 => ImGuiKey._3, - SDLScancode._4 => ImGuiKey._4, - SDLScancode._5 => ImGuiKey._5, - SDLScancode._6 => ImGuiKey._6, - SDLScancode._7 => ImGuiKey._7, - SDLScancode._8 => ImGuiKey._8, - SDLScancode._9 => ImGuiKey._9, - SDLScancode.A => ImGuiKey.A, - SDLScancode.B => ImGuiKey.B, - SDLScancode.C => ImGuiKey.C, - SDLScancode.D => ImGuiKey.D, - SDLScancode.E => ImGuiKey.E, - SDLScancode.F => ImGuiKey.F, - SDLScancode.G => ImGuiKey.G, - SDLScancode.H => ImGuiKey.H, - SDLScancode.I => ImGuiKey.I, - SDLScancode.J => ImGuiKey.J, - SDLScancode.K => ImGuiKey.K, - SDLScancode.L => ImGuiKey.L, - SDLScancode.M => ImGuiKey.M, - SDLScancode.N => ImGuiKey.N, - SDLScancode.O => ImGuiKey.O, - SDLScancode.P => ImGuiKey.P, - SDLScancode.Q => ImGuiKey.Q, - SDLScancode.R => ImGuiKey.R, - SDLScancode.S => ImGuiKey.S, - SDLScancode.T => ImGuiKey.T, - SDLScancode.U => ImGuiKey.U, - SDLScancode.V => ImGuiKey.V, - SDLScancode.W => ImGuiKey.W, - SDLScancode.X => ImGuiKey.X, - SDLScancode.Y => ImGuiKey.Y, - SDLScancode.Z => ImGuiKey.Z, - SDLScancode.F1 => ImGuiKey.F1, - SDLScancode.F2 => ImGuiKey.F2, - SDLScancode.F3 => ImGuiKey.F3, - SDLScancode.F4 => ImGuiKey.F4, - SDLScancode.F5 => ImGuiKey.F5, - SDLScancode.F6 => ImGuiKey.F6, - SDLScancode.F7 => ImGuiKey.F7, - SDLScancode.F8 => ImGuiKey.F8, - SDLScancode.F9 => ImGuiKey.F9, - SDLScancode.F10 => ImGuiKey.F10, - SDLScancode.F11 => ImGuiKey.F11, - SDLScancode.F12 => ImGuiKey.F12, - _ => ImGuiKey.None - }; - } - - private static bool TryGetWindowId( + SDLScancode.Tab => ImGuiKey.Tab, + SDLScancode.Left => ImGuiKey.LeftArrow, + SDLScancode.Right => ImGuiKey.RightArrow, + SDLScancode.Up => ImGuiKey.UpArrow, + SDLScancode.Down => ImGuiKey.DownArrow, + SDLScancode.Pageup => ImGuiKey.PageUp, + SDLScancode.Pagedown => ImGuiKey.PageDown, + SDLScancode.Home => ImGuiKey.Home, + SDLScancode.End => ImGuiKey.End, + SDLScancode.Insert => ImGuiKey.Insert, + SDLScancode.Delete => ImGuiKey.Delete, + SDLScancode.Backspace => ImGuiKey.Backspace, + SDLScancode.Space => ImGuiKey.Space, + SDLScancode.Return => ImGuiKey.Enter, + SDLScancode.Escape => ImGuiKey.Escape, + SDLScancode.Apostrophe => ImGuiKey.Apostrophe, + SDLScancode.Comma => ImGuiKey.Comma, + SDLScancode.Minus => ImGuiKey.Minus, + SDLScancode.Period => ImGuiKey.Period, + SDLScancode.Slash => ImGuiKey.Slash, + SDLScancode.Semicolon => ImGuiKey.Semicolon, + SDLScancode.Equals => ImGuiKey.Equal, + SDLScancode.Leftbracket => ImGuiKey.LeftBracket, + SDLScancode.Backslash => ImGuiKey.Backslash, + SDLScancode.Rightbracket => ImGuiKey.RightBracket, + SDLScancode.Grave => ImGuiKey.GraveAccent, + SDLScancode.Capslock => ImGuiKey.CapsLock, + SDLScancode.Scrolllock => ImGuiKey.ScrollLock, + SDLScancode.Numlockclear => ImGuiKey.NumLock, + SDLScancode.Printscreen => ImGuiKey.PrintScreen, + SDLScancode.Pause => ImGuiKey.Pause, + SDLScancode.Kp0 => ImGuiKey.Keypad0, + SDLScancode.Kp1 => ImGuiKey.Keypad1, + SDLScancode.Kp2 => ImGuiKey.Keypad2, + SDLScancode.Kp3 => ImGuiKey.Keypad3, + SDLScancode.Kp4 => ImGuiKey.Keypad4, + SDLScancode.Kp5 => ImGuiKey.Keypad5, + SDLScancode.Kp6 => ImGuiKey.Keypad6, + SDLScancode.Kp7 => ImGuiKey.Keypad7, + SDLScancode.Kp8 => ImGuiKey.Keypad8, + SDLScancode.Kp9 => ImGuiKey.Keypad9, + SDLScancode.KpPeriod => ImGuiKey.KeypadDecimal, + SDLScancode.KpDivide => ImGuiKey.KeypadDivide, + SDLScancode.KpMultiply => ImGuiKey.KeypadMultiply, + SDLScancode.KpMinus => ImGuiKey.KeypadSubtract, + SDLScancode.KpPlus => ImGuiKey.KeypadAdd, + SDLScancode.KpEnter => ImGuiKey.KeypadEnter, + SDLScancode.KpEquals => ImGuiKey.KeypadEqual, + SDLScancode.Lctrl => ImGuiKey.LeftCtrl, + SDLScancode.Lshift => ImGuiKey.LeftShift, + SDLScancode.Lalt => ImGuiKey.LeftAlt, + SDLScancode.Lgui => ImGuiKey.LeftSuper, + SDLScancode.Rctrl => ImGuiKey.RightCtrl, + SDLScancode.Rshift => ImGuiKey.RightShift, + SDLScancode.Ralt => ImGuiKey.RightAlt, + SDLScancode.Rgui => ImGuiKey.RightSuper, + SDLScancode.Menu => ImGuiKey.Menu, + SDLScancode._0 => ImGuiKey._0, + SDLScancode._1 => ImGuiKey._1, + SDLScancode._2 => ImGuiKey._2, + SDLScancode._3 => ImGuiKey._3, + SDLScancode._4 => ImGuiKey._4, + SDLScancode._5 => ImGuiKey._5, + SDLScancode._6 => ImGuiKey._6, + SDLScancode._7 => ImGuiKey._7, + SDLScancode._8 => ImGuiKey._8, + SDLScancode._9 => ImGuiKey._9, + SDLScancode.A => ImGuiKey.A, + SDLScancode.B => ImGuiKey.B, + SDLScancode.C => ImGuiKey.C, + SDLScancode.D => ImGuiKey.D, + SDLScancode.E => ImGuiKey.E, + SDLScancode.F => ImGuiKey.F, + SDLScancode.G => ImGuiKey.G, + SDLScancode.H => ImGuiKey.H, + SDLScancode.I => ImGuiKey.I, + SDLScancode.J => ImGuiKey.J, + SDLScancode.K => ImGuiKey.K, + SDLScancode.L => ImGuiKey.L, + SDLScancode.M => ImGuiKey.M, + SDLScancode.N => ImGuiKey.N, + SDLScancode.O => ImGuiKey.O, + SDLScancode.P => ImGuiKey.P, + SDLScancode.Q => ImGuiKey.Q, + SDLScancode.R => ImGuiKey.R, + SDLScancode.S => ImGuiKey.S, + SDLScancode.T => ImGuiKey.T, + SDLScancode.U => ImGuiKey.U, + SDLScancode.V => ImGuiKey.V, + SDLScancode.W => ImGuiKey.W, + SDLScancode.X => ImGuiKey.X, + SDLScancode.Y => ImGuiKey.Y, + SDLScancode.Z => ImGuiKey.Z, + SDLScancode.F1 => ImGuiKey.F1, + SDLScancode.F2 => ImGuiKey.F2, + SDLScancode.F3 => ImGuiKey.F3, + SDLScancode.F4 => ImGuiKey.F4, + SDLScancode.F5 => ImGuiKey.F5, + SDLScancode.F6 => ImGuiKey.F6, + SDLScancode.F7 => ImGuiKey.F7, + SDLScancode.F8 => ImGuiKey.F8, + SDLScancode.F9 => ImGuiKey.F9, + SDLScancode.F10 => ImGuiKey.F10, + SDLScancode.F11 => ImGuiKey.F11, + SDLScancode.F12 => ImGuiKey.F12, + _ => ImGuiKey.None + }; + + private static bool TryGetWindowID( ref SDLEvent sdlEvent, - out uint windowId + out uint windowID ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; switch (eventType) { case SDLEventType.KeyDown: case SDLEventType.KeyUp: - windowId = sdlEvent.Key.WindowID; + windowID = sdlEvent.Key.WindowID; return true; case SDLEventType.TextInput: - windowId = sdlEvent.Text.WindowID; + windowID = sdlEvent.Text.WindowID; return true; case SDLEventType.MouseMotion: - windowId = sdlEvent.Motion.WindowID; + windowID = sdlEvent.Motion.WindowID; return true; case SDLEventType.MouseButtonDown: case SDLEventType.MouseButtonUp: - windowId = sdlEvent.Button.WindowID; + windowID = sdlEvent.Button.WindowID; return true; case SDLEventType.MouseWheel: - windowId = sdlEvent.Wheel.WindowID; + windowID = sdlEvent.Wheel.WindowID; return true; case SDLEventType.WindowFocusGained: @@ -1392,13 +1442,12 @@ out uint windowId case SDLEventType.WindowResized: case SDLEventType.WindowPixelSizeChanged: case SDLEventType.WindowCloseRequested: - windowId = sdlEvent.Window.WindowID; + windowID = sdlEvent.Window.WindowID; return true; default: - windowId = 0; + windowID = 0; return false; } } - } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs index c340999d7..b91dbdce7 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; - using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -11,8 +11,8 @@ namespace Inno.Adapter.Presentation.ImGui; /// public static unsafe class ImGuiFont { - private static readonly object s_sync = new(); - private static readonly Dictionary> s_fontsByContext = []; + private static readonly object SYNC = new(); + private static readonly Dictionary> FONTS_BY_CONTEXT = []; /// /// Gets whether an exact font style is available in the current ImGui context. @@ -27,13 +27,15 @@ public static bool IsAvailable(ImGuiFontStyle style) { ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null) + if (context is null) + { return false; + } - lock (s_sync) + lock (SYNC) { - return s_fontsByContext.TryGetValue(GetContextKey(context), out Dictionary? fonts) && - fonts.ContainsKey(style); + return FONTS_BY_CONTEXT.TryGetValue(GetContextKey(context), out Dictionary? fonts) + && fonts.ContainsKey(style); } } @@ -50,16 +52,18 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) { ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null) + if (context is null) + { return default; + } nuint contextKey = GetContextKey(context); nint font; - lock (s_sync) + lock (SYNC) { - if (!s_fontsByContext.TryGetValue(contextKey, out Dictionary? fonts) || - !TryResolve(fonts, style, out font)) - { + if (!FONTS_BY_CONTEXT.TryGetValue(contextKey, out Dictionary? fonts) + || !TryResolve(fonts, style, out font) + ) { return default; } } @@ -72,8 +76,10 @@ internal static void RegisterContext( ImGuiNativeContext* context, IReadOnlyDictionary fonts ) { - if (context == null) + if (context is null) + { throw new ArgumentException("An ImGui context is required.", nameof(context)); + } ArgumentNullException.ThrowIfNull(fonts); var registered = new Dictionary(); @@ -81,11 +87,15 @@ IReadOnlyDictionary fonts { ValidateStyle(style); if (font != 0) + { registered[style] = font; + } } - lock (s_sync) - s_fontsByContext[GetContextKey(context)] = registered; + lock (SYNC) + { + FONTS_BY_CONTEXT[GetContextKey(context)] = registered; + } } internal static void RegisterStyle( @@ -93,19 +103,23 @@ internal static void RegisterStyle( ImGuiFontStyle style, nint font ) { - if (context == null) + if (context is null) + { throw new ArgumentException("An ImGui context is required.", nameof(context)); + } ValidateStyle(style); if (font == 0) + { throw new ArgumentException("A loaded font is required.", nameof(font)); + } - lock (s_sync) + lock (SYNC) { nuint contextKey = GetContextKey(context); - if (!s_fontsByContext.TryGetValue(contextKey, out Dictionary? fonts)) + if (!FONTS_BY_CONTEXT.TryGetValue(contextKey, out Dictionary? fonts)) { fonts = []; - s_fontsByContext.Add(contextKey, fonts); + FONTS_BY_CONTEXT.Add(contextKey, fonts); } fonts[style] = font; } @@ -113,24 +127,32 @@ nint font internal static void UnregisterContext(ImGuiNativeContext* context) { - if (context == null) + if (context is null) + { return; - lock (s_sync) - s_fontsByContext.Remove(GetContextKey(context)); + } + lock (SYNC) + { + FONTS_BY_CONTEXT.Remove(GetContextKey(context)); + } } internal static void ValidateStyle(ImGuiFontStyle style) { - const ImGuiFontStyle supported = ImGuiFontStyle.Bold | ImGuiFontStyle.Italic; - if ((style & ~supported) != 0) + const ImGuiFontStyle C_SUPPORTED = ImGuiFontStyle.Bold | ImGuiFontStyle.Italic; + if ((style & ~C_SUPPORTED) != 0) + { throw new ArgumentOutOfRangeException(nameof(style), style, "The font style contains unsupported flags."); + } } internal static void PopStyle(nuint contextKey) { ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null || GetContextKey(context) != contextKey) + if (context is null || GetContextKey(context) != contextKey) + { throw new InvalidOperationException("The font style scope must be disposed in the context where it was created."); + } NativeImGui.PopFont(); } @@ -142,39 +164,17 @@ private static bool TryResolve( out nint font ) { if (fonts.TryGetValue(style, out font)) + { return true; + } if ((style & ImGuiFontStyle.Bold) != 0 && fonts.TryGetValue(ImGuiFontStyle.Bold, out font)) + { return true; + } if ((style & ImGuiFontStyle.Italic) != 0 && fonts.TryGetValue(ImGuiFontStyle.Italic, out font)) + { return true; + } return fonts.TryGetValue(ImGuiFontStyle.Regular, out font); } } - -/// -/// Restores the previous ImGui font when a scoped style ends. -/// -public ref struct ImGuiFontScope -{ - private readonly nuint m_contextKey; - private bool m_isPushed; - - internal ImGuiFontScope( - nuint contextKey, - bool isPushed - ) { - m_contextKey = contextKey; - m_isPushed = isPushed; - } - - /// - /// Restores the font that was active before this scope. - /// - public void Dispose() - { - if (!m_isPushed) - return; - ImGuiFont.PopStyle(m_contextKey); - m_isPushed = false; - } -} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs new file mode 100644 index 000000000..5ab3d34c2 --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs @@ -0,0 +1,31 @@ +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Restores the previous ImGui font when a scoped style ends. +/// +public ref struct ImGuiFontScope +{ + private readonly nuint m_contextKey; + private bool m_isPushed; + + internal ImGuiFontScope( + nuint contextKey, + bool isPushed + ) { + m_contextKey = contextKey; + m_isPushed = isPushed; + } + + /// + /// Restores the font that was active before this scope. + /// + public void Dispose() + { + if (!m_isPushed) + { + return; + } + ImGuiFont.PopStyle(m_contextKey); + m_isPushed = false; + } +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs index e305d530f..491922d3f 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs @@ -12,12 +12,10 @@ public enum ImGuiFontStyle /// Uses the regular font face. /// Regular = 0, - /// /// Uses a bold font face. /// Bold = 1 << 0, - /// /// Uses an italic font face. /// diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIONative.cs similarity index 69% rename from backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs rename to backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIONative.cs index 544b3e35d..4486bb8e2 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIONative.cs @@ -1,13 +1,13 @@ using System; using System.Runtime.InteropServices; using Inno.Core.Execution; - using Inno.Native.ImGui; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; -internal static unsafe class ImGuiPlatformIoNative +internal static unsafe class ImGuiPlatformIONative { internal static void* CreateWindowCallbacks( ImGuiNativeContext* context, @@ -15,20 +15,48 @@ internal static unsafe class ImGuiPlatformIoNative delegate* unmanaged[Cdecl] setSize ) { void* registration = ImGuiNative.Raw.InnoCreatePlatformWindowCallbacks(context, setPosition, setSize); - if (registration == null) + if (registration is null) + { throw new InvalidOperationException("The current ImGui context cannot own platform window callbacks."); + } return registration; } internal static void DestroyWindowCallbacks(void* registration) { - if (registration == null) + if (registration is null) + { return; + } if (ImGuiNative.Raw.InnoCanDestroyPlatformWindowCallbacks(registration) == 0) + { throw new RetirementPendingException("Platform window callbacks still require their current context's idle owner thread."); + } ImGuiNative.Raw.InnoDestroyPlatformWindowCallbacks(registration); } + internal static void SetPlatformGetWindowPos( + ImGuiPlatformIO* platformIO, + PlatformGetWindowPosCallback callback + ) { + nint callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); + ImGuiNative.Raw.PlatformIOSetPlatformGetWindowPos( + platformIO, + (delegate* unmanaged[Cdecl])callbackPtr + ); + } + + internal static void SetPlatformGetWindowSize( + ImGuiPlatformIO* platformIO, + PlatformGetWindowSizeCallback callback + ) { + nint callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); + ImGuiNative.Raw.PlatformIOSetPlatformGetWindowSize( + platformIO, + (delegate* unmanaged[Cdecl])callbackPtr + ); + } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void PlatformGetWindowPosCallback( ImGuiViewport* viewport, @@ -40,22 +68,4 @@ internal unsafe delegate void PlatformGetWindowSizeCallback( ImGuiViewport* viewport, ImVec2C* outSize ); - - internal static void SetPlatformGetWindowPos( - ImGuiPlatformIO* platformIo, - PlatformGetWindowPosCallback callback - ) { - var callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); - var setterArg = (delegate* unmanaged[Cdecl])callbackPtr; - ImGuiNative.Raw.PlatformIOSetPlatformGetWindowPos(platformIo, setterArg); - } - - internal static void SetPlatformGetWindowSize( - ImGuiPlatformIO* platformIo, - PlatformGetWindowSizeCallback callback - ) { - var callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); - var setterArg = (delegate* unmanaged[Cdecl])callbackPtr; - ImGuiNative.Raw.PlatformIOSetPlatformGetWindowSize(platformIo, setterArg); - } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs index aaa18c2ab..0960d57ad 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs @@ -1,5 +1,4 @@ using System; - using Inno.Adapter.Platform.Sdl3; using Inno.Native.Sdl3; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs index cccd9b60f..71b6c0c33 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs @@ -1,8 +1,8 @@ using System; using System.Numerics; +using Inno.Native.Sdl3; using ImGuiNative = Inno.Native.ImGui.ImGui; -using Inno.Native.Sdl3; namespace Inno.Adapter.Presentation.ImGui; @@ -21,20 +21,20 @@ internal static void EnsureInitialized() return; } - var probe = new Vector4(0.125f, 0.5f, 0.875f, 1.0f); - var packed = ImGuiNative.GetColorU32(probe); - var expectedR = (int)(probe.X * 255.0f + 0.5f); - var expectedG = (int)(probe.Y * 255.0f + 0.5f); - var expectedB = (int)(probe.Z * 255.0f + 0.5f); - var expectedA = (int)(probe.W * 255.0f + 0.5f); + var probe = new Vector4(0.125f, 0.5f, 0.875f, 1f); + uint packed = ImGuiNative.GetColorU32(probe); + int expectedR = (int)(probe.X * 255f + 0.5f); + int expectedG = (int)(probe.Y * 255f + 0.5f); + int expectedB = (int)(probe.Z * 255f + 0.5f); + int expectedA = (int)(probe.W * 255f + 0.5f); - var b0 = (int)(packed & 0xFF); - var b1 = (int)((packed >> 8) & 0xFF); - var b2 = (int)((packed >> 16) & 0xFF); - var b3 = (int)((packed >> 24) & 0xFF); - Span packedBytes = stackalloc int[4] { b0, b1, b2, b3 }; + int b0 = (int)(packed & 0xFF); + int b1 = (int)((packed >> 8) & 0xFF); + int b2 = (int)((packed >> 16) & 0xFF); + int b3 = (int)((packed >> 24) & 0xFF); + Span packedBytes = [b0, b1, b2, b3]; - var usedMask = 0; + int usedMask = 0; s_rShift = SelectBestShift(packedBytes, expectedR, ref usedMask); s_gShift = SelectBestShift(packedBytes, expectedG, ref usedMask); s_bShift = SelectBestShift(packedBytes, expectedB, ref usedMask); @@ -46,11 +46,11 @@ internal static SDLFColor ToSdlFColor(uint packedColor) { EnsureInitialized(); - const float inv255 = 1f / 255f; - var r = ((packedColor >> s_rShift) & 0xFF) * inv255; - var g = ((packedColor >> s_gShift) & 0xFF) * inv255; - var b = ((packedColor >> s_bShift) & 0xFF) * inv255; - var a = ((packedColor >> s_aShift) & 0xFF) * inv255; + const float C_INV255 = 1f / 255f; + float r = ((packedColor >> s_rShift) & 0xFF) * C_INV255; + float g = ((packedColor >> s_gShift) & 0xFF) * C_INV255; + float b = ((packedColor >> s_bShift) & 0xFF) * C_INV255; + float a = ((packedColor >> s_aShift) & 0xFF) * C_INV255; return new SDLFColor { R = r, G = g, B = b, A = a }; } @@ -59,16 +59,16 @@ private static int SelectBestShift( int expected, ref int usedMask ) { - var bestIndex = 0; - var bestError = int.MaxValue; - for (var i = 0; i < 4; i++) + int bestIndex = 0; + int bestError = int.MaxValue; + for (int i = 0; i < 4; i++) { if ((usedMask & (1 << i)) != 0) { continue; } - var error = Math.Abs(packedBytes[i] - expected); + int error = Math.Abs(packedBytes[i] - expected); if (error < bestError) { bestError = error; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs index a6457d993..09207168d 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs @@ -1,11 +1,11 @@ -using System.Runtime.InteropServices; -using System.Threading.Tasks; using System; using System.Numerics; - +using System.Runtime.InteropServices; +using System.Threading.Tasks; using Inno.Adapter.Platform.Sdl3; -using Inno.Native.Sdl3; using Inno.Native.ImGui; +using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -21,7 +21,7 @@ internal sealed unsafe class PlatformImGuiSdlRenderer : IPlatformImGuiRenderer internal PlatformImGuiSdlRenderer(Sdl3PlatformWindow window) { m_renderer = SDL.Raw.CreateRenderer(window.GetSdlWindow(), null); - if (m_renderer == null) + if (m_renderer is null) { throw new InvalidOperationException(Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) ?? "SDL_CreateRenderer failed."); } @@ -34,7 +34,7 @@ internal PlatformImGuiSdlRenderer(Sdl3PlatformWindow window) /// public bool supportsViewports => false; - /// + /// public bool supportsVertexOffsets => true; /// @@ -43,7 +43,7 @@ internal PlatformImGuiSdlRenderer(Sdl3PlatformWindow window) /// /// The draw data consumed by render main; ownership remains with the caller unless explicitly stated otherwise. /// - public void RenderMain(IntPtr drawData) => Render((ImDrawData*)drawData); + public void RenderMain(nint drawData) => Render((ImDrawData*)drawData); /// /// Synchronizes the main render output with the current drawable dimensions. @@ -78,7 +78,7 @@ public void CreateViewport(PlatformImGuiViewportTarget target) /// /// The existing target that receives the validated result. /// - public void ResizeViewport(PlatformImGuiViewportTarget target) { } + public void ResizeViewport(PlatformImGuiViewportTarget target) {} /// /// Records ImGui draw data for the supplied auxiliary viewport. @@ -91,8 +91,8 @@ public void ResizeViewport(PlatformImGuiViewportTarget target) { } /// public void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData - ) { } + nint drawData + ) {} /// /// Presents the completed frame for the supplied auxiliary viewport. @@ -100,7 +100,7 @@ IntPtr drawData /// /// The existing target that receives the validated result. /// - public void PresentViewport(PlatformImGuiViewportTarget target) { } + public void PresentViewport(PlatformImGuiViewportTarget target) {} /// /// Destroys the auxiliary viewport and releases its rendering resources. @@ -111,14 +111,39 @@ public void PresentViewport(PlatformImGuiViewportTarget target) { } /// /// An already completed task because this renderer owns no additional native windows. /// - public Task RetireViewport(PlatformImGuiViewportTarget target) => Task.CompletedTask; + public Task RetireViewportAsync(PlatformImGuiViewportTarget target) => Task.CompletedTask; + + /// + public void DrainViewportRetirements() {} - /// - public void DrainViewportRetirements() { } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + + if (m_fontTexture is not null) + { + SDL.Raw.DestroyTexture(m_fontTexture); + m_fontTexture = null; + } + + if (m_renderer is not null) + { + SDL.Raw.DestroyRenderer(m_renderer); + m_renderer = null; + } + + m_disposed = true; + } internal void Render(ImDrawData* drawData) { - if (m_disposed || m_renderer == null || drawData == null || drawData->Valid == 0) + if (m_disposed || m_renderer is null || drawData is null || drawData->Valid == 0) { return; } @@ -131,43 +156,43 @@ internal void Render(ImDrawData* drawData) _ = SDL.Raw.SetRenderDrawColor(m_renderer, 20, 20, 22, 255); _ = SDL.Raw.RenderClear(m_renderer); - var clipOff = drawData->DisplayPos; - var clipScale = drawData->FramebufferScale; + ImVec2C clipOff = drawData->DisplayPos; + ImVec2C clipScale = drawData->FramebufferScale; - for (var listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) + for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { - var drawList = drawData->CmdLists.Data[listIndex]; - if (drawList == null) + ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; + if (drawList is null) { continue; } - var vertexCount = drawList->VtxBuffer.Size; + int vertexCount = drawList->VtxBuffer.Size; if (vertexCount <= 0) { continue; } EnsureVertexCapacity(vertexCount); - var srcVertices = drawList->VtxBuffer.Data; - for (var i = 0; i < vertexCount; i++) + ImDrawVert* srcVertices = drawList->VtxBuffer.Data; + for (int i = 0; i < vertexCount; i++) { m_vertexScratch[i] = ToSdlVertex(srcVertices[i], clipOff, clipScale); } - var cmdBufferCount = drawList->CmdBuffer.Size; - for (var cmdIndex = 0; cmdIndex < cmdBufferCount; cmdIndex++) + int cmdBufferCount = drawList->CmdBuffer.Size; + for (int cmdIndex = 0; cmdIndex < cmdBufferCount; cmdIndex++) { - var drawCmd = drawList->CmdBuffer.Data[cmdIndex]; - if (drawCmd.UserCallback != null) + ImDrawCmd drawCmd = drawList->CmdBuffer.Data[cmdIndex]; + if (drawCmd.UserCallback is not null) { continue; } - var clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; - var clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; - var clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; - var clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; + float clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; + float clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; + float clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; + float clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; if (clipRectZ <= clipRectX || clipRectW <= clipRectY) { @@ -176,8 +201,10 @@ internal void Render(ImDrawData* drawData) var clipRect = new SDLRect { - X = (int)clipRectX, Y = (int)clipRectY, - W = (int)(clipRectZ - clipRectX), H = (int)(clipRectW - clipRectY) + X = (int)clipRectX, + Y = (int)clipRectY, + W = (int)(clipRectZ - clipRectX), + H = (int)(clipRectW - clipRectY) }; if (SDL.Raw.SetRenderClipRect(m_renderer, &clipRect) == 0) @@ -185,7 +212,7 @@ internal void Render(ImDrawData* drawData) continue; } - var elemCount = (int)drawCmd.ElemCount; + int elemCount = (int)drawCmd.ElemCount; if (elemCount <= 0) { continue; @@ -193,17 +220,17 @@ internal void Render(ImDrawData* drawData) EnsureIndexCapacity(elemCount); - var srcIndices = drawList->IdxBuffer.Data; - var idxOffset = (int)drawCmd.IdxOffset; - var vtxOffset = (int)drawCmd.VtxOffset; - for (var i = 0; i < elemCount; i++) + ushort* srcIndices = drawList->IdxBuffer.Data; + int idxOffset = (int)drawCmd.IdxOffset; + int vtxOffset = (int)drawCmd.VtxOffset; + for (int i = 0; i < elemCount; i++) { m_indexScratch[i] = srcIndices[idxOffset + i] + vtxOffset; } - var textureId = ImGuiNative.Raw.GetTexID(&drawCmd); - var texture = TextureFromImGui(textureId); - if (texture == null) + ulong textureID = ImGuiNative.Raw.GetTexID(&drawCmd); + SDLTexture* texture = TextureFromImGui(textureID); + if (texture is null) { texture = m_fontTexture; } @@ -211,13 +238,7 @@ internal void Render(ImDrawData* drawData) fixed (SDLVertex* pVertices = m_vertexScratch) fixed (int* pIndices = m_indexScratch) { - _ = SDL.Raw.RenderGeometry( - m_renderer, - texture, - pVertices, - vertexCount, - pIndices, - elemCount); + _ = SDL.Raw.RenderGeometry(m_renderer, texture, pVertices, vertexCount, pIndices, elemCount); } } } @@ -231,7 +252,7 @@ internal void Render(ImDrawData* drawData) /// internal void SynchronizeOutputSize() { - if (m_disposed || m_renderer == null) + if (m_disposed || m_renderer is null) { return; } @@ -239,52 +260,23 @@ internal void SynchronizeOutputSize() // A macOS live-resize expose callback can run before SDL's renderer event watcher has // consumed the matching pixel-size event. Re-applying the disabled presentation mode // makes SDL query the native drawable immediately instead of clipping to its old size. - _ = SDL.Raw.SetRenderLogicalPresentation( - m_renderer, - 0, - 0, - SDLRendererLogicalPresentation.Disabled); + _ = SDL.Raw.SetRenderLogicalPresentation(m_renderer, 0, 0, SDLRendererLogicalPresentation.Disabled); _ = SDL.Raw.SetRenderViewport(m_renderer, null); _ = SDL.Raw.SetRenderClipRect(m_renderer, null); } - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - { - return; - } - - if (m_fontTexture != null) - { - SDL.Raw.DestroyTexture(m_fontTexture); - m_fontTexture = null; - } - - if (m_renderer != null) - { - SDL.Raw.DestroyRenderer(m_renderer); - m_renderer = null; - } - - m_disposed = true; - } - private void ProcessTextureRequests(ImDrawData* drawData) { - var textures = drawData->Textures; - if (textures == null) + ImVectorImTextureDataPtr* textures = drawData->Textures; + if (textures is null) { return; } - for (var i = 0; i < textures->Size; i++) + for (int i = 0; i < textures->Size; i++) { - var textureData = textures->Data[i]; - if (textureData == null) + ImTextureData* textureData = textures->Data[i]; + if (textureData is null) { continue; } @@ -306,16 +298,16 @@ private void ProcessTextureRequests(ImDrawData* drawData) private void EnsureFontTexture() { - var io = ImGuiNative.Raw.GetIO(); - var fonts = io->Fonts; - if (fonts == null) + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + ImFontAtlas* fonts = io->Fonts; + if (fonts is null) { return; } fonts->RendererHasTextures = 1; - var texData = fonts->TexData; - if (texData == null) + ImTextureData* texData = fonts->TexData; + if (texData is null) { return; } @@ -331,7 +323,7 @@ private void EnsureFontTexture() break; } - if (m_fontTexture == null) + if (m_fontTexture is null) { m_fontTexture = TextureFromImGui(texData->TexId); } @@ -341,11 +333,11 @@ private void CreateOrUpdateTexture( ImTextureData* textureData, bool createIfMissing ) { - var texture = TextureFromImGui(textureData->TexId); - if (texture == null && createIfMissing) + SDLTexture* texture = TextureFromImGui(textureData->TexId); + if (texture is null && createIfMissing) { texture = CreateTexture(textureData->Width, textureData->Height); - if (texture == null) + if (texture is null) { return; } @@ -353,16 +345,16 @@ bool createIfMissing ImGuiNative.Raw.SetTexID(textureData, (ulong)(nuint)texture); } - if (texture == null || textureData->Pixels == null) + if (texture is null || textureData->Pixels is null) { return; } - var pitch = ImGuiNative.Raw.GetPitch(textureData); + int pitch = ImGuiNative.Raw.GetPitch(textureData); _ = SDL.Raw.UpdateTexture(texture, null, textureData->Pixels, pitch); ImGuiNative.Raw.SetStatus(textureData, ImTextureStatus.Ok); - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); if (textureData->TexId == ImGuiNative.Raw.GetTexID(&io->Fonts->TexRef)) { m_fontTexture = texture; @@ -371,8 +363,8 @@ bool createIfMissing private void DestroyTexture(ImTextureData* textureData) { - var texture = TextureFromImGui(textureData->TexId); - if (texture != null) + SDLTexture* texture = TextureFromImGui(textureData->TexId); + if (texture is not null) { SDL.Raw.DestroyTexture(texture); } @@ -395,7 +387,7 @@ int height return null; } - var props = SDL.CreateProperties(); + uint props = SDL.CreateProperties(); try { _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, (long)SDLPixelFormat.Rgba32); @@ -403,8 +395,8 @@ int height _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, width); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, height); - var texture = SDL.Raw.CreateTextureWithProperties(m_renderer, props); - if (texture == null) + SDLTexture* texture = SDL.Raw.CreateTextureWithProperties(m_renderer, props); + if (texture is null) { return null; } @@ -419,28 +411,6 @@ int height } } - private static SDLVertex ToSdlVertex( - ImDrawVert vtx, - ImVec2C displayPos, - ImVec2C framebufferScale - ) { - var color = ImGuiPackedColor.ToSdlFColor(vtx.Col); - var x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; - var y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; - - return new SDLVertex - { - Position = new SDLFPoint { X = x, Y = y }, - Color = color, - TexCoord = new SDLFPoint { X = vtx.Uv.X, Y = vtx.Uv.Y } - }; - } - - private static SDLTexture* TextureFromImGui(ulong textureId) - { - return (SDLTexture*)(nuint)textureId; - } - private void EnsureVertexCapacity(int requiredCount) { if (m_vertexScratch.Length < requiredCount) @@ -456,4 +426,23 @@ private void EnsureIndexCapacity(int requiredCount) m_indexScratch = new int[Math.Max(requiredCount, m_indexScratch.Length * 2 + 256)]; } } + + private static SDLVertex ToSdlVertex( + ImDrawVert vtx, + ImVec2C displayPos, + ImVec2C framebufferScale + ) { + SDLFColor color = ImGuiPackedColor.ToSdlFColor(vtx.Col); + float x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; + float y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; + + return new SDLVertex + { + Position = new SDLFPoint { X = x, Y = y }, + Color = color, + TexCoord = new SDLFPoint { X = vtx.Uv.X, Y = vtx.Uv.Y } + }; + } + + private static SDLTexture* TextureFromImGui(ulong textureID) => (SDLTexture*)(nuint)textureID; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs index 947b1352b..e2ffc42e9 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs @@ -3,6 +3,7 @@ using System.Runtime.InteropServices; using Inno.Native.ImGui; using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -11,28 +12,34 @@ internal sealed unsafe partial class PlatformImGuiViewportBackend { private static void RefreshMonitors(SDLWindow* fallbackWindow) { - var monitors = new List(); + List monitors = []; int displayCount = 0; uint* displays = SDL.Raw.GetDisplays(&displayCount); try { uint primary = SDL.GetPrimaryDisplay(); - if (displays != null && displayCount > 0) + if (displays is not null && displayCount > 0) { if (primary != 0) + { AddDisplayMonitor(primary, monitors); + } for (int index = 0; index < displayCount; index++) { uint display = displays[index]; if (display != 0 && display != primary) + { AddDisplayMonitor(display, monitors); + } } } - if (monitors.Count == 0 && fallbackWindow != null) + if (monitors.Count == 0 && fallbackWindow is not null) { uint fallback = SDL.Raw.GetDisplayForWindow(fallbackWindow); if (fallback != 0) + { AddDisplayMonitor(fallback, monitors); + } } } finally @@ -45,9 +52,11 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) if (monitors.Count > storage.Capacity) { uint bytes = checked((uint)monitors.Count * (uint)sizeof(ImGuiPlatformMonitor)); - var replacement = (ImGuiPlatformMonitor*)ImGuiNative.Raw.MemAlloc(bytes); - if (replacement == null) + ImGuiPlatformMonitor* replacement = (ImGuiPlatformMonitor*)ImGuiNative.Raw.MemAlloc(bytes); + if (replacement is null) + { throw new OutOfMemoryException("Cannot allocate the ImGui monitor snapshot."); + } CollectionsMarshal.AsSpan(monitors).CopyTo(new Span(replacement, monitors.Count)); ImGuiPlatformMonitor* previous = storage.Data; storage.Data = replacement; @@ -64,15 +73,17 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) } private static void AddDisplayMonitor( - uint displayId, + uint displayID, List monitors ) { SDLRect main = default; - if (SDL.Raw.GetDisplayBounds(displayId, &main) == 0) + if (SDL.Raw.GetDisplayBounds(displayID, &main) == 0) + { return; + } SDLRect work = main; - _ = SDL.Raw.GetDisplayUsableBounds(displayId, &work); - float scale = SDL.GetDisplayContentScale(displayId); + _ = SDL.Raw.GetDisplayUsableBounds(displayID, &work); + float scale = SDL.GetDisplayContentScale(displayID); monitors.Add(new ImGuiPlatformMonitor { MainPos = new ImVec2C { X = main.X, Y = main.Y }, @@ -80,7 +91,7 @@ List monitors WorkPos = new ImVec2C { X = work.X, Y = work.Y }, WorkSize = new ImVec2C { X = work.W, Y = work.H }, DpiScale = scale <= 0f ? 1f : scale, - PlatformHandle = (void*)(nuint)displayId + PlatformHandle = (void*)(nuint)displayID }); } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs index 080896a90..813bde674 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs @@ -15,16 +15,25 @@ internal void ProcessRetirements() ViewportWindowData data = m_retiringViewports[index]; Task retirement = data.retirement!; if (!retirement.IsCompleted) + { continue; + } if (!retirement.IsCompletedSuccessfully) + { throw new RetirementPendingException("Rendering failed to release a detached SDL window.", retirement.Exception); + } DestroyRetiredWindow(data); m_retiringViewports.RemoveAt(index); } if (m_callbackFailure is Exception callbackFailure) { if (m_retiringViewports.Count != 0) - throw new RetirementPendingException("An ImGui callback failed; its renderer still borrows a detached window.", callbackFailure); + { + throw new RetirementPendingException( + "An ImGui callback failed; its renderer still borrows a detached window.", + callbackFailure + ); + } m_callbackFailure = null; throw new InvalidOperationException("An ImGui window callback failed and its resources have retired.", callbackFailure); } @@ -33,7 +42,9 @@ internal void ProcessRetirements() private static void DestroyViewportWindow(ViewportWindowData data) { if (data.detached) + { return; + } data.detached = true; data.drawable = false; data.owner.m_retiringViewports.Add(data); @@ -41,8 +52,8 @@ private static void DestroyViewportWindow(ViewportWindowData data) { data.owner.m_application.ReleaseWindow(data.registeredWindow); data.retirement = data.externalRenderer is not null && data.externalTarget is not null - ? data.externalRenderer.RetireViewport(data.externalTarget) - : Task.CompletedTask; + ? data.externalRenderer.RetireViewportAsync(data.externalTarget) + : Task.CompletedTask; } catch (Exception failure) { @@ -52,23 +63,25 @@ private static void DestroyViewportWindow(ViewportWindowData data) { data.viewport = default; if (data.gcHandle.IsAllocated) + { data.gcHandle.Free(); + } } } private static void DestroyRetiredWindow(ViewportWindowData data) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; } - if (data.renderer != null) + if (data.renderer is not null) { SDL.Raw.DestroyRenderer(data.renderer); data.renderer = null; } - if (data.window != null) + if (data.window is not null) { SDL.Raw.DestroyWindow(data.window); data.window = null; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs index 9855a9440..f203f9812 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs @@ -1,59 +1,33 @@ -using System.Threading.Tasks; -using Inno.Core.Execution; -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Numerics; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; - +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; -using Inno.Platform; -using Inno.Native.Sdl3; +using Inno.Core.Execution; using Inno.Native.ImGui; +using Inno.Native.Sdl3; +using Inno.Platform; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; internal sealed unsafe partial class PlatformImGuiViewportBackend : IDisposable { - private sealed class ViewportWindowData - { - internal required PlatformImGuiViewportBackend owner; - internal required Sdl3PlatformWindow registeredWindow; - internal ImGuiViewport* viewport; - internal bool drawable; - internal Task? retirement; - internal bool detached; - internal SDLWindow* window; - internal SDLRenderer* renderer; - internal IPlatformImGuiRenderer? externalRenderer; - internal PlatformImGuiViewportTarget? externalTarget; - internal SDLTexture* fontTexture; - internal int fontTextureWidth; - internal int fontTextureHeight; - internal nint fontPixelsPtr; - internal int fontTexturePitch; - internal int fontTextureUniqueId = -1; - internal ImTextureRect fontUsedRect; - internal ImTextureRect fontUpdateRect; - internal uint windowId; - internal GCHandle gcHandle; - internal SDLVertex[] vertexScratch = []; - internal int[] indexScratch = []; - } - - private static readonly ImGuiPlatformIoNative.PlatformGetWindowPosCallback s_platformGetWindowPos = PlatformGetWindowPosOutCallback; - private static readonly ImGuiPlatformIoNative.PlatformGetWindowSizeCallback s_platformGetWindowSize = PlatformGetWindowSizeOutCallback; + private static readonly ImGuiPlatformIONative.PlatformGetWindowPosCallback PLATFORM_GET_WINDOW_POS = PlatformGetWindowPosOutCallback; + private static readonly ImGuiPlatformIONative.PlatformGetWindowSizeCallback PLATFORM_GET_WINDOW_SIZE = PlatformGetWindowSizeOutCallback; - private static readonly object S_CONTEXT_SYNC = new(); - private static readonly Dictionary S_BACKENDS_BY_CONTEXT = []; + private static readonly object CONTEXT_SYNC = new(); + private static readonly Dictionary BACKENDS_BY_CONTEXT = []; private readonly Sdl3PlatformApplication m_application; private readonly SDLWindow* m_mainWindow; private readonly IPlatformImGuiRenderer m_renderer; private readonly nuint m_contextKey; - private readonly Dictionary m_viewportsById = []; + private readonly Dictionary m_viewportsByID = []; private readonly Dictionary m_windowToViewport = []; private readonly List m_retiringViewports = []; private void* m_windowCallbacks; @@ -68,37 +42,43 @@ IPlatformImGuiRenderer renderer ) { ArgumentNullException.ThrowIfNull(renderer); ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); - if (context == null) + if (context is null) + { throw new InvalidOperationException("An active ImGui context is required for viewport routing."); + } m_contextKey = (nuint)context; - lock (S_CONTEXT_SYNC) + lock (CONTEXT_SYNC) { - if (S_BACKENDS_BY_CONTEXT.ContainsKey(m_contextKey)) + if (BACKENDS_BY_CONTEXT.ContainsKey(m_contextKey)) + { throw new InvalidOperationException("The current ImGui context already owns a viewport backend."); + } } m_application = application; m_renderer = renderer; _ = SDL.SetHint(SDL.Constants.SDL_HINT_WINDOW_ACTIVATE_WHEN_RAISED, "1"); m_mainWindow = mainWindow.GetSdlWindow(); - var platformIo = ImGuiNative.Raw.GetPlatformIO(); - if (ImGuiNative.Raw.GetIO()->BackendPlatformUserData != null) + ImGuiPlatformIO* platformIO = ImGuiNative.Raw.GetPlatformIO(); + if (ImGuiNative.Raw.GetIO()->BackendPlatformUserData is not null) + { throw new InvalidOperationException("The current ImGui context already has platform backend state."); - platformIo->PlatformCreateWindow = &PlatformCreateWindowCallback; - platformIo->PlatformDestroyWindow = &PlatformDestroyWindowCallback; - platformIo->PlatformShowWindow = &PlatformShowWindowCallback; - platformIo->PlatformGetWindowFramebufferScale = default; - platformIo->PlatformSetWindowFocus = &PlatformSetWindowFocusCallback; - platformIo->PlatformGetWindowFocus = &PlatformGetWindowFocusCallback; - platformIo->PlatformGetWindowMinimized = &PlatformGetWindowMinimizedCallback; - platformIo->PlatformSetWindowTitle = &PlatformSetWindowTitleCallback; - platformIo->PlatformSetWindowAlpha = &PlatformSetWindowAlphaCallback; - platformIo->RendererRenderWindow = &RendererRenderWindowCallback; - platformIo->RendererSwapBuffers = &RendererSwapBuffersCallback; - ImGuiPlatformIoNative.SetPlatformGetWindowPos(platformIo, s_platformGetWindowPos); - ImGuiPlatformIoNative.SetPlatformGetWindowSize(platformIo, s_platformGetWindowSize); - - var mainViewport = ImGuiNative.Raw.GetMainViewport(); + } + platformIO->PlatformCreateWindow = &PlatformCreateWindowCallback; + platformIO->PlatformDestroyWindow = &PlatformDestroyWindowCallback; + platformIO->PlatformShowWindow = &PlatformShowWindowCallback; + platformIO->PlatformGetWindowFramebufferScale = default; + platformIO->PlatformSetWindowFocus = &PlatformSetWindowFocusCallback; + platformIO->PlatformGetWindowFocus = &PlatformGetWindowFocusCallback; + platformIO->PlatformGetWindowMinimized = &PlatformGetWindowMinimizedCallback; + platformIO->PlatformSetWindowTitle = &PlatformSetWindowTitleCallback; + platformIO->PlatformSetWindowAlpha = &PlatformSetWindowAlphaCallback; + platformIO->RendererRenderWindow = &RendererRenderWindowCallback; + platformIO->RendererSwapBuffers = &RendererSwapBuffersCallback; + ImGuiPlatformIONative.SetPlatformGetWindowPos(platformIO, PLATFORM_GET_WINDOW_POS); + ImGuiPlatformIONative.SetPlatformGetWindowSize(platformIO, PLATFORM_GET_WINDOW_SIZE); + + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); SDLWindow* mainSdlWindow = mainWindow.GetSdlWindow(); mainViewport->PlatformHandle = (void*)mainSdlWindow; mainViewport->PlatformHandleRaw = (void*)mainWindow.nativeHandles.windowHandle; @@ -106,65 +86,124 @@ IPlatformImGuiRenderer renderer try { RefreshMonitors(mainSdlWindow); - m_windowCallbacks = ImGuiPlatformIoNative.CreateWindowCallbacks( - context, &PlatformSetWindowPosCallback, &PlatformSetWindowSizeCallback); - lock (S_CONTEXT_SYNC) - S_BACKENDS_BY_CONTEXT.Add(m_contextKey, this); + m_windowCallbacks = ImGuiPlatformIONative.CreateWindowCallbacks( + context, + &PlatformSetWindowPosCallback, + &PlatformSetWindowSizeCallback + ); + lock (CONTEXT_SYNC) + { + BACKENDS_BY_CONTEXT.Add(m_contextKey, this); + } } catch { - ImGuiPlatformIoNative.DestroyWindowCallbacks(m_windowCallbacks); + ImGuiPlatformIONative.DestroyWindowCallbacks(m_windowCallbacks); m_windowCallbacks = null; - ImGuiNative.Raw.ClearPlatformHandlers(platformIo); - ImGuiNative.Raw.ClearRendererHandlers(platformIo); + ImGuiNative.Raw.ClearPlatformHandlers(platformIO); + ImGuiNative.Raw.ClearRendererHandlers(platformIO); mainViewport->PlatformHandle = null; mainViewport->PlatformHandleRaw = null; throw; } } - internal bool OwnsWindow(uint windowId) + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() { - return m_windowToViewport.ContainsKey(windowId); + if (m_disposed) + { + return; + } + + foreach (KeyValuePair kv in m_viewportsByID) + { + DestroyViewportWindow(kv.Value); + } + + m_viewportsByID.Clear(); + m_windowToViewport.Clear(); + if (m_retiringViewports.Count != 0) + { + m_renderer.DrainViewportRetirements(); + } + ProcessRetirements(); + if (m_retiringViewports.Count != 0) + { + throw new RetirementPendingException("Detached ImGui windows are still borrowed by their renderer."); + } + + ImGuiPlatformIO* platformIO = ImGuiNative.Raw.GetPlatformIO(); + ImGuiPlatformIONative.DestroyWindowCallbacks(m_windowCallbacks); + m_windowCallbacks = null; + ImGuiNative.Raw.ClearPlatformHandlers(platformIO); + ImGuiNative.Raw.ClearRendererHandlers(platformIO); + + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); + if (mainViewport is not null) + { + mainViewport->PlatformHandle = null; + mainViewport->PlatformHandleRaw = null; + } + + lock (CONTEXT_SYNC) + { + if (BACKENDS_BY_CONTEXT.TryGetValue(m_contextKey, out PlatformImGuiViewportBackend? registered) + && ReferenceEquals(registered, this) + ) { + BACKENDS_BY_CONTEXT.Remove(m_contextKey); + } + } + m_disposed = true; } - internal bool TryGetWindowId( - uint viewportId, - out uint windowId + internal bool OwnsWindow(uint windowID) => m_windowToViewport.ContainsKey(windowID); + + internal bool TryGetWindowID( + uint viewportID, + out uint windowID ) { - if (m_viewportsById.TryGetValue(viewportId, out ViewportWindowData? viewport)) + if (m_viewportsByID.TryGetValue(viewportID, out ViewportWindowData? viewport)) { - windowId = viewport.windowId; + windowID = viewport.windowID; return true; } - windowId = 0; + windowID = 0; return false; } internal void ProcessEvent( ref SDLEvent sdlEvent, - uint windowId + uint windowID ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; if (eventType >= SDLEventType.DisplayFirst && eventType <= SDLEventType.DisplayLast || eventType == SDLEventType.WindowDisplayChanged - || eventType == SDLEventType.WindowDisplayScaleChanged) - { + || eventType == SDLEventType.WindowDisplayScaleChanged + ) { m_monitorsDirty = true; } - if (!m_windowToViewport.TryGetValue(windowId, out uint viewportId) - || !m_viewportsById.TryGetValue(viewportId, out ViewportWindowData? data)) - { + if (!m_windowToViewport.TryGetValue(windowID, out uint viewportID) + || !m_viewportsByID.TryGetValue(viewportID, out ViewportWindowData? data) + ) { return; } ImGuiViewport* viewport = data.viewport; if (eventType == SDLEventType.WindowCloseRequested) + { viewport->PlatformRequestClose = 1; + } if (eventType == SDLEventType.WindowMoved) + { viewport->PlatformRequestMove = 1; + } if (eventType == SDLEventType.WindowResized || eventType == SDLEventType.WindowPixelSizeChanged) + { viewport->PlatformRequestResize = 1; + } } internal void SynchronizeMetrics() @@ -174,39 +213,43 @@ internal void SynchronizeMetrics() RefreshMonitors(m_mainWindow); m_monitorsDirty = false; } - var main = ImGuiNative.Raw.GetMainViewport(); + ImGuiViewport* main = ImGuiNative.Raw.GetMainViewport(); Vector2 scale = GetWindowFramebufferScale(m_mainWindow); if (scale.X > 0 && scale.Y > 0) { main->FramebufferScale = new ImVec2C { X = scale.X, Y = scale.Y }; if (main->DpiScale == 0f) + { main->DpiScale = GetWindowDpiScale(m_mainWindow); + } + } + foreach (ViewportWindowData data in m_viewportsByID.Values) + { + SynchronizeWindow(data.windowID); } - foreach (ViewportWindowData data in m_viewportsById.Values) - SynchronizeWindow(data.windowId); } /// /// Synchronizes a secondary viewport's drawable scale and renderer output. /// - /// + /// /// The SDL window identifier owned by the viewport-> /// - internal void SynchronizeWindow(uint windowId) + internal void SynchronizeWindow(uint windowID) { - if (!m_windowToViewport.TryGetValue(windowId, out var viewportId)) + if (!m_windowToViewport.TryGetValue(windowID, out uint viewportID)) { return; } - if (!m_viewportsById.TryGetValue(viewportId, out ViewportWindowData? data)) + if (!m_viewportsByID.TryGetValue(viewportID, out ViewportWindowData? data)) { return; } ImGuiViewport* viewport = data.viewport; - var width = 0; - var height = 0; + int width = 0; + int height = 0; SDL.Raw.GetWindowSize(data.window, &width, &height); if (width <= 0 || height <= 0) { @@ -220,7 +263,9 @@ internal void SynchronizeWindow(uint windowId) if (framebufferScale.X > 0 && framebufferScale.Y > 0) { if (viewport->DpiScale == 0f) + { viewport->DpiScale = GetWindowDpiScale(data.window); + } viewport->FramebufferScale = new ImVec2C { X = framebufferScale.X, Y = framebufferScale.Y }; } int pixelWidth = 0; @@ -243,64 +288,22 @@ internal void SynchronizeWindow(uint windowId) } } - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - { - return; - } - - foreach (var kv in m_viewportsById) - { - DestroyViewportWindow(kv.Value); - } - - m_viewportsById.Clear(); - m_windowToViewport.Clear(); - if (m_retiringViewports.Count != 0) - m_renderer.DrainViewportRetirements(); - ProcessRetirements(); - if (m_retiringViewports.Count != 0) - throw new RetirementPendingException("Detached ImGui windows are still borrowed by their renderer."); - - var platformIo = ImGuiNative.Raw.GetPlatformIO(); - ImGuiPlatformIoNative.DestroyWindowCallbacks(m_windowCallbacks); - m_windowCallbacks = null; - ImGuiNative.Raw.ClearPlatformHandlers(platformIo); - ImGuiNative.Raw.ClearRendererHandlers(platformIo); - - var mainViewport = ImGuiNative.Raw.GetMainViewport(); - if (mainViewport != null) - { - mainViewport->PlatformHandle = null; - mainViewport->PlatformHandleRaw = null; - } - - lock (S_CONTEXT_SYNC) - { - if (S_BACKENDS_BY_CONTEXT.TryGetValue(m_contextKey, out PlatformImGuiViewportBackend? registered) - && ReferenceEquals(registered, this)) - { - S_BACKENDS_BY_CONTEXT.Remove(m_contextKey); - } - } - m_disposed = true; - } + private void RecordCallbackFailure(Exception failure) + => m_callbackFailure = m_callbackFailure is null + ? failure + : new AggregateException("Multiple native viewport callbacks failed in the same frame.", m_callbackFailure, failure); [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) { try { - if (viewport == null || viewport->PlatformUserData != null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) + if (viewport is null || viewport->PlatformUserData is not null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) { return; } - var flags = SDLWindowFlags.Hidden | SDLWindowFlags.Resizable | SDLWindowFlags.HighPixelDensity; + SDLWindowFlags flags = SDLWindowFlags.Hidden | SDLWindowFlags.Resizable | SDLWindowFlags.HighPixelDensity; if ((viewport->Flags & (int)ImGuiViewportFlags.NoDecoration) != 0) { flags |= SDLWindowFlags.Borderless; @@ -316,12 +319,14 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) flags |= SDLWindowFlags.AlwaysOnTop; } - var width = Math.Max(1, (int)viewport->Size.X); - var height = Math.Max(1, (int)viewport->Size.Y); + int width = Math.Max(1, (int)viewport->Size.X); + int height = Math.Max(1, (int)viewport->Size.Y); SDLWindow* window; fixed (byte* title = "ImGui\0"u8) + { window = SDL.Raw.CreateWindow((sbyte*)title, width, height, (ulong)flags); - if (window == null) + } + if (window is null) { return; } @@ -334,7 +339,7 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) if (!rendererBackend.supportsViewports) { renderer = SDL.Raw.CreateRenderer(window, null); - if (renderer == null) + if (renderer is null) { SDL.Raw.DestroyWindow(window); return; @@ -350,12 +355,14 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) } catch { - if (renderer != null) + if (renderer is not null) + { SDL.Raw.DestroyRenderer(renderer); + } SDL.Raw.DestroyWindow(window); throw; } - var data = new ViewportWindowData + var data = new ViewportWindowData { owner = backend, registeredWindow = registeredWindow, @@ -363,7 +370,7 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) drawable = true, window = window, renderer = renderer, - windowId = SDL.Raw.GetWindowId(window) + windowID = SDL.Raw.GetWindowId(window) }; try { @@ -375,17 +382,18 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) data.externalRenderer = rendererBackend; data.externalTarget = new PlatformImGuiViewportTarget( viewport->ID, - data.windowId, + data.windowID, registeredWindow.nativeHandles, pixelWidth, - pixelHeight); + pixelHeight + ); rendererBackend.CreateViewport(data.externalTarget); } data.gcHandle = GCHandle.Alloc(data, GCHandleType.Normal); - backend.m_viewportsById.Add(viewport->ID, data); - backend.m_windowToViewport.Add(data.windowId, viewport->ID); + backend.m_viewportsByID.Add(viewport->ID, data); + backend.m_windowToViewport.Add(data.windowID, viewport->ID); - var handlePtr = GCHandle.ToIntPtr(data.gcHandle); + nint handlePtr = GCHandle.ToIntPtr(data.gcHandle); viewport->PlatformUserData = (void*)handlePtr; viewport->RendererUserData = (void*)handlePtr; viewport->PlatformHandle = (void*)window; @@ -393,8 +401,8 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) } catch { - backend.m_viewportsById.Remove(viewport->ID); - backend.m_windowToViewport.Remove(data.windowId); + backend.m_viewportsByID.Remove(viewport->ID); + backend.m_windowToViewport.Remove(data.windowID); DestroyViewportWindow(data); throw; } @@ -410,15 +418,15 @@ private static void PlatformDestroyWindowCallback(ImGuiViewport* viewport) { try { - if (viewport == null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) + if (viewport is null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) { return; } - if (TryGetViewportData(viewport, out var data)) + if (TryGetViewportData(viewport, out ViewportWindowData data)) { - data.owner.m_viewportsById.Remove(viewport->ID); - data.owner.m_windowToViewport.Remove(data.windowId); + data.owner.m_viewportsByID.Remove(viewport->ID); + data.owner.m_windowToViewport.Remove(data.windowID); DestroyViewportWindow(data); } @@ -438,7 +446,7 @@ private static void PlatformShowWindowCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -460,7 +468,7 @@ float y ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -479,19 +487,19 @@ private static void PlatformGetWindowPosOutCallback( ) { try { - if (outPos == null) + if (outPos is null) { return; } - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { *outPos = default; return; } - var x = 0; - var y = 0; + int x = 0; + int y = 0; _ = SDL.Raw.GetWindowPosition(window, &x, &y); *outPos = new ImVec2C { X = x, Y = y }; } @@ -509,7 +517,7 @@ float height ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -528,19 +536,19 @@ private static void PlatformGetWindowSizeOutCallback( ) { try { - if (outSize == null) + if (outSize is null) { return; } - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { *outSize = default; return; } - var width = 0; - var height = 0; + int width = 0; + int height = 0; SDL.Raw.GetWindowSize(window, &width, &height); *outSize = new ImVec2C { X = width, Y = height }; } @@ -555,7 +563,7 @@ private static void PlatformSetWindowFocusCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -573,12 +581,12 @@ private static byte PlatformGetWindowFocusCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return 0; } - var flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); + SDLWindowFlags flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); return (flags & SDLWindowFlags.InputFocus) != 0 ? (byte)1 : (byte)0; } catch (Exception failure) @@ -593,12 +601,12 @@ private static byte PlatformGetWindowMinimizedCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return 0; } - var flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); + SDLWindowFlags flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); return (flags & SDLWindowFlags.Minimized) != 0 ? (byte)1 : (byte)0; } catch (Exception failure) @@ -615,7 +623,7 @@ private static void PlatformSetWindowTitleCallback( ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -635,7 +643,7 @@ float alpha ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -656,18 +664,20 @@ private static void RendererRenderWindowCallback( try { _ = renderArg; - if (!TryGetViewportData(viewport, out var data) || viewport == null || viewport->DrawData == null) + if (!TryGetViewportData(viewport, out ViewportWindowData data) || viewport is null || viewport->DrawData is null) { return; } - data.owner.SynchronizeWindow(data.windowId); + data.owner.SynchronizeWindow(data.windowID); if (!data.drawable) + { return; + } if (data.externalRenderer is not null && data.externalTarget is not null) { - data.externalRenderer.RenderViewport(data.externalTarget, (IntPtr)viewport->DrawData); + data.externalRenderer.RenderViewport(data.externalTarget, (nint)viewport->DrawData); } else { @@ -689,14 +699,16 @@ private static void RendererSwapBuffersCallback( try { _ = renderArg; - if (!TryGetViewportData(viewport, out var data)) + if (!TryGetViewportData(viewport, out ViewportWindowData data)) { return; } - data.owner.SynchronizeWindow(data.windowId); + data.owner.SynchronizeWindow(data.windowID); if (!data.drawable) + { return; + } if (data.externalRenderer is not null && data.externalTarget is not null) { @@ -717,13 +729,13 @@ private static bool TryGetViewportData( ImGuiViewport* viewport, out ViewportWindowData data ) { - if (viewport == null || viewport->PlatformUserData == null) + if (viewport is null || viewport->PlatformUserData is null) { data = null!; return false; } - var handle = GCHandle.FromIntPtr((IntPtr)viewport->PlatformUserData); + GCHandle handle = GCHandle.FromIntPtr((nint)viewport->PlatformUserData); if (!handle.IsAllocated || handle.Target is not ViewportWindowData windowData) { data = null!; @@ -738,13 +750,13 @@ private static bool TryGetWindow( ImGuiViewport* viewport, out SDLWindow* window ) { - if (viewport != null && viewport->PlatformHandle != null) + if (viewport is not null && viewport->PlatformHandle is not null) { window = (SDLWindow*)viewport->PlatformHandle; return true; } - if (TryGetViewportData(viewport, out var data)) + if (TryGetViewportData(viewport, out ViewportWindowData data)) { window = data.window; return true; @@ -756,22 +768,22 @@ out SDLWindow* window private static void EnsureViewportFontTexture(ViewportWindowData data) { - var io = ImGuiNative.Raw.GetIO(); - if (io->Fonts == null) + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + if (io->Fonts is null) { return; } io->Fonts->RendererHasTextures = 1; - var texData = io->Fonts->TexData; - if (texData == null) + ImTextureData* texData = io->Fonts->TexData; + if (texData is null) { return; } if (texData->Status == ImTextureStatus.WantDestroy) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; @@ -779,7 +791,7 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) data.fontTextureHeight = 0; data.fontPixelsPtr = 0; data.fontTexturePitch = 0; - data.fontTextureUniqueId = -1; + data.fontTextureUniqueID = -1; data.fontUsedRect = default; data.fontUpdateRect = default; } @@ -787,24 +799,24 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) return; } - if (texData->Pixels == null || texData->Width <= 0 || texData->Height <= 0) + if (texData->Pixels is null || texData->Width <= 0 || texData->Height <= 0) { return; } - var needsRecreate = data.fontTexture == null - || data.fontTextureWidth != texData->Width - || data.fontTextureHeight != texData->Height; + bool needsRecreate = data.fontTexture is null + || data.fontTextureWidth != texData->Width + || data.fontTextureHeight != texData->Height; if (needsRecreate) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; } data.fontTexture = CreateTexture(data.renderer, texData->Width, texData->Height); - if (data.fontTexture == null) + if (data.fontTexture is null) { data.fontTextureWidth = 0; data.fontTextureHeight = 0; @@ -815,19 +827,19 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) data.fontTextureHeight = texData->Height; } - var pitch = ImGuiNative.Raw.GetPitch(texData); - var pixelsPtr = (nint)texData->Pixels; - var uniqueId = texData->UniqueId; - var usedRect = texData->UsedRect; - var updateRect = texData->UpdateRect; - var needsUpload = needsRecreate - || data.fontPixelsPtr != pixelsPtr - || data.fontTexturePitch != pitch - || data.fontTextureUniqueId != uniqueId - || !TextureRectEquals(data.fontUsedRect, usedRect) - || !TextureRectEquals(data.fontUpdateRect, updateRect) - || texData->Status == ImTextureStatus.WantCreate - || texData->Status == ImTextureStatus.WantUpdates; + int pitch = ImGuiNative.Raw.GetPitch(texData); + nint pixelsPtr = (nint)texData->Pixels; + int uniqueID = texData->UniqueId; + ImTextureRect usedRect = texData->UsedRect; + ImTextureRect updateRect = texData->UpdateRect; + bool needsUpload = needsRecreate + || data.fontPixelsPtr != pixelsPtr + || data.fontTexturePitch != pitch + || data.fontTextureUniqueID != uniqueID + || !TextureRectEquals(data.fontUsedRect, usedRect) + || !TextureRectEquals(data.fontUpdateRect, updateRect) + || texData->Status == ImTextureStatus.WantCreate + || texData->Status == ImTextureStatus.WantUpdates; if (!needsUpload) { return; @@ -836,7 +848,7 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) _ = SDL.Raw.UpdateTexture(data.fontTexture, null, texData->Pixels, pitch); data.fontPixelsPtr = pixelsPtr; data.fontTexturePitch = pitch; - data.fontTextureUniqueId = uniqueId; + data.fontTextureUniqueID = uniqueID; data.fontUsedRect = usedRect; data.fontUpdateRect = updateRect; } @@ -846,51 +858,51 @@ private static void RenderDrawData( SDLTexture* fontTexture, ImDrawData* drawDataNative ) { - var renderer = data.renderer; - if (renderer == null || drawDataNative == null || drawDataNative->Valid == 0) + SDLRenderer* renderer = data.renderer; + if (renderer is null || drawDataNative is null || drawDataNative->Valid == 0) { return; } - var drawData = drawDataNative; + ImDrawData* drawData = drawDataNative; _ = SDL.Raw.SetRenderViewport(renderer, null); _ = SDL.Raw.SetRenderClipRect(renderer, null); _ = SDL.Raw.SetRenderDrawColor(renderer, 0, 0, 0, 0); _ = SDL.Raw.RenderClear(renderer); - var clipOff = drawData->DisplayPos; - var clipScale = drawData->FramebufferScale; - var fontTexId = ImGuiNative.Raw.GetTexID(&ImGuiNative.Raw.GetIO()->Fonts->TexRef); + ImVec2C clipOff = drawData->DisplayPos; + ImVec2C clipScale = drawData->FramebufferScale; + ulong fontTexID = ImGuiNative.Raw.GetTexID(&ImGuiNative.Raw.GetIO()->Fonts->TexRef); - for (var listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) + for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { - var drawList = drawData->CmdLists.Data[listIndex]; - if (drawList == null || drawList->VtxBuffer.Size <= 0) + ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; + if (drawList is null || drawList->VtxBuffer.Size <= 0) { continue; } - var vertexCount = drawList->VtxBuffer.Size; + int vertexCount = drawList->VtxBuffer.Size; EnsureVertexCapacity(data, vertexCount); - var srcVertices = drawList->VtxBuffer.Data; - for (var i = 0; i < vertexCount; i++) + ImDrawVert* srcVertices = drawList->VtxBuffer.Data; + for (int i = 0; i < vertexCount; i++) { data.vertexScratch[i] = ToSdlVertex(srcVertices[i], clipOff, clipScale); } - var cmdCount = drawList->CmdBuffer.Size; - for (var cmdIndex = 0; cmdIndex < cmdCount; cmdIndex++) + int cmdCount = drawList->CmdBuffer.Size; + for (int cmdIndex = 0; cmdIndex < cmdCount; cmdIndex++) { - var drawCmd = drawList->CmdBuffer.Data[cmdIndex]; - if (drawCmd.UserCallback != null || drawCmd.ElemCount == 0) + ImDrawCmd drawCmd = drawList->CmdBuffer.Data[cmdIndex]; + if (drawCmd.UserCallback is not null || drawCmd.ElemCount == 0) { continue; } - var clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; - var clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; - var clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; - var clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; + float clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; + float clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; + float clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; + float clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; if (clipRectZ <= clipRectX || clipRectW <= clipRectY) { continue; @@ -898,23 +910,27 @@ private static void RenderDrawData( var clipRect = new SDLRect { - X = (int)clipRectX, Y = (int)clipRectY, - W = (int)(clipRectZ - clipRectX), H = (int)(clipRectW - clipRectY) + X = (int)clipRectX, + Y = (int)clipRectY, + W = (int)(clipRectZ - clipRectX), + H = (int)(clipRectW - clipRectY) }; _ = SDL.Raw.SetRenderClipRect(renderer, &clipRect); - var elemCount = (int)drawCmd.ElemCount; + int elemCount = (int)drawCmd.ElemCount; EnsureIndexCapacity(data, elemCount); - var srcIndices = drawList->IdxBuffer.Data; - var idxOffset = (int)drawCmd.IdxOffset; - var vtxOffset = (int)drawCmd.VtxOffset; - for (var i = 0; i < elemCount; i++) + ushort* srcIndices = drawList->IdxBuffer.Data; + int idxOffset = (int)drawCmd.IdxOffset; + int vtxOffset = (int)drawCmd.VtxOffset; + for (int i = 0; i < elemCount; i++) { data.indexScratch[i] = srcIndices[idxOffset + i] + vtxOffset; } - var texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexId ? fontTexture : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); - if (texture == null) + SDLTexture* texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexID + ? fontTexture + : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); + if (texture is null) { texture = fontTexture; } @@ -932,7 +948,7 @@ private static void RenderDrawData( private static void FocusWindow(SDLWindow* window) { - if (window != null) + if (window is not null) { _ = SDL.Raw.RaiseWindow(window); } @@ -941,13 +957,13 @@ private static void FocusWindow(SDLWindow* window) private static PlatformImGuiViewportBackend GetCurrentBackend() { ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); - if (context == null) + if (context is null) + { throw new InvalidOperationException("No ImGui context is active for a viewport callback."); - lock (S_CONTEXT_SYNC) + } + lock (CONTEXT_SYNC) { - if (S_BACKENDS_BY_CONTEXT.TryGetValue( - (nuint)context, - out PlatformImGuiViewportBackend? backend)) + if (BACKENDS_BY_CONTEXT.TryGetValue((nuint)context, out PlatformImGuiViewportBackend? backend)) { return backend; } @@ -957,16 +973,12 @@ private static PlatformImGuiViewportBackend GetCurrentBackend() private static void SynchronizeRendererOutput(SDLRenderer* renderer) { - if (renderer == null) + if (renderer is null) { return; } - _ = SDL.Raw.SetRenderLogicalPresentation( - renderer, - 0, - 0, - SDLRendererLogicalPresentation.Disabled); + _ = SDL.Raw.SetRenderLogicalPresentation(renderer, 0, 0, SDLRendererLogicalPresentation.Disabled); _ = SDL.Raw.SetRenderViewport(renderer, null); _ = SDL.Raw.SetRenderClipRect(renderer, null); } @@ -1000,15 +1012,15 @@ int required int width, int height ) { - var props = SDL.CreateProperties(); + uint props = SDL.CreateProperties(); try { _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, (long)SDLPixelFormat.Rgba32); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, (long)SDLTextureAccess.Static); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, width); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, height); - var texture = SDL.Raw.CreateTextureWithProperties(renderer, props); - if (texture != null) + SDLTexture* texture = SDL.Raw.CreateTextureWithProperties(renderer, props); + if (texture is not null) { _ = SDL.Raw.SetTextureBlendMode(texture, SDL.Constants.SDL_BLENDMODE_BLEND); _ = SDL.Raw.SetTextureScaleMode(texture, SDLScaleMode.Linear); @@ -1024,16 +1036,16 @@ int height private static Vector2 GetWindowFramebufferScale(SDLWindow* window) { - var windowWidth = 0; - var windowHeight = 0; + int windowWidth = 0; + int windowHeight = 0; SDL.Raw.GetWindowSize(window, &windowWidth, &windowHeight); if (windowWidth <= 0 || windowHeight <= 0) { return Vector2.Zero; } - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; SDL.Raw.GetWindowSizeInPixels(window, &pixelWidth, &pixelHeight); return new Vector2(pixelWidth / (float)windowWidth, pixelHeight / (float)windowHeight); } @@ -1043,8 +1055,12 @@ private static float GetWindowDpiScale(SDLWindow* window) // ImGui's DPI value is in logical coordinates; pixel density belongs to FramebufferScale. float scale = SDL.Raw.GetWindowDisplayScale(window) / SDL.Raw.GetWindowPixelDensity(window); if (!float.IsFinite(scale) || scale <= 0f) - throw new InvalidOperationException("SDL could not resolve the live window's display scale: " - + Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError())); + { + throw new InvalidOperationException( + "SDL could not resolve the live window's display scale: " + + Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) + ); + } return scale; } @@ -1053,9 +1069,9 @@ private static SDLVertex ToSdlVertex( ImVec2C displayPos, ImVec2C framebufferScale ) { - var color = ImGuiPackedColor.ToSdlFColor(vtx.Col); - var x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; - var y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; + SDLFColor color = ImGuiPackedColor.ToSdlFColor(vtx.Col); + float x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; + float y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; return new SDLVertex { @@ -1065,22 +1081,39 @@ ImVec2C framebufferScale }; } - private static SDLTexture* TextureFromImGui(ulong textureId) - { - return (SDLTexture*)(nuint)textureId; - } + private static SDLTexture* TextureFromImGui(ulong textureID) => (SDLTexture*)(nuint)textureID; private static bool TextureRectEquals( ImTextureRect a, ImTextureRect b - ) { - return a.X == b.X - && a.Y == b.Y - && a.W == b.W - && a.H == b.H; - } - - private void RecordCallbackFailure(Exception failure) => m_callbackFailure = m_callbackFailure is null - ? failure : new AggregateException("Multiple native viewport callbacks failed in the same frame.", m_callbackFailure, failure); + ) => a.X == b.X + && a.Y == b.Y + && a.W == b.W + && a.H == b.H; + private sealed class ViewportWindowData + { + internal required PlatformImGuiViewportBackend owner; + internal required Sdl3PlatformWindow registeredWindow; + internal ImGuiViewport* viewport; + internal bool drawable; + internal Task? retirement; + internal bool detached; + internal SDLWindow* window; + internal SDLRenderer* renderer; + internal IPlatformImGuiRenderer? externalRenderer; + internal PlatformImGuiViewportTarget? externalTarget; + internal SDLTexture* fontTexture; + internal int fontTextureWidth; + internal int fontTextureHeight; + internal nint fontPixelsPtr; + internal int fontTexturePitch; + internal int fontTextureUniqueID = -1; + internal ImTextureRect fontUsedRect; + internal ImTextureRect fontUpdateRect; + internal uint windowID; + internal GCHandle gcHandle; + internal SDLVertex[] vertexScratch = []; + internal int[] indexScratch = []; + } } diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs index 4d667bf36..8cadc8794 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs @@ -21,7 +21,7 @@ public sealed class NativeDeploymentIndex /// /// Freezes one product target and its explicit aliases without detecting the host OS. /// - /// + /// /// The exact deployment target selected by the product. /// /// @@ -37,12 +37,12 @@ public sealed class NativeDeploymentIndex /// A mapping is absent. /// public NativeDeploymentIndex( - string targetId, + string targetID, IReadOnlyDictionary libraries, IReadOnlyDictionary files ) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - this.targetId = targetId; + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + this.targetID = targetID; this.libraries = Freeze(libraries); this.files = Freeze(files); } @@ -50,7 +50,7 @@ IReadOnlyDictionary files /// /// Gets the explicit product target, without reconstructing it from OS or CPU names. /// - public string targetId { get; } + public string targetID { get; } /// /// Gets immutable logical library mappings selected by composition. @@ -74,7 +74,7 @@ public byte[] Encode() using (var writer = new Utf8JsonWriter(stream)) { writer.WriteStartObject(); - writer.WriteString("targetId", targetId); + writer.WriteString("targetId", targetID); WriteMapping(writer, "libraries", libraries); WriteMapping(writer, "files", files); writer.WriteEndObject(); @@ -82,36 +82,6 @@ public byte[] Encode() return stream.ToArray(); } - /// - /// Reads only the current index format and validates its complete path mappings. - /// - /// - /// Complete encoded bytes borrowed for this call. - /// - /// - /// An immutable layout; malformed or incomplete input is rejected. - /// - /// - /// The index is malformed, incomplete or contains invalid mappings. - /// - public static NativeDeploymentIndex Decode(ReadOnlySpan bytes) - { - try - { - using JsonDocument document = JsonDocument.Parse(bytes.ToArray()); - JsonElement root = document.RootElement; - string[] names = root.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal).ToArray(); - if (!names.SequenceEqual(new[] { "files", "libraries", "targetId" }, StringComparer.Ordinal)) - throw new InvalidDataException("The native deployment index must contain its exact current fields."); - return new(root.GetProperty("targetId").GetString()!, ReadMapping(root.GetProperty("libraries")), - ReadMapping(root.GetProperty("files"))); - } - catch (Exception failure) when (failure is JsonException or ArgumentException or InvalidOperationException) - { - throw new InvalidDataException("The native deployment index is malformed or incomplete.", failure); - } - } - /// /// Resolves a selected library without scanning directories or guessing suffixes. /// @@ -133,8 +103,10 @@ string name ) { string file = Resolve(nativeDirectory, name, libraries); if (!OperatingSystem.IsWindows() || file.StartsWith(@"\\?\", StringComparison.Ordinal) - || file.StartsWith(@"\\.\", StringComparison.Ordinal)) + || file.StartsWith(@"\\.\", StringComparison.Ordinal) + ) { return file; + } // Windows native loading can reject ordinary paths even below MAX_PATH. // Apply loading syntax only after validating the actual deployment boundary. return file.StartsWith(@"\\", StringComparison.Ordinal) ? @"\\?\UNC\" + file[2..] : @"\\?\" + file; @@ -160,6 +132,41 @@ public string ResolveFile( string name ) => Resolve(nativeDirectory, name, files); + /// + /// Reads only the current index format and validates its complete path mappings. + /// + /// + /// Complete encoded bytes borrowed for this call. + /// + /// + /// An immutable layout; malformed or incomplete input is rejected. + /// + /// + /// The index is malformed, incomplete or contains invalid mappings. + /// + public static NativeDeploymentIndex Decode(ReadOnlySpan bytes) + { + try + { + using JsonDocument document = JsonDocument.Parse(bytes.ToArray()); + JsonElement root = document.RootElement; + string[] names = root.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal).ToArray(); + if (!names.SequenceEqual(["files", "libraries", "targetId"], StringComparer.Ordinal)) + { + throw new InvalidDataException("The native deployment index must contain its exact current fields."); + } + return new( + root.GetProperty("targetId").GetString()!, + ReadMapping(root.GetProperty("libraries")), + ReadMapping(root.GetProperty("files")) + ); + } + catch (Exception failure) when (failure is JsonException or ArgumentException or InvalidOperationException) + { + throw new InvalidDataException("The native deployment index is malformed or incomplete.", failure); + } + } + private static IReadOnlyDictionary Freeze(IReadOnlyDictionary mapping) { ArgumentNullException.ThrowIfNull(mapping); @@ -168,8 +175,10 @@ private static IReadOnlyDictionary Freeze(IReadOnlyDictionary= 0 || alias is "." or ".." || string.IsNullOrWhiteSpace(path) || path.Contains('\\') - || path.Contains(':') || path.Split('/').Any(static part => part is "" or "." or "..")) + || path.Contains(':') || path.Split('/').Any(static part => part is "" or "." or "..") + ) { throw new ArgumentException("Native deployment aliases and paths must be assigned and portable.", nameof(mapping)); + } result.Add(alias, path); } return new ReadOnlyDictionary(result); @@ -182,15 +191,21 @@ IReadOnlyDictionary mapping ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!mapping.TryGetValue(name, out string? relative)) + { throw new FileNotFoundException($"No native deployment entry is registered for '{name}'."); + } string file = PathBoundary.RequireUnlinkedPath(directory, PathBoundary.Resolve(directory, relative)); if (!File.Exists(file)) + { throw new FileNotFoundException("An explicitly deployed native payload is absent.", file); + } return file; } private static IReadOnlyDictionary ReadMapping(JsonElement element) - => element.EnumerateObject().ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); + => element + .EnumerateObject() + .ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); private static void WriteMapping( Utf8JsonWriter writer, @@ -199,7 +214,9 @@ IReadOnlyDictionary mapping ) { writer.WriteStartObject(name); foreach ((string alias, string path) in mapping) + { writer.WriteString(alias, path); + } writer.WriteEndObject(); } } diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllConstants.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllConstants.cs index cb8dee784..0e3385c42 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllConstants.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllConstants.cs @@ -8,5 +8,5 @@ public static class NativeDllConstants /// /// Output folder name for native binaries. /// - public const string NATIVE_DIR_NAME = "native"; + public const string C_NATIVE_DIR_NAME = "native"; } diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs index 94643755f..6e1a35366 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs @@ -32,7 +32,7 @@ public static class NativeDllLoader public static string FindNativeLibrary(string libraryName) { ValidateFileName(libraryName, nameof(libraryName)); - string nativeRoot = Path.Combine(S_OUTPUT_ROOT, NativeDllConstants.NATIVE_DIR_NAME); + string nativeRoot = Path.Combine(S_OUTPUT_ROOT, NativeDllConstants.C_NATIVE_DIR_NAME); return ReadIndex(nativeRoot).ResolveLibrary(nativeRoot, libraryName); } @@ -57,7 +57,7 @@ public static string FindNativeLibrary(string libraryName) public static string FindNativeFile(string fileName) { ValidateFileName(fileName, nameof(fileName)); - string nativeRoot = Path.Combine(S_OUTPUT_ROOT, NativeDllConstants.NATIVE_DIR_NAME); + string nativeRoot = Path.Combine(S_OUTPUT_ROOT, NativeDllConstants.C_NATIVE_DIR_NAME); return ReadIndex(nativeRoot).ResolveFile(nativeRoot, fileName); } @@ -65,12 +65,20 @@ private static NativeDeploymentIndex ReadIndex(string nativeRoot) { string path = Path.Combine(nativeRoot, NativeDeploymentIndex.C_FILE_NAME); if (!File.Exists(path)) - throw new FileNotFoundException("The product has no explicit native deployment index. Prepare the product before starting it.", path); + { + throw new FileNotFoundException( + "The product has no explicit native deployment index. Prepare the product before starting it.", + path + ); + } return NativeDeploymentIndex.Decode(File.ReadAllBytes(path)); } - [UnconditionalSuppressMessage("SingleFile", "IL3000", - Justification = "Assembly-local outputs serve isolated hosts; an empty bundled assembly location explicitly selects the application directory.")] + [UnconditionalSuppressMessage( + "SingleFile", + "IL3000", + Justification = "Assembly-local outputs serve isolated hosts; an empty bundled assembly location explicitly selects the application directory." + )] private static string ResolveOutputRoot() { string location = typeof(NativeDllLoader).Assembly.Location; @@ -83,8 +91,9 @@ string parameterName ) { ArgumentException.ThrowIfNullOrWhiteSpace(fileName, parameterName); if (fileName is "." or ".." || fileName != Path.GetFileName(fileName) - || fileName.IndexOfAny(['*', '?', '/', '\\']) >= 0) + || fileName.IndexOfAny(['*', '?', '/', '\\']) >= 0 + ) { throw new ArgumentException("Native discovery requires an exact file name.", parameterName); + } } - } diff --git a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs index 34301810c..d3dead361 100644 --- a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs +++ b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs @@ -12,7 +12,7 @@ namespace Inno.Build.Toolchains.MiniAudio; /// public static class MiniAudioToolchain { - private static readonly string[] S_ARGUMENTS = ["-DBUILD_SHARED_LIBS=ON", "-DMINIAUDIO_BUILD_EXAMPLES=OFF", + private static readonly string[] ARGUMENTS = ["-DBUILD_SHARED_LIBS=ON", "-DMINIAUDIO_BUILD_EXAMPLES=OFF", "-DMINIAUDIO_BUILD_TESTS=OFF", "-DMINIAUDIO_BUILD_TOOLS=OFF", "-DMINIAUDIO_NO_EXTRA_NODES=ON", "-DMINIAUDIO_INSTALL=OFF"]; /// @@ -25,8 +25,10 @@ public static class MiniAudioToolchain new NativeStaticBuildDefinition( "backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/Native/StaticLibraries.cmake", ["extern/miniaudio"], - ["libminiaudio"]), - bindingDefinition: "backends/MiniAudio/native/Inno.Native.MiniAudio/Bindings/bindings.props"); + ["libminiaudio"] + ), + bindingDefinition: "backends/MiniAudio/native/Inno.Native.MiniAudio/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -54,26 +56,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = componentDescriptor.GetToolchainRoot(context.engineRoot); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "miniaudio", S_ARGUMENTS, token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "miniaudio", + ARGUMENTS, + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*miniaudio" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -102,10 +119,20 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } string implementation = componentDescriptor.GetToolchainRoot(context.engineRoot); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "miniaudio", selection.targetId, - [Path.Combine(context.engineRoot, "extern", "miniaudio"), Path.Combine(implementation, "CMakeLists.txt")], S_ARGUMENTS, - [Path.Combine(implementation, "MiniAudioToolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "miniaudio", + selection.targetID, + [Path.Combine(context.engineRoot, "extern", "miniaudio"), Path.Combine(implementation, "CMakeLists.txt")], + ARGUMENTS, + [Path.Combine(implementation, "MiniAudioToolchain.cs")] + ); } } diff --git a/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs b/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs index ff47c4515..5255d09ba 100644 --- a/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs +++ b/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs @@ -8,9 +8,9 @@ namespace Inno.Native.MiniAudio; public static unsafe partial class MiniAudio { #if DEBUG - internal const string LibName = "miniaudio-debug"; + internal const string C_LIB_NAME = "miniaudio-debug"; #else - internal const string LibName = "miniaudio-release"; + internal const string C_LIB_NAME = "miniaudio-release"; #endif static MiniAudio() @@ -20,7 +20,7 @@ static MiniAudio() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs index f9f27cd9b..88cf17961 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs @@ -11,12 +11,10 @@ public sealed class MiniAudioBackendProvider : AudioBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public MiniAudioBackendProvider() : base(AudioBackendId.miniAudio) { } + public MiniAudioBackendProvider() + : base(AudioBackendID.miniAudio) {} - /// + /// public override IAudioDevice CreateDevice(AudioBackendOptions options) - { - return new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = options.noDevice }); - } + => new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = options.noDevice }); } - diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs index e5ca77713..afc2211aa 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs @@ -18,14 +18,15 @@ internal MiniAudioClipPreparation( string path, SemaphoreSlim slots ) { - contentHash = source.contentHash.ToUpperInvariant(); - length = source.length; + this.contentHash = source.contentHash.ToUpperInvariant(); + this.length = source.length; this.path = path; try { using AsyncFlowControl? suppression = ExecutionContext.IsFlowSuppressed() - ? null : ExecutionContext.SuppressFlow(); - completion = Task.Run(() => PrepareAsync(source, slots), CancellationToken.None); + ? null + : ExecutionContext.SuppressFlow(); + this.completion = Task.Run(() => PrepareAsync(source, slots), CancellationToken.None); } catch { @@ -34,25 +35,29 @@ SemaphoreSlim slots } } - internal string contentHash { get; } - internal long length { get; } - internal string path { get; } - internal Task completion { get; } - internal int references { get; set; } - - internal void Cancel() => m_cancellation.Cancel(); - - /// + /// public void Dispose() { if (!completion.IsCompleted) + { throw new InvalidOperationException("Encoded preparation must drain before releasing its owner."); + } _ = completion.Exception; if (File.Exists(path)) + { File.Delete(path); + } m_cancellation.Dispose(); } + internal string contentHash { get; } + internal long length { get; } + internal string path { get; } + internal Task completion { get; } + internal int references { get; set; } + + internal void Cancel() => m_cancellation.Cancel(); + private async Task PrepareAsync( IAudioClipSource source, SemaphoreSlim slots @@ -70,21 +75,30 @@ SemaphoreSlim slots Directory.CreateDirectory(Path.GetDirectoryName(path)!); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); long copied = 0; - using (var output = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, - FileShare.None, buffer.Length, FileOptions.Asynchronous)) - { + using (var output = new FileStream( + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + buffer.Length, + FileOptions.Asynchronous + )) { int count; while ((count = await reader.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) != 0) { copied = checked(copied + count); if (copied > length) + { throw new InvalidDataException("Encoded audio exceeds its declared length."); + } hash.AppendData(buffer, 0, count); await output.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); } - if (copied != length || !string.Equals(Convert.ToHexString(hash.GetHashAndReset()), - contentHash, StringComparison.Ordinal)) - { + if (copied != length || !string.Equals( + Convert.ToHexString(hash.GetHashAndReset()), + contentHash, + StringComparison.Ordinal + )) { throw new InvalidDataException("Encoded audio does not match its content identity."); } await output.FlushAsync(cancellationToken).ConfigureAwait(false); @@ -97,7 +111,9 @@ SemaphoreSlim slots try { if (File.Exists(candidate)) + { File.Delete(candidate); + } } finally { diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs index ac935ab83..4ec652300 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs @@ -14,12 +14,12 @@ MiniAudioClipPreparation preparation this.preparation = preparation; } - internal MiniAudioClipPreparation preparation { get; } - - /// + /// public void Dispose() { m_owner?.Release(preparation); m_owner = null; } + + internal MiniAudioClipPreparation preparation { get; } } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs index 3bf3685c3..d3f887d6f 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs @@ -4,9 +4,9 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; - using Inno.Audio; using Inno.Native.MiniAudio; + using NativeApi = Inno.Native.MiniAudio.MiniAudio; namespace Inno.Adapter.Audio.MiniAudio; @@ -18,7 +18,7 @@ public sealed unsafe class MiniAudioDevice : AudioDevice, IAudioDevice { private const uint C_PROCESS_BLOCK_FRAMES = 4096; - private static int S_NEXT_GENERATION; + private static int s_nextGeneration; private readonly Dictionary m_buses = []; private readonly Dictionary m_clips = []; @@ -42,9 +42,7 @@ public sealed unsafe class MiniAudioDevice : AudioDevice, IAudioDevice /// Creates a MiniAudio device using the default operating-system output device. /// public MiniAudioDevice() - : this(new MiniAudioDeviceOptions()) - { - } + : this(new MiniAudioDeviceOptions()) {} /// /// Creates one MiniAudio backend generation with explicit output and headless settings. @@ -57,8 +55,9 @@ public MiniAudioDevice() /// public MiniAudioDevice(MiniAudioDeviceOptions options) { - m_options = (options ?? throw new ArgumentNullException(nameof(options))).Validate(); - generation = NextGeneration(); + ArgumentNullException.ThrowIfNull(options); + m_options = (options).Validate(); + this.generation = NextGeneration(); m_state = AudioDeviceState.Initializing; m_engine = (MaEngine*)NativeMemory.AllocZeroed((nuint)sizeof(MaEngine)); @@ -71,15 +70,18 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) config.NoDevice = m_options.noDevice ? 1u : 0u; MaResult result = NativeApi.Raw.EngineInit(&config, m_engine); if (result != MaResult.MA_SUCCESS) + { throw new InvalidOperationException($"MiniAudio engine initialization failed with result '{result}'."); + } m_engineInitialized = true; int actualSampleRate = checked((int)NativeApi.Raw.EngineGetSampleRate(m_engine)); - capabilities = new AudioCapabilities(true, true, true, m_options.listenerCount, actualSampleRate); + this.capabilities = new AudioCapabilities(true, true, true, m_options.listenerCount, actualSampleRate); if (m_options.noDevice) { m_processBuffer = (float*)NativeMemory.AllocZeroed( - checked((nuint)(C_PROCESS_BLOCK_FRAMES * (uint)m_options.channels * sizeof(float)))); + checked((nuint)(C_PROCESS_BLOCK_FRAMES * (uint)m_options.channels * sizeof(float))) + ); m_state = AudioDeviceState.Muted; } else @@ -90,7 +92,9 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) catch { if (m_engineInitialized) + { NativeApi.Raw.EngineUninit(m_engine); + } NativeMemory.Free(m_engine); throw; } @@ -116,8 +120,8 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) /// public double dspTime => m_engineInitialized - ? NativeApi.Raw.EngineGetTimeInPcmFrames(m_engine) / (double)capabilities.sampleRate - : 0d; + ? NativeApi.Raw.EngineGetTimeInPcmFrames(m_engine) / (double)capabilities.sampleRate + : 0d; /// /// Gets current native resource counts and approximate decoded storage. @@ -129,7 +133,53 @@ public AudioStatistics statistics m_clips.Values .Where(static descriptor => descriptor.loadMode == AudioClipLoadMode.Decode) .Sum(EstimateDecodedByteLength), - 0); + 0 + ); + + /// + /// Releases all sounds, buses, processor nodes, listeners, and the native engine in dependency order. + /// + /// + /// Canceled encoded preparation still owns a source reader. The owner must retain this device + /// and retry disposal at its retirement safe point until preparation drains. + /// + public void Dispose() + { + if (m_state == AudioDeviceState.Disposed) + { + return; + } + + foreach (VoiceRecord voice in m_voices.Values.ToArray()) + { + ReleaseVoice(voice); + } + m_voices.Clear(); + + m_encodedArtifacts.CancelPreparation(); + foreach (ulong identity in m_clips.Keys.ToArray()) + { + ReleaseClipSource(identity); + m_clips.Remove(identity); + } + m_encodedArtifacts.Dispose(); + + foreach (BusRecord bus in m_buses.Values.OrderByDescending(GetBusDepth).ToArray()) + { + ReleaseBus(bus); + } + m_buses.Clear(); + + if (m_engineInitialized) + { + NativeApi.Raw.EngineUninit(m_engine); + m_engineInitialized = false; + } + NativeMemory.Free(m_processBuffer); + NativeMemory.Free(m_engine); + m_state = AudioDeviceState.Disposed; + GC.SuppressFinalize(this); + } AudioClipHandle IAudioDevice.CreateClip( AudioClipDescriptor descriptor, @@ -138,10 +188,12 @@ IAudioClipSource source EnsureActive(); ArgumentNullException.ThrowIfNull(source); if (m_clips.Count >= m_options.limits.clips) + { return default; + } if (!descriptor.codec.isValid || descriptor.channels <= 0 || descriptor.sampleRate <= 0 - || descriptor.encodedByteLength != source.length || !Enum.IsDefined(descriptor.loadMode)) - { + || descriptor.encodedByteLength != source.length || !Enum.IsDefined(descriptor.loadMode) + ) { throw new ArgumentException("An audio descriptor must match its immutable source.", nameof(descriptor)); } MiniAudioClipSourceLease lease = m_encodedArtifacts.Acquire(source); @@ -151,69 +203,17 @@ IAudioClipSource source return CreateClipHandle(identity, generation); } - private bool PrepareNativeClip(ulong identity) - { - if (m_clipSources.ContainsKey(identity)) - return true; - if (m_failedClips.Contains(identity)) - return false; - MiniAudioClipPreparation preparation = m_clipPreparations[identity].preparation; - if (!preparation.completion.IsCompletedSuccessfully) - { - if (preparation.completion.IsCompleted) - { - _ = preparation.completion.Exception; - m_failedClips.Add(identity); - } - return false; - } - AudioClipDescriptor descriptor = m_clips[identity]; - MaResourceManagerDataSource* source = (MaResourceManagerDataSource*)NativeMemory.AllocZeroed( - (nuint)sizeof(MaResourceManagerDataSource)); - uint flags = (uint)(MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC | - (descriptor.loadMode == AudioClipLoadMode.Stream - ? MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM : MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE)); - MaResult result; - try - { - int pathByteCount = Encoding.UTF8.GetByteCount(preparation.path); - Span pathBytes = pathByteCount < 1024 - ? stackalloc byte[1024] : new byte[checked(pathByteCount + 1)]; - Encoding.UTF8.GetBytes(preparation.path, pathBytes); - pathBytes[pathByteCount] = 0; - fixed (byte* pathPointer = pathBytes) - { - // The resource manager copies the path before scheduling asynchronous IO. - result = NativeApi.Raw.ResourceManagerDataSourceInit( - NativeApi.Raw.EngineGetResourceManager(m_engine), - (sbyte*)pathPointer, - flags, - null, - source); - } - } - catch - { - NativeMemory.Free(source); - throw; - } - if (result != MaResult.MA_SUCCESS) - { - NativeMemory.Free(source); - m_failedClips.Add(identity); - return false; - } - m_clipSources.Add(identity, (nint)source); - return true; - } - AudioClipState IAudioDevice.GetClipState(AudioClipHandle clip) { DeviceHandleIdentity identity = GetHandleIdentity(clip); if (identity.generation != generation || !m_clips.ContainsKey(identity.value)) + { return AudioClipState.Failed; + } if (!PrepareNativeClip(identity.value)) + { return m_failedClips.Contains(identity.value) ? AudioClipState.Failed : AudioClipState.Preparing; + } nint pointer = m_clipSources[identity.value]; return NativeApi.Raw.ResourceManagerDataSourceResult((MaResourceManagerDataSource*)pointer) switch { @@ -227,13 +227,15 @@ bool IAudioDevice.DestroyClip(AudioClipHandle clip) { EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(clip); - if (identity.generation != generation || - m_voices.Values.Any(voice => voice.clipIdentity == identity.value)) - { + if (identity.generation != generation + || m_voices.Values.Any(voice => voice.clipIdentity == identity.value) + ) { return false; } if (!m_clips.ContainsKey(identity.value)) + { return false; + } ReleaseClipSource(identity.value); m_clips.Remove(identity.value); return true; @@ -247,34 +249,45 @@ AudioDeviceVoiceHandle IAudioDevice.Play( ) { EnsureActive(); if (m_voices.Count + m_completions.Count >= m_options.limits.voices) + { return default; + } if (!options.bus.isValid) + { return default; + } DeviceHandleIdentity clipIdentity = GetHandleIdentity(clip); DeviceHandleIdentity busIdentity = GetHandleIdentity(bus); if (clipIdentity.generation != generation || !m_clips.TryGetValue(clipIdentity.value, out AudioClipDescriptor descriptor)) + { return default; + } if (!PrepareNativeClip(clipIdentity.value)) + { return default; + } if (busIdentity.generation != generation || !m_buses.TryGetValue(busIdentity.value, out BusRecord? busRecord)) - return default; - if (scheduledDspTime is double startTime && - (double.IsNaN(startTime) || double.IsInfinity(startTime) || startTime < 0d)) { return default; } + if (scheduledDspTime is double startTime + && (double.IsNaN(startTime) || double.IsInfinity(startTime) || startTime < 0d) + ) { + return default; + } string path = m_clipPreparations[clipIdentity.value].preparation.path; int pathByteCount = Encoding.UTF8.GetByteCount(path); Span pathBytes = pathByteCount < 1024 - ? stackalloc byte[1024] : new byte[checked(pathByteCount + 1)]; + ? stackalloc byte[1024] + : new byte[checked(pathByteCount + 1)]; Encoding.UTF8.GetBytes(path, pathBytes); pathBytes[pathByteCount] = 0; MaSound* sound = (MaSound*)NativeMemory.AllocZeroed((nuint)sizeof(MaSound)); MaSound* soundPointer = sound; uint flags = descriptor.loadMode == AudioClipLoadMode.Stream - ? (uint)MaSoundFlags.MA_SOUND_FLAG_STREAM - : (uint)MaSoundFlags.MA_SOUND_FLAG_DECODE; + ? (uint)MaSoundFlags.MA_SOUND_FLAG_STREAM + : (uint)MaSoundFlags.MA_SOUND_FLAG_DECODE; flags |= (uint)MaSoundFlags.MA_SOUND_FLAG_ASYNC; MaResult initResult; try @@ -287,7 +300,8 @@ AudioDeviceVoiceHandle IAudioDevice.Play( flags, busRecord.group, null, - soundPointer); + soundPointer + ); } } catch @@ -310,7 +324,8 @@ AudioDeviceVoiceHandle IAudioDevice.Play( { NativeApi.Raw.SoundSetStartTimeInPcmFrames( soundPointer, - checked((ulong)Math.Round(scheduled * capabilities.sampleRate))); + checked((ulong)Math.Round(scheduled * capabilities.sampleRate)) + ); playbackState = AudioPlaybackState.Scheduled; } @@ -337,7 +352,9 @@ AudioDeviceVoiceHandle IAudioDevice.Play( bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out ulong identity, out VoiceRecord record)) + { return false; + } NativeApi.Raw.SoundStop(record.sound); CompleteVoice(identity, record, AudioCompletionReason.Stopped); return true; @@ -346,9 +363,13 @@ bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out _, out VoiceRecord record) || record.state == AudioPlaybackState.Paused) + { return false; + } if (NativeApi.Raw.SoundStop(record.sound) != MaResult.MA_SUCCESS) + { return false; + } record.state = AudioPlaybackState.Paused; return true; } @@ -356,12 +377,16 @@ bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) bool IAudioDevice.Resume(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out _, out VoiceRecord record) || record.state != AudioPlaybackState.Paused) + { return false; + } if (NativeApi.Raw.SoundStart(record.sound) != MaResult.MA_SUCCESS) + { return false; + } record.state = record.scheduledDspTime is double scheduled && scheduled > dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; return true; } @@ -370,7 +395,9 @@ bool IAudioDevice.Seek( TimeSpan position ) { if (position < TimeSpan.Zero || !TryGetVoice(voice, out _, out VoiceRecord record)) + { return false; + } ulong frame = checked((ulong)Math.Round(position.TotalSeconds * capabilities.sampleRate)); return NativeApi.Raw.SoundSeekToPcmFrame(record.sound, frame) == MaResult.MA_SUCCESS; } @@ -380,9 +407,13 @@ bool IAudioDevice.SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!TryGetVoice(voice, out _, out VoiceRecord record)) + { return false; + } ApplyVoiceParameters(record.sound, parameters); return true; } @@ -394,7 +425,8 @@ out AudioPlaybackState playbackState if (TryGetVoice(voice, out _, out VoiceRecord record)) { MaResult preparation = NativeApi.Raw.ResourceManagerDataSourceResult( - record.sound->PResourceManagerDataSource); + record.sound->PResourceManagerDataSource + ); playbackState = preparation == MaResult.MA_BUSY ? AudioPlaybackState.Preparing : record.state; return true; } @@ -403,21 +435,25 @@ out AudioPlaybackState playbackState } AudioBusHandle IAudioDevice.CreateBus( - AudioBusId id, + AudioBusID id, AudioBusHandle parent ) { EnsureActive(); if (!id.isValid || m_buses.Count >= m_options.limits.buses) + { return default; + } BusRecord? parentRecord = null; if (parent.isValid) { DeviceHandleIdentity parentIdentity = GetHandleIdentity(parent); if (parentIdentity.generation != generation || !m_buses.TryGetValue(parentIdentity.value, out parentRecord)) + { return default; + } } - else if (id != AudioBusId.master) + else if (id != AudioBusID.master) { return default; } @@ -427,7 +463,8 @@ AudioBusHandle parent m_engine, 0, parentRecord is null ? null : parentRecord.group, - group); + group + ); if (result != MaResult.MA_SUCCESS) { NativeMemory.Free(group); @@ -436,8 +473,8 @@ AudioBusHandle parent ulong identity = m_nextIdentity++; void* target = parentRecord is null - ? NativeApi.Raw.EngineGetEndpoint(m_engine) - : parentRecord.group; + ? NativeApi.Raw.EngineGetEndpoint(m_engine) + : parentRecord.group; m_buses.Add(identity, new BusRecord(id, parentRecord, group, target)); return CreateBusHandle(identity, generation); } @@ -446,12 +483,14 @@ bool IAudioDevice.DestroyBus(AudioBusHandle bus) { EnsureActive(); if (!TryGetBus(bus, out ulong identity, out BusRecord record)) - return false; - if (m_buses.Values.Any(candidate => candidate.parent == record) || - m_voices.Values.Any(voice => voice.bus == record)) { return false; } + if (m_buses.Values.Any(candidate => candidate.parent == record) + || m_voices.Values.Any(voice => voice.bus == record) + ) { + return false; + } ReleaseBus(record); m_buses.Remove(identity); return true; @@ -462,7 +501,9 @@ bool IAudioDevice.SetBusVolume( float volume ) { if (!float.IsFinite(volume) || volume < 0f || !TryGetBus(bus, out _, out BusRecord record)) + { return false; + } record.volume = volume; ApplyBusVolume(record); return true; @@ -473,7 +514,9 @@ bool IAudioDevice.SetBusMuted( bool muted ) { if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } record.muted = muted; ApplyBusVolume(record); return true; @@ -484,14 +527,20 @@ bool IAudioDevice.SetBusPaused( bool paused ) { if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } if (record.paused == paused) + { return true; + } MaResult result = paused - ? NativeApi.Raw.SoundGroupStop(record.group) - : NativeApi.Raw.SoundGroupStart(record.group); + ? NativeApi.Raw.SoundGroupStop(record.group) + : NativeApi.Raw.SoundGroupStart(record.group); if (result != MaResult.MA_SUCCESS) + { return false; + } record.paused = paused; return true; } @@ -502,15 +551,19 @@ AudioProcessorConfiguration processor ) { ArgumentNullException.ThrowIfNull(processor); if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } NativeProcessor? nativeProcessor = CreateProcessor(processor); if (nativeProcessor is null) + { return false; + } - if (NativeApi.Raw.NodeDetachOutputBus(record.tail, 0) != MaResult.MA_SUCCESS || - NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, nativeProcessor.node, 0) != MaResult.MA_SUCCESS || - NativeApi.Raw.NodeAttachOutputBus(nativeProcessor.node, 0, record.target, 0) != MaResult.MA_SUCCESS) - { + if (NativeApi.Raw.NodeDetachOutputBus(record.tail, 0) != MaResult.MA_SUCCESS + || NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, nativeProcessor.node, 0) != MaResult.MA_SUCCESS + || NativeApi.Raw.NodeAttachOutputBus(nativeProcessor.node, 0, record.target, 0) != MaResult.MA_SUCCESS + ) { NativeApi.Raw.NodeDetachOutputBus(record.tail, 0); NativeApi.Raw.NodeDetachOutputBus(nativeProcessor.node, 0); NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, record.target, 0); @@ -527,7 +580,9 @@ AudioListenerHandle IAudioDevice.CreateListener(AudioListenerState state) { EnsureActive(); if (m_listeners.Count >= capabilities.maxListeners) + { return default; + } uint listenerIndex = Enumerable.Range(0, capabilities.maxListeners) .Select(static index => checked((uint)index)) .First(index => !m_listeners.ContainsValue(index)); @@ -543,7 +598,9 @@ AudioListenerState state ) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.TryGetValue(identity.value, out uint listenerIndex)) + { return false; + } ApplyListener(listenerIndex, state, true); return true; } @@ -552,7 +609,9 @@ bool IAudioDevice.DestroyListener(AudioListenerHandle listener) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.Remove(identity.value, out uint listenerIndex)) + { return false; + } NativeApi.Raw.EngineListenerSetEnabled(m_engine, listenerIndex, 0); return true; } @@ -560,80 +619,120 @@ bool IAudioDevice.DestroyListener(AudioListenerHandle listener) void IAudioDevice.Update(float deltaTime) { if (deltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } EnsureActive(); foreach (ulong identity in m_clips.Keys) + { _ = PrepareNativeClip(identity); + } if (m_options.noDevice) + { ProcessHeadlessFrames(deltaTime); + } else + { UpdateOutputDeviceState(); + } if (m_state == AudioDeviceState.Lost) + { return; + } double currentTime = dspTime; foreach ((ulong identity, VoiceRecord record) in m_voices.ToArray()) { MaResult preparation = NativeApi.Raw.ResourceManagerDataSourceResult( - record.sound->PResourceManagerDataSource); + record.sound->PResourceManagerDataSource + ); if (preparation == MaResult.MA_BUSY) + { continue; + } if (preparation != MaResult.MA_SUCCESS) { CompleteVoice(identity, record, AudioCompletionReason.DecodeFailed); continue; } - if (record.state == AudioPlaybackState.Scheduled && - record.scheduledDspTime is double scheduled && scheduled <= currentTime) - { + if (record.state == AudioPlaybackState.Scheduled + && record.scheduledDspTime is double scheduled && scheduled <= currentTime + ) { record.state = AudioPlaybackState.Playing; } if (NativeApi.Raw.SoundAtEnd(record.sound) != 0) + { CompleteVoice(identity, record, AudioCompletionReason.NaturalEnd); + } } } bool IAudioDevice.TryDequeueCompletion(out AudioDeviceCompletion completion) => m_completions.TryDequeue(out completion); - /// - /// Releases all sounds, buses, processor nodes, listeners, and the native engine in dependency order. - /// - /// - /// Canceled encoded preparation still owns a source reader. The owner must retain this device - /// and retry disposal at its retirement safe point until preparation drains. - /// - public void Dispose() + private bool PrepareNativeClip(ulong identity) { - if (m_state == AudioDeviceState.Disposed) - return; - - foreach (VoiceRecord voice in m_voices.Values.ToArray()) - ReleaseVoice(voice); - m_voices.Clear(); - - m_encodedArtifacts.CancelPreparation(); - foreach (ulong identity in m_clips.Keys.ToArray()) + if (m_clipSources.ContainsKey(identity)) { - ReleaseClipSource(identity); - m_clips.Remove(identity); + return true; } - m_encodedArtifacts.Dispose(); - - foreach (BusRecord bus in m_buses.Values.OrderByDescending(GetBusDepth).ToArray()) - ReleaseBus(bus); - m_buses.Clear(); - - if (m_engineInitialized) + if (m_failedClips.Contains(identity)) { - NativeApi.Raw.EngineUninit(m_engine); - m_engineInitialized = false; + return false; } - NativeMemory.Free(m_processBuffer); - NativeMemory.Free(m_engine); - m_state = AudioDeviceState.Disposed; - GC.SuppressFinalize(this); + MiniAudioClipPreparation preparation = m_clipPreparations[identity].preparation; + if (!preparation.completion.IsCompletedSuccessfully) + { + if (preparation.completion.IsCompleted) + { + _ = preparation.completion.Exception; + m_failedClips.Add(identity); + } + return false; + } + AudioClipDescriptor descriptor = m_clips[identity]; + MaResourceManagerDataSource* source = (MaResourceManagerDataSource*)NativeMemory.AllocZeroed( + (nuint)sizeof(MaResourceManagerDataSource) + ); + uint flags = (uint)(MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC + | (descriptor.loadMode == AudioClipLoadMode.Stream + ? MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM + : MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE)); + MaResult result; + try + { + int pathByteCount = Encoding.UTF8.GetByteCount(preparation.path); + Span pathBytes = pathByteCount < 1024 + ? stackalloc byte[1024] + : new byte[checked(pathByteCount + 1)]; + Encoding.UTF8.GetBytes(preparation.path, pathBytes); + pathBytes[pathByteCount] = 0; + fixed (byte* pathPointer = pathBytes) + { + // The resource manager copies the path before scheduling asynchronous IO. + result = NativeApi.Raw.ResourceManagerDataSourceInit( + NativeApi.Raw.EngineGetResourceManager(m_engine), + (sbyte*)pathPointer, + flags, + null, + source + ); + } + } + catch + { + NativeMemory.Free(source); + throw; + } + if (result != MaResult.MA_SUCCESS) + { + NativeMemory.Free(source); + m_failedClips.Add(identity); + return false; + } + m_clipSources.Add(identity, (nint)source); + return true; } private void ReleaseClipSource(ulong identity) @@ -652,88 +751,6 @@ private void ReleaseClipSource(ulong identity) m_failedClips.Remove(identity); } - private static uint NextGeneration() - { - uint generation = unchecked((uint)Interlocked.Increment(ref S_NEXT_GENERATION)); - return generation == 0 - ? unchecked((uint)Interlocked.Increment(ref S_NEXT_GENERATION)) - : generation; - } - - private static long EstimateDecodedByteLength(AudioClipDescriptor descriptor) - { - try - { - long decoded = checked(descriptor.frameCount * descriptor.channels * sizeof(float)); - return Math.Max(descriptor.encodedByteLength, decoded); - } - catch (OverflowException) - { - return long.MaxValue; - } - } - - private static int GetBusDepth(BusRecord bus) - { - int depth = 0; - for (BusRecord? current = bus.parent; current is not null; current = current.parent) - depth++; - return depth; - } - - private static float GetParameter( - AudioProcessorConfiguration processor, - AudioParameterId id, - float defaultValue - ) { - foreach (AudioProcessorParameter parameter in processor.parameters) - { - if (parameter.id == id) - return parameter.value; - } - return defaultValue; - } - - private static MaAttenuationModel ToNativeDistanceModel(AudioDistanceModel model) - => model switch - { - AudioDistanceModel.None => MaAttenuationModel.ma_attenuation_model_none, - AudioDistanceModel.Inverse => MaAttenuationModel.ma_attenuation_model_inverse, - AudioDistanceModel.Linear => MaAttenuationModel.ma_attenuation_model_linear, - AudioDistanceModel.Exponential => MaAttenuationModel.ma_attenuation_model_exponential, - _ => throw new ArgumentOutOfRangeException(nameof(model)) - }; - - private static void ApplyVoiceParameters( - MaSound* sound, - AudioVoiceParameters parameters - ) { - NativeApi.Raw.SoundSetVolume(sound, parameters.volume); - NativeApi.Raw.SoundSetPitch(sound, parameters.pitch); - NativeApi.Raw.SoundSetPan(sound, parameters.pan); - if (parameters.spatial is not AudioSpatialOptions spatial) - { - NativeApi.Raw.SoundSetSpatializationEnabled(sound, 0); - return; - } - - NativeApi.Raw.SoundSetSpatializationEnabled(sound, 1); - NativeApi.Raw.SoundSetPositioning(sound, MaPositioning.ma_positioning_absolute); - NativeApi.Raw.SoundSetPosition(sound, spatial.position.x, spatial.position.y, spatial.position.z); - NativeApi.Raw.SoundSetDirection(sound, spatial.direction.x, spatial.direction.y, spatial.direction.z); - NativeApi.Raw.SoundSetVelocity(sound, spatial.velocity.x, spatial.velocity.y, spatial.velocity.z); - NativeApi.Raw.SoundSetAttenuationModel(sound, ToNativeDistanceModel(spatial.distanceModel)); - NativeApi.Raw.SoundSetMinDistance(sound, spatial.minDistance); - NativeApi.Raw.SoundSetMaxDistance(sound, spatial.maxDistance); - NativeApi.Raw.SoundSetRolloff(sound, spatial.rolloff); - NativeApi.Raw.SoundSetCone( - sound, - spatial.coneInnerAngle * (MathF.PI / 180f), - spatial.coneOuterAngle * (MathF.PI / 180f), - spatial.coneOuterGain); - NativeApi.Raw.SoundSetDopplerFactor(sound, spatial.dopplerFactor); - } - private void ApplyListener( uint index, AudioListenerState state, @@ -751,22 +768,24 @@ bool enabled private NativeProcessor? CreateProcessor(AudioProcessorConfiguration processor) { - if (processor.id == AudioProcessorId.delay) + if (processor.id == AudioProcessorID.delay) { - float delayMilliseconds = Math.Max(0f, GetParameter(processor, AudioParameterId.delayMilliseconds, 250f)); - float decay = Math.Clamp(GetParameter(processor, AudioParameterId.decay, 0.35f), 0f, 1f); + float delayMilliseconds = Math.Max(0f, GetParameter(processor, AudioParameterID.delayMilliseconds, 250f)); + float decay = Math.Clamp(GetParameter(processor, AudioParameterID.decay, 0.35f), 0f, 1f); uint delayFrames = checked((uint)Math.Round(delayMilliseconds * capabilities.sampleRate / 1000d)); MaDelayNode* node = (MaDelayNode*)NativeMemory.AllocZeroed((nuint)sizeof(MaDelayNode)); MaDelayNodeConfig config = NativeApi.DelayNodeConfigInit( checked((uint)m_options.channels), checked((uint)capabilities.sampleRate), delayFrames, - decay); + decay + ); MaResult result = NativeApi.Raw.DelayNodeInit( NativeApi.Raw.EngineGetNodeGraph(m_engine), &config, null, - node); + node + ); if (result != MaResult.MA_SUCCESS) { NativeMemory.Free(node); @@ -775,14 +794,14 @@ bool enabled return new NativeProcessor(node, true); } - if (processor.id != AudioProcessorId.lowPass && - processor.id != AudioProcessorId.highPass && - processor.id != AudioProcessorId.bandPass && - processor.id != AudioProcessorId.notch && - processor.id != AudioProcessorId.peak && - processor.id != AudioProcessorId.lowShelf && - processor.id != AudioProcessorId.highShelf) - { + if (processor.id != AudioProcessorID.lowPass + && processor.id != AudioProcessorID.highPass + && processor.id != AudioProcessorID.bandPass + && processor.id != AudioProcessorID.notch + && processor.id != AudioProcessorID.peak + && processor.id != AudioProcessorID.lowShelf + && processor.id != AudioProcessorID.highShelf + ) { return null; } @@ -795,12 +814,14 @@ bool enabled coefficients.b2, coefficients.a0, coefficients.a1, - coefficients.a2); + coefficients.a2 + ); MaResult biquadResult = NativeApi.Raw.BiquadNodeInit( NativeApi.Raw.EngineGetNodeGraph(m_engine), &biquadConfig, null, - biquad); + biquad + ); if (biquadResult != MaResult.MA_SUCCESS) { NativeMemory.Free(biquad); @@ -812,33 +833,51 @@ bool enabled private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration processor) { double frequency = Math.Clamp( - GetParameter(processor, AudioParameterId.frequency, processor.id == AudioProcessorId.lowPass ? 20000f : 200f), + GetParameter(processor, AudioParameterID.frequency, processor.id == AudioProcessorID.lowPass ? 20000f : 200f), 1f, - capabilities.sampleRate * 0.499f); - double quality = Math.Max(0.001, GetParameter(processor, AudioParameterId.quality, 0.70710678f)); - double gain = GetParameter(processor, AudioParameterId.gainDecibels, 0f); - double shelfSlope = Math.Max(0.001, GetParameter(processor, AudioParameterId.shelfSlope, 1f)); + capabilities.sampleRate * 0.499f + ); + double quality = Math.Max(0.001, GetParameter(processor, AudioParameterID.quality, 0.70710678f)); + double gain = GetParameter(processor, AudioParameterID.gainDecibels, 0f); + double shelfSlope = Math.Max(0.001, GetParameter(processor, AudioParameterID.shelfSlope, 1f)); double omega = 2d * Math.PI * frequency / capabilities.sampleRate; double sine = Math.Sin(omega); double cosine = Math.Cos(omega); double alpha = sine / (2d * quality); - if (processor.id == AudioProcessorId.lowPass) + if (processor.id == AudioProcessorID.lowPass) + { return new((1d - cosine) / 2d, 1d - cosine, (1d - cosine) / 2d, 1d + alpha, -2d * cosine, 1d - alpha); - if (processor.id == AudioProcessorId.highPass) + } + if (processor.id == AudioProcessorID.highPass) + { return new((1d + cosine) / 2d, -(1d + cosine), (1d + cosine) / 2d, 1d + alpha, -2d * cosine, 1d - alpha); - if (processor.id == AudioProcessorId.bandPass) + } + if (processor.id == AudioProcessorID.bandPass) + { return new(alpha, 0d, -alpha, 1d + alpha, -2d * cosine, 1d - alpha); - if (processor.id == AudioProcessorId.notch) + } + if (processor.id == AudioProcessorID.notch) + { return new(1d, -2d * cosine, 1d, 1d + alpha, -2d * cosine, 1d - alpha); + } double amplitude = Math.Pow(10d, gain / 40d); - if (processor.id == AudioProcessorId.peak) - return new(1d + alpha * amplitude, -2d * cosine, 1d - alpha * amplitude, 1d + alpha / amplitude, -2d * cosine, 1d - alpha / amplitude); + if (processor.id == AudioProcessorID.peak) + { + return new( + 1d + alpha * amplitude, + -2d * cosine, + 1d - alpha * amplitude, + 1d + alpha / amplitude, + -2d * cosine, + 1d - alpha / amplitude + ); + } double shelfAlpha = sine / 2d * Math.Sqrt((amplitude + 1d / amplitude) * (1d / shelfSlope - 1d) + 2d); double twoRootAAlpha = 2d * Math.Sqrt(amplitude) * shelfAlpha; - if (processor.id == AudioProcessorId.lowShelf) + if (processor.id == AudioProcessorID.lowShelf) { return new( amplitude * ((amplitude + 1d) - (amplitude - 1d) * cosine + twoRootAAlpha), @@ -846,7 +885,8 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration amplitude * ((amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha), (amplitude + 1d) + (amplitude - 1d) * cosine + twoRootAAlpha, -2d * ((amplitude - 1d) + (amplitude + 1d) * cosine), - (amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha); + (amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha + ); } return new( amplitude * ((amplitude + 1d) + (amplitude - 1d) * cosine + twoRootAAlpha), @@ -854,7 +894,8 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration amplitude * ((amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha), (amplitude + 1d) - (amplitude - 1d) * cosine + twoRootAAlpha, 2d * ((amplitude - 1d) - (amplitude + 1d) * cosine), - (amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha); + (amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha + ); } private void ProcessHeadlessFrames(float deltaTime) @@ -864,28 +905,28 @@ private void ProcessHeadlessFrames(float deltaTime) { ulong requested = (ulong)Math.Min(Math.Floor(m_pendingProcessFrames), C_PROCESS_BLOCK_FRAMES); ulong read = 0; - MaResult result = NativeApi.Raw.EngineReadPcmFrames( - m_engine, - m_processBuffer, - requested, - &read); + MaResult result = NativeApi.Raw.EngineReadPcmFrames(m_engine, m_processBuffer, requested, &read); if (result != MaResult.MA_SUCCESS) { m_state = AudioDeviceState.Lost; foreach ((ulong identity, VoiceRecord voice) in m_voices.ToArray()) + { CompleteVoice(identity, voice, AudioCompletionReason.DeviceLost); + } return; } m_pendingProcessFrames -= read; if (read == 0) + { return; + } } } private void UpdateOutputDeviceState() { MaDevice* device = NativeApi.Raw.EngineGetDevice(m_engine); - if (device == null) + if (device is null) { m_state = AudioDeviceState.Lost; return; @@ -903,7 +944,9 @@ private void UpdateOutputDeviceState() } m_state = AudioDeviceState.Lost; foreach ((ulong identity, VoiceRecord voice) in m_voices.ToArray()) + { CompleteVoice(identity, voice, AudioCompletionReason.DeviceLost); + } } private bool TryGetVoice( @@ -949,39 +992,128 @@ AudioCompletionReason reason m_completions.Enqueue(new AudioDeviceCompletion(handle, reason)); } - private static void ReleaseVoice(VoiceRecord record) - { - NativeApi.Raw.SoundUninit(record.sound); - NativeMemory.Free(record.sound); - } - private void ReleaseBus(BusRecord bus) { NativeApi.Raw.SoundGroupUninit(bus.group); for (int index = bus.processors.Count - 1; index >= 0; index--) + { ReleaseProcessor(bus.processors[index]); + } NativeMemory.Free(bus.group); } + private void EnsureActive() => ObjectDisposedException.ThrowIf(m_state == AudioDeviceState.Disposed, this); + + private static uint NextGeneration() + { + uint generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); + return generation == 0 + ? unchecked((uint)Interlocked.Increment(ref s_nextGeneration)) + : generation; + } + + private static long EstimateDecodedByteLength(AudioClipDescriptor descriptor) + { + try + { + long decoded = checked(descriptor.frameCount * descriptor.channels * sizeof(float)); + return Math.Max(descriptor.encodedByteLength, decoded); + } + catch (OverflowException) + { + return long.MaxValue; + } + } + + private static int GetBusDepth(BusRecord bus) + { + int depth = 0; + for (BusRecord? current = bus.parent; current is not null; current = current.parent) + { + depth++; + } + return depth; + } + + private static float GetParameter( + AudioProcessorConfiguration processor, + AudioParameterID id, + float defaultValue + ) { + foreach (AudioProcessorParameter parameter in processor.parameters) + { + if (parameter.id == id) + { + return parameter.value; + } + } + return defaultValue; + } + + private static MaAttenuationModel ToNativeDistanceModel(AudioDistanceModel model) + => model switch + { + AudioDistanceModel.None => MaAttenuationModel.ma_attenuation_model_none, + AudioDistanceModel.Inverse => MaAttenuationModel.ma_attenuation_model_inverse, + AudioDistanceModel.Linear => MaAttenuationModel.ma_attenuation_model_linear, + AudioDistanceModel.Exponential => MaAttenuationModel.ma_attenuation_model_exponential, + _ => throw new ArgumentOutOfRangeException(nameof(model)) + }; + + private static void ApplyVoiceParameters( + MaSound* sound, + AudioVoiceParameters parameters + ) { + NativeApi.Raw.SoundSetVolume(sound, parameters.volume); + NativeApi.Raw.SoundSetPitch(sound, parameters.pitch); + NativeApi.Raw.SoundSetPan(sound, parameters.pan); + if (parameters.spatial is not AudioSpatialOptions spatial) + { + NativeApi.Raw.SoundSetSpatializationEnabled(sound, 0); + return; + } + + NativeApi.Raw.SoundSetSpatializationEnabled(sound, 1); + NativeApi.Raw.SoundSetPositioning(sound, MaPositioning.ma_positioning_absolute); + NativeApi.Raw.SoundSetPosition(sound, spatial.position.x, spatial.position.y, spatial.position.z); + NativeApi.Raw.SoundSetDirection(sound, spatial.direction.x, spatial.direction.y, spatial.direction.z); + NativeApi.Raw.SoundSetVelocity(sound, spatial.velocity.x, spatial.velocity.y, spatial.velocity.z); + NativeApi.Raw.SoundSetAttenuationModel(sound, ToNativeDistanceModel(spatial.distanceModel)); + NativeApi.Raw.SoundSetMinDistance(sound, spatial.minDistance); + NativeApi.Raw.SoundSetMaxDistance(sound, spatial.maxDistance); + NativeApi.Raw.SoundSetRolloff(sound, spatial.rolloff); + NativeApi.Raw.SoundSetCone( + sound, + spatial.coneInnerAngle * (MathF.PI / 180f), + spatial.coneOuterAngle * (MathF.PI / 180f), + spatial.coneOuterGain + ); + NativeApi.Raw.SoundSetDopplerFactor(sound, spatial.dopplerFactor); + } + + private static void ReleaseVoice(VoiceRecord record) + { + NativeApi.Raw.SoundUninit(record.sound); + NativeMemory.Free(record.sound); + } + private static void ReleaseProcessor(NativeProcessor processor) { if (processor.isDelay) + { NativeApi.Raw.DelayNodeUninit((MaDelayNode*)processor.node, null); + } else + { NativeApi.Raw.BiquadNodeUninit((MaBiquadNode*)processor.node, null); + } NativeMemory.Free(processor.node); } - private void EnsureActive() - { - if (m_state == AudioDeviceState.Disposed) - throw new ObjectDisposedException(nameof(MiniAudioDevice)); - } - private sealed class BusRecord { internal readonly MaSound* group; - internal readonly AudioBusId id; + internal readonly AudioBusID id; internal readonly BusRecord? parent; internal readonly List processors = []; internal readonly void* target; @@ -991,7 +1123,7 @@ private sealed class BusRecord internal float volume = 1f; internal BusRecord( - AudioBusId id, + AudioBusID id, BusRecord? parent, MaSound* group, void* target @@ -1000,7 +1132,7 @@ internal BusRecord( this.parent = parent; this.group = group; this.target = target; - tail = group; + this.tail = group; } } @@ -1009,8 +1141,8 @@ private sealed class VoiceRecord internal readonly ulong clipIdentity; internal readonly MaSound* sound; internal readonly double? scheduledDspTime; - internal AudioPlaybackState state; internal readonly BusRecord bus; + internal AudioPlaybackState state; internal VoiceRecord( ulong clipIdentity, diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs index 3eff9d54e..5024dfa76 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs @@ -21,7 +21,7 @@ public sealed record MiniAudioDeviceOptions /// /// Gets or initializes the output sample rate in frames per second. /// - public int sampleRate { get; init; } = 48000; + public int sampleRate { get; init; } = 48_000; /// /// Gets or initializes the maximum listener count exposed by this backend generation. @@ -39,7 +39,9 @@ internal MiniAudioDeviceOptions Validate() ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); if (listenerCount is < 1 or > 4) + { throw new ArgumentOutOfRangeException(nameof(listenerCount), "MiniAudio supports between one and four listeners."); + } return this; } } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs index baafb2ea6..7291fc196 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs @@ -16,20 +16,43 @@ internal sealed class MiniAudioEncodedArtifactCache : IDisposable private readonly SemaphoreSlim m_slots = new(4); private bool m_disposed; + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + CancelPreparation(); + if (m_entries.Count != 0 || m_retiring.Count != 0) + { + throw new RetirementPendingException("Encoded audio still has clip owners awaiting retirement."); + } + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: false); + } + m_slots.Dispose(); + m_disposed = true; + } + internal MiniAudioClipSourceLease Acquire(IAudioClipSource source) { ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(source); if (source.length < 0 || source.contentHash is not { Length: 64 } - || source.contentHash.Any(static character => !Uri.IsHexDigit(character))) - { + || source.contentHash.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new ArgumentException("Encoded audio requires an exact length and SHA-256 identity.", nameof(source)); } string hash = source.contentHash.ToUpperInvariant(); if (!m_entries.TryGetValue(hash, out MiniAudioClipPreparation? entry)) { - entry = new MiniAudioClipPreparation(source, - Path.Combine(m_root, hash + "-" + Guid.NewGuid().ToString("N") + ".audio"), m_slots); + entry = new MiniAudioClipPreparation( + source, + Path.Combine(m_root, hash + "-" + Guid.NewGuid().ToString("N") + ".audio"), + m_slots + ); m_entries.Add(hash, entry); } else if (entry.length != source.length) @@ -45,7 +68,9 @@ internal void Release(MiniAudioClipPreparation entry) if (entry.references > 1) { if (!entry.completion.IsCompleted) + { throw new RetirementPendingException("Shared encoded audio preparation still borrows its first clip source."); + } entry.references--; return; } @@ -65,30 +90,20 @@ internal void Release(MiniAudioClipPreparation entry) internal void CancelPreparation() { foreach (MiniAudioClipPreparation entry in m_entries.Values) + { entry.Cancel(); + } foreach (MiniAudioClipPreparation entry in m_retiring) + { entry.Cancel(); - } - - /// - public void Dispose() - { - if (m_disposed) - return; - CancelPreparation(); - if (m_entries.Count != 0 || m_retiring.Count != 0) - throw new RetirementPendingException("Encoded audio still has clip owners awaiting retirement."); - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: false); - m_slots.Dispose(); - m_disposed = true; + } } private void RemoveActiveEntry(MiniAudioClipPreparation entry) { if (m_entries.TryGetValue(entry.contentHash, out MiniAudioClipPreparation? current) - && ReferenceEquals(current, entry)) - { + && ReferenceEquals(current, entry) + ) { m_entries.Remove(entry.contentHash); } } diff --git a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs similarity index 72% rename from backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs rename to backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs index c37c326c2..f85a7da48 100644 --- a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs +++ b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs @@ -10,7 +10,7 @@ namespace Inno.Build.Toolchains.UI; /// /// Owns this backend's native recipe while SDK selection remains with the platform provider. /// -public static class UiToolchain +public static class UIToolchain { /// /// Gets the component's sole source, binding and intermediate owner. @@ -21,10 +21,19 @@ public static class UiToolchain "backends/RmlUi/build/Inno.Build.Toolchains.UI/Inno.Build.Toolchains.UI.csproj", new NativeStaticBuildDefinition( "backends/RmlUi/build/Inno.Build.Toolchains.UI/Native/StaticLibraries.cmake", - ["extern/freetype", "extern/harfbuzz", "extern/RmlUi", "backends/RmlUi/native/Inno.Native.UI/Native/include", "backends/RmlUi/native/Inno.Native.UI/Native/src", "backends/RmlUi/native/Inno.Native.UI/Native/CMakeLists.txt"], + [ + "extern/freetype", + "extern/harfbuzz", + "extern/RmlUi", + "backends/RmlUi/native/Inno.Native.UI/Native/include", + "backends/RmlUi/native/Inno.Native.UI/Native/src", + "backends/RmlUi/native/Inno.Native.UI/Native/CMakeLists.txt" + ], ["libinno-ui", "librmlui"], - nativeSourceDirectory: "backends/RmlUi/native/Inno.Native.UI"), - bindingDefinition: "backends/RmlUi/native/Inno.Native.UI/Bindings/bindings.props"); + nativeSourceDirectory: "backends/RmlUi/native/Inno.Native.UI" + ), + bindingDefinition: "backends/RmlUi/native/Inno.Native.UI/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -52,26 +61,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "inno-ui", [], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "inno-ui", + [], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*inno-ui" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -100,9 +124,19 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "ui", selection.targetId, + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "ui", + selection.targetID, componentDescriptor.staticBuild!.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), - [], [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "UiToolchain.cs")]); + [], + [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "UIToolchain.cs")] + ); } } diff --git a/backends/RmlUi/native/Inno.Native.UI/UiNative.cs b/backends/RmlUi/native/Inno.Native.UI/UiNative.cs index 5802629bd..7f7748713 100644 --- a/backends/RmlUi/native/Inno.Native.UI/UiNative.cs +++ b/backends/RmlUi/native/Inno.Native.UI/UiNative.cs @@ -8,9 +8,9 @@ namespace Inno.Native.UI; public static unsafe partial class UiNative { #if DEBUG - internal const string LibName = "inno-ui-debug"; + internal const string C_LIB_NAME = "inno-ui-debug"; #else - internal const string LibName = "inno-ui-release"; + internal const string C_LIB_NAME = "inno-ui-release"; #endif static UiNative() @@ -20,7 +20,7 @@ static UiNative() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs index f249edd69..f13bb2dae 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs @@ -4,7 +4,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; - using Inno.Assets; using Inno.Text; using Inno.UI; @@ -15,29 +14,52 @@ namespace Inno.Adapter.UI.RmlUi.Authoring; /// /// Validates RML source for the bundled RmlUi runtime adapter. /// -public sealed class RmlUiDocumentFrontend : IUiDocumentFrontend +public sealed class RmlUiDocumentFrontend : IUIDocumentFrontend { - private static readonly Regex S_FONT_FACE = new(@"@font-face\s*\{(?[^{}]*)\}", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_PROPERTY = new(@"(?[a-z-]+)\s*:\s*(?[^;]+);?", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_FAMILY = new(@"(?im)(font-family\s*:\s*)(?[^;}]+)", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - private static readonly Regex S_URL = new(@"^url\(\s*['""]?(?[^)'""]+)['""]?\s*\)$", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_LINK = new(@"]*>", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_HREF = new(@"\bhref\s*=\s*['""](?[^'""]+)['""]", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_IMPORT = new(@"@import\s+(?:url\(\s*)?['""](?[^'""]+)['""]\s*\)?\s*;", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_FONT_SOURCE = new(@"(?\bsrc\s*:\s*url\(\s*['""]?)(?[^)'""]+)(?['""]?\s*\))", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex FONT_FACE = new( + @"@font-face\s*\{(?[^{}]*)\}", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex PROPERTY = new( + @"(?[a-z-]+)\s*:\s*(?[^;]+);?", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex FAMILY = new( + @"(?im)(font-family\s*:\s*)(?[^;}]+)", + RegexOptions.Compiled | RegexOptions.CultureInvariant + ); + + private static readonly Regex URL = new( + @"^url\(\s*['""]?(?[^)'""]+)['""]?\s*\)$", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex LINK = new( + @"]*>", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex HREF = new( + @"\bhref\s*=\s*['""](?[^'""]+)['""]", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex IMPORT = new( + @"@import\s+(?:url\(\s*)?['""](?[^'""]+)['""]\s*\)?\s*;", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex FONT_SOURCE = new( + @"(?\bsrc\s*:\s*url\(\s*['""]?)(?[^)'""]+)(?['""]?\s*\))", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); /// /// Gets the RML source language identifier accepted by this frontend. /// - public UiDocumentLanguageId languageId => RmlUiIdentifiers.documentLanguage; + public UIDocumentLanguageID languageID => RmlUiIdentifiers.documentLanguage; /// /// Analyzes source text and returns validated output with diagnostics. @@ -48,88 +70,106 @@ public sealed class RmlUiDocumentFrontend : IUiDocumentFrontend /// /// The validated ui document analysis that represents the completed operation. /// - public UiDocumentAnalysis Analyze(UiDocumentSourceFile source) + public UIDocumentAnalysis Analyze(UIDocumentSourceFile source) { ArgumentNullException.ThrowIfNull(source); if (string.IsNullOrWhiteSpace(source.text)) - return new(null, [new("RML_EMPTY", "The RML document is empty.", 1, 1)]); + { + return new(null, [new UIDocumentDiagnostic("RML_EMPTY", "The RML document is empty.", 1, 1)]); + } if (!source.text.Contains("(); - var fonts = new List(); + { + return new(null, [new UIDocumentDiagnostic("RML_ROOT_MISSING", "The RML document has no root rml element.", 1, 1)]); + } + List diagnostics = []; + List fonts = []; var families = new Dictionary(StringComparer.OrdinalIgnoreCase); AssetPath documentPath = AssetPath.Parse(source.assetPath); string expanded; try { - expanded = ExpandStyles(source, documentPath, new HashSet()); + expanded = ExpandStyles(source, documentPath, []); } catch (Exception exception) when (exception is IOException or ArgumentException or InvalidOperationException) { - return new(null, [new("RML_STYLESHEET_UNAVAILABLE", exception.Message, 1, 1)]); + return new(null, [new UIDocumentDiagnostic("RML_STYLESHEET_UNAVAILABLE", exception.Message, 1, 1)]); } - string withoutFaces = S_FONT_FACE.Replace(expanded, match => + string withoutFaces = FONT_FACE.Replace(expanded, match => { var properties = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (Match property in S_PROPERTY.Matches(match.Groups["body"].Value)) + foreach (Match property in PROPERTY.Matches(match.Groups["body"].Value)) + { properties[property.Groups["name"].Value] = property.Groups["value"].Value.Trim(); + } properties.TryGetValue("src", out string? sourceValue); - Match url = S_URL.Match(sourceValue ?? string.Empty); + Match url = URL.Match(sourceValue ?? string.Empty); if (!properties.TryGetValue("font-family", out string? logical) - || !url.Success) - { - diagnostics.Add(new("RML_FONT_FACE_INVALID", "@font-face requires font-family and src: url(...).", 1, 1)); + || !url.Success + ) { + diagnostics.Add( + new UIDocumentDiagnostic("RML_FONT_FACE_INVALID", "@font-face requires font-family and src: url(...).", 1, 1) + ); return string.Empty; } logical = logical.Trim('\'', '"', ' '); if (logical.Length == 0 || logical.Equals("none", StringComparison.OrdinalIgnoreCase)) { - diagnostics.Add(new("RML_FONT_FAMILY_INVALID", "A font face needs a named family other than none.", 1, 1)); + diagnostics.Add( + new UIDocumentDiagnostic("RML_FONT_FAMILY_INVALID", "A font face needs a named family other than none.", 1, 1) + ); return string.Empty; } string physical = families.TryGetValue(logical, out string? existing) - ? existing : families[logical] = PrivateFamily(source.assetPath, logical); + ? existing + : families[logical] = PrivateFamily(source.assetPath, logical); string path = url.Groups["path"].Value.Trim(); try { AssetPath fontPath = path.Contains("::", StringComparison.Ordinal) - ? AssetPath.Parse(path) - : new AssetPath(documentPath.source, - Path.Combine(Path.GetDirectoryName(documentPath.localPath) ?? string.Empty, path) - .Replace('\\', '/')); + ? AssetPath.Parse(path) + : new AssetPath( + documentPath.source, + Path.Combine(Path.GetDirectoryName(documentPath.localPath) ?? string.Empty, path) + .Replace('\\', '/') + ); int weight = properties.TryGetValue("font-weight", out string? weightText) - ? weightText.ToLowerInvariant() switch - { - "normal" => 400, - "bold" => 700, - _ when int.TryParse(weightText, out int numeric) => numeric, - _ => -1 - } : 400; + ? weightText.ToLowerInvariant() switch + { + "normal" => 400, + "bold" => 700, + _ when int.TryParse(weightText, out int numeric) => numeric, + _ => -1 + } + : 400; if (weight is < 100 or > 1000) + { throw new ArgumentException("font-weight must be 100–1000, normal, or bold."); + } TextFontStyle style = properties.TryGetValue("font-style", out string? styleText) - && styleText.Equals("italic", StringComparison.OrdinalIgnoreCase) - ? TextFontStyle.Italic : TextFontStyle.Normal; - fonts.Add(new(fontPath.ToString(), physical, style, weight)); + && styleText.Equals("italic", StringComparison.OrdinalIgnoreCase) + ? TextFontStyle.Italic + : TextFontStyle.Normal; + fonts.Add(new UIDocumentFontDeclaration(fontPath.ToString(), physical, style, weight)); } catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) { - diagnostics.Add(new("RML_FONT_ASSET_INVALID", exception.Message, 1, 1)); + diagnostics.Add(new UIDocumentDiagnostic("RML_FONT_ASSET_INVALID", exception.Message, 1, 1)); } return string.Empty; }); - string canonical = S_FAMILY.Replace(withoutFaces, match => + string canonical = FAMILY.Replace(withoutFaces, match => { string[] requested = match.Groups["value"].Value.Split(',', StringSplitOptions.TrimEntries); for (int index = 0; index < requested.Length; index++) { string logical = requested[index].Trim('\'', '"', ' '); requested[index] = families.TryGetValue(logical, out string? physical) - ? physical : PrivateFamily(source.assetPath, "missing/" + logical); + ? physical + : PrivateFamily(source.assetPath, "missing/" + logical); } return match.Groups[1].Value + string.Join(", ", requested); }); - return diagnostics.Count == 0 ? new(canonical, diagnostics, fonts) : new(null, diagnostics); + return diagnostics.Count == 0 ? new UIDocumentAnalysis(canonical, diagnostics, fonts) : new UIDocumentAnalysis(null, diagnostics); } private static string PrivateFamily( @@ -141,20 +181,23 @@ string logical } private static string ExpandStyles( - UiDocumentSourceFile source, + UIDocumentSourceFile source, AssetPath documentPath, HashSet active - ) - => S_LINK.Replace(source.text, match => + ) => LINK.Replace(source.text, match => + { + Match href = HREF.Match(match.Value); + if (!href.Success || !href.Groups["path"].Value.EndsWith(".rcss", StringComparison.OrdinalIgnoreCase)) { - Match href = S_HREF.Match(match.Value); - if (!href.Success || !href.Groups["path"].Value.EndsWith(".rcss", StringComparison.OrdinalIgnoreCase)) - return match.Value; - if (source.readSource is null) - throw new InvalidOperationException("External RCSS requires an import source reader."); - AssetPath sheetPath = ResolvePath(documentPath, href.Groups["path"].Value); - return ""; - }); + return match.Value; + } + if (source.readSource is null) + { + throw new InvalidOperationException("External RCSS requires an import source reader."); + } + AssetPath sheetPath = ResolvePath(documentPath, href.Groups["path"].Value); + return ""; + }); private static string ExpandSheet( Func readSource, @@ -162,16 +205,19 @@ private static string ExpandSheet( HashSet active ) { if (!active.Add(path)) + { throw new InvalidDataException($"RCSS import cycle includes '{path}'."); + } try { string text = readSource(path); - text = S_IMPORT.Replace(text, match => + text = IMPORT.Replace(text, match => ExpandSheet(readSource, ResolvePath(path, match.Groups["path"].Value), active)); - return S_FONT_FACE.Replace(text, match => S_FONT_SOURCE.Replace(match.Value, font => + return FONT_FACE.Replace(text, match => FONT_SOURCE.Replace(match.Value, font => ( font.Groups["prefix"].Value + FormatExplicitPath(ResolvePath(path, font.Groups["path"].Value.Trim())) - + font.Groups["suffix"].Value)); + + font.Groups["suffix"].Value + ))); } finally { @@ -184,23 +230,33 @@ private static AssetPath ResolvePath( string relative ) { if (relative.Contains("::", StringComparison.Ordinal)) + { return AssetPath.Parse(relative); + } if (Path.IsPathRooted(relative)) + { throw new ArgumentException("An RCSS path must be source-relative.", nameof(relative)); + } var segments = new List(owner.localPath.Replace('\\', '/').Split('/')); segments.RemoveAt(segments.Count - 1); foreach (string segment in relative.Replace('\\', '/').Split('/')) { if (segment is "" or ".") + { continue; + } if (segment == "..") { if (segments.Count == 0) + { throw new ArgumentException("An RCSS path escapes its asset source.", nameof(relative)); + } segments.RemoveAt(segments.Count - 1); } else + { segments.Add(segment); + } } return new AssetPath(owner.source, string.Join('/', segments)); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs index cab40a929..1f0b7228a 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; using Inno.UI; using Inno.UI.Assets; @@ -12,7 +11,7 @@ namespace Inno.Adapter.UI.RmlUi.Authoring; /// Maps the conventional .rml extension to explicit RML and RmlUi identities. /// [AssetImporter("inno.ui.rml-document")] -public sealed class RmlUiDocumentImporter : AssetImporter +public sealed class RmlUiDocumentImporter : AssetImporter { /// /// Gets the normalized source extensions accepted by this importer. @@ -36,13 +35,13 @@ public sealed class RmlUiDocumentImporter : AssetImporter /// protected override ValueTask ImportAsync( AssetImportContext context, - AssetImportWriter output, + AssetImportWriter output, CancellationToken cancellationToken - ) - => UiDocumentImportPipeline.ImportAsync( - context, - output, - RmlUiIdentifiers.documentLanguage, - RmlUiIdentifiers.backend.value, - cancellationToken); + ) => UIDocumentImportPipeline.ImportAsync( + context, + output, + RmlUiIdentifiers.documentLanguage, + RmlUiIdentifiers.backend.value, + cancellationToken + ); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs index c6db940a4..091117cc1 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; - using Inno.Core.Input; using Inno.Core.Mathematics; using Inno.Native.UI; @@ -17,38 +16,44 @@ namespace Inno.Adapter.UI.RmlUi; /// /// Implements retained-mode UI document processing through the pinned RmlUi native bridge. /// -public sealed unsafe class RmlUiBackend : IUiBackend +public sealed unsafe class RmlUiBackend : IUIBackend { - private static readonly UiBackendCapabilities S_CAPABILITIES = new( + private static readonly UIBackendCapabilities CAPABILITIES = new( [RmlUiIdentifiers.documentLanguage], - supportsFontCollectionFaces: false); - private static readonly Regex S_FONT_FAMILY = new( + supportsFontCollectionFaces: false + ); + + private static readonly Regex FONT_FAMILY = new( @"(?im)(font-family\s*:\s*)([^;}]+)", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - private InnoUIRmlUiAdapterRuntime* m_runtime; + RegexOptions.Compiled | RegexOptions.CultureInvariant + ); + private readonly Dictionary m_fontAliases = new(StringComparer.OrdinalIgnoreCase); + private InnoUIRmlUiAdapterRuntime* m_runtime; private bool m_disposed; - /// - /// Gets the implementation id text used by the current instance. - /// - public string implementationId => RmlUiIdentifiers.backend.value; - - /// - /// Gets the immutable feature and limit set reported by the active graphics backend. - /// - public UiBackendCapabilities capabilities => S_CAPABILITIES; - /// /// Creates and validates one isolated native UI engine. /// public RmlUiBackend() { m_runtime = RmlUiNativeErrors.CreateSession(); - if (m_runtime == null) + if (m_runtime is null) + { throw CreateNativeException("create UI runtime", Result.UnknownError); + } } + /// + /// Gets the implementation id text used by the current instance. + /// + public string implementationID => RmlUiIdentifiers.backend.value; + + /// + /// Gets the immutable feature and limit set reported by the active graphics backend. + /// + public UIBackendCapabilities capabilities => CAPABILITIES; + /// /// Creates a context using this implementation's validated inputs. /// @@ -58,13 +63,22 @@ public RmlUiBackend() /// /// The validated ui context handle that represents the completed operation. /// - public UiContextHandle CreateContext(UiContextOptions options) + public UIContextHandle CreateContext(UIContextOptions options) { EnsureActive(); ulong value = 0; - ThrowIfFailed(RmlUiNativeRuntime.CreateContext( - m_runtime, options.name, options.width, options.height, options.density, ref value), "create UI context"); - return new UiContextHandle(value); + ThrowIfFailed( + RmlUiNativeRuntime.CreateContext( + m_runtime, + options.name, + options.width, + options.height, + options.density, + ref value + ), + "create UI context" + ); + return new UIContextHandle(value); } /// @@ -73,7 +87,7 @@ public UiContextHandle CreateContext(UiContextOptions options) /// /// The context that supplies state and services for this operation. /// - public void DestroyContext(UiContextHandle context) + public void DestroyContext(UIContextHandle context) { EnsureActive(); ThrowIfFailed(RmlUiNativeRuntime.DestroyContext(m_runtime, Require(context)), "destroy UI context"); @@ -95,7 +109,7 @@ public void DestroyContext(UiContextHandle context) /// The density consumed by set viewport; ownership remains with the caller unless explicitly stated otherwise. /// public void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density @@ -104,7 +118,9 @@ float density ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); if (!float.IsFinite(density) || density <= 0f) + { throw new ArgumentOutOfRangeException(nameof(density)); + } ThrowIfFailed(RmlUiNativeRuntime.SetViewport(m_runtime, Require(context), width, height, density), "set UI viewport"); } @@ -120,17 +136,25 @@ float density /// /// The validated ui document handle that represents the completed operation. /// - public UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source + public UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source ) { EnsureActive(); ArgumentNullException.ThrowIfNull(source); EnsureRml(source.language); ulong document = 0; - ThrowIfFailed(RmlUiNativeRuntime.LoadDocument( - m_runtime, Require(context), RewriteFontFamilies(source.text), source.sourceUri, ref document), "load UI document"); - return new UiDocumentHandle(document); + ThrowIfFailed( + RmlUiNativeRuntime.LoadDocument( + m_runtime, + Require(context), + RewriteFontFamilies(source.text), + source.sourceUri, + ref document + ), + "load UI document" + ); + return new UIDocumentHandle(document); } /// @@ -143,8 +167,8 @@ UiDocumentSource source /// The document consumed by show document; ownership remains with the caller unless explicitly stated otherwise. /// public void ShowDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); ThrowIfFailed(RmlUiNativeRuntime.ShowDocument(m_runtime, Require(context), Require(document)), "show UI document"); @@ -160,8 +184,8 @@ UiDocumentHandle document /// The document consumed by hide document; ownership remains with the caller unless explicitly stated otherwise. /// public void HideDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); ThrowIfFailed(RmlUiNativeRuntime.HideDocument(m_runtime, Require(context), Require(document)), "hide UI document"); @@ -177,8 +201,8 @@ UiDocumentHandle document /// The document consumed by close document; ownership remains with the caller unless explicitly stated otherwise. /// public void CloseDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); ThrowIfFailed(RmlUiNativeRuntime.CloseDocument(m_runtime, Require(context), Require(document)), "close UI document"); @@ -193,7 +217,7 @@ UiDocumentHandle document /// /// The document consumed by set text; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set text operation. /// /// @@ -203,17 +227,26 @@ UiDocumentHandle document /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text ) { EnsureActive(); - ArgumentException.ThrowIfNullOrWhiteSpace(elementId); + ArgumentException.ThrowIfNullOrWhiteSpace(elementID); ArgumentNullException.ThrowIfNull(text); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetInnerMarkup( - m_runtime, Require(context), Require(document), elementId, WebUtility.HtmlEncode(text), ref changed), "set UI text"); + ThrowIfFailed( + RmlUiNativeRuntime.SetInnerMarkup( + m_runtime, + Require(context), + Require(document), + elementID, + WebUtility.HtmlEncode(text), + ref changed + ), + "set UI text" + ); return changed != 0; } @@ -226,7 +259,7 @@ string text /// /// The document consumed by set content; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set content operation. /// /// @@ -236,22 +269,26 @@ string text /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment content + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment content ) { EnsureActive(); - ArgumentException.ThrowIfNullOrWhiteSpace(elementId); + ArgumentException.ThrowIfNullOrWhiteSpace(elementID); EnsureRml(content.language); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetInnerMarkup( - m_runtime, - Require(context), - Require(document), - elementId, - RewriteFontFamilies(content.text), - ref changed), "set UI content"); + ThrowIfFailed( + RmlUiNativeRuntime.SetInnerMarkup( + m_runtime, + Require(context), + Require(document), + elementID, + RewriteFontFamilies(content.text), + ref changed + ), + "set UI content" + ); return changed != 0; } @@ -264,7 +301,7 @@ UiDocumentFragment content /// /// The document consumed by set attribute; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set attribute operation. /// /// @@ -277,25 +314,29 @@ UiDocumentFragment content /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value ) { EnsureActive(); - ArgumentException.ThrowIfNullOrWhiteSpace(elementId); + ArgumentException.ThrowIfNullOrWhiteSpace(elementID); ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(value); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetAttribute( - m_runtime, - Require(context), - Require(document), - elementId, - name, - value, - ref changed), "set UI attribute"); + ThrowIfFailed( + RmlUiNativeRuntime.SetAttribute( + m_runtime, + Require(context), + Require(document), + elementID, + name, + value, + ref changed + ), + "set UI attribute" + ); return changed != 0; } @@ -308,7 +349,7 @@ string value /// /// The document consumed by set class; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set class operation. /// /// @@ -321,24 +362,28 @@ string value /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active ) { EnsureActive(); - ArgumentException.ThrowIfNullOrWhiteSpace(elementId); + ArgumentException.ThrowIfNullOrWhiteSpace(elementID); ArgumentException.ThrowIfNullOrWhiteSpace(className); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetClass( - m_runtime, - Require(context), - Require(document), - elementId, - className, - active ? (byte)1 : (byte)0, - ref changed), "set UI class"); + ThrowIfFailed( + RmlUiNativeRuntime.SetClass( + m_runtime, + Require(context), + Require(document), + elementID, + className, + active ? (byte)1 : (byte)0, + ref changed + ), + "set UI class" + ); return changed != 0; } @@ -348,28 +393,35 @@ bool active /// /// The registration consumed by register font; ownership remains with the caller unless explicitly stated otherwise. /// - public void RegisterFont(UiFontRegistration registration) + public void RegisterFont(UIFontRegistration registration) { EnsureActive(); if (registration.faceIndex != 0) - throw new UiCapabilityUnavailableException(UiBackendCapability.FontCollectionFaceSelection); + { + throw new UICapabilityUnavailableException(UIBackendCapability.FontCollectionFaceSelection); + } // All weights and styles of one declared family must share one native family. // Document imports give each family a private name before it reaches this backend. - string familyHash = Convert.ToHexString(SHA256.HashData( - Encoding.UTF8.GetBytes(registration.family.ToLowerInvariant()))).ToLowerInvariant(); + string familyHash = Convert.ToHexString( + SHA256.HashData(Encoding.UTF8.GetBytes(registration.family.ToLowerInvariant())) + ).ToLowerInvariant(); string physicalFamily = $"__inno_{familyHash[..24]}"; ReadOnlySpan data = registration.data.Span; using var family = new RmlUiUtf8String(physicalFamily); fixed (byte* bytes = data) { - ThrowIfFailed(RmlUiNativeRuntime.LoadFont( - m_runtime, - bytes, - checked((uint)data.Length), - family.pointer, - (int)registration.style, - registration.weight, - 0), "register UI font"); + ThrowIfFailed( + RmlUiNativeRuntime.LoadFont( + m_runtime, + bytes, + checked((uint)data.Length), + family.pointer, + (int)registration.style, + registration.weight, + 0 + ), + "register UI font" + ); } m_fontAliases[registration.family] = physicalFamily; } @@ -387,9 +439,9 @@ public void RegisterFont(UiFontRegistration registration) /// The texture consumed by register texture; ownership remains with the caller unless explicitly stated otherwise. /// public void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture + UITextureData texture ) { EnsureActive(); ArgumentException.ThrowIfNullOrWhiteSpace(source); @@ -398,14 +450,18 @@ UiTextureData texture using var nativeSource = new RmlUiUtf8String(source); fixed (byte* pixelPointer = pixels) { - ThrowIfFailed(RmlUiNativeRuntime.RegisterTexture( - m_runtime, - Require(context), - nativeSource.pointer, - texture.width, - texture.height, - pixelPointer, - checked((uint)pixels.Length)), "register UI texture"); + ThrowIfFailed( + RmlUiNativeRuntime.RegisterTexture( + m_runtime, + Require(context), + nativeSource.pointer, + texture.width, + texture.height, + pixelPointer, + checked((uint)pixels.Length) + ), + "register UI texture" + ); } } @@ -422,13 +478,21 @@ UiTextureData texture /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool HasElementAtPoint( - UiContextHandle context, + UIContextHandle context, Vector2 position ) { EnsureActive(); byte hit = 0; - ThrowIfFailed(RmlUiNativeRuntime.HasElementAtPoint(m_runtime, Require(context), - (int)position.x, (int)position.y, ref hit), "query UI element hit"); + ThrowIfFailed( + RmlUiNativeRuntime.HasElementAtPoint( + m_runtime, + Require(context), + (int)position.x, + (int)position.y, + ref hit + ), + "query UI element hit" + ); return hit != 0; } @@ -442,28 +506,55 @@ Vector2 position /// The input consumed by update; ownership remains with the caller unless explicitly stated otherwise. /// public void Update( - UiContextHandle context, - UiInputSnapshot input + UIContextHandle context, + UIInputSnapshot input ) { EnsureActive(); ArgumentNullException.ThrowIfNull(input); ulong handle = Require(context); int modifiers = (int)input.modifiers; - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseMove( - m_runtime, handle, (int)input.mousePosition.x, (int)input.mousePosition.y, modifiers), "process UI pointer position"); + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseMove( + m_runtime, + handle, + (int)input.mousePosition.x, + (int)input.mousePosition.y, + modifiers + ), + "process UI pointer position" + ); if (input.scrollDelta.x != 0f || input.scrollDelta.y != 0f) { - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseWheel( - m_runtime, handle, input.scrollDelta.x, input.scrollDelta.y, modifiers), "process UI pointer wheel"); + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseWheel( + m_runtime, + handle, + input.scrollDelta.x, + input.scrollDelta.y, + modifiers + ), + "process UI pointer wheel" + ); } foreach (MouseButton button in input.buttonsPressed) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 1, modifiers), "process UI pointer press"); + } foreach (MouseButton button in input.buttonsReleased) - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 0, modifiers), "process UI pointer release"); + { + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 0, modifiers), + "process UI pointer release" + ); + } foreach (KeyCode key in input.keysPressed) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessKey(m_runtime, handle, (int)key, 1, modifiers), "process UI key press"); + } foreach (KeyCode key in input.keysReleased) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessKey(m_runtime, handle, (int)key, 0, modifiers), "process UI key release"); + } foreach (string text in input.textInput) { using var nativeText = new RmlUiUtf8String(text); @@ -481,61 +572,71 @@ UiInputSnapshot input /// /// The validated ui render frame that represents the completed operation. /// - public UiRenderFrame Render(UiContextHandle context) + public UIRenderFrame Render(UIContextHandle context) { EnsureActive(); ulong handle = Require(context); InnoUIRmlUiAdapterFrameInfo info = default; ThrowIfFailed(RmlUiNativeFrames.Render(m_runtime, handle, ref info), "render UI context"); - var builder = new UiRenderFrameBuilder(); + var builder = new UIRenderFrameBuilder(); try { for (int meshIndex = 0; meshIndex < checked((int)info.MeshUpdateCount); ++meshIndex) { InnoUIRmlUiAdapterMeshInfo mesh = default; ThrowIfFailed(RmlUiNativeFrames.GetMeshInfo(m_runtime, handle, checked((ulong)meshIndex), ref mesh), "query UI mesh"); - InnoUIRmlUiAdapterVertex[] nativeVertices = new InnoUIRmlUiAdapterVertex[checked((int)mesh.VertexCount)]; - uint[] indices = new uint[checked((int)mesh.IndexCount)]; + var nativeVertices = new InnoUIRmlUiAdapterVertex[checked((int)mesh.VertexCount)]; + var indices = new uint[checked((int)mesh.IndexCount)]; CopyMeshVertices(handle, mesh.Id, nativeVertices); CopyMeshIndices(handle, mesh.Id, indices); - UiVertex[] vertices = new UiVertex[nativeVertices.Length]; + var vertices = new UIVertex[nativeVertices.Length]; for (int vertexIndex = 0; vertexIndex < vertices.Length; ++vertexIndex) { InnoUIRmlUiAdapterVertex value = nativeVertices[vertexIndex]; vertices[vertexIndex] = new(value.X, value.Y, value.U, value.V, value.Color); } - builder.AddMeshUpdate(new(mesh.Id), mesh.Revision, vertices, indices); + builder.AddMeshUpdate(new UIMeshHandle(mesh.Id), mesh.Revision, vertices, indices); } foreach (ulong mesh in CopyReleasedMeshes(handle, info.ReleasedMeshCount)) - builder.AddReleasedMesh(new(mesh)); + { + builder.AddReleasedMesh(new UIMeshHandle(mesh)); + } - InnoUIRmlUiAdapterDrawCommand[] nativeCommands = new InnoUIRmlUiAdapterDrawCommand[checked((int)info.CommandCount)]; + var nativeCommands = new InnoUIRmlUiAdapterDrawCommand[checked((int)info.CommandCount)]; CopyCommands(handle, nativeCommands); foreach (InnoUIRmlUiAdapterDrawCommand value in nativeCommands) - builder.AddCommand(new( - new(value.MeshId), - new(value.TextureId), - value.ScissorEnabled != 0, - new(value.ScissorX, value.ScissorY, value.ScissorWidth, value.ScissorHeight))); + { + builder.AddCommand( + new UIDrawCommand( + new UIMeshHandle(value.MeshId), + new UITextureHandle(value.TextureId), + value.ScissorEnabled != 0, + new UIClipRectangle(value.ScissorX, value.ScissorY, value.ScissorWidth, value.ScissorHeight) + ) + ); + } for (int index = 0; index < checked((int)info.TextureUpdateCount); index++) { InnoUIRmlUiAdapterTextureInfo texture = default; ThrowIfFailed(RmlUiNativeFrames.GetTextureInfo(m_runtime, handle, checked((ulong)index), ref texture), "query UI texture"); - byte[] pixels = new byte[checked((int)texture.ByteLength)]; + var pixels = new byte[checked((int)texture.ByteLength)]; if (pixels.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyTexturePixels( - m_runtime, - handle, - texture.Id, - pixels.AsSpan()), "copy UI texture"); - builder.AddTextureUpdate(new(texture.Id), texture.Revision, texture.Width, texture.Height, pixels); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyTexturePixels(m_runtime, handle, texture.Id, pixels.AsSpan()), + "copy UI texture" + ); + } + builder.AddTextureUpdate(new UITextureHandle(texture.Id), texture.Revision, texture.Width, texture.Height, pixels); } foreach (ulong texture in CopyReleasedTextures(handle, info.ReleasedTextureCount)) - builder.AddReleasedTexture(new(texture)); + { + builder.AddReleasedTexture(new UITextureHandle(texture)); + } - UiRenderFrame frame = builder.Build(); + UIRenderFrame frame = builder.Build(); ThrowIfFailed(RmlUiNativeFrames.FinishFrame(m_runtime, handle), "finish UI frame transfer"); return frame; } @@ -555,29 +656,29 @@ public UiRenderFrame Render(UiContextHandle context) /// /// An immutable snapshot of the values selected by the operation. /// - public IReadOnlyList DrainEvents(UiContextHandle context) + public IReadOnlyList DrainEvents(UIContextHandle context) { EnsureActive(); ulong handle = Require(context); ulong eventCount = 0; ThrowIfFailed(RmlUiNativeFrames.GetEventCount(m_runtime, handle, ref eventCount), "query UI events"); - UiEvent[] events = new UiEvent[checked((int)eventCount)]; + var events = new UIEvent[checked((int)eventCount)]; try { for (int index = 0; index < events.Length; index++) { InnoUIRmlUiAdapterEventInfo info = default; ThrowIfFailed(RmlUiNativeFrames.GetEventInfo(m_runtime, handle, checked((ulong)index), ref info), "query UI event"); - byte[] targetBytes = new byte[checked((int)info.TargetIdLength + 1)]; - ThrowIfFailed(RmlUiNativeFrames.CopyEventTargetId( - m_runtime, - handle, - checked((ulong)index), - targetBytes.AsSpan()), "copy UI event target"); - events[index] = new UiEvent( - (UiEventType)info.Type, - new UiDocumentHandle(info.Document), - Encoding.UTF8.GetString(targetBytes, 0, checked((int)info.TargetIdLength))); + var targetBytes = new byte[checked((int)info.TargetIdLength + 1)]; + ThrowIfFailed( + RmlUiNativeFrames.CopyEventTargetID(m_runtime, handle, checked((ulong)index), targetBytes.AsSpan()), + "copy UI event target" + ); + events[index] = new UIEvent( + (UIEventType)info.Type, + new UIDocumentHandle(info.Document), + Encoding.UTF8.GetString(targetBytes, 0, checked((int)info.TargetIdLength)) + ); } return events; } @@ -593,7 +694,9 @@ public IReadOnlyList DrainEvents(UiContextHandle context) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; RmlUiNativeErrors.DestroySession(m_runtime); m_runtime = null; @@ -605,7 +708,9 @@ private void CopyMeshVertices( InnoUIRmlUiAdapterVertex[] values ) { if (values.Length == 0) + { return; + } ThrowIfFailed(RmlUiNativeFrames.CopyMeshVertices(m_runtime, context, mesh, values), "copy UI mesh vertices"); } @@ -615,12 +720,13 @@ private void CopyMeshIndices( uint[] values ) { if (values.Length == 0) + { return; - ThrowIfFailed(RmlUiNativeFrames.CopyMeshIndices( - m_runtime, - context, - mesh, - values.AsSpan()), "copy UI mesh indices"); + } + ThrowIfFailed( + RmlUiNativeFrames.CopyMeshIndices(m_runtime, context, mesh, values.AsSpan()), + "copy UI mesh indices" + ); } private void CopyCommands( @@ -628,7 +734,9 @@ private void CopyCommands( InnoUIRmlUiAdapterDrawCommand[] values ) { if (values.Length == 0) + { return; + } ThrowIfFailed(RmlUiNativeFrames.CopyCommands(m_runtime, context, values), "copy UI commands"); } @@ -636,12 +744,14 @@ private ulong[] CopyReleasedMeshes( ulong context, ulong count ) { - ulong[] values = new ulong[checked((int)count)]; + var values = new ulong[checked((int)count)]; if (values.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyReleasedMeshes( - m_runtime, - context, - values.AsSpan()), "copy released UI meshes"); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyReleasedMeshes(m_runtime, context, values.AsSpan()), + "copy released UI meshes" + ); + } return values; } @@ -649,23 +759,19 @@ private ulong[] CopyReleasedTextures( ulong context, ulong count ) { - ulong[] values = new ulong[checked((int)count)]; + var values = new ulong[checked((int)count)]; if (values.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyReleasedTextures( - m_runtime, - context, - values.AsSpan()), "copy released UI textures"); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyReleasedTextures(m_runtime, context, values.AsSpan()), + "copy released UI textures" + ); + } return values; } - private static void EnsureRml(UiDocumentLanguageId language) - { - if (language != RmlUiIdentifiers.documentLanguage) - throw new NotSupportedException($"RmlUi adapter cannot decode UI language '{language}'."); - } - private string RewriteFontFamilies(string source) - => S_FONT_FAMILY.Replace(source, match => + => FONT_FAMILY.Replace(source, match => { string[] requested = match.Groups[2].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); var resolved = new List(requested.Length); @@ -677,10 +783,20 @@ private string RewriteFontFamilies(string source) return match.Groups[1].Value + string.Join(", ", resolved); }); - private static ulong Require(UiContextHandle context) + private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); + + private static void EnsureRml(UIDocumentLanguageID language) + { + if (language != RmlUiIdentifiers.documentLanguage) + { + throw new NotSupportedException($"RmlUi adapter cannot decode UI language '{language}'."); + } + } + + private static ulong Require(UIContextHandle context) => context.isValid ? context.value : throw new ArgumentException("A valid UI context handle is required.", nameof(context)); - private static ulong Require(UiDocumentHandle document) + private static ulong Require(UIDocumentHandle document) => document.isValid ? document.value : throw new ArgumentException("A valid UI document handle is required.", nameof(document)); private static void ThrowIfFailed( @@ -688,14 +804,15 @@ private static void ThrowIfFailed( string operation ) { if (result != Result.Success) + { throw CreateNativeException(operation, result); + } } private static InvalidOperationException CreateNativeException( string operation, Result result ) { - string message = result switch { Result.InvalidArgument => "invalid argument", @@ -708,6 +825,4 @@ Result result }; return new InvalidOperationException($"Failed to {operation}: {message}."); } - - private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs index a5f8b57f0..0b1ddba61 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs @@ -5,13 +5,14 @@ namespace Inno.Adapter.UI.RmlUi; /// /// Supplies independently owned retained UI backend generations. /// -public sealed class RmlUiBackendProvider : UiBackendProvider +public sealed class RmlUiBackendProvider : UIBackendProvider { /// /// Creates a composition-owned registration for the bundled implementation. /// - public RmlUiBackendProvider() : base(UiBackendId.rmlUi) { } + public RmlUiBackendProvider() + : base(UIBackendID.rmlUI) {} - /// - public override IUiBackend CreateBackend() => new RmlUiBackend(); + /// + public override IUIBackend CreateBackend() => new RmlUiBackend(); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiIdentifiers.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiIdentifiers.cs index deab2df38..9d07ad06f 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiIdentifiers.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiIdentifiers.cs @@ -11,10 +11,10 @@ public static class RmlUiIdentifiers /// /// Gets the runtime implementation identity. /// - public static UiBackendId backend { get; } = UiBackendId.rmlUi; + public static UIBackendID backend { get; } = UIBackendID.rmlUI; /// /// Gets the RML source-language identity. /// - public static UiDocumentLanguageId documentLanguage { get; } = new("inno.ui-language.rml"); + public static UIDocumentLanguageID documentLanguage { get; } = new("inno.ui-language.rml"); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs index 848b21315..455aa3174 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs @@ -24,17 +24,23 @@ internal static void CheckBridge( int status, BgcsInnoRmluiError* error ) { - if (status == 0 && error == null) + if (status == 0 && error is null) + { return; + } try { - string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)UiNative.Raw.BgcsInnoRmluiErrorMessage(error)); - throw new InvalidOperationException($"The UI bridge failed with status {status}: {message ?? "No native error text is available."}"); + string? message = error is null ? null : Marshal.PtrToStringUTF8((nint)UiNative.Raw.BgcsInnoRmluiErrorMessage(error)); + throw new InvalidOperationException( + $"The UI bridge failed with status {status}: {message ?? "No native error text is available."}" + ); } finally { - if (error != null) + if (error is not null) + { UiNative.Raw.BgcsInnoRmluiErrorRelease(error); + } } } } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs index b58f5cf98..ddc4fc05b 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs @@ -11,13 +11,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ClearEvents( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ClearEvents(runtime, context, &result, &error), error); return result; } @@ -29,6 +23,7 @@ Span commands Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterDrawCommand* commandsPointer = commands) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyCommands( runtime, @@ -36,30 +31,37 @@ Span commands (InnoUIRmlUiAdapterDrawCommandNative*)commandsPointer, checked((ulong)commands.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } - internal static Result CopyEventTargetId( + internal static Result CopyEventTargetID( InnoUIRmlUiAdapterRuntime* runtime, ulong context, ulong index, - Span targetId + Span targetID ) { Result result = default; BgcsInnoRmluiError* error = null; - fixed (byte* targetIdPointer = targetId) + fixed (byte* targetIDPointer = targetID) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyEventTargetId( runtime, context, index, - (sbyte*)targetIdPointer, - checked((ulong)targetId.Length), + (sbyte*)targetIDPointer, + checked((ulong)targetID.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -72,6 +74,7 @@ Span indices Result result = default; BgcsInnoRmluiError* error = null; fixed (uint* indicesPointer = indices) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyMeshIndices( runtime, @@ -80,8 +83,11 @@ Span indices (uint*)indicesPointer, checked((ulong)indices.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -94,6 +100,7 @@ Span vertices Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterVertex* verticesPointer = vertices) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyMeshVertices( runtime, @@ -102,8 +109,11 @@ Span vertices (InnoUIRmlUiAdapterVertexNative*)verticesPointer, checked((ulong)vertices.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -115,6 +125,7 @@ Span meshes Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* meshesPointer = meshes) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyReleasedMeshes( runtime, @@ -122,8 +133,11 @@ Span meshes (ulong*)meshesPointer, checked((ulong)meshes.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -135,6 +149,7 @@ Span textures Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* texturesPointer = textures) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyReleasedTextures( runtime, @@ -142,8 +157,11 @@ Span textures (ulong*)texturesPointer, checked((ulong)textures.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -156,6 +174,7 @@ Span pixels Result result = default; BgcsInnoRmluiError* error = null; fixed (byte* pixelsPointer = pixels) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyTexturePixels( runtime, @@ -164,8 +183,11 @@ Span pixels (byte*)pixelsPointer, checked((ulong)pixels.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -175,13 +197,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.FinishFrame( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.FinishFrame(runtime, context, &result, &error), error); return result; } @@ -193,14 +209,12 @@ ref ulong count Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* countPointer = &count) + { RmlUiNativeErrors.CheckBridge( - UiNative.Raw.GetEventCount( - runtime, - context, - countPointer, - &result, - &error), - error); + UiNative.Raw.GetEventCount(runtime, context, countPointer, &result, &error), + error + ); + } return result; } @@ -213,6 +227,7 @@ ref InnoUIRmlUiAdapterEventInfo eventInfo Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterEventInfo* eventInfoPointer = &eventInfo) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetEventInfo( runtime, @@ -220,8 +235,11 @@ ref InnoUIRmlUiAdapterEventInfo eventInfo index, (InnoUIRmlUiAdapterEventInfoNative*)eventInfoPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -234,6 +252,7 @@ ref InnoUIRmlUiAdapterMeshInfo mesh Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterMeshInfo* meshPointer = &mesh) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetMeshInfo( runtime, @@ -241,8 +260,11 @@ ref InnoUIRmlUiAdapterMeshInfo mesh index, (InnoUIRmlUiAdapterMeshInfoNative*)meshPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -255,6 +277,7 @@ ref InnoUIRmlUiAdapterTextureInfo texture Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterTextureInfo* texturePointer = &texture) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetTextureInfo( runtime, @@ -262,8 +285,11 @@ ref InnoUIRmlUiAdapterTextureInfo texture index, (InnoUIRmlUiAdapterTextureInfoNative*)texturePointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -275,14 +301,18 @@ ref InnoUIRmlUiAdapterFrameInfo frame Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterFrameInfo* framePointer = &frame) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.Render( runtime, context, (InnoUIRmlUiAdapterFrameInfoNative*)framePointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs index 62cfcb061..f995b1f8d 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs @@ -12,14 +12,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.CloseDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.CloseDocument(runtime, context, document, &result, &error), error); return result; } @@ -35,6 +28,7 @@ ref ulong context BgcsInnoRmluiError* error = null; using var nameText = new RmlUiUtf8String(name); fixed (ulong* contextPointer = &context) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CreateContext( runtime, @@ -44,8 +38,11 @@ ref ulong context density, contextPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -55,13 +52,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.DestroyContext( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.DestroyContext(runtime, context, &result, &error), error); return result; } @@ -75,16 +66,12 @@ ref byte hit Result result = default; BgcsInnoRmluiError* error = null; fixed (byte* hitPointer = &hit) + { RmlUiNativeErrors.CheckBridge( - UiNative.Raw.HasElementAtPoint( - runtime, - context, - x, - y, - hitPointer, - &result, - &error), - error); + UiNative.Raw.HasElementAtPoint(runtime, context, x, y, hitPointer, &result, &error), + error + ); + } return result; } @@ -95,14 +82,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.HideDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.HideDocument(runtime, context, document, &result, &error), error); return result; } @@ -118,6 +98,7 @@ ref ulong document using var markupText = new RmlUiUtf8String(markup); using var sourceUrlText = new RmlUiUtf8String(sourceUrl); fixed (ulong* documentPointer = &document) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.LoadDocument( runtime, @@ -126,8 +107,11 @@ ref ulong document (sbyte*)sourceUrlText.pointer, documentPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -143,17 +127,9 @@ byte fallback Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.LoadFont( - runtime, - data, - dataLength, - (sbyte*)family, - style, - weight, - fallback, - &result, - &error), - error); + UiNative.Raw.LoadFont(runtime, data, dataLength, (sbyte*)family, style, weight, fallback, &result, &error), + error + ); return result; } @@ -167,15 +143,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessKey( - runtime, - context, - key, - down, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessKey(runtime, context, key, down, modifiers, &result, &error), + error + ); return result; } @@ -189,15 +159,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseButton( - runtime, - context, - button, - down, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseButton(runtime, context, button, down, modifiers, &result, &error), + error + ); return result; } @@ -211,15 +175,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseMove( - runtime, - context, - x, - y, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseMove(runtime, context, x, y, modifiers, &result, &error), + error + ); return result; } @@ -233,15 +191,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseWheel( - runtime, - context, - x, - y, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseWheel(runtime, context, x, y, modifiers, &result, &error), + error + ); return result; } @@ -252,14 +204,7 @@ internal static Result ProcessText( ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessText( - runtime, - context, - (sbyte*)text, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ProcessText(runtime, context, (sbyte*)text, &result, &error), error); return result; } @@ -284,8 +229,10 @@ ulong pixelCapacity pixels, pixelCapacity, &result, - &error), - error); + &error + ), + error + ); return result; } @@ -293,29 +240,33 @@ internal static Result SetAttribute( InnoUIRmlUiAdapterRuntime* runtime, ulong context, ulong document, - string elementId, + string elementID, string name, string value, ref byte changed ) { Result result = default; BgcsInnoRmluiError* error = null; - using var elementIdText = new RmlUiUtf8String(elementId); + using var elementIDText = new RmlUiUtf8String(elementID); using var nameText = new RmlUiUtf8String(name); using var valueText = new RmlUiUtf8String(value); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetAttribute( runtime, context, document, - (sbyte*)elementIdText.pointer, + (sbyte*)elementIDText.pointer, (sbyte*)nameText.pointer, (sbyte*)valueText.pointer, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -323,28 +274,32 @@ internal static Result SetClass( InnoUIRmlUiAdapterRuntime* runtime, ulong context, ulong document, - string elementId, + string elementID, string className, byte active, ref byte changed ) { Result result = default; BgcsInnoRmluiError* error = null; - using var elementIdText = new RmlUiUtf8String(elementId); + using var elementIDText = new RmlUiUtf8String(elementID); using var classNameText = new RmlUiUtf8String(className); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetClass( runtime, context, document, - (sbyte*)elementIdText.pointer, + (sbyte*)elementIDText.pointer, (sbyte*)classNameText.pointer, active, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -352,26 +307,30 @@ internal static Result SetInnerMarkup( InnoUIRmlUiAdapterRuntime* runtime, ulong context, ulong document, - string elementId, + string elementID, string markup, ref byte changed ) { Result result = default; BgcsInnoRmluiError* error = null; - using var elementIdText = new RmlUiUtf8String(elementId); + using var elementIDText = new RmlUiUtf8String(elementID); using var markupText = new RmlUiUtf8String(markup); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetInnerMarkup( runtime, context, document, - (sbyte*)elementIdText.pointer, + (sbyte*)elementIDText.pointer, (sbyte*)markupText.pointer, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -385,15 +344,9 @@ float density Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.SetViewport( - runtime, - context, - width, - height, - density, - &result, - &error), - error); + UiNative.Raw.SetViewport(runtime, context, width, height, density, &result, &error), + error + ); return result; } @@ -404,14 +357,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ShowDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ShowDocument(runtime, context, document, &result, &error), error); return result; } @@ -421,13 +367,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.Update( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.Update(runtime, context, &result, &error), error); return result; } } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs index d680e456d..8dcc127e9 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs @@ -6,7 +6,10 @@ internal readonly unsafe ref struct RmlUiUtf8String { private readonly nint m_memory; - internal RmlUiUtf8String(string value) => m_memory = Marshal.StringToCoTaskMemUTF8(value); + internal RmlUiUtf8String(string value) + { + m_memory = Marshal.StringToCoTaskMemUTF8(value); + } internal byte* pointer => (byte*)m_memory; diff --git a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs index fb5762dfa..78075c0cb 100644 --- a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs +++ b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs @@ -12,7 +12,7 @@ namespace Inno.Build.Toolchains.Sdl3; /// public static class Sdl3Toolchain { - private static readonly string[] S_ARGUMENTS = ["-DSDL_SHARED=ON", "-DSDL_STATIC=OFF", "-DSDL_TESTS=OFF", "-DSDL_EXAMPLES=OFF"]; + private static readonly string[] ARGUMENTS = ["-DSDL_SHARED=ON", "-DSDL_STATIC=OFF", "-DSDL_TESTS=OFF", "-DSDL_EXAMPLES=OFF"]; /// /// Gets the component's sole source, binding and intermediate owner. @@ -24,8 +24,10 @@ public static class Sdl3Toolchain new NativeStaticBuildDefinition( "backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Native/StaticLibraries.cmake", ["extern/SDL"], - ["libSDL3"]), - bindingDefinition: "backends/Sdl3/native/Inno.Native.Sdl3/Bindings/bindings.props"); + ["libSDL3"] + ), + bindingDefinition: "backends/Sdl3/native/Inno.Native.Sdl3/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -53,26 +55,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(context.engineRoot, "extern", "SDL"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "SDL3-shared", S_ARGUMENTS, token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "SDL3-shared", + ARGUMENTS, + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*SDL3" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -101,10 +118,20 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } string implementation = componentDescriptor.GetToolchainRoot(context.engineRoot); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "sdl3", selection.targetId, - [Path.Combine(context.engineRoot, "extern", "SDL")], S_ARGUMENTS, - [Path.Combine(implementation, "Sdl3Toolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "sdl3", + selection.targetID, + [Path.Combine(context.engineRoot, "extern", "SDL")], + ARGUMENTS, + [Path.Combine(implementation, "Sdl3Toolchain.cs")] + ); } } diff --git a/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs b/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs index 5d528de26..ce495d85c 100644 --- a/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs +++ b/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs @@ -8,9 +8,9 @@ namespace Inno.Native.Sdl3; public static unsafe partial class SDL { #if DEBUG - internal const string LibName = "SDL3-debug"; + internal const string C_LIB_NAME = "SDL3-debug"; #else - internal const string LibName = "SDL3-release"; + internal const string C_LIB_NAME = "SDL3-release"; #endif static SDL() @@ -20,7 +20,7 @@ static SDL() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/ISdl3ApplicationExtension.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/ISdl3ApplicationExtension.cs index 8e920b3f3..fb130df4d 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/ISdl3ApplicationExtension.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/ISdl3ApplicationExtension.cs @@ -27,12 +27,12 @@ scoped ReadOnlySpan nativeEventData /// /// The platform application requesting the redraw. /// - /// + /// /// The platform window identifier being resized. /// void PrepareLiveResizeWindow( Sdl3PlatformApplication application, - uint windowId + uint windowID ); /// diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs index 06a1ef0a6..207a79fd3 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs @@ -54,7 +54,9 @@ public static class Sdl3FolderDialog Thread.Sleep(10); } if (pumpFailure is not null) + { throw new InvalidOperationException("Platform event processing failed while selecting a directory.", pumpFailure); + } return result.Task.GetAwaiter().GetResult(); } finally @@ -69,13 +71,17 @@ private static unsafe void Complete( sbyte** files, int filter ) { - var result = (TaskCompletionSource)GCHandle.FromIntPtr((nint)userData).Target!; + TaskCompletionSource result = (TaskCompletionSource)GCHandle.FromIntPtr((nint)userData).Target!; try { - if (files == null) + if (files is null) + { result.TrySetException(new InvalidOperationException(Sdl3NativeText.ReadError() ?? "The native folder dialog failed.")); + } else - result.TrySetResult(files[0] == null ? null : Marshal.PtrToStringUTF8((nint)files[0])); + { + result.TrySetResult(files[0] is null ? null : Marshal.PtrToStringUTF8((nint)files[0])); + } } catch (Exception failure) { diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs index 20c3bac94..922b27a01 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs @@ -10,11 +10,6 @@ namespace Inno.Adapter.Platform.Sdl3; /// public sealed unsafe partial class Sdl3PlatformApplication : IPlatformApplication { - /// - /// Occurs after the observable redraw requested state changes. - /// - public event Action? redrawRequested; - /// /// Initializes platform subsystems required for windowing and input events. /// @@ -32,6 +27,11 @@ public Sdl3PlatformApplication(ISdl3HostIntegration hostIntegration) Initialize(); } + /// + /// Occurs after the observable redraw requested state changes. + /// + public event Action? redrawRequested; + /// /// Creates a platform window from the provided options. /// @@ -63,12 +63,6 @@ public Sdl3PlatformApplication(ISdl3HostIntegration hostIntegration) /// public partial IReadOnlyList GetWindows(); - IPlatformWindow IPlatformApplication.CreateWindow(PlatformWindowOptions options) - => CreateWindow(options); - - IReadOnlyList IPlatformApplication.GetWindows() - => GetWindows(); - /// /// Registers an optional platform backend integration for this application instance. /// @@ -84,4 +78,8 @@ IReadOnlyList IPlatformApplication.GetWindows() /// Releases all platform resources owned by this application instance. /// public partial void Dispose(); + + IPlatformWindow IPlatformApplication.CreateWindow(PlatformWindowOptions options) => CreateWindow(options); + + IReadOnlyList IPlatformApplication.GetWindows() => GetWindows(); } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs index ee1fd4309..78231d871 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs @@ -1,5 +1,5 @@ -using Inno.Adapter.Platform; using System; +using Inno.Adapter.Platform; using Inno.Platform; namespace Inno.Adapter.Platform.Sdl3; @@ -12,7 +12,7 @@ public sealed unsafe partial class Sdl3PlatformWindow : IPlatformWindow, INative /// /// Gets the platform window identifier. /// - public uint windowId => m_windowId; + public uint windowID => m_windowID; /// /// Gets the window title. diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs index b4bdac357..49b11b150 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs @@ -36,7 +36,9 @@ bool requireOpenGl ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.height); uint properties = SDL.CreateProperties(); if (properties == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_CreateProperties failed."); + } try { if (!SDL.SetStringProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_TITLE_STRING, options.title) @@ -45,13 +47,19 @@ bool requireOpenGl || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, requireOpenGl) || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, !options.visible) || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, options.resizable) - || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, options.highPixelDensity)) - { + || !SDL.SetBooleanProperty( + properties, + SDL.Constants.SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, + options.highPixelDensity + ) + ) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window properties could not be set."); } SDLWindow* window = SDL.Raw.CreateWindowWithProperties(properties); - if (window == null) + if (window is null) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window creation failed."); + } return (nint)window; } finally @@ -75,7 +83,9 @@ bool requireOpenGl public static unsafe bool ReadFocus(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } return ((SDLWindowFlags)SDL.Raw.GetWindowFlags((SDLWindow*)windowHandle) & SDLWindowFlags.InputFocus) != 0; } } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs index bc104195f..bf7c20b29 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; using System.Threading; using Inno.Core.Events; using Inno.Core.Input; @@ -17,7 +17,7 @@ namespace Inno.Adapter.Platform.Sdl3; public sealed unsafe partial class Sdl3PlatformApplication { private readonly ISdl3HostIntegration m_hostIntegration; - private readonly int m_ownerThreadId = Environment.CurrentManagedThreadId; + private readonly int m_ownerThreadID = Environment.CurrentManagedThreadId; private readonly List m_pendingEvents = []; private readonly Dictionary m_windows = []; private readonly List m_extensions = []; @@ -27,52 +27,12 @@ public sealed unsafe partial class Sdl3PlatformApplication private unsafe delegate* unmanaged[Cdecl] m_liveResizeMainThreadCallbackPointer; private GCHandle m_liveResizeEventWatchHandle; private int m_liveResizeRedrawQueued; - private uint m_liveResizeWindowId; + private uint m_liveResizeWindowID; private ExceptionDispatchInfo? m_redrawFailure; private bool m_dispatchingRedraw; private int m_pendingEventReadIndex; private bool m_disposed; - private unsafe void Initialize() - { - // Deliver the activating mouse press to the application as well as focusing the window. - // This is required for first-click widgets, double-clicks, and drags across editor viewports. - _ = SDL.SetHint(SDL.Constants.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); - _ = SDL.SetHint(SDL.Constants.SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); - - m_hostIntegration.ConfigureInitialization(); - - if (!SDL.Init(SDLInitFlags.Video | SDLInitFlags.Events)) - { - throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_Init failed."); - } - - // Browser frames are already driven by requestAnimationFrame; SDL's native - // resize callback is only needed by desktop window move/resize loops. - if (!m_hostIntegration.capabilities.liveResize) - return; - - m_liveResizeEventWatch = LiveResizeEventWatch; - m_liveResizeMainThreadCallback = LiveResizeMainThreadCallback; - m_liveResizeEventWatchPointer = (delegate* unmanaged[Cdecl]) - Marshal.GetFunctionPointerForDelegate(m_liveResizeEventWatch); - m_liveResizeMainThreadCallbackPointer = (delegate* unmanaged[Cdecl]) - Marshal.GetFunctionPointerForDelegate(m_liveResizeMainThreadCallback); - m_liveResizeEventWatchHandle = GCHandle.Alloc(this, GCHandleType.Normal); - var userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); - if (SDL.Raw.AddEventWatch(m_liveResizeEventWatchPointer, (void*)userData) == 0) - { - Exception failure = new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_AddEventWatch failed."); - m_liveResizeEventWatchHandle.Free(); - m_liveResizeEventWatch = null; - m_liveResizeMainThreadCallback = null; - m_liveResizeEventWatchPointer = null; - m_liveResizeMainThreadCallbackPointer = null; - SDL.QuitSubSystem(SDLInitFlags.Video | SDLInitFlags.Events); - throw failure; - } - } - /// /// Attempts to dequeue the next backend-neutral platform event. /// @@ -117,9 +77,6 @@ public partial IReadOnlyList GetWindows() return GetWindowsCore(); } - private IReadOnlyList GetWindowsCore() - => new List(m_windows.Values).AsReadOnly(); - /// /// Registers a platform extension for the application lifetime. /// @@ -135,62 +92,13 @@ public partial IDisposable RegisterExtension(ISdl3ApplicationExtension extension ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(extension); if (m_extensions.Contains(extension)) + { throw new InvalidOperationException("The platform extension is already registered."); + } m_extensions.Add(extension); return new ExtensionRegistration(this, extension); } - private bool TryDequeuePendingEvent(out Event? evnt) - { - if (m_pendingEventReadIndex >= m_pendingEvents.Count) - { - evnt = null; - return false; - } - - evnt = m_pendingEvents[m_pendingEventReadIndex++]; - if (m_pendingEventReadIndex >= m_pendingEvents.Count) - { - m_pendingEvents.Clear(); - m_pendingEventReadIndex = 0; - } - - return true; - } - - private void PollAndCoalescePendingEvents() - { - m_pendingEvents.Clear(); - m_pendingEventReadIndex = 0; - - Dictionary latestEventIndicesByKey = new(); - SDLEvent sdlEvent = default; - while (SDL.Raw.PollEvent(&sdlEvent) != 0) - { - m_redrawFailure?.Throw(); - DispatchNativeEvent(ref sdlEvent); - - if (!TryTranslateEvent(ref sdlEvent, out var translatedEvent) || translatedEvent is null) - { - continue; - } - - if (TryCreatePendingEventCoalesceKey(translatedEvent, out var key) - && latestEventIndicesByKey.TryGetValue(key, out var index)) - { - m_pendingEvents[index] = translatedEvent; - continue; - } - - var nextIndex = m_pendingEvents.Count; - m_pendingEvents.Add(translatedEvent); - if (TryCreatePendingEventCoalesceKey(translatedEvent, out key)) - { - latestEventIndicesByKey[key] = nextIndex; - } - } - } - /// /// Releases the resources owned by this instance. /// @@ -204,7 +112,7 @@ public partial void Dispose() if (m_liveResizeEventWatch is not null && m_liveResizeEventWatchHandle.IsAllocated) { - var userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); + nint userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); unsafe { SDL.Raw.RemoveEventWatch(m_liveResizeEventWatchPointer, (void*)userData); @@ -220,10 +128,12 @@ public partial void Dispose() } foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) + { extension.OnApplicationDisposing(this); + } m_extensions.Clear(); - foreach (var window in new List(m_windows.Values)) + foreach (Sdl3PlatformWindow window in new List(m_windows.Values)) { window.Dispose(); } @@ -233,95 +143,135 @@ public partial void Dispose() m_disposed = true; } - private static unsafe byte LiveResizeEventWatch( - void* userData, - SDLEvent* evnt - ) { - if (userData == null || evnt == null) - { - return 1; - } + private unsafe void Initialize() + { + // Deliver the activating mouse press to the application as well as focusing the window. + // This is required for first-click widgets, double-clicks, and drags across editor viewports. + _ = SDL.SetHint(SDL.Constants.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); + _ = SDL.SetHint(SDL.Constants.SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); - var eventType = (SDLEventType)evnt->Type; - if (eventType != SDLEventType.WindowExposed || evnt->Window.Data1 == 0) + m_hostIntegration.ConfigureInitialization(); + + if (!SDL.Init(SDLInitFlags.Video | SDLInitFlags.Events)) { - return 1; + throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_Init failed."); } - var handle = GCHandle.FromIntPtr((IntPtr)userData); - if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) + // Browser frames are already driven by requestAnimationFrame; SDL's native + // resize callback is only needed by desktop window move/resize loops. + if (!m_hostIntegration.capabilities.liveResize) { - return 1; + return; } - Volatile.Write(ref application.m_liveResizeWindowId, evnt->Window.WindowID); - if (Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 1) == 0) + m_liveResizeEventWatch = LiveResizeEventWatch; + m_liveResizeMainThreadCallback = LiveResizeMainThreadCallback; + m_liveResizeEventWatchPointer = (delegate* unmanaged[Cdecl]) + Marshal.GetFunctionPointerForDelegate(m_liveResizeEventWatch); + m_liveResizeMainThreadCallbackPointer = (delegate* unmanaged[Cdecl]) + Marshal.GetFunctionPointerForDelegate(m_liveResizeMainThreadCallback); + m_liveResizeEventWatchHandle = GCHandle.Alloc(this, GCHandleType.Normal); + nint userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); + if (SDL.Raw.AddEventWatch(m_liveResizeEventWatchPointer, (void*)userData) == 0) { - var userDataPtr = (nint)GCHandle.ToIntPtr(application.m_liveResizeEventWatchHandle); - if (SDL.Raw.RunOnMainThread(application.m_liveResizeMainThreadCallbackPointer, (void*)userDataPtr, 0) == 0) - { - Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); - } + Exception failure = new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_AddEventWatch failed."); + m_liveResizeEventWatchHandle.Free(); + m_liveResizeEventWatch = null; + m_liveResizeMainThreadCallback = null; + m_liveResizeEventWatchPointer = null; + m_liveResizeMainThreadCallbackPointer = null; + SDL.QuitSubSystem(SDLInitFlags.Video | SDLInitFlags.Events); + throw failure; } - - return 1; } - private static unsafe void LiveResizeMainThreadCallback(void* userData) + private IReadOnlyList GetWindowsCore() + => new List(m_windows.Values).AsReadOnly(); + + private bool TryDequeuePendingEvent(out Event? evnt) { - if (userData == null) + if (m_pendingEventReadIndex >= m_pendingEvents.Count) { - return; + evnt = null; + return false; } - var handle = GCHandle.FromIntPtr((IntPtr)userData); - if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) + evnt = m_pendingEvents[m_pendingEventReadIndex++]; + if (m_pendingEventReadIndex >= m_pendingEvents.Count) { - return; + m_pendingEvents.Clear(); + m_pendingEventReadIndex = 0; } - var windowId = Volatile.Read(ref application.m_liveResizeWindowId); - Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); - if (windowId != 0) + return true; + } + + private void PollAndCoalescePendingEvents() + { + m_pendingEvents.Clear(); + m_pendingEventReadIndex = 0; + + Dictionary latestEventIndicesByKey = []; + SDLEvent sdlEvent = default; + while (SDL.Raw.PollEvent(&sdlEvent) != 0) { - try + m_redrawFailure?.Throw(); + DispatchNativeEvent(ref sdlEvent); + + if (!TryTranslateEvent(ref sdlEvent, out Event? translatedEvent) || translatedEvent is null) { - application.DispatchLiveResizeRedraw(windowId); + continue; } - catch (Exception exception) + + if (TryCreatePendingEventCoalesceKey(translatedEvent, out PendingEventCoalesceKey key) + && latestEventIndicesByKey.TryGetValue(key, out int index) + ) { + m_pendingEvents[index] = translatedEvent; + continue; + } + + int nextIndex = m_pendingEvents.Count; + m_pendingEvents.Add(translatedEvent); + if (TryCreatePendingEventCoalesceKey(translatedEvent, out key)) { - // Never unwind managed exceptions through SDL's native event callback. - application.m_redrawFailure ??= ExceptionDispatchInfo.Capture(exception); + latestEventIndicesByKey[key] = nextIndex; } } } private unsafe void DispatchNativeEvent(ref SDLEvent sdlEvent) { - ReadOnlySpan nativeEventData = new( - Unsafe.AsPointer(ref sdlEvent), - sizeof(SDLEvent)); + var nativeEventData = new ReadOnlySpan(Unsafe.AsPointer(ref sdlEvent), sizeof(SDLEvent)); foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) + { extension.ProcessNativeEvent(this, nativeEventData); + } } - private void DispatchLiveResizeRedraw(uint windowId) + private void DispatchLiveResizeRedraw(uint windowID) { if (m_dispatchingRedraw || m_redrawFailure is not null) + { return; + } m_dispatchingRedraw = true; try { - if (m_windows.TryGetValue(windowId, out Sdl3PlatformWindow? window)) + if (m_windows.TryGetValue(windowID, out Sdl3PlatformWindow? window)) { - int width = 0, height = 0; + int width = 0; + int height = 0; if (SDL.Raw.GetWindowSize(window.sdlWindow, &width, &height) == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed during live resize."); + } window.UpdateLogicalSize(width, height); } foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) - extension.PrepareLiveResizeWindow(this, windowId); - redrawRequested?.Invoke(windowId); + { + extension.PrepareLiveResizeWindow(this, windowID); + } + redrawRequested?.Invoke(windowID); } finally { @@ -331,31 +281,11 @@ private void DispatchLiveResizeRedraw(uint windowId) private void UnregisterExtension(ISdl3ApplicationExtension extension) => m_extensions.Remove(extension); - private sealed class ExtensionRegistration( - Sdl3PlatformApplication application, - ISdl3ApplicationExtension extension - ) : IDisposable - { - private Sdl3PlatformApplication? m_application = application; - private ISdl3ApplicationExtension? m_extension = extension; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - Sdl3PlatformApplication? owner = Interlocked.Exchange(ref m_application, null); - ISdl3ApplicationExtension? registered = Interlocked.Exchange(ref m_extension, null); - if (owner is not null && registered is not null) - owner.UnregisterExtension(registered); - } - } - private unsafe bool TryTranslateEvent( ref SDLEvent sdlEvent, out Event? evnt ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; switch (eventType) { case SDLEventType.Quit: @@ -377,14 +307,14 @@ out Event? evnt if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? visibleWindow)) { visibleWindow.UpdateVisibility(eventType); - evnt = new WindowVisibilityChangedEvent(visibleWindow.windowId, visibleWindow.isVisible); + evnt = new WindowVisibilityChangedEvent(visibleWindow.windowID, visibleWindow.isVisible); return true; } evnt = null; return false; case SDLEventType.WindowResized: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var resizedWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? resizedWindow)) { resizedWindow.UpdateLogicalSize(sdlEvent.Window.Data1, sdlEvent.Window.Data2); } @@ -393,13 +323,14 @@ out Event? evnt return true; case SDLEventType.WindowPixelSizeChanged: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var pixelResizedWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? pixelResizedWindow)) { pixelResizedWindow.UpdatePixelSize(sdlEvent.Window.Data1, sdlEvent.Window.Data2); evnt = new WindowResizeEvent( sdlEvent.Window.WindowID, pixelResizedWindow.width, - pixelResizedWindow.height); + pixelResizedWindow.height + ); return true; } @@ -407,7 +338,7 @@ out Event? evnt return false; case SDLEventType.WindowCloseRequested: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var closingWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? closingWindow)) { closingWindow.MarkClosed(); } @@ -420,32 +351,34 @@ out Event? evnt { bool isFocused = eventType == SDLEventType.WindowFocusGained; if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? focusedWindow)) + { focusedWindow.UpdateFocus(isFocused); + } evnt = new WindowFocusChangedEvent(sdlEvent.Window.WindowID, isFocused); return true; } case SDLEventType.KeyDown: { - var key = TranslateKey(sdlEvent.Key.Key); - var modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); + KeyCode key = TranslateKey(sdlEvent.Key.Key); + KeyModifier modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); evnt = new KeyPressedEvent(sdlEvent.Key.WindowID, key, modifiers, sdlEvent.Key.Repeat != 0); return true; } case SDLEventType.KeyUp: { - var key = TranslateKey(sdlEvent.Key.Key); - var modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); + KeyCode key = TranslateKey(sdlEvent.Key.Key); + KeyModifier modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); evnt = new KeyReleasedEvent(sdlEvent.Key.WindowID, key, modifiers); return true; } case SDLEventType.TextInput: { - string? text = sdlEvent.Text.Text == null - ? null - : Marshal.PtrToStringUTF8((IntPtr)sdlEvent.Text.Text); + string? text = sdlEvent.Text.Text is null + ? null + : Marshal.PtrToStringUTF8((nint)sdlEvent.Text.Text); if (!string.IsNullOrEmpty(text)) { evnt = new TextInputEvent(sdlEvent.Text.WindowID, text); @@ -460,8 +393,8 @@ out Event? evnt case SDLEventType.MouseWheel: { - var wheelX = sdlEvent.Wheel.X; - var wheelY = sdlEvent.Wheel.Y; + float wheelX = sdlEvent.Wheel.X; + float wheelY = sdlEvent.Wheel.Y; if (sdlEvent.Wheel.Direction == SDLMouseWheelDirection.MousewheelFlipped) { wheelX = -wheelX; @@ -473,7 +406,7 @@ out Event? evnt } case SDLEventType.MouseButtonDown: - if (TryTranslateMouseButton(sdlEvent.Button.Button, out var pressedButton)) + if (TryTranslateMouseButton(sdlEvent.Button.Button, out MouseButton pressedButton)) { evnt = new MouseButtonPressedEvent(sdlEvent.Button.WindowID, pressedButton); return true; @@ -482,7 +415,7 @@ out Event? evnt break; case SDLEventType.MouseButtonUp: - if (TryTranslateMouseButton(sdlEvent.Button.Button, out var releasedButton)) + if (TryTranslateMouseButton(sdlEvent.Button.Button, out MouseButton releasedButton)) { evnt = new MouseButtonReleasedEvent(sdlEvent.Button.WindowID, releasedButton); return true; @@ -495,10 +428,73 @@ out Event? evnt return false; } + private static unsafe byte LiveResizeEventWatch( + void* userData, + SDLEvent* evnt + ) { + if (userData is null || evnt is null) + { + return 1; + } + + SDLEventType eventType = (SDLEventType)evnt->Type; + if (eventType != SDLEventType.WindowExposed || evnt->Window.Data1 == 0) + { + return 1; + } + + GCHandle handle = GCHandle.FromIntPtr((nint)userData); + if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) + { + return 1; + } + + Volatile.Write(ref application.m_liveResizeWindowID, evnt->Window.WindowID); + if (Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 1) == 0) + { + nint userDataPtr = (nint)GCHandle.ToIntPtr(application.m_liveResizeEventWatchHandle); + if (SDL.Raw.RunOnMainThread(application.m_liveResizeMainThreadCallbackPointer, (void*)userDataPtr, 0) == 0) + { + Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); + } + } + + return 1; + } + + private static unsafe void LiveResizeMainThreadCallback(void* userData) + { + if (userData is null) + { + return; + } + + GCHandle handle = GCHandle.FromIntPtr((nint)userData); + if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) + { + return; + } + + uint windowID = Volatile.Read(ref application.m_liveResizeWindowID); + Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); + if (windowID != 0) + { + try + { + application.DispatchLiveResizeRedraw(windowID); + } + catch (Exception exception) + { + // Never unwind managed exceptions through SDL's native event callback. + application.m_redrawFailure ??= ExceptionDispatchInfo.Capture(exception); + } + } + } + private static KeyModifier TranslateModifiers(SDLKeymod modifiers) { - var sdlModifiers = (uint)modifiers; - var result = KeyModifier.None; + uint sdlModifiers = (uint)modifiers; + KeyModifier result = KeyModifier.None; if ((sdlModifiers & (SDL.Constants.SDL_KMOD_LSHIFT | SDL.Constants.SDL_KMOD_RSHIFT)) != 0) { @@ -551,117 +547,115 @@ out MouseButton button } private static KeyCode TranslateKey(uint sdlKey) + => sdlKey switch { - return sdlKey switch - { - SDL.Constants.SDLK_A => KeyCode.A, - SDL.Constants.SDLK_B => KeyCode.B, - SDL.Constants.SDLK_C => KeyCode.C, - SDL.Constants.SDLK_D => KeyCode.D, - SDL.Constants.SDLK_E => KeyCode.E, - SDL.Constants.SDLK_F => KeyCode.F, - SDL.Constants.SDLK_G => KeyCode.G, - SDL.Constants.SDLK_H => KeyCode.H, - SDL.Constants.SDLK_I => KeyCode.I, - SDL.Constants.SDLK_J => KeyCode.J, - SDL.Constants.SDLK_K => KeyCode.K, - SDL.Constants.SDLK_L => KeyCode.L, - SDL.Constants.SDLK_M => KeyCode.M, - SDL.Constants.SDLK_N => KeyCode.N, - SDL.Constants.SDLK_O => KeyCode.O, - SDL.Constants.SDLK_P => KeyCode.P, - SDL.Constants.SDLK_Q => KeyCode.Q, - SDL.Constants.SDLK_R => KeyCode.R, - SDL.Constants.SDLK_S => KeyCode.S, - SDL.Constants.SDLK_T => KeyCode.T, - SDL.Constants.SDLK_U => KeyCode.U, - SDL.Constants.SDLK_V => KeyCode.V, - SDL.Constants.SDLK_W => KeyCode.W, - SDL.Constants.SDLK_X => KeyCode.X, - SDL.Constants.SDLK_Y => KeyCode.Y, - SDL.Constants.SDLK_Z => KeyCode.Z, - - SDL.Constants.SDLK_0 => KeyCode.D0, - SDL.Constants.SDLK_1 => KeyCode.D1, - SDL.Constants.SDLK_2 => KeyCode.D2, - SDL.Constants.SDLK_3 => KeyCode.D3, - SDL.Constants.SDLK_4 => KeyCode.D4, - SDL.Constants.SDLK_5 => KeyCode.D5, - SDL.Constants.SDLK_6 => KeyCode.D6, - SDL.Constants.SDLK_7 => KeyCode.D7, - SDL.Constants.SDLK_8 => KeyCode.D8, - SDL.Constants.SDLK_9 => KeyCode.D9, - - SDL.Constants.SDLK_ESCAPE => KeyCode.Escape, - SDL.Constants.SDLK_SPACE => KeyCode.Space, - SDL.Constants.SDLK_RETURN => KeyCode.Enter, - SDL.Constants.SDLK_TAB => KeyCode.Tab, - SDL.Constants.SDLK_BACKSPACE => KeyCode.Backspace, - - SDL.Constants.SDLK_LEFT => KeyCode.LeftArrow, - SDL.Constants.SDLK_UP => KeyCode.UpArrow, - SDL.Constants.SDLK_RIGHT => KeyCode.RightArrow, - SDL.Constants.SDLK_DOWN => KeyCode.DownArrow, - - SDL.Constants.SDLK_LGUI => KeyCode.LeftSuper, - SDL.Constants.SDLK_RGUI => KeyCode.RightSuper, - SDL.Constants.SDLK_LSHIFT => KeyCode.LeftShift, - SDL.Constants.SDLK_RSHIFT => KeyCode.RightShift, - SDL.Constants.SDLK_LCTRL => KeyCode.LeftCtrl, - SDL.Constants.SDLK_RCTRL => KeyCode.RightCtrl, - SDL.Constants.SDLK_LALT => KeyCode.LeftAlt, - SDL.Constants.SDLK_RALT => KeyCode.RightAlt, - - SDL.Constants.SDLK_CAPSLOCK => KeyCode.CapsLock, - SDL.Constants.SDLK_INSERT => KeyCode.Insert, - SDL.Constants.SDLK_DELETE => KeyCode.Delete, - SDL.Constants.SDLK_HOME => KeyCode.Home, - SDL.Constants.SDLK_END => KeyCode.End, - SDL.Constants.SDLK_PAGEUP => KeyCode.PageUp, - SDL.Constants.SDLK_PAGEDOWN => KeyCode.PageDown, - - SDL.Constants.SDLK_KP_0 => KeyCode.NumPad0, - SDL.Constants.SDLK_KP_1 => KeyCode.NumPad1, - SDL.Constants.SDLK_KP_2 => KeyCode.NumPad2, - SDL.Constants.SDLK_KP_3 => KeyCode.NumPad3, - SDL.Constants.SDLK_KP_4 => KeyCode.NumPad4, - SDL.Constants.SDLK_KP_5 => KeyCode.NumPad5, - SDL.Constants.SDLK_KP_6 => KeyCode.NumPad6, - SDL.Constants.SDLK_KP_7 => KeyCode.NumPad7, - SDL.Constants.SDLK_KP_8 => KeyCode.NumPad8, - SDL.Constants.SDLK_KP_9 => KeyCode.NumPad9, - - SDL.Constants.SDLK_NUMLOCKCLEAR => KeyCode.NumLock, - SDL.Constants.SDLK_SCROLLLOCK => KeyCode.ScrollLock, - - SDL.Constants.SDLK_F1 => KeyCode.F1, - SDL.Constants.SDLK_F2 => KeyCode.F2, - SDL.Constants.SDLK_F3 => KeyCode.F3, - SDL.Constants.SDLK_F4 => KeyCode.F4, - SDL.Constants.SDLK_F5 => KeyCode.F5, - SDL.Constants.SDLK_F6 => KeyCode.F6, - SDL.Constants.SDLK_F7 => KeyCode.F7, - SDL.Constants.SDLK_F8 => KeyCode.F8, - SDL.Constants.SDLK_F9 => KeyCode.F9, - SDL.Constants.SDLK_F10 => KeyCode.F10, - SDL.Constants.SDLK_F11 => KeyCode.F11, - SDL.Constants.SDLK_F12 => KeyCode.F12, - - SDL.Constants.SDLK_PLUS => KeyCode.Plus, - SDL.Constants.SDLK_EQUALS => KeyCode.Plus, - SDL.Constants.SDLK_COMMA => KeyCode.Comma, - SDL.Constants.SDLK_MINUS => KeyCode.Minus, - SDL.Constants.SDLK_PERIOD => KeyCode.Period, - SDL.Constants.SDLK_SLASH => KeyCode.Slash, - SDL.Constants.SDLK_GRAVE => KeyCode.Tilde, - SDL.Constants.SDLK_BACKSLASH => KeyCode.Backslash, - SDL.Constants.SDLK_SEMICOLON => KeyCode.Semicolon, - SDL.Constants.SDLK_APOSTROPHE => KeyCode.Quote, - SDL.Constants.SDLK_LEFTBRACKET => KeyCode.LeftBracket, - SDL.Constants.SDLK_RIGHTBRACKET => KeyCode.RightBracket, - _ => KeyCode.Unknown - }; - } + SDL.Constants.SDLK_A => KeyCode.A, + SDL.Constants.SDLK_B => KeyCode.B, + SDL.Constants.SDLK_C => KeyCode.C, + SDL.Constants.SDLK_D => KeyCode.D, + SDL.Constants.SDLK_E => KeyCode.E, + SDL.Constants.SDLK_F => KeyCode.F, + SDL.Constants.SDLK_G => KeyCode.G, + SDL.Constants.SDLK_H => KeyCode.H, + SDL.Constants.SDLK_I => KeyCode.I, + SDL.Constants.SDLK_J => KeyCode.J, + SDL.Constants.SDLK_K => KeyCode.K, + SDL.Constants.SDLK_L => KeyCode.L, + SDL.Constants.SDLK_M => KeyCode.M, + SDL.Constants.SDLK_N => KeyCode.N, + SDL.Constants.SDLK_O => KeyCode.O, + SDL.Constants.SDLK_P => KeyCode.P, + SDL.Constants.SDLK_Q => KeyCode.Q, + SDL.Constants.SDLK_R => KeyCode.R, + SDL.Constants.SDLK_S => KeyCode.S, + SDL.Constants.SDLK_T => KeyCode.T, + SDL.Constants.SDLK_U => KeyCode.U, + SDL.Constants.SDLK_V => KeyCode.V, + SDL.Constants.SDLK_W => KeyCode.W, + SDL.Constants.SDLK_X => KeyCode.X, + SDL.Constants.SDLK_Y => KeyCode.Y, + SDL.Constants.SDLK_Z => KeyCode.Z, + + SDL.Constants.SDLK_0 => KeyCode.D0, + SDL.Constants.SDLK_1 => KeyCode.D1, + SDL.Constants.SDLK_2 => KeyCode.D2, + SDL.Constants.SDLK_3 => KeyCode.D3, + SDL.Constants.SDLK_4 => KeyCode.D4, + SDL.Constants.SDLK_5 => KeyCode.D5, + SDL.Constants.SDLK_6 => KeyCode.D6, + SDL.Constants.SDLK_7 => KeyCode.D7, + SDL.Constants.SDLK_8 => KeyCode.D8, + SDL.Constants.SDLK_9 => KeyCode.D9, + + SDL.Constants.SDLK_ESCAPE => KeyCode.Escape, + SDL.Constants.SDLK_SPACE => KeyCode.Space, + SDL.Constants.SDLK_RETURN => KeyCode.Enter, + SDL.Constants.SDLK_TAB => KeyCode.Tab, + SDL.Constants.SDLK_BACKSPACE => KeyCode.Backspace, + + SDL.Constants.SDLK_LEFT => KeyCode.LeftArrow, + SDL.Constants.SDLK_UP => KeyCode.UpArrow, + SDL.Constants.SDLK_RIGHT => KeyCode.RightArrow, + SDL.Constants.SDLK_DOWN => KeyCode.DownArrow, + + SDL.Constants.SDLK_LGUI => KeyCode.LeftSuper, + SDL.Constants.SDLK_RGUI => KeyCode.RightSuper, + SDL.Constants.SDLK_LSHIFT => KeyCode.LeftShift, + SDL.Constants.SDLK_RSHIFT => KeyCode.RightShift, + SDL.Constants.SDLK_LCTRL => KeyCode.LeftCtrl, + SDL.Constants.SDLK_RCTRL => KeyCode.RightCtrl, + SDL.Constants.SDLK_LALT => KeyCode.LeftAlt, + SDL.Constants.SDLK_RALT => KeyCode.RightAlt, + + SDL.Constants.SDLK_CAPSLOCK => KeyCode.CapsLock, + SDL.Constants.SDLK_INSERT => KeyCode.Insert, + SDL.Constants.SDLK_DELETE => KeyCode.Delete, + SDL.Constants.SDLK_HOME => KeyCode.Home, + SDL.Constants.SDLK_END => KeyCode.End, + SDL.Constants.SDLK_PAGEUP => KeyCode.PageUp, + SDL.Constants.SDLK_PAGEDOWN => KeyCode.PageDown, + + SDL.Constants.SDLK_KP_0 => KeyCode.NumPad0, + SDL.Constants.SDLK_KP_1 => KeyCode.NumPad1, + SDL.Constants.SDLK_KP_2 => KeyCode.NumPad2, + SDL.Constants.SDLK_KP_3 => KeyCode.NumPad3, + SDL.Constants.SDLK_KP_4 => KeyCode.NumPad4, + SDL.Constants.SDLK_KP_5 => KeyCode.NumPad5, + SDL.Constants.SDLK_KP_6 => KeyCode.NumPad6, + SDL.Constants.SDLK_KP_7 => KeyCode.NumPad7, + SDL.Constants.SDLK_KP_8 => KeyCode.NumPad8, + SDL.Constants.SDLK_KP_9 => KeyCode.NumPad9, + + SDL.Constants.SDLK_NUMLOCKCLEAR => KeyCode.NumLock, + SDL.Constants.SDLK_SCROLLLOCK => KeyCode.ScrollLock, + + SDL.Constants.SDLK_F1 => KeyCode.F1, + SDL.Constants.SDLK_F2 => KeyCode.F2, + SDL.Constants.SDLK_F3 => KeyCode.F3, + SDL.Constants.SDLK_F4 => KeyCode.F4, + SDL.Constants.SDLK_F5 => KeyCode.F5, + SDL.Constants.SDLK_F6 => KeyCode.F6, + SDL.Constants.SDLK_F7 => KeyCode.F7, + SDL.Constants.SDLK_F8 => KeyCode.F8, + SDL.Constants.SDLK_F9 => KeyCode.F9, + SDL.Constants.SDLK_F10 => KeyCode.F10, + SDL.Constants.SDLK_F11 => KeyCode.F11, + SDL.Constants.SDLK_F12 => KeyCode.F12, + + SDL.Constants.SDLK_PLUS => KeyCode.Plus, + SDL.Constants.SDLK_EQUALS => KeyCode.Plus, + SDL.Constants.SDLK_COMMA => KeyCode.Comma, + SDL.Constants.SDLK_MINUS => KeyCode.Minus, + SDL.Constants.SDLK_PERIOD => KeyCode.Period, + SDL.Constants.SDLK_SLASH => KeyCode.Slash, + SDL.Constants.SDLK_GRAVE => KeyCode.Tilde, + SDL.Constants.SDLK_BACKSLASH => KeyCode.Backslash, + SDL.Constants.SDLK_SEMICOLON => KeyCode.Semicolon, + SDL.Constants.SDLK_APOSTROPHE => KeyCode.Quote, + SDL.Constants.SDLK_LEFTBRACKET => KeyCode.LeftBracket, + SDL.Constants.SDLK_RIGHTBRACKET => KeyCode.RightBracket, + _ => KeyCode.Unknown + }; private static bool TryCreatePendingEventCoalesceKey( Event evnt, @@ -669,7 +663,7 @@ out PendingEventCoalesceKey key ) { if (evnt is WindowEvent windowEvent) { - key = new PendingEventCoalesceKey(windowEvent.windowId, evnt.GetType()); + key = new PendingEventCoalesceKey(windowEvent.windowID, evnt.GetType()); return true; } @@ -683,8 +677,30 @@ out PendingEventCoalesceKey key return false; } + private sealed class ExtensionRegistration( + Sdl3PlatformApplication application, + ISdl3ApplicationExtension extension + ) : IDisposable + { + private Sdl3PlatformApplication? m_application = application; + private ISdl3ApplicationExtension? m_extension = extension; + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + Sdl3PlatformApplication? owner = Interlocked.Exchange(ref m_application, null); + ISdl3ApplicationExtension? registered = Interlocked.Exchange(ref m_extension, null); + if (owner is not null && registered is not null) + { + owner.UnregisterExtension(registered); + } + } + } + private readonly record struct PendingEventCoalesceKey( - uint windowId, + uint windowID, Type eventType ); } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs index db8939dd0..dbc1c03e4 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs @@ -29,7 +29,9 @@ public partial Sdl3PlatformWindow CreateWindow(PlatformWindowOptions options) ValidateWindowRegistration(); nint handle = m_hostIntegration.CreateWindow(options); if (handle == 0) + { throw new InvalidOperationException("The SDL host integration returned no window."); + } SDLWindow* nativeWindow = (SDLWindow*)handle; try { @@ -64,7 +66,9 @@ public Sdl3PlatformWindow AdoptWindow(nint windowHandle) { ValidateWindowRegistration(); if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } SDLWindow* window = (SDLWindow*)windowHandle; return RegisterWindow(window, Sdl3NativeText.ReadWindowTitle(window) ?? string.Empty, ownsNativeWindow: false); } @@ -86,9 +90,11 @@ public void ReleaseWindow(Sdl3PlatformWindow window) ValidateOwnerThread(); ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(window); - if (window.ownsNativeWindow || !m_windows.TryGetValue(window.windowId, out Sdl3PlatformWindow? registered) - || !ReferenceEquals(registered, window)) + if (window.ownsNativeWindow || !m_windows.TryGetValue(window.windowID, out Sdl3PlatformWindow? registered) + || !ReferenceEquals(registered, window) + ) { throw new ArgumentException("Only this application's adopted window can be released.", nameof(window)); + } window.Dispose(); } @@ -99,25 +105,38 @@ bool ownsNativeWindow ) { uint id = SDL.Raw.GetWindowId(nativeWindow); if (id == 0 || m_windows.ContainsKey(id)) + { throw new ArgumentException("The SDL window is invalid or already registered.", nameof(nativeWindow)); - var window = new Sdl3PlatformWindow(nativeWindow, title, ownsNativeWindow, m_hostIntegration, RemoveWindow, m_ownerThreadId); + } + var window = new Sdl3PlatformWindow( + nativeWindow, + title, + ownsNativeWindow, + m_hostIntegration, + RemoveWindow, + m_ownerThreadID + ); m_windows.Add(id, window); return window; } - private void RemoveWindow(Sdl3PlatformWindow window) => m_windows.Remove(window.windowId); + private void RemoveWindow(Sdl3PlatformWindow window) => m_windows.Remove(window.windowID); private void ValidateWindowRegistration() { ValidateOwnerThread(); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_hostIntegration.capabilities.multipleWindows && m_windows.Count != 0) + { throw new NotSupportedException("The selected SDL host supports only one window."); + } } private void ValidateOwnerThread() { - if (Environment.CurrentManagedThreadId != m_ownerThreadId) + if (Environment.CurrentManagedThreadId != m_ownerThreadID) + { throw new InvalidOperationException("SDL application operations must run on their owner thread."); + } } } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs index 2b7ffd79f..8a92e3025 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs @@ -19,15 +19,13 @@ public sealed class Sdl3PlatformBackendProvider : PlatformBackendProvider /// /// Host integration is absent. /// - public Sdl3PlatformBackendProvider(ISdl3HostIntegration hostIntegration) : base(PlatformBackendId.sdl3) + public Sdl3PlatformBackendProvider(ISdl3HostIntegration hostIntegration) + : base(PlatformBackendID.sdl3) { ArgumentNullException.ThrowIfNull(hostIntegration); m_hostIntegration = hostIntegration; } - /// - public override IPlatformApplication CreateApplication() - { - return new Sdl3PlatformApplication(m_hostIntegration); - } + /// + public override IPlatformApplication CreateApplication() => new Sdl3PlatformApplication(m_hostIntegration); } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs index 4ffe0d3dc..7abe93858 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs @@ -1,5 +1,5 @@ -using Inno.Adapter.Platform; using System; +using Inno.Adapter.Platform; using Inno.Native.Sdl3; using Inno.Platform; @@ -11,11 +11,13 @@ namespace Inno.Adapter.Platform.Sdl3; public sealed unsafe partial class Sdl3PlatformWindow { private readonly Action m_onDisposed; - private readonly int m_ownerThreadId; - private SDLWindow* m_window; - private readonly uint m_windowId; + private readonly int m_ownerThreadID; + private readonly uint m_windowID; private readonly string m_title; private readonly bool m_ownsNativeWindow; + private readonly PlatformNativeHandles m_nativeHandles; + private readonly nint m_sdlWindowHandle; + private SDLWindow* m_window; private int m_width; private int m_height; private int m_pixelWidth; @@ -24,12 +26,7 @@ public sealed unsafe partial class Sdl3PlatformWindow private bool m_isFocused; private bool m_hidden; private bool m_minimized; - private readonly PlatformNativeHandles m_nativeHandles; - private readonly nint m_sdlWindowHandle; private bool m_disposed; - internal SDLWindow* sdlWindow => m_window; - internal bool ownsNativeWindow => m_ownsNativeWindow; - internal bool isVisible => !m_hidden && !m_minimized; internal Sdl3PlatformWindow( SDLWindow* window, @@ -37,30 +34,67 @@ internal Sdl3PlatformWindow( bool ownsNativeWindow, ISdl3HostIntegration hostIntegration, Action onDisposed, - int ownerThreadId + int ownerThreadID ) { m_onDisposed = onDisposed; - m_ownerThreadId = ownerThreadId; + m_ownerThreadID = ownerThreadID; m_window = window; m_sdlWindowHandle = (nint)window; m_title = title; m_ownsNativeWindow = ownsNativeWindow; - m_windowId = SDL.Raw.GetWindowId(m_window); + m_windowID = SDL.Raw.GetWindowId(m_window); - var currentWidth = 0; - var currentHeight = 0; + int currentWidth = 0; + int currentHeight = 0; if (SDL.Raw.GetWindowSize(m_window, ¤tWidth, ¤tHeight) == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed."); + } m_width = currentWidth; m_height = currentHeight; RefreshPixelSize(); - var flags = (SDLWindowFlags)SDL.Raw.GetWindowFlags(m_window); + SDLWindowFlags flags = (SDLWindowFlags)SDL.Raw.GetWindowFlags(m_window); m_isFocused = hostIntegration.GetInitialFocus(m_sdlWindowHandle); m_hidden = (flags & SDLWindowFlags.Hidden) != 0; m_minimized = (flags & SDLWindowFlags.Minimized) != 0; m_nativeHandles = hostIntegration.ResolveNativeSurface(m_sdlWindowHandle); } + /// + /// Queues a close request for processing at the next platform safety point. + /// + public partial void RequestClose() => m_isClosed = true; + + /// + /// Releases the resources owned by this instance. + /// + public partial void Dispose() + { + if (Environment.CurrentManagedThreadId != m_ownerThreadID) + { + throw new InvalidOperationException("SDL window disposal must run on its owner thread."); + } + if (m_disposed) + { + return; + } + + if (m_window is not null && m_ownsNativeWindow) + { + SDL.Raw.DestroyWindow(m_window); + } + + m_window = null; + m_isClosed = true; + m_isFocused = false; + m_disposed = true; + m_onDisposed(this); + } + + internal SDLWindow* sdlWindow => m_window; + internal bool ownsNativeWindow => m_ownsNativeWindow; + internal bool isVisible => !m_hidden && !m_minimized; + internal void UpdateLogicalSize( int width, int height @@ -80,15 +114,9 @@ int height m_pixelHeight = height; } - internal void MarkClosed() - { - m_isClosed = true; - } + internal void MarkClosed() => m_isClosed = true; - internal void UpdateFocus(bool isFocused) - { - m_isFocused = isFocused; - } + internal void UpdateFocus(bool isFocused) => m_isFocused = isFocused; internal void UpdateVisibility(SDLEventType eventType) { @@ -111,43 +139,12 @@ internal void UpdateVisibility(SDLEventType eventType) private void RefreshPixelSize() { - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; if (SDL.Raw.GetWindowSizeInPixels(m_window, &pixelWidth, &pixelHeight) == 0) - throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSizeInPixels failed."); - UpdatePixelSize(pixelWidth, pixelHeight); - } - - /// - /// Queues a close request for processing at the next platform safety point. - /// - public partial void RequestClose() - { - m_isClosed = true; - } - - /// - /// Releases the resources owned by this instance. - /// - public partial void Dispose() - { - if (Environment.CurrentManagedThreadId != m_ownerThreadId) - throw new InvalidOperationException("SDL window disposal must run on its owner thread."); - if (m_disposed) - { - return; - } - - if (m_window != null && m_ownsNativeWindow) { - SDL.Raw.DestroyWindow(m_window); + throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSizeInPixels failed."); } - - m_window = null; - m_isClosed = true; - m_isFocused = false; - m_disposed = true; - m_onDisposed(this); + UpdatePixelSize(pixelWidth, pixelHeight); } - } diff --git a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs index fabc99d75..9bbf1b52b 100644 --- a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs +++ b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs @@ -21,10 +21,18 @@ public static class TextToolchain "backends/Text/build/Inno.Build.Toolchains.Text/Inno.Build.Toolchains.Text.csproj", new NativeStaticBuildDefinition( "backends/Text/build/Inno.Build.Toolchains.Text/Native/StaticLibraries.cmake", - ["extern/freetype", "extern/harfbuzz", "backends/Text/native/Inno.Native.Text/Native/include", "backends/Text/native/Inno.Native.Text/Native/src", "backends/Text/native/Inno.Native.Text/Native/CMakeLists.txt"], + [ + "extern/freetype", + "extern/harfbuzz", + "backends/Text/native/Inno.Native.Text/Native/include", + "backends/Text/native/Inno.Native.Text/Native/src", + "backends/Text/native/Inno.Native.Text/Native/CMakeLists.txt" + ], ["libinno-text", "libfreetype", "libharfbuzz"], - nativeSourceDirectory: "backends/Text/native/Inno.Native.Text"), - bindingDefinition: "backends/Text/native/Inno.Native.Text/Bindings/bindings.props"); + nativeSourceDirectory: "backends/Text/native/Inno.Native.Text" + ), + bindingDefinition: "backends/Text/native/Inno.Native.Text/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -52,26 +60,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "inno-text", [], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "inno-text", + [], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*inno-text" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -100,9 +123,19 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "text", selection.targetId, + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "text", + selection.targetID, componentDescriptor.staticBuild!.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), - [], [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "TextToolchain.cs")]); + [], + [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "TextToolchain.cs")] + ); } } diff --git a/backends/Text/native/Inno.Native.Text/TextNative.cs b/backends/Text/native/Inno.Native.Text/TextNative.cs index c0191ea6c..bf146532e 100644 --- a/backends/Text/native/Inno.Native.Text/TextNative.cs +++ b/backends/Text/native/Inno.Native.Text/TextNative.cs @@ -8,9 +8,9 @@ namespace Inno.Native.Text; public static unsafe partial class TextNative { #if DEBUG - internal const string LibName = "inno-text-debug"; + internal const string C_LIB_NAME = "inno-text-debug"; #else - internal const string LibName = "inno-text-release"; + internal const string C_LIB_NAME = "inno-text-release"; #endif static TextNative() @@ -20,7 +20,7 @@ static TextNative() #elif INNO_STATIC_NATIVE FromStatic(); #else - Load(NativeDllLoader.FindNativeLibrary(LibName)); + Load(NativeDllLoader.FindNativeLibrary(C_LIB_NAME)); #endif } -} \ No newline at end of file +} diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs index 98f9c27cd..9856ec902 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs @@ -1,6 +1,5 @@ using System; using System.Text; - using Inno.Native.Text; using Inno.Text; @@ -20,8 +19,10 @@ public sealed unsafe class FreeTypeHarfBuzzTextBackend : ITextBackend public FreeTypeHarfBuzzTextBackend() { InnoTextFontAdapterRuntime* context = TextNativeOperations.CreateSession(); - if (context == null) + if (context is null) + { throw new InvalidOperationException("The native text backend returned a null context."); + } m_context = context; } @@ -43,7 +44,9 @@ int faceIndex ) { EnsureActive(); if (data.IsEmpty) + { throw new ArgumentException("Font data cannot be empty.", nameof(data)); + } ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); ulong handle = 0; ThrowIfFailed(TextNativeOperations.LoadFont(m_context, data, faceIndex, ref handle), "load font"); @@ -60,7 +63,9 @@ public void ReleaseFont(TextFontHandle font) { EnsureActive(); if (!font.isValid) + { return; + } ThrowIfFailed(TextNativeOperations.ReleaseFont(m_context, font.value), "release font"); } @@ -90,7 +95,9 @@ TextShapingOptions options ) { EnsureActive(); if (!font.isValid) + { throw new ArgumentException("A valid font handle is required.", nameof(font)); + } ArgumentNullException.ThrowIfNull(text); byte[] textBytes = Utf8(text); byte[] languageBytes = Utf8(options.language ?? string.Empty); @@ -100,39 +107,47 @@ TextShapingOptions options fixed (byte* languagePointer = languageBytes) fixed (byte* scriptPointer = scriptBytes) { - ThrowIfFailed(TextNativeOperations.ShapeUtf8( - m_context, - font.value, - textPointer, - checked((uint)(textBytes.Length - 1)), - style.fontSize, - (Direction)options.direction, - languagePointer, - scriptPointer, - (InnoTextFontAdapterGlyph*)null, - 0, - &glyphCount), "query shaped glyph count"); - InnoTextFontAdapterGlyph[] nativeGlyphs = new InnoTextFontAdapterGlyph[checked((int)glyphCount)]; + ThrowIfFailed( + TextNativeOperations.ShapeUtf8( + m_context, + font.value, + textPointer, + checked((uint)(textBytes.Length - 1)), + style.fontSize, + (Direction)options.direction, + languagePointer, + scriptPointer, + (InnoTextFontAdapterGlyph*)null, + 0, + &glyphCount + ), + "query shaped glyph count" + ); + var nativeGlyphs = new InnoTextFontAdapterGlyph[checked((int)glyphCount)]; if (nativeGlyphs.Length > 0) { fixed (InnoTextFontAdapterGlyph* glyphPointer = nativeGlyphs) { - ThrowIfFailed(TextNativeOperations.ShapeUtf8( - m_context, - font.value, - textPointer, - checked((uint)(textBytes.Length - 1)), - style.fontSize, - (Direction)options.direction, - languagePointer, - scriptPointer, - glyphPointer, - checked((uint)nativeGlyphs.Length), - &glyphCount), "shape text"); + ThrowIfFailed( + TextNativeOperations.ShapeUtf8( + m_context, + font.value, + textPointer, + checked((uint)(textBytes.Length - 1)), + style.fontSize, + (Direction)options.direction, + languagePointer, + scriptPointer, + glyphPointer, + checked((uint)nativeGlyphs.Length), + &glyphCount + ), + "shape text" + ); } } - TextGlyph[] glyphs = new TextGlyph[nativeGlyphs.Length]; + var glyphs = new TextGlyph[nativeGlyphs.Length]; float width = 0f; for (int index = 0; index < nativeGlyphs.Length; index++) { @@ -140,9 +155,13 @@ TextShapingOptions options float advanceX = glyph.AdvanceX; float advanceY = glyph.AdvanceY; if (options.direction is TextDirection.TopToBottom or TextDirection.BottomToTop) + { advanceY += MathF.CopySign(style.letterSpacing, advanceY == 0f ? 1f : advanceY); + } else + { advanceX += MathF.CopySign(style.letterSpacing, advanceX == 0f ? 1f : advanceX); + } width += MathF.Abs(advanceX); glyphs[index] = new TextGlyph( glyph.GlyphId, @@ -150,7 +169,8 @@ TextShapingOptions options advanceX, advanceY, glyph.OffsetX, - glyph.OffsetY); + glyph.OffsetY + ); } InnoTextFontAdapterMetrics metrics = default; ThrowIfFailed(TextNativeOperations.GetMetrics(m_context, font.value, style.fontSize, ref metrics), "query font metrics"); @@ -159,7 +179,8 @@ TextShapingOptions options metrics.Descender, metrics.LineHeight, metrics.UnderlinePosition, - metrics.UnderlineThickness); + metrics.UnderlineThickness + ); return new TextLayout(glyphs, publicMetrics, width, MathF.Max(0f, metrics.LineHeight)); } } @@ -170,7 +191,7 @@ TextShapingOptions options /// /// The loaded face. /// - /// + /// /// The font-specific glyph identifier. /// /// @@ -181,32 +202,43 @@ TextShapingOptions options /// public GlyphBitmap Rasterize( TextFontHandle font, - uint glyphId, + uint glyphID, float fontSize ) { EnsureActive(); if (!font.isValid) + { throw new ArgumentException("A valid font handle is required.", nameof(font)); + } if (!float.IsFinite(fontSize) || fontSize <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSize)); + } InnoTextFontAdapterBitmap bitmap = default; - ThrowIfFailed(TextNativeOperations.RasterizeGlyph( - m_context, font.value, glyphId, fontSize, null, 0, &bitmap), "query glyph bitmap"); - byte[] pixels = new byte[checked((int)bitmap.ByteLength)]; + ThrowIfFailed( + TextNativeOperations.RasterizeGlyph(m_context, font.value, glyphID, fontSize, null, 0, &bitmap), + "query glyph bitmap" + ); + var pixels = new byte[checked((int)bitmap.ByteLength)]; if (pixels.Length > 0) { fixed (byte* pixelPointer = pixels) - ThrowIfFailed(TextNativeOperations.RasterizeGlyph( - m_context, font.value, glyphId, fontSize, pixelPointer, checked((uint)pixels.Length), &bitmap), - "rasterize glyph"); + { + ThrowIfFailed( + TextNativeOperations.RasterizeGlyph( + m_context, + font.value, + glyphID, + fontSize, + pixelPointer, + checked((uint)pixels.Length), + &bitmap + ), + "rasterize glyph" + ); + } } - return new GlyphBitmap( - bitmap.Width, - bitmap.Height, - bitmap.BearingX, - bitmap.BearingY, - bitmap.AdvanceX, - pixels); + return new GlyphBitmap(bitmap.Width, bitmap.Height, bitmap.BearingX, bitmap.BearingY, bitmap.AdvanceX, pixels); } /// @@ -215,15 +247,19 @@ float fontSize public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; TextNativeOperations.DestroySession(m_context); m_context = null; } + private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); + private static byte[] Utf8(string value) { - byte[] bytes = new byte[Encoding.UTF8.GetByteCount(value) + 1]; + var bytes = new byte[Encoding.UTF8.GetByteCount(value) + 1]; Encoding.UTF8.GetBytes(value, bytes); return bytes; } @@ -233,8 +269,10 @@ private static void ThrowIfFailed( string operation ) { if (result != Result.Success) - throw new InvalidOperationException($"Failed to {operation}: {TextNativeOperations.ResultMessage(result) ?? result.ToString()}."); + { + throw new InvalidOperationException( + $"Failed to {operation}: {TextNativeOperations.ResultMessage(result) ?? result.ToString()}." + ); + } } - - private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); } diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs index 78c5c20e6..85f16dc4e 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs @@ -11,12 +11,9 @@ public sealed class FreeTypeHarfBuzzTextBackendProvider : TextBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public FreeTypeHarfBuzzTextBackendProvider() : base(TextBackendId.freeTypeHarfBuzz) { } + public FreeTypeHarfBuzzTextBackendProvider() + : base(TextBackendID.freeTypeHarfBuzz) {} - /// - public override ITextBackend CreateBackend() - { - return new FreeTypeHarfBuzzTextBackend(); - } + /// + public override ITextBackend CreateBackend() => new FreeTypeHarfBuzzTextBackend(); } - diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs index 300a2175f..5ac6b3e9a 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs @@ -30,7 +30,12 @@ ref ulong handle BgcsInnoTextError* error = null; fixed (byte* bytes = data) fixed (ulong* destination = &handle) - CheckBridge(TextNative.Raw.LoadFont(runtime, bytes, checked((uint)data.Length), faceIndex, destination, &result, &error), error); + { + CheckBridge( + TextNative.Raw.LoadFont(runtime, bytes, checked((uint)data.Length), faceIndex, destination, &result, &error), + error + ); + } return result; } @@ -60,8 +65,24 @@ internal static Result ShapeUtf8( Result result = default; BgcsInnoTextError* error = null; // BGCS verifies every DTO field, offset, size and alignment in the native bridge. - CheckBridge(TextNative.Raw.ShapeUtf8(runtime, handle, (sbyte*)text, textLength, fontSize, direction, - (sbyte*)language, (sbyte*)script, (InnoTextFontAdapterGlyphNative*)glyphs, capacity, count, &result, &error), error); + CheckBridge( + TextNative.Raw.ShapeUtf8( + runtime, + handle, + (sbyte*)text, + textLength, + fontSize, + direction, + (sbyte*)language, + (sbyte*)script, + (InnoTextFontAdapterGlyphNative*)glyphs, + capacity, + count, + &result, + &error + ), + error + ); return result; } @@ -74,15 +95,26 @@ ref InnoTextFontAdapterMetrics metrics Result result = default; BgcsInnoTextError* error = null; fixed (InnoTextFontAdapterMetrics* destination = &metrics) - CheckBridge(TextNative.Raw.GetMetrics(runtime, handle, fontSize, - (InnoTextFontAdapterMetricsNative*)destination, &result, &error), error); + { + CheckBridge( + TextNative.Raw.GetMetrics( + runtime, + handle, + fontSize, + (InnoTextFontAdapterMetricsNative*)destination, + &result, + &error + ), + error + ); + } return result; } internal static Result RasterizeGlyph( InnoTextFontAdapterRuntime* runtime, ulong handle, - uint glyphId, + uint glyphID, float fontSize, byte* pixels, uint capacity, @@ -90,8 +122,20 @@ internal static Result RasterizeGlyph( ) { Result result = default; BgcsInnoTextError* error = null; - CheckBridge(TextNative.Raw.RasterizeGlyph(runtime, handle, glyphId, fontSize, pixels, capacity, - (InnoTextFontAdapterBitmapNative*)bitmap, &result, &error), error); + CheckBridge( + TextNative.Raw.RasterizeGlyph( + runtime, + handle, + glyphID, + fontSize, + pixels, + capacity, + (InnoTextFontAdapterBitmapNative*)bitmap, + &result, + &error + ), + error + ); return result; } @@ -107,17 +151,23 @@ private static void CheckBridge( int status, BgcsInnoTextError* error ) { - if (status == 0 && error == null) + if (status == 0 && error is null) + { return; + } try { - string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)TextNative.Raw.BgcsInnoTextErrorMessage(error)); - throw new InvalidOperationException($"The text bridge failed with status {status}: {message ?? "No native error text is available."}"); + string? message = error is null ? null : Marshal.PtrToStringUTF8((nint)TextNative.Raw.BgcsInnoTextErrorMessage(error)); + throw new InvalidOperationException( + $"The text bridge failed with status {status}: {message ?? "No native error text is available."}" + ); } finally { - if (error != null) + if (error is not null) + { TextNative.Raw.BgcsInnoTextErrorRelease(error); + } } } } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs index d54ee33bb..03e5b2a1d 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs @@ -18,41 +18,61 @@ NativeBindingProfile profile string definition = Path.GetFullPath(component.bindingDefinition!, context.engineRoot); string directory = Path.GetDirectoryName(definition)!; XElement project = XDocument.Load(definition).Root - ?? throw new InvalidDataException("A binding definition is empty."); + ?? throw new InvalidDataException("A binding definition is empty."); if (project.Name != "Project" || project.Attributes().Any()) + { throw new InvalidDataException("Binding definitions must be declarative Project data."); - Dictionary properties = new(StringComparer.Ordinal); + } + var properties = new Dictionary(StringComparer.Ordinal); foreach (XElement group in project.Elements()) { if (group.Attributes().Any()) + { throw new InvalidDataException("Binding definitions cannot evaluate conditions."); + } if (group.Name == "PropertyGroup") { foreach (XElement property in group.Elements()) { if (property.Name.LocalName is not ("InnoNativeComponentId" or "InnoBindingConfig") - || property.Attributes().Any() || property.HasElements || !properties.TryAdd(property.Name.LocalName, property.Value)) + || property.Attributes().Any() + || property.HasElements + || !properties.TryAdd(property.Name.LocalName, property.Value) + ) { throw new InvalidDataException("A binding definition has an unknown or repeated property."); + } } } else + { throw new InvalidDataException("A binding definition cannot contain executable build logic."); + } } - if (!properties.TryGetValue("InnoNativeComponentId", out string? componentId) || componentId != component.id) + if (!properties.TryGetValue("InnoNativeComponentId", out string? componentID) || componentID != component.id) + { throw new InvalidDataException("The binding definition must declare the requested component identity."); + } if (!properties.TryGetValue("InnoBindingConfig", out string? hostConfig)) + { throw new InvalidDataException("A binding definition requires its common binding configuration."); - if (request.targetId != profile.targetId) - throw new NotSupportedException($"The selected binding profile does not serve '{request.targetId}'."); + } + if (request.targetID != profile.targetID) + { + throw new NotSupportedException($"The selected binding profile does not serve '{request.targetID}'."); + } return new(component, definition, Resolve(hostConfig), request, profile); string Resolve(string path) { if (string.IsNullOrWhiteSpace(path) || Path.IsPathFullyQualified(path) || path.Contains('$') || path.Contains('@') - || path.Contains(':') || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + || path.Contains(':') || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..") + ) { throw new InvalidDataException("Binding definition paths must be literal relative children."); + } string absolute = Path.GetFullPath(path, directory); if (!File.Exists(absolute)) + { throw new FileNotFoundException("A declared binding input is missing.", absolute); + } return absolute; } } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs b/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs index 2c12dbc8f..d3850b6b0 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs @@ -33,33 +33,62 @@ NativeBindingProfile profile internal GenerationRequest Load( NativeBuildContext context, - CancellationToken cancellation + CancellationToken cancellationToken ) { - if (context.toolchain is NativeToolchainSelection selected && selected.targetId != request.targetId) + if (context.toolchain is NativeToolchainSelection selected && selected.targetID != request.targetID) + { throw new InvalidOperationException("The selected SDK does not match the binding target."); + } using HostServices host = BindingHostFactory.CreateHostServices(context.engineRoot); - GenerationRequest captured = GenerationRequest.FromFile(configPath).MaterializeAsync(host.paths, cancellation) - .AsTask().GetAwaiter().GetResult(); + GenerationRequest captured = GenerationRequest.FromFile(configPath) + .MaterializeAsync(host.paths, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); if (captured.configuration.targets.Length != 1) + { throw new InvalidDataException("A component binding request must select exactly one native target."); + } if (captured.configuration.output.layout != "singleFile" || captured.configuration.output.singleFileName != "Bindings.cs" - || captured.configuration.runtime.mode != "package") + || captured.configuration.runtime.mode != "package" + ) { throw new InvalidDataException("Native components require one Bindings.cs source and the package Runtime."); - captured = captured.WithConfiguration(captured.configuration with - { - cache = captured.configuration.cache with + } + captured = captured.WithConfiguration( + captured.configuration with { - directory = Path.Combine(context.engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces", component.id, request.targetId) + cache = captured.configuration.cache with + { + directory = Path.Combine( + context.engineRoot, + "artifacts", + "build-tools", + "bindings", + "sdk-workspaces", + component.id, + request.targetID + ) + } } - }); - return profile.Apply(captured, context.toolchain?.compilerInputs, - request.componentOptions.GetValueOrDefault(component.nativeProject), context.engineRoot) - .MaterializeAsync(host.paths, cancellation).AsTask().GetAwaiter().GetResult(); + ); + return profile + .Apply( + captured, + context.toolchain?.compilerInputs, + request.componentOptions.GetValueOrDefault(component.nativeProject), + context.engineRoot + ) + .MaterializeAsync(host.paths, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); } - internal string GetOutputRoot(NativeBuildContext context) => request.outputMode == NativeBindingOutputMode.TargetArtifacts - ? Path.Combine(context.engineRoot, "artifacts", "bindings", component.id, request.targetId) - : Path.Combine(component.GetNativeRoot(context.engineRoot), "Generated"); + internal string GetOutputRoot(NativeBuildContext context) + => request.outputMode == NativeBindingOutputMode.TargetArtifacts + ? Path.Combine(context.engineRoot, "artifacts", "bindings", component.id, request.targetID) + : Path.Combine(component.GetNativeRoot(context.engineRoot), "Generated"); - internal string GetHostNativeRoot(NativeBuildContext context) => Path.Combine(component.GetNativeRoot(context.engineRoot), "Native", "Generated"); + internal string GetHostNativeRoot(NativeBuildContext context) + => Path.Combine(component.GetNativeRoot(context.engineRoot), "Native", "Generated"); } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs index 31ad617ae..a2a9fb5a4 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs @@ -3,9 +3,11 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using System.Reflection; using BGCS; using BGCS.Configuration; using BGCS.Core; +using BGCS.Core.Inputs; using BGCS.Core.Targets; using Inno.Build.Toolchains; @@ -21,7 +23,7 @@ public sealed class NativeBindingProfile /// /// Creates a target profile without discovering an SDK or executing a generator. /// - /// + /// /// The engine target identity that may consume this profile. /// /// @@ -44,23 +46,29 @@ public sealed class NativeBindingProfile /// An identity is empty, uses implicit host selection, or a path escapes the checkout. /// public NativeBindingProfile( - string targetId, + string targetID, TargetConfiguration target, ManagedRuntimeId? runtime = null, IEnumerable? inputPaths = null, Action? configureGenerator = null, BindingImportMode? importMode = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - if (targetId == "host") - throw new ArgumentException("A binding profile requires an explicit engine target.", nameof(targetId)); + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + if (targetID == "host") + { + throw new ArgumentException("A binding profile requires an explicit engine target.", nameof(targetID)); + } ArgumentNullException.ThrowIfNull(target); if (target.id == "host" || string.IsNullOrWhiteSpace(target.id)) + { throw new ArgumentException("Binding profiles require an explicit native ABI.", nameof(target)); - this.targetId = targetId; + } + this.targetID = targetID; this.target = target; if (importMode is { } selectedImport && !Enum.IsDefined(selectedImport)) + { throw new ArgumentOutOfRangeException(nameof(importMode)); + } this.runtime = runtime; this.importMode = importMode; this.inputPaths = Array.AsReadOnly((inputPaths ?? []).Select(ValidatePath).ToArray()); @@ -70,19 +78,23 @@ public NativeBindingProfile( /// /// Gets the engine target authorized to consume this profile. /// - public string targetId { get; } + public string targetID { get; } + /// /// Gets the immutable official BGCS target configuration. /// public TargetConfiguration target { get; } + /// /// Gets the managed projection runtime, or null for the component's portable default. /// public ManagedRuntimeId? runtime { get; } + /// /// Gets the explicit platform import mechanism, or null for the component's mechanism. /// public BindingImportMode? importMode { get; } + /// /// Gets the profile's exact checkout implementation inputs. /// @@ -90,8 +102,8 @@ public NativeBindingProfile( internal void Configure(BindingHostBuilder builder) => m_configureGenerator?.Invoke(builder); - internal IEnumerable GetExtensionAssemblies() => - m_configureGenerator?.GetInvocationList().Select(static action => action.Method.Module.Assembly) ?? []; + internal IEnumerable GetExtensionAssemblies() + => m_configureGenerator?.GetInvocationList().Select(static action => action.Method.Module.Assembly) ?? []; internal GenerationRequest Apply( GenerationRequest request, @@ -101,12 +113,14 @@ string engineRoot ) { TargetConfiguration selected = target; if (compiler is not null) + { selected = selected with { settings = selected.settings with { - compilerPath = request.configuration.source.language == BGCS.Core.Inputs.SourceLanguage.Cpp - ? compiler.cppCompiler : compiler.cCompiler, + compilerPath = request.configuration.source.language == SourceLanguage.Cpp + ? compiler.cppCompiler + : compiler.cCompiler, sysRoot = compiler.sysRoot, systemIncludeDirectories = compiler.systemIncludeDirectories.ToImmutableArray(), cxxSystemIncludeDirectories = compiler.cppSystemIncludeDirectories.ToImmutableArray(), @@ -114,29 +128,37 @@ string engineRoot arguments = [.. selected.settings.arguments, .. compiler.arguments] } }; + } BindingConfiguration config = request.configuration; - return request.WithConfiguration(config with - { - targets = [selected], - api = config.api with - { - runtime = runtime ?? config.api.runtime, - importMode = importMode ?? config.api.importMode - }, - library = config.library with { nativeName = options?.bindingLibraryName ?? config.library.nativeName }, - source = config.source with + return request.WithConfiguration( + config with { - includeDirectories = [.. config.source.includeDirectories, - .. (options?.bindingIncludeDirectories ?? []).Select(path => Path.GetFullPath(path, engineRoot))] + targets = [selected], + api = config.api with + { + runtime = runtime ?? config.api.runtime, + importMode = importMode ?? config.api.importMode + }, + library = config.library with { nativeName = options?.bindingLibraryName ?? config.library.nativeName }, + source = config.source with + { + includeDirectories = + [ + .. config.source.includeDirectories, + .. (options?.bindingIncludeDirectories ?? []).Select(path => Path.GetFullPath(path, engineRoot)) + ] + } } - }); + ); } private static string ValidatePath(string path) { if (string.IsNullOrWhiteSpace(path) || Path.IsPathFullyQualified(path) || path.Contains(':') - || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..") + ) { throw new ArgumentException("Binding profile inputs must remain within the checkout.", nameof(path)); + } return path.Replace('\\', '/'); } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs index 0300f7f32..7ad569279 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs @@ -5,7 +5,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - +using BGCS; +using BGCS.Core; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -30,51 +31,129 @@ NativeBindingProfile profile m_request = request; } - internal async ValueTask ExecuteAsync(CancellationToken cancellation) + /// + /// Releases candidate outputs and generation leases after the complete batch has drained. + /// + public void Dispose() + { + List failures = []; + for (int index = m_reading.Count - 1; index >= 0; index--) + { + try + { + m_reading[index].Dispose(); + } + catch (Exception failure) + { + failures.Add(failure); + } + } + for (int index = m_publications.Count - 1; index >= 0; index--) + { + try + { + m_publications[index].Dispose(); + } + catch (Exception failure) + { + failures.Add(failure); + } + } + for (int index = m_leases.Count - 1; index >= 0; index--) + { + try + { + m_leases[index].Dispose(); + } + catch (Exception failure) + { + failures.Add(failure); + } + } + if (failures.Count > 0) + { + throw new AggregateException("Binding batch cleanup failed after draining generation.", failures); + } + } + + internal async ValueTask ExecuteAsync(CancellationToken cancellationToken) { BindingGenerationConfiguration[] definitions = m_request.components.Select(component => BindingDefinitionReader.Read(m_context, component, m_request, m_profile)).ToArray(); - string[] fingerprints = definitions.Select(definition => Compute(definition, m_context, cancellation)).ToArray(); + string[] fingerprints = definitions.Select(definition => Compute(definition, m_context, cancellationToken)).ToArray(); for (int index = 0; index < definitions.Length; index++) + { if (m_request.expectedFingerprints.TryGetValue(definitions[index].component.nativeProject, out string? expected) - && expected != fingerprints[index]) + && expected != fingerprints[index] + ) { throw new InvalidOperationException("Binding inputs changed after their generation was selected."); - BuildCacheOwnerCatalog.Register(m_context.engineRoot, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), - "bindings", BuildCacheArtifactRole.ImmutableArtifact, cancellation); + } + } + BuildCacheOwnerCatalog.Register( + m_context.engineRoot, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + "bindings", + BuildCacheArtifactRole.ImmutableArtifact, + cancellationToken + ); // Batch leases are acquired in canonical path order. No partial closure is returned on failure. StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; foreach (string path in definitions.Select(definition => Path.Combine( - definition.component.GetNativeRoot(m_context.engineRoot), "obj", "bindings", "generation.lock")).Order(paths)) - m_leases.Add(await FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)); + definition.component.GetNativeRoot(m_context.engineRoot), + "obj", + "bindings", + "generation.lock" + )).Order(paths) + ) { + m_leases.Add(await FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false)); + } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { - var cache = new BuildCachePublisher(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); - m_leases.Add(await cache.AcquireUseAsync(cancellation).ConfigureAwait(false)); + var cache = new BuildCachePublisher( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); + m_leases.Add(await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false)); } m_context.RecordBindingBatch(); - Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-locks"), cancellation); - Dictionary results = new(StringComparer.Ordinal); - HashSet protectedTargets = new(StringComparer.Ordinal); + Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-locks"), cancellationToken); + var results = new Dictionary(StringComparer.Ordinal); + var protectedTargets = new HashSet(StringComparer.Ordinal); for (int index = 0; index < definitions.Length; index++) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); BindingGenerationConfiguration definition = definitions[index]; string fingerprint = fingerprints[index]; string output = definition.GetOutputRoot(m_context); - var loaded = definition.Load(m_context, cancellation); - bool usesRuntimeImports = loaded.configuration.api.importMode != BGCS.Core.BindingImportMode.FunctionTable; + GenerationRequest loaded = definition.Load(m_context, cancellationToken); + bool usesRuntimeImports = loaded.configuration.api.importMode != BindingImportMode.FunctionTable; if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { string destination = Path.Combine(output, fingerprint); try { - m_reading.Add(await BuildArtifactReadLease.AcquireAsync(destination, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), fingerprint, - ["Native", "Generated"], cancellation, m_context).ConfigureAwait(false)); + m_reading.Add( + await BuildArtifactReadLease.AcquireAsync( + destination, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + fingerprint, + ["Native", "Generated"], + m_context, + cancellationToken + ).ConfigureAwait(false) + ); protectedTargets.Add(destination); if (!m_request.checkOnly) { - results.Add(definition.component.nativeProject, TargetBindingGeneration.Describe( - Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, fingerprint, usesRuntimeImports)); + results.Add( + definition.component.nativeProject, + TargetBindingGeneration.Describe( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + fingerprint, + usesRuntimeImports + ) + ); continue; } } @@ -82,20 +161,37 @@ internal async ValueTask ExecuteAsync(Cancellatio { // Invalid output is repaired only after exclusive artifact ownership is acquired at commit. } - var publication = BindingGenerationPublication.CreateTarget(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, cancellation); + BindingGenerationPublication publication = BindingGenerationPublication.CreateTarget( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + cancellationToken + ); m_publications.Add(publication); - TargetBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellation); - results.Add(definition.component.nativeProject, TargetBindingGeneration.Describe( - Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, fingerprint, usesRuntimeImports)); + TargetBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellationToken); + results.Add( + definition.component.nativeProject, + TargetBindingGeneration.Describe( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + fingerprint, + usesRuntimeImports + ) + ); } else { - var publication = BindingGenerationPublication.CreateHost(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), output, definition.GetHostNativeRoot(m_context), cancellation); + BindingGenerationPublication publication = BindingGenerationPublication.CreateHost( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + output, + definition.GetHostNativeRoot(m_context), + cancellationToken + ); m_publications.Add(publication); - HostBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellation); + HostBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellationToken); results.Add(definition.component.nativeProject, new NativeBindingGenerationDescriptor { - fingerprint = fingerprint, bindingsPath = Path.Combine(output, "Bindings.cs"), + fingerprint = fingerprint, + bindingsPath = Path.Combine(output, "Bindings.cs"), usesRuntimeImports = usesRuntimeImports, artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty, @@ -103,28 +199,45 @@ internal async ValueTask ExecuteAsync(Cancellatio }); } } - Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-generation"), cancellation); - cancellation.ThrowIfCancellationRequested(); + Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-generation"), cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); foreach (BindingGenerationPublication publication in m_publications) + { if (!m_request.checkOnly) { if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - publication.managedDestination, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), cancellation).ConfigureAwait(false); + publication.managedDestination, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + cancellationToken + ).ConfigureAwait(false); publication.Commit(); } else + { publication.Commit(); + } } + } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { foreach (NativeBindingGenerationDescriptor descriptor in results.Values) { string directory = descriptor.artifactDirectory; if (!protectedTargets.Contains(directory)) - m_reading.Add(await BuildArtifactReadLease.AcquireAsync(directory, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), descriptor.fingerprint, - ["Native", "Generated"], cancellation, m_context).ConfigureAwait(false)); + { + m_reading.Add( + await BuildArtifactReadLease.AcquireAsync( + directory, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + descriptor.fingerprint, + ["Native", "Generated"], + m_context, + cancellationToken + ).ConfigureAwait(false) + ); + } } } else @@ -135,12 +248,21 @@ internal async ValueTask ExecuteAsync(Cancellatio } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts && !m_request.checkOnly) { - var cache = new BuildCachePublisher(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); + var cache = new BuildCachePublisher( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); foreach (BindingGenerationConfiguration definition in definitions) { NativeBindingGenerationDescriptor generation = results[definition.component.nativeProject]; - cache.Record(generation.artifactDirectory, generation.artifactDirectory + ".read.lock", [], - definition.component.id + "/" + m_request.targetId, m_request.targetId, cancellation); + cache.Record( + generation.artifactDirectory, + generation.artifactDirectory + ".read.lock", + [], + definition.component.id + "/" + m_request.targetID, + m_request.targetID, + cancellationToken + ); } } var result = new NativeBindingGenerationResult(results, m_reading); @@ -148,69 +270,35 @@ internal async ValueTask ExecuteAsync(Cancellatio return result; } - /// - /// Releases candidate outputs and generation leases after the complete batch has drained. - /// - public void Dispose() - { - List failures = []; - for (int index = m_reading.Count - 1; index >= 0; index--) - { - try - { - m_reading[index].Dispose(); - } - catch (Exception failure) - { - failures.Add(failure); - } - } - for (int index = m_publications.Count - 1; index >= 0; index--) - { - try - { - m_publications[index].Dispose(); - } - catch (Exception failure) - { - failures.Add(failure); - } - } - for (int index = m_leases.Count - 1; index >= 0; index--) - { - try - { - m_leases[index].Dispose(); - } - catch (Exception failure) - { - failures.Add(failure); - } - } - if (failures.Count > 0) - throw new AggregateException("Binding batch cleanup failed after draining generation.", failures); - } - private void Verify( IReadOnlyList definitions, IReadOnlyList fingerprints, NativeBuildContext verification, - CancellationToken cancellation + CancellationToken cancellationToken ) { for (int index = 0; index < definitions.Count; index++) { - BindingGenerationConfiguration current = BindingDefinitionReader.Read(verification, definitions[index].component, m_request, m_profile); - if (Compute(current, verification, cancellation) != fingerprints[index]) - throw new InvalidOperationException("Binding inputs changed during an ownership wait or generation; the candidate was not published."); + BindingGenerationConfiguration current = BindingDefinitionReader.Read( + verification, + definitions[index].component, + m_request, + m_profile + ); + if (Compute(current, verification, cancellationToken) != fingerprints[index]) + { + throw new InvalidOperationException( + "Binding inputs changed during an ownership wait or generation; the candidate was not published." + ); + } } } private string Compute( BindingGenerationConfiguration definition, NativeBuildContext context, - CancellationToken cancellation + CancellationToken cancellationToken ) { - var loaded = definition.Load(context, cancellation); - return NativeBindingGenerationIdentity.Compute(loaded, definition, context, cancellation); + GenerationRequest loaded = definition.Load(context, cancellationToken); + return NativeBindingGenerationIdentity.Compute(loaded, definition, context, cancellationToken); } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs index 4ef98b628..63274dd08 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs @@ -1,9 +1,12 @@ using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using BGCS; +using BGCS.Core; using BGCS.Core.Artifacts; using BGCS.Core.Hosting; @@ -17,8 +20,8 @@ internal static void Generate( string engineRoot, string nativeOutput, string managedOutput, - CancellationToken cancellation - ) => GenerateAsync(request, profile, engineRoot, nativeOutput, managedOutput, cancellation).GetAwaiter().GetResult(); + CancellationToken cancellationToken + ) => GenerateAsync(request, profile, engineRoot, nativeOutput, managedOutput, cancellationToken).GetAwaiter().GetResult(); private static async Task GenerateAsync( GenerationRequest request, @@ -26,51 +29,84 @@ private static async Task GenerateAsync( string engineRoot, string nativeOutput, string managedOutput, - CancellationToken cancellation + CancellationToken cancellationToken ) { - await using BindingHost host = BindingHostFactory.CreateBuilder(profile, cancellation).Build(); + await using BindingHost host = BindingHostFactory.CreateBuilder(profile, cancellationToken).Build(); await using HostServices services = BindingHostFactory.CreateHostServices(engineRoot); - GenerationResult result = await host.GenerateAsync(request, cancellation).ConfigureAwait(false); - foreach (var diagnostic in result.diagnostics) + GenerationResult result = await host.GenerateAsync(request, cancellationToken).ConfigureAwait(false); + foreach (BindingDiagnostic diagnostic in result.diagnostics) { Console.WriteLine($"BGCS {diagnostic.severity} {diagnostic.code}: {diagnostic.message}"); if (diagnostic.details is not null) + { Console.WriteLine(diagnostic.details); + } } if (!result.success) - throw new InvalidDataException("BGCS generation failed: " + string.Join(Environment.NewLine, - result.diagnostics.Where(static diagnostic => diagnostic.severity is BGCS.Core.BindingDiagnosticSeverity.Error - or BGCS.Core.BindingDiagnosticSeverity.Critical) - .Select(static diagnostic => diagnostic.code + ": " + diagnostic.message))); - foreach (var stage in result.cacheStages) + { + throw new InvalidDataException( + "BGCS generation failed: " + string.Join( + Environment.NewLine, + result.diagnostics + .Where(static diagnostic => ( + diagnostic.severity is BindingDiagnosticSeverity.Error + or BindingDiagnosticSeverity.Critical + )) + .Select(static diagnostic => diagnostic.code + ": " + diagnostic.message) + ) + ); + } + foreach (GenerationCacheStageResult stage in result.cacheStages) + { Console.WriteLine($"BGCS cache {stage.targetId}/{stage.stage}: {stage.status}; {stage.reason}"); - var artifacts = BindingArtifactManifest.Read(result.outputRoot, request.configuration.library.id, services.paths, cancellation); - ArtifactDescriptor[] managed = artifacts.Where(static artifact => artifact.relativePath.EndsWith("/managed/Bindings.cs", StringComparison.Ordinal)).ToArray(); + } + ImmutableArray artifacts = BindingArtifactManifest.Read( + result.outputRoot, + request.configuration.library.id, + services.paths, + cancellationToken + ); + ArtifactDescriptor[] managed = artifacts + .Where(static artifact => artifact.relativePath.EndsWith("/managed/Bindings.cs", StringComparison.Ordinal)) + .ToArray(); if (managed.Length != 1) + { throw new InvalidDataException("BGCS must publish exactly one selected target's managed Bindings.cs."); + } NativeSourceManifest[] manifests = BindingArtifactManifest.ReadNativeSources( - result.outputRoot, request.configuration.library.id, services.paths, cancellation).ToArray(); + result.outputRoot, + request.configuration.library.id, + services.paths, + cancellationToken + ).ToArray(); if (manifests.Length != 1) + { throw new InvalidDataException("A component generation requires exactly one native source manifest."); + } NativeSourceManifest manifest = manifests[0]; - var generatedRoots = manifest.inputRoots.Where(static root => root.kind == "generated") - .Select(static root => root.id).ToHashSet(StringComparer.Ordinal); - var nativePaths = manifest.sources.Concat(manifest.headers).Select(static artifact => artifact.relativePath) + HashSet generatedRoots = manifest.inputRoots.Where(static root => root.kind == "generated") + .Select(static root => root.id) + .ToHashSet(StringComparer.Ordinal); + HashSet nativePaths = manifest.sources.Concat(manifest.headers) + .Select(static artifact => artifact.relativePath) .Concat(manifest.inputs.Where(input => generatedRoots.Contains(input.rootId)).Select(static input => input.relativePath)) .ToHashSet(StringComparer.Ordinal); - var selectedArtifacts = artifacts.Where(artifact => nativePaths.Contains(artifact.relativePath)).ToArray(); + ArtifactDescriptor[] selectedArtifacts = artifacts.Where(artifact => nativePaths.Contains(artifact.relativePath)).ToArray(); if (selectedArtifacts.Length != nativePaths.Count) + { throw new InvalidDataException("Every generated native input must belong to the SDK's verified publication."); + } Directory.CreateDirectory(managedOutput); Directory.CreateDirectory(nativeOutput); foreach (ArtifactDescriptor artifact in selectedArtifacts.Append(managed[0])) { - cancellation.ThrowIfCancellationRequested(); - string destination = artifact == managed[0] ? Path.Combine(managedOutput, "Bindings.cs") - : Path.Combine(nativeOutput, artifact.relativePath); + cancellationToken.ThrowIfCancellationRequested(); + string destination = artifact == managed[0] + ? Path.Combine(managedOutput, "Bindings.cs") + : Path.Combine(nativeOutput, artifact.relativePath); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(Path.Combine(result.outputRoot, artifact.relativePath), destination, overwrite: false); } - BindingNativeCompilation.Write(manifest, result, request, engineRoot, nativeOutput, cancellation); + BindingNativeCompilation.Write(manifest, result, request, engineRoot, nativeOutput, cancellationToken); } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs index 9c9016372..b0c88088d 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs @@ -4,8 +4,8 @@ using System.Threading; using BGCS; using BGCS.Core.Hosting; -using BGCS.Core.Ports; using BGCS.Core.Plugins; +using BGCS.Core.Ports; using BGCS.Frontend.Clang.Workers; using BGCS.Hosting.Standard; @@ -13,25 +13,29 @@ namespace Inno.Build.Bindings; internal static class BindingHostFactory { - internal static HostServices CreateHostServices(string baseDirectory) => new HostServicesProvider().Create( - new(baseDirectory, JsonSerializer.SerializeToElement(new { }))); + internal static HostServices CreateHostServices(string baseDirectory) + => new HostServicesProvider().Create(new HostServicesRequest(baseDirectory, JsonSerializer.SerializeToElement(new { }))); internal static BindingHostBuilder CreateBuilder( NativeBindingProfile profile, - CancellationToken cancellation + CancellationToken cancellationToken ) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); string application = Path.GetDirectoryName(typeof(BindingHost).Assembly.Location)!; // MSBuild's application directory is not the privately loaded SDK's deployment root. BindingHostBuilder builder = BindingGenerator.CreateBuilder().ReplaceFactory( "bgcs.frontend.clang.worker", - new("inno.bindings.frontend.clang.worker", ExtensionPort.Frontend), + new ExtensionDescriptor("inno.bindings.frontend.clang.worker", ExtensionPort.Frontend), context => { HostServices host = context.RequireHostServices(); - return new FrontendWorkerClient(WorkerAssetLocator.Locate(host, applicationBase: application), host, - TimeSpan.FromSeconds(300)); - }); + return new FrontendWorkerClient( + WorkerAssetLocator.Locate(host, applicationBase: application), + host, + TimeSpan.FromSeconds(300) + ); + } + ); profile.Configure(builder); return builder; } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs index a3b08f83b..be0bf576d 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -7,6 +8,8 @@ using BGCS; using BGCS.Core.Artifacts; using BGCS.Core.Inputs; +using BGCS.Core.Requests; +using BGCS.Core.Targets; using Inno.Build.Toolchains; namespace Inno.Build.Bindings; @@ -19,52 +22,86 @@ internal static void Write( GenerationRequest request, string engineRoot, string nativeOutput, - CancellationToken cancellation + CancellationToken cancellationToken ) { - var bindings = result.nativeInputRoots.Where(binding => binding.targetId == manifest.targetId) + Dictionary bindings = result.nativeInputRoots + .Where(binding => binding.targetId == manifest.targetId) .ToDictionary(static binding => binding.rootId, StringComparer.Ordinal); NativeBindingSourceRoot[] roots = manifest.inputRoots.Select(root => new NativeBindingSourceRoot( root.id, root.kind == "generated" ? string.Empty : Path.GetRelativePath(engineRoot, bindings[root.id].directory).Replace('\\', '/'), root.kind == "generated", - root.kind is "generated" or "project" or "user")).ToArray(); - var sources = manifest.sources.Select(static source => source.relativePath).ToHashSet(StringComparer.Ordinal); - var files = manifest.inputs.Select(input => new NativeBindingSourceFile(input.rootId, input.relativePath, - input.length, input.digest.value, input.role == "ShimSource" - || input.rootId == "generated" && sources.Contains(input.relativePath))).ToList(); + root.kind is "generated" or "project" or "user" + )).ToArray(); + HashSet sources = manifest.sources.Select(static source => source.relativePath).ToHashSet(StringComparer.Ordinal); + List files = manifest.inputs.Select(input => new NativeBindingSourceFile( + input.rootId, + input.relativePath, + input.length, + input.digest.value, + input.role == "ShimSource" + || input.rootId == "generated" && sources.Contains(input.relativePath) + )).ToList(); foreach (ArtifactDescriptor artifact in manifest.sources.Concat(manifest.headers)) { if (!files.Any(file => file.rootId == "generated" && file.relativePath == artifact.relativePath)) - files.Add(new("generated", artifact.relativePath, new FileInfo(Path.Combine(nativeOutput, artifact.relativePath)).Length, - artifact.digest.value, sources.Contains(artifact.relativePath))); + { + files.Add( + new NativeBindingSourceFile( + "generated", + artifact.relativePath, + new FileInfo(Path.Combine(nativeOutput, artifact.relativePath)).Length, + artifact.digest.value, + sources.Contains(artifact.relativePath) + ) + ); + } } - var table = manifest.staticExportTable; - var target = result.targetModels.Single(model => model.targetId == manifest.targetId).resolvedTarget - ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); - var parserDefines = target.toolchain.defines.ToHashSet(StringComparer.Ordinal); - var explicitDefines = request.configuration.source.defines.Concat(request.configuration.targets.Single().settings.defines) + StaticExportTableDescriptor? table = manifest.staticExportTable; + NativeTargetDescriptor target = result.targetModels.Single(model => model.targetId == manifest.targetId).resolvedTarget + ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); + HashSet parserDefines = target.toolchain.defines.ToHashSet(StringComparer.Ordinal); + HashSet explicitDefines = request.configuration.source.defines + .Concat(request.configuration.targets.Single().settings.defines) .ToHashSet(StringComparer.Ordinal); var compilation = new NativeBindingCompilation { roots = roots, files = files.OrderBy(static file => file.rootId, StringComparer.Ordinal) - .ThenBy(static file => file.relativePath, StringComparer.Ordinal).ToArray(), + .ThenBy(static file => file.relativePath, StringComparer.Ordinal) + .ToArray(), includeDirectories = manifest.includeDirectories.Select(static directory => new NativeBindingIncludeDirectory( - directory.rootId, directory.relativePath, directory.isSystem, directory.isFramework)).ToArray(), + directory.rootId, + directory.relativePath, + directory.isSystem, + directory.isFramework + )).ToArray(), defines = manifest.defines.Where(define => !parserDefines.Contains(define) || explicitDefines.Contains(define)).ToArray(), - compilerDefines = manifest.defines.Where(define => parserDefines.Contains(define) && !explicitDefines.Contains(define)).ToArray(), - cxxStandard = Math.Max(manifest.language == SourceLanguage.Cpp ? ParseStandard(manifest.languageStandard, "c++") : 0, - manifest.languageRequirements.Select(static requirement => requirement.minimumStandard).DefaultIfEmpty().Max()), + compilerDefines = manifest.defines + .Where(define => parserDefines.Contains(define) && !explicitDefines.Contains(define)) + .ToArray(), + cxxStandard = Math.Max( + manifest.language == SourceLanguage.Cpp ? ParseStandard(manifest.languageStandard, "c++") : 0, + manifest.languageRequirements.Select(static requirement => requirement.minimumStandard).DefaultIfEmpty().Max() + ), cStandard = manifest.language == SourceLanguage.C ? ParseStandard(manifest.languageStandard, "c") : 0, - requiredExports = manifest.exportBindings.Select(static binding => binding.exportName).Distinct(StringComparer.Ordinal).ToArray(), - staticExportSymbols = table is null ? [] : [table.getExportSymbol, table.getRevisionSymbol, table.getCountSymbol, - table.getAbiIdentitySymbol, table.getPointerSizeSymbol], + requiredExports = manifest.exportBindings + .Select(static binding => binding.exportName) + .Distinct(StringComparer.Ordinal) + .ToArray(), + staticExportSymbols = table is null ? [] : [ + table.getExportSymbol, + table.getRevisionSymbol, + table.getCountSymbol, + table.getAbiIdentitySymbol, + table.getPointerSizeSymbol + ], staticExportAbi = table?.abiIdentity ?? string.Empty, staticExportNames = table?.exportNames.ToArray() ?? [] }; File.WriteAllBytes(Path.Combine(nativeOutput, "compilation.json"), JsonSerializer.SerializeToUtf8Bytes(compilation)); NativeBindingCompilation verified = NativeBindingCompilation.Load(nativeOutput); - verified.VerifyInputs(id => verified.ResolveRoot(engineRoot, nativeOutput, id), cancellation); + verified.VerifyInputs(id => verified.ResolveRoot(engineRoot, nativeOutput, id), cancellationToken); } private static int ParseStandard( @@ -73,8 +110,10 @@ string prefix ) { string normalized = standard.StartsWith("gnu", StringComparison.Ordinal) ? "c" + standard[3..] : standard; if (!normalized.StartsWith(prefix, StringComparison.Ordinal) - || !int.TryParse(normalized.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int value)) + || !int.TryParse(normalized.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int value) + ) { throw new InvalidDataException("The selected native language standard cannot be represented by CMake: " + standard); + } return value; } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/HostBindingGeneration.cs b/build/bindings/Inno.Build.Bindings/Generation/HostBindingGeneration.cs index 034a80350..cd4d293d7 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/HostBindingGeneration.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/HostBindingGeneration.cs @@ -12,11 +12,11 @@ internal static void Generate( GenerationRequest loaded, BindingGenerationPublication publication, string fingerprint, - CancellationToken cancellation + CancellationToken cancellationToken ) { string managed = publication.GetHostCandidate(publication.managedDestination); string native = publication.GetHostCandidate(publication.nativeDestination!); - BindingGenerationDiagnostics.Generate(context, definition, loaded, publication.bgcsCandidate, native, managed, cancellation); + BindingGenerationDiagnostics.Generate(context, definition, loaded, publication.bgcsCandidate, native, managed, cancellationToken); if (definition.request.checkOnly) { BindingGenerationDiagnostics.RequireEqual(managed, publication.managedDestination, true); diff --git a/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs b/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs index 6a04f66b1..ab7252903 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs @@ -13,18 +13,20 @@ internal static void Generate( GenerationRequest loaded, BindingGenerationPublication publication, string fingerprint, - CancellationToken cancellation + CancellationToken cancellationToken ) { string native = Path.Combine(publication.targetCandidate, "Native"); string managed = Path.Combine(publication.targetCandidate, "Generated"); - BindingGenerationDiagnostics.Generate(context, definition, loaded, publication.bgcsCandidate, native, managed, cancellation); + BindingGenerationDiagnostics.Generate(context, definition, loaded, publication.bgcsCandidate, native, managed, cancellationToken); if (definition.request.checkOnly) { BindingGenerationDiagnostics.RequireEqual(managed, Path.Combine(publication.managedDestination, "Generated"), true); BindingGenerationDiagnostics.RequireEqual(native, Path.Combine(publication.managedDestination, "Native"), false); } else + { BuildArtifactManifest.Write(publication.targetCandidate, fingerprint, ["Native", "Generated"], context); + } } internal static NativeBindingGenerationDescriptor Describe( diff --git a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs index 8e43a4bff..7f24ca081 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs @@ -11,18 +11,20 @@ internal static class BindingInputPlanning internal static ValueTask ComputeAsync( NativeBuildContext context, NativeBindingGenerationRequest request, - CancellationToken cancellation, - NativeBindingProfile profile + NativeBindingProfile profile, + CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(request); - cancellation.ThrowIfCancellationRequested(); - var declarations = new List { "binding-source-inputs", request.targetId, request.outputMode.ToString() }; + cancellationToken.ThrowIfCancellationRequested(); + List declarations = ["binding-source-inputs", request.targetID, request.outputMode.ToString()]; foreach (NativeComponentDescriptor component in request.components) { BindingGenerationConfiguration definition = BindingDefinitionReader.Read(context, component, request, profile); - declarations.Add(NativeBindingGenerationIdentity.Compute(definition.Load(context, cancellation), definition, context, cancellation)); + declarations.Add( + NativeBindingGenerationIdentity.Compute(definition.Load(context, cancellationToken), definition, context, cancellationToken) + ); } - return ValueTask.FromResult(NativeBuildFingerprint.Create(context, declarations, [], cancellation)); + return ValueTask.FromResult(NativeBuildFingerprint.Create(context, declarations, [], cancellationToken)); } } diff --git a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs index 34625fdae..746f36bd7 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs @@ -9,16 +9,19 @@ using System.Text.Json.Serialization; using System.Threading; using BGCS; +using BGCS.Configuration; +using BGCS.Core; using BGCS.Core.Hosting; using BGCS.Core.Inputs; using BGCS.Core.Targets; +using BGCS.Runtime; using Inno.Build.Toolchains; namespace Inno.Build.Bindings; internal static class NativeBindingGenerationIdentity { - private static readonly JsonSerializerOptions S_OPTIONS = new() + private static readonly JsonSerializerOptions OPTIONS = new() { Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; @@ -27,26 +30,33 @@ internal static string Compute( GenerationRequest request, BindingGenerationConfiguration definition, NativeBuildContext context, - CancellationToken cancellation + CancellationToken cancellationToken ) { using HostServices services = BindingHostFactory.CreateHostServices(context.engineRoot); - var builder = BindingHostFactory.CreateBuilder(definition.profile, cancellation); + BindingHostBuilder builder = BindingHostFactory.CreateBuilder(definition.profile, cancellationToken); foreach (string plugin in request.configuration.extensions.plugins) + { builder.AddPluginManifest(plugin, services.paths); + } BindingHost host = builder.Build(); try { - var config = request.configuration; - var target = config.targets.Single(); - var settings = target.settings; - var source = config.source; + BindingConfiguration config = request.configuration; + TargetConfiguration target = config.targets.Single(); + ToolchainConfiguration settings = target.settings; + SourceConfiguration source = config.source; AnalysisResult analysis = host.AnalyzeAsync(new AnalysisRequest(source.headers, source.language, request.baseDirectory) { targetId = target.id, triple = target.triple, - toolchain = new NativeToolchainDescriptor(compilerPath: settings.compilerPath, sysRoot: settings.sysRoot, - systemIncludeFolders: settings.systemIncludeDirectories, cxxSystemIncludeFolders: settings.cxxSystemIncludeDirectories, - defines: settings.defines, arguments: settings.arguments), + toolchain = new NativeToolchainDescriptor( + compilerPath: settings.compilerPath, + sysRoot: settings.sysRoot, + systemIncludeFolders: settings.systemIncludeDirectories, + cxxSystemIncludeFolders: settings.cxxSystemIncludeDirectories, + defines: settings.defines, + arguments: settings.arguments + ), languageStandard = source.languageStandard!, includeDirectories = source.includeDirectories, systemIncludeDirectories = source.systemIncludeDirectories, @@ -57,11 +67,13 @@ CancellationToken cancellation parseMacros = source.parseMacros, parseComments = source.parseComments, parseSystemIncludes = source.includeSystemDeclarations - }, cancellation).GetAwaiter().GetResult(); + }, cancellationToken).GetAwaiter().GetResult(); if (!analysis.success || analysis.snapshot is null) - throw new InvalidDataException("BGCS input analysis failed: " + analysis.GetDiagnosticSummary()); - var declarations = new List { + throw new InvalidDataException("BGCS input analysis failed: " + analysis.GetDiagnosticSummary()); + } + List declarations = + [ SerializeIdentity(config), SerializeIdentity(analysis.target), SerializeIdentity(analysis.snapshot), @@ -69,31 +81,52 @@ CancellationToken cancellation SerializeIdentity(request.configurationSnapshot), SerializeIdentity(request.pluginSnapshots), definition.component.nativeProject, - definition.request.targetId, + definition.request.targetID, definition.request.outputMode.ToString() - }; - var profileInputs = definition.profile.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, Path.GetFullPath(path, context.engineRoot))); - var inputs = request.configurationSnapshot.files.Concat(request.pluginSnapshots.SelectMany(static snapshot => snapshot.files)).Concat(analysis.snapshot.files) - .Concat(analysis.argumentInputs?.files ?? []).Select(input => NativeBuildInput.FromPath(context.engineRoot, input.path)).ToList(); + ]; + IEnumerable profileInputs = definition.profile.inputPaths.Select( + path => NativeBuildInput.FromPath(context.engineRoot, Path.GetFullPath(path, context.engineRoot)) + ); + List inputs = request.configurationSnapshot.files + .Concat(request.pluginSnapshots.SelectMany(static snapshot => snapshot.files)) + .Concat(analysis.snapshot.files) + .Concat(analysis.argumentInputs?.files ?? []) + .Select(input => NativeBuildInput.FromPath(context.engineRoot, input.path)) + .ToList(); inputs.AddRange(profileInputs); Assembly implementation = typeof(NativeBindingGenerator).Assembly; string implementationIdentity = implementation.GetCustomAttributes() .Single(attribute => attribute.Key == "Inno.BindingImplementation").Value ?? throw new InvalidDataException("The binding implementation must declare its content identity."); declarations.Add("bindingImplementation=" + implementationIdentity); - var assemblies = new[] { typeof(BindingHost).Assembly, typeof(BGCS.Core.BindingDiagnostic).Assembly, - typeof(BGCS.Runtime.NativeModuleSession).Assembly }.Concat(definition.profile.GetExtensionAssemblies()).ToList(); - foreach (AssemblyName reference in assemblies.Prepend(implementation).SelectMany(static assembly => assembly.GetReferencedAssemblies()) - .Where(static reference => reference.Name == "BGCS" || reference.Name!.StartsWith("BGCS.", StringComparison.Ordinal)) - .DistinctBy(static reference => reference.FullName).ToArray()) + List assemblies = new[] + { + typeof(BindingHost).Assembly, + typeof(BindingDiagnostic).Assembly, + typeof(NativeModuleSession).Assembly + }.Concat(definition.profile.GetExtensionAssemblies()).ToList(); + foreach (AssemblyName reference in assemblies + .Prepend(implementation) + .SelectMany(static assembly => assembly.GetReferencedAssemblies()) + .Where( + static reference => reference.Name == "BGCS" || reference.Name!.StartsWith("BGCS.", StringComparison.Ordinal) + ) + .DistinctBy(static reference => reference.FullName) + .ToArray() + ) { assemblies.Add(Assembly.Load(reference)); + } foreach (Assembly assembly in assemblies.Distinct()) + { inputs.Add(new NativeBuildInput("binding-implementation/" + Path.GetFileName(assembly.Location), assembly.Location)); + } string resources = Path.Combine(Path.GetDirectoryName(typeof(BindingHost).Assembly.Location)!, "bgcs", "worker-assets"); if (!Directory.Exists(resources)) + { throw new DirectoryNotFoundException("The restored BGCS SDK worker content is missing: " + resources); + } inputs.Add(new NativeBuildInput("binding-worker-assets", resources)); - return NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); + return NativeBuildFingerprint.Create(context, declarations, inputs, cancellationToken); } finally { @@ -105,7 +138,7 @@ private static string SerializeIdentity(T value) { var buffer = new ArrayBufferWriter(); using var writer = new Utf8JsonWriter(buffer); - WriteIdentity(writer, JsonSerializer.SerializeToElement(value, S_OPTIONS)); + WriteIdentity(writer, JsonSerializer.SerializeToElement(value, OPTIONS)); writer.Flush(); return Encoding.UTF8.GetString(buffer.WrittenSpan); } @@ -129,10 +162,14 @@ JsonElement value { writer.WriteStartArray(); foreach (JsonElement element in value.EnumerateArray()) + { WriteIdentity(writer, element); + } writer.WriteEndArray(); } else + { value.WriteTo(writer); + } } } diff --git a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs index 4afb10927..7e7537dea 100644 --- a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs +++ b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs @@ -9,13 +9,13 @@ namespace Inno.Build.Bindings; /// public sealed partial class NativeBindingGenerator { - /// /// /// Configuration inheritance uses a remote input without local build ownership. /// + /// public ValueTask ComputeInputFingerprintAsync( NativeBuildContext context, NativeBindingGenerationRequest request, CancellationToken cancellationToken - ) => BindingInputPlanning.ComputeAsync(context, request, cancellationToken, m_profile); + ) => BindingInputPlanning.ComputeAsync(context, request, m_profile, cancellationToken); } diff --git a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs index 640193808..9619cb1a1 100644 --- a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs +++ b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs @@ -21,10 +21,11 @@ public sealed partial class NativeBindingGenerator : INativeBindingGenerator /// public NativeBindingGenerator(NativeBindingProfile profile) { - m_profile = profile ?? throw new ArgumentNullException(nameof(profile)); + ArgumentNullException.ThrowIfNull(profile); + m_profile = profile; } - /// + /// public async ValueTask GenerateAsync( NativeBuildContext context, NativeBindingGenerationRequest request, diff --git a/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs b/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs index 755fe4ef7..abf72193c 100644 --- a/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs +++ b/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs @@ -18,23 +18,33 @@ internal static void Generate( string candidate, string nativeOutput, string managedOutput, - CancellationToken cancellation + CancellationToken cancellationToken ) { - GenerationRequest selected = request.WithConfiguration(request.configuration with - { - output = request.configuration.output with { root = candidate } - }); + GenerationRequest selected = request.WithConfiguration( + request.configuration with + { + output = request.configuration.output with { root = candidate } + } + ); context.RecordBindingGeneration(); string root = Path.Combine(context.engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"); string workspace = selected.configuration.cache.directory; var cache = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, root, "bgcs-workspaces", BuildCacheArtifactRole.ReusableWorkspace, cancellation); - using FileLease activity = cache.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); - using FileLease ownership = FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult(); - cache.BeginWorkingDirectory(workspace, workspace + ".lock", definition.request.targetId, cancellation); - BindingHostExecution.Generate(selected, definition.profile, context.engineRoot, nativeOutput, managedOutput, cancellation); - cache.Record(workspace, workspace + ".lock", [], null, definition.request.targetId, cancellation); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + root, + "bgcs-workspaces", + BuildCacheArtifactRole.ReusableWorkspace, + cancellationToken + ); + using FileLease activity = cache.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease ownership = FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + cache.BeginWorkingDirectory(workspace, workspace + ".lock", definition.request.targetID, cancellationToken); + BindingHostExecution.Generate(selected, definition.profile, context.engineRoot, nativeOutput, managedOutput, cancellationToken); + cache.Record(workspace, workspace + ".lock", [], null, definition.request.targetID, cancellationToken); } internal static void RequireEqual( @@ -44,16 +54,23 @@ bool normalizeNewlines ) { string[] files = Directory.EnumerateFiles(candidate, "*", SearchOption.AllDirectories).ToArray(); if (!Directory.Exists(current) || Directory.EnumerateFiles(current, "*", SearchOption.AllDirectories).Count() != files.Length) + { throw new InvalidDataException($"Generated output is missing or has a different file inventory: {current}"); + } foreach (string file in files) { string other = Path.Combine(current, Path.GetRelativePath(candidate, file)); - bool equal = File.Exists(other) && (normalizeNewlines - ? File.ReadAllText(file).Replace("\r\n", "\n", StringComparison.Ordinal) - == File.ReadAllText(other).Replace("\r\n", "\n", StringComparison.Ordinal) - : File.ReadAllBytes(file).AsSpan().SequenceEqual(File.ReadAllBytes(other))); + bool equal = File.Exists(other) + && ( + normalizeNewlines + ? File.ReadAllText(file).Replace("\r\n", "\n", StringComparison.Ordinal) + == File.ReadAllText(other).Replace("\r\n", "\n", StringComparison.Ordinal) + : File.ReadAllBytes(file).AsSpan().SequenceEqual(File.ReadAllBytes(other)) + ); if (!equal) + { throw new InvalidDataException($"Generated output is out of date: {other}"); + } } } } diff --git a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs index 4fc3d107f..84c6ec56e 100644 --- a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs +++ b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; -using System.Threading; -using Inno.Core.IO; using System.IO; using System.Linq; +using System.Threading; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Bindings; @@ -20,16 +21,29 @@ private BindingGenerationPublication( string destination, string? native, bool target, - CancellationToken cancellation + CancellationToken cancellationToken ) { - managedDestination = destination; - nativeDestination = native; - m_owner = ProcessOwnedDirectory.CreateAsync(workingRoot, cancellation).AsTask().GetAwaiter().GetResult(); + this.managedDestination = destination; + this.nativeDestination = native; + m_owner = ProcessOwnedDirectory.CreateAsync(workingRoot, cancellationToken).AsTask().GetAwaiter().GetResult(); m_workingRoot = workingRoot; m_target = target; m_candidates.Add(destination, Path.Combine(m_owner.directory, "Managed")); if (native is not null) + { m_candidates.Add(native, Path.Combine(m_owner.directory, "Native")); + } + } + + /// + /// Releases unpublished staging directories without replacing completed output trees. + /// + public void Dispose() + { + if (!m_preserveRecovery) + { + m_owner.Dispose(); + } } internal string managedDestination { get; } @@ -38,19 +52,6 @@ CancellationToken cancellation internal string targetCandidate => m_candidates[managedDestination]; internal IEnumerable stagingPaths => m_candidates.Values; - internal static BindingGenerationPublication CreateTarget( - string workingRoot, - string destination, - CancellationToken cancellation - ) => new(workingRoot, destination, null, true, cancellation); - - internal static BindingGenerationPublication CreateHost( - string workingRoot, - string managed, - string? native, - CancellationToken cancellation - ) => new(workingRoot, managed, native, false, cancellation); - internal string GetHostCandidate(string destination) => m_candidates[destination]; internal void Commit() @@ -70,10 +71,10 @@ internal void Commit() // Generation locks protect the complete host output set. Keep every previous tree // in this claimed transaction until all candidate renames succeed. var previous = new Dictionary(StringComparer.Ordinal); - var installed = new List(); + List installed = []; try { - foreach (var candidate in m_candidates) + foreach (KeyValuePair candidate in m_candidates) { Directory.CreateDirectory(Path.GetDirectoryName(candidate.Key)!); if (Directory.Exists(candidate.Key)) @@ -88,15 +89,19 @@ internal void Commit() } catch (Exception commitFailure) { - var failures = new List { commitFailure }; + List failures = [commitFailure]; foreach (string destination in m_candidates.Keys.Reverse()) { try { if (installed.Contains(destination)) + { Directory.Move(destination, m_candidates[destination]); + } if (previous.TryGetValue(destination, out string? backup)) + { Directory.Move(backup, destination); + } } catch (Exception rollbackFailure) { @@ -106,20 +111,30 @@ internal void Commit() if (failures.Count > 1) { m_preserveRecovery = true; - new Inno.Build.Toolchains.BuildCachePublisher(m_workingRoot, Inno.Build.Toolchains.BuildCacheArtifactRole.ImmutableArtifact) - .Record(m_owner.directory, m_owner.directory + ".work.lock", [], "binding-recovery:" + Path.GetFileName(m_owner.directory), null); + new BuildCachePublisher(m_workingRoot, BuildCacheArtifactRole.ImmutableArtifact) + .Record( + m_owner.directory, + m_owner.directory + ".work.lock", + [], + "binding-recovery:" + Path.GetFileName(m_owner.directory), + null + ); throw new AggregateException("Binding publication failed; owned recovery trees could not be fully restored.", failures); } throw; } } - /// - /// Releases unpublished staging directories without replacing completed output trees. - /// - public void Dispose() - { - if (!m_preserveRecovery) - m_owner.Dispose(); - } + internal static BindingGenerationPublication CreateTarget( + string workingRoot, + string destination, + CancellationToken cancellationToken + ) => new(workingRoot, destination, null, true, cancellationToken); + + internal static BindingGenerationPublication CreateHost( + string workingRoot, + string managed, + string? native, + CancellationToken cancellationToken + ) => new(workingRoot, managed, native, false, cancellationToken); } diff --git a/build/cli/Inno.Build.Cli/BuildApplication.cs b/build/cli/Inno.Build.Cli/BuildApplication.cs index 7f7a4f6fc..49672c73d 100644 --- a/build/cli/Inno.Build.Cli/BuildApplication.cs +++ b/build/cli/Inno.Build.Cli/BuildApplication.cs @@ -3,7 +3,8 @@ using System.Threading.Tasks; using Inno.Tooling.Architecture; using Inno.Tooling.Validation; -using DocumentationCommand = Inno.Tooling.Documentation.DocumentationCommand; + +using ToolingCommand = Inno.Tooling.Documentation.DocumentationCommand; namespace Inno.Build.Cli; @@ -27,17 +28,24 @@ public static partial class BuildApplication /// /// The argument array is absent. /// - public static async Task Run( + public static async Task RunAsync( string[] arguments, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(arguments); if (arguments.Length == 0 || arguments[0] is "help" or "--help" or "-h") { - Console.WriteLine("InnoEngine.Build [options]"); + Console.WriteLine( + "InnoEngine.Build [options]" + ); Console.WriteLine("Default entry command: support --product editor (current SDK host and entry configuration)."); - Console.WriteLine("support --product editor|player --target TARGET: prepare reusable target support without building the Editor's managed source."); + Console.WriteLine( + "support --product editor|player --target TARGET: prepare reusable target support without building the Editor's managed source." + ); Console.WriteLine("editor [--clean]: build the complete Editor entry and its dependencies."); + Console.WriteLine( + "style check|fix ROOT [--rule ID]... [--paths-from FILE] [--report FILE]: check handwritten C# against the style rulebook or apply its automatic fixes." + ); return 0; } try @@ -51,27 +59,44 @@ CancellationToken cancellationToken case "plugin": case "scripts": case "import-sample": - return await ProjectBuildWorkflow.RunAsync(arguments, cancellationToken); + return await ProjectBuildWorkflow.RunAsync(arguments, cancellationToken).ConfigureAwait(false); case "verify": return ArchitectureValidator.Execute(options, cancellationToken); + case "style": + return StyleCommand.Execute(options); case "docs": if (options.Length != 0 && options[0] == "export-plan") - return await DocumentationReferences.PlanExportAsync(options[1..], cancellationToken); + { + return await DocumentationReferences.PlanExportAsync(options[1..], cancellationToken).ConfigureAwait(false); + } if (options.Length != 0 && options[0] == "export-projects") + { return DocumentationReferences.ExportProjects(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "export-api") + { return DocumentationReferences.ExportApi(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "validate-api") - return await DocumentationReferences.ValidateApiAsync(options[1..], cancellationToken); + { + return await DocumentationReferences.ValidateApiAsync(options[1..], cancellationToken).ConfigureAwait(false); + } if (options.Length > 0 && options[0] == "validate-examples") - return await DocumentationExamples.ExecuteAsync(options[1..], cancellationToken); + { + return await DocumentationExamples.ExecuteAsync(options[1..], cancellationToken).ConfigureAwait(false); + } if (options.Length > 0 && options[0] == "example-plan") - return await DocumentationExamples.ExecuteAsync([..options[1..], "--operation", "plan"], cancellationToken); - return await DocumentationCommand.ExecuteAsync(options, cancellationToken); + { + return await DocumentationExamples.ExecuteAsync( + [..options[1..], "--operation", "plan"], + cancellationToken + ).ConfigureAwait(false); + } + return await ToolingCommand.ExecuteAsync(options, cancellationToken).ConfigureAwait(false); case "validate": - return await ValidationCommand.ExecuteAsync(options, cancellationToken); + return await ValidationCommand.ExecuteAsync(options, cancellationToken).ConfigureAwait(false); case "verify-native": - return await NativeBindingsVerification.RunAsync(options, cancellationToken); + return await NativeBindingsVerification.RunAsync(options, cancellationToken).ConfigureAwait(false); case "native-dependencies": case "support": case "editor": @@ -91,18 +116,42 @@ CancellationToken cancellationToken "shader" => ["assets", "shader", "renderer", "output"], _ => [] }; - parsed.Validate(["engine-root", "dotnet", "target", "tools-target", "configuration", - "cache-budget-gib", "cache-min-free-gib", "cache-time-seconds", "native-dependencies", ..specific]); + parsed.Validate([ + "engine-root", + "dotnet", + "target", + "tools-target", + "configuration", + "cache-budget-gib", + "cache-min-free-gib", + "cache-time-seconds", + "native-dependencies", + ..specific + ]); var context = new BuildCommandContext(parsed); switch (command) { - case "native-dependencies": await NativeDependenciesCommand.RunAsync(context, parsed, cancellationToken); break; - case "support": await SupportBuildCommand.RunAsync(context, parsed, cancellationToken); break; - case "editor": await EditorBuildCommand.RunAsync(context, parsed, cancellationToken); break; - case "clean": await CleanCommand.RunAsync(context, parsed, cancellationToken); break; - case "bindings": await BindingCommand.RunAsync(context, parsed, cancellationToken); break; - case "support-pack": await SupportPackCommand.RunAsync(context, parsed, cancellationToken); break; - case "shader": await ShaderCommand.RunAsync(context, parsed, cancellationToken); break; + case "native-dependencies": + await NativeDependenciesCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "support": + await SupportBuildCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "editor": + await EditorBuildCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "clean": + await CleanCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "bindings": + await BindingCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "support-pack": + await SupportPackCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; + case "shader": + await ShaderCommand.RunAsync(context, parsed, cancellationToken).ConfigureAwait(false); + break; } if (command is "support" or "editor" or "support-pack" or "bindings" or "shader") { diff --git a/build/cli/Inno.Build.Cli/BuildCommand.cs b/build/cli/Inno.Build.Cli/BuildCommand.cs index b41b3c5fa..2d896ca14 100644 --- a/build/cli/Inno.Build.Cli/BuildCommand.cs +++ b/build/cli/Inno.Build.Cli/BuildCommand.cs @@ -2,20 +2,11 @@ using System.Collections.Generic; using System.IO; using Inno.Assets; -using Inno.Build; using Inno.Build.Managed; using Inno.Core.Settings; namespace Inno.Build.Cli; -internal enum BuildCommandKind -{ - Game, - Plugin, - ImportSample, - Scripts -} - internal sealed class BuildCommand { private readonly IReadOnlyDictionary m_values; @@ -27,11 +18,13 @@ IReadOnlyDictionary values this.kind = kind; m_values = values; if (kind == BuildCommandKind.Game) + { _ = Require(values, "target"); - projectDirectory = Require(values, "project"); - supportPackRoot = kind == BuildCommandKind.Game - ? Require(values, "support-packs") - : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); + } + this.projectDirectory = Require(values, "project"); + this.supportPackRoot = kind == BuildCommandKind.Game + ? Require(values, "support-packs") + : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); } internal BuildCommandKind kind { get; } @@ -42,13 +35,13 @@ IReadOnlyDictionary values internal string? engineRoot => m_values.ContainsKey("engine-root") ? Require(m_values, "engine-root") : null; - internal BuildTargetId toolsTarget => new(Require(m_values, "tools-target")); + internal BuildTargetID toolsTarget => new(Require(m_values, "tools-target")); internal string? nativeDependencies => m_values.GetValueOrDefault("native-dependencies"); internal string? dotnetHost => m_values.GetValueOrDefault("dotnet"); - internal BuildTargetId gameTarget => new(Require(m_values, "target")); + internal BuildTargetID gameTarget => new(Require(m_values, "target")); internal string? profilePath => m_values.GetValueOrDefault("profile"); @@ -58,10 +51,46 @@ IReadOnlyDictionary values internal bool generateIdeProjects => m_values.ContainsKey("ide"); + internal GameBuildRequest CreateGameRequest(BuildProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + if (m_values.TryGetValue("startup-scene", out string? scene)) + { + profile.startupScene = AssetPath.Parse(scene).ToString(); + } + if (m_values.TryGetValue("target", out string? target)) + { + profile.target = new BuildTargetID(target); + } + if (m_values.TryGetValue("deployment", out string? deployment)) + { + profile.managedDeployment = new ManagedDeploymentID(deployment); + } + return new GameBuildRequest + { + profile = profile, + outputDirectory = Require(m_values, "output") + }; + } + + internal PluginBuildRequest CreatePluginRequest(ProjectID projectID) + => new() + { + pluginID = projectID.value, + displayName = Require(m_values, "display-name"), + outputPath = Require(m_values, "output"), + dependencies = m_values.TryGetValue("dependencies", out string? dependencyList) + ? dependencyList.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) + : [], + includeDependencies = m_values.ContainsKey("include-dependencies") + }; + internal static BuildCommand Parse(IReadOnlyList args) { if (args.Count == 0 || args[0] is "help" or "--help" or "-h") + { throw new ArgumentException(Usage()); + } BuildCommandKind kind = args[0] switch { "game" => BuildCommandKind.Game, @@ -75,7 +104,9 @@ internal static BuildCommand Parse(IReadOnlyList args) { string argument = args[index]; if (!argument.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Unexpected argument '{argument}'."); + } string key = argument[2..]; if (key is "include-dependencies" or "ide") { @@ -83,7 +114,9 @@ internal static BuildCommand Parse(IReadOnlyList args) continue; } if (++index >= args.Count || args[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Argument '--{key}' requires a value."); + } values.Add(key, args[index]); } string[] specific = kind switch @@ -95,55 +128,42 @@ internal static BuildCommand Parse(IReadOnlyList args) _ => [] }; string[] preparation = kind is BuildCommandKind.Game or BuildCommandKind.Plugin - ? ["tools-target", "support-packs", "native-dependencies"] : []; - var allowed = new HashSet(["engine-root", "dotnet", "project", "output", ..preparation, ..specific], StringComparer.Ordinal); + ? ["tools-target", "support-packs", "native-dependencies"] + : []; + var allowed = new HashSet( + ["engine-root", "dotnet", "project", "output", ..preparation, ..specific], + StringComparer.Ordinal + ); foreach (string key in values.Keys) + { if (!allowed.Contains(key)) + { throw new ArgumentException($"Unknown argument '--{key}' for '{args[0]}'."); + } + } return new BuildCommand(kind, values); } - internal GameBuildRequest CreateGameRequest(BuildProfile profile) - { - ArgumentNullException.ThrowIfNull(profile); - if (m_values.TryGetValue("startup-scene", out string? scene)) - profile.startupScene = AssetPath.Parse(scene).ToString(); - if (m_values.TryGetValue("target", out string? target)) - profile.target = new BuildTargetId(target); - if (m_values.TryGetValue("deployment", out string? deployment)) - profile.managedDeployment = new ManagedDeploymentId(deployment); - return new GameBuildRequest - { - profile = profile, - outputDirectory = Require(m_values, "output") - }; - } - - internal PluginBuildRequest CreatePluginRequest(ProjectId projectId) - => new() - { - pluginId = projectId.value, - displayName = Require(m_values, "display-name"), - outputPath = Require(m_values, "output"), - dependencies = m_values.TryGetValue("dependencies", out string? dependencyList) - ? dependencyList.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) - : Array.Empty(), - includeDependencies = m_values.ContainsKey("include-dependencies") - }; - private static string Require( IReadOnlyDictionary values, string key - ) - => values.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value - : throw new ArgumentException($"Required argument '--{key}' is missing."); + ) => values.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value) + ? value + : throw new ArgumentException($"Required argument '--{key}' is missing."); private static string Usage() => "Usage:\n" - + " Project commands accept [--engine-root ] for an executable outside the source checkout.\n" - + " InnoEngine.Build game --tools-target --project --support-packs --output [--profile ] --target [--deployment ] [--startup-scene ]\n" - + " InnoEngine.Build plugin --tools-target --project --output --display-name [--dependencies ] [--include-dependencies]\n" - + " InnoEngine.Build import-sample --project --source [--dotnet ]\n" - + " InnoEngine.Build scripts --project --output [--dotnet ] [--ide]"; + + " Project commands accept [--engine-root ] for an executable outside the source checkout.\n" + + " InnoEngine.Build game --tools-target --project --support-packs --output [--profile ] --target [--deployment ] [--startup-scene ]\n" + + " InnoEngine.Build plugin --tools-target --project --output --display-name [--dependencies ] [--include-dependencies]\n" + + " InnoEngine.Build import-sample --project --source [--dotnet ]\n" + + " InnoEngine.Build scripts --project --output [--dotnet ] [--ide]"; +} + +internal enum BuildCommandKind +{ + Game, + Plugin, + ImportSample, + Scripts } diff --git a/build/cli/Inno.Build.Cli/BuildCommandContext.cs b/build/cli/Inno.Build.Cli/BuildCommandContext.cs index fb3648bc2..1d5e8d8b2 100644 --- a/build/cli/Inno.Build.Cli/BuildCommandContext.cs +++ b/build/cli/Inno.Build.Cli/BuildCommandContext.cs @@ -14,54 +14,72 @@ internal sealed class BuildCommandContext { internal BuildCommandContext(BuildCommandLine options) { - nativeDependencies = options.Read("native-dependencies", string.Empty); - root = ResolveEngineRoot(options.Read("engine-root", string.Empty)); + this.nativeDependencies = options.Read("native-dependencies", string.Empty); + this.root = ResolveEngineRoot(options.Read("engine-root", string.Empty)); if (nativeDependencies.Length > 0) - nativeDependencies = Path.GetFullPath(nativeDependencies, root); - configuration = options.Read("configuration", "Release"); + { + this.nativeDependencies = Path.GetFullPath(nativeDependencies, root); + } + this.configuration = options.Read("configuration", "Release"); ToolchainEnvironment.ValidateConfiguration(configuration.ToLowerInvariant()); - configuration = configuration.Equals("debug", StringComparison.OrdinalIgnoreCase) ? "Debug" : "Release"; - toolsTarget = new BuildTargetId(options.Require("tools-target")); - target = new BuildTargetId(options.Read("target", toolsTarget.value)); + this.configuration = configuration.Equals("debug", StringComparison.OrdinalIgnoreCase) ? "Debug" : "Release"; + this.toolsTarget = new BuildTargetID(options.Require("tools-target")); + this.target = new BuildTargetID(options.Read("target", toolsTarget.value)); string dotnet = ToolchainEnvironment.ResolveExecutable(options.Read("dotnet", "dotnet")); - composition = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!, toolsTarget, dotnet, - nativeDependencies.Length == 0 ? null : nativeDependencies); - distribution = StandardBuildDistribution.Create(composition).build; + this.composition = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!, + toolsTarget, + dotnet, + nativeDependencies.Length == 0 ? null : nativeDependencies + ); + this.distribution = StandardBuildDistribution.Create(composition).build; } internal string nativeDependencies { get; } internal string root { get; } internal string configuration { get; } - internal BuildTargetId target { get; } - internal BuildTargetId toolsTarget { get; } + internal BuildTargetID target { get; } + internal BuildTargetID toolsTarget { get; } internal BuildCompositionContext composition { get; } internal BuildDistribution distribution { get; } - internal static string ResolveEngineRoot(string? selectedRoot) - { - string root = Path.GetFullPath(string.IsNullOrWhiteSpace(selectedRoot) ? ToolchainEnvironment.FindRepoRoot() : selectedRoot); - if (!File.Exists(Path.Combine(root, "InnoEngine.sln"))) - throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{root}'."); - return root; - } - internal async Task PreflightEditorAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); BuildPlatformContribution? platform = distribution.platforms.SingleOrDefault(value => value.descriptor.id == target); string project = platform?.editorProject - ?? throw new NotSupportedException($"Target '{target}' does not provide an Editor product."); + ?? throw new NotSupportedException($"Target '{target}' does not provide an Editor product."); var native = new NativeBuildContext(root, configuration.ToLowerInvariant()); if (nativeDependencies.Length == 0) - await distribution.ResolveNativeToolchain(target.value).ResolveAsync(native, composition.host, - target.value, cancellationToken).ConfigureAwait(false); + { + await distribution.ResolveNativeToolchain(target.value).ResolveAsync( + native, + composition.host, + target.value, + cancellationToken + ).ConfigureAwait(false); + } return Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"); } - internal string[] ProductArguments(string project) => - [ - project, "--configuration", configuration, - "--disable-build-servers", "-m:1", "-nodeReuse:false", - ..(nativeDependencies.Length == 0 ? Array.Empty() : ["-p:InnoNativeDependencyManifest=" + nativeDependencies]) - ]; + internal string[] ProductArguments(string project) + => [ + project, + "--configuration", + configuration, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + ..(nativeDependencies.Length == 0 ? Array.Empty() : ["-p:InnoNativeDependencyManifest=" + nativeDependencies]) + ]; + + internal static string ResolveEngineRoot(string? selectedRoot) + { + string root = Path.GetFullPath(string.IsNullOrWhiteSpace(selectedRoot) ? ToolchainEnvironment.FindRepoRoot() : selectedRoot); + if (!File.Exists(Path.Combine(root, "InnoEngine.sln"))) + { + throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{root}'."); + } + return root; + } } diff --git a/build/cli/Inno.Build.Cli/BuildCommandLine.cs b/build/cli/Inno.Build.Cli/BuildCommandLine.cs index 045660602..c8741cd74 100644 --- a/build/cli/Inno.Build.Cli/BuildCommandLine.cs +++ b/build/cli/Inno.Build.Cli/BuildCommandLine.cs @@ -7,6 +7,30 @@ internal sealed class BuildCommandLine { private readonly Dictionary m_values = new(StringComparer.Ordinal); + internal bool Has(string name) => m_values.ContainsKey(name); + + internal void Validate(params string[] allowed) + { + var names = new HashSet(allowed, StringComparer.Ordinal); + foreach (string key in m_values.Keys) + { + if (!names.Contains(key)) + { + throw new ArgumentException($"Unknown option '--{key}'."); + } + } + } + + internal string Read( + string name, + string defaultValue + ) => m_values.GetValueOrDefault(name, defaultValue); + + internal string Require(string name) + => m_values.TryGetValue(name, out string? value) && !string.IsNullOrWhiteSpace(value) + ? value + : throw new ArgumentException($"Required option '--{name}' is missing."); + internal static BuildCommandLine Parse(IReadOnlyList arguments) { var result = new BuildCommandLine(); @@ -14,37 +38,24 @@ internal static BuildCommandLine Parse(IReadOnlyList arguments) { string key = arguments[index]; if (!key.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Expected '--name value'; incomplete option '{key}'."); + } bool flag = key is "--clean" or "--dry-run"; string value = "true"; if (!flag) { if (++index >= arguments.Count || arguments[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Missing value for '{key}'."); + } value = arguments[index]; } if (!result.m_values.TryAdd(key[2..], value)) + { throw new ArgumentException($"Duplicate option '{key}'."); + } } return result; } - - internal bool Has(string name) => m_values.ContainsKey(name); - - internal void Validate(params string[] allowed) - { - var names = new HashSet(allowed, StringComparer.Ordinal); - foreach (string key in m_values.Keys) - if (!names.Contains(key)) - throw new ArgumentException($"Unknown option '--{key}'."); - } - - internal string Read( - string name, - string defaultValue - ) => m_values.GetValueOrDefault(name, defaultValue); - - internal string Require(string name) - => m_values.TryGetValue(name, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value : throw new ArgumentException($"Required option '--{name}' is missing."); } diff --git a/build/cli/Inno.Build.Cli/BuildComposition.cs b/build/cli/Inno.Build.Cli/BuildComposition.cs index 7754f497e..c239796c8 100644 --- a/build/cli/Inno.Build.Cli/BuildComposition.cs +++ b/build/cli/Inno.Build.Cli/BuildComposition.cs @@ -28,15 +28,32 @@ internal static async Task PrepareNativeAsync( CancellationToken cancellationToken, string? nativeDependencies = null ) { - var distribution = StandardBuildDistribution.Create(context).build; + BuildDistribution distribution = StandardBuildDistribution.Create(context).build; NativeProductContribution contribution = distribution.ResolveNativeProduct(context.toolsTarget.value, "shader-tools"); if (nativeDependencies is not null) - return await NativeDependencyManifest.AcquireAsync(engineRoot, nativeDependencies, context.toolsTarget.value, - C_HOST_CONFIGURATION, contribution.plan, cancellationToken).ConfigureAwait(false); - var nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator(StandardBuildDistribution.Create(context).build.ResolveBindingGenerator(context.toolsTarget.value)); - var provider = StandardBuildDistribution.Create(context).build.ResolveNativeToolchain(context.toolsTarget.value); - nativeContext = nativeContext.WithToolchain(await provider.ResolveAsync( - nativeContext, context.host, context.toolsTarget.value, cancellationToken).ConfigureAwait(false)); + { + return await NativeDependencyManifest.AcquireAsync( + engineRoot, + nativeDependencies, + context.toolsTarget.value, + C_HOST_CONFIGURATION, + contribution.plan, + cancellationToken + ).ConfigureAwait(false); + } + NativeBuildContext nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator( + StandardBuildDistribution.Create(context).build.ResolveBindingGenerator(context.toolsTarget.value) + ); + INativeToolchainProvider provider = StandardBuildDistribution.Create(context).build + .ResolveNativeToolchain(context.toolsTarget.value); + nativeContext = nativeContext.WithToolchain( + await provider.ResolveAsync( + nativeContext, + context.host, + context.toolsTarget.value, + cancellationToken + ).ConfigureAwait(false) + ); return await contribution.BuildAsync(nativeContext, cancellationToken).ConfigureAwait(false); } @@ -49,8 +66,14 @@ internal static BuildPipeline CreatePipeline( ScriptCompiler compiler, string supportPackRoot, ToolRunner tools - ) { - return BuildPipelineFactory.Create( - context, StandardBuildDistribution.Create(context, tools).build, engine, assets, plugins, settings, compiler, supportPackRoot); - } + ) => BuildPipelineFactory.Create( + context, + StandardBuildDistribution.Create(context, tools).build, + engine, + assets, + plugins, + settings, + compiler, + supportPackRoot + ); } diff --git a/build/cli/Inno.Build.Cli/BuildWorkspace.cs b/build/cli/Inno.Build.Cli/BuildWorkspace.cs index ee85160c6..8c9059d73 100644 --- a/build/cli/Inno.Build.Cli/BuildWorkspace.cs +++ b/build/cli/Inno.Build.Cli/BuildWorkspace.cs @@ -1,22 +1,21 @@ -using Inno.Build.Composition; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Core.IO; -using Inno.Extensibility.Modules; -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; - +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build; +using Inno.Build.Composition; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Settings; +using Inno.Extensibility.Modules; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; @@ -49,7 +48,18 @@ string projectDirectory m_projectDirectory = projectDirectory; } - internal ProjectId projectId => m_settings.projectId; + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + m_plugins.Dispose(); + m_assets.Dispose(); + m_settings.Dispose(); + m_engine.Dispose(); + } + + internal ProjectID projectID => m_settings.projectID; internal BuildPipeline CreatePipeline( BuildCompositionContext context, @@ -76,11 +86,19 @@ CancellationToken cancellationToken ) => { ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( - cancellationToken: cancellationToken, sourceSnapshot: sources).ConfigureAwait(false); + sourceSnapshot: sources, + cancellationToken: cancellationToken + ).ConfigureAwait(false); if (!result.success) - throw new InvalidOperationException("Sample script preflight failed:" + Environment.NewLine - + string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Sample script preflight failed:" + Environment.NewLine + + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => diagnostic.message) + ) + ); + } }); while (!import.isValidationComplete) { @@ -104,24 +122,31 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory); ScriptCompilationResult result = m_compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); if (!result.success) - throw new InvalidOperationException("Project script compilation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Project script compilation failed:" + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); + } if (generateIdeProjects) + { m_compiler.GenerateProjectFiles(); + } cancellationToken.ThrowIfCancellationRequested(); string[] assemblies = result.moduleDeployments - .Where(static request => request.domain == Inno.Extensibility.Modules.AssemblyDomain.InnoScripting) - .SelectMany(static request => new[] { request.mainAssemblyPath } - .Concat(request.preloadAssemblyPaths)) + .Where(static request => request.domain == AssemblyDomain.InnoScripting) + .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); string destination = Path.GetFullPath(outputDirectory); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); using ProcessOwnedDirectory stagingOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string staging = stagingOwner.directory; try { @@ -131,7 +156,9 @@ CancellationToken cancellationToken File.Copy(assembly, Path.Combine(staging, Path.GetFileName(assembly))); string symbols = Path.ChangeExtension(assembly, ".pdb"); if (File.Exists(symbols)) + { File.Copy(symbols, Path.Combine(staging, Path.GetFileName(symbols))); + } } try { @@ -150,6 +177,31 @@ CancellationToken cancellationToken return destination; } + internal BuildProfile LoadGameProfile( + string? path, + BuildTargetID defaultTarget + ) { + if (!string.IsNullOrWhiteSpace(path)) + { + string profilePath = Path.GetFullPath(path, m_projectDirectory); + BuildProfile profile = new BuildProfileStore(profilePath, m_engine.serialization).Load(); + profile.applicationId = projectID.value; + return profile; + } + + BuildSettings defaults = BuildSettings.CreateDefault( + Path.GetFileName(Path.TrimEndingDirectorySeparator(m_projectDirectory)), + FindDefaultStartupScene(), + defaultTarget + ); + var settings = new BuildSettingsStore( + Path.Combine(m_projectDirectory, SettingsFileNames.C_BUILD), + m_engine.serialization, + defaults + ); + return settings.Load().CreateGameProfile(projectID); + } + internal static BuildWorkspace Open( string projectDirectory, string dotnetHost, @@ -161,7 +213,9 @@ CancellationToken cancellationToken string pluginsRoot = Path.Combine(projectRoot, "Plugins"); string libraryRoot = Path.Combine(projectRoot, "Library"); if (!Directory.Exists(assetsRoot)) + { throw new DirectoryNotFoundException($"Project Assets directory '{assetsRoot}' does not exist."); + } Directory.CreateDirectory(pluginsRoot); Directory.CreateDirectory(libraryRoot); @@ -172,14 +226,18 @@ CancellationToken cancellationToken try { engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildWorkspace).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildWorkspace).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var sources = new PluginSourceService(engine.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); AssetPipelineOptions options = AssetPipelineOptions.Create(assetsRoot, libraryRoot); - AssetSourceMount projectMount = options.sourceMounts!.Single(static mount => - mount.id == AssetSourceId.project); + AssetSourceMount projectMount = options.sourceMounts!.Single(static mount => ( + mount.id == AssetSourceID.project + )); assets = new AssetPipeline( engine.modules, engine.types, @@ -196,13 +254,15 @@ options with projectMount, .. PluginSourceService.GetActivatableMounts(scan) ] - }); + } + ); settings = new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.project))), + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.C_PROJECT))), engine.types, engine.serialization, - ProjectId.FromName(new DirectoryInfo(projectRoot).Name), - AssetSerializationContext.Create(assets)); + ProjectID.FromName(new DirectoryInfo(projectRoot).Name), + AssetSerializationContext.Create(assets) + ); plugins = new PluginEnvironment( assets, settings, @@ -210,13 +270,19 @@ .. PluginSourceService.GetActivatableMounts(scan) pluginsRoot, libraryRoot, scan, - engine.modules.generations); + engine.modules.generations + ); if (plugins.discovery.diagnostics.Count != 0 - || plugins.activePlugins.Count != scan.candidates.Count) - { - throw new InvalidOperationException("Installed Plugin activation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, plugins.discovery.diagnostics.Select(static diagnostic => - $"{diagnostic.sourcePath}: {diagnostic.message}"))); + || plugins.activePlugins.Count != scan.candidates.Count + ) { + throw new InvalidOperationException( + "Installed Plugin activation failed:" + Environment.NewLine + + string.Join( + Environment.NewLine, + plugins.discovery.diagnostics.Select(static diagnostic => + $"{diagnostic.sourcePath}: {diagnostic.message}") + ) + ); } var compiler = new ScriptCompiler( new ScriptCompilerOptions @@ -225,7 +291,8 @@ .. PluginSourceService.GetActivatableMounts(scan) compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); ActivateAuthoring(engine, plugins, compiler, Path.Combine(libraryRoot, "Build", "Metadata"), cancellationToken); engine.generations.Wait(); assets.CompleteExtensionDiscovery(); @@ -242,22 +309,36 @@ .. PluginSourceService.GetActivatableMounts(scan) } } + private string FindDefaultStartupScene() + { + foreach (AssetFileEntry entry in m_assets.GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.source == AssetSourceID.project) + .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) + .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) + ) { + if (m_assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) + { + return entry.assetPath.ToString(); + } + } + return string.Empty; + } + private static IModuleSource CreateScriptModuleSource( ScriptModuleDeployment deployment, string artifactRootDirectory - ) - => new DotNetModuleSource - { - artifactRootDirectory = artifactRootDirectory, - moduleName = deployment.moduleName, - mainAssemblyPath = deployment.mainAssemblyPath, - domain = deployment.domain, - scope = deployment.scope, - preloadAssemblyPaths = deployment.preloadAssemblyPaths, - upstreamModuleNames = deployment.upstreamModuleNames, - assemblyScopes = deployment.assemblyScopes, - collectible = true - }; + ) => new DotNetModuleSource + { + artifactRootDirectory = artifactRootDirectory, + moduleName = deployment.moduleName, + mainAssemblyPath = deployment.mainAssemblyPath, + domain = deployment.domain, + scope = deployment.scope, + preloadAssemblyPaths = deployment.preloadAssemblyPaths, + upstreamModuleNames = deployment.upstreamModuleNames, + assemblyScopes = deployment.assemblyScopes, + collectible = true + }; private static void ActivateAuthoring( EngineHost engine, @@ -268,60 +349,20 @@ CancellationToken cancellationToken ) { // Asset importers and graph extensions belong to the authoring generation, including in a // headless build. Compiling only Player scripts would export unresolved/last-good asset state. - ScriptCompilationResult result = compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken).GetAwaiter().GetResult(); + ScriptCompilationResult result = compiler + .CompileAuthoringGenerationAsync(cancellationToken: cancellationToken) + .GetAwaiter() + .GetResult(); if (!result.success) - throw new InvalidOperationException("Build authoring compilation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message))); - using Inno.Extensibility.Modules.AssemblyReloadSession reload = engine.modules.BeginReload( - result.moduleDeployments.Select(deployment => CreateScriptModuleSource(deployment, artifactRootDirectory)).ToArray()); - _ = engine.generations.Execute("Build authoring generation", reload, [plugins.CreateReloadChange()]); - } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - m_plugins.Dispose(); - m_assets.Dispose(); - m_settings.Dispose(); - m_engine.Dispose(); - } - - internal BuildProfile LoadGameProfile( - string? path, - BuildTargetId defaultTarget - ) { - if (!string.IsNullOrWhiteSpace(path)) { - string profilePath = Path.GetFullPath(path, m_projectDirectory); - BuildProfile profile = new BuildProfileStore(profilePath, m_engine.serialization).Load(); - profile.applicationId = projectId.value; - return profile; + throw new InvalidOperationException( + "Build authoring compilation failed:" + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); } - - BuildSettings defaults = BuildSettings.CreateDefault( - Path.GetFileName(Path.TrimEndingDirectorySeparator(m_projectDirectory)), - FindDefaultStartupScene(), - defaultTarget); - var settings = new BuildSettingsStore( - Path.Combine(m_projectDirectory, SettingsFileNames.build), - m_engine.serialization, - defaults); - return settings.Load().CreateGameProfile(projectId); - } - - private string FindDefaultStartupScene() - { - foreach (AssetFileEntry entry in m_assets.GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.source == AssetSourceId.project) - .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) - .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal)) - { - if (m_assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) - return entry.assetPath.ToString(); - } - return string.Empty; + using AssemblyReloadSession reload = engine.modules.BeginReload( + result.moduleDeployments.Select(deployment => CreateScriptModuleSource(deployment, artifactRootDirectory)).ToArray() + ); + _ = engine.generations.Execute("Build authoring generation", reload, [plugins.CreateReloadChange()]); } } - diff --git a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs index 317ba1efa..e4da9bd8c 100644 --- a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs +++ b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs @@ -12,8 +12,19 @@ internal static class ProductCleanExecutor internal static ValueTask AcquireAsync( BuildCommandContext context, CancellationToken cancellationToken - ) => FileLease.AcquireAsync(Path.Combine(context.root, "artifacts", "products", "editor", context.target.value, - context.configuration, "product.lock"), TimeSpan.FromSeconds(10), cancellationToken); + ) => FileLease.AcquireAsync( + Path.Combine( + context.root, + "artifacts", + "products", + "editor", + context.target.value, + context.configuration, + "product.lock" + ), + TimeSpan.FromSeconds(10), + cancellationToken + ); internal static void Execute( ProductCleanPlan plan, @@ -22,13 +33,17 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); foreach (string directory in plan.directories) + { PathBoundary.RequireUnlinkedPath(plan.root, directory); + } foreach (string directory in plan.directories) { cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine($"{(dryRun ? "Would clean" : "Cleaning")} {directory}"); if (!dryRun) + { ToolchainEnvironment.DeleteDirectory(directory); + } } } } diff --git a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs index db947ceb1..4e35b45c8 100644 --- a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs +++ b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Inno.Build.Composition; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -18,17 +19,26 @@ internal static async Task CreateAsync( string project, CancellationToken cancellationToken ) { - var projects = new List { project }; - foreach (var platform in context.distribution.platforms) + List projects = [project]; + foreach (BuildPlatformContribution platform in context.distribution.platforms) + { if (platform.descriptor.id == context.target && platform.editorProject is not null) + { projects.Add(Path.GetFullPath(platform.editorProject, context.root)); - var directories = new List(); + } + } + List directories = []; foreach (string selected in projects) { string result = await ToolchainEnvironment.CaptureOutputAsync( context.composition.dotnetHost, - ["msbuild", selected, "-nologo", "-getProperty:TargetDir,IntermediateOutputPath", - "-p:Configuration=" + context.configuration], + [ + "msbuild", + selected, + "-nologo", + "-getProperty:TargetDir,IntermediateOutputPath", + "-p:Configuration=" + context.configuration + ], context.root, cancellationToken, DotNetSdkEnvironment.Create(context.composition.dotnetHost) @@ -52,8 +62,10 @@ string output string path = Path.GetFullPath(output, owner).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); string relative = Path.GetRelativePath(root, path); if (Path.IsPathRooted(relative) || relative == "." || relative == ".." - || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { throw new InvalidOperationException($"The selected product output is outside its '{category}' owner: '{path}'."); + } return PathBoundary.RequireUnlinkedPath(root, path); } } diff --git a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs index 537e41cd9..ab53f6c89 100644 --- a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs @@ -26,30 +26,46 @@ CancellationToken cancellationToken ) { string root = request.root; string configuration = request.configuration; - BuildTargetId target = request.target; - BuildTargetId toolsTarget = request.toolsTarget; + BuildTargetID target = request.target; + BuildTargetID toolsTarget = request.toolsTarget; BuildCompositionContext context = request.composition; BuildDistribution distribution = request.distribution; - string productId = options.Read("product", "editor"); - ProductNativeBuildPlan product = distribution.ResolveNativeProduct(target.value, productId).plan; + string productID = options.Read("product", "editor"); + ProductNativeBuildPlan product = distribution.ResolveNativeProduct(target.value, productID).plan; if (request.nativeDependencies.Length != 0) { - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(root, - request.nativeDependencies, target.value, configuration.ToLowerInvariant(), product, cancellationToken).ConfigureAwait(false); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + root, + request.nativeDependencies, + target.value, + configuration.ToLowerInvariant(), + product, + cancellationToken + ).ConfigureAwait(false); return; } - NativeBuildContext bindings = new(root, configuration.ToLowerInvariant()); + var bindings = new NativeBuildContext(root, configuration.ToLowerInvariant()); bindings = bindings.WithBindingGenerator(distribution.ResolveBindingGenerator(target.value)); - bindings = bindings.WithToolchain(await distribution.ResolveNativeToolchain(target.value) - .ResolveAsync(bindings, context.host, target.value, cancellationToken).ConfigureAwait(false)); - var generation = new NativeBindingGenerationRequest(product.steps.Select(static step => step.component) - .Where(static owner => owner.bindingDefinition is not null).DistinctBy(static owner => owner.nativeProject), - target.value, NativeBindingOutputMode.TargetArtifacts, componentOptions: product.steps + bindings = bindings.WithToolchain( + await distribution.ResolveNativeToolchain(target.value) + .ResolveAsync(bindings, context.host, target.value, cancellationToken) + .ConfigureAwait(false) + ); + var generation = new NativeBindingGenerationRequest( + product.steps.Select(static step => step.component) + .Where(static owner => owner.bindingDefinition is not null) + .DistinctBy(static owner => owner.nativeProject), + target.value, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: product.steps .Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)); - using NativeBindingGenerationResult completed = await distribution.ResolveBindingGenerator(target.value).GenerateAsync(bindings, generation, cancellationToken).ConfigureAwait(false); - + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ); + using NativeBindingGenerationResult completed = await distribution + .ResolveBindingGenerator(target.value) + .GenerateAsync(bindings, generation, cancellationToken) + .ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs index 28ce259b5..53ed27edf 100644 --- a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -22,9 +23,11 @@ CancellationToken cancellationToken return; } if (scope != "product") + { throw new ArgumentException($"Unsupported cleanup scope '{scope}'."); + } string project = await context.PreflightEditorAsync(cancellationToken).ConfigureAwait(false); - using var ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); ProductCleanExecutor.Execute(plan, options.Has("dry-run"), cancellationToken); } @@ -33,23 +36,44 @@ internal static async Task CleanCachesAsync( BuildCommandContext context, BuildCommandLine options, bool automatic, - CancellationToken cancellation + CancellationToken cancellationToken ) { long ReadBytes( string name, long fallback ) { string? value = options.Has(name) ? options.Require(name) : null; - return value is null ? fallback : checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * 1024 * 1024 * 1024); + return value is null + ? fallback + : checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * 1024 * 1024 * 1024); } - double seconds = double.Parse(options.Read("cache-time-seconds", automatic ? "5" : "600"), - NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); - var policy = new BuildCachePolicy(ReadBytes("cache-budget-gib", 64L << 30), ReadBytes("cache-min-free-gib", 20L << 30), - TimeSpan.FromSeconds(seconds)); + double seconds = double.Parse( + options.Read("cache-time-seconds", automatic ? "5" : "600"), + NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture + ); + var policy = new BuildCachePolicy( + ReadBytes("cache-budget-gib", 64L << 30), + ReadBytes("cache-min-free-gib", 20L << 30), + TimeSpan.FromSeconds(seconds) + ); if (!options.Has("dry-run")) - StandardBuildCaches.CreateOwners(context.root, context.distribution.platforms.SelectMany(static platform => platform.nativeProducts.Values) - .SelectMany(static product => product.plan.steps).Select(static step => step.component).ToArray()); - await BuildMaintenanceApplication.CleanAsync(context.root, policy, !automatic, options.Has("dry-run"), - !automatic && options.Has("target") ? options.Require("target") : null, cancellation).ConfigureAwait(false); + { + StandardBuildCaches.CreateOwners( + context.root, + context.distribution.platforms.SelectMany(static platform => platform.nativeProducts.Values) + .SelectMany(static product => product.plan.steps) + .Select(static step => step.component) + .ToArray() + ); + } + await BuildMaintenanceApplication.CleanAsync( + context.root, + policy, + !automatic, + options.Has("dry-run"), + !automatic && options.Has("target") ? options.Require("target") : null, + cancellationToken + ).ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs index 0c0e8bb11..e0362e9c1 100644 --- a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs @@ -1,6 +1,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -12,13 +13,18 @@ internal static async Task RunAsync( CancellationToken cancellationToken ) { string project = await context.PreflightEditorAsync(cancellationToken).ConfigureAwait(false); - using var ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); if (options.Has("clean")) { ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); ProductCleanExecutor.Execute(plan, false, cancellationToken); } - await ToolchainEnvironment.RunAsync(context.composition.dotnetHost, ["build", ..context.ProductArguments(project), "-p:InnoSuppressBuildMaintenance=true"], - context.root, cancellationToken, DotNetSdkEnvironment.Create(context.composition.dotnetHost)).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + context.composition.dotnetHost, + ["build", ..context.ProductArguments(project), "-p:InnoSuppressBuildMaintenance=true"], + context.root, + cancellationToken, + DotNetSdkEnvironment.Create(context.composition.dotnetHost) + ).ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs index 37d3a792d..4aa99ae29 100644 --- a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs @@ -1,44 +1,56 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Text.Json; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; + internal static class NativeDependenciesCommand { internal static async Task RunAsync( BuildCommandContext request, BuildCommandLine options, - CancellationToken cancellation + CancellationToken cancellationToken ) { string operation = options.Read("operation", "produce"); if (operation == "import-cache") { - await NativeArtifactTransfer.ImportAsync(request.root, options.Require("input"), cancellation).ConfigureAwait(false); + await NativeArtifactTransfer.ImportAsync(request.root, options.Require("input"), cancellationToken).ConfigureAwait(false); return; } if (operation == "export-cache") { - await NativeArtifactTransfer.ExportAsync(request.root, options.Require("output"), cancellation).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync( + request.root, + options.Require("output"), + cancellationToken: cancellationToken + ).ConfigureAwait(false); return; } if (operation == "describe") { - BuildPlatformContribution platform = request.distribution.platforms.SingleOrDefault(platform => platform.descriptor.id == request.target) + BuildPlatformContribution platform = request.distribution.platforms.SingleOrDefault( + platform => platform.descriptor.id == request.target + ) ?? throw new NotSupportedException("No native dependency platform is registered for '" + request.target + "'."); - Inno.Core.IO.AtomicFile.WriteAllBytes(options.Require("output"), System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new - { - target = platform.descriptor.id.value, - products = platform.nativeProducts.Keys.Order(StringComparer.Ordinal).ToArray() - })); + AtomicFile.WriteAllBytes( + options.Require("output"), + JsonSerializer.SerializeToUtf8Bytes(new + { + target = platform.descriptor.id.value, + products = platform.nativeProducts.Keys.Order(StringComparer.Ordinal).ToArray() + }) + ); return; } @@ -46,22 +58,48 @@ CancellationToken cancellation if (operation == "verify-bindings") { if (options.Read("native-dependencies", string.Empty).Length != 0) + { throw new ArgumentException("Producer binding verification cannot consume a prebuilt selection."); - var steps = product.plan.steps.Where(static step => step.component.bindingDefinition is not null) - .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal).ToArray(); + } + IGrouping[] steps = product.plan.steps + .Where(static step => step.component.bindingDefinition is not null) + .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) + .ToArray(); if (steps.Length == 0) + { return; - var generator = request.distribution.ResolveBindingGenerator(request.target.value); - var bindingContext = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator(generator); - bindingContext = bindingContext.WithToolchain(await request.distribution.ResolveNativeToolchain(request.target.value) - .ResolveAsync(bindingContext, request.composition.host, request.target.value, cancellation).ConfigureAwait(false)); + } + INativeBindingGenerator generator = request.distribution.ResolveBindingGenerator(request.target.value); + NativeBuildContext bindingContext = new NativeBuildContext( + request.root, + request.configuration.ToLowerInvariant() + ).WithBindingGenerator(generator); + bindingContext = bindingContext.WithToolchain( + await request.distribution.ResolveNativeToolchain(request.target.value) + .ResolveAsync(bindingContext, request.composition.host, request.target.value, cancellationToken) + .ConfigureAwait(false) + ); // Verify the exact target publications being released, with their product linkage/options. // Authored host descriptors contain the author's SDK paths and are not target package evidence. - var bindingRequest = new NativeBindingGenerationRequest(steps.Select(static group => group.First().component), - request.target.value, NativeBindingOutputMode.TargetArtifacts, checkOnly: true, - componentOptions: steps.ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)); - using NativeBindingGenerationResult verified = await generator.GenerateAsync(bindingContext, bindingRequest, cancellation).ConfigureAwait(false); - Console.WriteLine($"Verified target binding publications: {steps.Length}; native processes: {bindingContext.statistics.nativeProcesses}."); + var bindingRequest = new NativeBindingGenerationRequest( + steps.Select(static group => group.First().component), + request.target.value, + NativeBindingOutputMode.TargetArtifacts, + checkOnly: true, + componentOptions: steps.ToDictionary( + static group => group.Key, + static group => group.First().options, + StringComparer.Ordinal + ) + ); + using NativeBindingGenerationResult verified = await generator.GenerateAsync( + bindingContext, + bindingRequest, + cancellationToken + ).ConfigureAwait(false); + Console.WriteLine( + $"Verified target binding publications: {steps.Length}; native processes: {bindingContext.statistics.nativeProcesses}." + ); return; } @@ -70,47 +108,92 @@ CancellationToken cancellation string output = options.Require("output"); try { - var assets = await NativeDependencyManifest.SelectAsync(request.root, options.Require("native-dependencies"), - request.target.value, request.configuration.ToLowerInvariant(), product.plan, cancellation).ConfigureAwait(false); - byte[] result = operation == "select" ? JsonSerializer.SerializeToUtf8Bytes(assets) - : JsonSerializer.SerializeToUtf8Bytes(new { matched = true, assets }); - Inno.Core.IO.AtomicFile.WriteAllBytes(output, result); + IReadOnlyList assets = await NativeDependencyManifest.SelectAsync( + request.root, + options.Require("native-dependencies"), + request.target.value, + request.configuration.ToLowerInvariant(), + product.plan, + cancellationToken + ).ConfigureAwait(false); + byte[] result = operation == "select" + ? JsonSerializer.SerializeToUtf8Bytes(assets) + : JsonSerializer.SerializeToUtf8Bytes(new { matched = true, assets }); + AtomicFile.WriteAllBytes(output, result); } catch (InvalidDataException failure) when (operation == "evaluate") { - Inno.Core.IO.AtomicFile.WriteAllBytes(output, JsonSerializer.SerializeToUtf8Bytes(new { matched = false, reason = failure.Message })); + AtomicFile.WriteAllBytes( + output, + JsonSerializer.SerializeToUtf8Bytes(new { matched = false, reason = failure.Message }) + ); } return; } if (operation != "produce") + { throw new ArgumentException("Unknown native dependency operation: " + operation); + } if (options.Read("native-dependencies", string.Empty).Length != 0) + { throw new ArgumentException("Dependency production cannot consume a prebuilt selection."); - var phase = Stopwatch.StartNew(); - Console.WriteLine($"Native producer: {product.plan.productId}/{request.target.value}/{request.configuration}; resolving the explicit toolchain."); - var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator(request.distribution.ResolveBindingGenerator(request.target.value)); - context = context.WithToolchain(await request.distribution.ResolveNativeToolchain(request.target.value).ResolveAsync(context, request.composition.host, request.target.value, cancellation).ConfigureAwait(false)); + } + Stopwatch phase = Stopwatch.StartNew(); + Console.WriteLine( + $"Native producer: {product.plan.productID}/{request.target.value}/{request.configuration}; resolving the explicit toolchain." + ); + NativeBuildContext context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator( + request.distribution.ResolveBindingGenerator(request.target.value) + ); + context = context.WithToolchain( + await request.distribution + .ResolveNativeToolchain(request.target.value) + .ResolveAsync(context, request.composition.host, request.target.value, cancellationToken) + .ConfigureAwait(false) + ); Report("toolchain"); StandardBuildCaches.CreateOwners(request.root, product.plan.steps.Select(static step => step.component).ToArray()); - string identity = await ProductNativePreparation.FreezeAsync(context, product.plan, cancellation).ConfigureAwait(false); + string identity = await ProductNativePreparation.FreezeAsync(context, product.plan, cancellationToken).ConfigureAwait(false); Report("input-capture"); - using ProductNativeBuildResult products = await product.BuildAsync(context, cancellation).ConfigureAwait(false); + using ProductNativeBuildResult products = await product.BuildAsync(context, cancellationToken).ConfigureAwait(false); Report("production"); - if (identity != await ProductNativePreparation.FreezeAsync(context.BeginInputVerification("dependency-export"), product.plan, cancellation).ConfigureAwait(false)) + if (identity != await ProductNativePreparation.FreezeAsync( + context.BeginInputVerification("dependency-export"), + product.plan, + cancellationToken + ).ConfigureAwait(false) + ) { throw new InvalidOperationException("Native producer inputs changed before export."); + } Report("pre-export-verification"); - string selection = await NativeDependencyManifest.ExportAsync(context, product.plan, products, options.Require("output"), cancellation).ConfigureAwait(false); + string selection = await NativeDependencyManifest.ExportAsync( + context, + product.plan, + products, + options.Require("output"), + cancellationToken + ).ConfigureAwait(false); Report("export"); - if (identity != await ProductNativePreparation.FreezeAsync(context.BeginInputVerification("dependency-export-complete"), product.plan, cancellation).ConfigureAwait(false)) + if (identity != await ProductNativePreparation.FreezeAsync( + context.BeginInputVerification("dependency-export-complete"), + product.plan, + cancellationToken + ).ConfigureAwait(false) + ) { throw new InvalidOperationException("Native producer inputs changed during export."); + } Report("closing-verification"); Console.WriteLine("Native dependency selection: " + selection); Console.WriteLine($"Native processes: {context.statistics.nativeProcesses}; hashed bytes: {context.statistics.hashedBytes}."); void Report(string name) { - Console.WriteLine(FormattableString.Invariant($"Native producer phase={name} seconds={phase.Elapsed.TotalSeconds:F3} nativeProcesses={context.statistics.nativeProcesses} hashedBytes={context.statistics.hashedBytes}")); + Console.WriteLine( + FormattableString.Invariant( + $"Native producer phase={name} seconds={phase.Elapsed.TotalSeconds:F3} nativeProcesses={context.statistics.nativeProcesses} hashedBytes={context.statistics.hashedBytes}" + ) + ); phase.Restart(); } } diff --git a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs index 9653d10a6..c795e7707 100644 --- a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs @@ -26,35 +26,62 @@ CancellationToken cancellationToken ) { string root = request.root; string configuration = request.configuration; - BuildTargetId target = request.target; - BuildTargetId toolsTarget = request.toolsTarget; + BuildTargetID target = request.target; + BuildTargetID toolsTarget = request.toolsTarget; BuildCompositionContext context = request.composition; BuildDistribution distribution = request.distribution; BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(context).ResolveShaderTarget(target); if (!GraphicsApi.TryParse(options.Require("renderer"), out GraphicsApi renderer)) + { throw new ArgumentException("The shader platform or rendering API is invalid."); + } NativeBuildContext native = new NativeBuildContext(root, configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(toolsTarget.value)); if (request.nativeDependencies.Length == 0) - native = native.WithToolchain(await distribution.ResolveNativeToolchain(toolsTarget.value) - .ResolveAsync(native, context.host, toolsTarget.value, cancellationToken).ConfigureAwait(false)); + { + native = native.WithToolchain( + await distribution.ResolveNativeToolchain(toolsTarget.value) + .ResolveAsync(native, context.host, toolsTarget.value, cancellationToken) + .ConfigureAwait(false) + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(toolsTarget.value, "shader-tools"); using ProductNativeBuildResult products = request.nativeDependencies.Length == 0 - ? await contribution.BuildAsync(native, cancellationToken).ConfigureAwait(false) - : await NativeDependencyManifest.AcquireAsync(root, request.nativeDependencies, toolsTarget.value, - configuration.ToLowerInvariant(), contribution.plan, cancellationToken).ConfigureAwait(false); + ? await contribution.BuildAsync(native, cancellationToken).ConfigureAwait(false) + : await NativeDependencyManifest.AcquireAsync( + root, + request.nativeDependencies, + toolsTarget.value, + configuration.ToLowerInvariant(), + contribution.plan, + cancellationToken + ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary(static tool => tool, - tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() - + extension)); + Dictionary executables = Enum.GetValues().ToDictionary( + static tool => tool, + tool => product.files.Single(file => ( + Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + + extension + )) + ); string includes = Path.GetDirectoryName(product.files.Single(file => Path.GetFileName(file) == "bgfx_shader.sh"))!; ShaderBuildInputs inputs = ShaderBuildInputs.Capture(options.Require("assets"), cancellationToken); - using ProcessOwnedDirectory compilation = await StandardBuildCaches.CreateShaderWorkspaceAsync(root, cancellationToken).ConfigureAwait(false); - ShaderArtifactBuilder.Compile(inputs, compilation, options.Require("shader"), - platform, renderer, options.Require("output"), new ToolRunner(executables, includes, context.host.services.workspaces), cancellationToken); + using ProcessOwnedDirectory compilation = await StandardBuildCaches.CreateShaderWorkspaceAsync( + root, + cancellationToken + ).ConfigureAwait(false); + ShaderArtifactBuilder.Compile( + inputs, + compilation, + options.Require("shader"), + platform, + renderer, + options.Require("output"), + new ToolRunner(executables, includes, context.host.services.workspaces), + cancellationToken + ); return; - } } diff --git a/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs b/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs index de579e5f6..4f6b23168 100644 --- a/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs @@ -15,25 +15,36 @@ internal static async Task RunAsync( BuildCommandLine options, CancellationToken cancellationToken ) { - string productId = options.Read("product", "editor"); - if (productId is not ("editor" or "player")) + string productID = options.Read("product", "editor"); + if (productID is not ("editor" or "player")) + { throw new ArgumentException("Support preparation requires product 'editor' or 'player'."); - NativeProductContribution product = request.distribution.ResolveNativeProduct(request.target.value, productId); + } + NativeProductContribution product = request.distribution.ResolveNativeProduct(request.target.value, productID); if (request.nativeDependencies.Length != 0) { - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(request.root, - request.nativeDependencies, request.target.value, request.configuration.ToLowerInvariant(), product.plan, cancellationToken).ConfigureAwait(false); - Console.WriteLine($"Consumed {productId} support for {request.target}: {imported.Count} artifacts; native processes: 0."); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + request.root, + request.nativeDependencies, + request.target.value, + request.configuration.ToLowerInvariant(), + product.plan, + cancellationToken + ).ConfigureAwait(false); + Console.WriteLine($"Consumed {productID} support for {request.target}: {imported.Count} artifacts; native processes: 0."); return; } var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()); context = context.WithBindingGenerator(request.distribution.ResolveBindingGenerator(request.target.value)); NativeToolchainSelection toolchain = await request.distribution.ResolveNativeToolchain(request.target.value) - .ResolveAsync(context, request.composition.host, request.target.value, cancellationToken).ConfigureAwait(false); + .ResolveAsync(context, request.composition.host, request.target.value, cancellationToken) + .ConfigureAwait(false); context = context.WithToolchain(toolchain); StandardBuildCaches.CreateOwners(context.engineRoot, product.plan.steps.Select(static step => step.component).ToArray()); using ProductNativeBuildResult products = await product.BuildAsync(context, cancellationToken).ConfigureAwait(false); - Console.WriteLine($"Prepared {productId} support for {request.target}: {products.Count} artifacts."); - Console.WriteLine($"Native processes: {context.statistics.nativeProcesses}; binding generations: {context.statistics.bindingGenerations}."); + Console.WriteLine($"Prepared {productID} support for {request.target}: {products.Count} artifacts."); + Console.WriteLine( + $"Native processes: {context.statistics.nativeProcesses}; binding generations: {context.statistics.bindingGenerations}." + ); } } diff --git a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs index 848698798..a6d62c740 100644 --- a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.IO.Compression; -using Inno.Build.SupportPacks; -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Build.SupportPacks; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -16,8 +16,14 @@ internal static async Task RunAsync( CancellationToken cancellationToken ) { string output = options.Read("output", Path.Combine(context.root, "artifacts", "support-packs")); - using PlayerSupportPackPublication pack = await context.distribution.supportPacks.PublishAsync(context.root, output, context.target, - context.composition.dotnetHost, cancellationToken, context.nativeDependencies.Length == 0 ? null : context.nativeDependencies).ConfigureAwait(false); + using PlayerSupportPackPublication pack = await context.distribution.supportPacks.PublishAsync( + context.root, + output, + context.target, + context.composition.dotnetHost, + context.nativeDependencies.Length == 0 ? null : context.nativeDependencies, + cancellationToken + ).ConfigureAwait(false); string archive = options.Read("archive", string.Empty); if (archive.Length != 0) { @@ -38,11 +44,15 @@ CancellationToken cancellationToken finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } Console.WriteLine(pack.directory); foreach (string diagnostic in pack.diagnostics) + { Console.Error.WriteLine(diagnostic); + } } } diff --git a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs index a91f4400d..dbf6efe03 100644 --- a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs +++ b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs @@ -36,42 +36,78 @@ CancellationToken cancellationToken { NativeVerificationOptions options = NativeVerificationOptions.Parse(args); string repositoryRoot = options.engineRoot; - BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, - new BuildTargetId(options.target), options.dotnet); + BuildCompositionContext execution = StandardBuildEnvironment.Capture( + AppContext.BaseDirectory, + new BuildTargetID(options.target), + options.dotnet + ); BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; - BuildPlatformContribution platform = distribution.platforms.SingleOrDefault(platform => platform.descriptor.id.value == options.target) + BuildPlatformContribution platform = distribution.platforms.SingleOrDefault( + platform => platform.descriptor.id.value == options.target + ) ?? throw new NotSupportedException($"No publication target is registered for '{options.target}'."); if (platform.editorProject is null) - throw new NotSupportedException($"Native verification requires a registered Editor test host; '{options.target}' contributes no such runner."); + { + throw new NotSupportedException( + $"Native verification requires a registered Editor test host; '{options.target}' contributes no such runner." + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(options.target, "editor"); - var nativeContext = new NativeBuildContext(repositoryRoot, options.configuration.ToLowerInvariant()) + NativeBuildContext nativeContext = new NativeBuildContext(repositoryRoot, options.configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(options.target)); NativeToolchainSelection sdk = await distribution.ResolveNativeToolchain(options.target) - .ResolveAsync(nativeContext, execution.host, options.target, cancellationToken).ConfigureAwait(false); + .ResolveAsync(nativeContext, execution.host, options.target, cancellationToken) + .ConfigureAwait(false); nativeContext = nativeContext.WithToolchain(sdk); string testHost = ToolchainEnvironment.ResolveExecutable("pwsh"); string testEntry = Path.Combine(repositoryRoot, "tests", "Invoke-IsolatedTests.ps1"); if (!File.Exists(testEntry)) + { throw new FileNotFoundException("The common test execution entry is unavailable.", testEntry); + } IReadOnlyList bindingProjects = DiscoverBindingProjects(repositoryRoot, contribution.plan); ValidateInputs(bindingProjects); string target = options.target; string operationRoot = Path.Combine(repositoryRoot, "artifacts", "build-tools", "verification"); - BuildCacheOwnerCatalog.Register(repositoryRoot, operationRoot, "native-verification", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); - using ProcessOwnedDirectory operation = await ProcessOwnedDirectory.CreateAsync(operationRoot, cancellationToken).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register( + repositoryRoot, + operationRoot, + "native-verification", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); + using ProcessOwnedDirectory operation = await ProcessOwnedDirectory.CreateAsync( + operationRoot, + cancellationToken + ).ConfigureAwait(false); string artifactsPath = Path.Combine(operation.directory, "managed"); Console.WriteLine("[inno-bindings] Verify deterministic generation against the checked-in host sources."); foreach (string project in bindingProjects) { - await ToolchainEnvironment.RunAsync(options.dotnet, - ["build", project, - "--configuration", options.configuration, "-t:CheckBindings", + await ToolchainEnvironment.RunAsync( + options.dotnet, + [ + "build", + project, + "--configuration", + options.configuration, + "-t:CheckBindings", $"-p:InnoBindingDotnetHost={options.dotnet}", - "-p:InnoBindingTargetId=" + target, "-p:InnoBindingOutputMode=HostSource", - $"-p:InnoNativeTarget={target}", $"-p:InnoToolTarget={target}", - "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false", "--nologo"], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + "-p:InnoBindingTargetId=" + target, + "-p:InnoBindingOutputMode=HostSource", + $"-p:InnoNativeTarget={target}", + $"-p:InnoToolTarget={target}", + "--disable-build-servers", + "-m:1", + "-nr:false", + "-p:UseSharedCompilation=false", + "--nologo" + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ).ConfigureAwait(false); } AuditNativeImports(repositoryRoot); @@ -80,7 +116,8 @@ await ToolchainEnvironment.RunAsync(options.dotnet, await ToolchainEnvironment.RunAsync( options.dotnet, [ - "restore", Path.Combine(repositoryRoot, "InnoEngine.sln"), + "restore", + Path.Combine(repositoryRoot, "InnoEngine.sln"), "-p:Configuration=Source" + options.configuration, $"-p:InnoToolTarget={target}", $"-p:ArtifactsPath={artifactsPath}", @@ -89,29 +126,52 @@ await ToolchainEnvironment.RunAsync( "/nodeReuse:false", "--nologo" ], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ).ConfigureAwait(false); - var native = await BuildNativeDependenciesAsync(nativeContext, contribution, cancellationToken); + (ProductNativeBuildPlan plan, ProductNativeBuildResult products) native = await BuildNativeDependenciesAsync( + nativeContext, + contribution, + cancellationToken + ).ConfigureAwait(false); using ProductNativeBuildResult nativeOwnership = native.products; Console.WriteLine("[inno-bindings] Build the complete InnoEngine solution."); await ToolchainEnvironment.RunAsync( options.dotnet, [ - "build", Path.Combine(repositoryRoot, "InnoEngine.sln"), - "--configuration", "Source" + options.configuration, + "build", + Path.Combine(repositoryRoot, "InnoEngine.sln"), + "--configuration", + "Source" + options.configuration, "--no-restore", - "-m:1", "-nodeReuse:false", "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--disable-build-servers", $"-p:InnoToolTarget={target}", $"-p:ArtifactsPath={artifactsPath}", "-p:TreatWarningsAsErrors=true", "--nologo" ], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ).ConfigureAwait(false); IReadOnlyList testProjects = DiscoverTestProjects(repositoryRoot); - string testResults = await RunTestsAsync(repositoryRoot, options, testProjects, - native.products, native.plan, testHost, testEntry, artifactsPath, cancellationToken); + string testResults = await RunTestsAsync( + repositoryRoot, + options, + testProjects, + native.products, + native.plan, + testHost, + testEntry, + artifactsPath, + cancellationToken + ).ConfigureAwait(false); string reportPath = await WriteReportAsync( repositoryRoot, target, @@ -119,10 +179,12 @@ await ToolchainEnvironment.RunAsync( testProjects.Count, native.plan, testResults, - cancellationToken); + cancellationToken + ).ConfigureAwait(false); Console.WriteLine( $"[inno-bindings] Project binding diffs, native builds, solution build, import audit, " - + $"and {testProjects.Count} test projects passed."); + + $"and {testProjects.Count} test projects passed." + ); Console.WriteLine($"[inno-bindings] Acceptance report: {reportPath}"); successfulRoot = repositoryRoot; return 0; @@ -138,8 +200,14 @@ await ToolchainEnvironment.RunAsync( { try { - await BuildMaintenanceApplication.CleanAsync(successfulRoot, new BuildCachePolicy(), - false, false, null, CancellationToken.None).ConfigureAwait(false); + await BuildMaintenanceApplication.CleanAsync( + successfulRoot, + new BuildCachePolicy(), + false, + false, + null, + CancellationToken.None + ).ConfigureAwait(false); } catch (Exception failure) { @@ -155,7 +223,9 @@ private static void ValidateInputs(IReadOnlyList bindingProjects) { string definition = Path.Combine(Path.GetDirectoryName(project)!, "Bindings", "bindings.props"); if (!File.Exists(definition)) + { throw new FileNotFoundException("The sole component binding definition was not found.", definition); + } } } @@ -165,12 +235,17 @@ ProductNativeBuildPlan plan ) { string[] projects = plan.steps .Select(step => Path.GetFullPath(step.component.nativeProject, repositoryRoot)) - .Distinct(StringComparer.Ordinal).Where(File.Exists) - .Where(project => XDocument.Load(project).Descendants("BindGenGeneratedBindings") + .Distinct(StringComparer.Ordinal) + .Where(File.Exists) + .Where(project => XDocument.Load(project) + .Descendants("BindGenGeneratedBindings") .Any(static property => property.Value.Trim() == "true")) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (projects.Length == 0) + { throw new InvalidOperationException("No Native projects declare BindGenGeneratedBindings=true."); + } return projects; } @@ -178,14 +253,14 @@ private static void AuditNativeImports(string repositoryRoot) { const int C_MAX_REPORTED_VIOLATIONS = 50; string nativeRoot = Path.Combine(repositoryRoot, "backends"); - var violations = new List(); + List violations = []; foreach (string path in Directory.EnumerateFiles(nativeRoot, "*.cs", SearchOption.AllDirectories)) { string relativePath = Path.GetRelativePath(repositoryRoot, path).Replace('\\', '/'); if (relativePath.Contains("/Generated/", StringComparison.OrdinalIgnoreCase) || relativePath.Contains("/bin/", StringComparison.OrdinalIgnoreCase) - || relativePath.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) - { + || relativePath.Contains("/obj/", StringComparison.OrdinalIgnoreCase) + ) { continue; } @@ -194,7 +269,9 @@ private static void AuditNativeImports(string repositoryRoot) { lineNumber++; if (NativeImportPattern().IsMatch(line)) + { violations.Add($"{relativePath}:{lineNumber}:{line.Trim()}"); + } } } @@ -202,13 +279,14 @@ private static void AuditNativeImports(string repositoryRoot) { string[] reported = violations.Take(C_MAX_REPORTED_VIOLATIONS).ToArray(); string remainder = violations.Count > reported.Length - ? $"{Environment.NewLine}... and {violations.Count - reported.Length} more violation(s)." - : string.Empty; + ? $"{Environment.NewLine}... and {violations.Count - reported.Length} more violation(s)." + : string.Empty; throw new InvalidOperationException( "Hand-authored native imports remain outside generated binding roots:" + Environment.NewLine + string.Join(Environment.NewLine, reported) - + remainder); + + remainder + ); } Console.WriteLine("[inno-bindings] No hand-authored native imports exist outside generated binding roots."); @@ -226,20 +304,26 @@ CancellationToken cancellationToken private static IReadOnlyList DiscoverTestProjects(string repositoryRoot) { string nativeTestsRoot = Path.Combine(repositoryRoot, "backends"); - var projects = Directory.EnumerateFiles(nativeTestsRoot, "*.csproj", SearchOption.AllDirectories) - .Where(static path => Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Native.", StringComparison.Ordinal) + List projects = Directory.EnumerateFiles(nativeTestsRoot, "*.csproj", SearchOption.AllDirectories) + .Where(static path => ( + Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Native.", StringComparison.Ordinal) && path.Contains(Path.DirectorySeparatorChar + "tests" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - && !path.Split(Path.DirectorySeparatorChar).Any(static part => part is "bin" or "obj")) - .Order(StringComparer.Ordinal).ToList(); + && !path.Split(Path.DirectorySeparatorChar).Any(static part => part is "bin" or "obj") + )) + .Order(StringComparer.Ordinal) + .ToList(); projects.Add(Path.Combine(repositoryRoot, "tests", "text", "Inno.Text.Tests", "Inno.Text.Tests.csproj")); projects.Add(Path.Combine(repositoryRoot, "tests", "ui", "Inno.UI.Tests", "Inno.UI.Tests.csproj")); if (projects.Count == 0) + { throw new InvalidOperationException("No native binding test projects were discovered."); + } if (projects.Any(static project => !File.Exists(project))) { throw new FileNotFoundException( "A required native binding test project is missing.", - projects.First(static project => !File.Exists(project))); + projects.First(static project => !File.Exists(project)) + ); } return projects; } @@ -258,33 +342,71 @@ CancellationToken cancellationToken Console.WriteLine("[inno-bindings] Run every native binding, Text, and UI test project."); foreach (string project in testProjects) { - string output = (await ToolchainEnvironment.CaptureOutputAsync(options.dotnet, - ["msbuild", project, "-getProperty:TargetDir", $"-p:Configuration={options.configuration}", - $"-p:InnoToolTarget={options.target}", $"-p:ArtifactsPath={artifactsPath}"], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet))).Trim(); + string output = (await ToolchainEnvironment.CaptureOutputAsync( + options.dotnet, + [ + "msbuild", + project, + "-getProperty:TargetDir", + $"-p:Configuration={options.configuration}", + $"-p:InnoToolTarget={options.target}", + $"-p:ArtifactsPath={artifactsPath}" + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ).ConfigureAwait(false)).Trim(); if (!Path.IsPathFullyQualified(output)) + { throw new InvalidDataException("The test project did not declare an absolute target output directory."); - await ProductNativeDeployment.InstallAsync(nativeProducts, nativePlan, - output, cancellationToken) + } + await ProductNativeDeployment.InstallAsync(nativeProducts, nativePlan, output, cancellationToken) .ConfigureAwait(false); } - string results = Path.Combine(repositoryRoot, "artifacts", "acceptance", "native-bindings", - options.target, Guid.NewGuid().ToString("N")); + string results = Path.Combine( + repositoryRoot, + "artifacts", + "acceptance", + "native-bindings", + options.target, + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(results); string selection = Path.Combine(results, "Native.slnf"); - File.WriteAllText(selection, JsonSerializer.Serialize(new - { - solution = new + File.WriteAllText( + selection, + JsonSerializer.Serialize(new { - path = Path.Combine(repositoryRoot, "InnoEngine.sln"), - projects = testProjects.Select(project => Path.GetRelativePath(repositoryRoot, project)).ToArray() - } - })); - await ToolchainEnvironment.RunAsync(testHost, - ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", testEntry, - "-Configuration", "Source" + options.configuration, "-Dotnet", options.dotnet, - "-Solution", selection, "-ResultsDirectory", results, "-ArtifactsPath", artifactsPath], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + solution = new + { + path = Path.Combine(repositoryRoot, "InnoEngine.sln"), + projects = testProjects.Select(project => Path.GetRelativePath(repositoryRoot, project)).ToArray() + } + }) + ); + await ToolchainEnvironment.RunAsync( + testHost, + [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-File", + testEntry, + "-Configuration", + "Source" + options.configuration, + "-Dotnet", + options.dotnet, + "-Solution", + selection, + "-ResultsDirectory", + results, + "-ArtifactsPath", + artifactsPath + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ).ConfigureAwait(false); return Path.GetRelativePath(repositoryRoot, results).Replace('\\', '/'); } @@ -298,17 +420,26 @@ private static async Task WriteReportAsync( CancellationToken cancellationToken ) { string innoRevision = (await ToolchainEnvironment.CaptureOutputAsync( - "git", ["-C", repositoryRoot, "rev-parse", "HEAD"], repositoryRoot, cancellationToken)).Trim(); + "git", + ["-C", repositoryRoot, "rev-parse", "HEAD"], + repositoryRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); Assembly bindingImplementation = typeof(NativeBindingGenerator).Assembly; string packageVersion = bindingImplementation.GetCustomAttributes() .Single(static metadata => metadata.Key == "Inno.BindingPackageVersion").Value - ?? throw new InvalidDataException("The binding implementation has no frozen package version."); + ?? throw new InvalidDataException("The binding implementation has no frozen package version."); string implementationHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(bindingImplementation.Location))); - bool innoDirty = !string.IsNullOrWhiteSpace(await ToolchainEnvironment.CaptureOutputAsync( - "git", ["-C", repositoryRoot, "status", "--porcelain", "--untracked-files=all"], repositoryRoot, cancellationToken)); + bool innoDirty = !string.IsNullOrWhiteSpace( + await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["-C", repositoryRoot, "status", "--porcelain", "--untracked-files=all"], + repositoryRoot, + cancellationToken + ).ConfigureAwait(false) + ); DateTimeOffset generatedAt = DateTimeOffset.UtcNow; - string reportDirectory = Path.Combine( - repositoryRoot, "artifacts", "bindings", "acceptance", target); + string reportDirectory = Path.Combine(repositoryRoot, "artifacts", "bindings", "acceptance", target); Directory.CreateDirectory(reportDirectory); var report = new @@ -339,7 +470,8 @@ CancellationToken cancellationToken File.WriteAllText( jsonPath, JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }) + Environment.NewLine, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) + ); string markdown = $""" # InnoEngine generated-native-binding acceptance @@ -360,11 +492,11 @@ CancellationToken cancellationToken File.WriteAllText( Path.Combine(reportDirectory, "report.md"), markdown + Environment.NewLine, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) + ); return jsonPath; } [GeneratedRegex(@"\[(DllImport|LibraryImport)\b|partial\s+.*\bextern\b|static\s+extern\b")] private static partial Regex NativeImportPattern(); - } diff --git a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs index a9f21437e..7e31072e2 100644 --- a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs +++ b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs @@ -41,29 +41,42 @@ internal static NativeVerificationOptions Parse(IReadOnlyList args) { string argument = args[index]; if (!argument.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Unexpected argument '{argument}'.{Environment.NewLine}{usage}"); + } string key = argument[2..]; if (++index >= args.Count) + { throw new ArgumentException($"Argument '{argument}' requires a value."); + } if (!values.TryAdd(key, args[index])) + { throw new ArgumentException($"Argument '{argument}' was specified more than once."); + } } string selectedRoot = values.GetValueOrDefault("engine-root", string.Empty); string engineRoot = Path.GetFullPath(string.IsNullOrWhiteSpace(selectedRoot) ? ToolchainEnvironment.FindRepoRoot() : selectedRoot); string configuration = values.GetValueOrDefault("configuration", C_DEFAULT_CONFIGURATION); if (configuration is not ("Debug" or "Release")) + { throw new ArgumentException("--configuration must be either Debug or Release."); - string dotnet = ToolchainEnvironment.ResolveExecutable(values.GetValueOrDefault("dotnet") - ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); + } + string dotnet = ToolchainEnvironment.ResolveExecutable( + values.GetValueOrDefault("dotnet") + ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet" + ); if (!values.TryGetValue("target", out string? target) || string.IsNullOrWhiteSpace(target)) + { throw new ArgumentException("--target requires an explicit implemented native target."); + } string[] knownKeys = ["engine-root", "configuration", "dotnet", "target"]; string? unknownKey = values.Keys.FirstOrDefault(key => !knownKeys.Contains(key, StringComparer.Ordinal)); - if (unknownKey != null) + if (unknownKey is not null) + { throw new ArgumentException($"Unknown argument '--{unknownKey}'.{Environment.NewLine}{usage}"); + } return new NativeVerificationOptions(engineRoot, configuration, dotnet, target); } - } diff --git a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs index 2272c648c..170e10ca9 100644 --- a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs +++ b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -24,8 +25,14 @@ CancellationToken cancellationToken { try { - await BuildMaintenanceApplication.CleanAsync(engineRoot, new BuildCachePolicy(), - false, false, null, cancellationToken).ConfigureAwait(false); + await BuildMaintenanceApplication.CleanAsync( + engineRoot, + new BuildCachePolicy(), + false, + false, + null, + cancellationToken + ).ConfigureAwait(false); } catch (Exception failure) { @@ -44,19 +51,32 @@ CancellationToken cancellationToken { string dotnet = StandardBuildEnvironment.ResolveManagedHost(command.dotnetHost); using BuildWorkspace authoring = BuildWorkspace.Open(command.projectDirectory, dotnet, cancellationToken); - Console.WriteLine(command.kind == BuildCommandKind.Scripts + Console.WriteLine( + command.kind == BuildCommandKind.Scripts ? authoring.ExportProjectScripts(command.outputDirectory, command.generateIdeProjects, cancellationToken) - : authoring.ImportSample(command.sampleSource, cancellationToken).ToString()); + : authoring.ImportSample(command.sampleSource, cancellationToken).ToString() + ); return 0; } string application = Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!; - BuildCompositionContext context = StandardBuildEnvironment.Capture(application, command.toolsTarget, command.dotnetHost, - string.IsNullOrWhiteSpace(command.nativeDependencies) ? null : Path.GetFullPath(command.nativeDependencies, engineRoot)); - using ProductNativeBuildResult products = await BuildComposition.PrepareNativeAsync(context, engineRoot, cancellationToken, command.nativeDependencies).ConfigureAwait(false); + BuildCompositionContext context = StandardBuildEnvironment.Capture( + application, + command.toolsTarget, + command.dotnetHost, + string.IsNullOrWhiteSpace(command.nativeDependencies) ? null : Path.GetFullPath(command.nativeDependencies, engineRoot) + ); + using ProductNativeBuildResult products = await BuildComposition.PrepareNativeAsync( + context, + engineRoot, + cancellationToken, + command.nativeDependencies + ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary(static tool => tool, - tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + extension)); + Dictionary executables = Enum.GetValues().ToDictionary( + static tool => tool, + tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + extension) + ); string includes = Path.GetDirectoryName(product.files.Single(file => Path.GetFileName(file) == "bgfx_shader.sh"))!; var tools = new ToolRunner(executables, includes, context.host.services.workspaces); using BuildWorkspace workspace = BuildWorkspace.Open(command.projectDirectory, context.dotnetHost, cancellationToken); @@ -68,24 +88,36 @@ CancellationToken cancellationToken GameBuildRequest request = command.CreateGameRequest(workspace.LoadGameProfile(command.profilePath, command.gameTarget)); // The command-line host has no UI scheduler. Keep the authoring owner on this thread // while preparing external tools, then capture its build snapshot before the first await. - using PlayerSupportPackLease prepared = pipeline.EnsurePlayerSupportPackAsync( - request.profile.target, request.profile.managedDeployment, cancellationToken) - .GetAwaiter().GetResult(); - result = await pipeline.BuildGameAsync(request, progress, cancellationToken); + using PlayerSupportPackLease prepared = pipeline + .EnsurePlayerSupportPackAsync( + request.profile.target, + request.profile.managedDeployment, + cancellationToken + ) + .GetAwaiter() + .GetResult(); + result = await pipeline.BuildGameAsync(request, progress, cancellationToken).ConfigureAwait(false); } else if (command.kind == BuildCommandKind.Plugin) { result = await pipeline.BuildPluginAsync( - command.CreatePluginRequest(workspace.projectId), progress, cancellationToken); + command.CreatePluginRequest(workspace.projectID), + progress, + cancellationToken + ).ConfigureAwait(false); } else { throw new InvalidOperationException("Unknown project build kind."); } foreach (BuildDiagnostic diagnostic in result.diagnostics) + { Console.Error.WriteLine($"{diagnostic.severity} {diagnostic.code}: {diagnostic.message}"); + } if (!result.succeeded) + { return 1; + } Console.WriteLine(result.outputPath); return 0; } diff --git a/build/composition/Inno.Build.Composition/BuildCompositionContext.cs b/build/composition/Inno.Build.Composition/BuildCompositionContext.cs index 55d2b20c1..24df083cb 100644 --- a/build/composition/Inno.Build.Composition/BuildCompositionContext.cs +++ b/build/composition/Inno.Build.Composition/BuildCompositionContext.cs @@ -34,18 +34,24 @@ public BuildCompositionContext( string dotnetHost, string applicationDirectory, BuildHostDescriptor host, - BuildTargetId toolsTarget, + BuildTargetID toolsTarget, string? nativeDependencies = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); ArgumentNullException.ThrowIfNull(host); if (string.IsNullOrWhiteSpace(toolsTarget.value)) + { throw new ArgumentException("A build composition must declare its executable native tools target.", nameof(toolsTarget)); + } if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("The build host requires an absolute application directory.", nameof(applicationDirectory)); + } if (nativeDependencies is not null && !Path.IsPathFullyQualified(nativeDependencies)) + { throw new ArgumentException("A native dependency selection must be absolute.", nameof(nativeDependencies)); + } this.dotnetHost = dotnetHost; this.applicationDirectory = Path.GetFullPath(applicationDirectory); this.host = host; @@ -71,11 +77,10 @@ public BuildCompositionContext( /// /// Gets the independently declared native target of build tools executed by this host. /// - public BuildTargetId toolsTarget { get; } + public BuildTargetID toolsTarget { get; } /// /// Gets the explicit consume-only selection propagated to product and Support Pack preparation. /// public string? nativeDependencies { get; } - } diff --git a/build/composition/Inno.Build.Composition/BuildDistribution.cs b/build/composition/Inno.Build.Composition/BuildDistribution.cs index 21db89648..304e7ea87 100644 --- a/build/composition/Inno.Build.Composition/BuildDistribution.cs +++ b/build/composition/Inno.Build.Composition/BuildDistribution.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using Inno.Assets.Pipeline; @@ -20,7 +21,7 @@ public sealed class BuildDistribution private readonly GameBuildContribution[] m_games; private readonly BuildPlatformContribution[] m_platforms; private readonly IReadOnlyList m_platformSnapshot; - private readonly HashSet m_targetIds; + private readonly HashSet m_targetIDs; private readonly IReadOnlyDictionary> m_nativeProducts; private readonly IReadOnlyDictionary m_nativeToolchains; @@ -50,40 +51,63 @@ public BuildDistribution( ArgumentNullException.ThrowIfNull(games); ArgumentNullException.ThrowIfNull(managedCompilers); if (games.Count == 0 || games.Any(static contribution => contribution is null)) + { throw new ArgumentException("A distribution requires complete platform contributions.", nameof(games)); + } m_games = games.ToArray(); m_platforms = m_games.Select(static game => game.platform).ToArray(); m_platformSnapshot = Array.AsReadOnly(m_platforms); foreach (BuildPlatformContribution platform in m_platforms) + { if (platform.bindingGenerator is not null) + { m_bindingGenerators.Add(platform.descriptor.id.value, platform.bindingGenerator); - m_targetIds = m_platforms.Select(static contribution => contribution.descriptor.id).ToHashSet(); - if (m_targetIds.Count != m_platforms.Length) + } + } + m_targetIDs = m_platforms.Select(static contribution => contribution.descriptor.id).ToHashSet(); + if (m_targetIDs.Count != m_platforms.Length) + { throw new ArgumentException("Platform target identities must be unique.", nameof(games)); - var native = m_platforms.ToDictionary(static platform => platform.descriptor.id.value, - static platform => platform.toolchainProvider, StringComparer.Ordinal); - var products = m_platforms.ToDictionary(static platform => platform.descriptor.id.value, - static platform => platform.nativeProducts, StringComparer.Ordinal); + } + Dictionary native = m_platforms.ToDictionary( + static platform => platform.descriptor.id.value, + static platform => platform.toolchainProvider, + StringComparer.Ordinal + ); + Dictionary> products = m_platforms.ToDictionary( + static platform => platform.descriptor.id.value, + static platform => platform.nativeProducts, + StringComparer.Ordinal + ); foreach (NativeToolchainContribution contribution in nativeOnlyContributions ?? []) { if (contribution is null || !native.TryAdd(contribution.descriptor.id.value, contribution.provider)) - throw new ArgumentException("Native SDK contributions must be complete and have unique target identities.", nameof(nativeOnlyContributions)); + { + throw new ArgumentException( + "Native SDK contributions must be complete and have unique target identities.", + nameof(nativeOnlyContributions) + ); + } products.Add(contribution.descriptor.id.value, contribution.nativeProducts); if (contribution.bindingGenerator is not null) + { m_bindingGenerators.Add(contribution.descriptor.id.value, contribution.bindingGenerator); + } } - m_nativeProducts = new System.Collections.ObjectModel.ReadOnlyDictionary>(products); - m_nativeToolchains = new System.Collections.ObjectModel.ReadOnlyDictionary(native); - availableTargets = Array.AsReadOnly(m_targetIds.OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); - managedDeployments = new ManagedDeploymentCatalog(managedCompilers); - supportPacks = new PlayerSupportPackPublisher(m_platforms.Select(static contribution => contribution.supportPackSource).ToArray()); + m_nativeToolchains = new ReadOnlyDictionary(native); + this.availableTargets = Array.AsReadOnly(m_targetIDs.OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); + this.managedDeployments = new ManagedDeploymentCatalog(managedCompilers); + this.supportPacks = new PlayerSupportPackPublisher( + m_platforms.Select(static contribution => contribution.supportPackSource).ToArray() + ); } /// /// Gets the immutable platform identities shared by all hosts. /// - public IReadOnlyList availableTargets { get; } + public IReadOnlyList availableTargets { get; } /// /// Gets complete platform registrations in their explicit composition order. @@ -103,7 +127,7 @@ public BuildDistribution( /// /// Resolves the generator explicitly registered by a target integration. /// - /// + /// /// The requested native target. /// /// @@ -112,14 +136,15 @@ public BuildDistribution( /// /// The target contributes no binding generator. /// - public INativeBindingGenerator ResolveBindingGenerator(string targetId) - => m_bindingGenerators.TryGetValue(targetId, out INativeBindingGenerator? generator) ? generator - : throw new NotSupportedException($"No binding generator is registered for '{targetId}'."); + public INativeBindingGenerator ResolveBindingGenerator(string targetID) + => m_bindingGenerators.TryGetValue(targetID, out INativeBindingGenerator? generator) + ? generator + : throw new NotSupportedException($"No binding generator is registered for '{targetID}'."); /// /// Resolves the SDK integration bound to an explicitly registered publication target. /// - /// + /// /// The requested native target identity, independently selected from the execution host. /// /// @@ -128,19 +153,21 @@ public INativeBindingGenerator ResolveBindingGenerator(string targetId) /// /// No native toolchain contribution is registered for the target. /// - public INativeToolchainProvider ResolveNativeToolchain(string targetId) + public INativeToolchainProvider ResolveNativeToolchain(string targetID) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - if (m_nativeToolchains.TryGetValue(targetId, out INativeToolchainProvider? provider)) + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + if (m_nativeToolchains.TryGetValue(targetID, out INativeToolchainProvider? provider)) + { return provider; - throw new NotSupportedException($"No native toolchain is registered for target '{targetId}'."); + } + throw new NotSupportedException($"No native toolchain is registered for target '{targetID}'."); } /// /// Checks whether this distribution contributes an SDK for an explicitly requested binding target. /// A standalone binding definition may describe a target without registering a product publisher. /// - /// + /// /// The exact target identity; no host-derived target is substituted. /// /// @@ -153,20 +180,20 @@ public INativeToolchainProvider ResolveNativeToolchain(string targetId) /// The target identity is empty. /// public bool TryResolveNativeToolchain( - string targetId, + string targetID, [NotNullWhen(true)] out INativeToolchainProvider? provider ) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - return m_nativeToolchains.TryGetValue(targetId, out provider); + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + return m_nativeToolchains.TryGetValue(targetID, out provider); } /// /// Resolves a platform-contributed product closure without selecting backends inside the invoking host. /// - /// + /// /// The explicit registered product target. /// - /// + /// /// The product whose ordinary native build is requested. /// /// @@ -179,15 +206,17 @@ public bool TryResolveNativeToolchain( /// A target or product identity is empty. /// public NativeProductContribution ResolveNativeProduct( - string targetId, - string productId + string targetID, + string productID ) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - ArgumentException.ThrowIfNullOrWhiteSpace(productId); - if (m_nativeProducts.TryGetValue(targetId, out IReadOnlyDictionary? products) - && products.TryGetValue(productId, out NativeProductContribution? plan)) + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + ArgumentException.ThrowIfNullOrWhiteSpace(productID); + if (m_nativeProducts.TryGetValue(targetID, out IReadOnlyDictionary? products) + && products.TryGetValue(productID, out NativeProductContribution? plan) + ) { return plan; - throw new NotSupportedException($"No ordinary native build is registered for product '{productId}' on target '{targetId}'."); + } + throw new NotSupportedException($"No ordinary native build is registered for product '{productID}' on target '{targetID}'."); } /// @@ -218,18 +247,20 @@ TypeCatalog types ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(types); var targets = new GameBuildTargetBinding[m_games.Length]; - var identities = new HashSet(); + var identities = new HashSet(); for (int index = 0; index < targets.Length; index++) { BuildPlatformContribution platform = m_platforms[index]; IGameBuildTarget target = platform.factory() - ?? throw new InvalidOperationException("A build target factory returned no target."); + ?? throw new InvalidOperationException("A build target factory returned no target."); if (target.id != platform.descriptor.id || target.runtimeIdentifier != platform.descriptor.runtimeIdentifier - || !identities.Add(target.id)) + || !identities.Add(target.id) + ) { throw new InvalidOperationException($"Build target '{target.id}' does not match its bound platform description."); + } managedDeployments.Resolve(target.defaultManagedDeployment, target.runtimeIdentifier); IGameContentCompiler compiler = m_games[index].compilerFactory(assets, serialization, types) - ?? throw new InvalidOperationException("A content compiler factory returned no compiler."); + ?? throw new InvalidOperationException("A content compiler factory returned no compiler."); targets[index] = new GameBuildTargetBinding(target, compiler); } return Array.AsReadOnly(targets); @@ -249,11 +280,13 @@ TypeCatalog types /// public void ValidateDeployment( IGameBuildTarget target, - ManagedDeploymentId deployment + ManagedDeploymentID deployment ) { ArgumentNullException.ThrowIfNull(target); - if (!m_targetIds.Contains(target.id)) + if (!m_targetIDs.Contains(target.id)) + { throw new InvalidOperationException($"Build target '{target.id}' is not registered in this distribution."); + } managedDeployments.Resolve(deployment, target.runtimeIdentifier); } } diff --git a/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs b/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs index e67cdf25e..603bbf4e4 100644 --- a/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs +++ b/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs @@ -1,8 +1,8 @@ using System; using Inno.Assets.Pipeline; using Inno.Build.SupportPacks; -using Inno.Core.Settings; using Inno.Core.Logging; +using Inno.Core.Settings; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; @@ -59,11 +59,22 @@ string supportPackRoot ArgumentNullException.ThrowIfNull(engine); Logger logger = engine.logs.CreateLogger(); return new BuildPipeline( - assets, plugins, settings, engine.serialization, engine.generations, compiler, supportPackRoot, + assets, + plugins, + settings, + engine.serialization, + engine.generations, + compiler, + supportPackRoot, distribution.CreateBindings(assets, engine.serialization, engine.types), distribution.managedDeployments, SourcePlayerSupportPackProvisioner.TryCreateForHost( - context.applicationDirectory, distribution.supportPacks, context.dotnetHost, - diagnostic => logger.Write(LogLevel.Warn, diagnostic), context.nativeDependencies)); + context.applicationDirectory, + distribution.supportPacks, + context.dotnetHost, + diagnostic => logger.Write(LogLevel.Warn, diagnostic), + context.nativeDependencies + ) + ); } } diff --git a/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs b/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs index 1e2816912..af87cd698 100644 --- a/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs +++ b/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs @@ -55,20 +55,24 @@ public BuildPlatformContribution( string? editorProject = null, IReadOnlyList? nativeProducts = null, INativeBindingGenerator? bindingGenerator = null, - IReadOnlyList? managedDeployments = null + IReadOnlyList? managedDeployments = null ) { ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(supportPackSource); ArgumentNullException.ThrowIfNull(toolchainProvider); if (descriptor.id != supportPackSource.target) + { throw new ArgumentException("A platform source must match its declared target.", nameof(supportPackSource)); + } string? editor = editorProject?.Replace('\\', '/'); if (descriptor.supportsEditor != (editor is not null) || editor is not null && (editor.StartsWith('/') || editor.Contains(':') - || !editor.EndsWith(".csproj", StringComparison.Ordinal) - || editor.Split('/').Any(static segment => segment is "" or "." or ".."))) + || !editor.EndsWith(".csproj", StringComparison.Ordinal) + || editor.Split('/').Any(static segment => segment is "" or "." or "..")) + ) { throw new ArgumentException("Editor capability requires one explicit contained product project.", nameof(editorProject)); + } this.descriptor = descriptor; this.bindingGenerator = bindingGenerator; this.factory = factory; @@ -77,13 +81,22 @@ public BuildPlatformContribution( this.editorProject = editor; var products = new Dictionary(StringComparer.Ordinal); foreach (NativeProductContribution product in nativeProducts ?? []) - if (product is null || !products.TryAdd(product.plan.productId, product)) - throw new ArgumentException("Native product plans must be complete and have unique product identities.", nameof(nativeProducts)); + { + if (product is null || !products.TryAdd(product.plan.productID, product)) + { + throw new ArgumentException( + "Native product plans must be complete and have unique product identities.", + nameof(nativeProducts) + ); + } + } this.nativeProducts = new ReadOnlyDictionary(products); - ManagedDeploymentId[] deployments = (managedDeployments ?? []).ToArray(); + ManagedDeploymentID[] deployments = (managedDeployments ?? []).ToArray(); if (deployments.Any(static id => string.IsNullOrWhiteSpace(id.value)) - || deployments.Distinct().Count() != deployments.Length) + || deployments.Distinct().Count() != deployments.Length + ) { throw new ArgumentException("Platform deployment identities must be assigned and unique.", nameof(managedDeployments)); + } this.managedDeployments = Array.AsReadOnly(deployments); } @@ -116,6 +129,7 @@ public BuildPlatformContribution( /// Gets the frozen ordinary product-build closures explicitly contributed by this target. /// public IReadOnlyDictionary nativeProducts { get; } + /// /// Gets the target-owned generator, or null when no binding capability is registered. /// @@ -124,6 +138,5 @@ public BuildPlatformContribution( /// /// Gets the deployment identities this platform authorizes for its declared managed runtime target. /// - public IReadOnlyList managedDeployments { get; } - + public IReadOnlyList managedDeployments { get; } } diff --git a/build/composition/Inno.Build.Composition/NativeProductContribution.cs b/build/composition/Inno.Build.Composition/NativeProductContribution.cs index b6368b358..5025db297 100644 --- a/build/composition/Inno.Build.Composition/NativeProductContribution.cs +++ b/build/composition/Inno.Build.Composition/NativeProductContribution.cs @@ -23,14 +23,17 @@ public NativeProductContribution( ProductNativeBuildPlan plan, INativeProductExecutor executor ) { - this.plan = plan ?? throw new ArgumentNullException(nameof(plan)); - this.executor = executor ?? throw new ArgumentNullException(nameof(executor)); + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(executor); + this.plan = plan; + this.executor = executor; } /// /// Gets the immutable product graph. /// public ProductNativeBuildPlan plan { get; } + /// /// Gets the platform-selected executor. /// diff --git a/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs b/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs index 0dd609006..8ad3d08a8 100644 --- a/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs +++ b/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs @@ -42,9 +42,12 @@ public NativeToolchainContribution( this.provider = provider; nativeProducts ??= []; if (nativeProducts.Any(static plan => plan is null)) + { throw new ArgumentException("Native product contributions cannot be null.", nameof(nativeProducts)); + } this.nativeProducts = new ReadOnlyDictionary( - nativeProducts.ToDictionary(static product => product.plan.productId, StringComparer.Ordinal)); + nativeProducts.ToDictionary(static product => product.plan.productID, StringComparer.Ordinal) + ); } /// @@ -56,6 +59,7 @@ public NativeToolchainContribution( /// Gets the registered SDK boundary; registration does not start tools or inspect the environment. /// public INativeToolchainProvider provider { get; } + /// /// Gets explicitly implemented native-only product closures keyed by stable product identity. /// @@ -65,5 +69,4 @@ public NativeToolchainContribution( /// Gets the target-owned generator, or null when no binding capability is registered. /// public INativeBindingGenerator? bindingGenerator { get; } - } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs index 4072dc246..912f76dea 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Distribution.Standard; @@ -42,9 +42,17 @@ public static ValueTask CreateShaderWorkspaceAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); if (!Path.IsPathFullyQualified(engineRoot)) + { throw new ArgumentException("Shader workspaces require an absolute checkout root.", nameof(engineRoot)); + } string root = Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"); - BuildCacheOwnerCatalog.Register(engineRoot, root, "shader-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + engineRoot, + root, + "shader-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); return ProcessOwnedDirectory.CreateAsync(root, cancellationToken); } @@ -71,30 +79,116 @@ IReadOnlyList components ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); ArgumentNullException.ThrowIfNull(components); if (!Path.IsPathFullyQualified(engineRoot)) - throw new ArgumentException("Cache registration requires an absolute checkout.", nameof(engineRoot)); - var owners = new List { - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact), "native"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact), "bindings"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "support-packs"), BuildCacheArtifactRole.ImmutableArtifact), "support-packs"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"), BuildCacheArtifactRole.ProcessWorkingDirectory), "shader-requests"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "managed", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "managed-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators"), BuildCacheArtifactRole.ImmutableArtifact), "managed-evaluators"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"), BuildCacheArtifactRole.ProcessWorkingDirectory), "managed-input-requests"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "extensions"), BuildCacheArtifactRole.ImmutableArtifact), "binding-extensions"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "intermediate"), BuildCacheArtifactRole.ReusableWorkspace), "binding-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "bgcs-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "hosts"), BuildCacheArtifactRole.ImmutableArtifact), "task-hosts"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "loads"), BuildCacheArtifactRole.ProcessWorkingDirectory), "task-loads"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "publishers"), BuildCacheArtifactRole.ProcessWorkingDirectory), "task-publishers"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "task-workspaces") - }; + throw new ArgumentException("Cache registration requires an absolute checkout.", nameof(engineRoot)); + } + List owners = + [ + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact), + "native" + ), + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact), + "bindings" + ), + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "support-packs"), BuildCacheArtifactRole.ImmutableArtifact), + "support-packs" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "shader-requests" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "managed", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "managed-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "managed-evaluators" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "managed-input-requests" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "extensions"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "binding-extensions" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "intermediate"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "binding-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "bgcs-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "hosts"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "task-hosts" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "loads"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "task-loads" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "publishers"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "task-publishers" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "task-workspaces" + ) + ]; NativeComponentDescriptor[] workspaceComponents = components.ToArray(); - foreach (string project in workspaceComponents.Select(static component => component.toolchainProject).Distinct(StringComparer.Ordinal)) - { + foreach (string project in workspaceComponents + .Select(static component => component.toolchainProject) + .Distinct(StringComparer.Ordinal) + ) { NativeComponentDescriptor component = workspaceComponents.First(value => value.toolchainProject == project); - owners.Add(Describe(new BuildCachePublisher(Path.Combine(component.GetToolchainRoot(engineRoot), "obj", "native"), BuildCacheArtifactRole.ReusableWorkspace), - "workspace:" + project)); + owners.Add( + Describe( + new BuildCachePublisher( + Path.Combine(component.GetToolchainRoot(engineRoot), "obj", "native"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "workspace:" + project + ) + ); } return owners.AsReadOnly(); diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs index 53edd6fda..3cde6d95d 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs @@ -22,11 +22,11 @@ namespace Inno.Build.Distribution.Standard; /// public sealed class StandardBuildDistribution { - private readonly IReadOnlyDictionary m_shaders; + private readonly IReadOnlyDictionary m_shaders; private StandardBuildDistribution( BuildDistribution build, - IReadOnlyDictionary shaders + IReadOnlyDictionary shaders ) { this.build = build; m_shaders = shaders; @@ -37,6 +37,23 @@ IReadOnlyDictionary shaders /// public BuildDistribution build { get; } + /// + /// Resolves explicitly registered shader configuration independently of tool execution target. + /// + /// + /// The artifact's actual publication target. + /// + /// + /// The borrowed immutable configuration; unavailable targets fail before native preparation. + /// + /// + /// The distribution has no shader configuration for this target. + /// + public BgfxShaderTargetProfile ResolveShaderTarget(BuildTargetID target) + => m_shaders.TryGetValue(target, out BgfxShaderTargetProfile? profile) + ? profile + : throw new NotSupportedException($"No shader configuration is registered for '{target}'."); + /// /// Composes one explicit binding per implemented platform without resolving tools. /// @@ -57,38 +74,57 @@ public static StandardBuildDistribution Create( tools ??= new ToolRunner(context.host.services.workspaces); (BuildPlatformContribution platform, BgfxShaderTargetProfile shaders, GameContentCompilerFactory compiler)[] bindings = [ - (WindowsX64BuildIntegration.Create(context), WindowsX64BgfxIntegration.shaderProfile, WindowsX64BgfxIntegration.CreateContentCompilerFactory(tools)), - (MacOSArm64BuildIntegration.Create(context), MacOSArm64BgfxIntegration.shaderProfile, MacOSArm64BgfxIntegration.CreateContentCompilerFactory(tools)), - (BrowserWasm32BuildIntegration.Create(context), BrowserWasm32BgfxIntegration.shaderProfile, BrowserWasm32BgfxIntegration.CreateContentCompilerFactory(tools)) + (WindowsX64BuildIntegration.Create( + context + ), WindowsX64BgfxIntegration.shaderProfile, WindowsX64BgfxIntegration.CreateContentCompilerFactory(tools)), + (MacOSArm64BuildIntegration.Create( + context + ), MacOSArm64BgfxIntegration.shaderProfile, MacOSArm64BgfxIntegration.CreateContentCompilerFactory(tools)), + (BrowserWasm32BuildIntegration.Create( + context + ), BrowserWasm32BgfxIntegration.shaderProfile, BrowserWasm32BgfxIntegration.CreateContentCompilerFactory(tools)) ]; foreach ((BuildPlatformContribution platform, BgfxShaderTargetProfile shaders, GameContentCompilerFactory _) in bindings) + { if (platform.descriptor.id.value != shaders.id) + { throw new InvalidOperationException("Platform publication and shader target identities disagree."); - string[] Runtimes(ManagedDeploymentId deployment) => bindings - .Where(binding => binding.platform.managedDeployments.Contains(deployment)) - .Select(static binding => binding.platform.descriptor.runtimeIdentifier).Distinct(StringComparer.Ordinal).ToArray(); - var build = new BuildDistribution(bindings.Select(static binding => new GameBuildContribution(binding.platform, binding.compiler)).ToArray(), - [new CoreClrDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.coreClr), context.host.services.workspaces), - new MonoWasmDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.monoWasm), context.host.services.workspaces, aheadOfTime: false), - new MonoWasmDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.monoWasmAot), context.host.services.workspaces, aheadOfTime: true), - new NativeAotDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.nativeAot), context.host.services.workspaces)]); - return new(build, new ReadOnlyDictionary( - bindings.ToDictionary(static binding => binding.platform.descriptor.id, static binding => binding.shaders))); + } + } + string[] Runtimes(ManagedDeploymentID deployment) + => bindings + .Where(binding => binding.platform.managedDeployments.Contains(deployment)) + .Select(static binding => binding.platform.descriptor.runtimeIdentifier) + .Distinct(StringComparer.Ordinal) + .ToArray(); + var build = new BuildDistribution( + bindings.Select(static binding => new GameBuildContribution(binding.platform, binding.compiler)).ToArray(), + [ + new CoreClrDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentID.coreClr), context.host.services.workspaces), + new MonoWasmDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentID.monoWasm), + context.host.services.workspaces, + aheadOfTime: false + ), + new MonoWasmDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentID.monoWasmAot), + context.host.services.workspaces, + aheadOfTime: true + ), + new NativeAotDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentID.nativeAot), + context.host.services.workspaces + ) + ] + ); + return new( + build, + new ReadOnlyDictionary( + bindings.ToDictionary(static binding => binding.platform.descriptor.id, static binding => binding.shaders) + ) + ); } - - /// - /// Resolves explicitly registered shader configuration independently of tool execution target. - /// - /// - /// The artifact's actual publication target. - /// - /// - /// The borrowed immutable configuration; unavailable targets fail before native preparation. - /// - /// - /// The distribution has no shader configuration for this target. - /// - public BgfxShaderTargetProfile ResolveShaderTarget(BuildTargetId target) - => m_shaders.TryGetValue(target, out BgfxShaderTargetProfile? profile) ? profile - : throw new NotSupportedException($"No shader configuration is registered for '{target}'."); } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs index 67626a513..8885f174e 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs @@ -38,7 +38,7 @@ public static class StandardBuildEnvironment /// public static BuildCompositionContext Capture( string applicationDirectory, - BuildTargetId toolsTarget, + BuildTargetID toolsTarget, string? dotnetHost = null, string? nativeDependencies = null ) { @@ -66,7 +66,7 @@ public static BuildCompositionContext Capture( public static string ResolveManagedHost(string? dotnetHost = null) { string host = dotnetHost ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? CurrentRuntimeHost("dotnet" + StandardBuildHosts.Capture().services.executableExtension); + ?? CurrentRuntimeHost("dotnet" + StandardBuildHosts.Capture().services.executableExtension); return ToolchainEnvironment.ResolveExecutable(host); } @@ -79,7 +79,9 @@ private static string CurrentRuntimeHost(string executable) { string runtimeHost = Path.Combine(installation.FullName, executable); if (File.Exists(runtimeHost)) + { return runtimeHost; + } } return executable; } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs index 547a0706b..fc570d7cb 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs @@ -23,8 +23,12 @@ public static BuildHostDescriptor Capture() { IBuildHostProvider[] providers = [new WindowsBuildHostProvider(), new MacOSArm64BuildHostProvider()]; foreach (IBuildHostProvider provider in providers) + { if (provider.TryCapture() is BuildHostDescriptor host) + { return host; + } + } throw new PlatformNotSupportedException("No registered build host supports this machine."); } } diff --git a/build/managed/Inno.Build.Managed/IManagedDeploymentCompiler.cs b/build/managed/Inno.Build.Managed/IManagedDeploymentCompiler.cs index 6d36a3425..d0ea1ea37 100644 --- a/build/managed/Inno.Build.Managed/IManagedDeploymentCompiler.cs +++ b/build/managed/Inno.Build.Managed/IManagedDeploymentCompiler.cs @@ -11,7 +11,7 @@ public interface IManagedDeploymentCompiler /// /// Gets the open stable implementation identity. /// - ManagedDeploymentId id { get; } + ManagedDeploymentID id { get; } /// /// Gets the provider's actual target and execution capabilities. diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs index a6be9c514..f21021c82 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs @@ -32,8 +32,10 @@ bool nativeStaticLinking ) { ArgumentNullException.ThrowIfNull(runtimeIdentifiers); if (runtimeIdentifiers.Count == 0 || runtimeIdentifiers.Any(string.IsNullOrWhiteSpace) - || runtimeIdentifiers.Distinct(StringComparer.Ordinal).Count() != runtimeIdentifiers.Count) + || runtimeIdentifiers.Distinct(StringComparer.Ordinal).Count() != runtimeIdentifiers.Count + ) { throw new ArgumentException("A managed provider requires unique runtime targets.", nameof(runtimeIdentifiers)); + } this.runtimeIdentifiers = Array.AsReadOnly(runtimeIdentifiers.ToArray()); this.dynamicCode = dynamicCode; this.aheadOfTime = aheadOfTime; diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs index 7cccc8e93..51b3134b2 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs @@ -9,7 +9,7 @@ namespace Inno.Build.Managed; /// public sealed class ManagedDeploymentCatalog { - private readonly IReadOnlyDictionary m_compilers; + private readonly IReadOnlyDictionary m_compilers; /// /// Copies providers and rejects ambiguous identities before any publication starts. @@ -23,19 +23,26 @@ public sealed class ManagedDeploymentCatalog public ManagedDeploymentCatalog(IReadOnlyList compilers) { ArgumentNullException.ThrowIfNull(compilers); - if (compilers.Count == 0 || compilers.Any(static compiler => compiler is null - || string.IsNullOrWhiteSpace(compiler.id.value)) - || compilers.Select(static compiler => compiler.id).Distinct().Count() != compilers.Count) + if (compilers.Count == 0 || compilers.Any(static compiler => ( + compiler is null + || string.IsNullOrWhiteSpace(compiler.id.value) + )) + || compilers.Select(static compiler => compiler.id).Distinct().Count() != compilers.Count + ) { throw new ArgumentException("Managed providers require unique valid identities.", nameof(compilers)); + } m_compilers = compilers.ToDictionary(static compiler => compiler.id); - availableDeployments = Array.AsReadOnly(compilers.Select(static compiler => compiler.id) - .OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); + this.availableDeployments = Array.AsReadOnly( + compilers.Select(static compiler => compiler.id) + .OrderBy(static id => id.value, StringComparer.Ordinal) + .ToArray() + ); } /// /// Gets the immutable provider identities in stable order. /// - public IReadOnlyList availableDeployments { get; } + public IReadOnlyList availableDeployments { get; } /// /// Returns the registered deployment identities that support one managed target. @@ -46,9 +53,11 @@ public ManagedDeploymentCatalog(IReadOnlyList compil /// /// A new immutable list in stable identity order; unsupported targets produce an empty list. /// - public IReadOnlyList GetSupportedDeployments(string runtimeIdentifier) - => Array.AsReadOnly(availableDeployments.Where(id => - m_compilers[id].capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)).ToArray()); + public IReadOnlyList GetSupportedDeployments(string runtimeIdentifier) + => Array.AsReadOnly( + availableDeployments.Where(id => + m_compilers[id].capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)).ToArray() + ); /// /// Resolves a provider and verifies target support before staging begins. @@ -66,13 +75,17 @@ public IReadOnlyList GetSupportedDeployments(string runtime /// No provider is registered, or the selected provider cannot publish the requested target. /// public IManagedDeploymentCompiler Resolve( - ManagedDeploymentId deployment, + ManagedDeploymentID deployment, string runtimeIdentifier ) { if (!m_compilers.TryGetValue(deployment, out IManagedDeploymentCompiler? compiler)) + { throw new InvalidOperationException($"Managed deployment '{deployment}' is not registered."); + } if (!compiler.capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)) + { throw new InvalidOperationException($"Managed deployment '{deployment}' does not support '{runtimeIdentifier}'."); + } return compiler; } } diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentID.cs similarity index 77% rename from build/managed/Inno.Build.Managed/ManagedDeploymentId.cs rename to build/managed/Inno.Build.Managed/ManagedDeploymentID.cs index c37350b42..95df5ea32 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentID.cs @@ -5,28 +5,8 @@ namespace Inno.Build.Managed; /// /// Identifies an open managed deployment implementation independently of the publication platform. /// -public readonly record struct ManagedDeploymentId +public readonly record struct ManagedDeploymentID { - /// - /// Identifies the desktop CoreCLR publisher. - /// - public static ManagedDeploymentId coreClr { get; } = new("coreclr"); - - /// - /// Identifies the Mono WebAssembly interpreter publisher. - /// - public static ManagedDeploymentId monoWasm { get; } = new("mono-wasm"); - - /// - /// Identifies the Mono WebAssembly ahead-of-time publisher. - /// - public static ManagedDeploymentId monoWasmAot { get; } = new("mono-wasm-aot"); - - /// - /// Identifies the .NET NativeAOT publisher. - /// - public static ManagedDeploymentId nativeAot { get; } = new("nativeaot"); - /// /// Validates a stable portable provider identity. /// @@ -36,20 +16,44 @@ public readonly record struct ManagedDeploymentId /// /// The identity is empty or contains nonportable characters. /// - public ManagedDeploymentId(string value) + public ManagedDeploymentID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (!(character is >= 'a' and <= 'z' or >= '0' and <= '9' or '-')) + { throw new ArgumentException("Managed deployment IDs require lowercase portable characters.", nameof(value)); + } + } this.value = value; } + /// + /// Identifies the desktop CoreCLR publisher. + /// + public static ManagedDeploymentID coreClr { get; } = new("coreclr"); + + /// + /// Identifies the Mono WebAssembly interpreter publisher. + /// + public static ManagedDeploymentID monoWasm { get; } = new("mono-wasm"); + + /// + /// Identifies the Mono WebAssembly ahead-of-time publisher. + /// + public static ManagedDeploymentID monoWasmAot { get; } = new("mono-wasm-aot"); + + /// + /// Identifies the .NET NativeAOT publisher. + /// + public static ManagedDeploymentID nativeAot { get; } = new("nativeaot"); + /// /// Gets the exact stable provider identity. /// public string value { get; } - /// + /// public override string ToString() => value ?? string.Empty; } diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs index c7c899b21..279a945a1 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs @@ -26,7 +26,7 @@ public sealed class ManagedDeploymentResult /// The nonempty set of relative output file paths, copied before returning to the pipeline. /// public ManagedDeploymentResult( - ManagedDeploymentId deployment, + ManagedDeploymentID deployment, string outputDirectory, string sdkIdentity, IReadOnlyList files @@ -35,10 +35,14 @@ IReadOnlyList files ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory); ArgumentException.ThrowIfNullOrWhiteSpace(sdkIdentity); ArgumentNullException.ThrowIfNull(files); - if (files.Count == 0 || files.Any(static file => string.IsNullOrWhiteSpace(file) - || Path.IsPathRooted(file) || file.Split('/', '\\').Any(static segment => segment is "." or "..")) - || files.Distinct(StringComparer.Ordinal).Count() != files.Count) + if (files.Count == 0 || files.Any(static file => ( + string.IsNullOrWhiteSpace(file) + || Path.IsPathRooted(file) || file.Split('/', '\\').Any(static segment => segment is "." or "..") + )) + || files.Distinct(StringComparer.Ordinal).Count() != files.Count + ) { throw new ArgumentException("Managed output requires unique relative artifact paths.", nameof(files)); + } this.deployment = deployment; this.outputDirectory = Path.GetFullPath(outputDirectory); this.sdkIdentity = sdkIdentity; @@ -48,7 +52,7 @@ IReadOnlyList files /// /// Gets the managed compiler identity that produced this publication. /// - public ManagedDeploymentId deployment { get; } + public ManagedDeploymentID deployment { get; } /// /// Gets the completed build-owned publication directory. diff --git a/build/pipeline/Inno.Build/BuildDiagnostic.cs b/build/pipeline/Inno.Build/BuildDiagnostic.cs index 72338f61c..a7d065c9e 100644 --- a/build/pipeline/Inno.Build/BuildDiagnostic.cs +++ b/build/pipeline/Inno.Build/BuildDiagnostic.cs @@ -2,27 +2,6 @@ namespace Inno.Build; -/// -/// Identifies the severity of one structured build diagnostic. -/// -public enum BuildDiagnosticSeverity -{ - /// - /// Provides non-failing build context. - /// - Information, - - /// - /// Reports a condition that did not prevent output creation. - /// - Warning, - - /// - /// Reports a condition that prevented a valid build. - /// - Error -} - /// /// Describes one stable machine-readable build problem or informational event. /// @@ -70,3 +49,22 @@ string message /// public string message { get; } } + +/// +/// Identifies the severity of one structured build diagnostic. +/// +public enum BuildDiagnosticSeverity +{ + /// + /// Provides non-failing build context. + /// + Information, + /// + /// Reports a condition that did not prevent output creation. + /// + Warning, + /// + /// Reports a condition that prevented a valid build. + /// + Error +} diff --git a/build/pipeline/Inno.Build/BuildPipeline.cs b/build/pipeline/Inno.Build/BuildPipeline.cs index 8804bd9d5..5a197c9d9 100644 --- a/build/pipeline/Inno.Build/BuildPipeline.cs +++ b/build/pipeline/Inno.Build/BuildPipeline.cs @@ -1,6 +1,4 @@ using System; -using Inno.Build.Managed; -using Inno.Extensibility.Reload; using System.Collections.Generic; using System.IO; using System.Linq; @@ -8,9 +6,11 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build.Managed; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Reload; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; namespace Inno.Build; @@ -20,8 +20,8 @@ namespace Inno.Build; /// public sealed class BuildPipeline { - private readonly IReadOnlyList m_availableGameTargets; - private readonly IReadOnlyDictionary m_gameTargets; + private readonly IReadOnlyList m_availableGameTargets; + private readonly IReadOnlyDictionary m_gameTargets; private readonly GameBuildPipeline m_game; private readonly PluginPackageBuilder m_plugins; private readonly PlayerSupportPackCatalog m_supportPacks; @@ -32,15 +32,9 @@ public sealed class BuildPipeline /// /// Creates a build pipeline from installed Player Support Packs and platform packagers. /// - /// - /// The directory containing one child directory per . - /// /// /// The active authoring asset pipeline captured by builds. /// - /// - /// The host-wide admission gate that remains pinned until the build snapshot is released. - /// /// /// The active Plugin environment captured by builds. /// @@ -50,9 +44,15 @@ public sealed class BuildPipeline /// /// The serialization registry used to pin and encode the build snapshot. /// + /// + /// The host-wide admission gate that remains pinned until the build snapshot is released. + /// /// /// The project compiler used to produce a fresh runtime-only assembly generation for each game build. /// + /// + /// The directory containing one child directory per . + /// /// /// The complete set of replaceable platform package implementations available to this host. /// @@ -81,7 +81,8 @@ public BuildPipeline( ArgumentNullException.ThrowIfNull(plugins); ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(serialization); - m_generations = generations ?? throw new ArgumentNullException(nameof(generations)); + ArgumentNullException.ThrowIfNull(generations); + m_generations = generations; ArgumentNullException.ThrowIfNull(compiler); ArgumentException.ThrowIfNullOrWhiteSpace(supportPackRoot); ArgumentNullException.ThrowIfNull(gameTargets); @@ -89,22 +90,34 @@ public BuildPipeline( m_managedDeployments = managedDeployments; GameBuildTargetBinding[] targets = gameTargets.ToArray(); if (targets.Any(static value => value is null)) + { throw new ArgumentException("Game target collection cannot contain null values.", nameof(gameTargets)); + } if (targets.Length == 0) + { throw new ArgumentException("At least one game build target is required.", nameof(gameTargets)); + } if (targets.Any(static value => string.IsNullOrWhiteSpace(value.packager.id.value))) + { throw new ArgumentException("Every game build target requires a valid identity.", nameof(gameTargets)); + } if (targets.Any(static value => string.IsNullOrWhiteSpace(value.packager.displayName))) + { throw new ArgumentException("Every game build target requires a display name.", nameof(gameTargets)); - IGrouping? duplicate = targets + } + IGrouping? duplicate = targets .GroupBy(static value => value.packager.id) .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) + { throw new ArgumentException($"Game target '{duplicate.Key}' is registered more than once.", nameof(gameTargets)); - m_availableGameTargets = Array.AsReadOnly(targets - .Select(static target => target.packager.id) - .OrderBy(static id => id.value, StringComparer.Ordinal) - .ToArray()); + } + m_availableGameTargets = Array.AsReadOnly( + targets + .Select(static target => target.packager.id) + .OrderBy(static id => id.value, StringComparer.Ordinal) + .ToArray() + ); m_gameTargets = targets.ToDictionary(static value => value.packager.id); m_supportPacks = new PlayerSupportPackCatalog(supportPackRoot); m_supportPackProvisioner = supportPackProvisioner; @@ -116,18 +129,15 @@ public BuildPipeline( compiler, m_gameTargets, m_supportPacks, - managedDeployments); - m_plugins = new PluginPackageBuilder( - assets, - plugins, - settings, - serialization); + managedDeployments + ); + m_plugins = new PluginPackageBuilder(assets, plugins, settings, serialization); } /// /// Gets an immutable view of every registered build target in stable identity order. /// - public IReadOnlyList availableGameTargets => m_availableGameTargets; + public IReadOnlyList availableGameTargets => m_availableGameTargets; /// /// Gets the managed deployment choices supported by a registered publication platform. @@ -141,10 +151,10 @@ public BuildPipeline( /// /// The publication target is not registered in this build composition. /// - public IReadOnlyList GetManagedDeployments(BuildTargetId target) + public IReadOnlyList GetManagedDeployments(BuildTargetID target) => m_gameTargets.TryGetValue(target, out GameBuildTargetBinding? gameTarget) - ? m_managedDeployments.GetSupportedDeployments(gameTarget.packager.runtimeIdentifier) - : throw new ArgumentException($"Game target '{target}' is not registered.", nameof(target)); + ? m_managedDeployments.GetSupportedDeployments(gameTarget.packager.runtimeIdentifier) + : throw new ArgumentException($"Game target '{target}' is not registered.", nameof(target)); /// /// Tries to get the adapter-owned display name for a registered game target. @@ -159,7 +169,7 @@ public IReadOnlyList GetManagedDeployments(BuildTargetId ta /// when the target is registered; otherwise, . /// public bool TryGetGameTargetDisplayName( - BuildTargetId target, + BuildTargetID target, out string displayName ) { if (m_gameTargets.TryGetValue(target, out GameBuildTargetBinding? gameTarget)) @@ -201,28 +211,28 @@ out string displayName /// An installed or newly published Pack fails deployment validation. /// public async ValueTask EnsurePlayerSupportPackAsync( - BuildTargetId target, - ManagedDeploymentId? deployment, + BuildTargetID target, + ManagedDeploymentID? deployment, CancellationToken cancellationToken = default ) { if (!m_gameTargets.TryGetValue(target, out GameBuildTargetBinding? binding)) + { throw new NotSupportedException($"Game target '{target}' is not registered."); + } IGameBuildTarget packager = binding.packager; _ = m_managedDeployments.Resolve(deployment ?? packager.defaultManagedDeployment, packager.runtimeIdentifier); cancellationToken.ThrowIfCancellationRequested(); return await m_supportPacks.ResolveOrProvisionAsync( - target, packager, m_supportPackProvisioner, cancellationToken).ConfigureAwait(false); + target, + packager, + m_supportPackProvisioner, + cancellationToken + ).ConfigureAwait(false); } /// /// Builds and installs one complete source-free game deployment with rollback protection. /// - /// - /// Prepare current packs with EnsurePlayerSupportPackAsync before invoking this method on the - /// authoring owner's thread. The synchronous snapshot phase never waits for asynchronous provisioning. - /// Coordinate readers and writers of the output directory during its two installation moves. - /// Post-commit backup, staging and progress observer failures are warnings on the successful result. - /// /// /// The exact profile, destination, and activated runtime compilation generation. /// @@ -250,6 +260,12 @@ public async ValueTask EnsurePlayerSupportPackAsync( /// /// Output installation and restoration both fail; the previous tree remains at the reported backup path. /// + /// + /// Prepare current packs with EnsurePlayerSupportPackAsync before invoking this method on the + /// authoring owner's thread. The synchronous snapshot phase never waits for asynchronous provisioning. + /// Coordinate readers and writers of the output directory during its two installation moves. + /// Post-commit backup, staging and progress observer failures are warnings on the successful result. + /// public async ValueTask BuildGameAsync( GameBuildRequest request, IProgress? progress = null, diff --git a/build/pipeline/Inno.Build/BuildProfile.cs b/build/pipeline/Inno.Build/BuildProfile.cs index ae399d299..087876fc2 100644 --- a/build/pipeline/Inno.Build/BuildProfile.cs +++ b/build/pipeline/Inno.Build/BuildProfile.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; - -using Inno.Core.Serialization; using Inno.Build.Managed; +using Inno.Core.Serialization; namespace Inno.Build; @@ -14,7 +13,7 @@ namespace Inno.Build; [GenerateSerializationConverter] public sealed class BuildProfile : ISerializable { - private static readonly HashSet S_WINDOWS_RESERVED_NAMES = new(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet WINDOWS_RESERVED_NAMES = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", @@ -49,7 +48,7 @@ public sealed class BuildProfile : ISerializable /// /// Gets or sets the platform target. /// - public BuildTargetId target + public BuildTargetID target { get => new(m_targetId); set => m_targetId = value.value; @@ -58,9 +57,9 @@ public BuildTargetId target /// /// Gets or sets an explicit managed publisher; null uses the platform composition's default. /// - public ManagedDeploymentId? managedDeployment + public ManagedDeploymentID? managedDeployment { - get => m_managedDeploymentId.Length == 0 ? null : new ManagedDeploymentId(m_managedDeploymentId); + get => m_managedDeploymentId.Length == 0 ? null : new ManagedDeploymentID(m_managedDeploymentId); set => m_managedDeploymentId = value?.value ?? string.Empty; } @@ -88,7 +87,8 @@ public ManagedDeploymentId? managedDeployment /// /// A newly owned profile with the same current-format scalar settings and stable selections. /// - public BuildProfile Copy() => new() + public BuildProfile Copy() + => new() { applicationId = applicationId, productName = productName, @@ -109,66 +109,87 @@ public ManagedDeploymentId? managedDeployment public void Validate() { if (!IsPortableIdentifier(applicationId)) + { throw new InvalidDataException("Application ID must be a stable lowercase portable identifier."); + } if (!IsPortableProductName(productName)) + { throw new InvalidDataException("Product name must be a portable file name."); - if (persistentDataPath is null || - !IsPortableDataPath(persistentDataPath.Length == 0 ? applicationId : persistentDataPath)) + } + if (persistentDataPath is null + || !IsPortableDataPath(persistentDataPath.Length == 0 ? applicationId : persistentDataPath) + ) { throw new InvalidDataException("Persistent data path must contain only portable folder names separated by '/'."); + } if (string.IsNullOrWhiteSpace(startupScene)) + { throw new InvalidDataException("A startup scene is required."); + } try { - _ = new BuildTargetId(m_targetId); + _ = new BuildTargetID(m_targetId); } catch (ArgumentException exception) { throw new InvalidDataException("A game build target is required and must use a portable target ID.", exception); } if (m_managedDeploymentId is null) + { throw new InvalidDataException("Managed deployment selection cannot be null."); + } if (m_managedDeploymentId.Length > 0) { - try { _ = new ManagedDeploymentId(m_managedDeploymentId); } + try + { + _ = new ManagedDeploymentID(m_managedDeploymentId); + } catch (ArgumentException exception) { throw new InvalidDataException("Managed deployment selection must use a portable provider ID.", exception); } } if (windowWidth <= 0 || windowHeight <= 0) + { throw new InvalidDataException("Window dimensions must be positive."); + } } private static bool IsPortableIdentifier(string value) { if (string.IsNullOrWhiteSpace(value)) + { return false; - return value.All(static character => + } + return value.All(static character => ( character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'); + || character is '.' or '_' or '-' + )); } private static bool IsPortableDataPath(string value) => value is not null - && (value.Length == 0 || value.Split('/').All(static segment => + && (value.Length == 0 || value.Split('/').All(static segment => ( segment is not "." and not ".." && !segment.EndsWith('.') - && !S_WINDOWS_RESERVED_NAMES.Contains(segment.Split('.', 2)[0]) - && IsPortableIdentifier(segment))); + && !WINDOWS_RESERVED_NAMES.Contains(segment.Split('.', 2)[0]) + && IsPortableIdentifier(segment) + ))); private static bool IsPortableProductName(string value) { if (string.IsNullOrWhiteSpace(value) || value is "." or ".." || value.EndsWith(' ') - || value.EndsWith('.')) - { + || value.EndsWith('.') + ) { return false; } if (value.Any(static character => character < ' ' || "<>:\"/\\|?*".Contains(character))) + { return false; + } string stem = value.Split('.', 2)[0]; - return !S_WINDOWS_RESERVED_NAMES.Contains(stem); + return !WINDOWS_RESERVED_NAMES.Contains(stem); } } diff --git a/build/pipeline/Inno.Build/BuildProfileStore.cs b/build/pipeline/Inno.Build/BuildProfileStore.cs index 7640d30d6..71f8d5956 100644 --- a/build/pipeline/Inno.Build/BuildProfileStore.cs +++ b/build/pipeline/Inno.Build/BuildProfileStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -63,7 +62,9 @@ SerializationRegistry serialization public BuildProfile Load() { if (!File.Exists(m_path)) + { throw new FileNotFoundException("The project build profile does not exist.", m_path); + } BuildProfile profile; try @@ -71,9 +72,9 @@ public BuildProfile Load() profile = m_serialization.Deserialize(File.ReadAllBytes(m_path)); } catch (Exception exception) when (exception is IOException - or InvalidDataException - or InvalidOperationException - or ArgumentException) + or InvalidDataException + or InvalidOperationException + or ArgumentException) { throw new InvalidDataException($"Build profile '{m_path}' is not a valid current-format document.", exception); } diff --git a/build/pipeline/Inno.Build/BuildProgress.cs b/build/pipeline/Inno.Build/BuildProgress.cs index b0233b8a7..61ceab869 100644 --- a/build/pipeline/Inno.Build/BuildProgress.cs +++ b/build/pipeline/Inno.Build/BuildProgress.cs @@ -29,13 +29,14 @@ public BuildProgress( string stage, double fraction, string message - ) - : this() + ) : this() { ArgumentException.ThrowIfNullOrWhiteSpace(stage); ArgumentException.ThrowIfNullOrWhiteSpace(message); if (fraction is < 0d or > 1d || double.IsNaN(fraction)) + { throw new ArgumentOutOfRangeException(nameof(fraction)); + } this.stage = stage; this.fraction = fraction; this.message = message; diff --git a/build/pipeline/Inno.Build/BuildResult.cs b/build/pipeline/Inno.Build/BuildResult.cs index 0fe01c6da..95d16a1b2 100644 --- a/build/pipeline/Inno.Build/BuildResult.cs +++ b/build/pipeline/Inno.Build/BuildResult.cs @@ -11,7 +11,7 @@ public sealed class BuildResult private BuildResult( bool succeeded, string? outputPath, - BuildTargetId? target, + BuildTargetID? target, string? contentHash, int assetCount, int artifactBundleCount, @@ -43,7 +43,7 @@ private BuildResult( /// /// Gets the game target, or for a Plugin package. /// - public BuildTargetId? target { get; } + public BuildTargetID? target { get; } /// /// Gets the deterministic content identity, or when the build failed. @@ -77,7 +77,7 @@ private BuildResult( internal static BuildResult Success( string outputPath, - BuildTargetId? target, + BuildTargetID? target, string contentHash, int assetCount, int artifactBundleCount, @@ -96,16 +96,19 @@ internal static BuildResult Success( artifactBundleCount, runtimeAssemblyCount, embeddedPluginCount, - diagnostics); + diagnostics + ); } internal static BuildResult Failure( - BuildTargetId? target, + BuildTargetID? target, IReadOnlyList diagnostics ) { ArgumentNullException.ThrowIfNull(diagnostics); if (diagnostics.Count == 0) + { throw new ArgumentException("A failed build requires at least one diagnostic.", nameof(diagnostics)); + } return new BuildResult( false, outputPath: null, @@ -115,6 +118,7 @@ IReadOnlyList diagnostics artifactBundleCount: 0, runtimeAssemblyCount: 0, embeddedPluginCount: 0, - diagnostics); + diagnostics + ); } } diff --git a/build/pipeline/Inno.Build/BuildSettings.cs b/build/pipeline/Inno.Build/BuildSettings.cs index 90ee51d4a..3bfd5050e 100644 --- a/build/pipeline/Inno.Build/BuildSettings.cs +++ b/build/pipeline/Inno.Build/BuildSettings.cs @@ -1,7 +1,6 @@ using System; -using Inno.Build.Managed; using System.IO; - +using Inno.Build.Managed; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -71,7 +70,7 @@ public sealed class BuildSettings : ISerializable /// /// Gets or sets the default game build target. /// - public BuildTargetId gameTarget + public BuildTargetID gameTarget { get => new(m_gameTargetId); set => m_gameTargetId = value.value; @@ -83,9 +82,9 @@ public BuildTargetId gameTarget /// /// Gets or sets the default managed publisher; null follows the selected platform's default. /// - public ManagedDeploymentId? gameManagedDeployment + public ManagedDeploymentID? gameManagedDeployment { - get => m_gameManagedDeploymentId.Length == 0 ? null : new ManagedDeploymentId(m_gameManagedDeploymentId); + get => m_gameManagedDeploymentId.Length == 0 ? null : new ManagedDeploymentID(m_gameManagedDeploymentId); set => m_gameManagedDeploymentId = value?.value ?? string.Empty; } @@ -113,17 +112,19 @@ public ManagedDeploymentId? gameManagedDeployment public static BuildSettings CreateDefault( string projectName, string startupScene, - BuildTargetId target + BuildTargetID target ) { ArgumentException.ThrowIfNullOrWhiteSpace(projectName); ArgumentNullException.ThrowIfNull(startupScene); if (string.IsNullOrWhiteSpace(target.value)) + { throw new ArgumentException("A default build target is required.", nameof(target)); - string portableId = ProjectId.FromName(projectName).value; + } + string portableID = ProjectID.FromName(projectName).value; return new BuildSettings { pluginDisplayName = projectName, - pluginOutputPath = $"Builds/{portableId}.iplugin", + pluginOutputPath = $"Builds/{portableID}.iplugin", includePluginDependencies = false, gameProductName = projectName, gameStartupScene = startupScene, @@ -137,24 +138,24 @@ BuildTargetId target /// /// Creates an isolated game profile from the current defaults. /// - /// + /// /// The authoritative project identity copied into the game profile. /// /// /// A newly owned profile that may be changed for one build without mutating these settings. /// - public BuildProfile CreateGameProfile(ProjectId projectId) + public BuildProfile CreateGameProfile(ProjectID projectID) => new() - { - applicationId = projectId.value, - productName = gameProductName, - persistentDataPath = gamePersistentDataPath, - startupScene = gameStartupScene, - target = gameTarget, - managedDeployment = gameManagedDeployment, - windowWidth = gameWindowWidth, - windowHeight = gameWindowHeight - }; + { + applicationId = projectID.value, + productName = gameProductName, + persistentDataPath = gamePersistentDataPath, + startupScene = gameStartupScene, + target = gameTarget, + managedDeployment = gameManagedDeployment, + windowWidth = gameWindowWidth, + windowHeight = gameWindowHeight + }; /// /// Creates an isolated copy suitable for a temporary export draft. @@ -164,19 +165,19 @@ public BuildProfile CreateGameProfile(ProjectId projectId) /// public BuildSettings Copy() => new() - { - pluginDisplayName = pluginDisplayName, - pluginOutputPath = pluginOutputPath, - includePluginDependencies = includePluginDependencies, - gameProductName = gameProductName, - gamePersistentDataPath = gamePersistentDataPath, - gameStartupScene = gameStartupScene, - gameOutputDirectory = gameOutputDirectory, - gameWindowWidth = gameWindowWidth, - gameWindowHeight = gameWindowHeight, - m_gameTargetId = m_gameTargetId, - m_gameManagedDeploymentId = m_gameManagedDeploymentId - }; + { + pluginDisplayName = pluginDisplayName, + pluginOutputPath = pluginOutputPath, + includePluginDependencies = includePluginDependencies, + gameProductName = gameProductName, + gamePersistentDataPath = gamePersistentDataPath, + gameStartupScene = gameStartupScene, + gameOutputDirectory = gameOutputDirectory, + gameWindowWidth = gameWindowWidth, + gameWindowHeight = gameWindowHeight, + m_gameTargetId = m_gameTargetId, + m_gameManagedDeploymentId = m_gameManagedDeploymentId + }; internal void ValidateDocument() { @@ -187,12 +188,14 @@ internal void ValidateDocument() || gameStartupScene is null || gameOutputDirectory is null || m_gameTargetId is null - || m_gameManagedDeploymentId is null) - { + || m_gameManagedDeploymentId is null + ) { throw new InvalidDataException("Build Settings contains a null string."); } if (gameWindowWidth <= 0 || gameWindowHeight <= 0) + { throw new InvalidDataException("Build Settings window dimensions must be positive."); + } try { _ = gameTarget; diff --git a/build/pipeline/Inno.Build/BuildSettingsStore.cs b/build/pipeline/Inno.Build/BuildSettingsStore.cs index 557f72a8b..4d9b1ac25 100644 --- a/build/pipeline/Inno.Build/BuildSettingsStore.cs +++ b/build/pipeline/Inno.Build/BuildSettingsStore.cs @@ -1,9 +1,8 @@ using System; using System.IO; - +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; namespace Inno.Build; @@ -47,7 +46,8 @@ BuildSettings defaultSettings new FileByteDocumentStore(Path.GetFullPath(path)), serialization, defaultSettings.Copy, - static value => value.ValidateDocument()); + static value => value.ValidateDocument() + ); m_defaultSettings = defaultSettings.Copy(); } @@ -59,7 +59,9 @@ public bool exists get { lock (m_sync) + { return m_documents.exists; + } } } @@ -71,7 +73,9 @@ public BuildSettings defaultSettings get { lock (m_sync) + { return m_defaultSettings.Copy(); + } } } @@ -87,7 +91,9 @@ public BuildSettings defaultSettings public BuildSettings Load() { lock (m_sync) + { return LoadLocked(); + } } /// @@ -110,7 +116,9 @@ public void Save(BuildSettings settings) ArgumentNullException.ThrowIfNull(settings); settings.ValidateDocument(); lock (m_sync) + { m_documents.Save(settings.Copy()); + } } /// @@ -122,7 +130,9 @@ public void Save(BuildSettings settings) public byte[] CaptureDocument() { lock (m_sync) + { return m_documents.Capture(LoadLocked()); + } } /// @@ -141,7 +151,9 @@ public void RestoreDocument(ReadOnlySpan document) { BuildSettings settings = Deserialize(document); lock (m_sync) + { m_documents.Save(settings); + } } /// @@ -156,15 +168,9 @@ public void RestoreDocument(ReadOnlySpan document) public void ValidateDocument(ReadOnlySpan document) => _ = Deserialize(document); private BuildSettings LoadLocked() - { - return m_documents.exists - ? m_documents.LoadRequired() - : m_defaultSettings.Copy(); - } - - private BuildSettings Deserialize(ReadOnlySpan document) - { - return m_documents.Deserialize(document); - } + => m_documents.exists + ? m_documents.LoadRequired() + : m_defaultSettings.Copy(); + private BuildSettings Deserialize(ReadOnlySpan document) => m_documents.Deserialize(document); } diff --git a/build/pipeline/Inno.Build/BuildTargetId.cs b/build/pipeline/Inno.Build/BuildTargetID.cs similarity index 91% rename from build/pipeline/Inno.Build/BuildTargetId.cs rename to build/pipeline/Inno.Build/BuildTargetID.cs index fa9363e50..0a720a950 100644 --- a/build/pipeline/Inno.Build/BuildTargetId.cs +++ b/build/pipeline/Inno.Build/BuildTargetID.cs @@ -5,7 +5,7 @@ namespace Inno.Build; /// /// Identifies one stable platform and architecture combination supported by the game build pipeline. /// -public readonly record struct BuildTargetId +public readonly record struct BuildTargetID { /// /// Creates a stable target identity. @@ -16,13 +16,15 @@ public readonly record struct BuildTargetId /// /// Thrown when is not a portable target identity. /// - public BuildTargetId(string value) + public BuildTargetID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) { if (!(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' || character == '-')) + { throw new ArgumentException("Build target IDs must use lowercase portable characters.", nameof(value)); + } } this.value = value; } diff --git a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs index fcc6c2f0c..d78ec6702 100644 --- a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs +++ b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs @@ -1,22 +1,21 @@ using System; +using System.Buffers; +using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Collections.Generic; -using System.Buffers; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - +using Inno.Content; using Inno.Core.IO; using Inno.Core.Serialization; -using Inno.Content; namespace Inno.Build; internal static class ContentPackWriter { - private static readonly DateTimeOffset S_ARCHIVE_TIME = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset ARCHIVE_TIME = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); internal static async ValueTask<(string packPath, string contentHash)> WriteAsync( string sourceRoot, @@ -27,18 +26,20 @@ CancellationToken cancellationToken Directory.CreateDirectory(contentRoot); string temporary = Path.Combine(contentRoot, ".content.pack.staging-" + Guid.NewGuid().ToString("N")); string[] files = PathBoundary.EnumerateFiles(sourceRoot) - .OrderBy(static value => value, StringComparer.Ordinal).ToArray(); + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray(); ContentKey[] keys = files.Select(file => new ContentKey(Path.GetRelativePath(sourceRoot, file).Replace('\\', '/'))).ToArray(); _ = new ContentPackIndex(keys.Select(static key => new ContentEntry(key, 0, new string('0', 64)))); try { - await using (FileStream stream = new( - temporary, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) + await using (var stream = new FileStream( + temporary, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { List entries = []; @@ -46,15 +47,16 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); ZipArchiveEntry entry = archive.CreateEntry(keys[index].value!, CompressionLevel.Optimal); - entry.LastWriteTime = S_ARCHIVE_TIME; + entry.LastWriteTime = ARCHIVE_TIME; await using Stream output = entry.Open(); - await using FileStream input = new( + await using var input = new FileStream( files[index], FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); byte[] buffer = ArrayPool.Shared.Rent(128 * 1024); long length = 0; @@ -74,22 +76,25 @@ CancellationToken cancellationToken ArrayPool.Shared.Return(buffer); } } - ContentPackIndex inventory = new(entries); + var inventory = new ContentPackIndex(entries); ZipArchiveEntry indexEntry = archive.CreateEntry(ContentPackIndex.C_INDEX_KEY, CompressionLevel.Optimal); - indexEntry.LastWriteTime = S_ARCHIVE_TIME; + indexEntry.LastWriteTime = ARCHIVE_TIME; await using Stream indexOutput = indexEntry.Open(); - await indexOutput.WriteAsync(ContentPackIndexCodec.Encode(inventory, serialization), cancellationToken).ConfigureAwait(false); + await indexOutput.WriteAsync( + ContentPackIndexCodec.Encode(inventory, serialization), + cancellationToken + ).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); string contentHash; - await using (FileStream input = new( - temporary, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (var input = new FileStream( + temporary, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { contentHash = Convert.ToHexString(await SHA256.HashDataAsync(input, cancellationToken).ConfigureAwait(false)); } string packPath = Path.Combine(contentRoot, $"content-{contentHash}.pack"); @@ -99,7 +104,9 @@ CancellationToken cancellationToken catch { if (File.Exists(temporary)) + { File.Delete(temporary); + } throw; } } diff --git a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs index e650d50fe..c3cf81af9 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs @@ -1,20 +1,20 @@ -using Inno.Build.Managed; -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Security.Cryptography; using System.Reflection; +using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build.Managed; +using Inno.Core.Diagnostics; +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; @@ -28,7 +28,7 @@ internal sealed class GameBuildPipeline private readonly ProjectSettingsStore m_settings; private readonly SerializationRegistry m_serialization; private readonly ScriptCompiler m_compiler; - private readonly IReadOnlyDictionary m_targets; + private readonly IReadOnlyDictionary m_targets; private readonly PlayerSupportPackCatalog m_supportPacks; private readonly ManagedDeploymentCatalog m_managedDeployments; @@ -38,7 +38,7 @@ internal GameBuildPipeline( ProjectSettingsStore settings, SerializationRegistry serialization, ScriptCompiler compiler, - IReadOnlyDictionary targets, + IReadOnlyDictionary targets, PlayerSupportPackCatalog supportPacks, ManagedDeploymentCatalog managedDeployments ) { @@ -60,12 +60,18 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(request); request.Validate(); if (!m_targets.TryGetValue(request.profile.target, out GameBuildTargetBinding? binding)) + { throw new InvalidOperationException($"No game packager is registered for '{request.profile.target}'."); + } IGameBuildTarget target = binding.packager; IManagedDeploymentCompiler managedCompiler = m_managedDeployments.Resolve( - request.profile.managedDeployment ?? target.defaultManagedDeployment, target.runtimeIdentifier); + request.profile.managedDeployment ?? target.defaultManagedDeployment, + target.runtimeIdentifier + ); if (!m_assets.isInitialized) + { throw new InvalidOperationException("Game build requires an active authoring asset database."); + } string outputRoot = Path.GetFullPath(request.outputDirectory); ValidateOutputRoot(outputRoot); cancellationToken.ThrowIfCancellationRequested(); @@ -75,12 +81,15 @@ CancellationToken cancellationToken m_assets.WaitForIdle(); AssetPath startupPath = AssetPath.Parse(request.profile.startupScene); if (!m_assets.TryGetAssetType(startupPath, out Type? sceneType) || sceneType != typeof(SceneAsset)) + { throw new InvalidOperationException($"Startup scene '{startupPath}' is not an imported Scene asset."); + } if (AssetSample.IsRuntimeExcluded(startupPath, isDirectory: false)) { throw new InvalidOperationException( - $"Startup scene '{startupPath}' belongs to an authoring-only '~' sample directory " + - "and cannot be included in a Player build."); + $"Startup scene '{startupPath}' belongs to an authoring-only '~' sample directory " + + "and cannot be included in a Player build." + ); } long assetRevision = m_assets.revision; @@ -92,12 +101,15 @@ CancellationToken cancellationToken progress?.Report(new BuildProgress("snapshot", 0.05d, "Captured the combined authoring generation.")); Directory.CreateDirectory(outputRoot); - using ProcessOwnedDirectory stagingOwner = await ProcessOwnedDirectory.CreateAsync(outputRoot, cancellationToken).ConfigureAwait(false); + using ProcessOwnedDirectory stagingOwner = await ProcessOwnedDirectory.CreateAsync( + outputRoot, + cancellationToken + ).ConfigureAwait(false); string staging = stagingOwner.directory; - using var stagingCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using CancellationTokenSource stagingCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); Task? assetExportTask = null; Task? targetContentTask = null; - var publicationDiagnostics = new List(); + List publicationDiagnostics = []; bool committed = false; try { @@ -106,18 +118,17 @@ CancellationToken cancellationToken string rawContent = Path.Combine(staging, "RawContent"); string targetContent = Path.Combine(staging, "TargetContent"); progress?.Report(new BuildProgress("content", 0.12d, "Exporting the runtime artifact closure.")); - assetExportTask = m_assets.ExportRuntimeArtifactsAsync( - rawContent, - stagingToken); - targetContentTask = binding.compiler.CompileAsync( - new GameBuildContentContext(request.profile, targetContent, serialization), - stagingToken) + assetExportTask = m_assets.ExportRuntimeArtifactsAsync(rawContent, stagingToken); + targetContentTask = binding.compiler + .CompileAsync(new GameBuildContentContext(request.profile, targetContent, serialization), stagingToken) .AsTask(); - ScriptCompilationResult compilation = await m_compiler.CompileRuntimeDeploymentAsync( + ScriptCompilationResult compilation = await m_compiler + .CompileRuntimeDeploymentAsync( Path.Combine(supportPack, "References"), new ScriptBuildProgress(progress), - stagingToken) + stagingToken + ) .ConfigureAwait(false); if (!compilation.success) { @@ -139,12 +150,15 @@ CancellationToken cancellationToken [new BuildDiagnostic( BuildDiagnosticSeverity.Error, "INNOBUILD1001", - "Runtime script compilation did not produce a complete assembly generation.")]); + "Runtime script compilation did not produce a complete assembly generation." + )] + ); } GameRuntimeModule[] runtimeModules = CreateRuntimeModules(compilation.moduleDeployments); byte[] runtimeManifest = RuntimeManifestEnvelope.Encode( CreateManifest(request.profile, plugins, runtimeModules), - serialization); + serialization + ); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); progress?.Report(new BuildProgress("prepare", 0.28d, "Prepared the runtime script and manifest generation.")); @@ -154,10 +168,7 @@ await BuildFileSystem.MergeDirectoryAsync(targetContent, rawContent, stagingToke .ConfigureAwait(false); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); - await File.WriteAllBytesAsync( - Path.Combine(rawContent, SettingsFileNames.project), - settings, - stagingToken) + await File.WriteAllBytesAsync(Path.Combine(rawContent, SettingsFileNames.C_PROJECT), settings, stagingToken) .ConfigureAwait(false); string managed = Path.Combine(staging, "CodeInputs"); Directory.CreateDirectory(managed); @@ -166,32 +177,25 @@ await File.WriteAllBytesAsync( stagingToken.ThrowIfCancellationRequested(); string destination = Path.Combine(managed, Path.GetFileName(assemblies[index])); if (File.Exists(destination)) + { throw new InvalidOperationException($"Runtime assembly '{Path.GetFileName(destination)}' is duplicated."); + } await BuildFileSystem.CopyFileAsync(assemblies[index], destination, stagingToken) .ConfigureAwait(false); } - string snapshotFingerprint = await BuildSnapshotFingerprint.ComputeAsync( - assetRevision, - assemblies, - plugins, - settings, - stagingToken) + string snapshotFingerprint = await BuildSnapshotFingerprint + .ComputeAsync(assetRevision, assemblies, plugins, settings, stagingToken) .ConfigureAwait(false); string packagedContent = Path.Combine(staging, "PackagedContent"); Directory.CreateDirectory(packagedContent); - await File.WriteAllBytesAsync( - Path.Combine(packagedContent, "runtime.manifest"), - runtimeManifest, - stagingToken) + await File + .WriteAllBytesAsync(Path.Combine(packagedContent, "runtime.manifest"), runtimeManifest, stagingToken) .ConfigureAwait(false); progress?.Report(new BuildProgress("pack", 0.55d, "Writing the deterministic content pack.")); - (_, string contentHash) = await ContentPackWriter.WriteAsync( - rawContent, - packagedContent, - serialization, - stagingToken) + (_, string contentHash) = await ContentPackWriter + .WriteAsync(rawContent, packagedContent, serialization, stagingToken) .ConfigureAwait(false); var catalog = new RuntimeContentCatalog { @@ -203,39 +207,59 @@ await File.WriteAllBytesAsync( runtimeAssemblyCount = assemblies.Length }; catalog.Validate(); - await File.WriteAllBytesAsync( + await File + .WriteAllBytesAsync( Path.Combine(packagedContent, "catalog.inno"), serialization.Serialize(catalog), - stagingToken) + stagingToken + ) .ConfigureAwait(false); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); string playerLink = Path.Combine(staging, "PlayerLink"); - await BuildFileSystem.CopyDirectoryAsync(Path.Combine(supportPack, "PlayerLink"), - playerLink, stagingToken).ConfigureAwait(false); - await PlayerCodeCompositionWriter.WriteAsync(playerLink, - GameCodeDeployment.FromManifest(runtimeModules), stagingToken).ConfigureAwait(false); + await BuildFileSystem.CopyDirectoryAsync( + Path.Combine(supportPack, "PlayerLink"), + playerLink, + stagingToken + ).ConfigureAwait(false); + await PlayerCodeCompositionWriter.WriteAsync( + playerLink, + GameCodeDeployment.FromManifest(runtimeModules), + stagingToken + ).ConfigureAwait(false); progress?.Report(new BuildProgress("managed", 0.62d, "Publishing the frozen game code deployment.")); string managedStaging = Path.Combine(staging, "ManagedDeployment"); ManagedDeploymentResult managedDeployment = await managedCompiler.CompileAsync( - new ManagedDeploymentRequest(Path.Combine(playerLink, "Player.csproj"), - target.runtimeIdentifier, managed, managedStaging, - Path.Combine(outputRoot, ".build-logs", Path.GetFileName(staging))), stagingToken).ConfigureAwait(false); + new ManagedDeploymentRequest( + Path.Combine(playerLink, "Player.csproj"), + target.runtimeIdentifier, + managed, + managedStaging, + Path.Combine(outputRoot, ".build-logs", Path.GetFileName(staging)) + ), + stagingToken + ).ConfigureAwait(false); ValidateManagedPublication(managedCompiler.id, managedStaging, managedDeployment); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); string platformStaging = Path.Combine(staging, "Platform"); Directory.CreateDirectory(platformStaging); progress?.Report(new BuildProgress("package", 0.78d, $"Composing {request.profile.target} Player output.")); - string composed = await target.PackageAsync( + string composed = await target + .PackageAsync( new GameBuildPackageContext(request.profile, supportPack, packagedContent, managedDeployment, platformStaging), - stagingToken) + stagingToken + ) .ConfigureAwait(false); string normalizedComposed = Path.GetFullPath(composed); if (!IsWithin(platformStaging, normalizedComposed)) + { throw new InvalidOperationException("A game target returned output outside its staging directory."); + } if (!Directory.Exists(normalizedComposed)) + { throw new DirectoryNotFoundException("The game target did not create its declared output directory."); + } stagingToken.ThrowIfCancellationRequested(); string final = Path.Combine(outputRoot, Path.GetFileName(normalizedComposed)); try @@ -244,7 +268,9 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, } catch (DirectoryCleanupException cleanupFailure) { - publicationDiagnostics.Add(new(BuildDiagnosticSeverity.Warning, "INNO-BUILD-CLEANUP", cleanupFailure.Message)); + publicationDiagnostics.Add( + new BuildDiagnostic(BuildDiagnosticSeverity.Warning, "INNO-BUILD-CLEANUP", cleanupFailure.Message) + ); } committed = true; try @@ -253,8 +279,13 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, } catch (Exception observerFailure) { - publicationDiagnostics.Add(new(BuildDiagnosticSeverity.Warning, "INNO-BUILD-PROGRESS", - $"The complete game was committed, but its progress observer failed: {observerFailure.Message}")); + publicationDiagnostics.Add( + new BuildDiagnostic( + BuildDiagnosticSeverity.Warning, + "INNO-BUILD-PROGRESS", + $"The complete game was committed, but its progress observer failed: {observerFailure.Message}" + ) + ); } return BuildResult.Success( final, @@ -264,7 +295,8 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, assetInfo.artifactBundleCount, assemblies.Length, embeddedPluginCount: 0, - diagnostics: publicationDiagnostics.AsReadOnly()); + diagnostics: publicationDiagnostics.AsReadOnly() + ); } finally { @@ -277,41 +309,91 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, } catch (Exception cleanupFailure) when (committed && cleanupFailure is IOException or UnauthorizedAccessException) { - publicationDiagnostics.Add(new(BuildDiagnosticSeverity.Warning, "INNO-BUILD-CLEANUP", - $"The complete game was committed, but staging cleanup was deferred for '{staging}': {cleanupFailure.Message}")); + publicationDiagnostics.Add( + new BuildDiagnostic( + BuildDiagnosticSeverity.Warning, + "INNO-BUILD-CLEANUP", + $"The complete game was committed, but staging cleanup was deferred for '{staging}': {cleanupFailure.Message}" + ) + ); } } } + private void EnsureGenerationUnchanged( + long expectedAssetRevision, + long expectedPluginRevision, + long expectedSettingsRevision + ) { + if (m_assets.revision != expectedAssetRevision + || m_plugins.revision != expectedPluginRevision + || m_settings.revision != expectedSettingsRevision + ) { + throw new InvalidOperationException( + "The active Asset, Plugin, or Project Settings generation changed during the build. " + + "No output was committed; start a new build from the latest generation." + ); + } + } + + private void ValidateOutputRoot(string outputRoot) + { + List protectedRoots = m_assets.sourceMounts + .Select(static mount => mount.rootPath) + .Append(m_assets.libraryRoot) + .ToList(); + string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; + if (projectRoot is not null) + { + protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); + } + string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, outputRoot)); + if (conflict is not null) + { + throw new InvalidOperationException( + $"Build output cannot be written inside managed project content '{Path.GetFullPath(conflict)}'." + ); + } + } + private static async ValueTask ObserveCompletionAsync(Task? task) { if (task is null) + { return; + } try { await task.ConfigureAwait(false); } - catch + catch (Exception) { // The primary build path reports the stage failure; cleanup only observes task completion. } } private static void ValidateManagedPublication( - ManagedDeploymentId deployment, + ManagedDeploymentID deployment, string staging, ManagedDeploymentResult result ) { ArgumentNullException.ThrowIfNull(result); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; if (result.deployment != deployment || !string.Equals(Path.GetFullPath(staging), result.outputDirectory, comparison) - || !Directory.Exists(result.outputDirectory)) + || !Directory.Exists(result.outputDirectory) + ) { throw new InvalidDataException("The managed publisher returned foreign or absent staging output."); + } string[] actualFiles = Directory.EnumerateFiles(result.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(result.outputDirectory, file)).Order(StringComparer.Ordinal).ToArray(); + .Select(file => Path.GetRelativePath(result.outputDirectory, file)) + .Order(StringComparer.Ordinal) + .ToArray(); if (!actualFiles.SequenceEqual(result.files.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + { throw new InvalidDataException("The managed publication evidence differs from its staged output."); + } } private static BuildDiagnostic ToBuildDiagnostic(ScriptDiagnostic diagnostic) @@ -323,8 +405,8 @@ private static BuildDiagnostic ToBuildDiagnostic(ScriptDiagnostic diagnostic) _ => BuildDiagnosticSeverity.Information }; string location = diagnostic.filePath is null - ? string.Empty - : $" ({diagnostic.filePath}:{diagnostic.line}:{diagnostic.column})"; + ? string.Empty + : $" ({diagnostic.filePath}:{diagnostic.line}:{diagnostic.column})"; return new BuildDiagnostic(severity, diagnostic.id, diagnostic.message + location); } @@ -362,16 +444,19 @@ private static GameRuntimeModule[] CreateRuntimeModules(IReadOnlyList request.assemblyScopes.TryGetValue( + .Where(path => ( + request.assemblyScopes.TryGetValue( Path.GetFileNameWithoutExtension(path), - out AssemblyScope scope) + out AssemblyScope scope + ) ? scope == AssemblyScope.Runtime - : request.scope == AssemblyScope.Runtime) + : request.scope == AssemblyScope.Runtime + )) .ToArray() }) .Where(static candidate => candidate.assemblies.Length > 0) .ToArray(); - var includedNames = selected + HashSet includedNames = selected .Select(static candidate => candidate.request.moduleName) .ToHashSet(StringComparer.Ordinal); GameRuntimeModule[] candidates = selected.Select(candidate => new GameRuntimeModule @@ -387,26 +472,33 @@ private static GameRuntimeModule[] CreateRuntimeModules(IReadOnlyList module.name, StringComparer.Ordinal); + Dictionary byName = candidates.ToDictionary(static module => module.name, StringComparer.Ordinal); var visiting = new HashSet(StringComparer.Ordinal); var visited = new HashSet(StringComparer.Ordinal); var ordered = new List(candidates.Length); foreach (GameRuntimeModule module in candidates.OrderBy(static module => module.name, StringComparer.Ordinal)) + { Visit(module); + } return ordered.ToArray(); void Visit(GameRuntimeModule module) { if (visited.Contains(module.name)) + { return; + } if (!visiting.Add(module.name)) + { throw new InvalidOperationException($"Runtime module dependency cycle contains '{module.name}'."); + } foreach (string dependencyName in module.dependencies.Order(StringComparer.Ordinal)) { if (!byName.TryGetValue(dependencyName, out GameRuntimeModule? dependency)) { throw new InvalidOperationException( - $"Runtime module '{module.name}' depends on missing module '{dependencyName}'."); + $"Runtime module '{module.name}' depends on missing module '{dependencyName}'." + ); } Visit(dependency); } @@ -416,52 +508,19 @@ void Visit(GameRuntimeModule module) } } - private void EnsureGenerationUnchanged( - long expectedAssetRevision, - long expectedPluginRevision, - long expectedSettingsRevision - ) { - if (m_assets.revision != expectedAssetRevision - || m_plugins.revision != expectedPluginRevision - || m_settings.revision != expectedSettingsRevision) - { - throw new InvalidOperationException( - "The active Asset, Plugin, or Project Settings generation changed during the build. " + - "No output was committed; start a new build from the latest generation."); - } - } - - private void ValidateOutputRoot(string outputRoot) - { - var protectedRoots = m_assets.sourceMounts - .Select(static mount => mount.rootPath) - .Append(m_assets.libraryRoot) - .ToList(); - string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; - if (projectRoot is not null) - protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); - string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, outputRoot)); - if (conflict is not null) - { - throw new InvalidOperationException( - $"Build output cannot be written inside managed project content '{Path.GetFullPath(conflict)}'."); - } - } - private static bool IsWithin( string root, string candidate ) { string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; return string.Equals(candidate, normalizedRoot, comparison) || candidate.StartsWith(normalizedRoot + Path.DirectorySeparatorChar, comparison); } - private sealed class ScriptBuildProgress(IProgress? progress) - : IProgress + private sealed class ScriptBuildProgress(IProgress? progress) : IProgress { /// /// Publishes one progress update to the receiving workflow. @@ -470,9 +529,6 @@ private sealed class ScriptBuildProgress(IProgress? progress) /// The concrete value read or transformed by this operation. /// public void Report(ScriptCompilationProgress value) - => progress?.Report(new BuildProgress( - "scripting", - 0.05d + value.fraction * 0.2d, - value.stage)); + => progress?.Report(new BuildProgress("scripting", 0.05d + value.fraction * 0.2d, value.stage)); } } diff --git a/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs b/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs index e8f5347d3..7bd66422d 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs @@ -29,7 +29,9 @@ IGameContentCompiler compiler ArgumentNullException.ThrowIfNull(packager); ArgumentNullException.ThrowIfNull(compiler); if (string.IsNullOrWhiteSpace(packager.id.value) || packager.id != compiler.target) + { throw new ArgumentException("Packaging and content compilation require the same assigned target.", nameof(compiler)); + } this.packager = packager; this.compiler = compiler; } diff --git a/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs b/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs index 645ba0979..019491dd0 100644 --- a/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs +++ b/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs @@ -1,6 +1,6 @@ -using Inno.Build.Managed; using System.Threading; using System.Threading.Tasks; +using Inno.Build.Managed; namespace Inno.Build; @@ -12,12 +12,12 @@ public interface IGameBuildTarget : IPlayerSupportPackValidator /// /// Gets the stable target identity implemented by this packager. /// - BuildTargetId id { get; } + BuildTargetID id { get; } /// /// Gets the managed publisher selected when the profile does not specify an override. /// - ManagedDeploymentId defaultManagedDeployment { get; } + ManagedDeploymentID defaultManagedDeployment { get; } /// /// Gets the managed toolchain target identifier required by this platform composition. diff --git a/build/pipeline/Inno.Build/Game/IGameContentCompiler.cs b/build/pipeline/Inno.Build/Game/IGameContentCompiler.cs index 7c1ea0d9b..b60b8c31a 100644 --- a/build/pipeline/Inno.Build/Game/IGameContentCompiler.cs +++ b/build/pipeline/Inno.Build/Game/IGameContentCompiler.cs @@ -11,7 +11,7 @@ public interface IGameContentCompiler /// /// Gets the exact publication target whose content this compiler produces. /// - BuildTargetId target { get; } + BuildTargetID target { get; } /// /// Writes target content into the current operation's isolated staging directory. diff --git a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs index c04f0dae1..6604550dc 100644 --- a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs +++ b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -20,33 +21,54 @@ CancellationToken cancellationToken XDocument document = XDocument.Load(project); string? assemblyName = document.Descendants("AssemblyName").Select(static item => item.Value).SingleOrDefault(); if (string.IsNullOrWhiteSpace(assemblyName)) + { throw new InvalidDataException("A prepared Player project must declare its assembly name explicitly."); + } var source = new StringBuilder("// \n#nullable enable\n"); - source.Append("namespace ").Append(assemblyName).Append(".Generated;\n\n") + source.Append("namespace ") + .Append(assemblyName) + .Append(".Generated;\n\n") .Append("internal static class PlayerDeploymentDefinition\n{\n") .Append(" internal static global::Inno.Runtime.GameCodeDeployment CreateDeployment() => new([\n"); foreach (GameCodeModule module in deployment.modules) { - source.Append(" new global::Inno.Runtime.GameCodeModule(\n ").Append(Quote(module.name)) - .Append(", global::Inno.Extensibility.Modules.AssemblyDomain.").Append(module.domain).Append(", [\n"); + source.Append(" new global::Inno.Runtime.GameCodeModule(\n ") + .Append(Quote(module.name)) + .Append(", global::Inno.Extensibility.Modules.AssemblyDomain.") + .Append(module.domain) + .Append(", [\n"); foreach (GameCodeAssembly assembly in module.assemblies) - source.Append(" new global::Inno.Runtime.GameCodeAssembly(").Append(Quote(assembly.name)) - .Append(", ").Append(Quote(assembly.contentFingerprint)).Append("),\n"); + { + source.Append(" new global::Inno.Runtime.GameCodeAssembly(") + .Append(Quote(assembly.name)) + .Append(", ") + .Append(Quote(assembly.contentFingerprint)) + .Append("),\n"); + } source.Append(" ], [").Append(string.Join(", ", module.dependencies.Select(Quote))).Append("]),\n"); } source.Append(" ]);\n\n") - .Append(" internal static global::System.Collections.Generic.IReadOnlyDictionary> CreateAssemblies() =>\n") - .Append(" new global::System.Collections.Generic.Dictionary>\n {\n"); + .Append( + " internal static global::System.Collections.Generic.IReadOnlyDictionary> CreateAssemblies() =>\n" + ) + .Append( + " new global::System.Collections.Generic.Dictionary>\n {\n" + ); foreach (GameCodeModule module in deployment.modules) { source.Append(" [").Append(Quote(module.name)).Append("] = [\n"); foreach (GameCodeAssembly assembly in module.assemblies) + { source.Append(" global::").Append(assembly.name).Append(".Generated.RuntimeModuleCatalog.assembly,\n"); + } source.Append(" ],\n"); } source.Append(" };\n}\n"); - await File.WriteAllTextAsync(Path.Combine(playerDirectory, "PlayerDeploymentDefinition.g.cs"), - source.ToString(), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(playerDirectory, "PlayerDeploymentDefinition.g.cs"), + source.ToString(), + cancellationToken + ).ConfigureAwait(false); } private static string Quote(string value) @@ -55,11 +77,17 @@ private static string Quote(string value) foreach (char character in value) { if (character is '\\' or '"') + { literal.Append('\\').Append(character); + } else if (char.IsControl(character)) - literal.Append("\\u").Append(((int)character).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); + { + literal.Append("\\u").Append(((int)character).ToString("x4", CultureInfo.InvariantCulture)); + } else + { literal.Append(character); + } } return literal.Append('"').ToString(); } diff --git a/build/pipeline/Inno.Build/GameBuildRequest.cs b/build/pipeline/Inno.Build/GameBuildRequest.cs index 30d419be2..4451d4234 100644 --- a/build/pipeline/Inno.Build/GameBuildRequest.cs +++ b/build/pipeline/Inno.Build/GameBuildRequest.cs @@ -27,9 +27,13 @@ public sealed class GameBuildRequest public void Validate() { if (profile is null) + { throw new InvalidDataException("A game build profile is required."); + } profile.Validate(); if (string.IsNullOrWhiteSpace(outputDirectory)) + { throw new InvalidDataException("A game output directory is required."); + } } } diff --git a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs index 4820bd5c0..b4f9b72ba 100644 --- a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs +++ b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs @@ -1,9 +1,8 @@ using System; using System.IO; - -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build; @@ -15,7 +14,9 @@ internal static async ValueTask MergeDirectoryAsync( CancellationToken cancellationToken ) { if (!Directory.Exists(source)) + { return; + } Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) { @@ -28,7 +29,9 @@ CancellationToken cancellationToken string target = Path.Combine(destination, Path.GetRelativePath(source, file)); Directory.CreateDirectory(Path.GetDirectoryName(target)!); if (File.Exists(target)) + { throw new IOException($"Target artifact '{Path.GetRelativePath(destination, target)}' collides with runtime content."); + } await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false); } } @@ -39,7 +42,9 @@ internal static async ValueTask CopyDirectoryAsync( CancellationToken cancellationToken ) { if (!Directory.Exists(source)) + { throw new DirectoryNotFoundException($"Build input directory '{source}' does not exist."); + } Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) { @@ -60,29 +65,32 @@ internal static async ValueTask CopyFileAsync( string destination, CancellationToken cancellationToken ) { - await using FileStream input = new( + await using var input = new FileStream( source, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); - await using FileStream output = new( + FileOptions.Asynchronous | FileOptions.SequentialScan + ); + await using var output = new FileStream( destination, FileMode.CreateNew, FileAccess.Write, FileShare.None, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); await output.FlushAsync(cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(source)); + } } internal static void InstallDirectoryAtomically( string source, string destination ) => AtomicDirectory.Install(source, destination); - } diff --git a/build/pipeline/Inno.Build/PlatformTargetDescriptor.cs b/build/pipeline/Inno.Build/PlatformTargetDescriptor.cs index b9219329a..ea8e1faf2 100644 --- a/build/pipeline/Inno.Build/PlatformTargetDescriptor.cs +++ b/build/pipeline/Inno.Build/PlatformTargetDescriptor.cs @@ -32,7 +32,7 @@ public sealed class PlatformTargetDescriptor /// An identity or required target fact is unassigned. /// public PlatformTargetDescriptor( - BuildTargetId id, + BuildTargetID id, string platform, string architecture, string abi, @@ -55,7 +55,7 @@ bool supportsEditor /// /// Gets the stable publication target identity. /// - public BuildTargetId id { get; } + public BuildTargetID id { get; } /// /// Gets the owning platform package. diff --git a/build/pipeline/Inno.Build/Player/IPlayerSupportPackProvisioner.cs b/build/pipeline/Inno.Build/Player/IPlayerSupportPackProvisioner.cs index 739140997..0b428ef99 100644 --- a/build/pipeline/Inno.Build/Player/IPlayerSupportPackProvisioner.cs +++ b/build/pipeline/Inno.Build/Player/IPlayerSupportPackProvisioner.cs @@ -24,7 +24,7 @@ public interface IPlayerSupportPackProvisioner /// An operation that completes after the pack has been installed. /// ValueTask ProvisionAsync( - BuildTargetId target, + BuildTargetID target, string supportPackRoot, CancellationToken cancellationToken = default ); diff --git a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs index cabc4682a..413a0816c 100644 --- a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs +++ b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs @@ -1,13 +1,14 @@ using System; -using System.Collections.Generic; +using System.Buffers.Binary; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build; @@ -16,12 +17,12 @@ namespace Inno.Build; /// public sealed class PlayerSupportPackCatalog { - private static readonly HashSet S_FORBIDDEN_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet FORBIDDEN_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) { ".cs", ".csproj", ".dbg", ".map", ".pdb", ".rsp", ".sln", ".xml" }; - private static readonly string[] S_FORBIDDEN_NAME_TOKENS = + private static readonly string[] FORBIDDEN_NAME_TOKENS = [ "Microsoft.CodeAnalysis", "Roslyn", @@ -35,7 +36,7 @@ public sealed class PlayerSupportPackCatalog ]; private readonly string m_root; - private readonly ConcurrentDictionary m_provisionGates = new(); + private readonly ConcurrentDictionary m_provisionGates = new(); /// /// Creates a catalog rooted at the directory containing target-specific Player Support Packs. @@ -83,7 +84,7 @@ public PlayerSupportPackCatalog(string root) /// Validation or selection was canceled. /// public async ValueTask SelectAsync( - BuildTargetId target, + BuildTargetID target, string fingerprint, IPlayerSupportPackValidator validator, Func verifyInputs, @@ -92,14 +93,24 @@ public async ValueTask SelectAsync( ArgumentNullException.ThrowIfNull(validator); ArgumentNullException.ThrowIfNull(verifyInputs); if (fingerprint is null || fingerprint.Length != 64 - || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character))) + || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new ArgumentException("A prepared Pack requires its exact content identity.", nameof(fingerprint)); + } cancellationToken.ThrowIfCancellationRequested(); string targetRoot = PathBoundary.Resolve(m_root, target.value); - using FileLease selection = await FileLease.AcquireAsync(Path.Combine(targetRoot, "current.lock"), - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); - PlayerSupportPackLease reading = AcquireArtifact(PathBoundary.Resolve(targetRoot, fingerprint), fingerprint, - target, validator, cancellationToken); + using FileLease selection = await FileLease.AcquireAsync( + Path.Combine(targetRoot, "current.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); + PlayerSupportPackLease reading = AcquireArtifact( + PathBoundary.Resolve(targetRoot, fingerprint), + fingerprint, + target, + validator, + cancellationToken + ); try { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); @@ -120,6 +131,12 @@ public async ValueTask SelectAsync( /// /// The platform and architecture identity of the required Support Pack. /// + /// + /// The target-owned validator for runtime or linker inputs. + /// + /// + /// Cancels ownership acquisition or complete content validation before returning a lease. + /// /// /// Reading ownership of the complete pack; dispose it after its final consumer finishes. /// @@ -129,12 +146,6 @@ public async ValueTask SelectAsync( /// /// Thrown when the pack is empty, contains build-time payload, or lacks its Player executable or native runtimes. /// - /// - /// The target-owned validator for runtime or linker inputs. - /// - /// - /// Cancels ownership acquisition or complete content validation before returning a lease. - /// /// /// Acquisition or validation was canceled; no reading ownership is transferred. /// @@ -142,7 +153,7 @@ public async ValueTask SelectAsync( /// Exclusive repair or retirement retains the artifact for more than thirty seconds. /// public PlayerSupportPackLease Acquire( - BuildTargetId target, + BuildTargetID target, IPlayerSupportPackValidator validator, CancellationToken cancellationToken = default ) { @@ -153,12 +164,15 @@ public PlayerSupportPackLease Acquire( if (!File.Exists(index)) { throw new DirectoryNotFoundException( - $"Player Support Pack '{target}' is not installed at '{targetRoot}'. " + - "Install or generate the target Support Pack before exporting."); + $"Player Support Pack '{target}' is not installed at '{targetRoot}'. " + + "Install or generate the target Support Pack before exporting." + ); } string fingerprint = File.ReadAllText(index); if (fingerprint.Length != 64 || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException($"Player Support Pack '{target}' has an invalid current fingerprint."); + } string directory = Path.Combine(targetRoot, fingerprint); return AcquireArtifact(directory, fingerprint, target, validator, cancellationToken); } @@ -176,13 +190,13 @@ public PlayerSupportPackLease Acquire( /// /// The target validator for runtime and linker inputs. /// - /// - /// Cancels validation or lease acquisition before selecting the completed pack. - /// /// /// Optional final source-input gate after output validation and any publication wait. /// Omit only when the caller exclusively owns a fully prepared tree with no external preparation inputs. /// + /// + /// Cancels validation or lease acquisition before selecting the completed pack. + /// /// /// Reading ownership of the selected immutable pack; earlier readers retain their own protection. /// @@ -196,11 +210,11 @@ public PlayerSupportPackLease Acquire( /// Cancellation occurred before the current index was committed. /// public async ValueTask PublishAsync( - BuildTargetId target, + BuildTargetID target, string stagingDirectory, IPlayerSupportPackValidator validator, - CancellationToken cancellationToken = default, - Func? verifyInputs = null + Func? verifyInputs = null, + CancellationToken cancellationToken = default ) { ArgumentException.ThrowIfNullOrWhiteSpace(stagingDirectory); ArgumentNullException.ThrowIfNull(validator); @@ -211,7 +225,10 @@ public async ValueTask PublishAsync( string targetRoot = Path.Combine(m_root, target.value); Directory.CreateDirectory(targetRoot); using FileLease ownership = await FileLease.AcquireAsync( - Path.Combine(targetRoot, "current.lock"), Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + Path.Combine(targetRoot, "current.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); string destination = Path.Combine(targetRoot, fingerprint); bool valid = false; if (Directory.Exists(destination)) @@ -219,7 +236,12 @@ public async ValueTask PublishAsync( try { using PlayerSupportPackLease existing = AcquireArtifact( - destination, fingerprint, target, validator, cancellationToken); + destination, + fingerprint, + target, + validator, + cancellationToken + ); valid = true; } catch (InvalidDataException) { } @@ -227,9 +249,14 @@ public async ValueTask PublishAsync( if (!valid) { using FileLease publication = await FileLease.AcquireAsync( - GetLeasePath(destination), TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); + GetLeasePath(destination), + TimeSpan.FromSeconds(30), + cancellationToken + ).ConfigureAwait(false); if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(targetRoot, destination); try @@ -242,12 +269,16 @@ public async ValueTask PublishAsync( } } else if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } PlayerSupportPackLease reading = AcquireArtifact(destination, fingerprint, target, validator, cancellationToken); try { if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); SelectCurrent(targetRoot, fingerprint); return reading; @@ -259,22 +290,50 @@ public async ValueTask PublishAsync( } } + internal async ValueTask ResolveOrProvisionAsync( + BuildTargetID target, + IPlayerSupportPackValidator validator, + IPlayerSupportPackProvisioner? provisioner, + CancellationToken cancellationToken + ) { + cancellationToken.ThrowIfCancellationRequested(); + if (provisioner is null) + { + return Acquire(target, validator, cancellationToken); + } + + SemaphoreSlim gate = m_provisionGates.GetOrAdd(target, static _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // The source provider checks its current SDK, code and native inputs before selecting a pack. + await provisioner.ProvisionAsync(target, m_root, cancellationToken).ConfigureAwait(false); + return Acquire(target, validator, cancellationToken); + } + finally + { + gate.Release(); + } + } + private static void SelectCurrent( string targetRoot, string fingerprint ) { string index = Path.Combine(targetRoot, "current"); if (!File.Exists(index) || File.ReadAllText(index) != fingerprint) + { AtomicFile.WriteAllBytes(index, Encoding.UTF8.GetBytes(fingerprint)); + } } private static async ValueTask VerifySelectionInputsAsync( Func verifyInputs, - CancellationToken cancellation + CancellationToken cancellationToken ) { try { - await verifyInputs(cancellation).ConfigureAwait(false); + await verifyInputs(cancellationToken).ConfigureAwait(false); } catch (Exception failure) when (failure is not OperationCanceledException) { @@ -285,23 +344,31 @@ CancellationToken cancellation private static PlayerSupportPackLease AcquireArtifact( string directory, string fingerprint, - BuildTargetId target, + BuildTargetID target, IPlayerSupportPackValidator validator, CancellationToken cancellationToken ) { string path = GetLeasePath(directory); if (!File.Exists(path)) { - using FileLease initializer = FileLease.AcquireAsync(path, - TimeSpan.FromSeconds(30), cancellationToken).GetAwaiter().GetResult(); + using FileLease initializer = FileLease.AcquireAsync( + path, + TimeSpan.FromSeconds(30), + cancellationToken + ).GetAwaiter().GetResult(); } - FileLease lease = FileLease.AcquireSharedAsync(path, - TimeSpan.FromSeconds(30), cancellationToken).GetAwaiter().GetResult(); + FileLease lease = FileLease.AcquireSharedAsync( + path, + TimeSpan.FromSeconds(30), + cancellationToken + ).GetAwaiter().GetResult(); try { ValidateDirectory(directory, target, validator); if (ComputeFingerprint(directory, cancellationToken) != fingerprint) + { throw new InvalidDataException($"Player Support Pack '{target}' no longer matches its immutable fingerprint."); + } return new PlayerSupportPackLease(directory, lease); } catch @@ -315,60 +382,43 @@ CancellationToken cancellationToken private static void ValidateDirectory( string directory, - BuildTargetId target, + BuildTargetID target, IPlayerSupportPackValidator validator ) { if (!Directory.Exists(directory)) + { throw new InvalidDataException($"Player Support Pack '{target}' points to a missing artifact '{directory}'."); + } string[] files = PathBoundary.EnumerateFiles(directory).ToArray(); if (files.Length == 0) + { throw new InvalidDataException($"Player Support Pack '{target}' is empty."); + } foreach (string file in files) { string relativePath = Path.GetRelativePath(directory, file); if (relativePath.StartsWith("PlayerLink" + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { continue; + } string name = Path.GetFileName(file); - if (S_FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(name)) - || S_FORBIDDEN_NAME_TOKENS.Any(token => name.Contains(token, StringComparison.OrdinalIgnoreCase))) - { + if (FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(name)) + || FORBIDDEN_NAME_TOKENS.Any(token => name.Contains(token, StringComparison.OrdinalIgnoreCase)) + ) { throw new InvalidDataException( - $"Player Support Pack '{target}' contains forbidden build-time file '{name}'."); + $"Player Support Pack '{target}' contains forbidden build-time file '{name}'." + ); } } string referenceDirectory = Path.Combine(directory, "References"); if (!Directory.Exists(referenceDirectory) - || !Directory.EnumerateFiles(referenceDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly).Any()) - { + || !Directory.EnumerateFiles(referenceDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly).Any() + ) { throw new InvalidDataException($"Player Support Pack '{target}' has no target compilation references."); } validator.Validate(directory); } - internal async ValueTask ResolveOrProvisionAsync( - BuildTargetId target, - IPlayerSupportPackValidator validator, - IPlayerSupportPackProvisioner? provisioner, - CancellationToken cancellationToken - ) { - cancellationToken.ThrowIfCancellationRequested(); - if (provisioner is null) - return Acquire(target, validator, cancellationToken); - - SemaphoreSlim gate = m_provisionGates.GetOrAdd(target, static _ => new SemaphoreSlim(1, 1)); - await gate.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - // The source provider checks its current SDK, code and native inputs before selecting a pack. - await provisioner.ProvisionAsync(target, m_root, cancellationToken).ConfigureAwait(false); - return Acquire(target, validator, cancellationToken); - } - finally - { - gate.Release(); - } - } - private static string ComputeFingerprint( string directory, CancellationToken cancellationToken @@ -376,12 +426,12 @@ CancellationToken cancellationToken using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Span length = stackalloc byte[sizeof(int)]; foreach (string file in PathBoundary.EnumerateFiles(directory) - .OrderBy(path => Path.GetRelativePath(directory, path).Replace('\\', '/'), StringComparer.Ordinal)) - { + .OrderBy(path => Path.GetRelativePath(directory, path).Replace('\\', '/'), StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(directory, file).Replace('\\', '/'); byte[] path = Encoding.UTF8.GetBytes(relative); - System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(length, path.Length); + BinaryPrimitives.WriteInt32LittleEndian(length, path.Length); hash.AppendData(length); hash.AppendData(path); using FileStream input = File.OpenRead(file); diff --git a/build/pipeline/Inno.Build/PluginBuildRequest.cs b/build/pipeline/Inno.Build/PluginBuildRequest.cs index e9e5fa32f..4393c47df 100644 --- a/build/pipeline/Inno.Build/PluginBuildRequest.cs +++ b/build/pipeline/Inno.Build/PluginBuildRequest.cs @@ -1,7 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Collections.Generic; namespace Inno.Build; @@ -13,7 +13,7 @@ public sealed class PluginBuildRequest /// /// Gets or initializes the globally stable lowercase Plugin identity. /// - public required string pluginId { get; init; } + public required string pluginID { get; init; } /// /// Gets or initializes the user-facing Plugin name. @@ -34,7 +34,7 @@ public sealed class PluginBuildRequest /// Gets or initializes the installed plugins this package actually requires. /// Their transitive dependencies are included in the package manifest. /// - public IReadOnlyList dependencies { get; init; } = Array.Empty(); + public IReadOnlyList dependencies { get; init; } = []; /// /// Validates package identity and destination syntax. @@ -44,24 +44,28 @@ public sealed class PluginBuildRequest /// public void Validate() { - if (string.IsNullOrWhiteSpace(pluginId) - || pluginId == "project" - || pluginId.Any(static character => + if (string.IsNullOrWhiteSpace(pluginID) + || pluginID == "project" + || pluginID.Any(static character => !(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { + || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("Plugin ID must be a non-reserved lowercase portable identifier."); } if (string.IsNullOrWhiteSpace(displayName)) + { throw new InvalidDataException("A Plugin display name is required."); + } if (string.IsNullOrWhiteSpace(outputPath) - || !string.Equals(Path.GetExtension(outputPath), ".iplugin", StringComparison.OrdinalIgnoreCase)) - { + || !string.Equals(Path.GetExtension(outputPath), ".iplugin", StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidDataException("Plugin destination must use the .iplugin extension."); } if (dependencies is null || dependencies.Any(string.IsNullOrWhiteSpace) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count) + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count + ) { throw new InvalidDataException("Plugin dependencies must be distinct non-empty IDs."); + } } } diff --git a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs index 54c04116c..4f9fdeff3 100644 --- a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs +++ b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs @@ -8,18 +8,19 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Plugins; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Plugins; +using Inno.Plugins.Authoring; namespace Inno.Build; internal sealed class PluginPackageBuilder { - private static readonly DateTimeOffset S_ARCHIVE_TIME = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); - private static readonly HashSet S_FORBIDDEN_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) + private static readonly DateTimeOffset ARCHIVE_TIME = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static readonly HashSet FORBIDDEN_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) { ".dll", ".exe", ".dylib", ".so", ".a", ".lib", ".pdb" }; @@ -49,11 +50,13 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(request); request.Validate(); if (!m_assets.isInitialized) + { throw new InvalidOperationException("Plugin build requires an active authoring asset database."); + } if (m_plugins.activePlugins.Any(plugin => - string.Equals(plugin.manifest.pluginId, request.pluginId, StringComparison.Ordinal))) - { - throw new InvalidOperationException($"Plugin ID '{request.pluginId}' is already active in this project."); + string.Equals(plugin.manifest.pluginId, request.pluginID, StringComparison.Ordinal)) + ) { + throw new InvalidOperationException($"Plugin ID '{request.pluginID}' is already active in this project."); } string destination = Path.GetFullPath(request.outputPath); ValidateDestination(destination); @@ -64,13 +67,14 @@ CancellationToken cancellationToken string temporary = destination + ".staging-" + Guid.NewGuid().ToString("N"); try { - await using (FileStream stream = new( - temporary, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) + await using (var stream = new FileStream( + temporary, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { await WriteBytesAsync(archive, "Plugin.inno", plan.manifest, cancellationToken) @@ -80,41 +84,50 @@ await WriteBytesAsync(archive, "Plugin.inno", plan.manifest, cancellationToken) { await WriteSourceAsync(archive, source, cancellationToken).ConfigureAwait(false); completed++; - progress?.Report(new BuildProgress( - "project-content", - 0.15d + 0.5d * completed / Math.Max(1d, plan.projectEntries.Count), - $"Packaging project source {completed}/{plan.projectEntries.Count}.")); + progress?.Report( + new BuildProgress( + "project-content", + 0.15d + 0.5d * completed / Math.Max(1d, plan.projectEntries.Count), + $"Packaging project source {completed}/{plan.projectEntries.Count}." + ) + ); } for (int index = 0; index < plan.dependencies.Count; index++) { PluginDependencyPlan dependency = plan.dependencies[index]; ZipArchiveEntry packageEntry = archive.CreateEntry( - $"Dependencies/{dependency.pluginId}.iplugin", - CompressionLevel.Optimal); - packageEntry.LastWriteTime = S_ARCHIVE_TIME; + $"Dependencies/{dependency.pluginID}.iplugin", + CompressionLevel.Optimal + ); + packageEntry.LastWriteTime = ARCHIVE_TIME; await using Stream packageStream = packageEntry.Open(); using var nested = new ZipArchive(packageStream, ZipArchiveMode.Create, leaveOpen: true); await WriteBytesAsync(nested, "Plugin.inno", dependency.manifest, cancellationToken) .ConfigureAwait(false); foreach (SourceEntry source in dependency.entries) + { await WriteSourceAsync(nested, source, cancellationToken).ConfigureAwait(false); - progress?.Report(new BuildProgress( - "dependencies", - 0.7d + 0.2d * (index + 1) / Math.Max(1d, plan.dependencies.Count), - $"Embedded dependency {index + 1}/{plan.dependencies.Count}.")); + } + progress?.Report( + new BuildProgress( + "dependencies", + 0.7d + 0.2d * (index + 1) / Math.Max(1d, plan.dependencies.Count), + $"Embedded dependency {index + 1}/{plan.dependencies.Count}." + ) + ); } } EnsurePlanUnchanged(plan); cancellationToken.ThrowIfCancellationRequested(); string contentHash; - await using (FileStream stream = new( - temporary, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (var stream = new FileStream( + temporary, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { contentHash = Convert.ToHexString(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)); } AtomicFile.Install(temporary, destination); @@ -126,80 +139,97 @@ await WriteBytesAsync(nested, "Plugin.inno", dependency.manifest, cancellationTo plan.assetCount, artifactBundleCount: 0, runtimeAssemblyCount: 0, - plan.dependencies.Count); + plan.dependencies.Count + ); } finally { if (File.Exists(temporary)) + { File.Delete(temporary); + } } } private PluginPackagePlan CapturePlan(PluginBuildRequest request) { - AssetSourceMount projectMount = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount projectMount = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceID.project); PluginCandidate[] installedPlugins = m_plugins.activePlugins.ToArray(); ValidateDependencyGraph(installedPlugins); - var selectedIds = new HashSet(StringComparer.Ordinal); - var installedById = installedPlugins.ToDictionary( - static plugin => plugin.manifest.pluginId, StringComparer.Ordinal); + var selectedIDs = new HashSet(StringComparer.Ordinal); + Dictionary installedByID = installedPlugins.ToDictionary( + static plugin => plugin.manifest.pluginId, + StringComparer.Ordinal + ); void SelectDependency(string id) { - if (!installedById.TryGetValue(id, out PluginCandidate? plugin)) + if (!installedByID.TryGetValue(id, out PluginCandidate? plugin)) + { throw new InvalidOperationException($"Declared plugin dependency '{id}' is not installed and active."); - if (!selectedIds.Add(id)) + } + if (!selectedIDs.Add(id)) + { return; + } foreach (string upstream in plugin.manifest.dependencies) + { SelectDependency(upstream); + } } foreach (string id in request.dependencies) + { SelectDependency(id); + } PluginCandidate[] activePlugins = installedPlugins - .Where(plugin => selectedIds.Contains(plugin.manifest.pluginId)) + .Where(plugin => selectedIDs.Contains(plugin.manifest.pluginId)) .ToArray(); - string[] dependencyIds = activePlugins.Select(static plugin => plugin.manifest.pluginId).ToArray(); + string[] dependencyIDs = activePlugins.Select(static plugin => plugin.manifest.pluginId).ToArray(); ProjectSettingsDocument settingsDocument = m_serialization.Deserialize( - m_settings.CaptureDocument()); + m_settings.CaptureDocument() + ); string[] overrides = activePlugins .Where(plugin => plugin.manifest.settingContributions.Any(contribution => settingsDocument.overrides.Any(project => project.id == contribution.id))) .Select(static plugin => plugin.manifest.pluginId) .ToArray(); - HashSet dependencySet = dependencyIds.ToHashSet(StringComparer.Ordinal); + HashSet dependencySet = dependencyIDs.ToHashSet(StringComparer.Ordinal); HashSet overrideSet = overrides.ToHashSet(StringComparer.Ordinal); - var settings = new List(); + List settings = []; foreach (ProjectSettingRecord record in settingsDocument.overrides - .OrderBy(static value => value.id.value, StringComparer.Ordinal)) - { + .OrderBy(static value => value.id.value, StringComparer.Ordinal) + ) { if (m_settings.TryCapture( - record.id, - request.pluginId, - dependencySet, - overrideSet, - out ProjectSettingRecord captured)) - { + record.id, + request.pluginID, + dependencySet, + overrideSet, + out ProjectSettingRecord captured + )) { settings.Add(captured); } } AssetFileEntry[] projectFiles = m_assets.GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.source == AssetSourceId.project) + .Where(static entry => entry.source == AssetSourceID.project) .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) .ToArray(); if (projectFiles.Length == 0) + { throw new InvalidOperationException("The project contains no source content to export."); + } string[] relativeFiles = projectFiles.Select(static entry => entry.assetPath.localPath).ToArray(); foreach (string relative in relativeFiles) { - if (S_FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(relative))) + if (FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(relative))) + { throw new InvalidOperationException($"Plugin content '{relative}' is a forbidden binary."); + } } var manifest = new PluginManifest { - pluginId = request.pluginId, + pluginId = request.pluginID, displayName = request.displayName, - dependencies = dependencyIds, + dependencies = dependencyIDs, overrides = overrides, contentRoots = ["Assets"], assemblyDefinitions = relativeFiles @@ -209,7 +239,7 @@ void SelectDependency(string id) settingContributions = settings.ToArray() }; manifest.Validate(); - var projectEntries = new List(); + List projectEntries = []; foreach (string directory in CollectDirectories(relativeFiles)) { string metadata = Path.Combine(projectMount.rootPath, directory.Replace('/', Path.DirectorySeparatorChar)) + ".imeta"; @@ -226,25 +256,27 @@ void SelectDependency(string id) right ) => StringComparer.Ordinal.Compare(left.archivePath, right.archivePath)); - var dependencies = new List(); + List dependencies = []; if (request.includeDependencies) { foreach (PluginCandidate plugin in activePlugins) { - SourceEntry[] entries = Directory.EnumerateFiles( - plugin.sourceMount.rootPath, - "*", - SearchOption.AllDirectories) + SourceEntry[] entries = Directory + .EnumerateFiles(plugin.sourceMount.rootPath, "*", SearchOption.AllDirectories) .Select(path => SourceEntry.Capture( path, - "Assets/" + Path.GetRelativePath(plugin.sourceMount.rootPath, path).Replace('\\', '/'))) + "Assets/" + Path.GetRelativePath(plugin.sourceMount.rootPath, path).Replace('\\', '/') + )) .OrderBy(static value => value.archivePath, StringComparer.Ordinal) .ToArray(); - dependencies.Add(new PluginDependencyPlan( - plugin.manifest.pluginId, - plugin.contentHash, - m_serialization.Serialize(plugin.manifest), - entries)); + dependencies.Add( + new PluginDependencyPlan( + plugin.manifest.pluginId, + plugin.contentHash, + m_serialization.Serialize(plugin.manifest), + entries + ) + ); } } return new PluginPackagePlan( @@ -252,7 +284,48 @@ void SelectDependency(string id) projectEntries, dependencies, projectFiles.Length, - installedPlugins.Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)).ToArray()); + installedPlugins.Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)).ToArray() + ); + } + + private void EnsurePlanUnchanged(PluginPackagePlan plan) + { + foreach (SourceEntry source in plan.projectEntries) + { + source.EnsureUnchanged(); + } + foreach (PluginDependencyPlan dependency in plan.dependencies) + { + foreach (SourceEntry source in dependency.entries) + { + source.EnsureUnchanged(); + } + } + (string pluginID, string contentHash)[] current = m_plugins.activePlugins + .Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)) + .ToArray(); + if (!plan.activePlugins.SequenceEqual(current)) + { + throw new InvalidOperationException("The active Plugin generation changed during package creation."); + } + } + + private void ValidateDestination(string destination) + { + List protectedRoots = m_assets.sourceMounts + .Select(static mount => mount.rootPath) + .Append(m_assets.libraryRoot) + .ToList(); + string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; + if (projectRoot is not null) + { + protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); + } + string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, destination)); + if (conflict is not null) + { + throw new InvalidOperationException($"Plugin output cannot be written inside '{Path.GetFullPath(conflict)}'."); + } } private static async ValueTask WriteSourceAsync( @@ -262,15 +335,16 @@ CancellationToken cancellationToken ) { source.EnsureUnchanged(); ZipArchiveEntry entry = archive.CreateEntry(source.archivePath, CompressionLevel.Optimal); - entry.LastWriteTime = S_ARCHIVE_TIME; + entry.LastWriteTime = ARCHIVE_TIME; await using Stream output = entry.Open(); - await using FileStream input = new( + await using var input = new FileStream( source.sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); source.EnsureUnchanged(); } @@ -282,48 +356,41 @@ private static async ValueTask WriteBytesAsync( CancellationToken cancellationToken ) { ZipArchiveEntry entry = archive.CreateEntry(path, CompressionLevel.Optimal); - entry.LastWriteTime = S_ARCHIVE_TIME; + entry.LastWriteTime = ARCHIVE_TIME; await using Stream output = entry.Open(); await output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); } - private void EnsurePlanUnchanged(PluginPackagePlan plan) - { - foreach (SourceEntry source in plan.projectEntries) - source.EnsureUnchanged(); - foreach (PluginDependencyPlan dependency in plan.dependencies) - { - foreach (SourceEntry source in dependency.entries) - source.EnsureUnchanged(); - } - (string pluginId, string contentHash)[] current = m_plugins.activePlugins - .Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)) - .ToArray(); - if (!plan.activePlugins.SequenceEqual(current)) - throw new InvalidOperationException("The active Plugin generation changed during package creation."); - } - private static void ValidateDependencyGraph(IReadOnlyList plugins) { - Dictionary byId = plugins.ToDictionary( + Dictionary byID = plugins.ToDictionary( static value => value.manifest.pluginId, - StringComparer.Ordinal); + StringComparer.Ordinal + ); var completed = new HashSet(StringComparer.Ordinal); var visiting = new HashSet(StringComparer.Ordinal); foreach (PluginCandidate plugin in plugins) + { Visit(plugin.manifest.pluginId); + } void Visit(string id) { if (completed.Contains(id)) + { return; + } if (!visiting.Add(id)) + { throw new InvalidOperationException($"Plugin dependency graph contains a cycle at '{id}'."); - PluginCandidate plugin = byId[id]; + } + PluginCandidate plugin = byID[id]; foreach (string dependency in plugin.manifest.dependencies) { - if (!byId.ContainsKey(dependency)) + if (!byID.ContainsKey(dependency)) + { throw new InvalidOperationException($"Plugin '{id}' requires unavailable dependency '{dependency}'."); + } Visit(dependency); } visiting.Remove(id); @@ -346,28 +413,14 @@ private static IEnumerable CollectDirectories(IEnumerable files) return result; } - private void ValidateDestination(string destination) - { - var protectedRoots = m_assets.sourceMounts - .Select(static mount => mount.rootPath) - .Append(m_assets.libraryRoot) - .ToList(); - string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; - if (projectRoot is not null) - protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); - string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, destination)); - if (conflict is not null) - throw new InvalidOperationException($"Plugin output cannot be written inside '{Path.GetFullPath(conflict)}'."); - } - private static bool IsWithin( string root, string candidate ) { string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; return string.Equals(candidate, normalizedRoot, comparison) || candidate.StartsWith(normalizedRoot + Path.DirectorySeparatorChar, comparison); } @@ -377,11 +430,11 @@ private sealed record PluginPackagePlan( IReadOnlyList projectEntries, IReadOnlyList dependencies, int assetCount, - IReadOnlyList<(string pluginId, string contentHash)> activePlugins + IReadOnlyList<(string pluginID, string contentHash)> activePlugins ); private sealed record PluginDependencyPlan( - string pluginId, + string pluginID, string contentHash, byte[] manifest, IReadOnlyList entries @@ -393,25 +446,25 @@ private sealed record SourceEntry( long length, DateTime lastWriteTimeUtc ) { + internal void EnsureUnchanged() + { + var info = new FileInfo(sourcePath); + if (!info.Exists || info.Length != length || info.LastWriteTimeUtc != lastWriteTimeUtc) + { + throw new InvalidOperationException($"Plugin source '{sourcePath}' changed during package creation."); + } + } + internal static SourceEntry Capture( string sourcePath, string archivePath ) { var info = new FileInfo(sourcePath); if (!info.Exists) + { throw new InvalidOperationException($"Plugin source dependency '{sourcePath}' is missing."); - return new SourceEntry( - info.FullName, - archivePath.Replace('\\', '/'), - info.Length, - info.LastWriteTimeUtc); - } - - internal void EnsureUnchanged() - { - var info = new FileInfo(sourcePath); - if (!info.Exists || info.Length != length || info.LastWriteTimeUtc != lastWriteTimeUtc) - throw new InvalidOperationException($"Plugin source '{sourcePath}' changed during package creation."); + } + return new SourceEntry(info.FullName, archivePath.Replace('\\', '/'), info.Length, info.LastWriteTimeUtc); } } } diff --git a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs index f4dafb011..876d1eaab 100644 --- a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs +++ b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.Json; using System.Threading; @@ -41,13 +41,17 @@ string projectRoot m_projectRoot = Path.GetFullPath(projectRoot); } - /// + /// public ScriptCompilationInputs Capture(CancellationToken cancellationToken = default) => CaptureAsync(cancellationToken).GetAwaiter().GetResult(); private async Task CaptureAsync(CancellationToken cancellationToken) { - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(m_dotnetHost, m_projectRoot, cancellationToken).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( + m_dotnetHost, + m_projectRoot, + cancellationToken + ).ConfigureAwait(false); string requests = Path.Combine(m_projectRoot, "Library", "Scripting", "SdkInputs"); using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(requests, cancellationToken).ConfigureAwait(false); string project = Path.Combine(owner.directory, "Framework.csproj"); @@ -71,23 +75,44 @@ await File.WriteAllTextAsync(project, """ """, cancellationToken).ConfigureAwait(false); - _ = await RunSdkAsync(sdk, + _ = await RunSdkAsync( + sdk, [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - owner.directory, cancellationToken).ConfigureAwait(false); - string output = await RunSdkAsync(sdk, - [sdk.cliPath, "msbuild", project, "-nologo", "-m:1", "-nr:false", "-t:CaptureScriptFramework", - "-getItem:ReferencePath", "-getProperty:TargetFramework,LangVersion,DefineConstants,NETCoreSdkVersion"], - owner.directory, cancellationToken).ConfigureAwait(false); + owner.directory, + cancellationToken + ).ConfigureAwait(false); + string output = await RunSdkAsync( + sdk, + [ + sdk.cliPath, + "msbuild", + project, + "-nologo", + "-m:1", + "-nr:false", + "-t:CaptureScriptFramework", + "-getItem:ReferencePath", + "-getProperty:TargetFramework,LangVersion,DefineConstants,NETCoreSdkVersion" + ], + owner.directory, + cancellationToken + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); if (properties.GetProperty("TargetFramework").GetString() != "net10.0" || properties.GetProperty("LangVersion").GetString() != "14.0" - || properties.GetProperty("NETCoreSdkVersion").GetString() != sdk.sdkIdentity) + || properties.GetProperty("NETCoreSdkVersion").GetString() != sdk.sdkIdentity + ) { throw new InvalidDataException("SDK scripting evaluation returned an inconsistent framework, language or SDK identity."); - return new ScriptCompilationInputs(sdk.sdkIdentity, - document.RootElement.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray() + } + return new ScriptCompilationInputs( + sdk.sdkIdentity, + document.RootElement.GetProperty("Items") + .GetProperty("ReferencePath") + .EnumerateArray() .Select(static item => item.GetProperty("FullPath").GetString()!), - properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries)); + properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries) + ); } private static async Task RunSdkAsync( @@ -100,13 +125,23 @@ CancellationToken cancellationToken using var errors = new StringWriter(); try { - await ToolchainEnvironment.RunAsync(sdk.hostPath, arguments, directory, cancellationToken, - DotNetSdkEnvironment.Create(sdk.hostPath), output, errors).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + arguments, + directory, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors, + cancellationToken + ).ConfigureAwait(false); return output.ToString(); } catch (InvalidOperationException failure) { - throw new InvalidOperationException($"Script framework evaluation with SDK '{sdk.sdkIdentity}' failed.\n{output}{errors}", failure); + throw new InvalidOperationException( + $"Script framework evaluation with SDK '{sdk.sdkIdentity}' failed.\n{output}{errors}", + failure + ); } } } diff --git a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs index e8efd5822..9e61dc407 100644 --- a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs +++ b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -20,7 +21,7 @@ internal static async ValueTask ComputeAsync( CancellationToken cancellationToken ) { using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - Append(hash, assetRevision.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Append(hash, assetRevision.ToString(CultureInfo.InvariantCulture)); hash.AppendData(projectSettings.Span); foreach (PluginCandidate plugin in plugins) { @@ -31,13 +32,14 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); Append(hash, Path.GetFileName(assembly)); - await using FileStream stream = new( + await using var stream = new FileStream( assembly, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); byte[] fileHash = await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false); hash.AppendData(fileHash); } @@ -49,12 +51,14 @@ internal static bool MatchesPlugins( IReadOnlyList actual ) { if (expected.Count != actual.Count) + { return false; + } for (int index = 0; index < expected.Count; index++) { if (!string.Equals(expected[index].manifest.pluginId, actual[index].manifest.pluginId, StringComparison.Ordinal) - || !string.Equals(expected[index].contentHash, actual[index].contentHash, StringComparison.Ordinal)) - { + || !string.Equals(expected[index].contentHash, actual[index].contentHash, StringComparison.Ordinal) + ) { return false; } } diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs index 8514cfdf2..b11bfa544 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs @@ -20,9 +20,6 @@ public static class StandardNativeComponents /// /// Composes the standard Player's reusable native components with explicit deployment policies. /// - /// - /// A fresh immutable Player plan without resolving tools or touching source files. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -32,6 +29,9 @@ public static class StandardNativeComponents /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A fresh immutable Player plan without resolving tools or touching source files. + /// public static ProductNativeBuildPlan CreatePlayer( BgfxNativeBuildProfile profile, Func options, @@ -41,9 +41,6 @@ public static ProductNativeBuildPlan CreatePlayer( /// /// Selects only the offline graphics compiler component needed for shader publication. /// - /// - /// An immutable tool product without runtime or Editor presentation dependencies. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -53,6 +50,9 @@ public static ProductNativeBuildPlan CreatePlayer( /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// An immutable tool product without runtime or Editor presentation dependencies. + /// public static ProductNativeBuildPlan CreateShaderTools( BgfxNativeBuildProfile profile, Func options, @@ -62,9 +62,6 @@ public static ProductNativeBuildPlan CreateShaderTools( /// /// Composes the shared runtime closure and the Editor's presentation and authoring tools. /// - /// - /// A fresh immutable Editor plan with the ImGuizmo dependency declared explicitly. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -74,6 +71,9 @@ public static ProductNativeBuildPlan CreateShaderTools( /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A fresh immutable Editor plan with the ImGuizmo dependency declared explicitly. + /// public static ProductNativeBuildPlan CreateEditor( BgfxNativeBuildProfile profile, Func options, @@ -81,48 +81,62 @@ public static ProductNativeBuildPlan CreateEditor( ) { List steps = CreatePlayerSteps(RequireProfile(profile), options, layout); steps.Add(CreateShaderToolsStep(profile, options, layout)); - steps.Add(new("cimgui", ImGuiToolchain.componentDescriptor, options("cimgui"), [], - static ( - context, - dependencies, - token - ) => ImGuiToolchain.BuildAsync(context, token), - ImGuiToolchain.CreateRecipe, - ( - relative, - target - ) => layout("cimgui", relative, target))); - steps.Add(new("cimguizmo", ImGuizmoToolchain.componentDescriptor, options("cimguizmo"), ["cimgui"], - static ( - context, - dependencies, - token - ) => ImGuizmoToolchain.BuildAsync(context, dependencies["cimgui"], token), - ImGuizmoToolchain.CreateRecipe, - ( - relative, - target - ) => layout("cimguizmo", relative, target), - bindDependencies: static ( - context, - recipe, - dependencies - ) => ImGuizmoToolchain.BindImGui(context, recipe, dependencies["cimgui"]))); + steps.Add( + new ProductNativeBuildStep( + "cimgui", + ImGuiToolchain.componentDescriptor, + options("cimgui"), + [], + static ( + context, + dependencies, + token + ) => ImGuiToolchain.BuildAsync(context, token), + ImGuiToolchain.CreateRecipe, + ( + relative, + target + ) => layout("cimgui", relative, target) + ) + ); + steps.Add( + new ProductNativeBuildStep( + "cimguizmo", + ImGuizmoToolchain.componentDescriptor, + options("cimguizmo"), + ["cimgui"], + static ( + context, + dependencies, + token + ) => ImGuizmoToolchain.BuildAsync(context, dependencies["cimgui"], token), + ImGuizmoToolchain.CreateRecipe, + ( + relative, + target + ) => layout("cimguizmo", relative, target), + bindDependencies: static ( + context, + recipe, + dependencies + ) => ImGuizmoToolchain.BindImGui(context, recipe, dependencies["cimgui"]) + ) + ); return new("editor", steps, StandardNativeDeployment.CreateMetadata); } /// /// Declares the real static component closure consumed by an explicit aggregate executor. /// - /// - /// A Player closure with static recipes and no unused standalone producers. - /// /// /// The platform-owned configuration for each named component. /// /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A Player closure with static recipes and no unused standalone producers. + /// public static ProductNativeBuildPlan CreateStaticPlayer( Func options, Func layout @@ -131,7 +145,9 @@ public static ProductNativeBuildPlan CreateStaticPlayer( ArgumentNullException.ThrowIfNull(layout); List steps = CreatePlayerSteps(null, options, layout); if (steps.Any(static step => step.options.libraryKind != NativeLibraryKind.Static)) + { throw new ArgumentException("Static aggregation requires explicit static component linkage.", nameof(options)); + } return new("player", steps); } @@ -145,26 +161,34 @@ private static ProductNativeBuildStep CreateShaderToolsStep( BgfxNativeBuildProfile profile, Func options, Func layout - ) => new("bgfx-tools", BgfxToolsBuild.componentDescriptor, options("bgfx-tools"), [], - ( - context, - dependencies, - token - ) => BgfxToolsBuild.BuildAsync(context, profile, token), - context => BgfxToolsBuild.CreateRecipe(context, profile), - ( - relative, - target - ) => layout("bgfx-tools", relative, target), - configuration: "release"); + ) => new( + "bgfx-tools", + BgfxToolsBuild.componentDescriptor, + options("bgfx-tools"), + [], + ( + context, + dependencies, + token + ) => BgfxToolsBuild.BuildAsync(context, profile, token), + context => BgfxToolsBuild.CreateRecipe(context, profile), + ( + relative, + target + ) => layout("bgfx-tools", relative, target), + configuration: "release" + ); private static List CreatePlayerSteps( BgfxNativeBuildProfile? profile, Func options, Func layout - ) => - [ - new("bgfx", BgfxNativeBuild.componentDescriptor, options("bgfx"), [], + ) => [ + new ProductNativeBuildStep( + "bgfx", + BgfxNativeBuild.componentDescriptor, + options("bgfx"), + [], profile is null ? null : ( context, dependencies, @@ -174,8 +198,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("bgfx", relative, target)), - new("sdl3", Sdl3Toolchain.componentDescriptor, options("sdl3"), [], + ) => layout("bgfx", relative, target) + ), + new ProductNativeBuildStep( + "sdl3", + Sdl3Toolchain.componentDescriptor, + options("sdl3"), + [], profile is null ? null : static ( context, dependencies, @@ -185,8 +214,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("sdl3", relative, target)), - new("miniaudio", MiniAudioToolchain.componentDescriptor, options("miniaudio"), [], + ) => layout("sdl3", relative, target) + ), + new ProductNativeBuildStep( + "miniaudio", + MiniAudioToolchain.componentDescriptor, + options("miniaudio"), + [], profile is null ? null : static ( context, dependencies, @@ -196,8 +230,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("miniaudio", relative, target)), - new("text", TextToolchain.componentDescriptor, options("text"), [], + ) => layout("miniaudio", relative, target) + ), + new ProductNativeBuildStep( + "text", + TextToolchain.componentDescriptor, + options("text"), + [], profile is null ? null : static ( context, dependencies, @@ -207,18 +246,23 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("text", relative, target)), - new("ui", UiToolchain.componentDescriptor, options("ui"), [], + ) => layout("text", relative, target) + ), + new ProductNativeBuildStep( + "ui", + UIToolchain.componentDescriptor, + options("ui"), + [], profile is null ? null : static ( context, dependencies, token - ) => UiToolchain.BuildAsync(context, token), - profile is null ? null : UiToolchain.CreateRecipe, + ) => UIToolchain.BuildAsync(context, token), + profile is null ? null : UIToolchain.CreateRecipe, ( relative, target - ) => layout("ui", relative, target)) + ) => layout("ui", relative, target) + ) ]; - } diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs index a7353f166..bdaa2d1f8 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs @@ -26,7 +26,7 @@ public static class StandardNativeDeployment /// A validator that rejects foreign or incomplete deployment metadata. /// public static IPlayerSupportPackValidator CreateValidator( - BuildTargetId target, + BuildTargetID target, string extension ) => new DeploymentValidator(target, extension); @@ -46,7 +46,7 @@ public static IReadOnlyDictionary CreateMetadata( IReadOnlyList products, IReadOnlyDictionary payloads ) { - string target = products.Select(static product => product.targetId).Distinct(StringComparer.Ordinal).Single(); + string target = products.Select(static product => product.targetID).Distinct(StringComparer.Ordinal).Single(); var libraries = new Dictionary(StringComparer.Ordinal); var files = new Dictionary(StringComparer.Ordinal); foreach ((string relative, string source) in payloads.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) @@ -57,8 +57,10 @@ IReadOnlyDictionary payloads Add(files, Path.GetFileNameWithoutExtension(name), portable); NativeBuildProduct product = products.Single(product => product.files.Contains(source, StringComparer.Ordinal)); if (product.artifacts.Single(artifact => artifact.file == source).role != NativeArtifactRole.SharedLibrary - || product.sharedLibraryExtension is not string extension) + || product.sharedLibraryExtension is not string extension + ) { continue; + } string stem = name[..^extension.Length]; AddLibraryAliases(libraries, stem, portable); } @@ -72,7 +74,9 @@ private static void Add( string path ) { if (mapping.TryGetValue(alias, out string? prior) && prior != path) + { throw new InvalidDataException($"Native deployment alias '{alias}' has multiple selected payloads."); + } mapping[alias] = path; } @@ -83,32 +87,47 @@ string path ) { Add(libraries, stem, path); if (stem.StartsWith("lib", StringComparison.Ordinal) && stem.Length > 3) + { Add(libraries, stem[3..], path); + } } private sealed class DeploymentValidator( - BuildTargetId target, + BuildTargetID target, string extension ) : IPlayerSupportPackValidator { - /// + /// public void Validate(string directory) { string root = PathBoundary.Resolve(directory, "native"); - NativeDeploymentIndex index = NativeDeploymentIndex.Decode(File.ReadAllBytes(Path.Combine(root, NativeDeploymentIndex.C_FILE_NAME))); - if (index.targetId != target.value) + NativeDeploymentIndex index = NativeDeploymentIndex.Decode( + File.ReadAllBytes(Path.Combine(root, NativeDeploymentIndex.C_FILE_NAME)) + ); + if (index.targetID != target.value) + { throw new InvalidDataException("The selected Native deployment metadata has a foreign target."); - var actual = new HashSet(PathBoundary.EnumerateFiles(root) - .Where(path => Path.GetFileName(path) != NativeDeploymentIndex.C_FILE_NAME) - .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')), StringComparer.Ordinal); + } + var actual = new HashSet( + PathBoundary.EnumerateFiles(root) + .Where(path => Path.GetFileName(path) != NativeDeploymentIndex.C_FILE_NAME) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')), + StringComparer.Ordinal + ); if (!actual.SetEquals(index.files.Values) || index.libraries.Values.Any(path => !actual.Contains(path))) + { throw new InvalidDataException("Native deployment metadata does not describe the complete selected payload."); + } var expectedLibraries = new Dictionary(StringComparer.Ordinal); foreach (string path in actual.Where(path => path.EndsWith(extension, StringComparison.Ordinal))) + { AddLibraryAliases(expectedLibraries, Path.GetFileName(path)[..^extension.Length], path); + } if (index.libraries.Count != expectedLibraries.Count - || expectedLibraries.Any(pair => !index.libraries.TryGetValue(pair.Key, out string? path) || path != pair.Value)) + || expectedLibraries.Any(pair => !index.libraries.TryGetValue(pair.Key, out string? path) || path != pair.Value) + ) { throw new InvalidDataException("Native deployment metadata does not expose the selected library aliases."); + } } } } diff --git a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs index ef4a1f85a..0437e257b 100644 --- a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs +++ b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs @@ -29,13 +29,18 @@ public static class StandardSupportPackRequirements /// public static PlayerSupportPackRequirements CreateDynamic( ProductNativeBuildPlan plan, - BuildTargetId target, + BuildTargetID target, string extension ) { - string[] groups = plan.steps.Select(step => step.deploymentPath("selected" + extension, target.value) - ?? throw new InvalidOperationException("A Player component has no runtime deployment policy.")) - .Select(path => Path.GetDirectoryName(path)?.Replace('\\', '/') - ?? throw new InvalidOperationException("A Player component must declare an owned deployment group.")) + string[] groups = plan.steps + .Select(step => ( + step.deploymentPath("selected" + extension, target.value) + ?? throw new InvalidOperationException("A Player component has no runtime deployment policy.") + )) + .Select(path => ( + Path.GetDirectoryName(path)?.Replace('\\', '/') + ?? throw new InvalidOperationException("A Player component must declare an owned deployment group.") + )) .ToArray(); return new(target, ManagedFiles(plan), "native", groups, extension); } @@ -49,23 +54,30 @@ string extension /// /// The exact platform target. /// - /// - /// Requirements matching the plan's actual component closure. - /// /// /// The explicit platform archive naming plan. /// + /// + /// Requirements matching the plan's actual component closure. + /// public static PlayerSupportPackRequirements CreateStatic( ProductNativeBuildPlan plan, - BuildTargetId target, + BuildTargetID target, NativeLinkPlan linkPlan ) { - string[] archives = plan.steps.SelectMany(step => step.component.staticBuild?.logicalOutputs - .Select(name => "PlayerLink/Native/" + step.id + "/" + target.value + "/" + linkPlan.GetStaticFileName(name)) - ?? throw new InvalidOperationException("A static Player component has no declared archive closure.")).ToArray(); - return new(target, [.. ManagedFiles(plan), .. archives], "PlayerLink/Native", - plan.steps.Select(step => step.id + "/" + target.value).ToArray(), linkPlan.staticLibraryExtension!, - archives.Select(path => path["PlayerLink/Native/".Length..]).ToArray()); + string[] archives = plan.steps.SelectMany(step => ( + step.component.staticBuild?.logicalOutputs + .Select(name => "PlayerLink/Native/" + step.id + "/" + target.value + "/" + linkPlan.GetStaticFileName(name)) + ?? throw new InvalidOperationException("A static Player component has no declared archive closure.") + )).ToArray(); + return new( + target, + [.. ManagedFiles(plan), .. archives], + "PlayerLink/Native", + plan.steps.Select(step => step.id + "/" + target.value).ToArray(), + linkPlan.staticLibraryExtension!, + archives.Select(path => path["PlayerLink/Native/".Length..]).ToArray() + ); } private static string[] ManagedFiles(ProductNativeBuildPlan plan) @@ -74,5 +86,7 @@ private static string[] ManagedFiles(ProductNativeBuildPlan plan) { "References/" + Path.GetFileNameWithoutExtension(step.component.nativeProject) + ".dll", "PlayerLink/References/" + Path.GetFileNameWithoutExtension(step.component.nativeProject) + ".dll" - }).Append("PlayerLink/References/BGCS.Runtime.dll").ToArray(); + }) + .Append("PlayerLink/References/BGCS.Runtime.dll") + .ToArray(); } diff --git a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs index 5d1ffe502..7b60471dd 100644 --- a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs +++ b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Inno.Build; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.SupportPacks; @@ -14,7 +15,7 @@ namespace Inno.Build.SupportPacks; /// public sealed class FilePlayerSupportPackPreparation { - private readonly BuildTargetId m_target; + private readonly BuildTargetID m_target; private readonly IPlayerSupportPackValidator m_validator; private readonly string m_runtimeIdentifier; private readonly string m_nativePlatform; @@ -55,15 +56,15 @@ public sealed class FilePlayerSupportPackPreparation /// /// The frozen product component closure. /// + /// + /// The product-selected native execution strategy. + /// /// /// The SDK provider for the explicit native target. /// /// /// The declared machine executing tools. /// - /// - /// The product-selected native execution strategy. - /// /// /// The borrowed generation service used by the frozen Native operation. /// @@ -77,7 +78,7 @@ public sealed class FilePlayerSupportPackPreparation /// The validator is null. /// public FilePlayerSupportPackPreparation( - BuildTargetId target, + BuildTargetID target, string runtimeIdentifier, string nativePlatform, string nativeExtension, @@ -99,12 +100,13 @@ IReadOnlyList preparationInputs ArgumentException.ThrowIfNullOrWhiteSpace(productProject); ArgumentException.ThrowIfNullOrWhiteSpace(templateFile); ArgumentNullException.ThrowIfNull(nativePlan); + ArgumentNullException.ThrowIfNull(nativeExecutor); ArgumentNullException.ThrowIfNull(toolchainProvider); ArgumentNullException.ThrowIfNull(host); m_productProject = productProject; m_templateFile = templateFile; m_nativePlan = nativePlan; - m_nativeExecutor = nativeExecutor ?? throw new ArgumentNullException(nameof(nativeExecutor)); + m_nativeExecutor = nativeExecutor; m_toolchainProvider = toolchainProvider; ArgumentNullException.ThrowIfNull(bindingGenerator); ArgumentNullException.ThrowIfNull(preparationInputs); @@ -121,7 +123,7 @@ IReadOnlyList preparationInputs /// /// Gets the platform identity whose closure this source prepares. /// - public BuildTargetId target => m_target; + public BuildTargetID target => m_target; /// /// Resolves tools and validates required source inputs before any staging exists. @@ -141,32 +143,64 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); - string project = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_productProject); - string template = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile); + string project = PathBoundary.Resolve(context.engineRoot, m_productProject); + string template = PathBoundary.Resolve(context.engineRoot, m_templateFile); if (!File.Exists(template)) + { throw new FileNotFoundException("The Player publication template is absent.", template); - var native = new NativeBuildContext(context.engineRoot, ToolchainLayout.C_RELEASE_CONFIGURATION) + } + NativeBuildContext native = new NativeBuildContext(context.engineRoot, ToolchainLayout.C_RELEASE_CONFIGURATION) .WithBindingGenerator(m_bindingGenerator); if (context.nativeDependencies is null) - native = native.WithToolchain(await m_toolchainProvider.ResolveAsync( - native, m_host, m_nativePlatform, cancellationToken).ConfigureAwait(false)); + { + native = native.WithToolchain( + await m_toolchainProvider.ResolveAsync( + native, + m_host, + m_nativePlatform, + cancellationToken + ).ConfigureAwait(false) + ); + } DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( - context.dotnetHost, project, cancellationToken).ConfigureAwait(false); + context.dotnetHost, + project, + cancellationToken + ).ConfigureAwait(false); var properties = new Dictionary { - ["Configuration"] = "Release", ["RuntimeIdentifier"] = m_runtimeIdentifier, - ["DebugType"] = "None", ["DebugSymbols"] = "false", + ["Configuration"] = "Release", + ["RuntimeIdentifier"] = m_runtimeIdentifier, + ["DebugType"] = "None", + ["DebugSymbols"] = "false", ["InnoShaderToolSourceRoot"] = context.engineRoot, - ["InnoNativeTarget"] = m_target.value, ["InnoPrepareProductNative"] = "false" + ["InnoNativeTarget"] = m_target.value, + ["InnoPrepareProductNative"] = "false" }; if (context.nativeDependencies is not null) + { properties["InnoNativeDependencyManifest"] = context.nativeDependencies; + } PlayerSupportPackPreparationIdentity identity = await PlayerSupportPackPreparationIdentity.CaptureAsync( - native, m_nativePlan, sdk, project, properties, - m_preparationInputs.Append(template).ToArray(), cancellationToken).ConfigureAwait(false); + native, + m_nativePlan, + sdk, + project, + properties, + m_preparationInputs.Append(template).ToArray(), + cancellationToken + ).ConfigureAwait(false); return new PreparationPlan(this, context.engineRoot, project, sdk, native, identity); } + /// + /// Validates the prepared platform inputs before atomic installation. + /// + /// + /// The isolated target pack directory. + /// + public void Validate(string directory) => m_validator.Validate(directory); + private async ValueTask ExecuteAsync( PlayerSupportPackBuildContext context, string project, @@ -175,64 +209,111 @@ private async ValueTask ExecuteAsync( CancellationToken cancellationToken ) { using ProductNativeBuildResult products = identity.nativeDependencies is string manifest - ? await NativeDependencyManifest.AcquireAsync(native.engineRoot, manifest, m_target.value, - native.configuration, m_nativePlan, cancellationToken).ConfigureAwait(false) + ? await NativeDependencyManifest.AcquireAsync( + native.engineRoot, + manifest, + m_target.value, + native.configuration, + m_nativePlan, + cancellationToken + ).ConfigureAwait(false) : await m_nativeExecutor.BuildAsync(native, m_nativePlan, cancellationToken).ConfigureAwait(false); using ManagedBuildExecution execution = await identity.CreateExecutionAsync(cancellationToken).ConfigureAwait(false); context = new PlayerSupportPackBuildContext(execution.engineRoot, context.stagingDirectory, context.sdk); project = execution.project; string bindingSelection = Path.Combine(Path.GetDirectoryName(execution.project)!, "obj", "support-pack", "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(bindingSelection, - m_nativePlan.steps.Select(( - step, - index - ) => (step, product: products[index])) + NativeBindingGenerationDescriptor.WriteSelection( + bindingSelection, + m_nativePlan.steps + .Select(( + step, + index + ) => (step, product: products[index])) .Where(static pair => pair.product.bindingGeneration is not null) - .ToDictionary(static pair => pair.step.component.nativeProject, - static pair => pair.product.bindingGeneration!, StringComparer.Ordinal), - m_nativePlan.steps.Where(( - step, - index - ) => products[index].bindingGeneration is not null) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - await ToolchainEnvironment.RunAsync(context.sdk.hostPath, - [context.sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--configuration", "Release", - "--runtime", m_runtimeIdentifier, "--nologo", "-p:DebugType=None", "-p:DebugSymbols=false", - "-p:InnoNativeTarget=" + m_target.value, "-p:InnoPrepareProductNative=false", + .ToDictionary( + static pair => pair.step.component.nativeProject, + static pair => pair.product.bindingGeneration!, + StringComparer.Ordinal + ), + m_nativePlan.steps + .Where(( + step, + index + ) => products[index].bindingGeneration is not null) + .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal) + ); + await ToolchainEnvironment.RunAsync( + context.sdk.hostPath, + [ + context.sdk.cliPath, + "build", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--configuration", + "Release", + "--runtime", + m_runtimeIdentifier, + "--nologo", + "-p:DebugType=None", + "-p:DebugSymbols=false", + "-p:InnoNativeTarget=" + m_target.value, + "-p:InnoPrepareProductNative=false", "-p:InnoShaderToolSourceRoot=" + native.engineRoot, "-p:InnoNativeBindingSelection=" + bindingSelection, - ..(identity.nativeDependencies is string selection ? new[] { "-p:InnoNativeDependencyManifest=" + selection } : Array.Empty())], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath)).ConfigureAwait(false); - string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync(context.sdk.hostPath, - [context.sdk.cliPath, "msbuild", project, "-getProperty:TargetDir", "-p:Configuration=Release", "-p:RuntimeIdentifier=" + m_runtimeIdentifier, - "-p:InnoNativeTarget=" + m_target.value, "-p:DesignTimeBuild=true", "-nologo"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath)).ConfigureAwait(false)).Trim(); + ..(identity.nativeDependencies is string selection + ? new[] { "-p:InnoNativeDependencyManifest=" + selection } + : Array.Empty()) + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath) + ).ConfigureAwait(false); + string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync( + context.sdk.hostPath, + [ + context.sdk.cliPath, + "msbuild", + project, + "-getProperty:TargetDir", + "-p:Configuration=Release", + "-p:RuntimeIdentifier=" + + m_runtimeIdentifier, + "-p:InnoNativeTarget=" + m_target.value, + "-p:DesignTimeBuild=true", + "-nologo" + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath) + ).ConfigureAwait(false)).Trim(); PlayerSupportPackFiles.CopyReferences( buildOutput, - Path.Combine(context.stagingDirectory, "References"), Path.GetFileNameWithoutExtension(project)); + Path.Combine(context.stagingDirectory, "References"), + Path.GetFileNameWithoutExtension(project) + ); await CopyNativeRuntimeAsync(products, context.stagingDirectory, cancellationToken).ConfigureAwait(false); string link = Path.Combine(context.stagingDirectory, "PlayerLink"); Directory.CreateDirectory(link); - File.Copy(Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile), Path.Combine(link, "Player.csproj")); + File.Copy(PathBoundary.Resolve(context.engineRoot, m_templateFile), Path.Combine(link, "Player.csproj")); await PlayerSupportPackFiles.CopyPlayerSourcesAsync( - context, project, link, cancellationToken).ConfigureAwait(false); + context, + project, + link, + cancellationToken + ).ConfigureAwait(false); PlayerSupportPackFiles.CopyCompositionInputs(context.engineRoot, link); string references = Path.Combine(link, "References"); Directory.CreateDirectory(references); foreach (string reference in Directory.EnumerateFiles(Path.Combine(context.stagingDirectory, "References"), "*.dll")) + { File.Copy(reference, Path.Combine(references, Path.GetFileName(reference))); + } await CopyNativeToTemplateAsync(context.stagingDirectory, link, cancellationToken).ConfigureAwait(false); await execution.VerifyAsync(cancellationToken).ConfigureAwait(false); } - /// - /// Validates the prepared platform inputs before atomic installation. - /// - /// - /// The isolated target pack directory. - /// - public void Validate(string directory) => m_validator.Validate(directory); - private async ValueTask CopyNativeRuntimeAsync( IReadOnlyList products, string staging, @@ -240,12 +321,17 @@ CancellationToken cancellationToken ) { foreach (NativeBuildProduct product in products) { - if (product.targetId != m_nativePlatform) - throw new InvalidDataException($"Native product '{product.component}' targets '{product.targetId}', not '{m_nativePlatform}'."); + if (product.targetID != m_nativePlatform) + { + throw new InvalidDataException( + $"Native product '{product.component}' targets '{product.targetID}', not '{m_nativePlatform}'." + ); + } if (!product.files.Any(file => string.Equals(Path.GetExtension(file), m_nativeExtension, StringComparison.OrdinalIgnoreCase))) { throw new InvalidDataException( - $"Native runtime product '{product.component}' and '{m_target}' is empty."); + $"Native runtime product '{product.component}' and '{m_target}' is empty." + ); } } await ProductNativeDeployment.StageAsync(products, m_nativePlan, staging, cancellationToken).ConfigureAwait(false); @@ -263,12 +349,15 @@ CancellationToken cancellationToken string destination = Path.Combine(playerDirectory, "native", Path.GetRelativePath(nativeRoot, input)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); await using FileStream source = File.OpenRead(input); - await using FileStream output = new(destination, FileMode.CreateNew); + await using var output = new FileStream(destination, FileMode.CreateNew); await source.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(input)); + } } } + private sealed class PreparationPlan( FilePlayerSupportPackPreparation owner, string engineRoot, @@ -276,16 +365,21 @@ private sealed class PreparationPlan( DotNetSdkDescriptor sdk, NativeBuildContext native, PlayerSupportPackPreparationIdentity identity - ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { - /// + ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) + { + /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); - /// + /// public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => owner.ExecuteAsync(new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), - project, native, identity, cancellationToken); + ) => owner.ExecuteAsync( + new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), + project, + native, + identity, + cancellationToken + ); } - } diff --git a/build/support/Inno.Build.SupportPacks.Core/IPlayerSupportPackSource.cs b/build/support/Inno.Build.SupportPacks.Core/IPlayerSupportPackSource.cs index 4e904588a..9a7c29b73 100644 --- a/build/support/Inno.Build.SupportPacks.Core/IPlayerSupportPackSource.cs +++ b/build/support/Inno.Build.SupportPacks.Core/IPlayerSupportPackSource.cs @@ -12,7 +12,7 @@ public interface IPlayerSupportPackSource : IPlayerSupportPackValidator /// /// Gets the stable target identity implemented by this source. /// - BuildTargetId target { get; } + BuildTargetID target { get; } /// /// Validates discovery inputs and freezes a plan before publication output exists. diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs index 4136bba22..02ce7b69c 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs @@ -34,8 +34,10 @@ public PlayerSupportPackClosureValidator( IPlayerSupportPackValidator platform, IPlayerSupportPackValidator? deployment ) { - m_requirements = requirements ?? throw new ArgumentNullException(nameof(requirements)); - m_platform = platform ?? throw new ArgumentNullException(nameof(platform)); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(platform); + m_requirements = requirements; + m_platform = platform; m_deployment = deployment; } @@ -56,22 +58,37 @@ public void Validate(string directory) ArgumentException.ThrowIfNullOrWhiteSpace(directory); m_platform.Validate(directory); foreach (string relative in m_requirements.requiredFiles) + { if (!File.Exists(PathBoundary.Resolve(directory, relative))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' lacks selected input '{relative}'."); + } + } string root = PathBoundary.Resolve(directory, m_requirements.nativeRoot); if (!Directory.Exists(root)) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' has no selected native deployment."); + } string[] libraries = PathBoundary.EnumerateFiles(root) .Where(path => Path.GetExtension(path).Equals(m_requirements.nativeExtension, StringComparison.OrdinalIgnoreCase)) - .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')).ToArray(); + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .ToArray(); foreach (string group in m_requirements.nativeDirectories) + { if (!libraries.Any(path => path.StartsWith(group + "/", StringComparison.Ordinal))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' lacks native component group '{group}'."); + } + } if (libraries.Any(path => !m_requirements.nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' contains an undeclared native component group."); + } if (m_requirements.nativeFiles is { } selected - && !libraries.ToHashSet(StringComparer.Ordinal).SetEquals(selected)) + && !libraries.ToHashSet(StringComparer.Ordinal).SetEquals(selected) + ) { throw new InvalidDataException($"Support Pack '{m_requirements.target}' does not match its selected native file closure."); + } m_deployment?.Validate(directory); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs index 43c4b8c70..584b9ab2f 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs @@ -49,30 +49,48 @@ public static async Task CopyPlayerSourcesAsync( ) { string evaluated = await ToolchainEnvironment.CaptureOutputAsync( context.sdk.hostPath, - [context.sdk.cliPath, "msbuild", project, "-getItem:Compile", "-p:Configuration=Release", - "-p:DesignTimeBuild=true", "-nodeReuse:false", "-nologo"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, environment)).ConfigureAwait(false); + [ + context.sdk.cliPath, + "msbuild", + project, + "-getItem:Compile", + "-p:Configuration=Release", + "-p:DesignTimeBuild=true", + "-nodeReuse:false", + "-nologo" + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, environment) + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(evaluated); JsonElement sources = document.RootElement.GetProperty("Items").GetProperty("Compile"); string projectDirectory = Path.GetDirectoryName(project)!; var outputs = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (JsonElement source in sources.EnumerateArray() - .OrderBy(static source => source.GetProperty("Identity").GetString(), StringComparer.Ordinal)) - { + .OrderBy(static source => source.GetProperty("Identity").GetString(), StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); string input = PathBoundary.RequireUnlinkedPath( - context.engineRoot, source.GetProperty("FullPath").GetString()!); + context.engineRoot, + source.GetProperty("FullPath").GetString()! + ); string relative = source.TryGetProperty("Link", out JsonElement link) - && !string.IsNullOrWhiteSpace(link.GetString()) - ? link.GetString()! : Path.GetRelativePath(projectDirectory, input); + && !string.IsNullOrWhiteSpace(link.GetString()) + ? link.GetString()! + : Path.GetRelativePath(projectDirectory, input); string output = PathBoundary.Resolve(destination, relative); if (!outputs.Add(relative.Replace('\\', '/'))) + { throw new InvalidDataException($"Player sources repeat publication path '{relative}'."); + } Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.Copy(input, output); } if (outputs.Count == 0) + { throw new InvalidDataException("The Player project declares no publication sources."); + } } /// @@ -93,15 +111,40 @@ string playerDirectory ) { string analyzerDirectory = Path.Combine(playerDirectory, "Analyzers"); Directory.CreateDirectory(analyzerDirectory); - string analyzer = Path.Combine(engineRoot, "src", "runtime", "generators", - "Inno.Runtime.Generators", "bin", "Release", "netstandard2.0", "Inno.Runtime.Generators.dll"); + string analyzer = Path.Combine( + engineRoot, + "src", + "runtime", + "generators", + "Inno.Runtime.Generators", + "bin", + "Release", + "netstandard2.0", + "Inno.Runtime.Generators.dll" + ); if (!File.Exists(analyzer)) + { throw new FileNotFoundException("The runtime registration generator is absent from the prepared build.", analyzer); + } File.Copy(analyzer, Path.Combine(analyzerDirectory, Path.GetFileName(analyzer))); - string serializationAnalyzer = Path.Combine(engineRoot, "src", "foundation", "core", - "Inno.Core.Serialization.Generators", "bin", "Release", "netstandard2.0", "Inno.Core.Serialization.Generators.dll"); + string serializationAnalyzer = Path.Combine( + engineRoot, + "src", + "foundation", + "core", + "Inno.Core.Serialization.Generators", + "bin", + "Release", + "netstandard2.0", + "Inno.Core.Serialization.Generators.dll" + ); if (!File.Exists(serializationAnalyzer)) - throw new FileNotFoundException("The serialization metadata generator is absent from the prepared build.", serializationAnalyzer); + { + throw new FileNotFoundException( + "The serialization metadata generator is absent from the prepared build.", + serializationAnalyzer + ); + } File.Copy(serializationAnalyzer, Path.Combine(analyzerDirectory, Path.GetFileName(serializationAnalyzer))); string sdkSelection = Path.Combine(engineRoot, "global.json"); File.Copy(sdkSelection, Path.Combine(playerDirectory, "global.json")); @@ -129,26 +172,39 @@ string productAssemblyName ) { string dependencyFile = Path.Combine(buildOutput, productAssemblyName + ".deps.json"); if (!File.Exists(dependencyFile)) + { throw new InvalidDataException("Player build has no SDK-selected runtime dependency closure."); + } using JsonDocument dependencies = JsonDocument.Parse(File.ReadAllBytes(dependencyFile)); JsonElement root = dependencies.RootElement; string target = root.GetProperty("runtimeTarget").GetProperty("name").GetString() - ?? throw new InvalidDataException("Player dependencies have no explicit runtime target."); - string[] files = root.GetProperty("targets").GetProperty(target).EnumerateObject() + ?? throw new InvalidDataException("Player dependencies have no explicit runtime target."); + string[] files = root.GetProperty("targets") + .GetProperty(target) + .EnumerateObject() .Where(static dependency => dependency.Value.TryGetProperty("runtime", out _)) - .SelectMany(static dependency => dependency.Value.GetProperty("runtime").EnumerateObject() + .SelectMany(static dependency => dependency.Value.GetProperty("runtime") + .EnumerateObject() .Select(static asset => Path.GetFileName(asset.Name))) - .Where(name => name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) - && Path.GetFileNameWithoutExtension(name) != productAssemblyName) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal) - .Select(name => PathBoundary.Resolve(buildOutput, name)).ToArray(); + .Where(name => ( + name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + && Path.GetFileNameWithoutExtension(name) != productAssemblyName + )) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .Select(name => PathBoundary.Resolve(buildOutput, name)) + .ToArray(); if (files.Length == 0) + { throw new InvalidDataException("Player build produced no target compilation references."); + } Directory.CreateDirectory(destination); foreach (string file in files) { if (!File.Exists(file)) + { throw new InvalidDataException($"Selected Player dependency '{Path.GetFileName(file)}' was not deployed by the SDK."); + } File.Copy(file, Path.Combine(destination, Path.GetFileName(file))); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs index 1d4f85007..317591d5d 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Inno.Build; @@ -23,13 +24,15 @@ public abstract class PlayerSupportPackPlan /// The target has no stable identity. /// protected PlayerSupportPackPlan( - BuildTargetId target, + BuildTargetID target, string preparationIdentity ) { ArgumentException.ThrowIfNullOrWhiteSpace(target.value); if (preparationIdentity is null || preparationIdentity.Length != 64 - || System.Linq.Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character))) + || Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new ArgumentException("A Support Pack requires a complete lowercase source input identity.", nameof(preparationIdentity)); + } this.target = target; this.preparationIdentity = preparationIdentity; } @@ -37,7 +40,7 @@ string preparationIdentity /// /// Gets the immutable target checked by the publisher before creating output. /// - public BuildTargetId target { get; } + public BuildTargetID target { get; } /// /// Gets the complete source preparation identity, independently of the resulting Pack content fingerprint. diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs index f4584fc33..996921219 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs @@ -16,12 +16,12 @@ public sealed class PlayerSupportPackPlanningContext /// /// The explicitly selected managed host executable. /// - /// - /// A required input is blank. - /// /// /// An exact dependency selection; null permits local source preparation. /// + /// + /// A required input is blank. + /// public PlayerSupportPackPlanningContext( string engineRoot, string dotnetHost, diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs index 520f822db..a5c211297 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Threading; @@ -47,6 +48,46 @@ IReadOnlyList inputs /// public string? nativeDependencies => m_properties.GetValueOrDefault("InnoNativeDependencyManifest"); + /// + /// Creates the exclusively owned fixed managed execution planned by this preparation identity. + /// + /// + /// Cancels materialization without changing any installed Pack. + /// + /// + /// Caller-owned input copies for compilation and source extraction. + /// + public ValueTask CreateExecutionAsync(CancellationToken cancellationToken = default) + => (m_managed + ?? throw new InvalidOperationException("Managed preparation was not captured.")).CreateExecutionAsync(cancellationToken); + + /// + /// Freshly verifies the complete current source input closure after waiting or preparing output. + /// + /// + /// Cancels verification before cache acceptance or publication. + /// + /// + /// Completion when the current graph and bytes still match the frozen preparation identity. + /// + /// + /// Preparation inputs changed; no candidate may be selected. + /// + /// + /// Verification was canceled. + /// + public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) + { + string current = await ComputeAsync( + m_context.BeginInputVerification("support-pack-inputs"), + cancellationToken + ).ConfigureAwait(false); + if (current != fingerprint) + { + throw new InvalidOperationException("Support Pack inputs changed after planning; the candidate cannot be selected."); + } + } + /// /// Captures Native declarations, selected binding inputs, the managed graph and explicit packaging inputs. /// @@ -98,87 +139,98 @@ public static async ValueTask CaptureAsync ArgumentNullException.ThrowIfNull(properties); ArgumentNullException.ThrowIfNull(preparationInputs); ArgumentException.ThrowIfNullOrWhiteSpace(project); - var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( - properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase)); - var result = new PlayerSupportPackPreparationIdentity(context, nativePlan, sdk, project, frozen, - Array.AsReadOnly(preparationInputs.ToArray())); + var frozen = new ReadOnlyDictionary( + properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) + ); + var result = new PlayerSupportPackPreparationIdentity( + context, + nativePlan, + sdk, + project, + frozen, + Array.AsReadOnly(preparationInputs.ToArray()) + ); result.fingerprint = await result.ComputeAsync(context, cancellationToken).ConfigureAwait(false); return result; } - /// - /// Creates the exclusively owned fixed managed execution planned by this preparation identity. - /// - /// - /// Cancels materialization without changing any installed Pack. - /// - /// - /// Caller-owned input copies for compilation and source extraction. - /// - public ValueTask CreateExecutionAsync(CancellationToken cancellationToken = default) - => (m_managed ?? throw new InvalidOperationException("Managed preparation was not captured.")).CreateExecutionAsync(cancellationToken); - - /// - /// Freshly verifies the complete current source input closure after waiting or preparing output. - /// - /// - /// Cancels verification before cache acceptance or publication. - /// - /// - /// Completion when the current graph and bytes still match the frozen preparation identity. - /// - /// - /// Preparation inputs changed; no candidate may be selected. - /// - /// - /// Verification was canceled. - /// - public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) - { - string current = await ComputeAsync(m_context.BeginInputVerification("support-pack-inputs"), cancellationToken).ConfigureAwait(false); - if (current != fingerprint) - throw new InvalidOperationException("Support Pack inputs changed after planning; the candidate cannot be selected."); - } - private async ValueTask ComputeAsync( NativeBuildContext context, - CancellationToken cancellation + CancellationToken cancellationToken ) { - cancellation.ThrowIfCancellationRequested(); - var declarations = new List { "support-pack-preparation", m_nativePlan.productId }; + cancellationToken.ThrowIfCancellationRequested(); + List declarations = ["support-pack-preparation", m_nativePlan.productID]; if (m_properties.TryGetValue("InnoNativeDependencyManifest", out string? manifest)) { - IReadOnlyList assets = await NativeDependencyManifest.SelectAsync(context.engineRoot, - manifest, m_properties["InnoNativeTarget"], context.configuration, m_nativePlan, cancellation).ConfigureAwait(false); - declarations.AddRange(assets.OrderBy(static asset => asset.asset, StringComparer.Ordinal) - .Select(static asset => asset.asset + "=" + asset.sha256)); + IReadOnlyList assets = await NativeDependencyManifest.SelectAsync( + context.engineRoot, + manifest, + m_properties["InnoNativeTarget"], + context.configuration, + m_nativePlan, + cancellationToken + ).ConfigureAwait(false); + declarations.AddRange( + assets.OrderBy(static asset => asset.asset, StringComparer.Ordinal) + .Select(static asset => asset.asset + "=" + asset.sha256) + ); } else { IReadOnlyList recipes = m_nativePlan.CreateRecipes(context); - declarations.Add(context.RequireToolchain().targetId); + declarations.Add(context.RequireToolchain().targetID); foreach (NativeBuildRecipe recipe in recipes) - declarations.Add(recipe.component + "=" + NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellation)); + { + declarations.Add( + recipe.component + "=" + NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellationToken) + ); + } NativeComponentDescriptor[] generated = m_nativePlan.steps.Select(static step => step.component) - .Where(static component => component.bindingDefinition is not null).DistinctBy(static component => component.nativeProject).ToArray(); + .Where(static component => component.bindingDefinition is not null) + .DistinctBy(static component => component.nativeProject) + .ToArray(); if (generated.Length > 0) - declarations.Add("bindings=" + await context.RequireBindingGenerator().ComputeInputFingerprintAsync(context, - new NativeBindingGenerationRequest(generated, context.RequireToolchain().targetId, NativeBindingOutputMode.TargetArtifacts, - componentOptions: m_nativePlan.steps.Where(static step => step.component.bindingDefinition is not null) - .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)), - cancellation).ConfigureAwait(false)); + { + declarations.Add( + "bindings=" + await context.RequireBindingGenerator().ComputeInputFingerprintAsync( + context, + new NativeBindingGenerationRequest( + generated, + context.RequireToolchain().targetID, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: m_nativePlan.steps.Where(static step => step.component.bindingDefinition is not null) + .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ), + cancellationToken + ).ConfigureAwait(false) + ); + } } - ManagedBuildInputSnapshot managed = await ManagedBuildInputSnapshot.CaptureAsync(context, m_sdk, m_project, - m_properties, cancellation).ConfigureAwait(false); + ManagedBuildInputSnapshot managed = await ManagedBuildInputSnapshot.CaptureAsync( + context, + m_sdk, + m_project, + m_properties, + cancellationToken + ).ConfigureAwait(false); m_managed ??= managed; declarations.Add("managed=" + managed.fingerprint); string root = Path.Combine(context.engineRoot, "build", "support", "Inno.Build.SupportPacks.Core"); - IEnumerable inputs = m_inputs.Concat(new[] { "FilePlayerSupportPackPreparation.cs", "PlayerSupportPackFiles.cs", - "PlayerSupportPackPreparationIdentity.cs", "PlayerSupportPackPublisher.cs", "PlayerSupportPackPreparationIndex.cs", - "PlayerSupportPackPlan.cs", "Inno.Build.SupportPacks.Core.csproj" }.Select(file => Path.Combine(root, file))) - .Append(Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "Native", "ProductNativeDeployment.cs")); - return NativeBuildFingerprint.Create(context, declarations, - inputs.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), cancellation); + IEnumerable inputs = m_inputs + .Concat( + new[] { "FilePlayerSupportPackPreparation.cs", "PlayerSupportPackFiles.cs", + "PlayerSupportPackPreparationIdentity.cs", "PlayerSupportPackPublisher.cs", "PlayerSupportPackPreparationIndex.cs", + "PlayerSupportPackPlan.cs", "Inno.Build.SupportPacks.Core.csproj" }.Select(file => Path.Combine(root, file)) + ) + .Append( + Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "Native", "ProductNativeDeployment.cs") + ); + return NativeBuildFingerprint.Create( + context, + declarations, + inputs.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), + cancellationToken + ); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs index adfe73d98..06dbc247b 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Text; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -15,7 +16,9 @@ string preparation ) { string path = GetPath(root, target, preparation); if (!File.Exists(path)) + { return null; + } string fingerprint = File.ReadAllText(path); return IsIdentity(fingerprint) ? fingerprint : null; } @@ -27,12 +30,16 @@ internal static void Write( string content ) { if (!IsIdentity(content)) + { throw new InvalidDataException("A prepared Pack index requires a complete content identity."); + } string path = GetPath(root, target, preparation); Directory.CreateDirectory(Path.GetDirectoryName(path)!); PathBoundary.RequireUnlinkedPath(root, path); if (!File.Exists(path) || File.ReadAllText(path) != content) + { AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(content)); + } new BuildCachePublisher(Path.GetFullPath(root), BuildCacheArtifactRole.ImmutableArtifact) .RecordIndex(path, [PathBoundary.Resolve(root, target + "/" + content)]); } @@ -43,10 +50,13 @@ private static string GetPath( string preparation ) { if (!IsIdentity(preparation)) + { throw new InvalidDataException("A prepared Pack index requires a complete source identity."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, target + "/.preparations/" + preparation)); } - private static bool IsIdentity(string identity) => identity.Length == 64 - && !System.Linq.Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); + private static bool IsIdentity(string identity) + => identity.Length == 64 + && !Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs index 56f91e45e..898159103 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs @@ -14,7 +14,7 @@ namespace Inno.Build.SupportPacks; /// public sealed class PlayerSupportPackPublisher { - private readonly IReadOnlyDictionary m_sources; + private readonly IReadOnlyDictionary m_sources; /// /// Freezes the platform sources used by this publisher. @@ -28,12 +28,14 @@ public sealed class PlayerSupportPackPublisher public PlayerSupportPackPublisher(IEnumerable sources) { ArgumentNullException.ThrowIfNull(sources); - var registered = new Dictionary(); + var registered = new Dictionary(); foreach (IPlayerSupportPackSource source in sources) { if (source is null || string.IsNullOrWhiteSpace(source.target.value) - || !registered.TryAdd(source.target, source)) + || !registered.TryAdd(source.target, source) + ) { throw new ArgumentException("Support Pack sources must be non-null and have unique target identities.", nameof(sources)); + } } m_sources = registered; } @@ -53,16 +55,15 @@ public PlayerSupportPackPublisher(IEnumerable sources) /// /// The SDK executable selected by the host. /// + /// + /// An explicit native selection disabling third-party production, or null for local source preparation. + /// /// /// Cancels preparation before directory installation begins. /// /// /// Reading ownership of the selected Pack and any post-commit diagnostics. Dispose after consuming its files. /// - /// - /// Writers targeting the same pack share an exclusive, cancelable preparation lease. - /// Publication atomically selects a fingerprint directory; previous generations remain valid for readers. - /// /// /// A required path is blank or the target has no registered source. /// @@ -78,37 +79,46 @@ public PlayerSupportPackPublisher(IEnumerable sources) /// /// Preparation was canceled; the installed pack is unchanged. /// - /// - /// An explicit native selection disabling third-party production, or null for local source preparation. - /// + /// + /// Writers targeting the same pack share an exclusive, cancelable preparation lease. + /// Publication atomically selects a fingerprint directory; previous generations remain valid for readers. + /// public async ValueTask PublishAsync( string engineRoot, string outputRoot, - BuildTargetId target, + BuildTargetID target, string dotnetHost, - CancellationToken cancellationToken = default, - string? nativeDependencies = null + string? nativeDependencies = null, + CancellationToken cancellationToken = default ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); ArgumentException.ThrowIfNullOrWhiteSpace(outputRoot); ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); if (!m_sources.TryGetValue(target, out IPlayerSupportPackSource? source)) + { throw new ArgumentException($"No Support Pack source is registered for '{target}'.", nameof(target)); + } string root = Path.GetFullPath(engineRoot); if (!File.Exists(Path.Combine(root, "InnoEngine.sln"))) + { throw new DirectoryNotFoundException($"Engine root '{root}' has no InnoEngine.sln."); + } cancellationToken.ThrowIfCancellationRequested(); PlayerSupportPackPlan plan = await source.CreatePlanAsync( - new PlayerSupportPackPlanningContext(root, dotnetHost, nativeDependencies), cancellationToken).ConfigureAwait(false); + new PlayerSupportPackPlanningContext(root, dotnetHost, nativeDependencies), + cancellationToken + ).ConfigureAwait(false); if (plan is null || plan.target != target) + { throw new InvalidDataException("The Support Pack plan does not match its registered target."); + } cancellationToken.ThrowIfCancellationRequested(); var cache = new BuildCachePublisher(Path.GetFullPath(outputRoot), BuildCacheArtifactRole.ImmutableArtifact); using FileLease cacheUse = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); string output = Path.GetFullPath(outputRoot); Directory.CreateDirectory(output); - using FileLease ownership = await FileLease.AcquireAsync( - Path.Combine(output, target.value + ".lock"), Timeout.InfiniteTimeSpan, cancellationToken) + using FileLease ownership = await FileLease + .AcquireAsync(Path.Combine(output, target.value + ".lock"), Timeout.InfiniteTimeSpan, cancellationToken) .ConfigureAwait(false); var catalog = new PlayerSupportPackCatalog(output); string? prepared = PlayerSupportPackPreparationIndex.Read(output, target.value, plan.preparationIdentity); @@ -116,8 +126,13 @@ public async ValueTask PublishAsync( { try { - PlayerSupportPackLease selected = await catalog.SelectAsync(target, prepared, source, - plan.VerifyInputsAsync, cancellationToken).ConfigureAwait(false); + PlayerSupportPackLease selected = await catalog.SelectAsync( + target, + prepared, + source, + plan.VerifyInputsAsync, + cancellationToken + ).ConfigureAwait(false); return Complete(selected, []); } catch (InvalidDataException) @@ -140,12 +155,21 @@ public async ValueTask PublishAsync( await plan.PrepareAsync(staging, cancellationToken) .ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - published = await catalog.PublishAsync(target, staging, source, cancellationToken, - plan.VerifyInputsAsync).ConfigureAwait(false); + published = await catalog.PublishAsync( + target, + staging, + source, + plan.VerifyInputsAsync, + cancellationToken + ).ConfigureAwait(false); try { - PlayerSupportPackPreparationIndex.Write(output, target.value, plan.preparationIdentity, - Path.GetFileName(published.directory)); + PlayerSupportPackPreparationIndex.Write( + output, + target.value, + plan.preparationIdentity, + Path.GetFileName(published.directory) + ); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) { diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs index 3c15bc474..26804c9e8 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs @@ -37,7 +37,7 @@ public sealed class PlayerSupportPackRequirements /// A required collection is null. /// public PlayerSupportPackRequirements( - BuildTargetId target, + BuildTargetID target, IReadOnlyList requiredFiles, string nativeRoot, IReadOnlyList nativeDirectories, @@ -49,19 +49,33 @@ public PlayerSupportPackRequirements( ArgumentNullException.ThrowIfNull(nativeDirectories); ArgumentException.ThrowIfNullOrWhiteSpace(nativeExtension); if (!nativeExtension.StartsWith(".", StringComparison.Ordinal) || nativeExtension.Contains('/') || nativeExtension.Contains('\\')) + { throw new ArgumentException("A selected native suffix must be one file extension.", nameof(nativeExtension)); + } ValidatePath(nativeRoot); foreach (string path in requiredFiles.Concat(nativeDirectories)) + { ValidatePath(path); + } foreach (string path in nativeFiles ?? []) + { ValidatePath(path); + } if (requiredFiles.Distinct(StringComparer.Ordinal).Count() != requiredFiles.Count || nativeDirectories.Distinct(StringComparer.Ordinal).Count() != nativeDirectories.Count - || nativeFiles is not null && nativeFiles.Distinct(StringComparer.Ordinal).Count() != nativeFiles.Count) + || nativeFiles is not null && nativeFiles.Distinct(StringComparer.Ordinal).Count() != nativeFiles.Count + ) { throw new ArgumentException("Selected publication inputs cannot repeat ownership paths."); - if (nativeFiles is not null && nativeFiles.Any(path => !path.EndsWith(nativeExtension, StringComparison.Ordinal) - || !nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)))) - throw new ArgumentException("Exact selected libraries must belong to their declared native groups and suffix.", nameof(nativeFiles)); + } + if (nativeFiles is not null && nativeFiles.Any(path => ( + !path.EndsWith(nativeExtension, StringComparison.Ordinal) + || !nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)) + ))) { + throw new ArgumentException( + "Exact selected libraries must belong to their declared native groups and suffix.", + nameof(nativeFiles) + ); + } this.target = target; this.requiredFiles = Array.AsReadOnly(requiredFiles.ToArray()); this.nativeRoot = nativeRoot; @@ -73,7 +87,7 @@ public PlayerSupportPackRequirements( /// /// Gets the explicitly selected target. /// - public BuildTargetId target { get; } + public BuildTargetID target { get; } /// /// Gets the immutable required Pack-relative input paths. @@ -104,7 +118,9 @@ private static void ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (path.Contains('\\') || path.Contains(':') || path.StartsWith('/') - || path.Split('/').Any(static segment => segment is "" or "." or "..")) + || path.Split('/').Any(static segment => segment is "" or "." or "..") + ) { throw new ArgumentException("Publication requirements must use portable owned relative paths.", nameof(path)); + } } } diff --git a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs index a2201da7d..1dab53dc2 100644 --- a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs +++ b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs @@ -23,9 +23,6 @@ public sealed class SourcePlayerSupportPackProvisioner : IPlayerSupportPackProvi /// /// The directory containing InnoEngine.sln and the Player project. /// - /// - /// The directory is not an engine checkout. - /// /// /// The publisher containing the host-selected platform sources. /// @@ -38,6 +35,9 @@ public sealed class SourcePlayerSupportPackProvisioner : IPlayerSupportPackProvi /// /// An absolute dependency selection disabling third-party production, or null for local source preparation. /// + /// + /// The directory is not an engine checkout. + /// public SourcePlayerSupportPackProvisioner( string engineRoot, PlayerSupportPackPublisher publisher, @@ -49,7 +49,9 @@ public SourcePlayerSupportPackProvisioner( ArgumentNullException.ThrowIfNull(reportDiagnostic); m_reportDiagnostic = reportDiagnostic; if (nativeDependencies is not null && !Path.IsPathFullyQualified(nativeDependencies)) + { throw new ArgumentException("A native dependency selection must be absolute.", nameof(nativeDependencies)); + } m_nativeDependencies = nativeDependencies; ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); m_publisher = publisher; @@ -57,7 +59,43 @@ public SourcePlayerSupportPackProvisioner( ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); m_engineRoot = Path.GetFullPath(engineRoot); if (!IsEngineRoot(m_engineRoot)) + { throw new DirectoryNotFoundException($"Engine source checkout '{m_engineRoot}' is unavailable."); + } + } + + /// + /// Prepares current target inputs and atomically selects their immutable Support Pack. + /// + /// + /// The target platform and architecture identity. + /// + /// + /// The directory that owns the installed target directories. + /// + /// + /// Cancels preparation or publication before a new current fingerprint is selected. + /// + /// + /// An operation that completes after the target Pack has been installed and verified. + /// + public async ValueTask ProvisionAsync( + BuildTargetID target, + string supportPackRoot, + CancellationToken cancellationToken = default + ) { + using PlayerSupportPackPublication installed = await m_publisher.PublishAsync( + m_engineRoot, + supportPackRoot, + target, + m_dotnetHost, + m_nativeDependencies, + cancellationToken + ).ConfigureAwait(false); + foreach (string diagnostic in installed.diagnostics) + { + m_reportDiagnostic(diagnostic); + } } /// @@ -66,12 +104,6 @@ public SourcePlayerSupportPackProvisioner( /// /// The host binary directory from which to search upward. /// - /// - /// A source provisioner, or null when the host is a source-independent distribution. - /// - /// - /// An explicit INNO_ENGINE_ROOT does not identify a complete engine checkout. - /// /// /// The publisher containing the host-selected platform sources. /// @@ -84,6 +116,12 @@ public SourcePlayerSupportPackProvisioner( /// /// The explicit consume-only selection retained by the returned provisioner, or null for local source preparation. /// + /// + /// A source provisioner, or null when the host is a source-independent distribution. + /// + /// + /// An explicit INNO_ENGINE_ROOT does not identify a complete engine checkout. + /// public static SourcePlayerSupportPackProvisioner? TryCreateForHost( string startDirectory, PlayerSupportPackPublisher publisher, @@ -97,50 +135,30 @@ public SourcePlayerSupportPackProvisioner( ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); string? configured = Environment.GetEnvironmentVariable("INNO_ENGINE_ROOT"); if (!string.IsNullOrWhiteSpace(configured)) + { return new SourcePlayerSupportPackProvisioner(configured, publisher, dotnetHost, reportDiagnostic, nativeDependencies); + } for (DirectoryInfo? directory = new(Path.GetFullPath(startDirectory)); directory is not null; - directory = directory.Parent) - { + directory = directory.Parent + ) { if (IsEngineRoot(directory.FullName)) - return new SourcePlayerSupportPackProvisioner(directory.FullName, publisher, dotnetHost, reportDiagnostic, nativeDependencies); + { + return new SourcePlayerSupportPackProvisioner( + directory.FullName, + publisher, + dotnetHost, + reportDiagnostic, + nativeDependencies + ); + } } return null; } - /// - /// Prepares current target inputs and atomically selects their immutable Support Pack. - /// - /// - /// The target platform and architecture identity. - /// - /// - /// The directory that owns the installed target directories. - /// - /// - /// Cancels preparation or publication before a new current fingerprint is selected. - /// - /// - /// An operation that completes after the target Pack has been installed and verified. - /// - public async ValueTask ProvisionAsync( - BuildTargetId target, - string supportPackRoot, - CancellationToken cancellationToken = default - ) { - using PlayerSupportPackPublication installed = await m_publisher.PublishAsync( - m_engineRoot, - supportPackRoot, - target, - m_dotnetHost, - cancellationToken, - m_nativeDependencies).ConfigureAwait(false); - foreach (string diagnostic in installed.diagnostics) - m_reportDiagnostic(diagnostic); - } - private static bool IsEngineRoot(string path) - => File.Exists(Path.Combine(path, "InnoEngine.sln")) && - File.Exists(Path.Combine(path, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj")); - + => File.Exists(Path.Combine(path, "InnoEngine.sln")) + && File.Exists( + Path.Combine(path, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj") + ); } diff --git a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs index b1fb4f6ce..e9c905373 100644 --- a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs @@ -4,16 +4,17 @@ using System.IO; using System.Linq; using System.Threading; -using Inno.Core.IO; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; /// /// Coordinates shared task-runtime compilation before immutable publication and private loading. /// -public sealed class BuildTaskRuntimeTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed class BuildTaskRuntimeTask : Task, ICancelableTask { private readonly object m_cancellationGate = new(); private readonly CancellationTokenSource m_cancellation = new(); @@ -76,7 +77,9 @@ public override bool Execute() CancellationToken token = m_cancellation.Token; token.ThrowIfCancellationRequested(); if (BuildEngine is not IBuildEngine4 engine) + { throw new InvalidOperationException("Task-runtime preparation requires the MSBuild Build-lifetime registry."); + } string project = RequireAbsolute(ProjectFile); string artifacts = RequireAbsolute(ArtifactsDirectory); string load = RequireAbsolute(LoadDirectory); @@ -86,23 +89,34 @@ public override bool Execute() string[] targets = Targets.ToArray(); string[] removed = RemoveProperties.ToArray(); if (!File.Exists(project) || targets.Length == 0 || targets.Any(string.IsNullOrWhiteSpace)) + { throw new ArgumentException("A task project and nonempty build targets are required."); + } IDictionary properties = FreezeProperties(artifacts, removed); // MSBuild's API applies undefinitions to the final request. Explicit task // properties must survive removal of identically named parent globals. removed = removed.Where(name => !properties.Contains(name)).ToArray(); - var workspaces = new BuildCachePublisher(Path.GetDirectoryName(artifacts)!, BuildCacheArtifactRole.ReusableWorkspace); + var workspaces = new BuildCachePublisher( + Path.GetDirectoryName(artifacts)!, + BuildCacheArtifactRole.ReusableWorkspace + ); ownerUses = AcquireOwnerUses( - [new(cache, BuildCacheArtifactRole.ImmutableArtifact), - new(taskRoot, BuildCacheArtifactRole.ProcessWorkingDirectory), workspaces], engine, token); + [ + new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact), + new BuildCachePublisher(taskRoot, BuildCacheArtifactRole.ProcessWorkingDirectory), + workspaces + ], + engine, + token + ); TaskRuntimePreparation.RegisterWorkspaceReader(load, artifacts, token); TaskRuntimeRequestSnapshot initial = TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); bool restoreRequired = initial.needsRestore; bool restoreRequested = targets.Contains("Restore", StringComparer.OrdinalIgnoreCase); string? request = restoreRequired ? null : initial.key; - if (request is not null && (TaskRuntimeBuildScope.Read(engine, request, load, cancellation: token) - ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] reused) - { + if (request is not null && (TaskRuntimeBuildScope.Read(engine, request, load, cancellationToken: token) + ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] reused + ) { TargetOutputs = reused; TaskRuntimeBuildScope.Register(engine, request, reused); Log.LogMessage(MessageImportance.High, "INNO-TASK-RUNTIME reused {0}", request); @@ -112,8 +126,11 @@ public override bool Execute() engine.Yield(); try { - ownership = FileLease.AcquireAsync(artifacts + ".lock", - Timeout.InfiniteTimeSpan, token).AsTask().GetAwaiter().GetResult(); + ownership = FileLease.AcquireAsync( + artifacts + ".lock", + Timeout.InfiniteTimeSpan, + token + ).AsTask().GetAwaiter().GetResult(); } finally { @@ -133,63 +150,114 @@ public override bool Execute() workspaces.BeginWorkingDirectory(artifacts, artifacts + ".lock", null, token); if (restoreRequired || restoreRequested) { - BuildEngineResult restored = engine.BuildProjectFilesInParallel([project], ["Restore"], - [RestoreProperties(properties)], [removed], [null!], returnTargetOutputs: false); + BuildEngineResult restored = engine.BuildProjectFilesInParallel( + [project], + ["Restore"], + [RestoreProperties(properties)], + [removed], + [null!], + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); if (!restored.Result) + { return false; - + } } TaskRuntimeRequestSnapshot restoredInputs = restoreRequired || restoreRequested - ? TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token) : initial; + ? TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token) + : initial; foreach (TaskRuntimeRestoreRequest inputRestore in restoredInputs.restoreRequests - .DistinctBy(static input => input.project + "|" + string.Join(";", input.properties - .OrderBy(static property => property.Key, StringComparer.OrdinalIgnoreCase) - .Select(static property => property.Key + "=" + property.Value)))) - { + .DistinctBy(static input => ( + input.project + "|" + string.Join( + ";", + input.properties + .OrderBy(static property => property.Key, StringComparer.OrdinalIgnoreCase) + .Select(static property => property.Key + "=" + property.Value) + ) + )) + ) { var inputProperties = new Hashtable(StringComparer.OrdinalIgnoreCase); - foreach (var property in inputRestore.properties) + foreach (KeyValuePair property in inputRestore.properties) + { inputProperties[property.Key] = property.Value; - BuildEngineResult restored = engine.BuildProjectFilesInParallel([inputRestore.project], ["Restore"], - [RestoreProperties(inputProperties)], [inputRestore.removedProperties - .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)).ToArray()], [null!], returnTargetOutputs: false); + } + BuildEngineResult restored = engine.BuildProjectFilesInParallel( + [inputRestore.project], + ["Restore"], + [RestoreProperties(inputProperties)], + [inputRestore.removedProperties + .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)) + .ToArray()], + [null!], + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); if (!restored.Result) + { return false; + } } TaskRuntimeRequestSnapshot locked = restoredInputs != initial && restoredInputs.restoreRequests.Count == 0 - ? restoredInputs : TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); + ? restoredInputs + : TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); if (locked.needsRestore) + { throw new InvalidOperationException("Task-runtime dependencies are not restored."); + } if (!restoreRequested && !restoreRequired && request is not null && locked.key != request) + { throw new InvalidOperationException("Task-runtime inputs changed while waiting for build ownership."); + } request = locked.key; - if ((TaskRuntimeBuildScope.Read(engine, request, load, cancellation: token) - ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] completed) - { + if ((TaskRuntimeBuildScope.Read(engine, request, load, cancellationToken: token) + ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] completed + ) { TargetOutputs = completed; TaskRuntimeBuildScope.Register(engine, request, completed); Log.LogMessage(MessageImportance.High, "INNO-TASK-RUNTIME reused {0}", request); return true; } - string[] compilationTargets = targets.Where(static target => !target.Equals("Restore", StringComparison.OrdinalIgnoreCase)).ToArray(); + string[] compilationTargets = targets + .Where(static target => !target.Equals("Restore", StringComparison.OrdinalIgnoreCase)) + .ToArray(); if (compilationTargets.Length == 0) + { throw new ArgumentException("Task-runtime preparation requires a publication target after restore.", nameof(Targets)); - BuildEngineResult result = engine.BuildProjectFilesInParallel([project], compilationTargets, - [properties], [removed], [null!], returnTargetOutputs: true); + } + BuildEngineResult result = engine.BuildProjectFilesInParallel( + [project], + compilationTargets, + [properties], + [removed], + [null!], + returnTargetOutputs: true + ); token.ThrowIfCancellationRequested(); if (!result.Result) + { return false; + } TargetOutputs = result.TargetOutputsPerProject.SelectMany(static projectOutputs => projectOutputs.Values) - .SelectMany(static output => output).ToArray(); + .SelectMany(static output => output) + .ToArray(); if (TargetOutputs.Length == 0) + { throw new InvalidDataException("The task project returned no runtime closure."); + } TaskRuntimeRequestSnapshot compiled = TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); if (compiled.key != request) - throw new InvalidOperationException("Task-runtime inputs changed during compilation; its preparation was not cached. " - + locked.DescribeChanges(compiled)); + { + throw new InvalidOperationException( + "Task-runtime inputs changed during compilation; its preparation was not cached. " + + locked.DescribeChanges(compiled) + ); + } TargetOutputs = TaskRuntimePreparation.Publish(cache, TargetOutputs, engine, load, token); - TaskRuntimePreparation.RegisterReader(load, TargetOutputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec); + TaskRuntimePreparation.RegisterReader( + load, + TargetOutputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec + ); workspaces.Record(artifacts, artifacts + ".lock", [], null, null, token); TaskRuntimeBuildScope.Register(engine, request, TargetOutputs); TaskRuntimePreparation.RecordRequest(cache, request, TargetOutputs); @@ -205,7 +273,9 @@ public override bool Execute() finally { foreach (FileLease activity in ownerUses) + { activity.Dispose(); + } lock (m_cancellationGate) { m_finished = true; @@ -220,27 +290,73 @@ public override bool Execute() public void Cancel() { lock (m_cancellationGate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } + } + + private IDictionary FreezeProperties( + string artifacts, + IReadOnlyList removed + ) { + var properties = new Hashtable(StringComparer.OrdinalIgnoreCase); + if (BuildEngine is IBuildEngine6 engine) + { + foreach (KeyValuePair property in engine.GetGlobalProperties()) + { + if (!removed.Contains(property.Key, StringComparer.OrdinalIgnoreCase)) + { + properties[property.Key] = property.Value; + } + } + } + var explicitNames = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string property in Properties) + { + int separator = property.IndexOf('='); + if (separator <= 0 || !explicitNames.Add(property[..separator])) + { + throw new ArgumentException("Task properties require unique name=value declarations."); + } + string name = property[..separator]; + if (string.Equals(name, "ArtifactsPath", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("The task artifact owner cannot be overridden."); + } + properties[name] = property[(separator + 1)..]; + } + properties["ArtifactsPath"] = artifacts; + // The private compiler workspace must not outlive this request in a shared server. + properties["UseSharedCompilation"] = "false"; + properties["ExcludeRestorePackageImports"] = "false"; + return properties; } private static FileLease[] AcquireOwnerUses( IReadOnlyList publishers, IBuildEngine4 engine, - CancellationToken cancellation + CancellationToken cancellationToken ) { var activities = new Stack(); engine.Yield(); try { foreach (BuildCachePublisher publisher in publishers.OrderBy( - static entry => entry.Describe("task-runtime").coordinationPath, StringComparer.Ordinal)) - activities.Push(publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult()); + static entry => entry.Describe("task-runtime").coordinationPath, + StringComparer.Ordinal + )) { + activities.Push(publisher.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult()); + } } catch { while (activities.TryPop(out FileLease? activity)) + { activity.Dispose(); + } throw; } finally @@ -252,46 +368,23 @@ CancellationToken cancellation catch { while (activities.TryPop(out FileLease? activity)) + { activity.Dispose(); + } throw; } } return activities.ToArray(); } - private IDictionary FreezeProperties( - string artifacts, - IReadOnlyList removed - ) { - Hashtable properties = new(StringComparer.OrdinalIgnoreCase); - if (BuildEngine is IBuildEngine6 engine) - foreach (var property in engine.GetGlobalProperties()) - if (!removed.Contains(property.Key, StringComparer.OrdinalIgnoreCase)) - properties[property.Key] = property.Value; - var explicitNames = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string property in Properties) - { - int separator = property.IndexOf('='); - if (separator <= 0 || !explicitNames.Add(property[..separator])) - throw new ArgumentException("Task properties require unique name=value declarations."); - string name = property[..separator]; - if (string.Equals(name, "ArtifactsPath", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("The task artifact owner cannot be overridden."); - properties[name] = property[(separator + 1)..]; - } - properties["ArtifactsPath"] = artifacts; - // The private compiler workspace must not outlive this request in a shared server. - properties["UseSharedCompilation"] = "false"; - properties["ExcludeRestorePackageImports"] = "false"; - return properties; - } - private static IDictionary RestoreProperties(IDictionary compilationProperties) { - var properties = new Hashtable(compilationProperties, StringComparer.OrdinalIgnoreCase); - // NuGet restore must not populate the build engine's compilation evaluation cache - // with package content items from the imports it is about to replace. - properties["ExcludeRestorePackageImports"] = "true"; + var properties = new Hashtable(compilationProperties, StringComparer.OrdinalIgnoreCase) + { + // NuGet restore must not populate the build engine's compilation evaluation cache + // with package content items from the imports it is about to replace. + ["ExcludeRestorePackageImports"] = "true" + }; return properties; } @@ -299,7 +392,9 @@ private static string RequireAbsolute(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); if (!Path.IsPathFullyQualified(value)) + { throw new ArgumentException("Task-runtime ownership requires absolute locations."); + } return Path.GetFullPath(value); } } diff --git a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs index 6aaff3322..e829cbf31 100644 --- a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs @@ -4,6 +4,7 @@ using Microsoft.Build.Framework; using Inno.Build.Toolchains; using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.TaskHosting; @@ -62,8 +63,12 @@ public sealed class MaterializeBindingsTask : BuildTask, ICancelableTask public void Cancel() { lock (m_lifecycle) + { if (!m_completed) + { m_cancellation.Cancel(); + } + } } /// @@ -79,17 +84,23 @@ public override bool Execute() CancellationToken cancellation = m_cancellation.Token; cancellation.ThrowIfCancellationRequested(); if (!Path.IsPathFullyQualified(Source) || !Path.IsPathFullyQualified(IntermediateDirectory) - || !Path.IsPathFullyQualified(ComponentProject)) + || !Path.IsPathFullyQualified(ComponentProject) + ) { throw new ArgumentException("Binding consumption requires absolute source and owner paths."); + } string source = Path.GetFullPath(Source); using IDisposable ownership = Acquire(source, cancellation); string destination = Path.Combine(Path.GetFullPath(IntermediateDirectory), "bindings", "Bindings.cs"); if (SamePath(source, destination)) + { throw new ArgumentException("The SDK consumer must not overwrite the publisher's source."); + } byte[] content = File.ReadAllBytes(source); cancellation.ThrowIfCancellationRequested(); if (!File.Exists(destination) || !content.AsSpan().SequenceEqual(File.ReadAllBytes(destination))) + { AtomicFile.WriteAllBytes(destination, content); + } MaterializedSource = destination; return true; } @@ -110,14 +121,14 @@ public override bool Execute() private IDisposable Acquire( string source, - CancellationToken cancellation + CancellationToken cancellationToken ) { IBuildEngine3? engine = BuildEngine as IBuildEngine3; IDisposable? ownership = null; engine?.Yield(); try { - ownership = AcquirePublication(source, cancellation); + ownership = AcquirePublication(source, cancellationToken); return ownership; } finally @@ -136,28 +147,45 @@ CancellationToken cancellation private IDisposable AcquirePublication( string source, - CancellationToken cancellation + CancellationToken cancellationToken ) { if (ArtifactDirectory.Length != 0) { if (!Path.IsPathFullyQualified(ArtifactDirectory)) + { throw new ArgumentException("Binding artifacts require an absolute publication owner."); + } string directory = Path.GetFullPath(ArtifactDirectory); if (!SamePath(source, Path.Combine(directory, "Generated", "Bindings.cs"))) + { throw new ArgumentException("The selected source is outside its declared binding artifact."); - return BuildArtifactReadLease.AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellation) - .AsTask().GetAwaiter().GetResult(); + } + return BuildArtifactReadLease + .AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellationToken: cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); } string owner = Path.GetDirectoryName(Path.GetFullPath(ComponentProject))!; if (!SamePath(source, Path.Combine(owner, "Generated", "Bindings.cs"))) + { throw new ArgumentException("Host bindings must belong to their Native project's Generated directory."); - return FileLease.AcquireAsync(Path.Combine(owner, "obj", "bindings", "generation.lock"), - Timeout.InfiniteTimeSpan, cancellation).AsTask().GetAwaiter().GetResult(); + } + return FileLease.AcquireAsync( + Path.Combine(owner, "obj", "bindings", "generation.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).AsTask().GetAwaiter().GetResult(); } private static bool SamePath( string left, string right - ) => string.Equals(left, right, OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + ) => string.Equals( + left, + right, + OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal + ); } diff --git a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs index bb6354629..c3fbe4a32 100644 --- a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs @@ -7,6 +7,7 @@ using System.Text; using System.Threading; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -16,7 +17,7 @@ namespace Inno.Build.TaskHosting; /// Publishes one immutable task runtime per content identity before a build loads its private closure. /// This bootstrap depends only on filesystem primitives and never loads the task runtime being built. /// -public sealed partial class PublishTaskHostTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed partial class PublishTaskHostTask : Task, ICancelableTask { private readonly object m_cancellationGate = new(); private readonly CancellationTokenSource m_cancellation = new(); @@ -83,25 +84,42 @@ public override bool Execute() var publisherCache = new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact); using FileLease activity = publisherCache.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); bool prepared = BuildEngine is IBuildEngine4 engine - && TaskRuntimeBuildScope.Read(engine, "publication:" + cache + "/" + fingerprint, load, verifyOutputs: false, cancellation: cancellation) - is ITaskItem[] publication - && publication.Length == files.Length - && publication.Zip(files).All(static pair => pair.First.ItemSpec == pair.Second.source - && pair.First.GetMetadata("RelativePath") == pair.Second.relative - && pair.First.GetMetadata("FileHash") == pair.Second.hash); + && TaskRuntimeBuildScope.Read( + engine, + "publication:" + cache + "/" + fingerprint, + load, + verifyOutputs: false, + cancellationToken: cancellation + ) + is ITaskItem[] publication + && publication.Length == files.Length + && publication.Zip(files).All(static pair => ( + pair.First.ItemSpec == pair.Second.source + && pair.First.GetMetadata("RelativePath") == pair.Second.relative + && pair.First.GetMetadata("FileHash") == pair.Second.hash + )); if (!prepared) { - using FileLease ownership = FileLease.AcquireAsync(destination + ".lock", - Timeout.InfiniteTimeSpan, cancellation).AsTask().GetAwaiter().GetResult(); + using FileLease ownership = FileLease.AcquireAsync( + destination + ".lock", + Timeout.InfiniteTimeSpan, + cancellation + ).AsTask().GetAwaiter().GetResult(); TaskRuntimePreparation.ValidateSources(files, cancellation); if (!TaskRuntimePreparation.IsComplete(Path.Combine(destination, "Runtime"), files, cancellation)) + { TaskRuntimePreparation.PublishCandidate(destination, files, cancellation); + } TaskRuntimePreparation.ValidateSources(files, cancellation); } PublishedAssembly = Path.Combine(destination, "Runtime", "Inno.Build.Tasks.dll"); using (FileLease ownership = FileLease.AcquireAsync(destination + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult()) + .AsTask() + .GetAwaiter() + .GetResult() + ) { publisherCache.Record(destination, destination + ".lock", [], null, null, cancellation); + } RegisterReader(load, PublishedAssembly); Log.LogMessage(MessageImportance.Normal, "INNO-TASK-HOST verified {0}", fingerprint); return true; @@ -127,15 +145,22 @@ is ITaskItem[] publication public void Cancel() { lock (m_cancellationGate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } } private TaskRuntimePreparation.RuntimeFile[] FreezeFiles() => TaskRuntimePreparation.FreezeFiles(InputFiles); + private static string RequireAbsolute(string path) => TaskRuntimePreparation.RequireAbsolute(path); + private static void RegisterReader( string load, string assembly ) => TaskRuntimePreparation.RegisterReader(load, assembly); + private static void RegisterProcessOwner(string directory) => TaskRuntimePreparation.RegisterProcessOwner(directory); } diff --git a/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs b/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs index 69be54df3..fee614bf8 100644 --- a/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs @@ -1,7 +1,8 @@ using System; using System.IO; -using Inno.Core.IO; using Microsoft.Build.Framework; +using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.TaskHosting; @@ -47,9 +48,15 @@ public override bool Execute() PathBoundary.RequireUnlinkedPath(root, bootstrap); string assembly = Path.GetFullPath(typeof(RegisterTaskPublisherTask).Assembly.Location); string expected = Path.Combine(directory, "Inno.Build.TaskHosting.dll"); - if (!string.Equals(assembly, expected, OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + if (!string.Equals( + assembly, + expected, + OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal + )) { throw new InvalidOperationException("Publisher ownership must identify this task's actual private assembly."); + } TaskRuntimePreparation.RegisterProcessOwner(directory); TaskRuntimePreparation.RegisterProcessOwner(bootstrap); return true; diff --git a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs index 25b128a84..6a7ec45e6 100644 --- a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs @@ -4,8 +4,10 @@ using System.IO; using System.Linq; using System.Threading; -using Inno.Core.IO; +using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; @@ -13,7 +15,7 @@ namespace Inno.Build.TaskHosting; /// Coordinates SDK restore writes for explicitly selected project closures. /// Parent solution entry points are excluded from these owned restores. /// -public sealed class RestoreOwnedProjectTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed class RestoreOwnedProjectTask : Task, ICancelableTask { private readonly object m_gate = new(); private readonly CancellationTokenSource m_cancellation = new(); @@ -49,9 +51,13 @@ public override bool Execute() try { if (BuildEngine is not IBuildEngine3 engine || !Path.IsPathFullyQualified(LockPath)) + { throw new ArgumentException("Owned restore requires an MSBuild node and an absolute write-owner lock."); + } if (Projects.Length == 0) + { throw new ArgumentException("Owned restore requires at least one explicitly selected project."); + } CancellationToken token = m_cancellation.Token; token.ThrowIfCancellationRequested(); var projects = new List(Projects.Length); @@ -60,7 +66,9 @@ public override bool Execute() { string path = project.GetMetadata("FullPath"); if (!File.Exists(path)) + { throw new FileNotFoundException("An owned restore project is missing.", path); + } var properties = new Hashtable(StringComparer.OrdinalIgnoreCase); Apply(project.GetMetadata("AdditionalProperties").Split(';', StringSplitOptions.RemoveEmptyEntries), properties); Apply(Properties, properties); @@ -72,7 +80,9 @@ public override bool Execute() try { ownership = FileLease.AcquireAsync(LockPath, Timeout.InfiniteTimeSpan, token) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); } finally { @@ -89,13 +99,23 @@ public override bool Execute() { "SolutionPath", "SolutionDir", "SolutionName", "SolutionFileName", "SolutionExt", "RestoreGraphProjectInput", "_RestoreSolutionFileUsed" - }.Concat(Projects[index].GetMetadata("GlobalPropertiesToRemove") - .Split(';', StringSplitOptions.RemoveEmptyEntries)) + } + .Concat( + Projects[index].GetMetadata("GlobalPropertiesToRemove") + .Split(';', StringSplitOptions.RemoveEmptyEntries) + ) .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); } - BuildEngineResult result = engine.BuildProjectFilesInParallel(projects.ToArray(), ["Restore"], - globals.ToArray(), removed, versions, returnTargetOutputs: false); + BuildEngineResult result = engine.BuildProjectFilesInParallel( + projects.ToArray(), + ["Restore"], + globals.ToArray(), + removed, + versions, + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); return result.Result; } @@ -121,8 +141,12 @@ public override bool Execute() public void Cancel() { lock (m_gate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } } private static void Apply( @@ -133,8 +157,10 @@ IDictionary properties { int separator = declaration.IndexOf('='); if (separator <= 0) + { throw new ArgumentException("Restore properties require explicit name=value declarations."); - properties[declaration[..separator]] = Microsoft.Build.Evaluation.ProjectCollection.Unescape(declaration[(separator + 1)..]); + } + properties[declaration[..separator]] = ProjectCollection.Unescape(declaration[(separator + 1)..]); } } } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs index db8fa5cb4..836560801 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs @@ -5,12 +5,14 @@ using System.Threading.Tasks; using Microsoft.Build.Framework; +using BuildTask = Microsoft.Build.Utilities.Task; + namespace Inno.Build.TaskHosting; /// /// Claims bootstrap storage before SDK compilation without depending on the full task runtime. /// -public sealed class TaskRuntimeBootstrapOwner : Microsoft.Build.Utilities.Task +public sealed class TaskRuntimeBootstrapOwner : BuildTask { /// /// Gets or sets the absolute publisher root managed by the standard distribution. @@ -51,10 +53,18 @@ public override bool Execute() // The IDE build host must not keep the normal SDK output file locked between builds. Assembly foundation = Assembly.Load(File.ReadAllBytes(FoundationAssembly)); Type owner = foundation.GetType("Inno.Core.IO.ProcessOwnedDirectory", throwOnError: true)!; - MethodInfo create = owner.GetMethod("CreateForProcessAsync", BindingFlags.Public | BindingFlags.Static, - null, [typeof(string), typeof(string), typeof(CancellationToken)], null)!; + MethodInfo create = owner.GetMethod( + "CreateForProcessAsync", + BindingFlags.Public | BindingFlags.Static, + null, + [typeof(string), typeof(string), typeof(CancellationToken)], + null + )!; object pending = create.Invoke(null, [Root, Identity, CancellationToken.None])!; - var operation = (Task)pending.GetType().GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance)!.Invoke(pending, null)!; + Task operation = (Task)pending + .GetType() + .GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance)! + .Invoke(pending, null)!; Directory = operation.GetAwaiter().GetResult(); return true; } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs index 680eac2ef..a9e848fed 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs @@ -19,25 +19,36 @@ internal static class TaskRuntimeBuildScope string identity, string load, bool verifyOutputs = true, - CancellationToken cancellation = default + CancellationToken cancellationToken = default ) { if (engine.GetRegisteredTaskObject(C_PREFIX + identity, RegisteredTaskObjectLifetime.Build) is not string[][] rows) + { return null; + } ITaskItem[] outputs = Restore(rows); string assembly = outputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec; string runtime = Path.GetDirectoryName(assembly)!; string publication = Path.GetDirectoryName(runtime)!; string owner = Path.GetDirectoryName(publication)!; if (!Directory.Exists(publication)) + { return null; + } try { - using FileLease activity = FileLease.AcquireSharedAsync(Path.Combine(owner, "owner.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); - using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); - if (verifyOutputs && !TaskRuntimePreparation.IsComplete(runtime, TaskRuntimePreparation.FreezeFiles(outputs), cancellation)) + using FileLease activity = FileLease.AcquireSharedAsync(Path.Combine(owner, "owner.lock"), TimeSpan.Zero, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.Zero, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + if (verifyOutputs + && !TaskRuntimePreparation.IsComplete(runtime, TaskRuntimePreparation.FreezeFiles(outputs), cancellationToken) + ) { return null; + } TaskRuntimePreparation.RegisterReader(load, assembly); return outputs; } @@ -53,8 +64,12 @@ internal static void Register( ITaskItem[] outputs ) { string[][] rows = outputs.Select(static output => new[] { output.ItemSpec } - .Concat(output.CloneCustomMetadata().Keys.Cast().Order(StringComparer.Ordinal) - .SelectMany(name => new[] { name, output.GetMetadata(name) })).ToArray()).ToArray(); + .Concat( + output.CloneCustomMetadata().Keys.Cast() + .Order(StringComparer.Ordinal) + .SelectMany(name => new[] { name, output.GetMetadata(name) }) + ) + .ToArray()).ToArray(); // Only BCL data crosses private task load boundaries. No leases or SDK owners enter the registry. engine.UnregisterTaskObject(C_PREFIX + identity, RegisteredTaskObjectLifetime.Build); engine.RegisterTaskObject(C_PREFIX + identity, rows, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); @@ -67,7 +82,9 @@ private static ITaskItem[] Restore(string[][] rows) { var item = new TaskItem(row[0]); for (int index = 1; index < row.Length; index += 2) + { item.SetMetadata(row[index], row[index + 1]); + } outputs.Add(item); } return outputs.ToArray(); diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs index 909cfb25e..68f8e9d87 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs @@ -4,14 +4,14 @@ using System.Linq; using System.Text.Json; using System.Threading; -using Inno.Core.IO; using Microsoft.Build.Execution; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; internal static class TaskRuntimePackageInputs { - private static readonly string[] S_ASSET_GROUPS = + private static readonly string[] ASSET_GROUPS = [ "compile", "runtime", "native", "resource", "runtimeTargets", "build", "buildMultiTargeting", "buildTransitive", "contentFiles" @@ -20,14 +20,18 @@ internal static class TaskRuntimePackageInputs internal static bool Collect( ProjectInstance project, ISet inputs, - CancellationToken cancellation + CancellationToken cancellationToken ) { string assets = project.GetPropertyValue("ProjectAssetsFile"); if (assets.Length == 0) + { return true; + } assets = Path.GetFullPath(assets, Path.GetDirectoryName(project.FullPath)!); if (!File.Exists(assets)) + { return false; + } inputs.Add(assets); using JsonDocument document = JsonDocument.Parse(File.ReadAllText(assets)); JsonElement root = document.RootElement; @@ -37,28 +41,44 @@ CancellationToken cancellation string runtime = project.GetPropertyValue("RuntimeIdentifier"); string suffix = runtime.Length == 0 ? string.Empty : "/" + runtime; if (!targets.TryGetProperty(framework + suffix, out JsonElement target) - && !targets.TryGetProperty(moniker + suffix, out target)) + && !targets.TryGetProperty(moniker + suffix, out target) + ) { return false; + } JsonElement libraries = root.GetProperty("libraries"); - string[] folders = root.GetProperty("packageFolders").EnumerateObject() - .Select(static folder => folder.Name).ToArray(); + string[] folders = root.GetProperty("packageFolders") + .EnumerateObject() + .Select(static folder => folder.Name) + .ToArray(); foreach (JsonProperty dependency in target.EnumerateObject()) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (dependency.Value.GetProperty("type").GetString() != "package") + { continue; + } JsonElement library = libraries.GetProperty(dependency.Name); string relative = library.GetProperty("path").GetString() - ?? throw new InvalidDataException("A restored task package has no location."); + ?? throw new InvalidDataException("A restored task package has no location."); string? directory = folders.Select(folder => PathBoundary.Resolve(folder, relative)) .FirstOrDefault(Directory.Exists); if (directory is null) - throw new DirectoryNotFoundException($"The task runtime package '{dependency.Name}' is absent from its restored package roots."); + { + throw new DirectoryNotFoundException( + $"The task runtime package '{dependency.Name}' is absent from its restored package roots." + ); + } var selected = new HashSet(StringComparer.Ordinal); - foreach (string group in S_ASSET_GROUPS) + foreach (string group in ASSET_GROUPS) + { if (dependency.Value.TryGetProperty(group, out JsonElement entries)) + { foreach (JsonProperty entry in entries.EnumerateObject()) + { selected.Add(entry.Name); + } + } + } // Analyzer assemblies are selected from the package file inventory by the SDK, // rather than represented as a separate target asset group. foreach (JsonElement entry in library.GetProperty("files").EnumerateArray()) @@ -66,17 +86,26 @@ CancellationToken cancellation string path = entry.GetString()!; if (path.StartsWith("analyzers/", StringComparison.Ordinal) && !path.Contains("/vb/", StringComparison.Ordinal) - && !path.Contains("/fs/", StringComparison.Ordinal)) + && !path.Contains("/fs/", StringComparison.Ordinal) + ) { selected.Add(path); + } } foreach (string relativeInput in selected) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (Path.GetFileName(relativeInput) == "_._") + { continue; + } string input = PathBoundary.Resolve(directory, relativeInput); if (!File.Exists(input)) - throw new FileNotFoundException($"The restored task runtime input '{dependency.Name}/{relativeInput}' is absent.", input); + { + throw new FileNotFoundException( + $"The restored task runtime input '{dependency.Name}/{relativeInput}' is absent.", + input + ); + } inputs.Add(input); } } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs index 3ce9ba7ba..1d59c713a 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs @@ -19,13 +19,15 @@ internal static class TaskRuntimePreparation string cache, string request, string load, - CancellationToken cancellation + CancellationToken cancellationToken ) { var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact); - using FileLease activity = publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); + using FileLease activity = publisher.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); string index = Path.Combine(cache, request + ".request.json"); if (!File.Exists(index)) + { return null; + } RuntimeFile[] files; try { @@ -38,18 +40,26 @@ CancellationToken cancellation return null; } if (files.Length == 0) + { return null; + } string assembly = files.Single(static file => file.relative == "Inno.Build.Tasks.dll").source; string runtime = Path.GetDirectoryName(assembly)!; string publication = Path.GetDirectoryName(runtime)!; PathBoundary.RequireUnlinkedPath(cache, publication); if (Path.GetRelativePath(cache, publication) != Fingerprint(files) - || files.Any(file => file.source != PathBoundary.Resolve(runtime, file.relative))) + || files.Any(file => file.source != PathBoundary.Resolve(runtime, file.relative)) + ) { return null; - using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.FromSeconds(30), cancellation) - .AsTask().GetAwaiter().GetResult(); - if (!IsComplete(runtime, files, cancellation)) + } + using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.FromSeconds(30), cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + if (!IsComplete(runtime, files, cancellationToken)) + { return null; + } RegisterReader(load, assembly); return CreateOutputs(files); } @@ -64,39 +74,43 @@ ITaskItem[] outputs RuntimeFile[] files = FreezeFiles(outputs); string path = Path.Combine(cache, request + ".request.json"); AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(files)); - publisher.RecordIndex(path, files.Select(static file => Path.GetDirectoryName(Path.GetDirectoryName(file.source)!)!) - .Distinct(StringComparer.Ordinal).ToArray()); + publisher.RecordIndex( + path, + files.Select(static file => Path.GetDirectoryName(Path.GetDirectoryName(file.source)!)!) + .Distinct(StringComparer.Ordinal) + .ToArray() + ); } - private static ITaskItem[] CreateOutputs(IReadOnlyList files) => files.Select(file => - { - var item = new TaskItem(file.source); - item.SetMetadata("RelativePath", file.relative); - item.SetMetadata("FileHash", file.hash); - return (ITaskItem)item; - }).ToArray(); - - internal static string Fingerprint(IReadOnlyList files) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - string.Join('\n', files.Select(static file => file.relative + "|" + file.hash))))); + internal static string Fingerprint(IReadOnlyList files) + => Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes(string.Join('\n', files.Select(static file => file.relative + "|" + file.hash))) + ) + ); internal static ITaskItem[] Publish( string cache, ITaskItem[] inputs, IBuildEngine4 engine, string load, - CancellationToken cancellation + CancellationToken cancellationToken ) { RuntimeFile[] files = FreezeFiles(inputs); string fingerprint = Fingerprint(files); string destination = Path.Combine(cache, fingerprint); var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact); - using FileLease activity = publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); - using FileLease lease = FileLease.AcquireAsync(destination + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult(); - ValidateSources(files, cancellation); - if (!IsComplete(Path.Combine(destination, "Runtime"), files, cancellation)) - PublishCandidate(destination, files, cancellation); - ValidateSources(files, cancellation); + using FileLease activity = publisher.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease lease = FileLease.AcquireAsync(destination + ".lock", Timeout.InfiniteTimeSpan, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + ValidateSources(files, cancellationToken); + if (!IsComplete(Path.Combine(destination, "Runtime"), files, cancellationToken)) + { + PublishCandidate(destination, files, cancellationToken); + } + ValidateSources(files, cancellationToken); ITaskItem[] output = files.Select(file => { var item = new TaskItem(Path.Combine(destination, "Runtime", file.relative)); @@ -104,7 +118,7 @@ CancellationToken cancellation item.SetMetadata("FileHash", file.hash); return (ITaskItem)item; }).ToArray(); - publisher.Record(destination, destination + ".lock", [], null, null, cancellation); + publisher.Record(destination, destination + ".lock", [], null, null, cancellationToken); RegisterReader(load, Path.Combine(destination, "Runtime", "Inno.Build.Tasks.dll")); TaskRuntimeBuildScope.Register(engine, "publication:" + cache + "/" + fingerprint, output); return output; @@ -113,7 +127,9 @@ CancellationToken cancellation internal static RuntimeFile[] FreezeFiles(ITaskItem[] inputFiles) { if (inputFiles.Length == 0) + { throw new InvalidDataException("The task runtime closure is empty."); + } var paths = new HashSet(StringComparer.OrdinalIgnoreCase); RuntimeFile[] files = inputFiles.Select(item => { @@ -121,12 +137,16 @@ internal static RuntimeFile[] FreezeFiles(ITaskItem[] inputFiles) string hash = item.GetMetadata("FileHash").ToUpperInvariant(); if (relative.Length == 0 || relative.Split('/').Any(static segment => segment is "" or "." or "..") || relative.Contains(':') || !paths.Add(relative) - || hash.Length != 64 || hash.Any(static character => !Uri.IsHexDigit(character))) + || hash.Length != 64 || hash.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new InvalidDataException("A runtime input has an invalid path, hash or duplicate identity."); + } return new RuntimeFile(RequireAbsolute(item.ItemSpec), relative, hash); }).OrderBy(static file => file.relative, StringComparer.Ordinal).ToArray(); if (!paths.Contains("Inno.Build.Tasks.dll")) + { throw new InvalidDataException("The task runtime closure has no task assembly."); + } return files; } @@ -134,38 +154,49 @@ internal static string RequireAbsolute(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("Task host locations must be absolute.", nameof(path)); + } return Path.GetFullPath(path); } internal static void ValidateSources( IReadOnlyList files, - CancellationToken cancellation + CancellationToken cancellationToken ) { foreach (RuntimeFile file in files) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (Hash(file.source) != file.hash) + { throw new InvalidDataException($"Task runtime input changed after selection: {file.source}"); + } } } internal static bool IsComplete( string runtime, IReadOnlyList files, - CancellationToken cancellation + CancellationToken cancellationToken ) { if (!Directory.Exists(runtime)) + { return false; + } string[] actual = PathBoundary.EnumerateFiles(runtime) - .Select(path => Path.GetRelativePath(runtime, path).Replace('\\', '/')).ToArray(); + .Select(path => Path.GetRelativePath(runtime, path).Replace('\\', '/')) + .ToArray(); if (!actual.ToHashSet(StringComparer.Ordinal).SetEquals(files.Select(static file => file.relative))) + { return false; + } foreach (RuntimeFile file in files) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (Hash(PathBoundary.Resolve(runtime, file.relative)) != file.hash) + { return false; + } } return true; } @@ -173,25 +204,30 @@ CancellationToken cancellation internal static void PublishCandidate( string destination, IReadOnlyList files, - CancellationToken cancellation + CancellationToken cancellationToken ) { - using ProcessOwnedDirectory candidateOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellation) - .AsTask().GetAwaiter().GetResult(); + using ProcessOwnedDirectory candidateOwner = ProcessOwnedDirectory + .CreateAsync(Path.GetDirectoryName(destination)!, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); string staging = candidateOwner.directory; string runtime = Path.Combine(staging, "Runtime"); try { foreach (RuntimeFile file in files) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); string output = PathBoundary.Resolve(runtime, file.relative); Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.Copy(file.source, output); } - if (!IsComplete(runtime, files, cancellation)) + if (!IsComplete(runtime, files, cancellationToken)) + { throw new InvalidDataException("The copied task runtime did not match its selected closure."); - ValidateSources(files, cancellation); - cancellation.ThrowIfCancellationRequested(); + } + ValidateSources(files, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); try { AtomicDirectory.Install(staging, destination); @@ -216,11 +252,11 @@ internal static string Hash(string path) internal static void RegisterWorkspaceReader( string load, string workspace, - CancellationToken cancellation + CancellationToken cancellationToken ) { string operation = Path.GetDirectoryName(load)!; new BuildCachePublisher(Path.GetDirectoryName(operation)!, BuildCacheArtifactRole.ProcessWorkingDirectory) - .RecordProcessUse(operation, operation + ".lock", [workspace], cancellation); + .RecordProcessUse(operation, operation + ".lock", [workspace], cancellationToken); } internal static void RegisterReader( @@ -235,15 +271,30 @@ string assembly string host = Path.GetDirectoryName(Path.GetDirectoryName(assembly))!; var hostPublisher = new BuildCachePublisher(Path.GetDirectoryName(host)!, BuildCacheArtifactRole.ImmutableArtifact); using FileLease activity = hostPublisher.AcquireUseAsync().AsTask().GetAwaiter().GetResult(); - new BuildCachePublisher(root, BuildCacheArtifactRole.ProcessWorkingDirectory).RecordProcessUse(operation, operation + ".lock", [host]); + new BuildCachePublisher( + root, + BuildCacheArtifactRole.ProcessWorkingDirectory + ).RecordProcessUse(operation, operation + ".lock", [host]); } internal static void RegisterProcessOwner(string directory) { string operation = Path.GetDirectoryName(directory)!; - new BuildCachePublisher(Path.GetDirectoryName(operation)!, BuildCacheArtifactRole.ProcessWorkingDirectory).RecordProcessUse(operation, operation + ".lock", []); + new BuildCachePublisher( + Path.GetDirectoryName(operation)!, + BuildCacheArtifactRole.ProcessWorkingDirectory + ).RecordProcessUse(operation, operation + ".lock", []); } + private static ITaskItem[] CreateOutputs(IReadOnlyList files) + => files.Select(file => + { + var item = new TaskItem(file.source); + item.SetMetadata("RelativePath", file.relative); + item.SetMetadata("FileHash", file.hash); + return (ITaskItem)item; + }).ToArray(); + internal sealed record RuntimeFile( string source, string relative, diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs index 30e4dba30..a462bbab0 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs @@ -1,12 +1,14 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.Build.Evaluation; +using Microsoft.Build.Execution; using Microsoft.Build.Graph; namespace Inno.Build.TaskHosting; @@ -18,77 +20,120 @@ internal static TaskRuntimeRequestSnapshot Capture( string artifacts, IReadOnlyList targets, IDictionary properties, - CancellationToken cancellation + CancellationToken cancellationToken ) { - var globals = properties.Cast().ToDictionary( - static entry => (string)entry.Key, static entry => (string)entry.Value!, StringComparer.OrdinalIgnoreCase); + Dictionary globals = properties.Cast().ToDictionary( + static entry => (string)entry.Key, + static entry => (string)entry.Value!, + StringComparer.OrdinalIgnoreCase + ); using var collection = new ProjectCollection(); var graph = new ProjectGraph(project, globals, collection); bool needsRestore = false; StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var inputs = new HashSet(paths); - var restoreRequests = new List(); - var declarations = new List { project, artifacts, string.Join(";", targets) }; + List restoreRequests = []; + List declarations = [project, artifacts, string.Join(";", targets)]; // Execution ownership reaches nested tool builds, but is not a compiler input itself. // Evaluated source, imports and compiler properties below still capture any derived behavior. - declarations.AddRange(globals.Where(static entry => IsInputProperty(entry.Key)) - .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) - .Select(static entry => entry.Key + "=" + entry.Value)); - foreach (var node in graph.ProjectNodes.OrderBy(static node => node.ProjectInstance.FullPath, paths)) + declarations.AddRange( + globals.Where(static entry => IsInputProperty(entry.Key)) + .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) + .Select(static entry => entry.Key + "=" + entry.Value) + ); + foreach (ProjectGraphNode node in graph.ProjectNodes.OrderBy(static node => node.ProjectInstance.FullPath, paths)) { - cancellation.ThrowIfCancellationRequested(); - var instance = node.ProjectInstance; - foreach (var item in instance.GetItems("InnoBuildInputRestoreProject")) + cancellationToken.ThrowIfCancellationRequested(); + ProjectInstance instance = node.ProjectInstance; + foreach (ProjectItemInstance item in instance.GetItems("InnoBuildInputRestoreProject")) { string restoreProject = Path.GetFullPath(item.EvaluatedInclude, Path.GetDirectoryName(instance.FullPath)!); - var restoreProperties = new Dictionary(instance.GlobalProperties, StringComparer.OrdinalIgnoreCase); + var restoreProperties = new Dictionary( + instance.GlobalProperties, + StringComparer.OrdinalIgnoreCase + ); string[] removedProperties = item.GetMetadataValue("GlobalPropertiesToRemove") .Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (string removedProperty in removedProperties) + { restoreProperties.Remove(removedProperty); + } foreach (string declaration in item.GetMetadataValue("AdditionalProperties") - .Split(';', StringSplitOptions.RemoveEmptyEntries)) - { + .Split(';', StringSplitOptions.RemoveEmptyEntries) + ) { int separator = declaration.IndexOf('='); if (separator <= 0) + { throw new ArgumentException("Owned input restore requires name=value properties."); + } restoreProperties[declaration[..separator]] = ProjectCollection.Unescape(declaration[(separator + 1)..]); } - restoreRequests.Add(new(restoreProject, - new System.Collections.ObjectModel.ReadOnlyDictionary(restoreProperties), removedProperties)); + restoreRequests.Add( + new TaskRuntimeRestoreRequest( + restoreProject, + new ReadOnlyDictionary(restoreProperties), + removedProperties + ) + ); } inputs.Add(instance.FullPath); foreach (string import in instance.ImportPaths) + { inputs.Add(import); - needsRestore |= !TaskRuntimePackageInputs.Collect(instance, inputs, cancellation); - declarations.AddRange(instance.GlobalProperties.Where(static entry => IsInputProperty(entry.Key)) - .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) - .Select(entry => instance.FullPath + "|" + entry.Key + "=" + entry.Value)); - foreach (string property in new[] { "TargetFramework", "RuntimeIdentifier", "NETCoreSdkRuntimeIdentifier", "DefineConstants", "LangVersion", "Nullable", "PathMap", - "NETCoreSdkVersion", "MSBuildToolsPath", "MSBuildSDKsPath", "TreatWarningsAsErrors", "Optimize" }) + } + needsRestore |= !TaskRuntimePackageInputs.Collect(instance, inputs, cancellationToken); + declarations.AddRange( + instance.GlobalProperties.Where(static entry => IsInputProperty(entry.Key)) + .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) + .Select(entry => instance.FullPath + "|" + entry.Key + "=" + entry.Value) + ); + foreach (string property in new[] + { + "TargetFramework", + "RuntimeIdentifier", + "NETCoreSdkRuntimeIdentifier", + "DefineConstants", + "LangVersion", + "Nullable", + "PathMap", + "NETCoreSdkVersion", + "MSBuildToolsPath", + "MSBuildSDKsPath", + "TreatWarningsAsErrors", + "Optimize" + }) { declarations.Add(instance.FullPath + "|" + property + "=" + instance.GetPropertyValue(property)); - foreach (var item in instance.Items) + } + foreach (ProjectItemInstance item in instance.Items) { bool source = item.ItemType is "Compile" or "EmbeddedResource" or "Analyzer" - or "AdditionalFiles" or "EditorConfigFiles" or "GlobalAnalyzerConfigFiles" or "AdditionalCompileInputs"; + or "AdditionalFiles" or "EditorConfigFiles" or "GlobalAnalyzerConfigFiles" or "AdditionalCompileInputs"; bool copy = item.GetMetadataValue("CopyToOutputDirectory") is "Always" or "PreserveNewest"; if (source || copy) { string input = Path.GetFullPath(item.EvaluatedInclude, Path.GetDirectoryName(instance.FullPath)!); if (File.Exists(input)) + { inputs.Add(input); + } } if (item.ItemType == "Reference" && item.GetMetadataValue("HintPath") is string hint && hint.Length != 0) { string input = Path.GetFullPath(hint, Path.GetDirectoryName(instance.FullPath)!); if (File.Exists(input)) + { inputs.Add(input); + } } if (item.ItemType == "PackageReference") + { declarations.Add(instance.FullPath + "|package:" + item.EvaluatedInclude + "=" + item.GetMetadataValue("Version")); + } } - for (DirectoryInfo? directory = new(Path.GetDirectoryName(instance.FullPath)!); directory is not null; directory = directory.Parent) - { + for (DirectoryInfo? directory = new( + Path.GetDirectoryName(instance.FullPath)! + ); directory is not null; directory = directory.Parent + ) { string sdkSelection = Path.Combine(directory.FullName, "global.json"); if (File.Exists(sdkSelection)) { @@ -99,31 +144,44 @@ CancellationToken cancellation } string sdkRoot = graph.EntryPointNodes.Single().ProjectInstance.GetPropertyValue("MSBuildToolsPath"); foreach (string name in new[] { "Microsoft.Build.dll", "Microsoft.Build.Framework.dll", "Microsoft.Build.Utilities.Core.dll", - "Microsoft.Build.Tasks.Core.dll", "MSBuild.runtimeconfig.json", "MSBuild.deps.json" }) - { + "Microsoft.Build.Tasks.Core.dll", "MSBuild.runtimeconfig.json", "MSBuild.deps.json" } + ) { string path = Path.Combine(sdkRoot, name); if (File.Exists(path)) + { inputs.Add(path); + } } string compiler = Path.Combine(sdkRoot, "Roslyn", "bincore"); if (Directory.Exists(compiler)) + { foreach (string path in Directory.EnumerateFiles(compiler)) + { inputs.Add(path); - using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + } + } + using IncrementalHash digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var hashes = new Dictionary(paths); foreach (string declaration in declarations) + { digest.AppendData(Encoding.UTF8.GetBytes(declaration + "\n")); + } foreach (string input in inputs.Order(paths)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); digest.AppendData(Encoding.UTF8.GetBytes(input + "\n")); using FileStream stream = File.OpenRead(input); byte[] hash = SHA256.HashData(stream); digest.AppendData(hash); hashes.Add(input, Convert.ToHexString(hash)); } - return new TaskRuntimeRequestSnapshot(Convert.ToHexString(digest.GetHashAndReset()), needsRestore, - new System.Collections.ObjectModel.ReadOnlyDictionary(hashes), declarations.AsReadOnly(), restoreRequests.AsReadOnly()); + return new TaskRuntimeRequestSnapshot( + Convert.ToHexString(digest.GetHashAndReset()), + needsRestore, + new ReadOnlyDictionary(hashes), + declarations.AsReadOnly(), + restoreRequests.AsReadOnly() + ); } private static bool IsInputProperty(string name) diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs index 171151387..8100ece66 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs @@ -14,12 +14,22 @@ IReadOnlyList restoreRequests internal string DescribeChanges(TaskRuntimeRequestSnapshot current) { string[] changed = inputs.Keys.Union(current.inputs.Keys, StringComparer.Ordinal) - .Where(path => !inputs.TryGetValue(path, out string? planned) - || !current.inputs.TryGetValue(path, out string? actual) || planned != actual).Take(8).ToArray(); + .Where(path => ( + !inputs.TryGetValue(path, out string? planned) + || !current.inputs.TryGetValue(path, out string? actual) || planned != actual + )) + .Take(8) + .ToArray(); if (changed.Length > 0) + { return "Changed files: " + string.Join("; ", changed); - return "Changed declarations: " + string.Join("; ", declarations.Except(current.declarations) - .Concat(current.declarations.Except(declarations)).Take(8)); + } + return "Changed declarations: " + string.Join( + "; ", + declarations.Except(current.declarations) + .Concat(current.declarations.Except(declarations)) + .Take(8) + ); } } diff --git a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs index f5481b72c..d43d5702f 100644 --- a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs +++ b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs @@ -12,6 +12,7 @@ using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.IO; using Inno.Rendering; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -74,6 +75,11 @@ public sealed class CompileShaderTask : BuildTask, ICancelableTask [Required] public string OutputFile { get; set; } = string.Empty; + /// + /// Gets or sets the exact native dependency selection, disabling source production when supplied. + /// + public string NativeDependencyManifestPath { get; set; } = string.Empty; + /// /// Compiles the requested graph artifact and reports compilation failures through MSBuild. /// @@ -82,20 +88,24 @@ public sealed class CompileShaderTask : BuildTask, ICancelableTask /// public override bool Execute() { - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); lock (m_gate) { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); - BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(execution).ResolveShaderTarget(new BuildTargetId(Target)); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(ToolTarget)); + BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(execution).ResolveShaderTarget(new BuildTargetID(Target)); if (!GraphicsApi.TryParse(Renderer, out GraphicsApi renderer)) + { throw new ArgumentException("The shader platform or rendering API is invalid."); - ToolRunner tools = PrepareTools(cancellation.Token, out string compilerFingerprint, out BuildArtifactReadLease toolLease); + } + ToolRunner tools = PrepareTools(out string compilerFingerprint, out BuildArtifactReadLease toolLease, cancellation.Token); using BuildArtifactReadLease toolOwnership = toolLease; CompileProduct(tools, compilerFingerprint, platform, renderer, cancellation.Token); return true; @@ -108,7 +118,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } @@ -124,62 +136,110 @@ public void Cancel() } } - /// - /// Gets or sets the exact native dependency selection, disabling source production when supplied. - /// - public string NativeDependencyManifestPath { get; set; } = string.Empty; - private ToolRunner PrepareTools( - CancellationToken cancellationToken, out string compilerFingerprint, - out BuildArtifactReadLease reading + out BuildArtifactReadLease reading, + CancellationToken cancellationToken ) { - NativeBuildContext context = new(EngineRoot, "release"); - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); + var context = new NativeBuildContext(EngineRoot, "release"); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(ToolTarget)); context = context.WithBindingGenerator(StandardBuildDistribution.Create(execution).build.ResolveBindingGenerator(ToolTarget)); - string cacheKey = "Inno.Build.ShaderTools|" + context.engineRoot + "|" + context.configuration + "|" + ToolTarget + "|" + NativeDependencyManifestPath; + string cacheKey = "Inno.Build.ShaderTools|" + + context.engineRoot + + "|" + + context.configuration + + "|" + + ToolTarget + + "|" + + NativeDependencyManifestPath; IBuildEngine4 engine = BuildEngine as IBuildEngine4 ?? throw new InvalidOperationException("Offline tool preparation requires MSBuild's build-lifetime task ownership."); - string leasePath = Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", - "native", ToolTarget + "-" + context.configuration + ".lock"); + string leasePath = Path.Combine( + context.engineRoot, + "artifacts", + "build-tools", + "tasks", + "native", + ToolTarget + "-" + context.configuration + ".lock" + ); using FileLease lease = FileLease.AcquireAsync(leasePath, Timeout.InfiniteTimeSpan, cancellationToken) - .GetAwaiter().GetResult(); - using FileLease publicationUse = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact) - .AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); + using FileLease publicationUse = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ) + .AcquireUseAsync(cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); if (NativeDependencyManifestPath.Length != 0) { - var selected = NativeDependencyManifest.SelectAsync(EngineRoot, NativeDependencyManifestPath, ToolTarget, - context.configuration, StandardBuildDistribution.Create(execution).build.ResolveNativeProduct(ToolTarget, "shader-tools").plan, - cancellationToken).GetAwaiter().GetResult(); + IReadOnlyList selected = NativeDependencyManifest.SelectAsync( + EngineRoot, + NativeDependencyManifestPath, + ToolTarget, + context.configuration, + StandardBuildDistribution.Create(execution).build.ResolveNativeProduct(ToolTarget, "shader-tools").plan, + cancellationToken + ).GetAwaiter().GetResult(); cacheKey += "|" + string.Join("|", selected.Select(static asset => asset.sha256).Order(StringComparer.Ordinal)); } // Only neutral file names cross task load contexts. MSBuild releases the record when this build ends. string[]? record = engine.GetRegisteredTaskObject(cacheKey, RegisteredTaskObjectLifetime.Build) as string[]; if (record is not null && (record.Length < 3 || !BuildArtifactManifest.IsComplete(record[0], record[1], ["Outputs", "Metadata"]))) + { throw new InvalidDataException("The build-owned offline tool product changed after preparation."); + } if (record is null) { - var distribution = StandardBuildDistribution.Create(execution).build; + BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; if (NativeDependencyManifestPath.Length == 0) - context = context.WithToolchain(distribution.ResolveNativeToolchain(ToolTarget) - .ResolveAsync(context, execution.host, ToolTarget, cancellationToken).AsTask().GetAwaiter().GetResult()); + { + context = context.WithToolchain( + distribution.ResolveNativeToolchain(ToolTarget) + .ResolveAsync(context, execution.host, ToolTarget, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult() + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(ToolTarget, "shader-tools"); ProductNativeBuildPlan plan = contribution.plan; StandardBuildCaches.CreateOwners(context.engineRoot, plan.steps.Select(static step => step.component).ToArray()); using ProductNativeBuildResult products = NativeDependencyManifestPath.Length == 0 - ? contribution.BuildAsync(context, cancellationToken).GetAwaiter().GetResult() - : NativeDependencyManifest.AcquireAsync(EngineRoot, NativeDependencyManifestPath, ToolTarget, - context.configuration, plan, cancellationToken).GetAwaiter().GetResult(); + ? contribution.BuildAsync(context, cancellationToken).GetAwaiter().GetResult() + : NativeDependencyManifest.AcquireAsync( + EngineRoot, + NativeDependencyManifestPath, + ToolTarget, + context.configuration, + plan, + cancellationToken + ).GetAwaiter().GetResult(); NativeBuildProduct product = products.Single(); record = [product.directory, product.fingerprint, .. product.files]; engine.RegisterTaskObject(cacheKey, record, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, "INNO-SHADER-TOOLS prepared {0}; hashedFiles={1}; hashedBytes={2}; nativeProcesses={3}", - product.fingerprint, context.statistics.hashedFiles, context.statistics.hashedBytes, - context.statistics.nativeProcesses); + product.fingerprint, + context.statistics.hashedFiles, + context.statistics.hashedBytes, + context.statistics.nativeProcesses + ); } - reading = BuildArtifactReadLease.AcquireAsync(record[0], Path.Combine(EngineRoot, "artifacts", "native"), record[1], ["Outputs", "Metadata"], cancellationToken) - .AsTask().GetAwaiter().GetResult(); + reading = BuildArtifactReadLease + .AcquireAsync( + record[0], + Path.Combine(EngineRoot, "artifacts", "native"), + record[1], + ["Outputs", "Metadata"], + cancellationToken: cancellationToken + ) + .AsTask() + .GetAwaiter() + .GetResult(); try { string extension = execution.host.services.executableExtension; @@ -210,16 +270,30 @@ CancellationToken cancellationToken string output = Path.GetFullPath(OutputFile); string outputs = Path.GetDirectoryName(output)!; if (Path.GetFileName(outputs) != "Outputs") + { throw new ArgumentException("A shader product must be published inside its owned Outputs directory.", nameof(OutputFile)); + } string directory = Path.GetDirectoryName(outputs)!; string runtime = Path.GetDirectoryName(typeof(CompileShaderTask).Assembly.Location)!; using FileLease lease = FileLease.AcquireAsync(directory + ".lock", Timeout.InfiniteTimeSpan, cancellationToken) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); ShaderBuildInputs source = ShaderBuildInputs.Capture(AssetRoot, cancellationToken); - string[] declarations = [source.fingerprint, compilerFingerprint, platform.id, platform.Resolve(renderer).key, - Renderer, Configuration, ShaderPath, Path.GetFileName(output)]; - NativeBuildInput[] inputs = Directory.EnumerateFiles(runtime, "*.dll").Order(StringComparer.Ordinal) - .Select(path => new NativeBuildInput("compiler-runtime/" + Path.GetFileName(path), path)).ToArray(); + string[] declarations = + [ + source.fingerprint, + compilerFingerprint, + platform.id, + platform.Resolve(renderer).key, + Renderer, + Configuration, + ShaderPath, + Path.GetFileName(output) + ]; + NativeBuildInput[] inputs = Directory.EnumerateFiles(runtime, "*.dll") + .Order(StringComparer.Ordinal) + .Select(path => new NativeBuildInput("compiler-runtime/" + Path.GetFileName(path), path)) + .ToArray(); string fingerprint = NativeBuildFingerprint.Create(declarations, inputs, cancellationToken); if (BuildArtifactManifest.IsComplete(directory, fingerprint, ["Outputs", "Metadata"])) { @@ -227,21 +301,35 @@ CancellationToken cancellationToken return; } using ProcessOwnedDirectory candidateOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(directory)!, cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string candidate = candidateOwner.directory; string candidateOutputs = Path.Combine(candidate, "Outputs"); Directory.CreateDirectory(candidateOutputs); try { using (ProcessOwnedDirectory compilation = StandardBuildCaches.CreateShaderWorkspaceAsync(EngineRoot, cancellationToken) - .AsTask().GetAwaiter().GetResult()) - { - ShaderArtifactBuilder.CompileGraphicsProgram(source, compilation, ShaderPath, platform, renderer, - Path.Combine(candidateOutputs, Path.GetFileName(output)), tools, cancellationToken); + .AsTask() + .GetAwaiter() + .GetResult() + ) { + ShaderArtifactBuilder.CompileGraphicsProgram( + source, + compilation, + ShaderPath, + platform, + renderer, + Path.Combine(candidateOutputs, Path.GetFileName(output)), + tools, + cancellationToken + ); } source.VerifyUnchanged(cancellationToken); if (NativeBuildFingerprint.Create(declarations, inputs, cancellationToken) != fingerprint) + { throw new InvalidDataException("Shader inputs changed during compilation; the candidate was not published."); + } BuildArtifactManifest.Write(candidate, fingerprint, ["Outputs", "Metadata"]); cancellationToken.ThrowIfCancellationRequested(); try diff --git a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs index fa66a29da..5dfa6a772 100644 --- a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs +++ b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs @@ -8,6 +8,7 @@ using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -26,58 +27,70 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask /// [Required] public string EngineRoot { get; set; } = string.Empty; + /// /// Gets or sets the stable component identity declared by the sole binding definition. /// [Required] public string ComponentId { get; set; } = string.Empty; + /// /// Gets or sets the absolute Native owner project, which must belong to this checkout. /// [Required] public string ComponentProject { get; set; } = string.Empty; + /// /// Gets or sets the sole literal definition consumed by both the project and direct generation. /// [Required] public string BindingDefinition { get; set; } = string.Empty; + /// /// Gets or sets the explicit configuration identity selected from the definition. /// [Required] public string TargetId { get; set; } = string.Empty; + /// /// Gets or sets HostSource or TargetArtifacts without deriving publication from a path. /// [Required] public string OutputMode { get; set; } = string.Empty; + /// /// Gets or sets the explicitly selected managed SDK host used to compose the target toolchain. /// [Required] public string DotnetHost { get; set; } = string.Empty; + /// /// Gets or sets comparison without publication. /// public bool CheckOnly { get; set; } + /// /// Gets or sets an optional request-owned descriptor destination written only after success. /// public string DescriptorOutputPath { get; set; } = string.Empty; + /// /// Gets or sets an optional expected identity; stale requests fail before generation. /// public string ExpectedFingerprint { get; set; } = string.Empty; + /// /// Gets the single source selected after complete publication or successful comparison. /// [Output] public string GeneratedBindings { get; private set; } = string.Empty; + /// /// Gets the complete validated input identity. /// [Output] public string GenerationFingerprint { get; private set; } = string.Empty; + /// /// Gets whether the selected generated context requires runtime-import initialization. /// @@ -90,6 +103,7 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask /// [Output] public string LibraryKind { get; private set; } = string.Empty; + /// /// Gets the complete native artifacts and compilation requirements selected by this operation. /// @@ -108,16 +122,6 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask [Output] public string ArtifactOwnerDirectory { get; private set; } = string.Empty; - /// - /// Cancels owned work before retiring the task cancellation source. - /// - public void Cancel() - { - lock (m_lifecycle) - if (!m_completed) - m_cancellation.Cancel(); - } - /// /// Gets or sets an exact dependency selection; selected bindings are imported without generation. /// @@ -133,6 +137,20 @@ public void Cancel() /// public string Configuration { get; set; } = "release"; + /// + /// Cancels owned work before retiring the task cancellation source. + /// + public void Cancel() + { + lock (m_lifecycle) + { + if (!m_completed) + { + m_cancellation.Cancel(); + } + } + } + /// /// Executes one explicit component request and publishes task outputs only after success. /// @@ -146,31 +164,53 @@ public override bool Execute() CancellationToken cancellation = m_cancellation.Token; cancellation.ThrowIfCancellationRequested(); if (!Enum.TryParse(OutputMode, out NativeBindingOutputMode mode) || !Enum.IsDefined(mode)) + { throw new ArgumentException("Binding output mode must be explicitly declared.", nameof(OutputMode)); + } string root = Path.GetFullPath(EngineRoot); string project = Path.GetRelativePath(root, Path.GetFullPath(ComponentProject)).Replace('\\', '/'); string definition = Path.GetRelativePath(root, Path.GetFullPath(BindingDefinition)).Replace('\\', '/'); - var owner = new NativeComponentDescriptor(ComponentId, project, project, - bindingDefinition: definition); + var owner = new NativeComponentDescriptor(ComponentId, project, project, bindingDefinition: definition); var context = new NativeBuildContext(root, "release"); - BuildCompositionContext captured = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(TargetId)); - var execution = new BuildCompositionContext(DotnetHost, captured.applicationDirectory, - captured.host, captured.toolsTarget); + BuildCompositionContext captured = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(TargetId)); + var execution = new BuildCompositionContext( + DotnetHost, + captured.applicationDirectory, + captured.host, + captured.toolsTarget + ); BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; if (NativeDependencyManifestPath.Length != 0) { if (string.IsNullOrWhiteSpace(ProductId)) + { throw new InvalidDataException("Consume-only binding generation requires its explicit product selection."); + } ProductNativeBuildPlan plan = distribution.ResolveNativeProduct(TargetId, ProductId).plan; - if (!plan.steps.Any(step => step.id == ComponentId && step.component.nativeProject == project - && step.component.bindingDefinition == definition)) + if (!plan.steps.Any(step => ( + step.id == ComponentId && step.component.nativeProject == project + && step.component.bindingDefinition == definition + ))) { throw new InvalidDataException("The selected product does not own this binding component: " + project); - using ProductNativeBuildResult products = NativeDependencyManifest.AcquireAsync(root, - NativeDependencyManifestPath, TargetId, Configuration.ToLowerInvariant(), plan, cancellation).GetAwaiter().GetResult(); - NativeBindingGenerationDescriptor imported = products.bindingGenerations.TryGetValue(project, out var binding) - ? binding : throw new InvalidDataException("The selected dependency does not contain its required bindings."); + } + using ProductNativeBuildResult products = NativeDependencyManifest.AcquireAsync( + root, + NativeDependencyManifestPath, + TargetId, + Configuration.ToLowerInvariant(), + plan, + cancellation + ).GetAwaiter().GetResult(); + NativeBindingGenerationDescriptor imported = products.bindingGenerations.TryGetValue( + project, + out NativeBindingGenerationDescriptor? binding + ) + ? binding + : throw new InvalidDataException("The selected dependency does not contain its required bindings."); if (ExpectedFingerprint.Length != 0 && ExpectedFingerprint != imported.fingerprint) + { throw new InvalidDataException("The dependency binding identity differs from the managed build selection."); + } LibraryKind = plan.steps.Single(step => step.id == ComponentId).options.libraryKind.ToString(); SetOutputs(imported); return true; @@ -178,34 +218,64 @@ public override bool Execute() INativeBindingGenerator generator = distribution.ResolveBindingGenerator(TargetId); context = context.WithBindingGenerator(generator); NativeToolchainSelection toolchain = distribution.ResolveNativeToolchain(TargetId) - .ResolveAsync(context, execution.host, TargetId, cancellation).AsTask().GetAwaiter().GetResult(); + .ResolveAsync(context, execution.host, TargetId, cancellation) + .AsTask() + .GetAwaiter() + .GetResult(); context = context.WithToolchain(toolchain); - Dictionary? expected = ExpectedFingerprint.Length == 0 ? null - : new(StringComparer.Ordinal) { [owner.nativeProject] = ExpectedFingerprint }; + Dictionary? expected = ExpectedFingerprint.Length == 0 + ? null + : new Dictionary(StringComparer.Ordinal) + { + [owner.nativeProject] = ExpectedFingerprint + }; // A source project can also host an offline producer that owns no runtime bindings. NativeComponentBuildOptions[] configured = distribution.platforms .Where(platform => platform.descriptor.id.value == TargetId) .SelectMany(static platform => platform.nativeProducts.Values) .SelectMany(static product => product.plan.steps) - .Where(step => step.component.id == owner.id && step.component.nativeProject == owner.nativeProject - && step.component.bindingDefinition is not null) - .Select(static step => step.options).ToArray(); + .Where(step => ( + step.component.id == owner.id && step.component.nativeProject == owner.nativeProject + && step.component.bindingDefinition is not null + )) + .Select(static step => step.options) + .ToArray(); NativeComponentBuildOptions? selectedOptions = configured.FirstOrDefault(); - if (selectedOptions is not null && configured.Any(options => options.libraryKind != selectedOptions.libraryKind + if (selectedOptions is not null && configured.Any(options => ( + options.libraryKind != selectedOptions.libraryKind || options.bindingLibraryName != selectedOptions.bindingLibraryName - || !options.bindingIncludeDirectories.SequenceEqual(selectedOptions.bindingIncludeDirectories, StringComparer.Ordinal))) - throw new InvalidOperationException($"The registered products for target '{TargetId}' declare ambiguous binding inputs for component '{ComponentId}' in '{project}'."); - Dictionary? componentOptions = selectedOptions is null ? null - : new(StringComparer.Ordinal) { [owner.nativeProject] = selectedOptions }; - var request = new NativeBindingGenerationRequest([owner], TargetId, mode, CheckOnly, expected, componentOptions); + || !options.bindingIncludeDirectories.SequenceEqual(selectedOptions.bindingIncludeDirectories, StringComparer.Ordinal) + ))) { + throw new InvalidOperationException( + $"The registered products for target '{TargetId}' declare ambiguous binding inputs for component '{ComponentId}' in '{project}'." + ); + } + Dictionary? componentOptions = selectedOptions is null + ? null + : new Dictionary(StringComparer.Ordinal) { [owner.nativeProject] = selectedOptions }; + var request = new NativeBindingGenerationRequest( + [owner], + TargetId, + mode, + CheckOnly, + expected, + componentOptions + ); using NativeBindingGenerationResult closure = generator.GenerateAsync(context, request, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); NativeBindingGenerationDescriptor result = closure[owner.nativeProject]; LibraryKind = selectedOptions?.libraryKind.ToString() ?? string.Empty; SetOutputs(result); - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, "INNO-BINDINGS-PREPARE project={0} fingerprint={1} batches={2} generations={3}", - project, result.fingerprint, context.statistics.bindingBatches, context.statistics.bindingGenerations); + project, + result.fingerprint, + context.statistics.bindingBatches, + context.statistics.bindingGenerations + ); return true; } catch (Exception failure) @@ -222,10 +292,13 @@ public override bool Execute() } } } + private void SetOutputs(NativeBindingGenerationDescriptor result) { if (DescriptorOutputPath.Length != 0) + { result.Write(DescriptorOutputPath); + } GeneratedBindings = result.bindingsPath; GenerationFingerprint = result.fingerprint; UsesRuntimeImports = result.usesRuntimeImports; @@ -233,5 +306,4 @@ private void SetOutputs(NativeBindingGenerationDescriptor result) ArtifactDirectory = result.artifactDirectory; ArtifactOwnerDirectory = result.artifactOwnerDirectory; } - } diff --git a/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs b/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs index 7b231fe0a..675fbd249 100644 --- a/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs +++ b/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs @@ -2,6 +2,7 @@ using System.Threading; using Microsoft.Build.Framework; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -27,8 +28,14 @@ public override bool Execute() { try { - BuildMaintenanceApplication.CleanAsync(EngineRoot, new BuildCachePolicy(), false, false, null, - CancellationToken.None).GetAwaiter().GetResult(); + BuildMaintenanceApplication.CleanAsync( + EngineRoot, + new BuildCachePolicy(), + false, + false, + null, + CancellationToken.None + ).GetAwaiter().GetResult(); Log.LogMessage(MessageImportance.High, "INNO-CACHE-MAINTENANCE root=Editor budgetSeconds=5"); } catch (Exception failure) diff --git a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs index cc8a87375..669698668 100644 --- a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs +++ b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs @@ -4,12 +4,14 @@ using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Microsoft.Build.Framework; using Inno.Build; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -81,53 +83,78 @@ public override bool Execute() { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { long started = Stopwatch.GetTimestamp(); - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(TargetId)); - var distribution = StandardBuildDistribution.Create(execution).build; + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(TargetId)); + BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; NativeProductContribution contribution = distribution.ResolveNativeProduct(TargetId, ProductId); ProductNativeBuildPlan plan = contribution.plan; if (NativeDependencyManifestPath.Length != 0) { - using ProductNativeBuildResult imported = NativeDependencyManifest.AcquireAsync(EngineRoot, - NativeDependencyManifestPath, TargetId, Configuration.ToLowerInvariant(), plan, cancellation.Token) - .GetAwaiter().GetResult(); + using ProductNativeBuildResult imported = NativeDependencyManifest + .AcquireAsync( + EngineRoot, + NativeDependencyManifestPath, + TargetId, + Configuration.ToLowerInvariant(), + plan, + cancellation.Token + ) + .GetAwaiter() + .GetResult(); Deploy(imported, plan, cancellation.Token); - Log.LogMessage(MessageImportance.High, - $"INNO-NATIVE-CONSUME products={imported.Count} processes=0 bindingGenerations=0 elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1}"); + Log.LogMessage( + MessageImportance.High, + $"INNO-NATIVE-CONSUME products={imported.Count} processes=0 bindingGenerations=0 elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1}" + ); return true; } - var context = new NativeBuildContext(EngineRoot, Configuration.ToLowerInvariant()) + NativeBuildContext context = new NativeBuildContext(EngineRoot, Configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(TargetId)); NativeToolchainSelection toolchain = distribution.ResolveNativeToolchain(TargetId) - .ResolveAsync(context, execution.host, TargetId, cancellation.Token).AsTask().GetAwaiter().GetResult(); + .ResolveAsync(context, execution.host, TargetId, cancellation.Token) + .AsTask() + .GetAwaiter() + .GetResult(); context = context.WithToolchain(toolchain); StandardBuildCaches.CreateOwners(context.engineRoot, plan.steps.Select(static step => step.component).ToArray()); IBuildEngine4 engine = BuildEngine as IBuildEngine4 - ?? throw new InvalidOperationException("Native preparation requires MSBuild build-lifetime ownership."); - string scope = NativeBuildFingerprint.Create([context.engineRoot, context.configuration, TargetId, plan.productId], []); + ?? throw new InvalidOperationException("Native preparation requires MSBuild build-lifetime ownership."); + string scope = NativeBuildFingerprint.Create([context.engineRoot, context.configuration, TargetId, plan.productID], []); string cacheKey = "Inno.Build.NativePreparation/" + scope; - using FileLease preparation = AcquirePreparation(engine, - Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", "native", scope + ".lock"), cancellation.Token); + using FileLease preparation = AcquirePreparation( + engine, + Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", "native", scope + ".lock"), + cancellation.Token + ); string[][][] candidates = engine.GetRegisteredTaskObject(cacheKey, RegisteredTaskObjectLifetime.Build) as string[][][] ?? []; ProductNativeBuildResult? prepared = null; string requestIdentity = string.Empty; foreach (string[][] candidate in candidates) { string identity = candidate[0][1]; - prepared = ProductNativePreparation.TryAcquireAsync(context, plan, candidate, identity, cancellation.Token).GetAwaiter().GetResult(); + prepared = ProductNativePreparation.TryAcquireAsync(context, plan, candidate, identity, cancellation.Token) + .GetAwaiter() + .GetResult(); if (prepared is null) + { continue; + } requestIdentity = identity; break; } if (prepared is null) + { requestIdentity = ProductNativePreparation.FreezeAsync(context, plan, cancellation.Token).GetAwaiter().GetResult(); + } bool reused = prepared is not null; - using var products = prepared ?? contribution.BuildAsync(context, cancellation.Token).GetAwaiter().GetResult(); + using ProductNativeBuildResult products = prepared + ?? contribution.BuildAsync(context, cancellation.Token).GetAwaiter().GetResult(); cancellation.Token.ThrowIfCancellationRequested(); Deploy(products, plan, cancellation.Token); string[][]? completed = reused ? null : ProductNativePreparation.Capture(context, plan, products, requestIdentity); @@ -141,17 +168,23 @@ public override bool Execute() engine.RegisterTaskObject(cacheKey, retained, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); } NativeBuildStatistics statistics = context.statistics; - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, $"INNO-NATIVE-PREPARE request={requestIdentity} elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1} " + $"hashedFiles={statistics.hashedFiles} hashedBytes={statistics.hashedBytes} " + $"processes={statistics.nativeProcesses} products={products.Count} " + $"reusedPreparation={(reused ? 1 : 0)} " + $"bindingBatches={statistics.bindingBatches} bindingGenerations={statistics.bindingGenerations} " + $"outputFiles={statistics.outputFiles} outputBytes={statistics.outputBytes} " - + $"materializedBytes={statistics.materializedBytes} managedProcesses={statistics.managedProcesses}"); + + $"materializedBytes={statistics.materializedBytes} managedProcesses={statistics.managedProcesses}" + ); foreach (NativeBuildPhaseStatistics phase in statistics.phases) - Log.LogMessage(MessageImportance.High, - $"INNO-NATIVE-PHASE name={phase.phase} files={phase.files} bytes={phase.bytes} reusedReads={phase.reusedReads}"); + { + Log.LogMessage( + MessageImportance.High, + $"INNO-NATIVE-PHASE name={phase.phase} files={phase.files} bytes={phase.bytes} reusedReads={phase.reusedReads}" + ); + } return true; } catch (Exception failure) @@ -162,7 +195,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } @@ -183,26 +218,35 @@ private void Deploy( ProductNativeBuildPlan plan, CancellationToken cancellationToken ) { - var generations = products.bindingGenerations; - var linkage = plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) + IReadOnlyDictionary generations = products.bindingGenerations; + Dictionary linkage = plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, - static group => group.Select(step => step.options.libraryKind).Distinct().Single(), StringComparer.Ordinal); + .ToDictionary( + static group => group.Key, + static group => group.Select(step => step.options.libraryKind).Distinct().Single(), + StringComparer.Ordinal + ); if (BindingSelectionInputPath.Length != 0) + { NativeBindingGenerationDescriptor.ValidateSelection(BindingSelectionInputPath, generations, linkage); + } ProductNativeDeployment.InstallAsync(products, plan, OutputDirectory, cancellationToken).GetAwaiter().GetResult(); if (BindingSelectionOutputPath.Length != 0) + { NativeBindingGenerationDescriptor.WriteSelection(BindingSelectionOutputPath, generations, linkage); + } } private static FileLease AcquirePreparation( IBuildEngine4 engine, string path, - CancellationToken cancellation + CancellationToken cancellationToken ) { - System.Threading.Tasks.Task pending = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).AsTask(); + Task pending = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellationToken).AsTask(); if (pending.IsCompleted) + { return pending.GetAwaiter().GetResult(); + } engine.Yield(); try { diff --git a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs index 175879237..dbac74d23 100644 --- a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs +++ b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs @@ -7,6 +7,7 @@ using Inno.Build.Distribution.Standard; using Inno.Build.SupportPacks; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -62,19 +63,29 @@ public override bool Execute() { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); - var context = new BuildCompositionContext(ToolchainEnvironment.ResolveExecutable(DotnetHost), - AppContext.BaseDirectory, execution.host, execution.toolsTarget); - using PlayerSupportPackPublication installed = StandardBuildDistribution.Create(context).build.supportPacks.PublishAsync( - EngineRoot, OutputRoot, new BuildTargetId(Target), DotnetHost, cancellation.Token) - .AsTask().GetAwaiter().GetResult(); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(ToolTarget)); + var context = new BuildCompositionContext( + ToolchainEnvironment.ResolveExecutable(DotnetHost), + AppContext.BaseDirectory, + execution.host, + execution.toolsTarget + ); + using PlayerSupportPackPublication installed = StandardBuildDistribution.Create(context).build.supportPacks + .PublishAsync(EngineRoot, OutputRoot, new BuildTargetID(Target), DotnetHost, cancellationToken: cancellation.Token) + .AsTask() + .GetAwaiter() + .GetResult(); Log.LogMessage(MessageImportance.Normal, "Installed Player Support Pack: {0}", installed.directory); foreach (string diagnostic in installed.diagnostics) + { Log.LogWarning(diagnostic); + } return true; } catch (Exception failure) @@ -85,7 +96,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs new file mode 100644 index 000000000..6379573be --- /dev/null +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Inno.Build.Toolchains; + +/// +/// Copies filtered native outputs into the engine's rebuildable dependency store. +/// +public static class BuildArtifactCopier +{ + private const string C_DSYM_TOKEN = ".dSYM"; + + /// + /// Copies all artifacts accepted by one product policy into its output directory. + /// + /// + /// The native dependency root containing the configured build directory. + /// + /// + /// The destination directory receiving normalized artifacts. + /// + /// + /// The normalized native build configuration. + /// + /// + /// The immutable filtering and naming policy. + /// + public static void CopyArtifacts( + string buildRoot, + string outputDir, + string config, + BuildArtifactOptions options + ) { + string buildDir = Path.Combine(buildRoot, options.buildDirName); + if (!Directory.Exists(buildDir)) + { + throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); + } + + List candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) + .Where(path => + { + if (path.Contains(C_DSYM_TOKEN, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string ext = Path.GetExtension(path); + if (!options.extensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) + { + return false; + } + + string fileName = Path.GetFileName(path); + if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) + || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config) + ) { + return false; + } + + if (options.requiredPathTokens is null || options.requiredPathTokens.Count == 0) + { + return true; + } + + string normalized = path.Replace('\\', '/'); + return ToolchainEnvironment.ContainsAny(normalized, options.requiredPathTokens.ToArray()); + }) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (candidates.Count == 0) + { + throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); + } + + (string source, string name)[] artifacts = candidates.Select(source => ( + source, + name: options.normalizeOutputName(Path.GetFileName(source), config))).ToArray(); + IGrouping? duplicate = artifacts + .GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(static group => group.Count() > 1); + if (duplicate is not null) + { + throw new InvalidOperationException($"Multiple native artifacts produce '{duplicate.Key}'."); + } + + Directory.CreateDirectory(outputDir); + foreach ((string source, string name) artifact in artifacts) + { + File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); + } + } + + private static bool MatchesConfiguration( + string path, + string config + ) { + string name = Path.GetFileNameWithoutExtension(path); + if (name.EndsWith("Debug", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } + if (name.EndsWith("Release", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } + string? directory = Path.GetDirectoryName(path); + if (string.IsNullOrEmpty(directory)) + { + return true; + } + string[] segments = directory.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + for (int index = segments.Length - 1; index >= 0; index--) + { + if (segments[index].Equals("Debug", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } + if (segments[index].Equals("Release", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } + } + return true; + } +} diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs index 0eac115e5..3d0a985ba 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs @@ -3,8 +3,8 @@ using System.IO; using System.Linq; using System.Security.Cryptography; -using System.Text.Json; using System.Text; +using System.Text.Json; using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -46,15 +46,19 @@ public static void Write( ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); Dictionary files = ReadFiles(directory, outputDirectories, context); if (files.Count == 0) + { throw new InvalidDataException("A completed artifact must contain output files."); + } using var bytes = new MemoryStream(); using (var writer = new Utf8JsonWriter(bytes)) { writer.WriteStartObject(); writer.WriteString("fingerprint", fingerprint); writer.WriteStartObject("files"); - foreach (var file in files.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + foreach (KeyValuePair file in files.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { writer.WriteString(file.Key, file.Value); + } writer.WriteEndObject(); writer.WriteEndObject(); } @@ -93,17 +97,24 @@ public static bool IsComplete( ) { string path = Path.Combine(directory, C_FILE_NAME); if (!File.Exists(path)) + { return false; + } Dictionary expected; try { using JsonDocument manifest = JsonDocument.Parse(File.ReadAllBytes(path)); JsonElement data = manifest.RootElement; - if (!data.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal) + if (!data.EnumerateObject() + .Select(static entry => entry.Name) + .Order(StringComparer.Ordinal) .SequenceEqual(new[] { "files", "fingerprint" }, StringComparer.Ordinal) - || data.GetProperty("fingerprint").GetString() != fingerprint) + || data.GetProperty("fingerprint").GetString() != fingerprint + ) { return false; - expected = data.GetProperty("files").EnumerateObject() + } + expected = data.GetProperty("files") + .EnumerateObject() .ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); } catch (Exception failure) when (failure is JsonException or InvalidOperationException or ArgumentException) @@ -111,11 +122,13 @@ public static bool IsComplete( return false; } if (expected.Count == 0) + { return false; + } Dictionary files = ReadFiles(directory, outputDirectories, context); return files.Count == expected.Count - && PathBoundary.EnumerateFiles(directory).Count() == files.Count + 1 - && files.All(pair => expected.TryGetValue(pair.Key, out string? value) && pair.Value == value); + && PathBoundary.EnumerateFiles(directory).Count() == files.Count + 1 + && files.All(pair => expected.TryGetValue(pair.Key, out string? value) && pair.Value == value); } private static Dictionary ReadFiles( @@ -125,37 +138,46 @@ private static Dictionary ReadFiles( ) { ArgumentNullException.ThrowIfNull(outputDirectories); string root = Path.GetFullPath(directory); - Dictionary files = new(StringComparer.Ordinal); + var files = new Dictionary(StringComparer.Ordinal); foreach (string relative in outputDirectories) { ArgumentException.ThrowIfNullOrWhiteSpace(relative); string output = Path.GetFullPath(Path.Combine(root, relative)); string check = Path.GetRelativePath(root, output); if (Path.IsPathRooted(check) || check is "." or ".." - || check.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + || check.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { throw new ArgumentException("An artifact output directory must be contained in its root.", nameof(outputDirectories)); + } if (!Directory.Exists(output)) + { continue; + } foreach (string path in PathBoundary.EnumerateFiles(output).Order(StringComparer.Ordinal)) { using FileStream input = File.OpenRead(path); - files.Add(Path.GetRelativePath(root, path).Replace('\\', '/'), - Convert.ToHexStringLower(SHA256.HashData(input))); + files.Add( + Path.GetRelativePath(root, path).Replace('\\', '/'), + Convert.ToHexStringLower(SHA256.HashData(input)) + ); context?.RecordOutputRead(input.Position); } } if (files.Count == 0) + { return files; + } foreach (string path in PathBoundary.EnumerateFiles(root).Order(StringComparer.Ordinal)) { string relative = Path.GetRelativePath(root, path).Replace('\\', '/'); if (relative == C_FILE_NAME || files.ContainsKey(relative)) + { continue; + } using FileStream input = File.OpenRead(path); files.Add(relative, Convert.ToHexStringLower(SHA256.HashData(input))); context?.RecordOutputRead(input.Position); } return files; } - } diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs index 68a849210..bd320573c 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; namespace Inno.Build.Toolchains; @@ -30,107 +28,3 @@ public sealed record BuildArtifactOptions( IReadOnlyCollection? requiredPathTokens, Func normalizeOutputName ); - -/// -/// Copies filtered native outputs into the engine's rebuildable dependency store. -/// -public static class BuildArtifactCopier -{ - private const string DSYM_TOKEN = ".dSYM"; - - /// - /// Copies all artifacts accepted by one product policy into its output directory. - /// - /// - /// The native dependency root containing the configured build directory. - /// - /// - /// The destination directory receiving normalized artifacts. - /// - /// - /// The normalized native build configuration. - /// - /// - /// The immutable filtering and naming policy. - /// - public static void CopyArtifacts( - string buildRoot, - string outputDir, - string config, - BuildArtifactOptions options - ) { - var buildDir = Path.Combine(buildRoot, options.buildDirName); - if (!Directory.Exists(buildDir)) - throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); - - var candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) - .Where(path => - { - if (path.Contains(DSYM_TOKEN, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - var ext = Path.GetExtension(path); - if (!options.extensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) - { - return false; - } - - var fileName = Path.GetFileName(path); - if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) - || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config)) - { - return false; - } - - if (options.requiredPathTokens == null || options.requiredPathTokens.Count == 0) - { - return true; - } - - var normalized = path.Replace('\\', '/'); - return ToolchainEnvironment.ContainsAny(normalized, options.requiredPathTokens.ToArray()); - }) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - - if (candidates.Count == 0) - throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); - - var artifacts = candidates.Select(source => ( - source, - name: options.normalizeOutputName(Path.GetFileName(source), config))).ToArray(); - var duplicate = artifacts.GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault(static group => group.Count() > 1); - if (duplicate is not null) - throw new InvalidOperationException($"Multiple native artifacts produce '{duplicate.Key}'."); - - Directory.CreateDirectory(outputDir); - foreach (var artifact in artifacts) - File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); - } - - private static bool MatchesConfiguration( - string path, - string config - ) { - string name = Path.GetFileNameWithoutExtension(path); - if (name.EndsWith("Debug", StringComparison.OrdinalIgnoreCase)) - return config.Equals("debug", StringComparison.OrdinalIgnoreCase); - if (name.EndsWith("Release", StringComparison.OrdinalIgnoreCase)) - return config.Equals("release", StringComparison.OrdinalIgnoreCase); - string? directory = Path.GetDirectoryName(path); - if (string.IsNullOrEmpty(directory)) - return true; - string[] segments = directory.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - for (int index = segments.Length - 1; index >= 0; index--) - { - if (segments[index].Equals("Debug", StringComparison.OrdinalIgnoreCase)) - return config.Equals("debug", StringComparison.OrdinalIgnoreCase); - if (segments[index].Equals("Release", StringComparison.OrdinalIgnoreCase)) - return config.Equals("release", StringComparison.OrdinalIgnoreCase); - } - return true; - } -} diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs index 7cace25cc..59c2facf9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs @@ -18,19 +18,7 @@ public static class BackendPrebuiltArchive { private const string C_MANIFEST = "manifest.json"; private const long C_MAX_BYTES = 8L * 1024 * 1024 * 1024; - private static readonly DateTimeOffset S_EPOCH = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); - private sealed record FileRecord( - string owner, - string configuration, - string input, - string path, - string sha256 - ); - private sealed record Inventory( - int version, - string target, - FileRecord[] files - ); + private static readonly DateTimeOffset EPOCH = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); /// /// Creates a fresh platform ZIP from an explicit inventory and an owned staging directory. @@ -65,7 +53,9 @@ public static void Create( using (var zip = new ZipArchive(stream, ZipArchiveMode.Create)) { using (Stream output = Entry(C_MANIFEST).Open()) + { JsonSerializer.Serialize(output, inventory); + } long total = 0; foreach (FileRecord file in inventory.files) { @@ -73,15 +63,20 @@ public static void Create( using FileStream input = File.OpenRead(source); total = checked(total + input.Length); if (total > C_MAX_BYTES) + { throw new InvalidDataException("Backend archive exceeds its size limit."); + } using Stream output = Entry(file.path).Open(); CopyVerified(input, output, file.sha256, input.Length, cancellationToken); } ZipArchiveEntry Entry(string path) { - ZipArchiveEntry entry = zip.CreateEntry(path, path.EndsWith(".zip", StringComparison.Ordinal) ? CompressionLevel.NoCompression : CompressionLevel.Fastest); - entry.LastWriteTime = S_EPOCH; + ZipArchiveEntry entry = zip.CreateEntry( + path, + path.EndsWith(".zip", StringComparison.Ordinal) ? CompressionLevel.NoCompression : CompressionLevel.Fastest + ); + entry.LastWriteTime = EPOCH; entry.ExternalAttributes = 0; return entry; } @@ -127,30 +122,44 @@ public static async Task ExtractAsync( string output = Path.GetFullPath(destination); string parent = Path.GetDirectoryName(output)!; using FileStream stream = File.OpenRead(archivePath); - if (!IsDigest(sha256) || Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)) != sha256) + if (!IsDigest(sha256) + || Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)) != sha256 + ) { throw new InvalidDataException("The backend platform ZIP differs from its receipt."); + } stream.Position = 0; using var zip = new ZipArchive(stream, ZipArchiveMode.Read); ZipArchiveEntry metadata = zip.GetEntry(C_MANIFEST) ?? throw new InvalidDataException("Missing backend inventory."); - if (metadata.Length > 16 * 1024 * 1024 || zip.Entries.Count > 50001) + if (metadata.Length > 16 * 1024 * 1024 || zip.Entries.Count > 50_001) + { throw new InvalidDataException("Backend ZIP inventory exceeds its limit."); + } Inventory inventory; using (Stream input = metadata.Open()) + { inventory = Read(input); + } if (inventory.target != target || zip.Entries.Count != inventory.files.Length + 1) + { throw new InvalidDataException("Backend target or inventory does not match the request."); + } using ProcessOwnedDirectory staging = await ProcessOwnedDirectory.CreateAsync(parent, cancellationToken).ConfigureAwait(false); string payload = Path.Combine(staging.directory, "payload"); Directory.CreateDirectory(payload); - var expected = inventory.files.ToDictionary(static file => file.path, StringComparer.Ordinal); + Dictionary expected = inventory.files.ToDictionary(static file => file.path, StringComparer.Ordinal); long total = 0; foreach (ZipArchiveEntry entry in zip.Entries) { if (entry == metadata) + { continue; - if (!expected.Remove(entry.FullName, out FileRecord? file) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) - || (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0 || (total = checked(total + entry.Length)) > C_MAX_BYTES) + } + if (!expected.Remove(entry.FullName, out FileRecord? file) || ((entry.ExternalAttributes >> 16) & 0xF000) is not (0 or 0x8000) + || (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0 + || (total = checked(total + entry.Length)) > C_MAX_BYTES + ) { throw new InvalidDataException("Unexpected, duplicate, linked or excessive backend ZIP entry: " + entry.FullName); + } string path = PathBoundary.Resolve(payload, entry.FullName); Directory.CreateDirectory(Path.GetDirectoryName(path)!); using Stream input = entry.Open(); @@ -158,31 +167,50 @@ public static async Task ExtractAsync( CopyVerified(input, targetFile, file.sha256, entry.Length, cancellationToken); } if (expected.Count != 0) + { throw new InvalidDataException("Missing backend ZIP entries."); + } byte[] manifestBytes = JsonSerializer.SerializeToUtf8Bytes(inventory); AtomicFile.WriteAllBytes(Path.Combine(payload, C_MANIFEST), manifestBytes); - AtomicFile.WriteAllBytes(Path.Combine(payload, "receipt.json"), JsonSerializer.SerializeToUtf8Bytes(new - { - target, sha256, manifestSha256 = Convert.ToHexStringLower(SHA256.HashData(manifestBytes)) - })); + AtomicFile.WriteAllBytes( + Path.Combine(payload, "receipt.json"), + JsonSerializer.SerializeToUtf8Bytes(new + { + target, + sha256, + manifestSha256 = Convert.ToHexStringLower(SHA256.HashData(manifestBytes)) + }) + ); AtomicDirectory.Publish(payload, output, cancellationToken); } private static Inventory Read(Stream input) { Inventory inventory = JsonSerializer.Deserialize(input) ?? throw new InvalidDataException("Missing backend inventory."); - if (inventory.version != 1 || string.IsNullOrWhiteSpace(inventory.target) || inventory.files is not { Length: > 0 and <= 50000 }) + if (inventory.version != 1 || string.IsNullOrWhiteSpace(inventory.target) || inventory.files is not { Length: > 0 and <= 50_000 }) + { throw new InvalidDataException("Unsupported or empty backend inventory."); + } var paths = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (FileRecord file in inventory.files) { - if (file is null || string.IsNullOrWhiteSpace(file.owner) || string.IsNullOrWhiteSpace(file.configuration) || !IsDigest(file.input) - || !IsDigest(file.sha256) || string.IsNullOrEmpty(file.path) || !paths.Add(file.path) || file.path.Equals(C_MANIFEST, StringComparison.OrdinalIgnoreCase) + if (file is null + || string.IsNullOrWhiteSpace(file.owner) + || string.IsNullOrWhiteSpace(file.configuration) + || !IsDigest(file.input) + || !IsDigest(file.sha256) + || string.IsNullOrEmpty(file.path) + || !paths.Add(file.path) + || file.path.Equals(C_MANIFEST, StringComparison.OrdinalIgnoreCase) || file.path.Equals("receipt.json", StringComparison.OrdinalIgnoreCase) - || file.path.Split('/').Any(static part => part is "" or "." or ".." || part.EndsWith('.') || part.EndsWith(' ') + || file.path.Split('/').Any(static part => ( + part is "" or "." or ".." || part.EndsWith('.') || part.EndsWith(' ') || part.Any(static c => !char.IsAsciiLetterOrDigit(c) && c is not ('.' or '_' or '-')) - || IsReservedName(part))) + || IsReservedName(part) + )) + ) { throw new InvalidDataException("Invalid or duplicated backend file ownership: " + file?.path); + } } return inventory with { files = inventory.files.OrderBy(static file => file.path, StringComparer.Ordinal).ToArray() }; } @@ -191,31 +219,50 @@ private static bool IsReservedName(string part) { string name = part.Split('.')[0].ToUpperInvariant(); return name is "CON" or "PRN" or "AUX" or "NUL" - || name.Length == 4 && name[..3] is ("LPT" or "COM") && name[3] is >= '1' and <= '9'; + || name.Length == 4 && name[..3] is ("LPT" or "COM") && name[3] is >= '1' and <= '9'; } - private static bool IsDigest(string? value) => value is { Length: 64 } && value.All(static c => char.IsAsciiDigit(c) || c is >= 'a' and <= 'f'); + private static bool IsDigest(string? value) + => value is { Length: 64 } && value.All(static c => char.IsAsciiDigit(c) || c is >= 'a' and <= 'f'); private static void CopyVerified( Stream input, Stream output, string digest, long length, - CancellationToken cancellation + CancellationToken cancellationToken ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - byte[] buffer = new byte[81920]; + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[81_920]; long copied = 0; int read; while ((read = input.Read(buffer)) > 0) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if ((copied += read) > length) + { throw new InvalidDataException("Backend payload exceeds its declared length."); + } hash.AppendData(buffer, 0, read); output.Write(buffer, 0, read); } if (copied != length || Convert.ToHexStringLower(hash.GetHashAndReset()) != digest) + { throw new InvalidDataException("Backend payload does not match its inventory."); + } } + + private sealed record FileRecord( + string owner, + string configuration, + string input, + string path, + string sha256 + ); + + private sealed record Inventory( + int version, + string target, + FileRecord[] files + ); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs index 1a8298c58..0241936b6 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs @@ -14,29 +14,37 @@ public sealed class BuildArtifactReadLease : IDisposable { private CoordinatedFileLease? m_lease; - private BuildArtifactReadLease(CoordinatedFileLease lease) => m_lease = lease; + private BuildArtifactReadLease(CoordinatedFileLease lease) + { + m_lease = lease; + } + + /// + /// Ends artifact access and allows repair or retirement; repeated disposal has no effect. + /// + public void Dispose() => Interlocked.Exchange(ref m_lease, null)?.Dispose(); /// /// Acquires reading ownership and verifies the complete artifact before exposing it to a consumer. /// - /// - /// The exact publisher root retaining the persistent owner.lock gate. - /// /// /// The absolute artifact directory owned by its publisher; its persistent lease is stored alongside it. /// + /// + /// The exact publisher root retaining the persistent owner.lock gate. + /// /// /// The exact input identity required by the consumer. /// /// /// The complete relative output roots declared by the publisher. /// - /// - /// Cancels ownership acquisition without releasing another reader's protection. - /// /// /// Optional borrowed operation receiving output-integrity read statistics; its input cache is not used. /// + /// + /// Cancels ownership acquisition without releasing another reader's protection. + /// /// /// Reading ownership which the caller must retain until all artifact access completes. /// @@ -57,15 +65,17 @@ public static async ValueTask AcquireAsync( string ownerDirectory, string fingerprint, IReadOnlyList outputDirectories, - CancellationToken cancellationToken = default, - NativeBuildContext? statistics = null - ) => await TryAcquireAsync(directory, ownerDirectory, fingerprint, outputDirectories, statistics, cancellationToken).ConfigureAwait(false) - ?? throw new InvalidDataException($"Build artifact '{directory}' is missing, damaged or has a different identity."); - - /// - /// Ends artifact access and allows repair or retirement; repeated disposal has no effect. - /// - public void Dispose() => Interlocked.Exchange(ref m_lease, null)?.Dispose(); + NativeBuildContext? statistics = null, + CancellationToken cancellationToken = default + ) => await TryAcquireAsync( + directory, + ownerDirectory, + fingerprint, + outputDirectories, + statistics, + cancellationToken + ).ConfigureAwait(false) + ?? throw new InvalidDataException($"Build artifact '{directory}' is missing, damaged or has a different identity."); internal static async ValueTask TryAcquireAsync( string directory, @@ -79,11 +89,18 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); ArgumentNullException.ThrowIfNull(outputDirectories); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("Artifact reading requires an absolute owner path.", nameof(directory)); + } string path = GetLeasePath(directory); BuildCacheCleanupPlan.RequireChild(ownerDirectory, directory); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(ownerDirectory, "owner.lock"), - path, TimeSpan.FromSeconds(30), shared: true, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(ownerDirectory, "owner.lock"), + path, + TimeSpan.FromSeconds(30), + shared: true, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs index 1601fdcc1..a55c3e1f4 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs @@ -13,17 +13,25 @@ public sealed class BuildArtifactWriteLease : IDisposable { private CoordinatedFileLease? m_lease; - private BuildArtifactWriteLease(CoordinatedFileLease lease) => m_lease = lease; + private BuildArtifactWriteLease(CoordinatedFileLease lease) + { + m_lease = lease; + } + + /// + /// Ends exclusive access without removing the persistent coordination file. + /// + public void Dispose() => Interlocked.Exchange(ref m_lease, null)?.Dispose(); /// /// Waits for all readers before allowing mutation of one immutable artifact directory. /// - /// - /// The exact publisher root retaining the persistent owner.lock gate. - /// /// /// The absolute artifact location controlled by the publisher. /// + /// + /// The exact publisher root retaining the persistent owner.lock gate. + /// /// /// Cancels this waiter without disturbing existing readers. /// @@ -46,14 +54,17 @@ public static async ValueTask AcquireAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("Artifact mutation requires an absolute owner path.", nameof(directory)); + } BuildCacheCleanupPlan.RequireChild(ownerDirectory, directory); - return new(await CoordinatedFileLease.AcquireAsync(Path.Combine(ownerDirectory, "owner.lock"), BuildArtifactReadLease.GetLeasePath(directory), - TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false)); + return new( + await CoordinatedFileLease.AcquireAsync( + Path.Combine(ownerDirectory, "owner.lock"), + BuildArtifactReadLease.GetLeasePath(directory), + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false) + ); } - - /// - /// Ends exclusive access without removing the persistent coordination file. - /// - public void Dispose() => Interlocked.Exchange(ref m_lease, null)?.Dispose(); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs index 2d750f158..2586ae450 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs @@ -20,13 +20,13 @@ public sealed class BuildCacheArtifactDescriptor /// /// The absolute persistent file used by this entry's actual producer and readers for Core.IO coordination. /// + /// + /// The explicit product target, or null for a shared host artifact that target-scoped cleanup must preserve. + /// /// /// The publisher-recorded sum of owned file lengths, captured under writing ownership for cache budgeting. /// It does not measure allocated disk blocks or count shared hardlinks as recovered volume space. /// - /// - /// The explicit product target, or null for a shared host artifact that target-scoped cleanup must preserve. - /// /// /// The publisher's last recorded use, used only to order retirement. /// @@ -48,7 +48,7 @@ public sealed class BuildCacheArtifactDescriptor public BuildCacheArtifactDescriptor( string directory, string leasePath, - string? targetId, + string? targetID, long bytes, DateTime lastUseUtc, IReadOnlyList dependencies, @@ -58,24 +58,32 @@ BuildCacheArtifactRole role ArgumentException.ThrowIfNullOrWhiteSpace(leasePath); ArgumentNullException.ThrowIfNull(dependencies); if (!Path.IsPathFullyQualified(directory) || !Path.IsPathFullyQualified(leasePath) - || dependencies.Any(static path => !Path.IsPathFullyQualified(path))) + || dependencies.Any(static path => !Path.IsPathFullyQualified(path)) + ) { throw new ArgumentException("Cache artifact paths must be absolute."); - if (bytes < 0) - throw new ArgumentOutOfRangeException(nameof(bytes)); - if (targetId is not null && string.IsNullOrWhiteSpace(targetId)) - throw new ArgumentException("A declared cache target cannot be blank.", nameof(targetId)); + } + ArgumentOutOfRangeException.ThrowIfNegative(bytes); + if (targetID is not null && string.IsNullOrWhiteSpace(targetID)) + { + throw new ArgumentException("A declared cache target cannot be blank.", nameof(targetID)); + } if (lastUseUtc.Kind != DateTimeKind.Utc) + { throw new ArgumentException("Cache use timestamps must be UTC.", nameof(lastUseUtc)); + } this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); this.leasePath = Path.GetFullPath(leasePath); - this.targetId = targetId; + this.targetID = targetID; this.bytes = bytes; this.lastUseUtc = lastUseUtc; if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } this.role = role; - this.dependencies = new ReadOnlyCollection(dependencies.Select(static path => - Path.TrimEndingDirectorySeparator(Path.GetFullPath(path))).ToArray()); + this.dependencies = new ReadOnlyCollection( + dependencies.Select(static path => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path))).ToArray() + ); } /// @@ -91,7 +99,7 @@ BuildCacheArtifactRole role /// /// Gets the producer-declared target, or null when this artifact is shared by host operations. /// - public string? targetId { get; } + public string? targetID { get; } /// /// Gets the logical file size used for budgeting, without weakening content validation. diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs index e0d3faf4b..cbd3669a1 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs @@ -9,12 +9,10 @@ public enum BuildCacheArtifactRole /// A complete immutable generation remains protected by selected products and active readers. /// ImmutableArtifact, - /// /// A mutable compiler workspace may retire when no producer or consumer is active. /// ReusableWorkspace, - /// /// An operation directory remains protected until its exact process owners have exited. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs index 647d69105..266a44193 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs @@ -52,6 +52,61 @@ Stopwatch elapsed /// public long protectedBytes { get; } + /// + /// Executes the original proposal under fresh owner and artifact leases without waiting for active readers. + /// + /// + /// Whether to report the proposal without acquiring mutation leases or deleting files. + /// + /// + /// Cancels remaining work; successful earlier retirements are not rolled back. + /// + /// + /// Actual retirement, activity skips and IO failures; protected generations are never forced out. + /// + /// + /// Fresh ownership metadata violates the registered boundary. + /// + /// + /// The caller canceled; no later candidate is processed. + /// + public ValueTask ExecuteAsync( + bool dryRun = false, + CancellationToken cancellationToken = default + ) { + cancellationToken.ThrowIfCancellationRequested(); + TimeSpan remaining = m_policy.timeBudget - m_elapsed.Elapsed; + if (!dryRun && remaining <= TimeSpan.Zero) + { + return ValueTask.FromResult( + new BuildCacheCleanupResult( + [], + candidates.Select(static entry => entry.directory), + new Dictionary(), + 0, + true + ) + ); + } + return dryRun + ? ValueTask.FromResult( + new BuildCacheCleanupResult( + [], + candidates.Select(static entry => entry.directory), + new Dictionary(), + 0, + false + ) + ) + : BuildCacheRetirement.ExecuteAsync( + m_workspace, + m_owners, + new BuildCachePolicy(m_policy.maximumBytes, m_policy.minimumFreeBytes, remaining), + candidates, + cancellationToken + ); + } + /// /// Plans retirement by budget pressure or an explicit request to retire every unreferenced artifact. /// @@ -67,13 +122,13 @@ Stopwatch elapsed /// /// Whether to propose all unreferenced generations regardless of size pressure. /// - /// - /// Cancels planning before any directory is removed. - /// - /// + /// /// An exact producer-declared target filter, or null to manage all registered scopes. /// Outside-scope generations and their dependencies remain protected. /// + /// + /// Cancels planning before any directory is removed. + /// /// /// A fixed proposal; execution rechecks ownership, roots and active readers before deletion. /// @@ -97,18 +152,20 @@ public static BuildCacheCleanupPlan Create( IReadOnlyList owners, BuildCachePolicy policy, bool retireAll = false, - string? targetId = null, + string? targetID = null, CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(policy); - using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); bounded.CancelAfter(policy.timeBudget); Stopwatch elapsed = Stopwatch.StartNew(); try { - BuildCacheCleanupPlan plan = CreateCore(workspace, owners, policy, retireAll, targetId, bounded.Token, elapsed); + BuildCacheCleanupPlan plan = CreateCore(workspace, owners, policy, retireAll, targetID, elapsed, bounded.Token); if (elapsed.Elapsed >= policy.timeBudget) + { throw new TimeoutException("Cache inventory exceeded its operation time budget; no artifact was retired."); + } return plan; } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) @@ -117,86 +174,88 @@ public static BuildCacheCleanupPlan Create( } } + internal static void RequireChild( + string root, + string path + ) { + if (!Path.IsPathFullyQualified(path) || !IsContained(root, path) + || BuildCacheInventory.PATH_COMPARER.Equals( + Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)), + Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)) + ) + ) { + throw new IOException($"Cache path '{path}' is not a child of owner '{root}'."); + } + PathBoundary.RequireUnlinkedPath(root, path); + } + + internal static bool IsContained( + string root, + string path + ) { + string relative = Path.GetRelativePath(root, path); + return !Path.IsPathRooted(relative) && relative != ".." + && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal); + } + private static BuildCacheCleanupPlan CreateCore( string workspace, IReadOnlyList owners, BuildCachePolicy policy, bool retireAll, - string? targetId, - CancellationToken cancellationToken, - Stopwatch elapsed + string? targetID, + Stopwatch elapsed, + CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(workspace); ArgumentNullException.ThrowIfNull(owners); ArgumentNullException.ThrowIfNull(policy); if (!Path.IsPathFullyQualified(workspace)) + { throw new ArgumentException("Cache cleanup requires an absolute checkout boundary.", nameof(workspace)); + } cancellationToken.ThrowIfCancellationRequested(); string root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(workspace)); BuildCacheOwnerDescriptor[] frozen = owners.ToArray(); ValidateOwners(root, frozen); BuildCacheInventory inventory = BuildCacheInventory.Read(root, frozen, cancellationToken); HashSet protectedPaths = inventory.Protect(inventory.roots); - if (targetId is not null) + if (targetID is not null) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - protectedPaths.UnionWith(inventory.Protect(inventory.artifacts.Values - .Where(entry => entry.artifact.targetId != targetId).Select(static entry => entry.artifact.directory))); + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + protectedPaths.UnionWith( + inventory.Protect( + inventory.artifacts.Values + .Where(entry => entry.artifact.targetID != targetID) + .Select(static entry => entry.artifact.directory) + ) + ); } long total = inventory.artifacts.Values.Sum(static entry => entry.artifact.bytes); long protectedSize = protectedPaths.Sum(path => inventory.artifacts[path].artifact.bytes); long free = new DriveInfo(Path.GetPathRoot(root)!).AvailableFreeSpace; - long requested = retireAll ? long.MaxValue : Math.Max(Math.Max(0, total - policy.maximumBytes), - Math.Max(0, policy.minimumFreeBytes - free)); - var selected = new List(); + long requested = retireAll ? long.MaxValue : Math.Max( + Math.Max(0, total - policy.maximumBytes), + Math.Max(0, policy.minimumFreeBytes - free) + ); + List selected = []; long proposed = 0; foreach (BuildCacheArtifactDescriptor artifact in inventory.artifacts.Values.Select(static entry => entry.artifact) .Where(entry => !protectedPaths.Contains(entry.directory)) - .OrderBy(static entry => entry.lastUseUtc).ThenBy(static entry => entry.directory, StringComparer.Ordinal)) - { + .OrderBy(static entry => entry.lastUseUtc) + .ThenBy(static entry => entry.directory, StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); if (proposed >= requested && artifact.role != BuildCacheArtifactRole.ProcessWorkingDirectory) + { continue; + } selected.Add(artifact); proposed = checked(proposed + artifact.bytes); } return new(root, frozen, policy, Array.AsReadOnly(selected.ToArray()), total, protectedSize, elapsed); } - /// - /// Executes the original proposal under fresh owner and artifact leases without waiting for active readers. - /// - /// - /// Whether to report the proposal without acquiring mutation leases or deleting files. - /// - /// - /// Cancels remaining work; successful earlier retirements are not rolled back. - /// - /// - /// Actual retirement, activity skips and IO failures; protected generations are never forced out. - /// - /// - /// Fresh ownership metadata violates the registered boundary. - /// - /// - /// The caller canceled; no later candidate is processed. - /// - public ValueTask ExecuteAsync( - bool dryRun = false, - CancellationToken cancellationToken = default - ) { - cancellationToken.ThrowIfCancellationRequested(); - TimeSpan remaining = m_policy.timeBudget - m_elapsed.Elapsed; - if (!dryRun && remaining <= TimeSpan.Zero) - return ValueTask.FromResult(new BuildCacheCleanupResult([], candidates.Select(static entry => entry.directory), - new Dictionary(), 0, true)); - return dryRun - ? ValueTask.FromResult(new BuildCacheCleanupResult([], candidates.Select(static entry => entry.directory), - new Dictionary(), 0, false)) - : BuildCacheRetirement.ExecuteAsync(m_workspace, m_owners, - new BuildCachePolicy(m_policy.maximumBytes, m_policy.minimumFreeBytes, remaining), candidates, cancellationToken); - } - private static void ValidateOwners( string workspace, IReadOnlyList owners @@ -206,32 +265,18 @@ IReadOnlyList owners { BuildCacheOwnerDescriptor owner = owners[index] ?? throw new ArgumentException("A cache owner is null.", nameof(owners)); if (!identities.Add(owner.id)) + { throw new ArgumentException("Cache owner identities must be unique.", nameof(owners)); + } RequireChild(workspace, owner.directory); RequireChild(owner.directory, owner.coordinationPath); for (int previous = 0; previous < index; previous++) + { if (IsContained(owners[previous].directory, owner.directory) || IsContained(owner.directory, owners[previous].directory)) + { throw new ArgumentException("Registered cache boundaries must not overlap.", nameof(owners)); + } + } } } - - internal static void RequireChild( - string root, - string path - ) { - if (!Path.IsPathFullyQualified(path) || !IsContained(root, path) - || BuildCacheInventory.pathComparer.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)), - Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)))) - throw new IOException($"Cache path '{path}' is not a child of owner '{root}'."); - PathBoundary.RequireUnlinkedPath(root, path); - } - - internal static bool IsContained( - string root, - string path - ) { - string relative = Path.GetRelativePath(root, path); - return !Path.IsPathRooted(relative) && relative != ".." - && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal); - } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs index 64c313fab..aba095e00 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs @@ -11,7 +11,7 @@ internal static class BuildCacheFileInventory internal static long Measure( string directory, BuildCacheArtifactRole role, - CancellationToken cancellation + CancellationToken cancellationToken ) { PathBoundary.RequireUnlinkedPath(directory, directory); long bytes = 0; @@ -19,24 +19,30 @@ CancellationToken cancellation pending.Push(directory); while (pending.TryPop(out string? current)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(directory, current); foreach (string entry in Directory.EnumerateFileSystemEntries(current)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); FileAttributes attributes = File.GetAttributes(entry); if ((attributes & FileAttributes.ReparsePoint) != 0) { if (role != BuildCacheArtifactRole.ReusableWorkspace || (attributes & FileAttributes.Directory) != 0) + { throw new IOException($"Cache entry '{entry}' cannot contain this filesystem link."); - ValidateFileLink(directory, entry, cancellation); + } + ValidateFileLink(directory, entry, cancellationToken); // A compiler's library-name alias owns no second copy of its target's bytes. continue; } if ((attributes & FileAttributes.Directory) != 0) + { pending.Push(entry); + } else + { bytes = checked(bytes + new FileInfo(entry).Length); + } } } return bytes; @@ -45,23 +51,27 @@ CancellationToken cancellation private static void ValidateFileLink( string directory, string entry, - CancellationToken cancellation + CancellationToken cancellationToken ) { var visited = new HashSet(StringComparer.Ordinal); while (true) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); entry = PathBoundary.RequireContained(directory, entry); PathBoundary.RequireUnlinkedPath(directory, Path.GetDirectoryName(entry)!); if (!visited.Add(entry)) + { throw new IOException($"Workspace file link '{entry}' forms a cycle."); + } var file = new FileInfo(entry); string? target = file.LinkTarget; if (target is null) { PathBoundary.RequireUnlinkedPath(directory, entry); if (!file.Exists || (file.Attributes & FileAttributes.Directory) != 0) + { throw new IOException($"Workspace file link '{entry}' has no regular owned target."); + } return; } entry = Path.GetFullPath(target, Path.GetDirectoryName(entry)!); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs index c5b265e10..bb7998174 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs @@ -8,40 +8,70 @@ namespace Inno.Build.Toolchains; internal sealed class BuildCacheInventory { - internal static readonly StringComparer pathComparer = OperatingSystem.IsWindows() - ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + internal static readonly StringComparer PATH_COMPARER = OperatingSystem.IsWindows() + ? StringComparer.OrdinalIgnoreCase + : StringComparer.Ordinal; - private BuildCacheInventory() - { - } + private BuildCacheInventory() {} + + internal Dictionary artifacts { get; } = new( + PATH_COMPARER + ); - internal Dictionary artifacts { get; } = new(pathComparer); internal List roots { get; } = []; internal List retirementOrder { get; } = []; + internal HashSet Protect(IEnumerable roots) + { + var protectedPaths = new HashSet(PATH_COMPARER); + var pending = new Stack(roots); + while (pending.TryPop(out string? path)) + { + if (!artifacts.TryGetValue(path, out (BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry)) + { + throw new InvalidDataException($"Protected cache path '{path}' has no registered artifact owner."); + } + if (!protectedPaths.Add(path)) + { + continue; + } + foreach (string dependency in entry.artifact.dependencies) + { + pending.Push(dependency); + } + } + return protectedPaths; + } + internal static BuildCacheInventory Read( string workspace, IReadOnlyList owners, - CancellationToken cancellation + CancellationToken cancellationToken ) { var result = new BuildCacheInventory(); foreach (BuildCacheOwnerDescriptor owner in owners) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); BuildCacheCleanupPlan.RequireChild(workspace, owner.directory); BuildCacheCleanupPlan.RequireChild(owner.directory, owner.coordinationPath); - foreach (BuildCacheArtifactDescriptor artifact in owner.ReadArtifacts(cancellation)) + foreach (BuildCacheArtifactDescriptor artifact in owner.ReadArtifacts(cancellationToken)) { if (artifact is null) + { throw new InvalidDataException($"Cache owner '{owner.id}' returned a null artifact."); + } BuildCacheCleanupPlan.RequireChild(owner.directory, artifact.directory); BuildCacheCleanupPlan.RequireChild(owner.directory, artifact.leasePath); if (BuildCacheCleanupPlan.IsContained(artifact.directory, owner.coordinationPath)) + { throw new InvalidDataException("An artifact cannot contain its owner's persistent coordination file."); + } if (!result.artifacts.TryAdd(artifact.directory, (owner, artifact))) + { throw new InvalidDataException("A cache artifact has repeated ownership."); + } } - foreach (string path in owner.ReadProtectedArtifacts(cancellation)) + foreach (string path in owner.ReadProtectedArtifacts(cancellationToken)) { BuildCacheCleanupPlan.RequireChild(owner.directory, path); result.roots.Add(Path.TrimEndingDirectorySeparator(Path.GetFullPath(path))); @@ -50,61 +80,72 @@ CancellationToken cancellation bool HasArtifactAncestor(string path) { for (string? current = path; current is not null; current = Path.GetDirectoryName(current)) + { if (result.artifacts.ContainsKey(current)) + { return true; + } + } return false; } foreach (string directory in result.artifacts.Keys) + { if (Path.GetDirectoryName(directory) is string parent && HasArtifactAncestor(parent)) + { throw new InvalidDataException("Cache artifacts must have disjoint ownership boundaries."); - var leasePaths = new HashSet(pathComparer); - foreach (var entry in result.artifacts.Values) + } + } + var leasePaths = new HashSet(PATH_COMPARER); + foreach ((BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry in result.artifacts.Values) { if (!leasePaths.Add(entry.artifact.leasePath) - || owners.Any(owner => pathComparer.Equals(owner.coordinationPath, entry.artifact.leasePath)) - || HasArtifactAncestor(entry.artifact.leasePath)) + || owners.Any(owner => PATH_COMPARER.Equals(owner.coordinationPath, entry.artifact.leasePath)) + || HasArtifactAncestor(entry.artifact.leasePath) + ) { throw new InvalidDataException("Artifact leases must be distinct persistent files outside all retired directories."); + } } foreach (string root in result.roots) + { if (!result.artifacts.ContainsKey(root)) + { throw new InvalidDataException($"Protected cache root '{root}' has no registered artifact owner."); - var incoming = result.artifacts.Keys.ToDictionary(static path => path, static _ => 0, pathComparer); - foreach (var entry in result.artifacts.Values) - foreach (string dependency in entry.artifact.dependencies.Distinct(pathComparer)) + } + } + Dictionary incoming = result.artifacts.Keys.ToDictionary(static path => path, static _ => 0, PATH_COMPARER); + foreach ((BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry in result.artifacts.Values) + { + foreach (string dependency in entry.artifact.dependencies.Distinct(PATH_COMPARER)) { if (!result.artifacts.ContainsKey(dependency)) + { throw new InvalidDataException($"Cache dependency '{dependency}' has no registered artifact owner."); + } incoming[dependency]++; } - var ready = new Queue(incoming.Where(static entry => entry.Value == 0) - .OrderBy(entry => result.artifacts[entry.Key].artifact.lastUseUtc) - .ThenBy(static entry => entry.Key, StringComparer.Ordinal).Select(static entry => entry.Key)); + } + var ready = new Queue( + incoming.Where(static entry => entry.Value == 0) + .OrderBy(entry => result.artifacts[entry.Key].artifact.lastUseUtc) + .ThenBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key) + ); while (ready.TryDequeue(out string? path)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); result.retirementOrder.Add(path); - foreach (string dependency in result.artifacts[path].artifact.dependencies.Distinct(pathComparer)) + foreach (string dependency in result.artifacts[path].artifact.dependencies.Distinct(PATH_COMPARER)) + { if (--incoming[dependency] == 0) + { ready.Enqueue(dependency); + } + } } if (result.retirementOrder.Count != result.artifacts.Count) - throw new ArgumentException("Cache dependency metadata must not contain cycles."); - return result; - } - - internal HashSet Protect(IEnumerable roots) - { - var protectedPaths = new HashSet(pathComparer); - var pending = new Stack(roots); - while (pending.TryPop(out string? path)) { - if (!artifacts.TryGetValue(path, out var entry)) - throw new InvalidDataException($"Protected cache path '{path}' has no registered artifact owner."); - if (!protectedPaths.Add(path)) - continue; - foreach (string dependency in entry.artifact.dependencies) - pending.Push(dependency); + throw new ArgumentException("Cache dependency metadata must not contain cycles."); } - return protectedPaths; + return result; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs index 8a4bca706..7669b9099 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs @@ -13,82 +13,102 @@ namespace Inno.Build.Toolchains; internal sealed class BuildCacheInventoryProgress( string workspace, bool readOnly -) -{ - internal static void PruneRetired( - string workspace, - IReadOnlyList owners, - CancellationToken cancellation - ) { - string root = PathBoundary.RequireUnlinkedPath(workspace, Path.Combine(workspace, "artifacts", "cache-owners", "inventory")); - if (!Directory.Exists(root)) - return; - // The retirement caller retains every selected publisher gate. Progress never authorizes payload removal. - using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); - foreach (string checkpoint in Directory.EnumerateFiles(root, "*.inventory").Order(StringComparer.Ordinal)) - { - cancellation.ThrowIfCancellationRequested(); - using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(root, checkpoint))); - JsonElement saved = document.RootElement; - string relative = saved.GetProperty("directory").GetString() ?? throw new InvalidDataException("Inventory owner is absent."); - var role = (BuildCacheArtifactRole)saved.GetProperty("role").GetInt32(); - string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); - if (Path.GetFileName(checkpoint) != key + ".inventory") - throw new InvalidDataException("Inventory checkpoint does not match its registered path identity."); - string directory = PathBoundary.Resolve(workspace, relative); - if (!owners.Any(owner => owner.directory != directory && BuildCacheCleanupPlan.IsContained(owner.directory, directory)) - || Directory.Exists(directory)) - continue; - File.Delete(checkpoint); - } - } - +) { internal long Measure( string directory, string metadata, string leasePath, BuildCacheArtifactRole role, - CancellationToken cancellation + CancellationToken cancellationToken ) { FileLease reading; try { - reading = FileLease.AcquireSharedAsync(leasePath, TimeSpan.Zero, cancellation).AsTask().GetAwaiter().GetResult(); + reading = FileLease.AcquireSharedAsync(leasePath, TimeSpan.Zero, cancellationToken).AsTask().GetAwaiter().GetResult(); } catch (TimeoutException) { // A live writer's changing size is never persisted as completed inventory. - return BuildCacheFileInventory.Measure(directory, role, cancellation); + return BuildCacheFileInventory.Measure(directory, role, cancellationToken); } using (reading) { string root = PathBoundary.RequireUnlinkedPath(workspace, Path.Combine(workspace, "artifacts", "cache-owners", "inventory")); - string identity = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, metadata)))); + string identity = Convert.ToHexStringLower( + SHA256.HashData(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, metadata))) + ); string relative = Path.GetRelativePath(workspace, directory).Replace('\\', '/'); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); string checkpoint = Path.Combine(root, key + ".inventory"); if (File.Exists(checkpoint)) { - using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, checkpoint))); + using JsonDocument document = JsonDocument.Parse( + File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, checkpoint)) + ); JsonElement saved = document.RootElement; if (saved.GetProperty("directory").GetString() != relative || saved.GetProperty("role").GetInt32() != (int)role - || saved.GetProperty("bytes").GetInt64() < 0) + || saved.GetProperty("bytes").GetInt64() < 0 + ) { throw new InvalidDataException("Cache inventory checkpoint has inconsistent ownership."); + } if (saved.GetProperty("identity").GetString() == identity) + { return saved.GetProperty("bytes").GetInt64(); + } } - long bytes = BuildCacheFileInventory.Measure(directory, role, cancellation); - cancellation.ThrowIfCancellationRequested(); + long bytes = BuildCacheFileInventory.Measure(directory, role, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); if (!readOnly) { // Only completed measurements are checkpoints. Dependencies, roots and retirement authority // are always read again from the publisher; the checkpoint never authorizes deletion. - using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); - AtomicFile.WriteAllBytes(checkpoint, JsonSerializer.SerializeToUtf8Bytes(new { directory = relative, role = (int)role, identity, bytes })); + using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + AtomicFile.WriteAllBytes( + checkpoint, + JsonSerializer.SerializeToUtf8Bytes(new { directory = relative, role = (int)role, identity, bytes }) + ); } return bytes; } } + + internal static void PruneRetired( + string workspace, + IReadOnlyList owners, + CancellationToken cancellationToken + ) { + string root = PathBoundary.RequireUnlinkedPath(workspace, Path.Combine(workspace, "artifacts", "cache-owners", "inventory")); + if (!Directory.Exists(root)) + { + return; + } + // The retirement caller retains every selected publisher gate. Progress never authorizes payload removal. + using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); + foreach (string checkpoint in Directory.EnumerateFiles(root, "*.inventory").Order(StringComparer.Ordinal)) + { + cancellationToken.ThrowIfCancellationRequested(); + using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(root, checkpoint))); + JsonElement saved = document.RootElement; + string relative = saved.GetProperty("directory").GetString() ?? throw new InvalidDataException("Inventory owner is absent."); + BuildCacheArtifactRole role = (BuildCacheArtifactRole)saved.GetProperty("role").GetInt32(); + string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); + if (Path.GetFileName(checkpoint) != key + ".inventory") + { + throw new InvalidDataException("Inventory checkpoint does not match its registered path identity."); + } + string directory = PathBoundary.Resolve(workspace, relative); + if (!owners.Any(owner => owner.directory != directory && BuildCacheCleanupPlan.IsContained(owner.directory, directory)) + || Directory.Exists(directory) + ) { + continue; + } + File.Delete(checkpoint); + } + } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs index 33ac5b0ec..fa957644d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs @@ -51,20 +51,29 @@ public static void Register( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } string root = Path.GetFullPath(engineRoot); string owned = PathBoundary.RequireUnlinkedPath(root, directory); if (owned == root) + { throw new ArgumentException("The checkout cannot be registered as a cache."); + } string relative = Path.GetRelativePath(root, owned).Replace('\\', '/'); string catalog = CatalogRoot(root); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative))); string file = Path.Combine(catalog, key + ".json"); - using FileLease writing = FileLease.AcquireAsync(Path.Combine(catalog, "owner.lock"), - TimeSpan.FromSeconds(30), cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease writing = FileLease.AcquireAsync( + Path.Combine(catalog, "owner.lock"), + TimeSpan.FromSeconds(30), + cancellationToken + ).AsTask().GetAwaiter().GetResult(); var registration = new Registration(id, relative, role); if (File.Exists(file) && Read(file) != registration) + { throw new InvalidDataException("A cache root cannot change its registered owner or lifetime."); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.WriteAllBytes(file, JsonSerializer.SerializeToUtf8Bytes(registration)); } @@ -100,20 +109,30 @@ CancellationToken cancellationToken string root = Path.GetFullPath(engineRoot); string catalog = CatalogRoot(root); if (!Directory.Exists(catalog)) + { return []; - using FileLease reading = FileLease.AcquireSharedAsync(Path.Combine(catalog, "owner.lock"), - TimeSpan.FromSeconds(30), cancellationToken).AsTask().GetAwaiter().GetResult(); - var result = new List(); + } + using FileLease reading = FileLease.AcquireSharedAsync( + Path.Combine(catalog, "owner.lock"), + TimeSpan.FromSeconds(30), + cancellationToken + ).AsTask().GetAwaiter().GetResult(); + List result = []; var identities = new HashSet(StringComparer.Ordinal); foreach (string file in PathBoundary.EnumerateFiles(catalog).Where(static file => file.EndsWith(".json", StringComparison.Ordinal))) { cancellationToken.ThrowIfCancellationRequested(); Registration value = Read(file); if (!identities.Add(value.id)) + { throw new InvalidDataException("Cache registration identities must be unique."); + } string owned = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, value.directory)); - result.Add((progress is null ? new BuildCachePublisher(owned, value.role) - : new BuildCachePublisher(owned, value.role, progress)).Describe(value.id)); + result.Add( + (progress is null + ? new BuildCachePublisher(owned, value.role) + : new BuildCachePublisher(owned, value.role, progress)).Describe(value.id) + ); } return result.AsReadOnly(); } @@ -128,15 +147,21 @@ private static Registration Read(string path) if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Count() != 3 || !root.TryGetProperty("id", out JsonElement id) || id.ValueKind != JsonValueKind.String || !root.TryGetProperty("directory", out JsonElement directory) || directory.ValueKind != JsonValueKind.String - || !root.TryGetProperty("role", out JsonElement role) || !role.TryGetInt32(out int lifetime)) + || !root.TryGetProperty("role", out JsonElement role) || !role.TryGetInt32(out int lifetime) + ) { throw new InvalidDataException("A cache registration lacks its exact owner, directory and lifetime."); + } var value = new Registration(id.GetString()!, directory.GetString()!, (BuildCacheArtifactRole)lifetime); if (string.IsNullOrWhiteSpace(value.id) || string.IsNullOrWhiteSpace(value.directory) - || Path.IsPathRooted(value.directory) || value.directory == "." || !Enum.IsDefined(value.role)) + || Path.IsPathRooted(value.directory) || value.directory == "." || !Enum.IsDefined(value.role) + ) { throw new InvalidDataException("A cache registration has invalid ownership metadata."); + } string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value.directory))); if (Path.GetFileName(path) != key + ".json") + { throw new InvalidDataException("A cache registration has a mismatched publisher key."); + } return value; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs index ee0d88236..73b6e8528 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs @@ -58,7 +58,9 @@ public BuildCacheOwnerDescriptor( ArgumentNullException.ThrowIfNull(readArtifacts); ArgumentNullException.ThrowIfNull(readProtectedArtifacts); if (!Path.IsPathFullyQualified(directory) || !Path.IsPathFullyQualified(coordinationPath)) + { throw new ArgumentException("Cache registration requires absolute owner paths."); + } this.id = id; this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); this.coordinationPath = Path.GetFullPath(coordinationPath); @@ -82,11 +84,12 @@ public BuildCacheOwnerDescriptor( /// public string coordinationPath { get; } - internal void RetireMetadata(CancellationToken cancellation) => m_retireMetadata?.Invoke(cancellation); + internal void RetireMetadata(CancellationToken cancellationToken) => m_retireMetadata?.Invoke(cancellationToken); - internal IReadOnlyList ReadArtifacts(CancellationToken cancellation) - => m_readArtifacts(cancellation) ?? throw new InvalidDataException($"Cache owner '{id}' returned no inventory."); + internal IReadOnlyList ReadArtifacts(CancellationToken cancellationToken) + => m_readArtifacts(cancellationToken) ?? throw new InvalidDataException($"Cache owner '{id}' returned no inventory."); - internal IReadOnlyList ReadProtectedArtifacts(CancellationToken cancellation) - => m_readProtectedArtifacts(cancellation) ?? throw new InvalidDataException($"Cache owner '{id}' returned no protection inventory."); + internal IReadOnlyList ReadProtectedArtifacts(CancellationToken cancellationToken) + => m_readProtectedArtifacts(cancellationToken) + ?? throw new InvalidDataException($"Cache owner '{id}' returned no protection inventory."); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs index 3d53ae2d5..2a6259879 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; namespace Inno.Build.Toolchains; @@ -27,13 +28,13 @@ public BuildCachePolicy( long minimumFreeBytes = 20L * 1024 * 1024 * 1024, TimeSpan? timeBudget = null ) { - if (maximumBytes < 0) - throw new ArgumentOutOfRangeException(nameof(maximumBytes)); - if (minimumFreeBytes < 0) - throw new ArgumentOutOfRangeException(nameof(minimumFreeBytes)); + ArgumentOutOfRangeException.ThrowIfNegative(maximumBytes); + ArgumentOutOfRangeException.ThrowIfNegative(minimumFreeBytes); TimeSpan duration = timeBudget ?? TimeSpan.FromSeconds(5); - if (duration <= TimeSpan.Zero || duration == System.Threading.Timeout.InfiniteTimeSpan) + if (duration <= TimeSpan.Zero || duration == Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeBudget)); + } this.maximumBytes = maximumBytes; this.minimumFreeBytes = minimumFreeBytes; this.timeBudget = duration; diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs index eb6f74594..9ca03e24e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -38,10 +39,14 @@ BuildCacheArtifactRole role ) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("A cache publisher requires an absolute root.", nameof(directory)); + } m_root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } m_role = role; } @@ -75,7 +80,9 @@ public async ValueTask AcquireUseAsync(CancellationToken cancellation { string path = Path.Combine(m_root, "owner.lock"); if (!File.Exists(path)) + { using (await FileLease.AcquireAsync(path, TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false)) { } + } return await FileLease.AcquireSharedAsync(path, TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); } @@ -95,12 +102,12 @@ public async ValueTask AcquireUseAsync(CancellationToken cancellation /// /// A product/target/configuration root identity, or null for an unselected generation. /// + /// + /// The producer's product target, or null for a shared host generation. + /// /// /// Cancels before metadata selection. /// - /// - /// The producer's product target, or null for a shared host generation. - /// /// /// An owned path escapes the boundary, crosses a directory link, or contains an invalid file link. /// @@ -117,27 +124,39 @@ public void Record( string leasePath, IReadOnlyList dependencies, string? currentKey, - string? targetId, + string? targetID, CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(dependencies); - if (targetId is not null) - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); + if (targetID is not null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); if (!Directory.Exists(directory)) + { throw new DirectoryNotFoundException(directory); + } cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); long bytes = BuildCacheFileInventory.Measure(directory, m_role, cancellationToken); - var metadata = new Entry(relative, Path.GetRelativePath(m_root, leasePath), DateTime.UtcNow, - dependencies.Select(Path.GetFullPath).ToArray(), bytes, targetId); + var metadata = new Entry( + relative, + Path.GetRelativePath(m_root, leasePath), + DateTime.UtcNow, + dependencies.Select(Path.GetFullPath).ToArray(), + bytes, + targetID + ); AtomicFile.WriteAllBytes(Path.Combine(m_root, Key(relative) + ".cache.json"), WriteEntry(metadata)); if (currentKey is not null && m_role == BuildCacheArtifactRole.ImmutableArtifact) { string pointer = Path.Combine(m_root, Key(currentKey) + ".current"); if (!File.Exists(pointer) || File.ReadAllText(pointer) != relative) + { AtomicFile.WriteAllBytes(pointer, Encoding.UTF8.GetBytes(relative)); + } } } @@ -153,17 +172,12 @@ public void Record( /// /// The exact dependency closure, in its original publication order. /// - /// + /// /// The producer's explicit target, or null for shared host work. /// /// /// Cancels inspection or initial registration before publication. /// - /// - /// This confirms ownership, not content integrity. The producer must verify the immutable payload itself. - /// Existing registration age is retained; use an active lease or a current generation dependency to protect - /// consumers. This operation neither selects a current root nor records a new use time. - /// /// /// This publisher does not own immutable artifacts. /// @@ -176,18 +190,27 @@ public void Record( /// /// Inspection or registration was canceled. /// + /// + /// This confirms ownership, not content integrity. The producer must verify the immutable payload itself. + /// Existing registration age is retained; use an active lease or a current generation dependency to protect + /// consumers. This operation neither selects a current root nor records a new use time. + /// public void EnsureImmutableRegistration( string directory, string leasePath, IReadOnlyList dependencies, - string? targetId, + string? targetID, CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(dependencies); - if (targetId is not null) - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); + if (targetID is not null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + } if (m_role != BuildCacheArtifactRole.ImmutableArtifact) + { throw new InvalidOperationException("Only immutable artifacts can retain publication registration."); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); @@ -195,16 +218,18 @@ public void EnsureImmutableRegistration( cancellationToken.ThrowIfCancellationRequested(); if (!File.Exists(record)) { - Record(directory, leasePath, dependencies, null, targetId, cancellationToken); + Record(directory, leasePath, dependencies, null, targetID, cancellationToken); return; } Entry previous = ReadEntry(record); long bytes = BuildCacheFileInventory.Measure(directory, m_role, cancellationToken); if (previous.directory != relative - || !BuildCacheInventory.pathComparer.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath)) - || !previous.dependencies.SequenceEqual(dependencies.Select(Path.GetFullPath), BuildCacheInventory.pathComparer) - || previous.targetId != targetId || previous.bytes != bytes) + || !BuildCacheInventory.PATH_COMPARER.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath)) + || !previous.dependencies.SequenceEqual(dependencies.Select(Path.GetFullPath), BuildCacheInventory.PATH_COMPARER) + || previous.targetID != targetID || previous.bytes != bytes + ) { throw new InvalidDataException("Immutable ownership differs from its completed publication registration."); + } } /// @@ -229,7 +254,7 @@ public BuildCacheOwnerDescriptor Describe(string id) /// /// The caller's persistent exclusive producer lease outside the workspace. /// - /// + /// /// The explicit product target, or null for shared host work. /// /// @@ -244,21 +269,30 @@ public BuildCacheOwnerDescriptor Describe(string id) public void BeginWorkingDirectory( string directory, string leasePath, - string? targetId, + string? targetID, CancellationToken cancellationToken = default ) { if (m_role != BuildCacheArtifactRole.ReusableWorkspace) + { throw new InvalidOperationException("Working registration requires a reusable workspace publisher."); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); string record = Path.Combine(m_root, Key(relative) + ".cache.json"); if (Directory.Exists(directory) && !File.Exists(record)) + { throw new InvalidOperationException($"An existing unregistered workspace cannot be adopted: '{directory}'."); + } if (File.Exists(record) && ReadEntry(record).directory != relative) + { throw new InvalidDataException("Working ownership has an inconsistent directory identity."); - AtomicFile.WriteAllBytes(record, WriteEntry(new(relative, Path.GetRelativePath(m_root, leasePath).Replace('\\', '/'), DateTime.UtcNow, [], 0, targetId))); + } + AtomicFile.WriteAllBytes( + record, + WriteEntry(new Entry(relative, Path.GetRelativePath(m_root, leasePath).Replace('\\', '/'), DateTime.UtcNow, [], 0, targetID)) + ); Directory.CreateDirectory(directory); } @@ -296,7 +330,9 @@ public void RecordProcessUse( BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); using FileLease writing = FileLease.AcquireAsync(leasePath, TimeSpan.FromSeconds(30), cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); string record = Path.Combine(m_root, Key(relative) + ".cache.json"); string[] retained = []; @@ -304,16 +340,19 @@ public void RecordProcessUse( { Entry previous = ReadEntry(record); if (previous.directory != relative - || !BuildCacheInventory.pathComparer.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath))) + || !BuildCacheInventory.PATH_COMPARER.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath)) + ) { throw new InvalidDataException("Process ownership has an inconsistent directory or lease identity."); + } retained = previous.dependencies; } string[] closure = retained.Concat(dependencies.Select(Path.GetFullPath)) - .Distinct(BuildCacheInventory.pathComparer).ToArray(); + .Distinct(BuildCacheInventory.PATH_COMPARER) + .ToArray(); string owners = Path.Combine(directory, "owners"); Directory.CreateDirectory(owners); ProcessOwnerStamp stamp = ProcessOwnerStamp.CaptureCurrent(); - string process = stamp.processId.ToString(System.Globalization.CultureInfo.InvariantCulture); + string process = stamp.processId.ToString(CultureInfo.InvariantCulture); AtomicFile.WriteAllBytes(Path.Combine(owners, process + ".pid"), JsonSerializer.SerializeToUtf8Bytes(stamp)); Record(directory, leasePath, closure, null, null, cancellationToken); } @@ -336,127 +375,184 @@ IReadOnlyList dependencies ) { BuildCacheCleanupPlan.RequireChild(m_root, path); foreach (string dependency in dependencies) + { BuildCacheCleanupPlan.RequireChild(m_root, dependency); + } string relative = Path.GetRelativePath(m_root, path).Replace('\\', '/'); - AtomicFile.WriteAllBytes(Path.Combine(m_root, Key(relative) + ".metadata.json"), - JsonSerializer.SerializeToUtf8Bytes(new Index(relative, dependencies.ToArray()))); + AtomicFile.WriteAllBytes( + Path.Combine(m_root, Key(relative) + ".metadata.json"), + JsonSerializer.SerializeToUtf8Bytes(new Index(relative, dependencies.ToArray())) + ); } - private void RetireMetadata(CancellationToken cancellation) + private void RetireMetadata(CancellationToken cancellationToken) { if (!Directory.Exists(m_root)) + { return; - HashSet currents = ReadRoots(cancellation).ToHashSet(BuildCacheInventory.pathComparer); + } + HashSet currents = ReadRoots(cancellationToken).ToHashSet(BuildCacheInventory.PATH_COMPARER); foreach (string pointer in m_role == BuildCacheArtifactRole.ImmutableArtifact - ? Directory.EnumerateFiles(m_root, "*.current") : Enumerable.Empty()) - { + ? Directory.EnumerateFiles(m_root, "*.current") + : [] + ) { string selected = PathBoundary.Resolve(m_root, File.ReadAllText(PathBoundary.RequireUnlinkedPath(m_root, pointer))); if (!Directory.Exists(selected)) + { throw new InvalidDataException($"Current cache publication is missing: '{selected}'."); + } } foreach (string record in Directory.EnumerateFiles(m_root, "*.cache.json").Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); Entry entry = ReadEntry(PathBoundary.RequireUnlinkedPath(m_root, record)); if (Path.GetFileName(record) != Key(entry.directory) + ".cache.json") + { throw new InvalidDataException("Cache metadata has an inconsistent owner identity."); + } string directory = PathBoundary.Resolve(m_root, entry.directory); string leaf = PathBoundary.Resolve(m_root, entry.leasePath); if (Directory.Exists(directory) || currents.Contains(directory)) + { continue; + } PathBoundary.RequireUnlinkedPath(m_root, leaf); - using (FileLease.AcquireAsync(leaf, TimeSpan.Zero, cancellation).AsTask().GetAwaiter().GetResult()) { } + using (FileLease.AcquireAsync(leaf, TimeSpan.Zero, cancellationToken).AsTask().GetAwaiter().GetResult()) { } File.Delete(leaf); // Keep explicit retirement authority until unlinking the leaf succeeds. File.Delete(record); } foreach (string record in Directory.EnumerateFiles(m_root, "*.metadata.json").Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); Index index = JsonSerializer.Deserialize(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(m_root, record))) - ?? throw new InvalidDataException("Cache index ownership is incomplete."); - if (index.dependencies is null || index.dependencies.Length == 0 || Path.GetFileName(record) != Key(index.path) + ".metadata.json") + ?? throw new InvalidDataException("Cache index ownership is incomplete."); + if (index.dependencies is null + || index.dependencies.Length == 0 + || Path.GetFileName(record) != Key(index.path) + ".metadata.json" + ) { throw new InvalidDataException("Cache index ownership is inconsistent."); + } string path = PathBoundary.Resolve(m_root, index.path); BuildCacheCleanupPlan.RequireChild(m_root, path); foreach (string dependency in index.dependencies) + { BuildCacheCleanupPlan.RequireChild(m_root, dependency); + } if (index.dependencies.All(Directory.Exists)) + { continue; + } File.Delete(path); File.Delete(record); } - ProcessOwnedDirectory.RetireMetadataUnderOwnership(m_root, cancellation); + ProcessOwnedDirectory.RetireMetadataUnderOwnership(m_root, cancellationToken); } - private sealed record Index( - string path, - string[] dependencies - ); - - private IReadOnlyList ReadArtifacts(CancellationToken cancellation) + private IReadOnlyList ReadArtifacts(CancellationToken cancellationToken) { List result = []; if (!Directory.Exists(m_root)) + { return result; + } foreach (string path in Directory.EnumerateFiles(m_root, "*.cache.json").Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(m_root, path); Entry entry = ReadEntry(path); string directory = PathBoundary.Resolve(m_root, entry.directory); string lease = PathBoundary.Resolve(m_root, entry.leasePath); if (Path.GetFileName(path) != Key(entry.directory) + ".cache.json") + { throw new InvalidDataException("Cache ownership metadata does not match its identity."); + } if (!Directory.Exists(directory)) + { continue; + } // Completed workspaces are measured by their sole writer. An unfinished registration // has zero bytes and must be inspected; this metadata never validates Native contents. long bytes = m_role == BuildCacheArtifactRole.ImmutableArtifact - || m_role == BuildCacheArtifactRole.ReusableWorkspace && entry.bytes > 0 - ? entry.bytes : m_inventoryProgress?.Measure(directory, path, lease, m_role, cancellation) - ?? BuildCacheFileInventory.Measure(directory, m_role, cancellation); - result.Add(new(directory, lease, entry.targetId, bytes, entry.lastUseUtc, entry.dependencies, m_role)); + || m_role == BuildCacheArtifactRole.ReusableWorkspace && entry.bytes > 0 + ? entry.bytes + : m_inventoryProgress?.Measure(directory, path, lease, m_role, cancellationToken) + ?? BuildCacheFileInventory.Measure(directory, m_role, cancellationToken); + result.Add( + new BuildCacheArtifactDescriptor(directory, lease, entry.targetID, bytes, entry.lastUseUtc, entry.dependencies, m_role) + ); } - foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellation)) + foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellationToken)) { - if (result.Any(entry => BuildCacheInventory.pathComparer.Equals(entry.directory, working.directory))) + if (result.Any(entry => BuildCacheInventory.PATH_COMPARER.Equals(entry.directory, working.directory))) + { continue; + } string metadata = Path.Combine(m_root, Key(Path.GetRelativePath(m_root, working.directory)) + ".work.json"); long bytes = working.ownerState == ProcessOwnerState.Exited && m_inventoryProgress is not null - ? m_inventoryProgress.Measure(working.directory, metadata, working.leasePath, BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation) - : BuildCacheFileInventory.Measure(working.directory, BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation); - result.Add(new(working.directory, working.leasePath, null, bytes, Directory.GetLastWriteTimeUtc(working.directory), [], BuildCacheArtifactRole.ProcessWorkingDirectory)); + ? m_inventoryProgress.Measure( + working.directory, + metadata, + working.leasePath, + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ) + : BuildCacheFileInventory.Measure( + working.directory, + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); + result.Add( + new BuildCacheArtifactDescriptor( + working.directory, + working.leasePath, + null, + bytes, + Directory.GetLastWriteTimeUtc(working.directory), + [], + BuildCacheArtifactRole.ProcessWorkingDirectory + ) + ); } return result; } - private IReadOnlyList ReadRoots(CancellationToken cancellation) + private IReadOnlyList ReadRoots(CancellationToken cancellationToken) { List result = []; if (!Directory.Exists(m_root)) + { return result; + } foreach (string path in m_role == BuildCacheArtifactRole.ImmutableArtifact - ? Directory.EnumerateFiles(m_root, "*.current").Order(StringComparer.Ordinal) : Enumerable.Empty()) - { - cancellation.ThrowIfCancellationRequested(); + ? Directory.EnumerateFiles(m_root, "*.current").Order(StringComparer.Ordinal) + : Enumerable.Empty() + ) { + cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(m_root, path); result.Add(PathBoundary.Resolve(m_root, File.ReadAllText(path))); } foreach (string path in Directory.EnumerateFiles(m_root, "*.cache.json").Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(m_root, path); Entry entry = ReadEntry(path); string directory = PathBoundary.Resolve(m_root, entry.directory); string owners = Path.Combine(directory, "owners"); if (m_role != BuildCacheArtifactRole.ReusableWorkspace && Directory.Exists(owners) && PathBoundary.EnumerateFiles(owners) - .Where(static file => Path.GetExtension(file) == ".pid").Any(IsProcessAlive)) + .Where(static file => Path.GetExtension(file) == ".pid") + .Any(IsProcessAlive) + ) { result.Add(directory); + } } - foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellation)) + foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellationToken)) + { if (working.ownerState != ProcessOwnerState.Exited) + { result.Add(working.directory); + } + } return result; } @@ -466,14 +562,21 @@ private static bool IsProcessAlive(string marker) { using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(marker)); JsonElement root = document.RootElement; - if (!root.EnumerateObject().Select(static property => property.Name).Order(StringComparer.Ordinal) - .SequenceEqual(new[] { "processId", "startedUtcTicks" }, StringComparer.Ordinal)) + if (!root.EnumerateObject() + .Select(static property => property.Name) + .Order(StringComparer.Ordinal) + .SequenceEqual(new[] { "processId", "startedUtcTicks" }, StringComparer.Ordinal) + ) { return true; - var stamp = new ProcessOwnerStamp(root.GetProperty("processId").GetInt32(), root.GetProperty("startedUtcTicks").GetInt64()); + } + var stamp = new ProcessOwnerStamp( + root.GetProperty("processId").GetInt32(), + root.GetProperty("startedUtcTicks").GetInt64() + ); return stamp.Query() != ProcessOwnerState.Exited; } catch (Exception exception) when (exception is JsonException or ArgumentException or InvalidOperationException - or IOException or UnauthorizedAccessException or FormatException or OverflowException) + or IOException or UnauthorizedAccessException or FormatException or OverflowException) { return true; } @@ -491,10 +594,12 @@ private static byte[] WriteEntry(Entry entry) writer.WriteString("leasePath", entry.leasePath); writer.WriteString("lastUseUtc", entry.lastUseUtc); writer.WriteNumber("bytes", entry.bytes); - writer.WriteString("targetId", entry.targetId); + writer.WriteString("targetId", entry.targetID); writer.WriteStartArray("dependencies"); foreach (string dependency in entry.dependencies) + { writer.WriteStringValue(dependency); + } writer.WriteEndArray(); writer.WriteEndObject(); } @@ -505,23 +610,42 @@ private static Entry ReadEntry(string path) { using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(path)); JsonElement root = document.RootElement; - if (!root.EnumerateObject().Select(static property => property.Name).Order(StringComparer.Ordinal) - .SequenceEqual(new[] { "bytes", "dependencies", "directory", "lastUseUtc", "leasePath", "targetId" }, StringComparer.Ordinal)) + if (!root.EnumerateObject() + .Select(static property => property.Name) + .Order(StringComparer.Ordinal) + .SequenceEqual(new[] { "bytes", "dependencies", "directory", "lastUseUtc", "leasePath", "targetId" }, StringComparer.Ordinal) + ) { throw new InvalidDataException("Cache ownership requires one complete current record."); + } long bytes = root.GetProperty("bytes").GetInt64(); if (bytes < 0) + { throw new InvalidDataException("Recorded cache size cannot be negative."); - return new(root.GetProperty("directory").GetString()!, root.GetProperty("leasePath").GetString()!, - root.GetProperty("lastUseUtc").GetDateTime(), root.GetProperty("dependencies").EnumerateArray() - .Select(static dependency => dependency.GetString()!).ToArray(), bytes, root.GetProperty("targetId").GetString()); + } + return new( + root.GetProperty("directory").GetString()!, + root.GetProperty("leasePath").GetString()!, + root.GetProperty("lastUseUtc").GetDateTime(), + root.GetProperty("dependencies") + .EnumerateArray() + .Select(static dependency => dependency.GetString()!) + .ToArray(), + bytes, + root.GetProperty("targetId").GetString() + ); } + private sealed record Index( + string path, + string[] dependencies + ); + private sealed record Entry( string directory, string leasePath, DateTime lastUseUtc, string[] dependencies, long bytes, - string? targetId + string? targetID ); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs index 020341782..ebef19300 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs @@ -17,30 +17,37 @@ internal static async ValueTask ExecuteAsync( IReadOnlyList owners, BuildCachePolicy policy, IReadOnlyList candidates, - CancellationToken cancellation + CancellationToken cancellationToken ) { - var retired = new List(); - var skipped = new HashSet(BuildCacheInventory.pathComparer); - var failures = new Dictionary(BuildCacheInventory.pathComparer); - var ownerLeases = new List(); - var artifactLeases = new Dictionary(BuildCacheInventory.pathComparer); - var proposed = candidates.ToDictionary(static entry => entry.directory, BuildCacheInventory.pathComparer); + List retired = []; + var skipped = new HashSet(BuildCacheInventory.PATH_COMPARER); + var failures = new Dictionary(BuildCacheInventory.PATH_COMPARER); + List ownerLeases = []; + var artifactLeases = new Dictionary(BuildCacheInventory.PATH_COMPARER); + Dictionary proposed = candidates.ToDictionary( + static entry => entry.directory, + BuildCacheInventory.PATH_COMPARER + ); long reclaimed = 0; Stopwatch elapsed = Stopwatch.StartNew(); bool limited = false; - using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); bounded.CancelAfter(policy.timeBudget); try { foreach (BuildCacheOwnerDescriptor owner in owners.OrderBy(static entry => entry.coordinationPath, StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (elapsed.Elapsed >= policy.timeBudget) + { return new([], proposed.Keys, failures, 0, true); + } try { BuildCacheCleanupPlan.RequireChild(owner.directory, owner.coordinationPath); - ownerLeases.Add(await FileLease.AcquireAsync(owner.coordinationPath, TimeSpan.Zero, cancellation).ConfigureAwait(false)); + ownerLeases.Add( + await FileLease.AcquireAsync(owner.coordinationPath, TimeSpan.Zero, cancellationToken).ConfigureAwait(false) + ); } catch (TimeoutException) { @@ -50,18 +57,28 @@ CancellationToken cancellation } BuildCacheInventory fresh = BuildCacheInventory.Read(workspace, owners, bounded.Token); HashSet protectedPaths = fresh.Protect(fresh.roots); - protectedPaths.UnionWith(fresh.Protect(fresh.artifacts.Keys.Except(proposed.Keys, BuildCacheInventory.pathComparer))); - var active = new List(); - foreach (string path in fresh.artifacts.Keys.Where(path => proposed.ContainsKey(path) && !protectedPaths.Contains(path)).Order(StringComparer.Ordinal)) - { - cancellation.ThrowIfCancellationRequested(); + protectedPaths.UnionWith(fresh.Protect(fresh.artifacts.Keys.Except(proposed.Keys, BuildCacheInventory.PATH_COMPARER))); + List active = []; + foreach (string path in fresh.artifacts.Keys + .Where(path => proposed.ContainsKey(path) && !protectedPaths.Contains(path)) + .Order(StringComparer.Ordinal) + ) { + cancellationToken.ThrowIfCancellationRequested(); if (elapsed.Elapsed >= policy.timeBudget) + { return new([], proposed.Keys, failures, 0, true); + } try { BuildCacheCleanupPlan.RequireChild(fresh.artifacts[path].owner.directory, path); - artifactLeases.Add(path, await FileLease.AcquireAsync(fresh.artifacts[path].artifact.leasePath, - TimeSpan.Zero, cancellation).ConfigureAwait(false)); + artifactLeases.Add( + path, + await FileLease.AcquireAsync( + fresh.artifacts[path].artifact.leasePath, + TimeSpan.Zero, + cancellationToken + ).ConfigureAwait(false) + ); } catch (TimeoutException) { @@ -76,24 +93,28 @@ CancellationToken cancellation protectedPaths.UnionWith(fresh.Protect(active)); // An active parent keeps its dependencies available to the original owner. foreach (string path in protectedPaths) + { if (artifactLeases.Remove(path, out FileLease? lease)) + { lease.Dispose(); + } + } foreach (string path in fresh.retirementOrder.Where(proposed.ContainsKey)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (elapsed.Elapsed >= policy.timeBudget) { limited = true; break; } - var current = fresh.artifacts[path]; + (BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) current = fresh.artifacts[path]; BuildCacheArtifactDescriptor original = proposed[path]; if (protectedPaths.Contains(path) || !artifactLeases.ContainsKey(path) || original.bytes != current.artifact.bytes || original.lastUseUtc != current.artifact.lastUseUtc - || original.targetId != current.artifact.targetId || original.role != current.artifact.role - || !BuildCacheInventory.pathComparer.Equals(original.leasePath, current.artifact.leasePath) - || !original.dependencies.SequenceEqual(current.artifact.dependencies, BuildCacheInventory.pathComparer)) - { + || original.targetID != current.artifact.targetID || original.role != current.artifact.role + || !BuildCacheInventory.PATH_COMPARER.Equals(original.leasePath, current.artifact.leasePath) + || !original.dependencies.SequenceEqual(current.artifact.dependencies, BuildCacheInventory.PATH_COMPARER) + ) { skipped.Add(path); continue; } @@ -120,39 +141,51 @@ CancellationToken cancellation } // Close leaf handles before unlinking them, while every owner gate remains exclusive. foreach (FileLease lease in artifactLeases.Values) + { lease.Dispose(); + } artifactLeases.Clear(); foreach (BuildCacheOwnerDescriptor owner in owners.OrderBy(static owner => owner.coordinationPath, StringComparer.Ordinal)) { bounded.Token.ThrowIfCancellationRequested(); - try { owner.RetireMetadata(bounded.Token); } + try + { + owner.RetireMetadata(bounded.Token); + } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or TimeoutException - or InvalidDataException or JsonException) + or InvalidDataException or JsonException) { // Payload retirement has already committed. Keep invalid metadata and report // the failure without losing completed work or another owner's cleanup result. failures[owner.directory] = failure.Message; } } - try { BuildCacheInventoryProgress.PruneRetired(workspace, owners, bounded.Token); } + try + { + BuildCacheInventoryProgress.PruneRetired(workspace, owners, bounded.Token); + } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or TimeoutException - or InvalidDataException or JsonException) + or InvalidDataException or JsonException) { failures[Path.Combine(workspace, "artifacts", "cache-owners", "inventory")] = failure.Message; } - skipped.UnionWith(proposed.Keys.Except(retired, BuildCacheInventory.pathComparer)); + skipped.UnionWith(proposed.Keys.Except(retired, BuildCacheInventory.PATH_COMPARER)); return new(retired, skipped, failures, reclaimed, limited); } - catch (OperationCanceledException) when (!cancellation.IsCancellationRequested) + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { - return new(retired, proposed.Keys.Except(retired, BuildCacheInventory.pathComparer), failures, reclaimed, true); + return new(retired, proposed.Keys.Except(retired, BuildCacheInventory.PATH_COMPARER), failures, reclaimed, true); } finally { foreach (FileLease lease in artifactLeases.Values.Reverse()) + { lease.Dispose(); + } for (int index = ownerLeases.Count - 1; index >= 0; index--) + { ownerLeases[index].Dispose(); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs index 79ec5bce8..06d59df50 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs @@ -23,12 +23,12 @@ public static class NativeArtifactTransfer /// /// The explicit transport file, atomically replaced after complete export. /// - /// - /// Cancels copying before the completed archive replaces its previous version. - /// /// /// Optional exact artifact paths relative to the artifacts root. Every selected generation must be exported. /// + /// + /// Cancels copying before the completed archive replaces its previous version. + /// /// /// The number of verified generations exported. /// @@ -41,8 +41,8 @@ public static class NativeArtifactTransfer public static async Task ExportAsync( string engineRoot, string archivePath, - CancellationToken cancellationToken = default, - IReadOnlySet? selectedArtifacts = null + IReadOnlySet? selectedArtifacts = null, + CancellationToken cancellationToken = default ) { string root = Path.GetFullPath(engineRoot); string destination = PathBoundary.RequireUnlinkedPath(root, Path.GetFullPath(archivePath)); @@ -54,31 +54,51 @@ public static async Task ExportAsync( using (var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) - foreach (BuildCacheOwnerDescriptor owner in BuildCacheOwnerCatalog.ReadOwners(root, cancellationToken) - .Where(static owner => owner.id is "native" or "bindings")) { + foreach (BuildCacheOwnerDescriptor owner in BuildCacheOwnerCatalog.ReadOwners(root, cancellationToken) + .Where(static owner => owner.id is "native" or "bindings") + ) { if (owner.directory != Path.Combine(root, "artifacts", owner.id)) + { throw new InvalidDataException("Native transfer encountered a foreign publisher registration."); - if (selectedArtifacts is not null && !selectedArtifacts.Any(path => path.StartsWith(owner.id + "/", StringComparison.Ordinal))) + } + if (selectedArtifacts is not null + && !selectedArtifacts.Any(path => path.StartsWith(owner.id + "/", StringComparison.Ordinal)) + ) { continue; + } using FileLease activity = await new BuildCachePublisher(owner.directory, BuildCacheArtifactRole.ImmutableArtifact) - .AcquireUseAsync(cancellationToken).ConfigureAwait(false); + .AcquireUseAsync(cancellationToken) + .ConfigureAwait(false); foreach (BuildCacheArtifactDescriptor artifact in owner.ReadArtifacts(cancellationToken) - .Where(static artifact => artifact.role == BuildCacheArtifactRole.ImmutableArtifact).OrderBy(static artifact => artifact.directory, StringComparer.Ordinal)) - { + .Where(static artifact => artifact.role == BuildCacheArtifactRole.ImmutableArtifact) + .OrderBy(static artifact => artifact.directory, StringComparer.Ordinal) + ) { string relative = Path.GetRelativePath(Path.Combine(root, "artifacts"), artifact.directory).Replace('\\', '/'); if (selectedArtifacts is not null && !selectedArtifacts.Contains(relative)) + { continue; + } string[] parts = RequireArtifactPath(relative); - using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(artifact.directory, owner.directory, - parts[3], OutputRoots(parts[0]), cancellationToken).ConfigureAwait(false); + using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + artifact.directory, + owner.directory, + parts[3], + OutputRoots(parts[0]), + cancellationToken: cancellationToken + ).ConfigureAwait(false); foreach (string file in PathBoundary.EnumerateFiles(artifact.directory).Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); - ZipArchiveEntry entry = zip.CreateEntry(relative + "/" + Path.GetRelativePath(artifact.directory, file).Replace('\\', '/'), CompressionLevel.Fastest); + ZipArchiveEntry entry = zip.CreateEntry( + relative + "/" + Path.GetRelativePath(artifact.directory, file).Replace('\\', '/'), + CompressionLevel.Fastest + ); entry.LastWriteTime = new DateTimeOffset(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); if (!OperatingSystem.IsWindows()) + { entry.ExternalAttributes = ((int)File.GetUnixFileMode(file) | 0x8000) << 16; + } using Stream output = entry.Open(); using FileStream input = File.OpenRead(file); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); @@ -86,12 +106,17 @@ public static async Task ExportAsync( count++; } } + } stream.Flush(flushToDisk: true); } if (selectedArtifacts is not null && count != selectedArtifacts.Count) + { throw new InvalidDataException("Native export did not find every selected registered generation."); + } if (count == 0) + { throw new InvalidDataException("No registered immutable native generations are available for export."); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.Install(candidate, destination); return count; @@ -99,7 +124,9 @@ public static async Task ExportAsync( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } @@ -131,23 +158,33 @@ public static async Task ImportAsync( ) { string root = Path.GetFullPath(engineRoot); string stagingRoot = Path.Combine(root, "artifacts", "native-transfer"); - BuildCacheOwnerCatalog.Register(root, stagingRoot, "native-transfer", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + root, + stagingRoot, + "native-transfer", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); using ProcessOwnedDirectory staging = await ProcessOwnedDirectory.CreateAsync(stagingRoot, cancellationToken).ConfigureAwait(false); var artifacts = new HashSet(StringComparer.Ordinal); var names = new HashSet(StringComparer.OrdinalIgnoreCase); using (ZipArchive zip = ZipFile.OpenRead(archivePath)) { long expanded = 0; - if (zip.Entries.Count == 0 || zip.Entries.Count > 200000) + if (zip.Entries.Count == 0 || zip.Entries.Count > 200_000) + { throw new InvalidDataException("Native transfer contains an empty or excessive file inventory."); + } foreach (ZipArchiveEntry entry in zip.Entries) { cancellationToken.ThrowIfCancellationRequested(); string[] parts = entry.FullName.Split('/'); if (parts.Length < 5 || parts.Any(static part => part is "" or "." or ".." || part.Contains('\\') || part.Contains(':')) - || !names.Add(entry.FullName) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) - || (expanded = checked(expanded + entry.Length)) > 32L * 1024 * 1024 * 1024) + || !names.Add(entry.FullName) || ((entry.ExternalAttributes >> 16) & 0xF000) is not (0 or 0x8000) + || (expanded = checked(expanded + entry.Length)) > 32L * 1024 * 1024 * 1024 + ) { throw new InvalidDataException("Native transfer contains an invalid, linked, duplicate or excessive entry."); + } string artifact = string.Join('/', parts.Take(4)); _ = RequireArtifactPath(artifact); artifacts.Add(artifact); @@ -155,9 +192,13 @@ public static async Task ImportAsync( Directory.CreateDirectory(Path.GetDirectoryName(output)!); using (Stream input = entry.Open()) using (var destination = new FileStream(output, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { await input.CopyToAsync(destination, cancellationToken).ConfigureAwait(false); + } if (!OperatingSystem.IsWindows() && entry.ExternalAttributes != 0) - File.SetUnixFileMode(output, (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1ff)); + { + File.SetUnixFileMode(output, (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF)); + } } } foreach (string artifact in artifacts) @@ -165,7 +206,9 @@ public static async Task ImportAsync( cancellationToken.ThrowIfCancellationRequested(); string[] parts = RequireArtifactPath(artifact); if (!BuildArtifactManifest.IsComplete(PathBoundary.Resolve(staging.directory, artifact), parts[3], OutputRoots(parts[0]))) + { throw new InvalidDataException("Native transfer failed exact manifest and payload verification: " + artifact); + } } int imported = 0; foreach (string artifact in artifacts.Order(StringComparer.Ordinal)) @@ -175,12 +218,21 @@ public static async Task ImportAsync( // An existing generation is never replaced by transport, including while a consumer reads it. // Its actual publisher remains responsible for completeness, repair and adoption. if (Directory.Exists(destination)) + { continue; - using CoordinatedFileLease writing = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "artifacts", parts[0], "owner.lock"), - destination + ".read.lock", TimeSpan.FromSeconds(30), shared: false, cancellationToken: cancellationToken).ConfigureAwait(false); + } + using CoordinatedFileLease writing = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "artifacts", parts[0], "owner.lock"), + destination + ".read.lock", + TimeSpan.FromSeconds(30), + shared: false, + cancellationToken: cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(destination)) + { continue; + } Directory.CreateDirectory(Path.GetDirectoryName(destination)!); Directory.Move(PathBoundary.Resolve(staging.directory, artifact), destination); imported++; @@ -191,10 +243,14 @@ public static async Task ImportAsync( private static string[] RequireArtifactPath(string relative) { string[] parts = relative.Split('/'); - if (parts.Length != 4 || parts[0] is not ("native" or "bindings") || parts.Any(static part => - part is "" or "." or ".." || part.Any(static character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.'))) - || parts[3].Length != 64 || parts[3].Any(static character => !char.IsAsciiHexDigitLower(character))) + if (parts.Length != 4 || parts[0] is not ("native" or "bindings") || parts.Any(static part => ( + part is "" or "." or ".." + || part.Any(static character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.')) + )) + || parts[3].Length != 64 || parts[3].Any(static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new InvalidDataException("Native transfer has an invalid publisher or content identity: " + relative); + } return parts; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs index 0f5844226..4e074bdf5 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs @@ -1,4 +1,5 @@ namespace Inno.Build.Toolchains; + /// /// Identifies one immutable native archive selected for a backend product closure. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs index 0146610a6..16c67fd42 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs @@ -9,37 +9,120 @@ using Inno.Core.IO; namespace Inno.Build.Toolchains; + /// /// Transfers aggregate native products and their exact binding generations through the dependency selection protocol. /// public static partial class NativeDependencyManifest { - private static string PlanOptions(ProductNativeBuildPlan plan) => JsonSerializer.Serialize(plan.steps.Select(step => new { step.id, step.component.nativeProject, step.component.toolchainProject, step.component.bindingDefinition, step.configuration, step.options, step.dependencies })); + private static string PlanOptions(ProductNativeBuildPlan plan) + => JsonSerializer.Serialize( + plan.steps.Select( + step => new + { + step.id, + step.component.nativeProject, + step.component.toolchainProject, + step.component.bindingDefinition, + step.configuration, + step.options, + step.dependencies + } + ) + ); + private static async Task ExportAggregateAsync( NativeBuildContext context, ProductNativeBuildPlan plan, ProductNativeBuildResult products, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { - NativeBuildRecipe recipe = products.aggregateRecipe ?? throw new InvalidDataException("An aggregate export must retain its producer recipe."); + NativeBuildRecipe recipe = products.aggregateRecipe + ?? throw new InvalidDataException("An aggregate export must retain its producer recipe."); NativeBuildProduct product = products.Single(); - var sources = await NativeDependencySource.CaptureAsync(context.engineRoot, recipe.inputs.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..]).Concat(context.inputState.CaptureRecordedInputs(context.engineRoot).entries.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..])).Concat(plan.steps.SelectMany(static step => new[] { step.component.nativeProject, step.component.toolchainProject })).Append(recipe.owner.nativeProject).Append(recipe.owner.toolchainProject), cancellation).ConfigureAwait(false); - var bindings = products.bindingGenerations.ToDictionary(static pair => pair.Key, pair => new BindingAsset(pair.Value.fingerprint, pair.Value.usesRuntimeImports, Relative(pair.Value.artifactDirectory), Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.bindingsPath).Replace('\\', '/'), Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.nativeDirectory).Replace('\\', '/')), StringComparer.Ordinal); - var directories = bindings.Values.Select(static binding => binding.directory).Append(Relative(product.directory)).ToHashSet(StringComparer.Ordinal); + Dictionary sources = await NativeDependencySource.CaptureAsync( + context.engineRoot, + recipe.inputs + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + .Concat( + context.inputState + .CaptureRecordedInputs(context.engineRoot).entries + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + ) + .Concat(plan.steps.SelectMany(static step => new[] { step.component.nativeProject, step.component.toolchainProject })) + .Append(recipe.owner.nativeProject) + .Append(recipe.owner.toolchainProject), + cancellationToken + ).ConfigureAwait(false); + Dictionary bindings = products.bindingGenerations.ToDictionary( + static pair => pair.Key, + pair => new BindingAsset( + pair.Value.fingerprint, + pair.Value.usesRuntimeImports, + Relative(pair.Value.artifactDirectory), + Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.bindingsPath).Replace('\\', '/'), + Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.nativeDirectory).Replace('\\', '/') + ), + StringComparer.Ordinal + ); + HashSet directories = bindings.Values + .Select(static binding => binding.directory) + .Append(Relative(product.directory)) + .ToHashSet(StringComparer.Ordinal); Directory.CreateDirectory(output); - string assetName = product.component + "-" + product.targetId + "-" + product.fingerprint + ".zip"; + string assetName = product.component + "-" + product.targetID + "-" + product.fingerprint + ".zip"; string archive = Path.Combine(output, assetName); - await NativeArtifactTransfer.ExportAsync(context.engineRoot, archive, cancellation, directories).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync(context.engineRoot, archive, directories, cancellationToken).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); - string hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellation).ConfigureAwait(false)); - string revision = (await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], context.engineRoot, cancellation).ConfigureAwait(false)).Trim(); - var asset = new AggregateAsset(plan.productId, product.component, product.targetId, context.configuration, PlanOptions(plan), Relative(product.directory), product.fingerprint, Path.GetRelativePath(product.directory, products.aggregateDirectory!).Replace('\\', '/'), product.sharedLibraryExtension, bindings, sources, context.RequireToolchain().declarations.ToArray(), assetName, hash, revision); - string path = Path.Combine(output, plan.productId + "-" + product.targetId + "-" + context.configuration + ".json"); - await VerifySourcesAsync(context.engineRoot, sources, cancellation).ConfigureAwait(false); - AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(new Selection([], [asset], "platform-packages"), new JsonSerializerOptions { WriteIndented = true })); + string hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)); + string revision = (await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); + var asset = new AggregateAsset( + plan.productID, + product.component, + product.targetID, + context.configuration, + PlanOptions(plan), + Relative(product.directory), + product.fingerprint, + Path.GetRelativePath(product.directory, products.aggregateDirectory!).Replace('\\', '/'), + product.sharedLibraryExtension, + bindings, + sources, + context.RequireToolchain().declarations.ToArray(), + assetName, + hash, + revision + ); + string path = Path.Combine(output, plan.productID + "-" + product.targetID + "-" + context.configuration + ".json"); + await VerifySourcesAsync(context.engineRoot, sources, cancellationToken).ConfigureAwait(false); + AtomicFile.WriteAllBytes( + path, + JsonSerializer.SerializeToUtf8Bytes( + new Selection([], [asset], "platform-packages"), + new JsonSerializerOptions { WriteIndented = true } + ) + ); return path; - string Relative(string directory) => Path.GetRelativePath(Path.Combine(context.engineRoot, "artifacts"), directory).Replace('\\', '/'); + string Relative(string directory) + => Path.GetRelativePath(Path.Combine(context.engineRoot, "artifacts"), directory).Replace('\\', '/'); } private static async Task AcquireAggregateAsync( @@ -47,12 +130,19 @@ private static async Task AcquireAggregateAsync( string archive, AggregateAsset asset, ProductNativeBuildPlan plan, - CancellationToken cancellation + CancellationToken cancellationToken ) { - string[] owners = plan.steps.Where(static step => step.component.bindingDefinition is not null).Select(static step => step.component.nativeProject).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] owners = plan.steps + .Where(static step => step.component.bindingDefinition is not null) + .Select(static step => step.component.nativeProject) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (!owners.SequenceEqual(asset.bindings.Keys.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + { throw new InvalidDataException("The aggregate dependency has a different binding closure."); - await VerifySourcesAsync(root, asset.sources, cancellation).ConfigureAwait(false); + } + await VerifySourcesAsync(root, asset.sources, cancellationToken).ConfigureAwait(false); RequireDigest(asset.fingerprint); RequireDigest(asset.sha256); string directory = Resolve(asset.directory, "native", asset.component, asset.fingerprint); @@ -60,26 +150,50 @@ CancellationToken cancellation if (!Directory.Exists(directory) || bindingDirectories.Any(path => !Directory.Exists(path))) { using (FileStream payload = File.OpenRead(archive)) - if (Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellation).ConfigureAwait(false)) != asset.sha256) + { + if (Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)) != asset.sha256) + { throw new InvalidDataException("Native aggregate archive differs from its pinned digest."); - await NativeArtifactTransfer.ImportAsync(root, archive, cancellation).ConfigureAwait(false); + } + } + await NativeArtifactTransfer.ImportAsync(root, archive, cancellationToken).ConfigureAwait(false); } - var readers = new List(); + List readers = []; NativeBuildProduct? product = null; try { var bindings = new Dictionary(StringComparer.Ordinal); - foreach (var pair in asset.bindings) + foreach (KeyValuePair pair in asset.bindings) { BindingAsset binding = pair.Value; string location = ResolveBinding(binding); string owner = Path.Combine(root, "artifacts", "bindings"); - readers.Add(await AcquireAsync(location, owner, "bindings", binding.fingerprint, ["Generated", "Native"], []).ConfigureAwait(false)); - bindings.Add(pair.Key, new() { fingerprint = binding.fingerprint, usesRuntimeImports = binding.runtimeImports, artifactDirectory = location, artifactOwnerDirectory = owner, bindingsPath = PathBoundary.Resolve(location, binding.managed), nativeDirectory = PathBoundary.Resolve(location, binding.native) }); + readers.Add( + await AcquireAsync(location, owner, "bindings", binding.fingerprint, ["Generated", "Native"], []).ConfigureAwait(false) + ); + bindings.Add( + pair.Key, + new NativeBindingGenerationDescriptor() + { + fingerprint = binding.fingerprint, + usesRuntimeImports = binding.runtimeImports, + artifactDirectory = location, + artifactOwnerDirectory = owner, + bindingsPath = PathBoundary.Resolve(location, binding.managed), + nativeDirectory = PathBoundary.Resolve(location, binding.native) + } + ); } - BuildArtifactReadLease reading = await AcquireAsync(directory, Path.Combine(root, "artifacts", "native"), "native", asset.fingerprint, ["Outputs", "Metadata"], bindingDirectories).ConfigureAwait(false); + BuildArtifactReadLease reading = await AcquireAsync( + directory, + Path.Combine(root, "artifacts", "native"), + "native", + asset.fingerprint, + ["Outputs", "Metadata"], + bindingDirectories + ).ConfigureAwait(false); try { product = new(asset.component, asset.target, asset.fingerprint, directory, null, asset.extension, reading); @@ -90,14 +204,16 @@ CancellationToken cancellation throw; } - await VerifySourcesAsync(root, asset.sources, cancellation).ConfigureAwait(false); + await VerifySourcesAsync(root, asset.sources, cancellationToken).ConfigureAwait(false); return new([product], new NativeBindingGenerationResult(bindings, readers), PathBoundary.Resolve(directory, asset.aggregate)); } catch { product?.Dispose(); foreach (IDisposable reader in readers) + { reader.Dispose(); + } throw; } @@ -106,7 +222,9 @@ string ResolveBinding(BindingAsset binding) RequireDigest(binding.fingerprint); string[] parts = binding.directory.Split('/'); if (parts.Length != 4) + { throw new InvalidDataException("Invalid binding aggregate path."); + } return Resolve(binding.directory, "bindings", parts[1], binding.fingerprint); } @@ -117,7 +235,9 @@ string Resolve( string fingerprint ) { if (component.Contains('/') || component.Contains('\\') || relative != $"{owner}/{component}/{asset.target}/{fingerprint}") + { throw new InvalidDataException("Aggregate dependency is outside its exact owner."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(Path.Combine(root, "artifacts"), relative)); } @@ -129,13 +249,19 @@ async Task AcquireAsync( string[] outputs, string[] dependencies ) { - BuildCacheOwnerCatalog.Register(root, owner, id, BuildCacheArtifactRole.ImmutableArtifact, cancellation); - BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(location, owner, fingerprint, outputs, cancellation).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register(root, owner, id, BuildCacheArtifactRole.ImmutableArtifact, cancellationToken); + BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + location, + owner, + fingerprint, + outputs, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { var publisher = new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact); - using FileLease activity = await publisher.AcquireUseAsync(cancellation).ConfigureAwait(false); - publisher.Record(location, location + ".read.lock", dependencies, null, asset.target, cancellation); + using FileLease activity = await publisher.AcquireUseAsync(cancellationToken).ConfigureAwait(false); + publisher.Record(location, location + ".read.lock", dependencies, null, asset.target, cancellationToken); return reading; } catch @@ -149,11 +275,18 @@ string[] dependencies private static async Task VerifySourcesAsync( string root, Dictionary expected, - CancellationToken cancellation + CancellationToken cancellationToken ) { - Dictionary current = await NativeDependencySource.CaptureAsync(root, expected.Keys, cancellation).ConfigureAwait(false); - if (current.Count != expected.Count || current.Any(pair => !expected.TryGetValue(pair.Key, out string? value) || value != pair.Value)) + Dictionary current = await NativeDependencySource.CaptureAsync( + root, + expected.Keys, + cancellationToken + ).ConfigureAwait(false); + if (current.Count != expected.Count + || current.Any(pair => !expected.TryGetValue(pair.Key, out string? value) || value != pair.Value) + ) { throw new InvalidDataException("Native dependency sources changed. Produce the matching backend package for this target."); + } } private sealed record AggregateAsset( diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs index ac71defbd..be98fd01d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs @@ -9,6 +9,7 @@ using Inno.Core.IO; namespace Inno.Build.Toolchains; + /// /// Publishes exact native dependency selections and acquires their immutable payloads without invoking producers. /// @@ -54,42 +55,85 @@ public static async Task> SelectAsync( ) { ToolchainEnvironment.ValidateConfiguration(configuration); Selection selection = ReadSelection(selectionPath); - AggregateAsset[] aggregate = selection.aggregates.Where(asset => asset.product == plan.productId && asset.target == target && asset.configuration == configuration && asset.options == PlanOptions(plan)).ToArray(); + AggregateAsset[] aggregate = selection.aggregates + .Where( + asset => ( + asset.product == plan.productID + && asset.target == target + && asset.configuration == configuration + && asset.options == PlanOptions(plan) + ) + ) + .ToArray(); if (aggregate.Length > 1) + { throw new InvalidDataException("Native aggregate dependency selection is ambiguous."); + } if (aggregate.Length == 1) { await VerifySourcesAsync(engineRoot, aggregate[0].sources, cancellationToken).ConfigureAwait(false); RequireDigest(aggregate[0].sha256); - return[new(aggregate[0].asset, aggregate[0].sha256)]; + return[new NativeDependencyAsset(aggregate[0].asset, aggregate[0].sha256)]; } - var assets = new List(); + List assets = []; var sources = new Dictionary(StringComparer.Ordinal); var selectedComponents = new Dictionary(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { - DependencyAsset[] matches = selection.assets.Where(asset => asset.product == plan.productId && asset.component == step.id && asset.target == target && asset.configuration == (step.configuration ?? configuration) && asset.options == Options(step) && asset.nativeProject == step.component.nativeProject && asset.toolchainProject == step.component.toolchainProject).ToArray(); + DependencyAsset[] matches = selection.assets + .Where( + asset => ( + asset.product == plan.productID + && asset.component == step.id + && asset.target == target + && asset.configuration == (step.configuration ?? configuration) + && asset.options == Options(step) + && asset.nativeProject == step.component.nativeProject + && asset.toolchainProject == step.component.toolchainProject + ) + ) + .ToArray(); if (matches.Length != 1) - throw new InvalidDataException($"Missing or ambiguous native dependency: {step.id}/{target}/{step.configuration ?? configuration}. Produce the matching backend package for the requested target."); + { + throw new InvalidDataException( + $"Missing or ambiguous native dependency: {step.id}/{target}/{step.configuration ?? configuration}. Produce the matching backend package for the requested target." + ); + } DependencyAsset selected = matches[0]; if ((selected.binding is null) != (step.component.bindingDefinition is null)) + { throw new InvalidDataException("Native dependency binding ownership differs: " + step.id); + } selectedComponents.Add(step.id, selected); RequireDigest(selected.sha256); - assets.Add(new(selected.asset, selected.sha256)); - foreach (var pair in selected.sources) + assets.Add(new NativeDependencyAsset(selected.asset, selected.sha256)); + foreach (KeyValuePair pair in selected.sources) + { if (sources.TryGetValue(pair.Key, out string? previous) && previous != pair.Value) + { throw new InvalidDataException("Native packages disagree about their shared source inputs."); + } else + { sources[pair.Key] = pair.Value; + } + } } foreach (ProductNativeBuildStep step in plan.steps) { DependencyAsset selected = selectedComponents[step.id]; - if (selected.dependencies.Count != step.dependencies.Count || step.dependencies.Any(id => !selected.dependencies.TryGetValue(id, out string? fingerprint) || selectedComponents[id].fingerprint != fingerprint)) + if (selected.dependencies.Count != step.dependencies.Count + || step.dependencies.Any( + id => ( + !selected.dependencies.TryGetValue(id, out string? fingerprint) + || selectedComponents[id].fingerprint != fingerprint + ) + ) + ) { throw new InvalidDataException("Native dependency was built against a different closure: " + step.id); + } } await VerifySourcesAsync(engineRoot, sources, cancellationToken).ConfigureAwait(false); @@ -130,28 +174,85 @@ public static async Task ExportAsync( string root = context.engineRoot; string output = PathBoundary.RequireUnlinkedPath(root, Path.GetFullPath(outputDirectory)); if (products.aggregateDirectory is not null) + { return await ExportAggregateAsync(context, plan, products, output, cancellationToken).ConfigureAwait(false); + } if (products.Count != plan.steps.Count) + { throw new InvalidDataException("Dependency export requires the exact complete product closure."); + } Directory.CreateDirectory(output); IReadOnlyList recipes = plan.CreateRecipes(context); - string revision = (await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], root, cancellationToken).ConfigureAwait(false)).Trim(); - var assets = new List(); + string revision = (await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + root, + cancellationToken + ).ConfigureAwait(false)).Trim(); + List assets = []; for (int index = 0; index < products.Count; index++) { ProductNativeBuildStep step = plan.steps[index]; NativeBuildProduct product = products[index]; - if (product.component != step.id || product.targetId != context.RequireToolchain().targetId) + if (product.component != step.id || product.targetID != context.RequireToolchain().targetID) + { throw new InvalidDataException("Dependency export encountered a foreign product."); - string[] sourcePaths = recipes[index].inputs.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath["engine/".Length..]).Append(step.component.nativeProject).Append(step.component.toolchainProject).Concat(step.component.bindingDefinition is string definition ? [definition] : Array.Empty()).Distinct(StringComparer.Ordinal).ToArray(); + } + string[] sourcePaths = recipes[index].inputs + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath["engine/".Length..]) + .Append(step.component.nativeProject) + .Append(step.component.toolchainProject) + .Concat(step.component.bindingDefinition is string definition ? [definition] : []) + .Distinct(StringComparer.Ordinal) + .ToArray(); if (step.component.bindingDefinition is not null) { - var bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration).WithToolchain(context.RequireToolchain()).WithBindingGenerator(context.RequireBindingGenerator()); - await bindingContext.RequireBindingGenerator().ComputeInputFingerprintAsync(bindingContext, new NativeBindingGenerationRequest([step.component], product.targetId, NativeBindingOutputMode.TargetArtifacts, componentOptions: new Dictionary { [step.component.nativeProject] = step.options }), cancellationToken).ConfigureAwait(false); - sourcePaths = sourcePaths.Concat(bindingContext.inputState.CaptureRecordedInputs(root).entries.Where(input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..])).Distinct(StringComparer.Ordinal).ToArray(); + NativeBuildContext bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration) + .WithToolchain(context.RequireToolchain()) + .WithBindingGenerator(context.RequireBindingGenerator()); + await bindingContext + .RequireBindingGenerator() + .ComputeInputFingerprintAsync( + bindingContext, + new NativeBindingGenerationRequest( + [step.component], + product.targetID, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: new Dictionary + { + [step.component.nativeProject] = step.options + } + ), + cancellationToken + ) + .ConfigureAwait(false); + sourcePaths = sourcePaths + .Concat( + bindingContext.inputState + .CaptureRecordedInputs(root).entries + .Where( + input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + ) + .Distinct(StringComparer.Ordinal) + .ToArray(); } - Dictionary sources = await NativeDependencySource.CaptureAsync(root, sourcePaths, cancellationToken).ConfigureAwait(false); + Dictionary sources = await NativeDependencySource.CaptureAsync( + root, + sourcePaths, + cancellationToken + ).ConfigureAwait(false); string directory = Relative(product.directory); var selected = new HashSet(StringComparer.Ordinal) { @@ -161,24 +262,67 @@ public static async Task ExportAsync( if (product.bindingGeneration is { } generation) { if (generation.artifactDirectory.Length == 0) + { throw new InvalidDataException("Dependency publication requires immutable target binding generations."); + } string bindingDirectory = Relative(generation.artifactDirectory); selected.Add(bindingDirectory); - binding = new(generation.fingerprint, generation.usesRuntimeImports, bindingDirectory, Path.GetRelativePath(generation.artifactDirectory, generation.bindingsPath).Replace('\\', '/'), Path.GetRelativePath(generation.artifactDirectory, generation.nativeDirectory).Replace('\\', '/')); + binding = new( + generation.fingerprint, + generation.usesRuntimeImports, + bindingDirectory, + Path.GetRelativePath(generation.artifactDirectory, generation.bindingsPath).Replace('\\', '/'), + Path.GetRelativePath(generation.artifactDirectory, generation.nativeDirectory).Replace('\\', '/') + ); } - string asset = step.id + "-" + product.targetId + "-" + product.fingerprint + ".zip"; + string asset = step.id + "-" + product.targetID + "-" + product.fingerprint + ".zip"; string archive = Path.Combine(output, asset); - await NativeArtifactTransfer.ExportAsync(root, archive, cancellationToken, selected).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync(root, archive, selected, cancellationToken).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); string digest = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)); - assets.Add(new(plan.productId, step.id, product.targetId, step.configuration ?? context.configuration, step.component.nativeProject, step.component.toolchainProject, Options(step), directory, product.fingerprint, product.sharedLibraryExtension, binding, sources, context.RequireToolchain().declarations.ToArray(), step.dependencies.ToDictionary(id => id, id => products.Single(product => product.component == id).fingerprint, StringComparer.Ordinal), asset, digest, revision)); + assets.Add( + new DependencyAsset( + plan.productID, + step.id, + product.targetID, + step.configuration ?? context.configuration, + step.component.nativeProject, + step.component.toolchainProject, + Options(step), + directory, + product.fingerprint, + product.sharedLibraryExtension, + binding, + sources, + context.RequireToolchain().declarations.ToArray(), + step.dependencies.ToDictionary( + id => id, + id => products.Single(product => product.component == id).fingerprint, + StringComparer.Ordinal + ), + asset, + digest, + revision + ) + ); } foreach (DependencyAsset asset in assets) + { await VerifySourcesAsync(root, asset.sources, cancellationToken).ConfigureAwait(false); - string destination = Path.Combine(output, plan.productId + "-" + context.RequireToolchain().targetId + "-" + context.configuration + ".json"); - AtomicFile.WriteAllBytes(destination, JsonSerializer.SerializeToUtf8Bytes(new Selection(assets.ToArray(), [], "platform-packages"), new JsonSerializerOptions { WriteIndented = true })); + } + string destination = Path.Combine( + output, + plan.productID + "-" + context.RequireToolchain().targetID + "-" + context.configuration + ".json" + ); + AtomicFile.WriteAllBytes( + destination, + JsonSerializer.SerializeToUtf8Bytes( + new Selection(assets.ToArray(), [], "platform-packages"), + new JsonSerializerOptions { WriteIndented = true } + ) + ); return destination; string Relative(string path) => Path.GetRelativePath(Path.Combine(root, "artifacts"), path).Replace('\\', '/'); } @@ -224,39 +368,70 @@ public static async Task AcquireAsync( ToolchainEnvironment.ValidateConfiguration(configuration); string root = Path.GetFullPath(engineRoot); Selection selection = ReadSelection(selectionPath); - AggregateAsset[] aggregates = selection.aggregates.Where(asset => asset.product == plan.productId && asset.target == target && asset.configuration == configuration && asset.options == PlanOptions(plan)).ToArray(); + AggregateAsset[] aggregates = selection.aggregates + .Where( + asset => ( + asset.product == plan.productID + && asset.target == target + && asset.configuration == configuration + && asset.options == PlanOptions(plan) + ) + ) + .ToArray(); if (aggregates.Length > 1) + { throw new InvalidDataException("Native dependency selection contains ambiguous aggregate products."); + } if (aggregates.Length == 1) - return await AcquireAggregateAsync(root, Archive(aggregates[0].sha256), aggregates[0], plan, cancellationToken).ConfigureAwait(false); + { + return await AcquireAggregateAsync( + root, + Archive(aggregates[0].sha256), + aggregates[0], + plan, + cancellationToken + ).ConfigureAwait(false); + } if (selection.assets is null) + { throw new InvalidDataException("Native dependency selection has no asset inventory."); + } var expectedSources = new Dictionary(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { DependencyAsset asset = Select(step); - foreach (var pair in asset.sources) + foreach (KeyValuePair pair in asset.sources) + { if (expectedSources.TryGetValue(pair.Key, out string? existing) && existing != pair.Value) + { throw new InvalidDataException("Dependency assets disagree about a shared source input: " + pair.Key); + } else + { expectedSources[pair.Key] = pair.Value; + } + } } string Archive(string digest) { RequireDigest(digest); if (selection.layout != "platform-packages") + { throw new InvalidDataException("Native acquisition requires a bound platform package store."); + } if (!target.All(static value => char.IsAsciiLetterOrDigit(value) || value == '-')) + { throw new InvalidDataException("The native payload requires a registered platform name."); + } string store = Path.GetDirectoryName(Path.GetFullPath(selectionPath))!; return PathBoundary.RequireUnlinkedPath(store, PathBoundary.Resolve(store, $"{target}/native/{digest}.zip")); } await VerifySourcesAsync().ConfigureAwait(false); - var products = new List(); + List products = []; var bindings = new Dictionary(StringComparer.Ordinal); - var reading = new List(); + List reading = []; try { foreach (ProductNativeBuildStep step in plan.steps) @@ -264,19 +439,43 @@ string Archive(string digest) cancellationToken.ThrowIfCancellationRequested(); string selectedConfiguration = step.configuration ?? configuration; DependencyAsset asset = Select(step); - if (asset.nativeProject != step.component.nativeProject || asset.toolchainProject != step.component.toolchainProject || (asset.binding is null) != (step.component.bindingDefinition is null)) + if (asset.nativeProject != step.component.nativeProject + || asset.toolchainProject != step.component.toolchainProject + || (asset.binding is null) != (step.component.bindingDefinition is null) + ) { throw new InvalidDataException("Native dependency component ownership differs from the current product: " + step.id); - if (asset.dependencies.Count != step.dependencies.Count || step.dependencies.Any(id => !asset.dependencies.TryGetValue(id, out string? fingerprint) || products.Single(product => product.component == id).fingerprint != fingerprint)) - throw new InvalidDataException("Native dependency artifacts were compiled against a different dependency closure: " + step.id); + } + if (asset.dependencies.Count != step.dependencies.Count + || step.dependencies.Any( + id => ( + !asset.dependencies.TryGetValue(id, out string? fingerprint) + || products.Single(product => product.component == id).fingerprint != fingerprint + ) + ) + ) { + throw new InvalidDataException( + "Native dependency artifacts were compiled against a different dependency closure: " + step.id + ); + } RequireDigest(asset.sha256); RequireDigest(asset.fingerprint); string directory = ResolveArtifact(asset.directory, "native", asset.component, target, asset.fingerprint); string archive = Archive(asset.sha256); - if (!Directory.Exists(directory) || asset.binding is { } requiredBinding && !Directory.Exists(PathBoundary.Resolve(Path.Combine(root, "artifacts"), requiredBinding.directory))) - { + if (!Directory.Exists(directory) + || asset.binding is { } requiredBinding + && !Directory.Exists(PathBoundary.Resolve(Path.Combine(root, "artifacts"), requiredBinding.directory)) + ) { using (FileStream payload = File.OpenRead(archive)) - if (Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)) != asset.sha256) - throw new InvalidDataException("Native dependency archive digest differs from its pinned selection: " + asset.asset); + { + if (Convert.ToHexStringLower( + await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false) + ) != asset.sha256 + ) { + throw new InvalidDataException( + "Native dependency archive digest differs from its pinned selection: " + asset.asset + ); + } + } await NativeArtifactTransfer.ImportAsync(root, archive, cancellationToken).ConfigureAwait(false); } @@ -286,13 +485,35 @@ string Archive(string digest) RequireDigest(binding.fingerprint); string[] parts = binding.directory.Split('/'); if (parts.Length != 4) + { throw new InvalidDataException("Invalid native binding artifact location."); + } string bindingDirectory = ResolveArtifact(binding.directory, "bindings", parts[1], target, binding.fingerprint); string owner = Path.Combine(root, "artifacts", "bindings"); BuildCacheOwnerCatalog.Register(root, owner, "bindings", BuildCacheArtifactRole.ImmutableArtifact, cancellationToken); - reading.Add(await BuildArtifactReadLease.AcquireAsync(bindingDirectory, owner, binding.fingerprint, ["Generated", "Native"], cancellationToken: cancellationToken).ConfigureAwait(false)); - using (FileLease activity = await new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).AcquireUseAsync(cancellationToken).ConfigureAwait(false)) - new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).Record(bindingDirectory, bindingDirectory + ".read.lock", [], null, target, cancellationToken); + reading.Add( + await BuildArtifactReadLease.AcquireAsync( + bindingDirectory, + owner, + binding.fingerprint, + ["Generated", "Native"], + cancellationToken: cancellationToken + ).ConfigureAwait(false) + ); + using (FileLease activity = await new BuildCachePublisher( + owner, + BuildCacheArtifactRole.ImmutableArtifact + ).AcquireUseAsync(cancellationToken).ConfigureAwait(false) + ) { + new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).Record( + bindingDirectory, + bindingDirectory + ".read.lock", + [], + null, + target, + cancellationToken + ); + } generation = new() { fingerprint = binding.fingerprint, @@ -302,19 +523,38 @@ string Archive(string digest) bindingsPath = PathBoundary.Resolve(bindingDirectory, binding.managed), nativeDirectory = PathBoundary.Resolve(bindingDirectory, binding.native) }; - if (bindings.TryGetValue(step.component.nativeProject, out var previous) && previous.fingerprint != generation.fingerprint) + if (bindings.TryGetValue(step.component.nativeProject, out NativeBindingGenerationDescriptor? previous) + && previous.fingerprint != generation.fingerprint + ) { throw new InvalidDataException("A dependency closure selected conflicting binding generations."); + } bindings[step.component.nativeProject] = generation; } string nativeOwner = Path.Combine(root, "artifacts", "native"); BuildCacheOwnerCatalog.Register(root, nativeOwner, "native", BuildCacheArtifactRole.ImmutableArtifact, cancellationToken); - BuildArtifactReadLease lease = await BuildArtifactReadLease.AcquireAsync(directory, nativeOwner, asset.fingerprint, ["Outputs", "Metadata"], cancellationToken: cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease lease = await BuildArtifactReadLease.AcquireAsync( + directory, + nativeOwner, + asset.fingerprint, + ["Outputs", "Metadata"], + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { - using FileLease activity = await new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).AcquireUseAsync(cancellationToken).ConfigureAwait(false); - new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).Record(directory, directory + ".read.lock", generation is null ? [] : [generation.artifactDirectory], step.id + "/" + target + "/" + selectedConfiguration, target, cancellationToken); - products.Add(new(step.id, target, asset.fingerprint, directory, generation, asset.extension, lease)); + using FileLease activity = await new BuildCachePublisher( + nativeOwner, + BuildCacheArtifactRole.ImmutableArtifact + ).AcquireUseAsync(cancellationToken).ConfigureAwait(false); + new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).Record( + directory, + directory + ".read.lock", + generation is null ? [] : [generation.artifactDirectory], + step.id + "/" + target + "/" + selectedConfiguration, + target, + cancellationToken + ); + products.Add(new NativeBuildProduct(step.id, target, asset.fingerprint, directory, generation, asset.extension, lease)); } catch { @@ -329,25 +569,52 @@ string Archive(string digest) catch { foreach (NativeBuildProduct product in products) + { product.Dispose(); + } foreach (IDisposable lease in reading) + { lease.Dispose(); + } throw; } DependencyAsset Select(ProductNativeBuildStep step) { - DependencyAsset[] matches = selection.assets.Where(asset => asset.product == plan.productId && asset.component == step.id && asset.target == target && asset.configuration == (step.configuration ?? configuration) && asset.options == Options(step)).ToArray(); + DependencyAsset[] matches = selection.assets + .Where( + asset => ( + asset.product == plan.productID + && asset.component == step.id + && asset.target == target + && asset.configuration == (step.configuration ?? configuration) + && asset.options == Options(step) + ) + ) + .ToArray(); if (matches.Length != 1) - throw new InvalidDataException($"Native dependency '{step.id}/{target}/{step.configuration ?? configuration}' requires exactly one matching artifact. Produce the matching backend package for the requested target."); + { + throw new InvalidDataException( + $"Native dependency '{step.id}/{target}/{step.configuration ?? configuration}' requires exactly one matching artifact. Produce the matching backend package for the requested target." + ); + } return matches[0]; } async Task VerifySourcesAsync() { - Dictionary current = await NativeDependencySource.CaptureAsync(root, expectedSources.Keys, cancellationToken).ConfigureAwait(false); - if (current.Count != expectedSources.Count || current.Any(pair => !expectedSources.TryGetValue(pair.Key, out string? value) || value != pair.Value)) - throw new InvalidDataException("Native dependency sources changed. Produce the matching backend package for the requested target."); + Dictionary current = await NativeDependencySource.CaptureAsync( + root, + expectedSources.Keys, + cancellationToken + ).ConfigureAwait(false); + if (current.Count != expectedSources.Count + || current.Any(pair => !expectedSources.TryGetValue(pair.Key, out string? value) || value != pair.Value) + ) { + throw new InvalidDataException( + "Native dependency sources changed. Produce the matching backend package for the requested target." + ); + } } string ResolveArtifact( @@ -358,7 +625,9 @@ string ResolveArtifact( string fingerprint ) { if (relative != $"{owner}/{component}/{abi}/{fingerprint}" || component.Contains('/') || component.Contains('\\')) + { throw new InvalidDataException("Native dependency artifact is outside its exact declared owner."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(Path.Combine(root, "artifacts"), relative)); } } @@ -368,7 +637,8 @@ private static Selection ReadSelection(string path) Selection selection; try { - selection = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new InvalidDataException("Native dependency selection is empty."); + selection = JsonSerializer.Deserialize(File.ReadAllBytes(path)) + ?? throw new InvalidDataException("Native dependency selection is empty."); } catch (JsonException failure) { @@ -376,20 +646,47 @@ private static Selection ReadSelection(string path) } if (selection.layout is not (null or "platform-packages")) + { throw new InvalidDataException("Unknown native payload layout."); + } if (selection.assets is null || selection.aggregates is null) + { throw new InvalidDataException("Native dependency selection requires component and aggregate inventories."); + } foreach (DependencyAsset asset in selection.assets) { - if (asset is null || asset.sources is null || asset.producerTools is null || asset.dependencies is null || string.IsNullOrWhiteSpace(asset.product) || string.IsNullOrWhiteSpace(asset.component) || string.IsNullOrWhiteSpace(asset.target) || string.IsNullOrWhiteSpace(asset.nativeProject) || string.IsNullOrWhiteSpace(asset.toolchainProject) || string.IsNullOrWhiteSpace(asset.options) || string.IsNullOrWhiteSpace(asset.directory)) + if (asset is null + || asset.sources is null + || asset.producerTools is null + || asset.dependencies is null + || string.IsNullOrWhiteSpace(asset.product) + || string.IsNullOrWhiteSpace(asset.component) + || string.IsNullOrWhiteSpace(asset.target) + || string.IsNullOrWhiteSpace(asset.nativeProject) + || string.IsNullOrWhiteSpace(asset.toolchainProject) + || string.IsNullOrWhiteSpace(asset.options) + || string.IsNullOrWhiteSpace(asset.directory) + ) { throw new InvalidDataException("Native dependency asset is missing required provenance or ownership."); + } ValidateAsset(asset.asset, asset.sha256, asset.fingerprint, asset.sources, asset.producerRevision); } foreach (AggregateAsset asset in selection.aggregates) { - if (asset is null || asset.sources is null || asset.producerTools is null || asset.bindings is null || string.IsNullOrWhiteSpace(asset.product) || string.IsNullOrWhiteSpace(asset.component) || string.IsNullOrWhiteSpace(asset.target) || string.IsNullOrWhiteSpace(asset.options) || string.IsNullOrWhiteSpace(asset.directory) || string.IsNullOrWhiteSpace(asset.aggregate)) + if (asset is null + || asset.sources is null + || asset.producerTools is null + || asset.bindings is null + || string.IsNullOrWhiteSpace(asset.product) + || string.IsNullOrWhiteSpace(asset.component) + || string.IsNullOrWhiteSpace(asset.target) + || string.IsNullOrWhiteSpace(asset.options) + || string.IsNullOrWhiteSpace(asset.directory) + || string.IsNullOrWhiteSpace(asset.aggregate) + ) { throw new InvalidDataException("Native aggregate is missing required provenance or ownership."); + } ValidateAsset(asset.asset, asset.sha256, asset.fingerprint, asset.sources, asset.producerRevision); } @@ -402,21 +699,34 @@ static void ValidateAsset( string revision ) { if (revision is null || revision.Length != 40 || revision.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException("Native dependency producer revision must be an exact commit."); + } RequireDigest(digest); RequireDigest(fingerprint); - if (string.IsNullOrWhiteSpace(name) || name != Path.GetFileName(name) || name.Contains('\\') || !name.EndsWith(".zip", StringComparison.Ordinal) || sources.Count == 0) + if (string.IsNullOrWhiteSpace(name) + || name != Path.GetFileName(name) + || name.Contains('\\') + || !name.EndsWith(".zip", StringComparison.Ordinal) + || sources.Count == 0 + ) { throw new InvalidDataException("Native dependency requires a named native archive and nonempty source provenance."); + } foreach (string identity in sources.Values) + { RequireDigest(identity); + } } } private static string Options(ProductNativeBuildStep step) => JsonSerializer.Serialize(new { step.options, step.dependencies }); + private static void RequireDigest(string value) { if (value is null || value.Length != 64 || value.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException("Native dependency digest must be a complete lowercase SHA-256 identity."); + } } private sealed record Selection( @@ -424,6 +734,7 @@ private sealed record Selection( AggregateAsset[] aggregates, string? layout = null ); + private sealed record BindingAsset( string fingerprint, bool runtimeImports, @@ -431,6 +742,7 @@ private sealed record BindingAsset( string managed, string native ); + private sealed record DependencyAsset( string product, string component, diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs index c0e5628ff..5f8e039ab 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs @@ -6,48 +6,73 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build.Toolchains; + internal static class NativeDependencySource { internal static async Task> CaptureAsync( string root, IEnumerable paths, - CancellationToken cancellation + CancellationToken cancellationToken ) { string index = await GitAsync(["ls-files", "--stage", "-z"]).ConfigureAwait(false); - string[] modules = index.Split('\0', StringSplitOptions.RemoveEmptyEntries).Where(static item => item.StartsWith("160000 ", StringComparison.Ordinal)).Select(static item => item[(item.IndexOf('\t') + 1)..]).ToArray(); - string[] roots = paths.Select(path => modules.FirstOrDefault(module => path == module || path.StartsWith(module + "/", StringComparison.Ordinal)) ?? path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] modules = index + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .Where(static item => item.StartsWith("160000 ", StringComparison.Ordinal)) + .Select(static item => item[(item.IndexOf('\t') + 1)..]) + .ToArray(); + string[] roots = paths + .Select( + path => modules.FirstOrDefault(module => path == module || path.StartsWith(module + "/", StringComparison.Ordinal)) ?? path + ) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (roots.Length == 0) + { throw new InvalidDataException("A native dependency must declare tracked source inputs."); + } foreach (string path in roots) - _ = Inno.Core.IO.PathBoundary.Resolve(root, path); - string dirty = await GitAsync(["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none", "--", ..roots]).ConfigureAwait(false); + { + _ = PathBoundary.Resolve(root, path); + } + string dirty = await GitAsync( + ["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none", "--", ..roots] + ).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(dirty)) + { throw new InvalidDataException("Native dependency sources must match their committed input: " + dirty); + } var result = new Dictionary(StringComparer.Ordinal); foreach (string[] batch in roots.Chunk(80)) { string tree = await GitAsync(["ls-tree", "-t", "-z", "HEAD", "--", ..batch]).ConfigureAwait(false); - var entries = tree.Split('\0', StringSplitOptions.RemoveEmptyEntries).ToDictionary(entry => entry[(entry.IndexOf('\t') + 1)..], StringComparer.Ordinal); + Dictionary entries = tree + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .ToDictionary(entry => entry[(entry.IndexOf('\t') + 1)..], StringComparer.Ordinal); foreach (string path in batch) { if (!entries.TryGetValue(path, out string? entry)) + { throw new InvalidDataException("Native dependency input has no committed owner: " + path); + } result.Add(path, NativeBuildFingerprint.Create([entry], [])); } } - await VerifyWorkingTreeAsync(root, "HEAD", roots, cancellation).ConfigureAwait(false); + await VerifyWorkingTreeAsync(root, "HEAD", roots, cancellationToken).ConfigureAwait(false); return result; - Task GitAsync(string[] arguments) => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellation); + Task GitAsync(string[] arguments) + => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellationToken); } private static async Task VerifyWorkingTreeAsync( string root, string revision, string[] paths, - CancellationToken cancellation + CancellationToken cancellationToken ) { var blobs = new Dictionary(StringComparer.Ordinal); foreach (string[] batch in paths.Chunk(80)) @@ -56,26 +81,39 @@ CancellationToken cancellation foreach (string entry in tree.Split('\0', StringSplitOptions.RemoveEmptyEntries)) { if (string.IsNullOrWhiteSpace(entry)) + { continue; + } int separator = entry.IndexOf('\t'); if (separator < 0) + { throw new InvalidDataException("Native source tree returned invalid object metadata."); + } string[] metadata = entry[..separator].Split(' '); if (metadata.Length != 3) + { throw new InvalidDataException("Native source tree returned incomplete object metadata."); + } string relative = entry[(separator + 1)..]; - string path = Inno.Core.IO.PathBoundary.Resolve(root, relative); - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); + string path = PathBoundary.Resolve(root, relative); + PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); if (metadata[1] == "commit") { - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, path); + PathBoundary.RequireUnlinkedPath(root, path); // A consumer does not need a third-party checkout. An initialized checkout is mutable and must be checked. if (File.Exists(Path.Combine(path, ".git")) || Directory.Exists(Path.Combine(path, ".git"))) { - string head = await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], path, cancellation).ConfigureAwait(false); + string head = await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + path, + cancellationToken + ).ConfigureAwait(false); if (head.Trim() != metadata[2]) + { throw new InvalidDataException("Native submodule revision differs from its committed owner: " + relative); - await VerifyWorkingTreeAsync(path, metadata[2], ["."], cancellation).ConfigureAwait(false); + } + await VerifyWorkingTreeAsync(path, metadata[2], ["."], cancellationToken).ConfigureAwait(false); } } else if (metadata[0] == "120000") @@ -84,15 +122,21 @@ CancellationToken cancellation byte[] bytes = target is null ? File.ReadAllBytes(path) : Encoding.UTF8.GetBytes(target.Replace('\\', '/')); byte[] prefix = Encoding.ASCII.GetBytes("blob " + bytes.Length + "\0"); byte[] content = [..prefix, ..bytes]; - string identity = Convert.ToHexStringLower(metadata[2].Length == 40 ? SHA1.HashData(content) : SHA256.HashData(content)); + string identity = Convert.ToHexStringLower( + metadata[2].Length == 40 ? SHA1.HashData(content) : SHA256.HashData(content) + ); if (identity != metadata[2]) + { throw new InvalidDataException("Native source link changed: " + relative); + } } else { - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, path); + PathBoundary.RequireUnlinkedPath(root, path); if (!File.Exists(path)) + { throw new InvalidDataException("Native source is missing: " + relative); + } blobs[relative] = metadata[2]; } } @@ -103,23 +147,33 @@ CancellationToken cancellation string[] hashes = (await GitAsync(["hash-object", "--", ..batch.Select(static pair => pair.Key)]).ConfigureAwait(false)) .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (hashes.Length != batch.Length) + { throw new InvalidDataException("Native source hashing returned an incomplete input inventory."); - var changed = batch.Where(( + } + KeyValuePair[] changed = batch.Where(( pair, index ) => hashes[index] != pair.Value).ToArray(); if (changed.Length == 0) + { continue; + } // Existing CRLF blobs can already match their checkout even when the current clean filter normalizes them. - string[] raw = (await GitAsync(["hash-object", "--no-filters", "--", ..changed.Select(static pair => pair.Key)]).ConfigureAwait(false)) + string[] raw = (await GitAsync( + ["hash-object", "--no-filters", "--", ..changed.Select(static pair => pair.Key)] + ).ConfigureAwait(false)) .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (raw.Length != changed.Length || changed.Where(( pair, index - ) => raw[index] != pair.Value).Any()) - throw new InvalidDataException("Native dependency source bytes changed. Produce the matching backend package for the requested target."); + ) => raw[index] != pair.Value).Any() + ) { + throw new InvalidDataException( + "Native dependency source bytes changed. Produce the matching backend package for the requested target." + ); + } } Task GitAsync(string[] arguments) - => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellation); + => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellationToken); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs b/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs index a449a3fab..c9403aa35 100644 --- a/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs +++ b/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs @@ -41,14 +41,17 @@ public BuildHostServices( /// Gets the host's scoped execution path provider. /// public IToolchainWorkspaceProvider workspaces { get; } + /// /// Gets environment variable name semantics. /// public StringComparer environmentComparer { get; } + /// /// Gets checkout-relative execution implementation inputs. /// public IReadOnlyList inputPaths { get; } + /// /// Gets the host-owned executable suffix. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs index 8ecc4da78..8808aa8c3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs +++ b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs @@ -10,17 +10,19 @@ namespace Inno.Build.Toolchains; /// public sealed class PhysicalToolchainWorkspaceProvider : IToolchainWorkspaceProvider { - /// + /// public string identity => "physical"; - /// + /// public ValueTask OpenAsync( string physicalPath, CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("Tool execution requires an absolute physical owner path.", nameof(physicalPath)); + } string physical = Path.GetFullPath(physicalPath); Directory.CreateDirectory(physical); return ValueTask.FromResult(new ToolchainWorkingDirectory(physical)); diff --git a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs index 498c73a2f..5b27fe4bf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs +++ b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs @@ -25,7 +25,7 @@ public static class BuildMaintenanceApplication /// /// Zero on success, two on cancellation, or one with a diagnostic on failure. /// - public static async Task Run( + public static async Task RunAsync( string[] arguments, CancellationToken cancellationToken ) { @@ -34,7 +34,9 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(arguments); cancellationToken.ThrowIfCancellationRequested(); if (arguments.Length == 0 || arguments[0] != "clean") + { throw new ArgumentException("Maintenance requires the clean command."); + } var options = new Dictionary(StringComparer.Ordinal); var allowed = new HashSet(StringComparer.Ordinal) { @@ -45,32 +47,56 @@ CancellationToken cancellationToken { string argument = arguments[index]; if (!argument.StartsWith("--", StringComparison.Ordinal) || !allowed.Contains(argument[2..])) + { throw new ArgumentException($"Unknown maintenance option '{argument}'."); + } string value = "true"; if (argument != "--dry-run") { if (++index >= arguments.Length || arguments[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Missing value for '{argument}'."); + } value = arguments[index]; } if (!options.TryAdd(argument[2..], value)) + { throw new ArgumentException($"Duplicate maintenance option '{argument}'."); + } } if (options.GetValueOrDefault("scope") != "cache" || !options.TryGetValue("engine-root", out string? root)) + { throw new ArgumentException("Cache maintenance requires --scope cache and --engine-root."); + } long Bytes( string name, long fallback ) => options.TryGetValue(name, out string? value) - ? checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * (1L << 30)) : fallback; - double seconds = double.Parse(options.GetValueOrDefault("cache-time-seconds", "600"), - NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); - await CleanAsync(root, new BuildCachePolicy(Bytes("cache-budget-gib", 64L << 30), - Bytes("cache-min-free-gib", 20L << 30), TimeSpan.FromSeconds(seconds)), - true, options.ContainsKey("dry-run"), options.GetValueOrDefault("target"), cancellationToken).ConfigureAwait(false); + ? checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * (1L << 30)) + : fallback; + double seconds = double.Parse( + options.GetValueOrDefault("cache-time-seconds", "600"), + NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture + ); + await CleanAsync( + root, + new BuildCachePolicy( + Bytes("cache-budget-gib", 64L << 30), + Bytes("cache-min-free-gib", 20L << 30), + TimeSpan.FromSeconds(seconds) + ), + true, + options.ContainsKey("dry-run"), + options.GetValueOrDefault("target"), + cancellationToken + ).ConfigureAwait(false); return 0; } - catch (OperationCanceledException) { return 2; } + catch (OperationCanceledException) + { + return 2; + } catch (Exception failure) { Console.Error.WriteLine(failure); @@ -93,7 +119,7 @@ long fallback /// /// Whether to report the plan without retiring it. /// - /// + /// /// An optional exact producer target filter; shared dependencies remain protected. /// /// @@ -119,18 +145,22 @@ public static async Task CleanAsync( BuildCachePolicy policy, bool retireAll, bool dryRun, - string? targetId, + string? targetID, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(policy); Stopwatch elapsed = Stopwatch.StartNew(); IReadOnlyList owners; - using (var inventoryBudget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + using (CancellationTokenSource inventoryBudget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { inventoryBudget.CancelAfter(policy.timeBudget); try { - owners = BuildCacheOwnerCatalog.ReadOwners(engineRoot, new BuildCacheInventoryProgress(engineRoot, dryRun), inventoryBudget.Token); + owners = BuildCacheOwnerCatalog.ReadOwners( + engineRoot, + new BuildCacheInventoryProgress(engineRoot, dryRun), + inventoryBudget.Token + ); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { @@ -139,18 +169,36 @@ CancellationToken cancellationToken } TimeSpan remaining = policy.timeBudget - elapsed.Elapsed; if (remaining <= TimeSpan.Zero) + { throw new TimeoutException("Cache owner discovery exhausted its operation budget; no artifact was retired."); + } var remainingPolicy = new BuildCachePolicy(policy.maximumBytes, policy.minimumFreeBytes, remaining); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(engineRoot, - owners, remainingPolicy, retireAll, targetId, cancellationToken); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + engineRoot, + owners, + remainingPolicy, + retireAll, + targetID, + cancellationToken + ); if (dryRun) + { foreach (BuildCacheArtifactDescriptor artifact in plan.candidates) + { Console.WriteLine($"Would retire {artifact.directory} ({artifact.bytes} bytes)"); + } + } BuildCacheCleanupResult result = await plan.ExecuteAsync(dryRun, cancellationToken).ConfigureAwait(false); - Console.WriteLine($"Cache: {plan.totalBytes} bytes; protected {plan.protectedBytes}; reclaimed {result.retiredBytes}; skipped {result.skipped.Count}."); - foreach (var failure in result.failures) + Console.WriteLine( + $"Cache: {plan.totalBytes} bytes; protected {plan.protectedBytes}; reclaimed {result.retiredBytes}; skipped {result.skipped.Count}." + ); + foreach (KeyValuePair failure in result.failures) + { Console.Error.WriteLine($"Cache retirement failed: {failure.Key}: {failure.Value}"); + } if (retireAll && result.failures.Count != 0) + { throw new InvalidOperationException("Explicit cache cleanup completed with failures."); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs index 53f07e3f6..30c4431df 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs @@ -10,7 +10,7 @@ namespace Inno.Build.Toolchains; /// public static class DotNetSdkEnvironment { - private static readonly string[] AmbientSdkVariables = + private static readonly string[] AMBIENT_SDK_VARIABLES = [ "MSBuildSDKsPath", "MSBUILD_EXE_PATH", "MSBuildExtensionsPath", "MSBuildExtensionsPath32", "MSBuildExtensionsPath64", @@ -45,10 +45,16 @@ public static class DotNetSdkEnvironment string host = ToolchainEnvironment.ResolveExecutable(hostPath); var selected = new Dictionary(StringComparer.OrdinalIgnoreCase); if (environment is not null) + { foreach ((string name, string value) in environment) + { selected[name] = value; - foreach (string variable in AmbientSdkVariables) + } + } + foreach (string variable in AMBIENT_SDK_VARIABLES) + { selected[variable] = null; + } selected["DOTNET_HOST_PATH"] = host; selected["DOTNET_ROOT"] = Path.GetDirectoryName(host)!; return new ReadOnlyDictionary(selected); diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs index 0b77850be..8431d6c07 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs @@ -41,7 +41,9 @@ public static ValueTask ResolveAsync( ArgumentException.ThrowIfNullOrWhiteSpace(projectPath); string project = Path.GetFullPath(projectPath); if (!File.Exists(project)) + { throw new FileNotFoundException("The managed entry project is absent.", project); + } return ResolveDirectoryAsync(hostPath, Path.GetDirectoryName(project)!, cancellationToken); } @@ -81,30 +83,44 @@ public static async ValueTask ResolveDirectoryAsync( ArgumentException.ThrowIfNullOrWhiteSpace(ownerDirectory); string directory = Path.GetFullPath(ownerDirectory); if (!Directory.Exists(directory)) + { throw new DirectoryNotFoundException($"The managed SDK source owner is absent: '{directory}'."); + } hostPath = ToolchainEnvironment.ResolveExecutable(hostPath); - string information = await ToolchainEnvironment.CaptureOutputAsync(hostPath, ["--info"], - directory, cancellationToken, + string information = await ToolchainEnvironment.CaptureOutputAsync( + hostPath, + ["--info"], + directory, + cancellationToken, DotNetSdkEnvironment.Create(hostPath, new Dictionary { ["DOTNET_CLI_UI_LANGUAGE"] = "en-US" - })).ConfigureAwait(false); + }) + ).ConfigureAwait(false); string identity = string.Empty; string sdkDirectory = string.Empty; foreach (string outputLine in information.Split('\n')) { string line = outputLine.Trim(); if (identity.Length == 0 && line.StartsWith("Version:", StringComparison.Ordinal)) + { identity = line["Version:".Length..].Trim(); + } if (line.StartsWith("Base Path:", StringComparison.Ordinal)) + { sdkDirectory = line["Base Path:".Length..].Trim(); + } } string numericVersion = identity.Split('-', 2)[0]; if (!Version.TryParse(numericVersion, out _) || !Path.IsPathFullyQualified(sdkDirectory)) + { throw new InvalidOperationException("The managed host did not resolve a valid project SDK identity and base path."); + } string cli = Path.Combine(sdkDirectory, "dotnet.dll"); if (!File.Exists(cli)) + { throw new FileNotFoundException("The selected SDK managed CLI entry assembly is unavailable.", cli); + } return new DotNetSdkDescriptor(hostPath, identity, cli); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs index 973048219..ec6c241c3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs @@ -21,7 +21,7 @@ public sealed class ManagedBuildExecution : IDisposable private readonly BuildCachePublisher m_cache; private readonly string m_workspace; private readonly string m_currentKey; - private readonly string? m_targetId; + private readonly string? m_targetID; private int m_disposed; private ManagedBuildExecution( @@ -32,7 +32,7 @@ private ManagedBuildExecution( BuildCachePublisher cache, string workspace, string currentKey, - string? targetId + string? targetID ) { m_ownership = ownership; this.engineRoot = engineRoot; @@ -41,7 +41,7 @@ private ManagedBuildExecution( m_cache = cache; m_workspace = workspace; m_currentKey = currentKey; - m_targetId = targetId; + m_targetID = targetID; } /// @@ -78,7 +78,9 @@ public ValueTask VerifyAsync(CancellationToken cancellationToken = default) cancellationToken.ThrowIfCancellationRequested(); using FileStream stream = File.OpenRead(input.physicalPath); if (!SHA256.HashData(stream).AsSpan().SequenceEqual(input.hash)) + { throw new InvalidOperationException($"Fixed managed input '{input.logicalPath}' changed during execution."); + } } return ValueTask.CompletedTask; } @@ -97,7 +99,7 @@ public void Dispose() try { using FileLease activity = m_cache.AcquireUseAsync().AsTask().GetAwaiter().GetResult(); - m_cache.Record(m_workspace, m_workspace + ".lock", [], m_currentKey, m_targetId); + m_cache.Record(m_workspace, m_workspace + ".lock", [], m_currentKey, m_targetID); } finally { @@ -111,55 +113,103 @@ internal static async ValueTask CreateAsync( DotNetSdkDescriptor sdk, string project, IReadOnlyDictionary properties, - CancellationToken cancellation + CancellationToken cancellationToken ) { string entry = Path.GetRelativePath(context.engineRoot, project); if (Path.IsPathRooted(entry) || entry == ".." || entry.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { throw new ArgumentException("A managed execution entry must belong to its declared source root.", nameof(project)); - string identity = NativeBuildFingerprint.Create(new[] { "managed-workspace", context.engineRoot, project, - sdk.hostPath, sdk.sdkIdentity, sdk.cliPath }.Concat(properties.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => pair.Key + "=" + pair.Value)), []); + } + string identity = NativeBuildFingerprint.Create( + new[] + { + "managed-workspace", + context.engineRoot, + project, + sdk.hostPath, + sdk.sdkIdentity, + sdk.cliPath + }.Concat( + properties.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value) + ), + [] + ); string workspace = Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces", identity); - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.GetDirectoryName(workspace)!, "managed-workspaces", cache.role, cancellation); - using FileLease cacheUse = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync(Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), workspace + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation).ConfigureAwait(false); + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.GetDirectoryName(workspace)!, + "managed-workspaces", + cache.role, + cancellationToken + ); + using FileLease cacheUse = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); + CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( + Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), + workspace + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { - cache.BeginWorkingDirectory(workspace, workspace + ".lock", - properties.TryGetValue("InnoNativeTarget", out string? selectedTarget) ? selectedTarget : context.toolchain?.targetId, cancellation); + cache.BeginWorkingDirectory( + workspace, + workspace + ".lock", + properties.TryGetValue("InnoNativeTarget", out string? selectedTarget) ? selectedTarget : context.toolchain?.targetID, + cancellationToken + ); string sourceRoot = Path.Combine(workspace, "Sources"); string metadata = Path.Combine(workspace, "inputs.json"); NativeInputSnapshot captured = context.inputState.CaptureRecordedInputs(context.engineRoot); - var selected = captured.entries.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal)) - .Where(input => IsSource(context.engineRoot, input.logicalPath["engine/".Length..])).ToArray(); - var paths = new HashSet(selected.Select(static input => input.logicalPath["engine/".Length..]), StringComparer.Ordinal); + NativeInputSnapshot.Entry[] selected = captured.entries + .Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal)) + .Where(input => IsSource(context.engineRoot, input.logicalPath["engine/".Length..])) + .ToArray(); + var paths = new HashSet( + selected.Select(static input => input.logicalPath["engine/".Length..]), + StringComparer.Ordinal + ); if (File.Exists(metadata)) { string[] previous = JsonSerializer.Deserialize(File.ReadAllText(metadata)) - ?? throw new InvalidDataException("A managed workspace has no owned input inventory."); + ?? throw new InvalidDataException("A managed workspace has no owned input inventory."); foreach (string removed in previous.Where(path => !paths.Contains(path))) { string file = PathBoundary.RequireUnlinkedPath(sourceRoot, PathBoundary.Resolve(sourceRoot, removed)); if (File.Exists(file)) + { File.Delete(file); + } } } - var fixedInputs = new List(); + List fixedInputs = []; foreach (NativeInputSnapshot.Entry input in selected) { string relative = input.logicalPath["engine/".Length..]; string destination = PathBoundary.Resolve(sourceRoot, relative); - await NativeInputMaterializer.CopyAsync(context, input.physicalPath, destination, cancellation).ConfigureAwait(false); - fixedInputs.Add(new(input.logicalPath, destination, input.hash)); + await NativeInputMaterializer.CopyAsync(context, input.physicalPath, destination, cancellationToken).ConfigureAwait(false); + fixedInputs.Add(new NativeInputSnapshot.Entry(input.logicalPath, destination, input.hash)); } string marker = Path.Combine(sourceRoot, "InnoEngine.sln"); if (!File.Exists(marker)) + { File.WriteAllText(marker, "Managed execution source owner.", new UTF8Encoding(false)); + } AtomicFile.WriteAllBytes(metadata, JsonSerializer.SerializeToUtf8Bytes(paths.Order(StringComparer.Ordinal).ToArray())); - return new(ownership, sourceRoot, PathBoundary.Resolve(sourceRoot, entry), fixedInputs.AsReadOnly(), - cache, workspace, project + "/" + context.configuration, - properties.TryGetValue("InnoNativeTarget", out string? targetId) ? targetId : context.toolchain?.targetId); + return new( + ownership, + sourceRoot, + PathBoundary.Resolve(sourceRoot, entry), + fixedInputs.AsReadOnly(), + cache, + workspace, + project + "/" + context.configuration, + properties.TryGetValue("InnoNativeTarget", out string? targetID) ? targetID : context.toolchain?.targetID + ); } catch { @@ -176,9 +226,13 @@ string relative foreach (string segment in relative.Split('/')) { if (segment == ".git" || segment == "artifacts" && directory == root) + { return false; + } if (segment is "bin" or "obj" && Directory.EnumerateFiles(directory, "*.csproj").Any()) + { return false; + } directory = Path.Combine(directory, segment); } return true; diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs index 5da044ee1..a6b7f2449 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using System.Text.Json; using System.Xml.Linq; using Inno.Core.IO; @@ -17,30 +17,73 @@ internal static async ValueTask CaptureAsync( DotNetSdkDescriptor sdk, string project, IReadOnlyDictionary properties, - CancellationToken cancellation + CancellationToken cancellationToken ) { - using ManagedInputEvaluation evaluation = await ManagedInputEvaluation.OpenAsync(context, sdk, project, - properties, cancellation).ConfigureAwait(false); + using ManagedInputEvaluation evaluation = await ManagedInputEvaluation.OpenAsync( + context, + sdk, + project, + properties, + cancellationToken + ).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet", - .. evaluation.properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value)], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment)).ConfigureAwait(false); - _ = await EvaluateAsync(context, sdk, project, evaluation.properties, true, cancellation).ConfigureAwait(false); - XElement captured = await EvaluateAsync(context, sdk, project, evaluation.properties, false, cancellation).ConfigureAwait(false); - var inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath(context.engineRoot, - (string?)element.Attribute("Path") ?? throw new InvalidDataException("A managed input has no physical location."))).ToList(); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "restore", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet", + .. evaluation.properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value) + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment) + ).ConfigureAwait(false); + _ = await EvaluateAsync(context, sdk, project, evaluation.properties, true, cancellationToken).ConfigureAwait(false); + XElement captured = await EvaluateAsync( + context, + sdk, + project, + evaluation.properties, + false, + cancellationToken + ).ConfigureAwait(false); + List inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath( + context.engineRoot, + (string?)element.Attribute("Path") ?? throw new InvalidDataException("A managed input has no physical location.") + )).ToList(); foreach (XElement assets in captured.Elements("Assets")) - CollectPackageInputs(context, assets, inputs, cancellation); - inputs.AddRange(new[] { sdk.hostPath, sdk.cliPath, - Path.Combine(Path.GetDirectoryName(sdk.cliPath)!, "Roslyn", "bincore") } - .Select(path => NativeBuildInput.FromPath(context.engineRoot, path))); - string[] declarations = captured.Elements("Declaration").Select(static element => element.Value) - .Prepend("sdk=" + sdk.sdkIdentity).Prepend("project=" + project).ToArray(); + { + CollectPackageInputs(context, assets, inputs, cancellationToken); + } + inputs.AddRange( + new[] + { + sdk.hostPath, + sdk.cliPath, + Path.Combine(Path.GetDirectoryName(sdk.cliPath)!, "Roslyn", "bincore") + } + .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)) + ); + string[] declarations = captured.Elements("Declaration") + .Select(static element => element.Value) + .Prepend("sdk=" + sdk.sdkIdentity) + .Prepend("project=" + project) + .ToArray(); // Evaluator implementation participates without depending on unrelated tool assembly MVIDs. - declarations = declarations.Append("evaluator=" + ((string?)captured.Attribute("EvaluatorFingerprint") ?? throw new InvalidDataException("The evaluator identity is absent."))).ToArray(); - string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); - evaluation.Complete(cancellation); + declarations = declarations + .Append( + "evaluator=" + + ((string?)captured.Attribute("EvaluatorFingerprint") ?? throw new InvalidDataException("The evaluator identity is absent.")) + ) + .ToArray(); + string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellationToken); + evaluation.Complete(cancellationToken); return new ManagedBuildInputCapture(fingerprint, declarations); } @@ -50,11 +93,20 @@ private static async ValueTask EvaluateAsync( string project, IReadOnlyDictionary properties, bool restoreContributions, - CancellationToken cancellation + CancellationToken cancellationToken ) { string requests = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"); - BuildCacheOwnerCatalog.Register(context.engineRoot, requests, "managed-input-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation); - using ProcessOwnedDirectory requestOwner = await ProcessOwnedDirectory.CreateAsync(requests, cancellation).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + requests, + "managed-input-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); + using ProcessOwnedDirectory requestOwner = await ProcessOwnedDirectory.CreateAsync( + requests, + cancellationToken + ).ConfigureAwait(false); string request = requestOwner.directory; string manifest = Path.Combine(request, "Inputs.xml"); string entry = Path.Combine(request, "Capture.proj"); @@ -62,29 +114,54 @@ CancellationToken cancellation try { using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync( - context, sdk, cancellation).ConfigureAwait(false); + context, + sdk, + cancellationToken + ).ConfigureAwait(false); using Stream template = typeof(ManagedBuildInputReader).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedBuildInputs.targets") - ?? throw new InvalidOperationException("The managed graph evaluator resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedBuildInputs.targets" + ) + ?? throw new InvalidOperationException("The managed graph evaluator resource is absent."); XElement document = XElement.Load(template); using Stream compilerInputs = typeof(ManagedBuildInputReader).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets") - ?? throw new InvalidOperationException("The compiler input target resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets" + ) + ?? throw new InvalidOperationException("The compiler input target resource is absent."); string compilerInputsPath = Path.Combine(request, "CompilerInputs.targets"); using (FileStream destination = File.Create(compilerInputsPath)) - await compilerInputs.CopyToAsync(destination, cancellation).ConfigureAwait(false); - document.AddFirst(new XElement("PropertyGroup", - new XElement("InnoCompilerInputsTargets", compilerInputsPath), - new XElement("InnoInputProject", project), new XElement("InnoRestoreContributions", restoreContributions), new XElement("InnoInputOutput", manifest), - new XElement("InnoInputEvaluator", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")))); - document.Add(new XElement("ItemGroup", properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) - .Select(static pair => new XElement("InnoInputProperty", new XAttribute("Include", pair.Key), - new XElement("Value", pair.Value))))); - await File.WriteAllTextAsync(entry, document.ToString(), cancellation).ConfigureAwait(false); + { + await compilerInputs.CopyToAsync(destination, cancellationToken).ConfigureAwait(false); + } + document.AddFirst( + new XElement( + "PropertyGroup", + new XElement("InnoCompilerInputsTargets", compilerInputsPath), + new XElement("InnoInputProject", project), + new XElement("InnoRestoreContributions", restoreContributions), + new XElement("InnoInputOutput", manifest), + new XElement("InnoInputEvaluator", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")) + ) + ); + document.Add( + new XElement( + "ItemGroup", + properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) + .Select(static pair => new XElement( + "InnoInputProperty", + new XAttribute("Include", pair.Key), + new XElement("Value", pair.Value) + )) + ) + ); + await File.WriteAllTextAsync(entry, document.ToString(), cancellationToken).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "msbuild", entry, "-t:CaptureManagedInputs", "-nologo", "-v:quiet", "-m:1", "-nodeReuse:false"], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment)).ConfigureAwait(false); + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment) + ).ConfigureAwait(false); XElement captured = XElement.Load(manifest); captured.SetAttributeValue("EvaluatorFingerprint", evaluator.fingerprint); return captured; @@ -99,51 +176,71 @@ private static void CollectPackageInputs( NativeBuildContext context, XElement selected, ICollection inputs, - CancellationToken cancellation + CancellationToken cancellationToken ) { string assets = (string)selected.Attribute("Path")!; if (!File.Exists(assets)) + { throw new FileNotFoundException("Managed input planning requires the selected project's restored dependency graph.", assets); + } inputs.Add(NativeBuildInput.FromPath(context.engineRoot, assets)); using JsonDocument document = JsonDocument.Parse(File.ReadAllText(assets)); JsonElement root = document.RootElement; JsonElement targets = root.GetProperty("targets"); string selectedTarget = (string)selected.Attribute("Target")!; if (!targets.TryGetProperty(selectedTarget, out JsonElement target)) - throw new InvalidDataException($"Restored graph '{assets}' does not contain target '{selectedTarget}'. " - + "Available targets: " + string.Join(", ", targets.EnumerateObject().Select(static item => item.Name)) + "."); + { + throw new InvalidDataException( + $"Restored graph '{assets}' does not contain target '{selectedTarget}'. " + + "Available targets: " + string.Join(", ", targets.EnumerateObject().Select(static item => item.Name)) + "." + ); + } string[] folders = root.GetProperty("packageFolders").EnumerateObject().Select(static folder => folder.Name).ToArray(); JsonElement libraries = root.GetProperty("libraries"); foreach (JsonProperty dependency in target.EnumerateObject()) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (dependency.Value.GetProperty("type").GetString() != "package") + { continue; + } JsonElement library = libraries.GetProperty(dependency.Name); string location = library.GetProperty("path").GetString() - ?? throw new InvalidDataException("A restored package has no physical location."); + ?? throw new InvalidDataException("A restored package has no physical location."); string directory = folders.Select(folder => PathBoundary.Resolve(folder, location)).FirstOrDefault(Directory.Exists) - ?? throw new DirectoryNotFoundException($"The restored package '{dependency.Name}' is unavailable."); + ?? throw new DirectoryNotFoundException($"The restored package '{dependency.Name}' is unavailable."); var files = new HashSet(StringComparer.Ordinal); foreach (string group in new[] { "compile", "runtime", "native", "resource", "runtimeTargets", "build", - "buildMultiTargeting", "buildTransitive", "contentFiles" }) + "buildMultiTargeting", "buildTransitive", "contentFiles" } + ) { if (dependency.Value.TryGetProperty(group, out JsonElement entries)) + { foreach (JsonProperty entry in entries.EnumerateObject()) + { files.Add(entry.Name); + } + } + } foreach (JsonElement entry in library.GetProperty("files").EnumerateArray()) { string file = entry.GetString()!; if (file.StartsWith("analyzers/", StringComparison.Ordinal) - && !file.Contains("/vb/", StringComparison.Ordinal) && !file.Contains("/fs/", StringComparison.Ordinal)) + && !file.Contains("/vb/", StringComparison.Ordinal) && !file.Contains("/fs/", StringComparison.Ordinal) + ) { files.Add(file); + } } foreach (string file in files) { if (Path.GetFileName(file) == "_._") + { continue; + } string path = PathBoundary.Resolve(directory, file); if (!File.Exists(path)) + { throw new FileNotFoundException($"The restored package input '{dependency.Name}/{file}' is absent.", path); + } inputs.Add(NativeBuildInput.FromPath(context.engineRoot, path)); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs index 141722a08..ef7dbda36 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -31,7 +32,7 @@ ManagedBuildInputCapture captured m_sdk = sdk; m_project = project; m_properties = properties; - fingerprint = captured.fingerprint; + this.fingerprint = captured.fingerprint; m_declarations = captured.declarations; } @@ -59,6 +60,64 @@ ManagedBuildInputCapture captured public ValueTask CreateExecutionAsync(CancellationToken cancellationToken = default) => ManagedBuildExecution.CreateAsync(m_context, m_sdk, m_project, m_properties, cancellationToken); + /// + /// Re-evaluates the graph and re-reads its current bytes in a fresh verification phase. + /// + /// + /// Cancels evaluation and verification without changing any published output. + /// + /// + /// Completion when the complete current input identity still matches this snapshot. + /// + /// + /// The graph, SDK, source, resource, analyzer or reference inputs changed. + /// + /// + /// Verification was canceled. + /// + public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) + { + ManagedBuildInputCapture current = await ManagedBuildInputReader.CaptureAsync( + m_context.BeginInputVerification("managed-inputs"), + m_sdk, + m_project, + m_properties, + cancellationToken + ).ConfigureAwait(false); + if (current.fingerprint != fingerprint) + { + List changed = []; + foreach (NativeInputSnapshot.Entry input in m_context.inputState.CaptureRecordedInputs(m_context.engineRoot).entries) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!File.Exists(input.physicalPath)) + { + changed.Add(input.logicalPath + " (missing)"); + } + else + { + using FileStream stream = File.OpenRead(input.physicalPath); + if (!SHA256.HashData(stream).AsSpan().SequenceEqual(input.hash)) + { + changed.Add(input.logicalPath); + } + } + } + throw new InvalidOperationException( + "Managed compilation inputs changed after planning; the candidate cannot be accepted. " + + (changed.Count == 0 + ? "Changed declarations: " + string.Join( + "; ", + current.declarations.Except(m_declarations) + .Select(static item => "added " + item) + .Concat(m_declarations.Except(current.declarations).Select(static item => "removed " + item)) + .Take(20) + ) + : "Changed files: " + string.Join(", ", changed)) + ); + } + } + /// /// Evaluates an explicit managed graph using its frozen SDK and hashes its declared compilation inputs. /// @@ -80,10 +139,6 @@ public ValueTask CreateExecutionAsync(CancellationToken c /// /// A snapshot that can be freshly verified after waiting or executing; no Player compilation is performed. /// - /// - /// Restore and evaluation use an owned SDK output layout, independently of ordinary IDE outputs. - /// An explicit ArtifactsPath remains the caller's responsibility, including its concurrency protection. - /// /// /// A required operation, SDK or property collection is null. /// @@ -99,6 +154,10 @@ public ValueTask CreateExecutionAsync(CancellationToken c /// /// Evaluation or hashing was canceled. /// + /// + /// Restore and evaluation use an owned SDK output layout, independently of ordinary IDE outputs. + /// An explicit ArtifactsPath remains the caller's responsibility, including its concurrency protection. + /// public static async ValueTask CaptureAsync( NativeBuildContext context, DotNetSdkDescriptor sdk, @@ -114,52 +173,19 @@ public static async ValueTask CaptureAsync( string selected = new PhysicalPathResolver().Resolve(Path.GetFullPath(project, context.engineRoot)); PathBoundary.RequireContained(context.engineRoot, selected); if (!File.Exists(selected)) - throw new FileNotFoundException("The managed input entry project is absent.", selected); - var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( - properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase)); - ManagedBuildInputCapture identity = await ManagedBuildInputReader.CaptureAsync(context, sdk, selected, frozen, - cancellationToken).ConfigureAwait(false); - return new(context, sdk, selected, frozen, identity); - } - - /// - /// Re-evaluates the graph and re-reads its current bytes in a fresh verification phase. - /// - /// - /// Cancels evaluation and verification without changing any published output. - /// - /// - /// Completion when the complete current input identity still matches this snapshot. - /// - /// - /// The graph, SDK, source, resource, analyzer or reference inputs changed. - /// - /// - /// Verification was canceled. - /// - public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) - { - ManagedBuildInputCapture current = await ManagedBuildInputReader.CaptureAsync( - m_context.BeginInputVerification("managed-inputs"), m_sdk, m_project, m_properties, - cancellationToken).ConfigureAwait(false); - if (current.fingerprint != fingerprint) { - var changed = new List(); - foreach (NativeInputSnapshot.Entry input in m_context.inputState.CaptureRecordedInputs(m_context.engineRoot).entries) - { - cancellationToken.ThrowIfCancellationRequested(); - if (!File.Exists(input.physicalPath)) - changed.Add(input.logicalPath + " (missing)"); - else - { - using FileStream stream = File.OpenRead(input.physicalPath); - if (!SHA256.HashData(stream).AsSpan().SequenceEqual(input.hash)) - changed.Add(input.logicalPath); - } - } - throw new InvalidOperationException("Managed compilation inputs changed after planning; the candidate cannot be accepted. " - + (changed.Count == 0 ? "Changed declarations: " + string.Join("; ", current.declarations.Except(m_declarations).Select(static item => "added " + item) - .Concat(m_declarations.Except(current.declarations).Select(static item => "removed " + item)).Take(20)) : "Changed files: " + string.Join(", ", changed))); + throw new FileNotFoundException("The managed input entry project is absent.", selected); } + var frozen = new ReadOnlyDictionary( + properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) + ); + ManagedBuildInputCapture identity = await ManagedBuildInputReader.CaptureAsync( + context, + sdk, + selected, + frozen, + cancellationToken + ).ConfigureAwait(false); + return new(context, sdk, selected, frozen, identity); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs index 56f1fb5b1..dbfde11f5 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs @@ -14,53 +14,78 @@ internal sealed class ManagedInputEvaluation : IDisposable private readonly CoordinatedFileLease? m_ownership; private readonly BuildCachePublisher? m_cache; private readonly string m_directory; - private readonly string? m_targetId; + private readonly string? m_targetID; private ManagedInputEvaluation( IReadOnlyDictionary properties, CoordinatedFileLease? ownership, BuildCachePublisher? cache, string directory, - string? targetId + string? targetID ) { this.properties = properties; m_ownership = ownership; m_cache = cache; m_directory = directory; - m_targetId = targetId; + m_targetID = targetID; } - /// + /// public void Dispose() => m_ownership?.Dispose(); internal IReadOnlyDictionary properties { get; } + internal void Complete(CancellationToken cancellationToken) + => m_cache?.Record(m_directory, m_directory + ".lock", [], null, m_targetID, cancellationToken); + internal static async ValueTask OpenAsync( NativeBuildContext context, DotNetSdkDescriptor sdk, string project, IReadOnlyDictionary properties, - CancellationToken cancellation + CancellationToken cancellationToken ) { // An explicitly supplied SDK layout remains the caller's owned concurrency boundary. if (properties.Keys.Any(static name => name.Equals("ArtifactsPath", StringComparison.OrdinalIgnoreCase))) + { return new(properties, null, null, string.Empty, null); - string identity = NativeBuildFingerprint.Create(new[] { "managed-input-layout", context.engineRoot, - project, sdk.hostPath, sdk.cliPath, sdk.sdkIdentity } - .Concat(properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) - .Select(static pair => pair.Key + "=" + pair.Value)), []); + } + string identity = NativeBuildFingerprint.Create( + new[] + { + "managed-input-layout", + context.engineRoot, + project, + sdk.hostPath, + sdk.cliPath, + sdk.sdkIdentity + } + .Concat( + properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) + .Select(static pair => pair.Key + "=" + pair.Value) + ), + [] + ); string root = Path.Combine(context.engineRoot, "artifacts", "managed", "evaluations"); string directory = Path.Combine(root, identity); var cache = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, root, "managed-evaluations", cache.role, cancellation); - using FileLease activity = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), - directory + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register(context.engineRoot, root, "managed-evaluations", cache.role, cancellationToken); + using FileLease activity = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); + CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + directory + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { - string? target = properties.TryGetValue("InnoNativeTarget", out string? selected) ? selected : context.toolchain?.targetId; - cache.BeginWorkingDirectory(directory, directory + ".lock", target, cancellation); - var isolated = properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase); + string? target = properties.TryGetValue("InnoNativeTarget", out string? selected) ? selected : context.toolchain?.targetID; + cache.BeginWorkingDirectory(directory, directory + ".lock", target, cancellationToken); + Dictionary isolated = properties.ToDictionary( + static pair => pair.Key, + static pair => pair.Value, + StringComparer.OrdinalIgnoreCase + ); isolated.Add("ArtifactsPath", directory); return new(new ReadOnlyDictionary(isolated), ownership, cache, directory, target); } @@ -70,7 +95,4 @@ CancellationToken cancellation throw; } } - - internal void Complete(CancellationToken cancellation) - => m_cache?.Record(m_directory, m_directory + ".lock", [], null, m_targetId, cancellation); } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs index 3de2eca65..4f77a3f0f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs @@ -11,51 +11,68 @@ namespace Inno.Build.Toolchains; internal static class ManagedInputEvaluatorPreparation { - internal sealed class Result( - string directory, - string fingerprint, - BuildArtifactReadLease reading - ) : IDisposable { - internal string directory { get; } = directory; - internal string fingerprint { get; } = fingerprint; - /// - public void Dispose() => reading.Dispose(); - } - internal static async ValueTask PrepareAsync( NativeBuildContext context, DotNetSdkDescriptor sdk, - CancellationToken cancellation + CancellationToken cancellationToken ) { using Stream source = typeof(ManagedInputEvaluatorPreparation).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedInputGraphTask.cs.txt") - ?? throw new InvalidOperationException("The managed graph evaluator source resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedInputGraphTask.cs.txt" + ) + ?? throw new InvalidOperationException("The managed graph evaluator source resource is absent."); using var reader = new StreamReader(source); - string code = await reader.ReadToEndAsync(cancellation).ConfigureAwait(false); + string code = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); using Stream compilerInputs = typeof(ManagedInputEvaluatorPreparation).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets") - ?? throw new InvalidOperationException("The compiler input target resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets" + ) + ?? throw new InvalidOperationException("The compiler input target resource is absent."); using var compilerInputsReader = new StreamReader(compilerInputs); - string compilerInputsCode = await compilerInputsReader.ReadToEndAsync(cancellation).ConfigureAwait(false); + string compilerInputsCode = await compilerInputsReader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); string sdkRoot = Path.GetDirectoryName(sdk.cliPath)!; - string[] assemblies = ["Microsoft.Build.dll", "Microsoft.Build.Framework.dll", "Microsoft.Build.Utilities.Core.dll", "NuGet.Frameworks.dll"]; + string[] assemblies = + [ + "Microsoft.Build.dll", + "Microsoft.Build.Framework.dll", + "Microsoft.Build.Utilities.Core.dll", + "NuGet.Frameworks.dll" + ]; NativeBuildInput[] inputs = assemblies.Select(name => NativeBuildInput.FromPath(context.engineRoot, Path.Combine(sdkRoot, name))) - .Concat(new[] { sdk.cliPath, sdk.hostPath, Path.Combine(sdkRoot, "Roslyn", "bincore"), - Path.Combine(sdkRoot, "Microsoft.NETCoreSdk.BundledVersions.props") } - .Select(path => NativeBuildInput.FromPath(context.engineRoot, path))).ToArray(); + .Concat( + new[] + { + sdk.cliPath, + sdk.hostPath, + Path.Combine(sdkRoot, "Roslyn", "bincore"), + Path.Combine(sdkRoot, "Microsoft.NETCoreSdk.BundledVersions.props") + } + .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)) + ) + .ToArray(); string[] declarations = ["managed-input-evaluator", "net10.0", "Release", sdk.sdkIdentity, code, compilerInputsCode]; - string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); + string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellationToken); string directory = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators", fingerprint); var cache = new BuildCachePublisher(Path.GetDirectoryName(directory)!, BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.GetDirectoryName(directory)!, "managed-evaluators", cache.role, cancellation); - using FileLease activity = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - BuildArtifactReadLease? existing = await BuildArtifactReadLease.TryAcquireAsync(directory, Path.GetDirectoryName(directory)!, fingerprint, - ["Outputs"], context, cancellation).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.GetDirectoryName(directory)!, + "managed-evaluators", + cache.role, + cancellationToken + ); + using FileLease activity = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease? existing = await BuildArtifactReadLease.TryAcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + fingerprint, + ["Outputs"], + context, + cancellationToken + ).ConfigureAwait(false); if (existing is not null) { try { - cache.Record(directory, directory + ".read.lock", [], sdk.sdkIdentity, null, cancellation); + cache.Record(directory, directory + ".read.lock", [], sdk.sdkIdentity, null, cancellationToken); return new(directory, fingerprint, existing); } catch @@ -64,42 +81,91 @@ CancellationToken cancellation throw; } } - using (FileLease generation = await FileLease.AcquireAsync(directory + ".generation.lock", - Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)) - { + using (FileLease generation = await FileLease.AcquireAsync( + directory + ".generation.lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false) + ) { Verify("managed-evaluator-lock"); if (!BuildArtifactManifest.IsComplete(directory, fingerprint, ["Outputs"], context)) { - using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(directory)!, cancellation).ConfigureAwait(false); + using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync( + Path.GetDirectoryName(directory)!, + cancellationToken + ).ConfigureAwait(false); string candidate = candidateOwner.directory; try { Directory.CreateDirectory(candidate); string project = Path.Combine(candidate, "ManagedInputGraphTask.csproj"); - var definition = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("LangVersion", "14.0"), new XElement("OutputType", "Library"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "disable"), - new XElement("ImportDirectoryBuildProps", "false"), new XElement("ImportDirectoryBuildTargets", "false"), - new XElement("GenerateAssemblyInfo", "false"), new XElement("DebugType", "None"), - new XElement("DebugSymbols", "false")), - new XElement("ItemGroup", assemblies.Select(name => new XElement("Reference", - new XAttribute("Include", Path.GetFileNameWithoutExtension(name)), - new XElement("HintPath", Path.Combine(sdkRoot, name)), new XElement("Private", "false"))))); - await File.WriteAllTextAsync(project, definition.ToString(), cancellation).ConfigureAwait(false); - await File.WriteAllTextAsync(Path.Combine(candidate, "ManagedInputGraphTask.cs"), code, cancellation).ConfigureAwait(false); + var definition = new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("OutputType", "Library"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "disable"), + new XElement("ImportDirectoryBuildProps", "false"), + new XElement("ImportDirectoryBuildTargets", "false"), + new XElement("GenerateAssemblyInfo", "false"), + new XElement("DebugType", "None"), + new XElement("DebugSymbols", "false") + ), + new XElement( + "ItemGroup", + assemblies.Select(name => new XElement( + "Reference", + new XAttribute("Include", Path.GetFileNameWithoutExtension(name)), + new XElement("HintPath", Path.Combine(sdkRoot, name)), + new XElement("Private", "false") + )) + ) + ); + await File.WriteAllTextAsync(project, definition.ToString(), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(candidate, "ManagedInputGraphTask.cs"), + code, + cancellationToken + ).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "build", project, "--configuration", "Release", "--output", Path.Combine(candidate, "Outputs"), - "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath)).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "build", + project, + "--configuration", + "Release", + "--output", + Path.Combine(candidate, "Outputs"), + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet" + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath) + ).ConfigureAwait(false); Verify("managed-evaluator-build"); File.Delete(project); File.Delete(Path.Combine(candidate, "ManagedInputGraphTask.cs")); string intermediate = Path.Combine(candidate, "obj"); if (Directory.Exists(intermediate)) + { Directory.Delete(intermediate, recursive: true); + } BuildArtifactManifest.Write(candidate, fingerprint, ["Outputs"], context); - using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync(directory, Path.GetDirectoryName(directory)!, cancellation).ConfigureAwait(false); + using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + cancellationToken + ).ConfigureAwait(false); try { AtomicDirectory.Install(candidate, directory); @@ -115,11 +181,17 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, } } } - BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(directory, Path.GetDirectoryName(directory)!, - fingerprint, ["Outputs"], cancellation, context).ConfigureAwait(false); + BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + fingerprint, + ["Outputs"], + context, + cancellationToken + ).ConfigureAwait(false); try { - cache.Record(directory, directory + ".read.lock", [], sdk.sdkIdentity, null, cancellation); + cache.Record(directory, directory + ".read.lock", [], sdk.sdkIdentity, null, cancellationToken); return new(directory, fingerprint, reading); } catch @@ -130,8 +202,28 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, void Verify(string phase) { - if (NativeBuildFingerprint.Create(context.BeginInputVerification(phase), declarations, inputs, cancellation) != fingerprint) + if (NativeBuildFingerprint.Create( + context.BeginInputVerification(phase), + declarations, + inputs, + cancellationToken + ) != fingerprint + ) { throw new InvalidOperationException("The managed evaluator's selected SDK changed; no candidate was published."); + } } } + + internal sealed class Result( + string directory, + string fingerprint, + BuildArtifactReadLease reading + ) : IDisposable + { + /// + public void Dispose() => reading.Dispose(); + + internal string directory { get; } = directory; + internal string fingerprint { get; } = fingerprint; + } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs index 67472809a..3296f50d7 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs @@ -29,12 +29,12 @@ public static class ManagedProjectGraphCapture /// /// The complete evaluation properties, including configuration and any explicit output owner. /// - /// - /// Cancels preparation or evaluation and drains child processes before releasing owners. - /// /// /// Resolves compile references and implicit symbols after restore without building project references or native products. /// + /// + /// Cancels preparation or evaluation and drains child processes before releasing owners. + /// /// /// A JSON array of SDK snapshots. An empty request or failed evaluation throws instead of returning partial evidence. /// @@ -55,12 +55,16 @@ public static async Task CaptureAsync( string dotnetHost, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken = default, - bool resolveReferences = false + bool resolveReferences = false, + CancellationToken cancellationToken = default ) { ValidateProjects(projects, properties); - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(dotnetHost, engineRoot, cancellationToken).ConfigureAwait(false); - return await EvaluateAsync(engineRoot, sdk, projects, properties, cancellationToken, resolveReferences).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( + dotnetHost, + engineRoot, + cancellationToken + ).ConfigureAwait(false); + return await EvaluateAsync(engineRoot, sdk, projects, properties, resolveReferences, cancellationToken).ConfigureAwait(false); } /// @@ -78,12 +82,12 @@ public static async Task CaptureAsync( /// /// The complete evaluation properties, including configuration and any explicit output owner. /// - /// - /// Cancels preparation or evaluation and drains child processes before releasing owners. - /// /// /// Resolves compile references and implicit symbols after restore without building project references or native products. /// + /// + /// Cancels preparation or evaluation and drains child processes before releasing owners. + /// /// /// A JSON array of SDK snapshots. An empty request or failed evaluation throws instead of returning partial evidence. /// @@ -104,12 +108,12 @@ public static async Task CaptureSelectedAsync( DotNetSdkDescriptor sdk, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken = default, - bool resolveReferences = false + bool resolveReferences = false, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(sdk); ValidateProjects(projects, properties); - return await EvaluateAsync(engineRoot, sdk, projects, properties, cancellationToken, resolveReferences).ConfigureAwait(false); + return await EvaluateAsync(engineRoot, sdk, projects, properties, resolveReferences, cancellationToken).ConfigureAwait(false); } private static void ValidateProjects( @@ -119,10 +123,16 @@ IReadOnlyDictionary properties ArgumentNullException.ThrowIfNull(projects); ArgumentNullException.ThrowIfNull(properties); if (projects.Count == 0 || projects.Any(static project => !Path.IsPathFullyQualified(project))) + { throw new ArgumentException("SDK capture requires nonempty absolute project paths.", nameof(projects)); + } foreach (string project in projects) + { if (!File.Exists(project)) + { throw new FileNotFoundException("The SDK project input is missing.", project); + } + } } private static async Task EvaluateAsync( @@ -130,49 +140,103 @@ private static async Task EvaluateAsync( DotNetSdkDescriptor sdk, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken, - bool resolveReferences + bool resolveReferences, + CancellationToken cancellationToken ) { var context = new NativeBuildContext(engineRoot, "debug"); - using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync(context, sdk, cancellationToken).ConfigureAwait(false); + using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync( + context, + sdk, + cancellationToken + ).ConfigureAwait(false); string requests = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"); - BuildCacheOwnerCatalog.Register(context.engineRoot, requests, "managed-input-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + requests, + "managed-input-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); using ProcessOwnedDirectory request = await ProcessOwnedDirectory.CreateAsync(requests, cancellationToken).ConfigureAwait(false); string output = Path.Combine(request.directory, "Graph.json"); string entry = Path.Combine(request.directory, "Graph.proj"); string compilerTargets = Path.Combine(request.directory, "RepositoryReferences.targets"); - var compiler = new XElement("Project", - new XElement("Import", new XAttribute("Project", "$(InnoOriginalCustomAfterMicrosoftCommonTargets)"), - new XAttribute("Condition", "'$(InnoOriginalCustomAfterMicrosoftCommonTargets)' != '' and Exists('$(InnoOriginalCustomAfterMicrosoftCommonTargets)')")), - new XElement("Target", new XAttribute("Name", "KeepInnoReferenceCaptureReadOnly"), + var compiler = new XElement( + "Project", + new XElement( + "Import", + new XAttribute("Project", "$(InnoOriginalCustomAfterMicrosoftCommonTargets)"), + new XAttribute( + "Condition", + "'$(InnoOriginalCustomAfterMicrosoftCommonTargets)' != '' and Exists('$(InnoOriginalCustomAfterMicrosoftCommonTargets)')" + ) + ), + new XElement( + "Target", + new XAttribute("Name", "KeepInnoReferenceCaptureReadOnly"), new XAttribute("BeforeTargets", "ResolveProjectReferences"), - new XElement("PropertyGroup", new XElement("BuildProjectReferences", "false"))), - new XElement("Target", new XAttribute("Name", "CaptureInnoRepositoryReferences"), + new XElement("PropertyGroup", new XElement("BuildProjectReferences", "false")) + ), + new XElement( + "Target", + new XAttribute("Name", "CaptureInnoRepositoryReferences"), new XAttribute("DependsOnTargets", "ResolveReferences;AddImplicitDefineConstants"), new XAttribute("Returns", "@(_InnoRepositoryCapture)"), - new XElement("ItemGroup", - new[] { "ReferencePath", "Compile" }.Select(name => new XElement("_InnoRepositoryCapture", - new XAttribute("Include", name == "Compile" ? "@(Compile->'%(FullPath)')" : "@(ReferencePath)"), new XElement("CaptureKind", name))), + new XElement( + "ItemGroup", + new[] { "ReferencePath", "Compile" }.Select(name => new XElement( + "_InnoRepositoryCapture", + new XAttribute("Include", name == "Compile" ? "@(Compile->'%(FullPath)')" : "@(ReferencePath)"), + new XElement("CaptureKind", name) + )), new[] { "TargetPath", "DefineConstants", "LangVersion", "Nullable", "AllowUnsafeBlocks" }.Select(name => - new XElement("_InnoRepositoryCapture", new XAttribute("Include", name), - new XElement("CaptureKind", "Property"), new XElement("Value", "$(" + name + ")")))))); - var document = new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", "Inno.Build.Toolchains.ManagedInputGraphTask"), - new XAttribute("AssemblyFile", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll"))), - new XElement("ItemGroup", + new XElement( + "_InnoRepositoryCapture", + new XAttribute("Include", name), + new XElement("CaptureKind", "Property"), + new XElement("Value", "$(" + name + ")") + )) + ) + ) + ); + var document = new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", "Inno.Build.Toolchains.ManagedInputGraphTask"), + new XAttribute("AssemblyFile", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")) + ), + new XElement( + "ItemGroup", projects.Select(project => new XElement("RepositoryProject", new XAttribute("Include", project))), - properties.Select(pair => new XElement("InputProperty", new XAttribute("Include", pair.Key), new XElement("Value", pair.Value)))), - new XElement("Target", new XAttribute("Name", "Capture"), - new XElement("Inno.Build.Toolchains.ManagedInputGraphTask", new XAttribute("ProjectPath", projects[0]), - new XAttribute("OutputPath", output), new XAttribute("CompilerInputsTargets", compilerTargets), + properties.Select( + pair => new XElement("InputProperty", new XAttribute("Include", pair.Key), new XElement("Value", pair.Value)) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "Capture"), + new XElement( + "Inno.Build.Toolchains.ManagedInputGraphTask", + new XAttribute("ProjectPath", projects[0]), + new XAttribute("OutputPath", output), + new XAttribute("CompilerInputsTargets", compilerTargets), new XAttribute("ResolveRepositoryReferences", resolveReferences), - new XAttribute("RepositoryProjects", "@(RepositoryProject)"), new XAttribute("Properties", "@(InputProperty)")))); + new XAttribute("RepositoryProjects", "@(RepositoryProject)"), + new XAttribute("Properties", "@(InputProperty)") + ) + ) + ); Directory.CreateDirectory(request.directory); await File.WriteAllTextAsync(compilerTargets, compiler.ToString(), cancellationToken).ConfigureAwait(false); await File.WriteAllTextAsync(entry, document.ToString(), cancellationToken).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "msbuild", entry, "-t:Capture", "-nologo", "-v:minimal", "-m:1", "-nodeReuse:false"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(sdk.hostPath)).ConfigureAwait(false); + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath) + ).ConfigureAwait(false); return await File.ReadAllTextAsync(output, cancellationToken).ConfigureAwait(false); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs index a6b4ac8b9..7ef7987fb 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs @@ -12,7 +12,7 @@ namespace Inno.Build.Toolchains; /// public sealed class ComponentNativeProductExecutor : INativeProductExecutor { - /// + /// public async Task BuildAsync( NativeBuildContext context, ProductNativeBuildPlan plan, @@ -22,28 +22,41 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(plan); cancellationToken.ThrowIfCancellationRequested(); if (plan.steps.Any(static step => step.build is null)) + { throw new NotSupportedException("This closure requires its platform's static aggregate executor."); + } NativeToolchainSelection toolchain = context.RequireToolchain(); plan.CreateRecipes(context); - NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync(context, - plan.steps.Select(static step => step.component).ToArray(), cancellationToken, + NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync( + context, + plan.steps.Select(static step => step.component).ToArray(), + cancellationToken, plan.steps.Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)).ConfigureAwait(false); + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ).ConfigureAwait(false); var completed = new Dictionary(StringComparer.Ordinal); var borrowed = new ReadOnlyDictionary(completed); try { context = context.WithBindings(bindings); if (await ProductNativeCacheLookup.TryAcquireAsync(context, plan.steps, cancellationToken).ConfigureAwait(false) - is IReadOnlyList cached) + is IReadOnlyList cached + ) { return new ProductNativeBuildResult(cached, bindings); + } foreach (ProductNativeBuildStep step in plan.steps) { cancellationToken.ThrowIfCancellationRequested(); - NativeBuildContext configured = step.configuration is string configuration ? context.WithConfiguration(configuration) : context; - NativeBuildProduct product = await step.build!(configured.WithComponentOptions(step.component, step.options), borrowed, cancellationToken).ConfigureAwait(false); - if (product.component != step.id || product.targetId != toolchain.targetId) + NativeBuildContext configured = step.configuration is string configuration + ? context.WithConfiguration(configuration) + : context; + NativeBuildProduct product = await step.build!( + configured.WithComponentOptions(step.component, step.options), + borrowed, + cancellationToken + ).ConfigureAwait(false); + if (product.component != step.id || product.targetID != toolchain.targetID) { product.Dispose(); throw new InvalidOperationException($"Native step '{step.id}' returned a foreign component or target."); @@ -60,11 +73,13 @@ CancellationToken cancellationToken } catch (Exception releaseFailure) { - throw new AggregateException("Native preparation failed and reading ownership could not be completely released.", - buildFailure, releaseFailure); + throw new AggregateException( + "Native preparation failed and reading ownership could not be completely released.", + buildFailure, + releaseFailure + ); } throw; } } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/INativeToolchainProvider.cs b/build/toolchains/Inno.Build.Toolchains/Native/INativeToolchainProvider.cs index 492568df3..04da38d71 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/INativeToolchainProvider.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/INativeToolchainProvider.cs @@ -17,7 +17,7 @@ public interface INativeToolchainProvider /// /// The explicitly declared execution host, independent of the target. /// - /// + /// /// The exact requested target; unsupported combinations must fail. /// /// @@ -29,7 +29,7 @@ public interface INativeToolchainProvider ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, - string targetId, + string targetID, CancellationToken cancellationToken ); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs index 785d72361..06a5a36af 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs @@ -7,29 +7,6 @@ namespace Inno.Build.Toolchains; -/// -/// Describes the link or deployment role explicitly assigned by a native producer. -/// -public enum NativeArtifactRole -{ - /// - /// A library loaded by the runtime. - /// - SharedLibrary, - /// - /// A separate linker input referring to a shared library. - /// - ImportLibrary, - /// - /// An archive linked into the final executable. - /// - StaticArchive, - /// - /// A tool, header or other supporting payload. - /// - SupportFile -} - /// /// Identifies one exact output and its producer-declared role. /// @@ -38,7 +15,7 @@ public sealed record NativeArtifact /// /// Captures an output independently of platform suffix conventions. /// - /// + /// /// The unique producer-owned output identity. /// /// @@ -51,14 +28,16 @@ public sealed record NativeArtifact /// The identity, path or role is invalid. /// public NativeArtifact( - string logicalId, + string logicalID, string file, NativeArtifactRole role ) { - ArgumentException.ThrowIfNullOrWhiteSpace(logicalId); + ArgumentException.ThrowIfNullOrWhiteSpace(logicalID); if (!Path.IsPathFullyQualified(file) || !Enum.IsDefined(role)) + { throw new ArgumentException("Native outputs require an absolute file and an explicit supported role."); - this.logicalId = logicalId; + } + this.logicalID = logicalID; this.file = Path.GetFullPath(file); this.role = role; } @@ -66,11 +45,13 @@ NativeArtifactRole role /// /// Gets the producer-owned output identity. /// - public string logicalId { get; } + public string logicalID { get; } + /// /// Gets the exact absolute output path. /// public string file { get; } + /// /// Gets the explicit link or deployment role. /// @@ -81,25 +62,50 @@ internal static void Write( IReadOnlyList artifacts ) { string output = Path.Combine(directory, "Outputs"); - if (artifacts.Count == 0 || artifacts.Select(static item => item.logicalId).Distinct(StringComparer.Ordinal).Count() != artifacts.Count) + if (artifacts.Count == 0 + || artifacts.Select(static item => item.logicalID).Distinct(StringComparer.Ordinal).Count() != artifacts.Count + ) { throw new InvalidDataException("A Native output inventory must contain unique logical identities."); + } foreach (NativeArtifact artifact in artifacts) + { PathBoundary.RequireUnlinkedPath(output, artifact.file); - if (!artifacts.Select(static artifact => artifact.file).ToHashSet(StringComparer.Ordinal) - .SetEquals(PathBoundary.EnumerateFiles(output))) + } + if (!artifacts.Select(static artifact => artifact.file) + .ToHashSet(StringComparer.Ordinal) + .SetEquals(PathBoundary.EnumerateFiles(output)) + ) { throw new InvalidDataException("The declared Native output inventory must match every produced file exactly."); + } Directory.CreateDirectory(Path.Combine(directory, "Metadata")); - File.WriteAllBytes(Path.Combine(directory, "Metadata", "artifacts.json"), JsonSerializer.SerializeToUtf8Bytes( - artifacts.Select(artifact => new Entry(artifact.logicalId, Path.GetRelativePath(output, artifact.file).Replace('\\', '/'), artifact.role)).ToArray())); + File.WriteAllBytes( + Path.Combine(directory, "Metadata", "artifacts.json"), + JsonSerializer.SerializeToUtf8Bytes( + artifacts + .Select( + artifact => new Entry( + artifact.logicalID, + Path.GetRelativePath(output, artifact.file).Replace('\\', '/'), + artifact.role + ) + ) + .ToArray() + ) + ); } internal static IReadOnlyList Read(string directory) { Entry[] entries = JsonSerializer.Deserialize(File.ReadAllBytes(Path.Combine(directory, "Metadata", "artifacts.json"))) - ?? throw new InvalidDataException("The Native output inventory is absent."); + ?? throw new InvalidDataException("The Native output inventory is absent."); string output = Path.Combine(directory, "Outputs"); - return Array.AsReadOnly(entries.Select(entry => new NativeArtifact(entry.logicalId, - PathBoundary.Resolve(output, entry.path), entry.role)).ToArray()); + return Array.AsReadOnly( + entries.Select(entry => new NativeArtifact( + entry.logicalId, + PathBoundary.Resolve(output, entry.path), + entry.role + )).ToArray() + ); } private sealed record Entry( @@ -108,3 +114,26 @@ private sealed record Entry( NativeArtifactRole role ); } + +/// +/// Describes the link or deployment role explicitly assigned by a native producer. +/// +public enum NativeArtifactRole +{ + /// + /// A library loaded by the runtime. + /// + SharedLibrary, + /// + /// A separate linker input referring to a shared library. + /// + ImportLibrary, + /// + /// An archive linked into the final executable. + /// + StaticArchive, + /// + /// A tool, header or other supporting payload. + /// + SupportFile +} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs index 29ccbcf06..8b3ced933 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs @@ -27,12 +27,12 @@ public static class NativeArtifactPublisher /// Producer receiving an identity-scoped context, private output directory and cancellation token. /// It must await all work and validate required outputs before returning. /// - /// - /// Cancels ownership acquisition or candidate preparation before publication. - /// /// /// The producer's exact role inventory, or null for generic support payloads. /// + /// + /// Cancels ownership acquisition or candidate preparation before publication. + /// /// /// A complete native product with an exact, read-only output closure. /// @@ -52,8 +52,8 @@ public static async Task PublishAsync( NativeBuildContext context, NativeBuildRecipe recipe, Func build, - CancellationToken cancellationToken = default, - Func>? describeOutputs = null + Func>? describeOutputs = null, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(recipe); @@ -61,64 +61,119 @@ public static async Task PublishAsync( cancellationToken.ThrowIfCancellationRequested(); NativeComponentDescriptor owner = recipe.owner; NativeBindingGenerationDescriptor? bindingGeneration = owner.bindingDefinition is null - ? null : context.RequireBindings(owner); + ? null + : context.RequireBindings(owner); if (bindingGeneration is not null) + { recipe = recipe.WithBindingGeneration(context.engineRoot, bindingGeneration); + } string component = recipe.component; - string targetId = recipe.targetId; + string targetID = recipe.targetID; NativeInputSnapshot snapshot = context.inputState.CaptureInitial(recipe.inputs, cancellationToken); string fingerprint = NativeBuildFingerprint.Create(recipe.declarations, snapshot); string workspaceIdentity = NativeWorkspaceIdentity.Create(context, recipe, snapshot); - NativeBuildContext scoped = context.WithIdentity(owner, targetId, workspaceIdentity); + NativeBuildContext scoped = context.WithIdentity(owner, targetID, workspaceIdentity); string intermediate = scoped.GetNativeBuildRoot(owner); - string destination = Path.Combine(context.engineRoot, "artifacts", "native", component, targetId, fingerprint); - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(context.engineRoot, "artifacts", "native"), "native", cache.role, cancellationToken); + string destination = Path.Combine(context.engineRoot, "artifacts", "native", component, targetID, fingerprint); + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(context.engineRoot, "artifacts", "native"), + "native", + cache.role, + cancellationToken + ); using FileLease cacheUse = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); - var workspaces = new BuildCachePublisher(Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), - "workspace:" + owner.toolchainProject, workspaces.role, cancellationToken); + var workspaces = new BuildCachePublisher( + Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), + BuildCacheArtifactRole.ReusableWorkspace + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), + "workspace:" + owner.toolchainProject, + workspaces.role, + cancellationToken + ); using FileLease workspaceUse = await workspaces.AcquireUseAsync(cancellationToken).ConfigureAwait(false); - using FileLease ownership = await FileLease.AcquireAsync(intermediate + ".lock", - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await FileLease.AcquireAsync( + intermediate + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - if (NativeBuildFingerprint.Create(context.BeginInputVerification("native-lock:" + component), - recipe.declarations, recipe.inputs, cancellationToken) != fingerprint) - throw new InvalidOperationException($"Native inputs for '{component}' changed while waiting for ownership."); - workspaces.BeginWorkingDirectory(intermediate, intermediate + ".lock", targetId, cancellationToken); - AtomicFile.WriteAllBytes(Path.Combine(intermediate, "recipe.json"), JsonSerializer.SerializeToUtf8Bytes(new - { - component, - targetId, - context.configuration, - workspaceIdentity, - artifactFingerprint = fingerprint, - recipe.owner.nativeProject, - recipe.owner.toolchainProject, + if (NativeBuildFingerprint.Create( + context.BeginInputVerification("native-lock:" + component), recipe.declarations, - inputs = snapshot.entries.Select(static entry => new + recipe.inputs, + cancellationToken + ) != fingerprint + ) { + throw new InvalidOperationException($"Native inputs for '{component}' changed while waiting for ownership."); + } + workspaces.BeginWorkingDirectory(intermediate, intermediate + ".lock", targetID, cancellationToken); + AtomicFile.WriteAllBytes( + Path.Combine(intermediate, "recipe.json"), + JsonSerializer.SerializeToUtf8Bytes(new { - entry.logicalPath, - hash = Convert.ToHexStringLower(entry.hash) + component, + targetID, + context.configuration, + workspaceIdentity, + artifactFingerprint = fingerprint, + recipe.owner.nativeProject, + recipe.owner.toolchainProject, + recipe.declarations, + inputs = snapshot.entries.Select(static entry => new + { + entry.logicalPath, + hash = Convert.ToHexStringLower(entry.hash) + }) }) - })); + ); BuildArtifactReadLease? cached = await BuildArtifactReadLease.TryAcquireAsync( - destination, Path.Combine(context.engineRoot, "artifacts", "native"), fingerprint, ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false); + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + fingerprint, + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false); if (cached is not null) { Record(cached); - return new(component, targetId, fingerprint, destination, bindingGeneration, context.toolchain?.linkPlan.sharedLibraryExtension, cached); + return new( + component, + targetID, + fingerprint, + destination, + bindingGeneration, + context.toolchain?.linkPlan.sharedLibraryExtension, + cached + ); } if (Directory.Exists(destination)) - Console.Error.WriteLine($"Rejected incomplete or modified Native cache '{destination}'; it remains isolated from consumers until verified replacement succeeds."); + { + Console.Error.WriteLine( + $"Rejected incomplete or modified Native cache '{destination}'; it remains isolated from consumers until verified replacement succeeds." + ); + } void Record(BuildArtifactReadLease reading) { try { - cache.Record(destination, destination + ".read.lock", + cache.Record( + destination, + destination + ".read.lock", bindingGeneration is { artifactDirectory.Length: > 0 } ? [bindingGeneration.artifactDirectory] : [], - component + "/" + targetId + "/" + context.configuration, targetId, cancellationToken); + component + "/" + targetID + "/" + context.configuration, + targetID, + cancellationToken + ); } catch { @@ -127,7 +182,10 @@ void Record(BuildArtifactReadLease reading) } } - using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(context.engineRoot, "artifacts", "native"), cancellationToken).ConfigureAwait(false); + using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(context.engineRoot, "artifacts", "native"), + cancellationToken + ).ConfigureAwait(false); string staging = candidateOwner.directory; string output = Path.Combine(staging, "Outputs"); Directory.CreateDirectory(output); @@ -135,25 +193,56 @@ void Record(BuildArtifactReadLease reading) { IToolchainWorkspaceProvider execution = context.toolchain?.host.services.workspaces ?? new PhysicalToolchainWorkspaceProvider(); using (ToolchainWorkingDirectory workspace = await execution.OpenAsync( - intermediate, cancellationToken).ConfigureAwait(false)) - await build(scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(snapshot), - output, cancellationToken).ConfigureAwait(false); + intermediate, + cancellationToken + ).ConfigureAwait(false) + ) { + await build( + scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(snapshot), + output, + cancellationToken + ).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); if (!PathBoundary.EnumerateFiles(output).Any()) + { throw new InvalidOperationException($"Native component '{component}' produced no output files."); - if (NativeBuildFingerprint.Create(context.BeginInputVerification("native-build:" + component), - recipe.declarations, recipe.inputs, cancellationToken) != fingerprint) - throw new InvalidOperationException($"Native inputs for '{component}' changed during preparation; the candidate was not published."); + } + if (NativeBuildFingerprint.Create( + context.BeginInputVerification("native-build:" + component), + recipe.declarations, + recipe.inputs, + cancellationToken + ) != fingerprint + ) { + throw new InvalidOperationException( + $"Native inputs for '{component}' changed during preparation; the candidate was not published." + ); + } // Validate compiler workspace links before publishing the immutable candidate. - workspaces.Record(intermediate, intermediate + ".lock", [], - targetId + "/" + context.configuration, targetId, cancellationToken); - NativeArtifact.Write(staging, describeOutputs?.Invoke(scoped, output) - ?? PathBoundary.EnumerateFiles(output).Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, NativeArtifactRole.SupportFile)).ToArray()); + workspaces.Record( + intermediate, + intermediate + ".lock", + [], + targetID + "/" + context.configuration, + targetID, + cancellationToken + ); + NativeArtifact.Write( + staging, + describeOutputs?.Invoke(scoped, output) + ?? PathBoundary.EnumerateFiles(output) + .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, NativeArtifactRole.SupportFile)) + .ToArray() + ); BuildArtifactManifest.Write(staging, fingerprint, ["Outputs", "Metadata"], context); cancellationToken.ThrowIfCancellationRequested(); - using (BuildArtifactWriteLease publication = await BuildArtifactWriteLease.AcquireAsync(destination, Path.Combine(context.engineRoot, "artifacts", "native"), - cancellationToken).ConfigureAwait(false)) - { + using (BuildArtifactWriteLease publication = await BuildArtifactWriteLease.AcquireAsync( + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + cancellationToken + ).ConfigureAwait(false) + ) { try { AtomicDirectory.Install(staging, destination); @@ -163,15 +252,29 @@ await build(scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(sna Console.Error.WriteLine(cleanupFailure.Message); } } - BuildArtifactReadLease reading = await BuildArtifactReadLease.TryAcquireAsync(destination, Path.Combine(context.engineRoot, "artifacts", "native"), fingerprint, ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false) + BuildArtifactReadLease reading = await BuildArtifactReadLease.TryAcquireAsync( + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + fingerprint, + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false) ?? throw new InvalidDataException("The published Native artifact changed before reading ownership was acquired."); Record(reading); - return new(component, targetId, fingerprint, destination, bindingGeneration, context.toolchain?.linkPlan.sharedLibraryExtension, reading); + return new( + component, + targetID, + fingerprint, + destination, + bindingGeneration, + context.toolchain?.linkPlan.sharedLibraryExtension, + reading + ); } finally { candidateOwner.Dispose(); } } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs index 16fa3b123..a34a8687d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -18,14 +19,18 @@ internal static void Write( CancellationToken cancellationToken ) { var text = new StringBuilder("include_guard(GLOBAL)\nfunction(inno_apply_binding target owner)\n"); - foreach (var entry in context.selectedBindings.Where(entry => target is null || entry.Key == owner.nativeProject) - .OrderBy(static entry => entry.Key, StringComparer.Ordinal)) - { + foreach (KeyValuePair entry in context.selectedBindings + .Where(entry => target is null || entry.Key == owner.nativeProject) + .OrderBy(static entry => entry.Key, StringComparer.Ordinal) + ) { NativeBindingGenerationDescriptor generation = entry.Value; if (generation.nativeDirectory.Length == 0) + { continue; + } NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); - string ResolveRoot(string id) => sources.ResolvePath(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, id)); + string ResolveRoot(string id) + => sources.ResolvePath(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, id)); compilation.VerifyInputs(ResolveRoot, cancellationToken); text.AppendLine("if(owner STREQUAL " + Literal(Path.GetFileNameWithoutExtension(entry.Key)) + ")"); NativeBindingSourceFile[] units = compilation.files.Where(static file => file.compile).ToArray(); @@ -41,47 +46,81 @@ CancellationToken cancellationToken text.AppendLine("target_sources(${binding_target} PRIVATE " + source + ")"); } foreach (string define in compilation.defines) + { text.AppendLine("target_compile_definitions(${binding_target} PRIVATE " + Literal(define) + ")"); + } foreach (NativeBindingIncludeDirectory include in compilation.includeDirectories) { NativeBindingSourceRoot root = compilation.roots.Single(root => root.id == include.rootId); // SDK search roots are requirements of the selected compiler, not duplicate -isystem flags. if (!root.frozen && include.system && !include.framework) + { continue; - string directory = include.relativePath.Length == 0 ? ResolveRoot(include.rootId) - : sources.ResolvePath(PathBoundary.Resolve(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, include.rootId), include.relativePath)); + } + string directory = include.relativePath.Length == 0 + ? ResolveRoot(include.rootId) + : sources.ResolvePath( + PathBoundary.Resolve( + compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, include.rootId), + include.relativePath + ) + ); if (include.framework) - text.AppendLine("target_compile_options(${binding_target} PRIVATE " + Literal("SHELL:-iframework \"" + directory.Replace('\\', '/') + "\"") + ")"); + { + text.AppendLine( + "target_compile_options(${binding_target} PRIVATE " + + Literal("SHELL:-iframework \"" + directory.Replace('\\', '/') + "\"") + + ")" + ); + } else - text.AppendLine("target_include_directories(${binding_target} " + (include.system ? "SYSTEM " : string.Empty) - + "PRIVATE " + Literal(directory) + ")"); + { + text.AppendLine( + "target_include_directories(${binding_target} " + (include.system ? "SYSTEM " : string.Empty) + + "PRIVATE " + Literal(directory) + ")" + ); + } } if (compilation.cxxStandard > 0) + { text.AppendLine("target_compile_features(${binding_target} PRIVATE cxx_std_" + compilation.cxxStandard + ")"); + } if (compilation.cStandard > 0) + { text.AppendLine("target_compile_features(${binding_target} PRIVATE c_std_" + compilation.cStandard + ")"); + } text.AppendLine("target_sources(${target} PRIVATE $)"); } text.Append("set_property(TARGET ${target} PROPERTY INNO_REQUIRED_EXPORTS"); foreach (string symbol in compilation.requiredExports.Concat(compilation.staticExportSymbols).Distinct(StringComparer.Ordinal)) + { text.Append(' ').Append(Literal(symbol)); + } text.AppendLine(")\nreturn()\nendif()"); } text.AppendLine("message(FATAL_ERROR \"No selected native binding requirements for ${owner}\")\nendfunction()"); if (target is not null && context.selectedBindings.ContainsKey(owner.nativeProject)) - text.AppendLine("cmake_language(DEFER DIRECTORY \"${CMAKE_SOURCE_DIR}\" CALL inno_apply_binding " - + Literal(target) + " " + Literal(Path.GetFileNameWithoutExtension(owner.nativeProject)) + ")"); + { + text.AppendLine( + "cmake_language(DEFER DIRECTORY \"${CMAKE_SOURCE_DIR}\" CALL inno_apply_binding " + + Literal(target) + " " + Literal(Path.GetFileNameWithoutExtension(owner.nativeProject)) + ")" + ); + } AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(text.ToString())); } private static string Literal(string value) { if (value.Contains(';') || value.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new InvalidDataException("A native CMake requirement cannot contain a list separator or control character."); + } string portable = value.Replace('\\', '/'); string delimiter = "="; while (portable.Contains("]" + delimiter + "]", StringComparison.Ordinal)) + { delimiter += "="; + } return "[" + delimiter + "[" + portable + "]" + delimiter + "]"; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs index ae7c43129..192904e86 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs @@ -15,7 +15,7 @@ namespace Inno.Build.Toolchains; /// public sealed class NativeBindingCompilation { - private static readonly JsonSerializerOptions S_OPTIONS = new() + private static readonly JsonSerializerOptions OPTIONS = new() { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, RespectRequiredConstructorParameters = true @@ -76,33 +76,6 @@ public sealed class NativeBindingCompilation /// public required string[] staticExportNames { get; init; } - /// - /// Reads the current engine-owned compilation description from a selected native output. - /// - /// - /// The complete selected generation's native directory. - /// - /// - /// The validated description; missing or malformed descriptions fail explicitly. - /// - /// - /// The description cannot be read. - /// - /// - /// The description does not match the current contract. - /// - /// - /// A root, path or content identity is invalid. - /// - public static NativeBindingCompilation Load(string nativeDirectory) - { - NativeBindingCompilation result = JsonSerializer.Deserialize( - File.ReadAllBytes(Path.Combine(nativeDirectory, "compilation.json")), S_OPTIONS) - ?? throw new InvalidDataException("A native compilation description is required."); - result.Validate(); - return result; - } - /// /// Resolves a component-local root using the current checkout and selected output. /// @@ -112,7 +85,7 @@ public static NativeBindingCompilation Load(string nativeDirectory) /// /// The selected generation's absolute native output. /// - /// + /// /// An ordinal root identity from this description. /// /// @@ -124,10 +97,10 @@ public static NativeBindingCompilation Load(string nativeDirectory) public string ResolveRoot( string engineRoot, string nativeDirectory, - string rootId + string rootID ) { - NativeBindingSourceRoot root = roots.SingleOrDefault(root => root.id == rootId) - ?? throw new InvalidDataException("Unknown native compilation root: " + rootId); + NativeBindingSourceRoot root = roots.SingleOrDefault(root => root.id == rootID) + ?? throw new InvalidDataException("Unknown native compilation root: " + rootID); return root.generated ? Path.GetFullPath(nativeDirectory) : Path.GetFullPath(root.directory, engineRoot); } @@ -160,7 +133,9 @@ public void VerifyInputs( string path = PathBoundary.Resolve(resolveRoot(input.rootId), input.relativePath); using FileStream stream = File.OpenRead(path); if (stream.Length != input.length || Convert.ToHexStringLower(SHA256.HashData(stream)) != input.sha256) + { throw new InvalidDataException("Native compilation input changed: " + path); + } } } @@ -179,47 +154,99 @@ public void VerifyInputs( public IEnumerable GetInputs( string engineRoot, string nativeDirectory - ) => files.Select(input => NativeBuildInput.FromPath(engineRoot, - PathBoundary.Resolve(ResolveRoot(engineRoot, nativeDirectory, input.rootId), input.relativePath))); + ) => files.Select(input => NativeBuildInput.FromPath( + engineRoot, + PathBoundary.Resolve(ResolveRoot(engineRoot, nativeDirectory, input.rootId), input.relativePath) + )); + + /// + /// Reads the current engine-owned compilation description from a selected native output. + /// + /// + /// The complete selected generation's native directory. + /// + /// + /// The validated description; missing or malformed descriptions fail explicitly. + /// + /// + /// The description cannot be read. + /// + /// + /// The description does not match the current contract. + /// + /// + /// A root, path or content identity is invalid. + /// + public static NativeBindingCompilation Load(string nativeDirectory) + { + NativeBindingCompilation result = JsonSerializer.Deserialize( + File.ReadAllBytes(Path.Combine(nativeDirectory, "compilation.json")), + OPTIONS + ) + ?? throw new InvalidDataException("A native compilation description is required."); + result.Validate(); + return result; + } private void Validate() { - if (roots is null || files is null || includeDirectories is null || defines is null || compilerDefines is null || requiredExports is null - || staticExportSymbols is null || staticExportNames is null || staticExportAbi is null) + if (roots is null + || files is null + || includeDirectories is null + || defines is null + || compilerDefines is null + || requiredExports is null + || staticExportSymbols is null || staticExportNames is null || staticExportAbi is null + ) { throw new InvalidDataException("Native compilation requirements are incomplete."); + } var ids = new HashSet(StringComparer.Ordinal); foreach (NativeBindingSourceRoot root in roots) { if (root is null || string.IsNullOrWhiteSpace(root.id) || !ids.Add(root.id) || root.directory is null || root.generated && (!root.frozen || root.directory.Length != 0) - || !root.generated && string.IsNullOrWhiteSpace(root.directory)) + || !root.generated && string.IsNullOrWhiteSpace(root.directory) + ) { throw new InvalidDataException("Native compilation roots must have unique, complete identities."); + } } if (roots.Count(static root => root.generated) != 1) + { throw new InvalidDataException("A native compilation must identify exactly one generated root."); + } var paths = new HashSet<(string, string)>(); foreach (NativeBindingSourceFile file in files) { if (file is null || !ids.Contains(file.rootId) || !IsRelative(file.relativePath, false) || !paths.Add((file.rootId, file.relativePath)) || file.length < 0 || file.sha256 is null - || file.sha256.Length != 64 || file.sha256.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + || file.sha256.Length != 64 || file.sha256.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f')) + ) { throw new InvalidDataException("Native compilation files require unique paths and exact content identities."); + } } - if (includeDirectories.Any(directory => directory is null || !ids.Contains(directory.rootId) - || !IsRelative(directory.relativePath, true)) || defines.Any(string.IsNullOrWhiteSpace) - || compilerDefines.Any(string.IsNullOrWhiteSpace) || requiredExports.Any(string.IsNullOrWhiteSpace) || staticExportSymbols.Any(string.IsNullOrWhiteSpace) + if (includeDirectories.Any(directory => ( + directory is null || !ids.Contains(directory.rootId) + || !IsRelative(directory.relativePath, true) + )) || defines.Any(string.IsNullOrWhiteSpace) + || compilerDefines.Any(string.IsNullOrWhiteSpace) + || requiredExports.Any(string.IsNullOrWhiteSpace) + || staticExportSymbols.Any(string.IsNullOrWhiteSpace) || staticExportNames.Any(string.IsNullOrWhiteSpace) || cxxStandard < 0 || cStandard < 0 || staticExportSymbols.Length == 0 && (staticExportAbi.Length != 0 || staticExportNames.Length != 0) || staticExportSymbols.Length != 0 && (staticExportAbi.Length != 64 || staticExportSymbols.Length != 5 - || staticExportAbi.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f')))) + || staticExportAbi.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + ) { throw new InvalidDataException("Native compilation search, language or export requirements are invalid."); + } } private static bool IsRelative( string? value, bool allowEmpty ) => value is not null && (allowEmpty && value.Length == 0 - || value.Length > 0 && !Path.IsPathRooted(value) && !value.Contains('\\') && !value.Contains(':') - && value.Split('/').All(static segment => segment.Length > 0 && segment is not ("." or "..") - && segment.AsSpan().IndexOfAnyInRange('\0', '\x1f') < 0)); + || value.Length > 0 && !Path.IsPathRooted(value) && !value.Contains('\\') && !value.Contains(':') + && value.Split('/').All(static segment => ( + segment.Length > 0 && segment is not ("." or "..") + && segment.AsSpan().IndexOfAnyInRange('\0', '\x1f') < 0 + ))); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs index e3f644d04..6e4f2d8d8 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs @@ -13,6 +13,63 @@ namespace Inno.Build.Toolchains; /// public sealed class NativeBindingGenerationDescriptor { + /// + /// Gets the immutable input identity assigned to this target generation. + /// + public required string fingerprint { get; init; } + + /// + /// Gets whether the generated context uses runtime-resolved imports instead of a module provider. + /// This initialization choice is independent of static or shared native linkage. + /// + public required bool usesRuntimeImports { get; init; } + + /// + /// Gets the absolute managed source path selected by the component project. + /// + public required string bindingsPath { get; init; } + + /// + /// Gets the complete native artifact and compilation-requirement directory, or empty when none is required. + /// + public required string nativeDirectory { get; init; } + + /// + /// Gets the immutable artifact root protected by reading leases, or an empty value for mutable host sources. + /// + public required string artifactDirectory { get; init; } + + /// + /// Gets the publisher root coordinating immutable artifact readers and retirement, or empty for host sources. + /// This owner remains unchanged when component sources are copied into a frozen build workspace. + /// + public required string artifactOwnerDirectory { get; init; } + + /// + /// Atomically writes this completed generation to a request-owned descriptor file. + /// + /// + /// The descriptor destination; a unique path keeps concurrent requests independent. + /// + public void Write(string path) + { + string destination = Path.GetFullPath(path); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + string staging = destination + ".staging-" + Guid.NewGuid().ToString("N"); + try + { + File.WriteAllText(staging, JsonSerializer.Serialize(this)); + File.Move(staging, destination, overwrite: true); + } + finally + { + if (File.Exists(staging)) + { + File.Delete(staging); + } + } + } + /// /// Writes the exact native binding identities for a subsequent managed build without reselecting generations. /// Identical content preserves the existing import timestamp; changed content is installed atomically. @@ -46,7 +103,9 @@ IReadOnlyDictionary linkage document.Save(buffer); byte[] content = buffer.ToArray(); if (File.Exists(destination) && File.ReadAllBytes(destination).AsSpan().SequenceEqual(content)) + { return; + } Directory.CreateDirectory(Path.GetDirectoryName(destination)!); AtomicFile.WriteAllBytes(destination, content); } @@ -84,41 +143,11 @@ public static void ValidateSelection( IReadOnlyDictionary linkage ) { if (!XNode.DeepEquals(XDocument.Load(path), CreateSelection(generations, linkage))) + { throw new InvalidDataException("Native publication must preserve the exact binding selection used by managed compilation."); + } } - /// - /// Gets the immutable input identity assigned to this target generation. - /// - public required string fingerprint { get; init; } - - /// - /// Gets whether the generated context uses runtime-resolved imports instead of a module provider. - /// This initialization choice is independent of static or shared native linkage. - /// - public required bool usesRuntimeImports { get; init; } - - /// - /// Gets the absolute managed source path selected by the component project. - /// - public required string bindingsPath { get; init; } - - /// - /// Gets the complete native artifact and compilation-requirement directory, or empty when none is required. - /// - public required string nativeDirectory { get; init; } - - /// - /// Gets the immutable artifact root protected by reading leases, or an empty value for mutable host sources. - /// - public required string artifactDirectory { get; init; } - - /// - /// Gets the publisher root coordinating immutable artifact readers and retirement, or empty for host sources. - /// This owner remains unchanged when component sources are copied into a frozen build workspace. - /// - public required string artifactOwnerDirectory { get; init; } - /// /// Reads and validates the result of a completed component generation request. /// @@ -140,34 +169,12 @@ IReadOnlyDictionary linkage public static NativeBindingGenerationDescriptor Load(string path) { NativeBindingGenerationDescriptor descriptor = JsonSerializer.Deserialize( - File.ReadAllText(path)) ?? throw new InvalidDataException("The binding generation descriptor is empty."); + File.ReadAllText(path) + ) ?? throw new InvalidDataException("The binding generation descriptor is empty."); descriptor.Validate(); return descriptor; } - /// - /// Atomically writes this completed generation to a request-owned descriptor file. - /// - /// - /// The descriptor destination; a unique path keeps concurrent requests independent. - /// - public void Write(string path) - { - string destination = Path.GetFullPath(path); - Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - string staging = destination + ".staging-" + Guid.NewGuid().ToString("N"); - try - { - File.WriteAllText(staging, JsonSerializer.Serialize(this)); - File.Move(staging, destination, overwrite: true); - } - finally - { - if (File.Exists(staging)) - File.Delete(staging); - } - } - internal void Validate() { NativeBindingGenerationDescriptor descriptor = this; @@ -178,12 +185,20 @@ internal void Validate() || descriptor.artifactDirectory.Length == 0 && descriptor.artifactOwnerDirectory.Length != 0 || descriptor.artifactDirectory.Length > 0 && !Path.IsPathFullyQualified(descriptor.artifactOwnerDirectory) || descriptor.artifactDirectory.Length > 0 && (!Path.IsPathFullyQualified(descriptor.artifactDirectory) - || Path.GetFullPath(descriptor.bindingsPath) != Path.Combine(Path.GetFullPath(descriptor.artifactDirectory), "Generated", "Bindings.cs")) + || Path.GetFullPath(descriptor.bindingsPath) != Path.Combine( + Path.GetFullPath(descriptor.artifactDirectory), + "Generated", + "Bindings.cs" + )) || descriptor.nativeDirectory.Length > 0 && (!Path.IsPathFullyQualified(descriptor.nativeDirectory) - || !Directory.Exists(descriptor.nativeDirectory))) + || !Directory.Exists(descriptor.nativeDirectory)) + ) { throw new InvalidDataException("The binding generation descriptor does not identify complete outputs."); + } if (descriptor.artifactDirectory.Length > 0) + { BuildCacheCleanupPlan.RequireChild(descriptor.artifactOwnerDirectory, descriptor.artifactDirectory); + } } private static XDocument CreateSelection( @@ -193,25 +208,39 @@ IReadOnlyDictionary linkage ArgumentNullException.ThrowIfNull(generations); ArgumentNullException.ThrowIfNull(linkage); if (generations.Count != linkage.Count || generations.Keys.Any(key => !linkage.ContainsKey(key))) + { throw new ArgumentException("Binding selections require exact component linkage coverage.", nameof(linkage)); + } var names = new HashSet(StringComparer.OrdinalIgnoreCase); var document = new XElement("Project"); - foreach (var entry in generations.OrderBy(static entry => entry.Key, StringComparer.Ordinal)) - { + foreach (KeyValuePair entry in generations.OrderBy( + static entry => entry.Key, + StringComparer.Ordinal + )) { string name = Path.GetFileNameWithoutExtension(entry.Key); - if (string.IsNullOrWhiteSpace(name) || name.Any(static value => !char.IsAsciiLetterOrDigit(value) - && value is not ('.' or '_' or '-')) || !names.Add(name)) + if (string.IsNullOrWhiteSpace(name) || name.Any(static value => ( + !char.IsAsciiLetterOrDigit(value) + && value is not ('.' or '_' or '-') + )) || !names.Add(name) + ) { throw new ArgumentException("Binding selections require unique portable project names.", nameof(generations)); + } if (!Enum.IsDefined(linkage[entry.Key])) + { throw new ArgumentException("A selected native component requires supported linkage.", nameof(linkage)); - document.Add(new XElement("PropertyGroup", - new XAttribute("Condition", "'$(MSBuildProjectName)' == '" + name + "'"), - new XElement("BindGenExpectedFingerprint", entry.Value.fingerprint), - new XElement("BindGenArtifactDirectory", entry.Value.artifactDirectory), - new XElement("BindGenArtifactOwnerDirectory", entry.Value.artifactOwnerDirectory), - new XElement("InnoNativeLibraryKind", linkage[entry.Key]), - new XElement("InnoNativeRuntimeImports", entry.Value.usesRuntimeImports ? "true" : "false"), - new XElement("BindGenOutputDirectory", Path.GetDirectoryName(entry.Value.bindingsPath)))); + } + document.Add( + new XElement( + "PropertyGroup", + new XAttribute("Condition", "'$(MSBuildProjectName)' == '" + name + "'"), + new XElement("BindGenExpectedFingerprint", entry.Value.fingerprint), + new XElement("BindGenArtifactDirectory", entry.Value.artifactDirectory), + new XElement("BindGenArtifactOwnerDirectory", entry.Value.artifactOwnerDirectory), + new XElement("InnoNativeLibraryKind", linkage[entry.Key]), + new XElement("InnoNativeRuntimeImports", entry.Value.usesRuntimeImports ? "true" : "false"), + new XElement("BindGenOutputDirectory", Path.GetDirectoryName(entry.Value.bindingsPath)) + ) + ); } return new XDocument(document); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs index e3e991a1d..d6ea9b749 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs @@ -5,21 +5,6 @@ namespace Inno.Build.Toolchains; -/// -/// Selects the publication owner of generated sources. -/// -public enum NativeBindingOutputMode -{ - /// - /// Replaces the component's authored host source and bridge outputs together. - /// - HostSource, - /// - /// Publishes immutable target outputs under the component's generation fingerprint. - /// - TargetArtifacts -} - /// /// Freezes the complete binding request before ownership waits or candidate creation. /// @@ -31,7 +16,7 @@ public sealed class NativeBindingGenerationRequest /// /// The component owners, each declaring one binding definition. /// - /// + /// /// The target identity selecting a declared configuration; host output uses the host definition. /// /// @@ -51,51 +36,68 @@ public sealed class NativeBindingGenerationRequest /// public NativeBindingGenerationRequest( IEnumerable components, - string targetId, + string targetID, NativeBindingOutputMode outputMode, bool checkOnly = false, IReadOnlyDictionary? expectedFingerprints = null, IReadOnlyDictionary? componentOptions = null ) { ArgumentNullException.ThrowIfNull(components); - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - if (!Enum.IsDefined(outputMode) || targetId is "." or ".." - || targetId.Any(static character => !char.IsAsciiLetterOrDigit(character) - && character is not ('-' or '_' or '.'))) + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + if (!Enum.IsDefined(outputMode) || targetID is "." or ".." + || targetID.Any(static character => ( + !char.IsAsciiLetterOrDigit(character) + && character is not ('-' or '_' or '.') + )) + ) { throw new ArgumentException("Binding requests require a portable target and a supported output mode."); + } NativeComponentDescriptor[] owners = components.ToArray(); if (owners.Any(static owner => owner is null || owner.bindingDefinition is null) - || owners.Select(static owner => owner.nativeProject).Distinct(StringComparer.Ordinal).Count() != owners.Length) + || owners.Select(static owner => owner.nativeProject).Distinct(StringComparer.Ordinal).Count() != owners.Length + ) { throw new ArgumentException("Binding owners must be distinct and declare their sole definition.", nameof(components)); + } this.components = Array.AsReadOnly(owners); - this.targetId = targetId; + this.targetID = targetID; this.outputMode = outputMode; this.checkOnly = checkOnly; - Dictionary expected = new(expectedFingerprints ?? new Dictionary(), StringComparer.Ordinal); - if (expected.Any(pair => !owners.Any(owner => owner.nativeProject == pair.Key) - || string.IsNullOrWhiteSpace(pair.Value))) + var expected = new Dictionary(expectedFingerprints ?? new Dictionary(), StringComparer.Ordinal); + if (expected.Any(pair => ( + !owners.Any(owner => owner.nativeProject == pair.Key) + || string.IsNullOrWhiteSpace(pair.Value) + ))) { throw new ArgumentException("An expected identity must belong to the requested binding closure.", nameof(expectedFingerprints)); + } this.expectedFingerprints = new ReadOnlyDictionary(expected); this.componentOptions = new ReadOnlyDictionary( - new Dictionary(componentOptions ?? new Dictionary(), StringComparer.Ordinal)); + new Dictionary( + componentOptions ?? new Dictionary(), + StringComparer.Ordinal + ) + ); } /// /// Gets the immutable component closure owned by this request. /// public IReadOnlyList components { get; } + /// /// Gets the explicit configuration target, independent of the build execution host. /// - public string targetId { get; } + public string targetID { get; } + /// /// Gets the selected output ownership policy. /// public NativeBindingOutputMode outputMode { get; } + /// /// Gets whether publication is forbidden and current output must match fresh generation. /// public bool checkOnly { get; } + /// /// Gets the expected identities which must match before any candidate is generated. /// @@ -106,3 +108,18 @@ public NativeBindingGenerationRequest( /// public IReadOnlyDictionary componentOptions { get; } } + +/// +/// Selects the publication owner of generated sources. +/// +public enum NativeBindingOutputMode +{ + /// + /// Replaces the component's authored host source and bridge outputs together. + /// + HostSource, + /// + /// Publishes immutable target outputs under the component's generation fingerprint. + /// + TargetArtifacts +} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs index b9f9b0f4d..5c137cae3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs @@ -40,33 +40,35 @@ IEnumerable ownership var copy = new Dictionary(generations, StringComparer.Ordinal); IDisposable[] owners = ownership.ToArray(); if (copy.Values.Any(static value => value is null) || owners.Any(static value => value is null)) + { throw new ArgumentException("Generation and ownership entries must be non-null."); + } m_generations = new ReadOnlyDictionary(copy); m_ownership = owners; } - /// /// /// Reading ownership has ended. /// + /// public int Count => RequireGenerations().Count; - /// + /// + /// Reading ownership has ended. + /// /// /// The returned sequence is borrowed and must be consumed before this result is disposed. /// + /// + public IEnumerable Keys => RequireGenerations().Keys; + /// /// Reading ownership has ended. /// - public IEnumerable Keys => RequireGenerations().Keys; - - /// /// /// Neither the returned sequence nor its descriptors extend the lifetime of reading protection. /// - /// - /// Reading ownership has ended. - /// + /// public IEnumerable Values => RequireGenerations().Values; /// @@ -86,31 +88,31 @@ IEnumerable ownership /// public NativeBindingGenerationDescriptor this[string key] => RequireGenerations()[key]; - /// /// /// Reading ownership has ended. /// + /// public bool ContainsKey(string key) => RequireGenerations().ContainsKey(key); - /// - /// - /// A returned descriptor is borrowed and must not be used to access files after this result is disposed. - /// /// /// Reading ownership has ended. /// + /// + /// A returned descriptor is borrowed and must not be used to access files after this result is disposed. + /// + /// public bool TryGetValue( string key, [MaybeNullWhen(false)] out NativeBindingGenerationDescriptor value ) => RequireGenerations().TryGetValue(key, out value); - /// - /// - /// Enumeration and all descriptor consumers must finish before the result's reading protection ends. - /// /// /// Reading ownership has ended. /// + /// + /// Enumeration and all descriptor consumers must finish before the result's reading protection ends. + /// + /// public IEnumerator> GetEnumerator() => RequireGenerations().GetEnumerator(); /// @@ -123,7 +125,9 @@ public void Dispose() { IDisposable[]? owners = Interlocked.Exchange(ref m_ownership, null); if (owners is null) + { return; + } List failures = []; for (int index = owners.Length - 1; index >= 0; index--) { @@ -137,7 +141,9 @@ public void Dispose() } } if (failures.Count != 0) + { throw new AggregateException("Binding reading ownership could not be completely released.", failures); + } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs index 54f2e895b..78c1a0f11 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs @@ -18,8 +18,10 @@ internal sealed class NativeBindingInputPaths private readonly HashSet m_generationDeclarations = new(StringComparer.Ordinal); private readonly List m_sourceRoots = []; private readonly string m_engineRoot; + private readonly StringComparison m_comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; internal NativeBindingInputPaths(NativeBuildContext context) { @@ -30,18 +32,24 @@ internal NativeBindingInputPaths(NativeBuildContext context) string root = ".inno-bindings/" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(entry.Key))); m_generationDeclarations.Add(entry.Key + "=" + generation.fingerprint); if (generation.artifactDirectory.Length > 0) + { Add(generation.artifactDirectory, root, false); + } else { Add(generation.bindingsPath, root + "/Generated/Bindings.cs", true); if (generation.nativeDirectory.Length > 0) + { Add(generation.nativeDirectory, root + "/Native", false); + } } if (generation.nativeDirectory.Length > 0) { NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); foreach (NativeBindingSourceRoot source in compilation.roots.Where(static source => source.frozen && !source.generated)) + { m_sourceRoots.Add(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, source.id)); + } } } } @@ -49,21 +57,27 @@ internal NativeBindingInputPaths(NativeBuildContext context) internal string? ResolveRelative(string path) { string absolute = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); - foreach (var entry in m_roots) + foreach ((string physical, string relative, bool file) entry in m_roots) { if (string.Equals(absolute, entry.physical, m_comparison)) + { return entry.relative; + } if (!entry.file && absolute.StartsWith(entry.physical + Path.DirectorySeparatorChar, m_comparison)) + { return entry.relative + "/" + Path.GetRelativePath(entry.physical, absolute).Replace('\\', '/'); + } } string checkoutRelative = Path.GetRelativePath(m_engineRoot, absolute); if ((checkoutRelative == ".." || checkoutRelative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) - || Path.IsPathRooted(checkoutRelative)) && m_sourceRoots.Any(root => string.Equals(root, absolute, m_comparison) - || absolute.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, m_comparison))) - { + || Path.IsPathRooted(checkoutRelative)) && m_sourceRoots.Any(root => ( + string.Equals(root, absolute, m_comparison) + || absolute.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, m_comparison) + )) + ) { string volume = Path.GetPathRoot(absolute)!; return ".inno-source-roots/" + Base64Url.EncodeToString(SHA256.HashData(Encoding.UTF8.GetBytes(volume))) - + "/" + Path.GetRelativePath(volume, absolute).Replace('\\', '/'); + + "/" + Path.GetRelativePath(volume, absolute).Replace('\\', '/'); } return null; } @@ -71,25 +85,34 @@ internal NativeBindingInputPaths(NativeBuildContext context) internal string NormalizeDeclaration(string declaration) { if (m_generationDeclarations.Contains(declaration)) + { return declaration[..(declaration.IndexOf('=') + 1)] + "selected-generation"; - const string nativePrefix = "bindingNativeRoot="; - if (declaration.StartsWith(nativePrefix, StringComparison.Ordinal)) + } + const string C_NATIVE_PREFIX = "bindingNativeRoot="; + if (declaration.StartsWith(C_NATIVE_PREFIX, StringComparison.Ordinal)) { - string path = declaration[nativePrefix.Length..]; + string path = declaration[C_NATIVE_PREFIX.Length..]; return path.Length > 0 && ResolveRelative(path) is { } native - ? nativePrefix + "workspace-input:" + native : declaration; + ? C_NATIVE_PREFIX + "workspace-input:" + native + : declaration; } int start = declaration.IndexOf("-D", StringComparison.Ordinal); if (start < 0 || start > 0 && declaration[start - 1] != '=') + { return declaration; + } int separator = declaration.IndexOf('=', start); if (separator < 0) + { return declaration; + } string[] values = declaration[(separator + 1)..].Split(';'); for (int index = 0; index < values.Length; index++) { if (Path.IsPathFullyQualified(values[index]) && ResolveRelative(values[index]) is { } relative) + { values[index] = "workspace-input:" + relative; + } } return declaration[..(separator + 1)] + string.Join(';', values); } @@ -100,10 +123,13 @@ private void Add( bool file ) { string absolute = Path.TrimEndingDirectorySeparator(Path.GetFullPath(physical)); - if (m_roots.Any(entry => string.Equals(entry.physical, absolute, m_comparison) + if (m_roots.Any(entry => ( + string.Equals(entry.physical, absolute, m_comparison) || !entry.file && absolute.StartsWith(entry.physical + Path.DirectorySeparatorChar, m_comparison) - || !file && entry.physical.StartsWith(absolute + Path.DirectorySeparatorChar, m_comparison))) + || !file && entry.physical.StartsWith(absolute + Path.DirectorySeparatorChar, m_comparison) + ))) { throw new InvalidOperationException("Selected binding owners cannot share or contain each other's output roots."); + } m_roots.Add((absolute, relative, file)); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs index 6de72e4e4..03b8a8304 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs @@ -42,11 +42,18 @@ public static async Task PrepareAsync( ArgumentNullException.ThrowIfNull(components); cancellationToken.ThrowIfCancellationRequested(); NativeComponentDescriptor[] owners = components.Where(static owner => owner.bindingDefinition is not null) - .DistinctBy(static owner => owner.nativeProject).ToArray(); + .DistinctBy(static owner => owner.nativeProject) + .ToArray(); if (owners.Length == 0) + { return new(new Dictionary(), []); - var request = new NativeBindingGenerationRequest(owners, context.RequireToolchain().targetId, - NativeBindingOutputMode.TargetArtifacts, componentOptions: componentOptions); + } + var request = new NativeBindingGenerationRequest( + owners, + context.RequireToolchain().targetID, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: componentOptions + ); return await context.RequireBindingGenerator().GenerateAsync(context, request, cancellationToken).ConfigureAwait(false); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs index 439588935..5f6593078 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs @@ -43,7 +43,7 @@ public static string Create( ) { ArgumentNullException.ThrowIfNull(declarations); ArgumentNullException.ThrowIfNull(inputs); - NativeBuildInputState state = new(); + var state = new NativeBuildInputState(); return Create(declarations, state.CaptureInitial(inputs, cancellationToken)); } @@ -83,7 +83,9 @@ NativeInputSnapshot snapshot ) { using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string declaration in declarations) + { Append(hash, declaration); + } foreach (NativeInputSnapshot.Entry entry in snapshot.entries) { Append(hash, entry.logicalPath); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs index 284cefa22..f534778b3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs @@ -27,12 +27,18 @@ string physicalPath ArgumentException.ThrowIfNullOrWhiteSpace(logicalPath); ArgumentException.ThrowIfNullOrWhiteSpace(physicalPath); if (logicalPath.Contains('\\') || logicalPath.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new ArgumentException("A native input identity must use portable, printable path segments.", nameof(logicalPath)); + } if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("A native input reading location must be absolute.", nameof(physicalPath)); + } this.logicalPath = logicalPath.TrimEnd('/'); if (this.logicalPath.Length == 0) + { throw new ArgumentException("A native input identity requires a logical root.", nameof(logicalPath)); + } this.physicalPath = Path.GetFullPath(physicalPath); } @@ -67,9 +73,9 @@ string path string physical = Path.GetFullPath(path, engineRoot); string relative = Path.GetRelativePath(engineRoot, physical).Replace('\\', '/'); string logical = relative != ".." && !relative.StartsWith("../", StringComparison.Ordinal) - && !Path.IsPathRooted(relative) - ? "engine/" + relative - : "external/" + physical.Replace('\\', '/').TrimStart('/'); + && !Path.IsPathRooted(relative) + ? "engine/" + relative + : "external/" + physical.Replace('\\', '/').TrimStart('/'); return new NativeBuildInput(logical, physical); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs index b1b4cb255..dd397766a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Threading; namespace Inno.Build.Toolchains; @@ -9,6 +9,7 @@ internal sealed class NativeBuildInputState { private readonly object m_gate = new(); private readonly NativeInputReadCache m_initialInputs; + private readonly Dictionary m_phases = new(StringComparer.Ordinal); private long m_hashedFiles; private long m_hashedBytes; private long m_nativeProcesses; @@ -18,11 +19,14 @@ internal sealed class NativeBuildInputState private long m_outputFiles; private long m_outputBytes; private long m_managedProcesses; - private readonly Dictionary m_phases = new(StringComparer.Ordinal); - internal NativeBuildInputState() => m_initialInputs = new(this); + internal NativeBuildInputState() + { + m_initialInputs = new(this); + } - internal NativeBuildStatistics statistics => new() + internal NativeBuildStatistics statistics + => new() { hashedFiles = Interlocked.Read(ref m_hashedFiles), hashedBytes = Interlocked.Read(ref m_hashedBytes), @@ -41,7 +45,9 @@ internal NativeInputSnapshot CaptureInitial( CancellationToken cancellationToken ) { lock (m_gate) + { return NativeInputSnapshot.Capture(inputs, m_initialInputs, cancellationToken); + } } internal NativeInputSnapshot CaptureVerification( @@ -57,7 +63,7 @@ string phase Interlocked.Add(ref m_hashedBytes, bytes); lock (m_gate) { - m_phases.TryGetValue(phase, out var value); + m_phases.TryGetValue(phase, out (long files, long bytes, long reused) value); m_phases[phase] = (value.files + 1, value.bytes + bytes, value.reused); } } @@ -65,32 +71,40 @@ string phase internal byte[] GetFrozenHash(string path) { lock (m_gate) + { return m_initialInputs.GetFrozenHash(path); + } } internal NativeInputSnapshot CaptureRecordedInputs(string engineRoot) { lock (m_gate) + { return m_initialInputs.CaptureRecordedInputs(engineRoot); + } } internal string[][] CaptureRootMembership() { lock (m_gate) + { return m_initialInputs.CaptureRootMembership(); + } } internal void RecordReuse(string phase) { lock (m_gate) { - m_phases.TryGetValue(phase, out var value); + m_phases.TryGetValue(phase, out (long files, long bytes, long reused) value); m_phases[phase] = (value.files, value.bytes, value.reused + 1); } } internal void RecordBindingBatch() => Interlocked.Increment(ref m_bindingBatches); + internal void RecordBindingGeneration() => Interlocked.Increment(ref m_bindingGenerations); + internal void RecordMaterialization(long bytes) => Interlocked.Add(ref m_materializedBytes, bytes); internal void RecordOutput(long bytes) @@ -101,15 +115,23 @@ internal void RecordOutput(long bytes) internal void RecordManagedProcess() => Interlocked.Increment(ref m_managedProcesses); + internal void RecordProcess() => Interlocked.Increment(ref m_nativeProcesses); + private IReadOnlyList CapturePhases() { lock (m_gate) - return Array.AsReadOnly(m_phases.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => new NativeBuildPhaseStatistics - { - phase = pair.Key, files = pair.Value.files, bytes = pair.Value.bytes, reusedReads = pair.Value.reused - }).ToArray()); + { + return Array.AsReadOnly( + m_phases.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => new NativeBuildPhaseStatistics + { + phase = pair.Key, + files = pair.Value.files, + bytes = pair.Value.bytes, + reusedReads = pair.Value.reused + }) + .ToArray() + ); + } } - - internal void RecordProcess() => Interlocked.Increment(ref m_nativeProcesses); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs index 505117559..f43d9fbe9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs @@ -9,14 +9,17 @@ public sealed record NativeBuildPhaseStatistics /// Gets the named operation phase which owns these read results. /// public required string phase { get; init; } + /// /// Gets the number of complete physical file reads. /// public long files { get; init; } + /// /// Gets the number of bytes actually read for hashing. /// public long bytes { get; init; } + /// /// Gets repeated physical hash requests satisfied from this phase's cache. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs index fd99a3ee6..f7bb3c315 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs @@ -14,7 +14,7 @@ public sealed class NativeBuildProduct : IDisposable internal NativeBuildProduct( string component, - string targetId, + string targetID, string fingerprint, string directory, NativeBindingGenerationDescriptor? bindingGeneration, @@ -22,7 +22,7 @@ internal NativeBuildProduct( BuildArtifactReadLease readLease ) { this.component = component; - this.targetId = targetId; + this.targetID = targetID; this.fingerprint = fingerprint; this.directory = directory; this.bindingGeneration = bindingGeneration; @@ -30,8 +30,8 @@ BuildArtifactReadLease readLease m_readLease = readLease; try { - artifacts = NativeArtifact.Read(directory); - files = Array.AsReadOnly(artifacts.Select(static artifact => artifact.file).Order(StringComparer.Ordinal).ToArray()); + this.artifacts = NativeArtifact.Read(directory); + this.files = Array.AsReadOnly(artifacts.Select(static artifact => artifact.file).Order(StringComparer.Ordinal).ToArray()); } catch { @@ -48,7 +48,7 @@ BuildArtifactReadLease readLease /// /// Gets the target ABI selected for this build. /// - public string targetId { get; } + public string targetID { get; } /// /// Gets the content fingerprint covering sources, tool executables and toolchain declarations. diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs index 280b19bb5..e1a9fdbcf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs @@ -10,7 +10,6 @@ namespace Inno.Build.Toolchains; /// public sealed class NativeBuildRecipe { - internal NativeToolchainSelection? toolchain { get; private init; } /// /// Creates a complete recipe without inferring implementation identity from an assembly MVID. /// @@ -20,7 +19,7 @@ public sealed class NativeBuildRecipe /// /// The component's portable artifact path segment. /// - /// + /// /// The ABI's portable artifact path segment. /// /// @@ -38,7 +37,7 @@ public sealed class NativeBuildRecipe public NativeBuildRecipe( NativeComponentDescriptor owner, string component, - string targetId, + string targetID, IEnumerable inputs, IEnumerable declarations ) { @@ -46,15 +45,17 @@ IEnumerable declarations ArgumentNullException.ThrowIfNull(inputs); ArgumentNullException.ThrowIfNull(declarations); ValidateSegment(component); - ValidateSegment(targetId); + ValidateSegment(targetID); NativeBuildInput[] frozenInputs = inputs.ToArray(); string[] frozenDeclarations = declarations.ToArray(); if (frozenInputs.Any(static input => input is null) - || frozenDeclarations.Any(static declaration => declaration is null)) + || frozenDeclarations.Any(static declaration => declaration is null) + ) { throw new ArgumentException("A recipe cannot contain null inputs or declarations."); + } this.owner = owner; this.component = component; - this.targetId = targetId; + this.targetID = targetID; this.inputs = Array.AsReadOnly(frozenInputs); this.declarations = Array.AsReadOnly(frozenDeclarations); } @@ -72,7 +73,7 @@ IEnumerable declarations /// /// Gets the target ABI's artifact path segment. /// - public string targetId { get; } + public string targetID { get; } /// /// Gets the frozen declarations of physical inputs and their logical identities. @@ -84,6 +85,39 @@ IEnumerable declarations /// public IReadOnlyList declarations { get; } + /// + /// Adds one explicitly selected published dependency while preserving the recipe's frozen execution tools. + /// + /// + /// The dependency file whose bytes participate in compilation. + /// + /// + /// The immutable dependency artifact identity selected by the product. + /// + /// + /// A new declaration with the dependency input and identity; this recipe is unchanged. + /// + /// + /// The dependency identity is empty. + /// + /// + /// The input is null. + /// + public NativeBuildRecipe WithDependency( + NativeBuildInput input, + string fingerprint + ) { + ArgumentNullException.ThrowIfNull(input); + ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); + return new( + owner, + component, + targetID, + inputs.Append(input), + declarations.Append("dependency=" + fingerprint) + ) { toolchain = toolchain }; + } + /// /// Declares a component's source, execution and SDK inputs before binding outputs need to exist. /// The artifact publisher attaches the exact selected generation before hashing or compiling. @@ -97,7 +131,7 @@ IEnumerable declarations /// /// The native component artifact segment. /// - /// + /// /// The selected target ABI. /// /// @@ -121,7 +155,7 @@ public static NativeBuildRecipe CreateForComponent( NativeBuildContext context, NativeComponentDescriptor owner, string component, - string targetId, + string targetID, IEnumerable inputPaths, IEnumerable declarations, IEnumerable implementationPaths @@ -135,24 +169,74 @@ IEnumerable implementationPaths context.toolchain?.linkPlan.GetFileExtension(options.libraryKind); string projectFile = Path.GetFullPath(owner.toolchainProject, context.engineRoot); if (!File.Exists(projectFile)) + { throw new FileNotFoundException("A native recipe owner project is unavailable.", projectFile); - List paths = [..inputPaths, ..options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), ..(context.toolchain?.inputPaths ?? []), projectFile]; + } + List paths = + [ + ..inputPaths, + ..options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), + ..(context.toolchain?.inputPaths ?? []), + projectFile + ]; paths.AddRange(implementationPaths); string commonRoot = Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains"); - paths.AddRange(new[] { "NativeBuildContext.cs", "ToolchainEnvironment.cs", "ToolchainLayout.cs", "BuildArtifactManifest.cs", "ToolchainWorkingDirectory.cs" } - .Select(file => Path.Combine(commonRoot, file))); - paths.AddRange(new[] - { - "NativeArtifactPublisher.cs", "ProductNativeCacheLookup.cs", "NativeBuildFingerprint.cs", "NativeBuildInput.cs", "NativeWorkspaceIdentity.cs", "NativeBindingInputPaths.cs", - "NativeBuildInputState.cs", "NativeInputSnapshot.cs", "NativeInputReadCache.cs", "NativeInputVerificationScope.cs", "NativeBuildPhaseStatistics.cs", "NativeBuildProduct.cs", - "NativeBuildStatistics.cs", "NativeToolchainSelection.cs", "NativeBuildRecipe.cs", "ProductNativeBuildResult.cs", "NativeArtifact.cs", "NativeCompilerInputs.cs", "NativeLinkPlan.cs", - "NativeCMakeExecutor.cs", "NativeCMakeSource.cs", "NativeComponentBuildOptions.cs", "ProductNativeBuildStep.cs", "ProductNativeBuildPlan.cs", "NativeInputMaterializer.cs", "NativeBindingGenerationDescriptor.cs", - "NativeBindingGenerationResult.cs", "NativeBindingPreparation.cs", "NativeComponentDescriptor.cs", "NativeStaticBuildDefinition.cs", - "NativeToolchainPreparation.cs", "BuildHostDescriptor.cs", - "NativeBindingCompilation.cs", "NativeBindingSourceRoot.cs", "NativeBindingSourceFile.cs", "NativeBindingIncludeDirectory.cs", "NativeBindingCMake.cs" - }.Select(file => Path.Combine(commonRoot, "Native", file))); - paths.AddRange(new[] { "BuildHostServices.cs", "IToolchainWorkspaceProvider.cs", "PhysicalToolchainWorkspaceProvider.cs" } - .Select(file => Path.Combine(commonRoot, "Host", file))); + paths.AddRange( + new[] { + "NativeBuildContext.cs", + "ToolchainEnvironment.cs", + "ToolchainLayout.cs", + "BuildArtifactManifest.cs", + "ToolchainWorkingDirectory.cs" + } + .Select(file => Path.Combine(commonRoot, file)) + ); + paths.AddRange( + new[] + { + "NativeArtifactPublisher.cs", + "ProductNativeCacheLookup.cs", + "NativeBuildFingerprint.cs", + "NativeBuildInput.cs", + "NativeWorkspaceIdentity.cs", + "NativeBindingInputPaths.cs", + "NativeBuildInputState.cs", + "NativeInputSnapshot.cs", + "NativeInputReadCache.cs", + "NativeInputVerificationScope.cs", + "NativeBuildPhaseStatistics.cs", + "NativeBuildProduct.cs", + "NativeBuildStatistics.cs", + "NativeToolchainSelection.cs", + "NativeBuildRecipe.cs", + "ProductNativeBuildResult.cs", + "NativeArtifact.cs", + "NativeCompilerInputs.cs", + "NativeLinkPlan.cs", + "NativeCMakeExecutor.cs", + "NativeCMakeSource.cs", + "NativeComponentBuildOptions.cs", + "ProductNativeBuildStep.cs", + "ProductNativeBuildPlan.cs", + "NativeInputMaterializer.cs", + "NativeBindingGenerationDescriptor.cs", + "NativeBindingGenerationResult.cs", + "NativeBindingPreparation.cs", + "NativeComponentDescriptor.cs", + "NativeStaticBuildDefinition.cs", + "NativeToolchainPreparation.cs", + "BuildHostDescriptor.cs", + "NativeBindingCompilation.cs", + "NativeBindingSourceRoot.cs", + "NativeBindingSourceFile.cs", + "NativeBindingIncludeDirectory.cs", + "NativeBindingCMake.cs" + }.Select(file => Path.Combine(commonRoot, "Native", file)) + ); + paths.AddRange( + new[] { "BuildHostServices.cs", "IToolchainWorkspaceProvider.cs", "PhysicalToolchainWorkspaceProvider.cs" } + .Select(file => Path.Combine(commonRoot, "Host", file)) + ); paths.AddRange((context.toolchain?.host.services.inputPaths ?? []).Select(path => Path.GetFullPath(path, context.engineRoot))); paths.Add(Path.Combine(commonRoot, "Managed", "DotNetSdkEnvironment.cs")); paths.Add(Path.Combine(commonRoot, "Cache", "BuildArtifactReadLease.cs")); @@ -160,41 +244,35 @@ IEnumerable implementationPaths paths.Add(Path.Combine(commonRoot, "Cache", "BuildCachePublisher.cs")); paths.Add(Path.Combine(commonRoot, "Cache", "BuildCacheFileInventory.cs")); string ioRoot = Path.Combine(context.engineRoot, "src", "foundation", "core", "Inno.Core.IO"); - paths.AddRange(new[] { "AtomicDirectory.cs", "AtomicFile.cs", "DirectoryCleanupException.cs", "FileSystemRename.cs", "FileLease.cs", "PathBoundary.cs", - "ProcessOwnerStamp.cs", "ProcessOwnerState.cs", "ProcessOwnedDirectory.cs", "ProcessOwnedDirectoryDescriptor.cs", "CoordinatedFileLease.cs" } - .Select(file => Path.Combine(ioRoot, file))); - return new NativeBuildRecipe(owner, component, targetId, + paths.AddRange( + new[] + { + "AtomicDirectory.cs", + "AtomicFile.cs", + "DirectoryCleanupException.cs", + "FileSystemRename.cs", + "FileLease.cs", + "PathBoundary.cs", + "ProcessOwnerStamp.cs", + "ProcessOwnerState.cs", + "ProcessOwnedDirectory.cs", + "ProcessOwnedDirectoryDescriptor.cs", + "CoordinatedFileLease.cs" + } + .Select(file => Path.Combine(ioRoot, file)) + ); + return new NativeBuildRecipe( + owner, + component, + targetID, paths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), - new[] { component, targetId, context.configuration, "executionRoot=" + context.engineRoot }.Concat(declarations) - .Concat(options.declarations).Concat(context.toolchain?.declarations ?? [])) { toolchain = context.toolchain }; + new[] { component, targetID, context.configuration, "executionRoot=" + context.engineRoot }.Concat(declarations) + .Concat(options.declarations) + .Concat(context.toolchain?.declarations ?? []) + ) { toolchain = context.toolchain }; } - /// - /// Adds one explicitly selected published dependency while preserving the recipe's frozen execution tools. - /// - /// - /// The dependency file whose bytes participate in compilation. - /// - /// - /// The immutable dependency artifact identity selected by the product. - /// - /// - /// A new declaration with the dependency input and identity; this recipe is unchanged. - /// - /// - /// The dependency identity is empty. - /// - /// - /// The input is null. - /// - public NativeBuildRecipe WithDependency( - NativeBuildInput input, - string fingerprint - ) { - ArgumentNullException.ThrowIfNull(input); - ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); - return new(owner, component, targetId, inputs.Append(input), declarations.Append("dependency=" + fingerprint)) { toolchain = this.toolchain }; - } + internal NativeToolchainSelection? toolchain { get; private init; } /// /// Freezes the selected output bytes and generation identity into the executable recipe. @@ -205,18 +283,28 @@ NativeBindingGenerationDescriptor generation ) { IEnumerable generated = [NativeBuildInput.FromPath(engineRoot, generation.bindingsPath)]; if (generation.nativeDirectory.Length > 0) + { generated = generated.Append(NativeBuildInput.FromPath(engineRoot, generation.nativeDirectory)) .Concat(NativeBindingCompilation.Load(generation.nativeDirectory).GetInputs(engineRoot, generation.nativeDirectory)); - return new NativeBuildRecipe(owner, component, targetId, inputs.Concat(generated), + } + return new NativeBuildRecipe( + owner, + component, + targetID, + inputs.Concat(generated), declarations.Append("bindings=" + generation.fingerprint) - .Append("bindingNativeRoot=" + generation.nativeDirectory)) { toolchain = this.toolchain }; + .Append("bindingNativeRoot=" + generation.nativeDirectory) + ) { toolchain = toolchain }; } private static void ValidateSegment(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); - if (value is "." or ".." || value.Any(static character => !char.IsAsciiLetterOrDigit(character) - && character is not ('-' or '_' or '.'))) + if (value is "." or ".." || value.Any(static character => ( + !char.IsAsciiLetterOrDigit(character) + && character is not ('-' or '_' or '.') + ))) { throw new ArgumentException("Native component and target identities must be single path segments.", nameof(value)); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs index c014c93ee..2fc257b89 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs @@ -57,5 +57,4 @@ public sealed record NativeBuildStatistics /// Gets managed SDK processes started for generator extension preparation and managed input evaluation. /// public long managedProcesses { get; init; } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs index e715633f2..63938afcd 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs @@ -96,19 +96,28 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(componentArguments); ArgumentException.ThrowIfNullOrWhiteSpace(sourceDirectory); if (target is not null) + { ArgumentException.ThrowIfNullOrWhiteSpace(target); + } NativeToolchainSelection selection = context.RequireToolchain(); NativeComponentBuildOptions options = context.RequireComponentOptions(component); var reserved = new HashSet(StringComparer.Ordinal); foreach (string argument in componentArguments) { if (argument.StartsWith("-D", StringComparison.Ordinal) && argument.Contains('=')) + { reserved.Add(argument[2..argument.IndexOf('=')].Split(':')[0]); + } } foreach (string argument in options.cmakeArguments) { if (reserved.Contains(argument[2..argument.IndexOf('=')].Split(':')[0])) - throw new ArgumentException("Product configuration cannot override a recipe-owned component definition.", nameof(componentArguments)); + { + throw new ArgumentException( + "Product configuration cannot override a recipe-owned component definition.", + nameof(componentArguments) + ); + } } string buildType = context.configuration == "debug" ? "Debug" : "Release"; string buildDirectory = Path.Combine(context.GetNativeBuildRoot(component), "CMake"); @@ -117,9 +126,11 @@ CancellationToken cancellationToken configure.AddRange(selection.cmakeArguments.Select(sources.ResolveDefinition)); configure.AddRange((options.linkPlan ?? selection.linkPlan).cmakeArguments.Select(sources.ResolveDefinition)); configure.Add("-DINNO_ROOT=" + sources.root); - configure.Add("-DINNO_NATIVE_TARGET=" + selection.targetId); + configure.Add("-DINNO_NATIVE_TARGET=" + selection.targetID); if (!selection.multiConfiguration) + { configure.Add("-DCMAKE_BUILD_TYPE=" + buildType); + } configure.Add("-DINNO_LIBRARY_KIND=" + options.libraryKind.ToString().ToUpperInvariant()); configure.AddRange(componentArguments.Select(sources.ResolveDefinition)); configure.AddRange(options.cmakeArguments.Select(sources.ResolveDefinition)); @@ -128,10 +139,10 @@ CancellationToken cancellationToken Directory.CreateDirectory(buildDirectory); string requirements = Path.Combine(buildDirectory, "BindingInputs.cmake"); NativeBindingCMake.Write(context, sources, requirements, component, target, cancellationToken); - const string hook = "-DCMAKE_PROJECT_TOP_LEVEL_INCLUDES="; - string[] hooks = configure.Where(argument => argument.StartsWith(hook, StringComparison.Ordinal)).ToArray(); - configure.RemoveAll(argument => argument.StartsWith(hook, StringComparison.Ordinal)); - configure.Add(hook + string.Join(';', hooks.Select(argument => argument[hook.Length..]).Append(requirements))); + const string C_HOOK = "-DCMAKE_PROJECT_TOP_LEVEL_INCLUDES="; + string[] hooks = configure.Where(argument => argument.StartsWith(C_HOOK, StringComparison.Ordinal)).ToArray(); + configure.RemoveAll(argument => argument.StartsWith(C_HOOK, StringComparison.Ordinal)); + configure.Add(C_HOOK + string.Join(';', hooks.Select(argument => argument[C_HOOK.Length..]).Append(requirements))); } var environment = new Dictionary(selection.environment, StringComparer.Ordinal); if (selection.TryResolveExecutable("python", out _)) @@ -140,13 +151,27 @@ CancellationToken cancellationToken // A different SDK source identity selects another workspace and cannot reuse stale bytecode. environment["PYTHONPYCACHEPREFIX"] = Path.Combine(buildDirectory, "PythonCache"); } - await ToolchainEnvironment.RunAsync(context, selection.ResolveExecutable("cmake"), configure, - sources.root, cancellationToken, environment).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + context, + selection.ResolveExecutable("cmake"), + configure, + sources.root, + environment, + cancellationToken + ).ConfigureAwait(false); List build = ["--build", buildDirectory, "--config", buildType]; if (target is not null) + { build.AddRange(["--target", target]); - await ToolchainEnvironment.RunAsync(context, selection.ResolveExecutable("cmake"), build, - sources.root, cancellationToken, environment).ConfigureAwait(false); + } + await ToolchainEnvironment.RunAsync( + context, + selection.ResolveExecutable("cmake"), + build, + sources.root, + environment, + cancellationToken + ).ConfigureAwait(false); return buildDirectory; } @@ -177,10 +202,13 @@ string filePattern string buildType = context.configuration == "debug" ? "Debug" : "Release"; string[] candidates = Directory.EnumerateFiles(buildDirectory, filePattern, SearchOption.AllDirectories) .Where(path => !Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains("CMakeFiles")) - .Where(path => !selection.multiConfiguration - || Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains(buildType)) + .Where(path => ( + !selection.multiConfiguration + || Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains(buildType) + )) .ToArray(); - return candidates.Length == 1 ? candidates[0] - : throw new FileNotFoundException($"Expected one native output '{filePattern}' but found {candidates.Length}."); + return candidates.Length == 1 + ? candidates[0] + : throw new FileNotFoundException($"Expected one native output '{filePattern}' but found {candidates.Length}."); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs index ed48135c2..d92691596 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs @@ -33,13 +33,17 @@ PhysicalPathResolver resolver { string path = Path.GetFullPath(entry.physicalPath); while (GetSourceRelative(m_engineRoot, bindings, resolver, path) is string relative - && m_paths.TryAdd(path, relative)) - { + && m_paths.TryAdd(path, relative) + ) { // Keep the source spelling for verification and also accept its declared physical counterpart. if (!IsCheckoutPath(m_engineRoot, path) && bindings.ResolveRelative(path) is null) + { m_paths.TryAdd(resolver.Resolve(path), relative); + } if (relative == ".") + { break; + } path = Path.GetDirectoryName(path)!; } } @@ -70,12 +74,18 @@ public string ResolvePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A CMake input path must be absolute.", nameof(path)); + } string absolute = Path.GetFullPath(path); if (m_paths.TryGetValue(absolute, out string? relative)) + { return PathBoundary.Resolve(root, relative); + } if (!IsCheckoutPath(m_engineRoot, absolute) && m_bindings.ResolveRelative(absolute) is null) + { return absolute; + } throw new InvalidOperationException("A CMake source was not declared by the native recipe: " + absolute); } @@ -96,13 +106,17 @@ public string ResolveDefinition(string argument) ArgumentNullException.ThrowIfNull(argument); int separator = argument.IndexOf('='); if (!argument.StartsWith("-D", StringComparison.Ordinal) || separator < 0) + { return argument; + } string[] values = argument[(separator + 1)..].Split(';'); for (int index = 0; index < values.Length; index++) { string value = values[index]; if (Path.IsPathFullyQualified(value) && m_paths.ContainsKey(Path.GetFullPath(value))) + { values[index] = ResolvePath(value); + } } return argument[..(separator + 1)] + string.Join(';', values); } @@ -121,21 +135,30 @@ CancellationToken cancellationToken .GroupBy(static entry => entry.physicalPath, comparer) .Select(group => new NativeInputSnapshot.Entry( "engine/" + GetSourceRelative(context.engineRoot, bindings, resolver, group.Key)!.Replace('\\', '/'), - group.Key, group.First().hash)) - .OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray(); + group.Key, + group.First().hash + )) + .OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal) + .ToArray(); NativeInputSnapshot.Entry[] entries = declared.GroupBy(static entry => entry.logicalPath, comparer).Select(group => { NativeInputSnapshot.Entry first = group.First(); string physical = resolver.Resolve(first.physicalPath); if (group.Any(entry => resolver.Resolve(entry.physicalPath) != physical || !entry.hash.AsSpan().SequenceEqual(first.hash))) + { throw new InvalidOperationException("Native source aliases disagree about one copied workspace location."); + } return first; }).ToArray(); if (entries.Length == 0) + { throw new InvalidOperationException("The native recipe declares no checkout or selected binding inputs."); + } string root = Path.Combine(context.GetNativeBuildRoot(component), "Sources"); if (Directory.Exists(root) && IsComplete(context, root, entries, cancellationToken)) + { return new(context.engineRoot, root, declared, bindings, resolver); + } Directory.CreateDirectory(root); var expected = new HashSet(entries.Select(static entry => entry.logicalPath["engine/".Length..]), comparer); foreach (string file in PathBoundary.EnumerateFiles(root)) @@ -143,7 +166,9 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(root, file).Replace('\\', '/'); if (!expected.Contains(relative)) + { File.Delete(file); + } } foreach (NativeInputSnapshot.Entry entry in entries) { @@ -163,12 +188,16 @@ string path ) { string? binding = bindings.ResolveRelative(path); if (binding is not null) + { return binding; + } if (IsCheckoutPath(engineRoot, path)) + { return Path.GetRelativePath(engineRoot, path); + } string physical = resolver.Resolve(path); return bindings.ResolveRelative(physical) - ?? (IsCheckoutPath(engineRoot, physical) ? Path.GetRelativePath(engineRoot, physical) : null); + ?? (IsCheckoutPath(engineRoot, physical) ? Path.GetRelativePath(engineRoot, physical) : null); } private static bool IsCheckoutPath( @@ -177,7 +206,7 @@ string path ) { string relative = Path.GetRelativePath(engineRoot, path); return relative != ".." && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) - && !Path.IsPathRooted(relative); + && !Path.IsPathRooted(relative); } private static bool IsComplete( @@ -188,24 +217,35 @@ CancellationToken cancellationToken ) { string[] files = PathBoundary.EnumerateFiles(root).ToArray(); if (files.Length != expected.Count) + { return false; - NativeInputSnapshot actual = context.inputState.CaptureVerification(files.Select(path => - new NativeBuildInput("engine/" + Path.GetRelativePath(root, path).Replace('\\', '/'), path)), cancellationToken); + } + NativeInputSnapshot actual = context.inputState.CaptureVerification( + files.Select(path => + new NativeBuildInput("engine/" + Path.GetRelativePath(root, path).Replace('\\', '/'), path)), + cancellationToken + ); for (int index = 0; index < expected.Count; index++) { if (actual.entries[index].logicalPath != expected[index].logicalPath - || !actual.entries[index].hash.AsSpan().SequenceEqual(expected[index].hash)) + || !actual.entries[index].hash.AsSpan().SequenceEqual(expected[index].hash) + ) { return false; + } } return true; } + internal sealed class Preparation { private readonly object m_gate = new(); private readonly NativeInputSnapshot m_inputs; private Task? m_task; - internal Preparation(NativeInputSnapshot inputs) => m_inputs = inputs; + internal Preparation(NativeInputSnapshot inputs) + { + m_inputs = inputs; + } internal Task GetAsync( NativeBuildContext context, @@ -213,7 +253,9 @@ internal Task GetAsync( CancellationToken cancellationToken ) { lock (m_gate) + { return m_task ??= CreateAsync(context, component, m_inputs, cancellationToken); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs index 4c9da217f..7432b0f3f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs @@ -59,41 +59,50 @@ public NativeCompilerInputs( /// Gets the explicit C compiler, or null when unavailable. /// public string? cCompiler { get; } + /// /// Gets the explicit C++ compiler, or null when unavailable. /// public string? cppCompiler { get; } + /// /// Gets the target SDK root, or null when unnecessary. /// public string? sysRoot { get; } + /// /// Gets ordered SDK header directories. /// public IReadOnlyList systemIncludeDirectories { get; } + /// /// Gets ordered C++ standard library directories. /// public IReadOnlyList cppSystemIncludeDirectories { get; } + /// /// Gets ordered target definitions. /// public IReadOnlyList defines { get; } + /// /// Gets ordered target parser arguments. /// public IReadOnlyList arguments { get; } - internal IEnumerable declarations => new[] { "cCompiler=" + cCompiler, "cppCompiler=" + cppCompiler, "sysRoot=" + sysRoot } - .Concat(systemIncludeDirectories.Select(static path => "systemInclude=" + path)) - .Concat(cppSystemIncludeDirectories.Select(static path => "cppSystemInclude=" + path)) - .Concat(defines.Select(static value => "compilerDefine=" + value)) - .Concat(arguments.Select(static value => "compilerArgument=" + value)); + internal IEnumerable declarations + => new[] { "cCompiler=" + cCompiler, "cppCompiler=" + cppCompiler, "sysRoot=" + sysRoot } + .Concat(systemIncludeDirectories.Select(static path => "systemInclude=" + path)) + .Concat(cppSystemIncludeDirectories.Select(static path => "cppSystemInclude=" + path)) + .Concat(defines.Select(static value => "compilerDefine=" + value)) + .Concat(arguments.Select(static value => "compilerArgument=" + value)); private static string? Validate(string? path) { if (path is not null && (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("Native compiler inputs require explicit absolute paths.", nameof(path)); + } return path; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs index 7df645a16..67be166ae 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs @@ -5,28 +5,15 @@ namespace Inno.Build.Toolchains; -/// -/// Specifies the linkage required by a product's native component operation. -/// -public enum NativeLibraryKind -{ - /// - /// Produces archives for the selected final linker. - /// - Static, - - /// - /// Produces libraries loaded by the deployed product. - /// - Shared -} - /// /// Freezes product-owned linkage, ordered component definitions and their configuration inputs. /// public sealed class NativeComponentBuildOptions { - private static readonly Regex S_DEFINITION = new("^-D[A-Za-z_][A-Za-z0-9_]*(?::(?:BOOL|STRING|PATH|FILEPATH|INTERNAL))?=", RegexOptions.CultureInvariant); + private static readonly Regex DEFINITION = new( + "^-D[A-Za-z_][A-Za-z0-9_]*(?::(?:BOOL|STRING|PATH|FILEPATH|INTERNAL))?=", + RegexOptions.CultureInvariant + ); /// /// Captures component configuration without selecting an SDK or starting a build. @@ -40,15 +27,15 @@ public sealed class NativeComponentBuildOptions /// /// Portable checkout-relative configuration files included in content hashing and stability checks. /// - /// - /// Component-specific platform link settings, or null for the selected SDK plan. - /// /// /// The explicit native import identity, or null to retain the component identity. /// /// /// Additional checkout-relative binding headers owned by an integration. /// + /// + /// Component-specific platform link settings, or null for the selected SDK plan. + /// /// /// Linkage is invalid, definitions are ambiguous or override SDK selection, or an input escapes the checkout. /// @@ -61,25 +48,37 @@ public NativeComponentBuildOptions( NativeLinkPlan? linkPlan = null ) { if (!Enum.IsDefined(libraryKind)) + { throw new ArgumentException("A supported native library kind is required.", nameof(libraryKind)); + } string[] arguments = (cmakeArguments ?? []).ToArray(); var names = new HashSet(StringComparer.Ordinal); foreach (string argument in arguments) { - if (argument is null || !S_DEFINITION.IsMatch(argument) || argument.Contains('\0')) + if (argument is null || !DEFINITION.IsMatch(argument) || argument.Contains('\0')) + { throw new ArgumentException("Component arguments must be explicit CMake definitions.", nameof(cmakeArguments)); + } string name = argument[2..argument.IndexOf('=')].Split(':')[0]; if (name.StartsWith("CMAKE_", StringComparison.Ordinal) || name is "INNO_ROOT" or "INNO_NATIVE_TARGET" or "INNO_LIBRARY_KIND" || name.StartsWith("INNO_COMPONENT_", StringComparison.Ordinal) - || !names.Add(name)) - throw new ArgumentException("Component definitions must be unique and cannot override SDK or linkage selection.", nameof(cmakeArguments)); + || !names.Add(name) + ) { + throw new ArgumentException( + "Component definitions must be unique and cannot override SDK or linkage selection.", + nameof(cmakeArguments) + ); + } } string[] inputs = (inputPaths ?? []).Select(ValidatePath).Distinct(StringComparer.Ordinal).ToArray(); this.libraryKind = libraryKind; this.cmakeArguments = Array.AsReadOnly(arguments); this.inputPaths = Array.AsReadOnly(inputs); - if (bindingLibraryName is not null && (string.IsNullOrWhiteSpace(bindingLibraryName) || bindingLibraryName.IndexOfAny(['/', '\\', ':']) >= 0)) + if (bindingLibraryName is not null + && (string.IsNullOrWhiteSpace(bindingLibraryName) || bindingLibraryName.IndexOfAny(['/', '\\', ':']) >= 0) + ) { throw new ArgumentException("A binding import identity must be a library name.", nameof(bindingLibraryName)); + } this.bindingLibraryName = bindingLibraryName; this.linkPlan = linkPlan; this.bindingIncludeDirectories = Array.AsReadOnly((bindingIncludeDirectories ?? []).Select(ValidatePath).ToArray()); @@ -115,18 +114,36 @@ public NativeComponentBuildOptions( /// public IReadOnlyList bindingIncludeDirectories { get; } - internal IEnumerable declarations => new[] { "libraryKind=" + libraryKind } - .Concat(cmakeArguments.Select(static argument => "componentArgument=" + argument)) - .Concat(linkPlan?.declarations ?? []) - .Append("bindingLibrary=" + bindingLibraryName) - .Concat(bindingIncludeDirectories.Select(static path => "bindingInclude=" + path)); + internal IEnumerable declarations + => new[] { "libraryKind=" + libraryKind } + .Concat(cmakeArguments.Select(static argument => "componentArgument=" + argument)) + .Concat(linkPlan?.declarations ?? []) + .Append("bindingLibrary=" + bindingLibraryName) + .Concat(bindingIncludeDirectories.Select(static path => "bindingInclude=" + path)); private static string ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); string portable = path.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || portable.Split('/').Any(static segment => segment is "" or "." or "..")) + { throw new ArgumentException("A component input must be a portable checkout-relative path.", nameof(path)); + } return portable; } } + +/// +/// Specifies the linkage required by a product's native component operation. +/// +public enum NativeLibraryKind +{ + /// + /// Produces archives for the selected final linker. + /// + Static, + /// + /// Produces libraries loaded by the deployed product. + /// + Shared +} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs index ac52bb29e..e1707f8b5 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs @@ -39,17 +39,25 @@ public NativeComponentDescriptor( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (id is "." or "..") + { throw new ArgumentException("A component identity must be a portable path segment.", nameof(id)); + } foreach (char character in id) + { if (!char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.')) + { throw new ArgumentException("A component identity must be a portable path segment.", nameof(id)); + } + } this.id = id; this.nativeProject = ValidateProject(nativeProject); this.toolchainProject = ValidateProject(toolchainProject); this.staticBuild = staticBuild; if (bindingDefinition is not null && (bindingDefinition.StartsWith('/') || bindingDefinition.Contains(':') - || bindingDefinition.Split('/').Any(static segment => segment is "" or "." or ".."))) + || bindingDefinition.Split('/').Any(static segment => segment is "" or "." or "..")) + ) { throw new ArgumentException("A binding definition must remain within its checkout.", nameof(bindingDefinition)); + } this.bindingDefinition = bindingDefinition; } @@ -106,7 +114,9 @@ string project ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); if (!Path.IsPathFullyQualified(engineRoot)) + { throw new ArgumentException("The operation checkout must be absolute.", nameof(engineRoot)); + } return Path.GetDirectoryName(Path.GetFullPath(project, engineRoot))!; } @@ -115,10 +125,16 @@ private static string ValidateProject(string project) ArgumentException.ThrowIfNullOrWhiteSpace(project); string portable = project.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || !portable.EndsWith(".csproj", StringComparison.Ordinal)) + { throw new ArgumentException("A component owner must be a checkout-relative project file.", nameof(project)); + } foreach (string segment in portable.Split('/')) + { if (segment is "" or "." or "..") + { throw new ArgumentException("A component owner cannot escape its checkout.", nameof(project)); + } + } return portable; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs index e01d375dd..6905528bd 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs @@ -44,33 +44,46 @@ public static async ValueTask CopyAsync( ) { ArgumentNullException.ThrowIfNull(context); NativeBuildInput input = NativeBuildInput.FromPath(context.engineRoot, source); - NativeBuildInput output = new(input.logicalPath, destination); + var output = new NativeBuildInput(input.logicalPath, destination); cancellationToken.ThrowIfCancellationRequested(); byte[] expected = context.inputState.GetFrozenHash(input.physicalPath); if (File.Exists(destination)) { byte[] existing = context.inputState.CaptureVerification([output], cancellationToken).entries.Single().hash; if (expected.AsSpan().SequenceEqual(existing)) + { return false; + } } Directory.CreateDirectory(Path.GetDirectoryName(output.physicalPath)!); string candidate = output.physicalPath + ".staging-" + Guid.NewGuid().ToString("N"); try { await using (FileStream read = File.OpenRead(input.physicalPath)) - await using (FileStream write = new(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, - 64 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (var write = new FileStream( + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 64 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { await read.CopyToAsync(write, cancellationToken).ConfigureAwait(false); await write.FlushAsync(cancellationToken).ConfigureAwait(false); write.Flush(flushToDisk: true); } byte[] copied = context.inputState.CaptureVerification( - [new NativeBuildInput(input.logicalPath, candidate)], cancellationToken).entries.Single().hash; + [new NativeBuildInput(input.logicalPath, candidate)], + cancellationToken + ).entries.Single().hash; if (!expected.AsSpan().SequenceEqual(copied)) + { throw new InvalidOperationException($"Native input '{input.logicalPath}' changed during materialization."); + } if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(candidate, File.GetUnixFileMode(input.physicalPath)); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.Install(candidate, output.physicalPath); context.inputState.RecordMaterialization(new FileInfo(output.physicalPath).Length); @@ -79,7 +92,9 @@ public static async ValueTask CopyAsync( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs index 55926f297..fc325e977 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs @@ -35,30 +35,47 @@ internal NativeInputReadCache( internal StringComparer pathComparer => OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; internal byte[] GetFrozenHash(string path) - => m_hashes.TryGetValue(m_physicalPaths.Resolve(path), out byte[]? hash) ? hash - : throw new InvalidOperationException($"Native input '{path}' was not frozen by this operation's recipe."); + => m_hashes.TryGetValue(m_physicalPaths.Resolve(path), out byte[]? hash) + ? hash + : throw new InvalidOperationException($"Native input '{path}' was not frozen by this operation's recipe."); internal NativeInputSnapshot CaptureRecordedInputs(string engineRoot) - => new(m_readingPaths.Select(entry => new NativeInputSnapshot.Entry( - NativeBuildInput.FromPath(engineRoot, entry.Key).logicalPath, entry.Key, m_hashes[entry.Value]))); + => new( + m_readingPaths.Select(entry => new NativeInputSnapshot.Entry( + NativeBuildInput.FromPath(engineRoot, entry.Key).logicalPath, + entry.Key, + m_hashes[entry.Value] + )) + ); internal string[][] CaptureRootMembership() => m_roots.OrderBy(static pair => pair.Key, pathComparer) - .Select(pair => new[] { pair.Key }.Concat(pair.Value.Select(static entry => entry.relative).Order(StringComparer.Ordinal)).ToArray()).ToArray(); + .Select( + pair => new[] { pair.Key }.Concat(pair.Value.Select(static entry => entry.relative).Order(StringComparer.Ordinal)).ToArray() + ) + .ToArray(); internal IReadOnlyList<(string relative, string physical)> Enumerate( string path, CancellationToken cancellationToken ) { if (m_roots.TryGetValue(path, out IReadOnlyList<(string relative, string physical)>? cached)) + { return cached; + } List<(string relative, string physical)> files = []; if (File.Exists(path)) + { files.Add((string.Empty, path)); + } else if (Directory.Exists(path)) + { EnumerateDirectory(path, string.Empty, files, new HashSet(pathComparer), cancellationToken); + } else + { throw new FileNotFoundException("A declared native build input is unavailable.", path); + } cached = files.AsReadOnly(); m_roots.Add(path, cached); return cached; @@ -69,7 +86,7 @@ internal byte[][] Hash( CancellationToken cancellationToken ) { var physicalPaths = new string[paths.Count]; - var pending = new List(); + List pending = []; var unique = new HashSet(pathComparer); for (int index = 0; index < paths.Count; index++) { @@ -79,9 +96,13 @@ CancellationToken cancellationToken m_readingPaths[readingPath] = physical; physicalPaths[index] = physical; if (m_hashes.ContainsKey(physical) || !unique.Add(physical)) + { m_state.RecordReuse(m_phase); + } else + { pending.Add(physical); + } } var hashes = new byte[pending.Count][]; var bytes = new long[pending.Count]; @@ -90,26 +111,36 @@ CancellationToken cancellationToken try { if (pending.Count == 1) + { Read(0); + } else if (pending.Count > 1) - Parallel.For(0, pending.Count, new ParallelOptions - { - MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), - CancellationToken = cancellationToken - }, ( - index, - loop - ) => { - try + { + Parallel.For( + 0, + pending.Count, + new ParallelOptions { - Read(index); - } - catch (Exception exception) + MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), + CancellationToken = cancellationToken + }, + ( + index, + loop + ) => { - Interlocked.CompareExchange(ref failure, ExceptionDispatchInfo.Capture(exception), null); - loop.Stop(); + try + { + Read(index); + } + catch (Exception exception) + { + Interlocked.CompareExchange(ref failure, ExceptionDispatchInfo.Capture(exception), null); + loop.Stop(); + } } - }); + ); + } failure?.Throw(); cancellationToken.ThrowIfCancellationRequested(); } @@ -117,12 +148,18 @@ CancellationToken cancellationToken { // Initial capture holds the state gate. Workers only read bytes; record after all workers drain. for (int index = 0; index < pending.Count; index++) + { if (opened[index]) + { m_state.RecordHash(bytes[index], m_phase); + } + } } // Publish this batch only after every read succeeds; failed/canceled batches never become frozen inputs. for (int index = 0; index < pending.Count; index++) + { m_hashes.Add(pending[index], hashes[index]); + } return physicalPaths.Select(path => m_hashes[path]).ToArray(); void Read(int index) @@ -149,6 +186,7 @@ void Read(int index) } } } + private void EnumerateDirectory( string directory, string relativeRoot, @@ -159,20 +197,26 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); string physicalRoot = m_physicalPaths.Resolve(directory); if (!ancestors.Add(physicalRoot)) + { throw new IOException($"A native input contains a directory link cycle at '{directory}'."); + } try { foreach (string file in Directory.EnumerateFiles(physicalRoot)) { cancellationToken.ThrowIfCancellationRequested(); if (Path.GetFileName(file) != ".git") + { files.Add((relativeRoot + Path.GetFileName(file), Path.Combine(directory, Path.GetFileName(file)))); + } } foreach (string child in Directory.EnumerateDirectories(physicalRoot)) { string name = Path.GetFileName(child); if (name is ".git" or ".build" or "bin" or "obj" or "__pycache__") + { continue; + } EnumerateDirectory(Path.Combine(directory, name), relativeRoot + name + "/", files, ancestors, cancellationToken); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs index cd98b3cc1..5f757b523 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs @@ -7,14 +7,10 @@ namespace Inno.Build.Toolchains; internal sealed class NativeInputSnapshot { - internal sealed record Entry( - string logicalPath, - string physicalPath, - byte[] hash - ); - internal NativeInputSnapshot(IEnumerable entries) - => this.entries = Array.AsReadOnly(entries.OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray()); + { + this.entries = Array.AsReadOnly(entries.OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray()); + } internal IReadOnlyList entries { get; } @@ -23,7 +19,7 @@ internal static NativeInputSnapshot Capture( NativeInputReadCache cache, CancellationToken cancellationToken ) { - Dictionary paths = new(StringComparer.Ordinal); + var paths = new Dictionary(StringComparer.Ordinal); foreach (NativeBuildInput input in inputs) { cancellationToken.ThrowIfCancellationRequested(); @@ -33,17 +29,27 @@ CancellationToken cancellationToken if (paths.TryGetValue(logical, out string? previous)) { if (!cache.pathComparer.Equals(previous, physical)) + { throw new ArgumentException($"Native input identity '{logical}' maps to different reading locations."); + } continue; } paths.Add(logical, physical); } } - var ordered = paths.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); + KeyValuePair[] ordered = paths.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); byte[][] hashes = cache.Hash(ordered.Select(static pair => pair.Value).ToArray(), cancellationToken); - return new NativeInputSnapshot(ordered.Select(( - pair, - index - ) => new Entry(pair.Key, pair.Value, hashes[index]))); + return new NativeInputSnapshot( + ordered.Select(( + pair, + index + ) => new Entry(pair.Key, pair.Value, hashes[index])) + ); } + + internal sealed record Entry( + string logicalPath, + string physicalPath, + byte[] hash + ); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs index 89f50d906..be00878a1 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs @@ -11,13 +11,17 @@ internal sealed class NativeInputVerificationScope internal NativeInputVerificationScope( NativeBuildInputState state, string phase - ) => m_inputs = new NativeInputReadCache(state, phase); + ) { + m_inputs = new NativeInputReadCache(state, phase); + } internal NativeInputSnapshot Capture( IEnumerable inputs, CancellationToken cancellationToken ) { lock (m_gate) + { return NativeInputSnapshot.Capture(inputs, m_inputs, cancellationToken); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs index 9107e04fa..7b53770d2 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs @@ -34,15 +34,21 @@ public NativeLinkPlan( IEnumerable? cmakeArguments = null ) { if (sharedLibraryExtension is null && staticLibraryExtension is null) + { throw new ArgumentException("A linker plan must contribute at least one library format."); + } if (importLibraryExtension is not null && sharedLibraryExtension is null) + { throw new ArgumentException("Import libraries require a shared-library format.", nameof(importLibraryExtension)); + } this.sharedLibraryExtension = sharedLibraryExtension is null ? null : Validate(sharedLibraryExtension); this.importLibraryExtension = importLibraryExtension is null ? null : Validate(importLibraryExtension); this.staticLibraryExtension = staticLibraryExtension is null ? null : Validate(staticLibraryExtension); string[] arguments = (cmakeArguments ?? []).ToArray(); if (arguments.Any(static argument => argument is null)) + { throw new ArgumentException("Linker arguments cannot contain null entries.", nameof(cmakeArguments)); + } this.cmakeArguments = Array.AsReadOnly(arguments); } @@ -50,14 +56,17 @@ public NativeLinkPlan( /// Gets the shared-library suffix, or null when shared linkage is unsupported. /// public string? sharedLibraryExtension { get; } + /// /// Gets the separate import suffix, or null when no separate import library is used. /// public string? importLibraryExtension { get; } + /// /// Gets the static archive suffix, or null when static linkage is unavailable. /// public string? staticLibraryExtension { get; } + /// /// Gets ordered platform linker definitions. /// @@ -92,20 +101,28 @@ public NativeLinkPlan( /// /// The linkage kind is not defined. /// - public string GetFileExtension(NativeLibraryKind kind) => (kind switch - { - NativeLibraryKind.Shared => sharedLibraryExtension, - NativeLibraryKind.Static => staticLibraryExtension, - _ => throw new ArgumentOutOfRangeException(nameof(kind)) - }) ?? throw new NotSupportedException($"This target does not contribute '{kind}' linkage."); + public string GetFileExtension(NativeLibraryKind kind) + => (kind switch + { + NativeLibraryKind.Shared => sharedLibraryExtension, + NativeLibraryKind.Static => staticLibraryExtension, + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }) ?? throw new NotSupportedException($"This target does not contribute '{kind}' linkage."); - internal IEnumerable declarations => new[] { "sharedSuffix=" + sharedLibraryExtension, - "importSuffix=" + importLibraryExtension, "staticSuffix=" + staticLibraryExtension }.Concat(cmakeArguments); + internal IEnumerable declarations + => new[] + { + "sharedSuffix=" + sharedLibraryExtension, + "importSuffix=" + importLibraryExtension, + "staticSuffix=" + staticLibraryExtension + }.Concat(cmakeArguments); private static string Validate(string value) { if (string.IsNullOrWhiteSpace(value) || !value.StartsWith('.') || value.IndexOfAny(['/', '\\', ':']) >= 0) + { throw new ArgumentException("A native output format requires a file suffix.", nameof(value)); + } return value; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs index dc81c0d12..cff101aff 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs @@ -41,15 +41,22 @@ public NativeStaticBuildDefinition( this.cmakeFile = ValidatePath(cmakeFile); this.inputPaths = Array.AsReadOnly(inputPaths.Select(ValidatePath).Distinct(StringComparer.Ordinal).ToArray()); this.nativeSourceDirectory = nativeSourceDirectory is null ? null : ValidatePath(nativeSourceDirectory); - if (this.nativeSourceDirectory is not null && !this.inputPaths.Any(path => path == this.nativeSourceDirectory - || path.StartsWith(this.nativeSourceDirectory + "/", StringComparison.Ordinal))) - throw new ArgumentException("The native source root must contain declared static recipe inputs.", nameof(nativeSourceDirectory)); + if (this.nativeSourceDirectory is not null && !this.inputPaths.Any(path => ( + path == this.nativeSourceDirectory + || path.StartsWith(this.nativeSourceDirectory + "/", StringComparison.Ordinal) + ))) { + throw new ArgumentException( + "The native source root must contain declared static recipe inputs.", + nameof(nativeSourceDirectory) + ); + } string[] archives = logicalOutputs.Select(ValidatePath).ToArray(); if (archives.Length == 0 || archives.Any(static name => name.Contains('/')) - || archives.Distinct(StringComparer.OrdinalIgnoreCase).Count() != archives.Length) + || archives.Distinct(StringComparer.OrdinalIgnoreCase).Count() != archives.Length + ) { throw new ArgumentException("A static recipe requires unique portable archive file names.", nameof(logicalOutputs)); + } this.logicalOutputs = Array.AsReadOnly(archives); - } /// @@ -72,13 +79,14 @@ public NativeStaticBuildDefinition( /// public IReadOnlyList logicalOutputs { get; } - private static string ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); string portable = path.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || portable.Split('/').Any(static part => part is "" or "." or "..")) + { throw new ArgumentException("A static recipe path must remain within its declared root.", nameof(path)); + } return portable; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs index 98053fd57..1bc52092d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs @@ -11,7 +11,7 @@ namespace Inno.Build.Toolchains; /// public static class NativeToolchainPreparation { - private static readonly string[] AmbientCompilerVariables = + private static readonly string[] AMBIENT_COMPILER_VARIABLES = [ "CL", "_CL_", "LINK", "_LINK_", "CFLAGS", "CXXFLAGS", "CPPFLAGS", "LDFLAGS", "CPATH", "C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH", "LIBRARY_PATH", @@ -24,14 +24,18 @@ public static class NativeToolchainPreparation /// /// A caller-owned dictionary to populate with explicitly selected SDK variables. /// - public static Dictionary CreateEnvironment() => AmbientCompilerVariables.ToDictionary( - static variable => variable, static _ => string.Empty, StringComparer.OrdinalIgnoreCase); + public static Dictionary CreateEnvironment() + => AMBIENT_COMPILER_VARIABLES.ToDictionary( + static variable => variable, + static _ => string.Empty, + StringComparer.OrdinalIgnoreCase + ); /// /// Validates and freezes a provider's complete tool selection before product staging, /// including CMake data from its physical installation rather than a shared command prefix. /// - /// + /// /// The explicit requested target. /// /// @@ -49,12 +53,12 @@ public static Dictionary CreateEnvironment() => AmbientCompilerV /// /// Ordered target configuration arguments. /// - /// - /// Whether configuration is chosen during build. - /// /// /// The sole source of target library formats and linker capabilities. /// + /// + /// Whether configuration is chosen during build. + /// /// /// The selected SDK parser inputs, or null for a selection without parsing capability. /// @@ -68,7 +72,7 @@ public static Dictionary CreateEnvironment() => AmbientCompilerV /// A selected CMake executable alias cannot be resolved to its installation. /// public static NativeToolchainSelection Freeze( - string targetId, + string targetID, BuildHostDescriptor host, IReadOnlyDictionary tools, IReadOnlyDictionary environment, @@ -84,13 +88,28 @@ public static NativeToolchainSelection Freeze( string physicalCMake = new PhysicalPathResolver().Resolve(cmake); string modules = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(physicalCMake)!, "..", "share")); if (Directory.Exists(modules)) + { complete.Add(modules); + } } complete.AddRange(tools.Values); foreach (string input in complete) + { if (!File.Exists(input) && !Directory.Exists(input)) + { throw new FileNotFoundException("A selected native toolchain input is unavailable.", input); - return new(targetId, host, tools, environment, complete, cmakeArguments, - linkPlan, multiConfiguration, compilerInputs); + } + } + return new( + targetID, + host, + tools, + environment, + complete, + cmakeArguments, + linkPlan, + multiConfiguration, + compilerInputs + ); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs index 924cec27e..21ada75ab 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs @@ -16,7 +16,7 @@ public sealed class NativeToolchainSelection /// /// Captures an immutable, explicit compiler and SDK selection supplied by a platform provider. /// - /// + /// /// The exact native target identity. /// /// @@ -34,12 +34,12 @@ public sealed class NativeToolchainSelection /// /// Ordered configuration arguments pinning compiler, generator and SDK. /// - /// - /// Whether configuration is selected during build rather than configure. - /// /// /// The sole source of target library formats and linker capabilities. /// + /// + /// Whether configuration is selected during build rather than configure. + /// /// /// Explicit SDK parser inputs, or null when no native parser is provided. /// @@ -53,7 +53,7 @@ public sealed class NativeToolchainSelection /// A selected executable or SDK input is unavailable before preparation begins. /// public NativeToolchainSelection( - string targetId, + string targetID, BuildHostDescriptor host, IReadOnlyDictionary tools, IReadOnlyDictionary environment, @@ -63,56 +63,77 @@ public NativeToolchainSelection( bool multiConfiguration, NativeCompilerInputs? compilerInputs = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(tools); ArgumentNullException.ThrowIfNull(environment); ArgumentNullException.ThrowIfNull(inputPaths); ArgumentNullException.ThrowIfNull(cmakeArguments); ArgumentNullException.ThrowIfNull(linkPlan); - if (tools.Count == 0 || tools.Any(static entry => string.IsNullOrWhiteSpace(entry.Key) - || string.IsNullOrWhiteSpace(entry.Value) || !Path.IsPathFullyQualified(entry.Value))) + if (tools.Count == 0 || tools.Any(static entry => ( + string.IsNullOrWhiteSpace(entry.Key) + || string.IsNullOrWhiteSpace(entry.Value) || !Path.IsPathFullyQualified(entry.Value) + ))) { throw new ArgumentException("A native tool selection requires explicit executables.", nameof(tools)); + } string[] inputs = inputPaths.Concat(tools.Values).Distinct(StringComparer.Ordinal).ToArray(); string[] arguments = cmakeArguments.ToArray(); if (inputs.Any(static path => string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("Native SDK inputs require absolute locations.", nameof(inputPaths)); + } if (arguments.Any(static argument => argument is null)) + { throw new ArgumentException("CMake arguments cannot contain null entries.", nameof(cmakeArguments)); + } if (environment.Any(static entry => string.IsNullOrWhiteSpace(entry.Key) || entry.Value is null)) + { throw new ArgumentException("Native environments require assigned names and values.", nameof(environment)); + } foreach (string executable in tools.Values) + { if (!File.Exists(executable)) + { throw new FileNotFoundException("A selected native executable is unavailable.", executable); + } + } foreach (string input in inputs) + { if (!File.Exists(input) && !Directory.Exists(input)) + { throw new FileNotFoundException("A selected native SDK input is unavailable.", input); - this.targetId = targetId; + } + } + this.targetID = targetID; this.host = host; m_tools = new ReadOnlyDictionary(new Dictionary(tools, StringComparer.Ordinal)); this.environment = new ReadOnlyDictionary( - new Dictionary(environment, - host.services.environmentComparer)); + new Dictionary(environment, host.services.environmentComparer) + ); this.inputPaths = Array.AsReadOnly(inputs); this.cmakeArguments = Array.AsReadOnly(arguments); this.multiConfiguration = multiConfiguration; this.compilerInputs = compilerInputs ?? new NativeCompilerInputs(); this.linkPlan = linkPlan; - declarations = Array.AsReadOnly(this.environment.OrderBy(static entry => entry.Key, StringComparer.Ordinal) - .Select(static entry => entry.Key + "=" + entry.Value) - .Concat(m_tools.OrderBy(static entry => entry.Key, StringComparer.Ordinal) - .Select(static entry => entry.Key + "=" + entry.Value)) - .Concat(this.cmakeArguments) - .Concat(this.compilerInputs.declarations) - .Concat(this.linkPlan.declarations) - .Concat([targetId, host.system, host.architecture, multiConfiguration.ToString()]) - .ToArray()); + this.declarations = Array.AsReadOnly( + this.environment.OrderBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key + "=" + entry.Value) + .Concat( + m_tools.OrderBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key + "=" + entry.Value) + ) + .Concat(this.cmakeArguments) + .Concat(this.compilerInputs.declarations) + .Concat(this.linkPlan.declarations) + .Concat([targetID, host.system, host.architecture, multiConfiguration.ToString()]) + .ToArray() + ); } /// /// Gets the target identity, without inferring it from the execution host. /// - public string targetId { get; } + public string targetID { get; } /// /// Gets the declared tool execution host. @@ -190,11 +211,22 @@ IEnumerable inputs foreach ((string name, string executable) in tools) { if (combined.TryGetValue(name, out string? existing) && existing != executable) + { throw new ArgumentException($"Integration tool '{name}' conflicts with the frozen SDK selection.", nameof(tools)); + } combined[name] = executable; } - return new NativeToolchainSelection(targetId, host, combined, environment, inputPaths.Concat(inputs), - cmakeArguments, linkPlan, multiConfiguration, compilerInputs); + return new NativeToolchainSelection( + targetID, + host, + combined, + environment, + inputPaths.Concat(inputs), + cmakeArguments, + linkPlan, + multiConfiguration, + compilerInputs + ); } /// @@ -209,9 +241,10 @@ IEnumerable inputs /// /// The provider did not register the requested command. /// - public string ResolveExecutable(string name) => m_tools.TryGetValue(name, out string? executable) - ? executable - : throw new InvalidOperationException($"Native target '{targetId}' has no '{name}' executable."); + public string ResolveExecutable(string name) + => m_tools.TryGetValue(name, out string? executable) + ? executable + : throw new InvalidOperationException($"Native target '{targetID}' has no '{name}' executable."); /// /// Checks an optional tool capability without discovering a command from the process environment. diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs index c1c9eadfb..03867c98c 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs @@ -13,14 +13,22 @@ NativeInputSnapshot snapshot ) { string[] tools = (recipe.toolchain ?? context.toolchain)?.inputPaths.Select(Path.GetFullPath).ToArray() ?? []; StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var configuration = new NativeInputSnapshot(snapshot.entries.Where(entry => tools.Any(tool => - string.Equals(entry.physicalPath, tool, comparison) - || entry.physicalPath.StartsWith(Path.TrimEndingDirectorySeparator(tool) + Path.DirectorySeparatorChar, comparison)))); + var configuration = new NativeInputSnapshot( + snapshot.entries.Where(entry => tools.Any(tool => ( + string.Equals(entry.physicalPath, tool, comparison) + || entry.physicalPath.StartsWith(Path.TrimEndingDirectorySeparator(tool) + Path.DirectorySeparatorChar, comparison) + ))) + ); var bindings = new NativeBindingInputPaths(context); - return NativeBuildFingerprint.Create(recipe.declarations.Where(static value => - !value.StartsWith("bindings=", StringComparison.Ordinal)) - .Select(bindings.NormalizeDeclaration) - .Prepend("executionRoot=" + (context.toolchain?.host.services.workspaces.identity ?? "physical")) - .Prepend(context.configuration).Prepend(recipe.targetId).Prepend("workspace"), configuration); + return NativeBuildFingerprint.Create( + recipe.declarations + .Where(static value => !value.StartsWith("bindings=", StringComparison.Ordinal)) + .Select(bindings.NormalizeDeclaration) + .Prepend("executionRoot=" + (context.toolchain?.host.services.workspaces.identity ?? "physical")) + .Prepend(context.configuration) + .Prepend(recipe.targetID) + .Prepend("workspace"), + configuration + ); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs index bb890e988..e4db2a22d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs @@ -18,7 +18,7 @@ public sealed class ProductNativeBuildPlan /// /// Validates the complete ordered component graph before tools or staging can start. /// - /// + /// /// The product identity whose native closure is selected. /// /// @@ -34,21 +34,25 @@ public sealed class ProductNativeBuildPlan /// The step collection is null. /// public ProductNativeBuildPlan( - string productId, + string productID, IReadOnlyList steps, NativeDeploymentMetadataFactory? deploymentMetadata = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(productId); + ArgumentException.ThrowIfNullOrWhiteSpace(productID); ArgumentNullException.ThrowIfNull(steps); var completed = new HashSet(StringComparer.Ordinal); if (steps.Count == 0) + { throw new ArgumentException("A native product requires an explicit component closure.", nameof(steps)); + } foreach (ProductNativeBuildStep step in steps) { if (step is null || step.dependencies.Any(dependency => !completed.Contains(dependency)) || !completed.Add(step.id)) + { throw new ArgumentException("Native steps must be unique and ordered after every dependency.", nameof(steps)); + } } - this.productId = productId; + this.productID = productID; m_steps = steps.ToArray(); this.steps = Array.AsReadOnly(m_steps); this.deploymentMetadata = deploymentMetadata; @@ -57,7 +61,7 @@ public ProductNativeBuildPlan( /// /// Gets the explicit product identity. /// - public string productId { get; } + public string productID { get; } /// /// Gets the frozen dependency-ordered component closure. @@ -100,19 +104,28 @@ public IReadOnlyList CreateRecipes(NativeBuildContext context NativeBuildContext selected = configured.WithComponentOptions(step.component, step.options); NativeBuildRecipe recipe; if (step.createRecipe is not null) + { recipe = step.createRecipe(selected); + } else { NativeStaticBuildDefinition definition = step.component.staticBuild!; - recipe = NativeBuildRecipe.CreateForComponent(selected, step.component, step.id, tools.targetId, + recipe = NativeBuildRecipe.CreateForComponent( + selected, + step.component, + step.id, + tools.targetID, definition.inputPaths.Append(definition.cmakeFile).Select(path => Path.GetFullPath(path, context.engineRoot)), definition.logicalOutputs.Select(static archive => "archive=" + archive).Prepend("static=" + definition.cmakeFile), - [Path.GetFullPath(definition.cmakeFile, context.engineRoot)]); + [Path.GetFullPath(definition.cmakeFile, context.engineRoot)] + ); } - if (recipe is null || recipe.component != step.id || recipe.targetId != tools.targetId + if (recipe is null || recipe.component != step.id || recipe.targetID != tools.targetID || recipe.owner.nativeProject != step.component.nativeProject - || recipe.owner.toolchainProject != step.component.toolchainProject) + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign source declaration."); + } recipes.Add(recipe); } return recipes.AsReadOnly(); @@ -134,25 +147,33 @@ public IReadOnlyDictionary CreateDeploymentFiles(IReadOnlyList(StringComparer.OrdinalIgnoreCase); for (int index = 0; index < m_steps.Length; index++) { ProductNativeBuildStep step = m_steps[index]; NativeBuildProduct product = products[index]; if (step.id != product.component) + { throw new ArgumentException("The products do not match this plan's declaration order.", nameof(products)); + } foreach (string file in product.files) { string relative = Path.GetRelativePath(Path.Combine(product.directory, "Outputs"), file); - string? output = step.deploymentPath(relative, product.targetId); + string? output = step.deploymentPath(relative, product.targetID); if (output is null) + { continue; + } string portable = output.Replace('\\', '/'); if (Path.IsPathFullyQualified(portable) || portable.Contains(':') || portable.Split('/').Any(static segment => segment is "" or "." or "..") - || !files.TryAdd(portable.Replace('/', Path.DirectorySeparatorChar), file)) + || !files.TryAdd(portable.Replace('/', Path.DirectorySeparatorChar), file) + ) { throw new ArgumentException("Native deployment paths must be portable, contained and unique.", nameof(products)); + } } } return new ReadOnlyDictionary(files); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs index f28fe662d..70e337d3d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs @@ -72,7 +72,6 @@ public IReadOnlyDictionary bindingGen /// public NativeBuildRecipe? aggregateRecipe { get; } - /// /// Borrows a product whose lease is owned by this result until disposal. /// @@ -119,10 +118,14 @@ public IEnumerator GetEnumerator() public void Dispose() { if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { return; + } Release(m_products, m_bindings); } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + internal static void Release( IReadOnlyList products, NativeBindingGenerationResult bindings @@ -148,8 +151,8 @@ NativeBindingGenerationResult bindings failures.Add(failure); } if (failures.Count != 0) + { throw new AggregateException("Native product reading ownership could not be completely released.", failures); + } } - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs index 6b6fbd7ef..2b56be339 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs @@ -58,23 +58,41 @@ public ProductNativeBuildStep( Func? createRecipe, Func deploymentPath, string? configuration = null, - Func, NativeBuildRecipe>? bindDependencies = null + Func< + NativeBuildContext, + NativeBuildRecipe, + IReadOnlyDictionary, + NativeBuildRecipe + >? bindDependencies = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(options); if (build is null && options.libraryKind != NativeLibraryKind.Static) + { throw new ArgumentException("Aggregate-only steps require explicit static linkage.", nameof(options)); + } ArgumentNullException.ThrowIfNull(dependencies); if (build is null && component.staticBuild is null) + { throw new ArgumentException("Aggregate-only steps require a real static build definition.", nameof(build)); + } if ((build is null) != (createRecipe is null)) - throw new ArgumentException("A standalone producer requires its own source declaration; aggregate steps use their static definition.", nameof(createRecipe)); + { + throw new ArgumentException( + "A standalone producer requires its own source declaration; aggregate steps use their static definition.", + nameof(createRecipe) + ); + } ArgumentNullException.ThrowIfNull(deploymentPath); if (configuration is not null) + { ToolchainEnvironment.ValidateConfiguration(configuration); + } if (dependencies.Any(string.IsNullOrWhiteSpace) || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count) + { throw new ArgumentException("Component dependencies must be assigned and unique.", nameof(dependencies)); + } this.id = id; this.component = component; this.options = options; @@ -109,7 +127,12 @@ public ProductNativeBuildStep( /// /// Gets the standalone producer, or null for a component owned by a static aggregate executor. /// - public Func, CancellationToken, Task>? build { get; } + public Func< + NativeBuildContext, + IReadOnlyDictionary, + CancellationToken, + Task + >? build { get; } /// /// Gets the producer's source declaration, or null when a static aggregate owns the component recipe. @@ -131,5 +154,10 @@ public ProductNativeBuildStep( /// Gets the backend-owned dependency transformation, or null for an independent source recipe. /// The supplied products are borrowed only during recipe construction. /// - public Func, NativeBuildRecipe>? bindDependencies { get; } + public Func< + NativeBuildContext, + NativeBuildRecipe, + IReadOnlyDictionary, + NativeBuildRecipe + >? bindDependencies { get; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs index d58aa2b89..b9c3b2986 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs @@ -13,102 +13,184 @@ internal static class ProductNativeCacheLookup internal static async Task?> TryAcquireAsync( NativeBuildContext context, IReadOnlyList steps, - CancellationToken cancellation + CancellationToken cancellationToken ) { - if (steps.Any(static step => step.createRecipe is null - || step.dependencies.Count != 0 && step.bindDependencies is null)) + if (steps.Any(static step => ( + step.createRecipe is null + || step.dependencies.Count != 0 && step.bindDependencies is null + ))) { return null; - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(context.engineRoot, "artifacts", "native"), "native", cache.role, cancellation); - var activities = new List(); - var ownership = new List(); + } + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(context.engineRoot, "artifacts", "native"), + "native", + cache.role, + cancellationToken + ); + List activities = []; + List ownership = []; var products = new Dictionary(StringComparer.Ordinal); - var candidates = new List(); + List candidates = []; bool transferred = false; try { - activities.Add(await cache.AcquireUseAsync(cancellation).ConfigureAwait(false)); + activities.Add(await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false)); foreach (string root in steps.Select(step => Path.Combine(step.component.GetToolchainRoot(context.engineRoot), "obj", "native")) - .Distinct(PathComparer).Order(PathComparer)) - activities.Add(await new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace) - .AcquireUseAsync(cancellation).ConfigureAwait(false)); + .Distinct(pathComparer) + .Order(pathComparer) + ) { + activities.Add( + await new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace) + .AcquireUseAsync(cancellationToken) + .ConfigureAwait(false) + ); + } foreach (ProductNativeBuildStep step in steps) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); NativeBuildContext selected = (step.configuration is string configuration - ? context.WithConfiguration(configuration) : context).WithComponentOptions(step.component, step.options); + ? context.WithConfiguration(configuration) + : context).WithComponentOptions(step.component, step.options); NativeBuildRecipe recipe = step.createRecipe!(selected); - if (recipe.component != step.id || recipe.targetId != context.RequireToolchain().targetId - || recipe.owner.nativeProject != step.component.nativeProject || recipe.owner.toolchainProject != step.component.toolchainProject) + if (recipe.component != step.id || recipe.targetID != context.RequireToolchain().targetID + || recipe.owner.nativeProject != step.component.nativeProject + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign source declaration."); + } if (step.bindDependencies is not null) + { recipe = step.bindDependencies(selected, recipe, products); - if (recipe.component != step.id || recipe.targetId != context.RequireToolchain().targetId - || recipe.owner.nativeProject != step.component.nativeProject || recipe.owner.toolchainProject != step.component.toolchainProject) + } + if (recipe.component != step.id || recipe.targetID != context.RequireToolchain().targetID + || recipe.owner.nativeProject != step.component.nativeProject + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign dependency declaration."); - NativeBindingGenerationDescriptor? binding = step.component.bindingDefinition is null ? null : selected.RequireBindings(step.component); + } + NativeBindingGenerationDescriptor? binding = step.component.bindingDefinition is null + ? null + : selected.RequireBindings(step.component); if (binding is not null) + { recipe = recipe.WithBindingGeneration(context.engineRoot, binding); - NativeInputSnapshot snapshot = context.inputState.CaptureInitial(recipe.inputs, cancellation); + } + NativeInputSnapshot snapshot = context.inputState.CaptureInitial(recipe.inputs, cancellationToken); string fingerprint = NativeBuildFingerprint.Create(recipe.declarations, snapshot); string identity = NativeWorkspaceIdentity.Create(selected, recipe, snapshot); - string workspace = selected.WithIdentity(step.component, recipe.targetId, identity).GetNativeBuildRoot(step.component); - string directory = Path.Combine(context.engineRoot, "artifacts", "native", step.id, recipe.targetId, fingerprint); + string workspace = selected.WithIdentity(step.component, recipe.targetID, identity).GetNativeBuildRoot(step.component); + string directory = Path.Combine(context.engineRoot, "artifacts", "native", step.id, recipe.targetID, fingerprint); var candidate = new Candidate(selected, recipe, fingerprint, directory, workspace, binding); - NativeBuildProduct? product = await AcquireProduct(candidate, cancellation).ConfigureAwait(false); + NativeBuildProduct? product = await AcquireProductAsync(candidate, cancellationToken).ConfigureAwait(false); if (product is null) + { return null; + } products.Add(step.id, product); candidates.Add(candidate); } // Preliminary readers freeze dependency selection. Release them before waiting for // compiler ownership, so repair holding a workspace never waits for this batch's reader. foreach (NativeBuildProduct product in products.Values) + { product.Dispose(); + } products.Clear(); - foreach (string workspace in candidates.Select(static candidate => candidate.workspace).Distinct(PathComparer).Order(PathComparer)) - ownership.Add(await FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)); + foreach (string workspace in candidates + .Select(static candidate => candidate.workspace) + .Distinct(pathComparer) + .Order(pathComparer) + ) { + ownership.Add( + await FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false) + ); + } foreach (Candidate candidate in candidates) { - NativeBuildProduct? product = await AcquireProduct(candidate, cancellation).ConfigureAwait(false); + NativeBuildProduct? product = await AcquireProductAsync(candidate, cancellationToken).ConfigureAwait(false); if (product is null) + { return null; + } products.Add(candidate.recipe.component, product); } NativeBuildContext verification = context.BeginInputVerification("native-product-lock"); foreach (Candidate candidate in candidates) - if (NativeBuildFingerprint.Create(verification, candidate.recipe.declarations, candidate.recipe.inputs, cancellation) != candidate.fingerprint) - throw new InvalidOperationException($"Native inputs for '{candidate.recipe.component}' changed during product ownership acquisition."); + { + if (NativeBuildFingerprint.Create( + verification, + candidate.recipe.declarations, + candidate.recipe.inputs, + cancellationToken + ) != candidate.fingerprint + ) { + throw new InvalidOperationException( + $"Native inputs for '{candidate.recipe.component}' changed during product ownership acquisition." + ); + } + } foreach (Candidate candidate in candidates) - cache.Record(candidate.directory, candidate.directory + ".read.lock", + { + cache.Record( + candidate.directory, + candidate.directory + ".read.lock", candidate.binding is { artifactDirectory.Length: > 0 } ? [candidate.binding.artifactDirectory] : [], - candidate.recipe.component + "/" + candidate.recipe.targetId + "/" + candidate.context.configuration, - candidate.recipe.targetId, cancellation); + candidate.recipe.component + "/" + candidate.recipe.targetID + "/" + candidate.context.configuration, + candidate.recipe.targetID, + cancellationToken + ); + } transferred = true; return steps.Select(step => products[step.id]).ToArray(); } finally { if (!transferred) + { foreach (NativeBuildProduct product in products.Values) + { product.Dispose(); + } + } for (int index = ownership.Count - 1; index >= 0; index--) + { ownership[index].Dispose(); + } for (int index = activities.Count - 1; index >= 0; index--) + { activities[index].Dispose(); + } } } - private static StringComparer PathComparer => OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + private static StringComparer pathComparer => OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; - private static async ValueTask AcquireProduct( + private static async ValueTask AcquireProductAsync( Candidate candidate, - CancellationToken cancellation + CancellationToken cancellationToken ) { - BuildArtifactReadLease? reading = await BuildArtifactReadLease.TryAcquireAsync(candidate.directory, Path.Combine(candidate.context.engineRoot, "artifacts", "native"), - candidate.fingerprint, ["Outputs", "Metadata"], candidate.context, cancellation).ConfigureAwait(false); - return reading is null ? null : new NativeBuildProduct(candidate.recipe.component, candidate.recipe.targetId, - candidate.fingerprint, candidate.directory, candidate.binding, candidate.context.RequireToolchain().linkPlan.sharedLibraryExtension, reading); + BuildArtifactReadLease? reading = await BuildArtifactReadLease.TryAcquireAsync( + candidate.directory, + Path.Combine(candidate.context.engineRoot, "artifacts", "native"), + candidate.fingerprint, + ["Outputs", "Metadata"], + candidate.context, + cancellationToken + ).ConfigureAwait(false); + return reading is null ? null : new NativeBuildProduct( + candidate.recipe.component, + candidate.recipe.targetID, + candidate.fingerprint, + candidate.directory, + candidate.binding, + candidate.context.RequireToolchain().linkPlan.sharedLibraryExtension, + reading + ); } private sealed record Candidate( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs index 8e505b085..3dd82dcc8 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs @@ -21,6 +21,12 @@ public static class ProductNativeDeployment /// Validated runtime and optional authoring products returned by the declared product plan. /// All products must use the same target; each component can appear once. /// + /// + /// The explicit component closure and deployment mapping used to produce these products. + /// + /// + /// The managed output directory receiving the complete native tree. + /// /// /// Cancels ownership acquisition or staging before the atomic installation starts. /// @@ -28,12 +34,6 @@ public static class ProductNativeDeployment /// Completion after the complete native tree has been validated under exclusive publication ownership. /// Identical deployments retain their files, including libraries loaded by a running application. /// - /// - /// The explicit component closure and deployment mapping used to produce these products. - /// - /// - /// The managed output directory receiving the complete native tree. - /// /// /// The product closure is empty, contains duplicate components or mixes targets. /// @@ -68,10 +68,6 @@ public static ValueTask InstallAsync( /// /// Completion after copying and verifying payload, without creating transaction metadata in the candidate. /// - /// - /// The caller must retain exclusive ownership and discard the entire candidate on failure or cancellation. - /// This operation neither selects a publication nor replaces an existing native tree. - /// /// /// The product closure or candidate path is invalid. /// @@ -84,6 +80,10 @@ public static ValueTask InstallAsync( /// /// Cancellation prevents completing the unpublished candidate. /// + /// + /// The caller must retain exclusive ownership and discard the entire candidate on failure or cancellation. + /// This operation neither selects a publication nor replaces an existing native tree. + /// public static ValueTask StageAsync( IReadOnlyList products, ProductNativeBuildPlan plan, @@ -103,36 +103,52 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); NativeBuildProduct[] closure = products.ToArray(); if (closure.Length == 0 || closure.Any(static product => product is null) - || closure.Select(static product => product.targetId).Distinct().Count() != 1 - || closure.Select(static product => product.component).Distinct().Count() != closure.Length) - throw new ArgumentException("Native deployment requires a nonempty closure of unique components for one target.", nameof(products)); + || closure.Select(static product => product.targetID).Distinct().Count() != 1 + || closure.Select(static product => product.component).Distinct().Count() != closure.Length + ) { + throw new ArgumentException( + "Native deployment requires a nonempty closure of unique components for one target.", + nameof(products) + ); + } string destination = Path.Combine(Path.GetFullPath(applicationDirectory), "native"); if (ownedCandidate) { if (!Directory.Exists(applicationDirectory)) + { throw new DirectoryNotFoundException("Native staging requires an existing caller-owned candidate."); + } PathBoundary.RequireUnlinkedPath(Path.GetFullPath(applicationDirectory), destination); if (Directory.Exists(destination) || File.Exists(destination)) + { throw new IOException("Native staging requires a candidate without a native subtree."); + } } - using FileLease? ownership = ownedCandidate ? null : await FileLease.AcquireAsync(destination + ".lock", - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease? ownership = ownedCandidate ? null : await FileLease.AcquireAsync( + destination + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ValidateProducts(closure, cancellationToken); IReadOnlyDictionary files = plan.CreateDeploymentFiles(closure); IReadOnlyDictionary contributed = plan.deploymentMetadata?.Invoke(closure, files) - ?? new Dictionary(); + ?? new Dictionary(); var metadata = new Dictionary(StringComparer.Ordinal); StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; - var payloadPaths = files.Keys.Select(relative => PathBoundary.Resolve(destination, relative)).ToHashSet(paths); + HashSet payloadPaths = files.Keys.Select(relative => PathBoundary.Resolve(destination, relative)).ToHashSet(paths); var metadataPaths = new HashSet(paths); foreach ((string relative, byte[] content) in contributed) { if (string.IsNullOrWhiteSpace(relative) || relative.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + { throw new InvalidDataException("Native deployment metadata must use literal relative file paths."); + } string path = PathBoundary.Resolve(destination, relative); if (payloadPaths.Contains(path) || !metadataPaths.Add(path)) + { throw new InvalidDataException("Native deployment metadata cannot replace a payload file."); + } metadata.Add(relative, content?.ToArray() ?? throw new InvalidDataException("Native deployment metadata has no bytes.")); } if (!ownedCandidate && HasSameFiles(destination, files, metadata, cancellationToken)) @@ -141,11 +157,14 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); return; } - using ProcessOwnedDirectory? stagingOwner = ownedCandidate ? null + using ProcessOwnedDirectory? stagingOwner = ownedCandidate + ? null : await ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellationToken).ConfigureAwait(false); string staging = stagingOwner?.directory ?? destination; if (ownedCandidate) + { Directory.CreateDirectory(staging); + } try { foreach ((string relative, string file) in files) @@ -154,10 +173,14 @@ CancellationToken cancellationToken string output = Path.Combine(staging, relative); Directory.CreateDirectory(Path.GetDirectoryName(output)!); await using (FileStream source = File.OpenRead(file)) - await using (FileStream target = new(output, FileMode.CreateNew)) + await using (var target = new FileStream(output, FileMode.CreateNew)) + { await source.CopyToAsync(target, cancellationToken).ConfigureAwait(false); + } if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(output, File.GetUnixFileMode(file)); + } } foreach ((string relative, byte[] bytes) in metadata) { @@ -170,7 +193,9 @@ CancellationToken cancellationToken try { if (!ownedCandidate) + { AtomicDirectory.Install(staging, destination); + } } catch (DirectoryCleanupException cleanupFailure) { @@ -191,7 +216,9 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!BuildArtifactManifest.IsComplete(product.directory, product.fingerprint, ["Outputs", "Metadata"])) + { throw new InvalidDataException($"Native product '{product.component}' changed after publication."); + } } } @@ -202,7 +229,9 @@ private static bool HasSameFiles( CancellationToken cancellationToken ) { if (!Directory.Exists(directory)) + { return false; + } int count = 0; foreach (string deployed in PathBoundary.EnumerateFiles(directory)) { @@ -211,19 +240,27 @@ CancellationToken cancellationToken if (metadata.TryGetValue(relative, out byte[]? bytes)) { if (!File.ReadAllBytes(deployed).AsSpan().SequenceEqual(bytes)) + { return false; + } count++; continue; } if (!files.TryGetValue(relative, out string? source) - || new FileInfo(deployed).Length != new FileInfo(source).Length) + || new FileInfo(deployed).Length != new FileInfo(source).Length + ) { return false; + } using FileStream deployedStream = File.OpenRead(deployed); using FileStream sourceStream = File.OpenRead(source); if (!SHA256.HashData(deployedStream).AsSpan().SequenceEqual(SHA256.HashData(sourceStream))) + { return false; + } if (!OperatingSystem.IsWindows() && File.GetUnixFileMode(deployed) != File.GetUnixFileMode(source)) + { return false; + } count++; } cancellationToken.ThrowIfCancellationRequested(); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs index 9ebba5c3d..b57928fbe 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs @@ -39,26 +39,47 @@ public static async Task FreezeAsync( ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(plan); NativeToolchainSelection tools = context.RequireToolchain(); - var identities = new List - { - NativeBuildFingerprint.Create(context, tools.declarations, - tools.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), cancellationToken) - }; + List identities = [NativeBuildFingerprint.Create( + context, + tools.declarations, + tools.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), + cancellationToken + )]; foreach (NativeBuildRecipe recipe in plan.CreateRecipes(context)) + { identities.Add(NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellationToken)); + } NativeComponentDescriptor[] components = plan.steps.Select(static step => step.component) - .Where(static component => component.bindingDefinition is not null).DistinctBy(static component => component.nativeProject).ToArray(); + .Where(static component => component.bindingDefinition is not null) + .DistinctBy(static component => component.nativeProject) + .ToArray(); if (components.Length != 0) { - var options = plan.steps.Where(static step => step.component.bindingDefinition is not null) + Dictionary options = plan.steps + .Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal); - var request = new NativeBindingGenerationRequest(components, tools.targetId, NativeBindingOutputMode.TargetArtifacts, componentOptions: options); - identities.Add(await context.RequireBindingGenerator().ComputeInputFingerprintAsync(context, request, cancellationToken).ConfigureAwait(false)); + var request = new NativeBindingGenerationRequest( + components, + tools.targetID, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: options + ); + identities.Add( + await context + .RequireBindingGenerator() + .ComputeInputFingerprintAsync(context, request, cancellationToken) + .ConfigureAwait(false) + ); } - IEnumerable declarations = new[] { context.engineRoot, context.configuration, plan.productId, tools.targetId } - .Concat(tools.environment.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Key + "=" + pair.Value)) - .Concat(tools.cmakeArguments).Concat(tools.inputPaths) + IEnumerable declarations = new[] { context.engineRoot, context.configuration, plan.productID, tools.targetID } + .Concat( + tools.environment + .OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value) + ) + .Concat(tools.cmakeArguments) + .Concat(tools.inputPaths) .Concat(plan.steps.Select(static step => step.id + "|" + step.configuration + "|" + JsonSerializer.Serialize(step.options))) .Concat(identities); return NativeBuildFingerprint.Create(declarations, []); @@ -94,21 +115,40 @@ string requestIdentity ArgumentNullException.ThrowIfNull(products); ArgumentException.ThrowIfNullOrWhiteSpace(requestIdentity); if (products.aggregateDirectory is not null || products.Count != plan.steps.Count - || products.Any(static product => product.bindingGeneration is { artifactDirectory.Length: 0 })) + || products.Any(static product => product.bindingGeneration is { artifactDirectory.Length: 0 }) + ) { return null; - var rows = new List { new[] { "request", requestIdentity } }; + } + List rows = [new[] { "request", requestIdentity }]; foreach (NativeInputSnapshot.Entry input in context.inputState.CaptureRecordedInputs(context.engineRoot).entries) + { rows.Add(["input", input.physicalPath, Convert.ToHexStringLower(input.hash)]); + } foreach (string[] root in context.inputState.CaptureRootMembership()) + { rows.Add(["root", ..root]); + } for (int index = 0; index < products.Count; index++) { NativeBuildProduct product = products[index]; if (product.component != plan.steps[index].id) + { throw new ArgumentException("The prepared products do not match their declaration order.", nameof(products)); - rows.Add(["product", product.component, product.targetId, product.fingerprint, product.directory, product.sharedLibraryExtension ?? string.Empty]); + } + rows.Add( + [ + "product", + product.component, + product.targetID, + product.fingerprint, + product.directory, + product.sharedLibraryExtension ?? string.Empty + ] + ); if (product.bindingGeneration is NativeBindingGenerationDescriptor binding) + { rows.Add(["binding", product.component, plan.steps[index].component.nativeProject, JsonSerializer.Serialize(binding)]); + } } return rows.ToArray(); } @@ -150,12 +190,16 @@ string requestIdentity ArgumentNullException.ThrowIfNull(rows); ArgumentException.ThrowIfNullOrWhiteSpace(requestIdentity); cancellationToken.ThrowIfCancellationRequested(); - if (rows.Length == 0 || rows.Any(static row => row is null || row.Length == 0 - || row[0] is not ("request" or "input" or "root" or "product" or "binding")) - || rows[0].Length != 2 || rows[0][0] != "request" || rows[0][1] != requestIdentity) + if (rows.Length == 0 || rows.Any(static row => ( + row is null || row.Length == 0 + || row[0] is not ("request" or "input" or "root" or "product" or "binding") + )) + || rows[0].Length != 2 || rows[0][0] != "request" || rows[0][1] != requestIdentity + ) { return null; - var products = new List(); - var leases = new List(); + } + List products = []; + List leases = []; var generations = new Dictionary(StringComparer.Ordinal); var byComponent = new Dictionary(StringComparer.Ordinal); bool transferred = false; @@ -164,79 +208,139 @@ string requestIdentity foreach (string[] row in rows.Where(static row => row[0] == "binding")) { if (row.Length != 4) + { return null; + } NativeBindingGenerationDescriptor? binding = JsonSerializer.Deserialize(row[3]); if (binding is null || string.IsNullOrEmpty(binding.artifactDirectory)) + { return null; + } binding.Validate(); BuildCacheCleanupPlan.RequireChild(context.engineRoot, binding.artifactOwnerDirectory); if (!generations.TryGetValue(row[2], out NativeBindingGenerationDescriptor? shared)) { - BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync(binding.artifactDirectory, - binding.artifactOwnerDirectory, binding.fingerprint, ["Generated", "Native"], context, cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync( + binding.artifactDirectory, + binding.artifactOwnerDirectory, + binding.fingerprint, + ["Generated", "Native"], + context, + cancellationToken + ).ConfigureAwait(false); if (lease is null) + { return null; + } leases.Add(lease); generations.Add(row[2], binding); } else if (JsonSerializer.Serialize(shared) != row[3]) + { return null; + } byComponent.Add(row[1], binding); } string[][] productRows = rows.Where(static row => row[0] == "product").ToArray(); if (productRows.Length != plan.steps.Count) + { return null; + } for (int index = 0; index < productRows.Length; index++) { string[] row = productRows[index]; - if (row.Length != 6 || row[1] != plan.steps[index].id || row[2] != context.RequireToolchain().targetId) + if (row.Length != 6 || row[1] != plan.steps[index].id || row[2] != context.RequireToolchain().targetID) + { return null; + } string owner = Path.Combine(context.engineRoot, "artifacts", "native"); - BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync(row[4], owner, row[3], - ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync( + row[4], + owner, + row[3], + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false); if (lease is null) + { return null; - products.Add(new NativeBuildProduct(row[1], row[2], row[3], row[4], byComponent.GetValueOrDefault(row[1]), - row[5].Length == 0 ? null : row[5], lease)); + } + products.Add( + new NativeBuildProduct( + row[1], + row[2], + row[3], + row[4], + byComponent.GetValueOrDefault(row[1]), + row[5].Length == 0 ? null : row[5], + lease + ) + ); } NativeBuildContext verification = context.BeginInputVerification("prepared-consumer"); if (await FreezeAsync(verification, plan, cancellationToken).ConfigureAwait(false) != requestIdentity) + { return null; + } foreach (string[] row in rows.Where(static row => row[0] == "root")) { if (row.Length < 2) + { return null; + } NativeBuildInput root = NativeBuildInput.FromPath(context.engineRoot, row[1]); NativeInputSnapshot membership = verification.CaptureInputs([root], cancellationToken); - if (!membership.entries.Select(entry => entry.logicalPath == root.logicalPath - ? string.Empty : entry.logicalPath[(root.logicalPath.Length + 1)..]) - .Order(StringComparer.Ordinal).SequenceEqual(row.Skip(2), StringComparer.Ordinal)) + if (!membership.entries + .Select(entry => ( + entry.logicalPath == root.logicalPath + ? string.Empty + : entry.logicalPath[(root.logicalPath.Length + 1)..] + )) + .Order(StringComparer.Ordinal) + .SequenceEqual(row.Skip(2), StringComparer.Ordinal) + ) { return null; + } } foreach (string[] row in rows.Where(static row => row[0] == "input")) { if (row.Length != 3) + { return null; - NativeInputSnapshot input = verification.CaptureInputs([NativeBuildInput.FromPath(context.engineRoot, row[1])], cancellationToken); + } + NativeInputSnapshot input = verification.CaptureInputs( + [NativeBuildInput.FromPath(context.engineRoot, row[1])], + cancellationToken + ); if (input.entries.Count != 1 || Convert.ToHexStringLower(input.entries[0].hash) != row[2]) + { return null; + } } if (!rows.Any(static row => row[0] == "input")) + { return null; + } cancellationToken.ThrowIfCancellationRequested(); var bindings = new NativeBindingGenerationResult(generations, leases); var result = new ProductNativeBuildResult(products, bindings); transferred = true; return result; } - catch (Exception failure) when (failure is FileNotFoundException or DirectoryNotFoundException or InvalidDataException or JsonException) + catch (Exception failure) when (failure is FileNotFoundException + or DirectoryNotFoundException + or InvalidDataException + or JsonException) { return null; } finally { if (!transferred) + { ProductNativeBuildResult.Release(products, new NativeBindingGenerationResult(generations, leases)); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs index 7ffe6ebf8..dd05b859f 100644 --- a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs +++ b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs @@ -1,7 +1,8 @@ using System; -using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.IO; +using System.Threading; using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -12,17 +13,22 @@ namespace Inno.Build.Toolchains; /// public sealed class NativeBuildContext { + private static readonly ReadOnlyDictionary NO_BINDINGS = new( + new Dictionary() + ); + private readonly NativeBuildInputState m_inputState; + private readonly string? m_buildOwner; + private readonly string? m_targetID; + private readonly string? m_fingerprint; + private readonly string? m_toolDirectory; private INativeBindingGenerator? m_bindingGenerator; private NativeInputVerificationScope? m_verification; private NativeComponentDescriptor? m_component; private NativeComponentBuildOptions? m_componentOptions; - private readonly string? m_buildOwner; - private readonly string? m_targetId; - private readonly string? m_fingerprint; - private readonly string? m_toolDirectory; - private IReadOnlyDictionary m_bindings = - new ReadOnlyDictionary(new Dictionary()); + + private IReadOnlyDictionary m_bindings = NO_BINDINGS; + /// /// Creates a build context without consulting the tool assembly's checkout. /// @@ -44,62 +50,66 @@ public sealed class NativeBuildContext public NativeBuildContext( string engineRoot, string configuration - ) : this(ResolveRoot(engineRoot, configuration), configuration, new NativeBuildInputState()) { } - - private NativeBuildContext( - string engineRoot, - string configuration, - NativeBuildInputState inputState - ) { - ToolchainEnvironment.ValidateConfiguration(configuration); - this.engineRoot = engineRoot; - if (!File.Exists(Path.Combine(this.engineRoot, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) - throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{this.engineRoot}'."); - this.configuration = configuration; - m_inputState = inputState; - } + ) : this(ResolveRoot(engineRoot, configuration), configuration, new NativeBuildInputState()) {} private NativeBuildContext( NativeBuildContext origin, - string buildOwner, - string targetId, - string fingerprint - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + NativeToolchainSelection toolchain + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; m_componentOptions = origin.m_componentOptions; - m_buildOwner = buildOwner; - m_targetId = targetId; - m_fingerprint = fingerprint; - toolchain = origin.toolchain; + this.toolchain = toolchain; m_bindings = origin.m_bindings; + m_buildOwner = origin.m_buildOwner; + m_targetID = origin.m_targetID; + m_fingerprint = origin.m_fingerprint; + m_toolDirectory = origin.m_toolDirectory; } private NativeBuildContext( NativeBuildContext origin, - NativeToolchainSelection toolchain - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + string? toolDirectory + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; m_componentOptions = origin.m_componentOptions; - this.toolchain = toolchain; - m_bindings = origin.m_bindings; m_buildOwner = origin.m_buildOwner; - m_targetId = origin.m_targetId; + m_targetID = origin.m_targetID; m_fingerprint = origin.m_fingerprint; - m_toolDirectory = origin.m_toolDirectory; + this.toolchain = origin.toolchain; + m_toolDirectory = toolDirectory; + m_bindings = origin.m_bindings; + } + + private NativeBuildContext( + string engineRoot, + string configuration, + NativeBuildInputState inputState + ) { + ToolchainEnvironment.ValidateConfiguration(configuration); + this.engineRoot = engineRoot; + if (!File.Exists(Path.Combine(this.engineRoot, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) + { + throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{this.engineRoot}'."); + } + this.configuration = configuration; + m_inputState = inputState; } private NativeBuildContext( NativeBuildContext origin, string configuration, NativeToolchainSelection? toolchain - ) : this(origin.engineRoot, configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + ) : this(origin.engineRoot, configuration, origin.m_inputState) + { + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; @@ -108,39 +118,41 @@ private NativeBuildContext( m_bindings = origin.m_bindings; } - private NativeBuildContext( NativeBuildContext origin, NativeComponentDescriptor component, NativeComponentBuildOptions options - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = component; m_componentOptions = options; m_buildOwner = origin.m_buildOwner; - m_targetId = origin.m_targetId; + m_targetID = origin.m_targetID; m_fingerprint = origin.m_fingerprint; m_toolDirectory = origin.m_toolDirectory; - toolchain = origin.toolchain; + this.toolchain = origin.toolchain; m_bindings = origin.m_bindings; } private NativeBuildContext( NativeBuildContext origin, - string? toolDirectory - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + string buildOwner, + string targetID, + string fingerprint + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; m_componentOptions = origin.m_componentOptions; - m_buildOwner = origin.m_buildOwner; - m_targetId = origin.m_targetId; - m_fingerprint = origin.m_fingerprint; - toolchain = origin.toolchain; - m_toolDirectory = toolDirectory; + m_buildOwner = buildOwner; + m_targetID = targetID; + m_fingerprint = fingerprint; + this.toolchain = origin.toolchain; m_bindings = origin.m_bindings; } @@ -160,6 +172,11 @@ private NativeBuildContext( /// public NativeToolchainSelection? toolchain { get; } + /// + /// Gets actual hashing and native execution work accumulated by this operation and its scoped contexts. + /// + public NativeBuildStatistics statistics => m_inputState.statistics; + /// /// Resolves native intermediates under the owning toolchain project in this checkout. /// @@ -183,26 +200,21 @@ public string GetNativeBuildRoot(NativeComponentDescriptor component) string projectRoot = component.GetToolchainRoot(engineRoot); string projectName = Path.GetFileNameWithoutExtension(component.toolchainProject); if (!File.Exists(Path.Combine(projectRoot, projectName + ".csproj"))) + { throw new InvalidOperationException($"Native build owner '{projectName}' is unavailable in '{engineRoot}'."); + } string root = Path.Combine(projectRoot, "obj", "native"); if (m_buildOwner is null) + { return root; + } if (component.toolchainProject != m_buildOwner) + { throw new InvalidOperationException($"The native operation belongs to '{m_buildOwner}', not '{projectName}'."); - return m_toolDirectory ?? Path.Combine(root, m_targetId!, m_fingerprint!); + } + return m_toolDirectory ?? Path.Combine(root, m_targetID!, m_fingerprint!); } - /// - /// Gets actual hashing and native execution work accumulated by this operation and its scoped contexts. - /// - public NativeBuildStatistics statistics => m_inputState.statistics; - - internal NativeBuildInputState inputState => m_inputState; - - internal IReadOnlyDictionary selectedBindings => m_bindings; - - internal NativeCMakeSource.Preparation? sourcePreparation { get; private set; } - /// /// Records one complete binding batch executed by the borrowed provider. /// @@ -226,12 +238,6 @@ public string GetNativeBuildRoot(NativeComponentDescriptor component) /// public void RecordManagedProcess() => m_inputState.RecordManagedProcess(); - internal NativeBuildContext WithIdentity( - NativeComponentDescriptor owner, - string targetId, - string fingerprint - ) => new(this, owner.toolchainProject, targetId, fingerprint); - /// /// Attaches a provider's immutable tool selection while preserving this operation's input ownership. /// @@ -264,7 +270,6 @@ public NativeBuildContext WithToolchain(NativeToolchainSelection toolchain) /// public NativeBuildContext WithConfiguration(string configuration) => new(this, configuration, toolchain); - /// /// Requires an explicit selection before a component can build or start a native tool. /// @@ -274,8 +279,9 @@ public NativeBuildContext WithToolchain(NativeToolchainSelection toolchain) /// /// Composition has not resolved a toolchain. /// - public NativeToolchainSelection RequireToolchain() => toolchain - ?? throw new InvalidOperationException("Native composition must provide an explicit target toolchain before building."); + public NativeToolchainSelection RequireToolchain() + => toolchain + ?? throw new InvalidOperationException("Native composition must provide an explicit target toolchain before building."); /// /// Scopes one component's explicit product configuration without changing the frozen SDK. @@ -317,8 +323,9 @@ public NativeComponentBuildOptions RequireComponentOptions(NativeComponentDescri { ArgumentNullException.ThrowIfNull(component); return m_component?.nativeProject == component.nativeProject - && m_component.toolchainProject == component.toolchainProject && m_componentOptions is not null - ? m_componentOptions : throw new InvalidOperationException("The native component requires explicit product configuration."); + && m_component.toolchainProject == component.toolchainProject && m_componentOptions is not null + ? m_componentOptions + : throw new InvalidOperationException("The native component requires explicit product configuration."); } /// @@ -353,9 +360,10 @@ public NativeBuildContext WithBindings(NativeBindingGenerationResult bindings) /// /// The caller released the borrowed binding result before this operation finished. /// - public NativeBindingGenerationDescriptor RequireBindings(NativeComponentDescriptor component) => - m_bindings.TryGetValue(component.nativeProject, out NativeBindingGenerationDescriptor? generation) - ? generation : throw new InvalidOperationException($"No target binding generation was prepared for '{component.nativeProject}'."); + public NativeBindingGenerationDescriptor RequireBindings(NativeComponentDescriptor component) + => m_bindings.TryGetValue(component.nativeProject, out NativeBindingGenerationDescriptor? generation) + ? generation + : throw new InvalidOperationException($"No target binding generation was prepared for '{component.nativeProject}'."); /// /// Borrows a generator while preserving this operation's input and tool ownership. @@ -383,8 +391,9 @@ public NativeBuildContext WithBindingGenerator(INativeBindingGenerator generator /// /// Composition has not supplied a binding generator. /// - public INativeBindingGenerator RequireBindingGenerator() => m_bindingGenerator - ?? throw new InvalidOperationException("Native composition must provide a binding generator."); + public INativeBindingGenerator RequireBindingGenerator() + => m_bindingGenerator + ?? throw new InvalidOperationException("Native composition must provide a binding generator."); /// /// Starts a fresh verification phase whose reads can be shared only within this derived context. @@ -406,11 +415,23 @@ public NativeBuildContext BeginInputVerification(string phase) return scoped; } + internal NativeBuildInputState inputState => m_inputState; + + internal IReadOnlyDictionary selectedBindings => m_bindings; + + internal NativeCMakeSource.Preparation? sourcePreparation { get; private set; } + + internal NativeBuildContext WithIdentity( + NativeComponentDescriptor owner, + string targetID, + string fingerprint + ) => new(this, owner.toolchainProject, targetID, fingerprint); + internal NativeInputSnapshot CaptureInputs( IEnumerable inputs, - System.Threading.CancellationToken cancellationToken + CancellationToken cancellationToken ) => m_verification?.Capture(inputs, cancellationToken) - ?? m_inputState.CaptureInitial(inputs, cancellationToken); + ?? m_inputState.CaptureInitial(inputs, cancellationToken); internal NativeBuildContext WithToolDirectory(string toolDirectory) => new(this, toolDirectory); @@ -429,7 +450,9 @@ string configuration ToolchainEnvironment.ValidateConfiguration(configuration); string root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(engineRoot)); if (!File.Exists(Path.Combine(root, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) + { throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{root}'."); + } return new PhysicalPathResolver().Resolve(root); } } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs index 35fc8c16e..6780053bf 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; - namespace Inno.Build.Toolchains; /// @@ -15,52 +14,45 @@ namespace Inno.Build.Toolchains; public static class ToolchainEnvironment { /// - /// Executes a declared absolute tool with an explicitly resolved SDK environment and records the operation cost. + /// Runs a child build using a complete argument string, without a shell. /// - /// - /// The operation owning execution statistics and frozen recipe inputs. - /// /// - /// The absolute executable declared by the recipe; no host-native SDK is inferred. + /// The executable resolved by the host operating system. /// /// - /// Individual arguments passed without shell interpretation. + /// Arguments quoted for the selected executable's command-line parser. /// /// - /// The owned source or intermediate directory. + /// The directory owned by the operation. /// /// - /// Cancels execution and drains the complete process tree. - /// - /// - /// The frozen environment supplied by the selected SDK resolver. + /// Cancels the complete process tree and waits for output to finish draining. /// /// - /// Completion after successful exit and output delivery. + /// Completion after successful exit; failures and cancellation propagate. /// - /// - /// The executable is not an absolute declared tool path. - /// /// /// The process fails to start or exits unsuccessfully. /// /// - /// Execution was canceled. + /// The operation was canceled. + /// + /// + /// Redirected output cannot be read or forwarded; the process tree is terminated before failure returns. /// public static Task RunAsync( - NativeBuildContext context, string fileName, - IReadOnlyList arguments, + string arguments, string workingDirectory, - CancellationToken cancellationToken, - IReadOnlyDictionary environment + CancellationToken cancellationToken ) { - ArgumentNullException.ThrowIfNull(context); - ArgumentNullException.ThrowIfNull(environment); - if (!Path.IsPathFullyQualified(fileName)) - throw new ArgumentException("An explicit SDK tool must have an absolute path.", nameof(fileName)); - context.inputState.RecordProcess(); - return RunAsync(fileName, arguments, workingDirectory, cancellationToken, CaptureEnvironmentOverrides(environment)); + Console.WriteLine($"> {fileName} {arguments}"); + var start = new ProcessStartInfo(fileName) + { + Arguments = arguments, + WorkingDirectory = workingDirectory + }; + return RunProcessAsync(start, cancellationToken, null, Console.Out); } /// @@ -98,7 +90,7 @@ public static Task RunAsync( CancellationToken cancellationToken ) { NativeToolchainSelection tools = context.toolchain - ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); + ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); string executable = Path.IsPathFullyQualified(fileName) ? fileName : tools.ResolveExecutable(fileName); context.inputState.RecordProcess(); return RunAsync(executable, arguments, workingDirectory, cancellationToken, CaptureEnvironmentOverrides(tools.environment)); @@ -139,49 +131,13 @@ public static Task RunAsync( CancellationToken cancellationToken ) { NativeToolchainSelection tools = context.toolchain - ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); + ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); string executable = Path.IsPathFullyQualified(fileName) ? fileName : tools.ResolveExecutable(fileName); var start = new ProcessStartInfo(executable) { Arguments = arguments, WorkingDirectory = workingDirectory }; context.inputState.RecordProcess(); return RunProcessAsync(start, cancellationToken, CaptureEnvironmentOverrides(tools.environment), Console.Out); } - /// - /// Resolves one explicitly selected executable before it becomes a build input. - /// - /// - /// An executable path or a command name available on the current process PATH. - /// - /// - /// The absolute executable path used for process execution and artifact identity. - /// - /// - /// The name is empty. - /// - /// - /// The executable is unavailable at the supplied path or on PATH. - /// - public static string ResolveExecutable(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - if (File.Exists(name)) - return Path.GetFullPath(name); - if (Path.IsPathRooted(name) || name.Contains(Path.DirectorySeparatorChar) - || name.Contains(Path.AltDirectorySeparatorChar)) - throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); - - string fileName = OperatingSystem.IsWindows() && !Path.HasExtension(name) ? name + ".exe" : name; - foreach (string directory in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(directory)) - continue; - string candidate = Path.Combine(directory.Trim('"'), fileName); - if (File.Exists(candidate)) - return Path.GetFullPath(candidate); - } - throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); - } - /// /// Runs a child build with structured arguments, cancellation and hidden windows. /// @@ -219,7 +175,58 @@ public static Task RunAsync( string workingDirectory, CancellationToken cancellationToken, IReadOnlyDictionary? environment = null - ) => RunCoreAsync(fileName, arguments, workingDirectory, cancellationToken, environment, Console.Out); + ) => RunCoreAsync(fileName, arguments, workingDirectory, environment, Console.Out, cancellationToken); + + /// + /// Executes a declared absolute tool with an explicitly resolved SDK environment and records the operation cost. + /// + /// + /// The operation owning execution statistics and frozen recipe inputs. + /// + /// + /// The absolute executable declared by the recipe; no host-native SDK is inferred. + /// + /// + /// Individual arguments passed without shell interpretation. + /// + /// + /// The owned source or intermediate directory. + /// + /// + /// The frozen environment supplied by the selected SDK resolver. + /// + /// + /// Cancels execution and drains the complete process tree. + /// + /// + /// Completion after successful exit and output delivery. + /// + /// + /// The executable is not an absolute declared tool path. + /// + /// + /// The process fails to start or exits unsuccessfully. + /// + /// + /// Execution was canceled. + /// + public static Task RunAsync( + NativeBuildContext context, + string fileName, + IReadOnlyList arguments, + string workingDirectory, + IReadOnlyDictionary environment, + CancellationToken cancellationToken + ) { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(environment); + if (!Path.IsPathFullyQualified(fileName)) + { + throw new ArgumentException("An explicit SDK tool must have an absolute path.", nameof(fileName)); + } + context.inputState.RecordProcess(); + return RunAsync(fileName, arguments, workingDirectory, cancellationToken, CaptureEnvironmentOverrides(environment)); + } /// /// Runs a child build with caller-owned output destinations and the shared process retirement protocol. @@ -233,9 +240,6 @@ public static Task RunAsync( /// /// The project directory controlling SDK and workload resolution. /// - /// - /// Cancels the complete process tree and drains both output streams. - /// /// /// Optional child-only toolchain variables. Null values remove inherited variables; /// empty values remain explicitly empty. @@ -246,6 +250,9 @@ public static Task RunAsync( /// /// The caller-owned standard error destination; the runner does not dispose it. /// + /// + /// Cancels the complete process tree and drains both output streams. + /// /// /// Completion after successful exit and complete output delivery; failures propagate. /// @@ -262,19 +269,87 @@ public static Task RunAsync( string fileName, IReadOnlyList arguments, string workingDirectory, - CancellationToken cancellationToken, IReadOnlyDictionary? environment, TextWriter standardOutput, - TextWriter standardError + TextWriter standardError, + CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(standardOutput); ArgumentNullException.ThrowIfNull(standardError); var start = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } return RunProcessAsync(start, cancellationToken, environment, standardOutput, standardError); } + /// + /// Resolves one explicitly selected executable before it becomes a build input. + /// + /// + /// An executable path or a command name available on the current process PATH. + /// + /// + /// The absolute executable path used for process execution and artifact identity. + /// + /// + /// The name is empty. + /// + /// + /// The executable is unavailable at the supplied path or on PATH. + /// + public static string ResolveExecutable(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + if (File.Exists(name)) + { + return Path.GetFullPath(name); + } + if (Path.IsPathRooted(name) || name.Contains(Path.DirectorySeparatorChar) + || name.Contains(Path.AltDirectorySeparatorChar) + ) { + throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); + } + + string fileName = OperatingSystem.IsWindows() && !Path.HasExtension(name) ? name + ".exe" : name; + foreach (string directory in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator)) + { + if (string.IsNullOrWhiteSpace(directory)) + { + continue; + } + string candidate = Path.Combine(directory.Trim('"'), fileName); + if (File.Exists(candidate)) + { + return Path.GetFullPath(candidate); + } + } + throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); + } + + /// + /// Captures platform tool discovery through the same cancellable process lifecycle as builds. + /// + /// + /// The prepared discovery command, including any platform-specific argument quoting. + /// + /// + /// Cancels discovery and waits for its process tree to exit. + /// + /// + /// Complete standard output after successful discovery; errors and cancellation propagate. + /// + public static async Task CaptureOutputAsync( + ProcessStartInfo start, + CancellationToken cancellationToken + ) { + ArgumentNullException.ThrowIfNull(start); + using var output = new StringWriter(); + await RunProcessAsync(start, cancellationToken, null, output).ConfigureAwait(false); + return output.ToString(); + } + /// /// Captures a tool's standard output while forwarding errors and preserving the common process lifecycle. /// @@ -316,7 +391,7 @@ public static async Task CaptureOutputAsync( using var output = new StringWriter(); try { - await RunCoreAsync(fileName, arguments, workingDirectory, cancellationToken, environment, output).ConfigureAwait(false); + await RunCoreAsync(fileName, arguments, workingDirectory, environment, output, cancellationToken).ConfigureAwait(false); } catch (InvalidOperationException failure) { @@ -337,7 +412,9 @@ public static async Task CaptureOutputAsync( public static void ValidateConfiguration(string configuration) { if (configuration is not (ToolchainLayout.C_DEBUG_CONFIGURATION or ToolchainLayout.C_RELEASE_CONFIGURATION)) + { throw new ArgumentException("Native configuration must be 'debug' or 'release'.", nameof(configuration)); + } } /// @@ -353,8 +430,8 @@ public static string FindRepoRoot() { string location = typeof(ToolchainEnvironment).Assembly.Location; string outputRoot = string.IsNullOrEmpty(location) ? AppContext.BaseDirectory : Path.GetDirectoryName(location)!; - var dir = new DirectoryInfo(outputRoot); - while (dir != null) + DirectoryInfo? dir = new DirectoryInfo(outputRoot); + while (dir is not null) { if (File.Exists(Path.Combine(dir.FullName, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) { @@ -367,48 +444,6 @@ public static string FindRepoRoot() throw new InvalidOperationException("Could not locate repo root (InnoEngine.sln not found)."); } - /// - /// Runs a child build using a complete argument string, without a shell. - /// - /// - /// The executable resolved by the host operating system. - /// - /// - /// Arguments quoted for the selected executable's command-line parser. - /// - /// - /// The directory owned by the operation. - /// - /// - /// Cancels the complete process tree and waits for output to finish draining. - /// - /// - /// Completion after successful exit; failures and cancellation propagate. - /// - /// - /// The process fails to start or exits unsuccessfully. - /// - /// - /// The operation was canceled. - /// - /// - /// Redirected output cannot be read or forwarded; the process tree is terminated before failure returns. - /// - public static Task RunAsync( - string fileName, - string arguments, - string workingDirectory, - CancellationToken cancellationToken - ) { - Console.WriteLine($"> {fileName} {arguments}"); - var start = new ProcessStartInfo(fileName) - { - Arguments = arguments, - WorkingDirectory = workingDirectory - }; - return RunProcessAsync(start, cancellationToken, null, Console.Out); - } - /// /// Determines whether a value contains at least one token without regard to casing. /// @@ -425,7 +460,7 @@ public static bool ContainsAny( string value, params string[] needles ) { - foreach (var needle in needles) + foreach (string needle in needles) { if (value.Contains(needle, StringComparison.OrdinalIgnoreCase)) { @@ -452,9 +487,9 @@ public static string NormalizeOutputName( string fileName, string config ) { - var ext = Path.GetExtension(fileName); - var baseName = Path.GetFileNameWithoutExtension(fileName); - var trimmed = TrimConfigSuffix(baseName); + string ext = Path.GetExtension(fileName); + string baseName = Path.GetFileNameWithoutExtension(fileName); + string trimmed = TrimConfigSuffix(baseName); return $"{trimmed}-{config}{ext}"; } @@ -504,28 +539,6 @@ public static void DeleteDirectory(string path) } } - /// - /// Captures platform tool discovery through the same cancellable process lifecycle as builds. - /// - /// - /// The prepared discovery command, including any platform-specific argument quoting. - /// - /// - /// Cancels discovery and waits for its process tree to exit. - /// - /// - /// Complete standard output after successful discovery; errors and cancellation propagate. - /// - public static async Task CaptureOutputAsync( - ProcessStartInfo start, - CancellationToken cancellationToken - ) { - ArgumentNullException.ThrowIfNull(start); - using var output = new StringWriter(); - await RunProcessAsync(start, cancellationToken, null, output).ConfigureAwait(false); - return output.ToString(); - } - private static IReadOnlyDictionary CaptureEnvironmentOverrides(IReadOnlyDictionary environment) => environment.ToDictionary(static entry => entry.Key, static entry => (string?)entry.Value, StringComparer.OrdinalIgnoreCase); @@ -533,13 +546,15 @@ private static async Task RunCoreAsync( string fileName, IReadOnlyList arguments, string workingDirectory, - CancellationToken cancellationToken, IReadOnlyDictionary? environment, - TextWriter standardOutput + TextWriter standardOutput, + CancellationToken cancellationToken ) { var start = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } await RunProcessAsync(start, cancellationToken, environment, standardOutput).ConfigureAwait(false); } @@ -556,23 +571,31 @@ private static async Task RunProcessAsync( start.RedirectStandardError = true; start.CreateNoWindow = true; if (environment is not null) + { foreach ((string name, string? value) in environment) { if (value is null) + { start.Environment.Remove(name); + } else + { start.Environment[name] = value; + } } + } cancellationToken.ThrowIfCancellationRequested(); using var process = new Process { StartInfo = start }; if (!process.Start()) + { throw new InvalidOperationException($"Cannot start '{start.FileName}'."); + } Task output = ForwardAsync(process.StandardOutput, standardOutput); Task error = ForwardAsync(process.StandardError, standardError ?? Console.Error); Task exited = process.WaitForExitAsync(cancellationToken); try { - var pending = new List { exited, output, error }; + List pending = [exited, output, error]; while (pending.Count > 0) { Task completed = await Task.WhenAny(pending).ConfigureAwait(false); @@ -585,7 +608,9 @@ private static async Task RunProcessAsync( try { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } } catch (InvalidOperationException) when (process.HasExited) { @@ -596,14 +621,16 @@ private static async Task RunProcessAsync( { await Task.WhenAll(exited, output, error).ConfigureAwait(false); } - catch + catch (Exception) { // Observe all pumps while preserving the failure that initiated process cleanup. } throw; } if (process.ExitCode != 0) + { throw new InvalidOperationException($"'{start.FileName}' failed with exit code {process.ExitCode}."); + } } private static async Task ForwardAsync( @@ -611,6 +638,8 @@ private static async Task ForwardAsync( TextWriter destination ) { while (await source.ReadLineAsync().ConfigureAwait(false) is { } line) + { await destination.WriteLineAsync(line).ConfigureAwait(false); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs index 9ab70acd8..2dcc3e0d8 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs @@ -28,7 +28,9 @@ public ToolchainWorkingDirectory( IDisposable? ownership = null ) { if (!Path.IsPathFullyQualified(toolPath)) + { throw new ArgumentException("Tool execution paths must be absolute.", nameof(toolPath)); + } this.toolPath = toolPath; m_ownership = ownership; } diff --git a/entry/InnoEngine.Build/Program.cs b/entry/InnoEngine.Build/Program.cs index 3d3d70ab7..dbac61d86 100644 --- a/entry/InnoEngine.Build/Program.cs +++ b/entry/InnoEngine.Build/Program.cs @@ -23,7 +23,7 @@ private static async Task Main(string[] arguments) Console.CancelKeyPress += onCancel; try { - return await BuildApplication.Run(CreateArguments(arguments), cancellation.Token).ConfigureAwait(false); + return await BuildApplication.RunAsync(CreateArguments(arguments), cancellation.Token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -43,17 +43,23 @@ private static async Task Main(string[] arguments) private static string[] CreateArguments(string[] arguments) { if (arguments.Length > 0 && arguments[0] is "help" or "--help" or "-h") + { return arguments; + } bool implicitSupport = arguments.Length == 0 || arguments[0].StartsWith("--", StringComparison.Ordinal); - var result = new List { implicitSupport ? "support" : arguments[0] }; + List result = [implicitSupport ? "support" : arguments[0]]; result.AddRange(implicitSupport ? arguments : arguments[1..]); if (result[0] is not ("support" or "editor" or "clean" or "bindings" or "support-pack" or "shader")) + { return result.ToArray(); + } string target = ReadDevelopmentTarget(); int scope = result.IndexOf("--scope"); bool allCaches = result[0] == "clean" && scope >= 0 && scope + 1 < result.Count && result[scope + 1] == "cache"; if (!allCaches) + { AddDefault(result, "--target", target); + } AddDefault(result, "--tools-target", target); string configuration = typeof(Program).Assembly.GetCustomAttribute()!.Configuration; AddDefault(result, "--configuration", result[0] is "support" or "editor" or "clean" ? configuration : "Release"); @@ -63,8 +69,12 @@ private static string[] CreateArguments(string[] arguments) private static string ReadDevelopmentTarget() { foreach (AssemblyMetadataAttribute metadata in typeof(Program).Assembly.GetCustomAttributes()) + { if (metadata.Key == "Inno.Build.DevelopmentTarget" && !string.IsNullOrWhiteSpace(metadata.Value)) + { return metadata.Value; + } + } throw new PlatformNotSupportedException("No build host is registered for the selected SDK."); } @@ -74,7 +84,9 @@ private static void AddDefault( string value ) { if (arguments.Contains(name)) + { return; + } arguments.Add(name); arguments.Add(value); } diff --git a/entry/InnoEngine.Editor/Program.cs b/entry/InnoEngine.Editor/Program.cs index 19a783c83..7cc23b419 100644 --- a/entry/InnoEngine.Editor/Program.cs +++ b/entry/InnoEngine.Editor/Program.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Reflection; using System.Threading; using Inno.Core.IO; @@ -28,11 +29,16 @@ private static int Main(string[] arguments) { string ownership = ReadProductLock(); // Product clean must wait until the running Editor has released its deployment. - if (!System.IO.File.Exists(ownership)) + if (!File.Exists(ownership)) + { FileLease.AcquireAsync(ownership, TimeSpan.FromSeconds(10), cancellation.Token) - .GetAwaiter().GetResult().Dispose(); + .GetAwaiter() + .GetResult() + .Dispose(); + } using FileLease reading = FileLease.AcquireSharedAsync(ownership, TimeSpan.FromSeconds(10), cancellation.Token) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); #if INNO_HOST_WINDOWS_X64 return WindowsX64EditorComposition.Run(arguments, cancellation.Token); #elif INNO_HOST_MACOS_ARM64 @@ -59,8 +65,12 @@ private static int Main(string[] arguments) private static string ReadProductLock() { foreach (AssemblyMetadataAttribute metadata in typeof(Program).Assembly.GetCustomAttributes()) + { if (metadata.Key == "Inno.Editor.ProductLock" && !string.IsNullOrWhiteSpace(metadata.Value)) + { return metadata.Value; + } + } throw new InvalidOperationException("The Editor build did not declare its product ownership path."); } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs index 1432aa1c3..fd6b2795b 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs @@ -14,7 +14,13 @@ public static class BrowserWasm32BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("browser-wasm"), "Browser", "wasm32", "emscripten-wasm32", "browser-wasm", false); + new BuildTargetID("browser-wasm"), + "Browser", + "wasm32", + "emscripten-wasm32", + "browser-wasm", + false + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -42,11 +48,14 @@ INativeBindingGenerator bindingGenerator ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); - return new(target, + return new( + target, () => new BrowserWasm32GameBuildTarget(supportPackValidator), new BrowserWasm32PlayerSupportPackSource(context.host, context.toolsTarget, nativePlan, bindingGenerator, supportPackValidator), new EmscriptenNativeToolchainProvider(context.dotnetHost), - nativeProducts: [nativePlan], bindingGenerator: bindingGenerator, - managedDeployments: [ManagedDeploymentId.monoWasm, ManagedDeploymentId.monoWasmAot]); + nativeProducts: [nativePlan], + bindingGenerator: bindingGenerator, + managedDeployments: [ManagedDeploymentID.monoWasm, ManagedDeploymentID.monoWasmAot] + ); } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs index 1add23e18..8907f7735 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs @@ -28,10 +28,6 @@ public static class EmscriptenToolchainResolver /// /// Variables for native builds and binding generation, without changing the parent process. /// - /// - /// Compiler worker budgets remain inherited from the host environment or tool defaults. - /// Runtime threading policy does not constrain build-time parallelism. - /// /// /// The SDK host or a required Emscripten workload component is missing. /// @@ -47,6 +43,10 @@ public static class EmscriptenToolchainResolver /// /// The operation was canceled. /// + /// + /// Compiler worker budgets remain inherited from the host environment or tool defaults. + /// Runtime threading policy does not constrain build-time parallelism. + /// public static async Task> ResolveAsync( string dotnetHost, string projectPath, @@ -58,29 +58,48 @@ public static async Task> ResolveAsync( host = File.ResolveLinkTarget(host, returnFinalTarget: true)?.FullName ?? host; string project = Path.GetFullPath(projectPath); if (!File.Exists(project)) + { throw new FileNotFoundException("The browser toolchain project is missing.", project); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", project, "-nologo", "-nodeReuse:false", - "-getProperty:EmscriptenSdkToolsPath,EmscriptenNodeToolsPath,EmscriptenPythonToolsPath,EmscriptenCacheSdkCacheDir"], - Path.GetDirectoryName(project)!, cancellationToken, - DotNetSdkEnvironment.Create(host, new Dictionary { ["DOTNET_NOLOGO"] = "true" })).ConfigureAwait(false); + } + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + project, + "-nologo", + "-nodeReuse:false", + "-getProperty:EmscriptenSdkToolsPath,EmscriptenNodeToolsPath,EmscriptenPythonToolsPath,EmscriptenCacheSdkCacheDir" + ], + Path.GetDirectoryName(project)!, + cancellationToken, + DotNetSdkEnvironment.Create(host, new Dictionary { ["DOTNET_NOLOGO"] = "true" }) + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); string root = Path.GetDirectoryName(host)!; string sdk = ReadToolPath(properties, "EmscriptenSdkToolsPath"); string cache = ReadToolPath(properties, "EmscriptenCacheSdkCacheDir"); - string node = Path.Combine(ReadToolPath(properties, "EmscriptenNodeToolsPath"), "bin", - OperatingSystem.IsWindows() ? "node.exe" : "node"); + string node = Path.Combine( + ReadToolPath(properties, "EmscriptenNodeToolsPath"), + "bin", + OperatingSystem.IsWindows() ? "node.exe" : "node" + ); string python = OperatingSystem.IsWindows() - ? Path.Combine(ReadToolPath(properties, "EmscriptenPythonToolsPath"), "python.exe") - : ToolchainEnvironment.ResolveExecutable("python3"); + ? Path.Combine(ReadToolPath(properties, "EmscriptenPythonToolsPath"), "python.exe") + : ToolchainEnvironment.ResolveExecutable("python3"); string clang = Path.Combine(sdk, "bin", OperatingSystem.IsWindows() ? "clang.exe" : "clang"); string clangCpp = Path.Combine(sdk, "bin", OperatingSystem.IsWindows() ? "clang++.exe" : "clang++"); foreach (string file in new[] { host, node, python, clang, clangCpp }) + { if (!File.Exists(file)) + { throw new FileNotFoundException("An installed WebAssembly toolchain executable is missing.", file); + } + } if (!Directory.Exists(Path.Combine(cache, "sysroot"))) + { throw new DirectoryNotFoundException($"The WebAssembly SDK sysroot is missing at '{cache}'."); + } return new Dictionary(StringComparer.Ordinal) { ["DOTNET_HOST_PATH"] = host, @@ -100,11 +119,16 @@ private static string ReadToolPath( string name ) { if (!properties.TryGetProperty(name, out JsonElement value) || string.IsNullOrWhiteSpace(value.GetString())) - throw new InvalidOperationException($"The browser application SDK did not select '{name}'. Verify its WebAssembly SDK and the selected host's wasm-tools workload."); + { + throw new InvalidOperationException( + $"The browser application SDK did not select '{name}'. Verify its WebAssembly SDK and the selected host's wasm-tools workload." + ); + } string path = Path.GetFullPath(value.GetString()!); if (!Directory.Exists(path)) + { throw new DirectoryNotFoundException($"The browser SDK's '{name}' directory is missing at '{path}'."); + } return path; } - } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs index 6b13560c0..93de9a245 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs @@ -13,6 +13,5 @@ public static class BrowserWasm32LinkerSettings /// /// The immutable target linker plan. /// - public static NativeLinkPlan Create() - => new(staticLibraryExtension: ".a"); + public static NativeLinkPlan Create() => new(staticLibraryExtension: ".a"); } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs index 3d75983cc..9ad52abcb 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs @@ -20,7 +20,8 @@ public sealed class BrowserWasm32NativeProductExecutor : INativeProductExecutor public static NativeComponentDescriptor componentDescriptor { get; } = new( "browser", "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj", - "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj"); + "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj" + ); /// /// Publishes one exact static closure without discovering components or reselecting tools. @@ -55,72 +56,140 @@ public async Task BuildAsync( ArgumentNullException.ThrowIfNull(plan); cancellationToken.ThrowIfCancellationRequested(); NativeToolchainSelection tools = context.RequireToolchain(); - if (tools.targetId != Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id.value || context.configuration != "release") + if (tools.targetID != BrowserWasm32BuildModule.target.id.value || context.configuration != "release") + { throw new InvalidOperationException("Browser static publication requires an explicit Release wasm32 selection."); + } foreach (ProductNativeBuildStep step in plan.steps) + { if (step.options.libraryKind != NativeLibraryKind.Static || step.component.staticBuild is null) + { throw new InvalidOperationException($"Component '{step.id}' has no selected static build capability."); + } + } NativeBindingGenerationResult generations = await NativeBindingPreparation.PrepareAsync( - context, plan.steps.Select(static step => step.component).ToArray(), cancellationToken, - plan.steps.ToDictionary(static step => step.component.nativeProject, static step => step.options, StringComparer.Ordinal)).ConfigureAwait(false); + context, + plan.steps.Select(static step => step.component).ToArray(), + cancellationToken, + plan.steps.ToDictionary(static step => step.component.nativeProject, static step => step.options, StringComparer.Ordinal) + ).ConfigureAwait(false); try { - context = context.WithBindings(generations).WithComponentOptions(componentDescriptor, new(NativeLibraryKind.Static)); + context = context + .WithBindings(generations) + .WithComponentOptions(componentDescriptor, new NativeComponentBuildOptions(NativeLibraryKind.Static)); string owner = componentDescriptor.GetToolchainRoot(context.engineRoot); - string[] inputs = plan.steps.SelectMany(step => step.component.staticBuild!.inputPaths + string[] inputs = plan.steps + .SelectMany(step => step.component.staticBuild!.inputPaths .Append(step.component.staticBuild.cmakeFile) .Select(path => Path.GetFullPath(path, context.engineRoot)) .Concat(step.options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)))) .Concat(generations.Values.Select(static generation => generation.bindingsPath)) - .Concat(generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) - .Select(static generation => generation.nativeDirectory)) - .Concat(generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) - .SelectMany(generation => NativeBindingCompilation.Load(generation.nativeDirectory) - .GetInputs(context.engineRoot, generation.nativeDirectory).Select(static input => input.physicalPath))) + .Concat( + generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) + .Select(static generation => generation.nativeDirectory) + ) + .Concat( + generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) + .SelectMany(generation => NativeBindingCompilation.Load(generation.nativeDirectory) + .GetInputs(context.engineRoot, generation.nativeDirectory) + .Select(static input => input.physicalPath)) + ) .Append(Path.Combine(owner, "Native", "CMakeLists.txt")) - .Distinct(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .ToArray(); string[] declarations = plan.steps.Select(step => step.id + "=" + step.component.staticBuild!.cmakeFile) - .Concat(plan.steps.SelectMany(step => step.component.staticBuild!.logicalOutputs.Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName) - .Select(name => step.id + ":archive=" + name))) - .Concat(plan.steps.SelectMany(static step => new[] { step.id + ":library=" + step.options.libraryKind, - step.id + ":native-source=" + step.component.staticBuild!.nativeSourceDirectory } - .Concat(step.options.cmakeArguments.Select(argument => step.id + ":argument=" + argument)))) - .Concat(generations.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => pair.Key + "=" + pair.Value.fingerprint)) - .Append("product=" + plan.productId).ToArray(); + .Concat( + plan.steps.SelectMany(step => step.component.staticBuild!.logicalOutputs + .Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName) + .Select(name => step.id + ":archive=" + name)) + ) + .Concat( + plan.steps.SelectMany(static step => new[] + { + step.id + ":library=" + step.options.libraryKind, + step.id + ":native-source=" + step.component.staticBuild!.nativeSourceDirectory + } + .Concat(step.options.cmakeArguments.Select(argument => step.id + ":argument=" + argument))) + ) + .Concat( + generations.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value.fingerprint) + ) + .Append("product=" + plan.productID) + .ToArray(); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( - context, componentDescriptor, "browser", tools.targetId, inputs, declarations, - [Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs")]); - NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + context, + componentDescriptor, + "browser", + tools.targetID, + inputs, + declarations, + [Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs")] + ); + NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { + ) => + { string intermediate = scoped.GetNativeBuildRoot(componentDescriptor); Directory.CreateDirectory(intermediate); string selection = Path.Combine(intermediate, "Components.cmake"); NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync( - @scoped, componentDescriptor, token).ConfigureAwait(false); + @scoped, + componentDescriptor, + token + ).ConfigureAwait(false); WriteComponentSelection(selection, scoped.engineRoot, sources, plan, generations); - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - Path.Combine(owner, "Native"), null, - ["-DINNO_COMPONENT_SELECTION=" + selection, "-DCMAKE_INSTALL_PREFIX=" + output, - "-DPython3_EXECUTABLE=" + tools.ResolveExecutable("python")], token).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(scoped, tools.ResolveExecutable("cmake"), - ["--install", build, "--component", "Inno"], scoped.engineRoot, token, - tools.environment).ConfigureAwait(false); - ValidateNativeOutputs(output, tools.targetId, plan); - NativeBindingGenerationDescriptor.WriteSelection(Path.Combine(output, "Metadata", "BindingSelection.props"), generations, + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + Path.Combine(owner, "Native"), + null, + [ + "-DINNO_COMPONENT_SELECTION=" + selection, + "-DCMAKE_INSTALL_PREFIX=" + output, + "-DPython3_EXECUTABLE=" + tools.ResolveExecutable("python") + ], + token + ).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + scoped, + tools.ResolveExecutable("cmake"), + ["--install", build, "--component", "Inno"], + scoped.engineRoot, + tools.environment, + token + ).ConfigureAwait(false); + ValidateNativeOutputs(output, tools.targetID, plan); + NativeBindingGenerationDescriptor.WriteSelection( + Path.Combine(output, "Metadata", "BindingSelection.props"), + generations, plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - }, cancellationToken, describeOutputs: static ( + .ToDictionary( + static step => step.component.nativeProject, + static step => step.options.libraryKind, + StringComparer.Ordinal + ) + ); + }, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories) - .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, - Path.GetExtension(file) == ".a" ? NativeArtifactRole.StaticArchive : NativeArtifactRole.SupportFile)).ToArray()).ConfigureAwait(false); + .Select(file => new NativeArtifact( + Path.GetRelativePath(output, file), + file, + Path.GetExtension(file) == ".a" ? NativeArtifactRole.StaticArchive : NativeArtifactRole.SupportFile + )) + .ToArray(), + cancellationToken: cancellationToken + ).ConfigureAwait(false); return new ProductNativeBuildResult([product], generations, Path.Combine(product.directory, "Outputs"), recipe); } catch @@ -153,8 +222,14 @@ IReadOnlyDictionary generations } text.AppendLine("set(INNO_COMPONENT_ID " + CMakeLiteral(step.id) + ")"); if (step.component.staticBuild!.nativeSourceDirectory is string nativeSource) - text.AppendLine("set(INNO_COMPONENT_NATIVE " + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(nativeSource, engineRoot))) + ")"); - text.AppendLine("include(" + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(step.component.staticBuild!.cmakeFile, engineRoot))) + ")"); + { + text.AppendLine( + "set(INNO_COMPONENT_NATIVE " + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(nativeSource, engineRoot))) + ")" + ); + } + text.AppendLine( + "include(" + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(step.component.staticBuild!.cmakeFile, engineRoot))) + ")" + ); text.AppendLine("endfunction()"); text.AppendLine(scope + "()"); } @@ -163,22 +238,27 @@ IReadOnlyDictionary generations private static void ValidateNativeOutputs( string directory, - string targetId, + string targetID, ProductNativeBuildPlan plan ) { var expected = new HashSet(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { - foreach (string archive in step.component.staticBuild!.logicalOutputs.Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName)) - { - string path = Path.Combine(directory, step.id, targetId, archive); + foreach (string archive in step.component.staticBuild!.logicalOutputs.Select( + BrowserWasm32LinkerSettings.Create().GetStaticFileName + )) { + string path = Path.Combine(directory, step.id, targetID, archive); if (!File.Exists(path) || new FileInfo(path).Length == 0) + { throw new InvalidDataException($"Component '{step.id}' did not produce its required archive '{archive}'."); + } expected.Add(path); } } if (!expected.SetEquals(Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))) + { throw new InvalidDataException("The static candidate contains outputs outside its frozen component closure."); + } } private static string CMakeLiteral(string value) @@ -186,8 +266,10 @@ private static string CMakeLiteral(string value) string portable = value.Replace('\\', '/'); int delimiter = 0; while (portable.Contains("]" + new string('=', delimiter) + "]", StringComparison.Ordinal)) + { delimiter++; - string equals = new('=', delimiter); + } + var equals = new string('=', delimiter); return "[" + equals + "[" + portable + "]" + equals + "]"; } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs index 3e75fc6b5..0965366f7 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs @@ -17,7 +17,7 @@ namespace Inno.Build.BrowserWasm32; public sealed class BrowserWasm32PlayerSupportPackSource : IPlayerSupportPackSource { private readonly BuildHostDescriptor m_host; - private readonly BuildTargetId m_toolsTarget; + private readonly BuildTargetID m_toolsTarget; private readonly NativeProductContribution m_nativeProduct; private readonly INativeBindingGenerator m_bindingGenerator; private readonly IPlayerSupportPackValidator m_validator; @@ -48,7 +48,7 @@ public sealed class BrowserWasm32PlayerSupportPackSource : IPlayerSupportPackSou /// public BrowserWasm32PlayerSupportPackSource( BuildHostDescriptor host, - BuildTargetId toolsTarget, + BuildTargetID toolsTarget, NativeProductContribution nativePlan, INativeBindingGenerator bindingGenerator, IPlayerSupportPackValidator supportPackValidator @@ -57,59 +57,106 @@ IPlayerSupportPackValidator supportPackValidator ArgumentNullException.ThrowIfNull(nativePlan); ArgumentException.ThrowIfNullOrWhiteSpace(toolsTarget.value); ArgumentNullException.ThrowIfNull(bindingGenerator); + ArgumentNullException.ThrowIfNull(supportPackValidator); m_bindingGenerator = bindingGenerator; m_host = host; m_toolsTarget = toolsTarget; m_nativeProduct = nativePlan; - m_validator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); + m_validator = supportPackValidator; } - /// - public BuildTargetId target => Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id; + /// + public BuildTargetID target => BrowserWasm32BuildModule.target.id; - /// + /// public async ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); - string project = Path.Combine(context.engineRoot, "platforms", "BrowserWasm32", "player", - "Inno.Player.BrowserWasm32", "Inno.Player.BrowserWasm32.csproj"); - string template = Path.Combine(BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot), - "Templates", "BrowserWasm32Player.project.xml"); + string project = Path.Combine( + context.engineRoot, + "platforms", + "BrowserWasm32", + "player", + "Inno.Player.BrowserWasm32", + "Inno.Player.BrowserWasm32.csproj" + ); + string template = Path.Combine( + BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot), + "Templates", + "BrowserWasm32Player.project.xml" + ); if (!File.Exists(template)) + { throw new FileNotFoundException("The Browser publication template is absent.", template); - var nativeContext = new NativeBuildContext(context.engineRoot, "release").WithBindingGenerator(m_bindingGenerator); + } + NativeBuildContext nativeContext = new NativeBuildContext(context.engineRoot, "release").WithBindingGenerator(m_bindingGenerator); NativeToolchainSelection tools = await new EmscriptenNativeToolchainProvider(context.dotnetHost) - .ResolveAsync(nativeContext, m_host, target.value, cancellationToken).ConfigureAwait(false); + .ResolveAsync(nativeContext, m_host, target.value, cancellationToken) + .ConfigureAwait(false); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( - tools.ResolveExecutable("dotnet"), project, cancellationToken).ConfigureAwait(false); + tools.ResolveExecutable("dotnet"), + project, + cancellationToken + ).ConfigureAwait(false); nativeContext = nativeContext.WithToolchain(tools); var properties = new Dictionary { - ["Configuration"] = "Release", ["InnoNativeTarget"] = target.value, ["InnoToolTarget"] = m_toolsTarget.value, + ["Configuration"] = "Release", + ["InnoNativeTarget"] = target.value, + ["InnoToolTarget"] = m_toolsTarget.value, ["InnoShaderToolSourceRoot"] = context.engineRoot, - ["DebugType"] = "None", ["DebugSymbols"] = "false" + ["DebugType"] = "None", + ["DebugSymbols"] = "false" }; if (context.nativeDependencies is not null) + { properties["InnoNativeDependencyManifest"] = context.nativeDependencies; - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet", - .. properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value)], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(sdk.hostPath, tools.environment)).ConfigureAwait(false); + } + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "restore", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet", + .. properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value) + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath, tools.environment) + ).ConfigureAwait(false); string owner = BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot); PlayerSupportPackPreparationIdentity identity = await PlayerSupportPackPreparationIdentity.CaptureAsync( - nativeContext, m_nativeProduct.plan, sdk, project, properties, - [template, Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "index.html"), + nativeContext, + m_nativeProduct.plan, + sdk, + project, + properties, + [ + template, + Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "index.html"), Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "main.js"), Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs"), - Path.Combine(owner, "Native", "CMakeLists.txt"), Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), + Path.Combine(owner, "Native", "CMakeLists.txt"), + Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), Path.Combine(owner, "SupportPacks", "BrowserWasm32PlayerSupportPackSource.cs"), - Path.Combine(owner, "SupportPacks", "BrowserWasm32SupportPackValidator.cs")], cancellationToken).ConfigureAwait(false); + Path.Combine(owner, "SupportPacks", "BrowserWasm32SupportPackValidator.cs") + ], + cancellationToken + ).ConfigureAwait(false); return new PreparationPlan(this, context.engineRoot, project, sdk, nativeContext, identity); } + /// + public void Validate(string directory) => m_validator.Validate(directory); + private async ValueTask ExecuteAsync( PlayerSupportPackBuildContext context, string project, @@ -119,41 +166,75 @@ CancellationToken cancellationToken ) { NativeToolchainSelection tools = nativeContext.RequireToolchain(); using ProductNativeBuildResult artifacts = identity.nativeDependencies is string manifest - ? await NativeDependencyManifest.AcquireAsync(nativeContext.engineRoot, manifest, target.value, - nativeContext.configuration, m_nativeProduct.plan, cancellationToken).ConfigureAwait(false) + ? await NativeDependencyManifest.AcquireAsync( + nativeContext.engineRoot, + manifest, + target.value, + nativeContext.configuration, + m_nativeProduct.plan, + cancellationToken + ).ConfigureAwait(false) : await m_nativeProduct.BuildAsync(nativeContext, cancellationToken).ConfigureAwait(false); using ManagedBuildExecution execution = await identity.CreateExecutionAsync(cancellationToken).ConfigureAwait(false); context = new PlayerSupportPackBuildContext(execution.engineRoot, context.stagingDirectory, context.sdk); project = execution.project; string profileRoot = Path.Combine(context.engineRoot, "artifacts", "managed", "browser-references", artifacts[0].fingerprint); using FileLease ownership = await FileLease.AcquireAsync( - profileRoot + ".lock", Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + profileRoot + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); string bindingSelection = Path.Combine(profileRoot, "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(bindingSelection, artifacts.bindingGenerations, + NativeBindingGenerationDescriptor.WriteSelection( + bindingSelection, + artifacts.bindingGenerations, m_nativeProduct.plan.steps.Where(step => artifacts.bindingGenerations.ContainsKey(step.component.nativeProject)) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - string[] properties = ["-p:Configuration=Release", "-p:InnoNativeTarget=" + target.value, - "-p:InnoToolTarget=" + m_toolsTarget.value, "-p:InnoNativeBuildFingerprint=" + artifacts[0].fingerprint, + .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal) + ); + string[] properties = + [ + "-p:Configuration=Release", + "-p:InnoNativeTarget=" + target.value, + "-p:InnoToolTarget=" + m_toolsTarget.value, + "-p:InnoNativeBuildFingerprint=" + artifacts[0].fingerprint, "-p:InnoShaderToolSourceRoot=" + nativeContext.engineRoot, "-p:InnoNativeBindingSelection=" + bindingSelection, - ..(identity.nativeDependencies is string selection ? new[] { "-p:InnoNativeDependencyManifest=" + selection } : Array.Empty()), - "-p:DebugType=None", "-p:DebugSymbols=false"]; - await ToolchainEnvironment.RunAsync(context.sdk.hostPath, + ..(identity.nativeDependencies is string selection + ? ["-p:InnoNativeDependencyManifest=" + selection] + : Array.Empty()), + "-p:DebugType=None", + "-p:DebugSymbols=false" + ]; + await ToolchainEnvironment.RunAsync( + context.sdk.hostPath, [context.sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", .. properties], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment)).ConfigureAwait(false); - string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync(context.sdk.hostPath, + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment) + ).ConfigureAwait(false); + string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync( + context.sdk.hostPath, [context.sdk.cliPath, "msbuild", project, "-getProperty:TargetDir", "-p:DesignTimeBuild=true", "-nologo", .. properties], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment)).ConfigureAwait(false)).Trim(); - PlayerSupportPackFiles.CopyReferences(buildOutput, Path.Combine(context.stagingDirectory, "References"), "Inno.Player.BrowserWasm32"); + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment) + ).ConfigureAwait(false)).Trim(); + PlayerSupportPackFiles.CopyReferences( + buildOutput, + Path.Combine(context.stagingDirectory, "References"), + "Inno.Player.BrowserWasm32" + ); CopyLinkTemplate(context.engineRoot, context.stagingDirectory, artifacts, project); - await PlayerSupportPackFiles.CopyPlayerSourcesAsync(context, project, - Path.Combine(context.stagingDirectory, "PlayerLink"), cancellationToken, tools.environment).ConfigureAwait(false); + await PlayerSupportPackFiles.CopyPlayerSourcesAsync( + context, + project, + Path.Combine(context.stagingDirectory, "PlayerLink"), + cancellationToken, + tools.environment + ).ConfigureAwait(false); await execution.VerifyAsync(cancellationToken).ConfigureAwait(false); } - /// - public void Validate(string directory) => m_validator.Validate(directory); - private static void CopyLinkTemplate( string engineRoot, string staging, @@ -171,7 +252,9 @@ string productProject CopyRequired(Path.Combine(owner, "Templates", "BrowserWasm32Player.project.xml"), Path.Combine(template, "Player.csproj")); PlayerSupportPackFiles.CopyCompositionInputs(engineRoot, template); foreach (string asset in new[] { "index.html", "main.js" }) + { CopyRequired(Path.Combine(Path.GetDirectoryName(productProject)!, "wwwroot", asset), Path.Combine(webRoot, asset)); + } foreach (string archive in Directory.EnumerateFiles(artifacts.aggregateDirectory!, "*.a", SearchOption.AllDirectories)) { string destination = PathBoundary.Resolve(native, Path.GetRelativePath(artifacts.aggregateDirectory!, archive)); @@ -180,7 +263,9 @@ string productProject } CopyRequired(Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), Path.Combine(native, "wasm_sjlj_shim.c")); foreach (string file in Directory.EnumerateFiles(Path.Combine(staging, "References"), "*.dll")) + { CopyRequired(file, Path.Combine(references, Path.GetFileName(file))); + } } private static void CopyRequired( @@ -188,9 +273,12 @@ private static void CopyRequired( string destination ) { if (!File.Exists(source)) + { throw new FileNotFoundException($"Browser Support Pack input is missing: '{source}'.", source); + } File.Copy(source, destination, overwrite: true); } + private sealed class PreparationPlan( BrowserWasm32PlayerSupportPackSource owner, string engineRoot, @@ -198,16 +286,21 @@ private sealed class PreparationPlan( DotNetSdkDescriptor sdk, NativeBuildContext native, PlayerSupportPackPreparationIdentity identity - ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { - /// + ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) + { + /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); - /// + /// public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => owner.ExecuteAsync(new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), - project, native, identity, cancellationToken); + ) => owner.ExecuteAsync( + new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), + project, + native, + identity, + cancellationToken + ); } - } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs index b96c9feb8..f8168febc 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; -using System.Globalization; using System.Text; using Inno.Build.Toolchains; @@ -28,16 +28,23 @@ public void Validate(string directory) string linker = Path.Combine(directory, "PlayerLink"); foreach (string input in new[] { - "Player.csproj", "Program.cs", "BrowserWasm32PlayerComposition.cs", "HttpPlayerContentSource.cs", "BrowserWasm32Bridge.cs", "global.json", + "Player.csproj", + "Program.cs", + "BrowserWasm32PlayerComposition.cs", + "HttpPlayerContentSource.cs", + "BrowserWasm32Bridge.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), - Path.Combine("wwwroot", "index.html"), Path.Combine("wwwroot", "main.js"), + Path.Combine("wwwroot", "index.html"), + Path.Combine("wwwroot", "main.js"), Path.Combine("Native", "wasm_sjlj_shim.c"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) - { + }) { if (!File.Exists(Path.Combine(linker, input))) + { throw new InvalidDataException($"The browser Support Pack lacks linker input '{input}'."); + } } string nativeDirectory = Path.Combine(linker, "Native"); string[] foreignBinaries = Directory.EnumerateFiles(nativeDirectory, "*", SearchOption.AllDirectories) @@ -46,9 +53,15 @@ public void Validate(string directory) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); if (foreignBinaries.Length != 0) - throw new InvalidDataException($"The browser Support Pack contains a foreign native binary '{Path.GetFileName(foreignBinaries[0])}'."); + { + throw new InvalidDataException( + $"The browser Support Pack contains a foreign native binary '{Path.GetFileName(foreignBinaries[0])}'." + ); + } foreach (string archive in Directory.EnumerateFiles(nativeDirectory, "*.a", SearchOption.AllDirectories)) + { ValidateArchive(archive); + } } private static void ValidateArchive(string file) @@ -56,24 +69,36 @@ private static void ValidateArchive(string file) using FileStream input = File.OpenRead(file); Span magic = stackalloc byte[8]; if (input.Length < magic.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has no archive header."); + } input.ReadExactly(magic); if (!magic.SequenceEqual("!\n"u8)) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' is not an owned object archive."); + } Span header = stackalloc byte[60]; Span objectHeader = stackalloc byte[8]; bool containsObject = false; while (input.Position < input.Length) { if (input.Length - input.Position < header.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has a truncated member header."); + } input.ReadExactly(header); string name = Encoding.ASCII.GetString(header[..16]).TrimEnd(); if (!header[58..].SequenceEqual("`\n"u8) - || !long.TryParse(Encoding.ASCII.GetString(header.Slice(48, 10)).Trim(), - NumberStyles.None, CultureInfo.InvariantCulture, out long length) - || length < 0 || length > input.Length - input.Position) + || !long.TryParse( + Encoding.ASCII.GetString(header.Slice(48, 10)).Trim(), + NumberStyles.None, + CultureInfo.InvariantCulture, + out long length + ) + || length < 0 || length > input.Length - input.Position + ) { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has an invalid member size."); + } long end = input.Position + length; bool metadata = name is "/" or "//" or "/SYM64/" || name.StartsWith("__.SYMDEF", StringComparison.Ordinal); if (!metadata) @@ -81,22 +106,32 @@ private static void ValidateArchive(string file) if (name.StartsWith("#1/", StringComparison.Ordinal)) { if (!int.TryParse(name[3..], NumberStyles.None, CultureInfo.InvariantCulture, out int prefix) - || prefix < 0 || prefix > length - objectHeader.Length) + || prefix < 0 || prefix > length - objectHeader.Length + ) { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has an invalid member name."); + } input.Position += prefix; } if (end - input.Position < objectHeader.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains a truncated object."); + } input.ReadExactly(objectHeader); if (!objectHeader.SequenceEqual("\0asm\u0001\0\0\0"u8)) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains a foreign object ABI."); + } containsObject = true; } input.Position = end + (length & 1); if (input.Position > input.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' lacks member alignment padding."); + } } if (!containsObject) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains no Wasm objects."); + } } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs index a930e7b1d..c0874ff5d 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs @@ -13,7 +13,6 @@ public sealed class BrowserWasm32GameBuildTarget : IGameBuildTarget { private readonly IPlayerSupportPackValidator m_supportPackValidator; - /// /// Creates a site packager bound to the selected native closure validator. /// @@ -29,26 +28,15 @@ public BrowserWasm32GameBuildTarget(IPlayerSupportPackValidator supportPackValid m_supportPackValidator = supportPackValidator; } - /// - /// Validates the target closure before runtime script compilation. - /// - /// - /// The Support Pack directory selected by the build catalog. - /// - /// - /// The required platform inputs are incomplete or incompatible. - /// - public void Validate(string directory) => m_supportPackValidator.Validate(directory); - /// /// Gets the browser WebAssembly target identity. /// - public BuildTargetId id => Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id; + public BuildTargetID id => BrowserWasm32BuildModule.target.id; - /// - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.monoWasm; + /// + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.monoWasm; - /// + /// public string runtimeIdentifier => "browser-wasm"; /// @@ -56,7 +44,16 @@ public BrowserWasm32GameBuildTarget(IPlayerSupportPackValidator supportPackValid /// public string displayName => "Web (WebGL 2)"; - + /// + /// Validates the target closure before runtime script compilation. + /// + /// + /// The Support Pack directory selected by the build catalog. + /// + /// + /// The required platform inputs are incomplete or incompatible. + /// + public void Validate(string directory) => m_supportPackValidator.Validate(directory); /// /// Composes an independently hostable site from a verified browser Support Pack and content pack. @@ -79,14 +76,19 @@ public async ValueTask PackageAsync( await CopyDirectoryAsync( Path.Combine(context.managedDeployment.outputDirectory, "wwwroot"), site, - cancellationToken); + cancellationToken + ).ConfigureAwait(false); if (!File.Exists(Path.Combine(site, "index.html"))) + { throw new InvalidDataException("The browser Support Pack has no index.html entry point."); + } string contentDirectory = Path.Combine(site, "Content"); - await CopyDirectoryAsync(context.contentDirectory, contentDirectory, cancellationToken); + await CopyDirectoryAsync(context.contentDirectory, contentDirectory, cancellationToken).ConfigureAwait(false); string[] packs = Directory.GetFiles(contentDirectory, "content-*.pack", SearchOption.TopDirectoryOnly); if (packs.Length != 1) + { throw new InvalidDataException("The browser deployment must contain exactly one content pack."); + } return site; } @@ -102,9 +104,9 @@ CancellationToken cancellationToken string relativePath = Path.GetRelativePath(source, file); string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); - await input.CopyToAsync(output, cancellationToken); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); + await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs index 963793496..e2fe83372 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs @@ -29,25 +29,39 @@ public EmscriptenNativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, - string targetId, + string targetID, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); - if (targetId != BrowserWasm32BuildModule.target.id.value || host.system is not ("Windows" or "MacOS")) - throw new PlatformNotSupportedException($"Emscripten cannot build '{targetId}' on {host.system}/{host.architecture}."); - string project = Path.Combine(context.engineRoot, "platforms", "BrowserWasm32", "build", - "Inno.Build.BrowserWasm32", "Templates", "BrowserWasm32Player.project.xml"); + if (targetID != BrowserWasm32BuildModule.target.id.value || host.system is not ("Windows" or "MacOS")) + { + throw new PlatformNotSupportedException($"Emscripten cannot build '{targetID}' on {host.system}/{host.architecture}."); + } + string project = Path.Combine( + context.engineRoot, + "platforms", + "BrowserWasm32", + "build", + "Inno.Build.BrowserWasm32", + "Templates", + "BrowserWasm32Player.project.xml" + ); IReadOnlyDictionary sdk = await EmscriptenToolchainResolver.ResolveAsync( - m_dotnetHost, project, cancellationToken).ConfigureAwait(false); + m_dotnetHost, + project, + cancellationToken + ).ConfigureAwait(false); Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); foreach ((string name, string value) in sdk) + { environment[name] = value; + } var tools = new Dictionary(StringComparer.Ordinal) { ["clang"] = Path.Combine(sdk["DOTNET_EMSCRIPTEN_LLVM_ROOT"], "clang" + host.services.executableExtension), @@ -59,13 +73,25 @@ CancellationToken cancellationToken ["node"] = sdk["EMSDK_NODE"] }; string toolchain = Path.Combine(sdk["EMSCRIPTEN"], "cmake", "Modules", "Platform", "Emscripten.cmake"); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, - [Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, + return NativeToolchainPreparation.Freeze( + targetID, + host, + tools, + environment, + [ + Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, Path.Combine(Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, "bin"), Path.GetDirectoryName(sdk["EMSDK_PYTHON"])!, - Path.Combine(sdk["EM_CACHE"], "sysroot", "include")], + Path.Combine(sdk["EM_CACHE"], "sysroot", "include") + ], ["-G", "Ninja", "-DCMAKE_MAKE_PROGRAM=" + tools["ninja"], "-DCMAKE_TOOLCHAIN_FILE=" + toolchain], - BrowserWasm32LinkerSettings.Create(), multiConfiguration: false, compilerInputs: new NativeCompilerInputs( - tools["clang"], tools["clang++"], Path.Combine(sdk["EM_CACHE"], "sysroot"))); + BrowserWasm32LinkerSettings.Create(), + multiConfiguration: false, + compilerInputs: new NativeCompilerInputs( + tools["clang"], + tools["clang++"], + Path.Combine(sdk["EM_CACHE"], "sysroot") + ) + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs index 1ca710ec3..aac2e7f1d 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs @@ -37,12 +37,17 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); + } if (role == BgfxSurfaceRole.Additional) + { throw new NotSupportedException("The browser canvas host does not support additional BGFX windows."); - if (handles.handleKind != PlatformNativeHandleId.browserCanvas) + } + if (handles.handleKind != PlatformNativeHandleID.browserCanvas) + { throw new NotSupportedException("The Browser BGFX integration requires its explicit browserCanvas surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: false); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: false); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs index 95b884d7a..663b2eddc 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs @@ -17,10 +17,13 @@ public static class BrowserWasm32BgfxIntegration /// public static NativeComponentBuildOptions nativeOptions { get; } = new( NativeLibraryKind.Static, - ["-DINNO_BGFX_RENDERER_DEFINITIONS=BGFX_CONFIG_RENDERER_OPENGLES=30", + [ + "-DINNO_BGFX_RENDERER_DEFINITIONS=BGFX_CONFIG_RENDERER_OPENGLES=30", "-DINNO_BGFX_SDK_DEFINITIONS=__EMSCRIPTEN_MAJOR__=__EMSCRIPTEN_major__;__EMSCRIPTEN_MINOR__=__EMSCRIPTEN_minor__;__EMSCRIPTEN_TINY__=__EMSCRIPTEN_tiny__", - "-DINNO_BGFX_SDK_OPTIONS=-include;emscripten/version.h"], - ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs"]); + "-DINNO_BGFX_SDK_OPTIONS=-include;emscripten/version.h" + ], + ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs"] + ); /// /// Gets the explicit shader configuration used by this integration. @@ -46,6 +49,6 @@ public static GameContentCompilerFactory CreateContentCompilerFactory(ToolRunner assets, serialization, types - ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.OpenGLES], tools); + ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.openGLES], tools); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs index 8fad73629..a44baa455 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs @@ -1,8 +1,7 @@ +using Inno.Build.BrowserWasm32; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Inno.Build.BrowserWasm32; - namespace Inno.Integration.BrowserWasm32.Bgfx; /// @@ -13,19 +12,38 @@ public static class BrowserWasm32BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(BrowserWasm32BuildModule.target.id.value, - [ - new(CreateCapabilities(), "asm.js", "300_es", "300_es", "") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + BrowserWasm32BuildModule.target.id.value, + [ + new BgfxShaderCompilerProfile(CreateCapabilities(), "asm.js", "300_es", "300_es", string.Empty) + ] + ); private static GraphicsCapabilities CreateCapabilities() { - RenderTextureFormat[] color = [RenderTextureFormat.R8, RenderTextureFormat.RG8, - RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA8Srgb, RenderTextureFormat.RGB10A2]; + RenderTextureFormat[] color = + [ + RenderTextureFormat.R8, + RenderTextureFormat.RG8, + RenderTextureFormat.RGBA8, + RenderTextureFormat.RGBA8Srgb, + RenderTextureFormat.RGB10A2 + ]; RenderTextureFormat[] sampled = [.. color, RenderTextureFormat.Depth24Stencil8]; - return new(GraphicsApi.OpenGLES, GraphicsCapability.Index32 | GraphicsCapability.Instancing + return new( + GraphicsApi.openGLES, + GraphicsCapability.Index32 | GraphicsCapability.Instancing | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D | GraphicsCapability.FragmentDepth, - new GraphicsLimits(256, 4, 2048, 0), sampled, sampled, [], [], true, true, - color, color, sampled); + new GraphicsLimits(256, 4, 2048, 0), + sampled, + sampled, + [], + [], + true, + true, + color, + color, + sampled + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs index 94f6acc7c..4c4ed43da 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs @@ -9,11 +9,13 @@ namespace Inno.Integration.BrowserWasm32.Build; internal static class BrowserWasm32BindingProfile { - internal static NativeBindingProfile Create() => new( - BrowserWasm32BuildModule.target.id.value, - new TargetConfiguration { id = "emscripten-wasm32-emscripten" }, - new ManagedRuntimeId("dotnet.mono-wasm"), - ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs"], - static builder => builder.AddPlugin(), - BindingImportMode.LibraryImport); + internal static NativeBindingProfile Create() + => new( + BrowserWasm32BuildModule.target.id.value, + new TargetConfiguration { id = "emscripten-wasm32-emscripten" }, + new ManagedRuntimeId("dotnet.mono-wasm"), + ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs"], + static builder => builder.AddPlugin(), + BindingImportMode.LibraryImport + ); } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs index 4463db1a3..66a630be4 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs @@ -27,11 +27,20 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(BrowserWasm32BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreateStaticPlayer(BrowserWasm32NativeProducts.Options, BrowserWasm32NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreateStaticPlayer( + BrowserWasm32NativeProducts.Options, + BrowserWasm32NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateStatic(player, BrowserWasm32BuildModule.target.id, BrowserWasm32LinkerSettings.Create()), - new BrowserWasm32SupportPackValidator(), null); - return BrowserWasm32BuildModule.CreateContribution(context, - new NativeProductContribution(player, new BrowserWasm32NativeProductExecutor()), validator, generator); + new BrowserWasm32SupportPackValidator(), + null + ); + return BrowserWasm32BuildModule.CreateContribution( + context, + new NativeProductContribution(player, new BrowserWasm32NativeProductExecutor()), + validator, + generator + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs index fe77a8ce8..6e83c36ff 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs @@ -11,10 +11,15 @@ internal static class BrowserWasm32NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs index 955fca50f..c1877179e 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs @@ -12,7 +12,8 @@ internal static class BrowserWasm32NativeProducts internal static NativeComponentBuildOptions Options(string component) { NativeComponentBuildOptions graphics = BrowserWasm32BgfxIntegration.nativeOptions; - return new(NativeLibraryKind.Static, + return new( + NativeLibraryKind.Static, component == "bgfx" ? graphics.cmakeArguments : [], [C_INPUT, ..(component == "bgfx" ? graphics.inputPaths : [])], bindingLibraryName: component switch @@ -23,6 +24,7 @@ internal static NativeComponentBuildOptions Options(string component) "text" => "libinno-text", "ui" => "libinno-ui", _ => throw new ArgumentException("This component is outside the Browser product closure.", nameof(component)) - }); + } + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs index 13b6eadbb..978c61299 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs @@ -11,41 +11,42 @@ namespace Inno.Integration.BrowserWasm32.Sdl3; /// public sealed class BrowserWasm32Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: false, liveResize: false); - /// - public void ConfigureInitialization() - { - } + /// + public void ConfigureInitialization() {} - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: true); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: true); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.emscripten.canvas_id\0"u8; fixed (byte* name = propertyName) { nint selector = (nint)SDL.Raw.GetStringProperty(properties, (sbyte*)name, null); if (selector == 0) + { throw new InvalidOperationException("SDL did not provide a browser canvas selector."); - return new PlatformNativeHandles(selector, handleKind: PlatformNativeHandleId.browserCanvas); + } + return new PlatformNativeHandles(selector, handleKind: PlatformNativeHandleID.browserCanvas); } } - /// + /// public bool GetInitialFocus(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } return false; } } diff --git a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs index 52829b446..16238faa4 100644 --- a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs +++ b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs @@ -1,18 +1,18 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.BrowserWasm32.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.BrowserWasm32.Sdl3; using System; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using System.Net.Http; using Inno.Adapter; using Inno.Adapter.Default; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.BrowserWasm32; using Inno.Core.Logging; +using Inno.Integration.BrowserWasm32.Bgfx.Runtime; +using Inno.Integration.BrowserWasm32.Sdl3; using Inno.Player.Runtime; using Inno.Runtime; using Inno.Shell; @@ -48,10 +48,12 @@ internal static async Task RunAsync(string[] arguments) new BgfxRenderingBackendProvider(new BrowserWasm32BgfxSurfaceIntegration()) ]) }), - adapterSelection = StandardAdapterSelection.Create(StorageBackendId.browser), + adapterSelection = StandardAdapterSelection.Create(StorageBackendID.browser), contentSource = new HttpPlayerContentSource(client), - createStorage = manifest => storage.CreateStorage(StorageBackendId.browser, - new StorageScope(manifest.applicationId)), + createStorage = manifest => storage.CreateStorage( + StorageBackendID.browser, + new StorageScope(manifest.applicationId) + ), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new ScheduledShellFrameDriver(NextFrameAsync), graphicsApi = command.graphicsApi, diff --git a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs index d8c160f2b..988485aad 100644 --- a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs +++ b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs @@ -19,7 +19,8 @@ internal sealed class HttpPlayerContentSource : IPlayerContentSource internal HttpPlayerContentSource(HttpClient client) { - m_client = client ?? throw new ArgumentNullException(nameof(client)); + ArgumentNullException.ThrowIfNull(client); + m_client = client; } /// @@ -38,8 +39,10 @@ public async ValueTask ReadMetadataAsync(CancellationToke { using MemoryStream manifest = await DownloadAsync("runtime.manifest", C_METADATA_LIMIT, cancellationToken); using MemoryStream catalog = await DownloadAsync("catalog.inno", C_METADATA_LIMIT, cancellationToken); - return new PlayerContentMetadata(manifest.GetBuffer().AsSpan(0, checked((int)manifest.Length)), - catalog.GetBuffer().AsSpan(0, checked((int)catalog.Length))); + return new PlayerContentMetadata( + manifest.GetBuffer().AsSpan(0, checked((int)manifest.Length)), + catalog.GetBuffer().AsSpan(0, checked((int)catalog.Length)) + ); } /// @@ -74,7 +77,9 @@ public async ValueTask PrepareAsync( ) { ArgumentNullException.ThrowIfNull(pack); if (!scope.isValid) + { throw new ArgumentException("Content preparation requires an application namespace.", nameof(scope)); + } MemoryStream stream = await DownloadAsync(pack.fileName, m_limits.packBytes, cancellationToken); return ContentPackReader.Open(stream, pack, serialization, m_limits, cancellationToken); } @@ -84,12 +89,17 @@ private async Task DownloadAsync( long budget, CancellationToken cancellationToken ) { - using HttpResponseMessage response = await m_client.GetAsync("Content/" + fileName, - HttpCompletionOption.ResponseHeadersRead, cancellationToken); + using HttpResponseMessage response = await m_client.GetAsync( + "Content/" + fileName, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken + ); response.EnsureSuccessStatusCode(); long? length = response.Content.Headers.ContentLength; if (length is < 0 || length > budget) + { throw new InvalidDataException($"Deployment content '{fileName}' exceeds its download budget."); + } var output = new MemoryStream(); byte[] buffer = ArrayPool.Shared.Rent(64 * 1024); try @@ -99,11 +109,15 @@ CancellationToken cancellationToken while ((count = await input.ReadAsync(buffer, cancellationToken)) != 0) { if (output.Length + count > budget) + { throw new InvalidDataException($"Deployment content '{fileName}' exceeds its download budget."); + } await output.WriteAsync(buffer.AsMemory(0, count), cancellationToken); } if (length is not null && output.Length != length) + { throw new InvalidDataException($"Deployment content '{fileName}' has a truncated HTTP body."); + } cancellationToken.ThrowIfCancellationRequested(); output.Position = 0; return output; diff --git a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs index a039bc324..eba524620 100644 --- a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs +++ b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs @@ -27,7 +27,9 @@ public sealed partial class BrowserWasm32ApplicationStorage : IApplicationStorag public BrowserWasm32ApplicationStorage(StorageScope scope) { if (!scope.isValid) + { throw new ArgumentException("Browser storage requires an assigned namespace.", nameof(scope)); + } m_prefix = scope.value + ":"; } @@ -116,7 +118,9 @@ public ValueTask DeleteAsync( cancellationToken.ThrowIfCancellationRequested(); string storageKey = Resolve(key); if (GetItem(storageKey) is null) + { return ValueTask.FromResult(false); + } RemoveItem(storageKey); return ValueTask.FromResult(true); } @@ -138,29 +142,34 @@ public ValueTask> ListAsync( CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); - var keys = new List(); + List keys = []; for (int index = 0; index < GetItemCount(); index++) { string? browserKey = GetKeyAt(index); if (browserKey is null || !browserKey.StartsWith(m_prefix, StringComparison.Ordinal)) + { continue; + } var key = new StorageKey(browserKey[m_prefix.Length..]); if (prefix is { } requested && key != requested - && !key.value.StartsWith(requested.value + "/", StringComparison.Ordinal)) - { + && !key.value.StartsWith(requested.value + "/", StringComparison.Ordinal) + ) { continue; } keys.Add(key); } return ValueTask.FromResult>( - keys.OrderBy(static key => key.value, StringComparer.Ordinal).ToArray()); + keys.OrderBy(static key => key.value, StringComparer.Ordinal).ToArray() + ); } private string Resolve(StorageKey key) { if (!key.isValid) + { throw new ArgumentException("A valid storage key is required.", nameof(key)); + } return m_prefix + key.value; } diff --git a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs index a5a031bd1..9ad664aaf 100644 --- a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs +++ b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs @@ -11,12 +11,9 @@ public sealed class BrowserWasm32StorageBackendProvider : StorageBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public BrowserWasm32StorageBackendProvider() : base(StorageBackendId.browser) { } + public BrowserWasm32StorageBackendProvider() + : base(StorageBackendID.browser) {} - /// - public override IApplicationStorage CreateStorage(StorageScope scope) - { - return new BrowserWasm32ApplicationStorage(scope); - } + /// + public override IApplicationStorage CreateStorage(StorageScope scope) => new BrowserWasm32ApplicationStorage(scope); } - diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs index fb27c34c6..34d230af0 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs @@ -9,9 +9,17 @@ namespace Inno.Build.MacOSArm64; /// public sealed class MacOSArm64BuildHostProvider : IBuildHostProvider { - /// - public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsMacOS() - || RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? null - : new("MacOS", "arm64", new BuildHostServices(new PhysicalToolchainWorkspaceProvider(), - inputPaths: ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs"])); + /// + public BuildHostDescriptor? TryCapture() + => !OperatingSystem.IsMacOS() + || RuntimeInformation.ProcessArchitecture != Architecture.Arm64 + ? null + : new BuildHostDescriptor( + "MacOS", + "arm64", + new BuildHostServices( + new PhysicalToolchainWorkspaceProvider(), + inputPaths: ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs"] + ) + ); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs index b7745ff09..278371ed0 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs @@ -14,7 +14,13 @@ public static class MacOSArm64BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("macos-arm64"), "MacOS", "arm64", "darwin-arm64", "osx-arm64", true); + new BuildTargetID("macos-arm64"), + "MacOS", + "arm64", + "darwin-arm64", + "osx-arm64", + true + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -51,11 +57,15 @@ INativeBindingGenerator bindingGenerator ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); ArgumentNullException.ThrowIfNull(editorNativePlan); - return new(target, + return new( + target, () => new MacOSArm64GameBuildTarget(supportPackValidator), - new MacOSArm64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), new MacOSArm64NativeToolchainProvider(context.dotnetHost), + new MacOSArm64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), + new MacOSArm64NativeToolchainProvider(context.dotnetHost), "platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/Inno.Editor.MacOSArm64.csproj", - [nativePlan, editorNativePlan, shaderToolsPlan], bindingGenerator, - [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot]); + [nativePlan, editorNativePlan, shaderToolsPlan], + bindingGenerator, + [ManagedDeploymentID.coreClr, ManagedDeploymentID.nativeAot] + ); } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs index 002df7f5d..98483a8ef 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs @@ -18,5 +18,14 @@ public static class MacOSArm64LinkerSettings /// The immutable target linker plan. /// public static NativeLinkPlan Create(IEnumerable? runtimeSearchPaths = null) - => new(".dylib", null, ".a", ["-DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON", "-DCMAKE_INSTALL_NAME_DIR=@rpath", "-DCMAKE_BUILD_RPATH=" + string.Join(';', runtimeSearchPaths ?? [])]); + => new( + ".dylib", + null, + ".a", + [ + "-DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON", + "-DCMAKE_INSTALL_NAME_DIR=@rpath", + "-DCMAKE_BUILD_RPATH=" + string.Join(';', runtimeSearchPaths ?? []) + ] + ); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs index 80a58a76d..502086523 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs @@ -22,12 +22,12 @@ public sealed class MacOSArm64PlayerSupportPackSource : IPlayerSupportPackSource /// /// The declared machine executing platform tools. /// - /// - /// The borrowed shared binding implementation selected by distribution. - /// /// /// The explicit SDK executable for binding generation. /// + /// + /// The borrowed shared binding implementation selected by distribution. + /// /// /// The borrowed validator selected by the distribution. /// @@ -39,24 +39,32 @@ public MacOSArm64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, "osx-arm64", Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id.value, ".dylib", + MacOSArm64BuildModule.target.id, + "osx-arm64", + MacOSArm64BuildModule.target.id.value, + ".dylib", supportPackValidator, "platforms/MacOSArm64/player/Inno.Player.MacOSArm64/Inno.Player.MacOSArm64.csproj", "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Templates/MacOSArm64Player.project.xml", - nativePlan.plan, nativePlan.executor, new MacOSArm64NativeToolchainProvider(dotnetHost), host, bindingGenerator, + nativePlan.plan, + nativePlan.executor, + new MacOSArm64NativeToolchainProvider(dotnetHost), + host, + bindingGenerator, ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs", - "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs"]); + "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs"] + ); } - /// - public BuildTargetId target => Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id; + /// + public BuildTargetID target => MacOSArm64BuildModule.target.id; - /// + /// public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => m_preparation.CreatePlanAsync(context, cancellationToken); - /// + /// public void Validate(string directory) => m_preparation.Validate(directory); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs index 0507b14ab..842b72de7 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs @@ -29,30 +29,44 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'."); + $"Player Support Pack '{MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + ); } if (Path.GetExtension(file).Equals(".dylib", StringComparison.OrdinalIgnoreCase)) + { ValidateLibrary(file); + } } foreach (string input in new[] { - "Player.csproj", "Program.cs", "MacOSArm64PlayerComposition.cs", "MacOSArm64PlayerContentSource.cs", "global.json", + "Player.csproj", + "Program.cs", + "MacOSArm64PlayerComposition.cs", + "MacOSArm64PlayerContentSource.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) + }) { if (!File.Exists(Path.Combine(directory, "PlayerLink", input))) + { throw new InvalidDataException($"The MacOS Support Pack lacks publication input '{input}'."); + } + } } private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); - if (input.BaseStream.Length < 32 || input.ReadUInt32() != 0xfeedfacf - || input.ReadUInt32() != 0x0100000c) + if (input.BaseStream.Length < 32 || input.ReadUInt32() != 0xFEED_FACF + || input.ReadUInt32() != 0x0100_000C + ) { throw new InvalidDataException($"MacOSArm64 native library '{file}' does not target the Mach-O ARM64 ABI."); + } _ = input.ReadUInt32(); if (input.ReadUInt32() != 6) + { throw new InvalidDataException($"MacOSArm64 native library '{file}' is not a dynamic library."); + } } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs index c405a1a7d..9d1352ea6 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs @@ -25,30 +25,19 @@ public sealed class MacOSArm64GameBuildTarget : IGameBuildTarget /// public MacOSArm64GameBuildTarget(IPlayerSupportPackValidator supportPackValidator) { - m_supportPackValidator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); + ArgumentNullException.ThrowIfNull(supportPackValidator); + m_supportPackValidator = supportPackValidator; } - - /// - /// Validates the target closure before runtime script compilation. - /// - /// - /// The Support Pack directory selected by the build catalog. - /// - /// - /// The required platform inputs are incomplete or incompatible. - /// - public void Validate(string directory) => m_supportPackValidator.Validate(directory); - /// /// Gets the macOS ARM64 target identity. /// - public BuildTargetId id => Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id; + public BuildTargetID id => MacOSArm64BuildModule.target.id; - /// - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; + /// + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.coreClr; - /// + /// public string runtimeIdentifier => "osx-arm64"; /// @@ -56,7 +45,16 @@ public MacOSArm64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// public string displayName => "macOS (Apple silicon)"; - + /// + /// Validates the target closure before runtime script compilation. + /// + /// + /// The Support Pack directory selected by the build catalog. + /// + /// + /// The required platform inputs are incomplete or incompatible. + /// + public void Validate(string directory) => m_supportPackValidator.Validate(directory); /// /// Composes a macOS application bundle in isolated staging. @@ -79,20 +77,31 @@ public async ValueTask PackageAsync( string contents = Path.Combine(application, "Contents"); string executableRoot = Path.Combine(contents, "MacOS"); string resources = Path.Combine(contents, "Resources"); - await CopyDirectoryAsync(context.managedDeployment.outputDirectory, executableRoot, cancellationToken, - excludeCompilerReferences: true) + await CopyDirectoryAsync( + context.managedDeployment.outputDirectory, + executableRoot, + excludeCompilerReferences: true, + cancellationToken: cancellationToken + ) .ConfigureAwait(false); string player = Path.Combine(executableRoot, "Inno.Player.MacOSArm64"); if (!File.Exists(player)) + { throw new InvalidDataException("The macOS managed publication does not contain Inno.Player.MacOSArm64."); + } File.Move(player, Path.Combine(executableRoot, context.profile.productName)); - await CopyDirectoryAsync(context.contentDirectory, Path.Combine(resources, "Content"), cancellationToken, - excludeCompilerReferences: false) + await CopyDirectoryAsync( + context.contentDirectory, + Path.Combine(resources, "Content"), + excludeCompilerReferences: false, + cancellationToken: cancellationToken + ) .ConfigureAwait(false); Directory.CreateDirectory(contents); string product = SecurityElement.Escape(context.profile.productName) ?? context.profile.productName; string identifier = SecurityElement.Escape(context.profile.applicationId) ?? context.profile.applicationId; - await File.WriteAllTextAsync( + await File + .WriteAllTextAsync( Path.Combine(contents, "Info.plist"), $""" @@ -105,7 +114,8 @@ await File.WriteAllTextAsync( NSHighResolutionCapable """, - cancellationToken) + cancellationToken + ) .ConfigureAwait(false); return application; } @@ -113,8 +123,8 @@ await File.WriteAllTextAsync( private static async ValueTask CopyDirectoryAsync( string source, string destination, - CancellationToken cancellationToken, - bool excludeCompilerReferences + bool excludeCompilerReferences, + CancellationToken cancellationToken ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) @@ -122,7 +132,9 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, directory); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } Directory.CreateDirectory(Path.Combine(destination, relativePath)); } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) @@ -130,14 +142,18 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, file); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(target, File.GetUnixFileMode(file)); + } } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs index 0ec82acff..92e3dbe26 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs @@ -30,36 +30,62 @@ public MacOSArm64NativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, - string targetId, + string targetID, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); - if (!(host.system == "MacOS" && host.architecture == "arm64" && targetId == "macos-arm64")) - throw new PlatformNotSupportedException($"The MacOS SDK cannot build '{targetId}' on {host.system}/{host.architecture}."); - var tools = new Dictionary(StringComparer.Ordinal) { ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) }; + if (!(host.system == "MacOS" && host.architecture == "arm64" && targetID == "macos-arm64")) + { + throw new PlatformNotSupportedException($"The MacOS SDK cannot build '{targetID}' on {host.system}/{host.architecture}."); + } + var tools = new Dictionary(StringComparer.Ordinal) + { + ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) + }; Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); - var inputs = new List(); - var cmakeArguments = new List(); + List inputs = []; + List cmakeArguments = []; string xcrun = ToolchainEnvironment.ResolveExecutable("xcrun"); - tools["clang"] = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--find", "clang"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); - tools["clang++"] = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--find", "clang++"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); - string sdk = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--sdk", "macosx", "--show-sdk-path"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); + tools["clang"] = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--find", "clang"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); + tools["clang++"] = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--find", "clang++"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); + string sdk = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--sdk", "macosx", "--show-sdk-path"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); environment["SDKROOT"] = sdk; inputs.AddRange([xcrun, Path.Combine(sdk, "usr", "include"), Path.Combine(sdk, "usr", "lib")]); cmakeArguments.AddRange(["-DCMAKE_OSX_SYSROOT=" + sdk, "-DCMAKE_OSX_ARCHITECTURES=arm64"]); ConfigureTools(tools, environment, cmakeArguments); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, inputs, - cmakeArguments, MacOSArm64LinkerSettings.Create(), false, new NativeCompilerInputs(tools["clang"], tools["clang++"], sdk)); + return NativeToolchainPreparation.Freeze( + targetID, + host, + tools, + environment, + inputs, + cmakeArguments, + MacOSArm64LinkerSettings.Create(), + false, + new NativeCompilerInputs(tools["clang"], tools["clang++"], sdk) + ); } private static void ConfigureTools( @@ -71,7 +97,9 @@ List cmakeArguments tools["cmake"] = ToolchainEnvironment.ResolveExecutable("cmake"); environment["CC"] = tools["clang"]; environment["CXX"] = tools["clang++"]; - cmakeArguments.AddRange(["-DCMAKE_C_COMPILER=" + environment["CC"], - "-DCMAKE_CXX_COMPILER=" + environment["CXX"]]); + cmakeArguments.AddRange([ + "-DCMAKE_C_COMPILER=" + environment["CC"], + "-DCMAKE_CXX_COMPILER=" + environment["CXX"] + ]); } } diff --git a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs index 10adacf6e..d116e2eef 100644 --- a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs +++ b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs @@ -14,7 +14,9 @@ using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; using Inno.Core.Input; @@ -44,13 +46,13 @@ public static class MacOSArm64EditorComposition /// /// An optional project directory and the shared Editor command-line options. /// - /// - /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. - /// /// /// Cancels preparation or requests orderly shutdown of the shared Editor host. /// An open native folder dialog retains its callback owner until the user completes or closes it. /// + /// + /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. + /// public static int Run( string[] arguments, CancellationToken cancellationToken @@ -64,31 +66,39 @@ CancellationToken cancellationToken using var picker = new Sdl3PlatformApplication(new MacOSArm64Sdl3HostIntegration()); string? selected = Sdl3FolderDialog.SelectFolder(picker); if (selected is null) + { return 0; + } arguments = [selected]; } EditorCommandLineOptions command = EditorCommandLineOptions.Parse(arguments); _ = MacOSArm64ApplicationLocations.userDataRoot; string project = Path.GetFullPath(command.projectDirectory); string persistentRoot = Path.Combine(project, "Library", "PersistentData"); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new MacOSArm64Sdl3HostIntegration())]), - rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new MacOSArm64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) - }, [new BgfxAuthoringProvider(MacOSArm64BgfxIntegration.shaderProfile)], - [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: true, horizontalWheelDirection: -1))]); - var buildContext = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, nativeDependencies: command.nativeDependencies); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new MacOSArm64Sdl3HostIntegration())]), + rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new MacOSArm64BgfxSurfaceIntegration())]), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) + }, + [new BgfxAuthoringProvider(MacOSArm64BgfxIntegration.shaderProfile)], + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: true, horizontalWheelDirection: -1))] + ); + BuildCompositionContext buildContext = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, + MacOSArm64BuildModule.target.id, + nativeDependencies: command.nativeDependencies + ); var launch = new EditorLaunchOptions { - defaultBuildTarget = Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + defaultBuildTarget = MacOSArm64BuildModule.target.id, projectDirectory = project, keyboard = new EditorKeyboardPolicy(KeyModifier.Super, "Cmd"), adapterCatalog = adapters, shell = new ShellOptions { - adapters = StandardAdapterSelection.Create(StorageBackendId.fileSystem), + adapters = StandardAdapterSelection.Create(StorageBackendID.fileSystem), window = new PlatformWindowOptions { title = "Inno Editor", @@ -101,18 +111,27 @@ CancellationToken cancellationToken preferredGraphicsApi = command.graphicsApi, sRgbBackbuffer = true }, - presentation = PresentationBackendId.imGui, + presentation = PresentationBackendID.imGui, frameDriver = new PollingShellFrameDriver(), distribution = StandardBuildDistribution.Create(buildContext).build, buildContext = buildContext, - supportPackRoot = Path.Combine(Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, "SupportPacks"), + supportPackRoot = Path.Combine( + Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, + "SupportPacks" + ), createEngineHost = CreateEngineHost, createScriptModuleSource = deployment => CreateScriptModuleSource(project, deployment), createSessionLogSink = ( kind, session - ) => new FileLogSink(Path.Combine(persistentRoot, - kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", "Logs", session.ToString())), + ) => new FileLogSink( + Path.Combine( + persistentRoot, + kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", + "Logs", + session.ToString() + ) + ), createHostLogSink = () => new ConsoleLogSink(useColors: true), smokeFrameLimit = command.smokeFrameLimit }; @@ -138,7 +157,8 @@ private static EngineHost CreateEngineHost() => new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(MacOSArm64EditorComposition).Assembly), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); private static IModuleSource CreateScriptModuleSource( string project, diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs index 40aafcba5..f1ae063a4 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs @@ -37,10 +37,13 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); - if (handles.handleKind != PlatformNativeHandleId.cocoa) + } + if (handles.handleKind != PlatformNativeHandleID.cocoa) + { throw new NotSupportedException("The MacOS BGFX integration requires its explicit cocoa surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: true); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: true); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs index f35ce4889..9f9eba269 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs @@ -1,6 +1,6 @@ using System; -using Inno.Build.MacOSArm64; using System.Collections.Generic; +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx; @@ -8,36 +8,42 @@ namespace Inno.Integration.MacOSArm64.Bgfx; internal sealed class MacOSArm64BgfxBuildProfile : BgfxNativeBuildProfile { - /// - public override NativeToolchainSelection SelectTools( - NativeBuildContext context, - bool includeTools - ) => MacOSArm64BgfxToolContribution.Select(context, includeTools); + /// + public override string targetID => MacOSArm64BuildModule.target.id.value; - /// - public override string targetId => MacOSArm64BuildModule.target.id.value; - /// + /// public override IReadOnlyList generatorArguments => ["--gcc=osx-arm64", "gmake"]; - /// + + /// public override string artifactPathToken => "/osx-arm64/bin/"; - /// + /// public override IReadOnlyList bindingCmakeArguments => []; - /// + /// + public override NativeToolchainSelection SelectTools( + NativeBuildContext context, + bool includeTools + ) => MacOSArm64BgfxToolContribution.Select(context, includeTools); + + /// public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) { ArgumentException.ThrowIfNullOrWhiteSpace(archivePath); return (archivePath, ["-Xlinker", "-force_load", "-Xlinker", "\"" + archivePath + "\""]); } - /// + /// public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, bool includeTools ) { string[] arguments = ["-C", ".build/projects/gmake-osx-arm64", "config=" + context.configuration]; - return new("make", includeTools - ? [.. arguments, "shaderc", "texturec", "geometryc", "geometryv", "texturev"] : arguments); + return new( + "make", + includeTools + ? [.. arguments, "shaderc", "texturec", "geometryc", "geometryv", "texturev"] + : arguments + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxIntegration.cs index 428818f3d..b4da484fd 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxIntegration.cs @@ -40,6 +40,6 @@ public static GameContentCompilerFactory CreateContentCompilerFactory(ToolRunner assets, serialization, types - ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.Metal], tools); + ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.metal], tools); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs index 9e4755a55..dba2a99eb 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs @@ -1,8 +1,7 @@ +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Inno.Build.MacOSArm64; - namespace Inno.Integration.MacOSArm64.Bgfx; /// @@ -13,10 +12,19 @@ public static class MacOSArm64BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(MacOSArm64BuildModule.target.id.value, - [ - new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"]), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "osx", "430", "430", "430") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + MacOSArm64BuildModule.target.id.value, + [ + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.metal), "osx", "metal", "metal", "metal"), + new BgfxShaderCompilerProfile( + BgfxTargetCapabilities.Create(GraphicsApi.vulkan), + "osx", + "spirv", + "spirv", + "spirv", + ["BGFX_SHADER_LANGUAGE_SPIRV=1"] + ), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.openGL), "osx", "430", "430", "430") + ] + ); } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs index 1a357ff46..f92c560d8 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs @@ -14,7 +14,9 @@ bool includeTools ) { NativeToolchainSelection sdk = context.RequireToolchain(); if (sdk.host.system != "MacOS") + { throw new PlatformNotSupportedException("This BGFX integration requires a MacOS tool host."); + } string generator; if (!sdk.TryResolveExecutable("genie", out generator)) { @@ -31,10 +33,20 @@ bool includeTools string dotnet = sdk.ResolveExecutable("dotnet"); string cmake = sdk.ResolveExecutable("cmake"); if (!includeTools) + { tools.Add("cmake", cmake); - return new NativeToolchainSelection(sdk.targetId, sdk.host, tools, sdk.environment, + } + return new NativeToolchainSelection( + sdk.targetID, + sdk.host, + tools, + sdk.environment, sdk.inputPaths.Where(path => path != dotnet && (!includeTools || path != cmake)) .Concat([Path.Combine(owner, "MacOSArm64BgfxToolContribution.cs"), Path.Combine(owner, "MacOSArm64BgfxBuildProfile.cs")]), - includeTools ? [] : sdk.cmakeArguments, sdk.linkPlan, sdk.multiConfiguration, sdk.compilerInputs); + includeTools ? [] : sdk.cmakeArguments, + sdk.linkPlan, + sdk.multiConfiguration, + sdk.compilerInputs + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs index f11f87736..cd8062b3e 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs @@ -7,9 +7,11 @@ namespace Inno.Integration.MacOSArm64.Build; internal static class MacOSArm64BindingProfile { - internal static NativeBindingProfile Create() => new( - MacOSArm64BuildModule.target.id.value, - new TargetConfiguration { id = "macos-arm64-darwin" }, - new ManagedRuntimeId("dotnet.coreclr"), - ["platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs"]); + internal static NativeBindingProfile Create() + => new( + MacOSArm64BuildModule.target.id.value, + new TargetConfiguration { id = "macos-arm64-darwin" }, + new ManagedRuntimeId("dotnet.coreclr"), + ["platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs"] + ); } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs index 6aff43b06..dfba5ea17 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs @@ -11,10 +11,15 @@ internal static class MacOSArm64NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs index 936ca4075..e3f917c16 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs @@ -27,13 +27,38 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(MacOSArm64BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateDynamic(player, MacOSArm64BuildModule.target.id, ".dylib"), - new MacOSArm64SupportPackValidator(), StandardNativeDeployment.CreateValidator(MacOSArm64BuildModule.target.id, ".dylib")); + new MacOSArm64SupportPackValidator(), + StandardNativeDeployment.CreateValidator(MacOSArm64BuildModule.target.id, ".dylib") + ); var executor = new ComponentNativeProductExecutor(); - return MacOSArm64BuildModule.CreateContribution(context, new NativeProductContribution(player, executor), - new NativeProductContribution(StandardNativeComponents.CreateEditor(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map), executor), - new NativeProductContribution(StandardNativeComponents.CreateShaderTools(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map), executor), validator, generator); + return MacOSArm64BuildModule.CreateContribution( + context, + new NativeProductContribution(player, executor), + new NativeProductContribution( + StandardNativeComponents.CreateEditor( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ), + executor + ), + new NativeProductContribution( + StandardNativeComponents.CreateShaderTools( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ), + executor + ), + validator, + generator + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs index 74c8a4ce5..b7c44216e 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs @@ -10,10 +10,12 @@ internal static class MacOSArm64NativeProducts private const string C_INPUT = "platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs"; internal static NativeComponentBuildOptions Options(string component) - { - return new(NativeLibraryKind.Shared, inputPaths: [C_INPUT], + => new( + NativeLibraryKind.Shared, + inputPaths: [C_INPUT], bindingIncludeDirectories: component == "bgfx" ? ["extern/bx/include/compat/osx"] : [], linkPlan: component == "cimguizmo" - ? MacOSArm64LinkerSettings.Create(["@loader_path/../../cimgui/" + MacOSArm64BuildModule.target.id.value]) : null); - } + ? MacOSArm64LinkerSettings.Create(["@loader_path/../../cimgui/" + MacOSArm64BuildModule.target.id.value]) + : null + ); } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs index 4b73d51e8..00bbc37ba 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs @@ -11,39 +11,36 @@ namespace Inno.Integration.MacOSArm64.Sdl3; /// public sealed class MacOSArm64Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: true, liveResize: true); - /// - public void ConfigureInitialization() - { - _ = SDL.SetHint("SDL_MAC_PRESS_AND_HOLD", "0"); - } + /// + public void ConfigureInitialization() => _ = SDL.SetHint("SDL_MAC_PRESS_AND_HOLD", "0"); - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.cocoa.window\0"u8; nint surface; fixed (byte* name = propertyName) + { surface = (nint)SDL.Raw.GetPointerProperty(properties, (sbyte*)name, null); + } if (surface == 0) + { throw new InvalidOperationException("SDL did not provide the required MacOS surface."); - return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.cocoa); + } + return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleID.cocoa); } - /// - public bool GetInitialFocus(nint windowHandle) - { - return Sdl3WindowOperations.ReadFocus(windowHandle); - } + /// + public bool GetInitialFocus(nint windowHandle) => Sdl3WindowOperations.ReadFocus(windowHandle); } diff --git a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs index ed336a300..06b14b356 100644 --- a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs +++ b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs @@ -1,23 +1,23 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.MacOSArm64.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.MacOSArm64.Sdl3; using System; +using System.IO; using Inno.Adapter; using Inno.Adapter.Default; -using Inno.Rendering; -using System.IO; -using Inno.Player.Runtime; -using Inno.Shell; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; +using Inno.Integration.MacOSArm64.Bgfx.Runtime; +using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Platform.MacOSArm64; +using Inno.Player.Runtime; +using Inno.Rendering; using Inno.Runtime; +using Inno.Shell; using Inno.Storage; -using Inno.Platform.MacOSArm64; namespace Inno.Player.MacOSArm64; @@ -46,15 +46,15 @@ internal static int Run(string[] arguments) types = Generated.PlayerMetadataComposition.CreateTypes(), serializationMetadata = Generated.PlayerMetadataComposition.CreateSerialization(), adapters = adapterCatalog, - adapterSelection = StandardAdapterSelection.Create(StorageBackendId.fileSystem), + adapterSelection = StandardAdapterSelection.Create(StorageBackendID.fileSystem), contentSource = new MacOSArm64PlayerContentSource(AppContext.BaseDirectory, dataRoot), createStorage = manifest => new FileSystemApplicationStorage( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage")), + Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage") + ), createLogSink = ( manifest, - sessionId - ) => new FileLogSink( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), + sessionID + ) => new FileLogSink(Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionID.ToString())), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new PollingShellFrameDriver(), consoleColors = true, @@ -74,5 +74,4 @@ private static string ResolveDataRoot( string root, GameRuntimeManifest manifest ) => Path.Combine(root, manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); - } diff --git a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs index 412f18f58..5384acc3f 100644 --- a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs +++ b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs @@ -16,8 +16,12 @@ internal sealed class MacOSArm64PlayerContentSource : IPlayerContentSource internal MacOSArm64PlayerContentSource( string applicationDirectory, string cacheRoot - ) => m_files = new FileContentDeployment( - MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), cacheRoot); + ) { + m_files = new FileContentDeployment( + MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); + } /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs b/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs index 030b283bf..25f986ed6 100644 --- a/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs +++ b/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs @@ -22,10 +22,18 @@ public static string userDataRoot get { if (!OperatingSystem.IsMacOS()) + { throw new PlatformNotSupportedException("This product requires MacOS."); - string location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Application Support"); + } + string location = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + "Library", + "Application Support" + ); if (string.IsNullOrWhiteSpace(location) || !Path.IsPathFullyQualified(location)) + { throw new InvalidOperationException("The system did not provide a usable application data root."); + } return location; } } @@ -46,7 +54,9 @@ public static string GetPlayerContentDirectory(string applicationDirectory) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("An application directory must be absolute.", nameof(applicationDirectory)); + } return Path.GetFullPath(Path.Combine(applicationDirectory, "..", "Resources", "Content")); } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs index bc81340a7..b67de386a 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs @@ -9,11 +9,20 @@ namespace Inno.Build.WindowsX64; /// public sealed class WindowsBuildHostProvider : IBuildHostProvider { - /// - public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsWindows() ? null - : new("Windows", RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), - new BuildHostServices(new WindowsToolchainWorkspaceProvider(), StringComparer.OrdinalIgnoreCase, - ["platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs"], ".exe")); + /// + public BuildHostDescriptor? TryCapture() + => !OperatingSystem.IsWindows() + ? null + : new BuildHostDescriptor( + "Windows", + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), + new BuildHostServices( + new WindowsToolchainWorkspaceProvider(), + StringComparer.OrdinalIgnoreCase, + ["platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs", + "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs", + "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs"], + ".exe" + ) + ); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs index ae25de827..79e3434fc 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs @@ -9,8 +9,8 @@ namespace Inno.Build.WindowsX64; internal sealed class WindowsToolchainDirectory : IDisposable { - private const uint C_MOUNT_POINT_TAG = 0xA0000003; - private const uint C_SET_REPARSE_POINT = 0x000900A4; + private const uint C_MOUNT_POINT_TAG = 0xA000_0003; + private const uint C_SET_REPARSE_POINT = 0x0009_00A4; private readonly string m_physicalPath; private WindowsToolchainDirectory( @@ -21,6 +21,17 @@ string toolPath this.toolPath = toolPath; } + /// + public void Dispose() + { + if (toolPath == m_physicalPath || !Directory.Exists(toolPath)) + { + return; + } + ValidateAlias(toolPath, m_physicalPath); + Directory.Delete(toolPath, recursive: false); + } + internal string toolPath { get; } internal static WindowsToolchainDirectory Create(string physicalPath) @@ -39,10 +50,13 @@ internal static WindowsToolchainDirectory Create(string physicalPath) Directory.CreateDirectory(alias); try { - byte[] substitute = Encoding.Unicode.GetBytes(physicalPath.StartsWith("\\\\", StringComparison.Ordinal) - ? "\\??\\UNC\\" + physicalPath[2..] : "\\??\\" + physicalPath); + byte[] substitute = Encoding.Unicode.GetBytes( + physicalPath.StartsWith("\\\\", StringComparison.Ordinal) + ? "\\??\\UNC\\" + physicalPath[2..] + : "\\??\\" + physicalPath + ); byte[] printable = Encoding.Unicode.GetBytes(physicalPath); - byte[] data = new byte[20 + substitute.Length + printable.Length]; + var data = new byte[20 + substitute.Length + printable.Length]; Write(data, 0, C_MOUNT_POINT_TAG); Write(data, 4, checked((ushort)(data.Length - 8))); Write(data, 10, checked((ushort)substitute.Length)); @@ -51,12 +65,15 @@ internal static WindowsToolchainDirectory Create(string physicalPath) substitute.CopyTo(data, 16); printable.CopyTo(data, 18 + substitute.Length); - using SafeFileHandle handle = CreateFile(alias, 0x40000000, 7, nint.Zero, 3, 0x02200000, nint.Zero); + using SafeFileHandle handle = CreateFile(alias, 0x4000_0000, 7, nint.Zero, 3, 0x0220_0000, nint.Zero); if (handle.IsInvalid) + { throw new Win32Exception(Marshal.GetLastPInvokeError(), "Cannot open the owned toolchain directory alias."); - if (!DeviceIoControl(handle, C_SET_REPARSE_POINT, data, (uint)data.Length, - nint.Zero, 0, out _, nint.Zero)) + } + if (!DeviceIoControl(handle, C_SET_REPARSE_POINT, data, (uint)data.Length, nint.Zero, 0, out _, nint.Zero)) + { throw new Win32Exception(Marshal.GetLastPInvokeError(), "Cannot create the owned toolchain directory alias."); + } return new(physicalPath, alias); } catch @@ -66,22 +83,15 @@ internal static WindowsToolchainDirectory Create(string physicalPath) } } - /// - public void Dispose() - { - if (toolPath == m_physicalPath || !Directory.Exists(toolPath)) - return; - ValidateAlias(toolPath, m_physicalPath); - Directory.Delete(toolPath, recursive: false); - } - private static void ValidateAlias( string alias, string physicalPath ) { string? target = new DirectoryInfo(alias).LinkTarget; if (target is null || !Path.GetFullPath(target).Equals(physicalPath, StringComparison.OrdinalIgnoreCase)) + { throw new IOException($"Toolchain directory alias '{alias}' is occupied by a different directory."); + } } private static void Write( diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs index 91be8c1cc..bc7dc3881 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs @@ -14,23 +14,31 @@ namespace Inno.Build.WindowsX64; /// public sealed class WindowsToolchainWorkspaceProvider : IToolchainWorkspaceProvider { - /// + /// public string identity => Path.Combine(Path.GetTempPath(), "InnoTools"); - /// + /// public async ValueTask OpenAsync( string physicalPath, CancellationToken cancellationToken = default ) { if (!OperatingSystem.IsWindows()) + { throw new PlatformNotSupportedException("Windows execution workspaces require a Windows host."); + } if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("Toolchain workspaces require absolute owner paths.", nameof(physicalPath)); + } string physical = Path.TrimEndingDirectorySeparator(Path.GetFullPath(physicalPath)); string leaf = GetAliasPath(physical) + ".lock"; string owner = Path.Combine(Path.GetDirectoryName(leaf)!, "owner.lock"); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(owner, leaf, - Timeout.InfiniteTimeSpan, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + owner, + leaf, + Timeout.InfiniteTimeSpan, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); @@ -47,7 +55,9 @@ public async ValueTask OpenAsync( internal static string GetAliasPath(string physicalPath) { string identity = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(physicalPath.ToUpperInvariant()))) - .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); return Path.Combine(Path.GetTempPath(), "InnoTools", identity); } @@ -58,7 +68,7 @@ private sealed class Ownership( string leaf ) : IDisposable { - /// + /// public void Dispose() { try diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs index fed649cb9..3a08bec8e 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs @@ -13,6 +13,5 @@ public static class WindowsX64LinkerSettings /// /// The immutable target linker plan. /// - public static NativeLinkPlan Create() - => new(".dll", ".lib", ".lib", []); + public static NativeLinkPlan Create() => new(".dll", ".lib", ".lib", []); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs index 60379b732..294765807 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs @@ -22,12 +22,12 @@ public sealed class WindowsX64PlayerSupportPackSource : IPlayerSupportPackSource /// /// The declared machine executing platform tools. /// - /// - /// The borrowed shared binding implementation selected by distribution. - /// /// /// The explicit SDK executable for binding generation. /// + /// + /// The borrowed shared binding implementation selected by distribution. + /// /// /// The borrowed validator selected by the distribution. /// @@ -39,24 +39,32 @@ public WindowsX64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, "win-x64", Inno.Build.WindowsX64.WindowsX64BuildModule.target.id.value, ".dll", + WindowsX64BuildModule.target.id, + "win-x64", + WindowsX64BuildModule.target.id.value, + ".dll", supportPackValidator, "platforms/WindowsX64/player/Inno.Player.WindowsX64/Inno.Player.WindowsX64.csproj", "platforms/WindowsX64/build/Inno.Build.WindowsX64/Templates/WindowsX64Player.project.xml", - nativePlan.plan, nativePlan.executor, new WindowsX64NativeToolchainProvider(dotnetHost), host, bindingGenerator, + nativePlan.plan, + nativePlan.executor, + new WindowsX64NativeToolchainProvider(dotnetHost), + host, + bindingGenerator, ["platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs"]); + "platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs"] + ); } - /// - public BuildTargetId target => Inno.Build.WindowsX64.WindowsX64BuildModule.target.id; + /// + public BuildTargetID target => WindowsX64BuildModule.target.id; - /// + /// public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => m_preparation.CreatePlanAsync(context, cancellationToken); - /// + /// public void Validate(string directory) => m_preparation.Validate(directory); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs index 4ed16d067..4e12a76ac 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs @@ -29,36 +29,54 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.WindowsX64.WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'."); + $"Player Support Pack '{WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + ); } if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase)) + { ValidateLibrary(file); + } } foreach (string input in new[] { - "Player.csproj", "Program.cs", "WindowsX64PlayerComposition.cs", "WindowsX64PlayerContentSource.cs", "global.json", + "Player.csproj", + "Program.cs", + "WindowsX64PlayerComposition.cs", + "WindowsX64PlayerContentSource.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) + }) { if (!File.Exists(Path.Combine(directory, "PlayerLink", input))) + { throw new InvalidDataException($"The Windows Support Pack lacks publication input '{input}'."); + } + } } private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); - if (input.BaseStream.Length < 64 || input.ReadUInt16() != 0x5a4d) + if (input.BaseStream.Length < 64 || input.ReadUInt16() != 0x5A4D) + { throw new InvalidDataException($"WindowsX64 native library '{file}' has no PE header."); + } input.BaseStream.Position = 60; int offset = input.ReadInt32(); if (offset < 64 || offset > input.BaseStream.Length - 26) + { throw new InvalidDataException($"WindowsX64 native library '{file}' has an invalid PE header offset."); + } input.BaseStream.Position = offset; - if (input.ReadUInt32() != 0x00004550 || input.ReadUInt16() != 0x8664) + if (input.ReadUInt32() != 0x0000_4550 || input.ReadUInt16() != 0x8664) + { throw new InvalidDataException($"WindowsX64 native library '{file}' does not target the AMD64 ABI."); + } input.BaseStream.Position = offset + 22; - if ((input.ReadUInt16() & 0x2000) == 0 || input.ReadUInt16() != 0x020b) + if ((input.ReadUInt16() & 0x2000) == 0 || input.ReadUInt16() != 0x020B) + { throw new InvalidDataException($"WindowsX64 native library '{file}' is not a PE32+ dynamic library."); + } } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs index 639a0a14c..8b2ddde16 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs @@ -24,30 +24,19 @@ public sealed class WindowsX64GameBuildTarget : IGameBuildTarget /// public WindowsX64GameBuildTarget(IPlayerSupportPackValidator supportPackValidator) { - m_supportPackValidator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); + ArgumentNullException.ThrowIfNull(supportPackValidator); + m_supportPackValidator = supportPackValidator; } - - /// - /// Validates the target closure before runtime script compilation. - /// - /// - /// The Support Pack directory selected by the build catalog. - /// - /// - /// The required platform inputs are incomplete or incompatible. - /// - public void Validate(string directory) => m_supportPackValidator.Validate(directory); - /// /// Gets the Windows x64 target identity. /// - public BuildTargetId id => Inno.Build.WindowsX64.WindowsX64BuildModule.target.id; + public BuildTargetID id => WindowsX64BuildModule.target.id; - /// - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; + /// + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.coreClr; - /// + /// public string runtimeIdentifier => "win-x64"; /// @@ -55,7 +44,16 @@ public WindowsX64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// public string displayName => "Windows (x64)"; - + /// + /// Validates the target closure before runtime script compilation. + /// + /// + /// The Support Pack directory selected by the build catalog. + /// + /// + /// The required platform inputs are incomplete or incompatible. + /// + public void Validate(string directory) => m_supportPackValidator.Validate(directory); /// /// Composes a Windows application directory in isolated staging. @@ -75,14 +73,24 @@ public async ValueTask PackageAsync( ) { ArgumentNullException.ThrowIfNull(context); string application = Path.Combine(context.outputDirectory, context.profile.productName + "-Windows-x64"); - await CopyDirectoryAsync(context.managedDeployment.outputDirectory, application, cancellationToken, - excludeCompilerReferences: true).ConfigureAwait(false); + await CopyDirectoryAsync( + context.managedDeployment.outputDirectory, + application, + excludeCompilerReferences: true, + cancellationToken: cancellationToken + ).ConfigureAwait(false); string player = Path.Combine(application, "Inno.Player.WindowsX64.exe"); if (!File.Exists(player)) + { throw new InvalidDataException("The Windows managed publication does not contain Inno.Player.WindowsX64.exe."); + } File.Move(player, Path.Combine(application, context.profile.productName + ".exe")); - await CopyDirectoryAsync(context.contentDirectory, Path.Combine(application, "Content"), cancellationToken, - excludeCompilerReferences: false) + await CopyDirectoryAsync( + context.contentDirectory, + Path.Combine(application, "Content"), + excludeCompilerReferences: false, + cancellationToken: cancellationToken + ) .ConfigureAwait(false); return application; } @@ -90,8 +98,8 @@ await CopyDirectoryAsync(context.contentDirectory, Path.Combine(application, "Co private static async ValueTask CopyDirectoryAsync( string source, string destination, - CancellationToken cancellationToken, - bool excludeCompilerReferences + bool excludeCompilerReferences, + CancellationToken cancellationToken ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) @@ -99,7 +107,9 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, directory); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } Directory.CreateDirectory(Path.Combine(destination, relativePath)); } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) @@ -107,11 +117,13 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, file); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs index ea563b162..a616fba16 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs @@ -30,71 +30,118 @@ public WindowsX64NativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, - string targetId, + string targetID, CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); - if (!(host.system == "Windows" && host.architecture == "x64" && targetId == "windows-x64")) - throw new PlatformNotSupportedException($"The Windows SDK cannot build '{targetId}' on {host.system}/{host.architecture}."); - var tools = new Dictionary(StringComparer.Ordinal) { ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) }; + if (!(host.system == "Windows" && host.architecture == "x64" && targetID == "windows-x64")) + { + throw new PlatformNotSupportedException($"The Windows SDK cannot build '{targetID}' on {host.system}/{host.architecture}."); + } + var tools = new Dictionary(StringComparer.Ordinal) + { + ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) + }; Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); - var inputs = new List(); - var cmakeArguments = new List(); - string locator = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), - "Microsoft Visual Studio", "Installer", "vswhere.exe"); - string installation = (await ToolchainEnvironment.CaptureOutputAsync(locator, + List inputs = []; + List cmakeArguments = []; + string locator = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), + "Microsoft Visual Studio", + "Installer", + "vswhere.exe" + ); + string installation = (await ToolchainEnvironment.CaptureOutputAsync( + locator, ["-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", - "-property", "installationPath"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); + "-property", "installationPath"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); if (!Directory.Exists(installation)) + { throw new InvalidOperationException("No Visual Studio installation with the x64 C++ tools was found."); + } string setup = Path.Combine(installation, "Common7", "Tools", "VsDevCmd.bat"); var query = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe")) { Arguments = $"/d /s /c \"call \"{setup}\" -arch=x64 -host_arch=x64 >nul && set\"" }; - query.Environment["PATH"] = string.Join(Path.PathSeparator, Environment.SystemDirectory, + query.Environment["PATH"] = string.Join( + Path.PathSeparator, + Environment.SystemDirectory, Environment.GetFolderPath(Environment.SpecialFolder.Windows), - Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0")); + Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0") + ); string output = await ToolchainEnvironment.CaptureOutputAsync(query, cancellationToken).ConfigureAwait(false); var selected = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string line in output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)) { int separator = line.IndexOf('='); if (separator > 0) + { selected[line[..separator]] = line[(separator + 1)..]; + } } foreach (string name in new[] { "PATH", "INCLUDE", "LIB", "LIBPATH", "VCToolsInstallDir", - "VCToolsVersion", "WindowsSdkDir", "WindowsSDKVersion" }) + "VCToolsVersion", "WindowsSdkDir", "WindowsSDKVersion" } + ) { environment[name] = RequireVariable(selected, name); + } string compilerDirectory = Path.Combine(environment["VCToolsInstallDir"], "bin", "Hostx64", "x64"); tools["cl"] = Path.Combine(compilerDirectory, "cl.exe"); tools["msbuild"] = Path.Combine(installation, "MSBuild", "Current", "Bin", "MSBuild.exe"); - tools["cmake"] = Path.Combine(installation, "Common7", "IDE", "CommonExtensions", "Microsoft", - "CMake", "CMake", "bin", "cmake.exe"); + tools["cmake"] = Path.Combine( + installation, + "Common7", + "IDE", + "CommonExtensions", + "Microsoft", + "CMake", + "CMake", + "bin", + "cmake.exe" + ); inputs.AddRange([locator, setup, compilerDirectory, Path.GetDirectoryName(tools["msbuild"])!]); foreach (string name in new[] { "INCLUDE", "LIB" }) + { inputs.AddRange(environment[name].Split(';', StringSplitOptions.RemoveEmptyEntries)); + } cmakeArguments.AddRange([ "-DCMAKE_GENERATOR_INSTANCE=" + installation, - "-T", "version=" + environment["VCToolsVersion"], - "-DCMAKE_SYSTEM_VERSION=" + environment["WindowsSDKVersion"].TrimEnd('\\', '/')]); + "-T", + "version=" + environment["VCToolsVersion"], + "-DCMAKE_SYSTEM_VERSION=" + environment["WindowsSDKVersion"].TrimEnd('\\', '/') + ]); cmakeArguments.InsertRange(0, ["-G", "Visual Studio 17 2022", "-A", "x64"]); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, inputs, - cmakeArguments, WindowsX64LinkerSettings.Create(), true, new NativeCompilerInputs(tools["cl"], tools["cl"], - systemIncludeDirectories: environment["INCLUDE"].Split(';', StringSplitOptions.RemoveEmptyEntries))); + return NativeToolchainPreparation.Freeze( + targetID, + host, + tools, + environment, + inputs, + cmakeArguments, + WindowsX64LinkerSettings.Create(), + true, + new NativeCompilerInputs( + tools["cl"], + tools["cl"], + systemIncludeDirectories: environment["INCLUDE"].Split(';', StringSplitOptions.RemoveEmptyEntries) + ) + ); } private static string RequireVariable( IReadOnlyDictionary selected, string name ) => selected.TryGetValue(name, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value - : throw new InvalidOperationException($"The selected C++ toolchain did not define '{name}'."); + ? value + : throw new InvalidOperationException($"The selected C++ toolchain did not define '{name}'."); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs index 182b9d833..245c1f082 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs @@ -14,7 +14,13 @@ public static class WindowsX64BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("windows-x64"), "Windows", "x64", "msvc-x64", "win-x64", true); + new BuildTargetID("windows-x64"), + "Windows", + "x64", + "msvc-x64", + "win-x64", + true + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -51,11 +57,15 @@ INativeBindingGenerator bindingGenerator ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); ArgumentNullException.ThrowIfNull(editorNativePlan); - return new(target, + return new( + target, () => new WindowsX64GameBuildTarget(supportPackValidator), - new WindowsX64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), new WindowsX64NativeToolchainProvider(context.dotnetHost), + new WindowsX64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), + new WindowsX64NativeToolchainProvider(context.dotnetHost), "platforms/WindowsX64/editor/Inno.Editor.WindowsX64/Inno.Editor.WindowsX64.csproj", - [nativePlan, editorNativePlan, shaderToolsPlan], bindingGenerator, - [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot]); + [nativePlan, editorNativePlan, shaderToolsPlan], + bindingGenerator, + [ManagedDeploymentID.coreClr, ManagedDeploymentID.nativeAot] + ); } } diff --git a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs index 596f6d4cc..b67b6b4a8 100644 --- a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs +++ b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs @@ -14,8 +14,10 @@ using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Build.WindowsX64; using Inno.Core.Execution; using Inno.Core.Input; using Inno.Core.Logging; @@ -44,13 +46,13 @@ public static class WindowsX64EditorComposition /// /// An optional project directory and the shared Editor command-line options. /// - /// - /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. - /// /// /// Cancels preparation or requests orderly shutdown of the shared Editor host. /// An open native folder dialog retains its callback owner until the user completes or closes it. /// + /// + /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. + /// public static int Run( string[] arguments, CancellationToken cancellationToken @@ -64,31 +66,39 @@ CancellationToken cancellationToken using var picker = new Sdl3PlatformApplication(new WindowsX64Sdl3HostIntegration()); string? selected = Sdl3FolderDialog.SelectFolder(picker); if (selected is null) + { return 0; + } arguments = [selected]; } EditorCommandLineOptions command = EditorCommandLineOptions.Parse(arguments); _ = WindowsX64ApplicationLocations.userDataRoot; string project = Path.GetFullPath(command.projectDirectory); string persistentRoot = Path.Combine(project, "Library", "PersistentData"); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())]), - rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) - }, [new BgfxAuthoringProvider(WindowsX64BgfxIntegration.shaderProfile)], - [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: false, horizontalWheelDirection: 1))]); - var buildContext = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, nativeDependencies: command.nativeDependencies); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())]), + rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())]), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) + }, + [new BgfxAuthoringProvider(WindowsX64BgfxIntegration.shaderProfile)], + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: false, horizontalWheelDirection: 1))] + ); + BuildCompositionContext buildContext = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, + WindowsX64BuildModule.target.id, + nativeDependencies: command.nativeDependencies + ); var launch = new EditorLaunchOptions { - defaultBuildTarget = Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + defaultBuildTarget = WindowsX64BuildModule.target.id, projectDirectory = project, keyboard = new EditorKeyboardPolicy(KeyModifier.Control, "Super"), adapterCatalog = adapters, shell = new ShellOptions { - adapters = StandardAdapterSelection.Create(StorageBackendId.fileSystem), + adapters = StandardAdapterSelection.Create(StorageBackendID.fileSystem), window = new PlatformWindowOptions { title = "Inno Editor", @@ -101,18 +111,27 @@ CancellationToken cancellationToken preferredGraphicsApi = command.graphicsApi, sRgbBackbuffer = true }, - presentation = PresentationBackendId.imGui, + presentation = PresentationBackendID.imGui, frameDriver = new PollingShellFrameDriver(), distribution = StandardBuildDistribution.Create(buildContext).build, buildContext = buildContext, - supportPackRoot = Path.Combine(Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, "SupportPacks"), + supportPackRoot = Path.Combine( + Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, + "SupportPacks" + ), createEngineHost = CreateEngineHost, createScriptModuleSource = deployment => CreateScriptModuleSource(project, deployment), createSessionLogSink = ( kind, session - ) => new FileLogSink(Path.Combine(persistentRoot, - kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", "Logs", session.ToString())), + ) => new FileLogSink( + Path.Combine( + persistentRoot, + kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", + "Logs", + session.ToString() + ) + ), createHostLogSink = () => new ConsoleLogSink(useColors: true), smokeFrameLimit = command.smokeFrameLimit }; @@ -138,7 +157,8 @@ private static EngineHost CreateEngineHost() => new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(WindowsX64EditorComposition).Assembly), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); private static IModuleSource CreateScriptModuleSource( string project, diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs index 8b2a7b105..da1449d5e 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs @@ -37,10 +37,13 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); - if (handles.handleKind != PlatformNativeHandleId.win32) + } + if (handles.handleKind != PlatformNativeHandleID.win32) + { throw new NotSupportedException("The Windows BGFX integration requires its explicit win32 surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: true); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: true); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs index 0f7560add..441b2dec2 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs @@ -1,32 +1,34 @@ using System; -using Inno.Build.WindowsX64; using System.Collections.Generic; using System.IO; using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx; +using Inno.Build.WindowsX64; namespace Inno.Integration.WindowsX64.Bgfx; internal sealed class WindowsX64BgfxBuildProfile : BgfxNativeBuildProfile { - /// - public override NativeToolchainSelection SelectTools( - NativeBuildContext context, - bool includeTools - ) => WindowsX64BgfxToolContribution.Select(context, includeTools); + /// + public override string targetID => WindowsX64BuildModule.target.id.value; - /// - public override string targetId => WindowsX64BuildModule.target.id.value; - /// + /// public override IReadOnlyList generatorArguments => ["vs2022"]; - /// + + /// public override string artifactPathToken => "/win64_vs2022/bin/"; - /// - public override IReadOnlyList bindingCmakeArguments => - ["-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$:Debug>"]; + /// + public override IReadOnlyList bindingCmakeArguments + => ["-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$:Debug>"]; + + /// + public override NativeToolchainSelection SelectTools( + NativeBuildContext context, + bool includeTools + ) => WindowsX64BgfxToolContribution.Select(context, includeTools); - /// + /// public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) { ArgumentException.ThrowIfNullOrWhiteSpace(archivePath); @@ -34,14 +36,20 @@ public override (string reference, IReadOnlyList arguments) CreateBindin return (Path.ChangeExtension(archivePath, null), ["/WHOLEARCHIVE:\"" + archivePath + "\""]); } - /// + /// public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, bool includeTools ) { string sdk = context.RequireToolchain().environment["WindowsSDKVersion"].TrimEnd('\\', '/'); string configuration = context.configuration == "debug" ? "Debug" : "Release"; - return new("msbuild", [".build/projects/vs2022/bgfx.sln", "/m:1", "/nodeReuse:false", - "/p:Configuration=" + configuration, "/p:Platform=x64", "/p:WindowsTargetPlatformVersion=" + sdk]); + return new("msbuild", [ + ".build/projects/vs2022/bgfx.sln", + "/m:1", + "/nodeReuse:false", + "/p:Configuration=" + configuration, + "/p:Platform=x64", + "/p:WindowsTargetPlatformVersion=" + sdk + ]); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs index 648fa4dd2..6d822ed0a 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs @@ -40,6 +40,13 @@ public static GameContentCompilerFactory CreateContentCompilerFactory(ToolRunner assets, serialization, types - ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL], tools); + ) => new BgfxGameContentCompiler( + assets, + serialization, + types, + shaderProfile, + [GraphicsApi.direct3D11, GraphicsApi.direct3D12, GraphicsApi.vulkan, GraphicsApi.openGL], + tools + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs index 93bc03a5e..0b4dc9d4a 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs @@ -1,7 +1,6 @@ using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Rendering; - using Inno.Build.WindowsX64; +using Inno.Rendering; namespace Inno.Integration.WindowsX64.Bgfx; @@ -13,11 +12,13 @@ public static class WindowsX64BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(WindowsX64BuildModule.target.id.value, - [ - new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D12), "windows", "s_5_0", "s_5_0", "s_5_0"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv"), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "windows", "430", "430", "430") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + WindowsX64BuildModule.target.id.value, + [ + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.direct3D12), "windows", "s_5_0", "s_5_0", "s_5_0"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.vulkan), "windows", "spirv", "spirv", "spirv"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.openGL), "windows", "430", "430", "430") + ] + ); } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs index 5db89d040..18c1581ff 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs @@ -14,7 +14,9 @@ bool includeTools ) { NativeToolchainSelection sdk = context.RequireToolchain(); if (sdk.host.system != "Windows") + { throw new PlatformNotSupportedException("This BGFX integration requires a Windows tool host."); + } string generator; if (!sdk.TryResolveExecutable("genie", out generator)) { @@ -30,10 +32,20 @@ bool includeTools string dotnet = sdk.ResolveExecutable("dotnet"); string cmake = sdk.ResolveExecutable("cmake"); if (!includeTools) + { tools.Add("cmake", cmake); - return new NativeToolchainSelection(sdk.targetId, sdk.host, tools, sdk.environment, + } + return new NativeToolchainSelection( + sdk.targetID, + sdk.host, + tools, + sdk.environment, sdk.inputPaths.Where(path => path != dotnet && (!includeTools || path != cmake)) .Concat([Path.Combine(owner, "WindowsX64BgfxToolContribution.cs"), Path.Combine(owner, "WindowsX64BgfxBuildProfile.cs")]), - includeTools ? [] : sdk.cmakeArguments, sdk.linkPlan, sdk.multiConfiguration, sdk.compilerInputs); + includeTools ? [] : sdk.cmakeArguments, + sdk.linkPlan, + sdk.multiConfiguration, + sdk.compilerInputs + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs index 4fc9eb096..1e5ffd0b0 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs @@ -7,9 +7,11 @@ namespace Inno.Integration.WindowsX64.Build; internal static class WindowsX64BindingProfile { - internal static NativeBindingProfile Create() => new( - WindowsX64BuildModule.target.id.value, - new TargetConfiguration { id = "windows-x64-msvc" }, - new ManagedRuntimeId("dotnet.coreclr"), - ["platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs"]); + internal static NativeBindingProfile Create() + => new( + WindowsX64BuildModule.target.id.value, + new TargetConfiguration { id = "windows-x64-msvc" }, + new ManagedRuntimeId("dotnet.coreclr"), + ["platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs"] + ); } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs index ca5bf4bd0..88d52b1b2 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs @@ -11,10 +11,15 @@ internal static class WindowsX64NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs index f2f9c1f18..863760fe2 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs @@ -7,9 +7,9 @@ internal static class WindowsX64NativeProducts private const string C_INPUT = "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs"; internal static NativeComponentBuildOptions Options(string component) - { - return new(NativeLibraryKind.Shared, + => new( + NativeLibraryKind.Shared, cmakeArguments: component == "cimgui" ? ["-DINNO_CIMGUI_COMPILE_DEFINITIONS=IMGUI_API=__declspec(dllexport)"] : [], - inputPaths: [C_INPUT]); - } + inputPaths: [C_INPUT] + ); } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs index d015f4b2b..9195b7a3b 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs @@ -27,13 +27,38 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(WindowsX64BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateDynamic(player, WindowsX64BuildModule.target.id, ".dll"), - new WindowsX64SupportPackValidator(), StandardNativeDeployment.CreateValidator(WindowsX64BuildModule.target.id, ".dll")); + new WindowsX64SupportPackValidator(), + StandardNativeDeployment.CreateValidator(WindowsX64BuildModule.target.id, ".dll") + ); var executor = new ComponentNativeProductExecutor(); - return WindowsX64BuildModule.CreateContribution(context, new NativeProductContribution(player, executor), - new NativeProductContribution(StandardNativeComponents.CreateEditor(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map), executor), - new NativeProductContribution(StandardNativeComponents.CreateShaderTools(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map), executor), validator, generator); + return WindowsX64BuildModule.CreateContribution( + context, + new NativeProductContribution(player, executor), + new NativeProductContribution( + StandardNativeComponents.CreateEditor( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ), + executor + ), + new NativeProductContribution( + StandardNativeComponents.CreateShaderTools( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ), + executor + ), + validator, + generator + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs index 31062aa38..c1d98548c 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs @@ -11,38 +11,36 @@ namespace Inno.Integration.WindowsX64.Sdl3; /// public sealed class WindowsX64Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: true, liveResize: true); - /// - public void ConfigureInitialization() - { - } + /// + public void ConfigureInitialization() {} - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.win32.hwnd\0"u8; nint surface; fixed (byte* name = propertyName) + { surface = (nint)SDL.Raw.GetPointerProperty(properties, (sbyte*)name, null); + } if (surface == 0) + { throw new InvalidOperationException("SDL did not provide the required Windows surface."); - return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.win32); + } + return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleID.win32); } - /// - public bool GetInitialFocus(nint windowHandle) - { - return Sdl3WindowOperations.ReadFocus(windowHandle); - } + /// + public bool GetInitialFocus(nint windowHandle) => Sdl3WindowOperations.ReadFocus(windowHandle); } diff --git a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs index 60e6b6657..45cd68253 100644 --- a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs +++ b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs @@ -1,23 +1,23 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.WindowsX64.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using System; +using System.IO; using Inno.Adapter; using Inno.Adapter.Default; -using Inno.Rendering; -using System.IO; -using Inno.Player.Runtime; -using Inno.Shell; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; +using Inno.Integration.WindowsX64.Bgfx.Runtime; +using Inno.Integration.WindowsX64.Sdl3; +using Inno.Platform.WindowsX64; +using Inno.Player.Runtime; +using Inno.Rendering; using Inno.Runtime; +using Inno.Shell; using Inno.Storage; -using Inno.Platform.WindowsX64; namespace Inno.Player.WindowsX64; @@ -46,15 +46,15 @@ internal static int Run(string[] arguments) types = Generated.PlayerMetadataComposition.CreateTypes(), serializationMetadata = Generated.PlayerMetadataComposition.CreateSerialization(), adapters = adapterCatalog, - adapterSelection = StandardAdapterSelection.Create(StorageBackendId.fileSystem), + adapterSelection = StandardAdapterSelection.Create(StorageBackendID.fileSystem), contentSource = new WindowsX64PlayerContentSource(AppContext.BaseDirectory, dataRoot), createStorage = manifest => new FileSystemApplicationStorage( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage")), + Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage") + ), createLogSink = ( manifest, - sessionId - ) => new FileLogSink( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), + sessionID + ) => new FileLogSink(Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionID.ToString())), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new PollingShellFrameDriver(), consoleColors = true, @@ -74,5 +74,4 @@ private static string ResolveDataRoot( string root, GameRuntimeManifest manifest ) => Path.Combine(root, manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); - } diff --git a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs index 8a8cb4b26..2c321cd70 100644 --- a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs +++ b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs @@ -16,8 +16,12 @@ internal sealed class WindowsX64PlayerContentSource : IPlayerContentSource internal WindowsX64PlayerContentSource( string applicationDirectory, string cacheRoot - ) => m_files = new FileContentDeployment( - WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), cacheRoot); + ) { + m_files = new FileContentDeployment( + WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); + } /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs b/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs index d5b13a59f..749667311 100644 --- a/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs +++ b/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs @@ -22,10 +22,14 @@ public static string userDataRoot get { if (!OperatingSystem.IsWindows()) + { throw new PlatformNotSupportedException("This product requires Windows."); + } string location = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (string.IsNullOrWhiteSpace(location) || !Path.IsPathFullyQualified(location)) + { throw new InvalidOperationException("The system did not provide a usable application data root."); + } return location; } } @@ -46,7 +50,9 @@ public static string GetPlayerContentDirectory(string applicationDirectory) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("An application directory must be absolute.", nameof(applicationDirectory)); + } return Path.Combine(applicationDirectory, "Content"); } } diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs index bdef70afd..065ad70ef 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Audio; /// public sealed class AudioBackendCatalog : IAudioBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -30,26 +30,29 @@ public AudioBackendCatalog(IEnumerable providers) foreach (AudioBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IAudioDevice CreateDevice( - AudioBackendId backend, + AudioBackendID backend, AudioBackendOptions options ) { if (!m_providers.TryGetValue(backend, out AudioBackendProvider? provider)) + { throw new NotSupportedException("Audio backend '" + backend + "' is not registered."); + } return provider.CreateDevice(options) - ?? throw new InvalidOperationException("Audio provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Audio provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendID.cs similarity index 88% rename from src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs rename to src/adapters/audio/Inno.Adapter.Audio/AudioBackendID.cs index b70f39b1a..9de0ad31e 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Audio; /// /// Identifies a audio implementation without closing the set of supported backends. /// -public readonly record struct AudioBackendId +public readonly record struct AudioBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,19 +16,23 @@ public readonly record struct AudioBackendId /// /// The identifier is empty or contains whitespace. /// - public AudioBackendId(string value) + public AudioBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled miniAudio implementation. /// - public static AudioBackendId miniAudio { get; } = new("inno.audio.mini-audio"); + public static AudioBackendID miniAudio { get; } = new("inno.audio.mini-audio"); /// /// Gets the stable identifier; a default value is unassigned. @@ -48,4 +52,3 @@ public AudioBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs index f45aab923..1316b9068 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs @@ -21,17 +21,19 @@ public abstract class AudioBackendProvider /// /// The identity is unassigned. /// - protected AudioBackendProvider(AudioBackendId id) + protected AudioBackendProvider(AudioBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public AudioBackendId id { get; } + public AudioBackendID id { get; } /// /// Creates a caller-owned audio service using this implementation. @@ -44,4 +46,3 @@ protected AudioBackendProvider(AudioBackendId id) /// public abstract IAudioDevice CreateDevice(AudioBackendOptions options); } - diff --git a/src/adapters/audio/Inno.Adapter.Audio/IAudioBackendFactory.cs b/src/adapters/audio/Inno.Adapter.Audio/IAudioBackendFactory.cs index b9281abfa..240d91bde 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/IAudioBackendFactory.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/IAudioBackendFactory.cs @@ -11,7 +11,7 @@ public interface IAudioBackendFactory /// /// Gets the exact registrations available in this composition snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates a new audio device for one runtime audio generation. @@ -29,7 +29,7 @@ public interface IAudioBackendFactory /// Thrown when the catalog does not contain the selected backend. /// IAudioDevice CreateDevice( - AudioBackendId backend, + AudioBackendID backend, AudioBackendOptions options = default ); } diff --git a/src/adapters/common/Inno.Adapter/AdapterSelection.cs b/src/adapters/common/Inno.Adapter/AdapterSelection.cs index 9393e803b..1dc0ff58d 100644 --- a/src/adapters/common/Inno.Adapter/AdapterSelection.cs +++ b/src/adapters/common/Inno.Adapter/AdapterSelection.cs @@ -19,37 +19,37 @@ public readonly struct AdapterSelection /// /// Gets the selected platform backend. /// - public PlatformBackendId platform { get; init; } + public PlatformBackendID platform { get; init; } /// /// Gets the selected input backend. /// - public InputBackendId input { get; init; } + public InputBackendID input { get; init; } /// /// Gets the selected storage backend. /// - public StorageBackendId storage { get; init; } + public StorageBackendID storage { get; init; } /// /// Gets the selected rendering backend. /// - public RenderingBackendId rendering { get; init; } + public RenderingBackendID rendering { get; init; } /// /// Gets the selected audio backend. /// - public AudioBackendId audio { get; init; } + public AudioBackendID audio { get; init; } /// /// Gets the selected Unicode text backend. /// - public TextBackendId text { get; init; } + public TextBackendID text { get; init; } /// /// Gets the selected retained-mode UI backend. /// - public UiBackendId ui { get; init; } + public UIBackendID ui { get; init; } /// /// Validates every selected registration before the composition creates any service. @@ -79,8 +79,11 @@ private static void Require( TBackend backend, IReadOnlyList available, string domain - ) where TBackend : struct, IEquatable { + ) where TBackend : struct, IEquatable + { if (backend.Equals(default) || !available.Contains(backend)) + { throw new NotSupportedException(domain + " backend '" + backend + "' is not registered."); + } } } diff --git a/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs b/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs index 158c8a7f3..ab8747a10 100644 --- a/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs +++ b/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs @@ -46,6 +46,5 @@ public interface IAdapterCatalog /// /// Gets the retained-mode UI backend factory. /// - IUiBackendFactory ui { get; } - + IUIBackendFactory ui { get; } } diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs b/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs index c17154282..f585b884f 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading; - using Inno.Core.Events; using Inno.Core.Input; using Inno.Core.Mathematics; @@ -22,7 +21,7 @@ public sealed class EventInputBackend : IInputBackend private readonly HashSet m_mouseButtonsReleased = []; private readonly List m_textInput = []; private readonly Lock m_sync = new(); - private readonly uint m_windowId; + private readonly uint m_windowID; private Action? m_disposeCallback; private IDisposable? m_subscription; private Vector2 m_mousePosition; @@ -35,19 +34,17 @@ public sealed class EventInputBackend : IInputBackend /// /// Creates an event-backed input adapter for one platform window. /// - /// + /// /// The translated event window identifier, or zero to accept input from every window. /// - public EventInputBackend(uint windowId) - : this(windowId, null) - { - } + public EventInputBackend(uint windowID) + : this(windowID, null) {} internal EventInputBackend( - uint windowId, + uint windowID, Action? disposeCallback ) { - m_windowId = windowId; + m_windowID = windowID; m_disposeCallback = disposeCallback; } @@ -68,36 +65,50 @@ public void ProcessEvent(Event evnt) ArgumentNullException.ThrowIfNull(evnt); ObjectDisposedException.ThrowIf(m_disposed, this); if (evnt.isGlobalHandled || !Accepts(evnt)) + { return; + } lock (m_sync) { ObjectDisposedException.ThrowIf(m_disposed, this); if (evnt is ApplicationSuspensionChangedEvent suspension) + { m_suspended = suspension.isSuspended; + } if (m_suspended && evnt is KeyEvent or MouseEvent or TextInputEvent) + { return; + } switch (evnt) { case KeyPressedEvent key when !key.repeat: m_modifiers = key.modifiers; if (m_keysDown.Add(key.key)) + { m_keysPressed.Add(key.key); + } break; case KeyReleasedEvent key: m_modifiers = key.modifiers; if (m_keysDown.Remove(key.key)) + { m_keysReleased.Add(key.key); + } break; case TextInputEvent text: m_textInput.Add(text.text); break; case MouseButtonPressedEvent button: if (m_mouseButtonsDown.Add(button.button)) + { m_mouseButtonsPressed.Add(button.button); + } break; case MouseButtonReleasedEvent button: if (m_mouseButtonsDown.Remove(button.button)) + { m_mouseButtonsReleased.Add(button.button); + } break; case MouseMovedEvent movement: var nextPosition = new Vector2(movement.x, movement.y); @@ -151,7 +162,8 @@ public InputSnapshot Capture(long frameIndex) m_mouseDelta, m_scrollDelta, m_modifiers, - m_textInput); + m_textInput + ); m_keysPressed.Clear(); m_keysReleased.Clear(); m_mouseButtonsPressed.Clear(); @@ -169,7 +181,9 @@ public InputSnapshot Capture(long frameIndex) public void Dispose() { if (m_disposed) + { return; + } lock (m_sync) { m_disposed = true; @@ -198,12 +212,12 @@ internal void DisconnectSource() } private bool Accepts(Event evnt) - => m_windowId == 0 || evnt switch + => m_windowID == 0 || evnt switch { - KeyEvent key => key.windowId == m_windowId, - TextInputEvent text => text.windowId == m_windowId, - MouseEvent mouse => mouse.windowId == m_windowId, - WindowEvent window => window.windowId == m_windowId, + KeyEvent key => key.windowID == m_windowID, + TextInputEvent text => text.windowID == m_windowID, + MouseEvent mouse => mouse.windowID == m_windowID, + WindowEvent window => window.windowID == m_windowID, ApplicationSuspensionChangedEvent => true, _ => false }; diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs index 60309bf4d..b9bcc015b 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs @@ -11,15 +11,15 @@ public sealed class EventInputBackendProvider : InputBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public EventInputBackendProvider() : base(InputBackendId.events) { } + public EventInputBackendProvider() + : base(InputBackendID.events) {} - /// + /// public override IInputEventSource CreateEventSource( IPlatformWindow window, bool acceptAllWindows ) { ArgumentNullException.ThrowIfNull(window); - return new EventInputSource(acceptAllWindows ? 0 : window.windowId); + return new EventInputSource(acceptAllWindows ? 0 : window.windowID); } } - diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs b/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs index cc1dfdb86..70a1a4dbe 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Events; using Inno.Input; @@ -14,18 +13,18 @@ public sealed class EventInputSource : IInputEventSource private readonly List m_backends = []; private readonly EventDispatcher m_events = new(); private readonly EventHub m_inputHub; - private readonly uint m_windowId; + private readonly uint m_windowID; private bool m_disposed; /// /// Creates an input source restricted to one window, or to all windows when the identifier is zero. /// - /// + /// /// The platform window identifier accepted by this source; zero accepts events from every window. /// - public EventInputSource(uint windowId) + public EventInputSource(uint windowID) { - m_windowId = windowId; + m_windowID = windowID; m_inputHub = m_events.CreateHub(); } @@ -41,7 +40,7 @@ public EventInputSource(uint windowId) public IInputBackend CreateBackend() { ObjectDisposedException.ThrowIf(m_disposed, this); - var backend = new EventInputBackend(m_windowId, RemoveBackend); + var backend = new EventInputBackend(m_windowID, RemoveBackend); backend.ConnectSource(m_inputHub.Listen(backend.ProcessEvent)); m_backends.Add(backend); return backend; @@ -72,13 +71,17 @@ public void ProcessEvent(Event evnt) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_inputHub.Dispose(); EventInputBackend[] snapshot = m_backends.ToArray(); m_backends.Clear(); foreach (EventInputBackend backend in snapshot) + { backend.DisconnectSource(); + } } private void RemoveBackend(EventInputBackend backend) => m_backends.Remove(backend); diff --git a/src/adapters/input/Inno.Adapter.Input/IInputBackendFactory.cs b/src/adapters/input/Inno.Adapter.Input/IInputBackendFactory.cs index a6acdb6e4..57e24732d 100644 --- a/src/adapters/input/Inno.Adapter.Input/IInputBackendFactory.cs +++ b/src/adapters/input/Inno.Adapter.Input/IInputBackendFactory.cs @@ -11,7 +11,7 @@ public interface IInputBackendFactory /// /// Gets the exact registrations available in this composition snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates an input event source for one window or for the entire application. @@ -32,7 +32,7 @@ public interface IInputBackendFactory /// Thrown when the catalog does not contain the selected backend or the platform is incompatible. /// IInputEventSource CreateEventSource( - InputBackendId backend, + InputBackendID backend, IPlatformWindow window, bool acceptAllWindows ); diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs index 2fb5dc593..5f3f3f6b3 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Input; /// public sealed class InputBackendCatalog : IInputBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -30,28 +30,31 @@ public InputBackendCatalog(IEnumerable providers) foreach (InputBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IInputEventSource CreateEventSource( - InputBackendId backend, + InputBackendID backend, IPlatformWindow window, bool acceptAllWindows ) { ArgumentNullException.ThrowIfNull(window); if (!m_providers.TryGetValue(backend, out InputBackendProvider? provider)) + { throw new NotSupportedException("Input backend '" + backend + "' is not registered."); + } return provider.CreateEventSource(window, acceptAllWindows) - ?? throw new InvalidOperationException("Input provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Input provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendID.cs similarity index 88% rename from src/adapters/input/Inno.Adapter.Input/InputBackendId.cs rename to src/adapters/input/Inno.Adapter.Input/InputBackendID.cs index 7a81b27a4..ec6c54e0d 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Input; /// /// Identifies a input implementation without closing the set of supported backends. /// -public readonly record struct InputBackendId +public readonly record struct InputBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,19 +16,23 @@ public readonly record struct InputBackendId /// /// The identifier is empty or contains whitespace. /// - public InputBackendId(string value) + public InputBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the backend-neutral event accumulator. /// - public static InputBackendId events { get; } = new("inno.input.events"); + public static InputBackendID events { get; } = new("inno.input.events"); /// /// Gets the stable identifier; a default value is unassigned. @@ -48,4 +52,3 @@ public InputBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs index 3e9f958de..1470b29a8 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs @@ -21,17 +21,19 @@ public abstract class InputBackendProvider /// /// The identity is unassigned. /// - protected InputBackendProvider(InputBackendId id) + protected InputBackendProvider(InputBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public InputBackendId id { get; } + public InputBackendID id { get; } /// /// Creates a caller-owned input service using this implementation. @@ -50,4 +52,3 @@ public abstract IInputEventSource CreateEventSource( bool acceptAllWindows ); } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/IPlatformBackendFactory.cs b/src/adapters/platform/Inno.Adapter.Platform/IPlatformBackendFactory.cs index aa18fbe14..0d70680be 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/IPlatformBackendFactory.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/IPlatformBackendFactory.cs @@ -11,7 +11,7 @@ public interface IPlatformBackendFactory /// /// Gets the exact registrations available in this composition snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates a new platform application for the selected backend. @@ -25,5 +25,5 @@ public interface IPlatformBackendFactory /// /// Thrown when the catalog does not contain the selected backend. /// - IPlatformApplication CreateApplication(PlatformBackendId backend); + IPlatformApplication CreateApplication(PlatformBackendID backend); } diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs index 43e4e1ec7..ddec6dabf 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Platform; /// public sealed class PlatformBackendCatalog : IPlatformBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -30,23 +30,27 @@ public PlatformBackendCatalog(IEnumerable providers) foreach (PlatformBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// - public IPlatformApplication CreateApplication(PlatformBackendId backend) { + /// + public IPlatformApplication CreateApplication(PlatformBackendID backend) + { if (!m_providers.TryGetValue(backend, out PlatformBackendProvider? provider)) + { throw new NotSupportedException("Platform backend '" + backend + "' is not registered."); + } return provider.CreateApplication() - ?? throw new InvalidOperationException("Platform provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Platform provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendID.cs similarity index 88% rename from src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs rename to src/adapters/platform/Inno.Adapter.Platform/PlatformBackendID.cs index 1dc421a39..a7a645201 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Platform; /// /// Identifies a platform implementation without closing the set of supported backends. /// -public readonly record struct PlatformBackendId +public readonly record struct PlatformBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,19 +16,23 @@ public readonly record struct PlatformBackendId /// /// The identifier is empty or contains whitespace. /// - public PlatformBackendId(string value) + public PlatformBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled sdl3 implementation. /// - public static PlatformBackendId sdl3 { get; } = new("inno.platform.sdl3"); + public static PlatformBackendID sdl3 { get; } = new("inno.platform.sdl3"); /// /// Gets the stable identifier; a default value is unassigned. @@ -48,4 +52,3 @@ public PlatformBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs index 28b088fab..04d0ab25a 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs @@ -21,17 +21,19 @@ public abstract class PlatformBackendProvider /// /// The identity is unassigned. /// - protected PlatformBackendProvider(PlatformBackendId id) + protected PlatformBackendProvider(PlatformBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public PlatformBackendId id { get; } + public PlatformBackendID id { get; } /// /// Creates a caller-owned platform service using this implementation. @@ -41,4 +43,3 @@ protected PlatformBackendProvider(PlatformBackendId id) /// public abstract IPlatformApplication CreateApplication(); } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleID.cs similarity index 83% rename from src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs rename to src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleID.cs index 72254548a..47a20a95f 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Platform; /// /// Identifies an open native surface ABI understood by cooperating window and graphics adapters. /// -public readonly record struct PlatformNativeHandleId +public readonly record struct PlatformNativeHandleID { /// /// Creates an ordinal, case-sensitive ABI identifier. @@ -16,29 +16,33 @@ public readonly record struct PlatformNativeHandleId /// /// The identifier is empty or contains whitespace. /// - public PlatformNativeHandleId(string value) + public PlatformNativeHandleID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A native surface identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the Win32 HWND surface ABI. /// - public static PlatformNativeHandleId win32 { get; } = new("inno.surface.win32"); + public static PlatformNativeHandleID win32 { get; } = new("inno.surface.win32"); /// /// Gets the Cocoa window surface ABI. /// - public static PlatformNativeHandleId cocoa { get; } = new("inno.surface.cocoa"); + public static PlatformNativeHandleID cocoa { get; } = new("inno.surface.cocoa"); /// /// Gets the UTF-8 canvas selector surface ABI. /// - public static PlatformNativeHandleId browserCanvas { get; } = new("inno.surface.browser-canvas"); + public static PlatformNativeHandleID browserCanvas { get; } = new("inno.surface.browser-canvas"); /// /// Gets the stable identifier; the default value is unassigned. diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs index 7fd79cb35..311d7a2c0 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs @@ -5,10 +5,6 @@ namespace Inno.Adapter.Platform; /// /// Borrows surface handles from a live window for cooperating native adapters. /// -/// -/// Handles remain valid only while their window is alive. Consumers must not release them. -/// The handle identifier selects the ABI; this value is not a runtime or scripting contract. -/// /// /// Native window handle, or a stable UTF-8 canvas selector for browser surfaces. /// @@ -21,8 +17,12 @@ namespace Inno.Adapter.Platform; /// /// A borrowed adapter-level surface description. /// +/// +/// Handles remain valid only while their window is alive. Consumers must not release them. +/// The handle identifier selects the ABI; this value is not a runtime or scripting contract. +/// public readonly record struct PlatformNativeHandles( - IntPtr windowHandle, - IntPtr displayHandle = default, - PlatformNativeHandleId handleKind = default + nint windowHandle, + nint displayHandle = default, + PlatformNativeHandleID handleKind = default ); diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationBackendFactory.cs b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationBackendFactory.cs index f9a2b7a1c..425cf6a3d 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationBackendFactory.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationBackendFactory.cs @@ -10,7 +10,7 @@ public interface IPresentationBackendFactory /// /// Gets the implementation identities available in this immutable factory snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates a presentation context over compatible platform and rendering adapters. @@ -28,7 +28,7 @@ public interface IPresentationBackendFactory /// Thrown when the selected platform, rendering, and presentation backends are incompatible. /// IPresentationContext CreateContext( - PresentationBackendId backend, + PresentationBackendID backend, PresentationBackendOptions options ); } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs index 85680d068..a1131d013 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs @@ -12,18 +12,18 @@ public interface IPresentationContext : IRenderFrameGraphContributor, IDisposabl /// /// Resolves the platform window that owns a presentation viewport. /// - /// + /// /// The presentation viewport identity. /// - /// + /// /// The owning platform window identity when available. /// /// /// when the viewport has a live platform window. /// - bool TryGetWindowId( - uint viewportId, - out uint windowId + bool TryGetWindowID( + uint viewportID, + out uint windowID ); /// @@ -115,5 +115,4 @@ void DrawImage( PresentationTextureHandle texture, Vector2 size ); - } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs index 8f4987c24..bab20d82a 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs @@ -9,7 +9,7 @@ namespace Inno.Adapter.Presentation; /// public sealed class PresentationBackendCatalog : IPresentationBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -29,26 +29,30 @@ public PresentationBackendCatalog(IEnumerable provi foreach (PresentationBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IPresentationContext CreateContext( - PresentationBackendId backend, + PresentationBackendID backend, PresentationBackendOptions options ) { ArgumentNullException.ThrowIfNull(options); if (!m_providers.TryGetValue(backend, out PresentationBackendProvider? provider)) + { throw new NotSupportedException("Presentation backend '" + backend + "' is not registered."); + } return provider.CreateContext(options) - ?? throw new InvalidOperationException("Presentation provider '" + backend + "' returned no context."); + ?? throw new InvalidOperationException("Presentation provider '" + backend + "' returned no context."); } } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendID.cs similarity index 87% rename from src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs rename to src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendID.cs index d750462f3..615073420 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Presentation; /// /// Identifies a presentation implementation without closing the set of supported backends. /// -public readonly record struct PresentationBackendId +public readonly record struct PresentationBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,19 +16,23 @@ public readonly record struct PresentationBackendId /// /// The identifier is empty or contains whitespace. /// - public PresentationBackendId(string value) + public PresentationBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled ImGui implementation. /// - public static PresentationBackendId imGui { get; } = new("inno.presentation.imgui"); + public static PresentationBackendID imGui { get; } = new("inno.presentation.imgui"); /// /// Gets the stable identifier; a default value is unassigned. @@ -48,4 +52,3 @@ public PresentationBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs index eb729c16b..65734c0bf 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs @@ -16,17 +16,19 @@ public abstract class PresentationBackendProvider /// /// The identifier is unassigned. /// - protected PresentationBackendProvider(PresentationBackendId id) + protected PresentationBackendProvider(PresentationBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public PresentationBackendId id { get; } + public PresentationBackendID id { get; } /// /// Creates a new caller-owned presentation context over the supplied host resources. diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs index 34cad0644..564610aa2 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs @@ -12,17 +12,14 @@ public enum PresentationFeatures /// Requests no optional presentation features. /// None = 0, - /// /// Allows the presentation to create detached native windows. /// MultipleWindows = 1 << 0, - /// /// Enables dockable host surfaces when supported. /// Docking = 1 << 1, - /// /// Enables smooth rendering while native windows are being resized. /// diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs index d284d8d5b..d8efbdb9f 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs @@ -15,8 +15,7 @@ public readonly record struct PresentationTextureHandle /// public PresentationTextureHandle(ulong value) { - if (value == 0) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfZero(value); this.value = value; } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/IRenderingAuthoringBackendFactory.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/IRenderingAuthoringBackendFactory.cs index 4dd01cc09..1ab7b33ed 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/IRenderingAuthoringBackendFactory.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/IRenderingAuthoringBackendFactory.cs @@ -12,7 +12,7 @@ public interface IRenderingAuthoringBackendFactory /// /// Gets the runtime backend identities supported by this authoring composition. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates the shader compiler toolchain paired with the selected rendering backend. @@ -23,7 +23,7 @@ public interface IRenderingAuthoringBackendFactory /// /// A target compiler compatible with devices created for the same backend. /// - IShaderCompilerToolchain CreateShaderCompilerToolchain(RenderingBackendId backend); + IShaderCompilerToolchain CreateShaderCompilerToolchain(RenderingBackendID backend); /// /// Creates the texture compiler paired with the selected rendering backend. @@ -34,5 +34,5 @@ public interface IRenderingAuthoringBackendFactory /// /// A texture target compiler compatible with devices created for the same backend. /// - ITextureTargetCompiler CreateTextureTargetCompiler(RenderingBackendId backend); + ITextureTargetCompiler CreateTextureTargetCompiler(RenderingBackendID backend); } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs index 11eb02450..be5ab21c5 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering; /// public sealed class RenderingAuthoringBackendCatalog : IRenderingAuthoringBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates that every runtime backend has exactly one matching authoring provider. @@ -32,18 +32,24 @@ IEnumerable providers ArgumentNullException.ThrowIfNull(runtime); ArgumentNullException.ThrowIfNull(providers); foreach (RenderingAuthoringBackendProvider provider in providers) + { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Authoring providers require unique, assigned backend IDs.", nameof(providers)); - var runtimeIds = new HashSet(runtime.supportedBackends); - if (!runtimeIds.SetEquals(m_providers.Keys)) + } + } + var runtimeIDs = new HashSet(runtime.supportedBackends); + if (!runtimeIDs.SetEquals(m_providers.Keys)) + { throw new ArgumentException("Runtime and authoring rendering providers must register the same backend IDs.", nameof(providers)); - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + } + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// /// Gets backend registrations available in this type generation. /// - public IReadOnlyList supportedBackends { get; } + public IReadOnlyList supportedBackends { get; } /// /// Creates a shader compiler toolchain using this implementation's validated inputs. @@ -54,7 +60,7 @@ IEnumerable providers /// /// The validated ishader compiler toolchain that represents the completed operation. /// - public IShaderCompilerToolchain CreateShaderCompilerToolchain(RenderingBackendId backend) + public IShaderCompilerToolchain CreateShaderCompilerToolchain(RenderingBackendID backend) => GetProvider(backend).CreateShaderCompilerToolchain() ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no shader compiler."); @@ -67,12 +73,12 @@ public IShaderCompilerToolchain CreateShaderCompilerToolchain(RenderingBackendId /// /// The validated itexture target compiler that represents the completed operation. /// - public ITextureTargetCompiler CreateTextureTargetCompiler(RenderingBackendId backend) + public ITextureTargetCompiler CreateTextureTargetCompiler(RenderingBackendID backend) => GetProvider(backend).CreateTextureTargetCompiler() ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no texture compiler."); - private RenderingAuthoringBackendProvider GetProvider(RenderingBackendId backend) + private RenderingAuthoringBackendProvider GetProvider(RenderingBackendID backend) => m_providers.TryGetValue(backend, out RenderingAuthoringBackendProvider? provider) - ? provider - : throw new NotSupportedException($"Rendering authoring backend '{backend}' is not registered."); + ? provider + : throw new NotSupportedException($"Rendering authoring backend '{backend}' is not registered."); } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs index e64fe10fd..5862e0fb0 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs @@ -18,17 +18,19 @@ public abstract class RenderingAuthoringBackendProvider /// /// The identity is unassigned. /// - protected RenderingAuthoringBackendProvider(RenderingBackendId id) + protected RenderingAuthoringBackendProvider(RenderingBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets the stable runtime implementation identity served by these tools. /// - public RenderingBackendId id { get; } + public RenderingBackendID id { get; } /// /// Creates the shader toolchain for this implementation. diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/IRenderingBackendFactory.cs b/src/adapters/rendering/Inno.Adapter.Rendering/IRenderingBackendFactory.cs index b3c5c4194..a64be54ff 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/IRenderingBackendFactory.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/IRenderingBackendFactory.cs @@ -12,7 +12,7 @@ public interface IRenderingBackendFactory /// /// Gets the exact runtime backend identities available in this composition generation. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates a rendering device for the supplied primary presentation surface. @@ -27,7 +27,7 @@ public interface IRenderingBackendFactory /// A caller-owned backend-neutral rendering device. /// IRenderDevice CreateDevice( - RenderingBackendId backend, + RenderingBackendID backend, RenderingBackendOptions options ); @@ -43,5 +43,5 @@ RenderingBackendOptions options /// /// No provider is registered for the requested backend identity. /// - IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend); + IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendID backend); } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs index 867a8a004..bffebe700 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Rendering; /// public sealed class RenderingBackendCatalog : IRenderingBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete set of runtime providers. @@ -27,15 +27,17 @@ public RenderingBackendCatalog(IEnumerable providers) foreach (RenderingBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Rendering providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// /// Gets backend registrations available in this type generation. /// - public IReadOnlyList supportedBackends { get; } + public IReadOnlyList supportedBackends { get; } /// /// Creates a device using this implementation's validated inputs. @@ -53,14 +55,16 @@ public RenderingBackendCatalog(IEnumerable providers) /// No provider is registered for this exact backend ID. /// public IRenderDevice CreateDevice( - RenderingBackendId backend, + RenderingBackendID backend, RenderingBackendOptions options ) { ArgumentNullException.ThrowIfNull(options); if (!m_providers.TryGetValue(backend, out RenderingBackendProvider? provider)) + { throw new NotSupportedException($"Rendering backend '{backend}' is not registered."); + } return provider.CreateDevice(options) - ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no device."); + ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no device."); } /// @@ -75,11 +79,13 @@ RenderingBackendOptions options /// /// No provider is registered for this exact backend identity. /// - public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) + public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendID backend) { if (!m_providers.TryGetValue(backend, out RenderingBackendProvider? provider)) + { throw new NotSupportedException($"Rendering backend '{backend}' is not registered."); + } return provider.CreateCompositionProgramProvider() - ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no composition program provider."); + ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no composition program provider."); } } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendID.cs similarity index 88% rename from src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs rename to src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendID.cs index cdb1dffdc..8a3220384 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Rendering; /// /// Identifies a rendering implementation independently from its graphics API and compiler language. /// -public readonly record struct RenderingBackendId +public readonly record struct RenderingBackendID { /// /// Creates an ordinal, case-sensitive backend identifier. @@ -16,19 +16,23 @@ public readonly record struct RenderingBackendId /// /// The identifier is empty or contains whitespace. /// - public RenderingBackendId(string value) + public RenderingBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A rendering backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled BGFX implementation, not a whitelist of supported backends. /// - public static RenderingBackendId bgfx { get; } = new("inno.rendering.bgfx"); + public static RenderingBackendID bgfx { get; } = new("inno.rendering.bgfx"); /// /// Gets the stable implementation identifier; the default value is unassigned. diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs index aff6a6519..010a89ce4 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs @@ -17,17 +17,19 @@ public abstract class RenderingBackendProvider /// /// The identity is unassigned. /// - protected RenderingBackendProvider(RenderingBackendId id) + protected RenderingBackendProvider(RenderingBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets the stable implementation identity paired with its authoring tools. /// - public RenderingBackendId id { get; } + public RenderingBackendID id { get; } /// /// Creates a caller-owned device using backend-neutral surface options. diff --git a/src/adapters/storage/Inno.Adapter.Storage/IStorageBackendFactory.cs b/src/adapters/storage/Inno.Adapter.Storage/IStorageBackendFactory.cs index 101b75c13..4681036da 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/IStorageBackendFactory.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/IStorageBackendFactory.cs @@ -11,7 +11,7 @@ public interface IStorageBackendFactory /// /// Gets the exact registrations available in this composition snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates isolated storage for a logical application namespace. @@ -29,7 +29,7 @@ public interface IStorageBackendFactory /// Thrown when the catalog does not contain the selected backend. /// IApplicationStorage CreateStorage( - StorageBackendId backend, + StorageBackendID backend, StorageScope scope ); } diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs index 0fe97394e..d0f4d0a84 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Storage; /// public sealed class StorageBackendCatalog : IStorageBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -30,28 +30,33 @@ public StorageBackendCatalog(IEnumerable providers) foreach (StorageBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IApplicationStorage CreateStorage( - StorageBackendId backend, + StorageBackendID backend, StorageScope scope ) { if (!scope.isValid) + { throw new ArgumentException("Storage requires an assigned application namespace.", nameof(scope)); + } if (!m_providers.TryGetValue(backend, out StorageBackendProvider? provider)) + { throw new NotSupportedException("Storage backend '" + backend + "' is not registered."); + } return provider.CreateStorage(scope) - ?? throw new InvalidOperationException("Storage provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Storage provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendID.cs similarity index 86% rename from src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs rename to src/adapters/storage/Inno.Adapter.Storage/StorageBackendID.cs index 785d8f680..1d37fe255 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Storage; /// /// Identifies a storage implementation without closing the set of supported backends. /// -public readonly record struct StorageBackendId +public readonly record struct StorageBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,24 +16,28 @@ public readonly record struct StorageBackendId /// /// The identifier is empty or contains whitespace. /// - public StorageBackendId(string value) + public StorageBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled fileSystem implementation. /// - public static StorageBackendId fileSystem { get; } = new("inno.storage.file-system"); + public static StorageBackendID fileSystem { get; } = new("inno.storage.file-system"); /// /// Gets the identifier of the bundled browser implementation. /// - public static StorageBackendId browser { get; } = new("inno.storage.browser"); + public static StorageBackendID browser { get; } = new("inno.storage.browser"); /// /// Gets the stable identifier; a default value is unassigned. @@ -53,4 +57,3 @@ public StorageBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs index d0eef7d51..7426459e4 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs @@ -21,17 +21,19 @@ public abstract class StorageBackendProvider /// /// The identity is unassigned. /// - protected StorageBackendProvider(StorageBackendId id) + protected StorageBackendProvider(StorageBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public StorageBackendId id { get; } + public StorageBackendID id { get; } /// /// Creates a caller-owned storage service using this implementation. @@ -44,4 +46,3 @@ protected StorageBackendProvider(StorageBackendId id) /// public abstract IApplicationStorage CreateStorage(StorageScope scope); } - diff --git a/src/adapters/text/Inno.Adapter.Text/ITextBackendFactory.cs b/src/adapters/text/Inno.Adapter.Text/ITextBackendFactory.cs index 949d0039a..0f903eff3 100644 --- a/src/adapters/text/Inno.Adapter.Text/ITextBackendFactory.cs +++ b/src/adapters/text/Inno.Adapter.Text/ITextBackendFactory.cs @@ -11,7 +11,7 @@ public interface ITextBackendFactory /// /// Gets the exact registrations available in this composition snapshot. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates one caller-owned text backend. @@ -22,5 +22,5 @@ public interface ITextBackendFactory /// /// A newly allocated text backend. /// - ITextBackend CreateBackend(TextBackendId backend); + ITextBackend CreateBackend(TextBackendID backend); } diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs index f037f2b29..0d1738bc6 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs @@ -10,7 +10,7 @@ namespace Inno.Adapter.Text; /// public sealed class TextBackendCatalog : ITextBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set without creating any service. @@ -30,23 +30,27 @@ public TextBackendCatalog(IEnumerable providers) foreach (TextBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// - public IReadOnlyList supportedBackends { get; } + /// + public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// - public ITextBackend CreateBackend(TextBackendId backend) { + /// + public ITextBackend CreateBackend(TextBackendID backend) + { if (!m_providers.TryGetValue(backend, out TextBackendProvider? provider)) + { throw new NotSupportedException("Text backend '" + backend + "' is not registered."); + } return provider.CreateBackend() - ?? throw new InvalidOperationException("Text provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Text provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendID.cs similarity index 88% rename from src/adapters/text/Inno.Adapter.Text/TextBackendId.cs rename to src/adapters/text/Inno.Adapter.Text/TextBackendID.cs index f8dd92386..b2685755d 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.Text; /// /// Identifies a text implementation without closing the set of supported backends. /// -public readonly record struct TextBackendId +public readonly record struct TextBackendID { /// /// Creates an ordinal, case-sensitive implementation identifier. @@ -16,19 +16,23 @@ public readonly record struct TextBackendId /// /// The identifier is empty or contains whitespace. /// - public TextBackendId(string value) + public TextBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled freeTypeHarfBuzz implementation. /// - public static TextBackendId freeTypeHarfBuzz { get; } = new("inno.text.free-type-harf-buzz"); + public static TextBackendID freeTypeHarfBuzz { get; } = new("inno.text.free-type-harf-buzz"); /// /// Gets the stable identifier; a default value is unassigned. @@ -48,4 +52,3 @@ public TextBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs index ef8ca5f34..557ea064c 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs @@ -21,17 +21,19 @@ public abstract class TextBackendProvider /// /// The identity is unassigned. /// - protected TextBackendProvider(TextBackendId id) + protected TextBackendProvider(TextBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this registration's immutable implementation identity. /// - public TextBackendId id { get; } + public TextBackendID id { get; } /// /// Creates a caller-owned text service using this implementation. @@ -41,4 +43,3 @@ protected TextBackendProvider(TextBackendId id) /// public abstract ITextBackend CreateBackend(); } - diff --git a/src/adapters/ui/Inno.Adapter.UI/IUiBackendFactory.cs b/src/adapters/ui/Inno.Adapter.UI/IUIBackendFactory.cs similarity index 80% rename from src/adapters/ui/Inno.Adapter.UI/IUiBackendFactory.cs rename to src/adapters/ui/Inno.Adapter.UI/IUIBackendFactory.cs index 44135597f..9a193e7e1 100644 --- a/src/adapters/ui/Inno.Adapter.UI/IUiBackendFactory.cs +++ b/src/adapters/ui/Inno.Adapter.UI/IUIBackendFactory.cs @@ -6,12 +6,12 @@ namespace Inno.Adapter.UI; /// /// Creates isolated UI backends without exposing implementation assemblies to composition code. /// -public interface IUiBackendFactory +public interface IUIBackendFactory { /// /// Gets exact backend identities available in this composition generation. /// - IReadOnlyList supportedBackends { get; } + IReadOnlyList supportedBackends { get; } /// /// Creates one caller-owned UI backend. @@ -22,5 +22,5 @@ public interface IUiBackendFactory /// /// A newly allocated UI backend. /// - IUiBackend CreateBackend(UiBackendId backend); + IUIBackend CreateBackend(UIBackendID backend); } diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs b/src/adapters/ui/Inno.Adapter.UI/UIBackendCatalog.cs similarity index 67% rename from src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs rename to src/adapters/ui/Inno.Adapter.UI/UIBackendCatalog.cs index e2e77e94f..aea0ade87 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UIBackendCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; - using Inno.UI; namespace Inno.Adapter.UI; @@ -9,9 +8,9 @@ namespace Inno.Adapter.UI; /// /// Resolves UI providers from one immutable composition-owned registration snapshot. /// -public sealed class UiBackendCatalog : IUiBackendFactory +public sealed class UIBackendCatalog : IUIBackendFactory { - private readonly Dictionary m_providers = []; + private readonly Dictionary m_providers = []; /// /// Validates and captures a complete provider set. @@ -19,19 +18,23 @@ public sealed class UiBackendCatalog : IUiBackendFactory /// /// Providers owned by this composition generation. /// - public UiBackendCatalog(IEnumerable providers) + public UIBackendCatalog(IEnumerable providers) { ArgumentNullException.ThrowIfNull(providers); - foreach (UiBackendProvider provider in providers) + foreach (UIBackendProvider provider in providers) + { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("UI providers require unique, assigned backend IDs.", nameof(providers)); - supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); + } + } + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// /// Gets backend registrations available in this type generation. /// - public IReadOnlyList supportedBackends { get; } + public IReadOnlyList supportedBackends { get; } /// /// Creates a backend using this implementation's validated inputs. @@ -42,11 +45,13 @@ public UiBackendCatalog(IEnumerable providers) /// /// The validated iui backend that represents the completed operation. /// - public IUiBackend CreateBackend(UiBackendId backend) + public IUIBackend CreateBackend(UIBackendID backend) { - if (!m_providers.TryGetValue(backend, out UiBackendProvider? provider)) + if (!m_providers.TryGetValue(backend, out UIBackendProvider? provider)) + { throw new NotSupportedException($"UI backend '{backend}' is not registered."); + } return provider.CreateBackend() - ?? throw new InvalidOperationException($"UI provider '{backend}' returned no backend."); + ?? throw new InvalidOperationException($"UI provider '{backend}' returned no backend."); } } diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs b/src/adapters/ui/Inno.Adapter.UI/UIBackendID.cs similarity index 87% rename from src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs rename to src/adapters/ui/Inno.Adapter.UI/UIBackendID.cs index 3e311057d..d7baf0ad0 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UIBackendID.cs @@ -5,7 +5,7 @@ namespace Inno.Adapter.UI; /// /// Identifies a UI implementation independently from its document language. /// -public readonly record struct UiBackendId +public readonly record struct UIBackendID { /// /// Creates an ordinal, case-sensitive backend identifier. @@ -13,19 +13,23 @@ public readonly record struct UiBackendId /// /// Stable nonempty implementation identifier. /// - public UiBackendId(string value) + public UIBackendID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A UI backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } /// /// Gets the identifier of the bundled RmlUi implementation, not a closed backend list. /// - public static UiBackendId rmlUi { get; } = new("inno.ui.rmlui"); + public static UIBackendID rmlUI { get; } = new("inno.ui.rmlui"); /// /// Gets the stable identifier; the default value is unassigned. diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs b/src/adapters/ui/Inno.Adapter.UI/UIBackendProvider.cs similarity index 82% rename from src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs rename to src/adapters/ui/Inno.Adapter.UI/UIBackendProvider.cs index bca128eee..8993b6c38 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UIBackendProvider.cs @@ -6,7 +6,7 @@ namespace Inno.Adapter.UI; /// /// Creates one concrete UI backend registered by a composition root. /// -public abstract class UiBackendProvider +public abstract class UIBackendProvider { /// /// Captures the registration identity assigned by the composition owner. @@ -17,17 +17,19 @@ public abstract class UiBackendProvider /// /// The identity is unassigned. /// - protected UiBackendProvider(UiBackendId id) + protected UIBackendProvider(UIBackendID id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } /// /// Gets this provider's stable implementation identity. /// - public UiBackendId id { get; } + public UIBackendID id { get; } /// /// Creates one caller-owned backend generation. @@ -35,5 +37,5 @@ protected UiBackendProvider(UiBackendId id) /// /// A new backend. /// - public abstract IUiBackend CreateBackend(); + public abstract IUIBackend CreateBackend(); } diff --git a/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs b/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs index e31f15168..068fe1e1e 100644 --- a/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs +++ b/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Adapter.Audio; using Inno.Adapter.Default; using Inno.Adapter.Input; @@ -49,14 +48,9 @@ IEnumerable presentationProviders m_runtime = new DefaultAdapterCatalog(options); ArgumentNullException.ThrowIfNull(presentationProviders); m_presentation = new PresentationBackendCatalog(presentationProviders); - m_renderingAuthoring = new RenderingAuthoringBackendCatalog( - m_runtime.rendering, - authoringProviders); + m_renderingAuthoring = new RenderingAuthoringBackendCatalog(m_runtime.rendering, authoringProviders); } - IReadOnlyList IRenderingAuthoringBackendFactory.supportedBackends - => m_renderingAuthoring.supportedBackends; - /// /// Gets the built-in platform backend factory. /// @@ -90,7 +84,7 @@ IReadOnlyList IRenderingAuthoringBackendFactory.supportedBac /// /// Gets the built-in retained-mode UI backend factory. /// - public IUiBackendFactory ui => m_runtime.ui; + public IUIBackendFactory ui => m_runtime.ui; /// /// Gets the built-in rendering authoring toolchain factory. @@ -102,12 +96,12 @@ IReadOnlyList IRenderingAuthoringBackendFactory.supportedBac /// public IPresentationBackendFactory presentation => m_presentation; - IShaderCompilerToolchain IRenderingAuthoringBackendFactory.CreateShaderCompilerToolchain( - RenderingBackendId backend) + IReadOnlyList IRenderingAuthoringBackendFactory.supportedBackends + => m_renderingAuthoring.supportedBackends; + + IShaderCompilerToolchain IRenderingAuthoringBackendFactory.CreateShaderCompilerToolchain(RenderingBackendID backend) => m_renderingAuthoring.CreateShaderCompilerToolchain(backend); - ITextureTargetCompiler IRenderingAuthoringBackendFactory.CreateTextureTargetCompiler( - RenderingBackendId backend) + ITextureTargetCompiler IRenderingAuthoringBackendFactory.CreateTextureTargetCompiler(RenderingBackendID backend) => m_renderingAuthoring.CreateTextureTargetCompiler(backend); - } diff --git a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs index 127c4bf5f..7760ce238 100644 --- a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs +++ b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Adapter.Audio; using Inno.Adapter.Audio.MiniAudio; using Inno.Adapter.Input; @@ -29,7 +28,7 @@ public sealed class DefaultAdapterCatalog : IAdapterCatalog private readonly IRenderingBackendFactory m_rendering; private readonly AudioBackendCatalog m_audio; private readonly TextBackendCatalog m_text; - private readonly UiBackendCatalog m_ui; + private readonly UIBackendCatalog m_ui; /// /// Captures each domain registration snapshot without initializing native services. @@ -51,7 +50,7 @@ public sealed class DefaultAdapterCatalog : IAdapterCatalog /// public DefaultAdapterCatalog( DefaultAdapterCatalogOptions options, - IEnumerable? uiProviders = null, + IEnumerable? uiProviders = null, IEnumerable? inputProviders = null, IEnumerable? audioProviders = null, IEnumerable? textProviders = null @@ -63,7 +62,7 @@ public DefaultAdapterCatalog( m_rendering = options.rendering ?? throw new ArgumentException("Host rendering must be configured.", nameof(options)); m_audio = new AudioBackendCatalog(audioProviders ?? [new MiniAudioBackendProvider()]); m_text = new TextBackendCatalog(textProviders ?? [new FreeTypeHarfBuzzTextBackendProvider()]); - m_ui = new UiBackendCatalog(uiProviders ?? [new RmlUiBackendProvider()]); + m_ui = new UIBackendCatalog(uiProviders ?? [new RmlUiBackendProvider()]); } /// @@ -99,5 +98,5 @@ public DefaultAdapterCatalog( /// /// Gets the composition-owned ui factory snapshot. /// - public IUiBackendFactory ui => m_ui; + public IUIBackendFactory ui => m_ui; } diff --git a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs index 3daf267e6..9a0ee9ae0 100644 --- a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs +++ b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs @@ -1,6 +1,6 @@ -using Inno.Adapter.Storage; -using Inno.Adapter.Rendering; using Inno.Adapter.Platform; +using Inno.Adapter.Rendering; +using Inno.Adapter.Storage; namespace Inno.Adapter.Default; diff --git a/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs b/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs index e91ff9bd9..728e31b96 100644 --- a/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs +++ b/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs @@ -22,14 +22,15 @@ public static class StandardAdapterSelection /// /// A fully assigned standard selection; its catalog must still be validated before creating resources. /// - public static AdapterSelection Create(StorageBackendId storage) => new() + public static AdapterSelection Create(StorageBackendID storage) + => new() { - platform = PlatformBackendId.sdl3, - input = InputBackendId.events, + platform = PlatformBackendID.sdl3, + input = InputBackendID.events, storage = storage, - rendering = RenderingBackendId.bgfx, - audio = AudioBackendId.miniAudio, - text = TextBackendId.freeTypeHarfBuzz, - ui = UiBackendId.rmlUi + rendering = RenderingBackendID.bgfx, + audio = AudioBackendID.miniAudio, + text = TextBackendID.freeTypeHarfBuzz, + ui = UIBackendID.rmlUI }; } diff --git a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs index 9780df7f3..86a8a9d8e 100644 --- a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs @@ -10,9 +10,12 @@ internal static class AnimationSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new AnimationRuntimeFactory(owner => { - var reporter = owner.resources.Own(owner.diagnostics.CreateReporter( - new DiagnosticSource($"inno.animation.bindings.{owner.identities.domainId}", "Animation"))); - var bindings = owner.resources.Own(new AnimationBindingRuntime(owner.types, reporter)); + DiagnosticReporter reporter = owner.resources.Own( + owner.diagnostics.CreateReporter( + new DiagnosticSource($"inno.animation.bindings.{owner.identities.domainID}", "Animation") + ) + ); + AnimationBindingRuntime bindings = owner.resources.Own(new AnimationBindingRuntime(owner.types, reporter)); return new AnimationRuntime(owner.events, bindings); }); } diff --git a/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs b/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs index 9f38f1ac2..edec76b0a 100644 --- a/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs @@ -17,8 +17,11 @@ private static AudioRuntime CreateRuntime( EngineSessionComposition composition, RuntimeSubsystemContext owner ) { - DiagnosticReporter diagnostics = owner.resources.Own(owner.diagnostics.CreateReporter( - new DiagnosticSource($"inno.audio.{composition.session.sessionId}", "Audio"))); + DiagnosticReporter diagnostics = owner.resources.Own( + owner.diagnostics.CreateReporter( + new DiagnosticSource($"inno.audio.{composition.session.sessionID}", "Audio") + ) + ); IAudioDevice device; try { @@ -26,17 +29,27 @@ RuntimeSubsystemContext owner } catch (Exception exception) { - diagnostics.Publish(new Diagnostic("AUDIO_DEVICE_INIT_FAILED", - $"Audio output could not start; this session is explicitly muted: {exception.Message}", - DiagnosticSeverity.Warning, composition.selection.audio.ToString())); + diagnostics.Publish( + new Diagnostic( + "AUDIO_DEVICE_INIT_FAILED", + $"Audio output could not start; this session is explicitly muted: {exception.Message}", + DiagnosticSeverity.Warning, + composition.selection.audio.ToString() + ) + ); device = new MutedAudioDevice(); } AudioRuntime? runtime = null; try { AudioProjectSettings settings = composition.audioSettings() - ?? throw new InvalidOperationException("The audio settings source returned null."); - runtime = new AudioRuntime(owner.types, device, composition.artifacts, owner.events, diagnostics, + ?? throw new InvalidOperationException("The audio settings source returned null."); + runtime = new AudioRuntime( + owner.types, + device, + composition.artifacts, + owner.events, + diagnostics, new AudioRuntimeOptions { maxVoices = settings.maxVoices, @@ -44,11 +57,16 @@ RuntimeSubsystemContext owner automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes }, contentScopeProvider: () => SceneContentSource.CreateScope(composition.session.scenes), - deviceRecoveryFactory: () => composition.adapters.audio.CreateDevice(composition.selection.audio)); + deviceRecoveryFactory: () => composition.adapters.audio.CreateDevice(composition.selection.audio) + ); if (settings.defaultMixer is not null && !runtime.ApplyMixer(settings.defaultMixer)) + { throw new InvalidOperationException("The configured default mixer could not be activated."); - if (!runtime.SetBusVolume(AudioBusId.master, settings.masterVolume)) + } + if (!runtime.SetBusVolume(AudioBusID.master, settings.masterVolume)) + { throw new InvalidOperationException("The configured master volume could not be applied."); + } return runtime; } catch (Exception failure) @@ -56,9 +74,13 @@ RuntimeSubsystemContext owner try { if (runtime is null) + { device.Dispose(); + } else + { runtime.Dispose(); + } } catch (Exception cleanup) { diff --git a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs index 275904d01..b5d169fa5 100644 --- a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs +++ b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs @@ -35,12 +35,12 @@ public sealed class EngineSessionComposition /// /// The portable audio defaults, captured during factory activation. /// - /// - /// An optional product-specific audio owner, such as Editor preview/Play isolation. - /// /// /// The host factory transferring one isolated storage service to the session. /// + /// + /// An optional product-specific audio owner, such as Editor preview/Play isolation. + /// public EngineSessionComposition( RuntimeSession session, IAdapterCatalog adapters, @@ -51,13 +51,19 @@ public EngineSessionComposition( Func createStorage, IRuntimeSubsystemFactory? audioOverride = null ) { - this.session = session ?? throw new ArgumentNullException(nameof(session)); - this.adapters = adapters ?? throw new ArgumentNullException(nameof(adapters)); + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(adapters); + ArgumentNullException.ThrowIfNull(inputSource); + ArgumentNullException.ThrowIfNull(artifacts); + ArgumentNullException.ThrowIfNull(audioSettings); + ArgumentNullException.ThrowIfNull(createStorage); + this.session = session; + this.adapters = adapters; this.selection = selection; - this.inputSource = inputSource ?? throw new ArgumentNullException(nameof(inputSource)); - this.artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - this.audioSettings = audioSettings ?? throw new ArgumentNullException(nameof(audioSettings)); - this.createStorage = createStorage ?? throw new ArgumentNullException(nameof(createStorage)); + this.inputSource = inputSource; + this.artifacts = artifacts; + this.audioSettings = audioSettings; + this.createStorage = createStorage; this.audioOverride = audioOverride; } @@ -65,30 +71,37 @@ public EngineSessionComposition( /// Gets the isolated session selected by the product. /// public RuntimeSession session { get; } + /// /// Gets the backend-neutral adapter factory catalog. /// public IAdapterCatalog adapters { get; } + /// /// Gets portable backend selection values. /// public AdapterSelection selection { get; } + /// /// Gets the host input source shared by isolated session readers. /// public IInputEventSource inputSource { get; } + /// /// Gets immutable encoded content artifacts from the selected host environment. /// public IAssetArtifactLookup artifacts { get; } + /// /// Gets the control-thread source of portable audio defaults. /// public Func audioSettings { get; } + /// /// Gets the factory transferring storage ownership to this session. /// public Func createStorage { get; } + /// /// Gets an optional product-specific audio owner factory. /// diff --git a/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs b/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs index f4e091d81..cf5014e87 100644 --- a/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs @@ -9,5 +9,6 @@ internal static class TextSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new TextRuntimeFactory(_ => new TextRuntime( context.adapters.text.CreateBackend(context.selection.text), - context.artifacts)); + context.artifacts + )); } diff --git a/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs b/src/composition/default/Inno.Engine.Default/UI/UISubsystem.cs similarity index 70% rename from src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs rename to src/composition/default/Inno.Engine.Default/UI/UISubsystem.cs index 3a85e02dc..38541f29b 100644 --- a/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/UI/UISubsystem.cs @@ -3,11 +3,12 @@ namespace Inno.Engine.Default; -internal static class UiSubsystem +internal static class UISubsystem { [RuntimeSubsystemRegistration("inno.runtime.ui")] internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) - => new UiRuntimeFactory(_ => new UiRuntime( + => new UIRuntimeFactory(_ => new UIRuntime( context.adapters.ui.CreateBackend(context.selection.ui), - context.artifacts)); + context.artifacts + )); } diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs new file mode 100644 index 000000000..da2e04af3 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs @@ -0,0 +1,39 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Starts a visually separated Inspector section before the annotated property. +/// +[Conditional("INNO_EDITOR")] +public sealed class HeaderAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a section header with optional explanatory text. + /// + /// + /// Visible section title. + /// + /// + /// Optional explanatory text displayed when the title is hovered. + /// + public HeaderAttribute( + string title, + string description = "" + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(title); + this.title = title; + this.description = description ?? string.Empty; + } + + /// + /// Gets the visible section title. + /// + public string title { get; } + + /// + /// Gets the optional explanatory text. + /// + public string description { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs new file mode 100644 index 000000000..e9bf266d9 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs @@ -0,0 +1,109 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Draws a wrapped explanatory message before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class HelpBoxAttribute : InspectorPresentationAttribute +{ + /// + /// Creates an Inspector help message. + /// + /// + /// Non-empty message text. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) {} + + /// + /// Creates an Inspector help message shown when a sibling satisfies a named condition. + /// + /// + /// Non-empty message text. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + string conditionMember, + InspectorCondition condition, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, conditionMember, condition, null) {} + + /// + /// Creates an Inspector help message shown when a sibling equals a compile-time value. + /// + /// + /// Non-empty message text. + /// + /// + /// Sibling field or property name. + /// + /// + /// The expected value consumed by help box attribute; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + string conditionMember, + object? expectedValue, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) {} + + private HelpBoxAttribute( + string text, + InspectorMessageType messageType, + string conditionMember, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + this.messageType = messageType; + this.conditionMember = conditionMember ?? string.Empty; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the message text. + /// + public string text { get; } + + /// + /// Gets the visual severity. + /// + public InspectorMessageType messageType { get; } + + /// + /// Gets the optional sibling member controlling message visibility. + /// + public string conditionMember { get; } + + /// + /// Gets the optional sibling comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs new file mode 100644 index 000000000..6bfc6bbd8 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs @@ -0,0 +1,74 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Hides the annotated Inspector property when a sibling member satisfies a condition. +/// +[Conditional("INNO_EDITOR")] +public sealed class HideIfAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a truthiness condition. + /// + /// + /// Sibling field or property name. + /// + public HideIfAttribute(string memberName) + : this(memberName, InspectorCondition.Truthy, null) {} + + /// + /// Creates an equality condition. + /// + /// + /// Sibling field or property name. + /// + /// + /// Compile-time value that hides the property. + /// + public HideIfAttribute( + string memberName, + object? expectedValue + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} + + /// + /// Creates a named condition that does not require an expected value. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + public HideIfAttribute( + string memberName, + InspectorCondition condition + ) : this(memberName, condition, null) {} + + private HideIfAttribute( + string memberName, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(memberName); + this.memberName = memberName; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the sibling member name. + /// + public string memberName { get; } + + /// + /// Gets the comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs new file mode 100644 index 000000000..e1c65928b --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs @@ -0,0 +1,40 @@ +namespace Inno.Editor.Annotations; + +/// +/// Defines the comparison used by conditional Inspector presentation. +/// +public enum InspectorCondition +{ + /// + /// Shows a value when it evaluates as true or non-empty. + /// + Truthy, + /// + /// Shows a value when it evaluates as false, null, or empty. + /// + Falsy, + /// + /// Compares the value with the supplied expected constant. + /// + Equal, + /// + /// Requires the value to differ from the supplied expected constant. + /// + NotEqual, + /// + /// Requires a null value. + /// + Null, + /// + /// Requires a non-null value. + /// + NotNull, + /// + /// Requires a reference-like value to expose an assigned resource. + /// + Assigned, + /// + /// Requires a reference-like value not to expose an assigned resource. + /// + NotAssigned +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs new file mode 100644 index 000000000..1b5be80f7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs @@ -0,0 +1,20 @@ +namespace Inno.Editor.Annotations; + +/// +/// Selects the visual severity of an Inspector help message. +/// +public enum InspectorMessageType +{ + /// + /// Neutral explanatory information. + /// + Info, + /// + /// A non-blocking configuration warning. + /// + Warning, + /// + /// An invalid or unusable configuration. + /// + Error +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs new file mode 100644 index 000000000..03c8c7ef0 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Replaces the generated Inspector label for one property. +/// +[Conditional("INNO_EDITOR")] +public sealed class InspectorNameAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a label override. + /// + /// + /// Non-empty visible label. + /// + public InspectorNameAttribute(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + this.name = name; + } + + /// + /// Gets the visible label. + /// + public string name { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs new file mode 100644 index 000000000..19955fd09 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs @@ -0,0 +1,21 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Provides editor-only presentation metadata for one serialized field or property. +/// +/// +/// Presentation attributes never participate in serialization. Concrete attributes are conditional on +/// INNO_EDITOR, so their applications are omitted from Player script assemblies. +/// +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] +[Conditional("INNO_EDITOR")] +public abstract class InspectorPresentationAttribute : Attribute +{ + /// + /// Gets or sets the relative order among presentation attributes declared on the same member. + /// + public int order { get; set; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs deleted file mode 100644 index b4b0c31cf..000000000 --- a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs +++ /dev/null @@ -1,535 +0,0 @@ -using System; -using System.Diagnostics; - -namespace Inno.Editor.Annotations; - -/// -/// Provides editor-only presentation metadata for one serialized field or property. -/// -/// -/// Presentation attributes never participate in serialization. Concrete attributes are conditional on -/// INNO_EDITOR, so their applications are omitted from Player script assemblies. -/// -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] -[Conditional("INNO_EDITOR")] -public abstract class InspectorPresentationAttribute : Attribute -{ - /// - /// Gets or sets the relative order among presentation attributes declared on the same member. - /// - public int order { get; set; } -} - -/// -/// Starts a visually separated Inspector section before the annotated property. -/// -[Conditional("INNO_EDITOR")] -public sealed class HeaderAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a section header with optional explanatory text. - /// - /// - /// Visible section title. - /// - /// - /// Optional explanatory text displayed when the title is hovered. - /// - public HeaderAttribute( - string title, - string description = "" - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(title); - this.title = title; - this.description = description ?? string.Empty; - } - - /// - /// Gets the visible section title. - /// - public string title { get; } - - /// - /// Gets the optional explanatory text. - /// - public string description { get; } -} - -/// -/// Draws persistent wrapped explanatory text before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class TextAttribute : InspectorPresentationAttribute -{ - /// - /// Creates persistent Inspector text. - /// - /// - /// Non-empty text displayed in the Inspector layout. - /// - public TextAttribute(string text) - { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - } - - /// - /// Gets the persistent Inspector text. - /// - public string text { get; } -} - -/// -/// Inserts vertical spacing before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class SpaceAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a spacing decorator. - /// - /// - /// Non-negative logical pixel height. - /// - public SpaceAttribute(float height = 8f) - { - ArgumentOutOfRangeException.ThrowIfNegative(height); - this.height = height; - } - - /// - /// Gets the logical pixel height. - /// - public float height { get; } -} - -/// -/// Provides hover help for one Inspector property label. -/// -[Conditional("INNO_EDITOR")] -public sealed class TooltipAttribute : InspectorPresentationAttribute -{ - /// - /// Creates property hover help. - /// - /// - /// Non-empty tooltip text. - /// - public TooltipAttribute(string text) - { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - } - - /// - /// Gets the tooltip text. - /// - public string text { get; } -} - -/// -/// Replaces the generated Inspector label for one property. -/// -[Conditional("INNO_EDITOR")] -public sealed class InspectorNameAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a label override. - /// - /// - /// Non-empty visible label. - /// - public InspectorNameAttribute(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - this.name = name; - } - - /// - /// Gets the visible label. - /// - public string name { get; } -} - -/// -/// Constrains a numeric Inspector control to an inclusive range. -/// -[Conditional("INNO_EDITOR")] -public sealed class RangeAttribute : InspectorPresentationAttribute -{ - /// - /// Creates an inclusive numeric range. - /// - /// - /// Inclusive lower bound. - /// - /// - /// Inclusive upper bound. - /// - public RangeAttribute( - double minimum, - double maximum - ) { - if (!double.IsFinite(minimum)) - throw new ArgumentOutOfRangeException(nameof(minimum)); - if (!double.IsFinite(maximum) || maximum < minimum) - throw new ArgumentOutOfRangeException(nameof(maximum)); - this.minimum = minimum; - this.maximum = maximum; - } - - /// - /// Gets the inclusive lower bound. - /// - public double minimum { get; } - - /// - /// Gets the inclusive upper bound. - /// - public double maximum { get; } -} - -/// -/// Makes an otherwise writable serialized property read-only in the Inspector. -/// -[Conditional("INNO_EDITOR")] -public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute -{ -} - -/// -/// Defines the comparison used by conditional Inspector presentation. -/// -public enum InspectorCondition -{ - /// - /// Shows a value when it evaluates as true or non-empty. - /// - Truthy, - - /// - /// Shows a value when it evaluates as false, null, or empty. - /// - Falsy, - - /// - /// Compares the value with the supplied expected constant. - /// - Equal, - - /// - /// Requires the value to differ from the supplied expected constant. - /// - NotEqual, - - /// - /// Requires a null value. - /// - Null, - - /// - /// Requires a non-null value. - /// - NotNull, - - /// - /// Requires a reference-like value to expose an assigned resource. - /// - Assigned, - - /// - /// Requires a reference-like value not to expose an assigned resource. - /// - NotAssigned -} - -/// -/// Shows the annotated Inspector property only when a sibling member satisfies a condition. -/// -[Conditional("INNO_EDITOR")] -public sealed class ShowIfAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a truthiness condition. - /// - /// - /// Sibling field or property name. - /// - public ShowIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) - { - } - - /// - /// Creates an equality condition. - /// - /// - /// Sibling field or property name. - /// - /// - /// Compile-time value required for visibility. - /// - public ShowIfAttribute( - string memberName, - object? expectedValue - ) - : this(memberName, InspectorCondition.Equal, expectedValue) - { - } - - /// - /// Creates a named condition that does not require an expected value. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - public ShowIfAttribute( - string memberName, - InspectorCondition condition - ) - : this(memberName, condition, null) - { - } - - private ShowIfAttribute( - string memberName, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - this.memberName = memberName; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the sibling member name. - /// - public string memberName { get; } - - /// - /// Gets the comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} - -/// -/// Hides the annotated Inspector property when a sibling member satisfies a condition. -/// -[Conditional("INNO_EDITOR")] -public sealed class HideIfAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a truthiness condition. - /// - /// - /// Sibling field or property name. - /// - public HideIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) - { - } - - /// - /// Creates an equality condition. - /// - /// - /// Sibling field or property name. - /// - /// - /// Compile-time value that hides the property. - /// - public HideIfAttribute( - string memberName, - object? expectedValue - ) - : this(memberName, InspectorCondition.Equal, expectedValue) - { - } - - /// - /// Creates a named condition that does not require an expected value. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - public HideIfAttribute( - string memberName, - InspectorCondition condition - ) - : this(memberName, condition, null) - { - } - - private HideIfAttribute( - string memberName, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - this.memberName = memberName; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the sibling member name. - /// - public string memberName { get; } - - /// - /// Gets the comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} - -/// -/// Selects the visual severity of an Inspector help message. -/// -public enum InspectorMessageType -{ - /// - /// Neutral explanatory information. - /// - Info, - - /// - /// A non-blocking configuration warning. - /// - Warning, - - /// - /// An invalid or unusable configuration. - /// - Error -} - -/// -/// Draws a wrapped explanatory message before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class HelpBoxAttribute : InspectorPresentationAttribute -{ - /// - /// Creates an Inspector help message. - /// - /// - /// Non-empty message text. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) - { - } - - /// - /// Creates an Inspector help message shown when a sibling satisfies a named condition. - /// - /// - /// Non-empty message text. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - string conditionMember, - InspectorCondition condition, - InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, conditionMember, condition, null) - { - } - - /// - /// Creates an Inspector help message shown when a sibling equals a compile-time value. - /// - /// - /// Non-empty message text. - /// - /// - /// Sibling field or property name. - /// - /// - /// The expected value consumed by help box attribute; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - string conditionMember, - object? expectedValue, - InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) - { - } - - private HelpBoxAttribute( - string text, - InspectorMessageType messageType, - string conditionMember, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - this.messageType = messageType; - this.conditionMember = conditionMember ?? string.Empty; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the message text. - /// - public string text { get; } - - /// - /// Gets the visual severity. - /// - public InspectorMessageType messageType { get; } - - /// - /// Gets the optional sibling member controlling message visibility. - /// - public string conditionMember { get; } - - /// - /// Gets the optional sibling comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs new file mode 100644 index 000000000..d48ae56b7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs @@ -0,0 +1,9 @@ +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Makes an otherwise writable serialized property read-only in the Inspector. +/// +[Conditional("INNO_EDITOR")] +public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute; diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs index b856737d2..57c54aac7 100644 --- a/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Annotations; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Annotations", "Inno.Editor.Annotations", ScriptingApiScope.Authoring)] [assembly: ScriptingApiExport(typeof(InspectorPresentationAttribute), ScriptingApiScope.Authoring)] diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs new file mode 100644 index 000000000..e4fc014d1 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs @@ -0,0 +1,46 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Constrains a numeric Inspector control to an inclusive range. +/// +[Conditional("INNO_EDITOR")] +public sealed class RangeAttribute : InspectorPresentationAttribute +{ + /// + /// Creates an inclusive numeric range. + /// + /// + /// Inclusive lower bound. + /// + /// + /// Inclusive upper bound. + /// + public RangeAttribute( + double minimum, + double maximum + ) { + if (!double.IsFinite(minimum)) + { + throw new ArgumentOutOfRangeException(nameof(minimum)); + } + if (!double.IsFinite(maximum) || maximum < minimum) + { + throw new ArgumentOutOfRangeException(nameof(maximum)); + } + this.minimum = minimum; + this.maximum = maximum; + } + + /// + /// Gets the inclusive lower bound. + /// + public double minimum { get; } + + /// + /// Gets the inclusive upper bound. + /// + public double maximum { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs new file mode 100644 index 000000000..285ab796b --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs @@ -0,0 +1,74 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Shows the annotated Inspector property only when a sibling member satisfies a condition. +/// +[Conditional("INNO_EDITOR")] +public sealed class ShowIfAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a truthiness condition. + /// + /// + /// Sibling field or property name. + /// + public ShowIfAttribute(string memberName) + : this(memberName, InspectorCondition.Truthy, null) {} + + /// + /// Creates an equality condition. + /// + /// + /// Sibling field or property name. + /// + /// + /// Compile-time value required for visibility. + /// + public ShowIfAttribute( + string memberName, + object? expectedValue + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} + + /// + /// Creates a named condition that does not require an expected value. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + public ShowIfAttribute( + string memberName, + InspectorCondition condition + ) : this(memberName, condition, null) {} + + private ShowIfAttribute( + string memberName, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(memberName); + this.memberName = memberName; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the sibling member name. + /// + public string memberName { get; } + + /// + /// Gets the comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs new file mode 100644 index 000000000..b1e94b8c7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Inserts vertical spacing before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class SpaceAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a spacing decorator. + /// + /// + /// Non-negative logical pixel height. + /// + public SpaceAttribute(float height = 8f) + { + ArgumentOutOfRangeException.ThrowIfNegative(height); + this.height = height; + } + + /// + /// Gets the logical pixel height. + /// + public float height { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs new file mode 100644 index 000000000..99e36bebd --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Draws persistent wrapped explanatory text before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class TextAttribute : InspectorPresentationAttribute +{ + /// + /// Creates persistent Inspector text. + /// + /// + /// Non-empty text displayed in the Inspector layout. + /// + public TextAttribute(string text) + { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + } + + /// + /// Gets the persistent Inspector text. + /// + public string text { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs new file mode 100644 index 000000000..3f1cc3b6f --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Provides hover help for one Inspector property label. +/// +[Conditional("INNO_EDITOR")] +public sealed class TooltipAttribute : InspectorPresentationAttribute +{ + /// + /// Creates property hover help. + /// + /// + /// Non-empty tooltip text. + /// + public TooltipAttribute(string text) + { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + } + + /// + /// Gets the tooltip text. + /// + public string text { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs new file mode 100644 index 000000000..a1455237c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs @@ -0,0 +1,42 @@ +using System; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Scripting.Api; + +namespace Inno.Editor.Assets; + +/// +/// Provides source encoding services to one detached Asset creation template invocation. +/// +public sealed class AssetCreationContext +{ + private readonly AssetSourceStore m_sources; + + /// + /// Creates a context over the source serializer owned by the active Asset pipeline. + /// + /// + /// Source serializer carrying the active reference context. + /// + [ScriptingApiIgnore] + public AssetCreationContext(AssetSourceStore sources) + { + ArgumentNullException.ThrowIfNull(sources); + m_sources = sources; + } + + /// + /// Encodes an Asset value through the current native structured source serializer. + /// + /// + /// Detached Asset value to encode. + /// + /// + /// Complete native source bytes, including the concrete serialized type identity. + /// + public byte[] EncodeNative(AssetObject asset) + { + ArgumentNullException.ThrowIfNull(asset); + return m_sources.Encode(asset); + } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs new file mode 100644 index 000000000..a41f300f5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs @@ -0,0 +1,116 @@ +using System; +using Inno.Assets; + +namespace Inno.Editor.Assets; + +/// +/// Declares the source name, extension, and menu placement that cannot be inferred from an +/// type alone. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetCreationMenuAttribute : Attribute +{ + /// + /// Creates one asset creation menu declaration. + /// + /// + /// Globally stable template identifier. + /// + /// + /// Slash-delimited path below the File Browser Create menu. + /// + /// + /// Native source extension, including its leading dot. + /// + /// + /// Default source name without an extension or numeric suffix. + /// + /// + /// Stable order of the top-level category below Create. + /// + /// + /// Stable order of the leaf within its immediate category. + /// + /// + /// Whether the top-level category starts after a separator. + /// + /// + /// Thrown when an identifier, path, source name, or native extension is invalid. + /// + public AssetCreationMenuAttribute( + string id, + string menuPath, + string extension, + string defaultName, + int groupOrder = 0, + int itemOrder = 0, + bool separatorBeforeGroup = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(menuPath); + ArgumentException.ThrowIfNullOrWhiteSpace(extension); + ArgumentException.ThrowIfNullOrWhiteSpace(defaultName); + if (extension.Length == 0 || extension[0] != '.' + || extension.IndexOfAny(['/', '\\']) >= 0 + ) { + throw new ArgumentException( + "A native source extension beginning with a dot is required.", + nameof(extension) + ); + } + + string normalizedPath = menuPath.Replace('\\', '/').Trim('/'); + if (normalizedPath.Length == 0 + || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment)) + ) { + throw new ArgumentException("A valid menu path is required.", nameof(menuPath)); + } + if (defaultName.IndexOfAny(['/', '\\']) >= 0) + { + throw new ArgumentException("The default name cannot contain a path separator.", nameof(defaultName)); + } + + this.id = id; + this.menuPath = normalizedPath; + this.extension = extension.ToLowerInvariant(); + this.defaultName = defaultName.Trim(); + this.groupOrder = groupOrder; + this.itemOrder = itemOrder; + this.separatorBeforeGroup = separatorBeforeGroup; + } + + /// + /// Gets the globally stable template identifier. + /// + public string id { get; } + + /// + /// Gets the slash-delimited path below the File Browser Create menu. + /// + public string menuPath { get; } + + /// + /// Gets the native source extension, including its leading dot. + /// + public string extension { get; } + + /// + /// Gets the default source name without an extension or numeric suffix. + /// + public string defaultName { get; } + + /// + /// Gets the stable order of the top-level category below Create. + /// + public int groupOrder { get; } + + /// + /// Gets the stable order of the leaf within its immediate category. + /// + public int itemOrder { get; } + + /// + /// Gets whether the top-level category starts after a separator. + /// + public bool separatorBeforeGroup { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs index faa653ec0..407a25d51 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs @@ -1,119 +1,8 @@ using System; using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Scripting.Api; namespace Inno.Editor.Assets; -/// -/// Declares the source name, extension, and menu placement that cannot be inferred from an -/// type alone. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetCreationMenuAttribute : Attribute -{ - /// - /// Creates one asset creation menu declaration. - /// - /// - /// Globally stable template identifier. - /// - /// - /// Slash-delimited path below the File Browser Create menu. - /// - /// - /// Native source extension, including its leading dot. - /// - /// - /// Default source name without an extension or numeric suffix. - /// - /// - /// Stable order of the top-level category below Create. - /// - /// - /// Stable order of the leaf within its immediate category. - /// - /// - /// Whether the top-level category starts after a separator. - /// - /// - /// Thrown when an identifier, path, source name, or native extension is invalid. - /// - public AssetCreationMenuAttribute( - string id, - string menuPath, - string extension, - string defaultName, - int groupOrder = 0, - int itemOrder = 0, - bool separatorBeforeGroup = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(menuPath); - ArgumentException.ThrowIfNullOrWhiteSpace(extension); - ArgumentException.ThrowIfNullOrWhiteSpace(defaultName); - if (extension.Length == 0 || extension[0] != '.' - || extension.IndexOfAny(['/', '\\']) >= 0) - { - throw new ArgumentException( - "A native source extension beginning with a dot is required.", - nameof(extension)); - } - - string normalizedPath = menuPath.Replace('\\', '/').Trim('/'); - if (normalizedPath.Length == 0 - || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment))) - { - throw new ArgumentException("A valid menu path is required.", nameof(menuPath)); - } - if (defaultName.IndexOfAny(['/', '\\']) >= 0) - throw new ArgumentException("The default name cannot contain a path separator.", nameof(defaultName)); - - this.id = id; - this.menuPath = normalizedPath; - this.extension = extension.ToLowerInvariant(); - this.defaultName = defaultName.Trim(); - this.groupOrder = groupOrder; - this.itemOrder = itemOrder; - this.separatorBeforeGroup = separatorBeforeGroup; - } - - /// - /// Gets the globally stable template identifier. - /// - public string id { get; } - - /// - /// Gets the slash-delimited path below the File Browser Create menu. - /// - public string menuPath { get; } - - /// - /// Gets the native source extension, including its leading dot. - /// - public string extension { get; } - - /// - /// Gets the default source name without an extension or numeric suffix. - /// - public string defaultName { get; } - - /// - /// Gets the stable order of the top-level category below Create. - /// - public int groupOrder { get; } - - /// - /// Gets the stable order of the leaf within its immediate category. - /// - public int itemOrder { get; } - - /// - /// Gets whether the top-level category starts after a separator. - /// - public bool separatorBeforeGroup { get; } -} - /// /// Produces the detached initial value for one authorable native asset source. /// @@ -163,38 +52,6 @@ AssetObject asset } } -/// -/// Provides source encoding services to one detached Asset creation template invocation. -/// -public sealed class AssetCreationContext -{ - private readonly AssetSourceStore m_sources; - - /// - /// Creates a context over the source serializer owned by the active Asset pipeline. - /// - /// - /// Source serializer carrying the active reference context. - /// - [ScriptingApiIgnore] - public AssetCreationContext(AssetSourceStore sources) => m_sources = sources ?? throw new ArgumentNullException(nameof(sources)); - - /// - /// Encodes an Asset value through the current native structured source serializer. - /// - /// - /// Detached Asset value to encode. - /// - /// - /// Complete native source bytes, including the concrete serialized type identity. - /// - public byte[] EncodeNative(AssetObject asset) - { - ArgumentNullException.ThrowIfNull(asset); - return m_sources.Encode(asset); - } -} - /// /// Creates a default-constructed native source for an authorable asset type. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs index 46af4351e..02a966b1c 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs @@ -4,19 +4,22 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Owns detached native asset drafts with shared document, History, recovery and explicit-save semantics. /// /// /// Native source type edited by the consuming feature. /// -public sealed class AssetDraftDocuments : IDisposable where TAsset : AssetObject +public sealed class AssetDraftDocuments : IDisposable + where TAsset : AssetObject { private readonly Dictionary m_drafts = []; private readonly HashSet m_imports = []; @@ -24,12 +27,13 @@ public sealed class AssetDraftDocuments : IDisposable where TAsset : Ass private readonly AssetSourceStore m_sources; private readonly AssetPipeline m_assets; private readonly EditorInteractions m_interactions; - private readonly string m_providerId; + private readonly string m_providerID; private readonly string m_historyKind; private readonly string m_extension; private readonly string m_label; private IDisposable? m_provider; private long m_sourceRevision = -1; + /// /// Creates a feature-owned draft store; call Start after document services become available. /// @@ -42,7 +46,7 @@ public sealed class AssetDraftDocuments : IDisposable where TAsset : Ass /// /// Shared documents and History services. /// - /// + /// /// Stable unique document provider identifier. /// /// @@ -58,7 +62,7 @@ public AssetDraftDocuments( AssetPipeline assets, SerializationRegistry serialization, EditorInteractions interactions, - string providerId, + string providerID, string historyKind, string extension, string label @@ -66,18 +70,22 @@ string label ArgumentNullException.ThrowIfNull(assets); ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(interactions); - ArgumentException.ThrowIfNullOrWhiteSpace(providerId); + ArgumentException.ThrowIfNullOrWhiteSpace(providerID); ArgumentException.ThrowIfNullOrWhiteSpace(historyKind); ArgumentException.ThrowIfNullOrWhiteSpace(label); if (string.IsNullOrWhiteSpace(extension) || !extension.StartsWith('.') || extension.IndexOfAny(['/', '\\']) >= 0) + { throw new ArgumentException("A native file extension is required.", nameof(extension)); - if (providerId is "." or ".." || providerId.IndexOfAny(['/', '\\', ':']) >= 0) - throw new ArgumentException("The provider identifier must be a safe single directory name.", nameof(providerId)); + } + if (providerID is "." or ".." || providerID.IndexOfAny(['/', '\\', ':']) >= 0) + { + throw new ArgumentException("The provider identifier must be a safe single directory name.", nameof(providerID)); + } m_assets = assets; m_interactions = interactions; m_serialization = serialization; m_sources = m_assets.CreateSourceStore(); - m_providerId = providerId; + m_providerID = providerID; m_historyKind = historyKind; m_extension = extension; m_label = label; @@ -86,13 +94,14 @@ string label /// /// Gets host-owned neutral presentation state for an open document. /// - /// + /// /// Persistent source identity. /// /// /// Read-only presentation state; it contains no live asset or extension objects. /// - public Draft GetDraft(Guid assetId) => m_drafts[assetId]; + public Draft GetDraft(Guid assetID) => m_drafts[assetID]; + /// /// Opens a native asset source in the shared document service without revealing a second Inspector. /// @@ -105,27 +114,32 @@ string label public Guid Open(AssetPath path) { if (!path.localPath.EndsWith(m_extension, StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("The source extension does not belong to this document provider.", nameof(path)); + } if (!m_assets.TryGetInfo(path, out AssetInfo? info) || info is null) + { throw new IOException("The asset identity is unavailable."); - m_interactions.documents.Open(path.ToString(), info.persistentId); - return info.persistentId; + } + m_interactions.documents.Open(path.ToString(), info.persistentID); + return info.persistentID; } /// /// Reads a detached current-generation value; callers must never mutate its referenced canonical assets. /// - /// + /// /// Open asset identity. /// /// /// A detached editable asset whose changes have not been published. /// - public TAsset Read(Guid assetId) => m_sources.Decode(m_drafts[assetId].bytes); + public TAsset Read(Guid assetID) => m_sources.Decode(m_drafts[assetID].bytes); + /// /// Updates the open draft through shared History without saving or publishing a runtime asset. /// - /// + /// /// Open asset identity. /// /// @@ -135,13 +149,15 @@ public Guid Open(AssetPath path) /// The current gesture key, or null for an independent discrete edit. /// public void Replace( - Guid assetId, + Guid assetID, TAsset candidate, string? mergeKey = null ) { - Draft draft = m_drafts[assetId]; + Draft draft = m_drafts[assetID]; if (draft.readOnly) + { throw new InvalidOperationException("Copy this installed asset to the project before editing."); + } RecordReplace(draft, m_sources.Encode(candidate), mergeKey); } @@ -160,47 +176,21 @@ public void ReplaceMany( ) { ArgumentNullException.ThrowIfNull(candidates); var encoded = new Dictionary(); - foreach (var pair in candidates) + foreach (KeyValuePair pair in candidates) { if (m_drafts[pair.Key].readOnly) + { throw new InvalidOperationException("The selection contains a read-only asset."); + } encoded.Add(pair.Key, m_sources.Encode(pair.Value)); } using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Edit " + m_label + " Selection"); - foreach (var pair in encoded) - RecordReplace(m_drafts[pair.Key], pair.Value, mergeKey); - transaction.Commit(); - } - - private void RecordReplace( - Draft draft, - byte[] next, - string? mergeKey = null - ) { - byte[] before = draft.bytes; - if (before.AsSpan().SequenceEqual(next)) - return; - var payload = new ChangeData + foreach (KeyValuePair pair in encoded) { - assetId = draft.id, - before = before, - after = next - }; - var change = new EditorHistoryChange(m_historyKind, EditorHistoryPayload.FromBytes(m_serialization.Serialize(payload)), mergeKey); - draft.bytes = next; - try - { - Changed(draft); - m_interactions.history.RecordApplied("Edit " + m_label, change); - } - catch - { - change.Dispose(); - draft.bytes = before; - Changed(draft); - throw; + RecordReplace(m_drafts[pair.Key], pair.Value, mergeKey); } + transaction.Commit(); } /// @@ -225,18 +215,26 @@ out EditorHistoryChange? merged ) { merged = null; if (older.kind != m_historyKind || newer.kind != m_historyKind || older.mergeKey is null || older.mergeKey != newer.mergeKey) + { return false; + } ChangeData first = m_serialization.Deserialize(older.payload.ReadBytes()); ChangeData last = m_serialization.Deserialize(newer.payload.ReadBytes()); if (first.assetId != last.assetId || !first.after.AsSpan().SequenceEqual(last.before)) + { return false; + } var combined = new ChangeData { assetId = first.assetId, before = first.before, after = last.after }; - merged = new EditorHistoryChange(m_historyKind, EditorHistoryPayload.FromBytes(m_serialization.Serialize(combined)), older.mergeKey); + merged = new EditorHistoryChange( + m_historyKind, + EditorHistoryPayload.FromBytes(m_serialization.Serialize(combined)), + older.mergeKey + ); return true; } @@ -255,7 +253,9 @@ EditorHistoryDirection direction ) { ChangeData data = m_serialization.Deserialize(change.payload.ReadBytes()); if (!m_drafts.ContainsKey(data.assetId)) + { throw new InvalidOperationException("Reopen the asset document to use its history."); + } } /// @@ -276,22 +276,132 @@ EditorHistoryDirection direction Changed(draft); } + /// + /// Registers the feature provider with the headless document ownership service. + /// + public void Start() + { + if (m_provider is not null) + { + throw new InvalidOperationException("This draft provider is already started."); + } + m_provider = m_interactions.documents.RegisterProvider(new Provider(this)); + } + + /// + /// Imports explicit saves and reconciles source changes without owning UI gesture lifetimes. + /// + public void Update() + { + foreach (AssetPath path in m_imports.ToArray()) + { + m_imports.Remove(path); + try + { + if (!m_assets.Import(path)) + { + string diagnostics = m_assets.TryGetInfo(path, out AssetInfo? info) + && info is not null + ? string.Join("\n", info.diagnostics) + : "The asset importer did not publish this asset."; + foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) + { + draft.error = "Saved; import failed: " + diagnostics; + } + } + } + catch (Exception error) when (Recoverable(error)) + { + foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) + { + draft.error = "Saved; import failed: " + error.Message; + } + } + } + + if (m_sourceRevision != m_assets.revision) + { + foreach (Draft draft in m_drafts.Values) + { + SynchronizeSource(draft); + } + m_sourceRevision = m_assets.revision; + } + } + + /// + /// Preserves unsaved recovery and unregisters the current feature provider. + /// + public void Dispose() + { + foreach (Draft draft in m_drafts.Values) + { + if (draft.isDirty) + { + Changed(draft); + } + } + + m_provider?.Dispose(); + m_provider = null; + } + + private void RecordReplace( + Draft draft, + byte[] next, + string? mergeKey = null + ) { + byte[] before = draft.bytes; + if (before.AsSpan().SequenceEqual(next)) + { + return; + } + var payload = new ChangeData + { + assetId = draft.id, + before = before, + after = next + }; + var change = new EditorHistoryChange( + m_historyKind, + EditorHistoryPayload.FromBytes(m_serialization.Serialize(payload)), + mergeKey + ); + draft.bytes = next; + try + { + Changed(draft); + m_interactions.history.RecordApplied("Edit " + m_label, change); + } + catch + { + change.Dispose(); + draft.bytes = before; + Changed(draft); + throw; + } + } + private (Draft, ChangeData) ResolveHistory( EditorHistoryChange change, EditorHistoryDirection direction ) { ChangeData data = m_serialization.Deserialize(change.payload.ReadBytes()); if (!m_drafts.TryGetValue(data.assetId, out Draft? draft)) + { throw new InvalidOperationException("Reopen the asset document to use its history."); + } byte[] expected = direction == EditorHistoryDirection.Undo ? data.after : data.before; if (!draft.bytes.AsSpan().SequenceEqual(expected)) + { throw new InvalidOperationException("The asset draft changed outside this history entry."); + } return (draft, data); } private void Changed(Draft draft) { - m_interactions.documents.SetDirty(draft.documentId, draft.isDirty); + m_interactions.documents.SetDirty(draft.documentID, draft.isDirty); try { if (!draft.isDirty) @@ -302,10 +412,14 @@ private void Changed(Draft draft) AtomicFile.WriteAllBytes( RecoveryPath(draft.id), - m_serialization.Serialize(new Recovery { assetId = draft.id, hash = draft.hash, baseline = draft.baseline, bytes = draft.bytes }) + m_serialization.Serialize( + new Recovery { assetId = draft.id, hash = draft.hash, baseline = draft.baseline, bytes = draft.bytes } + ) ); if (draft.error.StartsWith("Recovery write failed:", StringComparison.Ordinal)) - draft.error = ""; + { + draft.error = string.Empty; + } } catch (Exception error) when (Recoverable(error)) { @@ -320,7 +434,7 @@ private bool Save(Draft draft) RefreshPath(draft); draft.hash = m_sources.Save(draft.path, draft.bytes, draft.hash); draft.baseline = draft.bytes; - draft.error = ""; + draft.error = string.Empty; m_imports.Add(draft.path); DeleteRecovery(draft.id); return true; @@ -342,7 +456,7 @@ private bool Revert(Draft draft) draft.hash = source.contentHash; draft.baseline = draft.bytes; draft.readOnly = source.isReadOnly; - draft.error = ""; + draft.error = string.Empty; DeleteRecovery(draft.id); return true; } @@ -356,21 +470,31 @@ private bool Revert(Draft draft) private void RefreshPath(Draft draft) { if (!m_assets.TryGetInfo(draft.id, out AssetInfo? info) || info is null || info.status == AssetImportStatus.Missing) + { throw new IOException("Asset source is missing. Draft and history are retained."); + } draft.path = info.assetPath; - m_interactions.documents.UpdateAssetPath(draft.documentId, draft.path.ToString()); + m_interactions.documents.UpdateAssetPath(draft.documentID, draft.path.ToString()); } private void Open(EditorDocumentContext document) { - if (m_drafts.ContainsKey(document.assetId)) + if (m_drafts.ContainsKey(document.assetID)) + { return; + } AssetPath path = AssetPath.Parse(document.assetPath); - if (m_assets.TryGetInfo(document.assetId, out AssetInfo? info) && info is not null) + if (m_assets.TryGetInfo(document.assetID, out AssetInfo? info) && info is not null) + { path = info.assetPath; - Recovery? recovery = File.Exists(RecoveryPath(document.assetId)) ? m_serialization.Deserialize(File.ReadAllBytes(RecoveryPath(document.assetId))) : null; - if (recovery is not null && recovery.assetId != document.assetId) + } + Recovery? recovery = File.Exists(RecoveryPath(document.assetID)) + ? m_serialization.Deserialize(File.ReadAllBytes(RecoveryPath(document.assetID))) + : null; + if (recovery is not null && recovery.assetId != document.assetID) + { throw new InvalidDataException("Asset recovery identity does not match its document."); + } AssetSourceSnapshot? source = null; try { @@ -381,8 +505,8 @@ private void Open(EditorDocumentContext document) } var draft = new Draft( - document.assetId, - document.documentId, + document.assetID, + document.documentID, path, recovery?.bytes ?? source!.bytes, recovery?.baseline ?? source!.bytes, @@ -390,58 +514,13 @@ private void Open(EditorDocumentContext document) source?.isReadOnly ?? true ); if (recovery is not null && source?.contentHash != recovery.hash) + { draft.error = "Source changed externally. Recovery retained; resolve or Revert explicitly."; + } m_drafts.Add(draft.id, draft); if (draft.isDirty) - m_interactions.documents.SetDirty(draft.documentId); - } - - /// - /// Registers the feature provider with the headless document ownership service. - /// - public void Start() - { - if (m_provider is not null) - throw new InvalidOperationException("This draft provider is already started."); - m_provider = m_interactions.documents.RegisterProvider(new Provider(this)); - } - - /// - /// Imports explicit saves and reconciles source changes without owning UI gesture lifetimes. - /// - public void Update() - { - foreach (AssetPath path in m_imports.ToArray()) { - m_imports.Remove(path); - try - { - if (!m_assets.Import(path)) - { - string diagnostics = m_assets.TryGetInfo( - path, - out AssetInfo? info - ) - && info is not null ? string.Join( - "\n", - info.diagnostics - ) : "The asset importer did not publish this asset."; - foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) - draft.error = "Saved; import failed: " + diagnostics; - } - } - catch (Exception error) when (Recoverable(error)) - { - foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) - draft.error = "Saved; import failed: " + error.Message; - } - } - - if (m_sourceRevision != m_assets.revision) - { - foreach (Draft draft in m_drafts.Values) - SynchronizeSource(draft); - m_sourceRevision = m_assets.revision; + m_interactions.documents.SetDirty(draft.documentID); } } @@ -453,7 +532,9 @@ private void SynchronizeSource(Draft draft) AssetSourceSnapshot source = m_sources.Read(draft.path); draft.readOnly = source.isReadOnly; if (draft.hash == source.contentHash) + { return; + } if (draft.isDirty) { draft.error = "Source changed externally. Your draft is retained; Revert reloads it without overwriting the external edit."; @@ -463,7 +544,7 @@ private void SynchronizeSource(Draft draft) draft.bytes = source.bytes; draft.baseline = source.bytes; draft.hash = source.contentHash; - draft.error = ""; + draft.error = string.Empty; Changed(draft); } catch (Exception error) when (Recoverable(error)) @@ -472,37 +553,28 @@ private void SynchronizeSource(Draft draft) } } - /// - /// Preserves unsaved recovery and unregisters the current feature provider. - /// - public void Dispose() - { - foreach (Draft draft in m_drafts.Values) - { - if (draft.isDirty) - Changed(draft); - } + private string RecoveryPath(Guid id) + => Path.Combine(m_assets.libraryRoot, "Editor", "AssetDrafts", m_providerID, id.ToString("N") + ".inno"); - m_provider?.Dispose(); - m_provider = null; - } - - private string RecoveryPath(Guid id) => Path.Combine(m_assets.libraryRoot, "Editor", "AssetDrafts", m_providerId, id.ToString("N") + ".inno"); private void DeleteRecovery(Guid id) { string path = RecoveryPath(id); if (File.Exists(path)) + { File.Delete(path); + } } - private static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + private static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && RetirementPendingException.Find(error) is null; + private sealed class Provider(AssetDraftDocuments owner) : EditorDocumentProvider { /// /// Gets the stable identity used to reference this value across subsystem boundaries. /// - public override string id => owner.m_providerId; + public override string id => owner.m_providerID; /// /// Checks whether this document handler supports the selected asset. @@ -514,6 +586,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// when the documented condition is satisfied; otherwise, . /// public override bool CanOpen(string assetPath) => assetPath.EndsWith(owner.m_extension, StringComparison.OrdinalIgnoreCase); + /// /// Opens the requested resource and establishes its active lifetime. /// @@ -521,6 +594,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// The operation scope that provides state, services, and ownership boundaries. /// public override void Open(EditorDocumentContext context) => owner.Open(context); + /// /// Persists the supplied value through the configured storage contract. /// @@ -530,7 +604,8 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// /// when the documented condition is satisfied; otherwise, . /// - public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetId]); + public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetID]); + /// /// Restores the draft from the latest imported asset state. /// @@ -540,7 +615,8 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// /// when the documented condition is satisfied; otherwise, . /// - public override bool Revert(EditorDocumentContext context) => owner.Revert(owner.m_drafts[context.assetId]); + public override bool Revert(EditorDocumentContext context) => owner.Revert(owner.m_drafts[context.assetID]); + /// /// Closes the active resource and releases its operation-scoped state. /// @@ -549,8 +625,8 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// public override void Close(EditorDocumentContext context) { - owner.DeleteRecovery(context.assetId); - owner.m_drafts.Remove(context.assetId); + owner.DeleteRecovery(context.assetID); + owner.m_drafts.Remove(context.assetID); } } @@ -562,9 +638,10 @@ public sealed class Draft internal byte[] bytes; internal byte[] baseline; internal string hash; + internal Draft( Guid id, - Guid documentId, + Guid documentID, AssetPath path, byte[] bytes, byte[] baseline, @@ -572,7 +649,7 @@ internal Draft( bool readOnly ) { this.id = id; - this.documentId = documentId; + this.documentID = documentID; this.path = path; this.bytes = bytes; this.baseline = baseline; @@ -584,22 +661,27 @@ bool readOnly /// Gets the persistent source identity. /// public Guid id { get; } + /// /// Gets the shared document identity used for Save/Revert and close confirmation. /// - public Guid documentId { get; } + public Guid documentID { get; } + /// /// Gets the current resolved source path. /// public AssetPath path { get; internal set; } + /// /// Gets whether this source is installed read-only content. /// public bool readOnly { get; internal set; } + /// /// Gets the latest source, save or import diagnostic. /// - public string error { get; internal set; } = ""; + public string error { get; internal set; } = string.Empty; + /// /// Gets whether detached bytes differ from the saved baseline. /// @@ -612,7 +694,7 @@ private sealed class Recovery : ISerializable internal Guid assetId { get; set; } [SerializableProperty] - internal string hash { get; set; } = ""; + internal string hash { get; set; } = string.Empty; [SerializableProperty] internal byte[] baseline { get; set; } = []; diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs index a6f4895c8..cced46bd5 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs @@ -7,18 +7,14 @@ using Inno.Extensibility.Types; namespace Inno.Editor.Assets; + internal sealed class AssetCreationRegistry : TypeRegistry { - internal AssetCreationRegistry(TypeCatalog types) : base(types) - { - } + internal AssetCreationRegistry(TypeCatalog types) + : base(types) {} internal IReadOnlyList templates => current.registrations; - internal bool TryGet( - string id, - out Registration? registration - ) => current.byId.TryGetValue(id, out registration); /// /// Builds a validated result from the current immutable input snapshot. /// @@ -30,30 +26,40 @@ out Registration? registration /// protected override Snapshot Build(TypeCacheSnapshot types) { - var registrations = new List(); - var byId = new Dictionary(StringComparer.Ordinal); + List registrations = []; + var byID = new Dictionary(StringComparer.Ordinal); var byMenuPath = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (Type type in types.GetSubTypesOf().Select(typeRef => typeRef.Resolve(types)).Where(static type => !type.IsAbstract).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - )) - { - AssetCreationMenuAttribute declaration = type.GetCustomAttribute(false) ?? throw new InvalidOperationException($"Asset creation template '{type.FullName}' requires " + $"'{typeof(AssetCreationMenuAttribute).FullName}' source metadata."); + foreach (Type type in types + .GetSubTypesOf() + .Select(typeRef => typeRef.Resolve(types)) + .Where(static type => !type.IsAbstract) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { + AssetCreationMenuAttribute declaration = type.GetCustomAttribute(false) + ?? throw new InvalidOperationException( + $"Asset creation template '{type.FullName}' requires " + $"'{typeof(AssetCreationMenuAttribute).FullName}' source metadata." + ); AssetCreationTemplate template = CreateExtension(type); if (!typeof(AssetObject).IsAssignableFrom(template.assetType) || template.assetType.IsAbstract) { - throw new InvalidOperationException($"Asset creation template '{type.FullName}' declares invalid asset type " + $"'{template.assetType.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template '{type.FullName}' declares invalid asset type " + $"'{template.assetType.FullName}'." + ); } var registration = new Registration(type, template, declaration); - if (!byId.TryAdd(declaration.id, registration)) + if (!byID.TryAdd(declaration.id, registration)) { - throw new InvalidOperationException($"Asset creation template id '{declaration.id}' is registered by both " + $"'{byId[declaration.id].implementationType.FullName}' and '{type.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template id '{declaration.id}' is registered by both " + $"'{byID[declaration.id].implementationType.FullName}' and '{type.FullName}'." + ); } if (!byMenuPath.TryAdd(declaration.menuPath, registration)) { - throw new InvalidOperationException($"Asset creation menu path '{declaration.menuPath}' is registered by both " + $"'{byMenuPath[declaration.menuPath].implementationType.FullName}' and '{type.FullName}'."); + throw new InvalidOperationException( + $"Asset creation menu path '{declaration.menuPath}' is registered by both " + $"'{byMenuPath[declaration.menuPath].implementationType.FullName}' and '{type.FullName}'." + ); } registrations.Add(registration); @@ -66,7 +72,7 @@ protected override Snapshot Build(TypeCacheSnapshot types) static value => value.declaration.id, StringComparer.Ordinal ).ToArray(); - return new Snapshot(ordered, byId); + return new Snapshot(ordered, byID); } /// @@ -75,14 +81,22 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.registrations.Select(static value => value.template)); + protected override void DisposeSnapshot(Snapshot snapshot) + => DisposeExtensions(snapshot.registrations.Select(static value => value.template)); + + internal bool TryGet( + string id, + out Registration? registration + ) => current.byID.TryGetValue(id, out registration); + internal sealed record Registration( Type implementationType, AssetCreationTemplate template, AssetCreationMenuAttribute declaration ); + internal sealed record Snapshot( Registration[] registrations, - IReadOnlyDictionary byId + IReadOnlyDictionary byID ); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs index 7775c5406..355f4c061 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs @@ -7,6 +7,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Handles asset creation actions in the Editor file browser. /// @@ -26,9 +27,12 @@ public sealed partial class AssetEditingModule /// public AssetFileEntry CreateDirectory(AssetPath parent) { - AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == parent.source) ?? throw new InvalidOperationException("The asset source mount is unavailable."); + AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == parent.source) + ?? throw new InvalidOperationException("The asset source mount is unavailable."); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed asset sources are read-only."); + } string prefix = parent.localPath.Length == 0 ? string.Empty : parent.localPath + "/"; int suffix = 0; AssetPath candidate; @@ -40,8 +44,17 @@ public AssetFileEntry CreateDirectory(AssetPath parent) } while (m_pipeline.TryGetFileSystemEntry(candidate, out _)); m_pipeline.CreateDirectory(candidate); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateDirectory, candidate.ToString(), string.Empty, true, []); - using var change = new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateDirectory, + candidate.ToString(), + string.Empty, + true, + [] + ); + using var change = new EditorHistoryChange( + AssetHistoryKinds.C_SOURCE_OPERATION, + EditorHistoryPayload.FromBytes(data.Encode()) + ); try { m_interactions.history.RecordApplied("Create Folder", change); @@ -51,7 +64,9 @@ public AssetFileEntry CreateDirectory(AssetPath parent) RollbackAndRethrow(failure, () => m_pipeline.Delete(candidate)); } - return m_pipeline.TryGetFileSystemEntry(candidate, out AssetFileEntry entry) ? entry : throw new InvalidOperationException("The created directory was not indexed."); + return m_pipeline.TryGetFileSystemEntry(candidate, out AssetFileEntry entry) + ? entry + : throw new InvalidOperationException("The created directory was not indexed."); } /// @@ -76,21 +91,37 @@ public AssetFileEntry CreateSource( AssetPath path, ReadOnlySpan bytes ) { - AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == path.source) ?? throw new InvalidOperationException("The asset source mount is unavailable."); + AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == path.source) + ?? throw new InvalidOperationException("The asset source mount is unavailable."); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed asset sources are read-only."); + } string destination = mount.Resolve(path.localPath); if (!Directory.Exists(Path.GetDirectoryName(destination))) + { throw new IOException("The asset's parent directory does not exist."); + } if (File.Exists(destination + ".imeta")) + { throw new IOException("The new asset path already has an identity sidecar."); + } AtomicFile.WriteAllBytes(destination, bytes, overwrite: false); try { _ = m_pipeline.Import(path); byte[] archive = AssetSourceArchive.Capture(m_pipeline, path.ToString(), out bool isDirectory); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateAsset, path.ToString(), string.Empty, isDirectory, archive); - var change = new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateAsset, + path.ToString(), + string.Empty, + isDirectory, + archive + ); + var change = new EditorHistoryChange( + AssetHistoryKinds.C_SOURCE_OPERATION, + EditorHistoryPayload.FromBytes(data.Encode()) + ); try { m_interactions.history.RecordApplied("Create Asset", change); @@ -107,6 +138,8 @@ ReadOnlySpan bytes throw; } - return m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) ? entry : throw new InvalidOperationException("The created asset was not indexed."); + return m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) + ? entry + : throw new InvalidOperationException("The created asset was not indexed."); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs index 7b440e600..be1d1e825 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs @@ -7,6 +7,7 @@ using Inno.Scripting.Api; namespace Inno.Editor.Assets; + /// /// Applies validated selection operations through the authoritative asset and History owners. /// @@ -32,21 +33,23 @@ IReadOnlyList targets ArgumentNullException.ThrowIfNull(editor); ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return AssetOperationValidation.Invalid("The selection contains unavailable entries."); + } foreach (AssetFileEntry target in targets) { if (target.isReadOnly || target.identity.runtimeIdentity is null - || !TryCreateContext( - editor, - target.assetPath.ToString(), - out AssetEditorContext? context - ) - || context is null) + || !TryCreateContext(editor, target.assetPath.ToString(), out AssetEditorContext? context) + || context is null + ) { return AssetOperationValidation.Invalid("Every selected source must be available and writable."); + } AssetOperationValidation validation = m_editors.Resolve(context.assetType).ValidateDelete(context); if (!validation.isValid) + { return validation; + } } return AssetOperationValidation.valid; @@ -71,13 +74,19 @@ IReadOnlyList targets ) { AssetOperationValidation validation = ValidateDeleteSelection(editor, targets); if (!validation.isValid) + { throw new InvalidOperationException(validation.message); + } string[] roots = SelectedRoots(targets); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Delete Assets"); foreach (string path in roots) { - if (!TryCreateContext(editor, path, out AssetEditorContext? context) || context is null || !DeleteWithHistory(context, m_interactions.history)) + if (!TryCreateContext(editor, path, out AssetEditorContext? context) + || context is null + || !DeleteWithHistory(context, m_interactions.history) + ) { throw new InvalidOperationException($"Selected source '{path}' could not be deleted."); + } } transaction.Commit(); @@ -102,11 +111,17 @@ string targetDirectory ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0 || targets.Any(value => value.isReadOnly || value.identity.runtimeIdentity is null)) + { return false; + } var destinations = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string source in SelectedRoots(targets)) + { if (!TryPrepareMove(source, targetDirectory, true, out _, out _, out string destination) || !destinations.Add(destination)) + { return false; + } + } return true; } @@ -128,17 +143,23 @@ public void MoveSelection( string targetDirectory ) { if (!CanMoveSelection(targets, targetDirectory)) + { throw new InvalidOperationException("The selected assets cannot move to this directory."); + } string[] roots = SelectedRoots(targets); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Move Assets"); foreach (string source in roots) + { _ = MoveToDirectoryWithHistory(source, targetDirectory, m_interactions.history); + } transaction.Commit(); } private static string[] SelectedRoots(IReadOnlyList targets) { string[] paths = targets.Select(value => value.assetPath.ToString()).Distinct(StringComparer.Ordinal).ToArray(); - return paths.Where(path => !paths.Any(parent => parent != path && path.StartsWith(parent + "/", StringComparison.Ordinal))).ToArray(); + return paths + .Where(path => !paths.Any(parent => parent != path && path.StartsWith(parent + "/", StringComparison.Ordinal))) + .ToArray(); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs index 6f10882ca..cacd7d684 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs @@ -6,13 +6,15 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Editor.Core; using Inno.Editor.Assets; +using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Plugins.Authoring; +using Inno.Scripting.Api; namespace Inno.Editor.Assets; + /// /// Owns source mutations, asset extension dispatch and neutral shared-history records independently of presentation. /// @@ -26,6 +28,7 @@ public sealed partial class AssetEditingModule : EditorModule private readonly Logger m_log; private readonly PluginEnvironment m_plugins; private EditorContext? m_context; + /// /// Creates the asset editing service for one authoring generation. /// @@ -54,9 +57,12 @@ public AssetEditingModule( TypeCatalog types, LogRouter logs ) { - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - m_plugins = plugins ?? throw new ArgumentNullException(nameof(plugins)); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(pipeline); + ArgumentNullException.ThrowIfNull(plugins); + m_interactions = interactions; + m_pipeline = pipeline; + m_plugins = plugins; ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); @@ -67,18 +73,20 @@ LogRouter logs /// /// Gets the editor interaction owner used by source operations. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorInteractions interactions => m_interactions; /// /// Gets the authoritative authoring pipeline; mutations must use its existing ownership protocol. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetPipeline pipeline => m_pipeline; + /// /// Gets the current immutable creation menu declarations without retaining template instances. /// - public IReadOnlyList creationTemplates => m_creations.templates.Select(static registration => registration.declaration).ToArray(); + public IReadOnlyList creationTemplates + => m_creations.templates.Select(static registration => registration.declaration).ToArray(); /// /// Checks that a creation template and writable destination are available. @@ -86,22 +94,26 @@ LogRouter logs /// /// The source-relative writable destination directory. /// - /// + /// /// The stable identity of a discovered creation template. /// /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool CanCreateAsset( string directory, - string templateId + string templateID ) { - if (!m_pipeline.isInitialized || !m_creations.TryGet(templateId, out _)) + if (!m_pipeline.isInitialized || !m_creations.TryGet(templateID, out _)) + { return false; + } AssetPath path = AssetPath.Parse(directory); AssetSourceMount? mount = m_pipeline.sourceMounts.FirstOrDefault(source => source.id == path.source); - return mount is { isReadOnly: false } && (string.IsNullOrEmpty(path.localPath) || m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) && entry.isDirectory); + return mount is { isReadOnly: false } + && (string.IsNullOrEmpty(path.localPath) + || m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) && entry.isDirectory); } /// @@ -110,30 +122,34 @@ string templateId /// /// The source-relative writable destination directory. /// - /// + /// /// The stable identity of a discovered creation template. /// /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetFileEntry CreateAsset( string directory, - string templateId + string templateID ) { - if (!m_creations.TryGet(templateId, out AssetCreationRegistry.Registration? registration) || registration is null) + if (!m_creations.TryGet(templateID, out AssetCreationRegistry.Registration? registration) || registration is null) { - throw new InvalidOperationException($"Asset creation template '{templateId}' is unavailable."); + throw new InvalidOperationException($"Asset creation template '{templateID}' is unavailable."); } - if (!CanCreateAsset(directory, templateId)) + if (!CanCreateAsset(directory, templateID)) + { throw new InvalidOperationException("The selected Asset directory is not writable."); + } AssetCreationMenuAttribute declaration = registration.declaration; AssetPath parent = AssetPath.Parse(directory); AssetSourceMount mount = m_pipeline.sourceMounts.Single(source => source.id == parent.source); string prefix = parent.localPath.TrimEnd('/'); if (prefix.Length != 0) + { prefix += "/"; + } int suffix = 1; AssetPath path; do @@ -143,17 +159,20 @@ string templateId suffix++; } while (File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta")); - AssetObject candidate = registration.template.Create() ?? throw new InvalidOperationException($"Asset creation template '{templateId}' returned no asset."); + AssetObject candidate = registration.template.Create() + ?? throw new InvalidOperationException($"Asset creation template '{templateID}' returned no asset."); if (candidate.GetType() != registration.template.assetType) { - throw new InvalidOperationException($"Asset creation template '{templateId}' returned '{candidate.GetType().FullName}' " + $"instead of '{registration.template.assetType.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template '{templateID}' returned '{candidate.GetType().FullName}' " + $"instead of '{registration.template.assetType.FullName}'." + ); } AssetSourceStore sources = m_pipeline.CreateSourceStore(); byte[] source = registration.template.Encode( new AssetCreationContext(sources), candidate - ) ?? throw new InvalidOperationException($"Asset creation template '{templateId}' returned no source data."); + ) ?? throw new InvalidOperationException($"Asset creation template '{templateID}' returned no source data."); return CreateSource(path, source); } @@ -166,8 +185,9 @@ string templateId /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] - public bool IsPluginSource(AssetSourceId source) => m_plugins.TryGet(source, out _); + [ScriptingApiIgnore] + public bool IsPluginSource(AssetSourceID source) => m_plugins.TryGet(source, out _); + /// /// Determines whether an indexed entry is the root of an installed Plugin. /// @@ -177,7 +197,7 @@ string templateId /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool IsPluginRoot(AssetFileEntry entry) { ArgumentNullException.ThrowIfNull(entry); @@ -199,7 +219,7 @@ public bool IsPluginRoot(AssetFileEntry entry) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool TryCreateContext( EditorContext editor, string relativePath, @@ -213,7 +233,16 @@ out AssetEditorContext? context _ = m_pipeline.TryGetInfo(AssetPath.Parse(relativePath), out AssetInfo? info); _ = m_pipeline.TryGetAssetType(AssetPath.Parse(relativePath), out Type? assetType); - context = new AssetEditorContext(editor, m_interactions, entry.assetPath.ToString(), entry.name, entry.isDirectory, info, assetType, () => CreateDefaultDragData(entry)); + context = new AssetEditorContext( + editor, + m_interactions, + entry.assetPath.ToString(), + entry.name, + entry.isDirectory, + info, + assetType, + () => CreateDefaultDragData(entry) + ); return true; } @@ -226,12 +255,14 @@ out AssetEditorContext? context /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool Open(AssetEditorContext context) { AssetEditor editor = m_editors.Resolve(context.assetType); if (!editor.CanOpen(context)) + { return false; + } try { editor.Open(context); @@ -256,7 +287,7 @@ public bool Open(AssetEditorContext context) /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorValidationResult ValidateRename( AssetEditorContext context, string newName @@ -274,23 +305,43 @@ string newName /// /// The requested entry name without its protected file extension. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void Rename( AssetEditorContext context, string newName ) { AssetEditor editor = m_editors.Resolve(context.assetType); - AssetOperationValidation validation = ValidateRename(editor, context, Normalize(context.relativePath), newName, validateEditor: false, out string targetPath); + AssetOperationValidation validation = ValidateRename( + editor, + context, + Normalize(context.relativePath), + newName, + validateEditor: false, + out string targetPath + ); if (!validation.isValid) + { throw new InvalidOperationException(validation.message); + } string sourcePath = Normalize(context.relativePath); EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); - var data = new AssetHistoryData(AssetHistoryOperationKind.Move, sourcePath, targetPath, isDirectory: context.isDirectory, archive: []); + } + var data = new AssetHistoryData( + AssetHistoryOperationKind.Move, + sourcePath, + targetPath, + isDirectory: context.isDirectory, + archive: [] + ); try { - m_interactions.history.RecordApplied("Rename Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + m_interactions.history.RecordApplied( + "Rename Asset", + new EditorHistoryChange(AssetHistoryKinds.C_SOURCE_OPERATION, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { @@ -310,11 +361,12 @@ string newName /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool CanMoveToDirectory( string sourcePath, string targetDirectory ) => TryPrepareMove(sourcePath, targetDirectory, validateEditor: true, out _, out _, out _); + /// /// Moves a source and records the committed mutation in the supplied history. /// @@ -330,7 +382,7 @@ string targetDirectory /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetFileEntry MoveToDirectoryWithHistory( string sourcePath, string targetDirectory, @@ -346,19 +398,30 @@ IEditorHistory history out string targetPath ) || context is null - || editor is null) - { + || editor is null + ) { throw new InvalidOperationException($"Asset '{sourcePath}' cannot be moved to '{targetDirectory}'."); } string normalizedSource = Normalize(sourcePath); EditorHistoryResult result = MoveAsset(editor, context, normalizedSource, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); - var data = new AssetHistoryData(AssetHistoryOperationKind.Move, normalizedSource, targetPath, context.isDirectory, archive: []); + } + var data = new AssetHistoryData( + AssetHistoryOperationKind.Move, + normalizedSource, + targetPath, + context.isDirectory, + archive: [] + ); try { - history.RecordApplied("Move Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + history.RecordApplied( + "Move Asset", + new EditorHistoryChange(AssetHistoryKinds.C_SOURCE_OPERATION, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { @@ -371,30 +434,6 @@ out AssetFileEntry moved ) ? moved : throw new InvalidOperationException($"Moved asset '{targetPath}' is unavailable after the transaction."); } - internal bool Delete(AssetEditorContext context) - { - AssetEditor editor = m_editors.Resolve(context.assetType); - AssetOperationValidation validation = editor.ValidateDelete(context); - if (!validation.isValid) - { - m_log.Write(LogLevel.Warn, "Asset delete was rejected for '{0}': {1}", [context.relativePath, validation.message]); - return false; - } - - string path = context.relativePath; - m_pipeline.Delete(AssetPath.Parse(path)); - try - { - editor.OnDeleted(context); - } - catch (Exception exception) - { - m_log.Write(LogLevel.Error, "Asset editor delete hook failed for '{0}': {1}", [path, exception]); - } - - return true; - } - /// /// Deletes a source with a recoverable archive and records the committed mutation. /// @@ -407,7 +446,7 @@ internal bool Delete(AssetEditorContext context) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool DeleteWithHistory( AssetEditorContext asset, IEditorHistory history @@ -416,49 +455,41 @@ IEditorHistory history ArgumentNullException.ThrowIfNull(asset); byte[] archive = AssetSourceArchive.Capture(m_pipeline, asset.relativePath, out bool isDirectory); if (!Delete(asset)) + { return false; - var data = new AssetHistoryData(AssetHistoryOperationKind.Delete, Normalize(asset.relativePath), string.Empty, isDirectory, archive); + } + var data = new AssetHistoryData( + AssetHistoryOperationKind.Delete, + Normalize(asset.relativePath), + string.Empty, + isDirectory, + archive + ); try { - history.RecordApplied("Delete Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + history.RecordApplied( + "Delete Asset", + new EditorHistoryChange(AssetHistoryKinds.C_SOURCE_OPERATION, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { - RollbackAndRethrow(exception, () => AssetSourceArchive.Restore(m_pipeline, Normalize(asset.relativePath), isDirectory, archive)); + RollbackAndRethrow( + exception, + () => AssetSourceArchive.Restore(m_pipeline, Normalize(asset.relativePath), isDirectory, archive) + ); } return true; } - internal void MoveFromHistory( - string sourcePath, - string targetPath - ) { - EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); - if (!TryCreateContext(editorContext, sourcePath, out AssetEditorContext? context) || context is null) - throw new InvalidOperationException($"Asset '{sourcePath}' is no longer available."); - AssetEditor editor = m_editors.Resolve(context.assetType); - EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); - if (!result.succeeded) - throw new InvalidOperationException(result.message); - } - - internal void DeleteFromHistory(string relativePath) - { - EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); - if (!TryCreateContext(editorContext, relativePath, out AssetEditorContext? context) || context is null) - throw new InvalidOperationException($"Asset '{relativePath}' is no longer available."); - if (!Delete(context)) - throw new InvalidOperationException($"Asset '{relativePath}' could not be deleted."); - } - /// /// Selects the current source identity without retaining an indexed entry across generations. /// /// /// The isolated source-relative path to resolve. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void SelectPath(string relativePath) { object? target = m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry) ? entry : null; @@ -477,7 +508,7 @@ public void SelectPath(string relativePath) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool TryCreateDragData( AssetEditorContext context, out EditorDragData? data @@ -499,10 +530,7 @@ out EditorDragData? data /// /// The context that supplies state and services for this operation. /// - protected override void OnStart(EditorContext context) - { - m_context = context ?? throw new ArgumentNullException(nameof(context)); - } + protected override void OnStart(EditorContext context) => m_context = context ?? throw new ArgumentNullException(nameof(context)); /// /// Stops this feature before its owning runtime releases the active generation. @@ -510,10 +538,7 @@ protected override void OnStart(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnStop(EditorContext context) - { - m_context = null; - } + protected override void OnStop(EditorContext context) => m_context = null; /// /// Releases resources retained by this feature after it has stopped. @@ -524,6 +549,60 @@ protected override void OnDispose() m_editors.Dispose(); } + internal bool Delete(AssetEditorContext context) + { + AssetEditor editor = m_editors.Resolve(context.assetType); + AssetOperationValidation validation = editor.ValidateDelete(context); + if (!validation.isValid) + { + m_log.Write(LogLevel.Warn, "Asset delete was rejected for '{0}': {1}", [context.relativePath, validation.message]); + return false; + } + + string path = context.relativePath; + m_pipeline.Delete(AssetPath.Parse(path)); + try + { + editor.OnDeleted(context); + } + catch (Exception exception) + { + m_log.Write(LogLevel.Error, "Asset editor delete hook failed for '{0}': {1}", [path, exception]); + } + + return true; + } + + internal void MoveFromHistory( + string sourcePath, + string targetPath + ) { + EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); + if (!TryCreateContext(editorContext, sourcePath, out AssetEditorContext? context) || context is null) + { + throw new InvalidOperationException($"Asset '{sourcePath}' is no longer available."); + } + AssetEditor editor = m_editors.Resolve(context.assetType); + EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); + if (!result.succeeded) + { + throw new InvalidOperationException(result.message); + } + } + + internal void DeleteFromHistory(string relativePath) + { + EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); + if (!TryCreateContext(editorContext, relativePath, out AssetEditorContext? context) || context is null) + { + throw new InvalidOperationException($"Asset '{relativePath}' is no longer available."); + } + if (!Delete(context)) + { + throw new InvalidOperationException($"Asset '{relativePath}' could not be deleted."); + } + } + private AssetOperationValidation ValidateRename( AssetEditor editor, AssetEditorContext context, @@ -535,7 +614,9 @@ out string targetPath newName = newName.Trim(); targetPath = string.Empty; if (string.IsNullOrEmpty(newName)) + { return AssetOperationValidation.Invalid("An asset name is required."); + } if (newName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || newName.Contains('/') || newName.Contains('\\')) { return AssetOperationValidation.Invalid("Asset names cannot contain path separators or invalid file-name characters."); @@ -544,8 +625,9 @@ out string targetPath string renamedEntry = context.isDirectory ? newName : newName + Path.GetExtension(sourcePath); string parent = Normalize(Path.GetDirectoryName(sourcePath)); targetPath = string.IsNullOrEmpty(parent) ? renamedEntry : $"{parent}/{renamedEntry}"; - if (!string.Equals(sourcePath, targetPath, StringComparison.OrdinalIgnoreCase) && m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) - { + if (!string.Equals(sourcePath, targetPath, StringComparison.OrdinalIgnoreCase) + && m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _) + ) { return AssetOperationValidation.Invalid($"Asset '{targetPath}' already exists."); } @@ -567,34 +649,44 @@ out string targetPath string directory = Normalize(targetDirectory); AssetPath isolatedSource = AssetPath.Parse(source); AssetPath isolatedDirectory = AssetPath.Parse(directory); - if (isolatedSource.source != AssetSourceId.project || isolatedDirectory.source != AssetSourceId.project) + if (isolatedSource.source != AssetSourceID.project || isolatedDirectory.source != AssetSourceID.project) { return false; } EditorContext? editorContext = m_context; - if (editorContext is null || string.IsNullOrEmpty(source) || !TryCreateContext(editorContext, source, out context) || context is null) - { + if (editorContext is null + || string.IsNullOrEmpty(source) + || !TryCreateContext(editorContext, source, out context) + || context is null + ) { return false; } - if (!string.IsNullOrEmpty(directory) && (!m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(directory), out AssetFileEntry destination) || !destination.isDirectory)) - { + if (!string.IsNullOrEmpty(directory) + && (!m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(directory), out AssetFileEntry destination) || !destination.isDirectory) + ) { return false; } string parent = Normalize(Path.GetDirectoryName(source)); if (string.Equals(parent, directory, StringComparison.OrdinalIgnoreCase)) - return false; - if (context.isDirectory && (string.Equals(source, directory, StringComparison.OrdinalIgnoreCase) || directory.StartsWith(source + "/", StringComparison.OrdinalIgnoreCase))) { return false; } + if (context.isDirectory + && (string.Equals(source, directory, StringComparison.OrdinalIgnoreCase) + || directory.StartsWith(source + "/", StringComparison.OrdinalIgnoreCase)) + ) { + return false; + } string name = Path.GetFileName(source); targetPath = string.IsNullOrEmpty(directory) ? name : $"{directory}/{name}"; if (m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) + { return false; + } editor = m_editors.Resolve(context.assetType); return !validateEditor || editor.ValidateRename(context, targetPath).isValid; } @@ -626,7 +718,9 @@ string targetPath ) { EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } } private static void RollbackAndRethrow( @@ -639,13 +733,20 @@ Action rollback } catch (Exception rollbackException) { - throw new AggregateException("An Asset mutation could not be recorded and its compensation also failed.", failure, rollbackException); + throw new AggregateException( + "An Asset mutation could not be recorded and its compensation also failed.", + failure, + rollbackException + ); } ExceptionDispatchInfo.Capture(failure).Throw(); } - private static EditorValidationResult ToEditorValidation(AssetOperationValidation validation) => new(validation.isValid, validation.message); + private static EditorValidationResult ToEditorValidation(AssetOperationValidation validation) + => new(validation.isValid, validation.message); + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); + private static EditorDragData CreateDefaultDragData(AssetFileEntry entry) => new(entry, entry.name); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs index 97199c762..a2a47b16a 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs @@ -1,6 +1,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Customizes editor interactions for one imported asset type. /// @@ -16,15 +17,14 @@ public abstract class AssetEditor /// when can handle the entry; otherwise, . /// public virtual bool CanOpen(AssetEditorContext context) => false; + /// /// Opens the supplied asset entry when no more specific typed open action handled it. /// /// /// The immutable source and catalog snapshot for the operation. /// - public virtual void Open(AssetEditorContext context) - { - } + public virtual void Open(AssetEditorContext context) {} /// /// Validates a requested asset move before the AssetPipeline transaction begins. @@ -42,6 +42,7 @@ public virtual AssetOperationValidation ValidateRename( AssetEditorContext context, string targetPath ) => AssetOperationValidation.valid; + /// /// Runs after an asset move transaction commits successfully. /// @@ -58,8 +59,7 @@ public virtual void OnRenamed( AssetEditorContext context, string oldPath, string newPath - ) { - } + ) {} /// /// Validates a requested asset deletion before the AssetPipeline transaction begins. @@ -71,15 +71,14 @@ string newPath /// A valid result when the transaction may proceed, or a diagnostic describing the rejection. /// public virtual AssetOperationValidation ValidateDelete(AssetEditorContext context) => AssetOperationValidation.valid; + /// /// Runs after an asset deletion transaction commits successfully. /// /// /// The immutable snapshot captured before the entry was deleted. /// - public virtual void OnDeleted(AssetEditorContext context) - { - } + public virtual void OnDeleted(AssetEditorContext context) {} /// /// Gets whether the supplied entry can begin a managed editor drag operation. @@ -91,6 +90,7 @@ public virtual void OnDeleted(AssetEditorContext context) /// when drag data can be created; otherwise, . /// public virtual bool CanStartDrag(AssetEditorContext context) => true; + /// /// Creates the managed source, preview label, and validity predicate for an asset drag. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs index c770bfcf0..2f035024f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Assets; + /// /// Associates an asset editor with an imported asset type. /// @@ -27,7 +28,8 @@ public AssetEditorAttribute( bool useForChildren = false, int priority = 0 ) { - this.assetType = assetType ?? throw new ArgumentNullException(nameof(assetType)); + ArgumentNullException.ThrowIfNull(assetType); + this.assetType = assetType; this.useForChildren = useForChildren; this.priority = priority; } @@ -36,10 +38,12 @@ public AssetEditorAttribute( /// Gets the imported asset type handled by the editor. /// public Type assetType { get; } + /// /// Gets whether derived asset types are accepted. /// public bool useForChildren { get; } + /// /// Gets the tie-breaking priority. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs index 4d5c0fc25..8e375c440 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs @@ -4,12 +4,14 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Provides an immutable snapshot for an asset editor operation. /// public sealed class AssetEditorContext { private readonly Func m_createDefaultDragData; + /// /// Creates an immutable snapshot used by one asset-editor operation. /// @@ -50,40 +52,51 @@ internal AssetEditorContext( Type? assetType, Func createDefaultDragData ) { - this.editorContext = editorContext ?? throw new ArgumentNullException(nameof(editorContext)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - this.relativePath = relativePath ?? throw new ArgumentNullException(nameof(relativePath)); - this.name = name ?? throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(editorContext); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(relativePath); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(createDefaultDragData); + this.editorContext = editorContext; + this.interactions = interactions; + this.relativePath = relativePath; + this.name = name; this.isDirectory = isDirectory; this.info = info; this.assetType = assetType; - m_createDefaultDragData = createDefaultDragData ?? throw new ArgumentNullException(nameof(createDefaultDragData)); + m_createDefaultDragData = createDefaultDragData; } /// /// Gets the shared editor context. /// public EditorContext editorContext { get; } + /// /// Gets the active editor interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the source-relative path. /// public string relativePath { get; } + /// /// Gets the final source path segment. /// public string name { get; } + /// /// Gets whether the source represents a directory. /// public bool isDirectory { get; } + /// /// Gets the cataloged asset information when available. /// public AssetInfo? info { get; } + /// /// Gets the resolved imported asset type when available. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs index 36398d252..253383dfd 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs @@ -1,39 +1,18 @@ -using Inno.Editor.Core; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using Inno.Editor.Core; using Inno.Extensibility.Types; namespace Inno.Editor.Assets; + internal sealed class AssetEditorRegistry : TypeRegistry { - private static readonly AssetEditor S_DEFAULT_EDITOR = new DefaultAssetEditor(); - internal AssetEditorRegistry(TypeCatalog types) : base(types) - { - } + private static readonly AssetEditor DEFAULT_EDITOR = new DefaultAssetEditor(); - internal AssetEditor Resolve(Type? assetType) - { - if (assetType is null) - return S_DEFAULT_EDITOR; - Registration? best = null; - int bestDistance = int.MaxValue; - foreach (Registration registration in current.registrations) - { - if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance)) - continue; - if (distance > 0 && !registration.useForChildren) - continue; - if (best is null || distance < bestDistance || distance == bestDistance && registration.priority > best.priority) - { - best = registration; - bestDistance = distance; - } - } - - return best?.editor ?? S_DEFAULT_EDITOR; - } + internal AssetEditorRegistry(TypeCatalog types) + : base(types) {} /// /// Builds a validated result from the current immutable input snapshot. @@ -47,19 +26,25 @@ internal AssetEditor Resolve(Type? assetType) protected override Snapshot Build(TypeCacheSnapshot types) { var instances = new Dictionary(); - var registrations = new List(); + List registrations = []; foreach (Type type in types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( static value => value.FullName, StringComparer.Ordinal - )) - { + )) { AssetEditor editor = instances.TryGetValue(type, out AssetEditor? existing) ? existing : CreateExtension(type); instances[type] = editor; foreach (AssetEditorAttribute attribute in type.GetCustomAttributes(false)) { - if (registrations.Any(value => value.assetType == attribute.assetType && value.useForChildren == attribute.useForChildren && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset editor registration for '{attribute.assetType.FullName}' conflicts at " + $"priority {attribute.priority}."); + if (registrations.Any( + value => ( + value.assetType == attribute.assetType + && value.useForChildren == attribute.useForChildren + && value.priority == attribute.priority + ) + )) { + throw new InvalidOperationException( + $"Asset editor registration for '{attribute.assetType.FullName}' conflicts at " + $"priority {attribute.priority}." + ); } registrations.Add(new Registration(attribute.assetType, attribute.useForChildren, attribute.priority, type, editor)); @@ -75,8 +60,39 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.registrations.Select(static registration => registration.editor)); + protected override void DisposeSnapshot(Snapshot snapshot) + => DisposeExtensions(snapshot.registrations.Select(static registration => registration.editor)); + + internal AssetEditor Resolve(Type? assetType) + { + if (assetType is null) + { + return DEFAULT_EDITOR; + } + Registration? best = null; + int bestDistance = int.MaxValue; + foreach (Registration registration in current.registrations) + { + if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance)) + { + continue; + } + if (distance > 0 && !registration.useForChildren) + { + continue; + } + if (best is null || distance < bestDistance || distance == bestDistance && registration.priority > best.priority) + { + best = registration; + bestDistance = distance; + } + } + + return best?.editor ?? DEFAULT_EDITOR; + } + internal sealed record Snapshot(Registration[] registrations); + internal sealed record Registration( Type assetType, bool useForChildren, @@ -84,5 +100,6 @@ internal sealed record Registration( Type implementationType, AssetEditor editor ); + private sealed class DefaultAssetEditor : AssetEditor; } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs index 7715e2c0c..33f41081f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Assets; + /// /// Describes whether an editor asset operation may proceed. /// @@ -25,10 +26,12 @@ string message /// Gets whether the operation may proceed. /// public bool isValid { get; } + /// /// Gets the validation diagnostic. /// public string message { get; } + /// /// Gets a successful validation result. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs index 7142d0fb5..1576b0eb9 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs @@ -3,14 +3,14 @@ using System.Text; namespace Inno.Editor.Assets; + internal sealed record AssetHistoryData( AssetHistoryOperationKind operationKind, string sourcePath, string targetPath, bool isDirectory, byte[] archive -) -{ +) { internal byte[] Encode() { using var stream = new MemoryStream(); @@ -29,20 +29,28 @@ internal static AssetHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - var kind = (AssetHistoryOperationKind)reader.ReadByte(); + AssetHistoryOperationKind kind = (AssetHistoryOperationKind)reader.ReadByte(); if (!Enum.IsDefined(kind)) + { throw new InvalidDataException($"Unknown asset history operation kind '{kind}'."); + } string sourcePath = reader.ReadString(); string targetPath = reader.ReadString(); bool isDirectory = reader.ReadBoolean(); int archiveLength = reader.ReadInt32(); if (archiveLength < 0 || archiveLength > stream.Length - stream.Position) + { throw new InvalidDataException("Asset history archive length is invalid."); + } byte[] archive = reader.ReadBytes(archiveLength); if (archive.Length != archiveLength) + { throw new EndOfStreamException("Asset history archive is truncated."); + } if (stream.Position != stream.Length) + { throw new InvalidDataException("Asset history payload contains trailing data."); + } return new AssetHistoryData(kind, sourcePath, targetPath, isDirectory, archive); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs index ee2638df3..8f129cbd9 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs @@ -4,13 +4,15 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; -[EditorHistoryHandler(AssetHistoryKinds.SourceOperation)] + +[EditorHistoryHandler(AssetHistoryKinds.C_SOURCE_OPERATION)] internal sealed class AssetHistoryHandler( AssetEditingModule assets, LogRouter logs ) : EditorHistoryHandler { private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -40,7 +42,8 @@ EditorHistoryDirection direction AssetHistoryOperationKind.CreateDirectory => QueryCreateDirectory(data, direction), AssetHistoryOperationKind.Delete => QueryDelete(data, direction), AssetHistoryOperationKind.CreateAsset => QueryCreateAsset(data, direction), - _ => EditorHistoryAvailability.Unavailable("Unknown asset history operation.")}; + _ => EditorHistoryAvailability.Unavailable("Unknown asset history operation.") + }; } catch (Exception exception) { @@ -95,7 +98,9 @@ EditorHistoryDirection direction } if (!result.succeeded) + { return result; + } try { assets.SelectPath(selectionPath); @@ -124,15 +129,18 @@ string targetPath } catch (Exception exception) { - if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(sourcePath), out _) && assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) - { + if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(sourcePath), out _) + && assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _) + ) { try { assets.MoveFromHistory(targetPath, sourcePath); } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset move failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset move failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } } @@ -148,12 +156,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { assets.pipeline.CreateDirectory(AssetPath.Parse(data.sourcePath)); + } else + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The folder operation did not reach its requested state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -162,13 +176,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } else if (!shouldExist && !exists) + { assets.pipeline.CreateDirectory(AssetPath.Parse(data.sourcePath)); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset folder operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset folder operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -183,12 +203,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } else + { assets.DeleteFromHistory(data.sourcePath); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The Asset delete operation did not reach its requested state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -197,13 +223,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } else if (!shouldExist && !exists) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset delete operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset delete operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -218,12 +250,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } else + { assets.DeleteFromHistory(data.sourcePath); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The created Asset did not reach its requested history state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -232,13 +270,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.DeleteFromHistory(data.sourcePath); + } else if (!shouldExist && !exists) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset creation history failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset creation history failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -252,7 +296,9 @@ EditorHistoryDirection direction string source = direction == EditorHistoryDirection.Undo ? data.targetPath : data.sourcePath; string target = direction == EditorHistoryDirection.Undo ? data.sourcePath : data.targetPath; if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(source), out _)) + { return EditorHistoryAvailability.Unavailable($"Asset '{source}' no longer exists."); + } return !assets.pipeline.TryGetFileSystemEntry( AssetPath.Parse(target), out _ @@ -262,31 +308,39 @@ out _ private EditorHistoryAvailability QueryCreateDirectory( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' no longer exists.") : !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' already exists."); + ) => direction == EditorHistoryDirection.Undo + ? assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' no longer exists.") + : !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' already exists."); + private EditorHistoryAvailability QueryDelete( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists.") : assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists."); + ) => direction == EditorHistoryDirection.Undo + ? !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists.") + : assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists."); + private EditorHistoryAvailability QueryCreateAsset( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists.") : !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists."); + ) => direction == EditorHistoryDirection.Undo + ? assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists.") + : !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists."); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs index 645f029df..407d23bd9 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs @@ -1,5 +1,6 @@ namespace Inno.Editor.Assets; + internal static class AssetHistoryKinds { - internal const string SourceOperation = "inno.assets/source-operation"; + internal const string C_SOURCE_OPERATION = "inno.assets/source-operation"; } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs index a9a478a7e..57f3ae119 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Assets; + internal enum AssetHistoryOperationKind : byte { Move = 1, diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs index ea5a253ae..243ed164b 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs @@ -6,10 +6,12 @@ using Inno.Assets.Pipeline; namespace Inno.Editor.Assets; + internal static class AssetSourceArchive { private const string C_SOURCE_ENTRY = "source"; private const string C_META_ENTRY = "source.imeta"; + internal static byte[] Capture( AssetPipeline assets, string relativePath, @@ -19,7 +21,9 @@ out bool isDirectory string source = GetSourcePath(assets, relativePath); isDirectory = Directory.Exists(source); if (!isDirectory && !File.Exists(source)) + { throw new FileNotFoundException($"Asset source '{relativePath}' does not exist.", source); + } return CapturePhysical(source, isDirectory, CancellationToken.None); } @@ -58,31 +62,14 @@ CancellationToken cancellationToken string meta = source + ".imeta"; if (File.Exists(meta)) + { WriteEntry(archive, meta, C_META_ENTRY, cancellationToken); + } } return stream.ToArray(); } - private static void WriteEntry( - ZipArchive archive, - string source, - string entryName, - CancellationToken cancellationToken - ) { - cancellationToken.ThrowIfCancellationRequested(); - ZipArchiveEntry entry = archive.CreateEntry(entryName, CompressionLevel.Fastest); - using Stream output = entry.Open(); - using FileStream input = File.OpenRead(source); - byte[] buffer = new byte[81920]; - int count; - while ((count = input.Read(buffer)) != 0) - { - cancellationToken.ThrowIfCancellationRequested(); - output.Write(buffer, 0, count); - } - } - internal static void Restore( AssetPipeline assets, string relativePath, @@ -92,10 +79,14 @@ ReadOnlySpan data ArgumentNullException.ThrowIfNull(assets); string target = GetSourcePath(assets, relativePath); if (File.Exists(target) || Directory.Exists(target)) + { throw new IOException($"Asset source '{relativePath}' already exists."); + } string? parent = Path.GetDirectoryName(target); if (!string.IsNullOrEmpty(parent)) + { Directory.CreateDirectory(parent); + } string stagingDirectory = Path.Combine(Path.GetTempPath(), "InnoAssetHistory", Guid.NewGuid().ToString("N")); string stagingSource = Path.Combine(stagingDirectory, C_SOURCE_ENTRY); string stagingMeta = Path.Combine(stagingDirectory, C_META_ENTRY); @@ -114,7 +105,9 @@ ReadOnlySpan data string destination = ResolveDestination(stagingSource, stagingMeta, isDirectory, entry.FullName); string fullDestination = Path.GetFullPath(destination); if (!fullDestination.StartsWith(stagingRoot, StringComparison.Ordinal)) + { throw new InvalidDataException("Asset history archive escapes its staging directory."); + } if (entry.FullName.EndsWith("/", StringComparison.Ordinal)) { Directory.CreateDirectory(fullDestination); @@ -123,13 +116,17 @@ ReadOnlySpan data string? destinationParent = Path.GetDirectoryName(fullDestination); if (!string.IsNullOrEmpty(destinationParent)) + { Directory.CreateDirectory(destinationParent); + } entry.ExtractToFile(fullDestination, overwrite: false); } } if (isDirectory ? !Directory.Exists(stagingSource) : !File.Exists(stagingSource)) + { throw new InvalidDataException("Asset history archive does not contain its source payload."); + } MoveSource(stagingSource, target, isDirectory); sourceCommitted = true; if (File.Exists(stagingMeta)) @@ -144,9 +141,13 @@ ReadOnlySpan data catch { if (metaCommitted && File.Exists(target + ".imeta")) + { File.Move(target + ".imeta", stagingMeta); + } if (sourceCommitted && (isDirectory ? Directory.Exists(target) : File.Exists(target))) + { MoveSource(target, stagingSource, isDirectory); + } if (sourceCommitted) { try @@ -154,8 +155,9 @@ ReadOnlySpan data assets.Rescan(); assets.WaitForIdle(); } - catch + catch (Exception) { + // The original failure is rethrown below. A failed rescan must not replace it. } } @@ -164,7 +166,28 @@ ReadOnlySpan data finally { if (Directory.Exists(stagingDirectory)) + { Directory.Delete(stagingDirectory, recursive: true); + } + } + } + + private static void WriteEntry( + ZipArchive archive, + string source, + string entryName, + CancellationToken cancellationToken + ) { + cancellationToken.ThrowIfCancellationRequested(); + ZipArchiveEntry entry = archive.CreateEntry(entryName, CompressionLevel.Fastest); + using Stream output = entry.Open(); + using FileStream input = File.OpenRead(source); + var buffer = new byte[81_920]; + int count; + while ((count = input.Read(buffer)) != 0) + { + cancellationToken.ThrowIfCancellationRequested(); + output.Write(buffer, 0, count); } } @@ -175,9 +198,13 @@ private static string ResolveDestination( string entryName ) { if (string.Equals(entryName, C_META_ENTRY, StringComparison.Ordinal)) + { return stagingMeta; + } if (!isDirectory && string.Equals(entryName, C_SOURCE_ENTRY, StringComparison.Ordinal)) + { return stagingSource; + } string prefix = C_SOURCE_ENTRY + "/"; if (isDirectory && entryName.StartsWith(prefix, StringComparison.Ordinal)) { @@ -194,7 +221,9 @@ string relativePath string root = Path.GetFullPath(assets.assetRoot) + Path.DirectorySeparatorChar; string result = Path.GetFullPath(Path.Combine(assets.assetRoot, relativePath.Replace('/', Path.DirectorySeparatorChar))); if (!result.StartsWith(root, StringComparison.Ordinal)) + { throw new InvalidDataException($"Asset history path '{relativePath}' escapes the asset root."); + } return result; } @@ -204,8 +233,12 @@ private static void MoveSource( bool isDirectory ) { if (isDirectory) + { Directory.Move(source, target); + } else + { File.Move(source, target); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs index 28e73c575..24185c17f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs @@ -2,12 +2,15 @@ using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Editor.Assets; + /// /// Applies importer configuration through the common sidecar pipeline and stable-identity Editor history. /// @@ -19,6 +22,7 @@ public sealed partial class AssetImportSettingsEdits : EditorModule private readonly SerializationRegistry m_serialization; private readonly TypeCatalog m_types; private readonly EditorInteractions m_interactions; + /// /// Uses the authoring owners responsible for source identity, converter generations and shared undo. /// @@ -34,17 +38,21 @@ public sealed partial class AssetImportSettingsEdits : EditorModule /// /// Shared Editor history owner. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetImportSettingsEdits( AssetPipeline assets, SerializationRegistry serialization, TypeCatalog types, EditorInteractions interactions ) { - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(interactions); + m_assets = assets; + m_serialization = serialization; + m_types = types; + m_interactions = interactions; } /// @@ -70,27 +78,35 @@ string expectedFingerprint ArgumentNullException.ThrowIfNull(settings); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); if (before.fingerprint != expectedFingerprint) + { throw new IOException("Import settings changed externally. Reload before applying."); + } if (before.value is null || before.value.GetType() != settings.GetType()) + { throw new InvalidOperationException("The importer settings type changed. Reload the editor."); - if (!m_assets.TryGetPersistentId(path, out Guid id)) + } + if (!m_assets.TryGetPersistentID(path, out Guid id)) + { throw new InvalidOperationException("The source has no persistent identity."); + } var data = new ChangeData { assetId = id, - typeId = m_types.GetTypeRef(settings.GetType()).stableId, + typeId = m_types.GetTypeRef(settings.GetType()).stableID, before = Capture(before.value), after = Capture(settings) }; if (data.before.AsSpan().SequenceEqual(data.after)) + { return m_assets.TryGetInfo(id, out AssetInfo? info) && info?.status == AssetImportStatus.Imported; + } bool imported = m_assets.SaveImportSettings(path, settings, expectedFingerprint); var change = new EditorHistoryChange(C_HISTORY, EditorHistoryPayload.FromBytes(m_serialization.Serialize(data))); try { m_interactions.history.RecordApplied("Change Import Settings", change); } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) { change.Dispose(); try @@ -138,19 +154,29 @@ EditorHistoryDirection direction EditorHistoryDirection direction ) { if (!m_assets.TryGetInfo(data.assetId, out AssetInfo? info) || info is null || info.status == AssetImportStatus.Missing) + { throw new IOException("The import-settings source is missing. History is retained until it returns."); + } if (!m_assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) || entry.isReadOnly) + { throw new IOException("The import-settings source is not writable."); + } AssetImportSettingsSnapshot current = m_assets.GetImportSettings(info.assetPath); - if (current.value is null || m_types.GetTypeRef(current.value.GetType()).stableId != data.typeId) + if (current.value is null || m_types.GetTypeRef(current.value.GetType()).stableID != data.typeId) + { throw new InvalidOperationException("The importer settings extension is unavailable or changed type."); + } byte[] expected = direction == EditorHistoryDirection.Undo ? data.after : data.before; if (!Capture(current.value).AsSpan().SequenceEqual(expected)) + { throw new IOException("Import settings changed outside this history operation."); + } return (info.assetPath, current); } - private byte[] Capture(ISerializable value) => m_serialization.Encode(writer => writer.WriteProperties(value), AssetSerializationContext.Create(m_assets)); + private byte[] Capture(ISerializable value) + => m_serialization.Encode(writer => writer.WriteProperties(value), AssetSerializationContext.Create(m_assets)); + private sealed class ChangeData : ISerializable { [SerializableProperty] @@ -166,71 +192,3 @@ private sealed class ChangeData : ISerializable internal byte[] after { get; set; } = []; } } - -[EditorHistoryHandler(AssetImportSettingsEdits.C_HISTORY)] -internal sealed class AssetImportSettingsHistory(AssetImportSettingsEdits edits) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - edits.Validate(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) - { - return EditorHistoryAvailability.Unavailable(failure.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - edits.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) - { - return EditorHistoryResult.Failure(failure.Message); - } - } -} diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs new file mode 100644 index 000000000..0f3c2e7c7 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using Inno.Core.Execution; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Assets; + +[EditorHistoryHandler(AssetImportSettingsEdits.C_HISTORY)] +internal sealed class AssetImportSettingsHistory(AssetImportSettingsEdits edits) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + edits.Validate(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + return EditorHistoryAvailability.Unavailable(failure.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + edits.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + return EditorHistoryResult.Failure(failure.Message); + } + } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs index b628355d7..84cb17b32 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Editor.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Assets", "Inno.Editor.Assets", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs index 7be6f4c3c..176ab915f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs @@ -1,4 +1,3 @@ -using Inno.Editor.Assets; using System; using System.IO; using System.Linq; @@ -7,12 +6,14 @@ using Inno.Assets.Pipeline; using Inno.Core.Execution; using Inno.Core.Logging; +using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scripting; using Inno.Scripting.Compiler; namespace Inno.Editor.Assets; + /// /// Owns sample import validation, publication and rollback independently of its progress window. /// @@ -33,6 +34,7 @@ public sealed class AssetSampleImportModule : EditorModule private AssetSampleImportProgress m_progress = new(0, 0f, string.Empty, false); private long m_operation; private bool m_acceptProgress; + internal AssetSampleImportModule( AssetEditingModule assets, ScriptCompiler compiler, @@ -49,14 +51,17 @@ LogRouter logs /// Defers later modules while the import pins their generation or requires a Host restart. /// public override bool blocksFollowingUpdates => isBusy || m_faulted; + /// /// Gets whether an import still owns validation or publication work. /// public bool isBusy => !m_faulted && m_import is not null; + /// /// Gets whether the current authoring generation admits a new sample import. /// - public bool canImport => !m_faulted && !isBusy && m_scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed; + public bool canImport + => !m_faulted && !isBusy && m_scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed; /// /// Gets a complete immutable progress snapshot under the existing owner lock. @@ -66,7 +71,9 @@ public AssetSampleImportProgress progress get { lock (m_progressLock) + { return m_progress; + } } } @@ -82,7 +89,9 @@ public AssetSampleImportProgress progress public void Request(AssetPath source) { if (!canImport) + { throw new InvalidOperationException("Sample import requires an idle authoring generation."); + } m_import = m_assets.pipeline.PrepareSampleImport(source); m_canceled = false; lock (m_progressLock) @@ -92,29 +101,18 @@ public void Request(AssetPath source) } } - /// - /// Requests cancellation without releasing work that has not retired. - /// - private void CancelCurrent() - { - if (m_import is null) - return; - m_canceled = true; - lock (m_progressLock) - m_progress = m_progress with { status = "Canceling sample import...", cancellationRequested = true }; - m_import.Cancel(); - } - /// /// Cancels only the import observed by the presentation. /// - /// + /// /// The current import identity captured by the caller. /// - public void Cancel(long operationId) + public void Cancel(long operationID) { - if (progress.operationId == operationId) + if (progress.operationID == operationID) + { CancelCurrent(); + } } /// @@ -126,7 +124,9 @@ public void Cancel(long operationId) protected override void OnUpdate(EditorContext context) { if (!isBusy) + { return; + } try { if (m_canceled || m_failure is not null) @@ -139,25 +139,43 @@ protected override void OnUpdate(EditorContext context) if (!m_validating) { if (!import.Advance()) + { return; + } m_validating = true; SetProgress(0.2f, "Validating sample scripts..."); string physicalSource = Path.Combine(m_assets.pipeline.assetRoot, import.target.localPath); string targetPath = import.target.ToString(); - long operation = progress.operationId; + long operation = progress.operationID; import.BeginValidation(async ( sources, cancellationToken ) => { - ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync(new ImportProgress(this, operation), cancellationToken, sources).ConfigureAwait(false); + ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( + new ImportProgress(this, operation), + sources, + cancellationToken + ).ConfigureAwait(false); if (!result.success) - throw new InvalidOperationException("Sample script preflight failed:" + Environment.NewLine + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Sample script preflight failed:" + + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); + } SetProgress(0.85f, "Preparing sample history...", operation); m_historyPayload = await Task.Run(() => { byte[] archive = AssetSourceArchive.CapturePhysical(physicalSource, isDirectory: true, cancellationToken); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateAsset, targetPath, string.Empty, isDirectory: true, archive); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateAsset, + targetPath, + string.Empty, + isDirectory: true, + archive + ); cancellationToken.ThrowIfCancellationRequested(); return EditorHistoryPayload.FromBytes(data.Encode()); }, cancellationToken).ConfigureAwait(false); @@ -166,12 +184,17 @@ protected override void OnUpdate(EditorContext context) } if (!import.isValidationComplete) + { return; + } import.Commit(_ => { m_assets.interactions.history.RecordApplied( "Import Sample", - new EditorHistoryChange(AssetHistoryKinds.SourceOperation, m_historyPayload ?? throw new InvalidOperationException("Validated sample history is missing.")) + new EditorHistoryChange( + AssetHistoryKinds.C_SOURCE_OPERATION, + m_historyPayload ?? throw new InvalidOperationException("Validated sample history is missing.") + ) ); }); m_log.Write(LogLevel.Info, "Imported sample to '{0}'.", [import.target]); @@ -181,7 +204,9 @@ protected override void OnUpdate(EditorContext context) catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (m_import?.isFaulted == true) + { ReportFault(pending); + } // The next frame retries retirement while the modal and dependency ownership remain intact. } catch (Exception failure) @@ -189,7 +214,9 @@ protected override void OnUpdate(EditorContext context) m_failure = failure; CancelCurrent(); if (m_import?.isFaulted == true) + { ReportFault(failure); + } } } @@ -209,13 +236,35 @@ protected override void OnStop(EditorContext context) /// Retries retirement without releasing dependencies still used by background work. /// protected override void OnDispose() => RetireImport(); + + /// + /// Requests cancellation without releasing work that has not retired. + /// + private void CancelCurrent() + { + if (m_import is null) + { + return; + } + m_canceled = true; + lock (m_progressLock) + { + m_progress = m_progress with { status = "Canceling sample import...", cancellationRequested = true }; + } + m_import.Cancel(); + } + private void RetireImport() { m_import?.Rollback(); if (m_failure is not null) + { m_log.Write(LogLevel.Error, "Sample import failed: {0}", [m_failure]); + } else if (m_import is not null) + { m_log.Write(LogLevel.Info, "Sample import was canceled; no copy was published."); + } ClearImport(); } @@ -248,12 +297,16 @@ private void ReportFault(Exception failure) private void SetProgress( float progress, string status, - long? operationId = null + long? operationID = null ) { lock (m_progressLock) { - if (!m_acceptProgress || m_progress.cancellationRequested || (operationId is long expected && expected != m_progress.operationId)) + if (!m_acceptProgress + || m_progress.cancellationRequested + || (operationID is long expected && expected != m_progress.operationID) + ) { return; + } m_progress = m_progress with { fraction = progress, status = status }; } } @@ -263,7 +316,7 @@ private sealed class ImportProgress( long operation ) : IProgress { - /// + /// public void Report(ScriptCompilationProgress value) => owner.SetProgress(0.2f + value.fraction * 0.6f, value.stage, operation); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportProgress.cs b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportProgress.cs index ae294eb65..697cce661 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportProgress.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportProgress.cs @@ -3,7 +3,7 @@ namespace Inno.Editor.Assets; /// /// Contains one atomically captured sample import status. /// -/// +/// /// The import identity within its owner. /// /// @@ -16,7 +16,7 @@ namespace Inno.Editor.Assets; /// Whether cancellation is draining owned work. /// public readonly record struct AssetSampleImportProgress( - long operationId, + long operationID, float fraction, string status, bool cancellationRequested diff --git a/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs b/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs index 2fed5fe66..eb8d9fe79 100644 --- a/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs +++ b/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs @@ -1,14 +1,14 @@ -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Extensibility.Types; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; namespace Inno.Editor.Audio; @@ -51,11 +51,15 @@ public EditorAudioHost( Func deviceFactory, Func? settingsProvider = null ) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(artifacts); + ArgumentNullException.ThrowIfNull(diagnostics); + ArgumentNullException.ThrowIfNull(deviceFactory); + m_types = types; + m_artifacts = artifacts; + m_diagnostics = diagnostics; m_settingsProvider = settingsProvider ?? (() => new AudioProjectSettings()); - m_deviceFactory = deviceFactory ?? throw new ArgumentNullException(nameof(deviceFactory)); + m_deviceFactory = deviceFactory; } /// @@ -73,68 +77,6 @@ public IRuntimeSubsystemFactory CreateRuntimeSubsystemFactory(RuntimeSession ses return new EditorAudioRuntimeFactory(this, session); } - private AudioRuntime CreateRuntime( - RuntimeSession session, - RuntimeSubsystemContext context - ) { - ObjectDisposedException.ThrowIf(m_disposed, this); - ArgumentNullException.ThrowIfNull(session); - if (m_sessions.ContainsKey(session)) - throw new InvalidOperationException("The runtime session already owns an Editor audio generation."); - if (session.options.kind == RuntimeSessionKind.Play && - m_sessions.Keys.Any(static active => active.options.kind == RuntimeSessionKind.Play)) - { - throw new InvalidOperationException("Only one isolated Play Mode audio generation may be active."); - } - - AudioProjectSettings settings = m_settingsProvider() - ?? throw new InvalidOperationException("The audio settings provider returned null."); - DiagnosticReporter diagnostics = context.resources.Own(m_diagnostics.CreateReporter( - new DiagnosticSource($"inno.editor.audio.{session.sessionId}", $"Audio ({session.options.kind})"))); - IAudioDevice device = CreateDevice(diagnostics); - AudioRuntime? runtime = null; - try - { - runtime = new AudioRuntime( - m_types, - device, - m_artifacts, - session.events, - diagnostics, - new AudioRuntimeOptions - { - maxVoices = settings.maxVoices, - decodedCacheBudgetBytes = settings.decodedCacheBudgetBytes, - automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes - }, - contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), - deviceRecoveryFactory: m_deviceFactory); - if (settings.defaultMixer is not null && !runtime.ApplyMixer(settings.defaultMixer)) - throw new InvalidOperationException("The configured default Editor audio mixer could not be activated."); - if (!runtime.SetBusVolume(AudioBusId.master, settings.masterVolume)) - throw new InvalidOperationException("The configured Editor master audio volume could not be applied."); - m_sessions.Add(session, runtime); - if (session.options.kind == RuntimeSessionKind.Play) - SetEditModePaused(true); - return runtime; - } - catch (Exception failure) - { - try - { - if (runtime is not null) - runtime.Dispose(); - else - device.Dispose(); - } - catch (Exception cleanup) - { - throw new AggregateException("Editor audio startup and rollback failed.", failure, cleanup); - } - throw; - } - } - /// /// Binds the script-facing audio façade to one session's runtime. /// @@ -169,7 +111,9 @@ public AudioVoiceHandle PlayPreview( ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(clip); if (session.options.kind != RuntimeSessionKind.Edit) + { throw new ArgumentException("Audio previews require an Edit Mode runtime session.", nameof(session)); + } return GetRuntime(session).Play(clip, options ?? AudioPlayOptions.defaultValue); } @@ -191,7 +135,9 @@ AudioVoiceHandle voice ) { ArgumentNullException.ThrowIfNull(session); if (session.options.kind != RuntimeSessionKind.Edit) + { return false; + } return GetRuntime(session).Stop(voice); } @@ -201,7 +147,9 @@ AudioVoiceHandle voice public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; List? failures = null; foreach (AudioRuntime runtime in m_sessions.Values.Reverse().ToArray()) @@ -218,7 +166,87 @@ public void Dispose() } m_sessions.Clear(); if (failures is not null) + { throw new AggregateException("One or more Editor audio generations could not be released.", failures); + } + } + + private AudioRuntime CreateRuntime( + RuntimeSession session, + RuntimeSubsystemContext context + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + ArgumentNullException.ThrowIfNull(session); + if (m_sessions.ContainsKey(session)) + { + throw new InvalidOperationException("The runtime session already owns an Editor audio generation."); + } + if (session.options.kind == RuntimeSessionKind.Play + && m_sessions.Keys.Any(static active => active.options.kind == RuntimeSessionKind.Play) + ) { + throw new InvalidOperationException("Only one isolated Play Mode audio generation may be active."); + } + + AudioProjectSettings settings = m_settingsProvider() + ?? throw new InvalidOperationException("The audio settings provider returned null."); + DiagnosticReporter diagnostics = context.resources.Own( + m_diagnostics.CreateReporter( + new DiagnosticSource($"inno.editor.audio.{session.sessionID}", $"Audio ({session.options.kind})") + ) + ); + IAudioDevice device = CreateDevice(diagnostics); + AudioRuntime? runtime = null; + try + { + runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + session.events, + diagnostics, + new AudioRuntimeOptions + { + maxVoices = settings.maxVoices, + decodedCacheBudgetBytes = settings.decodedCacheBudgetBytes, + automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes + }, + contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), + deviceRecoveryFactory: m_deviceFactory + ); + if (settings.defaultMixer is not null && !runtime.ApplyMixer(settings.defaultMixer)) + { + throw new InvalidOperationException("The configured default Editor audio mixer could not be activated."); + } + if (!runtime.SetBusVolume(AudioBusID.master, settings.masterVolume)) + { + throw new InvalidOperationException("The configured Editor master audio volume could not be applied."); + } + m_sessions.Add(session, runtime); + if (session.options.kind == RuntimeSessionKind.Play) + { + SetEditModePaused(true); + } + return runtime; + } + catch (Exception failure) + { + try + { + if (runtime is not null) + { + runtime.Dispose(); + } + else + { + device.Dispose(); + } + } + catch (Exception cleanup) + { + throw new AggregateException("Editor audio startup and rollback failed.", failure, cleanup); + } + throw; + } } private IAudioDevice CreateDevice(IDiagnosticReporter diagnostics) @@ -229,11 +257,14 @@ private IAudioDevice CreateDevice(IDiagnosticReporter diagnostics) } catch (Exception exception) { - diagnostics.Publish(new Diagnostic( - "AUDIO_DEVICE_INIT_FAILED", - $"The Editor audio output could not start; this audio generation is explicitly muted: {exception.Message}", - DiagnosticSeverity.Warning, - "AudioAdapter")); + diagnostics.Publish( + new Diagnostic( + "AUDIO_DEVICE_INIT_FAILED", + $"The Editor audio output could not start; this audio generation is explicitly muted: {exception.Message}", + DiagnosticSeverity.Warning, + "AudioAdapter" + ) + ); return new MutedAudioDevice(); } } @@ -243,23 +274,25 @@ private AudioRuntime GetRuntime(RuntimeSession session) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(session); return m_sessions.TryGetValue(session, out AudioRuntime? runtime) - ? runtime - : throw new InvalidOperationException("The runtime session has no active Editor audio lease."); + ? runtime + : throw new InvalidOperationException("The runtime session has no active Editor audio lease."); } private void ReleaseRuntime( RuntimeSession session, AudioRuntime runtime ) { - if (!m_sessions.TryGetValue(session, out AudioRuntime? active) || - !ReferenceEquals(active, runtime)) - { + if (!m_sessions.TryGetValue(session, out AudioRuntime? active) + || !ReferenceEquals(active, runtime) + ) { return; } m_sessions.Remove(session); bool wasPlayMode = session.options.kind == RuntimeSessionKind.Play; if (wasPlayMode) + { SetEditModePaused(false); + } } private void SetEditModePaused(bool paused) @@ -267,23 +300,25 @@ private void SetEditModePaused(bool paused) foreach ((RuntimeSession session, AudioRuntime runtime) in m_sessions) { if (session.options.kind == RuntimeSessionKind.Edit) - _ = runtime.SetBusPaused(AudioBusId.master, paused); + { + _ = runtime.SetBusPaused(AudioBusID.master, paused); + } } } private sealed class EditorAudioRuntimeFactory( EditorAudioHost owner, RuntimeSession session - ) - : IRuntimeSubsystemFactory + ) : IRuntimeSubsystemFactory { /// /// Gets the stable audio feature descriptor shared by every Editor session. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.audio"), + new RuntimeSubsystemID("inno.runtime.audio"), order: 500, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemID("inno.runtime.scene")] + ); /// /// Creates one Editor-owned audio generation for the supplied runtime session. @@ -303,9 +338,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) } } - - - private sealed class SessionAudioRegistration( EditorAudioHost owner, RuntimeSession session, diff --git a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs index 0accdc29f..c376b1066 100644 --- a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs +++ b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs @@ -1,7 +1,7 @@ -using Inno.Runtime.Contracts; using System; using Inno.Audio; using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Editor.Audio; @@ -13,12 +13,12 @@ public interface IEditorAudioHost : IDisposable /// /// Creates the reusable factory that contributes isolated audio runtimes to Editor sessions. /// - /// - /// A factory whose features are owned and released by their runtime sessions. - /// /// /// The explicit session being composed. /// + /// + /// A factory whose features are owned and released by their runtime sessions. + /// IRuntimeSubsystemFactory CreateRuntimeSubsystemFactory(RuntimeSession session); /// diff --git a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportProgress.cs b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportProgress.cs index d9e97c02a..58d18d52c 100644 --- a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportProgress.cs +++ b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportProgress.cs @@ -3,7 +3,7 @@ namespace Inno.Editor.Exporting; /// /// Contains one owner-thread export presentation snapshot. /// -/// +/// /// The export identity within this service. /// /// @@ -22,7 +22,7 @@ namespace Inno.Editor.Exporting; /// Whether cancellation is draining work. /// public readonly record struct EditorExportProgress( - long operationId, + long operationID, float? fraction, string status, string error, diff --git a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs index e5f1194d4..91796e922 100644 --- a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs +++ b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs @@ -7,12 +7,13 @@ using System.Threading.Tasks; using Inno.Build; using Inno.Build.Managed; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Core.Settings; using Inno.Editor.Core; namespace Inno.Editor.Exporting; + /// /// Owns asynchronous export, progress, cancellation and retirement independently from presentation. /// @@ -31,11 +32,13 @@ public sealed class EditorExportService : EditorModule private Task? m_gameExport; private Task? m_pluginExport; private GameBuildRequest? m_pendingGameRequest; + internal EditorExportService( BuildPipeline buildPipeline, LogRouter logs ) { - m_buildPipeline = buildPipeline ?? throw new ArgumentNullException(nameof(buildPipeline)); + ArgumentNullException.ThrowIfNull(buildPipeline); + m_buildPipeline = buildPipeline; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -44,33 +47,44 @@ LogRouter logs /// Gets whether a Plugin source export still owns build resources. /// public bool isPluginBusy => m_pluginExport is not null; + /// /// Gets whether a game export or its Support Pack preparation is active. /// public bool isGameBusy => m_gamePreparation is not null || m_gameExport is not null; + /// /// Gets one owner-thread snapshot for the current export, including cancellation and action identity. /// - public EditorExportProgress progress => new(m_operation, m_fraction, m_status, m_error, - isGameBusy || isPluginBusy, m_cancellation?.IsCancellationRequested == true); + public EditorExportProgress progress + => new( + m_operation, + m_fraction, + m_status, + m_error, + isGameBusy || isPluginBusy, + m_cancellation?.IsCancellationRequested == true + ); + + /// + /// Gets the targets registered by the active Build distribution. + /// + public IReadOnlyList availableGameTargets => m_buildPipeline.availableGameTargets; /// /// Cancels the observed export only while that operation still owns this service. /// - /// + /// /// The operation observed by the caller. /// - public void Cancel(long operationId) + public void Cancel(long operationID) { - if (operationId == m_operation) + if (operationID == m_operation) + { CancelCurrent(); + } } - /// - /// Gets the targets registered by the active Build distribution. - /// - public IReadOnlyList availableGameTargets => m_buildPipeline.availableGameTargets; - /// /// Gets deployment implementations registered for a target. /// @@ -80,7 +94,8 @@ public void Cancel(long operationId) /// /// The registered deployment choices; no host fallback is introduced. /// - public IReadOnlyList GetManagedDeployments(BuildTargetId target) => m_buildPipeline.GetManagedDeployments(target); + public IReadOnlyList GetManagedDeployments(BuildTargetID target) => m_buildPipeline.GetManagedDeployments(target); + /// /// Gets a registered target label or a diagnostic for an unavailable target. /// @@ -90,10 +105,12 @@ public void Cancel(long operationId) /// /// A presentation label; never used as a routing identity. /// - public string GetGameTargetDisplayName(BuildTargetId target) => m_buildPipeline.TryGetGameTargetDisplayName( - target, - out string displayName - ) ? displayName : $"Missing ({target})"; + public string GetGameTargetDisplayName(BuildTargetID target) + => m_buildPipeline.TryGetGameTargetDisplayName( + target, + out string displayName + ) ? displayName : $"Missing ({target})"; + /// /// Starts a source-package export using the existing Build pipeline. /// @@ -110,7 +127,9 @@ public void StartPlugin(PluginBuildRequest request) StartCancellation(); m_status = "Capturing the current Plugin source and dependency generation..."; m_error = string.Empty; - m_pluginExport = m_buildPipeline.BuildPluginAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation!.Token).AsTask(); + m_pluginExport = m_buildPipeline + .BuildPluginAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation!.Token) + .AsTask(); } /// @@ -133,7 +152,9 @@ public void StartGame(GameBuildRequest request) m_pendingGameRequest = request; try { - m_gamePreparation = m_buildPipeline.EnsurePlayerSupportPackAsync(request.profile.target, request.profile.managedDeployment, m_cancellation!.Token).AsTask(); + m_gamePreparation = m_buildPipeline + .EnsurePlayerSupportPackAsync(request.profile.target, request.profile.managedDeployment, m_cancellation!.Token) + .AsTask(); } catch (Exception exception) { @@ -141,12 +162,6 @@ public void StartGame(GameBuildRequest request) } } - private void EnsureIdle() - { - if (isPluginBusy || isGameBusy) - throw new InvalidOperationException("An export still owns the build service."); - } - /// /// Advances compilation tickets, build progress, and completed export tasks. /// @@ -155,14 +170,18 @@ private void EnsureIdle() /// protected override void OnUpdate(EditorContext context) { - while (m_progress.TryDequeue(out var update)) + while (m_progress.TryDequeue(out (long operation, BuildProgress value) update)) { if (update.operation != m_operation || m_cancellation is null || m_cancellation.IsCancellationRequested) + { continue; + } BuildProgress progress = update.value; m_status = progress.message; if (isGameBusy || isPluginBusy) + { m_fraction = MathF.Max(m_fraction ?? 0f, (float)progress.fraction); + } } CompletePluginExport(); @@ -176,24 +195,28 @@ protected override void OnUpdate(EditorContext context) /// /// The active Editor context being stopped. /// - protected override void OnStop(EditorContext context) - { - RetireExports(); - } + protected override void OnStop(EditorContext context) => RetireExports(); /// /// Drains export cleanup before releasing cancellation resources owned by this module. /// - protected override void OnDispose() + protected override void OnDispose() => RetireExports(); + + private void EnsureIdle() { - RetireExports(); + if (isPluginBusy || isGameBusy) + { + throw new InvalidOperationException("An export still owns the build service."); + } } private void RetireExports() { m_cancellation?.Cancel(); - if (m_gamePreparation is { IsCompleted: false } || m_gameExport is { IsCompleted: false } || m_pluginExport is { IsCompleted: false }) - { + if (m_gamePreparation is { IsCompleted: false } + || m_gameExport is { IsCompleted: false } + || m_pluginExport is { IsCompleted: false } + ) { throw new RetirementPendingException("Canceled export work still owns build services; retry retirement after it drains."); } @@ -228,17 +251,13 @@ private void RetireExports() ReleaseCancellation(); } - private static void RequireRetiredOutcome(Task? task) - { - if (task?.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) - throw failure; - } - private void CompletePluginExport() { Task? export = m_pluginExport; if (export is null || !export.IsCompleted) + { return; + } m_pluginExport = null; try { @@ -250,7 +269,8 @@ private void CompletePluginExport() } string outputPath = result.outputPath ?? throw new InvalidOperationException("A successful Plugin build has no output path."); - string contentHash = result.contentHash ?? throw new InvalidOperationException("A successful Plugin build has no content identity."); + string contentHash = result.contentHash + ?? throw new InvalidOperationException("A successful Plugin build has no content identity."); m_fraction = 1f; m_status = $"Exported {result.assetCount} source files to {outputPath}"; m_error = string.Empty; @@ -282,7 +302,9 @@ private void CompleteGameExport() { Task? export = m_gameExport; if (export is null || !export.IsCompleted) + { return; + } m_gameExport = null; try { @@ -300,7 +322,13 @@ private void CompleteGameExport() m_log.Write( LogLevel.Info, "Exported game to '{0}' ({1}, {2} assets, {3} artifact bundles, {4} runtime assemblies).", - [outputPath, result.target?.ToString() ?? "unknown", result.assetCount, result.artifactBundleCount, result.runtimeAssemblyCount] + [ + outputPath, + result.target?.ToString() ?? "unknown", + result.assetCount, + result.artifactBundleCount, + result.runtimeAssemblyCount + ] ); } catch (OperationCanceledException) @@ -325,16 +353,21 @@ private void CompleteGamePreparation() { Task? preparation = m_gamePreparation; if (preparation is null || !preparation.IsCompleted) + { return; + } m_gamePreparation = null; try { using PlayerSupportPackLease prepared = preparation.GetAwaiter().GetResult(); m_cancellation!.Token.ThrowIfCancellationRequested(); - GameBuildRequest request = m_pendingGameRequest ?? throw new InvalidOperationException("The prepared game build has no request."); + GameBuildRequest request = m_pendingGameRequest + ?? throw new InvalidOperationException("The prepared game build has no request."); m_pendingGameRequest = null; m_status = "Capturing the authoring generation and compiling runtime scripts..."; - m_gameExport = m_buildPipeline.BuildGameAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation.Token).AsTask(); + m_gameExport = m_buildPipeline + .BuildGameAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation.Token) + .AsTask(); } catch (OperationCanceledException) { @@ -365,7 +398,9 @@ private void StartCancellation() private void CancelCurrent() { if (m_cancellation is null) + { return; + } m_status = "Canceling export..."; m_cancellation.Cancel(); } @@ -380,12 +415,23 @@ private void ReportBuildFailure( string operation, BuildResult result ) { - string message = string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => $"[{diagnostic.code}] {diagnostic.message}")); + string message = string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"[{diagnostic.code}] {diagnostic.message}") + ); m_status = string.Empty; m_error = message; m_log.Write(LogLevel.Error, "{0} failed:{1}{2}", [operation, Environment.NewLine, message]); } + private static void RequireRetiredOutcome(Task? task) + { + if (task?.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) + { + throw failure; + } + } + private sealed class BuildProgressSink( ConcurrentQueue<(long operation, BuildProgress value)> progress, long operation diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs b/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs index a60e90e29..5fa40e391 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs @@ -9,27 +9,22 @@ public enum EditorPlayModeState /// Editable scene documents are loaded and game simulation is stopped. /// Editing, - /// /// Play Mode is waiting for the requested script generation to become active. /// Compiling, - /// /// The active script generation is ready and isolated runtime state is being prepared. /// Preparing, - /// /// Isolated runtime scenes are receiving the game update lifecycle. /// Playing, - /// /// The isolated runtime session is stopping and releasing its owned state. /// Stopping, - /// /// The most recent transition failed and its diagnostic remains available for inspection. /// diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs b/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs index 28127edb0..5272e3f3a 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; namespace Inno.Editor.PlayMode; @@ -25,9 +24,9 @@ public interface IEditorPlayMode string? lastFailure { get; } /// - /// Gets the active isolated runtime log session, or outside a Play Mode request. + /// Gets the active isolated runtime log session, or outside a Play Mode request. /// - LogSessionId activeSessionId { get; } + LogSessionID activeSessionID { get; } /// /// Subscribes to committed state transitions through the Core event lifetime. diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIds.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIDs.cs similarity index 78% rename from src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIds.cs rename to src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIDs.cs index dabf3c637..aaa2eb508 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIds.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/PlayModeInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.PlayMode; -internal static class PlayModeInteractionIds +internal static class PlayModeInteractionIDs { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; internal const string C_TOGGLE_PLAY_MODE = "play-mode/toggle"; diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs index 77dfbff39..8dd104319 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs @@ -3,12 +3,13 @@ namespace Inno.Editor.PlayMode; -[EditorAction(PlayModeInteractionIds.C_TOGGLE_PLAY_MODE)] +[EditorAction(PlayModeInteractionIDs.C_TOGGLE_PLAY_MODE)] [EditorToolbarItem( - PlayModeInteractionIds.C_MAIN_MENU_AREA, + PlayModeInteractionIDs.C_MAIN_MENU_AREA, EditorToolbarIcon.Play, "Enter Play Mode", - activeIcon: EditorToolbarIcon.Stop)] + activeIcon: EditorToolbarIcon.Stop +)] [EditorShortcut(KeyCode.P, primary: true)] internal sealed class TogglePlayModeAction(IEditorPlayMode playMode) : EditorAction { @@ -23,34 +24,35 @@ internal sealed class TogglePlayModeAction(IEditorPlayMode playMode) : EditorAct /// protected override EditorActionState Query(EditorActionContext context) => playMode.state switch - { - EditorPlayModeState.Editing => new EditorActionState(true, true, displayName: "Enter Play Mode"), - EditorPlayModeState.Compiling => new EditorActionState( - true, - true, - isChecked: true, - displayName: "Cancel Script Compilation Wait"), - EditorPlayModeState.Preparing => new EditorActionState( - true, - false, - isChecked: true, - displayName: "Preparing Play Mode"), - EditorPlayModeState.Playing => new EditorActionState( - true, - true, - isChecked: true, - displayName: "Return to Edit Mode"), - EditorPlayModeState.Stopping => new EditorActionState( - true, - false, - isChecked: true, - displayName: "Restoring Edit Mode"), - EditorPlayModeState.Failed => new EditorActionState( - true, - true, - displayName: "Retry Play Mode"), - _ => EditorActionState.hidden - }; + { + EditorPlayModeState.Editing => new EditorActionState(true, true, displayName: "Enter Play Mode"), + EditorPlayModeState.Compiling => new EditorActionState( + true, + true, + isChecked: true, + displayName: "Cancel Script Compilation Wait" + ), + EditorPlayModeState.Preparing => new EditorActionState( + true, + false, + isChecked: true, + displayName: "Preparing Play Mode" + ), + EditorPlayModeState.Playing => new EditorActionState( + true, + true, + isChecked: true, + displayName: "Return to Edit Mode" + ), + EditorPlayModeState.Stopping => new EditorActionState( + true, + false, + isChecked: true, + displayName: "Restoring Edit Mode" + ), + EditorPlayModeState.Failed => new EditorActionState(true, true, displayName: "Retry Play Mode"), + _ => EditorActionState.hidden + }; /// /// Executes the prepared operation and publishes only a completed result. @@ -61,8 +63,12 @@ protected override EditorActionState Query(EditorActionContext context) protected override void Execute(EditorActionContext context) { if (playMode.state is EditorPlayModeState.Compiling or EditorPlayModeState.Preparing or EditorPlayModeState.Playing) + { _ = playMode.ExitPlayMode(); + } else + { _ = playMode.EnterPlayMode(); + } } } diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs index 99641b4d2..79abc14e3 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.PlayMode; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.PlayMode", - "Inno.Editor.PlayMode", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.PlayMode", "Inno.Editor.PlayMode", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorPlayModeState), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(IEditorPlayMode), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs index 1d9ad489e..45bcfbd9b 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs @@ -1,20 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Extensibility.Reload; using System; -using Inno.Core.Events; using System.Collections.Generic; - +using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Execution; using Inno.Core.Logging; -using Inno.Extensibility.Modules; -using Inno.Scripting.Api; using Inno.Editor.Audio; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Scripting; -using Inno.Scripting.Compiler; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Runtime; +using Inno.Scripting.Api; +using Inno.Scripting.Compiler; using Inno.UI.Runtime; namespace Inno.Editor.PlayMode; @@ -54,7 +53,7 @@ public sealed class EditorPlayModeController : private EditorPlayModeState m_state; private float m_playTime; private string? m_lastFailure; - private LogSessionId m_activeSessionId; + private LogSessionID m_activeSessionID; private bool m_disposed; /// @@ -93,17 +92,23 @@ public EditorPlayModeController( LogRouter logs, IEditorAudioHost? audio = null ) { - m_engineHost = engineHost ?? throw new ArgumentNullException(nameof(engineHost)); - m_runtimeOptions = runtimeOptions ?? throw new ArgumentNullException(nameof(runtimeOptions)); + ArgumentNullException.ThrowIfNull(engineHost); + ArgumentNullException.ThrowIfNull(runtimeOptions); + ArgumentNullException.ThrowIfNull(scenes); + ArgumentNullException.ThrowIfNull(scripting); + ArgumentNullException.ThrowIfNull(history); + m_engineHost = engineHost; + m_runtimeOptions = runtimeOptions; if (runtimeOptions.kind != RuntimeSessionKind.Play) { throw new ArgumentException( "Editor Play Mode requires RuntimeSessionKind.Play options.", - nameof(runtimeOptions)); + nameof(runtimeOptions) + ); } - m_scenes = scenes ?? throw new ArgumentNullException(nameof(scenes)); - m_scripting = scripting ?? throw new ArgumentNullException(nameof(scripting)); - m_history = history ?? throw new ArgumentNullException(nameof(history)); + m_scenes = scenes; + m_scripting = scripting; + m_history = history; m_audio = audio; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); @@ -120,18 +125,6 @@ public EditorPlayModeController( /// public bool isPlaying => m_state == EditorPlayModeState.Playing; - /// - bool IEditorReloadGuard.canRequestReload => !m_disposed && m_state == EditorPlayModeState.Editing; - - /// - bool IEditorReloadGuard.canActivateReload => !m_disposed - && m_state is EditorPlayModeState.Editing or EditorPlayModeState.Compiling - && m_runtimeSession is null && m_sceneLease is null && m_generationLease is null; - - /// - string? IEditorReloadGuard.blockingReason => m_state == EditorPlayModeState.Editing - ? null : "Stop Play Mode and wait for its runtime session to retire before reloading scripts or Plugins."; - /// /// Gets the most recent transition or simulation failure. /// @@ -140,9 +133,24 @@ public EditorPlayModeController( /// /// Gets the isolated runtime log session associated with the current request. /// - public LogSessionId activeSessionId => m_activeSessionId; + public LogSessionID activeSessionID => m_activeSessionID; + + /// + bool IEditorReloadGuard.canRequestReload => !m_disposed && m_state == EditorPlayModeState.Editing; - /// + /// + bool IEditorReloadGuard.canActivateReload + => !m_disposed + && m_state is EditorPlayModeState.Editing or EditorPlayModeState.Compiling + && m_runtimeSession is null && m_sceneLease is null && m_generationLease is null; + + /// + string? IEditorReloadGuard.blockingReason + => m_state == EditorPlayModeState.Editing + ? null + : "Stop Play Mode and wait for its runtime session to retire before reloading scripts or Plugins."; + + /// public IDisposable ListenStateChanges(Action listener) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -173,12 +181,14 @@ public bool EnterPlayMode() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_state is not (EditorPlayModeState.Editing or EditorPlayModeState.Failed)) + { return false; + } m_engineHost.generations.EnsureReady("enter Play Mode"); m_entryFailed = false; m_retirement = null; m_lastFailure = null; - m_activeSessionId = LogSessionId.none; + m_activeSessionID = LogSessionID.none; m_compilationTicket = m_scripting.RequestCompilation(); SetState(EditorPlayModeState.Compiling); return true; @@ -251,7 +261,8 @@ public void Tick(float deltaTime) m_playTime += Math.Max(0f, deltaTime); session.Tick(deltaTime); }, - "frame update"); + "frame update" + ); /// /// Releases the isolated runtime session and history scope owned by this controller. @@ -259,16 +270,24 @@ public void Tick(float deltaTime) public void Dispose() { if (m_disposed) + { return; + } if (m_startupRetirementFailure is not null) + { throw m_startupRetirementFailure; + } try { if (m_runtimeSession is not null) + { SetState(EditorPlayModeState.Stopping); + } ReleasePlayResources(); if (m_state != EditorPlayModeState.Editing) + { CompleteEditingTransition(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -283,6 +302,72 @@ public void Dispose() m_disposed = true; } + internal void Quiesce() + { + if (m_disposed) + { + return; + } + SetState(EditorPlayModeState.Stopping); + List? failures = null; + try + { + new RetirementBarrier("Play Mode before generation activation").Wait(ReleasePlayResources); + } + catch (Exception exception) + { + m_engineHost.generations.Fault(exception); + if (RetirementPendingException.Find(exception) is not null) + { + throw; + } + failures = [exception]; + m_lastFailure = $"Play Mode could not release its runtime generation: {exception.Message}"; + } + try + { + CompleteEditingTransition(); + } + catch (Exception exception) + { + failures ??= []; + failures.Add(exception); + } + + if (failures is not null) + { + throw new InvalidOperationException( + "Assembly reload cannot continue because Play Mode still owns generation-bound runtime state.", + new AggregateException(failures) + ); + } + } + + internal IDisposable? EnterPresentationScope() + { + if (m_state != EditorPlayModeState.Playing || m_runtimeSession is not RuntimeSession session) + { + return null; + } + IDisposable? sessionScope = null; + IDisposable? audioScope = null; + IDisposable? uiScope = null; + try + { + sessionScope = session.EnterExecutionScope(); + audioScope = m_audio?.EnterExecutionScope(session); + uiScope = session.subsystems.GetRequiredSubsystem().EnterExecutionScope(); + return new PresentationScope(sessionScope, audioScope, uiScope); + } + catch + { + uiScope?.Dispose(); + audioScope?.Dispose(); + sessionScope?.Dispose(); + throw; + } + } + private void AdvanceCompilation() { IScriptCompilationTicket? ticket = m_compilationTicket; @@ -304,7 +389,9 @@ private void AdvanceCompilation() return; case ScriptCompilationTicketState.Canceled: case ScriptCompilationTicketState.Superseded: - Fail($"Play Mode did not start because its script request was {ticket.state.ToString().ToLowerInvariant()}. {ticket.status}"); + Fail( + $"Play Mode did not start because its script request was {ticket.state.ToString().ToLowerInvariant()}. {ticket.status}" + ); return; default: throw new ArgumentOutOfRangeException(); @@ -319,8 +406,10 @@ private void PrepareRuntimeSession() m_runtimeSession = m_engineHost.CreateSession(m_runtimeOptions); m_generationLease = m_engineHost.generations.AcquireRead("active Play Mode session"); using (m_runtimeSession.EnterExecutionScope()) + { m_sceneLease = m_scenes.BeginPlayMode(m_runtimeSession); - m_activeSessionId = m_runtimeSession.sessionId; + } + m_activeSessionID = m_runtimeSession.sessionID; m_playTime = 0f; SetState(EditorPlayModeState.Playing); } @@ -345,9 +434,13 @@ private void StopRuntimeSession() { ReleasePlayResources(); if (m_entryFailed) + { SetState(EditorPlayModeState.Failed); + } else + { CompleteEditingTransition(); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -368,20 +461,28 @@ private void StopRuntimeSession() private void ReleasePlayResources() { if (m_startupRetirementFailure is not null) + { throw m_startupRetirementFailure; + } // The owner thread hands admission to the retirement reservation before it can process another frame. m_generationLease?.Dispose(); m_generationLease = null; if (m_sceneLease is null && m_runtimeSession is null && m_historyIsolation is null) + { return; + } if (m_retirementReservation is null && m_engineHost.generations.state == GenerationState.Ready) { if (!m_engineHost.generations.TryAcquireChange("retire Play Mode", out m_retirementReservation)) + { throw new RetirementPendingException("Play Mode retirement is waiting for the active generation reader."); + } } m_retirement ??= new RetirementBarrier("Editor Play Mode"); if (!m_retirement.TryComplete(ReleasePlayResourcesCore)) + { throw new RetirementPendingException("Play Mode is still draining its runtime session."); + } m_retirementReservation?.Dispose(); m_retirementReservation = null; } @@ -399,50 +500,16 @@ private void ReleasePlayResourcesCore() } } - internal void Quiesce() - { - if (m_disposed) - return; - SetState(EditorPlayModeState.Stopping); - List? failures = null; - try - { - new RetirementBarrier("Play Mode before generation activation").Wait(ReleasePlayResources); - } - catch (Exception exception) - { - m_engineHost.generations.Fault(exception); - if (RetirementPendingException.Find(exception) is not null) - throw; - failures = [exception]; - m_lastFailure = $"Play Mode could not release its runtime generation: {exception.Message}"; - } - try - { - CompleteEditingTransition(); - } - catch (Exception exception) - { - failures ??= []; - failures.Add(exception); - } - - if (failures is not null) - { - throw new InvalidOperationException( - "Assembly reload cannot continue because Play Mode still owns generation-bound runtime state.", - new AggregateException(failures)); - } - } - private void RunSimulation( Action callback, string phase ) { if (m_state != EditorPlayModeState.Playing) + { return; + } RuntimeSession session = m_runtimeSession - ?? throw new InvalidOperationException("Playing state has no active runtime session."); + ?? throw new InvalidOperationException("Playing state has no active runtime session."); try { callback(session); @@ -453,34 +520,12 @@ string phase m_log.Write( LogLevel.Error, "Play Mode {0} failed; isolated runtime disposal was requested: {1}", - [phase, exception]); + [phase, exception] + ); SetState(EditorPlayModeState.Stopping); } } - internal IDisposable? EnterPresentationScope() - { - if (m_state != EditorPlayModeState.Playing || m_runtimeSession is not RuntimeSession session) - return null; - IDisposable? sessionScope = null; - IDisposable? audioScope = null; - IDisposable? uiScope = null; - try - { - sessionScope = session.EnterExecutionScope(); - audioScope = m_audio?.EnterExecutionScope(session); - uiScope = session.subsystems.GetRequiredSubsystem().EnterExecutionScope(); - return new PresentationScope(sessionScope, audioScope, uiScope); - } - catch - { - uiScope?.Dispose(); - audioScope?.Dispose(); - sessionScope?.Dispose(); - throw; - } - } - private void Fail(string failure) { m_lastFailure = failure; @@ -491,51 +536,54 @@ private void Fail(string failure) private void CompleteEditingTransition() { m_compilationTicket = null; - m_activeSessionId = LogSessionId.none; + m_activeSessionID = LogSessionID.none; m_playTime = 0f; SetState(EditorPlayModeState.Editing); } - private static string CreateCompilationFailure(IScriptCompilationTicket ticket) - { - ScriptCompilationResult? compilation = ticket.result; - if (compilation is null) - return $"Play Mode requires a valid script generation. {ticket.status}"; - for (int i = 0; i < compilation.diagnostics.Count; i++) - { - ScriptDiagnostic diagnostic = compilation.diagnostics[i]; - if (diagnostic.severity == DiagnosticSeverity.Error) - return $"Play Mode is unavailable because scripts did not compile: {diagnostic.message}"; - } - return "Play Mode is unavailable because the active script compilation failed."; - } - private void SetState(EditorPlayModeState value) { if (m_state == value) + { return; + } m_state = value; var notification = new StateTransitionEvent(value); m_stateDispatcher.Emit(notification); if (notification.failures.Count != 0) + { throw new AggregateException("One or more Play Mode state observers failed.", notification.failures); + } } - private sealed class StateTransitionEvent(EditorPlayModeState state) : Event + private static string CreateCompilationFailure(IScriptCompilationTicket ticket) { - internal EditorPlayModeState state { get; } = state; - internal List failures { get; } = []; + ScriptCompilationResult? compilation = ticket.result; + if (compilation is null) + { + return $"Play Mode requires a valid script generation. {ticket.status}"; + } + for (int i = 0; i < compilation.diagnostics.Count; i++) + { + ScriptDiagnostic diagnostic = compilation.diagnostics[i]; + if (diagnostic.severity == DiagnosticSeverity.Error) + { + return $"Play Mode is unavailable because scripts did not compile: {diagnostic.message}"; + } + } + return "Play Mode is unavailable because the active script compilation failed."; } private static void DisposeResource( ref T? resource, ref List? failures - ) - where T : class, IDisposable + ) where T : class, IDisposable { T? owned = resource; if (owned is null) + { return; + } try { owned.Dispose(); @@ -552,6 +600,12 @@ ref List? failures resource = null; } + private sealed class StateTransitionEvent(EditorPlayModeState state) : Event + { + internal EditorPlayModeState state { get; } = state; + internal List failures { get; } = []; + } + private sealed class PresentationScope( IDisposable sessionScope, IDisposable? audioScope, diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs index 7ebd98d2e..6246140c8 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs @@ -7,7 +7,7 @@ namespace Inno.Editor.PlayMode; /// public sealed class EditorPlayModeLoop { - private static readonly IDisposable S_EMPTY_SCOPE = new EmptyScope(); + private static readonly IDisposable EMPTY_SCOPE = new EmptyScope(); private EditorPlayModeController? m_owner; @@ -26,7 +26,7 @@ public sealed class EditorPlayModeLoop /// /// A scope that must be disposed after the current editor presentation phase completes. /// - public IDisposable EnterPresentationScope() => m_owner?.EnterPresentationScope() ?? S_EMPTY_SCOPE; + public IDisposable EnterPresentationScope() => m_owner?.EnterPresentationScope() ?? EMPTY_SCOPE; /// /// Drains the active Play session before the product tears down editor modules, history or presentation. @@ -39,14 +39,18 @@ public sealed class EditorPlayModeLoop internal void Attach(EditorPlayModeController owner) { if (m_owner is not null && !ReferenceEquals(m_owner, owner)) + { throw new InvalidOperationException("The editor host already owns an active Play Mode module."); + } m_owner = owner; } internal void Detach(EditorPlayModeController owner) { if (ReferenceEquals(m_owner, owner)) + { m_owner = null; + } } private sealed class EmptyScope : IDisposable @@ -54,8 +58,6 @@ private sealed class EmptyScope : IDisposable /// /// Completes the inert presentation scope. /// - public void Dispose() - { - } + public void Dispose() {} } } diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs index 500a3fe98..54008097e 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Audio; using Inno.Editor.Core; @@ -29,8 +28,10 @@ internal EditorPlayModeModule( EditorReloadCoordinator reloads, IEditorAudioHost audio ) { - m_loop = loop ?? throw new ArgumentNullException(nameof(loop)); - m_reloads = reloads ?? throw new ArgumentNullException(nameof(reloads)); + ArgumentNullException.ThrowIfNull(loop); + ArgumentNullException.ThrowIfNull(reloads); + m_loop = loop; + m_reloads = reloads; m_controller = new EditorPlayModeController( engineHost, runtimeOptions, @@ -38,7 +39,8 @@ IEditorAudioHost audio scripting, interactions, engineHost.logs, - audio); + audio + ); } /// @@ -65,9 +67,9 @@ public override bool blocksFollowingUpdates /// /// Gets the isolated log session that owns the current Play Mode request. /// - public LogSessionId activeSessionId => m_controller.activeSessionId; + public LogSessionID activeSessionID => m_controller.activeSessionID; - /// + /// public IDisposable ListenStateChanges(Action listener) => m_controller.ListenStateChanges(listener); /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs index 353827ed4..5cc542ac9 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs @@ -3,9 +3,10 @@ using System.IO; using System.Linq; using System.Threading; +using Inno.Assets; using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Graphs; -using Inno.Assets; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -20,26 +21,30 @@ public sealed partial class EditorRenderTargetArtifactProvider private readonly Dictionary m_drafts = []; internal EditorShaderDraftCompilationSnapshot RequestDraft( - Guid documentId, + Guid documentID, GraphDocument graph, ulong revision, RenderShaderVariant variant, GraphicsCapabilities capabilities ) { - if (documentId == Guid.Empty) - throw new ArgumentException("A preview requires a document identity.", nameof(documentId)); + if (documentID == Guid.Empty) + { + throw new ArgumentException("A preview requires a document identity.", nameof(documentID)); + } ArgumentNullException.ThrowIfNull(graph); lock (m_sync) { EnsureActive(); ShaderCompileTarget target = m_shaderCompiler.CreateTarget(capabilities, optimize: false, debugInformation: true); - if (!m_drafts.TryGetValue(documentId, out DraftEntry? draft)) - m_drafts.Add(documentId, draft = new()); + if (!m_drafts.TryGetValue(documentID, out DraftEntry? draft)) + { + m_drafts.Add(documentID, draft = new()); + } ShaderEntry entry = draft.compilation; string targetVariant = target.key + "\n" + variant.value; if (!draft.attempted || draft.revision != revision || draft.assetRevision != m_assets.revision - || entry.extensionGeneration != m_types.current.version || draft.targetVariant != targetVariant) - { + || entry.extensionGeneration != m_types.current.version || draft.targetVariant != targetVariant + ) { draft.attempted = true; draft.revision = revision; draft.assetRevision = m_assets.revision; @@ -48,26 +53,40 @@ GraphicsCapabilities capabilities draft.targetVariant = targetVariant; try { - byte[] captured = ShaderGraphArtifact.Capture(graph, m_types, m_serialization, AssetSerializationContext.Create(m_assets), + byte[] captured = ShaderGraphArtifact.Capture( + graph, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), ( id, _ ) => { - if (!m_assets.TryGetInfo(id, out AssetInfo? source) || source is null || source.status != AssetImportStatus.Imported) - throw new InvalidDataException($"Shader function '{id}' has no current successful import. Preview cannot hide its source error with an old bundle."); - using ArtifactLease lease = m_assets.AcquireArtifact(id, ShaderSourceBundle.outputName); + if (!m_assets.TryGetInfo(id, out AssetInfo? source) + || source is null + || source.status != AssetImportStatus.Imported + ) { + throw new InvalidDataException( + $"Shader function '{id}' has no current successful import. Preview cannot hide its source error with an old bundle." + ); + } + using ArtifactLease lease = m_assets.AcquireArtifact(id, ShaderSourceBundle.C_OUTPUT_NAME); return lease.ReadAllBytes(); - }, m_lifetime.Token, + }, ( id, _ ) => { if (!m_assets.TryLoad(id, out ShaderAsset? node) || node is null || node.isMissing) + { throw new InvalidDataException($"Shader graph node '{id}' has no current successful import."); + } return ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(node, m_assets), m_serialization); - }); + }, + m_lifetime.Token + ); string hash = ShaderGraphArtifact.GetSemanticHash(captured, m_serialization); if (environmentChanged || entry.semanticHash != hash) { @@ -75,54 +94,81 @@ GraphicsCapabilities capabilities entry.pending = null; entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.semanticHash = hash; - entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync(captured, target, variant, m_types, - m_serialization, AssetSerializationContext.Create(m_assets), token), entry.cancellation.Token); + entry.pending = RunOwnedAsync(token => m_shaderCompiler.CompileGraphAsync( + captured, + target, + variant, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + token + ), entry.cancellation.Token); } } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) { Retire(entry.pending, entry.cancellation); - entry.pending = null; entry.cancellation = null; entry.semanticHash = ""; + entry.pending = null; + entry.cancellation = null; + entry.semanticHash = string.Empty; entry.latestSucceeded = false; - entry.sourceDiagnostics = [new("SHADER_PREVIEW_CAPTURE", DiagnosticSeverity.Error, failure.Message)]; + entry.sourceDiagnostics = [new ShaderDiagnostic("SHADER_PREVIEW_CAPTURE", DiagnosticSeverity.Error, failure.Message)]; } } if (entry.pending is { IsCompleted: true } pending) { - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; - entry.cancellation?.Dispose(); entry.cancellation = null; - ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new(null, - [new("SHADER_PREVIEW_COMPILE", DiagnosticSeverity.Error, pending.Exception?.GetBaseException().Message ?? "Preview compilation cancelled.")]); + entry.cancellation?.Dispose(); + entry.cancellation = null; + ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_PREVIEW_COMPILE", + DiagnosticSeverity.Error, + pending.Exception?.GetBaseException().Message ?? "Preview compilation cancelled." + )] + ); entry.latestSucceeded = result.succeeded; entry.sourceDiagnostics = Array.AsReadOnly(result.diagnostics.ToArray()); if (result.succeeded) + { entry.artifact = result.artifact!.CreateRuntimeArtifact(); + } } - return new(entry.pending is not null ? EditorShaderCompilationState.Compiling + return new( + entry.pending is not null + ? EditorShaderCompilationState.Compiling : entry.latestSucceeded ? EditorShaderCompilationState.Succeeded : EditorShaderCompilationState.Failed, - entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), entry.sourceDiagnostics, entry.artifact); + entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), + entry.sourceDiagnostics, + entry.artifact + ); } } - internal void ReleaseDraft(Guid documentId) + internal void ReleaseDraft(Guid documentID) { lock (m_sync) { EnsureActive(); - if (!m_drafts.Remove(documentId, out DraftEntry? draft)) + if (!m_drafts.Remove(documentID, out DraftEntry? draft)) + { return; + } Retire(draft.compilation.pending, draft.compilation.cancellation); } } private sealed class DraftEntry { + internal readonly ShaderEntry compilation = new(); internal bool attempted; internal ulong revision; internal long assetRevision; - internal string targetVariant = ""; - internal readonly ShaderEntry compilation = new(); + internal string targetVariant = string.Empty; } } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs index 3532f0aba..80a6a0371 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs @@ -1,12 +1,14 @@ -using Inno.Core.Diagnostics; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; @@ -30,7 +32,7 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr private readonly ITextureTargetCompiler m_textureCompiler; private readonly IDiagnosticReporter m_diagnostics; private readonly CancellationTokenSource m_lifetime = new(); - private readonly Inno.Core.Execution.LifetimeScope m_work = new(); + private readonly LifetimeScope m_work = new(); private readonly Dictionary m_shaders = []; private readonly Dictionary m_textures = []; private bool m_disposed; @@ -39,15 +41,18 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr /// /// Creates an Editor artifact provider backed by explicit shader and texture toolchains. /// - /// - /// The compiler that turns backend-neutral shader IR into device target programs. - /// /// /// The authoring asset pipeline that owns source mounts. /// /// /// The serialization registry that owns active Shader contracts. /// + /// + /// The shared authoring type generation owner for graph and source extensions. + /// + /// + /// The compiler that turns backend-neutral shader IR into device target programs. + /// /// /// The compiler that turns artist texture sources into portable KTX artifacts. /// @@ -57,9 +62,6 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr /// /// Thrown when any required service is null. /// - /// - /// The shared authoring type generation owner for graph and source extensions. - /// public EditorRenderTargetArtifactProvider( AssetPipeline assets, SerializationRegistry serialization, @@ -68,12 +70,18 @@ public EditorRenderTargetArtifactProvider( ITextureTargetCompiler textureCompiler, IDiagnosticReporter diagnostics ) { - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_shaderCompiler = shaderCompiler ?? throw new ArgumentNullException(nameof(shaderCompiler)); - m_textureCompiler = textureCompiler ?? throw new ArgumentNullException(nameof(textureCompiler)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(shaderCompiler); + ArgumentNullException.ThrowIfNull(textureCompiler); + ArgumentNullException.ThrowIfNull(diagnostics); + m_assets = assets; + m_serialization = serialization; + m_types = types; + m_shaderCompiler = shaderCompiler; + m_textureCompiler = textureCompiler; + m_diagnostics = diagnostics; } /// @@ -115,8 +123,9 @@ out RenderShaderArtifact? artifact ShaderCompileTarget target = m_shaderCompiler.CreateTarget( capabilities, optimize: false, - debugInformation: true); - var key = new ShaderKey(shader.identity.persistentId, target.key, variant.value); + debugInformation: true + ); + var key = new ShaderKey(shader.identity.persistentID, target.key, variant.value); if (!m_shaders.TryGetValue(key, out ShaderEntry? entry)) { entry = new ShaderEntry(); @@ -137,8 +146,8 @@ out RenderShaderArtifact? artifact CompleteShader(key, entry); artifact = entry.artifact; return artifact is not null - ? RenderTargetArtifactStatus.Ready - : entry.status; + ? RenderTargetArtifactStatus.Ready + : entry.status; } } @@ -155,8 +164,10 @@ public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) { ArgumentNullException.ThrowIfNull(artifact); EnsureActive(); - return m_serialization.Deserialize(artifact.definitionData.Span, - AssetSerializationContext.Create(m_assets)); + return m_serialization.Deserialize( + artifact.definitionData.Span, + AssetSerializationContext.Create(m_assets) + ); } /// @@ -183,10 +194,16 @@ GraphicsCapabilities capabilities { _ = GetShaderArtifact(shader, variant, capabilities, out _); ShaderCompileTarget target = m_shaderCompiler.CreateTarget(capabilities, optimize: false, debugInformation: true); - ShaderEntry entry = m_shaders[new(shader.identity.persistentId, target.key, variant.value)]; - return new(entry.pending is not null ? EditorShaderCompilationState.Compiling : entry.latestSucceeded - ? EditorShaderCompilationState.Succeeded : EditorShaderCompilationState.Failed, - entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), entry.sourceDiagnostics); + ShaderEntry entry = m_shaders[new ShaderKey(shader.identity.persistentID, target.key, variant.value)]; + return new( + entry.pending is not null + ? EditorShaderCompilationState.Compiling + : entry.latestSucceeded + ? EditorShaderCompilationState.Succeeded + : EditorShaderCompilationState.Failed, + entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), + entry.sourceDiagnostics + ); } } @@ -213,12 +230,14 @@ public RenderTargetArtifactStatus GetTextureArtifact( RenderTextureArtifactReference texture, out ReadOnlyMemory artifact ) { - if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + if (texture.assetID == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } lock (m_sync) { EnsureActive(); - var key = new TextureKey(texture.assetId, texture.slot.id, texture.slot.colorSpace); + var key = new TextureKey(texture.assetID, texture.slot.id, texture.slot.colorSpace); if (!m_textures.TryGetValue(key, out TextureEntry? entry)) { entry = new TextureEntry(); @@ -226,11 +245,13 @@ out ReadOnlyMemory artifact } CompleteTexture(key, entry); if (entry.attemptedContentVersion != texture.contentRevision) + { StartTexture(texture, entry); + } artifact = entry.artifact ?? ReadOnlyMemory.Empty; return !artifact.IsEmpty - ? RenderTargetArtifactStatus.Ready - : entry.status; + ? RenderTargetArtifactStatus.Ready + : entry.status; } } @@ -242,11 +263,15 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_stopping = true; m_lifetime.Cancel(); foreach (DraftEntry draft in m_drafts.Values) + { Retire(draft.compilation.pending, draft.compilation.cancellation); + } m_drafts.Clear(); foreach (ShaderEntry entry in m_shaders.Values) { @@ -279,24 +304,32 @@ ShaderEntry entry entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.attemptedContentVersion = shader.contentVersion; entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Pending - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Pending + : RenderTargetArtifactStatus.Ready; try { CancellationToken token = entry.cancellation.Token; - entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync(shader, target, variant, m_types, m_serialization, - AssetSerializationContext.Create(m_assets), m_assets, token), token); + entry.pending = RunOwnedAsync(token => m_shaderCompiler.CompileGraphAsync( + shader, + target, + variant, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + m_assets, + token + ), token); } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { entry.cancellation.Dispose(); entry.cancellation = null; - entry.pending = Task.FromResult(new ShaderCompilationResult( - null, - [new ShaderDiagnostic( - "SHADER_COMPILE_EXCEPTION", - DiagnosticSeverity.Error, - exception.Message)])); + entry.pending = Task.FromResult( + new ShaderCompilationResult( + null, + [new ShaderDiagnostic("SHADER_COMPILE_EXCEPTION", DiagnosticSeverity.Error, exception.Message)] + ) + ); } } @@ -306,14 +339,20 @@ ShaderEntry entry ) { Task? pending = entry.pending; if (pending is null || !pending.IsCompleted) + { return; - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + } + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; entry.cancellation?.Dispose(); entry.cancellation = null; if (pending.IsCanceled) + { return; + } ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new ShaderCompilationResult( @@ -321,19 +360,22 @@ ShaderEntry entry [new ShaderDiagnostic( "SHADER_COMPILE_EXCEPTION", DiagnosticSeverity.Error, - pending.Exception?.GetBaseException().Message ?? "Shader compilation failed without an exception.")]); + pending.Exception?.GetBaseException().Message ?? "Shader compilation failed without an exception." + )] + ); entry.latestSucceeded = result.succeeded; entry.sourceDiagnostics = Array.AsReadOnly(result.diagnostics.ToArray()); - var diagnostics = result.diagnostics + List diagnostics = result.diagnostics .Select(diagnostic => new Diagnostic( diagnostic.code, diagnostic.message, diagnostic.severity == DiagnosticSeverity.Error - ? DiagnosticSeverity.Error - : diagnostic.severity == DiagnosticSeverity.Warning - ? DiagnosticSeverity.Warning - : DiagnosticSeverity.Info, - diagnostic.location?.assetPath ?? key.shaderId.ToString("D"))) + ? DiagnosticSeverity.Error + : diagnostic.severity == DiagnosticSeverity.Warning + ? DiagnosticSeverity.Warning + : DiagnosticSeverity.Info, + diagnostic.location?.assetPath ?? key.shaderID.ToString("D") + )) .ToList(); if (result.succeeded) { @@ -342,11 +384,14 @@ [new ShaderDiagnostic( } else if (entry.artifact is not null) { - diagnostics.Add(new Diagnostic( - "RENDER_SHADER_USING_LAST_GOOD", - $"Shader '{key.shaderId:D}' kept its last-good target artifact.", - DiagnosticSeverity.Warning, - key.shaderId.ToString("D"))); + diagnostics.Add( + new Diagnostic( + "RENDER_SHADER_USING_LAST_GOOD", + $"Shader '{key.shaderID:D}' kept its last-good target artifact.", + DiagnosticSeverity.Warning, + key.shaderID.ToString("D") + ) + ); entry.status = RenderTargetArtifactStatus.Ready; } else @@ -365,14 +410,14 @@ TextureEntry entry entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.attemptedContentVersion = texture.contentRevision; entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Pending - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Pending + : RenderTargetArtifactStatus.Ready; try { CancellationToken token = entry.cancellation.Token; - entry.pending = RunOwned(async token => + entry.pending = RunOwnedAsync(async token => { - using ArtifactLease lease = m_assets.AcquireArtifact(texture.assetId, texture.slot.sourceOutputName); + using ArtifactLease lease = m_assets.AcquireArtifact(texture.assetID, texture.slot.sourceOutputName); return await Task.Run( async () => { @@ -380,11 +425,13 @@ TextureEntry entry return await m_textureCompiler.CompileKtxAsync( encoded, texture.slot.colorSpace, - token).ConfigureAwait(false); - }).ConfigureAwait(false); + token + ).ConfigureAwait(false); + } + ).ConfigureAwait(false); }, token); } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { entry.cancellation.Dispose(); entry.cancellation = null; @@ -398,9 +445,13 @@ TextureEntry entry ) { Task? pending = entry.pending; if (pending is null || !pending.IsCompleted) + { return; - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + } + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; entry.cancellation?.Dispose(); entry.cancellation = null; @@ -412,57 +463,96 @@ TextureEntry entry return; } if (pending.IsCanceled) + { return; + } string message = pending.IsCompletedSuccessfully - ? "The texture compiler produced an empty target artifact." - : pending.Exception?.GetBaseException().Message ?? "Texture compilation failed without an exception."; + ? "The texture compiler produced an empty target artifact." + : pending.Exception?.GetBaseException().Message ?? "Texture compilation failed without an exception."; ReplaceDiagnostics(entry.diagnostics, [new Diagnostic( "RENDER_TEXTURE_PREWARM_FAILED", - $"Texture '{key.textureId:D}' kept its last-good target artifact: {message}", + $"Texture '{key.textureID:D}' kept its last-good target artifact: {message}", DiagnosticSeverity.Error, - key.textureId.ToString("D"))]); + key.textureID.ToString("D") + )]); entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Failed - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Failed + : RenderTargetArtifactStatus.Ready; } - private AssetSourceMount GetMount(AssetSourceId source) + private AssetSourceMount GetMount(AssetSourceID source) => m_assets.sourceMounts.FirstOrDefault(mount => mount.id == source) - ?? throw new InvalidOperationException($"Asset source mount '{source}' is not active."); + ?? throw new InvalidOperationException($"Asset source mount '{source}' is not active."); - private Task RunOwned( + private Task RunOwnedAsync( Func> operation, - CancellationToken token + CancellationToken cancellationToken ) { // Admit before starting work or acquiring leases. Ordinary compilation errors are data; // retirement-pending failures stay in the lifetime and retain every dependent owner. - return Unwrap(m_work.RunAsync<(T value, Exception? failure)>(async cancellation => - { - try - { - return (await operation(cancellation).ConfigureAwait(false), null); - } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + return UnwrapAsync( + m_work.RunAsync<(T value, Exception? failure)>(async cancellation => { - return (default!, failure); - } - }, token)); + try + { + return (await operation(cancellation).ConfigureAwait(false), null); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) + { + return (default!, failure); + } + }, cancellationToken) + ); - static async Task Unwrap(Task<(T value, Exception? failure)> task) + static async Task UnwrapAsync(Task<(T value, Exception? failure)> task) { - var result = await task.ConfigureAwait(false); + (T value, Exception? failure) result = await task.ConfigureAwait(false); if (result.failure is not null) - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(result.failure).Throw(); + { + ExceptionDispatchInfo.Capture(result.failure).Throw(); + } return result.value; } } + private void ReplaceDiagnostics( + ISet active, + IEnumerable diagnostics + ) { + ClearDiagnostics(active); + foreach (Diagnostic diagnostic in diagnostics) + { + m_diagnostics.Publish(diagnostic); + active.Add(new DiagnosticIdentity(diagnostic.code, diagnostic.semanticID)); + } + } + + private void ClearDiagnostics(ISet active) + { + foreach (DiagnosticIdentity diagnostic in active) + { + m_diagnostics.Resolve(diagnostic.code, diagnostic.semanticID); + } + active.Clear(); + } + + private void EnsureActive() + { + ObjectDisposedException.ThrowIf(m_disposed, this); + if (m_stopping) + { + throw new InvalidOperationException("A retiring artifact provider cannot accept compilation requests."); + } + } + private static void Retire( Task? task, CancellationTokenSource? cancellation ) { if (cancellation is null) + { return; + } cancellation.Cancel(); if (task is null) { @@ -481,56 +571,33 @@ private static void Retire( cancellation, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - } - - private void ReplaceDiagnostics( - ISet active, - IEnumerable diagnostics - ) { - ClearDiagnostics(active); - foreach (Diagnostic diagnostic in diagnostics) - { - m_diagnostics.Publish(diagnostic); - active.Add(new DiagnosticIdentity(diagnostic.code, diagnostic.semanticId)); - } - } - - private void ClearDiagnostics(ISet active) - { - foreach (DiagnosticIdentity diagnostic in active) - m_diagnostics.Resolve(diagnostic.code, diagnostic.semanticId); - active.Clear(); - } - - private void EnsureActive() - { - ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_stopping) - throw new InvalidOperationException("A retiring artifact provider cannot accept compilation requests."); + TaskScheduler.Default + ); } private readonly record struct ShaderKey( - Guid shaderId, + Guid shaderID, string targetKey, string variantKey ); + private readonly record struct TextureKey( - Guid textureId, - string slotId, + Guid textureID, + string slotID, TextureColorSpace colorSpace ); + private readonly record struct DiagnosticIdentity( string code, - string? semanticId + string? semanticID ); private sealed class ShaderEntry { - internal string semanticHash { get; set; } = ""; + internal string semanticHash { get; set; } = string.Empty; internal long extensionGeneration { get; set; } = long.MinValue; internal bool latestSucceeded { get; set; } - internal IReadOnlyList sourceDiagnostics { get; set; } = Array.Empty(); + internal IReadOnlyList sourceDiagnostics { get; set; } = []; internal long attemptedContentVersion { get; set; } = long.MinValue; internal RenderShaderArtifact? artifact { get; set; } internal RenderTargetArtifactStatus status { get; set; } = RenderTargetArtifactStatus.Unavailable; diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs index 395b5f34f..a5edd7406 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs @@ -7,65 +7,6 @@ namespace Inno.Editor.Rendering; -/// -/// Identifies native compilation state independently of document persistence. -/// -public enum EditorShaderCompilationState -{ - /// - /// The latest semantic candidate is being compiled. - /// - Compiling, - /// - /// The latest semantic candidate compiled successfully. - /// - Succeeded, - /// - /// The latest semantic candidate failed. - /// - Failed -} - -/// -/// Contains detached compiler state without retaining assets, tasks or extension instances. -/// -/// -/// Latest requested semantic candidate state. -/// -/// -/// Whether rendering still uses a previous successful candidate. -/// -/// -/// Immutable latest completed compiler diagnostics. -/// -public sealed record EditorShaderCompilationSnapshot( - EditorShaderCompilationState state, - bool usingLastGood, - IReadOnlyList diagnostics -); - -/// -/// Contains a preview-only immutable candidate, never registered as a canonical asset artifact. -/// -/// -/// Latest draft compilation state. -/// -/// -/// Whether the preview artifact belongs to an earlier successful draft. -/// -/// -/// Latest detached preview diagnostics, separate from project diagnostics. -/// -/// -/// Preview-only complete shader candidate, or null before the first success. -/// -public sealed record EditorShaderDraftCompilationSnapshot( - EditorShaderCompilationState state, - bool usingLastGood, - IReadOnlyList diagnostics, - RenderShaderArtifact? artifact -); - /// /// Schedules Editor shader compilation for the active device without exposing native handles to authoring panels. /// @@ -74,6 +15,7 @@ public sealed class EditorShaderCompilation private readonly EditorRenderTargetArtifactProvider m_provider; private readonly GraphicsCapabilities m_capabilities; private readonly IEditorShaderArtifactValidator? m_validator; + /// /// Pairs the authoring artifact owner with the active device's immutable capability snapshot. /// @@ -87,8 +29,10 @@ public EditorShaderCompilation( EditorRenderTargetArtifactProvider provider, GraphicsCapabilities capabilities ) { - m_provider = provider ?? throw new ArgumentNullException(nameof(provider)); - m_capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities)); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(capabilities); + m_provider = provider; + m_capabilities = capabilities; } /// @@ -104,10 +48,13 @@ public EditorShaderCompilation( EditorRenderTargetArtifactProvider provider, IEditorShaderArtifactValidator validator ) { - m_provider = provider ?? throw new ArgumentNullException(nameof(provider)); - m_validator = validator ?? throw new ArgumentNullException(nameof(validator)); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(validator); + m_provider = provider; + m_validator = validator; m_capabilities = validator.capabilities; } + /// /// Requests current compilation and reads its explicit last-good status. /// @@ -123,8 +70,7 @@ IEditorShaderArtifactValidator validator public EditorShaderCompilationSnapshot Request( ShaderAsset shader, RenderShaderVariant variant - ) - => m_provider.RequestShaderCompilation(shader, variant, m_capabilities); + ) => m_provider.RequestShaderCompilation(shader, variant, m_capabilities); /// /// Reads the canonical Shader candidate for an isolated Material preview without modifying Material values. @@ -161,7 +107,7 @@ RenderShaderVariant variant /// /// Compiles a detached document through the same graph toolchain in an isolated preview cache. /// - /// + /// /// Preview owner identity, independent of canonical artifact lookup. /// /// @@ -177,45 +123,104 @@ RenderShaderVariant variant /// Preview-only state and artifact; calling this method cannot publish to Scene/Game. /// public EditorShaderDraftCompilationSnapshot RequestDraft( - Guid documentId, + Guid documentID, GraphDocument graph, ulong revision, RenderShaderVariant variant ) { EditorShaderDraftCompilationSnapshot compiled = m_provider.RequestDraft( - documentId, + documentID, graph, revision, variant, - m_capabilities); + m_capabilities + ); if (m_validator is null || compiled.state != EditorShaderCompilationState.Succeeded - || compiled.artifact is null) + || compiled.artifact is null + ) { return compiled; + } - EditorShaderArtifactValidationSnapshot validated = m_validator.Request( - documentId, - revision, - compiled.artifact); + EditorShaderArtifactValidationSnapshot validated = m_validator.Request(documentID, revision, compiled.artifact); IReadOnlyList diagnostics = compiled.diagnostics .Concat(validated.diagnostics) .ToArray(); return validated.state switch { - EditorShaderCompilationState.Compiling => new(validated.state, false, diagnostics, null), - EditorShaderCompilationState.Failed => new(validated.state, false, diagnostics, null), - _ => new(validated.state, false, diagnostics, compiled.artifact) + EditorShaderCompilationState.Compiling => new EditorShaderDraftCompilationSnapshot(validated.state, false, diagnostics, null), + EditorShaderCompilationState.Failed => new EditorShaderDraftCompilationSnapshot(validated.state, false, diagnostics, null), + _ => new EditorShaderDraftCompilationSnapshot(validated.state, false, diagnostics, compiled.artifact) }; } /// /// Cancels a document's preview work and retires its cached candidate without touching canonical artifacts. /// - /// + /// /// Closing preview owner identity. /// - public void ReleaseDraft(Guid documentId) + public void ReleaseDraft(Guid documentID) { - m_validator?.Release(documentId); - m_provider.ReleaseDraft(documentId); + m_validator?.Release(documentID); + m_provider.ReleaseDraft(documentID); } } + +/// +/// Identifies native compilation state independently of document persistence. +/// +public enum EditorShaderCompilationState +{ + /// + /// The latest semantic candidate is being compiled. + /// + Compiling, + /// + /// The latest semantic candidate compiled successfully. + /// + Succeeded, + /// + /// The latest semantic candidate failed. + /// + Failed +} + +/// +/// Contains detached compiler state without retaining assets, tasks or extension instances. +/// +/// +/// Latest requested semantic candidate state. +/// +/// +/// Whether rendering still uses a previous successful candidate. +/// +/// +/// Immutable latest completed compiler diagnostics. +/// +public sealed record EditorShaderCompilationSnapshot( + EditorShaderCompilationState state, + bool usingLastGood, + IReadOnlyList diagnostics +); + +/// +/// Contains a preview-only immutable candidate, never registered as a canonical asset artifact. +/// +/// +/// Latest draft compilation state. +/// +/// +/// Whether the preview artifact belongs to an earlier successful draft. +/// +/// +/// Latest detached preview diagnostics, separate from project diagnostics. +/// +/// +/// Preview-only complete shader candidate, or null before the first success. +/// +public sealed record EditorShaderDraftCompilationSnapshot( + EditorShaderCompilationState state, + bool usingLastGood, + IReadOnlyList diagnostics, + RenderShaderArtifact? artifact +); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs similarity index 93% rename from src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs rename to src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs index 70bcb11ab..04b224e4f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs @@ -5,20 +5,6 @@ namespace Inno.Editor.Rendering; -/// -/// Contains active-device validation state for one immutable Editor shader candidate. -/// -/// -/// Pending, successful, or failed validation state. -/// -/// -/// Detached device validation diagnostics. -/// -public sealed record EditorShaderArtifactValidationSnapshot( - EditorShaderCompilationState state, - IReadOnlyList diagnostics -); - /// /// Queues immutable shader candidates for validation at the active device's next frame safety point. /// @@ -32,7 +18,7 @@ public interface IEditorShaderArtifactValidator /// /// Requests or reads validation for an exact document revision and immutable artifact. /// - /// + /// /// Stable Editor document identity. /// /// @@ -45,7 +31,7 @@ public interface IEditorShaderArtifactValidator /// Current detached validation state. /// EditorShaderArtifactValidationSnapshot Request( - Guid documentId, + Guid documentID, ulong revision, RenderShaderArtifact artifact ); @@ -53,8 +39,22 @@ RenderShaderArtifact artifact /// /// Forgets pending and completed validation state owned by one document. /// - /// + /// /// Closing or invalidated document identity. /// - void Release(Guid documentId); + void Release(Guid documentID); } + +/// +/// Contains active-device validation state for one immutable Editor shader candidate. +/// +/// +/// Pending, successful, or failed validation state. +/// +/// +/// Detached device validation diagnostics. +/// +public sealed record EditorShaderArtifactValidationSnapshot( + EditorShaderCompilationState state, + IReadOnlyList diagnostics +); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs new file mode 100644 index 000000000..4afccf755 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs @@ -0,0 +1,59 @@ +using System; +using Inno.Core.Identity; +using Inno.References; + +namespace Inno.Editor.Rendering; + +/// +/// Provides scene content and selection for transient Editor gizmos. +/// +public sealed class EditorGizmoContext +{ + /// + /// Creates a frame-scoped gizmo request. + /// + /// + /// The scenes presented by the Scene viewport. + /// + /// + /// The selected live object, when available. + /// + /// + /// The Scene viewport width. + /// + /// + /// The Scene viewport height. + /// + public EditorGizmoContext( + ContentReadScope content, + RuntimeIdentity? selected, + int pixelWidth, + int pixelHeight + ) { + ArgumentNullException.ThrowIfNull(content); + this.content = content; + this.selected = selected; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the scene roots visible in this Editor viewport. + /// + public ContentReadScope content { get; } + + /// + /// Gets the transient selected identity. + /// + public RuntimeIdentity? selected { get; } + + /// + /// Gets the viewport width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets the viewport height in physical pixels. + /// + public int pixelHeight { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs new file mode 100644 index 000000000..86dee56d9 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Identity; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Holds the transient gizmo primitives for one Scene viewport frame. +/// +public sealed class EditorGizmoFrame : IEditorGizmoSink +{ + private readonly List m_icons = []; + private readonly List m_lines = []; + + /// + /// Gets the ordered selectable icons. + /// + public IReadOnlyList icons => m_icons; + + /// + /// Gets the ordered non-interactive lines. + /// + public IReadOnlyList lines => m_lines; + + /// + /// Appends a selectable scene icon to the current gizmo frame. + /// + /// + /// The object that owns the resulting lifetime and state. + /// + /// + /// The position consumed by icon; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The stable icon identity resolved by the Scene View. + /// + public void Icon( + Identity owner, + Vector3 position, + string iconID + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(iconID); + m_icons.Add(new EditorGizmoIcon(owner, position, iconID)); + } + + /// + /// Appends a world space line to the current gizmo frame. + /// + /// + /// The start consumed by line; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The end consumed by line; ownership remains with the caller unless explicitly stated otherwise. + /// + public void Line( + Vector3 start, + Vector3 end + ) => m_lines.Add(new EditorGizmoLine(start, end)); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs index 2df8ea56b..95ef0ac5b 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs @@ -1,99 +1,8 @@ -using System; -using System.Collections.Generic; using Inno.Core.Identity; using Inno.Core.Mathematics; -using Inno.References; namespace Inno.Editor.Rendering; -/// -/// Provides scene content and selection for transient Editor gizmos. -/// -public sealed class EditorGizmoContext -{ - /// - /// Creates a frame-scoped gizmo request. - /// - /// - /// The scenes presented by the Scene viewport. - /// - /// - /// The selected live object, when available. - /// - /// - /// The Scene viewport width. - /// - /// - /// The Scene viewport height. - /// - public EditorGizmoContext( - ContentReadScope content, - RuntimeIdentity? selected, - int pixelWidth, - int pixelHeight - ) { - this.content = content ?? throw new ArgumentNullException(nameof(content)); - this.selected = selected; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - } - - /// - /// Gets the scene roots visible in this Editor viewport. - /// - public ContentReadScope content { get; } - /// - /// Gets the transient selected identity. - /// - public RuntimeIdentity? selected { get; } - /// - /// Gets the viewport width in physical pixels. - /// - public int pixelWidth { get; } - /// - /// Gets the viewport height in physical pixels. - /// - public int pixelHeight { get; } -} - -/// -/// Receives transient world-space gizmo geometry from independent Editor extensions. -/// -public interface IEditorGizmoSink -{ - /// - /// Adds a visible, selectable icon at an object's world position. - /// - /// - /// The scene object selected when the icon is clicked. - /// - /// - /// The icon position in world space. - /// - /// - /// A stable semantic icon ID. Unknown IDs use the generic scene icon. - /// - void Icon( - Identity owner, - Vector3 position, - string iconId - ); - - /// - /// Adds a non-interactive world-space line, normally for selected bounds. - /// - /// - /// The first world-space endpoint. - /// - /// - /// The second world-space endpoint. - /// - void Line( - Vector3 start, - Vector3 end - ); -} - /// /// Contributes Editor-only icons and bounds without modifying a rendering model. /// @@ -114,30 +23,6 @@ IEditorGizmoSink sink ); } -/// -/// Marks one reloadable Editor gizmo provider. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class EditorGizmoProviderExtensionAttribute : Attribute -{ - /// - /// Creates a provider declaration with a stable identifier. - /// - /// - /// The globally unique provider identifier. - /// - public EditorGizmoProviderExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the stable provider identifier. - /// - public string id { get; } -} - /// /// One selectable Editor icon. /// @@ -147,13 +32,13 @@ public EditorGizmoProviderExtensionAttribute(string id) /// /// The vector3 value used to initialize this instance. /// -/// +/// /// The stable visual identity resolved by the Scene View presentation. /// public readonly record struct EditorGizmoIcon( Identity owner, Vector3 position, - string iconId + string iconID ); /// @@ -169,56 +54,3 @@ public readonly record struct EditorGizmoLine( Vector3 start, Vector3 end ); - -/// -/// Holds the transient gizmo primitives for one Scene viewport frame. -/// -public sealed class EditorGizmoFrame : IEditorGizmoSink -{ - private readonly List m_icons = []; - private readonly List m_lines = []; - - /// - /// Gets the ordered selectable icons. - /// - public IReadOnlyList icons => m_icons; - /// - /// Gets the ordered non-interactive lines. - /// - public IReadOnlyList lines => m_lines; - - /// - /// Appends a selectable scene icon to the current gizmo frame. - /// - /// - /// The object that owns the resulting lifetime and state. - /// - /// - /// The position consumed by icon; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The stable icon identity resolved by the Scene View. - /// - public void Icon( - Identity owner, - Vector3 position, - string iconId - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(iconId); - m_icons.Add(new EditorGizmoIcon(owner, position, iconId)); - } - - /// - /// Appends a world space line to the current gizmo frame. - /// - /// - /// The start consumed by line; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The end consumed by line; ownership remains with the caller unless explicitly stated otherwise. - /// - public void Line( - Vector3 start, - Vector3 end - ) => m_lines.Add(new EditorGizmoLine(start, end)); -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs new file mode 100644 index 000000000..f38d3bc05 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Marks one reloadable Editor gizmo provider. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class EditorGizmoProviderExtensionAttribute : Attribute +{ + /// + /// Creates a provider declaration with a stable identifier. + /// + /// + /// The globally unique provider identifier. + /// + public EditorGizmoProviderExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the stable provider identifier. + /// + public string id { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs index 0fb6f92bd..d771a6bb5 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs @@ -8,7 +8,8 @@ namespace Inno.Editor.Rendering; internal sealed class EditorGizmoProviderRegistry : TypeRegistry { - internal EditorGizmoProviderRegistry(TypeCatalog types) : base(types) { } + internal EditorGizmoProviderRegistry(TypeCatalog types) + : base(types) {} internal Snapshot providers => current; @@ -28,13 +29,16 @@ protected override Snapshot Build(TypeCacheSnapshot types) .OrderBy(static type => type.FullName, StringComparer.Ordinal) .Select(type => new Registration( type.GetCustomAttribute(false)!.id, - CreateExtension(type))) + CreateExtension(type) + )) .OrderBy(static entry => entry.id, StringComparer.Ordinal) .ToArray(); string? duplicate = providers.GroupBy(static entry => entry.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor gizmo provider ID '{duplicate}' is duplicated."); + } return new Snapshot(providers); } @@ -45,9 +49,10 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// The immutable state snapshot consumed by this operation. /// protected override void DisposeSnapshot(Snapshot snapshot) - => DisposeExtensions(snapshot.registrations.Select(static entry => entry.provider)); + => DisposeExtensions(snapshot.registrations.Select(static entry => entry.provider)); internal sealed record Snapshot(Registration[] registrations); + internal sealed record Registration( string id, EditorGizmoProvider provider diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs new file mode 100644 index 000000000..13af0c0b1 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs @@ -0,0 +1,67 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies one preview texture owned by a specific rendering-device generation. +/// +public readonly record struct EditorPreviewHandle +{ + /// + /// Creates one generation-scoped preview handle. + /// + /// + /// Non-zero preview identity. + /// + /// + /// Non-zero rendering-device generation. + /// + /// + /// Positive source width. + /// + /// + /// Positive source height. + /// + public EditorPreviewHandle( + ulong value, + uint deviceGeneration, + int pixelWidth, + int pixelHeight + ) { + if (value == 0 || deviceGeneration == 0) + { + throw new ArgumentOutOfRangeException(nameof(value), "Preview identity and device generation must be non-zero."); + } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + this.value = value; + this.deviceGeneration = deviceGeneration; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the opaque preview identity. + /// + public ulong value { get; } + + /// + /// Gets the rendering-device generation that owns this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets source width in pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets source height in pixels. + /// + public int pixelHeight { get; } + + /// + /// Gets whether this handle identifies a usable generation-scoped preview. + /// + public bool isValid => value != 0 && deviceGeneration != 0 && pixelWidth > 0 && pixelHeight > 0; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs index 3790f728f..c497a4418 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs @@ -1,17 +1,17 @@ -using Inno.References; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; - -using Inno.Scripting.Api; -using Inno.Extensibility.Types; using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Rendering; -using EngineColor = Inno.Core.Mathematics.Color; using Inno.Rendering.Runtime; +using Inno.Scripting.Api; + +using EngineColor = Inno.Core.Mathematics.Color; namespace Inno.Editor.Rendering; @@ -27,11 +27,12 @@ public sealed class EditorRenderingModule : EditorModule private readonly Dictionary m_navigationStates = new(StringComparer.Ordinal); private readonly Dictionary m_contentScopes = new(StringComparer.Ordinal); private readonly Dictionary m_compositionErrors = new(StringComparer.Ordinal); - private readonly Dictionary m_controllerIds = new(StringComparer.Ordinal); - private readonly Dictionary m_manipulationSpaces = - new(StringComparer.Ordinal); - private readonly Dictionary m_presentations = - new(StringComparer.Ordinal); + private readonly Dictionary m_controllerIDs = new(StringComparer.Ordinal); + + private readonly Dictionary m_manipulationSpaces = new(StringComparer.Ordinal); + + private readonly Dictionary m_presentations = new(StringComparer.Ordinal); + private readonly Dictionary m_outputInputs = new(StringComparer.Ordinal); private readonly Dictionary m_outputRoutes = new(StringComparer.Ordinal); private readonly IEditorRenderingHost m_host; @@ -58,17 +59,19 @@ public EditorRenderingModule( EditorInteractions interactions, TypeCatalog types ) { - m_host = host ?? throw new ArgumentNullException(nameof(host)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_contributors = new EditorViewportContributorRegistry( - types ?? throw new ArgumentNullException(nameof(types))); + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(types); + m_host = host; + m_interactions = interactions; + m_contributors = new EditorViewportContributorRegistry(types); m_gizmos = new EditorGizmoProviderRegistry(types); } /// /// Collects Editor-only icons and bounds for the current Scene viewport. /// - /// + /// /// The Scene viewport identity. /// /// @@ -82,19 +85,23 @@ TypeCatalog types /// [ScriptingApiIgnore] public EditorGizmoFrame CollectGizmos( - string viewportId, + string viewportID, int pixelWidth, int pixelHeight ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); var frame = new EditorGizmoFrame(); - if (!m_contentScopes.TryGetValue(viewportId, out ContentReadScope? content)) + if (!m_contentScopes.TryGetValue(viewportID, out ContentReadScope? content)) + { return frame; + } RuntimeIdentity? selected = (m_interactions.selection.selectedTarget as IdentityObject)? .identity.runtimeIdentity; var context = new EditorGizmoContext(content, selected, pixelWidth, pixelHeight); foreach (EditorGizmoProviderRegistry.Registration provider in m_gizmos.providers.registrations) + { provider.provider.Collect(context, frame); + } return frame; } @@ -107,77 +114,82 @@ int pixelHeight /// /// when at least one contributor is registered. /// - public bool HasContributors(EditorViewportKindId kind) => kind.isValid && m_contributors.contributors.byKind.ContainsKey(kind); + public bool HasContributors(EditorViewportKindID kind) => kind.isValid && m_contributors.contributors.byKind.ContainsKey(kind); /// /// Supplies viewport-local input captured by the output panel for this frame. /// - /// + /// /// Stable output identity. /// /// /// Physical-pixel input snapshot. /// public void SetOutputInput( - string viewportId, + string viewportID, RenderOutputInput input ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - m_outputInputs[viewportId] = input ?? throw new ArgumentNullException(nameof(input)); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + ArgumentNullException.ThrowIfNull(input); + m_outputInputs[viewportID] = input; } /// /// Sets the exact model contributor order for an output with several applicable models. /// - /// + /// /// Stable output identity. /// /// /// Explicit contributor route, or null for single-model selection. /// public void SetOutputRoute( - string viewportId, + string viewportID, RenderOutputRoute? route ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); if (route is null) - m_outputRoutes.Remove(viewportId); + { + m_outputRoutes.Remove(viewportID); + } else - m_outputRoutes[viewportId] = route; + { + m_outputRoutes[viewportID] = route; + } } /// /// Gets the most recent isolated contribution or composition failure for one stable viewport. /// - /// + /// /// Stable panel viewport identity. /// /// /// The failure message, or null when no current failure exists. /// - public string? GetCompositionError(string viewportId) + public string? GetCompositionError(string viewportID) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - return m_compositionErrors.GetValueOrDefault(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + return m_compositionErrors.GetValueOrDefault(viewportID); } /// /// Gets the host-owned neutral navigation state for one stable Editor viewport. /// - /// + /// /// Stable panel viewport identity. /// /// /// The reusable navigation state owned by the Editor host. /// [ScriptingApiIgnore] - public EditorViewportNavigationState GetNavigationState(string viewportId) + public EditorViewportNavigationState GetNavigationState(string viewportID) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - if (!m_navigationStates.TryGetValue(viewportId, out EditorViewportNavigationState? state)) + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + if (!m_navigationStates.TryGetValue(viewportID, out EditorViewportNavigationState? state)) { state = new EditorViewportNavigationState(); - m_navigationStates.Add(viewportId, state); + m_navigationStates.Add(viewportID, state); } return state; } @@ -185,7 +197,7 @@ public EditorViewportNavigationState GetNavigationState(string viewportId) /// /// Sets the explicit ordered host content visible to one Editor viewport. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -193,14 +205,16 @@ public EditorViewportNavigationState GetNavigationState(string viewportId) /// [ScriptingApiIgnore] public void SetContentScope( - string viewportId, + string viewportID, ContentReadScope content ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); ArgumentNullException.ThrowIfNull(content); - if (m_contentScopes.Remove(viewportId, out ContentReadScope? previous)) + if (m_contentScopes.Remove(viewportID, out ContentReadScope? previous)) + { previous.Dispose(); - m_contentScopes[viewportId] = content ?? throw new ArgumentNullException(nameof(content)); + } + m_contentScopes[viewportID] = content; } /// @@ -209,7 +223,7 @@ ContentReadScope content /// /// Open viewport purpose. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -225,47 +239,52 @@ ContentReadScope content /// True when a contributor returned a usable navigation profile and became the controller. /// public bool TryConfigureNavigation( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, out EditorViewportNavigationProfile profile ) { profile = EditorViewportNavigationProfile.disabled; - if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + if (!TryCreateContext(kind, viewportID, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return false; - var failures = new List(); + } + List failures = []; EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); foreach (EditorViewportContributorRegistry.Registration registration in contributors - .OrderByDescending(static value => value.attribute.controllerPriority) - .ThenBy(static value => value.attribute.id, StringComparer.Ordinal)) - { + .OrderByDescending(static value => value.attribute.controllerPriority) + .ThenBy(static value => value.attribute.id, StringComparer.Ordinal) + ) { try { EditorViewportNavigationProfile candidate = registration.contributor.ConfigureNavigation(context!) ?? throw new InvalidOperationException("Viewport contributor returned a null navigation profile."); if (!candidate.id.isValid) + { continue; + } profile = candidate; - m_controllerIds[viewportId] = registration.attribute.id; - SetCompositionFailures(viewportId, failures); + m_controllerIDs[viewportID] = registration.attribute.id; + SetCompositionFailures(viewportID, failures); return true; } catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' navigation failed: {exception.Message}"); + $"Viewport contributor '{registration.attribute.id}' navigation failed: {exception.Message}" + ); } } - m_controllerIds.Remove(viewportId); - SetCompositionFailures(viewportId, failures); + m_controllerIDs.Remove(viewportID); + SetCompositionFailures(viewportID, failures); return false; } /// /// Sets presentation preferences supplied to every contributor for one Editor viewport. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -273,17 +292,17 @@ out EditorViewportNavigationProfile profile /// [ScriptingApiIgnore] public void SetPresentation( - string viewportId, + string viewportID, EditorViewportPresentation presentation ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - m_presentations[viewportId] = presentation; + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + m_presentations[viewportID] = presentation; } /// /// Tries to get the manipulation space from the selected controller's latest contribution. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -294,11 +313,11 @@ EditorViewportPresentation presentation /// [ScriptingApiIgnore] public bool TryGetManipulationSpace( - string viewportId, + string viewportID, out EditorViewportManipulationSpace space ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - return m_manipulationSpaces.TryGetValue(viewportId, out space); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + return m_manipulationSpaces.TryGetValue(viewportID, out space); } /// @@ -307,7 +326,7 @@ out EditorViewportManipulationSpace space /// /// Open viewport purpose. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -317,19 +336,21 @@ out EditorViewportManipulationSpace space /// Current target height. /// public void DrawControllerToolbar( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight ) { - if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + if (!TryCreateContext(kind, viewportID, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return; - var failures = new List(); + } + List failures = []; EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); - EditorViewportContributorRegistry.Registration? registration = SelectController(viewportId, contributors); + EditorViewportContributorRegistry.Registration? registration = SelectController(viewportID, contributors); if (registration is null) { - SetCompositionFailures(viewportId, failures); + SetCompositionFailures(viewportID, failures); return; } try @@ -338,10 +359,9 @@ int pixelHeight } catch (Exception exception) { - failures.Add( - $"Viewport contributor '{registration.attribute.id}' toolbar failed: {exception.Message}"); + failures.Add($"Viewport contributor '{registration.attribute.id}' toolbar failed: {exception.Message}"); } - SetCompositionFailures(viewportId, failures); + SetCompositionFailures(viewportID, failures); } /// @@ -350,7 +370,7 @@ int pixelHeight /// /// Open viewport purpose. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -366,48 +386,46 @@ int pixelHeight /// when at least one model contribution was accepted. /// public bool TrySubmit( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, out EditorViewportOutput output ) { output = default; - if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + if (!TryCreateContext(kind, viewportID, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return false; - var failures = new List(); + } + List failures = []; EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); if (contributors.Length == 0) { - PublishViewportStatistics( - kind, - viewportId, - pixelWidth, - pixelHeight, - "Unavailable", - contributorIds: "None"); - m_host.Release(viewportId); - m_controllerIds.Remove(viewportId); - m_manipulationSpaces.Remove(viewportId); + PublishViewportStatistics(kind, viewportID, pixelWidth, pixelHeight, "Unavailable", contributorIDs: "None"); + m_host.Release(viewportID); + m_controllerIDs.Remove(viewportID); + m_manipulationSpaces.Remove(viewportID); failures.Add("No rendering-model contributor accepts the current viewport content."); - SetCompositionFailures(viewportId, failures); + SetCompositionFailures(viewportID, failures); return false; } RenderOutputRoute? route = null; if (contributors.Length > 1) { - if (!m_outputRoutes.TryGetValue(viewportId, out route) + if (!m_outputRoutes.TryGetValue(viewportID, out route) || route.layers.Count != contributors.Length - || route.layers.Any(layer => contributors.All(entry => entry.attribute.id != layer.modelId))) - { - failures.Add("Multiple rendering models accept this output; configure a RenderOutputRoute naming every contributor exactly once: " - + string.Join(", ", contributors.Select(static entry => entry.attribute.id))); - HandleViewportFailure(kind, viewportId, pixelWidth, pixelHeight, contributors, failures); + || route.layers.Any(layer => contributors.All(entry => entry.attribute.id != layer.modelID)) + ) { + failures.Add( + "Multiple rendering models accept this output; configure a RenderOutputRoute naming every contributor exactly once: " + + string.Join(", ", contributors.Select(static entry => entry.attribute.id)) + ); + HandleViewportFailure(kind, viewportID, pixelWidth, pixelHeight, contributors, failures); return false; } contributors = route.layers - .Select(layer => contributors.Single(entry => entry.attribute.id == layer.modelId)) + .Select(layer => contributors.Single(entry => entry.attribute.id == layer.modelID)) .ToArray(); } var accepted = new List(contributors.Length); @@ -418,16 +436,17 @@ out EditorViewportOutput output try { EditorViewportContext modelContext = route is null - ? context! - : context!.ForLayer(route.layers[index]); + ? context! + : context!.ForLayer(route.layers[index]); EditorViewportContribution contribution = registration.contributor.Build(modelContext) ?? throw new InvalidOperationException("Viewport contributor returned a null contribution."); if (targetFormat is RenderTextureFormat selectedFormat - && contribution.targetFormat != selectedFormat) - { + && contribution.targetFormat != selectedFormat + ) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' requested target format " + - $"'{contribution.targetFormat}' while the composition uses '{selectedFormat}'."); + $"Viewport contributor '{registration.attribute.id}' requested target format " + + $"'{contribution.targetFormat}' while the composition uses '{selectedFormat}'." + ); continue; } targetFormat ??= contribution.targetFormat; @@ -440,53 +459,62 @@ out EditorViewportOutput output } if (accepted.Count == 0) { - HandleViewportFailure(kind, viewportId, pixelWidth, pixelHeight, contributors, failures); + HandleViewportFailure(kind, viewportID, pixelWidth, pixelHeight, contributors, failures); return false; } if (accepted.Count != contributors.Length) { - HandleViewportFailure(kind, viewportId, pixelWidth, pixelHeight, contributors, failures); + HandleViewportFailure(kind, viewportID, pixelWidth, pixelHeight, contributors, failures); return false; } try { - output = m_host.Submit(new EditorViewportComposition( - viewportId, - pixelWidth, - pixelHeight, - targetFormat!.Value, - accepted.Select(( - value, - index - ) => new EditorViewportLayer( - value.registration.attribute.id, - value.contribution.pipeline, - value.contribution.data, - route is null ? value.registration.attribute.order : index)))); - EditorViewportContributorRegistry.Registration? controller = SelectController(viewportId, contributors); + output = m_host.Submit( + new EditorViewportComposition( + viewportID, + pixelWidth, + pixelHeight, + targetFormat!.Value, + accepted.Select(( + value, + index + ) => new EditorViewportLayer( + value.registration.attribute.id, + value.contribution.pipeline, + value.contribution.data, + route is null ? value.registration.attribute.order : index + )) + ) + ); + EditorViewportContributorRegistry.Registration? controller = SelectController(viewportID, contributors); EditorViewportContribution? controllerContribution = controller is null ? null : accepted.FirstOrDefault(value => ReferenceEquals(value.registration, controller))?.contribution; if (controllerContribution?.manipulationSpace is EditorViewportManipulationSpace manipulationSpace) - m_manipulationSpaces[viewportId] = manipulationSpace; + { + m_manipulationSpaces[viewportID] = manipulationSpace; + } else - m_manipulationSpaces.Remove(viewportId); + { + m_manipulationSpaces.Remove(viewportID); + } PublishViewportStatistics( kind, - viewportId, + viewportID, pixelWidth, pixelHeight, output.isReady ? "Ready" : "Preparing", string.Join(", ", accepted.Select(static value => value.registration.attribute.id)), - accepted); - SetCompositionFailures(viewportId, failures); + accepted + ); + SetCompositionFailures(viewportID, failures); return true; } catch (Exception exception) { failures.Add($"Viewport composition failed: {exception.Message}"); - HandleViewportFailure(kind, viewportId, pixelWidth, pixelHeight, contributors, failures); + HandleViewportFailure(kind, viewportID, pixelWidth, pixelHeight, contributors, failures); return false; } } @@ -497,7 +525,7 @@ out EditorViewportOutput output /// /// Open viewport purpose. /// - /// + /// /// Stable panel viewport identity. /// /// @@ -516,22 +544,24 @@ out EditorViewportOutput output /// Platform-independent pointer button index. /// public void HandlePointer( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, float x, float y, int button ) { - if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + if (!TryCreateContext(kind, viewportID, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return; - var failures = new List(); + } + List failures = []; EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); - EditorViewportContributorRegistry.Registration? registration = SelectController(viewportId, contributors); + EditorViewportContributorRegistry.Registration? registration = SelectController(viewportID, contributors); if (registration is null) { - SetCompositionFailures(viewportId, failures); + SetCompositionFailures(viewportID, failures); return; } try @@ -541,9 +571,10 @@ int button catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' pointer handler failed: {exception.Message}"); + $"Viewport contributor '{registration.attribute.id}' pointer handler failed: {exception.Message}" + ); } - SetCompositionFailures(viewportId, failures); + SetCompositionFailures(viewportID, failures); } /// @@ -563,19 +594,21 @@ Vector2 logicalSize /// /// Stops retaining one viewport target. /// - /// + /// /// Stable viewport identity. /// - public void Release(string viewportId) + public void Release(string viewportID) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - m_outputInputs.Remove(viewportId); - m_outputRoutes.Remove(viewportId); - m_manipulationSpaces.Remove(viewportId); - if (m_contentScopes.Remove(viewportId, out ContentReadScope? content)) + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + m_outputInputs.Remove(viewportID); + m_outputRoutes.Remove(viewportID); + m_manipulationSpaces.Remove(viewportID); + if (m_contentScopes.Remove(viewportID, out ContentReadScope? content)) + { content.Dispose(); - m_controllerIds.Remove(viewportId); - m_host.Release(viewportId); + } + m_controllerIDs.Remove(viewportID); + m_host.Release(viewportID); } /// @@ -600,8 +633,10 @@ protected override void OnUpdate(EditorContext context) { RenderFrameStatistics? statistics = GraphicsSettings.frameStatistics; if (statistics is null) + { return; - var groupId = new EditorStatisticGroupId("inno.rendering.frame"); + } + var groupID = new EditorStatisticGroupID("inno.rendering.frame"); context.statistics.Publish(new EditorStatistic[] { CreateStatistic("frame", "Frame", statistics.frameIndex.ToString(), 0), @@ -617,7 +652,12 @@ protected override void OnUpdate(EditorContext context) CreateStatistic("allocation-generation", "Allocation Generation", allocations.deviceGeneration.ToString(), 50), CreateStatistic("texture-allocations", "Transient Textures (lifetime)", allocations.textureAllocations.ToString(), 60), CreateStatistic("buffer-allocations", "Transient Buffers (lifetime)", allocations.bufferAllocations.ToString(), 70), - CreateStatistic("framebuffer-allocations", "Transient Framebuffers (lifetime)", allocations.frameBufferAllocations.ToString(), 80) + CreateStatistic( + "framebuffer-allocations", + "Transient Framebuffers (lifetime)", + allocations.frameBufferAllocations.ToString(), + 80 + ) }); } else @@ -634,15 +674,15 @@ EditorStatistic CreateStatistic( string label, string value, int order - ) - => new( - new EditorStatisticId($"inno.rendering.frame.{id}"), - groupId, - "Rendering", - label, - value, - C_RENDERING_STATISTICS_ORDER, - order); + ) => new( + new EditorStatisticID($"inno.rendering.frame.{id}"), + groupID, + "Rendering", + label, + value, + C_RENDERING_STATISTICS_ORDER, + order + ); } /// @@ -659,7 +699,7 @@ protected override void OnStop(EditorContext context) m_navigationStates.Clear(); ClearContentScopes(); m_compositionErrors.Clear(); - m_controllerIds.Clear(); + m_controllerIDs.Clear(); m_manipulationSpaces.Clear(); m_presentations.Clear(); m_outputInputs.Clear(); @@ -676,7 +716,7 @@ protected override void OnDispose() m_navigationStates.Clear(); ClearContentScopes(); m_compositionErrors.Clear(); - m_controllerIds.Clear(); + m_controllerIDs.Clear(); m_manipulationSpaces.Clear(); m_presentations.Clear(); m_outputInputs.Clear(); @@ -687,13 +727,15 @@ protected override void OnDispose() private void ClearContentScopes() { foreach (ContentReadScope scope in m_contentScopes.Values) + { scope.Dispose(); + } m_contentScopes.Clear(); } private bool TryCreateContext( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, out EditorViewportContext? context @@ -703,70 +745,75 @@ out EditorViewportContext? context context = null; return false; } - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); context = new EditorViewportContext( m_context, m_interactions, kind, - viewportId, + viewportID, pixelWidth, pixelHeight, - GetNavigationState(viewportId), - m_contentScopes.GetValueOrDefault(viewportId, ContentReadScope.empty), - m_presentations.GetValueOrDefault( - viewportId, - new EditorViewportPresentation(EngineColor.DARKGRAY)), + GetNavigationState(viewportID), + m_contentScopes.GetValueOrDefault(viewportID, ContentReadScope.empty), + m_presentations.GetValueOrDefault(viewportID, new EditorViewportPresentation(EngineColor.DARKGRAY)), m_host.viewContent, m_host.currentFrameIndex, - m_outputInputs.GetValueOrDefault(viewportId, RenderOutputInput.empty)); + m_outputInputs.GetValueOrDefault(viewportID, RenderOutputInput.empty) + ); return true; } private void PublishViewportStatistics( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, string state, - string contributorIds, + string contributorIDs, IReadOnlyList? contributions = null ) { if (m_context is null) - return; - string groupKey = $"inno.rendering.viewport.{viewportId}"; - var groupId = new EditorStatisticGroupId(groupKey); - string groupName = GetDisplayName(viewportId); - var statistics = new List { + return; + } + string groupKey = $"inno.rendering.viewport.{viewportID}"; + var groupID = new EditorStatisticGroupID(groupKey); + string groupName = GetDisplayName(viewportID); + List statistics = + [ CreateStatistic("kind", "Kind", kind.value, 0), - CreateStatistic("contributors", "Contributors", contributorIds, 10), + CreateStatistic("contributors", "Contributors", contributorIDs, 10), CreateStatistic("state", "State", state, 20), CreateStatistic("resolution", "Resolution", $"{pixelWidth} x {pixelHeight}", 30) - }; + ]; if (contributions is { Count: > 0 }) { - string pipeline = string.Join(", ", contributions.Select(static contribution => - string.IsNullOrWhiteSpace(contribution.contribution.pipeline?.pipelineTypeId) + string pipeline = string.Join( + ", ", + contributions.Select(static contribution => ( + string.IsNullOrWhiteSpace(contribution.contribution.pipeline?.pipelineTypeId) ? GraphicsSettings.defaultPipeline?.pipelineTypeId ?? "Project Default" - : contribution.contribution.pipeline.pipelineTypeId)); - statistics.Add(CreateStatistic( - "pipelines", - "Pipelines", - pipeline, - 40)); - statistics.Add(CreateStatistic( - "format", - "Target Format", - contributions[0].contribution.targetFormat.ToString(), - 50)); - statistics.Add(CreateStatistic( - "order", - "Composition Order", - string.Join(", ", contributions.Select(static contribution => - contribution.registration.attribute.order.ToString())), - 60)); + : contribution.contribution.pipeline.pipelineTypeId + )) + ); + statistics.Add(CreateStatistic("pipelines", "Pipelines", pipeline, 40)); + statistics.Add( + CreateStatistic("format", "Target Format", contributions[0].contribution.targetFormat.ToString(), 50) + ); + statistics.Add( + CreateStatistic( + "order", + "Composition Order", + string.Join( + ", ", + contributions.Select(static contribution => + contribution.registration.attribute.order.ToString()) + ), + 60 + ) + ); } m_context.statistics.Publish(statistics); return; @@ -776,15 +823,15 @@ EditorStatistic CreateStatistic( string label, string value, int order - ) - => new( - new EditorStatisticId($"{groupKey}.{id}"), - groupId, - groupName, - label, - value, - C_VIEWPORT_STATISTICS_ORDER, - order); + ) => new( + new EditorStatisticID($"{groupKey}.{id}"), + groupID, + groupName, + label, + value, + C_VIEWPORT_STATISTICS_ORDER, + order + ); } private EditorViewportContributorRegistry.Registration[] GetApplicableContributors( @@ -792,9 +839,9 @@ private EditorViewportContributorRegistry.Registration[] GetApplicableContributo List failures ) { if (!m_contributors.contributors.byKind.TryGetValue( - context.kind, - out EditorViewportContributorRegistry.Registration[]? registrations)) - { + context.kind, + out EditorViewportContributorRegistry.Registration[]? registrations + )) { return []; } @@ -804,31 +851,34 @@ List failures try { if (registration.contributor.CanContribute(context)) + { applicable.Add(registration); + } } catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' participation check failed: " + - exception.Message); + $"Viewport contributor '{registration.attribute.id}' participation check failed: " + + exception.Message + ); } } return applicable.ToArray(); } private EditorViewportContributorRegistry.Registration? SelectController( - string viewportId, + string viewportID, IReadOnlyList contributors ) { - if (m_controllerIds.TryGetValue(viewportId, out string? controllerId)) + if (m_controllerIDs.TryGetValue(viewportID, out string? controllerID)) { EditorViewportContributorRegistry.Registration? selected = contributors.FirstOrDefault( - contributor => string.Equals( - contributor.attribute.id, - controllerId, - StringComparison.Ordinal)); + contributor => string.Equals(contributor.attribute.id, controllerID, StringComparison.Ordinal) + ); if (selected is not null) + { return selected; + } } return contributors @@ -838,8 +888,8 @@ List failures } private void HandleViewportFailure( - EditorViewportKindId kind, - string viewportId, + EditorViewportKindID kind, + string viewportID, int pixelWidth, int pixelHeight, IReadOnlyList contributors, @@ -847,33 +897,33 @@ List failures ) { PublishViewportStatistics( kind, - viewportId, + viewportID, pixelWidth, pixelHeight, "Failed", - string.Join(", ", contributors.Select(static contributor => contributor.attribute.id))); - m_host.Release(viewportId); - m_controllerIds.Remove(viewportId); - m_manipulationSpaces.Remove(viewportId); - SetCompositionFailures(viewportId, failures); + string.Join(", ", contributors.Select(static contributor => contributor.attribute.id)) + ); + m_host.Release(viewportID); + m_controllerIDs.Remove(viewportID); + m_manipulationSpaces.Remove(viewportID); + SetCompositionFailures(viewportID, failures); } private void SetCompositionFailures( - string viewportId, + string viewportID, IReadOnlyList failures ) { string[] distinct = failures.Distinct(StringComparer.Ordinal).ToArray(); if (distinct.Length == 0) - m_compositionErrors.Remove(viewportId); + { + m_compositionErrors.Remove(viewportID); + } else - m_compositionErrors[viewportId] = string.Join(Environment.NewLine, distinct); + { + m_compositionErrors[viewportID] = string.Join(Environment.NewLine, distinct); + } } - private sealed record AcceptedContribution( - EditorViewportContributorRegistry.Registration registration, - EditorViewportContribution contribution - ); - private static string GetDisplayName(string identifier) { char[] characters = identifier.Replace('-', ' ').Replace('_', ' ').ToCharArray(); @@ -886,10 +936,17 @@ private static string GetDisplayName(string identifier) continue; } if (!capitalize) + { continue; + } characters[i] = char.ToUpperInvariant(characters[i]); capitalize = false; } return new string(characters); } + + private sealed record AcceptedContribution( + EditorViewportContributorRegistry.Registration registration, + EditorViewportContribution contribution + ); } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs new file mode 100644 index 000000000..60d6730ef --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Rendering; + +namespace Inno.Editor.Rendering; + +/// +/// Describes a complete ordered set of rendering-model layers targeting one Editor viewport. +/// +public sealed class EditorViewportComposition +{ + private readonly IReadOnlyList m_layers; + + /// + /// Creates an immutable viewport composition. + /// + /// + /// Stable panel viewport identity. + /// + /// + /// Positive target width. + /// + /// + /// Positive target height. + /// + /// + /// Shared presentation target format required by every layer. + /// + /// + /// Ordered non-empty rendering-model layer collection. + /// + public EditorViewportComposition( + string viewportID, + int pixelWidth, + int pixelHeight, + RenderTextureFormat targetFormat, + IEnumerable layers + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + ArgumentNullException.ThrowIfNull(layers); + EditorViewportLayer[] materializedLayers = layers.ToArray(); + if (materializedLayers.Length == 0) + { + throw new ArgumentException("A viewport composition requires at least one model layer.", nameof(layers)); + } + if (materializedLayers.Any(static layer => layer is null)) + { + throw new ArgumentException("A viewport composition cannot contain null model layers.", nameof(layers)); + } + if (materializedLayers.Select(static layer => layer.contributorID).Distinct(StringComparer.Ordinal).Count() + != materializedLayers.Length + ) { + throw new ArgumentException("Viewport contributor identities must be unique.", nameof(layers)); + } + m_layers = Array.AsReadOnly( + materializedLayers + .OrderBy(static layer => layer.order) + .ThenBy(static layer => layer.contributorID, StringComparer.Ordinal) + .ToArray() + ); + this.viewportID = viewportID; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + this.targetFormat = targetFormat; + } + + /// + /// Gets the stable viewport identity. + /// + public string viewportID { get; } + + /// + /// Gets the target width. + /// + public int pixelWidth { get; } + + /// + /// Gets the target height. + /// + public int pixelHeight { get; } + + /// + /// Gets the shared presentation target format. + /// + public RenderTextureFormat targetFormat { get; } + + /// + /// Gets the ordered rendering-model layers. + /// + public IReadOnlyList layers => m_layers; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs new file mode 100644 index 000000000..2934ed803 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs @@ -0,0 +1,120 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.References; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Supplies frame-only Editor interaction and output dimensions to a contributor. +/// +public sealed class EditorViewportContext +{ + internal EditorViewportContext( + EditorContext editor, + EditorInteractions interactions, + EditorViewportKindID kind, + string viewportID, + int pixelWidth, + int pixelHeight, + EditorViewportNavigationState navigation, + ContentReadScope content, + EditorViewportPresentation presentation, + IViewContentCollector viewContent, + ulong frameIndex, + RenderOutputInput input + ) { + this.editor = editor; + this.interactions = interactions; + this.kind = kind; + this.viewportID = viewportID; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + this.navigation = navigation; + this.content = content; + this.presentation = presentation; + this.viewContent = viewContent; + this.frameIndex = frameIndex; + this.input = input; + } + + /// + /// Gets the current Editor context. + /// + public EditorContext editor { get; } + + /// + /// Gets the shared Editor interaction and selection service. + /// + public EditorInteractions interactions { get; } + + /// + /// Gets the open viewport purpose. + /// + public EditorViewportKindID kind { get; } + + /// + /// Gets the stable panel viewport identity. + /// + public string viewportID { get; } + + /// + /// Gets target width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets target height in physical pixels. + /// + public int pixelHeight { get; } + + /// + /// Gets host-owned neutral navigation state that the selected controller can map to its camera model. + /// + public EditorViewportNavigationState navigation { get; } + + /// + /// Gets the explicit ordered host content visible to this viewport. + /// + public ContentReadScope content { get; } + + /// + /// Gets host-selected presentation preferences for this viewport. + /// + public EditorViewportPresentation presentation { get; } + + /// + /// Gets the active generation's model-independent world-content collector. + /// + public IViewContentCollector viewContent { get; } + + /// + /// Gets the frame index shared by all Editor views in this output frame. + /// + public ulong frameIndex { get; } + + /// + /// Gets input located in this viewport's physical pixels. + /// + public RenderOutputInput input { get; } + + internal EditorViewportContext ForLayer(RenderOutputLayer layer) + { + ArgumentNullException.ThrowIfNull(layer); + return new EditorViewportContext( + editor, + interactions, + kind, + viewportID, + pixelWidth, + pixelHeight, + navigation, + content, + presentation, + new SelectedViewContentCollector(viewContent, layer.sourceIDs), + frameIndex, + input + ); + } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs new file mode 100644 index 000000000..efc5186c5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs @@ -0,0 +1,60 @@ +using System; +using Inno.Rendering; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Returns one rendering-model contribution without exposing a GPU backend. +/// +public sealed class EditorViewportContribution +{ + /// + /// Creates a viewport model contribution. + /// + /// + /// Pipeline-defined frame-only data. + /// + /// + /// Contributor-selected pipeline, or null for the project default. + /// + /// + /// Presentation target format expected by the pipeline. + /// + /// + /// Optional exact view/projection contract for host-owned transform manipulation tools. + /// + public EditorViewportContribution( + RenderFrameData data, + RenderPipelineAsset? pipeline = null, + RenderTextureFormat targetFormat = RenderTextureFormat.RGBA8Srgb, + EditorViewportManipulationSpace? manipulationSpace = null + ) { + ArgumentNullException.ThrowIfNull(data); + this.data = data; + this.pipeline = pipeline; + this.targetFormat = targetFormat; + this.manipulationSpace = manipulationSpace; + } + + /// + /// Gets pipeline-defined frame-only data. + /// + public RenderFrameData data { get; } + + /// + /// Gets the selected pipeline, or null for the project default. + /// + public RenderPipelineAsset? pipeline { get; } + + /// + /// Gets the presentation target format expected by the pipeline. + /// + public RenderTextureFormat targetFormat { get; } + + /// + /// Gets the optional exact view/projection contract used by host-owned transform manipulation tools. + /// + public EditorViewportManipulationSpace? manipulationSpace { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs index 112f6145a..a8fd580c9 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs @@ -1,419 +1,5 @@ -using Inno.References; -using System; - -using Inno.Core.Mathematics; -using Inno.Editor.Core; -using Inno.Editor.Interactions; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; - namespace Inno.Editor.Rendering; -/// -/// Identifies one open Editor viewport purpose without prescribing rendering semantics. -/// -public readonly record struct EditorViewportKindId -{ - /// - /// Creates a stable viewport purpose identifier. - /// - /// - /// Globally stable viewport purpose. - /// - public EditorViewportKindId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the stable viewport purpose. - /// - public string value { get; } - - /// - /// Gets whether this identifier is usable. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Marks a reloadable rendering-model contributor for one Editor viewport purpose. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class EditorViewportContributorExtensionAttribute : Attribute -{ - /// - /// Creates a viewport contributor declaration. - /// - /// - /// Globally stable contributor identity. - /// - /// - /// Open viewport purpose handled by the contributor. - /// - /// - /// Ascending model-composition order within the viewport. - /// - /// - /// Priority used to select the contributor that owns navigation, tools, and pointer interaction. - /// - public EditorViewportContributorExtensionAttribute( - string id, - string kind, - int order = 0, - int controllerPriority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(kind); - this.id = id.Trim(); - this.kind = new EditorViewportKindId(kind); - this.order = order; - this.controllerPriority = controllerPriority; - } - - /// - /// Gets the globally stable contributor identity. - /// - public string id { get; } - - /// - /// Gets the open viewport purpose handled by the contributor. - /// - public EditorViewportKindId kind { get; } - - /// - /// Gets ascending model-composition order. - /// - public int order { get; } - - /// - /// Gets the priority used to select the viewport interaction controller. - /// - public int controllerPriority { get; } -} - -/// -/// Supplies frame-only Editor interaction and output dimensions to a contributor. -/// -public sealed class EditorViewportContext -{ - internal EditorViewportContext( - EditorContext editor, - EditorInteractions interactions, - EditorViewportKindId kind, - string viewportId, - int pixelWidth, - int pixelHeight, - EditorViewportNavigationState navigation, - ContentReadScope content, - EditorViewportPresentation presentation, - IViewContentCollector viewContent, - ulong frameIndex, - RenderOutputInput input - ) { - this.editor = editor; - this.interactions = interactions; - this.kind = kind; - this.viewportId = viewportId; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - this.navigation = navigation; - this.content = content; - this.presentation = presentation; - this.viewContent = viewContent; - this.frameIndex = frameIndex; - this.input = input; - } - - internal EditorViewportContext ForLayer(RenderOutputLayer layer) - { - ArgumentNullException.ThrowIfNull(layer); - return new EditorViewportContext(editor, interactions, kind, viewportId, - pixelWidth, pixelHeight, navigation, content, presentation, - new SelectedViewContentCollector(viewContent, layer.sourceIds), frameIndex, input); - } - - /// - /// Gets the current Editor context. - /// - public EditorContext editor { get; } - - /// - /// Gets the shared Editor interaction and selection service. - /// - public EditorInteractions interactions { get; } - - /// - /// Gets the open viewport purpose. - /// - public EditorViewportKindId kind { get; } - - /// - /// Gets the stable panel viewport identity. - /// - public string viewportId { get; } - - /// - /// Gets target width in physical pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets target height in physical pixels. - /// - public int pixelHeight { get; } - - /// - /// Gets host-owned neutral navigation state that the selected controller can map to its camera model. - /// - public EditorViewportNavigationState navigation { get; } - - /// - /// Gets the explicit ordered host content visible to this viewport. - /// - public ContentReadScope content { get; } - - /// - /// Gets host-selected presentation preferences for this viewport. - /// - public EditorViewportPresentation presentation { get; } - - /// - /// Gets the active generation's model-independent world-content collector. - /// - public IViewContentCollector viewContent { get; } - - /// - /// Gets the frame index shared by all Editor views in this output frame. - /// - public ulong frameIndex { get; } - /// - /// Gets input located in this viewport's physical pixels. - /// - public RenderOutputInput input { get; } -} - -/// -/// Describes host-selected presentation preferences without prescribing rendering behavior. -/// -public readonly record struct EditorViewportPresentation -{ - /// - /// Creates presentation preferences for one Editor viewport. - /// - /// - /// Linear clear color preferred by the host panel. - /// - /// - /// Physical render pixels per logical presentation unit. - /// - public EditorViewportPresentation( - Color backgroundColor, - float pixelDensity = 1f - ) { - if (!float.IsFinite(pixelDensity) || pixelDensity <= 0f) - throw new ArgumentOutOfRangeException(nameof(pixelDensity)); - this.backgroundColor = backgroundColor; - this.pixelDensity = pixelDensity; - } - - /// - /// Gets the linear clear color preferred by the host panel. - /// - public Color backgroundColor { get; } - - /// - /// Gets physical render pixels per logical presentation unit. - /// - public float pixelDensity { get; } -} - -/// -/// Selects whether transform handles use all axes or a contributor-declared planar orientation. -/// -public enum EditorViewportManipulationPlane -{ - /// - /// Keeps the full three-dimensional translation, rotation, and scale controls. - /// - Spatial, - - /// - /// Uses the X/Y translation and scale axes with the Z rotation handle. - /// - XY, - - /// - /// Uses the X/Z translation and scale axes with the Y rotation handle. - /// - XZ, - - /// - /// Uses the Y/Z translation and scale axes with the X rotation handle. - /// - YZ -} - -/// -/// Describes the exact backend-neutral view and projection used to draw a viewport so host tools can manipulate -/// selected scene transforms without knowing the controller's camera model. -/// -public readonly record struct EditorViewportManipulationSpace -{ - /// - /// Creates a manipulation space matching one rendered viewport frame. - /// - /// - /// World-to-view matrix used by the submitted frame. - /// - /// - /// View-to-clip matrix used by the submitted frame. - /// - /// - /// Whether the projection is orthographic; this does not imply planar manipulation. - /// - /// - /// The contributor-selected transform handle orientation, independent of projection. - /// - /// - /// The plane is not one of the defined neutral manipulation orientations. - /// - public EditorViewportManipulationSpace( - Matrix viewMatrix, - Matrix projectionMatrix, - bool isOrthographic, - EditorViewportManipulationPlane plane = EditorViewportManipulationPlane.Spatial - ) { - if (!Enum.IsDefined(plane)) - throw new ArgumentOutOfRangeException(nameof(plane)); - this.viewMatrix = viewMatrix; - this.projectionMatrix = projectionMatrix; - this.isOrthographic = isOrthographic; - this.plane = plane; - } - - /// - /// Gets the world-to-view matrix used by the submitted frame. - /// - public Matrix viewMatrix { get; } - - /// - /// Gets the view-to-clip matrix used by the submitted frame. - /// - public Matrix projectionMatrix { get; } - - /// - /// Gets whether the submitted frame used an orthographic projection. - /// - public bool isOrthographic { get; } - - /// - /// Gets the contributor-declared neutral manipulation plane, or Spatial for all axes. - /// - public EditorViewportManipulationPlane plane { get; } -} - -/// -/// Returns one rendering-model contribution without exposing a GPU backend. -/// -public sealed class EditorViewportContribution -{ - /// - /// Creates a viewport model contribution. - /// - /// - /// Pipeline-defined frame-only data. - /// - /// - /// Contributor-selected pipeline, or null for the project default. - /// - /// - /// Presentation target format expected by the pipeline. - /// - /// - /// Optional exact view/projection contract for host-owned transform manipulation tools. - /// - public EditorViewportContribution( - RenderFrameData data, - RenderPipelineAsset? pipeline = null, - RenderTextureFormat targetFormat = RenderTextureFormat.RGBA8Srgb, - EditorViewportManipulationSpace? manipulationSpace = null - ) { - this.data = data ?? throw new ArgumentNullException(nameof(data)); - this.pipeline = pipeline; - this.targetFormat = targetFormat; - this.manipulationSpace = manipulationSpace; - } - - /// - /// Gets pipeline-defined frame-only data. - /// - public RenderFrameData data { get; } - - /// - /// Gets the selected pipeline, or null for the project default. - /// - public RenderPipelineAsset? pipeline { get; } - - /// - /// Gets the presentation target format expected by the pipeline. - /// - public RenderTextureFormat targetFormat { get; } - - /// - /// Gets the optional exact view/projection contract used by host-owned transform manipulation tools. - /// - public EditorViewportManipulationSpace? manipulationSpace { get; } -} - -/// -/// Supplies normalized pointer interaction over one rendered viewport. -/// -public sealed class EditorViewportPointerContext -{ - internal EditorViewportPointerContext( - EditorViewportContext viewport, - float x, - float y, - int button - ) { - this.viewport = viewport; - this.x = Math.Clamp(x, 0f, 1f); - this.y = Math.Clamp(y, 0f, 1f); - this.button = button; - } - - /// - /// Gets the owning frame-only viewport context. - /// - public EditorViewportContext viewport { get; } - - /// - /// Gets normalized horizontal pointer position. - /// - public float x { get; } - - /// - /// Gets normalized vertical pointer position. - /// - public float y { get; } - - /// - /// Gets the platform-independent pointer button index. - /// - public int button { get; } -} - /// /// Contributes one rendering model while the host owns viewport composition, targets, and presentation. /// @@ -422,9 +8,7 @@ public abstract class EditorViewportContributor /// /// Creates a parameterless reloadable viewport contributor. /// - protected EditorViewportContributor() - { - } + protected EditorViewportContributor() {} /// /// Determines whether this rendering model participates in the supplied viewport content. @@ -466,9 +50,7 @@ public virtual EditorViewportNavigationProfile ConfigureNavigation(EditorViewpor /// /// Frame-only Editor and viewport context. /// - public virtual void DrawToolbar(EditorViewportContext context) - { - } + public virtual void DrawToolbar(EditorViewportContext context) {} /// /// Handles one pointer click when this contributor owns viewport interaction. @@ -476,7 +58,28 @@ public virtual void DrawToolbar(EditorViewportContext context) /// /// Normalized frame-only pointer context. /// - public virtual void HandlePointer(EditorViewportPointerContext context) - { - } + public virtual void HandlePointer(EditorViewportPointerContext context) {} +} + +/// +/// Selects whether transform handles use all axes or a contributor-declared planar orientation. +/// +public enum EditorViewportManipulationPlane +{ + /// + /// Keeps the full three-dimensional translation, rotation, and scale controls. + /// + Spatial, + /// + /// Uses the X/Y translation and scale axes with the Z rotation handle. + /// + XY, + /// + /// Uses the X/Z translation and scale axes with the Y rotation handle. + /// + XZ, + /// + /// Uses the Y/Z translation and scale axes with the X rotation handle. + /// + YZ } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs new file mode 100644 index 000000000..e3fc96731 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs @@ -0,0 +1,59 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Marks a reloadable rendering-model contributor for one Editor viewport purpose. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class EditorViewportContributorExtensionAttribute : Attribute +{ + /// + /// Creates a viewport contributor declaration. + /// + /// + /// Globally stable contributor identity. + /// + /// + /// Open viewport purpose handled by the contributor. + /// + /// + /// Ascending model-composition order within the viewport. + /// + /// + /// Priority used to select the contributor that owns navigation, tools, and pointer interaction. + /// + public EditorViewportContributorExtensionAttribute( + string id, + string kind, + int order = 0, + int controllerPriority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(kind); + this.id = id.Trim(); + this.kind = new EditorViewportKindID(kind); + this.order = order; + this.controllerPriority = controllerPriority; + } + + /// + /// Gets the globally stable contributor identity. + /// + public string id { get; } + + /// + /// Gets the open viewport purpose handled by the contributor. + /// + public EditorViewportKindID kind { get; } + + /// + /// Gets ascending model-composition order. + /// + public int order { get; } + + /// + /// Gets the priority used to select the viewport interaction controller. + /// + public int controllerPriority { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs index d261127da..8b010fbb6 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs @@ -2,18 +2,14 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Editor.Rendering; -internal sealed class EditorViewportContributorRegistry - : TypeRegistry +internal sealed class EditorViewportContributorRegistry : TypeRegistry { internal EditorViewportContributorRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot contributors => current; @@ -36,12 +32,14 @@ protected override Snapshot Build(TypeCacheSnapshot types) .OrderBy(static registration => registration.attribute.order) .ThenBy(static registration => registration.attribute.id, StringComparer.Ordinal) .ToArray(); - string? duplicateId = registrations + string? duplicateID = registrations .GroupBy(static registration => registration.attribute.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; - if (duplicateId is not null) - throw new InvalidOperationException($"Editor viewport contributor ID '{duplicateId}' is duplicated."); - IReadOnlyDictionary byKind = registrations + if (duplicateID is not null) + { + throw new InvalidOperationException($"Editor viewport contributor ID '{duplicateID}' is duplicated."); + } + IReadOnlyDictionary byKind = registrations .GroupBy(static registration => registration.attribute.kind) .ToDictionary(static group => group.Key, static group => group.ToArray()); return new Snapshot(types.version, registrations, byKind); @@ -59,12 +57,13 @@ protected override void DisposeSnapshot(Snapshot snapshot) private Registration CreateRegistration(Type type) => new( type.GetCustomAttribute(inherit: false)!, - CreateExtension(type)); + CreateExtension(type) + ); internal sealed record Snapshot( long revision, Registration[] registrations, - IReadOnlyDictionary byKind + IReadOnlyDictionary byKind ); internal sealed record Registration( diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs new file mode 100644 index 000000000..5e0a480a2 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs @@ -0,0 +1,53 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes a world-space sphere that can be framed by host navigation. +/// +public readonly record struct EditorViewportFocusBounds +{ + /// + /// Creates a finite focus bound. + /// + /// + /// World-space focus center. + /// + /// + /// Non-negative world-space radius. + /// + /// + /// Thrown when the center contains a non-finite value. + /// + /// + /// Thrown when the radius is negative or non-finite. + /// + public EditorViewportFocusBounds( + Vector3 center, + float radius + ) { + if (!IsFinite(center)) + { + throw new ArgumentException("Focus center components must be finite.", nameof(center)); + } + if (!float.IsFinite(radius) || radius < 0f) + { + throw new ArgumentOutOfRangeException(nameof(radius)); + } + this.center = center; + this.radius = radius; + } + + /// + /// Gets the world-space focus center. + /// + public Vector3 center { get; } + + /// + /// Gets the non-negative world-space radius. + /// + public float radius { get; } + + private static bool IsFinite(Vector3 value) => float.IsFinite(value.x) && float.IsFinite(value.y) && float.IsFinite(value.z); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs new file mode 100644 index 000000000..9dad5ba0c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies one open Editor viewport purpose without prescribing rendering semantics. +/// +public readonly record struct EditorViewportKindID +{ + /// + /// Creates a stable viewport purpose identifier. + /// + /// + /// Globally stable viewport purpose. + /// + public EditorViewportKindID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the stable viewport purpose. + /// + public string value { get; } + + /// + /// Gets whether this identifier is usable. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs new file mode 100644 index 000000000..cd4d3e74e --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs @@ -0,0 +1,60 @@ +using System; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Describes one model-neutral layer in an Editor viewport composition. +/// +public sealed class EditorViewportLayer +{ + /// + /// Creates one immutable model-neutral viewport layer. + /// + /// + /// Stable identity of the rendering-model contributor that produced the layer. + /// + /// + /// Contributor-selected pipeline, or null for the project default. + /// + /// + /// Contributor-defined frame-only data. + /// + /// + /// Ascending model-composition order. + /// + public EditorViewportLayer( + string contributorID, + RenderPipelineAsset? pipeline, + RenderFrameData data, + int order + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(contributorID); + ArgumentNullException.ThrowIfNull(data); + this.contributorID = contributorID; + this.pipeline = pipeline; + this.data = data; + this.order = order; + } + + /// + /// Gets the stable identity of the rendering-model contributor. + /// + public string contributorID { get; } + + /// + /// Gets the contributor-selected pipeline, or null for the project default. + /// + public RenderPipelineAsset? pipeline { get; } + + /// + /// Gets contributor-defined frame-only data. + /// + public RenderFrameData data { get; } + + /// + /// Gets ascending model-composition order. + /// + public int order { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs new file mode 100644 index 000000000..f48b2f977 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes the exact backend-neutral view and projection used to draw a viewport so host tools can manipulate +/// selected scene transforms without knowing the controller's camera model. +/// +public readonly record struct EditorViewportManipulationSpace +{ + /// + /// Creates a manipulation space matching one rendered viewport frame. + /// + /// + /// World-to-view matrix used by the submitted frame. + /// + /// + /// View-to-clip matrix used by the submitted frame. + /// + /// + /// Whether the projection is orthographic; this does not imply planar manipulation. + /// + /// + /// The contributor-selected transform handle orientation, independent of projection. + /// + /// + /// The plane is not one of the defined neutral manipulation orientations. + /// + public EditorViewportManipulationSpace( + Matrix viewMatrix, + Matrix projectionMatrix, + bool isOrthographic, + EditorViewportManipulationPlane plane = EditorViewportManipulationPlane.Spatial + ) { + if (!Enum.IsDefined(plane)) + { + throw new ArgumentOutOfRangeException(nameof(plane)); + } + this.viewMatrix = viewMatrix; + this.projectionMatrix = projectionMatrix; + this.isOrthographic = isOrthographic; + this.plane = plane; + } + + /// + /// Gets the world-to-view matrix used by the submitted frame. + /// + public Matrix viewMatrix { get; } + + /// + /// Gets the view-to-clip matrix used by the submitted frame. + /// + public Matrix projectionMatrix { get; } + + /// + /// Gets whether the submitted frame used an orthographic projection. + /// + public bool isOrthographic { get; } + + /// + /// Gets the contributor-declared neutral manipulation plane, or Spatial for all axes. + /// + public EditorViewportManipulationPlane plane { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs deleted file mode 100644 index 23ab6ed7b..000000000 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs +++ /dev/null @@ -1,595 +0,0 @@ -using System; - -using Inno.Core.Mathematics; - -namespace Inno.Editor.Rendering; - -/// -/// Identifies the projection family represented by neutral Editor viewport navigation state. -/// -public enum EditorViewportProjection -{ - /// - /// Uses a parallel projection controlled by an orthographic half-height. - /// - Orthographic, - - /// - /// Uses a perspective projection controlled by a vertical field of view. - /// - Perspective -} - -/// -/// Identifies the active interaction model without prescribing a rendering camera type. -/// -public enum EditorViewportNavigationMode -{ - /// - /// Pans and zooms over a provider-defined plane. - /// - Planar, - - /// - /// Rotates around a focus pivot and dollies along the view direction. - /// - Orbit, - - /// - /// Moves and looks freely from the current view position. - /// - Fly -} - -/// -/// Declares navigation operations supported by one viewport interaction controller. -/// -[Flags] -public enum EditorViewportNavigationCapabilities -{ - /// - /// Disables host-owned navigation. - /// - None = 0, - - /// - /// Allows translating the view parallel to its image plane. - /// - Pan = 1 << 0, - - /// - /// Allows changing orthographic size or perspective focus distance. - /// - Zoom = 1 << 1, - - /// - /// Allows the complete plane-oriented pan and zoom interaction model. - /// - Planar = Pan | Zoom, - - /// - /// Allows pivot-oriented orbit and dolly. - /// - Orbit = 1 << 2, - - /// - /// Allows free-look movement. - /// - Fly = 1 << 3, - - /// - /// Allows framing a provider-supplied or host-derived selection bound. - /// - FrameSelection = 1 << 4 -} - -/// -/// Identifies a provider-defined navigation profile across reload generations. -/// -public readonly record struct EditorViewportNavigationProfileId -{ - /// - /// Creates a stable profile identifier. - /// - /// - /// Globally stable profile identity. - /// - public EditorViewportNavigationProfileId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the stable profile identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes a world-space sphere that can be framed by host navigation. -/// -public readonly record struct EditorViewportFocusBounds -{ - /// - /// Creates a finite focus bound. - /// - /// - /// World-space focus center. - /// - /// - /// Non-negative world-space radius. - /// - /// - /// Thrown when the center contains a non-finite value. - /// - /// - /// Thrown when the radius is negative or non-finite. - /// - public EditorViewportFocusBounds( - Vector3 center, - float radius - ) { - if (!IsFinite(center)) - throw new ArgumentException("Focus center components must be finite.", nameof(center)); - if (!float.IsFinite(radius) || radius < 0f) - throw new ArgumentOutOfRangeException(nameof(radius)); - this.center = center; - this.radius = radius; - } - - /// - /// Gets the world-space focus center. - /// - public Vector3 center { get; } - - /// - /// Gets the non-negative world-space radius. - /// - public float radius { get; } - - private static bool IsFinite(Vector3 value) => float.IsFinite(value.x) && float.IsFinite(value.y) && float.IsFinite(value.z); -} - -/// -/// Describes how the host may navigate one provider-owned viewport without exposing the provider's camera model. -/// -public sealed class EditorViewportNavigationProfile -{ - /// - /// Creates a provider-defined navigation profile. - /// - /// - /// Stable profile identity. - /// - /// - /// Operations accepted by the provider. - /// - /// - /// Preferred mode when current state is unsupported. - /// - public EditorViewportNavigationProfile( - EditorViewportNavigationProfileId id, - EditorViewportNavigationCapabilities capabilities, - EditorViewportNavigationMode defaultMode - ) { - if (!id.isValid) - throw new ArgumentException("A valid navigation profile ID is required.", nameof(id)); - const EditorViewportNavigationCapabilities validCapabilities - = EditorViewportNavigationCapabilities.Pan - | EditorViewportNavigationCapabilities.Zoom - | EditorViewportNavigationCapabilities.Orbit - | EditorViewportNavigationCapabilities.Fly - | EditorViewportNavigationCapabilities.FrameSelection; - if ((capabilities & ~validCapabilities) != 0) - throw new ArgumentOutOfRangeException(nameof(capabilities)); - if (capabilities != EditorViewportNavigationCapabilities.None - && !SupportsMode(capabilities, defaultMode)) - { - throw new ArgumentException( - "The default navigation mode must be enabled by the profile capabilities.", - nameof(defaultMode)); - } - this.id = id; - this.capabilities = capabilities; - this.defaultMode = defaultMode; - } - - /// - /// Gets the stable profile identity. - /// - public EditorViewportNavigationProfileId id { get; } - - /// - /// Gets the operations accepted by this provider. - /// - public EditorViewportNavigationCapabilities capabilities { get; } - - /// - /// Gets the mode selected when current state is not supported. - /// - public EditorViewportNavigationMode defaultMode { get; } - - /// - /// Gets or sets the provider-defined world-up direction. - /// - public Vector3 worldUp { get; set; } = Vector3.UP; - - /// - /// Gets or sets the optional current selection bound. - /// - public EditorViewportFocusBounds? focusBounds { get; set; } - - /// - /// Gets or sets pointer rotation sensitivity in radians per pixel. - /// - public float rotationSensitivity { get; set; } = 0.005f; - - /// - /// Gets or sets exponential wheel zoom sensitivity. - /// - public float zoomSensitivity { get; set; } = 0.16f; - - /// - /// Gets or sets minimum orthographic half-height. - /// - public float minimumOrthographicSize { get; set; } = 0.001f; - - /// - /// Gets or sets maximum orthographic half-height. - /// - public float maximumOrthographicSize { get; set; } = 100000f; - - /// - /// Gets or sets minimum orbit or framing distance. - /// - public float minimumFocusDistance { get; set; } = 0.01f; - - /// - /// Gets or sets maximum orbit or framing distance. - /// - public float maximumFocusDistance { get; set; } = 1000000f; - - /// - /// Gets or sets the multiplier used while fast fly movement is requested. - /// - public float fastMovementMultiplier { get; set; } = 4f; - - /// - /// Gets or sets additional framing space around selection bounds. - /// - public float framePadding { get; set; } = 1.25f; - - /// - /// Gets a disabled fallback profile used when no provider navigation contract exists. - /// - public static EditorViewportNavigationProfile disabled { get; } = new( - new EditorViewportNavigationProfileId("inno.editor.navigation.disabled"), - EditorViewportNavigationCapabilities.None, - EditorViewportNavigationMode.Planar); - - private static bool SupportsMode( - EditorViewportNavigationCapabilities capabilities, - EditorViewportNavigationMode mode - ) - => mode switch - { - EditorViewportNavigationMode.Planar => - (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, - EditorViewportNavigationMode.Orbit => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), - EditorViewportNavigationMode.Fly => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), - _ => false - }; -} - -/// -/// Stores rendering-model-neutral navigation state for one Editor viewport across provider reloads. -/// -public sealed class EditorViewportNavigationState -{ - private const float C_MINIMUM_ORTHOGRAPHIC_SIZE = 0.001f; - private const float C_MINIMUM_FIELD_OF_VIEW = 1f; - private const float C_MAXIMUM_FIELD_OF_VIEW = 179f; - - private Vector3 m_position; - private Quaternion m_rotation = Quaternion.identity; - private Vector3 m_pivot; - private EditorViewportProjection m_projection = EditorViewportProjection.Orthographic; - private EditorViewportNavigationMode m_mode = EditorViewportNavigationMode.Planar; - private float m_orthographicSize = 5f; - private float m_fieldOfView = 60f; - private float m_nearClip = 0.01f; - private float m_farClip = 1000f; - private float m_focusDistance = 10f; - private float m_movementSpeed = 5f; - - /// - /// Gets whether a provider or restored panel state initialized this state. - /// - public bool isInitialized { get; private set; } - - /// - /// Gets or sets the current projection family. - /// - public EditorViewportProjection projection - { - get => m_projection; - set - { - if (!Enum.IsDefined(value)) - throw new ArgumentOutOfRangeException(nameof(value)); - m_projection = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the active host navigation mode. - /// - public EditorViewportNavigationMode mode - { - get => m_mode; - set - { - if (!Enum.IsDefined(value)) - throw new ArgumentOutOfRangeException(nameof(value)); - m_mode = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the provider-defined world-space view position. - /// - public Vector3 position - { - get => m_position; - set - { - ValidateFinite(value, nameof(value)); - m_position = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the normalized provider-defined world-space view rotation. - /// - public Quaternion rotation - { - get => m_rotation; - set - { - ValidateFinite(value, nameof(value)); - if (value.LengthSquared() < 0.000001f) - throw new ArgumentException("Navigation rotation must have a usable magnitude.", nameof(value)); - m_rotation = value.normalized; - isInitialized = true; - } - } - - /// - /// Gets or sets the world-space orbit and framing pivot. - /// - public Vector3 pivot - { - get => m_pivot; - set - { - ValidateFinite(value, nameof(value)); - m_pivot = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the positive orthographic half-height in provider world units. - /// - public float orthographicSize - { - get => m_orthographicSize; - set - { - if (!float.IsFinite(value) || value < C_MINIMUM_ORTHOGRAPHIC_SIZE) - throw new ArgumentOutOfRangeException(nameof(value)); - m_orthographicSize = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the perspective vertical field of view in degrees. - /// - public float fieldOfView - { - get => m_fieldOfView; - set - { - if (!float.IsFinite(value) || value < C_MINIMUM_FIELD_OF_VIEW || value > C_MAXIMUM_FIELD_OF_VIEW) - throw new ArgumentOutOfRangeException(nameof(value)); - m_fieldOfView = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the positive near clipping distance. - /// - public float nearClip - { - get => m_nearClip; - set - { - if (!float.IsFinite(value) || value <= 0f || value >= m_farClip) - throw new ArgumentOutOfRangeException(nameof(value)); - m_nearClip = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the far clipping distance greater than the near distance. - /// - public float farClip - { - get => m_farClip; - set - { - if (!float.IsFinite(value) || value <= m_nearClip) - throw new ArgumentOutOfRangeException(nameof(value)); - m_farClip = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the positive orbit and framing distance. - /// - public float focusDistance - { - get => m_focusDistance; - set - { - if (!float.IsFinite(value) || value <= 0f) - throw new ArgumentOutOfRangeException(nameof(value)); - m_focusDistance = value; - isInitialized = true; - } - } - - /// - /// Gets or sets the positive base movement speed in world units per second. - /// - public float movementSpeed - { - get => m_movementSpeed; - set - { - if (!float.IsFinite(value) || value <= 0f) - throw new ArgumentOutOfRangeException(nameof(value)); - m_movementSpeed = value; - } - } - - /// - /// Atomically initializes an orthographic navigation view. - /// - /// - /// Provider-defined world-space position. - /// - /// - /// Provider-defined world-space rotation. - /// - /// - /// Positive orthographic half-height. - /// - public void ConfigureOrthographic( - Vector3 position, - Quaternion rotation, - float orthographicSize - ) { - ValidateFinite(position, nameof(position)); - ValidateRotation(rotation, nameof(rotation)); - if (!float.IsFinite(orthographicSize) - || orthographicSize < C_MINIMUM_ORTHOGRAPHIC_SIZE) - { - throw new ArgumentOutOfRangeException(nameof(orthographicSize)); - } - m_position = position; - m_rotation = rotation.normalized; - m_orthographicSize = orthographicSize; - m_projection = EditorViewportProjection.Orthographic; - isInitialized = true; - } - - /// - /// Atomically initializes a perspective navigation view. - /// - /// - /// Provider-defined world-space position. - /// - /// - /// Provider-defined world-space rotation. - /// - /// - /// Perspective vertical field of view in degrees. - /// - /// - /// Positive near clipping distance. - /// - /// - /// Far clipping distance greater than . - /// - public void ConfigurePerspective( - Vector3 position, - Quaternion rotation, - float fieldOfView, - float nearClip, - float farClip - ) { - ValidateFinite(position, nameof(position)); - ValidateRotation(rotation, nameof(rotation)); - if (!float.IsFinite(fieldOfView) - || fieldOfView < C_MINIMUM_FIELD_OF_VIEW - || fieldOfView > C_MAXIMUM_FIELD_OF_VIEW) - { - throw new ArgumentOutOfRangeException(nameof(fieldOfView)); - } - if (!float.IsFinite(nearClip) || nearClip <= 0f) - throw new ArgumentOutOfRangeException(nameof(nearClip)); - if (!float.IsFinite(farClip) || farClip <= nearClip) - throw new ArgumentOutOfRangeException(nameof(farClip)); - m_position = position; - m_rotation = rotation.normalized; - m_fieldOfView = fieldOfView; - m_nearClip = nearClip; - m_farClip = farClip; - m_projection = EditorViewportProjection.Perspective; - isInitialized = true; - } - - private static void ValidateFinite( - Vector3 value, - string parameterName - ) { - if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z)) - throw new ArgumentException("Navigation position components must be finite.", parameterName); - } - - private static void ValidateFinite( - Quaternion value, - string parameterName - ) { - if (!float.IsFinite(value.x) - || !float.IsFinite(value.y) - || !float.IsFinite(value.z) - || !float.IsFinite(value.w)) - { - throw new ArgumentException("Navigation rotation components must be finite.", parameterName); - } - } - - private static void ValidateRotation( - Quaternion value, - string parameterName - ) { - ValidateFinite(value, parameterName); - if (value.LengthSquared() < 0.000001f) - throw new ArgumentException("Navigation rotation must have a usable magnitude.", parameterName); - } -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs new file mode 100644 index 000000000..a1575060e --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Declares navigation operations supported by one viewport interaction controller. +/// +[Flags] +public enum EditorViewportNavigationCapabilities +{ + /// + /// Disables host-owned navigation. + /// + None = 0, + /// + /// Allows translating the view parallel to its image plane. + /// + Pan = 1 << 0, + /// + /// Allows changing orthographic size or perspective focus distance. + /// + Zoom = 1 << 1, + /// + /// Allows the complete plane-oriented pan and zoom interaction model. + /// + Planar = Pan | Zoom, + /// + /// Allows pivot-oriented orbit and dolly. + /// + Orbit = 1 << 2, + /// + /// Allows free-look movement. + /// + Fly = 1 << 3, + /// + /// Allows framing a provider-supplied or host-derived selection bound. + /// + FrameSelection = 1 << 4 +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs new file mode 100644 index 000000000..da2d9f86c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs @@ -0,0 +1,20 @@ +namespace Inno.Editor.Rendering; + +/// +/// Identifies the active interaction model without prescribing a rendering camera type. +/// +public enum EditorViewportNavigationMode +{ + /// + /// Pans and zooms over a provider-defined plane. + /// + Planar, + /// + /// Rotates around a focus pivot and dollies along the view direction. + /// + Orbit, + /// + /// Moves and looks freely from the current view position. + /// + Fly +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs new file mode 100644 index 000000000..e63ab7b3c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs @@ -0,0 +1,141 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes how the host may navigate one provider-owned viewport without exposing the provider's camera model. +/// +public sealed class EditorViewportNavigationProfile +{ + /// + /// Creates a provider-defined navigation profile. + /// + /// + /// Stable profile identity. + /// + /// + /// Operations accepted by the provider. + /// + /// + /// Preferred mode when current state is unsupported. + /// + public EditorViewportNavigationProfile( + EditorViewportNavigationProfileID id, + EditorViewportNavigationCapabilities capabilities, + EditorViewportNavigationMode defaultMode + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid navigation profile ID is required.", nameof(id)); + } + const EditorViewportNavigationCapabilities C_VALID_CAPABILITIES = EditorViewportNavigationCapabilities.Pan + | EditorViewportNavigationCapabilities.Zoom + | EditorViewportNavigationCapabilities.Orbit + | EditorViewportNavigationCapabilities.Fly + | EditorViewportNavigationCapabilities.FrameSelection; + if ((capabilities & ~C_VALID_CAPABILITIES) != 0) + { + throw new ArgumentOutOfRangeException(nameof(capabilities)); + } + if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode) + ) { + throw new ArgumentException( + "The default navigation mode must be enabled by the profile capabilities.", + nameof(defaultMode) + ); + } + this.id = id; + this.capabilities = capabilities; + this.defaultMode = defaultMode; + } + + /// + /// Gets the stable profile identity. + /// + public EditorViewportNavigationProfileID id { get; } + + /// + /// Gets the operations accepted by this provider. + /// + public EditorViewportNavigationCapabilities capabilities { get; } + + /// + /// Gets the mode selected when current state is not supported. + /// + public EditorViewportNavigationMode defaultMode { get; } + + /// + /// Gets or sets the provider-defined world-up direction. + /// + public Vector3 worldUp { get; set; } = Vector3.UP; + + /// + /// Gets or sets the optional current selection bound. + /// + public EditorViewportFocusBounds? focusBounds { get; set; } + + /// + /// Gets or sets pointer rotation sensitivity in radians per pixel. + /// + public float rotationSensitivity { get; set; } = 0.005f; + + /// + /// Gets or sets exponential wheel zoom sensitivity. + /// + public float zoomSensitivity { get; set; } = 0.16f; + + /// + /// Gets or sets minimum orthographic half-height. + /// + public float minimumOrthographicSize { get; set; } = 0.001f; + + /// + /// Gets or sets maximum orthographic half-height. + /// + public float maximumOrthographicSize { get; set; } = 100000f; + + /// + /// Gets or sets minimum orbit or framing distance. + /// + public float minimumFocusDistance { get; set; } = 0.01f; + + /// + /// Gets or sets maximum orbit or framing distance. + /// + public float maximumFocusDistance { get; set; } = 1000000f; + + /// + /// Gets or sets the multiplier used while fast fly movement is requested. + /// + public float fastMovementMultiplier { get; set; } = 4f; + + /// + /// Gets or sets additional framing space around selection bounds. + /// + public float framePadding { get; set; } = 1.25f; + + /// + /// Gets a disabled fallback profile used when no provider navigation contract exists. + /// + public static EditorViewportNavigationProfile disabled { get; } = new( + new EditorViewportNavigationProfileID("inno.editor.navigation.disabled"), + EditorViewportNavigationCapabilities.None, + EditorViewportNavigationMode.Planar + ); + + private static bool SupportsMode( + EditorViewportNavigationCapabilities capabilities, + EditorViewportNavigationMode mode + ) => mode switch + { + EditorViewportNavigationMode.Planar => + (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, + EditorViewportNavigationMode.Orbit => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), + EditorViewportNavigationMode.Fly => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), + _ => false + }; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs new file mode 100644 index 000000000..8f69c2e0a --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies a provider-defined navigation profile across reload generations. +/// +public readonly record struct EditorViewportNavigationProfileID +{ + /// + /// Creates a stable profile identifier. + /// + /// + /// Globally stable profile identity. + /// + public EditorViewportNavigationProfileID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the stable profile identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs new file mode 100644 index 000000000..d239230f0 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs @@ -0,0 +1,327 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Stores rendering-model-neutral navigation state for one Editor viewport across provider reloads. +/// +public sealed class EditorViewportNavigationState +{ + private const float C_MINIMUM_ORTHOGRAPHIC_SIZE = 0.001f; + private const float C_MINIMUM_FIELD_OF_VIEW = 1f; + private const float C_MAXIMUM_FIELD_OF_VIEW = 179f; + + private Vector3 m_position; + private Quaternion m_rotation = Quaternion.identity; + private Vector3 m_pivot; + private EditorViewportProjection m_projection = EditorViewportProjection.Orthographic; + private EditorViewportNavigationMode m_mode = EditorViewportNavigationMode.Planar; + private float m_orthographicSize = 5f; + private float m_fieldOfView = 60f; + private float m_nearClip = 0.01f; + private float m_farClip = 1000f; + private float m_focusDistance = 10f; + private float m_movementSpeed = 5f; + + /// + /// Gets whether a provider or restored panel state initialized this state. + /// + public bool isInitialized { get; private set; } + + /// + /// Gets or sets the current projection family. + /// + public EditorViewportProjection projection + { + get => m_projection; + set + { + if (!Enum.IsDefined(value)) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_projection = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the active host navigation mode. + /// + public EditorViewportNavigationMode mode + { + get => m_mode; + set + { + if (!Enum.IsDefined(value)) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_mode = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the provider-defined world-space view position. + /// + public Vector3 position + { + get => m_position; + set + { + ValidateFinite(value, nameof(value)); + m_position = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the normalized provider-defined world-space view rotation. + /// + public Quaternion rotation + { + get => m_rotation; + set + { + ValidateFinite(value, nameof(value)); + if (value.LengthSquared() < 0.000001f) + { + throw new ArgumentException("Navigation rotation must have a usable magnitude.", nameof(value)); + } + m_rotation = value.normalized; + isInitialized = true; + } + } + + /// + /// Gets or sets the world-space orbit and framing pivot. + /// + public Vector3 pivot + { + get => m_pivot; + set + { + ValidateFinite(value, nameof(value)); + m_pivot = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the positive orthographic half-height in provider world units. + /// + public float orthographicSize + { + get => m_orthographicSize; + set + { + if (!float.IsFinite(value) || value < C_MINIMUM_ORTHOGRAPHIC_SIZE) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_orthographicSize = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the perspective vertical field of view in degrees. + /// + public float fieldOfView + { + get => m_fieldOfView; + set + { + if (!float.IsFinite(value) || value < C_MINIMUM_FIELD_OF_VIEW || value > C_MAXIMUM_FIELD_OF_VIEW) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_fieldOfView = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the positive near clipping distance. + /// + public float nearClip + { + get => m_nearClip; + set + { + if (!float.IsFinite(value) || value <= 0f || value >= m_farClip) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_nearClip = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the far clipping distance greater than the near distance. + /// + public float farClip + { + get => m_farClip; + set + { + if (!float.IsFinite(value) || value <= m_nearClip) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_farClip = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the positive orbit and framing distance. + /// + public float focusDistance + { + get => m_focusDistance; + set + { + if (!float.IsFinite(value) || value <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_focusDistance = value; + isInitialized = true; + } + } + + /// + /// Gets or sets the positive base movement speed in world units per second. + /// + public float movementSpeed + { + get => m_movementSpeed; + set + { + if (!float.IsFinite(value) || value <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + m_movementSpeed = value; + } + } + + /// + /// Atomically initializes an orthographic navigation view. + /// + /// + /// Provider-defined world-space position. + /// + /// + /// Provider-defined world-space rotation. + /// + /// + /// Positive orthographic half-height. + /// + public void ConfigureOrthographic( + Vector3 position, + Quaternion rotation, + float orthographicSize + ) { + ValidateFinite(position, nameof(position)); + ValidateRotation(rotation, nameof(rotation)); + if (!float.IsFinite(orthographicSize) + || orthographicSize < C_MINIMUM_ORTHOGRAPHIC_SIZE + ) { + throw new ArgumentOutOfRangeException(nameof(orthographicSize)); + } + m_position = position; + m_rotation = rotation.normalized; + m_orthographicSize = orthographicSize; + m_projection = EditorViewportProjection.Orthographic; + isInitialized = true; + } + + /// + /// Atomically initializes a perspective navigation view. + /// + /// + /// Provider-defined world-space position. + /// + /// + /// Provider-defined world-space rotation. + /// + /// + /// Perspective vertical field of view in degrees. + /// + /// + /// Positive near clipping distance. + /// + /// + /// Far clipping distance greater than . + /// + public void ConfigurePerspective( + Vector3 position, + Quaternion rotation, + float fieldOfView, + float nearClip, + float farClip + ) { + ValidateFinite(position, nameof(position)); + ValidateRotation(rotation, nameof(rotation)); + if (!float.IsFinite(fieldOfView) + || fieldOfView < C_MINIMUM_FIELD_OF_VIEW + || fieldOfView > C_MAXIMUM_FIELD_OF_VIEW + ) { + throw new ArgumentOutOfRangeException(nameof(fieldOfView)); + } + if (!float.IsFinite(nearClip) || nearClip <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(nearClip)); + } + if (!float.IsFinite(farClip) || farClip <= nearClip) + { + throw new ArgumentOutOfRangeException(nameof(farClip)); + } + m_position = position; + m_rotation = rotation.normalized; + m_fieldOfView = fieldOfView; + m_nearClip = nearClip; + m_farClip = farClip; + m_projection = EditorViewportProjection.Perspective; + isInitialized = true; + } + + private static void ValidateFinite( + Vector3 value, + string parameterName + ) { + if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z)) + { + throw new ArgumentException("Navigation position components must be finite.", parameterName); + } + } + + private static void ValidateFinite( + Quaternion value, + string parameterName + ) { + if (!float.IsFinite(value.x) + || !float.IsFinite(value.y) + || !float.IsFinite(value.z) + || !float.IsFinite(value.w) + ) { + throw new ArgumentException("Navigation rotation components must be finite.", parameterName); + } + } + + private static void ValidateRotation( + Quaternion value, + string parameterName + ) { + ValidateFinite(value, parameterName); + if (value.LengthSquared() < 0.000001f) + { + throw new ArgumentException("Navigation rotation must have a usable magnitude.", parameterName); + } + } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs index a51cdf3e8..df78cf386 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs @@ -1,11 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Inno.Adapter.Presentation; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Editor.Rendering; @@ -17,7 +11,7 @@ public readonly record struct EditorViewportOutput /// /// Creates an editor viewport output snapshot. /// - /// + /// /// Stable viewport identity. /// /// @@ -30,15 +24,15 @@ public readonly record struct EditorViewportOutput /// Current target height. /// public EditorViewportOutput( - string viewportId, + string viewportID, PresentationTextureHandle texture, int pixelWidth, int pixelHeight ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.viewportId = viewportId; + this.viewportID = viewportID; this.texture = texture; this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; @@ -47,7 +41,7 @@ int pixelHeight /// /// Gets the stable viewport identity. /// - public string viewportId { get; } + public string viewportID { get; } /// /// Gets the opaque presentation token. @@ -69,194 +63,3 @@ int pixelHeight /// public bool isReady => texture.isValid; } - -/// -/// Bridges editor extensions to a host-owned render request sink and opaque texture presenter. -/// -public interface IEditorRenderingHost -{ - /// - /// Gets the active generation's model-independent world-content collector. - /// - IViewContentCollector viewContent { get; } - - /// - /// Gets the current output frame index shared by Editor views. - /// - ulong currentFrameIndex { get; } - - /// - /// Submits or updates one composed offscreen editor viewport. - /// - /// - /// Complete ordered model composition for the current frame. - /// - /// - /// The current presentation output, which can be warming up for one frame. - /// - EditorViewportOutput Submit(EditorViewportComposition composition); - - /// - /// Draws a ready viewport output inside the current ImGui window. - /// - /// - /// Output returned by . - /// - /// - /// Destination size in logical UI pixels. - /// - void Draw( - EditorViewportOutput output, - Vector2 logicalSize - ); - - /// - /// Releases one viewport and queues its GPU target for frame-safe destruction. - /// - /// - /// Stable viewport identity. - /// - void Release(string viewportId); - - /// - /// Releases every viewport owned by this editor host service. - /// - void ReleaseAll(); -} - -/// -/// Describes one model-neutral layer in an Editor viewport composition. -/// -public sealed class EditorViewportLayer -{ - /// - /// Creates one immutable model-neutral viewport layer. - /// - /// - /// Stable identity of the rendering-model contributor that produced the layer. - /// - /// - /// Contributor-selected pipeline, or null for the project default. - /// - /// - /// Contributor-defined frame-only data. - /// - /// - /// Ascending model-composition order. - /// - public EditorViewportLayer( - string contributorId, - RenderPipelineAsset? pipeline, - RenderFrameData data, - int order - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(contributorId); - ArgumentNullException.ThrowIfNull(data); - this.contributorId = contributorId; - this.pipeline = pipeline; - this.data = data; - this.order = order; - } - - /// - /// Gets the stable identity of the rendering-model contributor. - /// - public string contributorId { get; } - - /// - /// Gets the contributor-selected pipeline, or null for the project default. - /// - public RenderPipelineAsset? pipeline { get; } - - /// - /// Gets contributor-defined frame-only data. - /// - public RenderFrameData data { get; } - - /// - /// Gets ascending model-composition order. - /// - public int order { get; } -} - -/// -/// Describes a complete ordered set of rendering-model layers targeting one Editor viewport. -/// -public sealed class EditorViewportComposition -{ - private readonly IReadOnlyList m_layers; - - /// - /// Creates an immutable viewport composition. - /// - /// - /// Stable panel viewport identity. - /// - /// - /// Positive target width. - /// - /// - /// Positive target height. - /// - /// - /// Shared presentation target format required by every layer. - /// - /// - /// Ordered non-empty rendering-model layer collection. - /// - public EditorViewportComposition( - string viewportId, - int pixelWidth, - int pixelHeight, - RenderTextureFormat targetFormat, - IEnumerable layers - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - ArgumentNullException.ThrowIfNull(layers); - EditorViewportLayer[] materializedLayers = layers.ToArray(); - if (materializedLayers.Length == 0) - throw new ArgumentException("A viewport composition requires at least one model layer.", nameof(layers)); - if (materializedLayers.Any(static layer => layer is null)) - throw new ArgumentException("A viewport composition cannot contain null model layers.", nameof(layers)); - if (materializedLayers.Select(static layer => layer.contributorId).Distinct(StringComparer.Ordinal).Count() - != materializedLayers.Length) - { - throw new ArgumentException("Viewport contributor identities must be unique.", nameof(layers)); - } - m_layers = Array.AsReadOnly(materializedLayers - .OrderBy(static layer => layer.order) - .ThenBy(static layer => layer.contributorId, StringComparer.Ordinal) - .ToArray()); - this.viewportId = viewportId; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - this.targetFormat = targetFormat; - } - - /// - /// Gets the stable viewport identity. - /// - public string viewportId { get; } - - /// - /// Gets the target width. - /// - public int pixelWidth { get; } - - /// - /// Gets the target height. - /// - public int pixelHeight { get; } - - /// - /// Gets the shared presentation target format. - /// - public RenderTextureFormat targetFormat { get; } - - /// - /// Gets the ordered rendering-model layers. - /// - public IReadOnlyList layers => m_layers; -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs new file mode 100644 index 000000000..fae74f060 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Supplies normalized pointer interaction over one rendered viewport. +/// +public sealed class EditorViewportPointerContext +{ + internal EditorViewportPointerContext( + EditorViewportContext viewport, + float x, + float y, + int button + ) { + this.viewport = viewport; + this.x = Math.Clamp(x, 0f, 1f); + this.y = Math.Clamp(y, 0f, 1f); + this.button = button; + } + + /// + /// Gets the owning frame-only viewport context. + /// + public EditorViewportContext viewport { get; } + + /// + /// Gets normalized horizontal pointer position. + /// + public float x { get; } + + /// + /// Gets normalized vertical pointer position. + /// + public float y { get; } + + /// + /// Gets the platform-independent pointer button index. + /// + public int button { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs new file mode 100644 index 000000000..ee0262f22 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes host-selected presentation preferences without prescribing rendering behavior. +/// +public readonly record struct EditorViewportPresentation +{ + /// + /// Creates presentation preferences for one Editor viewport. + /// + /// + /// Linear clear color preferred by the host panel. + /// + /// + /// Physical render pixels per logical presentation unit. + /// + public EditorViewportPresentation( + Color backgroundColor, + float pixelDensity = 1f + ) { + if (!float.IsFinite(pixelDensity) || pixelDensity <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pixelDensity)); + } + this.backgroundColor = backgroundColor; + this.pixelDensity = pixelDensity; + } + + /// + /// Gets the linear clear color preferred by the host panel. + /// + public Color backgroundColor { get; } + + /// + /// Gets physical render pixels per logical presentation unit. + /// + public float pixelDensity { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs new file mode 100644 index 000000000..bba7fe691 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs @@ -0,0 +1,16 @@ +namespace Inno.Editor.Rendering; + +/// +/// Identifies the projection family represented by neutral Editor viewport navigation state. +/// +public enum EditorViewportProjection +{ + /// + /// Uses a parallel projection controlled by an orthographic half-height. + /// + Orthographic, + /// + /// Uses a perspective projection controlled by a vertical field of view. + /// + Perspective +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs new file mode 100644 index 000000000..2e01c43e5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs @@ -0,0 +1,42 @@ +using Inno.Core.Identity; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Receives transient world-space gizmo geometry from independent Editor extensions. +/// +public interface IEditorGizmoSink +{ + /// + /// Adds a visible, selectable icon at an object's world position. + /// + /// + /// The scene object selected when the icon is clicked. + /// + /// + /// The icon position in world space. + /// + /// + /// A stable semantic icon ID. Unknown IDs use the generic scene icon. + /// + void Icon( + Identity owner, + Vector3 position, + string iconID + ); + + /// + /// Adds a non-interactive world-space line, normally for selected bounds. + /// + /// + /// The first world-space endpoint. + /// + /// + /// The second world-space endpoint. + /// + void Line( + Vector3 start, + Vector3 end + ); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs similarity index 62% rename from src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs rename to src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs index 8455f7bfa..d37374b8e 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs @@ -1,72 +1,8 @@ -using System; using System.Numerics; -using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Editor.Rendering; -/// -/// Identifies one preview texture owned by a specific rendering-device generation. -/// -public readonly record struct EditorPreviewHandle -{ - /// - /// Creates one generation-scoped preview handle. - /// - /// - /// Non-zero preview identity. - /// - /// - /// Non-zero rendering-device generation. - /// - /// - /// Positive source width. - /// - /// - /// Positive source height. - /// - public EditorPreviewHandle( - ulong value, - uint deviceGeneration, - int pixelWidth, - int pixelHeight - ) { - if (value == 0 || deviceGeneration == 0) - throw new ArgumentOutOfRangeException(nameof(value), "Preview identity and device generation must be non-zero."); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.value = value; - this.deviceGeneration = deviceGeneration; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - } - - /// - /// Gets the opaque preview identity. - /// - public ulong value { get; } - - /// - /// Gets the rendering-device generation that owns this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets source width in pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets source height in pixels. - /// - public int pixelHeight { get; } - - /// - /// Gets whether this handle identifies a usable generation-scoped preview. - /// - public bool isValid => value != 0 && deviceGeneration != 0 && pixelWidth > 0 && pixelHeight > 0; -} - /// /// Provides one shared preview texture bridge for browsers, inspectors, and document canvases. /// @@ -97,10 +33,10 @@ out EditorPreviewHandle handle /// /// Releases an offscreen preview, including one which has not produced its first handle. /// - /// + /// /// The same consumer-qualified identity submitted in the composition. /// - void ReleaseRendered(string viewportId); + void ReleaseRendered(string viewportID); /// /// Tries to resolve a standalone texture preview without blocking target compilation. diff --git a/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs new file mode 100644 index 000000000..60f7eadaf --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs @@ -0,0 +1,58 @@ +using System.Numerics; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Bridges editor extensions to a host-owned render request sink and opaque texture presenter. +/// +public interface IEditorRenderingHost +{ + /// + /// Gets the active generation's model-independent world-content collector. + /// + IViewContentCollector viewContent { get; } + + /// + /// Gets the current output frame index shared by Editor views. + /// + ulong currentFrameIndex { get; } + + /// + /// Submits or updates one composed offscreen editor viewport. + /// + /// + /// Complete ordered model composition for the current frame. + /// + /// + /// The current presentation output, which can be warming up for one frame. + /// + EditorViewportOutput Submit(EditorViewportComposition composition); + + /// + /// Draws a ready viewport output inside the current ImGui window. + /// + /// + /// Output returned by . + /// + /// + /// Destination size in logical UI pixels. + /// + void Draw( + EditorViewportOutput output, + Vector2 logicalSize + ); + + /// + /// Releases one viewport and queues its GPU target for frame-safe destruction. + /// + /// + /// Stable viewport identity. + /// + void Release(string viewportID); + + /// + /// Releases every viewport owned by this editor host service. + /// + void ReleaseAll(); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs index 55c7eb5e6..495d12bfe 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs @@ -2,15 +2,17 @@ using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Scripting.Api; namespace Inno.Editor.Rendering; + /// /// Edits Pipeline sources and typed extension settings without changing canonical rendering assets before Save. /// @@ -19,36 +21,37 @@ public sealed class PipelineDocuments : EditorModule { internal const string C_HISTORY = "inno.pipeline/draft"; private readonly TypeCatalog m_types; + + internal PipelineDocuments( + AssetPipeline assets, + SerializationRegistry serialization, + TypeCatalog types, + EditorInteractions interactions + ) { + this.assets = assets; + this.serialization = serialization; + m_types = types; + this.drafts = new(assets, serialization, interactions, "inno.pipeline", C_HISTORY, ".irenderpipeline", "Pipeline"); + } + /// /// Gets the authoritative asset pipeline used by source inspectors. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetPipeline assets { get; } /// /// Gets the current owner serialization registry. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public SerializationRegistry serialization { get; } /// /// Gets the source draft owner shared by Pipeline inspectors. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetDraftDocuments drafts { get; } - internal PipelineDocuments( - AssetPipeline assets, - SerializationRegistry serialization, - TypeCatalog types, - EditorInteractions interactions - ) { - this.assets = assets; - this.serialization = serialization; - m_types = types; - drafts = new(assets, serialization, interactions, "inno.pipeline", C_HISTORY, ".irenderpipeline", "Pipeline"); - } - /// /// Opens a native Pipeline source in the shared document service, including failed imports. /// @@ -59,20 +62,22 @@ EditorInteractions interactions /// The persistent source identity used by draft operations. /// public Guid Open(AssetPath path) => drafts.Open(path); + /// /// Reads a detached current-generation Pipeline value; its referenced canonical assets must not be mutated. /// - /// + /// /// Open Pipeline identity. /// /// /// The unsaved native Pipeline value. /// - public RenderPipelineAsset Read(Guid assetId) => drafts.Read(assetId); + public RenderPipelineAsset Read(Guid assetID) => drafts.Read(assetID); + /// /// Changes a draft through shared History without publishing it to Scene/Game. /// - /// + /// /// Open Pipeline identity. /// /// @@ -82,17 +87,18 @@ EditorInteractions interactions /// The current gesture key, or null for a discrete edit. /// public void Replace( - Guid assetId, + Guid assetID, RenderPipelineAsset candidate, string? mergeKey = null - ) => drafts.Replace(assetId, candidate, mergeKey); + ) => drafts.Replace(assetID, candidate, mergeKey); + /// /// Captures typed Pipeline settings with this source owner's complete reference and dependency context. /// /// /// Current plugin settings contract. /// - /// + /// /// Open Pipeline identity. /// /// @@ -102,15 +108,14 @@ public void Replace( /// The current gesture key, or null for a discrete edit. /// public void ReplaceSettings( - Guid assetId, + Guid assetID, TSettings settings, string? mergeKey = null - ) - where TSettings : class, ISerializable + ) where TSettings : class, ISerializable { - RenderPipelineAsset pipeline = Read(assetId); + RenderPipelineAsset pipeline = Read(assetID); pipeline.pipelineState = new SerializedRenderExtensionState(assets.CaptureProperties(settings)); - Replace(assetId, pipeline, mergeKey); + Replace(assetID, pipeline, mergeKey); } /// @@ -122,20 +127,22 @@ public void ReplaceSettings( /// /// The detached settings, or null when the extension is temporarily unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public ISerializable? RestoreSettings(SerializedRenderExtensionState state) { if (state.stableTypeId == Guid.Empty) + { return null; + } Type type = m_types.Resolve(new TypeRef(state.stableTypeId)); if (Activator.CreateInstance(type) is not ISerializable settings) + { throw new InvalidOperationException("Pipeline settings must be a constructible native serializable type."); + } assets.RestoreProperties(state.stableTypeId, state.propertyData, settings); return settings; } - internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; /// /// Initializes this feature when its owning runtime becomes active. /// @@ -143,6 +150,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnStart(EditorContext context) => drafts.Start(); + /// /// Advances this feature using the current runtime state. /// @@ -150,6 +158,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnUpdate(EditorContext context) => drafts.Update(); + /// /// Stops this feature before its owning runtime releases the active generation. /// @@ -157,77 +166,8 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnStop(EditorContext context) => drafts.Dispose(); -} - -[EditorHistoryHandler(PipelineDocuments.C_HISTORY)] -internal sealed class PipelineDraftHistory(PipelineDocuments documents) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.drafts.ValidateHistory(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception error) when (PipelineDocuments.Recoverable(error)) - { - return EditorHistoryAvailability.Unavailable(error.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.drafts.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception error) when (PipelineDocuments.Recoverable(error)) - { - return EditorHistoryResult.Failure(error.Message); - } - } - /// - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) => documents.drafts.TryMergeHistory(older, newer, out merged); + internal static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && RetirementPendingException.Find(error) is null; } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs new file mode 100644 index 000000000..e24de0b43 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs @@ -0,0 +1,77 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Rendering; + +[EditorHistoryHandler(PipelineDocuments.C_HISTORY)] +internal sealed class PipelineDraftHistory(PipelineDocuments documents) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.drafts.ValidateHistory(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception error) when (PipelineDocuments.Recoverable(error)) + { + return EditorHistoryAvailability.Unavailable(error.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.drafts.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception error) when (PipelineDocuments.Recoverable(error)) + { + return EditorHistoryResult.Failure(error.Message); + } + } + + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) => documents.drafts.TryMergeHistory(older, newer, out merged); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs index b076b7f2d..52c3f1c9f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs @@ -11,5 +11,6 @@ namespace Inno.Editor.Rendering; "New Render Pipeline", groupOrder: 200, itemOrder: 200, - separatorBeforeGroup: true)] + separatorBeforeGroup: true +)] internal sealed class RenderPipelineAssetCreationTemplate : AssetCreationTemplate; diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs index 93569ee9e..85bbe2161 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs @@ -1,19 +1,16 @@ -using Inno.Scripting.Api; using Inno.Editor.Rendering; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Rendering", - "Inno.Editor.Rendering", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Rendering", "Inno.Editor.Rendering", ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorViewportKindId), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorViewportKindID), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(PipelineDocuments), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportContributorExtensionAttribute), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportContext), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportProjection), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportNavigationMode), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportNavigationCapabilities), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorViewportNavigationProfileId), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorViewportNavigationProfileID), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportFocusBounds), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportNavigationProfile), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportNavigationState), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs index b23c2aacb..e7823685c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -15,25 +14,21 @@ internal static class SceneStateDiagnosticPublisher internal static void PublishMissingElements(IReadOnlyList scenes) { ArgumentNullException.ThrowIfNull(scenes); - var diagnostics = new List(); + List diagnostics = []; foreach (GameScene scene in scenes) { foreach (GameObject gameObject in scene.GetObjects()) { foreach (MissingGameComponent missing in gameObject.GetComponents().OfType()) { - diagnostics.Add(CreateMissingDiagnostic( - scene, - missing.identity.persistentId, - missing.missingTypeName)); + diagnostics.Add( + CreateMissingDiagnostic(scene, missing.identity.persistentID, missing.missingTypeName) + ); } } foreach (MissingGameSystem missing in scene.GetSystems().OfType()) { - diagnostics.Add(CreateMissingDiagnostic( - scene, - missing.identity.persistentId, - missing.missingTypeName)); + diagnostics.Add(CreateMissingDiagnostic(scene, missing.identity.persistentID, missing.missingTypeName)); } } Diagnostics.Set(C_MISSING_ELEMENTS, diagnostics); @@ -46,11 +41,10 @@ internal static void PublishReload(IReadOnlyList diagnost C_RELOAD, diagnostics.Select(static diagnostic => diagnostic.severity switch { - DiagnosticSeverity.Warning => Diagnostic.Warning( - diagnostic.code, - diagnostic.message), + DiagnosticSeverity.Warning => Diagnostic.Warning(diagnostic.code, diagnostic.message), _ => Diagnostic.Error(diagnostic.code, diagnostic.message) - })); + }) + ); } internal static void ClearAll() @@ -61,11 +55,11 @@ internal static void ClearAll() private static Diagnostic CreateMissingDiagnostic( GameScene scene, - Guid elementId, + Guid elementID, string missingTypeName - ) - => Diagnostic.Warning( - "INNOHR0002", - $"'{missingTypeName}' is unavailable in scene '{scene.name}' " + - $"({scene.identity.persistentId:D}), element {elementId:D}. Its identity and serialized state are preserved."); + ) => Diagnostic.Warning( + "INNOHR0002", + $"'{missingTypeName}' is unavailable in scene '{scene.name}' " + + $"({scene.identity.persistentID:D}), element {elementID:D}. Its identity and serialized state are preserved." + ); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs index 96112aff7..796962cda 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Extensibility.Types; using Inno.Scene; @@ -17,24 +16,26 @@ internal SceneStateDiagnosticTracker( SceneWorld world, TypeCatalog types ) { - m_world = world ?? throw new ArgumentNullException(nameof(world)); - m_types = types ?? throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(types); + m_world = world; + m_types = types; } internal void Reconcile(bool force = false) { IReadOnlyList scenes = m_world.loadedScenes; long typeCacheVersion = m_types.isInitialized - ? m_types.current.version - : -1; + ? m_types.current.version + : -1; bool scenesChanged = scenes.Count != m_scenes.Length; if (!scenesChanged) { for (int i = 0; i < scenes.Count; i++) { - if (m_scenes[i].TryGetTarget(out GameScene? tracked) && - ReferenceEquals(scenes[i], tracked)) - { + if (m_scenes[i].TryGetTarget(out GameScene? tracked) + && ReferenceEquals(scenes[i], tracked) + ) { continue; } scenesChanged = true; @@ -42,12 +43,16 @@ internal void Reconcile(bool force = false) } } if (!force && !scenesChanged && typeCacheVersion == m_typeCacheVersion) + { return; + } SceneStateDiagnosticPublisher.PublishMissingElements(scenes); var references = new WeakReference[scenes.Count]; for (int i = 0; i < scenes.Count; i++) + { references[i] = new WeakReference(scenes[i]); + } m_scenes = references; m_typeCacheVersion = typeCacheVersion; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs index 6a0fe268e..970f99f98 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -17,6 +16,22 @@ internal sealed class EditorSceneDiagnosticPublisher : IDisposable private readonly Dictionary m_dirtyCheckStates = []; private string m_restoreState = string.Empty; + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + ResolveRestore(); + foreach (Guid sceneID in m_synchronizationStates.Keys.ToArray()) + { + ResolveSynchronization(sceneID); + } + foreach (Guid sceneID in m_dirtyCheckStates.Keys.ToArray()) + { + ResolveDirtyCheck(sceneID); + } + } + internal bool PublishRestoreFailure( string code, string message @@ -25,7 +40,9 @@ string message ArgumentException.ThrowIfNullOrWhiteSpace(message); string state = $"{code}:{message}"; if (string.Equals(m_restoreState, state, StringComparison.Ordinal)) + { return false; + } Diagnostics.Set(C_RESTORE_GROUP, Diagnostic.Error(code, message)); m_restoreState = state; return true; @@ -34,7 +51,9 @@ string message internal void ResolveRestore() { if (string.IsNullOrEmpty(m_restoreState)) + { return; + } Diagnostics.Clear(C_RESTORE_GROUP); m_restoreState = string.Empty; } @@ -45,19 +64,20 @@ Exception exception ) { ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(exception); - Guid targetId = scene.identity.persistentId; + Guid targetID = scene.identity.persistentID; string state = exception.ToString(); - if (m_synchronizationStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_synchronizationStates.TryGetValue(targetID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; } Diagnostics.Set( - targetId, + targetID, C_SYNCHRONIZATION_GROUP, Diagnostic.Error("SCENE-SYNCHRONIZATION", exception.Message), - scene.name); - m_synchronizationStates[targetId] = state; + scene.name + ); + m_synchronizationStates[targetID] = state; return true; } @@ -65,21 +85,32 @@ internal void PublishSourceUnavailable( GameScene scene, string sourcePath ) { - Guid sceneId = scene.identity.persistentId; + Guid sceneID = scene.identity.persistentID; string state = "SCENE-SOURCE-MISSING:" + sourcePath; - if (m_synchronizationStates.TryGetValue(sceneId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) + if (m_synchronizationStates.TryGetValue(sceneID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; - Diagnostics.Set(sceneId, C_SYNCHRONIZATION_GROUP, - Diagnostic.Warning("SCENE-SOURCE-MISSING", $"Scene source '{sourcePath}' is unavailable; its assignment and current edits are preserved."), scene.name); - m_synchronizationStates[sceneId] = state; + } + Diagnostics.Set( + sceneID, + C_SYNCHRONIZATION_GROUP, + Diagnostic.Warning( + "SCENE-SOURCE-MISSING", + $"Scene source '{sourcePath}' is unavailable; its assignment and current edits are preserved." + ), + scene.name + ); + m_synchronizationStates[sceneID] = state; } - internal void ResolveSynchronization(Guid sceneId) + internal void ResolveSynchronization(Guid sceneID) { - if (!m_synchronizationStates.Remove(sceneId)) + if (!m_synchronizationStates.Remove(sceneID)) + { return; - Diagnostics.Clear(sceneId, C_SYNCHRONIZATION_GROUP); + } + Diagnostics.Clear(sceneID, C_SYNCHRONIZATION_GROUP); } internal bool PublishDirtyCheckFailure( @@ -88,48 +119,48 @@ Exception exception ) { ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(exception); - Guid targetId = scene.identity.persistentId; + Guid targetID = scene.identity.persistentID; string state = exception.ToString(); - if (m_dirtyCheckStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) + if (m_dirtyCheckStates.TryGetValue(targetID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; - Diagnostics.Set(targetId, C_DIRTY_CHECK_GROUP, - Diagnostic.Error("SCENE-DIRTY-CHECK", exception.Message), scene.name); - m_dirtyCheckStates[targetId] = state; + } + Diagnostics.Set( + targetID, + C_DIRTY_CHECK_GROUP, + Diagnostic.Error("SCENE-DIRTY-CHECK", exception.Message), + scene.name + ); + m_dirtyCheckStates[targetID] = state; return true; } - internal void ResolveDirtyCheck(Guid sceneId) + internal void ResolveDirtyCheck(Guid sceneID) { - if (!m_dirtyCheckStates.Remove(sceneId)) + if (!m_dirtyCheckStates.Remove(sceneID)) + { return; - Diagnostics.Clear(sceneId, C_DIRTY_CHECK_GROUP); + } + Diagnostics.Clear(sceneID, C_DIRTY_CHECK_GROUP); } - internal void RetainSynchronizationTargets(IReadOnlySet sceneIds) + internal void RetainSynchronizationTargets(IReadOnlySet sceneIDs) { - ArgumentNullException.ThrowIfNull(sceneIds); + ArgumentNullException.ThrowIfNull(sceneIDs); Guid[] removed = m_synchronizationStates.Keys - .Where(id => !sceneIds.Contains(id)) + .Where(id => !sceneIDs.Contains(id)) .ToArray(); for (int i = 0; i < removed.Length; i++) + { ResolveSynchronization(removed[i]); + } Guid[] removedDirtyChecks = m_dirtyCheckStates.Keys - .Where(id => !sceneIds.Contains(id)) + .Where(id => !sceneIDs.Contains(id)) .ToArray(); for (int i = 0; i < removedDirtyChecks.Length; i++) + { ResolveDirtyCheck(removedDirtyChecks[i]); - } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - ResolveRestore(); - foreach (Guid sceneId in m_synchronizationStates.Keys.ToArray()) - ResolveSynchronization(sceneId); - foreach (Guid sceneId in m_dirtyCheckStates.Keys.ToArray()) - ResolveDirtyCheck(sceneId); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs index ad1f8f7c6..6d35c4509 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - internal SceneDocumentSnapshot CaptureDocumentSnapshot(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); @@ -36,25 +34,26 @@ internal SceneDocumentSnapshot CaptureDocumentSnapshot(GameScene scene) SceneDocumentSnapshot? playBaseline = null; if (m_playModeSession is PlayModeLease playModeSession) { - if (playModeSession.TryGetSnapshot( - scene.identity.persistentId, - out SceneDocumentSnapshot snapshot)) + if (playModeSession.TryGetSnapshot(scene.identity.persistentID, out SceneDocumentSnapshot snapshot)) { playBaseline = snapshot; } } else + { document = GetOrCreateDocument(scene); + } SerializationContext serializationContext = AssetSerializationContext.Create(m_assets); return new SceneDocumentSnapshot( - scene.identity.persistentId, + scene.identity.persistentID, m_serialization.Serialize(scene, serializationContext), document?.sourcePath ?? playBaseline?.sourcePath ?? string.Empty, - document?.sourceAssetId ?? playBaseline?.sourceAssetId ?? Guid.Empty, + document?.sourceAssetID ?? playBaseline?.sourceAssetID ?? Guid.Empty, document?.savedHash.ToArray() ?? playBaseline?.savedHash.ToArray() ?? [], document?.isDirty ?? false, world.GetSceneIndex(scene), - document?.nextRefreshTimestamp ?? 0); + document?.nextRefreshTimestamp ?? 0 + ); } internal GameScene RestoreDocumentSnapshot(SceneDocumentSnapshot snapshot) @@ -67,11 +66,12 @@ internal GameScene RestoreDocumentSnapshot(SceneDocumentSnapshot snapshot) world.SetSceneIndex(scene, snapshot.sceneIndex); if (canPersist) { - m_documents[scene.identity.persistentId] = new SceneDocument( + m_documents[scene.identity.persistentID] = new SceneDocument( scene, snapshot.sourcePath, - snapshot.sourceAssetId, - snapshot.savedHash.ToArray()) + snapshot.sourceAssetID, + snapshot.savedHash.ToArray() + ) { isDirty = snapshot.isDirty, nextRefreshTimestamp = snapshot.nextRefreshTimestamp @@ -84,54 +84,61 @@ internal bool CloseDocumentForHistory(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); using IDisposable scope = EnterPresentationScope(); - Guid sceneId = scene.identity.persistentId; + Guid sceneID = scene.identity.persistentID; bool closed = world.UnloadScene(scene); if (closed && canPersist) { - m_documents.Remove(sceneId); - m_diagnostics.ResolveSynchronization(sceneId); - m_diagnostics.ResolveDirtyCheck(sceneId); + m_documents.Remove(sceneID); + m_diagnostics.ResolveSynchronization(sceneID); + m_diagnostics.ResolveDirtyCheck(sceneID); } return closed; } - internal void RestoreActiveScene(Guid? activeSceneId) + internal void RestoreActiveScene(Guid? activeSceneID) { using IDisposable scope = EnterPresentationScope(); - if (activeSceneId is Guid sceneId && FindEngineObject(sceneId) is GameScene { isLoaded: true } active) + if (activeSceneID is Guid sceneID && FindEngineObject(sceneID) is GameScene { isLoaded: true } active) + { world.SetActiveScene(active); + } else if (world.loadedScenes.Count > 0 && world.activeScene is null) + { world.SetActiveScene(world.loadedScenes[0]); + } } internal void RestoreSelection( - Guid? selectedId, + Guid? selectedID, bool selectActiveSceneWhenMissing = true ) { if (m_selection is null) + { return; - object? target = selectedId is Guid id ? FindEngineObject(id) : null; + } + object? target = selectedID is Guid id ? FindEngineObject(id) : null; if (target is null && selectActiveSceneWhenMissing) + { target = world.activeScene; + } m_selection.SetSelection(target); } private EngineObject? FindEngineObject(Guid id) => world.Find(id); - private Guid? GetSelectedSceneObjectId() + private Guid? GetSelectedSceneObjectID() => m_selection?.selectedTarget is EngineObject { isDestroyed: false } selected - ? selected.identity.persistentId - : null; + ? selected.identity.persistentID + : null; internal sealed record SceneDocumentSnapshot( - Guid sceneId, + Guid sceneID, byte[] payload, string sourcePath, - Guid sourceAssetId, + Guid sourceAssetID, byte[] savedHash, bool isDirty, int sceneIndex, long nextRefreshTimestamp = 0 ); - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs index 16cff4faa..9628c0d25 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - /// /// Gets whether a scene contains unsaved serialized changes. /// @@ -49,17 +47,23 @@ public bool IsDirty(GameScene scene) try { if (!SynchronizeSource(scene, document)) + { return true; + } } catch (Exception exception) { document.isDirty = true; if (m_diagnostics.PublishSynchronizationFailure(scene, exception)) + { m_log.Write(LogLevel.Error, "Scene document synchronization failed: {0}", [exception]); + } return true; } if (string.IsNullOrEmpty(document.sourcePath)) + { return true; + } if (!string.Equals(scene.name, GetAssetName(document.sourcePath), StringComparison.Ordinal)) { document.isDirty = true; @@ -68,19 +72,23 @@ public bool IsDirty(GameScene scene) long now = Stopwatch.GetTimestamp(); if (now < document.nextRefreshTimestamp) + { return document.isDirty; + } document.nextRefreshTimestamp = now + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); try { document.isDirty = HasSerializedChanges(scene, document); - m_diagnostics.ResolveDirtyCheck(scene.identity.persistentId); + m_diagnostics.ResolveDirtyCheck(scene.identity.persistentID); } catch (Exception exception) { document.isDirty = true; if (m_diagnostics.PublishDirtyCheckFailure(scene, exception)) + { m_log.Write(LogLevel.Error, "Scene dirty check failed: {0}", [exception]); + } } return document.isDirty; } @@ -142,9 +150,9 @@ string currentDirectory string currentParent = NormalizePath(Path.GetDirectoryName(currentPath)); string targetDirectory = NormalizePath(currentDirectory); string relativePath; - if (!string.IsNullOrEmpty(currentPath) && - string.Equals(currentParent, targetDirectory, StringComparison.Ordinal)) - { + if (!string.IsNullOrEmpty(currentPath) + && string.Equals(currentParent, targetDirectory, StringComparison.Ordinal) + ) { relativePath = RenameSceneSourceIfNeeded(scene, document); } else @@ -175,10 +183,10 @@ string currentDirectory EnsureCanPersist(); EnsureEditable(gameObject.scene); string relativePath = CreateUniquePath(currentDirectory, gameObject.name, C_PREFAB_EXTENSION); - if (!m_assets.Save( - AssetPath.Project(relativePath), - PrefabAsset.Capture(gameObject, m_serialization, m_assets))) + if (!m_assets.Save(AssetPath.Project(relativePath), PrefabAsset.Capture(gameObject, m_serialization, m_assets))) + { throw new InvalidOperationException($"No asset importer could save prefab '{relativePath}'."); + } return relativePath; } @@ -196,10 +204,11 @@ public GameScene Open(string relativePath) ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); EnsureCanPersist(); string normalizedPath = NormalizePath(relativePath); - SceneDocument? existing = m_documents.Values.FirstOrDefault(document => - document.scene.isLoaded && - !document.scene.isDestroyed && - string.Equals(document.sourcePath, normalizedPath, StringComparison.OrdinalIgnoreCase)); + SceneDocument? existing = m_documents.Values.FirstOrDefault(document => ( + document.scene.isLoaded + && !document.scene.isDestroyed + && string.Equals(document.sourcePath, normalizedPath, StringComparison.OrdinalIgnoreCase) + )); if (existing is not null) { m_runtimeSession.scenes.SetActiveScene(existing.scene); @@ -212,8 +221,9 @@ public GameScene Open(string relativePath) byte[] savedHash = ComputeSceneHash(scene); m_runtimeSession.scenes.LoadSceneAdditive(scene); m_documents.Add( - scene.identity.persistentId, - new SceneDocument(scene, normalizedPath, asset.identity.persistentId, savedHash)); + scene.identity.persistentID, + new SceneDocument(scene, normalizedPath, asset.identity.persistentID, savedHash) + ); return scene; } @@ -238,10 +248,11 @@ out string relativePath { EnsurePresentedScene(scene); relativePath = playModeSession.TryGetSnapshot( - scene.identity.persistentId, - out SceneDocumentSnapshot snapshot) - ? snapshot.sourcePath - : string.Empty; + scene.identity.persistentID, + out SceneDocumentSnapshot snapshot + ) + ? snapshot.sourcePath + : string.Empty; return !string.IsNullOrEmpty(relativePath); } SceneDocument document = GetOrCreateDocument(scene); @@ -249,8 +260,9 @@ out string relativePath { SynchronizeSource(scene, document); } - catch + catch (Exception) { + // The source could not be synchronized. The document stays dirty. document.isDirty = true; } relativePath = document.sourcePath; @@ -262,38 +274,44 @@ private void SaveSceneAtPath( string relativePath ) { SceneDocument document = GetOrCreateDocument(scene); - if (document.sourceAssetId != Guid.Empty && - string.Equals(document.sourcePath, relativePath, StringComparison.Ordinal) && !SynchronizeSource(scene, document)) - throw new InvalidOperationException($"Scene source '{relativePath}' is unavailable. Restore its source or explicitly save to another directory."); + if (document.sourceAssetID != Guid.Empty + && string.Equals(document.sourcePath, relativePath, StringComparison.Ordinal) && !SynchronizeSource(scene, document) + ) { + throw new InvalidOperationException( + $"Scene source '{relativePath}' is unavailable. Restore its source or explicitly save to another directory." + ); + } scene.name = GetAssetName(relativePath); bool exists = m_assets.TryLoad(AssetPath.Parse(relativePath), out SceneAsset? sceneAsset); sceneAsset ??= new SceneAsset(); sceneAsset.CaptureFrom(scene, m_serialization, m_assets); bool saved = exists - ? m_assets.Save(sceneAsset) - : m_assets.Save(AssetPath.Parse(relativePath), sceneAsset); + ? m_assets.Save(sceneAsset) + : m_assets.Save(AssetPath.Parse(relativePath), sceneAsset); if (!saved) + { throw new InvalidOperationException($"No asset importer could save scene '{relativePath}'."); + } byte[] savedHash = ComputeSceneHash(scene); document.sourcePath = relativePath; - document.sourceAssetId = sceneAsset.identity.persistentId; + document.sourceAssetID = sceneAsset.identity.persistentID; document.savedHash = savedHash; document.isDirty = false; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } private SceneDocument GetOrCreateDocument(GameScene scene) { - Guid sceneId = scene.identity.persistentId; - if (m_documents.TryGetValue(sceneId, out SceneDocument? document)) + Guid sceneID = scene.identity.persistentID; + if (m_documents.TryGetValue(sceneID, out SceneDocument? document)) { document.scene = scene; return document; } document = new SceneDocument(scene, string.Empty, Guid.Empty, []); - m_documents.Add(sceneId, document); + m_documents.Add(sceneID, document); return document; } @@ -302,7 +320,8 @@ private void EnsureCanPersist() if (!canPersist) { throw new InvalidOperationException( - "Scene and prefab persistence is unavailable while Play Mode runtime copies are active."); + "Scene and prefab persistence is unavailable while Play Mode runtime copies are active." + ); } } @@ -314,11 +333,15 @@ private byte[] ComputeSceneHash( SerializationContext context = AssetSerializationContext.Create(m_assets, dependencies); SerializationSnapshot captured = m_serialization.CaptureSnapshot(scene, context, document?.observedSnapshot); if (document is not null && ReferenceEquals(captured, document.observedSnapshot)) + { return document.observedHash!; - using var algorithm = SHA256.Create(); + } + using SHA256 algorithm = SHA256.Create(); using (var digest = new CryptoStream(Stream.Null, algorithm, CryptoStreamMode.Write, leaveOpen: true)) using (var output = new BufferedStream(digest, 64 * 1024)) + { captured.WriteTo(output); + } byte[] hash = algorithm.Hash ?? throw new InvalidOperationException("Scene content hashing did not complete."); if (document is not null) { @@ -331,8 +354,7 @@ private byte[] ComputeSceneHash( private bool HasSerializedChanges( GameScene scene, SceneDocument document - ) - => !ComputeSceneHash(scene, document).AsSpan().SequenceEqual(document.savedHash); + ) => !ComputeSceneHash(scene, document).AsSpan().SequenceEqual(document.savedHash); private string CreateUniquePath( string directory, @@ -343,21 +365,27 @@ string extension string fileName = SanitizeFileName(name); string candidate = Combine(directory, fileName + extension); for (int suffix = 1; m_assets.TryGetFileSystemEntry(AssetPath.Parse(candidate), out _); suffix++) + { candidate = Combine(directory, $"{fileName} {suffix}{extension}"); + } return candidate; } private static string CreateUniqueSceneName(IReadOnlyList scenes) { - const string c_baseName = "Untitled Scene"; - var names = scenes.Select(static scene => scene.name).ToHashSet(StringComparer.Ordinal); - if (!names.Contains(c_baseName)) - return c_baseName; + const string C_BASE_NAME = "Untitled Scene"; + HashSet names = scenes.Select(static scene => scene.name).ToHashSet(StringComparer.Ordinal); + if (!names.Contains(C_BASE_NAME)) + { + return C_BASE_NAME; + } for (int suffix = 1; ; suffix++) { - string candidate = $"{c_baseName} {suffix}"; + string candidate = $"{C_BASE_NAME} {suffix}"; if (!names.Contains(candidate)) + { return candidate; + } } } @@ -370,28 +398,29 @@ private static string GetAssetName(string relativePath) private static string SanitizeFileName(string value) { char[] invalid = Path.GetInvalidFileNameChars(); - string sanitized = new((value ?? string.Empty) - .Trim() - .Select(character => invalid.Contains(character) ? '_' : character) - .ToArray()); + var sanitized = new string( + (value ?? string.Empty) + .Trim() + .Select(character => invalid.Contains(character) ? '_' : character) + .ToArray() + ); return string.IsNullOrWhiteSpace(sanitized) ? "Untitled" : sanitized; } private static string Combine( string directory, string fileName - ) - => string.IsNullOrEmpty(directory) ? fileName : $"{directory}/{fileName}"; + ) => string.IsNullOrEmpty(directory) ? fileName : $"{directory}/{fileName}"; private static string NormalizePath(string? path) => string.IsNullOrWhiteSpace(path) - ? string.Empty - : path.Replace('\\', '/').Trim('/'); + ? string.Empty + : path.Replace('\\', '/').Trim('/'); private sealed class SceneDocument( GameScene scene, string sourcePath, - Guid sourceAssetId, + Guid sourceAssetID, byte[] savedHash ) { internal SerializationSnapshot? observedSnapshot; @@ -401,26 +430,30 @@ byte[] savedHash /// The scene value used as part of this type's public representation. /// public GameScene scene = scene; + /// /// The source path value used as part of this type's public representation. /// public string sourcePath = sourcePath; + /// /// The source asset id value used as part of this type's public representation. /// - public Guid sourceAssetId = sourceAssetId; + public Guid sourceAssetID = sourceAssetID; + /// /// The saved hash value used as part of this type's public representation. /// public byte[] savedHash = savedHash; + /// /// The is dirty value used as part of this type's public representation. /// public bool isDirty; + /// /// The next refresh timestamp value used as part of this type's public representation. /// public long nextRefreshTimestamp; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs index 412083e54..113fa74f6 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) { ArgumentNullException.ThrowIfNull(runtimeSession); @@ -34,13 +32,18 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) { throw new ArgumentException( "An editor Play Mode scene session requires a Play runtime session.", - nameof(runtimeSession)); + nameof(runtimeSession) + ); } SceneWorld runtimeWorld = runtimeSession.scenes; if (m_isPreparingPlayMode || m_playModeSession is not null) + { throw new InvalidOperationException("An editor Play Mode scene session is already active."); + } if (runtimeWorld.loadedScenes.Count != 0) + { throw new InvalidOperationException("A Play Mode scene snapshot requires an empty runtime world."); + } m_isPreparingPlayMode = true; try @@ -50,21 +53,24 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) .Select(CaptureDocumentSnapshot) .OrderBy(static snapshot => snapshot.sceneIndex) .ToArray(); - Guid? activeSceneId = m_runtimeSession.scenes.activeScene?.identity.persistentId; - Guid? selectedSceneObjectId = GetSelectedSceneObjectId(); + Guid? activeSceneID = m_runtimeSession.scenes.activeScene?.identity.persistentID; + Guid? selectedSceneObjectID = GetSelectedSceneObjectID(); var session = new PlayModeLease( this, runtimeSession, snapshots, - activeSceneId, - selectedSceneObjectId, - m_selection?.RegisterIdentityDomain(runtimeSession.identities)); + activeSceneID, + selectedSceneObjectID, + m_selection?.RegisterIdentityDomain(runtimeSession.identities) + ); try { MaterializeRuntimeSceneSet(session); m_playModeSession = session; - if (selectedSceneObjectId is not null) - RestoreSelection(selectedSceneObjectId); + if (selectedSceneObjectID is not null) + { + RestoreSelection(selectedSceneObjectID); + } return session; } catch (Exception startupFailure) @@ -75,7 +81,11 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) } catch (Exception cleanupFailure) { - throw new AggregateException("Play scene preparation and identity routing retirement failed.", startupFailure, cleanupFailure); + throw new AggregateException( + "Play scene preparation and identity routing retirement failed.", + startupFailure, + cleanupFailure + ); } throw; } @@ -89,20 +99,24 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) private void ReleasePlayModeLease(PlayModeLease session) { if (!ReferenceEquals(m_playModeSession, session)) + { return; + } object? runtimeSelection = m_selection?.selectedTarget; - Guid? runtimeSelectionId = runtimeSelection is EngineObject { isDestroyed: false } selected - ? selected.identity.persistentId - : null; + Guid? runtimeSelectionID = runtimeSelection is EngineObject { isDestroyed: false } selected + ? selected.identity.persistentID + : null; m_playModeSession = null; - Guid? editSelectionId = runtimeSelectionId is Guid currentId && - m_runtimeSession.scenes.Find(currentId) is not null - ? currentId - : session.editSelectionId; + Guid? editSelectionID = runtimeSelectionID is Guid currentID + && m_runtimeSession.scenes.Find(currentID) is not null + ? currentID + : session.editSelectionID; try { - if (runtimeSelection is EngineObject || runtimeSelection is null && session.editSelectionId is not null) - RestoreSelection(editSelectionId, selectActiveSceneWhenMissing: false); + if (runtimeSelection is EngineObject || runtimeSelection is null && session.editSelectionID is not null) + { + RestoreSelection(editSelectionID, selectActiveSceneWhenMissing: false); + } } catch { @@ -123,18 +137,19 @@ private void MaterializeRuntimeSceneSet(PlayModeLease session) for (int i = 0; i < snapshots.Count; i++) { SceneDocumentSnapshot snapshot = snapshots[i]; - GameScene runtimeScene = m_serialization.Deserialize( - snapshot.payload, - serializationContext); + GameScene runtimeScene = m_serialization.Deserialize(snapshot.payload, serializationContext); runtimeWorld.LoadSceneAdditive(runtimeScene, makeActive: false); runtimeWorld.SetSceneIndex(runtimeScene, snapshot.sceneIndex); } - if (session.activeSceneId is Guid activeSceneId) + if (session.activeSceneID is Guid activeSceneID) { GameScene? activeScene = runtimeWorld.loadedScenes.FirstOrDefault( - scene => scene.identity.persistentId == activeSceneId); + scene => scene.identity.persistentID == activeSceneID + ); if (activeScene is not null) + { runtimeWorld.SetActiveScene(activeScene); + } } } catch (Exception exception) @@ -148,11 +163,13 @@ private void MaterializeRuntimeSceneSet(PlayModeLease session) throw new AggregateException( "The Play Mode scene set could not be constructed and its partial state could not be released.", exception, - cleanupFailure); + cleanupFailure + ); } throw new InvalidOperationException( "The Play Mode start snapshot could not be materialized in its isolated runtime world.", - exception); + exception + ); } } @@ -165,18 +182,9 @@ private sealed class PlayModeLease( IDisposable? identityDomain ) : IDisposable { - private readonly Dictionary m_snapshotBySceneId = - sceneSnapshots.ToDictionary(static snapshot => snapshot.sceneId); - - internal IReadOnlyList snapshots { get; } = sceneSnapshots; - - internal Guid? activeSceneId { get; } = activeScene; - - internal Guid? editSelectionId { get; } = selectedSceneObject; - - internal RuntimeSession runtimeSession { get; } = playSession; - - internal SceneWorld runtimeWorld => runtimeSession.scenes; + private readonly Dictionary m_snapshotBySceneID = sceneSnapshots.ToDictionary( + static snapshot => snapshot.sceneID + ); private bool m_disposed; @@ -186,12 +194,24 @@ private sealed class PlayModeLease( public void Dispose() { if (m_disposed) + { return; + } workspace.ReleasePlayModeLease(this); identityDomain?.Dispose(); m_disposed = true; } + internal IReadOnlyList snapshots { get; } = sceneSnapshots; + + internal Guid? activeSceneID { get; } = activeScene; + + internal Guid? editSelectionID { get; } = selectedSceneObject; + + internal RuntimeSession runtimeSession { get; } = playSession; + + internal SceneWorld runtimeWorld => runtimeSession.scenes; + internal void Capture(EditorState state) { state.Set( @@ -199,19 +219,18 @@ internal void Capture(EditorState state) sceneSnapshots .Select(static snapshot => snapshot.sourcePath) .Where(static path => !string.IsNullOrEmpty(path)) - .ToArray()); - string activePath = activeSceneId is Guid activeId && - m_snapshotBySceneId.TryGetValue(activeId, out SceneDocumentSnapshot? active) - ? active.sourcePath - : string.Empty; + .ToArray() + ); + string activePath = activeSceneID is Guid activeID + && m_snapshotBySceneID.TryGetValue(activeID, out SceneDocumentSnapshot? active) + ? active.sourcePath + : string.Empty; state.Set("activeScene", activePath); } internal bool TryGetSnapshot( - Guid sceneId, + Guid sceneID, out SceneDocumentSnapshot snapshot - ) - => m_snapshotBySceneId.TryGetValue(sceneId, out snapshot!); + ) => m_snapshotBySceneID.TryGetValue(sceneID, out snapshot!); } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs index 44924bff3..af384a85c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,37 +25,35 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) { ArgumentNullException.ThrowIfNull(context); if (m_playModeSession is not null) { - return new WorkspaceReloadTransaction( - this, - Array.Empty(), - preserveDocumentBaselines: true); + return new WorkspaceReloadTransaction(this, [], preserveDocumentBaselines: true); } ApplyPendingSourceChanges(); var documents = new List(m_documents.Count); - foreach ((Guid sceneId, SceneDocument document) in m_documents) + foreach ((Guid sceneID, SceneDocument document) in m_documents) { GameScene scene = document.scene; if (scene.isDestroyed) + { continue; + } bool sourceAvailable = SynchronizeSource(scene, document); - bool wasDirty = !sourceAvailable || string.IsNullOrEmpty(document.sourcePath) || - !string.Equals( - scene.name, - GetAssetName(document.sourcePath), - StringComparison.Ordinal) || - HasSerializedChanges(scene, document); - documents.Add(new ReloadDocumentState( - sceneId, - document.savedHash.ToArray(), - document.isDirty, - document.nextRefreshTimestamp, - wasDirty)); + bool wasDirty = !sourceAvailable || string.IsNullOrEmpty(document.sourcePath) + || !string.Equals(scene.name, GetAssetName(document.sourcePath), StringComparison.Ordinal) + || HasSerializedChanges(scene, document); + documents.Add( + new ReloadDocumentState( + sceneID, + document.savedHash.ToArray(), + document.isDirty, + document.nextRefreshTimestamp, + wasDirty + ) + ); } return new WorkspaceReloadTransaction(this, documents, preserveDocumentBaselines: false); } @@ -70,9 +67,7 @@ bool preserveDocumentBaselines /// /// Prepares candidate state without changing the active generation. /// - public void PrepareForActivation() - { - } + public void PrepareForActivation() {} /// /// Applies the prepared state at the caller-controlled commit point. @@ -81,11 +76,15 @@ public void Apply() { workspace.SynchronizeReplacedScenes(); if (preserveDocumentBaselines) + { return; + } foreach (ReloadDocumentState state in documents) { - if (!workspace.m_documents.TryGetValue(state.sceneId, out SceneDocument? document)) + if (!workspace.m_documents.TryGetValue(state.sceneID, out SceneDocument? document)) + { continue; + } if (state.wasDirty) { document.isDirty = true; @@ -95,17 +94,15 @@ public void Apply() document.savedHash = workspace.ComputeSceneHash(document.scene); document.isDirty = false; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } } /// /// Completes the committed operation and releases temporary state. /// - public void Complete() - { - } + public void Complete() {} /// /// Restores the state that existed before candidate activation began. @@ -122,8 +119,10 @@ private void RestoreBaseline() workspace.SynchronizeReplacedScenes(); foreach (ReloadDocumentState state in documents) { - if (!workspace.m_documents.TryGetValue(state.sceneId, out SceneDocument? document)) + if (!workspace.m_documents.TryGetValue(state.sceneID, out SceneDocument? document)) + { continue; + } document.savedHash = state.savedHash.ToArray(); document.isDirty = state.isDirty; document.nextRefreshTimestamp = state.nextRefreshTimestamp; @@ -132,11 +131,10 @@ private void RestoreBaseline() } private readonly record struct ReloadDocumentState( - Guid sceneId, + Guid sceneID, byte[] savedHash, bool isDirty, long nextRefreshTimestamp, bool wasDirty ); - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs index ab7555c81..708cee8df 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - /// /// Captures an immutable snapshot of the current observable state. /// @@ -52,7 +50,9 @@ protected override void Capture(EditorState state) .ToArray(); state.Set("openScenes", scenePaths); if (m_runtimeSession.scenes.activeScene is GameScene active && TryGetSourcePath(active, out string activePath)) + { state.Set("activeScene", activePath); + } } /// @@ -89,13 +89,17 @@ private void TryRestorePendingScenes() } long typeCatalogVersion = m_types.current.version; if (m_waitingTypeCatalogVersion == typeCatalogVersion) + { return; + } long now = Stopwatch.GetTimestamp(); if (now < m_nextRestoreAttemptTimestamp) + { return; + } m_nextRestoreAttemptTimestamp = now + Stopwatch.Frequency / 4; - var candidates = new List<(GameScene Scene, string Path, Guid AssetId, byte[] Hash)>(); + List<(GameScene scene, string path, Guid assetID, byte[] hash)> candidates = []; bool waitingForSourceIndex = false; try { @@ -106,7 +110,8 @@ private void TryRestorePendingScenes() { string absolutePath = Path.Combine( m_assets.assetRoot, - path.Replace('/', Path.DirectorySeparatorChar)); + path.Replace('/', Path.DirectorySeparatorChar) + ); if (File.Exists(absolutePath)) { waitingForSourceIndex = true; @@ -118,26 +123,22 @@ private void TryRestorePendingScenes() SceneAsset asset = m_assets.Load(AssetPath.Parse(path)); GameScene scene = asset.Instantiate(m_serialization, m_assets); scene.name = GetAssetName(path); - candidates.Add(( - scene, - path, - asset.identity.persistentId, - ComputeSceneHash(scene))); + candidates.Add((scene, path, asset.identity.persistentID, ComputeSceneHash(scene))); } } catch (SceneTypeResolutionException exception) { DisposeRestoreCandidates(candidates); m_waitingTypeCatalogVersion = typeCatalogVersion; - string message = - $"{exception.elementKind} stable type id '{exception.stableTypeId}' " + - "is not present in the active type catalog."; + string message = $"{exception.elementKind} stable type id '{exception.stableTypeID}' " + + "is not present in the active type catalog."; if (m_diagnostics.PublishRestoreFailure("SCENE-TYPE", message)) { m_log.Write( LogLevel.Error, "Editor scene workspace cannot restore saved scenes because {0}", - [message]); + [message] + ); } return; } @@ -146,10 +147,9 @@ private void TryRestorePendingScenes() DisposeRestoreCandidates(candidates); m_waitingTypeCatalogVersion = typeCatalogVersion; if (m_diagnostics.PublishRestoreFailure("SCENE-RESTORE", exception.Message)) - m_log.Write( - LogLevel.Error, - "Editor scene workspace could not restore saved scenes: {0}", - [exception]); + { + m_log.Write(LogLevel.Error, "Editor scene workspace could not restore saved scenes: {0}", [exception]); + } return; } if (waitingForSourceIndex) @@ -162,31 +162,32 @@ private void TryRestorePendingScenes() m_documents.Clear(); for (int i = 0; i < candidates.Count; i++) { - (GameScene scene, string path, Guid assetId, byte[] hash) = candidates[i]; + (GameScene scene, string path, Guid assetID, byte[] hash) = candidates[i]; m_runtimeSession.scenes.LoadSceneAdditive(scene, makeActive: false); - m_documents.Add( - scene.identity.persistentId, - new SceneDocument(scene, path, assetId, hash)); + m_documents.Add(scene.identity.persistentID, new SceneDocument(scene, path, assetID, hash)); } SceneDocument? activeDocument = m_documents.Values.FirstOrDefault(document => string.Equals(document.sourcePath, m_pendingActivePath, StringComparison.OrdinalIgnoreCase)); if (activeDocument is not null && activeDocument.scene.isLoaded) + { m_runtimeSession.scenes.SetActiveScene(activeDocument.scene); + } m_selection?.SetSelection(null); m_pendingScenePaths = null; m_waitingTypeCatalogVersion = -1; m_diagnostics.ResolveRestore(); } - private void DisposeRestoreCandidates(IReadOnlyList<(GameScene Scene, string Path, Guid AssetId, byte[] Hash)> candidates) + private void DisposeRestoreCandidates(IReadOnlyList<(GameScene scene, string path, Guid assetID, byte[] hash)> candidates) { for (int i = candidates.Count - 1; i >= 0; i--) { - if (candidates[i].Scene.isDestroyed) + if (candidates[i].scene.isDestroyed) + { continue; - m_runtimeSession.scenes.LoadSceneAdditive(candidates[i].Scene, makeActive: false); - _ = m_runtimeSession.scenes.UnloadScene(candidates[i].Scene); + } + m_runtimeSession.scenes.LoadSceneAdditive(candidates[i].scene, makeActive: false); + _ = m_runtimeSession.scenes.UnloadScene(candidates[i].scene); } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs index c97c7bc70..6ca361c21 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,40 +25,43 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - private bool SynchronizeSource( GameScene scene, SceneDocument document ) { - if (document.sourceAssetId == Guid.Empty) + if (document.sourceAssetID == Guid.Empty) { - m_diagnostics.ResolveSynchronization(scene.identity.persistentId); + m_diagnostics.ResolveSynchronization(scene.identity.persistentID); return true; } - if (!m_assets.TryGetInfo(document.sourceAssetId, out AssetInfo? asset) || - asset is null || - asset.status == AssetImportStatus.Missing) - { + if (!m_assets.TryGetInfo(document.sourceAssetID, out AssetInfo? asset) + || asset is null + || asset.status == AssetImportStatus.Missing + ) { document.isDirty = true; m_diagnostics.PublishSourceUnavailable(scene, document.sourcePath); return false; } - m_diagnostics.ResolveSynchronization(scene.identity.persistentId); + m_diagnostics.ResolveSynchronization(scene.identity.persistentID); string sourcePath = NormalizePath(asset.assetPath.ToString()); string sourceName = GetAssetName(sourcePath); bool pathChanged = !string.Equals(document.sourcePath, sourcePath, StringComparison.Ordinal); if (!pathChanged) + { return true; + } bool wasDirty = HasSerializedChanges(scene, document); document.sourcePath = sourcePath; scene.name = sourceName; if (!wasDirty) + { document.savedHash = ComputeSceneHash(scene); + } document.isDirty = wasDirty; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); return true; } @@ -69,9 +71,9 @@ string newRelativePath ) { string oldPath = NormalizePath(oldRelativePath); string newPath = NormalizePath(newRelativePath); - if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out Inno.Assets.Pipeline.AssetFileEntry entry) && - entry.isDirectory) - { + if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out AssetFileEntry entry) + && entry.isDirectory + ) { ApplyDirectoryRename(oldPath, newPath); return; } @@ -82,7 +84,9 @@ string newRelativePath return; } if (string.Equals(extension, C_PREFAB_EXTENSION, StringComparison.OrdinalIgnoreCase)) + { ApplyPrefabRename(oldPath, newPath); + } } private void ApplySceneRename( @@ -91,9 +95,9 @@ string newPath ) { foreach (SceneDocument document in m_documents.Values) { - if (!string.Equals(document.sourcePath, oldPath, StringComparison.OrdinalIgnoreCase) || - document.scene.isDestroyed) - { + if (!string.Equals(document.sourcePath, oldPath, StringComparison.OrdinalIgnoreCase) + || document.scene.isDestroyed + ) { continue; } @@ -108,9 +112,9 @@ string newPath string oldPrefix = oldPath + "/"; foreach (SceneDocument document in m_documents.Values) { - if (document.scene.isDestroyed || - !document.sourcePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase)) - { + if (document.scene.isDestroyed + || !document.sourcePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase) + ) { continue; } @@ -126,13 +130,17 @@ string newPath bool wasDirty = HasSerializedChanges(document.scene, document); document.sourcePath = newPath; document.scene.name = GetAssetName(newPath); - if (m_assets.TryGetPersistentId(AssetPath.Parse(newPath), out Guid sourceAssetId)) - document.sourceAssetId = sourceAssetId; + if (m_assets.TryGetPersistentID(AssetPath.Parse(newPath), out Guid sourceAssetID)) + { + document.sourceAssetID = sourceAssetID; + } if (!wasDirty) + { document.savedHash = ComputeSceneHash(document.scene); + } document.isDirty = wasDirty; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } private string RenameSceneSourceIfNeeded( @@ -143,11 +151,14 @@ SceneDocument document string directory = NormalizePath(Path.GetDirectoryName(currentPath)); string targetPath = Combine(directory, SanitizeFileName(scene.name) + C_SCENE_EXTENSION); if (string.Equals(currentPath, targetPath, StringComparison.Ordinal)) + { return currentPath; + } if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) { throw new IOException( - $"Scene asset '{targetPath}' already exists. Choose a different scene name before saving."); + $"Scene asset '{targetPath}' already exists. Choose a different scene name before saving." + ); } m_assets.Move(AssetPath.Parse(currentPath), AssetPath.Parse(targetPath)); @@ -159,8 +170,10 @@ private void ApplyPrefabRename( string oldPath, string newPath ) { - if (!m_assets.TryGetPersistentId(AssetPath.Parse(newPath), out Guid sourceAssetId)) + if (!m_assets.TryGetPersistentID(AssetPath.Parse(newPath), out Guid sourceAssetID)) + { return; + } string oldName = GetAssetName(oldPath); string newName = GetAssetName(newPath); IReadOnlyList scenes = m_runtimeSession.scenes.loadedScenes; @@ -171,10 +184,10 @@ string newPath { GameObject gameObject = objects[objectIndex]; PrefabInstanceInfo? prefab = gameObject.prefabInstance; - if (prefab?.isRoot == true && - prefab.sourceAssetId == sourceAssetId && - string.Equals(gameObject.name, oldName, StringComparison.Ordinal)) - { + if (prefab?.isRoot == true + && prefab.sourceAssetID == sourceAssetID + && string.Equals(gameObject.name, oldName, StringComparison.Ordinal) + ) { gameObject.name = newName; } } @@ -185,7 +198,9 @@ private void OnAssetDatabaseChanged(AssetChangeSet changeSet) { m_waitingTypeCatalogVersion = -1; for (int i = 0; i < changeSet.changes.Count; i++) + { m_sourceChanges.Enqueue(changeSet.changes[i]); + } } private void ApplyPendingSourceChanges() @@ -195,9 +210,9 @@ private void ApplyPendingSourceChanges() try { if (change.kind == AssetChangeKind.Moved) - ApplyRename( - change.previousAssetPath?.ToString() ?? string.Empty, - change.assetPath.ToString()); + { + ApplyRename(change.previousAssetPath?.ToString() ?? string.Empty, change.assetPath.ToString()); + } } catch (Exception exception) { @@ -212,12 +227,11 @@ private void SynchronizeReplacedScenes() for (int i = 0; i < loaded.Count; i++) { GameScene scene = loaded[i]; - if (m_documents.TryGetValue(scene.identity.persistentId, out SceneDocument? document) && - !ReferenceEquals(document.scene, scene)) - { + if (m_documents.TryGetValue(scene.identity.persistentID, out SceneDocument? document) + && !ReferenceEquals(document.scene, scene) + ) { document.scene = scene; } } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs index 7cb5304de..b43f3571f 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -93,31 +92,22 @@ internal EditorSceneWorkspace( LogRouter logs, IEditorSelectionCoordinator? selection = null ) { - m_runtimeSession = runtimeSession ?? throw new ArgumentNullException(nameof(runtimeSession)); - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_reloads = reloads ?? throw new ArgumentNullException(nameof(reloads)); + ArgumentNullException.ThrowIfNull(runtimeSession); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(reloads); + m_runtimeSession = runtimeSession; + m_assets = assets; + m_types = types; + m_serialization = serialization; + m_reloads = reloads; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); m_selection = selection; m_sceneStateDiagnostics = new SceneStateDiagnosticTracker(runtimeSession.scenes, types); } - internal SceneWorld world => m_playModeSession?.runtimeWorld ?? m_runtimeSession.scenes; - - internal IDisposable EnterPresentationScope() => (m_playModeSession?.runtimeSession ?? m_runtimeSession).EnterExecutionScope(); - - internal SerializationRegistry serialization => m_serialization; - - internal IAssetReferenceResolver assets => m_assets; - - internal TypeCatalog types => m_types; - - internal TSceneObject? Find(Guid persistentId) - where TSceneObject : IdentityObject - => world.Find(persistentId); - /// /// Gets all scenes currently available to editor features. /// @@ -146,19 +136,23 @@ internal EditorSceneWorkspace( public bool CanEdit(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); - if (m_isPreparingPlayMode || scene.isDestroyed || !scene.isLoaded || - !world.loadedScenes.Any(candidate => ReferenceEquals(candidate, scene))) + if (m_isPreparingPlayMode || scene.isDestroyed || !scene.isLoaded + || !world.loadedScenes.Any(candidate => ReferenceEquals(candidate, scene)) + ) { return false; + } if (m_playModeSession is PlayModeLease playModeSession) { - if (!playModeSession.TryGetSnapshot(scene.identity.persistentId, out SceneDocumentSnapshot snapshot)) + if (!playModeSession.TryGetSnapshot(scene.identity.persistentID, out SceneDocumentSnapshot snapshot)) + { return true; + } return string.IsNullOrEmpty(snapshot.sourcePath) - || AssetPath.Parse(snapshot.sourcePath).source == AssetSourceId.project; + || AssetPath.Parse(snapshot.sourcePath).source == AssetSourceID.project; } - return !m_documents.TryGetValue(scene.identity.persistentId, out SceneDocument? document) - || string.IsNullOrEmpty(document.sourcePath) - || AssetPath.Parse(document.sourcePath).source == AssetSourceId.project; + return !m_documents.TryGetValue(scene.identity.persistentID, out SceneDocument? document) + || string.IsNullOrEmpty(document.sourcePath) + || AssetPath.Parse(document.sourcePath).source == AssetSourceID.project; } /// @@ -175,9 +169,9 @@ public ContentReadScope Capture() .Where(static scene => !scene.isDestroyed) .ToArray(); GameScene? activeScene = presentedWorld.activeScene; - if (activeScene is { isDestroyed: true } || - activeScene is not null && !scenes.Contains(activeScene)) - { + if (activeScene is { isDestroyed: true } + || activeScene is not null && !scenes.Contains(activeScene) + ) { activeScene = null; } return SceneContentSource.CreateScope(scenes, activeScene); @@ -196,6 +190,100 @@ public void SetActiveScene(GameScene scene) world.SetActiveScene(scene); } + void IEditorReloadParticipant.RefreshDiagnostics() => m_sceneStateDiagnostics.Reconcile(force: true); + + internal SceneWorld world => m_playModeSession?.runtimeWorld ?? m_runtimeSession.scenes; + + internal SerializationRegistry serialization => m_serialization; + + internal IAssetReferenceResolver assets => m_assets; + + internal TypeCatalog types => m_types; + + /// + /// Attaches the workspace to Asset Database changes and ensures an editable scene exists. + /// + /// + /// The shared editor context for the active runtime. + /// + protected override void OnStart(EditorContext context) + { + if (m_isAttached) + { + return; + } + m_assets.changed += OnAssetDatabaseChanged; + m_reloadIntegration = SceneReloadIntegration.Acquire(m_runtimeSession, m_serialization, m_assets, m_reloads); + m_reloadRegistration = m_reloads.Register(this); + m_isAttached = true; + m_sceneStateDiagnostics.Reconcile(force: true); + } + + /// + /// Refreshes source synchronization for loaded editor documents. + /// + /// + /// The shared editor context containing current frame state. + /// + protected override void OnUpdate(EditorContext context) + { + if (m_playModeSession is not null) + { + m_sceneStateDiagnostics.Reconcile(); + return; + } + TryRestorePendingScenes(); + Refresh(); + } + + /// + /// Detaches the workspace from Asset Database changes and releases any scene it created for the editor. + /// + /// + /// The shared editor context for the runtime being stopped. + /// + protected override void OnStop(EditorContext context) + { + if (!m_isAttached) + { + return; + } + try + { + m_playModeSession?.Dispose(); + } + finally + { + m_assets.changed -= OnAssetDatabaseChanged; + m_reloadRegistration?.Dispose(); + m_reloadRegistration = null; + m_runtimeSession.scenes.UnloadAllScenes(); + m_sceneStateDiagnostics.Reconcile(force: true); + m_reloadIntegration?.Dispose(); + m_reloadIntegration = null; + m_isAttached = false; + Clear(); + } + } + + /// + /// Releases resources retained by this feature after it has stopped. + /// + protected override void OnDispose() + { + m_reloadRegistration?.Dispose(); + m_reloadRegistration = null; + m_reloadIntegration?.Dispose(); + m_reloadIntegration = null; + m_diagnostics.Dispose(); + } + + internal IDisposable EnterPresentationScope() => (m_playModeSession?.runtimeSession ?? m_runtimeSession).EnterExecutionScope(); + + internal TSceneObject? Find(Guid persistentID) + where TSceneObject : IdentityObject + => world.Find(persistentID); + internal void DisposeUnattached() { m_playModeSession?.Dispose(); @@ -215,9 +303,7 @@ internal GameScene CreateScene() GameScene scene = world.LoadNewSceneAdditive(name); if (canPersist) { - m_documents.Add( - scene.identity.persistentId, - new SceneDocument(scene, string.Empty, Guid.Empty, [])); + m_documents.Add(scene.identity.persistentID, new SceneDocument(scene, string.Empty, Guid.Empty, [])); } return scene; } @@ -235,9 +321,11 @@ internal void Refresh() foreach (SceneDocument document in m_documents.Values) { if (document.scene.isDestroyed) + { continue; - Guid sceneId = document.scene.identity.persistentId; - synchronizedScenes.Add(sceneId); + } + Guid sceneID = document.scene.identity.persistentID; + synchronizedScenes.Add(sceneID); try { SynchronizeSource(document.scene, document); @@ -246,7 +334,9 @@ internal void Refresh() { document.isDirty = true; if (m_diagnostics.PublishSynchronizationFailure(document.scene, exception)) + { m_log.Write(LogLevel.Error, "Scene document synchronization failed: {0}", [exception]); + } } } m_diagnostics.RetainSynchronizationTargets(synchronizedScenes); @@ -266,15 +356,17 @@ internal bool CloseScene(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); if (scene.isDestroyed) + { return false; + } using IDisposable scope = EnterPresentationScope(); - Guid sceneId = scene.identity.persistentId; + Guid sceneID = scene.identity.persistentID; bool closed = world.UnloadScene(scene); if (closed && canPersist) { - m_documents.Remove(sceneId); - m_diagnostics.ResolveSynchronization(sceneId); - m_diagnostics.ResolveDirtyCheck(sceneId); + m_documents.Remove(sceneID); + m_diagnostics.ResolveSynchronization(sceneID); + m_diagnostics.ResolveDirtyCheck(sceneID); } return closed; } @@ -291,92 +383,14 @@ internal void Clear() } } - /// - /// Attaches the workspace to Asset Database changes and ensures an editable scene exists. - /// - /// - /// The shared editor context for the active runtime. - /// - protected override void OnStart(EditorContext context) - { - if (m_isAttached) - return; - m_assets.Changed += OnAssetDatabaseChanged; - m_reloadIntegration = SceneReloadIntegration.Acquire( - m_runtimeSession, - m_serialization, - m_assets, - m_reloads); - m_reloadRegistration = m_reloads.Register(this); - m_isAttached = true; - m_sceneStateDiagnostics.Reconcile(force: true); - } - - /// - /// Refreshes source synchronization for loaded editor documents. - /// - /// - /// The shared editor context containing current frame state. - /// - protected override void OnUpdate(EditorContext context) - { - if (m_playModeSession is not null) - { - m_sceneStateDiagnostics.Reconcile(); - return; - } - TryRestorePendingScenes(); - Refresh(); - } - - /// - /// Detaches the workspace from Asset Database changes and releases any scene it created for the editor. - /// - /// - /// The shared editor context for the runtime being stopped. - /// - protected override void OnStop(EditorContext context) - { - if (!m_isAttached) - return; - try - { - m_playModeSession?.Dispose(); - } - finally - { - m_assets.Changed -= OnAssetDatabaseChanged; - m_reloadRegistration?.Dispose(); - m_reloadRegistration = null; - m_runtimeSession.scenes.UnloadAllScenes(); - m_sceneStateDiagnostics.Reconcile(force: true); - m_reloadIntegration?.Dispose(); - m_reloadIntegration = null; - m_isAttached = false; - Clear(); - } - } - - /// - /// Releases resources retained by this feature after it has stopped. - /// - protected override void OnDispose() - { - m_reloadRegistration?.Dispose(); - m_reloadRegistration = null; - m_reloadIntegration?.Dispose(); - m_reloadIntegration = null; - m_diagnostics.Dispose(); - } - - void IEditorReloadParticipant.RefreshDiagnostics() - => m_sceneStateDiagnostics.Reconcile(force: true); - internal void EnsureEditable(GameScene scene) { if (!CanEdit(scene)) + { throw new InvalidOperationException( - "The scene is not editable in the current presentation or belongs to a read-only source."); + "The scene is not editable in the current presentation or belongs to a read-only source." + ); + } } private void EnsurePresentedScene(GameScene scene) @@ -385,9 +399,12 @@ private void EnsurePresentedScene(GameScene scene) for (int i = 0; i < presentedScenes.Count; i++) { if (ReferenceEquals(presentedScenes[i], scene)) + { return; + } } throw new InvalidOperationException( - "The scene is not owned by the Editor's active Edit or Play presentation session."); + "The scene is not owned by the Editor's active Edit or Play presentation session." + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs index 62e494514..1a40fb92c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs @@ -1,10 +1,10 @@ using System; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Scene; @@ -48,6 +48,5 @@ public static EditorSceneWorkspaceHost Create( SerializationRegistry serialization, LogRouter logs, IEditorSelectionCoordinator? selection = null - ) - => new(runtimeSession, assets, types, serialization, logs, selection); + ) => new(runtimeSession, assets, types, serialization, logs, selection); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs index b0ff9bec0..cbea478b1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs @@ -1,12 +1,11 @@ using System; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Scene; @@ -34,7 +33,8 @@ internal EditorSceneWorkspaceHost( serialization, new EditorReloadCoordinator(), logs, - selection); + selection + ); } /// @@ -58,7 +58,9 @@ internal EditorSceneWorkspaceHost( public void Dispose() { if (m_disposed) + { return; + } m_workspace.DisposeUnattached(); m_disposed = true; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs index 7e75bc641..a8b5de3a6 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs index 3e4e8e3dc..6538785ae 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Inno.Scene; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs index 1806ec590..fec75d78c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -sealed partial class SceneEdits + +public sealed partial class SceneEdits { /// /// Adds one component and records its identity, stable type, index, and persistent properties. @@ -46,9 +47,9 @@ public GameComponent AddComponent( historyName ?? $"Add {componentType.Name}", new SceneElementHistoryData( SceneElementKind.Component, - owner.scene.identity.persistentId, - owner.identity.persistentId, - component.identity.persistentId, + owner.scene.identity.persistentID, + owner.identity.persistentID, + component.identity.persistentID, typeRef, beforeIndex: -1, afterIndex: owner.GetComponentIndex(component), @@ -66,7 +67,9 @@ public GameComponent AddComponent( RollbackAndRethrow(exception, () => { if (!component.isDestroyed && !owner.RemoveComponent(component)) + { throw new InvalidOperationException("The unrecorded component could not be removed."); + } }); throw; } @@ -91,7 +94,9 @@ public bool RemoveComponent( ArgumentNullException.ThrowIfNull(component); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); if (component.isDestroyed) + { return false; + } m_workspace.EnsureEditable(component.gameObject.scene); GameObject owner = component.gameObject; GameScene scene = owner.scene; @@ -99,19 +104,21 @@ public bool RemoveComponent( byte[] state = SceneElementSerialization.CaptureState(component, m_workspace.serialization, m_workspace.assets); SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming(component, scene, m_workspace); int index = owner.GetComponentIndex(component); - Guid componentId = component.identity.persistentId; + Guid componentID = component.identity.persistentID; Type componentType = component.GetType(); try { if (!owner.RemoveComponent(component)) + { return false; + } RecordElement( historyName ?? $"Remove {componentType.Name}", new SceneElementHistoryData( SceneElementKind.Component, - scene.identity.persistentId, - owner.identity.persistentId, - componentId, + scene.identity.persistentID, + owner.identity.persistentID, + componentID, typeRef, beforeIndex: index, afterIndex: -1, @@ -125,14 +132,22 @@ public bool RemoveComponent( } catch (Exception exception) { - if (m_workspace.Find(componentId) is not null) + if (m_workspace.Find(componentID) is not null) { ExceptionDispatchInfo.Capture(exception).Throw(); } RollbackAndRethrow(exception, () => { - GameComponent restored = SceneElementSerialization.RestoreComponent(owner, typeRef, componentId, index, state, m_workspace.serialization, m_workspace.assets); + GameComponent restored = SceneElementSerialization.RestoreComponent( + owner, + typeRef, + componentID, + index, + state, + m_workspace.serialization, + m_workspace.assets + ); RequireElementRestore(restored, state); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); @@ -172,16 +187,18 @@ public void ResetComponent( } if (before.AsSpan().SequenceEqual(after)) + { return; + } int index = owner.GetComponentIndex(component); RecordWithRollback( () => RecordElement( historyName ?? $"Reset {component.GetType().Name}", new SceneElementHistoryData( SceneElementKind.Component, - owner.scene.identity.persistentId, - owner.identity.persistentId, - component.identity.persistentId, + owner.scene.identity.persistentID, + owner.identity.persistentID, + component.identity.persistentID, GetElementType(component), index, index, @@ -232,15 +249,17 @@ public void SetComponentIndex( } if (beforeIndex == afterIndex) + { return; + } RecordWithRollback( () => RecordElement( historyName, new SceneElementHistoryData( SceneElementKind.Component, - owner.scene.identity.persistentId, - owner.identity.persistentId, - component.identity.persistentId, + owner.scene.identity.persistentID, + owner.identity.persistentID, + component.identity.persistentID, GetElementType(component), beforeIndex, afterIndex, @@ -286,9 +305,9 @@ public GameSystem AddSystem( historyName ?? $"Add {systemType.Name}", new SceneElementHistoryData( SceneElementKind.System, - scene.identity.persistentId, + scene.identity.persistentID, Guid.Empty, - system.identity.persistentId, + system.identity.persistentID, GetTypeRef(systemType), beforeIndex: -1, afterIndex: scene.GetSystemIndex(system), @@ -306,7 +325,9 @@ public GameSystem AddSystem( RollbackAndRethrow(exception, () => { if (!system.isDestroyed && !scene.RemoveSystem(system)) + { throw new InvalidOperationException("The unrecorded system could not be removed."); + } }); throw; } @@ -330,29 +351,35 @@ public bool RemoveSystem( ) { ArgumentNullException.ThrowIfNull(system); if (system.isDestroyed) + { return false; + } GameScene scene = ResolveOwnerScene(system); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (system.isDestroyed) + { return false; + } byte[] state = SceneElementSerialization.CaptureState(system, m_workspace.serialization, m_workspace.assets); SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming(system, scene, m_workspace); int index = scene.GetSystemIndex(system); - Guid systemId = system.identity.persistentId; + Guid systemID = system.identity.persistentID; TypeRef typeRef = GetElementType(system); Type systemType = system.GetType(); try { if (!scene.RemoveSystem(system)) + { return false; + } RecordElement( historyName ?? $"Remove {systemType.Name}", new SceneElementHistoryData( SceneElementKind.System, - scene.identity.persistentId, + scene.identity.persistentID, Guid.Empty, - systemId, + systemID, typeRef, beforeIndex: index, afterIndex: -1, @@ -366,14 +393,22 @@ public bool RemoveSystem( } catch (Exception exception) { - if (m_workspace.Find(systemId) is not null) + if (m_workspace.Find(systemID) is not null) { ExceptionDispatchInfo.Capture(exception).Throw(); } RollbackAndRethrow(exception, () => { - GameSystem restored = SceneElementSerialization.RestoreSystem(scene, typeRef, systemId, index, state, m_workspace.serialization, m_workspace.assets); + GameSystem restored = SceneElementSerialization.RestoreSystem( + scene, + typeRef, + systemID, + index, + state, + m_workspace.serialization, + m_workspace.assets + ); RequireElementRestore(restored, state); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); @@ -413,16 +448,18 @@ public void ResetSystem( } if (before.AsSpan().SequenceEqual(after)) + { return; + } int index = scene.GetSystemIndex(system); RecordWithRollback( () => RecordElement( historyName ?? $"Reset {system.GetType().Name}", new SceneElementHistoryData( SceneElementKind.System, - scene.identity.persistentId, + scene.identity.persistentID, Guid.Empty, - system.identity.persistentId, + system.identity.persistentID, GetElementType(system), index, index, @@ -477,15 +514,17 @@ public void SetSystemIndex( } if (beforeIndex == afterIndex) + { return; + } RecordWithRollback( () => RecordElement( historyName, new SceneElementHistoryData( SceneElementKind.System, - scene.identity.persistentId, + scene.identity.persistentID, Guid.Empty, - system.identity.persistentId, + system.identity.persistentID, GetElementType(system), beforeIndex, afterIndex, @@ -500,11 +539,14 @@ public void SetSystemIndex( ); } - private TypeRef GetElementType(EngineObject element) => element switch + private TypeRef GetElementType(EngineObject element) + => element switch { MissingGameComponent missing => missing.missingType, MissingGameSystem missing => missing.missingType, - _ => GetTypeRef(element.GetType())}; + _ => GetTypeRef(element.GetType()) + }; + private void RequireElementRestore( EngineObject element, ReadOnlySpan data diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs index a0acc8336..dec88e60a 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Moves a loaded scene to a hierarchy index and records the two integer positions. @@ -48,15 +47,17 @@ public void SetSceneIndex( throw; } if (beforeIndex == afterIndex) + { return; - var data = new SceneOrderHistoryData(scene.identity.persistentId, beforeIndex, afterIndex); + } + var data = new SceneOrderHistoryData(scene.identity.persistentID, beforeIndex, afterIndex); RecordWithRollback( () => m_interactions.history.RecordApplied( historyName, - new EditorHistoryChange( - SceneHistoryKinds.Order, - EditorHistoryPayload.FromBytes(data.Encode()))), - () => m_workspace.world.SetSceneIndex(scene, beforeIndex)); + new EditorHistoryChange(SceneHistoryKinds.C_ORDER, EditorHistoryPayload.FromBytes(data.Encode())) + ), + () => m_workspace.world.SetSceneIndex(scene, beforeIndex) + ); } /// @@ -88,12 +89,14 @@ public bool ChangeHierarchy( ArgumentException.ThrowIfNullOrWhiteSpace(historyName); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(gameObject.scene); - GameObject[] affected = (relatedObjects ?? Array.Empty()) + GameObject[] affected = (relatedObjects ?? []) .Prepend(gameObject) - .DistinctBy(static candidate => candidate.identity.persistentId) + .DistinctBy(static candidate => candidate.identity.persistentID) .ToArray(); foreach (GameObject affectedObject in affected) + { m_workspace.EnsureEditable(affectedObject.scene); + } SceneObjectPlacement[] before = CapturePlacements(affected); SceneObjectPlacement[] after; try @@ -107,58 +110,60 @@ public bool ChangeHierarchy( throw; } if (before.SequenceEqual(after)) + { return false; - var data = new SceneHierarchyHistoryData( - before, - after, - gameObject.identity.persistentId); + } + var data = new SceneHierarchyHistoryData(before, after, gameObject.identity.persistentID); RecordWithRollback( - () => Record(historyName, SceneHistoryKinds.Hierarchy, data.Encode()), - () => RestorePlacements(before)); + () => Record(historyName, SceneHistoryKinds.C_HIERARCHY, data.Encode()), + () => RestorePlacements(before) + ); return true; } - private static SceneObjectPlacement[] CapturePlacements(IReadOnlyList gameObjects) - { - var placements = new SceneObjectPlacement[gameObjects.Count]; - for (int i = 0; i < gameObjects.Count; i++) - { - GameObject gameObject = gameObjects[i]; - placements[i] = new SceneObjectPlacement( - gameObject.scene.identity.persistentId, - gameObject.identity.persistentId, - gameObject.transform.parent?.gameObject.identity.persistentId, - gameObject.transform.siblingIndex); - } - return placements; - } - private void RestorePlacements(IReadOnlyList placements) { for (int i = 0; i < placements.Count; i++) { SceneObjectPlacement placement = placements[i]; - GameObject gameObject = m_workspace.Find(placement.objectId) - ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is unavailable."); - GameScene destination = m_workspace.Find(placement.sceneId) - ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is unavailable."); + GameObject gameObject = m_workspace.Find(placement.objectID) + ?? throw new InvalidOperationException($"GameObject '{placement.objectID}' is unavailable."); + GameScene destination = m_workspace.Find(placement.sceneID) + ?? throw new InvalidOperationException($"Scene '{placement.sceneID}' is unavailable."); if (!ReferenceEquals(gameObject.scene, destination)) + { m_workspace.world.MoveGameObjectToScene(gameObject, destination); + } } for (int i = 0; i < placements.Count; i++) { SceneObjectPlacement placement = placements[i]; - GameObject gameObject = m_workspace.Find(placement.objectId)!; - Transform? parent = placement.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + GameObject gameObject = m_workspace.Find(placement.objectID)!; + Transform? parent = placement.parentID is Guid parentID + ? m_workspace.Find(parentID)?.transform + : null; gameObject.transform.SetParent(parent); } foreach (SceneObjectPlacement placement in placements.OrderBy(static value => value.siblingIndex)) { - m_workspace.Find(placement.objectId)! + m_workspace.Find(placement.objectID)! .transform.SetSiblingIndex(placement.siblingIndex); } } + private static SceneObjectPlacement[] CapturePlacements(IReadOnlyList gameObjects) + { + var placements = new SceneObjectPlacement[gameObjects.Count]; + for (int i = 0; i < gameObjects.Count; i++) + { + GameObject gameObject = gameObjects[i]; + placements[i] = new SceneObjectPlacement( + gameObject.scene.identity.persistentID, + gameObject.identity.persistentID, + gameObject.transform.parent?.gameObject.identity.persistentID, + gameObject.transform.siblingIndex + ); + } + return placements; + } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs index 97c064e65..2e3f5d2b7 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { private void RecordDocument( string name, @@ -32,12 +31,12 @@ private void RecordDocument( activeBefore, activeAfter, selectedBefore, - selectedAfter); + selectedAfter + ); m_interactions.history.RecordApplied( name, - new EditorHistoryChange( - SceneHistoryKinds.Document, - EditorHistoryPayload.FromBytes(data.Encode()))); + new EditorHistoryChange(SceneHistoryKinds.C_DOCUMENT, EditorHistoryPayload.FromBytes(data.Encode())) + ); } private void RecordSubtree( @@ -51,17 +50,18 @@ private void RecordSubtree( Guid? selectedAfter ) { var data = new SceneSubtreeHistoryData( - root.scene.identity.persistentId, - root.identity.persistentId, - root.transform.parent?.gameObject.identity.persistentId, + root.scene.identity.persistentID, + root.identity.persistentID, + root.transform.parent?.gameObject.identity.persistentID, root.transform.siblingIndex, existsBefore, existsAfter, subtree, incoming, selectedBefore, - selectedAfter); - Record(name, SceneHistoryKinds.Subtree, data.Encode()); + selectedAfter + ); + Record(name, SceneHistoryKinds.C_SUBTREE, data.Encode()); } private void Record( @@ -69,40 +69,43 @@ private void Record( string kind, byte[] data, string? mergeKey = null - ) - => m_interactions.history.RecordApplied( - name, - new EditorHistoryChange( - kind, - EditorHistoryPayload.FromBytes(data), - mergeKey)); + ) => m_interactions.history.RecordApplied( + name, + new EditorHistoryChange(kind, EditorHistoryPayload.FromBytes(data), mergeKey) + ); private void RecordElement( string name, SceneElementHistoryData data - ) => Record(name, SceneHistoryKinds.Element, data.Encode()); + ) => Record(name, SceneHistoryKinds.C_ELEMENT, data.Encode()); - private Guid? GetActiveSceneId() + private Guid? GetActiveSceneID() => m_workspace.activeScene is { isDestroyed: false } scene - ? scene.identity.persistentId - : null; + ? scene.identity.persistentID + : null; private GameScene ResolveOwnerScene(EngineObject target) => target switch - { - GameScene scene => scene, - GameObject gameObject => gameObject.scene, - GameComponent component => component.gameObject.scene, - GameSystem system => m_workspace.scenes.FirstOrDefault(scene => - scene.GetSystems().Contains(system)) - ?? throw new InvalidOperationException("The system has no loaded scene."), - _ => throw new InvalidOperationException("The object has no loaded scene.") - }; + { + GameScene scene => scene, + GameObject gameObject => gameObject.scene, + GameComponent component => component.gameObject.scene, + GameSystem system => m_workspace.scenes.FirstOrDefault(scene => scene.GetSystems().Contains(system)) + ?? throw new InvalidOperationException("The system has no loaded scene."), + _ => throw new InvalidOperationException("The object has no loaded scene.") + }; - private Guid? GetSelectionId() + private Guid? GetSelectionID() => m_interactions.selection.selectedTarget is EngineObject { isDestroyed: false } target - ? target.identity.persistentId - : null; + ? target.identity.persistentID + : null; + + private TypeRef GetTypeRef(Type type) + => m_workspace.types.TryGetTypeRef(type, out TypeRef typeRef) + ? typeRef + : throw new InvalidOperationException( + $"Scene element type '{type.FullName}' does not have an active StableTypeID." + ); private static void RecordWithRollback( Action record, @@ -131,15 +134,9 @@ Action rollback throw new AggregateException( "An editor mutation could not be recorded and its compensation also failed.", failure, - rollbackException); + rollbackException + ); } ExceptionDispatchInfo.Capture(failure).Throw(); } - - private TypeRef GetTypeRef(Type type) - => m_workspace.types.TryGetTypeRef(type, out TypeRef typeRef) - ? typeRef - : throw new InvalidOperationException( - $"Scene element type '{type.FullName}' does not have an active StableTypeId."); - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs index fc09d6d77..11a0b92ac 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Creates a GameObject, optionally parents it, and records only the new subtree state. @@ -40,18 +39,23 @@ public GameObject CreateGameObject( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The parent belongs to another scene.", nameof(parent)); - Guid? selectedBefore = GetSelectionId(); + } + Guid? selectedBefore = GetSelectionID(); GameObject gameObject = scene.CreateObject(); RecordWithRollback( () => { if (parent is not null) + { gameObject.transform.SetParent(parent); + } byte[] subtree = SceneSubtreeSerialization.Capture( gameObject, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); RecordSubtree( historyName, gameObject, @@ -60,13 +64,17 @@ public GameObject CreateGameObject( subtree, [], selectedBefore, - gameObject.identity.persistentId); + gameObject.identity.persistentID + ); }, () => { if (gameObject.isRuntimeValid && !scene.DestroyObject(gameObject)) + { throw new InvalidOperationException("The unrecorded GameObject could not be removed."); - }); + } + } + ); return gameObject; } @@ -100,23 +108,24 @@ public GameObject InstantiatePrefab( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (!scene.isLoaded) + { throw new InvalidOperationException("A prefab can only be instantiated into a loaded scene."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The parent belongs to another scene.", nameof(parent)); + } - Guid? selectedBefore = GetSelectionId(); - GameObject instance = prefab.Instantiate( - scene, - m_workspace.serialization, - m_workspace.assets, - parent); + Guid? selectedBefore = GetSelectionID(); + GameObject instance = prefab.Instantiate(scene, m_workspace.serialization, m_workspace.assets, parent); RecordWithRollback( () => { byte[] subtree = SceneSubtreeSerialization.Capture( instance, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); RecordSubtree( historyName, instance, @@ -125,13 +134,17 @@ public GameObject InstantiatePrefab( subtree, [], selectedBefore, - instance.identity.persistentId); + instance.identity.persistentID + ); }, () => { if (instance.isRuntimeValid && !scene.DestroyObject(instance)) + { throw new InvalidOperationException("The unrecorded prefab instance could not be removed."); - }); + } + } + ); return instance; } @@ -156,58 +169,58 @@ public bool DeleteGameObject( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(gameObject.scene); if (!gameObject.isRuntimeValid) + { return false; + } GameScene scene = gameObject.scene; - byte[] subtree = SceneSubtreeSerialization.Capture( - gameObject, - m_workspace.serialization, - m_workspace.assets); - SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming( - gameObject, - m_workspace); - Guid? parentId = gameObject.transform.parent?.gameObject.identity.persistentId; + byte[] subtree = SceneSubtreeSerialization.Capture(gameObject, m_workspace.serialization, m_workspace.assets); + SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming(gameObject, m_workspace); + Guid? parentID = gameObject.transform.parent?.gameObject.identity.persistentID; int siblingIndex = gameObject.transform.siblingIndex; - Guid rootId = gameObject.identity.persistentId; - Guid? selectedBefore = GetSelectionId(); + Guid rootID = gameObject.identity.persistentID; + Guid? selectedBefore = GetSelectionID(); try { if (!scene.DestroyObject(gameObject)) + { return false; + } var data = new SceneSubtreeHistoryData( - scene.identity.persistentId, - rootId, - parentId, + scene.identity.persistentID, + rootID, + parentID, siblingIndex, existsBefore: true, existsAfter: false, subtree, incoming, selectedBefore, - selectedAfter: null); - Record(historyName, SceneHistoryKinds.Subtree, data.Encode()); + selectedAfter: null + ); + Record(historyName, SceneHistoryKinds.C_SUBTREE, data.Encode()); } catch (Exception exception) { - if (m_workspace.Find(rootId) is not null) + if (m_workspace.Find(rootID) is not null) { ExceptionDispatchInfo.Capture(exception).Throw(); } RollbackAndRethrow(exception, () => { - Transform? parent = parentId is Guid id - ? m_workspace.Find(id)?.transform - : null; + Transform? parent = parentID is Guid id + ? m_workspace.Find(id)?.transform + : null; _ = SceneSubtreeSerialization.Restore( scene, subtree, m_workspace.serialization, m_workspace.assets, parent, - siblingIndex); + siblingIndex + ); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); } return true; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs index 10a06f34f..24d8811c4 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs @@ -1,19 +1,19 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; +using System.Globalization; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Renames a loaded scene and records the two display strings. @@ -43,7 +43,8 @@ public void RenameScene( name, value => scene.name = value, historyName, - $"scene-name:{scene.identity.persistentId:N}"); + $"scene-name:{scene.identity.persistentID:N}" + ); } /// @@ -74,7 +75,8 @@ public void RenameGameObject( name, value => gameObject.name = value, historyName, - $"game-object-name:{gameObject.identity.persistentId:N}"); + $"game-object-name:{gameObject.identity.persistentID:N}" + ); } /// @@ -106,7 +108,8 @@ public void SetGameObjectActive( after, value => gameObject.SetActive(string.Equals(value, "1", StringComparison.Ordinal)), historyName ?? (active ? "Activate GameObject" : "Deactivate GameObject"), - mergeKey: null); + mergeKey: null + ); } /// @@ -145,7 +148,8 @@ public void SetGameObjectTag( requestedTag, value => gameObject.tag = value, historyName, - $"game-object-tag:{gameObject.identity.persistentId:N}"); + $"game-object-tag:{gameObject.identity.persistentID:N}" + ); } /// @@ -178,12 +182,12 @@ public void SetGameObjectLayer( ChangeScalar( gameObject, SceneScalarKind.GameObjectLayer, - gameObject.layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), - layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), - value => gameObject.layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)), + gameObject.layer.index.ToString(CultureInfo.InvariantCulture), + layer.index.ToString(CultureInfo.InvariantCulture), + value => gameObject.layer = new GameLayer(int.Parse(value, CultureInfo.InvariantCulture)), historyName, - $"game-object-layer:{gameObject.identity.persistentId:N}"); + $"game-object-layer:{gameObject.identity.persistentID:N}" + ); } /// @@ -221,16 +225,15 @@ public bool ChangeProperty( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(ResolveOwnerScene(target)); IReadOnlyList before = OrderPropertySnapshots( - ScenePropertySerialization.CapturePropertySnapshots( - target, - m_workspace.serialization, - m_workspace.assets), - propertyName); + ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets), + propertyName + ); if (!before.Any(snapshot => string.Equals(snapshot.name, propertyName, StringComparison.Ordinal))) { throw new ArgumentException( $"Serializable property '{propertyName}' was not found on '{target.GetType().FullName}'.", - nameof(propertyName)); + nameof(propertyName) + ); } IReadOnlyList after; try @@ -240,8 +243,10 @@ public bool ChangeProperty( ScenePropertySerialization.CapturePropertySnapshots( target, m_workspace.serialization, - m_workspace.assets), - propertyName); + m_workspace.assets + ), + propertyName + ); } catch (Exception exception) { @@ -251,54 +256,58 @@ public bool ChangeProperty( IReadOnlyDictionary afterByName = after.ToDictionary( static snapshot => snapshot.name, - StringComparer.Ordinal); - var deltas = new List(); + StringComparer.Ordinal + ); + List deltas = []; for (int index = 0; index < before.Count; index++) { SerializationPropertySnapshot previous = before[index]; if (!afterByName.TryGetValue(previous.name, out SerializationPropertySnapshot? current)) + { continue; + } if (previous.data.Span.SequenceEqual(current.data.Span)) + { continue; - deltas.Add(new ScenePropertyValueDelta( - previous.name, - m_workspace.serialization.EncodePropertySnapshots([previous]), - m_workspace.serialization.EncodePropertySnapshots([current]))); + } + deltas.Add( + new ScenePropertyValueDelta( + previous.name, + m_workspace.serialization.EncodePropertySnapshots([previous]), + m_workspace.serialization.EncodePropertySnapshots([current]) + ) + ); } if (deltas.Count == 0) + { return false; + } ScenePropertyHistoryData data = ScenePropertyHistoryData.Create( - target.identity.persistentId, + target.identity.persistentID, propertyName, - deltas); + deltas + ); RecordWithRollback( () => m_interactions.history.RecordApplied( historyName, new EditorHistoryChange( - SceneHistoryKinds.Property, + SceneHistoryKinds.C_PROPERTY, EditorHistoryPayload.FromBytes(data.Encode()), - mergeKey)), - () => RestorePropertyDeltas(target, deltas, useAfter: false)); + mergeKey + ) + ), + () => RestorePropertyDeltas(target, deltas, useAfter: false) + ); return true; } - private static IReadOnlyList OrderPropertySnapshots( - IReadOnlyList snapshots, - string primaryPropertyName - ) - => snapshots - .OrderBy(snapshot => string.Equals(snapshot.name, primaryPropertyName, StringComparison.Ordinal) ? 0 : 1) - .ToArray(); - private void RestoreSnapshots( EngineObject target, IReadOnlyList snapshots ) { for (int index = 0; index < snapshots.Count; index++) { - RequirePropertyRestore( - target, - m_workspace.serialization.EncodePropertySnapshots([snapshots[index]])); + RequirePropertyRestore(target, m_workspace.serialization.EncodePropertySnapshots([snapshots[index]])); } } @@ -308,7 +317,9 @@ private void RestorePropertyDeltas( bool useAfter ) { for (int index = 0; index < deltas.Count; index++) + { RequirePropertyRestore(target, useAfter ? deltas[index].after : deltas[index].before); + } } private void ChangeScalar( @@ -321,19 +332,23 @@ private void ChangeScalar( string? mergeKey ) { if (string.Equals(before, after, StringComparison.Ordinal)) + { return; + } RecordWithRollback( () => { setter(after); SceneScalarHistoryData data = SceneScalarHistoryData.Create( - target.identity.persistentId, + target.identity.persistentID, scalarKind, before, - after); - Record(historyName, SceneHistoryKinds.Scalar, data.Encode(), mergeKey); + after + ); + Record(historyName, SceneHistoryKinds.C_SCALAR, data.Encode(), mergeKey); }, - () => setter(before)); + () => setter(before) + ); } private void RequirePropertyRestore( @@ -344,15 +359,26 @@ ReadOnlySpan data target, data, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); if (!result.success || result.ignoredCount != 0 || result.restoredCount == 0) + { throw new InvalidOperationException("Scene property compensation was incomplete."); + } } + private static IReadOnlyList OrderPropertySnapshots( + IReadOnlyList snapshots, + string primaryPropertyName + ) => snapshots + .OrderBy(snapshot => string.Equals(snapshot.name, primaryPropertyName, StringComparison.Ordinal) ? 0 : 1) + .ToArray(); + private static void RequireReferenceRestore(SceneReferenceRestoreResult result) { if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs index 0443166d4..b0ce758f8 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs @@ -6,9 +6,11 @@ using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; +using Inno.Scene.Components; namespace Inno.Editor.Scene; -sealed partial class SceneEdits + +public sealed partial class SceneEdits { /// /// Deletes selected subtrees atomically, omitting descendants already covered by a selected ancestor. @@ -28,14 +30,18 @@ public void DeleteGameObjects(IReadOnlyList targets) ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(target.scene); if (!target.isRuntimeValid) + { throw new InvalidOperationException("A selected GameObject is no longer available."); + } } - var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); + HashSet selected = unique.Select(value => value.identity.persistentID).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Delete GameObjects"); foreach (GameObject target in roots) + { _ = DeleteGameObject(target); + } transaction.Commit(); } @@ -82,18 +88,27 @@ public bool ChangeProperties( ArgumentNullException.ThrowIfNull(mutation); ArgumentException.ThrowIfNullOrWhiteSpace(historyName); if (targets.Count == 0) + { throw new ArgumentException("A property edit requires at least one target.", nameof(targets)); + } foreach (EngineObject target in targets) { ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(ResolveOwnerScene(target)); - if (!ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets).Any(value => value.name == propertyName)) + if (!ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets) + .Any(value => value.name == propertyName) + ) { throw new ArgumentException($"Selected target has no serialized property '{propertyName}'.", nameof(targets)); + } } if (componentName is not null) + { foreach (EngineObject target in targets) + { ValidateComponent(GetSelectionProperty(target, propertyName).propertyType, componentName); + } + } using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction(historyName); bool changed = ChangeProperty(targets[0], propertyName, mutation, historyName, mergeKey); SerializationPropertySnapshot snapshot = ScenePropertySerialization.CapturePropertySnapshots( @@ -108,12 +123,15 @@ public bool ChangeProperties( changed |= ChangeProperty(target, propertyName, () => { if (componentName is null) + { RequirePropertyRestore(target, value); + } else { SerializedProperty property = GetSelectionProperty(target, propertyName); object primary = GetSelectionProperty(targets[0], propertyName).GetValue()!; - object current = property.GetValue() ?? Activator.CreateInstance(Nullable.GetUnderlyingType(property.propertyType) ?? property.propertyType)!; + object current = property.GetValue() + ?? Activator.CreateInstance(Nullable.GetUnderlyingType(property.propertyType) ?? property.propertyType)!; property.SetValue(CopyComponent(primary, current, componentName)); } }, historyName, mergeKey); @@ -153,7 +171,9 @@ string propertyName m_workspace.assets ).Single(value => value.name == propertyName); if (first is not null && !first.data.Span.SequenceEqual(current.data.Span)) + { return false; + } first = current; } @@ -191,38 +211,54 @@ public void MoveGameObjects( ArgumentNullException.ThrowIfNull(destination); m_workspace.EnsureEditable(destination); if (parent is not null && !ReferenceEquals(parent.scene, destination)) + { throw new ArgumentException("The parent must belong to the destination scene.", nameof(parent)); + } GameObject[] unique = targets.Distinct().ToArray(); foreach (GameObject target in unique) { ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(target.scene); if (!target.isRuntimeValid) + { throw new InvalidOperationException("A selected GameObject is no longer available."); + } } - var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); + HashSet selected = unique.Select(value => value.identity.persistentID).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); if (roots.Length == 0) + { return; - for (var ancestor = parent?.transform; ancestor is not null; ancestor = ancestor.parent) - if (selected.Contains(ancestor.gameObject.identity.persistentId)) + } + for (Transform? ancestor = parent?.transform; ancestor is not null; ancestor = ancestor.parent) + { + if (selected.Contains(ancestor.gameObject.identity.persistentID)) + { throw new InvalidOperationException("A selection cannot be moved beneath itself."); + } + } _ = ChangeHierarchy(roots[0], hierarchy => { foreach (GameObject target in roots) { if (!ReferenceEquals(target.scene, destination)) + { hierarchy.MoveToScene(target, destination); + } target.transform.SetParent(parent?.transform); target.transform.SetSiblingIndex(int.MaxValue); } - int available = parent is null ? destination.GetObjects().Count(value => value.transform.parent is null) - roots.Length : parent.transform.children.Count - roots.Length; + int available = parent is null + ? destination.GetObjects().Count(value => value.transform.parent is null) - roots.Length + : parent.transform.children.Count - roots.Length; int start = Math.Clamp(insertionIndex, 0, available); // Place from the end so intermediate sibling shifts cannot reverse the selection. for (int index = roots.Length - 1; index >= 0; index--) + { roots[index].transform.SetSiblingIndex(start); + } }, "Move GameObjects", roots); } @@ -237,10 +273,14 @@ string componentName ) { type = Nullable.GetUnderlyingType(type) ?? type; if (type == typeof(Quaternion) && componentName is "euler.x" or "euler.y" or "euler.z") + { return; + } FieldInfo? field = type.GetField(componentName, BindingFlags.Instance | BindingFlags.Public); if (!type.IsValueType || field is null || field.IsInitOnly || !field.FieldType.IsPrimitive) + { throw new ArgumentException("A batch component must be a writable public scalar value field.", nameof(componentName)); + } } private static object CopyComponent( @@ -254,9 +294,15 @@ string componentName Vector3 value = existing.ToEulerAnglesXYZDegrees(); switch (componentName) { - case "euler.x": value.x = next.x; break; - case "euler.y": value.y = next.y; break; - case "euler.z": value.z = next.z; break; + case "euler.x": + value.x = next.x; + break; + case "euler.y": + value.y = next.y; + break; + case "euler.z": + value.z = next.z; + break; } return Quaternion.FromEulerAnglesXYZDegrees(value).normalized; } @@ -270,9 +316,13 @@ private static bool HasSelectedAncestor( GameObject target, ISet selected ) { - for (var parent = target.transform.parent; parent is not null; parent = parent.parent) - if (selected.Contains(parent.gameObject.identity.persistentId)) + for (Transform? parent = target.transform.parent; parent is not null; parent = parent.parent) + { + if (selected.Contains(parent.gameObject.identity.persistentID)) + { return true; + } + } return false; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs index 058fb3eb8..c1457de5d 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -35,8 +34,10 @@ internal SceneEdits( EditorSceneWorkspace workspace, EditorInteractions interactions ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(workspace); + ArgumentNullException.ThrowIfNull(interactions); + m_workspace = workspace; + m_interactions = interactions; } /// @@ -64,7 +65,9 @@ public bool CanEdit(EngineObject target) { ArgumentNullException.ThrowIfNull(target); if (target.isDestroyed) + { return false; + } try { return m_workspace.CanEdit(ResolveOwnerScene(target)); @@ -88,30 +91,33 @@ public GameScene CreateScene(string historyName = "Create Scene") { ArgumentException.ThrowIfNullOrWhiteSpace(historyName); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); - Guid? activeBefore = GetActiveSceneId(); - Guid? selectedBefore = GetSelectionId(); + Guid? activeBefore = GetActiveSceneID(); + Guid? selectedBefore = GetSelectionID(); GameScene scene = m_workspace.CreateScene(); RecordWithRollback( () => { - EditorSceneWorkspace.SceneDocumentSnapshot snapshot = - m_workspace.CaptureDocumentSnapshot(scene); + EditorSceneWorkspace.SceneDocumentSnapshot snapshot = m_workspace.CaptureDocumentSnapshot(scene); RecordDocument( historyName, existsBefore: false, existsAfter: true, snapshot, activeBefore, - GetActiveSceneId(), + GetActiveSceneID(), selectedBefore, - scene.identity.persistentId); + scene.identity.persistentID + ); }, () => { if (!m_workspace.CloseScene(scene)) + { throw new InvalidOperationException("The unrecorded scene could not be removed."); + } m_workspace.RestoreActiveScene(activeBefore); - }); + } + ); return scene; } @@ -135,10 +141,12 @@ public bool CloseScene( ArgumentException.ThrowIfNullOrWhiteSpace(historyName); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); EditorSceneWorkspace.SceneDocumentSnapshot snapshot = m_workspace.CaptureDocumentSnapshot(scene); - Guid? activeBefore = GetActiveSceneId(); - Guid? selectedBefore = GetSelectionId(); + Guid? activeBefore = GetActiveSceneID(); + Guid? selectedBefore = GetSelectionID(); if (!m_workspace.CloseScene(scene)) + { return false; + } RecordWithRollback( () => RecordDocument( historyName, @@ -146,14 +154,16 @@ public bool CloseScene( existsAfter: false, snapshot, activeBefore, - GetActiveSceneId(), + GetActiveSceneID(), selectedBefore, - GetSelectionId()), + GetSelectionID() + ), () => { _ = m_workspace.RestoreDocumentSnapshot(snapshot); m_workspace.RestoreActiveScene(activeBefore); - }); + } + ); return true; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs index 2a6453dbc..7d18770d8 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs @@ -1,5 +1,4 @@ using System; - using Inno.Scene; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs index 7cb8754dd..9341b6ea6 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs @@ -40,7 +40,9 @@ internal static SceneDocumentHistoryData Decode(ReadOnlySpan bytes) Guid? selectedAfter = ReadGuid(reader); EditorSceneWorkspace.SceneDocumentSnapshot snapshot = ReadSnapshot(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene document history payload contains trailing data."); + } return new SceneDocumentHistoryData( existsBefore, existsAfter, @@ -48,18 +50,19 @@ internal static SceneDocumentHistoryData Decode(ReadOnlySpan bytes) activeBefore, activeAfter, selectedBefore, - selectedAfter); + selectedAfter + ); } private static void WriteSnapshot( BinaryWriter writer, EditorSceneWorkspace.SceneDocumentSnapshot snapshot ) { - writer.Write(snapshot.sceneId.ToByteArray()); + writer.Write(snapshot.sceneID.ToByteArray()); writer.Write(snapshot.payload.Length); writer.Write(snapshot.payload); writer.Write(snapshot.sourcePath); - writer.Write(snapshot.sourceAssetId.ToByteArray()); + writer.Write(snapshot.sourceAssetID.ToByteArray()); writer.Write(snapshot.savedHash.Length); writer.Write(snapshot.savedHash); writer.Write(snapshot.isDirty); @@ -68,21 +71,22 @@ EditorSceneWorkspace.SceneDocumentSnapshot snapshot private static EditorSceneWorkspace.SceneDocumentSnapshot ReadSnapshot(BinaryReader reader) { - Guid sceneId = new(reader.ReadBytes(16)); + var sceneID = new Guid(reader.ReadBytes(16)); byte[] payload = ReadBytes(reader, "scene"); string sourcePath = reader.ReadString(); - Guid sourceAssetId = new(reader.ReadBytes(16)); + var sourceAssetID = new Guid(reader.ReadBytes(16)); byte[] savedHash = ReadBytes(reader, "saved hash"); bool isDirty = reader.ReadBoolean(); int sceneIndex = reader.ReadInt32(); return new EditorSceneWorkspace.SceneDocumentSnapshot( - sceneId, + sceneID, payload, sourcePath, - sourceAssetId, + sourceAssetID, savedHash, isDirty, - sceneIndex); + sceneIndex + ); } private static byte[] ReadBytes( @@ -91,10 +95,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene document history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene document history {name} is truncated."); + } return bytes; } @@ -104,7 +112,9 @@ private static void WriteGuid( ) { writer.Write(value.HasValue); if (value.HasValue) + { writer.Write(value.Value.ToByteArray()); + } } private static Guid? ReadGuid(BinaryReader reader) => reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs index 379e9063c..ee5f411a7 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs @@ -1,12 +1,11 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Document)] +[EditorHistoryHandler(SceneHistoryKinds.C_DOCUMENT)] internal sealed class SceneDocumentHistoryHandler : EditorHistoryHandler { private readonly Logger m_log; @@ -16,7 +15,8 @@ internal SceneDocumentHistoryHandler( EditorSceneWorkspace workspace, LogRouter logs ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -45,27 +45,28 @@ EditorHistoryDirection direction { SceneDocumentHistoryData data = SceneDocumentHistoryData.Decode(change.payload.ReadBytes()); bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; - GameScene? current = m_workspace.Find(data.snapshot.sceneId); + ? data.existsBefore + : data.existsAfter; + GameScene? current = m_workspace.Find(data.snapshot.sceneID); if (shouldExist) { return current is null || current is { isLoaded: true, isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene '{data.snapshot.sceneId}' exists but is not a live loaded scene."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene '{data.snapshot.sceneID}' exists but is not a live loaded scene." + ); } if (current is not { isLoaded: true, isDestroyed: false }) { - return EditorHistoryAvailability.Unavailable( - $"Scene '{data.snapshot.sceneId}' is no longer loaded."); + return EditorHistoryAvailability.Unavailable($"Scene '{data.snapshot.sceneID}' is no longer loaded."); } return EditorHistoryAvailability.Available(); } catch (Exception exception) { return EditorHistoryAvailability.Unavailable( - $"Scene document history payload is invalid: {exception.Message}"); + $"Scene document history payload is invalid: {exception.Message}" + ); } } @@ -100,20 +101,20 @@ EditorHistoryDirection direction } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; Guid? active = direction == EditorHistoryDirection.Undo - ? data.activeBefore - : data.activeAfter; + ? data.activeBefore + : data.activeAfter; Guid? selected = direction == EditorHistoryDirection.Undo - ? data.selectedBefore - : data.selectedAfter; - GameScene? current = m_workspace.Find(data.snapshot.sceneId); + ? data.selectedBefore + : data.selectedAfter; + GameScene? current = m_workspace.Find(data.snapshot.sceneID); bool existed = current is { isLoaded: true, isDestroyed: false }; EditorSceneWorkspace.SceneDocumentSnapshot? original = existed - ? m_workspace.CaptureDocumentSnapshot(current!) - : null; - Guid? originalActive = m_workspace.activeScene?.identity.persistentId; + ? m_workspace.CaptureDocumentSnapshot(current!) + : null; + Guid? originalActive = m_workspace.activeScene?.identity.persistentID; DocumentMutation mutation = DocumentMutation.None; try @@ -128,13 +129,16 @@ EditorHistoryDirection direction else if (current is not { isLoaded: true, isDestroyed: false }) { return EditorHistoryResult.Failure( - $"Scene '{data.snapshot.sceneId}' cannot be restored over an invalid live object."); + $"Scene '{data.snapshot.sceneID}' cannot be restored over an invalid live object." + ); } } else if (current is not null) { if (!m_workspace.CloseDocumentForHistory(current)) - return EditorHistoryResult.Failure($"Scene '{data.snapshot.sceneId}' could not be closed."); + { + return EditorHistoryResult.Failure($"Scene '{data.snapshot.sceneID}' could not be closed."); + } mutation = DocumentMutation.Closed; } @@ -144,14 +148,15 @@ EditorHistoryDirection direction { try { - RollbackDocument(m_workspace, data.snapshot.sceneId, mutation, original); + RollbackDocument(m_workspace, data.snapshot.sceneID, mutation, original); m_workspace.RestoreActiveScene(originalActive); } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene document transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene document transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -169,23 +174,24 @@ EditorHistoryDirection direction private static void RollbackDocument( EditorSceneWorkspace workspace, - Guid sceneId, + Guid sceneID, DocumentMutation mutation, EditorSceneWorkspace.SceneDocumentSnapshot? original ) { if (mutation == DocumentMutation.Restored) { - GameScene? restored = workspace.Find(sceneId); - if (restored is { isLoaded: true, isDestroyed: false } && - !workspace.CloseDocumentForHistory(restored)) - { - throw new InvalidOperationException($"Restored scene '{sceneId}' could not be removed."); + GameScene? restored = workspace.Find(sceneID); + if (restored is { isLoaded: true, isDestroyed: false } + && !workspace.CloseDocumentForHistory(restored) + ) { + throw new InvalidOperationException($"Restored scene '{sceneID}' could not be removed."); } } else if (mutation == DocumentMutation.Closed) { _ = workspace.RestoreDocumentSnapshot( - original ?? throw new InvalidOperationException("The original scene document snapshot is missing.")); + original ?? throw new InvalidOperationException("The original scene document snapshot is missing.") + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs index f04b9e38a..3eb0457af 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs @@ -1,16 +1,15 @@ using System; using System.IO; using System.Text; - using Inno.Extensibility.Types; namespace Inno.Editor.Scene; internal sealed record SceneElementHistoryData( SceneElementKind elementKind, - Guid sceneId, - Guid ownerId, - Guid elementId, + Guid sceneID, + Guid ownerID, + Guid elementID, TypeRef type, int beforeIndex, int afterIndex, @@ -25,10 +24,10 @@ internal byte[] Encode() using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write((byte)elementKind); - writer.Write(sceneId.ToByteArray()); - writer.Write(ownerId.ToByteArray()); - writer.Write(elementId.ToByteArray()); - writer.Write(type.stableId.ToByteArray()); + writer.Write(sceneID.ToByteArray()); + writer.Write(ownerID.ToByteArray()); + writer.Write(elementID.ToByteArray()); + writer.Write(type.stableID.ToByteArray()); writer.Write(beforeIndex); writer.Write(afterIndex); writer.Write(existsBefore); @@ -39,7 +38,7 @@ internal byte[] Encode() for (int i = 0; i < incomingReferences.Length; i++) { SceneIncomingReferenceState reference = incomingReferences[i]; - writer.Write(reference.ownerId.ToByteArray()); + writer.Write(reference.ownerID.ToByteArray()); writer.Write(reference.propertyName); WriteBytes(writer, reference.data); } @@ -51,13 +50,15 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - var elementKind = (SceneElementKind)reader.ReadByte(); + SceneElementKind elementKind = (SceneElementKind)reader.ReadByte(); if (!Enum.IsDefined(elementKind)) + { throw new InvalidDataException($"Unknown scene element history kind '{elementKind}'."); - Guid sceneId = new(reader.ReadBytes(16)); - Guid ownerId = new(reader.ReadBytes(16)); - Guid elementId = new(reader.ReadBytes(16)); - TypeRef type = new(new Guid(reader.ReadBytes(16))); + } + var sceneID = new Guid(reader.ReadBytes(16)); + var ownerID = new Guid(reader.ReadBytes(16)); + var elementID = new Guid(reader.ReadBytes(16)); + var type = new TypeRef(new Guid(reader.ReadBytes(16))); int beforeIndex = reader.ReadInt32(); int afterIndex = reader.ReadInt32(); bool existsBefore = reader.ReadBoolean(); @@ -66,22 +67,27 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) byte[] afterState = ReadBytes(reader, "after state"); int referenceCount = reader.ReadInt32(); if (referenceCount < 0) + { throw new InvalidDataException("Scene element incoming reference count cannot be negative."); + } var references = new SceneIncomingReferenceState[referenceCount]; for (int i = 0; i < references.Length; i++) { references[i] = new SceneIncomingReferenceState( new Guid(reader.ReadBytes(16)), reader.ReadString(), - ReadBytes(reader, "incoming reference")); + ReadBytes(reader, "incoming reference") + ); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene element history payload contains trailing data."); + } return new SceneElementHistoryData( elementKind, - sceneId, - ownerId, - elementId, + sceneID, + ownerID, + elementID, type, beforeIndex, afterIndex, @@ -89,7 +95,8 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) existsAfter, beforeState, afterState, - references); + references + ); } private static void WriteBytes( @@ -106,10 +113,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene element history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene element history {name} is truncated."); + } return bytes; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs index a87871186..e6e253876 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs @@ -1,21 +1,21 @@ using System; using System.Collections.Generic; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Element)] +[EditorHistoryHandler(SceneHistoryKinds.C_ELEMENT)] internal sealed class SceneElementHistoryHandler : EditorHistoryHandler { private readonly EditorSceneWorkspace m_workspace; internal SceneElementHistoryHandler(EditorSceneWorkspace workspace) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; } /// @@ -41,27 +41,30 @@ EditorHistoryDirection direction try { SceneElementHistoryData data = SceneElementHistoryData.Decode(change.payload.ReadBytes()); - GameScene? scene = m_workspace.Find(data.sceneId); + GameScene? scene = m_workspace.Find(data.sceneID); if (scene is not { isLoaded: true, isDestroyed: false }) - return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + { + return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneID}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; - EngineObject? current = m_workspace.Find(data.elementId); + ? data.existsBefore + : data.existsAfter; + EngineObject? current = m_workspace.Find(data.elementID); if (!shouldExist) { return current is { isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene element '{data.elementId}' is no longer available."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene element '{data.elementID}' is no longer available." + ); } if (current is { isDestroyed: false }) { TypeRef typeRef = data.type; bool typeMatches = current switch { - MissingGameComponent missing => missing.missingType.stableId == typeRef.stableId, - MissingGameSystem missing => missing.missingType.stableId == typeRef.stableId, + MissingGameComponent missing => missing.missingType.stableID == typeRef.stableID, + MissingGameSystem missing => missing.missingType.stableID == typeRef.stableID, _ => m_workspace.types.TryResolve(typeRef, out Type? resolvedType) && current.GetType() == resolvedType }; bool kindMatches = data.elementKind switch @@ -71,15 +74,17 @@ EditorHistoryDirection direction _ => false }; return typeMatches && kindMatches - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene element '{data.elementId}' no longer matches stable type '{data.type.stableId}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene element '{data.elementID}' no longer matches stable type '{data.type.stableID}'." + ); } - if (data.elementKind == SceneElementKind.Component && - m_workspace.Find(data.ownerId) is not { isRuntimeValid: true }) - { + if (data.elementKind == SceneElementKind.Component + && m_workspace.Find(data.ownerID) is not { isRuntimeValid: true } + ) { return EditorHistoryAvailability.Unavailable( - $"Component owner '{data.ownerId}' is no longer available."); + $"Component owner '{data.ownerID}' is no longer available." + ); } return EditorHistoryAvailability.Available(); } @@ -112,15 +117,17 @@ EditorHistoryDirection direction try { SceneElementHistoryData data = SceneElementHistoryData.Decode(change.payload.ReadBytes()); - GameScene? scene = m_workspace.Find(data.sceneId); + GameScene? scene = m_workspace.Find(data.sceneID); if (scene is not { isLoaded: true, isDestroyed: false }) - return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + { + return EditorHistoryResult.Failure($"Scene '{data.sceneID}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; int index = direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex; byte[] state = direction == EditorHistoryDirection.Undo ? data.beforeState : data.afterState; - EngineObject? current = m_workspace.Find(data.elementId); + EngineObject? current = m_workspace.Find(data.elementID); if (shouldExist) { bool restored = current is null; @@ -132,36 +139,41 @@ EditorHistoryDirection direction } catch (Exception exception) { - EngineObject? partial = m_workspace.Find(data.elementId); + EngineObject? partial = m_workspace.Find(data.elementID); if (partial is null || partial.isDestroyed) + { return EditorHistoryResult.Failure(exception.Message); + } SceneHistoryCompensationResult cleanup = SceneHistoryCompensation.Remove( partial, () => Remove(data, scene, partial), - $"Partially restored scene element '{data.elementId}'", - m_workspace); + $"Partially restored scene element '{data.elementID}'", + m_workspace + ); return cleanup.statePreserved - ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) - : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); + ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) + : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); } } if (current.isDestroyed) - return EditorHistoryResult.Failure($"Scene element '{data.elementId}' is destroyed."); + { + return EditorHistoryResult.Failure($"Scene element '{data.elementID}' is destroyed."); + } if (restored) { - SceneReferenceRestoreResult referenceResult = - SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); + SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); if (!referenceResult.succeeded) { SceneHistoryCompensationResult cleanup = SceneHistoryCompensation.Remove( current, () => Remove(data, scene, current), - $"Restored scene element '{data.elementId}'", - m_workspace); + $"Restored scene element '{data.elementID}'", + m_workspace + ); string failure = JoinFailures(referenceResult.message, cleanup.message); return referenceResult.statePreserved && cleanup.statePreserved - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure(failure); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure(failure); } } else @@ -169,23 +181,29 @@ EditorHistoryDirection direction byte[] rollbackState = SceneElementSerialization.CaptureState( current, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); int rollbackIndex = GetIndex(data, scene, current); - SceneReferenceRollbackState[] rollbackReferences = - SceneReferenceIndex.CaptureCurrent(data.incomingReferences, m_workspace); + SceneReferenceRollbackState[] rollbackReferences = SceneReferenceIndex.CaptureCurrent( + data.incomingReferences, + m_workspace + ); try { if (state.Length > 0) { SceneElementSerialization.RestoreState( - current, - state, - m_workspace.serialization, - m_workspace.assets); + current, + state, + m_workspace.serialization, + m_workspace.assets + ); } SetIndex(data, scene, current, index); - SceneReferenceRestoreResult referenceResult = - SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); + SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreIncoming( + data.incomingReferences, + m_workspace + ); if (!referenceResult.succeeded) { return RollbackExisting( @@ -195,7 +213,8 @@ EditorHistoryDirection direction rollbackState, rollbackIndex, rollbackReferences, - referenceResult.message); + referenceResult.message + ); } } catch (Exception exception) @@ -207,7 +226,8 @@ EditorHistoryDirection direction rollbackState, rollbackIndex, rollbackReferences, - exception.Message); + exception.Message + ); } } } @@ -216,34 +236,40 @@ EditorHistoryDirection direction byte[] rollbackState = SceneElementSerialization.CaptureState( current, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); int rollbackIndex = GetIndex(data, scene, current); - SceneReferenceRollbackState[] rollbackReferences = - SceneReferenceIndex.CaptureCurrent(data.incomingReferences, m_workspace); + SceneReferenceRollbackState[] rollbackReferences = SceneReferenceIndex.CaptureCurrent(data.incomingReferences, m_workspace); try { if (!Remove(data, scene, current)) - return EditorHistoryResult.Failure($"Scene element '{data.elementId}' could not be removed."); + { + return EditorHistoryResult.Failure($"Scene element '{data.elementID}' could not be removed."); + } } catch (Exception exception) { - EngineObject? remaining = m_workspace.Find(data.elementId); + EngineObject? remaining = m_workspace.Find(data.elementID); if (remaining is { isDestroyed: false }) + { return EditorHistoryResult.Failure(exception.Message); + } try { EngineObject restored = Restore(data, scene, rollbackIndex, rollbackState); - SceneReferenceRestoreResult references = - SceneReferenceIndex.RestoreCurrent(rollbackReferences, m_workspace); + SceneReferenceRestoreResult references = SceneReferenceIndex.RestoreCurrent(rollbackReferences, m_workspace); if (!references.succeeded) + { throw new InvalidOperationException(references.message); + } _ = restored; } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene element removal failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene element removal failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -261,67 +287,29 @@ private EngineObject Restore( GameScene scene, int index, byte[] state - ) - => data.elementKind switch - { - SceneElementKind.Component => SceneElementSerialization.RestoreComponent( - m_workspace.Find(data.ownerId) - ?? throw new InvalidOperationException($"Component owner '{data.ownerId}' is unavailable."), - data.type, - data.elementId, - index, - state, - m_workspace.serialization, - m_workspace.assets), - SceneElementKind.System => SceneElementSerialization.RestoreSystem( - scene, - data.type, - data.elementId, - index, - state, - m_workspace.serialization, - m_workspace.assets), - _ => throw new InvalidOperationException($"Unsupported scene element kind '{data.elementKind}'.") - }; - - private static bool Remove( - SceneElementHistoryData data, - GameScene scene, - EngineObject current - ) - => data.elementKind switch - { - SceneElementKind.Component when current is GameComponent component => - component.gameObject.RemoveComponent(component), - SceneElementKind.System when current is GameSystem system => scene.RemoveSystem(system), - _ => false - }; - - private static void SetIndex( - SceneElementHistoryData data, - GameScene scene, - EngineObject current, - int index - ) { - if (data.elementKind == SceneElementKind.Component && current is GameComponent component) - component.gameObject.SetComponentIndex(component, index); - else if (data.elementKind == SceneElementKind.System && current is GameSystem system) - scene.SetSystemIndex(system, index); - } - - private static int GetIndex( - SceneElementHistoryData data, - GameScene scene, - EngineObject current - ) - => data.elementKind switch - { - SceneElementKind.Component when current is GameComponent component => - component.gameObject.GetComponentIndex(component), - SceneElementKind.System when current is GameSystem system => scene.GetSystemIndex(system), - _ => throw new InvalidOperationException( - $"Scene element '{data.elementId}' does not match history kind '{data.elementKind}'.") - }; + ) => data.elementKind switch + { + SceneElementKind.Component => SceneElementSerialization.RestoreComponent( + m_workspace.Find(data.ownerID) + ?? throw new InvalidOperationException($"Component owner '{data.ownerID}' is unavailable."), + data.type, + data.elementID, + index, + state, + m_workspace.serialization, + m_workspace.assets + ), + SceneElementKind.System => SceneElementSerialization.RestoreSystem( + scene, + data.type, + data.elementID, + index, + state, + m_workspace.serialization, + m_workspace.assets + ), + _ => throw new InvalidOperationException($"Unsupported scene element kind '{data.elementKind}'.") + }; private EditorHistoryResult RollbackExisting( SceneElementHistoryData data, @@ -332,14 +320,15 @@ private EditorHistoryResult RollbackExisting( IReadOnlyList rollbackReferences, string failure ) { - var failures = new System.Collections.Generic.List(); + List failures = []; try { SceneElementSerialization.RestoreState( - current, - rollbackState, - m_workspace.serialization, - m_workspace.assets); + current, + rollbackState, + m_workspace.serialization, + m_workspace.assets + ); } catch (Exception exception) { @@ -355,18 +344,63 @@ string failure } SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreCurrent( rollbackReferences, - m_workspace); + m_workspace + ); if (!referenceResult.succeeded) + { failures.Add($"reference rollback: {referenceResult.message}"); + } return failures.Count == 0 - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure( - $"Scene element transition failed: {failure} Rollback failed: {string.Join("; ", failures)}"); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure( + $"Scene element transition failed: {failure} Rollback failed: {string.Join("; ", failures)}" + ); + } + + private static bool Remove( + SceneElementHistoryData data, + GameScene scene, + EngineObject current + ) => data.elementKind switch + { + SceneElementKind.Component when current is GameComponent component => + component.gameObject.RemoveComponent(component), + SceneElementKind.System when current is GameSystem system => scene.RemoveSystem(system), + _ => false + }; + + private static void SetIndex( + SceneElementHistoryData data, + GameScene scene, + EngineObject current, + int index + ) { + if (data.elementKind == SceneElementKind.Component && current is GameComponent component) + { + component.gameObject.SetComponentIndex(component, index); + } + else if (data.elementKind == SceneElementKind.System && current is GameSystem system) + { + scene.SetSystemIndex(system, index); + } } + private static int GetIndex( + SceneElementHistoryData data, + GameScene scene, + EngineObject current + ) => data.elementKind switch + { + SceneElementKind.Component when current is GameComponent component => + component.gameObject.GetComponentIndex(component), + SceneElementKind.System when current is GameSystem system => scene.GetSystemIndex(system), + _ => throw new InvalidOperationException( + $"Scene element '{data.elementID}' does not match history kind '{data.elementKind}'." + ) + }; + private static string JoinFailures( string failure, string cleanup - ) - => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; + ) => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs index 2fdda5e2d..5fd7e26fa 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs @@ -3,23 +3,16 @@ namespace Inno.Editor.Scene; -internal readonly record struct SceneObjectPlacement( - Guid sceneId, - Guid objectId, - Guid? parentId, - int siblingIndex -); - internal sealed record SceneHierarchyHistoryData( SceneObjectPlacement[] before, SceneObjectPlacement[] after, - Guid selectedId + Guid selectedID ) { internal byte[] Encode() { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); - writer.Write(selectedId.ToByteArray()); + writer.Write(selectedID.ToByteArray()); WritePlacements(writer, before); WritePlacements(writer, after); writer.Flush(); @@ -30,12 +23,14 @@ internal static SceneHierarchyHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream); - Guid selectedId = new(reader.ReadBytes(16)); + var selectedID = new Guid(reader.ReadBytes(16)); SceneObjectPlacement[] before = ReadPlacements(reader); SceneObjectPlacement[] after = ReadPlacements(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene hierarchy history payload contains trailing data."); - return new SceneHierarchyHistoryData(before, after, selectedId); + } + return new SceneHierarchyHistoryData(before, after, selectedID); } private static void WritePlacements( @@ -46,11 +41,13 @@ SceneObjectPlacement[] placements for (int i = 0; i < placements.Length; i++) { SceneObjectPlacement placement = placements[i]; - writer.Write(placement.sceneId.ToByteArray()); - writer.Write(placement.objectId.ToByteArray()); - writer.Write(placement.parentId.HasValue); - if (placement.parentId.HasValue) - writer.Write(placement.parentId.Value.ToByteArray()); + writer.Write(placement.sceneID.ToByteArray()); + writer.Write(placement.objectID.ToByteArray()); + writer.Write(placement.parentID.HasValue); + if (placement.parentID.HasValue) + { + writer.Write(placement.parentID.Value.ToByteArray()); + } writer.Write(placement.siblingIndex); } } @@ -59,15 +56,24 @@ private static SceneObjectPlacement[] ReadPlacements(BinaryReader reader) { int count = reader.ReadInt32(); if (count < 0) + { throw new InvalidDataException("Scene hierarchy placement count cannot be negative."); + } var placements = new SceneObjectPlacement[count]; for (int i = 0; i < placements.Length; i++) { - Guid sceneId = new(reader.ReadBytes(16)); - Guid objectId = new(reader.ReadBytes(16)); - Guid? parentId = reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; - placements[i] = new SceneObjectPlacement(sceneId, objectId, parentId, reader.ReadInt32()); + var sceneID = new Guid(reader.ReadBytes(16)); + var objectID = new Guid(reader.ReadBytes(16)); + Guid? parentID = reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; + placements[i] = new SceneObjectPlacement(sceneID, objectID, parentID, reader.ReadInt32()); } return placements; } } + +internal readonly record struct SceneObjectPlacement( + Guid sceneID, + Guid objectID, + Guid? parentID, + int siblingIndex +); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs index adb0a440d..3b8d195ef 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -9,7 +8,7 @@ namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Hierarchy)] +[EditorHistoryHandler(SceneHistoryKinds.C_HIERARCHY)] internal sealed class SceneHierarchyHistoryHandler : EditorHistoryHandler { private readonly EditorSceneWorkspace m_workspace; @@ -19,7 +18,8 @@ internal SceneHierarchyHistoryHandler( EditorSceneWorkspace workspace, LogRouter logs ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -48,41 +48,44 @@ EditorHistoryDirection direction { SceneHierarchyHistoryData data = SceneHierarchyHistoryData.Decode(change.payload.ReadBytes()); SceneObjectPlacement[] placements = direction == EditorHistoryDirection.Undo - ? data.before - : data.after; + ? data.before + : data.after; IReadOnlyDictionary destinationScenes = placements.ToDictionary( - static placement => placement.objectId, - static placement => placement.sceneId); + static placement => placement.objectID, + static placement => placement.sceneID + ); for (int i = 0; i < placements.Length; i++) { SceneObjectPlacement placement = placements[i]; - if (ResolveScene(placement.sceneId) is null) + if (ResolveScene(placement.sceneID) is null) { - return EditorHistoryAvailability.Unavailable( - $"Scene '{placement.sceneId}' is no longer loaded."); + return EditorHistoryAvailability.Unavailable($"Scene '{placement.sceneID}' is no longer loaded."); } - if (m_workspace.Find(placement.objectId) is not { isRuntimeValid: true }) + if (m_workspace.Find(placement.objectID) is not { isRuntimeValid: true }) { return EditorHistoryAvailability.Unavailable( - $"GameObject '{placement.objectId}' is no longer available."); + $"GameObject '{placement.objectID}' is no longer available." + ); } GameObject? parent = null; - if (placement.parentId is Guid parentId) + if (placement.parentID is Guid parentID) { - parent = m_workspace.Find(parentId); + parent = m_workspace.Find(parentID); if (parent is not { isRuntimeValid: true }) { return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parentId}' is no longer available."); + $"Parent GameObject '{parentID}' is no longer available." + ); } } - if (parent is not null && - parent.scene.identity.persistentId != placement.sceneId && - (!destinationScenes.TryGetValue(parent.identity.persistentId, out Guid parentDestination) || - parentDestination != placement.sceneId)) - { + if (parent is not null + && parent.scene.identity.persistentID != placement.sceneID + && (!destinationScenes.TryGetValue(parent.identity.persistentID, out Guid parentDestination) + || parentDestination != placement.sceneID) + ) { return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parent.identity.persistentId}' does not belong to destination scene '{placement.sceneId}'."); + $"Parent GameObject '{parent.identity.persistentID}' does not belong to destination scene '{placement.sceneID}'." + ); } } return EditorHistoryAvailability.Available(); @@ -117,8 +120,8 @@ EditorHistoryDirection direction { SceneHierarchyHistoryData data = SceneHierarchyHistoryData.Decode(change.payload.ReadBytes()); SceneObjectPlacement[] destination = direction == EditorHistoryDirection.Undo - ? data.before - : data.after; + ? data.before + : data.after; SceneObjectPlacement[] rollback = Capture(destination); try { @@ -133,22 +136,20 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene hierarchy update failed: {exception.Message} " + - $"Placement rollback failed: {rollbackException.Message}"); + $"Scene hierarchy update failed: {exception.Message} " + + $"Placement rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } - GameObject? selected = m_workspace.Find(data.selectedId); + GameObject? selected = m_workspace.Find(data.selectedID); try { _ = context.interactions.For(context.interactions.focusedArea, selected).Select(); } catch (Exception exception) { - m_log.Write( - LogLevel.Error, - "Scene hierarchy selection notification failed: {0}", - [exception]); + m_log.Write(LogLevel.Error, "Scene hierarchy selection notification failed: {0}", [exception]); } return EditorHistoryResult.Success(); } @@ -161,25 +162,28 @@ EditorHistoryDirection direction private SceneObjectPlacement[] Capture(IEnumerable placements) => placements.Select(placement => { - GameObject gameObject = m_workspace.Find(placement.objectId) - ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is no longer available."); + GameObject gameObject = m_workspace.Find(placement.objectID) + ?? throw new InvalidOperationException($"GameObject '{placement.objectID}' is no longer available."); return new SceneObjectPlacement( - gameObject.scene.identity.persistentId, - placement.objectId, - gameObject.transform.parent?.gameObject.identity.persistentId, - gameObject.transform.siblingIndex); + gameObject.scene.identity.persistentID, + placement.objectID, + gameObject.transform.parent?.gameObject.identity.persistentID, + gameObject.transform.siblingIndex + ); }).ToArray(); private void ApplyPlacements(IReadOnlyCollection placements) { foreach (SceneObjectPlacement placement in placements.OrderBy(placement => - GetHierarchyDepth(ResolveObject(placement.objectId).transform))) - { - GameObject gameObject = ResolveObject(placement.objectId); - GameScene destination = ResolveScene(placement.sceneId) - ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is no longer loaded."); + GetHierarchyDepth(ResolveObject(placement.objectID).transform)) + ) { + GameObject gameObject = ResolveObject(placement.objectID); + GameScene destination = ResolveScene(placement.sceneID) + ?? throw new InvalidOperationException($"Scene '{placement.sceneID}' is no longer loaded."); if (!ReferenceEquals(gameObject.scene, destination)) + { m_workspace.world.MoveGameObjectToScene(gameObject, destination); + } } var pending = new List(placements); @@ -189,24 +193,40 @@ private void ApplyPlacements(IReadOnlyCollection placement for (int i = pending.Count - 1; i >= 0; i--) { SceneObjectPlacement placement = pending[i]; - GameObject gameObject = ResolveObject(placement.objectId); - Transform? parent = placement.parentId is Guid parentId - ? ResolveObject(parentId).transform - : null; + GameObject gameObject = ResolveObject(placement.objectID); + Transform? parent = placement.parentID is Guid parentID + ? ResolveObject(parentID).transform + : null; if (parent is not null && IsDescendantOf(parent, gameObject.transform)) + { continue; + } gameObject.transform.SetParent(parent); pending.RemoveAt(i); progressed = true; } if (!progressed) + { throw new InvalidOperationException("Scene hierarchy history would create a parent cycle."); + } } foreach (SceneObjectPlacement placement in placements.OrderBy(static value => value.siblingIndex)) - ResolveObject(placement.objectId).transform.SetSiblingIndex(placement.siblingIndex); + { + ResolveObject(placement.objectID).transform.SetSiblingIndex(placement.siblingIndex); + } } + private GameObject ResolveObject(Guid objectID) + => m_workspace.Find(objectID) is { isRuntimeValid: true } gameObject + ? gameObject + : throw new InvalidOperationException($"GameObject '{objectID}' is no longer available."); + + private GameScene? ResolveScene(Guid sceneID) + => m_workspace.Find(sceneID) is { isLoaded: true, isDestroyed: false } scene + ? scene + : null; + private static bool IsDescendantOf( Transform transform, Transform possibleAncestor @@ -214,7 +234,9 @@ Transform possibleAncestor for (Transform? current = transform; current is not null; current = current.parent) { if (ReferenceEquals(current, possibleAncestor)) + { return true; + } } return false; } @@ -223,17 +245,9 @@ private static int GetHierarchyDepth(Transform transform) { int depth = 0; for (Transform? current = transform.parent; current is not null; current = current.parent) + { depth++; + } return depth; } - - private GameObject ResolveObject(Guid objectId) - => m_workspace.Find(objectId) is { isRuntimeValid: true } gameObject - ? gameObject - : throw new InvalidOperationException($"GameObject '{objectId}' is no longer available."); - - private GameScene? ResolveScene(Guid sceneId) - => m_workspace.Find(sceneId) is { isLoaded: true, isDestroyed: false } scene - ? scene - : null; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs index 346ec8a33..1d70f246e 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Scene; namespace Inno.Editor.Scene; @@ -21,7 +20,7 @@ EditorSceneWorkspace workspace GameObject[] created = scene.GetObjects() .Where(gameObject => !existing.Contains(gameObject)) .ToArray(); - var messages = new List(); + List messages = []; bool statePreserved = true; for (int i = 0; i < created.Length; i++) { @@ -29,11 +28,14 @@ EditorSceneWorkspace workspace SceneHistoryCompensationResult result = Remove( gameObject, () => scene.DestroyObject(gameObject), - $"{description} GameObject '{gameObject.identity.persistentId}'", - workspace); + $"{description} GameObject '{gameObject.identity.persistentID}'", + workspace + ); statePreserved &= result.statePreserved; if (!string.IsNullOrWhiteSpace(result.message)) + { messages.Add(result.message); + } } GameObject[] survivors = scene.GetObjects() @@ -45,8 +47,8 @@ EditorSceneWorkspace workspace messages.Add($"{description} left {survivors.Length} untracked GameObject(s) in the scene."); } return statePreserved - ? SceneHistoryCompensationResult.Preserved(string.Join(" ", messages)) - : SceneHistoryCompensationResult.Lost(string.Join(" ", messages)); + ? SceneHistoryCompensationResult.Preserved(string.Join(" ", messages)) + : SceneHistoryCompensationResult.Lost(string.Join(" ", messages)); } internal static SceneHistoryCompensationResult Remove( @@ -58,7 +60,7 @@ EditorSceneWorkspace workspace ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(remove); ArgumentException.ThrowIfNullOrWhiteSpace(description); - Guid persistentId = target.identity.persistentId; + Guid persistentID = target.identity.persistentID; Exception? failure = null; bool reportedRemoved = false; try @@ -70,27 +72,28 @@ EditorSceneWorkspace workspace failure = exception; } - bool remainsRegistered = ReferenceEquals( - workspace.Find(persistentId), - target); + bool remainsRegistered = ReferenceEquals(workspace.Find(persistentID), target); if (target.isDestroyed && !remainsRegistered) { return SceneHistoryCompensationResult.Preserved( failure is null - ? string.Empty - : $"{description} was removed, but its destruction callback failed: {failure.Message}"); + ? string.Empty + : $"{description} was removed, but its destruction callback failed: {failure.Message}" + ); } if (failure is not null) { return SceneHistoryCompensationResult.Lost( - $"{description} did not reach the destroyed and unregistered postcondition " + - $"after removal threw: {failure.Message}"); + $"{description} did not reach the destroyed and unregistered postcondition " + + $"after removal threw: {failure.Message}" + ); } return SceneHistoryCompensationResult.Lost( reportedRemoved - ? $"{description} reported successful removal but did not reach the destroyed and unregistered postcondition." - : $"{description} could not be fully destroyed and unregistered."); + ? $"{description} reported successful removal but did not reach the destroyed and unregistered postcondition." + : $"{description} could not be fully destroyed and unregistered." + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryKinds.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryKinds.cs index 3efc93a46..a54bb3d01 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryKinds.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryKinds.cs @@ -2,11 +2,11 @@ namespace Inno.Editor.Scene; internal static class SceneHistoryKinds { - internal const string Document = "inno.scene/document"; - internal const string Order = "inno.scene/order"; - internal const string Property = "inno.scene/property"; - internal const string Subtree = "inno.scene/subtree"; - internal const string Hierarchy = "inno.scene/hierarchy"; - internal const string Element = "inno.scene/element"; - internal const string Scalar = "inno.scene/scalar"; + internal const string C_DOCUMENT = "inno.scene/document"; + internal const string C_ORDER = "inno.scene/order"; + internal const string C_PROPERTY = "inno.scene/property"; + internal const string C_SUBTREE = "inno.scene/subtree"; + internal const string C_HIERARCHY = "inno.scene/hierarchy"; + internal const string C_ELEMENT = "inno.scene/element"; + internal const string C_SCALAR = "inno.scene/scalar"; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs index e689e01fe..e158a153e 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs @@ -4,7 +4,7 @@ namespace Inno.Editor.Scene; internal readonly record struct SceneOrderHistoryData( - Guid sceneId, + Guid sceneID, int beforeIndex, int afterIndex ) { @@ -12,7 +12,7 @@ internal byte[] Encode() { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); - writer.Write(sceneId.ToByteArray()); + writer.Write(sceneID.ToByteArray()); writer.Write(beforeIndex); writer.Write(afterIndex); writer.Flush(); @@ -22,10 +22,13 @@ internal byte[] Encode() internal static SceneOrderHistoryData Decode(ReadOnlySpan bytes) { if (bytes.Length != 24) + { throw new InvalidDataException("Scene order history payload must contain exactly 24 bytes."); + } return new SceneOrderHistoryData( new Guid(bytes[..16]), BitConverter.ToInt32(bytes[16..20]), - BitConverter.ToInt32(bytes[20..24])); + BitConverter.ToInt32(bytes[20..24]) + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs index 1833d8af6..8d3b6d57a 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs @@ -1,12 +1,11 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Order)] +[EditorHistoryHandler(SceneHistoryKinds.C_ORDER)] internal sealed class SceneOrderHistoryHandler : EditorHistoryHandler { private readonly EditorSceneWorkspace m_workspace; @@ -16,7 +15,8 @@ internal SceneOrderHistoryHandler( EditorSceneWorkspace workspace, LogRouter logs ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -44,9 +44,9 @@ EditorHistoryDirection direction try { SceneOrderHistoryData data = SceneOrderHistoryData.Decode(change.payload.ReadBytes()); - return m_workspace.Find(data.sceneId) is { isLoaded: true, isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + return m_workspace.Find(data.sceneID) is { isLoaded: true, isDestroyed: false } + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"Scene '{data.sceneID}' is no longer loaded."); } catch (Exception exception) { @@ -77,15 +77,18 @@ EditorHistoryDirection direction try { SceneOrderHistoryData data = SceneOrderHistoryData.Decode(change.payload.ReadBytes()); - GameScene? scene = m_workspace.Find(data.sceneId); + GameScene? scene = m_workspace.Find(data.sceneID); if (scene is not { isLoaded: true, isDestroyed: false }) - return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + { + return EditorHistoryResult.Failure($"Scene '{data.sceneID}' is no longer loaded."); + } int rollbackIndex = m_workspace.world.GetSceneIndex(scene); try { m_workspace.world.SetSceneIndex( scene, - direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex); + direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex + ); } catch (Exception exception) { @@ -96,7 +99,8 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene reorder failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene reorder failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs index 013ffc461..504819c32 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs @@ -6,14 +6,8 @@ namespace Inno.Editor.Scene; -internal sealed record ScenePropertyValueDelta( - string propertyName, - byte[] before, - byte[] after -); - internal sealed record ScenePropertyHistoryData( - Guid targetId, + Guid targetID, string propertyName, ScenePropertyValueDelta[] deltas, long timestamp @@ -22,7 +16,7 @@ internal byte[] Encode() { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(targetId.ToByteArray()); + writer.Write(targetID.ToByteArray()); writer.Write(propertyName); writer.Write(deltas.Length); for (int index = 0; index < deltas.Length; index++) @@ -38,46 +32,51 @@ internal byte[] Encode() } internal static ScenePropertyHistoryData Create( - Guid targetId, + Guid targetID, string propertyName, IReadOnlyList deltas ) { ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); ArgumentNullException.ThrowIfNull(deltas); if (deltas.Count == 0) + { throw new ArgumentException("A scene property history change requires at least one delta.", nameof(deltas)); - return new ScenePropertyHistoryData( - targetId, - propertyName, - [.. deltas], - Stopwatch.GetTimestamp()); + } + return new ScenePropertyHistoryData(targetID, propertyName, [.. deltas], Stopwatch.GetTimestamp()); } internal static ScenePropertyHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid targetId = new(reader.ReadBytes(16)); + var targetID = new Guid(reader.ReadBytes(16)); string propertyName = reader.ReadString(); int count = reader.ReadInt32(); if (count <= 0) + { throw new InvalidDataException("Scene property history delta count must be positive."); + } var deltas = new ScenePropertyValueDelta[count]; var names = new HashSet(StringComparer.Ordinal); for (int index = 0; index < count; index++) { string affectedProperty = reader.ReadString(); if (string.IsNullOrWhiteSpace(affectedProperty) || !names.Add(affectedProperty)) + { throw new InvalidDataException("Scene property history contains an invalid or duplicate property name."); + } deltas[index] = new ScenePropertyValueDelta( affectedProperty, ReadBytes(reader, $"{affectedProperty} before"), - ReadBytes(reader, $"{affectedProperty} after")); + ReadBytes(reader, $"{affectedProperty} after") + ); } long timestamp = reader.ReadInt64(); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene property history payload contains trailing data."); - return new ScenePropertyHistoryData(targetId, propertyName, deltas, timestamp); + } + return new ScenePropertyHistoryData(targetID, propertyName, deltas, timestamp); } private static void WriteBytes( @@ -94,10 +93,20 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene property history {name} value length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene property history {name} value is truncated."); + } return bytes; } } + +internal sealed record ScenePropertyValueDelta( + string propertyName, + byte[] before, + byte[] after +); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs index 9260ea18a..fed8b1ce0 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs @@ -2,14 +2,13 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; - using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Property)] +[EditorHistoryHandler(SceneHistoryKinds.C_PROPERTY)] internal sealed class ScenePropertyHistoryHandler : EditorHistoryHandler { private const double C_MERGE_WINDOW_SECONDS = 1.0; @@ -17,7 +16,8 @@ internal sealed class ScenePropertyHistoryHandler : EditorHistoryHandler internal ScenePropertyHistoryHandler(EditorSceneWorkspace workspace) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; } /// @@ -43,13 +43,16 @@ EditorHistoryDirection direction try { ScenePropertyHistoryData data = ScenePropertyHistoryData.Decode(change.payload.ReadBytes()); - EngineObject? target = m_workspace.Find(data.targetId); + EngineObject? target = m_workspace.Find(data.targetID); if (target is null || target.isDestroyed) - return EditorHistoryAvailability.Unavailable($"Scene object '{data.targetId}' is no longer available."); + { + return EditorHistoryAvailability.Unavailable($"Scene object '{data.targetID}' is no longer available."); + } if (target is not ISerializable serializable) { return EditorHistoryAvailability.Unavailable( - $"Scene object '{data.targetId}' is not serializable in the current generation."); + $"Scene object '{data.targetID}' is not serializable in the current generation." + ); } HashSet currentProperties = ScenePropertySerialization .CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets) @@ -57,10 +60,11 @@ EditorHistoryDirection direction .ToHashSet(StringComparer.Ordinal); bool propertiesExist = data.deltas.All(delta => currentProperties.Contains(delta.propertyName)); return propertiesExist - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"One or more properties affected by '{data.propertyName}' no longer exist on " + - $"scene object '{data.targetId}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"One or more properties affected by '{data.propertyName}' no longer exist on " + + $"scene object '{data.targetID}'." + ); } catch (Exception exception) { @@ -93,9 +97,11 @@ EditorHistoryDirection direction try { data = ScenePropertyHistoryData.Decode(change.payload.ReadBytes()); - target = m_workspace.Find(data.targetId); + target = m_workspace.Find(data.targetID); if (target is null || target.isDestroyed) - return EditorHistoryResult.Failure($"Scene object '{data.targetId}' is no longer available."); + { + return EditorHistoryResult.Failure($"Scene object '{data.targetID}' is no longer available."); + } } catch (Exception exception) { @@ -110,7 +116,8 @@ EditorHistoryDirection direction target, delta.propertyName, m_workspace.serialization, - m_workspace.assets)) + m_workspace.assets + )) .ToArray(); } catch (Exception exception) @@ -128,42 +135,20 @@ EditorHistoryDirection direction try { for (int index = 0; index < rollback.Length; index++) + { RestoreOne(target, rollback[index]); + } } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene property restore failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene property restore failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } } - private static bool IsComplete(SerializationPropertyRestoreResult result) - => result.success && result.ignoredCount == 0 && result.restoredCount > 0; - - private void RestoreDeltas( - EngineObject target, - IReadOnlyList deltas, - bool useAfter - ) { - for (int index = 0; index < deltas.Count; index++) - RestoreOne(target, useAfter ? deltas[index].after : deltas[index].before); - } - - private void RestoreOne( - EngineObject target, - ReadOnlySpan data - ) { - SerializationPropertyRestoreResult result = ScenePropertySerialization.RestoreProperties( - target, - data, - m_workspace.serialization, - m_workspace.assets); - if (!IsComplete(result)) - throw new InvalidOperationException("The scene property restore was incomplete."); - } - /// /// Attempts to merge without changing state when the operation cannot complete. /// @@ -186,23 +171,27 @@ out EditorHistoryChange? merged ) { merged = null; if (!string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal) || older.mergeKey is null) + { return false; + } try { ScenePropertyHistoryData previous = ScenePropertyHistoryData.Decode(older.payload.ReadBytes()); ScenePropertyHistoryData current = ScenePropertyHistoryData.Decode(newer.payload.ReadBytes()); - if (previous.targetId != current.targetId || - !string.Equals(previous.propertyName, current.propertyName, StringComparison.Ordinal) || - Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS) - { + if (previous.targetID != current.targetID + || !string.Equals(previous.propertyName, current.propertyName, StringComparison.Ordinal) + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; } IReadOnlyDictionary previousByName = previous.deltas.ToDictionary( static delta => delta.propertyName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); IReadOnlyDictionary currentByName = current.deltas.ToDictionary( static delta => delta.propertyName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); string[] names = previous.deltas .Select(static delta => delta.propertyName) .Concat(current.deltas.Select(static delta => delta.propertyName)) @@ -212,29 +201,65 @@ out EditorHistoryChange? merged .Select(name => new ScenePropertyValueDelta( name, previousByName.TryGetValue(name, out ScenePropertyValueDelta? previousDelta) - ? previousDelta.before - : currentByName[name].before, + ? previousDelta.before + : currentByName[name].before, currentByName.TryGetValue(name, out ScenePropertyValueDelta? currentDelta) - ? currentDelta.after - : previousByName[name].after)) + ? currentDelta.after + : previousByName[name].after + )) .Where(static delta => !delta.before.AsSpan().SequenceEqual(delta.after)) .ToArray(); if (deltas.Length == 0) + { return false; + } var data = new ScenePropertyHistoryData( - previous.targetId, + previous.targetID, previous.propertyName, deltas, - current.timestamp); + current.timestamp + ); merged = new EditorHistoryChange( - SceneHistoryKinds.Property, + SceneHistoryKinds.C_PROPERTY, EditorHistoryPayload.FromBytes(data.Encode()), - older.mergeKey); + older.mergeKey + ); return true; } - catch + catch (Exception) { + // A payload that cannot be decoded is not merged. The two changes stay separate. return false; } } + + private void RestoreDeltas( + EngineObject target, + IReadOnlyList deltas, + bool useAfter + ) { + for (int index = 0; index < deltas.Count; index++) + { + RestoreOne(target, useAfter ? deltas[index].after : deltas[index].before); + } + } + + private void RestoreOne( + EngineObject target, + ReadOnlySpan data + ) { + SerializationPropertyRestoreResult result = ScenePropertySerialization.RestoreProperties( + target, + data, + m_workspace.serialization, + m_workspace.assets + ); + if (!IsComplete(result)) + { + throw new InvalidOperationException("The scene property restore was incomplete."); + } + } + + private static bool IsComplete(SerializationPropertyRestoreResult result) + => result.success && result.ignoredCount == 0 && result.restoredCount > 0; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs index b3560e23b..3312f0d78 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs @@ -6,7 +6,7 @@ namespace Inno.Editor.Scene; internal sealed record SceneScalarHistoryData( - Guid targetId, + Guid targetID, SceneScalarKind scalarKind, string before, string after, @@ -16,7 +16,7 @@ internal byte[] Encode() { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(targetId.ToByteArray()); + writer.Write(targetID.ToByteArray()); writer.Write((byte)scalarKind); writer.Write(before); writer.Write(after); @@ -26,26 +26,29 @@ internal byte[] Encode() } internal static SceneScalarHistoryData Create( - Guid targetId, + Guid targetID, SceneScalarKind scalarKind, string before, string after - ) - => new(targetId, scalarKind, before, after, Stopwatch.GetTimestamp()); + ) => new(targetID, scalarKind, before, after, Stopwatch.GetTimestamp()); internal static SceneScalarHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid targetId = new(reader.ReadBytes(16)); - var scalarKind = (SceneScalarKind)reader.ReadByte(); + var targetID = new Guid(reader.ReadBytes(16)); + SceneScalarKind scalarKind = (SceneScalarKind)reader.ReadByte(); if (!Enum.IsDefined(scalarKind)) + { throw new InvalidDataException($"Unknown scene scalar history kind '{scalarKind}'."); + } string before = reader.ReadString(); string after = reader.ReadString(); long timestamp = reader.ReadInt64(); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene scalar history payload contains trailing data."); - return new SceneScalarHistoryData(targetId, scalarKind, before, after, timestamp); + } + return new SceneScalarHistoryData(targetID, scalarKind, before, after, timestamp); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs index f6cf76c90..eec509cda 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs @@ -1,13 +1,13 @@ using System; using System.Diagnostics; - +using System.Globalization; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Scene.Layers; namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Scalar)] +[EditorHistoryHandler(SceneHistoryKinds.C_SCALAR)] internal sealed class SceneScalarHistoryHandler : EditorHistoryHandler { private const double C_MERGE_WINDOW_SECONDS = 1.0; @@ -15,7 +15,8 @@ internal sealed class SceneScalarHistoryHandler : EditorHistoryHandler internal SceneScalarHistoryHandler(EditorSceneWorkspace workspace) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; } /// @@ -42,9 +43,10 @@ EditorHistoryDirection direction { SceneScalarHistoryData data = SceneScalarHistoryData.Decode(change.payload.ReadBytes()); return Resolve(data) is not null - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene target '{data.targetId}' is no longer available for '{data.scalarKind}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene target '{data.targetID}' is no longer available for '{data.scalarKind}'." + ); } catch (Exception exception) { @@ -76,7 +78,7 @@ EditorHistoryDirection direction { SceneScalarHistoryData data = SceneScalarHistoryData.Decode(change.payload.ReadBytes()); EngineObject target = Resolve(data) - ?? throw new InvalidOperationException($"Scene target '{data.targetId}' is no longer available."); + ?? throw new InvalidOperationException($"Scene target '{data.targetID}' is no longer available."); string rollback = GetValue(target, data.scalarKind); string value = direction == EditorHistoryDirection.Undo ? data.before : data.after; try @@ -92,7 +94,8 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene scalar update failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene scalar update failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -126,64 +129,67 @@ out EditorHistoryChange? merged ) { merged = null; if (older.mergeKey is null || !string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal)) + { return false; + } try { SceneScalarHistoryData previous = SceneScalarHistoryData.Decode(older.payload.ReadBytes()); SceneScalarHistoryData current = SceneScalarHistoryData.Decode(newer.payload.ReadBytes()); - if (previous.targetId != current.targetId || - previous.scalarKind != current.scalarKind || - Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS) - { + if (previous.targetID != current.targetID + || previous.scalarKind != current.scalarKind + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; } var data = new SceneScalarHistoryData( - previous.targetId, + previous.targetID, previous.scalarKind, previous.before, current.after, - current.timestamp); + current.timestamp + ); merged = new EditorHistoryChange( - SceneHistoryKinds.Scalar, + SceneHistoryKinds.C_SCALAR, EditorHistoryPayload.FromBytes(data.Encode()), - older.mergeKey); + older.mergeKey + ); return true; } - catch + catch (Exception) { + // A payload that cannot be decoded is not merged. The two changes stay separate. return false; } } private EngineObject? Resolve(SceneScalarHistoryData data) => data.scalarKind switch - { - SceneScalarKind.SceneName => m_workspace.Find(data.targetId) is - { isLoaded: true, isDestroyed: false } scene ? scene : null, - SceneScalarKind.GameObjectName or - SceneScalarKind.GameObjectActive or - SceneScalarKind.GameObjectTag or - SceneScalarKind.GameObjectLayer => - m_workspace.Find(data.targetId) is { isRuntimeValid: true } gameObject - ? gameObject - : null, - _ => null - }; + { + SceneScalarKind.SceneName => m_workspace.Find(data.targetID) is + { isLoaded: true, isDestroyed: false } scene ? scene : null, + SceneScalarKind.GameObjectName + or SceneScalarKind.GameObjectActive + or SceneScalarKind.GameObjectTag + or SceneScalarKind.GameObjectLayer => + m_workspace.Find(data.targetID) is { isRuntimeValid: true } gameObject + ? gameObject + : null, + _ => null + }; private static string GetValue( EngineObject target, SceneScalarKind kind - ) - => kind switch - { - SceneScalarKind.SceneName => ((GameScene)target).name, - SceneScalarKind.GameObjectName => ((GameObject)target).name, - SceneScalarKind.GameObjectActive => ((GameObject)target).activeSelf ? "1" : "0", - SceneScalarKind.GameObjectTag => ((GameObject)target).tag, - SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString( - System.Globalization.CultureInfo.InvariantCulture), - _ => throw new InvalidOperationException($"Unsupported scene scalar '{kind}'.") - }; + ) => kind switch + { + SceneScalarKind.SceneName => ((GameScene)target).name, + SceneScalarKind.GameObjectName => ((GameObject)target).name, + SceneScalarKind.GameObjectActive => ((GameObject)target).activeSelf ? "1" : "0", + SceneScalarKind.GameObjectTag => ((GameObject)target).tag, + SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString(CultureInfo.InvariantCulture), + _ => throw new InvalidOperationException($"Unsupported scene scalar '{kind}'.") + }; private static void SetValue( EngineObject target, @@ -205,8 +211,7 @@ string value ((GameObject)target).tag = value; break; case SceneScalarKind.GameObjectLayer: - ((GameObject)target).layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); + ((GameObject)target).layer = new GameLayer(int.Parse(value, CultureInfo.InvariantCulture)); break; default: throw new InvalidOperationException($"Unsupported scene scalar '{kind}'."); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs index a4dd2f862..c273bd558 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs @@ -5,9 +5,9 @@ namespace Inno.Editor.Scene; internal sealed record SceneSubtreeHistoryData( - Guid sceneId, - Guid rootId, - Guid? parentId, + Guid sceneID, + Guid rootID, + Guid? parentID, int siblingIndex, bool existsBefore, bool existsAfter, @@ -20,9 +20,9 @@ internal byte[] Encode() { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(sceneId.ToByteArray()); - writer.Write(rootId.ToByteArray()); - WriteGuid(writer, parentId); + writer.Write(sceneID.ToByteArray()); + writer.Write(rootID.ToByteArray()); + WriteGuid(writer, parentID); writer.Write(siblingIndex); writer.Write(existsBefore); writer.Write(existsAfter); @@ -31,7 +31,7 @@ internal byte[] Encode() for (int i = 0; i < incomingReferences.Length; i++) { SceneIncomingReferenceState reference = incomingReferences[i]; - writer.Write(reference.ownerId.ToByteArray()); + writer.Write(reference.ownerID.ToByteArray()); writer.Write(reference.propertyName); WriteBytes(writer, reference.data); } @@ -45,39 +45,45 @@ internal static SceneSubtreeHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid sceneId = new(reader.ReadBytes(16)); - Guid rootId = new(reader.ReadBytes(16)); - Guid? parentId = ReadGuid(reader); + var sceneID = new Guid(reader.ReadBytes(16)); + var rootID = new Guid(reader.ReadBytes(16)); + Guid? parentID = ReadGuid(reader); int siblingIndex = reader.ReadInt32(); bool existsBefore = reader.ReadBoolean(); bool existsAfter = reader.ReadBoolean(); byte[] subtree = ReadBytes(reader, "subtree"); int referenceCount = reader.ReadInt32(); if (referenceCount < 0) + { throw new InvalidDataException("Scene subtree incoming reference count cannot be negative."); + } var references = new SceneIncomingReferenceState[referenceCount]; for (int i = 0; i < references.Length; i++) { references[i] = new SceneIncomingReferenceState( new Guid(reader.ReadBytes(16)), reader.ReadString(), - ReadBytes(reader, "incoming reference")); + ReadBytes(reader, "incoming reference") + ); } Guid? selectedBefore = ReadGuid(reader); Guid? selectedAfter = ReadGuid(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene subtree history payload contains trailing data."); + } return new SceneSubtreeHistoryData( - sceneId, - rootId, - parentId, + sceneID, + rootID, + parentID, siblingIndex, existsBefore, existsAfter, subtree, references, selectedBefore, - selectedAfter); + selectedAfter + ); } private static void WriteBytes( @@ -94,10 +100,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene subtree history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene subtree history {name} is truncated."); + } return bytes; } @@ -107,7 +117,9 @@ private static void WriteGuid( ) { writer.Write(value.HasValue); if (value.HasValue) + { writer.Write(value.Value.ToByteArray()); + } } private static Guid? ReadGuid(BinaryReader reader) => reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs index 4e717ebcd..cac2ff299 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -8,7 +7,7 @@ namespace Inno.Editor.Scene; -[EditorHistoryHandler(SceneHistoryKinds.Subtree)] +[EditorHistoryHandler(SceneHistoryKinds.C_SUBTREE)] internal sealed class SceneSubtreeHistoryHandler : EditorHistoryHandler { private readonly EditorSceneWorkspace m_workspace; @@ -18,7 +17,8 @@ internal SceneSubtreeHistoryHandler( EditorSceneWorkspace workspace, LogRouter logs ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + ArgumentNullException.ThrowIfNull(workspace); + m_workspace = workspace; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -46,26 +46,29 @@ EditorHistoryDirection direction try { SceneSubtreeHistoryData data = SceneSubtreeHistoryData.Decode(change.payload.ReadBytes()); - GameScene? scene = m_workspace.Find(data.sceneId); + GameScene? scene = m_workspace.Find(data.sceneID); if (scene is not { isLoaded: true, isDestroyed: false }) - return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + { + return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneID}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; - GameObject? current = m_workspace.Find(data.rootId); + ? data.existsBefore + : data.existsAfter; + GameObject? current = m_workspace.Find(data.rootID); if (!shouldExist) { return current is { isRuntimeValid: true } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"GameObject '{data.rootId}' is no longer available."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"GameObject '{data.rootID}' is no longer available."); } if (current is { isRuntimeValid: true }) - return EditorHistoryAvailability.Available(); - if (data.parentId is Guid parentId && - m_workspace.Find(parentId) is not { isRuntimeValid: true }) { - return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parentId}' is no longer available."); + return EditorHistoryAvailability.Available(); + } + if (data.parentID is Guid parentID + && m_workspace.Find(parentID) is not { isRuntimeValid: true } + ) { + return EditorHistoryAvailability.Unavailable($"Parent GameObject '{parentID}' is no longer available."); } return EditorHistoryAvailability.Available(); } @@ -98,24 +101,24 @@ EditorHistoryDirection direction try { SceneSubtreeHistoryData data = SceneSubtreeHistoryData.Decode(change.payload.ReadBytes()); - GameScene? scene = m_workspace.Find(data.sceneId); + GameScene? scene = m_workspace.Find(data.sceneID); if (scene is not { isLoaded: true, isDestroyed: false }) - return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + { + return EditorHistoryResult.Failure($"Scene '{data.sceneID}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; Guid? selected = direction == EditorHistoryDirection.Undo - ? data.selectedBefore - : data.selectedAfter; - GameObject? root = m_workspace.Find(data.rootId); + ? data.selectedBefore + : data.selectedAfter; + GameObject? root = m_workspace.Find(data.rootID); if (shouldExist && root is null) { - var existing = new HashSet( - scene.GetObjects(), - ReferenceEqualityComparer.Instance); - Transform? parent = data.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + var existing = new HashSet(scene.GetObjects(), ReferenceEqualityComparer.Instance); + Transform? parent = data.parentID is Guid parentID + ? m_workspace.Find(parentID)?.transform + : null; try { root = SceneSubtreeSerialization.Restore( @@ -124,33 +127,34 @@ EditorHistoryDirection direction m_workspace.serialization, m_workspace.assets, parent, - data.siblingIndex); + data.siblingIndex + ); } catch (Exception exception) { - SceneHistoryCompensationResult cleanup = - SceneHistoryCompensation.RemoveCreatedObjects( - scene, - existing, - $"Partial scene subtree '{data.rootId}'", - m_workspace); + SceneHistoryCompensationResult cleanup = SceneHistoryCompensation.RemoveCreatedObjects( + scene, + existing, + $"Partial scene subtree '{data.rootID}'", + m_workspace + ); return cleanup.statePreserved - ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) - : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); + ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) + : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); } - SceneReferenceRestoreResult referenceResult = - SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); + SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); if (!referenceResult.succeeded) { SceneHistoryCompensationResult cleanup = SceneHistoryCompensation.Remove( root, () => scene.DestroyObject(root), - $"Restored scene subtree '{data.rootId}'", - m_workspace); + $"Restored scene subtree '{data.rootID}'", + m_workspace + ); string failure = JoinFailures(referenceResult.message, cleanup.message); return referenceResult.statePreserved && cleanup.statePreserved - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure(failure); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure(failure); } } else if (!shouldExist && root is { isRuntimeValid: true }) @@ -158,42 +162,52 @@ EditorHistoryDirection direction try { if (!scene.DestroyObject(root)) - return EditorHistoryResult.Failure($"GameObject '{data.rootId}' could not be removed."); + { + return EditorHistoryResult.Failure($"GameObject '{data.rootID}' could not be removed."); + } } catch (Exception exception) { if (root.isRuntimeValid) + { return EditorHistoryResult.Failure(exception.Message); + } try { - Transform? parent = data.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + Transform? parent = data.parentID is Guid parentID + ? m_workspace.Find(parentID)?.transform + : null; _ = SceneSubtreeSerialization.Restore( scene, data.subtree, m_workspace.serialization, m_workspace.assets, parent, - data.siblingIndex); - SceneReferenceRestoreResult referenceRollback = - SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); + data.siblingIndex + ); + SceneReferenceRestoreResult referenceRollback = SceneReferenceIndex.RestoreIncoming( + data.incomingReferences, + m_workspace + ); if (!referenceRollback.succeeded) + { throw new InvalidOperationException(referenceRollback.message); + } } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene subtree removal failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene subtree removal failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } root = null; } - object? selection = selected is Guid selectionId - ? m_workspace.Find(selectionId) - : null; + object? selection = selected is Guid selectionID + ? m_workspace.Find(selectionID) + : null; try { _ = context.interactions.For(context.interactions.focusedArea, selection).Select(); @@ -213,6 +227,5 @@ EditorHistoryDirection direction private static string JoinFailures( string failure, string cleanup - ) - => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; + ) => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs index 818f9aeb2..9221ebced 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Scene; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Scene", - "Inno.Editor.Scene", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Scene", "Inno.Editor.Scene", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(IEditorSceneWorkspace), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(SceneEdits), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Scene/References/SceneIncomingReferenceState.cs b/src/composition/editor/features/Inno.Editor.Scene/References/SceneIncomingReferenceState.cs index 4f1edaaf8..0a9a5fe9f 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/References/SceneIncomingReferenceState.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/References/SceneIncomingReferenceState.cs @@ -3,7 +3,7 @@ namespace Inno.Editor.Scene; internal sealed record SceneIncomingReferenceState( - Guid ownerId, + Guid ownerID, string propertyName, byte[] data ); diff --git a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs index c56a1b267..1f66b5c65 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Reflection; - using Inno.Core.Serialization; using Inno.Scene; using Inno.Scene.Components; @@ -17,30 +16,36 @@ EditorSceneWorkspace workspace ) { ArgumentNullException.ThrowIfNull(root); ArgumentNullException.ThrowIfNull(workspace); - var subtreeIds = new HashSet(); - CollectSubtreeIds(root, subtreeIds); - var result = new List(); + var subtreeIDs = new HashSet(); + CollectSubtreeIDs(root, subtreeIDs); + List result = []; foreach (EngineObject owner in EnumerateSceneObjects(root.scene)) { - if (subtreeIds.Contains(owner.identity.persistentId) || owner is not ISerializable serializable) + if (subtreeIDs.Contains(owner.identity.persistentID) || owner is not ISerializable serializable) + { continue; + } IReadOnlyList properties = workspace.serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { SerializedProperty property = properties[i]; - if (!property.canRead || - !ContainsReference(property.GetValue(), subtreeIds, new HashSet(ReferenceEqualityComparer.Instance))) - { + if (!property.canRead + || !ContainsReference(property.GetValue(), subtreeIDs, new HashSet(ReferenceEqualityComparer.Instance)) + ) { continue; } - result.Add(new SceneIncomingReferenceState( - owner.identity.persistentId, - property.name, - ScenePropertySerialization.CaptureProperty( - owner, + result.Add( + new SceneIncomingReferenceState( + owner.identity.persistentID, property.name, - workspace.serialization, - workspace.assets))); + ScenePropertySerialization.CaptureProperty( + owner, + property.name, + workspace.serialization, + workspace.assets + ) + ) + ); } } return result.ToArray(); @@ -53,8 +58,8 @@ EditorSceneWorkspace workspace ) { ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(scene); - var targetIds = new HashSet { target.identity.persistentId }; - return CaptureIncoming(scene, targetIds, workspace); + var targetIDs = new HashSet { target.identity.persistentID }; + return CaptureIncoming(scene, targetIDs, workspace); } internal static SceneReferenceRestoreResult RestoreIncoming( @@ -65,13 +70,10 @@ EditorSceneWorkspace workspace for (int i = 0; i < references.Count; i++) { SceneIncomingReferenceState reference = references[i]; - EngineObject? owner = workspace.Find(reference.ownerId); + EngineObject? owner = workspace.Find(reference.ownerID); if (owner is null || owner.isDestroyed) { - return Rollback( - rollback, - $"Incoming reference owner '{reference.ownerId}' is unavailable.", - workspace); + return Rollback(rollback, $"Incoming reference owner '{reference.ownerID}' is unavailable.", workspace); } try { @@ -81,21 +83,24 @@ EditorSceneWorkspace workspace reference.data, workspace.serialization, workspace.assets, - SerializationPropertyRestoreMode.CollectFailures); + SerializationPropertyRestoreMode.CollectFailures + ); if (!IsComplete(result)) { return Rollback( rollback, - $"Incoming property '{reference.propertyName}' on '{reference.ownerId}' was not restored completely.", - workspace); + $"Incoming property '{reference.propertyName}' on '{reference.ownerID}' was not restored completely.", + workspace + ); } } catch (Exception exception) { return Rollback( rollback, - $"Incoming property '{reference.propertyName}' on '{reference.ownerId}' failed: {exception.Message}", - workspace); + $"Incoming property '{reference.propertyName}' on '{reference.ownerID}' failed: {exception.Message}", + workspace + ); } } return SceneReferenceRestoreResult.Success(); @@ -109,9 +114,10 @@ EditorSceneWorkspace workspace for (int i = 0; i < references.Count; i++) { SceneIncomingReferenceState reference = references[i]; - EngineObject owner = workspace.Find(reference.ownerId) - ?? throw new InvalidOperationException( - $"Incoming reference owner '{reference.ownerId}' is unavailable."); + EngineObject owner = workspace.Find(reference.ownerID) + ?? throw new InvalidOperationException( + $"Incoming reference owner '{reference.ownerID}' is unavailable." + ); result[i] = CaptureRollback(owner, reference.propertyName, workspace); } return result; @@ -120,22 +126,21 @@ EditorSceneWorkspace workspace internal static SceneReferenceRestoreResult RestoreCurrent( IReadOnlyList references, EditorSceneWorkspace workspace - ) - => Rollback(references, failure: null, workspace); + ) => Rollback(references, failure: null, workspace); private static SceneReferenceRestoreResult Rollback( IReadOnlyList rollback, string? failure, EditorSceneWorkspace workspace ) { - var rollbackFailures = new List(); + List rollbackFailures = []; for (int i = rollback.Count - 1; i >= 0; i--) { SceneReferenceRollbackState reference = rollback[i]; try { - EngineObject owner = workspace.Find(reference.ownerId) - ?? throw new InvalidOperationException("The rollback owner is unavailable."); + EngineObject owner = workspace.Find(reference.ownerID) + ?? throw new InvalidOperationException("The rollback owner is unavailable."); if (reference.data is not null) { SerializationPropertyRestoreResult result = ScenePropertySerialization.RestoreProperties( @@ -143,9 +148,12 @@ EditorSceneWorkspace workspace reference.data, workspace.serialization, workspace.assets, - SerializationPropertyRestoreMode.Strict); + SerializationPropertyRestoreMode.Strict + ); if (!IsComplete(result)) - rollbackFailures.Add($"'{reference.ownerId}.{reference.propertyName}' was incomplete"); + { + rollbackFailures.Add($"'{reference.ownerID}.{reference.propertyName}' was incomplete"); + } } else { @@ -155,16 +163,17 @@ EditorSceneWorkspace workspace } catch (Exception exception) { - rollbackFailures.Add($"'{reference.ownerId}.{reference.propertyName}': {exception.Message}"); + rollbackFailures.Add($"'{reference.ownerID}.{reference.propertyName}': {exception.Message}"); } } return rollbackFailures.Count == 0 - ? failure is null - ? SceneReferenceRestoreResult.Success() - : SceneReferenceRestoreResult.Failure(failure) - : SceneReferenceRestoreResult.StateIntegrityLost( - $"{failure ?? "Reference compensation failed."} " + - $"Reference rollback failed: {string.Join("; ", rollbackFailures)}"); + ? failure is null + ? SceneReferenceRestoreResult.Success() + : SceneReferenceRestoreResult.Failure(failure) + : SceneReferenceRestoreResult.StateIntegrityLost( + $"{failure ?? "Reference compensation failed."} " + + $"Reference rollback failed: {string.Join("; ", rollbackFailures)}" + ); } private static SceneReferenceRollbackState CaptureRollback( @@ -175,23 +184,26 @@ EditorSceneWorkspace workspace try { return new SceneReferenceRollbackState( - owner.identity.persistentId, + owner.identity.persistentID, propertyName, ScenePropertySerialization.CaptureProperty( owner, propertyName, workspace.serialization, - workspace.assets), - runtimeValue: null); + workspace.assets + ), + runtimeValue: null + ); } catch (InvalidOperationException) { SerializedProperty property = ResolveProperty(owner, propertyName, workspace.serialization); return new SceneReferenceRollbackState( - owner.identity.persistentId, + owner.identity.persistentID, propertyName, data: null, - property.GetValue()); + property.GetValue() + ); } } @@ -201,15 +213,20 @@ private static SerializedProperty ResolveProperty( SerializationRegistry serialization ) { if (owner is not ISerializable serializable) - throw new InvalidOperationException($"Incoming reference owner '{owner.identity.persistentId}' is not serializable."); + { + throw new InvalidOperationException($"Incoming reference owner '{owner.identity.persistentID}' is not serializable."); + } IReadOnlyList properties = serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { if (string.Equals(properties[i].name, propertyName, StringComparison.Ordinal)) + { return properties[i]; + } } throw new InvalidOperationException( - $"Incoming property '{propertyName}' on '{owner.identity.persistentId}' is unavailable."); + $"Incoming property '{propertyName}' on '{owner.identity.persistentID}' is unavailable." + ); } private static bool IsComplete(SerializationPropertyRestoreResult result) @@ -217,24 +234,34 @@ private static bool IsComplete(SerializationPropertyRestoreResult result) private static bool ContainsReference( object? value, - IReadOnlySet targetIds, + IReadOnlySet targetIDs, ISet visited ) { if (value is null) + { return false; + } if (value is EngineObject engineObject) - return !engineObject.isDestroyed && targetIds.Contains(engineObject.identity.persistentId); + { + return !engineObject.isDestroyed && targetIDs.Contains(engineObject.identity.persistentID); + } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum || value is string or Type or Delegate or decimal or DateTime or Guid) + { return false; + } if (!type.IsValueType && !visited.Add(value)) + { return false; + } if (value is IEnumerable enumerable) { foreach (object? item in enumerable) { - if (ContainsReference(item, targetIds, visited)) + if (ContainsReference(item, targetIDs, visited)) + { return true; + } } return false; } @@ -242,7 +269,8 @@ ISet visited for (Type? current = type; current is not null && current != typeof(object); current = current.BaseType) { FieldInfo[] fields = current.GetFields( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly + ); for (int i = 0; i < fields.Length; i++) { object? fieldValue; @@ -250,12 +278,15 @@ ISet visited { fieldValue = fields[i].GetValue(value); } - catch + catch (Exception) { + // A field that cannot be read is skipped. continue; } - if (ContainsReference(fieldValue, targetIds, visited)) + if (ContainsReference(fieldValue, targetIDs, visited)) + { return true; + } } } return false; @@ -263,31 +294,37 @@ ISet visited private static SceneIncomingReferenceState[] CaptureIncoming( GameScene scene, - IReadOnlySet targetIds, + IReadOnlySet targetIDs, EditorSceneWorkspace workspace ) { - var result = new List(); + List result = []; foreach (EngineObject owner in EnumerateSceneObjects(scene)) { - if (targetIds.Contains(owner.identity.persistentId) || owner is not ISerializable serializable) + if (targetIDs.Contains(owner.identity.persistentID) || owner is not ISerializable serializable) + { continue; + } IReadOnlyList properties = workspace.serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { SerializedProperty property = properties[i]; - if (!property.canRead || - !ContainsReference(property.GetValue(), targetIds, new HashSet(ReferenceEqualityComparer.Instance))) - { + if (!property.canRead + || !ContainsReference(property.GetValue(), targetIDs, new HashSet(ReferenceEqualityComparer.Instance)) + ) { continue; } - result.Add(new SceneIncomingReferenceState( - owner.identity.persistentId, - property.name, - ScenePropertySerialization.CaptureProperty( - owner, + result.Add( + new SceneIncomingReferenceState( + owner.identity.persistentID, property.name, - workspace.serialization, - workspace.assets))); + ScenePropertySerialization.CaptureProperty( + owner, + property.name, + workspace.serialization, + workspace.assets + ) + ) + ); } } return result.ToArray(); @@ -301,29 +338,37 @@ private static IEnumerable EnumerateSceneObjects(GameScene scene) yield return gameObjects[i]; IReadOnlyList components = gameObjects[i].GetComponents(); for (int componentIndex = 0; componentIndex < components.Count; componentIndex++) + { yield return components[componentIndex]; + } } IReadOnlyList systems = scene.GetSystems(); for (int i = 0; i < systems.Count; i++) + { yield return systems[i]; + } } - private static void CollectSubtreeIds( + private static void CollectSubtreeIDs( GameObject gameObject, ISet result ) { - _ = result.Add(gameObject.identity.persistentId); + _ = result.Add(gameObject.identity.persistentID); IReadOnlyList components = gameObject.GetComponents(); for (int i = 0; i < components.Count; i++) - _ = result.Add(components[i].identity.persistentId); + { + _ = result.Add(components[i].identity.persistentID); + } IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) - CollectSubtreeIds(children[i].gameObject, result); + { + CollectSubtreeIDs(children[i].gameObject, result); + } } } internal readonly record struct SceneReferenceRollbackState( - Guid ownerId, + Guid ownerID, string propertyName, byte[]? data, object? runtimeValue diff --git a/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs b/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs index cfb6b0e4b..03bb3cee5 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs @@ -1,11 +1,10 @@ -using Inno.Extensibility.Reload; using System; - using Inno.Assets; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Runtime; using Inno.Scene; @@ -55,9 +54,7 @@ public IGenerationChange Capture(AssemblyReloadContext context) ArgumentNullException.ThrowIfNull(context); using IDisposable scope = m_runtimeSession.EnterExecutionScope(); TypeCacheReloadContext typeReload = context.GetContext(); - return new SceneReloadTransaction( - m_runtimeSession, - m_reload.Capture(typeReload)); + return new SceneReloadTransaction(m_runtimeSession, m_reload.Capture(typeReload)); } /// @@ -83,7 +80,9 @@ public void PrepareForActivation() using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.PrepareForActivation(); foreach (object retiredObject in migration.retiredObjects) + { runtimeSession.StopCoroutines(retiredObject); + } } /// @@ -103,8 +102,7 @@ public void Complete() using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.Complete(); SceneStateDiagnosticPublisher.PublishReload(migration.diagnostics); - SceneStateDiagnosticPublisher.PublishMissingElements( - runtimeSession.scenes.loadedScenes); + SceneStateDiagnosticPublisher.PublishMissingElements(runtimeSession.scenes.loadedScenes); } /// @@ -123,8 +121,7 @@ public void RestorePreviousState() { using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.RestorePreviousState(); - SceneStateDiagnosticPublisher.PublishMissingElements( - runtimeSession.scenes.loadedScenes); + SceneStateDiagnosticPublisher.PublishMissingElements(runtimeSession.scenes.loadedScenes); } } @@ -139,7 +136,9 @@ public void Dispose() { IDisposable? current = m_registration; if (current is null) + { return; + } m_registration = null; try { @@ -151,5 +150,4 @@ public void Dispose() } } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs b/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs new file mode 100644 index 000000000..9a4d2c056 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs @@ -0,0 +1,28 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Scripting; + +[EditorAction(ScriptingInteractionIDs.C_RELOAD_PLUGINS, ScriptingInteractionIDs.C_MAIN_MENU_AREA)] +[EditorMenu(ScriptingInteractionIDs.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Plugins", order: 120)] +internal sealed class ReloadPluginsAction(EditorScripting scripting) : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => scripting.ReloadPlugins(); +} diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs b/src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs new file mode 100644 index 000000000..b00723374 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs @@ -0,0 +1,28 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Scripting; + +[EditorAction(ScriptingInteractionIDs.C_RELOAD_SCRIPTING, ScriptingInteractionIDs.C_MAIN_MENU_AREA)] +[EditorMenu(ScriptingInteractionIDs.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Scripts", order: 100)] +internal sealed class ReloadScriptingAction(EditorScripting scripting) : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => scripting.ReloadScripting(); +} diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScriptCompilationProgress.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScriptCompilationProgress.cs index 185e5690e..4c424f049 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScriptCompilationProgress.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScriptCompilationProgress.cs @@ -3,7 +3,7 @@ namespace Inno.Editor.Scripting; /// /// Captures the progress and cancellation policy of one editor script request. /// -/// +/// /// The request identity within the owning script host. /// /// @@ -19,7 +19,7 @@ namespace Inno.Editor.Scripting; /// Whether this exact operation currently admits cancellation. /// public readonly record struct EditorScriptCompilationProgress( - long operationId, + long operationID, float fraction, string status, bool cancellationRequested, diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs index 9d1377c5a..9908fb269 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs @@ -2,15 +2,16 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; using Inno.Core.Logging; using Inno.Core.Settings; using Inno.Editor.Core; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; namespace Inno.Editor.Scripting; + /// /// Owns script compilation and activation for one editor project. /// @@ -36,7 +37,8 @@ internal sealed class EditorScripting : EditorModule, IEditorScriptCompilation private bool m_explicitReloadPending; private bool m_reportedReloadWait; private string? m_activationFailure; - private long m_nextRequestId; + private long m_nextRequestID; + internal EditorScripting( AssetPipeline assets, PluginEnvironment plugins, @@ -47,13 +49,20 @@ internal EditorScripting( LogRouter logs, Func moduleSourceFactory ) { - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); - m_plugins = plugins ?? throw new ArgumentNullException(nameof(plugins)); - m_modules = modules ?? throw new ArgumentNullException(nameof(modules)); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - m_compiler = compiler ?? throw new ArgumentNullException(nameof(compiler)); - m_moduleSourceFactory = moduleSourceFactory ?? throw new ArgumentNullException(nameof(moduleSourceFactory)); - m_reloads = reloads ?? throw new ArgumentNullException(nameof(reloads)); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(plugins); + ArgumentNullException.ThrowIfNull(modules); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(compiler); + ArgumentNullException.ThrowIfNull(reloads); + ArgumentNullException.ThrowIfNull(moduleSourceFactory); + m_assets = assets; + m_plugins = plugins; + m_modules = modules; + m_settings = settings; + m_compiler = compiler; + m_moduleSourceFactory = moduleSourceFactory; + m_reloads = reloads; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); } @@ -62,20 +71,9 @@ Func moduleSourceFactory /// Gets whether blocks following updates is enabled for this implementation. /// public override bool blocksFollowingUpdates => m_blockFollowingUpdates; - /// - /// Gets whether script compilation is currently active. - /// - internal bool isCompiling => m_manager?.isFaulted != true - && (m_showCompilation - || m_compilation is not null - || m_pendingCompletion is not null - || m_manager?.isCompiling == true - || m_manager?.isUnloadVerificationPending == true - || m_manager?.isCompilationPending == true); - internal bool isAvailable => m_manager is not null; + /// public bool requiresExclusiveProgress => isCompiling && m_reloads.CanActivateReload(out _); - internal bool canReload => m_manager is not null && !isCompiling && !m_manager.isFaulted && m_reloads.CanRequestReload(out _); /// /// Gets the current lifecycle state observed by callers. @@ -86,13 +84,21 @@ public EditorScriptCompilationState state { ScriptReloadHost? manager = m_manager; if (manager is null) + { return EditorScriptCompilationState.Initializing; + } if (manager.isFaulted) + { return EditorScriptCompilationState.Failed; + } if (isCompiling) + { return EditorScriptCompilationState.Compiling; + } if (m_activationFailure is not null) + { return EditorScriptCompilationState.Failed; + } return manager.lastCompilation switch { { success: true } => EditorScriptCompilationState.Ready, @@ -111,19 +117,32 @@ public EditorScriptCompilationProgress progress { ScriptReloadProgress? current = m_manager?.progress; string message = m_activationFailure ?? (!m_reloads.CanActivateReload(out string? reason) - ? reason ?? "Waiting for Play Mode to stop." - : current?.stage ?? "Initializing project scripting."); + ? reason ?? "Waiting for Play Mode to stop." + : current?.stage ?? "Initializing project scripting."); if (m_manager?.isCompilationTakingLong == true && m_activationFailure is null) + { message = $"Long-running compilation ({m_manager.compilationElapsed.TotalSeconds:F1}s). {message}"; - return new(current?.operationId ?? 0, current?.fraction ?? 0f, message, - current?.cancellationRequested ?? false, current?.canCancel ?? false); + } + return new( + current?.operationID ?? 0, + current?.fraction ?? 0f, + message, + current?.cancellationRequested ?? false, + current?.canCancel ?? false + ); } } + /// /// Gets the most recently completed compiler result, which may still await activation and retirement verification. /// public ScriptCompilationResult? lastCompilation => m_manager?.lastCompilation; + /// + /// Gets the ticket for the newest accepted compilation, or null when idle; rejected requests do not replace it. + /// + public IScriptCompilationTicket? currentTicket => m_currentTicket; + /// /// Creates a compilation ticket for the newest observable source generation. /// @@ -132,7 +151,7 @@ public EditorScriptCompilationProgress progress /// public IScriptCompilationTicket RequestCompilation() { - var ticket = new ScriptCompilationTicket(++m_nextRequestId, "Script compilation is queued."); + var ticket = new ScriptCompilationTicket(++m_nextRequestID, "Script compilation is queued."); ScriptReloadHost? manager = m_manager; if (!m_reloads.CanRequestReload(out string? reason)) { @@ -155,32 +174,34 @@ public IScriptCompilationTicket RequestCompilation() return ticket; } + /// + /// The observed request identity; stale actions are ignored. + /// + /// + public void CancelCompilation(long operationID) + { + if (m_manager?.progress.operationID == operationID) + { + m_manager.CancelCompilation(operationID); + } + } + /// - /// Gets the ticket for the newest accepted compilation, or null when idle; rejected requests do not replace it. + /// Gets whether script compilation is currently active. /// - public IScriptCompilationTicket? currentTicket => m_currentTicket; + internal bool isCompiling + => m_manager?.isFaulted != true + && (m_showCompilation + || m_compilation is not null + || m_pendingCompletion is not null + || m_manager?.isCompiling == true + || m_manager?.isUnloadVerificationPending == true + || m_manager?.isCompilationPending == true); - internal void ReloadScripting() - { - if (canReload) - QueueReload(static manager => manager.RecompileScripting(), supersedeCurrentTicket: true); - } + internal bool isAvailable => m_manager is not null; - internal void ReloadPlugins() - { - if (canReload) - QueueReload(static manager => manager.ReloadPlugins(), supersedeCurrentTicket: true); - } + internal bool canReload => m_manager is not null && !isCompiling && !m_manager.isFaulted && m_reloads.CanRequestReload(out _); - /// - /// - /// The observed request identity; stale actions are ignored. - /// - public void CancelCompilation(long operationId) - { - if (m_manager?.progress.operationId == operationId) - m_manager.CancelCompilation(operationId); - } /// /// Initializes this feature when its owning runtime becomes active. /// @@ -189,7 +210,16 @@ public void CancelCompilation(long operationId) /// protected override void OnStart(EditorContext context) { - m_manager = new ScriptReloadHost(new ScriptReloadOptions(), m_compiler, m_assets, m_plugins, m_modules, m_settings, m_reloads, m_moduleSourceFactory); + m_manager = new ScriptReloadHost( + new ScriptReloadOptions(), + m_compiler, + m_assets, + m_plugins, + m_modules, + m_settings, + m_reloads, + m_moduleSourceFactory + ); m_manager.Start(); if (m_manager.TryCompilePending(out Task? compilation)) { @@ -234,7 +264,9 @@ protected override void OnUpdate(EditorContext context) m_reportedReloadWait = false; CompleteCompilation(); if (m_manager is null || m_compilation is not null) + { return; + } if (m_pendingCompletion is not null || m_manager.isUnloadVerificationPending) { AdvanceUnloadVerification(); @@ -242,9 +274,13 @@ protected override void OnUpdate(EditorContext context) } if (m_manager.isFaulted) + { return; + } if (!context.isFocused && !m_explicitReloadPending) + { return; + } if (m_manager.TryCompilePending(out Task? compilation)) { m_explicitReloadPending = false; @@ -261,17 +297,39 @@ protected override void OnUpdate(EditorContext context) /// The context that supplies state and services for this operation. /// protected override void OnStop(EditorContext context) => DisposeManager(); + /// /// Releases resources retained by this feature after it has stopped. /// protected override void OnDispose() => DisposeManager(); + + internal void ReloadScripting() + { + if (canReload) + { + QueueReload(static manager => manager.RecompileScripting(), supersedeCurrentTicket: true); + } + } + + internal void ReloadPlugins() + { + if (canReload) + { + QueueReload(static manager => manager.ReloadPlugins(), supersedeCurrentTicket: true); + } + } + private void CompleteCompilation() { Task? compilation = m_compilation; if (compilation is null || !compilation.IsCompleted || m_manager is null) + { return; + } if (!m_reloads.CanActivateReload(out _)) + { return; + } ScriptCompilationTicket? ticket = m_compilationTicket; try { @@ -289,7 +347,9 @@ private void CompleteCompilation() m_activationFailure = null; ScriptDiagnosticPublisher.ClearReload(); - CompleteAfterRetirement(new PendingCompletion(ticket, result, true, "Script generation compiled, activated, and retired successfully.")); + CompleteAfterRetirement( + new PendingCompletion(ticket, result, true, "Script generation compiled, activated, and retired successfully.") + ); } else { @@ -299,7 +359,14 @@ private void CompleteCompilation() m_blockFollowingUpdates = true; m_activationFailure = null; ScriptDiagnosticPublisher.ClearReload(); - CompleteAfterRetirement(new PendingCompletion(ticket, result, false, "Script compilation failed after a Plugin availability change; unavailable types were " + "preserved as Missing.")); + CompleteAfterRetirement( + new PendingCompletion( + ticket, + result, + false, + "Script compilation failed after a Plugin availability change; unavailable types were " + "preserved as Missing." + ) + ); } else { @@ -318,7 +385,9 @@ private void CompleteCompilation() catch (Exception exception) { if (!m_manager.isFaulted) + { m_plugins.RollbackPending(); + } m_activationFailure = $"Script generation activation failed: {exception.Message}"; ticket?.MarkFailed(ticket.result, $"Script generation activation failed: {exception.Message}"); ScriptDiagnosticPublisher.PublishReloadFailure(exception); @@ -328,7 +397,9 @@ private void CompleteCompilation() { m_compilation = null; m_compilationTicket = null; - m_hideCompilationOnNextUpdate = m_pendingCompletion is null && m_manager?.isUnloadVerificationPending != true && m_manager?.isCompilationPending != true; + m_hideCompilationOnNextUpdate = m_pendingCompletion is null + && m_manager?.isUnloadVerificationPending != true + && m_manager?.isCompilationPending != true; } } @@ -346,11 +417,16 @@ private void CompleteAfterRetirement(PendingCompletion completion) private void FinishCompletion(PendingCompletion completion) { if (completion.succeeded) + { m_assets.CompleteExtensionDiscovery(); + } bool projected = GenerateIdeProjection(); if (completion.succeeded) { - completion.ticket?.MarkSucceeded(completion.result, projected ? completion.status : "Script generation retired successfully, but IDE project generation failed."); + completion.ticket?.MarkSucceeded( + completion.result, + projected ? completion.status : "Script generation retired successfully, but IDE project generation failed." + ); } else { @@ -362,7 +438,9 @@ private void AdvanceUnloadVerification() { ScriptReloadHost? manager = m_manager; if (manager is null || !manager.AdvanceUnloadVerification(out Exception? failure)) + { return; + } PendingCompletion? completion = m_pendingCompletion; m_pendingCompletion = null; if (failure is not null) @@ -383,7 +461,9 @@ private void AdvanceUnloadVerification() ScriptDiagnosticPublisher.ClearUnload(); if (completion is not null) + { FinishCompletion(completion); + } m_hideCompilationOnNextUpdate = true; } @@ -410,9 +490,13 @@ bool supersedeCurrentTicket ) { ScriptReloadHost? manager = m_manager; if (manager is null) + { return; + } if (supersedeCurrentTicket) + { m_currentTicket?.MarkSuperseded(); + } request(manager); m_explicitReloadPending = true; m_hideCompilationOnNextUpdate = false; @@ -423,7 +507,9 @@ private void BeginCompilationTicket() { ScriptCompilationTicket? ticket = m_currentTicket; if (ticket is null || ticket.state != ScriptCompilationTicketState.Queued) + { return; + } m_compilationTicket = ticket; ticket.MarkCompiling("Compiling and validating the requested script generation."); } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs index 2318d9c19..8c40fda29 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs @@ -1,28 +1,6 @@ using Inno.Scripting.Compiler; namespace Inno.Editor.Scripting; -/// -/// Identifies whether the active project script generation can safely start game simulation. -/// -public enum EditorScriptCompilationState -{ - /// - /// The script service has not produced its initial active generation. - /// - Initializing, - /// - /// A requested script generation is compiling, activating, or completing unload verification. - /// - Compiling, - /// - /// The most recent compilation succeeded, its generation is active, and retired generations passed GC verification. - /// - Ready, - /// - /// Compilation, activation, or generation retirement failed, so game simulation must not start. - /// - Failed -} /// /// Exposes the minimal script-generation readiness contract required by editor workflows. @@ -39,13 +17,29 @@ public interface IEditorScriptCompilation /// EditorScriptCompilationProgress progress { get; } + /// + /// Gets the most recently requested compilation ticket, or when no explicit request exists. + /// + IScriptCompilationTicket? currentTicket { get; } + + /// + /// Gets the current script-generation readiness state. + /// + EditorScriptCompilationState state { get; } + + /// + /// Gets the most recently completed compilation, or before the first attempt completes. + /// + ScriptCompilationResult? lastCompilation { get; } + /// /// Requests cancellation while retaining ownership until compilation and retirement finish. /// - /// + /// /// The request observed by the presentation; stale requests have no effect. /// - void CancelCompilation(long operationId); + void CancelCompilation(long operationID); + /// /// Queues a fresh cache-aware compilation for a build or simulation workflow. /// @@ -54,19 +48,27 @@ public interface IEditorScriptCompilation /// a faulted host returns a failed ticket and requires restart. /// IScriptCompilationTicket RequestCompilation(); +} + +/// +/// Identifies whether the active project script generation can safely start game simulation. +/// +public enum EditorScriptCompilationState +{ /// - /// Gets the most recently requested compilation ticket, or when no explicit request exists. + /// The script service has not produced its initial active generation. /// - IScriptCompilationTicket? currentTicket { get; } - + Initializing, /// - /// Gets the current script-generation readiness state. + /// A requested script generation is compiling, activating, or completing unload verification. /// - EditorScriptCompilationState state { get; } - - + Compiling, /// - /// Gets the most recently completed compilation, or before the first attempt completes. + /// The most recent compilation succeeded, its generation is active, and retired generations passed GC verification. /// - ScriptCompilationResult? lastCompilation { get; } + Ready, + /// + /// Compilation, activation, or generation retirement failed, so game simulation must not start. + /// + Failed } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IScriptCompilationTicket.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IScriptCompilationTicket.cs index 7f6394afc..08e75e4b5 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IScriptCompilationTicket.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IScriptCompilationTicket.cs @@ -10,7 +10,7 @@ public interface IScriptCompilationTicket /// /// Gets the producer-local monotonic identifier of this request. /// - long requestId { get; } + long requestID { get; } /// /// Gets the current lifecycle state of this exact request. diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs index a933117ff..6365419bd 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs @@ -1,6 +1,5 @@ using System; using System.Threading; - using Inno.Scripting.Compiler; namespace Inno.Editor.Scripting; @@ -12,10 +11,10 @@ internal sealed class ScriptCompilationTicket : IScriptCompilationTicket private int m_state; internal ScriptCompilationTicket( - long requestId, + long requestID, string status ) { - this.requestId = requestId; + this.requestID = requestID; m_status = status; m_state = (int)ScriptCompilationTicketState.Queued; } @@ -23,7 +22,7 @@ string status /// /// Gets the scalar measurement or identity associated with the current state. /// - public long requestId { get; } + public long requestID { get; } /// /// Gets the current lifecycle state observed by callers. @@ -45,23 +44,21 @@ string status /// public bool isCompleted => state is ScriptCompilationTicketState.Succeeded - or ScriptCompilationTicketState.Failed - or ScriptCompilationTicketState.Canceled - or ScriptCompilationTicketState.Superseded; + or ScriptCompilationTicketState.Failed + or ScriptCompilationTicketState.Canceled + or ScriptCompilationTicketState.Superseded; internal void MarkCompiling(string status) => Transition(ScriptCompilationTicketState.Compiling, status, result: null); internal void MarkSucceeded( ScriptCompilationResult result, string status - ) - => Transition(ScriptCompilationTicketState.Succeeded, status, result); + ) => Transition(ScriptCompilationTicketState.Succeeded, status, result); internal void MarkFailed( ScriptCompilationResult? result, string status - ) - => Transition(ScriptCompilationTicketState.Failed, status, result); + ) => Transition(ScriptCompilationTicketState.Failed, status, result); internal void MarkCanceled(string status) => Transition(ScriptCompilationTicketState.Canceled, status, result: null); @@ -69,7 +66,8 @@ internal void MarkSuperseded() => Transition( ScriptCompilationTicketState.Superseded, "A newer script compilation request replaced this ticket.", - result: null); + result: null + ); private void Transition( ScriptCompilationTicketState state, @@ -81,12 +79,14 @@ private void Transition( if (current is ScriptCompilationTicketState.Succeeded or ScriptCompilationTicketState.Failed or ScriptCompilationTicketState.Canceled - or ScriptCompilationTicketState.Superseded) - { + or ScriptCompilationTicketState.Superseded + ) { return; } if (result is not null) + { Volatile.Write(ref m_result, result); + } Volatile.Write(ref m_status, status); Volatile.Write(ref m_state, (int)state); } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs index c2b0fb152..3ef78b15c 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs @@ -9,27 +9,22 @@ public enum ScriptCompilationTicketState /// The request is queued behind the active compiler operation. /// Queued, - /// /// The request owns the compiler pipeline or is activating its candidate generation. /// Compiling, - /// /// The request compiled and atomically activated its candidate generation. /// Succeeded, - /// /// Compilation or candidate activation failed without replacing the active generation. /// Failed, - /// /// The request was explicitly canceled before activation. /// Canceled, - /// /// A newer request replaced this request before its candidate could activate. /// diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs index f043a3d7e..09e6fa1ce 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs @@ -1,6 +1,5 @@ using System; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scripting.Compiler; @@ -16,33 +15,25 @@ internal static class ScriptDiagnosticPublisher internal static void PublishCompilation(ScriptCompilationResult result) { ArgumentNullException.ThrowIfNull(result); - Diagnostics.Set( - C_COMPILER_DIAGNOSTICS, - result.diagnostics.Select(CreateCompilationDiagnostic)); + Diagnostics.Set(C_COMPILER_DIAGNOSTICS, result.diagnostics.Select(CreateCompilationDiagnostic)); } internal static void PublishReloadFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_RELOAD_DIAGNOSTICS, - Diagnostic.Error("INNO-RELOAD", exception.ToString())); + Diagnostics.Set(C_RELOAD_DIAGNOSTICS, Diagnostic.Error("INNO-RELOAD", exception.ToString())); } internal static void PublishIdeProjectionFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_IDE_PROJECTION_DIAGNOSTICS, - Diagnostic.Warning("INNO-IDE-PROJECTION", exception.ToString())); + Diagnostics.Set(C_IDE_PROJECTION_DIAGNOSTICS, Diagnostic.Warning("INNO-IDE-PROJECTION", exception.ToString())); } internal static void PublishUnloadFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_UNLOAD_DIAGNOSTICS, - Diagnostic.Error("INNO-ALC-UNLOAD", exception.Message)); + Diagnostics.Set(C_UNLOAD_DIAGNOSTICS, Diagnostic.Error("INNO-ALC-UNLOAD", exception.Message)); } internal static void ClearReload() => Diagnostics.Clear(C_RELOAD_DIAGNOSTICS); @@ -62,30 +53,14 @@ internal static void ClearAll() private static Diagnostic CreateCompilationDiagnostic(ScriptDiagnostic diagnostic) { DiagnosticLocation? location = string.IsNullOrWhiteSpace(diagnostic.filePath) - ? null - : new DiagnosticLocation( - diagnostic.filePath, - diagnostic.line, - diagnostic.column); + ? null + : new DiagnosticLocation(diagnostic.filePath, diagnostic.line, diagnostic.column); return diagnostic.severity switch { - DiagnosticSeverity.Info => Diagnostic.Info( - diagnostic.id, - diagnostic.message, - location), - DiagnosticSeverity.Warning => Diagnostic.Warning( - diagnostic.id, - diagnostic.message, - location), - DiagnosticSeverity.Error => Diagnostic.Error( - diagnostic.id, - diagnostic.message, - location), - _ => Diagnostic.Error( - diagnostic.id, - diagnostic.message, - location) + DiagnosticSeverity.Info => Diagnostic.Info(diagnostic.id, diagnostic.message, location), + DiagnosticSeverity.Warning => Diagnostic.Warning(diagnostic.id, diagnostic.message, location), + DiagnosticSeverity.Error => Diagnostic.Error(diagnostic.id, diagnostic.message, location), + _ => Diagnostic.Error(diagnostic.id, diagnostic.message, location) }; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIds.cs b/src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIDs.cs similarity index 84% rename from src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIds.cs rename to src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIDs.cs index 3a8d0619b..d4f859741 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIds.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/ScriptingInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Scripting; -internal static class ScriptingInteractionIds +internal static class ScriptingInteractionIDs { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; internal const string C_RELOAD_SCRIPTING = "scripting/reload"; diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs b/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs deleted file mode 100644 index b910234d3..000000000 --- a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Inno.Editor.Interactions; - -namespace Inno.Editor.Scripting; -[EditorAction(ScriptingInteractionIds.C_RELOAD_SCRIPTING, ScriptingInteractionIds.C_MAIN_MENU_AREA)] -[EditorMenu(ScriptingInteractionIds.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Scripts", order: 100)] -internal sealed class ReloadScriptingAction(EditorScripting scripting) : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => scripting.ReloadScripting(); -} - -[EditorAction(ScriptingInteractionIds.C_RELOAD_PLUGINS, ScriptingInteractionIds.C_MAIN_MENU_AREA)] -[EditorMenu(ScriptingInteractionIds.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Plugins", order: 120)] -internal sealed class ReloadPluginsAction(EditorScripting scripting) : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => scripting.ReloadPlugins(); -} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs index 5183619d7..17d62c720 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs @@ -11,5 +11,6 @@ namespace Inno.Editor.Shaders; "New Material", groupOrder: 200, itemOrder: 100, - separatorBeforeGroup: true)] + separatorBeforeGroup: true +)] internal sealed class MaterialAssetCreationTemplate : AssetCreationTemplate; diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs index 6829869d1..d80dfa364 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs @@ -4,18 +4,22 @@ using System.Runtime.CompilerServices; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Serialization; +using Inno.Core.Execution; using Inno.Core.Graphs; +using Inno.Core.Serialization; using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Rendering; using Inno.Rendering.Assets; -using Draft = Inno.Editor.Assets.AssetDraftDocuments.Draft; using Inno.Rendering.Assets.Authoring; +using Inno.Scripting.Api; + +using MaterialDraft = Inno.Editor.Assets.AssetDraftDocuments.Draft; namespace Inno.Editor.Shaders; + /// /// Owns Material authoring sessions; native source editing uses the shared asset draft lifecycle. /// @@ -26,18 +30,7 @@ public sealed class MaterialDocuments : EditorModule private readonly AssetDraftDocuments m_documents; private readonly SerializationRegistry m_serialization; private readonly ConditionalWeakTable m_presentations = new(); - /// - /// Gets the authoritative asset catalog used by source-aware inspectors. - /// - [Inno.Scripting.Api.ScriptingApiIgnore] - public AssetPipeline assets { get; } - internal readonly EditorInteractions interactions; - /// - /// Gets the generation-scoped preview service shared by material presentations. - /// - [Inno.Scripting.Api.ScriptingApiIgnore] - public IEditorPreviewService previews { get; } internal MaterialDocuments( AssetPipeline assets, @@ -52,6 +45,18 @@ IEditorPreviewService previews m_documents = new(assets, serialization, interactions, "inno.material", C_HISTORY, ".imaterial", "Material"); } + /// + /// Gets the authoritative asset catalog used by source-aware inspectors. + /// + [ScriptingApiIgnore] + public AssetPipeline assets { get; } + + /// + /// Gets the generation-scoped preview service shared by material presentations. + /// + [ScriptingApiIgnore] + public IEditorPreviewService previews { get; } + /// /// Opens native source, including a source with failed import, without publishing its draft. /// @@ -62,20 +67,41 @@ IEditorPreviewService previews /// The persistent identity used for subsequent draft operations. /// public Guid Open(AssetPath path) => m_documents.Open(path); + + /// + /// Resolves the source draft for a canonical Material identity. + /// + /// + /// The current canonical Material whose source is edited. + /// + /// + /// The generation-scoped editable source draft. + /// + [ScriptingApiIgnore] + public MaterialDraft Open(MaterialAsset material) + { + if (!assets.TryGetInfo(material.identity.persistentID, out AssetInfo? info) || info is null) + { + throw new IOException("The Material source identity is unavailable."); + } + return OpenDraft(info.assetPath); + } + /// /// Reads a detached current-generation Material; referenced assets remain canonical read-only inputs. /// - /// + /// /// Open Material source identity. /// /// /// The current unsaved Material value. /// - public MaterialAsset Read(Guid assetId) => m_documents.Read(assetId); + public MaterialAsset Read(Guid assetID) => m_documents.Read(assetID); + /// /// Changes a draft through shared History without modifying its source or Scene/Game. /// - /// + /// /// Open Material source identity. /// /// @@ -85,10 +111,11 @@ IEditorPreviewService previews /// The current gesture key, or null for a discrete edit. /// public void Replace( - Guid assetId, + Guid assetID, MaterialAsset candidate, string? mergeKey = null - ) => m_documents.Replace(assetId, candidate, mergeKey); + ) => m_documents.Replace(assetID, candidate, mergeKey); + /// /// Changes compatible selected drafts within one shared gesture. /// @@ -102,6 +129,7 @@ public void ReplaceMany( IReadOnlyDictionary candidates, string? mergeKey = null ) => m_documents.ReplaceMany(candidates, mergeKey); + /// /// Opens the current source draft without publishing it. /// @@ -111,24 +139,8 @@ public void ReplaceMany( /// /// The generation-scoped draft; callers must not retain it across a reload. /// - [Inno.Scripting.Api.ScriptingApiIgnore] - public Draft OpenDraft(AssetPath path) => m_documents.GetDraft(Open(path)); - /// - /// Resolves the source draft for a canonical Material identity. - /// - /// - /// The current canonical Material whose source is edited. - /// - /// - /// The generation-scoped editable source draft. - /// - [Inno.Scripting.Api.ScriptingApiIgnore] - public Draft Open(MaterialAsset material) - { - if (!assets.TryGetInfo(material.identity.persistentId, out AssetInfo? info) || info is null) - throw new IOException("The Material source identity is unavailable."); - return OpenDraft(info.assetPath); - } + [ScriptingApiIgnore] + public MaterialDraft OpenDraft(AssetPath path) => m_documents.GetDraft(Open(path)); /// /// Reads parameter presentation from the current authoring Shader graph. @@ -136,7 +148,7 @@ public Draft Open(MaterialAsset material) /// /// The canonical Shader used by the Material. /// - /// + /// /// The stable binding identity. /// /// @@ -145,18 +157,18 @@ public Draft Open(MaterialAsset material) /// /// Detached presentation values; an unavailable graph uses the ordinary presentation defaults. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public ShaderParameterPresentation Presentation( ShaderAsset shader, - ShaderPropertyId propertyId, + ShaderPropertyID propertyID, out string error ) { - PresentationCache cache = m_presentations.GetValue(shader, static _ => new()); + PresentationCache cache = m_presentations.GetValue(shader, static _ => new PresentationCache()); if (cache.contentVersion != shader.contentVersion) { cache.contentVersion = shader.contentVersion; cache.graph = null; - cache.error = ""; + cache.error = string.Empty; try { cache.graph = ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(shader, assets), m_serialization); @@ -168,24 +180,11 @@ out string error } error = cache.error; - return cache.graph is null ? new() : ShaderParameterPresentation.Read(cache.graph, propertyId, m_serialization, AssetSerializationContext.Create(assets)); + return cache.graph is null + ? new ShaderParameterPresentation() + : ShaderParameterPresentation.Read(cache.graph, propertyID, m_serialization, AssetSerializationContext.Create(assets)); } - internal void ValidateHistory( - EditorHistoryChange change, - EditorHistoryDirection direction - ) => m_documents.ValidateHistory(change, direction); - internal void ApplyHistory( - EditorHistoryChange change, - EditorHistoryDirection direction - ) => m_documents.ApplyHistory(change, direction); - internal bool TryMergeHistory( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) => m_documents.TryMergeHistory(older, newer, out merged); - internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; /// /// Initializes this feature when its owning runtime becomes active. /// @@ -193,6 +192,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnStart(EditorContext context) => m_documents.Start(); + /// /// Advances this feature using the current runtime state. /// @@ -200,6 +200,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnUpdate(EditorContext context) => m_documents.Update(); + /// /// Stops this feature before its owning runtime releases the active generation. /// @@ -212,83 +213,30 @@ protected override void OnStop(EditorContext context) m_documents.Dispose(); } - private sealed class PresentationCache - { - internal long contentVersion = -1; - internal GraphDocument? graph; - internal string error = ""; - } -} - -[EditorHistoryHandler(MaterialDocuments.C_HISTORY)] -internal sealed class MaterialDraftHistory(MaterialDocuments documents) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, + internal void ValidateHistory( EditorHistoryChange change, EditorHistoryDirection direction - ) { - try - { - documents.ValidateHistory(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception error) when (MaterialDocuments.Recoverable(error)) - { - return EditorHistoryAvailability.Unavailable(error.Message); - } - } + ) => m_documents.ValidateHistory(change, direction); - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, + internal void ApplyHistory( EditorHistoryChange change, EditorHistoryDirection direction - ) { - try - { - documents.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception error) when (MaterialDocuments.Recoverable(error)) - { - return EditorHistoryResult.Failure(error.Message); - } - } + ) => m_documents.ApplyHistory(change, direction); - /// - protected override bool TryMerge( + internal bool TryMergeHistory( EditorHistoryChange older, EditorHistoryChange newer, out EditorHistoryChange? merged - ) => documents.TryMergeHistory(older, newer, out merged); + ) => m_documents.TryMergeHistory(older, newer, out merged); + + internal static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && RetirementPendingException.Find(error) is null; + + private sealed class PresentationCache + { + internal long contentVersion = -1; + internal GraphDocument? graph; + internal string error = string.Empty; + } } diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs new file mode 100644 index 000000000..84c94416a --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs @@ -0,0 +1,77 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Shaders; + +[EditorHistoryHandler(MaterialDocuments.C_HISTORY)] +internal sealed class MaterialDraftHistory(MaterialDocuments documents) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.ValidateHistory(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception error) when (MaterialDocuments.Recoverable(error)) + { + return EditorHistoryAvailability.Unavailable(error.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception error) when (MaterialDocuments.Recoverable(error)) + { + return EditorHistoryResult.Failure(error.Message); + } + } + + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) => documents.TryMergeHistory(older, newer, out merged); +} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs index 39fe22fa8..89b9c3d87 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs @@ -16,27 +16,38 @@ public sealed class ShaderParameterPresentation : ISerializable /// /// Gets or sets the Material Inspector section; empty uses the standard Parameters section. /// - [SerializableProperty] public string group { get; set; } = ""; + [SerializableProperty] + public string group { get; set; } = string.Empty; + /// /// Gets or sets the hover description without adding a permanent paragraph. /// - [SerializableProperty] public string description { get; set; } = ""; + [SerializableProperty] + public string description { get; set; } = string.Empty; + /// /// Gets or sets whether this Material-owned parameter appears in ordinary Material Inspectors. /// - [SerializableProperty] public bool visible { get; set; } = true; + [SerializableProperty] + public bool visible { get; set; } = true; + /// /// Gets or sets whether a scalar Float control uses the declared editing bounds. /// - [SerializableProperty] public bool hasRange { get; set; } + [SerializableProperty] + public bool hasRange { get; set; } + /// /// Gets or sets the inclusive editing minimum; existing values are not changed by presentation metadata. /// - [SerializableProperty] public double minimum { get; set; } + [SerializableProperty] + public double minimum { get; set; } + /// /// Gets or sets the inclusive editing maximum. /// - [SerializableProperty] public double maximum { get; set; } = 1; + [SerializableProperty] + public double maximum { get; set; } = 1; /// /// Reads detached presentation for one binding, defaulting only when no presentation was authored. @@ -44,7 +55,7 @@ public sealed class ShaderParameterPresentation : ISerializable /// /// Authoring graph, not a runtime Shader program. /// - /// + /// /// Stable parameter identity shared by all its nodes. /// /// @@ -58,14 +69,17 @@ public sealed class ShaderParameterPresentation : ISerializable /// public static ShaderParameterPresentation Read( GraphDocument graph, - ShaderPropertyId propertyId, + ShaderPropertyID propertyID, SerializationRegistry serialization, SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); - return graph.metadata.TryGetValue(C_PREFIX + propertyId.value, out GraphSerializedValue? encoded) - ? serialization.Deserialize(ShaderGraphDocument.Decode(encoded!, serialization, context), context) - : new(); + return graph.metadata.TryGetValue(C_PREFIX + propertyID.value, out GraphSerializedValue? encoded) + ? serialization.Deserialize( + ShaderGraphDocument.Decode(encoded!, serialization, context), + context + ) + : new ShaderParameterPresentation(); } /// @@ -74,7 +88,7 @@ SerializationContext context /// /// Detached graph owned by the caller's History transaction. /// - /// + /// /// Stable parameter identity. /// /// @@ -91,18 +105,22 @@ SerializationContext context /// public static void Write( GraphDocument graph, - ShaderPropertyId propertyId, + ShaderPropertyID propertyID, ShaderParameterPresentation presentation, SerializationRegistry serialization, SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); ArgumentNullException.ThrowIfNull(presentation); - if (!propertyId.isValid || !double.IsFinite(presentation.minimum) || !double.IsFinite(presentation.maximum) + if (!propertyID.isValid || !double.IsFinite(presentation.minimum) || !double.IsFinite(presentation.maximum) || presentation.minimum < -float.MaxValue || presentation.maximum > float.MaxValue - || presentation.minimum > presentation.maximum) + || presentation.minimum > presentation.maximum + ) { throw new ArgumentException("Parameter presentation requires a stable identity and finite ordered Float bounds."); - graph.SetMetadata(C_PREFIX + propertyId.value, - ShaderGraphDocument.Encode(serialization.Serialize(presentation, context), serialization, context)); + } + graph.SetMetadata( + C_PREFIX + propertyID.value, + ShaderGraphDocument.Encode(serialization.Serialize(presentation, context), serialization, context) + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs b/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs index 03fefb781..2247d899c 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs @@ -10,32 +10,37 @@ namespace Inno.Editor.Shaders; /// public sealed class ShaderInspectionSelection { - private readonly GraphNodeId[] m_nodes; + private readonly GraphNodeID[] m_nodes; + /// /// Creates a neutral Inspector selection separate from the Asset Browser's navigation. /// - /// + /// /// Persistent shader asset identity. /// /// /// Selected stable node identities; empty selects document settings. /// public ShaderInspectionSelection( - Guid assetId, - IEnumerable nodes + Guid assetID, + IEnumerable nodes ) { - if (assetId == Guid.Empty) - throw new ArgumentException("A persistent shader identity is required.", nameof(assetId)); + if (assetID == Guid.Empty) + { + throw new ArgumentException("A persistent shader identity is required.", nameof(assetID)); + } ArgumentNullException.ThrowIfNull(nodes); - this.assetId = assetId; + this.assetID = assetID; m_nodes = nodes.Distinct().OrderBy(static node => node.value, StringComparer.Ordinal).ToArray(); } + /// /// Gets the persistent shader identity. /// - public Guid assetId { get; } + public Guid assetID { get; } + /// /// Gets selected stable node identities. /// - public IReadOnlyList nodes => Array.AsReadOnly(m_nodes); + public IReadOnlyList nodes => Array.AsReadOnly(m_nodes); } diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs new file mode 100644 index 000000000..bb6f35f25 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs @@ -0,0 +1,99 @@ +using System; +using Inno.Core.Diagnostics; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Shaders; + +/// +/// Carries frame-only preview inputs; persistent provider state must retain stable values rather than this object. +/// +public sealed class ShaderPreviewContext +{ + /// + /// Creates a preview invocation from host-owned detached inputs. + /// + /// + /// Isolated material publication and viewport resource identity. + /// + /// + /// Detached values with a current Shader reference; do not modify the reference. + /// + /// + /// Compiled candidate, never published as a canonical Shader. + /// + /// + /// Detached contract captured by the candidate. + /// + /// + /// Preview-local reporter; errors must not contaminate project diagnostics. + /// + /// + /// Positive target width. + /// + /// + /// Positive target height. + /// + public ShaderPreviewContext( + RenderPersistentResourceID resourceID, + MaterialAsset material, + RenderShaderArtifact artifact, + ShaderDefinition definition, + IDiagnosticReporter diagnostics, + int pixelWidth, + int pixelHeight + ) { + if (!resourceID.isValid) + { + throw new ArgumentException("A resource identity is required.", nameof(resourceID)); + } + ArgumentNullException.ThrowIfNull(material); + ArgumentNullException.ThrowIfNull(artifact); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(diagnostics); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + this.resourceID = resourceID; + this.material = material; + this.artifact = artifact; + this.definition = definition; + this.diagnostics = diagnostics; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the publication scope released by the host when this preview closes. + /// + public RenderPersistentResourceID resourceID { get; } + + /// + /// Gets the invocation-local Material values. + /// + public MaterialAsset material { get; } + + /// + /// Gets the complete immutable GPU candidate. + /// + public RenderShaderArtifact artifact { get; } + + /// + /// Gets the candidate's exact contract, not the latest uncompiled source interface. + /// + public ShaderDefinition definition { get; } + + /// + /// Gets the host-owned, isolated diagnostic producer. + /// + public IDiagnosticReporter diagnostics { get; } + + /// + /// Gets target width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets target height in physical pixels. + /// + public int pixelHeight { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs index 816236c42..9aafc3978 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs @@ -1,28 +1,7 @@ -using System; -using Inno.Core.Diagnostics; using Inno.Editor.Rendering; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Editor.Shaders; -/// -/// Associates a reloadable preview implementation with one open Shader contract. -/// -/// -/// Non-empty domain-owned contract identity. -/// -[AttributeUsage(AttributeTargets.Class, Inherited = false)] -public sealed class ShaderPreviewProviderAttribute(string contractId) : Attribute -{ - /// - /// Gets the non-empty Shader contract consumed by this preview. - /// - public string contractId { get; } = string.IsNullOrWhiteSpace(contractId) - ? throw new ArgumentException("A preview contract is required.", nameof(contractId)) : contractId; -} - /// /// Builds domain-owned preview geometry and pass inputs without changing a scene or canonical asset. /// @@ -39,79 +18,3 @@ public abstract class ShaderPreviewProvider /// public abstract EditorViewportLayer CreateLayer(ShaderPreviewContext context); } - -/// -/// Carries frame-only preview inputs; persistent provider state must retain stable values rather than this object. -/// -public sealed class ShaderPreviewContext -{ - /// - /// Creates a preview invocation from host-owned detached inputs. - /// - /// - /// Isolated material publication and viewport resource identity. - /// - /// - /// Detached values with a current Shader reference; do not modify the reference. - /// - /// - /// Compiled candidate, never published as a canonical Shader. - /// - /// - /// Detached contract captured by the candidate. - /// - /// - /// Preview-local reporter; errors must not contaminate project diagnostics. - /// - /// - /// Positive target width. - /// - /// - /// Positive target height. - /// - public ShaderPreviewContext( - RenderPersistentResourceId resourceId, - MaterialAsset material, - RenderShaderArtifact artifact, - ShaderDefinition definition, - IDiagnosticReporter diagnostics, - int pixelWidth, - int pixelHeight - ) { - if (!resourceId.isValid) - throw new ArgumentException("A resource identity is required.", nameof(resourceId)); - ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(artifact); - ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(diagnostics); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.resourceId = resourceId; this.material = material; this.artifact = artifact; this.definition = definition; - this.diagnostics = diagnostics; this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; - } - /// - /// Gets the publication scope released by the host when this preview closes. - /// - public RenderPersistentResourceId resourceId { get; } - /// - /// Gets the invocation-local Material values. - /// - public MaterialAsset material { get; } - /// - /// Gets the complete immutable GPU candidate. - /// - public RenderShaderArtifact artifact { get; } - /// - /// Gets the candidate's exact contract, not the latest uncompiled source interface. - /// - public ShaderDefinition definition { get; } - /// - /// Gets the host-owned, isolated diagnostic producer. - /// - public IDiagnosticReporter diagnostics { get; } - /// - /// Gets target width in physical pixels. - /// - public int pixelWidth { get; } - /// - /// Gets target height in physical pixels. - /// - public int pixelHeight { get; } -} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs new file mode 100644 index 000000000..cfec19d45 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs @@ -0,0 +1,20 @@ +using System; + +namespace Inno.Editor.Shaders; + +/// +/// Associates a reloadable preview implementation with one open Shader contract. +/// +/// +/// Non-empty domain-owned contract identity. +/// +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class ShaderPreviewProviderAttribute(string contractID) : Attribute +{ + /// + /// Gets the non-empty Shader contract consumed by this preview. + /// + public string contractID { get; } = string.IsNullOrWhiteSpace(contractID) + ? throw new ArgumentException("A preview contract is required.", nameof(contractID)) + : contractID; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs index 9b7bf5bf9..d146a2686 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs @@ -1,5 +1,5 @@ +using System; using System.Numerics; - using Inno.Scripting.Api; namespace Inno.Editor.Core; @@ -59,7 +59,7 @@ public abstract class EditorModal [ScriptingApiIgnore] public void Draw(EditorContext context) { - System.ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(context); OnDraw(context); } @@ -87,10 +87,12 @@ public void Draw(EditorContext context) EditorContext context, Vector2 availableContentSize ) { - System.ArgumentNullException.ThrowIfNull(context); - if (!float.IsFinite(availableContentSize.X) || !float.IsFinite(availableContentSize.Y) || - availableContentSize.X <= 0f || availableContentSize.Y <= 0f) - throw new System.ArgumentOutOfRangeException(nameof(availableContentSize)); + ArgumentNullException.ThrowIfNull(context); + if (!float.IsFinite(availableContentSize.X) || !float.IsFinite(availableContentSize.Y) + || availableContentSize.X <= 0f || availableContentSize.Y <= 0f + ) { + throw new ArgumentOutOfRangeException(nameof(availableContentSize)); + } return OnPrepare(context, availableContentSize); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs index b5fc20406..581c6c61c 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs @@ -29,9 +29,13 @@ public EditorModalAttribute( int order = 0 ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor modal identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(title)) + { throw new ArgumentException("An editor modal title is required.", nameof(title)); + } this.id = id; this.title = title; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs index 6d5494b39..d0a59f446 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; using Inno.Scripting.Api; @@ -12,11 +11,11 @@ namespace Inno.Editor.Core; /// public abstract class EditorModule : IDisposable { + private readonly List m_retirementFailures = []; private bool m_started; private bool m_disposed; private bool m_active; private EditorContext? m_context; - private readonly List m_retirementFailures = []; /// /// Gets whether modules ordered after this module must defer their updates for the current frame. @@ -48,7 +47,9 @@ public void Start(EditorContext context) ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { throw new InvalidOperationException($"Editor module '{GetType().FullName}' is already started."); + } m_context = context; m_started = true; OnStart(context); @@ -76,16 +77,15 @@ public void Update(EditorContext context) ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_active) + { throw new InvalidOperationException($"Editor module '{GetType().FullName}' is not started."); + } OnUpdate(context); } /// /// Stops the module before the containing extension generation is released. /// - /// - /// Also compensates a partially failed Start. Completed stops are idempotent; pending stops may be retried. - /// /// /// The shared editor context for the runtime being stopped. /// @@ -98,13 +98,18 @@ public void Update(EditorContext context) /// /// Live work still depends on this module. Its owner must retain it and retry Stop before disposal. /// + /// + /// Also compensates a partially failed Start. Completed stops are idempotent; pending stops may be retried. + /// [ScriptingApiIgnore] public void Stop(EditorContext context) { ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_started) + { return; + } m_active = false; try { @@ -124,15 +129,56 @@ public void Stop(EditorContext context) m_context = null; } + void IDisposable.Dispose() + { + if (m_disposed) + { + return; + } + if (m_context is not null) + { + try + { + Stop(m_context); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception exception) + { + m_retirementFailures.Add(exception); + } + } + try + { + OnDispose(); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception exception) + { + m_retirementFailures.Add(exception); + } + m_disposed = true; + GC.SuppressFinalize(this); + if (m_retirementFailures.Count > 0) + { + var failure = new AggregateException("Editor module retirement failed.", m_retirementFailures); + m_retirementFailures.Clear(); + throw failure; + } + } + /// /// Runs after the module generation becomes active and before its first update. /// /// /// The shared editor context for the active runtime. /// - protected virtual void OnStart(EditorContext context) - { - } + protected virtual void OnStart(EditorContext context) {} /// /// Runs once per editor frame before views are drawn. @@ -140,100 +186,49 @@ protected virtual void OnStart(EditorContext context) /// /// The shared editor context containing the current frame state. /// - protected virtual void OnUpdate(EditorContext context) - { - } + protected virtual void OnUpdate(EditorContext context) {} /// /// Runs before the module generation is released and its disposable instances are destroyed. /// + /// + /// The shared editor context for the runtime being stopped. + /// /// /// This includes partial startup compensation. Pending retirement must throw RetirementPendingException /// and preserve unfinished ownership; completed steps must be idempotent across retries. /// - /// - /// The shared editor context for the runtime being stopped. - /// - protected virtual void OnStop(EditorContext context) - { - } + protected virtual void OnStop(EditorContext context) {} /// /// Captures readable project state owned by this module. /// + /// + /// The writable parameter that receives the complete readable state for this module. + /// /// /// Overriding this method opts the module into project-state IO. Modules that keep the base /// implementation are never registered with the persistence coordinator and therefore perform /// no state reads or writes. /// - /// - /// The writable parameter that receives the complete readable state for this module. - /// - protected virtual void Capture(EditorState state) - { - } + protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this module. /// - /// - /// This method is called only when is overridden. It runs once after the - /// module is started and before the module is allowed to capture replacement state. - /// /// /// The read-only state parameter for this module. Missing or incompatible values return the /// fallback supplied to . /// - protected virtual void Restore(EditorState state) - { - } + /// + /// This method is called only when is overridden. It runs once after the + /// module is started and before the module is allowed to capture replacement state. + /// + protected virtual void Restore(EditorState state) {} /// /// Releases resources owned by this module after it has stopped and left the active extension /// generation. /// - protected virtual void OnDispose() - { - } - - void IDisposable.Dispose() - { - if (m_disposed) - return; - if (m_context is not null) - { - try - { - Stop(m_context); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception exception) - { - m_retirementFailures.Add(exception); - } - } - try - { - OnDispose(); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception exception) - { - m_retirementFailures.Add(exception); - } - m_disposed = true; - GC.SuppressFinalize(this); - if (m_retirementFailures.Count > 0) - { - var failure = new AggregateException("Editor module retirement failed.", m_retirementFailures); - m_retirementFailures.Clear(); - throw failure; - } - } + protected virtual void OnDispose() {} } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs index f45f45085..75945b9d5 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs @@ -26,7 +26,9 @@ public EditorModuleAttribute( int order = 0 ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor module identifier is required.", nameof(id)); + } this.id = id; this.order = order; } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs index 93ecfbd86..084e53238 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs @@ -1,7 +1,5 @@ - using System; using System.Numerics; - using Inno.Core.Execution; using Inno.Scripting.Api; @@ -57,7 +55,9 @@ public void Attach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (m_attached) + { throw new InvalidOperationException($"Editor panel '{GetType().FullName}' is already attached."); + } m_attached = true; OnAttach(context); m_ready = true; @@ -66,9 +66,6 @@ public void Attach(EditorContext context) /// /// Detaches the panel before its extension generation is released. /// - /// - /// Also compensates partial attachment. Completed detachment is idempotent; a pending panel cannot draw. - /// /// /// The shared editor context for the runtime being detached. /// @@ -78,12 +75,17 @@ public void Attach(EditorContext context) /// /// Panel work is still active. The owner must retain the panel and its dependencies and retry detachment. /// + /// + /// Also compensates partial attachment. Completed detachment is idempotent; a pending panel cannot draw. + /// [ScriptingApiIgnore] public void Detach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (!m_attached) + { return; + } m_ready = false; try { @@ -118,7 +120,9 @@ public void Draw(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (!m_ready) + { throw new InvalidOperationException($"Editor panel '{GetType().FullName}' is not attached."); + } OnDraw(context); } @@ -136,51 +140,43 @@ public void Draw(EditorContext context) /// /// The shared editor context for the active runtime. /// - protected virtual void OnAttach(EditorContext context) - { - } + protected virtual void OnAttach(EditorContext context) {} /// /// Runs before the panel is detached from its active extension generation. /// + /// + /// The shared editor context for the runtime being detached. + /// /// /// This includes failed attachment compensation. Retain unfinished resources when throwing /// RetirementPendingException and avoid repeating completed cleanup steps on the next attempt. /// - /// - /// The shared editor context for the runtime being detached. - /// - protected virtual void OnDetach(EditorContext context) - { - } + protected virtual void OnDetach(EditorContext context) {} /// /// Captures readable project state owned by this panel. /// + /// + /// The writable parameter that receives the complete readable state for this panel. + /// /// /// Overriding this method opts the panel into project-state IO. Panels that keep the base /// implementation are never registered with the persistence coordinator and therefore perform /// no state reads or writes. Panel visibility is persisted separately for every registered panel. /// - /// - /// The writable parameter that receives the complete readable state for this panel. - /// - protected virtual void Capture(EditorState state) - { - } + protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this panel. /// - /// - /// This method is called only when is overridden. It runs once after the - /// panel is attached and before the panel is allowed to capture replacement state. - /// /// /// The read-only state parameter for this panel. Missing or incompatible values return the /// fallback supplied to . /// - protected virtual void Restore(EditorState state) - { - } + /// + /// This method is called only when is overridden. It runs once after the + /// panel is attached and before the panel is allowed to capture replacement state. + /// + protected virtual void Restore(EditorState state) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs index b0225d029..4574d6605 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs @@ -42,9 +42,13 @@ public EditorPanelAttribute( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor panel identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(title)) + { throw new ArgumentException("An editor panel title is required.", nameof(title)); + } this.id = id; this.title = title; this.order = order; @@ -86,16 +90,16 @@ public EditorPanelAttribute( private static string NormalizeMenuPath(string path) { if (string.IsNullOrWhiteSpace(path)) + { return string.Empty; + } string[] segments = path.Split('/'); for (int i = 0; i < segments.Length; i++) { segments[i] = segments[i].Trim(); if (segments[i].Length == 0) { - throw new ArgumentException( - "An editor panel menu path cannot contain an empty segment.", - nameof(path)); + throw new ArgumentException("An editor panel menu path cannot contain an empty segment.", nameof(path)); } } return string.Join('/', segments); diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs index 9cdc7b9ab..8e78776db 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Core; + /// /// Ranks assignable editor extension targets by class ancestry, with interface registrations one step away. /// @@ -48,7 +49,9 @@ out int distance while (current is not null) { if (current == candidateType) + { return true; + } distance++; current = current.BaseType; } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs index 694a08389..3af542812 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs @@ -1,13 +1,13 @@ -using Inno.Scripting.Api; using Inno.Editor.Core; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Core", "Inno.Editor.Core", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorKeyboardPolicy), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorContext), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorFrame), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorStatisticId), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorStatisticGroupId), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorStatisticID), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorStatisticGroupID), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorStatistic), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorStatistics), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorRuntime), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs index 98bb6de13..e743852ec 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.ExceptionServices; - -using Inno.Extensibility.Modules; using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Scripting.Reload; @@ -85,9 +84,9 @@ public IDisposable Register(IEditorReloadParticipant participant) { RemoveCollectedParticipants(); var registration = new Registration(this, Guid.NewGuid(), participant); - m_participants.Add(new ParticipantReference( - registration.id, - new WeakReference(participant))); + m_participants.Add( + new ParticipantReference(registration.id, new WeakReference(participant)) + ); return registration; } } @@ -116,7 +115,9 @@ public IAssemblyUnloadProbe Execute( ) { ArgumentNullException.ThrowIfNull(reload); if (!CanActivateReload(out string? reason)) + { throw new InvalidOperationException(reason ?? "An editor owner still prevents generation activation."); + } IGenerationChange[] transactions = CaptureTransactions(reload.context); var publication = new EditorPublication(reload, externalChange); return reload.generations.Execute("editor assembly reload", publication, [publication, .. transactions]); @@ -142,7 +143,8 @@ public void RefreshDiagnostics() Trace.TraceError( "Editor reload participant '{0}' failed to refresh diagnostics: {1}", participant.GetType().FullName, - exception); + exception + ); } } } @@ -160,14 +162,16 @@ private IGenerationChange[] CaptureTransactions(AssemblyReloadContext context) private List GetParticipants() { - var participants = new List(); + List participants = []; lock (m_sync) { RemoveCollectedParticipants(); foreach (ParticipantReference reference in m_participants) { if (reference.participant.TryGetTarget(out IEditorReloadParticipant? participant)) + { participants.Add(participant); + } } } return participants; @@ -184,8 +188,8 @@ out string? reason foreach (GuardReference reference in m_guards) { if (reference.guard.TryGetTarget(out IEditorReloadGuard? guard) - && !(manualRequest ? guard.canRequestReload : guard.canActivateReload)) - { + && !(manualRequest ? guard.canRequestReload : guard.canActivateReload) + ) { reason = guard.blockingReason ?? "Stop Play Mode before reloading scripts or Plugins."; return false; } @@ -195,11 +199,18 @@ out string? reason return true; } + private void Unregister(Guid registrationID) + { + lock (m_sync) + { + m_participants.RemoveAll(reference => reference.id == registrationID); + } + } + private sealed class EditorPublication( AssemblyReloadSession reload, IGenerationChange? external - ) - : IGenerationPublication, IGenerationChange + ) : IGenerationPublication, IGenerationChange { /// /// Publishes candidate assemblies before their external asset and settings generation. @@ -218,12 +229,6 @@ public void Activate() /// public IAssemblyUnloadProbe Complete() => reload.Complete(); - void IGenerationChange.PrepareForActivation() => external?.PrepareForActivation(); - void IGenerationChange.Apply() { } - void IGenerationChange.Complete() => external?.Complete(); - void IGenerationChange.RollbackStructure() => external?.RollbackStructure(); - void IGenerationChange.RestorePreviousState() { } - /// /// Restores old assemblies and external resolvers before domains restore their previous property values. /// @@ -255,17 +260,29 @@ public void Rollback() failures.Add(exception); } if (failures.Count > 0) + { throw new AggregateException("Editor publication rollback was incomplete.", failures); + } } + + void IGenerationChange.PrepareForActivation() => external?.PrepareForActivation(); + + void IGenerationChange.Apply() {} + + void IGenerationChange.Complete() => external?.Complete(); + + void IGenerationChange.RollbackStructure() => external?.RollbackStructure(); + + void IGenerationChange.RestorePreviousState() {} } private sealed class ParticipantChange( IEditorReloadParticipant participant, AssemblyReloadContext context - ) - : IGenerationChange + ) : IGenerationChange { private IGenerationChange? m_change; + /// /// Prepares candidate state without changing the active generation. /// @@ -275,10 +292,12 @@ public void PrepareForActivation() ?? throw new InvalidOperationException($"Editor reload participant '{participant.GetType().FullName}' returned no change."); m_change.PrepareForActivation(); } + /// /// Applies the prepared state at the caller-controlled commit point. /// public void Apply() => m_change!.Apply(); + /// /// Completes the committed operation and releases temporary state. /// @@ -287,10 +306,12 @@ public void Complete() m_change!.Complete(); m_change = null; } + /// /// Restores the state that existed before candidate activation began. /// public void RollbackStructure() => m_change?.RollbackStructure(); + /// /// Restores the state that existed before candidate activation began. /// @@ -301,12 +322,6 @@ public void RestorePreviousState() } } - private void Unregister(Guid registrationId) - { - lock (m_sync) - m_participants.RemoveAll(reference => reference.id == registrationId); - } - private readonly record struct ParticipantReference( Guid id, WeakReference participant @@ -325,19 +340,23 @@ IEditorReloadGuard guard { private IEditorReloadGuard? m_guard = guard; - internal Guid id { get; } = id; - - /// + /// public void Dispose() { IEditorReloadGuard? retained = m_guard; if (retained is null) + { return; + } lock (owner.m_sync) + { owner.m_guards.RemoveAll(reference => reference.id == id); + } m_guard = null; GC.KeepAlive(retained); } + + internal Guid id { get; } = id; } private sealed class Registration : IDisposable @@ -356,20 +375,22 @@ IEditorReloadParticipant participant m_participant = participant; } - internal Guid id { get; } - /// /// Releases the resources owned by this instance. /// public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; IEditorReloadParticipant? participant = m_participant; m_participant = null; m_owner.Unregister(id); GC.KeepAlive(participant); } + + internal Guid id { get; } } } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs b/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs index 91b2a191a..bb8e833f2 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs @@ -1,5 +1,5 @@ -using Inno.Extensibility.Reload; using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; namespace Inno.Editor.Core; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs index c52027aa5..8fc32f7ce 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Scripting.Api; namespace Inno.Editor.Core; @@ -44,12 +43,14 @@ public EditorContext( string? initialLayoutDocument = null ) { if (string.IsNullOrWhiteSpace(projectDirectory)) + { throw new ArgumentException("A project directory is required.", nameof(projectDirectory)); + } ArgumentNullException.ThrowIfNull(keyboard); this.keyboard = keyboard; this.projectDirectory = Path.GetFullPath(projectDirectory); - layout = new EditorLayoutSettings(this.projectDirectory, initialLayoutDocument); - statistics = new EditorStatistics(); + this.layout = new EditorLayoutSettings(this.projectDirectory, initialLayoutDocument); + this.statistics = new EditorStatistics(); } /// @@ -79,7 +80,15 @@ public EditorContext( [ScriptingApiIgnore] public string imguiLayout => layout.imguiLayout; - internal EditorLayoutSettings layout { get; } + /// + /// Gets the latest immutable editor frame snapshot. + /// + public EditorFrame frame { get; internal set; } + + /// + /// Gets whether any editor viewport currently owns application focus. + /// + public bool isFocused => frame.isFocused; /// /// Gets layout section names matching an ordinal prefix. @@ -115,8 +124,7 @@ public EditorContext( public bool TryGetLayoutSection( string sectionName, out IReadOnlyDictionary values - ) - => layout.TryGetSection(sectionName, out values); + ) => layout.TryGetSection(sectionName, out values); /// /// Adds or replaces one human-readable editor layout section in memory. @@ -137,8 +145,7 @@ out IReadOnlyDictionary values public void SetLayoutSection( string sectionName, IEnumerable> values - ) - => layout.SetSection(sectionName, values); + ) => layout.SetSection(sectionName, values); /// /// Removes one editor layout section from the in-memory document. @@ -191,14 +198,5 @@ IEnumerable> values [ScriptingApiIgnore] public void SaveLayout() => layout.Save(); - /// - /// Gets the latest immutable editor frame snapshot. - /// - public EditorFrame frame { get; internal set; } - - /// - /// Gets whether any editor viewport currently owns application focus. - /// - public bool isFocused => frame.isFocused; - + internal EditorLayoutSettings layout { get; } } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs index c0c6211e1..3adbe2a95 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs @@ -25,7 +25,9 @@ public EditorKeyboardPolicy( string superModifierLabel ) { if (primaryModifier is not (KeyModifier.Control or KeyModifier.Super or KeyModifier.Alt)) + { throw new ArgumentException("A primary shortcut requires one Control, Super or Alt modifier.", nameof(primaryModifier)); + } ArgumentException.ThrowIfNullOrWhiteSpace(superModifierLabel); this.primaryModifier = primaryModifier; this.superModifierLabel = superModifierLabel; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs index 03d5bf18f..34f55078d 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs @@ -57,7 +57,9 @@ internal string imguiLayout get { lock (m_sync) + { return m_imguiLayout; + } } } @@ -125,7 +127,9 @@ internal void SetImGuiLayout(string? layout) { Parse(layout ?? string.Empty, out string parsedLayout, out _); lock (m_sync) + { m_imguiLayout = parsedLayout; + } } /// @@ -155,7 +159,9 @@ IEnumerable> values } lock (m_sync) + { m_sections[sectionName] = replacement; + } } /// @@ -174,7 +180,9 @@ internal bool RemoveSection(string sectionName) { ValidateSectionName(sectionName); lock (m_sync) + { return m_sections.Remove(sectionName); + } } /// @@ -189,7 +197,9 @@ internal bool SaveIfChanged() { string document = Compose(m_imguiLayout, m_sections); if (string.Equals(document, m_lastSavedDocument, StringComparison.Ordinal)) + { return false; + } WriteDocument(document); return true; } @@ -201,7 +211,9 @@ internal bool SaveIfChanged() internal void Save() { lock (m_sync) + { WriteDocument(Compose(m_imguiLayout, m_sections)); + } } private void WriteDocument(string document) @@ -213,9 +225,13 @@ private void WriteDocument(string document) private string ReadDocument(string? initialDocument) { if (File.Exists(m_path)) + { return File.ReadAllText(m_path); + } if (initialDocument is null) + { return string.Empty; + } try { AtomicFile.WriteAllBytes(m_path, Encoding.UTF8.GetBytes(initialDocument), overwrite: false); @@ -246,17 +262,23 @@ out Dictionary> sections } if (line.StartsWith("[", StringComparison.Ordinal)) + { currentEditorSection = null; + } if (currentEditorSection is not null) { int separator = line.IndexOf('='); if (separator <= 0) + { continue; + } string key = line[..separator].Trim(); string value = line[(separator + 1)..].Trim(); if (IsValidKey(key) && IsValidValue(value)) + { currentEditorSection[key] = value; + } continue; } @@ -273,7 +295,9 @@ IReadOnlyDictionary> sections var builder = new StringBuilder(); string normalizedLayout = NormalizeLayout(layout); if (normalizedLayout.Length > 0) + { builder.Append(normalizedLayout).AppendLine().AppendLine(); + } string[] names = sections.Keys.OrderBy(static name => name, StringComparer.Ordinal).ToArray(); for (int sectionIndex = 0; sectionIndex < names.Length; sectionIndex++) @@ -282,9 +306,13 @@ IReadOnlyDictionary> sections builder.Append(C_SECTION_PREFIX).Append(name).AppendLine("]"); Dictionary section = sections[name]; foreach (KeyValuePair pair in OrderValues(section)) + { builder.Append(pair.Key).Append('=').AppendLine(pair.Value); + } if (sectionIndex + 1 < names.Length) + { builder.AppendLine(); + } } return builder.ToString(); } @@ -296,9 +324,9 @@ private static bool TryParseEditorSectionHeader( string line, out string sectionName ) { - if (line.StartsWith(C_SECTION_PREFIX, StringComparison.Ordinal) && - line.EndsWith(']')) - { + if (line.StartsWith(C_SECTION_PREFIX, StringComparison.Ordinal) + && line.EndsWith(']') + ) { sectionName = line[C_SECTION_PREFIX.Length..^1]; return IsValidSectionName(sectionName); } @@ -313,7 +341,8 @@ private static void ValidateSectionName(string sectionName) { throw new ArgumentException( "Editor settings section names cannot contain brackets or line breaks.", - nameof(sectionName)); + nameof(sectionName) + ); } } @@ -324,7 +353,8 @@ private static void ValidateKey(string key) { throw new ArgumentException( "Editor settings keys cannot contain an equals sign or line break.", - nameof(key)); + nameof(key) + ); } } @@ -333,24 +363,22 @@ private static void ValidateValue(string value) ArgumentNullException.ThrowIfNull(value); if (!IsValidValue(value)) { - throw new ArgumentException( - "Editor settings values cannot contain line breaks.", - nameof(value)); + throw new ArgumentException("Editor settings values cannot contain line breaks.", nameof(value)); } } private static bool IsValidSectionName(string value) - => !string.IsNullOrWhiteSpace(value) && - value.IndexOfAny(['[', ']', '\r', '\n']) < 0; + => !string.IsNullOrWhiteSpace(value) + && value.IndexOfAny(['[', ']', '\r', '\n']) < 0; private static bool IsValidKey(string value) - => !string.IsNullOrWhiteSpace(value) && - value.IndexOfAny(['=', '\r', '\n']) < 0; + => !string.IsNullOrWhiteSpace(value) + && value.IndexOfAny(['=', '\r', '\n']) < 0; private static bool IsValidValue(string value) => value.IndexOfAny(['\r', '\n']) < 0; private static string NormalizeLayout(string? layout) => string.IsNullOrWhiteSpace(layout) - ? string.Empty - : layout.TrimEnd('\r', '\n'); + ? string.Empty + : layout.TrimEnd('\r', '\n'); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorRuntime.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorRuntime.cs index dc1c83400..bd899d291 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorRuntime.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorRuntime.cs @@ -18,7 +18,8 @@ public abstract class EditorRuntime : IDisposable /// protected EditorRuntime(EditorContext context) { - this.context = context ?? throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(context); + this.context = context; } /// @@ -39,6 +40,11 @@ protected EditorRuntime(EditorContext context) /// public abstract void Update(EditorFrame frame); + /// + /// Stops the runtime and releases active extensions. + /// + public abstract void Dispose(); + /// /// Advances frame-scoped data and publishes the latest immutable frame. /// @@ -50,9 +56,4 @@ protected void SetFrame(EditorFrame frame) context.statistics.AdvanceFrame(); context.frame = frame; } - - /// - /// Stops the runtime and releases active extensions. - /// - public abstract void Dispose(); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs index ffce7cd7c..ad3998985 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs @@ -16,9 +16,7 @@ public abstract class EditorState /// /// Initializes the base contract for a runtime-owned editor state parameter. /// - protected EditorState() - { - } + protected EditorState() {} /// /// Reads a compatible value or returns the caller-provided fallback. diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs new file mode 100644 index 000000000..7ccd74d80 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs @@ -0,0 +1,100 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Describes one immutable, presentation-ready statistic without retaining provider instances or types. +/// +public sealed class EditorStatistic +{ + /// + /// Creates one statistic contribution. + /// + /// + /// Globally stable statistic identity used for replacement within a frame. + /// + /// + /// Stable visual group identity. + /// + /// + /// User-facing group heading. + /// + /// + /// User-facing metric label. + /// + /// + /// Already formatted user-facing value. + /// + /// + /// Ascending group presentation order. + /// + /// + /// Ascending metric order within the group. + /// + /// + /// Thrown when an identifier, group name, label, or value is empty. + /// + public EditorStatistic( + EditorStatisticID id, + EditorStatisticGroupID groupID, + string groupName, + string label, + string value, + int groupOrder = 0, + int order = 0 + ) { + if (!id.isValid) + { + throw new ArgumentException("A statistic ID is required.", nameof(id)); + } + if (!groupID.isValid) + { + throw new ArgumentException("A statistic group ID is required.", nameof(groupID)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(groupName); + ArgumentException.ThrowIfNullOrWhiteSpace(label); + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.id = id; + this.groupID = groupID; + this.groupName = groupName.Trim(); + this.label = label.Trim(); + this.value = value.Trim(); + this.groupOrder = groupOrder; + this.order = order; + } + + /// + /// Gets the globally stable statistic identity. + /// + public EditorStatisticID id { get; } + + /// + /// Gets the stable visual group identity. + /// + public EditorStatisticGroupID groupID { get; } + + /// + /// Gets the user-facing group heading. + /// + public string groupName { get; } + + /// + /// Gets the user-facing metric label. + /// + public string label { get; } + + /// + /// Gets the presentation-ready value. + /// + public string value { get; } + + /// + /// Gets ascending group presentation order. + /// + public int groupOrder { get; } + + /// + /// Gets ascending metric order within the group. + /// + public int order { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs new file mode 100644 index 000000000..28b660ef6 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs @@ -0,0 +1,42 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Identifies one visual group in the editor statistics presentation. +/// +public readonly record struct EditorStatisticGroupID +{ + /// + /// Creates a globally stable statistic-group identifier. + /// + /// + /// Non-empty globally stable identity. + /// + /// + /// Thrown when is empty. + /// + public EditorStatisticGroupID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the globally stable identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs new file mode 100644 index 000000000..1e2543975 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs @@ -0,0 +1,42 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Identifies one editor statistic across panels, modules, and reloadable extensions. +/// +public readonly record struct EditorStatisticID +{ + /// + /// Creates a globally stable statistic identifier. + /// + /// + /// Non-empty globally stable identity. + /// + /// + /// Thrown when is empty. + /// + public EditorStatisticID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the globally stable identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs index 4b46f6946..2b322541e 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs @@ -4,177 +4,6 @@ namespace Inno.Editor.Core; -/// -/// Identifies one editor statistic across panels, modules, and reloadable extensions. -/// -public readonly record struct EditorStatisticId -{ - /// - /// Creates a globally stable statistic identifier. - /// - /// - /// Non-empty globally stable identity. - /// - /// - /// Thrown when is empty. - /// - public EditorStatisticId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the globally stable identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Identifies one visual group in the editor statistics presentation. -/// -public readonly record struct EditorStatisticGroupId -{ - /// - /// Creates a globally stable statistic-group identifier. - /// - /// - /// Non-empty globally stable identity. - /// - /// - /// Thrown when is empty. - /// - public EditorStatisticGroupId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the globally stable identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes one immutable, presentation-ready statistic without retaining provider instances or types. -/// -public sealed class EditorStatistic -{ - /// - /// Creates one statistic contribution. - /// - /// - /// Globally stable statistic identity used for replacement within a frame. - /// - /// - /// Stable visual group identity. - /// - /// - /// User-facing group heading. - /// - /// - /// User-facing metric label. - /// - /// - /// Already formatted user-facing value. - /// - /// - /// Ascending group presentation order. - /// - /// - /// Ascending metric order within the group. - /// - /// - /// Thrown when an identifier, group name, label, or value is empty. - /// - public EditorStatistic( - EditorStatisticId id, - EditorStatisticGroupId groupId, - string groupName, - string label, - string value, - int groupOrder = 0, - int order = 0 - ) { - if (!id.isValid) - throw new ArgumentException("A statistic ID is required.", nameof(id)); - if (!groupId.isValid) - throw new ArgumentException("A statistic group ID is required.", nameof(groupId)); - ArgumentException.ThrowIfNullOrWhiteSpace(groupName); - ArgumentException.ThrowIfNullOrWhiteSpace(label); - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.id = id; - this.groupId = groupId; - this.groupName = groupName.Trim(); - this.label = label.Trim(); - this.value = value.Trim(); - this.groupOrder = groupOrder; - this.order = order; - } - - /// - /// Gets the globally stable statistic identity. - /// - public EditorStatisticId id { get; } - - /// - /// Gets the stable visual group identity. - /// - public EditorStatisticGroupId groupId { get; } - - /// - /// Gets the user-facing group heading. - /// - public string groupName { get; } - - /// - /// Gets the user-facing metric label. - /// - public string label { get; } - - /// - /// Gets the presentation-ready value. - /// - public string value { get; } - - /// - /// Gets ascending group presentation order. - /// - public int groupOrder { get; } - - /// - /// Gets ascending metric order within the group. - /// - public int order { get; } -} - /// /// Exchanges frame-scoped, reload-safe statistics between independent editor features and viewers. /// @@ -185,8 +14,8 @@ public EditorStatistic( public sealed class EditorStatistics { private readonly object m_sync = new(); - private Dictionary m_current = []; - private Dictionary m_completed = []; + private Dictionary m_current = []; + private Dictionary m_completed = []; private IReadOnlyList? m_snapshot; private bool m_snapshotDirty = true; @@ -206,7 +35,9 @@ public void Publish(EditorStatistic statistic) { EditorStatistic? previous = m_current.GetValueOrDefault(statistic.id) ?? m_completed.GetValueOrDefault(statistic.id); if (previous is null || !SameValue(previous, statistic)) + { m_snapshotDirty = true; + } m_current[statistic.id] = statistic; } } @@ -224,7 +55,9 @@ public void Publish(IEnumerable statistics) { ArgumentNullException.ThrowIfNull(statistics); foreach (EditorStatistic statistic in statistics) + { Publish(statistic); + } } /// @@ -240,10 +73,14 @@ public IReadOnlyList GetSnapshot() lock (m_sync) { if (!m_snapshotDirty && m_snapshot is not null) + { return m_snapshot; - var merged = new Dictionary(m_completed); - foreach ((EditorStatisticId id, EditorStatistic statistic) in m_current) + } + var merged = new Dictionary(m_completed); + foreach ((EditorStatisticID id, EditorStatistic statistic) in m_current) + { merged[id] = statistic; + } EditorStatistic[] values = merged.Values .OrderBy(static value => value.groupOrder) .ThenBy(static value => value.groupName, StringComparer.OrdinalIgnoreCase) @@ -261,10 +98,12 @@ internal void AdvanceFrame() { lock (m_sync) { - foreach (EditorStatisticId id in m_completed.Keys) + foreach (EditorStatisticID id in m_completed.Keys) { if (m_current.ContainsKey(id)) + { continue; + } m_snapshotDirty = true; break; } @@ -277,10 +116,10 @@ private static bool SameValue( EditorStatistic first, EditorStatistic second ) => ReferenceEquals(first, second) - || first.groupId == second.groupId - && first.groupOrder == second.groupOrder - && first.order == second.order - && string.Equals(first.groupName, second.groupName, StringComparison.Ordinal) - && string.Equals(first.label, second.label, StringComparison.Ordinal) - && string.Equals(first.value, second.value, StringComparison.Ordinal); + || first.groupID == second.groupID + && first.groupOrder == second.groupOrder + && first.order == second.order + && string.Equals(first.groupName, second.groupName, StringComparison.Ordinal) + && string.Equals(first.label, second.label, StringComparison.Ordinal) + && string.Equals(first.value, second.value, StringComparison.Ordinal); } diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs index 926e0a3b7..0503a7e4f 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Security.Cryptography; using System.Text; @@ -11,16 +12,16 @@ internal static string Create(EditorConsoleOccurrence occurrence) var builder = new StringBuilder(); Append(builder, occurrence.kind.ToString()); Append(builder, occurrence.level.ToString()); - Append(builder, occurrence.sourceId); + Append(builder, occurrence.sourceID); Append(builder, occurrence.source); Append(builder, occurrence.code); Append(builder, occurrence.category); Append(builder, occurrence.message); Append(builder, occurrence.file); - Append(builder, occurrence.line.ToString(System.Globalization.CultureInfo.InvariantCulture)); - Append(builder, occurrence.column.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Append(builder, occurrence.line.ToString(CultureInfo.InvariantCulture)); + Append(builder, occurrence.column.ToString(CultureInfo.InvariantCulture)); Append(builder, occurrence.stackTrace); - Append(builder, occurrence.sessionId.ToString()); + Append(builder, occurrence.sessionID.ToString()); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(builder.ToString()))); } diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs index d34efea5a..1b04caaba 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading; - using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.PlayMode; @@ -48,9 +47,12 @@ public EditorConsole( DiagnosticHub diagnosticHub, IEditorPlayMode playMode ) { - m_logRouter = logRouter ?? throw new ArgumentNullException(nameof(logRouter)); - m_diagnosticHub = diagnosticHub ?? throw new ArgumentNullException(nameof(diagnosticHub)); - m_playMode = playMode ?? throw new ArgumentNullException(nameof(playMode)); + ArgumentNullException.ThrowIfNull(logRouter); + ArgumentNullException.ThrowIfNull(diagnosticHub); + ArgumentNullException.ThrowIfNull(playMode); + m_logRouter = logRouter; + m_diagnosticHub = diagnosticHub; + m_playMode = playMode; } /// @@ -61,7 +63,9 @@ public int capacity get { lock (m_sync) + { return m_capacity; + } } set { @@ -69,7 +73,9 @@ public int capacity { int normalized = Math.Max(16, value); if (normalized == m_capacity) + { return; + } m_capacity = normalized; TrimLogsUnsafe(); m_revision++; @@ -93,7 +99,9 @@ public void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { return; + } IDisposable subscription = m_playMode.ListenStateChanges(OnPlayModeStateChanged); try { @@ -138,7 +146,9 @@ public void Replace(DiagnosticReport report) ArgumentNullException.ThrowIfNull(report); var entries = new EditorConsoleOccurrence[report.diagnostics.Count]; for (int i = 0; i < entries.Length; i++) + { entries[i] = FromDiagnostic(NextSequence(), report, report.diagnostics[i]); + } lock (m_sync) { m_diagnostics[report.source.id] = entries; @@ -146,6 +156,22 @@ public void Replace(DiagnosticReport report) } } + /// + /// Removes retained logs while keeping currently reported issues visible until their owners resolve them. + /// + public void Clear() + { + lock (m_sync) + { + if (m_logs.Count == 0) + { + return; + } + m_logs.Clear(); + m_revision++; + } + } + /// /// Removes the current diagnostic report for one producer. /// @@ -157,7 +183,9 @@ public void Clear(DiagnosticSource source) lock (m_sync) { if (m_diagnostics.Remove(source.id)) + { m_revision++; + } } } @@ -184,27 +212,15 @@ public EditorConsoleSnapshot Capture() } } - /// - /// Removes retained logs while keeping currently reported issues visible until their owners resolve them. - /// - public void Clear() - { - lock (m_sync) - { - if (m_logs.Count == 0) - return; - m_logs.Clear(); - m_revision++; - } - } - /// /// Detaches this service and releases its subscriptions. /// public void Dispose() { if (m_disposed) + { return; + } if (m_started) { m_playModeSubscription?.Dispose(); @@ -219,7 +235,9 @@ public void Dispose() private void OnPlayModeStateChanged(EditorPlayModeState state) { if (state == EditorPlayModeState.Compiling && clearOnPlay) + { ClearLogsForPlay(); + } } private void ClearLogsForPlay() @@ -228,31 +246,43 @@ private void ClearLogsForPlay() lock (m_sync) { if (m_logs.Count == 0) + { return; + } m_logs.Clear(); m_revision++; } } + private long NextSequence() => Interlocked.Increment(ref m_nextSequence); + + private void TrimLogsUnsafe() + { + while (m_logs.Count > m_capacity) + { + _ = m_logs.Dequeue(); + } + } + private static EditorConsoleOccurrence FromLog( long sequence, LogEntry entry - ) - => new( - sequence, - EditorConsoleEntryKind.Log, - entry.level, - $"{entry.domain}/{entry.scope}", - string.Empty, - string.Empty, - entry.category, - entry.message, - entry.time, - entry.file, - entry.line, - 0, - entry.stackTrace, - entry.sessionId); + ) => new( + sequence, + EditorConsoleEntryKind.Log, + entry.level, + $"{entry.domain}/{entry.scope}", + string.Empty, + string.Empty, + entry.category, + entry.message, + entry.time, + entry.file, + entry.line, + 0, + entry.stackTrace, + entry.sessionID + ); private static EditorConsoleOccurrence FromDiagnostic( long sequence, @@ -280,14 +310,7 @@ Diagnostic diagnostic location?.line ?? 0, location?.column ?? 0, string.Empty, - LogSessionId.none); - } - - private long NextSequence() => Interlocked.Increment(ref m_nextSequence); - - private void TrimLogsUnsafe() - { - while (m_logs.Count > m_capacity) - _ = m_logs.Dequeue(); + LogSessionID.none + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs index 1f5e488a3..31e11a4f1 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs @@ -9,7 +9,6 @@ public enum EditorConsoleEntryKind /// The occurrence was emitted through the runtime logging pipeline. /// Log, - /// /// The occurrence represents current state from a diagnostic producer. /// diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs index d64755925..777742287 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs @@ -14,7 +14,7 @@ EditorConsoleOccurrence[] occurrences ) { this.identity = identity; this.occurrences = Array.AsReadOnly(occurrences); - latest = occurrences[^1]; + this.latest = occurrences[^1]; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs index abdf44300..0a65d1fbf 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; namespace Inno.Editor.Diagnostics; @@ -14,7 +13,7 @@ internal EditorConsoleOccurrence( EditorConsoleEntryKind kind, LogLevel level, string source, - string sourceId, + string sourceID, string code, string category, string message, @@ -23,13 +22,13 @@ internal EditorConsoleOccurrence( int line, int column, string stackTrace, - LogSessionId sessionId + LogSessionID sessionID ) { this.sequence = sequence; this.kind = kind; this.level = level; this.source = source; - this.sourceId = sourceId; + this.sourceID = sourceID; this.code = code; this.category = category; this.message = message; @@ -38,7 +37,7 @@ LogSessionId sessionId this.line = line; this.column = column; this.stackTrace = stackTrace; - this.sessionId = sessionId; + this.sessionID = sessionID; } /// @@ -64,7 +63,7 @@ LogSessionId sessionId /// /// Gets the stable diagnostic producer identifier, or an empty string for log entries. /// - public string sourceId { get; } + public string sourceID { get; } /// /// Gets the diagnostic code, or an empty string for uncoded entries. @@ -114,5 +113,5 @@ LogSessionId sessionId /// /// Gets the isolated runtime session that emitted this occurrence. /// - public LogSessionId sessionId { get; } + public LogSessionID sessionID { get; } } diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs index 565f4377d..fb26779d9 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs @@ -1,6 +1,7 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; +using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.Interactions; @@ -11,10 +12,10 @@ namespace Inno.Editor.Graph; /// public sealed class GraphCanvasState { - private readonly HashSet m_selectedNodes = []; - private readonly HashSet m_selectedEdges = []; - private FrozenSet? m_nodeSelection; - private FrozenSet? m_edgeSelection; + private readonly HashSet m_selectedNodes = []; + private readonly HashSet m_selectedEdges = []; + private FrozenSet? m_nodeSelection; + private FrozenSet? m_edgeSelection; /// /// Gets the graph-space origin mapped to canvas screen origin. @@ -29,12 +30,12 @@ public sealed class GraphCanvasState /// /// Gets selected node identities. /// - public IReadOnlyCollection selectedNodes => m_nodeSelection ??= m_selectedNodes.ToFrozenSet(); + public IReadOnlyCollection selectedNodes => m_nodeSelection ??= m_selectedNodes.ToFrozenSet(); /// /// Gets selected edge identities. /// - public IReadOnlyCollection selectedEdges => m_edgeSelection ??= m_selectedEdges.ToFrozenSet(); + public IReadOnlyCollection selectedEdges => m_edgeSelection ??= m_selectedEdges.ToFrozenSet(); /// /// Gets the endpoint currently being connected, or . @@ -60,7 +61,9 @@ public void SetViewport( float zoom ) { if (!float.IsFinite(pan.x) || !float.IsFinite(pan.y)) + { throw new ArgumentOutOfRangeException(nameof(pan)); + } if (!float.IsFinite(zoom)) { throw new ArgumentOutOfRangeException(nameof(zoom)); @@ -107,7 +110,7 @@ float pivotY } float next = Math.Clamp(zoom * factor, 0.1f, 4f); - System.Numerics.Vector2 origin = EditorPlanarNavigation.ZoomOrigin(new(pan.x, pan.y), new(pivotX, pivotY), zoom, next); + Vector2 origin = EditorPlanarNavigation.ZoomOrigin(new Vector2(pan.x, pan.y), new Vector2(pivotX, pivotY), zoom, next); pan = new GraphPosition(origin.X, origin.Y); zoom = next; } @@ -118,7 +121,7 @@ float pivotY /// /// Complete selected-node set. /// - public void SelectNodes(IEnumerable nodes) + public void SelectNodes(IEnumerable nodes) { ArgumentNullException.ThrowIfNull(nodes); m_selectedNodes.Clear(); @@ -129,15 +132,15 @@ public void SelectNodes(IEnumerable nodes) /// /// Toggles one node while preserving the remaining selection. /// - /// + /// /// Node to toggle. /// - public void ToggleNode(GraphNodeId nodeId) + public void ToggleNode(GraphNodeID nodeID) { m_nodeSelection = null; - if (!m_selectedNodes.Remove(nodeId)) + if (!m_selectedNodes.Remove(nodeID)) { - m_selectedNodes.Add(nodeId); + m_selectedNodes.Add(nodeID); } } @@ -152,6 +155,14 @@ public void ClearSelection() m_edgeSelection = null; } + /// + /// Begins a connection drag from one output endpoint. + /// + /// + /// Stable output endpoint. + /// + public void BeginConnection(GraphEndpoint output) => BeginConnection(output, GraphPortDirection.Output); + /// /// Begins a connection drag from one endpoint. /// @@ -169,14 +180,6 @@ GraphPortDirection direction pendingConnectionDirection = direction; } - /// - /// Begins a connection drag from one output endpoint. - /// - /// - /// Stable output endpoint. - /// - public void BeginConnection(GraphEndpoint output) => BeginConnection(output, GraphPortDirection.Output); - /// /// Cancels any active connection drag. /// diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs new file mode 100644 index 000000000..f3bb03bc0 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs @@ -0,0 +1,28 @@ +using Inno.Core.Graphs; + +namespace Inno.Editor.Graph; + +/// +/// Contains a neutral copied node fragment suitable for graph clipboard operations. +/// +public sealed class GraphClipboardData +{ + private readonly GraphDocument m_fragment; + + internal GraphClipboardData(GraphDocument fragment) + { + m_fragment = fragment; + } + + /// + /// Gets the copied node count. + /// + public int nodeCount => m_fragment.nodes.Count; + + /// + /// Gets the copied connection count whose endpoints both belong to the fragment. + /// + public int edgeCount => m_fragment.edges.Count; + + internal GraphDocument CloneFragment() => m_fragment.Clone(); +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs index 648a7df84..9a3c38930 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs @@ -8,36 +8,12 @@ namespace Inno.Editor.Graph; -/// -/// Contains a neutral copied node fragment suitable for graph clipboard operations. -/// -public sealed class GraphClipboardData -{ - internal GraphClipboardData(GraphDocument fragment) => m_fragment = fragment; - - private readonly GraphDocument m_fragment; - - /// - /// Gets the copied node count. - /// - public int nodeCount => m_fragment.nodes.Count; - - /// - /// Gets the copied connection count whose endpoints both belong to the fragment. - /// - public int edgeCount => m_fragment.edges.Count; - - internal GraphDocument CloneFragment() => m_fragment.Clone(); -} - /// /// Applies neutral graph edits atomically and records every data mutation in reload-safe Editor History. /// public sealed class GraphDocumentController { private readonly Identity m_identity; - private GraphDocumentSession session => m_identity.Resolve() - ?? throw new InvalidOperationException("The Graph document controller belongs to a closed identity generation."); private readonly IEditorHistory m_history; private readonly SerializationRegistry m_serialization; @@ -54,7 +30,7 @@ SerializationRegistry serialization /// /// Gets the stable project-relative document identity. /// - public Guid documentId => m_identity.persistentId; + public Guid documentID => m_identity.persistentID; /// /// Gets whether the current document identity and source are both available. @@ -90,24 +66,28 @@ SerializationRegistry serialization /// /// Concise artist-facing history entry name. /// - /// + /// /// Unique active gesture identity for continuous samples, or null for an independent edit. /// public void ReplaceDocument( GraphDocument replacement, string historyName, - string? gestureId = null + string? gestureID = null ) { ArgumentNullException.ThrowIfNull(replacement); ArgumentException.ThrowIfNullOrWhiteSpace(historyName); GraphDocument snapshot = replacement.Clone(); - Mutate(historyName, gestureId is null ? null : $"graph:{documentId}:document:{gestureId}", () => document.ReplaceContents(snapshot)); + Mutate( + historyName, + gestureID is null ? null : $"graph:{documentID}:document:{gestureID}", + () => document.ReplaceContents(snapshot) + ); } /// /// Adds a node with a generated stable identity. /// - /// + /// /// Stable node definition ID. /// /// @@ -119,21 +99,21 @@ public void ReplaceDocument( /// /// The new stable node identity. /// - public GraphNodeId AddNode( - string definitionId, + public GraphNodeID AddNode( + string definitionID, GraphPosition position, IReadOnlyDictionary? values = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(definitionId); - GraphNodeId id = NewNodeId(); + ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); + GraphNodeID id = NewNodeID(); Mutate("Create Node", null, () => { - var node = new GraphNodeRecord(id, definitionId) { position = position }; + var node = new GraphNodeRecord(id, definitionID) { position = position }; if (values is not null) { - foreach ((string propertyId, GraphSerializedValue value) in values) + foreach ((string propertyID, GraphSerializedValue value) in values) { - node.SetValue(propertyId, value.Clone()); + node.SetValue(propertyID, value.Clone()); } } @@ -145,26 +125,26 @@ public GraphNodeId AddNode( /// /// Removes nodes and all incident connections as one structural edit. /// - /// + /// /// Nodes to remove. /// - public void RemoveNodes(IEnumerable nodeIds) + public void RemoveNodes(IEnumerable nodeIDs) { - ArgumentNullException.ThrowIfNull(nodeIds); - GraphNodeId[] ids = nodeIds.Distinct().ToArray(); + ArgumentNullException.ThrowIfNull(nodeIDs); + GraphNodeID[] ids = nodeIDs.Distinct().ToArray(); if (ids.Length == 0) { return; } - foreach (GraphNodeId id in ids) + foreach (GraphNodeID id in ids) { RequireNode(id); } Mutate(ids.Length == 1 ? "Delete Node" : "Delete Nodes", null, () => { - foreach (GraphNodeId id in ids) + foreach (GraphNodeID id in ids) { document.RemoveNode(id); } @@ -177,7 +157,7 @@ public void RemoveNodes(IEnumerable nodeIds) /// /// Complete destination positions keyed by node identity. /// - public void MoveNodes(IReadOnlyDictionary positions) + public void MoveNodes(IReadOnlyDictionary positions) { ArgumentNullException.ThrowIfNull(positions); if (positions.Count == 0) @@ -185,7 +165,7 @@ public void MoveNodes(IReadOnlyDictionary positions) return; } - foreach (GraphNodeId id in positions.Keys) + foreach (GraphNodeID id in positions.Keys) { RequireNode(id); } @@ -195,11 +175,12 @@ public void MoveNodes(IReadOnlyDictionary positions) null, () => { - foreach ((GraphNodeId id, GraphPosition position) in positions) + foreach ((GraphNodeID id, GraphPosition position) in positions) { document.FindNode(id)!.position = position; } - }); + } + ); } /// @@ -214,124 +195,125 @@ public void MoveNodes(IReadOnlyDictionary positions) /// /// The generated connection identity. /// - public GraphEdgeId Connect( + public GraphEdgeID Connect( GraphEndpoint output, GraphEndpoint input ) { - RequireNode(output.nodeId); - RequireNode(input.nodeId); - if (output.nodeId == input.nodeId && output.portId == input.portId) + RequireNode(output.nodeID); + RequireNode(input.nodeID); + if (output.nodeID == input.nodeID && output.portID == input.portID) { throw new ArgumentException("A graph endpoint cannot connect to itself.", nameof(input)); } - GraphEdgeId edgeId = NewEdgeId(); + GraphEdgeID edgeID = NewEdgeID(); Mutate("Connect Nodes", null, () => { - GraphEdgeId[] replaced = document.edges + GraphEdgeID[] replaced = document.edges .Where(edge => edge.input == input) .Select(static edge => edge.id) .ToArray(); - foreach (GraphEdgeId existing in replaced) + foreach (GraphEdgeID existing in replaced) { document.RemoveEdge(existing); } - document.AddEdge(new GraphEdgeRecord(edgeId, output, input)); + document.AddEdge(new GraphEdgeRecord(edgeID, output, input)); }); - return edgeId; + return edgeID; } /// /// Removes one stable connection. /// - /// + /// /// Connection to remove. /// /// /// after a connection was removed. /// - public bool Disconnect(GraphEdgeId edgeId) + public bool Disconnect(GraphEdgeID edgeID) { - if (!document.edges.Any(edge => edge.id == edgeId)) + if (!document.edges.Any(edge => edge.id == edgeID)) { return false; } - Mutate("Disconnect Nodes", null, () => document.RemoveEdge(edgeId)); + Mutate("Disconnect Nodes", null, () => document.RemoveEdge(edgeID)); return true; } /// /// Creates or replaces one neutral node property; only samples carrying the same explicit gesture identity merge. /// - /// + /// /// Owning node. /// - /// + /// /// Stable property ID. /// /// /// New neutral value. /// - /// + /// /// Unique current text/numeric gesture identity, or null for an independent edit. /// public void SetNodeValue( - GraphNodeId nodeId, - string propertyId, + GraphNodeID nodeID, + string propertyID, GraphSerializedValue value, - string? gestureId = null + string? gestureID = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyId); + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); ArgumentNullException.ThrowIfNull(value); - GraphNodeRecord node = RequireNode(nodeId); + GraphNodeRecord node = RequireNode(nodeID); Mutate( "Edit Node Property", - gestureId is null ? null : $"graph:{documentId}:value:{nodeId.value}:{propertyId}:{gestureId}", - () => node.SetValue(propertyId, value.Clone())); + gestureID is null ? null : $"graph:{documentID}:value:{nodeID.value}:{propertyID}:{gestureID}", + () => node.SetValue(propertyID, value.Clone()) + ); } /// /// Removes one neutral node property as a structural edit. /// - /// + /// /// Owning node. /// - /// + /// /// Stable property ID. /// /// /// when the property existed. /// public bool RemoveNodeValue( - GraphNodeId nodeId, - string propertyId + GraphNodeID nodeID, + string propertyID ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyId); - GraphNodeRecord node = RequireNode(nodeId); - if (!node.values.ContainsKey(propertyId)) + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + GraphNodeRecord node = RequireNode(nodeID); + if (!node.values.ContainsKey(propertyID)) { return false; } - Mutate("Remove Node Property", null, () => node.RemoveValue(propertyId)); + Mutate("Remove Node Property", null, () => node.RemoveValue(propertyID)); return true; } /// /// Copies selected nodes and only their internal connections. /// - /// + /// /// Nodes to copy. /// /// /// A detached neutral clipboard fragment. /// - public GraphClipboardData Copy(IEnumerable nodeIds) + public GraphClipboardData Copy(IEnumerable nodeIDs) { - ArgumentNullException.ThrowIfNull(nodeIds); - HashSet selected = [.. nodeIds]; + ArgumentNullException.ThrowIfNull(nodeIDs); + HashSet selected = [.. nodeIDs]; var fragment = new GraphDocument(); foreach (GraphNodeRecord source in document.nodes.Where(node => selected.Contains(node.id))) { @@ -339,8 +321,8 @@ public GraphClipboardData Copy(IEnumerable nodeIds) } foreach (GraphEdgeRecord edge in document.edges.Where( - edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId))) - { + edge => selected.Contains(edge.output.nodeID) && selected.Contains(edge.input.nodeID) + )) { fragment.AddEdge(new GraphEdgeRecord(edge.id, edge.output, edge.input)); } @@ -356,23 +338,23 @@ public GraphClipboardData Copy(IEnumerable nodeIds) /// /// Offset added to every copied node position. /// - /// - /// New node identities in clipboard document order. - /// /// /// Optional synchronous domain remapping of neutral node values after identity allocation. The callback is never stored in History. /// - public IReadOnlyList Paste( + /// + /// New node identities in clipboard document order. + /// + public IReadOnlyList Paste( GraphClipboardData clipboard, GraphPosition offset, - Action>? remapNode = null + Action>? remapNode = null ) { ArgumentNullException.ThrowIfNull(clipboard); GraphDocument fragment = clipboard.CloneFragment(); - Dictionary remap = []; + Dictionary remap = []; foreach (GraphNodeRecord node in fragment.nodes) { - remap.Add(node.id, NewNodeId()); + remap.Add(node.id, NewNodeID()); } Mutate("Paste Nodes", null, () => @@ -382,22 +364,30 @@ public IReadOnlyList Paste( GraphNodeRecord clone = CloneNode( source, remap[source.id], - new GraphPosition(source.position.x + offset.x, source.position.y + offset.y)); + new GraphPosition(source.position.x + offset.x, source.position.y + offset.y) + ); remapNode?.Invoke(clone, remap); document.AddNode(clone); } foreach (GraphEdgeRecord edge in fragment.edges) { - document.AddEdge(new GraphEdgeRecord( - NewEdgeId(), - new GraphEndpoint(remap[edge.output.nodeId], edge.output.portId), - new GraphEndpoint(remap[edge.input.nodeId], edge.input.portId))); + document.AddEdge( + new GraphEdgeRecord( + NewEdgeID(), + new GraphEndpoint(remap[edge.output.nodeID], edge.output.portID), + new GraphEndpoint(remap[edge.input.nodeID], edge.input.portID) + ) + ); } }); return fragment.nodes.Select(node => remap[node.id]).ToArray(); } + private GraphDocumentSession session + => m_identity.Resolve() + ?? throw new InvalidOperationException("The Graph document controller belongs to a closed identity generation."); + private void Mutate( string name, string? mergeKey, @@ -405,7 +395,7 @@ Action mutation ) { if (!session.available) { - throw new InvalidOperationException($"Graph document '{documentId}' is closed."); + throw new InvalidOperationException($"Graph document '{documentID}' is closed."); } byte[] before = GraphHistoryDocumentCodec.Encode(document, m_serialization); @@ -418,7 +408,7 @@ Action mutation return; } - var change = GraphHistoryData.CreateChange(documentId, before, after, mergeKey); + EditorHistoryChange change = GraphHistoryData.CreateChange(documentID, before, after, mergeKey); try { m_history.RecordApplied(name, change); @@ -439,24 +429,25 @@ Action mutation } } - private GraphNodeRecord RequireNode(GraphNodeId nodeId) - => document.FindNode(nodeId) - ?? throw new ArgumentException($"Node '{nodeId}' is not present in '{documentId}'.", nameof(nodeId)); + private GraphNodeRecord RequireNode(GraphNodeID nodeID) + => document.FindNode(nodeID) + ?? throw new ArgumentException($"Node '{nodeID}' is not present in '{documentID}'.", nameof(nodeID)); private static GraphNodeRecord CloneNode( GraphNodeRecord source, - GraphNodeId id, + GraphNodeID id, GraphPosition position ) { - var clone = new GraphNodeRecord(id, source.definitionId) { position = position }; - foreach ((string propertyId, GraphSerializedValue value) in source.values) + var clone = new GraphNodeRecord(id, source.definitionID) { position = position }; + foreach ((string propertyID, GraphSerializedValue value) in source.values) { - clone.SetValue(propertyId, value.Clone()); + clone.SetValue(propertyID, value.Clone()); } return clone; } - private static GraphNodeId NewNodeId() => new(Guid.NewGuid().ToString("N")); - private static GraphEdgeId NewEdgeId() => new(Guid.NewGuid().ToString("N")); + private static GraphNodeID NewNodeID() => new(Guid.NewGuid().ToString("N")); + + private static GraphEdgeID NewEdgeID() => new(Guid.NewGuid().ToString("N")); } diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs index 141aeb2df..7cbfc22d1 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Core.Identity; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; -using Inno.References; using Inno.Core.Graphs; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.References; namespace Inno.Editor.Graph; @@ -23,23 +23,23 @@ public sealed class GraphEditorModule : EditorModule, IEditorReloadParticipant private readonly HashSet m_documents = []; private readonly List m_ownedSessions = []; private readonly EditorReloadCoordinator m_reloads; - private IDisposable? m_registration; private readonly SerializationRegistry m_serialization; + private IDisposable? m_registration; internal GraphEditorModule( SerializationRegistry serialization, EditorReloadCoordinator reloads ) { - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_reloads = reloads ?? throw new ArgumentNullException(nameof(reloads)); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(reloads); + m_serialization = serialization; + m_reloads = reloads; } - internal SerializationRegistry serialization => m_serialization; - /// /// Opens or joins an active graph document session. /// - /// + /// /// Persistent document identity; use the Asset identity for asset-backed graphs. /// /// @@ -55,22 +55,26 @@ EditorReloadCoordinator reloads /// The bounded document owner is full. /// public GraphDocumentController OpenDocument( - Guid documentId, + Guid documentID, GraphDocument document, IEditorHistory history ) { - if (documentId == Guid.Empty) - throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentId)); + if (documentID == Guid.Empty) + { + throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentID)); + } ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(history); - GraphDocumentSession? session = m_identities.Get(documentId); + GraphDocumentSession? session = m_identities.Get(documentID); if (session is null) { if (m_documents.Count >= C_DOCUMENT_CAPACITY) + { throw new InvalidOperationException("Graph document capacity has been reached; close unused documents explicitly."); + } session = new GraphDocumentSession(document); - m_identities.Register(session, documentId); - m_documents.Add(documentId); + m_identities.Register(session, documentID); + m_documents.Add(documentID); m_ownedSessions.Add(session); } // Reattaching presentation joins the existing authoring state, including unsaved Missing nodes. @@ -80,19 +84,21 @@ IEditorHistory history /// /// Closes a document explicitly; its neutral History entries remain unavailable until the identity is reopened. /// - /// + /// /// The persistent document identity to release. /// /// /// True when a live document was closed. /// - public bool CloseDocument(Guid documentId) + public bool CloseDocument(Guid documentID) { - GraphDocumentSession? session = m_identities.Get(documentId); + GraphDocumentSession? session = m_identities.Get(documentID); if (session is null) + { return false; + } m_identities.Unregister(session); - m_documents.Remove(documentId); + m_documents.Remove(documentID); m_ownedSessions.Remove(session); return true; } @@ -100,7 +106,7 @@ public bool CloseDocument(Guid documentId) /// /// Resolves an already open document without replacing its authored contents. /// - /// + /// /// The persistent document identity. /// /// @@ -113,12 +119,12 @@ public bool CloseDocument(Guid documentId) /// True when the document is still owned by this module. /// public bool TryOpenDocument( - Guid documentId, + Guid documentID, IEditorHistory history, out GraphDocumentController? controller ) { ArgumentNullException.ThrowIfNull(history); - GraphDocumentSession? session = m_identities.Get(documentId); + GraphDocumentSession? session = m_identities.Get(documentID); controller = session is null ? null : new GraphDocumentController(session, history, m_serialization); return controller is not null; } @@ -126,24 +132,24 @@ out GraphDocumentController? controller /// /// Marks a temporarily Missing source without discarding its graph or advancing its History stack. /// - /// + /// /// The persistent identity of an open document. /// /// /// Whether its source can be resolved in the current generation. /// public void SetAvailability( - Guid documentId, + Guid documentID, bool available ) { - GraphDocumentSession? session = m_identities.Get(documentId); + GraphDocumentSession? session = m_identities.Get(documentID); session?.available = available; } /// /// Rebinds an active session to a newly imported current-generation document. /// - /// + /// /// Stable document identity. /// /// @@ -153,16 +159,18 @@ bool available /// Thrown when the document has no active session. /// public void RebindDocument( - Guid documentId, + Guid documentID, GraphDocument document ) { - if (documentId == Guid.Empty) - throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentId)); + if (documentID == Guid.Empty) + { + throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentID)); + } ArgumentNullException.ThrowIfNull(document); - GraphDocumentSession? session = m_identities.Get(documentId); + GraphDocumentSession? session = m_identities.Get(documentID); if (session is null) { - throw new InvalidOperationException($"Graph document '{documentId}' is not open."); + throw new InvalidOperationException($"Graph document '{documentID}' is not open."); } if (!session.isDirty) @@ -173,13 +181,12 @@ GraphDocument document session.available = true; } - internal bool TryResolve( - Guid documentId, - out GraphDocumentSession? session - ) { - session = m_identities.Get(documentId); - return session is not null && session.available; - } + IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) + => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], [new Recovery(this)]); + + void IEditorReloadParticipant.RefreshDiagnostics() {} + + internal SerializationRegistry serialization => m_serialization; /// /// Initializes this feature when its owning runtime becomes active. @@ -210,16 +217,21 @@ protected override void OnDispose() { GraphDocumentSession? session = m_identities.Get(id); if (session is not null) + { m_identities.Unregister(session); + } } m_documents.Clear(); m_ownedSessions.Clear(); } - IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) - => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], [new Recovery(this)]); - - void IEditorReloadParticipant.RefreshDiagnostics() { } + internal bool TryResolve( + Guid documentID, + out GraphDocumentSession? session + ) { + session = m_identities.Get(documentID); + return session is not null && session.available; + } private sealed class Recovery(GraphEditorModule owner) : IReferenceRecoveryParticipant { @@ -234,20 +246,33 @@ public void PrepareForActivation() foreach (Guid id in owner.m_documents) { GraphDocumentSession session = owner.m_identities.Get(id)!; - m_previous.Add(id, new State(GraphDocumentCodec.Encode(session.document, owner.m_serialization), - session.revision, session.isDirty, session.available)); + m_previous.Add( + id, + new State( + GraphDocumentCodec.Encode(session.document, owner.m_serialization), + session.revision, + session.isDirty, + session.available + ) + ); } } + /// /// Applies the prepared state at the caller-controlled commit point. /// public void Apply() { foreach ((Guid id, State state) in m_previous) + { m_candidate.Add(id, GraphDocumentCodec.Decode(state.bytes, owner.m_serialization)); + } foreach ((Guid id, GraphDocument document) in m_candidate) + { owner.m_identities.Get(id)!.document = document; + } } + /// /// Rejects any recovery that changes captured nodes, edges, properties or order. /// @@ -257,10 +282,18 @@ public void Apply() public void Validate(IReadOnlyList changes) { foreach ((Guid id, State state) in m_previous) - if (!state.bytes.AsSpan().SequenceEqual(GraphDocumentCodec.Encode( - owner.m_identities.Get(id)!.document, owner.m_serialization))) + { + if (!state.bytes.AsSpan().SequenceEqual( + GraphDocumentCodec.Encode( + owner.m_identities.Get(id)!.document, + owner.m_serialization + ) + )) { throw new InvalidOperationException("Graph recovery changed neutral authored content."); + } + } } + /// /// Completes the committed operation and releases temporary state. /// @@ -269,10 +302,12 @@ public void Complete() m_previous.Clear(); m_candidate.Clear(); } + /// /// Restores the state that existed before candidate activation began. /// public void RollbackStructure() => m_candidate.Clear(); + /// /// Restores the state that existed before candidate activation began. /// @@ -289,6 +324,7 @@ public void RestorePreviousState() } Complete(); } + private sealed record State( byte[] bytes, ulong revision, diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs deleted file mode 100644 index da803d55c..000000000 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs +++ /dev/null @@ -1,381 +0,0 @@ -using System; -using System.Buffers.Binary; -using System.Diagnostics; -using System.IO; -using System.Text; -using Inno.Core.Graphs; -using Inno.Core.Serialization; -using Inno.Editor.Interactions; - -namespace Inno.Editor.Graph; - -internal static class GraphHistoryDocumentCodec -{ - /// - /// Encodes the supplied value into deterministic structured data. - /// - /// - /// The document consumed by encode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The serialization consumed by encode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public static byte[] Encode( - GraphDocument document, - SerializationRegistry serialization - ) - => GraphDocumentCodec.Encode(document, serialization); - - /// - /// Decodes deterministic structured data into a validated value. - /// - /// - /// The complete immutable byte payload consumed by this operation. - /// - /// - /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The validated graph document that represents the completed operation. - /// - public static GraphDocument Decode( - ReadOnlySpan bytes, - SerializationRegistry serialization - ) - => GraphDocumentCodec.Decode(bytes, serialization); -} - -internal sealed record GraphHistoryData( - Guid documentId, - byte[] before, - byte[] after, - long timestamp -) { - /// - /// The c kind value used as part of this type's public representation. - /// - public const string C_KIND = "editor.graph.document"; - private static readonly UTF8Encoding S_UTF8 = new(false, true); - - /// - /// Creates and validates a caller-owned change value. - /// - /// - /// The document id text validated by the create change operation. - /// - /// - /// The before consumed by create change; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The after consumed by create change; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The merge key text validated by the create change operation. - /// - /// - /// The validated editor history change that represents the completed operation. - /// - public static EditorHistoryChange CreateChange( - Guid documentId, - ReadOnlySpan before, - ReadOnlySpan after, - string? mergeKey - ) { - var data = new GraphHistoryData(documentId, before.ToArray(), after.ToArray(), Stopwatch.GetTimestamp()); - return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(data.Encode()), mergeKey); - } - - /// - /// Encodes the supplied value into deterministic structured data. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public byte[] Encode() - { - byte[] id = S_UTF8.GetBytes(documentId.ToString("D")); - byte[] result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; - Span span = result; - BinaryPrimitives.WriteInt32LittleEndian(span, id.Length); - id.CopyTo(span[sizeof(int)..]); - int offset = sizeof(int) + id.Length; - BinaryPrimitives.WriteInt32LittleEndian(span[offset..], before.Length); - offset += sizeof(int); - before.CopyTo(span[offset..]); - offset += before.Length; - BinaryPrimitives.WriteInt32LittleEndian(span[offset..], after.Length); - offset += sizeof(int); - after.CopyTo(span[offset..]); - offset += after.Length; - BinaryPrimitives.WriteInt64LittleEndian(span[offset..], timestamp); - return result; - } - - /// - /// Decodes deterministic structured data into a validated value. - /// - /// - /// The payload consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The validated graph history data that represents the completed operation. - /// - public static GraphHistoryData Decode( - ReadOnlySpan payload, - SerializationRegistry serialization - ) { - int offset = 0; - int idLength = ReadLength(payload, ref offset); - Guid id = Guid.ParseExact(S_UTF8.GetString(ReadSlice(payload, ref offset, idLength)), "D"); - if (id == Guid.Empty) - throw new InvalidDataException("Graph history requires a persistent document identity."); - int beforeLength = ReadLength(payload, ref offset); - byte[] before = ReadSlice(payload, ref offset, beforeLength).ToArray(); - int afterLength = ReadLength(payload, ref offset); - byte[] after = ReadSlice(payload, ref offset, afterLength).ToArray(); - if (payload.Length - offset != sizeof(long)) - { - throw new InvalidDataException("Graph History payload has an invalid timestamp boundary."); - } - - long timestamp = BinaryPrimitives.ReadInt64LittleEndian(payload[offset..]); - _ = GraphHistoryDocumentCodec.Decode(before, serialization); - _ = GraphHistoryDocumentCodec.Decode(after, serialization); - return new GraphHistoryData(id, before, after, timestamp); - } - - private static int ReadLength( - ReadOnlySpan payload, - ref int offset - ) { - if (payload.Length - offset < sizeof(int)) - { - throw new InvalidDataException("Graph History payload is truncated."); - } - - int length = BinaryPrimitives.ReadInt32LittleEndian(payload[offset..]); - offset += sizeof(int); - if (length < 0 || length > payload.Length - offset) - { - throw new InvalidDataException("Graph History payload contains an invalid length."); - } - - return length; - } - - private static ReadOnlySpan ReadSlice( - ReadOnlySpan payload, - ref int offset, - int length - ) { - ReadOnlySpan result = payload.Slice(offset, length); - offset += length; - return result; - } -} - -internal readonly record struct GraphHistoryTransitionResult( - EditorHistoryResult result, - bool stateIntegrityLost -); - -internal static class GraphHistoryTransition -{ - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The module consumed by apply; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated graph history transition result that represents the completed operation. - /// - public static GraphHistoryTransitionResult Apply( - GraphEditorModule module, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - GraphHistoryData data = GraphHistoryData.Decode( - change.payload.ReadBytes(), - module.serialization); - if (!module.TryResolve(data.documentId, out GraphDocumentSession? session) || session is null) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure($"Graph document '{data.documentId}' is not open."), - false); - } - - GraphDocument original = session.document.Clone(); - try - { - session.document.ReplaceContents(GraphHistoryDocumentCodec.Decode( - direction == EditorHistoryDirection.Undo ? data.before : data.after, - module.serialization)); - session.revision++; - session.isDirty = true; - return new GraphHistoryTransitionResult(EditorHistoryResult.Success(), false); - } - catch (Exception exception) - { - try - { - session.document.ReplaceContents(original); - } - catch (Exception rollbackException) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure( - $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}"), - true); - } - - return new GraphHistoryTransitionResult(EditorHistoryResult.Failure(exception.Message), false); - } - } - catch (Exception exception) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure($"Graph History payload is invalid: {exception.Message}"), - false); - } - } -} - -[EditorHistoryHandler(GraphHistoryData.C_KIND)] -internal sealed class GraphHistoryHandler(GraphEditorModule module) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - _ = context; - _ = direction; - try - { - GraphHistoryData data = GraphHistoryData.Decode( - change.payload.ReadBytes(), - module.serialization); - return module.TryResolve(data.documentId, out _) - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentId}' is not open."); - } - catch (Exception exception) - { - return EditorHistoryAvailability.Unavailable($"Graph History payload is invalid: {exception.Message}"); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - _ = context; - GraphHistoryTransitionResult transition = GraphHistoryTransition.Apply(module, change, direction); - return transition.stateIntegrityLost - ? StateIntegrityFailure(transition.result.message) - : transition.result; - } - - /// - /// Attempts to merge without changing state when the operation cannot complete. - /// - /// - /// The earlier history payload considered for coalescing. - /// - /// - /// The later history payload considered for coalescing. - /// - /// - /// Receives the neutral coalesced payload when merging succeeds. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) { - merged = null; - if (older.mergeKey is null || !StringComparer.Ordinal.Equals(older.mergeKey, newer.mergeKey)) - { - return false; - } - - try - { - GraphHistoryData previous = GraphHistoryData.Decode( - older.payload.ReadBytes(), - module.serialization); - GraphHistoryData current = GraphHistoryData.Decode( - newer.payload.ReadBytes(), - module.serialization); - if (previous.documentId != current.documentId - || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0) - { - return false; - } - - var combined = new GraphHistoryData( - previous.documentId, - previous.before, - current.after, - current.timestamp); - merged = new EditorHistoryChange( - GraphHistoryData.C_KIND, - EditorHistoryPayload.FromBytes(combined.Encode()), - older.mergeKey); - return true; - } - catch - { - return false; - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs new file mode 100644 index 000000000..74eca1ac4 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs @@ -0,0 +1,144 @@ +using System; +using System.Buffers.Binary; +using System.Diagnostics; +using System.IO; +using System.Text; +using Inno.Core.Serialization; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +internal sealed record GraphHistoryData( + Guid documentID, + byte[] before, + byte[] after, + long timestamp +) { + /// + /// The c kind value used as part of this type's public representation. + /// + public const string C_KIND = "editor.graph.document"; + + private static readonly UTF8Encoding UTF8 = new(false, true); + + /// + /// Encodes the supplied value into deterministic structured data. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public byte[] Encode() + { + byte[] id = UTF8.GetBytes(documentID.ToString("D")); + var result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; + Span span = result; + BinaryPrimitives.WriteInt32LittleEndian(span, id.Length); + id.CopyTo(span[sizeof(int)..]); + int offset = sizeof(int) + id.Length; + BinaryPrimitives.WriteInt32LittleEndian(span[offset..], before.Length); + offset += sizeof(int); + before.CopyTo(span[offset..]); + offset += before.Length; + BinaryPrimitives.WriteInt32LittleEndian(span[offset..], after.Length); + offset += sizeof(int); + after.CopyTo(span[offset..]); + offset += after.Length; + BinaryPrimitives.WriteInt64LittleEndian(span[offset..], timestamp); + return result; + } + + /// + /// Creates and validates a caller-owned change value. + /// + /// + /// The document id text validated by the create change operation. + /// + /// + /// The before consumed by create change; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The after consumed by create change; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The merge key text validated by the create change operation. + /// + /// + /// The validated editor history change that represents the completed operation. + /// + public static EditorHistoryChange CreateChange( + Guid documentID, + ReadOnlySpan before, + ReadOnlySpan after, + string? mergeKey + ) { + var data = new GraphHistoryData(documentID, before.ToArray(), after.ToArray(), Stopwatch.GetTimestamp()); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(data.Encode()), mergeKey); + } + + /// + /// Decodes deterministic structured data into a validated value. + /// + /// + /// The payload consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The validated graph history data that represents the completed operation. + /// + public static GraphHistoryData Decode( + ReadOnlySpan payload, + SerializationRegistry serialization + ) { + int offset = 0; + int idLength = ReadLength(payload, ref offset); + Guid id = Guid.ParseExact(UTF8.GetString(ReadSlice(payload, ref offset, idLength)), "D"); + if (id == Guid.Empty) + { + throw new InvalidDataException("Graph history requires a persistent document identity."); + } + int beforeLength = ReadLength(payload, ref offset); + byte[] before = ReadSlice(payload, ref offset, beforeLength).ToArray(); + int afterLength = ReadLength(payload, ref offset); + byte[] after = ReadSlice(payload, ref offset, afterLength).ToArray(); + if (payload.Length - offset != sizeof(long)) + { + throw new InvalidDataException("Graph History payload has an invalid timestamp boundary."); + } + + long timestamp = BinaryPrimitives.ReadInt64LittleEndian(payload[offset..]); + _ = GraphHistoryDocumentCodec.Decode(before, serialization); + _ = GraphHistoryDocumentCodec.Decode(after, serialization); + return new GraphHistoryData(id, before, after, timestamp); + } + + private static int ReadLength( + ReadOnlySpan payload, + ref int offset + ) { + if (payload.Length - offset < sizeof(int)) + { + throw new InvalidDataException("Graph History payload is truncated."); + } + + int length = BinaryPrimitives.ReadInt32LittleEndian(payload[offset..]); + offset += sizeof(int); + if (length < 0 || length > payload.Length - offset) + { + throw new InvalidDataException("Graph History payload contains an invalid length."); + } + + return length; + } + + private static ReadOnlySpan ReadSlice( + ReadOnlySpan payload, + ref int offset, + int length + ) { + ReadOnlySpan result = payload.Slice(offset, length); + offset += length; + return result; + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs new file mode 100644 index 000000000..6390b3076 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs @@ -0,0 +1,42 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Editor.Graph; + +internal static class GraphHistoryDocumentCodec +{ + /// + /// Encodes the supplied value into deterministic structured data. + /// + /// + /// The document consumed by encode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The serialization consumed by encode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public static byte[] Encode( + GraphDocument document, + SerializationRegistry serialization + ) => GraphDocumentCodec.Encode(document, serialization); + + /// + /// Decodes deterministic structured data into a validated value. + /// + /// + /// The complete immutable byte payload consumed by this operation. + /// + /// + /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The validated graph document that represents the completed operation. + /// + public static GraphDocument Decode( + ReadOnlySpan bytes, + SerializationRegistry serialization + ) => GraphDocumentCodec.Decode(bytes, serialization); +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs new file mode 100644 index 000000000..6b5df0f5c --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs @@ -0,0 +1,122 @@ +using System; +using System.Diagnostics; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +[EditorHistoryHandler(GraphHistoryData.C_KIND)] +internal sealed class GraphHistoryHandler(GraphEditorModule module) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + _ = context; + _ = direction; + try + { + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); + return module.TryResolve(data.documentID, out _) + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentID}' is not open."); + } + catch (Exception exception) + { + return EditorHistoryAvailability.Unavailable($"Graph History payload is invalid: {exception.Message}"); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + _ = context; + GraphHistoryTransitionResult transition = GraphHistoryTransition.Apply(module, change, direction); + return transition.stateIntegrityLost + ? StateIntegrityFailure(transition.result.message) + : transition.result; + } + + /// + /// Attempts to merge without changing state when the operation cannot complete. + /// + /// + /// The earlier history payload considered for coalescing. + /// + /// + /// The later history payload considered for coalescing. + /// + /// + /// Receives the neutral coalesced payload when merging succeeds. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) { + merged = null; + if (older.mergeKey is null || !StringComparer.Ordinal.Equals(older.mergeKey, newer.mergeKey)) + { + return false; + } + + try + { + GraphHistoryData previous = GraphHistoryData.Decode(older.payload.ReadBytes(), module.serialization); + GraphHistoryData current = GraphHistoryData.Decode(newer.payload.ReadBytes(), module.serialization); + if (previous.documentID != current.documentID + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0 + ) { + return false; + } + + var combined = new GraphHistoryData(previous.documentID, previous.before, current.after, current.timestamp); + merged = new EditorHistoryChange( + GraphHistoryData.C_KIND, + EditorHistoryPayload.FromBytes(combined.Encode()), + older.mergeKey + ); + return true; + } + catch (Exception) + { + // A payload that cannot be decoded is not merged. The two changes stay separate. + return false; + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs new file mode 100644 index 000000000..b85b5d653 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs @@ -0,0 +1,85 @@ +using System; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +internal static class GraphHistoryTransition +{ + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The module consumed by apply; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated graph history transition result that represents the completed operation. + /// + public static GraphHistoryTransitionResult Apply( + GraphEditorModule module, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); + if (!module.TryResolve(data.documentID, out GraphDocumentSession? session) || session is null) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure($"Graph document '{data.documentID}' is not open."), + false + ); + } + + GraphDocument original = session.document.Clone(); + try + { + session.document.ReplaceContents( + GraphHistoryDocumentCodec.Decode( + direction == EditorHistoryDirection.Undo ? data.before : data.after, + module.serialization + ) + ); + session.revision++; + session.isDirty = true; + return new GraphHistoryTransitionResult(EditorHistoryResult.Success(), false); + } + catch (Exception exception) + { + try + { + session.document.ReplaceContents(original); + } + catch (Exception rollbackException) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure( + $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ), + true + ); + } + + return new GraphHistoryTransitionResult(EditorHistoryResult.Failure(exception.Message), false); + } + } + catch (Exception exception) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure($"Graph History payload is invalid: {exception.Message}"), + false + ); + } + } +} + +internal readonly record struct GraphHistoryTransitionResult( + EditorHistoryResult result, + bool stateIntegrityLost +); diff --git a/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs index 25911c73e..d34bf1b37 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Graph; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Graph", "Inno.Editor.Graph", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(GraphEditorModule), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs deleted file mode 100644 index 26ac1188f..000000000 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs +++ /dev/null @@ -1,261 +0,0 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; -using System.Collections; -using System.Globalization; -using System.Reflection; -using Inno.Core.Serialization; -using Inno.Editor.Annotations; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; - -namespace Inno.Editor.Inspection; -[InspectorAttributeDrawer(typeof(HeaderAttribute))] -internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders the section heading before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - var header = (HeaderAttribute)context.attribute; - EditorUI.current.widgets.SectionHeader(header.title, header.description); - } -} - -[InspectorAttributeDrawer(typeof(TextAttribute))] -internal sealed class TextInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders persistent explanatory text before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - string text = ((TextAttribute)context.attribute).text; - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); - try - { - EditorUI.current.widgets.WrappedText(text); - } - finally - { - Ui.PopStyleColor(); - } - } -} - -[InspectorAttributeDrawer(typeof(SpaceAttribute))] -internal sealed class SpaceInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders the requested vertical spacing before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - float height = ((SpaceAttribute)context.attribute).height; - Ui.Dummy(new System.Numerics.Vector2(0f, height)); - } -} - -[InspectorAttributeDrawer(typeof(TooltipAttribute))] -internal sealed class TooltipInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Applies tooltip text to the annotated property row. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.tooltip = ((TooltipAttribute)context.attribute).text; -} - -[InspectorAttributeDrawer(typeof(InspectorNameAttribute))] -internal sealed class NameInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Replaces the default serialized member label. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.label = ((InspectorNameAttribute)context.attribute).name; -} - -[InspectorAttributeDrawer(typeof(RangeAttribute))] -internal sealed class RangeInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Applies inclusive numeric slider bounds to the annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - var range = (RangeAttribute)context.attribute; - context.minimum = range.minimum; - context.maximum = range.maximum; - } -} - -[InspectorAttributeDrawer(typeof(InspectorReadOnlyAttribute))] -internal sealed class ReadOnlyInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Disables assignment for the annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.isReadOnly = true; -} - -[InspectorAttributeDrawer(typeof(ShowIfAttribute))] -internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Hides the annotated property unless its sibling condition succeeds. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - var condition = (ShowIfAttribute)context.attribute; - context.isVisible &= InspectorConditionEvaluator.Evaluate(context.GetSiblingValue(condition.memberName), condition.condition, condition.expectedValue); - } -} - -[InspectorAttributeDrawer(typeof(HideIfAttribute))] -internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Hides the annotated property when its sibling condition succeeds. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - var condition = (HideIfAttribute)context.attribute; - context.isVisible &= !InspectorConditionEvaluator.Evaluate(context.GetSiblingValue(condition.memberName), condition.condition, condition.expectedValue); - } -} - -[InspectorAttributeDrawer(typeof(HelpBoxAttribute))] -internal sealed class HelpBoxInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders a conditional diagnostic message before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - var help = (HelpBoxAttribute)context.attribute; - if (!string.IsNullOrWhiteSpace(help.conditionMember) - && !InspectorConditionEvaluator.Evaluate( - context.GetSiblingValue(help.conditionMember), - help.condition, - help.expectedValue - )) - { - return; - } - - System.Numerics.Vector4 color = help.messageType switch - { - InspectorMessageType.Warning => EditorPalette.warning, - InspectorMessageType.Error => EditorPalette.error, - _ => new System.Numerics.Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque)}; - string icon = help.messageType switch - { - InspectorMessageType.Warning => ImGuiIcon.TriangleExclamation, - InspectorMessageType.Error => ImGuiIcon.CircleXmark, - _ => ImGuiIcon.CircleInfo - }; - EditorUI.current.widgets.HelpBox(help.text, icon, color); - } -} - -internal static class InspectorConditionEvaluator -{ - internal static bool Evaluate( - object? value, - InspectorCondition condition, - object? expected - ) { - return condition switch - { - InspectorCondition.Truthy => IsTruthy(value), - InspectorCondition.Falsy => !IsTruthy(value), - InspectorCondition.Equal => AreEqual(value, expected), - InspectorCondition.NotEqual => !AreEqual(value, expected), - InspectorCondition.Null => value is null, - InspectorCondition.NotNull => value is not null, - InspectorCondition.Assigned => IsAssigned(value), - InspectorCondition.NotAssigned => !IsAssigned(value), - _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.")}; - } - - private static bool IsTruthy(object? value) - { - return value switch - { - null => false, - bool boolean => boolean, - string text => !string.IsNullOrWhiteSpace(text), - ICollection collection => collection.Count > 0, - _ => true - }; - } - - private static bool IsAssigned(object? value) - { - if (value is null) - return false; - PropertyInfo? property = value.GetType().GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 ? (bool)(property.GetValue(value) ?? false) : true; - } - - private static bool AreEqual( - object? value, - object? expected - ) { - if (Equals(value, expected)) - return true; - if (value is null || expected is null) - return false; - Type valueType = value.GetType(); - try - { - object converted = valueType.IsEnum ? expected is string name ? Enum.Parse( - valueType, - name, - ignoreCase: false - ) : Enum.ToObject( - valueType, - expected - ) : Convert.ChangeType( - expected, - valueType, - CultureInfo.InvariantCulture - ); - return Equals(value, converted); - } - catch (Exception exception) when (exception is ArgumentException or InvalidCastException or FormatException or OverflowException) - { - return false; - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs new file mode 100644 index 000000000..00783c4f1 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs @@ -0,0 +1,21 @@ +using Inno.Editor.Annotations; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HeaderAttribute))] +internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders the section heading before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + HeaderAttribute header = (HeaderAttribute)context.attribute; + EditorUI.current.widgets.SectionHeader(header.title, header.description); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs new file mode 100644 index 000000000..15009155c --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs @@ -0,0 +1,45 @@ +using System.Numerics; +using Inno.Editor.Annotations; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HelpBoxAttribute))] +internal sealed class HelpBoxInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders a conditional diagnostic message before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + HelpBoxAttribute help = (HelpBoxAttribute)context.attribute; + if (!string.IsNullOrWhiteSpace(help.conditionMember) + && !InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(help.conditionMember), + help.condition, + help.expectedValue + ) + ) { + return; + } + + Vector4 color = help.messageType switch + { + InspectorMessageType.Warning => EditorPalette.warning, + InspectorMessageType.Error => EditorPalette.error, + _ => new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.C_OPACITY_OPAQUE) + }; + string icon = help.messageType switch + { + InspectorMessageType.Warning => ImGuiIcon.C_TRIANGLE_EXCLAMATION, + InspectorMessageType.Error => ImGuiIcon.C_CIRCLE_XMARK, + _ => ImGuiIcon.C_CIRCLE_INFO + }; + EditorUI.current.widgets.HelpBox(help.text, icon, color); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs new file mode 100644 index 000000000..b2037a89f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs @@ -0,0 +1,23 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HideIfAttribute))] +internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Hides the annotated property when its sibling condition succeeds. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + HideIfAttribute condition = (HideIfAttribute)context.attribute; + context.isVisible &= !InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs index 24f29349f..5e45c9b07 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs @@ -11,9 +11,7 @@ public interface IInspectorAttributeDrawer /// /// Mutable presentation state for the annotated property. /// - void Update(InspectorAttributeDrawContext context) - { - } + void Update(InspectorAttributeDrawContext context) {} /// /// Draws a decorator immediately before the property row. @@ -21,9 +19,7 @@ void Update(InspectorAttributeDrawContext context) /// /// Current presentation state for the annotated property. /// - void DrawBefore(InspectorAttributeDrawContext context) - { - } + void DrawBefore(InspectorAttributeDrawContext context) {} /// /// Draws a decorator immediately after the property row. @@ -31,7 +27,5 @@ void DrawBefore(InspectorAttributeDrawContext context) /// /// Current presentation state for the annotated property. /// - void DrawAfter(InspectorAttributeDrawContext context) - { - } + void DrawAfter(InspectorAttributeDrawContext context) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs index 3b463b045..ac7138c87 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs @@ -19,13 +19,16 @@ internal InspectorAttributeDrawContext( string label, bool isReadOnly ) { - this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); - this.member = member ?? throw new ArgumentNullException(nameof(member)); + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(member); + ArgumentNullException.ThrowIfNull(label); + this.owner = owner; + this.member = member; this.property = property; this.path = string.IsNullOrWhiteSpace(path) - ? throw new ArgumentException("The property path is required.", nameof(path)) - : path; - this.label = label ?? throw new ArgumentNullException(nameof(label)); + ? throw new ArgumentException("The property path is required.", nameof(path)) + : path; + this.label = label; this.isReadOnly = isReadOnly; } @@ -99,25 +102,31 @@ bool isReadOnly public object? GetSiblingValue(string memberName) { ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + const BindingFlags C_FLAGS = BindingFlags.Instance | BindingFlags.Public + | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; for (Type? type = owner.GetType(); type is not null && type != typeof(object); type = type.BaseType) { - FieldInfo? field = type.GetField(memberName, flags); + FieldInfo? field = type.GetField(memberName, C_FLAGS); if (field is not null) + { return field.GetValue(owner); - PropertyInfo? candidate = type.GetProperty(memberName, flags); + } + PropertyInfo? candidate = type.GetProperty(memberName, C_FLAGS); if (candidate is null) + { continue; + } if (candidate.GetIndexParameters().Length != 0 || candidate.GetGetMethod(true) is null) { throw new InvalidOperationException( - $"Inspector condition member '{type.FullName}.{memberName}' is not readable."); + $"Inspector condition member '{type.FullName}.{memberName}' is not readable." + ); } return candidate.GetValue(owner); } throw new InvalidOperationException( - $"Inspector condition member '{owner.GetType().FullName}.{memberName}' does not exist."); + $"Inspector condition member '{owner.GetType().FullName}.{memberName}' does not exist." + ); } internal void SelectAttribute(Attribute value) => m_attribute = value ?? throw new ArgumentNullException(nameof(value)); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs index 370109030..cef004ca9 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs @@ -27,7 +27,9 @@ public InspectorAttributeDrawerAttribute( ) { ArgumentNullException.ThrowIfNull(targetType); if (!typeof(Attribute).IsAssignableFrom(targetType)) + { throw new ArgumentException($"'{targetType.FullName}' is not an attribute type.", nameof(targetType)); + } this.targetType = targetType; this.useForChildren = useForChildren; this.priority = priority; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs index 37d1b688c..6263d2fb2 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs @@ -39,32 +39,34 @@ IEnumerable drawerServices m_registry = new AttributeTypeRegistry(interactions, types, serialization, drawerServices); } + /// + /// Releases active drawer generations. + /// + public void Dispose() => m_registry.Dispose(); + internal void Update( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.Update(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.Update(value)); internal void DrawBefore( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.DrawBefore(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.DrawBefore(value)); internal void DrawAfter( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.DrawAfter(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.DrawAfter(value)); private void Apply( InspectorAttributeDrawContext context, @@ -76,16 +78,30 @@ Action callback Attribute attribute = attributes[index]; IInspectorAttributeDrawer? drawer = m_registry.Resolve(attribute.GetType()); if (drawer is null) + { continue; + } context.SelectAttribute(attribute); callback(drawer, context); } } - /// - /// Releases active drawer generations. - /// - public void Dispose() => m_registry.Dispose(); + private static void EnsureNoConflict( + IReadOnlyList registrations, + InspectorAttributeDrawerAttribute attribute, + Type drawerType + ) { + foreach (Registration existing in registrations) + { + if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) + { + throw new InvalidOperationException( + $"Inspector attribute drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); + } + } + } private sealed class AttributeTypeRegistry : TypeRegistry { @@ -98,36 +114,19 @@ internal AttributeTypeRegistry( TypeCatalog types, SerializationRegistry serialization, IEnumerable services - ) - : base(types) + ) : base(types) { - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(serialization); + m_interactions = interactions; + m_serialization = serialization; ArgumentNullException.ThrowIfNull(services); - m_services = services.Select(static service => service ?? throw new ArgumentException( - "Inspector attribute drawer services cannot contain null.", nameof(services))).ToArray(); - } - - internal IInspectorAttributeDrawer? Resolve(Type attributeType) - { - Registration? best = null; - int bestDistance = int.MaxValue; - foreach (Registration registration in current) - { - if (!DrawerTypeUtility.TryGetDistance( - attributeType, - registration.targetType, - registration.useForChildren, - out int distance)) - continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) - { - best = registration; - bestDistance = distance; - } - } - return best?.drawer; + m_services = services.Select(static service => ( + service ?? throw new ArgumentException( + "Inspector attribute drawer services cannot contain null.", + nameof(services) + ) + )).ToArray(); } /// @@ -142,25 +141,28 @@ IEnumerable services protected override Registration[] Build(TypeCacheSnapshot types) { var drawers = new Dictionary(); - var registrations = new List(); + List registrations = []; foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IInspectorAttributeDrawer drawer = drawers.TryGetValue(drawerType, out IInspectorAttributeDrawer? existing) - ? existing - : OwnCandidateExtension(CreateDrawer(drawerType, types)); + ? existing + : OwnCandidateExtension(CreateDrawer(drawerType, types)); drawers[drawerType] = drawer; foreach (InspectorAttributeDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -175,16 +177,42 @@ protected override Registration[] Build(TypeCacheSnapshot types) protected override void DisposeSnapshot(Registration[] snapshot) => DisposeExtensions(snapshot.Select(static registration => registration.drawer)); + internal IInspectorAttributeDrawer? Resolve(Type attributeType) + { + Registration? best = null; + int bestDistance = int.MaxValue; + foreach (Registration registration in current) + { + if (!DrawerTypeUtility.TryGetDistance( + attributeType, + registration.targetType, + registration.useForChildren, + out int distance + )) { + continue; + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { + best = registration; + bestDistance = distance; + } + } + return best?.drawer; + } + private IInspectorAttributeDrawer CreateDrawer( Type drawerType, TypeCacheSnapshot types ) { ConstructorInfo[] constructors = drawerType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1) { throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' must declare exactly one constructor."); + $"Inspector attribute drawer '{drawerType.FullName}' must declare exactly one constructor." + ); } ParameterInfo[] parameters = constructors[0].GetParameters(); var arguments = new object?[parameters.Length]; @@ -204,33 +232,20 @@ TypeCacheSnapshot types { 1 => matches[0], 0 => throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' requests unavailable service " + - $"'{parameterType.FullName}'."), + $"Inspector attribute drawer '{drawerType.FullName}' requests unavailable service " + + $"'{parameterType.FullName}'." + ), _ => throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' requests ambiguous service " + - $"'{parameterType.FullName}'.") + $"Inspector attribute drawer '{drawerType.FullName}' requests ambiguous service " + + $"'{parameterType.FullName}'." + ) }; } return constructors[0].Invoke(arguments) as IInspectorAttributeDrawer ?? throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' does not implement " + - $"'{typeof(IInspectorAttributeDrawer).FullName}'."); - } - } - - private static void EnsureNoConflict( - IReadOnlyList registrations, - InspectorAttributeDrawerAttribute attribute, - Type drawerType - ) { - foreach (Registration existing in registrations) - { - if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) - { - throw new InvalidOperationException( - $"Inspector attribute drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); - } + $"Inspector attribute drawer '{drawerType.FullName}' does not implement " + + $"'{typeof(IInspectorAttributeDrawer).FullName}'." + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs new file mode 100644 index 000000000..c1741eb06 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections; +using System.Globalization; +using System.Reflection; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +internal static class InspectorConditionEvaluator +{ + internal static bool Evaluate( + object? value, + InspectorCondition condition, + object? expected + ) => condition switch + { + InspectorCondition.Truthy => IsTruthy(value), + InspectorCondition.Falsy => !IsTruthy(value), + InspectorCondition.Equal => AreEqual(value, expected), + InspectorCondition.NotEqual => !AreEqual(value, expected), + InspectorCondition.Null => value is null, + InspectorCondition.NotNull => value is not null, + InspectorCondition.Assigned => IsAssigned(value), + InspectorCondition.NotAssigned => !IsAssigned(value), + _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") + }; + + private static bool IsTruthy(object? value) + => value switch + { + null => false, + bool boolean => boolean, + string text => !string.IsNullOrWhiteSpace(text), + ICollection collection => collection.Count > 0, + _ => true + }; + + private static bool IsAssigned(object? value) + { + if (value is null) + { + return false; + } + PropertyInfo? property = value + .GetType() + .GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 + ? (bool)(property.GetValue(value) ?? false) + : true; + } + + private static bool AreEqual( + object? value, + object? expected + ) { + if (Equals(value, expected)) + { + return true; + } + if (value is null || expected is null) + { + return false; + } + Type valueType = value.GetType(); + try + { + object converted = valueType.IsEnum + ? expected is string name + ? Enum.Parse(valueType, name, ignoreCase: false) + : Enum.ToObject(valueType, expected) + : Convert.ChangeType(expected, valueType, CultureInfo.InvariantCulture); + return Equals(value, converted); + } + catch (Exception exception) when (exception is ArgumentException or InvalidCastException or FormatException or OverflowException) + { + return false; + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs index 69292130d..80b6dc862 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs @@ -3,15 +3,17 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using Inno.Editor.Annotations; namespace Inno.Editor.Inspection; internal static class InspectorMemberMetadata { - private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - private static readonly ConditionalWeakTable S_MEMBERS = new(); - private static readonly ConditionalWeakTable S_ATTRIBUTES = new(); + private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Instance | BindingFlags.Public + | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + + private static readonly ConditionalWeakTable MEMBERS = new(); + private static readonly ConditionalWeakTable ATTRIBUTES = new(); internal static MemberInfo? Resolve( Type ownerType, @@ -19,14 +21,14 @@ string memberName ) { ArgumentNullException.ThrowIfNull(ownerType); ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - return S_MEMBERS.GetValue(ownerType, static type => new TypeMembers(type)).members + return MEMBERS.GetValue(ownerType, static type => new TypeMembers(type)).members .GetValueOrDefault(memberName); } internal static Attribute[] GetAttributes(MemberInfo member) { ArgumentNullException.ThrowIfNull(member); - return S_ATTRIBUTES.GetValue(member, static value => new AttributesBox(value)).attributes; + return ATTRIBUTES.GetValue(member, static value => new AttributesBox(value)).attributes; } private static Attribute[] BuildAttributes(MemberInfo member) @@ -37,10 +39,11 @@ private static Attribute[] BuildAttributes(MemberInfo member) index ) => new OrderedAttribute( attribute, - attribute is Inno.Editor.Annotations.InspectorPresentationAttribute presentation - ? presentation.order - : 0, - index)) + attribute is InspectorPresentationAttribute presentation + ? presentation.order + : 0, + index + )) .OrderBy(static value => value.order) .ThenBy(static value => value.index) .Select(static value => value.attribute) @@ -48,7 +51,10 @@ attribute is Inno.Editor.Annotations.InspectorPresentationAttribute presentation private sealed class AttributesBox { - internal AttributesBox(MemberInfo member) => attributes = BuildAttributes(member); + internal AttributesBox(MemberInfo member) + { + this.attributes = BuildAttributes(member); + } internal Attribute[] attributes { get; } } @@ -59,17 +65,21 @@ internal TypeMembers(Type runtimeType) { var hierarchy = new Stack(); for (Type? type = runtimeType; type is not null && type != typeof(object); type = type.BaseType) + { hierarchy.Push(type); + } var result = new Dictionary(StringComparer.Ordinal); while (hierarchy.Count > 0) { foreach (MemberInfo member in hierarchy.Pop().GetMembers(C_DECLARED_MEMBERS)) { if (member is FieldInfo or PropertyInfo) + { result[member.Name] = member; + } } } - members = result; + this.members = result; } internal IReadOnlyDictionary members { get; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs new file mode 100644 index 000000000..56b229fbb --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(InspectorNameAttribute))] +internal sealed class NameInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Replaces the default serialized member label. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.label = ((InspectorNameAttribute)context.attribute).name; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs new file mode 100644 index 000000000..f5db57ad9 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs @@ -0,0 +1,20 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(RangeAttribute))] +internal sealed class RangeInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Applies inclusive numeric slider bounds to the annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + RangeAttribute range = (RangeAttribute)context.attribute; + context.minimum = range.minimum; + context.maximum = range.maximum; + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs new file mode 100644 index 000000000..a9ba5be9c --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(InspectorReadOnlyAttribute))] +internal sealed class ReadOnlyInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Disables assignment for the annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.isReadOnly = true; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs new file mode 100644 index 000000000..af6b1528b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs @@ -0,0 +1,23 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(ShowIfAttribute))] +internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Hides the annotated property unless its sibling condition succeeds. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + ShowIfAttribute condition = (ShowIfAttribute)context.attribute; + context.isVisible &= InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs new file mode 100644 index 000000000..eb4d2df52 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs @@ -0,0 +1,22 @@ +using System.Numerics; +using Inno.Editor.Annotations; + +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(SpaceAttribute))] +internal sealed class SpaceInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders the requested vertical spacing before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + float height = ((SpaceAttribute)context.attribute).height; + Gui.Dummy(new Vector2(0f, height)); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs new file mode 100644 index 000000000..1dc49e67b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs @@ -0,0 +1,31 @@ +using Inno.Editor.Annotations; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(TextAttribute))] +internal sealed class TextInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders persistent explanatory text before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + string text = ((TextAttribute)context.attribute).text; + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); + try + { + EditorUI.current.widgets.WrappedText(text); + } + finally + { + Gui.PopStyleColor(); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs new file mode 100644 index 000000000..dad3f87aa --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(TooltipAttribute))] +internal sealed class TooltipInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Applies tooltip text to the annotated property row. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.tooltip = ((TooltipAttribute)context.attribute).text; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs index 561a43b2e..eab31ae9a 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs @@ -1,15 +1,17 @@ -using Inno.Editor.ImGui; using System; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [InspectionDrawer(typeof(object), useForChildren: true, priority: int.MinValue)] internal sealed class DefaultInspectionDrawer : InspectionDrawer { /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => ImGuiIcon.CircleInfo; + public override string icon => ImGuiIcon.C_CIRCLE_INFO; /// /// Binds a caller-visible label to the current inspection target. @@ -27,6 +29,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, object target ) => (target.GetType().Name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -39,7 +42,8 @@ object target protected override void DrawHeader( InspectionDrawContext context, object target - ) => Ui.Text(target.GetType().FullName ?? target.GetType().Name); + ) => Gui.Text(target.GetType().FullName ?? target.GetType().Name); + /// /// Renders the value presentation for the current editor frame. /// @@ -52,7 +56,5 @@ object target protected override void Draw( InspectionDrawContext context, object target - ) { - context.DrawProperties(); - } + ) => context.DrawProperties(); } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs new file mode 100644 index 000000000..65c23b24e --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs @@ -0,0 +1,59 @@ +using System; + +namespace Inno.Editor.Inspection; + +/// +/// Defines the runtime bridge used to render a discovered inspection drawer. +/// +public interface IInspectionDrawer +{ + /// + /// Determines whether a type-compatible selected value can be inspected by this drawer. + /// + /// + /// Selected value, never mutated by this query. + /// + /// + /// Whether this drawer accepts the value; ordinary type-only drawers accept by default. + /// + bool CanInspect(object target) => true; + + /// + /// Gets the icon glyph displayed in the Inspector target header. + /// + /// + /// The active Inspector drawing context. + /// + /// + /// The icon glyph for the current target. + /// + string GetIcon(InspectionDrawContext context); + + /// + /// Binds the target name displayed by the Inspector target header. + /// + /// + /// The active Inspector drawing context. + /// + /// + /// The current target name and a callback that accepts a requested replacement name, or + /// for the callback when the name is read-only. + /// + (string name, Action? setter) BindName(InspectionDrawContext context); + + /// + /// Draws the target-specific second header row. + /// + /// + /// The active Inspector drawing context. + /// + void DrawHeader(InspectionDrawContext context); + + /// + /// Draws the target-specific Inspector body. + /// + /// + /// The active Inspector drawing context. + /// + void Draw(InspectionDrawContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs index ea60a692c..1800bdc8f 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs @@ -1,11 +1,10 @@ using System; - -using Inno.Editor.Core; -using Inno.Editor.Interactions; -using Inno.Core.Serialization; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; +using Inno.Core.Serialization; +using Inno.Editor.Core; +using Inno.Editor.Interactions; namespace Inno.Editor.Inspection; @@ -16,6 +15,29 @@ public sealed class InspectionDrawContext { private readonly InspectionDrawerRegistry m_drawers; private readonly IReadOnlyList m_serializedProperties; + + internal InspectionDrawContext( + EditorContext editorContext, + EditorInteractions interactions, + object target, + SerializedPropertyRenderer properties, + InspectionDrawerRegistry drawers, + IReadOnlyList serializedProperties + ) { + ArgumentNullException.ThrowIfNull(editorContext); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(drawers); + ArgumentNullException.ThrowIfNull(serializedProperties); + this.editorContext = editorContext; + this.interactions = interactions; + this.target = target; + this.properties = properties; + m_drawers = drawers; + m_serializedProperties = serializedProperties; + } + /// /// Gets the shared editor context. /// @@ -49,14 +71,15 @@ public bool TryDrawInline(object target) { ArgumentNullException.ThrowIfNull(target); if (!m_drawers.TryResolveExact( - editorContext, - target, - properties, - out IInspectionDrawer? drawer, - out InspectionDrawContext? context) + editorContext, + target, + properties, + out IInspectionDrawer? drawer, + out InspectionDrawContext? context + ) || drawer is null - || context is null) - { + || context is null + ) { return false; } drawer.Draw(context); @@ -96,9 +119,10 @@ public T GetProperty(string propertyName) SerializedProperty property = RequireProperty(propertyName); object? value = property.GetValue(); return value is T typed - ? typed - : throw new InvalidOperationException( - $"Property '{propertyName}' does not contain '{typeof(T).FullName}'."); + ? typed + : throw new InvalidOperationException( + $"Property '{propertyName}' does not contain '{typeof(T).FullName}'." + ); } /// @@ -110,11 +134,7 @@ public T GetProperty(string propertyName) public void DrawProperty(string propertyName) { SerializedProperty property = RequireProperty(propertyName); - properties.Draw( - editorContext, - target, - $"inline.{RuntimeHelpers.GetHashCode(target)}", - property); + properties.Draw(editorContext, target, $"inline.{RuntimeHelpers.GetHashCode(target)}", property); } /// @@ -127,18 +147,10 @@ public void DrawProperty(string propertyName) /// public void DrawProperties() { - string ownerPath = string.Concat( - "inspection.", - target.GetType().FullName ?? target.GetType().Name, - ".", - RuntimeHelpers.GetHashCode(target).ToString("x8")); + string ownerPath = $"inspection.{target.GetType().FullName ?? target.GetType().Name}.{RuntimeHelpers.GetHashCode(target):x8}"; for (int index = 0; index < m_serializedProperties.Count; index++) { - properties.Draw( - editorContext, - target, - ownerPath, - m_serializedProperties[index]); + properties.Draw(editorContext, target, ownerPath, m_serializedProperties[index]); } } @@ -147,24 +159,8 @@ private SerializedProperty RequireProperty(string propertyName) ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); return m_serializedProperties.FirstOrDefault(property => string.Equals(property.name, propertyName, StringComparison.Ordinal)) - ?? throw new InvalidOperationException( - $"Target '{target.GetType().FullName}' has no visible serialized property '{propertyName}'."); - } - - internal InspectionDrawContext( - EditorContext editorContext, - EditorInteractions interactions, - object target, - SerializedPropertyRenderer properties, - InspectionDrawerRegistry drawers, - IReadOnlyList serializedProperties - ) { - this.editorContext = editorContext ?? throw new ArgumentNullException(nameof(editorContext)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - this.target = target ?? throw new ArgumentNullException(nameof(target)); - this.properties = properties ?? throw new ArgumentNullException(nameof(properties)); - m_drawers = drawers ?? throw new ArgumentNullException(nameof(drawers)); - m_serializedProperties = serializedProperties - ?? throw new ArgumentNullException(nameof(serializedProperties)); + ?? throw new InvalidOperationException( + $"Target '{target.GetType().FullName}' has no visible serialized property '{propertyName}'." + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs index 2a7e99f01..06723ce0e 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs @@ -16,6 +16,17 @@ public abstract class InspectionDrawer : IInspectionDrawer /// public abstract string icon { get; } + bool IInspectionDrawer.CanInspect(object target) => target is TTarget value && CanInspect(value); + + string IInspectionDrawer.GetIcon(InspectionDrawContext context) => GetIcon(context, GetTarget(context)); + + (string name, Action? setter) IInspectionDrawer.BindName(InspectionDrawContext context) + => BindName(context, GetTarget(context)); + + void IInspectionDrawer.DrawHeader(InspectionDrawContext context) => DrawHeader(context, GetTarget(context)); + + void IInspectionDrawer.Draw(InspectionDrawContext context) => Draw(context, GetTarget(context)); + /// /// Determines whether this drawer handles the selected value, in addition to its registered type. /// @@ -27,8 +38,6 @@ public abstract class InspectionDrawer : IInspectionDrawer /// protected virtual bool CanInspect(TTarget target) => true; - bool IInspectionDrawer.CanInspect(object target) => target is TTarget value && CanInspect(value); - /// /// Binds the name displayed in the first row of the Inspector target header. /// @@ -80,8 +89,7 @@ TTarget target protected virtual void DrawHeader( InspectionDrawContext context, TTarget target - ) { - } + ) {} /// /// Draws the target-specific Inspector body below the shared target header. @@ -97,80 +105,12 @@ protected abstract void Draw( TTarget target ); - string IInspectionDrawer.GetIcon(InspectionDrawContext context) - => GetIcon(context, GetTarget(context)); - - (string name, Action? setter) IInspectionDrawer.BindName( - InspectionDrawContext context) - => BindName(context, GetTarget(context)); - - void IInspectionDrawer.DrawHeader(InspectionDrawContext context) - => DrawHeader(context, GetTarget(context)); - - void IInspectionDrawer.Draw(InspectionDrawContext context) - => Draw(context, GetTarget(context)); - private static TTarget GetTarget(InspectionDrawContext context) { ArgumentNullException.ThrowIfNull(context); return context.target as TTarget ?? throw new InvalidOperationException( - $"Inspector drawer for '{typeof(TTarget).FullName}' cannot draw target " + - $"'{context.target.GetType().FullName}'."); + $"Inspector drawer for '{typeof(TTarget).FullName}' cannot draw target " + + $"'{context.target.GetType().FullName}'." + ); } } - -/// -/// Defines the runtime bridge used to render a discovered inspection drawer. -/// -public interface IInspectionDrawer -{ - /// - /// Determines whether a type-compatible selected value can be inspected by this drawer. - /// - /// - /// Selected value, never mutated by this query. - /// - /// - /// Whether this drawer accepts the value; ordinary type-only drawers accept by default. - /// - bool CanInspect(object target) => true; - - /// - /// Gets the icon glyph displayed in the Inspector target header. - /// - /// - /// The active Inspector drawing context. - /// - /// - /// The icon glyph for the current target. - /// - string GetIcon(InspectionDrawContext context); - - /// - /// Binds the target name displayed by the Inspector target header. - /// - /// - /// The active Inspector drawing context. - /// - /// - /// The current target name and a callback that accepts a requested replacement name, or - /// for the callback when the name is read-only. - /// - (string name, Action? setter) BindName(InspectionDrawContext context); - - /// - /// Draws the target-specific second header row. - /// - /// - /// The active Inspector drawing context. - /// - void DrawHeader(InspectionDrawContext context); - - /// - /// Draws the target-specific Inspector body. - /// - /// - /// The active Inspector drawing context. - /// - void Draw(InspectionDrawContext context); -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerAttribute.cs index 0b311618b..5374dafb9 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerAttribute.cs @@ -8,26 +8,6 @@ namespace Inno.Editor.Inspection; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class InspectionDrawerAttribute : Attribute { - /// - /// Gets the selected target type handled by the drawer. - /// - public Type targetType { get; } - - /// - /// Gets whether derived target types are accepted. - /// - public bool useForChildren { get; } - - /// - /// Gets the tie-breaking registration priority. - /// - public int priority { get; } - - /// - /// Gets whether CanInspect selects a subset of targets, allowing peer conditional registrations at the same priority. - /// - public bool conditional { get; } - /// /// Creates an inspector drawer registration. /// @@ -52,9 +32,30 @@ public InspectionDrawerAttribute( int priority = 0, bool conditional = false ) { - this.targetType = targetType ?? throw new ArgumentNullException(nameof(targetType)); + ArgumentNullException.ThrowIfNull(targetType); + this.targetType = targetType; this.useForChildren = useForChildren; this.priority = priority; this.conditional = conditional; } + + /// + /// Gets the selected target type handled by the drawer. + /// + public Type targetType { get; } + + /// + /// Gets whether derived target types are accepted. + /// + public bool useForChildren { get; } + + /// + /// Gets the tie-breaking registration priority. + /// + public int priority { get; } + + /// + /// Gets whether CanInspect selects a subset of targets, allowing peer conditional registrations at the same priority. + /// + public bool conditional { get; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs index b6707f32c..a8ab16341 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; +using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Editor.Inspection; @@ -44,8 +43,9 @@ public InspectionDrawerRegistry( TypeCatalog types, SerializationRegistry serialization ) { + ArgumentNullException.ThrowIfNull(serialization); m_registry = new InspectionTypeRegistry(interactions, factory, types); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + m_serialization = serialization; } /// @@ -95,7 +95,8 @@ out InspectionDrawContext? context target, renderer, this, - GetProperties(target)); + GetProperties(target) + ); return true; } @@ -146,74 +147,56 @@ out InspectionDrawContext? context target, renderer, this, - GetProperties(target)); + GetProperties(target) + ); return true; } - private IReadOnlyList GetProperties(object target) - => target is ISerializable serializable - ? m_serialization.GetProperties(serializable) - : Array.Empty(); - /// /// Releases every active drawer snapshot and unregisters the registry from type refreshes. /// public void Dispose() => m_registry.Dispose(); + private IReadOnlyList GetProperties(object target) + => target is ISerializable serializable + ? m_serialization.GetProperties(serializable) + : []; + + private static void EnsureNoConflict( + IReadOnlyList registrations, + InspectionDrawerAttribute attribute, + Type drawerType + ) { + foreach (Registration existing in registrations) + { + if (existing.targetType == attribute.targetType && existing.priority == attribute.priority + && (existing.drawerType == drawerType || !existing.conditional || !attribute.conditional) + ) { + throw new InvalidOperationException( + $"Inspector drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); + } + } + } + private sealed class InspectionTypeRegistry : TypeRegistry { private readonly InspectionDrawerFactory m_factory; - internal EditorInteractions interactions { get; } - internal InspectionTypeRegistry( EditorInteractions interactions, InspectionDrawerFactory factory, TypeCatalog types - ) - : base(types) + ) : base(types) { - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_factory = factory ?? throw new ArgumentNullException(nameof(factory)); - } - - internal IInspectionDrawer? Resolve( - object target, - bool exactOnly = false - ) { - Type targetType = target.GetType(); - Registration? best = null; - Registration? ambiguous = null; - int bestDistance = int.MaxValue; - foreach (Registration registration in current) - { - if (exactOnly && registration.targetType != targetType) - continue; - if (!DrawerTypeUtility.TryGetDistance( - targetType, - registration.targetType, - registration.useForChildren, - out int distance)) - continue; - if (!registration.drawer.CanInspect(target)) - continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) - { - best = registration; - bestDistance = distance; - ambiguous = null; - } - else if (distance == bestDistance && registration.priority == best.priority - && registration.drawerType != best.drawerType) - ambiguous = registration; - } - if (ambiguous is not null) - throw new InvalidOperationException($"Inspector drawers '{best!.drawerType.FullName}' and '{ambiguous.drawerType.FullName}' both accept '{targetType.FullName}' at equal specificity and priority."); - return best?.drawer; + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(factory); + this.interactions = interactions; + m_factory = factory; } - internal IInspectionDrawer? ResolveExact(object target) => Resolve(target, exactOnly: true); + internal EditorInteractions interactions { get; } /// /// Builds a validated result from the current immutable input snapshot. @@ -227,33 +210,37 @@ TypeCatalog types protected override Registration[] Build(TypeCacheSnapshot types) { var drawers = new Dictionary(); - var registrations = new List(); + List registrations = []; foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IInspectionDrawer drawer = drawers.TryGetValue(drawerType, out IInspectionDrawer? existing) - ? existing - : OwnCandidateExtension(m_factory(drawerType)); + ? existing + : OwnCandidateExtension(m_factory(drawerType)); if (!drawerType.IsInstanceOfType(drawer)) { throw new InvalidOperationException( - $"Inspection drawer factory returned '{drawer.GetType().FullName}' for " + - $"'{drawerType.FullName}'."); + $"Inspection drawer factory returned '{drawer.GetType().FullName}' for " + + $"'{drawerType.FullName}'." + ); } drawers[drawerType] = drawer; foreach (InspectionDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - attribute.conditional, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + attribute.conditional, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -267,23 +254,56 @@ protected override Registration[] Build(TypeCacheSnapshot types) /// protected override void DisposeSnapshot(Registration[] snapshot) => DisposeExtensions(snapshot.Select(static registration => registration.drawer)); - } - private static void EnsureNoConflict( - IReadOnlyList registrations, - InspectionDrawerAttribute attribute, - Type drawerType - ) { - foreach (Registration existing in registrations) - { - if (existing.targetType == attribute.targetType && existing.priority == attribute.priority - && (existing.drawerType == drawerType || !existing.conditional || !attribute.conditional)) + internal IInspectionDrawer? Resolve( + object target, + bool exactOnly = false + ) { + Type targetType = target.GetType(); + Registration? best = null; + Registration? ambiguous = null; + int bestDistance = int.MaxValue; + foreach (Registration registration in current) + { + if (exactOnly && registration.targetType != targetType) + { + continue; + } + if (!DrawerTypeUtility.TryGetDistance( + targetType, + registration.targetType, + registration.useForChildren, + out int distance + )) { + continue; + } + if (!registration.drawer.CanInspect(target)) + { + continue; + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { + best = registration; + bestDistance = distance; + ambiguous = null; + } + else if (distance == bestDistance && registration.priority == best.priority + && registration.drawerType != best.drawerType + ) { + ambiguous = registration; + } + } + if (ambiguous is not null) { throw new InvalidOperationException( - $"Inspector drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); + $"Inspector drawers '{best!.drawerType.FullName}' and '{ambiguous.drawerType.FullName}' both accept '{targetType.FullName}' at equal specificity and priority." + ); } + return best?.drawer; } + + internal IInspectionDrawer? ResolveExact(object target) => Resolve(target, exactOnly: true); } private sealed record Registration( diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs index a81860133..075744195 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Inspection; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Inspection", "Inno.Editor.Inspection", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(InspectionDrawer<>), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs index 8040d4c5c..6cfac74d2 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs @@ -1,6 +1,7 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(bool))] internal sealed class BooleanPropertyDrawer : IPropertyDrawer { diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs index 7f5fca8b7..524f1e139 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs @@ -1,13 +1,15 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Inno.Core.Serialization; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(IEnumerable<>), useForChildren: true, priority: -20)] [PropertyDrawer(typeof(IDictionary<, >), useForChildren: true, priority: 20)] [PropertyDrawer(typeof(IReadOnlyDictionary<, >), useForChildren: true, priority: 20)] @@ -33,7 +35,7 @@ public void Draw(PropertyDrawContext context) return; } - Ui.Text($"Unsupported collection: {context.propertyType.Name}"); + Gui.Text($"Unsupported collection: {context.propertyType.Name}"); } private static void DrawSequence( @@ -41,12 +43,12 @@ private static void DrawSequence( Type elementType ) { List values = EditorCollectionUtility.EnumerateSequence(context.GetValue()); - if (!Ui.TreeNode($"Count: {values.Count}##{context.path}_sequence", (ImGuiTreeNodeFlags.SpanAvailWidth))) + if (!Gui.TreeNode($"Count: {values.Count}##{context.path}_sequence", (ImGuiTreeNodeFlags.SpanAvailWidth))) { return; } - if (!context.isReadOnly && Ui.SmallButton($"+##{context.path}_add")) + if (!context.isReadOnly && Gui.SmallButton($"+##{context.path}_add")) { values.Add(CreateDefault(elementType)); context.SetValue(EditorCollectionUtility.BuildSequence(context.propertyType, elementType, values)); @@ -60,15 +62,20 @@ Type elementType break; } - context.DrawChild($"Element {index}", elementType, () => EditorCollectionUtility.EnumerateSequence(context.GetValue())[index], value => - { - List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); - updated[index] = value; - context.SetValue(EditorCollectionUtility.BuildSequence(context.propertyType, elementType, updated)); - }); + context.DrawChild( + $"Element {index}", + elementType, + () => EditorCollectionUtility.EnumerateSequence(context.GetValue())[index], + value => + { + List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); + updated[index] = value; + context.SetValue(EditorCollectionUtility.BuildSequence(context.propertyType, elementType, updated)); + } + ); } - Ui.TreePop(); + Gui.TreePop(); } private static bool DrawSequenceActions( @@ -78,7 +85,7 @@ private static bool DrawSequenceActions( int count ) { bool changed = false; - if (Ui.SmallButton($"Up##{context.path}_{index}_up") && index > 0) + if (Gui.SmallButton($"Up##{context.path}_{index}_up") && index > 0) { List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); (updated[index - 1], updated[index]) = (updated[index], updated[index - 1]); @@ -86,8 +93,8 @@ int count changed = true; } - Ui.SameLine(0f, -1f); - if (Ui.SmallButton($"Down##{context.path}_{index}_down") && index < count - 1) + Gui.SameLine(0f, -1f); + if (Gui.SmallButton($"Down##{context.path}_{index}_down") && index < count - 1) { List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); (updated[index + 1], updated[index]) = (updated[index], updated[index + 1]); @@ -95,8 +102,8 @@ int count changed = true; } - Ui.SameLine(0f, -1f); - if (Ui.SmallButton($"Remove##{context.path}_{index}_remove")) + Gui.SameLine(0f, -1f); + if (Gui.SmallButton($"Remove##{context.path}_{index}_remove")) { List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); updated.RemoveAt(index); @@ -113,12 +120,12 @@ private static void DrawMap( Type valueType ) { List> entries = EnumerateMap(context); - if (!Ui.TreeNode($"Count: {entries.Count}##{context.path}_map", (ImGuiTreeNodeFlags.SpanAvailWidth))) + if (!Gui.TreeNode($"Count: {entries.Count}##{context.path}_map", (ImGuiTreeNodeFlags.SpanAvailWidth))) { return; } - if (!context.isReadOnly && Ui.SmallButton($"+##{context.path}_map_add")) + if (!context.isReadOnly && Gui.SmallButton($"+##{context.path}_map_add")) { object? defaultKey = CreateDefault(keyType); if (defaultKey is not null && !entries.Any(entry => Equals(entry.Key, defaultKey))) @@ -160,7 +167,7 @@ Type valueType updated[index] = new KeyValuePair(updated[index].Key, value); context.SetValue(EditorCollectionUtility.BuildMap(context.propertyType, keyType, valueType, updated)); }); - if (!context.isReadOnly && Ui.SmallButton($"Remove##{context.path}_{index}_map_remove")) + if (!context.isReadOnly && Gui.SmallButton($"Remove##{context.path}_{index}_map_remove")) { List> updated = EnumerateMap(context); updated.RemoveAt(index); @@ -170,13 +177,16 @@ Type valueType } } - Ui.TreePop(); + Gui.TreePop(); } private static List> EnumerateMap(PropertyDrawContext context) { - if (EditorCollectionUtility.TryEnumerateMap(context.GetValue(), context.propertyType, out List> entries)) - { + if (EditorCollectionUtility.TryEnumerateMap( + context.GetValue(), + context.propertyType, + out List> entries + )) { return entries; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs new file mode 100644 index 000000000..36a8b7a08 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; +using Inno.Editor.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; +using NumericsVector4 = System.Numerics.Vector4; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Color))] +internal sealed unsafe class ColorPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Color value = context.GetValue() is Color current ? current : default; + var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); + ImGuiColorEditFlags flags = context.hdrColor + ? ImGuiColorEditFlags.Hdr + | ImGuiColorEditFlags.Float + | ImGuiColorEditFlags.InputRgb + | ImGuiColorEditFlags.DisplayRgb + : ImGuiColorEditFlags.None; + if (Gui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) + { + context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs new file mode 100644 index 000000000..b79801a0b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs @@ -0,0 +1,31 @@ +using System; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +internal static unsafe class ComponentFieldDrawer +{ + internal static float GetWidth(int count) + { + float spacing = Gui.GetLayout().itemSpacing.X; + return MathF.Max(1f, (Gui.GetContentRegionAvailable().X - spacing * (count - 1)) / count); + } + + internal static bool Float( + string path, + string label, + ref float value, + float width + ) => EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); + + internal static bool Int( + string path, + string label, + ref int value, + float width + ) => EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); + + internal static void Next() => Gui.SameLine(0f, -1f); +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs index 06b93e3d8..4b2fc8200 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs @@ -16,9 +16,9 @@ out int distance if (normalizedRegistered.IsGenericTypeDefinition) { - if (normalizedConcrete.IsGenericType && - normalizedConcrete.GetGenericTypeDefinition() == normalizedRegistered) - { + if (normalizedConcrete.IsGenericType + && normalizedConcrete.GetGenericTypeDefinition() == normalizedRegistered + ) { distance = 1; return true; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs index a9ef64333..8eddf4b14 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs @@ -36,9 +36,9 @@ out Type elementType } Type candidateElementType = candidate.GetGenericArguments()[0]; - if (candidateElementType.IsGenericType && - candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) - { + if (candidateElementType.IsGenericType + && candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) + ) { continue; } @@ -96,7 +96,7 @@ out Type valueType internal static List EnumerateSequence(object? sequence) { - var values = new List(); + List values = []; if (sequence is not IEnumerable enumerable) { return values; @@ -184,7 +184,8 @@ internal static object BuildSequence( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, listType, - typeof(IEnumerable<>).MakeGenericType(elementType)); + typeof(IEnumerable<>).MakeGenericType(elementType) + ); if (constructor is not null) { return constructor.Invoke([list]); @@ -199,7 +200,7 @@ internal static object BuildSequence( if (!targetType.IsAbstract && ResolveSequenceAddMethod(targetType, elementType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); for (int i = 0; i < values.Count; i++) { addMethod.Invoke(instance, [values[i]]); @@ -209,7 +210,8 @@ internal static object BuildSequence( } throw new InvalidOperationException( - $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)."); + $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)." + ); } internal static object BuildMap( @@ -231,7 +233,8 @@ internal static object BuildMap( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, pairListType, - typeof(IEnumerable<>).MakeGenericType(pairType)); + typeof(IEnumerable<>).MakeGenericType(pairType) + ); if (constructor is not null) { return constructor.Invoke([pairList]); @@ -246,7 +249,7 @@ internal static object BuildMap( if (!targetType.IsAbstract && ResolveMapAddMethod(targetType, keyType, valueType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; @@ -257,7 +260,8 @@ internal static object BuildMap( } throw new InvalidOperationException( - $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)."); + $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)." + ); } private static object BuildTypedList( @@ -282,9 +286,7 @@ private static object BuildTypedDictionary( for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; - dictionary.Add( - entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), - entry.Value); + dictionary.Add(entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), entry.Value); } return dictionary; @@ -310,7 +312,8 @@ private static object BuildTypedKeyValueList( params Type[] candidateArgumentTypes ) { ConstructorInfo[] constructors = targetType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); @@ -334,15 +337,14 @@ params Type[] candidateArgumentTypes private static MethodInfo? FindFactory( Type targetType, Type argumentType - ) { - return targetType - .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => - (method.Name == "CreateRange" || method.Name == "Create") && - targetType.IsAssignableFrom(method.ReturnType) && - method.GetParameters().Length == 1 && - method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType)); - } + ) => targetType + .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); private static MethodInfo? ResolveSequenceAddMethod( Type targetType, @@ -353,7 +355,8 @@ Type elementType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [elementType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -361,8 +364,8 @@ Type elementType Type collectionInterface = typeof(ICollection<>).MakeGenericType(elementType); return collectionInterface.IsAssignableFrom(targetType) - ? collectionInterface.GetMethod("Add", [elementType]) - : null; + ? collectionInterface.GetMethod("Add", [elementType]) + : null; } private static MethodInfo? ResolveMapAddMethod( @@ -375,7 +378,8 @@ Type valueType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [keyType, valueType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -383,8 +387,8 @@ Type valueType Type dictionaryInterface = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); return dictionaryInterface.IsAssignableFrom(targetType) - ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) - : null; + ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) + : null; } private static IEnumerable EnumerateSelfAndInterfaces(Type type) diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs index e6da674b5..98b099fcd 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs @@ -1,10 +1,12 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Enum), useForChildren: true, priority: 100)] internal sealed class EnumPropertyDrawer : IPropertyDrawer { @@ -35,7 +37,7 @@ public void Draw(PropertyDrawContext context) { object candidate = values.GetValue(i)!; string name = Enum.GetName(enumType, candidate) ?? candidate.ToString()!; - if (Ui.Selectable(name, Equals(candidate, value))) + if (Gui.Selectable(name, Equals(candidate, value))) { context.SetValue(candidate); } @@ -63,7 +65,7 @@ object value ulong candidateBits = ToBits(enumType, candidate); bool selected = candidateBits == 0 ? currentBits == 0 : (currentBits & candidateBits) == candidateBits; string name = Enum.GetName(enumType, candidate) ?? candidate.ToString()!; - if (!Ui.Selectable(name, selected, (ImGuiSelectableFlags.NoAutoClosePopups))) + if (!Gui.Selectable(name, selected, (ImGuiSelectableFlags.NoAutoClosePopups))) { continue; } @@ -90,6 +92,7 @@ object value TypeCode.UInt16 => Convert.ToUInt16(value), TypeCode.UInt32 => Convert.ToUInt32(value), TypeCode.UInt64 => Convert.ToUInt64(value), - _ => throw new InvalidOperationException($"Unsupported enum underlying type '{underlyingType.FullName}'.")}; + _ => throw new InvalidOperationException($"Unsupported enum underlying type '{underlyingType.FullName}'.") + }; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs index 3ffb93f87..51bd6ab2f 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs @@ -1,13 +1,16 @@ -using Inno.Editor.ImGui; using System; +using Inno.Editor.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Guid))] internal sealed class GuidPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 64; private const string C_TEXT_STATE = "guid"; + /// /// Renders the value presentation for the current editor frame. /// @@ -18,8 +21,9 @@ public void Draw(PropertyDrawContext context) { Guid value = context.GetValue() is Guid current ? current : Guid.Empty; string text = context.TryGetTextState(C_TEXT_STATE, out string? editing) ? editing! : value.ToString("D"); - if (EditorImGui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue) && Guid.TryParse(text, out Guid parsed)) - { + if (EditorImGui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue) + && Guid.TryParse(text, out Guid parsed) + ) { context.SetValue(parsed); context.ClearTextState(C_TEXT_STATE); return; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs index 052087445..379ebb901 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Inspection; + /// /// Applies one root serialized-property mutation through the history mechanism owned by a feature. /// diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs deleted file mode 100644 index 8a3b1b51e..000000000 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs +++ /dev/null @@ -1,281 +0,0 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; -using Inno.Core.Mathematics; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; -using NumericsVector4 = System.Numerics.Vector4; - -namespace Inno.Editor.Inspection; -internal static unsafe class ComponentFieldDrawer -{ - internal static float GetWidth(int count) - { - float spacing = Ui.GetLayout().itemSpacing.X; - return MathF.Max(1f, (Ui.GetContentRegionAvailable().X - spacing * (count - 1)) / count); - } - - internal static bool Float( - string path, - string label, - ref float value, - float width - ) { - return EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); - } - - internal static bool Int( - string path, - string label, - ref int value, - float width - ) { - return EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); - } - - internal static void Next() => Ui.SameLine(0f, -1f); -} - -[PropertyDrawer(typeof(Vector2))] -internal sealed unsafe class Vector2PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector2 value = context.GetValue() is Vector2 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(2); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - } -} - -[PropertyDrawer(typeof(Vector3))] -internal sealed unsafe class Vector3PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector3 value = context.GetValue() is Vector3 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) - context.SetValue(value, "z"); - } -} - -[PropertyDrawer(typeof(Vector4))] -internal sealed unsafe class Vector4PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector4 value = context.GetValue() is Vector4 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) - context.SetValue(value, "z"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "W", ref value.w, width)) - context.SetValue(value, "w"); - } -} - -[PropertyDrawer(typeof(Vector2Int))] -internal sealed unsafe class Vector2IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector2Int value = context.GetValue() is Vector2Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(2); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - } -} - -[PropertyDrawer(typeof(Vector3Int))] -internal sealed unsafe class Vector3IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector3Int value = context.GetValue() is Vector3Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) - context.SetValue(value, "z"); - } -} - -[PropertyDrawer(typeof(Vector4Int))] -internal sealed unsafe class Vector4IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector4Int value = context.GetValue() is Vector4Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) - context.SetValue(value, "z"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "W", ref value.w, width)) - context.SetValue(value, "w"); - } -} - -[PropertyDrawer(typeof(Rect))] -internal sealed unsafe class RectPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Rect value = context.GetValue() is Rect current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "W", ref value.width, width)) - context.SetValue(value, "width"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "H", ref value.height, width)) - context.SetValue(value, "height"); - } -} - -[PropertyDrawer(typeof(RectInt))] -internal sealed unsafe class RectIntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - RectInt value = context.GetValue() is RectInt current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - context.SetValue(value, "x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - context.SetValue(value, "y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "W", ref value.width, width)) - context.SetValue(value, "width"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "H", ref value.height, width)) - context.SetValue(value, "height"); - } -} - -[PropertyDrawer(typeof(Color))] -internal sealed unsafe class ColorPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Color value = context.GetValue() is Color current ? current : default; - var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); - var flags = context.hdrColor ? Inno.Editor.ImGui.ImGuiColorEditFlags.Hdr | Inno.Editor.ImGui.ImGuiColorEditFlags.Float | Inno.Editor.ImGui.ImGuiColorEditFlags.InputRgb | Inno.Editor.ImGui.ImGuiColorEditFlags.DisplayRgb : Inno.Editor.ImGui.ImGuiColorEditFlags.None; - if (Ui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) - { - context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); - } - } -} - -[PropertyDrawer(typeof(Quaternion))] -internal sealed unsafe class QuaternionPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Quaternion value = context.GetValue() is Quaternion current ? current : Quaternion.identity; - Vector3 eulerDegrees = value.ToEulerAnglesXYZDegrees(); - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Float(context.path, "X", ref eulerDegrees.x, width)) - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.x"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref eulerDegrees.y, width)) - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.y"); - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref eulerDegrees.z, width)) - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.z"); - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs index 950b3f7c9..d905d2c8c 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs @@ -1,8 +1,10 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Nullable<>))] internal sealed class NullablePropertyDrawer : IPropertyDrawer { @@ -14,7 +16,8 @@ internal sealed class NullablePropertyDrawer : IPropertyDrawer /// public void Draw(PropertyDrawContext context) { - Type underlyingType = Nullable.GetUnderlyingType(context.propertyType) ?? throw new InvalidOperationException("Nullable drawer requires a nullable property type."); + Type underlyingType = Nullable.GetUnderlyingType(context.propertyType) + ?? throw new InvalidOperationException("Nullable drawer requires a nullable property type."); object? value = context.GetValue(); bool hasValue = value is not null; bool previousHasValue = hasValue; @@ -27,12 +30,12 @@ public void Draw(PropertyDrawContext context) if (!hasValue) { - Ui.SameLine(0f, -1f); - Ui.Text("Null"); + Gui.SameLine(0f, -1f); + Gui.Text("Null"); return; } - Ui.SameLine(0f, -1f); + Gui.SameLine(0f, -1f); context.DrawInlineChild("Value", underlyingType, context.GetValue, value => context.SetValue(value)); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs index c2feafdc9..00a803529 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs @@ -1,10 +1,12 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Globalization; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(byte))] [PropertyDrawer(typeof(sbyte))] [PropertyDrawer(typeof(short))] @@ -20,6 +22,7 @@ internal sealed class NumericPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 128; private const string C_TEXT_STATE = "numeric"; + /// /// Renders the value presentation for the current editor frame. /// @@ -34,20 +37,14 @@ public void Draw(PropertyDrawContext context) { int value = rawValue is int current ? current : 0; bool changed = context.minimum is double minimum - && context.maximum is double maximum ? Ui.SliderInt( - $"##{context.path}", - ref value, - (int)Math.Clamp(Math.Ceiling(minimum), int.MinValue, int.MaxValue), - (int)Math.Clamp(Math.Floor(maximum), int.MinValue, int.MaxValue) - ) : Ui.DragInt( - $"##{context.path}", - ref value, - 1f, - 0, - 0, - "%d", - 0 - ); + && context.maximum is double maximum + ? Gui.SliderInt( + $"##{context.path}", + ref value, + (int)Math.Clamp(Math.Ceiling(minimum), int.MinValue, int.MaxValue), + (int)Math.Clamp(Math.Floor(maximum), int.MinValue, int.MaxValue) + ) + : Gui.DragInt($"##{context.path}", ref value, 1f, 0, 0, "%d", 0); if (changed) { context.SetValue(value); @@ -60,16 +57,14 @@ public void Draw(PropertyDrawContext context) { float value = rawValue is float current ? current : 0f; bool changed = context.minimum is double minimum - && context.maximum is double maximum ? EditorUI.current.widgets.CompactSliderFloat( - $"##{context.path}", - ref value, - (float)minimum, - (float)maximum - ) : EditorUI.current.widgets.CompactDragFloat( - $"##{context.path}", - ref value, - 0.1f - ); + && context.maximum is double maximum + ? EditorUI.current.widgets.CompactSliderFloat( + $"##{context.path}", + ref value, + (float)minimum, + (float)maximum + ) + : EditorUI.current.widgets.CompactDragFloat($"##{context.path}", ref value, 0.1f); if (changed) { context.SetValue(value); @@ -80,7 +75,7 @@ public void Draw(PropertyDrawContext context) _ = context.TryGetTextState(C_TEXT_STATE, out string? text); text ??= Convert.ToString(rawValue, CultureInfo.InvariantCulture) ?? "0"; - if (Ui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue)) + if (Gui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue)) { if (TryConvert(text, type, out object? converted)) { @@ -118,7 +113,9 @@ out object? value double? maximum ) { if (value is null || minimum is null || maximum is null) + { return value; + } double numeric = Convert.ToDouble(value, CultureInfo.InvariantCulture); double clamped = Math.Clamp(numeric, minimum.Value, maximum.Value); return Convert.ChangeType(clamped, type, CultureInfo.InvariantCulture); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs index 7e9f742dd..7e5cbfece 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs @@ -2,10 +2,11 @@ using System.Reflection; using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; namespace Inno.Editor.Inspection; + /// /// Encapsulates one editable property path and its drawing services. /// @@ -18,92 +19,107 @@ public sealed class PropertyDrawContext private readonly object m_owner; private readonly string m_rootPropertyName; private readonly bool m_isReadOnly; + + internal PropertyDrawContext( + EditorContext editorContext, + EditorInteractions interactions, + IInspectionPropertyEditService edits, + object owner, + string rootPropertyName, + string path, + string label, + Type propertyType, + PropertyVisibility visibility, + bool isReadOnly, + double? minimum, + double? maximum, + string? tooltip, + Func getter, + Action setter, + SerializedPropertyRenderer renderer, + bool hdrColor = false + ) { + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(owner); + this.editorContext = editorContext; + this.interactions = interactions; + m_edits = edits; + m_owner = owner; + m_rootPropertyName = string.IsNullOrWhiteSpace(rootPropertyName) + ? throw new ArgumentException( + "The root property name is required.", + nameof(rootPropertyName) + ) + : rootPropertyName; + this.path = path; + this.label = label; + this.propertyType = propertyType; + this.visibility = visibility; + m_isReadOnly = isReadOnly; + this.minimum = minimum; + this.maximum = maximum; + this.tooltip = tooltip; + m_getter = getter; + m_setter = setter; + m_renderer = renderer; + this.hdrColor = hdrColor; + } + /// /// Gets the shared editor context. /// public EditorContext editorContext { get; } + /// /// Gets the active editor interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the stable control path. /// public string path { get; } + /// /// Gets the display label. /// public string label { get; } + /// /// Gets the declared property type. /// public Type propertyType { get; } + /// /// Gets the serialization visibility flags. /// public PropertyVisibility visibility { get; } + /// /// Gets whether assignments are disabled. /// public bool isReadOnly => m_isReadOnly; + /// /// Gets the optional inclusive numeric lower bound supplied by Inspector metadata. /// public double? minimum { get; } + /// /// Gets the optional inclusive numeric upper bound supplied by Inspector metadata. /// public double? maximum { get; } + /// /// Gets optional hover help supplied by Inspector metadata. /// public string? tooltip { get; } + /// /// Gets whether Color values are unclamped linear floating-point channels. /// public bool hdrColor { get; } - internal object owner => m_owner; - - internal PropertyDrawContext( - EditorContext editorContext, - EditorInteractions interactions, - IInspectionPropertyEditService edits, - object owner, - string rootPropertyName, - string path, - string label, - Type propertyType, - PropertyVisibility visibility, - bool isReadOnly, - double? minimum, - double? maximum, - string? tooltip, - Func getter, - Action setter, - SerializedPropertyRenderer renderer, - bool hdrColor = false - ) { - this.editorContext = editorContext; - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); - m_owner = owner ?? throw new ArgumentNullException(nameof(owner)); - m_rootPropertyName = string.IsNullOrWhiteSpace(rootPropertyName) ? throw new ArgumentException( - "The root property name is required.", - nameof(rootPropertyName) - ) : rootPropertyName; - this.path = path; - this.label = label; - this.propertyType = propertyType; - this.visibility = visibility; - m_isReadOnly = isReadOnly; - this.minimum = minimum; - this.maximum = maximum; - this.tooltip = tooltip; - m_getter = getter; - m_setter = setter; - m_renderer = renderer; - this.hdrColor = hdrColor; - } /// /// Gets the latest value. @@ -112,6 +128,7 @@ internal PropertyDrawContext( /// The latest value returned by the serialized property's getter. /// public object? GetValue() => m_getter(); + /// /// Tries to read text-edit state scoped to this renderer, inspected owner, and property path. /// @@ -128,6 +145,7 @@ public bool TryGetTextState( string key, out string? value ) => m_renderer.TryGetTextState(m_owner, path, key, out value); + /// /// Stores text-edit state scoped to this renderer, inspected owner, and property path. /// @@ -141,6 +159,7 @@ public void SetTextState( string key, string value ) => m_renderer.SetTextState(m_owner, path, key, value); + /// /// Removes text-edit state for this renderer, inspected owner, and property path. /// @@ -148,6 +167,7 @@ string value /// Drawer-local state identity within the current property path. /// public void ClearTextState(string key) => m_renderer.ClearTextState(m_owner, path, key); + /// /// Assigns a value when the property is writable. /// @@ -162,14 +182,25 @@ public void SetValue( string? componentName = null ) { if (isReadOnly) + { return; - EditorUiSession ui = EditorUiSession.current; + } + EditorUISession ui = EditorUISession.current; if (Equals(m_getter(), value) && !ui.widgets.isMixedValue) + { return; + } ui.widgets.BeginPropertyEdit(interactions.history, path, $"Change {label}"); try { - _ = m_edits.ChangeProperty(m_owner, m_rootPropertyName, () => m_setter(value), $"Change {label}", ui.widgets.editMergeKey, componentName); + _ = m_edits.ChangeProperty( + m_owner, + m_rootPropertyName, + () => m_setter(value), + $"Change {label}", + ui.widgets.editMergeKey, + componentName + ); } catch { @@ -178,35 +209,6 @@ public void SetValue( } } - /// - /// Draws a nested value whose setter writes through this property path. - /// - /// - /// The stable child member name appended to this property path. - /// - /// - /// The declared type used to resolve a property drawer. - /// - /// - /// The callback that reads the latest child value. - /// - /// - /// The callback that writes an edited child value. - /// - /// - /// Whether the child should be presented without assignment support. - /// - public void DrawChild( - string childName, - Type childType, - Func getter, - Action setter, - bool readOnly = false - ) { - PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; - m_renderer.Draw(editorContext, m_owner, m_owner, null, null, m_rootPropertyName, $"{path}.{childName}", childName, childType, childVisibility, getter, setter, m_edits); - } - /// /// Draws a nested serialized property. /// @@ -214,6 +216,7 @@ public void DrawChild( /// Nested property. /// public void DrawChild(SerializedProperty property) => DrawChild(GetValue() ?? m_owner, property); + /// /// Draws a nested serialized property with presentation metadata resolved from its immediate owner. /// @@ -246,26 +249,41 @@ SerializedProperty property ); } - internal void DrawChildMember( - object metadataOwner, - MemberInfo member, + /// + /// Draws a nested value whose setter writes through this property path. + /// + /// + /// The stable child member name appended to this property path. + /// + /// + /// The declared type used to resolve a property drawer. + /// + /// + /// The callback that reads the latest child value. + /// + /// + /// The callback that writes an edited child value. + /// + /// + /// Whether the child should be presented without assignment support. + /// + public void DrawChild( + string childName, Type childType, Func getter, Action setter, - bool readOnly + bool readOnly = false ) { - ArgumentNullException.ThrowIfNull(metadataOwner); - ArgumentNullException.ThrowIfNull(member); PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; m_renderer.Draw( editorContext, m_owner, - metadataOwner, - member, + m_owner, + null, null, m_rootPropertyName, - $"{path}.{member.Name}", - member.Name, + $"{path}.{childName}", + childName, childType, childVisibility, getter, @@ -300,6 +318,49 @@ public void DrawInlineChild( bool readOnly = false ) { PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; - m_renderer.DrawInline(editorContext, m_owner, m_owner, null, m_rootPropertyName, $"{path}.{childName}", childName, childType, childVisibility, getter, setter, m_edits); + m_renderer.DrawInline( + editorContext, + m_owner, + m_owner, + null, + m_rootPropertyName, + $"{path}.{childName}", + childName, + childType, + childVisibility, + getter, + setter, + m_edits + ); + } + + internal object owner => m_owner; + + internal void DrawChildMember( + object metadataOwner, + MemberInfo member, + Type childType, + Func getter, + Action setter, + bool readOnly + ) { + ArgumentNullException.ThrowIfNull(metadataOwner); + ArgumentNullException.ThrowIfNull(member); + PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; + m_renderer.Draw( + editorContext, + m_owner, + metadataOwner, + member, + null, + m_rootPropertyName, + $"{path}.{member.Name}", + member.Name, + childType, + childVisibility, + getter, + setter, + m_edits + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerAttribute.cs index 2dfde0a9f..16912919c 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerAttribute.cs @@ -8,21 +8,6 @@ namespace Inno.Editor.Inspection; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class PropertyDrawerAttribute : Attribute { - /// - /// Gets the declared property type handled by the drawer. - /// - public Type targetType { get; } - - /// - /// Gets whether assignable derived types are accepted. - /// - public bool useForChildren { get; } - - /// - /// Gets the tie-breaking registration priority. - /// - public int priority { get; } - /// /// Creates a property drawer registration. /// @@ -43,8 +28,24 @@ public PropertyDrawerAttribute( bool useForChildren = false, int priority = 0 ) { - this.targetType = targetType ?? throw new ArgumentNullException(nameof(targetType)); + ArgumentNullException.ThrowIfNull(targetType); + this.targetType = targetType; this.useForChildren = useForChildren; this.priority = priority; } + + /// + /// Gets the declared property type handled by the drawer. + /// + public Type targetType { get; } + + /// + /// Gets whether assignable derived types are accepted. + /// + public bool useForChildren { get; } + + /// + /// Gets the tie-breaking registration priority. + /// + public int priority { get; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs index 47aec1593..e93633156 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Inspection; @@ -66,6 +65,67 @@ public IPropertyDrawer Resolve(Type propertyType) /// public void Dispose() => m_registry.Dispose(); + private static IPropertyDrawer CreateDrawer( + Type type, + EditorInteractions interactions, + TypeCacheSnapshot types, + SerializationRegistry serialization, + IReadOnlyList drawerServices + ) { + ConstructorInfo[] constructors = type.GetConstructors( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); + if (constructors.Length != 1) + { + throw new InvalidOperationException($"Property drawer '{type.FullName}' must declare exactly one constructor."); + } + ParameterInfo[] parameters = constructors[0].GetParameters(); + var arguments = new object?[parameters.Length]; + for (int index = 0; index < parameters.Length; index++) + { + Type parameterType = parameters[index].ParameterType; + object[] matches = drawerServices + .Where(parameterType.IsInstanceOfType) + .Prepend(parameterType == typeof(TypeCacheSnapshot) ? types : null) + .Prepend(parameterType == typeof(SerializationRegistry) ? serialization : null) + .Prepend(parameterType == typeof(EditorInteractions) ? interactions : null) + .Where(static service => service is not null) + .Cast() + .Distinct(ReferenceEqualityComparer.Instance) + .ToArray(); + arguments[index] = matches.Length switch + { + 1 => matches[0], + 0 => throw new InvalidOperationException( + $"Property drawer '{type.FullName}' requests unavailable service " + + $"'{parameterType.FullName}'." + ), + _ => throw new InvalidOperationException( + $"Property drawer '{type.FullName}' requests ambiguous service " + + $"'{parameterType.FullName}'." + ) + }; + } + return (IPropertyDrawer)constructors[0].Invoke(arguments); + } + + private static void EnsureNoConflict( + IReadOnlyList registrations, + PropertyDrawerAttribute attribute, + Type drawerType + ) { + foreach (Registration existing in registrations) + { + if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) + { + throw new InvalidOperationException( + $"Property drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); + } + } + } + private sealed class PropertyTypeRegistry : TypeRegistry { private readonly EditorInteractions m_interactions; @@ -77,38 +137,19 @@ internal PropertyTypeRegistry( TypeCatalog types, SerializationRegistry serialization, IEnumerable drawerServices - ) - : base(types) + ) : base(types) { - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(serialization); + m_interactions = interactions; + m_serialization = serialization; ArgumentNullException.ThrowIfNull(drawerServices); - m_drawerServices = drawerServices.Select(static service => + m_drawerServices = drawerServices.Select(static service => ( service ?? throw new ArgumentException( "Property drawer services cannot contain null.", - nameof(drawerServices))).ToArray(); - } - - internal IPropertyDrawer Resolve(Type propertyType) - { - Registration? best = null; - int bestDistance = int.MaxValue; - foreach (Registration registration in current) - { - if (!DrawerTypeUtility.TryGetDistance( - propertyType, - registration.targetType, - registration.useForChildren, - out int distance)) - continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) - { - best = registration; - bestDistance = distance; - } - } - return best?.drawer ?? UnsupportedPropertyDrawer.instance; + nameof(drawerServices) + ) + )).ToArray(); } /// @@ -123,31 +164,37 @@ internal IPropertyDrawer Resolve(Type propertyType) protected override Registration[] Build(TypeCacheSnapshot types) { var drawers = new Dictionary(); - var registrations = new List(); + List registrations = []; foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IPropertyDrawer drawer = drawers.TryGetValue(drawerType, out IPropertyDrawer? existing) - ? existing - : OwnCandidateExtension(CreateDrawer( - drawerType, - m_interactions, - types, - m_serialization, - m_drawerServices)); + ? existing + : OwnCandidateExtension( + CreateDrawer( + drawerType, + m_interactions, + types, + m_serialization, + m_drawerServices + ) + ); drawers[drawerType] = drawer; foreach (PropertyDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -161,60 +208,29 @@ protected override Registration[] Build(TypeCacheSnapshot types) /// protected override void DisposeSnapshot(Registration[] snapshot) => DisposeExtensions(snapshot.Select(static registration => registration.drawer)); - } - - private static IPropertyDrawer CreateDrawer( - Type type, - EditorInteractions interactions, - TypeCacheSnapshot types, - SerializationRegistry serialization, - IReadOnlyList drawerServices - ) { - ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (constructors.Length != 1) - throw new InvalidOperationException($"Property drawer '{type.FullName}' must declare exactly one constructor."); - ParameterInfo[] parameters = constructors[0].GetParameters(); - object?[] arguments = new object?[parameters.Length]; - for (int index = 0; index < parameters.Length; index++) - { - Type parameterType = parameters[index].ParameterType; - object[] matches = drawerServices - .Where(parameterType.IsInstanceOfType) - .Prepend(parameterType == typeof(TypeCacheSnapshot) ? types : null) - .Prepend(parameterType == typeof(SerializationRegistry) ? serialization : null) - .Prepend(parameterType == typeof(EditorInteractions) ? interactions : null) - .Where(static service => service is not null) - .Cast() - .Distinct(ReferenceEqualityComparer.Instance) - .ToArray(); - arguments[index] = matches.Length switch - { - 1 => matches[0], - 0 => throw new InvalidOperationException( - $"Property drawer '{type.FullName}' requests unavailable service " + - $"'{parameterType.FullName}'."), - _ => throw new InvalidOperationException( - $"Property drawer '{type.FullName}' requests ambiguous service " + - $"'{parameterType.FullName}'.") - }; - } - return (IPropertyDrawer)constructors[0].Invoke(arguments); - } - private static void EnsureNoConflict( - IReadOnlyList registrations, - PropertyDrawerAttribute attribute, - Type drawerType - ) { - foreach (Registration existing in registrations) + internal IPropertyDrawer Resolve(Type propertyType) { - if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) + Registration? best = null; + int bestDistance = int.MaxValue; + foreach (Registration registration in current) { - throw new InvalidOperationException( - $"Property drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); + if (!DrawerTypeUtility.TryGetDistance( + propertyType, + registration.targetType, + registration.useForChildren, + out int distance + )) { + continue; + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { + best = registration; + bestDistance = distance; + } } + return best?.drawer ?? UnsupportedPropertyDrawer.instance; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs new file mode 100644 index 000000000..97350cacb --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs @@ -0,0 +1,34 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Quaternion))] +internal sealed unsafe class QuaternionPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Quaternion value = context.GetValue() is Quaternion current ? current : Quaternion.identity; + Vector3 eulerDegrees = value.ToEulerAnglesXYZDegrees(); + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Float(context.path, "X", ref eulerDegrees.x, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref eulerDegrees.y, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref eulerDegrees.z, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs new file mode 100644 index 000000000..b9418491f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(RectInt))] +internal sealed unsafe class RectIntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + RectInt value = context.GetValue() is RectInt current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "W", ref value.width, width)) + { + context.SetValue(value, "width"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "H", ref value.height, width)) + { + context.SetValue(value, "height"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs new file mode 100644 index 000000000..bbcaea19f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Rect))] +internal sealed unsafe class RectPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Rect value = context.GetValue() is Rect current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "W", ref value.width, width)) + { + context.SetValue(value, "width"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "H", ref value.height, width)) + { + context.SetValue(value, "height"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs index c5d365de8..d4ce9a03a 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs @@ -1,24 +1,29 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Extensibility.Types; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(ISerializable), useForChildren: true, priority: 20)] internal sealed class SerializableObjectPropertyDrawer : IPropertyDrawer { private readonly SerializationRegistry m_serialization; private readonly TypeCacheSnapshot m_types; + internal SerializableObjectPropertyDrawer( TypeCacheSnapshot types, SerializationRegistry serialization ) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + m_types = types; + m_serialization = serialization; } /// @@ -35,12 +40,12 @@ public void Draw(PropertyDrawContext context) value = context.GetValue(); if (value is not ISerializable serializable) { - Ui.Text("Null"); + Gui.Text("Null"); return; } string header = $"{value.GetType().Name}##{context.path}_foldout"; - if (!Ui.TreeNode(header, (ImGuiTreeNodeFlags.SpanAvailWidth))) + if (!Gui.TreeNode(header, (ImGuiTreeNodeFlags.SpanAvailWidth))) { return; } @@ -53,7 +58,7 @@ public void Draw(PropertyDrawContext context) context.DrawChild(serializable, properties[i]); } }); - Ui.TreePop(); + Gui.TreePop(); } private void DrawTypeSelector( @@ -66,7 +71,7 @@ private void DrawTypeSelector( return; } - if (Ui.Selectable("Null", value is null)) + if (Gui.Selectable("Null", value is null)) { context.SetValue(null); } @@ -80,7 +85,7 @@ private void DrawTypeSelector( continue; } - if (Ui.Selectable(candidate.Name, candidate == runtimeType && value is not null)) + if (Gui.Selectable(candidate.Name, candidate == runtimeType && value is not null)) { context.SetValue(Activator.CreateInstance(candidate, nonPublic: true)); } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs index 1300a96e0..b12d90657 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs @@ -1,18 +1,20 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Inno.Core.Logging; -using Inno.Scripting.Api; using Inno.Core.Serialization; using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using Inno.Scripting.Api; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Inspection; + /// /// Resolves drawers and renders serialized property paths with isolated error handling. /// @@ -25,6 +27,7 @@ public sealed class SerializedPropertyRenderer private readonly EditorInteractions m_interactions; private readonly IInspectionPropertyEditService m_edits; private readonly Logger m_logger; + /// /// Creates a serialized property renderer over one drawer registry and feature-owned edit service. /// @@ -55,10 +58,14 @@ public SerializedPropertyRenderer( IInspectionPropertyEditService edits, LogRouter logs ) { - m_drawers = drawers ?? throw new ArgumentNullException(nameof(drawers)); - m_attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); + ArgumentNullException.ThrowIfNull(drawers); + ArgumentNullException.ThrowIfNull(attributes); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(edits); + m_drawers = drawers; + m_attributes = attributes; + m_interactions = interactions; + m_edits = edits; ArgumentNullException.ThrowIfNull(logs); m_logger = logs.CreateLogger(); } @@ -259,8 +266,17 @@ SerializedProperty property bool readOnly = (property.visibility & PropertyVisibility.RuntimeSet) == 0; MemberInfo? member = InspectorMemberMetadata.Resolve(owner.GetType(), property.name); if (member is null) + { return (true, readOnly); - var context = new InspectorAttributeDrawContext(owner, member, property, property.name, property.name, readOnly); + } + var context = new InspectorAttributeDrawContext( + owner, + member, + property, + property.name, + property.name, + readOnly + ); m_attributes.Update(context, InspectorMemberMetadata.GetAttributes(member)); return (context.isVisible, context.isReadOnly); } @@ -294,14 +310,20 @@ internal void Draw( attributeContext = new InspectorAttributeDrawContext(metadataOwner, member, property, path, displayLabel, isReadOnly); m_attributes.Update(attributeContext, attributes); if (!attributeContext.isVisible) + { return; + } displayLabel = attributeContext.label; isReadOnly = attributeContext.isReadOnly; if (!beginsSection && !EditorUI.current.widgets.isSectionContentVisible) + { return; + } m_attributes.DrawBefore(attributeContext, attributes); if (!EditorUI.current.widgets.isSectionContentVisible) + { return; + } } else if (!EditorUI.current.widgets.isSectionContentVisible) { @@ -309,7 +331,9 @@ internal void Draw( } if (!beginsSection && !EditorUI.current.widgets.EnsureSection()) + { return; + } var context = new PropertyDrawContext( editorContext, m_interactions, @@ -329,9 +353,16 @@ internal void Draw( this, hdrColor ); - EditorUI.current.widgets.PropertyRow(path, context.label, () => DrawContent(context), tooltip: attributeContext?.tooltip ?? tooltip); + EditorUI.current.widgets.PropertyRow( + path, + context.label, + () => DrawContent(context), + tooltip: attributeContext?.tooltip ?? tooltip + ); if (attributeContext is not null) + { m_attributes.DrawAfter(attributeContext, attributes); + } } internal void DrawInline( @@ -369,28 +400,6 @@ internal void DrawInline( DrawContent(context); } - private void DrawContent(PropertyDrawContext context) - { - Dictionary failureStates = m_failureStates.GetOrCreateValue(context.owner); - try - { - IPropertyDrawer drawer = m_drawers.Resolve(context.propertyType); - EditorUI.current.widgets.Disabled(context.isReadOnly, () => drawer.Draw(context)); - EditorUI.current.widgets.CompletePropertyEdit(context.path); - failureStates.Remove(context.path); - } - catch (Exception exception) - { - EditorUI.current.widgets.ColoredText(EditorPalette.error, $"Error: {exception.Message}"); - string failureState = $"{exception.GetType().FullName}|{exception.Message}"; - if (!failureStates.TryGetValue(context.path, out string? previous) || !string.Equals(previous, failureState, StringComparison.Ordinal)) - { - m_logger.Write(LogLevel.Error, "Inspector failed to draw property '{0}': {1}", [context.path, exception]); - failureStates[context.path] = failureState; - } - } - } - internal bool TryGetTextState( object owner, string path, @@ -399,7 +408,8 @@ out string? value ) { ArgumentNullException.ThrowIfNull(owner); value = null; - return m_textStates.TryGetValue(owner, out Dictionary? states) && states.TryGetValue(CreateStateKey(path, key), out value); + return m_textStates.TryGetValue(owner, out Dictionary? states) + && states.TryGetValue(CreateStateKey(path, key), out value); } internal void SetTextState( @@ -420,7 +430,32 @@ string key ) { ArgumentNullException.ThrowIfNull(owner); if (m_textStates.TryGetValue(owner, out Dictionary? states)) + { states.Remove(CreateStateKey(path, key)); + } + } + + private void DrawContent(PropertyDrawContext context) + { + Dictionary failureStates = m_failureStates.GetOrCreateValue(context.owner); + try + { + IPropertyDrawer drawer = m_drawers.Resolve(context.propertyType); + EditorUI.current.widgets.Disabled(context.isReadOnly, () => drawer.Draw(context)); + EditorUI.current.widgets.CompletePropertyEdit(context.path); + failureStates.Remove(context.path); + } + catch (Exception exception) + { + EditorUI.current.widgets.ColoredText(EditorPalette.error, $"Error: {exception.Message}"); + string failureState = $"{exception.GetType().FullName}|{exception.Message}"; + if (!failureStates.TryGetValue(context.path, out string? previous) + || !string.Equals(previous, failureState, StringComparison.Ordinal) + ) { + m_logger.Write(LogLevel.Error, "Inspector failed to draw property '{0}': {1}", [context.path, exception]); + failureStates[context.path] = failureState; + } + } } private static string CreateStateKey( @@ -429,6 +464,6 @@ string key ) { ArgumentException.ThrowIfNullOrWhiteSpace(path); ArgumentException.ThrowIfNullOrWhiteSpace(key); - return string.Concat(path, "\n", key); + return $"{path}\n{key}"; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs index 83697be97..0cb6d8918 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs @@ -1,11 +1,14 @@ using Inno.Editor.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(string))] internal sealed class StringPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 1024; + /// /// Renders the value presentation for the current editor frame. /// diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs index 43b0f0361..dce06dd2b 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs @@ -1,18 +1,21 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Inno.Core.Serialization; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(ValueType), useForChildren: true, priority: -100)] internal sealed class StructPropertyDrawer : IPropertyDrawer { - private static readonly ConditionalWeakTable S_MEMBER_CACHE = new(); + private static readonly ConditionalWeakTable MEMBER_CACHE = new(); + /// /// Renders the value presentation for the current editor frame. /// @@ -25,11 +28,11 @@ public void Draw(PropertyDrawContext context) MemberInfo[] members = GetMembers(context.propertyType); if (members.Length == 0) { - Ui.Text(boxedValue.ToString() ?? context.propertyType.Name); + Gui.Text(boxedValue.ToString() ?? context.propertyType.Name); return; } - if (!Ui.TreeNode($"{context.propertyType.Name}##{context.path}", (ImGuiTreeNodeFlags.SpanAvailWidth))) + if (!Gui.TreeNode($"{context.propertyType.Name}##{context.path}", (ImGuiTreeNodeFlags.SpanAvailWidth))) { return; } @@ -41,77 +44,84 @@ public void Draw(PropertyDrawContext context) MemberInfo member = members[i]; Type memberType = GetMemberType(member); bool memberReadOnly = !CanWrite(member) || (GetVisibility(member) & PropertyVisibility.RuntimeSet) == 0; - context.DrawChildMember(context.GetValue() ?? boxedValue, member, memberType, () => GetMemberValue(member, context.GetValue() ?? boxedValue), value => + context.DrawChildMember( + context.GetValue() + ?? boxedValue, + member, + memberType, + () => GetMemberValue(member, context.GetValue() ?? boxedValue), + value => { object updated = context.GetValue() ?? Activator.CreateInstance(context.propertyType)!; SetMemberValue(member, updated, value); context.SetValue(updated); - }, memberReadOnly); + }, + memberReadOnly + ); } }); - Ui.TreePop(); + Gui.TreePop(); } private static MemberInfo[] GetMembers(Type type) - { - return S_MEMBER_CACHE.GetValue( + => MEMBER_CACHE.GetValue( type, - static value => new MembersBox(value.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(IsRuntimeVisibleMember).OrderBy(static member => member.MetadataToken).ToArray()) + static value => new MembersBox( + value + .GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(IsRuntimeVisibleMember) + .OrderBy(static member => member.MetadataToken) + .ToArray() + ) ).members; - } private static bool IsRuntimeVisibleMember(MemberInfo member) { SerializablePropertyAttribute? attribute = member.GetCustomAttribute(inherit: true); PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; if ((visibility & PropertyVisibility.RuntimeGet) == 0) + { return false; + } return member switch { FieldInfo field => !field.IsStatic && (attribute is not null || field.IsPublic && !field.IsInitOnly), PropertyInfo property => property.GetIndexParameters().Length == 0 - && (attribute is not null - || property.GetGetMethod(nonPublic: true)?.IsPublic == true - && property.GetSetMethod(nonPublic: true)?.IsPublic == true), + && (attribute is not null + || property.GetGetMethod(nonPublic: true)?.IsPublic == true + && property.GetSetMethod(nonPublic: true)?.IsPublic == true), _ => false }; } private static PropertyVisibility GetVisibility(MemberInfo member) - { - return member.GetCustomAttribute(true)?.propertyVisibility ?? PropertyVisibility.Show; - } + => member.GetCustomAttribute(true)?.propertyVisibility ?? PropertyVisibility.Show; private static Type GetMemberType(MemberInfo member) + => member switch { - return member switch - { - FieldInfo field => field.FieldType, - PropertyInfo property => property.PropertyType, - _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.")}; - } + FieldInfo field => field.FieldType, + PropertyInfo property => property.PropertyType, + _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.") + }; private static object? GetMemberValue( MemberInfo member, object target - ) { - return member switch - { - FieldInfo field => field.GetValue(target), - PropertyInfo property => property.GetValue(target), - _ => null - }; - } + ) => member switch + { + FieldInfo field => field.GetValue(target), + PropertyInfo property => property.GetValue(target), + _ => null + }; private static bool CanWrite(MemberInfo member) + => member switch { - return member switch - { - FieldInfo field => !field.IsInitOnly, - PropertyInfo property => property.GetSetMethod(true) is not null, - _ => false - }; - } + FieldInfo field => !field.IsInitOnly, + PropertyInfo property => property.GetSetMethod(true) is not null, + _ => false + }; private static void SetMemberValue( MemberInfo member, diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs index ad5daf22f..2add0e031 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs @@ -1,11 +1,11 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Editor.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.Inspection; + internal sealed class UnsupportedPropertyDrawer : IPropertyDrawer { - internal static UnsupportedPropertyDrawer instance { get; } = new(); - /// /// Renders the value presentation for the current editor frame. /// @@ -20,4 +20,6 @@ public void Draw(PropertyDrawContext context) value is null ? $"Unsupported {context.propertyType.Name} (null)" : $"Unsupported {context.propertyType.Name}: {value}" ); } + + internal static UnsupportedPropertyDrawer instance { get; } = new(); } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs new file mode 100644 index 000000000..68b063c00 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs @@ -0,0 +1,28 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector2Int))] +internal sealed unsafe class Vector2IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector2Int value = context.GetValue() is Vector2Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(2); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs new file mode 100644 index 000000000..47336cc9f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs @@ -0,0 +1,28 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector2))] +internal sealed unsafe class Vector2PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector2 value = context.GetValue() is Vector2 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(2); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs new file mode 100644 index 000000000..60c6f12c0 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector3Int))] +internal sealed unsafe class Vector3IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector3Int value = context.GetValue() is Vector3Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs new file mode 100644 index 000000000..d5ed4f2a6 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector3))] +internal sealed unsafe class Vector3PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector3 value = context.GetValue() is Vector3 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs new file mode 100644 index 000000000..7e09a74ef --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector4Int))] +internal sealed unsafe class Vector4IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector4Int value = context.GetValue() is Vector4Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "W", ref value.w, width)) + { + context.SetValue(value, "w"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs new file mode 100644 index 000000000..0dadebf62 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector4))] +internal sealed unsafe class Vector4PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector4 value = context.GetValue() is Vector4 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "W", ref value.w, width)) + { + context.SetValue(value, "w"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs index d758c28d6..010635ae7 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs @@ -1,7 +1,8 @@ -using Inno.Editor.Core; using System; +using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Defines one automatically discovered editor operation and owns its complete multi-frame lifecycle. /// @@ -11,57 +12,31 @@ public abstract class EditorAction : IDisposable private EditorInteractions? m_activeInteractions; private bool m_isActive; private bool m_isDisposed; + /// /// Gets whether the action currently owns an active multi-frame operation. /// public bool isActive => m_isActive; + /// /// Gets the required target type, or for a targetless action. /// public virtual Type? targetType => null; - internal virtual Type? argumentType => null; - - internal EditorActionState QueryInternal(EditorActionContext context) - { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - return Query(context); - } - - internal void ExecuteInternal(EditorActionContext context) - { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - Execute(context); - } - - internal bool PresentInternal(EditorActionContext context) - { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - return m_isActive && m_activeTarget is not null && m_activeTarget.Matches(context.interactions, context.target) && Present(context); - } - internal void CancelInternal() => Cancel(); - internal void LosePresentationInternal() + /// + /// Cancels active work and releases this action instance. + /// + public void Dispose() { - if (!m_isActive) - return; - try - { - OnPresentationLost(); - } - finally + if (m_isDisposed) { - if (m_isActive) - Cancel(); + return; } + Cancel(); + m_isDisposed = true; + GC.SuppressFinalize(this); } - internal bool IsActiveFor(object? target) => m_isActive - && m_activeTarget is not null - && m_activeInteractions is not null - && m_activeTarget.Matches( - m_activeInteractions, - target - ); /// /// Resolves the active target afresh for this callback; null means the identity is unavailable. /// @@ -69,11 +44,14 @@ internal bool IsActiveFor(object? target) => m_isActive /// Do not retain the result across callbacks. Activation stores a domain-qualified reference rather than the live object. /// protected object? activeTarget => m_activeInteractions is null ? null : m_activeTarget?.Resolve(m_activeInteractions); + /// /// Gets the host-owned passive context of the active operation, or null after completion. /// protected EditorContext? activeEditorContext { get; private set; } + internal virtual Type? argumentType => null; + /// /// Activates this action for a target and cancels any operation it previously owned. /// @@ -99,7 +77,9 @@ protected void Activate(EditorActionContext context) protected void Complete() { if (!m_isActive) + { return; + } m_activeTarget = null; m_activeInteractions = null; activeEditorContext = null; @@ -113,7 +93,9 @@ protected void Complete() protected void Cancel() { if (!m_isActive) + { return; + } m_activeTarget = null; m_activeInteractions = null; activeEditorContext = null; @@ -131,6 +113,7 @@ protected void Cancel() /// The current presentation and availability state. /// protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Executes the action for the supplied context. /// @@ -138,6 +121,7 @@ protected void Cancel() /// The editor, area, target, and optional argument for the operation. /// protected abstract void Execute(EditorActionContext context); + /// /// Presents an active action at the current target location. /// @@ -148,19 +132,16 @@ protected void Cancel() /// when the action replaced the target's normal content; otherwise, . /// protected virtual bool Present(EditorActionContext context) => false; + /// /// Runs after an active operation completes successfully. /// - protected virtual void OnCompleted() - { - } + protected virtual void OnCompleted() {} /// /// Runs after an active operation is cancelled. /// - protected virtual void OnCancelled() - { - } + protected virtual void OnCancelled() {} /// /// Runs when this action's active target loses editor presentation focus. @@ -171,17 +152,51 @@ protected virtual void OnCancelled() /// without calling or . /// protected virtual void OnPresentationLost() => Cancel(); - /// - /// Cancels active work and releases this action instance. - /// - public void Dispose() + + internal EditorActionState QueryInternal(EditorActionContext context) { - if (m_isDisposed) + ObjectDisposedException.ThrowIf(m_isDisposed, this); + return Query(context); + } + + internal void ExecuteInternal(EditorActionContext context) + { + ObjectDisposedException.ThrowIf(m_isDisposed, this); + Execute(context); + } + + internal bool PresentInternal(EditorActionContext context) + { + ObjectDisposedException.ThrowIf(m_isDisposed, this); + return m_isActive && m_activeTarget is not null && m_activeTarget.Matches(context.interactions, context.target) && Present(context); + } + + internal void CancelInternal() => Cancel(); + + internal void LosePresentationInternal() + { + if (!m_isActive) + { return; - Cancel(); - m_isDisposed = true; - GC.SuppressFinalize(this); + } + try + { + OnPresentationLost(); + } + finally + { + if (m_isActive) + { + Cancel(); + } + } } + + internal bool IsActiveFor(object? target) + => m_isActive + && m_activeTarget is not null + && m_activeInteractions is not null + && m_activeTarget.Matches(m_activeInteractions, target); } /// @@ -199,21 +214,35 @@ public abstract class EditorAction : EditorAction /// Gets the concrete type handled by this extension implementation. /// public sealed override Type targetType => typeof(TTarget); + internal sealed override Type argumentType => typeof(TArgument); /// /// Evaluates the operation's current availability and presentation state. /// + /// + /// The context that supplies state and services for this operation. + /// /// /// The validated editor action state that represents the completed operation. /// + protected sealed override EditorActionState Query(EditorActionContext context) + => TryCreate( + context, + out EditorActionContext typed + ) ? Query(typed) : EditorActionState.hidden; + + /// + /// Evaluates the action for a typed target and argument. + /// /// - /// The context that supplies state and services for this operation. + /// The typed contextual request. /// - protected sealed override EditorActionState Query(EditorActionContext context) => TryCreate( - context, - out EditorActionContext typed - ) ? Query(typed) : EditorActionState.hidden; + /// + /// The current presentation and availability state. + /// + protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Applies the editor action to the supplied interaction context. /// @@ -224,39 +253,34 @@ protected sealed override void Execute(EditorActionContext context) { if (!TryCreate(context, out EditorActionContext typed)) { - throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires target '{typeof(TTarget).FullName}' " + $"and argument '{typeof(TArgument).FullName}'."); + throw new InvalidOperationException( + $"Editor action '{GetType().FullName}' requires target '{typeof(TTarget).FullName}' " + $"and argument '{typeof(TArgument).FullName}'." + ); } Execute(typed); } /// - /// Presents this action through the current editor interaction surface. + /// Executes the action for a typed target and argument. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// - /// The context that supplies state and services for this operation. + /// The typed contextual request. /// - protected sealed override bool Present(EditorActionContext context) => TryCreate(context, out EditorActionContext typed) && Present(typed); + protected abstract void Execute(EditorActionContext context); + /// - /// Evaluates the action for a typed target and argument. + /// Presents this action through the current editor interaction surface. /// /// - /// The typed contextual request. + /// The context that supplies state and services for this operation. /// /// - /// The current presentation and availability state. + /// when the operation succeeds or its condition is satisfied; otherwise, . /// - protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; - /// - /// Executes the action for a typed target and argument. - /// - /// - /// The typed contextual request. - /// - protected abstract void Execute(EditorActionContext context); + protected sealed override bool Present(EditorActionContext context) + => TryCreate(context, out EditorActionContext typed) && Present(typed); + /// /// Presents an active action for a typed target and argument. /// @@ -267,6 +291,7 @@ protected sealed override void Execute(EditorActionContext context) /// when content was presented. /// protected virtual bool Present(EditorActionContext context) => false; + private static bool TryCreate( EditorActionContext context, out EditorActionContext typed @@ -282,96 +307,6 @@ out EditorActionContext typed } } -/// -/// Defines a targetless editor action that requires one strongly typed command argument. -/// -/// -/// The command argument type accepted by the action. -/// -public abstract class EditorArgumentAction : EditorAction -{ - internal sealed override Type argumentType => typeof(TArgument); - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected sealed override EditorActionState Query(EditorActionContext context) => context.target is null - && context.argument is TArgument argument ? Query(new EditorActionArgumentContext(context, argument)) : EditorActionState.hidden; - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected sealed override void Execute(EditorActionContext context) - { - if (context.target is not null || context.argument is not TArgument argument) - { - throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires argument '{typeof(TArgument).FullName}'."); - } - - Execute(new EditorActionArgumentContext(context, argument)); - } - - /// - /// Evaluates the action for a typed argument. - /// - /// - /// The typed contextual request. - /// - /// - /// The current presentation and availability state. - /// - protected virtual EditorActionState Query(EditorActionArgumentContext context) => EditorActionState.enabled; - /// - /// Executes the action for a typed argument. - /// - /// - /// The typed contextual request. - /// - protected abstract void Execute(EditorActionArgumentContext context); -} - -/// -/// Defines a target action with a typed presentation-only argument. -/// -/// -/// The target type accepted by the action. -/// -/// -/// The presentation data type. -/// -public abstract class EditorPresentationAction : EditorAction -{ - /// - /// Presents this action through the current editor interaction surface. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// - protected sealed override bool Present(EditorActionContext context) => context.argument is TPresentation presentation - && Present(new EditorActionContext(context, context.target, presentation)); - /// - /// Presents active content using strongly typed presentation data. - /// - /// - /// The typed presentation request. - /// - /// - /// when content was presented. - /// - protected abstract bool Present(EditorActionContext context); -} - /// /// Defines a discoverable action whose target must be assignable to a specific reference type. /// @@ -400,6 +335,17 @@ protected sealed override EditorActionState Query(EditorActionContext context) return context.target is TTarget target ? Query(new EditorActionContext(context, target)) : EditorActionState.hidden; } + /// + /// Evaluates the action for a strongly typed target. + /// + /// + /// The contextual request containing the typed target. + /// + /// + /// The current presentation and availability state. + /// + protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Applies the editor action to the supplied interaction context. /// @@ -417,6 +363,14 @@ protected sealed override void Execute(EditorActionContext context) Execute(new EditorActionContext(context, target)); } + /// + /// Executes the action for a strongly typed target. + /// + /// + /// The contextual request containing the typed target. + /// + protected abstract void Execute(EditorActionContext context); + /// /// Presents this action through the current editor interaction surface. /// @@ -432,23 +386,6 @@ protected sealed override bool Present(EditorActionContext context) return context.target is TTarget target && Present(new EditorActionContext(context, target)); } - /// - /// Evaluates the action for a strongly typed target. - /// - /// - /// The contextual request containing the typed target. - /// - /// - /// The current presentation and availability state. - /// - protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; - /// - /// Executes the action for a strongly typed target. - /// - /// - /// The contextual request containing the typed target. - /// - protected abstract void Execute(EditorActionContext context); /// /// Presents an active action for a strongly typed target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs new file mode 100644 index 000000000..91b89a54a --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs @@ -0,0 +1,23 @@ +namespace Inno.Editor.Interactions; + +/// +/// Provides a strongly typed action argument to a targetless editor action. +/// +/// +/// The action argument type required by the action. +/// +public sealed class EditorActionArgumentContext : EditorActionContext +{ + internal EditorActionArgumentContext( + EditorActionContext context, + TArgument argument + ) : base(context.editor, context.interactions, context.area, target: null, argument: argument) + { + this.argument = argument; + } + + /// + /// Gets the strongly typed action argument. + /// + public new TArgument argument { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs index f003ded47..60ff2b4ec 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs @@ -23,10 +23,7 @@ public sealed class EditorActionAttribute : Attribute public EditorActionAttribute( string action, int priority = 0 - ) - : this(action, string.Empty, priority) - { - } + ) : this(action, string.Empty, priority) {} /// /// Creates an action registration restricted to one exact area. @@ -49,7 +46,9 @@ public EditorActionAttribute( int priority = 0 ) { if (string.IsNullOrWhiteSpace(action)) + { throw new ArgumentException("An editor action name is required.", nameof(action)); + } this.action = action; this.area = area ?? string.Empty; this.priority = priority; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs index 505563fa6..3b5840df4 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs @@ -2,9 +2,13 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Provides contextual state to an editor action. /// +/// +/// The typed action contexts derive from this class to add a strongly typed target or argument. It has no overridable members. +/// public class EditorActionContext { /// @@ -38,8 +42,10 @@ internal EditorActionContext( object? target = null, object? argument = null ) { - this.editor = editor ?? throw new ArgumentNullException(nameof(editor)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + this.editor = editor; + this.interactions = interactions; ArgumentException.ThrowIfNullOrWhiteSpace(area); this.area = area; this.target = target; @@ -50,22 +56,27 @@ internal EditorActionContext( /// Gets the shared passive editor context. /// public EditorContext editor { get; } + /// /// Gets the active interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the transactional history used to record reversible mutations performed by this action. /// public IEditorHistory history => interactions.history; + /// /// Gets the stable interaction area. /// public string area { get; } + /// /// Gets the contextual action target. /// public object? target { get; } + /// /// Gets the optional action argument. /// @@ -119,27 +130,6 @@ TArgument argument /// Gets the strongly typed action target. /// public new TTarget target { get; } - /// - /// Gets the strongly typed action argument. - /// - public new TArgument argument { get; } -} - -/// -/// Provides a strongly typed action argument to a targetless editor action. -/// -/// -/// The action argument type required by the action. -/// -public sealed class EditorActionArgumentContext : EditorActionContext -{ - internal EditorActionArgumentContext( - EditorActionContext context, - TArgument argument - ) : base(context.editor, context.interactions, context.area, target: null, argument: argument) - { - this.argument = argument; - } /// /// Gets the strongly typed action argument. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs index 7c18f3996..e6cbef4af 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs @@ -7,18 +7,19 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + internal sealed class EditorActionRouter( EditorExtensionCatalog catalog, EditorContext editor, EditorInteractions interactions, Logger log -) -{ +) { private readonly Queue m_pending = []; private readonly HashSet m_presentationFailures = new(StringComparer.Ordinal); private readonly HashSet m_queryFailures = new(StringComparer.Ordinal); - private IReadOnlyDictionary? m_byId; + private IReadOnlyDictionary? m_byID; private Dictionary<(KeyCode key, KeyModifier modifiers, string area), string[]>? m_shortcutIndex; + internal EditorActionState Query( string action, EditorActionContext context @@ -27,7 +28,9 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return EditorActionState.hidden; + } try { EditorActionState state = registration.action.QueryInternal(context); @@ -37,7 +40,9 @@ EditorActionContext context catch (Exception exception) { if (m_queryFailures.Add(action)) + { log.Write(LogLevel.Error, "Editor action '{0}' query failed: {1}", [action, exception]); + } return EditorActionState.disabled; } } @@ -50,12 +55,16 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return false; + } try { EditorActionState state = registration.action.QueryInternal(context); if (!state.isVisible || !state.isEnabled) + { return false; + } interactions.PrepareOperation(); registration.action.ExecuteInternal(context); return true; @@ -76,7 +85,9 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return false; + } try { bool presented = registration.action.PresentInternal(context); @@ -87,7 +98,9 @@ EditorActionContext context { TryCancel(registration.action, action, "presentation cleanup"); if (m_presentationFailures.Add(action)) + { log.Write(LogLevel.Error, "Editor action '{0}' presentation failed: {1}", [action, exception]); + } return false; } } @@ -108,7 +121,16 @@ EditorActionContext context ) { ArgumentException.ThrowIfNullOrWhiteSpace(action); ArgumentNullException.ThrowIfNull(context); - m_pending.Enqueue(new PendingAction(action, context.area, EditorTargetReference.Capture(context.target), context.target is not null, EditorTargetReference.Capture(context.argument), context.argument is not null)); + m_pending.Enqueue( + new PendingAction( + action, + context.area, + EditorTargetReference.Capture(context.target), + context.target is not null, + EditorTargetReference.Capture(context.argument), + context.argument is not null + ) + ); } internal void Flush() @@ -118,7 +140,9 @@ internal void Flush() object? target = request.target.Resolve(interactions); object? argument = request.argument.Resolve(interactions); if (request.hasTarget && target is null || request.hasArgument && argument is null) + { continue; + } _ = Execute(request.action, new EditorActionContext(editor, interactions, request.area, target, argument)); } } @@ -147,9 +171,10 @@ internal void ResetTransientState() internal void InvalidateDiscovery() { - m_byId = null; + m_byID = null; m_shortcutIndex = null; } + internal void LosePresentationExcept(object? target) { var visited = new HashSet(ReferenceEqualityComparer.Instance); @@ -157,14 +182,20 @@ internal void LosePresentationExcept(object? target) { EditorAction action = registration.action; if (!visited.Add(action) || !action.isActive || action.IsActiveFor(target)) + { continue; + } try { action.LosePresentationInternal(); } catch (Exception exception) { - log.Write(LogLevel.Error, "Editor action '{0}' failed while losing presentation focus: {1}", [registration.attribute.action, exception]); + log.Write( + LogLevel.Error, + "Editor action '{0}' failed while losing presentation focus: {1}", + [registration.attribute.action, exception] + ); } } } @@ -188,36 +219,50 @@ internal bool DispatchShortcut( object? target ) { if (keyEvent.repeat) + { return false; + } m_shortcutIndex ??= BuildShortcutIndex(); KeyModifier modifiers = new HotKeyGesture(keyEvent.key, keyEvent.modifiers).normalizedModifiers; _ = m_shortcutIndex.TryGetValue((keyEvent.key, modifiers, area), out string[]? exact); _ = m_shortcutIndex.TryGetValue((keyEvent.key, modifiers, string.Empty), out string[]? global); if (exact is null && global is null) + { return false; + } var context = new EditorActionContext(editor, interactions, area, target); - var candidates = new List(); + List candidates = []; for (int pass = 0; pass < 2; pass++) { - string[]? actionIds = pass == 0 ? exact : global; - if (actionIds is null) + string[]? actionIDs = pass == 0 ? exact : global; + if (actionIDs is null) + { continue; - foreach (string action in actionIds) + } + foreach (string action in actionIDs) { if (pass == 1 && exact is not null && Array.IndexOf(exact, action) >= 0) + { continue; + } ResolvedAction? resolved = ResolveWithSpecificity(action, context); if (resolved is null) + { continue; + } EditorExtensionCatalog.ActionRegistration registration = resolved.Value.registration; bool hasExact = HasExactShortcut(registration, area); foreach (EditorShortcutAttribute shortcut in registration.shortcuts) { if (hasExact ? !string.Equals(shortcut.area, area, StringComparison.Ordinal) : !string.IsNullOrEmpty(shortcut.area)) + { continue; + } HotKeyGesture gesture = CreateGesture(shortcut); if (!gesture.Matches(keyEvent)) + { continue; + } candidates.Add(new ShortcutCandidate(action, resolved.Value, gesture)); break; } @@ -231,25 +276,68 @@ internal bool DispatchShortcut( { int areaComparison = right.resolved.exactArea.CompareTo(left.resolved.exactArea); if (areaComparison != 0) + { return areaComparison; + } int distanceComparison = left.resolved.targetDistance.CompareTo(right.resolved.targetDistance); if (distanceComparison != 0) + { return distanceComparison; - int priorityComparison = right.resolved.registration.attribute.priority.CompareTo(left.resolved.registration.attribute.priority); + } + int priorityComparison = right.resolved.registration.attribute.priority.CompareTo( + left.resolved.registration.attribute.priority + ); if (priorityComparison != 0) + { return priorityComparison; + } return string.Compare(left.action, right.action, StringComparison.Ordinal); }); for (int i = 0; i < candidates.Count; i++) { ShortcutCandidate candidate = candidates[i]; if (Execute(candidate.action, context)) + { return true; + } } return false; } + internal IReadOnlyList BuildUnplacedCommands( + EditorActionContext context, + IReadOnlySet placed + ) { + List result = []; + foreach (string id in index.Keys) + { + if (placed.Contains(id)) + { + continue; + } + EditorActionState state = Query(id, context); + if (!state.isVisible) + { + continue; + } + string label = state.displayName ?? id; + result.Add(new EditorMenuItem(label, id, 0, false, state)); + } + + result.Sort(static ( + left, + right + ) => StringComparer.OrdinalIgnoreCase.Compare(left.label, right.label)); + return result; + } + + private IReadOnlyDictionary index + => m_byID ??= catalog.extensions.actions.GroupBy( + static registration => registration.id, + StringComparer.Ordinal + ).ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); + private bool TryResolveShortcut( EditorExtensionCatalog.ActionRegistration? registration, string area, @@ -261,7 +349,9 @@ out HotKeyGesture gesture foreach (EditorShortcutAttribute shortcut in registration.shortcuts) { if (hasExact ? !string.Equals(shortcut.area, area, StringComparison.Ordinal) : !string.IsNullOrEmpty(shortcut.area)) + { continue; + } gesture = CreateGesture(shortcut); return true; } @@ -274,14 +364,17 @@ out HotKeyGesture gesture string action, EditorActionContext context ) => ResolveWithSpecificity(action, context)?.registration; + private ResolvedAction? ResolveWithSpecificity( string action, EditorActionContext context ) { EditorExtensionCatalog.ActionRegistration? best = null; int bestDistance = int.MaxValue; - if (!Index.TryGetValue(action, out EditorExtensionCatalog.ActionRegistration[]? registrations)) + if (!index.TryGetValue(action, out EditorExtensionCatalog.ActionRegistration[]? registrations)) + { return null; + } foreach (EditorExtensionCatalog.ActionRegistration registration in registrations) { bool exactArea = registration.area is not null; @@ -309,19 +402,15 @@ EditorActionContext context bool bestExactArea = best?.area is not null; if (best is null || exactArea - && !bestExactArea + && !bestExactArea || exactArea == bestExactArea - && (distance < bestDistance - || distance == bestDistance - && registration.attribute.priority > best.attribute.priority - || distance == bestDistance - && registration.attribute.priority == best.attribute.priority - && string.Compare( - registration.type.FullName, - best.type.FullName, - StringComparison.Ordinal - ) < 0)) - { + && (distance < bestDistance + || distance == bestDistance + && registration.attribute.priority > best.attribute.priority + || distance == bestDistance + && registration.attribute.priority == best.attribute.priority + && string.Compare(registration.type.FullName, best.type.FullName, StringComparison.Ordinal) < 0) + ) { best = registration; bestDistance = distance; } @@ -330,47 +419,11 @@ EditorActionContext context return best is null ? null : new ResolvedAction(best, bestDistance, best.area is not null); } - internal IReadOnlyList BuildUnplacedCommands( - EditorActionContext context, - IReadOnlySet placed - ) { - var result = new List(); - foreach (string id in Index.Keys) - { - if (placed.Contains(id)) - continue; - EditorActionState state = Query(id, context); - if (!state.isVisible) - continue; - string label = state.displayName ?? id; - result.Add(new EditorMenuItem(label, id, 0, false, state)); - } + private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) + => shortcut.primary + ? HotKeyGesture.Primary(shortcut.key, editor.keyboard, shortcut.modifiers) + : new HotKeyGesture(shortcut.key, shortcut.modifiers, editor.keyboard.superModifierLabel); - result.Sort(static ( - left, - right - ) => StringComparer.OrdinalIgnoreCase.Compare(left.label, right.label)); - return result; - } - - private IReadOnlyDictionary Index => m_byId ??= catalog.extensions.actions.GroupBy( - static registration => registration.id, - StringComparer.Ordinal - ).ToDictionary( - static group => group.Key, - static group => group.ToArray(), - StringComparer.Ordinal - ); - - private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) => shortcut.primary ? HotKeyGesture.Primary( - shortcut.key, - editor.keyboard, - shortcut.modifiers - ) : new HotKeyGesture( - shortcut.key, - shortcut.modifiers, - editor.keyboard.superModifierLabel - ); private Dictionary<(KeyCode key, KeyModifier modifiers, string area), string[]> BuildShortcutIndex() { var candidates = new Dictionary<(KeyCode key, KeyModifier modifiers, string area), HashSet>(); @@ -380,31 +433,23 @@ private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) => shortcu { HotKeyGesture gesture = CreateGesture(shortcut); string area = string.IsNullOrEmpty(shortcut.area) ? registration.area ?? string.Empty : shortcut.area; - var key = (gesture.key, gesture.normalizedModifiers, area); + (KeyCode key, KeyModifier normalizedModifiers, string area) key = (gesture.key, gesture.normalizedModifiers, area); if (!candidates.TryGetValue(key, out HashSet? actions)) + { candidates.Add(key, actions = new(StringComparer.Ordinal)); + } actions.Add(registration.id); } } - return candidates.ToDictionary(static pair => pair.Key, - static pair => pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToArray()); - } - - private static bool HasExactShortcut( - EditorExtensionCatalog.ActionRegistration registration, - string area - ) { - foreach (EditorShortcutAttribute shortcut in registration.shortcuts) - { - if (!string.IsNullOrEmpty(shortcut.area) && string.Equals(shortcut.area, area, StringComparison.Ordinal)) - return true; - } - return false; + return candidates.ToDictionary( + static pair => pair.Key, + static pair => pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToArray() + ); } private void TryCancel( EditorAction action, - string actionId, + string actionID, string phase ) { try @@ -413,8 +458,22 @@ string phase } catch (Exception exception) { - log.Write(LogLevel.Error, "Editor action '{0}' failed during {1}: {2}", [actionId, phase, exception]); + log.Write(LogLevel.Error, "Editor action '{0}' failed during {1}: {2}", [actionID, phase, exception]); + } + } + + private static bool HasExactShortcut( + EditorExtensionCatalog.ActionRegistration registration, + string area + ) { + foreach (EditorShortcutAttribute shortcut in registration.shortcuts) + { + if (!string.IsNullOrEmpty(shortcut.area) && string.Equals(shortcut.area, area, StringComparison.Ordinal)) + { + return true; + } } + return false; } private sealed record PendingAction( @@ -425,11 +484,13 @@ private sealed record PendingAction( EditorTargetReference argument, bool hasArgument ); + private readonly record struct ResolvedAction( EditorExtensionCatalog.ActionRegistration registration, int targetDistance, bool exactArea ); + private readonly record struct ShortcutCandidate( string action, ResolvedAction resolved, diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs index a0e834a59..2cb9a7110 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Interactions; + /// /// Describes the current presentation and availability of an editor action. /// @@ -40,30 +41,37 @@ public EditorActionState( /// Gets whether the action should be displayed. /// public bool isVisible { get; } + /// /// Gets whether the action can execute. /// public bool isEnabled { get; } + /// /// Gets whether the action is currently checked. /// public bool isChecked { get; } + /// /// Gets an optional contextual display name. /// public string? displayName { get; } + /// /// Gets the current execution barrier, or null when no specific explanation is available. /// public string? unavailableReason { get; } + /// /// Gets a visible and enabled action state. /// public static EditorActionState enabled => new(true, true); + /// /// Gets a visible but disabled action state. /// public static EditorActionState disabled => new(true, false); + /// /// Gets a hidden action state. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs new file mode 100644 index 000000000..5474fd2c9 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs @@ -0,0 +1,64 @@ +using System; + +namespace Inno.Editor.Interactions; + +/// +/// Defines a targetless editor action that requires one strongly typed command argument. +/// +/// +/// The command argument type accepted by the action. +/// +public abstract class EditorArgumentAction : EditorAction +{ + internal sealed override Type argumentType => typeof(TArgument); + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected sealed override EditorActionState Query(EditorActionContext context) + => context.target is null + && context.argument is TArgument argument + ? Query(new EditorActionArgumentContext(context, argument)) + : EditorActionState.hidden; + + /// + /// Evaluates the action for a typed argument. + /// + /// + /// The typed contextual request. + /// + /// + /// The current presentation and availability state. + /// + protected virtual EditorActionState Query(EditorActionArgumentContext context) => EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected sealed override void Execute(EditorActionContext context) + { + if (context.target is not null || context.argument is not TArgument argument) + { + throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires argument '{typeof(TArgument).FullName}'."); + } + + Execute(new EditorActionArgumentContext(context, argument)); + } + + /// + /// Executes the action for a typed argument. + /// + /// + /// The typed contextual request. + /// + protected abstract void Execute(EditorActionArgumentContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs new file mode 100644 index 000000000..ba0ec1803 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs @@ -0,0 +1,37 @@ +namespace Inno.Editor.Interactions; + +/// +/// Defines a target action with a typed presentation-only argument. +/// +/// +/// The target type accepted by the action. +/// +/// +/// The presentation data type. +/// +public abstract class EditorPresentationAction : EditorAction +{ + /// + /// Presents this action through the current editor interaction surface. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// + protected sealed override bool Present(EditorActionContext context) + => context.argument is TPresentation presentation + && Present(new EditorActionContext(context, context.target, presentation)); + + /// + /// Presents active content using strongly typed presentation data. + /// + /// + /// The typed presentation request. + /// + /// + /// when content was presented. + /// + protected abstract bool Present(EditorActionContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs index 41464dcf4..466522b81 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Input; namespace Inno.Editor.Interactions; @@ -26,10 +25,7 @@ public EditorShortcutAttribute( KeyCode key, KeyModifier modifiers = KeyModifier.None, bool primary = false - ) - : this(string.Empty, key, modifiers, primary) - { - } + ) : this(string.Empty, key, modifiers, primary) {} /// /// Creates a shortcut scoped to an exact interaction area. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs index 834c45362..417532402 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Core; @@ -49,6 +48,34 @@ public HotKeyGesture( /// public KeyModifier modifiers { get; } + /// + /// Formats the gesture as a human-readable editor menu shortcut label. + /// + /// + /// A product-resolved textual representation of the gesture. + /// + public override string ToString() + { + string prefix = string.Empty; + if ((modifiers & KeyModifier.Control) != 0) + { + prefix += "Ctrl+"; + } + if ((modifiers & KeyModifier.Super) != 0) + { + prefix += (m_superModifierLabel ?? "Super") + "+"; + } + if ((modifiers & KeyModifier.Alt) != 0) + { + prefix += "Alt+"; + } + if ((modifiers & KeyModifier.Shift) != 0) + { + prefix += "Shift+"; + } + return prefix + key; + } + /// /// Creates a gesture that includes the product-selected primary modifier. /// @@ -74,24 +101,9 @@ public static HotKeyGesture Primary( } /// - /// Formats the gesture as a human-readable editor menu shortcut label. + /// Gets the normalized modifiers used by generation-owned shortcut indexes. /// - /// - /// A product-resolved textual representation of the gesture. - /// - public override string ToString() - { - string prefix = string.Empty; - if ((modifiers & KeyModifier.Control) != 0) - prefix += "Ctrl+"; - if ((modifiers & KeyModifier.Super) != 0) - prefix += (m_superModifierLabel ?? "Super") + "+"; - if ((modifiers & KeyModifier.Alt) != 0) - prefix += "Alt+"; - if ((modifiers & KeyModifier.Shift) != 0) - prefix += "Shift+"; - return prefix + key; - } + internal KeyModifier normalizedModifiers => Normalize(key, modifiers); /// /// Returns whether a non-repeating key event matches this gesture after normalizing @@ -104,26 +116,21 @@ public override string ToString() /// when the key and normalized modifiers match; otherwise, . /// internal bool Matches(KeyPressedEvent keyEvent) - => !keyEvent.repeat && - keyEvent.key == key && - Normalize(key, keyEvent.modifiers) == Normalize(key, modifiers); - - /// - /// Gets the normalized modifiers used by generation-owned shortcut indexes. - /// - internal KeyModifier normalizedModifiers => Normalize(key, modifiers); + => !keyEvent.repeat + && keyEvent.key == key + && Normalize(key, keyEvent.modifiers) == Normalize(key, modifiers); private static KeyModifier Normalize( KeyCode key, KeyModifier value ) { - KeyModifier normalized = value & - (KeyModifier.Alt | - KeyModifier.Control | - KeyModifier.Shift | - KeyModifier.Super); + KeyModifier normalized = value + & (KeyModifier.Alt + | KeyModifier.Control + | KeyModifier.Shift + | KeyModifier.Super); return key == KeyCode.Plus - ? normalized & ~KeyModifier.Shift - : normalized; + ? normalized & ~KeyModifier.Shift + : normalized; } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs index 01a941efd..e11d15578 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -25,21 +24,28 @@ internal EditorExtensionActivator( IEnumerable hostServices, IEnumerable? retainedInstances = null ) { - m_context = context ?? throw new ArgumentNullException(nameof(context)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(activeTypes); + ArgumentNullException.ThrowIfNull(hostServices); + m_context = context; + m_interactions = interactions; m_moduleTypes = moduleTypes .OrderBy(static type => type.FullName, StringComparer.Ordinal) .ToArray(); - m_hostServices = (hostServices ?? throw new ArgumentNullException(nameof(hostServices))).ToArray(); - var activeTypeSet = new HashSet( - activeTypes ?? throw new ArgumentNullException(nameof(activeTypes))); + m_hostServices = (hostServices).ToArray(); + var activeTypeSet = new HashSet(activeTypes); if (retainedInstances is null) + { return; + } foreach (object instance in retainedInstances) { Type instanceType = instance.GetType(); if (activeTypeSet.Contains(instanceType)) + { m_instances.TryAdd(instanceType, instance); + } } } @@ -48,14 +54,14 @@ internal EditorExtensionActivator( internal bool CanCreate(Type type) { ArgumentNullException.ThrowIfNull(type); - return CanCreate(type, new HashSet()); + return CanCreate(type, []); } internal EditorModule CreateModule(Type type) => (EditorModule)Create(type, typeof(EditorModule)); internal TExtension CreateExtension(Type type) where TExtension : class - => (TExtension)Create(type, typeof(TExtension)); + => (TExtension)Create(type, typeof(TExtension)); private bool CanCreate( Type type, @@ -72,7 +78,8 @@ HashSet visiting } ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1 || !visiting.Add(type)) { return true; @@ -84,8 +91,8 @@ HashSet visiting Type parameterType = parameter.ParameterType; if (parameterType == typeof(EditorContext) || IsInteractionContract(parameterType) - || parameterType == typeof(IEditorDocumentService)) - { + || parameterType == typeof(IEditorDocumentService) + ) { continue; } @@ -99,8 +106,8 @@ HashSet visiting .Where(parameterType.IsAssignableFrom) .ToArray(); if (matches.Length == 0 - || matches.Length == 1 && !CanCreate(matches[0], visiting)) - { + || matches.Length == 1 && !CanCreate(matches[0], visiting) + ) { result = false; break; } @@ -118,14 +125,21 @@ Type contract if (m_instances.TryGetValue(type, out object? existing)) { if (!contract.IsInstanceOfType(existing)) + { throw CreateContractException(type, contract); + } return existing; } if (type.IsAbstract || !contract.IsAssignableFrom(type)) + { throw CreateContractException(type, contract); + } if (!m_constructing.Add(type)) + { throw new InvalidOperationException( - $"Editor extension constructor dependency cycle contains '{type.FullName}'."); + $"Editor extension constructor dependency cycle contains '{type.FullName}'." + ); + } try { @@ -133,7 +147,9 @@ Type contract ParameterInfo[] parameters = constructor.GetParameters(); var arguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) + { arguments[i] = Resolve(parameters[i].ParameterType, type); + } object instance; try { @@ -143,7 +159,8 @@ Type contract { throw new InvalidOperationException( $"Editor extension '{type.FullName}' constructor failed.", - exception.InnerException ?? exception); + exception.InnerException ?? exception + ); } m_instances.Add(type, instance); return instance; @@ -159,51 +176,68 @@ private object Resolve( Type ownerType ) { if (parameterType == typeof(EditorContext)) + { return m_context; + } if (IsInteractionContract(parameterType)) + { return m_interactions; + } if (parameterType == typeof(IEditorDocumentService)) + { return m_interactions.documents; + } object[] services = m_hostServices .Where(parameterType.IsInstanceOfType) .ToArray(); if (services.Length == 1) + { return services[0]; + } if (services.Length > 1) { throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' has ambiguous host service dependency " + - $"'{parameterType.FullName}'."); + $"Editor extension '{ownerType.FullName}' has ambiguous host service dependency " + + $"'{parameterType.FullName}'." + ); } Type[] matches = m_moduleTypes .Where(parameterType.IsAssignableFrom) .ToArray(); if (matches.Length == 1) + { return CreateModule(matches[0]); + } if (matches.Length == 0) { throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' requests unsupported constructor dependency " + - $"'{parameterType.FullName}'. Only EditorContext, EditorInteractions, and discovered " + - "EditorModule types or explicit host services are injectable."); + $"Editor extension '{ownerType.FullName}' requests unsupported constructor dependency " + + $"'{parameterType.FullName}'. Only EditorContext, EditorInteractions, and discovered " + + "EditorModule types or explicit host services are injectable." + ); } throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' has ambiguous module dependency " + - $"'{parameterType.FullName}': {string.Join(", ", matches.Select(static type => type.FullName))}."); + $"Editor extension '{ownerType.FullName}' has ambiguous module dependency " + + $"'{parameterType.FullName}': {string.Join(", ", matches.Select(static type => type.FullName))}." + ); } private static ConstructorInfo SelectConstructor(Type type) { ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length == 0) + { throw new InvalidOperationException($"Editor extension '{type.FullName}' has no instance constructor."); + } if (constructors.Length > 1) { throw new InvalidOperationException( - $"Editor extension '{type.FullName}' must declare exactly one constructor."); + $"Editor extension '{type.FullName}' must declare exactly one constructor." + ); } return constructors[0]; } @@ -213,6 +247,5 @@ private static ConstructorInfo SelectConstructor(Type type) private static InvalidOperationException CreateContractException( Type type, Type contract - ) - => new($"Editor extension '{type.FullName}' must be a non-abstract '{contract.FullName}'."); + ) => new($"Editor extension '{type.FullName}' must be a non-abstract '{contract.FullName}'."); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs index b6c9fd6e5..fef023215 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs @@ -4,10 +4,11 @@ using System.Reflection; using Inno.Core.Execution; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Editor.Core; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions; + internal sealed class EditorExtensionCatalog : TypeRegistry { private readonly EditorContext m_context; @@ -22,6 +23,7 @@ internal sealed class EditorExtensionCatalog : TypeRegistry service ?? throw new ArgumentException("Host services cannot contain null.", nameof(hostServices))).ToArray(); - m_extensionsChanged = extensionsChanged ?? throw new ArgumentNullException(nameof(extensionsChanged)); + m_hostServices = hostServices + .Select(static service => service ?? throw new ArgumentException("Host services cannot contain null.", nameof(hostServices))) + .ToArray(); + m_extensionsChanged = extensionsChanged; m_state = new EditorExtensionStateStore(context, log); } @@ -46,192 +54,11 @@ internal Snapshot extensions { Snapshot snapshot = current; if (!ReferenceEquals(snapshot, m_active) && !ReferenceEquals(snapshot, m_staging)) - throw new InvalidOperationException("The extension registry returned an unpublished snapshot."); - return snapshot; - } - } - - internal bool TryGetModule(out TModule? module) - where TModule : EditorModule - { - Snapshot? snapshot = m_active; - if (snapshot is not null) - foreach (ModuleRegistration registration in snapshot.modules) - if (registration.module is TModule candidate && snapshot.startedModules.Contains(candidate) && !snapshot.quarantinedModules.Contains(candidate)) - { - module = candidate; - return true; - } - - module = null; - return false; - } - - internal void UpdateModules() - { - Snapshot snapshot = extensions; - for (int i = 0; i < snapshot.modules.Length; i++) - { - ModuleRegistration registration = snapshot.modules[i]; - if (snapshot.quarantinedModules.Contains(registration.module)) - continue; - try - { - registration.module.Update(m_context); - if (registration.module.blocksFollowingUpdates) - break; - } - catch (Exception exception) - { - snapshot.quarantinedModules.Add(registration.module); - LogError("Editor module '{0}' failed to update and was quarantined: {1}", registration.attribute.id, exception); - continue; - } - } - - m_state.Update(m_context.frame.totalTime, GetAvailableState(snapshot), GetAvailablePanels(snapshot)); - } - - internal void SaveState() - { - if (m_active is not null) - m_state.Save(GetAvailableState(m_active), GetAvailablePanels(m_active)); - } - - internal bool TryTogglePanel(string panelId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - Snapshot snapshot = extensions; - for (int i = 0; i < snapshot.panels.Length; i++) - { - PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) - { - continue; - } - - registration.panel.isOpen = !registration.panel.isOpen; - if (registration.panel.isOpen) - m_pendingPanelFocus.Add(panelId); - else - m_pendingPanelFocus.Remove(panelId); - return true; - } - - return false; - } - - internal IReadOnlyList GetPanelDeclarations() => extensions.panelDeclarations; - internal bool TryGetPanelState( - string panelId, - out bool isOpen - ) { - Snapshot snapshot = extensions; - foreach (PanelRegistration registration in snapshot.panels) - { - if (registration.attribute.id != panelId || snapshot.quarantinedPanels.Contains(registration.panel)) - continue; - isOpen = registration.panel.isOpen; - return true; - } - - isOpen = false; - return false; - } - - internal bool TryOpenPanel(string panelId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - Snapshot snapshot = extensions; - for (int i = 0; i < snapshot.panels.Length; i++) - { - PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) - { - continue; - } - - registration.panel.isOpen = true; - m_pendingPanelFocus.Add(panelId); - return true; - } - - return false; - } - - internal bool TryClosePanel(string panelId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - Snapshot snapshot = extensions; - for (int i = 0; i < snapshot.panels.Length; i++) - { - PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) { - continue; + throw new InvalidOperationException("The extension registry returned an unpublished snapshot."); } - - registration.panel.isOpen = false; - m_pendingPanelFocus.Remove(panelId); - return true; - } - - return false; - } - - internal bool TakePanelFocusRequest(string panelId) => m_pendingPanelFocus.Remove(panelId); - internal void PrepareShutdown() - { - if (m_active is not null) - m_state.PrepareShutdown(GetAvailableState(m_active), GetAvailablePanels(m_active)); - } - - internal ActionRegistration[] GetActionsForShutdown() => m_active?.actions ?? []; - internal void QuarantinePanel( - Snapshot snapshot, - PanelRegistration registration, - Exception exception - ) { - ArgumentNullException.ThrowIfNull(snapshot); - ArgumentNullException.ThrowIfNull(registration); - ArgumentNullException.ThrowIfNull(exception); - if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedPanels.Add(registration.panel)) - return; - registration.panel.isOpen = false; - m_diagnostics.ReportPanelFailure(registration.attribute.id, exception); - m_diagnostics.Commit(); - LogError("Editor panel '{0}' failed to draw and was quarantined: {1}", registration.attribute.id, exception); - } - - internal void QuarantineModal( - Snapshot snapshot, - ModalRegistration registration, - Exception exception - ) { - ArgumentNullException.ThrowIfNull(snapshot); - ArgumentNullException.ThrowIfNull(registration); - ArgumentNullException.ThrowIfNull(exception); - if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedModals.Add(registration.modal)) - return; - LogError("Editor modal '{0}' failed and was quarantined: {1}", registration.attribute.id, exception); - } - - internal void Shutdown(bool saveState = true) - { - List failures = []; - if (m_active is not null) - { - Snapshot active = m_active; - if (saveState) - AttemptCleanup(() => m_state.PrepareShutdown(GetAvailableState(active), GetAvailablePanels(active)), failures); - AttemptCleanup(() => Deactivate(active), failures); + return snapshot; } - - m_active = null; - NotifyExtensionsChanged(); - m_diagnostics.Dispose(); - m_state.ClearDiagnostics(); - ThrowCleanupFailures(failures); } /// @@ -258,56 +85,66 @@ protected override Snapshot Build(TypeCacheSnapshot types) m_hostServices, m_active?.instances ); - ModuleRegistration[] modules = moduleTypes.Where(activator.CanCreate).Select(type => new ModuleRegistration(type.GetCustomAttribute(false)!, type, activator.CreateModule(type))).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); - ActionRegistration[] actions = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateActionRegistration(type, activator)).ToArray(); + ModuleRegistration[] modules = moduleTypes + .Where(activator.CanCreate) + .Select( + type => new ModuleRegistration(type.GetCustomAttribute(false)!, type, activator.CreateModule(type)) + ) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); + ActionRegistration[] actions = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateActionRegistration(type, activator)) + .ToArray(); ValidateActions(actions); ValidateShortcuts(actions); ValidateToolbars(actions); - MenuSourceRegistration[] menuSources = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).SelectMany(type => CreateMenuSourceRegistrations(type, activator)).OrderByDescending(static value => value.priority).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + MenuSourceRegistration[] menuSources = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .SelectMany(type => CreateMenuSourceRegistrations(type, activator)) + .OrderByDescending(static value => value.priority) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); DropRegistration[] drops = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( static type => type.FullName, StringComparer.Ordinal ).Where(activator.CanCreate).SelectMany(type => CreateDropRegistrations(type, activator)).ToArray(); ValidateDrops(drops); - PanelRegistration[] panels = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreatePanelRegistration(type, activator)).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + PanelRegistration[] panels = types.GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreatePanelRegistration(type, activator)) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidatePanels(panels); - ValidateExtensionIds(modules, panels); - ModalRegistration[] modals = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateModalRegistration(type, activator)).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + ValidateExtensionIDs(modules, panels); + ModalRegistration[] modals = types.GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateModalRegistration(type, activator)) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidateModals(modals); - HistoryHandlerRegistration[] historyHandlers = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateHistoryHandlerRegistration(type, activator)).OrderBy( - static value => value.attribute.kind, - StringComparer.Ordinal - ).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + HistoryHandlerRegistration[] historyHandlers = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateHistoryHandlerRegistration(type, activator)) + .OrderBy(static value => value.attribute.kind, StringComparer.Ordinal) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidateHistoryHandlers(historyHandlers); StateRegistration[] state = CreateStateRegistrations(modules, panels); return new Snapshot(modules, actions, menuSources, drops, panels, modals, historyHandlers, state, activator.instances.ToArray()); @@ -327,14 +164,24 @@ protected override void OnActivating( Snapshot candidate ) { if (m_activation is not null) + { throw new InvalidOperationException("An extension generation transition is already active."); + } m_interactions.PrepareOperation(); if (previous is not null) + { CapturePanelStates(previous); + } if (previous is not null) + { m_state.Save(GetAvailableState(previous), GetAvailablePanels(previous)); - var existing = previous is null ? new HashSet(ReferenceEqualityComparer.Instance) : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); - EditorHistory.HandlerUpdate handlers = m_interactions.historyHost.PrepareHandlerUpdate(CreateHistoryHandlerMap(candidate.historyHandlers)); + } + HashSet existing = previous is null + ? new HashSet(ReferenceEqualityComparer.Instance) + : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); + EditorHistory.HandlerUpdate handlers = m_interactions.historyHost.PrepareHandlerUpdate( + CreateHistoryHandlerMap(candidate.historyHandlers) + ); var activation = new ActivationState(previous, candidate, existing, handlers); m_activation = activation; m_staging = candidate; @@ -345,38 +192,50 @@ Snapshot candidate foreach (ModuleRegistration registration in candidate.modules) { if (existing.Contains(registration.module) && previous.startedModules.Contains(registration.module)) + { candidate.startedModules.Add(registration.module); + } } foreach (PanelRegistration registration in candidate.panels) { if (existing.Contains(registration.panel) && previous.attachedPanels.Contains(registration.panel)) + { candidate.attachedPanels.Add(registration.panel); + } } } if (previous is not null) + { RetirePrevious(previous, candidate, activation); + } for (int i = 0; i < candidate.modules.Length; i++) { ModuleRegistration registration = candidate.modules[i]; if (existing.Contains(registration.module)) + { continue; + } activation.startedModules.Add(registration); candidate.startedModules.Add(registration.module); registration.module.Start(m_context); } - var retainedPanelIds = new HashSet( - candidate.panels.Where(registration => existing.Contains(registration.panel)).Select(static registration => registration.attribute.id), + var retainedPanelIDs = new HashSet( + candidate.panels + .Where(registration => existing.Contains(registration.panel)) + .Select(static registration => registration.attribute.id), StringComparer.Ordinal ); - m_diagnostics.RetainPanels(retainedPanelIds); + m_diagnostics.RetainPanels(retainedPanelIDs); for (int i = 0; i < candidate.panels.Length; i++) { PanelRegistration registration = candidate.panels[i]; if (existing.Contains(registration.panel)) + { continue; + } activation.attachedPanels.Add(registration); candidate.attachedPanels.Add(registration.panel); try @@ -418,7 +277,9 @@ Snapshot candidate m_active = previous; m_staging = null; if (activation is null || !ReferenceEquals(activation.candidate, candidate)) + { return; + } List failures = []; AttemptCleanup(activation.handlers.Rollback, failures); AttemptCleanup(m_interactions.RollbackGenerationTransition, failures); @@ -429,57 +290,274 @@ Snapshot candidate candidate.attachedPanels.Remove(registration.panel); } - for (int i = activation.startedModules.Count - 1; i >= 0; i--) + for (int i = activation.startedModules.Count - 1; i >= 0; i--) + { + ModuleRegistration registration = activation.startedModules[i]; + AttemptCleanup(() => StopModule(registration, "activation rollback"), failures); + candidate.startedModules.Remove(registration.module); + } + + AttemptCleanup(() => RestorePrevious(activation), failures); + m_activation = null; + HashSet previousPanelIDs = previous is null ? new HashSet(StringComparer.Ordinal) : new HashSet( + GetAvailablePanels(previous).Select(static registration => registration.attribute.id), + StringComparer.Ordinal + ); + m_diagnostics.RetainPanels(previousPanelIDs); + m_diagnostics.Commit(); + ThrowCleanupFailures(failures); + } + + /// + /// Releases previous-generation state after the candidate becomes active. + /// + /// + /// The previous consumed by on activation completed; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The current snapshot consumed by on activation completed; ownership remains with the caller unless explicitly stated otherwise. + /// + protected override void OnActivationCompleted( + Snapshot? previous, + Snapshot currentSnapshot + ) { + ActivationState? activation = m_activation; + if (activation is null || !ReferenceEquals(activation.candidate, currentSnapshot)) + { + return; + } + activation.handlers.Complete(); + m_interactions.CompleteGenerationTransition(); + NotifyExtensionsChanged(); + m_staging = null; + m_activation = null; + } + + /// + /// Releases the generation lease retained by an immutable registry snapshot. + /// + /// + /// The immutable state snapshot consumed by this operation. + /// + protected override void DisposeSnapshot(Snapshot snapshot) + { + HashSet? retained = m_active is null ? null : new HashSet(m_active.instances, ReferenceEqualityComparer.Instance); + DisposeExtensions(snapshot.instances.Where(instance => retained?.Contains(instance) != true)); + } + + internal bool TryGetModule(out TModule? module) + where TModule : EditorModule + { + Snapshot? snapshot = m_active; + if (snapshot is not null) + { + foreach (ModuleRegistration registration in snapshot.modules) + { + if (registration.module is TModule candidate + && snapshot.startedModules.Contains(candidate) + && !snapshot.quarantinedModules.Contains(candidate) + ) { + module = candidate; + return true; + } + } + } + + module = null; + return false; + } + + internal void UpdateModules() + { + Snapshot snapshot = extensions; + for (int i = 0; i < snapshot.modules.Length; i++) + { + ModuleRegistration registration = snapshot.modules[i]; + if (snapshot.quarantinedModules.Contains(registration.module)) + { + continue; + } + try + { + registration.module.Update(m_context); + if (registration.module.blocksFollowingUpdates) + { + break; + } + } + catch (Exception exception) + { + snapshot.quarantinedModules.Add(registration.module); + LogError("Editor module '{0}' failed to update and was quarantined: {1}", registration.attribute.id, exception); + continue; + } + } + + m_state.Update(m_context.frame.totalTime, GetAvailableState(snapshot), GetAvailablePanels(snapshot)); + } + + internal void SaveState() + { + if (m_active is not null) + { + m_state.Save(GetAvailableState(m_active), GetAvailablePanels(m_active)); + } + } + + internal bool TryTogglePanel(string panelID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + Snapshot snapshot = extensions; + for (int i = 0; i < snapshot.panels.Length; i++) + { + PanelRegistration registration = snapshot.panels[i]; + if (!string.Equals(registration.attribute.id, panelID, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { + continue; + } + + registration.panel.isOpen = !registration.panel.isOpen; + if (registration.panel.isOpen) + { + m_pendingPanelFocus.Add(panelID); + } + else + { + m_pendingPanelFocus.Remove(panelID); + } + return true; + } + + return false; + } + + internal IReadOnlyList GetPanelDeclarations() => extensions.panelDeclarations; + + internal bool TryGetPanelState( + string panelID, + out bool isOpen + ) { + Snapshot snapshot = extensions; + foreach (PanelRegistration registration in snapshot.panels) + { + if (registration.attribute.id != panelID || snapshot.quarantinedPanels.Contains(registration.panel)) + { + continue; + } + isOpen = registration.panel.isOpen; + return true; + } + + isOpen = false; + return false; + } + + internal bool TryOpenPanel(string panelID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + Snapshot snapshot = extensions; + for (int i = 0; i < snapshot.panels.Length; i++) + { + PanelRegistration registration = snapshot.panels[i]; + if (!string.Equals(registration.attribute.id, panelID, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { + continue; + } + + registration.panel.isOpen = true; + m_pendingPanelFocus.Add(panelID); + return true; + } + + return false; + } + + internal bool TryClosePanel(string panelID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + Snapshot snapshot = extensions; + for (int i = 0; i < snapshot.panels.Length; i++) + { + PanelRegistration registration = snapshot.panels[i]; + if (!string.Equals(registration.attribute.id, panelID, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { + continue; + } + + registration.panel.isOpen = false; + m_pendingPanelFocus.Remove(panelID); + return true; + } + + return false; + } + + internal bool TakePanelFocusRequest(string panelID) => m_pendingPanelFocus.Remove(panelID); + + internal void PrepareShutdown() + { + if (m_active is not null) + { + m_state.PrepareShutdown(GetAvailableState(m_active), GetAvailablePanels(m_active)); + } + } + + internal ActionRegistration[] GetActionsForShutdown() => m_active?.actions ?? []; + + internal void QuarantinePanel( + Snapshot snapshot, + PanelRegistration registration, + Exception exception + ) { + ArgumentNullException.ThrowIfNull(snapshot); + ArgumentNullException.ThrowIfNull(registration); + ArgumentNullException.ThrowIfNull(exception); + if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedPanels.Add(registration.panel)) { - ModuleRegistration registration = activation.startedModules[i]; - AttemptCleanup(() => StopModule(registration, "activation rollback"), failures); - candidate.startedModules.Remove(registration.module); + return; } - - AttemptCleanup(() => RestorePrevious(activation), failures); - m_activation = null; - var previousPanelIds = previous is null ? new HashSet(StringComparer.Ordinal) : new HashSet( - GetAvailablePanels(previous).Select(static registration => registration.attribute.id), - StringComparer.Ordinal - ); - m_diagnostics.RetainPanels(previousPanelIds); + registration.panel.isOpen = false; + m_diagnostics.ReportPanelFailure(registration.attribute.id, exception); m_diagnostics.Commit(); - ThrowCleanupFailures(failures); + LogError("Editor panel '{0}' failed to draw and was quarantined: {1}", registration.attribute.id, exception); } - /// - /// Releases previous-generation state after the candidate becomes active. - /// - /// - /// The previous consumed by on activation completed; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The current snapshot consumed by on activation completed; ownership remains with the caller unless explicitly stated otherwise. - /// - protected override void OnActivationCompleted( - Snapshot? previous, - Snapshot currentSnapshot + internal void QuarantineModal( + Snapshot snapshot, + ModalRegistration registration, + Exception exception ) { - ActivationState? activation = m_activation; - if (activation is null || !ReferenceEquals(activation.candidate, currentSnapshot)) + ArgumentNullException.ThrowIfNull(snapshot); + ArgumentNullException.ThrowIfNull(registration); + ArgumentNullException.ThrowIfNull(exception); + if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedModals.Add(registration.modal)) + { return; - activation.handlers.Complete(); - m_interactions.CompleteGenerationTransition(); - NotifyExtensionsChanged(); - m_staging = null; - m_activation = null; + } + LogError("Editor modal '{0}' failed and was quarantined: {1}", registration.attribute.id, exception); } - /// - /// Releases the generation lease retained by an immutable registry snapshot. - /// - /// - /// The immutable state snapshot consumed by this operation. - /// - protected override void DisposeSnapshot(Snapshot snapshot) + internal void Shutdown(bool saveState = true) { - HashSet? retained = m_active is null ? null : new HashSet(m_active.instances, ReferenceEqualityComparer.Instance); - DisposeExtensions(snapshot.instances.Where(instance => retained?.Contains(instance) != true)); + List failures = []; + if (m_active is not null) + { + Snapshot active = m_active; + if (saveState) + { + AttemptCleanup(() => m_state.PrepareShutdown(GetAvailableState(active), GetAvailablePanels(active)), failures); + } + AttemptCleanup(() => Deactivate(active), failures); + } + + m_active = null; + NotifyExtensionsChanged(); + m_diagnostics.Dispose(); + m_state.ClearDiagnostics(); + ThrowCleanupFailures(failures); } private void Deactivate(Snapshot snapshot) @@ -489,7 +567,9 @@ private void Deactivate(Snapshot snapshot) { PanelRegistration registration = snapshot.panels[i]; if (!snapshot.attachedPanels.Contains(registration.panel)) + { continue; + } AttemptCleanup(() => DetachPanel(registration, "shutdown"), failures); snapshot.attachedPanels.Remove(registration.panel); } @@ -498,13 +578,17 @@ private void Deactivate(Snapshot snapshot) { ModuleRegistration registration = snapshot.modules[i]; if (!snapshot.startedModules.Contains(registration.module)) + { continue; + } AttemptCleanup(() => StopModule(registration, "shutdown"), failures); snapshot.startedModules.Remove(registration.module); } if (ReferenceEquals(m_active, snapshot)) + { m_active = null; + } m_diagnostics.RetainPanels(new HashSet(StringComparer.Ordinal)); m_diagnostics.Commit(); ThrowCleanupFailures(failures); @@ -520,7 +604,9 @@ ActivationState activation { PanelRegistration registration = previous.panels[i]; if (retained.Contains(registration.panel) || !previous.attachedPanels.Contains(registration.panel)) + { continue; + } activation.detachedPreviousPanels.Add(registration); DetachPanel(registration, "generation retirement"); previous.attachedPanels.Remove(registration.panel); @@ -541,7 +627,9 @@ private void RestorePrevious(ActivationState activation) { Snapshot? previous = activation.previous; if (previous is null) + { return; + } List failures = []; for (int i = activation.stoppedPreviousModules.Count - 1; i >= 0; i--) { @@ -583,20 +671,22 @@ private void RestorePrevious(ActivationState activation) private void CapturePanelStates() { if (m_active is not null) + { CapturePanelStates(m_active); + } } private void CapturePanelStates(Snapshot snapshot) { foreach (PanelRegistration registration in snapshot.panels) { - ReadOnlyMemory payload = registration.panel is IEditorPanelReloadState reloadable ? reloadable.CaptureReloadState().ToArray() : ReadOnlyMemory.Empty; + ReadOnlyMemory payload = registration.panel is IEditorPanelReloadState reloadable + ? reloadable.CaptureReloadState().ToArray() + : ReadOnlyMemory.Empty; m_panelStates[registration.attribute.id] = new PanelState(registration.panel.isOpen, payload); } } - private static StateRegistration[] GetAvailableState(Snapshot snapshot) => snapshot.state.Where(registration => registration.kind != StateOwnerKind.Panel || !snapshot.quarantinedPanels.Contains((EditorPanel)registration.owner)).Where(registration => registration.kind != StateOwnerKind.Module || !snapshot.quarantinedModules.Contains((EditorModule)registration.owner)).ToArray(); - private static PanelRegistration[] GetAvailablePanels(Snapshot snapshot) => snapshot.panels.Where(registration => !snapshot.quarantinedPanels.Contains(registration.panel)).ToArray(); private void StopModule( ModuleRegistration registration, string phase @@ -629,28 +719,12 @@ string phase } } - private static void AttemptCleanup( - Action action, - List failures - ) { - try - { - action(); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception exception) - { - failures.Add(exception); - } - } - private void ThrowCleanupFailures(List failures) { if (failures.Count == 0) + { return; + } var failure = new AggregateException("Editor extension lifecycle cleanup failed.", failures); ReportRetirementFailure(failure); throw failure; @@ -684,23 +758,6 @@ private void LogError( string message, params object? [] arguments ) => m_log.Write(LogLevel.Error, message, arguments); - private static IEnumerable CreateMenuSourceRegistrations( - Type type, - EditorExtensionActivator activator - ) { - EditorMenuSource source = activator.CreateExtension(type); - return type.GetCustomAttributes(false).Select(attribute => new MenuSourceRegistration(attribute.area, attribute.priority, type, source)); - } - - private static IEnumerable CreateDropRegistrations( - Type type, - EditorExtensionActivator activator - ) { - EditorDrop drop = activator.CreateExtension(type); - Type sourceType = drop.sourceType; - Type targetType = drop.targetType; - return type.GetCustomAttributes(false).Select(attribute => new DropRegistration(sourceType, targetType, attribute.area, attribute.priority, type, drop)); - } private PanelRegistration CreatePanelRegistration( Type type, @@ -712,7 +769,9 @@ EditorExtensionActivator activator { panel.isOpen = state.isOpen; if (panel is IEditorPanelReloadState reloadable && !state.payload.IsEmpty) + { reloadable.RestoreReloadState(state.payload); + } } else { @@ -722,28 +781,9 @@ EditorExtensionActivator activator return new PanelRegistration(attribute, type, panel); } - private static ModalRegistration CreateModalRegistration( - Type type, - EditorExtensionActivator activator - ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); - private static HistoryHandlerRegistration CreateHistoryHandlerRegistration( - Type type, - EditorExtensionActivator activator - ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); - private static void ValidateActions(ActionRegistration[] actions) - { - foreach (IGrouping<(string Action, string Area, Type? Target, int Priority), ActionRegistration> group in actions.GroupBy(static value => (value.attribute.action, value.attribute.area, value.targetType, value.attribute.priority))) - { - if (group.Count() > 1) - { - throw new InvalidOperationException($"Editor action '{group.Key.Action}' has conflicting registrations for area " + $"'{(string.IsNullOrEmpty(group.Key.Area) ? "*" : group.Key.Area)}' and target " + $"'{group.Key.Target?.FullName ?? "*"}'."); - } - } - } - private void ValidateShortcuts(ActionRegistration[] actions) { - var shortcuts = new List(); + List shortcuts = []; for (int actionIndex = 0; actionIndex < actions.Length; actionIndex++) { ActionRegistration registration = actions[actionIndex]; @@ -752,13 +792,11 @@ private void ValidateShortcuts(ActionRegistration[] actions) EditorShortcutAttribute shortcut = registration.shortcuts[shortcutIndex]; if (!string.IsNullOrEmpty(registration.attribute.area) && !string.IsNullOrEmpty(shortcut.area) - && !string.Equals( - registration.attribute.area, - shortcut.area, - StringComparison.Ordinal - )) - { - throw new InvalidOperationException($"Editor shortcut on '{registration.id}' targets area '{shortcut.area}', " + $"outside its action area '{registration.attribute.area}'."); + && !string.Equals(registration.attribute.area, shortcut.area, StringComparison.Ordinal) + ) { + throw new InvalidOperationException( + $"Editor shortcut on '{registration.id}' targets area '{shortcut.area}', " + $"outside its action area '{registration.attribute.area}'." + ); } string effectiveArea = string.IsNullOrEmpty(shortcut.area) ? registration.attribute.area : shortcut.area; @@ -775,25 +813,114 @@ private void ValidateShortcuts(ActionRegistration[] actions) bool sameAction = string.Equals(left.registration.id, right.registration.id, StringComparison.Ordinal); if (left.gesture != right.gesture || left.registration.attribute.priority != right.registration.attribute.priority - || !string.Equals( - left.area, - right.area, - StringComparison.Ordinal - ) - || !MayHaveEqualTargetSpecificity( - left.registration.targetType, - right.registration.targetType - )) - { + || !string.Equals(left.area, right.area, StringComparison.Ordinal) + || !MayHaveEqualTargetSpecificity(left.registration.targetType, right.registration.targetType) + ) { continue; } if (sameAction) { - throw new InvalidOperationException($"Editor action '{left.registration.id}' declares duplicate shortcut " + $"'{left.gesture}' for area '{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'."); + throw new InvalidOperationException( + $"Editor action '{left.registration.id}' declares duplicate shortcut " + $"'{left.gesture}' for area '{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'." + ); } - throw new InvalidOperationException($"Editor shortcut '{left.gesture}' is ambiguous between actions " + $"'{left.registration.id}' and '{right.registration.id}' for area " + $"'{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'."); + throw new InvalidOperationException( + $"Editor shortcut '{left.gesture}' is ambiguous between actions " + + $"'{left.registration.id}' and '{right.registration.id}' for area " + + $"'{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'." + ); + } + } + } + + private HotKeyGesture CreateShortcutGesture(EditorShortcutAttribute shortcut) + => shortcut.primary + ? HotKeyGesture.Primary(shortcut.key, m_context.keyboard, shortcut.modifiers) + : new HotKeyGesture(shortcut.key, shortcut.modifiers, m_context.keyboard.superModifierLabel); + + private static StateRegistration[] GetAvailableState(Snapshot snapshot) + => snapshot.state + .Where( + registration => ( + registration.kind != StateOwnerKind.Panel + || !snapshot.quarantinedPanels.Contains((EditorPanel)registration.owner) + ) + ) + .Where( + registration => ( + registration.kind != StateOwnerKind.Module + || !snapshot.quarantinedModules.Contains((EditorModule)registration.owner) + ) + ) + .ToArray(); + + private static PanelRegistration[] GetAvailablePanels(Snapshot snapshot) + => snapshot.panels.Where(registration => !snapshot.quarantinedPanels.Contains(registration.panel)).ToArray(); + + private static void AttemptCleanup( + Action action, + List failures + ) { + try + { + action(); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception exception) + { + failures.Add(exception); + } + } + + private static IEnumerable CreateMenuSourceRegistrations( + Type type, + EditorExtensionActivator activator + ) { + EditorMenuSource source = activator.CreateExtension(type); + return type + .GetCustomAttributes(false) + .Select(attribute => new MenuSourceRegistration(attribute.area, attribute.priority, type, source)); + } + + private static IEnumerable CreateDropRegistrations( + Type type, + EditorExtensionActivator activator + ) { + EditorDrop drop = activator.CreateExtension(type); + Type sourceType = drop.sourceType; + Type targetType = drop.targetType; + return type + .GetCustomAttributes(false) + .Select(attribute => new DropRegistration(sourceType, targetType, attribute.area, attribute.priority, type, drop)); + } + + private static ModalRegistration CreateModalRegistration( + Type type, + EditorExtensionActivator activator + ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); + + private static HistoryHandlerRegistration CreateHistoryHandlerRegistration( + Type type, + EditorExtensionActivator activator + ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); + + private static void ValidateActions(ActionRegistration[] actions) + { + foreach (IGrouping<(string action, string area, Type? target, int priority), ActionRegistration> group in actions.GroupBy( + static value => (value.attribute.action, value.attribute.area, value.targetType, value.attribute.priority) + )) { + if (group.Count() > 1) + { + throw new InvalidOperationException( + $"Editor action '{group.Key.action}' has conflicting registrations for area " + + $"'{(string.IsNullOrEmpty(group.Key.area) ? "*" : group.Key.area)}' and target " + + $"'{group.Key.target?.FullName ?? "*"}'." + ); } } } @@ -803,9 +930,13 @@ private static bool MayHaveEqualTargetSpecificity( Type? right ) { if (left == right) + { return true; + } if (left is null || right is null) + { return false; + } return left.IsInterface || right.IsInterface; } @@ -815,7 +946,9 @@ private static void ValidateToolbars(IReadOnlyList actions) { ActionRegistration registration = actions[actionIndex]; if (registration.toolbars.Length == 0) + { continue; + } if (registration.targetType is not null || registration.argumentType is not null) { throw new InvalidOperationException($"Editor toolbar action '{registration.id}' must not require a target or argument."); @@ -824,101 +957,132 @@ private static void ValidateToolbars(IReadOnlyList actions) for (int toolbarIndex = 0; toolbarIndex < registration.toolbars.Length; toolbarIndex++) { EditorToolbarItemAttribute toolbar = registration.toolbars[toolbarIndex]; - if (!string.IsNullOrEmpty(registration.attribute.area) && !string.Equals(registration.attribute.area, toolbar.area, StringComparison.Ordinal)) - { - throw new InvalidOperationException($"Editor toolbar placement on '{registration.id}' targets area '{toolbar.area}', " + $"outside its action area '{registration.attribute.area}'."); + if (!string.IsNullOrEmpty(registration.attribute.area) + && !string.Equals(registration.attribute.area, toolbar.area, StringComparison.Ordinal) + ) { + throw new InvalidOperationException( + $"Editor toolbar placement on '{registration.id}' targets area '{toolbar.area}', " + $"outside its action area '{registration.attribute.area}'." + ); } } } - IGrouping<(string id, string area), (string id, string area)>? duplicate = actions.SelectMany(static registration => registration.toolbars.Select(toolbar => (registration.id, toolbar.area))).GroupBy( - static placement => placement, - EqualityComparer<(string id, string area)>.Default - ).FirstOrDefault(static group => group.Count() > 1); + IGrouping<(string id, string area), (string id, string area)>? duplicate = actions + .SelectMany(static registration => registration.toolbars.Select(toolbar => (registration.id, toolbar.area))) + .GroupBy(static placement => placement, EqualityComparer<(string id, string area)>.Default) + .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) + { throw new InvalidOperationException($"Editor action '{duplicate.Key.id}' has duplicate toolbar placements."); + } } - private HotKeyGesture CreateShortcutGesture(EditorShortcutAttribute shortcut) => shortcut.primary ? HotKeyGesture.Primary( - shortcut.key, - m_context.keyboard, - shortcut.modifiers - ) : new HotKeyGesture( - shortcut.key, - shortcut.modifiers, - m_context.keyboard.superModifierLabel - ); private static void ValidateDrops(DropRegistration[] drops) { - foreach (IGrouping<(Type Source, Type Target, string Area, int Priority), DropRegistration> group in drops.GroupBy(static value => (value.sourceType, value.targetType, value.area, value.priority))) - { + foreach (IGrouping<(Type source, Type target, string area, int priority), DropRegistration> group in drops.GroupBy( + static value => (value.sourceType, value.targetType, value.area, value.priority) + )) { if (group.Count() > 1) + { throw new InvalidOperationException("Editor drop registrations contain an ambiguous match."); + } } } private static void ValidatePanels(PanelRegistration[] panels) { - string? duplicate = panels.GroupBy(static value => value.attribute.id, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = panels + .GroupBy(static value => value.attribute.id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor panel id '{duplicate}' is registered more than once."); + } } private static void ValidateModals(ModalRegistration[] modals) { - string? duplicate = modals.GroupBy(static value => value.attribute.id, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = modals + .GroupBy(static value => value.attribute.id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor modal id '{duplicate}' is registered more than once."); + } } private static void ValidateHistoryHandlers(HistoryHandlerRegistration[] handlers) { - string? duplicate = handlers.GroupBy(static value => value.attribute.kind, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = handlers + .GroupBy(static value => value.attribute.kind, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) { throw new InvalidOperationException($"Editor history handler kind '{duplicate}' is registered more than once."); } } - private static IReadOnlyDictionary CreateHistoryHandlerMap(IReadOnlyList handlers) - { + private static IReadOnlyDictionary CreateHistoryHandlerMap( + IReadOnlyList handlers + ) { var result = new Dictionary(handlers.Count, StringComparer.Ordinal); for (int i = 0; i < handlers.Count; i++) + { result.Add(handlers[i].attribute.kind, handlers[i].handler); + } return result; } - private static void ValidateExtensionIds( + private static void ValidateExtensionIDs( IReadOnlyList modules, IReadOnlyList panels ) { - string? duplicate = modules.Select(static value => value.attribute.id).Concat(panels.Select(static value => value.attribute.id)).GroupBy( - static id => id, - StringComparer.Ordinal - ).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = modules + .Select(static value => value.attribute.id) + .Concat(panels.Select(static value => value.attribute.id)) + .GroupBy(static id => id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor extension id '{duplicate}' is registered more than once."); + } } private static StateRegistration[] CreateStateRegistrations( IReadOnlyList modules, IReadOnlyList panels ) { - var result = new List(); + List result = []; for (int i = 0; i < modules.Count; i++) { ModuleRegistration module = modules[i]; - StateRegistration? registration = CreateStateRegistration(module.attribute.id, StateOwnerKind.Module, module.type, module.module, typeof(EditorModule)); + StateRegistration? registration = CreateStateRegistration( + module.attribute.id, + StateOwnerKind.Module, + module.type, + module.module, + typeof(EditorModule) + ); if (registration is not null) + { result.Add(registration); + } } for (int i = 0; i < panels.Count; i++) { PanelRegistration panel = panels[i]; - StateRegistration? registration = CreateStateRegistration(panel.attribute.id, StateOwnerKind.Panel, panel.type, panel.panel, typeof(EditorPanel)); + StateRegistration? registration = CreateStateRegistration( + panel.attribute.id, + StateOwnerKind.Panel, + panel.type, + panel.panel, + typeof(EditorPanel) + ); if (registration is not null) + { result.Add(registration); + } } return result.OrderBy(static value => value.id, StringComparer.Ordinal).ToArray(); @@ -931,24 +1095,32 @@ IReadOnlyList panels object owner, Type baseType ) { - const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + const BindingFlags C_FLAGS = BindingFlags.Instance | BindingFlags.NonPublic; MethodInfo capture = type.GetMethod( "Capture", - flags, + C_FLAGS, binder: null, [typeof(EditorState)], modifiers: null ) ?? throw new InvalidOperationException($"Editor extension '{type.FullName}' has no state capture hook."); if (capture.DeclaringType == baseType) + { return null; + } MethodInfo restore = type.GetMethod( "Restore", - flags, + C_FLAGS, binder: null, [typeof(EditorState)], modifiers: null ) ?? throw new InvalidOperationException($"Editor extension '{type.FullName}' has no state restore hook."); - return new StateRegistration(id, kind, owner, capture.CreateDelegate>(owner), restore.CreateDelegate>(owner)); + return new StateRegistration( + id, + kind, + owner, + capture.CreateDelegate>(owner), + restore.CreateDelegate>(owner) + ); } internal sealed record Snapshot( @@ -961,9 +1133,11 @@ internal sealed record Snapshot( HistoryHandlerRegistration[] historyHandlers, StateRegistration[] state, object[] instances - ) - { - internal IReadOnlyList panelDeclarations { get; } = Array.AsReadOnly(panels.Select(static registration => registration.attribute).ToArray()); + ) { + internal IReadOnlyList panelDeclarations { get; } = Array.AsReadOnly( + panels.Select(static registration => registration.attribute).ToArray() + ); + internal HashSet quarantinedModules { get; } = new(ReferenceEqualityComparer.Instance); internal HashSet quarantinedPanels { get; } = new(ReferenceEqualityComparer.Instance); internal HashSet quarantinedModals { get; } = new(ReferenceEqualityComparer.Instance); @@ -976,6 +1150,7 @@ internal sealed record ModuleRegistration( Type type, EditorModule module ); + internal sealed record ActionRegistration( EditorActionAttribute attribute, Type type, @@ -985,8 +1160,7 @@ internal sealed record ActionRegistration( EditorMenuAttribute[] menus, EditorToolbarItemAttribute[] toolbars, EditorShortcutAttribute[] shortcuts - ) - { + ) { internal string id { get; } = attribute.action; internal string? area { get; } = string.IsNullOrEmpty(attribute.area) ? null : attribute.area; } @@ -997,6 +1171,7 @@ internal sealed record MenuSourceRegistration( Type type, EditorMenuSource source ); + internal sealed record DropRegistration( Type sourceType, Type targetType, @@ -1005,21 +1180,25 @@ internal sealed record DropRegistration( Type type, EditorDrop drop ); + internal sealed record PanelRegistration( EditorPanelAttribute attribute, Type type, EditorPanel panel ); + internal sealed record ModalRegistration( EditorModalAttribute attribute, Type type, EditorModal modal ); + internal sealed record HistoryHandlerRegistration( EditorHistoryHandlerAttribute attribute, Type type, EditorHistoryHandler handler ); + internal sealed record StateRegistration( string id, StateOwnerKind kind, @@ -1027,6 +1206,7 @@ internal sealed record StateRegistration( Action capture, Action restore ); + internal enum StateOwnerKind { Module, @@ -1037,18 +1217,19 @@ private readonly record struct PanelState( bool isOpen, ReadOnlyMemory payload ); + private readonly record struct ShortcutValidationEntry( ActionRegistration registration, string area, HotKeyGesture gesture ); + private sealed class ActivationState( Snapshot? previous, Snapshot candidate, HashSet existing, EditorHistory.HandlerUpdate handlers - ) - { + ) { internal Snapshot? previous { get; } = previous; internal Snapshot candidate { get; } = candidate; internal HashSet existing { get; } = existing; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs index 75596c9bb..4ab461ae0 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; namespace Inno.Editor.Interactions; @@ -13,29 +12,44 @@ internal sealed class EditorExtensionDiagnosticPublisher : IDisposable private readonly Dictionary m_panelFailures = new(StringComparer.Ordinal); private string m_publishedState = string.Empty; + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + m_panelFailures.Clear(); + if (!string.IsNullOrEmpty(m_publishedState)) + { + Diagnostics.Clear(C_PANEL_ACTIVATION_GROUP); + } + m_publishedState = string.Empty; + } + internal void ReportPanelFailure( - string panelId, + string panelID, Exception exception ) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); ArgumentNullException.ThrowIfNull(exception); - m_panelFailures[panelId] = exception.Message; + m_panelFailures[panelID] = exception.Message; } - internal void ResolvePanel(string panelId) + internal void ResolvePanel(string panelID) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - m_panelFailures.Remove(panelId); + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + m_panelFailures.Remove(panelID); } - internal void RetainPanels(IReadOnlySet panelIds) + internal void RetainPanels(IReadOnlySet panelIDs) { - ArgumentNullException.ThrowIfNull(panelIds); + ArgumentNullException.ThrowIfNull(panelIDs); string[] removed = m_panelFailures.Keys - .Where(id => !panelIds.Contains(id)) + .Where(id => !panelIDs.Contains(id)) .ToArray(); for (int i = 0; i < removed.Length; i++) + { m_panelFailures.Remove(removed[i]); + } } internal void Commit() @@ -43,7 +57,9 @@ internal void Commit() if (m_panelFailures.Count == 0) { if (!string.IsNullOrEmpty(m_publishedState)) + { Diagnostics.Clear(C_PANEL_ACTIVATION_GROUP); + } m_publishedState = string.Empty; return; } @@ -53,23 +69,16 @@ internal void Commit() .ToArray(); string state = string.Join('\n', failures.Select(static pair => $"{pair.Key}:{pair.Value}")); if (string.Equals(m_publishedState, state, StringComparison.Ordinal)) + { return; + } Diagnostics.Set( C_PANEL_ACTIVATION_GROUP, failures.Select(static pair => Diagnostic.Error( "EDITOR-PANEL", - $"Panel '{pair.Key}' failed to attach: {pair.Value}"))); + $"Panel '{pair.Key}' failed to attach: {pair.Value}" + )) + ); m_publishedState = state; } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - m_panelFailures.Clear(); - if (!string.IsNullOrEmpty(m_publishedState)) - Diagnostics.Clear(C_PANEL_ACTIVATION_GROUP); - m_publishedState = string.Empty; - } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs index 865da8e5d..e82ee3214 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs @@ -22,7 +22,7 @@ out int distance } var visited = new HashSet { actualType }; - var queue = new Queue<(Type Type, int Distance)>(); + var queue = new Queue<(Type type, int distance)>(); queue.Enqueue((actualType, 0)); while (queue.Count > 0) { @@ -40,7 +40,9 @@ out int distance foreach (Type interfaceType in type.GetInterfaces()) { if (!visited.Add(interfaceType)) + { continue; + } if (interfaceType == registeredType) { distance = currentDistance + 1; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs index dc91c87d3..a2f96024e 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs @@ -12,27 +12,27 @@ public sealed class EditorDocumentContext private readonly Dictionary m_viewParameters = new(StringComparer.Ordinal); internal EditorDocumentContext( - Guid documentId, - Guid assetId, + Guid documentID, + Guid assetID, string assetPath, - string providerId + string providerID ) { - this.documentId = documentId; - this.assetId = assetId; + this.documentID = documentID; + this.assetID = assetID; this.assetPath = assetPath; - this.providerId = providerId; - title = Path.GetFileName(assetPath); + this.providerID = providerID; + this.title = Path.GetFileName(assetPath); } /// /// Gets the stable identity of this open source document. /// - public Guid documentId { get; } + public Guid documentID { get; } /// /// Gets the persistent asset identity, or an empty value before the source has one. /// - public Guid assetId { get; } + public Guid assetID { get; } /// /// Gets the normalized project asset path. @@ -42,7 +42,7 @@ string providerId /// /// Gets the stable provider identity used to recover across extension reload. /// - public string providerId { get; } + public string providerID { get; } /// /// Gets or sets the author-facing source title used by diagnostics and dedicated editors. @@ -101,5 +101,4 @@ out string value ArgumentException.ThrowIfNullOrWhiteSpace(key); return m_viewParameters.TryGetValue(key, out value!); } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs index c42f94cb9..f591d26b0 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs @@ -1,15 +1,22 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Inno.Core.Events; namespace Inno.Editor.Interactions; + internal sealed class EditorDocumentService : IEditorDocumentService { private readonly List m_documents = []; private readonly Dictionary m_providers = new(StringComparer.Ordinal); private readonly EventDispatcher m_events; - internal EditorDocumentService(EventDispatcher events) => m_events = events; + + internal EditorDocumentService(EventDispatcher events) + { + m_events = events; + } + /// /// Gets an immutable snapshot of currently owned source documents. /// @@ -29,13 +36,17 @@ public IDisposable RegisterProvider(EditorDocumentProvider provider) ArgumentNullException.ThrowIfNull(provider); ArgumentException.ThrowIfNullOrWhiteSpace(provider.id); if (!m_providers.TryAdd(provider.id, provider)) + { throw new InvalidOperationException($"Editor document provider '{provider.id}' is already registered."); + } try { - foreach (EditorDocumentContext document in m_documents.Where(document => document.providerId == provider.id).ToArray()) + foreach (EditorDocumentContext document in m_documents.Where(document => document.providerID == provider.id).ToArray()) { if (!m_documents.Contains(document)) + { continue; + } document.isProviderAvailable = true; provider.Open(document); } @@ -55,7 +66,7 @@ public IDisposable RegisterProvider(EditorDocumentProvider provider) /// /// The asset path text validated by the open operation. /// - /// + /// /// Persistent asset identity used for single-instance matching, or an empty value to match by path. /// /// @@ -63,15 +74,19 @@ public IDisposable RegisterProvider(EditorDocumentProvider provider) /// public EditorDocumentContext Open( string assetPath, - Guid assetId = default + Guid assetID = default ) { string normalizedPath = NormalizePath(assetPath); - EditorDocumentContext? identityOwner = assetId == Guid.Empty ? null : m_documents.FirstOrDefault(document => document.assetId == assetId); + EditorDocumentContext? identityOwner = assetID == Guid.Empty + ? null + : m_documents.FirstOrDefault(document => document.assetID == assetID); EditorDocumentContext? pathOwner = FindPathOwner(normalizedPath); if (identityOwner is not null && pathOwner is not null && !ReferenceEquals(identityOwner, pathOwner)) + { RetireStalePathOwner(pathOwner, normalizedPath); + } EditorDocumentContext? existing = identityOwner ?? pathOwner; - if (existing is not null && assetId != Guid.Empty && existing.assetId != assetId) + if (existing is not null && assetID != Guid.Empty && existing.assetID != assetID) { RetireStalePathOwner(existing, normalizedPath); existing = null; @@ -79,15 +94,16 @@ public EditorDocumentContext Open( if (existing is not null) { - _ = UpdateAssetPath(existing.documentId, normalizedPath); + _ = UpdateAssetPath(existing.documentID, normalizedPath); return existing; } EditorDocumentProvider provider = m_providers.Values.OrderBy( static candidate => candidate.id, StringComparer.Ordinal - ).FirstOrDefault(candidate => candidate.CanOpen(normalizedPath)) ?? throw new InvalidOperationException($"No editor document provider can open '{normalizedPath}'."); - var context = new EditorDocumentContext(Guid.NewGuid(), assetId, normalizedPath, provider.id) + ).FirstOrDefault(candidate => candidate.CanOpen(normalizedPath)) + ?? throw new InvalidOperationException($"No editor document provider can open '{normalizedPath}'."); + var context = new EditorDocumentContext(Guid.NewGuid(), assetID, normalizedPath, provider.id) { isProviderAvailable = true }; @@ -108,7 +124,7 @@ public EditorDocumentContext Open( /// /// Updates asset path state from the current authoritative inputs. /// - /// + /// /// The document id consumed by update asset path; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -118,51 +134,62 @@ public EditorDocumentContext Open( /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool UpdateAssetPath( - Guid documentId, + Guid documentID, string assetPath ) { - EditorDocumentContext? document = Find(documentId); + EditorDocumentContext? document = Find(documentID); if (document is null) + { return false; + } string path = NormalizePath(assetPath); - if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider) && !provider.CanOpen(path)) + if (m_providers.TryGetValue(document.providerID, out EditorDocumentProvider? provider) && !provider.CanOpen(path)) + { throw new ArgumentException("The new source path is not supported by this document provider.", nameof(assetPath)); - EditorDocumentContext? pathOwner = FindPathOwner(path, documentId); + } + EditorDocumentContext? pathOwner = FindPathOwner(path, documentID); if (pathOwner is not null) + { RetireStalePathOwner(pathOwner, path); - bool defaultTitle = document.title == System.IO.Path.GetFileName(document.assetPath); + } + bool defaultTitle = document.title == Path.GetFileName(document.assetPath); document.assetPath = path; if (defaultTitle) - document.title = System.IO.Path.GetFileName(path); + { + document.title = Path.GetFileName(path); + } return true; } /// /// Updates whether an open document differs from its saved authoring baseline. /// - /// + /// /// Stable identity of the open document to mark. /// /// /// True when the provider retains unsaved changes. /// public void SetDirty( - Guid documentId, + Guid documentID, bool isDirty = true - ) => Get(documentId).isDirty = isDirty; + ) => Get(documentID).isDirty = isDirty; + /// /// Persists the supplied value through the configured storage contract. /// - /// + /// /// Stable identity of the open document to save. /// /// /// when the owning provider saved the document. /// - public bool Save(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Save(context), clearDirty: true); + public bool Save(Guid documentID) + => Invoke(documentID, static ( + provider, + context + ) => provider.Save(context), clearDirty: true); + /// /// Saves every dirty document through its owning provider. /// @@ -174,8 +201,10 @@ public bool SaveAll() bool succeeded = true; foreach (EditorDocumentContext document in m_documents.ToArray()) { - if (document.isDirty && !Save(document.documentId)) + if (document.isDirty && !Save(document.documentID)) + { succeeded = false; + } } return succeeded; @@ -184,33 +213,37 @@ public bool SaveAll() /// /// Applies a validated change atomically at the caller-controlled commit point. /// - /// + /// /// Stable identity of the open document whose staged state should be applied. /// /// /// when the owning provider applied the staged state. /// - public bool Apply(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Apply(context), clearDirty: true); + public bool Apply(Guid documentID) + => Invoke(documentID, static ( + provider, + context + ) => provider.Apply(context), clearDirty: true); + /// /// Reverts one open document through its owning provider. /// - /// + /// /// Stable identity of the open document to revert. /// /// /// when the owning provider restored the saved state. /// - public bool Revert(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Revert(context), clearDirty: true); + public bool Revert(Guid documentID) + => Invoke(documentID, static ( + provider, + context + ) => provider.Revert(context), clearDirty: true); + /// /// Closes the requested resource and releases its operation-scoped state. /// - /// + /// /// Stable identity of the open document to close. /// /// @@ -220,19 +253,27 @@ public bool Revert(Guid documentId) => Invoke(documentId, static ( /// when the document closed under the requested dirty-state policy. /// public bool Close( - Guid documentId, + Guid documentID, EditorDocumentCloseMode mode ) { m_events.Emit(new EditorOperationPreparingEvent()); - EditorDocumentContext? document = Find(documentId); + EditorDocumentContext? document = Find(documentID); if (document is null || mode == EditorDocumentCloseMode.Cancel) + { return false; - if (document.isDirty && mode == EditorDocumentCloseMode.Save && !Save(documentId)) + } + if (document.isDirty && mode == EditorDocumentCloseMode.Save && !Save(documentID)) + { return false; + } if (document.isDirty && mode != EditorDocumentCloseMode.Discard && mode != EditorDocumentCloseMode.Save) + { return false; - if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + } + if (m_providers.TryGetValue(document.providerID, out EditorDocumentProvider? provider)) + { provider.Close(document); + } m_documents.Remove(document); return true; } @@ -241,8 +282,10 @@ internal void Shutdown() { foreach (EditorDocumentContext document in m_documents.ToArray()) { - if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + if (m_providers.TryGetValue(document.providerID, out EditorDocumentProvider? provider)) + { provider.Close(document); + } } m_documents.Clear(); @@ -250,48 +293,55 @@ internal void Shutdown() } private bool Invoke( - Guid documentId, + Guid documentID, Func operation, bool clearDirty ) { m_events.Emit(new EditorOperationPreparingEvent()); - EditorDocumentContext document = Get(documentId); - if (!m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + EditorDocumentContext document = Get(documentID); + if (!m_providers.TryGetValue(document.providerID, out EditorDocumentProvider? provider)) + { return false; + } bool succeeded = operation(provider, document); if (succeeded && clearDirty) + { document.isDirty = false; + } return succeeded; } - private EditorDocumentContext Get(Guid documentId) => Find(documentId) ?? throw new ArgumentException($"Editor document '{documentId}' is not open.", nameof(documentId)); - private EditorDocumentContext? Find(Guid documentId) => m_documents.FirstOrDefault(document => document.documentId == documentId); + private EditorDocumentContext Get(Guid documentID) + => Find(documentID) ?? throw new ArgumentException($"Editor document '{documentID}' is not open.", nameof(documentID)); + + private EditorDocumentContext? Find(Guid documentID) => m_documents.FirstOrDefault(document => document.documentID == documentID); + private EditorDocumentContext? FindPathOwner( string assetPath, - Guid excludedDocumentId = default - ) => m_documents.FirstOrDefault(document => document.documentId != excludedDocumentId && string.Equals(document.assetPath, assetPath, StringComparison.Ordinal)); + Guid excludedDocumentID = default + ) => m_documents.FirstOrDefault( + document => document.documentID != excludedDocumentID && string.Equals(document.assetPath, assetPath, StringComparison.Ordinal) + ); + private void RetireStalePathOwner( EditorDocumentContext document, string destinationPath ) { if (document.isDirty) { - throw new InvalidOperationException($"Open document '{document.title}' has unsaved changes for '{destinationPath}'. " + "Save, revert, or close it before assigning that source path to another asset identity."); + throw new InvalidOperationException( + $"Open document '{document.title}' has unsaved changes for '{destinationPath}'. " + "Save, revert, or close it before assigning that source path to another asset identity." + ); } - if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + if (m_providers.TryGetValue(document.providerID, out EditorDocumentProvider? provider)) + { provider.Close(document); + } if (!m_documents.Remove(document)) + { return; - } - - private static string NormalizePath(string assetPath) - { - ArgumentException.ThrowIfNullOrWhiteSpace(assetPath); - string normalized = assetPath.Replace('\\', '/').Trim(); - while (normalized.StartsWith("./", StringComparison.Ordinal)) - normalized = normalized[2..]; - return normalized; + } } private void Unregister(EditorDocumentProvider provider) @@ -302,8 +352,21 @@ private void Unregister(EditorDocumentProvider provider) } m_providers.Remove(provider.id); - foreach (EditorDocumentContext document in m_documents.Where(document => document.providerId == provider.id)) + foreach (EditorDocumentContext document in m_documents.Where(document => document.providerID == provider.id)) + { document.isProviderAvailable = false; + } + } + + private static string NormalizePath(string assetPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(assetPath); + string normalized = assetPath.Replace('\\', '/').Trim(); + while (normalized.StartsWith("./", StringComparison.Ordinal)) + { + normalized = normalized[2..]; + } + return normalized; } private sealed class ProviderLease( @@ -312,6 +375,7 @@ EditorDocumentProvider provider ) : IDisposable { private EditorDocumentService? m_owner = owner; + /// /// Releases the resources owned by this instance. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs index 8b217266a..2161a6dac 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs @@ -3,25 +3,6 @@ namespace Inno.Editor.Interactions; -/// -/// Selects how a dirty document responds to a close request. -/// -public enum EditorDocumentCloseMode -{ - /// - /// Keeps the document open. - /// - Cancel, - /// - /// Closes the document after saving. - /// - Save, - /// - /// Closes the document and discards unsaved state. - /// - Discard -} - /// /// Owns single-instance editor documents independently from reloadable providers and presentation. /// @@ -49,7 +30,7 @@ public interface IEditorDocumentService /// /// Project asset path. /// - /// + /// /// Persistent asset identity when available. /// /// @@ -57,13 +38,13 @@ public interface IEditorDocumentService /// EditorDocumentContext Open( string assetPath, - Guid assetId = default + Guid assetID = default ); /// /// Updates an open document's source location after an identity-preserving asset move, without changing history or focus. /// - /// + /// /// Existing document identity. /// /// @@ -73,34 +54,34 @@ EditorDocumentContext Open( /// Whether the document exists. /// bool UpdateAssetPath( - Guid documentId, + Guid documentID, string assetPath ); /// /// Updates a document's unsaved state without saving, discarding or changing its History. /// - /// + /// /// Stable tab identity. /// /// /// Whether the provider's current draft differs from its saved baseline. /// void SetDirty( - Guid documentId, + Guid documentID, bool isDirty = true ); /// /// Saves one open document through its current provider. /// - /// + /// /// Stable tab identity. /// /// /// when the document is saved. /// - bool Save(Guid documentId); + bool Save(Guid documentID); /// /// Saves every dirty open document. @@ -113,29 +94,29 @@ void SetDirty( /// /// Applies staged changes through the current provider. /// - /// + /// /// Stable tab identity. /// /// /// when changes are applied. /// - bool Apply(Guid documentId); + bool Apply(Guid documentID); /// /// Reverts staged changes through the current provider. /// - /// + /// /// Stable tab identity. /// /// /// when changes are reverted. /// - bool Revert(Guid documentId); + bool Revert(Guid documentID); /// /// Closes one document using an explicit dirty-document decision. /// - /// + /// /// Stable tab identity. /// /// @@ -145,8 +126,26 @@ void SetDirty( /// when the document closed. /// bool Close( - Guid documentId, + Guid documentID, EditorDocumentCloseMode mode ); +} +/// +/// Selects how a dirty document responds to a close request. +/// +public enum EditorDocumentCloseMode +{ + /// + /// Keeps the document open. + /// + Cancel, + /// + /// Closes the document after saving. + /// + Save, + /// + /// Closes the document and discards unsaved state. + /// + Discard } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs index c5b581331..c84806e83 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -36,11 +35,14 @@ public EditorDragContext( string area, EditorDragData data ) { - this.editor = editor ?? throw new ArgumentNullException(nameof(editor)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(data); + this.editor = editor; + this.interactions = interactions; ArgumentException.ThrowIfNullOrWhiteSpace(area); this.area = area; - this.data = data ?? throw new ArgumentNullException(nameof(data)); + this.data = data; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs index b09cc243d..c02083c37 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; namespace Inno.Editor.Interactions; @@ -29,9 +28,10 @@ public EditorDragData( string label ) { ArgumentNullException.ThrowIfNull(source); - sourceIdentity = source.identity.runtimeIdentity - ?? throw new InvalidOperationException( - "An editor drag source must be registered in a live identity domain."); + this.sourceIdentity = source.identity.runtimeIdentity + ?? throw new InvalidOperationException( + "An editor drag source must be registered in a live identity domain." + ); this.label = label ?? string.Empty; } @@ -44,5 +44,4 @@ string label /// Gets the drag preview label. /// public string label { get; } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs index a0159c719..92275460a 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs @@ -1,7 +1,5 @@ using System; - using Inno.Core.Identity; -using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -79,8 +77,8 @@ public sealed override EditorDropStatus Query(EditorDropContext context) { ArgumentNullException.ThrowIfNull(context); return context.source is TSource source && context.target is TTarget target - ? Query(new EditorDropContext(context, source, target)) - : EditorDropStatus.rejected; + ? Query(new EditorDropContext(context, source, target)) + : EditorDropStatus.rejected; } /// @@ -96,7 +94,9 @@ public sealed override EditorDropResult Drop(EditorDropContext context) { ArgumentNullException.ThrowIfNull(context); if (context.source is not TSource source || context.target is not TTarget target) + { return EditorDropResult.rejected; + } return Drop(new EditorDropContext(context, source, target)); } @@ -122,62 +122,3 @@ public sealed override EditorDropResult Drop(EditorDropContext context) /// protected abstract EditorDropResult Drop(EditorDropContext context); } - -/// -/// Provides strongly typed source and target values to a drop operation. -/// -/// -/// The managed drag-source type. -/// -/// -/// The managed drop-target type. -/// -public sealed class EditorDropContext - where TSource : class - where TTarget : class -{ - internal EditorDropContext( - EditorDropContext context, - TSource source, - TTarget target - ) { - untyped = context; - this.source = source; - this.target = target; - } - - /// - /// Gets the untyped drop context. - /// - public EditorDropContext untyped { get; } - - /// - /// Gets the active editor context. - /// - public EditorContext editor => untyped.editor; - - /// - /// Gets the active interaction entry point. - /// - public EditorInteractions interactions => untyped.interactions; - - /// - /// Gets the interaction area. - /// - public string area => untyped.area; - - /// - /// Gets the typed drag source. - /// - public TSource source { get; } - - /// - /// Gets the typed drop target. - /// - public TTarget target { get; } - - /// - /// Gets the requested placement. - /// - public EditorDropPlacement placement => untyped.placement; -} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs index 123191354..3a244b14d 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs @@ -15,9 +15,7 @@ public sealed class EditorDropAttribute : Attribute /// The tie-breaking priority used after source and target specificity. /// public EditorDropAttribute(int priority = 0) - : this(string.Empty, priority) - { - } + : this(string.Empty, priority) {} /// /// Creates a drop registration scoped to an exact interaction area. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs index 369f8ac8d..4861234d5 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; using Inno.Editor.Core; @@ -50,13 +49,18 @@ public EditorDropContext( object target, EditorDropPlacement placement = EditorDropPlacement.None ) { - this.editor = editor ?? throw new ArgumentNullException(nameof(editor)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + this.editor = editor; + this.interactions = interactions; ArgumentException.ThrowIfNullOrWhiteSpace(area); this.area = area; - this.data = data ?? throw new ArgumentNullException(nameof(data)); - this.source = source ?? throw new ArgumentNullException(nameof(source)); - this.target = target ?? throw new ArgumentNullException(nameof(target)); + this.data = data; + this.source = source; + this.target = target; this.placement = placement; } @@ -95,3 +99,62 @@ public EditorDropContext( /// public EditorDropPlacement placement { get; } } + +/// +/// Provides strongly typed source and target values to a drop operation. +/// +/// +/// The managed drag-source type. +/// +/// +/// The managed drop-target type. +/// +public sealed class EditorDropContext + where TSource : class + where TTarget : class +{ + internal EditorDropContext( + EditorDropContext context, + TSource source, + TTarget target + ) { + this.untyped = context; + this.source = source; + this.target = target; + } + + /// + /// Gets the untyped drop context. + /// + public EditorDropContext untyped { get; } + + /// + /// Gets the active editor context. + /// + public EditorContext editor => untyped.editor; + + /// + /// Gets the active interaction entry point. + /// + public EditorInteractions interactions => untyped.interactions; + + /// + /// Gets the interaction area. + /// + public string area => untyped.area; + + /// + /// Gets the typed drag source. + /// + public TSource source { get; } + + /// + /// Gets the typed drop target. + /// + public TTarget target { get; } + + /// + /// Gets the requested placement. + /// + public EditorDropPlacement placement => untyped.placement; +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs index 1ecb5d6a2..079065745 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs @@ -9,17 +9,14 @@ public enum EditorDropPlacement /// No positional placement is requested. /// None, - /// /// Insert before the target. /// Before, - /// /// Drop into the target. /// Into, - /// /// Insert after the target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs index db6529916..b2f7e5182 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs @@ -62,6 +62,5 @@ public EditorDropResult( public static EditorDropResult Accepted( object? selectionTarget = null, object? revealTarget = null - ) - => new(true, selectionTarget, revealTarget); + ) => new(true, selectionTarget, revealTarget); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs index 4c531762c..47083d291 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Identity; using Inno.Core.Logging; @@ -8,7 +7,7 @@ namespace Inno.Editor.Interactions; internal sealed class EditorDropRouter( EditorExtensionCatalog catalog, - IReadOnlyDictionary identityDomains, + IReadOnlyDictionary identityDomains, Logger log ) { private readonly HashSet m_queryFailures = new(StringComparer.Ordinal); @@ -19,7 +18,9 @@ internal RuntimeIdentity Begin(EditorDragContext context) ArgumentNullException.ThrowIfNull(context); RuntimeIdentity identity = context.data.sourceIdentity; if (Resolve(identity) is null) + { throw new InvalidOperationException("The editor drag source is no longer registered."); + } m_activeIdentity = identity; return identity; } @@ -29,20 +30,24 @@ internal bool TryGetSource( out IdentityObject? source ) { source = m_activeIdentity == identity - ? Resolve(identity) - : null; + ? Resolve(identity) + : null; if (source is not null) + { return true; + } if (m_activeIdentity == identity) + { Cancel(); + } return false; } internal bool TryGetActiveIdentity(out RuntimeIdentity identity) { - if (m_activeIdentity is not RuntimeIdentity active || - Resolve(active) is null) - { + if (m_activeIdentity is not RuntimeIdentity active + || Resolve(active) is null + ) { Cancel(); identity = default; return false; @@ -55,9 +60,11 @@ internal EditorDropStatus Query( RuntimeIdentity identity, EditorDropContext context ) { - if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) || - registration is null) + if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) + || registration is null + ) { return EditorDropStatus.rejected; + } try { EditorDropStatus status = registration.drop.Query(context); @@ -69,7 +76,9 @@ EditorDropContext context { string dropName = registration.type.FullName ?? registration.type.Name; if (m_queryFailures.Add(dropName)) + { log.Write(LogLevel.Error, "Editor drop query failed: {0}", [exception]); + } return EditorDropStatus.rejected; } } @@ -78,16 +87,22 @@ internal EditorDropResult Drop( RuntimeIdentity identity, EditorDropContext context ) { - if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) || - registration is null) + if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) + || registration is null + ) { return EditorDropResult.rejected; + } try { if (!registration.drop.Query(context).canDrop) + { return EditorDropResult.rejected; + } EditorDropResult result = registration.drop.Drop(context); if (result.accepted) + { Cancel(); + } return result; } catch (Exception exception) @@ -124,20 +139,22 @@ out EditorExtensionCatalog.DropRegistration? best { bool exactArea = !string.IsNullOrEmpty(registration.area); if (exactArea && !string.Equals(registration.area, context.area, StringComparison.Ordinal)) - continue; - if (!EditorTypeDistance.TryGet(sourceType, registration.sourceType, out int sourceDistance) || - !EditorTypeDistance.TryGet(targetType, registration.targetType, out int targetDistance)) { continue; } - if (best is null || - exactArea && string.IsNullOrEmpty(best.area) || - exactArea == !string.IsNullOrEmpty(best.area) && - (sourceDistance < bestSourceDistance || - sourceDistance == bestSourceDistance && targetDistance < bestTargetDistance || - sourceDistance == bestSourceDistance && targetDistance == bestTargetDistance && - registration.priority > best.priority)) - { + if (!EditorTypeDistance.TryGet(sourceType, registration.sourceType, out int sourceDistance) + || !EditorTypeDistance.TryGet(targetType, registration.targetType, out int targetDistance) + ) { + continue; + } + if (best is null + || exactArea && string.IsNullOrEmpty(best.area) + || exactArea == !string.IsNullOrEmpty(best.area) + && (sourceDistance < bestSourceDistance + || sourceDistance == bestSourceDistance && targetDistance < bestTargetDistance + || sourceDistance == bestSourceDistance && targetDistance == bestTargetDistance + && registration.priority > best.priority) + ) { best = registration; bestSourceDistance = sourceDistance; bestTargetDistance = targetDistance; @@ -147,7 +164,7 @@ out EditorExtensionCatalog.DropRegistration? best } private IdentityObject? Resolve(RuntimeIdentity identity) - => identityDomains.TryGetValue(identity.domainId, out IdentityAllocator? allocator) - ? allocator.Get(identity) - : null; + => identityDomains.TryGetValue(identity.domainID, out IdentityAllocator? allocator) + ? allocator.Get(identity) + : null; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs index 4bfcec4a1..5357bce08 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs @@ -9,22 +9,18 @@ public enum EditorDropVisual /// No visual is drawn. /// None, - /// /// Draw a content highlight. /// Highlight, - /// /// Draw an insertion line before the target. /// InsertBefore, - /// /// Draw an insertion line after the target. /// InsertAfter, - /// /// Draw a disabled target visual. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs index 5268bad6c..59b03762a 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs @@ -1,12 +1,14 @@ using System; namespace Inno.Editor.Interactions; + /// /// Owns one continuous edit transaction without retaining edited objects, setters or extension instances. /// public sealed class EditorEditGesture : IDisposable { private EditorHistoryTransaction? m_transaction; + /// /// Begins an edit whose updates use the existing domain mutation and History protocols. /// @@ -28,13 +30,14 @@ string name ) { ArgumentNullException.ThrowIfNull(history); m_transaction = history.BeginTransaction(name); - mergeKey = "gesture:" + m_transaction.id.ToString("N"); + this.mergeKey = "gesture:" + m_transaction.id.ToString("N"); } /// /// Gets the transient merge boundary shared only by updates within this gesture. /// public string mergeKey { get; } + /// /// Gets whether this gesture still owns an active transaction, including a rejected completion. /// @@ -85,12 +88,17 @@ public EditorHistoryResult Cancel() public void Dispose() { if (m_transaction is null) + { return; + } EditorHistoryResult result = Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The edit gesture could not roll back: {result.message}"); + } GC.SuppressFinalize(this); } - private EditorHistoryTransaction RequireTransaction() => m_transaction ?? throw new InvalidOperationException("The edit gesture has already finished."); + private EditorHistoryTransaction RequireTransaction() + => m_transaction ?? throw new InvalidOperationException("The edit gesture has already finished."); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs index a6472e6f0..25e278707 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs @@ -1,6 +1,7 @@ using Inno.Core.Events; namespace Inno.Editor.Interactions; + /// /// Synchronously closes transient edits before command execution or an extension-handler generation switch. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIds.cs b/src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIDs.cs similarity index 87% rename from src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIds.cs rename to src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIDs.cs index 4f7ed9c55..305081204 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIds.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/EditorBuiltInInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Interactions; -internal static class EditorBuiltInInteractionIds +internal static class EditorBuiltInInteractionIDs { internal const string C_CLEAR_SELECTION = "editor/clear-selection"; internal const string C_GLOBAL_AREA = "editor/global"; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs index f46671a4f..5bd2d0134 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs @@ -5,24 +5,30 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Owns the bounded, transactional Undo and Redo history for one editor runtime. /// internal sealed class EditorHistory : IEditorHistory, IDisposable { - private List m_undo = []; - private List m_redo = []; private readonly Stack m_transactions = []; private readonly EditorHistoryOptions m_options; private readonly EditorHistoryBlobStore m_blobStore; private readonly Logger m_log; - private IReadOnlyDictionary m_handlers = new Dictionary(StringComparer.Ordinal); + private List m_undo = []; + private List m_redo = []; + + private IReadOnlyDictionary m_handlers = new Dictionary( + StringComparer.Ordinal + ); + private EditorHistoryContext? m_context; private IsolationState? m_isolation; private bool m_isTransitioning; private bool m_isFaulted; private string? m_faultReason; private bool m_isDisposed; + /// /// Creates an empty history with explicit entry, resident-memory, and temporary-disk budgets. /// @@ -43,10 +49,11 @@ internal EditorHistory( Logger log ) { ArgumentNullException.ThrowIfNull(options); - m_log = log ?? throw new ArgumentNullException(nameof(log)); + ArgumentNullException.ThrowIfNull(log); + m_log = log; options.Validate(); m_options = options; - capacity = options.maxEntries; + this.capacity = options.maxEntries; m_blobStore = new EditorHistoryBlobStore(options.cacheDirectory); } @@ -54,70 +61,72 @@ Logger log /// Gets the maximum number of committed top-level operations retained by this history. /// public int capacity { get; } + /// /// Gets whether a previous operation is currently available and permits Undo. /// public bool canUndo => !m_isFaulted && !m_isTransitioning && m_transactions.Count == 0 && m_undo.Count > 0 && m_undo[^1].canUndo; + /// /// Gets whether a reverted operation is currently available and permits Redo. /// public bool canRedo => !m_isFaulted && !m_isTransitioning && m_transactions.Count == 0 && m_redo.Count > 0 && m_redo[^1].canRedo; + /// /// Gets whether a failed compensation left the domain state indeterminate. /// public bool isFaulted => m_isFaulted; + /// /// Gets the diagnostic that faulted this history, or while the history is healthy. /// public string? faultReason => m_faultReason; + /// /// Gets the next operation name displayed by the Undo command, or when unavailable. /// public string? undoName => m_undo.Count == 0 ? null : m_undo[^1].name; + /// /// Gets the next operation name displayed by the Redo command, or when unavailable. /// public string? redoName => m_redo.Count == 0 ? null : m_redo[^1].name; + /// /// Gets the diagnostic explaining why the newest Undo entry is a barrier, or when available. /// public string? undoUnavailableReason => GetUnavailableReason(m_undo, EditorHistoryDirection.Undo); + /// /// Gets the diagnostic explaining why the newest Redo entry is a barrier, or when available. /// public string? redoUnavailableReason => GetUnavailableReason(m_redo, EditorHistoryDirection.Redo); + /// /// Gets the estimated resident payload bytes retained by committed Undo and Redo entries. /// - public long residentBytes => Sum( - m_undo, - static operation => operation.estimatedMemorySize - ) + Sum( - m_redo, - static operation => operation.estimatedMemorySize - ) + (m_isolation is IsolationState isolation ? Sum( - isolation.undo, - static operation => operation.estimatedMemorySize - ) + Sum( - isolation.redo, - static operation => operation.estimatedMemorySize - ) : 0L); + public long residentBytes + => Sum(m_undo, static operation => operation.estimatedMemorySize) + + Sum(m_redo, static operation => operation.estimatedMemorySize) + + (m_isolation is IsolationState isolation + ? Sum( + isolation.undo, + static operation => operation.estimatedMemorySize + ) + Sum(isolation.redo, static operation => operation.estimatedMemorySize) + : 0L); + /// /// Gets the estimated temporary disk payload bytes retained by committed Undo and Redo entries. /// - public long diskBytes => Sum( - m_undo, - static operation => operation.estimatedDiskSize - ) + Sum( - m_redo, - static operation => operation.estimatedDiskSize - ) + (m_isolation is IsolationState isolation ? Sum( - isolation.undo, - static operation => operation.estimatedDiskSize - ) + Sum( - isolation.redo, - static operation => operation.estimatedDiskSize - ) : 0L); + public long diskBytes + => Sum(m_undo, static operation => operation.estimatedDiskSize) + + Sum(m_redo, static operation => operation.estimatedDiskSize) + + (m_isolation is IsolationState isolation + ? Sum( + isolation.undo, + static operation => operation.estimatedDiskSize + ) + Sum(isolation.redo, static operation => operation.estimatedDiskSize) + : 0L); /// /// Begins an atomic group whose child operations appear as one Undo entry. @@ -145,37 +154,45 @@ public EditorHistoryTransaction BeginTransaction(string name) } /// - /// Executes a mutation and records its inverse only when the mutation succeeds. + /// Applies a neutral change through its current-generation handler and records it only when successful. /// /// /// The user-facing operation name. /// - /// - /// The callback that applies the initial mutation and every future Redo. - /// - /// - /// The callback that restores the previous state. - /// - /// - /// An optional stable key used to coalesce adjacent value-like edits. + /// + /// The independently owned neutral change whose ownership transfers to the history. /// /// - /// The result produced by the initial mutation. + /// The result of applying the change in the Redo direction. /// - internal EditorHistoryResult Execute( + /// + /// Thrown when is empty. + /// + /// + /// Thrown when is . + /// + public EditorHistoryResult Execute( string name, - Func execute, - Func undo, - object? mergeKey = null + EditorHistoryChange change ) { EnsureMutable(); ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(execute); - ArgumentNullException.ThrowIfNull(undo); - var operation = new DelegateOperation(name, undo, execute, mergeKey); + ArgumentNullException.ThrowIfNull(change); + DataOperation operation; + try + { + operation = new DataOperation(this, name, change); + } + finally + { + change.Dispose(); + } + EditorHistoryResult result = Invoke(operation.RedoInternal, name, "execute"); if (result.succeeded) + { Record(operation); + } else { ObserveFailure(result); @@ -186,7 +203,7 @@ internal EditorHistoryResult Execute( } /// - /// Applies a neutral change through its current-generation handler and records it only when successful. + /// Records a neutral change whose mutation has already been applied by its feature facade. /// /// /// The user-facing operation name. @@ -194,35 +211,94 @@ internal EditorHistoryResult Execute( /// /// The independently owned neutral change whose ownership transfers to the history. /// - /// - /// The result of applying the change in the Redo direction. - /// /// /// Thrown when is empty. /// /// /// Thrown when is . /// - public EditorHistoryResult Execute( + public void RecordApplied( string name, EditorHistoryChange change ) { EnsureMutable(); ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(change); - DataOperation operation; try { - operation = new DataOperation(this, name, change); + Record(new DataOperation(this, name, change)); } finally { change.Dispose(); } + } + /// + /// Attempts to restore the state preceding the newest committed operation. + /// + /// + /// The transition result. A failed operation remains available for retry. + /// + public EditorHistoryResult Undo() => Transition(m_undo, m_redo, undo: true); + + /// + /// Attempts to reapply the newest reverted operation. + /// + /// + /// The transition result. A failed operation remains available for retry. + /// + public EditorHistoryResult Redo() => Transition(m_redo, m_undo, undo: false); + + /// + /// Clears this history and releases every retained operation. + /// + public void Dispose() + { + if (m_isDisposed) + { + return; + } + Clear(); + m_blobStore.Dispose(); + m_isDisposed = true; + GC.SuppressFinalize(this); + } + + /// + /// Executes a mutation and records its inverse only when the mutation succeeds. + /// + /// + /// The user-facing operation name. + /// + /// + /// The callback that applies the initial mutation and every future Redo. + /// + /// + /// The callback that restores the previous state. + /// + /// + /// An optional stable key used to coalesce adjacent value-like edits. + /// + /// + /// The result produced by the initial mutation. + /// + internal EditorHistoryResult Execute( + string name, + Func execute, + Func undo, + object? mergeKey = null + ) { + EnsureMutable(); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(execute); + ArgumentNullException.ThrowIfNull(undo); + var operation = new DelegateOperation(name, undo, execute, mergeKey); EditorHistoryResult result = Invoke(operation.RedoInternal, name, "execute"); if (result.succeeded) + { Record(operation); + } else { ObserveFailure(result); @@ -248,38 +324,6 @@ internal void RecordApplied(EditorHistoryOperation operation) Record(operation); } - /// - /// Records a neutral change whose mutation has already been applied by its feature facade. - /// - /// - /// The user-facing operation name. - /// - /// - /// The independently owned neutral change whose ownership transfers to the history. - /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown when is . - /// - public void RecordApplied( - string name, - EditorHistoryChange change - ) { - EnsureMutable(); - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(change); - try - { - Record(new DataOperation(this, name, change)); - } - finally - { - change.Dispose(); - } - } - /// /// Records an already-applied value change with automatic adjacent-edit coalescing. /// @@ -315,20 +359,6 @@ object mergeKey Record(new ValueOperation(name, before, after, apply, mergeKey)); } - /// - /// Attempts to restore the state preceding the newest committed operation. - /// - /// - /// The transition result. A failed operation remains available for retry. - /// - public EditorHistoryResult Undo() => Transition(m_undo, m_redo, undo: true); - /// - /// Attempts to reapply the newest reverted operation. - /// - /// - /// The transition result. A failed operation remains available for retry. - /// - public EditorHistoryResult Redo() => Transition(m_redo, m_undo, undo: false); /// /// Starts a temporary empty history branch while retaining the current branch for restoration. /// @@ -342,9 +372,13 @@ internal IDisposable BeginIsolation() { EnsureMutable(); if (m_transactions.Count != 0) + { throw new InvalidOperationException("Editor history cannot be isolated during a transaction."); + } if (m_isolation is not null) + { throw new InvalidOperationException("Editor history already owns an isolated branch."); + } var isolation = new IsolationState(m_undo, m_redo, m_isFaulted, m_faultReason); m_isolation = isolation; m_undo = []; @@ -360,9 +394,13 @@ internal IDisposable BeginIsolation() internal void Clear() { if (m_isDisposed) + { return; + } if (m_isTransitioning) + { throw new InvalidOperationException("Editor history cannot be cleared during Undo or Redo."); + } DisposeAll(m_undo); DisposeAll(m_redo); if (m_isolation is IsolationState isolation) @@ -373,24 +411,13 @@ internal void Clear() } while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } m_isFaulted = false; m_faultReason = null; } - /// - /// Clears this history and releases every retained operation. - /// - public void Dispose() - { - if (m_isDisposed) - return; - Clear(); - m_blobStore.Dispose(); - m_isDisposed = true; - GC.SuppressFinalize(this); - } - internal void CommitTransaction(EditorHistoryTransaction transaction) { ArgumentNullException.ThrowIfNull(transaction); @@ -424,6 +451,21 @@ internal EditorHistoryResult RollbackTransaction(EditorHistoryTransaction transa return result; } + internal void Attach( + EditorContext editor, + EditorInteractions interactions + ) { + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + m_context = new EditorHistoryContext(editor, interactions); + } + + internal HandlerUpdate PrepareHandlerUpdate(IReadOnlyDictionary handlers) + { + ArgumentNullException.ThrowIfNull(handlers); + return new HandlerUpdate(this, m_handlers, handlers); + } + private void Record(EditorHistoryOperation operation) { if (m_transactions.TryPeek(out TransactionOperation? transaction)) @@ -457,14 +499,22 @@ bool undo ) { EnsureMutable(); if (m_transactions.Count != 0) + { return EditorHistoryResult.Failure("Undo and Redo are unavailable while a transaction is active."); + } if (source.Count == 0) + { return EditorHistoryResult.Failure(undo ? "Nothing to undo." : "Nothing to redo."); + } EditorHistoryOperation operation = source[^1]; m_isTransitioning = true; try { - EditorHistoryResult result = Invoke(undo ? operation.UndoInternal : operation.RedoInternal, operation.name, undo ? "undo" : "redo"); + EditorHistoryResult result = Invoke( + undo ? operation.UndoInternal : operation.RedoInternal, + operation.name, + undo ? "undo" : "redo" + ); if (!result.succeeded) { ObserveFailure(result); @@ -491,7 +541,9 @@ private TransactionOperation PopTransaction(Guid id) private TransactionOperation PeekTransaction(Guid id) { if (!m_transactions.TryPeek(out TransactionOperation? operation) || operation.id != id) + { throw new InvalidOperationException("Editor history transactions must complete in stack order."); + } return operation; } @@ -504,48 +556,42 @@ private void EnsureMutable() } if (m_isTransitioning) + { throw new InvalidOperationException("History cannot be modified while Undo or Redo is executing."); + } } private void ObserveFailure(EditorHistoryResult result) { if (result.succeeded || result.statePreserved) + { return; + } m_isFaulted = true; m_faultReason = result.message; m_log.Write(LogLevel.Error, "Editor history was faulted because state integrity was lost: {0}", [result.message]); } - internal void Attach( - EditorContext editor, - EditorInteractions interactions - ) { - ArgumentNullException.ThrowIfNull(editor); - ArgumentNullException.ThrowIfNull(interactions); - m_context = new EditorHistoryContext(editor, interactions); - } + private EditorHistoryChange RetainChange(EditorHistoryChange change) + => change.Retain( + m_blobStore, + m_options.inlinePayloadThreshold, + !string.IsNullOrWhiteSpace(m_options.cacheDirectory) + ); - internal HandlerUpdate PrepareHandlerUpdate(IReadOnlyDictionary handlers) - { - ArgumentNullException.ThrowIfNull(handlers); - return new HandlerUpdate(this, m_handlers, handlers); - } - - private EditorHistoryChange RetainChange(EditorHistoryChange change) => change.Retain( - m_blobStore, - m_options.inlinePayloadThreshold, - !string.IsNullOrWhiteSpace(m_options.cacheDirectory) - ); private bool TryGetHandler( string kind, out EditorHistoryHandler? handler ) => m_handlers.TryGetValue(kind, out handler); + private EditorHistoryAvailability Query( EditorHistoryChange change, EditorHistoryDirection direction ) { if (m_context is null) + { return EditorHistoryAvailability.Unavailable("The editor history is not attached to an interaction runtime."); + } if (!TryGetHandler(change.kind, out EditorHistoryHandler? handler) || handler is null) { return EditorHistoryAvailability.Unavailable($"Required history handler '{change.kind}' is not loaded."); @@ -567,7 +613,9 @@ EditorHistoryDirection direction ) { EditorHistoryAvailability availability = Query(change, direction); if (!availability.isAvailable) + { return EditorHistoryResult.Failure(availability.message); + } EditorHistoryHandler handler = m_handlers[change.kind]; return handler.ApplyInternal(m_context!, change, direction); } @@ -578,23 +626,12 @@ private bool TryMerge( out EditorHistoryChange? merged ) { merged = null; - if (!string.Equals( - older.kind, - newer.kind, - StringComparison.Ordinal - ) + if (!string.Equals(older.kind, newer.kind, StringComparison.Ordinal) || older.mergeKey is null - || !string.Equals( - older.mergeKey, - newer.mergeKey, - StringComparison.Ordinal - ) - || !TryGetHandler( - older.kind, - out EditorHistoryHandler? handler - ) - || handler is null) - { + || !string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal) + || !TryGetHandler(older.kind, out EditorHistoryHandler? handler) + || handler is null + ) { return false; } @@ -615,38 +652,30 @@ private void DiscardRuntimeBoundEntries() if (m_transactions.Count != 0) { while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } } DiscardRuntimeBoundEntries(m_undo, m_redo); if (m_isolation is IsolationState isolation) - DiscardRuntimeBoundEntries(isolation.undo, isolation.redo); - } - - private static void DiscardRuntimeBoundEntries( - List undo, - List redo - ) { - int newestUnsafe = undo.FindLastIndex(static operation => !operation.isReloadSafe); - if (newestUnsafe >= 0) { - for (int i = newestUnsafe; i >= 0; i--) - undo[i].Dispose(); - undo.RemoveRange(0, newestUnsafe + 1); + DiscardRuntimeBoundEntries(isolation.undo, isolation.redo); } - - if (redo.Exists(static operation => !operation.isReloadSafe)) - DisposeAll(redo); } private void EndIsolation(IsolationState isolation) { if (m_isDisposed || !ReferenceEquals(m_isolation, isolation)) + { return; + } DisposeAll(m_undo); DisposeAll(m_redo); while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } m_undo = isolation.undo; m_redo = isolation.redo; m_isFaulted = isolation.isFaulted; @@ -659,7 +688,9 @@ private void EndIsolation(IsolationState isolation) EditorHistoryDirection direction ) { if (operations.Count == 0) + { return null; + } EditorHistoryOperation operation = operations[^1]; if (operation is DataOperation data) { @@ -671,16 +702,6 @@ EditorHistoryDirection direction return available ? null : $"'{operation.name}' cannot currently be {direction.ToString().ToLowerInvariant()}."; } - private static long Sum( - IReadOnlyList operations, - Func selector - ) { - long total = 0L; - for (int i = 0; i < operations.Count; i++) - total = checked(total + selector(operations[i])); - return total; - } - private EditorHistoryResult Invoke( Func callback, string name, @@ -690,20 +711,58 @@ string transition { EditorHistoryResult result = callback(); if (!result.succeeded) + { m_log.Write(LogLevel.Warn, "Editor history operation '{0}' could not {1}: {2}", [name, transition, result.message]); + } return result; } catch (Exception exception) { m_log.Write(LogLevel.Error, "Editor history operation '{0}' failed to {1}: {2}", [name, transition, exception]); - return EditorHistoryResult.StateIntegrityLost($"The {transition} callback for '{name}' threw before it could prove rollback: {exception.Message}"); + return EditorHistoryResult.StateIntegrityLost( + $"The {transition} callback for '{name}' threw before it could prove rollback: {exception.Message}" + ); } } + private static void DiscardRuntimeBoundEntries( + List undo, + List redo + ) { + int newestUnsafe = undo.FindLastIndex(static operation => !operation.isReloadSafe); + if (newestUnsafe >= 0) + { + for (int i = newestUnsafe; i >= 0; i--) + { + undo[i].Dispose(); + } + undo.RemoveRange(0, newestUnsafe + 1); + } + + if (redo.Exists(static operation => !operation.isReloadSafe)) + { + DisposeAll(redo); + } + } + + private static long Sum( + IReadOnlyList operations, + Func selector + ) { + long total = 0L; + for (int i = 0; i < operations.Count; i++) + { + total = checked(total + selector(operations[i])); + } + return total; + } + private static void DisposeAll(List operations) { for (int i = operations.Count - 1; i >= 0; i--) + { operations[i].Dispose(); + } operations.Clear(); } @@ -711,16 +770,20 @@ internal sealed class HandlerUpdate( EditorHistory owner, IReadOnlyDictionary previous, IReadOnlyDictionary candidate - ) - { + ) { private bool m_activated; private bool m_finished; + internal void Activate() { if (m_finished) + { throw new InvalidOperationException("History handler update is already finished."); + } if (m_activated) + { return; + } owner.m_handlers = candidate; m_activated = true; } @@ -728,18 +791,26 @@ internal void Activate() internal void Rollback() { if (m_finished) + { return; + } if (m_activated) + { owner.m_handlers = previous; + } m_finished = true; } internal void Complete() { if (m_finished) + { return; + } if (!m_activated) + { throw new InvalidOperationException("History handler update has not been activated."); + } m_finished = true; try { @@ -758,12 +829,14 @@ private sealed record IsolationState( bool isFaulted, string? faultReason ); + private sealed class Isolation( EditorHistory owner, IsolationState state ) : IDisposable { private EditorHistory? m_owner = owner; + /// /// Releases the resources owned by this instance. /// @@ -771,7 +844,9 @@ public void Dispose() { EditorHistory? current = m_owner; if (current is null) + { return; + } m_owner = null; current.EndIsolation(state); } @@ -782,13 +857,14 @@ private sealed class DelegateOperation : EditorHistoryOperation private readonly Func m_undo; private readonly object? m_mergeKey; private Func m_redo; + internal DelegateOperation( string operationName, Func undo, Func redo, object? mergeKey ) { - name = operationName; + this.name = operationName; m_undo = undo; m_redo = redo; m_mergeKey = mergeKey; @@ -806,6 +882,7 @@ internal DelegateOperation( /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Undo() => m_undo(); + /// /// Reapplies the state represented by this history operation. /// @@ -813,6 +890,7 @@ internal DelegateOperation( /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Redo() => m_redo(); + /// /// Attempts to merge without changing state when the operation cannot complete. /// @@ -839,6 +917,7 @@ private sealed class DataOperation : EditorHistoryOperation private readonly EditorHistory m_owner; private readonly string m_name; private EditorHistoryChange m_change; + internal DataOperation( EditorHistory owner, string operationName, @@ -853,26 +932,32 @@ EditorHistoryChange change /// Gets the human-readable name used for presentation and diagnostics. /// public override string name => m_name; + /// /// Gets whether this value can undo. /// public override bool canUndo => m_owner.Query(m_change, EditorHistoryDirection.Undo).isAvailable; + /// /// Gets whether this value can redo. /// public override bool canRedo => m_owner.Query(m_change, EditorHistoryDirection.Redo).isAvailable; + /// /// Gets whether this value is reload safe. /// public override bool isReloadSafe => true; + /// /// Gets the estimated resident-memory cost in bytes. /// public override long estimatedMemorySize => m_change.residentSize; + /// /// Gets the estimated spill-file cost in bytes. /// public override long estimatedDiskSize => m_change.diskSize; + internal EditorHistoryChange change => m_change; /// @@ -882,6 +967,7 @@ EditorHistoryChange change /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Undo() => m_owner.Apply(m_change, EditorHistoryDirection.Undo); + /// /// Reapplies the state represented by this history operation. /// @@ -889,6 +975,7 @@ EditorHistoryChange change /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Redo() => m_owner.Apply(m_change, EditorHistoryDirection.Redo); + /// /// Attempts to merge without changing state when the operation cannot complete. /// @@ -900,8 +987,10 @@ EditorHistoryChange change /// protected override bool TryMerge(EditorHistoryOperation newer) { - if (newer is not DataOperation candidate || !m_owner.TryMerge(m_change, candidate.m_change, out EditorHistoryChange? merged) || merged is null) - { + if (newer is not DataOperation candidate + || !m_owner.TryMerge(m_change, candidate.m_change, out EditorHistoryChange? merged) + || merged is null + ) { return false; } @@ -929,7 +1018,9 @@ protected override bool TryMerge(EditorHistoryOperation newer) protected override void Dispose(bool disposing) { if (disposing) + { m_change.Dispose(); + } } } @@ -941,6 +1032,7 @@ private sealed class ValueOperation : EditorHistoryOperation private readonly object m_mergeKey; private T m_after; private long m_lastEditTimestamp; + internal ValueOperation( string operationName, T before, @@ -948,7 +1040,7 @@ internal ValueOperation( Action apply, object mergeKey ) { - name = operationName; + this.name = operationName; m_before = before; m_after = after; m_apply = apply; @@ -997,15 +1089,14 @@ protected override EditorHistoryResult Redo() protected override bool TryMerge(EditorHistoryOperation newer) { if (newer is not ValueOperation candidate - || !Equals( - m_mergeKey, - candidate.m_mergeKey - ) + || !Equals(m_mergeKey, candidate.m_mergeKey) || Stopwatch.GetElapsedTime( - m_lastEditTimestamp, - candidate.m_lastEditTimestamp - ).TotalSeconds > C_MERGE_WINDOW_SECONDS) + m_lastEditTimestamp, + candidate.m_lastEditTimestamp + ).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; + } m_after = candidate.m_after; m_lastEditTimestamp = candidate.m_lastEditTimestamp; return true; @@ -1014,47 +1105,43 @@ protected override bool TryMerge(EditorHistoryOperation newer) private sealed class TransactionOperation( string operationName, - Guid transactionId + Guid transactionID ) : EditorHistoryOperation { private readonly List m_children = []; + /// /// Gets the human-readable name used for presentation and diagnostics. /// public override string name => operationName; - internal Guid id => transactionId; - internal int count => m_children.Count; + /// /// Gets whether this value is reload safe. /// public override bool isReloadSafe => m_children.TrueForAll(static operation => operation.isReloadSafe); + /// /// Gets whether this value can undo. /// public override bool canUndo => m_children.TrueForAll(static operation => operation.canUndo); + /// /// Gets whether this value can redo. /// public override bool canRedo => m_children.TrueForAll(static operation => operation.canRedo); + /// /// Gets the estimated resident-memory cost in bytes. /// public override long estimatedMemorySize => Sum(m_children, static operation => operation.estimatedMemorySize); + /// /// Gets the estimated spill-file cost in bytes. /// public override long estimatedDiskSize => Sum(m_children, static operation => operation.estimatedDiskSize); - internal void Add(EditorHistoryOperation operation) - { - if (m_children.Count > 0 && m_children[^1].TryMergeInternal(operation)) - { - operation.Dispose(); - return; - } - - m_children.Add(operation); - } + internal Guid id => transactionID; + internal int count => m_children.Count; /// /// Restores the state that preceded this history operation. @@ -1064,17 +1151,25 @@ internal void Add(EditorHistoryOperation operation) /// protected override EditorHistoryResult Undo() { - var compensationFailures = new List(); + List compensationFailures = []; for (int i = m_children.Count - 1; i >= 0; i--) { EditorHistoryResult result = InvokeChild(m_children[i].UndoInternal, m_children[i].name, "undo"); if (result.succeeded) + { continue; + } for (int rollback = i + 1; rollback < m_children.Count; rollback++) { - EditorHistoryResult compensation = InvokeChild(m_children[rollback].RedoInternal, m_children[rollback].name, "redo compensation"); + EditorHistoryResult compensation = InvokeChild( + m_children[rollback].RedoInternal, + m_children[rollback].name, + "redo compensation" + ); if (!compensation.succeeded) + { compensationFailures.Add($"'{m_children[rollback].name}': {compensation.message}"); + } } return CombineFailure(result, compensationFailures, "undo"); @@ -1091,17 +1186,25 @@ protected override EditorHistoryResult Undo() /// protected override EditorHistoryResult Redo() { - var compensationFailures = new List(); + List compensationFailures = []; for (int i = 0; i < m_children.Count; i++) { EditorHistoryResult result = InvokeChild(m_children[i].RedoInternal, m_children[i].name, "redo"); if (result.succeeded) + { continue; + } for (int rollback = i - 1; rollback >= 0; rollback--) { - EditorHistoryResult compensation = InvokeChild(m_children[rollback].UndoInternal, m_children[rollback].name, "undo compensation"); + EditorHistoryResult compensation = InvokeChild( + m_children[rollback].UndoInternal, + m_children[rollback].name, + "undo compensation" + ); if (!compensation.succeeded) + { compensationFailures.Add($"'{m_children[rollback].name}': {compensation.message}"); + } } return CombineFailure(result, compensationFailures, "redo"); @@ -1110,6 +1213,36 @@ protected override EditorHistoryResult Redo() return EditorHistoryResult.Success(); } + /// + /// Releases the resources owned by this instance. + /// + /// + /// Whether the owner is permanently disposing rather than clearing reusable state. + /// + protected override void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + for (int i = m_children.Count - 1; i >= 0; i--) + { + m_children[i].Dispose(); + } + m_children.Clear(); + } + + internal void Add(EditorHistoryOperation operation) + { + if (m_children.Count > 0 && m_children[^1].TryMergeInternal(operation)) + { + operation.Dispose(); + return; + } + + m_children.Add(operation); + } + private static EditorHistoryResult InvokeChild( Func callback, string childName, @@ -1131,27 +1264,14 @@ private static EditorHistoryResult CombineFailure( string transition ) { if (original.statePreserved && compensationFailures.Count == 0) + { return original; + } string compensation = compensationFailures.Count == 0 ? "The failing child could not prove that it preserved its input state." : $"Compensation failures: {string.Join( "; ", compensationFailures )}"; return EditorHistoryResult.StateIntegrityLost($"Transaction {transition} failed: {original.message} {compensation}"); } - - /// - /// Releases the resources owned by this instance. - /// - /// - /// Whether the owner is permanently disposing rather than clearing reusable state. - /// - protected override void Dispose(bool disposing) - { - if (!disposing) - return; - for (int i = m_children.Count - 1; i >= 0; i--) - m_children[i].Dispose(); - m_children.Clear(); - } } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs index 005c65fe5..7af065d6c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs @@ -14,17 +14,47 @@ internal sealed class EditorHistoryBlobStore : IDisposable internal EditorHistoryBlobStore(string? cacheDirectory) { if (string.IsNullOrWhiteSpace(cacheDirectory)) + { + return; + } + m_sessionDirectory = Path.Combine(Path.GetFullPath(cacheDirectory), Guid.NewGuid().ToString("N")); + } + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { return; - m_sessionDirectory = Path.Combine( - Path.GetFullPath(cacheDirectory), - Guid.NewGuid().ToString("N")); + } + m_disposed = true; + m_references.Clear(); + if (m_sessionDirectory is not null) + { + try + { + if (Directory.Exists(m_sessionDirectory)) + { + Directory.Delete(m_sessionDirectory, recursive: true); + } + } + catch (Exception) + { + // A stale session directory is safe to remove with the project's Library cache. + } + } + GC.SuppressFinalize(this); } internal string Retain(ReadOnlySpan bytes) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_sessionDirectory is null) + { throw new InvalidOperationException("The history does not have a disk payload store."); + } Directory.CreateDirectory(m_sessionDirectory); string hash = Convert.ToHexStringLower(SHA256.HashData(bytes)); string path = Path.Combine(m_sessionDirectory, hash + ".bin"); @@ -48,7 +78,9 @@ internal string Retain(ReadOnlySpan bytes) internal void Release(string path) { if (m_disposed || !m_references.TryGetValue(path, out int count)) + { return; + } if (count > 1) { m_references[path] = count - 1; @@ -58,35 +90,13 @@ internal void Release(string path) try { if (File.Exists(path)) + { File.Delete(path); + } } - catch + catch (Exception) { // Session cleanup retries deletion when the history is disposed. } } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - m_references.Clear(); - if (m_sessionDirectory is not null) - { - try - { - if (Directory.Exists(m_sessionDirectory)) - Directory.Delete(m_sessionDirectory, recursive: true); - } - catch - { - // A stale session directory is safe to remove with the project's Library cache. - } - } - GC.SuppressFinalize(this); - } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs index addcafe80..712d18f4e 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs @@ -33,8 +33,9 @@ public EditorHistoryChange( string? mergeKey = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(kind); + ArgumentNullException.ThrowIfNull(payload); this.kind = kind; - this.payload = payload ?? throw new ArgumentNullException(nameof(payload)); + this.payload = payload; this.mergeKey = string.IsNullOrWhiteSpace(mergeKey) ? null : mergeKey; } @@ -53,29 +54,27 @@ public EditorHistoryChange( /// public string? mergeKey { get; } - internal long residentSize => payload.residentSize; - - internal long diskSize => payload.diskSize; - - internal EditorHistoryChange Retain( - EditorHistoryBlobStore store, - int inlinePayloadThreshold, - bool canStoreOnDisk - ) - => new( - kind, - payload.Retain(store, inlinePayloadThreshold, canStoreOnDisk), - mergeKey); - /// /// Releases the payload storage owned by this history change. /// public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; payload.Dispose(); GC.SuppressFinalize(this); } + + internal long residentSize => payload.residentSize; + + internal long diskSize => payload.diskSize; + + internal EditorHistoryChange Retain( + EditorHistoryBlobStore store, + int inlinePayloadThreshold, + bool canStoreOnDisk + ) => new(kind, payload.Retain(store, inlinePayloadThreshold, canStoreOnDisk), mergeKey); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs index bc3ef0dad..afd6a74f1 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -13,8 +12,10 @@ internal EditorHistoryContext( EditorContext editor, EditorInteractions interactions ) { - this.editor = editor ?? throw new ArgumentNullException(nameof(editor)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + this.editor = editor; + this.interactions = interactions; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs index 5a0618b69..c7674ef18 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs @@ -9,7 +9,6 @@ public enum EditorHistoryDirection /// Restores the state that existed before the change was committed. /// Undo = 0, - /// /// Restores the state produced by the committed change. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs index 597f7fb70..f6ebe466c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs @@ -73,35 +73,32 @@ out EditorHistoryChange? merged return false; } - /// - /// Creates a failed result for a transition whose compensation also failed. - /// - /// - /// The diagnostic containing both the transition and compensation failures. - /// - /// - /// A failure that faults the owning history. - /// - protected static EditorHistoryResult StateIntegrityFailure(string message) => EditorHistoryResult.StateIntegrityLost(message); - internal EditorHistoryAvailability QueryInternal( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) - => Query(context, change, direction); + ) => Query(context, change, direction); internal EditorHistoryResult ApplyInternal( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) - => Apply(context, change, direction); + ) => Apply(context, change, direction); internal bool TryMergeInternal( EditorHistoryChange older, EditorHistoryChange newer, out EditorHistoryChange? merged - ) - => TryMerge(older, newer, out merged); + ) => TryMerge(older, newer, out merged); + + /// + /// Creates a failed result for a transition whose compensation also failed. + /// + /// + /// The diagnostic containing both the transition and compensation failures. + /// + /// + /// A failure that faults the owning history. + /// + protected static EditorHistoryResult StateIntegrityFailure(string message) => EditorHistoryResult.StateIntegrityLost(message); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs index 025a69ef9..890d72929 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs @@ -27,5 +27,4 @@ public EditorHistoryHandlerAttribute(string kind) /// Gets the stable globally unique change protocol identifier. /// public string kind { get; } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs index 0f11dc79f..05bbf52f3 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs @@ -39,27 +39,18 @@ internal abstract class EditorHistoryOperation : IDisposable /// public virtual long estimatedDiskSize => 0L; - internal EditorHistoryResult UndoInternal() - { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - return canUndo - ? Undo() - : EditorHistoryResult.Failure($"'{name}' cannot currently be undone."); - } - - internal EditorHistoryResult RedoInternal() - { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - return canRedo - ? Redo() - : EditorHistoryResult.Failure($"'{name}' cannot currently be redone."); - } - - internal bool TryMergeInternal(EditorHistoryOperation newer) + /// + /// Releases resources retained exclusively for future undo and redo transitions. + /// + public void Dispose() { - ObjectDisposedException.ThrowIf(m_isDisposed, this); - ArgumentNullException.ThrowIfNull(newer); - return TryMerge(newer); + if (m_isDisposed) + { + return; + } + m_isDisposed = true; + Dispose(true); + GC.SuppressFinalize(this); } /// @@ -89,25 +80,34 @@ internal bool TryMergeInternal(EditorHistoryOperation newer) /// protected virtual bool TryMerge(EditorHistoryOperation newer) => false; - /// - /// Releases resources retained exclusively for future undo and redo transitions. - /// - public void Dispose() - { - if (m_isDisposed) - return; - m_isDisposed = true; - Dispose(true); - GC.SuppressFinalize(this); - } - /// /// Releases resources owned by a derived history operation. /// /// /// Whether managed resources may be released. /// - protected virtual void Dispose(bool disposing) + protected virtual void Dispose(bool disposing) {} + + internal EditorHistoryResult UndoInternal() { + ObjectDisposedException.ThrowIf(m_isDisposed, this); + return canUndo + ? Undo() + : EditorHistoryResult.Failure($"'{name}' cannot currently be undone."); + } + + internal EditorHistoryResult RedoInternal() + { + ObjectDisposedException.ThrowIf(m_isDisposed, this); + return canRedo + ? Redo() + : EditorHistoryResult.Failure($"'{name}' cannot currently be redone."); + } + + internal bool TryMergeInternal(EditorHistoryOperation newer) + { + ObjectDisposedException.ThrowIf(m_isDisposed, this); + ArgumentNullException.ThrowIfNull(newer); + return TryMerge(newer); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs index ecbb37114..cd9eef136 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs @@ -35,22 +35,28 @@ public sealed class EditorHistoryOptions internal void Validate() { if (maxEntries <= 0) + { throw new ArgumentOutOfRangeException(nameof(maxEntries), maxEntries, "History entry capacity must be positive."); + } if (maxResidentBytes <= 0) { throw new ArgumentOutOfRangeException( nameof(maxResidentBytes), maxResidentBytes, - "Resident history capacity must be positive."); + "Resident history capacity must be positive." + ); } if (maxDiskBytes <= 0) + { throw new ArgumentOutOfRangeException(nameof(maxDiskBytes), maxDiskBytes, "Disk history capacity must be positive."); + } if (inlinePayloadThreshold < 0) { throw new ArgumentOutOfRangeException( nameof(inlinePayloadThreshold), inlinePayloadThreshold, - "The inline payload threshold cannot be negative."); + "The inline payload threshold cannot be negative." + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs index b69fcd155..2417cc39c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs @@ -16,7 +16,7 @@ public sealed class EditorHistoryPayload : IDisposable private EditorHistoryPayload(byte[] bytes) { m_inlineBytes = bytes; - length = bytes.LongLength; + this.length = bytes.LongLength; } private EditorHistoryPayload( @@ -39,21 +39,6 @@ long length /// public bool isStoredOnDisk => m_path is not null; - internal long residentSize => m_inlineBytes?.LongLength ?? 0L; - - internal long diskSize => m_path is null ? 0L : length; - - /// - /// Creates an immutable history payload by copying the supplied bytes. - /// - /// - /// The neutral bytes to retain for future Undo and Redo transitions. - /// - /// - /// A new independently owned payload. - /// - public static EditorHistoryPayload FromBytes(ReadOnlySpan bytes) => new(bytes.ToArray()); - /// /// Reads the complete immutable payload into a newly allocated byte array. /// @@ -67,36 +52,59 @@ public byte[] ReadBytes() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_inlineBytes is not null) + { return (byte[])m_inlineBytes.Clone(); + } return File.ReadAllBytes(m_path!); } - internal EditorHistoryPayload Retain( - EditorHistoryBlobStore store, - int inlinePayloadThreshold, - bool canStoreOnDisk - ) { - ObjectDisposedException.ThrowIf(m_disposed, this); - byte[] bytes = ReadBytes(); - if (!canStoreOnDisk || bytes.Length < inlinePayloadThreshold) - return new EditorHistoryPayload(bytes); - string path = store.Retain(bytes); - return new EditorHistoryPayload(store, path, bytes.LongLength); - } - /// /// Releases the resident or temporary disk storage owned by this payload. /// public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; if (m_store is not null && m_path is not null) + { m_store.Release(m_path); + } m_inlineBytes = null; m_store = null; m_path = null; GC.SuppressFinalize(this); } + + /// + /// Creates an immutable history payload by copying the supplied bytes. + /// + /// + /// The neutral bytes to retain for future Undo and Redo transitions. + /// + /// + /// A new independently owned payload. + /// + public static EditorHistoryPayload FromBytes(ReadOnlySpan bytes) => new(bytes.ToArray()); + + internal long residentSize => m_inlineBytes?.LongLength ?? 0L; + + internal long diskSize => m_path is null ? 0L : length; + + internal EditorHistoryPayload Retain( + EditorHistoryBlobStore store, + int inlinePayloadThreshold, + bool canStoreOnDisk + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + byte[] bytes = ReadBytes(); + if (!canStoreOnDisk || bytes.Length < inlinePayloadThreshold) + { + return new EditorHistoryPayload(bytes); + } + string path = store.Retain(bytes); + return new EditorHistoryPayload(store, path, bytes.LongLength); + } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs index 2cb4388c8..d160bd740 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs @@ -25,8 +25,6 @@ Guid id /// public string name { get; } - internal Guid id { get; } - /// /// Commits all recorded child operations as one atomic history entry. /// @@ -54,9 +52,13 @@ public EditorHistoryResult Rollback() EditorHistory owner = GetOwner(); EditorHistoryResult result = owner.RollbackTransaction(this); if (result.succeeded) + { Complete(); + } else if (!result.statePreserved) + { Complete(); + } return result; } @@ -66,7 +68,9 @@ public EditorHistoryResult Rollback() public void Dispose() { if (m_completed) + { return; + } EditorHistory? owner = m_owner; if (owner is null) { @@ -88,19 +92,23 @@ public void Dispose() Complete(); GC.SuppressFinalize(this); throw new InvalidOperationException( - $"Transaction '{name}' could not roll back and was committed to Undo instead: {result.message}"); + $"Transaction '{name}' could not roll back and was committed to Undo instead: {result.message}" + ); } Complete(); GC.SuppressFinalize(this); throw new InvalidOperationException( - $"Transaction '{name}' lost state integrity while rolling back. The history is faulted: {result.message}"); + $"Transaction '{name}' lost state integrity while rolling back. The history is faulted: {result.message}" + ); } + internal Guid id { get; } + private EditorHistory GetOwner() => !m_completed && m_owner is not null - ? m_owner - : throw new InvalidOperationException("The editor history transaction is no longer active."); + ? m_owner + : throw new InvalidOperationException("The editor history transaction is no longer active."); private void Complete() { diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs index 63403f19f..9986d70ff 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs @@ -33,10 +33,14 @@ public EditorMenuAttribute( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor menu area is required.", nameof(area)); + } this.area = area; if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("An editor menu path is required.", nameof(path)); + } this.path = path; this.order = order; this.separatorBefore = separatorBefore; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs index 962cda222..bb42d490c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs @@ -29,7 +29,9 @@ public void AddGroup( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A menu group path is required.", nameof(path)); + } m_groups.Add(new EditorMenuGroupPlacement(path, order, separatorBefore)); } @@ -39,7 +41,7 @@ public void AddGroup( /// /// The slash-delimited path used to create parent menus and the leaf label. /// - /// + /// /// The stable action identifier invoked by the leaf. /// /// @@ -52,19 +54,21 @@ public void AddGroup( /// An optional argument captured for this menu generation. /// /// - /// Thrown when or is empty. + /// Thrown when or is empty. /// public void Add( string path, - string actionId, + string actionID, int order = 0, bool separatorBefore = false, object? argument = null ) { if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A menu path is required.", nameof(path)); - ArgumentException.ThrowIfNullOrWhiteSpace(actionId); - m_items.Add(new EditorMenuPlacement(path, actionId, order, separatorBefore, argument)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(actionID); + m_items.Add(new EditorMenuPlacement(path, actionID, order, separatorBefore, argument)); } internal IReadOnlyList items => m_items; @@ -76,42 +80,3 @@ internal sealed record EditorMenuGroupPlacement( int order, bool separatorBefore ); - -internal sealed class EditorMenuPlacement -{ - internal EditorMenuPlacement( - string path, - string actionId, - int order, - bool separatorBefore, - object? argument - ) { - this.path = path; - this.actionId = actionId; - this.order = order; - this.separatorBefore = separatorBefore; - this.argument = argument; - } - - internal string path { get; } - - /// - /// Gets the action identifier. - /// - internal string actionId { get; } - - /// - /// Gets the stable menu order. - /// - internal int order { get; } - - /// - /// Gets whether a separator precedes this placement. - /// - internal bool separatorBefore { get; } - - /// - /// Gets the optional action argument. - /// - internal object? argument { get; } -} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs index 3f3ba1b03..6e5d439cb 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs @@ -10,8 +10,7 @@ internal sealed class EditorMenuCatalog( EditorExtensionCatalog catalog, EditorActionRouter actions, Logger log -) -{ +) { private readonly HashSet m_sourceFailures = new(StringComparer.Ordinal); private Dictionary? m_templates; @@ -19,11 +18,13 @@ internal EditorMenuModel Build(EditorMenuContext context) { ArgumentNullException.ThrowIfNull(context); TemplateNode[] template = GetTemplate(context.area); - var dynamicPlacements = new List(); + List dynamicPlacements = []; foreach (EditorExtensionCatalog.MenuSourceRegistration registration in catalog.extensions.menuSources) { if (!string.Equals(registration.area, context.area, StringComparison.Ordinal)) + { continue; + } try { var builder = new EditorMenuBuilder(); @@ -31,25 +32,37 @@ internal EditorMenuModel Build(EditorMenuContext context) string sourceName = registration.type.FullName ?? registration.type.Name; m_sourceFailures.Remove(sourceName); if (builder.groups.Count == 0 && builder.items.Count == 0) + { continue; + } var placements = new List(builder.groups.Count + builder.items.Count); - foreach (var group in builder.groups) + foreach (EditorMenuGroupPlacement group in builder.groups) + { placements.Add(CreatePlacement(group.path, null, group.order, group.separatorBefore, null)); - foreach (var item in builder.items) - placements.Add(CreatePlacement(item.path, item.actionId, item.order, item.separatorBefore, item.argument)); + } + foreach (EditorMenuPlacement item in builder.items) + { + placements.Add(CreatePlacement(item.path, item.actionID, item.order, item.separatorBefore, item.argument)); + } dynamicPlacements.AddRange(placements); } catch (Exception exception) { string sourceName = registration.type.FullName ?? registration.type.Name; if (m_sourceFailures.Add(sourceName)) + { log.Write(LogLevel.Error, "Editor menu source '{0}' failed: {1}", [sourceName, exception]); + } } } if (dynamicPlacements.Count > 0) { - foreach (Placement placement in dynamicPlacements.OrderBy(static value => value.order).ThenBy(static value => value.path, StringComparer.Ordinal)) + foreach (Placement placement in dynamicPlacements + .OrderBy(static value => value.order) + .ThenBy(static value => value.path, StringComparer.Ordinal) + ) { template = Merge(template, placement, 0); + } } return new EditorMenuModel(Resolve(template, context)); } @@ -70,7 +83,9 @@ private TemplateNode[] GetTemplate(string area) foreach (EditorMenuAttribute menu in registration.menus) { if (!placementsByArea.TryGetValue(menu.area, out List? placements)) + { placementsByArea.Add(menu.area, placements = []); + } placements.Add(CreatePlacement(menu.path, registration.id, menu.order, menu.separatorBefore, null)); } } @@ -78,8 +93,12 @@ private TemplateNode[] GetTemplate(string area) foreach ((string key, List placements) in placementsByArea) { var root = new MutableNode(string.Empty, 0, false); - foreach (Placement placement in placements.OrderBy(static value => value.order).ThenBy(static value => value.path, StringComparer.Ordinal)) + foreach (Placement placement in placements + .OrderBy(static value => value.order) + .ThenBy(static value => value.path, StringComparer.Ordinal) + ) { AddPlacement(root, placement); + } templates.Add(key, FreezeTemplate(root.children.Values)); } m_templates = templates; @@ -92,7 +111,9 @@ private IReadOnlyList Resolve( EditorMenuContext context ) { if (nodes.Length == 0) - return Array.Empty(); + { + return []; + } var result = new List(nodes.Length); foreach (TemplateNode node in nodes) { @@ -103,11 +124,13 @@ EditorMenuContext context bool separatorBefore = false; foreach (Placement placement in node.placements) { - if (placement.actionId is string action) + if (placement.actionID is string action) { EditorActionState candidate = actions.Query(action, context.CreateActionContext(placement.argument)); if (!candidate.isVisible) + { continue; + } actionPlacement = placement; state = candidate; } @@ -117,17 +140,30 @@ EditorMenuContext context if (actionPlacement is null) { if (children.Count == 0) + { continue; + } state = EditorActionState.enabled; } string label = string.IsNullOrWhiteSpace(state.displayName) ? node.label : state.displayName!; - result.Add(new EditorMenuItem(label, actionPlacement?.actionId ?? string.Empty, order, - separatorBefore, state, children, actionPlacement?.argument)); + result.Add( + new EditorMenuItem( + label, + actionPlacement?.actionID ?? string.Empty, + order, + separatorBefore, + state, + children, + actionPlacement?.argument + ) + ); } for (int index = 1; index < result.Count; index++) { if (result[index - 1].order <= result[index].order) + { continue; + } result.Sort(static ( left, right @@ -139,15 +175,17 @@ EditorMenuContext context private static Placement CreatePlacement( string path, - string? actionId, + string? actionID, int order, bool separatorBefore, object? argument ) { string[] segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (segments.Length == 0) + { throw new InvalidOperationException("An editor menu path must contain at least one segment."); - return new Placement(string.Join('/', segments), segments, actionId, order, separatorBefore, argument); + } + return new Placement(string.Join('/', segments), segments, actionID, order, separatorBefore, argument); } private static void AddPlacement( @@ -160,8 +198,11 @@ Placement placement string segment = placement.segments[index]; if (!current.children.TryGetValue(segment, out MutableNode? child)) { - child = new MutableNode(segment, placement.order, - index == placement.segments.Length - 1 && placement.separatorBefore); + child = new MutableNode( + segment, + placement.order, + index == placement.segments.Length - 1 && placement.separatorBefore + ); current.children.Add(segment, child); } current = child; @@ -172,9 +213,16 @@ Placement placement } private static TemplateNode[] FreezeTemplate(IEnumerable nodes) - => nodes.OrderBy(static value => value.order).ThenBy(static value => value.label, StringComparer.Ordinal) - .Select(static node => new TemplateNode(node.label, node.order, node.separatorBefore, - node.placements.OrderBy(static placement => placement.order).ToArray(), FreezeTemplate(node.children.Values))).ToArray(); + => nodes.OrderBy(static value => value.order) + .ThenBy(static value => value.label, StringComparer.Ordinal) + .Select(static node => new TemplateNode( + node.label, + node.order, + node.separatorBefore, + node.placements.OrderBy(static placement => placement.order).ToArray(), + FreezeTemplate(node.children.Values) + )) + .ToArray(); private static TemplateNode[] Merge( TemplateNode[] nodes, @@ -186,7 +234,9 @@ int depth for (int candidate = 0; candidate < nodes.Length; candidate++) { if (!string.Equals(nodes[candidate].label, label, StringComparison.Ordinal)) + { continue; + } index = candidate; break; } @@ -197,14 +247,21 @@ int depth { int insertion = 0; while (insertion < placements.Length && placements[insertion].order <= placement.order) + { insertion++; + } placements = new Placement[current.placements.Length + 1]; Array.Copy(current.placements, placements, insertion); placements[insertion] = placement; Array.Copy(current.placements, insertion, placements, insertion + 1, current.placements.Length - insertion); } - TemplateNode replacement = new(label, current.order, current.separatorBefore, placements, - leaf ? current.children : Merge(current.children, placement, depth + 1)); + var replacement = new TemplateNode( + label, + current.order, + current.separatorBefore, + placements, + leaf ? current.children : Merge(current.children, placement, depth + 1) + ); var result = new TemplateNode[nodes.Length + (index < 0 ? 1 : 0)]; Array.Copy(nodes, result, nodes.Length); result[index >= 0 ? index : nodes.Length] = replacement; @@ -218,7 +275,7 @@ int depth private sealed record Placement( string path, string[] segments, - string? actionId, + string? actionID, int order, bool separatorBefore, object? argument @@ -236,12 +293,11 @@ private sealed class MutableNode( string label, int order, bool separatorBefore - ) - { + ) { + internal readonly List placements = []; + internal readonly Dictionary children = new(StringComparer.Ordinal); internal string label = label; internal int order = order; internal bool separatorBefore = separatorBefore; - internal readonly List placements = []; - internal readonly Dictionary children = new(StringComparer.Ordinal); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs index 4c7f68e3c..73acf70dc 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -36,8 +35,10 @@ public EditorMenuContext( string area, object? target = null ) { - this.editor = editor ?? throw new ArgumentNullException(nameof(editor)); - this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(interactions); + this.editor = editor; + this.interactions = interactions; ArgumentException.ThrowIfNullOrWhiteSpace(area); this.area = area; this.target = target; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs index 10b595b37..997007a4a 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scripting.Api; namespace Inno.Editor.Interactions; @@ -16,7 +15,7 @@ public sealed class EditorMenuItem /// /// The visible contextual label of the node. /// - /// + /// /// The leaf action identifier, or an empty string for a structural submenu. /// /// @@ -36,7 +35,7 @@ public sealed class EditorMenuItem /// internal EditorMenuItem( string label, - string actionId, + string actionID, int order, bool separatorBefore, EditorActionState status, @@ -44,11 +43,11 @@ internal EditorMenuItem( object? argument = null ) { this.label = label ?? string.Empty; - this.actionId = actionId ?? string.Empty; + this.actionID = actionID ?? string.Empty; this.order = order; this.separatorBefore = separatorBefore; this.status = status; - this.children = children ?? Array.Empty(); + this.children = children ?? []; this.argument = argument; } @@ -61,7 +60,7 @@ internal EditorMenuItem( /// Gets the stable action identifier consumed by a presentation backend. /// [ScriptingApiIgnore] - public string actionId { get; } + public string actionID { get; } /// /// Gets the stable ordering value. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuModel.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuModel.cs index d3acafd26..8576cb6dc 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuModel.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuModel.cs @@ -16,7 +16,7 @@ public sealed class EditorMenuModel /// public EditorMenuModel(IReadOnlyList? items) { - this.items = items ?? Array.Empty(); + this.items = items ?? []; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs new file mode 100644 index 000000000..a4a63ece2 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs @@ -0,0 +1,40 @@ +namespace Inno.Editor.Interactions; + +internal sealed class EditorMenuPlacement +{ + internal EditorMenuPlacement( + string path, + string actionID, + int order, + bool separatorBefore, + object? argument + ) { + this.path = path; + this.actionID = actionID; + this.order = order; + this.separatorBefore = separatorBefore; + this.argument = argument; + } + + internal string path { get; } + + /// + /// Gets the action identifier. + /// + internal string actionID { get; } + + /// + /// Gets the stable menu order. + /// + internal int order { get; } + + /// + /// Gets whether a separator precedes this placement. + /// + internal bool separatorBefore { get; } + + /// + /// Gets the optional action argument. + /// + internal object? argument { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs index de2fc14f2..07534a167 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs @@ -25,7 +25,9 @@ public EditorMenuSourceAttribute( int priority = 0 ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor menu area is required.", nameof(area)); + } this.area = area; this.priority = priority; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs index d5b8f332f..ed033ac76 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Interactions; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Interactions", "Inno.Editor.Interactions", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorInteractions), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs index ce91feaeb..b81c64f40 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs @@ -2,6 +2,7 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Provides a fluent handle that borrows an optional target for a synchronous interaction request. /// @@ -14,12 +15,14 @@ namespace Inno.Editor.Interactions; public readonly struct EditorInteraction { private readonly EditorInteractions m_interactions; + internal EditorInteraction( EditorInteractions interactions, string area, object? target ) { - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(interactions); + m_interactions = interactions; ArgumentException.ThrowIfNullOrWhiteSpace(area); this.area = area; this.target = target; @@ -29,10 +32,12 @@ internal EditorInteraction( /// Gets the stable interaction area. /// public string area { get; } + /// /// Gets the borrowed target without extending its validity or resolving a replacement generation. /// public object? target { get; } + /// /// Gets whether this handle's target is the current editor selection. /// @@ -42,13 +47,15 @@ internal EditorInteraction( /// Marks this area and target as the active keyboard context. /// public void Focus() => m_interactions.Focus(area, target); + /// /// Selects this target, or clears selection when the target is . /// /// /// when the built-in selection action executed; otherwise, . /// - public bool Select() => Execute(target is null ? EditorBuiltInInteractionIds.C_CLEAR_SELECTION : EditorBuiltInInteractionIds.C_SELECT); + public bool Select() => Execute(target is null ? EditorBuiltInInteractionIDs.C_CLEAR_SELECTION : EditorBuiltInInteractionIDs.C_SELECT); + /// /// Queries an action for this area and target. /// @@ -68,6 +75,7 @@ public EditorActionState Query( string action, object? argument = null ) => m_interactions.Query(action, area, target, argument); + /// /// Executes an action for this area and target. /// @@ -87,6 +95,7 @@ public bool Execute( string action, object? argument = null ) => m_interactions.Execute(action, area, target, argument); + /// /// Queues an action until the current UI traversal completes. /// @@ -103,6 +112,7 @@ public void Enqueue( string action, object? argument = null ) => m_interactions.Enqueue(action, area, target, argument); + /// /// Presents an active action in place of this target's normal content. /// @@ -122,6 +132,7 @@ public bool Present( string action, object? argument = null ) => m_interactions.Present(action, area, target, argument); + /// /// Gets whether an action owns an active multi-frame operation for this target. /// @@ -135,6 +146,7 @@ public bool Present( /// Thrown when is empty. /// public bool IsActive(string action) => m_interactions.IsActive(action, area, target); + /// /// Builds the complete contextual menu for this area and target. /// @@ -142,6 +154,7 @@ public bool Present( /// The immutable resolved menu model. /// public EditorMenuModel BuildMenu() => m_interactions.BuildMenu(area, target); + /// /// Builds searchable commands from this area's menus and applicable unplaced Actions. /// @@ -149,6 +162,7 @@ public bool Present( /// Current command states and neutral placement arguments; execution revalidates their targets. /// public EditorMenuModel BuildCommands() => m_interactions.BuildCommands(area, target); + /// /// Builds the complete compact toolbar for this area and target. /// @@ -156,6 +170,7 @@ public bool Present( /// The immutable resolved toolbar model. /// public EditorToolbarModel BuildToolbar() => m_interactions.BuildToolbar(area, target); + /// /// Resolves the shortcut displayed for an action in this area. /// @@ -175,6 +190,7 @@ public bool TryGetShortcut( string action, out HotKeyGesture gesture ) => m_interactions.TryGetShortcut(action, area, target, out gesture); + /// /// Gets the currently active drag identity, if its source remains registered. /// @@ -185,6 +201,7 @@ out HotKeyGesture gesture /// when a live drag source exists; otherwise, . /// public bool TryGetActiveDragIdentity(out RuntimeIdentity identity) => m_interactions.TryGetActiveDragIdentity(out identity); + /// /// Begins a managed drag originating from this area. /// @@ -195,6 +212,7 @@ out HotKeyGesture gesture /// The source object's domain-qualified transient identity. /// public RuntimeIdentity BeginDrag(EditorDragData data) => m_interactions.BeginDrag(area, data); + /// /// Queries this handle as a drop target. /// @@ -211,6 +229,7 @@ public EditorDropStatus QueryDrop( RuntimeIdentity identity, EditorDropPlacement placement = EditorDropPlacement.None ) => m_interactions.QueryDrop(identity, area, target, placement); + /// /// Delivers a managed drop to this target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs index 2e36ebe29..955ca4284 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs @@ -1,23 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Editor.Core; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions; /// /// Hosts attribute-discovered editor extensions without depending on a presentation backend. /// -public sealed class EditorInteractionRuntime : Inno.Editor.Core.EditorRuntime +public sealed class EditorInteractionRuntime : EditorRuntime { private readonly EditorInteractions m_interactions; private readonly EditorExtensionCatalog m_catalog; + private readonly List m_shutdownFailures = []; private EditorExtensionCatalog.Snapshot? m_describedSnapshot; private EditorPanelExtension[] m_panels = []; private EditorModalExtension[] m_modals = []; @@ -26,13 +26,12 @@ public sealed class EditorInteractionRuntime : Inno.Editor.Core.EditorRuntime private bool m_stopping; private int m_shutdownStage; private EditorExtensionCatalog.ActionRegistration[] m_shutdownActions = []; - private readonly List m_shutdownFailures = []; /// - /// Creates an interaction runtime for one project. + /// Creates an interaction runtime for an existing passive editor context. /// - /// - /// The project root containing Assets and Library. + /// + /// The passive editor context shared with the presentation backend. /// /// /// The type catalog that owns editor extension generations. @@ -40,24 +39,20 @@ public sealed class EditorInteractionRuntime : Inno.Editor.Core.EditorRuntime /// /// The host-owned logging router used by editor infrastructure. /// - /// - /// The explicit immutable product keyboard conventions. - /// + /// + /// Thrown when or is . + /// public EditorInteractionRuntime( - string projectDirectory, + EditorContext context, TypeCatalog types, - LogRouter logs, - EditorKeyboardPolicy keyboard - ) - : this(new EditorContext(projectDirectory, keyboard), types, logs) - { - } + LogRouter logs + ) : this(context, types, logs, []) {} /// - /// Creates an interaction runtime for an existing passive editor context. + /// Creates an interaction runtime for one project. /// - /// - /// The passive editor context shared with the presentation backend. + /// + /// The project root containing Assets and Library. /// /// /// The type catalog that owns editor extension generations. @@ -65,17 +60,15 @@ EditorKeyboardPolicy keyboard /// /// The host-owned logging router used by editor infrastructure. /// - /// - /// Thrown when or is . - /// + /// + /// The explicit immutable product keyboard conventions. + /// public EditorInteractionRuntime( - EditorContext context, + string projectDirectory, TypeCatalog types, - LogRouter logs - ) - : this(context, types, logs, Array.Empty()) - { - } + LogRouter logs, + EditorKeyboardPolicy keyboard + ) : this(new EditorContext(projectDirectory, keyboard), types, logs) {} /// /// Creates an interaction runtime with stable host-owned extension services. @@ -83,14 +76,14 @@ LogRouter logs /// /// The passive editor context shared with the presentation backend. /// - /// - /// Stable host-owned services that editor extension constructors may request by assignable contract. + /// + /// The type catalog that owns editor extension generations. /// /// /// The host-owned logging router used by editor infrastructure. /// - /// - /// The type catalog that owns editor extension generations. + /// + /// Stable host-owned services that editor extension constructors may request by assignable contract. /// /// /// Thrown when or is . @@ -100,25 +93,22 @@ public EditorInteractionRuntime( TypeCatalog types, LogRouter logs, IEnumerable hostServices - ) - : base(context) + ) : base(context) { ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(logs); ArgumentNullException.ThrowIfNull(hostServices); Logger logger = logs.CreateLogger(); object[] services = hostServices.ToArray(); - m_interactions = new EditorInteractions( - context, - services.OfType(), - logger); + m_interactions = new EditorInteractions(context, services.OfType(), logger); m_catalog = new EditorExtensionCatalog( types, context, m_interactions, logger, new object[] { logs }.Concat(services), - InvalidateDescriptions); + InvalidateDescriptions + ); m_interactions.Attach(m_catalog); } @@ -163,9 +153,13 @@ public override void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("A retiring editor runtime cannot restart."); + } if (m_started) + { return; + } _ = m_catalog.extensions; m_started = true; } @@ -180,9 +174,13 @@ public override void Update(EditorFrame frame) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("A retiring editor runtime cannot update."); + } if (!m_started) + { Start(); + } SetFrame(frame); m_interactions.Update(); m_catalog.UpdateModules(); @@ -210,13 +208,13 @@ public void SaveState() /// Freezes automatic extension-state persistence and writes the final state before modules /// begin shutting down. /// + /// + /// Thrown after this runtime has been disposed. + /// /// /// This operation is idempotent. After it succeeds, later disposal cannot recapture transient /// teardown state such as an empty scene workspace. /// - /// - /// Thrown after this runtime has been disposed. - /// public void PrepareShutdown() { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -233,7 +231,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) { ArgumentNullException.ThrowIfNull(keyEvent); if (m_interactions.DispatchShortcut(keyEvent)) + { keyEvent.HandleInGlobal(); + } } /// @@ -248,7 +248,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) public override void Dispose() { if (m_disposed) + { return; + } if (!m_stopping) { m_stopping = true; @@ -258,10 +260,18 @@ public override void Dispose() { switch (m_shutdownStage) { - case 0: TryShutdownStage(m_catalog.PrepareShutdown, m_shutdownFailures); break; - case 1: TryShutdownStage(() => m_catalog.Shutdown(saveState: false), m_shutdownFailures); break; - case 2: TryShutdownStage(() => m_interactions.Shutdown(m_shutdownActions), m_shutdownFailures); break; - case 3: TryShutdownStage(m_catalog.Dispose, m_shutdownFailures); break; + case 0: + TryShutdownStage(m_catalog.PrepareShutdown, m_shutdownFailures); + break; + case 1: + TryShutdownStage(() => m_catalog.Shutdown(saveState: false), m_shutdownFailures); + break; + case 2: + TryShutdownStage(() => m_interactions.Shutdown(m_shutdownActions), m_shutdownFailures); + break; + case 3: + TryShutdownStage(m_catalog.Dispose, m_shutdownFailures); + break; } m_shutdownStage++; } @@ -275,7 +285,8 @@ public override void Dispose() { var failure = new AggregateException( "One or more editor interaction shutdown stages failed.", - m_shutdownFailures); + m_shutdownFailures + ); m_shutdownFailures.Clear(); throw failure; } @@ -285,21 +296,28 @@ private void RefreshDescriptions() { EditorExtensionCatalog.Snapshot snapshot = m_catalog.extensions; if (ReferenceEquals(snapshot, m_describedSnapshot)) + { return; + } var panels = new List(snapshot.panels.Length); for (int i = 0; i < snapshot.panels.Length; i++) { EditorExtensionCatalog.PanelRegistration registration = snapshot.panels[i]; if (snapshot.quarantinedPanels.Contains(registration.panel)) + { continue; - panels.Add(new EditorPanelExtension( - registration.attribute.id, - registration.attribute.title, - registration.attribute.order, - registration.panel, - () => m_catalog.TakePanelFocusRequest(registration.attribute.id), - exception => m_catalog.QuarantinePanel(snapshot, registration, exception))); + } + panels.Add( + new EditorPanelExtension( + registration.attribute.id, + registration.attribute.title, + registration.attribute.order, + registration.panel, + () => m_catalog.TakePanelFocusRequest(registration.attribute.id), + exception => m_catalog.QuarantinePanel(snapshot, registration, exception) + ) + ); } m_panels = panels.ToArray(); @@ -308,13 +326,18 @@ private void RefreshDescriptions() { EditorExtensionCatalog.ModalRegistration registration = snapshot.modals[i]; if (snapshot.quarantinedModals.Contains(registration.modal)) + { continue; - modals.Add(new EditorModalExtension( - registration.attribute.id, - registration.attribute.title, - registration.attribute.order, - registration.modal, - exception => m_catalog.QuarantineModal(snapshot, registration, exception))); + } + modals.Add( + new EditorModalExtension( + registration.attribute.id, + registration.attribute.title, + registration.attribute.order, + registration.modal, + exception => m_catalog.QuarantineModal(snapshot, registration, exception) + ) + ); } m_modals = modals.ToArray(); m_describedSnapshot = snapshot; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs index 5cd3b36d6..c7ada8b25 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs @@ -5,45 +5,52 @@ using Inno.Core.Events; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Scripting.Api; using Inno.Editor.Core; +using Inno.Scripting.Api; namespace Inno.Editor.Interactions; + /// /// Provides the single presentation-independent entry point for editor actions, menus, selection, focus, and drag-and-drop. /// public sealed class EditorInteractions : IEditorSelectionCoordinator, IEditorHistoryIsolation { private readonly EditorContext m_editor; - private readonly Dictionary m_identityDomains; + private readonly Dictionary m_identityDomains; private readonly int m_identityOwnerThread = Environment.CurrentManagedThreadId; - private bool m_identityDomainsRetired; private readonly EditorHistory m_history; private readonly EditorDocumentService m_documents; private readonly Logger m_log; + private bool m_identityDomainsRetired; private EditorActionRouter? m_actions; private EditorExtensionCatalog? m_catalog; private EditorMenuCatalog? m_menus; private EditorToolbarCatalog? m_toolbars; private EditorDropRouter? m_drops; - private string m_focusedArea = EditorBuiltInInteractionIds.C_GLOBAL_AREA; + private string m_focusedArea = EditorBuiltInInteractionIDs.C_GLOBAL_AREA; private EditorTargetReference? m_focus; private EditorTargetReference[]? m_previousGenerationSelection; private EditorTargetReference? m_previousGenerationFocus; private EditorTargetReference? m_previousGenerationAnchor; private bool m_generationTransitionPrepared; + internal EditorInteractions( EditorContext editor, IEnumerable identityDomains, Logger log ) { - m_editor = editor ?? throw new ArgumentNullException(nameof(editor)); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(log); + m_editor = editor; ArgumentNullException.ThrowIfNull(identityDomains); - m_identityDomains = identityDomains.ToDictionary(static allocator => allocator.domainId); - m_log = log ?? throw new ArgumentNullException(nameof(log)); - selection = new EditorSelectionState(this); + m_identityDomains = identityDomains.ToDictionary(static allocator => allocator.domainID); + m_log = log; + this.selection = new EditorSelectionState(this); m_documents = new EditorDocumentService(events); - m_history = new EditorHistory(new EditorHistoryOptions { cacheDirectory = Path.Combine(editor.projectDirectory, "Library", "Editor", "History") }, log); + m_history = new EditorHistory( + new EditorHistoryOptions { cacheDirectory = Path.Combine(editor.projectDirectory, "Library", "Editor", "History") }, + log + ); m_history.Attach(editor, this); } @@ -56,7 +63,6 @@ Logger log [ScriptingApiIgnore] public EventDispatcher events { get; } = new(); - internal void PrepareOperation() => events.Emit(new EditorOperationPreparingEvent()); /// /// Gets the shared read-only editor selection state. /// @@ -67,16 +73,28 @@ Logger log /// public EditorKeyboardPolicy keyboard => m_editor.keyboard; - object? IEditorSelectionCoordinator.selectedTarget => selection.selectedTarget; /// /// Gets the transactional Undo and Redo history owned by this editor runtime. /// public IEditorHistory history => m_history; + /// /// Gets the headless reload-safe document lifetime used by dedicated asset editors and Inspectors. /// public IEditorDocumentService documents => m_documents; + /// + /// Gets the area that most recently received keyboard focus. + /// + public string focusedArea => m_focusedArea; + + /// + /// Gets the target associated with the focused area. + /// + public object? focusedTarget => m_focus?.Resolve(this); + + object? IEditorSelectionCoordinator.selectedTarget => selection.selectedTarget; + /// /// Resolves an active feature module for immediate use in the current Editor callback. /// @@ -96,7 +114,9 @@ public bool TryGetModule(out TModule? module) where TModule : EditorModule { if (m_catalog is not null) + { return m_catalog.TryGetModule(out module); + } module = null; return false; } @@ -104,23 +124,18 @@ public bool TryGetModule(out TModule? module) /// /// Starts an isolated temporary Undo and Redo branch while retaining the current editing branch. /// - /// - /// Disposing the returned scope releases every temporary operation and restores the retained branch. - /// This host-level boundary is intended for transient editor sessions such as Play Mode. - /// /// /// A scope that restores the retained history branch when disposed. /// /// /// Thrown during an Undo, Redo, transaction, or another isolated branch. /// + /// + /// Disposing the returned scope releases every temporary operation and restores the retained branch. + /// This host-level boundary is intended for transient editor sessions such as Play Mode. + /// [ScriptingApiIgnore] public IDisposable BeginHistoryIsolation() => m_history.BeginIsolation(); - internal EditorHistory historyHost => m_history; - /// - /// Gets the area that most recently received keyboard focus. - /// - public string focusedArea => m_focusedArea; /// /// Gets immutable discovery metadata for the active, available panels. @@ -128,11 +143,12 @@ public bool TryGetModule(out TModule? module) /// /// Current panel declarations; the snapshot contains no panel or extension instances. /// - public IReadOnlyList GetPanelDeclarations() => m_catalog?.GetPanelDeclarations() ?? Array.Empty(); + public IReadOnlyList GetPanelDeclarations() => m_catalog?.GetPanelDeclarations() ?? []; + /// /// Reads whether one available panel is currently open. /// - /// + /// /// The stable panel identity. /// /// @@ -142,19 +158,14 @@ public bool TryGetModule(out TModule? module) /// True when the current generation contains the requested available panel. /// public bool TryGetPanelState( - string panelId, + string panelID, out bool isOpen ) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); isOpen = false; - return m_catalog?.TryGetPanelState(panelId, out isOpen) == true; + return m_catalog?.TryGetPanelState(panelID, out isOpen) == true; } - /// - /// Gets the target associated with the focused area. - /// - public object? focusedTarget => m_focus?.Resolve(this); - /// /// Creates a lightweight interaction handle for one area and optional target. /// @@ -174,6 +185,7 @@ public EditorInteraction For( string area, object? target = null ) => new(this, area, target); + /// /// Replaces the editor selection after closing presentations owned by other targets. /// @@ -184,9 +196,13 @@ public void SetSelection(object? target) { PrepareOperation(); if (target is null) + { selection.Clear(); + } else + { selection.Select(target); + } PrepareSelectionChange(target); } @@ -226,11 +242,13 @@ public void SetSelection( public void ToggleSelection(IdentityObject target) { ArgumentNullException.ThrowIfNull(target); - var values = new List(); + List values = []; _ = selection.CopyTargets(values); bool removed = values.Remove(target); if (!removed) + { values.Add(target); + } SetSelection(values, selection.anchor as IdentityObject ?? target); } @@ -268,29 +286,41 @@ public void SelectRange( for (int i = 0; i < orderedTargets.Count; i++) { if (orderedTargets[i] == anchor.identity.runtimeIdentity) + { first = i; + } if (orderedTargets[i] == target.identity.runtimeIdentity) + { last = i; + } } if (last < 0) + { throw new ArgumentException("The selection endpoint is not in the visible order.", nameof(target)); + } if (first < 0) { first = last; anchor = target; } - var values = new List(); + List values = []; if (additive) + { _ = selection.CopyTargets(values); + } var included = new HashSet(values, ReferenceEqualityComparer.Instance); for (int i = Math.Min(first, last); i <= Math.Max(first, last); i++) { if (!TryResolveIdentity(orderedTargets[i], out IdentityObject? value) || value is null) + { throw new InvalidOperationException("The visible selection range contains an unavailable identity."); + } if (!ReferenceEquals(value, target) && included.Add(value)) + { values.Add(value); + } } _ = values.Remove(target); @@ -313,7 +343,8 @@ public void SelectRange( public bool TryGetDragSource( RuntimeIdentity identity, out IdentityObject? source - ) => Drops.TryGetSource(identity, out source); + ) => drops.TryGetSource(identity, out source); + /// /// Gets the active drag identity used to select the matching native payload domain. /// @@ -323,23 +354,24 @@ out IdentityObject? source /// /// when a live drag source exists; otherwise, . /// - public bool TryGetActiveDragIdentity(out RuntimeIdentity identity) => Drops.TryGetActiveIdentity(out identity); + public bool TryGetActiveDragIdentity(out RuntimeIdentity identity) => drops.TryGetActiveIdentity(out identity); + /// /// Toggles one panel in the currently active extension generation. /// - /// + /// /// The stable panel identifier to resolve. /// /// /// when an available panel was found and toggled. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// - public bool TogglePanel(string panelId) + public bool TogglePanel(string panelID) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - return m_catalog?.TryTogglePanel(panelId) == true; + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + return m_catalog?.TryTogglePanel(panelID) == true; } /// @@ -366,9 +398,11 @@ public IDisposable RegisterIdentityDomain(IdentityAllocator allocator) ArgumentNullException.ThrowIfNull(allocator); EnsureIdentityDomainOwner(); ObjectDisposedException.ThrowIf(m_identityDomainsRetired, this); - if (!m_identityDomains.TryAdd(allocator.domainId, allocator)) + if (!m_identityDomains.TryAdd(allocator.domainID, allocator)) + { throw new InvalidOperationException("The Editor identity domain is already registered."); - return new IdentityDomainLease(this, allocator.domainId); + } + return new IdentityDomainLease(this, allocator.domainID); } /// @@ -388,17 +422,19 @@ public bool TryResolveIdentity( RuntimeIdentity identity, out IdentityObject? target ) { - target = m_identityDomains.TryGetValue(identity.domainId, out IdentityAllocator? allocator) ? allocator.Get(identity) : null; + target = m_identityDomains.TryGetValue(identity.domainID, out IdentityAllocator? allocator) + ? allocator.Get(identity) + : null; return target is not null; } /// /// Resolves a persistent identity through one explicitly selected Editor identity domain. /// - /// + /// /// Identity domain that owns the object and any replacement generation. /// - /// + /// /// Stable object identity to resolve inside that domain. /// /// @@ -409,50 +445,56 @@ out IdentityObject? target /// [ScriptingApiIgnore] public bool TryResolveIdentity( - IdentityDomainId domainId, - Guid persistentId, + IdentityDomainID domainID, + Guid persistentID, out IdentityObject? target ) { - target = persistentId != Guid.Empty && m_identityDomains.TryGetValue(domainId, out IdentityAllocator? allocator) ? allocator.Get(persistentId) : null; + target = persistentID != Guid.Empty && m_identityDomains.TryGetValue(domainID, out IdentityAllocator? allocator) + ? allocator.Get(persistentID) + : null; return target is not null; } /// /// Opens and requests presentation focus for one panel in the active extension generation. /// - /// + /// /// The stable panel identifier to resolve. /// /// /// when an available panel was found. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// - public bool OpenPanel(string panelId) + public bool OpenPanel(string panelID) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - return m_catalog?.TryOpenPanel(panelId) == true; + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + return m_catalog?.TryOpenPanel(panelID) == true; } /// /// Closes one panel in the active extension generation without toggling its current state. /// - /// + /// /// The stable panel identifier to resolve. /// /// /// when an available panel was found. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// - public bool ClosePanel(string panelId) + public bool ClosePanel(string panelID) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - return m_catalog?.TryClosePanel(panelId) == true; + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + return m_catalog?.TryClosePanel(panelID) == true; } + internal EditorHistory historyHost => m_history; + + internal void PrepareOperation() => events.Emit(new EditorOperationPreparingEvent()); + internal void Attach(EditorExtensionCatalog catalog) { ArgumentNullException.ThrowIfNull(catalog); @@ -466,33 +508,37 @@ internal void Attach(EditorExtensionCatalog catalog) internal void Update() { ResolveGenerationTargets(); - Actions.Flush(); + actions.Flush(); } internal void PrepareGenerationTransition() { if (m_generationTransitionPrepared) + { throw new InvalidOperationException("An interaction generation transition is already active."); + } m_previousGenerationSelection = selection.CaptureReferences(); m_previousGenerationAnchor = selection.anchorReference; m_previousGenerationFocus = m_focus; m_generationTransitionPrepared = true; - Actions.ResetTransientState(); - Drops.Cancel(); + actions.ResetTransientState(); + drops.Cancel(); } internal void RollbackGenerationTransition() { - Actions.ResetTransientState(); + actions.ResetTransientState(); if (m_previousGenerationSelection is not null) + { selection.Restore(m_previousGenerationSelection, m_previousGenerationAnchor); + } m_focus = m_previousGenerationFocus; CompleteGenerationTransition(); } internal void CompleteGenerationTransition() { - Actions.InvalidateDiscovery(); + actions.InvalidateDiscovery(); m_menus?.InvalidateDiscovery(); selection.Rebind(); m_focus = m_focus?.Rebind(this); @@ -504,12 +550,12 @@ internal void CompleteGenerationTransition() internal void Shutdown(IReadOnlyList actions) { - Actions.Clear(actions); + this.actions.Clear(actions); m_menus?.InvalidateDiscovery(); - Drops.Cancel(); + drops.Cancel(); m_catalog = null; selection.Clear(); - m_focusedArea = EditorBuiltInInteractionIds.C_GLOBAL_AREA; + m_focusedArea = EditorBuiltInInteractionIDs.C_GLOBAL_AREA; m_focus = null; m_previousGenerationSelection = null; m_previousGenerationAnchor = null; @@ -520,7 +566,9 @@ internal void Shutdown(IReadOnlyList m_identityDomainsRetired = true; } - internal bool DispatchShortcut(KeyPressedEvent keyEvent) => Actions.DispatchShortcut(keyEvent, m_focusedArea, focusedTarget ?? selection.selectedTarget); + internal bool DispatchShortcut(KeyPressedEvent keyEvent) + => actions.DispatchShortcut(keyEvent, m_focusedArea, focusedTarget ?? selection.selectedTarget); + internal void Focus( string area, object? target @@ -529,40 +577,47 @@ internal void Focus( m_focus = target is null ? null : EditorTargetReference.Capture(target); } - internal void PrepareSelectionChange(object? target) => Actions.LosePresentationExcept(target); + internal void PrepareSelectionChange(object? target) => actions.LosePresentationExcept(target); + internal EditorActionState Query( string action, string area, object? target, object? argument - ) => Actions.Query(action, CreateActionContext(area, target, argument)); + ) => actions.Query(action, CreateActionContext(area, target, argument)); + internal bool Execute( string action, string area, object? target, object? argument - ) => Actions.Execute(action, CreateActionContext(area, target, argument)); + ) => actions.Execute(action, CreateActionContext(area, target, argument)); + internal void Enqueue( string action, string area, object? target, object? argument - ) => Actions.Enqueue(action, CreateActionContext(area, target, argument)); + ) => actions.Enqueue(action, CreateActionContext(area, target, argument)); + internal bool Present( string action, string area, object? target, object? argument - ) => Actions.Present(action, CreateActionContext(area, target, argument)); + ) => actions.Present(action, CreateActionContext(area, target, argument)); + internal bool IsActive( string action, string area, object? target - ) => Actions.IsActive(action, CreateActionContext(area, target, null)); + ) => actions.IsActive(action, CreateActionContext(area, target, null)); + internal EditorMenuModel BuildMenu( string area, object? target - ) => Menus.Build(new EditorMenuContext(m_editor, this, area, target)); + ) => menus.Build(new EditorMenuContext(m_editor, this, area, target)); + internal EditorMenuModel BuildCommands( string area, object? target @@ -570,14 +625,16 @@ internal EditorMenuModel BuildCommands( EditorMenuModel menu = BuildMenu(area, target); var placed = new HashSet(StringComparer.Ordinal); Collect(menu.items); - IReadOnlyList additional = Actions.BuildUnplacedCommands(CreateActionContext(area, target, null), placed); + IReadOnlyList additional = actions.BuildUnplacedCommands(CreateActionContext(area, target, null), placed); return new EditorMenuModel([..menu.items, ..additional]); void Collect(IReadOnlyList items) { foreach (EditorMenuItem item in items) { - if (item.actionId.Length != 0) - _ = placed.Add(item.actionId); + if (item.actionID.Length != 0) + { + _ = placed.Add(item.actionID); + } Collect(item.children); } } @@ -586,21 +643,25 @@ void Collect(IReadOnlyList items) internal EditorToolbarModel BuildToolbar( string area, object? target - ) => Toolbars.Build(CreateActionContext(area, target, argument: null)); + ) => toolbars.Build(CreateActionContext(area, target, argument: null)); + internal bool TryGetShortcut( string action, string area, object? target, out HotKeyGesture gesture - ) => Actions.TryGetShortcut(action, area, target, out gesture); + ) => actions.TryGetShortcut(action, area, target, out gesture); + internal RuntimeIdentity BeginDrag( string area, EditorDragData data ) { if (m_catalog is null) + { throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + } _ = m_catalog.extensions; - return Drops.Begin(new EditorDragContext(m_editor, this, area, data)); + return drops.Begin(new EditorDragContext(m_editor, this, area, data)); } internal EditorDropStatus QueryDrop( @@ -609,9 +670,14 @@ internal EditorDropStatus QueryDrop( object? target, EditorDropPlacement placement ) { - if (target is null || !Drops.TryGetSource(identity, out IdentityObject? source) || source is null) + if (target is null || !drops.TryGetSource(identity, out IdentityObject? source) || source is null) + { return EditorDropStatus.rejected; - return Drops.Query(identity, new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement)); + } + return drops.Query( + identity, + new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement) + ); } internal EditorDropResult Drop( @@ -620,48 +686,63 @@ internal EditorDropResult Drop( object? target, EditorDropPlacement placement ) { - if (target is null || !Drops.TryGetSource(identity, out IdentityObject? source) || source is null) + if (target is null || !drops.TryGetSource(identity, out IdentityObject? source) || source is null) + { return EditorDropResult.rejected; - return Drops.Drop(identity, new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement)); + } + return drops.Drop( + identity, + new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement) + ); } - private EditorActionRouter Actions => m_actions ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); - private EditorMenuCatalog Menus => m_menus ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); - private EditorDropRouter Drops => m_drops ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); - private EditorToolbarCatalog Toolbars => m_toolbars ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + private EditorActionRouter actions + => m_actions ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + + private EditorMenuCatalog menus => m_menus ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + private EditorDropRouter drops => m_drops ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + + private EditorToolbarCatalog toolbars + => m_toolbars ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); private EditorActionContext CreateActionContext( string area, object? target, object? argument ) => new(m_editor, this, area, target, argument); + private void ResolveGenerationTargets() { selection.Rebind(); m_focus = m_focus?.Rebind(this); } + private void EnsureIdentityDomainOwner() { if (Environment.CurrentManagedThreadId != m_identityOwnerThread) + { throw new InvalidOperationException("Editor identity domains must be changed on the owning thread."); + } } private sealed class IdentityDomainLease( EditorInteractions owner, - IdentityDomainId domain + IdentityDomainID domain ) : IDisposable { private EditorInteractions? m_owner = owner; - /// + + /// public void Dispose() { EditorInteractions? active = m_owner; if (active is null) + { return; + } active.EnsureIdentityDomainOwner(); active.m_identityDomains.Remove(domain); m_owner = null; } } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs index 1f0cfd394..8cbd12c52 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -73,15 +72,21 @@ out Vector2? contentSize ArgumentNullException.ThrowIfNull(context); contentSize = null; if (m_isQuarantined) + { return false; + } try { contentSize = m_modal.Prepare(context, availableContentSize); - if (contentSize is Vector2 size && - (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f)) + if (contentSize is Vector2 size + && (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f) + ) { throw new InvalidOperationException("Modal preparation returned an invalid content extent."); + } if (presentation.initialSize.Y <= 0f && contentSize is null) + { throw new InvalidOperationException("A content-sized modal must measure its current content before drawing."); + } return true; } catch (Exception exception) @@ -118,12 +123,17 @@ public bool TryGetPresentation(out Presentation presentation) m_modal.canResize, m_modal.allowScrolling, m_modal.initialSize, - m_modal.minimumSize); + m_modal.minimumSize + ); Vector2 initial = presentation.initialSize; Vector2 minimum = presentation.minimumSize; - if (!float.IsFinite(initial.X) || !float.IsFinite(initial.Y) || initial.X < 0f || initial.Y < 0f || - !float.IsFinite(minimum.X) || !float.IsFinite(minimum.Y) || minimum.X < 0f || minimum.Y < 0f) - throw new InvalidOperationException("Modal dimensions must be finite and nonnegative; zero leaves that dimension unspecified."); + if (!float.IsFinite(initial.X) || !float.IsFinite(initial.Y) || initial.X < 0f || initial.Y < 0f + || !float.IsFinite(minimum.X) || !float.IsFinite(minimum.Y) || minimum.X < 0f || minimum.Y < 0f + ) { + throw new InvalidOperationException( + "Modal dimensions must be finite and nonnegative; zero leaves that dimension unspecified." + ); + } return true; } catch (Exception exception) @@ -151,7 +161,9 @@ public bool Draw(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (m_isQuarantined) + { return false; + } try { m_modal.Draw(context); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs index 9bbf7727a..7e3b0ca53 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs @@ -1,6 +1,6 @@ using System; using System.Numerics; - +using Inno.Core.Execution; using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -89,10 +89,12 @@ out Vector2 initialSize allowScrolling = m_panel.allowScrolling; initialSize = m_panel.initialSize; if (!float.IsFinite(initialSize.X) || !float.IsFinite(initialSize.Y) || initialSize.X < 0 || initialSize.Y < 0) + { throw new InvalidOperationException("A panel's initial size must contain finite nonnegative dimensions."); + } return true; } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { useWindowPadding = true; allowScrolling = true; @@ -123,7 +125,7 @@ public bool Draw(EditorContext context) m_panel.Draw(context); return true; } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { m_panel.isOpen = false; m_quarantine(exception); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs index 790e2a766..2a1e98249 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs @@ -2,55 +2,43 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + internal sealed class EditorTargetReference { private readonly object? m_value; private readonly WeakReference? m_target; + private EditorTargetReference( RuntimeIdentity? runtimeIdentity, - Guid persistentId, + Guid persistentID, object? value, WeakReference? target ) { this.runtimeIdentity = runtimeIdentity; - this.persistentId = persistentId; + this.persistentID = persistentID; m_value = value; m_target = target; } internal RuntimeIdentity? runtimeIdentity { get; } - internal Guid persistentId { get; } - - internal static EditorTargetReference Capture(object? value) - { - if (value is IdentityObject target) - { - RuntimeIdentity runtime = target.identity.runtimeIdentity ?? throw new InvalidOperationException("An editor interaction target must belong to a live identity domain."); - return new EditorTargetReference(runtime, target.identity.persistentId, null, null); - } - - if (value is null or string or decimal or Guid or DateTime or DateTimeOffset - or DateOnly or TimeOnly or TimeSpan or Half or Int128 or UInt128) - return new EditorTargetReference(null, Guid.Empty, value, null); - Type type = value.GetType(); - if (type.IsPrimitive || type.IsEnum && !type.IsCollectible) - return new EditorTargetReference(null, Guid.Empty, value, null); - // A host-defined struct can still contain extension objects; boxing does not make it neutral. - return new EditorTargetReference(null, Guid.Empty, null, new WeakReference(value)); - } + internal Guid persistentID { get; } internal object? Resolve(EditorInteractions interactions) { if (runtimeIdentity is RuntimeIdentity runtime) + { return interactions.TryResolveIdentity(runtime, out IdentityObject? target) ? target : null; + } return m_target is not null ? m_target.TryGetTarget(out object? value) ? value : null : m_value; } internal EditorTargetReference Rebind(EditorInteractions interactions) { if (runtimeIdentity is not RuntimeIdentity runtime || interactions.TryResolveIdentity(runtime, out _)) + { return this; - if (interactions.TryResolveIdentity(runtime.domainId, persistentId, out IdentityObject? replacement) && replacement is not null) + } + if (interactions.TryResolveIdentity(runtime.domainID, persistentID, out IdentityObject? replacement) && replacement is not null) { return Capture(replacement); } @@ -63,7 +51,32 @@ internal bool Matches( object? target ) { if (target is IdentityObject identity && runtimeIdentity is RuntimeIdentity runtime) + { return identity.identity.runtimeIdentity == runtime; + } return Equals(Resolve(interactions), target); } + + internal static EditorTargetReference Capture(object? value) + { + if (value is IdentityObject target) + { + RuntimeIdentity runtime = target.identity.runtimeIdentity + ?? throw new InvalidOperationException("An editor interaction target must belong to a live identity domain."); + return new EditorTargetReference(runtime, target.identity.persistentID, null, null); + } + + if (value is null or string or decimal or Guid or DateTime or DateTimeOffset + or DateOnly or TimeOnly or TimeSpan or Half or Int128 or UInt128 + ) { + return new EditorTargetReference(null, Guid.Empty, value, null); + } + Type type = value.GetType(); + if (type.IsPrimitive || type.IsEnum && !type.IsCollectible) + { + return new EditorTargetReference(null, Guid.Empty, value, null); + } + // A host-defined struct can still contain extension objects; boxing does not make it neutral. + return new EditorTargetReference(null, Guid.Empty, null, new WeakReference(value)); + } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/IEditorSelectionCoordinator.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/IEditorSelectionCoordinator.cs index 09ba9d282..38080304f 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/IEditorSelectionCoordinator.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/IEditorSelectionCoordinator.cs @@ -9,6 +9,11 @@ namespace Inno.Editor.Interactions; /// public interface IEditorSelectionCoordinator { + /// + /// Gets the currently selected target, or when selection is empty. + /// + object? selectedTarget { get; } + /// /// Registers the Core identity domain used by a temporary scene presentation. /// @@ -30,11 +35,6 @@ public interface IEditorSelectionCoordinator [ScriptingApiIgnore] IDisposable RegisterIdentityDomain(IdentityAllocator allocator); - /// - /// Gets the currently selected target, or when selection is empty. - /// - object? selectedTarget { get; } - /// /// Replaces the current target after closing presentations owned by another target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs index 2c07a9d0e..d4494bff8 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs @@ -4,18 +4,22 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Captures ordered selection identities without retaining any domain object or extension instance. /// public sealed class EditorSelectionSnapshot { private readonly EditorTargetReference[] m_targets; + internal EditorSelectionSnapshot( IEnumerable targets, RuntimeIdentity? anchor ) { m_targets = targets.ToArray(); - this.identities = Array.AsReadOnly(m_targets.Where(value => value.runtimeIdentity is not null).Select(value => value.runtimeIdentity!.Value).ToArray()); + this.identities = Array.AsReadOnly( + m_targets.Where(value => value.runtimeIdentity is not null).Select(value => value.runtimeIdentity!.Value).ToArray() + ); this.anchor = anchor; } @@ -23,11 +27,17 @@ internal EditorSelectionSnapshot( /// Gets unique selection identities in order; the final identity is the primary selection. /// public IReadOnlyList identities { get; } + /// /// Gets the range anchor identity, or null when there is no registered anchor. /// public RuntimeIdentity? anchor { get; } + /// + /// Gets the primary identity, or null when this snapshot contains no registered targets. + /// + public RuntimeIdentity? primary => identities.Count == 0 ? null : identities[^1]; + /// /// Resolves this immutable selection in its original domains, including same-identity recovery after a generation change. /// @@ -46,20 +56,18 @@ internal EditorSelectionSnapshot( public int CopyTargets( EditorInteractions interactions, ICollection destination - ) - where TTarget : class + ) where TTarget : class { ArgumentNullException.ThrowIfNull(interactions); ArgumentNullException.ThrowIfNull(destination); destination.Clear(); foreach (EditorTargetReference reference in m_targets) + { if (reference.Rebind(interactions).Resolve(interactions) is TTarget target) + { destination.Add(target); + } + } return destination.Count; } - - /// - /// Gets the primary identity, or null when this snapshot contains no registered targets. - /// - public RuntimeIdentity? primary => identities.Count == 0 ? null : identities[^1]; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs index 93647e5cb..caf6756df 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs @@ -4,6 +4,7 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Owns ordered transient selection through domain-qualified identities instead of retaining live objects. /// @@ -14,6 +15,7 @@ public sealed class EditorSelectionState private HashSet m_identityMembership = []; private EditorTargetReference? m_anchor; private EditorSelectionSnapshot? m_snapshot; + internal EditorSelectionState(EditorInteractions interactions) { m_interactions = interactions; @@ -23,14 +25,17 @@ internal EditorSelectionState(EditorInteractions interactions) /// Gets the current primary target for this callback, or null when unavailable or unselected. /// public object? selectedTarget => m_targets.Length == 0 ? null : m_targets[^1].Resolve(m_interactions); + /// /// Gets the number of selected identities, including temporarily unavailable members. /// public int count => m_targets.Length; + /// /// Gets the current range anchor, or null when the anchor is unavailable. /// public object? anchor => m_anchor?.Resolve(m_interactions); + /// /// Gets the selection revision, incremented only when membership, order or resolved generation changes. /// @@ -48,13 +53,19 @@ internal EditorSelectionState(EditorInteractions interactions) public bool Contains(object? target) { if (target is null) + { return false; + } if (target is IdentityObject identity) + { return identity.identity.runtimeIdentity is RuntimeIdentity runtime && m_identityMembership.Contains(runtime); + } foreach (EditorTargetReference entry in m_targets) { if (entry.Matches(m_interactions, target)) + { return true; + } } return false; @@ -83,7 +94,9 @@ public int CopyTargets(ICollection destination) foreach (EditorTargetReference entry in m_targets) { if (entry.Resolve(m_interactions) is TTarget target) + { destination.Add(target); + } } return destination.Count; @@ -98,7 +111,9 @@ public int CopyTargets(ICollection destination) public EditorSelectionSnapshot Capture() { if (m_snapshot is not null) + { return m_snapshot; + } return m_snapshot = new EditorSelectionSnapshot(m_targets, m_anchor?.runtimeIdentity); } @@ -126,11 +141,15 @@ public bool TryGet([NotNullWhen(true)] out TTarget? target) return false; } + internal EditorTargetReference? anchorReference => m_anchor; + internal void Select(object target) { ArgumentNullException.ThrowIfNull(target); if (m_targets.Length == 1 && m_targets[0].Matches(m_interactions, target)) + { return; + } EditorTargetReference entry = EditorTargetReference.Capture(target); m_targets = [entry]; m_anchor = entry; @@ -142,22 +161,28 @@ internal void Replace( IdentityObject? anchor ) { ArgumentNullException.ThrowIfNull(targets); - var entries = new List(); + List entries = []; var seen = new HashSet(); foreach (IdentityObject target in targets) { ArgumentNullException.ThrowIfNull(target); EditorTargetReference entry = EditorTargetReference.Capture(target); if (seen.Add(entry.runtimeIdentity!.Value)) + { entries.Add(entry); + } } EditorTargetReference? nextAnchor = anchor is null ? entries.Count == 0 ? null : entries[0] : EditorTargetReference.Capture(anchor); bool equal = entries.Count == m_targets.Length && nextAnchor?.runtimeIdentity == m_anchor?.runtimeIdentity; for (int i = 0; equal && i < entries.Count; i++) + { equal = entries[i].runtimeIdentity == m_targets[i].runtimeIdentity; + } if (equal) + { return; + } m_targets = entries.ToArray(); m_anchor = nextAnchor; Changed(seen); @@ -166,15 +191,16 @@ internal void Replace( internal void Clear() { if (m_targets.Length == 0) + { return; + } m_targets = []; m_anchor = null; Changed(); } - internal EditorTargetReference? anchorReference => m_anchor; - internal EditorTargetReference[] CaptureReferences() => (EditorTargetReference[])m_targets.Clone(); + internal void Restore( EditorTargetReference[] targets, EditorTargetReference? anchor @@ -191,15 +217,21 @@ internal void Rebind() { EditorTargetReference rebound = m_targets[i].Rebind(m_interactions); if (rebound.runtimeIdentity == m_targets[i].runtimeIdentity) + { continue; + } m_targets[i] = rebound; changed = true; } if (m_anchor is not null) + { m_anchor = m_anchor.Rebind(m_interactions); + } if (changed) + { Changed(); + } } private void Changed(HashSet? identities = null) @@ -208,8 +240,12 @@ private void Changed(HashSet? identities = null) { identities = new HashSet(m_targets.Length); foreach (EditorTargetReference target in m_targets) + { if (target.runtimeIdentity is RuntimeIdentity identity) + { identities.Add(identity); + } + } } m_identityMembership = identities; m_snapshot = null; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs index f32a7692b..84dca55fd 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; namespace Inno.Editor.Interactions; @@ -14,6 +13,17 @@ internal sealed class EditorExtensionStateDiagnosticPublisher : IDisposable private readonly Dictionary m_states = new(StringComparer.Ordinal); + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + foreach (string group in m_states.Keys.ToArray()) + { + Resolve(group); + } + } + internal bool PublishCapture(IReadOnlyList messages) => Publish(C_CAPTURE_GROUP, "EDITOR-STATE-CAPTURE", messages); internal bool PublishRestore(IReadOnlyList messages) => Publish(C_RESTORE_GROUP, "EDITOR-STATE-RESTORE", messages); @@ -26,15 +36,6 @@ internal bool PublishSave(Exception exception) internal void ResolveSave() => Resolve(C_SAVE_GROUP); - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - foreach (string group in m_states.Keys.ToArray()) - Resolve(group); - } - private bool Publish( string group, string code, @@ -51,14 +52,12 @@ IReadOnlyList messages return false; } string state = string.Join('\n', current); - if (m_states.TryGetValue(group, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_states.TryGetValue(group, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; } - Diagnostics.Set( - group, - current.Select(message => Diagnostic.Error(code, message))); + Diagnostics.Set(group, current.Select(message => Diagnostic.Error(code, message))); m_states[group] = state; return true; } @@ -66,7 +65,9 @@ IReadOnlyList messages private void Resolve(string group) { if (!m_states.Remove(group)) + { return; + } Diagnostics.Clear(group); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs index 8015ae51b..ef451c12f 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; - using Inno.Core.Logging; using Inno.Editor.Core; @@ -27,19 +26,20 @@ internal EditorExtensionStateStore( Logger log ) { ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(log); m_context = context; - m_log = log ?? throw new ArgumentNullException(nameof(log)); + m_log = log; } internal bool TryGetPanelOpen( - string panelId, + string panelID, out bool isOpen ) { - ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - if (m_context.TryGetLayoutSection(C_PANELS_SECTION, out IReadOnlyDictionary values) && - values.TryGetValue(panelId, out string? stored) && - bool.TryParse(stored, out isOpen)) - { + ArgumentException.ThrowIfNullOrWhiteSpace(panelID); + if (m_context.TryGetLayoutSection(C_PANELS_SECTION, out IReadOnlyDictionary values) + && values.TryGetValue(panelID, out string? stored) + && bool.TryParse(stored, out isOpen) + ) { return true; } isOpen = false; @@ -50,56 +50,57 @@ internal void Capture( IReadOnlyList registrations, IReadOnlyList panels ) { - var failures = new List<(string Message, Exception Exception)>(); + List<(string message, Exception exception)> failures = []; for (int i = 0; i < registrations.Count; i++) { EditorExtensionCatalog.StateRegistration registration = registrations[i]; - if (!m_restoredOwners.TryGetValue(registration.owner, out RestoredOwner? owner) || - !owner.isRestored) - { + if (!m_restoredOwners.TryGetValue(registration.owner, out RestoredOwner? owner) + || !owner.isRestored + ) { continue; } try { var state = new EditorJsonState(); registration.capture(state); - m_context.SetLayoutSection( - GetSectionName(registration), - state.Export()); + m_context.SetLayoutSection(GetSectionName(registration), state.Export()); } catch (Exception exception) { - failures.Add(( - $"Extension '{registration.id}' failed to capture state: {exception.Message}", - exception)); + failures.Add( + ( + $"Extension '{registration.id}' failed to capture state: {exception.Message}", + exception) + ); } } - if (m_diagnostics.PublishCapture(failures.Select(static failure => failure.Message).ToArray())) + if (m_diagnostics.PublishCapture(failures.Select(static failure => failure.message).ToArray())) { for (int i = 0; i < failures.Count; i++) - m_log.Write( - LogLevel.Error, - "{0} Full exception: {1}", - [failures[i].Message, failures[i].Exception]); + { + m_log.Write(LogLevel.Error, "{0} Full exception: {1}", [failures[i].message, failures[i].exception]); + } } var panelValues = new Dictionary(StringComparer.Ordinal); for (int i = 0; i < panels.Count; i++) + { panelValues[panels[i].attribute.id] = panels[i].panel.isOpen ? "true" : "false"; + } m_context.SetLayoutSection(C_PANELS_SECTION, panelValues); } internal void Restore(IReadOnlyList registrations) { - var failures = new List<(string Message, Exception Exception)>(); + List<(string message, Exception exception)> failures = []; for (int i = 0; i < registrations.Count; i++) { EditorExtensionCatalog.StateRegistration registration = registrations[i]; - RestoredOwner owner = m_restoredOwners.GetValue( - registration.owner, - static _ => new RestoredOwner()); + RestoredOwner owner = m_restoredOwners.GetValue(registration.owner, static _ => new RestoredOwner()); if (owner.isRestored || owner.isRestoring) + { continue; + } owner.isRestoring = true; try { @@ -109,22 +110,23 @@ internal void Restore(IReadOnlyList re catch (Exception exception) { _ = m_restoredOwners.Remove(registration.owner); - failures.Add(( - $"Extension '{registration.id}' failed to restore state: {exception.Message}", - exception)); + failures.Add( + ( + $"Extension '{registration.id}' failed to restore state: {exception.Message}", + exception) + ); } finally { owner.isRestoring = false; } } - if (m_diagnostics.PublishRestore(failures.Select(static failure => failure.Message).ToArray())) + if (m_diagnostics.PublishRestore(failures.Select(static failure => failure.message).ToArray())) { for (int i = 0; i < failures.Count; i++) - m_log.Write( - LogLevel.Error, - "{0} Full exception: {1}", - [failures[i].Message, failures[i].Exception]); + { + m_log.Write(LogLevel.Error, "{0} Full exception: {1}", [failures[i].message, failures[i].exception]); + } } SaveIfChanged(); } @@ -137,7 +139,9 @@ internal void Update( IReadOnlyList panels ) { if (m_isShutdownPrepared || elapsedSeconds < m_nextSaveTime) + { return; + } m_nextSaveTime = elapsedSeconds + C_SAVE_INTERVAL_SECONDS; Capture(registrations, panels); SaveIfChanged(); @@ -161,7 +165,9 @@ internal void PrepareShutdown( IReadOnlyList panels ) { if (m_isShutdownPrepared) + { return; + } // Freeze periodic persistence before capturing the terminal extension snapshot. Module // shutdown may unload scenes and clear panels, and that transient teardown state must @@ -175,7 +181,9 @@ private EditorState CreateState(EditorExtensionCatalog.StateRegistration registr { string sectionName = GetSectionName(registration); if (!m_context.TryGetLayoutSection(sectionName, out IReadOnlyDictionary values)) + { return new EditorJsonState(values: null); + } return new EditorJsonState(values); } @@ -193,7 +201,8 @@ private void SaveIfChanged() m_log.Write( LogLevel.Error, "Editor extension state could not be saved to '{0}': {1}", - [m_context.layoutPath, exception]); + [m_context.layoutPath, exception] + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs index 7a16b23d3..c716a0381 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Text.Json; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -43,7 +42,9 @@ T fallback ) { ArgumentException.ThrowIfNullOrWhiteSpace(key); if (!m_values.TryGetValue(key, out string? payload)) + { return fallback; + } try { T? value = JsonSerializer.Deserialize(payload); @@ -78,8 +79,7 @@ T value ArgumentException.ThrowIfNullOrWhiteSpace(key); if (m_writableValues is null) { - throw new InvalidOperationException( - "Editor state supplied for restoration cannot be modified."); + throw new InvalidOperationException("Editor state supplied for restoration cannot be modified."); } try { @@ -87,13 +87,12 @@ T value } catch (JsonException exception) { - throw new NotSupportedException( - $"Editor state value '{key}' cannot be serialized.", - exception); + throw new NotSupportedException($"Editor state value '{key}' cannot be serialized.", exception); } } internal IReadOnlyDictionary Export() => m_writableValues ?? throw new InvalidOperationException( - "Only editor state captured by an extension can be exported."); + "Only editor state captured by an extension can be exported." + ); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs index ed5950316..72ec14427 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs @@ -10,7 +10,7 @@ EditorActionRouter actions internal EditorToolbarModel Build(EditorActionContext context) { ArgumentNullException.ThrowIfNull(context); - var items = new List<(EditorToolbarItem Item, string TypeName)>(); + List<(EditorToolbarItem item, string typeName)> items = []; EditorExtensionCatalog.Snapshot snapshot = catalog.extensions; for (int actionIndex = 0; actionIndex < snapshot.actions.Length; actionIndex++) { @@ -19,20 +19,27 @@ internal EditorToolbarModel Build(EditorActionContext context) { EditorToolbarItemAttribute placement = registration.toolbars[toolbarIndex]; if (!string.Equals(placement.area, context.area, StringComparison.Ordinal)) + { continue; + } EditorActionState status = actions.Query(registration.id, context); if (!status.isVisible) + { continue; + } EditorToolbarIcon icon = status.isChecked && placement.activeIcon != EditorToolbarIcon.None - ? placement.activeIcon - : placement.icon; - items.Add((new EditorToolbarItem( - registration.id, - icon, - status.displayName ?? placement.tooltip, - placement.order, - status), registration.type.FullName ?? registration.type.Name)); + ? placement.activeIcon + : placement.icon; + items.Add( + (new EditorToolbarItem( + registration.id, + icon, + status.displayName ?? placement.tooltip, + placement.order, + status + ), registration.type.FullName ?? registration.type.Name) + ); } } @@ -41,14 +48,16 @@ internal EditorToolbarModel Build(EditorActionContext context) right ) => { - int order = left.Item.order.CompareTo(right.Item.order); + int order = left.item.order.CompareTo(right.item.order); if (order != 0) + { return order; - int action = string.Compare(left.Item.actionId, right.Item.actionId, StringComparison.Ordinal); + } + int action = string.Compare(left.item.actionID, right.item.actionID, StringComparison.Ordinal); return action != 0 - ? action - : string.Compare(left.TypeName, right.TypeName, StringComparison.Ordinal); + ? action + : string.Compare(left.typeName, right.typeName, StringComparison.Ordinal); }); - return new EditorToolbarModel(items.ConvertAll(static value => value.Item)); + return new EditorToolbarModel(items.ConvertAll(static value => value.item)); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs index e797a225a..642b470d1 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs @@ -9,27 +9,22 @@ public enum EditorToolbarIcon /// No symbol is requested. /// None, - /// /// Starts an operation or simulation. /// Play, - /// /// Stops an operation or simulation. /// Stop, - /// /// Pauses an operation or simulation. /// Pause, - /// /// Advances a paused operation by one step. /// Step, - /// /// Returns to an editing state. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItem.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItem.cs index 6bb5249d3..19953f0ff 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItem.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItem.cs @@ -6,13 +6,13 @@ namespace Inno.Editor.Interactions; public sealed class EditorToolbarItem { internal EditorToolbarItem( - string actionId, + string actionID, EditorToolbarIcon icon, string tooltip, int order, EditorActionState status ) { - this.actionId = actionId; + this.actionID = actionID; this.icon = icon; this.tooltip = tooltip; this.order = order; @@ -22,7 +22,7 @@ EditorActionState status /// /// Gets the stable action dispatched when this item is pressed. /// - public string actionId { get; } + public string actionID { get; } /// /// Gets the resolved presentation-independent symbol. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs index 13cd4d4fa..55abb784c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs @@ -42,15 +42,25 @@ public EditorToolbarItemAttribute( EditorToolbarIcon activeIcon = EditorToolbarIcon.None ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor toolbar area is required.", nameof(area)); + } if (!Enum.IsDefined(icon)) + { throw new ArgumentOutOfRangeException(nameof(icon), icon, "Unknown editor toolbar icon."); + } if (icon == EditorToolbarIcon.None) + { throw new ArgumentException("A visible editor toolbar icon is required.", nameof(icon)); + } if (string.IsNullOrWhiteSpace(tooltip)) + { throw new ArgumentException("An editor toolbar tooltip is required.", nameof(tooltip)); + } if (!Enum.IsDefined(activeIcon)) + { throw new ArgumentOutOfRangeException(nameof(activeIcon), activeIcon, "Unknown active toolbar icon."); + } this.area = area; this.icon = icon; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs index 35ac4c658..2a4fdc531 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs @@ -52,7 +52,9 @@ public bool Update( bool allowAltPrimary = true ) { if (isPanning && !(m_primary ? primaryDown : middleDown)) + { Cancel(); + } if (!isPanning && hovered && (middlePressed || allowAltPrimary && alt && primaryPressed)) { m_primary = !middlePressed; @@ -86,9 +88,13 @@ public static float WheelFactor( float sensitivity = 0.16f ) { if (!float.IsFinite(wheel)) + { throw new ArgumentOutOfRangeException(nameof(wheel)); + } if (!float.IsFinite(sensitivity) || sensitivity <= 0) + { throw new ArgumentOutOfRangeException(nameof(sensitivity)); + } return MathF.Exp(Math.Clamp(wheel * sensitivity, -20f, 20f)); } @@ -120,13 +126,21 @@ public static Vector2 ZoomOrigin( float nextScale ) { if (!float.IsFinite(origin.X) || !float.IsFinite(origin.Y)) + { throw new ArgumentOutOfRangeException(nameof(origin)); + } if (!float.IsFinite(pivot.X) || !float.IsFinite(pivot.Y)) + { throw new ArgumentOutOfRangeException(nameof(pivot)); + } if (!float.IsFinite(previousScale) || previousScale <= 0) + { throw new ArgumentOutOfRangeException(nameof(previousScale)); + } if (!float.IsFinite(nextScale) || nextScale <= 0) + { throw new ArgumentOutOfRangeException(nameof(nextScale)); + } return pivot - (pivot - origin) * (nextScale / previousScale); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs new file mode 100644 index 000000000..aaf8bbcb2 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs @@ -0,0 +1,77 @@ +using Inno.Core.Input; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Interactions; + +/// +/// Contains one immutable viewport pointer sample in screen and world coordinates. +/// +public readonly record struct EditorViewportPointerEvent +{ + /// + /// Creates one viewport pointer sample. + /// + /// + /// Platform pointer identity. + /// + /// + /// Gesture lifecycle phase. + /// + /// + /// Viewport-local pixel position. + /// + /// + /// Corresponding world position. + /// + /// + /// Platform button number. + /// + /// + /// Active keyboard modifiers. + /// + public EditorViewportPointerEvent( + int pointerID, + EditorViewportPointerPhase phase, + Vector2 screenPosition, + Vector2 worldPosition, + int button, + KeyModifier modifiers + ) { + this.pointerID = pointerID; + this.phase = phase; + this.screenPosition = screenPosition; + this.worldPosition = worldPosition; + this.button = button; + this.modifiers = modifiers; + } + + /// + /// Gets the platform pointer identity. + /// + public int pointerID { get; } + + /// + /// Gets the gesture lifecycle phase. + /// + public EditorViewportPointerPhase phase { get; } + + /// + /// Gets the viewport-local pixel position. + /// + public Vector2 screenPosition { get; } + + /// + /// Gets the corresponding world position. + /// + public Vector2 worldPosition { get; } + + /// + /// Gets the platform button number. + /// + public int button { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs new file mode 100644 index 000000000..d581d2462 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs @@ -0,0 +1,46 @@ +using Inno.Core.Input; + +namespace Inno.Editor.Interactions; + +/// +/// Contains one presentation-independent shortcut sample for a focused viewport tool. +/// +public readonly record struct EditorViewportShortcut +{ + /// + /// Creates one viewport shortcut sample. + /// + /// + /// Pressed key. + /// + /// + /// Active keyboard modifiers. + /// + /// + /// Whether the platform generated an auto-repeat press. + /// + public EditorViewportShortcut( + KeyCode key, + KeyModifier modifiers = KeyModifier.None, + bool repeat = false + ) { + this.key = key; + this.modifiers = modifiers; + this.repeat = repeat; + } + + /// + /// Gets the pressed key. + /// + public KeyCode key { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } + + /// + /// Gets whether the shortcut is an auto-repeat press. + /// + public bool repeat { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs index c47832fbb..9a5f54577 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs @@ -1,211 +1,7 @@ using System; -using Inno.Core.Input; -using Inno.Core.Mathematics; namespace Inno.Editor.Interactions; -/// -/// Selects the lifecycle phase of one viewport pointer sample. -/// -public enum EditorViewportPointerPhase -{ - /// - /// The pointer button began a gesture. - /// - Down, - /// - /// The pointer moved or changed hover position. - /// - Move, - /// - /// The pointer button ended a gesture. - /// - Up, - /// - /// The platform cancelled the gesture. - /// - Cancel -} - -/// -/// Selects a presentation-independent cursor requested by a viewport tool. -/// -public enum EditorViewportCursor -{ - /// - /// Uses the normal arrow cursor. - /// - Arrow, - /// - /// Uses a precise crosshair. - /// - Crosshair, - /// - /// Uses a hand suitable for panning. - /// - Hand, - /// - /// Uses four-direction movement arrows. - /// - Move, - /// - /// Uses horizontal resizing arrows. - /// - ResizeHorizontal, - /// - /// Uses vertical resizing arrows. - /// - ResizeVertical, - /// - /// Hides the pointer while the tool owns it. - /// - Hidden -} - -/// -/// Contains one presentation-independent shortcut sample for a focused viewport tool. -/// -public readonly record struct EditorViewportShortcut -{ - /// - /// Creates one viewport shortcut sample. - /// - /// - /// Pressed key. - /// - /// - /// Active keyboard modifiers. - /// - /// - /// Whether the platform generated an auto-repeat press. - /// - public EditorViewportShortcut( - KeyCode key, - KeyModifier modifiers = KeyModifier.None, - bool repeat = false - ) { - this.key = key; - this.modifiers = modifiers; - this.repeat = repeat; - } - - /// - /// Gets the pressed key. - /// - public KeyCode key { get; } - - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } - - /// - /// Gets whether the shortcut is an auto-repeat press. - /// - public bool repeat { get; } -} - -/// -/// Contains one immutable viewport pointer sample in screen and world coordinates. -/// -public readonly record struct EditorViewportPointerEvent -{ - /// - /// Creates one viewport pointer sample. - /// - /// - /// Platform pointer identity. - /// - /// - /// Gesture lifecycle phase. - /// - /// - /// Viewport-local pixel position. - /// - /// - /// Corresponding world position. - /// - /// - /// Platform button number. - /// - /// - /// Active keyboard modifiers. - /// - public EditorViewportPointerEvent( - int pointerId, - EditorViewportPointerPhase phase, - Vector2 screenPosition, - Vector2 worldPosition, - int button, - KeyModifier modifiers - ) { - this.pointerId = pointerId; - this.phase = phase; - this.screenPosition = screenPosition; - this.worldPosition = worldPosition; - this.button = button; - this.modifiers = modifiers; - } - - /// - /// Gets the platform pointer identity. - /// - public int pointerId { get; } - - /// - /// Gets the gesture lifecycle phase. - /// - public EditorViewportPointerPhase phase { get; } - - /// - /// Gets the viewport-local pixel position. - /// - public Vector2 screenPosition { get; } - - /// - /// Gets the corresponding world position. - /// - public Vector2 worldPosition { get; } - - /// - /// Gets the platform button number. - /// - public int button { get; } - - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } -} - -/// -/// Converts coordinates for one viewport camera without exposing its presentation backend. -/// -public interface IEditorViewportCoordinateConverter -{ - /// - /// Converts viewport-local pixel coordinates to world coordinates. - /// - /// - /// Viewport-local pixel coordinates. - /// - /// - /// World coordinates. - /// - Vector2 ScreenToWorld(Vector2 screenPosition); - - /// - /// Converts world coordinates to viewport-local pixel coordinates. - /// - /// - /// World coordinates. - /// - /// - /// Viewport-local pixel coordinates. - /// - Vector2 WorldToScreen(Vector2 worldPosition); -} - /// /// Defines one presentation-independent, reloadable viewport editing tool. /// @@ -233,9 +29,7 @@ public abstract class EditorViewportTool public virtual void OnPointerDown( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles pointer movement or hover. @@ -249,9 +43,7 @@ EditorViewportPointerEvent pointer public virtual void OnPointerMove( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles a pointer release. @@ -265,9 +57,7 @@ EditorViewportPointerEvent pointer public virtual void OnPointerUp( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles platform cancellation of an active gesture. @@ -315,3 +105,61 @@ EditorViewportShortcut shortcut /// public virtual void DrawOverlay(EditorViewportToolContext context) => ArgumentNullException.ThrowIfNull(context); } + +/// +/// Selects the lifecycle phase of one viewport pointer sample. +/// +public enum EditorViewportPointerPhase +{ + /// + /// The pointer button began a gesture. + /// + Down, + /// + /// The pointer moved or changed hover position. + /// + Move, + /// + /// The pointer button ended a gesture. + /// + Up, + /// + /// The platform cancelled the gesture. + /// + Cancel +} + +/// +/// Selects a presentation-independent cursor requested by a viewport tool. +/// +public enum EditorViewportCursor +{ + /// + /// Uses the normal arrow cursor. + /// + Arrow, + /// + /// Uses a precise crosshair. + /// + Crosshair, + /// + /// Uses a hand suitable for panning. + /// + Hand, + /// + /// Uses four-direction movement arrows. + /// + Move, + /// + /// Uses horizontal resizing arrows. + /// + ResizeHorizontal, + /// + /// Uses vertical resizing arrows. + /// + ResizeVertical, + /// + /// Hides the pointer while the tool owns it. + /// + Hidden +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs index 03308f701..5246be64b 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs @@ -2,6 +2,7 @@ using Inno.Core.Mathematics; namespace Inno.Editor.Interactions; + /// /// Coordinates pointer capture, transforms, and one history transaction for a viewport gesture. /// @@ -10,23 +11,28 @@ public sealed class EditorViewportToolContext private readonly IEditorHistory m_history; private readonly IEditorViewportCoordinateConverter m_coordinates; private EditorEditGesture? m_transaction; - private int? m_capturedPointerId; + private int? m_capturedPointerID; + internal EditorViewportToolContext( IEditorHistory history, IEditorViewportCoordinateConverter coordinates ) { - m_history = history ?? throw new ArgumentNullException(nameof(history)); - m_coordinates = coordinates ?? throw new ArgumentNullException(nameof(coordinates)); + ArgumentNullException.ThrowIfNull(history); + ArgumentNullException.ThrowIfNull(coordinates); + m_history = history; + m_coordinates = coordinates; } /// /// Gets whether this tool owns a pointer. /// - public bool hasPointerCapture => m_capturedPointerId.HasValue; + public bool hasPointerCapture => m_capturedPointerID.HasValue; + /// /// Gets the captured pointer identity, or . /// - public int? capturedPointerId => m_capturedPointerId; + public int? capturedPointerID => m_capturedPointerID; + /// /// Gets whether a history transaction is active for the current gesture. /// @@ -35,14 +41,16 @@ IEditorViewportCoordinateConverter coordinates /// /// Captures one pointer until explicit release or cancellation. /// - /// + /// /// Platform pointer identity. /// - public void CapturePointer(int pointerId) + public void CapturePointer(int pointerID) { - if (m_capturedPointerId.HasValue && m_capturedPointerId.Value != pointerId) + if (m_capturedPointerID.HasValue && m_capturedPointerID.Value != pointerID) + { throw new InvalidOperationException("A viewport tool cannot capture two pointers concurrently."); - m_capturedPointerId = pointerId; + } + m_capturedPointerID = pointerID; } /// @@ -51,8 +59,10 @@ public void CapturePointer(int pointerId) public void ReleasePointer() { if (m_transaction is not null) + { throw new InvalidOperationException("Complete the viewport history gesture before releasing its pointer."); - m_capturedPointerId = null; + } + m_capturedPointerID = null; } /// @@ -65,9 +75,13 @@ public void BeginHistoryGesture(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!hasPointerCapture) + { throw new InvalidOperationException("A viewport history gesture requires pointer capture."); + } if (m_transaction is not null) + { throw new InvalidOperationException("The current viewport gesture already owns a history transaction."); + } m_transaction = new EditorEditGesture(m_history, name); } @@ -81,14 +95,20 @@ public void CompleteHistoryGesture(bool commit) { EditorEditGesture? transaction = m_transaction; if (transaction is null) + { return; + } if (commit) + { transaction.Commit(); + } else { EditorHistoryResult result = transaction.Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The viewport gesture could not roll back: {result.message}"); + } } m_transaction = null; @@ -105,6 +125,7 @@ public void CompleteHistoryGesture(bool commit) /// World coordinates. /// public Vector2 ScreenToWorld(Vector2 screenPosition) => m_coordinates.ScreenToWorld(screenPosition); + /// /// Converts world coordinates to viewport-local pixel coordinates. /// @@ -115,10 +136,12 @@ public void CompleteHistoryGesture(bool commit) /// Viewport-local pixel coordinates. /// public Vector2 WorldToScreen(Vector2 worldPosition) => m_coordinates.WorldToScreen(worldPosition); - internal bool Accepts(int pointerId) => !m_capturedPointerId.HasValue || m_capturedPointerId.Value == pointerId; + + internal bool Accepts(int pointerID) => !m_capturedPointerID.HasValue || m_capturedPointerID.Value == pointerID; + internal void Cancel() { CompleteHistoryGesture(commit: false); - m_capturedPointerId = null; + m_capturedPointerID = null; } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs index 57b582029..e6ca633ca 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs @@ -47,7 +47,9 @@ public void SetTool(EditorViewportTool? tool) { ObjectDisposedException.ThrowIf(m_disposed, this); if (ReferenceEquals(m_tool, tool)) + { return; + } m_context.Cancel(); m_tool = tool; } @@ -65,8 +67,10 @@ public bool HandlePointer(EditorViewportPointerEvent pointer) { ObjectDisposedException.ThrowIf(m_disposed, this); EditorViewportTool? current = m_tool; - if (current is null || !m_context.Accepts(pointer.pointerId)) + if (current is null || !m_context.Accepts(pointer.pointerID)) + { return false; + } switch (pointer.phase) { case EditorViewportPointerPhase.Down: @@ -115,7 +119,9 @@ public void DrawOverlay() public void Dispose() { if (m_disposed) + { return; + } m_context.Cancel(); m_tool = null; m_disposed = true; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs new file mode 100644 index 000000000..b01d6fd5f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs @@ -0,0 +1,31 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Interactions; + +/// +/// Converts coordinates for one viewport camera without exposing its presentation backend. +/// +public interface IEditorViewportCoordinateConverter +{ + /// + /// Converts viewport-local pixel coordinates to world coordinates. + /// + /// + /// Viewport-local pixel coordinates. + /// + /// + /// World coordinates. + /// + Vector2 ScreenToWorld(Vector2 screenPosition); + + /// + /// Converts world coordinates to viewport-local pixel coordinates. + /// + /// + /// World coordinates. + /// + /// + /// Viewport-local pixel coordinates. + /// + Vector2 WorldToScreen(Vector2 worldPosition); +} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs index d1b16bb13..7ee09cb7a 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs @@ -20,9 +20,7 @@ public abstract class EditorSetting /// Creates a Settings definition. A field supplies its persisted default through /// ; a page keeps the base implementation. /// - protected EditorSetting() - { - } + protected EditorSetting() {} /// /// Gets the complete slash-delimited identity and placement path. @@ -85,9 +83,7 @@ protected EditorSetting() public bool Draw(EditorSettingObject setting) { ArgumentNullException.ThrowIfNull(setting); - EditorSettingObject baseline = m_drawBaselines.GetValue( - setting, - static value => value.Copy()); + EditorSettingObject baseline = m_drawBaselines.GetValue(setting, static value => value.Copy()); OnDraw(setting); return !setting.ValueEquals(baseline); } @@ -111,11 +107,12 @@ public bool IsDefault(EditorSettingObject setting) { ArgumentNullException.ThrowIfNull(setting); EditorSettingObject boundDefault = m_boundDefaultValue - ?? throw new InvalidOperationException( - $"Settings page '{path}' does not own a default value."); + ?? throw new InvalidOperationException($"Settings page '{path}' does not own a default value."); return boundDefault.ValueEquals(setting); } + internal bool isPageDefinition { get; private set; } + /// /// Draws the field using the staged JSON object owned by the Settings frontend. /// A type that does not override this method describes a page. @@ -123,11 +120,7 @@ public bool IsDefault(EditorSettingObject setting) /// /// The isolated mutable object being edited. /// - protected virtual void OnDraw(EditorSettingObject setting) - { - } - - internal bool isPageDefinition { get; private set; } + protected virtual void OnDraw(EditorSettingObject setting) {} internal EditorSettingObject CreateDefault() => m_boundDefaultValue?.Copy() @@ -138,16 +131,15 @@ internal void BindPlacement( int placementOrder ) { string normalized = EditorSettingsPathUtility.Normalize(placementPath); - if (m_path is not null && - (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder)) - { + if (m_path is not null + && (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder) + ) { throw new InvalidOperationException( - $"Settings definition '{GetType().FullName}' was registered at more than one path."); + $"Settings definition '{GetType().FullName}' was registered at more than one path." + ); } - MethodInfo? drawMethod = GetType().GetMethod( - nameof(OnDraw), - BindingFlags.Instance | BindingFlags.NonPublic); + MethodInfo? drawMethod = GetType().GetMethod(nameof(OnDraw), BindingFlags.Instance | BindingFlags.NonPublic); isPageDefinition = drawMethod?.DeclaringType == typeof(EditorSetting); EditorSettingObject? declaredDefault = defaultValue; (string path, string parentPath, string label) = EditorSettingsPathUtility.Parse(normalized); @@ -155,13 +147,13 @@ int placementOrder { throw new InvalidOperationException( isPageDefinition - ? $"Settings page '{path}' cannot declare a persisted default value." - : $"Settings field '{path}' must declare a persisted default value."); + ? $"Settings page '{path}' cannot declare a persisted default value." + : $"Settings field '{path}' must declare a persisted default value." + ); } if (!isPageDefinition && parentPath.Length == 0) { - throw new InvalidOperationException( - $"Settings field '{path}' requires at least one parent page segment."); + throw new InvalidOperationException($"Settings field '{path}' requires at least one parent page segment."); } m_path = path; m_pagePath = isPageDefinition ? path : parentPath; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs index 67c9f4d75..92f26e45f 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; @@ -18,9 +17,7 @@ public sealed class EditorSettingObject : ISerializable /// /// Creates an empty Settings object. /// - public EditorSettingObject() - { - } + public EditorSettingObject() {} private EditorSettingObject(Dictionary values) { @@ -216,7 +213,9 @@ public void SetAsSingle( float value ) { if (!float.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Settings numbers must be finite."); + } Set(name, value); } @@ -254,7 +253,9 @@ public void SetAsDouble( double value ) { if (!double.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Settings numbers must be finite."); + } Set(name, value); } @@ -479,7 +480,9 @@ internal EditorSettingObject Copy() { var values = new Dictionary(m_values.Count, StringComparer.Ordinal); foreach ((string name, EditorSettingValue value) in m_values) + { values.Add(name, value.Copy()); + } return new EditorSettingObject(values); } @@ -487,12 +490,14 @@ internal bool ValueEquals(EditorSettingObject other) { ArgumentNullException.ThrowIfNull(other); if (m_values.Count != other.m_values.Count) + { return false; + } foreach ((string name, EditorSettingValue value) in m_values) { if (!other.m_values.TryGetValue(name, out EditorSettingValue? candidate) - || !value.ValueEquals(candidate)) - { + || !value.ValueEquals(candidate) + ) { return false; } } @@ -502,12 +507,16 @@ internal bool ValueEquals(EditorSettingObject other) internal void Validate(string settingPath) { if (m_values is null) + { throw new InvalidDataException($"Settings path '{settingPath}' has no value map."); + } foreach ((string name, EditorSettingValue value) in m_values) { ValidateName(name); if (value is null) + { throw new InvalidDataException($"Settings property '{settingPath}/{name}' is null."); + } value.Validate($"{settingPath}/{name}"); } } @@ -518,7 +527,9 @@ T defaultValue ) { ValidateName(name); if (!m_values.TryGetValue(name, out EditorSettingValue? value)) + { return defaultValue; + } return value.Read(defaultValue, name); } @@ -534,8 +545,8 @@ T value ValidateName(name); EditorSettingValue next = EditorSettingValue.Create(value); if (m_values.TryGetValue(name, out EditorSettingValue? current) - && current.ValueEquals(next)) - { + && current.ValueEquals(next) + ) { return; } m_values[name] = next; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs index d8b8922f2..6a107be87 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs @@ -26,12 +26,13 @@ public EditorSettingPathAttribute( int order = 0 ) { string normalized = EditorSettingsPathUtility.Normalize(path); - if (!string.Equals(normalized, "Editor", StringComparison.Ordinal) && - !normalized.StartsWith("Editor/", StringComparison.Ordinal)) - { + if (!string.Equals(normalized, "Editor", StringComparison.Ordinal) + && !normalized.StartsWith("Editor/", StringComparison.Ordinal) + ) { throw new ArgumentException( "An Editor setting path must be 'Editor' or begin with 'Editor/'.", - nameof(path)); + nameof(path) + ); } this.path = normalized; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs index 70b0d1ccc..82fec9986 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Linq; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; @@ -60,64 +59,6 @@ internal sealed class EditorSettingValue : ISerializable [SerializableProperty] internal bool[] stringArrayNulls = []; - internal static EditorSettingValue Create(T value) - { - Type type = typeof(T); - if (type == typeof(bool)) - return new EditorSettingValue { kind = EditorSettingValueKind.Boolean, booleanValue = (bool)(object)value! }; - if (type == typeof(int)) - return new EditorSettingValue { kind = EditorSettingValueKind.Int32, int32Value = (int)(object)value! }; - if (type == typeof(uint)) - return new EditorSettingValue { kind = EditorSettingValueKind.UInt32, uint32Value = (uint)(object)value! }; - if (type == typeof(long)) - return new EditorSettingValue { kind = EditorSettingValueKind.Int64, int64Value = (long)(object)value! }; - if (type == typeof(ulong)) - return new EditorSettingValue { kind = EditorSettingValueKind.UInt64, uint64Value = (ulong)(object)value! }; - if (type == typeof(float)) - return new EditorSettingValue { kind = EditorSettingValueKind.Single, singleValue = (float)(object)value! }; - if (type == typeof(double)) - return new EditorSettingValue { kind = EditorSettingValueKind.Double, doubleValue = (double)(object)value! }; - if (type == typeof(string)) - { - string? text = (string?)(object?)value; - return new EditorSettingValue - { - kind = EditorSettingValueKind.String, - hasStringValue = text is not null, - stringValue = text ?? string.Empty - }; - } - if (type == typeof(bool[])) - return new EditorSettingValue { kind = EditorSettingValueKind.BooleanArray, booleanArrayValue = Clone((bool[])(object)value!) }; - if (type == typeof(int[])) - return new EditorSettingValue { kind = EditorSettingValueKind.Int32Array, int32ArrayValue = Clone((int[])(object)value!) }; - if (type == typeof(uint[])) - return new EditorSettingValue { kind = EditorSettingValueKind.UInt32Array, uint32ArrayValue = Clone((uint[])(object)value!) }; - if (type == typeof(float[])) - return new EditorSettingValue { kind = EditorSettingValueKind.SingleArray, singleArrayValue = Clone((float[])(object)value!) }; - if (type == typeof(double[])) - return new EditorSettingValue { kind = EditorSettingValueKind.DoubleArray, doubleArrayValue = Clone((double[])(object)value!) }; - if (type == typeof(string[])) - { - string?[] source = (string?[])(object)value!; - var values = new string[source.Length]; - var nulls = new bool[source.Length]; - for (int i = 0; i < source.Length; i++) - { - nulls[i] = source[i] is null; - values[i] = source[i] ?? string.Empty; - } - return new EditorSettingValue - { - kind = EditorSettingValueKind.StringArray, - stringArrayValue = values, - stringArrayNulls = nulls - }; - } - - throw new NotSupportedException($"Editor Settings values do not support '{type.FullName}'."); - } - internal T Read( T defaultValue, string propertyName @@ -125,67 +66,98 @@ string propertyName Type type = typeof(T); object? value; if (type == typeof(bool) && kind == EditorSettingValueKind.Boolean) + { value = booleanValue; + } else if (type == typeof(int) && kind == EditorSettingValueKind.Int32) + { value = int32Value; + } else if (type == typeof(uint) && kind == EditorSettingValueKind.UInt32) + { value = uint32Value; + } else if (type == typeof(long) && kind == EditorSettingValueKind.Int64) + { value = int64Value; + } else if (type == typeof(ulong) && kind == EditorSettingValueKind.UInt64) + { value = uint64Value; + } else if (type == typeof(float) && kind == EditorSettingValueKind.Single) + { value = singleValue; + } else if (type == typeof(double) && kind == EditorSettingValueKind.Double) + { value = doubleValue; + } else if (type == typeof(string) && kind == EditorSettingValueKind.String) + { value = hasStringValue ? stringValue : defaultValue; + } else if (type == typeof(bool[]) && kind == EditorSettingValueKind.BooleanArray) + { value = Clone(booleanArrayValue); + } else if (type == typeof(int[]) && kind == EditorSettingValueKind.Int32Array) + { value = Clone(int32ArrayValue); + } else if (type == typeof(uint[]) && kind == EditorSettingValueKind.UInt32Array) + { value = Clone(uint32ArrayValue); + } else if (type == typeof(float[]) && kind == EditorSettingValueKind.SingleArray) + { value = Clone(singleArrayValue); + } else if (type == typeof(double[]) && kind == EditorSettingValueKind.DoubleArray) + { value = Clone(doubleArrayValue); + } else if (type == typeof(string[]) && kind == EditorSettingValueKind.StringArray) + { value = ReadStringArray(); + } else - throw new InvalidDataException( - $"Settings property '{propertyName}' contains {kind}, not {GetKind(type)}."); + { + throw new InvalidDataException($"Settings property '{propertyName}' contains {kind}, not {GetKind(type)}."); + } return (T)value!; } internal EditorSettingValue Copy() => new() - { - kind = kind, - booleanValue = booleanValue, - int32Value = int32Value, - uint32Value = uint32Value, - int64Value = int64Value, - uint64Value = uint64Value, - singleValue = singleValue, - doubleValue = doubleValue, - hasStringValue = hasStringValue, - stringValue = stringValue, - booleanArrayValue = Clone(booleanArrayValue), - int32ArrayValue = Clone(int32ArrayValue), - uint32ArrayValue = Clone(uint32ArrayValue), - singleArrayValue = Clone(singleArrayValue), - doubleArrayValue = Clone(doubleArrayValue), - stringArrayValue = Clone(stringArrayValue), - stringArrayNulls = Clone(stringArrayNulls) - }; + { + kind = kind, + booleanValue = booleanValue, + int32Value = int32Value, + uint32Value = uint32Value, + int64Value = int64Value, + uint64Value = uint64Value, + singleValue = singleValue, + doubleValue = doubleValue, + hasStringValue = hasStringValue, + stringValue = stringValue, + booleanArrayValue = Clone(booleanArrayValue), + int32ArrayValue = Clone(int32ArrayValue), + uint32ArrayValue = Clone(uint32ArrayValue), + singleArrayValue = Clone(singleArrayValue), + doubleArrayValue = Clone(doubleArrayValue), + stringArrayValue = Clone(stringArrayValue), + stringArrayNulls = Clone(stringArrayNulls) + }; internal bool ValueEquals(EditorSettingValue other) { ArgumentNullException.ThrowIfNull(other); if (kind != other.kind) + { return false; + } return kind switch { EditorSettingValueKind.Boolean => booleanValue == other.booleanValue, @@ -196,14 +168,14 @@ internal bool ValueEquals(EditorSettingValue other) EditorSettingValueKind.Single => singleValue.Equals(other.singleValue), EditorSettingValueKind.Double => doubleValue.Equals(other.doubleValue), EditorSettingValueKind.String => hasStringValue == other.hasStringValue - && string.Equals(stringValue, other.stringValue, StringComparison.Ordinal), + && string.Equals(stringValue, other.stringValue, StringComparison.Ordinal), EditorSettingValueKind.BooleanArray => booleanArrayValue.SequenceEqual(other.booleanArrayValue), EditorSettingValueKind.Int32Array => int32ArrayValue.SequenceEqual(other.int32ArrayValue), EditorSettingValueKind.UInt32Array => uint32ArrayValue.SequenceEqual(other.uint32ArrayValue), EditorSettingValueKind.SingleArray => singleArrayValue.SequenceEqual(other.singleArrayValue), EditorSettingValueKind.DoubleArray => doubleArrayValue.SequenceEqual(other.doubleArrayValue), EditorSettingValueKind.StringArray => stringArrayValue.SequenceEqual(other.stringArrayValue, StringComparer.Ordinal) - && stringArrayNulls.SequenceEqual(other.stringArrayNulls), + && stringArrayNulls.SequenceEqual(other.stringArrayNulls), _ => false }; } @@ -211,74 +183,190 @@ internal bool ValueEquals(EditorSettingValue other) internal void Validate(string propertyName) { if (!Enum.IsDefined(kind)) + { throw new InvalidDataException($"Settings property '{propertyName}' has an unknown value kind."); + } if (booleanArrayValue is null || int32ArrayValue is null || uint32ArrayValue is null || singleArrayValue is null || doubleArrayValue is null || stringArrayValue is null - || stringArrayNulls is null) - { + || stringArrayNulls is null + ) { throw new InvalidDataException($"Settings property '{propertyName}' has an invalid null array payload."); } if (stringValue is null) + { throw new InvalidDataException($"Settings property '{propertyName}' has an invalid null string payload."); + } if (kind == EditorSettingValueKind.StringArray - && stringArrayValue.Length != stringArrayNulls.Length) - { + && stringArrayValue.Length != stringArrayNulls.Length + ) { throw new InvalidDataException($"Settings property '{propertyName}' has inconsistent string-array payloads."); } if (kind == EditorSettingValueKind.Single && !float.IsFinite(singleValue) || kind == EditorSettingValueKind.Double && !double.IsFinite(doubleValue) || kind == EditorSettingValueKind.SingleArray && singleArrayValue.Any(static value => !float.IsFinite(value)) - || kind == EditorSettingValueKind.DoubleArray && doubleArrayValue.Any(static value => !double.IsFinite(value))) - { + || kind == EditorSettingValueKind.DoubleArray && doubleArrayValue.Any(static value => !double.IsFinite(value)) + ) { throw new InvalidDataException($"Settings property '{propertyName}' contains a non-finite number."); } } + internal static EditorSettingValue Create(T value) + { + Type type = typeof(T); + if (type == typeof(bool)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Boolean, booleanValue = (bool)(object)value! }; + } + if (type == typeof(int)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Int32, int32Value = (int)(object)value! }; + } + if (type == typeof(uint)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.UInt32, uint32Value = (uint)(object)value! }; + } + if (type == typeof(long)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Int64, int64Value = (long)(object)value! }; + } + if (type == typeof(ulong)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.UInt64, uint64Value = (ulong)(object)value! }; + } + if (type == typeof(float)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Single, singleValue = (float)(object)value! }; + } + if (type == typeof(double)) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Double, doubleValue = (double)(object)value! }; + } + if (type == typeof(string)) + { + string? text = (string?)(object?)value; + return new EditorSettingValue + { + kind = EditorSettingValueKind.String, + hasStringValue = text is not null, + stringValue = text ?? string.Empty + }; + } + if (type == typeof(bool[])) + { + return new EditorSettingValue { kind = EditorSettingValueKind.BooleanArray, booleanArrayValue = Clone((bool[])(object)value!) }; + } + if (type == typeof(int[])) + { + return new EditorSettingValue { kind = EditorSettingValueKind.Int32Array, int32ArrayValue = Clone((int[])(object)value!) }; + } + if (type == typeof(uint[])) + { + return new EditorSettingValue { kind = EditorSettingValueKind.UInt32Array, uint32ArrayValue = Clone((uint[])(object)value!) }; + } + if (type == typeof(float[])) + { + return new EditorSettingValue { kind = EditorSettingValueKind.SingleArray, singleArrayValue = Clone((float[])(object)value!) }; + } + if (type == typeof(double[])) + { + return new EditorSettingValue { kind = EditorSettingValueKind.DoubleArray, doubleArrayValue = Clone((double[])(object)value!) }; + } + if (type == typeof(string[])) + { + string?[] source = (string?[])(object)value!; + var values = new string[source.Length]; + var nulls = new bool[source.Length]; + for (int i = 0; i < source.Length; i++) + { + nulls[i] = source[i] is null; + values[i] = source[i] ?? string.Empty; + } + return new EditorSettingValue + { + kind = EditorSettingValueKind.StringArray, + stringArrayValue = values, + stringArrayNulls = nulls + }; + } + + throw new NotSupportedException($"Editor Settings values do not support '{type.FullName}'."); + } + + private string?[] ReadStringArray() + { + var result = new string?[stringArrayValue.Length]; + for (int i = 0; i < result.Length; i++) + { + result[i] = stringArrayNulls[i] ? null : stringArrayValue[i]; + } + return result; + } + private static EditorSettingValueKind GetKind(Type type) { if (type == typeof(bool)) + { return EditorSettingValueKind.Boolean; + } if (type == typeof(int)) + { return EditorSettingValueKind.Int32; + } if (type == typeof(uint)) + { return EditorSettingValueKind.UInt32; + } if (type == typeof(long)) + { return EditorSettingValueKind.Int64; + } if (type == typeof(ulong)) + { return EditorSettingValueKind.UInt64; + } if (type == typeof(float)) + { return EditorSettingValueKind.Single; + } if (type == typeof(double)) + { return EditorSettingValueKind.Double; + } if (type == typeof(string)) + { return EditorSettingValueKind.String; + } if (type == typeof(bool[])) + { return EditorSettingValueKind.BooleanArray; + } if (type == typeof(int[])) + { return EditorSettingValueKind.Int32Array; + } if (type == typeof(uint[])) + { return EditorSettingValueKind.UInt32Array; + } if (type == typeof(float[])) + { return EditorSettingValueKind.SingleArray; + } if (type == typeof(double[])) + { return EditorSettingValueKind.DoubleArray; + } if (type == typeof(string[])) + { return EditorSettingValueKind.StringArray; + } throw new NotSupportedException($"Editor Settings values do not support '{type.FullName}'."); } - private string?[] ReadStringArray() - { - var result = new string?[stringArrayValue.Length]; - for (int i = 0; i < result.Length; i++) - result[i] = stringArrayNulls[i] ? null : stringArrayValue[i]; - return result; - } - private static T[] Clone(T[] value) { ArgumentNullException.ThrowIfNull(value); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs index 84b3b2618..f93e38400 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs @@ -4,13 +4,13 @@ namespace Inno.Editor.Settings; internal static class EditorSettingsPathUtility { - internal static (string Path, string ParentPath, string Label) Parse(string path) + internal static (string path, string parentPath, string label) Parse(string path) { string normalized = Normalize(path); int separator = normalized.LastIndexOf('/'); return separator < 0 - ? (normalized, string.Empty, normalized) - : (normalized, normalized[..separator], normalized[(separator + 1)..]); + ? (normalized, string.Empty, normalized) + : (normalized, normalized[..separator], normalized[(separator + 1)..]); } internal static string Normalize(string path) @@ -18,7 +18,9 @@ internal static string Normalize(string path) ArgumentException.ThrowIfNullOrWhiteSpace(path); string[] segments = path.Split('/', StringSplitOptions.TrimEntries); if (segments.Length == 0 || Array.Exists(segments, static segment => segment.Length == 0)) + { throw new ArgumentException("Settings paths cannot contain empty segments.", nameof(path)); + } return string.Join('/', segments); } } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs index 0de86f374..15244bfc0 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs @@ -1,9 +1,8 @@ using System; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; -using Inno.Scripting.Api; using Inno.Core.Settings; +using Inno.Scripting.Api; namespace Inno.Editor.Settings; @@ -17,13 +16,13 @@ public abstract class ProjectSettingEditor private string? m_pagePath; private string? m_path; private SerializationRegistry? m_serialization; - private ProjectSettingId m_settingId; + private ProjectSettingID m_settingID; /// /// Gets the stable runtime project setting protocol read from the target setting type's /// by the Editor catalog. /// - public ProjectSettingId settingId => m_settingId; + public ProjectSettingID settingID => m_settingID; /// /// Gets the complete slash-delimited placement path. @@ -93,6 +92,11 @@ ISerializable right internal abstract Type valueType { get; } + internal SerializationRegistry serialization + => m_serialization ?? throw new InvalidOperationException( + $"Project setting editor '{GetType().FullName}' has not been bound to a serialization registry." + ); + internal abstract bool DrawValue(ISerializable value); internal abstract bool ValueEquals( @@ -100,31 +104,31 @@ internal abstract bool ValueEquals( ISerializable right ); - internal SerializationRegistry serialization - => m_serialization ?? throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' has not been bound to a serialization registry."); - internal void BindSerialization(SerializationRegistry serializationRegistry) { ArgumentNullException.ThrowIfNull(serializationRegistry); if (m_serialization is not null && !ReferenceEquals(m_serialization, serializationRegistry)) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' cannot be bound to more than one serialization registry."); + $"Project setting editor '{GetType().FullName}' cannot be bound to more than one serialization registry." + ); } m_serialization = serializationRegistry; } - internal void BindSettingId(ProjectSettingId id) + internal void BindSettingID(ProjectSettingID id) { if (!id.isValid) + { throw new ArgumentException("A project setting Editor requires a valid setting ID.", nameof(id)); - if (m_settingId.isValid && m_settingId != id) + } + if (m_settingID.isValid && m_settingID != id) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' cannot be bound to more than one setting protocol."); + $"Project setting editor '{GetType().FullName}' cannot be bound to more than one setting protocol." + ); } - m_settingId = id; + m_settingID = id; } internal void BindPlacement( @@ -132,20 +136,24 @@ internal void BindPlacement( int placementOrder ) { string normalized = EditorSettingsPathUtility.Normalize(placementPath); - if (m_path is not null && - (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder)) - { + if (m_path is not null + && (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder) + ) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' was registered at more than one path."); + $"Project setting editor '{GetType().FullName}' was registered at more than one path." + ); } - if (!settingId.isValid) + if (!settingID.isValid) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' returned an invalid setting ID."); + $"Project setting editor '{GetType().FullName}' returned an invalid setting ID." + ); } (string path, string parentPath, string label) = EditorSettingsPathUtility.Parse(normalized); if (parentPath.Length == 0) + { throw new InvalidOperationException($"Project setting editor '{path}' requires a parent page."); + } m_path = path; m_pagePath = parentPath; m_label = label; @@ -158,8 +166,9 @@ internal void ValidateValue(ISerializable value) if (value.GetType() != valueType) { throw new ArgumentException( - $"Project setting '{settingId}' requires '{valueType.FullName}', not '{value.GetType().FullName}'.", - nameof(value)); + $"Project setting '{settingID}' requires '{valueType.FullName}', not '{value.GetType().FullName}'.", + nameof(value) + ); } } } @@ -175,6 +184,8 @@ public abstract class ProjectSettingEditor : ProjectSettingEditor { private readonly ConditionalWeakTable m_baselines = new(); + internal sealed override Type valueType => typeof(TSetting); + /// /// Draws the isolated staged value. Mutations remain local until the Settings frontend applies them. /// @@ -183,18 +194,16 @@ public abstract class ProjectSettingEditor : ProjectSettingEditor /// protected abstract void OnDraw(TSetting setting); - internal sealed override Type valueType => typeof(TSetting); - internal sealed override bool DrawValue(ISerializable value) { ValidateValue(value); - var setting = (TSetting)value; + TSetting setting = (TSetting)value; Baseline baseline = m_baselines.GetValue( setting, - candidate => new Baseline(serialization.CapturePropertiesData(candidate))); + candidate => new Baseline(serialization.CapturePropertiesData(candidate)) + ); OnDraw(setting); - return !baseline.propertyData.AsSpan().SequenceEqual( - serialization.CapturePropertiesData(setting)); + return !baseline.propertyData.AsSpan().SequenceEqual(serialization.CapturePropertiesData(setting)); } internal sealed override bool ValueEquals( @@ -204,7 +213,8 @@ ISerializable right ValidateValue(left); ValidateValue(right); return serialization.CapturePropertiesData(left).AsSpan().SequenceEqual( - serialization.CapturePropertiesData(right)); + serialization.CapturePropertiesData(right) + ); } private sealed record Baseline(byte[] propertyData); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs index 365ba44e0..9e37c128e 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs @@ -27,9 +27,7 @@ public ProjectSettingPathAttribute( string normalized = EditorSettingsPathUtility.Normalize(path); if (!normalized.StartsWith("Project/", StringComparison.Ordinal)) { - throw new ArgumentException( - "A project setting editor path must begin with 'Project/'.", - nameof(path)); + throw new ArgumentException("A project setting editor path must begin with 'Project/'.", nameof(path)); } this.path = normalized; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs index 075e29161..cc6448278 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Settings; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Settings", "Inno.Editor.Settings", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs index 87b97364f..d07eef8f7 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs @@ -1,14 +1,15 @@ -using Inno.Core.Events; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Events; using Inno.Core.Logging; using Inno.Core.Serialization; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; + /// /// Owns the discovered Settings catalog and the project-root Settings document. /// @@ -21,6 +22,7 @@ public sealed class EditorSettings : EditorModule private readonly Logger m_log; private readonly object m_sync = new(); private readonly EditorSettingsStore m_store; + /// /// Creates the Settings service for one project and its shared editor history. /// @@ -30,13 +32,6 @@ public sealed class EditorSettings : EditorModule /// /// The runtime that owns the shared Undo and Redo history. /// - /// - /// Thrown when or is - /// . - /// - /// - /// Thrown when the project-root Settings document is malformed. - /// /// /// The host-owned type catalog used to discover setting presentations. /// @@ -46,6 +41,13 @@ public sealed class EditorSettings : EditorModule /// /// The host-owned current-generation serialization registry used for the project document. /// + /// + /// Thrown when or is + /// . + /// + /// + /// Thrown when the project-root Settings document is malformed. + /// internal EditorSettings( EditorContext context, EditorInteractions interactions, @@ -65,6 +67,16 @@ SerializationRegistry serialization m_log = logs.CreateLogger(); } + /// + /// Gets the current discovered type-catalog revision. + /// + public long catalogRevision => m_catalog.snapshot.revision; + + /// + /// Gets all discovered path definitions in deterministic path order. + /// + public IReadOnlyList definitions => Array.AsReadOnly(m_catalog.snapshot.definitions); + /// /// Observes committed Apply, Undo and Redo changes through an owned Core Event hub. /// @@ -84,7 +96,9 @@ public IDisposable ListenChanges(Action observer) hub.Listen(change => { if (!ReferenceEquals(change.settings, this)) + { return; + } try { observer(this); @@ -97,15 +111,6 @@ public IDisposable ListenChanges(Action observer) return hub; } - /// - /// Gets the current discovered type-catalog revision. - /// - public long catalogRevision => m_catalog.snapshot.revision; - /// - /// Gets all discovered path definitions in deterministic path order. - /// - public IReadOnlyList definitions => Array.AsReadOnly(m_catalog.snapshot.definitions); - /// /// Reads an isolated effective object from one complete Settings path. /// @@ -123,7 +128,9 @@ public EditorSettingObject Get(string path) EditorSetting definition = ResolveField(path); lock (m_sync) { - return m_store.TryGet(definition.path, out EditorSettingObject? value) && value is not null ? value : definition.CreateDefault(); + return m_store.TryGet(definition.path, out EditorSettingObject? value) && value is not null + ? value + : definition.CreateDefault(); } } @@ -169,7 +176,9 @@ public bool Apply( { normalizedResets = new HashSet(StringComparer.Ordinal); foreach (string path in resets) + { _ = normalizedResets.Add(ResolveField(path).path); + } } byte[] before; @@ -181,13 +190,17 @@ public bool Apply( if (normalizedResets is not null) { foreach (string path in normalizedResets) + { storageChanged |= replacement.Remove(path); + } } foreach ((string path, EditorSettingObject candidate)in normalizedValues) { if (normalizedResets?.Contains(path) == true) + { continue; + } if (replacement.TryGetValue(path, out EditorSettingObject? current) && current.ValueEquals(candidate)) { continue; @@ -203,7 +216,9 @@ public bool Apply( } if (!storageChanged) + { return false; + } before = m_store.GetDocument(); m_store.Replace(replacement); after = m_store.GetDocument(); @@ -217,7 +232,9 @@ public bool Apply( catch { lock (m_sync) + { m_store.ReplaceDocument(before); + } throw; } @@ -229,32 +246,44 @@ public bool Apply( /// Releases resources retained by this feature after it has stopped. /// protected override void OnDispose() => m_catalog.Dispose(); + internal void RestoreFromHistory(ReadOnlySpan document) { lock (m_sync) + { m_store.ReplaceDocument(document); + } } internal byte[] CaptureDocument() { lock (m_sync) + { return m_store.GetDocument(); + } } internal void ValidateDocument(ReadOnlySpan document) { lock (m_sync) + { m_store.ValidateDocument(document); + } } internal void NotifyChanged() => m_events.Emit(new EditorSettingsChangedEvent(this)); + private EditorSetting ResolveField(string path) { string normalized = EditorSettingsPathUtility.Normalize(path); if (!m_catalog.snapshot.byPath.TryGetValue(normalized, out EditorSetting? setting)) + { throw new ArgumentException($"No editor setting is registered at '{normalized}'.", nameof(path)); + } if (!setting.hasValue) + { throw new ArgumentException($"Editor setting '{normalized}' describes a page.", nameof(path)); + } return setting; } } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs index 765bcbacb..f1b0c2d05 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -9,9 +8,7 @@ namespace Inno.Editor.Settings; internal sealed class EditorSettingsCatalog : TypeRegistry { internal EditorSettingsCatalog(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot snapshot => current; @@ -40,13 +37,10 @@ protected override Snapshot Build(TypeCacheSnapshot types) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) { - throw new InvalidOperationException( - $"Editor setting path '{duplicatePath}' is registered more than once."); + throw new InvalidOperationException($"Editor setting path '{duplicatePath}' is registered more than once."); } - var byPath = definitions.ToDictionary( - static setting => setting.path, - StringComparer.Ordinal); + Dictionary byPath = definitions.ToDictionary(static setting => setting.path, StringComparer.Ordinal); return new Snapshot(types.version, definitions, byPath); } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs index 74d805b2d..ffce43074 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs @@ -1,6 +1,7 @@ using Inno.Core.Events; namespace Inno.Editor.Settings; + internal sealed class EditorSettingsChangedEvent(EditorSettings settings) : Event { internal EditorSettings settings { get; } = settings; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs index 186cc76cd..dc2e3c0f5 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs index ec1d5a345..e036f7c31 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - using Inno.Editor.Interactions; namespace Inno.Editor.Settings; @@ -14,106 +13,27 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(payload)); } - internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(EditorHistoryChange change) + internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(EditorHistoryChange change) { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Settings history payload has an invalid boundary."); + } ReadOnlyMemory before = payload.AsMemory(sizeof(int), beforeLength); ReadOnlyMemory after = payload.AsMemory(sizeof(int) + beforeLength); return (before, after); } } - -[EditorHistoryHandler(EditorSettingsHistory.C_KIND)] -internal sealed class EditorSettingsHistoryHandler(EditorSettings settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); - settings.RestoreFromHistory( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - settings.NotifyChanged(); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreFromHistory(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}"); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs new file mode 100644 index 000000000..eb3c5e91f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Settings; + +[EditorHistoryHandler(EditorSettingsHistory.C_KIND)] +internal sealed class EditorSettingsHistoryHandler(EditorSettings settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + settings.NotifyChanged(); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreFromHistory(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs index e478c3fa0..1136ec8f2 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs @@ -1,16 +1,15 @@ using System; using System.Collections.Generic; using System.IO; - +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; namespace Inno.Editor.Settings; internal sealed class EditorSettingsStore { - internal const string C_FILE_NAME = SettingsFileNames.editor; + internal const string C_FILE_NAME = SettingsFileNames.C_EDITOR; private readonly SettingsDocumentStore m_documents; private Dictionary m_values; @@ -26,7 +25,8 @@ SerializationRegistry serialization new FileByteDocumentStore(path), serialization, static () => new EditorSettingsDocument(), - ValidateDocumentValue); + ValidateDocumentValue + ); m_values = ValidateAndCopy(m_documents.Load().values); } @@ -75,19 +75,22 @@ private Dictionary ReadValues(ReadOnlySpan do return ValidateAndCopy(parsed.values); } catch (Exception exception) when (exception is ArgumentException - or InvalidDataException - or InvalidOperationException - or NotSupportedException) + or InvalidDataException + or InvalidOperationException + or NotSupportedException) { throw new InvalidDataException( "The editor Settings document is not a valid current-format document.", - exception); + exception + ); } } private byte[] Serialize(IReadOnlyDictionary values) => m_documents.Capture(new EditorSettingsDocument { values = Copy(values) }); + private void Write(ReadOnlySpan document) => m_documents.Restore(document); + private static Dictionary ValidateAndCopy(IReadOnlyDictionary values) { ArgumentNullException.ThrowIfNull(values); @@ -104,9 +107,13 @@ private static Dictionary ValidateAndCopy(IReadOnly throw new InvalidDataException("The editor Settings document contains an invalid path.", exception); } if (!string.Equals(path, normalized, StringComparison.Ordinal)) + { throw new InvalidDataException($"Settings path '{path}' is not normalized."); + } if (value is null) + { throw new InvalidDataException($"Settings path '{path}' has a null object."); + } value.Validate(path); result.Add(path, value.Copy()); } @@ -117,12 +124,12 @@ private static Dictionary Copy(IReadOnlyDictionary< { var result = new Dictionary(values.Count, StringComparer.Ordinal); foreach ((string path, EditorSettingObject value) in values) + { result.Add(path, value.Copy()); + } return result; } - private void Write(ReadOnlySpan document) => m_documents.Restore(document); - private static void ValidateDocumentValue(EditorSettingsDocument document) { ArgumentNullException.ThrowIfNull(document); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs index e58f17e1c..50fcbbc35 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -16,8 +15,7 @@ internal sealed class ProjectSettingEditorCatalog : TypeRegistry definition.path, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) + { throw new InvalidOperationException($"Project setting path '{duplicatePath}' is registered more than once."); + } - IGrouping? incompatiblePresentations = definitions - .GroupBy(static definition => definition.settingId) + IGrouping? incompatiblePresentations = definitions + .GroupBy(static definition => definition.settingID) .FirstOrDefault(static group => group .Select(static definition => definition.valueType) .Distinct() @@ -61,7 +61,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (incompatiblePresentations is not null) { throw new InvalidOperationException( - $"Project setting ID '{incompatiblePresentations.Key}' has Editor presentations for more than one value type."); + $"Project setting ID '{incompatiblePresentations.Key}' has Editor presentations for more than one value type." + ); } return new Snapshot(types.version, definitions); @@ -85,9 +86,10 @@ private ProjectSettingEditor CreateDefinition(Type type) ProjectSettingDefinitionAttribute setting = definition.valueType .GetCustomAttribute(inherit: false) ?? throw new InvalidOperationException( - $"Project setting editor '{type.FullName}' targets '{definition.valueType.FullName}', " + - $"which is missing {nameof(ProjectSettingDefinitionAttribute)}."); - definition.BindSettingId(new ProjectSettingId(setting.id)); + $"Project setting editor '{type.FullName}' targets '{definition.valueType.FullName}', " + + $"which is missing {nameof(ProjectSettingDefinitionAttribute)}." + ); + definition.BindSettingID(new ProjectSettingID(setting.id)); definition.BindSerialization(m_serialization); definition.BindPlacement(attribute.path, attribute.order); return definition; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs index 4bc73a0d8..a508db2be 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -26,9 +25,6 @@ public sealed class ProjectSettingsEditor : EditorModule /// /// The Editor interaction service that owns Undo and Redo. /// - /// - /// Thrown when is . - /// /// /// The host-owned type catalog used to discover setting presentations. /// @@ -38,6 +34,9 @@ public sealed class ProjectSettingsEditor : EditorModule /// /// The serialization registry used to compare staged setting values. /// + /// + /// Thrown when is . + /// internal ProjectSettingsEditor( EditorInteractions interactions, TypeCatalog types, @@ -81,10 +80,11 @@ SerializationRegistry serialization public ISerializable Get(ProjectSettingEditor definition) { ArgumentNullException.ThrowIfNull(definition); - if (!m_settings.TryClone(definition.settingId, out ISerializable? setting) || setting is null) + if (!m_settings.TryClone(definition.settingID, out ISerializable? setting) || setting is null) { throw new InvalidOperationException( - $"Project setting '{definition.settingId}' has no active runtime definition."); + $"Project setting '{definition.settingID}' has no active runtime definition." + ); } definition.ValidateValue(setting); return setting; @@ -108,12 +108,11 @@ public ISerializable Get(ProjectSettingEditor definition) public ISerializable GetComposedDefault(ProjectSettingEditor definition) { ArgumentNullException.ThrowIfNull(definition); - if (!m_settings.TryCloneComposedDefault( - definition.settingId, - out ISerializable? setting) || setting is null) + if (!m_settings.TryCloneComposedDefault(definition.settingID, out ISerializable? setting) || setting is null) { throw new InvalidOperationException( - $"Project setting '{definition.settingId}' has no active runtime definition."); + $"Project setting '{definition.settingID}' has no active runtime definition." + ); } definition.ValidateValue(setting); return setting; @@ -135,13 +134,15 @@ public ISerializable GetComposedDefault(ProjectSettingEditor definition) /// Thrown when is . /// public bool Apply( - IReadOnlyDictionary values, - IReadOnlySet? resets = null + IReadOnlyDictionary values, + IReadOnlySet? resets = null ) { ArgumentNullException.ThrowIfNull(values); byte[] before = m_settings.CaptureDocument(); if (!m_settings.ApplyProjectOverrides(values, resets)) + { return false; + } byte[] after = m_settings.CaptureDocument(); try { @@ -166,5 +167,4 @@ public bool Apply( internal void ValidateDocument(ReadOnlySpan document) => m_settings.ValidateDocument(document); internal void RestoreFromHistory(ReadOnlySpan document) => m_settings.RestoreDocument(document); - } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs index 5509b72e6..edb5bdedd 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - using Inno.Editor.Interactions; namespace Inno.Editor.Settings; @@ -14,106 +13,27 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(payload)); } - internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(EditorHistoryChange change) + internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(EditorHistoryChange change) { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Project Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Project Settings history payload has an invalid boundary."); + } ReadOnlyMemory before = payload.AsMemory(sizeof(int), beforeLength); ReadOnlyMemory after = payload.AsMemory(sizeof(int) + beforeLength); return (before, after); } } - -[EditorHistoryHandler(ProjectSettingsHistory.C_KIND)] -internal sealed class ProjectSettingsHistoryHandler(ProjectSettingsEditor settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); - settings.RestoreFromHistory( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreFromHistory(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Project Settings transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs new file mode 100644 index 000000000..0026e7216 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Settings; + +[EditorHistoryHandler(ProjectSettingsHistory.C_KIND)] +internal sealed class ProjectSettingsHistoryHandler(ProjectSettingsEditor settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreFromHistory(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Project Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs index c0afd1b8c..70a126e5f 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs @@ -1,7 +1,7 @@ using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Linq; namespace Inno.Editor.Hosting; @@ -53,14 +53,22 @@ public static async Task RunAsync( ArgumentException.ThrowIfNullOrWhiteSpace(options.projectDirectory); ArgumentException.ThrowIfNullOrWhiteSpace(options.supportPackRoot); if (options.smokeFrameLimit is <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "A smoke frame limit must be positive."); + } if (!options.distribution.availableTargets.Contains(options.defaultBuildTarget)) + { throw new ArgumentException("The explicit default build target is absent from the distribution.", nameof(options)); + } options.shell.adapters.Validate(options.adapterCatalog); if (!options.presentation.isValid || !options.adapterCatalog.presentation.supportedBackends.Contains(options.presentation)) + { throw new NotSupportedException("The selected presentation backend is not registered."); + } if (!options.adapterCatalog.renderingAuthoring.supportedBackends.Contains(options.shell.adapters.rendering)) + { throw new NotSupportedException("The selected rendering backend requires a matching authoring provider."); + } cancellationToken.ThrowIfCancellationRequested(); EditorHost host = EditorHost.Create(options); int result; diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs index e40c64f20..66afa6855 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs @@ -10,7 +10,10 @@ namespace Inno.Editor.Hosting; /// public sealed class EditorCommandLineOptions { - private EditorCommandLineOptions(string projectDirectory) => this.projectDirectory = projectDirectory; + private EditorCommandLineOptions(string projectDirectory) + { + this.projectDirectory = projectDirectory; + } /// /// Gets the caller-selected authoring project. @@ -51,8 +54,19 @@ public sealed class EditorCommandLineOptions /// public static EditorCommandLineOptions Parse(string[] arguments) { - if (!TryGetRunOptions(arguments, out string? project, out int? smoke, out GraphicsApi? graphics, out bool visible, out string? dependencies)) - throw new ArgumentException("Usage: Editor [--graphics-api ] [--window-visible ] [--smoke-frames ] [--native-dependencies ].", nameof(arguments)); + if (!TryGetRunOptions( + arguments, + out string? project, + out int? smoke, + out GraphicsApi? graphics, + out bool visible, + out string? dependencies + )) { + throw new ArgumentException( + "Usage: Editor [--graphics-api ] [--window-visible ] [--smoke-frames ] [--native-dependencies ].", + nameof(arguments) + ); + } return new EditorCommandLineOptions(project) { smokeFrameLimit = smoke, @@ -61,6 +75,7 @@ public static EditorCommandLineOptions Parse(string[] arguments) nativeDependencies = dependencies }; } + private static bool TryGetRunOptions( string[] args, [NotNullWhen(true)] out string? projectDirectory, @@ -77,17 +92,21 @@ out string? nativeDependencies bool hasVisibility = false; projectDirectory = args.Length > 0 ? args[0] : null; if (projectDirectory is null) + { return false; + } for (int index = 1; index < args.Length; index += 2) { if (index + 1 >= args.Length) + { return false; + } if (string.Equals(args[index], "--smoke-frames", StringComparison.Ordinal)) { if (smokeFrameLimit is not null || !int.TryParse(args[index + 1], out int parsedFrameLimit) - || parsedFrameLimit <= 0) - { + || parsedFrameLimit <= 0 + ) { return false; } smokeFrameLimit = parsedFrameLimit; @@ -96,21 +115,27 @@ out string? nativeDependencies if (string.Equals(args[index], "--graphics-api", StringComparison.Ordinal)) { if (graphicsApi is not null || !TryParseGraphicsApi(args[index + 1], out GraphicsApi parsedApi)) + { return false; + } graphicsApi = parsedApi; continue; } if (string.Equals(args[index], "--window-visible", StringComparison.Ordinal)) { if (hasVisibility || !bool.TryParse(args[index + 1], out windowVisible)) + { return false; + } hasVisibility = true; continue; } if (string.Equals(args[index], "--native-dependencies", StringComparison.Ordinal)) { if (nativeDependencies is not null || !Path.IsPathFullyQualified(args[index + 1])) + { return false; + } nativeDependencies = Path.GetFullPath(args[index + 1]); continue; } @@ -130,13 +155,13 @@ out GraphicsApi api } api = value.ToLowerInvariant() switch { - "d3d11" => GraphicsApi.Direct3D11, - "d3d12" => GraphicsApi.Direct3D12, - "metal" => GraphicsApi.Metal, - "vulkan" => GraphicsApi.Vulkan, - "opengl" => GraphicsApi.OpenGL, + "d3d11" => GraphicsApi.direct3D11, + "d3d12" => GraphicsApi.direct3D12, + "metal" => GraphicsApi.metal, + "vulkan" => GraphicsApi.vulkan, + "opengl" => GraphicsApi.openGL, _ => GraphicsApi.TryParse(value, out GraphicsApi parsed) ? parsed : default }; - return api.isValid && api != GraphicsApi.Noop; + return api.isValid && api != GraphicsApi.noop; } } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs index bff549b23..176adc96c 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs @@ -1,7 +1,7 @@ using System; using Inno.Adapter.Presentation; -using Inno.Build.Composition; using Inno.Build; +using Inno.Build.Composition; using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Extensibility.Modules; @@ -39,7 +39,7 @@ public sealed class EditorLaunchOptions /// /// Gets the explicit presentation implementation selected by the product. /// - public required PresentationBackendId presentation { get; init; } + public required PresentationBackendID presentation { get; init; } /// /// Gets the borrowed owner-thread scheduling policy. @@ -54,7 +54,7 @@ public sealed class EditorLaunchOptions /// /// Gets the explicit default game target for new project build settings. /// - public required BuildTargetId defaultBuildTarget { get; init; } + public required BuildTargetID defaultBuildTarget { get; init; } /// /// Gets the explicitly selected SDK and build execution host. @@ -79,7 +79,7 @@ public sealed class EditorLaunchOptions /// /// Gets an optional factory transferring each edit or play log sink to its owning session. /// - public Func? createSessionLogSink { get; init; } + public Func? createSessionLogSink { get; init; } /// /// Gets an optional factory transferring one host log sink to the Editor lifetime. diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs index bfad6ab29..1fd3e36fe 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs @@ -1,15 +1,14 @@ -using Inno.Core.IO; -using Inno.Build; using System; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Settings; +using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; @@ -36,6 +35,21 @@ ScriptCompiler compiler this.compiler = compiler; } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + plugins.Dispose(); + assets.Dispose(); + settings.Dispose(); + } + internal AssetPipeline assets { get; } internal IdentityAllocator identities { get; } @@ -46,6 +60,13 @@ ScriptCompiler compiler internal ProjectSettingsStore settings { get; } + internal void Update() + { + ObjectDisposedException.ThrowIf(m_disposed, this); + plugins.Update(); + assets.Update(); + } + internal static EditorAuthoringServices Start( string projectDirectory, EngineHost engineHost, @@ -68,14 +89,12 @@ string dotnetHost PluginEnvironment? plugins = null; try { - var pluginSources = new PluginSourceService( - engineHost.serialization, - pluginRoot, - libraryRoot); + var pluginSources = new PluginSourceService(engineHost.serialization, pluginRoot, libraryRoot); PluginScanResult pluginScan = pluginSources.Scan(); AssetPipelineOptions defaultOptions = AssetPipelineOptions.Create(assetRoot, libraryRoot); AssetSourceMount projectMount = defaultOptions.sourceMounts!.Single( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceID.project + ); assets = new AssetPipeline( engineHost.modules, engineHost.types, @@ -91,13 +110,15 @@ defaultOptions with projectMount, .. PluginSourceService.GetActivatableMounts(pluginScan) ] - }); + } + ); settings = new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.project))), + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.C_PROJECT))), engineHost.types, engineHost.serialization, - ProjectId.FromName(new DirectoryInfo(projectRoot).Name), - AssetSerializationContext.Create(assets)); + ProjectID.FromName(new DirectoryInfo(projectRoot).Name), + AssetSerializationContext.Create(assets) + ); plugins = new PluginEnvironment( assets, settings, @@ -105,13 +126,15 @@ .. PluginSourceService.GetActivatableMounts(pluginScan) pluginRoot, libraryRoot, pluginScan, - engineHost.modules.generations); + engineHost.modules.generations + ); foreach (PluginDiagnostic diagnostic in plugins.discovery.diagnostics) { log.Write( LogLevel.Warn, "Plugin source '{0}' was excluded from the active candidate: {1}", - [diagnostic.sourcePath, diagnostic.message]); + [diagnostic.sourcePath, diagnostic.message] + ); } var compiler = new ScriptCompiler( new ScriptCompilerOptions @@ -120,7 +143,8 @@ .. PluginSourceService.GetActivatableMounts(pluginScan) compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); return new EditorAuthoringServices(settings, assets, identities, plugins, compiler); } catch @@ -131,24 +155,4 @@ .. PluginSourceService.GetActivatableMounts(pluginScan) throw; } } - - internal void Update() - { - ObjectDisposedException.ThrowIf(m_disposed, this); - plugins.Update(); - assets.Update(); - } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - plugins.Dispose(); - assets.Dispose(); - settings.Dispose(); - } } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs index b0cb47e6b..527041bda 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs @@ -1,9 +1,4 @@ -using Inno.Extensibility.Modules; -using Inno.Scripting.Compiler; -using Inno.Engine.Default; -using Inno.Runtime.Contracts; using System; -using Inno.Core.Diagnostics; using System.Collections.Generic; using System.IO; using System.Linq; @@ -11,14 +6,14 @@ using Inno.Adapter.Audio; using Inno.Adapter.Input; using Inno.Adapter.Presentation; +using Inno.Animation.Runtime; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Animation.Runtime; -using Inno.Audio.Runtime; using Inno.Audio; +using Inno.Audio.Runtime; using Inno.Build; using Inno.Build.Composition; -using Inno.UI.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Layers; using Inno.Core.Logging; @@ -27,17 +22,24 @@ using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.Rendering; +using Inno.Engine.Default; +using Inno.Extensibility.Modules; using Inno.Input.Runtime; using Inno.Platform; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; +using Inno.Scripting.Compiler; using Inno.Shell; +using Inno.Storage; using Inno.Storage.Runtime; +using Inno.UI.Runtime; + using ShellHost = Inno.Shell.Shell; -using Inno.Rendering.Assets.Authoring; namespace Inno.Editor.Hosting; @@ -51,8 +53,8 @@ internal sealed class EditorHost : ShellHost private readonly EditorLaunchOptions m_launch; private readonly IAuthoringAdapterCatalog m_authoringAdapters; - private readonly HashSet m_focusedWindowIds = []; - private readonly PresentationBackendId m_presentationBackend; + private readonly HashSet m_focusedWindowIDs = []; + private readonly PresentationBackendID m_presentationBackend; private readonly EditorHostResourceStack m_resources; private readonly string m_bootLogPath; private RuntimeSession? m_editSession; @@ -70,14 +72,16 @@ private EditorHost( EditorLaunchOptions launch, string projectDirectory, string bootLogPath - ) : base(launch.adapterCatalog, launch.shell) { + ) : base(launch.adapterCatalog, launch.shell) + { m_launch = launch; m_authoringAdapters = launch.adapterCatalog; m_presentationBackend = launch.presentation; this.projectDirectory = projectDirectory; m_bootLogPath = bootLogPath; m_resources = new EditorHostResourceStack( - exception => AppendBootLog(bootLogPath, $"Teardown failure: {exception}")); + exception => AppendBootLog(bootLogPath, $"Teardown failure: {exception}") + ); } /// @@ -85,32 +89,6 @@ string bootLogPath /// public string projectDirectory { get; } - internal static EditorHost Create(EditorLaunchOptions launch) - { - IAuthoringAdapterCatalog adapterCatalog = launch.adapterCatalog; - AdapterSelection adapterSelection = launch.shell.adapters; - if (!adapterSelection.rendering.isValid || - !adapterCatalog.rendering.supportedBackends.Contains(adapterSelection.rendering) || - !adapterCatalog.renderingAuthoring.supportedBackends.Contains(adapterSelection.rendering)) - throw new NotSupportedException( - $"Rendering backend '{adapterSelection.rendering}' requires paired runtime and authoring providers."); - string normalizedProject = PrepareProjectDirectory(launch.projectDirectory); - string logDirectory = Path.Combine(normalizedProject, C_LOG_DIRECTORY_NAME); - Directory.CreateDirectory(logDirectory); - string bootLogPath = Path.Combine(logDirectory, C_BOOT_LOG_FILE_NAME); - var host = new EditorHost(launch, normalizedProject, bootLogPath); - try - { - host.Initialize(); - return host; - } - catch - { - host.Dispose(); - throw; - } - } - /// /// Records that the shared composition run loop is starting. /// @@ -140,9 +118,11 @@ protected override bool ShouldExit(Event evnt) } bool shouldExit = evnt is WindowCloseEvent closeEvent - && closeEvent.windowId == primaryWindow.windowId; + && closeEvent.windowID == primaryWindow.windowID; if (shouldExit) + { BootLog($"Exit requested by event: {evnt.GetType().Name}."); + } return shouldExit; } @@ -163,7 +143,9 @@ protected override bool ShouldExit(Event evnt) protected override void OnFrame(ShellFrame frame) { if (frame.frameIndex == 0) + { BootLog("About to execute first editor frame."); + } using (rendering.EnterExecutionScope()) using (audio.EnterExecutionScope(editSession)) @@ -173,7 +155,7 @@ protected override void OnFrame(ShellFrame frame) authoring.Update(); editSession.Tick(frame.deltaTime); using (editSession.EnterExecutionScope()) - using (editSession.subsystems.GetRequiredSubsystem().EnterExecutionScope()) + using (editSession.subsystems.GetRequiredSubsystem().EnterExecutionScope()) { layers.OnUpdate(frame.deltaTime); m_gameInputCapture?.BeginFrame(); @@ -183,15 +165,19 @@ protected override void OnFrame(ShellFrame frame) } finally { - uint resetWindowId = m_gameInputCapture?.CompleteFrame() ?? 0; - if (resetWindowId != 0) - m_gameInputSource?.ProcessEvent(new WindowFocusChangedEvent(resetWindowId, false)); + uint resetWindowID = m_gameInputCapture?.CompleteFrame() ?? 0; + if (resetWindowID != 0) + { + m_gameInputSource?.ProcessEvent(new WindowFocusChangedEvent(resetWindowID, false)); + } } } } if (frame.frameIndex == 0) + { BootLog("First editor frame completed."); + } } /// @@ -209,10 +195,17 @@ protected override void OnSmokeCompleted(int frameCount) hub.UnregisterSink(snapshot); string[] errors = snapshot.errors; foreach (string error in errors) + { BootLog("Smoke diagnostic: " + error); + } if (errors.Length != 0) - throw new InvalidOperationException($"Native Editor smoke completed with {errors.Length} active error diagnostic(s). See the smoke diagnostics above."); + { + throw new InvalidOperationException( + $"Native Editor smoke completed with {errors.Length} active error diagnostic(s). See the smoke diagnostics above." + ); + } } + /// /// Submits product UI requests while the host output pipeline is open. /// @@ -222,7 +215,7 @@ protected override void OnSmokeCompleted(int frameCount) protected override void OnPresentation(ShellFrame frame) { using IDisposable scope = editSession.EnterExecutionScope(); - using IDisposable uiScope = editSession.subsystems.GetRequiredSubsystem().EnterExecutionScope(); + using IDisposable uiScope = editSession.subsystems.GetRequiredSubsystem().EnterExecutionScope(); layers.RenderFrame(frame.deltaTime); } @@ -259,6 +252,35 @@ protected override void DisposeProductResources() /// internal void ReportShutdownCompleted() => BootLog("Dispose end."); + internal static EditorHost Create(EditorLaunchOptions launch) + { + IAuthoringAdapterCatalog adapterCatalog = launch.adapterCatalog; + AdapterSelection adapterSelection = launch.shell.adapters; + if (!adapterSelection.rendering.isValid + || !adapterCatalog.rendering.supportedBackends.Contains(adapterSelection.rendering) + || !adapterCatalog.renderingAuthoring.supportedBackends.Contains(adapterSelection.rendering) + ) { + throw new NotSupportedException( + $"Rendering backend '{adapterSelection.rendering}' requires paired runtime and authoring providers." + ); + } + string normalizedProject = PrepareProjectDirectory(launch.projectDirectory); + string logDirectory = Path.Combine(normalizedProject, C_LOG_DIRECTORY_NAME); + Directory.CreateDirectory(logDirectory); + string bootLogPath = Path.Combine(logDirectory, C_BOOT_LOG_FILE_NAME); + var host = new EditorHost(launch, normalizedProject, bootLogPath); + try + { + host.Initialize(); + return host; + } + catch + { + host.Dispose(); + throw; + } + } + private RuntimeSession editSession => m_editSession ?? throw new InvalidOperationException("The Editor runtime session is not initialized."); @@ -282,51 +304,59 @@ private void Initialize() AppendBootLog(m_bootLogPath, "EditorHost creation start."); InitializeAdapterResources(); if (primaryWindow.isFocused) - m_focusedWindowIds.Add(primaryWindow.windowId); + { + m_focusedWindowIDs.Add(primaryWindow.windowID); + } - EngineHost engineHost = m_resources.Acquire( - m_launch.createEngineHost, - static host => host.Dispose()); + EngineHost engineHost = m_resources.Acquire(m_launch.createEngineHost, static host => host.Dispose()); ILogSink? hostLog = m_launch.createHostLogSink?.Invoke(); m_diagnostics = engineHost.diagnostics; if (hostLog is not null) { if (hostLog is IDisposable disposableLog) + { m_resources.Register(disposableLog.Dispose); + } engineHost.logs.RegisterSink(hostLog); m_resources.Register(() => engineHost.logs.UnregisterSink(hostLog)); } EditorAuthoringServices activeAuthoring = m_resources.Acquire( () => EditorAuthoringServices.Start(projectDirectory, engineHost, m_launch.buildContext.dotnetHost), - static services => services.Dispose()); + static services => services.Dispose() + ); m_authoring = activeAuthoring; _ = m_resources.Acquire( () => AssetExecutionContext.EnterScope(activeAuthoring.assets), - static scope => scope.Dispose()); + static scope => scope.Dispose() + ); _ = m_resources.Acquire( () => ProjectSettingsExecutionContext.EnterScope(activeAuthoring.settings), - static scope => scope.Dispose()); + static scope => scope.Dispose() + ); EditorAudioHost activeAudio = m_resources.Acquire( () => new EditorAudioHost( engineHost.types, activeAuthoring.assets, engineHost.diagnostics, () => adapters.audio.CreateDevice(adapterSelection.audio, new AudioBackendOptions()), - () => activeAuthoring.settings.TryGet( - AudioProjectSettings.settingId, - out AudioProjectSettings? configured) && configured is not null + () => ( + activeAuthoring.settings.TryGet(AudioProjectSettings.settingID, out AudioProjectSettings? configured) + && configured is not null ? configured - : new AudioProjectSettings()), - static host => host.Dispose()); + : new AudioProjectSettings() + ) + ), + static host => host.Dispose() + ); m_audio = activeAudio; RuntimeSession activeEditSession = m_resources.Acquire( () => engineHost.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, - applicationId = "inno.editor", + applicationID = "inno.editor", createLogSink = m_launch.createSessionLogSink is null - ? null - : session => m_launch.createSessionLogSink(RuntimeSessionKind.Edit, session), + ? null + : session => m_launch.createSessionLogSink(RuntimeSessionKind.Edit, session), fixedDeltaTime = 1f / 60f, maxFrameDeltaTime = 0.25f, maxFixedStepsPerFrame = 8, @@ -334,11 +364,10 @@ private void Initialize() createSubsystems = owner => CreateStandardRuntimeSubsystems(activeAudio, inputSource, owner), referenceResolvers = [activeAuthoring.assets] }), - static session => session.Dispose()); + static session => session.Dispose() + ); m_editSession = activeEditSession; - _ = m_resources.Acquire( - activeEditSession.EnterExecutionScope, - static scope => scope.Dispose()); + _ = m_resources.Acquire(activeEditSession.EnterExecutionScope, static scope => scope.Dispose()); BuildPipeline buildPipeline = BuildPipelineFactory.Create( m_launch.buildContext, @@ -348,18 +377,22 @@ private void Initialize() activeAuthoring.plugins, activeAuthoring.settings, activeAuthoring.compiler, - m_launch.supportPackRoot); + m_launch.supportPackRoot + ); BuildSettings defaultBuildSettings = BuildSettings.CreateDefault( Path.GetFileName(Path.TrimEndingDirectorySeparator(projectDirectory)), FindDefaultStartupScene(activeAuthoring.assets), - m_launch.defaultBuildTarget); + m_launch.defaultBuildTarget + ); var buildSettings = new BuildSettingsStore( - Path.Combine(projectDirectory, SettingsFileNames.build), + Path.Combine(projectDirectory, SettingsFileNames.C_BUILD), engineHost.serialization, - defaultBuildSettings); + defaultBuildSettings + ); LayerStack activeLayers = m_resources.Acquire( () => new LayerStack(() => activeEditSession.events.CreateHub()), - static stack => stack.Dispose()); + static stack => stack.Dispose() + ); m_layers = activeLayers; m_resources.Register(() => { @@ -375,23 +408,26 @@ private void Initialize() }); var shaderCompiler = new ShaderCompiler( - m_authoringAdapters.renderingAuthoring.CreateShaderCompilerToolchain( - adapterSelection.rendering)); - ITextureTargetCompiler textureCompiler = - m_authoringAdapters.renderingAuthoring.CreateTextureTargetCompiler( - adapterSelection.rendering); + m_authoringAdapters.renderingAuthoring.CreateShaderCompilerToolchain(adapterSelection.rendering) + ); + ITextureTargetCompiler textureCompiler = m_authoringAdapters.renderingAuthoring.CreateTextureTargetCompiler( + adapterSelection.rendering + ); DiagnosticReporter renderDiagnostics = m_resources.Acquire( () => engineHost.diagnostics.CreateReporter(new DiagnosticSource("inno.editor.rendering", "Rendering")), - static sink => sink.Dispose()); - var renderArtifacts = m_resources.Acquire( + static sink => sink.Dispose() + ); + EditorRenderTargetArtifactProvider renderArtifacts = m_resources.Acquire( () => new EditorRenderTargetArtifactProvider( activeAuthoring.assets, engineHost.serialization, engineHost.types, shaderCompiler, textureCompiler, - renderDiagnostics), - static provider => provider.Dispose()); + renderDiagnostics + ), + static provider => provider.Dispose() + ); presentation = m_resources.Acquire( () => m_authoringAdapters.presentation.CreateContext( m_presentationBackend, @@ -403,16 +439,22 @@ private void Initialize() features = PresentationFeatures.MultipleWindows | PresentationFeatures.Docking | PresentationFeatures.SmoothResize - }), - static context => context.Dispose()); + } + ), + static context => context.Dispose() + ); m_gameInputCapture = new EditorGameInputCapture( - viewportId => presentation.TryGetWindowId(viewportId, out uint windowId) - && m_focusedWindowIds.Contains(windowId) - ? windowId - : null); + viewportID => ( + presentation.TryGetWindowID(viewportID, out uint windowID) + && m_focusedWindowIDs.Contains(windowID) + ? windowID + : null + ) + ); IInputEventSource gameInputSource = m_resources.Acquire( () => adapters.input.CreateEventSource(adapterSelection.input, primaryWindow, acceptAllWindows: true), - static source => source.Dispose()); + static source => source.Dispose() + ); m_gameInputSource = gameInputSource; activeEditSession.events.dispatched += RouteGameInput; m_resources.Register(() => activeEditSession.events.dispatched -= RouteGameInput); @@ -422,29 +464,27 @@ private void Initialize() renderDiagnostics, contributors: [presentation], targetArtifacts: renderArtifacts, - compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider( - adapterSelection.rendering)); + compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider(adapterSelection.rendering) + ); m_rendering = renderingLayer; RuntimeSubsystemPipeline hostPipeline = engineHost.CreateHostPipeline(DefaultEngine.CreateHostSubsystems(renderingLayer)); m_resources.Register(hostPipeline.Dispose); UseHostPipeline(hostPipeline); var reloadCoordinator = new EditorReloadCoordinator(); - var renderingHost = m_resources.Acquire( - () => new EditorRenderingHostService( - renderingLayer, - presentation, - reloadCoordinator), - static service => service.Dispose()); + EditorRenderingHostService renderingHost = m_resources.Acquire( + () => new EditorRenderingHostService(renderingLayer, presentation, reloadCoordinator), + static service => service.Dispose() + ); var editorContext = new EditorContext(projectDirectory, m_launch.keyboard, EditorDefaultLayout.document); presentation.SetLayoutFile(null); presentation.LoadLayout(editorContext.imguiLayout); var playOptions = new RuntimeSessionOptions { kind = RuntimeSessionKind.Play, - applicationId = "inno.editor.play", - createLogSink = m_launch.createSessionLogSink is null - ? null - : session => m_launch.createSessionLogSink(RuntimeSessionKind.Play, session), + applicationID = "inno.editor.play", + createLogSink = m_launch.createSessionLogSink is null + ? null + : session => m_launch.createSessionLogSink(RuntimeSessionKind.Play, session), fixedDeltaTime = 1f / 60f, maxFrameDeltaTime = 0.25f, maxFixedStepsPerFrame = 8, @@ -452,7 +492,7 @@ private void Initialize() createSubsystems = owner => CreateStandardRuntimeSubsystems(activeAudio, gameInputSource, owner), referenceResolvers = [activeAuthoring.assets] }; - EditorLayer layer = new EditorLayer( + var layer = new EditorLayer( presentation, editorContext, engineHost.types, @@ -480,7 +520,8 @@ private void Initialize() activeAuthoring.identities, activeEditSession.identities, activeAudio - ]) + ] + ) { isFocused = primaryWindow.isFocused }; @@ -488,23 +529,31 @@ private void Initialize() m_resources.Register(() => { if (overlayPushed) + { activeLayers.PopOverlay(layer); + } else + { layer.DisposeUnattached(); + } }); activeLayers.PushOverlay(layer); overlayPushed = true; if (layer.panelCount == 0) + { throw new InvalidOperationException("No editor panels were discovered from the active host assemblies."); + } BootLog($"Editor layer attached with {layer.panelCount} panel(s)."); BootLog( $"Rendering initialized with {renderDevice.capabilities.backend} " - + $"(views={renderDevice.capabilities.limits.maxViews})."); + + $"(views={renderDevice.capabilities.limits.maxViews})." + ); BootLog($"Primary presentation encodes sRGB: {renderDevice.primaryPresentationEncodesSrgb}."); BootLog( $"AssetPipeline initialized={activeAuthoring.assets.isInitialized} " - + $"root='{activeAuthoring.assets.assetRoot}'."); + + $"root='{activeAuthoring.assets.assetRoot}'." + ); } private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) @@ -517,56 +566,50 @@ RuntimeSession owner ) { ArgumentNullException.ThrowIfNull(activeAudio); ArgumentNullException.ThrowIfNull(activeInputSource); - return DefaultEngine.CreateSessionSubsystems(new EngineSessionComposition( - owner, adapters, adapterSelection, activeInputSource, authoring.assets, - () => authoring.settings.TryGet(AudioProjectSettings.settingId, out AudioProjectSettings? settings) && settings is not null - ? settings : new AudioProjectSettings(), - () => adapters.storage.CreateStorage(adapterSelection.storage, - new Inno.Storage.StorageScope(owner.options.applicationId)), - activeAudio.CreateRuntimeSubsystemFactory(owner))); - } - - private static string PrepareProjectDirectory(string projectDirectory) - { - if (string.IsNullOrWhiteSpace(projectDirectory)) - throw new ArgumentException("Project directory is required.", nameof(projectDirectory)); - string normalizedPath = Path.GetFullPath(projectDirectory); - if (File.Exists(normalizedPath)) - throw new IOException($"Project directory '{normalizedPath}' points to a file."); - Directory.CreateDirectory(normalizedPath); - return normalizedPath; - } - - private static string FindDefaultStartupScene(AssetPipeline assets) - { - foreach (AssetFileEntry entry in assets.GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.source == AssetSourceId.project) - .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) - .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal)) - { - if (assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) - return entry.assetPath.ToString(); - } - return string.Empty; + return DefaultEngine.CreateSessionSubsystems( + new EngineSessionComposition( + owner, + adapters, + adapterSelection, + activeInputSource, + authoring.assets, + () => ( + authoring.settings.TryGet(AudioProjectSettings.settingID, out AudioProjectSettings? settings) && settings is not null + ? settings + : new AudioProjectSettings() + ), + () => adapters.storage.CreateStorage( + adapterSelection.storage, + new StorageScope(owner.options.applicationID) + ), + activeAudio.CreateRuntimeSubsystemFactory(owner) + ) + ); } private void RouteGameInput(Event evnt) { Event? gameEvent = m_gameInputCapture?.Route(evnt); if (gameEvent is not null) + { m_gameInputSource?.ProcessEvent(gameEvent); + } } - private bool HasEditorFocus() => m_focusedWindowIds.Count > 0; + private bool HasEditorFocus() => m_focusedWindowIDs.Count > 0; private void SaveBeforeShutdown() { if (m_shutdownStateSaved || m_editorLayer is null) + { return; + } m_shutdownStateSaved = m_editorLayer.PrepareShutdown(); - BootLog(m_shutdownStateSaved + BootLog( + m_shutdownStateSaved ? "Project editor state frozen and saved before shutdown." - : "Project editor state save failed before shutdown."); + : "Project editor state save failed before shutdown." + ); } private void UpdateFocusedWindows(Event evnt) @@ -574,18 +617,52 @@ private void UpdateFocusedWindows(Event evnt) if (evnt is WindowFocusChangedEvent focusChanged) { if (focusChanged.isFocused) - m_focusedWindowIds.Add(focusChanged.windowId); + { + m_focusedWindowIDs.Add(focusChanged.windowID); + } else - m_focusedWindowIds.Remove(focusChanged.windowId); + { + m_focusedWindowIDs.Remove(focusChanged.windowID); + } } else if (evnt is WindowCloseEvent closeEvent) { - m_focusedWindowIds.Remove(closeEvent.windowId); + m_focusedWindowIDs.Remove(closeEvent.windowID); } } private void BootLog(string message) => AppendBootLog(m_bootLogPath, message); + private static string PrepareProjectDirectory(string projectDirectory) + { + if (string.IsNullOrWhiteSpace(projectDirectory)) + { + throw new ArgumentException("Project directory is required.", nameof(projectDirectory)); + } + string normalizedPath = Path.GetFullPath(projectDirectory); + if (File.Exists(normalizedPath)) + { + throw new IOException($"Project directory '{normalizedPath}' points to a file."); + } + Directory.CreateDirectory(normalizedPath); + return normalizedPath; + } + + private static string FindDefaultStartupScene(AssetPipeline assets) + { + foreach (AssetFileEntry entry in assets.GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.source == AssetSourceID.project) + .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) + .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) + ) { + if (assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) + { + return entry.assetPath.ToString(); + } + } + return string.Empty; + } + private static void AppendBootLog( string bootLogPath, string message @@ -606,12 +683,10 @@ private sealed class SmokeDiagnostics : IDiagnosticSink /// The current immutable report whose error messages are copied into the smoke snapshot. /// public void Replace(DiagnosticReport report) - { - m_reports[report.source] = report.diagnostics + => m_reports[report.source] = report.diagnostics .Where(static diagnostic => diagnostic.severity == DiagnosticSeverity.Error) .Select(diagnostic => report.source.id + "/" + diagnostic.code + ": " + diagnostic.message) .ToArray(); - } /// /// Removes errors when their diagnostic source is retired. diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs index 0d3c4d1f9..c0efc74b8 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs @@ -15,32 +15,15 @@ internal sealed class EditorHostResourceStack(Action reportCleanupFai private readonly List m_cleanup = []; private bool m_disposed; - internal T Acquire( - Func factory, - Action cleanup - ) { - ArgumentNullException.ThrowIfNull(factory); - ArgumentNullException.ThrowIfNull(cleanup); - ObjectDisposedException.ThrowIf(m_disposed, this); - T resource = factory(); - m_cleanup.Add(() => cleanup(resource)); - return resource; - } - - internal void Register(Action cleanup) - { - ArgumentNullException.ThrowIfNull(cleanup); - ObjectDisposedException.ThrowIf(m_disposed, this); - m_cleanup.Add(cleanup); - } - /// /// Releases the resources owned by this instance. /// public void Dispose() { if (m_disposed) + { return; + } List failures = []; for (int i = m_cleanup.Count - 1; i >= 0; i--) { @@ -60,7 +43,7 @@ public void Dispose() { reportCleanupFailure(exception); } - catch + catch (Exception) { // Cleanup diagnostics must never replace the original startup failure. } @@ -70,6 +53,27 @@ public void Dispose() m_disposed = true; m_cleanup.Clear(); if (failures.Count > 0) + { throw new AggregateException("Editor resources could not all retire cleanly.", failures); + } + } + + internal T Acquire( + Func factory, + Action cleanup + ) { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(cleanup); + ObjectDisposedException.ThrowIf(m_disposed, this); + T resource = factory(); + m_cleanup.Add(() => cleanup(resource)); + return resource; + } + + internal void Register(Action cleanup) + { + ArgumentNullException.ThrowIfNull(cleanup); + ObjectDisposedException.ThrowIf(m_disposed, this); + m_cleanup.Add(cleanup); } } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs index e850923d7..fdde4601f 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; +using Inno.Adapter.Presentation; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Layers; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Adapter.Presentation; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.PlayMode; +using Inno.Extensibility.Types; namespace Inno.Editor.Hosting; + /// /// Bridges the engine layer lifecycle to the attribute-discovered editor runtime. /// @@ -29,14 +30,16 @@ internal sealed class EditorLayer : Layer private bool m_isShutdownPrepared; private float m_totalTime; private double m_nextPersistenceRetryTime; + internal EditorLayer( IPresentationContext presentation, EditorContext context, TypeCatalog types, LogRouter logs, - System.Collections.Generic.IEnumerable? hostServices = null + IEnumerable? hostServices = null ) { - m_presentation = presentation ?? throw new ArgumentNullException(nameof(presentation)); + ArgumentNullException.ThrowIfNull(presentation); + m_presentation = presentation; m_context = context; m_log = logs.CreateLogger(); m_resources.Own(m_diagnostics); @@ -45,16 +48,6 @@ internal EditorLayer( m_prepareFrame = m_runtime.PrepareFrame; } - internal int panelCount => m_runtime.panelCount; - internal bool isFocused { get; set; } - internal float totalTime { set => m_totalTime = value; } - - internal void DisposeUnattached() - { - m_resources.Dispose(); - } - - internal void QuiescePlayMode() => m_playModeLoop.Quiesce(); /// /// Starts the editor extension runtime and subscribes its host-level input handling. /// @@ -80,6 +73,7 @@ public override void OnDetach() /// The elapsed frame time in seconds. /// public override void OnUpdate(float deltaTime) => m_playModeLoop.Tick(deltaTime); + /// /// Updates editor presentation after the active Play Mode session has advanced. /// @@ -93,15 +87,24 @@ public override void OnLateUpdate(float deltaTime) SaveLayoutIfChanged(); } - private void HandleKeyPressed(KeyPressedEvent keyEvent) + internal int panelCount => m_runtime.panelCount; + internal bool isFocused { get; set; } + + internal float totalTime { - m_runtime.HandleKeyPressed(keyEvent); + set => m_totalTime = value; } + internal void DisposeUnattached() => m_resources.Dispose(); + + internal void QuiescePlayMode() => m_playModeLoop.Quiesce(); + internal bool PrepareShutdown() { if (m_isShutdownPrepared) + { return true; + } try { // Extension-state capture freezes its periodic writer before reading module state. Layout is @@ -124,6 +127,8 @@ internal bool PrepareShutdown() } } + private void HandleKeyPressed(KeyPressedEvent keyEvent) => m_runtime.HandleKeyPressed(keyEvent); + private void SaveLayoutIfChanged() { bool layoutChanged = CaptureLayout(force: false); @@ -151,7 +156,9 @@ private void SaveLayoutIfChanged() private bool CaptureLayout(bool force) { if (!m_presentation.TryCaptureLayout(out string layout, force)) + { return false; + } m_context.SetImGuiLayout(layout); return true; } @@ -160,7 +167,7 @@ private static IEnumerable CreateHostServices( IEnumerable? hostServices, EditorPlayModeLoop playModeLoop ) { - List services = hostServices is null ? [] : new List(hostServices); + List services = hostServices is null ? [] : [.. hostServices]; services.Add(playModeLoop); return services; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs index dbd964784..acc402180 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Diagnostics; namespace Inno.Editor.Hosting; @@ -10,6 +9,11 @@ internal sealed class EditorProjectDiagnosticPublisher : IDisposable private string m_state = string.Empty; + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() => ResolvePersistence(); + internal bool hasPersistenceFailure => !string.IsNullOrEmpty(m_state); internal bool PublishPersistenceFailure(Exception exception) @@ -17,10 +21,10 @@ internal bool PublishPersistenceFailure(Exception exception) ArgumentNullException.ThrowIfNull(exception); string state = exception.ToString(); if (string.Equals(m_state, state, StringComparison.Ordinal)) + { return false; - Diagnostics.Set( - C_PERSISTENCE_GROUP, - Diagnostic.Error("EDITOR-PERSISTENCE", exception.Message)); + } + Diagnostics.Set(C_PERSISTENCE_GROUP, Diagnostic.Error("EDITOR-PERSISTENCE", exception.Message)); m_state = state; return true; } @@ -28,13 +32,10 @@ internal bool PublishPersistenceFailure(Exception exception) internal void ResolvePersistence() { if (string.IsNullOrEmpty(m_state)) + { return; + } Diagnostics.Clear(C_PERSISTENCE_GROUP); m_state = string.Empty; } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() => ResolvePersistence(); } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs index dfbd1fedc..13552a59d 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs @@ -1,18 +1,17 @@ -using Inno.Extensibility.Reload; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; - -using Inno.Extensibility.Modules; using Inno.Adapter.Presentation; -using Inno.Editor.Core; -using Inno.Editor.Rendering; using Inno.Core.Diagnostics; using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Editor.Rendering; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Rendering; -using Inno.Rendering.Runtime; using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; namespace Inno.Editor.Hosting; @@ -29,11 +28,11 @@ internal sealed class EditorRenderingHostService : private readonly IDisposable m_reloadRegistration; private readonly Dictionary m_viewports = new(StringComparer.Ordinal); private readonly Dictionary m_previews = []; - private readonly Dictionary m_previewsById = []; + private readonly Dictionary m_previewsByID = []; private readonly Dictionary m_renderedPreviews = new(StringComparer.Ordinal); private readonly object m_shaderValidationLock = new(); private readonly Dictionary m_shaderValidations = []; - private ulong m_nextPreviewId; + private ulong m_nextPreviewID; private bool m_disposed; internal EditorRenderingHostService( @@ -41,8 +40,10 @@ internal EditorRenderingHostService( IPresentationContext presentation, EditorReloadCoordinator reloads ) { - m_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); - m_presentation = presentation ?? throw new ArgumentNullException(nameof(presentation)); + ArgumentNullException.ThrowIfNull(runtime); + ArgumentNullException.ThrowIfNull(presentation); + m_runtime = runtime; + m_presentation = presentation; ArgumentNullException.ThrowIfNull(reloads); m_reloadRegistration = reloads.Register(this); m_runtime.SetPrimaryModelOutputEnabled(false); @@ -72,7 +73,7 @@ EditorReloadCoordinator reloads /// /// Requests validation of a compiled shader artifact for this device generation. /// - /// + /// /// The document id consumed by request; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -85,22 +86,24 @@ EditorReloadCoordinator reloads /// The validated editor shader artifact validation snapshot that represents the completed operation. /// public EditorShaderArtifactValidationSnapshot Request( - Guid documentId, + Guid documentID, ulong revision, RenderShaderArtifact artifact ) { ObjectDisposedException.ThrowIf(m_disposed, this); - if (documentId == Guid.Empty) - throw new ArgumentException("Shader validation requires a document identity.", nameof(documentId)); + if (documentID == Guid.Empty) + { + throw new ArgumentException("Shader validation requires a document identity.", nameof(documentID)); + } ArgumentNullException.ThrowIfNull(artifact); lock (m_shaderValidationLock) { - if (!m_shaderValidations.TryGetValue(documentId, out ShaderValidationState? state) + if (!m_shaderValidations.TryGetValue(documentID, out ShaderValidationState? state) || state.revision != revision - || !string.Equals(state.contentHash, artifact.contentHash, StringComparison.Ordinal)) - { - state = new ShaderValidationState(documentId, revision, artifact); - m_shaderValidations[documentId] = state; + || !string.Equals(state.contentHash, artifact.contentHash, StringComparison.Ordinal) + ) { + state = new ShaderValidationState(documentID, revision, artifact); + m_shaderValidations[documentID] = state; } return state.snapshot; } @@ -109,15 +112,71 @@ RenderShaderArtifact artifact /// /// Releases the caller-owned value lifetime and its retained resources. /// - /// + /// /// The document id consumed by release; ownership remains with the caller unless explicitly stated otherwise. /// - public void Release(Guid documentId) + public void Release(Guid documentID) { - if (documentId == Guid.Empty) + if (documentID == Guid.Empty) + { return; + } lock (m_shaderValidationLock) - m_shaderValidations.Remove(documentId); + { + m_shaderValidations.Remove(documentID); + } + } + + /// + /// Releases one cached preview registration. + /// + /// + /// Preview handle to release. + /// + /// + /// when the exact current-generation preview was released. + /// + public bool Release(EditorPreviewHandle handle) + { + if (!handle.isValid || handle.deviceGeneration != deviceGeneration + || !m_previewsByID.Remove(handle.value, out PreviewState? preview) + || preview.handle != handle + ) { + return false; + } + if (preview.viewportID is not null) + { + ReleaseRendered(preview.viewportID); + } + else + { + m_previews.Remove(preview.reference); + _ = m_presentation.UnregisterTexture(preview.presentationTexture); + } + return true; + } + + /// + /// Releases the caller-owned value lifetime and its retained resources. + /// + /// + /// The viewport id text validated by the release operation. + /// + public void Release(string viewportID) + { + ObjectDisposedException.ThrowIf(m_disposed, this); + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + if (m_renderedPreviews.Remove(viewportID, out PreviewState? preview)) + { + m_previewsByID.Remove(preview.handle.value); + } + m_runtime.resources.Release(new RenderPersistentResourceID(viewportID)); + if (!m_viewports.Remove(viewportID, out ViewportState? state)) + { + return; + } + Unregister(state); + m_runtime.targets.Release(state.target); } /// @@ -131,9 +190,11 @@ public void PrepareFrame(ulong frameIndex) _ = frameIndex; ShaderValidationState[] pending; lock (m_shaderValidationLock) + { pending = m_shaderValidations.Values .Where(static state => state.artifact is not null) .ToArray(); + } foreach (ShaderValidationState state in pending) { EditorShaderArtifactValidationSnapshot snapshot; @@ -148,14 +209,16 @@ public void PrepareFrame(ulong frameIndex) } catch (Exception failure) { - snapshot = new(EditorShaderCompilationState.Failed, - [new ShaderDiagnostic("SHADER_DEVICE_VALIDATION", DiagnosticSeverity.Error, failure.Message)]); + snapshot = new( + EditorShaderCompilationState.Failed, + [new ShaderDiagnostic("SHADER_DEVICE_VALIDATION", DiagnosticSeverity.Error, failure.Message)] + ); } lock (m_shaderValidationLock) { - if (m_shaderValidations.TryGetValue(state.documentId, out ShaderValidationState? current) - && ReferenceEquals(current, state)) - { + if (m_shaderValidations.TryGetValue(state.documentID, out ShaderValidationState? current) + && ReferenceEquals(current, state) + ) { state.snapshot = snapshot; state.artifact = null; } @@ -199,36 +262,42 @@ out EditorPreviewHandle handle EditorViewportOutput output = Submit(composition); if (!output.isReady) { - if (m_renderedPreviews.Remove(composition.viewportId, out PreviewState? stale)) - m_previewsById.Remove(stale.handle.value); + if (m_renderedPreviews.Remove(composition.viewportID, out PreviewState? stale)) + { + m_previewsByID.Remove(stale.handle.value); + } handle = default; return false; } - if (m_renderedPreviews.TryGetValue(composition.viewportId, out PreviewState? current) - && current.presentationTexture == output.texture && current.handle.deviceGeneration == deviceGeneration) - { + if (m_renderedPreviews.TryGetValue(composition.viewportID, out PreviewState? current) + && current.presentationTexture == output.texture && current.handle.deviceGeneration == deviceGeneration + ) { handle = current.handle; return true; } if (current is not null) - m_previewsById.Remove(current.handle.value); - ulong value = ++m_nextPreviewId; + { + m_previewsByID.Remove(current.handle.value); + } + ulong value = ++m_nextPreviewID; if (value == 0) - value = ++m_nextPreviewId; + { + value = ++m_nextPreviewID; + } handle = new(value, deviceGeneration, output.pixelWidth, output.pixelHeight); - var preview = new PreviewState(default, handle, default, output.texture, composition.viewportId); - m_renderedPreviews[composition.viewportId] = preview; - m_previewsById.Add(value, preview); + var preview = new PreviewState(default, handle, default, output.texture, composition.viewportID); + m_renderedPreviews[composition.viewportID] = preview; + m_previewsByID.Add(value, preview); return true; } /// /// Releases the caller-owned rendered lifetime and its retained resources. /// - /// + /// /// The viewport id text validated by the release rendered operation. /// - public void ReleaseRendered(string viewportId) => Release(viewportId); + public void ReleaseRendered(string viewportID) => Release(viewportID); /// /// Tries to resolve a standalone texture preview without blocking target compilation. @@ -247,11 +316,7 @@ public bool TryGetTexture( out EditorPreviewHandle handle ) { ArgumentNullException.ThrowIfNull(texture); - return TryGetTextureArtifact( - texture.GetTextureArtifactReference(), - texture.width, - texture.height, - out handle); + return TryGetTextureArtifact(texture.GetTextureArtifactReference(), texture.width, texture.height, out handle); } /// @@ -290,23 +355,26 @@ out EditorPreviewHandle handle if (m_previews.TryGetValue(texture, out PreviewState? existing)) { if (existing.residentTexture == resident && existing.handle.deviceGeneration == deviceGeneration - && existing.handle.pixelWidth == pixelWidth && existing.handle.pixelHeight == pixelHeight) - { + && existing.handle.pixelWidth == pixelWidth && existing.handle.pixelHeight == pixelHeight + ) { handle = existing.handle; return true; } Release(existing.handle); } - ulong value = ++m_nextPreviewId; + ulong value = ++m_nextPreviewID; if (value == 0) - value = ++m_nextPreviewId; + { + value = ++m_nextPreviewID; + } var preview = new PreviewState( texture, new EditorPreviewHandle(value, deviceGeneration, pixelWidth, pixelHeight), resident, - m_presentation.RegisterTexture(resident)); + m_presentation.RegisterTexture(resident) + ); m_previews.Add(texture, preview); - m_previewsById.Add(value, preview); + m_previewsByID.Add(value, preview); handle = preview.handle; return true; } @@ -326,56 +394,39 @@ Vector2 logicalSize ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!handle.isValid || handle.deviceGeneration != deviceGeneration - || !m_previewsById.TryGetValue(handle.value, out PreviewState? preview) - || preview.handle != handle) - { + || !m_previewsByID.TryGetValue(handle.value, out PreviewState? preview) + || preview.handle != handle + ) { throw new InvalidOperationException("The editor preview handle is stale or does not belong to this host."); } if (logicalSize.X <= 0f || logicalSize.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(logicalSize), "Preview size must be positive."); + } m_presentation.DrawImage(preview.presentationTexture, logicalSize); } /// - /// Releases one cached preview registration. + /// Renders the value presentation for the current editor frame. /// - /// - /// Preview handle to release. + /// + /// The import output writer that receives runtime data and dependency declarations. /// - /// - /// when the exact current-generation preview was released. - /// - public bool Release(EditorPreviewHandle handle) - { - if (!handle.isValid || handle.deviceGeneration != deviceGeneration - || !m_previewsById.Remove(handle.value, out PreviewState? preview) - || preview.handle != handle) - { - return false; - } - if (preview.viewportId is not null) - ReleaseRendered(preview.viewportId); - else + /// + /// The logical size consumed by draw; ownership remains with the caller unless explicitly stated otherwise. + /// + public void Draw( + EditorViewportOutput output, + Vector2 logicalSize + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + if (!output.isReady) { - m_previews.Remove(preview.reference); - _ = m_presentation.UnregisterTexture(preview.presentationTexture); + throw new InvalidOperationException( + $"Editor viewport '{output.viewportID}' has no completed render texture yet." + ); } - return true; - } - - /// - /// Releases every cached preview registration. - /// - void IEditorPreviewService.ReleaseAll() => ReleaseAllPreviews(); - - private void ReleaseAllPreviews() - { - foreach (string viewportId in new List(m_renderedPreviews.Keys)) - ReleaseRendered(viewportId); - foreach (PreviewState preview in m_previews.Values) - _ = m_presentation.UnregisterTexture(preview.presentationTexture); - m_previews.Clear(); - m_previewsById.Clear(); + m_presentation.DrawImage(output.texture, logicalSize); } /// @@ -392,10 +443,10 @@ public EditorViewportOutput Submit(EditorViewportComposition composition) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(composition); RenderTextureDescriptor descriptor = CreateDescriptor(composition); - if (!m_viewports.TryGetValue(composition.viewportId, out ViewportState? state)) + if (!m_viewports.TryGetValue(composition.viewportID, out ViewportState? state)) { - state = new ViewportState(new RenderTexture($"Editor/{composition.viewportId}", descriptor)); - m_viewports.Add(composition.viewportId, state); + state = new ViewportState(new RenderTexture($"Editor/{composition.viewportID}", descriptor)); + m_viewports.Add(composition.viewportID, state); } else if (!state.target.descriptor.Equals(descriptor)) { @@ -407,72 +458,42 @@ public EditorViewportOutput Submit(EditorViewportComposition composition) var viewport = new RenderViewport(0, 0, composition.pixelWidth, composition.pixelHeight); RenderRequest[] layers = composition.layers.Select(layer => new RenderRequest( - $"Editor:{composition.viewportId}:{layer.contributorId}", + $"Editor:{composition.viewportID}:{layer.contributorID}", target, viewport, layer.pipeline, layer.data, - layer.order)).ToArray(); + layer.order + )).ToArray(); if (layers.Length == 1) + { m_runtime.Submit(layers[0]); + } else - m_runtime.SubmitComposition($"Editor:{composition.viewportId}", target, - viewport, composition.targetFormat, layers); + { + m_runtime.SubmitComposition( + $"Editor:{composition.viewportID}", + target, + viewport, + composition.targetFormat, + layers + ); + } if (m_runtime.targets.TryGetTexture(state.target, out PersistentTextureHandle resident) - && resident != state.residentTexture) - { + && resident != state.residentTexture + ) { Unregister(state); state.presentationTexture = m_presentation.RegisterTexture(resident); state.residentTexture = resident; } return new EditorViewportOutput( - composition.viewportId, + composition.viewportID, state.presentationTexture, composition.pixelWidth, - composition.pixelHeight); - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The import output writer that receives runtime data and dependency declarations. - /// - /// - /// The logical size consumed by draw; ownership remains with the caller unless explicitly stated otherwise. - /// - public void Draw( - EditorViewportOutput output, - Vector2 logicalSize - ) { - ObjectDisposedException.ThrowIf(m_disposed, this); - if (!output.isReady) - { - throw new InvalidOperationException( - $"Editor viewport '{output.viewportId}' has no completed render texture yet."); - } - m_presentation.DrawImage(output.texture, logicalSize); - } - - /// - /// Releases the caller-owned value lifetime and its retained resources. - /// - /// - /// The viewport id text validated by the release operation. - /// - public void Release(string viewportId) - { - ObjectDisposedException.ThrowIf(m_disposed, this); - ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); - if (m_renderedPreviews.Remove(viewportId, out PreviewState? preview)) - m_previewsById.Remove(preview.handle.value); - m_runtime.resources.Release(new RenderPersistentResourceId(viewportId)); - if (!m_viewports.Remove(viewportId, out ViewportState? state)) - return; - Unregister(state); - m_runtime.targets.Release(state.target); + composition.pixelHeight + ); } /// @@ -481,16 +502,22 @@ public void Release(string viewportId) public void ReleaseAll() { if (m_disposed) + { return; + } foreach (ViewportState state in m_viewports.Values) { Unregister(state); m_runtime.targets.Release(state.target); } - foreach (string viewportId in m_viewports.Keys) - m_runtime.resources.Release(new RenderPersistentResourceId(viewportId)); + foreach (string viewportID in m_viewports.Keys) + { + m_runtime.resources.Release(new RenderPersistentResourceID(viewportID)); + } foreach (PreviewState preview in m_renderedPreviews.Values) - m_previewsById.Remove(preview.handle.value); + { + m_previewsByID.Remove(preview.handle.value); + } m_renderedPreviews.Clear(); m_viewports.Clear(); } @@ -501,41 +528,65 @@ public void ReleaseAll() public void Dispose() { if (m_disposed) + { return; + } _ = m_runtime.UnregisterContributor(this); m_reloadRegistration.Dispose(); ReleaseAll(); ReleaseAllPreviews(); lock (m_shaderValidationLock) + { m_shaderValidations.Clear(); + } m_disposed = true; } + /// + /// Releases every cached preview registration. + /// + void IEditorPreviewService.ReleaseAll() => ReleaseAllPreviews(); + IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) { ArgumentNullException.ThrowIfNull(context); return new RenderingReloadTransaction(this, m_runtime.BeginExtensionReload()); } - void IEditorReloadParticipant.RefreshDiagnostics() + void IEditorReloadParticipant.RefreshDiagnostics() {} + + private void ReleaseAllPreviews() { + foreach (string viewportID in new List(m_renderedPreviews.Keys)) + { + ReleaseRendered(viewportID); + } + foreach (PreviewState preview in m_previews.Values) + { + _ = m_presentation.UnregisterTexture(preview.presentationTexture); + } + m_previews.Clear(); + m_previewsByID.Clear(); } - private static RenderTextureDescriptor CreateDescriptor(EditorViewportComposition composition) - => new( - composition.pixelWidth, - composition.pixelHeight, - composition.targetFormat, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); - private void Unregister(ViewportState state) { if (state.presentationTexture.isValid) + { _ = m_presentation.UnregisterTexture(state.presentationTexture); + } state.presentationTexture = default; state.residentTexture = default; } + private static RenderTextureDescriptor CreateDescriptor(EditorViewportComposition composition) + => new( + composition.pixelWidth, + composition.pixelHeight, + composition.targetFormat, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); + private sealed class ViewportState(RenderTexture target) { internal RenderTexture target { get; } = target; @@ -556,7 +607,9 @@ public void PrepareForActivation() owner.ReleaseAll(); owner.ReleaseAllPreviews(); lock (owner.m_shaderValidationLock) + { owner.m_shaderValidations.Clear(); + } } /// @@ -581,9 +634,7 @@ public void Apply() /// /// Restores the state captured before the current transaction began. /// - public void RestorePreviousState() - { - } + public void RestorePreviousState() {} } private sealed record PreviewState( @@ -591,24 +642,24 @@ private sealed record PreviewState( EditorPreviewHandle handle, PersistentTextureHandle residentTexture, PresentationTextureHandle presentationTexture, - string? viewportId = null + string? viewportID = null ); private sealed class ShaderValidationState { internal ShaderValidationState( - Guid documentId, + Guid documentID, ulong revision, RenderShaderArtifact artifact ) { - this.documentId = documentId; + this.documentID = documentID; this.revision = revision; - contentHash = artifact.contentHash; + this.contentHash = artifact.contentHash; this.artifact = artifact; - snapshot = new(EditorShaderCompilationState.Compiling, []); + this.snapshot = new(EditorShaderCompilationState.Compiling, []); } - internal Guid documentId { get; set; } + internal Guid documentID { get; set; } internal ulong revision { get; } internal string contentHash { get; } internal RenderShaderArtifact? artifact { get; set; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs index dfd2e0adf..da1945a8b 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs @@ -12,7 +12,7 @@ internal static class EditorDefaultLayout private static string ReadDocument() { using Stream stream = typeof(EditorDefaultLayout).Assembly.GetManifestResourceStream(C_RESOURCE_NAME) - ?? throw new InvalidOperationException("The standard Editor layout resource is missing."); + ?? throw new InvalidOperationException("The standard Editor layout resource is missing."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs index 269c627d4..4f780be48 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs @@ -1,29 +1,31 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserChangeTracker(AssetBrowserModule assets) { private EditorContext? m_context; + internal void Attach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); m_context = context; - assets.edits.pipeline.Changed -= OnAssetsChanged; - assets.edits.pipeline.Changed += OnAssetsChanged; - assets.edits.pipeline.SourceMountsChanged -= OnSourceMountsChanged; - assets.edits.pipeline.SourceMountsChanged += OnSourceMountsChanged; + assets.edits.pipeline.changed -= OnAssetsChanged; + assets.edits.pipeline.changed += OnAssetsChanged; + assets.edits.pipeline.sourceMountsChanged -= OnSourceMountsChanged; + assets.edits.pipeline.sourceMountsChanged += OnSourceMountsChanged; } internal void Detach() { - assets.edits.pipeline.Changed -= OnAssetsChanged; - assets.edits.pipeline.SourceMountsChanged -= OnSourceMountsChanged; + assets.edits.pipeline.changed -= OnAssetsChanged; + assets.edits.pipeline.sourceMountsChanged -= OnSourceMountsChanged; m_context = null; } @@ -31,27 +33,40 @@ private void OnSourceMountsChanged() { EditorContext? context = m_context; if (context is null) + { return; + } string currentDirectory = FileBrowserUtility.NormalizePath(assets.browser.currentDirectory); - if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(currentDirectory), out AssetFileEntry current) || !current.isDirectory) + if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(currentDirectory), out AssetFileEntry current) + || !current.isDirectory + ) { assets.browser.SetCurrentDirectory(string.Empty); + } string selectedPath = FileBrowserUtility.NormalizePath(assets.browser.GetSelectedPath(context)); if (!string.IsNullOrEmpty(selectedPath) && !assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(selectedPath), out _)) + { assets.browser.Select(context, null); + } } private void OnAssetsChanged(AssetChangeSet changes) { EditorContext? context = m_context; if (context is null) + { return; + } for (int i = 0; i < changes.changes.Count; i++) { AssetChange change = changes.changes[i]; if (change.kind == AssetChangeKind.Moved) + { ApplyMove(context, change.previousAssetPath?.ToString() ?? string.Empty, change.assetPath.ToString()); + } else if (change.kind is AssetChangeKind.Missing or AssetChangeKind.Removed) + { ApplyRemoval(context, change.assetPath.ToString()); + } } } @@ -63,7 +78,9 @@ string newPath oldPath = Normalize(oldPath); newPath = Normalize(newPath); if (string.IsNullOrEmpty(oldPath) || string.IsNullOrEmpty(newPath)) + { return; + } string currentDirectory = Normalize(assets.browser.currentDirectory); if (IsSameOrDescendant(currentDirectory, oldPath)) { @@ -73,7 +90,9 @@ string newPath string selectedPath = Normalize(assets.browser.GetSelectedPath(context)); if (!IsSameOrDescendant(selectedPath, oldPath)) + { return; + } string selectedSuffix = selectedPath.Length == oldPath.Length ? string.Empty : selectedPath[oldPath.Length..].TrimStart('/'); assets.browser.Select(context, Combine(newPath, selectedSuffix)); } @@ -84,40 +103,44 @@ string removedPath ) { removedPath = Normalize(removedPath); if (string.IsNullOrEmpty(removedPath)) + { return; + } string selectedPath = Normalize(assets.browser.GetSelectedPath(context)); if (IsSameOrDescendant(selectedPath, removedPath)) + { assets.browser.Select(context, null); + } string currentDirectory = Normalize(assets.browser.currentDirectory); if (!IsSameOrDescendant(currentDirectory, removedPath)) + { return; + } string fallback = FileBrowserUtility.GetParentDirectory(removedPath); - while (!string.Equals( - fallback, - FileBrowserUtility.GetParentDirectory(fallback), - StringComparison.Ordinal - ) - && (!assets.edits.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(fallback), - out var entry - ) - || !entry.isDirectory)) - { + while (!string.Equals(fallback, FileBrowserUtility.GetParentDirectory(fallback), StringComparison.Ordinal) + && (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out AssetFileEntry entry) + || !entry.isDirectory) + ) { fallback = FileBrowserUtility.GetParentDirectory(fallback); } if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out AssetFileEntry available) || !available.isDirectory) + { fallback = string.Empty; + } assets.browser.SetCurrentDirectory(fallback); } private static bool IsSameOrDescendant( string path, string ancestor - ) => string.Equals(path, ancestor, StringComparison.OrdinalIgnoreCase) || path.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + ) => string.Equals(path, ancestor, StringComparison.OrdinalIgnoreCase) + || path.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + private static string Combine( string left, string right ) => string.IsNullOrEmpty(right) ? left : $"{left}/{right}"; + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs index 05b93ec91..9bf459a1d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs @@ -1,19 +1,22 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserContextMenu( AssetBrowserModule assets, FileBrowserRename rename -) -{ +) { internal void DrawEntry( EditorContext context, string id, @@ -21,13 +24,23 @@ internal void DrawEntry( FileBrowserPresentation presentation ) { if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry)) + { return; - if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !assets.edits.interactions.selection.Contains(entry)) + } + if (Gui.IsItemClicked(ImGuiMouseButton.Right) && !assets.edits.interactions.selection.Contains(entry)) + { assets.edits.interactions.SetSelection(entry); + } string creationDirectory = entry.isDirectory ? entry.assetPath.ToString() : GetParentDirectory(entry.assetPath.ToString()); - bool isOpen = EditorUI.current.menus.ContextMenu(id, CreateDirectoryInteraction(creationDirectory), assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry)); + bool isOpen = EditorUI.current.menus.ContextMenu( + id, + CreateDirectoryInteraction(creationDirectory), + assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, entry) + ); if (isOpen) + { rename.MarkInteraction(presentation); + } } internal void DrawDirectory( @@ -37,10 +50,14 @@ internal void DrawDirectory( FileBrowserPresentation presentation ) { if (IsReadOnlySource(assets.edits.pipeline, relativePath)) + { return; + } bool isOpen = EditorUI.current.menus.ContextMenu(id, CreateDirectoryInteraction(relativePath)); if (isOpen) + { rename.MarkInteraction(presentation); + } } internal void DrawBackground( @@ -49,14 +66,16 @@ internal void DrawBackground( FileBrowserPresentation presentation ) { if (IsReadOnlyLocation(assets.edits.pipeline, assets.browser)) + { return; + } bool isOpen = EditorUI.current.menus.WindowContextMenu(id, CreateDirectoryInteraction(assets.browser.currentDirectory)); if (isOpen) + { rename.MarkInteraction(presentation); + } } - private Inno.Editor.Interactions.EditorInteraction CreateDirectoryInteraction(string relativePath) => assets.edits.interactions.For( - FileBrowserInteractionIds.C_AREA, - NormalizePath(relativePath) - ); + private EditorInteraction CreateDirectoryInteraction(string relativePath) + => assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, NormalizePath(relativePath)); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs index af616c7e4..33e1bf7fc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs @@ -1,49 +1,37 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; -using System.Linq; using System.Diagnostics.CodeAnalysis; -using Inno.Core.Identity; +using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets.ImGui; namespace Inno.Editor.Panel.FileBrowser; -internal enum FileBrowserEntryTypeFilter -{ - All, - FoldersOnly, - FilesOnly -} - -internal enum FileBrowserEntryScopeFilter -{ - CurrentOnly, - Recursive -} -internal readonly record struct FileBrowserDisplayEntry( - RuntimeIdentity identity, - AssetPath path, - string displayName, - string extension, - bool isDirectory, - bool isPluginRoot = false -); internal sealed class FileBrowserData(AssetBrowserModule assets) { private ViewInput? m_input; - private IReadOnlyList m_entries = Array.Empty(); - internal IReadOnlyList visibleSelection { get; private set; } = Array.Empty(); + private IReadOnlyList m_entries = []; + internal IReadOnlyList visibleSelection { get; private set; } = []; internal IReadOnlyList CollectVisibleEntries( FileBrowserEntryTypeFilter typeFilter, FileBrowserEntryScopeFilter scopeFilter, string searchFilter ) { - var input = new ViewInput(assets.edits.pipeline.revision, assets.browser.root, assets.browser.currentDirectory, typeFilter, scopeFilter, searchFilter); + var input = new ViewInput( + assets.edits.pipeline.revision, + assets.browser.root, + assets.browser.currentDirectory, + typeFilter, + scopeFilter, + searchFilter + ); if (m_input == input) + { return m_entries; + } List entries = []; if (assets.browser.root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(assets.browser.currentDirectory)) { @@ -53,10 +41,14 @@ string searchFilter { IReadOnlyList children = GetVisibleChildren(assets.browser.currentDirectory); for (int i = 0; i < children.Count; i++) + { entries.Add(Describe(children[i], children[i].name)); + } } else + { CollectEntriesRecursive(assets.browser.currentDirectory, entries); + } ApplyTypeFilter(entries, typeFilter); ApplySearchFilter(entries, searchFilter); entries.Sort(static ( @@ -66,7 +58,9 @@ string searchFilter { int byName = string.Compare(left.displayName, right.displayName, StringComparison.OrdinalIgnoreCase); if (byName != 0) + { return byName; + } int byExtension = string.Compare(left.extension, right.extension, StringComparison.OrdinalIgnoreCase); return byExtension != 0 ? byExtension : string.CompareOrdinal(left.path.ToString(), right.path.ToString()); }); @@ -81,8 +75,8 @@ internal bool TryResolve( [NotNullWhen(true)] out AssetFileEntry? entry ) { if (assets.edits.interactions.TryResolveIdentity(item.identity, out IdentityObject? target) - && target is AssetFileEntry resolved && resolved.assetPath == item.path) - { + && target is AssetFileEntry resolved && resolved.assetPath == item.path + ) { entry = resolved; return true; } @@ -90,37 +84,41 @@ internal bool TryResolve( return false; } - private static FileBrowserDisplayEntry Describe( - AssetFileEntry entry, - string label, - bool pluginRoot = false - ) => new(entry.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset requires a registered identity."), - entry.assetPath, label, entry.extension, entry.isDirectory, pluginRoot); - - private static void ApplyTypeFilter( - List entries, - FileBrowserEntryTypeFilter typeFilter - ) { - switch (typeFilter) + internal List SortTreeEntries(IReadOnlyList entries) + { + List sorted = [.. entries]; + sorted.Sort(static ( + left, + right + ) => { - case FileBrowserEntryTypeFilter.FoldersOnly: - entries.RemoveAll(static item => !item.isDirectory); - break; - case FileBrowserEntryTypeFilter.FilesOnly: - entries.RemoveAll(static item => item.isDirectory); - break; - } + if (left.isDirectory != right.isDirectory) + { + return left.isDirectory ? -1 : 1; + } + return string.Compare(left.name, right.name, StringComparison.OrdinalIgnoreCase); + }); + return sorted; } - private static void ApplySearchFilter( - List entries, - string searchFilter - ) { - string filter = searchFilter.Trim(); - if (!string.IsNullOrEmpty(filter)) + internal IReadOnlyList GetVisibleChildren(string relativePath) + { + AssetSourceID source = AssetPath.Parse(relativePath).source; + IReadOnlyList children = assets.edits.pipeline.GetFileSystemChildren(AssetPath.Parse(relativePath)); + if (children.Count == 0) { - entries.RemoveAll(item => !item.displayName.Contains(filter, StringComparison.OrdinalIgnoreCase)); + return children; + } + List isolated = []; + for (int i = 0; i < children.Count; i++) + { + if (children[i].source == source) + { + isolated.Add(children[i]); + } } + + return isolated; } private void CollectPluginRoots( @@ -136,10 +134,14 @@ FileBrowserEntryScopeFilter scopeFilter AssetSourceMount mount = mounts[i]; var rootPath = new AssetPath(mount.id, string.Empty); if (!assets.edits.pipeline.TryGetFileSystemEntry(rootPath, out AssetFileEntry root)) + { continue; + } entries.Add(Describe(root, mount.id.value, pluginRoot: true)); if (scopeFilter == FileBrowserEntryScopeFilter.Recursive) + { CollectEntriesRecursive(root.assetPath.ToString(), entries); + } } } @@ -155,40 +157,50 @@ List entries { entries.Add(Describe(child, child.name)); if (child.isDirectory) + { pending.Push(child.assetPath.ToString()); + } } } } - internal List SortTreeEntries(IReadOnlyList entries) - { - List sorted = new(entries); - sorted.Sort(static ( - left, - right - ) => + private static FileBrowserDisplayEntry Describe( + AssetFileEntry entry, + string label, + bool pluginRoot = false + ) => new( + entry.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset requires a registered identity."), + entry.assetPath, + label, + entry.extension, + entry.isDirectory, + pluginRoot + ); + + private static void ApplyTypeFilter( + List entries, + FileBrowserEntryTypeFilter typeFilter + ) { + switch (typeFilter) { - if (left.isDirectory != right.isDirectory) - return left.isDirectory ? -1 : 1; - return string.Compare(left.name, right.name, StringComparison.OrdinalIgnoreCase); - }); - return sorted; + case FileBrowserEntryTypeFilter.FoldersOnly: + entries.RemoveAll(static item => !item.isDirectory); + break; + case FileBrowserEntryTypeFilter.FilesOnly: + entries.RemoveAll(static item => item.isDirectory); + break; + } } - internal IReadOnlyList GetVisibleChildren(string relativePath) - { - AssetSourceId source = AssetPath.Parse(relativePath).source; - IReadOnlyList children = assets.edits.pipeline.GetFileSystemChildren(AssetPath.Parse(relativePath)); - if (children.Count == 0) - return children; - List isolated = []; - for (int i = 0; i < children.Count; i++) + private static void ApplySearchFilter( + List entries, + string searchFilter + ) { + string filter = searchFilter.Trim(); + if (!string.IsNullOrEmpty(filter)) { - if (children[i].source == source) - isolated.Add(children[i]); + entries.RemoveAll(item => !item.displayName.Contains(filter, StringComparison.OrdinalIgnoreCase)); } - - return isolated; } private readonly record struct ViewInput( @@ -200,3 +212,25 @@ private readonly record struct ViewInput( string search ); } + +internal enum FileBrowserEntryTypeFilter +{ + All, + FoldersOnly, + FilesOnly +} + +internal enum FileBrowserEntryScopeFilter +{ + CurrentOnly, + Recursive +} + +internal readonly record struct FileBrowserDisplayEntry( + RuntimeIdentity identity, + AssetPath path, + string displayName, + string extension, + bool isDirectory, + bool isPluginRoot = false +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs index f1236289b..ec4ef41aa 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs @@ -1,14 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; +using System.Numerics; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + /// /// Binds managed File Browser drag sessions to native entry and directory items. /// @@ -30,19 +33,18 @@ internal void DrawAssetSource( EditorContext context, AssetFileEntry entry ) { - if (!assets.edits.TryCreateContext( - context, - entry.assetPath.ToString(), - out AssetEditorContext? assetContext - ) + if (!assets.edits.TryCreateContext(context, entry.assetPath.ToString(), out AssetEditorContext? assetContext) || assetContext is null - || !assets.edits.TryCreateDragData( - assetContext, - out EditorDragData? data - ) - || data is null) + || !assets.edits.TryCreateDragData(assetContext, out EditorDragData? data) + || data is null + ) { return; - _ = EditorDragDropRenderer.Source(assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry), data, () => Ui.Text(data.label)); + } + _ = EditorDragDropRenderer.Source( + assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, entry), + data, + () => Gui.Text(data.label) + ); } /// @@ -59,12 +61,18 @@ internal void DrawDirectoryTarget( string relativePath ) { if (FileBrowserUtility.IsReadOnlySource(assets.edits.pipeline, relativePath)) + { return; - System.Numerics.Vector2 minimum = Ui.GetItemMinimum(); - System.Numerics.Vector2 maximum = Ui.GetItemMaximum(); - EditorDropWidgetResult result = EditorDragDropRenderer.Target(assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, relativePath)); + } + Vector2 minimum = Gui.GetItemMinimum(); + Vector2 maximum = Gui.GetItemMaximum(); + EditorDropWidgetResult result = EditorDragDropRenderer.Target( + assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, relativePath) + ); if (!result.isPreviewing || !result.status.canDrop) + { return; + } EditorUI.current.widgets.DropTargetHighlight(minimum, maximum); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs index fb76db4da..7bcbf1dfc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs @@ -1,19 +1,21 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserNavigation(AssetBrowserModule assets) { private readonly Stack m_backHistory = []; private readonly Stack m_forwardHistory = []; - private BrowserLocation m_historyCurrent = BrowserLocation.AssetsRoot; + private BrowserLocation m_historyCurrent = BrowserLocation.assetsRoot; internal bool canGoBack => m_backHistory.Count > 0; internal bool canGoForward => m_forwardHistory.Count > 0; @@ -23,15 +25,21 @@ internal void NavigateTo( string? selectedPathAfterNavigation = null ) { directory = NormalizePath(directory); - AssetBrowserRoot root = string.IsNullOrEmpty(directory) ? assets.browser.root : AssetPath.Parse(directory).source == AssetSourceId.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; + AssetBrowserRoot root = string.IsNullOrEmpty(directory) + ? assets.browser.root + : AssetPath.Parse(directory).source == AssetSourceID.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; var target = new BrowserLocation(root, directory); - if (CurrentLocation == target) + if (currentLocation == target) + { return; - m_backHistory.Push(CurrentLocation); + } + m_backHistory.Push(currentLocation); m_forwardHistory.Clear(); ApplyLocation(context, target); if (selectedPathAfterNavigation is not null) + { assets.browser.Select(context, selectedPathAfterNavigation); + } } internal void NavigateToRoot( @@ -39,9 +47,11 @@ internal void NavigateToRoot( AssetBrowserRoot root ) { var target = new BrowserLocation(root, string.Empty); - if (CurrentLocation == target) + if (currentLocation == target) + { return; - m_backHistory.Push(CurrentLocation); + } + m_backHistory.Push(currentLocation); m_forwardHistory.Clear(); ApplyLocation(context, target); } @@ -51,7 +61,9 @@ internal void SwitchRoot( AssetBrowserRoot root ) { if (assets.browser.root == root) + { return; + } m_backHistory.Clear(); m_forwardHistory.Clear(); ApplyLocation(context, new BrowserLocation(root, assets.browser.GetDirectory(root))); @@ -60,28 +72,23 @@ AssetBrowserRoot root internal void GoBack(EditorContext context) { if (m_backHistory.Count == 0) + { return; - m_forwardHistory.Push(CurrentLocation); + } + m_forwardHistory.Push(currentLocation); ApplyLocation(context, m_backHistory.Pop()); } internal void GoForward(EditorContext context) { if (m_forwardHistory.Count == 0) + { return; - m_backHistory.Push(CurrentLocation); + } + m_backHistory.Push(currentLocation); ApplyLocation(context, m_forwardHistory.Pop()); } - private void ApplyLocation( - EditorContext context, - BrowserLocation location - ) { - m_historyCurrent = location; - assets.browser.SetLocation(location.root, location.directory); - assets.browser.Select(context, string.Empty); - } - internal void OpenEntry( EditorContext context, AssetFileEntry entry, @@ -94,7 +101,7 @@ FileBrowserTree tree return; } - _ = assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry).Execute(FileBrowserInteractionIds.C_OPEN); + _ = assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, entry).Execute(FileBrowserInteractionIDs.C_OPEN); } internal void SyncExternalDirectoryChange( @@ -103,19 +110,29 @@ string directory ) { var location = new BrowserLocation(root, NormalizePath(directory)); if (m_historyCurrent == location) + { return; + } m_historyCurrent = location; m_backHistory.Clear(); m_forwardHistory.Clear(); } - private BrowserLocation CurrentLocation => new(assets.browser.root, NormalizePath(assets.browser.currentDirectory)); + private BrowserLocation currentLocation => new(assets.browser.root, NormalizePath(assets.browser.currentDirectory)); + + private void ApplyLocation( + EditorContext context, + BrowserLocation location + ) { + m_historyCurrent = location; + assets.browser.SetLocation(location.root, location.directory); + assets.browser.Select(context, string.Empty); + } private readonly record struct BrowserLocation( AssetBrowserRoot root, string directory - ) - { - internal static BrowserLocation AssetsRoot { get; } = new(AssetBrowserRoot.Assets, string.Empty); + ) { + internal static BrowserLocation assetsRoot { get; } = new(AssetBrowserRoot.Assets, string.Empty); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs index d766dd373..65f8b2b06 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,23 +5,31 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawEntryFilterCombo() { if (!EditorUI.current.widgets.BeginBoundedCombo("##AssetEntryFilter", "Filter", ImGuiComboFlags.WidthFitPreview)) + { return; + } DrawEntryTypeFilterOption("All", FileBrowserEntryTypeFilter.All); DrawEntryTypeFilterOption("Folders", FileBrowserEntryTypeFilter.FoldersOnly); DrawEntryTypeFilterOption("Files", FileBrowserEntryTypeFilter.FilesOnly); - Ui.Separator(); + Gui.Separator(); DrawEntryScopeFilterOption("Current", FileBrowserEntryScopeFilter.CurrentOnly); DrawEntryScopeFilterOption("Recursive", FileBrowserEntryScopeFilter.Recursive); EditorUI.current.widgets.EndBoundedCombo(); @@ -35,12 +40,16 @@ private void DrawEntryTypeFilterOption( FileBrowserEntryTypeFilter filter ) { bool selected = m_entryTypeFilter == filter; - if (Ui.Checkbox(label, ref selected)) + if (Gui.Checkbox(label, ref selected)) { if (selected) + { m_entryTypeFilter = filter; + } else if (m_entryTypeFilter == filter) + { m_entryTypeFilter = FileBrowserEntryTypeFilter.All; + } } } @@ -49,17 +58,19 @@ private void DrawEntryScopeFilterOption( FileBrowserEntryScopeFilter filter ) { bool selected = m_entryScopeFilter == filter; - if (Ui.Checkbox(label, ref selected)) + if (Gui.Checkbox(label, ref selected)) { if (selected) + { m_entryScopeFilter = filter; + } else if (m_entryScopeFilter == filter) + { m_entryScopeFilter = FileBrowserEntryScopeFilter.CurrentOnly; + } } } private void DrawSearchInput() - { - _ = EditorUI.current.widgets.SearchInput("AssetSearch", ImGuiIcon.MagnifyingGlass, ref m_filter, (nuint)C_SEARCH_BUFFER_SIZE); - } + => _ = EditorUI.current.widgets.SearchInput("AssetSearch", ImGuiIcon.C_MAGNIFYING_GLASS, ref m_filter, (nuint)C_SEARCH_BUFFER_SIZE); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs index a83e65438..c30cdb037 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,31 +5,39 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawGridRegion( EditorContext context, IReadOnlyList entries ) { - EditorUiLayout style = Ui.GetLayout(); - float sliderHeight = Ui.GetFrameHeight() + style.windowPadding.Y * 2f + style.itemSpacing.Y; - bool entriesVisible = Ui.BeginChild("##EntriesScroll", new Vector2(0f, -sliderHeight), ImGuiChildFlags.None); + EditorUILayout style = Gui.GetLayout(); + float sliderHeight = Gui.GetFrameHeight() + style.windowPadding.Y * 2f + style.itemSpacing.Y; + bool entriesVisible = Gui.BeginChild("##EntriesScroll", new Vector2(0f, -sliderHeight), ImGuiChildFlags.None); try { if (entriesVisible) { - if (Ui.IsWindowFocused()) + if (Gui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.Grid); + } float cellSize = GetGridCellSize(); - int columns = Math.Max(1, (int)(Ui.GetContentRegionAvailable().X / cellSize)); - int rows = Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / cellSize)); + int columns = Math.Max(1, (int)(Gui.GetContentRegionAvailable().X / cellSize)); + int rows = Math.Max(1, (int)(Gui.GetContentRegionAvailable().Y / cellSize)); HandleEntryKeyboardNavigation(columns * rows); DrawGrid(context, entries); HandleBackgroundSelection(context); @@ -41,7 +46,7 @@ IReadOnlyList entries } finally { - Ui.EndChild(); + Gui.EndChild(); } DrawGridScaleSlider(); @@ -49,7 +54,7 @@ IReadOnlyList entries private void HandleBackgroundSelection(EditorContext context) { - if (!Ui.IsWindowHovered() || Ui.IsAnyItemHovered() || !Ui.IsMouseReleased(ImGuiMouseButton.Left)) + if (!Gui.IsWindowHovered() || Gui.IsAnyItemHovered() || !Gui.IsMouseReleased(ImGuiMouseButton.Left)) { return; } @@ -59,17 +64,17 @@ private void HandleBackgroundSelection(EditorContext context) private void DrawGridScaleSlider() { - m_gridScale = Math.Clamp(m_gridScale, CurrentBrowserStyle.gridMinimumScale, CurrentBrowserStyle.gridMaximumScale); + m_gridScale = Math.Clamp(m_gridScale, currentBrowserStyle.gridMinimumScale, currentBrowserStyle.gridMaximumScale); DrawFooterTopSplitter(); - Vector2 cursor = Ui.GetCursorPosition(); - float labelOffsetY = MathF.Max(0f, (Ui.GetFrameHeight() - Ui.GetTextLineHeight()) * 0.5f); - Ui.SetCursorPosY(cursor.Y + labelOffsetY); - Ui.Text("Scale"); - Ui.SameLine(0f, -1f); - Ui.SetCursorPosY(cursor.Y); - Ui.SetNextItemWidth(-1f); - _ = Ui.SliderFloat("##GridScale", ref m_gridScale, CurrentBrowserStyle.gridMinimumScale, CurrentBrowserStyle.gridMaximumScale); - m_gridScale = Math.Clamp(m_gridScale, CurrentBrowserStyle.gridMinimumScale, CurrentBrowserStyle.gridMaximumScale); + Vector2 cursor = Gui.GetCursorPosition(); + float labelOffsetY = MathF.Max(0f, (Gui.GetFrameHeight() - Gui.GetTextLineHeight()) * 0.5f); + Gui.SetCursorPosY(cursor.Y + labelOffsetY); + Gui.Text("Scale"); + Gui.SameLine(0f, -1f); + Gui.SetCursorPosY(cursor.Y); + Gui.SetNextItemWidth(-1f); + _ = Gui.SliderFloat("##GridScale", ref m_gridScale, currentBrowserStyle.gridMinimumScale, currentBrowserStyle.gridMaximumScale); + m_gridScale = Math.Clamp(m_gridScale, currentBrowserStyle.gridMinimumScale, currentBrowserStyle.gridMaximumScale); } private void DrawGrid( @@ -77,17 +82,19 @@ private void DrawGrid( IReadOnlyList entries ) { float cellSize = GetGridCellSize(); - float available = MathF.Max(cellSize, Ui.GetContentRegionAvailable().X); + float available = MathF.Max(cellSize, Gui.GetContentRegionAvailable().X); int columns = Math.Max(1, (int)(available / cellSize)); - bool tableStarted = Ui.BeginTable( + bool tableStarted = Gui.BeginTable( "##FileBrowserGrid", columns, (ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings), - default(System.Numerics.Vector2), + default, 0f ); if (!tableStarted) + { return; + } try { int rowCount = (entries.Count + columns - 1) / columns; @@ -101,13 +108,15 @@ IReadOnlyList entries { for (int row = start; row < end; row++) { - Ui.TableNextRow(); + Gui.TableNextRow(); for (int column = 0; column < state.columns; column++) { int index = row * state.columns + column; if (index >= state.entries.Count) + { break; - _ = Ui.TableSetColumnIndex(column); + } + _ = Gui.TableSetColumnIndex(column); state.panel.DrawGridItem(state.context, state.entries[index]); } } @@ -115,7 +124,7 @@ IReadOnlyList entries } finally { - Ui.EndTable(); + Gui.EndTable(); } } @@ -126,31 +135,33 @@ FileBrowserDisplayEntry item float cellSize = GetGridCellSize(); if (!m_data.TryResolve(item, out AssetFileEntry? entry)) { - Ui.Dummy(new(cellSize, cellSize)); + Gui.Dummy(new Vector2(cellSize, cellSize)); return; } string icon = m_assets.GetIcon(entry); string name = item.isPluginRoot ? item.displayName : entry.name; bool selected = m_assets.browser.IsSelected(context, entry); bool editing = m_rename.IsEditing(context, entry.assetPath.ToString(), FileBrowserPresentation.Grid); - Vector2 itemSize = new(cellSize - CurrentBrowserStyle.gridCellPadding, cellSize - CurrentBrowserStyle.gridCellPadding); - Ui.PushId(entry.assetPath.ToString()); - Ui.PushStyleColor(ImGuiCol.Header, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.HeaderHovered, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.HeaderActive, EditorPalette.transparent); + var itemSize = new Vector2(cellSize - currentBrowserStyle.gridCellPadding, cellSize - currentBrowserStyle.gridCellPadding); + Gui.PushID(entry.assetPath.ToString()); + Gui.PushStyleColor(ImGuiCol.Header, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.HeaderHovered, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.HeaderActive, EditorPalette.transparent); try { ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.AllowDoubleClick; if (editing) + { selectableFlags |= ImGuiSelectableFlags.AllowOverlap; + } RequestEntryKeyboardFocus(entry); - bool activated = Ui.Selectable("##GridItem", selected, selectableFlags, itemSize); - bool itemHovered = Ui.IsItemHovered(); - bool itemActive = Ui.IsItemActive(); - Vector2 itemMin = Ui.GetItemMinimum(); - Vector2 itemMax = Ui.GetItemMaximum(); - Vector2 layoutCursor = Ui.GetCursorScreenPosition(); - bool doubleClicked = itemHovered && Ui.IsMouseDoubleClicked(ImGuiMouseButton.Left); + bool activated = Gui.Selectable("##GridItem", selected, selectableFlags, itemSize); + bool itemHovered = Gui.IsItemHovered(); + bool itemActive = Gui.IsItemActive(); + Vector2 itemMin = Gui.GetItemMinimum(); + Vector2 itemMax = Gui.GetItemMaximum(); + Vector2 layoutCursor = Gui.GetCursorScreenPosition(); + bool doubleClicked = itemHovered && Gui.IsMouseDoubleClicked(ImGuiMouseButton.Left); if (activated && !m_keyboardHandled) { HandleEntryActivation(context, entry, FileBrowserPresentation.Grid, doubleClicked); @@ -161,31 +172,49 @@ FileBrowserDisplayEntry item m_dragDrop.DrawAssetSource(context, entry); m_contextMenu.DrawEntry(context, "##asset_grid_context", entry.assetPath.ToString(), FileBrowserPresentation.Grid); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, entry.assetPath.ToString()); + } } DrawGridItemVisual(icon, name, selected, m_gridScale, itemHovered, itemActive, itemMin, itemMax, drawName: !editing); if (editing) { - float width = MathF.Max(1f, itemMax.X - itemMin.X - CurrentBrowserStyle.gridLabelHorizontalPadding); - float lineHeight = Ui.GetTextLineHeight(); - float lineAdvance = MathF.Max(1f, lineHeight + CurrentBrowserStyle.gridLabelLineSpacing); + float width = MathF.Max(1f, itemMax.X - itemMin.X - currentBrowserStyle.gridLabelHorizontalPadding); + float lineHeight = Gui.GetTextLineHeight(); + float lineAdvance = MathF.Max(1f, lineHeight + currentBrowserStyle.gridLabelLineSpacing); float labelAreaHeight = lineHeight + lineAdvance * (C_GRID_LABEL_LINE_COUNT - 1); - float labelAreaTop = itemMax.Y - CurrentBrowserStyle.gridLabelBottomPadding - labelAreaHeight; + float labelAreaTop = itemMax.Y - currentBrowserStyle.gridLabelBottomPadding - labelAreaHeight; float y = labelAreaTop + (labelAreaHeight - lineHeight) * 0.5f; - Ui.SetCursorScreenPosition(new Vector2(itemMin.X + CurrentBrowserStyle.gridLabelHorizontalPadding * 0.5f, y)); - m_rename.Draw(context, $"grid_{entry.assetPath.ToString()}", entry.assetPath.ToString(), FileBrowserPresentation.Grid, width, lineHeight); - Ui.SetCursorScreenPosition(layoutCursor); - Ui.Dummy(Vector2.Zero); + Gui.SetCursorScreenPosition(new Vector2(itemMin.X + currentBrowserStyle.gridLabelHorizontalPadding * 0.5f, y)); + m_rename.Draw( + context, + $"grid_{entry.assetPath.ToString()}", + entry.assetPath.ToString(), + FileBrowserPresentation.Grid, + width, + lineHeight + ); + Gui.SetCursorScreenPosition(layoutCursor); + Gui.Dummy(Vector2.Zero); } } finally { - Ui.PopStyleColor(3); - Ui.PopId(); + Gui.PopStyleColor(3); + Gui.PopID(); } } + private float GetGridCellSize() + { + float fontSize = Gui.GetFontSize(); + return MathF.Max( + currentBrowserStyle.gridMinimumCellSize, + fontSize * (m_gridScale + currentBrowserStyle.gridScaleBias) + currentBrowserStyle.gridFixedCellPadding + ); + } + private static void DrawGridItemVisual( string icon, string name, @@ -200,25 +229,33 @@ bool drawName Vector2 size = max - min; Vector4 bg = selected ? EditorPalette.contentAccent : EditorPalette.collectionHeader; if (active) + { bg = EditorPalette.GetActive(bg); + } else if (hovered) + { bg = EditorPalette.GetHovered(bg); - uint bgColor = Ui.ToPackedColor(bg); - Ui.DrawFilledRectangle(min, max, bgColor, CurrentBrowserStyle.frameRounding); - float fontSize = Ui.GetFontSize(); + } + uint bgColor = Gui.ToPackedColor(bg); + Gui.DrawFilledRectangle(min, max, bgColor, currentBrowserStyle.frameRounding); + float fontSize = Gui.GetFontSize(); float iconFontSize = fontSize * scale; Vector4 iconBounds = EditorUI.current.widgets.GetGlyphVisualBounds(iconFontSize, icon); - Vector2 iconSize = new(iconBounds.Z - iconBounds.X, iconBounds.W - iconBounds.Y); - string[] nameLines = FitTextToLines(name, MathF.Max(1f, size.X - CurrentBrowserStyle.gridLabelHorizontalPadding), C_GRID_LABEL_LINE_COUNT); - float lineHeight = Ui.GetTextLineHeight(); - float lineAdvance = MathF.Max(1f, lineHeight + CurrentBrowserStyle.gridLabelLineSpacing); + var iconSize = new Vector2(iconBounds.Z - iconBounds.X, iconBounds.W - iconBounds.Y); + string[] nameLines = FitTextToLines( + name, + MathF.Max(1f, size.X - currentBrowserStyle.gridLabelHorizontalPadding), + C_GRID_LABEL_LINE_COUNT + ); + float lineHeight = Gui.GetTextLineHeight(); + float lineAdvance = MathF.Max(1f, lineHeight + currentBrowserStyle.gridLabelLineSpacing); float labelAreaHeight = lineHeight + lineAdvance * (C_GRID_LABEL_LINE_COUNT - 1); - float labelAreaTop = max.Y - CurrentBrowserStyle.gridLabelBottomPadding - labelAreaHeight; + float labelAreaTop = max.Y - currentBrowserStyle.gridLabelBottomPadding - labelAreaHeight; float labelHeight = lineHeight + lineAdvance * Math.Max(0, nameLines.Length - 1); float labelY = labelAreaTop + (labelAreaHeight - labelHeight) * 0.5f; - float iconAreaTop = min.Y + CurrentBrowserStyle.gridIconTopPadding; - float iconAreaBottom = MathF.Max(iconAreaTop + 1f, labelAreaTop - CurrentBrowserStyle.gridIconLabelSpacing); - float maximumIconWidth = MathF.Max(1f, size.X - CurrentBrowserStyle.gridIconHorizontalPadding * 2f); + float iconAreaTop = min.Y + currentBrowserStyle.gridIconTopPadding; + float iconAreaBottom = MathF.Max(iconAreaTop + 1f, labelAreaTop - currentBrowserStyle.gridIconLabelSpacing); + float maximumIconWidth = MathF.Max(1f, size.X - currentBrowserStyle.gridIconHorizontalPadding * 2f); float maximumIconHeight = MathF.Max(1f, iconAreaBottom - iconAreaTop); float fit = MathF.Min(1f, MathF.Min(maximumIconWidth / MathF.Max(1f, iconSize.X), maximumIconHeight / MathF.Max(1f, iconSize.Y))); if (fit < 1f) @@ -229,26 +266,20 @@ bool drawName } float horizontalCenter = min.X + size.X * 0.5f; - Vector2 iconAreaCenter = new(horizontalCenter + C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET * EditorUI.current.widgets.style.zoom, iconAreaTop + maximumIconHeight * 0.5f); - uint textColor = Ui.ToPackedColor(EditorPalette.contentText); - Ui.PushClipRect(min, max, true); + var iconAreaCenter = new Vector2( + horizontalCenter + C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET * EditorUI.current.widgets.style.zoom, + iconAreaTop + maximumIconHeight * 0.5f + ); + uint textColor = Gui.ToPackedColor(EditorPalette.contentText); + Gui.PushClipRect(min, max, true); EditorUI.current.widgets.AddGlyphCentered(iconFontSize, icon, iconAreaCenter, textColor); for (int i = 0; drawName && i < nameLines.Length; i++) { - Vector2 lineSize = Ui.MeasureText(nameLines[i]); - Vector2 linePosition = new(horizontalCenter - lineSize.X * 0.5f, labelY + lineAdvance * i); - Ui.DrawText(linePosition, textColor, nameLines[i]); + Vector2 lineSize = Gui.MeasureText(nameLines[i]); + var linePosition = new Vector2(horizontalCenter - lineSize.X * 0.5f, labelY + lineAdvance * i); + Gui.DrawText(linePosition, textColor, nameLines[i]); } - Ui.PopClipRect(); - } - - private float GetGridCellSize() - { - float fontSize = Ui.GetFontSize(); - return MathF.Max( - CurrentBrowserStyle.gridMinimumCellSize, - fontSize * (m_gridScale + CurrentBrowserStyle.gridScaleBias) + CurrentBrowserStyle.gridFixedCellPadding - ); + Gui.PopClipRect(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs index 56dc7d379..1382d70d2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs @@ -1,7 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -9,146 +5,145 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawBrowser(EditorContext context) { m_navigation.SyncExternalDirectoryChange(m_assets.browser.root, m_assets.browser.currentDirectory); - EditorUiLayout style = Ui.GetLayout(); + EditorUILayout style = Gui.GetLayout(); float breadcrumbBarHeight = GetBreadcrumbBarHeight(m_assets.browser.root, m_assets.browser.currentDirectory); - Vector2 bodySize = new(0f, -(breadcrumbBarHeight + style.itemSpacing.Y)); - bool mainVisible = Ui.BeginChild("##FileBrowserMain", bodySize, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + var bodySize = new Vector2(0f, -(breadcrumbBarHeight + style.itemSpacing.Y)); + bool mainVisible = Gui.BeginChild( + "##FileBrowserMain", + bodySize, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (mainVisible) { - ImGuiTableFlags splitFlags = ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoKeepColumnsVisible | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags splitFlags = ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoKeepColumnsVisible + | ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoSavedSettings; float splitterWidth = GetTreeSplitterWidth(style); - float availableWidth = MathF.Max(0f, Ui.GetContentRegionAvailable().X); + float availableWidth = MathF.Max(0f, Gui.GetContentRegionAvailable().X); float treeWidth = ResolveTreeWidth(m_treePaneRatio, availableWidth, splitterWidth); - Ui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); + Gui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); try { - bool splitStarted = Ui.BeginTable("##FileBrowserSplit", 3, splitFlags, default(System.Numerics.Vector2), 0f); + bool splitStarted = Gui.BeginTable("##FileBrowserSplit", 3, splitFlags, default, 0f); try { if (splitStarted) { - Ui.TableSetupColumn("##Tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); - Ui.TableSetupColumn("##Splitter", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), splitterWidth); - Ui.TableSetupColumn("##Content", ImGuiTableColumnFlags.WidthStretch); - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); + Gui.TableSetupColumn("##Tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); + Gui.TableSetupColumn( + "##Splitter", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + splitterWidth + ); + Gui.TableSetupColumn("##Content", ImGuiTableColumnFlags.WidthStretch); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); DrawTreePane(context); - _ = Ui.TableSetColumnIndex(1); + _ = Gui.TableSetColumnIndex(1); DrawTreeSplitter(splitterWidth, availableWidth, treeWidth); - _ = Ui.TableSetColumnIndex(2); + _ = Gui.TableSetColumnIndex(2); DrawContentPane(context); } } finally { if (splitStarted) - Ui.EndTable(); + { + Gui.EndTable(); + } } } finally { - Ui.PopStyleVar(); + Gui.PopStyleVar(); } } } finally { - Ui.EndChild(); + Gui.EndChild(); } DrawBreadcrumbBar(context, breadcrumbBarHeight); } - private static float GetTreeSplitterWidth(EditorUiLayout style) - { - return MathF.Max(EditorUI.current.widgets.style.splitterMinimumWidth, style.dockingSeparatorSize); - } - private void DrawTreeSplitter( float width, float availableWidth, float treeWidth ) { - Vector2 size = new(width, MathF.Max(1f, Ui.GetContentRegionAvailable().Y)); - _ = Ui.InvisibleButton("##TreeSplitterGrip", size); - bool hovered = Ui.IsItemHovered(); - bool active = Ui.IsItemActive(); + var size = new Vector2(width, MathF.Max(1f, Gui.GetContentRegionAvailable().Y)); + _ = Gui.InvisibleButton("##TreeSplitterGrip", size); + bool hovered = Gui.IsItemHovered(); + bool active = Gui.IsItemActive(); if (hovered || active) - Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + { + Gui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (active) { - Vector2 delta = Ui.GetMouseDragDelta(ImGuiMouseButton.Left); + Vector2 delta = Gui.GetMouseDragDelta(ImGuiMouseButton.Left); if (MathF.Abs(delta.X) > 0f) { float requestedWidth = ClampTreeWidth(treeWidth + delta.X, availableWidth, width); m_treePaneRatio = CalculateTreePaneRatio(requestedWidth, availableWidth, width); - Ui.ResetMouseDragDelta(ImGuiMouseButton.Left); + Gui.ResetMouseDragDelta(ImGuiMouseButton.Left); } } - Vector2 min = Ui.GetItemMinimum(); - Vector2 max = Ui.GetItemMaximum(); + Vector2 min = Gui.GetItemMinimum(); + Vector2 max = Gui.GetItemMaximum(); Vector4 color = active ? EditorPalette.contentAccent : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; - Ui.DrawFilledRectangle(min, max, Ui.ToPackedColor(color), 0f); - } - - private static float ClampTreeWidth( - float requestedWidth, - float availableWidth, - float splitterWidth - ) { - float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); - float minimumPaneWidth = MathF.Min(EditorUI.current.widgets.style.paneMinimumVisibleWidth, combinedPaneWidth * 0.5f); - float maximumTreeWidth = MathF.Max(minimumPaneWidth, combinedPaneWidth - minimumPaneWidth); - return Math.Clamp(requestedWidth, minimumPaneWidth, maximumTreeWidth); - } - - private static float ResolveTreeWidth( - float treePaneRatio, - float availableWidth, - float splitterWidth - ) { - float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); - return ClampTreeWidth(combinedPaneWidth * Math.Clamp(treePaneRatio, 0f, 1f), availableWidth, splitterWidth); - } - - private static float CalculateTreePaneRatio( - float treeWidth, - float availableWidth, - float splitterWidth - ) { - float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); - return combinedPaneWidth > float.Epsilon ? Math.Clamp(treeWidth / combinedPaneWidth, 0f, 1f) : 0.5f; + Gui.DrawFilledRectangle(min, max, Gui.ToPackedColor(color), 0f); } private void DrawTreePane(EditorContext context) { - Ui.PushStyleColor(ImGuiCol.ChildBg, EditorPalette.collectionHeader); + Gui.PushStyleColor(ImGuiCol.ChildBg, EditorPalette.collectionHeader); try { - EditorUiLayout style = Ui.GetLayout(); - Vector2 treePaneSize = new(-style.windowPadding.X, 0f); - bool treeVisible = Ui.BeginChild("##TreePane", treePaneSize, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + EditorUILayout style = Gui.GetLayout(); + var treePaneSize = new Vector2(-style.windowPadding.X, 0f); + bool treeVisible = Gui.BeginChild( + "##TreePane", + treePaneSize, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (treeVisible) { - float footerHeight = Ui.GetFrameHeight() + style.windowPadding.Y * 2f + style.itemSpacing.Y; - bool treeScrollVisible = Ui.BeginChild("##TreeScroll", new Vector2(0f, -footerHeight), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar); + float footerHeight = Gui.GetFrameHeight() + style.windowPadding.Y * 2f + style.itemSpacing.Y; + bool treeScrollVisible = Gui.BeginChild( + "##TreeScroll", + new Vector2(0f, -footerHeight), + ImGuiChildFlags.None, + ImGuiWindowFlags.HorizontalScrollbar + ); try { if (treeScrollVisible) @@ -170,7 +165,7 @@ private void DrawTreePane(EditorContext context) } finally { - Ui.EndChild(); + Gui.EndChild(); } DrawRootSwitchFooter(context); @@ -178,15 +173,17 @@ private void DrawTreePane(EditorContext context) } finally { - Ui.EndChild(); + Gui.EndChild(); } if (!IsReadOnlyLocation(m_assets.edits.pipeline, m_assets.browser)) + { m_dragDrop.DrawDirectoryTarget(context, m_assets.browser.currentDirectory); + } } finally { - Ui.PopStyleColor(); + Gui.PopStyleColor(); } } @@ -197,7 +194,7 @@ private void DrawRootSwitchFooter(EditorContext context) PushButtonColors(EditorPalette.contentAccent); try { - if (Ui.Button($"Switch to {nextRoot}##FileBrowserRoot", new Vector2(-1f, 0f))) + if (Gui.Button($"Switch to {nextRoot}##FileBrowserRoot", new Vector2(-1f, 0f))) { m_tree.RequestOpenRoot(); m_navigation.SwitchRoot(context, nextRoot); @@ -205,16 +202,21 @@ private void DrawRootSwitchFooter(EditorContext context) } finally { - Ui.PopStyleColor(3); + Gui.PopStyleColor(3); } } private void DrawContentPane(EditorContext context) { - Ui.PushStyleColor(ImGuiCol.ChildBg, EditorPalette.collectionHeader); + Gui.PushStyleColor(ImGuiCol.ChildBg, EditorPalette.collectionHeader); try { - bool contentVisible = Ui.BeginChild("##ContentPane", Vector2.Zero, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + bool contentVisible = Gui.BeginChild( + "##ContentPane", + Vector2.Zero, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (contentVisible) @@ -225,15 +227,17 @@ private void DrawContentPane(EditorContext context) } finally { - Ui.EndChild(); + Gui.EndChild(); } if (!IsReadOnlyLocation(m_assets.edits.pipeline, m_assets.browser)) + { m_dragDrop.DrawDirectoryTarget(context, m_assets.browser.currentDirectory); + } } finally { - Ui.PopStyleColor(); + Gui.PopStyleColor(); } } @@ -248,39 +252,77 @@ IReadOnlyList entries try { if (m_viewMode == ViewMode.List) + { DrawListRegion(context, entries); + } else + { DrawGridRegion(context, entries); + } } finally { - m_visibleSelection = Array.Empty(); + m_visibleSelection = []; m_drawKeyboardFocus = null; } RuntimeIdentity? activation = m_pendingActivation; m_pendingActivation = null; if (activation is RuntimeIdentity identity - && m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? target) - && target is AssetFileEntry entry) + && m_assets.edits.interactions.TryResolveIdentity(identity, out IdentityObject? target) + && target is AssetFileEntry entry + ) { m_navigation.OpenEntry(context, entry, m_tree); + } + } + + private static float GetTreeSplitterWidth(EditorUILayout style) + => MathF.Max(EditorUI.current.widgets.style.splitterMinimumWidth, style.dockingSeparatorSize); + + private static float ClampTreeWidth( + float requestedWidth, + float availableWidth, + float splitterWidth + ) { + float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); + float minimumPaneWidth = MathF.Min(EditorUI.current.widgets.style.paneMinimumVisibleWidth, combinedPaneWidth * 0.5f); + float maximumTreeWidth = MathF.Max(minimumPaneWidth, combinedPaneWidth - minimumPaneWidth); + return Math.Clamp(requestedWidth, minimumPaneWidth, maximumTreeWidth); + } + + private static float ResolveTreeWidth( + float treePaneRatio, + float availableWidth, + float splitterWidth + ) { + float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); + return ClampTreeWidth(combinedPaneWidth * Math.Clamp(treePaneRatio, 0f, 1f), availableWidth, splitterWidth); + } + + private static float CalculateTreePaneRatio( + float treeWidth, + float availableWidth, + float splitterWidth + ) { + float combinedPaneWidth = MathF.Max(0f, availableWidth - splitterWidth); + return combinedPaneWidth > float.Epsilon ? Math.Clamp(treeWidth / combinedPaneWidth, 0f, 1f) : 0.5f; } private static void DrawFooterTopSplitter() { - EditorUiLayout style = Ui.GetLayout(); - Vector2 cursor = Ui.GetCursorScreenPosition(); - float width = Ui.GetContentRegionAvailable().X; + EditorUILayout style = Gui.GetLayout(); + Vector2 cursor = Gui.GetCursorScreenPosition(); + float width = Gui.GetContentRegionAvailable().X; float lineY = cursor.Y + style.windowPadding.Y; - uint color = Ui.ToPackedColor(EditorPalette.contentBorder); - Ui.DrawLine(new Vector2(cursor.X, lineY), new Vector2(cursor.X + width, lineY), color, EditorUI.current.widgets.style.borderSize); - Ui.SetCursorPosY(Ui.GetCursorPosY() + style.windowPadding.Y * 2f); + uint color = Gui.ToPackedColor(EditorPalette.contentBorder); + Gui.DrawLine(new Vector2(cursor.X, lineY), new Vector2(cursor.X + width, lineY), color, EditorUI.current.widgets.style.borderSize); + Gui.SetCursorPosY(Gui.GetCursorPosY() + style.windowPadding.Y * 2f); } private static void DrawBreadcrumbTopSeparator() { - Vector2 min = Ui.GetWindowPos(); - Vector2 size = Ui.GetWindowSize(); - uint color = Ui.ToPackedColor(EditorPalette.contentBorder); - Ui.DrawLine(min, new Vector2(min.X + size.X, min.Y), color, EditorUI.current.widgets.style.borderSize); + Vector2 min = Gui.GetWindowPos(); + Vector2 size = Gui.GetWindowSize(); + uint color = Gui.ToPackedColor(EditorPalette.contentBorder); + Gui.DrawLine(min, new Vector2(min.X + size.X, min.Y), color, EditorUI.current.widgets.style.borderSize); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs index f89ad1f9e..6efe57c1d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,28 +5,36 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawListRegion( EditorContext context, IReadOnlyList entries ) { - bool entriesVisible = Ui.BeginChild("##EntriesScroll", Vector2.Zero, ImGuiChildFlags.None); + bool entriesVisible = Gui.BeginChild("##EntriesScroll", Vector2.Zero, ImGuiChildFlags.None); try { if (entriesVisible) { - if (Ui.IsWindowFocused()) + if (Gui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.List); - float rowHeight = Ui.GetTextLineHeight() + Ui.GetLayout().cellPadding.Y * 2f + CurrentBrowserStyle.listRowSpacing; - HandleEntryKeyboardNavigation(Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / rowHeight))); + } + float rowHeight = Gui.GetTextLineHeight() + Gui.GetLayout().cellPadding.Y * 2f + currentBrowserStyle.listRowSpacing; + HandleEntryKeyboardNavigation(Math.Max(1, (int)(Gui.GetContentRegionAvailable().Y / rowHeight))); DrawEntriesTable(context, entries, m_assets.browser.currentDirectory); HandleBackgroundSelection(context); m_contextMenu.DrawBackground(context, "##asset_list_background_context", FileBrowserPresentation.List); @@ -37,7 +42,7 @@ IReadOnlyList entries } finally { - Ui.EndChild(); + Gui.EndChild(); } } @@ -46,33 +51,51 @@ private void DrawEntriesTable( IReadOnlyList entries, string currentDirectory ) { - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings; - EditorUiLayout style = Ui.GetLayout(); - Vector2 tableOrigin = Ui.GetCursorScreenPosition(); - Vector2 tableSize = Ui.GetContentRegionAvailable(); - Ui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(style.windowPadding.X, style.cellPadding.Y)); + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoSavedSettings; + EditorUILayout style = Gui.GetLayout(); + Vector2 tableOrigin = Gui.GetCursorScreenPosition(); + Vector2 tableSize = Gui.GetContentRegionAvailable(); + Gui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(style.windowPadding.X, style.cellPadding.Y)); try { - bool tableStarted = Ui.BeginTable("##FileBrowserEntries", 3, flags, new Vector2(0f, 0f)); + bool tableStarted = Gui.BeginTable("##FileBrowserEntries", 3, flags, new Vector2(0f, 0f)); if (!tableStarted) { - Ui.Dummy(Vector2.Zero); + Gui.Dummy(Vector2.Zero); return; } try { - Ui.TableSetupColumn("Name", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), m_listNameSeparatorPosition); - Ui.TableSetupColumn("Type", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), m_listTypeSeparatorPosition - m_listNameSeparatorPosition); - Ui.TableSetupColumn("Source", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), 1f - m_listTypeSeparatorPosition); + Gui.TableSetupColumn( + "Name", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + m_listNameSeparatorPosition + ); + Gui.TableSetupColumn( + "Type", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + m_listTypeSeparatorPosition - m_listNameSeparatorPosition + ); + Gui.TableSetupColumn( + "Source", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + 1f - m_listTypeSeparatorPosition + ); DrawHeaderRow(); - uint rowBg = Ui.ToPackedColor(EditorPalette.collectionRow); - uint rowAltBg = Ui.ToPackedColor(EditorPalette.collectionRowAlternate); - float entryRowHeight = Ui.GetTextLineHeight() + style.cellPadding.Y * 2f + CurrentBrowserStyle.listRowSpacing; + uint rowBg = Gui.ToPackedColor(EditorPalette.collectionRow); + uint rowAltBg = Gui.ToPackedColor(EditorPalette.collectionRowAlternate); + float entryRowHeight = Gui.GetTextLineHeight() + style.cellPadding.Y * 2f + currentBrowserStyle.listRowSpacing; Span preserved = stackalloc int[3]; int preservedCount = CollectPreservedEntryRows(entries, preserved); - m_ui.widgets.ClippedRows(entries.Count, -1f, - (panel: this, context, entries, currentDirectory, rowBg, rowAltBg, entryRowHeight), static ( + m_ui.widgets.ClippedRows( + entries.Count, + -1f, + (panel: this, context, entries, currentDirectory, rowBg, rowAltBg, entryRowHeight), + static ( state, start, end @@ -81,34 +104,38 @@ string currentDirectory for (int index = start; index < end; index++) { FileBrowserDisplayEntry item = state.entries[index]; - Ui.TableNextRow(ImGuiTableRowFlags.None, state.entryRowHeight); + Gui.TableNextRow(ImGuiTableRowFlags.None, state.entryRowHeight); if (!state.panel.m_data.TryResolve(item, out AssetFileEntry? entry)) + { continue; - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, index % 2 == 0 ? state.rowBg : state.rowAltBg); + } + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, index % 2 == 0 ? state.rowBg : state.rowAltBg); state.panel.DrawNameCell(state.context, item, entry); DrawTextCell(item.isPluginRoot ? "IPLUGIN" : GetTypeText(entry), EditorPalette.contentText); DrawTextCell(item.isPluginRoot ? "~" : GetSourceText(entry, state.currentDirectory), EditorPalette.contentText); } - }, preserved[..preservedCount]); + }, + preserved[..preservedCount] + ); } finally { - Ui.EndTable(); + Gui.EndTable(); } - Vector2 tableEnd = Ui.GetCursorScreenPosition(); + Vector2 tableEnd = Gui.GetCursorScreenPosition(); float tableHeight = MathF.Max(1f, tableEnd.Y - tableOrigin.Y); var interactionSize = new Vector2(tableSize.X, tableHeight); ListColumnSeparatorState separators = HandleListColumnSeparators(tableOrigin, interactionSize); DrawListColumnSeparators(tableOrigin, tableSize.X, tableHeight, separators); - Ui.SetCursorScreenPosition(tableEnd); + Gui.SetCursorScreenPosition(tableEnd); // Commit the restored layout cursor so overlay separator hit targets cannot implicitly // extend the scrolling child when UI scaling changes their physical bounds. - Ui.Dummy(Vector2.Zero); + Gui.Dummy(Vector2.Zero); } finally { - Ui.PopStyleVar(); + Gui.PopStyleVar(); } } @@ -118,36 +145,40 @@ Vector2 size ) { float width = MathF.Max(1f, size.X); float height = MathF.Max(1f, size.Y); - float hitWidth = CurrentBrowserStyle.listSeparatorHitWidth; + float hitWidth = currentBrowserStyle.listSeparatorHitWidth; bool nameHovered; bool nameActive; bool typeHovered; bool typeActive; float nameX = origin.X + width * m_listNameSeparatorPosition; - Ui.SetCursorScreenPosition(new Vector2(nameX - hitWidth * 0.5f, origin.Y)); - Ui.SetNextItemAllowOverlap(); - _ = Ui.InvisibleButton("##AssetListNameSeparator", new Vector2(hitWidth, height)); - nameHovered = Ui.IsItemHovered(); - nameActive = Ui.IsItemActive(); + Gui.SetCursorScreenPosition(new Vector2(nameX - hitWidth * 0.5f, origin.Y)); + Gui.SetNextItemAllowOverlap(); + _ = Gui.InvisibleButton("##AssetListNameSeparator", new Vector2(hitWidth, height)); + nameHovered = Gui.IsItemHovered(); + nameActive = Gui.IsItemActive(); if (nameHovered || nameActive) - Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + { + Gui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (nameActive) { - float requested = (Ui.GetMousePos().X - origin.X) / width; + float requested = (Gui.GetMousePos().X - origin.X) / width; SetListColumnSeparators(requested, m_listTypeSeparatorPosition); } float typeX = origin.X + width * m_listTypeSeparatorPosition; - Ui.SetCursorScreenPosition(new Vector2(typeX - hitWidth * 0.5f, origin.Y)); - Ui.SetNextItemAllowOverlap(); - _ = Ui.InvisibleButton("##AssetListTypeSeparator", new Vector2(hitWidth, height)); - typeHovered = Ui.IsItemHovered(); - typeActive = Ui.IsItemActive(); + Gui.SetCursorScreenPosition(new Vector2(typeX - hitWidth * 0.5f, origin.Y)); + Gui.SetNextItemAllowOverlap(); + _ = Gui.InvisibleButton("##AssetListTypeSeparator", new Vector2(hitWidth, height)); + typeHovered = Gui.IsItemHovered(); + typeActive = Gui.IsItemActive(); if (typeHovered || typeActive) - Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + { + Gui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (typeActive) { - float requested = (Ui.GetMousePos().X - origin.X) / width; + float requested = (Gui.GetMousePos().X - origin.X) / width; SetListColumnSeparators(m_listNameSeparatorPosition, requested); } @@ -165,17 +196,6 @@ ListColumnSeparatorState state DrawListColumnSeparator(origin.X + width * m_listTypeSeparatorPosition, origin.Y, bottom, state.typeHovered, state.typeActive); } - private static void DrawListColumnSeparator( - float x, - float top, - float bottom, - bool hovered, - bool active - ) { - Vector4 color = active ? EditorPalette.contentAccent : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; - Ui.DrawLine(new Vector2(x, top), new Vector2(x, bottom), Ui.ToPackedColor(color), EditorUI.current.widgets.style.borderSize); - } - private void SetListColumnSeparators( float namePosition, float typePosition @@ -185,84 +205,77 @@ float typePosition m_listTypeSeparatorPosition = Math.Clamp(typePosition, m_listNameSeparatorPosition + minimum, 1f - minimum); } - private static void DrawHeaderRow() - { - Ui.TableNextRow(); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, Ui.ToPackedColor(EditorPalette.collectionHeader)); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, Ui.ToPackedColor(EditorPalette.collectionHeader)); - _ = Ui.TableSetColumnIndex(0); - InsetListCellContent(); - Ui.Text("Name"); - _ = Ui.TableSetColumnIndex(1); - InsetListCellContent(); - Ui.Text("Type"); - _ = Ui.TableSetColumnIndex(2); - InsetListCellContent(); - Ui.Text("Source"); - } - private void DrawNameCell( EditorContext context, FileBrowserDisplayEntry item, AssetFileEntry entry ) { - _ = Ui.TableSetColumnIndex(0); + _ = Gui.TableSetColumnIndex(0); string icon = m_assets.GetIcon(entry); string name = item.isPluginRoot ? item.displayName : entry.nameWithoutExtension; bool selected = m_assets.browser.IsSelected(context, entry); bool editing = m_rename.IsEditing(context, entry.assetPath.ToString(), FileBrowserPresentation.List); - var table = Ui.GetTableBounds(); + (float minimumX, float maximumX, float rowMinimum, float rowMaximum) table = Gui.GetTableBounds(); float rowMinimumY = table.rowMinimum; float rowMaximumY = table.rowMaximum; InsetListCellContent(); - Ui.PushStyleColor(ImGuiCol.Header, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.HeaderHovered, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.HeaderActive, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.Header, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.HeaderHovered, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.HeaderActive, EditorPalette.transparent); try { - Vector2 iconTextPos = Ui.GetCursorScreenPosition(); - ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.SpanAllColumns | ImGuiSelectableFlags.AllowDoubleClick | ImGuiSelectableFlags.AllowOverlap; + Vector2 iconTextPos = Gui.GetCursorScreenPosition(); + ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.SpanAllColumns + | ImGuiSelectableFlags.AllowDoubleClick + | ImGuiSelectableFlags.AllowOverlap; RequestEntryKeyboardFocus(entry); - bool activated = Ui.Selectable($"##entry_{entry.assetPath.ToString()}", selected, selectableFlags); - bool itemHovered = Ui.IsItemHovered(); - bool doubleClicked = itemHovered && Ui.IsMouseDoubleClicked(ImGuiMouseButton.Left); + bool activated = Gui.Selectable($"##entry_{entry.assetPath.ToString()}", selected, selectableFlags); + bool itemHovered = Gui.IsItemHovered(); + bool doubleClicked = itemHovered && Gui.IsMouseDoubleClicked(ImGuiMouseButton.Left); if (activated && !m_keyboardHandled) { HandleEntryActivation(context, entry, FileBrowserPresentation.List, doubleClicked); } - bool itemActive = Ui.IsItemActive(); + bool itemActive = Gui.IsItemActive(); if (!editing) { - m_contextMenu.DrawEntry(context, $"##asset_context_{entry.assetPath.ToString()}", entry.assetPath.ToString(), FileBrowserPresentation.List); + m_contextMenu.DrawEntry( + context, + $"##asset_context_{entry.assetPath.ToString()}", + entry.assetPath.ToString(), + FileBrowserPresentation.List + ); } if (selected || itemHovered) { Vector4 highlight = itemActive ? EditorPalette.GetHovered(EditorPalette.contentAccent) : EditorPalette.contentAccent; - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, Ui.ToPackedColor(highlight)); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, Gui.ToPackedColor(highlight)); } if (!editing) { m_dragDrop.DrawAssetSource(context, entry); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, entry.assetPath.ToString()); + } } - Ui.SameLine(iconTextPos.X - Ui.GetWindowPos().X, 0f); + Gui.SameLine(iconTextPos.X - Gui.GetWindowPos().X, 0f); if (editing) { EditorUI.current.widgets.IconText(icon, string.Empty, false); - Ui.SameLine(0f, 0f); - Vector2 renameCursor = Ui.GetCursorScreenPosition(); - Ui.SetCursorScreenPosition(new Vector2(renameCursor.X, rowMinimumY)); + Gui.SameLine(0f, 0f); + Vector2 renameCursor = Gui.GetCursorScreenPosition(); + Gui.SetCursorScreenPosition(new Vector2(renameCursor.X, rowMinimumY)); m_rename.Draw( context, $"list_{entry.assetPath.ToString()}", entry.assetPath.ToString(), FileBrowserPresentation.List, - Ui.GetContentRegionAvailable().X, + Gui.GetContentRegionAvailable().X, MathF.Max(1f, rowMaximumY - rowMinimumY) ); } @@ -273,25 +286,49 @@ AssetFileEntry entry } finally { - Ui.PopStyleColor(3); + Gui.PopStyleColor(3); } } + private static void DrawListColumnSeparator( + float x, + float top, + float bottom, + bool hovered, + bool active + ) { + Vector4 color = active ? EditorPalette.contentAccent : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; + Gui.DrawLine(new Vector2(x, top), new Vector2(x, bottom), Gui.ToPackedColor(color), EditorUI.current.widgets.style.borderSize); + } + + private static void DrawHeaderRow() + { + Gui.TableNextRow(); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, Gui.ToPackedColor(EditorPalette.collectionHeader)); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, Gui.ToPackedColor(EditorPalette.collectionHeader)); + _ = Gui.TableSetColumnIndex(0); + InsetListCellContent(); + Gui.Text("Name"); + _ = Gui.TableSetColumnIndex(1); + InsetListCellContent(); + Gui.Text("Type"); + _ = Gui.TableSetColumnIndex(2); + InsetListCellContent(); + Gui.Text("Source"); + } + private static void DrawTextCell( string text, Vector4 color ) { - Ui.TableNextColumn(); + Gui.TableNextColumn(); InsetListCellContent(); - Ui.PushStyleColor(ImGuiCol.Text, color); - Ui.Text(text); - Ui.PopStyleColor(); + Gui.PushStyleColor(ImGuiCol.Text, color); + Gui.Text(text); + Gui.PopStyleColor(); } - private static void InsetListCellContent() - { - Ui.SetCursorPosX(Ui.GetCursorPosX() + CurrentBrowserStyle.listContentHorizontalPadding); - } + private static void InsetListCellContent() => Gui.SetCursorPosX(Gui.GetCursorPosX() + currentBrowserStyle.listContentHorizontalPadding); private readonly record struct ListColumnSeparatorState( bool nameHovered, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs index 1282efbca..9257420f0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs @@ -1,8 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Interactions; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -10,13 +5,21 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private int CollectPreservedEntryRows( @@ -27,13 +30,17 @@ private int CollectPreservedEntryRows( RuntimeIdentity? editing = m_rename.activeTarget; RuntimeIdentity? dragging = m_assets.edits.interactions.TryGetActiveDragIdentity(out RuntimeIdentity source) ? source : null; if (editing is null && dragging is null && m_drawKeyboardFocus is null) + { return 0; + } int count = 0; for (int index = 0; index < entries.Count; index++) { RuntimeIdentity identity = entries[index].identity; if (identity == editing || identity == dragging || identity == m_drawKeyboardFocus) + { rows[count++] = index / columns; + } } return count; } @@ -47,42 +54,48 @@ private void DrawToolbar(EditorContext context) private void DrawNavigationBar(EditorContext context) { string current = m_assets.browser.currentDirectory; - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.breadcrumbFramePadding); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.breadcrumbFramePadding); bool canGoBack = m_navigation.canGoBack; PushButtonColors(canGoBack ? EditorPalette.contentAccent : EditorPalette.contentBorderSoft); - Ui.BeginDisabled(!canGoBack); - if (Ui.SmallButton($"{ImGuiIcon.AngleLeft}##Back")) + Gui.BeginDisabled(!canGoBack); + if (Gui.SmallButton($"{ImGuiIcon.C_ANGLE_LEFT}##Back")) + { m_navigation.GoBack(context); - Ui.EndDisabled(); - Ui.PopStyleColor(3); - Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarTightSpacing); + } + Gui.EndDisabled(); + Gui.PopStyleColor(3); + Gui.SameLine(0f, EditorUI.current.widgets.style.toolbarTightSpacing); bool canGoForward = m_navigation.canGoForward; PushButtonColors(canGoForward ? EditorPalette.contentAccent : EditorPalette.contentBorderSoft); - Ui.BeginDisabled(!canGoForward); - if (Ui.SmallButton($"{ImGuiIcon.AngleRight}##Forward")) + Gui.BeginDisabled(!canGoForward); + if (Gui.SmallButton($"{ImGuiIcon.C_ANGLE_RIGHT}##Forward")) + { m_navigation.GoForward(context); - Ui.EndDisabled(); - Ui.PopStyleColor(3); - Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarSectionSpacing); - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.contentText); - Ui.Text(GetDirectoryLabel(m_assets.browser.root, current)); - Ui.PopStyleColor(); - Ui.PopStyleVar(); + } + Gui.EndDisabled(); + Gui.PopStyleColor(3); + Gui.SameLine(0f, EditorUI.current.widgets.style.toolbarSectionSpacing); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.contentText); + Gui.Text(GetDirectoryLabel(m_assets.browser.root, current)); + Gui.PopStyleColor(); + Gui.PopStyleVar(); } private void DrawViewAndSearchBar() { - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.toolbarFramePadding); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.toolbarFramePadding); PushButtonColors(EditorPalette.contentAccent); - if (Ui.SmallButton($"{m_viewMode}##ViewMode")) + if (Gui.SmallButton($"{m_viewMode}##ViewMode")) + { m_viewMode = m_viewMode == ViewMode.List ? ViewMode.Grid : ViewMode.List; - Ui.PopStyleColor(3); - Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarSpacing); + } + Gui.PopStyleColor(3); + Gui.SameLine(0f, EditorUI.current.widgets.style.toolbarSpacing); DrawEntryFilterCombo(); - Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarSpacing); - Ui.SetNextItemWidth(-1f); + Gui.SameLine(0f, EditorUI.current.widgets.style.toolbarSpacing); + Gui.SetNextItemWidth(-1f); DrawSearchInput(); - Ui.PopStyleVar(); + Gui.PopStyleVar(); } private void HandleEntryActivation( @@ -93,7 +106,7 @@ bool doubleClicked ) { m_rename.MarkInteraction(presentation); m_keyboardFocus = entry.identity.runtimeIdentity; - m_assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry).Focus(); + m_assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, entry).Focus(); if (doubleClicked) { m_pendingActivation = entry.identity.runtimeIdentity; @@ -118,17 +131,23 @@ private void HandleEntryKeyboardNavigation(int pageSize) break; } if (candidate == selected) + { selectedIndex = i; + } } if (focus < 0) + { focus = selectedIndex; + } ListNavigationResult navigation = m_ui.widgets.NavigateList(interactions, m_visibleSelection.Count, focus, pageSize); m_keyboardHandled = navigation.focusChanged || navigation.selectionRequested || navigation.activate || navigation.cancel; if (navigation.focusedIndex >= 0 && m_keyboardHandled) { RuntimeIdentity identity = m_visibleSelection[navigation.focusedIndex]; if (!interactions.TryResolveIdentity(identity, out IdentityObject? target) || target is null) + { return; + } m_keyboardFocus = identity; if (navigation.focusChanged) { @@ -138,24 +157,36 @@ private void HandleEntryKeyboardNavigation(int pageSize) if (navigation.selectionRequested) { if (navigation.extendRange) + { interactions.SelectRange(m_visibleSelection, target, navigation.additive); + } else if (navigation.toggle) + { interactions.ToggleSelection(target); + } else + { interactions.SetSelection(target); + } } - interactions.For(FileBrowserInteractionIds.C_AREA, interactions.selection.selectedTarget).Focus(); + interactions.For(FileBrowserInteractionIDs.C_AREA, interactions.selection.selectedTarget).Focus(); if (navigation.activate) + { m_pendingActivation = m_keyboardFocus; + } } if (navigation.cancel) + { m_keyboardFocus = null; + } } private void RequestEntryKeyboardFocus(AssetFileEntry entry) { - if (entry.identity.runtimeIdentity == m_drawKeyboardFocus && Ui.IsWindowFocused(ImGuiFocusedFlags.ChildWindows)) - Ui.FocusNextItem(); + if (entry.identity.runtimeIdentity == m_drawKeyboardFocus && Gui.IsWindowFocused(ImGuiFocusedFlags.ChildWindows)) + { + Gui.FocusNextItem(); + } } private void DrawBreadcrumbBar( @@ -165,42 +196,46 @@ float height IReadOnlyList parts = BuildBreadcrumbParts(m_assets.browser.root, m_assets.browser.currentDirectory); Vector2 framePadding = EditorUI.current.widgets.style.breadcrumbFramePadding; float contentWidth = CalculateBreadcrumbContentWidth(parts, framePadding); - float availableWidth = Ui.GetContentRegionAvailable().X; + float availableWidth = Gui.GetContentRegionAvailable().X; bool hasHorizontalOverflow = contentWidth > availableWidth; - Ui.SetNextWindowContentSize(new Vector2(hasHorizontalOverflow ? contentWidth : 0f, 0f)); - Ui.PushStyleVar((ImGuiStyleVar.WindowPadding), Vector2.Zero); - if (Ui.BeginChild("##BreadcrumbBar", new Vector2(0f, height), (ImGuiChildFlags.None), (ImGuiWindowFlags.HorizontalScrollbar))) + Gui.SetNextWindowContentSize(new Vector2(hasHorizontalOverflow ? contentWidth : 0f, 0f)); + Gui.PushStyleVar((ImGuiStyleVar.WindowPadding), Vector2.Zero); + if (Gui.BeginChild("##BreadcrumbBar", new Vector2(0f, height), (ImGuiChildFlags.None), (ImGuiWindowFlags.HorizontalScrollbar))) { DrawBreadcrumbTopSeparator(); - float contentHeight = hasHorizontalOverflow ? height - Ui.GetLayout().scrollbarSize : height; + float contentHeight = hasHorizontalOverflow ? height - Gui.GetLayout().scrollbarSize : height; float itemHeight = EditorUI.current.widgets.GetClickableTextSize("A", framePadding).Y; - Ui.SetCursorPosY(MathF.Max(0f, (contentHeight - itemHeight) * 0.5f)); - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.contextText); + Gui.SetCursorPosY(MathF.Max(0f, (contentHeight - itemHeight) * 0.5f)); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.contextText); for (int i = 0; i < parts.Count; i++) { BreadcrumbPart part = parts[i]; if (i > 0) { - Ui.SameLine(0f, CurrentBrowserStyle.breadcrumbSpacing); - EditorUI.current.widgets.CenteredText(">", new Vector2(Ui.MeasureText(">").X, itemHeight)); - Ui.SameLine(0f, CurrentBrowserStyle.breadcrumbSpacing); + Gui.SameLine(0f, currentBrowserStyle.breadcrumbSpacing); + EditorUI.current.widgets.CenteredText(">", new Vector2(Gui.MeasureText(">").X, itemHeight)); + Gui.SameLine(0f, currentBrowserStyle.breadcrumbSpacing); } Vector2 itemSize = EditorUI.current.widgets.GetClickableTextSize(part.label, framePadding); if (EditorUI.current.widgets.ClickableText($"crumb_{part.root}_{part.directory}", part.label, itemSize)) { if (string.IsNullOrEmpty(part.directory)) + { m_navigation.NavigateToRoot(context, part.root); + } else + { m_navigation.NavigateTo(context, part.directory); + } } } - Ui.PopStyleColor(); + Gui.PopStyleColor(); } - Ui.EndChild(); - Ui.PopStyleVar(); + Gui.EndChild(); + Gui.PopStyleVar(); } private static float GetBreadcrumbBarHeight( @@ -208,14 +243,14 @@ private static float GetBreadcrumbBarHeight( string currentDirectory ) { IReadOnlyList parts = BuildBreadcrumbParts(root, currentDirectory); - EditorUiLayout style = Ui.GetLayout(); + EditorUILayout style = Gui.GetLayout(); float itemHeight = EditorUI.current.widgets.GetClickableTextSize("A", EditorUI.current.widgets.style.breadcrumbFramePadding).Y; float contentHeight = MathF.Max( - CurrentBrowserStyle.breadcrumbHeight, + currentBrowserStyle.breadcrumbHeight, MathF.Ceiling(itemHeight + style.itemSpacing.Y * 2f + EditorUI.current.widgets.style.borderSize) ); float contentWidth = CalculateBreadcrumbContentWidth(parts, EditorUI.current.widgets.style.breadcrumbFramePadding); - return contentWidth > Ui.GetContentRegionAvailable().X ? contentHeight + style.scrollbarSize : contentHeight; + return contentWidth > Gui.GetContentRegionAvailable().X ? contentHeight + style.scrollbarSize : contentHeight; } private static float CalculateBreadcrumbContentWidth( @@ -223,14 +258,18 @@ private static float CalculateBreadcrumbContentWidth( Vector2 framePadding ) { if (parts.Count == 0) + { return 0f; + } float width = 0f; - float separatorWidth = Ui.MeasureText(">").X; + float separatorWidth = Gui.MeasureText(">").X; for (int i = 0; i < parts.Count; i++) { if (i > 0) - width += separatorWidth + CurrentBrowserStyle.breadcrumbSpacing * 2f; - width += Ui.MeasureText(parts[i].label).X + framePadding.X * 2f; + { + width += separatorWidth + currentBrowserStyle.breadcrumbSpacing * 2f; + } + width += Gui.MeasureText(parts[i].label).X + framePadding.X * 2f; } return MathF.Ceiling(width); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs index 7e92fc74d..06b080fd7 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs @@ -1,6 +1,3 @@ -using Inno.Core.Identity; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,29 +5,28 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; namespace Inno.Editor.Panel.FileBrowser; + /// /// Asset browser panel with a tree pane and filtered table view. /// [EditorPanel("asset.file-browser", "File", order: 300, menuPath: "Content")] internal sealed partial class FileBrowserPanel : EditorPanel { - private IReadOnlyList m_visibleSelection = Array.Empty(); - private RuntimeIdentity? m_keyboardFocus; - private RuntimeIdentity? m_requestedKeyboardFocus; - private RuntimeIdentity? m_drawKeyboardFocus; - private RuntimeIdentity? m_pendingActivation; - private bool m_keyboardHandled; private const int C_SEARCH_BUFFER_SIZE = 256; private const int C_GRID_LABEL_LINE_COUNT = 2; private const float C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET = -1f; private readonly AssetBrowserModule m_assets; - private readonly EditorUiSession m_ui; + private readonly EditorUISession m_ui; private readonly FileBrowserData m_data; private readonly FileBrowserNavigation m_navigation; private readonly FileBrowserDragDrop m_dragDrop; @@ -38,6 +34,12 @@ internal sealed partial class FileBrowserPanel : EditorPanel private readonly FileBrowserRename m_rename; private readonly FileBrowserContextMenu m_contextMenu; private readonly FileBrowserTree m_tree; + private IReadOnlyList m_visibleSelection = []; + private RuntimeIdentity? m_keyboardFocus; + private RuntimeIdentity? m_requestedKeyboardFocus; + private RuntimeIdentity? m_drawKeyboardFocus; + private RuntimeIdentity? m_pendingActivation; + private bool m_keyboardHandled; private float m_treePaneRatio = 0.5f; private string m_filter = string.Empty; private ViewMode m_viewMode = ViewMode.List; @@ -46,10 +48,28 @@ internal sealed partial class FileBrowserPanel : EditorPanel private float m_gridScale; private float m_listNameSeparatorPosition; private float m_listTypeSeparatorPosition; - private enum ViewMode - { - List, - Grid + + /// + /// Creates the panel. + /// + internal FileBrowserPanel( + AssetBrowserModule assets, + EditorUISession ui + ) { + ArgumentNullException.ThrowIfNull(ui); + m_assets = assets; + m_ui = ui; + var style = new AssetBrowserStyle(ui.widgets.style); + m_gridScale = style.gridDefaultScale; + m_listNameSeparatorPosition = style.listNameSeparatorPosition; + m_listTypeSeparatorPosition = style.listTypeSeparatorPosition; + m_data = new FileBrowserData(assets); + m_navigation = new FileBrowserNavigation(assets); + m_dragDrop = new FileBrowserDragDrop(assets); + m_changeTracker = new FileBrowserChangeTracker(assets); + m_rename = new FileBrowserRename(assets); + m_contextMenu = new FileBrowserContextMenu(assets, m_rename); + m_tree = new FileBrowserTree(m_data, m_navigation, m_dragDrop, m_rename, m_contextMenu, assets); } /// @@ -57,8 +77,6 @@ private enum ViewMode /// public override bool allowScrolling => false; - private AssetBrowserStyle browserStyle => new(m_ui.widgets.style); - /// /// Captures an immutable snapshot of the current observable state. /// @@ -86,7 +104,9 @@ protected override void Capture(EditorState state) protected override void Restore(EditorState state) { if (Enum.TryParse(state.Get("viewMode", string.Empty), out ViewMode viewMode)) + { m_viewMode = viewMode; + } if (Enum.TryParse(state.Get("entryTypeFilter", string.Empty), out FileBrowserEntryTypeFilter typeFilter)) { m_entryTypeFilter = typeFilter; @@ -111,38 +131,13 @@ protected override void Restore(EditorState state) ); } - /// - /// Creates the panel. - /// - internal FileBrowserPanel( - AssetBrowserModule assets, - EditorUiSession ui - ) { - m_assets = assets; - m_ui = ui ?? throw new ArgumentNullException(nameof(ui)); - AssetBrowserStyle style = new(ui.widgets.style); - m_gridScale = style.gridDefaultScale; - m_listNameSeparatorPosition = style.listNameSeparatorPosition; - m_listTypeSeparatorPosition = style.listTypeSeparatorPosition; - m_data = new FileBrowserData(assets); - m_navigation = new FileBrowserNavigation(assets); - m_dragDrop = new FileBrowserDragDrop(assets); - m_changeTracker = new FileBrowserChangeTracker(assets); - m_rename = new FileBrowserRename(assets); - m_contextMenu = new FileBrowserContextMenu(assets, m_rename); - m_tree = new FileBrowserTree(m_data, m_navigation, m_dragDrop, m_rename, m_contextMenu, assets); - } - /// /// Attaches this feature to its owning runtime generation. /// /// /// The context that supplies state and services for this operation. /// - protected override void OnAttach(EditorContext context) - { - m_changeTracker.Attach(context); - } + protected override void OnAttach(EditorContext context) => m_changeTracker.Attach(context); /// /// Detaches this feature and releases generation-scoped state. @@ -150,10 +145,7 @@ protected override void OnAttach(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnDetach(EditorContext context) - { - m_changeTracker.Detach(); - } + protected override void OnDetach(EditorContext context) => m_changeTracker.Detach(); /// /// Draws this feature using the current editor presentation context. @@ -174,4 +166,12 @@ protected override void OnDraw(EditorContext context) PopBrowserStyle(); } } + + private AssetBrowserStyle browserStyle => new(m_ui.widgets.style); + + private enum ViewMode + { + List, + Grid + } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs index adfd71578..6d0f79582 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs @@ -1,19 +1,11 @@ -using Inno.Core.Identity; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui.ImGuiWidget; namespace Inno.Editor.Panel.FileBrowser; -internal enum FileBrowserPresentation -{ - Tree, - List, - Grid -} internal sealed class FileBrowserRename(AssetBrowserModule assets) { @@ -21,20 +13,21 @@ internal sealed class FileBrowserRename(AssetBrowserModule assets) private FileBrowserPresentation m_lastPresentation = FileBrowserPresentation.List; private FileBrowserPresentation m_activePresentation; internal RuntimeIdentity? activeTarget => m_activeTarget; + internal void Update(EditorContext context) { AssetFileEntry? target = assets.edits.interactions.selection.selectedTarget as AssetFileEntry; - bool isActive = target is not null && assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, target).IsActive(FileBrowserInteractionIds.C_RENAME); + bool isActive = target is not null + && assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, target).IsActive(FileBrowserInteractionIDs.C_RENAME); if (isActive && target?.identity.runtimeIdentity == m_activeTarget) + { return; + } m_activeTarget = isActive ? target!.identity.runtimeIdentity : null; m_activePresentation = m_lastPresentation; } - internal void MarkInteraction(FileBrowserPresentation presentation) - { - m_lastPresentation = presentation; - } + internal void MarkInteraction(FileBrowserPresentation presentation) => m_lastPresentation = presentation; internal bool IsEditing( EditorContext context, @@ -43,12 +36,8 @@ FileBrowserPresentation presentation ) { Update(context); return ResolveTarget() is AssetFileEntry target - && m_activePresentation == presentation - && string.Equals( - target.assetPath.ToString(), - relativePath, - StringComparison.Ordinal - ); + && m_activePresentation == presentation + && string.Equals(target.assetPath.ToString(), relativePath, StringComparison.Ordinal); } internal void Draw( @@ -60,19 +49,26 @@ internal void Draw( float rowHeight ) { if (!IsEditing(context, relativePath, presentation) || m_activeTarget is null) + { return; - _ = assets.edits.interactions.For( - FileBrowserInteractionIds.C_AREA, - ResolveTarget() - ).Present( - FileBrowserInteractionIds.C_RENAME, + } + _ = assets.edits.interactions.For(FileBrowserInteractionIDs.C_AREA, ResolveTarget()).Present( + FileBrowserInteractionIDs.C_RENAME, new InlineRenamePresentation(id, MathF.Max(1f, width), MathF.Max(1f, rowHeight)) ); } - private AssetFileEntry? ResolveTarget() => m_activeTarget is RuntimeIdentity identity - && assets.edits.interactions.TryResolveIdentity( - identity, - out IdentityObject? target - ) ? target as AssetFileEntry : null; + private AssetFileEntry? ResolveTarget() + => m_activeTarget is RuntimeIdentity identity + && assets.edits.interactions.TryResolveIdentity( + identity, + out IdentityObject? target + ) ? target as AssetFileEntry : null; +} + +internal enum FileBrowserPresentation +{ + Tree, + List, + Grid } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs index 3bc7c020b..c52010e89 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs @@ -3,13 +3,14 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; @@ -32,19 +33,23 @@ internal void CompleteNavigation(EditorContext context) { EditorInteractions interactions = m_assets.edits.interactions; if (m_pendingSelection is RuntimeIdentity pending - && interactions.TryResolveIdentity(pending, out IdentityObject? resolved) && resolved is AssetFileEntry entry) - { + && interactions.TryResolveIdentity(pending, out IdentityObject? resolved) && resolved is AssetFileEntry entry + ) { if (m_pendingActivation) { if (!interactions.selection.Contains(entry)) + { interactions.SetSelection(entry); + } m_navigation.OpenEntry(context, entry, this); } else - EditorUiSession.current.widgets.SelectTarget(interactions, entry, m_visibleSelection); + { + EditorUISession.current.widgets.SelectTarget(interactions, entry, m_visibleSelection); + } m_keyboardFocus = pending; m_rootFocused = false; - interactions.For(FileBrowserInteractionIds.C_AREA, entry).Focus(); + interactions.For(FileBrowserInteractionIDs.C_AREA, entry).Focus(); } if (m_pendingRootNavigation) { @@ -52,7 +57,7 @@ internal void CompleteNavigation(EditorContext context) m_assets.browser.Select(context, null); m_keyboardFocus = null; m_rootFocused = true; - interactions.For(FileBrowserInteractionIds.C_AREA).Focus(); + interactions.For(FileBrowserInteractionIDs.C_AREA).Focus(); } int focus = -1; int selectedIndex = -1; @@ -66,11 +71,20 @@ internal void CompleteNavigation(EditorContext context) break; } if (row.identity is not null && row.identity == selectedIdentity) + { selectedIndex = index; + } } if (focus < 0) + { focus = selectedIndex; - ListNavigationResult navigation = EditorUiSession.current.widgets.NavigateList(interactions, m_navigationRows.Count, focus, m_keyboardPageSize); + } + ListNavigationResult navigation = EditorUISession.current.widgets.NavigateList( + interactions, + m_navigationRows.Count, + focus, + m_keyboardPageSize + ); if (navigation.focusedIndex >= 0 && (navigation.focusChanged || navigation.selectionRequested || navigation.activate)) { TreeNavigationRow row = m_navigationRows[navigation.focusedIndex]; @@ -82,26 +96,34 @@ internal void CompleteNavigation(EditorContext context) m_requestedRootFocus = m_rootFocused; } if (row.identity is RuntimeIdentity identity - && interactions.TryResolveIdentity(identity, out IdentityObject? target) && target is AssetFileEntry asset) - { + && interactions.TryResolveIdentity(identity, out IdentityObject? target) && target is AssetFileEntry asset + ) { if (navigation.selectionRequested) { if (navigation.extendRange) + { interactions.SelectRange(m_visibleSelection, asset, navigation.additive); + } else if (navigation.toggle) + { interactions.ToggleSelection(asset); + } else + { interactions.SetSelection(asset); + } } if (navigation.activate) + { m_navigation.OpenEntry(context, asset, this); + } } else if (navigation.activate) { m_navigation.NavigateToRoot(context, m_assets.browser.root); m_assets.browser.Select(context, null); } - interactions.For(FileBrowserInteractionIds.C_AREA, interactions.selection.selectedTarget).Focus(); + interactions.For(FileBrowserInteractionIDs.C_AREA, interactions.selection.selectedTarget).Focus(); } if (navigation.cancel) { @@ -112,15 +134,17 @@ internal void CompleteNavigation(EditorContext context) private void BeginNavigation() { - if (Ui.IsWindowFocused()) + if (Gui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.Tree); + } ClearNavigationFrame(); m_drawKeyboardFocus = m_requestedKeyboardFocus; m_drawRootFocus = m_requestedRootFocus; m_requestedKeyboardFocus = null; m_requestedRootFocus = false; - float rowHeight = Ui.GetFrameHeight() + Ui.GetLayout().itemSpacing.Y; - m_keyboardPageSize = Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / rowHeight)); + float rowHeight = Gui.GetFrameHeight() + Gui.GetLayout().itemSpacing.Y; + m_keyboardPageSize = Math.Max(1, (int)(Gui.GetContentRegionAvailable().Y / rowHeight)); } private bool RequestsKeyboardFocus( diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs index e75b98273..4162103a4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs @@ -7,24 +7,15 @@ using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; internal sealed partial class FileBrowserTree { - private readonly record struct BrowserTreeRow( - string path, - string label, - string nodeId, - int depth, - bool isRoot, - bool virtualRoot, - bool isLeaf, - RuntimeIdentity? identity - ); - private readonly List m_rows = []; private long m_sourceRevision = long.MinValue; private ulong m_expansionRevision = ulong.MaxValue; @@ -41,8 +32,10 @@ internal void Draw(EditorContext context) { BrowserTreeRow row = m_rows[index]; if (row.identity is { } identity && (identity == dragging || identity == editing || identity == m_drawKeyboardFocus) - || row.isRoot && m_drawRootFocus) + || row.isRoot && m_drawRootFocus + ) { preserved[preservedCount++] = index; + } } EditorUI.current.widgets.ClippedRows(m_rows.Count, -1f, (tree: this, context), static ( state, @@ -51,53 +44,84 @@ internal void Draw(EditorContext context) ) => { for (int index = start; index < end; index++) + { state.tree.DrawRow(state.context, state.tree.m_rows[index]); + } }, preserved[..preservedCount]); } private void RefreshRows() { - var widgets = EditorUI.current.widgets; + ImGuiWidget widgets = EditorUI.current.widgets; AssetPipeline pipeline = m_assets.edits.pipeline; if (!m_rootOpenRequest && !m_currentDirectoryOpenRequest && m_rowsRoot == m_assets.browser.root - && m_sourceRevision == pipeline.revision && m_expansionRevision == widgets.treeExpansionRevision) + && m_sourceRevision == pipeline.revision && m_expansionRevision == widgets.treeExpansionRevision + ) { return; - var rows = new List(); + } + List rows = []; var pending = new Stack<(string path, string label, bool root, int depth)>(); if (m_assets.browser.root == AssetBrowserRoot.Assets) + { pending.Push((string.Empty, "Assets", true, 0)); + } else { - const string rootId = "tree_virtual_plugins"; + const string C_ROOT_ID = "tree_virtual_plugins"; if (m_rootOpenRequest || m_currentDirectoryOpenRequest) - widgets.SetTreeNodeOpen(rootId, true); - rows.Add(new(string.Empty, "Plugins", rootId, 0, true, true, false, null)); - if (widgets.IsTreeNodeOpen(rootId)) + { + widgets.SetTreeNodeOpen(C_ROOT_ID, true); + } + rows.Add(new BrowserTreeRow(string.Empty, "Plugins", C_ROOT_ID, 0, true, true, false, null)); + if (widgets.IsTreeNodeOpen(C_ROOT_ID)) { AssetSourceMount[] mounts = pipeline.sourceMounts.Where(mount => m_assets.edits.IsPluginSource(mount.id)) - .OrderBy(static mount => mount.id.value, StringComparer.OrdinalIgnoreCase).ToArray(); + .OrderBy(static mount => mount.id.value, StringComparer.OrdinalIgnoreCase) + .ToArray(); for (int index = mounts.Length - 1; index >= 0; index--) + { pending.Push((new AssetPath(mounts[index].id, string.Empty).ToString(), mounts[index].id.value, false, 1)); + } } } - while (pending.TryPop(out var next)) + while (pending.TryPop(out (string path, string label, bool root, int depth) next)) { AssetFileEntry? entry = null; if (!next.root && (!pipeline.TryGetFileSystemEntry(AssetPath.Parse(next.path), out entry) || entry is null)) + { continue; + } bool directory = next.root || entry!.isDirectory; - IReadOnlyList children = directory ? m_data.SortTreeEntries(m_data.GetVisibleChildren(next.path)) : Array.Empty(); + IReadOnlyList children = directory + ? m_data.SortTreeEntries(m_data.GetVisibleChildren(next.path)) + : Array.Empty(); string id = next.root ? "tree_root_" + next.path : "tree_" + next.path; if (ShouldOpenTreeEntry(next.path, next.root, directory)) + { widgets.SetTreeNodeOpen(id, true); + } RuntimeIdentity? identity = next.root ? null : entry!.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset tree entry requires a registered identity."); - rows.Add(new(next.path, next.label, id, next.depth, next.root, false, - !directory || !next.root && children.Count == 0, identity)); + rows.Add( + new BrowserTreeRow( + next.path, + next.label, + id, + next.depth, + next.root, + false, + !directory || !next.root && children.Count == 0, + identity + ) + ); if (!directory || !widgets.IsTreeNodeOpen(id)) + { continue; + } for (int index = children.Count - 1; index >= 0; index--) + { pending.Push((children[index].assetPath.ToString(), children[index].name, false, next.depth + 1)); + } } m_rows.Clear(); m_rows.AddRange(rows); @@ -107,10 +131,23 @@ private void RefreshRows() { m_navigationRows.Add(new TreeNavigationRow(row.identity)); if (row.identity is RuntimeIdentity identity) + { m_visibleSelection.Add(identity); + } } m_rowsRoot = m_assets.browser.root; m_sourceRevision = pipeline.revision; m_expansionRevision = widgets.treeExpansionRevision; } + + private readonly record struct BrowserTreeRow( + string path, + string label, + string nodeID, + int depth, + bool isRoot, + bool virtualRoot, + bool isLeaf, + RuntimeIdentity? identity + ); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs index 568aa0283..3bd38ce9c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs @@ -1,19 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserTree { private readonly FileBrowserData m_data; @@ -26,6 +30,7 @@ internal sealed partial class FileBrowserTree private bool m_currentDirectoryOpenRequest; private string m_currentDirectoryOpenTarget = string.Empty; private string? m_lastCurrentDirectoryOpenTarget; + internal FileBrowserTree( FileBrowserData data, FileBrowserNavigation navigation, @@ -42,6 +47,36 @@ AssetBrowserModule assets m_assets = assets; } + internal void PrepareOpenRequests() + { + BeginNavigation(); + string currentDirectory = NormalizePath(m_assets.browser.currentDirectory); + if (!m_currentDirectoryOpenRequest && !string.Equals(m_lastCurrentDirectoryOpenTarget, currentDirectory, StringComparison.Ordinal)) + { + m_currentDirectoryOpenTarget = currentDirectory; + m_currentDirectoryOpenRequest = true; + m_lastCurrentDirectoryOpenTarget = currentDirectory; + } + } + + internal void ClearOpenRequests() + { + m_rootOpenRequest = false; + m_currentDirectoryOpenRequest = false; + ClearNavigationFrame(); + } + + internal void RequestOpenRoot() => m_rootOpenRequest = true; + + internal void RequestOpenTreeToPath(string path) + { + string normalizedPath = NormalizePath(path); + string treePath = IsDirectoryPath(m_assets.edits.pipeline, normalizedPath) ? normalizedPath : GetParentDirectory(normalizedPath); + m_currentDirectoryOpenTarget = treePath; + m_currentDirectoryOpenRequest = true; + m_lastCurrentDirectoryOpenTarget = treePath; + } + private void DrawRow( EditorContext context, BrowserTreeRow row @@ -49,27 +84,37 @@ BrowserTreeRow row AssetFileEntry? entry = null; if (row.identity is { } identity) { - if (!m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? resolved) - || resolved is not AssetFileEntry current) - { - Ui.Dummy(new(1f, Ui.GetFrameHeight())); + if (!m_assets.edits.interactions.TryResolveIdentity(identity, out IdentityObject? resolved) + || resolved is not AssetFileEntry current + ) { + Gui.Dummy(new Vector2(1f, Gui.GetFrameHeight())); return; } entry = current; } bool selected = entry is not null && m_assets.edits.interactions.selection.Contains(entry); - bool currentDirectory = row.virtualRoot ? string.IsNullOrEmpty(m_assets.browser.currentDirectory) + bool currentDirectory = row.virtualRoot + ? string.IsNullOrEmpty(m_assets.browser.currentDirectory) : (entry?.isDirectory ?? row.isRoot) && string.Equals(m_assets.browser.currentDirectory, row.path, StringComparison.Ordinal) - && (m_assets.browser.root == AssetBrowserRoot.Assets) == (AssetPath.Parse(row.path).source == AssetSourceId.project); + && (m_assets.browser.root == AssetBrowserRoot.Assets) == (AssetPath.Parse(row.path).source == AssetSourceID.project); string icon = entry is { isDirectory: false } ? m_assets.GetIcon(entry) : m_assets.folderIcon; bool editing = !row.isRoot && m_rename.IsEditing(context, row.path, FileBrowserPresentation.Tree); TreeNodeResult result = EditorUI.current.widgets.TreeNode( - row.nodeId, - drawContext => DrawRowContent(context, row.nodeId, row.path, row.label, icon, currentDirectory, editing, drawContext.rowHeight), - new TreeNodeOptions { depth = row.depth, selected = selected, isLeaf = row.isLeaf, - requestFocus = RequestsKeyboardFocus(entry, row.isRoot), keepContentActive = editing }); + row.nodeID, + drawContext => DrawRowContent(context, row.nodeID, row.path, row.label, icon, currentDirectory, editing, drawContext.rowHeight), + new TreeNodeOptions + { + depth = row.depth, + selected = selected, + isLeaf = row.isLeaf, + requestFocus = RequestsKeyboardFocus(entry, row.isRoot), + keepContentActive = editing + } + ); if (!result.isSubmitted) + { return; + } if (entry is not null && result.isDoubleClicked) { m_rename.MarkInteraction(FileBrowserPresentation.Tree); @@ -82,13 +127,17 @@ BrowserTreeRow row m_pendingSelection = entry.identity.runtimeIdentity; } else if (row.isRoot && (result.isClicked || result.isDoubleClicked)) + { m_pendingRootNavigation = true; + } if (entry is not null && !editing) { m_dragDrop.DrawAssetSource(context, entry); m_contextMenu.DrawEntry(context, "##asset_tree_context_" + row.path, row.path, FileBrowserPresentation.Tree); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, row.path); + } } else if (row.isRoot && !row.virtualRoot) { @@ -114,37 +163,8 @@ float rowHeight } EditorUI.current.widgets.IconText(icon, string.Empty, false); - Ui.SameLine(0f, 0f); - m_rename.Draw(context, id, relativePath, FileBrowserPresentation.Tree, Ui.GetContentRegionAvailable().X, rowHeight); - } - - internal void PrepareOpenRequests() - { - BeginNavigation(); - string currentDirectory = NormalizePath(m_assets.browser.currentDirectory); - if (!m_currentDirectoryOpenRequest && !string.Equals(m_lastCurrentDirectoryOpenTarget, currentDirectory, StringComparison.Ordinal)) - { - m_currentDirectoryOpenTarget = currentDirectory; - m_currentDirectoryOpenRequest = true; - m_lastCurrentDirectoryOpenTarget = currentDirectory; - } - } - - internal void ClearOpenRequests() - { - m_rootOpenRequest = false; - m_currentDirectoryOpenRequest = false; - ClearNavigationFrame(); - } - - internal void RequestOpenRoot() => m_rootOpenRequest = true; - internal void RequestOpenTreeToPath(string path) - { - string normalizedPath = NormalizePath(path); - string treePath = IsDirectoryPath(m_assets.edits.pipeline, normalizedPath) ? normalizedPath : GetParentDirectory(normalizedPath); - m_currentDirectoryOpenTarget = treePath; - m_currentDirectoryOpenRequest = true; - m_lastCurrentDirectoryOpenTarget = treePath; + Gui.SameLine(0f, 0f); + m_rename.Draw(context, id, relativePath, FileBrowserPresentation.Tree, Gui.GetContentRegionAvailable().X, rowHeight); } private bool ShouldOpenTreeEntry( @@ -153,7 +173,9 @@ private bool ShouldOpenTreeEntry( bool isDirectory ) { if (!isDirectory) + { return false; + } if (isRoot) { if (string.IsNullOrEmpty(relativePath)) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs index 72d39922e..b46f0176e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.Globalization; @@ -8,67 +5,72 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal static class FileBrowserUtility { - internal static AssetBrowserStyle CurrentBrowserStyle => new(EditorUI.current.widgets.style); + internal static AssetBrowserStyle currentBrowserStyle => new(EditorUI.current.widgets.style); - internal readonly record struct BreadcrumbPart( - string label, - AssetBrowserRoot root, - string directory - ); internal static void PushBrowserStyle() { - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.contentText); - Ui.PushStyleColor((ImGuiCol.WindowBg), EditorPalette.collectionHeader); - Ui.PushStyleColor((ImGuiCol.ChildBg), EditorPalette.collectionHeader); - Ui.PushStyleColor((ImGuiCol.Border), EditorPalette.contentBorder); - Ui.PushStyleColor((ImGuiCol.TableHeaderBg), EditorPalette.collectionHeader); - Ui.PushStyleColor((ImGuiCol.TableBorderStrong), EditorPalette.contentBorder); - Ui.PushStyleColor((ImGuiCol.TableBorderLight), EditorPalette.contentBorderSoft); - Ui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); - Ui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); - Ui.PushStyleColor((ImGuiCol.Header), EditorPalette.contentAccent); - Ui.PushStyleColor((ImGuiCol.HeaderHovered), EditorPalette.contentAccent); - Ui.PushStyleColor((ImGuiCol.HeaderActive), EditorPalette.contentAccent); - Ui.PushStyleVar((ImGuiStyleVar.WindowPadding), CurrentBrowserStyle.windowPadding); - Ui.PushStyleVar((ImGuiStyleVar.ChildBorderSize), EditorUI.current.widgets.style.borderSize); - Ui.PushStyleVar((ImGuiStyleVar.CellPadding), CurrentBrowserStyle.cellPadding); - Ui.PushStyleVar((ImGuiStyleVar.ItemSpacing), CurrentBrowserStyle.itemSpacing); - Ui.PushStyleVar((ImGuiStyleVar.FrameRounding), CurrentBrowserStyle.frameRounding); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.contentText); + Gui.PushStyleColor((ImGuiCol.WindowBg), EditorPalette.collectionHeader); + Gui.PushStyleColor((ImGuiCol.ChildBg), EditorPalette.collectionHeader); + Gui.PushStyleColor((ImGuiCol.Border), EditorPalette.contentBorder); + Gui.PushStyleColor((ImGuiCol.TableHeaderBg), EditorPalette.collectionHeader); + Gui.PushStyleColor((ImGuiCol.TableBorderStrong), EditorPalette.contentBorder); + Gui.PushStyleColor((ImGuiCol.TableBorderLight), EditorPalette.contentBorderSoft); + Gui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); + Gui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); + Gui.PushStyleColor((ImGuiCol.Header), EditorPalette.contentAccent); + Gui.PushStyleColor((ImGuiCol.HeaderHovered), EditorPalette.contentAccent); + Gui.PushStyleColor((ImGuiCol.HeaderActive), EditorPalette.contentAccent); + Gui.PushStyleVar((ImGuiStyleVar.WindowPadding), currentBrowserStyle.windowPadding); + Gui.PushStyleVar((ImGuiStyleVar.ChildBorderSize), EditorUI.current.widgets.style.borderSize); + Gui.PushStyleVar((ImGuiStyleVar.CellPadding), currentBrowserStyle.cellPadding); + Gui.PushStyleVar((ImGuiStyleVar.ItemSpacing), currentBrowserStyle.itemSpacing); + Gui.PushStyleVar((ImGuiStyleVar.FrameRounding), currentBrowserStyle.frameRounding); } internal static void PopBrowserStyle() { - Ui.PopStyleVar(5); - Ui.PopStyleColor(12); + Gui.PopStyleVar(5); + Gui.PopStyleColor(12); } internal static void PushButtonColors(Vector4 color) { - Ui.PushStyleColor((ImGuiCol.Button), color); - Ui.PushStyleColor((ImGuiCol.ButtonHovered), EditorPalette.GetHovered(color)); - Ui.PushStyleColor((ImGuiCol.ButtonActive), EditorPalette.GetActive(color)); + Gui.PushStyleColor((ImGuiCol.Button), color); + Gui.PushStyleColor((ImGuiCol.ButtonHovered), EditorPalette.GetHovered(color)); + Gui.PushStyleColor((ImGuiCol.ButtonActive), EditorPalette.GetActive(color)); } internal static bool IsDirectoryPath( AssetPipeline assets, string relativePath ) => assets.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry) && entry.isDirectory; + internal static string GetDirectoryLabel( AssetBrowserRoot root, string relativePath ) { if (root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(relativePath)) + { return "Plugins"; + } AssetPath path = AssetPath.Parse(NormalizePath(relativePath)); if (string.IsNullOrEmpty(path.localPath)) + { return GetSourceRootLabel(path.source); + } string name = Path.GetFileName(path.localPath); return string.IsNullOrEmpty(name) ? GetSourceRootLabel(path.source) : name; } @@ -82,11 +84,17 @@ string currentDirectory string directory = GetLocalParent(entryPath.localPath); string result; if (entryPath.source != current.source) + { result = FormatSourcePath(entryPath.source, directory); + } else if (string.Equals(directory, current.localPath, StringComparison.Ordinal)) + { result = "~"; + } else if (string.IsNullOrEmpty(current.localPath)) + { result = string.IsNullOrEmpty(directory) ? "~" : $"~/{directory}"; + } else { string prefix = current.localPath + "/"; @@ -107,9 +115,13 @@ string currentDirectory internal static string GetTypeText(AssetFileEntry entry) { if (entry.isDirectory && AssetSample.HasSampleDirectoryName(entry.assetPath)) - return AssetSample.fileType.TrimStart('.').ToUpperInvariant(); + { + return AssetSample.C_FILE_TYPE.TrimStart('.').ToUpperInvariant(); + } if (entry.isDirectory) + { return "FOLDER"; + } string extension = string.IsNullOrEmpty(entry.extension) ? Path.GetExtension(entry.assetPath.localPath) : entry.extension; return string.IsNullOrEmpty(extension) ? "FILE" : extension.TrimStart('.').ToUpperInvariant(); } @@ -119,10 +131,12 @@ internal static IReadOnlyList BuildBreadcrumbParts( string relativePath ) { if (root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(relativePath)) + { return[new BreadcrumbPart("Plugins", AssetBrowserRoot.Plugins, string.Empty)]; + } AssetPath sourcePath = AssetPath.Parse(NormalizePath(relativePath)); string sourceRoot = new AssetPath(sourcePath.source, string.Empty).ToString(); - var parts = new List(); + List parts = []; if (root == AssetBrowserRoot.Plugins) { parts.Add(new BreadcrumbPart("Plugins", AssetBrowserRoot.Plugins, string.Empty)); @@ -134,7 +148,9 @@ string relativePath } if (string.IsNullOrEmpty(sourcePath.localPath)) + { return parts; + } string[] segments = sourcePath.localPath.Split('/', StringSplitOptions.RemoveEmptyEntries); string path = string.Empty; for (int i = 0; i < segments.Length; i++) @@ -150,7 +166,10 @@ internal static bool IsReadOnlyLocation( AssetPipeline assets, AssetBrowserState browser ) => browser.root == AssetBrowserRoot.Plugins || IsReadOnlySource(assets, browser.currentDirectory); - internal static string NormalizePath(string? path) => AssetPath.Parse(string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim()).ToString(); + + internal static string NormalizePath(string? path) + => AssetPath.Parse(string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim()).ToString(); + internal static string GetParentDirectory(string relativePath) { AssetPath path = AssetPath.Parse(NormalizePath(relativePath)); @@ -161,12 +180,14 @@ internal static bool IsReadOnlySource( AssetPipeline assets, string relativePath ) { - AssetSourceId source = AssetPath.Parse(NormalizePath(relativePath)).source; + AssetSourceID source = AssetPath.Parse(NormalizePath(relativePath)).source; for (int i = 0; i < assets.sourceMounts.Count; i++) { AssetSourceMount mount = assets.sourceMounts[i]; if (mount.id == source) + { return mount.isReadOnly; + } } return true; @@ -189,7 +210,9 @@ internal static string GetEditableName( bool isDirectory ) { if (isDirectory) + { return name; + } string extension = Path.GetExtension(name); return string.IsNullOrEmpty(extension) ? name : name[..^extension.Length]; } @@ -214,6 +237,7 @@ internal static string ComposeRenamedEntryName( string editedName, bool isDirectory ) => isDirectory ? editedName : editedName + Path.GetExtension(sourcePath); + internal static string[] FitTextToLines( string text, float maxWidth, @@ -221,17 +245,21 @@ int maxLines ) { ArgumentOutOfRangeException.ThrowIfLessThan(maxLines, 1); if (string.IsNullOrEmpty(text)) + { return[string.Empty]; + } List elements = []; TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(text); while (enumerator.MoveNext()) + { elements.Add(enumerator.GetTextElement()); - List lines = new(maxLines); + } + var lines = new List(maxLines); int offset = 0; for (int lineIndex = 0; lineIndex < maxLines && offset < elements.Count; lineIndex++) { string remaining = string.Concat(elements.GetRange(offset, elements.Count - offset)); - if (Ui.MeasureText(remaining).X <= maxWidth) + if (Gui.MeasureText(remaining).X <= maxWidth) { lines.Add(remaining); break; @@ -244,15 +272,17 @@ int maxLines while (offset + count < elements.Count) { string next = candidate + elements[offset + count]; - if (Ui.MeasureText(next + suffix).X > maxWidth) + if (Gui.MeasureText(next + suffix).X > maxWidth) + { break; + } candidate = next; count++; } if (count == 0) { - lines.Add(isLastLine && Ui.MeasureText("...").X <= maxWidth ? "..." : elements[offset]); + lines.Add(isLastLine && Gui.MeasureText("...").X <= maxWidth ? "..." : elements[offset]); offset++; continue; } @@ -271,23 +301,25 @@ string path AssetPath ancestor = AssetPath.Parse(NormalizePath(candidateAncestor)); AssetPath descendant = AssetPath.Parse(NormalizePath(path)); if (ancestor.source != descendant.source) + { return false; + } if (ancestor.localPath.Length == 0 || string.Equals(ancestor.localPath, descendant.localPath, StringComparison.Ordinal)) + { return true; + } return descendant.localPath.Length > ancestor.localPath.Length - && descendant.localPath.StartsWith( - ancestor.localPath, - StringComparison.Ordinal - ) - && descendant.localPath[ancestor.localPath.Length] == '/'; + && descendant.localPath.StartsWith(ancestor.localPath, StringComparison.Ordinal) + && descendant.localPath[ancestor.localPath.Length] == '/'; } - private static string GetSourceRootLabel(AssetSourceId source) => source == AssetSourceId.project ? "Assets" : source.value; + private static string GetSourceRootLabel(AssetSourceID source) => source == AssetSourceID.project ? "Assets" : source.value; + private static string FormatSourcePath( - AssetSourceId source, + AssetSourceID source, string localPath ) { - string root = source == AssetSourceId.project ? GetSourceRootLabel(source) : $"Plugins/{GetSourceRootLabel(source)}"; + string root = source == AssetSourceID.project ? GetSourceRootLabel(source) : $"Plugins/{GetSourceRootLabel(source)}"; return string.IsNullOrEmpty(localPath) ? root : $"{root}/{localPath}"; } @@ -296,4 +328,10 @@ private static string GetLocalParent(string localPath) int separator = localPath.LastIndexOf('/'); return separator < 0 ? string.Empty : localPath[..separator]; } + + internal readonly record struct BreadcrumbPart( + string label, + AssetBrowserRoot root, + string directory + ); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIDs.cs similarity index 91% rename from src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs rename to src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIDs.cs index 9a7526c75..68453b180 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIDs.cs @@ -2,7 +2,8 @@ using Inno.Editor.Assets.ImGui; namespace Inno.Editor.Panel.FileBrowser; -internal static class FileBrowserInteractionIds + +internal static class FileBrowserInteractionIDs { internal const string C_AREA = "panel/asset.file-browser"; internal const string C_CREATE_ASSET = "file-browser/create-asset"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs new file mode 100644 index 000000000..89f766930 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.FileBrowser; + +[EditorMenuSource(FileBrowserInteractionIDs.C_AREA)] +internal sealed class AssetCreationMenu(AssetBrowserModule assets) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + IReadOnlyList templates = assets.edits.creationTemplates; + var declaredGroups = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (AssetCreationMenuAttribute declaration in templates) + { + string[] segments = declaration.menuPath.Split('/'); + if (segments.Length > 1) + { + string topLevel = "Create/" + segments[0]; + if (declaredGroups.Add(topLevel)) + { + builder.AddGroup(topLevel, declaration.groupOrder, declaration.separatorBeforeGroup); + } + + for (int depth = 1; depth < segments.Length - 1; depth++) + { + string group = "Create/" + string.Join('/', segments.Take(depth + 1)); + if (declaredGroups.Add(group)) + { + builder.AddGroup(group, declaration.itemOrder); + } + } + } + + builder.Add( + "Create/" + declaration.menuPath, + FileBrowserInteractionIDs.C_CREATE_ASSET, + declaration.itemOrder, + argument: declaration.id + ); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs index ffb94a2c9..fcbfae46f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs @@ -1,15 +1,10 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_CREATE_ASSET, FileBrowserInteractionIds.C_AREA)] + +[EditorAction(FileBrowserInteractionIDs.C_CREATE_ASSET, FileBrowserInteractionIDs.C_AREA)] internal sealed class CreateAssetCommand(AssetBrowserModule assets) : EditorAction { /// @@ -21,10 +16,12 @@ internal sealed class CreateAssetCommand(AssetBrowserModule assets) : EditorActi /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => assets.edits.CanCreateAsset( - context.target, - context.argument - ) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => assets.edits.CanCreateAsset( + context.target, + context.argument + ) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -34,50 +31,8 @@ protected override EditorActionState Query(EditorActionContext c protected override void Execute(EditorActionContext context) { AssetFileEntry created = assets.edits.CreateAsset(context.target, context.argument); - _ = context.interactions.For(FileBrowserInteractionIds.C_AREA, created).Select(); - _ = context.interactions.For(FileBrowserInteractionIds.C_AREA, created).Execute(FileBrowserInteractionIds.C_RENAME); + _ = context.interactions.For(FileBrowserInteractionIDs.C_AREA, created).Select(); + _ = context.interactions.For(FileBrowserInteractionIDs.C_AREA, created).Execute(FileBrowserInteractionIDs.C_RENAME); context.interactions.OpenPanel("scene.inspector"); } } - -[EditorMenuSource(FileBrowserInteractionIds.C_AREA)] -internal sealed class AssetCreationMenu(AssetBrowserModule assets) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - IReadOnlyList templates = assets.edits.creationTemplates; - var declaredGroups = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (AssetCreationMenuAttribute declaration in templates) - { - string[] segments = declaration.menuPath.Split('/'); - if (segments.Length > 1) - { - string topLevel = "Create/" + segments[0]; - if (declaredGroups.Add(topLevel)) - { - builder.AddGroup(topLevel, declaration.groupOrder, declaration.separatorBeforeGroup); - } - - for (int depth = 1; depth < segments.Length - 1; depth++) - { - string group = "Create/" + string.Join('/', segments.Take(depth + 1)); - if (declaredGroups.Add(group)) - builder.AddGroup(group, declaration.itemOrder); - } - } - - builder.Add("Create/" + declaration.menuPath, FileBrowserInteractionIds.C_CREATE_ASSET, declaration.itemOrder, argument: declaration.id); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs index c63999f5d..b7e8078d6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs @@ -1,14 +1,15 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_CREATE_FOLDER, FileBrowserInteractionIds.C_AREA)] -[EditorMenu(FileBrowserInteractionIds.C_AREA, "Create/Folder", order: 100)] + +[EditorAction(FileBrowserInteractionIDs.C_CREATE_FOLDER, FileBrowserInteractionIDs.C_AREA)] +[EditorMenu(FileBrowserInteractionIDs.C_AREA, "Create/Folder", order: 100)] internal sealed class CreateAssetFolderCommand(AssetBrowserModule assets) : EditorAction { /// @@ -20,8 +21,10 @@ internal sealed class CreateAssetFolderCommand(AssetBrowserModule assets) : Edit /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => assets.edits.pipeline.isInitialized - && IsWritableDirectory(context.target) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => assets.edits.pipeline.isInitialized + && IsWritableDirectory(context.target) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -31,28 +34,29 @@ protected override EditorActionState Query(EditorActionContext context) protected override void Execute(EditorActionContext context) { AssetFileEntry target = assets.edits.CreateDirectory(AssetPath.Parse(context.target)); - EditorInteraction interaction = context.interactions.For(FileBrowserInteractionIds.C_AREA, target); + EditorInteraction interaction = context.interactions.For(FileBrowserInteractionIDs.C_AREA, target); _ = interaction.Select(); - _ = interaction.Execute(FileBrowserInteractionIds.C_RENAME); + _ = interaction.Execute(FileBrowserInteractionIDs.C_RENAME); } - private static string Combine( - string parent, - string name - ) => string.IsNullOrEmpty(parent) ? name : $"{parent}/{name}"; - private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); private bool IsWritableDirectory(string relativePath) { string normalized = Normalize(relativePath); - AssetSourceId source = AssetPath.Parse(normalized).source; + AssetSourceID source = AssetPath.Parse(normalized).source; AssetSourceMount? mount = assets.edits.pipeline.sourceMounts.FirstOrDefault(candidate => candidate.id == source); if (mount is null || mount.isReadOnly) + { return false; + } return string.IsNullOrEmpty(AssetPath.Parse(normalized).localPath) - || assets.edits.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(normalized), - out AssetFileEntry entry - ) - && entry.isDirectory; + || assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(normalized), out AssetFileEntry entry) + && entry.isDirectory; } + + private static string Combine( + string parent, + string name + ) => string.IsNullOrEmpty(parent) ? name : $"{parent}/{name}"; + + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs index eff199328..f5c602285 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs @@ -1,14 +1,15 @@ using System.Collections.Generic; +using Inno.Assets.Pipeline; +using Inno.Core.Input; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; -using Inno.Assets.Pipeline; using Inno.Editor.Interactions; -using Inno.Core.Input; namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_DELETE, priority: 100)] -[EditorMenu(FileBrowserInteractionIds.C_AREA, "Delete", order: 200)] -[EditorShortcut(FileBrowserInteractionIds.C_AREA, KeyCode.Delete)] + +[EditorAction(FileBrowserInteractionIDs.C_DELETE, priority: 100)] +[EditorMenu(FileBrowserInteractionIDs.C_AREA, "Delete", order: 200)] +[EditorShortcut(FileBrowserInteractionIDs.C_AREA, KeyCode.Delete)] internal sealed class DeleteAssetCommand(AssetBrowserModule assets) : EditorAction { /// @@ -41,8 +42,10 @@ protected override void Execute(EditorActionContext context) private static IReadOnlyList Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; - var values = new List(); + } + List values = []; context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs index fc4f2cc11..bf07f8723 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs @@ -1,13 +1,14 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_IMPORT_SAMPLE, FileBrowserInteractionIds.C_AREA)] -[EditorMenu(FileBrowserInteractionIds.C_AREA, "Import Sample", order: 120)] + +[EditorAction(FileBrowserInteractionIDs.C_IMPORT_SAMPLE, FileBrowserInteractionIDs.C_AREA)] +[EditorMenu(FileBrowserInteractionIDs.C_AREA, "Import Sample", order: 120)] internal sealed class ImportAssetSampleCommand( AssetBrowserModule assets, AssetSampleImportModule imports @@ -25,9 +26,13 @@ AssetSampleImportModule imports protected override EditorActionState Query(EditorActionContext context) { if (!context.target.isSample) + { return EditorActionState.hidden; + } if (!imports.canImport) + { return EditorActionState.disabled; + } try { AssetPath target = AssetPath.Project(AssetSample.GetImportName(context.target.assetPath)); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs index ac60f5765..b6ac5d393 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs @@ -1,32 +1,35 @@ using System.Collections.Generic; +using Inno.Assets.Pipeline; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; -using Inno.Assets.Pipeline; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + /// /// Moves directory drag payloads into File Browser directory targets. /// /// /// The assets used to initialize this instance. /// -[EditorDrop(FileBrowserInteractionIds.C_AREA, priority: 200)] +[EditorDrop(FileBrowserInteractionIDs.C_AREA, priority: 200)] internal sealed class MoveAssetEntryDropHandler(AssetBrowserModule assets) : EditorDrop { /// /// Evaluates the operation's current availability and presentation state. /// - /// - /// The validated editor drop status that represents the completed operation. - /// /// /// The context that supplies state and services for this operation. /// - protected override EditorDropStatus Query(EditorDropContext context) => assets.edits.CanMoveSelection( - SelectedSources(context), - context.target - ) ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + /// + /// The validated editor drop status that represents the completed operation. + /// + protected override EditorDropStatus Query(EditorDropContext context) + => assets.edits.CanMoveSelection( + SelectedSources(context), + context.target + ) ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + /// /// Validates and applies the current editor drag-and-drop interaction atomically. /// @@ -39,7 +42,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } assets.edits.MoveSelection(SelectedSources(context), context.target); return EditorDropResult.Accepted(context.source, context.target); } @@ -47,8 +52,10 @@ protected override EditorDropResult Drop(EditorDropContext SelectedSources(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; - var values = new List(); + } + List values = []; context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs index 98c547ef0..98262c542 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs @@ -1,11 +1,12 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_OPEN, FileBrowserInteractionIds.C_AREA, priority: 100)] + +[EditorAction(FileBrowserInteractionIDs.C_OPEN, FileBrowserInteractionIDs.C_AREA, priority: 100)] internal sealed class OpenAssetCommand(AssetBrowserModule assets) : EditorAction { /// @@ -20,7 +21,9 @@ internal sealed class OpenAssetCommand(AssetBrowserModule assets) : EditorAction protected override EditorActionState Query(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return EditorActionState.hidden; + } return assetContext.isDirectory ? EditorActionState.hidden : EditorActionState.enabled; } @@ -33,20 +36,18 @@ protected override EditorActionState Query(EditorActionContext c protected override void Execute(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return; + } if (assets.edits.pipeline.TryLoad( AssetPath.Parse(assetContext.relativePath), out AssetObject? asset ) && asset is not null - && context.interactions.For( - FileBrowserInteractionIds.C_AREA, - asset - ).Execute( - FileBrowserInteractionIds.C_OPEN, - assetContext.relativePath - )) - { + && context.interactions + .For(FileBrowserInteractionIDs.C_AREA, asset) + .Execute(FileBrowserInteractionIDs.C_OPEN, assetContext.relativePath) + ) { return; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs index 0eeae9549..05b4ed2b9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs @@ -1,18 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets.Pipeline; using Inno.Core.Input; using Inno.Core.Logging; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.Panel.FileBrowser; -[EditorAction(FileBrowserInteractionIds.C_RENAME, priority: 100)] -[EditorMenu(FileBrowserInteractionIds.C_AREA, "Rename", order: 100)] -[EditorShortcut(FileBrowserInteractionIds.C_AREA, KeyCode.F2)] + +[EditorAction(FileBrowserInteractionIDs.C_RENAME, priority: 100)] +[EditorMenu(FileBrowserInteractionIDs.C_AREA, "Rename", order: 100)] +[EditorShortcut(FileBrowserInteractionIDs.C_AREA, KeyCode.F2)] internal sealed class RenameAssetCommand( AssetBrowserModule assets, LogRouter logs @@ -21,6 +24,7 @@ LogRouter logs private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); private string m_buffer = string.Empty; private bool m_requestFocus; + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -30,11 +34,10 @@ LogRouter logs /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isReadOnly - && TryGetAssetContext( - context, - out _ - ) ? EditorActionState.enabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isReadOnly + && TryGetAssetContext(context, out _) ? EditorActionState.enabled : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -44,7 +47,9 @@ out _ protected override void Execute(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return; + } Activate(context); m_buffer = GetEditableName(assetContext.name, assetContext.isDirectory); m_requestFocus = true; @@ -62,7 +67,9 @@ protected override void Execute(EditorActionContext context) protected override bool Present(EditorActionContext context) { if (!TryResolveAsset(out AssetEditorContext? asset) || asset is null) + { return false; + } InlineRenamePresentation presentation = context.argument; InlineRenameResult result = EditorUI.current.widgets.InlineRename( presentation.id, @@ -85,7 +92,9 @@ protected override bool Present(EditorActionContext protected override void OnCompleted() => ClearState(); + /// /// Cancels the interaction without committing its pending value. /// protected override void OnCancelled() => ClearState(); + /// /// Cancels pending presentation state when its editor surface disappears. /// protected override void OnPresentationLost() => _ = TryCommit(keepActiveWhenInvalid: false); + private bool TryCommit(bool keepActiveWhenInvalid) { if (!TryResolveAsset(out AssetEditorContext? asset) || asset is null) @@ -115,9 +127,13 @@ private bool TryCommit(bool keepActiveWhenInvalid) { m_log.Write(LogLevel.Warn, "Asset rename was rejected: {0}", [validation.message]); if (keepActiveWhenInvalid) + { m_requestFocus = true; + } else + { Cancel(); + } return false; } @@ -130,7 +146,9 @@ private bool TryCommit(bool keepActiveWhenInvalid) private bool TryResolveAsset(out AssetEditorContext? asset) { asset = null; - return activeTarget is AssetFileEntry entry && activeEditorContext is { } editor && assets.edits.TryCreateContext(editor, entry.assetPath.ToString(), out asset); + return activeTarget is AssetFileEntry entry + && activeEditorContext is { } editor + && assets.edits.TryCreateContext(editor, entry.assetPath.ToString(), out asset); } private void ClearState() diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs index f7f5ed54a..36f09f4b8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs @@ -1,34 +1,48 @@ using System.Numerics; +using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Editor.Assets; + namespace Inno.Editor.Panel.FileBrowser; + [EditorModal("asset-sample-import.progress", "Importing Sample", order: 110)] internal sealed class AssetSampleImportModal(AssetSampleImportModule imports) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; - /// + + /// public override bool isVisible => imports.isBusy; - /// + + /// public override bool allowScrolling => false; - /// + + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = imports.progress; - m_operation = snapshot.operationId; - m_content = new(snapshot.status, snapshot.fraction, actionLabel: "Cancel", actionEnabled: !snapshot.cancellationRequested, cancelOnEscape: true); - m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); + AssetSampleImportProgress snapshot = imports.progress; + m_operation = snapshot.operationID; + m_content = new( + snapshot.status, + snapshot.fraction, + actionLabel: "Cancel", + actionEnabled: !snapshot.cancellationRequested, + cancelOnEscape: true + ); + m_layout = EditorUISession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } - /// + + /// protected override void OnDraw(EditorContext context) { - if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + if (EditorUISession.current.widgets.DrawDialog(m_content, m_layout)) + { imports.Cancel(m_operation); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs index ba83d4480..0c3713f94 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs @@ -2,9 +2,11 @@ using Inno.Core.Settings; using Inno.Editor.Settings; using Inno.Runtime; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.GameView; + [ProjectSettingPath("Project/Player/Presentation")] internal sealed class GamePresentationSetting : ProjectSettingEditor { @@ -12,6 +14,7 @@ internal sealed class GamePresentationSetting : ProjectSettingEditor public override string section => "Display"; + /// /// Gets the explanation shared by Game View and deployed Player presentation. /// @@ -26,21 +29,27 @@ internal sealed class GamePresentationSetting : ProjectSettingEditor /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Viewport Backgrounds"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -31,22 +36,27 @@ internal sealed class GameViewBackgroundSetting : EditorSetting protected override void OnDraw(EditorSettingObject setting) { Vector4 value = ReadVector(setting); - Ui.SetNextItemWidth(-1f); - if (Ui.ColorEditLinear4("##game_view_background", ref value)) + Gui.SetNextItemWidth(-1f); + if (Gui.ColorEditLinear4("##game_view_background", ref value)) + { setting.SetAsSingleArray("value", [value.X, value.Y, value.Z, value.W]); + } } internal static Vector4 Read(EditorSettings settings) => ReadVector(settings.Get(C_PATH)); + private static EditorSettingObject CreateDefault() { var result = new EditorSettingObject(); - result.SetAsSingleArray("value", S_DEFAULT); + result.SetAsSingleArray("value", DEFAULT); return result; } private static Vector4 ReadVector(EditorSettingObject setting) { - float[] values = setting.GetAsSingleArray("value", S_DEFAULT); - return values.Length == 4 ? new Vector4(values[0], values[1], values[2], values[3]) : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); + float[] values = setting.GetAsSingleArray("value", DEFAULT); + return values.Length == 4 + ? new Vector4(values[0], values[1], values[2], values[3]) + : new Vector4(DEFAULT[0], DEFAULT[1], DEFAULT[2], DEFAULT[3]); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs index 00544e39b..d95302bc8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs @@ -1,32 +1,35 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.References; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Settings; using Inno.Core.Input; +using Inno.Core.Settings; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.PlayMode; using Inno.Editor.Rendering; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.References; using Inno.Rendering; -using Inno.Runtime; -using Ui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Runtime; +using Inno.Runtime; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using EngineColor = Inno.Core.Mathematics.Color; +using EngineVector2 = Inno.Core.Mathematics.Vector2; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.GameView; + /// /// Presents the active Plugin provider for the open Game viewport purpose. /// [EditorPanel("rendering.game-view", "Game", order: 220, menuPath: "Viewports")] internal sealed class GameViewPanel : EditorPanel { - private IDisposable? m_settingsSubscription; private const string C_VIEWPORT_ID = "game-view"; - private static readonly EditorViewportKindId S_KIND = new("inno.editor.viewport.game"); - private static readonly Vector2 S_UNAVAILABLE_PADDING = new(48f, 32f); + private static readonly EditorViewportKindID KIND = new("inno.editor.viewport.game"); + private static readonly Vector2 UNAVAILABLE_PADDING = new(48f, 32f); private readonly EditorRenderingModule m_rendering; private readonly IEditorGameScenePresentation m_scenePresentation; private readonly IEditorPlayMode m_playMode; @@ -34,10 +37,12 @@ internal sealed class GameViewPanel : EditorPanel private readonly EditorGameInputCapture m_inputCapture; private readonly EditorSettings m_editorSettings; private readonly ProjectSettingsStore m_projectSettings; + private IDisposable? m_settingsSubscription; private Vector4 m_backgroundColor; private GamePresentationSettings m_presentation = new(); private long m_presentationRevision = -1; private bool m_leftPointerActive; + internal GameViewPanel( EditorRenderingModule rendering, IEditorGameScenePresentation scenePresentation, @@ -47,19 +52,27 @@ internal GameViewPanel( EditorSettings editorSettings, ProjectSettingsStore projectSettings ) { - m_rendering = rendering ?? throw new ArgumentNullException(nameof(rendering)); - m_scenePresentation = scenePresentation ?? throw new ArgumentNullException(nameof(scenePresentation)); - m_playMode = playMode ?? throw new ArgumentNullException(nameof(playMode)); - m_playModeLoop = playModeLoop ?? throw new ArgumentNullException(nameof(playModeLoop)); - m_inputCapture = inputCapture ?? throw new ArgumentNullException(nameof(inputCapture)); - m_editorSettings = editorSettings ?? throw new ArgumentNullException(nameof(editorSettings)); - m_projectSettings = projectSettings ?? throw new ArgumentNullException(nameof(projectSettings)); + ArgumentNullException.ThrowIfNull(rendering); + ArgumentNullException.ThrowIfNull(scenePresentation); + ArgumentNullException.ThrowIfNull(playMode); + ArgumentNullException.ThrowIfNull(playModeLoop); + ArgumentNullException.ThrowIfNull(inputCapture); + ArgumentNullException.ThrowIfNull(editorSettings); + ArgumentNullException.ThrowIfNull(projectSettings); + m_rendering = rendering; + m_scenePresentation = scenePresentation; + m_playMode = playMode; + m_playModeLoop = playModeLoop; + m_inputCapture = inputCapture; + m_editorSettings = editorSettings; + m_projectSettings = projectSettings; } /// /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Gets whether allow scrolling is enabled for this implementation. /// @@ -75,64 +88,88 @@ protected override void OnDraw(EditorContext context) { using IDisposable presentationScope = m_playModeLoop.EnterPresentationScope(); _ = context; - Vector2 available = Ui.GetContentRegionAvailable(); + Vector2 available = Gui.GetContentRegionAvailable(); if (available.X <= 0f || available.Y <= 0f) + { return; + } RefreshPresentationSettings(); - float framebufferScale = Ui.GetInput().framebufferScale.X; + float framebufferScale = Gui.GetInput().framebufferScale.X; if (!float.IsFinite(framebufferScale) || framebufferScale <= 0f) + { framebufferScale = 1f; + } GameViewportLayout layout = CalculateLayout(available, m_presentation, framebufferScale); m_rendering.SetPresentation( C_VIEWPORT_ID, - new EditorViewportPresentation(new Inno.Core.Mathematics.Color(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), framebufferScale) + new EditorViewportPresentation( + new EngineColor(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), + framebufferScale + ) ); m_rendering.SetContentScope(C_VIEWPORT_ID, CreateContentScope()); - Vector2 outputOrigin = Ui.GetCursorScreenPosition() + layout.offset; - Vector2 mouse = Ui.GetMousePos(); + Vector2 outputOrigin = Gui.GetCursorScreenPosition() + layout.offset; + Vector2 mouse = Gui.GetMousePos(); Vector2 local = mouse - outputOrigin; bool inside = local.X >= 0f && local.Y >= 0f && local.X < layout.size.X && local.Y < layout.size.Y; - var viewport = Ui.GetViewport(); - bool gameViewFocused = m_playMode.isPlaying && Ui.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows); - bool imageHovered = inside && Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows); + (uint id, Vector2 position) viewport = Gui.GetViewport(); + bool gameViewFocused = m_playMode.isPlaying && Gui.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows); + bool imageHovered = inside && Gui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows); bool focused = m_inputCapture.Report(viewport.id, outputOrigin - viewport.position, layout.size, gameViewFocused, imageHovered); bool acceptsPointer = focused && imageHovered; - if (!Ui.IsMouseButtonDown(ImGuiMouseButton.Left) && !Ui.IsMouseReleased(ImGuiMouseButton.Left)) + if (!Gui.IsMouseButtonDown(ImGuiMouseButton.Left) && !Gui.IsMouseReleased(ImGuiMouseButton.Left)) { m_leftPointerActive = false; } - bool leftPressed = acceptsPointer && Ui.IsMouseClicked(ImGuiMouseButton.Left); + bool leftPressed = acceptsPointer && Gui.IsMouseClicked(ImGuiMouseButton.Left); if (leftPressed) + { m_leftPointerActive = true; - bool leftReleased = m_leftPointerActive && Ui.IsMouseReleased(ImGuiMouseButton.Left); + } + bool leftReleased = m_leftPointerActive && Gui.IsMouseReleased(ImGuiMouseButton.Left); if (leftReleased || !focused) + { m_leftPointerActive = false; - var io = Ui.GetInput(); + } + EditorUIInput io = Gui.GetInput(); KeyModifier modifiers = KeyModifier.None; if (io.alt) + { modifiers |= KeyModifier.Alt; + } if (io.control) + { modifiers |= KeyModifier.Control; + } if (io.shift) + { modifiers |= KeyModifier.Shift; + } if (io.super) + { modifiers |= KeyModifier.Super; + } m_rendering.SetOutputInput( C_VIEWPORT_ID, - focused ? new RenderOutputInput( - new Inno.Core.Mathematics.Vector2(local.X * layout.pixelWidth / layout.size.X, local.Y * layout.pixelHeight / layout.size.Y), + focused + ? new RenderOutputInput( + new EngineVector2( + local.X * layout.pixelWidth / layout.size.X, + local.Y * layout.pixelHeight / layout.size.Y + ), acceptsPointer, - acceptsPointer ? new Inno.Core.Mathematics.Vector2(0f, io.wheel) : default, + acceptsPointer ? new EngineVector2(0f, io.wheel) : default, modifiers, [], [], leftPressed ? [MouseButton.Left] : [], leftReleased ? [MouseButton.Left] : [], [] - ) : RenderOutputInput.suspended + ) + : RenderOutputInput.suspended ); - if (!m_rendering.TrySubmit(S_KIND, C_VIEWPORT_ID, layout.pixelWidth, layout.pixelHeight, out EditorViewportOutput output)) + if (!m_rendering.TrySubmit(KIND, C_VIEWPORT_ID, layout.pixelWidth, layout.pixelHeight, out EditorViewportOutput output)) { DrawUnavailable(available, m_rendering.GetCompositionError(C_VIEWPORT_ID) ?? "No rendering model contributes to Game View."); return; @@ -144,16 +181,21 @@ protected override void OnDraw(EditorContext context) return; } - Vector2 origin = Ui.GetCursorScreenPosition(); + Vector2 origin = Gui.GetCursorScreenPosition(); if (m_presentation.preserveAspectRatio) { - Ui.DrawFilledRectangle(origin, origin + available, Ui.ToPackedColor(new Vector4(0f, 0f, 0f, EditorPalette.opacityOpaque)), 0); + Gui.DrawFilledRectangle( + origin, + origin + available, + Gui.ToPackedColor(new Vector4(0f, 0f, 0f, EditorPalette.C_OPACITY_OPAQUE)), + 0 + ); } - Ui.SetCursorScreenPosition(origin + layout.offset); + Gui.SetCursorScreenPosition(origin + layout.offset); m_rendering.Draw(output, layout.size); - Ui.SetCursorScreenPosition(origin); - Ui.Dummy(available); + Gui.SetCursorScreenPosition(origin); + Gui.Dummy(available); } /// @@ -186,14 +228,36 @@ protected override void OnDetach(EditorContext context) } private void ApplyEditorSettings(EditorSettings settings) => m_backgroundColor = GameViewBackgroundSetting.Read(settings); + private void RefreshPresentationSettings() { if (m_presentationRevision == m_projectSettings.revision) + { return; - m_presentation = m_projectSettings.Get(GamePresentationSettings.settingId); + } + m_presentation = m_projectSettings.Get(GamePresentationSettings.settingID); m_presentationRevision = m_projectSettings.revision; } + private ContentReadScope CreateContentScope() => m_scenePresentation.Capture(); + + private void DrawUnavailable( + Vector2 size, + string message + ) { + Vector2 minimum = Gui.GetCursorScreenPosition(); + Gui.DrawFilledRectangle(minimum, minimum + size, Gui.ToPackedColor(m_backgroundColor), 0); + Gui.PushStyleColor(ImGuiCol.Text, EditorPalette.textDisabled); + try + { + EditorUI.current.widgets.CenteredWrappedText(message, size, UNAVAILABLE_PADDING); + } + finally + { + Gui.PopStyleColor(); + } + } + private static GameViewportLayout CalculateLayout( Vector2 available, GamePresentationSettings presentation, @@ -210,24 +274,6 @@ float framebufferScale ); } - private ContentReadScope CreateContentScope() => m_scenePresentation.Capture(); - private void DrawUnavailable( - Vector2 size, - string message - ) { - Vector2 minimum = Ui.GetCursorScreenPosition(); - Ui.DrawFilledRectangle(minimum, minimum + size, Ui.ToPackedColor(m_backgroundColor), 0); - Ui.PushStyleColor(ImGuiCol.Text, EditorPalette.textDisabled); - try - { - EditorUI.current.widgets.CenteredWrappedText(message, size, S_UNAVAILABLE_PADDING); - } - finally - { - Ui.PopStyleColor(); - } - } - private readonly record struct GameViewportLayout( Vector2 offset, Vector2 size, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIDs.cs similarity index 95% rename from src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIds.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIDs.cs index 1762e4839..948bde83e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/HierarchyInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Panel.Hierarchy; -internal static class HierarchyInteractionIds +internal static class HierarchyInteractionIDs { internal const string C_AREA = "panel/scene.hierarchy"; internal const string C_FILE_BROWSER_AREA = "panel/asset.file-browser"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs index 9a2a62da8..197e85ee4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs @@ -4,8 +4,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_CREATE_CHILD)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Create/Empty Child", order: 100)] +[EditorAction(HierarchyInteractionIDs.C_CREATE_CHILD)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Create/Empty Child", order: 100)] internal sealed class CreateChildGameObjectCommand(SceneEdits edits) : EditorAction { /// @@ -19,8 +19,8 @@ internal sealed class CreateChildGameObjectCommand(SceneEdits edits) : EditorAct /// protected override EditorActionState Query(EditorActionContext context) => context.target.isRuntimeValid - ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled - : EditorActionState.hidden; + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -31,8 +31,8 @@ protected override EditorActionState Query(EditorActionContext conte protected override void Execute(EditorActionContext context) { GameObject child = edits.CreateGameObject(context.target.scene, context.target.transform); - EditorInteraction interaction = context.interactions.For(HierarchyInteractionIds.C_AREA, child); + EditorInteraction interaction = context.interactions.For(HierarchyInteractionIDs.C_AREA, child); _ = interaction.Select(); - _ = interaction.Execute(HierarchyInteractionIds.C_RENAME); + _ = interaction.Execute(HierarchyInteractionIDs.C_RENAME); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs index e5176f2dd..f05a97b32 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs @@ -4,8 +4,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_CREATE_GAME_OBJECT)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Create/Empty GameObject", order: 200)] +[EditorAction(HierarchyInteractionIDs.C_CREATE_GAME_OBJECT)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Create/Empty GameObject", order: 200)] internal sealed class CreateGameObjectCommand(SceneEdits edits) : EditorAction { /// @@ -19,8 +19,8 @@ internal sealed class CreateGameObjectCommand(SceneEdits edits) : EditorAction protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded - ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled - : EditorActionState.hidden; + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -31,8 +31,8 @@ protected override EditorActionState Query(EditorActionContext contex protected override void Execute(EditorActionContext context) { GameObject created = edits.CreateGameObject(context.target); - EditorInteraction interaction = context.interactions.For(HierarchyInteractionIds.C_AREA, created); + EditorInteraction interaction = context.interactions.For(HierarchyInteractionIDs.C_AREA, created); _ = interaction.Select(); - _ = interaction.Execute(HierarchyInteractionIds.C_RENAME); + _ = interaction.Execute(HierarchyInteractionIDs.C_RENAME); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateSceneCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateSceneCommand.cs index a0849f3b7..7078ebd03 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateSceneCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateSceneCommand.cs @@ -4,8 +4,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_CREATE_SCENE)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Create/Scene", order: 300)] +[EditorAction(HierarchyInteractionIDs.C_CREATE_SCENE)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Create/Scene", order: 300)] internal sealed class CreateSceneCommand(SceneEdits edits) : EditorAction { /// @@ -17,8 +17,8 @@ internal sealed class CreateSceneCommand(SceneEdits edits) : EditorAction protected override void Execute(EditorActionContext context) { GameScene scene = edits.CreateScene(); - EditorInteraction interaction = context.interactions.For(HierarchyInteractionIds.C_AREA, scene); + EditorInteraction interaction = context.interactions.For(HierarchyInteractionIDs.C_AREA, scene); _ = interaction.Select(); - _ = interaction.Execute(HierarchyInteractionIds.C_RENAME); + _ = interaction.Execute(HierarchyInteractionIDs.C_RENAME); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs index 1f7a00942..5ac112d30 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs @@ -1,14 +1,15 @@ using System.Collections.Generic; using System.Linq; +using Inno.Core.Input; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Core.Input; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_DELETE_GAME_OBJECT, priority: 100)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Delete", order: 300)] -[EditorShortcut(HierarchyInteractionIds.C_AREA, KeyCode.Delete)] + +[EditorAction(HierarchyInteractionIDs.C_DELETE_GAME_OBJECT, priority: 100)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Delete", order: 300)] +[EditorShortcut(HierarchyInteractionIDs.C_AREA, KeyCode.Delete)] internal sealed class DeleteGameObjectCommand(SceneEdits edits) : EditorAction { /// @@ -23,14 +24,16 @@ internal sealed class DeleteGameObjectCommand(SceneEdits edits) : EditorAction context) { if (!context.target.isRuntimeValid) + { return EditorActionState.hidden; + } GameObject[] targets = Targets(context); return targets.Length != 0 - && targets.All(edits.CanEdit) ? EditorActionState.enabled : new EditorActionState( - isVisible: true, - isEnabled: false, - unavailableReason: "Every selected object must belong to an editable scene." - ); + && targets.All(edits.CanEdit) ? EditorActionState.enabled : new EditorActionState( + isVisible: true, + isEnabled: false, + unavailableReason: "Every selected object must belong to an editable scene." + ); } /// @@ -48,8 +51,10 @@ protected override void Execute(EditorActionContext context) private static GameObject[] Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; - var values = new List(); + } + List values = []; context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs index 6862e08af..325ea336c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; @@ -21,7 +19,8 @@ public sealed class HierarchyObjectDropTarget /// public HierarchyObjectDropTarget(GameObject gameObject) { - this.gameObject = gameObject ?? throw new ArgumentNullException(nameof(gameObject)); + ArgumentNullException.ThrowIfNull(gameObject); + this.gameObject = gameObject; } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs index b90b9e523..a85523a75 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; @@ -21,7 +19,8 @@ public sealed class HierarchySceneDropTarget /// public HierarchySceneDropTarget(GameScene scene) { - this.scene = scene ?? throw new ArgumentNullException(nameof(scene)); + ArgumentNullException.ThrowIfNull(scene); + this.scene = scene; } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs index 199fabba1..c7ebedb10 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs @@ -1,13 +1,12 @@ using System; - using Inno.Assets.Pipeline; using Inno.Editor.Interactions; using Inno.Editor.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_INSTANTIATE_PREFAB_ASSET, priority: 200)] -[EditorMenu(HierarchyInteractionIds.C_FILE_BROWSER_AREA, "Instantiate", order: 40)] +[EditorAction(HierarchyInteractionIDs.C_INSTANTIATE_PREFAB_ASSET, priority: 200)] +[EditorMenu(HierarchyInteractionIDs.C_FILE_BROWSER_AREA, "Instantiate", order: 40)] internal sealed class InstantiatePrefabAssetCommand(IEditorSceneWorkspace workspace) : EditorAction { /// @@ -20,11 +19,11 @@ internal sealed class InstantiatePrefabAssetCommand(IEditorSceneWorkspace worksp /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => string.Equals(context.target.extension, ".iprefab", StringComparison.OrdinalIgnoreCase) - ? workspace.canPersist && workspace.activeScene is { } scene && workspace.CanEdit(scene) - ? EditorActionState.enabled - : EditorActionState.disabled - : EditorActionState.hidden; + => string.Equals(context.target.extension, ".iprefab", StringComparison.OrdinalIgnoreCase) + ? workspace.canPersist && workspace.activeScene is { } scene && workspace.CanEdit(scene) + ? EditorActionState.enabled + : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,7 +32,7 @@ protected override EditorActionState Query(EditorActionContext c /// The operation scope that provides state, services, and ownership boundaries. /// protected override void Execute(EditorActionContext context) - => _ = context.interactions - .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) - .Execute(HierarchyInteractionIds.C_OPEN); + => _ = context.interactions + .For(HierarchyInteractionIDs.C_FILE_BROWSER_AREA, context.target) + .Execute(HierarchyInteractionIDs.C_OPEN); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs index eb6ecbf88..f196f483d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs @@ -1,13 +1,12 @@ using System; - using Inno.Assets.Pipeline; using Inno.Editor.Interactions; using Inno.Editor.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_LOAD_SCENE_ASSET, priority: 200)] -[EditorMenu(HierarchyInteractionIds.C_FILE_BROWSER_AREA, "Load", order: 40)] +[EditorAction(HierarchyInteractionIDs.C_LOAD_SCENE_ASSET, priority: 200)] +[EditorMenu(HierarchyInteractionIDs.C_FILE_BROWSER_AREA, "Load", order: 40)] internal sealed class LoadSceneAssetCommand(IEditorSceneWorkspace workspace) : EditorAction { /// @@ -20,11 +19,11 @@ internal sealed class LoadSceneAssetCommand(IEditorSceneWorkspace workspace) : E /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => string.Equals(context.target.extension, ".iscene", StringComparison.OrdinalIgnoreCase) - ? workspace.canPersist - ? EditorActionState.enabled - : EditorActionState.disabled - : EditorActionState.hidden; + => string.Equals(context.target.extension, ".iscene", StringComparison.OrdinalIgnoreCase) + ? workspace.canPersist + ? EditorActionState.enabled + : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,7 +32,7 @@ protected override EditorActionState Query(EditorActionContext c /// The operation scope that provides state, services, and ownership boundaries. /// protected override void Execute(EditorActionContext context) - => _ = context.interactions - .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) - .Execute(HierarchyInteractionIds.C_OPEN); + => _ = context.interactions + .For(HierarchyInteractionIDs.C_FILE_BROWSER_AREA, context.target) + .Execute(HierarchyInteractionIDs.C_OPEN); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs index fbb131719..063dcbe58 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs @@ -7,7 +7,8 @@ using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorDrop(HierarchyInteractionIds.C_AREA)] + +[EditorDrop(HierarchyInteractionIDs.C_AREA)] internal sealed class MoveGameObjectToSceneDropHandler(SceneEdits edits) : EditorDrop { /// @@ -24,9 +25,9 @@ protected override EditorDropStatus Query(EditorDropContext 0 - && sources.All(value => value.isRuntimeValid && edits.CanEdit(value)) - && edits.CanEdit(target) - && target is { isLoaded: true, isDestroyed: false } ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + && sources.All(value => value.isRuntimeValid && edits.CanEdit(value)) + && edits.CanEdit(target) + && target is { isLoaded: true, isDestroyed: false } ? EditorDropStatus.Accept() : EditorDropStatus.rejected; } /// @@ -41,7 +42,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } edits.MoveGameObjects(SelectedSources(context), context.target.scene); return EditorDropResult.Accepted(context.source, context.target); } @@ -49,8 +52,10 @@ protected override EditorDropResult Drop(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; - var values = new List(); + } + List values = []; context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs index 1c0f076bf..05f9dba86 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs @@ -4,7 +4,7 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_OPEN, priority: 200)] +[EditorAction(HierarchyInteractionIDs.C_OPEN, priority: 200)] internal sealed class OpenPrefabAssetAction( IEditorSceneWorkspace workspace, SceneEdits edits @@ -20,9 +20,9 @@ SceneEdits edits /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => workspace.canPersist && workspace.activeScene is not null - ? EditorActionState.enabled - : EditorActionState.disabled; + => workspace.canPersist && workspace.activeScene is not null + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Applies the editor action to the supplied interaction context. @@ -34,8 +34,10 @@ protected override void Execute(EditorActionContext context { GameScene? scene = workspace.activeScene; if (scene is null) + { return; + } GameObject instance = edits.InstantiatePrefab(context.target, scene); - _ = context.interactions.For(HierarchyInteractionIds.C_AREA, instance).Select(); + _ = context.interactions.For(HierarchyInteractionIDs.C_AREA, instance).Select(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs index c569191d3..d65a6065b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs @@ -4,7 +4,7 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_OPEN, priority: 200)] +[EditorAction(HierarchyInteractionIDs.C_OPEN, priority: 200)] internal sealed class OpenSceneAssetAction(IEditorSceneWorkspace workspace) : EditorAction { /// @@ -17,9 +17,9 @@ internal sealed class OpenSceneAssetAction(IEditorSceneWorkspace workspace) : Ed /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => workspace.canPersist - ? EditorActionState.enabled - : EditorActionState.disabled; + => workspace.canPersist + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Executes the prepared operation and publishes only a completed result. @@ -30,6 +30,6 @@ protected override EditorActionState Query(EditorActionContext context) { GameScene scene = workspace.Open(context.argument); - _ = context.interactions.For(HierarchyInteractionIds.C_AREA, scene).Select(); + _ = context.interactions.For(HierarchyInteractionIDs.C_AREA, scene).Select(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs index 5bae41e51..5fadf1c84 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs @@ -1,20 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Input; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; -using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_RENAME, priority: 100)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Rename", order: 200)] -[EditorShortcut(HierarchyInteractionIds.C_AREA, KeyCode.F2)] + +[EditorAction(HierarchyInteractionIDs.C_RENAME, priority: 100)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Rename", order: 200)] +[EditorShortcut(HierarchyInteractionIDs.C_AREA, KeyCode.F2)] internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPresentationAction { private string m_buffer = string.Empty; private bool m_requestFocus; private string m_originalName = string.Empty; + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -24,7 +27,11 @@ internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPre /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => IsAvailable(context.target) ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => IsAvailable(context.target) + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -34,7 +41,9 @@ internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPre protected override void Execute(EditorActionContext context) { if (!TryGetName(context.target, out string name)) + { return; + } Activate(context); m_buffer = name; m_originalName = name; @@ -53,7 +62,9 @@ protected override void Execute(EditorActionContext context) protected override bool Present(EditorActionContext context) { if (activeTarget is not EngineObject target) + { return false; + } InlineRenamePresentation presentation = context.argument; InlineRenameResult result = EditorUI.current.widgets.InlineRename( presentation.id, @@ -70,7 +81,9 @@ protected override bool Present(EditorActionContext protected override void OnCompleted() => ClearState(); + /// /// Cancels the interaction without committing its pending value. /// protected override void OnCancelled() => ClearState(); + /// /// Cancels pending presentation state when its editor surface disappears. /// @@ -99,7 +114,9 @@ protected override void OnPresentationLost() private void CommitName() { if (activeTarget is not EngineObject target) + { return; + } string fallback = target is GameScene ? "Scene" : "GameObject"; string name = string.IsNullOrWhiteSpace(m_buffer) ? fallback : m_buffer.Trim(); if (!string.Equals(m_originalName, name, StringComparison.Ordinal)) @@ -125,12 +142,14 @@ private void ClearState() m_originalName = string.Empty; } - private static bool IsAvailable(EngineObject target) => target switch + private static bool IsAvailable(EngineObject target) + => target switch { GameScene scene => scene.isLoaded && !scene.isDestroyed, GameObject gameObject => gameObject.isRuntimeValid, _ => false }; + private static bool TryGetName( EngineObject target, out string name diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs index 7b16b46fe..6c4cc8b8f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs @@ -1,5 +1,5 @@ using System; - +using System.Collections.Generic; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -7,12 +7,11 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorDrop(HierarchyInteractionIds.C_AREA)] +[EditorDrop(HierarchyInteractionIDs.C_AREA)] internal sealed class ReorderSceneDropHandler( IEditorSceneWorkspace workspace, SceneEdits edits -) - : EditorDrop +) : EditorDrop { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -28,11 +27,14 @@ protected override EditorDropStatus Query(EditorDropContext @@ -52,20 +54,24 @@ protected override EditorDropResult Drop(EditorDropContext scenes, + IReadOnlyList scenes, GameScene scene ) { for (int index = 0; index < scenes.Count; index++) { if (ReferenceEquals(scenes[index], scene)) + { return index; + } } throw new InvalidOperationException("Only a loaded scene can be reordered."); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReparentGameObjectDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReparentGameObjectDropHandler.cs index 041664d6e..9e2a94e5e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReparentGameObjectDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReparentGameObjectDropHandler.cs @@ -8,7 +8,8 @@ using Inno.Scene.Components; namespace Inno.Editor.Panel.Hierarchy; -[EditorDrop(HierarchyInteractionIds.C_AREA)] + +[EditorDrop(HierarchyInteractionIDs.C_AREA)] internal sealed class ReparentGameObjectDropHandler(SceneEdits edits) : EditorDrop { /// @@ -24,20 +25,33 @@ protected override EditorDropStatus Query(EditorDropContext !value.isRuntimeValid || !edits.CanEdit(value))) + if (sources.Length == 0 + || !target.isRuntimeValid + || !edits.CanEdit(target) + || sources.Any(value => !value.isRuntimeValid || !edits.CanEdit(value)) + ) { return EditorDropStatus.rejected; + } Transform? parent = context.placement == EditorDropPlacement.Into ? target.transform : target.transform.parent; for (Transform? ancestor = parent; ancestor is not null; ancestor = ancestor.parent) + { if (sources.Any(value => ReferenceEquals(value.transform, ancestor))) + { return EditorDropStatus.rejected; + } + } if (sources.Contains(target)) - return EditorDropStatus.rejected; - return EditorDropStatus.Accept(context.placement switch { - EditorDropPlacement.Before => EditorDropVisual.InsertBefore, - EditorDropPlacement.After => EditorDropVisual.InsertAfter, - _ => EditorDropVisual.Highlight - }); + return EditorDropStatus.rejected; + } + return EditorDropStatus.Accept( + context.placement switch + { + EditorDropPlacement.Before => EditorDropVisual.InsertBefore, + EditorDropPlacement.After => EditorDropVisual.InsertAfter, + _ => EditorDropVisual.Highlight + } + ); } /// @@ -52,7 +66,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } GameObject target = context.target.gameObject; GameObject[] sources = SelectedSources(context); Transform? parent = context.placement == EditorDropPlacement.Into ? target.transform : target.transform.parent; @@ -60,9 +76,17 @@ protected override EditorDropResult Drop(EditorDropContext ReferenceEquals(value.transform.parent, parent) && ReferenceEquals(value.scene, target.scene) && value.transform.siblingIndex < target.transform.siblingIndex); + insertionIndex -= sources.Count( + value => ( + ReferenceEquals(value.transform.parent, parent) + && ReferenceEquals(value.scene, target.scene) + && value.transform.siblingIndex < target.transform.siblingIndex + ) + ); if (context.placement == EditorDropPlacement.After) + { insertionIndex++; + } } edits.MoveGameObjects(sources, target.scene, parent?.gameObject, insertionIndex); @@ -72,8 +96,10 @@ protected override EditorDropResult Drop(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; - var values = new List(); + } + List values = []; context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs index 139fef8ab..fb374bd05 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; -using Inno.Core.Logging; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_SAVE)] -[EditorMenu(HierarchyInteractionIds.C_MAIN_MENU_AREA, "File/Save", order: 100)] + +[EditorAction(HierarchyInteractionIDs.C_SAVE)] +[EditorMenu(HierarchyInteractionIDs.C_MAIN_MENU_AREA, "File/Save", order: 100)] [EditorShortcut(KeyCode.S, primary: true)] internal sealed class SaveCommand( IEditorSceneWorkspace workspace, @@ -16,6 +17,7 @@ LogRouter logs ) : EditorAction { private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -25,8 +27,10 @@ LogRouter logs /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => workspace.canPersist - && workspace.activeScene is not null ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => workspace.canPersist + && workspace.activeScene is not null ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs index b3c0c56ac..c472addef 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs @@ -1,6 +1,6 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -8,9 +8,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorDrop(HierarchyInteractionIds.C_FILE_BROWSER_AREA)] -internal sealed class SavePrefabAssetDropHandler - : EditorDrop +[EditorDrop(HierarchyInteractionIDs.C_FILE_BROWSER_AREA)] +internal sealed class SavePrefabAssetDropHandler : EditorDrop { private readonly IEditorSceneWorkspace m_workspace; private readonly AssetPipeline m_assets; @@ -19,8 +18,10 @@ internal SavePrefabAssetDropHandler( IEditorSceneWorkspace workspace, AssetPipeline assets ) { - m_workspace = workspace ?? throw new System.ArgumentNullException(nameof(workspace)); - m_assets = assets ?? throw new System.ArgumentNullException(nameof(assets)); + ArgumentNullException.ThrowIfNull(workspace); + ArgumentNullException.ThrowIfNull(assets); + m_workspace = workspace; + m_assets = assets; } /// @@ -34,8 +35,8 @@ AssetPipeline assets /// protected override EditorDropStatus Query(EditorDropContext context) => m_workspace.canPersist && context.source.isRuntimeValid - ? EditorDropStatus.Accept() - : EditorDropStatus.rejected; + ? EditorDropStatus.Accept() + : EditorDropStatus.rejected; /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -50,7 +51,9 @@ protected override EditorDropResult Drop(EditorDropContext c { string path = m_workspace.SavePrefab(context.source, context.target); if (!m_assets.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry selection)) + { return EditorDropResult.rejected; + } _ = context.interactions.For(context.area, selection).Select(); return EditorDropResult.Accepted(selection); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs index 5c655fbf5..240c3b66f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs @@ -1,6 +1,6 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -8,9 +8,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorDrop(HierarchyInteractionIds.C_FILE_BROWSER_AREA)] -internal sealed class SaveSceneAssetDropHandler - : EditorDrop +[EditorDrop(HierarchyInteractionIDs.C_FILE_BROWSER_AREA)] +internal sealed class SaveSceneAssetDropHandler : EditorDrop { private readonly IEditorSceneWorkspace m_workspace; private readonly AssetPipeline m_assets; @@ -19,8 +18,10 @@ internal SaveSceneAssetDropHandler( IEditorSceneWorkspace workspace, AssetPipeline assets ) { - m_workspace = workspace ?? throw new System.ArgumentNullException(nameof(workspace)); - m_assets = assets ?? throw new System.ArgumentNullException(nameof(assets)); + ArgumentNullException.ThrowIfNull(workspace); + ArgumentNullException.ThrowIfNull(assets); + m_workspace = workspace; + m_assets = assets; } /// @@ -34,8 +35,8 @@ AssetPipeline assets /// protected override EditorDropStatus Query(EditorDropContext context) => m_workspace.canPersist && context.source.isLoaded - ? EditorDropStatus.Accept() - : EditorDropStatus.rejected; + ? EditorDropStatus.Accept() + : EditorDropStatus.rejected; /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -50,7 +51,9 @@ protected override EditorDropResult Drop(EditorDropContext co { string path = m_workspace.SaveToDirectory(context.source, context.target); if (!m_assets.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry selection)) + { return EditorDropResult.rejected; + } _ = context.interactions.For(context.area, selection).Select(); return EditorDropResult.Accepted(selection); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs index d7104e693..479592759 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs @@ -4,8 +4,8 @@ namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_SET_ACTIVE_SCENE)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Set Active Scene", order: 100)] +[EditorAction(HierarchyInteractionIDs.C_SET_ACTIVE_SCENE)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Set Active Scene", order: 100)] internal sealed class SetActiveSceneCommand(IEditorSceneWorkspace workspace) : EditorAction { /// @@ -19,8 +19,8 @@ internal sealed class SetActiveSceneCommand(IEditorSceneWorkspace workspace) : E /// protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded - ? new EditorActionState(true, !ReferenceEquals(context.target, workspace.activeScene)) - : EditorActionState.hidden; + ? new EditorActionState(true, !ReferenceEquals(context.target, workspace.activeScene)) + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs index 984ebe360..c48819c96 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs @@ -1,13 +1,13 @@ +using Inno.Core.Input; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Core.Input; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; -[EditorAction(HierarchyInteractionIds.C_UNLOAD_SCENE, priority: 100)] -[EditorMenu(HierarchyInteractionIds.C_AREA, "Unload", order: 400, separatorBefore: true)] -[EditorShortcut(HierarchyInteractionIds.C_AREA, KeyCode.Delete)] +[EditorAction(HierarchyInteractionIDs.C_UNLOAD_SCENE, priority: 100)] +[EditorMenu(HierarchyInteractionIDs.C_AREA, "Unload", order: 400, separatorBefore: true)] +[EditorShortcut(HierarchyInteractionIDs.C_AREA, KeyCode.Delete)] internal sealed class UnloadSceneCommand(SceneEdits edits) : EditorAction { /// @@ -21,8 +21,8 @@ internal sealed class UnloadSceneCommand(SceneEdits edits) : EditorAction protected override EditorActionState Query(EditorActionContext context) => context.target is { isLoaded: true, isDestroyed: false } - ? EditorActionState.enabled - : EditorActionState.disabled; + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,8 +33,12 @@ protected override EditorActionState Query(EditorActionContext contex protected override void Execute(EditorActionContext context) { if (!edits.CloseScene(context.target)) + { return; + } if (context.interactions.selection.TryGet(out GameScene? selected) && ReferenceEquals(selected, context.target)) + { _ = context.interactions.For(context.area).Select(); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs index 2c9913245..b1abf73f6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs @@ -1,19 +1,22 @@ -using UiDrawing = Inno.Editor.ImGui.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using GuiDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + internal sealed class HierarchyDropVisual { internal EditorDropPlacement GetScenePlacement( in TreeNodeResult result, float mouseY ) => mouseY >= (result.min.Y + result.max.Y) * 0.5f ? EditorDropPlacement.After : EditorDropPlacement.Before; + internal EditorDropPlacement GetObjectPlacement( in TreeNodeResult result, float mouseY @@ -21,7 +24,9 @@ float mouseY float height = MathF.Max(1f, result.max.Y - result.min.Y); float relativeY = (mouseY - result.min.Y) / height; if (relativeY < 0.25f) + { return EditorDropPlacement.Before; + } return relativeY > 0.75f ? EditorDropPlacement.After : EditorDropPlacement.Into; } @@ -40,7 +45,7 @@ EditorDropVisual visual case EditorDropVisual.Highlight: { Vector2 highlightMin = result.contentMin; - highlightMin.X = MathF.Max(result.min.X, highlightMin.X - UiDrawing.GetLayout().itemInnerSpacing.X); + highlightMin.X = MathF.Max(result.min.X, highlightMin.X - GuiDrawing.GetLayout().itemInnerSpacing.X); EditorUI.current.widgets.DropTargetHighlight(highlightMin, result.max); break; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs index 3b9dc8e31..9a134d2c7 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs @@ -1,71 +1,93 @@ using System; using System.Collections.Generic; +using System.Numerics; using Inno.Core.Identity; using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; using Inno.Scene.Components; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; internal sealed partial class HierarchyPanel { - private readonly record struct HierarchyRow( - RuntimeIdentity identity, - int depth - ); - private readonly List m_rows = []; private readonly List<(RuntimeIdentity identity, ulong revision)> m_sceneInputs = []; private ulong m_expansionRevision = ulong.MaxValue; private void RefreshRows(IReadOnlyList scenes) { - var widgets = EditorUI.current.widgets; + ImGuiWidget widgets = EditorUI.current.widgets; foreach (GameScene scene in scenes) - if (m_initializedSceneIds.Add(scene.identity.persistentId)) - widgets.SetTreeNodeOpen("scene_" + scene.identity.persistentId.ToString("N"), true); - foreach (Guid id in m_forceOpenSceneIds) + { + if (m_initializedSceneIDs.Add(scene.identity.persistentID)) + { + widgets.SetTreeNodeOpen("scene_" + scene.identity.persistentID.ToString("N"), true); + } + } + foreach (Guid id in m_forceOpenSceneIDs) + { widgets.SetTreeNodeOpen("scene_" + id.ToString("N"), true); - foreach (Guid id in m_forceOpenIds) + } + foreach (Guid id in m_forceOpenIDs) + { widgets.SetTreeNodeOpen("hierarchy_" + id.ToString("N"), true); - m_forceOpenSceneIds.Clear(); - m_forceOpenIds.Clear(); + } + m_forceOpenSceneIDs.Clear(); + m_forceOpenIDs.Clear(); bool changed = m_expansionRevision != widgets.treeExpansionRevision || m_sceneInputs.Count != scenes.Count; for (int index = 0; !changed && index < scenes.Count; index++) + { changed = m_sceneInputs[index] != (RequireIdentity(scenes[index]), scenes[index].hierarchyRevision); + } if (!changed) + { return; + } - var rows = new List(); - var inputs = new List<(RuntimeIdentity, ulong)>(); + List rows = []; + List<(RuntimeIdentity, ulong)> inputs = []; var pending = new Stack<(GameObject target, int depth)>(); var visited = new HashSet(); foreach (GameScene scene in scenes) { - RuntimeIdentity sceneId = RequireIdentity(scene); - inputs.Add((sceneId, scene.hierarchyRevision)); - rows.Add(new(sceneId, 0)); - if (!widgets.IsTreeNodeOpen("scene_" + scene.identity.persistentId.ToString("N"))) + RuntimeIdentity sceneID = RequireIdentity(scene); + inputs.Add((sceneID, scene.hierarchyRevision)); + rows.Add(new HierarchyRow(sceneID, 0)); + if (!widgets.IsTreeNodeOpen("scene_" + scene.identity.persistentID.ToString("N"))) + { continue; + } IReadOnlyList roots = m_selection.GetRootObjects(scene); for (int index = roots.Count - 1; index >= 0; index--) + { pending.Push((roots[index], 1)); - while (pending.TryPop(out var next)) + } + while (pending.TryPop(out (GameObject target, int depth) next)) { if (!next.target.isRuntimeValid) + { continue; + } RuntimeIdentity identity = RequireIdentity(next.target); if (!visited.Add(identity)) + { throw new InvalidOperationException("A hierarchy view encountered a duplicate object identity."); - rows.Add(new(identity, next.depth)); - if (!widgets.IsTreeNodeOpen("hierarchy_" + next.target.identity.persistentId.ToString("N"))) + } + rows.Add(new HierarchyRow(identity, next.depth)); + if (!widgets.IsTreeNodeOpen("hierarchy_" + next.target.identity.persistentID.ToString("N"))) + { continue; + } IReadOnlyList children = next.target.transform.children; for (int index = children.Count - 1; index >= 0; index--) + { pending.Push((children[index].gameObject, next.depth + 1)); + } } } @@ -75,7 +97,9 @@ private void RefreshRows(IReadOnlyList scenes) m_sceneInputs.AddRange(inputs); m_visibleSelection.Clear(); foreach (HierarchyRow row in rows) + { m_visibleSelection.Add(row.identity); + } m_expansionRevision = widgets.treeExpansionRevision; } @@ -86,8 +110,12 @@ private void DrawRows(EditorContext context) Span preserved = stackalloc int[3]; int count = 0; for (int index = 0; index < m_rows.Count; index++) + { if (m_rows[index].identity == selected || m_rows[index].identity == dragging || m_rows[index].identity == m_drawKeyboardFocus) + { preserved[count++] = index; + } + } EditorUI.current.widgets.ClippedRows(m_rows.Count, -1f, (panel: this, context), static ( state, start, @@ -101,18 +129,32 @@ private void DrawRows(EditorContext context) if (state.panel.m_interactions.TryResolveIdentity(row.identity, out IdentityObject? target)) { if (target is GameScene scene) + { state.panel.DrawScene(state.context, scene, row.depth); + } else if (target is GameObject gameObject) + { state.panel.DrawObject(state.context, gameObject, row.depth); + } else - Ui.Dummy(new(1f, Ui.GetFrameHeight())); + { + Gui.Dummy(new Vector2(1f, Gui.GetFrameHeight())); + } } else - Ui.Dummy(new(1f, Ui.GetFrameHeight())); + { + Gui.Dummy(new Vector2(1f, Gui.GetFrameHeight())); + } } }, preserved[..count]); } private static RuntimeIdentity RequireIdentity(IdentityObject target) - => target.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible hierarchy row requires a registered identity."); + => target.identity.runtimeIdentity + ?? throw new InvalidOperationException("A visible hierarchy row requires a registered identity."); + + private readonly record struct HierarchyRow( + RuntimeIdentity identity, + int depth + ); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs index 8603953df..0bb491319 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs @@ -1,19 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; using Inno.Core.Identity; using Inno.Editor.Core; +using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; using Inno.Scene.Components; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + /// /// Edits the active scene object hierarchy. /// @@ -23,30 +25,22 @@ internal sealed partial class HierarchyPanel : EditorPanel private const nuint C_NAME_BUFFER_SIZE = 512; private readonly List m_visibleSelection = []; - private RuntimeIdentity? m_pendingSelection; - private RuntimeIdentity? m_keyboardFocus; - private RuntimeIdentity? m_requestedKeyboardFocus; - private RuntimeIdentity? m_drawKeyboardFocus; - private int m_keyboardPageSize = 1; private readonly IEditorSceneWorkspace m_workspace; private readonly EditorInteractions m_interactions; private readonly SceneEdits m_edits; private readonly HierarchySelection m_selection; private readonly EditorSettings m_settings; private readonly HierarchyDropVisual m_dropVisual = new(); - private readonly HashSet m_forceOpenIds = []; - private readonly HashSet m_forceOpenSceneIds = []; - private readonly HashSet m_initializedSceneIds = []; + private readonly HashSet m_forceOpenIDs = []; + private readonly HashSet m_forceOpenSceneIDs = []; + private readonly HashSet m_initializedSceneIDs = []; + private RuntimeIdentity? m_pendingSelection; + private RuntimeIdentity? m_keyboardFocus; + private RuntimeIdentity? m_requestedKeyboardFocus; + private RuntimeIdentity? m_drawKeyboardFocus; + private int m_keyboardPageSize = 1; private ulong m_lastRevealedSelectionVersion = ulong.MaxValue; private int m_visibleRowIndex; - /// - /// Gets whether use window padding is enabled for this implementation. - /// - public override bool useWindowPadding => false; - /// - /// Lets the hierarchy content child own both scroll directions. - /// - public override bool allowScrolling => false; /// /// Creates the hierarchy panel. @@ -57,13 +51,27 @@ internal HierarchyPanel( SceneEdits edits, EditorSettings settings ) { - m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(workspace); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(settings); + m_workspace = workspace; + m_interactions = interactions; + m_edits = edits; + m_settings = settings; m_selection = new HierarchySelection(workspace, interactions, m_settings); } + /// + /// Gets whether use window padding is enabled for this implementation. + /// + public override bool useWindowPadding => false; + + /// + /// Lets the hierarchy content child own both scroll directions. + /// + public override bool allowScrolling => false; + /// /// Draws this feature using the current editor presentation context. /// @@ -72,18 +80,23 @@ EditorSettings settings /// protected override void OnDraw(EditorContext context) { - bool visible = Ui.BeginChild("##HierarchyContent", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.HorizontalScrollbar)); + bool visible = Gui.BeginChild( + "##HierarchyContent", + Vector2.Zero, + (ImGuiChildFlags.None), + (ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.HorizontalScrollbar) + ); try { if (visible) { - m_keyboardPageSize = Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / Math.Max(1f, Ui.GetFrameHeight()))); + m_keyboardPageSize = Math.Max(1, (int)(Gui.GetContentRegionAvailable().Y / Math.Max(1f, Gui.GetFrameHeight()))); DrawContent(context); } } finally { - Ui.EndChild(); + Gui.EndChild(); } } @@ -97,33 +110,35 @@ private void DrawContent(EditorContext context) m_visibleRowIndex = 0; m_selection.Prune(); RevealSelection(); - Ui.PushStyleVar((ImGuiStyleVar.ItemSpacing), hierarchyStyle.itemSpacing); - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); + Gui.PushStyleVar((ImGuiStyleVar.ItemSpacing), hierarchyStyle.itemSpacing); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); try { IReadOnlyList scenes = m_workspace.scenes; if (scenes.Count > 0) { - Vector2 contentOrigin = Ui.GetCursorScreenPosition(); - Ui.SetCursorScreenPosition(new Vector2(contentOrigin.X, contentOrigin.Y - Ui.GetWindowBounds().padding.Y)); + Vector2 contentOrigin = Gui.GetCursorScreenPosition(); + Gui.SetCursorScreenPosition(new Vector2(contentOrigin.X, contentOrigin.Y - Gui.GetWindowBounds().padding.Y)); } RefreshRows(scenes); DrawRows(context); DrawBlankArea(context); - if (m_pendingSelection is RuntimeIdentity pending && m_interactions.TryResolveIdentity(pending, out IdentityObject? target) && target is not null) - { + if (m_pendingSelection is RuntimeIdentity pending + && m_interactions.TryResolveIdentity(pending, out IdentityObject? target) + && target is not null + ) { EditorUI.current.widgets.SelectTarget(m_interactions, target, m_visibleSelection); m_keyboardFocus = pending; - m_interactions.For(HierarchyInteractionIds.C_AREA, target).Focus(); + m_interactions.For(HierarchyInteractionIDs.C_AREA, target).Focus(); } HandleKeyboardNavigation(); } finally { m_pendingSelection = null; - Ui.PopStyleVar(2); + Gui.PopStyleVar(2); } } @@ -136,40 +151,65 @@ private void HandleKeyboardNavigation() { RuntimeIdentity item = m_visibleSelection[index]; if (item == m_keyboardFocus) + { focused = index; + } if (item == selectedTarget) + { selected = index; + } } if (focused < 0) + { focused = selected; - ListNavigationResult navigation = EditorUI.current.widgets.NavigateList(m_interactions, m_visibleSelection.Count, focused, m_keyboardPageSize); + } + ListNavigationResult navigation = EditorUI.current.widgets.NavigateList( + m_interactions, + m_visibleSelection.Count, + focused, + m_keyboardPageSize + ); if (navigation.focusedIndex >= 0 && (navigation.focusChanged || navigation.selectionRequested || navigation.activate)) { RuntimeIdentity identity = m_visibleSelection[navigation.focusedIndex]; if (!m_interactions.TryResolveIdentity(identity, out IdentityObject? target) || target is null) + { return; + } m_keyboardFocus = identity; if (navigation.focusChanged) + { m_requestedKeyboardFocus = m_keyboardFocus; + } if (navigation.selectionRequested) { if (navigation.extendRange) + { m_interactions.SelectRange(m_visibleSelection, target, navigation.additive); + } else if (navigation.toggle) + { m_interactions.ToggleSelection(target); + } else + { m_interactions.SetSelection(target); + } } - m_interactions.For(HierarchyInteractionIds.C_AREA, m_interactions.selection.selectedTarget).Focus(); + m_interactions.For(HierarchyInteractionIDs.C_AREA, m_interactions.selection.selectedTarget).Focus(); if (navigation.activate) { if (!m_interactions.selection.Contains(target)) + { m_interactions.SetSelection(target); - _ = m_interactions.For(HierarchyInteractionIds.C_AREA, target).Execute(HierarchyInteractionIds.C_RENAME); + } + _ = m_interactions.For(HierarchyInteractionIDs.C_AREA, target).Execute(HierarchyInteractionIDs.C_RENAME); } } if (navigation.cancel) + { m_keyboardFocus = null; + } } private void DrawScene( @@ -177,29 +217,47 @@ private void DrawScene( GameScene scene, int depth ) { - string id = scene.identity.persistentId.ToString("N"); + string id = scene.identity.persistentID.ToString("N"); bool selected = m_interactions.selection.Contains(scene); TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"scene_{id}", drawContext => DrawSceneRowContent(scene, id, drawContext.rowHeight), - new TreeNodeOptions { - depth = depth, selected = selected, requestFocus = scene.identity.runtimeIdentity == m_drawKeyboardFocus, - keepContentActive = m_interactions.For(HierarchyInteractionIds.C_AREA, scene).IsActive(HierarchyInteractionIds.C_RENAME), - showBackground = true, backgroundColor = EditorPalette.title - }); + new TreeNodeOptions + { + depth = depth, + selected = selected, + requestFocus = scene.identity.runtimeIdentity == m_drawKeyboardFocus, + keepContentActive = m_interactions.For(HierarchyInteractionIDs.C_AREA, scene).IsActive(HierarchyInteractionIDs.C_RENAME), + showBackground = true, + backgroundColor = EditorPalette.title + } + ); if (!result.isSubmitted) + { return; + } if (result.isClicked || result.isDoubleClicked) + { m_pendingSelection = scene.identity.runtimeIdentity; + } if (result.isDoubleClicked) - _ = m_interactions.For(HierarchyInteractionIds.C_AREA, scene).Execute(HierarchyInteractionIds.C_RENAME); - _ = EditorDragDropRenderer.Source(m_interactions.For(HierarchyInteractionIds.C_AREA, scene), - new EditorDragData(scene, scene.name), () => Ui.Text(scene.name)); - EditorDropPlacement placement = m_dropVisual.GetScenePlacement(result, Ui.GetMousePos().Y); + { + _ = m_interactions.For(HierarchyInteractionIDs.C_AREA, scene).Execute(HierarchyInteractionIDs.C_RENAME); + } + _ = EditorDragDropRenderer.Source( + m_interactions.For(HierarchyInteractionIDs.C_AREA, scene), + new EditorDragData(scene, scene.name), + () => Gui.Text(scene.name) + ); + EditorDropPlacement placement = m_dropVisual.GetScenePlacement(result, Gui.GetMousePos().Y); EditorDropWidgetResult drop = EditorDragDropRenderer.Target( - m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchySceneDropTarget(scene)), placement); + m_interactions.For(HierarchyInteractionIDs.C_AREA, new HierarchySceneDropTarget(scene)), + placement + ); if (drop.isPreviewing && drop.status.canDrop) + { m_dropVisual.Draw(result, drop.status.visual); + } ApplyDropResult(drop.result); DrawSceneContextMenu(context, scene, id); } @@ -210,32 +268,53 @@ private void DrawObject( int depth ) { if (!gameObject.isRuntimeValid) + { return; - string id = gameObject.identity.persistentId.ToString("N"); + } + string id = gameObject.identity.persistentID.ToString("N"); TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"hierarchy_{id}", drawContext => DrawRowContent(context, gameObject, drawContext.rowHeight), - new TreeNodeOptions { - depth = depth, selected = m_interactions.selection.Contains(gameObject), + new TreeNodeOptions + { + depth = depth, + selected = m_interactions.selection.Contains(gameObject), requestFocus = gameObject.identity.runtimeIdentity == m_drawKeyboardFocus, - keepContentActive = m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject).IsActive(HierarchyInteractionIds.C_RENAME), - isLeaf = gameObject.transform.children.Count == 0, showBackground = true, + keepContentActive = m_interactions + .For(HierarchyInteractionIDs.C_AREA, gameObject) + .IsActive(HierarchyInteractionIDs.C_RENAME), + isLeaf = gameObject.transform.children.Count == 0, + showBackground = true, backgroundColor = m_visibleRowIndex % 2 == 0 ? EditorPalette.collectionRow : EditorPalette.collectionRowAlternate, drawViewportOverlay = () => DrawVisibilityButton(gameObject, id) - }); + } + ); if (!result.isSubmitted) + { return; + } if (result.isClicked || result.isDoubleClicked) + { m_pendingSelection = gameObject.identity.runtimeIdentity; + } if (result.isDoubleClicked) - _ = m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject).Execute(HierarchyInteractionIds.C_RENAME); - _ = EditorDragDropRenderer.Source(m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject), - new EditorDragData(gameObject, gameObject.name), () => Ui.Text(gameObject.name)); - EditorDropPlacement placement = m_dropVisual.GetObjectPlacement(result, Ui.GetMousePos().Y); + { + _ = m_interactions.For(HierarchyInteractionIDs.C_AREA, gameObject).Execute(HierarchyInteractionIDs.C_RENAME); + } + _ = EditorDragDropRenderer.Source( + m_interactions.For(HierarchyInteractionIDs.C_AREA, gameObject), + new EditorDragData(gameObject, gameObject.name), + () => Gui.Text(gameObject.name) + ); + EditorDropPlacement placement = m_dropVisual.GetObjectPlacement(result, Gui.GetMousePos().Y); EditorDropWidgetResult drop = EditorDragDropRenderer.Target( - m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchyObjectDropTarget(gameObject)), placement); + m_interactions.For(HierarchyInteractionIDs.C_AREA, new HierarchyObjectDropTarget(gameObject)), + placement + ); if (drop.isPreviewing && drop.status.canDrop) + { m_dropVisual.Draw(result, drop.status.visual); + } ApplyDropResult(drop.result); DrawObjectContextMenu(context, gameObject, id); } @@ -245,37 +324,50 @@ private void DrawRowContent( GameObject gameObject, float rowHeight ) { - string id = gameObject.identity.persistentId.ToString("N"); + string id = gameObject.identity.persistentID.ToString("N"); bool dimmed = !gameObject.activeInHierarchy; if (dimmed) { - Ui.PushStyleColor((ImGuiCol.Text), HierarchyStyle.inactiveText); + Gui.PushStyleColor((ImGuiCol.Text), HierarchyStyle.inactiveText); } try { - EditorInteraction interaction = m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject); - bool isRenaming = interaction.IsActive(HierarchyInteractionIds.C_RENAME); + EditorInteraction interaction = m_interactions.For(HierarchyInteractionIDs.C_AREA, gameObject); + bool isRenaming = interaction.IsActive(HierarchyInteractionIDs.C_RENAME); if (isRenaming) { - EditorUI.current.widgets.IconText(m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, string.Empty, false); - Ui.SameLine(0f, 0f); + EditorUI.current.widgets.IconText( + m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.C_CUBE)!, + string.Empty, + false + ); + Gui.SameLine(0f, 0f); float visibilityWidth = GetVisibilityButtonWidth(); float renameWidth = MathF.Max( hierarchyStyle.renameMinimumWidth, - Ui.GetContentRegionAvailable().X - visibilityWidth - hierarchyStyle.renameTrailingGap + Gui.GetContentRegionAvailable().X - visibilityWidth - hierarchyStyle.renameTrailingGap + ); + _ = interaction.Present( + HierarchyInteractionIDs.C_RENAME, + new InlineRenamePresentation($"hierarchy_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE) ); - _ = interaction.Present(HierarchyInteractionIds.C_RENAME, new InlineRenamePresentation($"hierarchy_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE)); } else { - EditorUI.current.widgets.IconText(m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, gameObject.name, false); + EditorUI.current.widgets.IconText( + m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.C_CUBE)!, + gameObject.name, + false + ); } } finally { if (dimmed) - Ui.PopStyleColor(); + { + Gui.PopStyleColor(); + } } } @@ -284,51 +376,55 @@ private void DrawSceneRowContent( string id, float rowHeight ) { - EditorInteraction interaction = m_interactions.For(HierarchyInteractionIds.C_AREA, scene); - if (!interaction.IsActive(HierarchyInteractionIds.C_RENAME)) + EditorInteraction interaction = m_interactions.For(HierarchyInteractionIDs.C_AREA, scene); + if (!interaction.IsActive(HierarchyInteractionIDs.C_RENAME)) { m_selection.DrawSceneRowContent(scene); return; } EditorUI.current.widgets.IconText( - m_settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.Cubes)!, + m_settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.C_CUBES)!, string.Empty, ReferenceEquals(scene, m_workspace.activeScene) ); - Ui.SameLine(0f, 0f); + Gui.SameLine(0f, 0f); float renameWidth = MathF.Max( hierarchyStyle.renameMinimumWidth, - Ui.GetContentRegionAvailable().X - hierarchyStyle.renameTrailingGap + Gui.GetContentRegionAvailable().X - hierarchyStyle.renameTrailingGap + ); + _ = interaction.Present( + HierarchyInteractionIDs.C_RENAME, + new InlineRenamePresentation($"scene_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE) ); - _ = interaction.Present(HierarchyInteractionIds.C_RENAME, new InlineRenamePresentation($"scene_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE)); } private void DrawVisibilityButton( GameObject gameObject, string id ) { - string icon = gameObject.activeSelf ? ImGuiIcon.Eye : ImGuiIcon.EyeSlash; + string icon = gameObject.activeSelf ? ImGuiIcon.C_EYE : ImGuiIcon.C_EYE_SLASH; float buttonWidth = GetVisibilityButtonWidth(); - float right = Ui.GetWindowBounds().workMaximum.X - EditorUI.current.widgets.style.windowPadding.X - buttonWidth; - Ui.SameLine(0f, -1f); - Vector2 cursor = Ui.GetCursorScreenPosition(); - Ui.SetCursorScreenPosition(new Vector2(MathF.Max(cursor.X, right), cursor.Y)); + float right = Gui.GetWindowBounds().workMaximum.X - EditorUI.current.widgets.style.windowPadding.X - buttonWidth; + Gui.SameLine(0f, -1f); + Vector2 cursor = Gui.GetCursorScreenPosition(); + Gui.SetCursorScreenPosition(new Vector2(MathF.Max(cursor.X, right), cursor.Y)); if (EditorUI.current.widgets.ClickableIcon($"hierarchy_visibility_{id}", icon, gameObject.activeSelf ? "Deactivate" : "Activate")) { m_edits.SetGameObjectActive(gameObject, !gameObject.activeSelf); } } - private static float GetVisibilityButtonWidth() => EditorUI.current.widgets.GetCompactIconSize().X; private void DrawSceneContextMenu( EditorContext context, GameScene scene, string id ) { - if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(scene)) + if (Gui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(scene)) + { m_interactions.SetSelection(scene); - _ = EditorUI.current.menus.ContextMenu($"##scene_context_{id}", m_interactions.For(HierarchyInteractionIds.C_AREA, scene)); + } + _ = EditorUI.current.menus.ContextMenu($"##scene_context_{id}", m_interactions.For(HierarchyInteractionIDs.C_AREA, scene)); } private void DrawObjectContextMenu( @@ -336,26 +432,28 @@ private void DrawObjectContextMenu( GameObject gameObject, string id ) { - if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(gameObject)) + if (Gui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(gameObject)) + { m_interactions.SetSelection(gameObject); - _ = EditorUI.current.menus.ContextMenu($"##hierarchy_context_{id}", m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject)); + } + _ = EditorUI.current.menus.ContextMenu($"##hierarchy_context_{id}", m_interactions.For(HierarchyInteractionIDs.C_AREA, gameObject)); } private void DrawBlankArea(EditorContext context) { - Vector2 available = Ui.GetContentRegionAvailable(); - Vector2 size = new(MathF.Max(1f, available.X), MathF.Max(hierarchyStyle.blankMinimumHeight, available.Y)); - _ = Ui.InvisibleButton("##hierarchy_blank", size); - if (Ui.IsItemClicked((ImGuiMouseButton.Left))) + Vector2 available = Gui.GetContentRegionAvailable(); + var size = new Vector2(MathF.Max(1f, available.X), MathF.Max(hierarchyStyle.blankMinimumHeight, available.Y)); + _ = Gui.InvisibleButton("##hierarchy_blank", size); + if (Gui.IsItemClicked((ImGuiMouseButton.Left))) { - _ = m_interactions.For(HierarchyInteractionIds.C_AREA).Select(); + _ = m_interactions.For(HierarchyInteractionIDs.C_AREA).Select(); } GameScene? activeScene = m_workspace.activeScene; if (activeScene is not null) { EditorDropWidgetResult drop = EditorDragDropRenderer.Target( - m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchySceneDropTarget(activeScene)), + m_interactions.For(HierarchyInteractionIDs.C_AREA, new HierarchySceneDropTarget(activeScene)), EditorDropPlacement.Into ); ApplyDropResult(drop.result); @@ -363,7 +461,9 @@ private void DrawBlankArea(EditorContext context) _ = EditorUI.current.menus.ContextMenu( "##hierarchy_blank_context", - activeScene is null ? m_interactions.For(HierarchyInteractionIds.C_AREA) : m_interactions.For(HierarchyInteractionIds.C_AREA, activeScene) + activeScene is null + ? m_interactions.For(HierarchyInteractionIDs.C_AREA) + : m_interactions.For(HierarchyInteractionIDs.C_AREA, activeScene) ); } @@ -371,29 +471,39 @@ private void RevealSelection() { ulong selectionVersion = m_interactions.selection.version; if (m_lastRevealedSelectionVersion == selectionVersion) + { return; + } m_lastRevealedSelectionVersion = selectionVersion; if (!m_interactions.selection.TryGet(out GameObject? gameObject) || !gameObject.isRuntimeValid) + { return; - m_forceOpenSceneIds.Add(gameObject.scene.identity.persistentId); + } + m_forceOpenSceneIDs.Add(gameObject.scene.identity.persistentID); for (Transform? current = gameObject.transform.parent; current is not null; current = current.parent) { if (current.gameObject is not null) - m_forceOpenIds.Add(current.gameObject.identity.persistentId); + { + m_forceOpenIDs.Add(current.gameObject.identity.persistentID); + } } } private void ApplyDropResult(EditorDropResult result) { if (!result.accepted) + { return; + } if (result.revealTarget is GameScene scene) { - m_forceOpenSceneIds.Add(scene.identity.persistentId); + m_forceOpenSceneIDs.Add(scene.identity.persistentID); } else if (result.revealTarget is GameObject gameObject) { - m_forceOpenIds.Add(gameObject.identity.persistentId); + m_forceOpenIDs.Add(gameObject.identity.persistentID); } } + + private static float GetVisibilityButtonWidth() => EditorUI.current.widgets.GetCompactIconSize().X; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs index 89405238e..f39034c59 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs @@ -1,14 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System.Collections.Generic; +using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + internal sealed class HierarchySelection( IEditorSceneWorkspace workspace, EditorInteractions interactions, @@ -16,14 +18,18 @@ EditorSettings settings ) { internal void Prune() { - if (interactions.selection.TryGet(out GameScene? selectedScene) && (!selectedScene.isLoaded || !ContainsScene(workspace.scenes, selectedScene))) - { - _ = interactions.For(HierarchyInteractionIds.C_AREA).Select(); + if (interactions.selection.TryGet(out GameScene? selectedScene) + && (!selectedScene.isLoaded || !ContainsScene(workspace.scenes, selectedScene)) + ) { + _ = interactions.For(HierarchyInteractionIDs.C_AREA).Select(); return; } - if (interactions.selection.TryGet(out GameObject? gameObject) && (!gameObject.isRuntimeValid || !ContainsScene(workspace.scenes, gameObject.scene))) - _ = interactions.For(HierarchyInteractionIds.C_AREA).Select(); + if (interactions.selection.TryGet(out GameObject? gameObject) + && (!gameObject.isRuntimeValid || !ContainsScene(workspace.scenes, gameObject.scene)) + ) { + _ = interactions.For(HierarchyInteractionIDs.C_AREA).Select(); + } } internal IReadOnlyList GetRootObjects(GameScene scene) @@ -33,7 +39,9 @@ internal IReadOnlyList GetRootObjects(GameScene scene) for (int i = 0; i < objects.Count; i++) { if (objects[i].transform.parent is null) + { roots.Add(objects[i]); + } } roots.Sort(static ( @@ -46,15 +54,17 @@ internal IReadOnlyList GetRootObjects(GameScene scene) internal void DrawSceneRowContent(GameScene scene) { EditorUI.current.widgets.IconText( - settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.Cubes)!, + settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.C_CUBES)!, scene.name, ReferenceEquals(scene, workspace.activeScene) ); if (!workspace.IsDirty(scene)) + { return; - Ui.SameLine(0f, 0f); + } + Gui.SameLine(0f, 0f); using ImGuiFontScope font = ImGuiFont.PushStyle(ImGuiFontStyle.Italic); - Ui.Text(" *"); + Gui.Text(" *"); } private static bool ContainsScene( @@ -64,7 +74,9 @@ GameScene scene for (int i = 0; i < scenes.Count; i++) { if (ReferenceEquals(scenes[i], scene)) + { return true; + } } return false; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs index 65f0e4c62..c8fc2803b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Panel.Hierarchy; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Hierarchy", - "Inno.Editor.Panel.Hierarchy", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Hierarchy", "Inno.Editor.Panel.Hierarchy", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(HierarchyObjectDropTarget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(HierarchySceneDropTarget), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs index b8aeb77c1..994aed8e0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs @@ -7,12 +7,15 @@ internal readonly struct HierarchyStyle { private readonly float m_zoom; - internal HierarchyStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal HierarchyStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } /// /// Gets the text color of inactive hierarchy entries. /// - internal static Vector4 inactiveText { get; } = new(0.52f, 0.52f, 0.54f, EditorPalette.opacityOpaque); + internal static Vector4 inactiveText { get; } = new(0.52f, 0.52f, 0.54f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets hierarchy item spacing. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs index 0bc25f4b2..1c1b5dbd6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs @@ -1,12 +1,12 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.Inspector; -[EditorDrop(InspectorInteractionIds.C_ASSET_REFERENCE_AREA, priority: 100)] -internal sealed class AssetReferenceDropHandler(AssetPipeline assets) - : EditorDrop +[EditorDrop(InspectorInteractionIDs.C_ASSET_REFERENCE_AREA, priority: 100)] +internal sealed class AssetReferenceDropHandler(AssetPipeline assets) : EditorDrop { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -19,12 +19,12 @@ internal sealed class AssetReferenceDropHandler(AssetPipeline assets) /// protected override EditorDropStatus Query(EditorDropContext context) { - if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId) || - persistentId == System.Guid.Empty || - !assets.TryGetAssetType(context.source.assetPath, out System.Type? assetType) || - assetType is null || - !context.target.expectedType.IsAssignableFrom(assetType)) - { + if (!assets.TryGetPersistentID(context.source.assetPath, out Guid persistentID) + || persistentID == Guid.Empty + || !assets.TryGetAssetType(context.source.assetPath, out Type? assetType) + || assetType is null + || !context.target.expectedType.IsAssignableFrom(assetType) + ) { return EditorDropStatus.rejected; } return EditorDropStatus.Accept(); @@ -42,10 +42,14 @@ assetType is null || protected override EditorDropResult Drop(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; - if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId)) + } + if (!assets.TryGetPersistentID(context.source.assetPath, out Guid persistentID)) + { return EditorDropResult.rejected; - context.target.Assign(persistentId); + } + context.target.Assign(persistentID); return EditorDropResult.Accepted(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropTarget.cs index b78dff422..7f73e940d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropTarget.cs @@ -31,8 +31,9 @@ public AssetReferenceDropTarget( Action assign ) { ArgumentNullException.ThrowIfNull(expectedType); + ArgumentNullException.ThrowIfNull(assign); m_expectedType = expectedType; - m_assign = assign ?? throw new ArgumentNullException(nameof(assign)); + m_assign = assign; } /// @@ -43,8 +44,8 @@ Action assign /// /// Assigns a persistent asset identity to the represented property. /// - /// + /// /// The stable persistent identity used for lookup. /// - public void Assign(Guid persistentId) => m_assign(persistentId); + public void Assign(Guid persistentID) => m_assign(persistentID); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs index 747106aec..c76bdb892 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs @@ -1,7 +1,4 @@ - - using System.Collections.Generic; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Runtime; @@ -9,7 +6,7 @@ namespace Inno.Editor.Panel.Inspector; -[EditorDrop(InspectorInteractionIds.C_ENGINE_OBJECT_REFERENCE_AREA, priority: 100)] +[EditorDrop(InspectorInteractionIDs.C_ENGINE_OBJECT_REFERENCE_AREA, priority: 100)] internal sealed class EngineObjectReferenceDropHandler(RuntimeSession runtimeSession) : EditorDrop { @@ -24,8 +21,8 @@ internal sealed class EngineObjectReferenceDropHandler(RuntimeSession runtimeSes /// protected override EditorDropStatus Query(EditorDropContext context) => Resolve(context) is null - ? EditorDropStatus.rejected - : EditorDropStatus.Accept(); + ? EditorDropStatus.rejected + : EditorDropStatus.Accept(); /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -40,7 +37,9 @@ protected override EditorDropResult Drop(EditorDropContext components = gameObject.GetComponents(); for (int i = 0; i < components.Count; i++) { if (context.target.expectedType.IsInstanceOfType(components[i])) + { return components[i]; + } } return null; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs index 443c58f84..230133bda 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Inspector; @@ -34,8 +32,9 @@ public EngineObjectReferenceDropTarget( Action assign ) { ArgumentNullException.ThrowIfNull(expectedType); + ArgumentNullException.ThrowIfNull(assign); m_expectedType = expectedType; - m_assign = assign ?? throw new ArgumentNullException(nameof(assign)); + m_assign = assign; } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIDs.cs similarity index 94% rename from src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIds.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIDs.cs index b56b2ea2e..474273b2e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/InspectorInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Panel.Inspector; -internal static class InspectorInteractionIds +internal static class InspectorInteractionIDs { internal const string C_COMPONENT_AREA = "panel/scene.inspector/component"; internal const string C_SYSTEM_AREA = "panel/scene.inspector/system"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs index ce240b94a..e135c6624 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs @@ -1,12 +1,13 @@ using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_ADD_COMPONENT, InspectorInteractionIds.C_COMPONENT_AREA)] + +[EditorAction(InspectorInteractionIDs.C_ADD_COMPONENT, InspectorInteractionIDs.C_COMPONENT_AREA)] internal sealed class AddComponentCommand( SceneEdits edits, TypeCatalog types @@ -21,9 +22,11 @@ TypeCatalog types /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => Targets(context).Count > 0 - && Targets(context).All(value => value.isRuntimeValid && edits.CanEdit(value)) - && context.argument.IsValid(types) ? EditorActionState.enabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => Targets(context).Count > 0 + && Targets(context).All(value => value.isRuntimeValid && edits.CanEdit(value)) + && context.argument.IsValid(types) ? EditorActionState.enabled : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -34,15 +37,19 @@ protected override void Execute(EditorActionContext context { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Add Components"); foreach (GameObject target in Targets(context)) + { _ = edits.AddComponent(target, context.argument.Resolve(types)); + } transaction.Commit(); } private static IReadOnlyList Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; - var targets = new List(); + } + List targets = []; context.interactions.selection.CopyTargets(targets); return targets.Count == context.interactions.selection.count ? targets : []; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs index 68eb90f64..ec9227470 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs @@ -1,14 +1,13 @@ using System; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorMenuSource(InspectorInteractionIds.C_COMPONENT_AREA)] +[EditorMenuSource(InspectorInteractionIDs.C_COMPONENT_AREA)] internal sealed class AddComponentMenuProvider(TypeCatalog types) : EditorMenuSource { /// @@ -25,14 +24,18 @@ public override void Build( EditorMenuBuilder builder ) { if (context.target is not GameObject gameObject) + { return; + } TypeCacheSnapshot snapshot = types.current; foreach (TypeRef typeRef in snapshot.GetSubTypesOf()) { Type type = typeRef.Resolve(snapshot); if (!IsAddable(type, gameObject)) + { continue; - builder.Add(type.Name, InspectorInteractionIds.C_ADD_COMPONENT, argument: typeRef); + } + builder.Add(type.Name, InspectorInteractionIDs.C_ADD_COMPONENT, argument: typeRef); } } @@ -41,12 +44,15 @@ private static bool IsAddable( GameObject gameObject ) { if (type.IsAbstract || type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, - Type.EmptyTypes, - modifiers: null) is null) + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is null + ) { return false; - return type.IsDefined(typeof(AllowMultipleComponentAttribute), inherit: false) || - !gameObject.GetComponents().Any(component => component.GetType() == type); + } + return type.IsDefined(typeof(AllowMultipleComponentAttribute), inherit: false) + || !gameObject.GetComponents().Any(component => component.GetType() == type); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs index 39deb4460..6313e4f14 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs @@ -1,16 +1,15 @@ -using Inno.Extensibility.Types; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_ADD_SYSTEM, InspectorInteractionIds.C_SYSTEM_AREA)] +[EditorAction(InspectorInteractionIDs.C_ADD_SYSTEM, InspectorInteractionIDs.C_SYSTEM_AREA)] internal sealed class AddSystemCommand( SceneEdits edits, TypeCatalog types -) - : EditorAction +) : EditorAction { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -23,8 +22,8 @@ TypeCatalog types /// protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded && context.argument.IsValid(types) - ? EditorActionState.enabled - : EditorActionState.hidden; + ? EditorActionState.enabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs index bd0f5cb61..3c3adb790 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs @@ -1,14 +1,13 @@ using System; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorMenuSource(InspectorInteractionIds.C_SYSTEM_AREA)] +[EditorMenuSource(InspectorInteractionIDs.C_SYSTEM_AREA)] internal sealed class AddSystemMenuProvider(TypeCatalog types) : EditorMenuSource { /// @@ -25,14 +24,18 @@ public override void Build( EditorMenuBuilder builder ) { if (context.target is not GameScene scene) + { return; + } TypeCacheSnapshot snapshot = types.current; foreach (TypeRef typeRef in snapshot.GetSubTypesOf()) { Type type = typeRef.Resolve(snapshot); if (!IsAddable(type, scene)) + { continue; - builder.Add(type.Name, InspectorInteractionIds.C_ADD_SYSTEM, argument: typeRef); + } + builder.Add(type.Name, InspectorInteractionIDs.C_ADD_SYSTEM, argument: typeRef); } } @@ -41,12 +44,15 @@ private static bool IsAddable( GameScene scene ) { if (type.IsAbstract || type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, - Type.EmptyTypes, - modifiers: null) is null) + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is null + ) { return false; - return type.IsDefined(typeof(AllowMultipleSystemAttribute), inherit: false) || - !scene.GetSystems().Any(system => system.GetType() == type); + } + return type.IsDefined(typeof(AllowMultipleSystemAttribute), inherit: false) + || !scene.GetSystems().Any(system => system.GetType() == type); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs index f3ce5e32a..ee4962278 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs @@ -1,11 +1,12 @@ -using Inno.Scene; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Scene; using Inno.Scene.Components; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_REMOVE_COMPONENT, priority: 100)] -[EditorMenu(InspectorInteractionIds.C_COMPONENT_AREA, "Remove Component", order: 200)] + +[EditorAction(InspectorInteractionIDs.C_REMOVE_COMPONENT, priority: 100)] +[EditorMenu(InspectorInteractionIDs.C_COMPONENT_AREA, "Remove Component", order: 200)] internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction { /// @@ -17,7 +18,9 @@ internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => context.target is not Transform ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => context.target is not Transform ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -27,6 +30,8 @@ internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction context) { if (context.target is not Transform) + { _ = edits.RemoveComponent(context.target); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs index 57ec6d7ce..35faf9e11 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs @@ -1,10 +1,11 @@ -using Inno.Scene; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_REMOVE_SYSTEM, priority: 100)] -[EditorMenu(InspectorInteractionIds.C_SYSTEM_AREA, "Remove System", order: 200)] + +[EditorAction(InspectorInteractionIDs.C_REMOVE_SYSTEM, priority: 100)] +[EditorMenu(InspectorInteractionIDs.C_SYSTEM_AREA, "Remove System", order: 200)] internal sealed class RemoveSystemCommand(SceneEdits edits) : EditorAction { /// @@ -16,7 +17,9 @@ internal sealed class RemoveSystemCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs index 4c900abca..8469b1b81 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs @@ -3,8 +3,9 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_RESET_COMPONENT, priority: 100)] -[EditorMenu(InspectorInteractionIds.C_COMPONENT_AREA, "Reset Component", order: 100)] + +[EditorAction(InspectorInteractionIDs.C_RESET_COMPONENT, priority: 100)] +[EditorMenu(InspectorInteractionIDs.C_COMPONENT_AREA, "Reset Component", order: 100)] internal sealed class ResetComponentCommand(SceneEdits edits) : EditorAction { /// @@ -16,8 +17,10 @@ internal sealed class ResetComponentCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed - && context.target is not MissingGameComponent ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed + && context.target is not MissingGameComponent ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs index 0f7b5c51d..fec9a7100 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs @@ -3,8 +3,9 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; -[EditorAction(InspectorInteractionIds.C_RESET_SYSTEM, priority: 100)] -[EditorMenu(InspectorInteractionIds.C_SYSTEM_AREA, "Reset System", order: 100)] + +[EditorAction(InspectorInteractionIDs.C_RESET_SYSTEM, priority: 100)] +[EditorMenu(InspectorInteractionIDs.C_SYSTEM_AREA, "Reset System", order: 100)] internal sealed class ResetSystemCommand(SceneEdits edits) : EditorAction { /// @@ -16,8 +17,10 @@ internal sealed class ResetSystemCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed - && context.target is not MissingGameSystem ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed + && context.target is not MissingGameSystem ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs index 705b788d3..75151d444 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; using Inno.Scene.Layers; @@ -23,8 +22,10 @@ internal GameLayerDiagnosticPublisher( SceneWorld world, DiagnosticHub diagnostics ) { - m_world = world ?? throw new ArgumentNullException(nameof(world)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(diagnostics); + m_world = world; + m_diagnostics = diagnostics; } /// @@ -45,21 +46,29 @@ internal void Refresh(GameLayerCatalog stack) { GameObject gameObject = objects[objectIndex]; if (stack.IsDefined(gameObject.layer)) + { continue; - Guid targetId = gameObject.identity.persistentId; - currentTargets.Add(targetId); - if (m_activeTargets.Contains(targetId)) + } + Guid targetID = gameObject.identity.persistentID; + currentTargets.Add(targetID); + if (m_activeTargets.Contains(targetID)) + { continue; + } m_diagnostics.Set( - CreateSource(targetId, gameObject.name), + CreateSource(targetID, gameObject.name), [Diagnostic.Error( "GAMEOBJECT-LAYER-UNDEFINED", - $"GameObject '{gameObject.name}' uses undefined layer slot {gameObject.layer.index}.")]); + $"GameObject '{gameObject.name}' uses undefined layer slot {gameObject.layer.index}." + )] + ); } } - foreach (Guid targetId in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) - m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + foreach (Guid targetID in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) + { + m_diagnostics.Clear(CreateSource(targetID, targetID.ToString("D"))); + } m_activeTargets.Clear(); m_activeTargets.UnionWith(currentTargets); } @@ -69,14 +78,15 @@ internal void Refresh(GameLayerCatalog stack) /// internal void Clear() { - foreach (Guid targetId in m_activeTargets) - m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + foreach (Guid targetID in m_activeTargets) + { + m_diagnostics.Clear(CreateSource(targetID, targetID.ToString("D"))); + } m_activeTargets.Clear(); } private static DiagnosticSource CreateSource( - Guid targetId, + Guid targetID, string displayName - ) - => new($"editor.scene.layer:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); + ) => new($"editor.scene.layer:{targetID:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs index b4d38694c..52440869d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Globalization; @@ -9,9 +8,12 @@ using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; using Inno.Scene.Layers; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [ProjectSettingPath("Project/Scene/Layers")] internal sealed class GameLayersSetting : ProjectSettingEditor { @@ -19,14 +21,17 @@ internal sealed class GameLayersSetting : ProjectSettingEditor private readonly string[] m_nameBuffers = new string[GameLayer.C_MAX_COUNT]; private string m_error = string.Empty; private string? []? m_observedNames; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Definitions"; + /// /// Gets the user-facing explanation of this feature or setting. /// - public override string description => "Define layer names and slots. Stable IDs are generated as projectId.name and are never authored manually."; + public override string description + => "Define layer names and slots. Stable IDs are generated as projectId.name and are never authored manually."; /// /// Draws this feature using the current editor presentation context. @@ -40,7 +45,9 @@ protected override void OnDraw(GameLayerCatalog setting) SynchronizeBuffers(names); DrawLayerRows(setting, names); if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } private void DrawLayerRows( @@ -49,31 +56,46 @@ private void DrawLayerRows( ) { int definedCount = names.Count(static name => !string.IsNullOrWhiteSpace(name)); DrawLayerToolbar(setting, names, definedCount); - Ui.Spacing(); - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings; - Ui.PushStyleVar(ImGuiStyleVar.CellPadding, EditorUI.current.widgets.style.cellPadding); - if (!Ui.BeginTable("##game_layer_definitions", 3, flags, default(System.Numerics.Vector2), 0f)) + Gui.Spacing(); + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.BordersInnerH + | ImGuiTableFlags.BordersInnerV + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoSavedSettings; + Gui.PushStyleVar(ImGuiStyleVar.CellPadding, EditorUI.current.widgets.style.cellPadding); + if (!Gui.BeginTable("##game_layer_definitions", 3, flags, default, 0f)) { - Ui.PopStyleVar(); + Gui.PopStyleVar(); return; } try { - Ui.TableSetupColumn("Slot", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 48f * EditorUI.current.widgets.style.zoom); - Ui.TableSetupColumn("Name", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); - Ui.TableSetupColumn("Action", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 72f * EditorUI.current.widgets.style.zoom); + Gui.TableSetupColumn( + "Slot", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 48f * EditorUI.current.widgets.style.zoom + ); + Gui.TableSetupColumn("Name", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); + Gui.TableSetupColumn( + "Action", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 72f * EditorUI.current.widgets.style.zoom + ); DrawLayerTableHeader(); for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) { if (!string.IsNullOrWhiteSpace(names[index])) + { DrawLayerRow(setting, names, index); + } } } finally { - Ui.EndTable(); - Ui.PopStyleVar(); + Gui.EndTable(); + Gui.PopStyleVar(); } } @@ -83,35 +105,41 @@ private void DrawLayerRow( int index ) { var layer = new GameLayer(index); - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); - Ui.AlignTextToFramePadding(); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); + Gui.AlignTextToFramePadding(); InsetPlainCell(); - Ui.Text(index.ToString("00", CultureInfo.InvariantCulture)); - _ = Ui.TableSetColumnIndex(1); + Gui.Text(index.ToString("00", CultureInfo.InvariantCulture)); + _ = Gui.TableSetColumnIndex(1); if (layer == GameLayer.defaultLayer) { InsetPlainCell(); - Ui.Text(names[index] ?? "Default"); - _ = Ui.TableSetColumnIndex(2); + Gui.Text(names[index] ?? "Default"); + _ = Gui.TableSetColumnIndex(2); InsetPlainCell(); EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Fixed"); return; } - Ui.PushId(index); + Gui.PushID(index); try { string name = m_nameBuffers[index]; bool committed = DrawTextField("##layer_name", "Layer name", ref name); m_nameBuffers[index] = name; if (committed) + { CommitDefinition(setting, layer, name); - _ = Ui.TableSetColumnIndex(2); + } + _ = Gui.TableSetColumnIndex(2); InsetPlainCell(); - Vector2 removeSize = new(Ui.MeasureText("Remove").X, Ui.GetFrameHeight()); - if (EditorUI.current.widgets.ClickableText($"remove_layer_{index}", "Remove", removeSize, "Remove this definition while preserving Scene slot assignments.")) - { + var removeSize = new Vector2(Gui.MeasureText("Remove").X, Gui.GetFrameHeight()); + if (EditorUI.current.widgets.ClickableText( + $"remove_layer_{index}", + "Remove", + removeSize, + "Remove this definition while preserving Scene slot assignments." + )) { _ = setting.Remove(layer); SynchronizeSlot(setting, layer); m_error = string.Empty; @@ -119,27 +147,7 @@ int index } finally { - Ui.PopId(); - } - } - - private static bool DrawTextField( - string id, - string hint, - ref string value - ) { - Ui.SetNextItemWidth(-1f); - Ui.PushStyleColor(ImGuiCol.FrameBg, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.FrameBgHovered, EditorPalette.transparent); - Ui.PushStyleColor(ImGuiCol.FrameBgActive, EditorPalette.transparent); - try - { - bool submitted = Ui.InputTextWithHint(id, hint, ref value, C_LAYER_NAME_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue); - return submitted || Ui.IsItemDeactivatedAfterEdit(); - } - finally - { - Ui.PopStyleColor(3); + Gui.PopID(); } } @@ -148,59 +156,23 @@ private void DrawLayerToolbar( string? [] names, int definedCount ) { - float spacing = Ui.GetLayout().itemSpacing.X; + float spacing = Gui.GetLayout().itemSpacing.X; EditorUI.current.widgets.LabelChip("Defined", EditorPalette.collectionRowAlternate); - Ui.SameLine(0f, 0f); + Gui.SameLine(0f, 0f); DrawReadOnlyCount($"{definedCount} / {GameLayer.C_MAX_COUNT}", 78f * EditorUI.current.widgets.style.zoom); - Ui.SameLine(0f, spacing); + Gui.SameLine(0f, spacing); DrawAddLayer(setting, names, definedCount); } - private static void DrawReadOnlyCount( - string value, - float width - ) { - EditorUiLayout style = Ui.GetLayout(); - Vector2 minimum = Ui.GetCursorScreenPosition(); - Vector2 size = new(MathF.Max(1f, width), Ui.GetFrameHeight()); - Ui.Dummy(size); - Vector2 maximum = minimum + size; - Ui.DrawFilledRectangle(minimum, maximum, Ui.GetStyleColor(ImGuiCol.FrameBg), style.frameRounding); - Ui.DrawRectangle(minimum, maximum, Ui.GetStyleColor(ImGuiCol.Border), style.frameRounding, EditorUI.current.widgets.style.borderSize); - Vector2 textSize = Ui.MeasureText(value); - Ui.DrawText(minimum + (size - textSize) * 0.5f, Ui.GetStyleColor(ImGuiCol.Text), value); - } - - private static void DrawLayerTableHeader() - { - uint background = Ui.ToPackedColor(EditorPalette.collectionHeader); - Ui.TableNextRow(); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, background); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, background); - DrawHeaderCell(0, "Slot"); - DrawHeaderCell(1, "Name"); - DrawHeaderCell(2, "Action"); - } - - private static void DrawHeaderCell( - int column, - string label - ) { - _ = Ui.TableSetColumnIndex(column); - InsetPlainCell(); - Ui.Text(label); - } - - private static void InsetPlainCell() => Ui.SetCursorPosX(Ui.GetCursorPosX() + Ui.GetLayout().framePadding.X); private void DrawAddLayer( GameLayerCatalog setting, string? [] names, int definedCount ) { - Ui.BeginDisabled(definedCount >= GameLayer.C_MAX_COUNT); + Gui.BeginDisabled(definedCount >= GameLayer.C_MAX_COUNT); try { - float selectorWidth = MathF.Max(1f, Ui.GetContentRegionAvailable().X); + float selectorWidth = MathF.Max(1f, Gui.GetContentRegionAvailable().X); if (!EditorUI.current.widgets.BeginMenuSelector("add_game_layer", "Add layer...", selectorWidth, selectorWidth)) { return; @@ -211,10 +183,14 @@ int definedCount for (int index = 1; index < GameLayer.C_MAX_COUNT; index++) { if (!string.IsNullOrWhiteSpace(names[index])) + { continue; + } string slot = index.ToString("00", CultureInfo.InvariantCulture); - if (Ui.Selectable($"{slot} Layer {index}")) + if (Gui.Selectable($"{slot} Layer {index}")) + { CommitDefinition(setting, new GameLayer(index), $"Layer {index}"); + } } } finally @@ -224,7 +200,7 @@ int definedCount } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } @@ -254,7 +230,9 @@ private void SynchronizeBuffers(IReadOnlyList names) } for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) + { m_nameBuffers[index] = names[index] ?? string.Empty; + } m_observedNames = names.ToArray(); } @@ -266,11 +244,76 @@ GameLayer layer m_observedNames = CaptureNames(setting); } + private static bool DrawTextField( + string id, + string hint, + ref string value + ) { + Gui.SetNextItemWidth(-1f); + Gui.PushStyleColor(ImGuiCol.FrameBg, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.FrameBgHovered, EditorPalette.transparent); + Gui.PushStyleColor(ImGuiCol.FrameBgActive, EditorPalette.transparent); + try + { + bool submitted = Gui.InputTextWithHint(id, hint, ref value, C_LAYER_NAME_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue); + return submitted || Gui.IsItemDeactivatedAfterEdit(); + } + finally + { + Gui.PopStyleColor(3); + } + } + + private static void DrawReadOnlyCount( + string value, + float width + ) { + EditorUILayout style = Gui.GetLayout(); + Vector2 minimum = Gui.GetCursorScreenPosition(); + var size = new Vector2(MathF.Max(1f, width), Gui.GetFrameHeight()); + Gui.Dummy(size); + Vector2 maximum = minimum + size; + Gui.DrawFilledRectangle(minimum, maximum, Gui.GetStyleColor(ImGuiCol.FrameBg), style.frameRounding); + Gui.DrawRectangle( + minimum, + maximum, + Gui.GetStyleColor(ImGuiCol.Border), + style.frameRounding, + EditorUI.current.widgets.style.borderSize + ); + Vector2 textSize = Gui.MeasureText(value); + Gui.DrawText(minimum + (size - textSize) * 0.5f, Gui.GetStyleColor(ImGuiCol.Text), value); + } + + private static void DrawLayerTableHeader() + { + uint background = Gui.ToPackedColor(EditorPalette.collectionHeader); + Gui.TableNextRow(); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, background); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, background); + DrawHeaderCell(0, "Slot"); + DrawHeaderCell(1, "Name"); + DrawHeaderCell(2, "Action"); + } + + private static void DrawHeaderCell( + int column, + string label + ) { + _ = Gui.TableSetColumnIndex(column); + InsetPlainCell(); + Gui.Text(label); + } + + private static void InsetPlainCell() => Gui.SetCursorPosX(Gui.GetCursorPosX() + Gui.GetLayout().framePadding.X); + private static string? [] CaptureNames(GameLayerCatalog stack) { var result = new string? [GameLayer.C_MAX_COUNT]; for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) + { result[index] = stack.GetName(new GameLayer(index)); + } return result; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs index c7cc565ac..ded1aa06a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs @@ -1,16 +1,18 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; using Inno.Scene.Layers; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the project layer picker used by GameObject target headers. /// @@ -18,6 +20,7 @@ internal sealed class GameObjectLayerSelector { private readonly SceneProjectSettingsModule m_settings; private readonly SceneEdits m_edits; + /// /// Creates a layer selector backed by the project Settings layer catalog. /// @@ -34,8 +37,10 @@ internal GameObjectLayerSelector( SceneProjectSettingsModule settings, SceneEdits edits ) { - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(edits); + m_settings = settings; + m_edits = edits; } /// @@ -57,18 +62,26 @@ float width ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return; + } GameObject target = targets[0]; bool mixed = targets.Any(value => value.layer != target.layer); GameLayerCatalog stack = m_settings.layerStack; string preview = FormatLayerPreview(stack.GetName(target.layer)); if (mixed) + { preview = "Mixed values"; + } EditorUI.current.widgets.LabelChip("Layer", InspectorTargetStyle.layerLabel); - Ui.SameLine(0f, 0f); + Gui.SameLine(0f, 0f); float selectorWidth = MathF.Max(1f, width); - if (!EditorUI.current.widgets.BeginMenuSelector($"game_object_layer_{target.identity.persistentId:N}", preview, selectorWidth, selectorWidth)) - { + if (!EditorUI.current.widgets.BeginMenuSelector( + $"game_object_layer_{target.identity.persistentID:N}", + preview, + selectorWidth, + selectorWidth + )) { return; } @@ -79,11 +92,13 @@ float width { GameLayerDefinition definition = definitions[i]; string label = FormatLayerLabel(definition.layer, definition.name); - if (Ui.Selectable(label, definition.layer == target.layer)) + if (Gui.Selectable(label, definition.layer == target.layer)) { using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Set Selection Layer"); foreach (GameObject selected in targets) + { m_edits.SetGameObjectLayer(selected, definition.layer); + } transaction.Commit(); } } @@ -104,9 +119,11 @@ float width /// when the layer can be selected. /// internal bool IsLayerDefined(GameLayer layer) => m_settings.layerStack.IsDefined(layer); + private static string FormatLayerLabel( GameLayer layer, string name ) => $"({layer.index}) {name}"; + private static string FormatLayerPreview(string? name) => name ?? "Undefined"; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs index 935eb2405..4c032d8f0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs @@ -1,11 +1,10 @@ using System; - using Inno.Core.Diagnostics; using Inno.Core.Settings; using Inno.Editor.Core; +using Inno.Runtime; using Inno.Scene; using Inno.Scene.Layers; -using Inno.Runtime; namespace Inno.Editor.Panel.Inspector; @@ -27,7 +26,8 @@ internal SceneProjectSettingsModule( RuntimeSession runtimeSession, DiagnosticHub diagnostics ) { - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(settings); + m_settings = settings; ArgumentNullException.ThrowIfNull(runtimeSession); ArgumentNullException.ThrowIfNull(diagnostics); m_layerDiagnostics = new GameLayerDiagnosticPublisher(runtimeSession.scenes, diagnostics); @@ -40,8 +40,9 @@ DiagnosticHub diagnostics /// /// Thrown before the module has started. /// - internal GameLayerCatalog layerStack => m_layerStack - ?? throw new InvalidOperationException("The project layer settings are not available."); + internal GameLayerCatalog layerStack + => m_layerStack + ?? throw new InvalidOperationException("The project layer settings are not available."); /// /// Gets the effective project tag catalog snapshot. @@ -49,8 +50,9 @@ DiagnosticHub diagnostics /// /// Thrown before the module has started. /// - internal GameTagCatalog tagCatalog => m_tagCatalog - ?? throw new InvalidOperationException("The project tag settings are not available."); + internal GameTagCatalog tagCatalog + => m_tagCatalog + ?? throw new InvalidOperationException("The project tag settings are not available."); /// /// Initializes this feature when its owning runtime becomes active. @@ -69,7 +71,9 @@ DiagnosticHub diagnostics protected override void OnUpdate(EditorContext context) { if (m_observedRevision != m_settings.revision) + { RefreshSettings(); + } m_layerDiagnostics.Refresh(layerStack); m_tagDiagnostics.Refresh(tagCatalog); } @@ -91,8 +95,8 @@ protected override void OnStop(EditorContext context) private void RefreshSettings() { - m_layerStack = m_settings.Get(GameLayerCatalog.settingId); - m_tagCatalog = m_settings.Get(GameTagCatalog.settingId); + m_layerStack = m_settings.Get(GameLayerCatalog.settingID); + m_tagCatalog = m_settings.Get(GameTagCatalog.settingID); m_observedRevision = m_settings.revision; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs index 8a9721041..d59aeae18 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Core.Identity; @@ -9,14 +8,18 @@ using Inno.Editor.Scene; using Inno.Scene; using Inno.Scene.Components; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + internal sealed class InspectorCardControls { private const string C_COMPONENT_PAYLOAD = "INNO_INSPECTOR_COMPONENT"; private const string C_SYSTEM_PAYLOAD = "INNO_INSPECTOR_SYSTEM"; private readonly Logger m_log; + internal InspectorCardControls(LogRouter logs) { ArgumentNullException.ThrowIfNull(logs); @@ -24,6 +27,7 @@ internal InspectorCardControls(LogRouter logs) } internal float GetWidth(bool canRemove) => EditorUI.current.widgets.GetCompactClickableTextSize().X * (canRemove ? 2f : 1f); + internal void DrawComponent( SceneEdits edits, GameComponent component, @@ -33,16 +37,18 @@ Action requestRemove ArgumentNullException.ThrowIfNull(edits); ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(requestRemove); - Guid componentId = component.identity.persistentId; - if (EditorUI.current.widgets.ClickableText($"reset_Component_{componentId:N}", ImGuiIcon.ArrowRotateLeft, "Reset Component")) + Guid componentID = component.identity.persistentID; + if (EditorUI.current.widgets.ClickableText($"reset_Component_{componentID:N}", ImGuiIcon.C_ARROW_ROTATE_LEFT, "Reset Component")) { TryEdit(() => edits.ResetComponent(component), "Component reset"); } if (!canRemove) + { return; - Ui.SameLine(0f, 0f); - if (EditorUI.current.widgets.ClickableText($"remove_Component_{componentId:N}", ImGuiIcon.Xmark, "Remove Component")) + } + Gui.SameLine(0f, 0f); + if (EditorUI.current.widgets.ClickableText($"remove_Component_{componentID:N}", ImGuiIcon.C_XMARK, "Remove Component")) { requestRemove(); } @@ -58,14 +64,14 @@ Action requestRemove ArgumentNullException.ThrowIfNull(owner); ArgumentNullException.ThrowIfNull(system); ArgumentNullException.ThrowIfNull(requestRemove); - Guid systemId = system.identity.persistentId; - if (EditorUI.current.widgets.ClickableText($"reset_System_{systemId:N}", ImGuiIcon.ArrowRotateLeft, "Reset System")) + Guid systemID = system.identity.persistentID; + if (EditorUI.current.widgets.ClickableText($"reset_System_{systemID:N}", ImGuiIcon.C_ARROW_ROTATE_LEFT, "Reset System")) { TryEdit(() => edits.ResetSystem(system), "System reset"); } - Ui.SameLine(0f, 0f); - if (EditorUI.current.widgets.ClickableText($"remove_System_{systemId:N}", ImGuiIcon.Xmark, "Remove System")) + Gui.SameLine(0f, 0f); + if (EditorUI.current.widgets.ClickableText($"remove_System_{systemID:N}", ImGuiIcon.C_XMARK, "Remove System")) { requestRemove(); } @@ -79,8 +85,15 @@ bool dimmed ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(title); if (component.identity.runtimeIdentity is not RuntimeIdentity identity) + { return; - _ = EditorUI.current.widgets.DragDropSource(C_COMPONENT_PAYLOAD, identity, () => DrawDragPreview(title, dimmed), allowHoldToOpenOthers: false); + } + _ = EditorUI.current.widgets.DragDropSource( + C_COMPONENT_PAYLOAD, + identity, + () => DrawDragPreview(title, dimmed), + allowHoldToOpenOthers: false + ); } internal void DrawSystemDragSource( @@ -91,8 +104,15 @@ bool dimmed ArgumentNullException.ThrowIfNull(system); ArgumentNullException.ThrowIfNull(title); if (system.identity.runtimeIdentity is not RuntimeIdentity identity) + { return; - _ = EditorUI.current.widgets.DragDropSource(C_SYSTEM_PAYLOAD, identity, () => DrawDragPreview(title, dimmed), allowHoldToOpenOthers: false); + } + _ = EditorUI.current.widgets.DragDropSource( + C_SYSTEM_PAYLOAD, + identity, + () => DrawDragPreview(title, dimmed), + allowHoldToOpenOthers: false + ); } internal void DrawComponentDropTarget( @@ -106,25 +126,30 @@ Vector2 cardMaximum ArgumentNullException.ThrowIfNull(interactions); ArgumentNullException.ThrowIfNull(edits); ArgumentNullException.ThrowIfNull(target); - DrawDropTarget(C_COMPONENT_PAYLOAD, $"component_{target.identity.persistentId:N}", interactions, cardMinimum, cardMaximum, source => source is GameComponent component - && ReferenceEquals( - component.gameObject, - target.gameObject - ) - && !ReferenceEquals( - component, - target - ), ( - source, - insertAfter - ) => - { - var component = (GameComponent)source; + DrawDropTarget( + C_COMPONENT_PAYLOAD, + $"component_{target.identity.persistentID:N}", + interactions, + cardMinimum, + cardMaximum, + source => ( + source is GameComponent component + && ReferenceEquals(component.gameObject, target.gameObject) + && !ReferenceEquals(component, target) + ), + ( + source, + insertAfter + ) => + { + GameComponent component = (GameComponent)source; int sourceIndex = component.gameObject.GetComponentIndex(component); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; edits.SetComponentIndex(component, destinationIndex); - }, "Component reorder"); + }, + "Component reorder" + ); } internal void DrawSystemDropTarget( @@ -140,25 +165,30 @@ Vector2 cardMaximum ArgumentNullException.ThrowIfNull(edits); ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(target); - DrawDropTarget(C_SYSTEM_PAYLOAD, $"system_{target.identity.persistentId:N}", interactions, cardMinimum, cardMaximum, source => source is GameSystem system - && !ReferenceEquals( - system, - target - ) - && IsOwnedBy( - scene, - system - ), ( - source, - insertAfter - ) => - { - var system = (GameSystem)source; + DrawDropTarget( + C_SYSTEM_PAYLOAD, + $"system_{target.identity.persistentID:N}", + interactions, + cardMinimum, + cardMaximum, + source => ( + source is GameSystem system + && !ReferenceEquals(system, target) + && IsOwnedBy(scene, system) + ), + ( + source, + insertAfter + ) => + { + GameSystem system = (GameSystem)source; int sourceIndex = scene.GetSystemIndex(system); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; edits.SetSystemIndex(scene, system, destinationIndex); - }, "System reorder"); + }, + "System reorder" + ); } private void DrawDropTarget( @@ -171,54 +201,40 @@ private void DrawDropTarget( Action move, string operation ) { - if (!Inno.Editor.ImGui.ImGui.HasDragPayload(payloadType) || cardMaximum.X <= cardMinimum.X || cardMaximum.Y <= cardMinimum.Y) + if (!Gui.HasDragPayload(payloadType) || cardMaximum.X <= cardMinimum.X || cardMaximum.Y <= cardMinimum.Y) { return; } - uint targetId = Ui.GetControlId($"##inspector_card_drop_{id}"); + uint targetID = Gui.GetControlID($"##inspector_card_drop_{id}"); bool delivered = EditorUI.current.widgets.DragDropTarget( payloadType, cardMinimum, cardMaximum, - targetId, + targetID, out RuntimeIdentity identity, out bool isPreviewing, drawDefaultHighlight: false ); if (!isPreviewing && !delivered) + { return; + } if (!interactions.TryResolveIdentity(identity, out IdentityObject? source) || source is null || !accepts(source)) { return; } - bool insertAfter = Ui.GetMousePos().Y >= (cardMinimum.Y + cardMaximum.Y) * 0.5f; + bool insertAfter = Gui.GetMousePos().Y >= (cardMinimum.Y + cardMaximum.Y) * 0.5f; float markerY = insertAfter ? cardMaximum.Y : cardMinimum.Y; if (isPreviewing) + { EditorUI.current.widgets.InsertionLine(cardMinimum.X, cardMaximum.X, markerY); + } if (delivered) + { TryEdit(() => move(source, insertAfter), operation); - } - - private static void DrawDragPreview( - string title, - bool dimmed - ) { - Vector2 origin = Ui.GetCursorScreenPosition(); - Vector2 padding = EditorUI.current.widgets.style.cardHeaderPadding; - Vector2 gripSize = Ui.MeasureText(ImGuiIcon.GripVertical); - Vector2 titleSize = Ui.MeasureText(title); - Vector2 size = new( - padding.X * 2f + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing + titleSize.X, - MathF.Max(gripSize.Y, titleSize.Y) + padding.Y * 2f - ); - Ui.DrawFilledRectangle(origin, origin + size, Ui.ToPackedColor(EditorPalette.cardHeader), EditorUI.current.widgets.style.frameRounding); - uint color = Ui.ToPackedColor(dimmed ? EditorPalette.cardDisabledText : EditorPalette.text); - Vector2 textOrigin = origin + padding; - Ui.DrawText(textOrigin, color, ImGuiIcon.GripVertical); - Ui.DrawText(new Vector2(textOrigin.X + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing, textOrigin.Y), color, title); - Ui.Dummy(size); + } } private void TryEdit( @@ -235,6 +251,35 @@ string operation } } + private static void DrawDragPreview( + string title, + bool dimmed + ) { + Vector2 origin = Gui.GetCursorScreenPosition(); + Vector2 padding = EditorUI.current.widgets.style.cardHeaderPadding; + Vector2 gripSize = Gui.MeasureText(ImGuiIcon.C_GRIP_VERTICAL); + Vector2 titleSize = Gui.MeasureText(title); + var size = new Vector2( + padding.X * 2f + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing + titleSize.X, + MathF.Max(gripSize.Y, titleSize.Y) + padding.Y * 2f + ); + Gui.DrawFilledRectangle( + origin, + origin + size, + Gui.ToPackedColor(EditorPalette.cardHeader), + EditorUI.current.widgets.style.frameRounding + ); + uint color = Gui.ToPackedColor(dimmed ? EditorPalette.cardDisabledText : EditorPalette.text); + Vector2 textOrigin = origin + padding; + Gui.DrawText(textOrigin, color, ImGuiIcon.C_GRIP_VERTICAL); + Gui.DrawText( + new Vector2(textOrigin.X + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing, textOrigin.Y), + color, + title + ); + Gui.Dummy(size); + } + private static bool IsOwnedBy( GameScene scene, GameSystem system diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs index c8cdcc93e..bd96f3124 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; using Inno.Editor.Interactions; using Inno.Scene; @@ -14,9 +13,14 @@ internal sealed class InspectorLockControl private WeakReference? m_collectibleTarget; private object? m_lockedTarget; private RuntimeIdentity? m_lockedIdentity; - private Guid m_lockedPersistentId; + private Guid m_lockedPersistentID; private bool m_isLocked; + /// + /// Gets whether the Inspector is currently retaining a target independently from global selection. + /// + internal bool isLocked => m_isLocked; + /// /// Resolves the target that the Inspector should present this frame. /// @@ -44,11 +48,6 @@ internal sealed class InspectorLockControl return IsValid(target) ? target : null; } - /// - /// Gets whether the Inspector is currently retaining a target independently from global selection. - /// - internal bool isLocked => m_isLocked; - /// /// Toggles target retention using the target currently displayed by the Inspector. /// @@ -70,14 +69,16 @@ object displayedTarget } if (!IsValid(displayedTarget)) + { return; + } m_isLocked = true; if (displayedTarget is IdentityObject identityObject) { if (identityObject.identity.runtimeIdentity is RuntimeIdentity runtimeIdentity) { m_lockedIdentity = runtimeIdentity; - m_lockedPersistentId = identityObject.identity.persistentId; + m_lockedPersistentID = identityObject.identity.persistentID; return; } } @@ -96,7 +97,7 @@ private void Clear() m_collectibleTarget = null; m_lockedTarget = null; m_lockedIdentity = null; - m_lockedPersistentId = Guid.Empty; + m_lockedPersistentID = Guid.Empty; m_isLocked = false; } @@ -105,14 +106,18 @@ private void Clear() if (m_lockedIdentity is RuntimeIdentity identity) { if (interactions.TryResolveIdentity(identity, out IdentityObject? target)) + { return target; - return interactions.TryResolveIdentity(identity.domainId, m_lockedPersistentId, out target) - ? target - : null; + } + return interactions.TryResolveIdentity(identity.domainID, m_lockedPersistentID, out target) + ? target + : null; } if (m_collectibleTarget is not null) + { return m_collectibleTarget.TryGetTarget(out object? target) ? target : null; + } return m_lockedTarget; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs index aa7077e08..9192d7e3a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Core.Logging; @@ -10,9 +9,12 @@ using Inno.Editor.PlayMode; using Inno.Editor.Scene; using Inno.Scene; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the registered inspector for the current editor selection. /// @@ -26,14 +28,6 @@ internal sealed class InspectorPanel : EditorPanel private readonly InspectorTargetHeader m_targetHeader; private readonly Logger m_log; private string m_failureState = string.Empty; - /// - /// Gets whether use window padding is enabled for this implementation. - /// - public override bool useWindowPadding => false; - /// - /// Lets the inspector content child own vertical scrolling. - /// - public override bool allowScrolling => false; /// /// Creates the panel. @@ -63,15 +57,29 @@ internal InspectorPanel( IEditorPlayMode playMode, LogRouter logs ) { - m_inspection = inspection ?? throw new ArgumentNullException(nameof(inspection)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_sceneEdits = sceneEdits ?? throw new ArgumentNullException(nameof(sceneEdits)); - m_playMode = playMode ?? throw new ArgumentNullException(nameof(playMode)); + ArgumentNullException.ThrowIfNull(inspection); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(sceneEdits); + ArgumentNullException.ThrowIfNull(playMode); + m_inspection = inspection; + m_interactions = interactions; + m_sceneEdits = sceneEdits; + m_playMode = playMode; ArgumentNullException.ThrowIfNull(logs); m_log = logs.CreateLogger(); m_targetHeader = new InspectorTargetHeader(); } + /// + /// Gets whether use window padding is enabled for this implementation. + /// + public override bool useWindowPadding => false; + + /// + /// Lets the inspector content child own vertical scrolling. + /// + public override bool allowScrolling => false; + /// /// Draws this feature using the current editor presentation context. /// @@ -80,7 +88,7 @@ LogRouter logs /// protected override void OnDraw(EditorContext context) { - bool visible = Ui.BeginChild("##InspectorScrollRegion", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoSavedSettings)); + bool visible = Gui.BeginChild("##InspectorScrollRegion", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoSavedSettings)); try { if (visible) @@ -90,13 +98,16 @@ protected override void OnDraw(EditorContext context) } finally { - Ui.EndChild(); + Gui.EndChild(); } } private void DrawContent(EditorContext context) { - object? target = m_targetHeader.Resolve(m_interactions, m_interactions.selection.count > 1 ? m_interactions.selection.Capture() : m_interactions.selection.selectedTarget); + object? target = m_targetHeader.Resolve( + m_interactions, + m_interactions.selection.count > 1 ? m_interactions.selection.Capture() : m_interactions.selection.selectedTarget + ); if (target is null) { m_failureState = string.Empty; @@ -104,8 +115,10 @@ private void DrawContent(EditorContext context) return; } - if (!m_inspection.TryResolve(context, target, out IInspectionDrawer? drawer, out InspectionDrawContext? drawContext) || drawer is null || drawContext is null) - { + if (!m_inspection.TryResolve(context, target, out IInspectionDrawer? drawer, out InspectionDrawContext? drawContext) + || drawer is null + || drawContext is null + ) { m_failureState = string.Empty; EditorUI.current.widgets.Hint($"No inspector drawer is registered for {target.GetType().Name}."); return; @@ -118,14 +131,14 @@ private void DrawContent(EditorContext context) try { m_targetHeader.Draw(drawer, drawContext, readOnlyScene, notice); - Ui.BeginDisabled(readOnlyScene); + Gui.BeginDisabled(readOnlyScene); try { EditorUI.current.widgets.SectionLayout(() => drawer.Draw(drawContext)); } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } m_failureState = string.Empty; @@ -136,7 +149,11 @@ private void DrawContent(EditorContext context) string failureState = $"{target.GetType().FullName}:{exception}"; if (!string.Equals(m_failureState, failureState, StringComparison.Ordinal)) { - m_log.Write(LogLevel.Error, "Inspector failed for target '{0}': {1}", [target.GetType().FullName ?? target.GetType().Name, exception]); + m_log.Write( + LogLevel.Error, + "Inspector failed for target '{0}': {1}", + [target.GetType().FullName ?? target.GetType().Name, exception] + ); m_failureState = failureState; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs index 8a571c9a9..1141a76a7 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs @@ -1,13 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; -using Inno.Editor.Inspection; +using System.Runtime.CompilerServices; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; using Inno.Editor.Interactions; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the persistent identity header shared by every Inspector target type. /// @@ -15,22 +18,24 @@ internal sealed class InspectorTargetHeader { private const int C_NAME_BUFFER_SIZE = 512; private readonly InspectorLockControl m_lock = new(); + /// /// Resolves the target that should be presented after applying Inspector lock state. /// - /// - /// The current valid Inspector target, or when none is available. - /// /// /// Shared interaction service that resolves targets in their owning identity domains. /// /// /// The current inspection target used to render the header. /// + /// + /// The current valid Inspector target, or when none is available. + /// internal object? Resolve( EditorInteractions interactions, object? selectedTarget ) => m_lock.Resolve(interactions, selectedTarget); + /// /// Draws the common framed header for a resolved Inspector target. /// @@ -56,20 +61,26 @@ internal void Draw( ArgumentNullException.ThrowIfNull(context); EditorUI.current.widgets.HeaderSurface("##inspector_target_header", () => { - Ui.BeginDisabled(readOnly); + Gui.BeginDisabled(readOnly); try { DrawContent(drawer, context); } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } if (notice is null) + { return; - Ui.Spacing(); - EditorUI.current.widgets.HelpBox(notice, ImGuiIcon.CircleInfo, new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque)); + } + Gui.Spacing(); + EditorUI.current.widgets.HelpBox( + notice, + ImGuiIcon.C_CIRCLE_INFO, + new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.C_OPACITY_OPAQUE) + ); }, spanWindowPadding: true); } @@ -77,30 +88,30 @@ private void DrawContent( IInspectionDrawer drawer, InspectionDrawContext context ) { - Ui.PushStyleVar(ImGuiStyleVar.ItemSpacing, EditorUI.current.widgets.style.compactItemSpacing); - Ui.PushStyleVar(ImGuiStyleVar.FramePadding, EditorUI.current.widgets.style.compactFramePadding); + Gui.PushStyleVar(ImGuiStyleVar.ItemSpacing, EditorUI.current.widgets.style.compactItemSpacing); + Gui.PushStyleVar(ImGuiStyleVar.FramePadding, EditorUI.current.widgets.style.compactFramePadding); try { - float rowHeight = Ui.GetFrameHeight(); + float rowHeight = Gui.GetFrameHeight(); float rowSpacing = EditorUI.current.widgets.style.targetHeaderRowSpacing; float headerContentHeight = rowHeight * 2f + rowSpacing; DrawIcon(drawer.GetIcon(context), headerContentHeight); - Ui.SameLine(0f, -1f); - Ui.BeginGroup(); + Gui.SameLine(0f, -1f); + Gui.BeginGroup(); try { DrawNameRow(drawer, context, rowHeight); - Ui.SetCursorPosY(Ui.GetCursorPosY() + rowSpacing); + Gui.SetCursorPosY(Gui.GetCursorPosY() + rowSpacing); DrawCustomRow(drawer, context, rowHeight); } finally { - Ui.EndGroup(); + Gui.EndGroup(); } } finally { - Ui.PopStyleVar(2); + Gui.PopStyleVar(2); } } @@ -110,56 +121,62 @@ private void DrawNameRow( float rowHeight ) { Vector2 lockSize = EditorUI.current.widgets.GetCompactIconSize(); - float itemSpacing = Ui.GetLayout().itemSpacing.X; - float nameWidth = MathF.Max(1f, Ui.GetContentRegionAvailable().X - lockSize.X - itemSpacing); + float itemSpacing = Gui.GetLayout().itemSpacing.X; + float nameWidth = MathF.Max(1f, Gui.GetContentRegionAvailable().X - lockSize.X - itemSpacing); (string name, Action? nameSetter) = drawer.BindName(context); if (nameSetter is not null) { - Ui.SetNextItemWidth(nameWidth); - if (Ui.InputText($"##inspector_target_name_{GetTargetId(context.target)}", ref name, C_NAME_BUFFER_SIZE, ImGuiInputTextFlags.None)) - { + Gui.SetNextItemWidth(nameWidth); + if (Gui.InputText( + $"##inspector_target_name_{GetTargetID(context.target)}", + ref name, + C_NAME_BUFFER_SIZE, + ImGuiInputTextFlags.None + )) { nameSetter(name); } - Ui.SameLine(0f, itemSpacing); + Gui.SameLine(0f, itemSpacing); } else { - Ui.AlignTextToFramePadding(); - Vector2 textOrigin = Ui.GetCursorScreenPosition(); - EditorDrawList drawList = Ui.GetDrawList(); + Gui.AlignTextToFramePadding(); + Vector2 textOrigin = Gui.GetCursorScreenPosition(); + EditorDrawList drawList = Gui.GetDrawList(); drawList.PushClip(textOrigin, textOrigin + new Vector2(nameWidth, rowHeight)); try { - Ui.DrawText(textOrigin, Ui.GetStyleColor(ImGuiCol.Text), name); + Gui.DrawText(textOrigin, Gui.GetStyleColor(ImGuiCol.Text), name); } finally { drawList.PopClip(); } - Ui.Dummy(new Vector2(nameWidth, rowHeight)); - Ui.SameLine(0f, itemSpacing); + Gui.Dummy(new Vector2(nameWidth, rowHeight)); + Gui.SameLine(0f, itemSpacing); } - string lockIcon = m_lock.isLocked ? ImGuiIcon.Lock : ImGuiIcon.LockOpen; + string lockIcon = m_lock.isLocked ? ImGuiIcon.C_LOCK : ImGuiIcon.C_LOCK_OPEN; string tooltip = m_lock.isLocked ? "Unlock Inspector" : "Lock Inspector"; if (EditorUI.current.widgets.ClickableIcon("inspector_target_lock", lockIcon, tooltip)) + { m_lock.Toggle(context.interactions, context.target); + } } private static void DrawIcon( string icon, float slotSize ) { - Vector2 minimum = Ui.GetCursorScreenPosition(); + Vector2 minimum = Gui.GetCursorScreenPosition(); EditorUI.current.widgets.AddGlyphCentered( - Ui.GetFontSize() * EditorUI.current.widgets.style.targetIconScale, + Gui.GetFontSize() * EditorUI.current.widgets.style.targetIconScale, icon, minimum + new Vector2(slotSize * 0.5f), - Ui.GetStyleColor(ImGuiCol.Text) + Gui.GetStyleColor(ImGuiCol.Text) ); - Ui.Dummy(new Vector2(slotSize)); + Gui.Dummy(new Vector2(slotSize)); } private static void DrawCustomRow( @@ -168,17 +185,25 @@ private static void DrawCustomRow( float rowHeight ) { ImGuiWindowFlags flags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; - bool visible = Ui.BeginChild($"##inspector_target_custom_{GetTargetId(context.target)}", new Vector2(0f, rowHeight), ImGuiChildFlags.None, flags); + bool visible = Gui.BeginChild( + $"##inspector_target_custom_{GetTargetID(context.target)}", + new Vector2(0f, rowHeight), + ImGuiChildFlags.None, + flags + ); try { if (visible) + { drawer.DrawHeader(context); + } } finally { - Ui.EndChild(); + Gui.EndChild(); } } - private static string GetTargetId(object target) => $"{target.GetType().FullName}_{System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(target)}"; + private static string GetTargetID(object target) + => $"{target.GetType().FullName}_{RuntimeHelpers.GetHashCode(target)}"; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs index b500609c3..f093d72e2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs @@ -1,25 +1,27 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Reflection; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Extensibility.Modules; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + internal static class InspectorTypeOrigin { internal static void Draw(Type type) { ArgumentNullException.ThrowIfNull(type); - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.contextText); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.contextText); try { EditorUI.current.widgets.WrappedText("Source: " + Describe(type)); } finally { - Ui.PopStyleColor(); + Gui.PopStyleColor(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs index 7113b8c79..b94f0077b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Panel.Inspector; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Inspection", - "Inno.Editor.Panel.Inspector", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Inspection", "Inno.Editor.Panel.Inspector", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EngineObjectReferenceDropTarget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetReferenceDropTarget), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs index 6734731c7..f38ac0540 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs @@ -1,31 +1,35 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.IO; -using System.Runtime.CompilerServices; using System.Numerics; +using System.Runtime.CompilerServices; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [PropertyDrawer(typeof(AssetObject), useForChildren: true, priority: 100)] internal sealed class AssetReferencePropertyDrawer : IPropertyDrawer, IDisposable { private const nuint C_SEARCH_BUFFER_SIZE = 256; private readonly object m_sync = new(); private readonly AssetPipeline m_assets; - private ConditionalWeakTable m_candidatesByType = new(); private readonly Dictionary m_searchByPath = new(StringComparer.Ordinal); + private ConditionalWeakTable m_candidatesByType = new(); + internal AssetReferencePropertyDrawer(AssetPipeline assets) { - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); - m_assets.Changed += OnAssetsChanged; + ArgumentNullException.ThrowIfNull(assets); + m_assets = assets; + m_assets.changed += OnAssetsChanged; } /// @@ -33,7 +37,7 @@ internal AssetReferencePropertyDrawer(AssetPipeline assets) /// public void Dispose() { - m_assets.Changed -= OnAssetsChanged; + m_assets.changed -= OnAssetsChanged; lock (m_sync) { m_candidatesByType = new ConditionalWeakTable(); @@ -52,53 +56,64 @@ public void Draw(PropertyDrawContext context) Type assetType = context.propertyType; AssetCandidate[] candidates = GetCandidates(assetType); object? currentValue = context.GetValue(); - Guid persistentId = ReadPersistentId(currentValue); - AssetCandidate? selected = Array.Find(candidates, candidate => candidate.persistentId == persistentId); - string preview = persistentId == Guid.Empty ? "None" : currentValue is AssetObject { isMissing: true } missing ? $"Missing {missing.GetType().Name} [{persistentId}]" : selected is null ? $"Missing ({persistentId})" : selected.displayName; + Guid persistentID = ReadPersistentID(currentValue); + AssetCandidate? selected = Array.Find(candidates, candidate => candidate.persistentID == persistentID); + string preview = persistentID == Guid.Empty + ? "None" + : currentValue is AssetObject { isMissing: true } missing + ? $"Missing {missing.GetType().Name} [{persistentID}]" + : selected is null ? $"Missing ({persistentID})" : selected.displayName; bool open = EditorUI.current.widgets.BeginBoundedCombo($"##{context.path}", preview); - Vector2 dropMinimum = Ui.GetItemMinimum(); - Vector2 dropMaximum = Ui.GetItemMaximum(); - EditorDropWidgetResult drop = EditorDragDropRenderer.Target(context.interactions.For(InspectorInteractionIds.C_ASSET_REFERENCE_AREA, new AssetReferenceDropTarget(assetType, persistentIdToAssign => - { - AssetCandidate? dropped = Array.Find(candidates, candidate => candidate.persistentId == persistentIdToAssign); - if (dropped is not null) - AssignAsset(context, assetType, dropped); - }))); + Vector2 dropMinimum = Gui.GetItemMinimum(); + Vector2 dropMaximum = Gui.GetItemMaximum(); + EditorDropWidgetResult drop = EditorDragDropRenderer.Target( + context.interactions.For( + InspectorInteractionIDs.C_ASSET_REFERENCE_AREA, + new AssetReferenceDropTarget(assetType, persistentIDToAssign => + { + AssetCandidate? dropped = Array.Find(candidates, candidate => candidate.persistentID == persistentIDToAssign); + if (dropped is not null) + { + AssignAsset(context, assetType, dropped); + } + }) + ) + ); if (drop.isPreviewing && drop.status.canDrop) + { EditorUI.current.widgets.DropTargetHighlight(dropMinimum, dropMaximum); + } if (!open) + { return; + } try { string search = m_searchByPath.TryGetValue(context.path, out string? existingSearch) ? existingSearch : string.Empty; _ = EditorUI.current.widgets.SearchInput(context.path, "Search assets...", ref search, C_SEARCH_BUFFER_SIZE); m_searchByPath[context.path] = search; - if (Ui.Selectable("None", persistentId == Guid.Empty)) + if (Gui.Selectable("None", persistentID == Guid.Empty)) + { context.SetValue(null); + } for (int i = 0; i < candidates.Length; i++) { AssetCandidate candidate = candidates[i]; if (!string.IsNullOrWhiteSpace(search) - && candidate.displayName.IndexOf( - search, - StringComparison.OrdinalIgnoreCase - ) < 0 - && candidate.fullPath.IndexOf( - search, - StringComparison.OrdinalIgnoreCase - ) < 0) - { + && candidate.displayName.IndexOf(search, StringComparison.OrdinalIgnoreCase) < 0 + && candidate.fullPath.IndexOf(search, StringComparison.OrdinalIgnoreCase) < 0 + ) { continue; } - if (Ui.Selectable($"{candidate.displayName}##{candidate.persistentId:N}", candidate.persistentId == persistentId)) + if (Gui.Selectable($"{candidate.displayName}##{candidate.persistentID:N}", candidate.persistentID == persistentID)) { AssignAsset(context, assetType, candidate); } - if (Ui.IsItemHovered() && EditorUI.current.widgets.BeginMenuTooltip()) + if (Gui.IsItemHovered() && EditorUI.current.widgets.BeginMenuTooltip()) { - Ui.Text(candidate.fullPath); + Gui.Text(candidate.fullPath); EditorUI.current.widgets.EndMenuTooltip(); } } @@ -114,22 +129,26 @@ private AssetCandidate[] GetCandidates(Type targetAssetType) lock (m_sync) { if (m_candidatesByType.TryGetValue(targetAssetType, out CandidatesBox? cached)) + { return cached.candidates; + } IReadOnlyList entries = m_assets.GetFileSystemEntries(includeDirectories: false); var candidates = new List(entries.Count); for (int i = 0; i < entries.Count; i++) { AssetFileEntry entry = entries[i]; - if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) || assetType is null || !targetAssetType.IsAssignableFrom(assetType)) - { + if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) + || assetType is null + || !targetAssetType.IsAssignableFrom(assetType) + ) { continue; } - if (m_assets.TryGetPersistentId(entry.assetPath, out Guid persistentId)) + if (m_assets.TryGetPersistentID(entry.assetPath, out Guid persistentID)) { string name = Path.GetFileNameWithoutExtension(entry.assetPath.localPath); string displayName = $"{entry.assetPath.source.value}:{name}"; - candidates.Add(new AssetCandidate(entry.assetPath, persistentId, displayName, entry.assetPath.ToString())); + candidates.Add(new AssetCandidate(entry.assetPath, persistentID, displayName, entry.assetPath.ToString())); } } @@ -143,14 +162,15 @@ private AssetCandidate[] GetCandidates(Type targetAssetType) } } - private static Guid ReadPersistentId(object? reference) => reference is AssetObject asset ? asset.identity.persistentId : Guid.Empty; private void AssignAsset( PropertyDrawContext context, Type assetType, AssetCandidate candidate ) { - if (ReadPersistentId(context.GetValue()) == candidate.persistentId) + if (ReadPersistentID(context.GetValue()) == candidate.persistentID) + { return; + } object asset = m_assets.Load(candidate.assetPath, assetType); context.SetValue(asset); } @@ -158,14 +178,19 @@ AssetCandidate candidate private void OnAssetsChanged(AssetChangeSet changes) { lock (m_sync) + { m_candidatesByType = new ConditionalWeakTable(); + } } + private static Guid ReadPersistentID(object? reference) => reference is AssetObject asset ? asset.identity.persistentID : Guid.Empty; + private sealed record AssetCandidate( AssetPath assetPath, - Guid persistentId, + Guid persistentID, string displayName, string fullPath ); + private sealed record CandidatesBox(AssetCandidate[] candidates); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs index 1a1d05064..1467cba3a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs @@ -1,17 +1,19 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [PropertyDrawer(typeof(GameObject), useForChildren: true, priority: 100)] [PropertyDrawer(typeof(GameComponent), useForChildren: true, priority: 100)] internal sealed class EngineObjectReferencePropertyDrawer : IPropertyDrawer @@ -19,9 +21,11 @@ internal sealed class EngineObjectReferencePropertyDrawer : IPropertyDrawer private const nuint C_SEARCH_BUFFER_SIZE = 256; private readonly Dictionary m_searchByPath = new(StringComparer.Ordinal); private readonly RuntimeSession m_runtimeSession; + internal EngineObjectReferencePropertyDrawer(RuntimeSession runtimeSession) { - m_runtimeSession = runtimeSession ?? throw new ArgumentNullException(nameof(runtimeSession)); + ArgumentNullException.ThrowIfNull(runtimeSession); + m_runtimeSession = runtimeSession; } /// @@ -37,16 +41,25 @@ public void Draw(PropertyDrawContext context) List candidates = CollectCandidates(targetType); string preview = selected is null || selected.isDestroyed ? "None" : GetDisplayName(selected); bool open = EditorUI.current.widgets.BeginBoundedCombo($"##{context.path}", preview); - _ = EditorDragDropRenderer.Target(context.interactions.For(InspectorInteractionIds.C_ENGINE_OBJECT_REFERENCE_AREA, new EngineObjectReferenceDropTarget(targetType, value => context.SetValue(value)))); + _ = EditorDragDropRenderer.Target( + context.interactions.For( + InspectorInteractionIDs.C_ENGINE_OBJECT_REFERENCE_AREA, + new EngineObjectReferenceDropTarget(targetType, value => context.SetValue(value)) + ) + ); if (!open) + { return; + } try { string search = m_searchByPath.TryGetValue(context.path, out string? currentSearch) ? currentSearch : string.Empty; _ = EditorUI.current.widgets.SearchInput(context.path, "Search scene objects...", ref search, C_SEARCH_BUFFER_SIZE); m_searchByPath[context.path] = search; - if (Ui.Selectable("None", selected is null)) + if (Gui.Selectable("None", selected is null)) + { context.SetValue(null); + } for (int i = 0; i < candidates.Count; i++) { EngineObject candidate = candidates[i]; @@ -56,8 +69,10 @@ public void Draw(PropertyDrawContext context) continue; } - if (Ui.Selectable(displayName, ReferenceEquals(candidate, selected))) + if (Gui.Selectable(displayName, ReferenceEquals(candidate, selected))) + { context.SetValue(candidate); + } } } finally @@ -75,12 +90,16 @@ private List CollectCandidates(Type targetType) { GameObject gameObject = objects[objectIndex]; if (targetType.IsInstanceOfType(gameObject)) + { candidates.Add(gameObject); + } IReadOnlyList components = gameObject.GetComponents(); for (int componentIndex = 0; componentIndex < components.Count; componentIndex++) { if (targetType.IsInstanceOfType(components[componentIndex])) + { candidates.Add(components[componentIndex]); + } } } @@ -88,12 +107,10 @@ private List CollectCandidates(Type targetType) } private static string GetDisplayName(EngineObject target) + => target switch { - return target switch - { - GameObject gameObject => gameObject.name, - GameComponent component => $"{component.gameObject.name} ({component.GetType().Name})", - _ => target.GetType().Name - }; - } + GameObject gameObject => gameObject.name, + GameComponent component => $"{component.gameObject.name} ({component.GetType().Name})", + _ => target.GetType().Name + }; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs index 735f32075..b3db59199 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs @@ -4,12 +4,14 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + /// /// Adapts generic inspection property edits to compact Scene history records. /// internal sealed class SceneInspectionPropertyEditService : IInspectionPropertyEditService { private readonly SceneEdits m_edits; + /// /// Creates the Scene property edit adapter. /// @@ -18,10 +20,11 @@ internal sealed class SceneInspectionPropertyEditService : IInspectionPropertyEd /// internal SceneInspectionPropertyEditService(SceneEdits edits) { - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); + ArgumentNullException.ThrowIfNull(edits); + m_edits = edits; } - /// + /// public bool ChangeProperty( object owner, string propertyName, @@ -31,7 +34,8 @@ public bool ChangeProperty( string? componentName ) { ArgumentNullException.ThrowIfNull(owner); - EngineObject sceneObject = owner as EngineObject ?? throw new ArgumentException($"Scene property edits require an '{typeof(EngineObject).FullName}' owner.", nameof(owner)); + EngineObject sceneObject = owner as EngineObject + ?? throw new ArgumentException($"Scene property edits require an '{typeof(EngineObject).FullName}' owner.", nameof(owner)); return m_edits.ChangeProperty(sceneObject, propertyName, mutation, historyName, mergeKey); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs index 4784c6831..75d5ab1eb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Reflection; - using Inno.Editor.Inspection; namespace Inno.Editor.Panel.Inspector; @@ -23,7 +22,9 @@ internal InspectionDrawerActivator(params object[] dependencies) { ArgumentNullException.ThrowIfNull(dependencies); if (dependencies.Any(static dependency => dependency is null)) + { throw new ArgumentException("Inspection drawer dependencies cannot contain null.", nameof(dependencies)); + } m_dependencies = [.. dependencies]; } @@ -40,21 +41,26 @@ internal IInspectionDrawer Create(Type drawerType) { ArgumentNullException.ThrowIfNull(drawerType); ConstructorInfo[] constructors = drawerType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1) { throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' must declare exactly one constructor."); + $"Inspection drawer '{drawerType.FullName}' must declare exactly one constructor." + ); } ParameterInfo[] parameters = constructors[0].GetParameters(); var arguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) + { arguments[i] = Resolve(drawerType, parameters[i].ParameterType); + } return constructors[0].Invoke(arguments) as IInspectionDrawer ?? throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' does not implement " + - $"'{typeof(IInspectionDrawer).FullName}'."); + $"Inspection drawer '{drawerType.FullName}' does not implement " + + $"'{typeof(IInspectionDrawer).FullName}'." + ); } private object Resolve( @@ -68,12 +74,14 @@ Type dependencyType { 1 => matches[0], 0 => throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' requests unavailable dependency " + - $"'{dependencyType.FullName}'. Drawers should normally use InspectionDrawContext, " + - "or request one dependency supplied by the Inspector composition root."), + $"Inspection drawer '{drawerType.FullName}' requests unavailable dependency " + + $"'{dependencyType.FullName}'. Drawers should normally use InspectionDrawContext, " + + "or request one dependency supplied by the Inspector composition root." + ), _ => throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' has ambiguous dependency " + - $"'{dependencyType.FullName}'.") + $"Inspection drawer '{drawerType.FullName}' has ambiguous dependency " + + $"'{dependencyType.FullName}'." + ) }; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs index b7ecd068c..317cbc694 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs @@ -1,8 +1,6 @@ using System; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -10,6 +8,7 @@ using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Panel.Inspector; @@ -76,16 +75,16 @@ internal SceneInspectionModule( RuntimeSession runtimeSession, LogRouter logs ) { - System.ArgumentNullException.ThrowIfNull(interactions); - System.ArgumentNullException.ThrowIfNull(edits); - System.ArgumentNullException.ThrowIfNull(assetIcons); - System.ArgumentNullException.ThrowIfNull(classificationSettings); - System.ArgumentNullException.ThrowIfNull(settings); - System.ArgumentNullException.ThrowIfNull(assets); - System.ArgumentNullException.ThrowIfNull(types); - System.ArgumentNullException.ThrowIfNull(serialization); - System.ArgumentNullException.ThrowIfNull(runtimeSession); - System.ArgumentNullException.ThrowIfNull(logs); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(assetIcons); + ArgumentNullException.ThrowIfNull(classificationSettings); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(runtimeSession); + ArgumentNullException.ThrowIfNull(logs); m_assets = assets; var activator = new InspectionDrawerActivator( interactions, @@ -94,50 +93,23 @@ LogRouter logs classificationSettings, settings, serialization, - logs); + logs + ); m_inspectors = new InspectionDrawerRegistry(interactions, activator.Create, types, serialization); - m_properties = new PropertyDrawerRegistry( - interactions, - types, - serialization, - [assets, runtimeSession]); + m_properties = new PropertyDrawerRegistry(interactions, types, serialization, [assets, runtimeSession]); m_attributes = new InspectorAttributeDrawerRegistry( interactions, types, serialization, - [assets, runtimeSession]); + [assets, runtimeSession] + ); m_renderer = new SerializedPropertyRenderer( m_properties, m_attributes, interactions, new SceneInspectionPropertyEditService(edits), - logs); - } - - internal bool TryResolve( - EditorContext editorContext, - object target, - out IInspectionDrawer? drawer, - out InspectionDrawContext? drawContext - ) { - if (target is AssetFileEntry { isDirectory: false } entry && - m_assets.TryLoad(entry.assetPath, out AssetObject? asset) && - asset is not null && - m_inspectors.TryResolveExact( - editorContext, - asset, - m_renderer, - out drawer, - out drawContext)) - { - return true; - } - return m_inspectors.TryResolve( - editorContext, - target, - m_renderer, - out drawer, - out drawContext); + logs + ); } /// @@ -149,4 +121,20 @@ protected override void OnDispose() m_attributes.Dispose(); m_properties.Dispose(); } + + internal bool TryResolve( + EditorContext editorContext, + object target, + out IInspectionDrawer? drawer, + out InspectionDrawContext? drawContext + ) { + if (target is AssetFileEntry { isDirectory: false } entry + && m_assets.TryLoad(entry.assetPath, out AssetObject? asset) + && asset is not null + && m_inspectors.TryResolveExact(editorContext, asset, m_renderer, out drawer, out drawContext) + ) { + return true; + } + return m_inspectors.TryResolve(editorContext, target, m_renderer, out drawer, out drawContext); + } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs index 010d5e1ae..88650d54c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs @@ -8,10 +8,10 @@ internal static class InspectorTargetStyle /// /// Gets the subdued background of Tag labels in Inspector target headers. /// - internal static Vector4 tagLabel { get; } = new(0.34f, 0.29f, 0.44f, EditorPalette.opacityOpaque); + internal static Vector4 tagLabel { get; } = new(0.34f, 0.29f, 0.44f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets the subdued background of Layer labels in Inspector target headers. /// - internal static Vector4 layerLabel { get; } = new(0.24f, 0.34f, 0.40f, EditorPalette.opacityOpaque); + internal static Vector4 layerLabel { get; } = new(0.24f, 0.34f, 0.4f, EditorPalette.C_OPACITY_OPAQUE); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs index d35ee1c92..3c87cc7a8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs @@ -1,21 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Serialization; using Inno.Core.Logging; +using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; using Inno.Scene; using Inno.Scene.Components; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(GameObject))] internal sealed class GameObjectInspectionDrawer : InspectionDrawer { @@ -27,6 +29,7 @@ internal sealed class GameObjectInspectionDrawer : InspectionDrawer private readonly GameObjectLayerSelector m_layerSelector; private readonly EditorSettings m_settings; private string m_componentSearch = string.Empty; + /// /// Creates a GameObject drawer backed by the current project classification settings. /// @@ -56,19 +59,22 @@ internal GameObjectInspectionDrawer( SerializationRegistry serialization, LogRouter logs ) { - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(serialization); + m_edits = edits; ArgumentNullException.ThrowIfNull(classificationSettings); m_tagSelector = new GameObjectTagSelector(classificationSettings, edits); m_layerSelector = new GameObjectLayerSelector(classificationSettings, edits); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + m_settings = settings; + m_serialization = serialization; m_cardControls = new InspectorCardControls(logs); } /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!; + public override string icon => m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.C_CUBE)!; /// /// Binds a caller-visible label to the current inspection target. @@ -86,6 +92,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, GameObject target ) => (target.name, name => m_edits.RenameGameObject(target, name)); + /// /// Renders the header presentation for the current editor frame. /// @@ -100,20 +107,26 @@ protected override void DrawHeader( GameObject target ) { bool active = target.activeSelf; - if (EditorUI.current.widgets.CompactCheckbox($"target_active_{target.identity.persistentId:N}", ref active, tooltip: "Enable or disable this GameObject.")) - { + if (EditorUI.current.widgets.CompactCheckbox( + $"target_active_{target.identity.persistentID:N}", + ref active, + tooltip: "Enable or disable this GameObject." + )) { m_edits.SetGameObjectActive(target, active); } - Ui.SameLine(0f, -1f); - Ui.Text("Active"); - Ui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); - float available = Ui.GetContentRegionAvailable().X; + Gui.SameLine(0f, -1f); + Gui.Text("Active"); + Gui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); + float available = Gui.GetContentRegionAvailable().X; float tagLabelWidth = EditorUI.current.widgets.GetLabelChipSize("Tag").X; float layerLabelWidth = EditorUI.current.widgets.GetLabelChipSize("Layer").X; - float controlWidth = MathF.Max(1f, (available - tagLabelWidth - layerLabelWidth - EditorUI.current.widgets.style.headerSectionSpacing) * 0.5f); + float controlWidth = MathF.Max( + 1f, + (available - tagLabelWidth - layerLabelWidth - EditorUI.current.widgets.style.headerSectionSpacing) * 0.5f + ); m_tagSelector.Draw([target], context.interactions, controlWidth); - Ui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); + Gui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); m_layerSelector.Draw([target], context.interactions, controlWidth); } @@ -133,28 +146,32 @@ GameObject gameObject if (!gameObject.isRuntimeValid || !gameObject.scene.isLoaded) { _ = context.interactions.For(context.interactions.focusedArea).Select(); - Ui.Text("Selected GameObject is not available in the active scene."); + Gui.Text("Selected GameObject is not available in the active scene."); return; } if (!m_layerSelector.IsLayerDefined(gameObject.layer)) { - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Layer slot {gameObject.layer.index} is not defined in the current project settings. " + "Choose Default or restore that layer definition."); - Ui.PopStyleColor(); - Ui.Spacing(); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); + EditorUI.current.widgets.WrappedText( + $"Layer slot {gameObject.layer.index} is not defined in the current project settings. " + "Choose Default or restore that layer definition." + ); + Gui.PopStyleColor(); + Gui.Spacing(); } if (!m_tagSelector.IsTagDefined(gameObject.tag)) { - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Tag '{gameObject.tag}' is not defined in the current Project Settings. " + "Choose another tag or restore that tag definition."); - Ui.PopStyleColor(); - Ui.Spacing(); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); + EditorUI.current.widgets.WrappedText( + $"Tag '{gameObject.tag}' is not defined in the current Project Settings. " + "Choose another tag or restore that tag definition." + ); + Gui.PopStyleColor(); + Gui.Spacing(); } - Ui.PushStyleVar((ImGuiStyleVar.ItemSpacing), EditorUI.current.widgets.style.compactItemSpacing); - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); + Gui.PushStyleVar((ImGuiStyleVar.ItemSpacing), EditorUI.current.widgets.style.compactItemSpacing); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); try { DrawComponents(context, gameObject); @@ -162,7 +179,7 @@ GameObject gameObject } finally { - Ui.PopStyleVar(2); + Gui.PopStyleVar(2); } } @@ -176,50 +193,80 @@ GameObject gameObject GameComponent component = components[i]; Type componentType = component.GetType(); MissingGameComponent? missing = component as MissingGameComponent; - IReadOnlyList properties = missing is null ? m_serialization.GetProperties(component) : Array.Empty(); - string componentId = component.identity.persistentId.ToString("N"); + IReadOnlyList properties = missing is null + ? m_serialization.GetProperties(component) + : []; + string componentID = component.identity.persistentID.ToString("N"); GameBehavior? behavior = component as GameBehavior; - var editorTarget = component; + GameComponent editorTarget = component; string title = missing?.missingTypeName ?? componentType.Name; bool canRemove = componentType != typeof(Transform); bool dimmed = behavior is { enabled: false }; Vector2 cardMinimum = default; Vector2 headerMaximum = default; - bool open = EditorUI.current.widgets.CollapsingCard(componentId, title, behavior is not null ? () => - { - bool enabled = behavior.enabled; - if (EditorUI.current.widgets.CompactCheckbox($"enabled_{componentId}", ref enabled, tooltip: "Enable or disable this component.")) + bool open = EditorUI.current.widgets.CollapsingCard( + componentID, + title, + behavior is not null + ? () => { - _ = m_edits.ChangeProperty(behavior, "enabled", () => behavior.enabled = enabled, enabled ? "Enable Component" : "Disable Component", mergeKey: null); + bool enabled = behavior.enabled; + if (EditorUI.current.widgets.CompactCheckbox( + $"enabled_{componentID}", + ref enabled, + tooltip: "Enable or disable this component." + )) { + _ = m_edits.ChangeProperty( + behavior, + "enabled", + () => behavior.enabled = enabled, + enabled ? "Enable Component" : "Disable Component", + mergeKey: null + ); + } } - } : null, () => m_cardControls.DrawComponent( - m_edits, - component, - canRemove, - () => context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget).Enqueue(InspectorInteractionIds.C_REMOVE_COMPONENT) - ), dimmed: dimmed, trailingControlWidth: m_cardControls.GetWidth(canRemove), drawContextMenu: () => - { - cardMinimum = Ui.GetItemMinimum(); - headerMaximum = Ui.GetItemMaximum(); - _ = EditorUI.current.menus.ContextMenu($"##component_menu_{componentId}", context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget)); - m_cardControls.DrawComponentDragSource(component, title, dimmed); - }); + : null, + () => m_cardControls.DrawComponent( + m_edits, + component, + canRemove, + () => context.interactions + .For(InspectorInteractionIDs.C_COMPONENT_AREA, editorTarget) + .Enqueue(InspectorInteractionIDs.C_REMOVE_COMPONENT) + ), + dimmed: dimmed, + trailingControlWidth: m_cardControls.GetWidth(canRemove), + drawContextMenu: () => + { + cardMinimum = Gui.GetItemMinimum(); + headerMaximum = Gui.GetItemMaximum(); + _ = EditorUI.current.menus.ContextMenu( + $"##component_menu_{componentID}", + context.interactions.For(InspectorInteractionIDs.C_COMPONENT_AREA, editorTarget) + ); + m_cardControls.DrawComponentDragSource(component, title, dimmed); + } + ); Vector2 cardMaximum = headerMaximum; if (open) { - Ui.Unindent(); - EditorUI.current.widgets.CardBody(componentId, () => EditorUI.current.widgets.SectionLayout(() => + Gui.Unindent(); + EditorUI.current.widgets.CardBody(componentID, () => EditorUI.current.widgets.SectionLayout(() => { if (missing is not null) { - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Missing component script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns."); - Ui.PopStyleColor(); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); + EditorUI.current.widgets.WrappedText( + $"Missing component script ({missing.missingType.stableID:D}). " + "Its serialized state is preserved and will recover automatically when the type returns." + ); + Gui.PopStyleColor(); return; } if (context.TryDrawInline(component)) + { return; + } if (properties.Count == 0) { InspectorTypeOrigin.Draw(componentType); @@ -228,16 +275,21 @@ GameObject gameObject for (int propertyIndex = 0; propertyIndex < properties.Count; propertyIndex++) { - context.properties.Draw(context.editorContext, component, $"gameObject.{gameObject.identity.persistentId:N}.{componentId}", properties[propertyIndex]); + context.properties.Draw( + context.editorContext, + component, + $"gameObject.{gameObject.identity.persistentID:N}.{componentID}", + properties[propertyIndex] + ); } }), dimmed: dimmed); - cardMaximum = Ui.GetItemMaximum(); - Ui.Indent(); - Ui.TreePop(); + cardMaximum = Gui.GetItemMaximum(); + Gui.Indent(); + Gui.TreePop(); } m_cardControls.DrawComponentDropTarget(context.interactions, m_edits, component, i, cardMinimum, cardMaximum); - Ui.Dummy(new Vector2(0f, EditorUI.current.widgets.style.cardSpacing)); + Gui.Dummy(new Vector2(0f, EditorUI.current.widgets.style.cardSpacing)); } } @@ -248,19 +300,25 @@ GameObject gameObject if (EditorUI.current.widgets.CenteredButton("Add Component", EditorUI.current.widgets.style.addButtonTopPadding)) { m_componentSearch = string.Empty; - Ui.OpenPopup("##add_component_popup"); + Gui.OpenPopup("##add_component_popup"); } - if (!EditorUI.current.widgets.BeginSearchPopup("##add_component_popup", ref m_componentSearch, "Search components...", C_SEARCH_BUFFER_SIZE)) - { + if (!EditorUI.current.widgets.BeginSearchPopup( + "##add_component_popup", + ref m_componentSearch, + "Search components...", + C_SEARCH_BUFFER_SIZE + )) { return; } try { - EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, gameObject); + EditorInteraction interaction = context.interactions.For(InspectorInteractionIDs.C_COMPONENT_AREA, gameObject); if (EditorUI.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) - Ui.CloseCurrentPopup(); + { + Gui.CloseCurrentPopup(); + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs index 1478f8a5f..2b3c96456 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs @@ -1,15 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the project-defined tag picker used by GameObject target headers. /// @@ -17,6 +19,7 @@ internal sealed class GameObjectTagSelector { private readonly SceneProjectSettingsModule m_settings; private readonly SceneEdits m_edits; + /// /// Creates a tag selector backed by the effective Project Settings snapshot. /// @@ -33,8 +36,10 @@ internal GameObjectTagSelector( SceneProjectSettingsModule settings, SceneEdits edits ) { - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(edits); + m_settings = settings; + m_edits = edits; } /// @@ -56,18 +61,26 @@ float width ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return; + } GameObject target = targets[0]; bool mixed = targets.Any(value => value.tag != target.tag); IReadOnlyList tags = m_settings.tagCatalog.GetTags(); string preview = m_settings.tagCatalog.IsDefined(target.tag) ? target.tag : $"{target.tag} (Undefined)"; if (mixed) + { preview = "Mixed values"; + } EditorUI.current.widgets.LabelChip("Tag", InspectorTargetStyle.tagLabel); - Ui.SameLine(0f, 0f); + Gui.SameLine(0f, 0f); float selectorWidth = MathF.Max(1f, width); - if (!EditorUI.current.widgets.BeginMenuSelector($"game_object_tag_{target.identity.persistentId:N}", preview, selectorWidth, selectorWidth)) - { + if (!EditorUI.current.widgets.BeginMenuSelector( + $"game_object_tag_{target.identity.persistentID:N}", + preview, + selectorWidth, + selectorWidth + )) { return; } @@ -76,11 +89,13 @@ float width for (int i = 0; i < tags.Count; i++) { string tag = tags[i]; - if (Ui.Selectable(tag, string.Equals(target.tag, tag, StringComparison.Ordinal))) + if (Gui.Selectable(tag, string.Equals(target.tag, tag, StringComparison.Ordinal))) { using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Set Selection Tag"); foreach (GameObject selected in targets) + { m_edits.SetGameObjectTag(selected, tag); + } transaction.Commit(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs index 08f698ef5..12889bb6c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs @@ -1,20 +1,22 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Serialization; using Inno.Core.Logging; +using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; using Inno.Scene; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(GameScene))] internal sealed class GameSceneInspectionDrawer : InspectionDrawer { @@ -24,6 +26,7 @@ internal sealed class GameSceneInspectionDrawer : InspectionDrawer private readonly EditorSettings m_settings; private readonly SerializationRegistry m_serialization; private string m_systemSearch = string.Empty; + /// /// Creates a Scene drawer backed by the Scene editing service. /// @@ -48,16 +51,19 @@ internal GameSceneInspectionDrawer( SerializationRegistry serialization, LogRouter logs ) { - m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(serialization); + m_edits = edits; + m_settings = settings; + m_serialization = serialization; m_cardControls = new InspectorCardControls(logs); } /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => m_settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.Cubes)!; + public override string icon => m_settings.Get("Editor/Appearance/Icons/Scene").GetAsString("value", ImGuiIcon.C_CUBES)!; /// /// Binds a caller-visible label to the current inspection target. @@ -75,6 +81,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, GameScene target ) => (target.name, name => m_edits.RenameScene(target, name)); + /// /// Renders the header presentation for the current editor frame. /// @@ -87,7 +94,8 @@ GameScene target protected override void DrawHeader( InspectionDrawContext context, GameScene target - ) => Ui.Text(target.isLoaded ? "Loaded Scene" : "Scene"); + ) => Gui.Text(target.isLoaded ? "Loaded Scene" : "Scene"); + /// /// Renders the value presentation for the current editor frame. /// @@ -104,12 +112,12 @@ GameScene scene if (!scene.isLoaded || scene.isDestroyed) { _ = context.interactions.For(context.interactions.focusedArea).Select(); - Ui.Text("Selected scene is no longer loaded."); + Gui.Text("Selected scene is no longer loaded."); return; } - Ui.PushStyleVar((ImGuiStyleVar.ItemSpacing), EditorUI.current.widgets.style.compactItemSpacing); - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); + Gui.PushStyleVar((ImGuiStyleVar.ItemSpacing), EditorUI.current.widgets.style.compactItemSpacing); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.compactFramePadding); try { DrawSystems(context, scene); @@ -117,7 +125,7 @@ GameScene scene } finally { - Ui.PopStyleVar(2); + Gui.PopStyleVar(2); } } @@ -130,43 +138,71 @@ GameScene scene { GameSystem system = systems[i]; MissingGameSystem? missing = system as MissingGameSystem; - IReadOnlyList properties = missing is null ? m_serialization.GetProperties(system) : Array.Empty(); - string systemId = system.identity.persistentId.ToString("N"); - var editorTarget = system; + IReadOnlyList properties = missing is null + ? m_serialization.GetProperties(system) + : []; + string systemID = system.identity.persistentID.ToString("N"); + GameSystem editorTarget = system; string title = missing?.missingTypeName ?? system.GetType().Name; bool dimmed = !system.enabled; Vector2 cardMinimum = default; Vector2 headerMaximum = default; - bool open = EditorUI.current.widgets.CollapsingCard(systemId, title, missing is null ? () => - { - bool enabled = system.enabled; - if (EditorUI.current.widgets.CompactCheckbox($"enabled_{systemId}", ref enabled, tooltip: "Enable or disable this system.")) + bool open = EditorUI.current.widgets.CollapsingCard( + systemID, + title, + missing is null + ? () => { - _ = m_edits.ChangeProperty(system, "enabled", () => system.enabled = enabled, enabled ? "Enable System" : "Disable System", mergeKey: null); + bool enabled = system.enabled; + if (EditorUI.current.widgets.CompactCheckbox( + $"enabled_{systemID}", + ref enabled, + tooltip: "Enable or disable this system." + )) { + _ = m_edits.ChangeProperty( + system, + "enabled", + () => system.enabled = enabled, + enabled ? "Enable System" : "Disable System", + mergeKey: null + ); + } } - } : null, () => m_cardControls.DrawSystem( - m_edits, - scene, - system, - () => context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget).Enqueue(InspectorInteractionIds.C_REMOVE_SYSTEM) - ), dimmed: dimmed, trailingControlWidth: m_cardControls.GetWidth(canRemove: true), drawContextMenu: () => - { - cardMinimum = Ui.GetItemMinimum(); - headerMaximum = Ui.GetItemMaximum(); - _ = EditorUI.current.menus.ContextMenu($"##system_menu_{systemId}", context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget)); - m_cardControls.DrawSystemDragSource(system, title, dimmed); - }); + : null, + () => m_cardControls.DrawSystem( + m_edits, + scene, + system, + () => context.interactions + .For(InspectorInteractionIDs.C_SYSTEM_AREA, editorTarget) + .Enqueue(InspectorInteractionIDs.C_REMOVE_SYSTEM) + ), + dimmed: dimmed, + trailingControlWidth: m_cardControls.GetWidth(canRemove: true), + drawContextMenu: () => + { + cardMinimum = Gui.GetItemMinimum(); + headerMaximum = Gui.GetItemMaximum(); + _ = EditorUI.current.menus.ContextMenu( + $"##system_menu_{systemID}", + context.interactions.For(InspectorInteractionIDs.C_SYSTEM_AREA, editorTarget) + ); + m_cardControls.DrawSystemDragSource(system, title, dimmed); + } + ); Vector2 cardMaximum = headerMaximum; if (open) { - Ui.Unindent(); - EditorUI.current.widgets.CardBody(systemId, () => EditorUI.current.widgets.SectionLayout(() => + Gui.Unindent(); + EditorUI.current.widgets.CardBody(systemID, () => EditorUI.current.widgets.SectionLayout(() => { if (missing is not null) { - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Missing system script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns."); - Ui.PopStyleColor(); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); + EditorUI.current.widgets.WrappedText( + $"Missing system script ({missing.missingType.stableID:D}). " + "Its serialized state is preserved and will recover automatically when the type returns." + ); + Gui.PopStyleColor(); return; } @@ -178,16 +214,21 @@ GameScene scene for (int propertyIndex = 0; propertyIndex < properties.Count; propertyIndex++) { - context.properties.Draw(context.editorContext, system, $"scene.{scene.identity.persistentId:N}.{systemId}", properties[propertyIndex]); + context.properties.Draw( + context.editorContext, + system, + $"scene.{scene.identity.persistentID:N}.{systemID}", + properties[propertyIndex] + ); } }), dimmed: dimmed); - cardMaximum = Ui.GetItemMaximum(); - Ui.Indent(); - Ui.TreePop(); + cardMaximum = Gui.GetItemMaximum(); + Gui.Indent(); + Gui.TreePop(); } m_cardControls.DrawSystemDropTarget(context.interactions, m_edits, scene, system, i, cardMinimum, cardMaximum); - Ui.Dummy(new Vector2(0f, EditorUI.current.widgets.style.cardSpacing)); + Gui.Dummy(new Vector2(0f, EditorUI.current.widgets.style.cardSpacing)); } } @@ -198,16 +239,20 @@ GameScene scene if (EditorUI.current.widgets.CenteredButton("Add System", EditorUI.current.widgets.style.addButtonTopPadding)) { m_systemSearch = string.Empty; - Ui.OpenPopup("##add_system_popup"); + Gui.OpenPopup("##add_system_popup"); } if (!EditorUI.current.widgets.BeginSearchPopup("##add_system_popup", ref m_systemSearch, "Search systems...", C_SEARCH_BUFFER_SIZE)) + { return; + } try { - EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, scene); + EditorInteraction interaction = context.interactions.For(InspectorInteractionIDs.C_SYSTEM_AREA, scene); if (EditorUI.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_systemSearch)) - Ui.CloseCurrentPopup(); + { + Gui.CloseCurrentPopup(); + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs index b4a25678f..c9ea14136 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -22,8 +21,10 @@ internal GameTagDiagnosticPublisher( SceneWorld world, DiagnosticHub diagnostics ) { - m_world = world ?? throw new ArgumentNullException(nameof(world)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(diagnostics); + m_world = world; + m_diagnostics = diagnostics; } /// @@ -44,21 +45,29 @@ internal void Refresh(GameTagCatalog catalog) { GameObject gameObject = objects[objectIndex]; if (catalog.IsDefined(gameObject.tag)) + { continue; - Guid targetId = gameObject.identity.persistentId; - currentTargets.Add(targetId); - if (m_activeTargets.Contains(targetId)) + } + Guid targetID = gameObject.identity.persistentID; + currentTargets.Add(targetID); + if (m_activeTargets.Contains(targetID)) + { continue; + } m_diagnostics.Set( - CreateSource(targetId, gameObject.name), + CreateSource(targetID, gameObject.name), [Diagnostic.Error( "GAMEOBJECT-TAG-UNDEFINED", - $"GameObject '{gameObject.name}' uses undefined tag '{gameObject.tag}'.")]); + $"GameObject '{gameObject.name}' uses undefined tag '{gameObject.tag}'." + )] + ); } } - foreach (Guid targetId in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) - m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + foreach (Guid targetID in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) + { + m_diagnostics.Clear(CreateSource(targetID, targetID.ToString("D"))); + } m_activeTargets.Clear(); m_activeTargets.UnionWith(currentTargets); } @@ -68,14 +77,15 @@ internal void Refresh(GameTagCatalog catalog) /// internal void Clear() { - foreach (Guid targetId in m_activeTargets) - m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + foreach (Guid targetID in m_activeTargets) + { + m_diagnostics.Clear(CreateSource(targetID, targetID.ToString("D"))); + } m_activeTargets.Clear(); } private static DiagnosticSource CreateSource( - Guid targetId, + Guid targetID, string displayName - ) - => new($"editor.scene.tag:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); + ) => new($"editor.scene.tag:{targetID:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs index 79ed086e7..c8f46bdc0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; @@ -7,19 +6,24 @@ using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; using Inno.Scene; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [ProjectSettingPath("Project/Scene/Tags")] internal sealed class GameTagsSetting : ProjectSettingEditor { private const int C_TAG_BUFFER_SIZE = 128; private string m_error = string.Empty; private string m_newTag = string.Empty; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Definitions"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -34,28 +38,42 @@ internal sealed class GameTagsSetting : ProjectSettingEditor protected override void OnDraw(GameTagCatalog setting) { DrawAddRow(setting); - Ui.Spacing(); + Gui.Spacing(); DrawTags(setting); if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } private void DrawAddRow(GameTagCatalog setting) { - float spacing = Ui.GetLayout().itemSpacing.X; + float spacing = Gui.GetLayout().itemSpacing.X; float actionWidth = EditorUI.current.widgets.GetCompactIconSize().X; - Ui.SetNextItemWidth(MathF.Max(1f, Ui.GetContentRegionAvailable().X - actionWidth - spacing)); - bool submit = Ui.InputTextWithHint("##new_project_tag", "New tag", ref m_newTag, C_TAG_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue); - Ui.SameLine(0f, spacing); - submit |= EditorUI.current.widgets.ClickableIcon("add_project_tag", ImGuiIcon.Plus, "Add project tag"); + Gui.SetNextItemWidth(MathF.Max(1f, Gui.GetContentRegionAvailable().X - actionWidth - spacing)); + bool submit = Gui.InputTextWithHint( + "##new_project_tag", + "New tag", + ref m_newTag, + C_TAG_BUFFER_SIZE, + ImGuiInputTextFlags.EnterReturnsTrue + ); + Gui.SameLine(0f, spacing); + submit |= EditorUI.current.widgets.ClickableIcon("add_project_tag", ImGuiIcon.C_PLUS, "Add project tag"); if (!submit || string.IsNullOrWhiteSpace(m_newTag)) + { return; + } try { if (!setting.Add(m_newTag)) + { m_error = $"Tag '{m_newTag.Trim()}' is already defined."; + } else + { m_error = string.Empty; + } m_newTag = string.Empty; } catch (ArgumentException exception) @@ -67,29 +85,38 @@ private void DrawAddRow(GameTagCatalog setting) private static void DrawTags(GameTagCatalog setting) { IReadOnlyList tags = setting.GetTags(); - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings; - Ui.PushStyleVar((ImGuiStyleVar.CellPadding), EditorUI.current.widgets.style.cellPadding); - if (!Ui.BeginTable("##project_tag_definitions", 2, flags, default(System.Numerics.Vector2), 0f)) + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.BordersInnerH + | ImGuiTableFlags.BordersInnerV + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoSavedSettings; + Gui.PushStyleVar((ImGuiStyleVar.CellPadding), EditorUI.current.widgets.style.cellPadding); + if (!Gui.BeginTable("##project_tag_definitions", 2, flags, default, 0f)) { - Ui.PopStyleVar(); + Gui.PopStyleVar(); return; } try { - Ui.TableSetupColumn("Tag", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); - Ui.TableSetupColumn("Action", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 72f * EditorUI.current.widgets.style.zoom); + Gui.TableSetupColumn("Tag", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); + Gui.TableSetupColumn( + "Action", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 72f * EditorUI.current.widgets.style.zoom + ); DrawTagTableHeader(); for (int i = 0; i < tags.Count; i++) { string tag = tags[i]; - bool isDefault = string.Equals(tag, GameObject.defaultTag, StringComparison.Ordinal); - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); - Ui.AlignTextToFramePadding(); + bool isDefault = string.Equals(tag, GameObject.C_DEFAULT_TAG, StringComparison.Ordinal); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); + Gui.AlignTextToFramePadding(); InsetPlainCell(); - Ui.Text(tag); - _ = Ui.TableSetColumnIndex(1); + Gui.Text(tag); + _ = Gui.TableSetColumnIndex(1); InsetPlainCell(); if (isDefault) { @@ -100,27 +127,26 @@ private static void DrawTags(GameTagCatalog setting) if (EditorUI.current.widgets.ClickableText( $"remove_project_tag_{tag}", "Remove", - new Vector2(Ui.MeasureText("Remove").X, Ui.GetFrameHeight()), + new Vector2(Gui.MeasureText("Remove").X, Gui.GetFrameHeight()), "Remove this definition. Existing scene assignments are preserved and become undefined." - )) - { + )) { _ = setting.Remove(tag); } } } finally { - Ui.EndTable(); - Ui.PopStyleVar(); + Gui.EndTable(); + Gui.PopStyleVar(); } } private static void DrawTagTableHeader() { - uint background = Ui.ToPackedColor(EditorPalette.collectionHeader); - Ui.TableNextRow(); - Ui.TableSetBgColor((ImGuiTableBgTarget.RowBg0), background); - Ui.TableSetBgColor((ImGuiTableBgTarget.RowBg1), background); + uint background = Gui.ToPackedColor(EditorPalette.collectionHeader); + Gui.TableNextRow(); + Gui.TableSetBgColor((ImGuiTableBgTarget.RowBg0), background); + Gui.TableSetBgColor((ImGuiTableBgTarget.RowBg1), background); DrawHeaderCell(0, "Tag"); DrawHeaderCell(1, "Action"); } @@ -129,10 +155,10 @@ private static void DrawHeaderCell( int column, string label ) { - _ = Ui.TableSetColumnIndex(column); + _ = Gui.TableSetColumnIndex(column); InsetPlainCell(); - Ui.Text(label); + Gui.Text(label); } - private static void InsetPlainCell() => Ui.SetCursorPosX(Ui.GetCursorPosX() + Ui.GetLayout().framePadding.X); + private static void InsetPlainCell() => Gui.SetCursorPosX(Gui.GetCursorPosX() + Gui.GetLayout().framePadding.X); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs index 0ef4ddaa8..7a9c8f001 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs @@ -1,25 +1,20 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Rendering; using System; -using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Serialization; -using Inno.Editor.Assets; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; -using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Rendering; using Inno.Rendering.Assets; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(RenderPipelineAsset))] internal sealed class PipelineInspectionDrawer(IInspectionIconProvider icons) : InspectionDrawer { /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.C_FILE; /// /// Retrieves the current icon from authoritative state. @@ -36,17 +31,15 @@ internal sealed class PipelineInspectionDrawer(IInspectionIconProvider context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + ) => context.interactions.TryGetModule(out PipelineDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(target.identity.persistentID, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -63,6 +56,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, RenderPipelineAsset target ) => (target.name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -76,14 +70,13 @@ protected override void DrawHeader( InspectionDrawContext context, RenderPipelineAsset target ) { - if (context.interactions.TryGetModule(out var documents) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(target.identity.persistentID, out AssetInfo? info) + && info is not null + ) { PipelineInspector.DrawHeader(context, documents, documents.Open(info.assetPath)); + } } /// @@ -99,279 +92,12 @@ protected override void Draw( InspectionDrawContext context, RenderPipelineAsset target ) { - if (context.interactions.TryGetModule(out var documents) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null) - PipelineInspector.Draw(context, documents, documents.Open(info.assetPath)); - } -} - -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class PipelineSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) - PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) - PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); - } -} - -internal static class PipelineInspector -{ - internal static void DrawHeader( - InspectionDrawContext context, - PipelineDocuments documents, - Guid id - ) { - AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); - ImGuiApi.BeginDisabled(draft.readOnly); - try - { - if (ImGuiApi.Button("Save")) - _ = context.interactions.documents.Save(draft.documentId); - ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.Button("Revert")) - _ = context.interactions.documents.Revert(draft.documentId); - } - finally - { - ImGuiApi.EndDisabled(); - } - } - - internal static void Draw( - InspectionDrawContext context, - PipelineDocuments documents, - Guid id - ) { - AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); - RenderPipelineAsset pipeline = documents.Read(id); - var edits = new DraftEdits(documents, id, pipeline); - ImGuiApi.PushId(id.ToString("N")); - try - { - if (EditorUI.current.widgets.SectionHeader( - "Render Pipeline", - "This source is the configuration authority. Unsaved settings do not change Scene, Game or Player content." - )) - { - EditorUI.current.widgets.Hint(draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate"); - if (draft.error.Length != 0) - EditorUI.current.widgets.Hint(draft.error); - if (draft.readOnly) - EditorUI.current.widgets.Hint("Installed Pipeline · copy into the project to edit"); - EditorUI.current.widgets.Hint("Pipeline: " + pipeline.pipelineTypeId); - DrawSettings("pipeline.settings", pipeline.pipelineState, value => pipeline.pipelineState = value); - } - - bool featuresOpen = EditorUI.current.widgets.SectionHeader( - "Features", - "Ordered extension settings belong to this Pipeline. Each enabled feature participates in its render graph." - ); - RenderFeatureConfiguration[] features = pipeline.features; - for (int index = 0; featuresOpen && index < features.Length; index++) - { - int slot = index; - ImGuiApi.PushId(slot); - try - { - RenderFeatureConfiguration feature = features[slot]; - context.properties.DrawValue(context.editorContext, draft, "pipeline.features." + slot + ".enabled", feature.featureTypeId, typeof(bool), () => features[slot].enabled, value => - { - features[slot].enabled = (bool)value!; - pipeline.features = features; - }, edits, draft.readOnly); - DrawSettings("pipeline.features." + slot, feature.state, value => - { - features[slot].state = value; - pipeline.features = features; - }); - ImGuiApi.BeginDisabled(draft.readOnly); - try - { - if (slot > 0 && ImGuiApi.SmallButton("Move Up")) - { - (features[slot - 1], features[slot]) = (features[slot], features[slot - 1]); - pipeline.features = features; - documents.Replace(id, pipeline); - break; - } - - if (slot + 1 < features.Length) - { - if (slot > 0) - ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.SmallButton("Move Down")) - { - (features[slot + 1], features[slot]) = (features[slot], features[slot + 1]); - pipeline.features = features; - documents.Replace(id, pipeline); - break; - } - } - } - finally - { - ImGuiApi.EndDisabled(); - } - } - finally - { - ImGuiApi.PopId(); - } - } - - if (featuresOpen && features.Length == 0) - EditorUI.current.widgets.Hint("No additional features"); - } - finally - { - ImGuiApi.PopId(); - } - - void DrawSettings( - string path, - SerializedRenderExtensionState state, - Action assign + && documents.assets.TryGetInfo(target.identity.persistentID, out AssetInfo? info) + && info is not null ) { - try - { - ISerializable? settings = documents.RestoreSettings(state); - if (settings is null) - { - EditorUI.current.widgets.Hint("No typed settings"); - return; - } - - var settingsEdits = new SettingsEdits(edits, () => assign(new(documents.assets.CaptureProperties(settings)))); - foreach (SerializedProperty property in documents.serialization.GetProperties(settings)) - context.properties.DrawDraftProperty(context.editorContext, draft, settings, path, property, settingsEdits, draft.readOnly); - } - catch (Exception error) when ((error is System.IO.IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(error) is null) - { - EditorUI.current.widgets.Hint("Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained."); - } - } - } - - private sealed class DraftEdits( - PipelineDocuments documents, - Guid id, - RenderPipelineAsset pipeline - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - mutation(); - documents.Replace(id, pipeline, mergeKey); - return true; + PipelineInspector.Draw(context, documents, documents.Open(info.assetPath)); } } - - private sealed class SettingsEdits( - DraftEdits edits, - Action capture - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) => edits.ChangeProperty(owner, propertyName, () => - { - mutation(); - capture(); - }, historyName, mergeKey, componentName); - } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs new file mode 100644 index 000000000..dd3f70add --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs @@ -0,0 +1,238 @@ +using System; +using System.IO; +using Inno.Core.Execution; +using Inno.Core.Serialization; +using Inno.Editor.Assets; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Panel.Inspector; + +internal static class PipelineInspector +{ + internal static void DrawHeader( + InspectionDrawContext context, + PipelineDocuments documents, + Guid id + ) { + AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); + ImGuiApi.BeginDisabled(draft.readOnly); + try + { + if (ImGuiApi.Button("Save")) + { + _ = context.interactions.documents.Save(draft.documentID); + } + ImGuiApi.SameLine(0f, -1f); + if (ImGuiApi.Button("Revert")) + { + _ = context.interactions.documents.Revert(draft.documentID); + } + } + finally + { + ImGuiApi.EndDisabled(); + } + } + + internal static void Draw( + InspectionDrawContext context, + PipelineDocuments documents, + Guid id + ) { + AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); + RenderPipelineAsset pipeline = documents.Read(id); + var edits = new DraftEdits(documents, id, pipeline); + ImGuiApi.PushID(id.ToString("N")); + try + { + if (EditorUI.current.widgets.SectionHeader( + "Render Pipeline", + "This source is the configuration authority. Unsaved settings do not change Scene, Game or Player content." + )) { + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate" + ); + if (draft.error.Length != 0) + { + EditorUI.current.widgets.Hint(draft.error); + } + if (draft.readOnly) + { + EditorUI.current.widgets.Hint("Installed Pipeline · copy into the project to edit"); + } + EditorUI.current.widgets.Hint("Pipeline: " + pipeline.pipelineTypeId); + DrawSettings("pipeline.settings", pipeline.pipelineState, value => pipeline.pipelineState = value); + } + + bool featuresOpen = EditorUI.current.widgets.SectionHeader( + "Features", + "Ordered extension settings belong to this Pipeline. Each enabled feature participates in its render graph." + ); + RenderFeatureConfiguration[] features = pipeline.features; + for (int index = 0; featuresOpen && index < features.Length; index++) + { + int slot = index; + ImGuiApi.PushID(slot); + try + { + RenderFeatureConfiguration feature = features[slot]; + context.properties.DrawValue( + context.editorContext, + draft, + "pipeline.features." + + slot + + ".enabled", + feature.featureTypeId, + typeof(bool), + () => features[slot].enabled, + value => + { + features[slot].enabled = (bool)value!; + pipeline.features = features; + }, + edits, + draft.readOnly + ); + DrawSettings("pipeline.features." + slot, feature.state, value => + { + features[slot].state = value; + pipeline.features = features; + }); + ImGuiApi.BeginDisabled(draft.readOnly); + try + { + if (slot > 0 && ImGuiApi.SmallButton("Move Up")) + { + (features[slot - 1], features[slot]) = (features[slot], features[slot - 1]); + pipeline.features = features; + documents.Replace(id, pipeline); + break; + } + + if (slot + 1 < features.Length) + { + if (slot > 0) + { + ImGuiApi.SameLine(0f, -1f); + } + if (ImGuiApi.SmallButton("Move Down")) + { + (features[slot + 1], features[slot]) = (features[slot], features[slot + 1]); + pipeline.features = features; + documents.Replace(id, pipeline); + break; + } + } + } + finally + { + ImGuiApi.EndDisabled(); + } + } + finally + { + ImGuiApi.PopID(); + } + } + + if (featuresOpen && features.Length == 0) + { + EditorUI.current.widgets.Hint("No additional features"); + } + } + finally + { + ImGuiApi.PopID(); + } + + void DrawSettings( + string path, + SerializedRenderExtensionState state, + Action assign + ) { + try + { + ISerializable? settings = documents.RestoreSettings(state); + if (settings is null) + { + EditorUI.current.widgets.Hint("No typed settings"); + return; + } + + var settingsEdits = new SettingsEdits( + edits, + () => assign(new SerializedRenderExtensionState(documents.assets.CaptureProperties(settings))) + ); + foreach (SerializedProperty property in documents.serialization.GetProperties(settings)) + { + context.properties.DrawDraftProperty( + context.editorContext, + draft, + settings, + path, + property, + settingsEdits, + draft.readOnly + ); + } + } + catch (Exception error) when ((error is IOException + or UnauthorizedAccessException + or InvalidOperationException + or ArgumentException + or FormatException) + && RetirementPendingException.Find(error) is null) + { + EditorUI.current.widgets.Hint( + "Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained." + ); + } + } + } + + private sealed class DraftEdits( + PipelineDocuments documents, + Guid id, + RenderPipelineAsset pipeline + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + mutation(); + documents.Replace(id, pipeline, mergeKey); + return true; + } + } + + private sealed class SettingsEdits( + DraftEdits edits, + Action capture + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) => edits.ChangeProperty(owner, propertyName, () => + { + mutation(); + capture(); + }, historyName, mergeKey, componentName); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs new file mode 100644 index 000000000..fd8db373f --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs @@ -0,0 +1,100 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; + +namespace Inno.Editor.Panel.Inspector; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class PipelineSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => ImGuiIcon.C_FILE; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) + { + PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) + { + PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs index 5d926093a..c66d16c00 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs @@ -4,12 +4,17 @@ using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; +using Inno.Scene.Components; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(EditorSelectionSnapshot))] internal sealed class SelectionInspectionDrawer( SceneEdits edits, @@ -19,15 +24,17 @@ SceneProjectSettingsModule settings { private readonly GameObjectTagSelector m_tags = new(settings, edits); private readonly GameObjectLayerSelector m_layers = new(settings, edits); - private string m_componentSearch = ""; + private string m_componentSearch = string.Empty; + /// - public override string icon => ImGuiIcon.LayerGroup; + public override string icon => ImGuiIcon.C_LAYER_GROUP; /// protected override (string name, Action? setter) BindName( InspectionDrawContext context, EditorSelectionSnapshot target ) => ($"{target.identities.Count} Selected", null); + /// protected override void Draw( InspectionDrawContext context, @@ -37,12 +44,16 @@ EditorSelectionSnapshot target target.CopyTargets(context.interactions, values); if (values.Count != target.identities.Count) { - EditorUiSession.current.widgets.Hint("The selection includes unavailable or different content. Select compatible scene objects or assets to edit common values."); + EditorUISession.current.widgets.Hint( + "The selection includes unavailable or different content. Select compatible scene objects or assets to edit common values." + ); return; } if (values.Count == 0) + { return; + } int primaryIndex = values.FindIndex(value => value.identity.runtimeIdentity == target.primary); if (primaryIndex > 0) { @@ -52,13 +63,23 @@ EditorSelectionSnapshot target } bool readOnly = values.Any(value => !edits.CanEdit(value)); if (readOnly) - EditorUiSession.current.widgets.HelpBox("The selection includes a read-only owner. No batch changes will be applied.", ImGuiIcon.Lock, EditorPalette.warning); - EditorUiSession.current.widgets.Disabled(readOnly, () => + { + EditorUISession.current.widgets.HelpBox( + "The selection includes a read-only owner. No batch changes will be applied.", + ImGuiIcon.C_LOCK, + EditorPalette.warning + ); + } + EditorUISession.current.widgets.Disabled(readOnly, () => { if (values.All(value => value is GameObject)) + { DrawGameObjects(context, target, values.Cast().ToArray()); + } else + { DrawCommon(context, target, values, "selection"); + } }); } @@ -69,17 +90,24 @@ IReadOnlyList targets ) { bool active = targets[0].activeSelf; bool mixed = targets.Any(value => value.activeSelf != active); - EditorUiSession.current.widgets.MixedValue(mixed, () => + EditorUISession.current.widgets.MixedValue(mixed, () => { - if (!EditorUiSession.current.widgets.CompactCheckbox("selection.active", ref active, tooltip: "Set the active state of every selected object.")) + if (!EditorUISession.current.widgets.CompactCheckbox( + "selection.active", + ref active, + tooltip: "Set the active state of every selected object." + )) { return; + } using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Set Selected Active"); foreach (GameObject target in targets) + { edits.SetGameObjectActive(target, active); + } transaction.Commit(); }); - EditorUiSession.current.widgets.Hint(mixed ? "Active \u00b7 Mixed values" : "Active"); - float width = MathF.Max(1, Inno.Editor.ImGui.ImGui.GetContentRegionAvailable().X); + EditorUISession.current.widgets.Hint(mixed ? "Active \u00b7 Mixed values" : "Active"); + float width = MathF.Max(1, Gui.GetContentRegionAvailable().X); m_tags.Draw(targets, context.interactions, width); m_layers.Draw(targets, context.interactions, width); IReadOnlyList primary = targets[0].GetComponents(); @@ -89,29 +117,39 @@ IReadOnlyList targets Type type = component.GetType(); int occurrence = occurrences.GetValueOrDefault(type); occurrences[type] = occurrence + 1; - GameComponent? [] matches = targets.Select(value => value.GetComponents().Where(candidate => candidate.GetType() == type).Skip(occurrence).FirstOrDefault()).ToArray(); + GameComponent? [] matches = targets + .Select(value => value.GetComponents().Where(candidate => candidate.GetType() == type).Skip(occurrence).FirstOrDefault()) + .ToArray(); if (matches.Any(value => value is null)) - continue; - if (EditorUiSession.current.widgets.SectionHeader($"{type.Name} ({occurrence + 1})", "Common component values. Changes apply atomically to the entire selection.")) { + continue; + } + if (EditorUISession.current.widgets.SectionHeader( + $"{type.Name} ({occurrence + 1})", + "Common component values. Changes apply atomically to the entire selection." + )) { string id = $"selection.{type.FullName}.{occurrence}"; DrawCommon(context, state, matches.Cast().ToArray(), id); - if (Inno.Editor.ImGui.ImGui.Button("Reset Selected##" + id)) + if (Gui.Button("Reset Selected##" + id)) { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Reset Components"); foreach (GameComponent match in matches.Cast()) + { edits.ResetComponent(match); + } transaction.Commit(); } - if (matches.All(value => value is not Inno.Scene.Components.Transform)) + if (matches.All(value => value is not Transform)) { - Inno.Editor.ImGui.ImGui.SameLine(0, -1); - if (Inno.Editor.ImGui.ImGui.Button("Remove Selected##" + id)) + Gui.SameLine(0, -1); + if (Gui.Button("Remove Selected##" + id)) { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Remove Components"); foreach (GameComponent match in matches.Cast()) + { edits.RemoveComponent(match); + } transaction.Commit(); return; } @@ -126,20 +164,24 @@ private void DrawAddComponents( InspectionDrawContext context, GameObject primary ) { - var widgets = EditorUiSession.current.widgets; + ImGuiWidget widgets = EditorUISession.current.widgets; if (widgets.CenteredButton("Add Component to Selection", widgets.style.addButtonTopPadding)) { - m_componentSearch = ""; - Inno.Editor.ImGui.ImGui.OpenPopup("selection.add-component"); + m_componentSearch = string.Empty; + Gui.OpenPopup("selection.add-component"); } if (!widgets.BeginSearchPopup("selection.add-component", ref m_componentSearch, "Search components...", 256)) + { return; + } try { - EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, primary); - if (EditorUiSession.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) - Inno.Editor.ImGui.ImGui.CloseCurrentPopup(); + EditorInteraction interaction = context.interactions.For(InspectorInteractionIDs.C_COMPONENT_AREA, primary); + if (EditorUISession.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) + { + Gui.CloseCurrentPopup(); + } } finally { @@ -155,36 +197,56 @@ string path ) { if (targets.Any(value => value is not ISerializable)) { - EditorUiSession.current.widgets.Hint("These objects expose no common serialized properties."); + EditorUISession.current.widgets.Hint("These objects expose no common serialized properties."); return; } - IReadOnlyList[] properties = targets.Select(value => serialization.GetProperties((ISerializable)value)).ToArray(); + IReadOnlyList[] properties = targets + .Select(value => serialization.GetProperties((ISerializable)value)) + .ToArray(); int common = 0; foreach (SerializedProperty property in properties[0]) { if (properties.Any(values => !values.Any(value => value.name == property.name && value.propertyType == property.propertyType))) + { continue; - var availability = properties.Select(( + } + (bool isVisible, bool isReadOnly)[] availability = properties.Select(( values, index ) => context.properties.GetPropertyAvailability( - targets[index], values.Single(value => value.name == property.name && value.propertyType == property.propertyType))).ToArray(); + targets[index], + values.Single(value => value.name == property.name && value.propertyType == property.propertyType) + )).ToArray(); if (availability.Any(value => !value.isVisible)) + { continue; + } bool readOnly = availability.Any(value => value.isReadOnly); common++; bool mixed = !edits.HaveSamePropertyValues(targets, property.name); - EditorUiSession.current.widgets.MixedValue( + EditorUISession.current.widgets.MixedValue( mixed, - () => context.properties.DrawDraftProperty(context.editorContext, state, targets[0], path, property, new SelectionEdits(edits, targets), readOnly) + () => context.properties.DrawDraftProperty( + context.editorContext, + state, + targets[0], + path, + property, + new SelectionEdits(edits, targets), + readOnly + ) ); if (mixed) - EditorUiSession.current.widgets.Hint("Mixed values"); + { + EditorUISession.current.widgets.Hint("Mixed values"); + } } if (common == 0) - EditorUiSession.current.widgets.Hint("No common editable properties."); + { + EditorUISession.current.widgets.Hint("No common editable properties."); + } } private sealed class SelectionEdits( @@ -192,7 +254,7 @@ private sealed class SelectionEdits( IReadOnlyList targets ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs index 919a295e9..5c678ed14 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Mathematics; using Inno.Editor.ImGui; @@ -6,9 +5,12 @@ using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene.Components; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(Transform))] internal sealed class TransformInspectionDrawer( SceneEdits edits, @@ -16,10 +18,11 @@ EditorInteractions interactions ) : InspectionDrawer { private bool m_world; + /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => ImGuiIcon.ArrowsUpDownLeftRight; + public override string icon => ImGuiIcon.C_ARROWS_UP_DOWN_LEFT_RIGHT; /// /// Binds a caller-visible label to the current inspection target. @@ -37,6 +40,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, Transform target ) => ("Transform", null); + /// /// Renders the value presentation for the current editor frame. /// @@ -53,9 +57,12 @@ Transform target if (!EditorUI.current.widgets.SectionHeader( m_world ? "World Space" : "Local Space", m_world ? "Position, rotation, and scale include the parent hierarchy. Edits are stored as local values and support Undo/Redo." : "Position, rotation, and scale are relative to the parent. Rotation is expressed in degrees.", - () => _ = EditorUI.current.widgets.CompactCheckbox("##transform_space", ref m_world, tooltip: m_world ? "Switch to Local Space." : "Switch to World Space.") - )) - { + () => _ = EditorUI.current.widgets.CompactCheckbox( + "##transform_space", + ref m_world, + tooltip: m_world ? "Switch to Local Space." : "Switch to World Space." + ) + )) { return; } @@ -73,44 +80,76 @@ Transform target } if (!invertible) + { EditorUI.current.widgets.HelpBox( "World editing requires an invertible parent transform. Edit in Local Space or restore the parent's zero scale.", - ImGuiIcon.TriangleExclamation, + ImGuiIcon.C_TRIANGLE_EXCLAMATION, EditorPalette.warning ); - Ui.BeginDisabled(!invertible); + } + Gui.BeginDisabled(!invertible); try { Vector3 position = m_world ? target.worldPosition : target.localPosition; Quaternion rotation = m_world ? target.worldRotation : target.localRotation; Vector3 euler = rotation.ToEulerAnglesZYXDegrees(); Vector3 scale = m_world ? target.worldScale : target.localScale; - DrawVector(EditPath(target, "localPosition"), "Position", "Translation in world units.", position, value => Change(target, "localPosition", () => - { - if (m_world) - target.worldPosition = value; - else - target.localPosition = value; - })); - DrawVector(EditPath(target, "localRotation"), "Rotation", "Euler rotation in degrees.", euler, value => Change(target, "localRotation", () => - { - Quaternion next = Quaternion.FromEulerAnglesZYXDegrees(value); - if (m_world) - target.worldRotation = next; - else - target.localRotation = next; - })); - DrawVector(EditPath(target, "localScale"), "Scale", "Scale along each axis. One preserves the original size.", scale, value => Change(target, "localScale", () => - { - if (m_world) - target.worldScale = value; - else - target.localScale = value; - })); + DrawVector( + EditPath(target, "localPosition"), + "Position", + "Translation in world units.", + position, + value => Change(target, "localPosition", () => + { + if (m_world) + { + target.worldPosition = value; + } + else + { + target.localPosition = value; + } + }) + ); + DrawVector( + EditPath(target, "localRotation"), + "Rotation", + "Euler rotation in degrees.", + euler, + value => Change(target, "localRotation", () => + { + Quaternion next = Quaternion.FromEulerAnglesZYXDegrees(value); + if (m_world) + { + target.worldRotation = next; + } + else + { + target.localRotation = next; + } + }) + ); + DrawVector( + EditPath(target, "localScale"), + "Scale", + "Scale along each axis. One preserves the original size.", + scale, + value => Change(target, "localScale", () => + { + if (m_world) + { + target.worldScale = value; + } + else + { + target.localScale = value; + } + }) + ); } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } @@ -135,7 +174,8 @@ Action mutation private string EditPath( Transform target, string property - ) => $"transform:{target.identity.persistentId:N}:{property}:{m_world}"; + ) => $"transform:{target.identity.persistentID:N}:{property}:{m_world}"; + private static void DrawVector( string path, string label, @@ -145,14 +185,16 @@ Action apply ) { EditorUI.current.widgets.PropertyRow("transform." + label, label, () => { - float width = MathF.Max(1f, (Ui.GetContentRegionAvailable().X - Ui.GetLayout().itemSpacing.X * 2f) / 3f); + float width = MathF.Max(1f, (Gui.GetContentRegionAvailable().X - Gui.GetLayout().itemSpacing.X * 2f) / 3f); bool changed = EditorUI.current.widgets.AxisDragFloat(label, "X", ref value.x, width); - Ui.SameLine(0f, -1f); + Gui.SameLine(0f, -1f); changed |= EditorUI.current.widgets.AxisDragFloat(label, "Y", ref value.y, width); - Ui.SameLine(0f, -1f); + Gui.SameLine(0f, -1f); changed |= EditorUI.current.widgets.AxisDragFloat(label, "Z", ref value.z, width); if (changed) + { apply(value); + } }, tooltip: tooltip); EditorUI.current.widgets.CompletePropertyEdit(path); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs index 684f70cdf..f87f831eb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs @@ -3,10 +3,12 @@ using Inno.Editor.Diagnostics; namespace Inno.Editor.Panel.Logging; + internal readonly struct ConsoleEntryCopyTarget { private readonly EditorConsoleOccurrence m_entry; private readonly int m_repeatCount; + internal ConsoleEntryCopyTarget( EditorConsoleOccurrence entry, int repeatCount @@ -23,10 +25,21 @@ private static string FormatFullText( int repeatCount ) { var builder = new StringBuilder(); - builder.Append('[').Append(entry.time.ToString("yyyy-MM-dd HH:mm:ss.fff")).Append("] [").Append(entry.kind).Append("] [").Append(entry.level).Append("] [").Append(entry.category).Append(']'); + builder + .Append('[') + .Append(entry.time.ToString("yyyy-MM-dd HH:mm:ss.fff")) + .Append("] [") + .Append(entry.kind) + .Append("] [") + .Append(entry.level) + .Append("] [") + .Append(entry.category) + .Append(']'); builder.Append(' ').Append(entry.displayMessage); if (repeatCount > 1) + { builder.Append(" (x").Append(repeatCount).Append(')'); + } if (!string.IsNullOrWhiteSpace(entry.file)) { builder.AppendLine(); @@ -35,7 +48,9 @@ int repeatCount { builder.Append('(').Append(entry.line); if (entry.column > 0) + { builder.Append(',').Append(entry.column); + } builder.Append(')'); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs index 1f4c557ba..73908a707 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs @@ -1,15 +1,10 @@ -using Ui = Inno.Editor.ImGui.ImGui; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + internal static class ConsoleEntryImGuiIdentity { - internal static void Push(string identity) - { - Ui.PushId(identity); - } + internal static void Push(string identity) => Gui.PushID(identity); - internal static void Pop() - { - Ui.PopId(); - } + internal static void Pop() => Gui.PopID(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs index fdeced606..2ce0b4ee1 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs @@ -1,45 +1,30 @@ using System; using System.Collections.Generic; using System.Numerics; -using Ui = Inno.Editor.ImGui.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; internal sealed partial class ConsolePanel { - private sealed class EntryMeasurement( - ConsoleView.Row row, - bool open, - float height - ) { - internal readonly ConsoleView.Row row = row; - internal readonly bool open = open; - internal float height = height; - internal int remainingMeasurements = open ? 2 : 0; - } - + private readonly List m_pendingMeasurements = []; + private readonly Dictionary m_cardSlots = new(StringComparer.Ordinal); + private readonly List m_cardWindowNames = []; + private readonly Stack m_freeCardWindows = []; + private readonly List m_retiredCardKeys = []; private Dictionary m_measurements = new(StringComparer.Ordinal); private EntryMeasurement[] m_layout = []; - private readonly List m_pendingMeasurements = []; private IReadOnlyList? m_layoutRows; private float[] m_offsets = [0f]; private (float width, float frameHeight, float padding, float spacing, float zoom)? m_layoutShape; private int m_openRevision; private int m_layoutOpenRevision = -1; private bool m_scrollFocusedRow; - private readonly Dictionary m_cardSlots = new(StringComparer.Ordinal); - private readonly List m_cardWindowNames = []; - private readonly Stack m_freeCardWindows = []; - private readonly List m_retiredCardKeys = []; private ulong m_cardFrame; - private sealed class CardWindowSlot(int index) - { - internal readonly int index = index; - internal ulong lastFrame; - } - private string AcquireCardWindow(string key) { if (!m_cardSlots.TryGetValue(key, out CardWindowSlot? slot)) @@ -59,9 +44,13 @@ private string AcquireCardWindow(string key) private void RetireCardWindows() { m_retiredCardKeys.Clear(); - foreach (var entry in m_cardSlots) + foreach (KeyValuePair entry in m_cardSlots) + { if (entry.Value.lastFrame != m_cardFrame) + { m_retiredCardKeys.Add(entry.Key); + } + } foreach (string key in m_retiredCardKeys) { m_freeCardWindows.Push(m_cardSlots[key].index); @@ -73,7 +62,9 @@ private void RetireCardWindows() private void ToggleEntry(string key) { if (!m_openEntries.Remove(key)) + { m_openEntries.Add(key); + } m_openRevision++; } @@ -89,16 +80,25 @@ private void ClearLayout() m_cardSlots.Clear(); m_freeCardWindows.Clear(); for (int index = m_cardWindowNames.Count - 1; index >= 0; index--) + { m_freeCardWindows.Push(index); + } } private void RefreshLayout() { - var layout = Ui.GetLayout(); - var shape = (width: Ui.GetContentRegionAvailable().X, frameHeight: Ui.GetFrameHeight(), padding: layout.framePadding.Y, - spacing: layout.itemSpacing.Y, zoom: EditorUI.current.widgets.style.zoom); + EditorUILayout layout = Gui.GetLayout(); + (float width, float frameHeight, float padding, float spacing, float zoom) shape = ( + width: Gui.GetContentRegionAvailable().X, + frameHeight: Gui.GetFrameHeight(), + padding: layout.framePadding.Y, + spacing: layout.itemSpacing.Y, + zoom: EditorUI.current.widgets.style.zoom + ); if (ReferenceEquals(m_layoutRows, m_view.rows) && m_layoutShape == shape && m_layoutOpenRevision == m_openRevision) + { return; + } bool sameShape = m_layoutShape == shape; float collapsedHeight = MathF.Truncate(shape.frameHeight + shape.padding * 2f); var measurements = new Dictionary(m_view.rows.Count, StringComparer.Ordinal); @@ -108,8 +108,9 @@ private void RefreshLayout() ConsoleView.Row row = m_view.rows[index]; bool open = m_openEntries.Contains(row.key); EntryMeasurement measurement = sameShape && m_measurements.TryGetValue(row.key, out EntryMeasurement? previous) - && ReferenceEquals(previous.row, row) && previous.open == open - ? previous : new(row, open, collapsedHeight); + && ReferenceEquals(previous.row, row) && previous.open == open + ? previous + : new EntryMeasurement(row, open, collapsedHeight); entries[index] = measurement; measurements.Add(row.key, measurement); } @@ -117,8 +118,12 @@ private void RefreshLayout() m_layout = entries; m_pendingMeasurements.Clear(); for (int index = 0; index < entries.Length; index++) + { if (entries[index].remainingMeasurements > 0) + { m_pendingMeasurements.Add(index); + } + } m_offsets = new float[entries.Length + 1]; m_layoutRows = m_view.rows; m_layoutShape = shape; @@ -128,19 +133,23 @@ private void RefreshLayout() private void RefreshOffsets(int start) { - float spacing = Ui.GetLayout().itemSpacing.Y; + float spacing = Gui.GetLayout().itemSpacing.Y; for (int index = start; index < m_layout.Length; index++) + { m_offsets[index + 1] = m_offsets[index] + m_layout[index].height + spacing; + } } private void DrawVisibleEntries() { - var clip = Ui.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = Gui.GetClipBounds(); if (clip.maximum.Y <= clip.minimum.Y || clip.maximum.X <= clip.minimum.X) + { return; + } RefreshLayout(); m_cardFrame++; - Vector2 origin = Ui.GetCursorScreenPosition(); + Vector2 origin = Gui.GetCursorScreenPosition(); int first = FindLayoutRow(clip.minimum.Y - origin.Y); int last = FindLayoutRow(clip.maximum.Y - origin.Y); int focused = m_view.FindIndex(m_focusedKey); @@ -151,24 +160,38 @@ private void DrawVisibleEntries() bool focusPending = focused >= 0; while (visibleIndex <= last || pendingIndex < m_pendingMeasurements.Count || focusPending) { - int index = Math.Min(visibleIndex <= last ? visibleIndex : int.MaxValue, - pendingIndex < m_pendingMeasurements.Count ? m_pendingMeasurements[pendingIndex] : int.MaxValue); + int index = Math.Min( + visibleIndex <= last ? visibleIndex : int.MaxValue, + pendingIndex < m_pendingMeasurements.Count ? m_pendingMeasurements[pendingIndex] : int.MaxValue + ); if (focusPending) + { index = Math.Min(index, focused); + } if (index == visibleIndex) + { visibleIndex++; + } if (pendingIndex < m_pendingMeasurements.Count && index == m_pendingMeasurements[pendingIndex]) + { pendingIndex++; + } if (index == focused) + { focusPending = false; + } EntryMeasurement entry = m_layout[index]; bool measure = entry.remainingMeasurements > 0; - Ui.SetCursorScreenPosition(origin + new Vector2(0f, m_offsets[index] + adjustment)); + Gui.SetCursorScreenPosition(origin + new Vector2(0f, m_offsets[index] + adjustment)); float height = DrawConsoleEntry(entry.row, measure); if (!float.IsFinite(height) || height <= 0f) + { throw new InvalidOperationException("Console row measurement did not produce a finite positive height."); + } if (measure) + { entry.remainingMeasurements--; + } if (height != entry.height) { adjustment += height - entry.height; @@ -179,21 +202,31 @@ private void DrawVisibleEntries() { float top = origin.Y + m_offsets[index] + adjustment; if (top < clip.minimum.Y) - Ui.SetScrollHereY(0f); + { + Gui.SetScrollHereY(0f); + } else if (top + height > clip.maximum.Y) - Ui.SetScrollHereY(1f); + { + Gui.SetScrollHereY(1f); + } } } for (int index = m_pendingMeasurements.Count - 1; index >= 0; index--) + { if (m_layout[m_pendingMeasurements[index]].remainingMeasurements == 0) + { m_pendingMeasurements.RemoveAt(index); + } + } if (changedFrom < m_layout.Length) + { RefreshOffsets(changedFrom); + } m_scrollFocusedRow = false; // A slot is reusable only after all rows have finished submitting this frame. RetireCardWindows(); - Ui.SetCursorScreenPosition(origin); - Ui.Dummy(new(1f, MathF.Max(1f, m_offsets[^1] - Ui.GetLayout().itemSpacing.Y))); + Gui.SetCursorScreenPosition(origin); + Gui.Dummy(new Vector2(1f, MathF.Max(1f, m_offsets[^1] - Gui.GetLayout().itemSpacing.Y))); } private int FindLayoutRow(float position) @@ -201,4 +234,21 @@ private int FindLayoutRow(float position) int index = Array.BinarySearch(m_offsets, position); return Math.Clamp(index < 0 ? ~index - 1 : index, 0, m_layout.Length - 1); } + + private sealed class EntryMeasurement( + ConsoleView.Row row, + bool open, + float height + ) { + internal readonly ConsoleView.Row row = row; + internal readonly bool open = open; + internal float height = height; + internal int remainingMeasurements = open ? 2 : 0; + } + + private sealed class CardWindowSlot(int index) + { + internal readonly int index = index; + internal ulong lastFrame; + } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs index df1122689..d9770dc63 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; @@ -6,24 +5,28 @@ using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.Diagnostics; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + /// /// Displays append-only logs and current diagnostics in the unified editor Console. /// [EditorPanel("diagnostics.console", "Console", order: 400, menuPath: "Diagnostics")] internal sealed partial class ConsolePanel : EditorPanel { -#region State private readonly ConsolePanelContent m_content = new(); private readonly HashSet m_filterLevels = Enum.GetValues().ToHashSet(); private readonly LogLevel[] m_levels = Enum.GetValues(); private readonly HashSet m_openEntries = new(StringComparer.Ordinal); private readonly ConsoleView m_view = new(); + private readonly IEditorConsole m_console; + private readonly EditorInteractions m_interactions; private string m_query = string.Empty; private string? m_focusedKey; private string? m_selectedKey; @@ -34,15 +37,7 @@ internal sealed partial class ConsolePanel : EditorPanel private bool m_collapse = true; private long m_lastRevision = -1; private bool m_requestScrollToBottom = true; - private readonly IEditorConsole m_console; - private readonly EditorInteractions m_interactions; -#endregion - /// - /// Lets the Console entries region own vertical scrolling. - /// - public override bool allowScrolling => false; -#region Lifecycle /// /// Creates the panel. /// @@ -59,20 +54,24 @@ internal ConsolePanel( IEditorConsole console, EditorInteractions interactions ) { - m_console = console ?? throw new ArgumentNullException(nameof(console)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); + ArgumentNullException.ThrowIfNull(console); + ArgumentNullException.ThrowIfNull(interactions); + m_console = console; + m_interactions = interactions; } + /// + /// Lets the Console entries region own vertical scrolling. + /// + public override bool allowScrolling => false; + /// /// Captures the persistent Console layout preferences without retaining log content. /// /// /// The project-level panel state that receives stable presentation values. /// - protected override void Capture(EditorState state) - { - state.Set("collapse", m_collapse); - } + protected override void Capture(EditorState state) => state.Set("collapse", m_collapse); /// /// Restores persistent Console layout preferences without restoring historical log content. @@ -80,12 +79,9 @@ protected override void Capture(EditorState state) /// /// The project-level panel state containing stable presentation values. /// - protected override void Restore(EditorState state) - { - m_collapse = state.Get("collapse", true); - } + protected override void Restore(EditorState state) => m_collapse = state.Get("collapse", true); - /// + /// protected override void OnDetach(EditorContext context) { ClearFocus(); @@ -104,42 +100,47 @@ protected override void OnDetach(EditorContext context) /// protected override void OnDraw(EditorContext context) { - Ui.BeginChild("ConsoleChild", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + Gui.BeginChild( + "ConsoleChild", + Vector2.Zero, + (ImGuiChildFlags.None), + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { DrawToolbar(); - Ui.Separator(); + Gui.Separator(); DrawConsoleRegion(); } finally { - Ui.EndChild(); + Gui.EndChild(); } } -#endregion -#region Toolbar private static ConsoleStyle consoleStyle => new(EditorUI.current.widgets.style); private void DrawToolbar() { if (EditorUI.current.widgets.SearchInput("console", "Search messages, sources and files", ref m_query, 1024)) + { m_requestScrollToBottom = false; - bool collapseChanged = Ui.Checkbox("Collapse", ref m_collapse); + } + bool collapseChanged = Gui.Checkbox("Collapse", ref m_collapse); if (collapseChanged) { m_requestScrollToBottom = true; } - Ui.SameLine(0f, -1f); + Gui.SameLine(0f, -1f); bool filterChanged = DrawFilterCombo(); if (filterChanged) { m_requestScrollToBottom = true; } - Ui.SameLine(0f, -1f); - if (Ui.Button("Clear")) + Gui.SameLine(0f, -1f); + if (Gui.Button("Clear")) { m_console.Clear(); m_openEntries.Clear(); @@ -160,7 +161,7 @@ private bool DrawFilterCombo() { LogLevel level = m_levels[i]; bool selected = m_filterLevels.Contains(level); - if (!Ui.Checkbox(level.ToString(), ref selected)) + if (!Gui.Checkbox(level.ToString(), ref selected)) { continue; } @@ -181,16 +182,16 @@ private bool DrawFilterCombo() return changed; } -#endregion -#region Console Region private void DrawConsoleRegion() { - Ui.BeginChild("ConsoleRegion", Vector2.Zero, 0, 0); + Gui.BeginChild("ConsoleRegion", Vector2.Zero, 0, 0); try { EditorConsoleSnapshot snapshot = m_console.Capture(); if (m_lastRevision != snapshot.revision) + { RemoveStaleOpenEntries(snapshot); + } bool viewChanged = m_view.Update(snapshot, m_query, m_filterLevels, m_collapse); if (viewChanged) { @@ -199,32 +200,34 @@ private void DrawConsoleRegion() { ClearFocus(); } - else if (m_interactions.focusedArea == LoggingInteractionIds.C_ENTRY_AREA) + else if (m_interactions.focusedArea == LoggingInteractionIDs.C_ENTRY_AREA) + { FocusRow(m_view.rows[focused], select: false); + } } bool hasNewEntries = m_lastRevision >= 0 && snapshot.revision != m_lastRevision; m_lastRevision = snapshot.revision; - bool scrollAtBottom = Ui.GetScrollY() >= Ui.GetScrollMaxY() - consoleStyle.autoScrollTolerance; + bool scrollAtBottom = Gui.GetScrollY() >= Gui.GetScrollMaxY() - consoleStyle.autoScrollTolerance; bool shouldScrollToBottom = m_requestScrollToBottom || (hasNewEntries && scrollAtBottom); HandleKeyboardNavigation(); if (m_keyboardHandled) + { m_requestScrollToBottom = false; + } DrawEntries(snapshot); DrawEntryContextMenu(); if (shouldScrollToBottom && !m_keyboardHandled) { - Ui.SetScrollHereY(1f); + Gui.SetScrollHereY(1f); m_requestScrollToBottom = false; } } finally { - Ui.EndChild(); + Gui.EndChild(); } } -#endregion -#region Entries private void ClearFocus() { m_focusedKey = null; @@ -232,8 +235,10 @@ private void ClearFocus() m_focusedCopyTarget = null; m_contextKey = null; m_requestContextMenu = false; - if (m_interactions.focusedArea == LoggingInteractionIds.C_ENTRY_AREA) - m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA).Focus(); + if (m_interactions.focusedArea == LoggingInteractionIDs.C_ENTRY_AREA) + { + m_interactions.For(LoggingInteractionIDs.C_ENTRY_AREA).Focus(); + } } private void DrawEntries(EditorConsoleSnapshot snapshot) @@ -254,8 +259,6 @@ private void DrawEntries(EditorConsoleSnapshot snapshot) DrawVisibleEntries(); } -#endregion -#region Entry Card private float DrawConsoleEntry( ConsoleView.Row row, bool measure @@ -272,21 +275,26 @@ bool measure ) { bool open = m_openEntries.Contains(row.key); Vector4 cardBg = open ? m_content.GetExpandedBgColor(levelColor) : m_content.GetCollapsedBgColor(); - Vector4 cardBorder = row.key == m_selectedKey ? EditorPalette.contentAccent - : open ? ConsoleStyle.GetExpandedBorder(levelColor) : m_content.GetCollapsedBorderColor(); - Ui.PushStyleColor((ImGuiCol.FrameBg), cardBg); - Ui.PushStyleColor((ImGuiCol.Border), cardBorder); - Ui.PushStyleVar((ImGuiStyleVar.FrameRounding), Ui.GetLayout().frameRounding); - Ui.PushStyleVar((ImGuiStyleVar.FrameBorderSize), EditorUI.current.widgets.style.borderSize); - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.framePadding); + Vector4 cardBorder = row.key == m_selectedKey + ? EditorPalette.contentAccent + : open ? ConsoleStyle.GetExpandedBorder(levelColor) : m_content.GetCollapsedBorderColor(); + Gui.PushStyleColor((ImGuiCol.FrameBg), cardBg); + Gui.PushStyleColor((ImGuiCol.Border), cardBorder); + Gui.PushStyleVar((ImGuiStyleVar.FrameRounding), Gui.GetLayout().frameRounding); + Gui.PushStyleVar((ImGuiStyleVar.FrameBorderSize), EditorUI.current.widgets.style.borderSize); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.framePadding); try { ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | (open ? ImGuiChildFlags.AutoResizeY : ImGuiChildFlags.None); if (open && measure) + { childFlags |= ImGuiChildFlags.AlwaysAutoResize; - ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; - float height = open ? 0f : Ui.GetFrameHeight() + Ui.GetLayout().framePadding.Y * 2f; - bool visible = Ui.BeginChild(AcquireCardWindow(row.key), new Vector2(0f, height), childFlags, windowFlags); + } + ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings; + float height = open ? 0f : Gui.GetFrameHeight() + Gui.GetLayout().framePadding.Y * 2f; + bool visible = Gui.BeginChild(AcquireCardWindow(row.key), new Vector2(0f, height), childFlags, windowFlags); try { if (visible) @@ -296,9 +304,13 @@ bool measure { DrawHeader(row.latest, row.occurrences.Count, levelColor, levelIcon, open, cardBg, out bool toggled); if (toggled) + { ToggleEntry(row.key); + } if (open) + { DrawOccurrences(row.occurrences, cardBg); + } } finally { @@ -308,12 +320,14 @@ bool measure } finally { - Ui.EndChild(); + Gui.EndChild(); } - float measuredHeight = Ui.GetItemMaximum().Y - Ui.GetItemMinimum().Y; - if (Ui.IsItemClicked(ImGuiMouseButton.Left) || Ui.IsItemClicked(ImGuiMouseButton.Right)) + float measuredHeight = Gui.GetItemMaximum().Y - Gui.GetItemMinimum().Y; + if (Gui.IsItemClicked(ImGuiMouseButton.Left) || Gui.IsItemClicked(ImGuiMouseButton.Right)) + { FocusRow(row, select: true); - if (Ui.IsItemHovered() && Ui.IsMouseReleased(ImGuiMouseButton.Right)) + } + if (Gui.IsItemHovered() && Gui.IsMouseReleased(ImGuiMouseButton.Right)) { m_contextKey = row.key; m_requestContextMenu = true; @@ -322,42 +336,11 @@ bool measure } finally { - Ui.PopStyleVar(3); - Ui.PopStyleColor(2); - } - } - - private static void DrawOccurrences( - IReadOnlyList occurrences, - Vector4 cardBackground - ) { - Ui.PushStyleColor(ImGuiCol.Separator, ConsoleStyle.GetSeparator(cardBackground)); - try - { - Ui.Separator(); - for (int i = 0; i < occurrences.Count; i++) - { - if (i > 0) - Ui.Separator(); - Ui.PushId(unchecked((int)occurrences[i].sequence)); - try - { - DrawDetail(occurrences[i]); - } - finally - { - Ui.PopId(); - } - } - } - finally - { - Ui.PopStyleColor(); + Gui.PopStyleVar(3); + Gui.PopStyleColor(2); } } -#endregion -#region Entry Header / Detail private void DrawHeader( EditorConsoleOccurrence entry, int repeatCount, @@ -368,139 +351,92 @@ private void DrawHeader( out bool toggled ) { toggled = false; - EditorUiLayout style = Ui.GetLayout(); + EditorUILayout style = Gui.GetLayout(); string content = isOpen ? entry.displayMessage : m_content.GetFirstLine(entry.displayMessage); string repeatText = repeatCount > 1 ? $" (x{repeatCount})" : string.Empty; string prefix = $"{levelIcon} [{entry.level}] "; string toggleText = isOpen ? "▼" : "▶"; - float toggleW = Ui.MeasureText(toggleText).X + consoleStyle.disclosurePadding.X * 2f; - float prefixW = Ui.MeasureText(prefix).X + toggleW + style.itemInnerSpacing.X; - float suffixW = Ui.MeasureText(repeatText).X; + float toggleW = Gui.MeasureText(toggleText).X + consoleStyle.disclosurePadding.X * 2f; + float prefixW = Gui.MeasureText(prefix).X + toggleW + style.itemInnerSpacing.X; + float suffixW = Gui.MeasureText(repeatText).X; float suffixColW = MathF.Max(1f, suffixW); - float tableOuterW = MathF.Max(1f, Ui.GetContentRegionAvailable().X); + float tableOuterW = MathF.Max(1f, Gui.GetContentRegionAvailable().X); float contentW = MathF.Max(1f, tableOuterW - prefixW - suffixColW); if (!isOpen) { content = m_content.FitTextWithEllipsis(m_content.GetFirstLine(entry.displayMessage), contentW); } - Vector2 tableOuterSize = new(tableOuterW, 0f); - ImGuiTableFlags flags = ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoHostExtendX | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoPadInnerX | ImGuiTableFlags.NoSavedSettings; - if (Ui.BeginTable("##HeaderTable", 3, flags, tableOuterSize)) + var tableOuterSize = new Vector2(tableOuterW, 0f); + ImGuiTableFlags flags = ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoHostExtendX + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoPadInnerX + | ImGuiTableFlags.NoSavedSettings; + if (Gui.BeginTable("##HeaderTable", 3, flags, tableOuterSize)) { try { - Ui.TableSetupColumn("##prefix", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), prefixW); - Ui.TableSetupColumn("##content", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), contentW); - Ui.TableSetupColumn("##suffix", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), suffixColW); - Ui.TableNextRow(); + Gui.TableSetupColumn("##prefix", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), prefixW); + Gui.TableSetupColumn("##content", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), contentW); + Gui.TableSetupColumn("##suffix", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), suffixColW); + Gui.TableNextRow(); if (isOpen) { - uint headerBgU32 = Ui.ToPackedColor(headerBgColor); - Ui.TableSetBgColor((ImGuiTableBgTarget.RowBg0), headerBgU32); + uint headerBgU32 = Gui.ToPackedColor(headerBgColor); + Gui.TableSetBgColor((ImGuiTableBgTarget.RowBg0), headerBgU32); } - _ = Ui.TableSetColumnIndex(0); - Ui.PushStyleVar((ImGuiStyleVar.FramePadding), consoleStyle.disclosurePadding); - Ui.PushStyleVar((ImGuiStyleVar.FrameBorderSize), 0f); - Ui.PushStyleColor((ImGuiCol.Button), ConsoleStyle.toggle); - Ui.PushStyleColor((ImGuiCol.ButtonHovered), ConsoleStyle.toggleHovered); - Ui.PushStyleColor((ImGuiCol.ButtonActive), ConsoleStyle.toggleActive); + _ = Gui.TableSetColumnIndex(0); + Gui.PushStyleVar((ImGuiStyleVar.FramePadding), consoleStyle.disclosurePadding); + Gui.PushStyleVar((ImGuiStyleVar.FrameBorderSize), 0f); + Gui.PushStyleColor((ImGuiCol.Button), ConsoleStyle.toggle); + Gui.PushStyleColor((ImGuiCol.ButtonHovered), ConsoleStyle.toggleHovered); + Gui.PushStyleColor((ImGuiCol.ButtonActive), ConsoleStyle.toggleActive); try { - if (Ui.SmallButton($"{toggleText}##HeaderToggle") && !m_keyboardHandled) + if (Gui.SmallButton($"{toggleText}##HeaderToggle") && !m_keyboardHandled) { toggled = true; } - } finally { - Ui.PopStyleColor(3); - Ui.PopStyleVar(2); + Gui.PopStyleColor(3); + Gui.PopStyleVar(2); } - Ui.SameLine(0f, -1f); + Gui.SameLine(0f, -1f); EditorUI.current.widgets.ColoredText(levelColor, prefix); - _ = Ui.TableSetColumnIndex(1); + _ = Gui.TableSetColumnIndex(1); if (isOpen) { EditorUI.current.widgets.WrappedText(content); } else { - Ui.Text(content); + Gui.Text(content); } - _ = Ui.TableSetColumnIndex(2); + _ = Gui.TableSetColumnIndex(2); if (!string.IsNullOrEmpty(repeatText)) { - float remainW = Ui.GetContentRegionAvailable().X; + float remainW = Gui.GetContentRegionAvailable().X; float suffixOffsetX = MathF.Max(0f, remainW - suffixW); - Ui.SetCursorPosX(Ui.GetCursorPosX() + suffixOffsetX); - Ui.Text(repeatText); + Gui.SetCursorPosX(Gui.GetCursorPosX() + suffixOffsetX); + Gui.Text(repeatText); } - } finally { - Ui.EndTable(); + Gui.EndTable(); } } } - private static void DrawDetail(EditorConsoleOccurrence entry) - { - string timeText = entry.time.ToString("HH:mm:ss"); - string sourceText = entry.source; - if (string.IsNullOrWhiteSpace(sourceText)) - { - sourceText = "-"; - } - - string fileText = string.IsNullOrWhiteSpace(entry.file) ? "-" : entry.file; - string fileWithLineText = entry.line > 0 ? entry.column > 0 ? $"{fileText}:{entry.line}:{entry.column}" : $"{fileText}:{entry.line}" : fileText; - // These cards may be culled between frames; do not rely on a previous frame's auto-fit width. - float labelWidth = Ui.MeasureText("Session:").X; - float availableWidth = Ui.GetContentRegionAvailable().X; - if (availableWidth < labelWidth + Ui.MeasureText("Diagnostic").X + Ui.GetLayout().cellPadding.X * 4) - { - DrawStackedField("Kind:", entry.kind.ToString()); - DrawStackedField("File:", fileWithLineText); - DrawStackedField("Source:", sourceText); - if (entry.sessionId.isAssigned) - DrawStackedField("Session:", entry.sessionId.ToString()); - DrawStackedField("Time:", timeText); - } - else if (Ui.BeginTable("##ConsoleEntryDetails", 2, (ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings), new Vector2(availableWidth, 0))) - { - try - { - Ui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), labelWidth); - Ui.TableSetupColumn("##value", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), 1f); - DrawDetailFieldRow("Kind:", entry.kind.ToString()); - DrawDetailFieldRow("File:", fileWithLineText); - DrawDetailFieldRow("Source:", sourceText); - if (entry.sessionId.isAssigned) - DrawDetailFieldRow("Session:", entry.sessionId.ToString()); - DrawDetailFieldRow("Time:", timeText); - } - finally - { - Ui.EndTable(); - } - } - - if (!string.IsNullOrWhiteSpace(entry.stackTrace)) - { - Ui.Separator(); - EditorUI.current.widgets.WrappedText(entry.stackTrace); - } - } - private void HandleKeyboardNavigation() { int current = m_view.FindIndex(m_focusedKey); - int pageSize = Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / Math.Max(1f, Ui.GetFrameHeight()))); + int pageSize = Math.Max(1, (int)(Gui.GetContentRegionAvailable().Y / Math.Max(1f, Gui.GetFrameHeight()))); ListNavigationResult navigation = EditorUI.current.widgets.NavigateList(m_interactions, m_view.rows.Count, current, pageSize); m_keyboardHandled = navigation.activate || navigation.selectionRequested || navigation.focusChanged; m_scrollFocusedRow = navigation.focusChanged || navigation.activate; @@ -514,7 +450,9 @@ private void HandleKeyboardNavigation() } } if (navigation.cancel) + { ClearFocus(); + } } private void FocusRow( @@ -523,29 +461,33 @@ bool select ) { m_focusedKey = row.key; if (select) + { m_selectedKey = row.key; + } // The view owns this neutral boxed payload while Core keeps only a weak action target. m_focusedCopyTarget = row.copyTarget; - m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA, m_focusedCopyTarget).Focus(); + m_interactions.For(LoggingInteractionIDs.C_ENTRY_AREA, m_focusedCopyTarget).Focus(); } private void DrawEntryContextMenu() { - const string popupId = "##ConsoleEntryContextMenu"; + const string C_POPUP_ID = "##ConsoleEntryContextMenu"; if (m_contextKey is null) + { return; + } int index = m_view.FindIndex(m_contextKey); if (index < 0) { - if (Ui.BeginPopup(popupId)) + if (Gui.BeginPopup(C_POPUP_ID)) { try { - Ui.CloseCurrentPopup(); + Gui.CloseCurrentPopup(); } finally { - Ui.EndPopup(); + Gui.EndPopup(); } } m_contextKey = null; @@ -554,34 +496,131 @@ private void DrawEntryContextMenu() } if (m_requestContextMenu) { - Ui.OpenPopup(popupId); + Gui.OpenPopup(C_POPUP_ID); m_requestContextMenu = false; } - if (!EditorUI.current.menus.ContextMenu(popupId, - m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA, m_view.rows[index].copyTarget))) + if (!EditorUI.current.menus.ContextMenu( + C_POPUP_ID, + m_interactions.For(LoggingInteractionIDs.C_ENTRY_AREA, m_view.rows[index].copyTarget) + )) { m_contextKey = null; + } } private void RemoveStaleOpenEntries(EditorConsoleSnapshot snapshot) { if (m_openEntries.Count == 0) + { return; - var activeIds = new HashSet(StringComparer.Ordinal); + } + var activeIDs = new HashSet(StringComparer.Ordinal); for (int i = 0; i < snapshot.groups.Count; i++) - activeIds.Add($"group/{snapshot.groups[i].identity}"); + { + activeIDs.Add($"group/{snapshot.groups[i].identity}"); + } for (int i = 0; i < snapshot.occurrences.Count; i++) - activeIds.Add($"occurrence/{snapshot.occurrences[i].sequence}"); - m_openEntries.RemoveWhere(id => !activeIds.Contains(id)); + { + activeIDs.Add($"occurrence/{snapshot.occurrences[i].sequence}"); + } + m_openEntries.RemoveWhere(id => !activeIDs.Contains(id)); + } + + private static void DrawOccurrences( + IReadOnlyList occurrences, + Vector4 cardBackground + ) { + Gui.PushStyleColor(ImGuiCol.Separator, ConsoleStyle.GetSeparator(cardBackground)); + try + { + Gui.Separator(); + for (int i = 0; i < occurrences.Count; i++) + { + if (i > 0) + { + Gui.Separator(); + } + Gui.PushID(unchecked((int)occurrences[i].sequence)); + try + { + DrawDetail(occurrences[i]); + } + finally + { + Gui.PopID(); + } + } + } + finally + { + Gui.PopStyleColor(); + } + } + + private static void DrawDetail(EditorConsoleOccurrence entry) + { + string timeText = entry.time.ToString("HH:mm:ss"); + string sourceText = entry.source; + if (string.IsNullOrWhiteSpace(sourceText)) + { + sourceText = "-"; + } + + string fileText = string.IsNullOrWhiteSpace(entry.file) ? "-" : entry.file; + string fileWithLineText = entry.line > 0 ? entry.column > 0 ? $"{fileText}:{entry.line}:{entry.column}" : $"{fileText}:{entry.line}" : fileText; + // These cards may be culled between frames; do not rely on a previous frame's auto-fit width. + float labelWidth = Gui.MeasureText("Session:").X; + float availableWidth = Gui.GetContentRegionAvailable().X; + if (availableWidth < labelWidth + Gui.MeasureText("Diagnostic").X + Gui.GetLayout().cellPadding.X * 4) + { + DrawStackedField("Kind:", entry.kind.ToString()); + DrawStackedField("File:", fileWithLineText); + DrawStackedField("Source:", sourceText); + if (entry.sessionID.isAssigned) + { + DrawStackedField("Session:", entry.sessionID.ToString()); + } + DrawStackedField("Time:", timeText); + } + else if (Gui.BeginTable( + "##ConsoleEntryDetails", + 2, + (ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings), + new Vector2(availableWidth, 0) + )) { + try + { + Gui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), labelWidth); + Gui.TableSetupColumn("##value", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), 1f); + DrawDetailFieldRow("Kind:", entry.kind.ToString()); + DrawDetailFieldRow("File:", fileWithLineText); + DrawDetailFieldRow("Source:", sourceText); + if (entry.sessionID.isAssigned) + { + DrawDetailFieldRow("Session:", entry.sessionID.ToString()); + } + DrawDetailFieldRow("Time:", timeText); + } + finally + { + Gui.EndTable(); + } + } + + if (!string.IsNullOrWhiteSpace(entry.stackTrace)) + { + Gui.Separator(); + EditorUI.current.widgets.WrappedText(entry.stackTrace); + } } private static void DrawDetailFieldRow( string label, string value ) { - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); - _ = Ui.TableSetColumnIndex(1); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); + _ = Gui.TableSetColumnIndex(1); EditorUI.current.widgets.WrappedText(value); } @@ -589,8 +628,7 @@ private static void DrawStackedField( string label, string value ) { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); EditorUI.current.widgets.WrappedText(value); } -#endregion } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs index 33604dca3..397bcea92 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs @@ -2,47 +2,56 @@ using System.Numerics; using Inno.Core.Logging; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + internal sealed class ConsolePanelContent { - private const string C_ICON_BUG = ImGuiIcon.Bug; - private const string C_ICON_INFO = ImGuiIcon.CircleInfo; - private const string C_ICON_WARN = ImGuiIcon.TriangleExclamation; - private const string C_ICON_ERROR = ImGuiIcon.CircleXmark; - private const string C_ICON_FATAL = ImGuiIcon.SkullCrossbones; - private const string C_ICON_DEFAULT = ImGuiIcon.FileLines; + private const string C_ICON_BUG = ImGuiIcon.C_BUG; + private const string C_ICON_INFO = ImGuiIcon.C_CIRCLE_INFO; + private const string C_ICON_WARN = ImGuiIcon.C_TRIANGLE_EXCLAMATION; + private const string C_ICON_ERROR = ImGuiIcon.C_CIRCLE_XMARK; + private const string C_ICON_FATAL = ImGuiIcon.C_SKULL_CROSSBONES; + private const string C_ICON_DEFAULT = ImGuiIcon.C_FILE_LINES; + internal void DrawDisabledHint(string text) { - Ui.BeginDisabled(true); - Ui.Text(text); - Ui.EndDisabled(); + Gui.BeginDisabled(true); + Gui.Text(text); + Gui.EndDisabled(); } internal (Vector4 color, string icon) GetLevelVisual(LogLevel level) + => level switch { - return level switch - { - LogLevel.Debug => (ConsoleStyle.debug, C_ICON_BUG), - LogLevel.Info => (ConsoleStyle.info, C_ICON_INFO), - LogLevel.Warn => (ConsoleStyle.warning, C_ICON_WARN), - LogLevel.Error => (ConsoleStyle.error, C_ICON_ERROR), - LogLevel.Fatal => (ConsoleStyle.fatal, C_ICON_FATAL), - _ => (EditorPalette.text, C_ICON_DEFAULT)}; - } + LogLevel.Debug => (ConsoleStyle.debug, C_ICON_BUG), + LogLevel.Info => (ConsoleStyle.info, C_ICON_INFO), + LogLevel.Warn => (ConsoleStyle.warning, C_ICON_WARN), + LogLevel.Error => (ConsoleStyle.error, C_ICON_ERROR), + LogLevel.Fatal => (ConsoleStyle.fatal, C_ICON_FATAL), + _ => (EditorPalette.text, C_ICON_DEFAULT) + }; internal Vector4 GetCollapsedBgColor() => ConsoleStyle.collapsedCard; + internal Vector4 GetCollapsedBorderColor() => ConsoleStyle.collapsedBorder; + internal Vector4 GetExpandedBgColor(Vector4 levelColor) => ConsoleStyle.GetExpandedCard(levelColor); + internal string GetFirstLine(string text) { if (string.IsNullOrEmpty(text)) + { return string.Empty; + } for (int i = 0; i < text.Length; i++) { if (text[i] is '\n' or '\r') + { return text[..i]; + } } return text; @@ -52,28 +61,40 @@ internal string FitTextWithEllipsis( string text, float maxWidth ) { - const string c_ellipsis = "..."; + const string C_ELLIPSIS = "..."; if (string.IsNullOrEmpty(text)) + { return string.Empty; + } if (maxWidth <= 1f) - return c_ellipsis; - if (Ui.MeasureText(text).X <= maxWidth) + { + return C_ELLIPSIS; + } + if (Gui.MeasureText(text).X <= maxWidth) + { return text; - float ellipsisWidth = Ui.MeasureText(c_ellipsis).X; + } + float ellipsisWidth = Gui.MeasureText(C_ELLIPSIS).X; if (ellipsisWidth >= maxWidth) - return c_ellipsis; + { + return C_ELLIPSIS; + } float maxTextWidth = maxWidth - ellipsisWidth; int low = 0; int high = text.Length; while (low < high) { int middle = (low + high + 1) / 2; - if (Ui.MeasureText(text[..middle]).X <= maxTextWidth) + if (Gui.MeasureText(text[..middle]).X <= maxTextWidth) + { low = middle; + } else + { high = middle - 1; + } } - return low <= 0 ? c_ellipsis : text[..low] + c_ellipsis; + return low <= 0 ? C_ELLIPSIS : text[..low] + C_ELLIPSIS; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs index 5a17c1422..f0132a5fb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs @@ -8,13 +8,13 @@ namespace Inno.Editor.Panel.Logging; internal sealed class ConsoleView { + private readonly Dictionary m_indices = new(StringComparer.Ordinal); private long m_revision = -1; private string m_query = string.Empty; private ulong m_levels; private bool m_collapsed; - private readonly Dictionary m_indices = new(StringComparer.Ordinal); - internal IReadOnlyList rows { get; private set; } = Array.Empty(); + internal IReadOnlyList rows { get; private set; } = []; internal bool Update( EditorConsoleSnapshot snapshot, @@ -24,23 +24,31 @@ bool collapsed ) { ulong mask = 0; foreach (LogLevel level in levels) + { mask |= 1UL << (int)level; + } if (m_revision == snapshot.revision && m_levels == mask && m_collapsed == collapsed - && string.Equals(m_query, query, StringComparison.Ordinal)) + && string.Equals(m_query, query, StringComparison.Ordinal) + ) { return false; - var filtered = new List(); + } + List filtered = []; if (collapsed) { foreach (EditorConsoleGroup group in snapshot.groups) { - var matches = new List(); + List matches = []; foreach (EditorConsoleOccurrence occurrence in group.occurrences) { if (Matches(occurrence, query, levels)) + { matches.Add(occurrence); + } } if (matches.Count > 0) + { filtered.Add(new Row("group/" + group.identity, matches[^1], matches.AsReadOnly())); + } } } else @@ -48,7 +56,9 @@ bool collapsed foreach (EditorConsoleOccurrence occurrence in snapshot.occurrences) { if (Matches(occurrence, query, levels)) - filtered.Add(new Row("occurrence/" + occurrence.sequence, occurrence, Array.AsReadOnly(new[] { occurrence }))); + { + filtered.Add(new Row("occurrence/" + occurrence.sequence, occurrence, Array.AsReadOnly([occurrence]))); + } } } if (collapsed) @@ -65,12 +75,16 @@ bool collapsed { Row previous = rows[previousIndex]; if (ReferenceEquals(previous.latest, candidate.latest) && previous.occurrences.SequenceEqual(candidate.occurrences)) + { filtered[index] = previous; + } } } m_indices.Clear(); for (int index = 0; index < filtered.Count; index++) + { m_indices.Add(filtered[index].key, index); + } rows = filtered.AsReadOnly(); m_revision = snapshot.revision; m_query = query; @@ -83,7 +97,7 @@ bool collapsed internal void Clear() { - rows = Array.Empty(); + rows = []; m_indices.Clear(); m_revision = -1; m_query = string.Empty; @@ -96,13 +110,13 @@ private static bool Matches( string query, IReadOnlySet levels ) => levels.Contains(occurrence.level) - && (query.Length == 0 - || occurrence.message.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.source.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.file.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.code.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.category.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.stackTrace.Contains(query, StringComparison.OrdinalIgnoreCase)); + && (query.Length == 0 + || occurrence.message.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.source.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.file.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.code.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.category.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.stackTrace.Contains(query, StringComparison.OrdinalIgnoreCase)); internal sealed class Row { @@ -114,7 +128,7 @@ IReadOnlyList occurrences this.key = key; this.latest = latest; this.occurrences = occurrences; - copyTarget = new ConsoleEntryCopyTarget(latest, occurrences.Count); + this.copyTarget = new ConsoleEntryCopyTarget(latest, occurrences.Count); } internal string key { get; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs index 7fa3f4ac3..eceafe467 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs @@ -1,11 +1,13 @@ -using Inno.Editor.Interactions; using Inno.Core.Input; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Interactions; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; -[EditorAction(LoggingInteractionIds.C_COPY_DETAILS, LoggingInteractionIds.C_ENTRY_AREA)] -[EditorMenu(LoggingInteractionIds.C_ENTRY_AREA, "Copy Full Entry", order: 110)] -[EditorShortcut(LoggingInteractionIds.C_ENTRY_AREA, KeyCode.C, KeyModifier.Shift, primary: true)] + +[EditorAction(LoggingInteractionIDs.C_COPY_DETAILS, LoggingInteractionIDs.C_ENTRY_AREA)] +[EditorMenu(LoggingInteractionIDs.C_ENTRY_AREA, "Copy Full Entry", order: 110)] +[EditorShortcut(LoggingInteractionIDs.C_ENTRY_AREA, KeyCode.C, KeyModifier.Shift, primary: true)] internal sealed class CopyConsoleDetailsCommand : EditorAction { /// @@ -14,5 +16,5 @@ internal sealed class CopyConsoleDetailsCommand : EditorAction /// The operation scope that provides state, services, and ownership boundaries. /// - protected override void Execute(EditorActionContext context) => Ui.SetClipboardText(context.target.fullText); + protected override void Execute(EditorActionContext context) => Gui.SetClipboardText(context.target.fullText); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs index 3352f1666..b8e6589af 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs @@ -1,11 +1,13 @@ -using Inno.Editor.Interactions; using Inno.Core.Input; -using Ui = Inno.Editor.ImGui.ImGui; +using Inno.Editor.Interactions; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; -[EditorAction(LoggingInteractionIds.C_COPY_MESSAGE, LoggingInteractionIds.C_ENTRY_AREA)] -[EditorMenu(LoggingInteractionIds.C_ENTRY_AREA, "Copy Message", order: 100)] -[EditorShortcut(LoggingInteractionIds.C_ENTRY_AREA, KeyCode.C, primary: true)] + +[EditorAction(LoggingInteractionIDs.C_COPY_MESSAGE, LoggingInteractionIDs.C_ENTRY_AREA)] +[EditorMenu(LoggingInteractionIDs.C_ENTRY_AREA, "Copy Message", order: 100)] +[EditorShortcut(LoggingInteractionIDs.C_ENTRY_AREA, KeyCode.C, primary: true)] internal sealed class CopyConsoleMessageCommand : EditorAction { /// @@ -14,5 +16,5 @@ internal sealed class CopyConsoleMessageCommand : EditorAction /// The operation scope that provides state, services, and ownership boundaries. /// - protected override void Execute(EditorActionContext context) => Ui.SetClipboardText(context.target.message); + protected override void Execute(EditorActionContext context) => Gui.SetClipboardText(context.target.message); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs index 852bfebe8..f1fad692c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs @@ -7,22 +7,41 @@ using Inno.Editor.Settings; namespace Inno.Editor.Panel.Logging; + [EditorModule("diagnostics-logging", order: int.MinValue)] internal sealed class LoggingModule : EditorModule, IEditorConsole { - private IDisposable? m_settingsSubscription; private readonly EditorConsole m_console; private readonly EditorSettings m_settings; + private IDisposable? m_settingsSubscription; + internal LoggingModule( LogRouter logRouter, DiagnosticHub diagnosticHub, IEditorPlayMode playMode, EditorSettings settings ) { - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(settings); + m_settings = settings; m_console = new EditorConsole(logRouter, diagnosticHub, playMode); } + int IEditorConsole.capacity + { + get => m_console.capacity; + set => m_console.capacity = value; + } + + bool IEditorConsole.clearOnPlay + { + get => m_console.clearOnPlay; + set => m_console.clearOnPlay = value; + } + + EditorConsoleSnapshot IEditorConsole.Capture() => m_console.Capture(); + + void IEditorConsole.Clear() => m_console.Clear(); + /// /// Initializes this feature after its owning runtime has activated all required services. /// @@ -58,10 +77,4 @@ protected override void OnDispose() } private void ApplySettings(EditorSettings settings) => m_console.clearOnPlay = ClearConsoleOnPlaySetting.Read(settings); - int IEditorConsole.capacity { get => m_console.capacity; set => m_console.capacity = value; } - - bool IEditorConsole.clearOnPlay { get => m_console.clearOnPlay; set => m_console.clearOnPlay = value; } - - EditorConsoleSnapshot IEditorConsole.Capture() => m_console.Capture(); - void IEditorConsole.Clear() => m_console.Clear(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIDs.cs similarity index 85% rename from src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIds.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIDs.cs index c5a0e2d23..3c8c9fd65 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/LoggingInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Panel.Logging; -internal static class LoggingInteractionIds +internal static class LoggingInteractionIDs { internal const string C_ENTRY_AREA = "panel/diagnostics.console/entry"; internal const string C_COPY_DETAILS = "console/copy-details"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs similarity index 59% rename from src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs index ef1b31961..da0a130c2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs @@ -1,29 +1,14 @@ using Inno.Editor.Settings; -using Ui = Inno.Editor.ImGui.ImGui; -namespace Inno.Editor.Panel.Logging; -[EditorSettingPath("Editor/Diagnostics")] -internal sealed class DiagnosticsSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure diagnostic presentation and retention behavior for this editor."; -} +using Gui = Inno.Editor.ImGui.ImGui; -[EditorSettingPath("Editor/Diagnostics/Console")] -internal sealed class ConsoleSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure how the Console retains ordinary logs across editor workflows."; -} +namespace Inno.Editor.Panel.Logging; [EditorSettingPath(C_PATH)] internal sealed class ClearConsoleOnPlaySetting : EditorSetting { internal const string C_PATH = "Editor/Diagnostics/Console/Clear on Play"; + /// /// Gets a new value initialized to the canonical Console retention policy. /// @@ -41,10 +26,12 @@ public override EditorSettingObject defaultValue /// Gets the presentation section that groups this setting. /// public override string section => "Play Mode"; + /// /// Gets the user-facing explanation of this feature or setting. /// - public override string description => "Clear ordinary Console logs when a new Play Mode request begins while retaining active diagnostics."; + public override string description + => "Clear ordinary Console logs when a new Play Mode request begins while retaining active diagnostics."; /// /// Draws the staged Console retention preference. @@ -55,8 +42,10 @@ public override EditorSettingObject defaultValue protected override void OnDraw(EditorSettingObject setting) { bool value = setting.GetAsBoolean("value", true); - if (Ui.Checkbox("Clear ordinary logs when entering Play Mode", ref value)) + if (Gui.Checkbox("Clear ordinary logs when entering Play Mode", ref value)) + { setting.SetAsBoolean("value", value); + } } internal static bool Read(EditorSettings settings) => settings.Get(C_PATH).GetAsBoolean("value", true); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs new file mode 100644 index 000000000..621888974 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Logging; + +[EditorSettingPath("Editor/Diagnostics/Console")] +internal sealed class ConsoleSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure how the Console retains ordinary logs across editor workflows."; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs new file mode 100644 index 000000000..35c8074fd --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Logging; + +[EditorSettingPath("Editor/Diagnostics")] +internal sealed class DiagnosticsSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure diagnostic presentation and retention behavior for this editor."; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs index ef94e75e6..67114ba7b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs @@ -7,67 +7,80 @@ internal readonly struct ConsoleStyle { private readonly float m_zoom; - internal ConsoleStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal ConsoleStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } /// /// Gets debug log color. /// - internal static Vector4 debug { get; } = new(0.80f, 0.90f, 0.85f, EditorPalette.opacityOpaque); + internal static Vector4 debug { get; } = new(0.8f, 0.9f, 0.85f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets informational log color. /// - internal static Vector4 info { get; } = new(0.20f, 1f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 info { get; } = new(0.2f, 1f, 0.2f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets warning log color. /// - internal static Vector4 warning { get; } = new(1f, 1f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 warning { get; } = new(1f, 1f, 0.2f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets error log color. /// - internal static Vector4 error { get; } = new(1f, 0.20f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 error { get; } = new(1f, 0.2f, 0.2f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets fatal log color. /// - internal static Vector4 fatal { get; } = new(1f, 0.20f, 1f, EditorPalette.opacityOpaque); + internal static Vector4 fatal { get; } = new(1f, 0.2f, 1f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets collapsed log card background. /// - internal static Vector4 collapsedCard { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, EditorPalette.opacityMuted); + internal static Vector4 collapsedCard { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, EditorPalette.C_OPACITY_MUTED); /// /// Gets collapsed log card border. /// - internal static Vector4 collapsedBorder { get; } = new(0.32f, 0.34f, 0.37f, EditorPalette.opacityMedium); + internal static Vector4 collapsedBorder { get; } = new(0.32f, 0.34f, 0.37f, EditorPalette.C_OPACITY_MEDIUM); /// /// Gets the base expanded log card background. /// - internal static Vector4 expandedBase { get; } = new(0.10f, 0.10f, 0.10f, EditorPalette.opacityOpaque); + internal static Vector4 expandedBase { get; } = new(0.1f, 0.1f, 0.1f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets the base expanded log card border. /// - internal static Vector4 expandedBorderBase { get; } = new(0.24f, 0.24f, 0.24f, EditorPalette.opacityOpaque); + internal static Vector4 expandedBorderBase { get; } = new(0.24f, 0.24f, 0.24f, EditorPalette.C_OPACITY_OPAQUE); /// /// Gets log header button background. /// - internal static Vector4 toggle { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, EditorPalette.opacityNone); + internal static Vector4 toggle { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, EditorPalette.C_OPACITY_NONE); /// /// Gets hovered log header button background. /// - internal static Vector4 toggleHovered { get; } = new(0.7372549f, 0.69411767f, 0.8862745f, EditorPalette.opacityMedium); + internal static Vector4 toggleHovered { get; } = new(0.7372549f, 0.69411767f, 0.8862745f, EditorPalette.C_OPACITY_MEDIUM); /// /// Gets active log header button background. /// - internal static Vector4 toggleActive { get; } = new(0.8156863f, 0.77254903f, 0.9647059f, EditorPalette.opacityMedium); + internal static Vector4 toggleActive { get; } = new(0.8156863f, 0.77254903f, 0.9647059f, EditorPalette.C_OPACITY_MEDIUM); + + /// + /// Gets the distance from the bottom treated as auto-scroll. + /// + internal float autoScrollTolerance => m_zoom; + + /// + /// Gets log disclosure padding. + /// + internal Vector2 disclosurePadding => new Vector2(6f, 1f) * m_zoom; /// /// Gets the expanded log card background derived from a severity color. @@ -89,7 +102,7 @@ internal readonly struct ConsoleStyle /// /// The standard expanded-border base blended with the severity color. /// - internal static Vector4 GetExpandedBorder(Vector4 severityColor) => EditorPalette.Lerp(expandedBorderBase, severityColor, 0.20f); + internal static Vector4 GetExpandedBorder(Vector4 severityColor) => EditorPalette.Lerp(expandedBorderBase, severityColor, 0.2f); /// /// Gets the separator color used inside an expanded log card. @@ -101,14 +114,4 @@ internal readonly struct ConsoleStyle /// The card color blended toward the shared text color. /// internal static Vector4 GetSeparator(Vector4 cardColor) => EditorPalette.Lerp(cardColor, EditorPalette.text, 0.12f); - - /// - /// Gets the distance from the bottom treated as auto-scroll. - /// - internal float autoScrollTolerance => m_zoom; - - /// - /// Gets log disclosure padding. - /// - internal Vector2 disclosurePadding => new Vector2(6f, 1f) * m_zoom; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs index a69226a30..65b742bdf 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs @@ -1,22 +1,27 @@ using System.Numerics; using Inno.Editor.ImGui; using Inno.Editor.Settings; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.SceneView; + [EditorSettingPath(C_PATH)] internal sealed class SceneViewBackgroundSetting : EditorSetting { internal const string C_PATH = "Editor/Appearance/Viewports/Scene Background"; - private static readonly float[] S_DEFAULT = [0.11f, 0.12f, 0.14f, EditorPalette.opacityOpaque]; + private static readonly float[] DEFAULT = [0.11f, 0.12f, 0.14f, EditorPalette.C_OPACITY_OPAQUE]; + /// /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Viewport Backgrounds"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -31,22 +36,27 @@ internal sealed class SceneViewBackgroundSetting : EditorSetting protected override void OnDraw(EditorSettingObject setting) { Vector4 value = ReadVector(setting); - Ui.SetNextItemWidth(-1f); - if (Ui.ColorEditLinear4("##scene_view_background", ref value)) + Gui.SetNextItemWidth(-1f); + if (Gui.ColorEditLinear4("##scene_view_background", ref value)) + { setting.SetAsSingleArray("value", [value.X, value.Y, value.Z, value.W]); + } } internal static Vector4 Read(EditorSettings settings) => ReadVector(settings.Get(C_PATH)); + private static EditorSettingObject CreateDefault() { var result = new EditorSettingObject(); - result.SetAsSingleArray("value", S_DEFAULT); + result.SetAsSingleArray("value", DEFAULT); return result; } private static Vector4 ReadVector(EditorSettingObject setting) { - float[] values = setting.GetAsSingleArray("value", S_DEFAULT); - return values.Length == 4 ? new Vector4(values[0], values[1], values[2], values[3]) : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); + float[] values = setting.GetAsSingleArray("value", DEFAULT); + return values.Length == 4 + ? new Vector4(values[0], values[1], values[2], values[3]) + : new Vector4(DEFAULT[0], DEFAULT[1], DEFAULT[2], DEFAULT[3]); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs index 8417a698b..506afad25 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs @@ -1,10 +1,8 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.References; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; +using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; @@ -13,45 +11,52 @@ using Inno.Editor.Rendering; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.References; +using Inno.Rendering; using Inno.Scene; using Inno.Scene.Components; -using ImGuizmoMode = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoSpace; -using ImGuizmoOperation = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoOperation; -using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using EngineColor = Inno.Core.Mathematics.Color; using EngineMatrix = Inno.Core.Mathematics.Matrix; using EngineQuaternion = Inno.Core.Mathematics.Quaternion; using EngineVector3 = Inno.Core.Mathematics.Vector3; +using EngineVector4 = Inno.Core.Mathematics.Vector4; +using Gui = Inno.Editor.ImGui.ImGui; +using ImGuizmoMode = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoSpace; +using ImGuizmoOperation = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoOperation; namespace Inno.Editor.Panel.SceneView; + /// /// Presents the active Plugin provider and host-owned transform manipulation for the Scene viewport. /// [EditorPanel("rendering.scene-view", "Scene", order: 210, menuPath: "Viewports")] internal sealed class SceneViewPanel : EditorPanel { - private IDisposable? m_settingsSubscription; private const string C_VIEWPORT_ID = "scene-view"; private const string C_GIZMO_CLUSTER_POPUP = "##scene-gizmo-cluster"; private const int C_MANIPULATION_TOOL_COUNT = 4; private const string C_TRANSFORM_EDIT = "scene-view.transform"; - private static readonly EditorViewportKindId S_KIND = new("inno.editor.viewport.scene"); - private static readonly Vector2 S_UNAVAILABLE_PADDING = new(48f, 32f); + private static readonly EditorViewportKindID KIND = new("inno.editor.viewport.scene"); + private static readonly Vector2 UNAVAILABLE_PADDING = new(48f, 32f); private readonly EditorRenderingModule m_rendering; private readonly EditorInteractions m_interactions; private readonly SceneEdits m_sceneEdits; private readonly IEditorGameScenePresentation m_scenePresentation; private readonly EditorPlayModeLoop m_playModeLoop; private readonly EditorSettings m_settings; + private readonly EditorPlanarNavigation m_planarNavigation = new(); + private IDisposable? m_settingsSubscription; private Vector4 m_backgroundColor; private NavigationDrag m_navigationDrag; - private readonly EditorPlanarNavigation m_planarNavigation = new(); private ImGuiMouseButton m_navigationDragButton; private ImGuizmoOperation m_operation = ImGuizmoOperation.Translate; private ImGuizmoMode m_mode = ImGuizmoMode.World; private RuntimeIdentity? m_gestureTarget; private RuntimeIdentity[] m_gestureTargets = []; private Identity[] m_popupGizmoOwners = []; + internal SceneViewPanel( EditorRenderingModule rendering, EditorInteractions interactions, @@ -60,18 +65,25 @@ internal SceneViewPanel( EditorPlayModeLoop playModeLoop, EditorSettings settings ) { - m_rendering = rendering ?? throw new ArgumentNullException(nameof(rendering)); - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_sceneEdits = sceneEdits ?? throw new ArgumentNullException(nameof(sceneEdits)); - m_scenePresentation = scenePresentation ?? throw new ArgumentNullException(nameof(scenePresentation)); - m_playModeLoop = playModeLoop ?? throw new ArgumentNullException(nameof(playModeLoop)); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(rendering); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(sceneEdits); + ArgumentNullException.ThrowIfNull(scenePresentation); + ArgumentNullException.ThrowIfNull(playModeLoop); + ArgumentNullException.ThrowIfNull(settings); + m_rendering = rendering; + m_interactions = interactions; + m_sceneEdits = sceneEdits; + m_scenePresentation = scenePresentation; + m_playModeLoop = playModeLoop; + m_settings = settings; } /// /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Gets whether allow scrolling is enabled for this implementation. /// @@ -87,23 +99,27 @@ protected override void OnDraw(EditorContext context) { using IDisposable presentationScope = m_playModeLoop.EnterPresentationScope(); _ = context; - if (m_gestureTarget is not null && !Ui.IsMouseButtonDown(ImGuiMouseButton.Left)) + if (m_gestureTarget is not null && !Gui.IsMouseButtonDown(ImGuiMouseButton.Left)) + { CommitGesture(); - Vector2 available = Ui.GetContentRegionAvailable(); + } + Vector2 available = Gui.GetContentRegionAvailable(); if (available.X <= 0f || available.Y <= 0f) + { return; + } int width = Math.Max(1, (int)MathF.Floor(available.X)); int height = Math.Max(1, (int)MathF.Floor(available.Y)); m_rendering.SetPresentation(C_VIEWPORT_ID, new EditorViewportPresentation(ToEngineColor(m_backgroundColor))); m_rendering.SetContentScope(C_VIEWPORT_ID, CreateContentScope()); - Vector2 minimum = Ui.GetCursorScreenPosition(); + Vector2 minimum = Gui.GetCursorScreenPosition(); Vector2 maximum = minimum + new Vector2(width, height); ManipulationToolbarLayout toolbar = CreateManipulationToolbarLayout(minimum, maximum); - bool hovered = Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) && Ui.IsMouseHoveringRect(minimum, maximum); + bool hovered = Gui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) && Gui.IsMouseHoveringRect(minimum, maximum); bool toolbarHovered = IsManipulationToolbarHovered(toolbar); - _ = m_rendering.TryConfigureNavigation(S_KIND, C_VIEWPORT_ID, width, height, out EditorViewportNavigationProfile navigationProfile); + _ = m_rendering.TryConfigureNavigation(KIND, C_VIEWPORT_ID, width, height, out EditorViewportNavigationProfile navigationProfile); bool navigationOwnsPointer = HandleNavigation(navigationProfile, hovered && !toolbarHovered, minimum, maximum); - if (!m_rendering.TrySubmit(S_KIND, C_VIEWPORT_ID, width, height, out EditorViewportOutput output)) + if (!m_rendering.TrySubmit(KIND, C_VIEWPORT_ID, width, height, out EditorViewportOutput output)) { DrawUnavailable(available, m_rendering.GetCompositionError(C_VIEWPORT_ID) ?? "No rendering model contributes to Scene View."); _ = DrawManipulationToolbar(toolbar); @@ -118,12 +134,12 @@ protected override void OnDraw(EditorContext context) } m_rendering.Draw(output, new Vector2(width, height)); - minimum = Ui.GetItemMinimum(); - maximum = Ui.GetItemMaximum(); - bool viewportClicked = Ui.IsItemClicked(ImGuiMouseButton.Left); + minimum = Gui.GetItemMinimum(); + maximum = Gui.GetItemMaximum(); + bool viewportClicked = Gui.IsItemClicked(ImGuiMouseButton.Left); toolbar = CreateManipulationToolbarLayout(minimum, maximum); toolbarHovered = IsManipulationToolbarHovered(toolbar); - EditorDrawList drawList = Ui.GetDrawList(); + EditorDrawList drawList = Gui.GetDrawList(); IReadOnlyList<(Vector2 center, EditorGizmoIcon icon)> icons; bool toolbarOwnsPointer; bool gizmoOwnsPointer; @@ -142,13 +158,18 @@ protected override void OnDraw(EditorContext context) drawList.MergeChannels(); } - bool iconOwnsPointer = SelectGizmoIcons(icons, viewportClicked && !toolbarOwnsPointer && !gizmoOwnsPointer && !navigationOwnsPointer); - if (!viewportClicked || toolbarOwnsPointer || gizmoOwnsPointer || iconOwnsPointer || navigationOwnsPointer || Ui.GetInput().alt) + bool iconOwnsPointer = SelectGizmoIcons( + icons, + viewportClicked && !toolbarOwnsPointer && !gizmoOwnsPointer && !navigationOwnsPointer + ); + if (!viewportClicked || toolbarOwnsPointer || gizmoOwnsPointer || iconOwnsPointer || navigationOwnsPointer || Gui.GetInput().alt) + { return; - Vector2 mouse = Ui.GetMousePos(); + } + Vector2 mouse = Gui.GetMousePos(); float x = (mouse.X - minimum.X) / Math.Max(1f, maximum.X - minimum.X); float y = (mouse.Y - minimum.Y) / Math.Max(1f, maximum.Y - minimum.Y); - m_rendering.HandlePointer(S_KIND, C_VIEWPORT_ID, width, height, x, y, button: 0); + m_rendering.HandlePointer(KIND, C_VIEWPORT_ID, width, height, x, y, button: 0); } /// @@ -191,7 +212,9 @@ protected override void Capture(EditorState state) EditorViewportNavigationState navigation = m_rendering.GetNavigationState(C_VIEWPORT_ID); state.Set("navigation.initialized", navigation.isInitialized); if (!navigation.isInitialized) + { return; + } state.Set("navigation.position.x", navigation.position.x); state.Set("navigation.position.y", navigation.position.y); state.Set("navigation.position.z", navigation.position.z); @@ -221,16 +244,29 @@ protected override void Capture(EditorState state) protected override void Restore(EditorState state) { if (!state.Get("navigation.initialized", false)) + { return; - var position = new EngineVector3(state.Get("navigation.position.x", 0f), state.Get("navigation.position.y", 0f), state.Get("navigation.position.z", 0f)); + } + var position = new EngineVector3( + state.Get("navigation.position.x", 0f), + state.Get("navigation.position.y", 0f), + state.Get("navigation.position.z", 0f) + ); var rotation = new EngineQuaternion( state.Get("navigation.rotation.x", 0f), state.Get("navigation.rotation.y", 0f), state.Get("navigation.rotation.z", 0f), state.Get("navigation.rotation.w", 1f) ); - var pivot = new EngineVector3(state.Get("navigation.pivot.x", 0f), state.Get("navigation.pivot.y", 0f), state.Get("navigation.pivot.z", 0f)); - EditorViewportProjection projection = (EditorViewportProjection)state.Get("navigation.projection", (int)EditorViewportProjection.Orthographic); + var pivot = new EngineVector3( + state.Get("navigation.pivot.x", 0f), + state.Get("navigation.pivot.y", 0f), + state.Get("navigation.pivot.z", 0f) + ); + EditorViewportProjection projection = (EditorViewportProjection)state.Get( + "navigation.projection", + (int)EditorViewportProjection.Orthographic + ); try { EditorViewportNavigationState navigation = m_rendering.GetNavigationState(C_VIEWPORT_ID); @@ -261,38 +297,46 @@ protected override void Restore(EditorState state) } private void ApplySettings(EditorSettings settings) => m_backgroundColor = SceneViewBackgroundSetting.Read(settings); + private ContentReadScope CreateContentScope() => m_scenePresentation.Capture(); + private IReadOnlyList<(Vector2 center, EditorGizmoIcon icon)> DrawGizmos( Vector2 minimum, Vector2 maximum ) { if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace space)) + { return[]; + } int width = Math.Max(1, (int)(maximum.X - minimum.X)); int height = Math.Max(1, (int)(maximum.Y - minimum.Y)); EditorGizmoFrame frame = m_rendering.CollectGizmos(C_VIEWPORT_ID, width, height); EngineMatrix worldToClip = space.projectionMatrix * space.viewMatrix; - EditorDrawList draw = Ui.GetDrawList(); - uint white = Ui.ToPackedColor(Vector4.One); - uint outline = Ui.ToPackedColor(new Vector4(0f, 0f, 0f, 0.75f)); + EditorDrawList draw = Gui.GetDrawList(); + uint white = Gui.ToPackedColor(Vector4.One); + uint outline = Gui.ToPackedColor(new Vector4(0f, 0f, 0f, 0.75f)); foreach (EditorGizmoLine line in frame.lines) { if (!TryProject(line.start, out Vector2 start) || !TryProject(line.end, out Vector2 end)) + { continue; - Ui.DrawLine(start + Vector2.One, end + Vector2.One, outline, 3.5f); - Ui.DrawLine(start, end, white, 2.5f); + } + Gui.DrawLine(start + Vector2.One, end + Vector2.One, outline, 3.5f); + Gui.DrawLine(start, end, white, 2.5f); } float iconSize = 24f * EditorUI.current.widgets.style.zoom; - var displayIcons = new List<(Vector2 center, EditorGizmoIcon icon)>(); + List<(Vector2 center, EditorGizmoIcon icon)> displayIcons = []; foreach (EditorGizmoIcon icon in frame.icons) { if (!TryProject(icon.position, out Vector2 center)) + { continue; + } displayIcons.Add((center, icon)); - string glyph = GizmoIconGlyph(icon.iconId); - float fontScale = iconSize / Ui.GetFontSize(); - Vector2 size = Ui.MeasureText(glyph, fontScale); + string glyph = GizmoIconGlyph(icon.iconID); + float fontScale = iconSize / Gui.GetFontSize(); + Vector2 size = Gui.MeasureText(glyph, fontScale); Vector2 origin = center - size * 0.5f; draw.Text(origin + Vector2.One, outline, glyph, fontScale); draw.Text(origin, white, glyph, fontScale); @@ -303,7 +347,7 @@ bool TryProject( EngineVector3 world, out Vector2 screen ) { - Inno.Core.Mathematics.Vector4 clip = Inno.Core.Mathematics.Vector4.Transform(new Inno.Core.Mathematics.Vector4(world.x, world.y, world.z, 1f), worldToClip); + EngineVector4 clip = EngineVector4.Transform(new EngineVector4(world.x, world.y, world.z, 1f), worldToClip); if (clip.w <= 0.000001f) { screen = default; @@ -322,9 +366,13 @@ bool maySelect bool iconClicked = false; if (maySelect) { - Vector2 mouse = Ui.GetMousePos(); + Vector2 mouse = Gui.GetMousePos(); float radius = 20f * EditorUI.current.widgets.style.zoom; - Identity[] owners = displayIcons.Where(icon => Vector2.DistanceSquared(mouse, icon.center) <= radius * radius).Select(static icon => icon.icon.owner).DistinctBy(static owner => owner.persistentId).ToArray(); + Identity[] owners = displayIcons + .Where(icon => Vector2.DistanceSquared(mouse, icon.center) <= radius * radius) + .Select(static icon => icon.icon.owner) + .DistinctBy(static owner => owner.persistentID) + .ToArray(); if (owners.Length == 1 && owners[0].Resolve() is { isDestroyed: false } owner) { m_interactions.SetSelection(owner); @@ -333,7 +381,7 @@ bool maySelect else if (owners.Length > 1) { m_popupGizmoOwners = owners; - Ui.OpenPopup(C_GIZMO_CLUSTER_POPUP); + Gui.OpenPopup(C_GIZMO_CLUSTER_POPUP); iconClicked = true; } } @@ -344,31 +392,30 @@ bool maySelect private void DrawGizmoClusterPopup() { - if (!Ui.BeginPopup(C_GIZMO_CLUSTER_POPUP)) + if (!Gui.BeginPopup(C_GIZMO_CLUSTER_POPUP)) + { return; + } foreach (Identity identity in m_popupGizmoOwners) { GameObject? owner = identity.Resolve(); if (owner is null || owner.isDestroyed) + { continue; + } string label = $"{owner.name}##{identity.runtimeIdentity}"; - if (!Ui.MenuItem(label, string.Empty, false, true)) + if (!Gui.MenuItem(label, string.Empty, false, true)) + { continue; + } m_interactions.SetSelection(owner); - Ui.CloseCurrentPopup(); + Gui.CloseCurrentPopup(); break; } - Ui.EndPopup(); + Gui.EndPopup(); } - private static string GizmoIconGlyph(string iconId) => iconId switch - { - "camera" => ImGuiIcon.Camera, - "light" => ImGuiIcon.Lightbulb, - "canvas" => ImGuiIcon.VectorSquare, - _ => ImGuiIcon.CircleQuestion - }; private bool HandleNavigation( EditorViewportNavigationProfile profile, bool hovered, @@ -384,25 +431,27 @@ Vector2 maximum } if (!SupportsMode(profile, navigation.mode)) + { navigation.mode = profile.defaultMode; - EditorUiInput io = Ui.GetInput(); - if (m_navigationDrag != NavigationDrag.None && !Ui.IsMouseButtonDown(m_navigationDragButton)) + } + EditorUIInput io = Gui.GetInput(); + if (m_navigationDrag != NavigationDrag.None && !Gui.IsMouseButtonDown(m_navigationDragButton)) { m_navigationDrag = NavigationDrag.None; } bool panning = m_planarNavigation.Update( hovered && m_navigationDrag == NavigationDrag.None && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Pan), - Ui.IsMouseClicked(ImGuiMouseButton.Left), - Ui.IsMouseClicked(ImGuiMouseButton.Middle), - Ui.IsMouseButtonDown(ImGuiMouseButton.Left), - Ui.IsMouseButtonDown(ImGuiMouseButton.Middle), + Gui.IsMouseClicked(ImGuiMouseButton.Left), + Gui.IsMouseClicked(ImGuiMouseButton.Middle), + Gui.IsMouseButtonDown(ImGuiMouseButton.Left), + Gui.IsMouseButtonDown(ImGuiMouseButton.Middle), io.alt, allowAltPrimary: !profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit) ); if (hovered && !panning && m_navigationDrag == NavigationDrag.None) { - if (io.alt && Ui.IsMouseClicked(ImGuiMouseButton.Left)) + if (io.alt && Gui.IsMouseClicked(ImGuiMouseButton.Left)) { if (profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit)) { @@ -410,14 +459,14 @@ Vector2 maximum m_navigationDragButton = ImGuiMouseButton.Left; } } - else if (Ui.IsMouseClicked(ImGuiMouseButton.Right) && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly)) + else if (Gui.IsMouseClicked(ImGuiMouseButton.Right) && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly)) { m_navigationDrag = NavigationDrag.Fly; m_navigationDragButton = ImGuiMouseButton.Right; } } - if (!io.wantsText && Ui.IsKeyPressed(ImGuiKey.Escape, repeat: false)) + if (!io.wantsText && Gui.IsKeyPressed(ImGuiKey.Escape, repeat: false)) { m_planarNavigation.Cancel(); m_navigationDrag = NavigationDrag.None; @@ -426,14 +475,16 @@ Vector2 maximum bool ownsPointer = panning || m_navigationDrag != NavigationDrag.None; if (!hovered && !ownsPointer) + { return false; + } float width = MathF.Max(1f, maximum.X - minimum.X); float height = MathF.Max(1f, maximum.Y - minimum.Y); float aspect = width / height; if (panning) { Pan(navigation, new Vector2(io.mouseDelta.X, io.mouseDelta.Y), height); - Ui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); + Gui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); } switch (m_navigationDrag) @@ -447,25 +498,321 @@ Vector2 maximum } if (hovered && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Zoom) && io.wheel != 0f) - Zoom(navigation, profile, io.wheel, minimum, width, height, aspect); - if (hovered && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.FrameSelection) && Ui.IsKeyPressed(ImGuiKey.F, repeat: false)) { + Zoom(navigation, profile, io.wheel, minimum, width, height, aspect); + } + if (hovered + && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.FrameSelection) + && Gui.IsKeyPressed(ImGuiKey.F, repeat: false) + ) { EditorViewportFocusBounds? bounds = profile.focusBounds; if (bounds is null && TryGetSelectedTransform(out Transform? selected)) + { bounds = new EditorViewportFocusBounds(selected!.worldPosition, 0.5f); + } if (bounds is EditorViewportFocusBounds focus) + { Frame(navigation, profile, focus); + } } return ownsPointer; } + private void DrawUnavailable( + Vector2 size, + string message + ) { + Vector2 minimum = Gui.GetCursorScreenPosition(); + Vector2 maximum = minimum + size; + EditorDrawList drawList = Gui.GetDrawList(); + Gui.DrawFilledRectangle(minimum, maximum, Gui.ToPackedColor(m_backgroundColor), 0); + Gui.PushStyleColor(ImGuiCol.Text, EditorPalette.textDisabled); + try + { + EditorUI.current.widgets.CenteredWrappedText(message, size, UNAVAILABLE_PADDING); + } + finally + { + Gui.PopStyleColor(); + } + } + + private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) + { + EditorDrawList drawList = Gui.GetDrawList(); + Vector4 background = EditorPalette.targetHeader; + background.W = EditorPalette.C_OPACITY_MEDIUM; + Gui.DrawFilledRectangle( + layout.minimum, + layout.maximum, + Gui.ToPackedColor(background), + EditorUI.current.widgets.style.frameRounding + ); + float itemX = layout.minimum.X + layout.padding; + float itemY = layout.minimum.Y + layout.padding; + try + { + if (DrawManipulationTool( + "move", + ImGuiIcon.C_UP_DOWN_LEFT_RIGHT, + "Move", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Translate + )) { + m_operation = ImGuizmoOperation.Translate; + } + + itemY += layout.itemSize.Y + layout.spacing; + if (DrawManipulationTool( + "rotate", + ImGuiIcon.C_ROTATE, + "Rotate", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Rotate + )) { + m_operation = ImGuizmoOperation.Rotate; + } + + itemY += layout.itemSize.Y + layout.spacing; + if (DrawManipulationTool( + "scale", + ImGuiIcon.C_UP_RIGHT_AND_DOWN_LEFT_FROM_CENTER, + "Scale", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Scale + )) { + m_operation = ImGuizmoOperation.Scale; + } + + itemY += layout.itemSize.Y + layout.sectionSpacing; + float separatorY = itemY - layout.sectionSpacing * 0.5f; + Gui.DrawLine( + new Vector2(layout.minimum.X + layout.padding, separatorY), + new Vector2(layout.maximum.X - layout.padding, separatorY), + Gui.ToPackedColor(Vector4.One), + EditorUI.current.widgets.style.borderSize + ); + bool supportsCoordinateSpace = m_operation != ImGuizmoOperation.Scale; + string modeIcon = supportsCoordinateSpace && m_mode == ImGuizmoMode.World ? ImGuiIcon.C_GLOBE : ImGuiIcon.C_CUBE; + string modeTooltip = !supportsCoordinateSpace + ? "Coordinate Space: Local (Scale is always local)" + : m_mode == ImGuizmoMode.Local ? "Coordinate Space: Local (axes follow the selected transform)" : "Coordinate Space: World (axes follow the world)"; + if (!supportsCoordinateSpace) + { + Gui.BeginDisabled(true); + } + bool toggleCoordinateSpace; + try + { + toggleCoordinateSpace = DrawManipulationTool( + "coordinate_space", + modeIcon, + modeTooltip, + new Vector2(itemX, itemY), + layout.itemSize, + selected: false + ); + } + finally + { + if (!supportsCoordinateSpace) + { + Gui.EndDisabled(); + } + } + + if (!supportsCoordinateSpace + && Gui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled) + && EditorUI.current.widgets.BeginMenuTooltip() + ) { + Gui.Text(modeTooltip); + EditorUI.current.widgets.EndMenuTooltip(); + } + + if (toggleCoordinateSpace && supportsCoordinateSpace) + { + m_mode = m_mode == ImGuizmoMode.Local ? ImGuizmoMode.World : ImGuizmoMode.Local; + } + } + finally + { + Gui.SetCursorScreenPosition(layout.viewportMaximum); + Gui.Dummy(Vector2.Zero); + } + + return IsManipulationToolbarHovered(layout); + } + + private bool DrawTransformGizmo( + Vector2 minimum, + Vector2 maximum, + bool canInteract + ) { + if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace manipulationSpace) + || !TryGetSelectedTransform(out Transform? selected) + ) { + return false; + } + + if (m_gestureTarget is not null && !EditorUI.current.widgets.IsEditing(C_TRANSFORM_EDIT)) + { + m_gestureTarget = null; + m_gestureTargets = []; + } + + Transform target = m_gestureTarget is RuntimeIdentity identity + && m_interactions.TryResolveIdentity(identity, out IdentityObject? resolved) + && resolved is Transform active ? active : selected!; + EngineMatrix world = target.localToWorldMatrix; + ImGuizmoOperation operation = SelectManipulationOperation(manipulationSpace.plane, m_operation); + bool planarTranslation = manipulationSpace.plane != EditorViewportManipulationPlane.Spatial + && m_operation == ImGuizmoOperation.Translate; + TransformGizmoResult result = EditorUI.current.widgets.TransformGizmo( + world, + new TransformGizmoOptions + { + minimum = minimum, + maximum = maximum, + view = manipulationSpace.viewMatrix, + projection = manipulationSpace.projectionMatrix, + orthographic = manipulationSpace.isOrthographic, + enabled = canInteract || m_gestureTarget is not null, + operation = operation, + space = m_operation == ImGuizmoOperation.Scale ? ImGuizmoMode.Local : m_mode, + maskX = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.YZ, + maskY = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.XZ, + maskZ = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.XY + } + ); + if (Gui.IsKeyPressed(ImGuiKey.Escape, false) && m_gestureTarget is not null) + { + EditorUI.current.widgets.CancelEdits(); + m_gestureTarget = null; + m_gestureTargets = []; + return true; + } + + if (result.isUsing) + { + if (m_gestureTarget is null) + { + m_gestureTarget = target.identity.runtimeIdentity; + m_gestureTargets = SelectedTransforms().Select(value => value.identity.runtimeIdentity!.Value).ToArray(); + } + + EditorUI.current.widgets.BeginEdit(m_interactions.history, C_TRANSFORM_EDIT, "Transform Selection"); + } + + if (result.changed && m_gestureTargets.Length != 0) + { + try + { + EngineMatrix delta = result.matrix * EngineMatrix.Invert(world); + foreach (RuntimeIdentity current in m_gestureTargets) + { + if (!m_interactions.TryResolveIdentity(current, out IdentityObject? value) || value is not Transform transform) + { + throw new InvalidOperationException("A transform gesture target is no longer available."); + } + EngineMatrix next = delta * transform.localToWorldMatrix; + if (!TryReadManipulatedTransform( + next, + transform, + m_operation, + out EngineVector3 position, + out EngineQuaternion rotation, + out EngineVector3 scale + ) + || !IsUsable(position, rotation, scale) + ) { + throw new InvalidOperationException("The manipulated transform is not invertible or finite."); + } + _ = m_sceneEdits.ChangeProperty( + transform, + nameof(Transform.localPosition), + () => transform.SetWorldTransform(position, rotation, scale), + "Transform Selection", + EditorUI.current.widgets.editMergeKey + ); + } + } + catch + { + EditorUI.current.widgets.CancelEdits(); + m_gestureTarget = null; + m_gestureTargets = []; + throw; + } + } + + if (!result.isUsing && m_gestureTarget is not null) + { + CommitGesture(); + } + return result.isUsing || result.isOver; + } + + private Transform[] SelectedTransforms() + { + List selected = []; + m_interactions.selection.CopyTargets(selected); + Transform[] transforms = selected.Select(value => value switch + { + GameObject gameObject => gameObject.transform, + GameComponent component => component.transform, + _ => null + }).OfType().Distinct().ToArray(); + HashSet set = transforms.ToHashSet(); + return transforms.Where(value => !HasSelectedAncestor(value, set)).ToArray(); + } + + private bool TryGetSelectedTransform(out Transform? transform) + { + transform = m_interactions.selection.selectedTarget switch + { + GameObject gameObject when !gameObject.isDestroyed => gameObject.transform, + Transform selectedTransform when !selectedTransform.isDestroyed => selectedTransform, + GameComponent component when !component.isDestroyed => component.transform, + _ => null + }; + return transform is not null && m_sceneEdits.CanEdit(transform); + } + + private void CommitGesture() + { + if (m_gestureTarget is null) + { + return; + } + if (EditorUI.current.widgets.IsEditing(C_TRANSFORM_EDIT)) + { + EditorUI.current.widgets.CommitEdits(); + } + m_gestureTarget = null; + m_gestureTargets = []; + } + + private static string GizmoIconGlyph(string iconID) + => iconID switch + { + "camera" => ImGuiIcon.C_CAMERA, + "light" => ImGuiIcon.C_LIGHTBULB, + "canvas" => ImGuiIcon.C_VECTOR_SQUARE, + _ => ImGuiIcon.C_CIRCLE_QUESTION + }; + private static void Pan( EditorViewportNavigationState navigation, Vector2 mouseDelta, float height ) { - float verticalSpan = navigation.projection == EditorViewportProjection.Orthographic ? navigation.orthographicSize * 2f : 2f * navigation.focusDistance * MathF.Tan(navigation.fieldOfView * MathF.PI / 360f); + float verticalSpan = navigation.projection == EditorViewportProjection.Orthographic + ? navigation.orthographicSize * 2f + : 2f * navigation.focusDistance * MathF.Tan(navigation.fieldOfView * MathF.PI / 360f); float unitsPerPixel = verticalSpan / height; EngineVector3 right = EngineVector3.Transform(EngineVector3.RIGHT, navigation.rotation); EngineVector3 up = EngineVector3.Transform(EngineVector3.UP, navigation.rotation); @@ -493,7 +840,7 @@ Vector2 mouseDelta private static void Fly( EditorViewportNavigationState navigation, EditorViewportNavigationProfile profile, - EditorUiInput io + EditorUIInput io ) { float sensitivity = GetPositive(profile.rotationSensitivity, 0.005f); EngineVector3 worldUp = GetWorldUp(profile); @@ -505,18 +852,30 @@ EditorUiInput io EngineVector3 movement = EngineVector3.ZERO; EngineVector3 forward = EngineVector3.Transform(EngineVector3.FORWARD, navigation.rotation); right = EngineVector3.Transform(EngineVector3.RIGHT, navigation.rotation); - if (Ui.IsKeyDown(ImGuiKey.W)) + if (Gui.IsKeyDown(ImGuiKey.W)) + { movement += forward; - if (Ui.IsKeyDown(ImGuiKey.S)) + } + if (Gui.IsKeyDown(ImGuiKey.S)) + { movement -= forward; - if (Ui.IsKeyDown(ImGuiKey.D)) + } + if (Gui.IsKeyDown(ImGuiKey.D)) + { movement += right; - if (Ui.IsKeyDown(ImGuiKey.A)) + } + if (Gui.IsKeyDown(ImGuiKey.A)) + { movement -= right; - if (Ui.IsKeyDown(ImGuiKey.E)) + } + if (Gui.IsKeyDown(ImGuiKey.E)) + { movement += worldUp; - if (Ui.IsKeyDown(ImGuiKey.Q)) + } + if (Gui.IsKeyDown(ImGuiKey.Q)) + { movement -= worldUp; + } if (movement.LengthSquared() > 0.000001f) { float multiplier = io.shift ? GetPositive(profile.fastMovementMultiplier, 4f) : 1f; @@ -537,14 +896,18 @@ float aspect float zoomSensitivity = GetPositive(profile.zoomSensitivity, 0.16f); if (navigation.projection == EditorViewportProjection.Orthographic) { - Vector2 mouse = Ui.GetMousePos(); + Vector2 mouse = Gui.GetMousePos(); float normalizedX = Math.Clamp((mouse.X - minimum.X) / width, 0f, 1f); float normalizedY = Math.Clamp((mouse.Y - minimum.Y) / height, 0f, 1f); float previousSize = navigation.orthographicSize; EngineVector3 previousOffset = GetViewportOffset(normalizedX, normalizedY, previousSize, aspect, navigation.rotation); float minimumSize = GetPositive(profile.minimumOrthographicSize, 0.001f); float maximumSize = MathF.Max(minimumSize, GetPositive(profile.maximumOrthographicSize, 100000f)); - float nextSize = Math.Clamp(previousSize / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), minimumSize, maximumSize); + float nextSize = Math.Clamp( + previousSize / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), + minimumSize, + maximumSize + ); EngineVector3 nextOffset = GetViewportOffset(normalizedX, normalizedY, nextSize, aspect, navigation.rotation); EngineVector3 delta = previousOffset - nextOffset; navigation.position += delta; @@ -555,7 +918,11 @@ float aspect float minimumDistance = GetPositive(profile.minimumFocusDistance, 0.01f); float maximumDistance = MathF.Max(minimumDistance, GetPositive(profile.maximumFocusDistance, 1000000f)); - navigation.focusDistance = Math.Clamp(navigation.focusDistance / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), minimumDistance, maximumDistance); + navigation.focusDistance = Math.Clamp( + navigation.focusDistance / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), + minimumDistance, + maximumDistance + ); EngineVector3 direction = EngineVector3.Transform(EngineVector3.FORWARD, navigation.rotation); navigation.position = navigation.pivot - direction * navigation.focusDistance; } @@ -580,7 +947,11 @@ EditorViewportFocusBounds focus { float halfFov = navigation.fieldOfView * MathF.PI / 360f; float distance = radius * padding / MathF.Max(0.001f, MathF.Tan(halfFov)); - navigation.focusDistance = Math.Clamp(distance, GetPositive(profile.minimumFocusDistance, 0.01f), GetPositive(profile.maximumFocusDistance, 1000000f)); + navigation.focusDistance = Math.Clamp( + distance, + GetPositive(profile.minimumFocusDistance, 0.01f), + GetPositive(profile.maximumFocusDistance, 1000000f) + ); } navigation.position = focus.center - forward * navigation.focusDistance; @@ -595,6 +966,7 @@ EditorViewportNavigationMode mode EditorViewportNavigationMode.Fly => profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), _ => (profile.capabilities & EditorViewportNavigationCapabilities.Planar) != 0 }; + private static EngineQuaternion ApplyConstrainedPitch( EngineQuaternion yawed, EngineVector3 right, @@ -607,11 +979,14 @@ float angle return MathF.Abs(EngineVector3.Dot(forward, worldUp)) < 0.999f ? candidate : yawed; } - private static EngineVector3 GetWorldUp(EditorViewportNavigationProfile profile) => profile.worldUp.LengthSquared() > 0.000001f ? profile.worldUp.normalized : EngineVector3.UP; + private static EngineVector3 GetWorldUp(EditorViewportNavigationProfile profile) + => profile.worldUp.LengthSquared() > 0.000001f ? profile.worldUp.normalized : EngineVector3.UP; + private static float GetPositive( float value, float fallback ) => float.IsFinite(value) && value > 0f ? value : fallback; + private static EngineVector3 GetViewportOffset( float normalizedX, float normalizedY, @@ -623,96 +998,7 @@ EngineQuaternion rotation return EngineVector3.Transform(local, rotation); } - private void DrawUnavailable( - Vector2 size, - string message - ) { - Vector2 minimum = Ui.GetCursorScreenPosition(); - Vector2 maximum = minimum + size; - EditorDrawList drawList = Ui.GetDrawList(); - Ui.DrawFilledRectangle(minimum, maximum, Ui.ToPackedColor(m_backgroundColor), 0); - Ui.PushStyleColor(ImGuiCol.Text, EditorPalette.textDisabled); - try - { - EditorUI.current.widgets.CenteredWrappedText(message, size, S_UNAVAILABLE_PADDING); - } - finally - { - Ui.PopStyleColor(); - } - } - - private static Inno.Core.Mathematics.Color ToEngineColor(Vector4 value) => new(value.X, value.Y, value.Z, value.W); - private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) - { - EditorDrawList drawList = Ui.GetDrawList(); - Vector4 background = EditorPalette.targetHeader; - background.W = EditorPalette.opacityMedium; - Ui.DrawFilledRectangle(layout.minimum, layout.maximum, Ui.ToPackedColor(background), EditorUI.current.widgets.style.frameRounding); - float itemX = layout.minimum.X + layout.padding; - float itemY = layout.minimum.Y + layout.padding; - try - { - if (DrawManipulationTool("move", ImGuiIcon.UpDownLeftRight, "Move", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Translate)) - { - m_operation = ImGuizmoOperation.Translate; - } - - itemY += layout.itemSize.Y + layout.spacing; - if (DrawManipulationTool("rotate", ImGuiIcon.Rotate, "Rotate", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Rotate)) - { - m_operation = ImGuizmoOperation.Rotate; - } - - itemY += layout.itemSize.Y + layout.spacing; - if (DrawManipulationTool("scale", ImGuiIcon.UpRightAndDownLeftFromCenter, "Scale", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Scale)) - { - m_operation = ImGuizmoOperation.Scale; - } - - itemY += layout.itemSize.Y + layout.sectionSpacing; - float separatorY = itemY - layout.sectionSpacing * 0.5f; - Ui.DrawLine( - new Vector2(layout.minimum.X + layout.padding, separatorY), - new Vector2(layout.maximum.X - layout.padding, separatorY), - Ui.ToPackedColor(Vector4.One), - EditorUI.current.widgets.style.borderSize - ); - bool supportsCoordinateSpace = m_operation != ImGuizmoOperation.Scale; - string modeIcon = supportsCoordinateSpace && m_mode == ImGuizmoMode.World ? ImGuiIcon.Globe : ImGuiIcon.Cube; - string modeTooltip = !supportsCoordinateSpace ? "Coordinate Space: Local (Scale is always local)" : m_mode == ImGuizmoMode.Local ? "Coordinate Space: Local (axes follow the selected transform)" : "Coordinate Space: World (axes follow the world)"; - if (!supportsCoordinateSpace) - Ui.BeginDisabled(true); - bool toggleCoordinateSpace; - try - { - toggleCoordinateSpace = DrawManipulationTool("coordinate_space", modeIcon, modeTooltip, new Vector2(itemX, itemY), layout.itemSize, selected: false); - } - finally - { - if (!supportsCoordinateSpace) - Ui.EndDisabled(); - } - - if (!supportsCoordinateSpace && Ui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled) && EditorUI.current.widgets.BeginMenuTooltip()) - { - Ui.Text(modeTooltip); - EditorUI.current.widgets.EndMenuTooltip(); - } - - if (toggleCoordinateSpace && supportsCoordinateSpace) - { - m_mode = m_mode == ImGuizmoMode.Local ? ImGuizmoMode.World : ImGuizmoMode.Local; - } - } - finally - { - Ui.SetCursorScreenPosition(layout.viewportMaximum); - Ui.Dummy(Vector2.Zero); - } - - return IsManipulationToolbarHovered(layout); - } + private static EngineColor ToEngineColor(Vector4 value) => new(value.X, value.Y, value.Z, value.W); private static bool DrawManipulationTool( string id, @@ -722,9 +1008,11 @@ private static bool DrawManipulationTool( Vector2 size, bool selected ) { - Ui.SetCursorScreenPosition(position); + Gui.SetCursorScreenPosition(position); if (selected) - Ui.PushStyleColor(ImGuiCol.Text, Vector4.One); + { + Gui.PushStyleColor(ImGuiCol.Text, Vector4.One); + } bool pressed; try { @@ -733,15 +1021,17 @@ bool selected finally { if (selected) - Ui.PopStyleColor(); + { + Gui.PopStyleColor(); + } } if (selected) { - Vector2 minimum = Ui.GetItemMinimum(); - Vector2 maximum = Ui.GetItemMaximum(); + Vector2 minimum = Gui.GetItemMinimum(); + Vector2 maximum = Gui.GetItemMaximum(); float thickness = EditorUI.current.widgets.style.interactionOverlayThickness; - Ui.DrawFilledRectangle(minimum, new Vector2(minimum.X + thickness, maximum.Y), Ui.ToPackedColor(Vector4.One), 0); + Gui.DrawFilledRectangle(minimum, new Vector2(minimum.X + thickness, maximum.Y), Gui.ToPackedColor(Vector4.One), 0); } return pressed; @@ -756,8 +1046,8 @@ Vector2 viewportMaximum float padding = 4f * zoom; float spacing = 2f * zoom; float sectionSpacing = 8f * zoom; - float itemExtent = MathF.Max(Ui.GetFrameHeight(), 26f * zoom); - Vector2 itemSize = new(itemExtent); + float itemExtent = MathF.Max(Gui.GetFrameHeight(), 26f * zoom); + var itemSize = new Vector2(itemExtent); float width = itemExtent + padding * 2f; float height = padding * 2f + itemExtent * C_MANIPULATION_TOOL_COUNT + spacing * 2f + sectionSpacing; Vector2 minimum = viewportMinimum + new Vector2(inset); @@ -779,127 +1069,21 @@ Vector2 viewportMaximum return new ManipulationToolbarLayout(minimum, maximum, viewportMaximum, itemSize, padding, spacing, sectionSpacing); } - private static bool IsManipulationToolbarHovered(ManipulationToolbarLayout layout) => Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) - && Ui.IsMouseHoveringRect( - layout.minimum, - layout.maximum - ); - private bool DrawTransformGizmo( - Vector2 minimum, - Vector2 maximum, - bool canInteract - ) { - if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace manipulationSpace) || !TryGetSelectedTransform(out Transform? selected)) - { - return false; - } - - if (m_gestureTarget is not null && !EditorUI.current.widgets.IsEditing(C_TRANSFORM_EDIT)) - { - m_gestureTarget = null; - m_gestureTargets = []; - } - - Transform target = m_gestureTarget is RuntimeIdentity identity - && m_interactions.TryResolveIdentity( - identity, - out IdentityObject? resolved - ) - && resolved is Transform active ? active : selected!; - EngineMatrix world = target.localToWorldMatrix; - ImGuizmoOperation operation = SelectManipulationOperation(manipulationSpace.plane, m_operation); - bool planarTranslation = manipulationSpace.plane != EditorViewportManipulationPlane.Spatial && m_operation == ImGuizmoOperation.Translate; - TransformGizmoResult result = EditorUI.current.widgets.TransformGizmo( - world, - new TransformGizmoOptions { - minimum = minimum, - maximum = maximum, - view = manipulationSpace.viewMatrix, - projection = manipulationSpace.projectionMatrix, - orthographic = manipulationSpace.isOrthographic, - enabled = canInteract || m_gestureTarget is not null, - operation = operation, - space = m_operation == ImGuizmoOperation.Scale ? ImGuizmoMode.Local : m_mode, - maskX = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.YZ, - maskY = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.XZ, - maskZ = planarTranslation && manipulationSpace.plane == EditorViewportManipulationPlane.XY - } - ); - if (Ui.IsKeyPressed(ImGuiKey.Escape, false) && m_gestureTarget is not null) - { - EditorUI.current.widgets.CancelEdits(); - m_gestureTarget = null; - m_gestureTargets = []; - return true; - } - - if (result.isUsing) - { - if (m_gestureTarget is null) - { - m_gestureTarget = target.identity.runtimeIdentity; - m_gestureTargets = SelectedTransforms().Select(value => value.identity.runtimeIdentity!.Value).ToArray(); - } - - EditorUI.current.widgets.BeginEdit(m_interactions.history, C_TRANSFORM_EDIT, "Transform Selection"); - } - - if (result.changed && m_gestureTargets.Length != 0) - { - try - { - EngineMatrix delta = result.matrix * EngineMatrix.Invert(world); - foreach (RuntimeIdentity current in m_gestureTargets) - { - if (!m_interactions.TryResolveIdentity(current, out IdentityObject? value) || value is not Transform transform) - throw new InvalidOperationException("A transform gesture target is no longer available."); - EngineMatrix next = delta * transform.localToWorldMatrix; - if (!TryReadManipulatedTransform(next, transform, m_operation, out var position, out var rotation, out var scale) || !IsUsable(position, rotation, scale)) - throw new InvalidOperationException("The manipulated transform is not invertible or finite."); - _ = m_sceneEdits.ChangeProperty( - transform, - nameof(Transform.localPosition), - () => transform.SetWorldTransform(position, rotation, scale), - "Transform Selection", - EditorUI.current.widgets.editMergeKey - ); - } - } - catch - { - EditorUI.current.widgets.CancelEdits(); - m_gestureTarget = null; - m_gestureTargets = []; - throw; - } - } - - if (!result.isUsing && m_gestureTarget is not null) - CommitGesture(); - return result.isUsing || result.isOver; - } - - private Transform[] SelectedTransforms() - { - var selected = new List(); - m_interactions.selection.CopyTargets(selected); - Transform[] transforms = selected.Select(value => value switch - { - GameObject gameObject => gameObject.transform, - GameComponent component => component.transform, - _ => null - }).OfType().Distinct().ToArray(); - var set = transforms.ToHashSet(); - return transforms.Where(value => !HasSelectedAncestor(value, set)).ToArray(); - } + private static bool IsManipulationToolbarHovered(ManipulationToolbarLayout layout) + => Gui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) + && Gui.IsMouseHoveringRect(layout.minimum, layout.maximum); private static bool HasSelectedAncestor( Transform transform, ISet selected ) { for (Transform? parent = transform.parent; parent is not null; parent = parent.parent) + { if (selected.Contains(parent)) + { return true; + } + } return false; } @@ -918,23 +1102,26 @@ ImGuizmoOperation operation }, _ => operation }; + private static bool TryReadManipulatedTransform( EngineMatrix matrix, Transform target, ImGuizmoOperation operation, - out Inno.Core.Mathematics.Vector3 position, + out EngineVector3 position, out EngineQuaternion rotation, - out Inno.Core.Mathematics.Vector3 scale + out EngineVector3 scale ) { - position = new Inno.Core.Mathematics.Vector3(matrix.m14, matrix.m24, matrix.m34); + position = new EngineVector3(matrix.m14, matrix.m24, matrix.m34); rotation = target.worldRotation; scale = target.worldScale; if (operation == ImGuizmoOperation.Translate) + { return true; + } if (operation == ImGuizmoOperation.Scale) { EngineMatrix original = target.localToWorldMatrix; - scale = new Inno.Core.Mathematics.Vector3( + scale = new EngineVector3( scale.x * SignedColumnRatio(original.m11, original.m21, original.m31, matrix.m11, matrix.m21, matrix.m31), scale.y * SignedColumnRatio(original.m12, original.m22, original.m32, matrix.m12, matrix.m22, matrix.m32), scale.z * SignedColumnRatio(original.m13, original.m23, original.m33, matrix.m13, matrix.m23, matrix.m33) @@ -943,8 +1130,10 @@ out Inno.Core.Mathematics.Vector3 scale } if (MathF.Abs(scale.x) <= 0.00001f || MathF.Abs(scale.y) <= 0.00001f || MathF.Abs(scale.z) <= 0.00001f) + { return false; - EngineMatrix normalized = new( + } + var normalized = new EngineMatrix( matrix.m11 / scale.x, matrix.m12 / scale.y, matrix.m13 / scale.z, @@ -978,45 +1167,24 @@ float changedZ return squaredLength <= 0.0000000001f ? 1f : (originalX * changedX + originalY * changedY + originalZ * changedZ) / squaredLength; } - private bool TryGetSelectedTransform(out Transform? transform) - { - transform = m_interactions.selection.selectedTarget switch - { - GameObject gameObject when !gameObject.isDestroyed => gameObject.transform, - Transform selectedTransform when !selectedTransform.isDestroyed => selectedTransform, - GameComponent component when !component.isDestroyed => component.transform, - _ => null - }; - return transform is not null && m_sceneEdits.CanEdit(transform); - } - - private void CommitGesture() - { - if (m_gestureTarget is null) - return; - if (EditorUI.current.widgets.IsEditing(C_TRANSFORM_EDIT)) - EditorUI.current.widgets.CommitEdits(); - m_gestureTarget = null; - m_gestureTargets = []; - } - private static bool IsUsable( - Inno.Core.Mathematics.Vector3 position, + EngineVector3 position, EngineQuaternion rotation, - Inno.Core.Mathematics.Vector3 scale + EngineVector3 scale ) => float.IsFinite(position.x) - && float.IsFinite(position.y) - && float.IsFinite(position.z) - && float.IsFinite(rotation.x) - && float.IsFinite(rotation.y) - && float.IsFinite(rotation.z) - && float.IsFinite(rotation.w) - && float.IsFinite(scale.x) - && float.IsFinite(scale.y) - && float.IsFinite(scale.z) - && MathF.Abs(scale.x) > 0.00001f - && MathF.Abs(scale.y) > 0.00001f - && MathF.Abs(scale.z) > 0.00001f; + && float.IsFinite(position.y) + && float.IsFinite(position.z) + && float.IsFinite(rotation.x) + && float.IsFinite(rotation.y) + && float.IsFinite(rotation.z) + && float.IsFinite(rotation.w) + && float.IsFinite(scale.x) + && float.IsFinite(scale.y) + && float.IsFinite(scale.z) + && MathF.Abs(scale.x) > 0.00001f + && MathF.Abs(scale.y) > 0.00001f + && MathF.Abs(scale.z) > 0.00001f; + private readonly record struct ManipulationToolbarLayout( Vector2 minimum, Vector2 maximum, @@ -1026,6 +1194,7 @@ private readonly record struct ManipulationToolbarLayout( float spacing, float sectionSpacing ); + private enum NavigationDrag { None, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs new file mode 100644 index 000000000..b7862e9f1 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs @@ -0,0 +1,255 @@ +using System; +using Inno.Build; +using Inno.Build.Managed; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Panel.Settings; + +internal sealed class BuildSettingsField +{ + private const int C_TEXT_CAPACITY = 4096; + + internal BuildSettingsField( + BuildSettingsKey key, + string path, + string section, + string description + ) { + this.key = key; + this.path = path; + this.pagePath = path[..path.LastIndexOf('/')]; + this.label = path[(path.LastIndexOf('/') + 1)..]; + this.section = section; + this.description = description; + } + + internal BuildSettingsKey key { get; } + internal string path { get; } + internal string pagePath { get; } + internal string label { get; } + internal string section { get; } + internal string description { get; } + + internal bool Draw( + BuildSettings settings, + BuildPipeline buildPipeline + ) => key switch + { + BuildSettingsKey.GameProductName => DrawTextValue(settings.gameProductName, value => settings.gameProductName = value), + BuildSettingsKey.GamePersistentDataPath => DrawTextValue( + settings.gamePersistentDataPath, + value => settings.gamePersistentDataPath = value + ), + BuildSettingsKey.GameStartupScene => DrawTextValue(settings.gameStartupScene, value => settings.gameStartupScene = value), + BuildSettingsKey.GameWindowWidth => DrawPositiveInt(settings.gameWindowWidth, value => settings.gameWindowWidth = value), + BuildSettingsKey.GameWindowHeight => DrawPositiveInt(settings.gameWindowHeight, value => settings.gameWindowHeight = value), + BuildSettingsKey.GameTarget => DrawTarget(settings, buildPipeline), + BuildSettingsKey.GameManagedDeployment => DrawManagedDeployment(settings, buildPipeline), + BuildSettingsKey.GameOutputDirectory => DrawTextValue(settings.gameOutputDirectory, value => settings.gameOutputDirectory = value), + BuildSettingsKey.PluginDisplayName => DrawTextValue(settings.pluginDisplayName, value => settings.pluginDisplayName = value), + BuildSettingsKey.PluginOutputPath => DrawTextValue(settings.pluginOutputPath, value => settings.pluginOutputPath = value), + BuildSettingsKey.IncludePluginDependencies => DrawIncludeDependencies(settings), + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + + internal bool IsDefault( + BuildSettings settings, + BuildSettings defaults + ) => key switch + { + BuildSettingsKey.GameProductName => settings.gameProductName == defaults.gameProductName, + BuildSettingsKey.GamePersistentDataPath => settings.gamePersistentDataPath == defaults.gamePersistentDataPath, + BuildSettingsKey.GameStartupScene => settings.gameStartupScene == defaults.gameStartupScene, + BuildSettingsKey.GameWindowWidth => settings.gameWindowWidth == defaults.gameWindowWidth, + BuildSettingsKey.GameWindowHeight => settings.gameWindowHeight == defaults.gameWindowHeight, + BuildSettingsKey.GameTarget => settings.gameTarget == defaults.gameTarget, + BuildSettingsKey.GameManagedDeployment => settings.gameManagedDeployment == defaults.gameManagedDeployment, + BuildSettingsKey.GameOutputDirectory => settings.gameOutputDirectory == defaults.gameOutputDirectory, + BuildSettingsKey.PluginDisplayName => settings.pluginDisplayName == defaults.pluginDisplayName, + BuildSettingsKey.PluginOutputPath => settings.pluginOutputPath == defaults.pluginOutputPath, + BuildSettingsKey.IncludePluginDependencies => settings.includePluginDependencies == defaults.includePluginDependencies, + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + + internal void Reset( + BuildSettings settings, + BuildSettings defaults + ) { + switch (key) + { + case BuildSettingsKey.GameProductName: + settings.gameProductName = defaults.gameProductName; + break; + case BuildSettingsKey.GamePersistentDataPath: + settings.gamePersistentDataPath = defaults.gamePersistentDataPath; + break; + case BuildSettingsKey.GameStartupScene: + settings.gameStartupScene = defaults.gameStartupScene; + break; + case BuildSettingsKey.GameWindowWidth: + settings.gameWindowWidth = defaults.gameWindowWidth; + break; + case BuildSettingsKey.GameWindowHeight: + settings.gameWindowHeight = defaults.gameWindowHeight; + break; + case BuildSettingsKey.GameManagedDeployment: + settings.gameManagedDeployment = defaults.gameManagedDeployment; + break; + case BuildSettingsKey.GameTarget: + settings.gameTarget = defaults.gameTarget; + break; + case BuildSettingsKey.GameOutputDirectory: + settings.gameOutputDirectory = defaults.gameOutputDirectory; + break; + case BuildSettingsKey.PluginDisplayName: + settings.pluginDisplayName = defaults.pluginDisplayName; + break; + case BuildSettingsKey.PluginOutputPath: + settings.pluginOutputPath = defaults.pluginOutputPath; + break; + case BuildSettingsKey.IncludePluginDependencies: + settings.includePluginDependencies = defaults.includePluginDependencies; + break; + default: + throw new InvalidOperationException($"Unknown Build Settings field '{key}'."); + } + } + + internal static bool ValuesEqual( + BuildSettings left, + BuildSettings right + ) => string.Equals(left.gameProductName, right.gameProductName, StringComparison.Ordinal) + && string.Equals(left.gamePersistentDataPath, right.gamePersistentDataPath, StringComparison.Ordinal) + && string.Equals(left.gameStartupScene, right.gameStartupScene, StringComparison.Ordinal) + && string.Equals(left.gameOutputDirectory, right.gameOutputDirectory, StringComparison.Ordinal) + && left.gameWindowWidth == right.gameWindowWidth + && left.gameWindowHeight == right.gameWindowHeight + && left.gameTarget == right.gameTarget + && left.gameManagedDeployment == right.gameManagedDeployment + && string.Equals(left.pluginDisplayName, right.pluginDisplayName, StringComparison.Ordinal) + && string.Equals(left.pluginOutputPath, right.pluginOutputPath, StringComparison.Ordinal) + && left.includePluginDependencies == right.includePluginDependencies; + + private static bool DrawTextValue( + string value, + Action apply + ) { + Gui.SetNextItemWidth(-1f); + if (!Gui.InputText("##value", ref value, C_TEXT_CAPACITY)) + { + return false; + } + apply(value); + return true; + } + + private static bool DrawPositiveInt( + int value, + Action apply + ) { + Gui.SetNextItemWidth(-1f); + if (!Gui.InputInt("##value", ref value, 1, 100, 0)) + { + return false; + } + apply(Math.Max(1, value)); + return true; + } + + private static bool DrawManagedDeployment( + BuildSettings settings, + BuildPipeline buildPipeline + ) { + bool changed = false; + Gui.SetNextItemWidth(-1f); + if (!EditorUI.current.widgets.BeginBoundedCombo("##value", settings.gameManagedDeployment?.value ?? "Platform default")) + { + return false; + } + try + { + if (Gui.Selectable("Platform default", settings.gameManagedDeployment is null)) + { + settings.gameManagedDeployment = null; + changed = true; + } + + foreach (ManagedDeploymentID deployment in buildPipeline.GetManagedDeployments(settings.gameTarget)) + { + if (!Gui.Selectable(deployment.value, settings.gameManagedDeployment == deployment)) + { + continue; + } + settings.gameManagedDeployment = deployment; + changed = true; + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + return changed; + } + + private static bool DrawTarget( + BuildSettings settings, + BuildPipeline buildPipeline + ) { + bool changed = false; + Gui.SetNextItemWidth(-1f); + if (!EditorUI.current.widgets.BeginBoundedCombo("##value", GetTargetLabel(settings.gameTarget, buildPipeline))) + { + return false; + } + try + { + foreach (BuildTargetID target in buildPipeline.availableGameTargets) + { + changed |= DrawTargetChoice(settings, target, buildPipeline); + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + return changed; + } + + private static bool DrawIncludeDependencies(BuildSettings settings) + { + bool value = settings.includePluginDependencies; + if (!Gui.Checkbox("##value", ref value)) + { + return false; + } + settings.includePluginDependencies = value; + return true; + } + + private static bool DrawTargetChoice( + BuildSettings settings, + BuildTargetID target, + BuildPipeline buildPipeline + ) { + bool selected = settings.gameTarget == target; + bool changed = Gui.Selectable(GetTargetLabel(target, buildPipeline), selected); + if (changed) + { + settings.gameTarget = target; + } + if (selected) + { + Gui.SetItemDefaultFocus(); + } + return changed; + } + + private static string GetTargetLabel( + BuildTargetID target, + BuildPipeline buildPipeline + ) => buildPipeline.TryGetGameTargetDisplayName(target, out string displayName) ? displayName : $"Missing ({target})"; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs index d5647db0a..7fb541719 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs @@ -1,275 +1,17 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; using System.Collections.Generic; -using Inno.Build; -using Inno.Build.Managed; -using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; -internal enum BuildSettingsKey -{ - GameProductName, - GamePersistentDataPath, - GameStartupScene, - GameWindowWidth, - GameWindowHeight, - GameTarget, - GameManagedDeployment, - GameOutputDirectory, - PluginDisplayName, - PluginOutputPath, - IncludePluginDependencies -} - -internal sealed class BuildSettingsField -{ - private const int C_TEXT_CAPACITY = 4096; - internal BuildSettingsField( - BuildSettingsKey key, - string path, - string section, - string description - ) { - this.key = key; - this.path = path; - pagePath = path[..path.LastIndexOf('/')]; - label = path[(path.LastIndexOf('/') + 1)..]; - this.section = section; - this.description = description; - } - - internal BuildSettingsKey key { get; } - internal string path { get; } - internal string pagePath { get; } - internal string label { get; } - internal string section { get; } - internal string description { get; } - - internal bool Draw( - BuildSettings settings, - BuildPipeline buildPipeline - ) => key switch - { - BuildSettingsKey.GameProductName => DrawTextValue(settings.gameProductName, value => settings.gameProductName = value), - BuildSettingsKey.GamePersistentDataPath => DrawTextValue(settings.gamePersistentDataPath, value => settings.gamePersistentDataPath = value), - BuildSettingsKey.GameStartupScene => DrawTextValue(settings.gameStartupScene, value => settings.gameStartupScene = value), - BuildSettingsKey.GameWindowWidth => DrawPositiveInt(settings.gameWindowWidth, value => settings.gameWindowWidth = value), - BuildSettingsKey.GameWindowHeight => DrawPositiveInt(settings.gameWindowHeight, value => settings.gameWindowHeight = value), - BuildSettingsKey.GameTarget => DrawTarget(settings, buildPipeline), - BuildSettingsKey.GameManagedDeployment => DrawManagedDeployment(settings, buildPipeline), - BuildSettingsKey.GameOutputDirectory => DrawTextValue(settings.gameOutputDirectory, value => settings.gameOutputDirectory = value), - BuildSettingsKey.PluginDisplayName => DrawTextValue(settings.pluginDisplayName, value => settings.pluginDisplayName = value), - BuildSettingsKey.PluginOutputPath => DrawTextValue(settings.pluginOutputPath, value => settings.pluginOutputPath = value), - BuildSettingsKey.IncludePluginDependencies => DrawIncludeDependencies(settings), - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.")}; - internal bool IsDefault( - BuildSettings settings, - BuildSettings defaults - ) => key switch - { - BuildSettingsKey.GameProductName => settings.gameProductName == defaults.gameProductName, - BuildSettingsKey.GamePersistentDataPath => settings.gamePersistentDataPath == defaults.gamePersistentDataPath, - BuildSettingsKey.GameStartupScene => settings.gameStartupScene == defaults.gameStartupScene, - BuildSettingsKey.GameWindowWidth => settings.gameWindowWidth == defaults.gameWindowWidth, - BuildSettingsKey.GameWindowHeight => settings.gameWindowHeight == defaults.gameWindowHeight, - BuildSettingsKey.GameTarget => settings.gameTarget == defaults.gameTarget, - BuildSettingsKey.GameManagedDeployment => settings.gameManagedDeployment == defaults.gameManagedDeployment, - BuildSettingsKey.GameOutputDirectory => settings.gameOutputDirectory == defaults.gameOutputDirectory, - BuildSettingsKey.PluginDisplayName => settings.pluginDisplayName == defaults.pluginDisplayName, - BuildSettingsKey.PluginOutputPath => settings.pluginOutputPath == defaults.pluginOutputPath, - BuildSettingsKey.IncludePluginDependencies => settings.includePluginDependencies == defaults.includePluginDependencies, - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.")}; - internal void Reset( - BuildSettings settings, - BuildSettings defaults - ) { - switch (key) - { - case BuildSettingsKey.GameProductName: - settings.gameProductName = defaults.gameProductName; - break; - case BuildSettingsKey.GamePersistentDataPath: - settings.gamePersistentDataPath = defaults.gamePersistentDataPath; - break; - case BuildSettingsKey.GameStartupScene: - settings.gameStartupScene = defaults.gameStartupScene; - break; - case BuildSettingsKey.GameWindowWidth: - settings.gameWindowWidth = defaults.gameWindowWidth; - break; - case BuildSettingsKey.GameWindowHeight: - settings.gameWindowHeight = defaults.gameWindowHeight; - break; - case BuildSettingsKey.GameManagedDeployment: - settings.gameManagedDeployment = defaults.gameManagedDeployment; - break; - case BuildSettingsKey.GameTarget: - settings.gameTarget = defaults.gameTarget; - break; - case BuildSettingsKey.GameOutputDirectory: - settings.gameOutputDirectory = defaults.gameOutputDirectory; - break; - case BuildSettingsKey.PluginDisplayName: - settings.pluginDisplayName = defaults.pluginDisplayName; - break; - case BuildSettingsKey.PluginOutputPath: - settings.pluginOutputPath = defaults.pluginOutputPath; - break; - case BuildSettingsKey.IncludePluginDependencies: - settings.includePluginDependencies = defaults.includePluginDependencies; - break; - default: - throw new InvalidOperationException($"Unknown Build Settings field '{key}'."); - } - } - - internal static bool ValuesEqual( - BuildSettings left, - BuildSettings right - ) => string.Equals( - left.gameProductName, - right.gameProductName, - StringComparison.Ordinal - ) - && string.Equals( - left.gamePersistentDataPath, - right.gamePersistentDataPath, - StringComparison.Ordinal - ) - && string.Equals( - left.gameStartupScene, - right.gameStartupScene, - StringComparison.Ordinal - ) - && string.Equals( - left.gameOutputDirectory, - right.gameOutputDirectory, - StringComparison.Ordinal - ) - && left.gameWindowWidth == right.gameWindowWidth - && left.gameWindowHeight == right.gameWindowHeight - && left.gameTarget == right.gameTarget - && left.gameManagedDeployment == right.gameManagedDeployment - && string.Equals( - left.pluginDisplayName, - right.pluginDisplayName, - StringComparison.Ordinal - ) - && string.Equals( - left.pluginOutputPath, - right.pluginOutputPath, - StringComparison.Ordinal - ) - && left.includePluginDependencies == right.includePluginDependencies; - private static bool DrawTextValue( - string value, - Action apply - ) { - Ui.SetNextItemWidth(-1f); - if (!Ui.InputText("##value", ref value, C_TEXT_CAPACITY)) - return false; - apply(value); - return true; - } - - private static bool DrawPositiveInt( - int value, - Action apply - ) { - Ui.SetNextItemWidth(-1f); - if (!Ui.InputInt("##value", ref value, 1, 100, 0)) - return false; - apply(Math.Max(1, value)); - return true; - } - - private static bool DrawManagedDeployment( - BuildSettings settings, - BuildPipeline buildPipeline - ) { - bool changed = false; - Ui.SetNextItemWidth(-1f); - if (!EditorUI.current.widgets.BeginBoundedCombo("##value", settings.gameManagedDeployment?.value ?? "Platform default")) - return false; - try - { - if (Ui.Selectable("Platform default", settings.gameManagedDeployment is null)) - { - settings.gameManagedDeployment = null; - changed = true; - } - - foreach (ManagedDeploymentId deployment in buildPipeline.GetManagedDeployments(settings.gameTarget)) - { - if (!Ui.Selectable(deployment.value, settings.gameManagedDeployment == deployment)) - continue; - settings.gameManagedDeployment = deployment; - changed = true; - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - return changed; - } - - private static bool DrawTarget( - BuildSettings settings, - BuildPipeline buildPipeline - ) { - bool changed = false; - Ui.SetNextItemWidth(-1f); - if (!EditorUI.current.widgets.BeginBoundedCombo("##value", GetTargetLabel(settings.gameTarget, buildPipeline))) - return false; - try - { - foreach (BuildTargetId target in buildPipeline.availableGameTargets) - changed |= DrawTargetChoice(settings, target, buildPipeline); - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - return changed; - } - - private static bool DrawIncludeDependencies(BuildSettings settings) - { - bool value = settings.includePluginDependencies; - if (!Ui.Checkbox("##value", ref value)) - return false; - settings.includePluginDependencies = value; - return true; - } - - private static bool DrawTargetChoice( - BuildSettings settings, - BuildTargetId target, - BuildPipeline buildPipeline - ) { - bool selected = settings.gameTarget == target; - bool changed = Ui.Selectable(GetTargetLabel(target, buildPipeline), selected); - if (changed) - settings.gameTarget = target; - if (selected) - Ui.SetItemDefaultFocus(); - return changed; - } - - private static string GetTargetLabel( - BuildTargetId target, - BuildPipeline buildPipeline - ) => buildPipeline.TryGetGameTargetDisplayName(target, out string displayName) ? displayName : $"Missing ({target})"; -} internal static class BuildSettingsPresentation { - internal static IReadOnlyList fields { get; } = [ - new BuildSettingsField(BuildSettingsKey.GameProductName, "Build/Game/Product Name", "Game Export Defaults", "Player-facing product name copied into each game export."), + internal static IReadOnlyList fields { get; } = + [ + new BuildSettingsField( + BuildSettingsKey.GameProductName, + "Build/Game/Product Name", + "Game Export Defaults", + "Player-facing product name copied into each game export." + ), new BuildSettingsField( BuildSettingsKey.GamePersistentDataPath, "Build/Game/Persistent Data Folder", @@ -282,9 +24,24 @@ internal static class BuildSettingsPresentation "Game Export Defaults", "Mount-qualified Scene path loaded when the exported Player starts." ), - new BuildSettingsField(BuildSettingsKey.GameWindowWidth, "Build/Game/Initial Window Width", "Game Export Defaults", "Initial logical Player window width."), - new BuildSettingsField(BuildSettingsKey.GameWindowHeight, "Build/Game/Initial Window Height", "Game Export Defaults", "Initial logical Player window height."), - new BuildSettingsField(BuildSettingsKey.GameTarget, "Build/Game/Target", "Game Export Defaults", "Platform target selected when the game export window opens."), + new BuildSettingsField( + BuildSettingsKey.GameWindowWidth, + "Build/Game/Initial Window Width", + "Game Export Defaults", + "Initial logical Player window width." + ), + new BuildSettingsField( + BuildSettingsKey.GameWindowHeight, + "Build/Game/Initial Window Height", + "Game Export Defaults", + "Initial logical Player window height." + ), + new BuildSettingsField( + BuildSettingsKey.GameTarget, + "Build/Game/Target", + "Game Export Defaults", + "Platform target selected when the game export window opens." + ), new BuildSettingsField( BuildSettingsKey.GameManagedDeployment, "Build/Game/Managed Deployment", @@ -317,3 +74,18 @@ internal static class BuildSettingsPresentation ) ]; } + +internal enum BuildSettingsKey +{ + GameProductName, + GamePersistentDataPath, + GameStartupScene, + GameWindowWidth, + GameWindowHeight, + GameTarget, + GameManagedDeployment, + GameOutputDirectory, + PluginDisplayName, + PluginOutputPath, + IncludePluginDependencies +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs index 97ebdacc5..e42b4b035 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs @@ -1,20 +1,24 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Settings; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; + using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Panel.Settings; + [ProjectSettingPath("Project/Identity/Project ID")] internal sealed class ProjectIdentitySettingsEditor : ProjectSettingEditor { private string m_error = string.Empty; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Identity"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -43,6 +47,8 @@ protected override void OnDraw(ProjectIdentitySettings setting) } if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs index 38b33cbd6..a9b9a0929 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs @@ -1,15 +1,17 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Numerics; +using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; -using Inno.Core.Logging; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + [EditorModal("editor.settings", "Settings", order: 100)] internal sealed class SettingsModal( EditorSettings editorSettings, @@ -20,31 +22,37 @@ LogRouter logs { private readonly SettingsNavigation m_navigation = new(); private readonly SettingsTree m_tree = new(); + private readonly Logger m_log = logs.CreateLogger(); private long m_navigationRevision = -1; private string m_query = string.Empty; private float m_treePaneRatio = 0.25f; - private readonly Logger m_log = logs.CreateLogger(); private string m_applyError = string.Empty; + /// /// Gets whether this implementation is visible. /// public override bool isVisible => window.isVisible; + /// /// Gets whether this implementation can move. /// public override bool canMove => true; + /// /// Gets whether this implementation can resize. /// public override bool canResize => true; + /// /// Lets the navigation tree and current settings page own their scrolling. /// public override bool allowScrolling => false; + /// /// Gets the preferred initial window size in logical editor units. /// public override Vector2 initialSize => new(1050f, 700f); + /// /// Gets the smallest editor window size that keeps every setting control usable. /// @@ -80,13 +88,18 @@ private void DrawWindow() { SettingsEditSession? session = window.session; if (session is null) - return; - if (session.editorCatalogRevision != editorSettings.catalogRevision || session.projectCatalogRevision != projectSettings.catalogRevision) { + return; + } + if (session.editorCatalogRevision != editorSettings.catalogRevision + || session.projectCatalogRevision != projectSettings.catalogRevision + ) { window.Refresh(); session = window.session; if (session is null) + { return; + } } IReadOnlyList pages = session.pages; @@ -94,20 +107,28 @@ private void DrawWindow() SettingsPage? selected = SettingsTree.FindPage(pages, m_navigation.currentPath); selected ??= SettingsTree.FindFirstMatch(pages, m_query); if (selected is not null) + { m_navigation.Replace(selected.path); - float footerHeight = Ui.GetFrameHeightWithSpacing() + Ui.GetLayout().itemSpacing.Y; + } + float footerHeight = Gui.GetFrameHeightWithSpacing() + Gui.GetLayout().itemSpacing.Y; if (m_applyError.Length != 0) - footerHeight += Ui.GetFrameHeightWithSpacing(); - Vector2 available = Ui.GetContentRegionAvailable(); + { + footerHeight += Gui.GetFrameHeightWithSpacing(); + } + Vector2 available = Gui.GetContentRegionAvailable(); DrawBody(session, pages, new Vector2(available.X, MathF.Max(1f, available.Y - footerHeight))); - Ui.Separator(); + Gui.Separator(); if (m_applyError.Length != 0) { - EditorUiSession.current.widgets.ColoredText(EditorPalette.error, - session.isHistoryFaulted ? "History integrity was lost. Restart the Editor." - : session.canApply ? "Apply failed. Edits remain staged; retry or Cancel." - : "Settings recovery is required. See Console for details."); - EditorUiSession.current.widgets.DrawItemTooltip(m_applyError); + EditorUISession.current.widgets.ColoredText( + EditorPalette.error, + session.isHistoryFaulted + ? "History integrity was lost. Restart the Editor." + : session.canApply + ? "Apply failed. Edits remain staged; retry or Cancel." + : "Settings recovery is required. See Console for details." + ); + EditorUISession.current.widgets.DrawItemTooltip(m_applyError); } DrawButtons(session); } @@ -117,33 +138,42 @@ private void DrawBody( IReadOnlyList pages, Vector2 size ) { - ImGuiTableFlags flags = ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoKeepColumnsVisible | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoSavedSettings; - float splitterWidth = MathF.Max(5f * EditorUiSession.current.widgets.style.zoom, Ui.GetLayout().dockingSeparatorSize); + ImGuiTableFlags flags = ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoKeepColumnsVisible + | ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoSavedSettings; + float splitterWidth = MathF.Max(5f * EditorUISession.current.widgets.style.zoom, Gui.GetLayout().dockingSeparatorSize); float treeWidth = ResolveTreeWidth(size.X, splitterWidth); - Ui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); + Gui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); bool tableStarted = false; try { - tableStarted = Ui.BeginTable("##settings_split", 3, flags, size); + tableStarted = Gui.BeginTable("##settings_split", 3, flags, size); if (tableStarted) { - Ui.TableSetupColumn("##settings_tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); - Ui.TableSetupColumn("##settings_splitter", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), splitterWidth); - Ui.TableSetupColumn("##settings_page", ImGuiTableColumnFlags.WidthStretch); - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); + Gui.TableSetupColumn("##settings_tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); + Gui.TableSetupColumn( + "##settings_splitter", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + splitterWidth + ); + Gui.TableSetupColumn("##settings_page", ImGuiTableColumnFlags.WidthStretch); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); DrawTreePane(pages, size.Y); - _ = Ui.TableSetColumnIndex(1); + _ = Gui.TableSetColumnIndex(1); DrawSplitter(splitterWidth, size.X, treeWidth, size.Y); - _ = Ui.TableSetColumnIndex(2); + _ = Gui.TableSetColumnIndex(2); DrawPagePane(session, pages, size.Y); } } finally { if (tableStarted) - Ui.EndTable(); - Ui.PopStyleVar(); + { + Gui.EndTable(); + } + Gui.PopStyleVar(); } } @@ -151,7 +181,7 @@ private void DrawTreePane( IReadOnlyList pages, float height ) { - bool visible = Ui.BeginChild( + bool visible = Gui.BeginChild( "##settings_tree_pane", new Vector2(0f, height), (ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding), @@ -160,21 +190,27 @@ float height try { if (!visible) + { return; + } DrawNavigationButtons(); - Ui.SameLine(0f, EditorUiSession.current.widgets.style.toolbarSectionSpacing); + Gui.SameLine(0f, EditorUISession.current.widgets.style.toolbarSectionSpacing); bool wasSearching = !string.IsNullOrWhiteSpace(m_query); - Ui.SetNextItemWidth(-1f); - bool queryChanged = EditorUiSession.current.widgets.SearchInput("settings", "Search settings", ref m_query, width: -1f); + Gui.SetNextItemWidth(-1f); + bool queryChanged = EditorUISession.current.widgets.SearchInput("settings", "Search settings", ref m_query, width: -1f); if (queryChanged) { SettingsPage? first = SettingsTree.FindFirstMatch(pages, m_query); if (first is not null) { if (wasSearching) + { m_navigation.Replace(first.path); + } else + { m_navigation.NavigateTo(first.path); + } } else { @@ -182,8 +218,8 @@ float height } } - Ui.Separator(); - bool scrollVisible = Ui.BeginChild("##settings_tree_scroll", Vector2.Zero, 0, 0); + Gui.Separator(); + bool scrollVisible = Gui.BeginChild("##settings_tree_scroll", Vector2.Zero, 0, 0); try { if (scrollVisible) @@ -193,12 +229,12 @@ float height } finally { - Ui.EndChild(); + Gui.EndChild(); } } finally { - Ui.EndChild(); + Gui.EndChild(); } } @@ -207,11 +243,17 @@ private void DrawPagePane( IReadOnlyList pages, float height ) { - bool visible = Ui.BeginChild("##settings_page_pane", new Vector2(0f, height), (ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding)); + bool visible = Gui.BeginChild( + "##settings_page_pane", + new Vector2(0f, height), + (ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding) + ); try { if (!visible) + { return; + } SettingsPage? page = SettingsTree.FindPage(pages, m_navigation.currentPath); if (page is not null) { @@ -224,12 +266,12 @@ float height } else { - Ui.Text("No matching settings"); + Gui.Text("No matching settings"); } } finally { - Ui.EndChild(); + Gui.EndChild(); } } @@ -239,28 +281,37 @@ private void DrawSplitter( float treeWidth, float height ) { - _ = Ui.InvisibleButton("##settings_tree_splitter_grip", new Vector2(width, MathF.Max(1f, height))); - bool hovered = Ui.IsItemHovered(); - bool active = Ui.IsItemActive(); + _ = Gui.InvisibleButton("##settings_tree_splitter_grip", new Vector2(width, MathF.Max(1f, height))); + bool hovered = Gui.IsItemHovered(); + bool active = Gui.IsItemActive(); if (hovered || active) - Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + { + Gui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (active) { - Vector2 delta = Ui.GetMouseDragDelta(ImGuiMouseButton.Left); + Vector2 delta = Gui.GetMouseDragDelta(ImGuiMouseButton.Left); if (MathF.Abs(delta.X) > 0f) { float usable = MathF.Max(0f, availableWidth - width); float requested = ClampTreeWidth(treeWidth + delta.X, usable); m_treePaneRatio = usable > float.Epsilon ? Math.Clamp(requested / usable, 0f, 1f) : 0.25f; - Ui.ResetMouseDragDelta(ImGuiMouseButton.Left); + Gui.ResetMouseDragDelta(ImGuiMouseButton.Left); } } - Vector2 minimum = Ui.GetItemMinimum(); - Vector2 maximum = Ui.GetItemMaximum(); - System.Numerics.Vector4 color = active ? EditorPalette.contentAccent : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; + Vector2 minimum = Gui.GetItemMinimum(); + Vector2 maximum = Gui.GetItemMaximum(); + Vector4 color = active + ? EditorPalette.contentAccent + : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; float centerX = (minimum.X + maximum.X) * 0.5f; - Ui.DrawLine(new Vector2(centerX, minimum.Y), new Vector2(centerX, maximum.Y), Ui.ToPackedColor(color), EditorUiSession.current.widgets.style.borderSize); + Gui.DrawLine( + new Vector2(centerX, minimum.Y), + new Vector2(centerX, maximum.Y), + Gui.ToPackedColor(color), + EditorUISession.current.widgets.style.borderSize + ); } private float ResolveTreeWidth( @@ -271,38 +322,33 @@ float splitterWidth return ClampTreeWidth(usable * Math.Clamp(m_treePaneRatio, 0f, 1f), usable); } - private static float ClampTreeWidth( - float requested, - float usable - ) { - float minimum = MathF.Min(EditorUiSession.current.widgets.style.paneMinimumVisibleWidth, usable * 0.5f); - float maximum = MathF.Max(minimum, usable - minimum); - return Math.Clamp(requested, minimum, maximum); - } - private void DrawButtons(SettingsEditSession session) { - EditorUiLayout style = Ui.GetLayout(); + EditorUILayout style = Gui.GetLayout(); if (!session.isDirty) { - float okWidth = Ui.MeasureText("OK").X + style.framePadding.X * 2f; - Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - okWidth)); - if (Ui.Button("OK")) + float okWidth = Gui.MeasureText("OK").X + style.framePadding.X * 2f; + Gui.SetCursorPosX(Gui.GetCursorPosX() + MathF.Max(0f, Gui.GetContentRegionAvailable().X - okWidth)); + if (Gui.Button("OK")) + { TryClose(); + } return; } - float cancelWidth = Ui.MeasureText("Cancel").X + style.framePadding.X * 2f; - float applyWidth = Ui.MeasureText("Apply").X + style.framePadding.X * 2f; + float cancelWidth = Gui.MeasureText("Cancel").X + style.framePadding.X * 2f; + float applyWidth = Gui.MeasureText("Apply").X + style.framePadding.X * 2f; float totalWidth = cancelWidth + style.itemSpacing.X + applyWidth; - Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - totalWidth)); - if (Ui.Button("Cancel")) + Gui.SetCursorPosX(Gui.GetCursorPosX() + MathF.Max(0f, Gui.GetContentRegionAvailable().X - totalWidth)); + if (Gui.Button("Cancel")) + { TryClose(); - Ui.SameLine(0f, -1f); - Ui.BeginDisabled(!session.canApply); + } + Gui.SameLine(0f, -1f); + Gui.BeginDisabled(!session.canApply); try { - if (Ui.Button("Apply")) + if (Gui.Button("Apply")) { try { @@ -317,7 +363,7 @@ private void DrawButtons(SettingsEditSession session) } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } @@ -340,37 +386,48 @@ private void ReportFailure(Exception failure) m_log.Write(LogLevel.Error, "Settings operation failed; edits and History ownership were retained: {0}", [failure]); } - private static bool IsOperationalFailure(Exception failure) - => failure is IOException or UnauthorizedAccessException or ArgumentException or InvalidOperationException or AggregateException; - private void DrawNavigationButtons() { - float frameHeight = Ui.GetFrameHeight(); + float frameHeight = Gui.GetFrameHeight(); var buttonSize = new Vector2(frameHeight, frameHeight); - Ui.BeginDisabled(!m_navigation.canGoBack); - if (Ui.Button($"{Inno.Editor.ImGui.ImGuiIcon.AngleLeft}##SettingsBack", buttonSize)) + Gui.BeginDisabled(!m_navigation.canGoBack); + if (Gui.Button($"{ImGuiIcon.C_ANGLE_LEFT}##SettingsBack", buttonSize)) { m_navigation.GoBack(); } - Ui.EndDisabled(); - Ui.SameLine(0f, EditorUiSession.current.widgets.style.toolbarTightSpacing); - Ui.BeginDisabled(!m_navigation.canGoForward); - if (Ui.Button($"{Inno.Editor.ImGui.ImGuiIcon.AngleRight}##SettingsForward", buttonSize)) + Gui.EndDisabled(); + Gui.SameLine(0f, EditorUISession.current.widgets.style.toolbarTightSpacing); + Gui.BeginDisabled(!m_navigation.canGoForward); + if (Gui.Button($"{ImGuiIcon.C_ANGLE_RIGHT}##SettingsForward", buttonSize)) { m_navigation.GoForward(); } - Ui.EndDisabled(); + Gui.EndDisabled(); } private void EnsureNavigationSession(IReadOnlyList pages) { if (m_navigationRevision == window.sessionRevision) + { return; + } m_navigationRevision = window.sessionRevision; m_applyError = string.Empty; SettingsPage? first = SettingsTree.FindFirstMatch(pages, m_query); m_navigation.Reset(first?.path ?? string.Empty); } + + private static float ClampTreeWidth( + float requested, + float usable + ) { + float minimum = MathF.Min(EditorUISession.current.widgets.style.paneMinimumVisibleWidth, usable * 0.5f); + float maximum = MathF.Max(minimum, usable - minimum); + return Math.Clamp(requested, minimum, maximum); + } + + private static bool IsOperationalFailure(Exception failure) + => failure is IOException or UnauthorizedAccessException or ArgumentException or InvalidOperationException or AggregateException; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs index 9e4612e5e..4ba3e9f28 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs @@ -25,9 +25,13 @@ internal void NavigateTo(string path) { ArgumentNullException.ThrowIfNull(path); if (string.Equals(currentPath, path, StringComparison.Ordinal)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_back.Push(currentPath); + } currentPath = path; m_forward.Clear(); } @@ -41,18 +45,26 @@ internal void Replace(string path) internal void GoBack() { if (!m_back.TryPop(out string? path)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_forward.Push(currentPath); + } currentPath = path; } internal void GoForward() { if (!m_forward.TryPop(out string? path)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_back.Push(currentPath); + } currentPath = path; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs index bda719e53..ad7149d2e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs @@ -1,102 +1,91 @@ -using System.Numerics; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + internal sealed class SettingsPageView(SettingsEditSession session) { - private static SettingsStyle settingsStyle => new(EditorUI.current.widgets.style); - internal void Draw( SettingsPage page, Action navigate ) { DrawPageHeader(page); - Ui.Spacing(); + Gui.Spacing(); PushDisabledText(); EditorUI.current.widgets.WrappedText(page.description); - Ui.PopStyleColor(); - Ui.Dummy(new System.Numerics.Vector2(0f, 16f * EditorUI.current.widgets.style.zoom)); + Gui.PopStyleColor(); + Gui.Dummy(new Vector2(0f, 16f * EditorUI.current.widgets.style.zoom)); if (page.children.Count != 0) { DrawOverview(page.children, navigate); - Ui.Dummy(new System.Numerics.Vector2(0f, 8f * EditorUI.current.widgets.style.zoom)); + Gui.Dummy(new Vector2(0f, 8f * EditorUI.current.widgets.style.zoom)); } if (!page.hasSettings) { if (page.children.Count == 0) + { DrawOverview(page.children, navigate); + } return; } int fieldIndex = 0; - foreach (IGrouping group in page.settings.GroupBy(static setting => setting.section ?? string.Empty, StringComparer.OrdinalIgnoreCase)) - { + foreach (IGrouping group in page.settings.GroupBy( + static setting => setting.section ?? string.Empty, + StringComparer.OrdinalIgnoreCase + )) { if (!string.IsNullOrEmpty(group.Key)) - Ui.SeparatorText(group.Key); + { + Gui.SeparatorText(group.Key); + } DrawSection(group, ref fieldIndex); - Ui.Spacing(); + Gui.Spacing(); } } + private static SettingsStyle settingsStyle => new(EditorUI.current.widgets.style); + private void DrawPageHeader(SettingsPage page) { ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX; - if (!Ui.BeginTable("##settings_page_header", 2, flags, default(System.Numerics.Vector2), 0f)) + if (!Gui.BeginTable("##settings_page_header", 2, flags, default, 0f)) + { return; + } try { - Ui.TableSetupColumn("##settings_page_title", ImGuiTableColumnFlags.WidthStretch, 1f); - Ui.TableSetupColumn("##settings_page_reset", ImGuiTableColumnFlags.WidthFixed, GetResetColumnWidth()); - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); - Ui.AlignTextToFramePadding(); - Ui.Text(page.label); - _ = Ui.TableSetColumnIndex(1); - Ui.PushId(page.path); + Gui.TableSetupColumn("##settings_page_title", ImGuiTableColumnFlags.WidthStretch, 1f); + Gui.TableSetupColumn("##settings_page_reset", ImGuiTableColumnFlags.WidthFixed, GetResetColumnWidth()); + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); + Gui.AlignTextToFramePadding(); + Gui.Text(page.label); + _ = Gui.TableSetColumnIndex(1); + Gui.PushID(page.path); try { bool canReset = session.CanReset(page); if (DrawResetButton(canReset)) + { session.Reset(page); + } } finally { - Ui.PopId(); + Gui.PopID(); } } finally { - Ui.EndTable(); - } - } - - private static void DrawOverview( - IReadOnlyList children, - Action navigate - ) { - if (children.Count == 0) - { - PushDisabledText(); - Ui.Text("No settings are currently registered on this page."); - Ui.PopStyleColor(); - return; - } - - for (int i = 0; i < children.Count; i++) - { - SettingsPage child = children[i]; - bool clicked = EditorUI.current.widgets.HoverText($"settings_overview_{child.path}", child.label); - if (clicked) - navigate(child); - EditorUI.current.widgets.DrawItemTooltip(child.description); - Ui.Spacing(); + Gui.EndTable(); } } @@ -105,24 +94,30 @@ private void DrawSection( ref int fieldIndex ) { ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX; - float tableWidth = MathF.Max(1f, Ui.GetContentRegionAvailable().X); - Ui.PushStyleVar(ImGuiStyleVar.CellPadding, settingsStyle.fieldPadding); + float tableWidth = MathF.Max(1f, Gui.GetContentRegionAvailable().X); + Gui.PushStyleVar(ImGuiStyleVar.CellPadding, settingsStyle.fieldPadding); bool tableStarted = false; try { - tableStarted = Ui.BeginTable("##settings_section", 3, flags, new System.Numerics.Vector2(tableWidth, 0f)); + tableStarted = Gui.BeginTable("##settings_section", 3, flags, new Vector2(tableWidth, 0f)); if (!tableStarted) + { return; + } EditorUI.current.widgets.SetupPropertyColumns(); - Ui.TableSetupColumn("##settings_reset", ImGuiTableColumnFlags.WidthFixed, GetResetColumnWidth()); + Gui.TableSetupColumn("##settings_reset", ImGuiTableColumnFlags.WidthFixed, GetResetColumnWidth()); foreach (SettingsField setting in settings) + { DrawFieldRow(setting, fieldIndex++); + } } finally { if (tableStarted) - Ui.EndTable(); - Ui.PopStyleVar(); + { + Gui.EndTable(); + } + Gui.PopStyleVar(); } } @@ -130,48 +125,77 @@ private void DrawFieldRow( SettingsField setting, int fieldIndex ) { - Ui.TableNextRow(); - uint background = Ui.ToPackedColor(fieldIndex % 2 == 0 ? SettingsStyle.field : SettingsStyle.alternateField); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, background); - Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, background); - Ui.PushId(setting.path); + Gui.TableNextRow(); + uint background = Gui.ToPackedColor(fieldIndex % 2 == 0 ? SettingsStyle.field : SettingsStyle.alternateField); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, background); + Gui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, background); + Gui.PushID(setting.path); try { - _ = Ui.TableSetColumnIndex(0); - Ui.SetCursorPosX(Ui.GetCursorPosX() + Ui.GetLayout().windowPadding.X); + _ = Gui.TableSetColumnIndex(0); + Gui.SetCursorPosX(Gui.GetCursorPosX() + Gui.GetLayout().windowPadding.X); EditorUI.current.widgets.PropertyLabel(setting.label, setting.description); - _ = Ui.TableSetColumnIndex(1); + _ = Gui.TableSetColumnIndex(1); bool groupStarted = false; try { - Ui.BeginGroup(); + Gui.BeginGroup(); groupStarted = true; session.UpdateDirty(setting, session.Draw(setting)); - Ui.EndGroup(); + Gui.EndGroup(); groupStarted = false; - _ = Ui.TableSetColumnIndex(2); + _ = Gui.TableSetColumnIndex(2); bool canReset = session.CanReset(setting); if (DrawResetButton(canReset)) + { session.Reset(setting); + } } finally { if (groupStarted) - Ui.EndGroup(); + { + Gui.EndGroup(); + } } } finally { - Ui.PopId(); + Gui.PopID(); } DrawFieldBackgroundGutters(background); } + private static void DrawOverview( + IReadOnlyList children, + Action navigate + ) { + if (children.Count == 0) + { + PushDisabledText(); + Gui.Text("No settings are currently registered on this page."); + Gui.PopStyleColor(); + return; + } + + for (int i = 0; i < children.Count; i++) + { + SettingsPage child = children[i]; + bool clicked = EditorUI.current.widgets.HoverText($"settings_overview_{child.path}", child.label); + if (clicked) + { + navigate(child); + } + EditorUI.current.widgets.DrawItemTooltip(child.description); + Gui.Spacing(); + } + } + private static void DrawFieldBackgroundGutters(uint background) { - var table = Ui.GetTableBounds(); - var window = Ui.GetWindowBounds(); + (float minimumX, float maximumX, float rowMinimum, float rowMaximum) table = Gui.GetTableBounds(); + (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padding) window = Gui.GetWindowBounds(); float tableMinimumX = table.minimumX; float tableMaximumX = table.maximumX; float rowMinimumY = table.rowMinimum; @@ -179,19 +203,31 @@ private static void DrawFieldBackgroundGutters(uint background) float windowMinimumX = window.minimumX; float windowMaximumX = window.maximumX; if (rowMaximumY <= rowMinimumY) + { return; - EditorDrawList drawList = Ui.GetDrawList(); + } + EditorDrawList drawList = Gui.GetDrawList(); drawList.PushClip(new Vector2(windowMinimumX, rowMinimumY), new Vector2(windowMaximumX, rowMaximumY), false); try { if (tableMinimumX > windowMinimumX) { - Ui.DrawFilledRectangle(new System.Numerics.Vector2(windowMinimumX, rowMinimumY), new System.Numerics.Vector2(tableMinimumX, rowMaximumY), background, 0); + Gui.DrawFilledRectangle( + new Vector2(windowMinimumX, rowMinimumY), + new Vector2(tableMinimumX, rowMaximumY), + background, + 0 + ); } if (tableMaximumX < windowMaximumX) { - Ui.DrawFilledRectangle(new System.Numerics.Vector2(tableMaximumX, rowMinimumY), new System.Numerics.Vector2(windowMaximumX, rowMaximumY), background, 0); + Gui.DrawFilledRectangle( + new Vector2(tableMaximumX, rowMinimumY), + new Vector2(windowMaximumX, rowMaximumY), + background, + 0 + ); } } finally @@ -202,24 +238,24 @@ private static void DrawFieldBackgroundGutters(uint background) private static float GetResetColumnWidth() { - EditorUiLayout style = Ui.GetLayout(); - return style.itemSpacing.X + Ui.MeasureText("Reset").X + style.framePadding.X * 2f + style.windowPadding.X; + EditorUILayout style = Gui.GetLayout(); + return style.itemSpacing.X + Gui.MeasureText("Reset").X + style.framePadding.X * 2f + style.windowPadding.X; } private static bool DrawResetButton(bool enabled) { - EditorUiLayout style = Ui.GetLayout(); - Ui.SetCursorPosX(Ui.GetCursorPosX() + style.itemSpacing.X); - Ui.BeginDisabled(!enabled); + EditorUILayout style = Gui.GetLayout(); + Gui.SetCursorPosX(Gui.GetCursorPosX() + style.itemSpacing.X); + Gui.BeginDisabled(!enabled); try { - return Ui.SmallButton("Reset"); + return Gui.SmallButton("Reset"); } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } - private static void PushDisabledText() => Ui.PushStyleColor(ImGuiCol.Text, Ui.GetStyleColorValue(ImGuiCol.TextDisabled)); + private static void PushDisabledText() => Gui.PushStyleColor(ImGuiCol.Text, Gui.GetStyleColorValue(ImGuiCol.TextDisabled)); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs index 53a35da01..b5f7c6291 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs @@ -1,14 +1,17 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + internal sealed class SettingsTree { private string? m_revealPath; + internal void Reveal(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); @@ -27,7 +30,9 @@ Action select for (int i = 0; i < pages.Count; i++) { if (Matches(pages[i], query)) + { DrawPage(pages[i], query, selectedPath, revealPath, select); + } } } finally @@ -46,10 +51,14 @@ string path { SettingsPage page = pages[i]; if (string.Equals(page.path, path, StringComparison.Ordinal)) + { return page; + } SettingsPage? nested = FindPage(page.children, path); if (nested is not null) + { return nested; + } } return null; @@ -60,17 +69,25 @@ string path string query ) { if (string.IsNullOrWhiteSpace(query)) + { return pages.Count > 0 ? pages[0] : null; + } SettingsPage? fieldMatch = FindFirstFieldMatch(pages, query); if (fieldMatch is not null) + { return fieldMatch; + } for (int i = 0; i < pages.Count; i++) { if (MatchesSelf(pages[i], query)) + { return pages[i]; + } SettingsPage? nested = FindFirstMatch(pages[i].children, query); if (nested is not null) + { return nested; + } } return null; @@ -85,43 +102,67 @@ Action select ) { bool hasVisibleChildren = false; for (int i = 0; i < page.children.Count; i++) + { hasVisibleChildren |= Matches(page.children[i], query); + } if ((!string.IsNullOrWhiteSpace(query) && hasVisibleChildren) || (hasVisibleChildren && IsRevealed(page.path, revealPath))) + { EditorUI.current.widgets.SetNextTreeNodeOpen(true); + } TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"settings_tree_{page.path}", - _ => Ui.Text(page.label), - new TreeNodeOptions { selected = string.Equals(page.path, selectedPath, StringComparison.Ordinal), isLeaf = !hasVisibleChildren, hideGuideLines = false } + _ => Gui.Text(page.label), + new TreeNodeOptions + { + selected = string.Equals(page.path, selectedPath, StringComparison.Ordinal), + isLeaf = !hasVisibleChildren, + hideGuideLines = false + } ); if (result.isClicked) + { select(page); + } if (!result.isOpen) + { return; + } for (int i = 0; i < page.children.Count; i++) { if (Matches(page.children[i], query)) + { DrawPage(page.children[i], query, selectedPath, revealPath, select); + } } - Ui.TreePop(); + Gui.TreePop(); } private static bool IsRevealed( string pagePath, string? revealPath - ) => revealPath is not null && (string.Equals(pagePath, revealPath, StringComparison.Ordinal) || revealPath.StartsWith(pagePath + "/", StringComparison.Ordinal)); + ) => revealPath is not null + && (string.Equals(pagePath, revealPath, StringComparison.Ordinal) + || revealPath.StartsWith(pagePath + "/", StringComparison.Ordinal)); + private static bool Matches( SettingsPage page, string query ) { if (string.IsNullOrWhiteSpace(query)) + { return true; + } if (MatchesSelf(page, query)) + { return true; + } for (int i = 0; i < page.children.Count; i++) { if (Matches(page.children[i], query)) + { return true; + } } return false; @@ -131,38 +172,20 @@ private static bool MatchesSelf( SettingsPage page, string query ) { - if (page.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || page.path.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || page.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (page.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || page.path.Contains(query, StringComparison.OrdinalIgnoreCase) + || page.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return true; } for (int i = 0; i < page.settings.Count; i++) { SettingsField setting = page.settings[i]; - if (setting.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || (setting.section?.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) ?? false) - || setting.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (setting.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || (setting.section?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) + || setting.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return true; } } @@ -180,26 +203,19 @@ string query for (int settingIndex = 0; settingIndex < page.settings.Count; settingIndex++) { SettingsField setting = page.settings[settingIndex]; - if (setting.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || (setting.section?.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) ?? false) - || setting.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (setting.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || (setting.section?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) + || setting.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return page; } } SettingsPage? nested = FindFirstFieldMatch(page.children, query); if (nested is not null) + { return nested; + } } return null; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs index d1ecd7898..5eb4750f0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs @@ -1,8 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - -using Inno.Build; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.Settings; @@ -15,106 +13,27 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(payload)); } - internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(EditorHistoryChange change) + internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(EditorHistoryChange change) { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Build Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Build Settings history payload has an invalid boundary."); + } return ( payload.AsMemory(sizeof(int), beforeLength), payload.AsMemory(sizeof(int) + beforeLength)); } } - -[EditorHistoryHandler(BuildSettingsHistory.C_KIND)] -internal sealed class BuildSettingsHistoryHandler(BuildSettingsStore settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); - settings.RestoreDocument( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreDocument(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Build Settings transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs new file mode 100644 index 000000000..6830a1a96 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using Inno.Build; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.Settings; + +[EditorHistoryHandler(BuildSettingsHistory.C_KIND)] +internal sealed class BuildSettingsHistoryHandler(BuildSettingsStore settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); + settings.RestoreDocument(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreDocument(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Build Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs index 901ca08f3..bc8a56f4f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs @@ -2,11 +2,11 @@ namespace Inno.Editor.Panel.Settings; -[EditorAction(SettingsInteractionIds.C_OPEN)] -[EditorMenu(SettingsInteractionIds.C_MAIN_MENU_AREA, "Edit/Settings...", order: 1000)] +[EditorAction(SettingsInteractionIDs.C_OPEN)] +[EditorMenu(SettingsInteractionIDs.C_MAIN_MENU_AREA, "Edit/Settings...", order: 1000)] internal sealed class OpenSettingsAction(SettingsWindowModule window) : EditorAction { - /// + /// protected override EditorActionState Query(EditorActionContext context) => new(true, window.canOpen, unavailableReason: window.unavailableReason); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs index 098e8f7aa..dc951466c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Build; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -10,67 +9,6 @@ namespace Inno.Editor.Panel.Settings; -internal enum SettingsScope -{ - Editor, - Project, - Build -} - -internal sealed class SettingsField -{ - private readonly BuildSettingsField? m_build; - private readonly EditorSetting? m_editor; - private readonly ProjectSettingEditor? m_project; - - internal SettingsField(EditorSetting definition) - { - m_editor = definition; - scope = SettingsScope.Editor; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = definition.order; - section = definition.section ?? string.Empty; - description = definition.description; - } - - internal SettingsField(ProjectSettingEditor definition) - { - m_project = definition; - scope = SettingsScope.Project; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = definition.order; - section = definition.section ?? string.Empty; - description = definition.description; - } - - internal SettingsField(BuildSettingsField definition) - { - m_build = definition; - scope = SettingsScope.Build; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = 0; - section = definition.section; - description = definition.description; - } - - internal SettingsScope scope { get; } - internal string path { get; } - internal string pagePath { get; } - internal string label { get; } - internal int order { get; } - internal string section { get; } - internal string description { get; } - internal EditorSetting? editor => m_editor; - internal ProjectSettingEditor? project => m_project; - internal BuildSettingsField? build => m_build; -} - internal sealed class SettingsEditSession : IDisposable { private readonly EditorSettings m_editorSettings; @@ -80,12 +18,12 @@ internal sealed class SettingsEditSession : IDisposable private readonly HashSet m_editorResetIntent = new(StringComparer.Ordinal); private readonly HashSet m_editorResets = new(StringComparer.Ordinal); private readonly Dictionary m_editorValues = new(StringComparer.Ordinal); - private readonly HashSet m_projectModified = []; - private readonly HashSet m_projectInitiallyNonDefault = []; - private readonly HashSet m_projectResetIntent = []; - private readonly HashSet m_projectResets = []; - private readonly Dictionary m_projectOriginalValues = []; - private readonly Dictionary m_projectValues = []; + private readonly HashSet m_projectModified = []; + private readonly HashSet m_projectInitiallyNonDefault = []; + private readonly HashSet m_projectResetIntent = []; + private readonly HashSet m_projectResets = []; + private readonly Dictionary m_projectOriginalValues = []; + private readonly Dictionary m_projectValues = []; private readonly BuildSettingsStore m_buildSettings; private readonly BuildPipeline m_buildPipeline; private readonly IEditorHistory m_history; @@ -101,56 +39,73 @@ internal SettingsEditSession( BuildSettingsStore buildSettings, IEditorHistory history ) { - m_editorSettings = editorSettings ?? throw new ArgumentNullException(nameof(editorSettings)); - m_projectSettings = projectSettings ?? throw new ArgumentNullException(nameof(projectSettings)); - m_buildPipeline = buildPipeline ?? throw new ArgumentNullException(nameof(buildPipeline)); - m_buildSettings = buildSettings ?? throw new ArgumentNullException(nameof(buildSettings)); - m_history = history ?? throw new ArgumentNullException(nameof(history)); - editorCatalogRevision = editorSettings.catalogRevision; - projectCatalogRevision = projectSettings.catalogRevision; + ArgumentNullException.ThrowIfNull(editorSettings); + ArgumentNullException.ThrowIfNull(projectSettings); + ArgumentNullException.ThrowIfNull(buildPipeline); + ArgumentNullException.ThrowIfNull(buildSettings); + ArgumentNullException.ThrowIfNull(history); + m_editorSettings = editorSettings; + m_projectSettings = projectSettings; + m_buildPipeline = buildPipeline; + m_buildSettings = buildSettings; + m_history = history; + this.editorCatalogRevision = editorSettings.catalogRevision; + this.projectCatalogRevision = projectSettings.catalogRevision; m_buildDefault = buildSettings.defaultSettings; m_buildOriginal = buildSettings.Load(); m_buildValue = m_buildOriginal.Copy(); - var fields = new List(); + List fields = []; foreach (EditorSetting definition in editorSettings.definitions) { if (!definition.hasValue) + { continue; + } fields.Add(new SettingsField(definition)); EditorSettingObject value = editorSettings.Get(definition.path); m_editorValues.Add(definition.path, value); if (!definition.IsDefault(value)) + { m_editorInitiallyNonDefault.Add(definition.path); + } } foreach (ProjectSettingEditor definition in projectSettings.definitions) { fields.Add(new SettingsField(definition)); - if (m_projectValues.ContainsKey(definition.settingId)) + if (m_projectValues.ContainsKey(definition.settingID)) + { continue; + } ISerializable value = projectSettings.Get(definition); - m_projectValues.Add(definition.settingId, value); - m_projectOriginalValues.Add(definition.settingId, projectSettings.Get(definition)); + m_projectValues.Add(definition.settingID, value); + m_projectOriginalValues.Add(definition.settingID, projectSettings.Get(definition)); if (!definition.ValuesEqual(value, projectSettings.GetComposedDefault(definition))) - m_projectInitiallyNonDefault.Add(definition.settingId); + { + m_projectInitiallyNonDefault.Add(definition.settingID); + } } foreach (BuildSettingsField definition in BuildSettingsPresentation.fields) + { fields.Add(new SettingsField(definition)); + } string? duplicatePath = fields .GroupBy(static field => field.path, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) + { throw new InvalidOperationException($"Settings field path '{duplicatePath}' is registered more than once."); + } - definitions = fields + this.definitions = fields .OrderBy(static field => field.path, StringComparer.Ordinal) .ThenBy(static field => field.order) .ToArray(); - pages = BuildPages(editorSettings.definitions, definitions); + this.pages = BuildPages(editorSettings.definitions, definitions); } - /// + /// public void Dispose() { m_applyTransaction?.Dispose(); @@ -171,25 +126,36 @@ public void Dispose() internal bool Draw(SettingsField field) { if (field.editor is EditorSetting editor) + { return editor.Draw(m_editorValues[editor.path]); + } if (field.project is ProjectSettingEditor project) - return project.Draw(m_projectValues[project.settingId]); + { + return project.Draw(m_projectValues[project.settingID]); + } if (field.build is BuildSettingsField build) + { return build.Draw(m_buildValue, m_buildPipeline); + } throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); } internal bool CanReset(SettingsField field) { if (field.editor is EditorSetting editor) + { return !editor.IsDefault(m_editorValues[editor.path]); + } if (field.build is BuildSettingsField build) + { return !build.IsDefault(m_buildValue, m_buildDefault); + } ProjectSettingEditor project = field.project - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); bool differsFromDefault = !project.ValuesEqual( - m_projectValues[project.settingId], - m_projectSettings.GetComposedDefault(project)); + m_projectValues[project.settingID], + m_projectSettings.GetComposedDefault(project) + ); return differsFromDefault; } @@ -198,12 +164,16 @@ internal bool CanReset(SettingsPage page) for (int i = 0; i < page.settings.Count; i++) { if (CanReset(page.settings[i])) + { return true; + } } for (int i = 0; i < page.children.Count; i++) { if (CanReset(page.children[i])) + { return true; + } } return false; } @@ -211,7 +181,9 @@ internal bool CanReset(SettingsPage page) internal void Reset(SettingsField field) { if (!CanReset(field)) + { return; + } if (field.editor is EditorSetting editor) { m_editorValues[editor.path] = editor.defaultValue; @@ -219,7 +191,8 @@ internal void Reset(SettingsField field) editor.path, m_editorInitiallyNonDefault.Contains(editor.path), m_editorResetIntent, - m_editorResets); + m_editorResets + ); _ = m_editorModified.Remove(editor.path); return; } @@ -229,22 +202,27 @@ internal void Reset(SettingsField field) return; } ProjectSettingEditor project = field.project - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); - m_projectValues[project.settingId] = m_projectSettings.GetComposedDefault(project); + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + m_projectValues[project.settingID] = m_projectSettings.GetComposedDefault(project); SetResetState( - project.settingId, - m_projectInitiallyNonDefault.Contains(project.settingId), + project.settingID, + m_projectInitiallyNonDefault.Contains(project.settingID), m_projectResetIntent, - m_projectResets); - _ = m_projectModified.Remove(project.settingId); + m_projectResets + ); + _ = m_projectModified.Remove(project.settingID); } internal void Reset(SettingsPage page) { for (int i = 0; i < page.settings.Count; i++) + { Reset(page.settings[i]); + } for (int i = 0; i < page.children.Count; i++) + { Reset(page.children[i]); + } } internal void UpdateDirty( @@ -252,19 +230,16 @@ internal void UpdateDirty( bool differsFromDrawBaseline ) { if (field.build is not null) + { return; + } if (field.editor is EditorSetting editor) { - UpdateDirty( - editor.path, - differsFromDrawBaseline, - m_editorModified, - m_editorResets, - m_editorResetIntent); + UpdateDirty(editor.path, differsFromDrawBaseline, m_editorModified, m_editorResets, m_editorResetIntent); return; } - ProjectSettingId id = field.project?.settingId - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + ProjectSettingID id = field.project?.settingID + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); ProjectSettingEditor project = field.project; ISerializable value = m_projectValues[id]; if (m_projectResetIntent.Contains(id)) @@ -281,15 +256,23 @@ bool differsFromDrawBaseline bool differsFromOriginal = !project.ValuesEqual(value, m_projectOriginalValues[id]); if (differsFromOriginal) + { _ = m_projectModified.Add(id); + } else + { _ = m_projectModified.Remove(id); + } } internal bool Apply() { if (!canApply) - throw new InvalidOperationException("Settings cannot be applied while their previous transaction or History requires recovery."); + { + throw new InvalidOperationException( + "Settings cannot be applied while their previous transaction or History requires recovery." + ); + } bool editorDirty = isEditorDirty; bool projectDirty = isProjectDirty; bool buildDirty = isBuildDirty; @@ -298,11 +281,17 @@ internal bool Apply() try { if (editorDirty) + { changed |= ApplyEditor(); + } if (projectDirty) + { changed |= ApplyProject(); + } if (buildDirty) + { changed |= ApplyBuild(); + } m_applyTransaction.Commit(); m_applyTransaction = null; } @@ -317,25 +306,33 @@ internal bool Apply() throw new AggregateException( "Settings Apply failed and its History transaction could not retire. Recovery is required before further editing.", failure, - rollbackFailure); + rollbackFailure + ); } throw; } if (editorDirty) + { AcceptEditorValues(); + } if (projectDirty) + { AcceptProjectValues(); + } if (buildDirty) + { AcceptBuildValues(); + } return changed; } private bool ApplyEditor() { - var values = m_editorModified.ToDictionary( + Dictionary values = m_editorModified.ToDictionary( path => path, path => m_editorValues[path], - StringComparer.Ordinal); + StringComparer.Ordinal + ); return m_editorSettings.Apply(values, m_editorResets); } @@ -351,13 +348,15 @@ private void AcceptEditorValues() EditorSettingObject value = m_editorSettings.Get(field.path); m_editorValues[field.path] = value; if (!definition.IsDefault(value)) + { m_editorInitiallyNonDefault.Add(field.path); + } } } private bool ApplyProject() { - var values = m_projectModified.ToDictionary(id => id, id => m_projectValues[id]); + Dictionary values = m_projectModified.ToDictionary(id => id, id => m_projectValues[id]); return m_projectSettings.Apply(values, m_projectResets); } @@ -368,16 +367,18 @@ private void AcceptProjectValues() m_projectResetIntent.Clear(); m_projectResets.Clear(); foreach (SettingsField field in definitions - .Where(static field => field.scope == SettingsScope.Project) - .GroupBy(static field => field.project!.settingId) - .Select(static group => group.First())) - { + .Where(static field => field.scope == SettingsScope.Project) + .GroupBy(static field => field.project!.settingID) + .Select(static group => group.First()) + ) { ProjectSettingEditor definition = field.project!; ISerializable value = m_projectSettings.Get(definition); - m_projectValues[definition.settingId] = value; - m_projectOriginalValues[definition.settingId] = m_projectSettings.Get(definition); + m_projectValues[definition.settingID] = value; + m_projectOriginalValues[definition.settingID] = m_projectSettings.Get(definition); if (!definition.ValuesEqual(value, m_projectSettings.GetComposedDefault(definition))) - m_projectInitiallyNonDefault.Add(definition.settingId); + { + m_projectInitiallyNonDefault.Add(definition.settingID); + } } } @@ -413,8 +414,7 @@ private static void UpdateDirty( ISet modified, ISet resets, ISet resetIntent - ) - where T : notnull + ) where T : notnull { if (differs) { @@ -424,7 +424,9 @@ ISet resetIntent } _ = modified.Remove(id); if (resetIntent.Contains(id)) + { _ = resets.Add(id); + } } private static void SetResetState( @@ -432,8 +434,7 @@ private static void SetResetState( bool changesEffectiveValue, ISet resetIntent, ISet resets - ) - where T : notnull + ) where T : notnull { if (changesEffectiveValue) { @@ -461,11 +462,15 @@ IReadOnlyList fields page.description = definition.description; } foreach (SettingsField field in fields) + { EnsurePage(field.pagePath, byPath).settings.Add(field); + } string? collision = fields.Select(static field => field.path).FirstOrDefault(byPath.ContainsKey); if (collision is not null) + { throw new InvalidOperationException($"Settings path '{collision}' cannot be a field and a page."); + } return root.children .OrderBy(static page => page.label, StringComparer.OrdinalIgnoreCase) @@ -478,7 +483,9 @@ private static MutablePage EnsurePage( IDictionary byPath ) { if (byPath.TryGetValue(path, out MutablePage? existing)) + { return existing; + } string[] segments = path.Split('/'); string currentPath = string.Empty; MutablePage parent = byPath[string.Empty]; @@ -531,11 +538,19 @@ internal SettingsPage Build() label, string.IsNullOrWhiteSpace(description) ? fallback : description, orderedSettings, - orderedChildren); + orderedChildren + ); } } } +internal enum SettingsScope +{ + Editor, + Project, + Build +} + internal sealed record SettingsPage( string path, string label, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs new file mode 100644 index 000000000..1918fcaa6 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs @@ -0,0 +1,57 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Settings; + +internal sealed class SettingsField +{ + private readonly BuildSettingsField? m_build; + private readonly EditorSetting? m_editor; + private readonly ProjectSettingEditor? m_project; + + internal SettingsField(EditorSetting definition) + { + m_editor = definition; + this.scope = SettingsScope.Editor; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; + } + + internal SettingsField(ProjectSettingEditor definition) + { + m_project = definition; + this.scope = SettingsScope.Project; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; + } + + internal SettingsField(BuildSettingsField definition) + { + m_build = definition; + this.scope = SettingsScope.Build; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = 0; + this.section = definition.section; + this.description = definition.description; + } + + internal SettingsScope scope { get; } + internal string path { get; } + internal string pagePath { get; } + internal string label { get; } + internal int order { get; } + internal string section { get; } + internal string description { get; } + internal EditorSetting? editor => m_editor; + internal ProjectSettingEditor? project => m_project; + internal BuildSettingsField? build => m_build; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs index 0ed225df8..1718d431f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs @@ -22,6 +22,12 @@ EditorReloadCoordinator reloads private IDisposable? m_reloadGuard; private long m_failedCatalogRevision = long.MinValue; + bool IEditorReloadGuard.canRequestReload => !isVisible; + bool IEditorReloadGuard.canActivateReload => !isVisible; + + string? IEditorReloadGuard.blockingReason + => isVisible ? "Close Settings before reloading scripts to retire its current-generation editing state." : null; + internal bool isVisible { get; private set; } internal SettingsEditSession? session => m_session; @@ -29,10 +35,28 @@ EditorReloadCoordinator reloads internal bool canOpen => m_failedCatalogRevision != editorSettings.catalogRevision; internal string? unavailableReason => canOpen ? null : C_PRESENTATION_FAILURE; + /// + /// Registers the admission boundary for generation-bound Settings editing. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void OnStart(EditorContext context) => m_reloadGuard = reloads.RegisterGuard(this); + + /// + protected override void OnStop(EditorContext context) + { + Close(); + m_reloadGuard?.Dispose(); + m_reloadGuard = null; + } + internal void Open() { if (!canOpen) + { throw new InvalidOperationException(C_PRESENTATION_FAILURE); + } if (!isVisible) { m_session = new SettingsEditSession( @@ -40,7 +64,8 @@ internal void Open() projectSettings, buildPipeline, buildSettings, - interactions.history); + interactions.history + ); sessionRevision++; } isVisible = true; @@ -62,7 +87,8 @@ internal void Refresh() projectSettings, buildPipeline, buildSettings, - interactions.history); + interactions.history + ); sessionRevision++; } @@ -71,25 +97,4 @@ internal void FailPresentation() m_failedCatalogRevision = editorSettings.catalogRevision; Close(); } - - /// - /// Registers the admission boundary for generation-bound Settings editing. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void OnStart(EditorContext context) => m_reloadGuard = reloads.RegisterGuard(this); - - /// - protected override void OnStop(EditorContext context) - { - Close(); - m_reloadGuard?.Dispose(); - m_reloadGuard = null; - } - - bool IEditorReloadGuard.canRequestReload => !isVisible; - bool IEditorReloadGuard.canActivateReload => !isVisible; - string? IEditorReloadGuard.blockingReason - => isVisible ? "Close Settings before reloading scripts to retire its current-generation editing state." : null; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIDs.cs similarity index 78% rename from src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIds.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIDs.cs index 0858c6860..e6764328f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/SettingsInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.Panel.Settings; -internal static class SettingsInteractionIds +internal static class SettingsInteractionIDs { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; internal const string C_OPEN = "editor.settings.open"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs index e08247097..5eab4901e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs @@ -7,9 +7,12 @@ internal readonly struct SettingsStyle { private readonly float m_zoom; - internal SettingsStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal SettingsStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } - internal static Vector4 field { get; } = new(0.36f, 0.36f, 0.38f, EditorPalette.opacityTrace); - internal static Vector4 alternateField { get; } = new(0.52f, 0.52f, 0.56f, EditorPalette.opacityTrace); + internal static Vector4 field { get; } = new(0.36f, 0.36f, 0.38f, EditorPalette.C_OPACITY_TRACE); + internal static Vector4 alternateField { get; } = new(0.52f, 0.52f, 0.56f, EditorPalette.C_OPACITY_TRACE); internal Vector2 fieldPadding => new Vector2(8f, 6f) * m_zoom; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs index e57e0c728..cb05f5425 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs @@ -1,28 +1,42 @@ -using Inno.Editor.Core; -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using System.Globalization; +using System.IO; using System.Linq; +using System.Numerics; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; +using Inno.Editor.Core; +using Inno.Editor.ImGui; +using Inno.Editor.Interactions; +using Inno.Editor.Rendering; +using Inno.Editor.Shaders.ImGui; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; + using EditorImGui = Inno.Editor.ImGui.ImGui; -using Inno.Rendering.Assets.Authoring; +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void Controls(GraphNodeRecord node) { - if (owner.drawers?.TryDraw(node.definitionId, new(node, owner.serialization, owner.context, ( - key, - value, - continuous - ) => SetEncoded(node, key, value, continuous), owner.previews, m_inspection!, draft.readOnly)) == true) + if (owner.drawers?.TryDraw( + node.definitionID, + new ShaderNodeDrawContext(node, owner.serialization, owner.context, ( + key, + value, + continuous + ) => SetEncoded(node, key, value, continuous), owner.previews, m_inspection!, draft.readOnly) + ) == true + ) { return; - switch (node.definitionId) + } + switch (node.definitionID) { case "inno.shader.constant": Scalar(node); @@ -32,7 +46,12 @@ private void Controls(GraphNodeRecord node) Choice(node, "type", "float", ["float", "float2", "float3", "float4", "int", "uint"]); break; case "inno.shader.construct": - Choice(node, "type", "float4", ["float2", "float3", "float4", "int2", "int3", "int4", "uint2", "uint3", "uint4", "float3x3", "float4x4"]); + Choice( + node, + "type", + "float4", + ["float2", "float3", "float4", "int2", "int3", "int4", "uint2", "uint3", "uint4", "float3x3", "float4x4"] + ); break; case "inno.shader.select": Choice(node, "type", "float", ["float", "float2", "float3", "float4", "int", "uint", "bool"]); @@ -42,7 +61,7 @@ private void Controls(GraphNodeRecord node) "reroute.type", "Type", () => EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, Read(node, "valueType", new ShaderGraphType { id = "float" }).CreateType().id ) ); @@ -54,16 +73,25 @@ private void Controls(GraphNodeRecord node) InspectorRow("extract.component", "Component", () => { if (EditorImGui.InputInt("##component", ref index, 1, 100, 0) && index >= 0) + { Set(node, "index", index); + } }); break; case "inno.shader.sample": - Choice(node, "type", "sampled-texture2d", ["sampled-texture2d", "sampled-texture2d-array", "sampled-texture3d", "sampled-texture-cube"]); + Choice( + node, + "type", + "sampled-texture2d", + ["sampled-texture2d", "sampled-texture2d-array", "sampled-texture3d", "sampled-texture-cube"] + ); bool level = Read(node, "explicitLevel", false); InspectorRow("sample.explicit-level", "Explicit LOD", () => { if (EditorImGui.Checkbox("##explicit-level", ref level)) + { Set(node, "explicitLevel", level); + } }); break; case "inno.shader.stage-input": @@ -72,16 +100,16 @@ private void Controls(GraphNodeRecord node) case "inno.shader.source": Source(node); break; - case ShaderGraphNodes.callDefinitionId: + case ShaderGraphNodes.C_CALL_DEFINITION_ID: GraphCall(node); break; - case ShaderGraphNodes.inputDefinitionId: + case ShaderGraphNodes.C_INPUT_DEFINITION_ID: GraphInputs(node); break; - case ShaderGraphNodes.outputDefinitionId: + case ShaderGraphNodes.C_OUTPUT_DEFINITION_ID: GraphOutputs(node); break; - case ShaderGraphDocument.outputDefinitionId: + case ShaderGraphDocument.C_OUTPUT_DEFINITION_ID: Output(node); break; case "inno.shader.storage-load": @@ -90,22 +118,31 @@ private void Controls(GraphNodeRecord node) ShaderGraphType resource = Read( node, "resource", - new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } + new ShaderGraphType + { + isStorage = true, + storageElement = new() { id = "float4" }, + access = RenderStorageAccess.ReadWrite + } ); InspectorRow("storage.contract", "Contract", () => { if (EditorImGui.Button("Storage Contract…")) + { EditorImGui.OpenPopup("##storage"); + } }); if (StoragePopup(ref resource)) + { Set(node, "resource", resource); + } EditorUI.current.widgets.WrappedText("Connect then → after to order memory effects."); break; case "inno.shader.discard": EditorUI.current.widgets.WrappedText("Discard fragments where condition is true."); break; default: - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Extension node"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Extension node"); break; } } @@ -113,39 +150,47 @@ private void Controls(GraphNodeRecord node) private void GraphCall(GraphNodeRecord node) { Guid selected = Read(node, "sourceId", Guid.Empty); - string path = Read(node, "sourcePath", ""); - ShaderGraphNodeInterface nodeInterface = Read(node, ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()); + string path = Read(node, "sourcePath", string.Empty); + ShaderGraphNodeInterface nodeInterface = Read(node, ShaderGraphNodes.C_INTERFACE_KEY, new ShaderGraphNodeInterface()); InspectorRow("graph-node.asset", "Node Graph", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##graph-node", selected == Guid.Empty ? "Choose Shader node…" : System.IO.Path.GetFileName(path))) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##graph-node", + selected == Guid.Empty ? "Choose Shader node…" : Path.GetFileName(path) + )) { return; + } try { - foreach (AssetFileEntry entry in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.extension == ".ishader").OrderBy( - static entry => entry.assetPath.ToString(), - StringComparer.Ordinal - )) - { - Guid id = owner.AssetId(entry); + foreach (AssetFileEntry entry in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.extension == ".ishader") + .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) + ) { + Guid id = owner.AssetID(entry); if (id == draft.id) + { continue; + } ShaderGraphNodeInterface candidate; try { candidate = owner.LoadGraphNodeInterface(id); } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { continue; } if (!EditorImGui.Selectable(candidate.displayName + " · " + entry.assetPath.localPath, id == selected)) + { continue; - using var transaction = owner.interactions.history.BeginTransaction("Assign Graph Node"); + } + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Assign Graph Node"); Set(node, "sourceId", id); Set(node, "sourcePath", entry.assetPath.ToString()); - Set(node, ShaderGraphNodes.interfaceKey, candidate); + Set(node, ShaderGraphNodes.C_INTERFACE_KEY, candidate); transaction.Commit(); selected = id; path = entry.assetPath.ToString(); @@ -158,38 +203,52 @@ private void GraphCall(GraphNodeRecord node) } }); EditorUI.current.widgets.DrawItemTooltip(path); - InspectorRow("graph-node.kind", "Kind", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.kind.ToString())); - InspectorRow("graph-node.effect", "Effect", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.effect.ToString())); + InspectorRow( + "graph-node.kind", + "Kind", + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.kind.ToString()) + ); + InspectorRow( + "graph-node.effect", + "Effect", + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.effect.ToString()) + ); if (nodeInterface.kind == ShaderGraphNodeKind.DomainOutput) - InspectorRow("graph-node.role", "Target Role", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.role)); + { + InspectorRow( + "graph-node.role", + "Target Role", + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.role) + ); + } RepairPorts(node); } private void GraphInputs(GraphNodeRecord node) { GraphInterfaceMetadata(); - ShaderGraphNodeInputSettings settings = Read(node, ShaderGraphDocument.settingsKey, new ShaderGraphNodeInputSettings()); + ShaderGraphNodeInputSettings settings = Read(node, ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeInputSettings()); GraphPorts(node, settings.ports, inputs: true, ports => { settings.ports = ports; - Set(node, ShaderGraphDocument.settingsKey, settings); + Set(node, ShaderGraphDocument.C_SETTINGS_KEY, settings); }); } private void GraphOutputs(GraphNodeRecord node) { GraphInterfaceMetadata(); - ShaderGraphNodeOutputSettings settings = Read(node, ShaderGraphDocument.settingsKey, new ShaderGraphNodeOutputSettings()); + ShaderGraphNodeOutputSettings settings = Read(node, ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeOutputSettings()); GraphPorts(node, settings.ports, inputs: false, ports => { settings.ports = ports; - Set(node, ShaderGraphDocument.settingsKey, settings); + Set(node, ShaderGraphDocument.C_SETTINGS_KEY, settings); }); } private void GraphInterfaceMetadata() { - ShaderGraphNodeSettings settings = ShaderGraphNodes.ReadSettings(Controller.document, owner.serialization, owner.context); + ShaderGraphNodeSettings settings = ShaderGraphNodes.ReadSettings(controller.document, owner.serialization, owner.context); string displayName = settings.displayName; InspectorRow("node-interface.name", "Node Name", () => { @@ -226,15 +285,19 @@ private void GraphInterfaceMetadata() InspectorRow("node-interface.kind", "Kind", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##kind", settings.kind.ToString())) + { return; + } try { foreach (ShaderGraphNodeKind kind in Enum.GetValues()) + { if (EditorImGui.Selectable(kind.ToString(), settings.kind == kind)) { settings.kind = kind; SetGraphNodeSettings(settings); } + } } finally { @@ -246,15 +309,19 @@ private void GraphInterfaceMetadata() InspectorRow("node-interface.effect", "Effect", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##effect", settings.effect.ToString())) + { return; + } try { foreach (ShaderGraphNodeEffect effect in Enum.GetValues()) + { if (EditorImGui.Selectable(effect.ToString(), settings.effect == effect)) { settings.effect = effect; SetGraphNodeSettings(settings); } + } } finally { @@ -283,9 +350,9 @@ private void SetGraphNodeSettings( ShaderGraphNodeSettings settings, bool continuous = false ) { - GraphDocument candidate = Controller.document.Clone(); + GraphDocument candidate = controller.document.Clone(); ShaderGraphNodes.WriteSettings(candidate, settings, owner.serialization, owner.context); - Controller.ReplaceDocument(candidate, "Edit Graph Node Interface", continuous ? draft.valueGesture : null); + controller.ReplaceDocument(candidate, "Edit Graph Node Interface", continuous ? draft.valueGesture : null); owner.Changed(draft); } @@ -298,7 +365,7 @@ Action apply EditorImGui.SeparatorText(inputs ? "Inputs" : "Outputs"); for (int index = 0; index < ports.Length; index++) { - EditorImGui.PushId(index); + EditorImGui.PushID(index); try { ShaderGraphNodePortDefinition port = ports[index]; @@ -322,7 +389,9 @@ Action apply InspectorRow("node-port.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##type", port.type.id)) + { return; + } try { foreach (string type in new[] @@ -348,7 +417,7 @@ Action apply "sampled-texture-cube" } - ) + ) { if (EditorImGui.Selectable(type, port.type.id == type)) { ShaderGraphNodePortDefinition[] changedPorts = ports.ToArray(); @@ -363,6 +432,7 @@ Action apply }; apply(changedPorts); } + } } finally { @@ -375,7 +445,9 @@ Action apply InspectorRow("node-port.required", "Required", () => { if (!EditorImGui.Checkbox("##required", ref required)) + { return; + } ShaderGraphNodePortDefinition[] changedPorts = ports.ToArray(); changedPorts[index] = new() { @@ -387,18 +459,22 @@ Action apply }); } - InspectorRow("node-port.remove", "", () => + InspectorRow("node-port.remove", string.Empty, () => { if (EditorImGui.SmallButton("Remove")) - apply(ports.Where(( - _, - item - ) => item != index).ToArray()); + { + apply( + ports.Where(( + _, + item + ) => item != index).ToArray() + ); + } }); } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } @@ -407,8 +483,10 @@ Action apply string prefix = inputs ? "input" : "output"; string id = prefix; for (int suffix = 2; ports.Any(port => port.id == id); suffix++) + { id = prefix + suffix; - apply([..ports, new() { id = id, type = new() { id = "float" }, required = false }]); + } + apply([..ports, new ShaderGraphNodePortDefinition() { id = id, type = new() { id = "float" }, required = false }]); } RepairPorts(node); @@ -420,7 +498,9 @@ private void Scalar(GraphNodeRecord node) InspectorRow("constant.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##constant-type", type)) + { return; + } try { foreach (string candidate in new[] @@ -431,10 +511,10 @@ private void Scalar(GraphNodeRecord node) "bool" } - ) + ) { if (EditorImGui.Selectable(candidate, type == candidate)) { - using var transaction = owner.interactions.history.BeginTransaction("Change Constant Type"); + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Change Constant Type"); Set(node, "type", candidate); switch (candidate) { @@ -455,6 +535,7 @@ private void Scalar(GraphNodeRecord node) transaction.Commit(); type = candidate; } + } } finally { @@ -470,7 +551,9 @@ private void Scalar(GraphNodeRecord node) bool changed = EditorUI.current.widgets.CompactDragFloat("##value", ref number, 0.01f); Gesture(); if (changed) + { Set(node, "value", number, true); + } }); break; case "bool": @@ -478,7 +561,9 @@ private void Scalar(GraphNodeRecord node) InspectorRow("constant.value", "Value", () => { if (EditorImGui.Checkbox("##value", ref boolean)) + { Set(node, "value", boolean); + } }); break; case "int": @@ -488,17 +573,21 @@ private void Scalar(GraphNodeRecord node) bool integerChanged = EditorImGui.InputInt("##value", ref integer, 1, 100, 0); Gesture(); if (integerChanged) + { Set(node, "value", integer, true); + } }); break; case "uint": - string unsigned = Read(node, "value", 0u).ToString(System.Globalization.CultureInfo.InvariantCulture); + string unsigned = Read(node, "value", 0u).ToString(CultureInfo.InvariantCulture); InspectorRow("constant.value", "Value", () => { bool unsignedChanged = EditorImGui.InputText("##value", ref unsigned, 32, ImGuiInputTextFlags.CharsDecimal); Gesture(); if (unsignedChanged && uint.TryParse(unsigned, out uint value)) + { Set(node, "value", value, true); + } }); break; } @@ -507,24 +596,34 @@ private void Scalar(GraphNodeRecord node) private void Source(GraphNodeRecord node) { Guid selected = Read(node, "sourceId", Guid.Empty); - string path = Read(node, "sourcePath", ""); - string selectedFunction = Read(node, "function", ""); + string path = Read(node, "sourcePath", string.Empty); + string selectedFunction = Read(node, "function", string.Empty); InspectorRow("source.library", "Library", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##library", selected == Guid.Empty ? "Choose source library…" : System.IO.Path.GetFileName(path))) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##library", + selected == Guid.Empty ? "Choose source library…" : Path.GetFileName(path) + )) { return; + } try { - foreach (AssetFileEntry entry in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.assetPath.localPath.EndsWith(".ishadersource", StringComparison.OrdinalIgnoreCase))) - if (EditorImGui.Selectable(entry.assetPath.ToString(), owner.AssetId(entry) == selected)) + foreach (AssetFileEntry entry in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.assetPath.localPath.EndsWith(".ishadersource", StringComparison.OrdinalIgnoreCase)) + ) { + if (EditorImGui.Selectable(entry.assetPath.ToString(), owner.AssetID(entry) == selected)) { - using var transaction = owner.interactions.history.BeginTransaction("Assign Shader Function"); - Set(node, "sourceId", owner.AssetId(entry)); + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Assign Shader Function"); + Set(node, "sourceId", owner.AssetID(entry)); Set(node, "sourcePath", entry.assetPath.ToString()); if (owner.assets.TryLoad(entry.assetPath, out ShaderFunctionAsset? library) && library is not null) - Set(node, "function", library.exports.FirstOrDefault() ?? ""); + { + Set(node, "function", library.exports.FirstOrDefault() ?? string.Empty); + } transaction.Commit(); } + } } finally { @@ -533,20 +632,33 @@ private void Source(GraphNodeRecord node) }); EditorUI.current.widgets.DrawItemTooltip(path); if (selected == Guid.Empty) - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Choose a library and one of its explicitly exported functions."); + { + EditorUI.current.widgets.ColoredText( + EditorPalette.textDisabled, + "Choose a library and one of its explicitly exported functions." + ); + } else { if (owner.assets.TryLoad(selected, out ShaderFunctionAsset? library) && library is not null && !library.isMissing) { InspectorRow("source.function", "Function", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##function", selectedFunction.Length == 0 ? "Choose exported function…" : selectedFunction)) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##function", + selectedFunction.Length == 0 ? "Choose exported function…" : selectedFunction + )) { return; + } try { foreach (string function in library.exports) + { if (EditorImGui.Selectable(function, function == selectedFunction)) + { Set(node, "function", function); + } + } } finally { @@ -577,14 +689,18 @@ private void Input(GraphNodeRecord node) InspectorRow("input.source", "Source", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##source", input.kind.ToString())) + { return; + } try { foreach (ShaderIrInputKind kind in Enum.GetValues()) + { if (EditorImGui.Selectable(kind.ToString(), input.kind == kind)) { input.kind = kind; if (kind == ShaderIrInputKind.Storage) + { input.type = new() { isStorage = true, @@ -594,20 +710,25 @@ private void Input(GraphNodeRecord node) }, access = RenderStorageAccess.ReadWrite }; + } else if (kind == ShaderIrInputKind.SampledTexture) + { input.type = new() { id = "sampled-texture2d" }; + } else if (input.type.isStorage || input.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { input.type = new() { id = "float4" }; + } if (kind == ShaderIrInputKind.Builtin) { - string stageId = Read(node, "stage", ""); - GraphNodeRecord? output = stageId.Length == 0 ? null : Controller.document.FindNode(new(stageId)); + string stageID = Read(node, "stage", string.Empty); + GraphNodeRecord? output = stageID.Length == 0 ? null : controller.document.FindNode(new GraphNodeID(stageID)); if (output is not null && Read(output, "settings", new ShaderGraphStageSettings()).stage == ShaderStage.Compute) { input.semantic = "global-invocation-id"; @@ -620,6 +741,7 @@ private void Input(GraphNodeRecord node) Set(node, "settings", input); } + } } finally { @@ -632,7 +754,9 @@ private void Input(GraphNodeRecord node) InspectorRow("input.storage", "Contract", () => { if (EditorImGui.Button("Storage Contract…")) + { EditorImGui.OpenPopup("##storage"); + } }); ShaderGraphType resource = input.type; if (StoragePopup(ref resource)) @@ -642,10 +766,13 @@ private void Input(GraphNodeRecord node) } } else + { InspectorRow("input.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##type", type)) + { return; + } try { foreach (string candidate in new[] @@ -671,7 +798,7 @@ private void Input(GraphNodeRecord node) "sampled-texture-cube" } - ) + ) { if (EditorImGui.Selectable(candidate, type == candidate)) { input.type = new() @@ -680,12 +807,14 @@ private void Input(GraphNodeRecord node) }; Set(node, "settings", input); } + } } finally { EditorUI.current.widgets.EndBoundedCombo(); } }); + } string semantic = input.semantic; bool semanticChanged = false; InspectorRow("input.semantic", "Semantic", () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 256)); @@ -696,7 +825,9 @@ private void Input(GraphNodeRecord node) Set(node, "settings", input, true); } - EditorUI.current.widgets.DrawItemTooltip("Stage semantic, not a native expression. Builtins must be supported by the selected stage and target; compute invocation IDs use uint3."); + EditorUI.current.widgets.DrawItemTooltip( + "Stage semantic, not a native expression. Builtins must be supported by the selected stage and target; compute invocation IDs use uint3." + ); int location = input.location; bool locationChanged = false; InspectorRow("input.location", "Location", () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0)); @@ -720,19 +851,30 @@ private void Input(GraphNodeRecord node) if (EditorImGui.Checkbox("##preview", ref expanded)) { if (expanded) + { draft.expandedPreviews.Add(node.id); + } else + { draft.expandedPreviews.Remove(node.id); + } } }); if (expanded) { - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, owner.serialization, owner.context); TextureAsset? texture = definition.properties.FirstOrDefault(value => value.id.value == input.id).defaultValue.texture; - if (texture is not null && owner.previews.TryGetTexture(texture, out var preview)) - owner.previews.Draw(preview, new(120 * Canvas.zoom, 120 * Canvas.zoom)); + if (texture is not null && owner.previews.TryGetTexture(texture, out EditorPreviewHandle preview)) + { + owner.previews.Draw(preview, new Vector2(120 * canvas.zoom, 120 * canvas.zoom)); + } else - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, texture is null ? "No default texture" : "Preparing preview…"); + { + EditorUI.current.widgets.ColoredText( + EditorPalette.textDisabled, + texture is null ? "No default texture" : "Preparing preview…" + ); + } } } } @@ -744,26 +886,29 @@ private void Output(GraphNodeRecord node) "output.passes", "Passes", () => EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, string.Join( ", ", - ShaderGraphPrograms.Read( - Controller.document, - owner.serialization, - owner.context - ).Where(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).Select(static program => program.pass) + ShaderGraphPrograms + .Read(controller.document, owner.serialization, owner.context) + .Where(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)) + .Select(static program => program.pass) ) ) ); InspectorRow("output.settings", "Settings", () => { if (EditorImGui.Button("Stage & Pass Settings…")) + { EditorImGui.OpenPopup("##stage-settings"); + } }); StageSettingsPopup(node, stage); if (stage.stage == ShaderStage.Compute) { - int x = stage.threadsX, y = stage.threadsY, z = stage.threadsZ; + int x = stage.threadsX; + int y = stage.threadsY; + int z = stage.threadsZ; InspectorRow("output.threads-x", "Threads X", () => { if (EditorImGui.InputInt("##threads-x", ref x, 1, 100, 0) && x > 0) @@ -801,12 +946,18 @@ string[] values InspectorRow("choice." + key, EditorDisplayNames.Nicify(key), () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##" + key, current)) + { return; + } try { foreach (string candidate in values) + { if (EditorImGui.Selectable(candidate, current == candidate)) + { Set(node, key, candidate); + } + } } finally { @@ -818,6 +969,8 @@ string[] values private void Gesture() { if (EditorImGui.IsItemActivated()) + { draft.valueGesture = Guid.NewGuid().ToString("N"); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs index efa53e84a..e2c562045 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs @@ -1,46 +1,60 @@ -using Inno.Editor.Core; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System.Linq; using Inno.Core.Graphs; +using Inno.Editor.Core; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void DrawInputDefault( GraphNodeRecord node, ShaderNodePort port ) { - var endpoint = new GraphEndpoint(node.id, new(port.id)); - GraphEdgeRecord? edge = Controller.document.edges.FirstOrDefault(value => value.input == endpoint); - ImGuiApi.PushId(port.id); + var endpoint = new GraphEndpoint(node.id, new GraphPortID(port.id)); + GraphEdgeRecord? edge = controller.document.edges.FirstOrDefault(value => value.input == endpoint); + ImGuiApi.PushID(port.id); try { if (edge is not null) { - InspectorPortStatusRow("port." + port.id, port, null, "From " + edge.output.nodeId.value + "." + edge.output.portId.value); + InspectorPortStatusRow("port." + port.id, port, null, "From " + edge.output.nodeID.value + "." + edge.output.portID.value); return; } - if (node.definitionId == ShaderGraphDocument.outputDefinitionId || draft.missingPorts.Contains(endpoint)) + if (node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID || draft.missingPorts.Contains(endpoint)) { InspectorPortStatusRow("port." + port.id, port, null, "Connect an available output"); return; } if (m_inspectionNodes is { Length: > 1 } selected - && selected.Any(value => !draft.ports[value.id].Any(candidate => candidate.id == port.id && candidate.type.IsEquivalentTo(port.type)) || Controller.document.edges.Any(connection => connection.input == new GraphEndpoint(value.id, new(port.id))))) - { + && selected.Any( + value => ( + !draft.ports[value.id].Any(candidate => candidate.id == port.id && candidate.type.IsEquivalentTo(port.type)) + || controller.document.edges.Any( + connection => connection.input == new GraphEndpoint(value.id, new GraphPortID(port.id)) + ) + ) + ) + ) { InspectorPortStatusRow("port." + port.id, port, null, "Mixed connections or types"); return; } - InspectorPortStatusRow("port." + port.id, port, null, port.required ? "Required · Connect a Constant or compatible output" : "Optional · Zero when unconnected"); + InspectorPortStatusRow( + "port." + port.id, + port, + null, + port.required ? "Required · Connect a Constant or compatible output" : "Optional · Zero when unconnected" + ); } finally { - ImGuiApi.PopId(); + ImGuiApi.PopID(); } } @@ -54,9 +68,11 @@ string status PortLabel(port, component), () => EditorUI.current.widgets.MetadataValue(DisplayType(port.type.id), status, "Shader value type · " + port.type.id) ); + private static string PortLabel( ShaderNodePort port, string? component ) => component is null ? port.id : port.id + " " + component; - private static string DisplayType(string typeId) => EditorDisplayNames.Nicify(typeId); + + private static string DisplayType(string typeID) => EditorDisplayNames.Nicify(typeID); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs index 4195f7257..19277d0a8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs @@ -1,42 +1,29 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private const float C_MINI_MAP_WIDTH = 220f; private const float C_MINI_MAP_HEIGHT = 145f; private const float C_MINI_MAP_MARGIN = 14f; private const float C_MINI_MAP_PADDING = 9f; - private readonly Dictionary m_miniMapGeometry = []; - private readonly record struct MiniMapNodeGeometry( - Vector2 minimum, - Vector2 maximum - ) - { - internal Vector2 center => (minimum + maximum) * 0.5f; - } - - private readonly record struct MiniMapLayout( - Vector2 worldMinimum, - Vector2 screenOrigin, - float scale - ) - { - internal Vector2 ToScreen(Vector2 position) => screenOrigin + (position - worldMinimum) * scale; - internal Vector2 ToWorld(Vector2 position) => worldMinimum + (position - screenOrigin) / scale; - } + private readonly Dictionary m_miniMapGeometry = []; private bool MiniMapContains(Vector2 point) { if (!TryGetMiniMapBounds(out Vector2 minimum, out Vector2 maximum)) + { return false; + } return point.X >= minimum.X && point.X <= maximum.X && point.Y >= minimum.Y && point.Y <= maximum.Y; } @@ -46,9 +33,11 @@ out Vector2 maximum ) { minimum = maximum = default; if (m_size.X < 320f || m_size.Y < 220f) + { return false; + } float zoom = EditorUI.current.widgets.style.zoom; - Vector2 size = new(MathF.Min(C_MINI_MAP_WIDTH * zoom, m_size.X * 0.30f), MathF.Min(C_MINI_MAP_HEIGHT * zoom, m_size.Y * 0.30f)); + var size = new Vector2(MathF.Min(C_MINI_MAP_WIDTH * zoom, m_size.X * 0.3f), MathF.Min(C_MINI_MAP_HEIGHT * zoom, m_size.Y * 0.3f)); maximum = m_origin + new Vector2(m_size.X - C_MINI_MAP_MARGIN * zoom, C_MINI_MAP_MARGIN * zoom + size.Y); minimum = maximum - size; return true; @@ -57,7 +46,9 @@ out Vector2 maximum private void DrawMiniMap() { if (!TryGetMiniMapBounds(out Vector2 minimum, out Vector2 maximum)) + { return; + } Vector2 size = maximum - minimum; Vector2 cursor = ImGuiApi.GetCursorScreenPosition(); ImGuiApi.SetCursorScreenPosition(minimum); @@ -74,21 +65,32 @@ private void DrawMiniMap() ); began = true; if (!visible) + { return; + } MiniMapLayout layout = CreateMiniMapLayout(minimum, maximum); - ImGuiApi.InvisibleButton("##mini-map-navigation", Vector2.Max(ImGuiApi.GetContentRegionAvailable(), Vector2.One), ImGuiButtonFlags.MouseButtonLeft); + ImGuiApi.InvisibleButton( + "##mini-map-navigation", + Vector2.Max(ImGuiApi.GetContentRegionAvailable(), Vector2.One), + ImGuiButtonFlags.MouseButtonLeft + ); if (ImGuiApi.IsItemActive() && ImGuiApi.IsMouseButtonDown(ImGuiMouseButton.Left)) { Vector2 graphPoint = layout.ToWorld(Vector2.Clamp(ImGuiApi.GetMousePos(), minimum, maximum)); - Canvas.SetViewport(new(m_size.X * 0.5f - graphPoint.X * Canvas.zoom, m_size.Y * 0.5f - graphPoint.Y * Canvas.zoom), Canvas.zoom); + canvas.SetViewport( + new GraphPosition(m_size.X * 0.5f - graphPoint.X * canvas.zoom, m_size.Y * 0.5f - graphPoint.Y * canvas.zoom), + canvas.zoom + ); } - DrawMiniMapContents(Inno.Editor.ImGui.ImGui.GetDrawList(), layout); + DrawMiniMapContents(ImGuiApi.GetDrawList(), layout); } finally { if (began) + { ImGuiApi.EndChild(); + } ImGuiApi.PopStyleColor(); ImGuiApi.PopStyleVar(); ImGuiApi.SetCursorScreenPosition(cursor); @@ -99,17 +101,17 @@ private MiniMapLayout CreateMiniMapLayout( Vector2 minimum, Vector2 maximum ) { - Vector2 viewMinimum = -new Vector2(Canvas.pan.x, Canvas.pan.y) / Canvas.zoom; - Vector2 viewMaximum = viewMinimum + m_size / Canvas.zoom; + Vector2 viewMinimum = -new Vector2(canvas.pan.x, canvas.pan.y) / canvas.zoom; + Vector2 viewMaximum = viewMinimum + m_size / canvas.zoom; Vector2 worldMinimum = viewMinimum; Vector2 worldMaximum = viewMaximum; m_miniMapGeometry.Clear(); - foreach (GraphNodeRecord node in Controller.document.nodes) + foreach (GraphNodeRecord node in controller.document.nodes) { GraphPosition position = draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position); - Vector2 nodeMinimum = new(position.x, position.y); + var nodeMinimum = new Vector2(position.x, position.y); Vector2 nodeMaximum = nodeMinimum + new Vector2(NodeWidth(node), C_HEADER + Rows(node) * C_ROW + 20f); - m_miniMapGeometry.Add(node.id, new(nodeMinimum, nodeMaximum)); + m_miniMapGeometry.Add(node.id, new MiniMapNodeGeometry(nodeMinimum, nodeMaximum)); worldMinimum = Vector2.Min(worldMinimum, nodeMinimum); worldMaximum = Vector2.Max(worldMaximum, nodeMaximum); } @@ -126,32 +128,45 @@ private void DrawMiniMapContents( EditorDrawList draw, MiniMapLayout layout ) { - foreach (GraphEdgeRecord edge in Controller.document.edges) + foreach (GraphEdgeRecord edge in controller.document.edges) { - if (!m_miniMapGeometry.TryGetValue( - edge.output.nodeId, - out MiniMapNodeGeometry source - ) - || !m_miniMapGeometry.TryGetValue( - edge.input.nodeId, - out MiniMapNodeGeometry target - )) + if (!m_miniMapGeometry.TryGetValue(edge.output.nodeID, out MiniMapNodeGeometry source) + || !m_miniMapGeometry.TryGetValue(edge.input.nodeID, out MiniMapNodeGeometry target) + ) { continue; + } draw.Line(layout.ToScreen(source.center), layout.ToScreen(target.center), Color(0.55f, 0.42f, 0.76f, 0.65f), 1f); } - foreach (GraphNodeRecord node in Controller.document.nodes) + foreach (GraphNodeRecord node in controller.document.nodes) { MiniMapNodeGeometry geometry = m_miniMapGeometry[node.id]; - uint fill = Canvas.selectedNodes.Contains(node.id) ? Color(0.60f, 0.44f, 0.83f) : Color(0.34f, 0.37f, 0.44f); + uint fill = canvas.selectedNodes.Contains(node.id) ? Color(0.6f, 0.44f, 0.83f) : Color(0.34f, 0.37f, 0.44f); draw.FilledRectangle(layout.ToScreen(geometry.minimum), layout.ToScreen(geometry.maximum), fill, 2f, false); } - Vector2 viewMinimum = -new Vector2(Canvas.pan.x, Canvas.pan.y) / Canvas.zoom; - Vector2 viewMaximum = viewMinimum + m_size / Canvas.zoom; + Vector2 viewMinimum = -new Vector2(canvas.pan.x, canvas.pan.y) / canvas.zoom; + Vector2 viewMaximum = viewMinimum + m_size / canvas.zoom; Vector2 screenMinimum = layout.ToScreen(viewMinimum); Vector2 screenMaximum = layout.ToScreen(viewMaximum); - draw.FilledRectangle(screenMinimum, screenMaximum, Color(0.65f, 0.47f, 0.88f, 0.10f), 0, false); + draw.FilledRectangle(screenMinimum, screenMaximum, Color(0.65f, 0.47f, 0.88f, 0.1f), 0, false); draw.Rectangle(screenMinimum, screenMaximum, Color(0.76f, 0.62f, 0.95f), 0f, 1.5f); } + + private readonly record struct MiniMapNodeGeometry( + Vector2 minimum, + Vector2 maximum + ) { + internal Vector2 center => (minimum + maximum) * 0.5f; + } + + private readonly record struct MiniMapLayout( + Vector2 worldMinimum, + Vector2 screenOrigin, + float scale + ) { + internal Vector2 ToScreen(Vector2 position) => screenOrigin + (position - worldMinimum) * scale; + + internal Vector2 ToWorld(Vector2 position) => worldMinimum + (position - screenOrigin) / scale; + } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs index 566435989..2ccb2aee8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs @@ -1,23 +1,29 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; +using System.Numerics; using Inno.Core.Graphs; -using Inno.Rendering; -using Inno.Rendering.Shaders; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using EditorImGui = Inno.Editor.ImGui.ImGui; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; + +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private bool StoragePopup(ref ShaderGraphType type) { - EditorImGui.SetNextWindowSize(new(490, 390), (ImGuiCond.Appearing)); + EditorImGui.SetNextWindowSize(new Vector2(490, 390), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##storage")) + { return false; + } bool changed = false; try { @@ -28,7 +34,7 @@ private bool StoragePopup(ref ShaderGraphType type) { type.isImage = image; type.isStorage = true; - type.storageElement = image ? null : new() + type.storageElement = image ? null : new ShaderGraphType() { id = "float4" }; @@ -75,7 +81,9 @@ private bool StoragePopup(ref ShaderGraphType type) InspectorRow("storage.element", "Element", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##element", current)) + { return; + } try { foreach (string candidate in new[] @@ -94,9 +102,12 @@ private bool StoragePopup(ref ShaderGraphType type) "uint4" } - ) + ) { if (EditorImGui.Selectable(candidate, current == candidate)) + { selected = candidate; + } + } } finally { @@ -113,7 +124,9 @@ private bool StoragePopup(ref ShaderGraphType type) } } - EditorUI.current.widgets.WrappedText("Storage resources are bound by the render pass. The graph declares types and access; the Render Graph owns resource lifetime and synchronization."); + EditorUI.current.widgets.WrappedText( + "Storage resources are bound by the render pass. The graph declares types and access; the Render Graph owns resource lifetime and synchronization." + ); } finally { @@ -126,8 +139,10 @@ private bool StoragePopup(ref ShaderGraphType type) private void DrawParameter(ShaderGraphInputSettings input) { if (m_inspection is null) + { return; - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); + } + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, owner.serialization, owner.context); int index = Array.FindIndex(definition.properties, value => value.id.value == input.id); if (index < 0) { @@ -144,7 +159,11 @@ private void DrawParameter(ShaderGraphInputSettings input) { string displayName = property.displayName; bool changed = false; - InspectorRow("parameter.display-name", "Display Name", () => changed = EditorImGui.InputText("##display-name", ref displayName, 256)); + InspectorRow( + "parameter.display-name", + "Display Name", + () => changed = EditorImGui.InputText("##display-name", ref displayName, 256) + ); Gesture(); if (changed) { @@ -179,23 +198,33 @@ private void DrawParameter(ShaderGraphInputSettings input) if (property.bindingOwner != ShaderPropertyBindingOwner.Material) { if (parameterOpen) + { EditorUI.current.widgets.Hint("Supplied by the Render Pass. This binding is read-only in Material Inspectors."); + } return; } if (property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture)) { if (parameterOpen) + { EditorUI.current.widgets.Hint("Storage resources require a Render Pass owner."); + } return; } - ShaderParameterPresentation presentation = ShaderParameterPresentation.Read(Controller.document, property.id, owner.serialization, owner.context); + ShaderParameterPresentation presentation = ShaderParameterPresentation.Read( + controller.document, + property.id, + owner.serialization, + owner.context + ); if (!EditorUI.current.widgets.SectionHeader( "Material Inspector", "Presentation belongs only to this Shader's authoring graph. It does not modify existing Material values or enter the Player." - )) + )) { return; + } string group = presentation.group; bool groupChanged = false; InspectorRow("parameter.group", "Group", () => groupChanged = EditorImGui.InputText("##group", ref group, 256)); @@ -208,7 +237,11 @@ private void DrawParameter(ShaderGraphInputSettings input) Gesture(); string description = presentation.description; bool descriptionChanged = false; - InspectorRow("parameter.description", "Description", () => descriptionChanged = EditorImGui.InputText("##description", ref description, 2048)); + InspectorRow( + "parameter.description", + "Description", + () => descriptionChanged = EditorImGui.InputText("##description", ref description, 2048) + ); if (descriptionChanged) { presentation.description = description; @@ -238,20 +271,52 @@ private void DrawParameter(ShaderGraphInputSettings input) }); if (range) { - m_inspection.properties.DrawValue(m_inspection.editorContext, draft, "shader.parameter." + property.id.value + ".minimum", "Minimum", typeof(double), () => presentation.minimum, value => + m_inspection.properties.DrawValue( + m_inspection.editorContext, + draft, + "shader.parameter." + + property.id.value + + ".minimum", + "Minimum", + typeof(double), + () => presentation.minimum, + value => { if (!double.IsFinite((double)value!)) + { return; + } presentation.minimum = Math.Clamp((double)value!, -float.MaxValue, presentation.maximum); SavePresentation(true); - }, new ParameterEdits(this), draft.readOnly, minimum: -float.MaxValue, maximum: presentation.maximum); - m_inspection.properties.DrawValue(m_inspection.editorContext, draft, "shader.parameter." + property.id.value + ".maximum", "Maximum", typeof(double), () => presentation.maximum, value => + }, + new ParameterEdits(this), + draft.readOnly, + minimum: -float.MaxValue, + maximum: presentation.maximum + ); + m_inspection.properties.DrawValue( + m_inspection.editorContext, + draft, + "shader.parameter." + + property.id.value + + ".maximum", + "Maximum", + typeof(double), + () => presentation.maximum, + value => { if (!double.IsFinite((double)value!)) + { return; + } presentation.maximum = Math.Clamp((double)value!, presentation.minimum, float.MaxValue); SavePresentation(true); - }, new ParameterEdits(this), draft.readOnly, minimum: presentation.minimum, maximum: float.MaxValue); + }, + new ParameterEdits(this), + draft.readOnly, + minimum: presentation.minimum, + maximum: float.MaxValue + ); EditorUI.current.widgets.Hint("Editing bounds only · existing defaults and overrides are not clamped on display"); } } @@ -266,9 +331,9 @@ private void DrawParameter(ShaderGraphInputSettings input) void SavePresentation(bool continuous) { Gesture(); - GraphDocument candidate = Controller.document.Clone(); + GraphDocument candidate = controller.document.Clone(); ShaderParameterPresentation.Write(candidate, property.id, presentation, owner.serialization, owner.context); - Controller.ReplaceDocument(candidate, "Edit Parameter Presentation", continuous ? EditorUI.current.widgets.editMergeKey : null); + controller.ReplaceDocument(candidate, "Edit Parameter Presentation", continuous ? EditorUI.current.widgets.editMergeKey : null); owner.Changed(draft); } @@ -281,9 +346,23 @@ bool continuous } } - private sealed class ParameterEdits(ShaderEditorCanvas canvas) : Inno.Editor.Inspection.IInspectionPropertyEditService + private void CommitDefinition( + ShaderDefinition definition, + string label, + bool continuous = false + ) { + GraphDocument candidate = controller.document.Clone(); + candidate.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(owner.serialization.Serialize(definition, owner.context), owner.serialization, owner.context) + ); + controller.ReplaceDocument(candidate, label, continuous ? EditorUI.current.widgets.editMergeKey : null); + owner.Changed(draft); + } + + private sealed class ParameterEdits(ShaderEditorCanvas canvas) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, @@ -297,18 +376,4 @@ public bool ChangeProperty( return true; } } - - private void CommitDefinition( - ShaderDefinition definition, - string label, - bool continuous = false - ) { - GraphDocument candidate = Controller.document.Clone(); - candidate.SetMetadata( - ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(owner.serialization.Serialize(definition, owner.context), owner.serialization, owner.context) - ); - Controller.ReplaceDocument(candidate, label, continuous ? EditorUI.current.widgets.editMergeKey : null); - owner.Changed(draft); - } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs index 87d5b9fab..f414a2f1b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs @@ -1,26 +1,32 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Core.Graphs; +using Inno.Editor.ImGui; using Inno.Rendering; +using Inno.Rendering.Assets; using Inno.Rendering.Shaders; + using EditorImGui = Inno.Editor.ImGui.ImGui; -using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void StageSettingsPopup( GraphNodeRecord node, ShaderGraphStageSettings stage ) { - EditorImGui.SetNextWindowSize(new(540, 600), (ImGuiCond.Appearing)); + EditorImGui.SetNextWindowSize(new Vector2(540, 600), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##stage-settings")) + { return; + } try { - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, owner.serialization, owner.context); bool definitionChanged = false; EditorImGui.SeparatorText("Shader"); string name = definition.name; @@ -34,22 +40,30 @@ ShaderGraphStageSettings stage Gesture(); EditorImGui.SeparatorText(stage.stage + " Interface"); - ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(Controller.document, owner.serialization, owner.context); + ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(controller.document, owner.serialization, owner.context); string activePass = draft.inspectedPass; if (!definition.passes.Any(pass => pass.name == activePass)) - activePass = programs.FirstOrDefault(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).pass ?? definition.passes.FirstOrDefault().name ?? ""; + { + activePass = programs.FirstOrDefault(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).pass + ?? definition.passes.FirstOrDefault().name + ?? string.Empty; + } InspectorRow("settings.pass", "Pass State", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##pass-state", activePass)) + { return; + } try { foreach (ShaderPassDefinition available in definition.passes) + { if (EditorImGui.Selectable(available.name, activePass == available.name)) { activePass = available.name; draft.inspectedPass = activePass; } + } } finally { @@ -60,23 +74,40 @@ ShaderGraphStageSettings stage bool assigned = assignment.stages?.Contains(node.id.value, StringComparer.Ordinal) == true; bool assignmentChanged = false; if (activePass.Length != 0) - InspectorRow("settings.shared-stage", "Shared Stage", () => assignmentChanged = EditorImGui.Checkbox("##shared-stage", ref assigned)); + { + InspectorRow( + "settings.shared-stage", + "Shared Stage", + () => assignmentChanged = EditorImGui.Checkbox("##shared-stage", ref assigned) + ); + } if (assignmentChanged) { - var stageIds = (assignment.stages ?? []).Where(id => id != node.id.value).Select(static id => new GraphNodeId(id)).ToList(); + List stageIDs = (assignment.stages ?? []) + .Where(id => id != node.id.value) + .Select(static id => new GraphNodeID(id)) + .ToList(); if (assigned) { - stageIds.RemoveAll(id => Controller.document.FindNode(id) is GraphNodeRecord existing && Read(existing, "settings", new ShaderGraphStageSettings()).stage == stage.stage); - stageIds.Add(node.id); + stageIDs.RemoveAll( + id => ( + controller.document.FindNode(id) is GraphNodeRecord existing + && Read(existing, "settings", new ShaderGraphStageSettings()).stage == stage.stage + ) + ); + stageIDs.Add(node.id); } - Controller.ReplaceDocument(ShaderGraphPrograms.Bind(Controller.document, activePass, stageIds, owner.serialization, owner.context), "Assign Shared Shader Stage"); + controller.ReplaceDocument( + ShaderGraphPrograms.Bind(controller.document, activePass, stageIDs, owner.serialization, owner.context), + "Assign Shared Shader Stage" + ); owner.Changed(draft); } for (int i = 0; i < stage.outputs.Length; i++) { - EditorImGui.PushId(i); + EditorImGui.PushID(i); try { ShaderGraphOutput output = stage.outputs[i]; @@ -98,9 +129,13 @@ ShaderGraphStageSettings stage changed = true; } - string semantic = output.semantic ?? ""; + string semantic = output.semantic ?? string.Empty; bool semanticChanged = false; - InspectorRow("output.semantic", "Semantic", () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 128)); + InspectorRow( + "output.semantic", + "Semantic", + () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 128) + ); if (semanticChanged) { output.semantic = semantic; @@ -110,7 +145,11 @@ ShaderGraphStageSettings stage Gesture(); int location = output.location; bool locationChanged = false; - InspectorRow("output.location", "Location", () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0)); + InspectorRow( + "output.location", + "Location", + () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0) + ); if (locationChanged) { output.location = location; @@ -138,20 +177,22 @@ ShaderGraphStageSettings stage } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } if (CenteredAddButton("Add Output")) { - stage.outputs = [..stage.outputs, new() - { - id = "output-" + Guid.NewGuid().ToString("N"), - kind = stage.stage == ShaderStage.Vertex ? ShaderIrOutputKind.Varying : ShaderIrOutputKind.Color, - semantic = "texcoord", - location = stage.outputs.Length - } - + stage.outputs = + [ + ..stage.outputs, + new ShaderGraphOutput() + { + id = "output-" + Guid.NewGuid().ToString("N"), + kind = stage.stage == ShaderStage.Vertex ? ShaderIrOutputKind.Varying : ShaderIrOutputKind.Color, + semantic = "texcoord", + location = stage.outputs.Length + } ]; Set(node, "settings", stage); } @@ -190,10 +231,20 @@ ShaderGraphStageSettings stage changed = true; } - bool depthWrite = state.depthWrite, multisampling = state.multisampling; - bool depthWriteChanged = false, multisamplingChanged = false; - InspectorRow("state.depth-write", "Depth Write", () => depthWriteChanged = EditorImGui.Checkbox("##depth-write", ref depthWrite)); - InspectorRow("state.multisampling", "Multisampling", () => multisamplingChanged = EditorImGui.Checkbox("##multisampling", ref multisampling)); + bool depthWrite = state.depthWrite; + bool multisampling = state.multisampling; + bool depthWriteChanged = false; + bool multisamplingChanged = false; + InspectorRow( + "state.depth-write", + "Depth Write", + () => depthWriteChanged = EditorImGui.Checkbox("##depth-write", ref depthWrite) + ); + InspectorRow( + "state.multisampling", + "Multisampling", + () => multisamplingChanged = EditorImGui.Checkbox("##multisampling", ref multisampling) + ); if (depthWriteChanged) { state.depthWrite = depthWrite; @@ -209,7 +260,9 @@ ShaderGraphStageSettings stage InspectorRow("state.blend-preset", "Blend Preset", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##blend-preset", state.blend.enabled ? "Blended" : "Opaque")) + { return; + } try { if (EditorImGui.Selectable("Opaque")) @@ -243,7 +296,11 @@ ShaderGraphStageSettings stage }); int mask = state.colorWriteMask; bool maskChanged = false; - InspectorRow("state.write-mask", "RGBA Write Mask", () => maskChanged = EditorImGui.InputInt("##write-mask", ref mask, 1, 100, 0)); + InspectorRow( + "state.write-mask", + "RGBA Write Mask", + () => maskChanged = EditorImGui.InputInt("##write-mask", ref mask, 1, 100, 0) + ); if (maskChanged) { state.colorWriteMask = (byte)Math.Clamp(mask, 0, 15); @@ -262,8 +319,12 @@ ShaderGraphStageSettings stage changed = true; } - RenderBlendFactor colorSource = blend.colorSource, colorDestination = blend.colorDestination, alphaSource = blend.alphaSource, alphaDestination = blend.alphaDestination; - RenderBlendEquation colorEquation = blend.colorEquation, alphaEquation = blend.alphaEquation; + RenderBlendFactor colorSource = blend.colorSource; + RenderBlendFactor colorDestination = blend.colorDestination; + RenderBlendFactor alphaSource = blend.alphaSource; + RenderBlendFactor alphaDestination = blend.alphaDestination; + RenderBlendEquation colorEquation = blend.colorEquation; + RenderBlendEquation alphaEquation = blend.alphaEquation; if (EnumControl("RGB Source", ref colorSource)) { blend.colorSource = colorSource; @@ -324,7 +385,7 @@ ShaderGraphStageSettings stage { for (int i = 0; i < definition.keywords.Length; i++) { - EditorImGui.PushId("keyword-" + i); + EditorImGui.PushID("keyword-" + i); try { ShaderKeywordDefinition keyword = definition.keywords[i]; @@ -341,7 +402,8 @@ ShaderGraphStageSettings stage for (int j = 0; j < keyword.options.Length; j++) { string option = keyword.options[j]; - bool optionChanged = false, remove = false; + bool optionChanged = false; + bool remove = false; InspectorRow("variant.option", "Option " + (j + 1), () => { optionChanged = EditorImGui.InputText("##option", ref option, 128); @@ -385,25 +447,29 @@ ShaderGraphStageSettings stage } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } if (CenteredAddButton("Add Keyword")) { - definition.keywords = [..definition.keywords, new("Keyword" + definition.keywords.Length, ["Off", "On"])]; + definition.keywords = + [ + ..definition.keywords, + new ShaderKeywordDefinition("Keyword" + definition.keywords.Length, ["Off", "On"]) + ]; definitionChanged = true; } } if (definitionChanged) { - GraphDocument candidate = Controller.document.Clone(); + GraphDocument candidate = controller.document.Clone(); candidate.SetMetadata( - ShaderGraphDocument.definitionKey, + ShaderGraphDocument.C_DEFINITION_KEY, ShaderGraphDocument.Encode(owner.serialization.Serialize(definition, owner.context), owner.serialization, owner.context) ); - Controller.ReplaceDocument(candidate, "Edit Shader Settings", EditorImGui.IsAnyItemActive() ? draft.valueGesture : null); + controller.ReplaceDocument(candidate, "Edit Shader Settings", EditorImGui.IsAnyItemActive() ? draft.valueGesture : null); owner.Changed(draft); } } @@ -416,23 +482,26 @@ ShaderGraphStageSettings stage private bool EnumControl( string label, ref T value - ) - where T : struct, Enum + ) where T : struct, Enum { bool changed = false; T current = value; InspectorRow("enum." + label, label, () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##enum", current.ToString())) + { return; + } try { foreach (T candidate in Enum.GetValues()) + { if (EditorImGui.Selectable(candidate.ToString(), candidate.Equals(current))) { current = candidate; changed = true; } + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs index 54cb928bc..c0bc0ac6d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs @@ -1,51 +1,80 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Core.Graphs; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void RepairPorts(GraphNodeRecord node) { - GraphEndpoint[] missing = draft.missingPorts.Where(endpoint => endpoint.nodeId == node.id).ToArray(); + GraphEndpoint[] missing = draft.missingPorts.Where(endpoint => endpoint.nodeID == node.id).ToArray(); if (missing.Length == 0) + { return; + } if (ImGuiApi.SmallButton("Repair Ports…")) + { ImGuiApi.OpenPopup("##repair-ports"); + } if (!ImGuiApi.BeginPopup("##repair-ports")) + { return; + } try { - EditorUI.current.widgets.WrappedText("Removed ports retain their connections. Choose a replacement explicitly; occupied inputs are not overwritten."); + EditorUI.current.widgets.WrappedText( + "Removed ports retain their connections. Choose a replacement explicitly; occupied inputs are not overwritten." + ); foreach (GraphEndpoint endpoint in missing) { ShaderNodePort old = Port(endpoint); - ImGuiApi.PushId(endpoint.portId.value); + ImGuiApi.PushID(endpoint.portID.value); try { - ImGuiApi.Text(endpoint.portId.value + " · " + old.type.id); + ImGuiApi.Text(endpoint.portID.value + " · " + old.type.id); if (!EditorUI.current.widgets.BeginBoundedCombo("##replacement", "Reconnect to…")) + { continue; + } foreach (ShaderNodePort replacement in draft.ports[node.id]) { - var target = new GraphEndpoint(node.id, new(replacement.id)); + var target = new GraphEndpoint(node.id, new GraphPortID(replacement.id)); if (replacement.direction != old.direction || draft.missingPorts.Contains(target)) + { continue; - bool occupied = replacement.direction == GraphPortDirection.Input && Controller.document.edges.Any(edge => edge.input == target); - bool compatible = old.type.id == "missing" || replacement.type.id == "any" || old.type.IsEquivalentTo(replacement.type); + } + bool occupied = replacement.direction == GraphPortDirection.Input + && controller.document.edges.Any(edge => edge.input == target); + bool compatible = old.type.id == "missing" + || replacement.type.id == "any" + || old.type.IsEquivalentTo(replacement.type); ImGuiApi.BeginDisabled(occupied || !compatible); - bool selected = ImGuiApi.Selectable(replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : "")); + bool selected = ImGuiApi.Selectable( + replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : string.Empty) + ); ImGuiApi.EndDisabled(); if (!selected) - continue; - GraphDocument candidate = Controller.document.Clone(); - foreach (GraphEdgeRecord edge in candidate.edges.Where(edge => edge.input == endpoint || edge.output == endpoint).ToArray()) { + continue; + } + GraphDocument candidate = controller.document.Clone(); + foreach (GraphEdgeRecord edge in candidate.edges + .Where(edge => edge.input == endpoint || edge.output == endpoint) + .ToArray() + ) { candidate.RemoveEdge(edge.id); - candidate.AddEdge(new(edge.id, edge.output == endpoint ? target : edge.output, edge.input == endpoint ? target : edge.input)); + candidate.AddEdge( + new GraphEdgeRecord( + edge.id, + edge.output == endpoint ? target : edge.output, + edge.input == endpoint ? target : edge.input + ) + ); } // Keep the retired declaration in metadata for a future source restoration and Undo. @@ -53,7 +82,7 @@ private void RepairPorts(GraphNodeRecord node) ShaderEditorDocuments.C_PORT_SNAPSHOT, ShaderGraphDocument.Encode(draft.portSnapshots[node.id], owner.serialization, owner.context) ); - Controller.ReplaceDocument(candidate, "Reconnect Shader Port"); + controller.ReplaceDocument(candidate, "Reconnect Shader Port"); owner.Changed(draft); break; } @@ -62,7 +91,7 @@ private void RepairPorts(GraphNodeRecord node) } finally { - ImGuiApi.PopId(); + ImGuiApi.PopID(); } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs index 9e711558a..17afc00dc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs @@ -1,61 +1,81 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.IO; using System.Linq; +using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.ImGui; using Inno.Rendering.Assets; -using EditorImGui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets.Authoring; +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { - private void SourceSettings(Guid sourceId) + private void SourceSettings(Guid sourceID) { - if (!owner.assets.TryGetInfo(sourceId, out AssetInfo? info) || info is null) + if (!owner.assets.TryGetInfo(sourceID, out AssetInfo? info) || info is null) + { return; + } InspectorRow("source.actions", "Source", () => { if (EditorImGui.SmallButton("Show in File Browser") - && owner.interactions.TryGetModule(out var browser) - && browser is not null) - RevealShaderFunction.Reveal(owner, browser, sourceId); + && owner.interactions.TryGetModule(out AssetBrowserModule? browser) + && browser is not null + ) { + RevealShaderFunction.Reveal(owner, browser, sourceID); + } EditorImGui.SameLine(0f, -1f); if (EditorImGui.SmallButton("Import Settings…")) { - LoadSourceSettings(info.assetPath, sourceId); + LoadSourceSettings(info.assetPath, sourceID); EditorImGui.OpenPopup("##source-settings"); } }); - EditorImGui.SetNextWindowSize(new(580, 470), (ImGuiCond.Appearing)); + EditorImGui.SetNextWindowSize(new Vector2(580, 470), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##source-settings")) + { return; + } try { EditorImGui.Text(info.assetPath.ToString()); EditorImGui.Separator(); - if (draft.settingsSource != sourceId) - LoadSourceSettings(info.assetPath, sourceId); + if (draft.settingsSource != sourceID) + { + LoadSourceSettings(info.assetPath, sourceID); + } bool readOnly = !owner.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) || entry.isReadOnly; EditorImGui.BeginDisabled(readOnly); try { - var settings = owner.serialization.Deserialize(draft.sourceSettings, owner.context); + ShaderSourceImportSettings settings = owner.serialization.Deserialize( + draft.sourceSettings, + owner.context + ); bool changed = false; InspectorRow("source.language", "Language", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##language", settings.languageId)) + { return; + } try { - foreach (string language in owner.frontends.languageIds) + foreach (string language in owner.frontends.languageIDs) + { if (EditorImGui.Selectable(language, settings.languageId == language)) { settings.languageId = language; changed = true; } + } } finally { @@ -64,7 +84,11 @@ private void SourceSettings(Guid sourceId) }); string implementation = settings.implementationId; bool implementationChanged = false; - InspectorRow("source.adapter", "Adapter", () => implementationChanged = EditorImGui.InputText("##adapter", ref implementation, 256)); + InspectorRow( + "source.adapter", + "Adapter", + () => implementationChanged = EditorImGui.InputText("##adapter", ref implementation, 256) + ); if (implementationChanged) { settings.implementationId = implementation; @@ -82,22 +106,29 @@ private void SourceSettings(Guid sourceId) int catalogOrder = settings.catalogOrder; bool orderChanged = false; - InspectorRow("source.catalog-order", "Catalog Order", () => orderChanged = EditorImGui.InputInt("##catalog-order", ref catalogOrder, 1, 100, 0)); + InspectorRow( + "source.catalog-order", + "Catalog Order", + () => orderChanged = EditorImGui.InputInt("##catalog-order", ref catalogOrder, 1, 100, 0) + ); if (orderChanged) { settings.catalogOrder = catalogOrder; changed = true; } - EditorUI.current.widgets.WrappedText("Catalog paths are declared by the source library and group its exported functions in Shader creation tools. They do not affect compilation or runtime assets."); + EditorUI.current.widgets.WrappedText( + "Catalog paths are declared by the source library and group its exported functions in Shader creation tools. They do not affect compilation or runtime assets." + ); EditorImGui.SeparatorText("Exported Functions"); for (int i = 0; i < settings.exports.Length; i++) { - EditorImGui.PushId("export." + i); + EditorImGui.PushID("export." + i); try { string function = settings.exports[i]; - bool functionChanged = false, remove = false; + bool functionChanged = false; + bool remove = false; InspectorRow("source.export", "Function " + (i + 1), () => { functionChanged = EditorImGui.InputText("##name", ref function, 256); @@ -122,7 +153,7 @@ private void SourceSettings(Guid sourceId) } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } @@ -132,37 +163,43 @@ private void SourceSettings(Guid sourceId) changed = true; } - EditorUI.current.widgets.WrappedText("Every listed name is exported as an independent graph function. All other functions remain private helpers. Ports are parsed from each exported declaration; alternative implementations must expose matching interfaces."); + EditorUI.current.widgets.WrappedText( + "Every listed name is exported as an independent graph function. All other functions remain private helpers. Ports are parsed from each exported declaration; alternative implementations must expose matching interfaces." + ); EditorImGui.SeparatorText("Alternative Implementations"); for (int i = 0; i < settings.implementations.Length; i++) { - EditorImGui.PushId(i); + EditorImGui.PushID(i); try { ShaderFunctionAsset? current = settings.implementations[i]; bool remove = false; InspectorRow("source.implementation", "Implementation " + (i + 1), () => { - if (EditorUI.current.widgets.BeginBoundedCombo("##implementation", current?.assetPath.ToString() ?? "Missing source")) - { + if (EditorUI.current.widgets.BeginBoundedCombo( + "##implementation", + current?.assetPath.ToString() ?? "Missing source" + )) { try { foreach (AssetFileEntry source in owner.assets.GetFileSystemEntries(includeDirectories: false)) + { if (source.extension == ".ishadersource" && source.assetPath != info.assetPath && EditorImGui.Selectable( - source.assetPath.ToString(), - current?.assetPath == source.assetPath - ) + source.assetPath.ToString(), + current?.assetPath == source.assetPath + ) && owner.assets.TryLoad( - source.assetPath, - out ShaderFunctionAsset? replacement - ) - && replacement is not null) - { + source.assetPath, + out ShaderFunctionAsset? replacement + ) + && replacement is not null + ) { settings.implementations[i] = replacement; changed = true; } + } } finally { @@ -185,7 +222,7 @@ out ShaderFunctionAsset? replacement } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } @@ -196,12 +233,14 @@ out ShaderFunctionAsset? replacement } if (changed) + { draft.sourceSettings = owner.serialization.Serialize(settings, owner.context); + } EditorImGui.Separator(); if (EditorImGui.Button("Apply Import Settings")) { bool imported = owner.importSettings.Apply(info.assetPath, settings, draft.sourceSettingsFingerprint); - LoadSourceSettings(info.assetPath, sourceId); + LoadSourceSettings(info.assetPath, sourceID); draft.sourceSettingsStatus = imported ? "Applied · ports refreshed" : "Settings saved · import failed; see diagnostics"; draft.portRevision = ulong.MaxValue; } @@ -213,14 +252,23 @@ out ShaderFunctionAsset? replacement EditorImGui.SameLine(0f, -1f); if (EditorImGui.Button("Reload")) - LoadSourceSettings(info.assetPath, sourceId); + { + LoadSourceSettings(info.assetPath, sourceID); + } if (readOnly) - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Installed source settings are read-only."); + { + EditorUI.current.widgets.ColoredText( + EditorPalette.textDisabled, + "Installed source settings are read-only." + ); + } if (draft.sourceSettingsStatus.Length != 0) + { EditorUI.current.widgets.WrappedText(draft.sourceSettingsStatus); + } } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.sourceSettingsStatus = failure.Message; EditorUI.current.widgets.WrappedText(draft.sourceSettingsStatus); @@ -233,14 +281,16 @@ out ShaderFunctionAsset? replacement private void LoadSourceSettings( AssetPath path, - Guid sourceId + Guid sourceID ) { AssetImportSettingsSnapshot snapshot = owner.assets.GetImportSettings(path); if (snapshot.value is not ShaderSourceImportSettings settings) + { throw new InvalidOperationException("The source importer settings are unavailable."); - draft.settingsSource = sourceId; + } + draft.settingsSource = sourceID; draft.sourceSettingsFingerprint = snapshot.fingerprint; draft.sourceSettings = owner.serialization.Serialize(settings, owner.context); - draft.sourceSettingsStatus = ""; + draft.sourceSettingsStatus = string.Empty; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs index 90888483c..5ce259b75 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs @@ -1,29 +1,41 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Core.Graphs; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void DrawTarget() { - string current = ShaderGraphDocument.ReadTarget(Controller.document, owner.serialization, owner.context); + string current = ShaderGraphDocument.ReadTarget(controller.document, owner.serialization, owner.context); ImGuiApi.BeginDisabled(draft.readOnly); try { InspectorRow("target", "Target", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##target", current.Length == 0 ? "Explicit Stages" : current)) + { return; + } try { if (ImGuiApi.Selectable("Explicit Stages", current.Length == 0)) - Assign(""); + { + Assign(string.Empty); + } if (owner.targets is { } targets) + { foreach (string id in targets.ids) + { if (ImGuiApi.Selectable(id, current == id)) + { Assign(id); + } + } + } } finally { @@ -39,10 +51,12 @@ private void DrawTarget() void Assign(string id) { if (id == current) + { return; - GraphDocument candidate = Controller.document.Clone(); + } + GraphDocument candidate = controller.document.Clone(); ShaderGraphDocument.SetTarget(candidate, id, owner.serialization, owner.context); - Controller.ReplaceDocument(candidate, "Change Shader Target"); + controller.ReplaceDocument(candidate, "Change Shader Target"); owner.Changed(draft); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs index 1d3d1d50b..6538160f6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs @@ -1,26 +1,33 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Rendering; -using EditorImGui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private bool TechniqueControls(ShaderDefinition definition) { if (!EditorImGui.CollapsingHeader("Techniques & Roles")) + { return false; - EditorUI.current.widgets.WrappedText("Techniques map pipeline-defined roles to this shader's passes. Contract and role identities are supplied by the rendering pipeline."); + } + EditorUI.current.widgets.WrappedText( + "Techniques map pipeline-defined roles to this shader's passes. Contract and role identities are supplied by the rendering pipeline." + ); bool changed = false; for (int i = 0; i < definition.techniques.Length; i++) { - EditorImGui.PushId("technique-" + i); + EditorImGui.PushID("technique-" + i); try { ShaderTechniqueDefinition technique = definition.techniques[i]; - string id = technique.id.value ?? "", contract = technique.contract.value ?? ""; + string id = technique.id.value ?? string.Empty; + string contract = technique.contract.value ?? string.Empty; bool idChanged = false; InspectorRow("technique.id", "ID", () => idChanged = EditorImGui.InputText("##id", ref id, 128)); if (idChanged) @@ -34,7 +41,11 @@ private bool TechniqueControls(ShaderDefinition definition) Gesture(); bool contractChanged = false; - InspectorRow("technique.contract", "Contract", () => contractChanged = EditorImGui.InputText("##contract", ref contract, 256)); + InspectorRow( + "technique.contract", + "Contract", + () => contractChanged = EditorImGui.InputText("##contract", ref contract, 256) + ); if (contractChanged) { technique.contract = new() @@ -54,11 +65,11 @@ private bool TechniqueControls(ShaderDefinition definition) for (int j = 0; j < technique.passes.Length; j++) { - EditorImGui.PushId(j); + EditorImGui.PushID(j); try { ShaderTechniquePass mapping = technique.passes[j]; - string role = mapping.role.value ?? ""; + string role = mapping.role.value ?? string.Empty; bool roleChanged = false; InspectorRow("technique.role", "Role", () => roleChanged = EditorImGui.InputText("##role", ref role, 128)); if (roleChanged) @@ -75,15 +86,19 @@ private bool TechniqueControls(ShaderDefinition definition) InspectorRow("technique.pass", "Pass", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##pass", mapping.passName)) + { return; + } try { foreach (ShaderPassDefinition pass in definition.passes) + { if (EditorImGui.Selectable(pass.name, pass.name == mapping.passName)) { mapping.passName = pass.name; passChanged = true; } + } } finally { @@ -104,18 +119,20 @@ private bool TechniqueControls(ShaderDefinition definition) } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } if (CenteredAddButton("Add Role")) { - technique.passes = [..technique.passes, new() - { - role = new("role-" + technique.passes.Length), - passName = definition.passes.FirstOrDefault().name ?? "" - } - + technique.passes = + [ + ..technique.passes, + new ShaderTechniquePass() + { + role = new("role-" + technique.passes.Length), + passName = definition.passes.FirstOrDefault().name ?? string.Empty + } ]; changed = true; } @@ -135,19 +152,21 @@ private bool TechniqueControls(ShaderDefinition definition) } finally { - EditorImGui.PopId(); + EditorImGui.PopID(); } } if (CenteredAddButton("Add Technique")) { - definition.techniques = [..definition.techniques, new() - { - id = new("technique-" + Guid.NewGuid().ToString("N")), - contract = default, - passes = [] - } - + definition.techniques = + [ + ..definition.techniques, + new ShaderTechniqueDefinition() + { + id = new("technique-" + Guid.NewGuid().ToString("N")), + contract = default, + passes = [] + } ]; changed = true; } @@ -158,7 +177,9 @@ private bool TechniqueControls(ShaderDefinition definition) private static bool FeatureControls(ref GraphicsCapability features) { if (!EditorImGui.TreeNode("Required Capabilities", 0)) + { return false; + } try { bool changed = false; @@ -167,10 +188,16 @@ private static bool FeatureControls(ref GraphicsCapability features) { ulong bits = Convert.ToUInt64(feature); if (bits == 0 || (bits & (bits - 1)) != 0) + { continue; + } bool enabled = (updated & feature) != 0; bool featureChanged = false; - InspectorRow("feature." + feature, feature.ToString(), () => featureChanged = EditorImGui.Checkbox("##enabled", ref enabled)); + InspectorRow( + "feature." + feature, + feature.ToString(), + () => featureChanged = EditorImGui.Checkbox("##enabled", ref enabled) + ); if (featureChanged) { updated = enabled ? updated | feature : updated & ~feature; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs index 2cd28d719..18971b3fe 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs @@ -1,33 +1,33 @@ -using Inno.Editor.Core; -using Inno.Editor.Graph.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Numerics; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; +using Inno.Editor.Core; using Inno.Editor.Graph; +using Inno.Editor.Graph.ImGui; using Inno.Editor.ImGui; +using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas( ShaderEditorDocuments owner, ShaderEditorDocuments.Draft draft ) { - private readonly record struct PortHandle( - GraphEndpoint endpoint, - GraphPortDirection direction - ); internal const string C_AREA = "panel/rendering.shader-editor"; - private static readonly Vector4 C_EMPTY_GROUP_HEADER = new(0.16f, 0.17f, 0.20f, EditorPalette.opacityOpaque); private const string C_NODE_WIDTH = "editor.width"; private const float C_DEFAULT_WIDTH = 270f; private const float C_MINIMUM_WIDTH = 180f; @@ -35,12 +35,14 @@ GraphPortDirection direction private const float C_HEADER = 32f; private const float C_ROW = 24f; private const float C_RESIZE_HANDLE = 14f; - private GraphDocumentController Controller => owner.Controller(draft); - private GraphCanvasState Canvas => draft.canvas; - private GraphCanvasView View => new(Canvas, m_origin, m_size); + + private static readonly Vector4 EMPTY_GROUP_HEADER = new(0.16f, 0.17f, 0.2f, EditorPalette.C_OPACITY_OPAQUE); private Vector2 m_origin; private Vector2 m_size; + private GraphNodeRecord[]? m_inspectionNodes; + private InspectionDrawContext? m_inspection; + internal void Draw() { DrawHeader(owner, draft); @@ -57,7 +59,11 @@ internal void Draw() } ImGuiApi.SetNextItemAllowOverlap(); - _ = ImGuiApi.InvisibleButton("##shader-canvas", m_size, (ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonMiddle | ImGuiButtonFlags.MouseButtonRight)); + _ = ImGuiApi.InvisibleButton( + "##shader-canvas", + m_size, + (ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonMiddle | ImGuiButtonFlags.MouseButtonRight) + ); bool hovered = ImGuiApi.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); Vector2 mouse = ImGuiApi.GetMousePos(); bool miniMapHovered = MiniMapContains(mouse); @@ -68,16 +74,20 @@ internal void Draw() ShaderCanvasGroup? hitGroup = HitGroupHeader(mouse); if (hitGroup is ShaderCanvasGroup group) { - draft.selectedGroupId = group.id; - Canvas.SelectNodes(group.nodes.Select(static id => new GraphNodeId(id))); + draft.selectedGroupID = group.id; + canvas.SelectNodes(group.nodes.Select(static id => new GraphNodeID(id))); } GraphNodeRecord? hit = hitGroup is null ? HitNode(mouse) : null; draft.selectedEdge = hit is null ? HitEdge(mouse) : null; if (draft.selectedEdge is not null) - Canvas.ClearSelection(); - if (hit is not null && !Canvas.selectedNodes.Contains(hit.id)) - Canvas.SelectNodes([hit.id]); + { + canvas.ClearSelection(); + } + if (hit is not null && !canvas.selectedNodes.Contains(hit.id)) + { + canvas.SelectNodes([hit.id]); + } SetStage(hit); } @@ -85,7 +95,9 @@ internal void Draw() { EditorInteraction interaction = owner.interactions.For(C_AREA, entry); if (ImGuiApi.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows)) + { interaction.Focus(); + } _ = EditorUI.current.menus.ContextMenu("##shader-menu", interaction); } @@ -98,24 +110,29 @@ internal void Draw() Grid(draw); Groups(draw); Edges(draw); - foreach (GraphNodeRecord node in Controller.document.nodes) + foreach (GraphNodeRecord node in controller.document.nodes) + { Node(draw, node, mouse); + } Pointer(hovered && !miniMapHovered); if (draft.pointer.isBoxSelecting) { - Vector2 min = Vector2.Min(draft.pointer.boxStart, mouse), max = Vector2.Max(draft.pointer.boxStart, mouse); - draw.FilledRectangle(min, max, Color(0.52f, 0.37f, 0.78f, EditorPalette.opacitySubtle), 0, false); + Vector2 min = Vector2.Min(draft.pointer.boxStart, mouse); + Vector2 max = Vector2.Max(draft.pointer.boxStart, mouse); + draw.FilledRectangle(min, max, Color(0.52f, 0.37f, 0.78f, EditorPalette.C_OPACITY_SUBTLE), 0, false); draw.Rectangle(min, max, Color(0.65f, 0.47f, 0.88f), 0, 1f); } - string status = draft.readOnly ? "Read-only · copy to project to edit" : Controller.isDirty ? "Unsaved changes · Save to apply" : draft.status; + string status = draft.readOnly ? "Read-only · copy to project to edit" : controller.isDirty ? "Unsaved changes · Save to apply" : draft.status; status += " · Saved asset: " + draft.compilationStatus; { draw.Text(m_origin + new Vector2(12, 10), ImGuiApi.GetStyleColor(ImGuiCol.TextDisabled), status, 1f); } if (draft.compilationDiagnostics.Length != 0 && mouse.Y < m_origin.Y + 32 && hovered) + { EditorUI.current.widgets.DrawTooltip(draft.compilationDiagnostics); + } if (draft.error.Length != 0) { draw.Text(m_origin + new Vector2(12, 34), Color(1f, 0.47f, 0.44f), draft.error, 1f); @@ -134,18 +151,9 @@ internal void Draw() SynchronizeInspection(); } - private void SynchronizeInspection() - { - if (Canvas.selectedNodes.SequenceEqual(draft.inspectedNodes)) - return; - draft.inspectedNodes = Canvas.selectedNodes.ToArray(); - draft.inspectionSelection = new ShaderInspectionSelection(draft.id, draft.inspectedNodes); - owner.interactions.SetSelection(draft.inspectionSelection); - } - internal void DrawInspector( - Inno.Editor.Inspection.InspectionDrawContext inspection, - IReadOnlyList selected + InspectionDrawContext inspection, + IReadOnlyList selected ) { m_inspection = inspection; try @@ -158,15 +166,159 @@ IReadOnlyList selected } } - private void DrawInspectorContents(IReadOnlyList selected) + internal string Title(GraphNodeRecord node) + { + if (owner.drawers?.GetDisplayName(node.definitionID) is { } displayName) + { + return displayName; + } + if (node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + { + return Read(node, "settings", new ShaderGraphStageSettings()).stage + " Output"; + } + if (node.definitionID == "inno.shader.binary") + { + return EditorDisplayNames.Nicify(Read(node, "operation", "add").Replace('-', ' ')); + } + if (node.definitionID == "inno.shader.stage-input") + { + ShaderGraphInputSettings input = Read(node, "settings", new ShaderGraphInputSettings()); + return input.id.Length != 0 ? EditorDisplayNames.Nicify(input.id) : "Stage Input"; + } + + if (node.definitionID == "inno.shader.source") + { + string function = Read(node, "function", string.Empty); + return function.Length == 0 ? "Source Function" : function; + } + + if (node.definitionID == ShaderGraphNodes.C_CALL_DEFINITION_ID) + { + return Read(node, ShaderGraphNodes.C_INTERFACE_KEY, new ShaderGraphNodeInterface()).displayName; + } + if (node.definitionID == ShaderGraphNodes.C_INPUT_DEFINITION_ID) + { + return ShaderGraphNodes.ReadSettings( + controller.document, + owner.serialization, + owner.context + ).kind == ShaderGraphNodeKind.DomainOutput ? "Domain Inputs" : "Function Inputs"; + } + if (node.definitionID == ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) + { + return "Function Outputs"; + } + return EditorDisplayNames.Nicify( + node.definitionID.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') + ); + } + + internal static void DrawHeader( + ShaderEditorDocuments owner, + ShaderEditorDocuments.Draft? draft + ) { + ArgumentNullException.ThrowIfNull(owner); + EditorUI.current.widgets.HeaderSurface("##shader-header", () => + { + ImGuiApi.SetNextItemWidth(-1f); + string title = draft is null + ? "Select Shader" + : Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : string.Empty); + if (EditorUI.current.widgets.BeginBoundedCombo("##shader-header-select", title)) + { + try + { + foreach (AssetFileEntry candidate in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static candidate => candidate.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase)) + .OrderBy(static candidate => candidate.assetPath.ToString(), StringComparer.Ordinal) + ) { + bool selected = draft is not null && candidate.assetPath == draft.path; + if (ImGuiApi.Selectable(candidate.assetPath.ToString(), selected)) + { + owner.interactions.SetSelection(candidate); + _ = owner.Open(candidate); + } + + if (selected) + { + ImGuiApi.SetItemDefaultFocus(); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + } + + bool noDocument = draft is null; + ImGuiApi.BeginDisabled(noDocument || draft!.readOnly); + if (ImGuiApi.Button("Save") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) + { + _ = owner.interactions.For(C_AREA, entry).Execute("shader/save"); + } + EditorUI.current.widgets.DrawItemTooltip( + "Save this shader and apply its changes (Command/Ctrl + S). Invalid graphs can be saved; rendering retains the last successful programs." + ); + ImGuiApi.SameLine(0f, -1f); + if (ImGuiApi.Button("Revert") && draft is not null) + { + _ = owner.interactions.documents.Revert(draft.documentID); + } + EditorUI.current.widgets.DrawItemTooltip("Restore the saved shader. This draft change can be undone."); + ImGuiApi.EndDisabled(); + ImGuiApi.SameLine(0f, -1f); + ImGuiApi.BeginDisabled(noDocument); + if (ImGuiApi.Button("Format") + && draft is not null + && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry formatEntry) + ) { + _ = owner.interactions.For(C_AREA, formatEntry).Execute("shader/format"); + } + EditorUI.current.widgets.DrawItemTooltip( + "Arrange the graph from inputs on the left to outputs on the right. This changes only authoring positions and is undoable." + ); + ImGuiApi.SameLine(0f, -1f); + if (ImGuiApi.Button("Check") + && draft is not null + && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry checkEntry) + ) { + _ = owner.interactions.For(C_AREA, checkEntry).Execute("shader/check"); + } + EditorUI.current.widgets.DrawItemTooltip( + "Compile-check the current draft without saving or publishing it, and show diagnostics with source locations." + ); + ImGuiApi.EndDisabled(); + }, spanWindowPadding: true); + } + + private GraphDocumentController controller => owner.Controller(draft); + private GraphCanvasState canvas => draft.canvas; + private GraphCanvasView view => new(canvas, m_origin, m_size); + + private void SynchronizeInspection() + { + if (canvas.selectedNodes.SequenceEqual(draft.inspectedNodes)) + { + return; + } + draft.inspectedNodes = canvas.selectedNodes.ToArray(); + draft.inspectionSelection = new ShaderInspectionSelection(draft.id, draft.inspectedNodes); + owner.interactions.SetSelection(draft.inspectionSelection); + } + + private void DrawInspectorContents(IReadOnlyList selected) { RefreshPorts(); - bool graphNode = ShaderGraphNodes.IsNodeGraph(Controller.document); + bool graphNode = ShaderGraphNodes.IsNodeGraph(controller.document); if (!graphNode) { - if (EditorUI.current.widgets.SectionHeader("Preview", "The preview uses the current draft without publishing it to Scene or Game views.")) - { - var preview = owner.Preview(draft); + if (EditorUI.current.widgets.SectionHeader( + "Preview", + "The preview uses the current draft without publishing it to Scene or Game views." + )) { + EditorShaderDraftCompilationSnapshot? preview = owner.Preview(draft); if (preview is null) { EditorUI.current.widgets.Hint("Run Check to build a preview for the current draft."); @@ -176,14 +328,14 @@ private void DrawInspectorContents(IReadOnlyList selected) EditorUI.current.widgets.Hint("Shader check failed. See Console."); } else if (preview.state == EditorShaderCompilationState.Succeeded - && preview.artifact is not null - && owner.interactions.TryGetModule(out var images) - && images is not null) - { - var shader = owner.assets.Load(draft.path); + && preview.artifact is not null + && owner.interactions.TryGetModule(out ShaderPreviews? images) + && images is not null + ) { + ShaderAsset shader = owner.assets.Load(draft.path); images.Draw( draft.id, - new Inno.Rendering.Assets.MaterialAsset { shader = shader }, + new MaterialAsset { shader = shader }, preview, MathF.Max(1f, MathF.Min(256f, ImGuiApi.GetContentRegionAvailable().X)) ); @@ -195,18 +347,26 @@ private void DrawInspectorContents(IReadOnlyList selected) if (EditorUI.current.widgets.SectionHeader( "Graph Node", "Function Inputs and Function Outputs independently define the reusable typed interface. Check validates the interface; callers validate the inlined computation." - )) - { + )) { try { - ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface(Controller.document, owner.serialization, owner.context); + ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface( + controller.document, + owner.serialization, + owner.context + ); InspectorRow( "graph-node.summary", "Interface", - () => EditorUI.current.widgets.WrappedText($"{nodeInterface.inputs.Length} input(s) · {nodeInterface.outputs.Length} output(s) · {nodeInterface.kind}") + () => EditorUI.current.widgets.WrappedText( + $"{nodeInterface.inputs.Length} input(s) · {nodeInterface.outputs.Length} output(s) · {nodeInterface.kind}" + ) ); } - catch (Exception failure) when (failure is InvalidOperationException or ArgumentException or FormatException or NotSupportedException) + catch (Exception failure) when (failure is InvalidOperationException + or ArgumentException + or FormatException + or NotSupportedException) { EditorUI.current.widgets.Hint(failure.Message); } @@ -218,19 +378,26 @@ private void DrawInspectorContents(IReadOnlyList selected) if (EditorUI.current.widgets.SectionHeader( graphNode ? "Node Definition" : "Shader", graphNode ? "Select Function Inputs or Function Outputs to edit this reusable node's public interface." : "Target and public interface belong to this Shader, not to any Material override." - )) - { + )) { if (!graphNode) + { DrawTarget(); - if (Controller.document.metadata.ContainsKey(ShaderGraphDocument.definitionKey)) + } + if (controller.document.metadata.ContainsKey(ShaderGraphDocument.C_DEFINITION_KEY)) { - var definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); - foreach (var property in definition.properties) + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + controller.document, + owner.serialization, + owner.context + ); + foreach (ShaderPropertyDefinition property in definition.properties) + { InspectorRow( "definition." + property.id.value, property.displayName, () => EditorUI.current.widgets.WrappedText(property.type + " · " + property.bindingOwner) ); + } } owner.RefreshCompilation(draft); @@ -240,176 +407,156 @@ private void DrawInspectorContents(IReadOnlyList selected) return; } - GraphNodeRecord[] nodes = selected.Select(Controller.document.FindNode).OfType().ToArray(); + GraphNodeRecord[] nodes = selected.Select(controller.document.FindNode).OfType().ToArray(); if (nodes.Length != selected.Count) + { EditorUI.current.widgets.Hint("Some selected nodes are unavailable. Stable identities are retained."); + } if (nodes.Length == 0) + { return; - if (nodes.Any(node => node.definitionId != nodes[0].definitionId)) + } + if (nodes.Any(node => node.definitionID != nodes[0].definitionID)) { EditorUI.current.widgets.Hint("Select nodes of the same kind to edit common settings."); return; } m_inspectionNodes = nodes; - ImGuiApi.PushId(draft.id.ToString("N")); - ImGuiApi.PushId(nodes[0].id.value); + ImGuiApi.PushID(draft.id.ToString("N")); + ImGuiApi.PushID(nodes[0].id.value); ImGuiApi.BeginDisabled(draft.readOnly); try { if (EditorUI.current.widgets.SectionHeader( Title(nodes[0]), "Inputs, defaults and output configuration are edited here. Changes remain in the Shader draft until Save." - )) - { + )) { if (nodes.Length > 1) + { EditorUI.current.widgets.Hint("Editing " + nodes.Length + " nodes · differing values are replaced together"); + } Controls(nodes[0]); } ShaderNodePort[] inputs = draft.ports[nodes[0].id].Where(port => port.direction == GraphPortDirection.Input).ToArray(); if (inputs.Length != 0 && EditorUI.current.widgets.SectionHeader( - "Inputs", - "Connected inputs show their source. Optional inputs use an automatic zero; required inputs must be connected in the graph." - )) - { + "Inputs", + "Connected inputs show their source. Optional inputs use an automatic zero; required inputs must be connected in the graph." + ) + ) { foreach (ShaderNodePort port in inputs) + { DrawInputDefault(nodes[0], port); + } } } finally { ImGuiApi.EndDisabled(); - ImGuiApi.PopId(); - ImGuiApi.PopId(); + ImGuiApi.PopID(); + ImGuiApi.PopID(); m_inspectionNodes = null; } } - private GraphNodeRecord[]? m_inspectionNodes; - private Inno.Editor.Inspection.InspectionDrawContext? m_inspection; - private static void InspectorRow( - string id, - string label, - Action draw - ) => EditorUI.current.widgets.PropertyRow("shader." + id, label, draw); - internal static void DrawHeader( - ShaderEditorDocuments owner, - ShaderEditorDocuments.Draft? draft - ) { - ArgumentNullException.ThrowIfNull(owner); - EditorUI.current.widgets.HeaderSurface("##shader-header", () => - { - ImGuiApi.SetNextItemWidth(-1f); - string title = draft is null ? "Select Shader" : System.IO.Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : ""); - if (EditorUI.current.widgets.BeginBoundedCombo("##shader-header-select", title)) - { - try - { - foreach (AssetFileEntry candidate in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static candidate => candidate.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase)).OrderBy( - static candidate => candidate.assetPath.ToString(), - StringComparer.Ordinal - )) - { - bool selected = draft is not null && candidate.assetPath == draft.path; - if (ImGuiApi.Selectable(candidate.assetPath.ToString(), selected)) - { - owner.interactions.SetSelection(candidate); - _ = owner.Open(candidate); - } - - if (selected) - ImGuiApi.SetItemDefaultFocus(); - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - } - - bool noDocument = draft is null; - ImGuiApi.BeginDisabled(noDocument || draft!.readOnly); - if (ImGuiApi.Button("Save") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) - _ = owner.interactions.For(C_AREA, entry).Execute("shader/save"); - EditorUI.current.widgets.DrawItemTooltip("Save this shader and apply its changes (Command/Ctrl + S). Invalid graphs can be saved; rendering retains the last successful programs."); - ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.Button("Revert") && draft is not null) - _ = owner.interactions.documents.Revert(draft.documentId); - EditorUI.current.widgets.DrawItemTooltip("Restore the saved shader. This draft change can be undone."); - ImGuiApi.EndDisabled(); - ImGuiApi.SameLine(0f, -1f); - ImGuiApi.BeginDisabled(noDocument); - if (ImGuiApi.Button("Format") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry formatEntry)) - _ = owner.interactions.For(C_AREA, formatEntry).Execute("shader/format"); - EditorUI.current.widgets.DrawItemTooltip("Arrange the graph from inputs on the left to outputs on the right. This changes only authoring positions and is undoable."); - ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.Button("Check") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry checkEntry)) - _ = owner.interactions.For(C_AREA, checkEntry).Execute("shader/check"); - EditorUI.current.widgets.DrawItemTooltip("Compile-check the current draft without saving or publishing it, and show diagnostics with source locations."); - ImGuiApi.EndDisabled(); - }, spanWindowPadding: true); - } - private void RefreshPorts() { - if (draft.portRevision == Controller.revision && draft.assetRevision == owner.assets.revision && draft.typeRevision == owner.typeVersion) + if (draft.portRevision == controller.revision + && draft.assetRevision == owner.assets.revision + && draft.typeRevision == owner.typeVersion + ) { return; + } draft.ports.Clear(); draft.missingPorts.Clear(); draft.nodeErrors.Clear(); - foreach (GraphNodeRecord node in Controller.document.nodes) + foreach (GraphNodeRecord node in controller.document.nodes) { if (!draft.portSnapshots.ContainsKey(node.id)) + { draft.portSnapshots[node.id] = Read(node, ShaderEditorDocuments.C_PORT_SNAPSHOT, Array.Empty()); - var ports = new List(); + } + List ports = []; try { - if (node.definitionId == ShaderGraphDocument.outputDefinitionId) + if (node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) { ShaderGraphStageSettings settings = Read(node, "settings", new ShaderGraphStageSettings()); - ports.AddRange(settings.outputs.Select(static output => new ShaderNodePort(output.id, ShaderSourceType.Atomic(output.kind == ShaderIrOutputKind.Depth ? "float" : output.kind == ShaderIrOutputKind.Varying ? "any" : "float4"), GraphPortDirection.Input))); + ports.AddRange( + settings.outputs.Select( + static output => new ShaderNodePort( + output.id, + ShaderSourceType.Atomic( + output.kind == ShaderIrOutputKind.Depth + ? "float" + : output.kind == ShaderIrOutputKind.Varying ? "any" : "float4" + ), + GraphPortDirection.Input + ) + ) + ); } else + { ports.AddRange(owner.Describe(node)); + } } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.nodeErrors[node.id] = failure.Message; } foreach (ShaderPortSnapshot old in draft.portSnapshots[node.id]) + { if (!ports.Any(port => port.id == old.id)) { - ports.Add(new(old.id, old.type.CreateType(), old.direction, old.required)); - draft.missingPorts.Add(new(node.id, new(old.id))); + ports.Add(new ShaderNodePort(old.id, old.type.CreateType(), old.direction, old.required)); + draft.missingPorts.Add(new GraphEndpoint(node.id, new GraphPortID(old.id))); } + } - foreach (GraphEdgeRecord edge in Controller.document.edges) + foreach (GraphEdgeRecord edge in controller.document.edges) { - if (edge.input.nodeId == node.id) + if (edge.input.nodeID == node.id) + { KeepEndpoint(edge.input, GraphPortDirection.Input); - if (edge.output.nodeId == node.id) + } + if (edge.output.nodeID == node.id) + { KeepEndpoint(edge.output, GraphPortDirection.Output); + } } - draft.portSnapshots[node.id] = ports.Select(static port => new ShaderPortSnapshot { id = port.id, type = ShaderGraphType.Capture(port.type), direction = port.direction, required = port.required }).ToArray(); + draft.portSnapshots[node.id] = ports + .Select( + static port => new ShaderPortSnapshot + { + id = port.id, + type = ShaderGraphType.Capture(port.type), + direction = port.direction, + required = port.required + } + ) + .ToArray(); draft.ports.Add(node.id, ports.ToArray()); void KeepEndpoint( GraphEndpoint endpoint, GraphPortDirection direction ) { - if (ports.Any(port => port.id == endpoint.portId.value)) + if (ports.Any(port => port.id == endpoint.portID.value)) + { return; - ports.Add(new(endpoint.portId.value, ShaderSourceType.Atomic("missing"), direction, false)); + } + ports.Add(new ShaderNodePort(endpoint.portID.value, ShaderSourceType.Atomic("missing"), direction, false)); draft.missingPorts.Add(endpoint); } } - draft.portRevision = Controller.revision; - draft.groups = GroupShaderNodes.Read(owner, Controller.document); + draft.portRevision = controller.revision; + draft.groups = GroupShaderNodes.Read(owner, controller.document); draft.assetRevision = owner.assets.revision; draft.typeRevision = owner.typeVersion; owner.PublishNodeDiagnostics(draft); @@ -423,7 +570,7 @@ private void Navigate(bool hovered) draft.navigation.Cancel(); return; } - EditorUiInput io = ImGuiApi.GetInput(); + EditorUIInput io = ImGuiApi.GetInput(); draft.navigation.Update( hovered, ImGuiApi.IsMouseClicked(ImGuiMouseButton.Left), @@ -434,7 +581,7 @@ private void Navigate(bool hovered) ); if (draft.navigation.isPanning) { - Canvas.PanBy(io.mouseDelta.X, io.mouseDelta.Y); + canvas.PanBy(io.mouseDelta.X, io.mouseDelta.Y); ImGuiApi.SetMouseCursor(ImGuiMouseCursor.ResizeAll); } @@ -442,7 +589,7 @@ private void Navigate(bool hovered) { owner.CompleteCanvasEdit(draft); Vector2 pivot = ImGuiApi.GetMousePos() - m_origin; - Canvas.ZoomAt(EditorPlanarNavigation.WheelFactor(io.wheel), pivot.X, pivot.Y); + canvas.ZoomAt(EditorPlanarNavigation.WheelFactor(io.wheel), pivot.X, pivot.Y); } if (hovered && !io.wantsText && ImGuiApi.IsKeyPressed(ImGuiKey.F, false)) @@ -462,7 +609,9 @@ private void Navigate(bool hovered) private void Pointer(bool hovered) { if (ImGuiApi.IsAnyPopupOpen()) + { return; + } if (draft.navigation.isPanning || ImGuiApi.GetInput().alt) { owner.CompleteCanvasEdit(draft); @@ -474,12 +623,16 @@ private void Pointer(bool hovered) return; } Vector2 mouse = ImGuiApi.GetMousePos(); - if (draft.resizingNode is GraphNodeId resizing) + if (draft.resizingNode is GraphNodeID resizing) { ImGuiApi.SetMouseCursor(ImGuiMouseCursor.ResizeNwse); if (ImGuiApi.IsMouseButtonDown(ImGuiMouseButton.Left)) { - draft.resizePreviewWidth = Math.Clamp(draft.resizeStartWidth + (mouse.X - draft.resizePointerStart.X) / Canvas.zoom, C_MINIMUM_WIDTH, C_MAXIMUM_WIDTH); + draft.resizePreviewWidth = Math.Clamp( + draft.resizeStartWidth + (mouse.X - draft.resizePointerStart.X) / canvas.zoom, + C_MINIMUM_WIDTH, + C_MAXIMUM_WIDTH + ); } else { @@ -491,14 +644,16 @@ private void Pointer(bool hovered) GraphNodeRecord? resizeTarget = !draft.readOnly && hovered ? HitResizeHandle(mouse) : null; if (resizeTarget is not null) + { ImGuiApi.SetMouseCursor(ImGuiMouseCursor.ResizeNwse); + } if (hovered && ImGuiApi.IsMouseClicked(ImGuiMouseButton.Left)) { if (resizeTarget is not null) { - draft.selectedGroupId = ""; + draft.selectedGroupID = string.Empty; draft.selectedEdge = null; - Canvas.SelectNodes([resizeTarget.id]); + canvas.SelectNodes([resizeTarget.id]); draft.resizingNode = resizeTarget.id; draft.resizeStartWidth = NodeWidth(resizeTarget, includePreview: false); draft.resizePreviewWidth = draft.resizeStartWidth; @@ -511,27 +666,31 @@ private void Pointer(bool hovered) if (group is ShaderCanvasGroup selectedGroup) { draft.selectedEdge = null; - draft.selectedGroupId = selectedGroup.id; - Canvas.SelectNodes(selectedGroup.nodes.Select(static id => new GraphNodeId(id))); + draft.selectedGroupID = selectedGroup.id; + canvas.SelectNodes(selectedGroup.nodes.Select(static id => new GraphNodeID(id))); SynchronizeInspection(); if (!draft.readOnly) - draft.pointer.BeginMove(draft.layout, Canvas.selectedNodes, mouse); + { + draft.pointer.BeginMove(draft.layout, canvas.selectedNodes, mouse); + } return; } if (hitNode is null && HitPort(mouse) is null) { - draft.selectedGroupId = ""; + draft.selectedGroupID = string.Empty; draft.selectedEdge = HitEdge(mouse); if (draft.selectedEdge is not null) { if (!ImGuiApi.GetInput().shift) - Canvas.ClearSelection(); + { + canvas.ClearSelection(); + } return; } } } - GraphCanvasPointerResult intent = draft.pointer.Step(View, draft.layout, new GraphCanvasPointerInput + GraphCanvasPointerResult intent = draft.pointer.Step(view, draft.layout, new GraphCanvasPointerInput { position = mouse, isHovered = hovered, @@ -541,14 +700,16 @@ private void Pointer(bool hovered) shift = ImGuiApi.GetInput().shift, readOnly = draft.readOnly }); - if (intent.nodePressed is GraphNodeId pressed && Controller.document.FindNode(pressed) is { } node) + if (intent.nodePressed is GraphNodeID pressed && controller.document.FindNode(pressed) is { } node) { - draft.selectedGroupId = ""; + draft.selectedGroupID = string.Empty; draft.selectedEdge = null; SetStage(node); SynchronizeInspection(); if (!draft.readOnly && !draft.pointer.isMoving) - draft.pointer.BeginMove(draft.layout, Canvas.selectedNodes, mouse); + { + draft.pointer.BeginMove(draft.layout, canvas.selectedNodes, mouse); + } } if (intent.movedNodes is { } positions) { @@ -561,7 +722,7 @@ private void Pointer(bool hovered) ShaderNodePort inputPort = Port(input); if (outputPort.type.IsEquivalentTo(inputPort.type) || inputPort.type.id == "any") { - Controller.Connect(output, input); + controller.Connect(output, input); owner.Changed(draft); } } @@ -578,46 +739,79 @@ private void Node( GraphNodeRecord node, Vector2 mouse ) { - var rect = Rect(node); + (Vector2 min, Vector2 max) rect = Rect(node); if (rect.max.X < m_origin.X || rect.min.X > m_origin.X + m_size.X || rect.max.Y < m_origin.Y || rect.min.Y > m_origin.Y + m_size.Y) + { return; - float zoom = Canvas.zoom; + } + float zoom = canvas.zoom; if (!draft.layout.TryGetNode(node.id, out GraphCanvasNode? presentation)) + { return; - _ = View.DrawNode(draw, presentation, ImGuiApi.ToPackedColor(NodeHeaderColor(node)), Canvas.selectedNodes.Contains(node.id), - previewPosition: draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null); + } + _ = view.DrawNode( + draw, + presentation, + ImGuiApi.ToPackedColor(NodeHeaderColor(node)), + canvas.selectedNodes.Contains(node.id), + previewPosition: draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null + ); ShaderNodePort[] nodePorts = draft.ports[node.id]; if (UsesSplitPortLayout(nodePorts)) { float divider = (rect.min.X + rect.max.X) * 0.5f; float padding = 7f * zoom; - draw.Line(new(divider, rect.min.Y + C_HEADER * zoom + padding), new(divider, rect.max.Y - padding), - Color(0.62f, 0.63f, 0.69f, EditorPalette.opacityFaint), 1f); + draw.Line( + new Vector2(divider, rect.min.Y + C_HEADER * zoom + padding), + new Vector2(divider, rect.max.Y - padding), + Color(0.62f, 0.63f, 0.69f, EditorPalette.C_OPACITY_FAINT), + 1f + ); } foreach (ShaderNodePort port in nodePorts) { - var endpoint = new GraphEndpoint(node.id, new GraphPortId(port.id)); + var endpoint = new GraphEndpoint(node.id, new GraphPortID(port.id)); if (!TryPortPosition(endpoint, port.direction, out Vector2 point)) + { continue; + } if (Vector2.DistanceSquared(point, mouse) <= 64f) { bool missing = draft.missingPorts.Contains(endpoint); bool optional = port.direction == GraphPortDirection.Input && !port.required; - EditorUI.current.widgets.DrawTooltip(port.type.id + (missing ? " · missing port; reconnect explicitly" - : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : "")); + EditorUI.current.widgets.DrawTooltip( + port.type.id + (missing + ? " · missing port; reconnect explicitly" + : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : string.Empty) + ); } } if (!draft.readOnly) { bool resizeHovered = ContainsResizeHandle(rect, ImGuiApi.GetMousePos()); - uint gripColor = Color(0.62f, 0.63f, 0.69f, resizeHovered || draft.resizingNode == node.id ? EditorPalette.opacityEmphasized : EditorPalette.opacityMedium); - const float inset = 4f; - draw.Line(rect.max - new Vector2(C_RESIZE_HANDLE, inset) * zoom, rect.max - new Vector2(inset, C_RESIZE_HANDLE) * zoom, gripColor, 1f); - draw.Line(rect.max - new Vector2(C_RESIZE_HANDLE * 0.62f, inset) * zoom, rect.max - new Vector2(inset, C_RESIZE_HANDLE * 0.62f) * zoom, gripColor, 1f); + uint gripColor = Color( + 0.62f, + 0.63f, + 0.69f, + resizeHovered || draft.resizingNode == node.id ? EditorPalette.C_OPACITY_EMPHASIZED : EditorPalette.C_OPACITY_MEDIUM + ); + const float C_INSET = 4f; + draw.Line( + rect.max - new Vector2(C_RESIZE_HANDLE, C_INSET) * zoom, + rect.max - new Vector2(C_INSET, C_RESIZE_HANDLE) * zoom, + gripColor, + 1f + ); + draw.Line( + rect.max - new Vector2(C_RESIZE_HANDLE * 0.62f, C_INSET) * zoom, + rect.max - new Vector2(C_INSET, C_RESIZE_HANDLE * 0.62f) * zoom, + gripColor, + 1f + ); } - if (draft.ports[node.id].Length == 0 && node.definitionId == ShaderGraphNodes.inputDefinitionId) + if (draft.ports[node.id].Length == 0 && node.definitionID == ShaderGraphNodes.C_INPUT_DEFINITION_ID) { draw.Text( rect.min + new Vector2(12, C_HEADER + 8) * zoom, @@ -629,45 +823,51 @@ Vector2 mouse if (draft.nodeErrors.TryGetValue(node.id, out string? error)) { - draw.FilledCircle(new(rect.max.X - 14 * zoom, rect.min.Y + 16 * zoom), 4 * zoom, Color(1, 0.4f, 0.35f)); + draw.FilledCircle(new Vector2(rect.max.X - 14 * zoom, rect.min.Y + 16 * zoom), 4 * zoom, Color(1, 0.4f, 0.35f)); if (Contains(rect, ImGuiApi.GetMousePos())) + { EditorUI.current.widgets.DrawTooltip(error); + } } } - private void Grid(EditorDrawList draw) => View.DrawGrid(Color(0.105f, 0.115f, 0.135f)); + private void Grid(EditorDrawList draw) => view.DrawGrid(Color(0.105f, 0.115f, 0.135f)); + private void Groups(EditorDrawList draw) { foreach (ShaderCanvasGroup group in draft.groups) { if (GroupRect(group) is not { } bounds) + { continue; - Vector2 min = bounds.min, max = bounds.max; - bool selected = draft.selectedGroupId == group.id; + } + Vector2 min = bounds.min; + Vector2 max = bounds.max; + bool selected = draft.selectedGroupID == group.id; Vector4 headerColor = GroupHeaderColor(group); - Vector4 bodyColor = EditorPalette.WithOpacity(headerColor, EditorPalette.opacitySoft); - Vector4 borderColor = selected ? new( - 0.65f, - 0.47f, - 0.88f, - EditorPalette.opacityOpaque - ) : new( + Vector4 bodyColor = EditorPalette.WithOpacity(headerColor, EditorPalette.C_OPACITY_SOFT); + Vector4 borderColor = selected ? new Vector4(0.65f, 0.47f, 0.88f, EditorPalette.C_OPACITY_OPAQUE) : new Vector4( MathF.Min(1f, headerColor.X * 1.22f), MathF.Min(1f, headerColor.Y * 1.22f), MathF.Min(1f, headerColor.Z * 1.22f), - EditorPalette.opacityEmphasized + EditorPalette.C_OPACITY_EMPHASIZED + ); + float headerHeight = C_HEADER * canvas.zoom; + draw.FilledRectangle(min, max, ImGuiApi.ToPackedColor(bodyColor), 8 * canvas.zoom, false); + draw.FilledRectangle(min, new Vector2(max.X, min.Y + headerHeight), ImGuiApi.ToPackedColor(headerColor), 8 * canvas.zoom, true); + draw.Line( + new Vector2(min.X, min.Y + headerHeight), + new Vector2(max.X, min.Y + headerHeight), + ImGuiApi.ToPackedColor(borderColor), + 1f ); - float headerHeight = C_HEADER * Canvas.zoom; - draw.FilledRectangle(min, max, ImGuiApi.ToPackedColor(bodyColor), 8 * Canvas.zoom, false); - draw.FilledRectangle(min, new(max.X, min.Y + headerHeight), ImGuiApi.ToPackedColor(headerColor), 8 * Canvas.zoom, true); - draw.Line(new(min.X, min.Y + headerHeight), new(max.X, min.Y + headerHeight), ImGuiApi.ToPackedColor(borderColor), 1f); - draw.Rectangle(min, max, ImGuiApi.ToPackedColor(borderColor), 8 * Canvas.zoom, selected ? 2f : 1f); + draw.Rectangle(min, max, ImGuiApi.ToPackedColor(borderColor), 8 * canvas.zoom, selected ? 2f : 1f); { draw.Text( - min + new Vector2(12, 7) * Canvas.zoom, + min + new Vector2(12, 7) * canvas.zoom, ImGuiApi.GetStyleColor(ImGuiCol.Text), group.title, - (ImGuiApi.GetFontSize() * Canvas.zoom) / ImGuiApi.GetFontSize() + (ImGuiApi.GetFontSize() * canvas.zoom) / ImGuiApi.GetFontSize() ); } } @@ -676,46 +876,65 @@ private void Groups(EditorDrawList draw) private ShaderCanvasGroup? HitGroupHeader(Vector2 point) { foreach (ShaderCanvasGroup group in draft.groups.Reverse()) - if (GroupRect(group) is { } bounds && point.X >= bounds.min.X && point.X <= bounds.max.X && point.Y >= bounds.min.Y && point.Y <= bounds.min.Y + 32f * Canvas.zoom) + { + if (GroupRect(group) is { } bounds + && point.X >= bounds.min.X + && point.X <= bounds.max.X + && point.Y >= bounds.min.Y + && point.Y <= bounds.min.Y + 32f * canvas.zoom + ) { return group; + } + } return null; } private (Vector2 min, Vector2 max)? GroupRect(ShaderCanvasGroup group) { - Vector2 min = new(float.MaxValue), max = new(float.MinValue); + var min = new Vector2(float.MaxValue); + var max = new Vector2(float.MinValue); foreach (string id in group.nodes) - if (Controller.document.FindNode(new(id)) is GraphNodeRecord node) + { + if (controller.document.FindNode(new GraphNodeID(id)) is GraphNodeRecord node) { - var rect = Rect(node); + (Vector2 min, Vector2 max) rect = Rect(node); min = Vector2.Min(min, rect.min); max = Vector2.Max(max, rect.max); } + } if (min.X == float.MaxValue) + { return null; - return (min - new Vector2(20, 40) * Canvas.zoom, max + new Vector2(20) * Canvas.zoom); + } + return (min - new Vector2(20, 40) * canvas.zoom, max + new Vector2(20) * canvas.zoom); } private void RefreshGeometry() { - bool changed = draft.layoutRevision != Controller.revision - || draft.layoutAssetRevision != owner.assets.revision || draft.layoutTypeRevision != owner.typeVersion; - if (!changed && draft.resizingNode is GraphNodeId resizing + bool changed = draft.layoutRevision != controller.revision + || draft.layoutAssetRevision != owner.assets.revision || draft.layoutTypeRevision != owner.typeVersion; + if (!changed && draft.resizingNode is GraphNodeID resizing && draft.layout.TryGetNode(resizing, out GraphCanvasNode? current) - && Controller.document.FindNode(resizing) is { } resizedNode) - { + && controller.document.FindNode(resizing) is { } resizedNode + ) { if (current.size.X != NodeWidth(resizedNode)) + { _ = draft.layout.SetNodes(draft.layout.nodes.Select(node => node.id == resizing ? DescribeNode(resizedNode) : node)); + } return; } if (!changed) + { return; - var nodes = new List(Controller.document.nodes.Count); - foreach (GraphNodeRecord node in Controller.document.nodes) + } + var nodes = new List(controller.document.nodes.Count); + foreach (GraphNodeRecord node in controller.document.nodes) + { nodes.Add(DescribeNode(node)); + } _ = draft.layout.SetNodes(nodes); - draft.layoutRevision = Controller.revision; + draft.layoutRevision = controller.revision; draft.layoutAssetRevision = owner.assets.revision; draft.layoutTypeRevision = owner.typeVersion; @@ -725,20 +944,34 @@ GraphCanvasNode DescribeNode(GraphNodeRecord node) bool split = UsesSplitPortLayout(draft.ports[node.id]); int left = 0; int right = 0; - var ports = new List(); + List ports = []; foreach (ShaderNodePort port in draft.ports[node.id]) { bool input = port.direction == GraphPortDirection.Input; int row = input ? left++ : right++; float y = C_HEADER + C_ROW * (row + 0.5f); - var endpoint = new GraphEndpoint(node.id, new GraphPortId(port.id)); - ports.Add(new GraphCanvasPort(endpoint, port.direction, new(input ? 0f : width, y), port.id, - input && !port.required, draft.missingPorts.Contains(endpoint), - (new(split && !input ? width * 0.5f : 0f, y - C_ROW * 0.5f), - new(split && input ? width * 0.5f : width, y + C_ROW * 0.5f)))); + var endpoint = new GraphEndpoint(node.id, new GraphPortID(port.id)); + ports.Add( + new GraphCanvasPort( + endpoint, + port.direction, + new Vector2(input ? 0f : width, y), + port.id, + input && !port.required, + draft.missingPorts.Contains(endpoint), + (new Vector2(split && !input ? width * 0.5f : 0f, y - C_ROW * 0.5f), + new Vector2(split && input ? width * 0.5f : width, y + C_ROW * 0.5f)) + ) + ); } - return new GraphCanvasNode(node.id, node.position, - new(width, C_HEADER + Rows(node) * C_ROW + 20f), C_HEADER, Title(node), ports); + return new GraphCanvasNode( + node.id, + node.position, + new Vector2(width, C_HEADER + Rows(node) * C_ROW + 20f), + C_HEADER, + Title(node), + ports + ); } } @@ -747,53 +980,66 @@ private bool TryPortPosition( GraphPortDirection direction, out Vector2 position ) { - if (draft.layout.TryGetNode(endpoint.nodeId, out GraphCanvasNode? node)) + if (draft.layout.TryGetNode(endpoint.nodeID, out GraphCanvasNode? node)) + { foreach (GraphCanvasPort port in node.ports) + { if (port.endpoint == endpoint && port.direction == direction) { - position = View.ToScreen(draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position)) + port.position * Canvas.zoom; + position = view.ToScreen(draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position)) + + port.position * canvas.zoom; return true; } + } + } position = default; return false; } private void Edges(EditorDrawList draw) { - foreach (GraphEdgeRecord edge in Controller.document.edges) - if (TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) && TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b)) - Curve(a, b, edge.id == draft.selectedEdge); - if (Canvas.pendingConnection is GraphEndpoint pending - && Canvas.pendingConnectionDirection is GraphPortDirection direction - && TryPortPosition( - pending, - direction, - out Vector2 start - )) + foreach (GraphEdgeRecord edge in controller.document.edges) { + if (TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) + && TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b) + ) { + Curve(a, b, edge.id == draft.selectedEdge); + } + } + if (canvas.pendingConnection is GraphEndpoint pending + && canvas.pendingConnectionDirection is GraphPortDirection direction + && TryPortPosition(pending, direction, out Vector2 start) + ) { if (direction == GraphPortDirection.Output) + { Curve(start, ImGuiApi.GetMousePos()); + } else + { Curve(ImGuiApi.GetMousePos(), start); + } } void Curve( Vector2 a, Vector2 b, bool selected = false - ) { - View.DrawConnection(draw, a, b, selected ? Color(0.87f, 0.72f, 1f) : Color(0.59f, 0.46f, 0.82f), selected ? 3f : 2f); - } + ) => view.DrawConnection(draw, a, b, selected ? Color(0.87f, 0.72f, 1f) : Color(0.59f, 0.46f, 0.82f), selected ? 3f : 2f); } - private GraphEdgeId? HitEdge(Vector2 mouse) + private GraphEdgeID? HitEdge(Vector2 mouse) { - foreach (GraphEdgeRecord edge in Controller.document.edges) + foreach (GraphEdgeRecord edge in controller.document.edges) { - if (!TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) || !TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b)) + if (!TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) + || !TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b) + ) { continue; + } if (GraphCanvasView.HitConnection(mouse, a, b)) + { return edge.id; + } } return null; @@ -802,9 +1048,14 @@ void Curve( private (Vector2 min, Vector2 max) Rect(GraphNodeRecord node) { if (draft.layout.TryGetNode(node.id, out GraphCanvasNode? presentation)) - return View.NodeBounds(presentation, draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null); - Vector2 minimum = View.ToScreen(node.position); - return (minimum, minimum + new Vector2(NodeWidth(node), C_HEADER + Rows(node) * C_ROW + 20f) * Canvas.zoom); + { + return view.NodeBounds( + presentation, + draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null + ); + } + Vector2 minimum = view.ToScreen(node.position); + return (minimum, minimum + new Vector2(NodeWidth(node), C_HEADER + Rows(node) * C_ROW + 20f) * canvas.zoom); } private int Rows(GraphNodeRecord node) @@ -813,23 +1064,26 @@ private int Rows(GraphNodeRecord node) draft.ports[node.id].Count(static port => port.direction == GraphPortDirection.Input), draft.ports[node.id].Count(static port => port.direction == GraphPortDirection.Output) ); - return rows == 0 && node.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId ? 1 : rows; + return rows == 0 && node.definitionID is ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID + ? 1 + : rows; } - private static bool UsesSplitPortLayout(IEnumerable ports) => ports.Any(static port => port.direction == GraphPortDirection.Input) - && ports.Any(static port => port.direction == GraphPortDirection.Output); private GraphNodeRecord? HitNode(Vector2 point) - => View.HitNode(draft.layout, point) is { } node ? Controller.document.FindNode(node.id) : null; + => view.HitNode(draft.layout, point) is { } node ? controller.document.FindNode(node.id) : null; - private PortHandle? HitPort(Vector2 point) => View.HitPort(draft.layout, point) is { } port ? new PortHandle(port.endpoint, port.direction) : null; + private PortHandle? HitPort(Vector2 point) + => view.HitPort(draft.layout, point) is { } port ? new PortHandle(port.endpoint, port.direction) : null; private GraphNodeRecord? HitResizeHandle(Vector2 point) { - foreach (GraphNodeRecord node in Controller.document.nodes.Reverse()) + foreach (GraphNodeRecord node in controller.document.nodes.Reverse()) { (Vector2 min, Vector2 max) rect = Rect(node); if (ContainsResizeHandle(rect, point)) + { return node; + } } return null; @@ -839,7 +1093,7 @@ private bool ContainsResizeHandle( (Vector2 min, Vector2 max) rect, Vector2 point ) { - float extent = MathF.Max(10f, C_RESIZE_HANDLE * Canvas.zoom); + float extent = MathF.Max(10f, C_RESIZE_HANDLE * canvas.zoom); return point.X >= rect.max.X - extent && point.X <= rect.max.X + 2f && point.Y >= rect.max.Y - extent && point.Y <= rect.max.Y + 2f; } @@ -848,39 +1102,45 @@ private float NodeWidth( bool includePreview = true ) { if (includePreview && draft.resizingNode == node.id) + { return draft.resizePreviewWidth; + } float width = Read(node, C_NODE_WIDTH, C_DEFAULT_WIDTH); return float.IsFinite(width) ? Math.Clamp(width, C_MINIMUM_WIDTH, C_MAXIMUM_WIDTH) : C_DEFAULT_WIDTH; } - private ShaderNodePort Port(PortHandle handle) => draft.ports[handle.endpoint.nodeId].Single(port => port.id == handle.endpoint.portId.value && port.direction == handle.direction); - private ShaderNodePort Port(GraphEndpoint endpoint) => draft.ports[endpoint.nodeId].Single(port => port.id == endpoint.portId.value); - private GraphPosition ToGraph(Vector2 point) => View.ToGraph(point); - private static bool Contains( - (Vector2 min, Vector2 max) rect, - Vector2 point - ) => point.X >= rect.min.X && point.Y >= rect.min.Y && point.X <= rect.max.X && point.Y <= rect.max.Y; - private static uint Color( - float r, - float g, - float b, - float a = EditorPalette.opacityOpaque - ) => ImGuiApi.ToPackedColor(new(r, g, b, a)); + private ShaderNodePort Port(PortHandle handle) + => draft.ports[handle.endpoint.nodeID].Single( + port => port.id == handle.endpoint.portID.value && port.direction == handle.direction + ); + + private ShaderNodePort Port(GraphEndpoint endpoint) => draft.ports[endpoint.nodeID].Single(port => port.id == endpoint.portID.value); + + private GraphPosition ToGraph(Vector2 point) => view.ToGraph(point); + private Vector4 NodeHeaderColor(GraphNodeRecord node) { - string key = node.definitionId + "/" + Title(node); - return node.definitionId switch + string key = node.definitionID + "/" + Title(node); + return node.definitionID switch { - ShaderGraphDocument.outputDefinitionId => StableHeaderColor(key, 258f, 34f), - ShaderGraphNodes.outputDefinitionId => StableHeaderColor(key, 258f, 34f), - "inno.shader.stage-input" or "inno.shader.constant" or ShaderGraphNodes.inputDefinitionId => StableHeaderColor(key, 22f, 24f), + ShaderGraphDocument.C_OUTPUT_DEFINITION_ID => StableHeaderColor(key, 258f, 34f), + ShaderGraphNodes.C_OUTPUT_DEFINITION_ID => StableHeaderColor(key, 258f, 34f), + "inno.shader.stage-input" + or "inno.shader.constant" + or ShaderGraphNodes.C_INPUT_DEFINITION_ID => StableHeaderColor(key, 22f, 24f), "inno.shader.sample" => StableHeaderColor(key, 158f, 30f), "inno.shader.source" => StableHeaderColor(key, 198f, 42f), "inno.shader.binary" => StableHeaderColor(key, 205f, 45f), - "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" or "inno.shader.reroute" => StableHeaderColor(key, 178f, 58f), - "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => StableHeaderColor(key, 105f, 42f), + "inno.shader.construct" + or "inno.shader.extract" + or "inno.shader.select" + or "inno.shader.reroute" => StableHeaderColor(key, 178f, 58f), + "inno.shader.storage-load" + or "inno.shader.storage-store" + or "inno.shader.storage-atomic-add" => StableHeaderColor(key, 105f, 42f), "inno.shader.discard" => StableHeaderColor(key, 350f, 22f), - _ => StableHeaderColor(key, 0f, 360f)}; + _ => StableHeaderColor(key, 0f, 360f) + }; } private Vector4 GroupHeaderColor(ShaderCanvasGroup group) @@ -889,60 +1149,40 @@ private Vector4 GroupHeaderColor(ShaderCanvasGroup group) int count = 0; foreach (string id in group.nodes) { - if (Controller.document.FindNode(new(id)) is not GraphNodeRecord node) + if (controller.document.FindNode(new GraphNodeID(id)) is not GraphNodeRecord node) + { continue; + } total += NodeHeaderColor(node); count++; } if (count == 0) - return C_EMPTY_GROUP_HEADER; - Vector4 average = total / count; - return EditorPalette.WithOpacity(average, EditorPalette.opacityNearOpaque); - } - - private static Vector4 StableHeaderColor( - string key, - float startHue, - float hueRange - ) { - uint hash = 2166136261; - foreach (char value in key) { - hash ^= value; - hash *= 16777619; + return EMPTY_GROUP_HEADER; } - - float hue = (startHue + hueRange * (hash & 0xffff) / 65535f) % 360f; - float saturation = 0.52f + 0.12f * ((hash >> 16) & 0xff) / 255f; - float brightness = 0.34f + 0.08f * ((hash >> 24) & 0xff) / 255f; - float chroma = brightness * saturation; - float sector = hue / 60f; - float secondary = chroma * (1f - MathF.Abs(sector % 2f - 1f)); - (float red, float green, float blue) = sector switch - { - < 1f => (chroma, secondary, 0f), - < 2f => (secondary, chroma, 0f), - < 3f => (0f, chroma, secondary), - < 4f => (0f, secondary, chroma), - < 5f => (secondary, 0f, chroma), - _ => (chroma, 0f, secondary)}; - float match = brightness - chroma; - return new(red + match, green + match, blue + match, EditorPalette.opacityOpaque); + Vector4 average = total / count; + return EditorPalette.WithOpacity(average, EditorPalette.C_OPACITY_NEAR_OPAQUE); } - private static bool CenteredAddButton(string label) => EditorUI.current.widgets.CenteredButton(label, EditorUI.current.widgets.style.addButtonTopPadding); private T Read( GraphNodeRecord node, string key, T value ) => ShaderGraphDocument.Read(node, key, value, owner.serialization, owner.context); + private void Set( GraphNodeRecord node, string key, T value, bool continuous = false - ) => SetEncoded(node, key, ShaderGraphDocument.Encode(value, owner.serialization, owner.context), continuous ? draft.valueGesture : null); + ) => SetEncoded( + node, + key, + ShaderGraphDocument.Encode(value, owner.serialization, owner.context), + continuous ? draft.valueGesture : null + ); + private void SetEncoded( GraphNodeRecord node, string key, @@ -951,10 +1191,11 @@ private void SetEncoded( ) { if (m_inspectionNodes is { Length: > 1 } selected) { - GraphDocument candidate = Controller.document.Clone(); + GraphDocument candidate = controller.document.Clone(); foreach (GraphNodeRecord target in selected) { - if (key == "settings" && target.definitionId == "inno.shader.stage-input") + if (key == "settings" && target.definitionID == "inno.shader.stage-input") + { candidate = ShaderGraphBindings.ChangeInput( candidate, target.id, @@ -962,16 +1203,20 @@ private void SetEncoded( owner.serialization, owner.context ); + } else + { candidate.FindNode(target.id)!.SetValue(key, value.Clone()); + } } - Controller.ReplaceDocument(candidate, "Edit Shader Nodes", mergeKey); + controller.ReplaceDocument(candidate, "Edit Shader Nodes", mergeKey); } - else if (key == "settings" && node.definitionId == "inno.shader.stage-input") - Controller.ReplaceDocument( + else if (key == "settings" && node.definitionID == "inno.shader.stage-input") + { + controller.ReplaceDocument( ShaderGraphBindings.ChangeInput( - Controller.document, + controller.document, node.id, ShaderGraphDocument.Decode(value, owner.serialization, owner.context), owner.serialization, @@ -980,62 +1225,106 @@ private void SetEncoded( "Edit Shader Input", mergeKey ); + } else - Controller.SetNodeValue(node.id, key, value, mergeKey); + { + controller.SetNodeValue(node.id, key, value, mergeKey); + } owner.Changed(draft); } private void SetStage(GraphNodeRecord? node) { if (node is null) + { return; - string stage = node.definitionId == ShaderGraphDocument.outputDefinitionId ? node.id.value : Read(node, "stage", ""); + } + string stage = node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID ? node.id.value : Read(node, "stage", string.Empty); if (stage.Length != 0) + { draft.activeStage = new(stage); + } } private void Frame() { - GraphNodeRecord[] selection = Controller.document.nodes.Where(node => Canvas.selectedNodes.Count == 0 || Canvas.selectedNodes.Contains(node.id)).ToArray(); + GraphNodeRecord[] selection = controller.document.nodes + .Where(node => canvas.selectedNodes.Count == 0 || canvas.selectedNodes.Contains(node.id)) + .ToArray(); if (selection.Length == 0) + { return; - float minX = selection.Min(static node => node.position.x), minY = selection.Min(static node => node.position.y); + } + float minX = selection.Min(static node => node.position.x); + float minY = selection.Min(static node => node.position.y); float maxX = selection.Max(node => node.position.x + NodeWidth(node)); float maxY = selection.Max(node => node.position.y + C_HEADER + Rows(node) * C_ROW + 20); - float scale = Math.Clamp(MathF.Min(MathF.Max(1, m_size.X - 80) / MathF.Max(1, maxX - minX), MathF.Max(1, m_size.Y - 80) / MathF.Max(1, maxY - minY)), 0.1f, 1f); - Canvas.SetViewport(new(m_size.X / 2 - (minX + maxX) / 2 * scale, m_size.Y / 2 - (minY + maxY) / 2 * scale), scale); + float scale = Math.Clamp( + MathF.Min(MathF.Max(1, m_size.X - 80) / MathF.Max(1, maxX - minX), MathF.Max(1, m_size.Y - 80) / MathF.Max(1, maxY - minY)), + 0.1f, + 1f + ); + canvas.SetViewport(new GraphPosition(m_size.X / 2 - (minX + maxX) / 2 * scale, m_size.Y / 2 - (minY + maxY) / 2 * scale), scale); } - internal string Title(GraphNodeRecord node) - { - if (owner.drawers?.GetDisplayName(node.definitionId) is { } displayName) - return displayName; - if (node.definitionId == ShaderGraphDocument.outputDefinitionId) - return Read(node, "settings", new ShaderGraphStageSettings()).stage + " Output"; - if (node.definitionId == "inno.shader.binary") - return EditorDisplayNames.Nicify(Read(node, "operation", "add").Replace('-', ' ')); - if (node.definitionId == "inno.shader.stage-input") - { - ShaderGraphInputSettings input = Read(node, "settings", new ShaderGraphInputSettings()); - return input.id.Length != 0 ? EditorDisplayNames.Nicify(input.id) : "Stage Input"; - } + private static void InspectorRow( + string id, + string label, + Action draw + ) => EditorUI.current.widgets.PropertyRow("shader." + id, label, draw); + + private static bool UsesSplitPortLayout(IEnumerable ports) + => ports.Any(static port => port.direction == GraphPortDirection.Input) + && ports.Any(static port => port.direction == GraphPortDirection.Output); + + private static bool Contains( + (Vector2 min, Vector2 max) rect, + Vector2 point + ) => point.X >= rect.min.X && point.Y >= rect.min.Y && point.X <= rect.max.X && point.Y <= rect.max.Y; - if (node.definitionId == "inno.shader.source") + private static uint Color( + float r, + float g, + float b, + float a = EditorPalette.C_OPACITY_OPAQUE + ) => ImGuiApi.ToPackedColor(new Vector4(r, g, b, a)); + + private static Vector4 StableHeaderColor( + string key, + float startHue, + float hueRange + ) { + uint hash = 2_166_136_261; + foreach (char value in key) { - string function = Read(node, "function", ""); - return function.Length == 0 ? "Source Function" : function; + hash ^= value; + hash *= 16_777_619; } - if (node.definitionId == ShaderGraphNodes.callDefinitionId) - return Read(node, ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()).displayName; - if (node.definitionId == ShaderGraphNodes.inputDefinitionId) - return ShaderGraphNodes.ReadSettings( - Controller.document, - owner.serialization, - owner.context - ).kind == ShaderGraphNodeKind.DomainOutput ? "Domain Inputs" : "Function Inputs"; - if (node.definitionId == ShaderGraphNodes.outputDefinitionId) - return "Function Outputs"; - return EditorDisplayNames.Nicify(node.definitionId.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' ')); + float hue = (startHue + hueRange * (hash & 0xFFFF) / 65535f) % 360f; + float saturation = 0.52f + 0.12f * ((hash >> 16) & 0xFF) / 255f; + float brightness = 0.34f + 0.08f * ((hash >> 24) & 0xFF) / 255f; + float chroma = brightness * saturation; + float sector = hue / 60f; + float secondary = chroma * (1f - MathF.Abs(sector % 2f - 1f)); + (float red, float green, float blue) = sector switch + { + < 1f => (chroma, secondary, 0f), + < 2f => (secondary, chroma, 0f), + < 3f => (0f, chroma, secondary), + < 4f => (0f, secondary, chroma), + < 5f => (secondary, 0f, chroma), + _ => (chroma, 0f, secondary) + }; + float match = brightness - chroma; + return new(red + match, green + match, blue + match, EditorPalette.C_OPACITY_OPAQUE); } + + private static bool CenteredAddButton(string label) + => EditorUI.current.widgets.CenteredButton(label, EditorUI.current.widgets.style.addButtonTopPadding); + + private readonly record struct PortHandle( + GraphEndpoint endpoint, + GraphPortDirection direction + ); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs index c1b20ea5e..c368a583d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs @@ -14,13 +14,15 @@ internal void CompleteCanvasEdit(Draft draft) // A preview remains presentation-only until this atomic domain edit succeeds. // Preserve a released intent when History rejects the operation so it can be retried. draft.pendingMove ??= draft.pointer.previewPositions.Count == 0 - ? null - : new Dictionary(draft.pointer.previewPositions); + ? null + : new Dictionary(draft.pointer.previewPositions); if (draft.pendingMove is { } positions) { bool changed = false; - foreach (var entry in positions) + foreach (KeyValuePair entry in positions) + { changed |= controller.document.FindNode(entry.Key) is not { } current || current.position != entry.Value; + } if (changed) { controller.MoveNodes(positions); @@ -28,27 +30,31 @@ internal void CompleteCanvasEdit(Draft draft) } draft.pendingMove = null; } - if (draft.resizingNode is GraphNodeId resizing - && controller.document.FindNode(resizing) is { } node) - { + if (draft.resizingNode is GraphNodeID resizing + && controller.document.FindNode(resizing) is { } node + ) { GraphDocument replacement = controller.document.Clone(); - replacement.FindNode(node.id)!.SetValue("editor.width", ShaderGraphDocument.Encode(draft.resizePreviewWidth, serialization, context)); + replacement + .FindNode(node.id)! + .SetValue("editor.width", ShaderGraphDocument.Encode(draft.resizePreviewWidth, serialization, context)); controller.ReplaceDocument(replacement, "Resize Shader Node"); Changed(draft); } CancelCanvasEdit(draft); } - private void CompleteCanvasEdits() - { - foreach (Draft draft in m_drafts.Values) - CompleteCanvasEdit(draft); - } - internal static void CancelCanvasEdit(Draft draft) { draft.pendingMove = null; draft.pointer.Cancel(); draft.resizingNode = null; } + + private void CompleteCanvasEdits() + { + foreach (Draft draft in m_drafts.Values) + { + CompleteCanvasEdit(draft); + } + } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs index 5bc8afbdf..238c6d503 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs @@ -1,20 +1,23 @@ using System; +using System.Collections.Generic; using System.Linq; using Inno.Core.Graphs; using Inno.Editor.Graph; +using Inno.Rendering; using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; -internal sealed record ShaderClipboardData( - byte[] graph, - Guid owner -); - internal sealed partial class ShaderEditorDocuments { internal ShaderClipboardData Copy(Draft draft) - => new(GraphDocumentCodec.Encode(ShaderGraphClipboard.Copy(Controller(draft).document, draft.canvas.selectedNodes, serialization, context), serialization), draft.id); + => new( + GraphDocumentCodec.Encode( + ShaderGraphClipboard.Copy(Controller(draft).document, draft.canvas.selectedNodes, serialization, context), + serialization + ), + draft.id + ); internal bool CanPaste( Draft draft, @@ -22,10 +25,11 @@ ShaderClipboardData data ) { GraphDocument destination = Controller(draft).document; GraphDocument fragment = GraphDocumentCodec.Decode(data.graph, serialization); - var existingStages = destination.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + HashSet existingStages = destination.nodes + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), serialization, context).stage) .ToHashSet(); - return !fragment.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + return !fragment.nodes.Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), serialization, context).stage) .Any(existingStages.Contains); } @@ -35,12 +39,25 @@ internal void Paste( ShaderClipboardData clipboard ) { if (!CanPaste(draft, clipboard)) + { throw new InvalidOperationException("The shader already contains an output for one of the copied stages."); + } GraphDocumentController controller = Controller(draft); - ShaderGraphPasteResult result = ShaderGraphClipboard.Paste(controller.document, - GraphDocumentCodec.Decode(clipboard.graph, serialization), clipboard.owner == draft.id, draft.activeStage, serialization, context); + ShaderGraphPasteResult result = ShaderGraphClipboard.Paste( + controller.document, + GraphDocumentCodec.Decode(clipboard.graph, serialization), + clipboard.owner == draft.id, + draft.activeStage, + serialization, + context + ); controller.ReplaceDocument(result.document, "Paste Shader Nodes"); draft.canvas.SelectNodes(result.insertedNodes); Changed(draft); } } + +internal sealed record ShaderClipboardData( + byte[] graph, + Guid owner +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs index e79f5c5dc..cd3f627bf 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs @@ -3,20 +3,14 @@ using System.IO; using System.Linq; using Inno.Assets; +using Inno.Core.Execution; using Inno.Core.Graphs; -using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; -internal sealed record ShaderNodeCreation( - string definitionId, - Guid sourceId = default, - string function = "" -); - internal sealed partial class ShaderEditorDocuments { internal GraphNodeRecord PrepareNode( @@ -24,49 +18,82 @@ internal GraphNodeRecord PrepareNode( ShaderNodeCreation creation ) { GraphDocument graph = Controller(draft).document; - GraphNodeId? stage = draft.createFromPort is GraphEndpoint endpoint - ? new(ShaderGraphDocument.Read(graph.FindNode(endpoint.nodeId)!, "stage", "", serialization, context)) - : draft.activeStage ?? graph.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; - var node = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), creation.definitionId) { position = draft.menuPosition }; - if (stage is GraphNodeId id) + GraphNodeID? stage = draft.createFromPort is GraphEndpoint endpoint + ? new GraphNodeID(ShaderGraphDocument.Read(graph.FindNode(endpoint.nodeID)!, "stage", string.Empty, serialization, context)) + : draft.activeStage + ?? graph.nodes.FirstOrDefault(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID)?.id; + var node = new GraphNodeRecord( + new GraphNodeID(Guid.NewGuid().ToString("N")), + creation.definitionID + ) { position = draft.menuPosition }; + if (stage is GraphNodeID id) + { node.SetValue("stage", ShaderGraphDocument.Encode(id.value, serialization, context)); - if (creation.definitionId == "inno.shader.stage-input") + } + if (creation.definitionID == "inno.shader.stage-input") { - HashSet names = graph.nodes.Where(static value => value.definitionId == "inno.shader.stage-input") - .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context).id).ToHashSet(StringComparer.Ordinal); + HashSet names = graph.nodes.Where(static value => value.definitionID == "inno.shader.stage-input") + .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context).id) + .ToHashSet(StringComparer.Ordinal); string name = "parameter"; for (int suffix = 2; names.Contains(name); suffix++) + { name = "parameter" + suffix; - node.SetValue("settings", ShaderGraphDocument.Encode(new ShaderGraphInputSettings - { id = name, kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" }, semantic = "" }, serialization, context)); - } - else if (creation.definitionId == ShaderGraphNodes.inputDefinitionId) - node.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings(), serialization, context)); - else if (creation.definitionId == ShaderGraphNodes.outputDefinitionId) - node.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings(), serialization, context)); + } + node.SetValue( + "settings", + ShaderGraphDocument.Encode(new ShaderGraphInputSettings + { + id = name, + kind = ShaderIrInputKind.Uniform, + type = new() { id = "float4" }, + semantic = string.Empty + }, serialization, context) + ); + } + else if (creation.definitionID == ShaderGraphNodes.C_INPUT_DEFINITION_ID) + { + node.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings(), serialization, context) + ); + } + else if (creation.definitionID == ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) + { + node.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings(), serialization, context) + ); + } if (draft.createFromPort is GraphEndpoint source) { - ShaderNodePort port = draft.ports[source.nodeId].Single(value => value.id == source.portId.value); + ShaderNodePort port = draft.ports[source.nodeID].Single(value => value.id == source.portID.value); node.SetValue("type", ShaderGraphDocument.Encode(port.type.id, serialization, context)); - if (creation.definitionId == "inno.shader.reroute") + if (creation.definitionID == "inno.shader.reroute") + { node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(port.type), serialization, context)); + } } - if (creation.sourceId != Guid.Empty) + if (creation.sourceID != Guid.Empty) { - if (!assets.TryGetInfo(creation.sourceId, out AssetInfo? info) || info is null) + if (!assets.TryGetInfo(creation.sourceID, out AssetInfo? info) || info is null) + { throw new IOException("Referenced Shader authoring asset is unavailable."); - node.SetValue("sourceId", ShaderGraphDocument.Encode(creation.sourceId, serialization, context)); + } + node.SetValue("sourceId", ShaderGraphDocument.Encode(creation.sourceID, serialization, context)); node.SetValue("sourcePath", ShaderGraphDocument.Encode(info.assetPath.ToString(), serialization, context)); - if (creation.definitionId == "inno.shader.source") + if (creation.definitionID == "inno.shader.source") { ArgumentException.ThrowIfNullOrWhiteSpace(creation.function); node.SetValue("function", ShaderGraphDocument.Encode(creation.function, serialization, context)); } - else if (creation.definitionId == ShaderGraphNodes.callDefinitionId) - node.SetValue(ShaderGraphNodes.interfaceKey, - ShaderGraphDocument.Encode(LoadGraphNodeInterface(creation.sourceId), serialization, context)); + else if (creation.definitionID == ShaderGraphNodes.C_CALL_DEFINITION_ID) + { + node.SetValue( + ShaderGraphNodes.C_INTERFACE_KEY, + ShaderGraphDocument.Encode(LoadGraphNodeInterface(creation.sourceID), serialization, context) + ); + } } return node; } @@ -74,65 +101,66 @@ ShaderNodeCreation creation internal IReadOnlyList Describe(GraphNodeRecord node) { ShaderSourceModuleAnalysis? module = null; - string implementation = ""; - ShaderIrStageInput? input = node.definitionId == "inno.shader.stage-input" - ? ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).CreateBinding() : null; - if (node.definitionId == "inno.shader.source") + string implementation = string.Empty; + ShaderIrStageInput? input = node.definitionID == "inno.shader.stage-input" + ? ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).CreateBinding() + : null; + if (node.definitionID == "inno.shader.source") { Guid id = ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, serialization, context); - if (id != Guid.Empty && assets.TryGetInfo(id, out AssetInfo? info) && info is not null && info.status != AssetImportStatus.Imported) + if (id != Guid.Empty + && assets.TryGetInfo(id, out AssetInfo? info) + && info is not null + && info.status != AssetImportStatus.Imported + ) { throw new InvalidOperationException("Source function " + info.status + ": " + string.Join("\n", info.diagnostics)); + } if (id != Guid.Empty && assets.TryLoad(id, out ShaderFunctionAsset? function) && function is not null && !function.isMissing) { - string selected = ShaderGraphDocument.Read(node, "function", "", serialization, context); - module = frontends.AnalyzeModule(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(function, assets), selected, serialization)); + string selected = ShaderGraphDocument.Read(node, "function", string.Empty, serialization, context); + module = frontends.AnalyzeModule( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(function, assets), selected, serialization) + ); implementation = function.implementationId; } } GraphNodeRecord described = node; - if (node.definitionId == ShaderGraphNodes.callDefinitionId) + if (node.definitionID == ShaderGraphNodes.C_CALL_DEFINITION_ID) { Guid id = ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, serialization, context); if (id != Guid.Empty && TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface)) { - described = new GraphNodeRecord(node.id, node.definitionId) { position = node.position }; + described = new GraphNodeRecord(node.id, node.definitionID) { position = node.position }; foreach ((string key, GraphSerializedValue value) in node.values) + { described.SetValue(key, value); - described.SetValue(ShaderGraphNodes.interfaceKey, - ShaderGraphDocument.Encode(nodeInterface!, serialization, context)); + } + described.SetValue( + ShaderGraphNodes.C_INTERFACE_KEY, + ShaderGraphDocument.Encode(nodeInterface!, serialization, context) + ); } } return nodes.DescribePorts(described, serialization, context, module, implementation, input); } internal ShaderGraphNodeInterface LoadGraphNodeInterface(Guid id) - { - return TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface) - ? nodeInterface! - : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); - } - - private bool TryLoadGraphNodeInterface( - Guid id, - out ShaderGraphNodeInterface? nodeInterface - ) { - nodeInterface = null; - if (!assets.TryGetInfo(id, out AssetInfo? info) || info is null || info.status != AssetImportStatus.Imported - || !assets.TryLoad(id, out ShaderAsset? shader) || shader is null || shader.isMissing) - return false; - GraphDocument graph = ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(shader, assets), serialization); - nodeInterface = ShaderGraphNodes.ReadInterface(graph, serialization, context); - return true; - } + => TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface) + ? nodeInterface! + : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); internal ShaderNodePort? CompatibleInput( Draft draft, GraphNodeRecord node ) { if (draft.createFromPort is not GraphEndpoint source) + { return null; - ShaderNodePort output = draft.ports[source.nodeId].Single(value => value.id == source.portId.value); - return Describe(node).FirstOrDefault(value => value.direction == GraphPortDirection.Input && value.type.IsEquivalentTo(output.type)); + } + ShaderNodePort output = draft.ports[source.nodeID].Single(value => value.id == source.portID.value); + return Describe(node).FirstOrDefault( + value => value.direction == GraphPortDirection.Input && value.type.IsEquivalentTo(output.type) + ); } internal bool CanCreate( @@ -140,17 +168,24 @@ internal bool CanCreate( ShaderNodeCreation creation ) { if (draft.readOnly) + { return false; - if (creation.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId - && Controller(draft).document.nodes.Any(node => node.definitionId == creation.definitionId)) + } + if (creation.definitionID is ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID + && Controller(draft).document.nodes.Any(node => node.definitionID == creation.definitionID) + ) { return false; + } if (draft.createFromPort is null) + { return true; + } try { return CompatibleInput(draft, PrepareNode(draft, creation)) is not null; } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or IOException or FormatException) && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or IOException or FormatException) + && RetirementPendingException.Find(failure) is null) { return false; } @@ -164,17 +199,55 @@ ShaderNodeCreation creation ShaderNodePort? input = CompatibleInput(draft, node); GraphDocument graph = Controller(draft).document.Clone(); graph.AddNode(node); - if (node.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId - && !ShaderGraphNodes.IsNodeGraph(graph)) + if (node.definitionID is ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID + && !ShaderGraphNodes.IsNodeGraph(graph) + ) { ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); - if (node.definitionId == "inno.shader.stage-input") - graph = ShaderGraphBindings.ChangeInput(graph, node.id, - ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), serialization, context); + } + if (node.definitionID == "inno.shader.stage-input") + { + graph = ShaderGraphBindings.ChangeInput( + graph, + node.id, + ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), + serialization, + context + ); + } if (input is not null && draft.createFromPort is GraphEndpoint source) - graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), source, new(node.id, new(input.id)))); + { + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + source, + new GraphEndpoint(node.id, new GraphPortID(input.id)) + ) + ); + } Controller(draft).ReplaceDocument(graph, "Create Shader Node"); draft.createFromPort = null; draft.canvas.SelectNodes([node.id]); Changed(draft); } + + private bool TryLoadGraphNodeInterface( + Guid id, + out ShaderGraphNodeInterface? nodeInterface + ) { + nodeInterface = null; + if (!assets.TryGetInfo(id, out AssetInfo? info) || info is null || info.status != AssetImportStatus.Imported + || !assets.TryLoad(id, out ShaderAsset? shader) || shader is null || shader.isMissing + ) { + return false; + } + GraphDocument graph = ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(shader, assets), serialization); + nodeInterface = ShaderGraphNodes.ReadInterface(graph, serialization, context); + return true; + } } + +internal sealed record ShaderNodeCreation( + string definitionID, + Guid sourceID = default, + string function = "" +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs index e36ca273e..d9c95f9a5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs @@ -1,30 +1,32 @@ -using Inno.Editor.Graph.ImGui; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Graphs; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Execution; +using Inno.Core.Graphs; using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Graph; +using Inno.Editor.Graph.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; -using Inno.Rendering; using Inno.Extensibility.Types; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; + [EditorModule("rendering.shader-documents", order: 170)] internal sealed partial class ShaderEditorDocuments : EditorModule { @@ -33,16 +35,8 @@ internal sealed partial class ShaderEditorDocuments : EditorModule private readonly Dictionary m_drafts = []; private readonly Dictionary m_views = []; private readonly HashSet m_pendingImports = []; - private Guid? m_checkDraftId; - private long m_sourceRevision = long.MinValue; private readonly GraphEditorModule m_graphs; private readonly ShaderGraphSourceStore m_sources; - private Inno.Core.Execution.LifetimeScope? m_lifetime; - private ShaderNodeCompilerRegistry? m_nodes; - private ShaderSourceFrontendRegistry? m_frontends; - internal ShaderNodeDrawerRegistry? drawers; - internal ShaderGraphTemplateRegistry? templates; - internal ShaderTargetRegistry? targets; private readonly TypeCatalog m_types; private readonly EditorShaderCompilation m_compilation; internal readonly AssetImportSettingsEdits importSettings; @@ -50,7 +44,16 @@ internal sealed partial class ShaderEditorDocuments : EditorModule internal readonly AssetPipeline assets; internal readonly SerializationRegistry serialization; internal readonly EditorInteractions interactions; + private Guid? m_checkDraftID; + private long m_sourceRevision = long.MinValue; + private LifetimeScope? m_lifetime; + private ShaderNodeCompilerRegistry? m_nodes; + private ShaderSourceFrontendRegistry? m_frontends; + internal ShaderNodeDrawerRegistry? drawers; + internal ShaderGraphTemplateRegistry? templates; + internal ShaderTargetRegistry? targets; internal ShaderClipboardData? clipboard; + internal ShaderEditorDocuments( AssetPipeline assets, SerializationRegistry serialization, @@ -75,9 +78,167 @@ IEditorPreviewService previews internal string checkStatus { get; private set; } = "Checking the current Shader draft…"; internal SerializationContext context => AssetSerializationContext.Create(assets); internal ShaderNodeCompilerRegistry nodes => m_nodes ?? throw new InvalidOperationException("Shader documents have not started."); - internal ShaderSourceFrontendRegistry frontends => m_frontends ?? throw new InvalidOperationException("Shader documents have not started."); + + internal ShaderSourceFrontendRegistry frontends + => m_frontends ?? throw new InvalidOperationException("Shader documents have not started."); + internal long typeVersion => m_types.current.version; + /// + /// Initializes this feature when its owning runtime becomes active. + /// + /// + /// The editor consumed by on start; ownership remains with the caller unless explicitly stated otherwise. + /// + protected override void OnStart(EditorContext editor) + { + m_lifetime = new(); + try + { + m_nodes = m_lifetime.Own(new ShaderNodeCompilerRegistry(m_types)); + m_frontends = m_lifetime.Own(new ShaderSourceFrontendRegistry(m_types)); + drawers = m_lifetime.Own(new ShaderNodeDrawerRegistry(m_types)); + templates = m_lifetime.Own(new ShaderGraphTemplateRegistry(m_types)); + targets = m_lifetime.Own(new ShaderTargetRegistry(m_types)); + _ = m_lifetime.Own(interactions.documents.RegisterProvider(new Provider(this))); + EventHub operations = m_lifetime.Own(interactions.events.CreateHub(int.MaxValue - 1)); + operations.Listen(_ => CompleteCanvasEdits()); + } + catch (Exception failure) + { + try + { + m_lifetime.Dispose(); + } + catch (Exception retirement) + { + throw new AggregateException(failure, retirement); + } + + throw; + } + } + + /// + /// Advances this feature using the current runtime state. + /// + /// + /// The editor consumed by on update; ownership remains with the caller unless explicitly stated otherwise. + /// + protected override void OnUpdate(EditorContext editor) + { + if (TryGetCheckDraft(out Draft checking)) + { + EditorShaderDraftCompilationSnapshot result = Check(checking); + if (result.state != EditorShaderCompilationState.Compiling) + { + PublishCheck(checking, result); + checkStatus = result.state == EditorShaderCompilationState.Succeeded + ? "Shader check completed." + : "Shader check failed. See Console diagnostics."; + CloseCheck(); + } + } + foreach (AssetPath path in m_pendingImports.ToArray()) + { + m_pendingImports.Remove(path); + try + { + _ = assets.Import(path); + } + catch (Exception failure) when ((failure is IOException + or UnauthorizedAccessException + or InvalidOperationException + or FormatException) + && RetirementPendingException.Find(failure) is null) + { + foreach (Draft draft in m_drafts.Values.Where(draft => draft.path == path)) + { + draft.compilationStatus = "Import failed"; + draft.compilationDiagnostics = failure.Message; + } + } + } + + if (m_sourceRevision != assets.revision) + { + SynchronizeSources(); + m_sourceRevision = assets.revision; + } + + foreach (Draft draft in m_drafts.Values) + { + GraphDocumentController controller = Controller(draft); + if (controller.revision != draft.observedRevision) + { + Changed(draft); + } + } + } + + /// + /// Captures an immutable snapshot of the current observable state. + /// + /// + /// The lifecycle or domain state applied by this operation. + /// + protected override void Capture(EditorState state) + { + foreach (Draft draft in m_drafts.Values) + { + RememberView(draft); + } + state.Set("views", m_views.Values.ToArray()); + } + + /// + /// Restores the supplied snapshot while preserving current invariants. + /// + /// + /// The lifecycle or domain state applied by this operation. + /// + protected override void Restore(EditorState state) + { + m_views.Clear(); + foreach (ViewState view in state.Get("views", Array.Empty())) + { + if (view.assetID != Guid.Empty && float.IsFinite(view.x) && float.IsFinite(view.y) && float.IsFinite(view.zoom)) + { + m_views[view.assetID] = view; + } + } + } + + /// + /// Stops this feature before its owning runtime releases the active generation. + /// + /// + /// The editor consumed by on stop; ownership remains with the caller unless explicitly stated otherwise. + /// + protected override void OnStop(EditorContext editor) + { + m_checkDraftID = null; + // Recovery is not an asset save. Closing the panel, shutdown and reload must not apply a draft. + foreach (Draft draft in m_drafts.Values) + { + CancelCanvasEdit(draft); + if (Controller(draft).isDirty) + { + PreserveRecovery(draft, Controller(draft)); + } + ClearNodeDiagnostics(draft); + ReleasePreview(draft); + } + + m_lifetime?.Dispose(); + m_lifetime = null; + m_frontends = null; + drawers = null; + templates = null; + targets = null; + m_nodes = null; + } + internal EditorShaderDraftCompilationSnapshot? Preview(Draft draft) { GraphDocumentController controller = Controller(draft); @@ -95,8 +256,11 @@ internal EditorShaderDraftCompilationSnapshot Check(Draft draft) _ = ShaderGraphNodes.ReadInterface(controller.document, serialization, context); nodeSnapshot = new(EditorShaderCompilationState.Succeeded, false, [], null); } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException or NotSupportedException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is InvalidOperationException + or ArgumentException + or FormatException + or NotSupportedException) + && RetirementPendingException.Find(failure) is null) { nodeSnapshot = new( EditorShaderCompilationState.Failed, @@ -111,9 +275,16 @@ [new ShaderDiagnostic("SHADER_GRAPH_NODE_INTERFACE", DiagnosticSeverity.Error, f return draft.preview = nodeSnapshot; } - EditorShaderDraftCompilationSnapshot snapshot = m_compilation.RequestDraft(draft.id, controller.document, controller.revision, RenderShaderVariant.empty); + EditorShaderDraftCompilationSnapshot snapshot = m_compilation.RequestDraft( + draft.id, + controller.document, + controller.revision, + RenderShaderVariant.empty + ); if (snapshot.state == EditorShaderCompilationState.Compiling) + { return snapshot; + } draft.checkedRevision = controller.revision; draft.checkedState = snapshot.state; if (snapshot.state == EditorShaderCompilationState.Failed) @@ -129,16 +300,18 @@ [new ShaderDiagnostic("SHADER_GRAPH_NODE_INTERFACE", DiagnosticSeverity.Error, f internal void ShowCheck(Draft draft) { - m_checkDraftId = draft.id; + m_checkDraftID = draft.id; checkStatus = "Checking the current Shader draft…"; } + internal bool TryGetCheckDraft(out Draft draft) { draft = null!; - return m_checkDraftId is Guid id && m_drafts.TryGetValue(id, out draft!); + return m_checkDraftID is Guid id && m_drafts.TryGetValue(id, out draft!); } - internal void CloseCheck() => m_checkDraftId = null; + internal void CloseCheck() => m_checkDraftID = null; + internal void ReleasePreview(Draft draft) { m_compilation.ReleaseDraft(draft.id); @@ -149,49 +322,22 @@ internal void ReleasePreview(Draft draft) internal void PublishNodeDiagnostics(Draft draft) { - Diagnostic[] diagnostics = draft.nodeErrors.Select(pair => new Diagnostic("SHADER_NODE_INVALID", $"Node '{pair.Key.value}' cannot be evaluated: {pair.Value}", DiagnosticSeverity.Error, semanticId: pair.Key.value, objectId: draft.id, location: new DiagnosticLocation(draft.path.ToString()))).ToArray(); + Diagnostic[] diagnostics = draft.nodeErrors + .Select( + pair => new Diagnostic( + "SHADER_NODE_INVALID", + $"Node '{pair.Key.value}' cannot be evaluated: {pair.Value}", + DiagnosticSeverity.Error, + semanticID: pair.Key.value, + objectID: draft.id, + location: new DiagnosticLocation(draft.path.ToString()) + ) + ) + .ToArray(); Diagnostics.Set(draft.id, C_NODE_DIAGNOSTIC_GROUP, diagnostics, draft.path.ToString()); } - private static void PublishCheck( - Draft draft, - EditorShaderDraftCompilationSnapshot snapshot - ) { - var diagnostics = new List(Math.Max(1, snapshot.diagnostics.Count)); - for (int index = 0; index < snapshot.diagnostics.Count; index++) - { - ShaderDiagnostic shader = snapshot.diagnostics[index]; - DiagnosticLocation? location = shader.location is ShaderSourceLocation source ? new(source.assetPath, source.line, source.column) : null; - diagnostics.Add(shader.severity switch - { - DiagnosticSeverity.Info => Diagnostic.Info(shader.code, shader.message, location), - DiagnosticSeverity.Warning => Diagnostic.Warning(shader.code, shader.message, location), - DiagnosticSeverity.Error => Diagnostic.Error(shader.code, shader.message, location), - _ => Diagnostic.Error(shader.code, shader.message, location) - }); - } - - if (diagnostics.Count == 0) - { - diagnostics.Add(snapshot.state == EditorShaderCompilationState.Succeeded - ? Diagnostic.Info("SHADER_CHECK_SUCCEEDED", "Shader check completed without diagnostics.") - : Diagnostic.Error("SHADER_CHECK_FAILED", "Shader check failed without a compiler diagnostic.")); - } - - Diagnostics.Set(draft.id, "Shader Check", diagnostics, draft.path.ToString()); - } - - private static void ClearNodeDiagnostics(Draft draft) => Diagnostics.Clear(draft.id, C_NODE_DIAGNOSTIC_GROUP); - internal Draft Open(AssetFileEntry entry) => Open(entry, AssetId(entry)); - private Draft Open( - AssetFileEntry entry, - Guid id - ) { - if (m_drafts.TryGetValue(id, out Draft? existing)) - return existing; - EditorDocumentContext document = interactions.documents.Open(entry.assetPath.ToString(), id); - return m_drafts[document.assetId]; - } + internal Draft Open(AssetFileEntry entry) => Open(entry, AssetID(entry)); internal bool TryOpen( AssetFileEntry entry, @@ -199,34 +345,41 @@ out Draft draft ) { draft = null!; if (!assets.TryGetInfo(entry.assetPath, out AssetInfo? info) || info is null) + { return false; - draft = Open(entry, info.persistentId); + } + draft = Open(entry, info.persistentID); return true; } - internal GraphDocumentController Controller(Draft draft) => m_graphs.TryOpenDocument( - draft.id, - interactions.history, - out GraphDocumentController? controller - ) ? controller! : throw new InvalidOperationException("The Shader graph document is not available."); - internal Guid AssetId(AssetFileEntry entry) => assets.TryGetInfo( - entry.assetPath, - out AssetInfo? info - ) - && info is not null ? info.persistentId : throw new InvalidOperationException("The shader asset identity is not available yet."); + internal GraphDocumentController Controller(Draft draft) + => m_graphs.TryOpenDocument( + draft.id, + interactions.history, + out GraphDocumentController? controller + ) ? controller! : throw new InvalidOperationException("The Shader graph document is not available."); + + internal Guid AssetID(AssetFileEntry entry) + => assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + && info is not null ? info.persistentID : throw new InvalidOperationException("The shader asset identity is not available yet."); + internal bool TryGet( AssetFileEntry entry, out Draft draft ) { draft = null!; - return assets.TryGetInfo(entry.assetPath, out AssetInfo? info) && info is not null && m_drafts.TryGetValue(info.persistentId, out draft!); + return assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + && info is not null + && m_drafts.TryGetValue(info.persistentID, out draft!); } internal void RefreshCompilation(Draft draft) { long now = Stopwatch.GetTimestamp(); if (now < draft.nextCompilationPoll) + { return; + } draft.nextCompilationPoll = now + Stopwatch.Frequency / 4; draft.diagnostics = []; try @@ -236,7 +389,7 @@ internal void RefreshCompilation(Draft draft) { _ = ShaderGraphNodes.ReadInterface(document, serialization, context); draft.compilationStatus = "Reusable node · interface valid"; - draft.compilationDiagnostics = ""; + draft.compilationDiagnostics = string.Empty; return; } @@ -267,11 +420,14 @@ internal void RefreshCompilation(Draft draft) EditorShaderCompilationState.Succeeded => "Compiled", _ => "Compilation failed" }; - draft.compilationDiagnostics = string.Join("\n", snapshot.diagnostics.Select(static value => value.code + ": " + value.message)); + draft.compilationDiagnostics = string.Join( + "\n", + snapshot.diagnostics.Select(static value => value.code + ": " + value.message) + ); draft.diagnostics = snapshot.diagnostics.ToArray(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.compilationStatus = "Compilation unavailable"; draft.compilationDiagnostics = failure.Message; @@ -281,20 +437,26 @@ internal void RefreshCompilation(Draft draft) internal void RemoveNodes(Draft draft) { if (draft.canvas.selectedNodes.Count == 0) + { return; + } GraphDocumentController controller = Controller(draft); GraphDocument candidate = ShaderGraphBindings.RemoveNodes(controller.document, draft.canvas.selectedNodes, serialization, context); ShaderCanvasGroup[] groups = GroupShaderNodes.Read(this, candidate).Select(group => { - group.nodes = group.nodes.Where(id => candidate.FindNode(new(id)) is not null).ToArray(); + group.nodes = group.nodes.Where(id => candidate.FindNode(new GraphNodeID(id)) is not null).ToArray(); return group; }).Where(static group => group.nodes.Length != 0).ToArray(); candidate.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, serialization, context)); - if (draft.selectedGroupId.Length != 0 && !groups.Any(group => group.id == draft.selectedGroupId)) - draft.selectedGroupId = ""; + if (draft.selectedGroupID.Length != 0 && !groups.Any(group => group.id == draft.selectedGroupID)) + { + draft.selectedGroupID = string.Empty; + } controller.ReplaceDocument(candidate, "Delete Shader Nodes"); - if (draft.activeStage is GraphNodeId stage && controller.document.FindNode(stage) is null) + if (draft.activeStage is GraphNodeID stage && controller.document.FindNode(stage) is null) + { draft.activeStage = null; + } draft.navigation.Cancel(); draft.pointer.Cancel(); } @@ -303,24 +465,28 @@ internal void Changed(Draft draft) { GraphDocumentController controller = Controller(draft); if (draft.checkedRevision != ulong.MaxValue && draft.checkedRevision != controller.revision) + { ReleasePreview(draft); + } draft.observedRevision = controller.revision; - interactions.documents.SetDirty(draft.documentId, controller.isDirty); + interactions.documents.SetDirty(draft.documentID, controller.isDirty); if (!controller.isDirty) { string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } return; } try { PreserveRecovery(draft, controller); - draft.error = ""; + draft.error = string.Empty; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = "Recovery could not be written: " + failure.Message; } @@ -330,27 +496,33 @@ internal bool Save(Draft draft) { GraphDocumentController controller = Controller(draft); if (!controller.isDirty) + { return true; + } try { PreserveRecovery(draft, controller); if (!controller.isAvailable) + { throw new IOException("The shader source is unavailable. Recovery and history are retained until it returns."); + } draft.hash = m_sources.Save(draft.path, CaptureSource(draft, controller.document), draft.hash); controller.MarkSaved(); draft.observedRevision = controller.revision; m_pendingImports.Add(draft.path); - draft.error = ""; + draft.error = string.Empty; draft.status = "Saved"; draft.nextCompilationPoll = 0; string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } // Import runs at the next editor update, independently of persistence success and watcher timing. return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; draft.status = "Not saved · recovery retained"; @@ -369,213 +541,98 @@ internal bool Reload(Draft draft) draft.hash = source.contentHash; draft.readOnly = source.isReadOnly; draft.observedRevision = controller.revision; - draft.error = ""; + draft.error = string.Empty; draft.status = "Reloaded · compilation is separate"; string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; return false; } } - /// - /// Initializes this feature when its owning runtime becomes active. - /// - /// - /// The editor consumed by on start; ownership remains with the caller unless explicitly stated otherwise. - /// - protected override void OnStart(EditorContext editor) - { - m_lifetime = new(); - try - { - m_nodes = m_lifetime.Own(new ShaderNodeCompilerRegistry(m_types)); - m_frontends = m_lifetime.Own(new ShaderSourceFrontendRegistry(m_types)); - drawers = m_lifetime.Own(new ShaderNodeDrawerRegistry(m_types)); - templates = m_lifetime.Own(new ShaderGraphTemplateRegistry(m_types)); - targets = m_lifetime.Own(new ShaderTargetRegistry(m_types)); - _ = m_lifetime.Own(interactions.documents.RegisterProvider(new Provider(this))); - var operations = m_lifetime.Own(interactions.events.CreateHub(int.MaxValue - 1)); - operations.Listen(_ => CompleteCanvasEdits()); - } - catch (Exception failure) - { - try - { - m_lifetime.Dispose(); - } - catch (Exception retirement) - { - throw new AggregateException(failure, retirement); - } - - throw; - } - } - - /// - /// Advances this feature using the current runtime state. - /// - /// - /// The editor consumed by on update; ownership remains with the caller unless explicitly stated otherwise. - /// - protected override void OnUpdate(EditorContext editor) - { - if (TryGetCheckDraft(out Draft checking)) - { - EditorShaderDraftCompilationSnapshot result = Check(checking); - if (result.state != EditorShaderCompilationState.Compiling) - { - PublishCheck(checking, result); - checkStatus = result.state == EditorShaderCompilationState.Succeeded - ? "Shader check completed." : "Shader check failed. See Console diagnostics."; - CloseCheck(); - } - } - foreach (AssetPath path in m_pendingImports.ToArray()) - { - m_pendingImports.Remove(path); - try - { - _ = assets.Import(path); - } - catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) - { - foreach (Draft draft in m_drafts.Values.Where(draft => draft.path == path)) - { - draft.compilationStatus = "Import failed"; - draft.compilationDiagnostics = failure.Message; - } - } - } - - if (m_sourceRevision != assets.revision) - { - SynchronizeSources(); - m_sourceRevision = assets.revision; - } - - foreach (Draft draft in m_drafts.Values) - { - GraphDocumentController controller = Controller(draft); - if (controller.revision != draft.observedRevision) - Changed(draft); - } - } - - /// - /// Captures an immutable snapshot of the current observable state. - /// - /// - /// The lifecycle or domain state applied by this operation. - /// - protected override void Capture(EditorState state) - { - foreach (Draft draft in m_drafts.Values) - RememberView(draft); - state.Set("views", m_views.Values.ToArray()); - } - - /// - /// Restores the supplied snapshot while preserving current invariants. - /// - /// - /// The lifecycle or domain state applied by this operation. - /// - protected override void Restore(EditorState state) - { - m_views.Clear(); - foreach (ViewState view in state.Get("views", Array.Empty())) - if (view.assetId != Guid.Empty && float.IsFinite(view.x) && float.IsFinite(view.y) && float.IsFinite(view.zoom)) - m_views[view.assetId] = view; - } - - /// - /// Stops this feature before its owning runtime releases the active generation. - /// - /// - /// The editor consumed by on stop; ownership remains with the caller unless explicitly stated otherwise. - /// - protected override void OnStop(EditorContext editor) - { - m_checkDraftId = null; - // Recovery is not an asset save. Closing the panel, shutdown and reload must not apply a draft. - foreach (Draft draft in m_drafts.Values) - { - CancelCanvasEdit(draft); - if (Controller(draft).isDirty) - PreserveRecovery(draft, Controller(draft)); - ClearNodeDiagnostics(draft); - ReleasePreview(draft); - } - - m_lifetime?.Dispose(); - m_lifetime = null; - m_frontends = null; - drawers = null; - templates = null; - targets = null; - m_nodes = null; - } - private void Open(EditorDocumentContext document) { - if (m_drafts.ContainsKey(document.assetId)) + if (m_drafts.ContainsKey(document.assetID)) + { return; + } AssetPath path = AssetPath.Parse(document.assetPath); - string recoveryPath = RecoveryPath(document.assetId); + string recoveryPath = RecoveryPath(document.assetID); RecoveryData? recovery = null; if (File.Exists(recoveryPath)) { recovery = serialization.Deserialize(File.ReadAllBytes(recoveryPath)); - if (recovery.assetId != document.assetId) + if (recovery.assetId != document.assetID) + { throw new InvalidDataException("Shader recovery identity does not match its document."); + } } - if (assets.TryGetInfo(document.assetId, out AssetInfo? info) && info is not null && info.status != AssetImportStatus.Missing) + if (assets.TryGetInfo(document.assetID, out AssetInfo? info) && info is not null && info.status != AssetImportStatus.Missing) { path = info.assetPath; - interactions.documents.UpdateAssetPath(document.documentId, path.ToString()); + interactions.documents.UpdateAssetPath(document.documentID, path.ToString()); } ShaderGraphSourceSnapshot? source = null; - string missing = ""; + string missing = string.Empty; try { source = m_sources.Read(path); } catch (Exception failure) when ((recovery is not null - && failure is IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && failure is IOException or InvalidOperationException or FormatException) + && RetirementPendingException.Find(failure) is null) { missing = failure.Message; } - GraphDocumentController controller = m_graphs.OpenDocument(document.assetId, source?.document ?? new GraphDocument(), interactions.history); - string staleRecovery = ""; + GraphDocumentController controller = m_graphs.OpenDocument( + document.assetID, + source?.document ?? new GraphDocument(), + interactions.history + ); + string staleRecovery = string.Empty; bool canRecover = recovery is not null && (source is null || recovery.hash == source.contentHash); if (canRecover && !controller.isDirty) + { controller.ReplaceDocument(GraphDocumentCodec.Decode(recovery!.graph, serialization), "Recover Shader Edits"); + } else if (recovery is not null) - staleRecovery = ArchiveStaleRecovery(document.assetId, recoveryPath); - var draft = new Draft(document.assetId, document.documentId, path, recovery?.hash ?? source!.contentHash, source?.isReadOnly ?? true) + { + staleRecovery = ArchiveStaleRecovery(document.assetID, recoveryPath); + } + var draft = new Draft( + document.assetID, + document.documentID, + path, + recovery?.hash ?? source!.contentHash, + source?.isReadOnly ?? true + ) { observedRevision = controller.revision }; if (m_views.TryGetValue(draft.id, out ViewState view)) - draft.canvas.SetViewport(new(view.x, view.y), view.zoom); + { + draft.canvas.SetViewport(new GraphPosition(view.x, view.y), view.zoom); + } else + { draft.frameRequested = true; + } m_drafts.Add(draft.id, draft); if (canRecover) + { Changed(draft); + } else if (staleRecovery.Length != 0) { draft.hash = source!.contentHash; @@ -590,43 +647,65 @@ private void Open(EditorDocumentContext document) } } + private Draft Open( + AssetFileEntry entry, + Guid id + ) { + if (m_drafts.TryGetValue(id, out Draft? existing)) + { + return existing; + } + EditorDocumentContext document = interactions.documents.Open(entry.assetPath.ToString(), id); + return m_drafts[document.assetID]; + } + private void PreserveRecovery( Draft draft, GraphDocumentController controller ) => AtomicFile.WriteAllBytes( RecoveryPath(draft.id), - serialization.Serialize(new RecoveryData { assetId = draft.id, path = draft.path.ToString(), hash = draft.hash, graph = GraphDocumentCodec.Encode(CaptureSource(draft, controller.document), serialization) }) + serialization.Serialize( + new RecoveryData + { + assetId = draft.id, + path = draft.path.ToString(), + hash = draft.hash, + graph = GraphDocumentCodec.Encode(CaptureSource(draft, controller.document), serialization) + } + ) ); + private GraphDocument CaptureSource( Draft draft, GraphDocument graph ) { GraphDocument snapshot = graph.Clone(); foreach (GraphNodeRecord node in snapshot.nodes) + { if (draft.portSnapshots.TryGetValue(node.id, out ShaderPortSnapshot[]? ports)) + { node.SetValue(C_PORT_SNAPSHOT, ShaderGraphDocument.Encode(ports, serialization, context)); + } + } return snapshot; } private string RecoveryPath(Guid id) => Path.Combine(assets.libraryRoot, "Editor", "ShaderRecovery", id.ToString("N") + ".inno"); - private static string ArchiveStaleRecovery( - Guid id, - string recoveryPath - ) { - string directory = Path.GetDirectoryName(recoveryPath) ?? throw new InvalidOperationException("The Shader recovery directory is unavailable."); - string archive = Path.Combine(directory, id.ToString("N") + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") + ".stale.inno"); - File.Move(recoveryPath, archive); - return archive; - } private void SynchronizeSources() { if (m_drafts.Count == 0) + { return; + } Dictionary entries = []; foreach (AssetFileEntry entry in assets.GetFileSystemEntries(includeDirectories: false)) + { if (entry.extension == ".ishader" && assets.TryGetInfo(entry.assetPath, out AssetInfo? info) && info is not null) - entries.Add(info.persistentId, entry); + { + entries.Add(info.persistentID, entry); + } + } foreach (Draft draft in m_drafts.Values) { GraphDocumentController controller = Controller(draft); @@ -643,13 +722,15 @@ private void SynchronizeSources() bool wasMissing = !controller.isAvailable; m_graphs.SetAvailability(draft.id, true); draft.path = entry.assetPath; - interactions.documents.UpdateAssetPath(draft.documentId, draft.path.ToString()); + interactions.documents.UpdateAssetPath(draft.documentID, draft.path.ToString()); ShaderGraphSourceSnapshot source = m_sources.Read(draft.path); draft.readOnly = source.isReadOnly; if (source.contentHash == draft.hash) { if (wasMissing) - draft.error = ""; + { + draft.error = string.Empty; + } continue; } @@ -663,11 +744,14 @@ private void SynchronizeSources() m_graphs.RebindDocument(draft.id, source.document); draft.hash = source.contentHash; draft.observedRevision = controller.revision; - draft.error = ""; + draft.error = string.Empty; draft.status = "Source updated · compilation is separate"; } - catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is IOException + or UnauthorizedAccessException + or InvalidOperationException + or FormatException) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; } @@ -675,12 +759,61 @@ private void SynchronizeSources() } private void RememberView(Draft draft) => m_views[draft.id] = new(draft.id, draft.canvas.pan.x, draft.canvas.pan.y, draft.canvas.zoom); + + private static void PublishCheck( + Draft draft, + EditorShaderDraftCompilationSnapshot snapshot + ) { + var diagnostics = new List(Math.Max(1, snapshot.diagnostics.Count)); + for (int index = 0; index < snapshot.diagnostics.Count; index++) + { + ShaderDiagnostic shader = snapshot.diagnostics[index]; + DiagnosticLocation? location = shader.location is ShaderSourceLocation source + ? new DiagnosticLocation(source.assetPath, source.line, source.column) + : null; + diagnostics.Add( + shader.severity switch + { + DiagnosticSeverity.Info => Diagnostic.Info(shader.code, shader.message, location), + DiagnosticSeverity.Warning => Diagnostic.Warning(shader.code, shader.message, location), + DiagnosticSeverity.Error => Diagnostic.Error(shader.code, shader.message, location), + _ => Diagnostic.Error(shader.code, shader.message, location) + } + ); + } + + if (diagnostics.Count == 0) + { + diagnostics.Add( + snapshot.state == EditorShaderCompilationState.Succeeded + ? Diagnostic.Info("SHADER_CHECK_SUCCEEDED", "Shader check completed without diagnostics.") + : Diagnostic.Error("SHADER_CHECK_FAILED", "Shader check failed without a compiler diagnostic.") + ); + } + + Diagnostics.Set(draft.id, "Shader Check", diagnostics, draft.path.ToString()); + } + + private static void ClearNodeDiagnostics(Draft draft) => Diagnostics.Clear(draft.id, C_NODE_DIAGNOSTIC_GROUP); + + private static string ArchiveStaleRecovery( + Guid id, + string recoveryPath + ) { + string directory = Path.GetDirectoryName(recoveryPath) + ?? throw new InvalidOperationException("The Shader recovery directory is unavailable."); + string archive = Path.Combine(directory, id.ToString("N") + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") + ".stale.inno"); + File.Move(recoveryPath, archive); + return archive; + } + private readonly record struct ViewState( - Guid assetId, + Guid assetID, float x, float y, float zoom ); + private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvider { /// @@ -698,6 +831,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// when the documented condition is satisfied; otherwise, . /// public override bool CanOpen(string assetPath) => assetPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase); + /// /// Opens the requested resource and establishes its active lifetime. /// @@ -705,6 +839,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// The operation scope that provides state, services, and ownership boundaries. /// public override void Open(EditorDocumentContext context) => owner.Open(context); + /// /// Persists the supplied value through the configured storage contract. /// @@ -714,7 +849,8 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// /// when the documented condition is satisfied; otherwise, . /// - public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetId]); + public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetID]); + /// /// Restores the draft from the latest imported asset state. /// @@ -724,7 +860,8 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// /// when the documented condition is satisfied; otherwise, . /// - public override bool Revert(EditorDocumentContext context) => owner.Reload(owner.m_drafts[context.assetId]); + public override bool Revert(EditorDocumentContext context) => owner.Reload(owner.m_drafts[context.assetID]); + /// /// Closes the active resource and releases its operation-scoped state. /// @@ -734,11 +871,15 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi public override void Close(EditorDocumentContext context) { // The shared host already applied Save/Discard/Cancel policy. Close must never turn Discard into Save. - if (!owner.m_drafts.TryGetValue(context.assetId, out Draft? draft)) + if (!owner.m_drafts.TryGetValue(context.assetID, out Draft? draft)) + { return; + } string recovery = owner.RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } owner.RememberView(draft); CancelCanvasEdit(draft); ClearNodeDiagnostics(draft); @@ -751,63 +892,63 @@ public override void Close(EditorDocumentContext context) internal sealed class Draft( Guid id, - Guid documentId, + Guid documentID, AssetPath path, string hash, bool readOnly - ) - { + ) { internal readonly Guid id = id; - internal readonly Guid documentId = documentId; + internal readonly Guid documentID = documentID; + internal readonly HashSet expandedPreviews = []; + internal readonly GraphCanvasState canvas = new(); + internal readonly EditorPlanarNavigation navigation = new(); + internal readonly GraphCanvasLayout layout = new(); + internal readonly Dictionary ports = []; + internal readonly Dictionary portSnapshots = []; + internal readonly HashSet missingPorts = []; + internal readonly Dictionary nodeErrors = []; internal AssetPath path = path; internal string hash = hash; internal bool readOnly = readOnly; internal ulong observedRevision; - internal string error = ""; + internal string error = string.Empty; internal string status = "Saved"; internal string compilationStatus = "Waiting for import"; - internal string compilationDiagnostics = ""; + internal string compilationDiagnostics = string.Empty; internal ShaderDiagnostic[] diagnostics = []; internal ulong checkedRevision = ulong.MaxValue; internal EditorShaderCompilationState? checkedState; internal EditorShaderDraftCompilationSnapshot? preview; internal long nextCompilationPoll; internal GraphEndpoint? createFromPort; - internal GraphEdgeId? selectedEdge; + internal GraphEdgeID? selectedEdge; internal bool frameRequested; internal ShaderCanvasGroup[] groups = []; - internal string selectedGroupId = ""; - internal readonly HashSet expandedPreviews = []; + internal string selectedGroupID = string.Empty; internal Guid settingsSource; internal byte[] sourceSettings = []; - internal string sourceSettingsFingerprint = ""; - internal string sourceSettingsStatus = ""; - internal readonly GraphCanvasState canvas = new(); + internal string sourceSettingsFingerprint = string.Empty; + internal string sourceSettingsStatus = string.Empty; internal GraphPosition menuPosition; - internal GraphNodeId? activeStage; - internal string inspectedPass = ""; - internal GraphNodeId[] inspectedNodes = []; + internal GraphNodeID? activeStage; + internal string inspectedPass = string.Empty; + internal GraphNodeID[] inspectedNodes = []; internal ShaderInspectionSelection? inspectionSelection; internal string valueGesture = Guid.NewGuid().ToString("N"); - internal readonly EditorPlanarNavigation navigation = new(); private GraphCanvasPointerController? m_pointer; - internal GraphCanvasPointerController pointer => m_pointer ??= new(canvas); - internal IReadOnlyDictionary? pendingMove; - internal readonly GraphCanvasLayout layout = new(); + internal IReadOnlyDictionary? pendingMove; internal ulong layoutRevision = ulong.MaxValue; internal long layoutAssetRevision = long.MinValue; internal long layoutTypeRevision = long.MinValue; - internal GraphNodeId? resizingNode; + internal GraphNodeID? resizingNode; internal float resizeStartWidth; internal float resizePreviewWidth; - internal System.Numerics.Vector2 resizePointerStart; + internal Vector2 resizePointerStart; internal ulong portRevision = ulong.MaxValue; internal long assetRevision = long.MinValue; internal long typeRevision = long.MinValue; - internal readonly Dictionary ports = []; - internal readonly Dictionary portSnapshots = []; - internal readonly HashSet missingPorts = []; - internal readonly Dictionary nodeErrors = []; + + internal GraphCanvasPointerController pointer => m_pointer ??= new(canvas); } private sealed class RecoveryData : ISerializable @@ -822,13 +963,13 @@ private sealed class RecoveryData : ISerializable /// Gets or sets the diagnostic source path. /// [SerializableProperty] - public string path { get; set; } = ""; + public string path { get; set; } = string.Empty; /// /// Gets or sets the expected disk source fingerprint. /// [SerializableProperty] - public string hash { get; set; } = ""; + public string hash { get; set; } = string.Empty; /// /// Gets or sets the complete neutral unsaved graph. @@ -837,23 +978,3 @@ private sealed class RecoveryData : ISerializable public byte[] graph { get; set; } = []; } } - -internal struct ShaderPortSnapshot -{ - /// - /// Gets the stable identity used to reference this value across subsystem boundaries. - /// - public string id { get; set; } - /// - /// Gets the graph port's shader value type. - /// - public ShaderGraphType type { get; set; } - /// - /// Gets the graph port's input or output direction. - /// - public GraphPortDirection direction { get; set; } - /// - /// Gets whether required is active for the current instance. - /// - public bool required { get; set; } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs new file mode 100644 index 000000000..4e147b56f --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs @@ -0,0 +1,27 @@ +using Inno.Core.Graphs; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +internal struct ShaderPortSnapshot +{ + /// + /// Gets the stable identity used to reference this value across subsystem boundaries. + /// + public string id { get; set; } + + /// + /// Gets the graph port's shader value type. + /// + public ShaderGraphType type { get; set; } + + /// + /// Gets the graph port's input or output direction. + /// + public GraphPortDirection direction { get; set; } + + /// + /// Gets whether required is active for the current instance. + /// + public bool required { get; set; } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs new file mode 100644 index 000000000..00cac263c --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs @@ -0,0 +1,88 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(ShaderAsset))] +internal sealed class ShaderAssetDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + ShaderAsset target + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetFileSystemEntry( + target.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + ShaderAsset target + ) => (target.name, null); + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + ShaderAsset target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) + { + return; + } + if (!documents.assets.TryGetFileSystemEntry(target.assetPath, out AssetFileEntry entry)) + { + return; + } + if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs deleted file mode 100644 index 7c71b5f09..000000000 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs +++ /dev/null @@ -1,284 +0,0 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; -using System.IO; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Graphs; -using Inno.Editor.ImGui; -using Inno.Editor.Inspection; -using Inno.Editor.Shaders; -using Inno.Rendering; -using Inno.Rendering.Assets; - -namespace Inno.Editor.Panel.ShaderEditor; -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class ShaderSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out var documents)) - { - if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) - new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); - else - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } - } -} - -[InspectionDrawer(typeof(ShaderInspectionSelection))] -internal sealed class ShaderSelectionDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - ShaderInspectionSelection target - ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) - && info is not null) - return (Path.GetFileName(info.assetPath.localPath), null); - return ("Shader", null); - } - - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (!context.interactions.TryGetModule(out var documents) - || documents is null - || !documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) - || info is null - || !documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - )) - { - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node selection unavailable"); - return; - } - - if (!documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - { - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Waiting for Shader asset import…"); - return; - } - - if (target.nodes.Count == 1 && documents.Controller(draft).document.FindNode(target.nodes[0]) is GraphNodeRecord node) - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node: " + new ShaderEditorCanvas(documents, draft).Title(node)); - else - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, $"Nodes: {target.nodes.Count} selected"); - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (!context.interactions.TryGetModule(out var documents) || documents is null) - return; - if (!documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) || info is null || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) - { - EditorUI.current.widgets.WrappedText("Shader source unavailable. Selection identities are retained."); - return; - } - - if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - new ShaderEditorCanvas(documents, draft).DrawInspector(context, target.nodes); - else - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } -} - -[InspectionDrawer(typeof(ShaderAsset))] -internal sealed class ShaderAssetDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - ShaderAsset target - ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetFileSystemEntry( - target.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - ShaderAsset target - ) => (target.name, null); - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - ShaderAsset target - ) { - if (!context.interactions.TryGetModule(out var documents) || documents is null) - return; - if (!documents.assets.TryGetFileSystemEntry(target.assetPath, out AssetFileEntry entry)) - return; - if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); - else - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs new file mode 100644 index 000000000..b5e647fc4 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs @@ -0,0 +1,148 @@ +using System; +using System.IO; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Editor.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(ShaderInspectionSelection))] +internal sealed class ShaderSelectionDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + ShaderInspectionSelection target + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + && info is not null + ) { + return (Path.GetFileName(info.assetPath.localPath), null); + } + return ("Shader", null); + } + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + || documents is null + || !documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + || info is null + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node selection unavailable"); + return; + } + + if (!documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Waiting for Shader asset import…"); + return; + } + + if (target.nodes.Count == 1 && documents.Controller(draft).document.FindNode(target.nodes[0]) is GraphNodeRecord node) + { + EditorUI.current.widgets.ColoredText( + EditorPalette.contextText, + "Node: " + new ShaderEditorCanvas(documents, draft).Title(node) + ); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, $"Nodes: {target.nodes.Count} selected"); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) + { + return; + } + if (!documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + || info is null + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { + EditorUI.current.widgets.WrappedText("Shader source unavailable. Selection identities are retained."); + return; + } + + if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, target.nodes); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs new file mode 100644 index 000000000..7be921242 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs @@ -0,0 +1,89 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class ShaderSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents)) + { + if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs new file mode 100644 index 000000000..3ddda7479 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; +using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/collapse-subgraph", ShaderEditorCanvas.C_AREA)] +internal sealed class CollapseShaderSubgraph( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!base.Query(context).isEnabled) + { + return EditorActionState.disabled; + } + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocument graph = documents.Controller(draft).document; + GraphNodeRecord[] selected = draft.canvas.selectedNodes.Select(graph.FindNode).OfType().ToArray(); + if (selected.Length != draft.canvas.selectedNodes.Count + || selected.Any( + static node => ( + node.definitionID is ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + or ShaderGraphNodes.C_INPUT_DEFINITION_ID + or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID + ) + ) + ) { + return EditorActionState.disabled; + } + string[] stages = selected + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_STAGE_KEY, + string.Empty, + documents.serialization, + documents.context + ) + ) + .Distinct(StringComparer.Ordinal) + .ToArray(); + if (stages.Length != 1 || stages[0].Length == 0) + { + return EditorActionState.disabled; + } + HashSet ids = selected.Select(static node => node.id).ToHashSet(); + return graph.edges.Any(edge => ids.Contains(edge.input.nodeID) != ids.Contains(edge.output.nodeID)) + ? EditorActionState.enabled + : EditorActionState.disabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + GraphDocument parent = controller.document; + HashSet selected = [..draft.canvas.selectedNodes]; + GraphNodeRecord[] nodes = parent.nodes.Where(node => selected.Contains(node.id)).ToArray(); + string stage = nodes + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_STAGE_KEY, + string.Empty, + documents.serialization, + documents.context + ) + ) + .Distinct(StringComparer.Ordinal) + .Single(); + GraphEdgeRecord[] incomingEdges = parent.edges + .Where(edge => selected.Contains(edge.input.nodeID) && !selected.Contains(edge.output.nodeID)) + .ToArray(); + GraphEdgeRecord[] outgoingEdges = parent.edges + .Where(edge => selected.Contains(edge.output.nodeID) && !selected.Contains(edge.input.nodeID)) + .ToArray(); + IGrouping[] inputGroups = incomingEdges.GroupBy(static edge => edge.output).ToArray(); + IGrouping[] outputGroups = outgoingEdges.GroupBy(static edge => edge.output).ToArray(); + var inputNames = new HashSet(StringComparer.Ordinal); + var outputNames = new HashSet(StringComparer.Ordinal); + ShaderGraphNodePortDefinition[] inputs = inputGroups + .Select( + group => Port( + Unique(group.First().input.portID.value, "input", inputNames), + draft.ports[group.First().input.nodeID].Single(port => port.id == group.First().input.portID.value).type, + required: true + ) + ) + .ToArray(); + ShaderGraphNodePortDefinition[] outputs = outputGroups + .Select( + group => Port( + Unique(group.Key.portID.value, "output", outputNames), + draft.ports[group.Key.nodeID].Single(port => port.id == group.Key.portID.value).type, + required: false + ) + ) + .ToArray(); + ShaderDefinition parentDefinition = ShaderGraphDocument.ReadDefinition(parent, documents.serialization, documents.context); + HashSet ownedBindings = nodes + .Where(static node => node.definitionID == "inno.shader.stage-input") + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphInputSettings(), + documents.serialization, + documents.context + ).id + ) + .ToHashSet(StringComparer.Ordinal); + var childDefinition = new ShaderDefinition( + "Graph Node", + parentDefinition.properties.Where(property => ownedBindings.Contains(property.id.value)), + [], + [] + ); + GraphDocument child = ShaderGraphDocument.Create(childDefinition, documents.serialization, documents.context); + string displayName = SuggestedName(documents, draft, selected); + var nodeSettings = new ShaderGraphNodeSettings + { + displayName = displayName, + createPath = "Project", + kind = ShaderGraphNodeKind.Function, + effect = outputs.Length == 0 ? ShaderGraphNodeEffect.SideEffect : ShaderGraphNodeEffect.Pure + }; + ShaderGraphNodes.WriteSettings(child, nodeSettings, documents.serialization, documents.context); + float minX = nodes.Min(static node => node.position.x); + float minY = nodes.Min(static node => node.position.y); + var remap = new Dictionary(); + foreach (GraphNodeRecord source in nodes) + { + var id = new GraphNodeID("body/" + source.id.value); + var copy = new GraphNodeRecord(id, source.definitionID) + { + position = new(source.position.x - minX + 280, source.position.y - minY + 80) + }; + foreach ((string key, GraphSerializedValue value)in source.values) + { + if (key != ShaderGraphDocument.C_STAGE_KEY) + { + copy.SetValue(key, value.Clone()); + } + } + child.AddNode(copy); + remap.Add(source.id, id); + } + + foreach (GraphEdgeRecord edge in parent.edges.Where( + edge => selected.Contains(edge.output.nodeID) && selected.Contains(edge.input.nodeID) + )) { + child.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("body/" + edge.id.value), + new GraphEndpoint(remap[edge.output.nodeID], edge.output.portID), + new GraphEndpoint(remap[edge.input.nodeID], edge.input.portID) + ) + ); + } + if (inputs.Length != 0) + { + var boundary = new GraphNodeRecord(new GraphNodeID("function-inputs"), ShaderGraphNodes.C_INPUT_DEFINITION_ID) + { + position = new(20, 80) + }; + boundary.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings { ports = inputs }, documents.serialization, documents.context) + ); + child.AddNode(boundary); + for (int index = 0; index < inputGroups.Length; index++) + { + foreach (GraphEdgeRecord edge in inputGroups[index]) + { + child.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("input/" + edge.id.value), + new GraphEndpoint(boundary.id, new GraphPortID(inputs[index].id)), + new GraphEndpoint(remap[edge.input.nodeID], edge.input.portID) + ) + ); + } + } + } + + if (outputs.Length != 0) + { + var boundary = new GraphNodeRecord(new GraphNodeID("function-outputs"), ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) + { + position = new(nodes.Max(static node => node.position.x) - minX + 600, 80) + }; + boundary.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode( + new ShaderGraphNodeOutputSettings { ports = outputs }, + documents.serialization, + documents.context + ) + ); + child.AddNode(boundary); + for (int index = 0; index < outputGroups.Length; index++) + { + child.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("output/" + index), + new GraphEndpoint(remap[outputGroups[index].Key.nodeID], outputGroups[index].Key.portID), + new GraphEndpoint(boundary.id, new GraphPortID(outputs[index].id)) + ) + ); + } + } + + AssetPath path = UniquePath(draft.path, displayName, documents); + using EditorHistoryTransaction transaction = documents.interactions.history.BeginTransaction("Collapse Shader Subgraph"); + AssetFileEntry created = browser.edits.CreateSource(path, GraphDocumentCodec.Encode(child, documents.serialization)); + Guid sourceID = documents.AssetID(created); + ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface(child, documents.serialization, documents.context); + GraphDocument candidate = parent.Clone(); + foreach (GraphNodeID id in selected) + { + candidate.RemoveNode(id); + } + var call = new GraphNodeRecord(new GraphNodeID(Guid.NewGuid().ToString("N")), ShaderGraphNodes.C_CALL_DEFINITION_ID) + { + position = new(nodes.Average(static node => node.position.x), nodes.Average(static node => node.position.y)) + }; + call.SetValue(ShaderGraphDocument.C_STAGE_KEY, ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); + call.SetValue("sourceId", ShaderGraphDocument.Encode(sourceID, documents.serialization, documents.context)); + call.SetValue("sourcePath", ShaderGraphDocument.Encode(path.ToString(), documents.serialization, documents.context)); + call.SetValue( + ShaderGraphNodes.C_INTERFACE_KEY, + ShaderGraphDocument.Encode(nodeInterface, documents.serialization, documents.context) + ); + candidate.AddNode(call); + for (int index = 0; index < inputGroups.Length; index++) + { + candidate.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + inputGroups[index].Key, + new GraphEndpoint(call.id, new GraphPortID(inputs[index].id)) + ) + ); + } + for (int index = 0; index < outputGroups.Length; index++) + { + foreach (GraphEdgeRecord edge in outputGroups[index]) + { + candidate.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(call.id, new GraphPortID(outputs[index].id)), + edge.input + ) + ); + } + } + ShaderCanvasGroup[] groups = GroupShaderNodes.Read(documents, candidate).Select(group => + { + group.nodes = group.nodes.Where(id => !selected.Contains(new GraphNodeID(id))).ToArray(); + return group; + }).Where(static group => group.nodes.Length != 0).ToArray(); + candidate.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); + controller.ReplaceDocument(candidate, "Collapse Shader Subgraph"); + transaction.Commit(); + draft.canvas.SelectNodes([call.id]); + draft.selectedGroupID = string.Empty; + documents.Changed(draft); + } + + private static ShaderGraphNodePortDefinition Port( + string id, + ShaderSourceType type, + bool required + ) => new() + { + id = id, + type = ShaderGraphType.Capture(type), + required = required + }; + + private static string Unique( + string candidate, + string fallback, + HashSet used + ) { + string root = string.IsNullOrWhiteSpace(candidate) ? fallback : candidate; + string value = root; + for (int suffix = 2; !used.Add(value); suffix++) + { + value = root + suffix; + } + return value; + } + + private static string SuggestedName( + ShaderEditorDocuments documents, + ShaderEditorDocuments.Draft draft, + HashSet selected + ) { + ShaderCanvasGroup? group = GroupShaderNodes.Read( + documents, + documents.Controller(draft).document + ).FirstOrDefault(value => value.nodes.Length == selected.Count && value.nodes.All(id => selected.Contains(new GraphNodeID(id)))); + return group is ShaderCanvasGroup exact && !string.IsNullOrWhiteSpace(exact.title) ? exact.title : "Shader Node"; + } + + private static AssetPath UniquePath( + AssetPath source, + string name, + ShaderEditorDocuments documents + ) { + AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == source.source); + string directory = Path.GetDirectoryName(source.localPath)?.Replace('\\', '/') ?? string.Empty; + string safeName = string.Concat(name.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character)) + .Trim(); + if (safeName.Length == 0) + { + safeName = "Shader Node"; + } + string prefix = directory.Length == 0 ? string.Empty : directory + "/"; + var path = new AssetPath(source.source, prefix + safeName + ".ishader"); + for (int suffix = 2; File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta"); suffix++) + { + path = new(source.source, prefix + safeName + " " + suffix + ".ishader"); + } + return path; + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs new file mode 100644 index 000000000..08192e296 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs @@ -0,0 +1,27 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/copy", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.C, primary: true)] +internal sealed class CopyShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.clipboard = documents.Copy(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs new file mode 100644 index 000000000..a90ebaba8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs @@ -0,0 +1,52 @@ +using System.IO; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/copy-to-project", ShaderEditorCanvas.C_AREA)] +internal sealed class CopyShaderToProject( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceID.project); + string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; + AssetPath destination = AssetPath.Project(name + ".ishader"); + for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) + || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++ + ) { + destination = AssetPath.Project(name + " " + index + ".ishader"); + } + AssetFileEntry entry = browser.edits.CreateSource( + destination, + GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization) + ); + _ = context.interactions.For("panel/asset.file-browser", entry).Select(); + _ = context.interactions.For("panel/asset.file-browser", entry).Execute("file-browser/rename"); + context.interactions.OpenPanel("rendering.shader-editor"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs index b4b964f10..113c555ad 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs @@ -4,12 +4,11 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; -using Inno.Editor.Interactions; using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; -using Inno.Rendering.Shaders; +using Inno.Editor.Interactions; namespace Inno.Editor.Panel.ShaderEditor; + [EditorAction("shader/create-asset", "panel/asset.file-browser")] internal sealed class CreateShaderAsset( ShaderEditorDocuments documents, @@ -28,7 +27,9 @@ AssetEditingModule browser protected override EditorActionState Query(EditorActionContext context) { AssetPath path = AssetPath.Parse(context.target); - return documents.assets.sourceMounts.Any(mount => mount.id == path.source && !mount.isReadOnly) ? EditorActionState.enabled : EditorActionState.disabled; + return documents.assets.sourceMounts.Any(mount => mount.id == path.source && !mount.isReadOnly) + ? EditorActionState.enabled + : EditorActionState.disabled; } /// @@ -43,7 +44,9 @@ protected override void Execute(EditorActionContext context) AssetSourceMount mount = documents.assets.sourceMounts.Single(mount => mount.id == parent.source); string prefix = parent.localPath.TrimEnd('/'); if (prefix.Length != 0) + { prefix += "/"; + } int index = 0; AssetPath path; do @@ -62,28 +65,3 @@ protected override void Execute(EditorActionContext context) context.interactions.OpenPanel("rendering.shader-editor"); } } - -[EditorMenuSource("panel/asset.file-browser")] -internal sealed class ShaderTemplateMenu(ShaderEditorDocuments documents) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - if (documents.templates is null) - return; - builder.AddGroup("Create/Rendering", order: 200, separatorBefore: true); - builder.AddGroup("Create/Rendering/Shaders", order: 0); - foreach (ShaderGraphTemplateInfo template in documents.templates.templates) - builder.Add("Create/Rendering/Shaders/" + template.displayName, "shader/create-asset", argument: template.id, order: 0); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs new file mode 100644 index 000000000..97cac6243 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs @@ -0,0 +1,30 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/create-node", ShaderEditorCanvas.C_AREA)] +internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && documents.CanCreate(draft, context.argument) ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => documents.Create(documents.Open(context.target), context.argument); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs new file mode 100644 index 000000000..c693164ad --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs @@ -0,0 +1,159 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; +using Inno.Rendering; +using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/create-output", ShaderEditorCanvas.C_AREA)] +internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + || draft.readOnly + || !Enum.TryParse(context.argument, out ShaderStage stage) + ) { + return EditorActionState.disabled; + } + GraphDocument graph = documents.Controller(draft).document; + if (ShaderGraphDocument.ReadTarget(graph, documents.serialization, documents.context).Length != 0) + { + return EditorActionState.disabled; + } + bool exists = graph.nodes + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ); + return exists ? EditorActionState.disabled : EditorActionState.enabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + GraphDocument graph = controller.document.Clone(); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + graph, + documents.serialization, + documents.context + ); + ShaderStage stage = Enum.Parse(context.argument); + ShaderProgramKind kind = stage == ShaderStage.Compute + ? ShaderProgramKind.Compute + : ShaderProgramKind.Raster; + ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); + ShaderGraphPassProgram? incomplete = kind == ShaderProgramKind.Raster + ? programs.FirstOrDefault( + program => ( + definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) + && !program.stages + .Select(id => graph.FindNode(new GraphNodeID(id))) + .OfType() + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ) + ) + ) + : null; + string name; + string[] stages; + if (incomplete is ShaderGraphPassProgram existing && existing.pass is not null) + { + name = existing.pass; + stages = existing.stages; + } + else + { + string prefix = kind.ToString(); + name = prefix; + for (int suffix = 2; definition.passes.Any(pass => pass.name == name); suffix++) + { + name = prefix + " " + suffix; + } + definition.passes = [..definition.passes, new ShaderPassDefinition(name, kind)]; + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode( + documents.serialization.Serialize(definition, documents.context), + documents.serialization, + documents.context + ) + ); + stages = []; + } + + var id = new GraphNodeID(Guid.NewGuid().ToString("N")); + var node = new GraphNodeRecord(id, ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + { + position = draft.menuPosition + }; + node.SetValue( + "settings", + ShaderGraphDocument.Encode( + new ShaderGraphStageSettings + { + stage = stage, + outputs = stage == ShaderStage.Compute + ? [] + : [new ShaderGraphOutput() + { + id = stage == ShaderStage.Vertex ? "position" : "color", + kind = stage == ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color + }] + }, + documents.serialization, + documents.context + ) + ); + graph.AddNode(node); + graph = ShaderGraphPrograms.Bind( + graph, + name, + stages.Select(static value => new GraphNodeID(value)).Append(id), + documents.serialization, + documents.context + ); + controller.ReplaceDocument(graph, "Create " + stage + " Output"); + draft.canvas.SelectNodes([id]); + draft.activeStage = id; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs new file mode 100644 index 000000000..c5b4f43e5 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs @@ -0,0 +1,25 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/cut", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.X, primary: true)] +internal sealed class CutShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.clipboard = documents.Copy(draft); + documents.RemoveNodes(draft); + draft.canvas.ClearSelection(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs new file mode 100644 index 000000000..bc4bd2305 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs @@ -0,0 +1,40 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Core.Input; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/delete", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Delete)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Backspace)] +internal sealed class DeleteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Delete Shader Selection"); + if (draft.selectedEdge is GraphEdgeID edge) + { + controller.Disconnect(edge); + } + documents.RemoveNodes(draft); + transaction.Commit(); + draft.selectedEdge = null; + draft.canvas.ClearSelection(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs new file mode 100644 index 000000000..46d9f7c15 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs @@ -0,0 +1,35 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/disconnect", ShaderEditorCanvas.C_AREA)] +internal sealed class DisconnectShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Disconnect Nodes"); + foreach (GraphEdgeRecord edge in controller.document.edges + .Where( + edge => draft.canvas.selectedNodes.Contains(edge.input.nodeID) || draft.canvas.selectedNodes.Contains(edge.output.nodeID) + ) + .ToArray() + ) { + controller.Disconnect(edge.id); + } + transaction.Commit(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs new file mode 100644 index 000000000..b4adcb6f6 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs @@ -0,0 +1,46 @@ +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/duplicate", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.D, primary: true)] +internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft)) + { + return EditorActionState.disabled; + } + return draft.canvas.selectedNodes.Any( + id => documents.Controller(draft).document.FindNode(id)?.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + ) + ? EditorActionState.disabled + : EditorActionState.enabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.Paste(draft, documents.Copy(draft)); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs new file mode 100644 index 000000000..2768a8fbf --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs @@ -0,0 +1,26 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/focus", ShaderEditorCanvas.C_AREA)] +internal sealed class FocusShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => documents.Open(context.target).frameRequested = true; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs new file mode 100644 index 000000000..7ddeb30d8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs @@ -0,0 +1,32 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/format", ShaderEditorCanvas.C_AREA)] +internal sealed class FormatShaderGraph(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + controller.ReplaceDocument( + ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), + "Format Shader Graph" + ); + draft.frameRequested = true; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs new file mode 100644 index 000000000..ef0586205 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs @@ -0,0 +1,49 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/group", ShaderEditorCanvas.C_AREA)] +internal sealed class GroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + internal const string C_GROUPS = "inno.editor.shader.groups"; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocument graph = documents.Controller(draft).document.Clone(); + ShaderCanvasGroup[] groups = Read(documents, graph); + groups = + [ + ..groups, + new ShaderCanvasGroup() + { + id = Guid.NewGuid().ToString("N"), + title = "Group " + (groups.Length + 1), + nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() + } + ]; + graph.SetMetadata(C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); + documents.Controller(draft).ReplaceDocument(graph, "Group Shader Nodes"); + draft.selectedGroupID = groups[^1].id; + documents.Changed(draft); + } + + internal static ShaderCanvasGroup[] Read( + ShaderEditorDocuments documents, + GraphDocument graph + ) => graph.metadata.TryGetValue( + C_GROUPS, + out GraphSerializedValue? value + ) ? ShaderGraphDocument.Decode(value, documents.serialization, documents.context) : []; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs new file mode 100644 index 000000000..88e9608b0 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reroute", ShaderEditorCanvas.C_AREA)] +internal sealed class InsertShaderReroute(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + GraphDocument graph = controller.document.Clone(); + GraphEdgeRecord edge = graph.edges.Single(value => value.id == draft.selectedEdge); + ShaderNodePort source = draft.ports[edge.output.nodeID].Single(value => value.id == edge.output.portID.value); + var node = new GraphNodeRecord(new GraphNodeID(Guid.NewGuid().ToString("N")), "inno.shader.reroute") + { + position = draft.menuPosition + }; + node.SetValue( + "valueType", + ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context) + ); + string stage = ShaderGraphDocument.Read( + graph.FindNode(edge.output.nodeID)!, + "stage", + string.Empty, + documents.serialization, + documents.context + ); + node.SetValue("stage", ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); + graph.AddNode(node); + graph.RemoveEdge(edge.id); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + edge.output, + new GraphEndpoint(node.id, new GraphPortID("input")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(node.id, new GraphPortID("value")), + edge.input + ) + ); + controller.ReplaceDocument(graph, "Insert Shader Reroute"); + draft.selectedEdge = null; + draft.canvas.SelectNodes([node.id]); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs new file mode 100644 index 000000000..285fe0257 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs @@ -0,0 +1,45 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/paste", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.V, primary: true)] +internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.clipboard is not null + && documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && documents.CanPaste(draft, documents.clipboard) ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + if (documents.clipboard is not null) + { + documents.Paste(draft, documents.clipboard); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs new file mode 100644 index 000000000..15b8d595d --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs @@ -0,0 +1,27 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reload", ShaderEditorCanvas.C_AREA)] +internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Revert(documents.Open(context.target).documentID); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs new file mode 100644 index 000000000..e626a5998 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs @@ -0,0 +1,43 @@ +using System.IO; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reveal-shader", ShaderEditorCanvas.C_AREA)] +internal sealed class RevealShaderAsset( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; + browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); + if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) + { + throw new FileNotFoundException("Shader source is missing from the Asset Browser.", draft.path.ToString()); + } + documents.interactions.SetSelection(entry); + documents.interactions.OpenPanel("asset.file-browser"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs new file mode 100644 index 000000000..58e92a0e8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reveal-source", ShaderEditorCanvas.C_AREA)] +internal sealed class RevealShaderFunction( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!base.Query(context).isEnabled) + { + return EditorActionState.disabled; + } + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + string? definition = draft.canvas.selectedNodes.Count == 1 + ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionID + : null; + return definition is "inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID + ? EditorActionState.enabled + : EditorActionState.disabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphNodeRecord node = documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())!; + Reveal(documents, browser, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, documents.serialization, documents.context)); + } + + internal static void Reveal( + ShaderEditorDocuments documents, + AssetBrowserModule browser, + Guid sourceID + ) { + if (!documents.assets.TryGetInfo(sourceID, out AssetInfo? info) || info is null) + { + throw new IOException("Referenced Shader authoring asset is missing. Select a replacement in the node."); + } + if (!documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) + { + throw new FileNotFoundException( + "Referenced Shader authoring asset is missing from the Asset Browser.", + info.assetPath.ToString() + ); + } + string parent = Path.GetDirectoryName(info.assetPath.localPath)?.Replace('\\', '/') ?? string.Empty; + browser.browser.SetCurrentDirectory(new AssetPath(info.assetPath.source, parent).ToString()); + documents.interactions.SetSelection(entry); + documents.interactions.OpenPanel("asset.file-browser"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs new file mode 100644 index 000000000..cf19807fd --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs @@ -0,0 +1,24 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/save", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.S, primary: true)] +internal sealed class SaveShader(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Save(documents.Open(context.target).documentID); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs deleted file mode 100644 index 158fe9913..000000000 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs +++ /dev/null @@ -1,556 +0,0 @@ -using Inno.Editor.Core; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders.ImGui; -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Graphs; -using Inno.Core.Input; -using Inno.Editor.Interactions; -using Inno.Editor.Shaders; -using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; -using Inno.Rendering.Assets.Authoring; - -namespace Inno.Editor.Panel.ShaderEditor; -[EditorMenuSource(ShaderEditorCanvas.C_AREA)] -internal sealed class ShaderCanvasMenu(ShaderEditorDocuments documents) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out var draft)) - return; - builder.AddGroup("Create/Functions", order: 500, separatorBefore: true); - builder.AddGroup("Create/Graph Nodes", order: 550, separatorBefore: true); - builder.AddGroup("Create/Domain Outputs", order: 800, separatorBefore: true); - bool explicitStages = ShaderGraphDocument.ReadTarget(documents.Controller(draft).document, documents.serialization, documents.context).Length == 0; - if (draft.createFromPort is null && explicitStages) - { - builder.Add("Create/Outputs/Vertex Output", "shader/create-output", order: 0, argument: "Vertex"); - builder.Add("Create/Outputs/Fragment Output", "shader/create-output", order: 10, argument: "Fragment"); - builder.Add("Create/Outputs/Compute Output", "shader/create-output", order: 20, argument: "Compute"); - } - - foreach (string definition in documents.nodes.definitionIds) - if (definition is not ("inno.shader.source" or ShaderGraphNodes.callDefinitionId) && documents.CanCreate(draft, new(definition))) - { - string category = Category(definition); - int order = CategoryOrder(category); - if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true && presentation.createPath.Length != 0) - { - category = presentation.createPath; - order = presentation.createOrder; - builder.AddGroup("Create/" + category, order, presentation.separatorBefore); - } - - builder.Add( - "Create/" + category + "/" + (documents.drawers?.GetDisplayName(definition) ?? EditorDisplayNames.Nicify(definition.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' '))), - "shader/create-node", - order, - argument: new ShaderNodeCreation(definition) - ); - } - - var functionLibraries = new List<(AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)>(); - foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) - if (source.extension == ".ishadersource" - && documents.assets.TryGetInfo( - source.assetPath, - out var info - ) - && info is not null - && documents.assets.TryLoad( - info.persistentId, - out ShaderFunctionAsset? library - ) - && library is not null - && !library.isMissing) - functionLibraries.Add((source, info, library)); - foreach (var catalog in functionLibraries.Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)).Where(static value => value.path.Length != 0).GroupBy( - static value => value.path.Split('/')[0], - StringComparer.Ordinal - ).Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))).OrderBy(static value => value.order).ThenBy( - static value => value.name, - StringComparer.Ordinal - )) - builder.AddGroup("Create/Functions/" + catalog.name, order: 500 + catalog.order, separatorBefore: true); - foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries.OrderBy(static value => value.library.catalogOrder).ThenBy( - static value => value.source.nameWithoutExtension, - StringComparer.Ordinal - )) - foreach (string function in library.exports) - if (documents.CanCreate(draft, new("inno.shader.source", info.persistentId, function))) - { - string catalog = NormalizeCatalog(library.catalogPath); - string prefix = "Create/Functions/" + (catalog.Length == 0 ? "General" : catalog); - builder.Add( - prefix + "/" + source.nameWithoutExtension + "/" + function, - "shader/create-node", - order: 500 + library.catalogOrder, - argument: new ShaderNodeCreation("inno.shader.source", info.persistentId, function) - ); - } - - foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.extension == ".ishader").OrderBy( - static entry => entry.assetPath.ToString(), - StringComparer.Ordinal - )) - { - if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) || info is null || info.persistentId == draft.id || info.status != AssetImportStatus.Imported) - continue; - ShaderGraphNodeInterface nodeInterface; - try - { - nodeInterface = documents.LoadGraphNodeInterface(info.persistentId); - } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) - { - continue; - } - - var creation = new ShaderNodeCreation(ShaderGraphNodes.callDefinitionId, info.persistentId); - if (!documents.CanCreate(draft, creation)) - continue; - string catalog = NormalizeCatalog(nodeInterface.createPath); - string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; - string group = "Create/" + root + (catalog.Length == 0 ? "" : "/" + catalog); - builder.AddGroup(group, order: nodeInterface.createOrder, separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput); - builder.Add(group + "/" + nodeInterface.displayName, "shader/create-node", order: nodeInterface.createOrder, argument: creation); - } - - builder.Add("View/Focus Selection", "shader/focus", order: 900); - builder.Add("Edit/Copy", "shader/copy", order: 1000); - builder.Add("Edit/Cut", "shader/cut", order: 110); - builder.Add("Edit/Paste", "shader/paste", order: 120); - builder.Add("Edit/Duplicate", "shader/duplicate", order: 130); - builder.Add("Edit/Delete", "shader/delete", order: 140, separatorBefore: true); - builder.Add("Connections/Disconnect", "shader/disconnect", order: 1500); - builder.Add("Connections/Insert Reroute", "shader/reroute", order: 160); - builder.Add("Organize/Group Selection", "shader/group", order: 1700); - builder.Add("Organize/Ungroup Selection", "shader/ungroup", order: 180); - builder.Add("Organize/Collapse to Subgraph", "shader/collapse-subgraph", order: 190, separatorBefore: true); - builder.Add("Assets/Show Shader in File Browser", "shader/reveal-shader", order: 1900); - builder.Add("Assets/Show Source in File Browser", "shader/reveal-source", order: 1910); - builder.Add("Assets/Copy Shader To Project", "shader/copy-to-project", order: 1920, separatorBefore: true); - static string Category(string definition) => definition switch - { - "inno.shader.constant" or "inno.shader.stage-input" => "Inputs", - ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId => "Interface", - "inno.shader.sample" => "Textures", - "inno.shader.binary" or "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" => "Math", - "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => "Resources", - "inno.shader.discard" => "Flow", - "inno.shader.reroute" => "Utility", - _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domain Outputs", - _ => "Domain" - }; - static int CategoryOrder(string category) => category switch - { - "Outputs" => 0, - "Interface" => 50, - "Inputs" => 100, - "Textures" => 200, - "Math" => 300, - "Resources" => 400, - "Flow" => 600, - "Utility" => 700, - "Domain Outputs" => 800, - _ => 850 - }; - static string NormalizeCatalog(string value) => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); - } -} - -[EditorAction("shader/create-output", ShaderEditorCanvas.C_AREA)] -internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!documents.TryGet(context.target, out var draft) || draft.readOnly || !Enum.TryParse(context.argument, out Inno.Rendering.ShaderStage stage)) - return EditorActionState.disabled; - GraphDocument graph = documents.Controller(draft).document; - if (ShaderGraphDocument.ReadTarget(graph, documents.serialization, documents.context).Length != 0) - return EditorActionState.disabled; - bool exists = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).Any(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), documents.serialization, documents.context).stage == stage); - return exists ? EditorActionState.disabled : EditorActionState.enabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - GraphDocument graph = controller.document.Clone(); - Inno.Rendering.Assets.ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, documents.serialization, documents.context); - Inno.Rendering.ShaderStage stage = Enum.Parse(context.argument); - Inno.Rendering.ShaderProgramKind kind = stage == Inno.Rendering.ShaderStage.Compute ? Inno.Rendering.ShaderProgramKind.Compute : Inno.Rendering.ShaderProgramKind.Raster; - ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); - ShaderGraphPassProgram? incomplete = kind == Inno.Rendering.ShaderProgramKind.Raster ? programs.FirstOrDefault(program => definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) && !program.stages.Select(id => graph.FindNode(new(id))).OfType().Any(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), documents.serialization, documents.context).stage == stage)) : null; - string name; - string[] stages; - if (incomplete is ShaderGraphPassProgram existing && existing.pass is not null) - { - name = existing.pass; - stages = existing.stages; - } - else - { - string prefix = kind.ToString(); - name = prefix; - for (int suffix = 2; definition.passes.Any(pass => pass.name == name); suffix++) - name = prefix + " " + suffix; - definition.passes = [..definition.passes, new(name, kind)]; - graph.SetMetadata( - ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(documents.serialization.Serialize(definition, documents.context), documents.serialization, documents.context) - ); - stages = []; - } - - GraphNodeId id = new(Guid.NewGuid().ToString("N")); - var node = new GraphNodeRecord(id, ShaderGraphDocument.outputDefinitionId) - { - position = draft.menuPosition - }; - node.SetValue( - "settings", - ShaderGraphDocument.Encode( - new ShaderGraphStageSettings { - stage = stage, - outputs = stage == Inno.Rendering.ShaderStage.Compute ? [] : [new() { id = stage == Inno.Rendering.ShaderStage.Vertex ? "position" : "color", kind = stage == Inno.Rendering.ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color }] - }, - documents.serialization, - documents.context - ) - ); - graph.AddNode(node); - graph = ShaderGraphPrograms.Bind(graph, name, stages.Select(static value => new GraphNodeId(value)).Append(id), documents.serialization, documents.context); - controller.ReplaceDocument(graph, "Create " + stage + " Output"); - draft.canvas.SelectNodes([id]); - draft.activeStage = id; - documents.Changed(draft); - } -} - -[EditorAction("shader/create-node", ShaderEditorCanvas.C_AREA)] -internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => documents.TryGet( - context.target, - out var draft - ) - && documents.CanCreate( - draft, - context.argument - ) ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => documents.Create(documents.Open(context.target), context.argument); -} - -internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Gets documents presented by this Shader Editor action. - /// - protected ShaderEditorDocuments documents { get; } = documents; - /// - /// Gets whether writes is active for the current instance. - /// - protected virtual bool writes => true; - /// - /// Gets whether needs selection is active for the current instance. - /// - protected virtual bool needsSelection => true; - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => documents.TryGet( - context.target, - out var draft - ) - && (!writes - || !draft.readOnly) - && (!needsSelection - || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; -} - -[EditorAction("shader/copy", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.C, primary: true)] -internal sealed class CopyShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - documents.clipboard = documents.Copy(draft); - } -} - -[EditorAction("shader/delete", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Delete)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Backspace)] -internal sealed class DeleteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - using var transaction = context.history.BeginTransaction("Delete Shader Selection"); - if (draft.selectedEdge is GraphEdgeId edge) - controller.Disconnect(edge); - documents.RemoveNodes(draft); - transaction.Commit(); - draft.selectedEdge = null; - draft.canvas.ClearSelection(); - documents.Changed(draft); - } -} - -[EditorAction("shader/cut", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.X, primary: true)] -internal sealed class CutShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - documents.clipboard = documents.Copy(draft); - documents.RemoveNodes(draft); - draft.canvas.ClearSelection(); - documents.Changed(draft); - } -} - -[EditorAction("shader/paste", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.V, primary: true)] -internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => base.Query(context).isEnabled - && documents.clipboard is not null - && documents.TryGet( - context.target, - out var draft - ) - && documents.CanPaste( - draft, - documents.clipboard - ) ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - if (documents.clipboard is not null) - documents.Paste(draft, documents.clipboard); - } -} - -[EditorAction("shader/duplicate", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.D, primary: true)] -internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out var draft)) - return EditorActionState.disabled; - return draft.canvas.selectedNodes.Any(id => documents.Controller(draft).document.FindNode(id)?.definitionId == ShaderGraphDocument.outputDefinitionId) ? EditorActionState.disabled : EditorActionState.enabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - documents.Paste(draft, documents.Copy(draft)); - } -} - -[EditorAction("shader/disconnect", ShaderEditorCanvas.C_AREA)] -internal sealed class DisconnectShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - using var transaction = context.history.BeginTransaction("Disconnect Nodes"); - foreach (GraphEdgeRecord edge in controller.document.edges.Where(edge => draft.canvas.selectedNodes.Contains(edge.input.nodeId) || draft.canvas.selectedNodes.Contains(edge.output.nodeId)).ToArray()) - controller.Disconnect(edge.id); - transaction.Commit(); - documents.Changed(draft); - } -} - -[EditorAction("shader/save", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.S, primary: true)] -internal sealed class SaveShader(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => context.interactions.documents.Save(documents.Open(context.target).documentId); -} - -[EditorAction("shader/format", ShaderEditorCanvas.C_AREA)] -internal sealed class FormatShaderGraph(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - controller.ReplaceDocument(ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), "Format Shader Graph"); - draft.frameRequested = true; - documents.Changed(draft); - } -} - -[EditorAction("shader/reload", ShaderEditorCanvas.C_AREA)] -internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => context.interactions.documents.Revert(documents.Open(context.target).documentId); -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs new file mode 100644 index 000000000..b9c92259b --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs @@ -0,0 +1,19 @@ +namespace Inno.Editor.Panel.ShaderEditor; + +internal struct ShaderCanvasGroup +{ + /// + /// Gets the stable identity used to reference this value across subsystem boundaries. + /// + public string id { get; set; } + + /// + /// Gets the title text used by the current instance. + /// + public string title { get; set; } + + /// + /// Gets graph nodes affected by this organization action. + /// + public string[] nodes { get; set; } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs new file mode 100644 index 000000000..90a850254 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.Editor.Shaders.ImGui; +using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorMenuSource(ShaderEditorCanvas.C_AREA)] +internal sealed class ShaderCanvasMenu(ShaderEditorDocuments documents) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out ShaderEditorDocuments.Draft draft)) + { + return; + } + builder.AddGroup("Create/Functions", order: 500, separatorBefore: true); + builder.AddGroup("Create/Graph Nodes", order: 550, separatorBefore: true); + builder.AddGroup("Create/Domain Outputs", order: 800, separatorBefore: true); + bool explicitStages = ShaderGraphDocument.ReadTarget( + documents.Controller(draft).document, + documents.serialization, + documents.context + ).Length == 0; + if (draft.createFromPort is null && explicitStages) + { + builder.Add("Create/Outputs/Vertex Output", "shader/create-output", order: 0, argument: "Vertex"); + builder.Add("Create/Outputs/Fragment Output", "shader/create-output", order: 10, argument: "Fragment"); + builder.Add("Create/Outputs/Compute Output", "shader/create-output", order: 20, argument: "Compute"); + } + + foreach (string definition in documents.nodes.definitionIDs) + { + if (definition is not ("inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID) + && documents.CanCreate(draft, new ShaderNodeCreation(definition)) + ) { + string category = Category(definition); + int order = CategoryOrder(category); + if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true + && presentation.createPath.Length != 0 + ) { + category = presentation.createPath; + order = presentation.createOrder; + builder.AddGroup("Create/" + category, order, presentation.separatorBefore); + } + + builder.Add( + "Create/" + + category + + "/" + + (documents.drawers?.GetDisplayName(definition) + ?? EditorDisplayNames.Nicify( + definition.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') + )), + "shader/create-node", + order, + argument: new ShaderNodeCreation(definition) + ); + } + } + + List<(AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)> functionLibraries = []; + foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) + { + if (source.extension == ".ishadersource" + && documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) + && info is not null + && documents.assets.TryLoad(info.persistentID, out ShaderFunctionAsset? library) + && library is not null + && !library.isMissing + ) { + functionLibraries.Add((source, info, library)); + } + } + foreach ((string name, int order) catalog in functionLibraries + .Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)) + .Where(static value => value.path.Length != 0) + .GroupBy(static value => value.path.Split('/')[0], StringComparer.Ordinal) + .Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))) + .OrderBy(static value => value.order) + .ThenBy(static value => value.name, StringComparer.Ordinal) + ) { + builder.AddGroup("Create/Functions/" + catalog.name, order: 500 + catalog.order, separatorBefore: true); + } + foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries + .OrderBy(static value => value.library.catalogOrder) + .ThenBy(static value => value.source.nameWithoutExtension, StringComparer.Ordinal) + ) { + foreach (string function in library.exports) + { + if (documents.CanCreate(draft, new ShaderNodeCreation("inno.shader.source", info.persistentID, function))) + { + string catalog = NormalizeCatalog(library.catalogPath); + string prefix = "Create/Functions/" + (catalog.Length == 0 ? "General" : catalog); + builder.Add( + prefix + "/" + source.nameWithoutExtension + "/" + function, + "shader/create-node", + order: 500 + library.catalogOrder, + argument: new ShaderNodeCreation("inno.shader.source", info.persistentID, function) + ); + } + } + } + + foreach (AssetFileEntry source in documents.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.extension == ".ishader") + .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) + ) { + if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) + || info is null + || info.persistentID == draft.id + || info.status != AssetImportStatus.Imported + ) { + continue; + } + ShaderGraphNodeInterface nodeInterface; + try + { + nodeInterface = documents.LoadGraphNodeInterface(info.persistentID); + } + catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + continue; + } + + var creation = new ShaderNodeCreation(ShaderGraphNodes.C_CALL_DEFINITION_ID, info.persistentID); + if (!documents.CanCreate(draft, creation)) + { + continue; + } + string catalog = NormalizeCatalog(nodeInterface.createPath); + string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; + string group = "Create/" + root + (catalog.Length == 0 ? string.Empty : "/" + catalog); + builder.AddGroup( + group, + order: nodeInterface.createOrder, + separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput + ); + builder.Add( + group + "/" + nodeInterface.displayName, + "shader/create-node", + order: nodeInterface.createOrder, + argument: creation + ); + } + + builder.Add("View/Focus Selection", "shader/focus", order: 900); + builder.Add("Edit/Copy", "shader/copy", order: 1000); + builder.Add("Edit/Cut", "shader/cut", order: 110); + builder.Add("Edit/Paste", "shader/paste", order: 120); + builder.Add("Edit/Duplicate", "shader/duplicate", order: 130); + builder.Add("Edit/Delete", "shader/delete", order: 140, separatorBefore: true); + builder.Add("Connections/Disconnect", "shader/disconnect", order: 1500); + builder.Add("Connections/Insert Reroute", "shader/reroute", order: 160); + builder.Add("Organize/Group Selection", "shader/group", order: 1700); + builder.Add("Organize/Ungroup Selection", "shader/ungroup", order: 180); + builder.Add("Organize/Collapse to Subgraph", "shader/collapse-subgraph", order: 190, separatorBefore: true); + builder.Add("Assets/Show Shader in File Browser", "shader/reveal-shader", order: 1900); + builder.Add("Assets/Show Source in File Browser", "shader/reveal-source", order: 1910); + builder.Add("Assets/Copy Shader To Project", "shader/copy-to-project", order: 1920, separatorBefore: true); + static string Category(string definition) + => definition switch + { + "inno.shader.constant" or "inno.shader.stage-input" => "Inputs", + ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID => "Interface", + "inno.shader.sample" => "Textures", + "inno.shader.binary" or "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" => "Math", + "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => "Resources", + "inno.shader.discard" => "Flow", + "inno.shader.reroute" => "Utility", + _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domain Outputs", + _ => "Domain" + }; + static int CategoryOrder(string category) + => category switch + { + "Outputs" => 0, + "Interface" => 50, + "Inputs" => 100, + "Textures" => 200, + "Math" => 300, + "Resources" => 400, + "Flow" => 600, + "Utility" => 700, + "Domain Outputs" => 800, + _ => 850 + }; + static string NormalizeCatalog(string value) + => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs deleted file mode 100644 index 29a18c26b..000000000 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs +++ /dev/null @@ -1,519 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Graphs; -using Inno.Editor.Graph; -using Inno.Editor.Interactions; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; -using Inno.Rendering; -using Inno.Rendering.Shaders; -using Inno.Rendering.Assets; - -namespace Inno.Editor.Panel.ShaderEditor; -internal struct ShaderCanvasGroup -{ - /// - /// Gets the stable identity used to reference this value across subsystem boundaries. - /// - public string id { get; set; } - /// - /// Gets the title text used by the current instance. - /// - public string title { get; set; } - /// - /// Gets graph nodes affected by this organization action. - /// - public string[] nodes { get; set; } -} - -[EditorAction("shader/focus", ShaderEditorCanvas.C_AREA)] -internal sealed class FocusShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => documents.Open(context.target).frameRequested = true; -} - -[EditorAction("shader/reroute", ShaderEditorCanvas.C_AREA)] -internal sealed class InsertShaderReroute(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => base.Query(context).isEnabled - && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - GraphDocument graph = controller.document.Clone(); - GraphEdgeRecord edge = graph.edges.Single(value => value.id == draft.selectedEdge); - ShaderNodePort source = draft.ports[edge.output.nodeId].Single(value => value.id == edge.output.portId.value); - var node = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), "inno.shader.reroute") - { - position = draft.menuPosition - }; - node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context)); - string stage = ShaderGraphDocument.Read(graph.FindNode(edge.output.nodeId)!, "stage", "", documents.serialization, documents.context); - node.SetValue("stage", ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); - graph.AddNode(node); - graph.RemoveEdge(edge.id); - graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), edge.output, new(node.id, new("input")))); - graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(node.id, new("value")), edge.input)); - controller.ReplaceDocument(graph, "Insert Shader Reroute"); - draft.selectedEdge = null; - draft.canvas.SelectNodes([node.id]); - documents.Changed(draft); - } -} - -[EditorAction("shader/group", ShaderEditorCanvas.C_AREA)] -internal sealed class GroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - internal const string C_GROUPS = "inno.editor.shader.groups"; - internal static ShaderCanvasGroup[] Read( - ShaderEditorDocuments documents, - GraphDocument graph - ) => graph.metadata.TryGetValue( - C_GROUPS, - out GraphSerializedValue? value - ) ? ShaderGraphDocument.Decode( - value, - documents.serialization, - documents.context - ) : []; - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - GraphDocument graph = documents.Controller(draft).document.Clone(); - ShaderCanvasGroup[] groups = Read(documents, graph); - groups = [..groups, new() - { - id = Guid.NewGuid().ToString("N"), - title = "Group " + (groups.Length + 1), - nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() - } - - ]; - graph.SetMetadata(C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); - documents.Controller(draft).ReplaceDocument(graph, "Group Shader Nodes"); - draft.selectedGroupId = groups[^1].id; - documents.Changed(draft); - } -} - -[EditorAction("shader/ungroup", ShaderEditorCanvas.C_AREA)] -internal sealed class UngroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - GraphDocument graph = documents.Controller(draft).document.Clone(); - var groups = GroupShaderNodes.Read( - documents, - graph - ).Where(group => draft.selectedGroupId.Length != 0 ? group.id != draft.selectedGroupId : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new(id)))).ToArray(); - graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); - documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); - draft.selectedGroupId = ""; - documents.Changed(draft); - } -} - -[EditorAction("shader/collapse-subgraph", ShaderEditorCanvas.C_AREA)] -internal sealed class CollapseShaderSubgraph( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!base.Query(context).isEnabled) - return EditorActionState.disabled; - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocument graph = documents.Controller(draft).document; - GraphNodeRecord[] selected = draft.canvas.selectedNodes.Select(graph.FindNode).OfType().ToArray(); - if (selected.Length != draft.canvas.selectedNodes.Count - || selected.Any(static node => node.definitionId is ShaderGraphDocument.outputDefinitionId or ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId)) - return EditorActionState.disabled; - string[] stages = selected.Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)).Distinct(StringComparer.Ordinal).ToArray(); - if (stages.Length != 1 || stages[0].Length == 0) - return EditorActionState.disabled; - HashSet ids = selected.Select(static node => node.id).ToHashSet(); - return graph.edges.Any(edge => ids.Contains(edge.input.nodeId) != ids.Contains(edge.output.nodeId)) ? EditorActionState.enabled : EditorActionState.disabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - GraphDocument parent = controller.document; - HashSet selected = [..draft.canvas.selectedNodes]; - GraphNodeRecord[] nodes = parent.nodes.Where(node => selected.Contains(node.id)).ToArray(); - string stage = nodes.Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)).Distinct(StringComparer.Ordinal).Single(); - GraphEdgeRecord[] incomingEdges = parent.edges.Where(edge => selected.Contains(edge.input.nodeId) && !selected.Contains(edge.output.nodeId)).ToArray(); - GraphEdgeRecord[] outgoingEdges = parent.edges.Where(edge => selected.Contains(edge.output.nodeId) && !selected.Contains(edge.input.nodeId)).ToArray(); - var inputGroups = incomingEdges.GroupBy(static edge => edge.output).ToArray(); - var outputGroups = outgoingEdges.GroupBy(static edge => edge.output).ToArray(); - var inputNames = new HashSet(StringComparer.Ordinal); - var outputNames = new HashSet(StringComparer.Ordinal); - ShaderGraphNodePortDefinition[] inputs = inputGroups.Select(group => Port(Unique(group.First().input.portId.value, "input", inputNames), draft.ports[group.First().input.nodeId].Single(port => port.id == group.First().input.portId.value).type, required: true)).ToArray(); - ShaderGraphNodePortDefinition[] outputs = outputGroups.Select(group => Port(Unique(group.Key.portId.value, "output", outputNames), draft.ports[group.Key.nodeId].Single(port => port.id == group.Key.portId.value).type, required: false)).ToArray(); - ShaderDefinition parentDefinition = ShaderGraphDocument.ReadDefinition(parent, documents.serialization, documents.context); - HashSet ownedBindings = nodes.Where(static node => node.definitionId == "inno.shader.stage-input").Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, new ShaderGraphInputSettings(), documents.serialization, documents.context).id).ToHashSet(StringComparer.Ordinal); - ShaderDefinition childDefinition = new("Graph Node", parentDefinition.properties.Where(property => ownedBindings.Contains(property.id.value)), [], []); - GraphDocument child = ShaderGraphDocument.Create(childDefinition, documents.serialization, documents.context); - string displayName = SuggestedName(documents, draft, selected); - var nodeSettings = new ShaderGraphNodeSettings - { - displayName = displayName, - createPath = "Project", - kind = ShaderGraphNodeKind.Function, - effect = outputs.Length == 0 ? ShaderGraphNodeEffect.SideEffect : ShaderGraphNodeEffect.Pure - }; - ShaderGraphNodes.WriteSettings(child, nodeSettings, documents.serialization, documents.context); - float minX = nodes.Min(static node => node.position.x); - float minY = nodes.Min(static node => node.position.y); - var remap = new Dictionary(); - foreach (GraphNodeRecord source in nodes) - { - var id = new GraphNodeId("body/" + source.id.value); - var copy = new GraphNodeRecord(id, source.definitionId) - { - position = new(source.position.x - minX + 280, source.position.y - minY + 80) - }; - foreach ((string key, GraphSerializedValue value)in source.values) - if (key != ShaderGraphDocument.stageKey) - copy.SetValue(key, value.Clone()); - child.AddNode(copy); - remap.Add(source.id, id); - } - - foreach (GraphEdgeRecord edge in parent.edges.Where(edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId))) - child.AddEdge(new(new("body/" + edge.id.value), new(remap[edge.output.nodeId], edge.output.portId), new(remap[edge.input.nodeId], edge.input.portId))); - if (inputs.Length != 0) - { - var boundary = new GraphNodeRecord(new("function-inputs"), ShaderGraphNodes.inputDefinitionId) - { - position = new(20, 80) - }; - boundary.SetValue( - ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings { ports = inputs }, documents.serialization, documents.context) - ); - child.AddNode(boundary); - for (int index = 0; index < inputGroups.Length; index++) - foreach (GraphEdgeRecord edge in inputGroups[index]) - child.AddEdge(new(new("input/" + edge.id.value), new(boundary.id, new(inputs[index].id)), new(remap[edge.input.nodeId], edge.input.portId))); - } - - if (outputs.Length != 0) - { - var boundary = new GraphNodeRecord(new("function-outputs"), ShaderGraphNodes.outputDefinitionId) - { - position = new(nodes.Max(static node => node.position.x) - minX + 600, 80) - }; - boundary.SetValue( - ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings { ports = outputs }, documents.serialization, documents.context) - ); - child.AddNode(boundary); - for (int index = 0; index < outputGroups.Length; index++) - child.AddEdge(new(new("output/" + index), new(remap[outputGroups[index].Key.nodeId], outputGroups[index].Key.portId), new(boundary.id, new(outputs[index].id)))); - } - - AssetPath path = UniquePath(draft.path, displayName, documents); - using EditorHistoryTransaction transaction = documents.interactions.history.BeginTransaction("Collapse Shader Subgraph"); - AssetFileEntry created = browser.edits.CreateSource(path, GraphDocumentCodec.Encode(child, documents.serialization)); - Guid sourceId = documents.AssetId(created); - ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface(child, documents.serialization, documents.context); - GraphDocument candidate = parent.Clone(); - foreach (GraphNodeId id in selected) - candidate.RemoveNode(id); - var call = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), ShaderGraphNodes.callDefinitionId) - { - position = new(nodes.Average(static node => node.position.x), nodes.Average(static node => node.position.y)) - }; - call.SetValue(ShaderGraphDocument.stageKey, ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); - call.SetValue("sourceId", ShaderGraphDocument.Encode(sourceId, documents.serialization, documents.context)); - call.SetValue("sourcePath", ShaderGraphDocument.Encode(path.ToString(), documents.serialization, documents.context)); - call.SetValue(ShaderGraphNodes.interfaceKey, ShaderGraphDocument.Encode(nodeInterface, documents.serialization, documents.context)); - candidate.AddNode(call); - for (int index = 0; index < inputGroups.Length; index++) - candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), inputGroups[index].Key, new(call.id, new(inputs[index].id)))); - for (int index = 0; index < outputGroups.Length; index++) - foreach (GraphEdgeRecord edge in outputGroups[index]) - candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(call.id, new(outputs[index].id)), edge.input)); - ShaderCanvasGroup[] groups = GroupShaderNodes.Read(documents, candidate).Select(group => - { - group.nodes = group.nodes.Where(id => !selected.Contains(new(id))).ToArray(); - return group; - }).Where(static group => group.nodes.Length != 0).ToArray(); - candidate.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); - controller.ReplaceDocument(candidate, "Collapse Shader Subgraph"); - transaction.Commit(); - draft.canvas.SelectNodes([call.id]); - draft.selectedGroupId = ""; - documents.Changed(draft); - } - - private static ShaderGraphNodePortDefinition Port( - string id, - ShaderSourceType type, - bool required - ) => new() - { - id = id, - type = ShaderGraphType.Capture(type), - required = required - }; - private static string Unique( - string candidate, - string fallback, - HashSet used - ) { - string root = string.IsNullOrWhiteSpace(candidate) ? fallback : candidate; - string value = root; - for (int suffix = 2; !used.Add(value); suffix++) - value = root + suffix; - return value; - } - - private static string SuggestedName( - ShaderEditorDocuments documents, - ShaderEditorDocuments.Draft draft, - HashSet selected - ) { - ShaderCanvasGroup? group = GroupShaderNodes.Read( - documents, - documents.Controller(draft).document - ).FirstOrDefault(value => value.nodes.Length == selected.Count && value.nodes.All(id => selected.Contains(new(id)))); - return group is ShaderCanvasGroup exact && !string.IsNullOrWhiteSpace(exact.title) ? exact.title : "Shader Node"; - } - - private static AssetPath UniquePath( - AssetPath source, - string name, - ShaderEditorDocuments documents - ) { - AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == source.source); - string directory = Path.GetDirectoryName(source.localPath)?.Replace('\\', '/') ?? ""; - string safeName = string.Concat(name.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character)).Trim(); - if (safeName.Length == 0) - safeName = "Shader Node"; - string prefix = directory.Length == 0 ? "" : directory + "/"; - AssetPath path = new(source.source, prefix + safeName + ".ishader"); - for (int suffix = 2; File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta"); suffix++) - path = new(source.source, prefix + safeName + " " + suffix + ".ishader"); - return path; - } -} - -[EditorAction("shader/reveal-source", ShaderEditorCanvas.C_AREA)] -internal sealed class RevealShaderFunction( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!base.Query(context).isEnabled) - return EditorActionState.disabled; - var draft = documents.Open(context.target); - string? definition = draft.canvas.selectedNodes.Count == 1 ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionId : null; - return definition is "inno.shader.source" or ShaderGraphNodes.callDefinitionId ? EditorActionState.enabled : EditorActionState.disabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - GraphNodeRecord node = documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())!; - Reveal(documents, browser, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, documents.serialization, documents.context)); - } - - internal static void Reveal( - ShaderEditorDocuments documents, - AssetBrowserModule browser, - Guid sourceId - ) { - if (!documents.assets.TryGetInfo(sourceId, out AssetInfo? info) || info is null) - throw new IOException("Referenced Shader authoring asset is missing. Select a replacement in the node."); - if (!documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) - throw new FileNotFoundException("Referenced Shader authoring asset is missing from the Asset Browser.", info.assetPath.ToString()); - string parent = Path.GetDirectoryName(info.assetPath.localPath)?.Replace('\\', '/') ?? string.Empty; - browser.browser.SetCurrentDirectory(new AssetPath(info.assetPath.source, parent).ToString()); - documents.interactions.SetSelection(entry); - documents.interactions.OpenPanel("asset.file-browser"); - } -} - -[EditorAction("shader/reveal-shader", ShaderEditorCanvas.C_AREA)] -internal sealed class RevealShaderAsset( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; - browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); - if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) - throw new FileNotFoundException("Shader source is missing from the Asset Browser.", draft.path.ToString()); - documents.interactions.SetSelection(entry); - documents.interactions.OpenPanel("asset.file-browser"); - } -} - -[EditorAction("shader/check", ShaderEditorCanvas.C_AREA)] -internal sealed class ShowShaderDiagnostics(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => documents.ShowCheck(documents.Open(context.target)); -} - -[EditorAction("shader/copy-to-project", ShaderEditorCanvas.C_AREA)] -internal sealed class CopyShaderToProject( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - var draft = documents.Open(context.target); - AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceId.project); - string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; - AssetPath destination = AssetPath.Project(name + ".ishader"); - for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++) - destination = AssetPath.Project(name + " " + index + ".ishader"); - AssetFileEntry entry = browser.edits.CreateSource(destination, GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization)); - _ = context.interactions.For("panel/asset.file-browser", entry).Select(); - _ = context.interactions.For("panel/asset.file-browser", entry).Execute("file-browser/rename"); - context.interactions.OpenPanel("rendering.shader-editor"); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs index 8eb667f2f..d884ddb12 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs @@ -27,25 +27,42 @@ Func> describePorts ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(describePorts); GraphDocument graph = source.Clone(); - var placed = new HashSet(); + var placed = new HashSet(); float laneY = 70f; - GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) .OrderBy(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), serialization, context).stage) - .ThenBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); if (outputs.Length == 0) - outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphNodes.outputDefinitionId - || node.definitionId.EndsWith("-output", StringComparison.Ordinal)) - .OrderBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + { + outputs = graph.nodes + .Where(static node => ( + node.definitionID == ShaderGraphNodes.C_OUTPUT_DEFINITION_ID + || node.definitionID.EndsWith("-output", StringComparison.Ordinal) + )) + .OrderBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); + } foreach (GraphNodeRecord output in outputs) { - GraphNodeRecord[] members = output.definitionId == ShaderGraphDocument.outputDefinitionId - ? graph.nodes.Where(node => node.id == output.id - || ShaderGraphDocument.Read(node, "stage", "", serialization, context) == output.id.value).ToArray() - : graph.nodes.Where(node => !placed.Contains(node.id)).ToArray(); + GraphNodeRecord[] members = output.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + ? graph.nodes.Where(node => ( + node.id == output.id + || ShaderGraphDocument.Read( + node, + "stage", + string.Empty, + serialization, + context + ) == output.id.value + )).ToArray() + : graph.nodes.Where(node => !placed.Contains(node.id)).ToArray(); LayoutLane(output, members, ref laneY); } GraphNodeRecord[] remaining = graph.nodes.Where(node => !placed.Contains(node.id)) - .OrderBy(static node => node.position.y).ThenBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + .OrderBy(static node => node.position.y) + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); for (int i = 0; i < remaining.Length; i++) { remaining[i].position = new((i % 4) * C_COLUMN + 70f, laneY + i / 4 * C_ROW); @@ -58,22 +75,26 @@ void LayoutLane( GraphNodeRecord[] members, ref float y ) { - var memberIds = members.Select(static node => node.id).ToHashSet(); - var distance = new Dictionary { [output.id] = 0 }; - var queue = new Queue(); + HashSet memberIDs = members.Select(static node => node.id).ToHashSet(); + var distance = new Dictionary { [output.id] = 0 }; + var queue = new Queue(); queue.Enqueue(output.id); while (queue.Count != 0) { - GraphNodeId current = queue.Dequeue(); - foreach (GraphNodeId predecessor in graph.edges.Where(edge => edge.input.nodeId == current && memberIds.Contains(edge.output.nodeId)) - .Select(static edge => edge.output.nodeId).Distinct()) - { + GraphNodeID current = queue.Dequeue(); + foreach (GraphNodeID predecessor in graph.edges + .Where(edge => edge.input.nodeID == current && memberIDs.Contains(edge.output.nodeID)) + .Select(static edge => edge.output.nodeID) + .Distinct() + ) { int next = distance[current] + 1; // A draft may be invalid and contain a cycle. Layout must still terminate; // compilation owns cycle diagnostics, while the first reverse-BFS rank gives // every reachable node a stable visual column. if (distance.ContainsKey(predecessor)) + { continue; + } distance[predecessor] = next; queue.Enqueue(predecessor); } @@ -84,7 +105,8 @@ ref float y .GroupBy(node => distance[node.id]) .ToDictionary(static group => group.Key, static group => group .OrderBy(static node => node.position.y) - .ThenBy(static node => node.id.value, StringComparer.Ordinal).ToList()); + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToList()); // Alternating barycentric sweeps are the crossing-reduction phase of a layered graph // layout. Port order participates in the score, so values feeding ordered inputs do @@ -92,9 +114,13 @@ ref float y for (int sweep = 0; sweep < C_SWEEPS; sweep++) { for (int rank = 1; rank <= maximumDistance; rank++) + { Order(rank, towardOutput: true); + } for (int rank = maximumDistance - 1; rank >= 0; rank--) + { Order(rank, towardOutput: false); + } } int maximumRows = ranks.Values.Select(static rank => rank.Count).DefaultIfEmpty(1).Max(); @@ -114,8 +140,10 @@ void Order( bool towardOutput ) { if (!ranks.TryGetValue(rank, out List? nodes) || nodes.Count < 2) + { return; - var oldOrder = nodes.Select(static ( + } + Dictionary oldOrder = nodes.Select(static ( node, index ) => (node.id, index)).ToDictionary(); @@ -126,7 +154,9 @@ bool towardOutput { int comparison = Score(left, towardOutput).CompareTo(Score(right, towardOutput)); if (comparison != 0) + { return comparison; + } comparison = oldOrder[left.id].CompareTo(oldOrder[right.id]); return comparison != 0 ? comparison : StringComparer.Ordinal.Compare(left.id.value, right.id.value); }); @@ -136,21 +166,25 @@ double Score( GraphNodeRecord node, bool towardOutput ) { - IEnumerable<(GraphNodeId neighbor, GraphPortId port)> endpoints = towardOutput - ? graph.edges.Where(edge => edge.output.nodeId == node.id && distance.ContainsKey(edge.input.nodeId)) - .Select(static edge => (edge.input.nodeId, edge.input.portId)) - : graph.edges.Where(edge => edge.input.nodeId == node.id && distance.ContainsKey(edge.output.nodeId)) - .Select(static edge => (edge.output.nodeId, edge.output.portId)); + IEnumerable<(GraphNodeID neighbor, GraphPortID port)> endpoints = towardOutput + ? graph.edges.Where(edge => edge.output.nodeID == node.id && distance.ContainsKey(edge.input.nodeID)) + .Select(static edge => (edge.input.nodeID, edge.input.portID)) + : graph.edges.Where(edge => edge.input.nodeID == node.id && distance.ContainsKey(edge.output.nodeID)) + .Select(static edge => (edge.output.nodeID, edge.output.portID)); double total = 0; int count = 0; - foreach ((GraphNodeId neighborId, GraphPortId port) in endpoints) + foreach ((GraphNodeID neighborID, GraphPortID port) in endpoints) { - if (!distance.TryGetValue(neighborId, out int neighborRank) - || !ranks.TryGetValue(neighborRank, out List? neighbors)) + if (!distance.TryGetValue(neighborID, out int neighborRank) + || !ranks.TryGetValue(neighborRank, out List? neighbors) + ) { continue; - int index = neighbors.FindIndex(candidate => candidate.id == neighborId); + } + int index = neighbors.FindIndex(candidate => candidate.id == neighborID); if (index < 0) + { continue; + } IReadOnlyList ports; try { @@ -158,13 +192,14 @@ bool towardOutput } catch (Exception failure) when (failure is InvalidOperationException or ArgumentException or FormatException) { - ports = Array.Empty(); + ports = []; } GraphPortDirection direction = towardOutput ? GraphPortDirection.Input : GraphPortDirection.Output; ShaderNodePort[] matching = ports.Where(candidate => candidate.direction == direction).ToArray(); int portIndex = Array.FindIndex(matching, candidate => candidate.id == port.value); - double portOffset = portIndex < 0 || matching.Length < 2 ? 0d - : ((double)portIndex / (matching.Length - 1) - 0.5d) * 0.8d; + double portOffset = portIndex < 0 || matching.Length < 2 + ? 0d + : ((double)portIndex / (matching.Length - 1) - 0.5d) * 0.8d; total += index + portOffset; count++; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs new file mode 100644 index 000000000..4ebf80165 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs @@ -0,0 +1,38 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Gets documents presented by this Shader Editor action. + /// + protected ShaderEditorDocuments documents { get; } = documents; + + /// + /// Gets whether writes is active for the current instance. + /// + protected virtual bool writes => true; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected virtual bool needsSelection => true; + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && (!writes + || !draft.readOnly) + && (!needsSelection + || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs new file mode 100644 index 000000000..051b430d9 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs @@ -0,0 +1,33 @@ +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorMenuSource("panel/asset.file-browser")] +internal sealed class ShaderTemplateMenu(ShaderEditorDocuments documents) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + if (documents.templates is null) + { + return; + } + builder.AddGroup("Create/Rendering", order: 200, separatorBefore: true); + builder.AddGroup("Create/Rendering/Shaders", order: 0); + foreach (ShaderGraphTemplateInfo template in documents.templates.templates) + { + builder.Add("Create/Rendering/Shaders/" + template.displayName, "shader/create-asset", argument: template.id, order: 0); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs new file mode 100644 index 000000000..c44e64f7c --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs @@ -0,0 +1,26 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/check", ShaderEditorCanvas.C_AREA)] +internal sealed class ShowShaderDiagnostics(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => documents.ShowCheck(documents.Open(context.target)); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs new file mode 100644 index 000000000..2ce604930 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs @@ -0,0 +1,38 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/ungroup", ShaderEditorCanvas.C_AREA)] +internal sealed class UngroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocument graph = documents.Controller(draft).document.Clone(); + ShaderCanvasGroup[] groups = GroupShaderNodes + .Read(documents, graph) + .Where( + group => ( + draft.selectedGroupID.Length != 0 + ? group.id != draft.selectedGroupID + : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new GraphNodeID(id))) + ) + ) + .ToArray(); + graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); + documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); + draft.selectedGroupID = string.Empty; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs new file mode 100644 index 000000000..8a1efeb23 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs @@ -0,0 +1,35 @@ +using System; +using Inno.Editor.Interactions; +using Inno.Rendering.Assets; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("editor/open", priority: 1000)] +internal sealed class OpenShaderEditorAction : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + context.interactions.SetSelection(context.target); + if (!context.interactions.OpenPanel("rendering.shader-editor")) + { + throw new InvalidOperationException("Shader Editor is unavailable."); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs index 0d3a73495..1bdbe8a74 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs @@ -2,6 +2,7 @@ using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + namespace Inno.Editor.Panel.ShaderEditor; [EditorModal("shader.check", "Checking Shader", order: 220)] @@ -9,19 +10,23 @@ internal sealed class ShaderCheckModal(ShaderEditorDocuments documents) : Editor { private DialogPresentation m_content; private DialogLayout m_layout; - /// + + /// public override bool isVisible => documents.TryGetCheckDraft(out _); - /// + + /// public override bool allowScrolling => false; - /// + + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { m_content = new(documents.checkStatus); - m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); + m_layout = EditorUISession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } - /// - protected override void OnDraw(EditorContext context) => EditorUiSession.current.widgets.DrawDialog(m_content, m_layout); + + /// + protected override void OnDraw(EditorContext context) => EditorUISession.current.widgets.DrawDialog(m_content, m_layout); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs index f958f61a8..513a0c2fa 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs @@ -1,17 +1,18 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using System.IO; using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.Shaders; -using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Panel.ShaderEditor; + [EditorPanel("rendering.shader-editor", "Shader Editor", order: 230, menuPath: "Authoring")] internal sealed class ShaderEditorPanel(ShaderEditorDocuments documents) : EditorPanel { @@ -19,10 +20,12 @@ internal sealed class ShaderEditorPanel(ShaderEditorDocuments documents) : Edito /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => true; + /// /// Gets whether allow scrolling is enabled for this implementation. /// public override bool allowScrolling => false; + /// /// Gets the preferred initial window size in logical editor units. /// @@ -38,20 +41,21 @@ protected override void OnDraw(EditorContext context) { AssetFileEntry? entry = documents.interactions.selection.selectedTarget as AssetFileEntry; if (documents.interactions.selection.selectedTarget is ShaderAsset shader) + { _ = documents.assets.TryGetFileSystemEntry(shader.assetPath, out entry); + } if (documents.interactions.selection.selectedTarget is ShaderInspectionSelection selection - && documents.assets.TryGetInfo( - selection.assetId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(selection.assetID, out AssetInfo? info) + && info is not null + ) { _ = documents.assets.TryGetFileSystemEntry(info.assetPath, out entry); + } if (entry is null || entry.isDirectory || !entry.assetPath.localPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase)) { ShaderEditorCanvas.DrawHeader(documents, null); EditorUI.current.widgets.CenteredWrappedText( "Select a Shader (.ishader) in the File Browser.", - Vector2.Max(Vector2.One, Ui.GetContentRegionAvailable()), + Vector2.Max(Vector2.One, Gui.GetContentRegionAvailable()), new Vector2(40f, 28f) ); return; @@ -61,37 +65,10 @@ out AssetInfo? info { new ShaderEditorCanvas(documents, documents.Open(entry)).Draw(); } - catch (Exception failure) when ((failure is System.IO.IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is IOException or InvalidOperationException or FormatException) + && RetirementPendingException.Find(failure) is null) { EditorUI.current.widgets.WrappedText(failure.Message); } } } - -[EditorAction("editor/open", priority: 1000)] -internal sealed class OpenShaderEditorAction : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - context.interactions.SetSelection(context.target); - if (!context.interactions.OpenPanel("rendering.shader-editor")) - throw new InvalidOperationException("Shader Editor is unavailable."); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs index 81d04bdf5..6d9a3b98a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs @@ -27,24 +27,34 @@ internal bool Update( float frameDeltaTime ) { if (!float.IsFinite(totalTime) || !float.IsFinite(frameDeltaTime) || frameDeltaTime <= 0f) + { return false; + } if (float.IsFinite(m_lastFrameTime) && (totalTime < m_lastFrameTime || totalTime - m_lastFrameTime > C_SAMPLE_RESET_SECONDS - || totalTime - m_lastFrameTime > frameDeltaTime * 1.5f + 0.0001f)) + || totalTime - m_lastFrameTime > frameDeltaTime * 1.5f + 0.0001f) + ) { Reset(); + } m_lastFrameTime = totalTime; int expired = 0; while (expired < m_count && m_sampleTimes[expired] < totalTime - C_SAMPLE_WINDOW_SECONDS) + { expired++; + } RemoveOldest(expired); m_duration += frameDeltaTime; m_frames++; if (m_count > 0 && totalTime < m_nextSampleTime) + { return false; + } deltaTime = (float)(m_duration / m_frames); framesPerSecond = (float)(m_frames / m_duration); if (m_count == C_SAMPLE_CAPACITY) + { RemoveOldest(1); + } m_frameTimes[m_count] = deltaTime * 1000f; m_frameRates[m_count] = framesPerSecond; m_sampleTimes[m_count++] = totalTime; @@ -67,7 +77,9 @@ internal void Reset() private void RemoveOldest(int count) { if (count == 0) + { return; + } m_count -= count; Array.Copy(m_frameTimes, count, m_frameTimes, 0, m_count); Array.Copy(m_frameRates, count, m_frameRates, 0, m_count); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs index 3839f690c..6a3d3f561 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs @@ -1,13 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Stats; + /// /// Shows lightweight runtime metrics. /// @@ -20,17 +23,16 @@ internal sealed class StatsPanel : EditorPanel private IReadOnlyList? m_previousStatistics; private StatisticGroup[] m_groups = []; private (string label, string value)[] m_frameValues = []; + /// - /// Gets whether use window padding is active for the current instance. + /// Creates the panel. /// - public override bool useWindowPadding => false; + internal StatsPanel() {} /// - /// Creates the panel. + /// Gets whether use window padding is active for the current instance. /// - internal StatsPanel() - { - } + public override bool useWindowPadding => false; /// /// Draws this feature using the current editor presentation context. @@ -55,9 +57,12 @@ protected override void OnDraw(EditorContext context) IReadOnlyList statistics = context.statistics.GetSnapshot(); if (!ReferenceEquals(statistics, m_previousStatistics)) { - m_groups = statistics.GroupBy(static statistic => statistic.groupId) - .Select(static group => new StatisticGroup(group.First().groupName, - group.Select(static value => (value.label, value.value)).ToArray())).ToArray(); + m_groups = statistics.GroupBy(static statistic => statistic.groupID) + .Select(static group => new StatisticGroup( + group.First().groupName, + group.Select(static value => (value.label, value.value)).ToArray() + )) + .ToArray(); m_previousStatistics = statistics; } if (m_groups.Length == 0) @@ -66,10 +71,12 @@ protected override void OnDraw(EditorContext context) return; } foreach (StatisticGroup group in m_groups) + { DrawGroup(group.title, group.values); + } } - /// + /// protected override void OnDetach(EditorContext context) { m_statistics.Reset(); @@ -83,37 +90,45 @@ private static void DrawGroup( ReadOnlySpan<(string label, string value)> values ) { EditorUI.current.widgets.CollectionSectionHeader(title); - System.Numerics.Vector2 padding = EditorUI.current.widgets.style.sectionPadding; - ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.RowBg | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.PadOuterX; - Ui.PushStyleVar((ImGuiStyleVar.CellPadding), new System.Numerics.Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom)); - Ui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); - Ui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); + Vector2 padding = EditorUI.current.widgets.style.sectionPadding; + ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.RowBg + | ImGuiTableFlags.NoSavedSettings + | ImGuiTableFlags.PadOuterX; + Gui.PushStyleVar( + (ImGuiStyleVar.CellPadding), + new Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom) + ); + Gui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); + Gui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); try { - if (!Ui.BeginTable($"##stats_{title}", 2, flags, default(System.Numerics.Vector2), 0f)) + if (!Gui.BeginTable($"##stats_{title}", 2, flags, default, 0f)) + { return; + } try { - Ui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthStretch), 0.42f); - Ui.TableSetupColumn("##value", (ImGuiTableColumnFlags.WidthStretch), 0.58f); + Gui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthStretch), 0.42f); + Gui.TableSetupColumn("##value", (ImGuiTableColumnFlags.WidthStretch), 0.58f); foreach ((string label, string value) in values) { - Ui.TableNextRow(); - Ui.TableSetColumnIndex(0); - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); - Ui.TableSetColumnIndex(1); + Gui.TableNextRow(); + Gui.TableSetColumnIndex(0); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); + Gui.TableSetColumnIndex(1); EditorUI.current.widgets.WrappedText(value); } } finally { - Ui.EndTable(); + Gui.EndTable(); } } finally { - Ui.PopStyleColor(2); - Ui.PopStyleVar(); + Gui.PopStyleColor(2); + Gui.PopStyleVar(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs index ea598c569..84180c413 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs @@ -1,8 +1,9 @@ +using System; using Inno.Editor.Assets; using Inno.Editor.Core; -using System; namespace Inno.Editor.Assets.ImGui; + /// /// Declares the icon used by the Asset Browser for an imported asset type or source extension. /// @@ -10,65 +11,70 @@ namespace Inno.Editor.Assets.ImGui; /// Apply one or more declarations to a container type. The container has no runtime responsibility; /// it only keeps related icon declarations together so the type catalog can discover them. /// -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)] +[AttributeUsage( + AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate, + AllowMultiple = true, + Inherited = false +)] public sealed class AssetIconAttribute : Attribute { /// - /// Creates an icon declaration using a glyph from the Editor icon catalog. + /// Creates an icon declaration for files ending with a source extension. /// - /// - /// The imported asset type represented by the icon. + /// + /// The simple or compound file extension. A leading period is optional and matching is case-insensitive. /// /// /// The Editor icon glyph to render. /// - /// - /// Whether the declaration may also represent derived asset types. - /// /// - /// The tie-breaking priority after exactness and inheritance distance. + /// The tie-breaking priority after extension specificity. /// - /// - /// Thrown when is . - /// /// - /// Thrown when is empty. + /// Thrown when is empty or contains a path separator, or when + /// is empty. /// public AssetIconAttribute( - Type assetType, + string extension, string icon, - bool useForChildren = false, int priority = 0 ) { - this.assetType = assetType ?? throw new ArgumentNullException(nameof(assetType)); + this.extension = NormalizeExtension(extension); this.icon = ValidateIcon(icon); - this.useForChildren = useForChildren; this.priority = priority; } /// - /// Creates an icon declaration for files ending with a source extension. + /// Creates an icon declaration using a glyph from the Editor icon catalog. /// - /// - /// The simple or compound file extension. A leading period is optional and matching is case-insensitive. + /// + /// The imported asset type represented by the icon. /// /// /// The Editor icon glyph to render. /// + /// + /// Whether the declaration may also represent derived asset types. + /// /// - /// The tie-breaking priority after extension specificity. + /// The tie-breaking priority after exactness and inheritance distance. /// + /// + /// Thrown when is . + /// /// - /// Thrown when is empty or contains a path separator, or when - /// is empty. + /// Thrown when is empty. /// public AssetIconAttribute( - string extension, + Type assetType, string icon, + bool useForChildren = false, int priority = 0 ) { - this.extension = NormalizeExtension(extension); + ArgumentNullException.ThrowIfNull(assetType); + this.assetType = assetType; this.icon = ValidateIcon(icon); + this.useForChildren = useForChildren; this.priority = priority; } @@ -77,20 +83,24 @@ public AssetIconAttribute( /// an extension declaration. /// public Type? assetType { get; } + /// /// Gets the normalized source extension represented by this declaration, or /// for a type declaration. /// public string? extension { get; } + /// /// Gets the Editor icon glyph to render. /// public string icon { get; } + /// /// Gets whether a type declaration may also represent derived asset types. Extension declarations /// always return . /// public bool useForChildren { get; } + /// /// Gets the tie-breaking priority after target specificity. /// @@ -99,21 +109,31 @@ public AssetIconAttribute( private static string NormalizeExtension(string extension) { if (string.IsNullOrWhiteSpace(extension)) + { throw new ArgumentException("A source file extension is required.", nameof(extension)); + } string normalized = extension.Trim(); if (normalized.Contains('/') || normalized.Contains('\\')) + { throw new ArgumentException("A source file extension cannot contain path separators.", nameof(extension)); + } if (!normalized.StartsWith(".", StringComparison.Ordinal)) + { normalized = "." + normalized; + } if (normalized.Length == 1) + { throw new ArgumentException("A source file extension must contain a suffix.", nameof(extension)); + } return normalized.ToLowerInvariant(); } private static string ValidateIcon(string icon) { if (string.IsNullOrWhiteSpace(icon)) + { throw new ArgumentException("An Editor icon glyph is required.", nameof(icon)); + } return icon; } } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs index 8428eff48..e4844f1f4 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs @@ -1,45 +1,25 @@ -using Inno.Editor.Assets; -using Inno.Editor.Core; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; -using Inno.Extensibility.Types; +using Inno.Editor.Assets; +using Inno.Editor.Core; using Inno.Editor.Settings; +using Inno.Extensibility.Types; namespace Inno.Editor.Assets.ImGui; + internal sealed class AssetIconRegistry : TypeRegistry { private readonly EditorSettings m_settings; + internal AssetIconRegistry( EditorSettings settings, TypeCatalog types ) : base(types) { - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); - } - - internal bool TryResolve( - Type? assetType, - string relativePath, - out string icon - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); - if (TryResolveType(assetType, out icon) || TryResolveExtension(relativePath, out icon)) - { - try - { - icon = m_settings.Get(icon).GetAsString("value", icon) ?? icon; - } - catch (ArgumentException) - { - // Extension-defined attributes may still contain a literal glyph. - } - - return true; - } - - return false; + ArgumentNullException.ThrowIfNull(settings); + m_settings = settings; } /// @@ -53,28 +33,27 @@ out string icon /// protected override Snapshot Build(TypeCacheSnapshot types) { - var typeRegistrations = new List(); - var extensionRegistrations = new List(); + List typeRegistrations = []; + List extensionRegistrations = []; foreach (Type declarationType in types.types.Select(typeRef => typeRef.Resolve(types)).OrderBy( static type => type.Assembly.GetName().Name, StringComparer.Ordinal - ).ThenBy( - static type => type.FullName, - StringComparer.Ordinal - )) - { + ).ThenBy(static type => type.FullName, StringComparer.Ordinal) + ) { foreach (AssetIconAttribute attribute in declarationType.GetCustomAttributes( typeof(AssetIconAttribute), inherit: false ).Cast().OrderBy( static value => value.assetType?.FullName ?? value.extension, StringComparer.Ordinal - ).ThenBy(static value => value.priority)) - { + ).ThenBy(static value => value.priority) + ) { if (attribute.assetType is Type assetType) { ValidateType(attribute, declarationType, assetType, typeRegistrations); - typeRegistrations.Add(new TypeRegistration(assetType, attribute.useForChildren, attribute.priority, declarationType, attribute.icon)); + typeRegistrations.Add( + new TypeRegistration(assetType, attribute.useForChildren, attribute.priority, declarationType, attribute.icon) + ); } else if (attribute.extension is string extension) { @@ -87,6 +66,29 @@ protected override Snapshot Build(TypeCacheSnapshot types) return new Snapshot(typeRegistrations.ToArray(), extensionRegistrations.ToArray()); } + internal bool TryResolve( + Type? assetType, + string relativePath, + out string icon + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + if (TryResolveType(assetType, out icon) || TryResolveExtension(relativePath, out icon)) + { + try + { + icon = m_settings.Get(icon).GetAsString("value", icon) ?? icon; + } + catch (ArgumentException) + { + // Extension-defined attributes may still contain a literal glyph. + } + + return true; + } + + return false; + } + private bool TryResolveType( Type? assetType, out string icon @@ -97,8 +99,9 @@ out string icon { foreach (TypeRegistration registration in current.typeRegistrations) { - if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance) || distance > 0 && !registration.useForChildren) - { + if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance) + || distance > 0 && !registration.useForChildren + ) { continue; } @@ -122,12 +125,14 @@ out string icon foreach (ExtensionRegistration registration in current.extensionRegistrations) { if (!relativePath.EndsWith(registration.extension, StringComparison.OrdinalIgnoreCase)) + { continue; + } if (best is null || registration.extension.Length > best.extension.Length || registration.extension.Length == best.extension.Length - && registration.priority > best.priority) - { + && registration.priority > best.priority + ) { best = registration; } } @@ -144,12 +149,21 @@ IReadOnlyList registrations ) { if (!typeof(AssetObject).IsAssignableFrom(assetType)) { - throw new InvalidOperationException($"Asset icon declaration on '{declarationType.FullName}' targets " + $"'{assetType.FullName}', " + $"which does not derive from '{typeof(AssetObject).FullName}'."); + throw new InvalidOperationException( + $"Asset icon declaration on '{declarationType.FullName}' targets " + $"'{assetType.FullName}', " + $"which does not derive from '{typeof(AssetObject).FullName}'." + ); } - if (registrations.Any(value => value.assetType == assetType && value.useForChildren == attribute.useForChildren && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset icon registration for '{assetType.FullName}' conflicts at priority " + $"{attribute.priority}."); + if (registrations.Any( + value => ( + value.assetType == assetType + && value.useForChildren == attribute.useForChildren + && value.priority == attribute.priority + ) + )) { + throw new InvalidOperationException( + $"Asset icon registration for '{assetType.FullName}' conflicts at priority " + $"{attribute.priority}." + ); } } @@ -159,9 +173,12 @@ private static void ValidateExtension( string extension, IReadOnlyList registrations ) { - if (registrations.Any(value => string.Equals(value.extension, extension, StringComparison.OrdinalIgnoreCase) && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset icon declaration on '{declarationType.FullName}' for extension '{extension}' " + $"conflicts at priority {attribute.priority}."); + if (registrations.Any( + value => string.Equals(value.extension, extension, StringComparison.OrdinalIgnoreCase) && value.priority == attribute.priority + )) { + throw new InvalidOperationException( + $"Asset icon declaration on '{declarationType.FullName}' for extension '{extension}' " + $"conflicts at priority {attribute.priority}." + ); } } @@ -169,6 +186,7 @@ internal sealed record Snapshot( TypeRegistration[] typeRegistrations, ExtensionRegistration[] extensionRegistrations ); + internal sealed record TypeRegistration( Type assetType, bool useForChildren, @@ -176,6 +194,7 @@ internal sealed record TypeRegistration( Type declarationType, string icon ); + internal sealed record ExtensionRegistration( string extension, int priority, diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs index 5079b01f9..a0437c09c 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs @@ -1,24 +1,25 @@ -using Inno.Editor.ImGui; using Inno.Editor.Assets; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Settings; namespace Inno.Editor.Assets.ImGui; -[AssetIcon(".txt", ImGuiIcon.FileLines)] -[AssetIcon(".json", ImGuiIcon.FileLines)] -[AssetIcon(".yaml", ImGuiIcon.FileLines)] -[AssetIcon(".yml", ImGuiIcon.FileLines)] -[AssetIcon(".md", ImGuiIcon.FileLines)] -[AssetIcon(".xml", ImGuiIcon.FileLines)] -[AssetIcon(".bytes", ImGuiIcon.File)] -[AssetIcon(".bin", ImGuiIcon.File)] -[AssetIcon(".dat", ImGuiIcon.File)] + +[AssetIcon(".txt", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".json", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".yaml", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".yml", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".md", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".xml", ImGuiIcon.C_FILE_LINES)] +[AssetIcon(".bytes", ImGuiIcon.C_FILE)] +[AssetIcon(".bin", ImGuiIcon.C_FILE)] +[AssetIcon(".dat", ImGuiIcon.C_FILE)] [AssetIcon(".iscene", "Editor/Appearance/Icons/Scene")] [AssetIcon(".iprefab", "Editor/Appearance/Icons/Prefab")] [AssetIcon(".ishader", "Editor/Appearance/Icons/Shader")] [AssetIcon(".ishadersource", "Editor/Appearance/Icons/ShaderSource")] [AssetIcon(".imaterial", "Editor/Appearance/Icons/Material")] [AssetIcon(".irenderpipeline", "Editor/Appearance/Icons/RenderPipeline")] -[AssetIcon(".cs", ImGuiIcon.FileCode)] -[AssetIcon(".iasmdef", ImGuiIcon.Gears)] +[AssetIcon(".cs", ImGuiIcon.C_FILE_CODE)] +[AssetIcon(".iasmdef", ImGuiIcon.C_GEARS)] internal static class BuiltInAssetIcons; diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs index 27a7a6550..fae32b8f4 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs @@ -1,18 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; using System; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.Assets.ImGui; + [InspectionDrawer(typeof(AssetFileEntry))] internal sealed class AssetSelectionInspectionDrawer : InspectionDrawer { private readonly AssetBrowserModule m_assets; + /// /// Creates an Asset source drawer that shares the Asset Browser presentation registry. /// @@ -24,13 +27,14 @@ internal sealed class AssetSelectionInspectionDrawer : InspectionDrawer internal AssetSelectionInspectionDrawer(AssetBrowserModule assets) { - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); + ArgumentNullException.ThrowIfNull(assets); + m_assets = assets; } /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => ImGuiIcon.File; + public override string icon => ImGuiIcon.C_FILE; /// /// Retrieves the requested icon value from current authoritative state. @@ -48,6 +52,7 @@ protected override string GetIcon( InspectionDrawContext context, AssetFileEntry target ) => m_assets.GetIcon(target); + /// /// Binds a caller-visible label to the current inspection target. /// @@ -64,6 +69,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, AssetFileEntry target ) => (target.nameWithoutExtension, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -77,6 +83,7 @@ protected override void DrawHeader( InspectionDrawContext context, AssetFileEntry target ) => EditorUI.current.widgets.ColoredText(EditorPalette.contextText, target.assetPath.ToString()); + /// /// Renders the value presentation for the current editor frame. /// @@ -90,15 +97,17 @@ protected override void Draw( InspectionDrawContext context, AssetFileEntry entry ) { - if (!EditorUI.current.widgets.SectionHeader("Asset", "This view describes the selected source entry. Structured assets may replace it with a dedicated authoring drawer.")) - { + if (!EditorUI.current.widgets.SectionHeader( + "Asset", + "This view describes the selected source entry. Structured assets may replace it with a dedicated authoring drawer." + )) { return; } DrawMetadata( "Type", m_assets.edits.IsPluginRoot(entry) ? "IPlugin" : entry.isDirectory - && AssetSample.HasSampleDirectoryName(entry.assetPath) ? "ISample" : entry.isDirectory ? "Directory" : "File" + && AssetSample.HasSampleDirectoryName(entry.assetPath) ? "ISample" : entry.isDirectory ? "Directory" : "File" ); if (!entry.isDirectory) { @@ -109,7 +118,5 @@ AssetFileEntry entry private static void DrawMetadata( string label, string value - ) { - EditorUI.current.widgets.PropertyRow("asset.metadata." + label, label, () => EditorUI.current.widgets.Hint(value)); - } + ) => EditorUI.current.widgets.PropertyRow("asset.metadata." + label, label, () => EditorUI.current.widgets.Hint(value)); } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs index bfbe2a40e..4182d8181 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs @@ -1,15 +1,17 @@ -using Inno.Editor.ImGui; using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Assets; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Settings; using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Editor.Assets.ImGui; + /// /// Owns asset navigation and icon presentation independently from source mutations. /// @@ -18,6 +20,7 @@ public sealed class AssetBrowserModule : EditorModule, IInspectionIconProvider /// Creates the asset presentation module for the current editor generation. /// @@ -36,31 +39,64 @@ public sealed class AssetBrowserModule : EditorModule, IInspectionIconProvider /// A required owner is null. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetBrowserModule( AssetEditingModule edits, EditorInteractions interactions, EditorSettings settings, TypeCatalog types ) { - this.edits = edits ?? throw new ArgumentNullException(nameof(edits)); - m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(settings); + this.edits = edits; + m_settings = settings; m_icons = new AssetIconRegistry(settings, types); - browser = new AssetBrowserState(interactions, edits.pipeline); + this.browser = new AssetBrowserState(interactions, edits.pipeline); } /// /// Gets the source editing service; this module does not implement source transactions. /// public AssetEditingModule edits { get; } + /// /// Gets navigation state; object selection belongs to the shared interaction owner. /// public AssetBrowserState browser { get; } + /// /// Gets the configured folder glyph used by asset navigation. /// - public string folderIcon => m_settings.Get("Editor/Appearance/Icons/Folder").GetAsString("value", Inno.Editor.ImGui.ImGuiIcon.Folder)!; + public string folderIcon => m_settings.Get("Editor/Appearance/Icons/Folder").GetAsString("value", ImGuiIcon.C_FOLDER)!; + + /// + /// Resolves the presentation icon registered for an asset type or source extension. + /// + /// + /// The source entry whose presentation icon should be resolved. + /// + /// + /// The most specific registered icon, or the built-in directory or file icon when no + /// registration matches the entry. + /// + /// + /// Thrown when is . + /// + public string GetIcon(AssetFileEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + if (entry.isDirectory) + { + return folderIcon; + } + _ = edits.pipeline.TryGetAssetType(entry.assetPath, out Type? assetType); + if (m_icons.TryResolve(assetType, entry.assetPath.ToString(), out string icon)) + { + return icon; + } + + return m_settings.Get("Editor/Appearance/Icons/File").GetAsString("value", ImGuiIcon.C_FILE)!; + } /// /// Captures an immutable snapshot of the current observable state. @@ -83,63 +119,47 @@ protected override void Capture(EditorState state) /// protected override void Restore(EditorState state) { - AssetBrowserRoot restoredRoot = Enum.TryParse(state.Get("root", string.Empty), out AssetBrowserRoot parsedRoot) ? parsedRoot : AssetBrowserRoot.Assets; + AssetBrowserRoot restoredRoot = Enum.TryParse(state.Get("root", string.Empty), out AssetBrowserRoot parsedRoot) + ? parsedRoot + : AssetBrowserRoot.Assets; string assetsDirectory = RestoreDirectory(AssetBrowserRoot.Assets, state.Get("assetsDirectory", string.Empty)); string pluginsDirectory = RestoreDirectory(AssetBrowserRoot.Plugins, state.Get("pluginsDirectory", string.Empty)); browser.Restore(restoredRoot, assetsDirectory, pluginsDirectory); } + /// + protected override void OnDispose() => m_icons.Dispose(); + private string RestoreDirectory( AssetBrowserRoot root, string path ) { string directory = AssetPath.Parse(path).ToString(); if (string.IsNullOrEmpty(directory)) + { return string.Empty; + } AssetPath isolated = AssetPath.Parse(directory); - if ((root == AssetBrowserRoot.Assets) != (isolated.source == AssetSourceId.project)) + if ((root == AssetBrowserRoot.Assets) != (isolated.source == AssetSourceID.project)) + { return string.Empty; + } while (!IsAvailableDirectory(directory)) { string parent = ParentDirectory(directory); if (string.Equals(parent, directory, StringComparison.Ordinal)) + { return string.Empty; + } directory = parent; } return directory; } - private bool IsAvailableDirectory(string path) => edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry entry) && entry.isDirectory; - /// - /// Resolves the presentation icon registered for an asset type or source extension. - /// - /// - /// The source entry whose presentation icon should be resolved. - /// - /// - /// The most specific registered icon, or the built-in directory or file icon when no - /// registration matches the entry. - /// - /// - /// Thrown when is . - /// - public string GetIcon(AssetFileEntry entry) - { - ArgumentNullException.ThrowIfNull(entry); - if (entry.isDirectory) - return folderIcon; - _ = edits.pipeline.TryGetAssetType(entry.assetPath, out Type? assetType); - if (m_icons.TryResolve(assetType, entry.assetPath.ToString(), out string icon)) - { - return icon; - } - - return m_settings.Get("Editor/Appearance/Icons/File").GetAsString("value", Inno.Editor.ImGui.ImGuiIcon.File)!; - } + private bool IsAvailableDirectory(string path) + => edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry entry) && entry.isDirectory; - /// - protected override void OnDispose() => m_icons.Dispose(); private static string ParentDirectory(string value) { AssetPath path = AssetPath.Parse(value); diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs index edc2981d1..214c4dec3 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs @@ -1,27 +1,10 @@ -using Inno.Editor.Assets; using System; -using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Inno.Editor.Inspection; namespace Inno.Editor.Assets.ImGui; -/// -/// Identifies the authoring or installed-content root displayed by the Asset Browser. -/// -public enum AssetBrowserRoot -{ - /// - /// The writable project Assets authoring root. - /// - Assets, - /// - /// The read-only Plugins installation root. - /// - Plugins -} /// /// Stores asset browser navigation independently from global object selection. @@ -32,6 +15,7 @@ public sealed class AssetBrowserState private readonly AssetPipeline m_assets; private string m_assetsDirectory = string.Empty; private string m_pluginsDirectory = string.Empty; + /// /// Creates Asset Browser navigation state. /// @@ -48,18 +32,22 @@ internal AssetBrowserState( EditorInteractions interactions, AssetPipeline assets ) { - m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(assets); + m_interactions = interactions; + m_assets = assets; } /// /// Gets the root currently displayed by the Asset Browser. /// public AssetBrowserRoot root { get; private set; } + /// /// Gets the current directory inside . An empty value identifies that root's overview. /// public string currentDirectory => root == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; + /// /// Gets the most recently visited writable project directory, independently of the displayed root. /// @@ -80,7 +68,7 @@ AssetPipeline assets public string? GetSelectedPath(EditorContext context) { ArgumentNullException.ThrowIfNull(context); - return (m_interactions.selection.selectedTarget as Inno.Assets.Pipeline.AssetFileEntry)?.assetPath.ToString(); + return (m_interactions.selection.selectedTarget as AssetFileEntry)?.assetPath.ToString(); } /// @@ -99,6 +87,7 @@ public bool IsSelected( EditorContext context, AssetFileEntry entry ) => m_interactions.selection.Contains(entry); + /// /// Adds or removes an asset from the current selection without retaining runtime asset objects. /// @@ -111,9 +100,7 @@ AssetFileEntry entry public void ToggleSelection( EditorContext context, AssetFileEntry entry - ) { - m_interactions.ToggleSelection(entry); - } + ) => m_interactions.ToggleSelection(entry); /// /// Switches the displayed root while preserving the last directory visited in each root. @@ -122,6 +109,7 @@ AssetFileEntry entry /// The authoring or installed-content root to display. /// public void SetRoot(AssetBrowserRoot value) => root = value; + /// /// Sets the current Asset Browser directory and infers its root from the isolated source identity. /// @@ -138,7 +126,7 @@ public void SetCurrentDirectory(string relativePath) } AssetPath path = AssetPath.Parse(normalized); - AssetBrowserRoot targetRoot = path.source == AssetSourceId.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; + AssetBrowserRoot targetRoot = path.source == AssetSourceID.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; SetDirectory(targetRoot, normalized); root = targetRoot; } @@ -163,7 +151,7 @@ public void Select( object? target = null; if (!string.IsNullOrWhiteSpace(relativePath)) { - if (m_assets.TryGetFileSystemEntry(Inno.Assets.AssetPath.Parse(Normalize(relativePath)), out Inno.Assets.Pipeline.AssetFileEntry entry)) + if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(Normalize(relativePath)), out AssetFileEntry entry)) { target = entry; } @@ -181,16 +169,8 @@ public void Select( /// /// The source-relative directory, or an empty string for the root. /// - public string GetDirectory(AssetBrowserRoot targetRoot) => targetRoot == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; - internal void Restore( - AssetBrowserRoot restoredRoot, - string assetsDirectory, - string pluginsDirectory - ) { - m_assetsDirectory = Normalize(assetsDirectory); - m_pluginsDirectory = Normalize(pluginsDirectory); - root = restoredRoot; - } + public string GetDirectory(AssetBrowserRoot targetRoot) + => targetRoot == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; /// /// Changes the displayed source root and its isolated navigation directory. @@ -212,7 +192,7 @@ string directory if (!string.IsNullOrEmpty(normalized)) { AssetPath path = AssetPath.Parse(normalized); - bool isProject = path.source == AssetSourceId.project; + bool isProject = path.source == AssetSourceID.project; if ((targetRoot == AssetBrowserRoot.Assets) != isProject) { throw new ArgumentException($"Directory '{directory}' does not belong to the '{targetRoot}' root.", nameof(directory)); @@ -223,20 +203,51 @@ string directory root = targetRoot; } + internal void Restore( + AssetBrowserRoot restoredRoot, + string assetsDirectory, + string pluginsDirectory + ) { + m_assetsDirectory = Normalize(assetsDirectory); + m_pluginsDirectory = Normalize(pluginsDirectory); + root = restoredRoot; + } + private void SetDirectory( AssetBrowserRoot targetRoot, string directory ) { if (targetRoot == AssetBrowserRoot.Assets) + { m_assetsDirectory = directory; + } else + { m_pluginsDirectory = directory; + } } private static string Normalize(string? relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return string.Empty; + } return AssetPath.Parse(relativePath.Replace('\\', '/').Trim()).ToString(); } } + +/// +/// Identifies the authoring or installed-content root displayed by the Asset Browser. +/// +public enum AssetBrowserRoot +{ + /// + /// The writable project Assets authoring root. + /// + Assets, + /// + /// The read-only Plugins installation root. + /// + Plugins +} diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Styling/AssetBrowserStyle.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Styling/AssetBrowserStyle.cs index 5b2d2b7f2..2c9c19eb0 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Styling/AssetBrowserStyle.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Styling/AssetBrowserStyle.cs @@ -30,17 +30,17 @@ public AssetBrowserStyle(EditorStyleMetrics metrics) /// /// Gets asset browser window padding. /// - public Vector2 windowPadding => ScaleVector(new(2f, 1f)); + public Vector2 windowPadding => ScaleVector(new Vector2(2f, 1f)); /// /// Gets asset browser cell padding. /// - public Vector2 cellPadding => ScaleVector(new(5f, 2f)); + public Vector2 cellPadding => ScaleVector(new Vector2(5f, 2f)); /// /// Gets asset browser item spacing. /// - public Vector2 itemSpacing => ScaleVector(new(2f, 2f)); + public Vector2 itemSpacing => ScaleVector(new Vector2(2f, 2f)); /// /// Gets asset browser frame rounding. diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs index 64eb02377..feba066f3 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs @@ -11,8 +11,8 @@ namespace Inno.Editor.Graph.ImGui; /// public sealed class GraphCanvasLayout { - private IReadOnlyList m_nodes = Array.Empty(); - private Dictionary m_byId = []; + private IReadOnlyList m_nodes = []; + private Dictionary m_byID = []; /// /// Gets nodes in draw order; reverse order determines overlapping-node hit priority. @@ -38,24 +38,32 @@ public int SetNodes(IEnumerable nodes) { ArgumentNullException.ThrowIfNull(nodes); GraphCanvasNode[] candidate = nodes.ToArray(); - var byId = new Dictionary(candidate.Length); + var byID = new Dictionary(candidate.Length); int changes = 0; for (int index = 0; index < candidate.Length; index++) { GraphCanvasNode node = candidate[index]; ArgumentNullException.ThrowIfNull(node); - if (m_byId.TryGetValue(node.id, out GraphCanvasNode? current) && Equivalent(current, node)) + if (m_byID.TryGetValue(node.id, out GraphCanvasNode? current) && Equivalent(current, node)) + { candidate[index] = node = current; + } else + { changes++; - if (!byId.TryAdd(node.id, node)) + } + if (!byID.TryAdd(node.id, node)) + { throw new ArgumentException("A graph layout cannot contain duplicate node identities.", nameof(nodes)); + } } - changes += m_byId.Keys.Count(id => !byId.ContainsKey(id)); + changes += m_byID.Keys.Count(id => !byID.ContainsKey(id)); if (changes == 0 && m_nodes.SequenceEqual(candidate)) + { return 0; + } m_nodes = Array.AsReadOnly(candidate); - m_byId = byId; + m_byID = byID; return changes; } @@ -72,9 +80,9 @@ public int SetNodes(IEnumerable nodes) /// True when the current snapshot contains the node. /// public bool TryGetNode( - GraphNodeId id, + GraphNodeID id, [NotNullWhen(true)] out GraphCanvasNode? node - ) => m_byId.TryGetValue(id, out node); + ) => m_byID.TryGetValue(id, out node); private static bool Equivalent( GraphCanvasNode left, diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs index 61df6f786..b8934e995 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs @@ -42,7 +42,7 @@ public sealed class GraphCanvasNode /// The node's geometry is nonfinite or has an invalid extent. /// public GraphCanvasNode( - GraphNodeId id, + GraphNodeID id, GraphPosition position, Vector2 size, float headerHeight, @@ -53,15 +53,23 @@ IEnumerable ports ArgumentNullException.ThrowIfNull(title); ArgumentNullException.ThrowIfNull(ports); if (!float.IsFinite(position.x) || !float.IsFinite(position.y)) + { throw new ArgumentOutOfRangeException(nameof(position)); + } if (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X <= 0f || size.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(size)); + } if (!float.IsFinite(headerHeight) || headerHeight < 0f || headerHeight > size.Y) + { throw new ArgumentOutOfRangeException(nameof(headerHeight)); + } GraphCanvasPort[] frozen = ports.ToArray(); - if (frozen.Any(port => port.endpoint.nodeId != id) - || frozen.Select(static port => (port.endpoint, port.direction)).Distinct().Count() != frozen.Length) + if (frozen.Any(port => port.endpoint.nodeID != id) + || frozen.Select(static port => (port.endpoint, port.direction)).Distinct().Count() != frozen.Length + ) { throw new ArgumentException("Node ports require unique endpoint/direction pairs owned by the same node.", nameof(ports)); + } this.id = id; this.position = position; this.size = size; @@ -73,7 +81,7 @@ IEnumerable ports /// /// Gets the stable graph identity represented by this display snapshot. /// - public GraphNodeId id { get; } + public GraphNodeID id { get; } /// /// Gets the document position, before transient gesture previews. diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs index 9dc09c562..e1a15dd51 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs @@ -14,13 +14,13 @@ namespace Inno.Editor.Graph.ImGui; public sealed class GraphCanvasPointerController { private readonly GraphCanvasState m_state; - private readonly Dictionary m_starts = []; - private readonly Dictionary m_preview = []; - private readonly IReadOnlyDictionary m_previewView; + private readonly Dictionary m_starts = []; + private readonly Dictionary m_preview = []; + private readonly IReadOnlyDictionary m_previewView; private Vector2 m_pointerStart; private bool m_dragging; private bool m_boxSelecting; - private GraphNodeId[] m_boxSelection = []; + private GraphNodeID[] m_boxSelection = []; /// /// Creates a pointer owner over existing document navigation and selection state. @@ -35,13 +35,13 @@ public GraphCanvasPointerController(GraphCanvasState state) { ArgumentNullException.ThrowIfNull(state); m_state = state; - m_previewView = new ReadOnlyDictionary(m_preview); + m_previewView = new ReadOnlyDictionary(m_preview); } /// /// Gets frame-local movement previews; callers must not persist this changing view. /// - public IReadOnlyDictionary previewPositions => m_previewView; + public IReadOnlyDictionary previewPositions => m_previewView; /// /// Gets whether a node movement preview is active. @@ -84,18 +84,24 @@ public void Cancel() /// public void BeginMove( GraphCanvasLayout layout, - IEnumerable nodes, + IEnumerable nodes, Vector2 pointer ) { ArgumentNullException.ThrowIfNull(layout); ArgumentNullException.ThrowIfNull(nodes); - var starts = new Dictionary(); - foreach (GraphNodeId id in nodes) + var starts = new Dictionary(); + foreach (GraphNodeID id in nodes) + { if (layout.TryGetNode(id, out GraphCanvasNode? node)) + { starts.TryAdd(id, node.position); + } + } Cancel(); - foreach (var entry in starts) + foreach (KeyValuePair entry in starts) + { m_starts.Add(entry.Key, entry.Value); + } m_dragging = m_starts.Count != 0; m_pointerStart = pointer; } @@ -125,20 +131,26 @@ GraphCanvasPointerInput input ) { ArgumentNullException.ThrowIfNull(layout); if (!float.IsFinite(input.position.X) || !float.IsFinite(input.position.Y)) + { throw new ArgumentOutOfRangeException(nameof(input)); + } if (input.cancel) { Cancel(); return default; } if (input.readOnly && (m_dragging || m_state.pendingConnection is not null)) + { Cancel(); - GraphNodeId? pressed = null; + } + GraphNodeID? pressed = null; if (input.isPressed && input.isHovered) { GraphCanvasPort? port = view.HitPort(layout, input.position); if (!input.readOnly && port is { isMissing: false } endpoint) + { m_state.BeginConnection(endpoint.endpoint, endpoint.direction); + } else { GraphCanvasNode? node = view.HitNode(layout, input.position); @@ -146,16 +158,24 @@ GraphCanvasPointerInput input { pressed = node.id; if (input.shift) + { m_state.ToggleNode(node.id); + } else if (!m_state.selectedNodes.Contains(node.id)) + { m_state.SelectNodes([node.id]); + } if (!input.readOnly) + { BeginMove(layout, m_state.selectedNodes, input.position); + } } else if (node is null) { if (!input.shift) + { m_state.ClearSelection(); + } m_boxSelecting = true; m_boxSelection = input.shift ? m_state.selectedNodes.ToArray() : []; m_pointerStart = input.position; @@ -166,23 +186,31 @@ GraphCanvasPointerInput input { GraphPosition start = view.ToGraph(m_pointerStart); GraphPosition current = view.ToGraph(input.position); - foreach ((GraphNodeId id, GraphPosition position) in m_starts) + foreach ((GraphNodeID id, GraphPosition position) in m_starts) + { m_preview[id] = new(position.x + current.x - start.x, position.y + current.y - start.y); + } } if (!input.isReleased) + { return new(pressed, null, null, null, null); + } - IReadOnlyDictionary? moved = null; + IReadOnlyDictionary? moved = null; if (m_dragging && m_preview.Any(entry => m_starts[entry.Key] != entry.Value)) - moved = new ReadOnlyDictionary(new Dictionary(m_preview)); + { + moved = new ReadOnlyDictionary(new Dictionary(m_preview)); + } if (m_boxSelecting) + { m_state.SelectNodes(m_boxSelection.Concat(view.BoxNodes(layout, m_pointerStart, input.position)).Distinct()); + } GraphEndpoint? output = null; GraphEndpoint? targetInput = null; GraphEndpoint? released = null; if (!input.readOnly && input.isHovered && m_state.pendingConnection is GraphEndpoint source - && m_state.pendingConnectionDirection is GraphPortDirection direction) - { + && m_state.pendingConnectionDirection is GraphPortDirection direction + ) { GraphCanvasPort? destination = view.HitPort(layout, input.position); if (destination is { isMissing: false } target && target.direction != direction) { @@ -190,8 +218,10 @@ GraphCanvasPointerInput input targetInput = direction == GraphPortDirection.Input ? source : target.endpoint; } else if (destination is null && direction == GraphPortDirection.Output - && input.isHovered && view.HitNode(layout, input.position) is null) + && input.isHovered && view.HitNode(layout, input.position) is null + ) { released = source; + } } Cancel(); return new(pressed, moved, output, targetInput, released); diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerResult.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerResult.cs index 3ffdca15c..0a0e12f76 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerResult.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerResult.cs @@ -9,8 +9,8 @@ namespace Inno.Editor.Graph.ImGui; public readonly struct GraphCanvasPointerResult { internal GraphCanvasPointerResult( - GraphNodeId? nodePressed, - IReadOnlyDictionary? movedNodes, + GraphNodeID? nodePressed, + IReadOnlyDictionary? movedNodes, GraphEndpoint? output, GraphEndpoint? input, GraphEndpoint? releasedOutput @@ -25,12 +25,12 @@ internal GraphCanvasPointerResult( /// /// Gets the pressed node header, or null when no header was pressed. /// - public GraphNodeId? nodePressed { get; } + public GraphNodeID? nodePressed { get; } /// /// Gets completed movement positions, or null when no data edit was requested. /// - public IReadOnlyDictionary? movedNodes { get; } + public IReadOnlyDictionary? movedNodes { get; } /// /// Gets a requested connection's output endpoint; its domain type still requires validation. diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs index 59fe75f61..81e1d9ba3 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs @@ -51,17 +51,23 @@ public GraphCanvasPort( bool isMissing = false, (Vector2 minimum, Vector2 maximum)? labelBounds = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(endpoint.nodeId.value); - ArgumentException.ThrowIfNullOrWhiteSpace(endpoint.portId.value); + ArgumentException.ThrowIfNullOrWhiteSpace(endpoint.nodeID.value); + ArgumentException.ThrowIfNullOrWhiteSpace(endpoint.portID.value); ArgumentNullException.ThrowIfNull(label); if (!float.IsFinite(position.X) || !float.IsFinite(position.Y)) + { throw new ArgumentOutOfRangeException(nameof(position)); + } if (direction is not GraphPortDirection.Input and not GraphPortDirection.Output) + { throw new ArgumentOutOfRangeException(nameof(direction)); + } if (labelBounds is { } bounds && (!float.IsFinite(bounds.minimum.X) || !float.IsFinite(bounds.minimum.Y) - || !float.IsFinite(bounds.maximum.X) || !float.IsFinite(bounds.maximum.Y) - || bounds.maximum.X < bounds.minimum.X || bounds.maximum.Y < bounds.minimum.Y)) + || !float.IsFinite(bounds.maximum.X) || !float.IsFinite(bounds.maximum.Y) + || bounds.maximum.X < bounds.minimum.X || bounds.maximum.Y < bounds.minimum.Y) + ) { throw new ArgumentOutOfRangeException(nameof(labelBounds)); + } this.endpoint = endpoint; this.direction = direction; this.position = position; diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs index 60371d316..97020bb8f 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs @@ -3,6 +3,7 @@ using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.ImGui; + using CanvasDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Graph.ImGui; @@ -53,9 +54,11 @@ Vector2 point for (int index = layout.nodes.Count - 1; index >= 0; index--) { GraphCanvasNode node = layout.nodes[index]; - var bounds = NodeBounds(node); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node); if (Contains(bounds, point)) + { return node; + } } return null; } @@ -85,21 +88,34 @@ Vector2 point ) { ArgumentNullException.ThrowIfNull(layout); if (!float.IsFinite(radius) || radius < 0f) + { throw new ArgumentOutOfRangeException(nameof(radius)); + } float hitRadius = MathF.Max(radius, 7f * zoom); for (int index = layout.nodes.Count - 1; index >= 0; index--) { GraphCanvasNode node = layout.nodes[index]; Vector2 minimum = ToScreen(node.position); foreach (GraphCanvasPort port in node.ports) + { if (Vector2.DistanceSquared(point, minimum + port.position * m_zoom) <= hitRadius * hitRadius) + { return port; + } + } if (!Contains(NodeBounds(node), point)) + { continue; + } foreach (GraphCanvasPort port in node.ports) + { if (port.labelBounds is { } label && Contains( - (ToScreen(node.position) + label.minimum * m_zoom, ToScreen(node.position) + label.maximum * m_zoom), point)) + (ToScreen(node.position) + label.minimum * m_zoom, ToScreen(node.position) + label.maximum * m_zoom), + point + )) { return port; + } + } // Covered nodes must not receive interaction through the frontmost node's body. return null; } @@ -121,7 +137,7 @@ Vector2 point /// /// Stable graph node IDs; no live domain objects are returned. /// - public IReadOnlyList BoxNodes( + public IReadOnlyList BoxNodes( GraphCanvasLayout layout, Vector2 first, Vector2 second @@ -129,13 +145,15 @@ Vector2 second ArgumentNullException.ThrowIfNull(layout); Vector2 minimum = Vector2.Min(first, second); Vector2 maximum = Vector2.Max(first, second); - var nodes = new List(); + List nodes = []; foreach (GraphCanvasNode node in layout.nodes) { - var bounds = NodeBounds(node); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node); if (bounds.maximum.X >= minimum.X && bounds.minimum.X <= maximum.X - && bounds.maximum.Y >= minimum.Y && bounds.minimum.Y <= maximum.Y) + && bounds.maximum.Y >= minimum.Y && bounds.minimum.Y <= maximum.Y + ) { nodes.Add(node.id); + } } return nodes.AsReadOnly(); } @@ -178,45 +196,73 @@ public bool DrawNode( Action? drawContent = null, GraphPosition? previewPosition = null ) { - var bounds = NodeBounds(node, previewPosition); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node, previewPosition); Vector2 minimum = bounds.minimum; Vector2 maximum = bounds.maximum; if (m_size.X == 0f || m_size.Y == 0f || maximum.X < m_origin.X || minimum.X > m_origin.X + m_size.X - || maximum.Y < m_origin.Y || minimum.Y > m_origin.Y + m_size.Y) + || maximum.Y < m_origin.Y || minimum.Y > m_origin.Y + m_size.Y + ) { return false; - var clip = CanvasDrawing.GetClipBounds(); + } + (Vector2 minimum, Vector2 maximum) clip = CanvasDrawing.GetClipBounds(); if (maximum.X < clip.minimum.X || minimum.X > clip.maximum.X || maximum.Y < clip.minimum.Y || minimum.Y > clip.maximum.Y) + { return false; + } float zoom = this.zoom; - draw.PushClip(Vector2.Max(m_origin, minimum - new Vector2(6f * zoom)), - Vector2.Min(m_origin + m_size, maximum + new Vector2(6f * zoom)), true); + draw.PushClip( + Vector2.Max(m_origin, minimum - new Vector2(6f * zoom)), + Vector2.Min(m_origin + m_size, maximum + new Vector2(6f * zoom)), + true + ); try { - draw.FilledRectangle(minimum + new Vector2(3, 5), maximum + new Vector2(3, 5), Pack(0f, 0f, 0f, EditorPalette.opacityMuted), 6f * zoom, false); + draw.FilledRectangle( + minimum + new Vector2(3, 5), + maximum + new Vector2(3, 5), + Pack(0f, 0f, 0f, EditorPalette.C_OPACITY_MUTED), + 6f * zoom, + false + ); draw.FilledRectangle(minimum, maximum, Pack(0.115f, 0.12f, 0.14f), 6f * zoom, false); - draw.FilledRectangle(minimum, new(maximum.X, minimum.Y + node.headerHeight * zoom), headerColor, 6f * zoom, true); - draw.Rectangle(minimum, maximum, selected ? Pack(0.65f, 0.47f, 0.88f) : Pack(0.26f, 0.27f, 0.31f), 6f * zoom, selected ? 2f : 1f); + draw.FilledRectangle(minimum, new Vector2(maximum.X, minimum.Y + node.headerHeight * zoom), headerColor, 6f * zoom, true); + draw.Rectangle( + minimum, + maximum, + selected ? Pack(0.65f, 0.47f, 0.88f) : Pack(0.26f, 0.27f, 0.31f), + 6f * zoom, + selected ? 2f : 1f + ); draw.Text(minimum + new Vector2(10f, 7f) * zoom, CanvasDrawing.GetStyleColor(ImGuiCol.Text), node.title, zoom); foreach (GraphCanvasPort port in node.ports) { Vector2 point = minimum + port.position * zoom; - uint color = port.isMissing ? Pack(0.95f, 0.35f, 0.3f) : Pack(0.60f, 0.48f, 0.84f); + uint color = port.isMissing ? Pack(0.95f, 0.35f, 0.3f) : Pack(0.6f, 0.48f, 0.84f); draw.FilledCircle(point, 5f * zoom, color); if (port.isOptional && !port.isMissing) + { draw.FilledCircle(point, 2.75f * zoom, Pack(0.115f, 0.12f, 0.14f)); + } if (port.labelBounds is not { } labelBounds) + { continue; + } Vector2 labelMinimum = minimum + labelBounds.minimum * zoom; Vector2 labelMaximum = minimum + labelBounds.maximum * zoom; float padding = 12f * zoom; - var label = FitLabel(port.label, labelMaximum.X - labelMinimum.X - padding * 2f, zoom); - float textX = port.direction == GraphPortDirection.Input ? labelMinimum.X + padding - : labelMaximum.X - padding - label.width; + (string text, float width) label = FitLabel(port.label, labelMaximum.X - labelMinimum.X - padding * 2f, zoom); + float textX = port.direction == GraphPortDirection.Input + ? labelMinimum.X + padding + : labelMaximum.X - padding - label.width; draw.PushClip(labelMinimum, labelMaximum, true); try { - draw.Text(new Vector2(textX, point.Y - 8f * zoom), - CanvasDrawing.ToPackedColor(port.isOptional ? EditorPalette.textDisabled : EditorPalette.text), label.text, zoom); + draw.Text( + new Vector2(textX, point.Y - 8f * zoom), + CanvasDrawing.ToPackedColor(port.isOptional ? EditorPalette.textDisabled : EditorPalette.text), + label.text, + zoom + ); } finally { @@ -239,24 +285,34 @@ float zoom ) { float measuredWidth = CanvasDrawing.MeasureText(label).X * zoom; if (measuredWidth <= width) + { return (label, measuredWidth); - const string ellipsis = "…"; - if (CanvasDrawing.MeasureText(ellipsis).X * zoom > width) + } + const string C_ELLIPSIS = "…"; + if (CanvasDrawing.MeasureText(C_ELLIPSIS).X * zoom > width) + { return (string.Empty, 0f); + } int low = 0; int high = label.Length; while (low < high) { int length = (low + high + 1) / 2; - if (CanvasDrawing.MeasureText(label[..length] + ellipsis).X * zoom <= width) + if (CanvasDrawing.MeasureText(label[..length] + C_ELLIPSIS).X * zoom <= width) + { low = length; + } else + { high = length - 1; + } } // Avoid splitting a UTF-16 surrogate pair when a label contains supplementary characters. if (low > 0 && low < label.Length && char.IsHighSurrogate(label[low - 1])) + { low--; - string text = label[..low] + ellipsis; + } + string text = label[..low] + C_ELLIPSIS; return (text, CanvasDrawing.MeasureText(text).X * zoom); } @@ -264,7 +320,7 @@ private static bool Contains( (Vector2 minimum, Vector2 maximum) bounds, Vector2 point ) => point.X >= bounds.minimum.X && point.X <= bounds.maximum.X - && point.Y >= bounds.minimum.Y && point.Y <= bounds.maximum.Y; + && point.Y >= bounds.minimum.Y && point.Y <= bounds.maximum.Y; private static uint Pack( float red, diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs index 13c531469..108719bee 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs @@ -3,9 +3,11 @@ using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.ImGui; + using CanvasDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Graph.ImGui; + /// /// Projects and presents an arbitrary graph viewport without owning document mutations or domain semantics. /// @@ -16,6 +18,7 @@ public readonly partial struct GraphCanvasView private readonly float m_zoom; private readonly Vector2 m_origin; private readonly Vector2 m_size; + /// /// Creates a frame-local graph presenter over navigation owned by its document. /// @@ -41,9 +44,13 @@ Vector2 size ) { ArgumentNullException.ThrowIfNull(state); if (!float.IsFinite(origin.X) || !float.IsFinite(origin.Y)) + { throw new ArgumentOutOfRangeException(nameof(origin)); + } if (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f) + { throw new ArgumentOutOfRangeException(nameof(size)); + } m_pan = state.pan; m_zoom = state.zoom; m_origin = origin; @@ -56,7 +63,8 @@ Vector2 size /// /// The view was not initialized through its constructor. /// - public float zoom => m_zoom > 0f ? m_zoom : throw new InvalidOperationException("A graph canvas view requires an initialized projection."); + public float zoom + => m_zoom > 0f ? m_zoom : throw new InvalidOperationException("A graph canvas view requires an initialized projection."); /// /// Projects a graph-space location into the current screen rectangle. @@ -68,6 +76,7 @@ Vector2 size /// The corresponding screen coordinate. /// public Vector2 ToScreen(GraphPosition point) => m_origin + new Vector2(m_pan.x, m_pan.y) + new Vector2(point.x, point.y) * zoom; + /// /// Converts a screen location back into graph coordinates. /// @@ -78,6 +87,7 @@ Vector2 size /// The graph coordinate under the pointer. /// public GraphPosition ToGraph(Vector2 point) => new((point.X - m_origin.X - m_pan.x) / zoom, (point.Y - m_origin.Y - m_pan.y) / zoom); + /// /// Draws a bounded graph-space grid through the current UI drawing context. /// @@ -95,12 +105,18 @@ public void DrawGrid( float spacing = 32f ) { if (!float.IsFinite(spacing) || spacing <= 0f) + { throw new ArgumentOutOfRangeException(nameof(spacing)); + } float step = MathF.Max(MathF.Max(4f, spacing * zoom), MathF.Max(m_size.X, m_size.Y) / C_MAX_GRID_LINES_PER_AXIS); for (float x = ((m_pan.x % step) + step) % step; x < m_size.X; x += step) + { CanvasDrawing.DrawLine(m_origin + new Vector2(x, 0f), m_origin + new Vector2(x, m_size.Y), color); + } for (float y = ((m_pan.y % step) + step) % step; y < m_size.Y; y += step) + { CanvasDrawing.DrawLine(m_origin + new Vector2(0f, y), m_origin + new Vector2(m_size.X, y), color); + } } /// @@ -136,22 +152,32 @@ public void DrawConnection( ) { _ = zoom; if (!float.IsFinite(thickness) || thickness <= 0f) + { throw new ArgumentOutOfRangeException(nameof(thickness)); + } if (!float.IsFinite(output.X) || !float.IsFinite(output.Y) || !float.IsFinite(input.X) || !float.IsFinite(input.Y)) + { throw new ArgumentOutOfRangeException(nameof(output), "Connection endpoints must be finite screen coordinates."); + } if (m_size.X == 0f || m_size.Y == 0f) + { return; + } float tangent = Tangent(output, input); Vector2 first = output + new Vector2(tangent, 0f); Vector2 second = input - new Vector2(tangent, 0f); if (!float.IsFinite(first.X) || !float.IsFinite(second.X)) + { throw new ArgumentOutOfRangeException(nameof(input), "Connection controls exceed finite screen coordinates."); - var clip = CanvasDrawing.GetClipBounds(); + } + (Vector2 minimum, Vector2 maximum) clip = CanvasDrawing.GetClipBounds(); Vector2 minimum = Vector2.Min(Vector2.Min(output, input), Vector2.Min(first, second)) - new Vector2(thickness); Vector2 maximum = Vector2.Max(Vector2.Max(output, input), Vector2.Max(first, second)) + new Vector2(thickness); if (maximum.X < MathF.Max(m_origin.X, clip.minimum.X) || minimum.X > MathF.Min(m_origin.X + m_size.X, clip.maximum.X) - || maximum.Y < MathF.Max(m_origin.Y, clip.minimum.Y) || minimum.Y > MathF.Min(m_origin.Y + m_size.Y, clip.maximum.Y)) + || maximum.Y < MathF.Max(m_origin.Y, clip.minimum.Y) || minimum.Y > MathF.Min(m_origin.Y + m_size.Y, clip.maximum.Y) + ) { return; + } draw.PushClip(m_origin, m_origin + m_size, true); try { @@ -191,7 +217,9 @@ public static bool HitConnection( float radius = 6f ) { if (!float.IsFinite(radius) || radius < 0f) + { throw new ArgumentOutOfRangeException(nameof(radius)); + } float tangent = Tangent(output, input); Vector2 first = output + new Vector2(tangent, 0f); Vector2 second = input - new Vector2(tangent, 0f); @@ -204,7 +232,9 @@ public static bool HitConnection( Vector2 line = next - previous; float projection = Math.Clamp(Vector2.Dot(point - previous, line) / MathF.Max(0.001f, line.LengthSquared()), 0f, 1f); if (Vector2.DistanceSquared(point, previous + projection * line) <= radius * radius) + { return true; + } previous = next; } diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs index 0fc54eb12..5a548aaa1 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Graph.ImGui; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Graph", "Inno.Editor.Graph.ImGui", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(GraphCanvasView), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs index c7ac2ca73..a42e8d4bf 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides pointer-free controls within the active Editor UI session. /// @@ -28,7 +30,7 @@ public static bool InvisibleButton( Vector2 size, ImGuiButtonFlags flags = ImGuiButtonFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.InvisibleButton(label, size, (int)flags); } @@ -56,7 +58,7 @@ public static bool MenuItem( bool selected = false, bool enabled = true ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.MenuItem(label, shortcut, selected, enabled); } @@ -92,7 +94,7 @@ public static bool SliderInt( string format = "%d", ImGuiSliderFlags flags = ImGuiSliderFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.SliderInt(label, ref value, minimum, maximum, format, (int)flags); } @@ -132,7 +134,7 @@ public static bool DragInt( string format = "%d", ImGuiSliderFlags flags = ImGuiSliderFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.DragInt(label, ref value, speed, minimum, maximum, format, (int)flags); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs index 0345dfa35..598be6842 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides frame-bounded drawing access and copied presentation values. /// @@ -19,7 +21,7 @@ public static partial class ImGui /// public static uint GetStyleColor(ImGuiCol color) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetColorU32((int)color); } @@ -32,9 +34,9 @@ public static uint GetStyleColor(ImGuiCol color) /// /// A copied value from the active presentation context. /// - public static uint GetControlId(string label) + public static uint GetControlID(string label) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetID(label); } @@ -55,7 +57,7 @@ public static void PushClipRect( Vector2 maximum, bool intersect ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushClipRect(minimum, maximum, intersect); } @@ -64,7 +66,7 @@ bool intersect /// public static void PopClipRect() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PopClipRect(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs index bf8a53a6a..de0f6a159 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs @@ -1,8 +1,11 @@ using System.Numerics; using Inno.Native.ImGui; + +using NativeKey = Inno.Native.ImGui.ImGuiKey; using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Reads copied input values from the active Editor UI session. /// @@ -16,7 +19,7 @@ public static partial class ImGui /// public static Vector2 GetMousePos() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetMousePos(); } @@ -36,7 +39,7 @@ public static bool IsMouseClicked( ImGuiMouseButton button, bool repeat = false ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsMouseClicked((int)button, repeat); } @@ -51,7 +54,7 @@ public static bool IsMouseClicked( /// public static bool IsMouseReleased(ImGuiMouseButton button) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsMouseReleased((int)button); } @@ -66,7 +69,7 @@ public static bool IsMouseReleased(ImGuiMouseButton button) /// public static bool IsMouseDoubleClicked(ImGuiMouseButton button) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsMouseDoubleClicked((int)button); } @@ -81,8 +84,8 @@ public static bool IsMouseDoubleClicked(ImGuiMouseButton button) /// public static bool IsKeyDown(ImGuiKey key) { - EditorUiSession.current.EnsureDrawing(); - return RawImGui.IsKeyDown((Inno.Native.ImGui.ImGuiKey)key); + EditorUISession.current.EnsureDrawing(); + return RawImGui.IsKeyDown((NativeKey)key); } /// @@ -101,8 +104,8 @@ public static bool IsKeyPressed( ImGuiKey key, bool repeat = true ) { - EditorUiSession.current.EnsureDrawing(); - return RawImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)key, repeat); + EditorUISession.current.EnsureDrawing(); + return RawImGui.IsKeyPressed((NativeKey)key, repeat); } /// @@ -113,7 +116,7 @@ public static bool IsKeyPressed( /// public static void ResetMouseDragDelta(ImGuiMouseButton button) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.ResetMouseDragDelta((int)button); } @@ -125,7 +128,7 @@ public static void ResetMouseDragDelta(ImGuiMouseButton button) /// public static void SetMouseCursor(ImGuiMouseCursor cursor) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetMouseCursor((int)cursor); } @@ -149,7 +152,7 @@ public static bool IsMouseHoveringRect( Vector2 maximum, bool clip = true ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsMouseHoveringRect(minimum, maximum, clip); } @@ -164,7 +167,7 @@ public static bool IsMouseHoveringRect( /// public static bool IsWindowHovered(ImGuiHoveredFlags flags = ImGuiHoveredFlags.None) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsWindowHovered((int)flags); } @@ -179,7 +182,7 @@ public static bool IsWindowHovered(ImGuiHoveredFlags flags = ImGuiHoveredFlags.N /// public static bool IsWindowFocused(ImGuiFocusedFlags flags = ImGuiFocusedFlags.None) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsWindowFocused((int)flags); } @@ -191,7 +194,7 @@ public static bool IsWindowFocused(ImGuiFocusedFlags flags = ImGuiFocusedFlags.N /// public static bool IsAnyItemHovered() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsAnyItemHovered(); } @@ -203,7 +206,7 @@ public static bool IsAnyItemHovered() /// public static bool IsAnyItemActive() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsAnyItemActive(); } @@ -215,7 +218,7 @@ public static bool IsAnyItemActive() /// public static bool IsItemActivated() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsItemActivated(); } @@ -227,7 +230,7 @@ public static bool IsItemActivated() /// public static bool IsItemDeactivatedAfterEdit() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsItemDeactivatedAfterEdit(); } @@ -239,7 +242,7 @@ public static bool IsItemDeactivatedAfterEdit() /// public static void SetKeyboardFocusHere(int offset = 0) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetKeyboardFocusHere(offset); } @@ -248,7 +251,7 @@ public static void SetKeyboardFocusHere(int offset = 0) /// public static void SetItemDefaultFocus() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetItemDefaultFocus(); } @@ -260,7 +263,7 @@ public static void SetItemDefaultFocus() /// public static void SetClipboardText(string text) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetClipboardText(text); } @@ -272,7 +275,7 @@ public static void SetClipboardText(string text) /// public static int GetFrameCount() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetFrameCount(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs index 0143391de..6480d8619 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides scoped layout operations without exposing native context storage. /// @@ -16,7 +18,7 @@ public static partial class ImGui /// public static void SetCursorScreenPosition(Vector2 position) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetCursorScreenPos(position); } @@ -28,7 +30,7 @@ public static void SetCursorScreenPosition(Vector2 position) /// public static void SetCursorPosX(float position) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetCursorPosX(position); } @@ -40,7 +42,7 @@ public static void SetCursorPosX(float position) /// public static void SetCursorPosY(float position) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetCursorPosY(position); } @@ -52,7 +54,7 @@ public static void SetCursorPosY(float position) /// public static float GetCursorPosX() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetCursorPosX(); } @@ -64,7 +66,7 @@ public static float GetCursorPosX() /// public static float GetCursorPosY() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetCursorPosY(); } @@ -76,7 +78,7 @@ public static float GetCursorPosY() /// public static Vector2 GetWindowPos() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetWindowPos(); } @@ -88,7 +90,7 @@ public static Vector2 GetWindowPos() /// public static Vector2 GetWindowSize() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetWindowSize(); } @@ -100,7 +102,7 @@ public static Vector2 GetWindowSize() /// public static float GetFontSize() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetFontSize(); } @@ -112,7 +114,7 @@ public static float GetFontSize() /// public static float GetFrameHeight() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetFrameHeight(); } @@ -124,7 +126,7 @@ public static float GetFrameHeight() /// public static float GetTextLineHeight() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetTextLineHeight(); } @@ -136,7 +138,7 @@ public static float GetTextLineHeight() /// public static float GetFrameHeightWithSpacing() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetFrameHeightWithSpacing(); } @@ -148,7 +150,7 @@ public static float GetFrameHeightWithSpacing() /// public static float GetWindowDpiScale() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetWindowDpiScale(); } @@ -157,7 +159,7 @@ public static float GetWindowDpiScale() /// public static void AlignTextToFramePadding() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.AlignTextToFramePadding(); } @@ -166,7 +168,7 @@ public static void AlignTextToFramePadding() /// public static void SetNextItemAllowOverlap() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetNextItemAllowOverlap(); } @@ -183,7 +185,7 @@ public static void SetNextWindowSize( Vector2 size, ImGuiCond condition = ImGuiCond.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetNextWindowSize(size, (int)condition); } @@ -195,7 +197,7 @@ public static void SetNextWindowSize( /// public static void SetNextWindowContentSize(Vector2 size) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetNextWindowContentSize(size); } @@ -207,7 +209,7 @@ public static void SetNextWindowContentSize(Vector2 size) /// public static void Indent(float amount = 0f) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.Indent(amount); } @@ -219,7 +221,7 @@ public static void Indent(float amount = 0f) /// public static void Unindent(float amount = 0f) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.Unindent(amount); } @@ -231,7 +233,7 @@ public static void Unindent(float amount = 0f) /// public static void PushTextWrapPos(float position = 0f) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushTextWrapPos(position); } @@ -240,7 +242,7 @@ public static void PushTextWrapPos(float position = 0f) /// public static void PopTextWrapPos() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PopTextWrapPos(); } @@ -252,7 +254,7 @@ public static void PopTextWrapPos() /// public static float GetScrollY() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetScrollY(); } @@ -264,7 +266,7 @@ public static float GetScrollY() /// public static float GetScrollMaxY() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetScrollMaxY(); } @@ -276,7 +278,7 @@ public static float GetScrollMaxY() /// public static void SetScrollHereY(float ratio = 0.5f) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetScrollHereY(ratio); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs index 8ecf5a21e..85ba2be52 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Presents tables through the active Editor UI context. /// @@ -19,7 +21,7 @@ public static partial class ImGui /// public static bool TableSetColumnIndex(int index) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.TableSetColumnIndex(index); } @@ -40,7 +42,7 @@ public static void TableSetBgColor( uint color, int column = -1 ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TableSetBgColor((int)target, color, column); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs index 791a9be6f..6002101a7 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeButtonFlags = Inno.Native.ImGui.ImGuiButtonFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported button flags choices at the Editor presentation boundary. /// @@ -10,25 +13,25 @@ public enum ImGuiButtonFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiButtonFlags.None, + None = (int)NativeButtonFlags.None, /// /// React on left mouse button (default) /// - MouseButtonLeft = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonLeft, + MouseButtonLeft = (int)NativeButtonFlags.MouseButtonLeft, /// /// React on right mouse button /// - MouseButtonRight = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonRight, + MouseButtonRight = (int)NativeButtonFlags.MouseButtonRight, /// /// React on center mouse button /// - MouseButtonMiddle = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonMiddle, + MouseButtonMiddle = (int)NativeButtonFlags.MouseButtonMiddle, /// /// Selects the mouse button mask presentation behavior. /// - MouseButtonMask = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonMask, + MouseButtonMask = (int)NativeButtonFlags.MouseButtonMask, /// /// InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. /// - EnableNav = (int)Inno.Native.ImGui.ImGuiButtonFlags.EnableNav, + EnableNav = (int)NativeButtonFlags.EnableNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs index 47cb3cc84..0b04dc914 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeChildFlags = Inno.Native.ImGui.ImGuiChildFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported child flags choices at the Editor presentation boundary. /// @@ -10,41 +13,41 @@ public enum ImGuiChildFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiChildFlags.None, + None = (int)NativeChildFlags.None, /// /// Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) /// - Borders = (int)Inno.Native.ImGui.ImGuiChildFlags.Borders, + Borders = (int)NativeChildFlags.Borders, /// /// Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) /// - AlwaysUseWindowPadding = (int)Inno.Native.ImGui.ImGuiChildFlags.AlwaysUseWindowPadding, + AlwaysUseWindowPadding = (int)NativeChildFlags.AlwaysUseWindowPadding, /// /// Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) /// - ResizeX = (int)Inno.Native.ImGui.ImGuiChildFlags.ResizeX, + ResizeX = (int)NativeChildFlags.ResizeX, /// /// Allow resize from bottom border (layout direction). " /// - ResizeY = (int)Inno.Native.ImGui.ImGuiChildFlags.ResizeY, + ResizeY = (int)NativeChildFlags.ResizeY, /// /// Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. /// - AutoResizeX = (int)Inno.Native.ImGui.ImGuiChildFlags.AutoResizeX, + AutoResizeX = (int)NativeChildFlags.AutoResizeX, /// /// Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. /// - AutoResizeY = (int)Inno.Native.ImGui.ImGuiChildFlags.AutoResizeY, + AutoResizeY = (int)NativeChildFlags.AutoResizeY, /// /// Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. /// - AlwaysAutoResize = (int)Inno.Native.ImGui.ImGuiChildFlags.AlwaysAutoResize, + AlwaysAutoResize = (int)NativeChildFlags.AlwaysAutoResize, /// /// Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. /// - FrameStyle = (int)Inno.Native.ImGui.ImGuiChildFlags.FrameStyle, + FrameStyle = (int)NativeChildFlags.FrameStyle, /// /// Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. /// - NavFlattened = (int)Inno.Native.ImGui.ImGuiChildFlags.NavFlattened, + NavFlattened = (int)NativeChildFlags.NavFlattened } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs index eeee906c8..ead46190b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs @@ -1,6 +1,9 @@ using System; +using NativeCol = Inno.Native.ImGui.ImGuiCol; + namespace Inno.Editor.ImGui; + /// /// Defines the supported col choices at the Editor presentation boundary. /// @@ -9,253 +12,253 @@ public enum ImGuiCol : int /// /// Selects the text presentation behavior. /// - Text = (int)Inno.Native.ImGui.ImGuiCol.Text, + Text = (int)NativeCol.Text, /// /// Selects the text disabled presentation behavior. /// - TextDisabled = (int)Inno.Native.ImGui.ImGuiCol.TextDisabled, + TextDisabled = (int)NativeCol.TextDisabled, /// /// Selects the window bg presentation behavior. /// - WindowBg = (int)Inno.Native.ImGui.ImGuiCol.WindowBg, + WindowBg = (int)NativeCol.WindowBg, /// /// Selects the child bg presentation behavior. /// - ChildBg = (int)Inno.Native.ImGui.ImGuiCol.ChildBg, + ChildBg = (int)NativeCol.ChildBg, /// /// Selects the popup bg presentation behavior. /// - PopupBg = (int)Inno.Native.ImGui.ImGuiCol.PopupBg, + PopupBg = (int)NativeCol.PopupBg, /// /// Selects the border presentation behavior. /// - Border = (int)Inno.Native.ImGui.ImGuiCol.Border, + Border = (int)NativeCol.Border, /// /// Selects the border shadow presentation behavior. /// - BorderShadow = (int)Inno.Native.ImGui.ImGuiCol.BorderShadow, + BorderShadow = (int)NativeCol.BorderShadow, /// /// Selects the frame bg presentation behavior. /// - FrameBg = (int)Inno.Native.ImGui.ImGuiCol.FrameBg, + FrameBg = (int)NativeCol.FrameBg, /// /// Selects the frame bg hovered presentation behavior. /// - FrameBgHovered = (int)Inno.Native.ImGui.ImGuiCol.FrameBgHovered, + FrameBgHovered = (int)NativeCol.FrameBgHovered, /// /// Selects the frame bg active presentation behavior. /// - FrameBgActive = (int)Inno.Native.ImGui.ImGuiCol.FrameBgActive, + FrameBgActive = (int)NativeCol.FrameBgActive, /// /// Selects the title bg presentation behavior. /// - TitleBg = (int)Inno.Native.ImGui.ImGuiCol.TitleBg, + TitleBg = (int)NativeCol.TitleBg, /// /// Selects the title bg active presentation behavior. /// - TitleBgActive = (int)Inno.Native.ImGui.ImGuiCol.TitleBgActive, + TitleBgActive = (int)NativeCol.TitleBgActive, /// /// Selects the title bg collapsed presentation behavior. /// - TitleBgCollapsed = (int)Inno.Native.ImGui.ImGuiCol.TitleBgCollapsed, + TitleBgCollapsed = (int)NativeCol.TitleBgCollapsed, /// /// Selects the menu bar bg presentation behavior. /// - MenuBarBg = (int)Inno.Native.ImGui.ImGuiCol.MenuBarBg, + MenuBarBg = (int)NativeCol.MenuBarBg, /// /// Selects the scrollbar bg presentation behavior. /// - ScrollbarBg = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarBg, + ScrollbarBg = (int)NativeCol.ScrollbarBg, /// /// Selects the scrollbar grab presentation behavior. /// - ScrollbarGrab = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrab, + ScrollbarGrab = (int)NativeCol.ScrollbarGrab, /// /// Selects the scrollbar grab hovered presentation behavior. /// - ScrollbarGrabHovered = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrabHovered, + ScrollbarGrabHovered = (int)NativeCol.ScrollbarGrabHovered, /// /// Selects the scrollbar grab active presentation behavior. /// - ScrollbarGrabActive = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrabActive, + ScrollbarGrabActive = (int)NativeCol.ScrollbarGrabActive, /// /// Selects the check mark presentation behavior. /// - CheckMark = (int)Inno.Native.ImGui.ImGuiCol.CheckMark, + CheckMark = (int)NativeCol.CheckMark, /// /// Selects the slider grab presentation behavior. /// - SliderGrab = (int)Inno.Native.ImGui.ImGuiCol.SliderGrab, + SliderGrab = (int)NativeCol.SliderGrab, /// /// Selects the slider grab active presentation behavior. /// - SliderGrabActive = (int)Inno.Native.ImGui.ImGuiCol.SliderGrabActive, + SliderGrabActive = (int)NativeCol.SliderGrabActive, /// /// Selects the button presentation behavior. /// - Button = (int)Inno.Native.ImGui.ImGuiCol.Button, + Button = (int)NativeCol.Button, /// /// Selects the button hovered presentation behavior. /// - ButtonHovered = (int)Inno.Native.ImGui.ImGuiCol.ButtonHovered, + ButtonHovered = (int)NativeCol.ButtonHovered, /// /// Selects the button active presentation behavior. /// - ButtonActive = (int)Inno.Native.ImGui.ImGuiCol.ButtonActive, + ButtonActive = (int)NativeCol.ButtonActive, /// /// Selects the header presentation behavior. /// - Header = (int)Inno.Native.ImGui.ImGuiCol.Header, + Header = (int)NativeCol.Header, /// /// Selects the header hovered presentation behavior. /// - HeaderHovered = (int)Inno.Native.ImGui.ImGuiCol.HeaderHovered, + HeaderHovered = (int)NativeCol.HeaderHovered, /// /// Selects the header active presentation behavior. /// - HeaderActive = (int)Inno.Native.ImGui.ImGuiCol.HeaderActive, + HeaderActive = (int)NativeCol.HeaderActive, /// /// Selects the separator presentation behavior. /// - Separator = (int)Inno.Native.ImGui.ImGuiCol.Separator, + Separator = (int)NativeCol.Separator, /// /// Selects the separator hovered presentation behavior. /// - SeparatorHovered = (int)Inno.Native.ImGui.ImGuiCol.SeparatorHovered, + SeparatorHovered = (int)NativeCol.SeparatorHovered, /// /// Selects the separator active presentation behavior. /// - SeparatorActive = (int)Inno.Native.ImGui.ImGuiCol.SeparatorActive, + SeparatorActive = (int)NativeCol.SeparatorActive, /// /// Selects the resize grip presentation behavior. /// - ResizeGrip = (int)Inno.Native.ImGui.ImGuiCol.ResizeGrip, + ResizeGrip = (int)NativeCol.ResizeGrip, /// /// Selects the resize grip hovered presentation behavior. /// - ResizeGripHovered = (int)Inno.Native.ImGui.ImGuiCol.ResizeGripHovered, + ResizeGripHovered = (int)NativeCol.ResizeGripHovered, /// /// Selects the resize grip active presentation behavior. /// - ResizeGripActive = (int)Inno.Native.ImGui.ImGuiCol.ResizeGripActive, + ResizeGripActive = (int)NativeCol.ResizeGripActive, /// /// Selects the input text cursor presentation behavior. /// - InputTextCursor = (int)Inno.Native.ImGui.ImGuiCol.InputTextCursor, + InputTextCursor = (int)NativeCol.InputTextCursor, /// /// Selects the tab hovered presentation behavior. /// - TabHovered = (int)Inno.Native.ImGui.ImGuiCol.TabHovered, + TabHovered = (int)NativeCol.TabHovered, /// /// Selects the tab presentation behavior. /// - Tab = (int)Inno.Native.ImGui.ImGuiCol.Tab, + Tab = (int)NativeCol.Tab, /// /// Selects the tab selected presentation behavior. /// - TabSelected = (int)Inno.Native.ImGui.ImGuiCol.TabSelected, + TabSelected = (int)NativeCol.TabSelected, /// /// Selects the tab selected overline presentation behavior. /// - TabSelectedOverline = (int)Inno.Native.ImGui.ImGuiCol.TabSelectedOverline, + TabSelectedOverline = (int)NativeCol.TabSelectedOverline, /// /// Selects the tab dimmed presentation behavior. /// - TabDimmed = (int)Inno.Native.ImGui.ImGuiCol.TabDimmed, + TabDimmed = (int)NativeCol.TabDimmed, /// /// Selects the tab dimmed selected presentation behavior. /// - TabDimmedSelected = (int)Inno.Native.ImGui.ImGuiCol.TabDimmedSelected, + TabDimmedSelected = (int)NativeCol.TabDimmedSelected, /// /// Selects the tab dimmed selected overline presentation behavior. /// - TabDimmedSelectedOverline = (int)Inno.Native.ImGui.ImGuiCol.TabDimmedSelectedOverline, + TabDimmedSelectedOverline = (int)NativeCol.TabDimmedSelectedOverline, /// /// Selects the docking preview presentation behavior. /// - DockingPreview = (int)Inno.Native.ImGui.ImGuiCol.DockingPreview, + DockingPreview = (int)NativeCol.DockingPreview, /// /// Selects the docking empty bg presentation behavior. /// - DockingEmptyBg = (int)Inno.Native.ImGui.ImGuiCol.DockingEmptyBg, + DockingEmptyBg = (int)NativeCol.DockingEmptyBg, /// /// Selects the plot lines presentation behavior. /// - PlotLines = (int)Inno.Native.ImGui.ImGuiCol.PlotLines, + PlotLines = (int)NativeCol.PlotLines, /// /// Selects the plot lines hovered presentation behavior. /// - PlotLinesHovered = (int)Inno.Native.ImGui.ImGuiCol.PlotLinesHovered, + PlotLinesHovered = (int)NativeCol.PlotLinesHovered, /// /// Selects the plot histogram presentation behavior. /// - PlotHistogram = (int)Inno.Native.ImGui.ImGuiCol.PlotHistogram, + PlotHistogram = (int)NativeCol.PlotHistogram, /// /// Selects the plot histogram hovered presentation behavior. /// - PlotHistogramHovered = (int)Inno.Native.ImGui.ImGuiCol.PlotHistogramHovered, + PlotHistogramHovered = (int)NativeCol.PlotHistogramHovered, /// /// Selects the table header bg presentation behavior. /// - TableHeaderBg = (int)Inno.Native.ImGui.ImGuiCol.TableHeaderBg, + TableHeaderBg = (int)NativeCol.TableHeaderBg, /// /// Selects the table border strong presentation behavior. /// - TableBorderStrong = (int)Inno.Native.ImGui.ImGuiCol.TableBorderStrong, + TableBorderStrong = (int)NativeCol.TableBorderStrong, /// /// Selects the table border light presentation behavior. /// - TableBorderLight = (int)Inno.Native.ImGui.ImGuiCol.TableBorderLight, + TableBorderLight = (int)NativeCol.TableBorderLight, /// /// Selects the table row bg presentation behavior. /// - TableRowBg = (int)Inno.Native.ImGui.ImGuiCol.TableRowBg, + TableRowBg = (int)NativeCol.TableRowBg, /// /// Selects the table row bg alt presentation behavior. /// - TableRowBgAlt = (int)Inno.Native.ImGui.ImGuiCol.TableRowBgAlt, + TableRowBgAlt = (int)NativeCol.TableRowBgAlt, /// /// Selects the text link presentation behavior. /// - TextLink = (int)Inno.Native.ImGui.ImGuiCol.TextLink, + TextLink = (int)NativeCol.TextLink, /// /// Selects the text selected bg presentation behavior. /// - TextSelectedBg = (int)Inno.Native.ImGui.ImGuiCol.TextSelectedBg, + TextSelectedBg = (int)NativeCol.TextSelectedBg, /// /// Selects the tree lines presentation behavior. /// - TreeLines = (int)Inno.Native.ImGui.ImGuiCol.TreeLines, + TreeLines = (int)NativeCol.TreeLines, /// /// Selects the drag drop target presentation behavior. /// - DragDropTarget = (int)Inno.Native.ImGui.ImGuiCol.DragDropTarget, + DragDropTarget = (int)NativeCol.DragDropTarget, /// /// Selects the drag drop target bg presentation behavior. /// - DragDropTargetBg = (int)Inno.Native.ImGui.ImGuiCol.DragDropTargetBg, + DragDropTargetBg = (int)NativeCol.DragDropTargetBg, /// /// Selects the unsaved marker presentation behavior. /// - UnsavedMarker = (int)Inno.Native.ImGui.ImGuiCol.UnsavedMarker, + UnsavedMarker = (int)NativeCol.UnsavedMarker, /// /// Selects the nav cursor presentation behavior. /// - NavCursor = (int)Inno.Native.ImGui.ImGuiCol.NavCursor, + NavCursor = (int)NativeCol.NavCursor, /// /// Selects the nav windowing highlight presentation behavior. /// - NavWindowingHighlight = (int)Inno.Native.ImGui.ImGuiCol.NavWindowingHighlight, + NavWindowingHighlight = (int)NativeCol.NavWindowingHighlight, /// /// Selects the nav windowing dim bg presentation behavior. /// - NavWindowingDimBg = (int)Inno.Native.ImGui.ImGuiCol.NavWindowingDimBg, + NavWindowingDimBg = (int)NativeCol.NavWindowingDimBg, /// /// Selects the modal window dim bg presentation behavior. /// - ModalWindowDimBg = (int)Inno.Native.ImGui.ImGuiCol.ModalWindowDimBg, + ModalWindowDimBg = (int)NativeCol.ModalWindowDimBg, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiCol.Count, + Count = (int)NativeCol.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs index 6db099ef5..d7d5a015b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeColorEditFlags = Inno.Native.ImGui.ImGuiColorEditFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported color edit flags choices at the Editor presentation boundary. /// @@ -10,129 +13,129 @@ public enum ImGuiColorEditFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiColorEditFlags.None, + None = (int)NativeColorEditFlags.None, /// /// // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). /// - NoAlpha = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoAlpha, + NoAlpha = (int)NativeColorEditFlags.NoAlpha, /// /// // ColorEdit: disable picker when clicking on color square. /// - NoPicker = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoPicker, + NoPicker = (int)NativeColorEditFlags.NoPicker, /// /// // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. /// - NoOptions = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoOptions, + NoOptions = (int)NativeColorEditFlags.NoOptions, /// /// // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) /// - NoSmallPreview = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoSmallPreview, + NoSmallPreview = (int)NativeColorEditFlags.NoSmallPreview, /// /// // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). /// - NoInputs = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoInputs, + NoInputs = (int)NativeColorEditFlags.NoInputs, /// /// // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoTooltip, + NoTooltip = (int)NativeColorEditFlags.NoTooltip, /// /// // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). /// - NoLabel = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoLabel, + NoLabel = (int)NativeColorEditFlags.NoLabel, /// /// // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. /// - NoSidePreview = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoSidePreview, + NoSidePreview = (int)NativeColorEditFlags.NoSidePreview, /// /// // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. /// - NoDragDrop = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoDragDrop, + NoDragDrop = (int)NativeColorEditFlags.NoDragDrop, /// /// // ColorButton: disable border (which is enforced by default) /// - NoBorder = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoBorder, + NoBorder = (int)NativeColorEditFlags.NoBorder, /// /// // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. /// - NoColorMarkers = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoColorMarkers, + NoColorMarkers = (int)NativeColorEditFlags.NoColorMarkers, /// /// // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. /// - AlphaOpaque = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaOpaque, + AlphaOpaque = (int)NativeColorEditFlags.AlphaOpaque, /// /// // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. /// - AlphaNoBg = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaNoBg, + AlphaNoBg = (int)NativeColorEditFlags.AlphaNoBg, /// /// // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. /// - AlphaPreviewHalf = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaPreviewHalf, + AlphaPreviewHalf = (int)NativeColorEditFlags.AlphaPreviewHalf, /// /// // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. /// - AlphaBar = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaBar, + AlphaBar = (int)NativeColorEditFlags.AlphaBar, /// /// Selects the hdr presentation behavior. /// - Hdr = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Hdr, + Hdr = (int)NativeColorEditFlags.Hdr, /// /// Selects the display rgb presentation behavior. /// - DisplayRgb = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayRgb, + DisplayRgb = (int)NativeColorEditFlags.DisplayRgb, /// /// Selects the display hsv presentation behavior. /// - DisplayHsv = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayHsv, + DisplayHsv = (int)NativeColorEditFlags.DisplayHsv, /// /// // " /// - DisplayHex = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayHex, + DisplayHex = (int)NativeColorEditFlags.DisplayHex, /// /// // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. /// - Uint8 = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Uint8, + Uint8 = (int)NativeColorEditFlags.Uint8, /// /// // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. /// - Float = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Float, + Float = (int)NativeColorEditFlags.Float, /// /// // ColorPicker: bar for Hue, rectangle for Sat/Value. /// - PickerHueBar = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerHueBar, + PickerHueBar = (int)NativeColorEditFlags.PickerHueBar, /// /// // ColorPicker: wheel for Hue, triangle for Sat/Value. /// - PickerHueWheel = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerHueWheel, + PickerHueWheel = (int)NativeColorEditFlags.PickerHueWheel, /// /// Selects the input rgb presentation behavior. /// - InputRgb = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputRgb, + InputRgb = (int)NativeColorEditFlags.InputRgb, /// /// Selects the input hsv presentation behavior. /// - InputHsv = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputHsv, + InputHsv = (int)NativeColorEditFlags.InputHsv, /// /// Selects the default options presentation behavior. /// - DefaultOptions = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DefaultOptions, + DefaultOptions = (int)NativeColorEditFlags.DefaultOptions, /// /// Selects the alpha mask presentation behavior. /// - AlphaMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaMask, + AlphaMask = (int)NativeColorEditFlags.AlphaMask, /// /// Selects the display mask presentation behavior. /// - DisplayMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayMask, + DisplayMask = (int)NativeColorEditFlags.DisplayMask, /// /// Selects the data type mask presentation behavior. /// - DataTypeMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DataTypeMask, + DataTypeMask = (int)NativeColorEditFlags.DataTypeMask, /// /// Selects the picker mask presentation behavior. /// - PickerMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerMask, + PickerMask = (int)NativeColorEditFlags.PickerMask, /// /// Selects the input mask presentation behavior. /// - InputMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputMask, + InputMask = (int)NativeColorEditFlags.InputMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs index 535401069..5f1cd1867 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeComboFlags = Inno.Native.ImGui.ImGuiComboFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported combo flags choices at the Editor presentation boundary. /// @@ -10,41 +13,41 @@ public enum ImGuiComboFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiComboFlags.None, + None = (int)NativeComboFlags.None, /// /// Align the popup toward the left by default /// - PopupAlignLeft = (int)Inno.Native.ImGui.ImGuiComboFlags.PopupAlignLeft, + PopupAlignLeft = (int)NativeComboFlags.PopupAlignLeft, /// /// Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() /// - HeightSmall = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightSmall, + HeightSmall = (int)NativeComboFlags.HeightSmall, /// /// Max ~8 items visible (default) /// - HeightRegular = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightRegular, + HeightRegular = (int)NativeComboFlags.HeightRegular, /// /// Max ~20 items visible /// - HeightLarge = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightLarge, + HeightLarge = (int)NativeComboFlags.HeightLarge, /// /// As many fitting items as possible /// - HeightLargest = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightLargest, + HeightLargest = (int)NativeComboFlags.HeightLargest, /// /// Display on the preview box without the square arrow button /// - NoArrowButton = (int)Inno.Native.ImGui.ImGuiComboFlags.NoArrowButton, + NoArrowButton = (int)NativeComboFlags.NoArrowButton, /// /// Display only a square arrow button /// - NoPreview = (int)Inno.Native.ImGui.ImGuiComboFlags.NoPreview, + NoPreview = (int)NativeComboFlags.NoPreview, /// /// Width dynamically calculated from preview contents /// - WidthFitPreview = (int)Inno.Native.ImGui.ImGuiComboFlags.WidthFitPreview, + WidthFitPreview = (int)NativeComboFlags.WidthFitPreview, /// /// Selects the height mask presentation behavior. /// - HeightMask = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightMask, + HeightMask = (int)NativeComboFlags.HeightMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs index 67cbbf90e..a48ff4862 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs @@ -1,6 +1,9 @@ using System; +using NativeCond = Inno.Native.ImGui.ImGuiCond; + namespace Inno.Editor.ImGui; + /// /// Defines the supported cond choices at the Editor presentation boundary. /// @@ -10,21 +13,21 @@ public enum ImGuiCond : int /// /// No condition (always set the variable), same as _Always /// - None = (int)Inno.Native.ImGui.ImGuiCond.None, + None = (int)NativeCond.None, /// /// No condition (always set the variable), same as _None /// - Always = (int)Inno.Native.ImGui.ImGuiCond.Always, + Always = (int)NativeCond.Always, /// /// Set the variable once per runtime session (only the first call will succeed) /// - Once = (int)Inno.Native.ImGui.ImGuiCond.Once, + Once = (int)NativeCond.Once, /// /// Set the variable if the object/window has no persistently saved data (no entry in .ini file) /// - FirstUseEver = (int)Inno.Native.ImGui.ImGuiCond.FirstUseEver, + FirstUseEver = (int)NativeCond.FirstUseEver, /// /// Set the variable if the object/window is appearing after being hidden/inactive (or the first time) /// - Appearing = (int)Inno.Native.ImGui.ImGuiCond.Appearing, + Appearing = (int)NativeCond.Appearing } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs index 04bcc642c..039401efe 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported focused flags choices at the Editor presentation boundary. /// @@ -10,29 +13,29 @@ public enum ImGuiFocusedFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiFocusedFlags.None, + None = (int)NativeFocusedFlags.None, /// /// Return true if any children of the window is focused /// - ChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows, + ChildWindows = (int)NativeFocusedFlags.ChildWindows, /// /// Test from root window (top most parent of the current hierarchy) /// - RootWindow = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootWindow, + RootWindow = (int)NativeFocusedFlags.RootWindow, /// /// Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! /// - AnyWindow = (int)Inno.Native.ImGui.ImGuiFocusedFlags.AnyWindow, + AnyWindow = (int)NativeFocusedFlags.AnyWindow, /// /// Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) /// - NoPopupHierarchy = (int)Inno.Native.ImGui.ImGuiFocusedFlags.NoPopupHierarchy, + NoPopupHierarchy = (int)NativeFocusedFlags.NoPopupHierarchy, /// /// Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) /// - DockHierarchy = (int)Inno.Native.ImGui.ImGuiFocusedFlags.DockHierarchy, + DockHierarchy = (int)NativeFocusedFlags.DockHierarchy, /// /// Selects the root and child windows presentation behavior. /// - RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows, + RootAndChildWindows = (int)NativeFocusedFlags.RootAndChildWindows } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs index 0a8025156..e220b67b8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeHoveredFlags = Inno.Native.ImGui.ImGuiHoveredFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported hovered flags choices at the Editor presentation boundary. /// @@ -10,85 +13,85 @@ public enum ImGuiHoveredFlags : int /// /// Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. /// - None = (int)Inno.Native.ImGui.ImGuiHoveredFlags.None, + None = (int)NativeHoveredFlags.None, /// /// IsWindowHovered() only: Return true if any children of the window is hovered /// - ChildWindows = (int)Inno.Native.ImGui.ImGuiHoveredFlags.ChildWindows, + ChildWindows = (int)NativeHoveredFlags.ChildWindows, /// /// IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) /// - RootWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RootWindow, + RootWindow = (int)NativeHoveredFlags.RootWindow, /// /// IsWindowHovered() only: Return true if any window is hovered /// - AnyWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AnyWindow, + AnyWindow = (int)NativeHoveredFlags.AnyWindow, /// /// IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) /// - NoPopupHierarchy = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoPopupHierarchy, + NoPopupHierarchy = (int)NativeHoveredFlags.NoPopupHierarchy, /// /// IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) /// - DockHierarchy = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DockHierarchy, + DockHierarchy = (int)NativeHoveredFlags.DockHierarchy, /// /// Return true even if a popup window is normally blocking access to this item/window /// - AllowWhenBlockedByPopup = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByPopup, + AllowWhenBlockedByPopup = (int)NativeHoveredFlags.AllowWhenBlockedByPopup, /// /// Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. /// - AllowWhenBlockedByActiveItem = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, + AllowWhenBlockedByActiveItem = (int)NativeHoveredFlags.AllowWhenBlockedByActiveItem, /// /// IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. /// - AllowWhenOverlappedByItem = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlappedByItem, + AllowWhenOverlappedByItem = (int)NativeHoveredFlags.AllowWhenOverlappedByItem, /// /// IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. /// - AllowWhenOverlappedByWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlappedByWindow, + AllowWhenOverlappedByWindow = (int)NativeHoveredFlags.AllowWhenOverlappedByWindow, /// /// IsItemHovered() only: Return true even if the item is disabled /// - AllowWhenDisabled = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenDisabled, + AllowWhenDisabled = (int)NativeHoveredFlags.AllowWhenDisabled, /// /// IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse /// - NoNavOverride = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoNavOverride, + NoNavOverride = (int)NativeHoveredFlags.NoNavOverride, /// /// Selects the allow when overlapped presentation behavior. /// - AllowWhenOverlapped = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlapped, + AllowWhenOverlapped = (int)NativeHoveredFlags.AllowWhenOverlapped, /// /// Selects the rect only presentation behavior. /// - RectOnly = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RectOnly, + RectOnly = (int)NativeHoveredFlags.RectOnly, /// /// Selects the root and child windows presentation behavior. /// - RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RootAndChildWindows, + RootAndChildWindows = (int)NativeHoveredFlags.RootAndChildWindows, /// /// Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. /// - ForTooltip = (int)Inno.Native.ImGui.ImGuiHoveredFlags.ForTooltip, + ForTooltip = (int)NativeHoveredFlags.ForTooltip, /// /// Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. /// - Stationary = (int)Inno.Native.ImGui.ImGuiHoveredFlags.Stationary, + Stationary = (int)NativeHoveredFlags.Stationary, /// /// IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. /// - DelayNone = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayNone, + DelayNone = (int)NativeHoveredFlags.DelayNone, /// /// IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). /// - DelayShort = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayShort, + DelayShort = (int)NativeHoveredFlags.DelayShort, /// /// IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). /// - DelayNormal = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayNormal, + DelayNormal = (int)NativeHoveredFlags.DelayNormal, /// /// IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) /// - NoSharedDelay = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoSharedDelay, + NoSharedDelay = (int)NativeHoveredFlags.NoSharedDelay } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs index 57a99f283..6a9dc3240 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeInputTextFlags = Inno.Native.ImGui.ImGuiInputTextFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported input text flags choices at the Editor presentation boundary. /// @@ -10,105 +13,105 @@ public enum ImGuiInputTextFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiInputTextFlags.None, + None = (int)NativeInputTextFlags.None, /// /// Allow 0123456789.+-*/ /// - CharsDecimal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsDecimal, + CharsDecimal = (int)NativeInputTextFlags.CharsDecimal, /// /// Allow 0123456789ABCDEFabcdef /// - CharsHexadecimal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsHexadecimal, + CharsHexadecimal = (int)NativeInputTextFlags.CharsHexadecimal, /// /// Allow 0123456789.+-*/eE (Scientific notation input) /// - CharsScientific = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsScientific, + CharsScientific = (int)NativeInputTextFlags.CharsScientific, /// /// Turn a..z into A..Z /// - CharsUppercase = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsUppercase, + CharsUppercase = (int)NativeInputTextFlags.CharsUppercase, /// /// Filter out spaces, tabs /// - CharsNoBlank = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsNoBlank, + CharsNoBlank = (int)NativeInputTextFlags.CharsNoBlank, /// /// Pressing TAB input a '\t' character into the text field /// - AllowTabInput = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AllowTabInput, + AllowTabInput = (int)NativeInputTextFlags.AllowTabInput, /// /// Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider using IsItemDeactivatedAfterEdit() instead! /// - EnterReturnsTrue = (int)Inno.Native.ImGui.ImGuiInputTextFlags.EnterReturnsTrue, + EnterReturnsTrue = (int)NativeInputTextFlags.EnterReturnsTrue, /// /// Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) /// - EscapeClearsAll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.EscapeClearsAll, + EscapeClearsAll = (int)NativeInputTextFlags.EscapeClearsAll, /// /// In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). /// - CtrlEnterForNewLine = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CtrlEnterForNewLine, + CtrlEnterForNewLine = (int)NativeInputTextFlags.CtrlEnterForNewLine, /// /// Read-only mode /// - ReadOnly = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ReadOnly, + ReadOnly = (int)NativeInputTextFlags.ReadOnly, /// /// Password mode, display all characters as '*', disable copy /// - Password = (int)Inno.Native.ImGui.ImGuiInputTextFlags.Password, + Password = (int)NativeInputTextFlags.Password, /// /// Overwrite mode /// - AlwaysOverwrite = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AlwaysOverwrite, + AlwaysOverwrite = (int)NativeInputTextFlags.AlwaysOverwrite, /// /// Select entire text when first taking mouse focus /// - AutoSelectAll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AutoSelectAll, + AutoSelectAll = (int)NativeInputTextFlags.AutoSelectAll, /// /// InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. /// - ParseEmptyRefVal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ParseEmptyRefVal, + ParseEmptyRefVal = (int)NativeInputTextFlags.ParseEmptyRefVal, /// /// InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags_ParseEmptyRefVal. /// - DisplayEmptyRefVal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.DisplayEmptyRefVal, + DisplayEmptyRefVal = (int)NativeInputTextFlags.DisplayEmptyRefVal, /// /// Disable following the cursor horizontally /// - NoHorizontalScroll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.NoHorizontalScroll, + NoHorizontalScroll = (int)NativeInputTextFlags.NoHorizontalScroll, /// /// Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). /// - NoUndoRedo = (int)Inno.Native.ImGui.ImGuiInputTextFlags.NoUndoRedo, + NoUndoRedo = (int)NativeInputTextFlags.NoUndoRedo, /// /// When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! /// - ElideLeft = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ElideLeft, + ElideLeft = (int)NativeInputTextFlags.ElideLeft, /// /// Callback on pressing TAB (for completion handling) /// - CallbackCompletion = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackCompletion, + CallbackCompletion = (int)NativeInputTextFlags.CallbackCompletion, /// /// Callback on pressing Up/Down arrows (for history handling) /// - CallbackHistory = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackHistory, + CallbackHistory = (int)NativeInputTextFlags.CallbackHistory, /// /// Callback on each iteration. User code may query cursor position, modify text buffer. /// - CallbackAlways = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackAlways, + CallbackAlways = (int)NativeInputTextFlags.CallbackAlways, /// /// Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. /// - CallbackCharFilter = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackCharFilter, + CallbackCharFilter = (int)NativeInputTextFlags.CallbackCharFilter, /// /// Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) /// - CallbackResize = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackResize, + CallbackResize = (int)NativeInputTextFlags.CallbackResize, /// /// Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. /// - CallbackEdit = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackEdit, + CallbackEdit = (int)NativeInputTextFlags.CallbackEdit, /// /// InputTextMultiline(): word-wrap lines that are too long. /// - WordWrap = (int)Inno.Native.ImGui.ImGuiInputTextFlags.WordWrap, + WordWrap = (int)NativeInputTextFlags.WordWrap } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs index 0120f2fa9..1264a8a64 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs @@ -1,6 +1,9 @@ using System; +using NativeKey = Inno.Native.ImGui.ImGuiKey; + namespace Inno.Editor.ImGui; + /// /// Defines the supported key choices at the Editor presentation boundary. /// @@ -9,661 +12,661 @@ public enum ImGuiKey : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiKey.None, + None = (int)NativeKey.None, /// /// Identifies the NamedKeyBegin presentation key or modifier. /// - NamedKeyBegin = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyBegin, + NamedKeyBegin = (int)NativeKey.NamedKeyBegin, /// /// == ImGuiKey_NamedKey_BEGIN /// - Tab = (int)Inno.Native.ImGui.ImGuiKey.Tab, + Tab = (int)NativeKey.Tab, /// /// Identifies the LeftArrow presentation key or modifier. /// - LeftArrow = (int)Inno.Native.ImGui.ImGuiKey.LeftArrow, + LeftArrow = (int)NativeKey.LeftArrow, /// /// Identifies the RightArrow presentation key or modifier. /// - RightArrow = (int)Inno.Native.ImGui.ImGuiKey.RightArrow, + RightArrow = (int)NativeKey.RightArrow, /// /// Identifies the UpArrow presentation key or modifier. /// - UpArrow = (int)Inno.Native.ImGui.ImGuiKey.UpArrow, + UpArrow = (int)NativeKey.UpArrow, /// /// Identifies the DownArrow presentation key or modifier. /// - DownArrow = (int)Inno.Native.ImGui.ImGuiKey.DownArrow, + DownArrow = (int)NativeKey.DownArrow, /// /// Identifies the PageUp presentation key or modifier. /// - PageUp = (int)Inno.Native.ImGui.ImGuiKey.PageUp, + PageUp = (int)NativeKey.PageUp, /// /// Identifies the PageDown presentation key or modifier. /// - PageDown = (int)Inno.Native.ImGui.ImGuiKey.PageDown, + PageDown = (int)NativeKey.PageDown, /// /// Identifies the Home presentation key or modifier. /// - Home = (int)Inno.Native.ImGui.ImGuiKey.Home, + Home = (int)NativeKey.Home, /// /// Identifies the End presentation key or modifier. /// - End = (int)Inno.Native.ImGui.ImGuiKey.End, + End = (int)NativeKey.End, /// /// Identifies the Insert presentation key or modifier. /// - Insert = (int)Inno.Native.ImGui.ImGuiKey.Insert, + Insert = (int)NativeKey.Insert, /// /// Identifies the Delete presentation key or modifier. /// - Delete = (int)Inno.Native.ImGui.ImGuiKey.Delete, + Delete = (int)NativeKey.Delete, /// /// Identifies the Backspace presentation key or modifier. /// - Backspace = (int)Inno.Native.ImGui.ImGuiKey.Backspace, + Backspace = (int)NativeKey.Backspace, /// /// Identifies the Space presentation key or modifier. /// - Space = (int)Inno.Native.ImGui.ImGuiKey.Space, + Space = (int)NativeKey.Space, /// /// Identifies the Enter presentation key or modifier. /// - Enter = (int)Inno.Native.ImGui.ImGuiKey.Enter, + Enter = (int)NativeKey.Enter, /// /// Identifies the Escape presentation key or modifier. /// - Escape = (int)Inno.Native.ImGui.ImGuiKey.Escape, + Escape = (int)NativeKey.Escape, /// /// Identifies the LeftCtrl presentation key or modifier. /// - LeftCtrl = (int)Inno.Native.ImGui.ImGuiKey.LeftCtrl, + LeftCtrl = (int)NativeKey.LeftCtrl, /// /// Identifies the LeftShift presentation key or modifier. /// - LeftShift = (int)Inno.Native.ImGui.ImGuiKey.LeftShift, + LeftShift = (int)NativeKey.LeftShift, /// /// Identifies the LeftAlt presentation key or modifier. /// - LeftAlt = (int)Inno.Native.ImGui.ImGuiKey.LeftAlt, + LeftAlt = (int)NativeKey.LeftAlt, /// /// Identifies the LeftSuper presentation key or modifier. /// - LeftSuper = (int)Inno.Native.ImGui.ImGuiKey.LeftSuper, + LeftSuper = (int)NativeKey.LeftSuper, /// /// Identifies the RightCtrl presentation key or modifier. /// - RightCtrl = (int)Inno.Native.ImGui.ImGuiKey.RightCtrl, + RightCtrl = (int)NativeKey.RightCtrl, /// /// Identifies the RightShift presentation key or modifier. /// - RightShift = (int)Inno.Native.ImGui.ImGuiKey.RightShift, + RightShift = (int)NativeKey.RightShift, /// /// Identifies the RightAlt presentation key or modifier. /// - RightAlt = (int)Inno.Native.ImGui.ImGuiKey.RightAlt, + RightAlt = (int)NativeKey.RightAlt, /// /// Identifies the RightSuper presentation key or modifier. /// - RightSuper = (int)Inno.Native.ImGui.ImGuiKey.RightSuper, + RightSuper = (int)NativeKey.RightSuper, /// /// Identifies the Menu presentation key or modifier. /// - Menu = (int)Inno.Native.ImGui.ImGuiKey.Menu, + Menu = (int)NativeKey.Menu, /// /// Identifies the _0 presentation key or modifier. /// - _0 = (int)Inno.Native.ImGui.ImGuiKey._0, + _0 = (int)NativeKey._0, /// /// Identifies the _1 presentation key or modifier. /// - _1 = (int)Inno.Native.ImGui.ImGuiKey._1, + _1 = (int)NativeKey._1, /// /// Identifies the _2 presentation key or modifier. /// - _2 = (int)Inno.Native.ImGui.ImGuiKey._2, + _2 = (int)NativeKey._2, /// /// Identifies the _3 presentation key or modifier. /// - _3 = (int)Inno.Native.ImGui.ImGuiKey._3, + _3 = (int)NativeKey._3, /// /// Identifies the _4 presentation key or modifier. /// - _4 = (int)Inno.Native.ImGui.ImGuiKey._4, + _4 = (int)NativeKey._4, /// /// Identifies the _5 presentation key or modifier. /// - _5 = (int)Inno.Native.ImGui.ImGuiKey._5, + _5 = (int)NativeKey._5, /// /// Identifies the _6 presentation key or modifier. /// - _6 = (int)Inno.Native.ImGui.ImGuiKey._6, + _6 = (int)NativeKey._6, /// /// Identifies the _7 presentation key or modifier. /// - _7 = (int)Inno.Native.ImGui.ImGuiKey._7, + _7 = (int)NativeKey._7, /// /// Identifies the _8 presentation key or modifier. /// - _8 = (int)Inno.Native.ImGui.ImGuiKey._8, + _8 = (int)NativeKey._8, /// /// Identifies the _9 presentation key or modifier. /// - _9 = (int)Inno.Native.ImGui.ImGuiKey._9, + _9 = (int)NativeKey._9, /// /// Identifies the A presentation key or modifier. /// - A = (int)Inno.Native.ImGui.ImGuiKey.A, + A = (int)NativeKey.A, /// /// Identifies the B presentation key or modifier. /// - B = (int)Inno.Native.ImGui.ImGuiKey.B, + B = (int)NativeKey.B, /// /// Identifies the C presentation key or modifier. /// - C = (int)Inno.Native.ImGui.ImGuiKey.C, + C = (int)NativeKey.C, /// /// Identifies the D presentation key or modifier. /// - D = (int)Inno.Native.ImGui.ImGuiKey.D, + D = (int)NativeKey.D, /// /// Identifies the E presentation key or modifier. /// - E = (int)Inno.Native.ImGui.ImGuiKey.E, + E = (int)NativeKey.E, /// /// Identifies the F presentation key or modifier. /// - F = (int)Inno.Native.ImGui.ImGuiKey.F, + F = (int)NativeKey.F, /// /// Identifies the G presentation key or modifier. /// - G = (int)Inno.Native.ImGui.ImGuiKey.G, + G = (int)NativeKey.G, /// /// Identifies the H presentation key or modifier. /// - H = (int)Inno.Native.ImGui.ImGuiKey.H, + H = (int)NativeKey.H, /// /// Identifies the I presentation key or modifier. /// - I = (int)Inno.Native.ImGui.ImGuiKey.I, + I = (int)NativeKey.I, /// /// Identifies the J presentation key or modifier. /// - J = (int)Inno.Native.ImGui.ImGuiKey.J, + J = (int)NativeKey.J, /// /// Identifies the K presentation key or modifier. /// - K = (int)Inno.Native.ImGui.ImGuiKey.K, + K = (int)NativeKey.K, /// /// Identifies the L presentation key or modifier. /// - L = (int)Inno.Native.ImGui.ImGuiKey.L, + L = (int)NativeKey.L, /// /// Identifies the M presentation key or modifier. /// - M = (int)Inno.Native.ImGui.ImGuiKey.M, + M = (int)NativeKey.M, /// /// Identifies the N presentation key or modifier. /// - N = (int)Inno.Native.ImGui.ImGuiKey.N, + N = (int)NativeKey.N, /// /// Identifies the O presentation key or modifier. /// - O = (int)Inno.Native.ImGui.ImGuiKey.O, + O = (int)NativeKey.O, /// /// Identifies the P presentation key or modifier. /// - P = (int)Inno.Native.ImGui.ImGuiKey.P, + P = (int)NativeKey.P, /// /// Identifies the Q presentation key or modifier. /// - Q = (int)Inno.Native.ImGui.ImGuiKey.Q, + Q = (int)NativeKey.Q, /// /// Identifies the R presentation key or modifier. /// - R = (int)Inno.Native.ImGui.ImGuiKey.R, + R = (int)NativeKey.R, /// /// Identifies the S presentation key or modifier. /// - S = (int)Inno.Native.ImGui.ImGuiKey.S, + S = (int)NativeKey.S, /// /// Identifies the T presentation key or modifier. /// - T = (int)Inno.Native.ImGui.ImGuiKey.T, + T = (int)NativeKey.T, /// /// Identifies the U presentation key or modifier. /// - U = (int)Inno.Native.ImGui.ImGuiKey.U, + U = (int)NativeKey.U, /// /// Identifies the V presentation key or modifier. /// - V = (int)Inno.Native.ImGui.ImGuiKey.V, + V = (int)NativeKey.V, /// /// Identifies the W presentation key or modifier. /// - W = (int)Inno.Native.ImGui.ImGuiKey.W, + W = (int)NativeKey.W, /// /// Identifies the X presentation key or modifier. /// - X = (int)Inno.Native.ImGui.ImGuiKey.X, + X = (int)NativeKey.X, /// /// Identifies the Y presentation key or modifier. /// - Y = (int)Inno.Native.ImGui.ImGuiKey.Y, + Y = (int)NativeKey.Y, /// /// Identifies the Z presentation key or modifier. /// - Z = (int)Inno.Native.ImGui.ImGuiKey.Z, + Z = (int)NativeKey.Z, /// /// Identifies the F1 presentation key or modifier. /// - F1 = (int)Inno.Native.ImGui.ImGuiKey.F1, + F1 = (int)NativeKey.F1, /// /// Identifies the F2 presentation key or modifier. /// - F2 = (int)Inno.Native.ImGui.ImGuiKey.F2, + F2 = (int)NativeKey.F2, /// /// Identifies the F3 presentation key or modifier. /// - F3 = (int)Inno.Native.ImGui.ImGuiKey.F3, + F3 = (int)NativeKey.F3, /// /// Identifies the F4 presentation key or modifier. /// - F4 = (int)Inno.Native.ImGui.ImGuiKey.F4, + F4 = (int)NativeKey.F4, /// /// Identifies the F5 presentation key or modifier. /// - F5 = (int)Inno.Native.ImGui.ImGuiKey.F5, + F5 = (int)NativeKey.F5, /// /// Identifies the F6 presentation key or modifier. /// - F6 = (int)Inno.Native.ImGui.ImGuiKey.F6, + F6 = (int)NativeKey.F6, /// /// Identifies the F7 presentation key or modifier. /// - F7 = (int)Inno.Native.ImGui.ImGuiKey.F7, + F7 = (int)NativeKey.F7, /// /// Identifies the F8 presentation key or modifier. /// - F8 = (int)Inno.Native.ImGui.ImGuiKey.F8, + F8 = (int)NativeKey.F8, /// /// Identifies the F9 presentation key or modifier. /// - F9 = (int)Inno.Native.ImGui.ImGuiKey.F9, + F9 = (int)NativeKey.F9, /// /// Identifies the F10 presentation key or modifier. /// - F10 = (int)Inno.Native.ImGui.ImGuiKey.F10, + F10 = (int)NativeKey.F10, /// /// Identifies the F11 presentation key or modifier. /// - F11 = (int)Inno.Native.ImGui.ImGuiKey.F11, + F11 = (int)NativeKey.F11, /// /// Identifies the F12 presentation key or modifier. /// - F12 = (int)Inno.Native.ImGui.ImGuiKey.F12, + F12 = (int)NativeKey.F12, /// /// Identifies the F13 presentation key or modifier. /// - F13 = (int)Inno.Native.ImGui.ImGuiKey.F13, + F13 = (int)NativeKey.F13, /// /// Identifies the F14 presentation key or modifier. /// - F14 = (int)Inno.Native.ImGui.ImGuiKey.F14, + F14 = (int)NativeKey.F14, /// /// Identifies the F15 presentation key or modifier. /// - F15 = (int)Inno.Native.ImGui.ImGuiKey.F15, + F15 = (int)NativeKey.F15, /// /// Identifies the F16 presentation key or modifier. /// - F16 = (int)Inno.Native.ImGui.ImGuiKey.F16, + F16 = (int)NativeKey.F16, /// /// Identifies the F17 presentation key or modifier. /// - F17 = (int)Inno.Native.ImGui.ImGuiKey.F17, + F17 = (int)NativeKey.F17, /// /// Identifies the F18 presentation key or modifier. /// - F18 = (int)Inno.Native.ImGui.ImGuiKey.F18, + F18 = (int)NativeKey.F18, /// /// Identifies the F19 presentation key or modifier. /// - F19 = (int)Inno.Native.ImGui.ImGuiKey.F19, + F19 = (int)NativeKey.F19, /// /// Identifies the F20 presentation key or modifier. /// - F20 = (int)Inno.Native.ImGui.ImGuiKey.F20, + F20 = (int)NativeKey.F20, /// /// Identifies the F21 presentation key or modifier. /// - F21 = (int)Inno.Native.ImGui.ImGuiKey.F21, + F21 = (int)NativeKey.F21, /// /// Identifies the F22 presentation key or modifier. /// - F22 = (int)Inno.Native.ImGui.ImGuiKey.F22, + F22 = (int)NativeKey.F22, /// /// Identifies the F23 presentation key or modifier. /// - F23 = (int)Inno.Native.ImGui.ImGuiKey.F23, + F23 = (int)NativeKey.F23, /// /// Identifies the F24 presentation key or modifier. /// - F24 = (int)Inno.Native.ImGui.ImGuiKey.F24, + F24 = (int)NativeKey.F24, /// /// Identifies the Apostrophe presentation key or modifier. /// - Apostrophe = (int)Inno.Native.ImGui.ImGuiKey.Apostrophe, + Apostrophe = (int)NativeKey.Apostrophe, /// /// Identifies the Comma presentation key or modifier. /// - Comma = (int)Inno.Native.ImGui.ImGuiKey.Comma, + Comma = (int)NativeKey.Comma, /// /// Identifies the Minus presentation key or modifier. /// - Minus = (int)Inno.Native.ImGui.ImGuiKey.Minus, + Minus = (int)NativeKey.Minus, /// /// Identifies the Period presentation key or modifier. /// - Period = (int)Inno.Native.ImGui.ImGuiKey.Period, + Period = (int)NativeKey.Period, /// /// Identifies the Slash presentation key or modifier. /// - Slash = (int)Inno.Native.ImGui.ImGuiKey.Slash, + Slash = (int)NativeKey.Slash, /// /// Identifies the Semicolon presentation key or modifier. /// - Semicolon = (int)Inno.Native.ImGui.ImGuiKey.Semicolon, + Semicolon = (int)NativeKey.Semicolon, /// /// Identifies the Equal presentation key or modifier. /// - Equal = (int)Inno.Native.ImGui.ImGuiKey.Equal, + Equal = (int)NativeKey.Equal, /// /// Identifies the LeftBracket presentation key or modifier. /// - LeftBracket = (int)Inno.Native.ImGui.ImGuiKey.LeftBracket, + LeftBracket = (int)NativeKey.LeftBracket, /// /// Identifies the Backslash presentation key or modifier. /// - Backslash = (int)Inno.Native.ImGui.ImGuiKey.Backslash, + Backslash = (int)NativeKey.Backslash, /// /// Identifies the RightBracket presentation key or modifier. /// - RightBracket = (int)Inno.Native.ImGui.ImGuiKey.RightBracket, + RightBracket = (int)NativeKey.RightBracket, /// /// Identifies the GraveAccent presentation key or modifier. /// - GraveAccent = (int)Inno.Native.ImGui.ImGuiKey.GraveAccent, + GraveAccent = (int)NativeKey.GraveAccent, /// /// Identifies the CapsLock presentation key or modifier. /// - CapsLock = (int)Inno.Native.ImGui.ImGuiKey.CapsLock, + CapsLock = (int)NativeKey.CapsLock, /// /// Identifies the ScrollLock presentation key or modifier. /// - ScrollLock = (int)Inno.Native.ImGui.ImGuiKey.ScrollLock, + ScrollLock = (int)NativeKey.ScrollLock, /// /// Identifies the NumLock presentation key or modifier. /// - NumLock = (int)Inno.Native.ImGui.ImGuiKey.NumLock, + NumLock = (int)NativeKey.NumLock, /// /// Identifies the PrintScreen presentation key or modifier. /// - PrintScreen = (int)Inno.Native.ImGui.ImGuiKey.PrintScreen, + PrintScreen = (int)NativeKey.PrintScreen, /// /// Identifies the Pause presentation key or modifier. /// - Pause = (int)Inno.Native.ImGui.ImGuiKey.Pause, + Pause = (int)NativeKey.Pause, /// /// Identifies the Keypad0 presentation key or modifier. /// - Keypad0 = (int)Inno.Native.ImGui.ImGuiKey.Keypad0, + Keypad0 = (int)NativeKey.Keypad0, /// /// Identifies the Keypad1 presentation key or modifier. /// - Keypad1 = (int)Inno.Native.ImGui.ImGuiKey.Keypad1, + Keypad1 = (int)NativeKey.Keypad1, /// /// Identifies the Keypad2 presentation key or modifier. /// - Keypad2 = (int)Inno.Native.ImGui.ImGuiKey.Keypad2, + Keypad2 = (int)NativeKey.Keypad2, /// /// Identifies the Keypad3 presentation key or modifier. /// - Keypad3 = (int)Inno.Native.ImGui.ImGuiKey.Keypad3, + Keypad3 = (int)NativeKey.Keypad3, /// /// Identifies the Keypad4 presentation key or modifier. /// - Keypad4 = (int)Inno.Native.ImGui.ImGuiKey.Keypad4, + Keypad4 = (int)NativeKey.Keypad4, /// /// Identifies the Keypad5 presentation key or modifier. /// - Keypad5 = (int)Inno.Native.ImGui.ImGuiKey.Keypad5, + Keypad5 = (int)NativeKey.Keypad5, /// /// Identifies the Keypad6 presentation key or modifier. /// - Keypad6 = (int)Inno.Native.ImGui.ImGuiKey.Keypad6, + Keypad6 = (int)NativeKey.Keypad6, /// /// Identifies the Keypad7 presentation key or modifier. /// - Keypad7 = (int)Inno.Native.ImGui.ImGuiKey.Keypad7, + Keypad7 = (int)NativeKey.Keypad7, /// /// Identifies the Keypad8 presentation key or modifier. /// - Keypad8 = (int)Inno.Native.ImGui.ImGuiKey.Keypad8, + Keypad8 = (int)NativeKey.Keypad8, /// /// Identifies the Keypad9 presentation key or modifier. /// - Keypad9 = (int)Inno.Native.ImGui.ImGuiKey.Keypad9, + Keypad9 = (int)NativeKey.Keypad9, /// /// Identifies the KeypadDecimal presentation key or modifier. /// - KeypadDecimal = (int)Inno.Native.ImGui.ImGuiKey.KeypadDecimal, + KeypadDecimal = (int)NativeKey.KeypadDecimal, /// /// Identifies the KeypadDivide presentation key or modifier. /// - KeypadDivide = (int)Inno.Native.ImGui.ImGuiKey.KeypadDivide, + KeypadDivide = (int)NativeKey.KeypadDivide, /// /// Identifies the KeypadMultiply presentation key or modifier. /// - KeypadMultiply = (int)Inno.Native.ImGui.ImGuiKey.KeypadMultiply, + KeypadMultiply = (int)NativeKey.KeypadMultiply, /// /// Identifies the KeypadSubtract presentation key or modifier. /// - KeypadSubtract = (int)Inno.Native.ImGui.ImGuiKey.KeypadSubtract, + KeypadSubtract = (int)NativeKey.KeypadSubtract, /// /// Identifies the KeypadAdd presentation key or modifier. /// - KeypadAdd = (int)Inno.Native.ImGui.ImGuiKey.KeypadAdd, + KeypadAdd = (int)NativeKey.KeypadAdd, /// /// Identifies the KeypadEnter presentation key or modifier. /// - KeypadEnter = (int)Inno.Native.ImGui.ImGuiKey.KeypadEnter, + KeypadEnter = (int)NativeKey.KeypadEnter, /// /// Identifies the KeypadEqual presentation key or modifier. /// - KeypadEqual = (int)Inno.Native.ImGui.ImGuiKey.KeypadEqual, + KeypadEqual = (int)NativeKey.KeypadEqual, /// /// Identifies the AppBack presentation key or modifier. /// - AppBack = (int)Inno.Native.ImGui.ImGuiKey.AppBack, + AppBack = (int)NativeKey.AppBack, /// /// Identifies the AppForward presentation key or modifier. /// - AppForward = (int)Inno.Native.ImGui.ImGuiKey.AppForward, + AppForward = (int)NativeKey.AppForward, /// /// Identifies the Oem102 presentation key or modifier. /// - Oem102 = (int)Inno.Native.ImGui.ImGuiKey.Oem102, + Oem102 = (int)NativeKey.Oem102, /// /// Identifies the GamepadStart presentation key or modifier. /// - GamepadStart = (int)Inno.Native.ImGui.ImGuiKey.GamepadStart, + GamepadStart = (int)NativeKey.GamepadStart, /// /// Identifies the GamepadBack presentation key or modifier. /// - GamepadBack = (int)Inno.Native.ImGui.ImGuiKey.GamepadBack, + GamepadBack = (int)NativeKey.GamepadBack, /// /// Identifies the GamepadFaceLeft presentation key or modifier. /// - GamepadFaceLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceLeft, + GamepadFaceLeft = (int)NativeKey.GamepadFaceLeft, /// /// Identifies the GamepadFaceRight presentation key or modifier. /// - GamepadFaceRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceRight, + GamepadFaceRight = (int)NativeKey.GamepadFaceRight, /// /// Identifies the GamepadFaceUp presentation key or modifier. /// - GamepadFaceUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceUp, + GamepadFaceUp = (int)NativeKey.GamepadFaceUp, /// /// Identifies the GamepadFaceDown presentation key or modifier. /// - GamepadFaceDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceDown, + GamepadFaceDown = (int)NativeKey.GamepadFaceDown, /// /// Identifies the GamepadDpadLeft presentation key or modifier. /// - GamepadDpadLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadLeft, + GamepadDpadLeft = (int)NativeKey.GamepadDpadLeft, /// /// Identifies the GamepadDpadRight presentation key or modifier. /// - GamepadDpadRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadRight, + GamepadDpadRight = (int)NativeKey.GamepadDpadRight, /// /// Identifies the GamepadDpadUp presentation key or modifier. /// - GamepadDpadUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadUp, + GamepadDpadUp = (int)NativeKey.GamepadDpadUp, /// /// Identifies the GamepadDpadDown presentation key or modifier. /// - GamepadDpadDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadDown, + GamepadDpadDown = (int)NativeKey.GamepadDpadDown, /// /// Identifies the GamepadL1 presentation key or modifier. /// - GamepadL1 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL1, + GamepadL1 = (int)NativeKey.GamepadL1, /// /// Identifies the GamepadR1 presentation key or modifier. /// - GamepadR1 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR1, + GamepadR1 = (int)NativeKey.GamepadR1, /// /// Identifies the GamepadL2 presentation key or modifier. /// - GamepadL2 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL2, + GamepadL2 = (int)NativeKey.GamepadL2, /// /// Identifies the GamepadR2 presentation key or modifier. /// - GamepadR2 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR2, + GamepadR2 = (int)NativeKey.GamepadR2, /// /// Identifies the GamepadL3 presentation key or modifier. /// - GamepadL3 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL3, + GamepadL3 = (int)NativeKey.GamepadL3, /// /// Identifies the GamepadR3 presentation key or modifier. /// - GamepadR3 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR3, + GamepadR3 = (int)NativeKey.GamepadR3, /// /// Identifies the GamepadLStickLeft presentation key or modifier. /// - GamepadLStickLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickLeft, + GamepadLStickLeft = (int)NativeKey.GamepadLStickLeft, /// /// Identifies the GamepadLStickRight presentation key or modifier. /// - GamepadLStickRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickRight, + GamepadLStickRight = (int)NativeKey.GamepadLStickRight, /// /// Identifies the GamepadLStickUp presentation key or modifier. /// - GamepadLStickUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickUp, + GamepadLStickUp = (int)NativeKey.GamepadLStickUp, /// /// Identifies the GamepadLStickDown presentation key or modifier. /// - GamepadLStickDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickDown, + GamepadLStickDown = (int)NativeKey.GamepadLStickDown, /// /// Identifies the GamepadRStickLeft presentation key or modifier. /// - GamepadRStickLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickLeft, + GamepadRStickLeft = (int)NativeKey.GamepadRStickLeft, /// /// Identifies the GamepadRStickRight presentation key or modifier. /// - GamepadRStickRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickRight, + GamepadRStickRight = (int)NativeKey.GamepadRStickRight, /// /// Identifies the GamepadRStickUp presentation key or modifier. /// - GamepadRStickUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickUp, + GamepadRStickUp = (int)NativeKey.GamepadRStickUp, /// /// Identifies the GamepadRStickDown presentation key or modifier. /// - GamepadRStickDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickDown, + GamepadRStickDown = (int)NativeKey.GamepadRStickDown, /// /// Identifies the MouseLeft presentation key or modifier. /// - MouseLeft = (int)Inno.Native.ImGui.ImGuiKey.MouseLeft, + MouseLeft = (int)NativeKey.MouseLeft, /// /// Identifies the MouseRight presentation key or modifier. /// - MouseRight = (int)Inno.Native.ImGui.ImGuiKey.MouseRight, + MouseRight = (int)NativeKey.MouseRight, /// /// Identifies the MouseMiddle presentation key or modifier. /// - MouseMiddle = (int)Inno.Native.ImGui.ImGuiKey.MouseMiddle, + MouseMiddle = (int)NativeKey.MouseMiddle, /// /// Identifies the MouseX1 presentation key or modifier. /// - MouseX1 = (int)Inno.Native.ImGui.ImGuiKey.MouseX1, + MouseX1 = (int)NativeKey.MouseX1, /// /// Identifies the MouseX2 presentation key or modifier. /// - MouseX2 = (int)Inno.Native.ImGui.ImGuiKey.MouseX2, + MouseX2 = (int)NativeKey.MouseX2, /// /// Identifies the MouseWheelX presentation key or modifier. /// - MouseWheelX = (int)Inno.Native.ImGui.ImGuiKey.MouseWheelX, + MouseWheelX = (int)NativeKey.MouseWheelX, /// /// Identifies the MouseWheelY presentation key or modifier. /// - MouseWheelY = (int)Inno.Native.ImGui.ImGuiKey.MouseWheelY, + MouseWheelY = (int)NativeKey.MouseWheelY, /// /// Identifies the ReservedForModCtrl presentation key or modifier. /// - ReservedForModCtrl = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModCtrl, + ReservedForModCtrl = (int)NativeKey.ReservedForModCtrl, /// /// Identifies the ReservedForModShift presentation key or modifier. /// - ReservedForModShift = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModShift, + ReservedForModShift = (int)NativeKey.ReservedForModShift, /// /// Identifies the ReservedForModAlt presentation key or modifier. /// - ReservedForModAlt = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModAlt, + ReservedForModAlt = (int)NativeKey.ReservedForModAlt, /// /// Identifies the ReservedForModSuper presentation key or modifier. /// - ReservedForModSuper = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModSuper, + ReservedForModSuper = (int)NativeKey.ReservedForModSuper, /// /// Identifies the NamedKeyEnd presentation key or modifier. /// - NamedKeyEnd = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyEnd, + NamedKeyEnd = (int)NativeKey.NamedKeyEnd, /// /// Identifies the NamedKeyCount presentation key or modifier. /// - NamedKeyCount = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyCount, + NamedKeyCount = (int)NativeKey.NamedKeyCount, /// /// Identifies the ImGuiModNone presentation key or modifier. /// - ImGuiModNone = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModNone, + ImGuiModNone = (int)NativeKey.ImGuiModNone, /// /// Identifies the ImGuiModCtrl presentation key or modifier. /// - ImGuiModCtrl = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModCtrl, + ImGuiModCtrl = (int)NativeKey.ImGuiModCtrl, /// /// Identifies the ImGuiModShift presentation key or modifier. /// - ImGuiModShift = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModShift, + ImGuiModShift = (int)NativeKey.ImGuiModShift, /// /// Identifies the ImGuiModAlt presentation key or modifier. /// - ImGuiModAlt = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModAlt, + ImGuiModAlt = (int)NativeKey.ImGuiModAlt, /// /// Identifies the ImGuiModSuper presentation key or modifier. /// - ImGuiModSuper = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModSuper, + ImGuiModSuper = (int)NativeKey.ImGuiModSuper, /// /// Identifies the ImGuiModMask presentation key or modifier. /// - ImGuiModMask = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModMask, + ImGuiModMask = (int)NativeKey.ImGuiModMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs index 5afa25489..a10723cab 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs @@ -1,6 +1,9 @@ using System; +using NativeMouseButton = Inno.Native.ImGui.ImGuiMouseButton; + namespace Inno.Editor.ImGui; + /// /// Defines the supported mouse button choices at the Editor presentation boundary. /// @@ -9,17 +12,17 @@ public enum ImGuiMouseButton : int /// /// Selects the left presentation behavior. /// - Left = (int)Inno.Native.ImGui.ImGuiMouseButton.Left, + Left = (int)NativeMouseButton.Left, /// /// Selects the right presentation behavior. /// - Right = (int)Inno.Native.ImGui.ImGuiMouseButton.Right, + Right = (int)NativeMouseButton.Right, /// /// Selects the middle presentation behavior. /// - Middle = (int)Inno.Native.ImGui.ImGuiMouseButton.Middle, + Middle = (int)NativeMouseButton.Middle, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseButton.Count, + Count = (int)NativeMouseButton.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs index 86180b833..76affeb48 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs @@ -1,6 +1,9 @@ using System; +using NativeMouseCursor = Inno.Native.ImGui.ImGuiMouseCursor; + namespace Inno.Editor.ImGui; + /// /// Defines the supported mouse cursor choices at the Editor presentation boundary. /// @@ -9,53 +12,53 @@ public enum ImGuiMouseCursor : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiMouseCursor.None, + None = (int)NativeMouseCursor.None, /// /// Selects the arrow presentation behavior. /// - Arrow = (int)Inno.Native.ImGui.ImGuiMouseCursor.Arrow, + Arrow = (int)NativeMouseCursor.Arrow, /// /// Selects the text input presentation behavior. /// - TextInput = (int)Inno.Native.ImGui.ImGuiMouseCursor.TextInput, + TextInput = (int)NativeMouseCursor.TextInput, /// /// Selects the resize all presentation behavior. /// - ResizeAll = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeAll, + ResizeAll = (int)NativeMouseCursor.ResizeAll, /// /// Selects the resize ns presentation behavior. /// - ResizeNs = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNs, + ResizeNs = (int)NativeMouseCursor.ResizeNs, /// /// Selects the resize ew presentation behavior. /// - ResizeEw = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeEw, + ResizeEw = (int)NativeMouseCursor.ResizeEw, /// /// Selects the resize nesw presentation behavior. /// - ResizeNesw = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNesw, + ResizeNesw = (int)NativeMouseCursor.ResizeNesw, /// /// Selects the resize nwse presentation behavior. /// - ResizeNwse = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNwse, + ResizeNwse = (int)NativeMouseCursor.ResizeNwse, /// /// Selects the hand presentation behavior. /// - Hand = (int)Inno.Native.ImGui.ImGuiMouseCursor.Hand, + Hand = (int)NativeMouseCursor.Hand, /// /// Selects the wait presentation behavior. /// - Wait = (int)Inno.Native.ImGui.ImGuiMouseCursor.Wait, + Wait = (int)NativeMouseCursor.Wait, /// /// Selects the progress presentation behavior. /// - Progress = (int)Inno.Native.ImGui.ImGuiMouseCursor.Progress, + Progress = (int)NativeMouseCursor.Progress, /// /// Selects the not allowed presentation behavior. /// - NotAllowed = (int)Inno.Native.ImGui.ImGuiMouseCursor.NotAllowed, + NotAllowed = (int)NativeMouseCursor.NotAllowed, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseCursor.Count, + Count = (int)NativeMouseCursor.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs index 017a77d2a..843b4e6f0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs @@ -1,6 +1,9 @@ using System; +using NativePopupFlags = Inno.Native.ImGui.ImGuiPopupFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported popup flags choices at the Editor presentation boundary. /// @@ -10,53 +13,53 @@ public enum ImGuiPopupFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiPopupFlags.None, + None = (int)NativePopupFlags.None, /// /// For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! /// - MouseButtonLeft = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonLeft, + MouseButtonLeft = (int)NativePopupFlags.MouseButtonLeft, /// /// For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) /// - MouseButtonRight = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonRight, + MouseButtonRight = (int)NativePopupFlags.MouseButtonRight, /// /// For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! /// - MouseButtonMiddle = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonMiddle, + MouseButtonMiddle = (int)NativePopupFlags.MouseButtonMiddle, /// /// For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) /// - NoReopen = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoReopen, + NoReopen = (int)NativePopupFlags.NoReopen, /// /// For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack /// - NoOpenOverExistingPopup = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoOpenOverExistingPopup, + NoOpenOverExistingPopup = (int)NativePopupFlags.NoOpenOverExistingPopup, /// /// For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space /// - NoOpenOverItems = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoOpenOverItems, + NoOpenOverItems = (int)NativePopupFlags.NoOpenOverItems, /// /// For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. /// - AnyPopupId = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopupId, + AnyPopupID = (int)NativePopupFlags.AnyPopupId, /// /// For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) /// - AnyPopupLevel = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopupLevel, + AnyPopupLevel = (int)NativePopupFlags.AnyPopupLevel, /// /// Selects the any popup presentation behavior. /// - AnyPopup = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopup, + AnyPopup = (int)NativePopupFlags.AnyPopup, /// /// Selects the mouse button shift presentation behavior. /// - MouseButtonShift = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonShift, + MouseButtonShift = (int)NativePopupFlags.MouseButtonShift, /// /// Selects the mouse button mask presentation behavior. /// - MouseButtonMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonMask, + MouseButtonMask = (int)NativePopupFlags.MouseButtonMask, /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.InvalidMask, + InvalidMask = (int)NativePopupFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs index e8ba440f5..a2adde01d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeSelectableFlags = Inno.Native.ImGui.ImGuiSelectableFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported selectable flags choices at the Editor presentation boundary. /// @@ -10,33 +13,33 @@ public enum ImGuiSelectableFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiSelectableFlags.None, + None = (int)NativeSelectableFlags.None, /// /// Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) /// - NoAutoClosePopups = (int)Inno.Native.ImGui.ImGuiSelectableFlags.NoAutoClosePopups, + NoAutoClosePopups = (int)NativeSelectableFlags.NoAutoClosePopups, /// /// Frame will span all columns of its container table (text will still fit in current column) /// - SpanAllColumns = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SpanAllColumns, + SpanAllColumns = (int)NativeSelectableFlags.SpanAllColumns, /// /// Generate press events on double clicks too /// - AllowDoubleClick = (int)Inno.Native.ImGui.ImGuiSelectableFlags.AllowDoubleClick, + AllowDoubleClick = (int)NativeSelectableFlags.AllowDoubleClick, /// /// Cannot be selected, display grayed out text /// - Disabled = (int)Inno.Native.ImGui.ImGuiSelectableFlags.Disabled, + Disabled = (int)NativeSelectableFlags.Disabled, /// /// (WIP) Hit testing to allow subsequent widgets to overlap this one /// - AllowOverlap = (int)Inno.Native.ImGui.ImGuiSelectableFlags.AllowOverlap, + AllowOverlap = (int)NativeSelectableFlags.AllowOverlap, /// /// Make the item be displayed as if it is hovered /// - Highlight = (int)Inno.Native.ImGui.ImGuiSelectableFlags.Highlight, + Highlight = (int)NativeSelectableFlags.Highlight, /// /// Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. /// - SelectOnNav = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SelectOnNav, + SelectOnNav = (int)NativeSelectableFlags.SelectOnNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs index 6eadc7060..7d52dfc5c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeSliderFlags = Inno.Native.ImGui.ImGuiSliderFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported slider flags choices at the Editor presentation boundary. /// @@ -10,45 +13,45 @@ public enum ImGuiSliderFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiSliderFlags.None, + None = (int)NativeSliderFlags.None, /// /// Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. /// - Logarithmic = (int)Inno.Native.ImGui.ImGuiSliderFlags.Logarithmic, + Logarithmic = (int)NativeSliderFlags.Logarithmic, /// /// Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). /// - NoRoundToFormat = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoRoundToFormat, + NoRoundToFormat = (int)NativeSliderFlags.NoRoundToFormat, /// /// Disable Ctrl+Click or Enter key allowing to input text directly into the widget. /// - NoInput = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoInput, + NoInput = (int)NativeSliderFlags.NoInput, /// /// Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. /// - WrapAround = (int)Inno.Native.ImGui.ImGuiSliderFlags.WrapAround, + WrapAround = (int)NativeSliderFlags.WrapAround, /// /// Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. /// - ClampOnInput = (int)Inno.Native.ImGui.ImGuiSliderFlags.ClampOnInput, + ClampOnInput = (int)NativeSliderFlags.ClampOnInput, /// /// Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. /// - ClampZeroRange = (int)Inno.Native.ImGui.ImGuiSliderFlags.ClampZeroRange, + ClampZeroRange = (int)NativeSliderFlags.ClampZeroRange, /// /// Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. /// - NoSpeedTweaks = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoSpeedTweaks, + NoSpeedTweaks = (int)NativeSliderFlags.NoSpeedTweaks, /// /// DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. /// - ColorMarkers = (int)Inno.Native.ImGui.ImGuiSliderFlags.ColorMarkers, + ColorMarkers = (int)NativeSliderFlags.ColorMarkers, /// /// Selects the always clamp presentation behavior. /// - AlwaysClamp = (int)Inno.Native.ImGui.ImGuiSliderFlags.AlwaysClamp, + AlwaysClamp = (int)NativeSliderFlags.AlwaysClamp, /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiSliderFlags.InvalidMask, + InvalidMask = (int)NativeSliderFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs index b61d56d6b..87b6ea40e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs @@ -1,6 +1,9 @@ using System; +using NativeStyleVar = Inno.Native.ImGui.ImGuiStyleVar; + namespace Inno.Editor.ImGui; + /// /// Defines the supported style var choices at the Editor presentation boundary. /// @@ -9,169 +12,169 @@ public enum ImGuiStyleVar : int /// /// Selects the alpha presentation behavior. /// - Alpha = (int)Inno.Native.ImGui.ImGuiStyleVar.Alpha, + Alpha = (int)NativeStyleVar.Alpha, /// /// Selects the disabled alpha presentation behavior. /// - DisabledAlpha = (int)Inno.Native.ImGui.ImGuiStyleVar.DisabledAlpha, + DisabledAlpha = (int)NativeStyleVar.DisabledAlpha, /// /// Selects the window padding presentation behavior. /// - WindowPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowPadding, + WindowPadding = (int)NativeStyleVar.WindowPadding, /// /// Selects the window rounding presentation behavior. /// - WindowRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowRounding, + WindowRounding = (int)NativeStyleVar.WindowRounding, /// /// Selects the window border size presentation behavior. /// - WindowBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowBorderSize, + WindowBorderSize = (int)NativeStyleVar.WindowBorderSize, /// /// Selects the window min size presentation behavior. /// - WindowMinSize = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowMinSize, + WindowMinSize = (int)NativeStyleVar.WindowMinSize, /// /// Selects the window title align presentation behavior. /// - WindowTitleAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowTitleAlign, + WindowTitleAlign = (int)NativeStyleVar.WindowTitleAlign, /// /// Selects the child rounding presentation behavior. /// - ChildRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ChildRounding, + ChildRounding = (int)NativeStyleVar.ChildRounding, /// /// Selects the child border size presentation behavior. /// - ChildBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ChildBorderSize, + ChildBorderSize = (int)NativeStyleVar.ChildBorderSize, /// /// Selects the popup rounding presentation behavior. /// - PopupRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.PopupRounding, + PopupRounding = (int)NativeStyleVar.PopupRounding, /// /// Selects the popup border size presentation behavior. /// - PopupBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.PopupBorderSize, + PopupBorderSize = (int)NativeStyleVar.PopupBorderSize, /// /// Selects the frame padding presentation behavior. /// - FramePadding = (int)Inno.Native.ImGui.ImGuiStyleVar.FramePadding, + FramePadding = (int)NativeStyleVar.FramePadding, /// /// Selects the frame rounding presentation behavior. /// - FrameRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.FrameRounding, + FrameRounding = (int)NativeStyleVar.FrameRounding, /// /// Selects the frame border size presentation behavior. /// - FrameBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.FrameBorderSize, + FrameBorderSize = (int)NativeStyleVar.FrameBorderSize, /// /// Selects the item spacing presentation behavior. /// - ItemSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.ItemSpacing, + ItemSpacing = (int)NativeStyleVar.ItemSpacing, /// /// Selects the item inner spacing presentation behavior. /// - ItemInnerSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.ItemInnerSpacing, + ItemInnerSpacing = (int)NativeStyleVar.ItemInnerSpacing, /// /// Selects the indent spacing presentation behavior. /// - IndentSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.IndentSpacing, + IndentSpacing = (int)NativeStyleVar.IndentSpacing, /// /// Selects the cell padding presentation behavior. /// - CellPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.CellPadding, + CellPadding = (int)NativeStyleVar.CellPadding, /// /// Selects the scrollbar size presentation behavior. /// - ScrollbarSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarSize, + ScrollbarSize = (int)NativeStyleVar.ScrollbarSize, /// /// Selects the scrollbar rounding presentation behavior. /// - ScrollbarRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarRounding, + ScrollbarRounding = (int)NativeStyleVar.ScrollbarRounding, /// /// Selects the scrollbar padding presentation behavior. /// - ScrollbarPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarPadding, + ScrollbarPadding = (int)NativeStyleVar.ScrollbarPadding, /// /// Selects the grab min size presentation behavior. /// - GrabMinSize = (int)Inno.Native.ImGui.ImGuiStyleVar.GrabMinSize, + GrabMinSize = (int)NativeStyleVar.GrabMinSize, /// /// Selects the grab rounding presentation behavior. /// - GrabRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.GrabRounding, + GrabRounding = (int)NativeStyleVar.GrabRounding, /// /// Selects the image rounding presentation behavior. /// - ImageRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ImageRounding, + ImageRounding = (int)NativeStyleVar.ImageRounding, /// /// Selects the image border size presentation behavior. /// - ImageBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ImageBorderSize, + ImageBorderSize = (int)NativeStyleVar.ImageBorderSize, /// /// Selects the tab rounding presentation behavior. /// - TabRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.TabRounding, + TabRounding = (int)NativeStyleVar.TabRounding, /// /// Selects the tab border size presentation behavior. /// - TabBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBorderSize, + TabBorderSize = (int)NativeStyleVar.TabBorderSize, /// /// Selects the tab min width base presentation behavior. /// - TabMinWidthBase = (int)Inno.Native.ImGui.ImGuiStyleVar.TabMinWidthBase, + TabMinWidthBase = (int)NativeStyleVar.TabMinWidthBase, /// /// Selects the tab min width shrink presentation behavior. /// - TabMinWidthShrink = (int)Inno.Native.ImGui.ImGuiStyleVar.TabMinWidthShrink, + TabMinWidthShrink = (int)NativeStyleVar.TabMinWidthShrink, /// /// Selects the tab bar border size presentation behavior. /// - TabBarBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBarBorderSize, + TabBarBorderSize = (int)NativeStyleVar.TabBarBorderSize, /// /// Selects the tab bar overline size presentation behavior. /// - TabBarOverlineSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBarOverlineSize, + TabBarOverlineSize = (int)NativeStyleVar.TabBarOverlineSize, /// /// Selects the table angled headers angle presentation behavior. /// - TableAngledHeadersAngle = (int)Inno.Native.ImGui.ImGuiStyleVar.TableAngledHeadersAngle, + TableAngledHeadersAngle = (int)NativeStyleVar.TableAngledHeadersAngle, /// /// Selects the table angled headers text align presentation behavior. /// - TableAngledHeadersTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.TableAngledHeadersTextAlign, + TableAngledHeadersTextAlign = (int)NativeStyleVar.TableAngledHeadersTextAlign, /// /// Selects the tree lines size presentation behavior. /// - TreeLinesSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TreeLinesSize, + TreeLinesSize = (int)NativeStyleVar.TreeLinesSize, /// /// Selects the tree lines rounding presentation behavior. /// - TreeLinesRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.TreeLinesRounding, + TreeLinesRounding = (int)NativeStyleVar.TreeLinesRounding, /// /// Selects the button text align presentation behavior. /// - ButtonTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.ButtonTextAlign, + ButtonTextAlign = (int)NativeStyleVar.ButtonTextAlign, /// /// Selects the selectable text align presentation behavior. /// - SelectableTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.SelectableTextAlign, + SelectableTextAlign = (int)NativeStyleVar.SelectableTextAlign, /// /// Selects the separator text border size presentation behavior. /// - SeparatorTextBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextBorderSize, + SeparatorTextBorderSize = (int)NativeStyleVar.SeparatorTextBorderSize, /// /// Selects the separator text align presentation behavior. /// - SeparatorTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextAlign, + SeparatorTextAlign = (int)NativeStyleVar.SeparatorTextAlign, /// /// Selects the separator text padding presentation behavior. /// - SeparatorTextPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextPadding, + SeparatorTextPadding = (int)NativeStyleVar.SeparatorTextPadding, /// /// Selects the docking separator size presentation behavior. /// - DockingSeparatorSize = (int)Inno.Native.ImGui.ImGuiStyleVar.DockingSeparatorSize, + DockingSeparatorSize = (int)NativeStyleVar.DockingSeparatorSize, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiStyleVar.Count, + Count = (int)NativeStyleVar.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs index 0664d4257..88b52b3f6 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTabBarFlags = Inno.Native.ImGui.ImGuiTabBarFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported tab bar flags choices at the Editor presentation boundary. /// @@ -10,53 +13,53 @@ public enum ImGuiTabBarFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTabBarFlags.None, + None = (int)NativeTabBarFlags.None, /// /// Allow manually dragging tabs to re-order them + New tabs are appended at the end of list /// - Reorderable = (int)Inno.Native.ImGui.ImGuiTabBarFlags.Reorderable, + Reorderable = (int)NativeTabBarFlags.Reorderable, /// /// Automatically select new tabs when they appear /// - AutoSelectNewTabs = (int)Inno.Native.ImGui.ImGuiTabBarFlags.AutoSelectNewTabs, + AutoSelectNewTabs = (int)NativeTabBarFlags.AutoSelectNewTabs, /// /// Disable buttons to open the tab list popup /// - TabListPopupButton = (int)Inno.Native.ImGui.ImGuiTabBarFlags.TabListPopupButton, + TabListPopupButton = (int)NativeTabBarFlags.TabListPopupButton, /// /// Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() & & IsMouseClicked(2)) *p_open = false. /// - NoCloseWithMiddleMouseButton = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoCloseWithMiddleMouseButton, + NoCloseWithMiddleMouseButton = (int)NativeTabBarFlags.NoCloseWithMiddleMouseButton, /// /// Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) /// - NoTabListScrollingButtons = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoTabListScrollingButtons, + NoTabListScrollingButtons = (int)NativeTabBarFlags.NoTabListScrollingButtons, /// /// Disable tooltips when hovering a tab /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoTooltip, + NoTooltip = (int)NativeTabBarFlags.NoTooltip, /// /// Draw selected overline markers over selected tab /// - DrawSelectedOverline = (int)Inno.Native.ImGui.ImGuiTabBarFlags.DrawSelectedOverline, + DrawSelectedOverline = (int)NativeTabBarFlags.DrawSelectedOverline, /// /// Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling buttons. /// - FittingPolicyMixed = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyMixed, + FittingPolicyMixed = (int)NativeTabBarFlags.FittingPolicyMixed, /// /// Shrink down tabs when they don't fit /// - FittingPolicyShrink = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyShrink, + FittingPolicyShrink = (int)NativeTabBarFlags.FittingPolicyShrink, /// /// Enable scrolling buttons when tabs don't fit /// - FittingPolicyScroll = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyScroll, + FittingPolicyScroll = (int)NativeTabBarFlags.FittingPolicyScroll, /// /// Selects the fitting policy mask presentation behavior. /// - FittingPolicyMask = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyMask, + FittingPolicyMask = (int)NativeTabBarFlags.FittingPolicyMask, /// /// Selects the fitting policy default presentation behavior. /// - FittingPolicyDefault = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyDefault, + FittingPolicyDefault = (int)NativeTabBarFlags.FittingPolicyDefault } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs index 58d858b6b..0f2cc4ecf 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTabItemFlags = Inno.Native.ImGui.ImGuiTabItemFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported tab item flags choices at the Editor presentation boundary. /// @@ -10,41 +13,41 @@ public enum ImGuiTabItemFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTabItemFlags.None, + None = (int)NativeTabItemFlags.None, /// /// Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. /// - UnsavedDocument = (int)Inno.Native.ImGui.ImGuiTabItemFlags.UnsavedDocument, + UnsavedDocument = (int)NativeTabItemFlags.UnsavedDocument, /// /// Trigger flag to programmatically make the tab selected when calling BeginTabItem() /// - SetSelected = (int)Inno.Native.ImGui.ImGuiTabItemFlags.SetSelected, + SetSelected = (int)NativeTabItemFlags.SetSelected, /// /// Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() & & IsMouseClicked(2)) *p_open = false. /// - NoCloseWithMiddleMouseButton = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoCloseWithMiddleMouseButton, + NoCloseWithMiddleMouseButton = (int)NativeTabItemFlags.NoCloseWithMiddleMouseButton, /// /// Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() /// - NoPushId = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoPushId, + NoPushID = (int)NativeTabItemFlags.NoPushId, /// /// Disable tooltip for the given tab /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoTooltip, + NoTooltip = (int)NativeTabItemFlags.NoTooltip, /// /// Disable reordering this tab or having another tab cross over this tab /// - NoReorder = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoReorder, + NoReorder = (int)NativeTabItemFlags.NoReorder, /// /// Enforce the tab position to the left of the tab bar (after the tab list popup button) /// - Leading = (int)Inno.Native.ImGui.ImGuiTabItemFlags.Leading, + Leading = (int)NativeTabItemFlags.Leading, /// /// Enforce the tab position to the right of the tab bar (before the scrolling buttons) /// - Trailing = (int)Inno.Native.ImGui.ImGuiTabItemFlags.Trailing, + Trailing = (int)NativeTabItemFlags.Trailing, /// /// Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. /// - NoAssumedClosure = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoAssumedClosure, + NoAssumedClosure = (int)NativeTabItemFlags.NoAssumedClosure } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs index db6dbba57..1852ec27a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs @@ -1,6 +1,9 @@ using System; +using NativeTableBgTarget = Inno.Native.ImGui.ImGuiTableBgTarget; + namespace Inno.Editor.ImGui; + /// /// Defines the supported table bg target choices at the Editor presentation boundary. /// @@ -9,17 +12,17 @@ public enum ImGuiTableBgTarget : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableBgTarget.None, + None = (int)NativeTableBgTarget.None, /// /// Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) /// - RowBg0 = (int)Inno.Native.ImGui.ImGuiTableBgTarget.RowBg0, + RowBg0 = (int)NativeTableBgTarget.RowBg0, /// /// Set row background color 1 (generally used for selection marking) /// - RowBg1 = (int)Inno.Native.ImGui.ImGuiTableBgTarget.RowBg1, + RowBg1 = (int)NativeTableBgTarget.RowBg1, /// /// Set cell background color (top-most color) /// - CellBg = (int)Inno.Native.ImGui.ImGuiTableBgTarget.CellBg, + CellBg = (int)NativeTableBgTarget.CellBg } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs index 99b9b6ec3..578e6f21e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTableColumnFlags = Inno.Native.ImGui.ImGuiTableColumnFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported table column flags choices at the Editor presentation boundary. /// @@ -10,113 +13,113 @@ public enum ImGuiTableColumnFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.None, + None = (int)NativeTableColumnFlags.None, /// /// Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) /// - Disabled = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.Disabled, + Disabled = (int)NativeTableColumnFlags.Disabled, /// /// Default as a hidden/disabled column. /// - DefaultHide = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.DefaultHide, + DefaultHide = (int)NativeTableColumnFlags.DefaultHide, /// /// Default as a sorting column. /// - DefaultSort = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.DefaultSort, + DefaultSort = (int)NativeTableColumnFlags.DefaultSort, /// /// Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). /// - WidthStretch = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthStretch, + WidthStretch = (int)NativeTableColumnFlags.WidthStretch, /// /// Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). /// - WidthFixed = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthFixed, + WidthFixed = (int)NativeTableColumnFlags.WidthFixed, /// /// Disable manual resizing. /// - NoResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoResize, + NoResize = (int)NativeTableColumnFlags.NoResize, /// /// Disable manual reordering this column, this will also prevent other columns from crossing over this column. /// - NoReorder = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoReorder, + NoReorder = (int)NativeTableColumnFlags.NoReorder, /// /// Disable ability to hide/disable this column. /// - NoHide = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHide, + NoHide = (int)NativeTableColumnFlags.NoHide, /// /// Disable clipping for this column (all NoClip columns will render in a same draw command). /// - NoClip = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoClip, + NoClip = (int)NativeTableColumnFlags.NoClip, /// /// Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). /// - NoSort = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSort, + NoSort = (int)NativeTableColumnFlags.NoSort, /// /// Disable ability to sort in the ascending direction. /// - NoSortAscending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSortAscending, + NoSortAscending = (int)NativeTableColumnFlags.NoSortAscending, /// /// Disable ability to sort in the descending direction. /// - NoSortDescending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSortDescending, + NoSortDescending = (int)NativeTableColumnFlags.NoSortDescending, /// /// TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. /// - NoHeaderLabel = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHeaderLabel, + NoHeaderLabel = (int)NativeTableColumnFlags.NoHeaderLabel, /// /// Disable header text width contribution to automatic column width. /// - NoHeaderWidth = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHeaderWidth, + NoHeaderWidth = (int)NativeTableColumnFlags.NoHeaderWidth, /// /// Make the initial sort direction Ascending when first sorting on this column (default). /// - PreferSortAscending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.PreferSortAscending, + PreferSortAscending = (int)NativeTableColumnFlags.PreferSortAscending, /// /// Make the initial sort direction Descending when first sorting on this column. /// - PreferSortDescending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.PreferSortDescending, + PreferSortDescending = (int)NativeTableColumnFlags.PreferSortDescending, /// /// Use current Indent value when entering cell (default for column 0). /// - IndentEnable = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentEnable, + IndentEnable = (int)NativeTableColumnFlags.IndentEnable, /// /// Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. /// - IndentDisable = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentDisable, + IndentDisable = (int)NativeTableColumnFlags.IndentDisable, /// /// TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. /// - AngledHeader = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.AngledHeader, + AngledHeader = (int)NativeTableColumnFlags.AngledHeader, /// /// Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. /// - IsEnabled = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsEnabled, + IsEnabled = (int)NativeTableColumnFlags.IsEnabled, /// /// Status: is visible == is enabled AND not clipped by scrolling. /// - IsVisible = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsVisible, + IsVisible = (int)NativeTableColumnFlags.IsVisible, /// /// Status: is currently part of the sort specs /// - IsSorted = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsSorted, + IsSorted = (int)NativeTableColumnFlags.IsSorted, /// /// Status: is hovered by mouse /// - IsHovered = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsHovered, + IsHovered = (int)NativeTableColumnFlags.IsHovered, /// /// Selects the width mask presentation behavior. /// - WidthMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthMask, + WidthMask = (int)NativeTableColumnFlags.WidthMask, /// /// Selects the indent mask presentation behavior. /// - IndentMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentMask, + IndentMask = (int)NativeTableColumnFlags.IndentMask, /// /// Selects the status mask presentation behavior. /// - StatusMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.StatusMask, + StatusMask = (int)NativeTableColumnFlags.StatusMask, /// /// Selects the no direct resize presentation behavior. /// - NoDirectResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoDirectResize, + NoDirectResize = (int)NativeTableColumnFlags.NoDirectResize } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs index e483ba5fa..7450453a1 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTableFlags = Inno.Native.ImGui.ImGuiTableFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported table flags choices at the Editor presentation boundary. /// @@ -10,149 +13,149 @@ public enum ImGuiTableFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableFlags.None, + None = (int)NativeTableFlags.None, /// /// Enable resizing columns. /// - Resizable = (int)Inno.Native.ImGui.ImGuiTableFlags.Resizable, + Resizable = (int)NativeTableFlags.Resizable, /// /// Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) /// - Reorderable = (int)Inno.Native.ImGui.ImGuiTableFlags.Reorderable, + Reorderable = (int)NativeTableFlags.Reorderable, /// /// Enable hiding/disabling columns in context menu. /// - Hideable = (int)Inno.Native.ImGui.ImGuiTableFlags.Hideable, + Hideable = (int)NativeTableFlags.Hideable, /// /// Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. /// - Sortable = (int)Inno.Native.ImGui.ImGuiTableFlags.Sortable, + Sortable = (int)NativeTableFlags.Sortable, /// /// Disable persisting columns order, width, visibility and sort settings in the .ini file. /// - NoSavedSettings = (int)Inno.Native.ImGui.ImGuiTableFlags.NoSavedSettings, + NoSavedSettings = (int)NativeTableFlags.NoSavedSettings, /// /// Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). /// - ContextMenuInBody = (int)Inno.Native.ImGui.ImGuiTableFlags.ContextMenuInBody, + ContextMenuInBody = (int)NativeTableFlags.ContextMenuInBody, /// /// Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) /// - RowBg = (int)Inno.Native.ImGui.ImGuiTableFlags.RowBg, + RowBg = (int)NativeTableFlags.RowBg, /// /// Draw horizontal borders between rows. /// - BordersInnerH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInnerH, + BordersInnerH = (int)NativeTableFlags.BordersInnerH, /// /// Draw horizontal borders at the top and bottom. /// - BordersOuterH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuterH, + BordersOuterH = (int)NativeTableFlags.BordersOuterH, /// /// Draw vertical borders between columns. /// - BordersInnerV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInnerV, + BordersInnerV = (int)NativeTableFlags.BordersInnerV, /// /// Draw vertical borders on the left and right sides. /// - BordersOuterV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuterV, + BordersOuterV = (int)NativeTableFlags.BordersOuterV, /// /// Draw horizontal borders. /// - BordersH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersH, + BordersH = (int)NativeTableFlags.BordersH, /// /// Draw vertical borders. /// - BordersV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersV, + BordersV = (int)NativeTableFlags.BordersV, /// /// Draw inner borders. /// - BordersInner = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInner, + BordersInner = (int)NativeTableFlags.BordersInner, /// /// Draw outer borders. /// - BordersOuter = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuter, + BordersOuter = (int)NativeTableFlags.BordersOuter, /// /// Draw all borders. /// - Borders = (int)Inno.Native.ImGui.ImGuiTableFlags.Borders, + Borders = (int)NativeTableFlags.Borders, /// /// Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style /// - NoBordersInBody = (int)Inno.Native.ImGui.ImGuiTableFlags.NoBordersInBody, + NoBordersInBody = (int)NativeTableFlags.NoBordersInBody, /// /// Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style /// - NoBordersInBodyUntilResize = (int)Inno.Native.ImGui.ImGuiTableFlags.NoBordersInBodyUntilResize, + NoBordersInBodyUntilResize = (int)NativeTableFlags.NoBordersInBodyUntilResize, /// /// Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. /// - SizingFixedFit = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingFixedFit, + SizingFixedFit = (int)NativeTableFlags.SizingFixedFit, /// /// Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. /// - SizingFixedSame = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingFixedSame, + SizingFixedSame = (int)NativeTableFlags.SizingFixedSame, /// /// Columns default to _WidthStretch with default weights proportional to each columns contents widths. /// - SizingStretchProp = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingStretchProp, + SizingStretchProp = (int)NativeTableFlags.SizingStretchProp, /// /// Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). /// - SizingStretchSame = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingStretchSame, + SizingStretchSame = (int)NativeTableFlags.SizingStretchSame, /// /// Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. /// - NoHostExtendX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoHostExtendX, + NoHostExtendX = (int)NativeTableFlags.NoHostExtendX, /// /// Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. /// - NoHostExtendY = (int)Inno.Native.ImGui.ImGuiTableFlags.NoHostExtendY, + NoHostExtendY = (int)NativeTableFlags.NoHostExtendY, /// /// Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. /// - NoKeepColumnsVisible = (int)Inno.Native.ImGui.ImGuiTableFlags.NoKeepColumnsVisible, + NoKeepColumnsVisible = (int)NativeTableFlags.NoKeepColumnsVisible, /// /// Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. /// - PreciseWidths = (int)Inno.Native.ImGui.ImGuiTableFlags.PreciseWidths, + PreciseWidths = (int)NativeTableFlags.PreciseWidths, /// /// Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). /// - NoClip = (int)Inno.Native.ImGui.ImGuiTableFlags.NoClip, + NoClip = (int)NativeTableFlags.NoClip, /// /// Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. /// - PadOuterX = (int)Inno.Native.ImGui.ImGuiTableFlags.PadOuterX, + PadOuterX = (int)NativeTableFlags.PadOuterX, /// /// Default if BordersOuterV is off. Disable outermost padding. /// - NoPadOuterX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoPadOuterX, + NoPadOuterX = (int)NativeTableFlags.NoPadOuterX, /// /// Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). /// - NoPadInnerX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoPadInnerX, + NoPadInnerX = (int)NativeTableFlags.NoPadInnerX, /// /// Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. /// - ScrollX = (int)Inno.Native.ImGui.ImGuiTableFlags.ScrollX, + ScrollX = (int)NativeTableFlags.ScrollX, /// /// Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. /// - ScrollY = (int)Inno.Native.ImGui.ImGuiTableFlags.ScrollY, + ScrollY = (int)NativeTableFlags.ScrollY, /// /// Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). /// - SortMulti = (int)Inno.Native.ImGui.ImGuiTableFlags.SortMulti, + SortMulti = (int)NativeTableFlags.SortMulti, /// /// Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). /// - SortTristate = (int)Inno.Native.ImGui.ImGuiTableFlags.SortTristate, + SortTristate = (int)NativeTableFlags.SortTristate, /// /// Highlight column headers when hovered (may evolve into a fuller highlight) /// - HighlightHoveredColumn = (int)Inno.Native.ImGui.ImGuiTableFlags.HighlightHoveredColumn, + HighlightHoveredColumn = (int)NativeTableFlags.HighlightHoveredColumn, /// /// Selects the sizing mask presentation behavior. /// - SizingMask = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingMask, + SizingMask = (int)NativeTableFlags.SizingMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs index c664e0e69..7769dc082 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTableRowFlags = Inno.Native.ImGui.ImGuiTableRowFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported table row flags choices at the Editor presentation boundary. /// @@ -10,9 +13,9 @@ public enum ImGuiTableRowFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableRowFlags.None, + None = (int)NativeTableRowFlags.None, /// /// Identify header row (set default background color + width of its contents accounted differently for auto column width) /// - Headers = (int)Inno.Native.ImGui.ImGuiTableRowFlags.Headers, + Headers = (int)NativeTableRowFlags.Headers } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs index 2179ce729..2af5dc80c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeTreeNodeFlags = Inno.Native.ImGui.ImGuiTreeNodeFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported tree node flags choices at the Editor presentation boundary. /// @@ -10,89 +13,89 @@ public enum ImGuiTreeNodeFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.None, + None = (int)NativeTreeNodeFlags.None, /// /// Draw as selected /// - Selected = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Selected, + Selected = (int)NativeTreeNodeFlags.Selected, /// /// Draw frame with background (e.g. for CollapsingHeader) /// - Framed = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Framed, + Framed = (int)NativeTreeNodeFlags.Framed, /// /// Hit testing to allow subsequent widgets to overlap this one /// - AllowOverlap = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.AllowOverlap, + AllowOverlap = (int)NativeTreeNodeFlags.AllowOverlap, /// /// Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack /// - NoTreePushOnOpen = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NoTreePushOnOpen, + NoTreePushOnOpen = (int)NativeTreeNodeFlags.NoTreePushOnOpen, /// /// Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) /// - NoAutoOpenOnLog = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NoAutoOpenOnLog, + NoAutoOpenOnLog = (int)NativeTreeNodeFlags.NoAutoOpenOnLog, /// /// Default node to be open /// - DefaultOpen = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DefaultOpen, + DefaultOpen = (int)NativeTreeNodeFlags.DefaultOpen, /// /// Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. /// - OpenOnDoubleClick = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.OpenOnDoubleClick, + OpenOnDoubleClick = (int)NativeTreeNodeFlags.OpenOnDoubleClick, /// /// Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. /// - OpenOnArrow = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.OpenOnArrow, + OpenOnArrow = (int)NativeTreeNodeFlags.OpenOnArrow, /// /// No collapsing, no arrow (use as a convenience for leaf nodes). /// - Leaf = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Leaf, + Leaf = (int)NativeTreeNodeFlags.Leaf, /// /// Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! /// - Bullet = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Bullet, + Bullet = (int)NativeTreeNodeFlags.Bullet, /// /// Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. /// - FramePadding = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.FramePadding, + FramePadding = (int)NativeTreeNodeFlags.FramePadding, /// /// Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. /// - SpanAvailWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanAvailWidth, + SpanAvailWidth = (int)NativeTreeNodeFlags.SpanAvailWidth, /// /// Extend hit box to the left-most and right-most edges (cover the indent area). /// - SpanFullWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanFullWidth, + SpanFullWidth = (int)NativeTreeNodeFlags.SpanFullWidth, /// /// Narrow hit box + narrow hovering highlight, will only cover the label text. /// - SpanLabelWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanLabelWidth, + SpanLabelWidth = (int)NativeTreeNodeFlags.SpanLabelWidth, /// /// Frame will span all columns of its container table (label will still fit in current column) /// - SpanAllColumns = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanAllColumns, + SpanAllColumns = (int)NativeTreeNodeFlags.SpanAllColumns, /// /// Label will span all columns of its container table /// - LabelSpanAllColumns = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.LabelSpanAllColumns, + LabelSpanAllColumns = (int)NativeTreeNodeFlags.LabelSpanAllColumns, /// /// Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. /// - NavLeftJumpsToParent = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NavLeftJumpsToParent, + NavLeftJumpsToParent = (int)NativeTreeNodeFlags.NavLeftJumpsToParent, /// /// Selects the collapsing header presentation behavior. /// - CollapsingHeader = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.CollapsingHeader, + CollapsingHeader = (int)NativeTreeNodeFlags.CollapsingHeader, /// /// No lines drawn /// - DrawLinesNone = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesNone, + DrawLinesNone = (int)NativeTreeNodeFlags.DrawLinesNone, /// /// Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). /// - DrawLinesFull = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesFull, + DrawLinesFull = (int)NativeTreeNodeFlags.DrawLinesFull, /// /// Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). /// - DrawLinesToNodes = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesToNodes, + DrawLinesToNodes = (int)NativeTreeNodeFlags.DrawLinesToNodes } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs index 4fc22b7c6..74c3fdf89 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs @@ -1,6 +1,9 @@ using System; +using NativeWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; + namespace Inno.Editor.ImGui; + /// /// Defines the supported window flags choices at the Editor presentation boundary. /// @@ -10,121 +13,121 @@ public enum ImGuiWindowFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiWindowFlags.None, + None = (int)NativeWindowFlags.None, /// /// Disable title-bar /// - NoTitleBar = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoTitleBar, + NoTitleBar = (int)NativeWindowFlags.NoTitleBar, /// /// Disable user resizing with the lower-right grip /// - NoResize = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoResize, + NoResize = (int)NativeWindowFlags.NoResize, /// /// Disable user moving the window /// - NoMove = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoMove, + NoMove = (int)NativeWindowFlags.NoMove, /// /// Disable scrollbars (window can still scroll with mouse or programmatically) /// - NoScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoScrollbar, + NoScrollbar = (int)NativeWindowFlags.NoScrollbar, /// /// Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. /// - NoScrollWithMouse = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoScrollWithMouse, + NoScrollWithMouse = (int)NativeWindowFlags.NoScrollWithMouse, /// /// Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). /// - NoCollapse = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoCollapse, + NoCollapse = (int)NativeWindowFlags.NoCollapse, /// /// Resize every window to its content every frame /// - AlwaysAutoResize = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysAutoResize, + AlwaysAutoResize = (int)NativeWindowFlags.AlwaysAutoResize, /// /// Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). /// - NoBackground = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoBackground, + NoBackground = (int)NativeWindowFlags.NoBackground, /// /// Never load/save settings in .ini file /// - NoSavedSettings = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoSavedSettings, + NoSavedSettings = (int)NativeWindowFlags.NoSavedSettings, /// /// Disable catching mouse, hovering test with pass through. /// - NoMouseInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoMouseInputs, + NoMouseInputs = (int)NativeWindowFlags.NoMouseInputs, /// /// Has a menu-bar /// - MenuBar = (int)Inno.Native.ImGui.ImGuiWindowFlags.MenuBar, + MenuBar = (int)NativeWindowFlags.MenuBar, /// /// Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. /// - HorizontalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.HorizontalScrollbar, + HorizontalScrollbar = (int)NativeWindowFlags.HorizontalScrollbar, /// /// Disable taking focus when transitioning from hidden to visible state /// - NoFocusOnAppearing = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoFocusOnAppearing, + NoFocusOnAppearing = (int)NativeWindowFlags.NoFocusOnAppearing, /// /// Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) /// - NoBringToFrontOnFocus = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoBringToFrontOnFocus, + NoBringToFrontOnFocus = (int)NativeWindowFlags.NoBringToFrontOnFocus, /// /// Always show vertical scrollbar (even if ContentSize.y < Size.y) /// - AlwaysVerticalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysVerticalScrollbar, + AlwaysVerticalScrollbar = (int)NativeWindowFlags.AlwaysVerticalScrollbar, /// /// Always show horizontal scrollbar (even if ContentSize.x < Size.x) /// - AlwaysHorizontalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysHorizontalScrollbar, + AlwaysHorizontalScrollbar = (int)NativeWindowFlags.AlwaysHorizontalScrollbar, /// /// No keyboard/gamepad navigation within the window /// - NoNavInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNavInputs, + NoNavInputs = (int)NativeWindowFlags.NoNavInputs, /// /// No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) /// - NoNavFocus = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNavFocus, + NoNavFocus = (int)NativeWindowFlags.NoNavFocus, /// /// Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. /// - UnsavedDocument = (int)Inno.Native.ImGui.ImGuiWindowFlags.UnsavedDocument, + UnsavedDocument = (int)NativeWindowFlags.UnsavedDocument, /// /// Disable docking of this window /// - NoDocking = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoDocking, + NoDocking = (int)NativeWindowFlags.NoDocking, /// /// Selects the no nav presentation behavior. /// - NoNav = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNav, + NoNav = (int)NativeWindowFlags.NoNav, /// /// Selects the no decoration presentation behavior. /// - NoDecoration = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoDecoration, + NoDecoration = (int)NativeWindowFlags.NoDecoration, /// /// Selects the no inputs presentation behavior. /// - NoInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoInputs, + NoInputs = (int)NativeWindowFlags.NoInputs, /// /// Don't use! For internal use by Begin()/NewFrame() /// - DockNodeHost = (int)Inno.Native.ImGui.ImGuiWindowFlags.DockNodeHost, + DockNodeHost = (int)NativeWindowFlags.DockNodeHost, /// /// Don't use! For internal use by BeginChild() /// - ChildWindow = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildWindow, + ChildWindow = (int)NativeWindowFlags.ChildWindow, /// /// Don't use! For internal use by BeginTooltip() /// - Tooltip = (int)Inno.Native.ImGui.ImGuiWindowFlags.Tooltip, + Tooltip = (int)NativeWindowFlags.Tooltip, /// /// Don't use! For internal use by BeginPopup() /// - Popup = (int)Inno.Native.ImGui.ImGuiWindowFlags.Popup, + Popup = (int)NativeWindowFlags.Popup, /// /// Don't use! For internal use by BeginPopupModal() /// - Modal = (int)Inno.Native.ImGui.ImGuiWindowFlags.Modal, + Modal = (int)NativeWindowFlags.Modal, /// /// Don't use! For internal use by BeginMenu() /// - ChildMenu = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildMenu, + ChildMenu = (int)NativeWindowFlags.ChildMenu } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs index 8ba5a9a2a..64e000dbf 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs @@ -2,18 +2,21 @@ using System.Numerics; using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// A pointer-free drawing borrow valid only in its original window, UI session and frame. /// public readonly unsafe struct EditorDrawList { - private readonly EditorUiSession m_session; + private readonly EditorUISession m_session; private readonly int m_frame; private readonly uint m_window; - internal EditorDrawList(EditorUiSession session) + + internal EditorDrawList(EditorUISession session) { ImGuiNativeContext* context = session.RequireDrawingFrame(); m_session = session; @@ -42,6 +45,7 @@ public void Line( uint color, float thickness = 1f ) => ImGui.DrawNativeLine(Resolve(), start, end, color, thickness); + /// /// Adds a filled rectangular surface. /// @@ -66,7 +70,15 @@ public void FilledRectangle( uint color, float rounding = 0f, bool topCornersOnly = false - ) => ImGui.DrawNativeFilledRectangle(Resolve(), minimum, maximum, color, rounding, topCornersOnly ? (int)ImDrawFlags.RoundCornersTop : 0); + ) => ImGui.DrawNativeFilledRectangle( + Resolve(), + minimum, + maximum, + color, + rounding, + topCornersOnly ? (int)ImDrawFlags.RoundCornersTop : 0 + ); + /// /// Adds a rectangular outline. /// @@ -92,6 +104,7 @@ public void Rectangle( float rounding = 0f, float thickness = 1f ) => ImGui.DrawNativeRectangle(Resolve(), minimum, maximum, color, rounding, 0, thickness); + /// /// Adds a filled circle with backend-selected tessellation. /// @@ -139,7 +152,17 @@ public void Text( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(scale); ImVec2C native = ImGui.ToNative(position); using NativeStringLease encoded = Utf8Codec.EncodeNullTerminated(text, allowsNull: false); - NativeImGui.Raw.AddText(draw, NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize() * scale, &native, color, (sbyte*)encoded.pointer, null, 0f, null); + NativeImGui.Raw.AddText( + draw, + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize() * scale, + &native, + color, + (sbyte*)encoded.pointer, + null, + 0f, + null + ); } /// @@ -159,7 +182,8 @@ public void PushClip( Vector2 maximum, bool intersect = true ) { - ImVec2C first = ImGui.ToNative(minimum), last = ImGui.ToNative(maximum); + ImVec2C first = ImGui.ToNative(minimum); + ImVec2C last = ImGui.ToNative(maximum); NativeImGui.Raw.PushClipRect(Resolve(), &first, &last, intersect ? (byte)1 : (byte)0); } @@ -167,6 +191,7 @@ public void PushClip( /// Restores the enclosing clip after a matching PushClip. /// public void PopClip() => NativeImGui.Raw.PopClipRect(Resolve()); + /// /// Begins ordered draw channels within this window. /// @@ -186,17 +211,23 @@ public void SplitChannels(int count) /// The zero-based channel. /// public void SetChannel(int index) => NativeImGui.Raw.ChannelsSetCurrent(Resolve(), index); + /// /// Merges the current split back into ordered draw commands. /// public void MergeChannels() => NativeImGui.Raw.ChannelsMerge(Resolve()); + private ImDrawList* Resolve() { if (m_session is null) + { throw new InvalidOperationException("A default drawing borrow has no owner."); + } ImGuiNativeContext* context = m_session.RequireDrawingFrame(); if (context->FrameCount != m_frame || context->CurrentWindow->ID != m_window) + { throw new InvalidOperationException("The drawing borrow belongs to a different window or frame."); + } return NativeImGui.Raw.GetWindowDrawList(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs index 85cc436ef..118c1e70b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs @@ -1,7 +1,12 @@ +using System; using System.Numerics; +using BGCS.Runtime; +using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies presentation values and creates frame-bounded drawing borrows. /// @@ -13,10 +18,10 @@ public static unsafe partial class ImGui /// /// Value metrics valid independently from the native style pointer. /// - public static EditorUiLayout GetLayout() + public static EditorUILayout GetLayout() { - EditorUiSession.current.EnsureDrawing(); - return new EditorUiLayout(NativeImGui.Raw.GetStyle()); + EditorUISession.current.EnsureDrawing(); + return new EditorUILayout(NativeImGui.Raw.GetStyle()); } /// @@ -25,10 +30,10 @@ public static EditorUiLayout GetLayout() /// /// A neutral value snapshot; no pointer or callback is retained. /// - public static EditorUiInput GetInput() + public static EditorUIInput GetInput() { - EditorUiSession.current.EnsureDrawing(); - return new EditorUiInput(NativeImGui.Raw.GetIO()); + EditorUISession.current.EnsureDrawing(); + return new EditorUIInput(NativeImGui.Raw.GetIO()); } /// @@ -42,7 +47,7 @@ public static EditorUiInput GetInput() /// public static Vector4 GetStyleColorValue(ImGuiCol color) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return FromNative(NativeImGui.Raw.GetStyle()->Colors[(int)color]); } @@ -54,8 +59,8 @@ public static Vector4 GetStyleColorValue(ImGuiCol color) /// public static (uint id, Vector2 position) GetViewport() { - EditorUiSession.current.EnsureDrawing(); - var viewport = NativeImGui.Raw.GetWindowViewport(); + EditorUISession.current.EnsureDrawing(); + ImGuiViewport* viewport = NativeImGui.Raw.GetWindowViewport(); return (viewport->ID, FromNative(viewport->Pos)); } @@ -70,10 +75,12 @@ public static (uint id, Vector2 position) GetViewport() /// public static (float minimumX, float maximumX, float rowMinimum, float rowMaximum) GetTableBounds() { - _ = EditorUiSession.current.RequireDrawingFrame(); - var table = NativeImGui.Raw.GetCurrentTable(); + _ = EditorUISession.current.RequireDrawingFrame(); + ImGuiTable* table = NativeImGui.Raw.GetCurrentTable(); if (table is null) - throw new System.InvalidOperationException("A table row layout requires an active table."); + { + throw new InvalidOperationException("A table row layout requires an active table."); + } return (table->OuterRect.Min.X, table->OuterRect.Max.X, table->RowPosY1, table->RowPosY2); } @@ -88,8 +95,8 @@ public static (float minimumX, float maximumX, float rowMinimum, float rowMaximu /// public static (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padding) GetWindowBounds() { - _ = EditorUiSession.current.RequireDrawingFrame(); - var window = NativeImGui.Raw.GetCurrentWindow(); + _ = EditorUISession.current.RequireDrawingFrame(); + ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); return (window->InnerRect.Min.X, window->InnerRect.Max.X, FromNative(window->WorkRect.Max), FromNative(window->WindowPadding)); } @@ -104,8 +111,8 @@ public static (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padd /// public static (Vector2 minimum, Vector2 maximum) GetClipBounds() { - _ = EditorUiSession.current.RequireDrawingFrame(); - var clip = NativeImGui.Raw.GetCurrentWindow()->ClipRect; + _ = EditorUISession.current.RequireDrawingFrame(); + ImRect clip = NativeImGui.Raw.GetCurrentWindow()->ClipRect; return (FromNative(clip.Min), FromNative(clip.Max)); } @@ -115,7 +122,8 @@ public static (Vector2 minimum, Vector2 maximum) GetClipBounds() /// /// A value that rejects use after a window, frame, context or session change. /// - public static EditorDrawList GetDrawList() => new(EditorUiSession.current); + public static EditorDrawList GetDrawList() => new(EditorUISession.current); + /// /// Checks the active payload's logical protocol without exposing its native buffer. /// @@ -127,11 +135,13 @@ public static (Vector2 minimum, Vector2 maximum) GetClipBounds() /// public static bool HasDragPayload(string protocol) { - EditorUiSession.current.EnsureDrawing(); - var payload = NativeImGui.Raw.GetDragDropPayload(); + EditorUISession.current.EnsureDrawing(); + ImGuiPayload* payload = NativeImGui.Raw.GetDragDropPayload(); if (payload is null) + { return false; - using var text = BGCS.Runtime.Utf8Codec.EncodeNullTerminated(protocol, allowsNull: false); + } + using NativeStringLease text = Utf8Codec.EncodeNullTerminated(protocol, allowsNull: false); return NativeImGui.Raw.IsDataType(payload, (sbyte*)text.pointer) != 0; } @@ -151,7 +161,7 @@ public static Vector2 MeasureText( string text, float scale ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return NativeImGui.CalcTextSize(text) * scale; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs index 781a6a53c..197cb9d26 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs @@ -2,9 +2,11 @@ using System.Numerics; using BGCS.Runtime; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Exposes a script-safe, pointer-free subset of Dear ImGui for custom Editor tools. /// Every call is valid only while an Editor drawing callback is active. @@ -19,7 +21,7 @@ public static unsafe partial class ImGui /// public static void Text(string text) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TextUnformatted(text); } @@ -39,22 +41,22 @@ public static bool Button( string label, Vector2 size = default ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.Button(label, size); } /// /// Draws a compact button. /// - /// - /// when the button is activated. - /// /// /// The visible label and optional ImGui identity suffix. /// + /// + /// when the button is activated. + /// public static bool SmallButton(string label) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.SmallButton(label); } @@ -64,17 +66,17 @@ public static bool SmallButton(string label) /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The checked state, updated when the user toggles the control. /// + /// + /// when the value changes. + /// public static bool Checkbox( string label, ref bool value ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.Checkbox(label, ref value); } @@ -150,9 +152,6 @@ public static bool InputTextWithHint( /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The integer displayed by the control and replaced after an accepted edit. /// @@ -165,6 +164,9 @@ public static bool InputTextWithHint( /// /// Text editing options for the numeric field. /// + /// + /// when the value changes. + /// public static bool InputInt( string label, ref int value, @@ -172,7 +174,7 @@ public static bool InputInt( int fastStep = 100, ImGuiInputTextFlags flags = ImGuiInputTextFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.InputInt(label, ref value, step, fastStep, (int)flags); } @@ -182,17 +184,17 @@ public static bool InputInt( /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The number displayed with three fractional digits and replaced after an accepted edit. /// + /// + /// when the value changes. + /// public static bool InputFloat( string label, ref float value ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.InputFloat(label, ref value, 0f, 0f, "%.3f", 0); } @@ -224,7 +226,7 @@ public static bool DragFloat( float minimum = 0f, float maximum = 0f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.DragFloat(label, ref value, speed, minimum, maximum); } @@ -256,7 +258,7 @@ public static bool SliderFloat( float maximum, ImGuiSliderFlags flags = ImGuiSliderFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.SliderFloat(label, ref value, minimum, maximum, (int)flags); } @@ -311,11 +313,15 @@ public static bool ColorEditLinear4( ImGuiColorEditFlags flags = ImGuiColorEditFlags.None ) { if ((flags & ImGuiColorEditFlags.InputHsv) != 0) + { throw new ArgumentException("Linear RGBA editing requires RGB input storage.", nameof(flags)); - Vector4 display = new(LinearToSrgb(value.X), LinearToSrgb(value.Y), LinearToSrgb(value.Z), value.W); + } + var display = new Vector4(LinearToSrgb(value.X), LinearToSrgb(value.Y), LinearToSrgb(value.Z), value.W); Vector4 original = display; if (!ColorEdit4(label, ref display, flags | ImGuiColorEditFlags.InputRgb)) + { return false; + } value = new Vector4( display.X == original.X ? value.X : SrgbToLinear(display.X), display.Y == original.Y ? value.Y : SrgbToLinear(display.Y), @@ -337,19 +343,19 @@ public static bool ColorEditLinear4( /// /// Child-region behavior. /// - /// - /// when child contents should be submitted. - /// /// /// Scroll and window policies for the child. /// + /// + /// when child contents should be submitted. + /// public static bool BeginChild( string id, Vector2 size = default, ImGuiChildFlags flags = ImGuiChildFlags.None, ImGuiWindowFlags windowFlags = ImGuiWindowFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.BeginChild(id, size, (int)flags, (int)windowFlags); } @@ -358,7 +364,7 @@ public static bool BeginChild( /// public static void EndChild() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndChild(); } @@ -377,12 +383,12 @@ public static void EndChild() /// /// The requested outer size. /// - /// - /// when table contents should be submitted. - /// /// /// Optional inner scrolling width; zero uses the outer size. /// + /// + /// when table contents should be submitted. + /// public static bool BeginTable( string id, int columns, @@ -390,7 +396,7 @@ public static bool BeginTable( Vector2 size = default, float innerWidth = 0f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.BeginTable(id, columns, (int)flags, size, innerWidth); } @@ -399,7 +405,7 @@ public static bool BeginTable( /// public static void EndTable() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndTable(); } @@ -420,7 +426,7 @@ public static void TableSetupColumn( ImGuiTableColumnFlags flags = ImGuiTableColumnFlags.None, float widthOrWeight = 0f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TableSetupColumn(label, (int)(flags), widthOrWeight); } @@ -429,7 +435,7 @@ public static void TableSetupColumn( /// public static void TableHeadersRow() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TableHeadersRow(); } @@ -446,7 +452,7 @@ public static void TableNextRow( ImGuiTableRowFlags flags = ImGuiTableRowFlags.None, float minimumHeight = 0f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TableNextRow((int)flags, minimumHeight); } @@ -458,7 +464,7 @@ public static void TableNextRow( /// public static bool TableNextColumn() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.TableNextColumn(); } @@ -482,7 +488,7 @@ public static bool BeginCombo( string preview, ImGuiComboFlags flags = ImGuiComboFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.BeginCombo(label, preview, (int)(flags)); } @@ -491,7 +497,7 @@ public static bool BeginCombo( /// public static void EndCombo() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndCombo(); } @@ -507,19 +513,19 @@ public static void EndCombo() /// /// Selectable behavior. /// - /// - /// when the item is activated. - /// /// /// The interaction bounds, or zero for the ordinary content size. /// + /// + /// when the item is activated. + /// public static bool Selectable( string label, bool selected = false, ImGuiSelectableFlags flags = ImGuiSelectableFlags.None, Vector2 size = default ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.Selectable(label, selected, (int)flags, size); } @@ -539,7 +545,7 @@ public static bool CollapsingHeader( string label, ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.CollapsingHeader(label, (int)(flags)); } @@ -559,7 +565,7 @@ public static bool TreeNode( string label, ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.TreeNodeEx(label, (int)(flags)); } @@ -568,7 +574,7 @@ public static bool TreeNode( /// public static void TreePop() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.TreePop(); } @@ -588,7 +594,7 @@ public static bool BeginTabBar( string id, ImGuiTabBarFlags flags = ImGuiTabBarFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.BeginTabBar(id, (int)(flags)); } @@ -597,7 +603,7 @@ public static bool BeginTabBar( /// public static void EndTabBar() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndTabBar(); } @@ -640,16 +646,14 @@ public static unsafe bool BeginTabItem( string label, ref bool isOpen, ImGuiTabItemFlags flags = ImGuiTabItemFlags.None - ) { - return RawImGui.BeginTabItem(label, ref isOpen, (int)flags); - } + ) => RawImGui.BeginTabItem(label, ref isOpen, (int)flags); /// /// Ends the current tab item. /// public static void EndTabItem() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndTabItem(); } @@ -666,7 +670,7 @@ public static void OpenPopup( string id, ImGuiPopupFlags flags = ImGuiPopupFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.OpenPopup(id, (int)(flags)); } @@ -686,7 +690,7 @@ public static bool BeginPopup( string id, ImGuiWindowFlags flags = ImGuiWindowFlags.None ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.BeginPopup(id, (int)(flags)); } @@ -695,7 +699,7 @@ public static bool BeginPopup( /// public static void EndPopup() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndPopup(); } @@ -704,7 +708,7 @@ public static void EndPopup() /// public static void CloseCurrentPopup() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.CloseCurrentPopup(); } @@ -719,8 +723,8 @@ public static void CloseCurrentPopup() /// public static bool IsAnyPopupOpen() { - EditorUiSession.current.EnsureDrawing(); - return RawImGui.IsPopupOpen(string.Empty, (int)(ImGuiPopupFlags.AnyPopupId | ImGuiPopupFlags.AnyPopupLevel)); + EditorUISession.current.EnsureDrawing(); + return RawImGui.IsPopupOpen(string.Empty, (int)(ImGuiPopupFlags.AnyPopupID | ImGuiPopupFlags.AnyPopupLevel)); } /// @@ -731,7 +735,7 @@ public static bool IsAnyPopupOpen() /// public static void BeginDisabled(bool disabled = true) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.BeginDisabled(disabled); } @@ -740,7 +744,7 @@ public static void BeginDisabled(bool disabled = true) /// public static void EndDisabled() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndDisabled(); } @@ -749,7 +753,7 @@ public static void EndDisabled() /// public static void BeginGroup() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.BeginGroup(); } @@ -758,7 +762,7 @@ public static void BeginGroup() /// public static void EndGroup() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.EndGroup(); } @@ -768,9 +772,9 @@ public static void EndGroup() /// /// The stable identity used to locate the requested value. /// - public static void PushId(string id) + public static void PushID(string id) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushID(id); } @@ -780,18 +784,18 @@ public static void PushId(string id) /// /// The stable identity used to locate the requested value. /// - public static void PushId(int id) + public static void PushID(int id) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushID(id); } /// /// Pops one identity from the ImGui ID stack. /// - public static void PopId() + public static void PopID() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PopID(); } @@ -808,7 +812,7 @@ public static void PushStyleColor( ImGuiCol color, Vector4 value ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushStyleColor((int)(color), value); } @@ -820,7 +824,7 @@ Vector4 value /// public static void PopStyleColor(int count = 1) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PopStyleColor(count); } @@ -837,7 +841,7 @@ public static void PushStyleVar( ImGuiStyleVar style, float value ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushStyleVar((int)(style), value); } @@ -854,7 +858,7 @@ public static void PushStyleVar( ImGuiStyleVar style, Vector2 value ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PushStyleVar((int)(style), value); } @@ -866,7 +870,7 @@ Vector2 value /// public static void PopStyleVar(int count = 1) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.PopStyleVar(count); } @@ -883,7 +887,7 @@ public static void SameLine( float offset = 0f, float spacing = -1f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SameLine(offset, spacing); } @@ -892,7 +896,7 @@ public static void SameLine( /// public static void Separator() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.Separator(); } @@ -904,7 +908,7 @@ public static void Separator() /// public static void SeparatorText(string label) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SeparatorText(label); } @@ -913,7 +917,7 @@ public static void SeparatorText(string label) /// public static void Spacing() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.Spacing(); } @@ -925,7 +929,7 @@ public static void Spacing() /// public static void Dummy(Vector2 size) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.Dummy(size); } @@ -937,7 +941,7 @@ public static void Dummy(Vector2 size) /// public static void SetNextItemWidth(float width) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetNextItemWidth(width); } @@ -949,7 +953,7 @@ public static void SetNextItemWidth(float width) /// public static void FocusNextItem() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetKeyboardFocusHere(); } @@ -961,7 +965,7 @@ public static void FocusNextItem() /// public static Vector2 GetContentRegionAvailable() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetContentRegionAvail(); } @@ -973,7 +977,7 @@ public static Vector2 GetContentRegionAvailable() /// public static Vector2 GetCursorPosition() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetCursorPos(); } @@ -985,7 +989,7 @@ public static Vector2 GetCursorPosition() /// public static void SetCursorPosition(Vector2 position) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); RawImGui.SetCursorPos(position); } @@ -997,7 +1001,7 @@ public static void SetCursorPosition(Vector2 position) /// public static Vector2 GetCursorScreenPosition() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetCursorScreenPos(); } @@ -1009,7 +1013,7 @@ public static Vector2 GetCursorScreenPosition() /// public static Vector2 GetItemMinimum() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetItemRectMin(); } @@ -1021,22 +1025,22 @@ public static Vector2 GetItemMinimum() /// public static Vector2 GetItemMaximum() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetItemRectMax(); } /// /// Measures text using the current font. /// - /// - /// The measured width and height. - /// /// /// The text text validated by the measure text operation. /// + /// + /// The measured width and height. + /// public static Vector2 MeasureText(string text) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.CalcTextSize(text); } @@ -1074,10 +1078,12 @@ public static Vector2 MeasureWrappedText( string text, float wrapWidth ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); ArgumentNullException.ThrowIfNull(text); if (!float.IsFinite(wrapWidth) || wrapWidth <= 0f) + { throw new ArgumentOutOfRangeException(nameof(wrapWidth)); + } return ImGuiUtf8Buffer.MeasureText(text, wrapWidth); } @@ -1092,7 +1098,7 @@ float wrapWidth /// public static bool IsItemHovered(ImGuiHoveredFlags flags = ImGuiHoveredFlags.None) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsItemHovered((int)(flags)); } @@ -1104,7 +1110,7 @@ public static bool IsItemHovered(ImGuiHoveredFlags flags = ImGuiHoveredFlags.Non /// public static bool IsItemActive() { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsItemActive(); } @@ -1119,7 +1125,7 @@ public static bool IsItemActive() /// public static bool IsItemClicked(ImGuiMouseButton button = ImGuiMouseButton.Left) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsItemClicked((int)(button)); } @@ -1134,7 +1140,7 @@ public static bool IsItemClicked(ImGuiMouseButton button = ImGuiMouseButton.Left /// public static bool IsMouseButtonDown(ImGuiMouseButton button = ImGuiMouseButton.Left) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.IsMouseDown((int)button); } @@ -1155,22 +1161,22 @@ public static Vector2 GetMouseDragDelta( ImGuiMouseButton button = ImGuiMouseButton.Left, float threshold = -1f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return RawImGui.GetMouseDragDelta((int)button, threshold); } /// /// Converts a floating-point RGBA color to Dear ImGui packed color order. /// - /// - /// The packed color value. - /// /// /// The color consumed by to packed color; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The packed color value. + /// public static uint ToPackedColor(Vector4 color) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return Channel(color.X) | Channel(color.Y) << 8 | Channel(color.Z) << 16 | Channel(color.W) << 24; static uint Channel(float value) => unchecked((uint)float.ConvertToIntegerNative(Math.Clamp(value, 0f, 1f) * 255f + 0.5f)); @@ -1197,7 +1203,7 @@ public static void DrawLine( uint color, float thickness = 1f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); ImGui.DrawNativeLine(RawImGui.Raw.GetWindowDrawList(), start, end, color, thickness); } @@ -1226,7 +1232,7 @@ public static void DrawRectangle( float rounding = 0f, float thickness = 1f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); ImGui.DrawNativeRectangle(RawImGui.Raw.GetWindowDrawList(), minimum, maximum, color, rounding, 0, thickness); } @@ -1251,7 +1257,7 @@ public static void DrawFilledRectangle( uint color, float rounding = 0f ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); ImGui.DrawNativeFilledRectangle(RawImGui.Raw.GetWindowDrawList(), minimum, maximum, color, rounding, 0); } @@ -1284,8 +1290,11 @@ public static void DrawCubicCurve( uint color, float thickness = 1f ) { - EditorUiSession.current.EnsureDrawing(); - ImVec2C a = ToNative(start), b = ToNative(firstControl), c = ToNative(secondControl), d = ToNative(end); + EditorUISession.current.EnsureDrawing(); + ImVec2C a = ToNative(start); + ImVec2C b = ToNative(firstControl); + ImVec2C c = ToNative(secondControl); + ImVec2C d = ToNative(end); RawImGui.Raw.AddBezierCubic(RawImGui.Raw.GetWindowDrawList(), &a, &b, &c, &d, color, thickness, 0); } @@ -1306,24 +1315,30 @@ public static void DrawText( uint color, string text ) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); ImGui.DrawNativeText(RawImGui.Raw.GetWindowDrawList(), position, color, text); } - internal static ImVec2C ToNative(Vector2 value) => new() + internal static ImVec2C ToNative(Vector2 value) + => new() { X = value.X, Y = value.Y }; - internal static ImVec4C ToNative(Vector4 value) => new() + + internal static ImVec4C ToNative(Vector4 value) + => new() { X = value.X, Y = value.Y, Z = value.Z, W = value.W }; + internal static Vector2 FromNative(ImVec2C value) => new(value.X, value.Y); + internal static Vector4 FromNative(ImVec4C value) => new(value.X, value.Y, value.Z, value.W); + internal static void DrawNativeLine( ImDrawList* drawList, Vector2 start, @@ -1446,10 +1461,12 @@ internal static bool BeginNativeWindow( bool modal ) { using NativeStringLease nativeLabel = Utf8Codec.EncodeNullTerminated(label, allowsNull: false); - return (modal ? RawImGui.Raw.BeginPopupModal((sbyte*)nativeLabel.pointer, null, (int)flags) : RawImGui.Raw.Begin((sbyte*)nativeLabel.pointer, null, (int)flags)) != 0; + return (modal + ? RawImGui.Raw.BeginPopupModal((sbyte*)nativeLabel.pointer, null, (int)flags) + : RawImGui.Raw.Begin((sbyte*)nativeLabel.pointer, null, (int)flags)) != 0; } - internal static uint HashNativeId( + internal static uint HashNativeID( string text, uint seed = 0 ) { @@ -1458,5 +1475,6 @@ internal static uint HashNativeId( } private static float LinearToSrgb(float value) => value <= 0.0031308f ? value * 12.92f : 1.055f * MathF.Pow(value, 1f / 2.4f) - 0.055f; + private static float SrgbToLinear(float value) => value <= 0.04045f ? value / 12.92f : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIds.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIDs.cs similarity index 70% rename from src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIds.cs rename to src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIDs.cs index 300040545..b38f70c66 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIds.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGuiInteractionIDs.cs @@ -1,6 +1,6 @@ namespace Inno.Editor.ImGui; -internal static class ImGuiInteractionIds +internal static class ImGuiInteractionIDs { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs index 69a33c42f..9864f30da 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs @@ -1,15 +1,16 @@ -using Inno.Scripting.Api; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Scripting.Api; + using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; [assembly: ScriptingApiNamespace("InnoEditor.ImGui", "Inno.Editor.ImGui", ScriptingApiScope.Editor)] [assembly: ScriptingApiNamespace("InnoEditor.ImGui", "Inno.Editor.ImGui.ImGuiWidget", ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorUiSession), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorUISession), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorPalette), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorStyleMetrics), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(ListNavigationResult), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(Inno.Editor.ImGui.ImGui), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(ImGui), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorWidget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(InlineRenameResult), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(TreeNodeDrawContext), ScriptingApiScope.Editor)] @@ -34,8 +35,8 @@ [assembly: ScriptingApiExport(typeof(ImGuiTreeNodeFlags), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(ImGuiWindowFlags), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorDrawList), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorUiLayout), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(EditorUiInput), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorUILayout), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(EditorUIInput), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(TransformGizmoOperation), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(TransformGizmoSpace), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(TransformGizmoOptions), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs index b6cfab1b8..95246561f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs @@ -1,17 +1,19 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Globalization; using Inno.Core.Identity; using Inno.Editor.Interactions; -using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; namespace Inno.Editor.ImGui; + /// /// Bridges managed editor drag sessions to the native ImGui payload API. /// public static class EditorDragDropRenderer { private const string C_IDENTITY_PAYLOAD_PREFIX = "INNO_ID_"; + /// /// Publishes managed drag data for the most recently submitted ImGui item. /// @@ -33,7 +35,11 @@ public static bool Source( Action? drawPreview = null ) { ArgumentNullException.ThrowIfNull(data); - return EditorUI.current.widgets.DragDropSource(GetPayloadType(data.sourceIdentity.domainId), () => interaction.BeginDrag(data).runtimeId, drawPreview); + return EditorUI.current.widgets.DragDropSource( + GetPayloadType(data.sourceIdentity.domainID), + () => interaction.BeginDrag(data).runtimeID, + drawPreview + ); } /// @@ -53,62 +59,29 @@ public static EditorDropWidgetResult Target( EditorDropPlacement placement = EditorDropPlacement.None ) { if (!interaction.TryGetActiveDragIdentity(out RuntimeIdentity activeIdentity)) + { return EditorDropWidgetResult.none; - bool delivered = EditorUI.current.widgets.DragDropTarget(GetPayloadType(activeIdentity.domainId), out int runtimeId, out bool isPreviewing, drawDefaultHighlight: false); + } + bool delivered = EditorUI.current.widgets.DragDropTarget( + GetPayloadType(activeIdentity.domainID), + out int runtimeID, + out bool isPreviewing, + drawDefaultHighlight: false + ); if (!isPreviewing && !delivered) + { return EditorDropWidgetResult.none; - if (runtimeId <= 0) + } + if (runtimeID <= 0) + { return EditorDropWidgetResult.none; - var identity = new RuntimeIdentity(activeIdentity.domainId, runtimeId); + } + var identity = new RuntimeIdentity(activeIdentity.domainID, runtimeID); EditorDropStatus status = interaction.QueryDrop(identity, placement); EditorDropResult result = delivered && status.canDrop ? interaction.Drop(identity, placement) : EditorDropResult.rejected; return new EditorDropWidgetResult(isPreviewing, status, result); } - private static string GetPayloadType(IdentityDomainId domainId) => C_IDENTITY_PAYLOAD_PREFIX + domainId.value.ToString("X8", CultureInfo.InvariantCulture); -} - -/// -/// Reports the preview and delivery state of an ImGui editor drop target. -/// -public readonly record struct EditorDropWidgetResult -{ - /// - /// Creates a combined native-preview and managed-drop result. - /// - /// - /// Whether a compatible native payload is currently hovering the target. - /// - /// - /// The compatibility and visual state returned by the managed drop router. - /// - /// - /// The result produced when the payload was delivered. - /// - public EditorDropWidgetResult( - bool isPreviewing, - EditorDropStatus status, - EditorDropResult result - ) { - this.isPreviewing = isPreviewing; - this.status = status; - this.result = result; - } - - /// - /// Gets whether a compatible native payload is hovering the target. - /// - public bool isPreviewing { get; } - /// - /// Gets the managed drop compatibility status. - /// - public EditorDropStatus status { get; } - /// - /// Gets the delivered drop result. - /// - public EditorDropResult result { get; } - /// - /// Gets an inactive drop target result. - /// - public static EditorDropWidgetResult none => new(false, EditorDropStatus.rejected, EditorDropResult.rejected); + private static string GetPayloadType(IdentityDomainID domainID) + => C_IDENTITY_PAYLOAD_PREFIX + domainID.value.ToString("X8", CultureInfo.InvariantCulture); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs new file mode 100644 index 000000000..7d06ce308 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs @@ -0,0 +1,51 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.ImGui; + +/// +/// Reports the preview and delivery state of an ImGui editor drop target. +/// +public readonly record struct EditorDropWidgetResult +{ + /// + /// Creates a combined native-preview and managed-drop result. + /// + /// + /// Whether a compatible native payload is currently hovering the target. + /// + /// + /// The compatibility and visual state returned by the managed drop router. + /// + /// + /// The result produced when the payload was delivered. + /// + public EditorDropWidgetResult( + bool isPreviewing, + EditorDropStatus status, + EditorDropResult result + ) { + this.isPreviewing = isPreviewing; + this.status = status; + this.result = result; + } + + /// + /// Gets whether a compatible native payload is hovering the target. + /// + public bool isPreviewing { get; } + + /// + /// Gets the managed drop compatibility status. + /// + public EditorDropStatus status { get; } + + /// + /// Gets the delivered drop result. + /// + public EditorDropResult result { get; } + + /// + /// Gets an inactive drop target result. + /// + public static EditorDropWidgetResult none => new(false, EditorDropStatus.rejected, EditorDropResult.rejected); +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs index 73fbc687e..3c98a3ce1 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Numerics; - using Inno.Core.Events; using Inno.Core.Input; @@ -16,8 +15,8 @@ public sealed class EditorGameInputCapture private readonly HashSet m_pressedButtons = []; private Vector2 m_origin; private Vector2 m_size; - private uint m_targetWindowId; - private uint m_deliveredWindowId; + private uint m_targetWindowID; + private uint m_deliveredWindowID; private bool m_reported; private bool m_focused; private bool m_hovered; @@ -34,7 +33,8 @@ public sealed class EditorGameInputCapture /// public EditorGameInputCapture(Func resolveWindow) { - m_resolveWindow = resolveWindow ?? throw new ArgumentNullException(nameof(resolveWindow)); + ArgumentNullException.ThrowIfNull(resolveWindow); + m_resolveWindow = resolveWindow; } /// @@ -45,7 +45,7 @@ public EditorGameInputCapture(Func resolveWindow) /// /// Reports the Game View image in coordinates local to its platform window. /// - /// + /// /// The presentation viewport containing the Game View. /// /// @@ -64,17 +64,17 @@ public EditorGameInputCapture(Func resolveWindow) /// when the Game View and its platform window both own focus. /// public bool Report( - uint viewportId, + uint viewportID, Vector2 origin, Vector2 size, bool focused, bool hovered ) { m_reported = true; - m_targetWindowId = m_resolveWindow(viewportId) ?? 0; + m_targetWindowID = m_resolveWindow(viewportID) ?? 0; m_origin = origin; m_size = size; - m_focused = focused && m_targetWindowId != 0; + m_focused = focused && m_targetWindowID != 0; m_hovered = hovered && m_focused; m_pointerInside = m_hovered; return m_focused; @@ -90,20 +90,22 @@ public uint CompleteFrame() { if (!m_reported) { - m_targetWindowId = 0; + m_targetWindowID = 0; m_focused = false; m_hovered = false; m_pointerInside = false; } - if (m_deliveredWindowId == 0 - || m_focused && m_deliveredWindowId == m_targetWindowId) + if (m_deliveredWindowID == 0 + || m_focused && m_deliveredWindowID == m_targetWindowID + ) { return 0; + } - uint formerWindowId = m_deliveredWindowId; - m_deliveredWindowId = 0; + uint formerWindowID = m_deliveredWindowID; + m_deliveredWindowID = 0; m_pressedButtons.Clear(); - return formerWindowId; + return formerWindowID; } /// @@ -115,116 +117,121 @@ public uint CompleteFrame() /// /// A routed event or a synthetic focus reset, or null when the Game View must not receive input. /// + /// + /// Thrown when the event is null. + /// /// /// A globally consumed key, button, focus or close release is not replayed to the game. /// It returns a new focus-reset event so previously held input is released before simulation. /// Consumed pointer movement still updates hit-test bounds without reaching the game backend. /// - /// - /// Thrown when the event is null. - /// public Event? Route(Event evnt) { ArgumentNullException.ThrowIfNull(evnt); - if (evnt is MouseMovedEvent observed && observed.windowId == m_targetWindowId) + if (evnt is MouseMovedEvent observed && observed.windowID == m_targetWindowID) + { UpdatePointerBounds(observed); + } if (evnt.isGlobalHandled) { - if (m_deliveredWindowId != 0 && IsReleaseFromWindow(evnt, m_deliveredWindowId) - || IsWindowExit(evnt, m_targetWindowId)) - { - uint formerWindowId = m_deliveredWindowId; + if (m_deliveredWindowID != 0 && IsReleaseFromWindow(evnt, m_deliveredWindowID) + || IsWindowExit(evnt, m_targetWindowID) + ) { + uint formerWindowID = m_deliveredWindowID; ReleaseCapture(); - return formerWindowId != 0 ? new WindowFocusChangedEvent(formerWindowId, false) : null; + return formerWindowID != 0 ? new WindowFocusChangedEvent(formerWindowID, false) : null; } return null; } if (evnt is WindowFocusChangedEvent { isFocused: false } lostFocus - && (lostFocus.windowId == m_deliveredWindowId || lostFocus.windowId == m_targetWindowId)) - { - bool needsReset = m_deliveredWindowId != 0; + && (lostFocus.windowID == m_deliveredWindowID || lostFocus.windowID == m_targetWindowID) + ) { + bool needsReset = m_deliveredWindowID != 0; ReleaseCapture(); return needsReset ? lostFocus : null; } if (evnt is WindowCloseEvent closed - && (closed.windowId == m_deliveredWindowId || closed.windowId == m_targetWindowId)) - { - bool needsReset = m_deliveredWindowId != 0; + && (closed.windowID == m_deliveredWindowID || closed.windowID == m_targetWindowID) + ) { + bool needsReset = m_deliveredWindowID != 0; ReleaseCapture(); - return needsReset ? new WindowFocusChangedEvent(closed.windowId, false) : null; + return needsReset ? new WindowFocusChangedEvent(closed.windowID, false) : null; } - if (!m_focused || m_targetWindowId == 0) + if (!m_focused || m_targetWindowID == 0) + { return null; + } Event? routed = evnt switch { - KeyEvent key when key.windowId == m_targetWindowId => key, - TextInputEvent text when text.windowId == m_targetWindowId => text, - MouseMovedEvent moved when moved.windowId == m_targetWindowId => RouteMove(moved), - MouseButtonPressedEvent pressed when pressed.windowId == m_targetWindowId => RoutePress(pressed), - MouseButtonReleasedEvent released when released.windowId == m_targetWindowId => RouteRelease(released), - MouseScrolledEvent scrolled when scrolled.windowId == m_targetWindowId && m_pointerInside => scrolled, + KeyEvent key when key.windowID == m_targetWindowID => key, + TextInputEvent text when text.windowID == m_targetWindowID => text, + MouseMovedEvent moved when moved.windowID == m_targetWindowID => RouteMove(moved), + MouseButtonPressedEvent pressed when pressed.windowID == m_targetWindowID => RoutePress(pressed), + MouseButtonReleasedEvent released when released.windowID == m_targetWindowID => RouteRelease(released), + MouseScrolledEvent scrolled when scrolled.windowID == m_targetWindowID && m_pointerInside => scrolled, _ => null }; if (routed is not null) - m_deliveredWindowId = m_targetWindowId; + { + m_deliveredWindowID = m_targetWindowID; + } return routed; } private void ReleaseCapture() { - m_deliveredWindowId = 0; + m_deliveredWindowID = 0; m_pressedButtons.Clear(); m_focused = false; m_hovered = false; m_pointerInside = false; } - private static bool IsReleaseFromWindow( - Event evnt, - uint windowId - ) => evnt switch - { - KeyReleasedEvent key => key.windowId == windowId, - MouseButtonReleasedEvent button => button.windowId == windowId, - _ => IsWindowExit(evnt, windowId) - }; - - private static bool IsWindowExit( - Event evnt, - uint windowId - ) => evnt switch - { - WindowFocusChangedEvent { isFocused: false } focus => focus.windowId == windowId, - WindowCloseEvent close => close.windowId == windowId, - _ => false - }; - private Event? RouteMove(MouseMovedEvent moved) { - Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); + var local = new Vector2(moved.x - m_origin.X, moved.y - m_origin.Y); return m_pointerInside || m_pressedButtons.Count > 0 - ? moved.WithPosition(local.X, local.Y) - : null; + ? moved.WithPosition(local.X, local.Y) + : null; } private void UpdatePointerBounds(MouseMovedEvent moved) { - Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); + var local = new Vector2(moved.x - m_origin.X, moved.y - m_origin.Y); m_pointerInside = m_hovered && local.X >= 0f && local.Y >= 0f - && local.X < m_size.X && local.Y < m_size.Y; + && local.X < m_size.X && local.Y < m_size.Y; } private Event? RoutePress(MouseButtonPressedEvent pressed) { if (!m_pointerInside) + { return null; + } m_pressedButtons.Add(pressed.button); return pressed; } - private Event? RouteRelease(MouseButtonReleasedEvent released) + private Event? RouteRelease(MouseButtonReleasedEvent released) => m_pressedButtons.Remove(released.button) ? released : null; + + private static bool IsReleaseFromWindow( + Event evnt, + uint windowID + ) => evnt switch + { + KeyReleasedEvent key => key.windowID == windowID, + MouseButtonReleasedEvent button => button.windowID == windowID, + _ => IsWindowExit(evnt, windowID) + }; + + private static bool IsWindowExit( + Event evnt, + uint windowID + ) => evnt switch { - return m_pressedButtons.Remove(released.button) ? released : null; - } + WindowFocusChangedEvent { isFocused: false } focus => focus.windowID == windowID, + WindowCloseEvent close => close.windowID == windowID, + _ => false + }; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs index bf661b25f..e5da58400 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs @@ -1,33 +1,30 @@ -using System.Linq; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; +using System.Linq; using System.Numerics; -using Inno.Editor.Interactions; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeMouseButton = Inno.Native.ImGui.ImGuiMouseButton; namespace Inno.Editor.ImGui; + /// /// Renders immutable editor menu models through ImGui. /// public sealed unsafe class EditorMenuRenderer { - private readonly EditorUiSession m_session; - private readonly Dictionary<(string Owner, uint Popup), string> m_contextSearches = []; - internal EditorMenuRenderer(EditorUiSession session) => m_session = session; - internal void RetireOwner(string owner) + private readonly EditorUISession m_session; + private readonly Dictionary<(string owner, uint popup), string> m_contextSearches = []; + + internal EditorMenuRenderer(EditorUISession session) { - foreach (var key in m_contextSearches.Keys.Where(value => value.Owner == owner).ToArray()) - m_contextSearches.Remove(key); + m_session = session; } - internal void Clear() => m_contextSearches.Clear(); - private readonly record struct MenuSection( - EditorInteraction interaction, - IReadOnlyList items - ); /// /// Draws a resolved right-click menu for the most recently submitted ImGui item. /// @@ -46,21 +43,25 @@ EditorInteraction interaction ) { m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); - uint popupId = NativeImGui.GetID(id); + uint popupID = NativeImGui.GetID(id); if (!ShouldResolveItemContextMenu(id)) { - m_contextSearches.Remove((m_session.owner, popupId)); + m_contextSearches.Remove((m_session.owner, popupID)); return false; } EditorMenuModel menu = interaction.BuildMenu(); if (menu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginContextMenu(id)) + { return false; + } try { - DrawContextMenuContents(popupId, [new MenuSection(interaction, menu.items)]); + DrawContextMenuContents(popupID, [new MenuSection(interaction, menu.items)]); } finally { @@ -92,22 +93,29 @@ EditorInteraction itemInteraction ) { m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); - uint popupId = NativeImGui.GetID(id); + uint popupID = NativeImGui.GetID(id); if (!ShouldResolveItemContextMenu(id)) { - m_contextSearches.Remove((m_session.owner, popupId)); + m_contextSearches.Remove((m_session.owner, popupID)); return false; } EditorMenuModel scopeMenu = scopeInteraction.BuildMenu(); EditorMenuModel itemMenu = itemInteraction.BuildMenu(); if (scopeMenu.items.Count == 0 && itemMenu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginContextMenu(id)) + { return false; + } try { - DrawContextMenuContents(popupId, [new MenuSection(scopeInteraction, scopeMenu.items), new MenuSection(itemInteraction, itemMenu.items)]); + DrawContextMenuContents( + popupID, + [new MenuSection(scopeInteraction, scopeMenu.items), new MenuSection(itemInteraction, itemMenu.items)] + ); } finally { @@ -135,21 +143,25 @@ EditorInteraction interaction ) { m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); - uint popupId = NativeImGui.GetID(id); + uint popupID = NativeImGui.GetID(id); if (!ShouldResolveWindowContextMenu(id)) { - m_contextSearches.Remove((m_session.owner, popupId)); + m_contextSearches.Remove((m_session.owner, popupID)); return false; } EditorMenuModel menu = interaction.BuildMenu(); if (menu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginWindowContextMenu(id)) + { return false; + } try { - DrawContextMenuContents(popupId, [new MenuSection(interaction, menu.items)]); + DrawContextMenuContents(popupID, [new MenuSection(interaction, menu.items)]); } finally { @@ -159,37 +171,159 @@ EditorInteraction interaction return true; } + /// + /// Draws the complete editor main menu bar for the supplied menu context. + /// + /// + /// The main-menu interaction area. + /// + public void MainMenu(EditorInteraction interaction) + { + m_session.EnsureDrawing(); + if (!NativeImGui.BeginMainMenuBar()) + { + return; + } + try + { + DrawItems(interaction, interaction.BuildMenu().items); + DrawCenteredToolbar(interaction, interaction.BuildToolbar().items); + } + finally + { + NativeImGui.EndMainMenuBar(); + } + } + + /// + /// Recursively draws resolved menu nodes into the currently open popup or menu. + /// + /// + /// The interaction used to resolve shortcuts and enqueue selected actions. + /// + /// + /// The immutable menu nodes to draw in display order. + /// + public void DrawItems( + EditorInteraction interaction, + IReadOnlyList items + ) { + m_session.EnsureDrawing(); + ArgumentNullException.ThrowIfNull(items); + for (int i = 0; i < items.Count; i++) + { + EditorMenuItem item = items[i]; + // A separator groups adjacent commands; it is never meaningful before the first + // visible item of a popup or submenu. Enforcing that here keeps every menu surface + // consistent even when a type-specific query hides the commands that preceded it. + if (i > 0 && item.separatorBefore) + { + NativeImGui.Separator(); + } + if (item.children.Count > 0) + { + if (!NativeImGui.BeginMenu(item.label, item.status.isEnabled)) + { + continue; + } + try + { + DrawItems(interaction, item.children); + } + finally + { + NativeImGui.EndMenu(); + } + + continue; + } + + string shortcut = interaction.TryGetShortcut(item.actionID, out HotKeyGesture gesture) ? gesture.ToString() : string.Empty; + if (NativeImGui.MenuItem(item.label, shortcut, item.status.isChecked, item.status.isEnabled)) + { + interaction.Enqueue(item.actionID, item.argument); + } + + DrawUnavailableReason(item.status); + } + } + + /// + /// Draws matching leaf commands as a flat searchable list. + /// + /// + /// The interaction used to enqueue selected actions. + /// + /// + /// The immutable menu tree whose leaves should be searched. + /// + /// + /// The case-insensitive text matched against each slash-delimited leaf path. + /// + /// + /// when a command was selected. + /// + public bool DrawSearchItems( + EditorInteraction interaction, + IReadOnlyList items, + string search + ) { + m_session.EnsureDrawing(); + ArgumentNullException.ThrowIfNull(items); + return DrawSearchItems(interaction, items, search ?? string.Empty, string.Empty); + } + + internal void RetireOwner(string owner) + { + foreach ((string owner, uint popup) key in m_contextSearches.Keys.Where(value => value.owner == owner).ToArray()) + { + m_contextSearches.Remove(key); + } + } + + internal void Clear() => m_contextSearches.Clear(); + private void DrawContextMenuContents( - uint popupId, + uint popupID, IReadOnlyList sections ) { - string search = NativeImGui.IsWindowAppearing() ? string.Empty : m_contextSearches.GetValueOrDefault((m_session.owner, popupId), string.Empty); + string search = NativeImGui.IsWindowAppearing() + ? string.Empty + : m_contextSearches.GetValueOrDefault((m_session.owner, popupID), string.Empty); NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.menuSearchFramePadding); try { if (NativeImGui.IsWindowAppearing()) + { NativeImGui.SetKeyboardFocusHere(); - _ = EditorUI.current.widgets.SearchInput($"context-menu-{popupId}", "Search commands…", ref search, width: -1f); + } + _ = EditorUI.current.widgets.SearchInput($"context-menu-{popupID}", "Search commands…", ref search, width: -1f); } finally { NativeImGui.PopStyleVar(); } - m_contextSearches[(m_session.owner, popupId)] = search; + m_contextSearches[(m_session.owner, popupID)] = search; NativeImGui.Separator(); bool searching = !string.IsNullOrWhiteSpace(search); bool drewSection = false; foreach (MenuSection section in sections) { if (section.items.Count == 0) + { continue; + } if (!searching && drewSection) + { NativeImGui.Separator(); + } if (searching) { if (!DrawSearchItems(section.interaction, section.items, search)) + { continue; + } NativeImGui.CloseCurrentPopup(); return; } @@ -199,41 +333,25 @@ IReadOnlyList sections } } - private bool ShouldResolveItemContextMenu(string id) => NativeImGui.IsPopupOpen(id) - || NativeImGui.IsItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); - private bool ShouldResolveWindowContextMenu(string id) => NativeImGui.IsPopupOpen(id) - || NativeImGui.IsWindowHovered() - && !NativeImGui.IsAnyItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); - /// - /// Draws the complete editor main menu bar for the supplied menu context. - /// - /// - /// The main-menu interaction area. - /// - public void MainMenu(EditorInteraction interaction) - { - m_session.EnsureDrawing(); - if (!NativeImGui.BeginMainMenuBar()) - return; - try - { - DrawItems(interaction, interaction.BuildMenu().items); - DrawCenteredToolbar(interaction, interaction.BuildToolbar().items); - } - finally - { - NativeImGui.EndMainMenuBar(); - } - } + private bool ShouldResolveItemContextMenu(string id) + => NativeImGui.IsPopupOpen(id) + || NativeImGui.IsItemHovered() + && NativeImGui.IsMouseReleased((int)(NativeMouseButton.Right)); + + private bool ShouldResolveWindowContextMenu(string id) + => NativeImGui.IsPopupOpen(id) + || NativeImGui.IsWindowHovered() + && !NativeImGui.IsAnyItemHovered() + && NativeImGui.IsMouseReleased((int)(NativeMouseButton.Right)); private void DrawCenteredToolbar( EditorInteraction interaction, IReadOnlyList items ) { if (items.Count == 0) + { return; + } ImGuiStyle* style = NativeImGui.Raw.GetStyle(); float extent = NativeImGui.GetFrameHeight(); float width = extent * items.Count + style->ItemSpacing.X * (items.Count - 1); @@ -243,7 +361,9 @@ IReadOnlyList items for (int i = 0; i < items.Count; i++) { if (i > 0) + { NativeImGui.SameLine(0f, style->ItemSpacing.X); + } DrawToolbarItem(interaction, items[i], new Vector2(extent, extent)); } } @@ -255,13 +375,17 @@ Vector2 size ) { bool disabled = !item.status.isEnabled; if (disabled) + { NativeImGui.BeginDisabled(true); + } Vector2 minimum = NativeImGui.GetCursorScreenPos(); - bool pressed = NativeImGui.InvisibleButton($"##editor_toolbar_{item.actionId}", size); + bool pressed = NativeImGui.InvisibleButton($"##editor_toolbar_{item.actionID}", size); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); if (disabled) + { NativeImGui.EndDisabled(); + } if (item.status.isChecked || hovered || active) { Vector4 background = active ? EditorPalette.accentActive : hovered ? EditorPalette.accentHovered : EditorPalette.accent; @@ -279,97 +403,29 @@ Vector2 size EditorUI.current.widgets.AddGlyphCentered(NativeImGui.GetFontSize(), GetToolbarIcon(item.icon), minimum + size * 0.5f, color); if (hovered && EditorUI.current.widgets.BeginMenuTooltip()) { - string tooltip = interaction.TryGetShortcut(item.actionId, out HotKeyGesture shortcut) ? $"{item.tooltip} ({shortcut})" : item.tooltip; + string tooltip = interaction.TryGetShortcut(item.actionID, out HotKeyGesture shortcut) + ? $"{item.tooltip} ({shortcut})" + : item.tooltip; NativeImGui.TextUnformatted(tooltip); EditorUI.current.widgets.EndMenuTooltip(); } if (pressed && item.status.isEnabled) - interaction.Enqueue(item.actionId); + { + interaction.Enqueue(item.actionID); + } } - private string GetToolbarIcon(EditorToolbarIcon icon) => icon switch + private string GetToolbarIcon(EditorToolbarIcon icon) + => icon switch { - EditorToolbarIcon.Play => ImGuiIcon.Play, - EditorToolbarIcon.Stop => ImGuiIcon.Stop, - EditorToolbarIcon.Pause => ImGuiIcon.Pause, - EditorToolbarIcon.Step => ImGuiIcon.ForwardStep, - EditorToolbarIcon.Edit => ImGuiIcon.Pen, + EditorToolbarIcon.Play => ImGuiIcon.C_PLAY, + EditorToolbarIcon.Stop => ImGuiIcon.C_STOP, + EditorToolbarIcon.Pause => ImGuiIcon.C_PAUSE, + EditorToolbarIcon.Step => ImGuiIcon.C_FORWARD_STEP, + EditorToolbarIcon.Edit => ImGuiIcon.C_PEN, _ => string.Empty }; - /// - /// Recursively draws resolved menu nodes into the currently open popup or menu. - /// - /// - /// The interaction used to resolve shortcuts and enqueue selected actions. - /// - /// - /// The immutable menu nodes to draw in display order. - /// - public void DrawItems( - EditorInteraction interaction, - IReadOnlyList items - ) { - m_session.EnsureDrawing(); - ArgumentNullException.ThrowIfNull(items); - for (int i = 0; i < items.Count; i++) - { - EditorMenuItem item = items[i]; - // A separator groups adjacent commands; it is never meaningful before the first - // visible item of a popup or submenu. Enforcing that here keeps every menu surface - // consistent even when a type-specific query hides the commands that preceded it. - if (i > 0 && item.separatorBefore) - NativeImGui.Separator(); - if (item.children.Count > 0) - { - if (!NativeImGui.BeginMenu(item.label, item.status.isEnabled)) - continue; - try - { - DrawItems(interaction, item.children); - } - finally - { - NativeImGui.EndMenu(); - } - - continue; - } - - string shortcut = interaction.TryGetShortcut(item.actionId, out HotKeyGesture gesture) ? gesture.ToString() : string.Empty; - if (NativeImGui.MenuItem(item.label, shortcut, item.status.isChecked, item.status.isEnabled)) - { - interaction.Enqueue(item.actionId, item.argument); - } - - DrawUnavailableReason(item.status); - } - } - - /// - /// Draws matching leaf commands as a flat searchable list. - /// - /// - /// The interaction used to enqueue selected actions. - /// - /// - /// The immutable menu tree whose leaves should be searched. - /// - /// - /// The case-insensitive text matched against each slash-delimited leaf path. - /// - /// - /// when a command was selected. - /// - public bool DrawSearchItems( - EditorInteraction interaction, - IReadOnlyList items, - string search - ) { - m_session.EnsureDrawing(); - ArgumentNullException.ThrowIfNull(items); - return DrawSearchItems(interaction, items, search ?? string.Empty, string.Empty); - } private bool DrawSearchItems( EditorInteraction interaction, @@ -384,7 +440,9 @@ string parentPath if (item.children.Count > 0) { if (DrawSearchItems(interaction, item.children, search, path)) + { return true; + } continue; } @@ -407,7 +465,7 @@ string parentPath DrawUnavailableReason(item.status); if (chosen && item.status.isEnabled) { - interaction.Enqueue(item.actionId, item.argument); + interaction.Enqueue(item.actionID, item.argument); return true; } } @@ -417,8 +475,12 @@ string parentPath private void DrawUnavailableReason(EditorActionState state) { - if (state.isEnabled || string.IsNullOrWhiteSpace(state.unavailableReason) || !NativeImGui.IsItemHovered((int)ImGuiHoveredFlags.AllowWhenDisabled)) + if (state.isEnabled + || string.IsNullOrWhiteSpace(state.unavailableReason) + || !NativeImGui.IsItemHovered((int)ImGuiHoveredFlags.AllowWhenDisabled) + ) { return; + } NativeImGui.BeginTooltip(); try { @@ -429,4 +491,9 @@ private void DrawUnavailableReason(EditorActionState state) NativeImGui.EndTooltip(); } } + + private readonly record struct MenuSection( + EditorInteraction interaction, + IReadOnlyList items + ); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs index d3f9772a8..e95cd3658 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs @@ -1,14 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.ImGui; + internal sealed class EditorModalHost { private readonly Dictionary m_transitions = new(StringComparer.Ordinal); + internal bool Update( IReadOnlyList modals, double now @@ -16,8 +19,10 @@ double now bool newBlockingModalRequested = false; for (int i = 0; i < modals.Count; i++) { - if (modals[i].TryGetPresentation(out EditorModalExtension.Presentation candidate) && candidate.isVisible && candidate.blocksInteraction) - { + if (modals[i].TryGetPresentation(out EditorModalExtension.Presentation candidate) + && candidate.isVisible + && candidate.blocksInteraction + ) { newBlockingModalRequested = true; break; } @@ -28,14 +33,22 @@ double now { EditorModalExtension extension = modals[i]; if (!extension.TryGetPresentation(out EditorModalExtension.Presentation presentation)) + { continue; + } Transition transition = GetTransition(extension.id); if (newBlockingModalRequested && !presentation.isVisible) + { transition.HideImmediately(); + } else + { transition.Update(presentation.isVisible, now); + } if (presentation.blocksInteraction && transition.isVisible) + { blocksInteraction = true; + } } return blocksInteraction; @@ -67,10 +80,13 @@ double now } internal void Clear() => m_transitions.Clear(); + private Transition GetTransition(string id) { if (m_transitions.TryGetValue(id, out Transition? transition)) + { return transition; + } transition = new Transition(); m_transitions.Add(id, transition); return transition; @@ -99,7 +115,9 @@ double now if (!m_requested) { if (!isVisible) + { m_visibleAt = now; + } isVisible = true; } @@ -122,11 +140,11 @@ internal float GetAlpha(double now) if (m_requested || now <= m_hideAt) { double fadeIn = (now - m_visibleAt) / EditorUI.current.widgets.style.modalFadeInSeconds; - return (float)Math.Clamp(fadeIn, EditorPalette.opacityFaint, EditorPalette.opacityOpaque); + return (float)Math.Clamp(fadeIn, EditorPalette.C_OPACITY_FAINT, EditorPalette.C_OPACITY_OPAQUE); } double fadeOut = (now - m_hideAt) / EditorUI.current.widgets.style.modalFadeOutSeconds; - return (float)Math.Clamp(1.0 - fadeOut, EditorPalette.opacityFaint, EditorPalette.opacityOpaque); + return (float)Math.Clamp(1.0 - fadeOut, EditorPalette.C_OPACITY_FAINT, EditorPalette.C_OPACITY_OPAQUE); } } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs index 23e29023f..6fd11c8cd 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs @@ -1,14 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; -using BGCS.Runtime; using System.Numerics; using System.Runtime.CompilerServices; +using BGCS.Runtime; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Renders centered editor modals consistently on the main viewport. /// @@ -49,29 +51,38 @@ EditorContext context ArgumentException.ThrowIfNullOrWhiteSpace(title); ArgumentNullException.ThrowIfNull(modal); ArgumentNullException.ThrowIfNull(context); - EditorUiSession session = EditorUI.current; + EditorUISession session = EditorUI.current; // The runtime established this session; revalidate below after invoking extension preparation. - string popupId = $"{title}##{id}"; + string popupID = $"{title}##{id}"; ImGuiViewport* viewport = NativeImGui.Raw.GetMainViewport(); - var style = NativeImGui.Raw.GetStyle(); + ImGuiStyle* style = NativeImGui.Raw.GetStyle(); Vector2 workSize = Vector2.Max(Vector2.One, ImGui.FromNative(viewport->WorkSize)); Vector2 padding = ImGui.FromNative(style->WindowPadding); Vector2 bounds = Vector2.Max(Vector2.One, workSize - padding * 2f); - Vector2 maximumSize = new(MathF.Floor(bounds.X), MathF.Floor(bounds.Y)); + var maximumSize = new Vector2(MathF.Floor(bounds.X), MathF.Floor(bounds.Y)); Vector2 minimumSize = Vector2.Min(presentation.minimumSize * EditorUI.current.widgets.style.zoom, maximumSize); Vector2 initialSize = presentation.initialSize * EditorUI.current.widgets.style.zoom; if (presentation.canResize && initialSize.Y <= 0f) { - using NativeStringLease nativeTitle = Utf8Codec.EncodeNullTerminated(popupId, allowsNull: false); + using NativeStringLease nativeTitle = Utf8Codec.EncodeNullTerminated(popupID, allowsNull: false); ImGuiWindow* existing = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTitle.pointer); - if (existing != null && existing->WasActive != 0) + if (existing is not null && existing->WasActive != 0) + { initialSize = ImGui.FromNative(existing->SizeFull); + } } - float width = MathF.Floor(Math.Clamp(initialSize.X > 0f ? initialSize.X : EditorUI.current.widgets.style.modalWidth, - MathF.Max(1f, minimumSize.X), maximumSize.X)); + float width = MathF.Floor( + Math.Clamp( + initialSize.X > 0f ? initialSize.X : EditorUI.current.widgets.style.modalWidth, + MathF.Max(1f, minimumSize.X), + maximumSize.X + ) + ); float decorations = NativeImGui.GetFrameHeight(); - Vector2 available = new(MathF.Max(1f, width - padding.X * 2f), - MathF.Max(1f, (initialSize.Y > 0f ? MathF.Min(initialSize.Y, maximumSize.Y) : maximumSize.Y) - padding.Y * 2f - decorations)); + var available = new Vector2( + MathF.Max(1f, width - padding.X * 2f), + MathF.Max(1f, (initialSize.Y > 0f ? MathF.Min(initialSize.Y, maximumSize.Y) : maximumSize.Y) - padding.Y * 2f - decorations) + ); // Explicit resizable windows commit current input in Begin; measure their actual content area afterwards. bool prepareInside = presentation.canResize && initialSize.Y > 0f; Vector2? measured = null; @@ -81,7 +92,9 @@ EditorContext context return; } if (!ReferenceEquals(EditorUI.current, session)) + { throw new InvalidOperationException("Modal preparation changed the active UI session."); + } session.EnsureDrawing(); bool horizontalOverflow = false; if (presentation.allowScrolling && measured is Vector2 content) @@ -92,47 +105,58 @@ EditorContext context } float height = initialSize.Y > 0f ? initialSize.Y : measured!.Value.Y + padding.Y * 2f + decorations; if (horizontalOverflow && initialSize.Y <= 0f) + { height += style->ScrollbarSize; - Vector2 windowSize = new(width, MathF.Ceiling(Math.Clamp(height, MathF.Max(1f, minimumSize.Y), maximumSize.Y))); + } + var windowSize = new Vector2(width, MathF.Ceiling(Math.Clamp(height, MathF.Max(1f, minimumSize.Y), maximumSize.Y))); Vector2 center = ImGui.FromNative(viewport->WorkPos) + workSize * 0.5f; if (presentation.blocksInteraction) - NativeImGui.OpenPopup(popupId, (int)ImGuiPopupFlags.NoReopen); + { + NativeImGui.OpenPopup(popupID, (int)ImGuiPopupFlags.NoReopen); + } NativeImGui.SetNextWindowViewport(viewport->ID); ImGuiCond placementCondition = presentation.canMove || presentation.canResize ? ImGuiCond.Appearing : ImGuiCond.Always; NativeImGui.SetNextWindowPos(center, (int)placementCondition, new Vector2(0.5f)); NativeImGui.SetNextWindowSize(windowSize, (int)(presentation.canResize ? ImGuiCond.Appearing : ImGuiCond.Always)); ImGui.ConstrainNativeWindowSize(minimumSize, maximumSize, null, null); if (measured is Vector2 extent) + { NativeImGui.SetNextWindowContentSize(extent); + } NativeImGui.PushStyleVar((int)(ImGuiStyleVar.Alpha), alpha); ImGuiWindowFlags flags = ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoCollapse; if (horizontalOverflow) + { flags |= ImGuiWindowFlags.HorizontalScrollbar; + } if (!presentation.allowScrolling) + { flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + } if (!presentation.canMove) + { flags |= ImGuiWindowFlags.NoMove; + } if (!presentation.canResize) + { flags |= ImGuiWindowFlags.NoResize; + } bool beganWindow = false; try { - bool visible = presentation.blocksInteraction ? ImGui.BeginNativeWindow( - popupId, - flags, - modal: true - ) : ImGui.BeginNativeWindow( - popupId, - flags | ImGuiWindowFlags.NoSavedSettings, - modal: false - ); + bool visible = presentation.blocksInteraction + ? ImGui.BeginNativeWindow(popupID, flags, modal: true) + : ImGui.BeginNativeWindow(popupID, flags | ImGuiWindowFlags.NoSavedSettings, modal: false); beganWindow = !presentation.blocksInteraction || visible; if (visible) { - if (!prepareInside || modal.TryPrepare(context, presentation, Vector2.Max(Vector2.One, NativeImGui.GetContentRegionAvail()), out _)) + if (!prepareInside + || modal.TryPrepare(context, presentation, Vector2.Max(Vector2.One, NativeImGui.GetContentRegionAvail()), out _) + ) { _ = modal.Draw(context); + } } } finally @@ -140,9 +164,13 @@ EditorContext context if (beganWindow) { if (presentation.blocksInteraction) + { NativeImGui.EndPopup(); + } else + { NativeImGui.End(); + } } NativeImGui.PopStyleVar(); @@ -162,9 +190,11 @@ internal static void Close( string id, string title ) { - string popupId = $"{title}##{id}"; - if (!NativeImGui.IsPopupOpen(popupId) || !ImGui.BeginNativeWindow(popupId, ImGuiWindowFlags.None, modal: true)) + string popupID = $"{title}##{id}"; + if (!NativeImGui.IsPopupOpen(popupID) || !ImGui.BeginNativeWindow(popupID, ImGuiWindowFlags.None, modal: true)) + { return; + } try { NativeImGui.CloseCurrentPopup(); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUIInput.cs similarity index 71% rename from src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs rename to src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUIInput.cs index 95581416c..acdbac89e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUIInput.cs @@ -2,59 +2,68 @@ using Inno.Native.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies frame input facts used by presentation without exposing native input storage. /// -public readonly struct EditorUiInput +public readonly struct EditorUIInput { + internal unsafe EditorUIInput(ImGuiIO* io) + { + this.alt = io->KeyAlt != 0; + bool swapsModifiers = io->ConfigMacOsxBehaviors != 0; + this.control = (swapsModifiers ? io->KeySuper : io->KeyCtrl) != 0; + this.shift = io->KeyShift != 0; + this.super = (swapsModifiers ? io->KeyCtrl : io->KeySuper) != 0; + this.wantsText = io->WantTextInput != 0; + this.mouseDelta = ImGui.FromNative(io->MouseDelta); + this.framebufferScale = ImGui.FromNative(io->DisplayFramebufferScale); + this.wheel = io->MouseWheel; + this.deltaTime = io->DeltaTime; + } + /// /// Gets whether Alt is held. /// public bool alt { get; } + /// /// Gets whether the physical Control modifier is held, independently of native shortcut conventions. /// public bool control { get; } + /// /// Gets whether Shift is held. /// public bool shift { get; } + /// /// Gets whether the physical Super modifier is held, independently of native shortcut conventions. /// public bool super { get; } + /// /// Gets whether an active control owns text input. /// public bool wantsText { get; } + /// /// Gets the current pointer movement in UI units. /// public Vector2 mouseDelta { get; } + /// /// Gets the vertical scroll movement. /// public float wheel { get; } + /// /// Gets the frame duration in seconds. /// public float deltaTime { get; } + /// /// Gets the drawable pixel scale relative to logical UI coordinates. /// public Vector2 framebufferScale { get; } - - internal unsafe EditorUiInput(ImGuiIO* io) - { - alt = io->KeyAlt != 0; - bool swapsModifiers = io->ConfigMacOsxBehaviors != 0; - control = (swapsModifiers ? io->KeySuper : io->KeyCtrl) != 0; - shift = io->KeyShift != 0; - super = (swapsModifiers ? io->KeyCtrl : io->KeySuper) != 0; - wantsText = io->WantTextInput != 0; - mouseDelta = ImGui.FromNative(io->MouseDelta); - framebufferScale = ImGui.FromNative(io->DisplayFramebufferScale); - wheel = io->MouseWheel; - deltaTime = io->DeltaTime; - } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUISession.cs similarity index 88% rename from src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs rename to src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUISession.cs index 89bed97a7..1b53ec12c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUISession.cs @@ -1,18 +1,22 @@ +using System; using Inno.Core.Events; using Inno.Editor.Interactions; -using EditorControls = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using System; using Inno.Native.ImGui; +using Inno.Scripting.Api; + +using EditorControls = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Owns editor controls and transient presentation state for one host, independently from other ImGui contexts. /// -public sealed unsafe class EditorUiSession : IDisposable +public sealed unsafe class EditorUISession : IDisposable { [ThreadStatic] - private static EditorUiSession? s_current; + private static EditorUISession? s_current; + private readonly int m_ownerThread = Environment.CurrentManagedThreadId; private EventHub? m_lifecycleHub; private Scope? m_scope; @@ -21,13 +25,14 @@ public sealed unsafe class EditorUiSession : IDisposable private int m_styleInputFrame = -1; private bool m_disposed; private string m_owner = "root"; + /// /// Creates independent controls and style state; the presentation backend retains its native context ownership. /// - public EditorUiSession() + public EditorUISession() { - widgets = new EditorControls(this); - menus = new EditorMenuRenderer(this); + this.widgets = new EditorControls(this); + this.menus = new EditorMenuRenderer(this); } /// @@ -36,7 +41,9 @@ public EditorUiSession() /// /// No UI drawing scope is active on the calling thread. /// - public static EditorUiSession current => s_current ?? throw new InvalidOperationException("Editor drawing requires an active UI session scope."); + public static EditorUISession current + => s_current ?? throw new InvalidOperationException("Editor drawing requires an active UI session scope."); + /// /// Gets the controls whose transient state belongs exclusively to this session. /// @@ -45,26 +52,13 @@ public EditorUiSession() /// /// Gets the menu presenter whose search state belongs exclusively to this session. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorMenuRenderer menus { get; } + /// /// Gets whether this session has successfully retired its presentation state. /// public bool isDisposed => m_disposed; - internal string owner => m_owner; - - internal bool shouldDeferStyleChanges - { - get - { - EnsureOwner(); - ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_nativeContext == 0) - return false; - ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - return context is null || (nint)context != m_nativeContext || context->WithinFrameScope != 0; - } - } /// /// Activates this session for a synchronous callback while preserving the enclosing scope. @@ -98,9 +92,13 @@ public void Dispose() { EnsureOwner(); if (m_disposed) + { return; + } if (m_scope is not null) + { throw new InvalidOperationException("The UI session still owns an active drawing scope."); + } widgets.Retire(); menus.Clear(); m_lifecycleHub?.Dispose(); @@ -109,11 +107,30 @@ public void Dispose() GC.SuppressFinalize(this); } + internal string owner => m_owner; + + internal bool shouldDeferStyleChanges + { + get + { + EnsureOwner(); + ObjectDisposedException.ThrowIf(m_disposed, this); + if (m_nativeContext == 0) + { + return false; + } + ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); + return context is null || (nint)context != m_nativeContext || context->WithinFrameScope != 0; + } + } + internal void Connect(EditorInteractions interactions) { EnsureOwner(); if (m_lifecycleHub is not null) + { throw new InvalidOperationException("The UI session already belongs to an interaction runtime."); + } m_lifecycleHub = interactions.events.CreateHub(int.MaxValue); m_lifecycleHub.Listen(_ => widgets.CommitEdits()); } @@ -142,25 +159,33 @@ internal void PrepareStyleInput() if (context->WithinFrameScope != 0) { if (m_styleInputFrame == context->FrameCount) + { return; + } m_styleInputFrame = context->FrameCount; } else + { m_styleInputFrame = context->FrameCount + 1; + } widgets.style.CommitPending(); } internal void RequireFramePreparation() { if (RequireContext()->WithinFrameScope != 0) + { throw new InvalidOperationException("Style preparation must run before native frame creation."); + } } internal ImGuiNativeContext* RequireDrawingFrame() { ImGuiNativeContext* context = RequireContext(); if (context->WithinFrameScope == 0 || context->CurrentWindow is null) + { throw new InvalidOperationException("Drawing requires an active native frame and window."); + } return context; } @@ -173,38 +198,53 @@ internal void RequireFramePreparation() EnsureOwner(); ObjectDisposedException.ThrowIf(m_disposed, this); if (!ReferenceEquals(s_current, this)) + { throw new InvalidOperationException("Controls must be drawn within their owning UI session scope."); + } nint context = (nint)NativeImGui.Raw.GetCurrentContext(); if (context == 0) + { throw new InvalidOperationException("Editor controls require a live ImGui context."); + } if (m_nativeContext == 0) + { m_nativeContext = context; + } else if (m_nativeContext != context) + { throw new InvalidOperationException("The UI session belongs to a different ImGui context."); + } return (ImGuiNativeContext*)context; } private void EnsureOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Editor UI sessions must be used and retired on their owner thread."); + } } private sealed class Scope( - EditorUiSession owner, - EditorUiSession? previous, + EditorUISession owner, + EditorUISession? previous, Scope? previousScope ) : IDisposable { private bool m_disposed; - /// + + /// public void Dispose() { owner.EnsureOwner(); if (m_disposed) + { return; + } if (!ReferenceEquals(s_current, owner) || !ReferenceEquals(owner.m_scope, this)) + { throw new InvalidOperationException("UI drawing scopes must retire in reverse activation order."); + } owner.m_scope = previousScope; s_current = previous; m_disposed = true; @@ -212,20 +252,25 @@ public void Dispose() } private sealed class OwnerScope( - EditorUiSession session, + EditorUISession session, string previous, OwnerScope? previousScope ) : IDisposable { private bool m_disposed; - /// + + /// public void Dispose() { if (m_disposed) + { return; + } session.EnsureOwner(); if (!ReferenceEquals(session.m_ownerScope, this)) + { throw new InvalidOperationException("UI owner scopes must retire in reverse activation order."); + } session.m_owner = previous; session.m_ownerScope = previousScope; m_disposed = true; diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs index 3b3f5f53d..2fb20eb90 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs @@ -1,20 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using Inno.Core.Events; using Inno.Core.Execution; -using Inno.Core.Logging; using Inno.Core.Input; -using Inno.Extensibility.Types; +using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Presents the backend-independent editor interaction runtime through ImGui. /// @@ -22,14 +25,15 @@ public sealed unsafe class ImGuiEditorRuntime : EditorRuntime { private readonly Stopwatch m_timer = Stopwatch.StartNew(); private readonly EditorInteractionRuntime m_runtime; - private readonly EditorUiSession m_ui = new(); + private readonly EditorUISession m_ui = new(); private readonly EditorModalHost m_modals = new(); private readonly HashSet m_openOwners = new(StringComparer.Ordinal); private readonly HashSet m_currentOwners = new(StringComparer.Ordinal); private readonly List m_retiredOwners = []; - private uint m_dockspaceId; + private uint m_dockspaceID; private Vector2 m_dockspaceSize; private bool m_disposed; + /// /// Creates an ImGui editor runtime with stable host-owned extension services. /// @@ -73,6 +77,7 @@ IEnumerable hostServices /// Gets the active presentation-independent interaction entry point. /// public EditorInteractions interactions => m_runtime.interactions; + /// /// Gets the number of active dockable panels. /// @@ -116,13 +121,13 @@ public void SaveState() /// Freezes automatic extension-state persistence and writes the final project state before editor /// modules begin shutting down. /// + /// + /// Thrown after this runtime has been disposed. + /// /// /// This operation is idempotent and prevents module teardown from overwriting the saved /// module sections with transient empty state. /// - /// - /// Thrown after this runtime has been disposed. - /// public void PrepareShutdown() { using IDisposable uiScope = m_ui.Enter(); @@ -161,20 +166,24 @@ public void Draw() double now = m_timer.Elapsed.TotalSeconds; bool blocksInteraction = m_modals.Update(modals, now); if (blocksInteraction) + { NativeImGui.BeginDisabled(true); + } try { // The main menu must reserve the viewport work area before the dockspace snapshots it. // Reversing this order makes the dockspace overlap the bottom of the menu and clip the // first docked tab bar row. - EditorUI.current.menus.MainMenu(interactions.For(ImGuiInteractionIds.C_MAIN_MENU_AREA)); + EditorUI.current.menus.MainMenu(interactions.For(ImGuiInteractionIDs.C_MAIN_MENU_AREA)); DrawDockSpace(); DrawPanels(m_runtime.panels); } finally { if (blocksInteraction) + { NativeImGui.EndDisabled(); + } } m_ui.widgets.CompleteEditingFrame(); @@ -185,93 +194,6 @@ public void Draw() m_modals.Draw(context, modals, now); } - private void DrawDockSpace() - { - ImGuiViewport* viewport = NativeImGui.Raw.GetMainViewport(); - Vector2 size = ImGui.FromNative(viewport->WorkSize); - ImGuiStyle* style = NativeImGui.Raw.GetStyle(); - if (m_dockspaceId == 0) - { - uint hostId = ImGui.HashNativeId($"WindowOverViewport_{viewport->ID:X8}"); - m_dockspaceId = ImGui.HashNativeId("DockSpace", hostId); - ImGuiDockNode* loaded = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (loaded != null) - ResizeDockSplits(loaded, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); - } - else if (m_dockspaceSize != Vector2.Zero && (MathF.Abs(size.X - m_dockspaceSize.X) >= 0.5f || MathF.Abs(size.Y - m_dockspaceSize.Y) >= 0.5f)) - { - ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (root != null) - ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); - } - - NativeImGui.PushStyleColor((int)(ImGuiCol.ResizeGripHovered), EditorPalette.accentHovered); - NativeImGui.PushStyleColor((int)(ImGuiCol.ResizeGripActive), EditorPalette.accentActive); - try - { - uint submittedId = NativeImGui.Raw.DockSpaceOverViewport(0, null, 0, null); - if (submittedId != m_dockspaceId) - throw new InvalidOperationException("The ImGui viewport dockspace identity changed before layout could be resized."); - } - finally - { - NativeImGui.PopStyleColor(2); - } - - if (m_dockspaceSize == Vector2.Zero) - { - ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (root != null) - ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); - } - - m_dockspaceSize = size; - } - - private static unsafe void ResizeDockSplits( - ImGuiDockNode* node, - Vector2 size, - float separator, - Vector2 minimumWindowSize - ) { - ImGuiDockNode* first = node->ChildNodes[0]; - ImGuiDockNode* second = node->ChildNodes[1]; - if (first == null || second == null || node->SplitAxis is not (ImGuiAxis.X or ImGuiAxis.Y)) - return; - bool horizontal = node->SplitAxis == ImGuiAxis.X; - float firstReference = horizontal ? first->Size.X : first->Size.Y; - float secondReference = horizontal ? second->Size.X : second->Size.Y; - float previousAvailable = (horizontal ? node->Size.X : node->Size.Y) - separator; - if (firstReference <= 0f || secondReference <= 0f || MathF.Abs(firstReference + secondReference - previousAvailable) > MathF.Max(1f, separator)) - { - firstReference = horizontal ? first->SizeRef.X : first->SizeRef.Y; - secondReference = horizontal ? second->SizeRef.X : second->SizeRef.Y; - } - - float available = (horizontal ? size.X : size.Y) - separator; - if (!float.IsFinite(firstReference) || !float.IsFinite(secondReference) || firstReference <= 0f || secondReference <= 0f || available <= 1f) - return; - float minimum = MathF.Min(available * 0.5f, horizontal ? minimumWindowSize.X : minimumWindowSize.Y); - float firstExtent = Math.Clamp(available * firstReference / (firstReference + secondReference), minimum, available - minimum); - Vector2 firstSize = size; - Vector2 secondSize = size; - if (horizontal) - { - firstSize.X = firstExtent; - secondSize.X = available - firstExtent; - } - else - { - firstSize.Y = firstExtent; - secondSize.Y = available - firstExtent; - } - - first->SizeRef = ImGui.ToNative(firstSize); - second->SizeRef = ImGui.ToNative(secondSize); - ResizeDockSplits(first, firstSize, separator, minimumWindowSize); - ResizeDockSplits(second, secondSize, separator, minimumWindowSize); - } - /// /// Dispatches contextual shortcuts, leaving editing keys with active text widgets while permitting explicit save. /// @@ -283,12 +205,16 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) using IDisposable uiScope = m_ui.Enter(); ArgumentNullException.ThrowIfNull(keyEvent); if (m_modals.Update(m_runtime.modals, m_timer.Elapsed.TotalSeconds)) + { return; + } // Text widgets own editing keys, including Backspace and clipboard/history gestures. // Explicit document save remains available without first leaving an input field. HotKeyGesture save = HotKeyGesture.Primary(KeyCode.S, context.keyboard); if (NativeImGui.Raw.GetIO()->WantTextInput != 0 && (keyEvent.key != save.key || keyEvent.modifiers != save.modifiers)) + { return; + } m_ui.widgets.CommitEdits(); m_runtime.HandleKeyPressed(keyEvent); } @@ -302,7 +228,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) public override void Dispose() { if (m_disposed) + { return; + } m_modals.Clear(); try { @@ -328,6 +256,58 @@ public override void Dispose() GC.SuppressFinalize(this); } + private void DrawDockSpace() + { + ImGuiViewport* viewport = NativeImGui.Raw.GetMainViewport(); + Vector2 size = ImGui.FromNative(viewport->WorkSize); + ImGuiStyle* style = NativeImGui.Raw.GetStyle(); + if (m_dockspaceID == 0) + { + uint hostID = ImGui.HashNativeID($"WindowOverViewport_{viewport->ID:X8}"); + m_dockspaceID = ImGui.HashNativeID("DockSpace", hostID); + ImGuiDockNode* loaded = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceID); + if (loaded is not null) + { + ResizeDockSplits(loaded, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } + } + else if (m_dockspaceSize != Vector2.Zero + && (MathF.Abs(size.X - m_dockspaceSize.X) >= 0.5f || MathF.Abs(size.Y - m_dockspaceSize.Y) >= 0.5f) + ) { + ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceID); + if (root is not null) + { + ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } + } + + NativeImGui.PushStyleColor((int)(ImGuiCol.ResizeGripHovered), EditorPalette.accentHovered); + NativeImGui.PushStyleColor((int)(ImGuiCol.ResizeGripActive), EditorPalette.accentActive); + try + { + uint submittedID = NativeImGui.Raw.DockSpaceOverViewport(0, null, 0, null); + if (submittedID != m_dockspaceID) + { + throw new InvalidOperationException("The ImGui viewport dockspace identity changed before layout could be resized."); + } + } + finally + { + NativeImGui.PopStyleColor(2); + } + + if (m_dockspaceSize == Vector2.Zero) + { + ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceID); + if (root is not null) + { + ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } + } + + m_dockspaceSize = size; + } + private void DrawPanels(IReadOnlyList panels) { m_currentOwners.Clear(); @@ -338,25 +318,35 @@ private void DrawPanels(IReadOnlyList panels) if (!extension.isOpen) { if (m_openOwners.Remove(extension.id)) + { m_ui.RetireOwner(extension.id); + } continue; } m_openOwners.Add(extension.id); using IDisposable ownerScope = m_ui.EnterOwner(extension.id); if (!extension.TryGetWindowPresentation(out bool useWindowPadding, out bool allowScrolling, out Vector2 initialSize)) + { continue; + } bool isOpen = extension.isOpen; if (initialSize.X > 0 && initialSize.Y > 0) + { NativeImGui.SetNextWindowSize(initialSize, (int)(ImGuiCond.FirstUseEver)); + } ImGuiWindowFlags flags = ImGuiWindowFlags.NoCollapse; if (!allowScrolling) + { flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + } if (extension.TakeFocusRequest()) + { NativeImGui.SetNextWindowFocus(); + } EditorUI.current.widgets.PanelWindow(extension.title, ref isOpen, () => { - if (extension.Draw(context) && NativeImGui.IsWindowFocused((int)(Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows))) + if (extension.Draw(context) && NativeImGui.IsWindowFocused((int)(NativeFocusedFlags.RootAndChildWindows))) { interactions.For($"panel/{extension.id}", interactions.selection.selectedTarget).Focus(); } @@ -366,8 +356,12 @@ private void DrawPanels(IReadOnlyList panels) m_retiredOwners.Clear(); foreach (string owner in m_openOwners) + { if (!m_currentOwners.Contains(owner)) + { m_retiredOwners.Add(owner); + } + } foreach (string owner in m_retiredOwners) { m_ui.RetireOwner(owner); @@ -376,4 +370,58 @@ private void DrawPanels(IReadOnlyList panels) m_retiredOwners.Clear(); } + + private static unsafe void ResizeDockSplits( + ImGuiDockNode* node, + Vector2 size, + float separator, + Vector2 minimumWindowSize + ) { + ImGuiDockNode* first = node->ChildNodes[0]; + ImGuiDockNode* second = node->ChildNodes[1]; + if (first is null || second is null || node->SplitAxis is not (ImGuiAxis.X or ImGuiAxis.Y)) + { + return; + } + bool horizontal = node->SplitAxis == ImGuiAxis.X; + float firstReference = horizontal ? first->Size.X : first->Size.Y; + float secondReference = horizontal ? second->Size.X : second->Size.Y; + float previousAvailable = (horizontal ? node->Size.X : node->Size.Y) - separator; + if (firstReference <= 0f + || secondReference <= 0f + || MathF.Abs(firstReference + secondReference - previousAvailable) > MathF.Max(1f, separator) + ) { + firstReference = horizontal ? first->SizeRef.X : first->SizeRef.Y; + secondReference = horizontal ? second->SizeRef.X : second->SizeRef.Y; + } + + float available = (horizontal ? size.X : size.Y) - separator; + if (!float.IsFinite(firstReference) + || !float.IsFinite(secondReference) + || firstReference <= 0f + || secondReference <= 0f + || available <= 1f + ) { + return; + } + float minimum = MathF.Min(available * 0.5f, horizontal ? minimumWindowSize.X : minimumWindowSize.Y); + float firstExtent = Math.Clamp(available * firstReference / (firstReference + secondReference), minimum, available - minimum); + Vector2 firstSize = size; + Vector2 secondSize = size; + if (horizontal) + { + firstSize.X = firstExtent; + secondSize.X = available - firstExtent; + } + else + { + firstSize.Y = firstExtent; + secondSize.Y = available - firstExtent; + } + + first->SizeRef = ImGui.ToNative(firstSize); + second->SizeRef = ImGui.ToNative(secondSize); + ResizeDockSplits(first, firstSize, separator, minimumWindowSize); + ResizeDockSplits(second, secondSize, separator, minimumWindowSize); + } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs index 5dfe8ceca..abf38d944 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Native.ImGui; namespace Inno.Editor.ImGui; @@ -13,102 +12,102 @@ public static unsafe class EditorPalette /// /// Gets zero opacity for invisible surfaces. /// - public const float opacityNone = 0f; + public const float C_OPACITY_NONE = 0f; /// /// Gets trace opacity for barely perceptible alternating surfaces. /// - public const float opacityTrace = 0.005f; + public const float C_OPACITY_TRACE = 0.005f; /// /// Gets faint opacity for quiet guides and separators. /// - public const float opacityFaint = 0.04f; + public const float C_OPACITY_FAINT = 0.04f; /// /// Gets subtle opacity for selection washes and low-emphasis overlays. /// - public const float opacitySubtle = 0.12f; + public const float C_OPACITY_SUBTLE = 0.12f; /// /// Gets soft opacity for tinted container surfaces. /// - public const float opacitySoft = 0.20f; + public const float C_OPACITY_SOFT = 0.2f; /// /// Gets muted opacity for shadows and subdued outlines. /// - public const float opacityMuted = 0.28f; + public const float C_OPACITY_MUTED = 0.28f; /// /// Gets medium opacity for secondary content and overlays. /// - public const float opacityMedium = 0.45f; + public const float C_OPACITY_MEDIUM = 0.45f; /// /// Gets strong opacity for accents that remain translucent. /// - public const float opacityStrong = 0.55f; + public const float C_OPACITY_STRONG = 0.55f; /// /// Gets prominent opacity for navigation emphasis. /// - public const float opacityProminent = 0.70f; + public const float C_OPACITY_PROMINENT = 0.7f; /// /// Gets emphasized opacity for borders and interactive grips. /// - public const float opacityEmphasized = 0.82f; + public const float C_OPACITY_EMPHASIZED = 0.82f; /// /// Gets near-opaque opacity for active overlays. /// - public const float opacityNearOpaque = 0.92f; + public const float C_OPACITY_NEAR_OPAQUE = 0.92f; /// /// Gets popup opacity, retaining only enough transparency for depth. /// - public const float opacityPopup = 0.985f; + public const float C_OPACITY_POPUP = 0.985f; /// /// Gets full opacity. /// - public const float opacityOpaque = 1f; + public const float C_OPACITY_OPAQUE = 1f; /// /// Gets fully transparent color. /// - public static Vector4 transparent { get; } = new(0f, 0f, 0f, opacityNone); + public static Vector4 transparent { get; } = new(0f, 0f, 0f, C_OPACITY_NONE); /// /// Gets the primary text color. /// - public static Vector4 text { get; } = new(0.88f, 0.89f, 0.91f, opacityOpaque); + public static Vector4 text { get; } = new(0.88f, 0.89f, 0.91f, C_OPACITY_OPAQUE); /// /// Gets disabled text color. /// - public static Vector4 textDisabled { get; } = new(0.58f, 0.60f, 0.64f, opacityOpaque); + public static Vector4 textDisabled { get; } = new(0.58f, 0.6f, 0.64f, C_OPACITY_OPAQUE); /// /// Gets the standard error color. /// - public static Vector4 error { get; } = new(1f, 0.35f, 0.35f, opacityOpaque); + public static Vector4 error { get; } = new(1f, 0.35f, 0.35f, C_OPACITY_OPAQUE); /// /// Gets the standard warning color. /// - public static Vector4 warning { get; } = new(0.9f, 0.65f, 0.25f, opacityOpaque); + public static Vector4 warning { get; } = new(0.9f, 0.65f, 0.25f, C_OPACITY_OPAQUE); /// /// Gets the editor window background. /// - public static Vector4 windowBackground { get; } = new(0.105f, 0.112f, 0.125f, opacityOpaque); + public static Vector4 windowBackground { get; } = new(0.105f, 0.112f, 0.125f, C_OPACITY_OPAQUE); /// /// Gets the editor popup background. /// - public static Vector4 popupBackground { get; } = new(0.075f, 0.081f, 0.092f, opacityPopup); + public static Vector4 popupBackground { get; } = new(0.075f, 0.081f, 0.092f, C_OPACITY_POPUP); /// /// Gets text color used by editor context menus. @@ -128,12 +127,12 @@ public static unsafe class EditorPalette /// /// Gets the hovered background of an editor context-menu item. /// - public static Vector4 menuItemHovered => new(0.235f, 0.245f, 0.275f, opacityOpaque); + public static Vector4 menuItemHovered => new(0.235f, 0.245f, 0.275f, C_OPACITY_OPAQUE); /// /// Gets the active background of an editor context-menu item. /// - public static Vector4 menuItemActive => new(0.31f, 0.285f, 0.43f, opacityOpaque); + public static Vector4 menuItemActive => new(0.31f, 0.285f, 0.43f, C_OPACITY_OPAQUE); /// /// Gets the separator color used by editor context menus. @@ -143,187 +142,187 @@ public static unsafe class EditorPalette /// /// Gets the standard border color. /// - public static Vector4 border { get; } = new(0.235f, 0.25f, 0.285f, opacityEmphasized); + public static Vector4 border { get; } = new(0.235f, 0.25f, 0.285f, C_OPACITY_EMPHASIZED); /// /// Gets the standard border shadow color. /// - public static Vector4 borderShadow { get; } = new(0f, 0f, 0f, opacityMedium); + public static Vector4 borderShadow { get; } = new(0f, 0f, 0f, C_OPACITY_MEDIUM); /// /// Gets the standard frame background. /// - public static Vector4 frame { get; } = new(0.145f, 0.155f, 0.175f, opacityOpaque); + public static Vector4 frame { get; } = new(0.145f, 0.155f, 0.175f, C_OPACITY_OPAQUE); /// /// Gets the hovered frame background. /// - public static Vector4 frameHovered { get; } = new(0.205f, 0.218f, 0.245f, opacityOpaque); + public static Vector4 frameHovered { get; } = new(0.205f, 0.218f, 0.245f, C_OPACITY_OPAQUE); /// /// Gets the active frame background. /// - public static Vector4 frameActive { get; } = new(0.275f, 0.258f, 0.36f, opacityOpaque); + public static Vector4 frameActive { get; } = new(0.275f, 0.258f, 0.36f, C_OPACITY_OPAQUE); /// /// Gets the inactive title background. /// - public static Vector4 title { get; } = new(0.075f, 0.081f, 0.092f, opacityOpaque); + public static Vector4 title { get; } = new(0.075f, 0.081f, 0.092f, C_OPACITY_OPAQUE); /// /// Gets the active title background. /// - public static Vector4 titleActive { get; } = new(0.115f, 0.123f, 0.139f, opacityOpaque); + public static Vector4 titleActive { get; } = new(0.115f, 0.123f, 0.139f, C_OPACITY_OPAQUE); /// /// Gets the collapsed title background. /// - public static Vector4 titleCollapsed { get; } = new(0.065f, 0.070f, 0.080f, opacityOpaque); + public static Vector4 titleCollapsed { get; } = new(0.065f, 0.07f, 0.08f, C_OPACITY_OPAQUE); /// /// Gets the standard scrollbar thumb. /// - public static Vector4 scrollbarGrab { get; } = new(0.30f, 0.32f, 0.36f, opacityEmphasized); + public static Vector4 scrollbarGrab { get; } = new(0.3f, 0.32f, 0.36f, C_OPACITY_EMPHASIZED); /// /// Gets the hovered scrollbar thumb. /// - public static Vector4 scrollbarGrabHovered { get; } = new(0.42f, 0.44f, 0.49f, opacityNearOpaque); + public static Vector4 scrollbarGrabHovered { get; } = new(0.42f, 0.44f, 0.49f, C_OPACITY_NEAR_OPAQUE); /// /// Gets the active scrollbar thumb. /// - public static Vector4 scrollbarGrabActive { get; } = new(0.55f, 0.57f, 0.63f, opacityOpaque); + public static Vector4 scrollbarGrabActive { get; } = new(0.55f, 0.57f, 0.63f, C_OPACITY_OPAQUE); /// /// Gets the standard accent color. /// - public static Vector4 accent { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, opacityStrong); + public static Vector4 accent { get; } = new(0.61960787f, 0.5764706f, 0.76862746f, C_OPACITY_STRONG); /// /// Gets the hovered accent color. /// - public static Vector4 accentHovered { get; } = new(0.7372549f, 0.69411767f, 0.8862745f, opacityStrong); + public static Vector4 accentHovered { get; } = new(0.7372549f, 0.69411767f, 0.8862745f, C_OPACITY_STRONG); /// /// Gets the active accent color. /// - public static Vector4 accentActive { get; } = new(0.8156863f, 0.77254903f, 0.9647059f, opacityStrong); + public static Vector4 accentActive { get; } = new(0.8156863f, 0.77254903f, 0.9647059f, C_OPACITY_STRONG); /// /// Gets the standard tab color. /// - public static Vector4 tab { get; } = new(0.105f, 0.112f, 0.125f, opacityOpaque); + public static Vector4 tab { get; } = new(0.105f, 0.112f, 0.125f, C_OPACITY_OPAQUE); /// /// Gets the hovered tab color. /// - public static Vector4 tabHovered { get; } = new(0.19f, 0.20f, 0.225f, opacityOpaque); + public static Vector4 tabHovered { get; } = new(0.19f, 0.2f, 0.225f, C_OPACITY_OPAQUE); /// /// Gets the selected tab color. /// - public static Vector4 tabSelected { get; } = new(0.17f, 0.176f, 0.20f, opacityOpaque); + public static Vector4 tabSelected { get; } = new(0.17f, 0.176f, 0.2f, C_OPACITY_OPAQUE); /// /// Gets the dimmed tab color. /// - public static Vector4 tabDimmed { get; } = new(0.082f, 0.088f, 0.10f, opacityOpaque); + public static Vector4 tabDimmed { get; } = new(0.082f, 0.088f, 0.1f, C_OPACITY_OPAQUE); /// /// Gets the selected dimmed tab color. /// - public static Vector4 tabDimmedSelected { get; } = new(0.135f, 0.142f, 0.16f, opacityOpaque); + public static Vector4 tabDimmedSelected { get; } = new(0.135f, 0.142f, 0.16f, C_OPACITY_OPAQUE); /// /// Gets the selected tab overline color. /// - public static Vector4 tabSelectedOverline { get; } = new(0.72f, 0.66f, 0.90f, opacityOpaque); + public static Vector4 tabSelectedOverline { get; } = new(0.72f, 0.66f, 0.9f, C_OPACITY_OPAQUE); /// /// Gets the table header background. /// - public static Vector4 tableHeader { get; } = new(0.1882353f, 0.1882353f, 0.2f, opacityOpaque); + public static Vector4 tableHeader { get; } = new(0.1882353f, 0.1882353f, 0.2f, C_OPACITY_OPAQUE); /// /// Gets the strong table border. /// - public static Vector4 tableBorderStrong { get; } = new(0.245f, 0.258f, 0.29f, opacityEmphasized); + public static Vector4 tableBorderStrong { get; } = new(0.245f, 0.258f, 0.29f, C_OPACITY_EMPHASIZED); /// /// Gets the light table border. /// - public static Vector4 tableBorderLight { get; } = new(0.205f, 0.215f, 0.245f, opacityStrong); + public static Vector4 tableBorderLight { get; } = new(0.205f, 0.215f, 0.245f, C_OPACITY_STRONG); /// /// Gets the alternate table row background. /// - public static Vector4 tableRowAlternate { get; } = new(1f, 1f, 1f, opacityFaint); + public static Vector4 tableRowAlternate { get; } = new(1f, 1f, 1f, C_OPACITY_FAINT); /// /// Gets the standard drag target color. /// - public static Vector4 dragDropTarget { get; } = new(1f, 1f, 0f, opacityNearOpaque); + public static Vector4 dragDropTarget { get; } = new(1f, 1f, 0f, C_OPACITY_NEAR_OPAQUE); /// /// Gets navigation highlight color. /// - public static Vector4 navigationHighlight { get; } = new(1f, 1f, 1f, opacityProminent); + public static Vector4 navigationHighlight { get; } = new(1f, 1f, 1f, C_OPACITY_PROMINENT); /// /// Gets navigation dim background. /// - public static Vector4 navigationDim { get; } = new(0.8f, 0.8f, 0.8f, opacitySoft); + public static Vector4 navigationDim { get; } = new(0.8f, 0.8f, 0.8f, C_OPACITY_SOFT); /// /// Gets modal dim background. /// - public static Vector4 modalDim { get; } = new(0.8f, 0.8f, 0.8f, opacityMuted); + public static Vector4 modalDim { get; } = new(0.8f, 0.8f, 0.8f, C_OPACITY_MUTED); /// /// Gets card header background. /// - public static Vector4 cardHeader { get; } = new(0.17f, 0.18f, 0.205f, opacityOpaque); + public static Vector4 cardHeader { get; } = new(0.17f, 0.18f, 0.205f, C_OPACITY_OPAQUE); /// /// Gets the persistent target header background. /// - public static Vector4 targetHeader { get; } = new(0.14f, 0.14f, 0.16f, opacityOpaque); + public static Vector4 targetHeader { get; } = new(0.14f, 0.14f, 0.16f, C_OPACITY_OPAQUE); /// /// Gets the persistent target header border. /// - public static Vector4 targetHeaderBorder { get; } = new(0.30f, 0.29f, 0.34f, opacityOpaque); + public static Vector4 targetHeaderBorder { get; } = new(0.3f, 0.29f, 0.34f, C_OPACITY_OPAQUE); /// /// Gets card body background. /// - public static Vector4 cardBody { get; } = new(0.12f, 0.12f, 0.14f, opacityOpaque); + public static Vector4 cardBody { get; } = new(0.12f, 0.12f, 0.14f, C_OPACITY_OPAQUE); /// /// Gets card body border. /// - public static Vector4 cardBodyBorder { get; } = new(0.28f, 0.27f, 0.32f, opacityOpaque); + public static Vector4 cardBodyBorder { get; } = new(0.28f, 0.27f, 0.32f, C_OPACITY_OPAQUE); /// /// Gets the outline color of framed sections. /// - public static Vector4 sectionBorder { get; } = new(0.34f, 0.33f, 0.39f, opacityOpaque); + public static Vector4 sectionBorder { get; } = new(0.34f, 0.33f, 0.39f, C_OPACITY_OPAQUE); /// /// Gets disabled card text. /// - public static Vector4 cardDisabledText { get; } = new(0.52f, 0.52f, 0.54f, opacityOpaque); + public static Vector4 cardDisabledText { get; } = new(0.52f, 0.52f, 0.54f, C_OPACITY_OPAQUE); /// /// Gets card disclosure hover background. /// - public static Vector4 cardDisclosureHovered { get; } = new(0.24f, 0.22f, 0.31f, opacityOpaque); + public static Vector4 cardDisclosureHovered { get; } = new(0.24f, 0.22f, 0.31f, C_OPACITY_OPAQUE); /// /// Gets compact control hover color. /// - public static Vector4 compactControlHovered { get; } = new(0.74f, 0.70f, 0.90f, opacityOpaque); + public static Vector4 compactControlHovered { get; } = new(0.74f, 0.7f, 0.9f, C_OPACITY_OPAQUE); /// /// Gets the deepest collection background. @@ -333,94 +332,94 @@ public static unsafe class EditorPalette /// /// Gets the primary collection row background. /// - public static Vector4 collectionRow { get; } = new(0.115f, 0.123f, 0.137f, opacityOpaque); + public static Vector4 collectionRow { get; } = new(0.115f, 0.123f, 0.137f, C_OPACITY_OPAQUE); /// /// Gets the alternate collection row background. /// - public static Vector4 collectionRowAlternate { get; } = new(0.135f, 0.144f, 0.160f, opacityOpaque); + public static Vector4 collectionRowAlternate { get; } = new(0.135f, 0.144f, 0.16f, C_OPACITY_OPAQUE); /// /// Gets the content field background. /// - public static Vector4 contentField { get; } = new(0.235f, 0.22f, 0.27f, opacityOpaque); + public static Vector4 contentField { get; } = new(0.235f, 0.22f, 0.27f, C_OPACITY_OPAQUE); /// /// Gets the content border. /// - public static Vector4 contentBorder { get; } = new(0.31f, 0.30f, 0.35f, opacityOpaque); + public static Vector4 contentBorder { get; } = new(0.31f, 0.3f, 0.35f, C_OPACITY_OPAQUE); /// /// Gets the soft content border. /// - public static Vector4 contentBorderSoft { get; } = new(0.24f, 0.24f, 0.27f, opacityOpaque); + public static Vector4 contentBorderSoft { get; } = new(0.24f, 0.24f, 0.27f, C_OPACITY_OPAQUE); /// /// Gets the content text color. /// - public static Vector4 contentText { get; } = new(0.86f, 0.86f, 0.86f, opacityOpaque); + public static Vector4 contentText { get; } = new(0.86f, 0.86f, 0.86f, C_OPACITY_OPAQUE); /// /// Gets the muted content text color. /// - public static Vector4 contentTextMuted { get; } = new(0.54f, 0.54f, 0.56f, opacityOpaque); + public static Vector4 contentTextMuted { get; } = new(0.54f, 0.54f, 0.56f, C_OPACITY_OPAQUE); /// /// Gets the subdued contextual text color used by paths and origin hints. /// - public static Vector4 contextText { get; } = new(0.86f, 0.86f, 0.86f, opacityMedium); + public static Vector4 contextText { get; } = new(0.86f, 0.86f, 0.86f, C_OPACITY_MEDIUM); /// /// Gets the opaque content accent. /// - public static Vector4 contentAccent { get; } = new(0.50f, 0.45f, 0.62f, opacityOpaque); + public static Vector4 contentAccent { get; } = new(0.5f, 0.45f, 0.62f, C_OPACITY_OPAQUE); /// - /// Gets a hover treatment derived from a base theme color. + /// Gets the guide color of reusable tree controls. /// - /// - /// The base color blended toward the palette text color using the standard hover amount. - /// - /// - /// The color consumed by get hovered; ownership remains with the caller unless explicitly stated otherwise. - /// - public static Vector4 GetHovered(Vector4 color) => Lerp(color, text, 0.16f); + public static Vector4 treeGuide { get; } = new(0.62f, 0.62f, 0.66f, C_OPACITY_OPAQUE); /// - /// Gets an active treatment derived from a base theme color. + /// Gets X axis color. /// - /// - /// The base color blended toward the palette text color using the standard active amount. - /// - /// - /// The color consumed by get active; ownership remains with the caller unless explicitly stated otherwise. - /// - public static Vector4 GetActive(Vector4 color) => Lerp(color, text, 0.24f); + public static Vector4 axisX { get; } = new(0.76f, 0.2f, 0.22f, C_OPACITY_OPAQUE); /// - /// Gets the guide color of reusable tree controls. + /// Gets Y axis color. /// - public static Vector4 treeGuide { get; } = new(0.62f, 0.62f, 0.66f, opacityOpaque); + public static Vector4 axisY { get; } = new(0.16f, 0.62f, 0.3f, C_OPACITY_OPAQUE); /// - /// Gets X axis color. + /// Gets Z axis color. /// - public static Vector4 axisX { get; } = new(0.76f, 0.20f, 0.22f, opacityOpaque); + public static Vector4 axisZ { get; } = new(0.2f, 0.34f, 0.78f, C_OPACITY_OPAQUE); /// - /// Gets Y axis color. + /// Gets W axis color. /// - public static Vector4 axisY { get; } = new(0.16f, 0.62f, 0.30f, opacityOpaque); + public static Vector4 axisW { get; } = new(0.48f, 0.48f, 0.5f, C_OPACITY_OPAQUE); /// - /// Gets Z axis color. + /// Gets a hover treatment derived from a base theme color. /// - public static Vector4 axisZ { get; } = new(0.20f, 0.34f, 0.78f, opacityOpaque); + /// + /// The color consumed by get hovered; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The base color blended toward the palette text color using the standard hover amount. + /// + public static Vector4 GetHovered(Vector4 color) => Lerp(color, text, 0.16f); /// - /// Gets W axis color. + /// Gets an active treatment derived from a base theme color. /// - public static Vector4 axisW { get; } = new(0.48f, 0.48f, 0.50f, opacityOpaque); + /// + /// The color consumed by get active; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The base color blended toward the palette text color using the standard active amount. + /// + public static Vector4 GetActive(Vector4 color) => Lerp(color, text, 0.24f); /// /// Linearly interpolates two palette colors using a clamped amount. @@ -447,9 +446,27 @@ float amount from.X + (to.X - from.X) * value, from.Y + (to.Y - from.Y) * value, from.Z + (to.Z - from.Z) * value, - from.W + (to.W - from.W) * value); + from.W + (to.W - from.W) * value + ); } + /// + /// Returns a theme color with a caller-selected opacity, normally one of the shared opacity levels. + /// + /// + /// Base RGB color. + /// + /// + /// Replacement alpha in the inclusive zero-to-one range. + /// + /// + /// The validated vector4 that represents the completed operation. + /// + public static Vector4 WithOpacity( + Vector4 color, + float opacity + ) => new(color.X, color.Y, color.Z, Math.Clamp(opacity, C_OPACITY_NONE, C_OPACITY_OPAQUE)); + internal static void Apply(ImGuiStyle* style) { style->Colors[(int)ImGuiCol.Text] = ImGui.ToNative(text); @@ -466,7 +483,7 @@ internal static void Apply(ImGuiStyle* style) style->Colors[(int)ImGuiCol.TitleBgActive] = ImGui.ToNative(titleActive); style->Colors[(int)ImGuiCol.TitleBgCollapsed] = ImGui.ToNative(titleCollapsed); style->Colors[(int)ImGuiCol.MenuBarBg] = ImGui.ToNative(transparent); - style->Colors[(int)ImGuiCol.ScrollbarBg] = ImGui.ToNative(WithOpacity(frame, opacityNone)); + style->Colors[(int)ImGuiCol.ScrollbarBg] = ImGui.ToNative(WithOpacity(frame, C_OPACITY_NONE)); style->Colors[(int)ImGuiCol.ScrollbarGrab] = ImGui.ToNative(scrollbarGrab); style->Colors[(int)ImGuiCol.ScrollbarGrabHovered] = ImGui.ToNative(scrollbarGrabHovered); style->Colors[(int)ImGuiCol.ScrollbarGrabActive] = ImGui.ToNative(scrollbarGrabActive); @@ -507,22 +524,4 @@ internal static void Apply(ImGuiStyle* style) style->Colors[(int)ImGuiCol.ModalWindowDimBg] = ImGui.ToNative(modalDim); style->Colors[(int)ImGuiCol.DockingPreview] = ImGui.ToNative(accentActive); } - - /// - /// Returns a theme color with a caller-selected opacity, normally one of the shared opacity levels. - /// - /// - /// Base RGB color. - /// - /// - /// Replacement alpha in the inclusive zero-to-one range. - /// - /// - /// The validated vector4 that represents the completed operation. - /// - public static Vector4 WithOpacity( - Vector4 color, - float opacity - ) - => new(color.X, color.Y, color.Z, Math.Clamp(opacity, opacityNone, opacityOpaque)); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs index 21146dd06..8216cce65 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs @@ -21,14 +21,14 @@ public sealed class EditorStyleMetrics /// /// Defines the largest supported editor UI zoom. /// - public const float C_MAX_ZOOM = 1.50f; + public const float C_MAX_ZOOM = 1.5f; /// /// Defines one keyboard or menu zoom increment. /// - public const float C_ZOOM_STEP = 0.10f; + public const float C_ZOOM_STEP = 0.1f; - private readonly WeakReference? m_owner; + private readonly WeakReference? m_owner; private float m_requestedZoom = 1f; private bool m_requestedCompactMode; private float m_zoom = 1f; @@ -37,9 +37,9 @@ public sealed class EditorStyleMetrics /// /// Creates independent metrics whose changes apply immediately without a native context. /// - public EditorStyleMetrics() { } + public EditorStyleMetrics() {} - internal EditorStyleMetrics(EditorUiSession owner) + internal EditorStyleMetrics(EditorUISession owner) { ArgumentNullException.ThrowIfNull(owner); m_owner = new(owner); @@ -60,100 +60,20 @@ internal EditorStyleMetrics(EditorUiSession owner) /// public float trendHeight => Scale(64f); - /// - /// Requests comfortable or compact density without changing an active session frame. - /// - /// - /// for compact density. - /// - /// - /// when the requested density changed; owned drawing applies it at the next frame preparation. - /// - /// - /// The owning session has retired or is no longer available. - /// - /// - /// The caller is not the owning session's thread. - /// - public bool SetCompactMode(bool value) - { - bool defer = ShouldDeferChanges(); - bool changed = m_requestedCompactMode != value; - m_requestedCompactMode = value; - if (!defer) - CommitPending(); - return changed; - } - - /// - /// Requests a bounded zoom without changing metrics partway through an owned native frame. - /// - /// - /// The requested UI zoom multiplier. - /// - /// - /// when the requested zoom changed; owned drawing applies it at the next frame preparation. - /// - /// - /// Thrown when is not finite. - /// - /// - /// The owning session has retired or is no longer available. - /// - /// - /// The caller is not the owning session's thread. - /// - public bool SetZoom(float value) - { - if (!float.IsFinite(value)) - throw new ArgumentOutOfRangeException(nameof(value), value, "UI zoom must be finite."); - bool defer = ShouldDeferChanges(); - float clamped = Math.Clamp(value, C_MIN_ZOOM, C_MAX_ZOOM); - bool changed = MathF.Abs(m_requestedZoom - clamped) >= 0.0001f; - m_requestedZoom = clamped; - if (!defer) - CommitPending(); - return changed; - } - - /// - /// Increases editor UI zoom by one bounded increment. - /// - /// - /// when the requested zoom changed. - /// - public bool ZoomIn() => SetZoom(m_requestedZoom + C_ZOOM_STEP); - - /// - /// Decreases editor UI zoom by one bounded increment. - /// - /// - /// when the requested zoom changed. - /// - public bool ZoomOut() => SetZoom(m_requestedZoom - C_ZOOM_STEP); - - /// - /// Restores the baseline editor UI zoom. - /// - /// - /// when the requested zoom changed. - /// - public bool ResetZoom() => SetZoom(1f); - /// /// Gets global content scale. /// - public float fontScale => Scale(m_compactMode ? 1.10f : 1.20f); + public float fontScale => Scale(m_compactMode ? 1.1f : 1.2f); /// /// Gets disabled content opacity. /// - public float disabledAlpha => EditorPalette.opacityMedium; + public float disabledAlpha => EditorPalette.C_OPACITY_MEDIUM; /// /// Gets standard window padding. /// - public Vector2 windowPadding => ScaleVector(m_compactMode ? new(5f, 4f) : new(8f, 7f)); + public Vector2 windowPadding => ScaleVector(m_compactMode ? new Vector2(5f, 4f) : new Vector2(8f, 7f)); /// /// Gets standard window rounding. @@ -168,38 +88,38 @@ public bool SetZoom(float value) /// /// Gets minimum window size. /// - public Vector2 windowMinimumSize => ScaleVector(new(30f, 30f)); + public Vector2 windowMinimumSize => ScaleVector(new Vector2(30f, 30f)); /// /// Gets standard frame padding. /// - public Vector2 framePadding => ScaleVector(m_compactMode ? new(4f, 1f) : new(7f, 3f)); + public Vector2 framePadding => ScaleVector(m_compactMode ? new Vector2(4f, 1f) : new Vector2(7f, 3f)); /// /// Gets the frame padding used while docked panel tabs are laid out. /// - public Vector2 panelTabFramePadding => ScaleVector(m_compactMode ? new(4f, 3f) : new(7f, 4f)); + public Vector2 panelTabFramePadding => ScaleVector(m_compactMode ? new Vector2(4f, 3f) : new Vector2(7f, 4f)); /// /// Gets the uniform content padding of editor context menus. /// - public Vector2 menuWindowPadding => ScaleVector(new(8f, 6f)); + public Vector2 menuWindowPadding => ScaleVector(new Vector2(8f, 6f)); /// /// Gets the uniform item padding of editor context menus. /// - public Vector2 menuFramePadding => ScaleVector(new(8f, 3f)); + public Vector2 menuFramePadding => ScaleVector(new Vector2(8f, 3f)); /// /// Gets the compact padding used by the search field at the top of editor context menus. /// Its vertical padding matches the half-spacing that menu entries add above and below a line. /// - public Vector2 menuSearchFramePadding => ScaleVector(new(8f, 1f)); + public Vector2 menuSearchFramePadding => ScaleVector(new Vector2(8f, 1f)); /// /// Gets the uniform spacing between editor context-menu items. /// - public Vector2 menuItemSpacing => ScaleVector(new(4f, 2f)); + public Vector2 menuItemSpacing => ScaleVector(new Vector2(4f, 2f)); /// /// Gets editor context-menu corner rounding. @@ -214,22 +134,22 @@ public bool SetZoom(float value) /// /// Gets compact frame padding. /// - public Vector2 compactFramePadding => ScaleVector(new(4f, 1f)); + public Vector2 compactFramePadding => ScaleVector(new Vector2(4f, 1f)); /// /// Gets the compact inner padding of inline rename fields. /// - public Vector2 inlineRenameFramePadding => ScaleVector(new(4f, 0f)); + public Vector2 inlineRenameFramePadding => ScaleVector(new Vector2(4f, 0f)); /// /// Gets toolbar frame padding. /// - public Vector2 toolbarFramePadding => ScaleVector(new(5f, 1f)); + public Vector2 toolbarFramePadding => ScaleVector(new Vector2(5f, 1f)); /// /// Gets breadcrumb frame padding. /// - public Vector2 breadcrumbFramePadding => ScaleVector(new(6f, 1f)); + public Vector2 breadcrumbFramePadding => ScaleVector(new Vector2(6f, 1f)); /// /// Gets standard frame rounding. @@ -239,22 +159,22 @@ public bool SetZoom(float value) /// /// Gets standard item spacing. /// - public Vector2 itemSpacing => ScaleVector(m_compactMode ? new(4f, 2f) : new(6f, 4f)); + public Vector2 itemSpacing => ScaleVector(m_compactMode ? new Vector2(4f, 2f) : new Vector2(6f, 4f)); /// /// Gets compact vertical item spacing. /// - public Vector2 compactItemSpacing => ScaleVector(new(4f, 2f)); + public Vector2 compactItemSpacing => ScaleVector(new Vector2(4f, 2f)); /// /// Gets standard inner item spacing. /// - public Vector2 itemInnerSpacing => ScaleVector(m_compactMode ? new(3f, 3f) : new(5f, 4f)); + public Vector2 itemInnerSpacing => ScaleVector(m_compactMode ? new Vector2(3f, 3f) : new Vector2(5f, 4f)); /// /// Gets standard table cell padding. /// - public Vector2 cellPadding => ScaleVector(m_compactMode ? new(3f, 1f) : new(5f, 3f)); + public Vector2 cellPadding => ScaleVector(m_compactMode ? new Vector2(3f, 1f) : new Vector2(5f, 3f)); /// /// Gets tree indentation. @@ -299,7 +219,7 @@ public bool SetZoom(float value) /// /// Gets the inner padding of the persistent target header. /// - public Vector2 targetHeaderPadding => ScaleVector(new(6f, 4f)); + public Vector2 targetHeaderPadding => ScaleVector(new Vector2(6f, 4f)); /// /// Gets spacing between the two rows of the persistent target header. @@ -314,22 +234,22 @@ public bool SetZoom(float value) /// /// Gets card body padding. /// - public Vector2 cardBodyPadding => ScaleVector(new(7f, 5f)); + public Vector2 cardBodyPadding => ScaleVector(new Vector2(7f, 5f)); /// /// Gets card header padding. /// - public Vector2 cardHeaderPadding => ScaleVector(new(4f, 1f)); + public Vector2 cardHeaderPadding => ScaleVector(new Vector2(4f, 1f)); /// /// Gets the shared padding around separator-style section titles. /// - public Vector2 sectionHeaderPadding => ScaleVector(new(20f, 3f)); + public Vector2 sectionHeaderPadding => ScaleVector(new Vector2(20f, 3f)); /// /// Gets the inner padding of a framed Inspector section. /// - public Vector2 sectionPadding => ScaleVector(new(7f, 5f)); + public Vector2 sectionPadding => ScaleVector(new Vector2(7f, 5f)); /// /// Gets the gap between an Inspector section legend and its interrupted top border. @@ -364,7 +284,7 @@ public bool SetZoom(float value) /// /// Gets property label width ratio. /// - public float propertyLabelRatio => 0.40f; + public float propertyLabelRatio => 0.4f; /// /// Gets the default width of searchable editor popups. @@ -389,7 +309,7 @@ public bool SetZoom(float value) /// /// Gets the inner padding of compact colored label chips. /// - public Vector2 labelChipPadding => ScaleVector(new(6f, 1f)); + public Vector2 labelChipPadding => ScaleVector(new Vector2(6f, 1f)); /// /// Gets the corner rounding of compact colored label chips. @@ -399,7 +319,7 @@ public bool SetZoom(float value) /// /// Gets the compact inner padding of outlined type badges. /// - public Vector2 typeBadgePadding => ScaleVector(new(5f, 1f)); + public Vector2 typeBadgePadding => ScaleVector(new Vector2(5f, 1f)); /// /// Gets the corner rounding of outlined type badges. @@ -496,6 +416,92 @@ public bool SetZoom(float value) /// public float textDecorationOffset => Scale(2f); + /// + /// Requests comfortable or compact density without changing an active session frame. + /// + /// + /// for compact density. + /// + /// + /// when the requested density changed; owned drawing applies it at the next frame preparation. + /// + /// + /// The owning session has retired or is no longer available. + /// + /// + /// The caller is not the owning session's thread. + /// + public bool SetCompactMode(bool value) + { + bool defer = ShouldDeferChanges(); + bool changed = m_requestedCompactMode != value; + m_requestedCompactMode = value; + if (!defer) + { + CommitPending(); + } + return changed; + } + + /// + /// Requests a bounded zoom without changing metrics partway through an owned native frame. + /// + /// + /// The requested UI zoom multiplier. + /// + /// + /// when the requested zoom changed; owned drawing applies it at the next frame preparation. + /// + /// + /// Thrown when is not finite. + /// + /// + /// The owning session has retired or is no longer available. + /// + /// + /// The caller is not the owning session's thread. + /// + public bool SetZoom(float value) + { + if (!float.IsFinite(value)) + { + throw new ArgumentOutOfRangeException(nameof(value), value, "UI zoom must be finite."); + } + bool defer = ShouldDeferChanges(); + float clamped = Math.Clamp(value, C_MIN_ZOOM, C_MAX_ZOOM); + bool changed = MathF.Abs(m_requestedZoom - clamped) >= 0.0001f; + m_requestedZoom = clamped; + if (!defer) + { + CommitPending(); + } + return changed; + } + + /// + /// Increases editor UI zoom by one bounded increment. + /// + /// + /// when the requested zoom changed. + /// + public bool ZoomIn() => SetZoom(m_requestedZoom + C_ZOOM_STEP); + + /// + /// Decreases editor UI zoom by one bounded increment. + /// + /// + /// when the requested zoom changed. + /// + public bool ZoomOut() => SetZoom(m_requestedZoom - C_ZOOM_STEP); + + /// + /// Restores the baseline editor UI zoom. + /// + /// + /// when the requested zoom changed. + /// + public bool ResetZoom() => SetZoom(1f); + internal void CommitPending() { m_zoom = m_requestedZoom; @@ -505,9 +511,13 @@ internal void CommitPending() private bool ShouldDeferChanges() { if (m_owner is null) + { return false; - if (!m_owner.TryGetTarget(out EditorUiSession? owner)) - throw new ObjectDisposedException(nameof(EditorUiSession)); + } + if (!m_owner.TryGetTarget(out EditorUISession? owner)) + { + throw new ObjectDisposedException(nameof(EditorUISession)); + } return owner.shouldDeferStyleChanges; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUILayout.cs similarity index 65% rename from src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs rename to src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUILayout.cs index f26d83e9c..ce7469466 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUILayout.cs @@ -2,53 +2,61 @@ using Inno.Native.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies the presentation metrics needed by custom layouts without retaining native style memory. /// -public readonly struct EditorUiLayout +public readonly struct EditorUILayout { + internal unsafe EditorUILayout(ImGuiStyle* style) + { + this.itemSpacing = ImGui.FromNative(style->ItemSpacing); + this.windowPadding = ImGui.FromNative(style->WindowPadding); + this.cellPadding = ImGui.FromNative(style->CellPadding); + this.itemInnerSpacing = ImGui.FromNative(style->ItemInnerSpacing); + this.framePadding = ImGui.FromNative(style->FramePadding); + this.dockingSeparatorSize = style->DockingSeparatorSize; + this.scrollbarSize = style->ScrollbarSize; + this.frameRounding = style->FrameRounding; + } + /// /// Gets spacing between neighboring controls. /// public Vector2 itemSpacing { get; } + /// /// Gets the current window inset. /// public Vector2 windowPadding { get; } + /// /// Gets table cell padding. /// public Vector2 cellPadding { get; } + /// /// Gets spacing between parts of a compound control. /// public Vector2 itemInnerSpacing { get; } + /// /// Gets padding inside a control. /// public Vector2 framePadding { get; } + /// /// Gets dock splitter thickness. /// public float dockingSeparatorSize { get; } + /// /// Gets scrollbar width. /// public float scrollbarSize { get; } + /// /// Gets control corner radius. /// public float frameRounding { get; } - - internal unsafe EditorUiLayout(ImGuiStyle* style) - { - itemSpacing = ImGui.FromNative(style->ItemSpacing); - windowPadding = ImGui.FromNative(style->WindowPadding); - cellPadding = ImGui.FromNative(style->CellPadding); - itemInnerSpacing = ImGui.FromNative(style->ItemInnerSpacing); - framePadding = ImGui.FromNative(style->FramePadding); - dockingSeparatorSize = style->DockingSeparatorSize; - scrollbarSize = style->ScrollbarSize; - frameRounding = style->FrameRounding; - } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs index 511dc310f..145c56bb6 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs @@ -1,8 +1,12 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using HostIcon = Inno.Adapter.Presentation.ImGui.ImGuiIcon; + namespace Inno.Editor.ImGui; + /// /// Describes the host's complete standard glyph vocabulary as immutable presentation values. /// @@ -11,5 +15,12 @@ public static class EditorIconCatalog /// /// Gets all named glyphs supplied by the installed UI font, in deterministic name order. /// - public static IReadOnlyList<(string Name, string Glyph)> standard { get; } = System.Array.AsReadOnly(typeof(Inno.Adapter.Presentation.ImGui.ImGuiIcon).GetFields(BindingFlags.Public | BindingFlags.Static).Where(static field => field.IsLiteral && field.FieldType == typeof(string)).Select(static field => (field.Name, (string)field.GetRawConstantValue()!)).OrderBy(static value => value.Name, System.StringComparer.Ordinal).ToArray()); + public static IReadOnlyList<(string name, string glyph)> standard { get; } = Array.AsReadOnly( + typeof(HostIcon) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(static field => field.IsLiteral && field.FieldType == typeof(string)) + .Select(static field => (name: field.Name, glyph: (string)field.GetRawConstantValue()!)) + .OrderBy(static value => value.name, StringComparer.Ordinal) + .ToArray() + ); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs index f65210df6..d12b4a6f2 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs @@ -1,28 +1,11 @@ using System; -using NativeImGui = Inno.Native.ImGui.ImGui; + using HostFont = Inno.Adapter.Presentation.ImGui.ImGuiFont; +using HostScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; using HostStyle = Inno.Adapter.Presentation.ImGui.ImGuiFontStyle; +using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; -/// -/// Chooses composable font emphasis while leaving actual font ownership with the presentation host. -/// -[Flags] -public enum ImGuiFontStyle -{ - /// - /// Uses the ordinary face. - /// - Regular = 0, - /// - /// Emphasizes text with the bold face. - /// - Bold = 1, - /// - /// Emphasizes text with the italic face. - /// - Italic = 2 -} /// /// Uses the host's context-owned font catalog without exposing backend types to Editor features. @@ -40,7 +23,7 @@ public static unsafe class ImGuiFont /// public static bool IsAvailable(ImGuiFontStyle style) { - EditorUiSession.current.EnsureDrawing(); + EditorUISession.current.EnsureDrawing(); return HostFont.IsAvailable((HostStyle)style); } @@ -55,48 +38,29 @@ public static bool IsAvailable(ImGuiFontStyle style) /// public static ImGuiFontScope PushStyle(ImGuiFontStyle style) { - EditorUiSession session = EditorUiSession.current; + EditorUISession session = EditorUISession.current; session.EnsureDrawing(); - var scope = HostFont.PushStyle((HostStyle)style); + HostScope scope = HostFont.PushStyle((HostStyle)style); return new ImGuiFontScope(session, scope, NativeImGui.GetFrameCount(), NativeImGui.Raw.GetCurrentContext()->FontStack.Size); } } /// -/// Restores a font push only in its original session, frame and native stack position. +/// Chooses composable font emphasis while leaving actual font ownership with the presentation host. /// -public unsafe ref struct ImGuiFontScope : IDisposable +[Flags] +public enum ImGuiFontStyle { - private EditorUiSession? m_session; - private Inno.Adapter.Presentation.ImGui.ImGuiFontScope m_scope; - private readonly int m_frame; - private readonly int m_depth; - internal ImGuiFontScope( - EditorUiSession session, - Inno.Adapter.Presentation.ImGui.ImGuiFontScope scope, - int frame, - int depth - ) { - m_session = session; - m_scope = scope; - m_frame = frame; - m_depth = depth; - } - /// - /// Restores the preceding font after validating scope order; default and retired scopes are inert. + /// Uses the ordinary face. /// - /// - /// The scope is used in another context, frame or stack position. - /// - public void Dispose() - { - if (m_session is null) - return; - m_session.EnsureDrawing(); - if (NativeImGui.GetFrameCount() != m_frame || NativeImGui.Raw.GetCurrentContext()->FontStack.Size != m_depth) - throw new InvalidOperationException("Font scopes must retire in their original frame and reverse stack order."); - m_scope.Dispose(); - m_session = null; - } + Regular = 0, + /// + /// Emphasizes text with the bold face. + /// + Bold = 1, + /// + /// Emphasizes text with the italic face. + /// + Italic = 2 } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs new file mode 100644 index 000000000..5cceb3810 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs @@ -0,0 +1,50 @@ +using System; + +using HostScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; +using NativeImGui = Inno.Native.ImGui.ImGui; + +namespace Inno.Editor.ImGui; + +/// +/// Restores a font push only in its original session, frame and native stack position. +/// +public unsafe ref struct ImGuiFontScope : IDisposable +{ + private EditorUISession? m_session; + private HostScope m_scope; + private readonly int m_frame; + private readonly int m_depth; + + internal ImGuiFontScope( + EditorUISession session, + HostScope scope, + int frame, + int depth + ) { + m_session = session; + m_scope = scope; + m_frame = frame; + m_depth = depth; + } + + /// + /// Restores the preceding font after validating scope order; default and retired scopes are inert. + /// + /// + /// The scope is used in another context, frame or stack position. + /// + public void Dispose() + { + if (m_session is null) + { + return; + } + m_session.EnsureDrawing(); + if (NativeImGui.GetFrameCount() != m_frame || NativeImGui.Raw.GetCurrentContext()->FontStack.Size != m_depth) + { + throw new InvalidOperationException("Font scopes must retire in their original frame and reverse stack order."); + } + m_scope.Dispose(); + m_session = null; + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs index 17f59b64d..aafe25a55 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs @@ -1,6 +1,7 @@ using BackendIcon = Inno.Adapter.Presentation.ImGui.ImGuiIcon; namespace Inno.Editor.ImGui; + /// /// Provides the standard Editor glyph vocabulary; extension controls may also supply their own glyph text. /// @@ -9,178 +10,220 @@ public static class ImGuiIcon /// /// Gets the InnoEngine logo glyph available in every default Editor font style. /// - public const string Inno = BackendIcon.Inno; + public const string C_INNO = BackendIcon.Inno; /// /// Gets the angle left glyph used by standard Editor controls. /// - public const string AngleLeft = BackendIcon.AngleLeft; + public const string C_ANGLE_LEFT = BackendIcon.AngleLeft; + /// /// Gets the angle right glyph used by standard Editor controls. /// - public const string AngleRight = BackendIcon.AngleRight; + public const string C_ANGLE_RIGHT = BackendIcon.AngleRight; + /// /// Gets the arrow rotate left glyph used by standard Editor controls. /// - public const string ArrowRotateLeft = BackendIcon.ArrowRotateLeft; + public const string C_ARROW_ROTATE_LEFT = BackendIcon.ArrowRotateLeft; + /// /// Gets the arrows up down left right glyph used by standard Editor controls. /// - public const string ArrowsUpDownLeftRight = BackendIcon.ArrowsUpDownLeftRight; + public const string C_ARROWS_UP_DOWN_LEFT_RIGHT = BackendIcon.ArrowsUpDownLeftRight; + /// /// Gets the bug glyph used by standard Editor controls. /// - public const string Bug = BackendIcon.Bug; + public const string C_BUG = BackendIcon.Bug; + /// /// Gets the camera glyph used by standard Editor controls. /// - public const string Camera = BackendIcon.Camera; + public const string C_CAMERA = BackendIcon.Camera; + /// /// Gets the circle info glyph used by standard Editor controls. /// - public const string CircleInfo = BackendIcon.CircleInfo; + public const string C_CIRCLE_INFO = BackendIcon.CircleInfo; + /// /// Gets the circle question glyph used by standard Editor controls. /// - public const string CircleQuestion = BackendIcon.CircleQuestion; + public const string C_CIRCLE_QUESTION = BackendIcon.CircleQuestion; + /// /// Gets the circle xmark glyph used by standard Editor controls. /// - public const string CircleXmark = BackendIcon.CircleXmark; + public const string C_CIRCLE_XMARK = BackendIcon.CircleXmark; + /// /// Gets the cube glyph used by standard Editor controls. /// - public const string Cube = BackendIcon.Cube; + public const string C_CUBE = BackendIcon.Cube; + /// /// Gets the cubes glyph used by standard Editor controls. /// - public const string Cubes = BackendIcon.Cubes; + public const string C_CUBES = BackendIcon.Cubes; + /// /// Gets the dice d6 glyph used by standard Editor controls. /// - public const string DiceD6 = BackendIcon.DiceD6; + public const string C_DICE_D_6 = BackendIcon.DiceD6; + /// /// Gets the eye glyph used by standard Editor controls. /// - public const string Eye = BackendIcon.Eye; + public const string C_EYE = BackendIcon.Eye; + /// /// Gets the eye slash glyph used by standard Editor controls. /// - public const string EyeSlash = BackendIcon.EyeSlash; + public const string C_EYE_SLASH = BackendIcon.EyeSlash; + /// /// Gets the file glyph used by standard Editor controls. /// - public const string File = BackendIcon.File; + public const string C_FILE = BackendIcon.File; + /// /// Gets the file code glyph used by standard Editor controls. /// - public const string FileCode = BackendIcon.FileCode; + public const string C_FILE_CODE = BackendIcon.FileCode; + /// /// Gets the file lines glyph used by standard Editor controls. /// - public const string FileLines = BackendIcon.FileLines; + public const string C_FILE_LINES = BackendIcon.FileLines; + /// /// Gets the folder glyph used by standard Editor controls. /// - public const string Folder = BackendIcon.Folder; + public const string C_FOLDER = BackendIcon.Folder; + /// /// Gets the forward step glyph used by standard Editor controls. /// - public const string ForwardStep = BackendIcon.ForwardStep; + public const string C_FORWARD_STEP = BackendIcon.ForwardStep; + /// /// Gets the gears glyph used by standard Editor controls. /// - public const string Gears = BackendIcon.Gears; + public const string C_GEARS = BackendIcon.Gears; + /// /// Gets the globe glyph used by standard Editor controls. /// - public const string Globe = BackendIcon.Globe; + public const string C_GLOBE = BackendIcon.Globe; + /// /// Gets the grip vertical glyph used by standard Editor controls. /// - public const string GripVertical = BackendIcon.GripVertical; + public const string C_GRIP_VERTICAL = BackendIcon.GripVertical; + /// /// Gets the layer group glyph used by standard Editor controls. /// - public const string LayerGroup = BackendIcon.LayerGroup; + public const string C_LAYER_GROUP = BackendIcon.LayerGroup; + /// /// Gets the lightbulb glyph used by standard Editor controls. /// - public const string Lightbulb = BackendIcon.Lightbulb; + public const string C_LIGHTBULB = BackendIcon.Lightbulb; + /// /// Gets the lock glyph used by standard Editor controls. /// - public const string Lock = BackendIcon.Lock; + public const string C_LOCK = BackendIcon.Lock; + /// /// Gets the lock open glyph used by standard Editor controls. /// - public const string LockOpen = BackendIcon.LockOpen; + public const string C_LOCK_OPEN = BackendIcon.LockOpen; + /// /// Gets the magnifying glass glyph used by standard Editor controls. /// - public const string MagnifyingGlass = BackendIcon.MagnifyingGlass; + public const string C_MAGNIFYING_GLASS = BackendIcon.MagnifyingGlass; + /// /// Gets the palette glyph used by standard Editor controls. /// - public const string Palette = BackendIcon.Palette; + public const string C_PALETTE = BackendIcon.Palette; + /// /// Gets the pause glyph used by standard Editor controls. /// - public const string Pause = BackendIcon.Pause; + public const string C_PAUSE = BackendIcon.Pause; + /// /// Gets the pen glyph used by standard Editor controls. /// - public const string Pen = BackendIcon.Pen; + public const string C_PEN = BackendIcon.Pen; + /// /// Gets the play glyph used by standard Editor controls. /// - public const string Play = BackendIcon.Play; + public const string C_PLAY = BackendIcon.Play; + /// /// Gets the plus glyph used by standard Editor controls. /// - public const string Plus = BackendIcon.Plus; + public const string C_PLUS = BackendIcon.Plus; + /// /// Gets the rotate glyph used by standard Editor controls. /// - public const string Rotate = BackendIcon.Rotate; + public const string C_ROTATE = BackendIcon.Rotate; + /// /// Gets the rupee sign glyph used by standard Editor controls. /// - public const string RupeeSign = BackendIcon.RupeeSign; + public const string C_RUPEE_SIGN = BackendIcon.RupeeSign; + /// /// Gets the rupiah sign glyph used by standard Editor controls. /// - public const string RupiahSign = BackendIcon.RupiahSign; + public const string C_RUPIAH_SIGN = BackendIcon.RupiahSign; + /// /// Gets the shader glyph used by standard Editor controls. /// - public const string Shader = BackendIcon.Shader; + public const string C_SHADER = BackendIcon.Shader; + /// /// Gets the skull crossbones glyph used by standard Editor controls. /// - public const string SkullCrossbones = BackendIcon.SkullCrossbones; + public const string C_SKULL_CROSSBONES = BackendIcon.SkullCrossbones; + /// /// Gets the stop glyph used by standard Editor controls. /// - public const string Stop = BackendIcon.Stop; + public const string C_STOP = BackendIcon.Stop; + /// /// Gets the triangle exclamation glyph used by standard Editor controls. /// - public const string TriangleExclamation = BackendIcon.TriangleExclamation; + public const string C_TRIANGLE_EXCLAMATION = BackendIcon.TriangleExclamation; + /// /// Gets the up down left right glyph used by standard Editor controls. /// - public const string UpDownLeftRight = BackendIcon.UpDownLeftRight; + public const string C_UP_DOWN_LEFT_RIGHT = BackendIcon.UpDownLeftRight; + /// /// Gets the up right and down left from center glyph used by standard Editor controls. /// - public const string UpRightAndDownLeftFromCenter = BackendIcon.UpRightAndDownLeftFromCenter; + public const string C_UP_RIGHT_AND_DOWN_LEFT_FROM_CENTER = BackendIcon.UpRightAndDownLeftFromCenter; + /// /// Gets the vector square glyph used by standard Editor controls. /// - public const string VectorSquare = BackendIcon.VectorSquare; + public const string C_VECTOR_SQUARE = BackendIcon.VectorSquare; + /// /// Gets the xmark glyph used by standard Editor controls. /// - public const string Xmark = BackendIcon.Xmark; + public const string C_XMARK = BackendIcon.Xmark; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs index a51621f2f..e7c160ddb 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs @@ -1,17 +1,19 @@ using System; +using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; -using System.Buffers; using System.Text.Unicode; using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + internal static unsafe class ImGuiUtf8Buffer { - private static readonly UTF8Encoding S_TEXT_ENCODING = new(false, true); + private static readonly UTF8Encoding TEXT_ENCODING = new(false, true); internal static Vector2 MeasureText( string text, @@ -20,40 +22,6 @@ float wrapWidth internal static void DrawText(string text) => _ = PresentText(text, 0f, measure: false); - [SkipLocalsInit] - [MethodImpl(MethodImplOptions.AggressiveOptimization)] - private static Vector2 PresentText( - string text, - float wrapWidth, - bool measure - ) { - ArgumentNullException.ThrowIfNull(text); - if (text.AsSpan().Contains('\0')) - throw new ArgumentException("Literal native text cannot contain zero code units.", nameof(text)); - int length = checked(S_TEXT_ENCODING.GetByteCount(text) + 1); - byte[]? rented = length > 1024 ? ArrayPool.Shared.Rent(length) : null; - Span buffer = rented is null ? stackalloc byte[length] : rented.AsSpan(0, length); - try - { - int count = S_TEXT_ENCODING.GetBytes(text.AsSpan(), buffer); - buffer[count] = 0; - fixed (byte* value = buffer) - { - ImVec2C size = default; - if (measure) - NativeImGui.Raw.CalcTextSize((sbyte*)value, (sbyte*)value + count, 0, wrapWidth, &size); - else - NativeImGui.Raw.TextUnformatted((sbyte*)value, (sbyte*)value + count); - return new Vector2(size.X, size.Y); - } - } - finally - { - if (rented is not null) - ArrayPool.Shared.Return(rented, clearArray: true); - } - } - internal static bool InputText( string label, string? hint, @@ -63,10 +31,19 @@ ImGuiInputTextFlags flags ) { ArgumentException.ThrowIfNullOrWhiteSpace(label); if (capacity is 0 or > int.MaxValue) + { throw new ArgumentOutOfRangeException(nameof(capacity)); - const ImGuiInputTextFlags callbacks = ImGuiInputTextFlags.CallbackCompletion | ImGuiInputTextFlags.CallbackHistory | ImGuiInputTextFlags.CallbackAlways | ImGuiInputTextFlags.CallbackCharFilter | ImGuiInputTextFlags.CallbackResize | ImGuiInputTextFlags.CallbackEdit; - if ((flags & callbacks) != 0) + } + const ImGuiInputTextFlags C_CALLBACKS = ImGuiInputTextFlags.CallbackCompletion + | ImGuiInputTextFlags.CallbackHistory + | ImGuiInputTextFlags.CallbackAlways + | ImGuiInputTextFlags.CallbackCharFilter + | ImGuiInputTextFlags.CallbackResize + | ImGuiInputTextFlags.CallbackEdit; + if ((flags & C_CALLBACKS) != 0) + { throw new ArgumentException("Managed text controls do not accept native callback flags.", nameof(flags)); + } int length = (int)capacity; byte[]? rented = length > 1024 ? ArrayPool.Shared.Rent(length) : null; Span buffer = rented is null ? stackalloc byte[length] : rented.AsSpan(0, length); @@ -79,22 +56,24 @@ ImGuiInputTextFlags flags using NativeStringLease nativeHint = Utf8Codec.EncodeNullTerminated(hint, allowsNull: true); fixed (byte* nativeBuffer = buffer) { - changed = hint is null ? NativeImGui.Raw.InputText( - (sbyte*)nativeLabel.pointer, - (sbyte*)nativeBuffer, - (uint)capacity, - (int)flags, - null, - null - ) != 0 : NativeImGui.Raw.InputTextWithHint( - (sbyte*)nativeLabel.pointer, - (sbyte*)nativeHint.pointer, - (sbyte*)nativeBuffer, - (uint)capacity, - (int)flags, - null, - null - ) != 0; + changed = hint is null + ? NativeImGui.Raw.InputText( + (sbyte*)nativeLabel.pointer, + (sbyte*)nativeBuffer, + (uint)capacity, + (int)flags, + null, + null + ) != 0 + : NativeImGui.Raw.InputTextWithHint( + (sbyte*)nativeLabel.pointer, + (sbyte*)nativeHint.pointer, + (sbyte*)nativeBuffer, + (uint)capacity, + (int)flags, + null, + null + ) != 0; } if (changed) @@ -108,7 +87,51 @@ ImGuiInputTextFlags flags finally { if (rented is not null) + { ArrayPool.Shared.Return(rented, clearArray: true); + } + } + } + + [SkipLocalsInit] + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private static Vector2 PresentText( + string text, + float wrapWidth, + bool measure + ) { + ArgumentNullException.ThrowIfNull(text); + if (text.AsSpan().Contains('\0')) + { + throw new ArgumentException("Literal native text cannot contain zero code units.", nameof(text)); + } + int length = checked(TEXT_ENCODING.GetByteCount(text) + 1); + byte[]? rented = length > 1024 ? ArrayPool.Shared.Rent(length) : null; + Span buffer = rented is null ? stackalloc byte[length] : rented.AsSpan(0, length); + try + { + int count = TEXT_ENCODING.GetBytes(text.AsSpan(), buffer); + buffer[count] = 0; + fixed (byte* value = buffer) + { + ImVec2C size = default; + if (measure) + { + NativeImGui.Raw.CalcTextSize((sbyte*)value, (sbyte*)value + count, 0, wrapWidth, &size); + } + else + { + NativeImGui.Raw.TextUnformatted((sbyte*)value, (sbyte*)value + count); + } + return new Vector2(size.X, size.Y); + } + } + finally + { + if (rented is not null) + { + ArrayPool.Shared.Return(rented, clearArray: true); + } } } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs new file mode 100644 index 000000000..c714a157c --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs @@ -0,0 +1,39 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Carries a measured dialog layout. Only its required extent is public; drawing mechanics remain owned by the widget. +/// +public readonly struct DialogLayout +{ + internal DialogLayout( + Vector2 size, + float textWidth, + float bodyHeight, + float bodyContentHeight, + float spacing, + float frameHeight, + float actionWidth + ) { + this.size = size; + this.textWidth = textWidth; + this.bodyHeight = bodyHeight; + this.bodyContentHeight = bodyContentHeight; + this.spacing = spacing; + this.frameHeight = frameHeight; + this.actionWidth = actionWidth; + } + + /// + /// Gets the content extent, excluding the window title, border and padding. + /// + public Vector2 size { get; } + + internal float textWidth { get; } + internal float bodyHeight { get; } + internal float bodyContentHeight { get; } + internal float spacing { get; } + internal float frameHeight { get; } + internal float actionWidth { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs index d99726228..e4b5509a9 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -54,12 +56,18 @@ public bool CollapsingCard( ArgumentNullException.ThrowIfNull(title); if (trailingControlWidth < 0f) { - throw new ArgumentOutOfRangeException(nameof(trailingControlWidth), trailingControlWidth, "Trailing control width cannot be negative."); + throw new ArgumentOutOfRangeException( + nameof(trailingControlWidth), + trailingControlWidth, + "Trailing control width cannot be negative." + ); } ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.SpanAvailWidth | ImGuiTreeNodeFlags.AllowOverlap | ImGuiTreeNodeFlags.OpenOnArrow; if (defaultOpen) + { flags |= ImGuiTreeNodeFlags.DefaultOpen; + } NativeImGui.PushStyleColor((int)(ImGuiCol.Header), EditorPalette.cardHeader); NativeImGui.PushStyleColor((int)(ImGuiCol.HeaderHovered), EditorPalette.cardHeader); NativeImGui.PushStyleColor((int)(ImGuiCol.HeaderActive), EditorPalette.cardHeader); @@ -74,8 +82,8 @@ public bool CollapsingCard( { Vector2 headerCursor = NativeImGui.GetCursorScreenPos(); (float cardLeft, float cardRight) = GetFullWidthCardBounds(headerCursor); - Vector2 persistentHeaderMin = new(cardLeft, headerCursor.Y); - Vector2 persistentHeaderMax = new(cardRight, headerCursor.Y + NativeImGui.GetFrameHeight()); + var persistentHeaderMin = new Vector2(cardLeft, headerCursor.Y); + var persistentHeaderMax = new Vector2(cardRight, headerCursor.Y + NativeImGui.GetFrameHeight()); ImGui.DrawNativeFilledRectangle( NativeImGui.Raw.GetWindowDrawList(), persistentHeaderMin, @@ -112,10 +120,14 @@ public bool CollapsingCard( float contentX = itemHeaderMin.X + NativeImGui.GetTreeNodeToLabelSpacing(); DrawDisclosureIndicator(new Vector2(itemHeaderMin.X, headerMin.Y), new Vector2(contentX, headerMax.Y), open, dimmed); float contentY = headerMin.Y + MathF.Max(0f, (headerMax.Y - headerMin.Y - NativeImGui.GetFrameHeight()) * 0.5f); - float trailingWidth = drawTrailingControl is null ? 0f : trailingControlWidth > 0f ? trailingControlWidth : NativeImGui.GetFrameHeight(); + float trailingWidth = drawTrailingControl is null + ? 0f + : trailingControlWidth > 0f ? trailingControlWidth : NativeImGui.GetFrameHeight(); float titleRight = headerMax.X - trailingWidth; if (drawTrailingControl is not null) + { titleRight -= style.headerControlSpacing; + } NativeImGui.SetCursorScreenPos(new Vector2(contentX, contentY)); bool dimmedColorPushed = false; bool groupStarted = false; @@ -161,9 +173,13 @@ public bool CollapsingCard( finally { if (groupStarted) + { NativeImGui.EndGroup(); + } if (dimmedColorPushed) + { NativeImGui.PopStyleColor(); + } NativeImGui.SetCursorScreenPos(contentCursor); } @@ -172,7 +188,9 @@ public bool CollapsingCard( catch { if (open) + { NativeImGui.TreePop(); + } throw; } } @@ -253,7 +271,12 @@ public void CardBody( NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FramePadding), style.cardBodyPadding); ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY; ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; - bool visible = NativeImGui.BeginChild($"##card_body_{id}", new Vector2(MathF.Max(1f, cardRight - cardLeft), 0f), (int)(childFlags), (int)(windowFlags)); + bool visible = NativeImGui.BeginChild( + $"##card_body_{id}", + new Vector2(MathF.Max(1f, cardRight - cardLeft), 0f), + (int)(childFlags), + (int)(windowFlags) + ); bool disabled = false; try { @@ -264,12 +287,16 @@ public void CardBody( } if (visible) + { drawContent(); + } } finally { if (disabled) + { NativeImGui.EndDisabled(); + } NativeImGui.EndChild(); float nextY = NativeImGui.GetCursorScreenPos().Y; NativeImGui.PopStyleVar(3); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs index a4d40f645..49e54985f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs @@ -1,5 +1,6 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -48,27 +49,42 @@ public void ClippedRows( ) { m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(drawRange); - if (itemCount < 0) - throw new ArgumentOutOfRangeException(nameof(itemCount)); + ArgumentOutOfRangeException.ThrowIfNegative(itemCount); if (!float.IsFinite(itemHeight) || (itemHeight <= 0f && itemHeight != -1f)) + { throw new ArgumentOutOfRangeException(nameof(itemHeight)); + } foreach (int row in preservedRows) + { if (row < 0 || row >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(preservedRows)); + } + } if (NativeImGui.Raw.GetCurrentContext()->WithinFrameScope == 0) + { throw new InvalidOperationException("Row clipping requires an active native frame."); + } if (itemCount == 0) + { return; + } ImGuiListClipper* clipper = NativeImGui.Raw.ImGuiListClipper(); - if (clipper == null) + if (clipper is null) + { throw new OutOfMemoryException("The native row clipper could not be allocated."); + } try { NativeImGui.Raw.Begin(clipper, itemCount, itemHeight); foreach (int row in preservedRows) + { NativeImGui.Raw.IncludeItemByIndex(clipper, row); + } while (NativeImGui.Raw.Step(clipper) != 0) + { drawRange(state, clipper->DisplayStart, clipper->DisplayEnd); + } } finally { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs index d29200af9..5e36dd266 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs @@ -3,9 +3,11 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -13,6 +15,7 @@ public sealed unsafe partial class ImGuiWidget { private const float C_TOOLTIP_MINIMUM_WIDTH = 300f; private const float C_TOOLTIP_WRAP_WIDTH = 440f; + /// /// Begins an explicitly opened popup using the editor context-menu presentation contract. /// The popup stays in its parent viewport, sizes itself to submitted content, and scrolls when @@ -36,7 +39,9 @@ public bool BeginMenuPopup(string id) NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); ImGuiWindowFlags flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings; if (NativeImGui.BeginPopup(id, (int)(flags))) + { return true; + } PopContextMenuStyle(); return false; } @@ -64,7 +69,9 @@ public bool BeginMenuTooltip() PushContextMenuStyle(); NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); if (NativeImGui.BeginTooltip()) + { return true; + } PopContextMenuStyle(); return false; } @@ -106,31 +113,42 @@ public void DrawTooltip(string? text) { m_session.EnsureDrawing(); if (string.IsNullOrWhiteSpace(text)) + { return; + } ImGuiViewport* viewport = NativeImGui.Raw.GetWindowViewport(); - Vector2 margin = new(6f * style.zoom); + var margin = new Vector2(6f * style.zoom); Vector2 available = Vector2.Max(Vector2.One, ImGui.FromNative(viewport->WorkSize) - margin * 2f); Vector2 padding = style.menuWindowPadding; float outerWidth = MathF.Min(C_TOOLTIP_WRAP_WIDTH * style.zoom, available.X); float innerWidth = MathF.Max(1f, outerWidth - padding.X * 2f - style.menuBorderSize * 2f); Vector2 textSize = NativeImGui.CalcTextSize(text, false, innerWidth); - outerWidth = MathF.Min(outerWidth, MathF.Max(MathF.Min(C_TOOLTIP_MINIMUM_WIDTH * style.zoom, available.X), textSize.X + padding.X * 2f + style.menuBorderSize * 2f)); + outerWidth = MathF.Min( + outerWidth, + MathF.Max(MathF.Min(C_TOOLTIP_MINIMUM_WIDTH * style.zoom, available.X), textSize.X + padding.X * 2f + style.menuBorderSize * 2f) + ); innerWidth = MathF.Max(1f, outerWidth - padding.X * 2f - style.menuBorderSize * 2f); textSize = NativeImGui.CalcTextSize(text, false, innerWidth); - Vector2 size = new(outerWidth, MathF.Min(available.Y, textSize.Y + padding.Y * 2f + style.menuBorderSize * 2f)); + var size = new Vector2(outerWidth, MathF.Min(available.Y, textSize.Y + padding.Y * 2f + style.menuBorderSize * 2f)); Vector2 workMin = ImGui.FromNative(viewport->WorkPos) + margin; Vector2 workMax = workMin + available; Vector2 mouse = NativeImGui.GetMousePos(); Vector2 position = mouse + new Vector2(16f, 20f) * style.zoom; if (position.X + size.X > workMax.X) + { position.X = mouse.X - size.X - 12f * style.zoom; + } if (position.Y + size.Y > workMax.Y) + { position.Y = mouse.Y - size.Y - 12f * style.zoom; + } position = Vector2.Clamp(position, workMin, Vector2.Max(workMin, workMax - size)); NativeImGui.SetNextWindowPos(position); NativeImGui.SetNextWindowSize(size); if (!BeginMenuTooltip()) + { return; + } try { NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + MathF.Max(1f, NativeImGui.GetContentRegionAvail().X)); @@ -166,7 +184,9 @@ public bool BeginContextMenu(string id) NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); ConstrainContextMenu(); if (NativeImGui.BeginPopupContextItem(id, (int)(ImGuiPopupFlags.MouseButtonRight))) + { return true; + } PopContextMenuStyle(); return false; } @@ -206,6 +226,7 @@ public void EndContextMenu() } private bool IsPopupBlockingInteraction() => ImGui.IsAnyPopupOpen(); + private void ConstrainContextMenu() { Vector2 workSize = ImGui.FromNative(NativeImGui.Raw.GetWindowViewport()->WorkSize); @@ -222,14 +243,6 @@ Vector2 maximum ImGui.ConstrainNativeWindowSize(pixelMinimum, pixelMaximum, &RoundMenuPopupSize, null); } - [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] - private static unsafe void RoundMenuPopupSize(ImGuiSizeCallbackData* data) - { - // ImGui truncates constrained sizes. Round content upward within integer bounds so - // fractional padding cannot turn a fully fitting menu into a scrolling window. - data->DesiredSize = ImGui.ToNative(new Vector2(MathF.Ceiling(data->DesiredSize.X), MathF.Ceiling(data->DesiredSize.Y))); - } - private void PushContextMenuStyle() { NativeImGui.PushStyleColor((int)(ImGuiCol.Text), EditorPalette.menuText); @@ -251,4 +264,10 @@ private void PopContextMenuStyle() NativeImGui.PopStyleVar(5); NativeImGui.PopStyleColor(7); } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] + private static unsafe void RoundMenuPopupSize(ImGuiSizeCallbackData* data) => + // ImGui truncates constrained sizes. Round content upward within integer bounds so + // fractional padding cannot turn a fully fitting menu into a scrolling window. + data->DesiredSize = ImGui.ToNative(new Vector2(MathF.Ceiling(data->DesiredSize.X), MathF.Ceiling(data->DesiredSize.Y))); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs index b04c223a1..ebfad4832 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -26,7 +28,10 @@ public Vector2 GetLabelChipSize(string label) m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(label); Vector2 textSize = NativeImGui.CalcTextSize(label); - return new Vector2(textSize.X + style.labelChipPadding.X * 2f, MathF.Max(NativeImGui.GetFrameHeight(), textSize.Y + style.labelChipPadding.Y * 2f)); + return new Vector2( + textSize.X + style.labelChipPadding.X * 2f, + MathF.Max(NativeImGui.GetFrameHeight(), textSize.Y + style.labelChipPadding.Y * 2f) + ); } /// @@ -51,7 +56,14 @@ Vector4 background Vector2 minimum = NativeImGui.GetCursorScreenPos(); Vector2 textSize = NativeImGui.CalcTextSize(label); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); - ImGui.DrawNativeFilledRectangle(drawList, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(background), style.labelChipRounding, 0); + ImGui.DrawNativeFilledRectangle( + drawList, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(background), + style.labelChipRounding, + 0 + ); ImGui.DrawNativeText(drawList, minimum + (size - textSize) * 0.5f, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), label); NativeImGui.Dummy(size); } @@ -103,11 +115,26 @@ public void TypeBadge( Vector2 textSize = NativeImGui.CalcTextSize(label); ImDrawList* draw = NativeImGui.Raw.GetWindowDrawList(); Vector4 background = Vector4.Lerp(EditorPalette.windowBackground, accent, 0.14f); - background.W = EditorPalette.opacityOpaque; + background.W = EditorPalette.C_OPACITY_OPAQUE; Vector4 outline = accent; - outline.W = EditorPalette.opacityStrong; - ImGui.DrawNativeFilledRectangle(draw, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(background), style.typeBadgeRounding, 0); - ImGui.DrawNativeRectangle(draw, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(outline), style.typeBadgeRounding, (int)(ImDrawFlags.None), style.borderSize); + outline.W = EditorPalette.C_OPACITY_STRONG; + ImGui.DrawNativeFilledRectangle( + draw, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(background), + style.typeBadgeRounding, + 0 + ); + ImGui.DrawNativeRectangle( + draw, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(outline), + style.typeBadgeRounding, + (int)(ImDrawFlags.None), + style.borderSize + ); ImGui.DrawNativeText(draw, minimum + (size - textSize) * 0.5f, NativeImGui.ColorConvertFloat4ToU32(accent), label); NativeImGui.Dummy(size); DrawItemTooltip(tooltip); @@ -140,7 +167,9 @@ public bool CompactCheckbox( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); if (size < 0f) + { size = style.compactCheckboxSize; + } if (size <= 0f) { throw new ArgumentOutOfRangeException(nameof(size), size, "Checkbox size must be positive."); @@ -164,8 +193,20 @@ public bool CompactCheckbox( { ImGui.DrawNativeFilledRectangle(drawList, min, max, textColor, 1f, 0); uint checkColor = NativeImGui.ColorConvertFloat4ToU32(EditorPalette.cardHeader); - ImGui.DrawNativeLine(drawList, min + new Vector2(size * 0.22f, size * 0.52f), min + new Vector2(size * 0.43f, size * 0.72f), checkColor, 1.5f); - ImGui.DrawNativeLine(drawList, min + new Vector2(size * 0.43f, size * 0.72f), min + new Vector2(size * 0.80f, size * 0.28f), checkColor, 1.5f); + ImGui.DrawNativeLine( + drawList, + min + new Vector2(size * 0.22f, size * 0.52f), + min + new Vector2(size * 0.43f, size * 0.72f), + checkColor, + 1.5f + ); + ImGui.DrawNativeLine( + drawList, + min + new Vector2(size * 0.43f, size * 0.72f), + min + new Vector2(size * 0.8f, size * 0.28f), + checkColor, + 1.5f + ); } else { @@ -174,7 +215,15 @@ public bool CompactCheckbox( if (hovered) { - ImGui.DrawNativeRectangle(drawList, min - Vector2.One, max + Vector2.One, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered), 1f, 0, 1.5f); + ImGui.DrawNativeRectangle( + drawList, + min - Vector2.One, + max + Vector2.One, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered), + 1f, + 0, + 1.5f + ); } DrawItemTooltip(tooltip); @@ -235,7 +284,12 @@ public bool CenteredButton( } float width = ImGuiUtf8Buffer.MeasureText(label, -1f).X + NativeImGui.Raw.GetStyle()->FramePadding.X * 2f; - return DrawCenteredButton(label, NativeImGui.GetCursorScreenPos() + new Vector2(0f, topPadding), NativeImGui.GetContentRegionAvail().X, width); + return DrawCenteredButton( + label, + NativeImGui.GetCursorScreenPos() + new Vector2(0f, topPadding), + NativeImGui.GetContentRegionAvail().X, + width + ); } /// @@ -263,7 +317,9 @@ string overlay ImVec2C nativeSize = ImGui.ToNative(size); ReadOnlySpan emptyOverlay = "\0"u8; fixed (byte* empty = emptyOverlay) + { NativeImGui.Raw.ProgressBar(fraction, &nativeSize, (sbyte*)empty); + } Vector2 minimum = NativeImGui.GetItemRectMin(); Vector2 maximum = NativeImGui.GetItemRectMax(); Vector2 textSize = NativeImGui.CalcTextSize(overlay); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs index 36d0de6d9..2b48367dd 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs @@ -2,79 +2,13 @@ using System.Numerics; using System.Runtime.CompilerServices; using Inno.Native.ImGui; + +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; -/// -/// Describes immutable content for a measured message dialog. Actions are returned to its owner, never retained as callbacks. -/// -/// -/// The current status or error text. -/// -/// -/// A completed fraction, or null when no progress bar is needed. -/// -/// -/// Whether to show activity without inventing a completed fraction. -/// -/// -/// The optional centered action label. -/// -/// -/// Whether the current operation admits the action. -/// -/// -/// Optional expanded diagnostic text sharing the message scroll owner. -/// -/// -/// Whether Escape activates this action; opt in only for cancellation or dismissal. -/// -public readonly record struct DialogPresentation( - string message, - float? progress = null, - bool indeterminate = false, - string? actionLabel = null, - bool actionEnabled = true, - string? details = null, - bool cancelOnEscape = false -); - -/// -/// Carries a measured dialog layout. Only its required extent is public; drawing mechanics remain owned by the widget. -/// -public readonly struct DialogLayout -{ - internal DialogLayout( - Vector2 size, - float textWidth, - float bodyHeight, - float bodyContentHeight, - float spacing, - float frameHeight, - float actionWidth - ) { - this.size = size; - this.textWidth = textWidth; - this.bodyHeight = bodyHeight; - this.bodyContentHeight = bodyContentHeight; - this.spacing = spacing; - this.frameHeight = frameHeight; - this.actionWidth = actionWidth; - } - - /// - /// Gets the content extent, excluding the window title, border and padding. - /// - public Vector2 size { get; } - internal float textWidth { get; } - internal float bodyHeight { get; } - internal float bodyContentHeight { get; } - internal float spacing { get; } - internal float frameHeight { get; } - internal float actionWidth { get; } -} - /// /// Presents measured message dialogs through the owning editor UI session. /// @@ -121,13 +55,19 @@ public DialogLayout MeasureDialog( Vector2 availableSize ) { ImGuiNativeContext* native = m_session.RequireContext(); - if (native->WithinFrameScope == 0 || native->Font == null || native->FontBaked == null) + if (native->WithinFrameScope == 0 || native->Font is null || native->FontBaked is null) + { throw new InvalidOperationException("Dialog measurement requires an active native frame and font."); + } ArgumentNullException.ThrowIfNull(presentation.message); if (presentation.progress is float fraction && (!float.IsFinite(fraction) || fraction < 0f || fraction > 1f)) + { throw new ArgumentOutOfRangeException(nameof(presentation), "A determinate progress fraction must be between zero and one."); + } if (!float.IsFinite(availableSize.X) || !float.IsFinite(availableSize.Y) || availableSize.X <= 0f || availableSize.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(availableSize)); + } float width = MathF.Max(1f, MathF.Floor(availableSize.X)); ImGuiStyle* nativeStyle = &native->Style; float spacing = nativeStyle->ItemSpacing.Y; @@ -137,19 +77,38 @@ Vector2 availableSize ImFont* font = native->Font; ImFontBaked* baked = native->FontBaked; // Only value data is retained. Shared or remapped native fonts are measured on every request. - bool memoize = font->OwnerAtlas->OwnerContext == native && font->RemapPairs.Data.Size == 0 && - (long)presentation.message.Length + (presentation.details?.Length ?? 0) + (presentation.actionLabel?.Length ?? 0) <= C_MAX_CACHED_DIALOG_CHARS; - DialogMeasurementKey key = new(presentation.message, presentation.details, presentation.actionLabel, - availableSize, hasProgress, font->FontId, baked->BakedId, baked->Glyphs.Size, - baked->IndexAdvanceX.Size, font->Sources.Size, font->OwnerAtlas->FontNextUniqueId, - native->FontSize, baked->RasterizerDensity, baked->FallbackAdvanceX, - nativeStyle->ItemSpacing.Y, ImGui.FromNative(nativeStyle->FramePadding), nativeStyle->ScrollbarSize); + bool memoize = font->OwnerAtlas->OwnerContext == native && font->RemapPairs.Data.Size == 0 + && (long)presentation.message.Length + (presentation.details?.Length ?? 0) + (presentation.actionLabel?.Length ?? 0) + <= C_MAX_CACHED_DIALOG_CHARS; + var key = new DialogMeasurementKey( + presentation.message, + presentation.details, + presentation.actionLabel, + availableSize, + hasProgress, + font->FontId, + baked->BakedId, + baked->Glyphs.Size, + baked->IndexAdvanceX.Size, + font->Sources.Size, + font->OwnerAtlas->FontNextUniqueId, + native->FontSize, + baked->RasterizerDensity, + baked->FallbackAdvanceX, + nativeStyle->ItemSpacing.Y, + ImGui.FromNative(nativeStyle->FramePadding), + nativeStyle->ScrollbarSize + ); if (memoize) { if (m_dialogLayout.size.X > 0f && m_dialogKey == key) + { return m_dialogLayout; + } if (m_previousDialogLayout.size.X > 0f && m_previousDialogKey == key) + { return m_previousDialogLayout; + } } float footer = (hasProgress ? frame : 0f) + (hasAction ? frame : 0f) + (hasProgress && hasAction ? spacing : 0f); float body = MeasureDialogBody(presentation, width, spacing); @@ -162,8 +121,10 @@ Vector2 availableSize } float visibleBody = MathF.Min(body, availableBody); float height = visibleBody + footer + (visibleBody > 0f && footer > 0f ? spacing : 0f); - float actionWidth = hasAction ? ImGuiUtf8Buffer.MeasureText(presentation.actionLabel!, -1f).X + nativeStyle->FramePadding.X * 2f : 0f; - DialogLayout result = new(new Vector2(width, MathF.Ceiling(height)), textWidth, visibleBody, body, spacing, frame, actionWidth); + float actionWidth = hasAction + ? ImGuiUtf8Buffer.MeasureText(presentation.actionLabel!, -1f).X + nativeStyle->FramePadding.X * 2f + : 0f; + var result = new DialogLayout(new Vector2(width, MathF.Ceiling(height)), textWidth, visibleBody, body, spacing, frame, actionWidth); if (memoize) { m_previousDialogKey = m_dialogKey; @@ -206,7 +167,9 @@ DialogLayout layout m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(presentation.message); if (!float.IsFinite(layout.size.X) || !float.IsFinite(layout.size.Y) || layout.size.X <= 0f || layout.size.Y < 0f) + { throw new ArgumentOutOfRangeException(nameof(layout)); + } Vector2 origin = NativeGui.GetCursorScreenPos(); bool scrolling = layout.bodyContentHeight > layout.bodyHeight; if (layout.bodyHeight > 0f) @@ -219,14 +182,18 @@ DialogLayout layout { NativeGui.SetNextWindowContentSize(new Vector2(0f, layout.bodyContentHeight)); ImVec2C bodySize = ImGui.ToNative(new Vector2(layout.size.X, layout.bodyHeight)); - ReadOnlySpan bodyId = "##dialog-body\0"u8; + ReadOnlySpan bodyID = "##dialog-body\0"u8; bool visible; - fixed (byte* id = bodyId) + fixed (byte* id = bodyID) + { visible = NativeGui.Raw.BeginChild((sbyte*)id, &bodySize, 0, 0) != 0; + } try { if (visible) + { DrawDialogBody(presentation, layout.textWidth); + } } finally { @@ -239,17 +206,24 @@ DialogLayout layout } } else + { DrawDialogBody(presentation, layout.textWidth); + } } float y = layout.bodyHeight; if (y > 0f && (presentation.progress.HasValue || presentation.indeterminate || !string.IsNullOrEmpty(presentation.actionLabel))) + { y += layout.spacing; + } if (presentation.progress.HasValue || presentation.indeterminate) { NativeGui.SetCursorScreenPos(origin + new Vector2(0f, y)); float fraction = presentation.progress ?? 0f; - CenteredProgressBar(presentation.indeterminate ? -(float)NativeGui.GetTime() : fraction, - new Vector2(layout.size.X, layout.frameHeight), presentation.indeterminate ? "Working…" : $"{fraction:P0}"); + CenteredProgressBar( + presentation.indeterminate ? -(float)NativeGui.GetTime() : fraction, + new Vector2(layout.size.X, layout.frameHeight), + presentation.indeterminate ? "Working…" : $"{fraction:P0}" + ); y += layout.frameHeight + layout.spacing; } bool activated = false; @@ -257,18 +231,27 @@ DialogLayout layout { bool disabled = !presentation.actionEnabled; if (disabled) + { NativeGui.BeginDisabled(true); + } try { activated = DrawCenteredButton(presentation.actionLabel, origin + new Vector2(0f, y), layout.size.X, layout.actionWidth); - if (presentation.cancelOnEscape && presentation.actionEnabled && NativeGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows) && - NativeGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false)) + if (presentation.cancelOnEscape + && presentation.actionEnabled + && NativeGui.IsWindowFocused((int)NativeFocusedFlags.RootAndChildWindows) + && + NativeGui.IsKeyPressed(NativeKey.Escape, false) + ) { activated = true; + } } finally { if (disabled) + { NativeGui.EndDisabled(); + } } } return activated; @@ -282,26 +265,6 @@ private void ClearDialogMeasurements() m_previousDialogLayout = default; } - private readonly record struct DialogMeasurementKey( - string message, - string? details, - string? action, - Vector2 available, - bool progress, - uint font, - uint baked, - int glyphs, - int advances, - int sources, - int nextFont, - float fontSize, - float density, - float fallbackAdvance, - float spacing, - Vector2 framePadding, - float scrollbar - ); - private static float MeasureDialogBody( DialogPresentation presentation, float width, @@ -309,7 +272,9 @@ float spacing ) { float height = presentation.message.Length == 0 ? 0f : ImGuiUtf8Buffer.MeasureText(presentation.message, width).Y; if (!string.IsNullOrEmpty(presentation.details)) + { height += (height > 0f ? spacing : 0f) + ImGuiUtf8Buffer.MeasureText(presentation.details, width).Y; + } return MathF.Ceiling(height); } @@ -321,7 +286,9 @@ float width try { if (presentation.message.Length != 0) + { ImGuiUtf8Buffer.DrawText(presentation.message); + } if (!string.IsNullOrEmpty(presentation.details)) { // Native text already contributes the same inter-item spacing used by measurement. @@ -333,4 +300,58 @@ float width NativeGui.PopTextWrapPos(); } } + + private readonly record struct DialogMeasurementKey( + string message, + string? details, + string? action, + Vector2 available, + bool progress, + uint font, + uint baked, + int glyphs, + int advances, + int sources, + int nextFont, + float fontSize, + float density, + float fallbackAdvance, + float spacing, + Vector2 framePadding, + float scrollbar + ); } + +/// +/// Describes immutable content for a measured message dialog. Actions are returned to its owner, never retained as callbacks. +/// +/// +/// The current status or error text. +/// +/// +/// A completed fraction, or null when no progress bar is needed. +/// +/// +/// Whether to show activity without inventing a completed fraction. +/// +/// +/// The optional centered action label. +/// +/// +/// Whether the current operation admits the action. +/// +/// +/// Optional expanded diagnostic text sharing the message scroll owner. +/// +/// +/// Whether Escape activates this action; opt in only for cancellation or dismissal. +/// +public readonly record struct DialogPresentation( + string message, + float? progress = null, + bool indeterminate = false, + string? actionLabel = null, + bool actionEnabled = true, + string? details = null, + bool cancelOnEscape = false +); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs index 2ed173cbb..60b1d1738 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs @@ -1,10 +1,12 @@ using System; -using BGCS.Runtime; using System.Numerics; +using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -39,8 +41,7 @@ public bool DragDropSource( in TPayload payload, Action? drawPreview = null, bool allowHoldToOpenOthers = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); ImGuiDragDropFlags sourceFlags = allowHoldToOpenOthers ? ImGuiDragDropFlags.None : ImGuiDragDropFlags.SourceNoHoldToOpenOthers; @@ -87,8 +88,7 @@ public bool DragDropSource( Func payloadFactory, Action? drawPreview = null, bool allowHoldToOpenOthers = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); ArgumentNullException.ThrowIfNull(payloadFactory); @@ -123,11 +123,7 @@ public bool DragDropSource( public bool DragDropTarget( string payloadType, out TPayload payload - ) - where TPayload : unmanaged - { - return DragDropTarget(payloadType, out payload, out _); - } + ) where TPayload : unmanaged => DragDropTarget(payloadType, out payload, out _); /// /// Accepts an unmanaged payload and reports its preview state on the most recently submitted item. @@ -151,11 +147,7 @@ public bool DragDropTarget( string payloadType, out TPayload payload, out bool isPreviewing - ) - where TPayload : unmanaged - { - return DragDropTarget(payloadType, out payload, out isPreviewing, drawDefaultHighlight: true); - } + ) where TPayload : unmanaged => DragDropTarget(payloadType, out payload, out isPreviewing, drawDefaultHighlight: true); /// /// Accepts an unmanaged payload and controls whether ImGui draws its default target rectangle. @@ -183,8 +175,7 @@ public bool DragDropTarget( out TPayload payload, out bool isPreviewing, bool drawDefaultHighlight - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); payload = default; @@ -196,12 +187,16 @@ bool drawDefaultHighlight ImGuiDragDropFlags flags = ImGuiDragDropFlags.AcceptBeforeDelivery; if (!drawDefaultHighlight) + { flags |= ImGuiDragDropFlags.AcceptNoDrawDefaultRect; + } using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); ImGuiPayload* nativePayload = NativeImGui.Raw.AcceptDragDropPayload((sbyte*)nativeType.pointer, (int)flags); bool compatible = TryReadDragDropPayload(nativePayload, out payload); if (compatible) + { isPreviewing = nativePayload->Preview != 0; + } bool delivered = compatible && nativePayload->Delivery != 0; NativeImGui.EndDragDropTarget(); return delivered; @@ -222,7 +217,7 @@ bool drawDefaultHighlight /// /// Maximum screen coordinate of the complete target. /// - /// + /// /// ImGui identifier unique within the current window. /// /// @@ -244,35 +239,42 @@ public bool DragDropTarget( string payloadType, Vector2 minimum, Vector2 maximum, - uint targetId, + uint targetID, out TPayload payload, out bool isPreviewing, bool drawDefaultHighlight = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); payload = default; isPreviewing = false; if (maximum.X <= minimum.X || maximum.Y <= minimum.Y) + { return false; - ImRect bounds = new() + } + var bounds = new ImRect() { Min = ImGui.ToNative(minimum), Max = ImGui.ToNative(maximum) }; - if (NativeImGui.Raw.BeginDragDropTargetCustom(&bounds, targetId) == 0) + if (NativeImGui.Raw.BeginDragDropTargetCustom(&bounds, targetID) == 0) + { return false; + } try { ImGuiDragDropFlags flags = ImGuiDragDropFlags.AcceptBeforeDelivery; if (!drawDefaultHighlight) + { flags |= ImGuiDragDropFlags.AcceptNoDrawDefaultRect; + } using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); ImGuiPayload* nativePayload = NativeImGui.Raw.AcceptDragDropPayload((sbyte*)nativeType.pointer, (int)flags); bool compatible = TryReadDragDropPayload(nativePayload, out payload); if (compatible) + { isPreviewing = nativePayload->Preview != 0; + } return compatible && nativePayload->Delivery != 0; } finally @@ -284,8 +286,7 @@ public bool DragDropTarget( private unsafe void SetDragDropPayload( string payloadType, in TPayload payload - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { TPayload payloadCopy = payload; using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); @@ -295,12 +296,13 @@ in TPayload payload private unsafe bool TryReadDragDropPayload( ImGuiPayload* nativePayload, out TPayload payload - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { payload = default; - if ((nativePayload == null) || nativePayload->DataSize != sizeof(TPayload) || nativePayload->Data == null) + if ((nativePayload is null) || nativePayload->DataSize != sizeof(TPayload) || nativePayload->Data is null) + { return false; + } payload = *(TPayload*)nativePayload->Data; return true; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs index c8600bfa4..5fc35540f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs @@ -1,18 +1,22 @@ using System; using Inno.Editor.Interactions; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Owns session-local controls, native adaptation and reversible edit gestures. /// public sealed unsafe partial class ImGuiWidget { private EditorEditGesture? m_propertyGesture; - private (string Owner, string Path) m_propertyEditKey; + private (string owner, string path) m_propertyEditKey; private bool m_propertyEditTouched; + /// /// Gets the current continuous-edit merge boundary, or null for a discrete edit. /// @@ -43,7 +47,9 @@ string name m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(path); if (NativeImGui.IsAnyItemActive()) + { BeginEdit(history, path, name); + } } /// @@ -67,9 +73,11 @@ string name m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(history); ArgumentException.ThrowIfNullOrWhiteSpace(path); - var key = (m_session.owner, path); + (string owner, string path) key = (m_session.owner, path); if (m_propertyGesture is not null && m_propertyEditKey != key) + { CommitEdits(); + } if (m_propertyGesture is null) { m_propertyGesture = new EditorEditGesture(history, name); @@ -90,6 +98,7 @@ string name /// [ScriptingApiIgnore] public bool IsEditing(string path) => m_propertyGesture is not null && m_propertyEditKey == (m_session.owner, path); + /// /// Observes the current property after drawing, including release and cancellation without a new value sample. /// @@ -101,12 +110,18 @@ public void CompletePropertyEdit(string path) { m_session.EnsureDrawing(); if (m_propertyGesture is null || m_propertyEditKey != (m_session.owner, path)) + { return; + } m_propertyEditTouched = true; - if (NativeImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)ImGuiKey.Escape, false)) + if (NativeImGui.IsKeyPressed((NativeKey)ImGuiKey.Escape, false)) + { CancelEdits(); + } else if (!NativeImGui.IsAnyItemActive()) + { CommitEdits(); + } } /// @@ -119,7 +134,9 @@ public void CompletePropertyEdit(string path) public void CommitEdits() { if (m_propertyGesture is null) + { return; + } m_propertyGesture.Commit(); m_propertyGesture.Dispose(); m_propertyGesture = null; @@ -135,18 +152,25 @@ public void CommitEdits() public void CancelEdits() { if (m_propertyGesture is null) + { return; + } EditorHistoryResult result = m_propertyGesture.Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The property gesture could not roll back: {result.message}"); + } m_propertyGesture.Dispose(); m_propertyGesture = null; } internal void BeginEditingFrame() => m_propertyEditTouched = false; + internal void CompleteEditingFrame() { if (m_propertyGesture is not null && !m_propertyEditTouched) + { CancelEdits(); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs index 34816bca5..7a37e579a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs @@ -1,131 +1,14 @@ using System; -using System.Numerics; -using Matrix = Inno.Core.Mathematics.Matrix; -using NativeImGui = Inno.Native.ImGui.ImGui; +using Inno.Native.ImGuizmo; + +using EngineMatrix = Inno.Core.Mathematics.Matrix; using NativeGizmo = Inno.Native.ImGuizmo.ImGuizmo; +using NativeImGui = Inno.Native.ImGui.ImGui; using NativeOperation = Inno.Native.ImGuizmo.ImGuizmoOperation; using NativeSpace = Inno.Native.ImGuizmo.ImGuizmoMode; namespace Inno.Editor.ImGui.ImGuiWidget; -/// -/// Chooses the transform handles rendered by the viewport presenter. -/// -[Flags] -public enum TransformGizmoOperation -{ - /// - /// Renders translation handles. - /// - Translate = 1, - /// - /// Renders rotation handles. - /// - Rotate = 2, - /// - /// Renders the X scale handle. - /// - ScaleX = 4, - /// - /// Renders the Y scale handle. - /// - ScaleY = 8, - /// - /// Renders the Z scale handle. - /// - ScaleZ = 16, - /// - /// Renders all local scale handles. - /// - Scale = ScaleX | ScaleY | ScaleZ -} - -/// -/// Chooses how the manipulation axes are oriented. -/// -public enum TransformGizmoSpace -{ - /// - /// Uses the object's local orientation. - /// - Local, - /// - /// Uses the world's orientation. - /// - World -} - -/// -/// Supplies frame-local matrices and interaction policy without native handles. -/// -public readonly record struct TransformGizmoOptions -{ - /// - /// Gets the viewport's screen-space minimum. - /// - public Vector2 minimum { get; init; } - /// - /// Gets the viewport's screen-space maximum. - /// - public Vector2 maximum { get; init; } - /// - /// Gets the column-vector view matrix. - /// - public Matrix view { get; init; } - /// - /// Gets the projection matrix supplied by the viewport owner. - /// - public Matrix projection { get; init; } - /// - /// Gets whether this viewport uses an orthographic projection. - /// - public bool orthographic { get; init; } - /// - /// Gets whether manipulation can consume pointer input. - /// - public bool enabled { get; init; } - /// - /// Gets the requested handles. - /// - public TransformGizmoOperation operation { get; init; } - /// - /// Gets the handle coordinate space. - /// - public TransformGizmoSpace space { get; init; } - /// - /// Gets whether the X translation axis is excluded by the viewport plane. - /// - public bool maskX { get; init; } - /// - /// Gets whether the Y translation axis is excluded by the viewport plane. - /// - public bool maskY { get; init; } - /// - /// Gets whether the Z translation axis is excluded by the viewport plane. - /// - public bool maskZ { get; init; } -} -/// -/// Returns copied manipulation output; the domain owner decides how to apply and record it. -/// -/// -/// The resulting world matrix. -/// -/// -/// Whether the native presenter reported an edited value. -/// -/// -/// Whether the handle currently captures the pointer. -/// -/// -/// Whether the pointer is over a handle. -/// -public readonly record struct TransformGizmoResult( - Matrix matrix, - bool changed, - bool isUsing, - bool isOver -); /// /// Owns session-local controls, native adaptation and reversible edit gestures. /// @@ -144,7 +27,7 @@ public sealed unsafe partial class ImGuiWidget /// Copied output with no native pointer or domain object. /// public TransformGizmoResult TransformGizmo( - Matrix world, + EngineMatrix world, TransformGizmoOptions options ) { m_session.EnsureDrawing(); @@ -156,12 +39,17 @@ TransformGizmoOptions options WriteColumnMajor(world, model); NativeOperation operation = ToNativeOperation(options.operation); NativeGizmo.BeginFrame(); - NativeGizmo.Raw.SetDrawlist((Inno.Native.ImGuizmo.ImDrawList*)(nint)NativeImGui.Raw.GetWindowDrawList()); - NativeGizmo.SetRect(options.minimum.X, options.minimum.Y, MathF.Max(1f, options.maximum.X - options.minimum.X), MathF.Max(1f, options.maximum.Y - options.minimum.Y)); + NativeGizmo.Raw.SetDrawlist((ImDrawList*)(nint)NativeImGui.Raw.GetWindowDrawList()); + NativeGizmo.SetRect( + options.minimum.X, + options.minimum.Y, + MathF.Max(1f, options.maximum.X - options.minimum.X), + MathF.Max(1f, options.maximum.Y - options.minimum.Y) + ); NativeGizmo.SetOrthographic(options.orthographic); NativeGizmo.SetGizmoSizeClipSpace(0.21f); - var style = NativeGizmo.Raw.GetStyle(); - var previousStyle = *style; + Style* style = NativeGizmo.Raw.GetStyle(); + Style previousStyle = *style; try { style->TranslationLineThickness = 3.5f; @@ -199,23 +87,35 @@ TransformGizmoOptions options private static NativeOperation ToNativeOperation(TransformGizmoOperation operation) { if (operation == TransformGizmoOperation.Translate) + { return NativeOperation.Translate; + } if (operation == TransformGizmoOperation.Rotate) + { return NativeOperation.Rotate; + } NativeOperation result = 0; if (operation.HasFlag(TransformGizmoOperation.ScaleX)) + { result |= NativeOperation.ScaleX; + } if (operation.HasFlag(TransformGizmoOperation.ScaleY)) + { result |= NativeOperation.ScaleY; + } if (operation.HasFlag(TransformGizmoOperation.ScaleZ)) + { result |= NativeOperation.ScaleZ; + } if (result == 0) + { throw new ArgumentOutOfRangeException(nameof(operation)); + } return result; } private static unsafe void WriteColumnMajor( - Matrix matrix, + EngineMatrix matrix, float* destination ) { destination[0] = matrix.m11; @@ -236,22 +136,92 @@ private static unsafe void WriteColumnMajor( destination[15] = matrix.m44; } - private static unsafe Matrix ReadColumnMajor(float* source) => new( - source[0], - source[4], - source[8], - source[12], - source[1], - source[5], - source[9], - source[13], - source[2], - source[6], - source[10], - source[14], - source[3], - source[7], - source[11], - source[15] - ); + private static unsafe EngineMatrix ReadColumnMajor(float* source) + => new( + source[0], + source[4], + source[8], + source[12], + source[1], + source[5], + source[9], + source[13], + source[2], + source[6], + source[10], + source[14], + source[3], + source[7], + source[11], + source[15] + ); +} + +/// +/// Chooses the transform handles rendered by the viewport presenter. +/// +[Flags] +public enum TransformGizmoOperation +{ + /// + /// Renders translation handles. + /// + Translate = 1, + /// + /// Renders rotation handles. + /// + Rotate = 2, + /// + /// Renders the X scale handle. + /// + ScaleX = 4, + /// + /// Renders the Y scale handle. + /// + ScaleY = 8, + /// + /// Renders the Z scale handle. + /// + ScaleZ = 16, + /// + /// Renders all local scale handles. + /// + Scale = ScaleX | ScaleY | ScaleZ +} + +/// +/// Chooses how the manipulation axes are oriented. +/// +public enum TransformGizmoSpace +{ + /// + /// Uses the object's local orientation. + /// + Local, + /// + /// Uses the world's orientation. + /// + World } + +/// +/// Returns copied manipulation output; the domain owner decides how to apply and record it. +/// +/// +/// The resulting world matrix. +/// +/// +/// Whether the native presenter reported an edited value. +/// +/// +/// Whether the handle currently captures the pointer. +/// +/// +/// Whether the pointer is over a handle. +/// +public readonly record struct TransformGizmoResult( + EngineMatrix matrix, + bool changed, + bool isUsing, + bool isOver +); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs index eebd74b85..c1b266e2c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs @@ -1,15 +1,27 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides standard help box presentation in the Editor UI. /// public sealed unsafe partial class ImGuiWidget { private SectionLayoutState? m_sectionLayout; + + /// + /// Gets whether content belonging to the current Inspector section should be drawn. + /// + /// + /// Attribute-driven drawers use this value to skip properties until the next section header + /// when the current section is collapsed. + /// + public bool isSectionContentVisible => m_sectionLayout?.contentVisible ?? true; + /// /// Draws a wrapped contextual message with a semantic icon and a subdued status surface. /// @@ -31,7 +43,7 @@ Vector4 color ArgumentNullException.ThrowIfNull(text); ArgumentNullException.ThrowIfNull(icon); Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 padding = new(10f * style.zoom, 8f * style.zoom); + var padding = new Vector2(10f * style.zoom, 8f * style.zoom); float width = MathF.Max(1f, NativeImGui.GetContentRegionAvail().X); float iconWidth = NativeImGui.CalcTextSize(icon).X; float gap = 8f * style.zoom; @@ -40,12 +52,34 @@ Vector4 color float height = MathF.Max(NativeImGui.GetTextLineHeight(), textSize.Y) + padding.Y * 2f; ImDrawList* draw = NativeImGui.Raw.GetWindowDrawList(); Vector4 background = Vector4.Lerp(EditorPalette.windowBackground, color, 0.075f); - background.W = EditorPalette.opacityOpaque; + background.W = EditorPalette.C_OPACITY_OPAQUE; Vector4 outline = color; - outline.W = EditorPalette.opacityMuted; - ImGui.DrawNativeFilledRectangle(draw, origin, origin + new Vector2(width, height), NativeImGui.ColorConvertFloat4ToU32(background), 4f * style.zoom, 0); - ImGui.DrawNativeRectangle(draw, origin, origin + new Vector2(width, height), NativeImGui.ColorConvertFloat4ToU32(outline), 4f * style.zoom, 0, 1f); - ImGui.DrawNativeFilledRectangle(draw, origin, origin + new Vector2(2f * style.zoom, height), NativeImGui.ColorConvertFloat4ToU32(color), 0, 0); + outline.W = EditorPalette.C_OPACITY_MUTED; + ImGui.DrawNativeFilledRectangle( + draw, + origin, + origin + new Vector2(width, height), + NativeImGui.ColorConvertFloat4ToU32(background), + 4f * style.zoom, + 0 + ); + ImGui.DrawNativeRectangle( + draw, + origin, + origin + new Vector2(width, height), + NativeImGui.ColorConvertFloat4ToU32(outline), + 4f * style.zoom, + 0, + 1f + ); + ImGui.DrawNativeFilledRectangle( + draw, + origin, + origin + new Vector2(2f * style.zoom, height), + NativeImGui.ColorConvertFloat4ToU32(color), + 0, + 0 + ); ImGui.DrawNativeText(draw, origin + padding, NativeImGui.ColorConvertFloat4ToU32(color), icon); NativeImGui.SetCursorScreenPos(origin + padding + new Vector2(iconWidth + gap, 0f)); NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + textWidth); @@ -125,15 +159,6 @@ public void SectionLayout(Action drawContent) } } - /// - /// Gets whether content belonging to the current Inspector section should be drawn. - /// - /// - /// Attribute-driven drawers use this value to skip properties until the next section header - /// when the current section is collapsed. - /// - public bool isSectionContentVisible => m_sectionLayout?.contentVisible ?? true; - /// /// Ensures that subsequently drawn default properties belong to a framed section. /// @@ -158,7 +183,9 @@ public bool EnsureSection( ArgumentNullException.ThrowIfNull(title); SectionLayoutState? layout = m_sectionLayout; if (layout is null) + { return true; + } return layout.sectionIndex == 0 ? SectionHeader(title, description) : layout.contentVisible; } @@ -174,13 +201,13 @@ public bool EnsureSection( /// /// Optional interactive control drawn before the section title. /// - /// - /// Thrown when is . - /// /// /// when the section content should be drawn; otherwise, /// when the section is collapsed. /// + /// + /// Thrown when is . + /// public bool SectionHeader( string title, string? description = null, @@ -203,9 +230,9 @@ public bool SectionHeader( float paddingX = style.sectionPadding.X; float legendInset = style.sectionHeaderPadding.X; int sectionIndex = layout.sectionIndex++; - uint stateId = NativeImGui.GetID($"##inspector_section_{sectionIndex}"); + uint stateID = NativeImGui.GetID($"##inspector_section_{sectionIndex}"); ImGuiStorage* storage = NativeImGui.Raw.GetStateStorage(); - bool open = NativeImGui.Raw.GetBool(storage, stateId, 1) != 0; + bool open = NativeImGui.Raw.GetBool(storage, stateID, 1) != 0; NativeImGui.SetCursorScreenPos(new Vector2(origin.X + legendInset, origin.Y)); bool titlePressed = false; Vector2 titleSize = GetClickableTextSize(title, Vector2.Zero); @@ -218,7 +245,12 @@ public bool SectionHeader( NativeImGui.SameLine(0f, style.headerControlSpacing); } - titlePressed = ClickableText($"inspector_section_title_{sectionIndex}", title, new Vector2(MathF.Max(1f, titleSize.X), frameHeight), description); + titlePressed = ClickableText( + $"inspector_section_title_{sectionIndex}", + title, + new Vector2(MathF.Max(1f, titleSize.X), frameHeight), + description + ); } finally { @@ -228,7 +260,7 @@ public bool SectionHeader( if (titlePressed) { open = !open; - NativeImGui.Raw.SetBool(storage, stateId, open ? (byte)1 : (byte)0); + NativeImGui.Raw.SetBool(storage, stateID, open ? (byte)1 : (byte)0); } Vector2 legendMin = NativeImGui.GetItemRectMin(); @@ -291,7 +323,9 @@ uint color private void CompleteSection(SectionLayoutState layout) { if (!layout.active) + { return; + } NativeImGui.Dummy(new Vector2(0f, style.sectionPadding.Y)); NativeImGui.Unindent(style.sectionPadding.X); float bottom = MathF.Max(NativeImGui.GetCursorScreenPos().Y, layout.top + NativeImGui.GetFrameHeight()); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs index db25fd6ab..b493d4d1d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs @@ -1,15 +1,19 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// public sealed unsafe partial class ImGuiWidget { private const float C_INLINE_RENAME_FOCUS_OFFSET = 1f; + /// /// Draws a compact single-line rename editor inside an existing row. /// @@ -57,7 +61,7 @@ public InlineRenameResult InlineRename( } float fieldWidth = MathF.Max(1f, width < 0f ? NativeImGui.GetContentRegionAvail().X : width); - string controlId = $"##rename_{id}"; + string controlID = $"##rename_{id}"; bool selectAll = requestFocus; NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FramePadding), style.inlineRenameFramePadding); NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FrameRounding), style.frameRounding); @@ -77,7 +81,13 @@ public InlineRenameResult InlineRename( NativeImGui.PushStyleColor((int)(ImGuiCol.NavCursor), EditorPalette.transparent); try { - submitted = ImGuiUtf8Buffer.InputText(controlId, null, ref text, (nuint)capacity, ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll); + submitted = ImGuiUtf8Buffer.InputText( + controlID, + null, + ref text, + (nuint)capacity, + ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll + ); } finally { @@ -85,14 +95,14 @@ public InlineRenameResult InlineRename( } bool deactivated = NativeImGui.IsItemDeactivated(); - bool escapePressed = NativeImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)ImGuiKey.Escape); + bool escapePressed = NativeImGui.IsKeyPressed((NativeKey)ImGuiKey.Escape); bool active = NativeImGui.IsItemActive(); bool contextMenuRequested = active && NativeImGui.IsMouseReleased((int)(ImGuiMouseButton.Right)); if (selectAll && active) { - uint inputId = NativeImGui.GetItemID(); - ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputId); - if (inputState != null) + uint inputID = NativeImGui.GetItemID(); + ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputID); + if (inputState is not null) { NativeImGui.Raw.SelectAll(inputState); requestFocus = false; @@ -101,7 +111,7 @@ public InlineRenameResult InlineRename( if (active) { - Vector2 focusOffset = new(C_INLINE_RENAME_FOCUS_OFFSET); + var focusOffset = new Vector2(C_INLINE_RENAME_FOCUS_OFFSET); ImGui.DrawNativeRectangle( NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), NativeImGui.GetItemRectMin() - focusOffset, @@ -114,9 +124,13 @@ public InlineRenameResult InlineRename( } if (escapePressed) + { return InlineRenameResult.Cancel; + } if (submitted) + { return InlineRenameResult.Commit; + } if (contextMenuRequested) { // A context menu transfers focus into a popup after this item has already been @@ -135,80 +149,6 @@ public InlineRenameResult InlineRename( } } -/// -/// Describes the view-owned geometry used to present an active inline rename action. -/// -public sealed class InlineRenamePresentation -{ - /// - /// Creates inline rename presentation data. - /// - /// - /// The stable ImGui identifier used by the input field. - /// - /// - /// The requested input width in logical pixels. - /// - /// - /// The height of the row area in which the field is centered. - /// - /// - /// The maximum UTF-8 buffer size accepted by the input. - /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown when or is not finite and - /// positive, or when is zero. - /// - public InlineRenamePresentation( - string id, - float width, - float rowHeight, - nuint bufferSize = 512 - ) { - if (string.IsNullOrWhiteSpace(id)) - throw new ArgumentException("An inline rename identifier is required.", nameof(id)); - if (!float.IsFinite(width) || width <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(width), width, "The inline rename width must be finite and positive."); - } - - if (!float.IsFinite(rowHeight) || rowHeight <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(rowHeight), rowHeight, "The inline rename row height must be finite and positive."); - } - - if (bufferSize == 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "The inline rename buffer size must be positive."); - } - - this.id = id; - this.width = width; - this.rowHeight = rowHeight; - this.bufferSize = bufferSize; - } - - /// - /// Gets the stable ImGui identifier used by the input field. - /// - public string id { get; } - /// - /// Gets the requested input width in logical pixels. - /// - public float width { get; } - /// - /// Gets the height of the row area in which the input field is centered. - /// - public float rowHeight { get; } - /// - /// Gets the maximum UTF-8 buffer size accepted by the input. - /// - public nuint bufferSize { get; } -} - /// /// Describes the outcome of an inline rename control. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs index 09bc0526b..e9d569e2a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs @@ -2,31 +2,40 @@ using System.Collections.Generic; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Owns and retires transient controls by session and stable presentation owner. /// public sealed unsafe partial class ImGuiWidget { - private readonly EditorUiSession m_session; - internal ImGuiWidget(EditorUiSession session) + private readonly EditorUISession m_session; + + internal ImGuiWidget(EditorUISession session) { - m_session = session ?? throw new ArgumentNullException(nameof(session)); - style = new EditorStyleMetrics(session); + ArgumentNullException.ThrowIfNull(session); + m_session = session; + this.style = new EditorStyleMetrics(session); } internal void RetireOwner(string owner) { - if (m_propertyGesture is not null && m_propertyEditKey.Owner == owner) + if (m_propertyGesture is not null && m_propertyEditKey.owner == owner) + { CancelEdits(); - var retired = new List<(string Owner, uint Window)>(); - foreach (var key in m_treeStatesByWindow.Keys) + } + List<(string owner, uint window)> retired = []; + foreach ((string owner, uint window) key in m_treeStatesByWindow.Keys) { - if (string.Equals(key.Owner, owner, StringComparison.Ordinal)) + if (string.Equals(key.owner, owner, StringComparison.Ordinal)) + { retired.Add(key); + } } - foreach (var key in retired) + foreach ((string owner, uint window) key in retired) + { m_treeStatesByWindow.Remove(key); + } } internal void Retire() diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs index 4b2880b0a..998f6c274 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs @@ -1,8 +1,10 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Presents mixed values using the same controls and shared History. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs index c6e85ce7a..d5cc1ec3e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs @@ -1,10 +1,12 @@ using System; using System.Numerics; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Reusable editor widgets built on top of . /// @@ -38,7 +40,9 @@ public void PanelWindow( ) { m_session.EnsureDrawing(); if (!isOpen) + { return; + } bool pushedPadding = false; bool beganWindow = false; try @@ -76,17 +80,25 @@ public void PanelWindow( if (visible) { if (DrawPanelCloseButton(title)) + { isOpen = false; + } if (isOpen) + { drawBody(); + } } } finally { if (pushedPadding) + { NativeImGui.PopStyleVar(); + } if (beganWindow) + { NativeImGui.End(); + } } } @@ -122,14 +134,18 @@ public void ConstrainedContent( float contentWidth = MathF.Max(1f, width - padding.X * 2f); ImGuiChildFlags childFlags = ImGuiChildFlags.AutoResizeY | ImGuiChildFlags.AlwaysAutoResize; if (useWindowPadding) + { childFlags |= ImGuiChildFlags.AlwaysUseWindowPadding; + } ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; NativeImGui.SetNextWindowContentSize(new Vector2(contentWidth, 0f)); bool visible = NativeImGui.BeginChild(id, new Vector2(width, 0f), (int)(childFlags), (int)(windowFlags)); try { if (visible) + { drawContent(); + } } finally { @@ -178,7 +194,9 @@ public void HeaderSurface( try { ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY; - ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; + ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings; bool visible = NativeImGui.BeginChild(id, new Vector2(width, 0f), (int)(childFlags), (int)(windowFlags)); // FrameStyle consumed the square outer-container rounding in BeginChild. Restore the // normal editor rounding before drawing controls inside the header. @@ -186,7 +204,9 @@ public void HeaderSurface( try { if (visible) + { drawContent(); + } } finally { @@ -202,42 +222,86 @@ public void HeaderSurface( NativeImGui.SetCursorScreenPos(new Vector2(contentCursor.X, NativeImGui.GetCursorScreenPos().Y)); } + /// + /// Draws disabled hint text that wraps to the current content width. + /// + /// + /// Hint text. + /// + /// + /// Thrown when is . + /// + public void Hint(string text) + { + m_session.EnsureDrawing(); + ArgumentNullException.ThrowIfNull(text); + NativeImGui.BeginDisabled(true); + try + { + NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + MathF.Max(1f, NativeImGui.GetContentRegionAvail().X)); + try + { + NativeImGui.TextUnformatted(text); + } + finally + { + NativeImGui.PopTextWrapPos(); + } + } + finally + { + NativeImGui.EndDisabled(); + } + } + private bool DrawPanelCloseButton(string title) { if (!NativeImGui.IsWindowDocked()) + { return DrawFloatingPanelCloseButton(title); - uint dockId = NativeImGui.GetWindowDockID(); - ImGuiDockNode* dockNode = NativeImGui.Raw.DockBuilderGetNode(dockId); - if (dockNode == null || NativeImGui.Raw.DockNodeBeginAmendTabBar(dockNode) == 0) + } + uint dockID = NativeImGui.GetWindowDockID(); + ImGuiDockNode* dockNode = NativeImGui.Raw.DockBuilderGetNode(dockID); + if (dockNode is null || NativeImGui.Raw.DockNodeBeginAmendTabBar(dockNode) == 0) + { return false; + } try { ImGuiTabBar* tabBar = dockNode->TabBar; - if (tabBar == null) + if (tabBar is null) + { return false; + } ImRect tabBarBounds = tabBar->BarRect; float tabBarHeight = MathF.Max(1f, tabBarBounds.Max.Y - tabBarBounds.Min.Y); float iconSlotSize = MathF.Min(GetCompactIconSize().X, tabBarHeight); - Vector2 itemCenter = new(tabBarBounds.Max.X - iconSlotSize * 0.5f, (tabBarBounds.Min.Y + tabBarBounds.Max.Y) * 0.5f); + var itemCenter = new Vector2(tabBarBounds.Max.X - iconSlotSize * 0.5f, (tabBarBounds.Min.Y + tabBarBounds.Max.Y) * 0.5f); Vector2 itemMinimum = itemCenter - new Vector2(iconSlotSize * 0.5f); Vector2 itemMaximum = itemCenter + new Vector2(iconSlotSize * 0.5f); - ImRect itemBounds = new() + var itemBounds = new ImRect() { Min = ImGui.ToNative(itemMinimum), Max = ImGui.ToNative(itemMaximum) }; - uint itemId = NativeImGui.GetID($"##panel_close_{dockId}"); + uint itemID = NativeImGui.GetID($"##panel_close_{dockID}"); bool hovered = false; bool held = false; - ImGuiButtonFlags buttonFlags = (ImGuiButtonFlags)((int)ImGuiButtonFlagsPrivate.AllowOverlap | (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease); + ImGuiButtonFlags buttonFlags = (ImGuiButtonFlags)((int)ImGuiButtonFlagsPrivate.AllowOverlap + | (int)ImGuiButtonFlagsPrivate.NoNavFocus + | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease); ImGuiWindow* hoveredWindow = NativeImGui.Raw.GetCurrentContext()->HoveredWindow; - bool hostHovered = hoveredWindow != null && hoveredWindow->RootWindowDockTree == dockNode->HostWindow->RootWindowDockTree; + bool hostHovered = hoveredWindow is not null && hoveredWindow->RootWindowDockTree == dockNode->HostWindow->RootWindowDockTree; bool mouseHovered = hostHovered && NativeImGui.IsMouseHoveringRect(itemMinimum, itemMaximum); - bool itemAdded = NativeImGui.Raw.ItemAdd(&itemBounds, itemId, null, 0) != 0; - bool pressed = hostHovered && itemAdded && NativeImGui.ButtonBehavior(itemBounds, itemId, out hovered, out held, (int)buttonFlags); + bool itemAdded = NativeImGui.Raw.ItemAdd(&itemBounds, itemID, null, 0) != 0; + bool pressed = hostHovered + && itemAdded + && NativeImGui.ButtonBehavior(itemBounds, itemID, out hovered, out held, (int)buttonFlags); hovered |= mouseHovered; pressed |= mouseHovered && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left)); - uint iconColor = hovered || held ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + uint iconColor = hovered || held + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); DrawPanelCloseMark(NativeImGui.Raw.GetWindowDrawList(), itemCenter, iconSlotSize, iconColor); if (hovered && BeginMenuTooltip()) { @@ -257,12 +321,17 @@ private bool DrawFloatingPanelCloseButton(string title) { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); if ((window->Flags & (int)ImGuiWindowFlags.NoTitleBar) != 0) + { return false; + } ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); float size = GetCompactIconSize().X; - Vector2 maximum = new(window->Pos.X + window->Size.X - nativeStyle->WindowBorderSize - nativeStyle->FramePadding.X, window->Pos.Y + (window->TitleBarHeight + size) * 0.5f); + var maximum = new Vector2( + window->Pos.X + window->Size.X - nativeStyle->WindowBorderSize - nativeStyle->FramePadding.X, + window->Pos.Y + (window->TitleBarHeight + size) * 0.5f + ); Vector2 minimum = maximum - new Vector2(size); - ImRect bounds = new() + var bounds = new ImRect() { Min = ImGui.ToNative(minimum), Max = ImGui.ToNative(maximum) @@ -279,24 +348,24 @@ private bool DrawFloatingPanelCloseButton(string title) try { uint id = NativeImGui.GetID("##floating_panel_close"); - bool hovered = false, held = false; - bool pressed = NativeImGui.Raw.ItemAdd( - &bounds, - id, - null, - 0 - ) != 0 - && NativeImGui.ButtonBehavior( - bounds, - id, - out hovered, - out held, - (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease - ); - uint iconColor = hovered || held ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + bool hovered = false; + bool held = false; + bool pressed = NativeImGui.Raw.ItemAdd(&bounds, id, null, 0) != 0 + && NativeImGui.ButtonBehavior( + bounds, + id, + out hovered, + out held, + (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease + ); + uint iconColor = hovered || held + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); DrawPanelCloseMark(draw, minimum + new Vector2(size * 0.5f), size, iconColor); if (hovered) + { DrawItemTooltip($"Close {title}"); + } return pressed; } finally @@ -318,36 +387,4 @@ uint color ImGui.DrawNativeLine(drawList, center - diagonal, center + diagonal, color, thickness); ImGui.DrawNativeLine(drawList, center + new Vector2(-extent, extent), center + new Vector2(extent, -extent), color, thickness); } - - /// - /// Draws disabled hint text that wraps to the current content width. - /// - /// - /// Hint text. - /// - /// - /// Thrown when is . - /// - public void Hint(string text) - { - m_session.EnsureDrawing(); - ArgumentNullException.ThrowIfNull(text); - NativeImGui.BeginDisabled(true); - try - { - NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + MathF.Max(1f, NativeImGui.GetContentRegionAvail().X)); - try - { - NativeImGui.TextUnformatted(text); - } - finally - { - NativeImGui.PopTextWrapPos(); - } - } - finally - { - NativeImGui.EndDisabled(); - } - } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs index 5c4439f5a..e8705aac8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -11,37 +13,6 @@ public sealed unsafe partial class ImGuiWidget { private const string C_COMPACT_FLOAT_FORMAT = "%.1f"; private const string C_PRECISE_FLOAT_FORMAT = "%.9g"; - /// - /// Draws a two-column property row with a stable internal identifier. - /// - /// - /// Stable row identifier. - /// - /// - /// Human-readable property label. - /// - /// - /// Value control callback. - /// - /// - /// Optional hover help displayed from the property label. - /// - /// - /// Thrown when is empty or whitespace. - /// - /// - /// Thrown when or is . - /// - public void PropertyRow( - string id, - string label, - Action drawValue, - string? tooltip = null - ) { - m_session.EnsureDrawing(); - ArgumentNullException.ThrowIfNull(label); - PropertyRow(id, () => PropertyLabel(label, tooltip), drawValue); - } /// /// Draws a two-column property row whose label is supplied by a custom presentation callback. @@ -93,6 +64,38 @@ Action drawValue } } + /// + /// Draws a two-column property row with a stable internal identifier. + /// + /// + /// Stable row identifier. + /// + /// + /// Human-readable property label. + /// + /// + /// Value control callback. + /// + /// + /// Optional hover help displayed from the property label. + /// + /// + /// Thrown when is empty or whitespace. + /// + /// + /// Thrown when or is . + /// + public void PropertyRow( + string id, + string label, + Action drawValue, + string? tooltip = null + ) { + m_session.EnsureDrawing(); + ArgumentNullException.ThrowIfNull(label); + PropertyRow(id, () => PropertyLabel(label, tooltip), drawValue); + } + /// /// Configures the label and input columns of an active table with a shared two-to-three ratio. /// A following fixed-width action column may be added by the caller. @@ -382,7 +385,13 @@ float y ) { m_session.EnsureDrawing(); uint color = NativeImGui.GetColorU32((int)(ImGuiCol.DragDropTarget)); - ImGui.DrawNativeLine(NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), new Vector2(fromX, y), new Vector2(toX, y), color, style.interactionOverlayThickness); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), + new Vector2(fromX, y), + new Vector2(toX, y), + color, + style.interactionOverlayThickness + ); } /// @@ -422,10 +431,22 @@ float width float axisWidth = MathF.Min(MathF.Max(style.axisPrefixMinimumWidth, height), width * style.axisPrefixWidthRatio); Vector2 prefixMin = NativeImGui.GetCursorScreenPos(); Vector2 prefixMax = prefixMin + new Vector2(axisWidth, height); - ImGui.DrawNativeFilledRectangle(NativeImGui.Raw.GetWindowDrawList(), prefixMin, prefixMax, NativeImGui.ColorConvertFloat4ToU32(GetAxisColor(axis)), 1f, 0); + ImGui.DrawNativeFilledRectangle( + NativeImGui.Raw.GetWindowDrawList(), + prefixMin, + prefixMax, + NativeImGui.ColorConvertFloat4ToU32(GetAxisColor(axis)), + 1f, + 0 + ); Vector2 textSize = NativeImGui.CalcTextSize(axis); Vector2 textPosition = prefixMin + (new Vector2(axisWidth, height) - textSize) * 0.5f; - ImGui.DrawNativeText(NativeImGui.Raw.GetWindowDrawList(), textPosition, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.text), axis); + ImGui.DrawNativeText( + NativeImGui.Raw.GetWindowDrawList(), + textPosition, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.text), + axis + ); NativeImGui.Dummy(new Vector2(axisWidth, height)); NativeImGui.SameLine(0f, 0f); NativeImGui.SetNextItemWidth(MathF.Max(1f, width - axisWidth)); @@ -434,13 +455,16 @@ float width private bool WantsPreciseFloatInput(string label) { bool inputRequested = NativeImGui.IsMouseDoubleClicked((int)(ImGuiMouseButton.Left)) - || (NativeImGui.Raw.GetIO()->KeyCtrl != 0 - && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left))); + || (NativeImGui.Raw.GetIO()->KeyCtrl != 0 + && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left))); if (!inputRequested) + { return false; + } Vector2 minimum = NativeImGui.GetCursorScreenPos(); Vector2 maximum = minimum + new Vector2(MathF.Max(1f, NativeImGui.CalcItemWidth()), NativeImGui.GetFrameHeight()); - return NativeImGui.IsWindowHovered((int)(ImGuiHoveredFlags.RootAndChildWindows)) && NativeImGui.IsMouseHoveringRect(minimum, maximum, true); + return NativeImGui.IsWindowHovered((int)(ImGuiHoveredFlags.RootAndChildWindows)) + && NativeImGui.IsMouseHoveringRect(minimum, maximum, true); } private void ValidateFloatBounds( @@ -453,19 +477,21 @@ private void ValidateFloatBounds( } if (minimum is not float lower || maximum is not float upper) + { return; + } if (!float.IsFinite(lower) || !float.IsFinite(upper) || lower > upper) + { throw new ArgumentOutOfRangeException(nameof(maximum), "Floating-point bounds must be finite and ordered."); + } } private Vector4 GetAxisColor(string axis) + => axis.ToUpperInvariant() switch { - return axis.ToUpperInvariant() switch - { - "X" or "R" => EditorPalette.axisX, - "Y" or "G" => EditorPalette.axisY, - "Z" or "B" => EditorPalette.axisZ, - _ => EditorPalette.axisW - }; - } + "X" or "R" => EditorPalette.axisX, + "Y" or "G" => EditorPalette.axisY, + "Z" or "B" => EditorPalette.axisZ, + _ => EditorPalette.axisW + }; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs index 692b20460..4c71bb428 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs @@ -1,8 +1,10 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -11,9 +13,6 @@ public sealed partial class ImGuiWidget /// /// Draws a single-line search field with a stable identifier. /// - /// - /// Escape clears a nonempty query before leaving text input on a subsequent press. - /// /// /// The stable control identifier. /// @@ -32,6 +31,9 @@ public sealed partial class ImGuiWidget /// /// when the query changed; otherwise, . /// + /// + /// Escape clears a nonempty query before leaving text input on a subsequent press. + /// public bool SearchInput( string id, string hint, @@ -76,11 +78,17 @@ public bool BeginSearchPopup( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); if (width < 0f) + { width = style.searchPopupWidth; + } if (!BeginMenuPopup(id)) + { return false; + } if (NativeImGui.IsWindowAppearing()) + { NativeImGui.SetKeyboardFocusHere(); + } _ = SearchInput(id, hint, ref query, capacity, width); NativeImGui.Separator(); return true; diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs index 2d1d62f43..b81ff6e37 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs @@ -5,9 +5,13 @@ using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Native.ImGui; + +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Applies ordered selection gestures through the authoritative interaction owner. /// @@ -37,11 +41,17 @@ IReadOnlyList visibleTargets ImGuiIO* io = NativeImGui.Raw.GetIO(); bool additive = HasPrimaryModifier(interactions.keyboard, io); if (io->KeyShift != 0) + { interactions.SelectRange(visibleTargets, target, additive); + } else if (additive) + { interactions.ToggleSelection(target); + } else + { interactions.SetSelection(target); + } } /// @@ -82,43 +92,71 @@ public ListNavigationResult NavigateList( ArgumentOutOfRangeException.ThrowIfNegative(itemCount); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); if (focusedIndex < -1 || focusedIndex >= itemCount && focusedIndex != -1) + { throw new ArgumentOutOfRangeException(nameof(focusedIndex)); + } ImGuiIO* io = NativeImGui.Raw.GetIO(); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); bool ownsActiveRow = RouteTreeNavigationKeys(context); - if (!NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) - || io->WantTextInput != 0 || (context->ActiveId != 0 && !ownsActiveRow) || ImGui.IsAnyPopupOpen()) + if (!NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows) + || io->WantTextInput != 0 || (context->ActiveId != 0 && !ownsActiveRow) || ImGui.IsAnyPopupOpen() + ) { return new(focusedIndex, false, false, false, false, false, false, false); + } int next = focusedIndex; bool navigation = false; if (itemCount > 0) { navigation = true; - if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.DownArrow)) + if (NativeImGui.IsKeyPressed(NativeKey.DownArrow)) + { next = focusedIndex < 0 ? 0 : Math.Min(itemCount - 1, focusedIndex + 1); - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.UpArrow)) + } + else if (NativeImGui.IsKeyPressed(NativeKey.UpArrow)) + { next = focusedIndex < 0 ? itemCount - 1 : Math.Max(0, focusedIndex - 1); - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Home)) + } + else if (NativeImGui.IsKeyPressed(NativeKey.Home)) + { next = 0; - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.End)) + } + else if (NativeImGui.IsKeyPressed(NativeKey.End)) + { next = itemCount - 1; - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageDown)) + } + else if (NativeImGui.IsKeyPressed(NativeKey.PageDown)) + { next = focusedIndex < 0 ? 0 : (int)Math.Min(itemCount - 1L, (long)focusedIndex + pageSize); - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageUp)) + } + else if (NativeImGui.IsKeyPressed(NativeKey.PageUp)) + { next = focusedIndex < 0 ? 0 : Math.Max(0, focusedIndex - pageSize); + } else + { navigation = false; + } } bool primary = HasPrimaryModifier(interactions.keyboard, io); bool extend = io->KeyShift != 0; - bool space = itemCount > 0 && NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Space, false); - bool activate = itemCount > 0 && (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Enter, false) - || NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.KeypadEnter, false)); - bool cancel = NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false); + bool space = itemCount > 0 && NativeImGui.IsKeyPressed(NativeKey.Space, false); + bool activate = itemCount > 0 && (NativeImGui.IsKeyPressed(NativeKey.Enter, false) + || NativeImGui.IsKeyPressed(NativeKey.KeypadEnter, false)); + bool cancel = NativeImGui.IsKeyPressed(NativeKey.Escape, false); if ((space || activate) && next < 0) + { next = 0; - return new(next, next != focusedIndex, space || navigation && (!primary || extend), - extend, primary, space && primary, activate, cancel); + } + return new( + next, + next != focusedIndex, + space || navigation && (!primary || extend), + extend, + primary, + space && primary, + activate, + cancel + ); } private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) @@ -126,19 +164,21 @@ private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) uint window = NativeImGui.Raw.GetCurrentWindow()->ID; if (!m_treeStatesByWindow.TryGetValue((m_session.owner, window), out TreeWidgetWindowState? state) || state.lastFrame != NativeImGui.GetFrameCount() - || !NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) - || NativeImGui.Raw.GetIO()->WantTextInput != 0 || ImGui.IsAnyPopupOpen()) + || !NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows) + || NativeImGui.Raw.GetIO()->WantTextInput != 0 || ImGui.IsAnyPopupOpen() + ) { return false; + } bool ownsActiveRow = context->ActiveId != 0 - && context->ActiveIdSource == ImGuiInputSource.Keyboard && state.navigationItemIds.Contains(context->ActiveId); - if (state.navigationItemIds.Contains(context->NavId) && (context->ActiveId == 0 || ownsActiveRow)) + && context->ActiveIdSource == ImGuiInputSource.Keyboard && state.navigationItemIDs.Contains(context->ActiveId); + if (state.navigationItemIDs.Contains(context->NavId) && (context->ActiveId == 0 || ownsActiveRow)) { // Native navigation must not activate the disclosure while the list owns selection/activation. // A distinct owner preserves text fields and overlay buttons, including their native navigation. uint owner = NativeImGui.GetID("##inno_list_navigation"); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.Space, owner, 0); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.Enter, owner, 0); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.KeypadEnter, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.Space, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.Enter, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.KeypadEnter, owner, 0); } return ownsActiveRow; } @@ -147,75 +187,24 @@ private static bool HasPrimaryModifier( EditorKeyboardPolicy keyboard, ImGuiIO* io ) { - var input = new EditorUiInput(io); + var input = new EditorUIInput(io); KeyModifier modifiers = KeyModifier.None; if (input.control) + { modifiers |= KeyModifier.Control; + } if (input.super) + { modifiers |= KeyModifier.Super; + } if (input.alt) + { modifiers |= KeyModifier.Alt; + } if (input.shift) + { modifiers |= KeyModifier.Shift; + } return (modifiers & keyboard.primaryModifier) == keyboard.primaryModifier; } } - -/// -/// Carries frame-local list navigation intents over visible indices without owning objects or selection state. -/// -public readonly struct ListNavigationResult -{ - internal ListNavigationResult( - int focusedIndex, - bool focusChanged, - bool selectionRequested, - bool extendRange, - bool additive, - bool toggle, - bool activate, - bool cancel - ) { - this.focusedIndex = focusedIndex; - this.focusChanged = focusChanged; - this.selectionRequested = selectionRequested; - this.extendRange = extendRange; - this.additive = additive; - this.toggle = toggle; - this.activate = activate; - this.cancel = cancel; - } - - /// - /// Gets the resulting visible focus index, or minus one for no focus. - /// - public int focusedIndex { get; } - /// - /// Gets whether the visible focus index changed. - /// - public bool focusChanged { get; } - /// - /// Gets whether the caller should apply a domain selection operation. - /// - public bool selectionRequested { get; } - /// - /// Gets whether the selection should extend from its existing anchor. - /// - public bool extendRange { get; } - /// - /// Gets whether the product's primary modifier requests preserving other selected entries. - /// - public bool additive { get; } - /// - /// Gets whether Space with the primary modifier requests toggling the focused entry. - /// - public bool toggle { get; } - /// - /// Gets whether Enter requests activation of the focused entry. - /// - public bool activate { get; } - /// - /// Gets whether Escape requests canceling the current list workflow. - /// - public bool cancel { get; } -} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs index 70cf5fe24..fdc320552 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -43,9 +45,13 @@ public bool BeginBoundedCombo( ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(preview); if ((flags & ~ImGuiComboFlags.WidthFitPreview) != 0) + { throw new ArgumentOutOfRangeException(nameof(flags), flags, "The combo flag is not supported by the editor selector."); + } ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); - float width = (flags & ImGuiComboFlags.WidthFitPreview) != 0 ? NativeImGui.CalcTextSize(preview).X + NativeImGui.GetFrameHeight() + nativeStyle->FramePadding.X * 2f : NativeImGui.CalcItemWidth(); + float width = (flags & ImGuiComboFlags.WidthFitPreview) != 0 + ? NativeImGui.CalcTextSize(preview).X + NativeImGui.GetFrameHeight() + nativeStyle->FramePadding.X * 2f + : NativeImGui.CalcItemWidth(); return BeginMenuSelector(id, preview, MathF.Max(1f, width), MathF.Max(1f, width)); } @@ -53,6 +59,7 @@ public bool BeginBoundedCombo( /// Ends a combo opened by . /// public void EndBoundedCombo() => EndMenuSelector(); + /// /// Draws a compact selector control and begins a work-area-bounded menu popup. /// @@ -91,35 +98,40 @@ float minimumPopupWidth ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(preview); if (width <= 0f) + { throw new ArgumentOutOfRangeException(nameof(width), width, "Selector width must be positive."); + } if (minimumPopupWidth <= 0f) { throw new ArgumentOutOfRangeException(nameof(minimumPopupWidth), minimumPopupWidth, "Popup width must be positive."); } - string popupId = $"##menu_selector_popup_{id}"; + string popupID = $"##menu_selector_popup_{id}"; Vector2 minimum = NativeImGui.GetCursorScreenPos(); float height = NativeImGui.GetFrameHeight(); - Vector2 size = new(width, height); + var size = new Vector2(width, height); bool pressed = NativeImGui.InvisibleButton($"##menu_selector_{id}", size); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); - bool open = NativeImGui.IsPopupOpen(popupId); + bool open = NativeImGui.IsPopupOpen(popupID); if (pressed) - NativeImGui.OpenPopup(popupId); + { + NativeImGui.OpenPopup(popupID); + } DrawMenuSelectorFrame(minimum, size, preview, hovered, active || open); - Vector2 popupOrigin = new(minimum.X, minimum.Y + height); + var popupOrigin = new Vector2(minimum.X, minimum.Y + height); NativeImGui.SetNextWindowPos(popupOrigin, (int)ImGuiCond.Always, Vector2.Zero); ImGuiViewport* parentViewport = NativeImGui.Raw.GetWindowViewport(); NativeImGui.SetNextWindowViewport(parentViewport->ID); SetWorkAreaPopupSize(MathF.Max(width, minimumPopupWidth), popupOrigin, parentViewport); - return BeginMenuPopup(popupId); + return BeginMenuPopup(popupID); } /// /// Ends a selector popup opened by . /// public void EndMenuSelector() => EndMenuPopup(); + private void SetWorkAreaPopupSize( float requestedWidth, Vector2 popupOrigin, @@ -143,13 +155,22 @@ private void DrawMenuSelectorFrame( bool active ) { ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); - uint background = NativeImGui.GetColorU32((int)(active ? ImGuiCol.FrameBgActive : hovered ? ImGuiCol.FrameBgHovered : ImGuiCol.FrameBg)); + uint background = NativeImGui.GetColorU32( + (int)(active ? ImGuiCol.FrameBgActive : hovered ? ImGuiCol.FrameBgHovered : ImGuiCol.FrameBg) + ); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); Vector2 maximum = minimum + size; float arrowSlot = size.Y; float arrowMinimumX = MathF.Max(minimum.X, maximum.X - arrowSlot); ImDrawFlags previewRounding = size.X <= arrowSlot ? ImDrawFlags.RoundCornersAll : ImDrawFlags.RoundCornersLeft; - ImGui.DrawNativeFilledRectangle(drawList, minimum, new Vector2(arrowMinimumX, maximum.Y), background, nativeStyle->FrameRounding, (int)(previewRounding)); + ImGui.DrawNativeFilledRectangle( + drawList, + minimum, + new Vector2(arrowMinimumX, maximum.Y), + background, + nativeStyle->FrameRounding, + (int)(previewRounding) + ); uint arrowBackground = NativeImGui.GetColorU32((int)(active || hovered ? ImGuiCol.ButtonHovered : ImGuiCol.Button)); ImGui.DrawNativeFilledRectangle( drawList, @@ -160,7 +181,7 @@ bool active (int)(size.X <= arrowSlot ? ImDrawFlags.RoundCornersAll : ImDrawFlags.RoundCornersRight) ); Vector2 textMinimum = minimum + ImGui.FromNative(nativeStyle->FramePadding); - Vector2 textMaximum = new(arrowMinimumX, maximum.Y); + var textMaximum = new Vector2(arrowMinimumX, maximum.Y); ImGui.PushNativeClipRectangle(drawList, textMinimum, textMaximum, 1); ImGui.DrawNativeText(drawList, textMinimum, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), preview); NativeImGui.Raw.PopClipRect(drawList); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs index 0f0ca7bbd..d1c328099 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -11,6 +13,7 @@ public sealed unsafe partial class ImGuiWidget { private float m_appliedZoom = float.NaN; private bool? m_appliedCompactMode; + /// /// Gets the centralized editor layout metrics shared by every widget and feature panel. /// @@ -34,12 +37,14 @@ internal void ApplyPendingStyle() { m_session.PrepareStyleInput(); if (float.IsNaN(m_appliedZoom) || MathF.Abs(m_appliedZoom - style.zoom) > 0.0001f || m_appliedCompactMode != style.isCompact) + { SetupStyle(); + } } private void ApplyLayoutStyle(ImGuiStyle* nativeStyle) { - nativeStyle->Alpha = EditorPalette.opacityOpaque; + nativeStyle->Alpha = EditorPalette.C_OPACITY_OPAQUE; nativeStyle->DisabledAlpha = style.disabledAlpha; nativeStyle->FontScaleMain = style.fontScale; nativeStyle->WindowPadding = ImGui.ToNative(style.windowPadding); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs index 562167eff..4b5417594 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs @@ -1,10 +1,12 @@ using System; using System.Numerics; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -12,6 +14,7 @@ public sealed unsafe partial class ImGuiWidget { private int m_iconCatalogFrame = -1; private float m_iconCatalogWidth; + /// /// Measures the standard glyph column once per native frame in this UI session. /// @@ -23,12 +26,14 @@ public float GetIconCatalogWidth() m_session.EnsureDrawing(); int frame = NativeImGui.GetFrameCount(); if (m_iconCatalogFrame == frame) + { return m_iconCatalogWidth; + } float fontSize = NativeImGui.GetFontSize(); float width = NativeImGui.GetTextLineHeight(); - foreach (var entry in EditorIconCatalog.standard) + foreach ((string name, string glyph) entry in EditorIconCatalog.standard) { - Vector4 bounds = GetGlyphVisualBounds(fontSize, entry.Glyph); + Vector4 bounds = GetGlyphVisualBounds(fontSize, entry.glyph); width = MathF.Max(width, bounds.Z - bounds.X); } @@ -86,80 +91,34 @@ uint color } /// - /// Gets the visible bounds of the first glyph in a string at a requested font size. + /// Draws clickable text without a persistent or hovered background. /// - /// - /// Font that owns the glyph. - /// - /// - /// Requested baked font size. + /// + /// Stable identifier used by ImGui to track the interaction. /// /// - /// Text whose first Unicode scalar identifies the glyph. + /// Visible text or icon glyph. + /// + /// + /// Optional tooltip displayed while the interaction is hovered. /// /// - /// A vector containing the glyph's left, top, right, and bottom offsets relative to the - /// text drawing origin. + /// when the text is pressed. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// - private Vector4 GetGlyphVisualBoundsNative( - ImFont* font, - float fontSize, - string text - ) { - m_session.EnsureDrawing(); - if (string.IsNullOrEmpty(text)) - throw new ArgumentException("Glyph text cannot be empty.", nameof(text)); - int codepoint = char.ConvertToUtf32(text, 0); - ImFontBaked* baked = NativeImGui.Raw.GetFontBaked(font, fontSize, -1f); - ImFontGlyph* glyph = codepoint <= ushort.MaxValue ? NativeImGui.Raw.FindGlyph(baked, (ushort)codepoint) : null; - if (glyph != null) - return new Vector4(glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); - NativeImGui.Raw.PushFont(font, fontSize); - Vector2 fallbackSize = NativeImGui.CalcTextSize(text); - NativeImGui.PopFont(); - return new Vector4(0f, 0f, fallbackSize.X, fallbackSize.Y); - } - - /// - /// Draws one glyph so the center of its visible bounds matches a requested point. - /// - /// - /// Draw list that receives the glyph. - /// - /// - /// Font that owns the glyph. - /// - /// - /// Requested baked font size. - /// - /// - /// Text containing the glyph to draw. - /// - /// - /// Target center in screen coordinates. - /// - /// - /// Packed ImGui text color. - /// - private void AddGlyphCenteredNative( - ImDrawList* drawList, - ImFont* font, - float fontSize, + /// + /// Thrown when is . + /// + public bool ClickableText( + string id, string text, - Vector2 center, - uint color - ) { - m_session.EnsureDrawing(); - Vector4 bounds = GetGlyphVisualBoundsNative(font, fontSize, text); - Vector2 visibleCenterOffset = new((bounds.X + bounds.Z) * 0.5f, (bounds.Y + bounds.W) * 0.5f); - ImGui.DrawNativeText(drawList, font, fontSize, center - visibleCenterOffset, color, text); - } + string? tooltip = null + ) => ClickableText(id, text, GetCompactClickableTextSize(), tooltip); /// - /// Draws clickable text without a persistent or hovered background. + /// Draws clickable text centered inside an explicitly sized transparent interaction area. /// /// /// Stable identifier used by ImGui to track the interaction. @@ -167,6 +126,9 @@ uint color /// /// Visible text or icon glyph. /// + /// + /// Size of the transparent interaction area. + /// /// /// Optional tooltip displayed while the interaction is hovered. /// @@ -179,11 +141,38 @@ uint color /// /// Thrown when is . /// + /// + /// Thrown when either component of is not positive. + /// public bool ClickableText( string id, string text, + Vector2 controlSize, string? tooltip = null - ) => ClickableText(id, text, GetCompactClickableTextSize(), tooltip); + ) { + m_session.EnsureDrawing(); + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(text); + if (controlSize.X <= 0f || controlSize.Y <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(controlSize), controlSize, "Clickable text size must be positive."); + } + + Vector2 textSize = NativeImGui.CalcTextSize(text); + Vector2 cursor = NativeImGui.GetCursorScreenPos(); + bool pressed = NativeImGui.InvisibleButton($"##clickable_text_{id}", controlSize); + bool hovered = NativeImGui.IsItemHovered(); + bool active = NativeImGui.IsItemActive(); + DrawClickableTextPresentation(NativeImGui.Raw.GetWindowDrawList(), cursor, controlSize, text, textSize, hovered, active); + if (!string.IsNullOrWhiteSpace(tooltip) && hovered && BeginMenuTooltip()) + { + NativeImGui.TextUnformatted(tooltip); + EndMenuTooltip(); + } + + return pressed; + } + /// /// Draws a text link with no button background and highlights it only through text presentation. /// @@ -221,7 +210,13 @@ string text { NativeImGui.SetMouseCursor((int)(ImGuiMouseCursor.Hand)); float underlineY = cursor.Y + size.Y; - ImGui.DrawNativeLine(NativeImGui.Raw.GetWindowDrawList(), new Vector2(cursor.X, underlineY), new Vector2(cursor.X + size.X, underlineY), packedColor, 1f); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetWindowDrawList(), + new Vector2(cursor.X, underlineY), + new Vector2(cursor.X + size.X, underlineY), + packedColor, + 1f + ); } return pressed; @@ -262,64 +257,17 @@ public bool ClickableIcon( bool pressed = NativeImGui.InvisibleButton($"##clickable_icon_{id}", controlSize); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); - uint color = hovered || active ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); - AddGlyphCenteredNative(NativeImGui.Raw.GetWindowDrawList(), NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize(), icon, cursor + controlSize * 0.5f, color); - if (!string.IsNullOrWhiteSpace(tooltip) && hovered && BeginMenuTooltip()) - { - NativeImGui.TextUnformatted(tooltip); - EndMenuTooltip(); - } - - return pressed; - } - - /// - /// Draws clickable text centered inside an explicitly sized transparent interaction area. - /// - /// - /// Stable identifier used by ImGui to track the interaction. - /// - /// - /// Visible text or icon glyph. - /// - /// - /// Size of the transparent interaction area. - /// - /// - /// Optional tooltip displayed while the interaction is hovered. - /// - /// - /// when the text is pressed. - /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown when is . - /// - /// - /// Thrown when either component of is not positive. - /// - public bool ClickableText( - string id, - string text, - Vector2 controlSize, - string? tooltip = null - ) { - m_session.EnsureDrawing(); - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentNullException.ThrowIfNull(text); - if (controlSize.X <= 0f || controlSize.Y <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(controlSize), controlSize, "Clickable text size must be positive."); - } - - Vector2 textSize = NativeImGui.CalcTextSize(text); - Vector2 cursor = NativeImGui.GetCursorScreenPos(); - bool pressed = NativeImGui.InvisibleButton($"##clickable_text_{id}", controlSize); - bool hovered = NativeImGui.IsItemHovered(); - bool active = NativeImGui.IsItemActive(); - DrawClickableTextPresentation(NativeImGui.Raw.GetWindowDrawList(), cursor, controlSize, text, textSize, hovered, active); + uint color = hovered || active + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + AddGlyphCenteredNative( + NativeImGui.Raw.GetWindowDrawList(), + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize(), + icon, + cursor + controlSize * 0.5f, + color + ); if (!string.IsNullOrWhiteSpace(tooltip) && hovered && BeginMenuTooltip()) { NativeImGui.TextUnformatted(tooltip); @@ -357,7 +305,12 @@ Vector2 areaSize Vector2 cursor = NativeImGui.GetCursorScreenPos(); Vector2 textSize = NativeImGui.CalcTextSize(text); - ImGui.DrawNativeText(NativeImGui.Raw.GetWindowDrawList(), cursor + (areaSize - textSize) * 0.5f, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), text); + ImGui.DrawNativeText( + NativeImGui.Raw.GetWindowDrawList(), + cursor + (areaSize - textSize) * 0.5f, + NativeImGui.GetColorU32((int)(ImGuiCol.Text)), + text + ); NativeImGui.Dummy(areaSize); } @@ -397,7 +350,10 @@ Vector2 padding } Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 effectivePadding = new(MathF.Min(padding.X, MathF.Max(0f, (areaSize.X - 1f) * 0.5f)), MathF.Min(padding.Y, MathF.Max(0f, (areaSize.Y - 1f) * 0.5f))); + var effectivePadding = new Vector2( + MathF.Min(padding.X, MathF.Max(0f, (areaSize.X - 1f) * 0.5f)), + MathF.Min(padding.Y, MathF.Max(0f, (areaSize.Y - 1f) * 0.5f)) + ); float wrapWidth = MathF.Max(1f, areaSize.X - effectivePadding.X * 2f); Vector2 textSize = NativeImGui.CalcTextSize(text, hide_text_after_double_hash: false, wrapWidth); Vector2 textPosition = origin + new Vector2( @@ -408,7 +364,15 @@ Vector2 padding ImGui.PushNativeClipRectangle(drawList, origin + effectivePadding, origin + areaSize - effectivePadding, 1); try { - ImGui.DrawNativeText(drawList, NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize(), textPosition, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), text, wrapWidth); + ImGui.DrawNativeText( + drawList, + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize(), + textPosition, + NativeImGui.GetColorU32((int)(ImGuiCol.Text)), + text, + wrapWidth + ); } finally { @@ -498,23 +462,10 @@ float wrapWidth m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(text); if (!float.IsFinite(wrapWidth) || wrapWidth <= 0f) - throw new ArgumentOutOfRangeException(nameof(wrapWidth)); - DrawWrappedText(text, wrapWidth); - } - - private static void DrawWrappedText( - string text, - float wrapWidth - ) { - NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + wrapWidth); - try { - NativeImGui.TextUnformatted(text); - } - finally - { - NativeImGui.PopTextWrapPos(); + throw new ArgumentOutOfRangeException(nameof(wrapWidth)); } + DrawWrappedText(text, wrapWidth); } /// @@ -560,7 +511,7 @@ public Vector2 GetCompactClickableTextSize() { m_session.EnsureDrawing(); float iconSlotWidth = NativeImGui.GetTextLineHeight(); - return new Vector2(iconSlotWidth + this.style.iconLabelSpacing, NativeImGui.GetFrameHeight()); + return new Vector2(iconSlotWidth + style.iconLabelSpacing, NativeImGui.GetFrameHeight()); } /// @@ -576,19 +527,6 @@ public Vector2 GetCompactIconSize() return new Vector2(iconSlotSize); } - private void DrawClickableTextPresentation( - ImDrawList* drawList, - Vector2 minimum, - Vector2 controlSize, - string text, - Vector2 textSize, - bool hovered, - bool active - ) { - uint color = hovered || active ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); - ImGui.DrawNativeText(drawList, minimum + (controlSize - textSize) * 0.5f, color, text); - } - /// /// Draws icon and text with the icon's visible glyph bounds centered in a slot that expands /// when the glyph is wider than the normal editor icon slot. @@ -619,15 +557,28 @@ bool highlight Vector4 glyphBounds = GetGlyphVisualBoundsNative(font, fontSize, icon); float iconSlotWidth = MathF.Max(lineHeight, glyphBounds.Z - glyphBounds.X); Vector2 textSize = NativeImGui.CalcTextSize(text); - Vector2 textPos = new(cursor.X + iconSlotWidth + style->ItemInnerSpacing.X, cursor.Y); + var textPos = new Vector2(cursor.X + iconSlotWidth + style->ItemInnerSpacing.X, cursor.Y); uint color = NativeImGui.GetColorU32((int)(ImGuiCol.Text)); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); - AddGlyphCenteredNative(drawList, font, fontSize, icon, new Vector2(cursor.X + iconSlotWidth * 0.5f, cursor.Y + lineHeight * 0.5f), color); + AddGlyphCenteredNative( + drawList, + font, + fontSize, + icon, + new Vector2(cursor.X + iconSlotWidth * 0.5f, cursor.Y + lineHeight * 0.5f), + color + ); ImGui.DrawNativeText(drawList, textPos, color, text); if (highlight) { float lineY = cursor.Y + NativeImGui.GetTextLineHeight() - this.style.textDecorationOffset; - ImGui.DrawNativeLine(drawList, new Vector2(cursor.X, lineY), new Vector2(textPos.X + textSize.X, lineY), color, this.style.borderSize); + ImGui.DrawNativeLine( + drawList, + new Vector2(cursor.X, lineY), + new Vector2(textPos.X + textSize.X, lineY), + color, + this.style.borderSize + ); } NativeImGui.Dummy(new Vector2(iconSlotWidth + style->ItemInnerSpacing.X + textSize.X, lineHeight)); @@ -638,6 +589,98 @@ bool highlight } } + /// + /// Gets the visible bounds of the first glyph in a string at a requested font size. + /// + /// + /// Font that owns the glyph. + /// + /// + /// Requested baked font size. + /// + /// + /// Text whose first Unicode scalar identifies the glyph. + /// + /// + /// A vector containing the glyph's left, top, right, and bottom offsets relative to the + /// text drawing origin. + /// + /// + /// Thrown when is empty. + /// + private Vector4 GetGlyphVisualBoundsNative( + ImFont* font, + float fontSize, + string text + ) { + m_session.EnsureDrawing(); + if (string.IsNullOrEmpty(text)) + { + throw new ArgumentException("Glyph text cannot be empty.", nameof(text)); + } + int codepoint = char.ConvertToUtf32(text, 0); + ImFontBaked* baked = NativeImGui.Raw.GetFontBaked(font, fontSize, -1f); + ImFontGlyph* glyph = codepoint <= ushort.MaxValue ? NativeImGui.Raw.FindGlyph(baked, (ushort)codepoint) : null; + if (glyph is not null) + { + return new Vector4(glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + } + NativeImGui.Raw.PushFont(font, fontSize); + Vector2 fallbackSize = NativeImGui.CalcTextSize(text); + NativeImGui.PopFont(); + return new Vector4(0f, 0f, fallbackSize.X, fallbackSize.Y); + } + + /// + /// Draws one glyph so the center of its visible bounds matches a requested point. + /// + /// + /// Draw list that receives the glyph. + /// + /// + /// Font that owns the glyph. + /// + /// + /// Requested baked font size. + /// + /// + /// Text containing the glyph to draw. + /// + /// + /// Target center in screen coordinates. + /// + /// + /// Packed ImGui text color. + /// + private void AddGlyphCenteredNative( + ImDrawList* drawList, + ImFont* font, + float fontSize, + string text, + Vector2 center, + uint color + ) { + m_session.EnsureDrawing(); + Vector4 bounds = GetGlyphVisualBoundsNative(font, fontSize, text); + var visibleCenterOffset = new Vector2((bounds.X + bounds.Z) * 0.5f, (bounds.Y + bounds.W) * 0.5f); + ImGui.DrawNativeText(drawList, font, fontSize, center - visibleCenterOffset, color, text); + } + + private void DrawClickableTextPresentation( + ImDrawList* drawList, + Vector2 minimum, + Vector2 controlSize, + string text, + Vector2 textSize, + bool hovered, + bool active + ) { + uint color = hovered || active + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + ImGui.DrawNativeText(drawList, minimum + (controlSize - textSize) * 0.5f, color, text); + } + private void IconTextAt( Vector2 screenPos, string icon, @@ -648,4 +691,19 @@ bool highlight NativeImGui.SameLine(offsetFromWindowStart, 0f); IconText(icon, text, highlight); } + + private static void DrawWrappedText( + string text, + float wrapWidth + ) { + NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + wrapWidth); + try + { + NativeImGui.TextUnformatted(text); + } + finally + { + NativeImGui.PopTextWrapPos(); + } + } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs index b2bc23807..4c4c4ab21 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs @@ -2,23 +2,35 @@ using System.Collections.Generic; using System.Numerics; using Inno.Native.ImGui; + +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// public sealed unsafe partial class ImGuiWidget { - private readonly Dictionary<(string Owner, uint Window), TreeWidgetWindowState> m_treeStatesByWindow = []; + private readonly Dictionary<(string owner, uint window), TreeWidgetWindowState> m_treeStatesByWindow = []; private bool m_hasNextTreeNodeOpen; private bool m_nextTreeNodeOpen; - private List m_treeNodeStack => GetTreeWindowState().treeNodeStack; - private List m_lastNodeIdsByDepth => GetTreeWindowState().lastNodeIdsByDepth; - private List m_lineSegments => GetTreeWindowState().lineSegments; - private Dictionary m_hasNextSiblingById => GetTreeWindowState().hasNextSiblingById; - private Dictionary m_openStatesById => GetTreeWindowState().openStatesById; - private int m_lastFrame { get => GetTreeWindowState().lastFrame; set => GetTreeWindowState().lastFrame = value; } + + /// + /// Gets this window and owner's expansion change counter for invalidating neutral flattened views. + /// + /// + /// No valid drawing session or native frame is active. + /// + public ulong treeExpansionRevision + { + get + { + m_session.EnsureDrawing(); + return GetTreeWindowState().expansionRevision; + } + } /// /// Draws a full-width interactive tree row whose non-leaf content toggles expansion when @@ -46,10 +58,14 @@ in TreeNodeOptions options ) { m_session.EnsureDrawing(); if (options.depth < 0) + { throw new ArgumentOutOfRangeException(nameof(options), "A flattened tree depth cannot be negative."); + } float indentation = (options.depth ?? 0) * NativeImGui.Raw.GetStyle()->IndentSpacing; if (indentation > 0f) + { NativeImGui.Indent(indentation); + } try { return DrawTreeRow(id, onDraw, options); @@ -57,22 +73,9 @@ in TreeNodeOptions options finally { if (indentation > 0f) + { NativeImGui.Unindent(indentation); - } - } - - /// - /// Gets this window and owner's expansion change counter for invalidating neutral flattened views. - /// - /// - /// No valid drawing session or native frame is active. - /// - public ulong treeExpansionRevision - { - get - { - m_session.EnsureDrawing(); - return GetTreeWindowState().expansionRevision; + } } } @@ -95,7 +98,7 @@ public bool IsTreeNodeOpen(string id) { m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); - return m_openStatesById.GetValueOrDefault(id); + return openStatesByID.GetValueOrDefault(id); } /// @@ -119,12 +122,39 @@ bool open ) { m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); - if (m_openStatesById.GetValueOrDefault(id) == open) + if (openStatesByID.GetValueOrDefault(id) == open) + { return; - m_openStatesById[id] = open; + } + openStatesByID[id] = open; GetTreeWindowState().expansionRevision++; } + /// + /// Overrides the retained expansion state of the next submitted non-leaf tree row. + /// + /// + /// Whether the next row should be expanded. + /// + public void SetNextTreeNodeOpen(bool open) + { + m_session.EnsureDrawing(); + m_hasNextTreeNodeOpen = true; + m_nextTreeNodeOpen = open; + } + + private List treeNodeStack => GetTreeWindowState().treeNodeStack; + private List lastNodeIDsByDepth => GetTreeWindowState().lastNodeIDsByDepth; + private List lineSegments => GetTreeWindowState().lineSegments; + private Dictionary hasNextSiblingByID => GetTreeWindowState().hasNextSiblingByID; + private Dictionary openStatesByID => GetTreeWindowState().openStatesByID; + + private int lastFrame + { + get => GetTreeWindowState().lastFrame; + set => GetTreeWindowState().lastFrame = value; + } + private TreeNodeResult DrawTreeRow( string id, Action onDraw, @@ -139,12 +169,14 @@ in TreeNodeOptions options Vector2 cursor = NativeImGui.GetCursorScreenPos(); TreeWidgetWindowState state = GetTreeWindowState(); bool visible = cursor.Y <= window->ClipRect.Max.Y - && cursor.Y + NativeImGui.GetFrameHeight() >= window->ClipRect.Min.Y; + && cursor.Y + NativeImGui.GetFrameHeight() >= window->ClipRect.Min.Y; bool drawContent = visible || options.requestFocus || options.keepContentActive - || state.activeContentOwner == id; + || state.activeContentOwner == id; uint activeBefore = NativeImGui.Raw.GetCurrentContext()->ActiveId; if (!drawContent) + { return DrawTreeNode(id, onDraw, options, isLeaf, null, false); + } ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); NativeImGui.Raw.ChannelsSplit(drawList, 2); NativeImGui.Raw.ChannelsSetCurrent(drawList, 1); @@ -155,7 +187,7 @@ in TreeNodeOptions options if (active != 0 && (active != activeBefore || active == NativeImGui.Raw.GetCurrentContext()->LastItemData.ID)) { state.activeContentOwner = id; - state.activeContentId = active; + state.activeContentID = active; } return result; } @@ -173,7 +205,7 @@ private TreeNodeResult DrawTreeNode( ImDrawList* drawList, bool drawContent ) { - bool open = !isLeaf && m_openStatesById.TryGetValue(id, out bool storedOpen) && storedOpen; + bool open = !isLeaf && openStatesByID.TryGetValue(id, out bool storedOpen) && storedOpen; if (!isLeaf && m_hasNextTreeNodeOpen) { open = m_nextTreeNodeOpen; @@ -186,30 +218,44 @@ bool drawContent // Each disclosure, content row and overlay owns its own hit region. ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.None; if (isLeaf) + { flags |= ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen; + } else + { flags |= ImGuiTreeNodeFlags.OpenOnArrow; + } if (options.depth is not null) + { flags |= ImGuiTreeNodeFlags.NoTreePushOnOpen; + } int depth = options.depth ?? Math.Max(0, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); PruneTreeNodeStack(depth); bool hasNextSibling = TrackSiblingState(id, depth); if (drawContent && !options.hideGuideLines) + { DrawTreeGuideLines(nodeCursor, hasNextSibling, !isLeaf); + } if (drawContent) + { PushTransparentTreeNodeHeaderColors(); + } bool isOpen; try { - if (options.requestFocus && NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows)) + if (options.requestFocus && NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows)) + { NativeImGui.SetKeyboardFocusHere(); + } isOpen = NativeImGui.TreeNodeEx($"##{id}", (int)(flags)); - GetTreeWindowState().navigationItemIds.Add(NativeImGui.Raw.GetCurrentContext()->LastItemData.ID); + GetTreeWindowState().navigationItemIDs.Add(NativeImGui.Raw.GetCurrentContext()->LastItemData.ID); } finally { if (drawContent) + { NativeImGui.PopStyleColor(3); + } } float nativeRowMaxY = NativeImGui.GetItemRectMax().Y; @@ -217,57 +263,87 @@ bool drawContent { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); if (isOpen && !isLeaf) - m_treeNodeStack.Add(new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = nativeRowMaxY, hasNextSibling = hasNextSibling }); - return new TreeNodeResult(isOpen && !isLeaf, false, false, false, - new Vector2(window->Pos.X, nodeCursor.Y), new Vector2(window->WorkRect.Max.X, nativeRowMaxY), - new Vector2(nodeCursor.X + NativeImGui.GetTreeNodeToLabelSpacing(), nodeCursor.Y), false); + { + treeNodeStack.Add( + new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = nativeRowMaxY, hasNextSibling = hasNextSibling } + ); + } + return new TreeNodeResult( + isOpen && !isLeaf, + false, + false, + false, + new Vector2(window->Pos.X, nodeCursor.Y), + new Vector2(window->WorkRect.Max.X, nativeRowMaxY), + new Vector2(nodeCursor.X + NativeImGui.GetTreeNodeToLabelSpacing(), nodeCursor.Y), + false + ); } try { if (!isLeaf && NativeImGui.IsItemToggledOpen()) + { SetTreeNodeOpen(id, isOpen); - TreeWidgetHighlightRect contentRect = DrawTreeNodeContentContainer(id, nodeCursor, nativeRowMaxY, onDraw, options.drawViewportOverlay, out Vector2 interactionMin); + } + TreeWidgetHighlightRect contentRect = DrawTreeNodeContentContainer( + id, + nodeCursor, + nativeRowMaxY, + onDraw, + options.drawViewportOverlay, + out Vector2 interactionMin + ); bool hovered = NativeImGui.IsItemHovered((int)(ImGuiHoveredFlags.AllowWhenOverlappedByItem)); bool clicked = hovered && NativeImGui.IsItemClicked((int)(ImGuiMouseButton.Left)); bool doubleClicked = hovered && NativeImGui.IsMouseDoubleClicked((int)(ImGuiMouseButton.Left)); if (!isLeaf && doubleClicked) + { SetTreeNodeOpen(id, !isOpen); + } bool showHoverHighlight = hovered && !options.suppressHoverHighlight && NativeImGui.Raw.IsDragDropActive() == 0; if (options.selected || showHoverHighlight) - DrawTreeRowBackground(drawList, contentRect, NativeImGui.GetColorU32((int)(options.selected ? ImGuiCol.Header : ImGuiCol.HeaderHovered))); + { + DrawTreeRowBackground( + drawList, + contentRect, + NativeImGui.GetColorU32((int)(options.selected ? ImGuiCol.Header : ImGuiCol.HeaderHovered)) + ); + } else if (options.showBackground) + { DrawTreeRowBackground(drawList, contentRect, NativeImGui.ColorConvertFloat4ToU32(options.backgroundColor)); + } if (isOpen && !isLeaf) { - m_treeNodeStack.Add(new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = contentRect.max.Y, hasNextSibling = hasNextSibling }); + treeNodeStack.Add( + new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = contentRect.max.Y, hasNextSibling = hasNextSibling } + ); } - return new TreeNodeResult(isOpen && !isLeaf, clicked, doubleClicked, hovered, contentRect.min, contentRect.max, interactionMin, true); + return new TreeNodeResult( + isOpen && !isLeaf, + clicked, + doubleClicked, + hovered, + contentRect.min, + contentRect.max, + interactionMin, + true + ); } catch { if (isOpen && !isLeaf && options.depth is null) + { NativeImGui.TreePop(); + } throw; } } - /// - /// Overrides the retained expansion state of the next submitted non-leaf tree row. - /// - /// - /// Whether the next row should be expanded. - /// - public void SetNextTreeNodeOpen(bool open) - { - m_session.EnsureDrawing(); - m_hasNextTreeNodeOpen = true; - m_nextTreeNodeOpen = open; - } - private TreeWidgetWindowState GetTreeWindowState() { - var windowKey = (m_session.owner, NativeImGui.Raw.GetCurrentWindow()->ID); + (string owner, uint) windowKey = (m_session.owner, NativeImGui.Raw.GetCurrentWindow()->ID); if (!m_treeStatesByWindow.TryGetValue(windowKey, out TreeWidgetWindowState? state)) { state = new TreeWidgetWindowState(); @@ -306,12 +382,12 @@ out Vector2 interactionMin Vector2 contentMin = NativeImGui.GetItemRectMin(); Vector2 contentMax = NativeImGui.GetItemRectMax(); - TreeWidgetHighlightRect rect = new() + var rect = new TreeWidgetHighlightRect() { min = new Vector2(windowPos.X, MathF.Min(nodeCursor.Y, contentMin.Y)), max = new Vector2(contentRightX, MathF.Max(nativeRowMaxY, contentMax.Y)) }; - Vector2 hitMin = new(contentX, rect.min.Y); + var hitMin = new Vector2(contentX, rect.min.Y); Vector2 hitMax = rect.max; interactionMin = hitMin; DrawTreeNodeViewportOverlay(window, drawViewportOverlay); @@ -329,7 +405,9 @@ private void DrawTreeNodeViewportOverlay( Action? drawViewportOverlay ) { if (drawViewportOverlay is null) + { return; + } float contentBoundaryX = window->DC.CursorMaxPos.X; float idealBoundaryX = window->DC.IdealMaxPos.X; try @@ -353,41 +431,51 @@ private void PushTransparentTreeNodeHeaderColors() private void BeginTreeFrameIfNeeded() { int frame = NativeImGui.GetFrameCount(); - if (frame == m_lastFrame) + if (frame == lastFrame) + { return; + } TreeWidgetWindowState state = GetTreeWindowState(); state.treeNodeStack.Clear(); - state.lastNodeIdsByDepth.Clear(); + state.lastNodeIDsByDepth.Clear(); state.lineSegments.Clear(); - state.navigationItemIds.Clear(); - if (state.activeContentId != NativeImGui.Raw.GetCurrentContext()->ActiveId) + state.navigationItemIDs.Clear(); + if (state.activeContentID != NativeImGui.Raw.GetCurrentContext()->ActiveId) { - state.activeContentId = 0; + state.activeContentID = 0; state.activeContentOwner = null; } - m_lastFrame = frame; + lastFrame = frame; } private void PruneTreeNodeStack(int nativeDepth) { - while (m_treeNodeStack.Count > nativeDepth) - m_treeNodeStack.RemoveAt(m_treeNodeStack.Count - 1); + while (treeNodeStack.Count > nativeDepth) + { + treeNodeStack.RemoveAt(treeNodeStack.Count - 1); + } } private bool TrackSiblingState( string id, int depth ) { - bool hasNextSibling = m_hasNextSiblingById.TryGetValue(id, out bool cachedHasNextSibling) && cachedHasNextSibling; - while (m_lastNodeIdsByDepth.Count <= depth) - m_lastNodeIdsByDepth.Add(string.Empty); - string previousId = m_lastNodeIdsByDepth[depth]; - if (!string.IsNullOrEmpty(previousId) && !string.Equals(previousId, id, StringComparison.Ordinal)) - m_hasNextSiblingById[previousId] = true; - m_hasNextSiblingById[id] = false; - m_lastNodeIdsByDepth[depth] = id; - for (int i = depth + 1; i < m_lastNodeIdsByDepth.Count; i++) - m_lastNodeIdsByDepth[i] = string.Empty; + bool hasNextSibling = hasNextSiblingByID.TryGetValue(id, out bool cachedHasNextSibling) && cachedHasNextSibling; + while (lastNodeIDsByDepth.Count <= depth) + { + lastNodeIDsByDepth.Add(string.Empty); + } + string previousID = lastNodeIDsByDepth[depth]; + if (!string.IsNullOrEmpty(previousID) && !string.Equals(previousID, id, StringComparison.Ordinal)) + { + hasNextSiblingByID[previousID] = true; + } + hasNextSiblingByID[id] = false; + lastNodeIDsByDepth[depth] = id; + for (int i = depth + 1; i < lastNodeIDsByDepth.Count; i++) + { + lastNodeIDsByDepth[i] = string.Empty; + } return hasNextSibling; } @@ -396,8 +484,10 @@ private void DrawTreeGuideLines( bool hasNextSibling, bool hasDisclosureArrow ) { - if (m_treeNodeStack.Count == 0) + if (treeNodeStack.Count == 0) + { return; + } ImGuiStyle* style = NativeImGui.Raw.GetStyle(); float textLineHeight = NativeImGui.GetTextLineHeight(); float lineOverlap = this.style.treeGuideLineOverlap; @@ -409,10 +499,10 @@ bool hasDisclosureArrow float fileConnectorPadding = MathF.Max(1f, style->ItemInnerSpacing.X); float folderConnectorPadding = fileConnectorPadding * 2f + this.style.treeFolderConnectorPadding; float targetX = hasDisclosureArrow ? nodeCursor.X + guideOffset - folderConnectorPadding : labelStartX - fileConnectorPadding; - for (int i = 0; i < m_treeNodeStack.Count - 1; i++) + for (int i = 0; i < treeNodeStack.Count - 1; i++) { - TreeWidgetNodeState ancestorState = m_treeNodeStack[i]; - TreeWidgetNodeState pathChildState = m_treeNodeStack[i + 1]; + TreeWidgetNodeState ancestorState = treeNodeStack[i]; + TreeWidgetNodeState pathChildState = treeNodeStack[i + 1]; if (pathChildState.hasNextSibling) { float ancestorX = ancestorState.cursor.X + guideOffset; @@ -421,31 +511,36 @@ bool hasDisclosureArrow } } - TreeWidgetNodeState parentState = m_treeNodeStack[^1]; + TreeWidgetNodeState parentState = treeNodeStack[^1]; float branchX = parentState.cursor.X + guideOffset; float branchStartY = MathF.Max(parentState.rowMaxY, nodeCursor.Y); AddTreeLine(new Vector2(branchX, branchStartY), new Vector2(branchX, hasNextSibling ? rowMaxY : rowCenterY)); if (targetX > branchX) + { AddTreeLine(new Vector2(branchX, rowCenterY), new Vector2(targetX, rowCenterY)); + } } private void AddTreeLine( Vector2 from, Vector2 to ) { - TreeWidgetLineSegment line = new() + var line = new TreeWidgetLineSegment() { from = SnapTreeLinePoint(from), to = SnapTreeLinePoint(to) }; - m_lineSegments.Add(line); - ImGui.DrawNativeLine(NativeImGui.Raw.GetWindowDrawList(), line.from, line.to, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.treeGuide), this.style.borderSize); + lineSegments.Add(line); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetWindowDrawList(), + line.from, + line.to, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.treeGuide), + style.borderSize + ); } - private Vector2 SnapTreeLinePoint(Vector2 point) - { - return new Vector2(MathF.Floor(point.X) + 0.5f, MathF.Floor(point.Y) + 0.5f); - } + private Vector2 SnapTreeLinePoint(Vector2 point) => new Vector2(MathF.Floor(point.X) + 0.5f, MathF.Floor(point.Y) + 0.5f); private void DrawTreeRowBackground( ImDrawList* drawList, @@ -457,165 +552,3 @@ uint color NativeImGui.Raw.ChannelsSetCurrent(drawList, 1); } } - -/// -/// Provides the native geometry of a tree row while its custom content is being drawn. -/// -public readonly struct TreeNodeDrawContext -{ - internal TreeNodeDrawContext(float rowHeight) - { - this.rowHeight = rowHeight; - } - - /// - /// Gets the actual native row height established for the current tree node. - /// - public float rowHeight { get; } -} - -/// -/// Configures an interactive tree row. -/// -public readonly struct TreeNodeOptions -{ - /// - /// Gets explicit indentation for a flattened row, or null for a nested native tree. - /// Explicit-depth rows never push a native tree scope; callers must not call TreePop for them. - /// - public int? depth { get; init; } - /// - /// Gets whether this row should receive keyboard focus during this submission when its tree window is focused. - /// - public bool requestFocus { get; init; } - - /// - /// Gets whether an active edit requires content submission even while its row is clipped. - /// - public bool keepContentActive { get; init; } - - /// - /// Gets whether the row is selected. - /// - public bool selected { get; init; } - /// - /// Gets whether the row has no expandable children. - /// - public bool isLeaf { get; init; } - /// - /// Gets whether a custom background is drawn behind an unselected row. - /// - public bool showBackground { get; init; } - /// - /// Gets the custom background color used when is enabled. - /// - public Vector4 backgroundColor { get; init; } - /// - /// Gets whether the row keeps its configured background while hovered. - /// - public bool suppressHoverHighlight { get; init; } - /// - /// Gets whether ancestor and branch guide lines are omitted for this row. - /// - public bool hideGuideLines { get; init; } - /// - /// Gets the callback that draws controls fixed to the current viewport without extending the - /// tree's horizontal content boundary. - /// - public Action? drawViewportOverlay { get; init; } -} - -/// -/// Describes interaction state produced by a tree row. -/// -public readonly struct TreeNodeResult -{ - internal TreeNodeResult( - bool isOpen, - bool isClicked, - bool isDoubleClicked, - bool isHovered, - Vector2 min, - Vector2 max, - Vector2 contentMin, - bool isSubmitted - ) { - this.isOpen = isOpen; - this.isClicked = isClicked; - this.isDoubleClicked = isDoubleClicked; - this.isHovered = isHovered; - this.min = min; - this.max = max; - this.contentMin = contentMin; - this.isSubmitted = isSubmitted; - } - - /// - /// Gets whether row controls were submitted; ordinary clipped rows are false, while preserved active edits remain true. - /// - public bool isSubmitted { get; } - - /// - /// Gets whether child content should be rendered. - /// - public bool isOpen { get; } - /// - /// Gets whether the content row was clicked. - /// - public bool isClicked { get; } - /// - /// Gets whether the content row was double-clicked. Double-clicking a non-leaf content row - /// also toggles its retained expansion state for the next frame. - /// - public bool isDoubleClicked { get; } - /// - /// Gets whether the full row is hovered. - /// - public bool isHovered { get; } - /// - /// Gets the row minimum screen coordinate. - /// - public Vector2 min { get; } - /// - /// Gets the row maximum screen coordinate. - /// - public Vector2 max { get; } - /// - /// Gets the minimum screen coordinate of the row's interactive content, excluding tree indentation. - /// - public Vector2 contentMin { get; } -} - -internal sealed class TreeWidgetWindowState -{ - internal ulong expansionRevision; - internal uint activeContentId; - internal string? activeContentOwner; - internal readonly HashSet navigationItemIds = []; - internal readonly List treeNodeStack = []; - internal readonly List lastNodeIdsByDepth = []; - internal readonly List lineSegments = []; - internal readonly Dictionary hasNextSiblingById = new(StringComparer.Ordinal); - internal readonly Dictionary openStatesById = new(StringComparer.Ordinal); - internal int lastFrame = -1; -} - -internal struct TreeWidgetNodeState -{ - internal string id; - internal Vector2 cursor; - internal float rowMaxY; - internal bool hasNextSibling; -} - -internal struct TreeWidgetLineSegment -{ - internal Vector2 from; - internal Vector2 to; -} - -internal struct TreeWidgetHighlightRect -{ - internal Vector2 min; - internal Vector2 max; -} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs index a62cd51f7..deb61ad29 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs @@ -1,6 +1,7 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -39,19 +40,23 @@ public void Trend( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(label); if (offset < 0 || (values.Length == 0 ? offset != 0 : offset >= values.Length)) + { throw new ArgumentOutOfRangeException(nameof(offset)); + } float maximum = 0f; float minimum = 0f; foreach (float value in values) { if (!float.IsFinite(value)) + { throw new ArgumentException("Trend samples must be finite.", nameof(values)); + } maximum = MathF.Max(maximum, value); minimum = MathF.Min(minimum, value); } NativeImGui.TextUnformatted(label); Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 size = new(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), style.trendHeight); + var size = new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), style.trendHeight); _ = NativeImGui.InvisibleButton(label, size); EditorDrawList draw = ImGui.GetDrawList(); draw.FilledRectangle(origin, origin + size, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.collectionRow)); @@ -65,7 +70,9 @@ public void Trend( float normalized = (float)(((double)value - minimum) / range); Vector2 point = origin + new Vector2(x * size.X, (1f - normalized) * size.Y); if (index > 0) + { draw.Line(previous, point, color); + } previous = point; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs new file mode 100644 index 000000000..ae419cb5b --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs @@ -0,0 +1,86 @@ +using System; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Describes the view-owned geometry used to present an active inline rename action. +/// +public sealed class InlineRenamePresentation +{ + /// + /// Creates inline rename presentation data. + /// + /// + /// The stable ImGui identifier used by the input field. + /// + /// + /// The requested input width in logical pixels. + /// + /// + /// The height of the row area in which the field is centered. + /// + /// + /// The maximum UTF-8 buffer size accepted by the input. + /// + /// + /// Thrown when is empty. + /// + /// + /// Thrown when or is not finite and + /// positive, or when is zero. + /// + public InlineRenamePresentation( + string id, + float width, + float rowHeight, + nuint bufferSize = 512 + ) { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentException("An inline rename identifier is required.", nameof(id)); + } + if (!float.IsFinite(width) || width <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(width), width, "The inline rename width must be finite and positive."); + } + + if (!float.IsFinite(rowHeight) || rowHeight <= 0f) + { + throw new ArgumentOutOfRangeException( + nameof(rowHeight), + rowHeight, + "The inline rename row height must be finite and positive." + ); + } + + if (bufferSize == 0) + { + throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "The inline rename buffer size must be positive."); + } + + this.id = id; + this.width = width; + this.rowHeight = rowHeight; + this.bufferSize = bufferSize; + } + + /// + /// Gets the stable ImGui identifier used by the input field. + /// + public string id { get; } + + /// + /// Gets the requested input width in logical pixels. + /// + public float width { get; } + + /// + /// Gets the height of the row area in which the input field is centered. + /// + public float rowHeight { get; } + + /// + /// Gets the maximum UTF-8 buffer size accepted by the input. + /// + public nuint bufferSize { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs new file mode 100644 index 000000000..43df7ae66 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs @@ -0,0 +1,67 @@ +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Carries frame-local list navigation intents over visible indices without owning objects or selection state. +/// +public readonly struct ListNavigationResult +{ + internal ListNavigationResult( + int focusedIndex, + bool focusChanged, + bool selectionRequested, + bool extendRange, + bool additive, + bool toggle, + bool activate, + bool cancel + ) { + this.focusedIndex = focusedIndex; + this.focusChanged = focusChanged; + this.selectionRequested = selectionRequested; + this.extendRange = extendRange; + this.additive = additive; + this.toggle = toggle; + this.activate = activate; + this.cancel = cancel; + } + + /// + /// Gets the resulting visible focus index, or minus one for no focus. + /// + public int focusedIndex { get; } + + /// + /// Gets whether the visible focus index changed. + /// + public bool focusChanged { get; } + + /// + /// Gets whether the caller should apply a domain selection operation. + /// + public bool selectionRequested { get; } + + /// + /// Gets whether the selection should extend from its existing anchor. + /// + public bool extendRange { get; } + + /// + /// Gets whether the product's primary modifier requests preserving other selected entries. + /// + public bool additive { get; } + + /// + /// Gets whether Space with the primary modifier requests toggling the focused entry. + /// + public bool toggle { get; } + + /// + /// Gets whether Enter requests activation of the focused entry. + /// + public bool activate { get; } + + /// + /// Gets whether Escape requests canceling the current list workflow. + /// + public bool cancel { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs new file mode 100644 index 000000000..d53f4f68a --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs @@ -0,0 +1,66 @@ +using System.Numerics; + +using EngineMatrix = Inno.Core.Mathematics.Matrix; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Supplies frame-local matrices and interaction policy without native handles. +/// +public readonly record struct TransformGizmoOptions +{ + /// + /// Gets the viewport's screen-space minimum. + /// + public Vector2 minimum { get; init; } + + /// + /// Gets the viewport's screen-space maximum. + /// + public Vector2 maximum { get; init; } + + /// + /// Gets the column-vector view matrix. + /// + public EngineMatrix view { get; init; } + + /// + /// Gets the projection matrix supplied by the viewport owner. + /// + public EngineMatrix projection { get; init; } + + /// + /// Gets whether this viewport uses an orthographic projection. + /// + public bool orthographic { get; init; } + + /// + /// Gets whether manipulation can consume pointer input. + /// + public bool enabled { get; init; } + + /// + /// Gets the requested handles. + /// + public TransformGizmoOperation operation { get; init; } + + /// + /// Gets the handle coordinate space. + /// + public TransformGizmoSpace space { get; init; } + + /// + /// Gets whether the X translation axis is excluded by the viewport plane. + /// + public bool maskX { get; init; } + + /// + /// Gets whether the Y translation axis is excluded by the viewport plane. + /// + public bool maskY { get; init; } + + /// + /// Gets whether the Z translation axis is excluded by the viewport plane. + /// + public bool maskZ { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs new file mode 100644 index 000000000..a7d8f8f14 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs @@ -0,0 +1,17 @@ +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Provides the native geometry of a tree row while its custom content is being drawn. +/// +public readonly struct TreeNodeDrawContext +{ + internal TreeNodeDrawContext(float rowHeight) + { + this.rowHeight = rowHeight; + } + + /// + /// Gets the actual native row height established for the current tree node. + /// + public float rowHeight { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs new file mode 100644 index 000000000..a0ae78418 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs @@ -0,0 +1,62 @@ +using System; +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Configures an interactive tree row. +/// +public readonly struct TreeNodeOptions +{ + /// + /// Gets explicit indentation for a flattened row, or null for a nested native tree. + /// Explicit-depth rows never push a native tree scope; callers must not call TreePop for them. + /// + public int? depth { get; init; } + + /// + /// Gets whether this row should receive keyboard focus during this submission when its tree window is focused. + /// + public bool requestFocus { get; init; } + + /// + /// Gets whether an active edit requires content submission even while its row is clipped. + /// + public bool keepContentActive { get; init; } + + /// + /// Gets whether the row is selected. + /// + public bool selected { get; init; } + + /// + /// Gets whether the row has no expandable children. + /// + public bool isLeaf { get; init; } + + /// + /// Gets whether a custom background is drawn behind an unselected row. + /// + public bool showBackground { get; init; } + + /// + /// Gets the custom background color used when is enabled. + /// + public Vector4 backgroundColor { get; init; } + + /// + /// Gets whether the row keeps its configured background while hovered. + /// + public bool suppressHoverHighlight { get; init; } + + /// + /// Gets whether ancestor and branch guide lines are omitted for this row. + /// + public bool hideGuideLines { get; init; } + + /// + /// Gets the callback that draws controls fixed to the current viewport without extending the + /// tree's horizontal content boundary. + /// + public Action? drawViewportOverlay { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs new file mode 100644 index 000000000..910331ebc --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs @@ -0,0 +1,70 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Describes interaction state produced by a tree row. +/// +public readonly struct TreeNodeResult +{ + internal TreeNodeResult( + bool isOpen, + bool isClicked, + bool isDoubleClicked, + bool isHovered, + Vector2 min, + Vector2 max, + Vector2 contentMin, + bool isSubmitted + ) { + this.isOpen = isOpen; + this.isClicked = isClicked; + this.isDoubleClicked = isDoubleClicked; + this.isHovered = isHovered; + this.min = min; + this.max = max; + this.contentMin = contentMin; + this.isSubmitted = isSubmitted; + } + + /// + /// Gets whether row controls were submitted; ordinary clipped rows are false, while preserved active edits remain true. + /// + public bool isSubmitted { get; } + + /// + /// Gets whether child content should be rendered. + /// + public bool isOpen { get; } + + /// + /// Gets whether the content row was clicked. + /// + public bool isClicked { get; } + + /// + /// Gets whether the content row was double-clicked. Double-clicking a non-leaf content row + /// also toggles its retained expansion state for the next frame. + /// + public bool isDoubleClicked { get; } + + /// + /// Gets whether the full row is hovered. + /// + public bool isHovered { get; } + + /// + /// Gets the row minimum screen coordinate. + /// + public Vector2 min { get; } + + /// + /// Gets the row maximum screen coordinate. + /// + public Vector2 max { get; } + + /// + /// Gets the minimum screen coordinate of the row's interactive content, excluding tree indentation. + /// + public Vector2 contentMin { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs new file mode 100644 index 000000000..41ce4a06e --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs @@ -0,0 +1,9 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal readonly struct TreeWidgetHighlightRect +{ + internal Vector2 min { get; init; } + internal Vector2 max { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs new file mode 100644 index 000000000..00dc2e7d0 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs @@ -0,0 +1,9 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal readonly struct TreeWidgetLineSegment +{ + internal Vector2 from { get; init; } + internal Vector2 to { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs new file mode 100644 index 000000000..b279ba3fc --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs @@ -0,0 +1,11 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal readonly struct TreeWidgetNodeState +{ + internal string id { get; init; } + internal Vector2 cursor { get; init; } + internal float rowMaxY { get; init; } + internal bool hasNextSibling { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs new file mode 100644 index 000000000..2497beb9c --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal sealed class TreeWidgetWindowState +{ + internal readonly HashSet navigationItemIDs = []; + internal readonly List treeNodeStack = []; + internal readonly List lastNodeIDsByDepth = []; + internal readonly List lineSegments = []; + internal readonly Dictionary hasNextSiblingByID = new(StringComparer.Ordinal); + internal readonly Dictionary openStatesByID = new(StringComparer.Ordinal); + internal ulong expansionRevision; + internal uint activeContentID; + internal string? activeContentOwner; + internal int lastFrame = -1; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs index 839cca60a..4d2d14daf 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs @@ -1,22 +1,18 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; -using System.Linq; using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; -using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; namespace Inno.Editor.Shaders.ImGui; + [InspectionDrawer(typeof(MaterialAsset))] internal sealed class MaterialInspectionDrawer(IInspectionIconProvider icons) : InspectionDrawer { /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.C_FILE; /// /// Retrieves the current icon from authoritative state. @@ -33,12 +29,13 @@ internal sealed class MaterialInspectionDrawer(IInspectionIconProvider context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetFileSystemEntry( - target.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + ) => context.interactions.TryGetModule(out MaterialDocuments? documents) + && documents is not null + && documents.assets.TryGetFileSystemEntry( + target.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -55,6 +52,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, MaterialAsset target ) => (target.name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -68,8 +66,10 @@ protected override void DrawHeader( InspectionDrawContext context, MaterialAsset target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) + { MaterialInspector.DrawHeader(context, documents, documents.Open(target)); + } } /// @@ -85,385 +85,9 @@ protected override void Draw( InspectionDrawContext context, MaterialAsset target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) - MaterialInspector.Draw(context, documents, documents.Open(target)); - } -} - -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class MaterialSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) - MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) - MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); - } -} - -internal static class MaterialInspector -{ - internal static void DrawHeader( - InspectionDrawContext context, - MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft - ) { - EditorUI.current.widgets.Disabled(draft.readOnly, () => + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) { - if (Ui.Button("Save")) - _ = context.interactions.documents.Save(draft.documentId); - Ui.SameLine(0f, -1f); - if (Ui.Button("Revert")) - _ = context.interactions.documents.Revert(draft.documentId); - }); - } - - internal static void Draw( - InspectionDrawContext context, - MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft - ) { - MaterialAsset material = documents.Read(draft.id); - var edits = new DraftEdits(documents, draft, material); - Ui.PushId(draft.id.ToString("N")); - try - { - if (EditorUI.current.widgets.SectionHeader("Preview", "Shows an isolated preview of the current Material draft.")) - { - if (material.shader is null || material.shader.isMissing) - EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); - else if (context.interactions.TryGetModule(out var shaderPreviews) && shaderPreviews is not null) - shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Ui.GetContentRegionAvailable().X))); - else - EditorUI.current.widgets.Hint("Material preview is unavailable."); - } - - bool materialOpen = EditorUI.current.widgets.SectionHeader( - "Material", - "Edits stay in this draft. Save publishes through normal asset import; Revert reloads the source." - ); - if (materialOpen) - { - EditorUI.current.widgets.Hint(draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate"); - if (draft.error.Length != 0) - EditorUI.current.widgets.Hint(draft.error); - if (draft.readOnly) - EditorUI.current.widgets.Hint("Installed material · copy to the project to edit"); - Draw("shader", "Shader", typeof(ShaderAsset), () => material.shader, value => material.shader = (ShaderAsset? )value); - } - - ShaderDefinition? definition = material.shader?.definition; - if (material.shader is null || material.shader.isMissing || definition is null) - { - if (materialOpen) - EditorUI.current.widgets.Hint("Choose an available Shader. Existing overrides are retained until its interface can be resolved."); - return; - } - - if (materialOpen && Ui.SmallButton("Open Shader Editor")) - { - context.interactions.SetSelection(material.shader); - context.interactions.OpenPanel("rendering.shader-editor"); - } - - if (materialOpen) - { - Ui.SameLine(0f, -1f); - if (Ui.SmallButton("Locate Shader") && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry)) - context.interactions.SetSelection(shaderEntry); - } - - if (materialOpen && (definition.techniques.Length > 1 || material.techniqueId.isValid)) - { - if (EditorUI.current.widgets.BeginBoundedCombo("##technique", material.techniqueId.isValid ? material.techniqueId.value : "Automatic")) - { - try - { - if (Ui.Selectable("Automatic", !material.techniqueId.isValid) && !draft.readOnly) - { - material.techniqueId = default; - documents.Replace(draft.id, material); - } - - foreach (ShaderTechniqueDefinition technique in definition.techniques) - if (Ui.Selectable(technique.id.value, material.techniqueId == technique.id) && !draft.readOnly) - { - material.techniqueId = technique.id; - documents.Replace(draft.id, material); - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - } - } - - bool parametersOpen = EditorUI.current.widgets.SectionHeader( - "Parameters", - "Inherited values follow Shader defaults. Changing a field creates a Material override; Reset restores inheritance." - ); - bool groupOpen = parametersOpen; - string currentGroup = ""; - int visibleParameters = 0; - foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) - { - ShaderParameterPresentation presentation = documents.Presentation(material.shader, property.id, out string presentationError); - if (presentationError.Length != 0) - EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); - if (!presentation.visible) - continue; - visibleParameters++; - if (presentation.group != currentGroup) - { - currentGroup = presentation.group; - groupOpen = EditorUI.current.widgets.SectionHeader(currentGroup.Length == 0 ? "Parameters" : currentGroup); - } - - if (!groupOpen) - continue; - bool overridden = material.TryGet(property.id, out MaterialValue value); - if (overridden && !ShaderPropertyInspector.Compatible(property.type, value.kind)) - continue; - if (!overridden) - value = property.defaultValue; - Ui.PushId(property.id.value); - try - { - ShaderPropertyInspector.Draw( - context, - draft, - "material." + property.id.value, - property, - value, - next => material.Set(property.id, next), - edits, - draft.readOnly, - presentation - ); - EditorUI.current.widgets.Hint(overridden ? "Material override" : "Inherited from Shader"); - if (overridden && !draft.readOnly && Ui.SmallButton("Reset override")) - { - material.ReplaceProperties(material.properties.Where(entry => entry.id != property.id).ToArray()); - documents.Replace(draft.id, material); - } - - if (value.kind == MaterialValueKind.Texture) - { - if (value.texture is { isMissing: false } texture && documents.previews.TryGetTexture(texture, out var preview)) - { - float width = MathF.Max(1f, MathF.Min(128f, Ui.GetContentRegionAvailable().X)); - float height = width * preview.pixelHeight / preview.pixelWidth; - if (height > 128f) - { - width *= 128f / height; - height = 128f; - } - - documents.previews.Draw(preview, new(width, height)); - } - } - } - finally - { - Ui.PopId(); - } - } - - if (parametersOpen && visibleParameters == 0 && definition.keywords.Length == 0) - EditorUI.current.widgets.Hint("No editable parameters."); - if (parametersOpen && material.properties.Count != 0 && !draft.readOnly && Ui.Button("Reset all overrides")) - { - material.ReplaceProperties([]); - documents.Replace(draft.id, material); - } - - foreach (ShaderKeywordDefinition keyword in parametersOpen ? definition.keywords : []) - { - string selected = keyword.options.FirstOrDefault(option => material.keywords.Contains(option)) ?? "None"; - if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, selected)) - continue; - try - { - if (Ui.Selectable("None", selected == "None")) - SetOption(null); - foreach (string option in keyword.options) - if (Ui.Selectable(option, selected == option)) - SetOption(option); - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - void SetOption(string? next) - { - if (draft.readOnly) - return; - foreach (string option in keyword.options) - material.SetKeyword(option, option == next); - documents.Replace(draft.id, material); - } - } - - MaterialPropertyEntry[] orphaned = material.properties.Where(entry => !definition.properties.Any(property => property.id == entry.id && IsEditable(property) && ShaderPropertyInspector.Compatible(property.type, entry.value.kind))).ToArray(); - if (orphaned.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader( - "Unresolved Overrides", - "These values were retained after an interface change. Remove them explicitly or restore a compatible Shader before publishing." - )) - { - foreach (MaterialPropertyEntry entry in orphaned) - { - Ui.Text(entry.id.value + " · " + entry.value.kind); - if (!draft.readOnly && Ui.SmallButton("Remove##" + entry.id.value)) - { - material.ReplaceProperties(material.properties.Where(value => value.id != entry.id).ToArray()); - documents.Replace(draft.id, material); - } - } - } - } - - ShaderPropertyDefinition[] passBindings = definition.properties.Where(property => !IsEditable(property)).ToArray(); - string[] unknownKeywords = material.keywords.Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))).ToArray(); - if (unknownKeywords.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader( - "Unresolved Keywords", - "These overrides no longer belong to the Shader interface. They remain until explicitly removed." - )) - { - foreach (string keyword in unknownKeywords) - { - Ui.Text(keyword); - if (!draft.readOnly && Ui.SmallButton("Remove##keyword." + keyword)) - { - material.SetKeyword(keyword, false); - documents.Replace(draft.id, material); - } - } - } - } - - if (passBindings.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader("Pipeline Bindings", "These resources are supplied by the Render Pass, not by this Material.")) - { - foreach (ShaderPropertyDefinition property in passBindings) - EditorUI.current.widgets.Hint(property.displayName + " · " + property.type + " · " + property.bindingOwner); - } - } - } - finally - { - Ui.PopId(); - } - - void Draw( - string path, - string label, - Type type, - Func getter, - Action setter - ) => context.properties.DrawValue(context.editorContext, draft, "material." + path, label, type, getter, setter, edits, draft.readOnly); - } - - private static bool IsEditable(ShaderPropertyDefinition property) => property.bindingOwner == ShaderPropertyBindingOwner.Material - && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; - private sealed class DraftEdits( - MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft, - MaterialAsset material - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - mutation(); - documents.Replace(draft.id, material, mergeKey); - return true; + MaterialInspector.Draw(context, documents, documents.Open(target)); } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs new file mode 100644 index 000000000..b4ecfa71d --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs @@ -0,0 +1,388 @@ +using System; +using System.Linq; +using System.Numerics; +using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Shaders.ImGui; + +internal static class MaterialInspector +{ + internal static void DrawHeader( + InspectionDrawContext context, + MaterialDocuments documents, + AssetDraftDocuments.Draft draft + ) => EditorUI.current.widgets.Disabled(draft.readOnly, () => + { + if (Gui.Button("Save")) + { + _ = context.interactions.documents.Save(draft.documentID); + } + Gui.SameLine(0f, -1f); + if (Gui.Button("Revert")) + { + _ = context.interactions.documents.Revert(draft.documentID); + } + }); + + internal static void Draw( + InspectionDrawContext context, + MaterialDocuments documents, + AssetDraftDocuments.Draft draft + ) { + MaterialAsset material = documents.Read(draft.id); + var edits = new DraftEdits(documents, draft, material); + Gui.PushID(draft.id.ToString("N")); + try + { + if (EditorUI.current.widgets.SectionHeader("Preview", "Shows an isolated preview of the current Material draft.")) + { + if (material.shader is null || material.shader.isMissing) + { + EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); + } + else if (context.interactions.TryGetModule(out ShaderPreviews? shaderPreviews) + && shaderPreviews is not null + ) { + shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Gui.GetContentRegionAvailable().X))); + } + else + { + EditorUI.current.widgets.Hint("Material preview is unavailable."); + } + } + + bool materialOpen = EditorUI.current.widgets.SectionHeader( + "Material", + "Edits stay in this draft. Save publishes through normal asset import; Revert reloads the source." + ); + if (materialOpen) + { + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate" + ); + if (draft.error.Length != 0) + { + EditorUI.current.widgets.Hint(draft.error); + } + if (draft.readOnly) + { + EditorUI.current.widgets.Hint("Installed material · copy to the project to edit"); + } + Draw("shader", "Shader", typeof(ShaderAsset), () => material.shader, value => material.shader = (ShaderAsset? )value); + } + + ShaderDefinition? definition = material.shader?.definition; + if (material.shader is null || material.shader.isMissing || definition is null) + { + if (materialOpen) + { + EditorUI.current.widgets.Hint( + "Choose an available Shader. Existing overrides are retained until its interface can be resolved." + ); + } + return; + } + + if (materialOpen && Gui.SmallButton("Open Shader Editor")) + { + context.interactions.SetSelection(material.shader); + context.interactions.OpenPanel("rendering.shader-editor"); + } + + if (materialOpen) + { + Gui.SameLine(0f, -1f); + if (Gui.SmallButton("Locate Shader") + && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry) + ) { + context.interactions.SetSelection(shaderEntry); + } + } + + if (materialOpen && (definition.techniques.Length > 1 || material.techniqueId.isValid)) + { + if (EditorUI.current.widgets.BeginBoundedCombo( + "##technique", + material.techniqueId.isValid ? material.techniqueId.value : "Automatic" + )) { + try + { + if (Gui.Selectable("Automatic", !material.techniqueId.isValid) && !draft.readOnly) + { + material.techniqueId = default; + documents.Replace(draft.id, material); + } + + foreach (ShaderTechniqueDefinition technique in definition.techniques) + { + if (Gui.Selectable(technique.id.value, material.techniqueId == technique.id) && !draft.readOnly) + { + material.techniqueId = technique.id; + documents.Replace(draft.id, material); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + } + } + + bool parametersOpen = EditorUI.current.widgets.SectionHeader( + "Parameters", + "Inherited values follow Shader defaults. Changing a field creates a Material override; Reset restores inheritance." + ); + bool groupOpen = parametersOpen; + string currentGroup = string.Empty; + int visibleParameters = 0; + foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) + { + ShaderParameterPresentation presentation = documents.Presentation( + material.shader, + property.id, + out string presentationError + ); + if (presentationError.Length != 0) + { + EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); + } + if (!presentation.visible) + { + continue; + } + visibleParameters++; + if (presentation.group != currentGroup) + { + currentGroup = presentation.group; + groupOpen = EditorUI.current.widgets.SectionHeader(currentGroup.Length == 0 ? "Parameters" : currentGroup); + } + + if (!groupOpen) + { + continue; + } + bool overridden = material.TryGet(property.id, out MaterialValue value); + if (overridden && !ShaderPropertyInspector.Compatible(property.type, value.kind)) + { + continue; + } + if (!overridden) + { + value = property.defaultValue; + } + Gui.PushID(property.id.value); + try + { + ShaderPropertyInspector.Draw( + context, + draft, + "material." + property.id.value, + property, + value, + next => material.Set(property.id, next), + edits, + draft.readOnly, + presentation + ); + EditorUI.current.widgets.Hint(overridden ? "Material override" : "Inherited from Shader"); + if (overridden && !draft.readOnly && Gui.SmallButton("Reset override")) + { + material.ReplaceProperties(material.properties.Where(entry => entry.id != property.id).ToArray()); + documents.Replace(draft.id, material); + } + + if (value.kind == MaterialValueKind.Texture) + { + if (value.texture is { isMissing: false } texture + && documents.previews.TryGetTexture(texture, out EditorPreviewHandle preview) + ) { + float width = MathF.Max(1f, MathF.Min(128f, Gui.GetContentRegionAvailable().X)); + float height = width * preview.pixelHeight / preview.pixelWidth; + if (height > 128f) + { + width *= 128f / height; + height = 128f; + } + + documents.previews.Draw(preview, new Vector2(width, height)); + } + } + } + finally + { + Gui.PopID(); + } + } + + if (parametersOpen && visibleParameters == 0 && definition.keywords.Length == 0) + { + EditorUI.current.widgets.Hint("No editable parameters."); + } + if (parametersOpen && material.properties.Count != 0 && !draft.readOnly && Gui.Button("Reset all overrides")) + { + material.ReplaceProperties([]); + documents.Replace(draft.id, material); + } + + foreach (ShaderKeywordDefinition keyword in parametersOpen ? definition.keywords : []) + { + string selected = keyword.options.FirstOrDefault(option => material.keywords.Contains(option)) ?? "None"; + if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, selected)) + { + continue; + } + try + { + if (Gui.Selectable("None", selected == "None")) + { + SetOption(null); + } + foreach (string option in keyword.options) + { + if (Gui.Selectable(option, selected == option)) + { + SetOption(option); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + void SetOption(string? next) + { + if (draft.readOnly) + { + return; + } + foreach (string option in keyword.options) + { + material.SetKeyword(option, option == next); + } + documents.Replace(draft.id, material); + } + } + + MaterialPropertyEntry[] orphaned = material.properties + .Where( + entry => !definition.properties.Any( + property => ( + property.id == entry.id + && IsEditable(property) + && ShaderPropertyInspector.Compatible(property.type, entry.value.kind) + ) + ) + ) + .ToArray(); + if (orphaned.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Unresolved Overrides", + "These values were retained after an interface change. Remove them explicitly or restore a compatible Shader before publishing." + )) { + foreach (MaterialPropertyEntry entry in orphaned) + { + Gui.Text(entry.id.value + " · " + entry.value.kind); + if (!draft.readOnly && Gui.SmallButton("Remove##" + entry.id.value)) + { + material.ReplaceProperties(material.properties.Where(value => value.id != entry.id).ToArray()); + documents.Replace(draft.id, material); + } + } + } + } + + ShaderPropertyDefinition[] passBindings = definition.properties.Where(property => !IsEditable(property)).ToArray(); + string[] unknownKeywords = material.keywords + .Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))) + .ToArray(); + if (unknownKeywords.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Unresolved Keywords", + "These overrides no longer belong to the Shader interface. They remain until explicitly removed." + )) { + foreach (string keyword in unknownKeywords) + { + Gui.Text(keyword); + if (!draft.readOnly && Gui.SmallButton("Remove##keyword." + keyword)) + { + material.SetKeyword(keyword, false); + documents.Replace(draft.id, material); + } + } + } + } + + if (passBindings.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Pipeline Bindings", + "These resources are supplied by the Render Pass, not by this Material." + )) { + foreach (ShaderPropertyDefinition property in passBindings) + { + EditorUI.current.widgets.Hint(property.displayName + " · " + property.type + " · " + property.bindingOwner); + } + } + } + } + finally + { + Gui.PopID(); + } + + void Draw( + string path, + string label, + Type type, + Func getter, + Action setter + ) => context.properties.DrawValue( + context.editorContext, + draft, + "material." + path, + label, + type, + getter, + setter, + edits, + draft.readOnly + ); + } + + private static bool IsEditable(ShaderPropertyDefinition property) + => property.bindingOwner == ShaderPropertyBindingOwner.Material + && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; + + private sealed class DraftEdits( + MaterialDocuments documents, + AssetDraftDocuments.Draft draft, + MaterialAsset material + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + mutation(); + documents.Replace(draft.id, material, mergeKey); + return true; + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs index fc5373a7d..88c0be14a 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs @@ -1,19 +1,22 @@ -using Inno.Editor.ImGui; -using Inno.Editor.Interactions; -using Inno.Core.Identity; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; +using Inno.Editor.Interactions; +using Inno.Editor.Shaders; using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Shaders.ImGui; + [InspectionDrawer(typeof(EditorSelectionSnapshot), priority: 100, conditional: true)] internal sealed class MaterialSelectionDrawer( IInspectionIconProvider icons, @@ -23,7 +26,7 @@ EditorInteractions interactions /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.C_FILE; /// /// Retrieves the current icon from authoritative state. @@ -41,19 +44,16 @@ protected override string GetIcon( InspectionDrawContext context, EditorSelectionSnapshot target ) { - Guid id = GetAssetIds(target).FirstOrDefault(); + Guid id = GetAssetIDs(target).FirstOrDefault(); return id != Guid.Empty - && context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - id, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && context.interactions.TryGetModule(out MaterialDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(id, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; } /// @@ -71,7 +71,8 @@ out AssetFileEntry entry protected override (string name, Action? setter) BindName( InspectionDrawContext context, EditorSelectionSnapshot target - ) => (GetAssetIds(target).Count + " Assets", null); + ) => (GetAssetIDs(target).Count + " Assets", null); + /// /// Renders the header presentation for the current editor frame. /// @@ -85,26 +86,32 @@ protected override void DrawHeader( InspectionDrawContext context, EditorSelectionSnapshot target ) { - if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out var drafts)) + if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out List.Draft> drafts)) + { return; + } bool readOnly = drafts.Any(value => value.readOnly); ImGuiApi.BeginDisabled(readOnly); try { if (ImGuiApi.Button("Save Selected")) { - EditorUiSession.current.widgets.CommitEdits(); - foreach (var draft in drafts) - _ = context.interactions.documents.Save(draft.documentId); + EditorUISession.current.widgets.CommitEdits(); + foreach (AssetDraftDocuments.Draft draft in drafts) + { + _ = context.interactions.documents.Save(draft.documentID); + } } ImGuiApi.SameLine(0f, -1f); if (ImGuiApi.Button("Revert Selected")) { - EditorUiSession.current.widgets.CommitEdits(); - using var transaction = context.interactions.history.BeginTransaction("Revert Materials"); - foreach (var draft in drafts) - _ = context.interactions.documents.Revert(draft.documentId); + EditorUISession.current.widgets.CommitEdits(); + using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Revert Materials"); + foreach (AssetDraftDocuments.Draft draft in drafts) + { + _ = context.interactions.documents.Revert(draft.documentID); + } transaction.Commit(); } } @@ -127,24 +134,28 @@ protected override void Draw( InspectionDrawContext context, EditorSelectionSnapshot target ) { - if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out var drafts)) + if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out List.Draft> drafts)) { EditorUI.current.widgets.Hint("Select Materials with compatible Shader interfaces to edit their common parameters."); return; } MaterialDocuments owner = documents!; - var materials = drafts.ToDictionary(value => value.id, value => owner.Read(value.id)); + Dictionary materials = drafts.ToDictionary(value => value.id, value => owner.Read(value.id)); bool readOnly = drafts.Any(value => value.readOnly); - ImGuiApi.PushId("materials." + string.Join(".", GetAssetIds(target))); + ImGuiApi.PushID("materials." + string.Join(".", GetAssetIDs(target))); ImGuiApi.BeginDisabled(readOnly); try { EditorUI.current.widgets.Hint("Save runs per document. Unsaved edits do not change Scene/Game."); if (readOnly) + { EditorUI.current.widgets.Hint("Selection includes installed read-only content. Copy it to the project before editing."); - foreach (var draft in drafts.Where(value => value.error.Length != 0)) + } + foreach (AssetDraftDocuments.Draft draft in drafts.Where(value => value.error.Length != 0)) + { EditorUI.current.widgets.Hint(draft.path.localPath + ": " + draft.error); + } var edits = new SelectionEdits(owner, materials); MaterialAsset first = materials.Values.First(); bool selectionOpen = EditorUI.current.widgets.SectionHeader( @@ -153,23 +164,49 @@ EditorSelectionSnapshot target ); if (selectionOpen) { - if (materials.Values.Any(value => value.shader?.identity.persistentId != first.shader?.identity.persistentId)) - EditorUI.current.widgets.Hint("Shader · Mixed values"); - context.properties.DrawValue(context.editorContext, target, "materials.shader", "Shader", typeof(ShaderAsset), () => first.shader, value => + if (materials.Values.Any(value => value.shader?.identity.persistentID != first.shader?.identity.persistentID)) { - foreach (MaterialAsset material in materials.Values) - material.shader = (ShaderAsset? )value; - }, edits, readOnly); + EditorUI.current.widgets.Hint("Shader · Mixed values"); + } + context.properties.DrawValue( + context.editorContext, + target, + "materials.shader", + "Shader", + typeof(ShaderAsset), + () => first.shader, + value => + { + foreach (MaterialAsset material in materials.Values) + { + material.shader = (ShaderAsset? )value; + } + }, + edits, + readOnly + ); } if (first.shader is null || first.shader.isMissing || first.shader.definition is not { } firstDefinition) { if (selectionOpen) + { EditorUI.current.widgets.Hint("A selected Shader is unavailable."); + } return; } - ShaderTechniqueId[] commonTechniques = firstDefinition.techniques.Select(value => value.id).Where(id => materials.Values.All(material => material.shader is { isMissing: false, definition: { } definition } && definition.techniques.Any(technique => technique.id == id))).ToArray(); + ShaderTechniqueID[] commonTechniques = firstDefinition.techniques + .Select(value => value.id) + .Where( + id => materials.Values.All( + material => ( + material.shader is { isMissing: false, definition: { } definition } + && definition.techniques.Any(technique => technique.id == id) + ) + ) + ) + .ToArray(); bool mixedTechnique = materials.Values.Any(value => value.techniqueId != first.techniqueId); if (selectionOpen && (commonTechniques.Length > 1 || materials.Values.Any(value => value.techniqueId.isValid))) { @@ -179,10 +216,16 @@ EditorSelectionSnapshot target try { if (ImGuiApi.Selectable("Automatic", !mixedTechnique && !first.techniqueId.isValid)) + { SetTechnique(default); - foreach (ShaderTechniqueId technique in commonTechniques) + } + foreach (ShaderTechniqueID technique in commonTechniques) + { if (ImGuiApi.Selectable(technique.value, !mixedTechnique && first.techniqueId == technique)) + { SetTechnique(technique); + } + } } finally { @@ -193,20 +236,34 @@ EditorSelectionSnapshot target foreach (ShaderKeywordDefinition keyword in selectionOpen ? firstDefinition.keywords : []) { - if (!materials.Values.All(material => material.shader is { isMissing: false, definition: { } definition } && definition.keywords.Any(value => value.id == keyword.id && value.options.SequenceEqual(keyword.options)))) + if (!materials.Values.All( + material => ( + material.shader is { isMissing: false, definition: { } definition } + && definition.keywords.Any(value => value.id == keyword.id && value.options.SequenceEqual(keyword.options)) + ) + )) { continue; + } string Option(MaterialAsset material) => keyword.options.FirstOrDefault(material.keywords.Contains) ?? "None"; string selected = Option(first); bool mixed = materials.Values.Any(material => Option(material) != selected); if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, mixed ? "Mixed values" : selected)) + { continue; + } try { if (ImGuiApi.Selectable("None", !mixed && selected == "None")) + { SetOption(null); + } foreach (string option in keyword.options) + { if (ImGuiApi.Selectable(option, !mixed && selected == option)) + { SetOption(option); + } + } } finally { @@ -216,8 +273,12 @@ EditorSelectionSnapshot target void SetOption(string? next) { foreach (MaterialAsset material in materials.Values) + { foreach (string option in keyword.options) + { material.SetKeyword(option, option == next); + } + } owner.ReplaceMany(materials); } } @@ -227,25 +288,38 @@ void SetOption(string? next) "Only compatible Material-owned inputs appear here. Unrelated overrides are retained per Material." ); bool groupOpen = parametersOpen; - string currentGroup = ""; + string currentGroup = string.Empty; foreach (ShaderPropertyDefinition property in firstDefinition.properties) { if (property.bindingOwner != ShaderPropertyBindingOwner.Material - || property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture)) + || property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture) + ) { continue; - var values = new List(); + } + List values = []; ShaderParameterPresentation presentation = owner.Presentation(first.shader, property.id, out string presentationError); if (presentationError.Length != 0) + { EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); + } if (!presentation.visible) + { continue; + } bool compatible = true; foreach (MaterialAsset material in materials.Values) { - ShaderPropertyDefinition[] declarations = material.shader is { isMissing: false } shader ? shader.definition?.properties ?? [] : []; + ShaderPropertyDefinition[] declarations = material.shader is { isMissing: false } shader + ? shader.definition?.properties ?? [] + : []; int index = Array.FindIndex( declarations, - value => value.id == property.id && value.type == property.type && value.bindingKind == property.bindingKind && value.bindingOwner == property.bindingOwner + value => ( + value.id == property.id + && value.type == property.type + && value.bindingKind == property.bindingKind + && value.bindingOwner == property.bindingOwner + ) ); if (index < 0) { @@ -280,7 +354,9 @@ void SetOption(string? next) } } - MaterialValue value = material.TryGet(property.id, out var overridden) ? overridden : declarations[index].defaultValue; + MaterialValue value = material.TryGet(property.id, out MaterialValue overridden) + ? overridden + : declarations[index].defaultValue; if (!ShaderPropertyInspector.Compatible(property.type, value.kind)) { compatible = false; @@ -291,7 +367,9 @@ void SetOption(string? next) } if (!compatible) + { continue; + } if (presentation.group != currentGroup) { currentGroup = presentation.group; @@ -299,86 +377,107 @@ void SetOption(string? next) } if (!groupOpen) + { continue; + } bool mixed = values.Skip(1).Any(value => !value.Equals(values[0])); - ImGuiApi.PushId(property.id.value); + ImGuiApi.PushID(property.id.value); try { if (mixed) + { EditorUI.current.widgets.Hint(property.displayName + " · Mixed values (editing applies to all selected Materials)"); + } ShaderPropertyInspector.Draw(context, target, "materials." + property.id.value, property, values[0], value => { int selectedIndex = 0; foreach (MaterialAsset material in materials.Values) - material.Set(property.id, ShaderPropertyInspector.ApplyEdit(property.type, values[0], value, values[selectedIndex++])); + { + material.Set( + property.id, + ShaderPropertyInspector.ApplyEdit(property.type, values[0], value, values[selectedIndex++]) + ); + } }, edits, readOnly, presentation); if (mixed && ImGuiApi.SmallButton("Use First Value for Selection")) { foreach (MaterialAsset material in materials.Values) + { material.Set(property.id, values[0]); + } owner.ReplaceMany(materials); } if (ImGuiApi.SmallButton("Reset Selected Overrides")) { foreach (MaterialAsset material in materials.Values) + { material.ReplaceProperties(material.properties.Where(value => value.id != property.id).ToArray()); + } owner.ReplaceMany(materials); } } finally { - ImGuiApi.PopId(); + ImGuiApi.PopID(); } } - if (parametersOpen && materials.Values.Any(value => value.properties.Count != 0) && ImGuiApi.Button("Reset All Selected Overrides")) - { + if (parametersOpen + && materials.Values.Any(value => value.properties.Count != 0) + && ImGuiApi.Button("Reset All Selected Overrides") + ) { foreach (MaterialAsset material in materials.Values) + { material.ReplaceProperties([]); + } owner.ReplaceMany(materials); } - void SetTechnique(ShaderTechniqueId technique) + void SetTechnique(ShaderTechniqueID technique) { foreach (MaterialAsset material in materials.Values) + { material.techniqueId = technique; + } owner.ReplaceMany(materials); } } finally { ImGuiApi.EndDisabled(); - ImGuiApi.PopId(); + ImGuiApi.PopID(); } } /// - protected override bool CanInspect(EditorSelectionSnapshot target) => target.identities.Count > 1 && GetAssetIds(target).Count == target.identities.Count; - private IReadOnlyList GetAssetIds(EditorSelectionSnapshot target) + protected override bool CanInspect(EditorSelectionSnapshot target) + => target.identities.Count > 1 && GetAssetIDs(target).Count == target.identities.Count; + + private IReadOnlyList GetAssetIDs(EditorSelectionSnapshot target) { - if (!interactions.TryGetModule(out var materials) || materials is null) - return Array.Empty(); + if (!interactions.TryGetModule(out MaterialDocuments? materials) || materials is null) + { + return []; + } var ids = new List(target.identities.Count); var entries = new List(target.identities.Count); target.CopyTargets(interactions, entries); if (entries.Count != target.identities.Count) - return Array.Empty(); + { + return []; + } entries.Reverse(); foreach (AssetFileEntry entry in entries) { if (entry.isDirectory - || !entry.extension.Equals( - ".imaterial", - StringComparison.OrdinalIgnoreCase - ) - || !materials.assets.TryGetInfo( - entry.assetPath, - out AssetInfo? info - ) - || info is null) - return Array.Empty(); - ids.Add(info.persistentId); + || !entry.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase) + || !materials.assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + || info is null + ) { + return []; + } + ids.Add(info.persistentID); } return ids; @@ -388,28 +487,23 @@ private bool TryOpenDrafts( InspectionDrawContext context, EditorSelectionSnapshot target, out MaterialDocuments? documents, - out List.Draft> drafts + out List.Draft> drafts ) { drafts = []; if (!context.interactions.TryGetModule(out documents) || documents is null) + { return false; - foreach (Guid id in GetAssetIds(target)) + } + foreach (Guid id in GetAssetIDs(target)) { - if (!documents.assets.TryGetInfo( - id, - out AssetInfo? info - ) + if (!documents.assets.TryGetInfo(id, out AssetInfo? info) || info is null - || !documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) - || !entry.extension.Equals( - ".imaterial", - StringComparison.OrdinalIgnoreCase - )) + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + || !entry.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase) + ) { return false; - var draft = documents.OpenDraft(info.assetPath); + } + AssetDraftDocuments.Draft draft = documents.OpenDraft(info.assetPath); drafts.Add(draft); } @@ -421,7 +515,7 @@ private sealed class SelectionEdits( IReadOnlyDictionary materials ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs new file mode 100644 index 000000000..f8b986de4 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs @@ -0,0 +1,99 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Shaders.ImGui; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class MaterialSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => ImGuiIcon.C_FILE; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) + { + MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) + { + MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs index 4b63d7825..2820c09a5 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs @@ -1,12 +1,14 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using Inno.Core.Mathematics; using Inno.Editor.Inspection; +using Inno.Editor.Shaders; using Inno.Rendering; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUISession; + namespace Inno.Editor.Shaders.ImGui; + /// /// Uses the shared Inspector drawers for both Shader defaults and Material overrides. /// @@ -69,15 +71,30 @@ public static void Draw( maximum: property.type == ShaderPropertyType.Float && presentation?.hasRange == true ? presentation.maximum : null ); if (property.type == ShaderPropertyType.Color) + { EditorUI.current.widgets.Hint("Linear RGBA · HDR values are preserved"); + } if (property.bindingKind == ShaderPropertyBindingKind.SampledTexture) - context.properties.DrawValue(context.editorContext, owner, path + ".sampler", "Sampler", typeof(RenderSamplerState), () => value.sampler, next => + { + context.properties.DrawValue( + context.editorContext, + owner, + path + + ".sampler", + "Sampler", + typeof(RenderSamplerState), + () => value.sampler, + next => { - var candidate = value; + MaterialValue candidate = value; candidate.kind = MaterialValueKind.Texture; candidate.sampler = (RenderSamplerState)next!; setter(candidate); - }, edits, readOnly); + }, + edits, + readOnly + ); + } } /// @@ -101,9 +118,13 @@ MaterialValueKind kind ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => kind == MaterialValueKind.Vector, ShaderPropertyType.Color => kind == MaterialValueKind.Color, ShaderPropertyType.Matrix4x4 => kind == MaterialValueKind.Matrix, - ShaderPropertyType.Texture2D or ShaderPropertyType.Texture2DArray or ShaderPropertyType.Texture3D or ShaderPropertyType.TextureCube => kind == MaterialValueKind.Texture, + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => kind == MaterialValueKind.Texture, _ => false }; + /// /// Applies the edited components of a representative value without replacing unrelated mixed components. /// @@ -129,13 +150,19 @@ public static MaterialValue ApplyEdit( MaterialValue target ) { if (!Compatible(type, before.kind) || !Compatible(type, edited.kind) || !Compatible(type, target.kind)) + { throw new ArgumentException("A multi-Material edit requires exactly matching value kinds."); + } if (type == ShaderPropertyType.Float) + { return edited; + } if (edited.kind == MaterialValueKind.Texture) { if (!ReferenceEquals(before.texture, edited.texture)) + { target.texture = edited.texture; + } target.sampler = new( before.sampler.filter == edited.sampler.filter ? target.sampler.filter : edited.sampler.filter, before.sampler.addressU == edited.sampler.addressU ? target.sampler.addressU : edited.sampler.addressU, @@ -145,7 +172,9 @@ MaterialValue target } else if (edited.kind == MaterialValueKind.Matrix) { - Matrix b = before.matrix, e = edited.matrix, t = target.matrix; + Matrix b = before.matrix; + Matrix e = edited.matrix; + Matrix t = target.matrix; target.matrix = new( Merge(b.m11, e.m11, t.m11), Merge(b.m12, e.m12, t.m12), @@ -167,7 +196,9 @@ MaterialValue target } else { - Vector4 b = before.vector, e = edited.vector, t = target.vector; + Vector4 b = before.vector; + Vector4 e = edited.vector; + Vector4 t = target.vector; target.vector = new(Merge(b.x, e.x, t.x), Merge(b.y, e.y, t.y), Merge(b.z, e.z, t.z), Merge(b.w, e.w, t.w)); } @@ -179,7 +210,8 @@ float current ) => BitConverter.SingleToUInt32Bits(previous) == BitConverter.SingleToUInt32Bits(next) ? current : next; } - private static Type ValueType(ShaderPropertyType type) => type switch + private static Type ValueType(ShaderPropertyType type) + => type switch { ShaderPropertyType.Float => typeof(float), ShaderPropertyType.Vector2 => typeof(Vector2), @@ -187,8 +219,13 @@ float current ShaderPropertyType.Vector4 => typeof(Vector4), ShaderPropertyType.Color => typeof(Color), ShaderPropertyType.Matrix4x4 => typeof(Matrix), - ShaderPropertyType.Texture2D or ShaderPropertyType.Texture2DArray or ShaderPropertyType.Texture3D or ShaderPropertyType.TextureCube => typeof(TextureAsset), - _ => throw new InvalidOperationException("No material editor exists for " + type)}; + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => typeof(TextureAsset), + _ => throw new InvalidOperationException("No material editor exists for " + type) + }; + private static object? Unbox( ShaderPropertyType type, MaterialValue value @@ -202,6 +239,7 @@ MaterialValue value ShaderPropertyType.Matrix4x4 => value.matrix, _ => value.texture }; + private static MaterialValue Box( ShaderPropertyType type, object? value, @@ -210,7 +248,9 @@ MaterialValue previous { ShaderPropertyType.Float => MaterialValue.FromFloat((float)value!), ShaderPropertyType.Vector2 => MaterialValue.FromVector(new Vector4(((Vector2)value!).x, ((Vector2)value!).y, 0, 0)), - ShaderPropertyType.Vector3 => MaterialValue.FromVector(new Vector4(((Vector3)value!).x, ((Vector3)value!).y, ((Vector3)value!).z, 0)), + ShaderPropertyType.Vector3 => MaterialValue.FromVector( + new Vector4(((Vector3)value!).x, ((Vector3)value!).y, ((Vector3)value!).z, 0) + ), ShaderPropertyType.Vector4 => MaterialValue.FromVector((Vector4)value!), ShaderPropertyType.Color => MaterialValue.FromColor((Color)value!), ShaderPropertyType.Matrix4x4 => MaterialValue.FromMatrix((Matrix)value!), diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs new file mode 100644 index 000000000..835106669 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs @@ -0,0 +1,177 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Exposes detached node values and one-gesture writes without exposing the live graph document. +/// +public sealed class ShaderNodeDrawContext +{ + private readonly GraphNodeRecord m_node; + private readonly SerializationRegistry m_serialization; + private readonly SerializationContext m_context; + private readonly Action m_write; + private readonly InspectionDrawContext m_inspection; + private readonly bool m_readOnly; + + /// + /// Creates invocation-scoped access for a graph or Inspector host. + /// + /// + /// Detached node values for this invocation. + /// + /// + /// Current owner converter registry. + /// + /// + /// Complete owner reference context. + /// + /// + /// Host callback recording changes in the shared draft history. + /// + /// + /// Current generation preview service. + /// + /// + /// Shared Inspector context, including native property controls and drag/drop. + /// + /// + /// Whether the source belongs to an immutable installation. + /// + public ShaderNodeDrawContext( + GraphNodeRecord node, + SerializationRegistry serialization, + SerializationContext context, + Action write, + IEditorPreviewService previews, + InspectionDrawContext inspection, + bool readOnly + ) { + m_node = node; + m_serialization = serialization; + m_context = context; + m_write = write; + this.previews = previews; + m_inspection = inspection; + m_readOnly = readOnly; + } + + /// + /// Gets the shared generation-scoped preview service for optional inline texture previews; valid only during this draw. + /// + public IEditorPreviewService previews { get; } + + /// + /// Gets the stable node identity for Editor widget IDs. + /// + public GraphNodeID nodeID => m_node.id; + + /// + /// Reads a detached property value; missing values use the node's declared default. + /// + /// + /// Native serializable property type. + /// + /// + /// Stable node-local property key. + /// + /// + /// Default used only when the property is absent. + /// + /// + /// The detached value. Malformed stored data is not silently replaced. + /// + public T Read( + string key, + T defaultValue + ) => ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); + + /// + /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. + /// + /// + /// Native serializable property type. + /// + /// + /// Stable node-local property key. + /// + /// + /// New detached value. + /// + /// + /// The current shared gesture key, or null for an independent edit. + /// + public void Write( + string key, + T value, + string? mergeKey = null + ) { + if (m_readOnly) + { + throw new InvalidOperationException("Copy this installed Shader into the project before editing."); + } + m_write(key, ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); + } + + /// + /// Draws a node property through the existing Inspector controls, including precise numbers and asset picking. + /// + /// + /// Supported native property type. + /// + /// + /// Stable node property identity. + /// + /// + /// Artist-facing property label. + /// + /// + /// Value used only when no property is stored. + /// + public void DrawProperty( + string key, + string label, + T defaultValue + ) { + T value = Read(key, defaultValue); + m_inspection.properties.DrawValue( + m_inspection.editorContext, + m_node, + "shader.node." + key, + label, + typeof(T), + () => value, + edited => value = (T)edited!, + new Edits(( + mutation, + mergeKey + ) => + { + mutation(); + Write(key, value, mergeKey); + }), + m_readOnly + ); + } + + private sealed class Edits(Action apply) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + apply(mutation, mergeKey); + return true; + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs index ac92c4ee0..8e1b2a7aa 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs @@ -1,121 +1,4 @@ -using Inno.Editor.Shaders; -using System; -using Inno.Core.Graphs; -using Inno.Core.Serialization; -using Inno.Editor.Rendering; -using Inno.Editor.Inspection; - namespace Inno.Editor.Shaders.ImGui; -/// -/// Registers Editor-only node controls independently from a node's shader compiler. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderNodeDrawerAttribute : Attribute -{ - /// - /// Associates the drawer with one stable node definition. - /// - /// - /// The compiler-independent graph node identity. - /// - /// - /// Optional artist-facing name used in node headers and creation menus. - /// - /// - /// Optional slash-delimited path below Create. Empty uses the host's built-in classification. - /// - /// - /// Stable ordering value among sibling creation groups and nodes. - /// - /// - /// Whether the contributed creation group is preceded by a separator at its own level. - /// - public ShaderNodeDrawerAttribute( - string definitionId, - string displayName = "", - string createPath = "", - int createOrder = 0, - bool separatorBefore = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(definitionId); - this.definitionId = definitionId; - this.displayName = displayName ?? throw new ArgumentNullException(nameof(displayName)); - this.createPath = createPath ?? throw new ArgumentNullException(nameof(createPath)); - this.createOrder = createOrder; - this.separatorBefore = separatorBefore; - } - - /// - /// Gets the stable node identity handled by this drawer. - /// - public string definitionId { get; } - /// - /// Gets the optional presentation-only name; it does not participate in Shader compilation or identity. - /// - public string displayName { get; } - /// - /// Gets the optional creation-menu path below Create. - /// - public string createPath { get; } - /// - /// Gets the creation-menu order. - /// - public int createOrder { get; } - /// - /// Gets whether the contributed creation group starts a new visual section. - /// - public bool separatorBefore { get; } -} - -/// -/// Immutable authoring presentation contributed for one Shader node definition. -/// -public readonly record struct ShaderNodePresentation -{ - /// - /// Creates presentation metadata for one Shader node definition. - /// - /// - /// Optional artist-facing node name. - /// - /// - /// Optional slash-delimited creation-menu path. - /// - /// - /// Stable ordering value within the creation menu. - /// - /// - /// Whether the contributed group starts a visual section. - /// - public ShaderNodePresentation( - string displayName, - string createPath, - int createOrder, - bool separatorBefore - ) { - this.displayName = displayName; - this.createPath = createPath; - this.createOrder = createOrder; - this.separatorBefore = separatorBefore; - } - - /// - /// Gets the optional artist-facing node name. - /// - public string displayName { get; } - /// - /// Gets the optional slash-delimited creation-menu path. - /// - public string createPath { get; } - /// - /// Gets the stable ordering value within the creation menu. - /// - public int createOrder { get; } - /// - /// Gets whether the contributed group starts a visual section. - /// - public bool separatorBefore { get; } -} /// /// Provides reloadable Inspector controls; instances must not retain frame contexts or asset objects. @@ -130,157 +13,3 @@ public abstract class ShaderNodeDrawer /// public abstract void Draw(ShaderNodeDrawContext context); } - -/// -/// Exposes detached node values and one-gesture writes without exposing the live graph document. -/// -public sealed class ShaderNodeDrawContext -{ - private readonly GraphNodeRecord m_node; - private readonly SerializationRegistry m_serialization; - private readonly SerializationContext m_context; - private readonly Action m_write; - private readonly InspectionDrawContext m_inspection; - private readonly bool m_readOnly; - /// - /// Creates invocation-scoped access for a graph or Inspector host. - /// - /// - /// Detached node values for this invocation. - /// - /// - /// Current owner converter registry. - /// - /// - /// Complete owner reference context. - /// - /// - /// Host callback recording changes in the shared draft history. - /// - /// - /// Current generation preview service. - /// - /// - /// Shared Inspector context, including native property controls and drag/drop. - /// - /// - /// Whether the source belongs to an immutable installation. - /// - public ShaderNodeDrawContext( - GraphNodeRecord node, - SerializationRegistry serialization, - SerializationContext context, - Action write, - IEditorPreviewService previews, - InspectionDrawContext inspection, - bool readOnly - ) { - m_node = node; - m_serialization = serialization; - m_context = context; - m_write = write; - this.previews = previews; - m_inspection = inspection; - m_readOnly = readOnly; - } - - /// - /// Gets the shared generation-scoped preview service for optional inline texture previews; valid only during this draw. - /// - public IEditorPreviewService previews { get; } - /// - /// Gets the stable node identity for Editor widget IDs. - /// - public GraphNodeId nodeId => m_node.id; - - /// - /// Reads a detached property value; missing values use the node's declared default. - /// - /// - /// Native serializable property type. - /// - /// - /// Stable node-local property key. - /// - /// - /// Default used only when the property is absent. - /// - /// - /// The detached value. Malformed stored data is not silently replaced. - /// - public T Read( - string key, - T defaultValue - ) => Inno.Rendering.Shaders.ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); - /// - /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. - /// - /// - /// Native serializable property type. - /// - /// - /// Stable node-local property key. - /// - /// - /// New detached value. - /// - /// - /// The current shared gesture key, or null for an independent edit. - /// - public void Write( - string key, - T value, - string? mergeKey = null - ) { - if (m_readOnly) - throw new InvalidOperationException("Copy this installed Shader into the project before editing."); - m_write(key, Inno.Rendering.Shaders.ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); - } - - /// - /// Draws a node property through the existing Inspector controls, including precise numbers and asset picking. - /// - /// - /// Supported native property type. - /// - /// - /// Stable node property identity. - /// - /// - /// Artist-facing property label. - /// - /// - /// Value used only when no property is stored. - /// - public void DrawProperty( - string key, - string label, - T defaultValue - ) { - T value = Read(key, defaultValue); - m_inspection.properties.DrawValue(m_inspection.editorContext, m_node, "shader.node." + key, label, typeof(T), () => value, edited => value = (T)edited!, new Edits(( - mutation, - mergeKey - ) => - { - mutation(); - Write(key, value, mergeKey); - }), m_readOnly); - } - - private sealed class Edits(Action apply) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - apply(mutation, mergeKey); - return true; - } - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs new file mode 100644 index 000000000..071cdf4ea --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs @@ -0,0 +1,70 @@ +using System; + +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Registers Editor-only node controls independently from a node's shader compiler. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderNodeDrawerAttribute : Attribute +{ + /// + /// Associates the drawer with one stable node definition. + /// + /// + /// The compiler-independent graph node identity. + /// + /// + /// Optional artist-facing name used in node headers and creation menus. + /// + /// + /// Optional slash-delimited path below Create. Empty uses the host's built-in classification. + /// + /// + /// Stable ordering value among sibling creation groups and nodes. + /// + /// + /// Whether the contributed creation group is preceded by a separator at its own level. + /// + public ShaderNodeDrawerAttribute( + string definitionID, + string displayName = "", + string createPath = "", + int createOrder = 0, + bool separatorBefore = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); + ArgumentNullException.ThrowIfNull(displayName); + ArgumentNullException.ThrowIfNull(createPath); + this.definitionID = definitionID; + this.displayName = displayName; + this.createPath = createPath; + this.createOrder = createOrder; + this.separatorBefore = separatorBefore; + } + + /// + /// Gets the stable node identity handled by this drawer. + /// + public string definitionID { get; } + + /// + /// Gets the optional presentation-only name; it does not participate in Shader compilation or identity. + /// + public string displayName { get; } + + /// + /// Gets the optional creation-menu path below Create. + /// + public string createPath { get; } + + /// + /// Gets the creation-menu order. + /// + public int createOrder { get; } + + /// + /// Gets whether the contributed creation group starts a new visual section. + /// + public bool separatorBefore { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs index 6ffb0b791..d2858f4f6 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs @@ -1,11 +1,12 @@ -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using Inno.Editor.Shaders; using Inno.Extensibility.Types; namespace Inno.Editor.Shaders.ImGui; + /// /// Shares generation-scoped node presentation between graph and Inspector hosts. /// @@ -13,6 +14,7 @@ public sealed class ShaderNodeDrawerRegistry : IDisposable { private readonly TypeCatalog m_types; private readonly Registry m_registry; + /// /// Creates a presentation registry owned by the current editor feature lifetime. /// @@ -21,14 +23,15 @@ public sealed class ShaderNodeDrawerRegistry : IDisposable /// public ShaderNodeDrawerRegistry(TypeCatalog types) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types); + m_types = types; m_registry = new(types); } /// /// Invokes optional node controls within one generation lease. /// - /// + /// /// Stable node definition identity. /// /// @@ -38,12 +41,14 @@ public ShaderNodeDrawerRegistry(TypeCatalog types) /// True when a registered drawer rendered the controls; false leaves presentation to the host. /// public bool TryDraw( - string definitionId, + string definitionID, ShaderNodeDrawContext context ) { using IDisposable operation = m_types.AcquireOperation("Draw shader node controls"); - if (!m_registry.snapshot.drawers.TryGetValue(definitionId, out ShaderNodeDrawer? drawer)) + if (!m_registry.snapshot.drawers.TryGetValue(definitionID, out ShaderNodeDrawer? drawer)) + { return false; + } drawer.Draw(context); return true; } @@ -51,22 +56,22 @@ ShaderNodeDrawContext context /// /// Resolves an optional artist-facing name without executing a drawer or retaining its generation. /// - /// + /// /// Stable compiler-independent node identity. /// /// /// The contributed name, or null when the host should use its generic presentation. /// - public string? GetDisplayName(string definitionId) + public string? GetDisplayName(string definitionID) { using IDisposable operation = m_types.AcquireOperation("Resolve shader node presentation"); - return m_registry.snapshot.names.TryGetValue(definitionId, out string? name) && name.Length != 0 ? name : null; + return m_registry.snapshot.names.TryGetValue(definitionID, out string? name) && name.Length != 0 ? name : null; } /// /// Gets optional creation-menu presentation without executing the drawer. /// - /// + /// /// Stable compiler-independent node identity. /// /// @@ -76,17 +81,21 @@ ShaderNodeDrawContext context /// True when the current generation contributes presentation for the node; otherwise false. /// public bool TryGetPresentation( - string definitionId, + string definitionID, out ShaderNodePresentation presentation ) { using IDisposable operation = m_types.AcquireOperation("Resolve shader node authoring presentation"); - return m_registry.snapshot.presentations.TryGetValue(definitionId, out presentation); + return m_registry.snapshot.presentations.TryGetValue(definitionID, out presentation); } /// /// Retires the current presentation providers through the shared lifecycle. /// public void Dispose() => m_registry.Dispose(); + + private static string Normalize(string value) + => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + private sealed class Registry(TypeCatalog types) : TypeRegistry(types) { internal Snapshot snapshot => current; @@ -107,15 +116,27 @@ protected override Snapshot Build(TypeCacheSnapshot snapshot) var presentations = new Dictionary(StringComparer.Ordinal); try { - foreach (Type type in snapshot.GetTypesWithAttribute().Select(reference => reference.Resolve(snapshot))) - { + foreach (Type type in snapshot + .GetTypesWithAttribute() + .Select(reference => reference.Resolve(snapshot)) + ) { ShaderNodeDrawerAttribute attribute = type.GetCustomAttribute()!; - string id = attribute.definitionId; + string id = attribute.definitionID; if (result.ContainsKey(id)) + { throw new InvalidOperationException($"Shader node drawer '{id}' is registered twice."); + } result.Add(id, CreateExtension(type)); names.Add(id, attribute.displayName); - presentations.Add(id, new(attribute.displayName, Normalize(attribute.createPath), attribute.createOrder, attribute.separatorBefore)); + presentations.Add( + id, + new ShaderNodePresentation( + attribute.displayName, + Normalize(attribute.createPath), + attribute.createOrder, + attribute.separatorBefore + ) + ); } return new(result, names, presentations); @@ -144,7 +165,6 @@ protected override Snapshot Build(TypeCacheSnapshot snapshot) protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.drawers.Values); } - private static string Normalize(string value) => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); private sealed record Snapshot( IReadOnlyDictionary drawers, IReadOnlyDictionary names, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs new file mode 100644 index 000000000..a42b3cf36 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs @@ -0,0 +1,54 @@ +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Immutable authoring presentation contributed for one Shader node definition. +/// +public readonly record struct ShaderNodePresentation +{ + /// + /// Creates presentation metadata for one Shader node definition. + /// + /// + /// Optional artist-facing node name. + /// + /// + /// Optional slash-delimited creation-menu path. + /// + /// + /// Stable ordering value within the creation menu. + /// + /// + /// Whether the contributed group starts a visual section. + /// + public ShaderNodePresentation( + string displayName, + string createPath, + int createOrder, + bool separatorBefore + ) { + this.displayName = displayName; + this.createPath = createPath; + this.createOrder = createOrder; + this.separatorBefore = separatorBefore; + } + + /// + /// Gets the optional artist-facing node name. + /// + public string displayName { get; } + + /// + /// Gets the optional slash-delimited creation-menu path. + /// + public string createPath { get; } + + /// + /// Gets the stable ordering value within the creation menu. + /// + public int createOrder { get; } + + /// + /// Gets whether the contributed group starts a visual section. + /// + public bool separatorBefore { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs index 286b829e2..f1e12dc69 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs @@ -1,19 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using System.Reflection; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Editor.Core; using Inno.Editor.Rendering; +using Inno.Editor.Shaders; using Inno.Extensibility.Types; using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Shaders.ImGui; + /// /// Hosts isolated Shader and Material images using domain-contributed preview pipelines. /// @@ -26,6 +30,7 @@ public sealed class ShaderPreviews : EditorModule private readonly EditorShaderCompilation m_compilation; private readonly Dictionary m_states = []; private ulong m_frame; + internal ShaderPreviews( TypeCatalog types, IEditorPreviewService previews, @@ -40,7 +45,7 @@ EditorShaderCompilation compilation /// /// Draws detached Material overrides using its Shader's compiled contract. /// - /// + /// /// Persistent document identity; no Material is retained under this identity. /// /// @@ -50,7 +55,7 @@ EditorShaderCompilation compilation /// Positive square image size in logical pixels. /// public void DrawMaterial( - Guid ownerId, + Guid ownerID, MaterialAsset material, float logicalSize ) { @@ -62,7 +67,12 @@ float logicalSize try { - Draw(ownerId, material, m_compilation.RequestArtifact(material.shader, RenderShaderVariant.FromMaterial(material)), logicalSize); + Draw( + ownerID, + material, + m_compilation.RequestArtifact(material.shader, RenderShaderVariant.FromMaterial(material)), + logicalSize + ); } catch (Exception error) when (Recoverable(error)) { @@ -73,7 +83,7 @@ float logicalSize /// /// Draws a compiled draft without modifying the source Shader or its canonical runtime publication. /// - /// + /// /// Persistent document identity, independent of the canonical Shader publication. /// /// @@ -86,31 +96,42 @@ float logicalSize /// Positive square image size in logical pixels. /// public void Draw( - Guid ownerId, + Guid ownerID, MaterialAsset material, EditorShaderDraftCompilationSnapshot compilation, float logicalSize ) { - if (ownerId == Guid.Empty) - throw new ArgumentException("A preview owner identity is required.", nameof(ownerId)); + if (ownerID == Guid.Empty) + { + throw new ArgumentException("A preview owner identity is required.", nameof(ownerID)); + } ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(compilation); if (!(logicalSize > 0f) || !float.IsFinite(logicalSize)) + { throw new ArgumentOutOfRangeException(nameof(logicalSize)); + } if (compilation.artifact is not { } artifact) { EditorUI.current.widgets.Hint("Preview: " + compilation.state); return; } - if (!m_states.TryGetValue(ownerId, out State? state)) - m_states.Add(ownerId, state = new("shader-preview/" + ownerId.ToString("N"))); + if (!m_states.TryGetValue(ownerID, out State? state)) + { + m_states.Add(ownerID, state = new("shader-preview/" + ownerID.ToString("N"))); + } state.frame = m_frame; try { using IDisposable operation = m_types.AcquireOperation("Build isolated Shader preview"); ShaderDefinition definition = m_compilation.ReadDefinition(artifact); - string[] contracts = definition.techniques.Where(value => !material.techniqueId.isValid || value.id == material.techniqueId).Select(value => value.contract.value).Distinct(StringComparer.Ordinal).Where(m_registry.providers.ContainsKey).ToArray(); + string[] contracts = definition.techniques + .Where(value => !material.techniqueId.isValid || value.id == material.techniqueId) + .Select(value => value.contract.value) + .Distinct(StringComparer.Ordinal) + .Where(m_registry.providers.ContainsKey) + .ToArray(); if (contracts.Length == 0) { EditorUI.current.widgets.Hint("No preview provider for this Shader contract."); @@ -124,15 +145,33 @@ float logicalSize } int pixels = Math.Clamp((int)MathF.Ceiling(logicalSize * ImGuiApi.GetWindowDpiScale()), 1, 2048); - var context = new ShaderPreviewContext(new(state.viewportId), material, artifact, definition, state, pixels, pixels); + var context = new ShaderPreviewContext( + new RenderPersistentResourceID(state.viewportID), + material, + artifact, + definition, + state, + pixels, + pixels + ); EditorViewportLayer layer = m_registry.providers[contracts[0]].CreateLayer(context); - if (m_previews.TryRender(new(state.viewportId, pixels, pixels, RenderTextureFormat.RGBA8, [layer]), out var handle)) - m_previews.Draw(handle, new(logicalSize, logicalSize)); + if (m_previews.TryRender( + new EditorViewportComposition(state.viewportID, pixels, pixels, RenderTextureFormat.RGBA8, [layer]), + out EditorPreviewHandle handle + )) { + m_previews.Draw(handle, new Vector2(logicalSize, logicalSize)); + } else - ImGuiApi.Dummy(new(logicalSize, logicalSize)); - EditorUI.current.widgets.Hint(compilation.usingLastGood ? "Draft preview · last-good candidate · Scene/Game unchanged" : "Isolated preview · Scene/Game unchanged"); + { + ImGuiApi.Dummy(new Vector2(logicalSize, logicalSize)); + } + EditorUI.current.widgets.Hint( + compilation.usingLastGood ? "Draft preview · last-good candidate · Scene/Game unchanged" : "Isolated preview · Scene/Game unchanged" + ); foreach (Diagnostic error in state.errors.Values) + { EditorUI.current.widgets.WrappedText(error.message); + } } catch (Exception error) when (Recoverable(error)) { @@ -143,13 +182,15 @@ float logicalSize /// /// Releases this document's viewport and scoped GPU publication without touching other consumers. /// - /// + /// /// Closing or disabled preview owner. /// - public void Release(Guid ownerId) + public void Release(Guid ownerID) { - if (m_states.Remove(ownerId, out State? state)) - m_previews.ReleaseRendered(state.viewportId); + if (m_states.Remove(ownerID, out State? state)) + { + m_previews.ReleaseRendered(state.viewportID); + } } /// @@ -162,7 +203,9 @@ protected override void OnUpdate(EditorContext context) { m_frame++; foreach (Guid id in m_states.Where(pair => m_frame - pair.Value.frame > 2).Select(pair => pair.Key).ToArray()) + { Release(id); + } } /// @@ -174,41 +217,48 @@ protected override void OnUpdate(EditorContext context) protected override void OnStop(EditorContext context) { foreach (Guid id in m_states.Keys.ToArray()) + { Release(id); + } m_registry.Dispose(); } - private static bool Recoverable(Exception error) => RetirementPendingException.Find(error) is null - && error is InvalidOperationException or ArgumentException or FormatException; - private sealed class State(string viewportId) : IDiagnosticReporter + private static bool Recoverable(Exception error) + => RetirementPendingException.Find(error) is null + && error is InvalidOperationException or ArgumentException or FormatException; + + private sealed class State(string viewportID) : IDiagnosticReporter { - internal readonly string viewportId = viewportId; - internal readonly Dictionary<(string code, string? semanticId, Guid? objectId), Diagnostic> errors = []; + internal readonly string viewportID = viewportID; + internal readonly Dictionary<(string code, string? semanticID, Guid? objectID), Diagnostic> errors = []; internal ulong frame; + /// /// Publishes the supplied diagnostic to the configured observers. /// /// /// The diagnostic consumed by publish; ownership remains with the caller unless explicitly stated otherwise. /// - public void Publish(Diagnostic diagnostic) => errors[(diagnostic.code, diagnostic.semanticId, diagnostic.objectId)] = diagnostic; + public void Publish(Diagnostic diagnostic) => errors[(diagnostic.code, diagnostic.semanticID, diagnostic.objectID)] = diagnostic; + /// /// Resolves the requested stable identity to its current-generation value. /// /// /// The code text validated by the resolve operation. /// - /// + /// /// The semantic id text validated by the resolve operation. /// - /// + /// /// The object id consumed by resolve; ownership remains with the caller unless explicitly stated otherwise. /// public void Resolve( string code, - string? semanticId = null, - Guid? objectId = null - ) => errors.Remove((code, semanticId, objectId)); + string? semanticID = null, + Guid? objectID = null + ) => errors.Remove((code, semanticID, objectID)); + /// /// Records errors from the current diagnostic report. /// @@ -219,7 +269,9 @@ public void Replace(IEnumerable diagnostics) { errors.Clear(); foreach (Diagnostic value in diagnostics) + { Publish(value); + } } } @@ -241,11 +293,15 @@ protected override IReadOnlyDictionary Build(Type var result = new Dictionary(StringComparer.Ordinal); try { - foreach (Type type in snapshot.GetTypesWithAttribute().Select(value => value.Resolve(snapshot))) - { - string id = type.GetCustomAttribute()!.contractId; + foreach (Type type in snapshot + .GetTypesWithAttribute() + .Select(value => value.Resolve(snapshot)) + ) { + string id = type.GetCustomAttribute()!.contractID; if (result.ContainsKey(id)) + { throw new InvalidOperationException("Duplicate Shader preview contract: " + id); + } result.Add(id, CreateExtension(type)); } @@ -272,6 +328,7 @@ protected override IReadOnlyDictionary Build(Type /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) => DisposeExtensions(snapshot.Values); + protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) + => DisposeExtensions(snapshot.Values); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs new file mode 100644 index 000000000..5fd47220b --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_CLEAR_SELECTION)] +internal sealed class ClearEditorSelectionAction : EditorAction +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(null); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs deleted file mode 100644 index 5202c7bc9..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Inno.Core.Input; -using Inno.Editor.Interactions; - -namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIds.C_UNDO, priority: 1000)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "Edit/Undo", order: 100)] -[EditorShortcut(KeyCode.Z, primary: true)] -internal sealed class UndoEditorAction : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => new( - isVisible: true, - isEnabled: context.history.canUndo, - displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", - unavailableReason: context.history.undoUnavailableReason - ); - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => _ = context.history.Undo(); -} - -[EditorAction(GlobalInteractionIds.C_REDO, priority: 1000)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "Edit/Redo", order: 110)] -[EditorShortcut(KeyCode.Z, KeyModifier.Shift, primary: true)] -[EditorShortcut(KeyCode.Y, primary: true)] -internal sealed class RedoEditorAction : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => new( - isVisible: true, - isEnabled: context.history.canRedo, - displayName: context.history.redoName is { } name ? $"Redo {name}" : "Redo", - unavailableReason: context.history.redoUnavailableReason - ); - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => _ = context.history.Redo(); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs new file mode 100644 index 000000000..2e9c27937 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_REDO, priority: 1000)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Edit/Redo", order: 110)] +[EditorShortcut(KeyCode.Z, KeyModifier.Shift, primary: true)] +[EditorShortcut(KeyCode.Y, primary: true)] +internal sealed class RedoEditorAction : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => new( + isVisible: true, + isEnabled: context.history.canRedo, + displayName: context.history.redoName is { } name ? $"Redo {name}" : "Redo", + unavailableReason: context.history.redoUnavailableReason + ); + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => _ = context.history.Redo(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs new file mode 100644 index 000000000..3535d3b61 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_SELECT)] +internal sealed class SelectEditorTargetAction : EditorAction +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(context.target); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs deleted file mode 100644 index e5a24c756..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Inno.Editor.Interactions; - -namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIds.C_CLEAR_SELECTION)] -internal sealed class ClearEditorSelectionAction : EditorAction -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(null); -} - -[EditorAction(GlobalInteractionIds.C_SELECT)] -internal sealed class SelectEditorTargetAction : EditorAction -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(context.target); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs index 14ab346e4..6d0720083 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs @@ -1,18 +1,17 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIds.C_TOGGLE_PANEL, GlobalInteractionIds.C_MAIN_MENU_AREA)] + +[EditorAction(GlobalInteractionIDs.C_TOGGLE_PANEL, GlobalInteractionIDs.C_MAIN_MENU_AREA)] internal sealed class TogglePanelAction : EditorArgumentAction { /// - protected override EditorActionState Query(EditorActionArgumentContext context) => context.interactions.TryGetPanelState( - context.argument, - out bool isOpen - ) ? new EditorActionState( - true, - true, - isChecked: isOpen - ) : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionArgumentContext context) + => context.interactions.TryGetPanelState( + context.argument, + out bool isOpen + ) ? new EditorActionState(true, true, isChecked: isOpen) : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs new file mode 100644 index 000000000..30aa47bfe --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs @@ -0,0 +1,35 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_UNDO, priority: 1000)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Edit/Undo", order: 100)] +[EditorShortcut(KeyCode.Z, primary: true)] +internal sealed class UndoEditorAction : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => new( + isVisible: true, + isEnabled: context.history.canUndo, + displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", + unavailableReason: context.history.undoUnavailableReason + ); + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => _ = context.history.Undo(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs index c38394789..603255c9f 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs @@ -2,13 +2,16 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIds.C_FIND_COMMAND)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "Tools/Find Command...", order: 0)] + +[EditorAction(GlobalInteractionIDs.C_FIND_COMMAND)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Tools/Find Command...", order: 0)] [EditorShortcut(KeyCode.P, KeyModifier.Shift, primary: true)] internal sealed class CommandSearchAction(CommandSearchModule commands) : EditorAction { /// - protected override EditorActionState Query(EditorActionContext context) => commands.isOpen ? EditorActionState.disabled : EditorActionState.enabled; + protected override EditorActionState Query(EditorActionContext context) + => commands.isOpen ? EditorActionState.disabled : EditorActionState.enabled; + /// protected override void Execute(EditorActionContext context) => commands.Open(); } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs index 7bb0bc72d..7d31fc65e 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs @@ -1,19 +1,23 @@ using System.Numerics; using Inno.Editor.Core; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; -[EditorModal(GlobalInteractionIds.C_COMMAND_SEARCH_MODAL, "Find Command", order: 50)] + +[EditorModal(GlobalInteractionIDs.C_COMMAND_SEARCH_MODAL, "Find Command", order: 50)] internal sealed class CommandSearchModal( CommandSearchModule commands, - EditorUiSession ui + EditorUISession ui ) : EditorModal { /// public override bool isVisible => commands.isOpen; + /// public override bool allowScrolling => false; + /// public override Vector2 initialSize => new(620f, 440f); @@ -22,26 +26,35 @@ protected override void OnDraw(EditorContext context) { if (commands.requestsFocus) { - Ui.SetKeyboardFocusHere(); + Gui.SetKeyboardFocusHere(); commands.requestsFocus = false; } string search = commands.search; _ = ui.widgets.SearchInput("commands", "Search commands...", ref search); commands.search = search; - bool opened = Ui.BeginChild("##command-results", new Vector2(0f, -Ui.GetFrameHeightWithSpacing()), 0, ImGuiWindowFlags.NoSavedSettings); + bool opened = Gui.BeginChild( + "##command-results", + new Vector2(0f, -Gui.GetFrameHeightWithSpacing()), + 0, + ImGuiWindowFlags.NoSavedSettings + ); bool chosen = false; try { if (opened) + { chosen = commands.Draw(ui); + } } finally { - Ui.EndChild(); + Gui.EndChild(); } - if (chosen || ui.widgets.CenteredButton("Close") || Ui.IsKeyPressed(ImGuiKey.Escape, false)) + if (chosen || ui.widgets.CenteredButton("Close") || Gui.IsKeyPressed(ImGuiKey.Escape, false)) + { commands.Close(); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs index 3f093368c..cbc5cd150 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs @@ -7,7 +7,8 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; -[EditorModule(GlobalInteractionIds.C_COMMAND_SEARCH_MODULE, order: 20)] + +[EditorModule(GlobalInteractionIDs.C_COMMAND_SEARCH_MODULE, order: 20)] internal sealed class CommandSearchModule(EditorInteractions interactions) : EditorModule { private string m_area = "editor/global"; @@ -16,6 +17,9 @@ internal sealed class CommandSearchModule(EditorInteractions interactions) : Edi internal string search { get; set; } = string.Empty; internal bool requestsFocus { get; set; } + /// + protected override void OnStop(EditorContext context) => Close(); + internal void Open() { m_area = interactions.focusedArea; @@ -32,42 +36,48 @@ internal void Close() search = string.Empty; } - internal bool Draw(EditorUiSession ui) + internal bool Draw(EditorUISession ui) { - EditorInteraction global = interactions.For(GlobalInteractionIds.C_MAIN_MENU_AREA); + EditorInteraction global = interactions.For(GlobalInteractionIDs.C_MAIN_MENU_AREA); EditorMenuModel globalMenu = global.BuildMenu(); - var globalIds = new HashSet(StringComparer.Ordinal); + var globalIDs = new HashSet(StringComparer.Ordinal); Collect(globalMenu.items); if (ui.menus.DrawSearchItems(global, globalMenu.items, search)) + { return true; + } object? target = m_target is RuntimeIdentity id && interactions.TryResolveIdentity(id, out IdentityObject? live) ? live : null; EditorInteraction local = interactions.For(m_area, target); EditorMenuModel commands = local.BuildCommands(); - var localItems = Leaves(commands.items).Where(item => !globalIds.Contains(item.actionId)).ToArray(); + EditorMenuItem[] localItems = Leaves(commands.items).Where(item => !globalIDs.Contains(item.actionID)).ToArray(); return ui.menus.DrawSearchItems(local, localItems, search); void Collect(IReadOnlyList items) { foreach (EditorMenuItem item in items) { - if (item.actionId.Length != 0) - _ = globalIds.Add(item.actionId); + if (item.actionID.Length != 0) + { + _ = globalIDs.Add(item.actionID); + } Collect(item.children); } } } - /// - protected override void OnStop(EditorContext context) => Close(); private static IEnumerable Leaves(IReadOnlyList items) { foreach (EditorMenuItem item in items) { if (item.children.Count == 0) + { yield return item; + } else { foreach (EditorMenuItem child in Leaves(item.children)) + { yield return child; + } } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs deleted file mode 100644 index 75dcf1557..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Inno.Editor.Interactions; - -namespace Inno.Editor.Workbench; -[EditorAction(ExportInteractionIds.C_EXPORT_PLUGIN)] -[EditorMenu(ExportInteractionIds.C_MAIN_MENU_AREA, "File/Export as Plugin...", order: 800, separatorBefore: true)] -internal sealed class ExportPluginAction(ExportWindowModule window) : EditorAction -{ - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => window.OpenPlugin(); -} - -[EditorAction(ExportInteractionIds.C_EXPORT_GAME)] -[EditorMenu(ExportInteractionIds.C_MAIN_MENU_AREA, "File/Export as Game...", order: 810)] -internal sealed class ExportGameAction(ExportWindowModule window) : EditorAction -{ - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => window.OpenGame(); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs new file mode 100644 index 000000000..8a4c7cbe7 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(ExportInteractionIDs.C_EXPORT_GAME)] +[EditorMenu(ExportInteractionIDs.C_MAIN_MENU_AREA, "File/Export as Game...", order: 810)] +internal sealed class ExportGameAction(ExportWindowModule window) : EditorAction +{ + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => window.OpenGame(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIDs.cs similarity index 83% rename from src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIDs.cs index e27e00e2b..e920289ad 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIDs.cs @@ -1,5 +1,6 @@ namespace Inno.Editor.Workbench; -internal static class ExportInteractionIds + +internal static class ExportInteractionIDs { internal const string C_EXPORT_GAME = "export/game"; internal const string C_EXPORT_PLUGIN = "export/plugin"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs new file mode 100644 index 000000000..73f6f937a --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(ExportInteractionIDs.C_EXPORT_PLUGIN)] +[EditorMenu(ExportInteractionIDs.C_MAIN_MENU_AREA, "File/Export as Plugin...", order: 800, separatorBefore: true)] +internal sealed class ExportPluginAction(ExportWindowModule window) : EditorAction +{ + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => window.OpenPlugin(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs index 945dd8a6b..71f9efeae 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs @@ -8,45 +8,49 @@ using Inno.Editor.Exporting; namespace Inno.Editor.Workbench; + [EditorModule("export.windows", order: 310)] internal sealed class ExportWindowModule( - EditorContext m_editor, - EditorExportService m_exports, - BuildSettingsStore m_buildSettings, - ProjectSettingsStore m_projectSettings + EditorContext editor, + EditorExportService exports, + BuildSettingsStore buildSettings, + ProjectSettingsStore projectSettings ) : EditorModule { private bool m_gameProgressVisible; private string m_formError = string.Empty; internal bool isPluginVisible { get; private set; } internal bool isGameVisible { get; private set; } - internal bool isGameProgressVisible => m_gameProgressVisible && m_exports.isGameBusy; - internal bool isPluginBusy => m_exports.isPluginBusy; - internal bool isGameBusy => m_exports.isGameBusy; - internal string pluginId => m_projectSettings.projectId.value; + internal bool isGameProgressVisible => m_gameProgressVisible && exports.isGameBusy; + internal bool isPluginBusy => exports.isPluginBusy; + internal bool isGameBusy => exports.isGameBusy; + internal string pluginID => projectSettings.projectID.value; internal string pluginDisplayName { get; set; } = string.Empty; internal string pluginOutputPath { get; set; } = string.Empty; - internal string gameApplicationId => m_projectSettings.projectId.value; + internal string gameApplicationID => projectSettings.projectID.value; internal string gameProductName { get; set; } = string.Empty; internal string gamePersistentDataPath { get; set; } = string.Empty; internal string gameStartupScene { get; set; } = string.Empty; internal string gameOutputDirectory { get; set; } = string.Empty; internal int gameWindowWidth { get; set; } = 1280; internal int gameWindowHeight { get; set; } = 720; - internal BuildTargetId gameTarget { get; set; } - internal ManagedDeploymentId? gameManagedDeployment { get; set; } - internal IReadOnlyList availableManagedDeployments => m_exports.GetManagedDeployments(gameTarget); - internal IReadOnlyList availableGameTargets => m_exports.availableGameTargets; - internal EditorExportProgress progress => m_exports.progress; + internal BuildTargetID gameTarget { get; set; } + internal ManagedDeploymentID? gameManagedDeployment { get; set; } + internal IReadOnlyList availableManagedDeployments => exports.GetManagedDeployments(gameTarget); + internal IReadOnlyList availableGameTargets => exports.availableGameTargets; + internal EditorExportProgress progress => exports.progress; internal string status => progress.status; - internal string error => m_formError.Length == 0 ? m_exports.progress.error : m_formError; + internal string error => m_formError.Length == 0 ? exports.progress.error : m_formError; internal bool includePluginDependencies { get; set; } - internal string GetGameTargetDisplayName(BuildTargetId target) => m_exports.GetGameTargetDisplayName(target); + internal string GetGameTargetDisplayName(BuildTargetID target) => exports.GetGameTargetDisplayName(target); + internal void OpenPlugin() { if (isPluginBusy || isGameBusy) + { return; + } CloseGame(); BuildSettings defaults = LoadBuildSettings(); pluginDisplayName = defaults.pluginDisplayName; @@ -58,7 +62,9 @@ internal void OpenPlugin() internal void OpenGame() { if (isPluginBusy || isGameBusy) + { return; + } ClosePlugin(); m_gameProgressVisible = false; BuildSettings defaults = LoadBuildSettings(); @@ -76,30 +82,60 @@ internal void OpenGame() internal void BeginPluginExport() { m_formError = string.Empty; - m_exports.StartPlugin(new PluginBuildRequest { pluginId = pluginId, displayName = pluginDisplayName, outputPath = ResolveOutputPath(pluginOutputPath), includeDependencies = includePluginDependencies }); + exports.StartPlugin( + new PluginBuildRequest + { + pluginID = pluginID, + displayName = pluginDisplayName, + outputPath = ResolveOutputPath(pluginOutputPath), + includeDependencies = includePluginDependencies + } + ); } internal void BeginGameExport() { m_formError = string.Empty; - m_exports.StartGame(new GameBuildRequest { profile = new BuildProfile { applicationId = gameApplicationId, productName = gameProductName, persistentDataPath = gamePersistentDataPath, startupScene = gameStartupScene, target = gameTarget, managedDeployment = gameManagedDeployment, windowWidth = gameWindowWidth, windowHeight = gameWindowHeight }, outputDirectory = ResolveOutputPath(gameOutputDirectory) }); + exports.StartGame( + new GameBuildRequest + { + profile = new BuildProfile + { + applicationId = gameApplicationID, + productName = gameProductName, + persistentDataPath = gamePersistentDataPath, + startupScene = gameStartupScene, + target = gameTarget, + managedDeployment = gameManagedDeployment, + windowWidth = gameWindowWidth, + windowHeight = gameWindowHeight + }, + outputDirectory = ResolveOutputPath(gameOutputDirectory) + } + ); isGameVisible = false; m_gameProgressVisible = true; } - internal void CancelPluginExport(long operationId) => m_exports.Cancel(operationId); - internal void CancelGameExport(long operationId) => m_exports.Cancel(operationId); + internal void CancelPluginExport(long operationID) => exports.Cancel(operationID); + + internal void CancelGameExport(long operationID) => exports.Cancel(operationID); + internal void ClosePlugin() { if (isPluginBusy) - m_exports.Cancel(m_exports.progress.operationId); + { + exports.Cancel(exports.progress.operationID); + } isPluginVisible = false; } internal void CloseGame() { if (isGameBusy) - m_exports.Cancel(m_exports.progress.operationId); + { + exports.Cancel(exports.progress.operationID); + } isGameVisible = false; } @@ -107,19 +143,24 @@ private BuildSettings LoadBuildSettings() { try { - return m_buildSettings.Load(); + return buildSettings.Load(); } - catch (Exception exception) when (exception is IOException or InvalidDataException or InvalidOperationException or UnauthorizedAccessException) + catch (Exception exception) when (exception is IOException + or InvalidDataException + or InvalidOperationException + or UnauthorizedAccessException) { m_formError = exception.Message; - return m_buildSettings.defaultSettings; + return buildSettings.defaultSettings; } } private string ResolveOutputPath(string path) { if (string.IsNullOrWhiteSpace(path)) + { return path; - return Path.IsPathFullyQualified(path) ? Path.GetFullPath(path) : Path.GetFullPath(path, m_editor.projectDirectory); + } + return Path.IsPathFullyQualified(path) ? Path.GetFullPath(path) : Path.GetFullPath(path, editor.projectDirectory); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs index 76940a130..04ff98d2d 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs @@ -1,33 +1,40 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Build; using Inno.Build.Managed; using Inno.Editor.Core; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorModal("export.game", "Export as Game", order: 310)] internal sealed class GameExportModal(ExportWindowModule window) : EditorModal { private const int C_TEXT_CAPACITY = 4096; + /// /// Gets whether this implementation is visible. /// public override bool isVisible => window.isGameVisible; + /// /// Gets whether this implementation can move. /// public override bool canMove => true; + /// /// Gets whether this implementation can resize. /// public override bool canResize => true; + /// /// Gets the preferred initial window size in logical editor units. /// public override Vector2 initialSize => new(760f, 540f); + /// /// Gets the smallest size that keeps the export form usable. /// @@ -41,25 +48,32 @@ internal sealed class GameExportModal(ExportWindowModule window) : EditorModal /// protected override void OnDraw(EditorContext context) { - EditorUI.current.widgets.WrappedText("Build a standalone Player from the current project. Only imported runtime content " + "is deployed; source files stay in the project."); - Ui.SeparatorText("Application"); + EditorUI.current.widgets.WrappedText( + "Build a standalone Player from the current project. Only imported runtime content " + "is deployed; source files stay in the project." + ); + Gui.SeparatorText("Application"); if (BeginFields("##application_fields")) { try { EditorUI.current.widgets.SetupPropertyColumns(); - DrawReadOnly("Application ID", window.gameApplicationId); + DrawReadOnly("Application ID", window.gameApplicationID); DrawText("Product Name", "game_name", window.gameProductName, value => window.gameProductName = value); - DrawText("Persistent Data Folder", "game_data", window.gamePersistentDataPath, value => window.gamePersistentDataPath = value); + DrawText( + "Persistent Data Folder", + "game_data", + window.gamePersistentDataPath, + value => window.gamePersistentDataPath = value + ); DrawText("Startup Scene", "game_scene", window.gameStartupScene, value => window.gameStartupScene = value); } finally { - Ui.EndTable(); + Gui.EndTable(); } } - Ui.SeparatorText("Window and Platform"); + Gui.SeparatorText("Window and Platform"); if (BeginFields("##platform_fields")) { try @@ -71,11 +85,11 @@ protected override void OnDraw(EditorContext context) } finally { - Ui.EndTable(); + Gui.EndTable(); } } - Ui.SeparatorText("Output"); + Gui.SeparatorText("Output"); if (BeginFields("##output_fields")) { try @@ -85,80 +99,61 @@ protected override void OnDraw(EditorContext context) } finally { - Ui.EndTable(); + Gui.EndTable(); } } - Ui.Spacing(); + Gui.Spacing(); EditorUI.current.widgets.WrappedText("Defaults: Settings > Build > Game. Application ID: Settings > Project > Identity."); if (!string.IsNullOrEmpty(window.error)) { - Ui.Spacing(); + Gui.Spacing(); EditorUI.current.widgets.WrappedText(window.error); } - Ui.Separator(); + Gui.Separator(); DrawButtons(); } - private static bool BeginFields(string id) => Ui.BeginTable( - id, - 2, - ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX, - default(Vector2), - 0f); - - private static void BeginField(string label) - { - Ui.TableNextRow(); - _ = Ui.TableSetColumnIndex(0); - EditorUI.current.widgets.PropertyLabel(label); - _ = Ui.TableSetColumnIndex(1); - } - - private static void DrawReadOnly( - string label, - string value - ) { - BeginField(label); - Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); - try - { - EditorUI.current.widgets.WrappedText(value); - } - finally - { - Ui.PopStyleColor(); - } - } - private void DrawWindowSize() { int width = window.gameWindowWidth; int height = window.gameWindowHeight; BeginField("Initial Width"); - Ui.SetNextItemWidth(-1f); - if (Ui.InputInt("##game_window_width", ref width, 1, 100, 0)) + Gui.SetNextItemWidth(-1f); + if (Gui.InputInt("##game_window_width", ref width, 1, 100, 0)) + { window.gameWindowWidth = Math.Max(1, width); + } BeginField("Initial Height"); - Ui.SetNextItemWidth(-1f); - if (Ui.InputInt("##game_window_height", ref height, 1, 100, 0)) + Gui.SetNextItemWidth(-1f); + if (Gui.InputInt("##game_window_height", ref height, 1, 100, 0)) + { window.gameWindowHeight = Math.Max(1, height); + } } private void DrawManagedDeployment() { BeginField("Managed Deployment"); - Ui.SetNextItemWidth(-1f); + Gui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##game_deployment", window.gameManagedDeployment?.value ?? "Platform default")) + { return; + } try { - if (Ui.Selectable("Platform default", window.gameManagedDeployment is null)) + if (Gui.Selectable("Platform default", window.gameManagedDeployment is null)) + { window.gameManagedDeployment = null; - foreach (ManagedDeploymentId deployment in window.availableManagedDeployments) - if (Ui.Selectable(deployment.value, window.gameManagedDeployment == deployment)) + } + foreach (ManagedDeploymentID deployment in window.availableManagedDeployments) + { + if (Gui.Selectable(deployment.value, window.gameManagedDeployment == deployment)) + { window.gameManagedDeployment = deployment; + } + } } finally { @@ -169,14 +164,18 @@ private void DrawManagedDeployment() private void DrawTarget() { BeginField("Target"); - Ui.SetNextItemWidth(-1f); + Gui.SetNextItemWidth(-1f); string preview = window.GetGameTargetDisplayName(window.gameTarget); if (!EditorUI.current.widgets.BeginBoundedCombo("##game_target", preview)) + { return; + } try { - foreach (BuildTargetId target in window.availableGameTargets) + foreach (BuildTargetID target in window.availableGameTargets) + { DrawTargetChoice(target); + } } finally { @@ -184,28 +183,71 @@ private void DrawTarget() } } - private void DrawTargetChoice(BuildTargetId target) + private void DrawTargetChoice(BuildTargetID target) { bool selected = window.gameTarget == target; - if (Ui.Selectable(window.GetGameTargetDisplayName(target), selected)) + if (Gui.Selectable(window.GetGameTargetDisplayName(target), selected)) + { window.gameTarget = target; + } if (selected) - Ui.SetItemDefaultFocus(); + { + Gui.SetItemDefaultFocus(); + } } private void DrawButtons() { - Ui.Spacing(); + Gui.Spacing(); string primaryLabel = "Export"; - EditorUiLayout style = Ui.GetLayout(); - float closeWidth = Ui.MeasureText("Close").X + style.framePadding.X * 2f; - float primaryWidth = Ui.MeasureText(primaryLabel).X + style.framePadding.X * 2f; - Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - closeWidth - style.itemSpacing.X - primaryWidth)); - if (Ui.Button("Close")) + EditorUILayout style = Gui.GetLayout(); + float closeWidth = Gui.MeasureText("Close").X + style.framePadding.X * 2f; + float primaryWidth = Gui.MeasureText(primaryLabel).X + style.framePadding.X * 2f; + Gui.SetCursorPosX( + Gui.GetCursorPosX() + MathF.Max(0f, Gui.GetContentRegionAvailable().X - closeWidth - style.itemSpacing.X - primaryWidth) + ); + if (Gui.Button("Close")) + { window.CloseGame(); - Ui.SameLine(0f, -1f); - if (Ui.Button(primaryLabel)) + } + Gui.SameLine(0f, -1f); + if (Gui.Button(primaryLabel)) + { window.BeginGameExport(); + } + } + + private static bool BeginFields(string id) + => Gui.BeginTable( + id, + 2, + ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX, + default, + 0f + ); + + private static void BeginField(string label) + { + Gui.TableNextRow(); + _ = Gui.TableSetColumnIndex(0); + EditorUI.current.widgets.PropertyLabel(label); + _ = Gui.TableSetColumnIndex(1); + } + + private static void DrawReadOnly( + string label, + string value + ) { + BeginField(label); + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); + try + { + EditorUI.current.widgets.WrappedText(value); + } + finally + { + Gui.PopStyleColor(); + } } private static void DrawText( @@ -215,8 +257,8 @@ private static void DrawText( Action apply ) { BeginField(label); - Ui.SetNextItemWidth(-1f); - _ = Ui.InputText($"##{id}", ref value, C_TEXT_CAPACITY); + Gui.SetNextItemWidth(-1f); + _ = Gui.InputText($"##{id}", ref value, C_TEXT_CAPACITY); apply(value); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs index a3d7b9cf8..52d868a28 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs @@ -1,25 +1,31 @@ using System.Numerics; using Inno.Editor.Core; +using Inno.Editor.Exporting; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + namespace Inno.Editor.Workbench; + [EditorModal("export.game.progress", "Exporting Game", order: 311)] internal sealed class GameExportProgressModal(ExportWindowModule window) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; - /// + + /// public override bool isVisible => window.isGameProgressVisible; - /// + + /// public override bool allowScrolling => false; - /// + + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = window.progress; - m_operation = snapshot.operationId; + EditorExportProgress snapshot = window.progress; + m_operation = snapshot.operationID; m_content = new( string.IsNullOrEmpty(snapshot.error) ? snapshot.status : snapshot.error, snapshot.fraction, @@ -28,13 +34,16 @@ Vector2 availableContentSize actionEnabled: !snapshot.cancellationRequested, cancelOnEscape: true ); - m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); + m_layout = EditorUISession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } - /// + + /// protected override void OnDraw(EditorContext context) { - if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + if (EditorUISession.current.widgets.DrawDialog(m_content, m_layout)) + { window.CancelGameExport(m_operation); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs index dcf5d8d11..0948ebcb1 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.Numerics; using Inno.Editor.Core; +using Inno.Editor.Exporting; using Inno.Editor.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; @@ -22,29 +24,33 @@ internal sealed class PluginExportModal(ExportWindowModule window) : EditorModal private bool m_dependencies; private long m_operation; private float m_wrapWidth; - /// + + /// public override bool isVisible => window.isPluginVisible; - /// + + /// public override bool canMove => true; - /// + + /// public override Vector2 initialSize => new(680f, 0f); - /// + + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var progress = window.progress; - m_operation = progress.operationId; - m_identity = $"{window.pluginId} (from Project ID)"; + EditorExportProgress progress = window.progress; + m_operation = progress.operationID; + m_identity = $"{window.pluginID} (from Project ID)"; m_name = window.pluginDisplayName; m_destination = window.pluginOutputPath; m_dependencies = window.includePluginDependencies; m_busy = window.isPluginBusy; m_outcome = string.IsNullOrEmpty(progress.error) ? progress.status : progress.error; float width = availableContentSize.X; - float scrollbar = Ui.GetLayout().scrollbarSize; - float checkboxWidth = Ui.GetFrameHeight() + Ui.GetLayout().itemInnerSpacing.X + - Ui.MeasureText("Include dependency Plugin packages").X; + float scrollbar = Gui.GetLayout().scrollbarSize; + float checkboxWidth = Gui.GetFrameHeight() + Gui.GetLayout().itemInnerSpacing.X + + Gui.MeasureText("Include dependency Plugin packages").X; float height = Present(false, width); float availableHeight = availableContentSize.Y - (checkboxWidth > width ? scrollbar : 0f); if (height > availableHeight) @@ -55,7 +61,8 @@ Vector2 availableContentSize m_wrapWidth = width; return new Vector2(MathF.Max(width, checkboxWidth), height); } - /// + + /// protected override void OnDraw(EditorContext context) => Present(true, m_wrapWidth); private float Present( @@ -64,12 +71,14 @@ float width ) { float height = 0f; int row = 0; - Vector2 origin = draw ? Ui.GetCursorPosition() : Vector2.Zero; + Vector2 origin = draw ? Gui.GetCursorPosition() : Vector2.Zero; if (!draw) + { m_rows.Clear(); - var layout = Ui.GetLayout(); + } + EditorUILayout layout = Gui.GetLayout(); float gap = layout.itemSpacing.Y; - float frame = Ui.MeasureText("M").Y + layout.framePadding.Y * 2f; + float frame = Gui.MeasureText("M").Y + layout.framePadding.Y * 2f; Text(C_DESCRIPTION, true); Text("Plugin ID"); Text(m_identity, true); @@ -78,43 +87,53 @@ float width Row(frame); if (draw) { - Ui.BeginDisabled(m_busy); + Gui.BeginDisabled(m_busy); try { - if (Ui.Checkbox("Include dependency Plugin packages", ref m_dependencies)) + if (Gui.Checkbox("Include dependency Plugin packages", ref m_dependencies)) + { window.includePluginDependencies = m_dependencies; + } } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } Text(C_HINT, true); if (m_outcome.Length != 0) + { Text(m_outcome, true); + } Row(frame); if (draw) { - float closeWidth = Ui.MeasureText("Close").X + layout.framePadding.X * 2f; - float actionWidth = Ui.MeasureText(m_busy ? "Cancel" : "Export").X + layout.framePadding.X * 2f; - Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, width - closeWidth - actionWidth - layout.itemSpacing.X)); - Ui.BeginDisabled(m_busy); + float closeWidth = Gui.MeasureText("Close").X + layout.framePadding.X * 2f; + float actionWidth = Gui.MeasureText(m_busy ? "Cancel" : "Export").X + layout.framePadding.X * 2f; + Gui.SetCursorPosX(Gui.GetCursorPosX() + MathF.Max(0f, width - closeWidth - actionWidth - layout.itemSpacing.X)); + Gui.BeginDisabled(m_busy); try { - if (Ui.Button("Close")) + if (Gui.Button("Close")) + { window.ClosePlugin(); + } } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } - Ui.SameLine(0f, -1f); - if (Ui.Button(m_busy ? "Cancel" : "Export")) + Gui.SameLine(0f, -1f); + if (Gui.Button(m_busy ? "Cancel" : "Export")) { if (m_busy) + { window.CancelPluginExport(m_operation); + } else + { window.BeginPluginExport(); + } } } return MathF.Ceiling(height); @@ -122,11 +141,15 @@ float width void Row(float extent) { if (draw) - Ui.SetCursorPosition(origin + new Vector2(0f, m_rows[row++])); + { + Gui.SetCursorPosition(origin + new Vector2(0f, m_rows[row++])); + } else { if (m_rows.Count != 0) + { height += gap; + } m_rows.Add(height); height += extent; } @@ -135,13 +158,19 @@ void Text( string text, bool wrapped = true ) { - Row(draw ? 0f : (wrapped ? Ui.MeasureWrappedText(text, width) : Ui.MeasureText(text)).Y); + Row(draw ? 0f : (wrapped ? Gui.MeasureWrappedText(text, width) : Gui.MeasureText(text)).Y); if (!draw) + { return; + } if (wrapped) - EditorUiSession.current.widgets.WrappedText(text, width); + { + EditorUISession.current.widgets.WrappedText(text, width); + } else - Ui.Text(text); + { + Gui.Text(text); + } } void Field( string label, @@ -151,22 +180,28 @@ ref string value Text(label); Row(frame); if (!draw) + { return; - Ui.BeginDisabled(m_busy); + } + Gui.BeginDisabled(m_busy); try { - Ui.SetNextItemWidth(width); - if (Ui.InputText(id, ref value, C_TEXT_CAPACITY)) + Gui.SetNextItemWidth(width); + if (Gui.InputText(id, ref value, C_TEXT_CAPACITY)) { if (id == "##plugin_name") + { window.pluginDisplayName = value; + } else + { window.pluginOutputPath = value; + } } } finally { - Ui.EndDisabled(); + Gui.EndDisabled(); } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIDs.cs similarity index 94% rename from src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIDs.cs index 2e2ba8575..50ad058f2 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIDs.cs @@ -1,5 +1,6 @@ namespace Inno.Editor.Workbench; -internal static class GlobalInteractionIds + +internal static class GlobalInteractionIDs { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; internal const string C_FIND_COMMAND = "editor/find-command"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs index adad5c98e..515e66050 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs @@ -2,7 +2,8 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; -[EditorMenuSource(GlobalInteractionIds.C_MAIN_MENU_AREA)] + +[EditorMenuSource(GlobalInteractionIDs.C_MAIN_MENU_AREA)] internal sealed class WorkbenchMenuSource : EditorMenuSource { /// @@ -20,7 +21,7 @@ EditorMenuBuilder builder foreach (EditorPanelAttribute panel in context.interactions.GetPanelDeclarations()) { string path = string.IsNullOrEmpty(panel.menuPath) ? "Window/" + panel.title : "Window/" + panel.menuPath + "/" + panel.title; - builder.Add(path, GlobalInteractionIds.C_TOGGLE_PANEL, panel.order, panel.separatorBefore, panel.id); + builder.Add(path, GlobalInteractionIDs.C_TOGGLE_PANEL, panel.order, panel.separatorBefore, panel.id); } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs index 621165937..84f1cab86 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs @@ -3,32 +3,40 @@ using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Scripting; + namespace Inno.Editor.Workbench; + [EditorModal("scripting.compilation", "Compiling Scripts", order: 100)] internal sealed class ScriptCompilationModal(IEditorScriptCompilation scripting) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; - /// + + /// public override bool isVisible => scripting.requiresExclusiveProgress; - /// + + /// public override bool allowScrolling => false; - /// + + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = scripting.progress; - m_operation = snapshot.operationId; + EditorScriptCompilationProgress snapshot = scripting.progress; + m_operation = snapshot.operationID; m_content = new(snapshot.status, snapshot.fraction, actionLabel: "Cancel", actionEnabled: snapshot.canCancel, cancelOnEscape: true); - m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); + m_layout = EditorUISession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } - /// + + /// protected override void OnDraw(EditorContext context) { - if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + if (EditorUISession.current.widgets.DrawDialog(m_content, m_layout)) + { scripting.CancelCompilation(m_operation); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs new file mode 100644 index 000000000..941f3638e --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance")] +internal sealed class AppearanceSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Customize editor appearance, scaling, and semantic presentation."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs index b9eac6bc9..25ef74039 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs @@ -1,9 +1,11 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor/Appearance/Density", order: 50)] internal sealed class DensitySetting : EditorSetting { @@ -11,10 +13,12 @@ internal sealed class DensitySetting : EditorSetting /// Gets the comfortable default density. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the appearance section containing this setting. /// public override string section => "Layout"; + /// /// Gets the user-facing density description. /// @@ -30,15 +34,21 @@ protected override void OnDraw(EditorSettingObject setting) { bool compact = setting.GetAsBoolean("compact", false); string preview = compact ? "Compact" : "Comfortable"; - Ui.SetNextItemWidth(-1f); + Gui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##editor_density", preview)) + { return; + } try { - if (Ui.Selectable("Comfortable", !compact)) + if (Gui.Selectable("Comfortable", !compact)) + { setting.SetAsBoolean("compact", false); - if (Ui.Selectable("Compact", compact)) + } + if (Gui.Selectable("Compact", compact)) + { setting.SetAsBoolean("compact", true); + } } finally { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs new file mode 100644 index 000000000..7fefd2f32 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Settings; +using Inno.Platform; + +namespace Inno.Editor.Workbench; + +[EditorModule("editor-frame-pacing", order: 20)] +internal sealed class EditorFramePacingModule( + EditorSettings settings, + FramePacingOptions pacing +) : EditorModule +{ + private IDisposable? m_settingsSubscription; + + /// + /// Initializes this feature when its owning runtime becomes active. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void OnStart(EditorContext context) + { + Apply(settings); + m_settingsSubscription = settings.ListenChanges(Apply); + } + + /// + /// Stops this feature before its owning runtime releases the active generation. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); + + private void Apply(EditorSettings current) + { + pacing.verticalSync = current.Get("Editor/Rendering/Vertical Sync").GetAsBoolean("enabled", false); + pacing.maximumFrameRate = Math.Clamp(current.Get("Editor/Rendering/Maximum Frame Rate").GetAsInt32("value", 0), 0, 1000); + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs new file mode 100644 index 000000000..9ad2fc917 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering")] +internal sealed class EditorRenderingSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Control editor presentation independently of game simulation timing."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs new file mode 100644 index 000000000..496120ccb --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/File")] +internal sealed class FileIconSetting() : IconSetting(ImGuiIcon.C_FILE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a generic source file."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs new file mode 100644 index 000000000..89a1197e4 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Folder")] +internal sealed class FolderIconSetting() : IconSetting(ImGuiIcon.C_FOLDER) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a source directory."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs deleted file mode 100644 index 57b0598db..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs +++ /dev/null @@ -1,129 +0,0 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; -using Inno.Editor.Core; -using Inno.Editor.Settings; -using Inno.Platform; -using Ui = Inno.Editor.ImGui.ImGui; - -namespace Inno.Editor.Workbench; -[EditorSettingPath("Editor/Rendering")] -internal sealed class EditorRenderingSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Control editor presentation independently of game simulation timing."; -} - -[EditorSettingPath("Editor/Rendering/Vertical Sync", order: 10)] -internal sealed class VerticalSyncSetting : EditorSetting -{ - /// - /// Gets a new value initialized to this setting's canonical default state. - /// - public override EditorSettingObject defaultValue - { - get - { - var result = new EditorSettingObject(); - result.SetAsBoolean("enabled", false); - return result; - } - } - - /// - /// Gets the presentation section that groups this setting. - /// - public override string section => "Frame Rate"; - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Synchronize presentation to the display refresh rate. Disable to allow higher frame rates."; - - /// - /// Draws this feature using the current editor presentation context. - /// - /// - /// The mutable editor setting value currently being presented. - /// - protected override void OnDraw(EditorSettingObject setting) - { - bool enabled = setting.GetAsBoolean("enabled", false); - if (Ui.Checkbox("##vsync", ref enabled)) - setting.SetAsBoolean("enabled", enabled); - } -} - -[EditorSettingPath("Editor/Rendering/Maximum Frame Rate", order: 20)] -internal sealed class MaximumFrameRateSetting : EditorSetting -{ - /// - /// Gets a new value initialized to this setting's canonical default state. - /// - public override EditorSettingObject defaultValue - { - get - { - var result = new EditorSettingObject(); - result.SetAsInt32("value", 0); - return result; - } - } - - /// - /// Gets the presentation section that groups this setting. - /// - public override string section => "Frame Rate"; - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Software frame-rate limit. Zero means Unlimited. Fixed-step simulation is unaffected."; - - /// - /// Draws this feature using the current editor presentation context. - /// - /// - /// The mutable editor setting value currently being presented. - /// - protected override void OnDraw(EditorSettingObject setting) - { - int rate = setting.GetAsInt32("value", 0); - if (Ui.InputInt("##maximum_fps", ref rate, 1, 100, 0)) - setting.SetAsInt32("value", Math.Clamp(rate, 0, 1000)); - if (rate == 0) - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Unlimited"); - } -} - -[EditorModule("editor-frame-pacing", order: 20)] -internal sealed class EditorFramePacingModule( - EditorSettings settings, - FramePacingOptions pacing -) : EditorModule -{ - private IDisposable? m_settingsSubscription; - /// - /// Initializes this feature when its owning runtime becomes active. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void OnStart(EditorContext context) - { - Apply(settings); - m_settingsSubscription = settings.ListenChanges(Apply); - } - - /// - /// Stops this feature before its owning runtime releases the active generation. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); - private void Apply(EditorSettings current) - { - pacing.verticalSync = current.Get("Editor/Rendering/Vertical Sync").GetAsBoolean("enabled", false); - pacing.maximumFrameRate = Math.Clamp(current.Get("Editor/Rendering/Maximum Frame Rate").GetAsInt32("value", 0), 0, 1000); - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs new file mode 100644 index 000000000..a7774e651 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/GameObject")] +internal sealed class GameObjectIconSetting() : IconSetting(ImGuiIcon.C_CUBE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a scene GameObject."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs new file mode 100644 index 000000000..4fe179c92 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor")] +internal sealed class GlobalSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure editor-wide appearance, behavior, and user-facing tools."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs deleted file mode 100644 index 401cdb0f1..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Inno.Editor.Settings; - -namespace Inno.Editor.Workbench; -[EditorSettingPath("Editor")] -internal sealed class GlobalSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure editor-wide appearance, behavior, and user-facing tools."; -} - -[EditorSettingPath("Editor/Appearance")] -internal sealed class AppearanceSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Customize editor appearance, scaling, and semantic presentation."; -} - -[EditorSettingPath("Editor/Appearance/Icons")] -internal sealed class IconSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Choose the glyph used for each semantic object throughout the editor."; -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs new file mode 100644 index 000000000..0d8788248 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Workbench; + +internal abstract class IconSetting : EditorSetting +{ + private static readonly IReadOnlyList<(string name, string glyph)> ICONS = EditorIconCatalog.standard; + private readonly string m_glyph; + + /// + /// Creates a validated icon setting instance. + /// + /// + /// The glyph text validated by the icon setting operation. + /// + protected IconSetting(string glyph) + { + ArgumentException.ThrowIfNullOrWhiteSpace(glyph); + m_glyph = glyph; + } + + /// + /// Gets a new value initialized to this setting's canonical default state. + /// + public override EditorSettingObject defaultValue => CreateDefault(m_glyph); + + /// + /// Gets the presentation section that groups this setting. + /// + public override string section => "Editor Icons"; + + /// + /// Renders this feature using the current editor presentation context. + /// + /// + /// The mutable editor setting value currently being presented. + /// + protected override void OnDraw(EditorSettingObject setting) + { + string value = setting.GetAsString("value", m_glyph) ?? m_glyph; + float iconSlotWidth = GetIconSlotWidth(); + Gui.SetNextItemWidth(-1f); + bool isOpen = EditorUI.current.widgets.BeginBoundedCombo("##icon", value + " " + GetIconName(value)); + if (isOpen) + { + try + { + for (int i = 0; i < ICONS.Count; i++) + { + (string name, string candidate) = ICONS[i]; + Gui.PushID(name); + try + { + bool selected = string.Equals(candidate, value, StringComparison.Ordinal); + if (Gui.Selectable("##icon_option", selected, ImGuiSelectableFlags.None, new Vector2(0f, Gui.GetFrameHeight()))) + { + value = candidate; + setting.SetAsString("value", candidate); + } + + Vector2 minimum = Gui.GetItemMinimum(); + Vector2 maximum = Gui.GetItemMaximum(); + EditorUILayout style = Gui.GetLayout(); + float lineHeight = Gui.GetTextLineHeight(); + DrawIconTextAt( + Gui.GetDrawList(), + new Vector2( + minimum.X + style.framePadding.X, + minimum.Y + MathF.Max(0f, (maximum.Y - minimum.Y - lineHeight) * 0.5f) + ), + candidate, + name, + iconSlotWidth + ); + if (selected) + { + Gui.SetItemDefaultFocus(); + } + } + finally + { + Gui.PopID(); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + } + } + + private static EditorSettingObject CreateDefault(string glyph) + { + ArgumentException.ThrowIfNullOrWhiteSpace(glyph); + var result = new EditorSettingObject(); + result.SetAsString("value", glyph); + return result; + } + + private static float GetIconSlotWidth() => EditorUI.current.widgets.GetIconCatalogWidth(); + + private static string GetIconName(string glyph) + { + for (int i = 0; i < ICONS.Count; i++) + { + if (string.Equals(ICONS[i].glyph, glyph, StringComparison.Ordinal)) + { + return ICONS[i].name; + } + } + + return glyph; + } + + private static void DrawIconTextAt( + EditorDrawList drawList, + Vector2 origin, + string glyph, + string text, + float iconSlotWidth + ) { + EditorUILayout style = Gui.GetLayout(); + float fontSize = Gui.GetFontSize(); + float lineHeight = Gui.GetTextLineHeight(); + uint color = Gui.GetStyleColor(ImGuiCol.Text); + EditorUI.current.widgets.AddGlyphCentered( + fontSize, + glyph, + new Vector2(origin.X + iconSlotWidth * 0.5f, origin.Y + lineHeight * 0.5f), + color + ); + Gui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs deleted file mode 100644 index e9d68e178..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs +++ /dev/null @@ -1,217 +0,0 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Editor.Settings; -using Ui = Inno.Editor.ImGui.ImGui; - -namespace Inno.Editor.Workbench; -internal abstract class IconSetting : EditorSetting -{ - private static readonly IReadOnlyList<(string Name, string Glyph)> C_ICONS = EditorIconCatalog.standard; - private readonly string m_glyph; - /// - /// Creates a validated icon setting instance. - /// - /// - /// The glyph text validated by the icon setting operation. - /// - protected IconSetting(string glyph) - { - ArgumentException.ThrowIfNullOrWhiteSpace(glyph); - m_glyph = glyph; - } - - /// - /// Gets a new value initialized to this setting's canonical default state. - /// - public override EditorSettingObject defaultValue => CreateDefault(m_glyph); - /// - /// Gets the presentation section that groups this setting. - /// - public override string section => "Editor Icons"; - - /// - /// Renders this feature using the current editor presentation context. - /// - /// - /// The mutable editor setting value currently being presented. - /// - protected override void OnDraw(EditorSettingObject setting) - { - string value = setting.GetAsString("value", m_glyph) ?? m_glyph; - float iconSlotWidth = GetIconSlotWidth(); - Ui.SetNextItemWidth(-1f); - bool isOpen = EditorUI.current.widgets.BeginBoundedCombo("##icon", value + " " + GetIconName(value)); - if (isOpen) - { - try - { - for (int i = 0; i < C_ICONS.Count; i++) - { - (string name, string candidate) = C_ICONS[i]; - Ui.PushId(name); - try - { - bool selected = string.Equals(candidate, value, StringComparison.Ordinal); - if (Ui.Selectable("##icon_option", selected, ImGuiSelectableFlags.None, new Vector2(0f, Ui.GetFrameHeight()))) - { - value = candidate; - setting.SetAsString("value", candidate); - } - - Vector2 minimum = Ui.GetItemMinimum(); - Vector2 maximum = Ui.GetItemMaximum(); - EditorUiLayout style = Ui.GetLayout(); - float lineHeight = Ui.GetTextLineHeight(); - DrawIconTextAt( - Ui.GetDrawList(), - new Vector2(minimum.X + style.framePadding.X, minimum.Y + MathF.Max(0f, (maximum.Y - minimum.Y - lineHeight) * 0.5f)), - candidate, - name, - iconSlotWidth - ); - if (selected) - Ui.SetItemDefaultFocus(); - } - finally - { - Ui.PopId(); - } - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - } - } - - private static EditorSettingObject CreateDefault(string glyph) - { - ArgumentException.ThrowIfNullOrWhiteSpace(glyph); - var result = new EditorSettingObject(); - result.SetAsString("value", glyph); - return result; - } - - private static float GetIconSlotWidth() => EditorUI.current.widgets.GetIconCatalogWidth(); - private static string GetIconName(string glyph) - { - for (int i = 0; i < C_ICONS.Count; i++) - { - if (string.Equals(C_ICONS[i].Glyph, glyph, StringComparison.Ordinal)) - return C_ICONS[i].Name; - } - - return glyph; - } - - private static void DrawIconTextAt( - EditorDrawList drawList, - Vector2 origin, - string glyph, - string text, - float iconSlotWidth - ) { - EditorUiLayout style = Ui.GetLayout(); - float fontSize = Ui.GetFontSize(); - float lineHeight = Ui.GetTextLineHeight(); - uint color = Ui.GetStyleColor(ImGuiCol.Text); - EditorUI.current.widgets.AddGlyphCentered(fontSize, glyph, new Vector2(origin.X + iconSlotWidth * 0.5f, origin.Y + lineHeight * 0.5f), color); - Inno.Editor.ImGui.ImGui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); - } -} - -[EditorSettingPath("Editor/Appearance/Icons/Scene")] -internal sealed class SceneIconSetting() : IconSetting(ImGuiIcon.Cubes) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a scene document or loaded scene."; -} - -[EditorSettingPath("Editor/Appearance/Icons/GameObject")] -internal sealed class GameObjectIconSetting() : IconSetting(ImGuiIcon.Cube) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a scene GameObject."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Prefab")] -internal sealed class PrefabIconSetting() : IconSetting(ImGuiIcon.DiceD6) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a reusable prefab object."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Layers")] -internal sealed class LayersIconSetting() : IconSetting(ImGuiIcon.LayerGroup) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a project layer configuration."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Folder")] -internal sealed class FolderIconSetting() : IconSetting(ImGuiIcon.Folder) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a source directory."; -} - -[EditorSettingPath("Editor/Appearance/Icons/File")] -internal sealed class FileIconSetting() : IconSetting(ImGuiIcon.File) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a generic source file."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Shader")] -internal sealed class ShaderIconSetting() : IconSetting(ImGuiIcon.Shader) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Shader graph assets and their Inspector headers."; -} - -[EditorSettingPath("Editor/Appearance/Icons/ShaderSource")] -internal sealed class ShaderSourceIconSetting() : IconSetting(ImGuiIcon.RupeeSign) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Material")] -internal sealed class MaterialIconSetting() : IconSetting(ImGuiIcon.Palette) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Material assets and their Inspector headers."; -} - -[EditorSettingPath("Editor/Appearance/Icons/RenderPipeline")] -internal sealed class RenderPipelineIconSetting() : IconSetting(ImGuiIcon.RupiahSign) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Render Pipeline assets and their Inspector headers."; -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs new file mode 100644 index 000000000..3cc555388 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons")] +internal sealed class IconSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Choose the glyph used for each semantic object throughout the editor."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs new file mode 100644 index 000000000..2ee0d74a5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Layers")] +internal sealed class LayersIconSetting() : IconSetting(ImGuiIcon.C_LAYER_GROUP) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a project layer configuration."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs new file mode 100644 index 000000000..658e905a5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Material")] +internal sealed class MaterialIconSetting() : IconSetting(ImGuiIcon.C_PALETTE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Material assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs new file mode 100644 index 000000000..bed2a4ea5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs @@ -0,0 +1,54 @@ +using System; +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering/Maximum Frame Rate", order: 20)] +internal sealed class MaximumFrameRateSetting : EditorSetting +{ + /// + /// Gets a new value initialized to this setting's canonical default state. + /// + public override EditorSettingObject defaultValue + { + get + { + var result = new EditorSettingObject(); + result.SetAsInt32("value", 0); + return result; + } + } + + /// + /// Gets the presentation section that groups this setting. + /// + public override string section => "Frame Rate"; + + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Software frame-rate limit. Zero means Unlimited. Fixed-step simulation is unaffected."; + + /// + /// Draws this feature using the current editor presentation context. + /// + /// + /// The mutable editor setting value currently being presented. + /// + protected override void OnDraw(EditorSettingObject setting) + { + int rate = setting.GetAsInt32("value", 0); + if (Gui.InputInt("##maximum_fps", ref rate, 1, 100, 0)) + { + setting.SetAsInt32("value", Math.Clamp(rate, 0, 1000)); + } + if (rate == 0) + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Unlimited"); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs new file mode 100644 index 000000000..3101c7d17 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Prefab")] +internal sealed class PrefabIconSetting() : IconSetting(ImGuiIcon.C_DICE_D_6) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a reusable prefab object."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs new file mode 100644 index 000000000..9da26e959 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/RenderPipeline")] +internal sealed class RenderPipelineIconSetting() : IconSetting(ImGuiIcon.C_RUPIAH_SIGN) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Render Pipeline assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs new file mode 100644 index 000000000..e17d7677f --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Scene")] +internal sealed class SceneIconSetting() : IconSetting(ImGuiIcon.C_CUBES) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a scene document or loaded scene."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs new file mode 100644 index 000000000..679b03d30 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Shader")] +internal sealed class ShaderIconSetting() : IconSetting(ImGuiIcon.C_SHADER) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Shader graph assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs new file mode 100644 index 000000000..f0acc497f --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs @@ -0,0 +1,14 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/ShaderSource")] +internal sealed class ShaderSourceIconSetting() : IconSetting(ImGuiIcon.C_RUPEE_SIGN) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description + => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs new file mode 100644 index 000000000..60751f0df --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs @@ -0,0 +1,47 @@ +using Inno.Editor.Settings; + +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering/Vertical Sync", order: 10)] +internal sealed class VerticalSyncSetting : EditorSetting +{ + /// + /// Gets a new value initialized to this setting's canonical default state. + /// + public override EditorSettingObject defaultValue + { + get + { + var result = new EditorSettingObject(); + result.SetAsBoolean("enabled", false); + return result; + } + } + + /// + /// Gets the presentation section that groups this setting. + /// + public override string section => "Frame Rate"; + + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Synchronize presentation to the display refresh rate. Disable to allow higher frame rates."; + + /// + /// Draws this feature using the current editor presentation context. + /// + /// + /// The mutable editor setting value currently being presented. + /// + protected override void OnDraw(EditorSettingObject setting) + { + bool enabled = setting.GetAsBoolean("enabled", false); + if (Gui.Checkbox("##vsync", ref enabled)) + { + setting.SetAsBoolean("enabled", enabled); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs new file mode 100644 index 000000000..6ffb300c0 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Restores UI zoom to the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_RESET)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Actual Size", order: 120)] +[EditorShortcut(KeyCode.D0, primary: true)] +internal sealed class ActualSizeEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.UseActualSize(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs index 7b46f0185..64f46acb0 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs @@ -1,23 +1,36 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor/Appearance/Accessibility/Actual Size")] internal sealed class ActualSizeSetting : EditorSetting { - private static readonly (float Value, string Label)[] C_CHOICES = [(0.75f, "75%"), (0.9f, "90%"), (1f, "100%"), (1.1f, "110%"), (1.25f, "125%"), (1.5f, "150%")]; + private static readonly (float value, string label)[] CHOICES = + [ + (0.75f, "75%"), + (0.9f, "90%"), + (1f, "100%"), + (1.1f, "110%"), + (1.25f, "125%"), + (1.5f, "150%") + ]; + /// /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Font"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -33,16 +46,20 @@ protected override void OnDraw(EditorSettingObject setting) { float value = setting.GetAsSingle("value", 1f); string preview = GetLabel(value); - Ui.SetNextItemWidth(-1f); + Gui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##actual_size", preview)) + { return; + } try { - for (int i = 0; i < C_CHOICES.Length; i++) + for (int i = 0; i < CHOICES.Length; i++) { - (float candidate, string label) = C_CHOICES[i]; - if (Ui.Selectable(label, MathF.Abs(candidate - value) < 0.0001f)) + (float candidate, string label) = CHOICES[i]; + if (Gui.Selectable(label, MathF.Abs(candidate - value) < 0.0001f)) + { setting.SetAsSingle("value", candidate); + } } } finally @@ -60,10 +77,12 @@ private static EditorSettingObject CreateDefault() private static string GetLabel(float value) { - for (int i = 0; i < C_CHOICES.Length; i++) + for (int i = 0; i < CHOICES.Length; i++) { - if (MathF.Abs(C_CHOICES[i].Value - value) < 0.0001f) - return C_CHOICES[i].Label; + if (MathF.Abs(CHOICES[i].value - value) < 0.0001f) + { + return CHOICES[i].label; + } } return $"{value * 100f:0}%"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs index 92f399fc5..98f1a60e5 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs @@ -4,24 +4,26 @@ using Inno.Editor.Settings; namespace Inno.Editor.Workbench; + /// /// Applies the configured actual UI size and preserves project-local zoom multiples around it. /// -/// -/// The host-owned presentation session receiving the selected scale. -/// /// /// The validated configuration that controls this operation. /// +/// +/// The host-owned presentation session receiving the selected scale. +/// [EditorModule("editor-zoom", order: 10)] internal sealed class EditorZoomModule( EditorSettings settings, - EditorUiSession ui + EditorUISession ui ) : EditorModule { - private IDisposable? m_settingsSubscription; private const string C_ACTUAL_SIZE_PATH = "Editor/Appearance/Accessibility/Actual Size"; private const string C_DENSITY_PATH = "Editor/Appearance/Density"; + + private IDisposable? m_settingsSubscription; private float m_actualSize = 1f; private int m_zoomStep; internal float zoom => ui.widgets.style.zoom; @@ -29,9 +31,6 @@ EditorUiSession ui internal bool canZoomOut => ResolveZoom(m_zoomStep - 1) < ResolveZoom(m_zoomStep) - 0.0001f; internal bool isActualSize => m_zoomStep == 0; - internal bool ZoomIn() => SetStep(m_zoomStep + 1); - internal bool ZoomOut() => SetStep(m_zoomStep - 1); - internal bool UseActualSize() => SetStep(0); /// /// Initializes this feature when its owning runtime becomes active. /// @@ -50,10 +49,7 @@ protected override void OnStart(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnStop(EditorContext context) - { - m_settingsSubscription?.Dispose(); - } + protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); /// /// Captures the zoom step relative to the configured actual UI size. @@ -61,10 +57,7 @@ protected override void OnStop(EditorContext context) /// /// The project-local module state that receives the zoom step. /// - protected override void Capture(EditorState state) - { - state.Set("step", m_zoomStep); - } + protected override void Capture(EditorState state) => state.Set("step", m_zoomStep); /// /// Restores the bounded project-local zoom step after settings initialize. @@ -78,6 +71,12 @@ protected override void Restore(EditorState state) _ = ui.widgets.style.SetZoom(ResolveZoom(m_zoomStep)); } + internal bool ZoomIn() => SetStep(m_zoomStep + 1); + + internal bool ZoomOut() => SetStep(m_zoomStep - 1); + + internal bool UseActualSize() => SetStep(0); + private void ApplyActualSize(EditorSettings changedSettings) { m_actualSize = NormalizeActualSize(changedSettings.Get(C_ACTUAL_SIZE_PATH).GetAsSingle("value", 1f)); @@ -95,10 +94,13 @@ private bool SetStep(int step) { float resolved = ResolveZoom(step); if (MathF.Abs(resolved - ResolveZoom(m_zoomStep)) < 0.0001f) + { return false; + } m_zoomStep = step; return ui.widgets.style.SetZoom(resolved); } - private static float NormalizeActualSize(float value) => float.IsFinite(value) ? Math.Clamp(value, EditorStyleMetrics.C_MIN_ZOOM, EditorStyleMetrics.C_MAX_ZOOM) : 1f; + private static float NormalizeActualSize(float value) + => float.IsFinite(value) ? Math.Clamp(value, EditorStyleMetrics.C_MIN_ZOOM, EditorStyleMetrics.C_MAX_ZOOM) : 1f; } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs deleted file mode 100644 index 8b9e31b64..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Inno.Core.Input; -using Inno.Editor.Interactions; - -namespace Inno.Editor.Workbench; -/// -/// Increases UI zoom by one multiple of the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIds.C_ZOOM_IN)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "View/Zoom In", order: 100)] -[EditorShortcut(KeyCode.Plus, primary: true)] -internal sealed class ZoomInEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.ZoomIn(); -} - -/// -/// Decreases UI zoom by one multiple of the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIds.C_ZOOM_OUT)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "View/Zoom Out", order: 110)] -[EditorShortcut(KeyCode.Minus, primary: true)] -internal sealed class ZoomOutEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.ZoomOut(); -} - -/// -/// Restores UI zoom to the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIds.C_ZOOM_RESET)] -[EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "View/Actual Size", order: 120)] -[EditorShortcut(KeyCode.D0, primary: true)] -internal sealed class ActualSizeEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.UseActualSize(); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs new file mode 100644 index 000000000..ad959c7cb --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Increases UI zoom by one multiple of the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_IN)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom In", order: 100)] +[EditorShortcut(KeyCode.Plus, primary: true)] +internal sealed class ZoomInEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.ZoomIn(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs new file mode 100644 index 000000000..c1404ec2d --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Decreases UI zoom by one multiple of the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_OUT)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom Out", order: 110)] +[EditorShortcut(KeyCode.Minus, primary: true)] +internal sealed class ZoomOutEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.ZoomOut(); +} diff --git a/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs b/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs index de68bfe67..e515e037d 100644 --- a/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs +++ b/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs @@ -24,7 +24,9 @@ public PlayerContentMetadata( ReadOnlySpan catalog ) { if (manifest.IsEmpty || catalog.IsEmpty) + { throw new ArgumentException("A Player deployment requires nonempty manifest and catalog documents."); + } this.manifest = manifest.ToArray(); this.catalog = catalog.ToArray(); } diff --git a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs index ef426889f..9a708118a 100644 --- a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs +++ b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs @@ -35,23 +35,30 @@ IReadOnlyDictionary> assemblies ArgumentNullException.ThrowIfNull(deployment); ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Count != deployment.modules.Count) + { throw new InvalidDataException("Linked module ownership differs from the code deployment."); + } var sources = new List(deployment.modules.Count); foreach (GameCodeModule module in deployment.modules) { if (!assemblies.TryGetValue(module.name, out IReadOnlyList? linked) || linked is null || linked.Any(static assembly => assembly is null) || !module.assemblies.Select(static assembly => assembly.name).SequenceEqual( - linked.Select(static assembly => assembly.GetName().Name), StringComparer.Ordinal)) + linked.Select(static assembly => assembly.GetName().Name), + StringComparer.Ordinal + ) + ) { throw new InvalidDataException($"Linked code for module '{module.name}' differs from its deployment."); - sources.Add(new StaticModuleSource(module.name, module.domain, - AssemblyScope.Runtime, linked, module.dependencies)); + } + sources.Add( + new StaticModuleSource(module.name, module.domain, AssemblyScope.Runtime, linked, module.dependencies) + ); } m_linkedDeployment = deployment; m_sources = sources.AsReadOnly(); } - /// + /// public void Activate( ModuleHost modules, GameCodeDeployment deployment @@ -60,7 +67,9 @@ GameCodeDeployment deployment ArgumentNullException.ThrowIfNull(deployment); deployment.ValidateMatches(m_linkedDeployment); if (m_sources.Count == 0) + { return; + } using AssemblyReloadSession activation = modules.BeginReload(m_sources); activation.Activate(); _ = activation.Complete(); diff --git a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs index 763360fe8..70628e4fb 100644 --- a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs +++ b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs @@ -1,5 +1,3 @@ -using Inno.Core.IO; -using Inno.Content; using System; using System.Collections.Generic; using System.IO; @@ -8,30 +6,33 @@ using System.Threading.Tasks; using Inno.Adapter; using Inno.Adapter.Audio; -using Inno.Assets; using Inno.Animation; using Inno.Animation.Runtime; +using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; -using Inno.Core.Events; +using Inno.Content; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Execution; +using Inno.Core.IO; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Modules; using Inno.Engine.Default; +using Inno.Extensibility.Modules; using Inno.Input.Runtime; -using Inno.Runtime; -using Inno.Runtime.Contracts; -using Inno.Scene; using Inno.Platform; using Inno.Rendering; using Inno.Rendering.Runtime; +using Inno.Runtime; +using Inno.Runtime.Contracts; +using Inno.Scene; using Inno.Shell; -using Inno.Storage.Runtime; using Inno.Storage; +using Inno.Storage.Runtime; using Inno.UI.Runtime; + using ShellHost = Inno.Shell.Shell; namespace Inno.Player.Runtime; @@ -51,106 +52,12 @@ private GamePlayerHost( ShellOptions shellOptions, EngineHost engine, PlayerLaunchOptions options - ) - : base(adapterCatalog, shellOptions) + ) : base(adapterCatalog, shellOptions) { m_engine = engine; m_engine.logs.RegisterSink(new ConsoleLogSink(options.consoleColors)); } - internal static async Task CreateAsync( - PlayerLaunchOptions options, - CancellationToken cancellationToken - ) { - ArgumentNullException.ThrowIfNull(options); - EngineHost engine = new EngineHostBuilder() - .UseMetadataSources(options.modules, options.types, options.serializationMetadata) - .UseLogDelivery(options.logDeliveryMode) - .Build(); - GamePlayerHost? host = null; - IRuntimeContentStore? content = null; - try - { - PlayerContentMetadata metadata = await options.contentSource.ReadMetadataAsync(cancellationToken); - using SerializationGeneration serialization = engine.serialization.CaptureGeneration(); - GameRuntimeManifest manifest = RuntimeManifestEnvelope.Decode(metadata.manifest.Span, serialization); - RuntimeContentCatalog catalog = serialization.Deserialize(metadata.catalog.Span); - catalog.Validate(); - if (catalog.runtimeAssemblyCount != manifest.modules.Sum(static module => module.assemblies.Length)) - throw new InvalidDataException("The content catalog and runtime manifest have different code closures."); - ActivateRuntimeModules( - options.moduleActivator, - engine.modules, - GameCodeDeployment.FromManifest(manifest.modules)); - var pack = new ContentPackDescriptor(catalog.contentHash, catalog.packFileName); - content = await options.contentSource.PrepareAsync( - pack, - new StorageScope(manifest.applicationId), - serialization, - cancellationToken); - if (content is null) - throw new InvalidOperationException("The Player content source returned no prepared store."); - if (content.descriptor != pack) - throw new InvalidDataException("The prepared Player content store differs from the selected deployment pack."); - cancellationToken.ThrowIfCancellationRequested(); - host = new GamePlayerHost( - options.adapters, - new ShellOptions - { - adapters = options.adapterSelection, - window = new PlatformWindowOptions - { - title = manifest.productName, - width = manifest.windowWidth, - height = manifest.windowHeight, - resizable = true, - highPixelDensity = true, - visible = options.windowVisible - }, - preferredGraphicsApi = options.graphicsApi, - verticalSync = true, - sRgbBackbuffer = true, - forceSingleThreadedRendering = options.renderOnCallingThread, - suspendWhenHidden = options.windowVisible - }, - engine, options); - host.m_content = content; - content = null; - host.InitializeRuntime(manifest, options); - return host; - } - catch - { - if (host is not null) - { - host.Dispose(); - } - else - { - try - { - content?.Dispose(); - } - finally - { - engine.Dispose(); - } - } - throw; - } - } - - internal async Task RunGameAsync( - IShellFrameDriver frameDriver, - int? smokeFrameLimit = null, - CancellationToken cancellationToken = default - ) { - using IDisposable scope = settings.EnterExecutionScope(); - using IDisposable sessionScope = session.EnterExecutionScope(); - using IDisposable uiScope = session.subsystems.GetRequiredSubsystem().EnterExecutionScope(); - return await RunAsync(frameDriver, smokeFrameLimit, cancellationToken); - } - /// /// Routes one backend-neutral platform event into the active game runtime session. /// @@ -160,10 +67,12 @@ internal async Task RunGameAsync( protected override void OnEvent(Event evnt) { if (evnt is not ApplicationSuspensionChangedEvent) + { session.events.Enqueue(evnt); + } } - /// + /// protected override void OnSuspensionChanged(bool isSuspended) => session.events.Emit(new ApplicationSuspensionChangedEvent(isSuspended)); @@ -187,16 +96,23 @@ protected override void OnSmokeCompleted(int frameCount) m_engine.diagnostics.RegisterSink(diagnostics); m_engine.diagnostics.UnregisterSink(diagnostics); if (diagnostics.errors.Count != 0) - throw new InvalidOperationException("Player smoke completed with active errors:" + Environment.NewLine - + string.Join(Environment.NewLine, diagnostics.errors)); + { + throw new InvalidOperationException( + "Player smoke completed with active errors:" + Environment.NewLine + + string.Join(Environment.NewLine, diagnostics.errors) + ); + } RenderFrameStatistics? statistics; using (rendering.EnterExecutionScope()) + { statistics = GraphicsSettings.frameStatistics; + } Console.WriteLine( $"INNO-SMOKE frames={frameCount} " + $"views={statistics?.viewCount ?? 0} " + $"draws={statistics?.drawCount ?? 0} " - + $"dispatches={statistics?.dispatchCount ?? 0}"); + + $"dispatches={statistics?.dispatchCount ?? 0}" + ); } /// @@ -218,7 +134,9 @@ protected override void DisposeProductResources() Attempt(() => m_diagnosticLogs?.Dispose()); m_diagnosticLogs = null; if (failures.Count > 0) + { throw new AggregateException("Player retirement failed after all available owners were attempted.", failures); + } void Attempt(Action cleanup) { @@ -237,6 +155,109 @@ void Attempt(Action cleanup) } } + internal async Task RunGameAsync( + IShellFrameDriver frameDriver, + int? smokeFrameLimit = null, + CancellationToken cancellationToken = default + ) { + using IDisposable scope = settings.EnterExecutionScope(); + using IDisposable sessionScope = session.EnterExecutionScope(); + using IDisposable uiScope = session.subsystems.GetRequiredSubsystem().EnterExecutionScope(); + return await RunAsync(frameDriver, smokeFrameLimit, cancellationToken); + } + + internal static async Task CreateAsync( + PlayerLaunchOptions options, + CancellationToken cancellationToken + ) { + ArgumentNullException.ThrowIfNull(options); + EngineHost engine = new EngineHostBuilder() + .UseMetadataSources(options.modules, options.types, options.serializationMetadata) + .UseLogDelivery(options.logDeliveryMode) + .Build(); + GamePlayerHost? host = null; + IRuntimeContentStore? content = null; + try + { + PlayerContentMetadata metadata = await options.contentSource.ReadMetadataAsync(cancellationToken); + using SerializationGeneration serialization = engine.serialization.CaptureGeneration(); + GameRuntimeManifest manifest = RuntimeManifestEnvelope.Decode(metadata.manifest.Span, serialization); + RuntimeContentCatalog catalog = serialization.Deserialize(metadata.catalog.Span); + catalog.Validate(); + if (catalog.runtimeAssemblyCount != manifest.modules.Sum(static module => module.assemblies.Length)) + { + throw new InvalidDataException("The content catalog and runtime manifest have different code closures."); + } + ActivateRuntimeModules( + options.moduleActivator, + engine.modules, + GameCodeDeployment.FromManifest(manifest.modules) + ); + var pack = new ContentPackDescriptor(catalog.contentHash, catalog.packFileName); + content = await options.contentSource.PrepareAsync( + pack, + new StorageScope(manifest.applicationId), + serialization, + cancellationToken + ); + if (content is null) + { + throw new InvalidOperationException("The Player content source returned no prepared store."); + } + if (content.descriptor != pack) + { + throw new InvalidDataException("The prepared Player content store differs from the selected deployment pack."); + } + cancellationToken.ThrowIfCancellationRequested(); + host = new GamePlayerHost( + options.adapters, + new ShellOptions + { + adapters = options.adapterSelection, + window = new PlatformWindowOptions + { + title = manifest.productName, + width = manifest.windowWidth, + height = manifest.windowHeight, + resizable = true, + highPixelDensity = true, + visible = options.windowVisible + }, + preferredGraphicsApi = options.graphicsApi, + verticalSync = true, + sRgbBackbuffer = true, + forceSingleThreadedRendering = options.renderOnCallingThread, + suspendWhenHidden = options.windowVisible + }, + engine, + options + ); + host.m_content = content; + content = null; + host.InitializeRuntime(manifest, options); + return host; + } + catch + { + if (host is not null) + { + host.Dispose(); + } + else + { + try + { + content?.Dispose(); + } + finally + { + engine.Dispose(); + } + } + throw; + } + } + private RuntimeSession session => m_session ?? throw new InvalidOperationException("The Player runtime session is not initialized."); private ProjectSettingsStore settings @@ -245,14 +266,6 @@ private ProjectSettingsStore settings private RenderRuntime rendering => m_rendering ?? throw new InvalidOperationException("The Player rendering runtime is not initialized."); - private static RenderViewport CreatePresentationViewport( - GamePresentationSettings presentation, - RenderPresentationSize size - ) { - GamePresentationViewport viewport = presentation.CalculateViewport(size.width, size.height); - return new RenderViewport(viewport.x, viewport.y, viewport.width, viewport.height); - } - private void InitializeRuntime( GameRuntimeManifest manifest, PlayerLaunchOptions options @@ -264,46 +277,67 @@ PlayerLaunchOptions options { kind = RuntimeSessionKind.Player, jobExecutionMode = options.jobExecutionMode, - applicationId = manifest.applicationId, + applicationID = manifest.applicationId, contentStore = m_content, createLogSink = options.createLogSink is null ? null : id => options.createLogSink(manifest, id), createSubsystems = owner => { - using ContentReadLease document = m_content!.Acquire(new ContentKey(SettingsFileNames.project)); + using ContentReadLease document = m_content!.Acquire(new ContentKey(SettingsFileNames.C_PROJECT)); using Stream documentStream = document.OpenRead(); - byte[] documentBytes = new byte[checked((int)document.entry.length)]; + var documentBytes = new byte[checked((int)document.entry.length)]; documentStream.ReadExactly(documentBytes); m_settings = new ProjectSettingsStore( new ReadOnlyByteDocumentStore(document.entry.key.value!, documentBytes), - m_engine.types, m_engine.serialization, new ProjectId(manifest.applicationId), - AssetSerializationContext.Create(owner.assets)); + m_engine.types, + m_engine.serialization, + new ProjectID(manifest.applicationId), + AssetSerializationContext.Create(owner.assets) + ); settings.SetContributors(manifest.CreateSettingContributors()); settings.RebuildCurrent(); - if (!string.Equals(settings.projectId.value, manifest.applicationId, StringComparison.Ordinal)) + if (!string.Equals(settings.projectID.value, manifest.applicationId, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest and Project Settings identities do not match."); - return DefaultEngine.CreateSessionSubsystems(new EngineSessionComposition( - owner, adapters, adapterSelection, inputSource, owner.assets, - () => settings.Get(AudioProjectSettings.settingId), - () => options.createStorage(manifest))); + } + return DefaultEngine.CreateSessionSubsystems( + new EngineSessionComposition( + owner, + adapters, + adapterSelection, + inputSource, + owner.assets, + () => settings.Get(AudioProjectSettings.settingID), + () => options.createStorage(manifest) + ) + ); } }); - GamePresentationSettings presentation = settings.Get(GamePresentationSettings.settingId); + GamePresentationSettings presentation = settings.Get(GamePresentationSettings.settingID); AudioRuntime audio = session.subsystems .GetRequiredSubsystem(); AnimationRuntime animation = session.subsystems .GetRequiredSubsystem(); InputRuntime inputRuntime = session.subsystems .GetRequiredSubsystem(); - m_rendering = new RenderRuntime(m_engine.types, renderDevice, m_renderDiagnostics, - targetArtifacts: new ContentRenderTargetArtifactProvider(m_content!, m_engine.serialization, - AssetSerializationContext.Create(session.assets)), + m_rendering = new RenderRuntime( + m_engine.types, + renderDevice, + m_renderDiagnostics, + targetArtifacts: new ContentRenderTargetArtifactProvider( + m_content!, + m_engine.serialization, + AssetSerializationContext.Create(session.assets) + ), contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), primaryPresentationViewportProvider: size => CreatePresentationViewport(presentation, size), inputSnapshotProvider: () => inputRuntime.snapshot, - primaryInputSurfaceSizeProvider: () => primaryWindow.width > 0 && primaryWindow.height > 0 - ? new RenderPresentationSize(primaryWindow.width, primaryWindow.height) : null, - compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider( - adapterSelection.rendering)); + primaryInputSurfaceSizeProvider: () => ( + primaryWindow.width > 0 && primaryWindow.height > 0 + ? new RenderPresentationSize(primaryWindow.width, primaryWindow.height) + : null + ), + compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider(adapterSelection.rendering) + ); UseHostPipeline(m_engine.CreateHostPipeline(DefaultEngine.CreateHostSubsystems(m_rendering))); using (settings.EnterExecutionScope()) using (AnimationExecutionContext.EnterScope(animation)) @@ -311,14 +345,19 @@ PlayerLaunchOptions options using (rendering.EnterExecutionScope()) using (session.EnterExecutionScope()) { - SceneAsset startupAsset = session.assets.Load( - AssetPath.Parse(manifest.startupScene)); - session.scenes.LoadScene(startupAsset.Instantiate( - m_engine.serialization, - session.assets)); + SceneAsset startupAsset = session.assets.Load(AssetPath.Parse(manifest.startupScene)); + session.scenes.LoadScene(startupAsset.Instantiate(m_engine.serialization, session.assets)); } } + private static RenderViewport CreatePresentationViewport( + GamePresentationSettings presentation, + RenderPresentationSize size + ) { + GamePresentationViewport viewport = presentation.CalculateViewport(size.width, size.height); + return new RenderViewport(viewport.x, viewport.y, viewport.width, viewport.height); + } + private static void ActivateRuntimeModules( IPlayerModuleActivator activator, ModuleHost modules, @@ -329,16 +368,21 @@ GameCodeDeployment deployment ArgumentNullException.ThrowIfNull(deployment); activator.Activate(modules, deployment); string[] activeNames = modules.modules.Select(static module => module.moduleName) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); string[] expectedNames = deployment.modules.Select(static module => module.name) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (!activeNames.SequenceEqual(expectedNames, StringComparer.Ordinal)) + { throw new InvalidOperationException("The frozen runtime code generation was not activated completely."); + } } private sealed class SmokeDiagnostics : IDiagnosticSink { internal readonly List errors = []; + /// /// Records errors from the current diagnostic report. /// @@ -348,15 +392,20 @@ private sealed class SmokeDiagnostics : IDiagnosticSink public void Replace(DiagnosticReport report) { foreach (Diagnostic diagnostic in report.diagnostics) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { errors.Add(report.source.id + "/" + diagnostic.code + ": " + diagnostic.message); + } + } } + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// /// /// The source value or location read by this operation. /// - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} } } diff --git a/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs b/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs index cfe87c5e2..65a21350e 100644 --- a/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs +++ b/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs @@ -21,10 +21,6 @@ public static class PlayerApplication /// /// Zero after orderly shutdown; startup, execution and retirement failures propagate. /// - /// - /// Hosts must preserve their owner thread across asynchronous startup and frame callbacks using - /// their synchronization context. A blocking host can use OwnerThreadExecution.Run. - /// /// /// Options or a required host service is null. /// @@ -37,6 +33,10 @@ public static class PlayerApplication /// /// A host factory does not provide its required product, or runtime startup or retirement fails. /// + /// + /// Hosts must preserve their owner thread across asynchronous startup and frame callbacks using + /// their synchronization context. A blocking host can use OwnerThreadExecution.Run. + /// public static async Task RunAsync( PlayerLaunchOptions options, CancellationToken cancellationToken = default diff --git a/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs b/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs index 0b9ab0bae..f77da2683 100644 --- a/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs +++ b/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs @@ -8,7 +8,7 @@ namespace Inno.Player.Runtime; /// public sealed class PlayerCommandLineOptions { - private PlayerCommandLineOptions() { } + private PlayerCommandLineOptions() {} /// /// Gets an optional positive bounded run length. @@ -48,6 +48,7 @@ public static PlayerCommandLineOptions Parse(string[] arguments) windowVisible = visible }; } + private static void ParseValues( string[] arguments, out int? smokeFrameLimit, @@ -61,13 +62,15 @@ out bool windowVisible for (int index = 0; index < arguments.Length; index += 2) { if (index + 1 >= arguments.Length) + { throw Usage(); + } if (string.Equals(arguments[index], "--smoke-frames", StringComparison.Ordinal)) { if (smokeFrameLimit is not null || !int.TryParse(arguments[index + 1], out int frameCount) - || frameCount <= 0) - { + || frameCount <= 0 + ) { throw Usage(); } smokeFrameLimit = frameCount; @@ -76,14 +79,18 @@ out bool windowVisible if (string.Equals(arguments[index], "--graphics-api", StringComparison.Ordinal)) { if (graphicsApi is not null || !TryParseGraphicsApi(arguments[index + 1], out GraphicsApi api)) + { throw Usage(); + } graphicsApi = api; continue; } if (string.Equals(arguments[index], "--window-visible", StringComparison.Ordinal)) { if (visibilitySpecified || !bool.TryParse(arguments[index + 1], out windowVisible)) + { throw Usage(); + } visibilitySpecified = true; continue; } @@ -102,16 +109,18 @@ out GraphicsApi api } api = value.ToLowerInvariant() switch { - "d3d11" => GraphicsApi.Direct3D11, - "d3d12" => GraphicsApi.Direct3D12, - "metal" => GraphicsApi.Metal, - "vulkan" => GraphicsApi.Vulkan, - "opengl" => GraphicsApi.OpenGL, + "d3d11" => GraphicsApi.direct3D11, + "d3d12" => GraphicsApi.direct3D12, + "metal" => GraphicsApi.metal, + "vulkan" => GraphicsApi.vulkan, + "opengl" => GraphicsApi.openGL, _ => GraphicsApi.TryParse(value, out GraphicsApi parsed) ? parsed : default }; - return api.isValid && api != GraphicsApi.Noop; + return api.isValid && api != GraphicsApi.noop; } - private static ArgumentException Usage() => new( - "Usage: Player [--graphics-api ] [--window-visible ] [--smoke-frames ]."); + private static ArgumentException Usage() + => new( + "Usage: Player [--graphics-api ] [--window-visible ] [--smoke-frames ]." + ); } diff --git a/src/composition/player/Inno.Player.Runtime/PlayerLaunchOptions.cs b/src/composition/player/Inno.Player.Runtime/PlayerLaunchOptions.cs index 8c017f56c..6fbd8d8c7 100644 --- a/src/composition/player/Inno.Player.Runtime/PlayerLaunchOptions.cs +++ b/src/composition/player/Inno.Player.Runtime/PlayerLaunchOptions.cs @@ -49,7 +49,7 @@ public sealed class PlayerLaunchOptions /// /// Gets the optional host factory transferring a session log sink to the game session. /// - public Func? createLogSink { get; init; } + public Func? createLogSink { get; init; } /// /// Gets the strategy that activates the frozen deployment's managed modules. diff --git a/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs b/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs index 4b3dba8a2..40b53e0ff 100644 --- a/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs +++ b/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs @@ -41,7 +41,9 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!advanceFrame()) + { return ValueTask.CompletedTask; + } } } } diff --git a/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs b/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs index 50db2552c..4d0881fef 100644 --- a/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs +++ b/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs @@ -22,7 +22,8 @@ public sealed class ScheduledShellFrameDriver : IShellFrameDriver /// public ScheduledShellFrameDriver(Func nextFrame) { - m_nextFrame = nextFrame ?? throw new ArgumentNullException(nameof(nextFrame)); + ArgumentNullException.ThrowIfNull(nextFrame); + m_nextFrame = nextFrame; } /// @@ -59,7 +60,9 @@ CancellationToken cancellationToken await m_nextFrame(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (!advanceFrame()) + { return; + } } } } diff --git a/src/composition/shell/Inno.Shell/Shell.cs b/src/composition/shell/Inno.Shell/Shell.cs index b0a35f0ae..f6e1f9455 100644 --- a/src/composition/shell/Inno.Shell/Shell.cs +++ b/src/composition/shell/Inno.Shell/Shell.cs @@ -60,12 +60,13 @@ protected Shell( IAdapterCatalog adapterCatalog, ShellOptions options ) { - m_adapterCatalog = adapterCatalog ?? throw new ArgumentNullException(nameof(adapterCatalog)); + ArgumentNullException.ThrowIfNull(adapterCatalog); + m_adapterCatalog = adapterCatalog; ArgumentNullException.ThrowIfNull(options); m_adapterSelection = options.adapters; m_suspendWhenHidden = options.suspendWhenHidden; this.options = options; - framePacing = new FramePacingOptions { verticalSync = options.verticalSync }; + this.framePacing = new FramePacingOptions { verticalSync = options.verticalSync }; } /// @@ -142,12 +143,14 @@ public async Task RunAsync( { state = ShellState.Faulted; failure = failure is null - ? stoppingFailure - : new AggregateException("Shell execution and stopping both failed.", failure, stoppingFailure); + ? stoppingFailure + : new AggregateException("Shell execution and stopping both failed.", failure, stoppingFailure); } } if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } return 0; } @@ -157,18 +160,28 @@ public async Task RunAsync( public void Dispose() { if (m_disposed) + { return; + } List? failures = null; Release(NotifyStopping, ref failures); Release(RetireProductResources, ref failures); if (m_renderDevice is not null) + { Release(m_renderDevice.Dispose, ref failures); + } if (m_inputSource is not null) + { Release(m_inputSource.Dispose, ref failures); + } if (m_primaryWindow is not null) + { Release(m_primaryWindow.Dispose, ref failures); + } if (m_platformApplication is not null) + { Release(m_platformApplication.Dispose, ref failures); + } m_disposed = true; if (failures is not null) { @@ -240,7 +253,9 @@ protected void UseHostPipeline(RuntimeSubsystemPipeline pipeline) { ArgumentNullException.ThrowIfNull(pipeline); if (m_subsystems is not null) + { throw new InvalidOperationException("The Shell already has a host subsystem pipeline."); + } m_subsystems = pipeline; } @@ -254,7 +269,9 @@ protected void InitializeAdapterResources() { ObjectDisposedException.ThrowIf(m_disposed, this); if (state != ShellState.Created) + { throw new InvalidOperationException("The composition shell cannot initialize adapter resources in its current state."); + } m_adapterSelection.Validate(m_adapterCatalog); try @@ -264,7 +281,8 @@ protected void InitializeAdapterResources() m_inputSource = m_adapterCatalog.input.CreateEventSource( m_adapterSelection.input, m_primaryWindow, - acceptAllWindows: false); + acceptAllWindows: false + ); m_renderDevice = m_adapterCatalog.rendering.CreateDevice( m_adapterSelection.rendering, new RenderingBackendOptions @@ -274,7 +292,8 @@ protected void InitializeAdapterResources() verticalSync = options.verticalSync, sRgbBackbuffer = options.sRgbBackbuffer, forceSingleThreaded = options.forceSingleThreadedRendering - }); + } + ); UpdatePrimaryPresentationSize(); state = ShellState.Ready; } @@ -283,16 +302,24 @@ protected void InitializeAdapterResources() state = ShellState.Faulted; List? failures = null; if (m_renderDevice is not null) + { Release(m_renderDevice.Dispose, ref failures); + } m_renderDevice = null; if (m_inputSource is not null) + { Release(m_inputSource.Dispose, ref failures); + } m_inputSource = null; if (m_primaryWindow is not null) + { Release(m_primaryWindow.Dispose, ref failures); + } m_primaryWindow = null; if (m_platformApplication is not null) + { Release(m_platformApplication.Dispose, ref failures); + } m_platformApplication = null; if (failures is not null) { @@ -311,9 +338,7 @@ protected void InitializeAdapterResources() /// /// Runs once immediately before the common event and frame loop starts. /// - protected virtual void OnStarting() - { - } + protected virtual void OnStarting() {} /// /// Receives one backend-neutral platform event after shared input routing and close evaluation. @@ -321,9 +346,7 @@ protected virtual void OnStarting() /// /// Event produced by the active platform adapter. /// - protected virtual void OnEvent(Event evnt) - { - } + protected virtual void OnEvent(Event evnt) {} /// /// Receives an effective application suspension change at an event-pump safety point. @@ -332,7 +355,7 @@ protected virtual void OnEvent(Event evnt) /// /// Whether product frames and their clock are suspended after the change. /// - protected virtual void OnSuspensionChanged(bool isSuspended) { } + protected virtual void OnSuspensionChanged(bool isSuspended) {} /// /// Determines whether one event requests orderly product shutdown. @@ -345,7 +368,7 @@ protected virtual void OnSuspensionChanged(bool isSuspended) { } /// protected virtual bool ShouldExit(Event evnt) => evnt is ApplicationQuitEvent - || evnt is WindowCloseEvent close && close.windowId == primaryWindow.windowId; + || evnt is WindowCloseEvent close && close.windowID == primaryWindow.windowID; /// /// Advances one product-specific frame after all pending platform events have been dispatched. @@ -361,7 +384,7 @@ protected virtual bool ShouldExit(Event evnt) /// /// The current application frame. /// - protected virtual void OnPresentation(ShellFrame frame) { } + protected virtual void OnPresentation(ShellFrame frame) {} /// /// Receives the final frame count only when a bounded smoke run reaches its requested frame limit. @@ -370,35 +393,37 @@ protected virtual void OnPresentation(ShellFrame frame) { } /// /// Number of product frames completed by the smoke run. /// - protected virtual void OnSmokeCompleted(int frameCount) - { - } + protected virtual void OnSmokeCompleted(int frameCount) {} /// /// Runs once when the main loop is stopping while all product and adapter resources remain alive. /// - protected virtual void OnStopping() - { - } + protected virtual void OnStopping() {} /// /// Releases resources owned by the derived product before common adapter resources are destroyed. /// - protected virtual void DisposeProductResources() - { - } + protected virtual void DisposeProductResources() {} private bool AdvanceFrame() { if (m_exitRequested || primaryWindow.isClosed) + { return false; + } PumpEvents(); if (m_exitRequested || primaryWindow.isClosed) + { return false; + } if (state == ShellState.Running) + { DrawFrame(); + } else if (m_allowBlockingPacing) + { Thread.Sleep(10); + } return !m_exitRequested && !primaryWindow.isClosed; } @@ -407,27 +432,35 @@ private void PrepareRun( bool allowBlockingPacing ) { ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_platformApplication is null || m_primaryWindow is null || - m_inputSource is null || m_renderDevice is null) - { + if (m_platformApplication is null || m_primaryWindow is null + || m_inputSource is null || m_renderDevice is null + ) { throw new InvalidOperationException("The composition shell adapter resources are not initialized."); } if (smokeFrameLimit is <= 0) + { throw new ArgumentOutOfRangeException(nameof(smokeFrameLimit)); + } if (m_hasRun || state != ShellState.Ready) + { throw new InvalidOperationException("A composition shell can run only once."); + } m_hasRun = true; m_timer = Stopwatch.StartNew(); m_smokeFrameLimit = smokeFrameLimit; m_allowBlockingPacing = allowBlockingPacing; } - private void Redraw(uint windowId) + private void Redraw(uint windowID) { if (state != ShellState.Running || !hasCompletedFrame || m_frameActive || m_exitRequested || primaryWindow.isClosed) + { return; - if (windowId == primaryWindow.windowId) + } + if (windowID == primaryWindow.windowID) + { UpdatePrimaryPresentationSize(); + } DrawFrame(); } @@ -445,8 +478,15 @@ private void DrawFrame() double totalTime = m_timer!.Elapsed.TotalSeconds; float deltaTime = Math.Max(0f, (float)(totalTime - m_previousTime)); var frame = new ShellFrame(m_frameCount, totalTime, deltaTime); - var runtimeFrame = new RuntimeFrame(m_frameCount, (float)totalTime, (float)totalTime, - deltaTime, deltaTime, 1f, false); + var runtimeFrame = new RuntimeFrame( + m_frameCount, + (float)totalTime, + (float)totalTime, + deltaTime, + deltaTime, + 1f, + false + ); try { m_subsystems?.BeginFrame(runtimeFrame); @@ -454,9 +494,13 @@ private void DrawFrame() m_subsystems?.Update(runtimeFrame); m_subsystems?.LateUpdate(runtimeFrame); if (m_subsystems is not null) + { m_subsystems.RenderFrame(runtimeFrame, () => OnPresentation(frame)); + } else + { OnPresentation(frame); + } } finally { @@ -466,13 +510,17 @@ private void DrawFrame() m_frameCount++; hasCompletedFrame = true; if (m_smokeFrameLimit.HasValue && m_frameCount >= m_smokeFrameLimit.Value) + { RequestExit(); + } int maximumRate = framePacing.maximumFrameRate; if (m_allowBlockingPacing && maximumRate > 0) { double remaining = 1d / maximumRate - (m_timer.Elapsed.TotalSeconds - totalTime); if (remaining > 0d) + { Thread.Sleep(TimeSpan.FromSeconds(remaining)); + } } } finally @@ -484,7 +532,9 @@ private void DrawFrame() private void CompleteSmokeRun() { if (m_smokeFrameLimit.HasValue && m_frameCount >= m_smokeFrameLimit.Value) + { OnSmokeCompleted(m_frameCount); + } } private void PumpEvents() @@ -492,14 +542,22 @@ private void PumpEvents() while (platformApplication.PollEvent(out Event? evnt)) { if (evnt is null) + { continue; + } ApplySuspension(evnt); if (state == ShellState.Suspended && evnt is KeyEvent or MouseEvent or TextInputEvent) + { continue; + } if (evnt is not ApplicationSuspensionChangedEvent) + { inputSource.ProcessEvent(evnt); - if (evnt is WindowResizeEvent resize && resize.windowId == primaryWindow.windowId) + } + if (evnt is WindowResizeEvent resize && resize.windowID == primaryWindow.windowID) + { UpdatePrimaryPresentationSize(); + } if (ShouldExit(evnt)) { RequestExit(); @@ -529,7 +587,7 @@ private void ApplySuspension(Event evnt) case ApplicationSuspensionChangedEvent application: m_applicationSuspended = application.isSuspended; break; - case WindowVisibilityChangedEvent window when window.windowId == primaryWindow.windowId: + case WindowVisibilityChangedEvent window when window.windowID == primaryWindow.windowID: m_primaryWindowHidden = !window.isVisible; break; default: @@ -538,7 +596,9 @@ private void ApplySuspension(Event evnt) UpdatePrimaryPresentationSize(); bool suspended = m_applicationSuspended || (m_suspendWhenHidden && m_primaryWindowHidden); if (suspended == (state == ShellState.Suspended)) + { return; + } if (suspended) { m_timer!.Stop(); @@ -559,13 +619,17 @@ private void UpdatePrimaryPresentationSize() int height = primaryWindow.pixelHeight; renderDevice.SetPrimaryPresentationSize( !primaryWindow.isClosed && !m_primaryWindowHidden && !m_applicationSuspended && width > 0 && height > 0 - ? new RenderPresentationSize(width, height) : null); + ? new RenderPresentationSize(width, height) + : null + ); } private void NotifyStopping() { if (m_stoppingNotified) + { return; + } m_stoppingNotified = true; bool faulted = state == ShellState.Faulted; state = ShellState.Stopping; diff --git a/src/composition/shell/Inno.Shell/ShellState.cs b/src/composition/shell/Inno.Shell/ShellState.cs index 1ed238822..507266e2e 100644 --- a/src/composition/shell/Inno.Shell/ShellState.cs +++ b/src/composition/shell/Inno.Shell/ShellState.cs @@ -9,37 +9,30 @@ public enum ShellState /// Adapter resources have not been initialized. /// Created, - /// /// Adapter resources are ready for the single permitted run. /// Ready, - /// /// Platform events and product frames are advancing. /// Running, - /// /// Platform events continue while product frames and their clock are suspended. /// Suspended, - /// /// The stopping callback is executing while resources remain alive. /// Stopping, - /// /// The run ended or was canceled and the stopping callback completed. /// Stopped, - /// /// Initialization, execution, or retirement failed; another run is prohibited. /// Faulted, - /// /// All owned resources were released successfully. /// diff --git a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs index 098c4d0fe..551b23f2f 100644 --- a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs +++ b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -14,12 +13,12 @@ namespace Inno.Animation.Assets; [AssetImporter("inno.animation.clip")] public sealed partial class AnimationClipImporter : AssetImporter { - private static readonly IReadOnlyList S_EXTENSIONS = [".ianim"]; + private static readonly IReadOnlyList EXTENSIONS = [".ianim"]; /// /// Gets the current structured animation source extension. /// - public override IReadOnlyList supportedExtensions => S_EXTENSIONS; + public override IReadOnlyList supportedExtensions => EXTENSIONS; /// /// Imports one validated structured animation clip. @@ -43,7 +42,8 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); AnimationClipSource source = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); var clip = new AnimationClipAsset { duration = source.duration, @@ -52,10 +52,7 @@ CancellationToken cancellationToken }; clip.Validate(); output.SetAsset(clip); - await output.WriteArtifactAsync( - "runtime", - context.sourceBytes, - cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } /// diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs index e8b980613..ecb8d3e42 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs @@ -30,7 +30,8 @@ public AnimationBindingRuntime( IDiagnosticReporter diagnostics ) { ArgumentNullException.ThrowIfNull(types); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(diagnostics); + m_diagnostics = diagnostics; m_registry = new Registry(types); try { @@ -59,22 +60,30 @@ public void Apply(ReadOnlySpan samples) { ObjectDisposedException.ThrowIf(m_disposed, this); if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Animation bindings must run on their owner thread."); + } Snapshot snapshot = m_registry.snapshot; var issues = new Dictionary<(string, Guid), Diagnostic>(); foreach (AnimationSample sample in samples) { if (sample.target.isSamplingOnly) + { continue; + } string? message = null; if (!snapshot.providers.TryGetValue((sample.binding, sample.value.kind), out AnimationBindingProvider? provider)) + { message = "The animation binding provider is missing; the playback remains available."; + } else { try { if (!provider.TryApply(sample.target, sample.value)) + { message = "The animation destination is missing or incompatible."; + } } catch (Exception exception) { @@ -82,9 +91,15 @@ public void Apply(ReadOnlySpan samples) } } if (message is not null) - issues[(sample.binding.value, sample.target.persistentId)] = new Diagnostic( - "animation.binding.unavailable", message, DiagnosticSeverity.Warning, - sample.binding.value, sample.target.persistentId); + { + issues[(sample.binding.value, sample.target.persistentID)] = new Diagnostic( + "animation.binding.unavailable", + message, + DiagnosticSeverity.Warning, + sample.binding.value, + sample.target.persistentID + ); + } } m_diagnostics.Replace(issues.Values); } @@ -95,7 +110,9 @@ public void Apply(ReadOnlySpan samples) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_registry.Dispose(); m_diagnostics.Replace([]); @@ -123,13 +140,24 @@ protected override Snapshot Build(TypeCacheSnapshot types) foreach (TypeRef reference in types.GetTypesWithAttribute()) { Type type = reference.Resolve(types); - AnimationBindingProviderAttribute declaration = types.GetAttribute(reference, false)!; + AnimationBindingProviderAttribute declaration = types.GetAttribute( + reference, + false + )!; if (type.IsAbstract || type.ContainsGenericParameters || !typeof(AnimationBindingProvider).IsAssignableFrom(type) - || !types.CanCreateInstance(reference)) - throw new InvalidOperationException($"Animation provider '{declaration.id}' requires a concrete public parameterless implementation."); - var key = (declaration.bindingId, declaration.kind); + || !types.CanCreateInstance(reference) + ) { + throw new InvalidOperationException( + $"Animation provider '{declaration.id}' requires a concrete public parameterless implementation." + ); + } + (AnimationBindingID bindingID, AnimationValueKind kind) key = (declaration.bindingID, declaration.kind); if (!ids.Add(declaration.id) || result.providers.ContainsKey(key)) - throw new InvalidOperationException($"Animation provider '{declaration.id}' duplicates an extension ID or binding protocol."); + { + throw new InvalidOperationException( + $"Animation provider '{declaration.id}' duplicates an extension ID or binding protocol." + ); + } result.providers.Add(key, CreateExtension(type)); } return result; @@ -152,8 +180,6 @@ protected override Snapshot Build(TypeCacheSnapshot types) private sealed class Snapshot : IDisposable { - internal Dictionary<(AnimationBindingId, AnimationValueKind), AnimationBindingProvider> providers { get; } = []; - /// /// Attempts to release every provider without retaining failed instances. /// @@ -173,7 +199,11 @@ public void Dispose() } providers.Clear(); if (failures is not null) + { throw new AggregateException("Animation provider retirement failed.", failures); + } } + + internal Dictionary<(AnimationBindingID, AnimationValueKind), AnimationBindingProvider> providers { get; } = []; } } diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs index 61250c6a4..60578449e 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs @@ -6,10 +6,13 @@ internal sealed class AnimationClipSnapshot { private AnimationClipSnapshot(AnimationClipAsset clip) { - duration = clip.duration; - tracks = clip.tracks.Select(static track => new AnimationTrack( - track.bindingId, track.interpolation, track.keyframes)).ToArray(); - events = clip.events.Select(static marker => new AnimationEventMarker + this.duration = clip.duration; + this.tracks = clip.tracks.Select(static track => new AnimationTrack( + track.bindingId, + track.interpolation, + track.keyframes + )).ToArray(); + this.events = clip.events.Select(static marker => new AnimationEventMarker { time = marker.time, eventId = marker.eventId, diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs index 9f341b4d1..0b5b06880 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs @@ -1,10 +1,9 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; - using Inno.Core.Events; +using Inno.Runtime.Contracts; namespace Inno.Animation.Runtime; @@ -21,23 +20,9 @@ public sealed class AnimationRuntime : RuntimeSubsystem, IAnimationService private readonly IAnimationBindingSink m_bindings; private readonly EventDispatcher m_events; private readonly uint m_runtimeGeneration; - private bool m_disposed; private readonly int m_maxPlaybacks; + private bool m_disposed; private long m_rejectedPlaybacks; - /// - /// Captures snapshots and binds service façades. - /// - /// - /// The variable frame timing. - /// - protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(AnimationExecutionContext.EnterScope(this)); - /// - /// Advances domain state on the variable clock. - /// - /// - /// The variable frame timing. - /// - protected override void OnUpdate(RuntimeFrame frame) => Update(frame.deltaTime, frame.unscaledDeltaTime); /// /// Creates one isolated animation runtime generation. @@ -54,21 +39,36 @@ public sealed class AnimationRuntime : RuntimeSubsystem, IAnimationService public AnimationRuntime( EventDispatcher events, IAnimationBindingSink bindings, - int maxPlaybacks = 16384 + int maxPlaybacks = 16_384 ) { - m_events = events ?? throw new ArgumentNullException(nameof(events)); - m_bindings = bindings ?? throw new ArgumentNullException(nameof(bindings)); + ArgumentNullException.ThrowIfNull(events); + ArgumentNullException.ThrowIfNull(bindings); + m_events = events; + m_bindings = bindings; m_runtimeGeneration = m_handles.generation; ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxPlaybacks); m_maxPlaybacks = maxPlaybacks; } + /// + /// Gets active animation playback slots. + /// + public int playbackCount => m_playbacks.Count - m_freeSlots.Count; + + /// + /// Gets playback admissions rejected by finite capacity. + /// + public long rejectedPlaybacks => m_rejectedPlaybacks; + /// /// Starts one clip with the runtime's default playback policy. /// /// /// Valid clip to sample until completion or explicit stop. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// A generation-checked handle owned by this runtime. /// @@ -81,14 +81,10 @@ public AnimationRuntime( /// /// Thrown when the clip is structurally invalid. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target - ) - => Play(clip, target, AnimationPlayOptions.defaultValue); + ) => Play(clip, target, AnimationPlayOptions.defaultValue); /// /// Starts one clip with an explicit clock, looping, speed, layer, and blend policy. @@ -96,6 +92,9 @@ AnimationTarget target /// /// Valid clip to sample until completion or explicit stop. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback options validated before a runtime slot is allocated. /// @@ -114,9 +113,6 @@ AnimationTarget target /// /// Thrown when the clip is structurally invalid. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, @@ -125,7 +121,9 @@ AnimationPlayOptions options ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(clip); if (!target.isValid) + { throw new ArgumentException("An explicit animation destination is required.", nameof(target)); + } clip.Validate(); ValidateOptions(options); if (m_playbacks.Count - m_freeSlots.Count >= m_maxPlaybacks) @@ -147,22 +145,16 @@ AnimationPlayOptions options } var playback = new Playback(snapshot, target, options, generation); if (slot == m_playbacks.Count) + { m_playbacks.Add(playback); + } else + { m_playbacks[slot] = playback; + } return m_handles.Create(slot, generation); } - /// - /// Gets active animation playback slots. - /// - public int playbackCount => m_playbacks.Count - m_freeSlots.Count; - - /// - /// Gets playback admissions rejected by finite capacity. - /// - public long rejectedPlaybacks => m_rejectedPlaybacks; - /// /// Stops and retires one live playback slot. /// @@ -175,8 +167,10 @@ AnimationPlayOptions options public bool Stop(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback)) + { return false; - var identity = m_handles.Decode(handle); + } + (int slot, uint generation) identity = m_handles.Decode(handle); Retire(identity.slot, playback); return true; } @@ -193,7 +187,9 @@ public bool Stop(AnimationPlaybackHandle handle) public bool Pause(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback) || playback.state == AnimationPlaybackState.Paused) + { return false; + } playback.state = AnimationPlaybackState.Paused; return true; } @@ -210,7 +206,9 @@ public bool Pause(AnimationPlaybackHandle handle) public bool Resume(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback) || playback.state == AnimationPlaybackState.Playing) + { return false; + } playback.state = AnimationPlaybackState.Playing; return true; } @@ -235,9 +233,13 @@ public bool Seek( float time ) { if (!float.IsFinite(time)) + { throw new ArgumentOutOfRangeException(nameof(time)); + } if (!TryGetPlayback(handle, out Playback? playback)) + { return false; + } playback.time = Math.Clamp(time, 0f, playback.clip.duration); return true; } @@ -288,53 +290,73 @@ float unscaledDeltaTime ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!float.IsFinite(scaledDeltaTime) || scaledDeltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(scaledDeltaTime)); + } if (!float.IsFinite(unscaledDeltaTime) || unscaledDeltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(unscaledDeltaTime)); + } - var samples = new Dictionary<(AnimationTarget target, AnimationBindingId binding), BlendAccumulator>(); + var samples = new Dictionary<(AnimationTarget target, AnimationBindingID binding), BlendAccumulator>(); for (int slot = 0; slot < m_playbacks.Count; slot++) { Playback? playback = m_playbacks[slot]; if (playback is null) + { continue; - AnimationPlaybackHandle handle = m_handles.Create( - slot, - playback.generation); + } + AnimationPlaybackHandle handle = m_handles.Create(slot, playback.generation); float previousTime = playback.time; if (playback.state == AnimationPlaybackState.Playing) { float delta = playback.options.clock == AnimationClock.Scaled - ? scaledDeltaTime - : unscaledDeltaTime; - bool completed = Advance( - handle, - playback, - previousTime, - delta * playback.options.speed); + ? scaledDeltaTime + : unscaledDeltaTime; + bool completed = Advance(handle, playback, previousTime, delta * playback.options.speed); Sample(playback, samples); if (completed) + { Retire(slot, playback); + } continue; } Sample(playback, samples); } AnimationSample[] output = samples - .OrderBy(static pair => pair.Key.target.persistentId) + .OrderBy(static pair => pair.Key.target.persistentID) .ThenBy(static pair => pair.Key.binding.value, StringComparer.Ordinal) .Select(static pair => new AnimationSample(pair.Key.target, pair.Key.binding, pair.Value.Complete())) .ToArray(); m_bindings.Apply(output); } + /// + /// Captures snapshots and binds service façades. + /// + /// + /// The variable frame timing. + /// + protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(AnimationExecutionContext.EnterScope(this)); + + /// + /// Advances domain state on the variable clock. + /// + /// + /// The variable frame timing. + /// + protected override void OnUpdate(RuntimeFrame frame) => Update(frame.deltaTime, frame.unscaledDeltaTime); + /// /// Releases every live playback in this runtime generation. /// protected override void OnStop() { if (m_disposed) + { return; + } m_disposed = true; m_playbacks.Clear(); m_slotGenerations.Clear(); @@ -348,7 +370,9 @@ private bool Advance( float delta ) { if (delta <= 0f) + { return false; + } float duration = playback.clip.duration; float total = previousTime + delta; if (!playback.options.loop && total >= duration) @@ -374,7 +398,9 @@ float delta remaining -= segment; cursor += segment; if (cursor >= duration) + { cursor = 0f; + } } playback.time = cursor; return false; @@ -391,33 +417,58 @@ float endInclusive AnimationEventMarker marker = clip.events[index]; if (marker.time > startExclusive && marker.time <= endInclusive) { - m_events.Enqueue(new AnimationMarkerEvent( - handle, - marker.eventId, - marker.payload)); + m_events.Enqueue(new AnimationMarkerEvent(handle, marker.eventId, marker.payload)); } } } + private bool TryGetPlayback( + AnimationPlaybackHandle handle, + [NotNullWhen(true)] out Playback? playback + ) { + playback = null; + (int slot, uint generation) identity = m_handles.Decode(handle); + if (m_disposed || !handle.isValid || handle.runtimeGeneration != m_runtimeGeneration + || identity.slot < 0 || identity.slot >= m_playbacks.Count + ) { + return false; + } + playback = m_playbacks[identity.slot]; + return playback is not null && playback.generation == identity.generation; + } + + private void Retire( + int slot, + Playback playback + ) { + uint next = unchecked(playback.generation + 1); + if (next == 0) + { + next = 1; + } + m_slotGenerations[slot] = next; + m_playbacks[slot] = null; + m_freeSlots.Push(slot); + } + private static void Sample( Playback playback, - IDictionary<(AnimationTarget target, AnimationBindingId binding), BlendAccumulator> samples + IDictionary<(AnimationTarget target, AnimationBindingID binding), BlendAccumulator> samples ) { if (playback.options.weight <= 0f) + { return; + } for (int index = 0; index < playback.clip.tracks.Length; index++) { AnimationTrack track = playback.clip.tracks[index]; - var binding = new AnimationBindingId(track.bindingId); - var destination = (playback.target, binding); + var binding = new AnimationBindingID(track.bindingId); + (AnimationTarget target, AnimationBindingID binding) destination = (playback.target, binding); AnimationValue value = SampleTrack(track, playback.time); - if (!samples.TryGetValue(destination, out BlendAccumulator accumulator) || - playback.options.layer > accumulator.layer) - { - samples[destination] = new BlendAccumulator( - playback.options.layer, - value, - playback.options.weight); + if (!samples.TryGetValue(destination, out BlendAccumulator accumulator) + || playback.options.layer > accumulator.layer + ) { + samples[destination] = new BlendAccumulator(playback.options.layer, value, playback.options.weight); continue; } if (playback.options.layer == accumulator.layer) @@ -434,56 +485,40 @@ float time ) { AnimationKeyframe[] keys = track.keyframes; if (time <= keys[0].time) + { return keys[0].value; + } for (int index = 1; index < keys.Length; index++) { if (time > keys[index].time) + { continue; + } AnimationKeyframe left = keys[index - 1]; AnimationKeyframe right = keys[index]; if (track.interpolation == AnimationInterpolation.Step || right.time <= left.time) + { return left.value; + } return AnimationSampling.Interpolate( left.value, right.value, - (time - left.time) / (right.time - left.time)); + (time - left.time) / (right.time - left.time) + ); } return keys[^1].value; } - private bool TryGetPlayback( - AnimationPlaybackHandle handle, - [NotNullWhen(true)] out Playback? playback - ) { - playback = null; - var identity = m_handles.Decode(handle); - if (m_disposed || !handle.isValid || handle.runtimeGeneration != m_runtimeGeneration || - identity.slot < 0 || identity.slot >= m_playbacks.Count) - { - return false; - } - playback = m_playbacks[identity.slot]; - return playback is not null && playback.generation == identity.generation; - } - - private void Retire( - int slot, - Playback playback - ) { - uint next = unchecked(playback.generation + 1); - if (next == 0) - next = 1; - m_slotGenerations[slot] = next; - m_playbacks[slot] = null; - m_freeSlots.Push(slot); - } - private static void ValidateOptions(AnimationPlayOptions options) { if (!float.IsFinite(options.speed) || options.speed < 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Animation speed must be finite and non-negative."); + } if (!float.IsFinite(options.weight) || options.weight < 0f || options.weight > 1f) + { throw new ArgumentOutOfRangeException(nameof(options), "Animation weight must be between zero and one."); + } } private sealed class Playback( @@ -528,13 +563,6 @@ float weight private static AnimationValue Multiply( AnimationValue value, float weight - ) - => new( - value.kind, - value.x * weight, - value.y * weight, - value.z * weight, - value.w * weight); + ) => new(value.kind, value.x * weight, value.y * weight, value.z * weight, value.w * weight); } - } diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs b/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs index 1bd14c190..1ee939a36 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Animation.Runtime; @@ -20,16 +19,18 @@ public sealed class AnimationRuntimeFactory : IRuntimeSubsystemFactory /// public AnimationRuntimeFactory(Func runtimeFactory) { - m_runtimeFactory = runtimeFactory ?? throw new ArgumentNullException(nameof(runtimeFactory)); + ArgumentNullException.ThrowIfNull(runtimeFactory); + m_runtimeFactory = runtimeFactory; } /// /// Gets ordering metadata that evaluates animation after scene simulation. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.animation"), + new RuntimeSubsystemID("inno.runtime.animation"), order: 400, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemID("inno.runtime.scene")] + ); /// /// Creates a feature over a newly allocated animation runtime. @@ -44,7 +45,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); AnimationRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The animation runtime factory returned null."); + ?? throw new InvalidOperationException("The animation runtime factory returned null."); return runtime; } } diff --git a/src/content/animation/Inno.Animation/Animation.cs b/src/content/animation/Inno.Animation/Animation.cs index fffd3e743..fa894f654 100644 --- a/src/content/animation/Inno.Animation/Animation.cs +++ b/src/content/animation/Inno.Animation/Animation.cs @@ -1,38 +1,5 @@ -using Inno.Core.Execution; -using System; -using System.Threading; - namespace Inno.Animation; -/// -/// Binds one animation service to the current asynchronous execution context. -/// -public static class AnimationExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("animation"); - - /// - /// Gets the animation service bound to the current execution context. - /// - public static IAnimationService current => S_CURRENT_SCOPE.current; - - /// - /// Binds one animation service until the returned strict scope is disposed. - /// - /// - /// Session-owned animation service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IAnimationService animation) - { - ArgumentNullException.ThrowIfNull(animation); - return S_CURRENT_SCOPE.Enter(animation); - } - -} - /// /// Provides script-friendly animation control through the current runtime context. /// @@ -44,17 +11,16 @@ public static class Animation /// /// Valid imported animation clip. /// - /// - /// A generation-checked playback handle. - /// /// /// The weak destination or explicit sampling-only policy. /// + /// + /// A generation-checked playback handle. + /// public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target - ) - => AnimationExecutionContext.current.Play(clip, target); + ) => AnimationExecutionContext.current.Play(clip, target); /// /// Starts one clip with explicit playback options. @@ -62,21 +28,20 @@ AnimationTarget target /// /// Valid imported animation clip. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback and blend options. /// /// /// A generation-checked playback handle. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, AnimationPlayOptions options - ) - => AnimationExecutionContext.current.Play(clip, target, options); + ) => AnimationExecutionContext.current.Play(clip, target, options); /// /// Stops one live playback. @@ -147,6 +112,5 @@ public static bool TryGetState( AnimationPlaybackHandle handle, out AnimationPlaybackState state, out float time - ) - => AnimationExecutionContext.current.TryGetState(handle, out state, out time); + ) => AnimationExecutionContext.current.TryGetState(handle, out state, out time); } diff --git a/src/content/animation/Inno.Animation/AnimationBindingID.cs b/src/content/animation/Inno.Animation/AnimationBindingID.cs new file mode 100644 index 000000000..c96639229 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationBindingID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Animation; + +/// +/// Identifies one backend-neutral value destination inside an animation binding scope. +/// +public readonly record struct AnimationBindingID +{ + /// + /// Creates a stable animation binding identifier. + /// + /// + /// The non-empty binding protocol value. + /// + public AnimationBindingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the stable binding protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this identifier for diagnostics and persistence. + /// + /// + /// The protocol value, or an empty string for an uninitialized identifier. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/content/animation/Inno.Animation/AnimationBindingProvider.cs b/src/content/animation/Inno.Animation/AnimationBindingProvider.cs index 425dd6037..60bda7bb9 100644 --- a/src/content/animation/Inno.Animation/AnimationBindingProvider.cs +++ b/src/content/animation/Inno.Animation/AnimationBindingProvider.cs @@ -27,5 +27,5 @@ AnimationValue value /// /// Releases subscriptions and resources owned by this extension generation. /// - public virtual void Dispose() { } + public virtual void Dispose() {} } diff --git a/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs b/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs index 7febb51b9..f84ae4b43 100644 --- a/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs +++ b/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs @@ -14,7 +14,7 @@ public sealed class AnimationBindingProviderAttribute : Attribute /// /// Globally unique stable extension identifier. /// - /// + /// /// Stable track binding protocol, independent of CLR type names. /// /// @@ -25,15 +25,17 @@ public sealed class AnimationBindingProviderAttribute : Attribute /// public AnimationBindingProviderAttribute( string id, - string bindingId, + string bindingID, AnimationValueKind kind ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); + ArgumentException.ThrowIfNullOrWhiteSpace(bindingID); if (!Enum.IsDefined(kind)) + { throw new ArgumentException("A defined animation value kind is required.", nameof(kind)); + } this.id = id; - this.bindingId = new AnimationBindingId(bindingId); + this.bindingID = new AnimationBindingID(bindingID); this.kind = kind; } @@ -45,7 +47,7 @@ AnimationValueKind kind /// /// Gets the supported track binding protocol. /// - public AnimationBindingId bindingId { get; } + public AnimationBindingID bindingID { get; } /// /// Gets the accepted value representation. diff --git a/src/content/animation/Inno.Animation/AnimationClipAsset.cs b/src/content/animation/Inno.Animation/AnimationClipAsset.cs index c318521d7..223e70a04 100644 --- a/src/content/animation/Inno.Animation/AnimationClipAsset.cs +++ b/src/content/animation/Inno.Animation/AnimationClipAsset.cs @@ -1,152 +1,15 @@ using System; using System.Collections.Generic; -using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; namespace Inno.Animation; -/// -/// Stores one timestamped value inside an animation track. -/// -public struct AnimationKeyframe -{ - /// - /// Creates one animation keyframe. - /// - /// - /// Non-negative clip-local time in seconds. - /// - /// - /// Value sampled at the keyframe time. - /// - public AnimationKeyframe( - float time, - AnimationValue value - ) { - if (!float.IsFinite(time) || time < 0f) - throw new ArgumentOutOfRangeException(nameof(time)); - this.time = time; - this.value = value; - } - - /// - /// Gets or sets clip-local time in seconds. - /// - [SerializableProperty] - public float time { get; set; } - - /// - /// Gets or sets the sampled value. - /// - [SerializableProperty] - public AnimationValue value { get; set; } -} - -/// -/// Stores one ordered value track targeting a stable binding. -/// -public sealed class AnimationTrack : ISerializable -{ - /// - /// Creates an empty track for structured deserialization. - /// - public AnimationTrack() - { - } - - /// - /// Creates one validated animation track. - /// - /// - /// Stable target binding identifier. - /// - /// - /// Sampling rule between adjacent keyframes. - /// - /// - /// Keyframes ordered by non-decreasing clip-local time. - /// - public AnimationTrack( - string bindingId, - AnimationInterpolation interpolation, - IEnumerable keyframes - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); - ArgumentNullException.ThrowIfNull(keyframes); - this.bindingId = bindingId; - this.interpolation = interpolation; - this.keyframes = keyframes.ToArray(); - Validate(float.PositiveInfinity); - } - - /// - /// Gets or sets the stable target binding identifier. - /// - [SerializableProperty] - public string bindingId { get; set; } = string.Empty; - - /// - /// Gets or sets the sampling rule between adjacent keyframes. - /// - [SerializableProperty] - public AnimationInterpolation interpolation { get; set; } - - /// - /// Gets or sets ordered keyframes. - /// - [SerializableProperty] - public AnimationKeyframe[] keyframes { get; set; } = []; - - internal void Validate(float duration) - { - ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); - if (keyframes is null || keyframes.Length == 0) - throw new InvalidOperationException($"Animation track '{bindingId}' requires at least one keyframe."); - AnimationValueKind kind = keyframes[0].value.kind; - float previous = -1f; - for (int index = 0; index < keyframes.Length; index++) - { - AnimationKeyframe keyframe = keyframes[index]; - if (!float.IsFinite(keyframe.time) || keyframe.time < previous || keyframe.time > duration) - throw new InvalidOperationException($"Animation track '{bindingId}' contains invalid keyframe times."); - if (keyframe.value.kind != kind) - throw new InvalidOperationException($"Animation track '{bindingId}' mixes incompatible value kinds."); - previous = keyframe.time; - } - } -} - -/// -/// Stores one stable event marker embedded in an animation clip. -/// -public sealed class AnimationEventMarker : ISerializable -{ - /// - /// Gets or sets clip-local marker time in seconds. - /// - [SerializableProperty] - public float time { get; set; } - - /// - /// Gets or sets the stable event protocol identifier. - /// - [SerializableProperty] - public string eventId { get; set; } = string.Empty; - - /// - /// Gets or sets opaque reload-safe event payload bytes. - /// - [SerializableProperty] - public byte[] payload { get; set; } = []; -} - /// /// Represents one imported backend-neutral collection of tracks and event markers. /// -[StableTypeId("da0df43b-f6e4-4c84-b45f-d58aa4030e6f")] +[StableTypeID("da0df43b-f6e4-4c84-b45f-d58aa4030e6f")] public sealed class AnimationClipAsset : AssetObject { /// @@ -176,27 +39,37 @@ public sealed class AnimationClipAsset : AssetObject public void Validate() { if (!float.IsFinite(duration) || duration <= 0f) + { throw new InvalidOperationException("An animation clip requires a positive finite duration."); + } if (tracks is null || events is null) + { throw new InvalidOperationException("Animation clip collections cannot be null."); + } var bindings = new HashSet(StringComparer.Ordinal); for (int index = 0; index < tracks.Length; index++) { AnimationTrack track = tracks[index] - ?? throw new InvalidOperationException("Animation clip tracks cannot contain null entries."); + ?? throw new InvalidOperationException("Animation clip tracks cannot contain null entries."); track.Validate(duration); if (!bindings.Add(track.bindingId)) + { throw new InvalidOperationException($"Animation binding '{track.bindingId}' is duplicated."); + } } float previous = -1f; for (int index = 0; index < events.Length; index++) { AnimationEventMarker marker = events[index] - ?? throw new InvalidOperationException("Animation clip events cannot contain null entries."); + ?? throw new InvalidOperationException("Animation clip events cannot contain null entries."); if (!float.IsFinite(marker.time) || marker.time < previous || marker.time > duration) + { throw new InvalidOperationException("Animation clip event markers must be ordered within its duration."); + } if (string.IsNullOrWhiteSpace(marker.eventId)) + { throw new InvalidOperationException("Animation event markers require stable event identifiers."); + } marker.payload ??= []; previous = marker.time; } diff --git a/src/content/animation/Inno.Animation/AnimationClock.cs b/src/content/animation/Inno.Animation/AnimationClock.cs new file mode 100644 index 000000000..14b81258f --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationClock.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Selects the session clock used to advance an animation playback. +/// +public enum AnimationClock +{ + /// + /// Uses scaled simulation time and stops while the session is paused. + /// + Scaled, + /// + /// Uses unscaled session time and continues while simulation is paused. + /// + Unscaled +} diff --git a/src/content/animation/Inno.Animation/AnimationEventMarker.cs b/src/content/animation/Inno.Animation/AnimationEventMarker.cs new file mode 100644 index 000000000..21c91bb3c --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationEventMarker.cs @@ -0,0 +1,27 @@ +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one stable event marker embedded in an animation clip. +/// +public sealed class AnimationEventMarker : ISerializable +{ + /// + /// Gets or sets clip-local marker time in seconds. + /// + [SerializableProperty] + public float time { get; set; } + + /// + /// Gets or sets the stable event protocol identifier. + /// + [SerializableProperty] + public string eventId { get; set; } = string.Empty; + + /// + /// Gets or sets opaque reload-safe event payload bytes. + /// + [SerializableProperty] + public byte[] payload { get; set; } = []; +} diff --git a/src/content/animation/Inno.Animation/AnimationExecutionContext.cs b/src/content/animation/Inno.Animation/AnimationExecutionContext.cs new file mode 100644 index 000000000..ee535bdb5 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Animation; + +/// +/// Binds one animation service to the current asynchronous execution context. +/// +public static class AnimationExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("animation"); + + /// + /// Gets the animation service bound to the current execution context. + /// + public static IAnimationService current => CURRENT_SCOPE.current; + + /// + /// Binds one animation service until the returned strict scope is disposed. + /// + /// + /// Session-owned animation service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IAnimationService animation) + { + ArgumentNullException.ThrowIfNull(animation); + return CURRENT_SCOPE.Enter(animation); + } +} diff --git a/src/content/animation/Inno.Animation/AnimationInterpolation.cs b/src/content/animation/Inno.Animation/AnimationInterpolation.cs new file mode 100644 index 000000000..3b8b2f2ca --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationInterpolation.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Selects how values are sampled between adjacent keyframes. +/// +public enum AnimationInterpolation +{ + /// + /// Holds the previous keyframe value until the next keyframe. + /// + Step, + /// + /// Blends linearly between adjacent keyframes. + /// + Linear +} diff --git a/src/content/animation/Inno.Animation/AnimationKeyframe.cs b/src/content/animation/Inno.Animation/AnimationKeyframe.cs new file mode 100644 index 000000000..ebd03234f --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationKeyframe.cs @@ -0,0 +1,43 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one timestamped value inside an animation track. +/// +public struct AnimationKeyframe +{ + /// + /// Creates one animation keyframe. + /// + /// + /// Non-negative clip-local time in seconds. + /// + /// + /// Value sampled at the keyframe time. + /// + public AnimationKeyframe( + float time, + AnimationValue value + ) { + if (!float.IsFinite(time) || time < 0f) + { + throw new ArgumentOutOfRangeException(nameof(time)); + } + this.time = time; + this.value = value; + } + + /// + /// Gets or sets clip-local time in seconds. + /// + [SerializableProperty] + public float time { get; set; } + + /// + /// Gets or sets the sampled value. + /// + [SerializableProperty] + public AnimationValue value { get; set; } +} diff --git a/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs b/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs new file mode 100644 index 000000000..82bcded4e --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs @@ -0,0 +1,52 @@ +using System; +using Inno.Core.Events; + +namespace Inno.Animation; + +/// +/// Publishes a stable marker reached by one animation playback on the main runtime thread. +/// +public sealed class AnimationMarkerEvent : Event +{ + /// + /// Creates one immutable animation marker event. + /// + /// + /// Playback that crossed the marker. + /// + /// + /// Stable marker protocol identifier. + /// + /// + /// Opaque reload-safe marker payload bytes. + /// + public AnimationMarkerEvent( + AnimationPlaybackHandle playback, + string eventID, + ReadOnlyMemory payload + ) { + if (!playback.isValid) + { + throw new ArgumentException("A valid animation playback handle is required.", nameof(playback)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(eventID); + this.playback = playback; + this.eventID = eventID; + this.payload = payload.ToArray(); + } + + /// + /// Gets the playback that crossed the marker. + /// + public AnimationPlaybackHandle playback { get; } + + /// + /// Gets the stable marker protocol identifier. + /// + public string eventID { get; } + + /// + /// Gets an immutable copy of the marker payload. + /// + public ReadOnlyMemory payload { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlayOptions.cs b/src/content/animation/Inno.Animation/AnimationPlayOptions.cs new file mode 100644 index 000000000..4cc823a5d --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlayOptions.cs @@ -0,0 +1,44 @@ +namespace Inno.Animation; + +/// +/// Stores immutable options used to begin one animation playback. +/// +public struct AnimationPlayOptions +{ + /// + /// Gets the default playback options. + /// + public static AnimationPlayOptions defaultValue + => new() + { + speed = 1f, + weight = 1f, + layer = 0, + clock = AnimationClock.Scaled + }; + + /// + /// Gets or sets the non-negative playback speed multiplier. + /// + public float speed { get; set; } + + /// + /// Gets or sets the finite blend weight in the inclusive zero-to-one range. + /// + public float weight { get; set; } + + /// + /// Gets or sets the deterministic blend layer. + /// + public int layer { get; set; } + + /// + /// Gets or sets whether the clip repeats after its duration. + /// + public bool loop { get; set; } + + /// + /// Gets or sets the session clock used by the playback. + /// + public AnimationClock clock { get; set; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs index 944c47f5f..1ef1d1fde 100644 --- a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs +++ b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs @@ -8,7 +8,7 @@ namespace Inno.Animation; /// public sealed class AnimationPlaybackAllocator { - private static int S_NEXT_GENERATION; + private static int s_nextGeneration; /// /// Creates a process-unique playback owner. @@ -18,10 +18,12 @@ public sealed class AnimationPlaybackAllocator /// public AnimationPlaybackAllocator() { - int next = Interlocked.Increment(ref S_NEXT_GENERATION); + int next = Interlocked.Increment(ref s_nextGeneration); if (next <= 0) + { throw new InvalidOperationException("Animation owner generations are exhausted."); - generation = (uint)next; + } + this.generation = (uint)next; } /// @@ -49,9 +51,8 @@ public AnimationPlaybackHandle Create( uint slotGeneration ) { ArgumentOutOfRangeException.ThrowIfNegative(slot); - if (slotGeneration == 0) - throw new ArgumentOutOfRangeException(nameof(slotGeneration)); - return new AnimationPlaybackHandle(((ulong)slotGeneration << 32) | ((uint)slot + 1U), generation); + ArgumentOutOfRangeException.ThrowIfZero(slotGeneration); + return new AnimationPlaybackHandle(((ulong)slotGeneration << 32) | ((uint)slot + 1u), generation); } /// @@ -66,8 +67,10 @@ uint slotGeneration public (int slot, uint generation) Decode(AnimationPlaybackHandle handle) { if (!handle.isValid || handle.runtimeGeneration != generation) + { return (-1, 0); + } uint encodedSlot = (uint)(handle.value & uint.MaxValue); - return (checked((int)(encodedSlot - 1U)), (uint)(handle.value >> 32)); + return (checked((int)(encodedSlot - 1u)), (uint)(handle.value >> 32)); } } diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs b/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs new file mode 100644 index 000000000..d4ef2c7f8 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Animation; + +/// +/// Identifies one generation-checked animation playback owned by a runtime service. +/// +public readonly record struct AnimationPlaybackHandle +{ + internal AnimationPlaybackHandle( + ulong value, + uint runtimeGeneration + ) { + this.value = value; + this.runtimeGeneration = runtimeGeneration; + } + + /// + /// Gets whether the handle was initialized by an animation service. + /// + public bool isValid => value != 0 && runtimeGeneration != 0; + + internal ulong value { get; } + + /// + /// Gets the isolated runtime generation that created this handle. + /// + public uint runtimeGeneration { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackState.cs b/src/content/animation/Inno.Animation/AnimationPlaybackState.cs new file mode 100644 index 000000000..da645acde --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlaybackState.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Describes the observable lifecycle of one animation playback. +/// +public enum AnimationPlaybackState +{ + /// + /// The playback is advancing and producing samples. + /// + Playing, + /// + /// The playback retains its position without advancing. + /// + Paused +} diff --git a/src/content/animation/Inno.Animation/AnimationSample.cs b/src/content/animation/Inno.Animation/AnimationSample.cs new file mode 100644 index 000000000..5ccaac047 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationSample.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Animation; + +/// +/// Stores one final blended value emitted for a stable binding identifier. +/// +public readonly record struct AnimationSample +{ + /// + /// Creates one final animation sample. + /// + /// + /// The weak destination or explicit sampling-only policy. + /// + /// + /// Stable target binding. + /// + /// + /// Final blended value. + /// + public AnimationSample( + AnimationTarget target, + AnimationBindingID binding, + AnimationValue value + ) { + if (!target.isValid) + { + throw new ArgumentException("A valid animation destination is required.", nameof(target)); + } + if (!binding.isValid) + { + throw new ArgumentException("A valid animation binding is required.", nameof(binding)); + } + this.binding = binding; + this.target = target; + this.value = value; + } + + /// + /// Gets the stable target binding. + /// + public AnimationBindingID binding { get; } + + /// + /// Gets the generation-qualified destination for this sample. + /// + public AnimationTarget target { get; } + + /// + /// Gets the final blended value. + /// + public AnimationValue value { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationSampling.cs b/src/content/animation/Inno.Animation/AnimationSampling.cs index 92b3b2be9..4e46fd0e8 100644 --- a/src/content/animation/Inno.Animation/AnimationSampling.cs +++ b/src/content/animation/Inno.Animation/AnimationSampling.cs @@ -24,8 +24,7 @@ public static AnimationValue Interpolate( AnimationValue left, AnimationValue right, float amount - ) - => AnimationValue.Lerp(left, right, amount); + ) => AnimationValue.Lerp(left, right, amount); /// /// Adds one weighted value to an accumulation of the same kind. @@ -46,8 +45,7 @@ public static AnimationValue AddWeighted( AnimationValue sum, AnimationValue value, float weight - ) - => AnimationValue.AddWeighted(sum, value, weight); + ) => AnimationValue.AddWeighted(sum, value, weight); /// /// Normalizes a weighted sum, including quaternion normalization. @@ -64,6 +62,5 @@ float weight public static AnimationValue CompleteWeighted( AnimationValue sum, float inverseWeight - ) - => AnimationValue.WeightedAverage(sum, inverseWeight); + ) => AnimationValue.WeightedAverage(sum, inverseWeight); } diff --git a/src/content/animation/Inno.Animation/AnimationTarget.cs b/src/content/animation/Inno.Animation/AnimationTarget.cs index b9eea0c61..eed4003c5 100644 --- a/src/content/animation/Inno.Animation/AnimationTarget.cs +++ b/src/content/animation/Inno.Animation/AnimationTarget.cs @@ -24,7 +24,7 @@ namespace Inno.Animation; public AnimationTarget(Identity identity) { m_runtimeIdentity = identity.runtimeIdentity - ?? throw new ArgumentException("Animation targets require a live identity.", nameof(identity)); + ?? throw new ArgumentException("Animation targets require a live identity.", nameof(identity)); m_identity = identity; m_samplingOnly = false; } @@ -49,12 +49,12 @@ private AnimationTarget(bool samplingOnly) /// /// Gets whether this value was initialized with a destination or sampling policy. /// - public bool isValid => m_samplingOnly || m_identity.persistentId != Guid.Empty; + public bool isValid => m_samplingOnly || m_identity.persistentID != Guid.Empty; /// /// Gets the persistent destination identifier, or empty for sampling-only playback. /// - public Guid persistentId => m_identity.persistentId; + public Guid persistentID => m_identity.persistentID; /// /// Resolves the original runtime slot without binding to a replacement generation. @@ -65,7 +65,8 @@ private AnimationTarget(bool samplingOnly) /// /// The live destination, or null for a missing, retired, or incompatible target. /// - public TObject? Resolve() where TObject : IdentityObject => m_identity.Resolve(); + public TObject? Resolve() + where TObject : IdentityObject => m_identity.Resolve(); /// /// Compares runtime destinations, including their identity domain. diff --git a/src/content/animation/Inno.Animation/AnimationTrack.cs b/src/content/animation/Inno.Animation/AnimationTrack.cs new file mode 100644 index 000000000..4cbe3f299 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationTrack.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one ordered value track targeting a stable binding. +/// +public sealed class AnimationTrack : ISerializable +{ + /// + /// Creates an empty track for structured deserialization. + /// + public AnimationTrack() {} + + /// + /// Creates one validated animation track. + /// + /// + /// Stable target binding identifier. + /// + /// + /// Sampling rule between adjacent keyframes. + /// + /// + /// Keyframes ordered by non-decreasing clip-local time. + /// + public AnimationTrack( + string bindingID, + AnimationInterpolation interpolation, + IEnumerable keyframes + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(bindingID); + ArgumentNullException.ThrowIfNull(keyframes); + this.bindingId = bindingID; + this.interpolation = interpolation; + this.keyframes = keyframes.ToArray(); + Validate(float.PositiveInfinity); + } + + /// + /// Gets or sets the stable target binding identifier. + /// + [SerializableProperty] + public string bindingId { get; set; } = string.Empty; + + /// + /// Gets or sets the sampling rule between adjacent keyframes. + /// + [SerializableProperty] + public AnimationInterpolation interpolation { get; set; } + + /// + /// Gets or sets ordered keyframes. + /// + [SerializableProperty] + public AnimationKeyframe[] keyframes { get; set; } = []; + + internal void Validate(float duration) + { + ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); + if (keyframes is null || keyframes.Length == 0) + { + throw new InvalidOperationException($"Animation track '{bindingId}' requires at least one keyframe."); + } + AnimationValueKind kind = keyframes[0].value.kind; + float previous = -1f; + for (int index = 0; index < keyframes.Length; index++) + { + AnimationKeyframe keyframe = keyframes[index]; + if (!float.IsFinite(keyframe.time) || keyframe.time < previous || keyframe.time > duration) + { + throw new InvalidOperationException($"Animation track '{bindingId}' contains invalid keyframe times."); + } + if (keyframe.value.kind != kind) + { + throw new InvalidOperationException($"Animation track '{bindingId}' mixes incompatible value kinds."); + } + previous = keyframe.time; + } + } +} diff --git a/src/content/animation/Inno.Animation/AnimationTypes.cs b/src/content/animation/Inno.Animation/AnimationTypes.cs deleted file mode 100644 index 105710d8a..000000000 --- a/src/content/animation/Inno.Animation/AnimationTypes.cs +++ /dev/null @@ -1,378 +0,0 @@ -using System; - -using Inno.Core.Serialization; - -namespace Inno.Animation; - -/// -/// Identifies one backend-neutral value destination inside an animation binding scope. -/// -public readonly record struct AnimationBindingId -{ - /// - /// Creates a stable animation binding identifier. - /// - /// - /// The non-empty binding protocol value. - /// - public AnimationBindingId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the stable binding protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this identifier for diagnostics and persistence. - /// - /// - /// The protocol value, or an empty string for an uninitialized identifier. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes the number and interpretation of components in an animation value. -/// -public enum AnimationValueKind -{ - /// - /// A single scalar component. - /// - Scalar, - - /// - /// Two independent components. - /// - Vector2, - - /// - /// Three independent components. - /// - Vector3, - - /// - /// Four independent components. - /// - Vector4, - - /// - /// Four normalized rotation components. - /// - Quaternion -} - -/// -/// Stores one backend-neutral scalar, vector, or quaternion animation value. -/// -public struct AnimationValue -{ - /// - /// Creates a four-component animation value. - /// - /// - /// Interpretation of the populated components. - /// - /// - /// First component. - /// - /// - /// Second component. - /// - /// - /// Third component. - /// - /// - /// Fourth component. - /// - public AnimationValue( - AnimationValueKind kind, - float x, - float y = 0f, - float z = 0f, - float w = 0f - ) { - this.kind = kind; - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - /// - /// Gets or sets the component interpretation. - /// - [SerializableProperty] - public AnimationValueKind kind { get; set; } - - /// - /// Gets or sets the first component. - /// - [SerializableProperty] - public float x { get; set; } - - /// - /// Gets or sets the second component. - /// - [SerializableProperty] - public float y { get; set; } - - /// - /// Gets or sets the third component. - /// - [SerializableProperty] - public float z { get; set; } - - /// - /// Gets or sets the fourth component. - /// - [SerializableProperty] - public float w { get; set; } - - internal static AnimationValue Lerp( - AnimationValue left, - AnimationValue right, - float amount - ) { - if (left.kind != right.kind) - throw new InvalidOperationException("Animation values with different kinds cannot be interpolated."); - float t = Math.Clamp(amount, 0f, 1f); - var value = new AnimationValue( - left.kind, - left.x + ((right.x - left.x) * t), - left.y + ((right.y - left.y) * t), - left.z + ((right.z - left.z) * t), - left.w + ((right.w - left.w) * t)); - return left.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; - } - - internal static AnimationValue WeightedAverage( - AnimationValue sum, - float inverseWeight - ) { - var value = new AnimationValue( - sum.kind, - sum.x * inverseWeight, - sum.y * inverseWeight, - sum.z * inverseWeight, - sum.w * inverseWeight); - return sum.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; - } - - internal static AnimationValue AddWeighted( - AnimationValue sum, - AnimationValue value, - float weight - ) { - if (sum.kind != value.kind) - throw new InvalidOperationException("Animation tracks targeting one binding must use one value kind."); - sum.x += value.x * weight; - sum.y += value.y * weight; - sum.z += value.z * weight; - sum.w += value.w * weight; - return sum; - } - - private static AnimationValue NormalizeQuaternion(AnimationValue value) - { - float length = MathF.Sqrt( - (value.x * value.x) + - (value.y * value.y) + - (value.z * value.z) + - (value.w * value.w)); - return length <= float.Epsilon - ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) - : new AnimationValue( - AnimationValueKind.Quaternion, - value.x / length, - value.y / length, - value.z / length, - value.w / length); - } -} - -/// -/// Selects how values are sampled between adjacent keyframes. -/// -public enum AnimationInterpolation -{ - /// - /// Holds the previous keyframe value until the next keyframe. - /// - Step, - - /// - /// Blends linearly between adjacent keyframes. - /// - Linear -} - -/// -/// Selects the session clock used to advance an animation playback. -/// -public enum AnimationClock -{ - /// - /// Uses scaled simulation time and stops while the session is paused. - /// - Scaled, - - /// - /// Uses unscaled session time and continues while simulation is paused. - /// - Unscaled -} - -/// -/// Describes the observable lifecycle of one animation playback. -/// -public enum AnimationPlaybackState -{ - /// - /// The playback is advancing and producing samples. - /// - Playing, - - /// - /// The playback retains its position without advancing. - /// - Paused -} - -/// -/// Stores immutable options used to begin one animation playback. -/// -public struct AnimationPlayOptions -{ - /// - /// Gets the default playback options. - /// - public static AnimationPlayOptions defaultValue => new() - { - speed = 1f, - weight = 1f, - layer = 0, - clock = AnimationClock.Scaled - }; - - /// - /// Gets or sets the non-negative playback speed multiplier. - /// - public float speed { get; set; } - - /// - /// Gets or sets the finite blend weight in the inclusive zero-to-one range. - /// - public float weight { get; set; } - - /// - /// Gets or sets the deterministic blend layer. - /// - public int layer { get; set; } - - /// - /// Gets or sets whether the clip repeats after its duration. - /// - public bool loop { get; set; } - - /// - /// Gets or sets the session clock used by the playback. - /// - public AnimationClock clock { get; set; } -} - -/// -/// Identifies one generation-checked animation playback owned by a runtime service. -/// -public readonly record struct AnimationPlaybackHandle -{ - internal AnimationPlaybackHandle( - ulong value, - uint runtimeGeneration - ) { - this.value = value; - this.runtimeGeneration = runtimeGeneration; - } - - /// - /// Gets whether the handle was initialized by an animation service. - /// - public bool isValid => value != 0 && runtimeGeneration != 0; - - internal ulong value { get; } - - /// - /// Gets the isolated runtime generation that created this handle. - /// - public uint runtimeGeneration { get; } -} - -/// -/// Stores one final blended value emitted for a stable binding identifier. -/// -public readonly record struct AnimationSample -{ - /// - /// Creates one final animation sample. - /// - /// - /// Stable target binding. - /// - /// - /// Final blended value. - /// - /// - /// The weak destination or explicit sampling-only policy. - /// - public AnimationSample( - AnimationTarget target, - AnimationBindingId binding, - AnimationValue value - ) { - if (!target.isValid) - throw new ArgumentException("A valid animation destination is required.", nameof(target)); - if (!binding.isValid) - throw new ArgumentException("A valid animation binding is required.", nameof(binding)); - this.binding = binding; - this.target = target; - this.value = value; - } - - /// - /// Gets the stable target binding. - /// - public AnimationBindingId binding { get; } - - /// - /// Gets the generation-qualified destination for this sample. - /// - public AnimationTarget target { get; } - - /// - /// Gets the final blended value. - /// - public AnimationValue value { get; } -} - -/// -/// Receives final backend-neutral samples after runtime blending has completed. -/// -public interface IAnimationBindingSink -{ - /// - /// Applies one immutable frame of final animation samples. - /// - /// - /// Samples sorted by stable binding identifier. - /// - void Apply(ReadOnlySpan samples); -} diff --git a/src/content/animation/Inno.Animation/AnimationValue.cs b/src/content/animation/Inno.Animation/AnimationValue.cs new file mode 100644 index 000000000..a9e72f206 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationValue.cs @@ -0,0 +1,168 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one backend-neutral scalar, vector, or quaternion animation value. +/// +public struct AnimationValue +{ + /// + /// Creates a four-component animation value. + /// + /// + /// Interpretation of the populated components. + /// + /// + /// First component. + /// + /// + /// Second component. + /// + /// + /// Third component. + /// + /// + /// Fourth component. + /// + public AnimationValue( + AnimationValueKind kind, + float x, + float y = 0f, + float z = 0f, + float w = 0f + ) { + this.kind = kind; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /// + /// Gets or sets the component interpretation. + /// + [SerializableProperty] + public AnimationValueKind kind { get; set; } + + /// + /// Gets or sets the first component. + /// + [SerializableProperty] + public float x { get; set; } + + /// + /// Gets or sets the second component. + /// + [SerializableProperty] + public float y { get; set; } + + /// + /// Gets or sets the third component. + /// + [SerializableProperty] + public float z { get; set; } + + /// + /// Gets or sets the fourth component. + /// + [SerializableProperty] + public float w { get; set; } + + internal static AnimationValue Lerp( + AnimationValue left, + AnimationValue right, + float amount + ) { + if (left.kind != right.kind) + { + throw new InvalidOperationException("Animation values with different kinds cannot be interpolated."); + } + float t = Math.Clamp(amount, 0f, 1f); + var value = new AnimationValue( + left.kind, + left.x + ((right.x - left.x) * t), + left.y + ((right.y - left.y) * t), + left.z + ((right.z - left.z) * t), + left.w + ((right.w - left.w) * t) + ); + return left.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; + } + + internal static AnimationValue WeightedAverage( + AnimationValue sum, + float inverseWeight + ) { + var value = new AnimationValue( + sum.kind, + sum.x * inverseWeight, + sum.y * inverseWeight, + sum.z * inverseWeight, + sum.w * inverseWeight + ); + return sum.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; + } + + internal static AnimationValue AddWeighted( + AnimationValue sum, + AnimationValue value, + float weight + ) { + if (sum.kind != value.kind) + { + throw new InvalidOperationException("Animation tracks targeting one binding must use one value kind."); + } + sum.x += value.x * weight; + sum.y += value.y * weight; + sum.z += value.z * weight; + sum.w += value.w * weight; + return sum; + } + + private static AnimationValue NormalizeQuaternion(AnimationValue value) + { + float length = MathF.Sqrt( + (value.x * value.x) + + (value.y * value.y) + + (value.z * value.z) + + (value.w * value.w) + ); + return length <= float.Epsilon + ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) + : new AnimationValue( + AnimationValueKind.Quaternion, + value.x / length, + value.y / length, + value.z / length, + value.w / length + ); + } +} + +/// +/// Describes the number and interpretation of components in an animation value. +/// +public enum AnimationValueKind +{ + /// + /// A single scalar component. + /// + Scalar, + /// + /// Two independent components. + /// + Vector2, + /// + /// Three independent components. + /// + Vector3, + /// + /// Four independent components. + /// + Vector4, + /// + /// Four normalized rotation components. + /// + Quaternion +} diff --git a/src/content/animation/Inno.Animation/IAnimationBindingSink.cs b/src/content/animation/Inno.Animation/IAnimationBindingSink.cs new file mode 100644 index 000000000..9e51a96a0 --- /dev/null +++ b/src/content/animation/Inno.Animation/IAnimationBindingSink.cs @@ -0,0 +1,17 @@ +using System; + +namespace Inno.Animation; + +/// +/// Receives final backend-neutral samples after runtime blending has completed. +/// +public interface IAnimationBindingSink +{ + /// + /// Applies one immutable frame of final animation samples. + /// + /// + /// Samples sorted by stable binding identifier. + /// + void Apply(ReadOnlySpan samples); +} diff --git a/src/content/animation/Inno.Animation/IAnimationService.cs b/src/content/animation/Inno.Animation/IAnimationService.cs index 60ed77c09..f48acf97c 100644 --- a/src/content/animation/Inno.Animation/IAnimationService.cs +++ b/src/content/animation/Inno.Animation/IAnimationService.cs @@ -1,7 +1,3 @@ -using System; - -using Inno.Core.Events; - namespace Inno.Animation; /// @@ -15,12 +11,12 @@ public interface IAnimationService /// /// Valid imported animation clip. /// - /// - /// A generation-checked playback handle. - /// /// /// The weak destination or explicit sampling-only policy. /// + /// + /// A generation-checked playback handle. + /// AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target @@ -32,15 +28,15 @@ AnimationTarget target /// /// Valid imported animation clip. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback clock, speed, blend, layer, and looping policy. /// /// /// A generation-checked playback handle. /// - /// - /// The weak destination or explicit sampling-only policy. - /// AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, @@ -118,49 +114,3 @@ bool TryGetState( out float time ); } - -/// -/// Publishes a stable marker reached by one animation playback on the main runtime thread. -/// -public sealed class AnimationMarkerEvent : Event -{ - /// - /// Creates one immutable animation marker event. - /// - /// - /// Playback that crossed the marker. - /// - /// - /// Stable marker protocol identifier. - /// - /// - /// Opaque reload-safe marker payload bytes. - /// - public AnimationMarkerEvent( - AnimationPlaybackHandle playback, - string eventId, - ReadOnlyMemory payload - ) { - if (!playback.isValid) - throw new ArgumentException("A valid animation playback handle is required.", nameof(playback)); - ArgumentException.ThrowIfNullOrWhiteSpace(eventId); - this.playback = playback; - this.eventId = eventId; - this.payload = payload.ToArray(); - } - - /// - /// Gets the playback that crossed the marker. - /// - public AnimationPlaybackHandle playback { get; } - - /// - /// Gets the stable marker protocol identifier. - /// - public string eventId { get; } - - /// - /// Gets an immutable copy of the marker payload. - /// - public ReadOnlyMemory payload { get; } -} diff --git a/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs b/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs index 825c1bf78..1151f1051 100644 --- a/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs +++ b/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs @@ -1,13 +1,10 @@ using Inno.Animation; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Animation", - "Inno.Animation", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Animation", "Inno.Animation", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Animation), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AnimationBindingId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AnimationBindingID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AnimationTarget), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AnimationBindingProvider), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AnimationBindingProviderAttribute), ScriptingApiScope.Runtime)] diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs b/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs index 292a9837b..5288217cf 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs @@ -24,11 +24,9 @@ public readonly struct AssetCacheOptions /// The default cache options. /// public static AssetCacheOptions CreateDefault() + => new AssetCacheOptions { - return new AssetCacheOptions - { - maximumSizeBytes = 4L * 1024 * 1024 * 1024, - garbageCollectionGracePeriod = TimeSpan.FromDays(7) - }; - } + maximumSizeBytes = 4L * 1024 * 1024 * 1024, + garbageCollectionGracePeriod = TimeSpan.FromDays(7) + }; } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs index 677abc7f8..fcb782004 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs @@ -4,27 +4,26 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Tries to resolve a named artifact output. /// - /// + /// /// The artifact owner identity. /// /// @@ -37,16 +36,15 @@ sealed partial class AssetPipeline /// when the output exists. /// public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact - ) - => GetLoader().TryGetArtifact(persistentId, outputName, out artifact); + ) => GetLoader().TryGetArtifact(persistentID, outputName, out artifact); /// /// Acquires one verified authoring artifact generation for an explicit lifetime. /// - /// + /// /// Persistent identity of the artifact owner. /// /// @@ -59,9 +57,9 @@ out AssetArtifactInfo? artifact /// Thrown when the requested artifact is unavailable. /// public ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName - ) => GetLoader().AcquireArtifact(persistentId, outputName); + ) => GetLoader().AcquireArtifact(persistentID, outputName); /// /// Runs an aggregate asset build using the processor registered for a definition. @@ -111,19 +109,12 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationContentR using IDisposable operationScope = AcquireOperation(); WaitForIdle(); using SerializationGeneration serialization = m_serialization.CaptureGeneration(); - return GetLoader().ExportRuntimeArtifacts( - destinationContentRoot, - serialization, - CancellationToken.None); + return GetLoader().ExportRuntimeArtifacts(destinationContentRoot, serialization, CancellationToken.None); } /// /// Exports a runtime-only artifact snapshot on a worker without loading artifact files into memory. /// - /// - /// Keeps generation admission and serialization pinned until the worker completes, fails or cancels. - /// A pending or faulted generation cannot start a new export. - /// /// /// The empty destination that receives the runtime asset database. /// @@ -140,6 +131,10 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationContentR /// /// Thrown when cancellation is requested before export completes. /// + /// + /// Keeps generation admission and serialization pinned until the worker completes, fails or cancels. + /// A pending or faulted generation cannot start a new export. + /// [ScriptingApiIgnore] public async Task ExportRuntimeArtifactsAsync( string destinationContentRoot, @@ -152,7 +147,8 @@ public async Task ExportRuntimeArtifactsAsync( using SerializationGeneration serialization = m_serialization.CaptureGeneration(); return await Task.Run( () => loader.ExportRuntimeArtifacts(destinationContentRoot, serialization, cancellationToken), - CancellationToken.None).ConfigureAwait(false); + CancellationToken.None + ).ConfigureAwait(false); } private void CollectArtifactsIfDue( @@ -160,14 +156,15 @@ private void CollectArtifactsIfDue( bool force ) { if (m_options.mode == AssetPipelineMode.RuntimeArtifacts) + { return; + } long now = Environment.TickCount64; if (!force && now - m_lastArtifactCollectionTimestamp < 60_000) + { return; + } m_lastArtifactCollectionTimestamp = now; - _ = loader.CollectArtifacts( - m_cacheOptions.garbageCollectionGracePeriod, - m_cacheOptions.maximumSizeBytes); + _ = loader.CollectArtifacts(m_cacheOptions.garbageCollectionGracePeriod, m_cacheOptions.maximumSizeBytes); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs index ac5ba6a11..2b959e79e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs @@ -4,22 +4,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Reconciles source files, generated files and the persistent catalog. @@ -40,7 +39,9 @@ public void Update() { EnsureInitializationThread(); if (m_sampleImport is not null) + { return; + } using IDisposable operationScope = AcquireOperation(); PruneRetiredObservers(); AssetFileSystem fileSystem = GetFileSystem(); @@ -98,9 +99,7 @@ public IReadOnlyList GetFileSystemEntries(bool includeDirectorie public bool TryGetFileSystemEntry( AssetPath path, out AssetFileEntry entry - ) { - return GetFileSystem().TryGetEntry(path, out entry); - } + ) => GetFileSystem().TryGetEntry(path, out entry); private void ApplySourceChanges( IReadOnlyList changes, @@ -108,8 +107,10 @@ bool requiresFullRescan ) { AssetLoader? loader = m_loader; if (loader is null) + { return; - Dictionary previousIds = CapturePreviousIds(loader, changes); + } + Dictionary previousIDs = CapturePreviousIDs(loader, changes); try { if (requiresFullRescan) @@ -118,7 +119,9 @@ bool requiresFullRescan GetFileSystem().Refresh(); } else + { loader.ApplySourceChanges(changes); + } m_diagnostics.ResolveSourceDatabase(); } catch (Exception exception) @@ -131,30 +134,34 @@ bool requiresFullRescan m_log.Write( LogLevel.Warn, "Asset source refresh failed and was recovered by a full rescan: {0}", - [exception]); + [exception] + ); } catch (Exception recoveryException) { m_log.Write( LogLevel.Error, "Asset source refresh and recovery rescan both failed. Refresh: {0} Recovery: {1}", - [exception, recoveryException]); - m_diagnostics.PublishSourceDatabaseFailure( - exception, - recoveryException); + [exception, recoveryException] + ); + m_diagnostics.PublishSourceDatabaseFailure(exception, recoveryException); } } - AssetChange[] committed = CreateCommittedChanges(loader, changes, previousIds, requiresFullRescan); - InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); + AssetChange[] committed = CreateCommittedChanges(loader, changes, previousIDs, requiresFullRescan); + InvokeObservers(changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); } private void DrainPendingChanges(AssetFileSystem fileSystem) { if (!fileSystem.isWatching) + { return; + } IReadOnlyList pending = fileSystem.WaitForIdle(out bool requiresFullRescan); if (pending.Count > 0 || requiresFullRescan) + { ApplySourceChanges(pending, requiresFullRescan); + } } private AssetChangedEvent[] CreateDeletionEvents( @@ -163,47 +170,52 @@ string sourcePath ) { string prefix = sourcePath + "/"; return fileSystem.GetEntries() - .Where(entry => - string.Equals(entry.assetPath.ToString(), sourcePath, StringComparison.OrdinalIgnoreCase) || - entry.assetPath.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Where(entry => ( + string.Equals(entry.assetPath.ToString(), sourcePath, StringComparison.OrdinalIgnoreCase) + || entry.assetPath.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + )) .OrderBy(static entry => entry.assetPath.ToString().Length) .Select(static entry => new AssetChangedEvent(entry.assetPath.ToString(), WatcherChangeTypes.Deleted)) .DefaultIfEmpty(new AssetChangedEvent(sourcePath, WatcherChangeTypes.Deleted)) .ToArray(); } - private void OnAssetReloaded(AssetObject asset) => InvokeObservers(AssetReloaded, asset); + private void OnAssetReloaded(AssetObject asset) => InvokeObservers(assetReloaded, asset); - private void InvokeObservers( - Action? handlers, - T value - ) { + private void InvokeObservers(Action? handlers) + { if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try { - ((Action)handler)(value); + ((Action)handler)(); } - catch + catch (Exception) { // Observer failures cannot roll back committed manager state. } } } - private void InvokeObservers(Action? handlers) - { + private void InvokeObservers( + Action? handlers, + T value + ) { if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try { - ((Action)handler)(); + ((Action)handler)(value); } - catch + catch (Exception) { // Observer failures cannot roll back committed manager state. } @@ -214,11 +226,11 @@ private AssetFileSystem GetFileSystem() { EnsureAccess(); return isInitialized && m_fileSystem is not null - ? m_fileSystem - : throw new InvalidOperationException("AssetPipeline is not initialized."); + ? m_fileSystem + : throw new InvalidOperationException("AssetPipeline is not initialized."); } - private Dictionary CapturePreviousIds( + private Dictionary CapturePreviousIDs( AssetLoader loader, IReadOnlyList changes ) { @@ -227,10 +239,12 @@ IReadOnlyList changes { AssetChangedEvent change = changes[i]; string path = string.IsNullOrWhiteSpace(change.oldRelativePath) - ? change.relativePath - : change.oldRelativePath; - if (loader.TryGetPersistentId(AssetPath.Parse(path), out Guid id)) + ? change.relativePath + : change.oldRelativePath; + if (loader.TryGetPersistentID(AssetPath.Parse(path), out Guid id)) + { result[path] = id; + } } return result; } @@ -238,11 +252,13 @@ IReadOnlyList changes private AssetChange[] CreateCommittedChanges( AssetLoader loader, IReadOnlyList changes, - IReadOnlyDictionary previousIds, + IReadOnlyDictionary previousIDs, bool requiresFullRescan ) { if (requiresFullRescan && changes.Count == 0) + { return [new AssetChange(AssetChangeKind.StatusChanged, Guid.Empty, AssetPath.Project(string.Empty))]; + } var result = new List(changes.Count); for (int i = 0; i < changes.Count; i++) @@ -251,34 +267,34 @@ bool requiresFullRescan bool moved = change.changeType.HasFlag(WatcherChangeTypes.Renamed); bool deleted = change.changeType.HasFlag(WatcherChangeTypes.Deleted); Guid id = Guid.Empty; - if (!loader.TryGetPersistentId(AssetPath.Parse(change.relativePath), out id)) + if (!loader.TryGetPersistentID(AssetPath.Parse(change.relativePath), out id)) { string previousPath = moved ? change.oldRelativePath : change.relativePath; - _ = previousIds.TryGetValue(previousPath, out id); + _ = previousIDs.TryGetValue(previousPath, out id); } AssetChangeKind kind = moved - ? AssetChangeKind.Moved - : deleted - ? System.IO.File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) - ? AssetChangeKind.Missing - : AssetChangeKind.Removed - : change.changeType.HasFlag(WatcherChangeTypes.Created) - ? AssetChangeKind.Added - : AssetChangeKind.Modified; - result.Add(new AssetChange( - kind, - id, - AssetPath.Parse(change.relativePath), - string.IsNullOrWhiteSpace(change.oldRelativePath) + ? AssetChangeKind.Moved + : deleted + ? File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) + ? AssetChangeKind.Missing + : AssetChangeKind.Removed + : change.changeType.HasFlag(WatcherChangeTypes.Created) + ? AssetChangeKind.Added + : AssetChangeKind.Modified; + result.Add( + new AssetChange( + kind, + id, + AssetPath.Parse(change.relativePath), + string.IsNullOrWhiteSpace(change.oldRelativePath) ? null - : AssetPath.Parse(change.oldRelativePath))); + : AssetPath.Parse(change.oldRelativePath) + ) + ); } return result.ToArray(); } private void PublishMutation(AssetChange change) - => InvokeObservers( - Changed, - new AssetChangeSet(Interlocked.Increment(ref m_revision), [change])); - + => InvokeObservers(changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), [change])); } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs index a7e51f366..919ad6904 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs @@ -4,22 +4,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Ends initial authoring extension discovery and strictly retries dependent imports. @@ -59,16 +58,16 @@ out Type? assetType /// /// The isolated source path. /// - /// + /// /// The resolved persistent identity. /// /// /// when catalog metadata exists. /// - public bool TryGetPersistentId( + public bool TryGetPersistentID( AssetPath path, - out Guid persistentId - ) => GetLoader().TryGetPersistentId(path, out persistentId); + out Guid persistentID + ) => GetLoader().TryGetPersistentID(path, out persistentID); /// /// Tries to get a catalog snapshot by source-relative path. @@ -90,7 +89,7 @@ out AssetInfo? info /// /// Tries to get a catalog snapshot by persistent identity. /// - /// + /// /// The persistent asset identity. /// /// @@ -100,9 +99,9 @@ out AssetInfo? info /// when the identity is cataloged. /// public bool TryGetInfo( - Guid persistentId, + Guid persistentID, out AssetInfo? info - ) => GetLoader().TryGetInfo(persistentId, out info); + ) => GetLoader().TryGetInfo(persistentID, out info); private sealed class AssetCatalogParticipant(AssetPipeline owner) : IAssemblyCatalogParticipant { @@ -119,12 +118,14 @@ public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) { ArgumentNullException.ThrowIfNull(catalog); if (!owner.isInitialized || owner.m_catalogParticipantRegistration is null) + { return new AssetCatalogTransaction(null, false, AssetImportHealthSnapshot.empty); + } owner.EnsureOwnerThread(); AssetImportHealthSnapshot existingFailures = owner.m_loader!.CaptureWritableImportHealth(); bool ownsCandidate = owner.m_sourceMountCandidate is null; AssetSourceMountTransaction candidate = owner.m_sourceMountCandidate - ?? owner.PrepareSourceMounts(owner.sourceMounts); + ?? owner.PrepareSourceMounts(owner.sourceMounts); return new AssetCatalogTransaction(candidate, ownsCandidate, existingFailures); } } @@ -153,17 +154,21 @@ public void Activate() { candidate.candidateLoader.ActivateExtensionDiscovery(); candidate.candidateLoader.RefreshRegistries(); - IReadOnlyList failures = - candidate.candidateLoader.FindIntroducedImportFailures(existingFailures); + IReadOnlyList failures = candidate.candidateLoader.FindIntroducedImportFailures(existingFailures); if (failures.Count != 0) { - string details = string.Join("; ", failures.Select(static failure => - $"{failure.assetPath}: {failure.diagnostics}")); + string details = string.Join( + "; ", + failures.Select(static failure => $"{failure.assetPath}: {failure.diagnostics}") + ); throw new InvalidDataException( - "The candidate assembly catalog introduced or changed writable Asset import failures: " + details); + "The candidate assembly catalog introduced or changed writable Asset import failures: " + details + ); } if (ownsCandidate) + { candidate.Activate(); + } } m_activated = true; } @@ -175,9 +180,13 @@ public void Complete() { EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Asset catalog transaction has not been activated."); + } if (ownsCandidate) + { candidate!.Complete(); + } m_finished = true; } @@ -187,17 +196,22 @@ public void Complete() public void Rollback() { if (m_finished) + { return; + } if (ownsCandidate) + { candidate!.Rollback(); + } m_finished = true; } private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Asset catalog transaction is already finished."); + } } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs index 91f358c8a..72abc0654 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs @@ -4,22 +4,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Loads a canonical asset by isolated source path. @@ -33,11 +32,37 @@ sealed partial class AssetPipeline /// /// The canonical asset instance. /// - public TAsset Load(AssetPath path) where TAsset : AssetObject + public TAsset Load(AssetPath path) + where TAsset : AssetObject { AssetObject? asset = GetLoader().Load(path, typeof(TAsset)); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); + } + + /// + /// Loads a canonical asset by persistent identity. + /// + /// + /// The required asset type. + /// + /// + /// The persistent asset identity. + /// + /// + /// The canonical asset instance. + /// + /// + /// Thrown when no compatible asset can be loaded. + /// + public TAsset Load(Guid persistentID) + where TAsset : AssetObject + { + AssetObject? asset = GetLoader().Load(persistentID, typeof(TAsset)); + return asset as TAsset ?? throw new InvalidOperationException( + $"Asset '{persistentID}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -71,32 +96,12 @@ Type assetType { throw new ArgumentException( $"Asset type '{assetType.FullName}' must derive from '{typeof(AssetObject).FullName}'.", - nameof(assetType)); + nameof(assetType) + ); } return GetLoader().Load(path, assetType) ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{assetType.FullName}'."); - } - - /// - /// Loads a canonical asset by persistent identity. - /// - /// - /// The required asset type. - /// - /// - /// The persistent asset identity. - /// - /// - /// The canonical asset instance. - /// - /// - /// Thrown when no compatible asset can be loaded. - /// - public TAsset Load(Guid persistentId) where TAsset : AssetObject - { - AssetObject? asset = GetLoader().Load(persistentId, typeof(TAsset)); - return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{path}' cannot be loaded as '{assetType.FullName}'." + ); } /// @@ -130,7 +135,7 @@ out TAsset? asset /// /// The required asset type. /// - /// + /// /// The persistent asset identity. /// /// @@ -140,11 +145,11 @@ out TAsset? asset /// when a compatible asset was loaded. /// public bool TryLoad( - Guid persistentId, + Guid persistentID, out TAsset? asset ) where TAsset : AssetObject { - bool success = GetLoader().TryLoad(persistentId, typeof(TAsset), out AssetObject? value); + bool success = GetLoader().TryLoad(persistentID, typeof(TAsset), out AssetObject? value); asset = value as TAsset; return success && asset is not null; } @@ -167,15 +172,15 @@ out TAsset? asset public async ValueTask LoadAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { AssetLoader loader = GetLoader(); AssetObject? asset = await loader .LoadAsync(path, typeof(TAsset), cancellationToken) .ConfigureAwait(false); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -184,7 +189,7 @@ public async ValueTask LoadAsync( /// /// The required asset type. /// - /// + /// /// The persistent asset identity. /// /// @@ -194,17 +199,17 @@ public async ValueTask LoadAsync( /// The canonical asset instance. /// public async ValueTask LoadAsync( - Guid persistentId, + Guid persistentID, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { AssetLoader loader = GetLoader(); AssetObject? asset = await loader - .LoadAsync(persistentId, typeof(TAsset), cancellationToken) + .LoadAsync(persistentID, typeof(TAsset), cancellationToken) .ConfigureAwait(false); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{persistentID}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -225,11 +230,10 @@ public async ValueTask LoadAsync( public async ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { TAsset asset = await LoadAsync(path, cancellationToken).ConfigureAwait(false); - return CreateAssetLease(asset, static () => { }); + return CreateAssetLease(asset, static () => {}); } /// @@ -238,7 +242,7 @@ public async ValueTask> AcquireAsync( /// /// Required asset contract. /// - /// + /// /// Persistent asset identity. /// /// @@ -248,37 +252,12 @@ public async ValueTask> AcquireAsync( /// A lease whose strong reference participates in the existing reachability sweep. /// public async ValueTask> AcquireAsync( - Guid persistentId, + Guid persistentID, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { - TAsset asset = await LoadAsync(persistentId, cancellationToken).ConfigureAwait(false); - return CreateAssetLease(asset, static () => { }); - } - - AssetObject IAssetReferenceResolver.Resolve( - Guid persistentId, - Guid stableTypeId, - string lastKnownPath, - Type expectedType, - string propertyPath - ) { - try - { - return GetLoader().ResolveReference( - persistentId, - stableTypeId, - lastKnownPath, - expectedType); - } - catch (Exception exception) - { - throw new InvalidOperationException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + - $"'{expectedType.FullName}'.", - exception); - } + TAsset asset = await LoadAsync(persistentID, cancellationToken).ConfigureAwait(false); + return CreateAssetLease(asset, static () => {}); } /// @@ -304,8 +283,7 @@ string propertyPath public IReadOnlyList GetDependencies( AssetObject asset, bool recursive = false - ) - => GetLoader().GetDependencies(asset, recursive); + ) => GetLoader().GetDependencies(asset, recursive); /// /// Gets source import dependencies that invalidate an asset artifact. @@ -322,8 +300,7 @@ public IReadOnlyList GetDependencies( public IReadOnlyList GetImportDependencies( AssetObject asset, bool recursive = false - ) - => GetLoader().GetImportDependencies(asset, recursive); + ) => GetLoader().GetImportDependencies(asset, recursive); /// /// Gets an engine-known reference diagnostic snapshot. @@ -336,14 +313,34 @@ public IReadOnlyList GetImportDependencies( /// public AssetReferenceInfo GetReferenceInfo(AssetObject asset) => GetLoader().GetReferenceInfo(asset); + AssetObject IAssetReferenceResolver.Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ) { + try + { + return GetLoader().ResolveReference(persistentID, stableTypeID, lastKnownPath, expectedType); + } + catch (Exception exception) + { + throw new InvalidOperationException( + $"Asset reference '{persistentID:D}' at '{propertyPath}' cannot be resolved as " + + $"'{expectedType.FullName}'.", + exception + ); + } + } + private AssetLoader GetLoader() { EnsureAccess(); _ = m_types.current; AssetLoader loader = isInitialized && m_loader is not null - ? m_loader - : throw new InvalidOperationException("AssetPipeline is not initialized."); + ? m_loader + : throw new InvalidOperationException("AssetPipeline is not initialized."); return loader; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs index 20fa7f55e..c8857d185 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs @@ -4,22 +4,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Imports one source asset from an isolated source mount. @@ -39,8 +38,8 @@ public bool Import(AssetPath path) if (imported) { GetFileSystem().Refresh(); - _ = loader.TryGetPersistentId(path, out Guid persistentId); - PublishMutation(new AssetChange(AssetChangeKind.Modified, persistentId, path)); + _ = loader.TryGetPersistentID(path, out Guid persistentID); + PublishMutation(new AssetChange(AssetChangeKind.Modified, persistentID, path)); } return imported; } @@ -90,8 +89,8 @@ string expectedFingerprint AssetLoader loader = GetLoader(); bool imported = loader.SaveImportSettings(path, settings, expectedFingerprint); GetFileSystem().Refresh(); - _ = loader.TryGetPersistentId(path, out Guid persistentId); - PublishMutation(new AssetChange(AssetChangeKind.Modified, persistentId, path)); + _ = loader.TryGetPersistentID(path, out Guid persistentID); + PublishMutation(new AssetChange(AssetChangeKind.Modified, persistentID, path)); return imported; } @@ -131,16 +130,15 @@ AssetObject asset _ = NormalizeMutationPath(path, nameof(path)); ArgumentNullException.ThrowIfNull(asset); AssetLoader loader = GetLoader(); - bool existed = loader.TryGetPersistentId(path, out _); + bool existed = loader.TryGetPersistentID(path, out _); bool saved = loader.Save(path, asset); if (saved) { GetFileSystem().Refresh(); - _ = loader.TryGetPersistentId(path, out Guid persistentId); - PublishMutation(new AssetChange( - existed ? AssetChangeKind.Modified : AssetChangeKind.Added, - persistentId, - path)); + _ = loader.TryGetPersistentID(path, out Guid persistentID); + PublishMutation( + new AssetChange(existed ? AssetChangeKind.Modified : AssetChangeKind.Added, persistentID, path) + ); } return saved; } @@ -169,7 +167,9 @@ AssetPath target string sourcePath = NormalizeMutationPath(source, nameof(source)); string targetPath = NormalizeMutationPath(target, nameof(target)); if (string.Equals(sourcePath, targetPath, StringComparison.Ordinal)) + { return; + } AssetFileSystem fileSystem = GetFileSystem(); AssetLoader loader = GetLoader(); @@ -177,31 +177,39 @@ AssetPath target { IReadOnlyList pending = fileSystem.WaitForIdle(out bool requiresFullRescan); if (pending.Count > 0 || requiresFullRescan) + { ApplySourceChanges(pending, requiresFullRescan); + } } string absoluteSource = Path.Combine(assetRoot, sourcePath); string absoluteTarget = Path.Combine(assetRoot, targetPath); bool isDirectory = Directory.Exists(absoluteSource); - if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + if (!isDirectory && !File.Exists(absoluteSource)) + { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); - if (Directory.Exists(absoluteTarget) || System.IO.File.Exists(absoluteTarget)) + } + if (Directory.Exists(absoluteTarget) || File.Exists(absoluteTarget)) + { throw new IOException($"Asset move target '{targetPath}' already exists."); - if (System.IO.File.Exists(absoluteTarget + ".imeta")) + } + if (File.Exists(absoluteTarget + ".imeta")) + { throw new IOException($"Asset move target metadata '{targetPath}.imeta' already exists."); + } bool restartWatcher = fileSystem.isWatching; fileSystem.Stop(); Directory.CreateDirectory(Path.GetDirectoryName(absoluteTarget)!); var change = new AssetChangedEvent(targetPath, WatcherChangeTypes.Renamed, sourcePath); - Dictionary previousIds = CapturePreviousIds(loader, [change]); + Dictionary previousIDs = CapturePreviousIDs(loader, [change]); try { MovePhysicalSource(absoluteSource, absoluteTarget, isDirectory); loader.ApplySourceChanges([change]); fileSystem.Refresh(); - AssetChange[] committed = CreateCommittedChanges(loader, [change], previousIds, requiresFullRescan: false); - InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); + AssetChange[] committed = CreateCommittedChanges(loader, [change], previousIDs, requiresFullRescan: false); + InvokeObservers(changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); } catch { @@ -214,7 +222,9 @@ AssetPath target finally { if (restartWatcher) + { fileSystem.Start(); + } } } @@ -238,16 +248,19 @@ public void Delete(AssetPath path) string absoluteSource = Path.Combine(assetRoot, sourcePath); bool isDirectory = Directory.Exists(absoluteSource); - if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + if (!isDirectory && !File.Exists(absoluteSource)) + { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); + } AssetChangedEvent[] changes = CreateDeletionEvents(fileSystem, sourcePath); - Dictionary previousIds = CapturePreviousIds(loader, changes); + Dictionary previousIDs = CapturePreviousIDs(loader, changes); string transactionRoot = Path.Combine( libraryRoot, "AssetDatabase", "Transactions", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); string stagedSource = Path.Combine(transactionRoot, "source"); string sourceMeta = absoluteSource + ".imeta"; string stagedMeta = Path.Combine(transactionRoot, "source.imeta"); @@ -258,11 +271,13 @@ public void Delete(AssetPath path) try { MovePhysicalSource(absoluteSource, stagedSource, isDirectory); - if (System.IO.File.Exists(sourceMeta)) - System.IO.File.Move(sourceMeta, stagedMeta); + if (File.Exists(sourceMeta)) + { + File.Move(sourceMeta, stagedMeta); + } loader.ApplySourceChanges(changes); fileSystem.Refresh(); - committed = CreateCommittedChanges(loader, changes, previousIds, requiresFullRescan: false); + committed = CreateCommittedChanges(loader, changes, previousIDs, requiresFullRescan: false); } catch { @@ -276,10 +291,12 @@ public void Delete(AssetPath path) finally { if (restartWatcher) + { fileSystem.Start(); + } } DeleteTransactionDirectorySafely(transactionRoot); - InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); + InvokeObservers(changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); CollectArtifactsIfDue(loader, force: true); } @@ -309,12 +326,17 @@ public void CreateDirectory(AssetPath path) if (!Directory.Exists(parentPath)) { throw new DirectoryNotFoundException( - $"Asset directory parent '{Path.GetDirectoryName(sourcePath)}' does not exist."); + $"Asset directory parent '{Path.GetDirectoryName(sourcePath)}' does not exist." + ); } - if (Directory.Exists(absolutePath) || System.IO.File.Exists(absolutePath)) + if (Directory.Exists(absolutePath) || File.Exists(absolutePath)) + { throw new IOException($"Asset directory target '{sourcePath}' already exists."); - if (System.IO.File.Exists(absolutePath + ".imeta")) + } + if (File.Exists(absolutePath + ".imeta")) + { throw new IOException($"Asset directory target metadata '{sourcePath}.imeta' already exists."); + } bool restartWatcher = fileSystem.isWatching; fileSystem.Stop(); @@ -328,15 +350,20 @@ public void CreateDirectory(AssetPath path) loader, [change], new Dictionary(StringComparer.OrdinalIgnoreCase), - requiresFullRescan: false); - InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); + requiresFullRescan: false + ); + InvokeObservers(changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); } catch { if (Directory.Exists(absolutePath)) + { Directory.Delete(absolutePath, recursive: true); - if (System.IO.File.Exists(absolutePath + ".imeta")) - System.IO.File.Delete(absolutePath + ".imeta"); + } + if (File.Exists(absolutePath + ".imeta")) + { + File.Delete(absolutePath + ".imeta"); + } loader.Rescan(); fileSystem.Refresh(); throw; @@ -344,7 +371,9 @@ public void CreateDirectory(AssetPath path) finally { if (restartWatcher) + { fileSystem.Start(); + } } } @@ -353,9 +382,13 @@ private string NormalizeMutationPath( string parameterName ) { if (!path.isValid || string.IsNullOrWhiteSpace(path.localPath)) + { throw new ArgumentException("Asset source path is required.", parameterName); - if (path.source != AssetSourceId.project) + } + if (path.source != AssetSourceID.project) + { throw new InvalidOperationException($"Asset source '{path.source}' is read-only."); + } return path.localPath; } @@ -365,9 +398,13 @@ private void MovePhysicalSource( bool isDirectory ) { if (isDirectory) + { Directory.Move(sourcePath, targetPath); + } else - System.IO.File.Move(sourcePath, targetPath); + { + File.Move(sourcePath, targetPath); + } } private void TryRollbackPhysicalMove( @@ -377,12 +414,14 @@ bool isDirectory ) { try { - bool targetExists = isDirectory ? Directory.Exists(targetPath) : System.IO.File.Exists(targetPath); - bool sourceExists = isDirectory ? Directory.Exists(sourcePath) : System.IO.File.Exists(sourcePath); + bool targetExists = isDirectory ? Directory.Exists(targetPath) : File.Exists(targetPath); + bool sourceExists = isDirectory ? Directory.Exists(sourcePath) : File.Exists(sourcePath); if (targetExists && !sourceExists) + { MovePhysicalSource(targetPath, sourcePath, isDirectory); + } } - catch + catch (Exception) { // The following catalog rescan reports any remaining physical conflict. } @@ -394,10 +433,12 @@ string targetPath ) { try { - if (System.IO.File.Exists(targetPath) && !System.IO.File.Exists(sourcePath)) - System.IO.File.Move(targetPath, sourcePath); + if (File.Exists(targetPath) && !File.Exists(sourcePath)) + { + File.Move(targetPath, sourcePath); + } } - catch + catch (Exception) { // The following catalog rescan reports any remaining metadata conflict. } @@ -408,7 +449,7 @@ private void RestoreStagedDeletion( string stagedSource, bool isDirectory ) { - if (isDirectory ? Directory.Exists(stagedSource) : System.IO.File.Exists(stagedSource)) + if (isDirectory ? Directory.Exists(stagedSource) : File.Exists(stagedSource)) { Directory.CreateDirectory(Path.GetDirectoryName(sourcePath)!); MovePhysicalSource(stagedSource, sourcePath, isDirectory); @@ -419,10 +460,12 @@ private void RestoreStagedMetadata( string metaPath, string stagedMetaPath ) { - if (!System.IO.File.Exists(stagedMetaPath)) + if (!File.Exists(stagedMetaPath)) + { return; + } Directory.CreateDirectory(Path.GetDirectoryName(metaPath)!); - System.IO.File.Move(stagedMetaPath, metaPath); + File.Move(stagedMetaPath, metaPath); } private static void DeleteTransactionDirectorySafely(string transactionRoot) @@ -430,7 +473,9 @@ private static void DeleteTransactionDirectorySafely(string transactionRoot) try { if (Directory.Exists(transactionRoot)) + { Directory.Delete(transactionRoot, recursive: true); + } } catch (IOException) { @@ -441,5 +486,4 @@ private static void DeleteTransactionDirectorySafely(string transactionRoot) // Read-only transaction debris must not roll back an already committed deletion. } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs index 45339170e..e211a6574 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs @@ -4,22 +4,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Releases watchers, catalog participants, canonical objects, and rebuildable staging state. @@ -27,7 +26,9 @@ sealed partial class AssetPipeline public void Dispose() { lock (m_lifecycleLock) + { ShutdownLocked(); + } GC.SuppressFinalize(this); } @@ -41,8 +42,8 @@ public void Dispose() private void PruneRetiredObservers() { - RemoveRetiredObservers(Changed, observer => Changed -= observer); - RemoveRetiredObservers(AssetReloaded, observer => AssetReloaded -= observer); + RemoveRetiredObservers(changed, observer => changed -= observer); + RemoveRetiredObservers(assetReloaded, observer => assetReloaded -= observer); } private void RemoveRetiredObservers( @@ -50,11 +51,15 @@ private void RemoveRetiredObservers( Action> remove ) { if (handlers is null) + { return; + } foreach (Delegate observer in handlers.GetInvocationList()) { if (!IsRetiredCollectibleObserver(observer)) + { continue; + } remove((Action)observer); } } @@ -63,15 +68,15 @@ private bool IsRetiredCollectibleObserver(Delegate observer) { Type? declaringType = observer.Method.DeclaringType; Type? targetType = observer.Target?.GetType(); - return IsRetiredCollectibleType(declaringType) || - IsRetiredCollectibleType(targetType); + return IsRetiredCollectibleType(declaringType) + || IsRetiredCollectibleType(targetType); } private bool IsRetiredCollectibleType(Type? type) { - if (type is null || - !type.Assembly.IsCollectible) - { + if (type is null + || !type.Assembly.IsCollectible + ) { return false; } return !m_types.TryGetTypeRef(type, out _); @@ -88,15 +93,21 @@ private void ShutdownLocked() m_shutdown = new LifetimeScope(); if (m_loader is not null) { - m_loader.AssetReloaded -= OnAssetReloaded; + m_loader.assetReloaded -= OnAssetReloaded; m_shutdown.Own(m_loader); } if (m_fileSystem is not null) + { m_shutdown.Own(m_fileSystem); + } if (m_catalogParticipantRegistration is not null) + { m_shutdown.Own(m_catalogParticipantRegistration); + } if (m_failedPreparation is not null) + { m_shutdown.Own(m_failedPreparation); + } } try { @@ -125,16 +136,15 @@ private void FinishShutdown() libraryRoot = string.Empty; artifactRoot = string.Empty; sourceMounts = []; - m_ownerThreadId = 0; + m_ownerThreadID = 0; m_revision = 0; m_reconcileSampleImport = false; m_cacheOptions = default; m_options = default; m_lastArtifactCollectionTimestamp = 0; isInitialized = false; - Changed = null; - AssetReloaded = null; - SourceMountsChanged = null; + changed = null; + assetReloaded = null; + sourceMountsChanged = null; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs index 5e4648b2e..d6d4530c4 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -44,7 +43,7 @@ public sealed partial class AssetPipeline : AssetResidencyProvider, private AssetLoader? m_loader; private AssetFileSystem? m_fileSystem; private IDisposable? m_catalogParticipantRegistration; - private int m_ownerThreadId; + private int m_ownerThreadID; private long m_revision; private AssetCacheOptions m_cacheOptions; private long m_lastArtifactCollectionTimestamp; @@ -54,120 +53,6 @@ public sealed partial class AssetPipeline : AssetResidencyProvider, private LifetimeScope? m_shutdown; private RetirementBarrier? m_shutdownBarrier; - /// - /// Gets whether asset services are initialized. - /// - public bool isInitialized { get; private set; } - - /// - /// Gets the absolute source asset root. - /// - public string assetRoot { get; private set; } = string.Empty; - - /// - /// Gets the absolute root containing rebuildable asset database data. - /// - public string libraryRoot { get; private set; } = string.Empty; - - /// - /// Gets the absolute generated artifact root. - /// - public string artifactRoot { get; private set; } = string.Empty; - - /// - /// Gets the monotonic identity of the current committed asset and source-mount state. - /// - [ScriptingApiIgnore] - public long revision => Interlocked.Read(ref m_revision); - - /// - /// Gets the active isolated source mount snapshot. - /// - [ScriptingApiIgnore] - public IReadOnlyList sourceMounts { get; private set; } = []; - - /// - /// Gets the authoring identity domain shared by canonical assets and addressable source entries. - /// - [ScriptingApiIgnore] - public IdentityAllocator identities => m_identities; - - /// - /// Creates a detached source editor sharing this owner's mounts, native converters and references. - /// - /// - /// A source store that must not outlive this asset pipeline. - /// - [ScriptingApiIgnore] - public AssetSourceStore CreateSourceStore() => new(this, new AssetSerializationServices(m_types, m_serialization, this, null)); - - /// - /// Captures native settings and nested asset dependencies through this explicit authoring owner. - /// - /// - /// Current settings type. - /// - /// - /// Typed settings, never retained by the returned snapshot. - /// - /// - /// Complete stable properties and dependencies without writing or importing an asset. - /// - public AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable - { - EnsureOwnerThread(); - using IDisposable operationScope = AcquireOperation(); - return new AssetSerializationServices(m_types, m_serialization, this, null).CaptureProperties(value); - } - - /// - /// Restores serialized properties to the existing asset object. - /// - /// - /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// Serialized asset object type receiving restored properties. - /// - public void RestoreProperties( - Guid stableTypeId, - byte[] propertyData, - TValue target - ) where TValue : class, ISerializable - { - ArgumentNullException.ThrowIfNull(target); - using IDisposable operationScope = AcquireOperation(); - if (m_types.GetTypeRef(target.GetType()).stableId != stableTypeId) - throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); - m_serialization.Decode(propertyData, reader => - { - reader.RestoreProperties(target); - return true; - }, AssetSerializationContext.Create(this)); - } - - /// - /// Occurs after an asset database transaction has committed. - /// - public event Action? Changed; - - /// - /// Occurs after a canonical loaded asset has been updated in place. - /// - public event Action? AssetReloaded; - - /// - /// Occurs after a complete isolated source-mount generation is atomically replaced. - /// - [ScriptingApiIgnore] - public event Action? SourceMountsChanged; - /// /// Creates one isolated authoring or deployed-runtime asset pipeline. /// @@ -183,12 +68,12 @@ TValue target /// /// The identity allocator that owns every canonical asset in this pipeline. /// - /// - /// The explicitly owned router receiving asset pipeline diagnostics. - /// /// /// The diagnostic hub that owns source database and asset processing reports. /// + /// + /// The explicitly owned router receiving asset pipeline diagnostics. + /// /// /// The asset source, artifact and watcher configuration. /// @@ -212,9 +97,13 @@ AssetPipelineOptions options ArgumentNullException.ThrowIfNull(diagnostics); ArgumentNullException.ThrowIfNull(logs); if (string.IsNullOrWhiteSpace(options.assetRoot)) + { throw new ArgumentException("Asset root is required.", nameof(options)); + } if (string.IsNullOrWhiteSpace(options.libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(options)); + } m_types = types; m_generations = modules.generations; @@ -227,17 +116,19 @@ AssetPipelineOptions options lock (m_lifecycleLock) { AssetSourceMount[] mounts = options.sourceMounts?.ToArray() - ?? [new AssetSourceMount(AssetSourceId.project, options.assetRoot, isReadOnly: false)]; - AssetSourceMount projectMount = mounts.SingleOrDefault(static mount => mount.id == AssetSourceId.project) - ?? throw new ArgumentException("A project asset source mount is required.", nameof(options)); + ?? [new AssetSourceMount(AssetSourceID.project, options.assetRoot, isReadOnly: false)]; + AssetSourceMount projectMount = mounts.SingleOrDefault(static mount => mount.id == AssetSourceID.project) + ?? throw new ArgumentException("A project asset source mount is required.", nameof(options)); if (projectMount.isReadOnly && options.mode != AssetPipelineMode.RuntimeArtifacts) + { throw new ArgumentException("The project asset source mount must be writable.", nameof(options)); - assetRoot = projectMount.rootPath; - libraryRoot = Path.GetFullPath(options.libraryRoot); + } + this.assetRoot = projectMount.rootPath; + this.libraryRoot = Path.GetFullPath(options.libraryRoot); DeleteCandidateCatalogRoots(libraryRoot); - artifactRoot = Path.Combine(libraryRoot, "Artifacts"); - sourceMounts = Array.AsReadOnly(mounts.ToArray()); - AssetLoader loader = new( + this.artifactRoot = Path.Combine(libraryRoot, "Artifacts"); + this.sourceMounts = Array.AsReadOnly(mounts.ToArray()); + var loader = new AssetLoader( types, serialization, identities, @@ -246,39 +137,45 @@ AssetPipelineOptions options mounts, libraryRoot, options.sourcePolicy, - runtimeArtifactsOnly: options.mode == AssetPipelineMode.RuntimeArtifacts); + runtimeArtifactsOnly: options.mode == AssetPipelineMode.RuntimeArtifacts + ); if (options.deferUnavailableExtensions) + { loader.DeferUnavailableExtensions(); - AssetFileSystem fileSystem = new( + } + var fileSystem = new AssetFileSystem( mounts, autoStart: false, options.fileWatcherFlushDelayMs, options.sourcePolicy, requireWritableProject: options.mode == AssetPipelineMode.Authoring, identities, - persistentIdentityResolver: path => - loader.TryGetPersistentId(path, out Guid persistentId) - ? persistentId - : null, - activateIdentities: true); - loader.AssetReloaded += OnAssetReloaded; + persistentIdentityResolver: path => ( + loader.TryGetPersistentID(path, out Guid persistentID) + ? persistentID + : null + ), + activateIdentities: true + ); + loader.assetReloaded += OnAssetReloaded; m_loader = loader; m_fileSystem = fileSystem; - m_ownerThreadId = Environment.CurrentManagedThreadId; + m_ownerThreadID = Environment.CurrentManagedThreadId; m_revision = 0; m_cacheOptions = options.cacheOptions; m_options = options with { sourceMounts = mounts }; m_lastArtifactCollectionTimestamp = 0; - isInitialized = true; + this.isInitialized = true; try { loader.Rescan(); CollectArtifactsIfDue(loader, force: true); fileSystem.Refresh(); if (options.enableFileSystemWatcher && options.mode == AssetPipelineMode.Authoring) + { fileSystem.Start(); - m_catalogParticipantRegistration = modules.RegisterCatalogParticipant( - m_catalogParticipant); + } + m_catalogParticipantRegistration = modules.RegisterCatalogParticipant(m_catalogParticipant); } catch { @@ -288,6 +185,123 @@ AssetPipelineOptions options } } + /// + /// Gets whether asset services are initialized. + /// + public bool isInitialized { get; private set; } + + /// + /// Gets the absolute source asset root. + /// + public string assetRoot { get; private set; } = string.Empty; + + /// + /// Gets the absolute root containing rebuildable asset database data. + /// + public string libraryRoot { get; private set; } = string.Empty; + + /// + /// Gets the absolute generated artifact root. + /// + public string artifactRoot { get; private set; } = string.Empty; + + /// + /// Gets the monotonic identity of the current committed asset and source-mount state. + /// + [ScriptingApiIgnore] + public long revision => Interlocked.Read(ref m_revision); + + /// + /// Gets the active isolated source mount snapshot. + /// + [ScriptingApiIgnore] + public IReadOnlyList sourceMounts { get; private set; } = []; + + /// + /// Gets the authoring identity domain shared by canonical assets and addressable source entries. + /// + [ScriptingApiIgnore] + public IdentityAllocator identities => m_identities; + + /// + /// Occurs after an asset database transaction has committed. + /// + public event Action? changed; + + /// + /// Occurs after a canonical loaded asset has been updated in place. + /// + public event Action? assetReloaded; + + /// + /// Occurs after a complete isolated source-mount generation is atomically replaced. + /// + [ScriptingApiIgnore] + public event Action? sourceMountsChanged; + + /// + /// Creates a detached source editor sharing this owner's mounts, native converters and references. + /// + /// + /// A source store that must not outlive this asset pipeline. + /// + [ScriptingApiIgnore] + public AssetSourceStore CreateSourceStore() => new(this, new AssetSerializationServices(m_types, m_serialization, this, null)); + + /// + /// Captures native settings and nested asset dependencies through this explicit authoring owner. + /// + /// + /// Current settings type. + /// + /// + /// Typed settings, never retained by the returned snapshot. + /// + /// + /// Complete stable properties and dependencies without writing or importing an asset. + /// + public AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable + { + EnsureOwnerThread(); + using IDisposable operationScope = AcquireOperation(); + return new AssetSerializationServices(m_types, m_serialization, this, null).CaptureProperties(value); + } + + /// + /// Restores serialized properties to the existing asset object. + /// + /// + /// Serialized asset object type receiving restored properties. + /// + /// + /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The existing target that receives the validated result. + /// + public void RestoreProperties( + Guid stableTypeID, + byte[] propertyData, + TValue target + ) where TValue : class, ISerializable + { + ArgumentNullException.ThrowIfNull(target); + using IDisposable operationScope = AcquireOperation(); + if (m_types.GetTypeRef(target.GetType()).stableID != stableTypeID) + { + throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } + m_serialization.Decode(propertyData, reader => + { + reader.RestoreProperties(target); + return true; + }, AssetSerializationContext.Create(this)); + } + /// /// Waits until queued source watcher changes have been processed. /// @@ -298,7 +312,9 @@ public void WaitForIdle() AssetFileSystem fileSystem = GetFileSystem(); IReadOnlyList changes = fileSystem.WaitForIdle(out bool requiresFullRescan); if (changes.Count > 0 || requiresFullRescan) + { ApplySourceChanges(changes, requiresFullRescan); + } GetLoader().WaitForIdle(); CollectArtifactsIfDue(GetLoader(), force: true); } @@ -314,26 +330,35 @@ private void EnsureAccess() { m_generations.EnsureRetirementSafe(); if (m_generations.state == GenerationState.Faulted) + { m_generations.EnsureReady("access Asset Pipeline"); + } if (m_shutdown is not null || m_failedPreparation is not null) + { throw new InvalidOperationException("The Asset Pipeline is retiring and cannot accept operations."); + } } private void EnsureOwnerThread() { EnsureInitializationThread(); if (m_sampleImport is not null) + { throw new InvalidOperationException("Asset mutations are deferred until the pending sample import finishes."); + } } private void EnsureInitializationThread() { if (!isInitialized) + { throw new InvalidOperationException("AssetPipeline is not initialized."); - if (Environment.CurrentManagedThreadId != m_ownerThreadId) + } + if (Environment.CurrentManagedThreadId != m_ownerThreadID) { throw new InvalidOperationException( - "Asset database mutations must run on the thread that initialized AssetPipeline."); + "Asset database mutations must run on the thread that initialized AssetPipeline." + ); } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs index 22fbd6490..83b3ba93d 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs @@ -9,7 +9,6 @@ public enum AssetPipelineMode /// Reconciles writable source files and produces immutable artifacts. /// Authoring, - /// /// Loads a read-only deployed catalog and its content-addressed artifacts without source files. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs index ec6f311b9..48f3187a2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets.Pipeline; namespace Inno.Assets.Pipeline; @@ -75,9 +74,13 @@ public static AssetPipelineOptions Create( string libraryRoot ) { if (string.IsNullOrWhiteSpace(assetRoot)) + { throw new ArgumentException("Asset root is required.", nameof(assetRoot)); + } if (string.IsNullOrWhiteSpace(libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(libraryRoot)); + } return new AssetPipelineOptions { @@ -87,7 +90,7 @@ string libraryRoot enableFileSystemWatcher = true, fileWatcherFlushDelayMs = 80, sourcePolicy = AssetSourcePolicy.defaultPolicy, - sourceMounts = [new AssetSourceMount(Inno.Assets.AssetSourceId.project, assetRoot, isReadOnly: false)], + sourceMounts = [new AssetSourceMount(AssetSourceID.project, assetRoot, isReadOnly: false)], cacheOptions = AssetCacheOptions.CreateDefault() }; } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs index 09669ad80..7ba72313c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs @@ -9,13 +9,12 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetSourceMountRecovery( AssetPipeline owner, AssetSourceMountTransaction transaction -) - : IReferenceRecoveryParticipant +) : IReferenceRecoveryParticipant { /// /// Keeps the previous loader and its canonical instances intact until provisional publication. /// - public void PrepareForActivation() { } + public void PrepareForActivation() {} /// /// Publishes the candidate identity domain before shared reference slots are resolved. @@ -34,13 +33,18 @@ public void Validate(IReadOnlyList changes) { ReferenceResolution result = change.resolution; if (result.state is ReferenceResolutionState.Invalid or ReferenceResolutionState.TypeMismatch) + { throw new InvalidDataException(result.diagnostic ?? "Asset recovery has an invalid identity."); - if (result.state == ReferenceResolutionState.Missing && - transaction.candidateLoader.TryGetInfo(result.descriptor.targetPersistentId, out AssetInfo? info) && - info!.status == AssetImportStatus.Imported && - !transaction.candidateLoader.IsSourceBackedTypeUnavailable( - result.descriptor.targetPersistentId)) - throw new InvalidDataException($"Imported asset '{info.assetPath}' could not recover its canonical state: {result.diagnostic}"); + } + if (result.state == ReferenceResolutionState.Missing + && transaction.candidateLoader.TryGetInfo(result.descriptor.targetPersistentID, out AssetInfo? info) + && info!.status == AssetImportStatus.Imported + && !transaction.candidateLoader.IsSourceBackedTypeUnavailable(result.descriptor.targetPersistentID) + ) { + throw new InvalidDataException( + $"Imported asset '{info.assetPath}' could not recover its canonical state: {result.diagnostic}" + ); + } } } @@ -61,5 +65,5 @@ public void Complete() /// /// Finishes compensation without decoding old objects through candidate serializers. /// - public void RestorePreviousState() { } + public void RestorePreviousState() {} } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs index f571efd7a..06c22b313 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs @@ -3,9 +3,9 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Scripting.Api; -using Inno.References; using Inno.Core.Execution; +using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -32,32 +32,12 @@ long generation this.catalogCandidate = catalogCandidate; this.candidateFileSystem = candidateFileSystem; m_recovery = new ReferenceRecoveryTransaction( - ReferenceCatalog.Create(generation, [candidateLoader]), previousStates, - [new AssetSourceMountRecovery(owner, this)]); + ReferenceCatalog.Create(generation, [candidateLoader]), + previousStates, + [new AssetSourceMountRecovery(owner, this)] + ); } - internal AssetCatalogCandidate catalogCandidate { get; } - - internal AssetLoader candidateLoader => catalogCandidate.loader; - - internal AssetFileSystem candidateFileSystem { get; } - - internal AssetLoader? previousLoader { get; set; } - - internal AssetFileSystem? previousFileSystem { get; set; } - - internal IReadOnlyList? previousMounts { get; set; } - - internal AssetPipelineOptions previousOptions { get; set; } - - internal bool isActivated { get; set; } - - internal bool isFinished { get; set; } - - internal LifetimeScope? retirement { get; set; } - - internal RetirementBarrier retirementBarrier { get; } = new("Asset source-mount generation"); - /// /// Gets the complete isolated mount snapshot represented by this candidate. /// @@ -102,12 +82,14 @@ public IReadOnlyList GetFileSystemEntries(bool includeDirectorie /// Thrown when no compatible candidate asset exists. /// [ScriptingApiIgnore] - public TAsset Load(AssetPath path) where TAsset : AssetObject + public TAsset Load(AssetPath path) + where TAsset : AssetObject { EnsureOpen(); AssetObject? asset = candidateLoader.Load(path, typeof(TAsset)); return asset as TAsset ?? throw new InvalidOperationException( - $"Candidate asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Candidate asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -131,20 +113,20 @@ out AssetInfo? info return candidateLoader.TryGetInfo(path, out info); } - /// + /// [ScriptingApiIgnore] public ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName ) { EnsureOpen(); - return candidateLoader.AcquireArtifact(persistentId, outputName); + return candidateLoader.AcquireArtifact(persistentID, outputName); } /// /// Tries to resolve one named candidate artifact. /// - /// + /// /// Candidate asset identity. /// /// @@ -158,12 +140,12 @@ string outputName /// [ScriptingApiIgnore] public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact ) { EnsureOpen(); - return candidateLoader.TryGetArtifact(persistentId, outputName, out artifact); + return candidateLoader.TryGetArtifact(persistentID, outputName, out artifact); } /// @@ -174,7 +156,9 @@ public void Activate() { EnsureOpen(); if (m_activationComplete) + { return; + } if (!m_prepared) { m_prepared = true; @@ -198,7 +182,9 @@ public void Complete() { EnsureOpen(); if (!m_activationComplete) + { throw new InvalidOperationException("A source-mount candidate must finish activation before completion."); + } try { m_recovery.Complete(); @@ -223,9 +209,13 @@ public void Complete() public void Rollback() { if (isFinished) + { return; + } if (m_terminalFailure is not null) + { throw m_terminalFailure; + } if (!m_prepared) { m_prepared = true; @@ -252,11 +242,34 @@ public void Dispose() GC.SuppressFinalize(this); } + internal AssetCatalogCandidate catalogCandidate { get; } + + internal AssetLoader candidateLoader => catalogCandidate.loader; + + internal AssetFileSystem candidateFileSystem { get; } + + internal AssetLoader? previousLoader { get; set; } + + internal AssetFileSystem? previousFileSystem { get; set; } + + internal IReadOnlyList? previousMounts { get; set; } + + internal AssetPipelineOptions previousOptions { get; set; } + + internal bool isActivated { get; set; } + + internal bool isFinished { get; set; } + + internal LifetimeScope? retirement { get; set; } + + internal RetirementBarrier retirementBarrier { get; } = new("Asset source-mount generation"); + private void EnsureOpen() { if (m_terminalFailure is not null) + { throw m_terminalFailure; - if (isFinished) - throw new ObjectDisposedException(nameof(AssetSourceMountTransaction)); + } + ObjectDisposedException.ThrowIf(isFinished, this); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs b/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs index 44ce3b1e0..9e0866fbe 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Diagnostics; namespace Inno.Assets.Pipeline; @@ -7,9 +6,11 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetPipelineDiagnosticPublisher { private const string C_SOURCE_DATABASE_GROUP = "Asset Source Database"; - private static readonly DiagnosticSource S_SOURCE_DATABASE = new( + + private static readonly DiagnosticSource SOURCE_DATABASE = new( "inno.assets.pipeline/source-database", - C_SOURCE_DATABASE_GROUP); + C_SOURCE_DATABASE_GROUP + ); private readonly DiagnosticHub m_diagnostics; @@ -26,14 +27,16 @@ Exception recoveryException ArgumentNullException.ThrowIfNull(refreshException); ArgumentNullException.ThrowIfNull(recoveryException); m_diagnostics.Set( - S_SOURCE_DATABASE, + SOURCE_DATABASE, [ Diagnostic.Error( "ASSET-SOURCE", - $"Incremental refresh failed: {refreshException.Message} " + - $"Recovery rescan failed: {recoveryException.Message}") - ]); + $"Incremental refresh failed: {refreshException.Message} " + + $"Recovery rescan failed: {recoveryException.Message}" + ) + ] + ); } - internal void ResolveSourceDatabase() => m_diagnostics.Clear(S_SOURCE_DATABASE); + internal void ResolveSourceDatabase() => m_diagnostics.Clear(SOURCE_DATABASE); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs new file mode 100644 index 000000000..2eb1bab58 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs @@ -0,0 +1,34 @@ +namespace Inno.Assets.Pipeline; + +/// +/// Contains detached authoring bytes and conflict-detection state. +/// +public sealed class AssetSourceSnapshot +{ + private readonly byte[] m_bytes; + + internal AssetSourceSnapshot( + byte[] bytes, + string hash, + bool readOnly + ) { + m_bytes = bytes; + this.contentHash = hash; + this.isReadOnly = readOnly; + } + + /// + /// Gets a copy of the captured native source bytes. + /// + public byte[] bytes => (byte[])m_bytes.Clone(); + + /// + /// Gets the source fingerprint required by a subsequent save. + /// + public string contentHash { get; } + + /// + /// Gets whether the installation source cannot be edited in place. + /// + public bool isReadOnly { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs index 28b76541c..1bfb51d6a 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs @@ -50,7 +50,8 @@ public AssetSourceSnapshot Read(AssetPath path) /// /// Native source bytes, with no canonical asset mutation. /// - public byte[] Encode(TAsset asset) where TAsset : AssetObject => NativeAssetSourceSerialization.Export(asset, m_serialization); + public byte[] Encode(TAsset asset) + where TAsset : AssetObject => NativeAssetSourceSerialization.Export(asset, m_serialization); /// /// Restores a detached native value using current-generation asset references. @@ -64,8 +65,9 @@ public AssetSourceSnapshot Read(AssetPath path) /// /// A detached value; referenced assets remain canonical read-only inputs. /// - public TAsset Decode(ReadOnlySpan bytes) where TAsset : AssetObject - => NativeAssetSourceSerialization.Import(bytes, m_serialization, out _); + public TAsset Decode(ReadOnlySpan bytes) + where TAsset : AssetObject + => NativeAssetSourceSerialization.Import(bytes, m_serialization, out _); /// /// Atomically saves bytes after checking the source fingerprint; import is a separate operation. @@ -90,18 +92,38 @@ public string Save( ArgumentNullException.ThrowIfNull(bytes); AssetSourceMount mount = Mount(path); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed assets are read-only. Copy the asset to the project before editing."); + } string destination = mount.Resolve(path.localPath); bool exists = File.Exists(destination); if (expectedHash is null ? exists : !exists || Hash(File.ReadAllBytes(destination)) != expectedHash) - throw new IOException("The asset source changed externally. Draft and history are retained; reload or save a project copy explicitly."); + { + throw new IOException( + "The asset source changed externally. Draft and history are retained; reload or save a project copy explicitly." + ); + } if (expectedHash is null) + { AtomicFile.WriteAllBytes(destination, bytes, overwrite: false); + } else + { ReplaceExisting(destination, bytes, expectedHash); + } return Hash(bytes); } + private AssetSourceMount Mount(AssetPath path) + { + if (!path.isValid) + { + throw new ArgumentException("A valid mounted asset path is required.", nameof(path)); + } + return m_assets.sourceMounts.SingleOrDefault(mount => mount.id == path.source) + ?? throw new InvalidOperationException($"Asset source mount '{path.source}' is unavailable."); + } + private static void ReplaceExisting( string destination, byte[] bytes, @@ -118,53 +140,20 @@ string expectedHash { string conflict = destination + ".external-conflict-" + token; File.Move(replaced, conflict, overwrite: false); - throw new IOException($"A concurrent external edit was preserved at '{conflict}'. Resolve both versions before saving again."); + throw new IOException( + $"A concurrent external edit was preserved at '{conflict}'. Resolve both versions before saving again." + ); } File.Delete(replaced); } finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } - private AssetSourceMount Mount(AssetPath path) - { - if (!path.isValid) - throw new ArgumentException("A valid mounted asset path is required.", nameof(path)); - return m_assets.sourceMounts.SingleOrDefault(mount => mount.id == path.source) - ?? throw new InvalidOperationException($"Asset source mount '{path.source}' is unavailable."); - } - private static string Hash(ReadOnlySpan bytes) => Convert.ToHexString(SHA256.HashData(bytes)); } - -/// -/// Contains detached authoring bytes and conflict-detection state. -/// -public sealed class AssetSourceSnapshot -{ - private readonly byte[] m_bytes; - internal AssetSourceSnapshot( - byte[] bytes, - string hash, - bool readOnly - ) { - m_bytes = bytes; - contentHash = hash; - isReadOnly = readOnly; - } - /// - /// Gets a copy of the captured native source bytes. - /// - public byte[] bytes => (byte[])m_bytes.Clone(); - /// - /// Gets the source fingerprint required by a subsequent save. - /// - public string contentHash { get; } - /// - /// Gets whether the installation source cannot be edited in place. - /// - public bool isReadOnly { get; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs b/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs index 6931e9e82..7abaa0db3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs +++ b/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; @@ -23,8 +22,11 @@ public static byte[] EncodeNative(AssetObject asset) { ArgumentNullException.ThrowIfNull(asset); if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException( - "Encoding an authoring asset requires an asset pipeline execution context."); + "Encoding an authoring asset requires an asset pipeline execution context." + ); + } return pipeline.CreateSourceStore().Encode(asset); } @@ -40,12 +42,16 @@ public static byte[] EncodeNative(AssetObject asset) /// /// A detached asset value that can be edited without publishing it. /// - public static TAsset DecodeNative(byte[] bytes) where TAsset : AssetObject + public static TAsset DecodeNative(byte[] bytes) + where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(bytes); if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException( - "Decoding an authoring asset requires an asset pipeline execution context."); + "Decoding an authoring asset requires an asset pipeline execution context." + ); + } return pipeline.CreateSourceStore().Decode(bytes); } @@ -61,12 +67,16 @@ public static TAsset DecodeNative(byte[] bytes) where TAsset : AssetObje /// /// Native properties, stable type identity and automatically collected dependencies. /// - public static AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable + public static AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable { if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException("Capturing authoring settings requires an asset pipeline execution context."); + } return pipeline.CaptureProperties(value); } + /// /// Creates or replaces a writable project asset source and imports the committed result. /// @@ -93,7 +103,8 @@ AssetObject asset if (AssetExecutionContext.current is not AssetPipeline pipeline) { throw new InvalidOperationException( - "Editor asset mutation requires an authoring asset pipeline execution context."); + "Editor asset mutation requires an authoring asset pipeline execution context." + ); } return pipeline.Save(path, asset); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs index 767836c04..d11e660c7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs @@ -4,15 +4,9 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetArtifactManifest : ISerializable { - [SerializableProperty] internal string key { get; set; } = string.Empty; - [SerializableProperty] internal AssetArtifactOutputData[] outputs { get; set; } = []; -} + [SerializableProperty] + internal string key { get; set; } = string.Empty; -internal struct AssetArtifactOutputData -{ - [SerializableProperty] internal string name { get; set; } - [SerializableProperty] internal string fileName { get; set; } - [SerializableProperty] internal string contentHash { get; set; } - [SerializableProperty] internal long length { get; set; } - [SerializableProperty] internal AssetDeploymentScope deploymentScope { get; set; } + [SerializableProperty] + internal AssetArtifactOutputData[] outputs { get; set; } = []; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs new file mode 100644 index 000000000..2e68a4f93 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs @@ -0,0 +1,21 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetArtifactOutputData +{ + [SerializableProperty] + internal string name { get; set; } + + [SerializableProperty] + internal string fileName { get; set; } + + [SerializableProperty] + internal string contentHash { get; set; } + + [SerializableProperty] + internal long length { get; set; } + + [SerializableProperty] + internal AssetDeploymentScope deploymentScope { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs index abab51d83..530fdabe9 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Security.Cryptography; using System.Text; - +using System.Threading; using Inno.Assets; using Inno.Core.IO; using Inno.Core.Serialization; @@ -42,12 +42,16 @@ internal AssetArtifactKey Commit( SerializationGeneration? serialization = null ) { if (outputs.Count == 0) + { throw new InvalidOperationException("An artifact bundle requires at least one output."); + } AssetArtifactKey key = ComputeKey(inputFingerprint, outputs, authoringOutputs); string finalPath = GetBundlePath(key); if (Directory.Exists(finalPath)) + { return key; + } string stagingPath = Path.Combine(m_stagingRoot, Guid.NewGuid().ToString("N")); string outputRoot = Path.Combine(stagingPath, "outputs"); @@ -59,8 +63,13 @@ internal AssetArtifactKey Commit( .Select(( pair, index - ) => WriteOutput(outputRoot, pair.Key, pair.Value, index, - authoringOutputs?.Contains(pair.Key) == true ? AssetDeploymentScope.AuthoringOnly : AssetDeploymentScope.Runtime)) + ) => WriteOutput( + outputRoot, + pair.Key, + pair.Value, + index, + authoringOutputs?.Contains(pair.Key) == true ? AssetDeploymentScope.AuthoringOnly : AssetDeploymentScope.Runtime + )) .ToArray(); var manifest = new AssetArtifactManifest { @@ -69,7 +78,8 @@ internal AssetArtifactKey Commit( }; AtomicFile.WriteAllBytes( Path.Combine(stagingPath, "manifest"), - serialization is null ? m_serialization.Serialize(manifest) : serialization.Serialize(manifest)); + serialization is null ? m_serialization.Serialize(manifest) : serialization.Serialize(manifest) + ); Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); try @@ -85,7 +95,9 @@ internal AssetArtifactKey Commit( catch { if (Directory.Exists(stagingPath)) + { Directory.Delete(stagingPath, recursive: true); + } throw; } } @@ -94,8 +106,7 @@ internal bool TryGet( AssetArtifactKey key, string outputName, out AssetArtifactInfo? artifact - ) - => TryGet(key, outputName, serialization: null, out artifact); + ) => TryGet(key, outputName, serialization: null, out artifact); internal bool TryGet( AssetArtifactKey key, @@ -105,17 +116,25 @@ out AssetArtifactInfo? artifact ) { artifact = null; if (key.isEmpty || string.IsNullOrWhiteSpace(outputName)) + { return false; + } AssetArtifactManifest? manifest = ReadManifest(key, serialization); AssetArtifactOutputData output = manifest?.outputs.FirstOrDefault(value => string.Equals(value.name, outputName, StringComparison.Ordinal)) ?? default; if (string.IsNullOrEmpty(output.fileName)) + { return false; + } string path = PathBoundary.Resolve(Path.Combine(GetBundlePath(key), "outputs"), output.fileName); if (!IOFile.Exists(path)) + { return false; + } if (new FileInfo(path).Length != output.length) + { throw new InvalidDataException($"Artifact '{key}/{output.name}' has an invalid output length."); + } artifact = new AssetArtifactInfo(key, output.name, output.contentHash, output.length); return true; } @@ -123,23 +142,23 @@ out AssetArtifactInfo? artifact internal byte[] Read( AssetArtifactKey key, string outputName - ) { - return TryGet(key, outputName, out AssetArtifactInfo? artifact) && artifact is not null - ? ReadOutputBytes(artifact, ResolveOutput(artifact)) - : []; - } + ) => TryGet(key, outputName, out AssetArtifactInfo? artifact) && artifact is not null + ? ReadOutputBytes(artifact, ResolveOutput(artifact)) + : []; internal Func CreateReadFactory(AssetArtifactInfo artifact) { string path = ResolveOutput(artifact); return () => { - FileStream input = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); try { if (input.Length != artifact.length - || Convert.ToHexString(SHA256.HashData(input)) != artifact.contentHash) + || Convert.ToHexString(SHA256.HashData(input)) != artifact.contentHash + ) { throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' failed integrity validation."); + } input.Position = 0; return input; } @@ -151,16 +170,6 @@ internal Func CreateReadFactory(AssetArtifactInfo artifact) }; } - private string ResolveOutput(AssetArtifactInfo artifact) - { - AssetArtifactManifest manifest = ReadManifest(artifact.key, serialization: null) - ?? throw new InvalidDataException($"Artifact bundle '{artifact.key}' has no manifest."); - AssetArtifactOutputData output = manifest.outputs.Single(value => value.name == artifact.outputName); - if (output.length != artifact.length || output.contentHash != artifact.contentHash) - throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' changed its metadata."); - return PathBoundary.Resolve(Path.Combine(GetBundlePath(artifact.key), "outputs"), output.fileName); - } - internal int Collect( IReadOnlySet reachableKeys, TimeSpan gracePeriod, @@ -171,12 +180,14 @@ long maximumSizeBytes long totalSize = bundles.Sum(static bundle => bundle.size); int removed = 0; foreach (ArtifactDirectory bundle in bundles - .Where(bundle => !reachableKeys.Contains(bundle.key)) - .OrderBy(static bundle => bundle.lastWriteUtc)) - { + .Where(bundle => !reachableKeys.Contains(bundle.key)) + .OrderBy(static bundle => bundle.lastWriteUtc) + ) { bool exceededLimit = maximumSizeBytes > 0 && totalSize > maximumSizeBytes; if (!exceededLimit && bundle.lastWriteUtc > cutoff) + { continue; + } try { Directory.Delete(bundle.path, recursive: true); @@ -195,68 +206,112 @@ long maximumSizeBytes return removed; } + internal AssetArtifactKey ExportRuntime( + AssetArtifactKey key, + AssetArtifactStore destination, + SerializationGeneration? serialization, + CancellationToken cancellationToken + ) { + AssetArtifactManifest manifest = ReadManifest(key, serialization) + ?? throw new InvalidDataException($"Artifact bundle '{key}' has no manifest."); + var outputs = new Dictionary>(StringComparer.Ordinal); + foreach (AssetArtifactOutputData output in manifest.outputs) + { + cancellationToken.ThrowIfCancellationRequested(); + if (output.deploymentScope == AssetDeploymentScope.AuthoringOnly) + { + continue; + } + string path = PathBoundary.Resolve(Path.Combine(GetBundlePath(key), "outputs"), output.fileName); + byte[] bytes = ReadOutputBytes(new AssetArtifactInfo(key, output.name, output.contentHash, output.length), path); + outputs.Add(output.name, bytes); + } + return destination.Commit("Inno.RuntimeProjection:" + key.value, outputs, serialization: serialization); + } + + private string ResolveOutput(AssetArtifactInfo artifact) + { + AssetArtifactManifest manifest = ReadManifest(artifact.key, serialization: null) + ?? throw new InvalidDataException($"Artifact bundle '{artifact.key}' has no manifest."); + AssetArtifactOutputData output = manifest.outputs.Single(value => value.name == artifact.outputName); + if (output.length != artifact.length || output.contentHash != artifact.contentHash) + { + throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' changed its metadata."); + } + return PathBoundary.Resolve(Path.Combine(GetBundlePath(artifact.key), "outputs"), output.fileName); + } + private AssetArtifactManifest? ReadManifest( AssetArtifactKey key, SerializationGeneration? serialization ) { string path = Path.Combine(GetBundlePath(key), "manifest"); if (!IOFile.Exists(path)) + { return null; + } try { byte[] bytes = IOFile.ReadAllBytes(path); AssetArtifactManifest manifest = serialization is null - ? m_serialization.Deserialize(bytes) - : serialization.Deserialize(bytes); + ? m_serialization.Deserialize(bytes) + : serialization.Deserialize(bytes); if (!string.Equals(manifest.key, key.value, StringComparison.Ordinal) || manifest.outputs.Length == 0 - || manifest.outputs.Any(static output => + || manifest.outputs.Any(static output => ( string.IsNullOrWhiteSpace(output.name) || string.IsNullOrWhiteSpace(output.fileName) || output.fileName is "." or ".." || output.fileName.IndexOfAny(['/', '\\', ':']) >= 0 || !IsContentHash(output.contentHash) - || output.length < 0 || !Enum.IsDefined(output.deploymentScope))) - { + || output.length < 0 || !Enum.IsDefined(output.deploymentScope) + )) + ) { throw new InvalidDataException($"Artifact bundle '{key}' has an invalid manifest contract."); } if (manifest.outputs.Select(static output => output.name).Distinct(StringComparer.Ordinal).Count() != manifest.outputs.Length - || manifest.outputs.Select(static output => output.fileName).Distinct(StringComparer.Ordinal).Count() != manifest.outputs.Length) + || manifest.outputs + .Select(static output => output.fileName) + .Distinct(StringComparer.Ordinal) + .Count() != manifest.outputs.Length + ) { throw new InvalidDataException($"Artifact bundle '{key}' contains duplicate output identities."); + } return manifest; } catch (Exception exception) when (exception is IOException - or InvalidDataException - or InvalidOperationException - or ArgumentException) + or InvalidDataException + or InvalidOperationException + or ArgumentException) { throw new InvalidDataException( $"Artifact bundle '{key}' has a corrupt current-format manifest.", - exception); + exception + ); } } private ArtifactDirectory[] EnumerateBundles() { - var result = new List(); + List result = []; foreach (string firstLevel in Directory.EnumerateDirectories(m_root)) { if (string.Equals(Path.GetFileName(firstLevel), ".staging", StringComparison.Ordinal)) + { continue; + } foreach (string secondLevel in Directory.EnumerateDirectories(firstLevel)) { foreach (string bundlePath in Directory.EnumerateDirectories(secondLevel)) { string key = Path.GetFileName(bundlePath).ToUpperInvariant(); if (key.Length != C_SHA256_HEX_LENGTH) + { continue; + } long size = Directory.EnumerateFiles(bundlePath, "*", SearchOption.AllDirectories) .Sum(static path => new FileInfo(path).Length); - result.Add(new ArtifactDirectory( - key, - bundlePath, - Directory.GetLastWriteTimeUtc(bundlePath), - size)); + result.Add(new ArtifactDirectory(key, bundlePath, Directory.GetLastWriteTimeUtc(bundlePath), size)); } } } @@ -267,7 +322,9 @@ private string GetBundlePath(AssetArtifactKey key) { string value = key.value; if (key.isEmpty) + { throw new ArgumentException("Artifact keys must contain a SHA-256 value.", nameof(key)); + } return Path.Combine(m_root, value[..2].ToLowerInvariant(), value[2..4].ToLowerInvariant(), value); } @@ -296,12 +353,12 @@ private static AssetArtifactKey ComputeKey( IReadOnlyDictionary> outputs, IReadOnlySet? authoringOutputs ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Append(hash, "Inno.AssetArtifact"); Append(hash, inputFingerprint); foreach (KeyValuePair> output in outputs - .OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - { + .OrderBy(static pair => pair.Key, StringComparer.Ordinal) + ) { Append(hash, output.Key); Append(hash, authoringOutputs?.Contains(output.Key) == true ? "authoring" : "runtime"); hash.AppendData(output.Value.Span); @@ -309,45 +366,31 @@ private static AssetArtifactKey ComputeKey( return new AssetArtifactKey(Convert.ToHexString(hash.GetHashAndReset())); } - internal AssetArtifactKey ExportRuntime( - AssetArtifactKey key, - AssetArtifactStore destination, - SerializationGeneration? serialization, - System.Threading.CancellationToken cancellationToken - ) { - AssetArtifactManifest manifest = ReadManifest(key, serialization) - ?? throw new InvalidDataException($"Artifact bundle '{key}' has no manifest."); - var outputs = new Dictionary>(StringComparer.Ordinal); - foreach (AssetArtifactOutputData output in manifest.outputs) - { - cancellationToken.ThrowIfCancellationRequested(); - if (output.deploymentScope == AssetDeploymentScope.AuthoringOnly) - continue; - string path = PathBoundary.Resolve(Path.Combine(GetBundlePath(key), "outputs"), output.fileName); - byte[] bytes = ReadOutputBytes(new AssetArtifactInfo(key, output.name, output.contentHash, output.length), path); - outputs.Add(output.name, bytes); - } - return destination.Commit("Inno.RuntimeProjection:" + key.value, outputs, serialization: serialization); - } - private static bool IsContentHash(string value) { if (string.IsNullOrEmpty(value) || value.Length != C_SHA256_HEX_LENGTH) + { return false; + } foreach (char digit in value) + { if (digit is not (>= '0' and <= '9') and not (>= 'A' and <= 'F')) + { return false; + } + } return true; } private static byte[] ReadOutputBytes( AssetArtifactInfo artifact, string path - ) - { + ) { byte[] bytes = IOFile.ReadAllBytes(path); if (bytes.LongLength != artifact.length || Convert.ToHexString(SHA256.HashData(bytes)) != artifact.contentHash) + { throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' failed integrity validation."); + } return bytes; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs index 0c5feb6f8..bae2444be 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs @@ -10,8 +10,8 @@ namespace Inno.Assets.Pipeline; /// public sealed class AssetArtifactWriter { - private readonly Dictionary> m_outputs = - new(StringComparer.Ordinal); + private readonly Dictionary> m_outputs = new(StringComparer.Ordinal); + private readonly List m_diagnostics = []; private readonly HashSet m_authoringOutputs = new(StringComparer.Ordinal); @@ -24,30 +24,39 @@ public sealed class AssetArtifactWriter /// /// The output content. /// - /// - /// Cancellation for the write operation. - /// /// /// Whether runtime packages retain this output. /// + /// + /// Cancellation for the write operation. + /// /// /// A completed operation after the output has been staged. /// public ValueTask WriteAsync( string outputName, ReadOnlyMemory bytes, - CancellationToken cancellationToken = default, - AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime + AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime, + CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) + { throw new ArgumentException("An artifact output name is required.", nameof(outputName)); - if (!Enum.IsDefined(deploymentScope) || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state")) + } + if (!Enum.IsDefined(deploymentScope) + || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state") + ) { throw new ArgumentException("The output deployment scope is invalid.", nameof(deploymentScope)); + } if (!m_outputs.TryAdd(outputName, bytes.ToArray())) + { throw new InvalidOperationException($"Artifact output '{outputName}' was written more than once."); + } if (deploymentScope == AssetDeploymentScope.AuthoringOnly) + { m_authoringOutputs.Add(outputName); + } return ValueTask.CompletedTask; } @@ -60,7 +69,9 @@ public ValueTask WriteAsync( public void ReportDiagnostic(string message) { if (string.IsNullOrWhiteSpace(message)) + { throw new ArgumentException("A diagnostic message is required.", nameof(message)); + } m_diagnostics.Add(message); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs index 230b303c3..d9aa78465 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs @@ -49,7 +49,9 @@ public void Commit() { EnsureOpen(); if (m_committed) + { throw new InvalidOperationException("The Asset catalog candidate has already been committed."); + } loader.PromoteCatalogTo(m_activeLibraryRoot); m_committed = true; } @@ -60,24 +62,27 @@ public void Commit() public void Dispose() { if (m_disposed) + { return; + } DeleteCandidateRoot(m_candidateLibraryRoot); m_disposed = true; GC.SuppressFinalize(this); } - private void EnsureOpen() - { - ObjectDisposedException.ThrowIf(m_disposed, this); - } + private void EnsureOpen() => ObjectDisposedException.ThrowIf(m_disposed, this); private static void DeleteCandidateRoot(string candidateLibraryRoot) { if (!Directory.Exists(candidateLibraryRoot)) + { return; + } Directory.Delete(candidateLibraryRoot, recursive: true); string? parent = Directory.GetParent(candidateLibraryRoot)?.FullName; if (parent is not null && Directory.Exists(parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) + { Directory.Delete(parent); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs index cc834c6ff..b9cb72110 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs @@ -9,7 +9,6 @@ public enum AssetDeploymentScope /// The asset is deployed and must produce a named runtime artifact output. /// Runtime, - /// /// The asset exists only for authoring workflows and is omitted from deployed catalogs. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs index 28abbde7b..3c67e43b0 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs @@ -1,7 +1,6 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -14,12 +13,15 @@ public sealed class AssetExportContext internal AssetExportContext( TypeCatalog types, SerializationRegistry serialization, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { - this.types = types ?? throw new ArgumentNullException(nameof(types)); - this.serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - this.artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - services = new AssetSerializationServices(types, serialization, references: null, dependencySink: null); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(artifacts); + this.types = types; + this.serialization = serialization; + this.artifacts = artifacts; + this.services = new AssetSerializationServices(types, serialization, references: null, dependencySink: null); } /// @@ -43,5 +45,5 @@ Inno.Assets.IAssetArtifactLookup artifacts /// Gets the owner-bound immutable outputs used to reconstruct editable sources. /// [ScriptingApiIgnore] - public Inno.Assets.IAssetArtifactLookup artifacts { get; } + public IAssetArtifactLookup artifacts { get; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs index d37a9ed2d..f19cd1656 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Text; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -20,6 +19,7 @@ public sealed class AssetImportContext private readonly List m_importDependencies = []; private readonly Func m_dependencyResolver; private readonly Func> m_sourceReader; + private readonly IAssetArtifactLookup m_artifacts; /// /// Creates an asset import context. @@ -36,7 +36,7 @@ public sealed class AssetImportContext /// /// The deterministic source hash. /// - /// + /// /// The persistent identity assigned to the source asset. /// /// @@ -62,7 +62,7 @@ internal AssetImportContext( string absolutePath, ReadOnlyMemory sourceBytes, string sourceHash, - Guid persistentId, + Guid persistentID, TypeCatalog types, SerializationRegistry serialization, IAssetReferenceResolver references, @@ -70,45 +70,32 @@ internal AssetImportContext( Func> sourceReader, IAssetArtifactLookup artifacts ) { - assetPath = AssetPath.Parse(relativePath ?? throw new ArgumentNullException(nameof(relativePath))); - this.absolutePath = absolutePath ?? throw new ArgumentNullException(nameof(absolutePath)); + ArgumentNullException.ThrowIfNull(relativePath); + ArgumentNullException.ThrowIfNull(absolutePath); + ArgumentNullException.ThrowIfNull(sourceHash); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(references); + ArgumentNullException.ThrowIfNull(dependencyResolver); + ArgumentNullException.ThrowIfNull(sourceReader); + ArgumentNullException.ThrowIfNull(artifacts); + this.assetPath = AssetPath.Parse(relativePath); + this.absolutePath = absolutePath; this.sourceBytes = sourceBytes; - this.sourceHash = sourceHash ?? throw new ArgumentNullException(nameof(sourceHash)); - this.persistentId = persistentId; - this.types = types ?? throw new ArgumentNullException(nameof(types)); - this.serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - this.references = references ?? throw new ArgumentNullException(nameof(references)); - services = new AssetSerializationServices( + this.sourceHash = sourceHash; + this.persistentID = persistentID; + this.types = types; + this.serialization = serialization; + this.references = references; + this.services = new AssetSerializationServices( types, serialization, references, - dependency => m_runtimeDependencies.Add(dependency)); - m_dependencyResolver = dependencyResolver - ?? throw new ArgumentNullException(nameof(dependencyResolver)); - m_sourceReader = sourceReader ?? throw new ArgumentNullException(nameof(sourceReader)); - m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - } - - private readonly IAssetArtifactLookup m_artifacts; - - /// - /// Acquires an immutable dependency output and records its invalidation dependency automatically. - /// - /// - /// Persistent dependency identity. - /// - /// - /// Stable named output protocol. - /// - /// - /// A caller-owned lease that must be disposed after reading. - /// - public ArtifactLease AcquireArtifact( - Guid assetId, - string outputName - ) { - DependsOnArtifact(assetId); - return m_artifacts.AcquireArtifact(assetId, outputName); + dependency => m_runtimeDependencies.Add(dependency) + ); + m_dependencyResolver = dependencyResolver; + m_sourceReader = sourceReader; + m_artifacts = artifacts; } /// @@ -134,7 +121,7 @@ string outputName /// /// Gets the persistent identity assigned to the source asset. /// - public Guid persistentId { get; } + public Guid persistentID { get; } /// /// Gets the type catalog bound to the active import generation. @@ -170,16 +157,33 @@ string outputName /// public string extension => Path.GetExtension(assetPath.localPath).ToLowerInvariant(); + /// + /// Acquires an immutable dependency output and records its invalidation dependency automatically. + /// + /// + /// Persistent dependency identity. + /// + /// + /// Stable named output protocol. + /// + /// + /// A caller-owned lease that must be disposed after reading. + /// + public ArtifactLease AcquireArtifact( + Guid assetID, + string outputName + ) { + DependsOnArtifact(assetID); + return m_artifacts.AcquireArtifact(assetID, outputName); + } + /// /// Reads the source bytes as UTF-8 text. /// /// /// The decoded text without an optional byte-order mark. /// - public string ReadUtf8Text() - { - return DecodeUtf8(sourceBytes.Span); - } + public string ReadUtf8Text() => DecodeUtf8(sourceBytes.Span); /// /// Reads another source from the same candidate mount snapshot and records it as an import dependency. @@ -199,7 +203,9 @@ public string ReadUtf8Text() public ReadOnlyMemory ReadSourceBytes(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("An import source dependency path is required.", nameof(path)); + } DependsOnSource(path); return m_sourceReader(path.ToString()); } @@ -215,12 +221,6 @@ public ReadOnlyMemory ReadSourceBytes(AssetPath path) /// public string ReadSourceUtf8Text(AssetPath path) => DecodeUtf8(ReadSourceBytes(path).Span); - private static string DecodeUtf8(ReadOnlySpan bytes) - { - string text = Encoding.UTF8.GetString(bytes); - return text.Length > 0 && text[0] == '\uFEFF' ? text[1..] : text; - } - /// /// Declares a direct runtime dependency by isolated source path. /// @@ -230,7 +230,9 @@ private static string DecodeUtf8(ReadOnlySpan bytes) public void DependsOnAsset(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("A runtime dependency path is required.", nameof(path)); + } m_runtimeDependencyPaths.Add(path.ToString()); } @@ -240,10 +242,7 @@ public void DependsOnAsset(AssetPath path) /// /// The persistent dependency descriptor. /// - public void DependsOnAsset(AssetDependency dependency) - { - m_runtimeDependencies.Add(dependency); - } + public void DependsOnAsset(AssetDependency dependency) => m_runtimeDependencies.Add(dependency); /// /// Resolves and declares a strongly typed runtime asset dependency during import. @@ -272,8 +271,9 @@ public TAsset ResolveDependency(AssetPath path) DependsOnAsset(path); AssetObject? resolved = m_dependencyResolver(normalized, typeof(TAsset)); return resolved as TAsset - ?? throw new InvalidOperationException( - $"Asset dependency '{normalized}' cannot be resolved as '{typeof(TAsset).FullName}'."); + ?? throw new InvalidOperationException( + $"Asset dependency '{normalized}' cannot be resolved as '{typeof(TAsset).FullName}'." + ); } /// @@ -285,27 +285,29 @@ public TAsset ResolveDependency(AssetPath path) public void DependsOnSource(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("An import source dependency path is required.", nameof(path)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Source, - path.ToString(), - string.Empty)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Source, path.ToString(), string.Empty) + ); } /// /// Declares an imported artifact that invalidates this imported asset. /// - /// + /// /// The persistent identity of the artifact owner. /// - public void DependsOnArtifact(Guid persistentId) + public void DependsOnArtifact(Guid persistentID) { - if (persistentId == Guid.Empty) - throw new ArgumentException("An artifact dependency identity is required.", nameof(persistentId)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Artifact, - persistentId.ToString("D"), - string.Empty)); + if (persistentID == Guid.Empty) + { + throw new ArgumentException("An artifact dependency identity is required.", nameof(persistentID)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Artifact, persistentID.ToString("D"), string.Empty) + ); } /// @@ -322,17 +324,23 @@ public void DependsOnCustomInput( string fingerprint ) { if (string.IsNullOrWhiteSpace(key)) + { throw new ArgumentException("A custom dependency key is required.", nameof(key)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Custom, - key, - fingerprint ?? string.Empty)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Custom, key, fingerprint ?? string.Empty) + ); } internal IReadOnlyList runtimeDependencyPaths => m_runtimeDependencyPaths; internal IReadOnlyList runtimeDependencies => m_runtimeDependencies; internal IReadOnlyList importDependencies => m_importDependencies; + private static string DecodeUtf8(ReadOnlySpan bytes) + { + string text = Encoding.UTF8.GetString(bytes); + return text.Length > 0 && text[0] == '\uFEFF' ? text[1..] : text; + } } internal enum AssetImportDependencyKind diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs index 249935e1d..19b274ac0 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs @@ -16,19 +16,18 @@ public sealed class AssetImportExtensionUnavailableException : InvalidOperationE /// /// The stable extension protocol identity. /// - /// + /// /// The required implementation's stable identity. /// public AssetImportExtensionUnavailableException( string extensionKind, - string extensionId - ) - : base($"Required authoring extension '{extensionKind}/{extensionId}' is unavailable. Source and last-good artifacts are retained.") + string extensionID + ) : base($"Required authoring extension '{extensionKind}/{extensionID}' is unavailable. Source and last-good artifacts are retained.") { ArgumentException.ThrowIfNullOrWhiteSpace(extensionKind); - ArgumentException.ThrowIfNullOrWhiteSpace(extensionId); + ArgumentException.ThrowIfNullOrWhiteSpace(extensionID); this.extensionKind = extensionKind; - this.extensionId = extensionId; + this.extensionID = extensionID; } /// @@ -39,5 +38,5 @@ string extensionId /// /// Gets the required implementation's stable identity. /// - public string extensionId { get; } + public string extensionID { get; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs index 06c8db1ca..eef36a930 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs @@ -13,8 +13,7 @@ namespace Inno.Assets.Pipeline; /// public sealed class AssetImportHealthSnapshot { - private static readonly AssetImportHealthSnapshot S_EMPTY = new( - new HashSet()); + private static readonly AssetImportHealthSnapshot EMPTY = new(new HashSet()); private readonly IReadOnlySet m_failures; @@ -24,12 +23,12 @@ internal AssetImportHealthSnapshot(IReadOnlySet f m_failures = failures; } - internal IReadOnlySet failures => m_failures; - /// /// Gets the immutable snapshot used when no Asset Pipeline generation is active. /// - public static AssetImportHealthSnapshot empty => S_EMPTY; + public static AssetImportHealthSnapshot empty => EMPTY; + + internal IReadOnlySet failures => m_failures; } /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs new file mode 100644 index 000000000..3513c38f2 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Assets.Pipeline; + +internal readonly struct AssetImportProduct( + AssetObject asset, + IReadOnlyDictionary> outputs, + IReadOnlyList diagnostics, + IReadOnlySet authoringOutputs, + AssetDeploymentScope? deploymentScope +) { + internal AssetObject asset { get; } = asset ?? throw new ArgumentNullException(nameof(asset)); + internal IReadOnlyDictionary> outputs { get; } = outputs; + internal IReadOnlyList diagnostics { get; } = diagnostics; + internal IReadOnlySet authoringOutputs { get; } = authoringOutputs; + internal AssetDeploymentScope? deploymentScope { get; } = deploymentScope; + + internal ReadOnlyMemory runtimePayload + => outputs.TryGetValue("runtime", out ReadOnlyMemory bytes) + ? bytes + : ReadOnlyMemory.Empty; +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs index 9c5322a49..62c0c71ea 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs @@ -2,49 +2,25 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; using Inno.Core.Serialization; namespace Inno.Assets.Pipeline; -/// -/// Declares the immutable protocol identity of an automatically discovered asset importer. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetImporterAttribute : Attribute -{ - /// - /// Creates importer discovery metadata. - /// - /// - /// Globally stable importer protocol identifier. - /// - public AssetImporterAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id.Trim(); - } - - /// - /// Gets the globally stable importer protocol identifier. - /// - public string id { get; } -} - /// /// Defines metadata shared by automatically discovered asset importers. /// public abstract class AssetImporter { - private string? m_importerId; + private string? m_importerID; /// /// Gets the stable importer implementation identifier. /// - public string importerId => m_importerId - ?? throw new InvalidOperationException( - $"Asset importer '{GetType().FullName}' has not been bound to discovery metadata."); + public string importerID + => m_importerID + ?? throw new InvalidOperationException( + $"Asset importer '{GetType().FullName}' has not been bound to discovery metadata." + ); /// /// Gets whether imported assets are deployed or retained only for authoring workflows. @@ -74,21 +50,23 @@ internal abstract ValueTask ImportInternalAsync( AssetImportContext context, CancellationToken cancellationToken ); + internal abstract ValueTask?> ExportInternalAsync( AssetExportContext context, AssetObject asset, CancellationToken cancellationToken ); - internal void BindImporterId(string id) + internal void BindImporterID(string id) { ArgumentException.ThrowIfNullOrWhiteSpace(id); - if (m_importerId is not null && !string.Equals(m_importerId, id, StringComparison.Ordinal)) + if (m_importerID is not null && !string.Equals(m_importerID, id, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Asset importer '{GetType().FullName}' cannot be bound to more than one protocol ID."); + $"Asset importer '{GetType().FullName}' cannot be bound to more than one protocol ID." + ); } - m_importerId = id; + m_importerID = id; } } @@ -98,7 +76,8 @@ internal void BindImporterId(string id) /// /// The concrete imported asset type. /// -public abstract class AssetImporter : AssetImporter where TAsset : AssetObject +public abstract class AssetImporter : AssetImporter + where TAsset : AssetObject { /// /// Gets the runtime asset type accepted by this importer implementation. @@ -145,8 +124,7 @@ CancellationToken cancellationToken AssetExportContext context, TAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(null); + ) => ValueTask.FromResult?>(null); internal sealed override async ValueTask ImportInternalAsync( AssetImportContext context, @@ -163,26 +141,9 @@ CancellationToken cancellationToken CancellationToken cancellationToken ) { if (asset is TAsset typed) + { return ExportAsync(context, typed, cancellationToken); + } return ValueTask.FromResult?>(null); } } - -internal readonly struct AssetImportProduct( - AssetObject asset, - IReadOnlyDictionary> outputs, - IReadOnlyList diagnostics, - IReadOnlySet authoringOutputs, - AssetDeploymentScope? deploymentScope -) { - internal AssetObject asset { get; } = asset ?? throw new ArgumentNullException(nameof(asset)); - internal IReadOnlyDictionary> outputs { get; } = outputs; - internal IReadOnlyList diagnostics { get; } = diagnostics; - internal IReadOnlySet authoringOutputs { get; } = authoringOutputs; - internal AssetDeploymentScope? deploymentScope { get; } = deploymentScope; - - internal ReadOnlyMemory runtimePayload - => outputs.TryGetValue("runtime", out ReadOnlyMemory bytes) - ? bytes - : ReadOnlyMemory.Empty; -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs new file mode 100644 index 000000000..4051891f7 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Declares the immutable protocol identity of an automatically discovered asset importer. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetImporterAttribute : Attribute +{ + /// + /// Creates importer discovery metadata. + /// + /// + /// Globally stable importer protocol identifier. + /// + public AssetImporterAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id.Trim(); + } + + /// + /// Gets the globally stable importer protocol identifier. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs index 0ac52b0fc..413583160 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Creates an isolated source-mount and catalog candidate without changing the active catalog. @@ -55,7 +54,8 @@ public AssetCatalogCandidate PrepareCatalogCandidate( libraryRoot, "AssetDatabase", "Candidates", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); AssetLoader? candidateLoader = null; try { @@ -69,7 +69,8 @@ public AssetCatalogCandidate PrepareCatalogCandidate( mounts, libraryRoot, candidateLibraryRoot, - sourcePolicy ?? m_sourcePolicy); + sourcePolicy ?? m_sourcePolicy + ); candidateLoader.m_identitiesActive = false; candidateLoader.m_deferUnavailableExtensions = true; candidateLoader.m_preserveInitialExtensionDiscovery = m_deferUnavailableExtensions; @@ -81,24 +82,14 @@ public AssetCatalogCandidate PrepareCatalogCandidate( { candidateLoader?.Dispose(); if (Directory.Exists(candidateLibraryRoot)) + { Directory.Delete(candidateLibraryRoot, recursive: true); + } throw; } }); } - internal void PromoteCatalogTo(string destinationLibraryRoot) - => Execute(() => - { - if (m_sourceMetadataStage is not null) - { - m_sourceMetadataStage.Commit(() => m_catalog.PromoteTo(destinationLibraryRoot)); - m_sourceMetadataStage = null; - } - else - m_catalog.PromoteTo(destinationLibraryRoot); - }); - /// /// Tries to get a catalog snapshot by isolated source path. /// @@ -128,7 +119,7 @@ out AssetInfo? info /// /// Tries to get a catalog snapshot by persistent identity. /// - /// + /// /// The stable persistent identity used for lookup. /// /// @@ -138,12 +129,14 @@ out AssetInfo? info /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool TryGetInfo( - Guid persistentId, + Guid persistentID, out AssetInfo? info ) { - AssetInfo? result = Execute(() => m_recordsById.TryGetValue(persistentId, out AssetRecord? record) + AssetInfo? result = Execute(() => ( + m_recordsByID.TryGetValue(persistentID, out AssetRecord? record) ? CreateInfo(record) - : null); + : null + )); info = result; return result is not null; } @@ -154,23 +147,23 @@ out AssetInfo? info /// /// The isolated source path. /// - /// + /// /// The resolved identity. /// /// /// when catalog metadata exists. /// - public bool TryGetPersistentId( + public bool TryGetPersistentID( AssetPath path, - out Guid persistentId + out Guid persistentID ) { if (!TryNormalizeCatalogPath(path, out string normalized)) { - persistentId = Guid.Empty; + persistentID = Guid.Empty; return false; } - Guid result = Execute(() => FindRecordLocked(normalized)?.persistentId ?? Guid.Empty); - persistentId = result; + Guid result = Execute(() => FindRecordLocked(normalized)?.persistentID ?? Guid.Empty); + persistentID = result; return result != Guid.Empty; } @@ -214,6 +207,20 @@ public IReadOnlyList GetLoadedPaths() .ThenBy(static path => path.localPath, StringComparer.Ordinal) .ToArray()); + internal void PromoteCatalogTo(string destinationLibraryRoot) + => Execute(() => + { + if (m_sourceMetadataStage is not null) + { + m_sourceMetadataStage.Commit(() => m_catalog.PromoteTo(destinationLibraryRoot)); + m_sourceMetadataStage = null; + } + else + { + m_catalog.PromoteTo(destinationLibraryRoot); + } + }); + private void LoadCatalogLocked() { AssetMeta[] catalogEntries; @@ -224,41 +231,47 @@ private void LoadCatalogLocked() catch (Exception exception) { if (m_diagnostics.PublishCatalogFailure(exception)) + { m_log.Write(LogLevel.Error, "Asset catalog load failed: {0}", [exception]); + } throw; } for (int i = 0; i < catalogEntries.Length; i++) + { MergeCatalogMetaLocked(catalogEntries[i]); + } foreach (AssetSourceMount mount in m_mounts.Values) { foreach (string metaPath in Directory.GetFiles( - mount.rootPath, - "*" + C_META_POSTFIX, - SearchOption.AllDirectories)) - { + mount.rootPath, + "*" + C_META_POSTFIX, + SearchOption.AllDirectories + )) { string localMeta = Path.GetRelativePath(mount.rootPath, metaPath).Replace('\\', '/'); - string relative = new AssetPath( - mount.id, - localMeta[..^C_META_POSTFIX.Length]).ToString(); + string relative = new AssetPath(mount.id, localMeta[..^C_META_POSTFIX.Length]).ToString(); string sourcePath = GetSourcePath(relative); if (Directory.Exists(sourcePath)) + { continue; + } try { AssetSourceMeta sourceMeta = m_serialization.Deserialize( - ReadMetadata(metaPath) ?? throw new IOException("Source metadata is no longer available.")); + ReadMetadata(metaPath) ?? throw new IOException("Source metadata is no longer available.") + ); if (sourceMeta.persistentId != Guid.Empty) { - AssetRecord? existing = FindRecordByIdWithoutLoading(sourceMeta.persistentId); - if (existing is not null && - !string.Equals(existing.relativePath, relative, StringComparison.OrdinalIgnoreCase) && - IOFile.Exists(GetSourcePath(existing.relativePath))) - { + AssetRecord? existing = FindRecordByIDWithoutLoading(sourceMeta.persistentId); + if (existing is not null + && !string.Equals(existing.relativePath, relative, StringComparison.OrdinalIgnoreCase) + && IOFile.Exists(GetSourcePath(existing.relativePath)) + ) { if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source '{relative}' duplicates persistent ID '{sourceMeta.persistentId}'."); + $"Read-only source '{relative}' duplicates persistent ID '{sourceMeta.persistentId}'." + ); } sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); @@ -283,25 +296,32 @@ private void LoadCatalogLocked() m_recordsByPath.TryGetValue(relativePath, out AssetRecord? record); string metaPath = GetMetaPath(relativePath); if (!TryReadSourceMeta(metaPath, out AssetSourceMeta sourceMeta)) + { return record; + } if (sourceMeta.persistentId == Guid.Empty) + { return record; - if (record is not null && record.persistentId == sourceMeta.persistentId) + } + if (record is not null && record.persistentID == sourceMeta.persistentId) + { return record; - if (record is not null && record.persistentId != Guid.Empty) + } + if (record is not null && record.persistentID != Guid.Empty) { // The source sidecar owns path identity. A catalog entry at the same path can be // historical after an interrupted save or catalog promotion and must not replace it. RetireRecordLocked( record, - $"Source '{relativePath}' now declares persistent id '{sourceMeta.persistentId}'."); + $"Source '{relativePath}' now declares persistent id '{sourceMeta.persistentId}'." + ); record = null; } - if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? tombstone) && - tombstone.meta.isTombstone) - { + if (m_recordsByID.TryGetValue(sourceMeta.persistentId, out AssetRecord? tombstone) + && tombstone.meta.isTombstone + ) { tombstone.relativePath = relativePath; - tombstone.persistentId = sourceMeta.persistentId; + tombstone.persistentID = sourceMeta.persistentId; tombstone.meta = new AssetMeta { relativePath = relativePath, @@ -312,24 +332,24 @@ record = null; AddOrReplaceRecordLocked(tombstone); return tombstone; } - if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? sameId) && - !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase)) - { - if (IOFile.Exists(GetSourcePath(sameId.relativePath)) || - Directory.Exists(GetSourcePath(sameId.relativePath))) - { + if (m_recordsByID.TryGetValue(sourceMeta.persistentId, out AssetRecord? sameID) + && !string.Equals(sameID.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + ) { + if (IOFile.Exists(GetSourcePath(sameID.relativePath)) + || Directory.Exists(GetSourcePath(sameID.relativePath)) + ) { sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); } else { - HandleRenameLocked(sameId.relativePath, relativePath); - return sameId; + HandleRenameLocked(sameID.relativePath, relativePath); + return sameID; } } - record = m_recordsById.GetValueOrDefault(sourceMeta.persistentId) ?? record ?? new AssetRecord(); + record = m_recordsByID.GetValueOrDefault(sourceMeta.persistentId) ?? record ?? new AssetRecord(); record.relativePath = relativePath; - record.persistentId = sourceMeta.persistentId; + record.persistentID = sourceMeta.persistentId; if (record.meta.isTombstone || record.meta.persistentId == Guid.Empty) { record.meta = new AssetMeta @@ -346,21 +366,22 @@ record = null; private void AddOrReplaceRecordLocked(AssetRecord record) { - if (record.persistentId == Guid.Empty) + if (record.persistentID == Guid.Empty) { m_recordsByPath[record.relativePath] = record; return; } - if (m_recordsById.TryGetValue(record.persistentId, out AssetRecord? sameId) && - !ReferenceEquals(sameId, record) && - !string.Equals(sameId.relativePath, record.relativePath, StringComparison.OrdinalIgnoreCase)) - { + if (m_recordsByID.TryGetValue(record.persistentID, out AssetRecord? sameID) + && !ReferenceEquals(sameID, record) + && !string.Equals(sameID.relativePath, record.relativePath, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException( - $"Asset persistent id '{record.persistentId}' is used by both " + - $"'{sameId.relativePath}' and '{record.relativePath}'."); + $"Asset persistent id '{record.persistentID}' is used by both " + + $"'{sameID.relativePath}' and '{record.relativePath}'." + ); } m_recordsByPath[record.relativePath] = record; - m_recordsById[record.persistentId] = record; + m_recordsByID[record.persistentID] = record; } private void RebindTombstoneLocked( @@ -379,26 +400,32 @@ private void RemoveRecordLocked( bool removeGeneratedFiles = true ) { m_recordsByPath.Remove(record.relativePath); - if (record.persistentId != Guid.Empty) + if (record.persistentID != Guid.Empty) { - m_recordsById.Remove(record.persistentId); - m_runtimeGraph.RemoveNode(record.persistentId); + m_recordsByID.Remove(record.persistentID); + m_runtimeGraph.RemoveNode(record.persistentID); } m_importGraph.RemoveNode(record.relativePath); if (removeGeneratedFiles) + { DeleteIfExists(GetMetaPath(record.relativePath)); + } } private Type? ResolveRecordType(AssetRecord? record) { if (record is null) + { return null; + } if (record.asset is not null) + { return record.asset.GetType(); - TypeRef typeRef = new(record.stableTypeId); + } + var typeRef = new TypeRef(record.stableTypeID); return m_types.TryResolve(typeRef, out Type? type) && typeof(AssetObject).IsAssignableFrom(type) - ? type - : m_importers.FindById(record.meta.importerId)?.targetAssetType; + ? type + : m_importers.FindByID(record.meta.importerId)?.targetAssetType; } private Type ResolveDependencyExpectedType(AssetDependency dependency) @@ -416,7 +443,9 @@ private bool TryNormalizeCatalogPath( out string normalized ) { if (!path.isValid) + { throw new ArgumentException("A valid isolated asset path is required.", nameof(path)); + } _ = GetMount(path); if (string.IsNullOrWhiteSpace(path.localPath)) { @@ -430,25 +459,28 @@ out string normalized private AssetInfo? CreateInfo(AssetRecord? record) { if (record is null) + { return null; + } return new AssetInfo( - record.persistentId, + record.persistentID, AssetPath.Parse(record.relativePath), record.meta.isDirectory ? AssetSourceKind.Directory : AssetSourceKind.File, Enum.IsDefined(typeof(AssetImportStatus), record.meta.importStatus) - ? (AssetImportStatus)record.meta.importStatus - : AssetImportStatus.Failed, + ? (AssetImportStatus)record.meta.importStatus + : AssetImportStatus.Failed, record.meta.importerId, - record.stableTypeId, + record.stableTypeID, new AssetArtifactKey(record.meta.artifactKey), new AssetArtifactKey(record.meta.lastSuccessfulArtifactKey), - record.meta.diagnostics); + record.meta.diagnostics + ); } private void CommitCatalogLocked() { - AssetMeta[] entries = m_recordsById.Values - .Concat(m_recordsByPath.Values.Where(static record => record.persistentId == Guid.Empty)) + AssetMeta[] entries = m_recordsByID.Values + .Concat(m_recordsByPath.Values.Where(static record => record.persistentID == Guid.Empty)) .Distinct() .Select(static record => record.meta) .OrderBy(static meta => meta.relativePath, StringComparer.OrdinalIgnoreCase) @@ -461,7 +493,9 @@ private void CommitCatalogLocked() catch (Exception exception) { if (m_diagnostics.PublishCatalogFailure(exception)) + { m_log.Write(LogLevel.Error, "Asset catalog commit failed: {0}", [exception]); + } throw; } m_diagnostics.SynchronizeImports(entries); @@ -470,57 +504,63 @@ private void CommitCatalogLocked() private void MergeCatalogMetaLocked(AssetMeta meta) { if (string.IsNullOrWhiteSpace(meta.relativePath)) + { return; + } if (meta.isTombstone) { if (meta.persistentId == Guid.Empty) - return; - AssetRecord tombstone = FindRecordByIdWithoutLoading(meta.persistentId) ?? new AssetRecord(); - if (!string.IsNullOrWhiteSpace(tombstone.relativePath) && - m_recordsByPath.TryGetValue(tombstone.relativePath, out AssetRecord? pathRecord) && - ReferenceEquals(pathRecord, tombstone)) { + return; + } + AssetRecord tombstone = FindRecordByIDWithoutLoading(meta.persistentId) ?? new AssetRecord(); + if (!string.IsNullOrWhiteSpace(tombstone.relativePath) + && m_recordsByPath.TryGetValue(tombstone.relativePath, out AssetRecord? pathRecord) + && ReferenceEquals(pathRecord, tombstone) + ) { m_recordsByPath.Remove(tombstone.relativePath); } tombstone.relativePath = meta.relativePath; - tombstone.persistentId = meta.persistentId; - tombstone.stableTypeId = meta.stableAssetTypeId; + tombstone.persistentID = meta.persistentId; + tombstone.stableTypeID = meta.stableAssetTypeId; tombstone.meta = meta; tombstone.payload = []; - m_recordsById[meta.persistentId] = tombstone; + m_recordsByID[meta.persistentId] = tombstone; return; } AssetRecord record = meta.persistentId == Guid.Empty - ? m_recordsByPath.GetValueOrDefault(meta.relativePath) ?? new AssetRecord() - : FindRecordByIdWithoutLoading(meta.persistentId) ?? new AssetRecord(); - if (!string.IsNullOrWhiteSpace(record.relativePath) && - !string.Equals(record.relativePath, meta.relativePath, StringComparison.OrdinalIgnoreCase)) - { - if (m_recordsByPath.TryGetValue(record.relativePath, out AssetRecord? pathRecord) && - ReferenceEquals(pathRecord, record)) - { + ? m_recordsByPath.GetValueOrDefault(meta.relativePath) ?? new AssetRecord() + : FindRecordByIDWithoutLoading(meta.persistentId) ?? new AssetRecord(); + if (!string.IsNullOrWhiteSpace(record.relativePath) + && !string.Equals(record.relativePath, meta.relativePath, StringComparison.OrdinalIgnoreCase) + ) { + if (m_recordsByPath.TryGetValue(record.relativePath, out AssetRecord? pathRecord) + && ReferenceEquals(pathRecord, record) + ) { m_recordsByPath.Remove(record.relativePath); } } record.relativePath = meta.relativePath; - record.persistentId = meta.persistentId; - record.stableTypeId = meta.stableAssetTypeId; + record.persistentID = meta.persistentId; + record.stableTypeID = meta.stableAssetTypeId; record.meta = meta; record.payload = m_artifacts.Read(new AssetArtifactKey(meta.artifactKey), "runtime"); record.importerGeneration = m_importers.GetGeneration(meta.importerId); AddOrReplaceRecordLocked(record); - if (record.persistentId != Guid.Empty) + if (record.persistentID != Guid.Empty) + { UpdateGraphsLocked(record); + } } - private AssetRecord? FindRecordByIdWithoutLoading(Guid persistentId) - => m_recordsById.TryGetValue(persistentId, out AssetRecord? record) ? record : null; + private AssetRecord? FindRecordByIDWithoutLoading(Guid persistentID) + => m_recordsByID.TryGetValue(persistentID, out AssetRecord? record) ? record : null; private sealed class AssetRecord { internal string relativePath = string.Empty; - internal Guid persistentId; - internal Guid stableTypeId; + internal Guid persistentID; + internal Guid stableTypeID; internal AssetMeta meta = new(); internal byte[] payload = []; internal AssetObject? asset; @@ -529,5 +569,4 @@ private sealed class AssetRecord internal long failedTypeGeneration; internal AssetSourceFileStamp settingsStamp; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs index a1f51f645..665d4e716 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Gets direct or transitive runtime dependencies of an asset. @@ -43,7 +42,7 @@ public IReadOnlyList GetDependencies( bool recursive = false ) { ArgumentNullException.ThrowIfNull(asset); - return Execute(() => GetDependenciesLocked(asset.identity.persistentId, recursive)); + return Execute(() => GetDependenciesLocked(asset.identity.persistentID, recursive)); } /// @@ -92,17 +91,20 @@ public AssetReferenceInfo GetReferenceInfo(AssetObject asset) private void AttachDependenciesLocked(AssetRecord record) { if (record.asset is null) + { return; - var dependencies = new List(); + } + List dependencies = []; foreach (AssetDependency dependency in GetDirectDependencies(record.meta)) { AssetRecord? dependencyRecord = FindDependencyRecordLocked(dependency); AssetObject dependencyAsset = dependencyRecord?.asset - ?? ResolveReferenceLocked( - dependency.persistentId, - dependency.type.stableId, - dependency.lastKnownPath, - ResolveDependencyExpectedType(dependency)); + ?? ResolveReferenceLocked( + dependency.persistentID, + dependency.type.stableID, + dependency.lastKnownPath, + ResolveDependencyExpectedType(dependency) + ); dependencies.Add(dependencyAsset); } m_dependencyRetention.Remove(record.asset); @@ -111,21 +113,20 @@ private void AttachDependenciesLocked(AssetRecord record) private AssetDependency[] ResolveDeclaredDependenciesLocked(AssetImportContext context) { - var result = context.runtimeDependencies.ToDictionary(static value => value.persistentId); - foreach (Guid persistentId in result.Keys.ToArray()) + Dictionary result = context.runtimeDependencies.ToDictionary(static value => value.persistentID); + foreach (Guid persistentID in result.Keys.ToArray()) { - AssetDependency dependency = result[persistentId]; + AssetDependency dependency = result[persistentID]; string dependencyPath = dependency.lastKnownPath; - if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) + if (m_recordsByID.TryGetValue(dependency.persistentID, out AssetRecord? record)) { dependencyPath = record.relativePath; - result[persistentId] = new AssetDependency( - dependency.persistentId, - dependency.type, - dependencyPath); + result[persistentID] = new AssetDependency(dependency.persistentID, dependency.type, dependencyPath); } if (!string.IsNullOrWhiteSpace(dependencyPath)) + { ValidateSourceReferenceLocked(context.assetPath.ToString(), NormalizeRelativePath(dependencyPath)); + } } foreach (string path in context.runtimeDependencyPaths.Distinct(StringComparer.OrdinalIgnoreCase)) { @@ -133,31 +134,33 @@ private AssetDependency[] ResolveDeclaredDependenciesLocked(AssetImportContext c ValidateSourceReferenceLocked(context.assetPath.ToString(), normalized); if (m_activeImports.Contains(normalized)) { - Guid pendingId = m_pendingImportIds[normalized]; + Guid pendingID = m_pendingImportIDs[normalized]; AssetImporter? pendingImporter = m_importers.FindByPath(normalized); - TypeRef typeRef = pendingImporter is not null && - m_types.TryGetTypeRef(pendingImporter.targetAssetType, out TypeRef pendingTypeRef) - ? pendingTypeRef - : default; - result[pendingId] = new AssetDependency(pendingId, typeRef, normalized); + TypeRef typeRef = pendingImporter is not null + && m_types.TryGetTypeRef(pendingImporter.targetAssetType, out TypeRef pendingTypeRef) + ? pendingTypeRef + : default; + result[pendingID] = new AssetDependency(pendingID, typeRef, normalized); continue; } AssetRecord? dependencyRecord = FindRecordLocked(normalized); - bool dependencyStale = dependencyRecord is null || - IsStale(dependencyRecord, out _); + bool dependencyStale = dependencyRecord is null + || IsStale(dependencyRecord, out _); if (dependencyStale && !ImportLocked(normalized)) { throw new InvalidOperationException( - $"Runtime dependency '{normalized}' referenced by '{context.assetPath}' cannot be imported."); + $"Runtime dependency '{normalized}' referenced by '{context.assetPath}' cannot be imported." + ); } dependencyRecord = FindRecordLocked(normalized) - ?? throw new InvalidOperationException($"Runtime dependency '{normalized}' has no metadata."); - result[dependencyRecord.persistentId] = new AssetDependency( - dependencyRecord.persistentId, - new TypeRef(dependencyRecord.stableTypeId), - dependencyRecord.relativePath); + ?? throw new InvalidOperationException($"Runtime dependency '{normalized}' has no metadata."); + result[dependencyRecord.persistentID] = new AssetDependency( + dependencyRecord.persistentID, + new TypeRef(dependencyRecord.stableTypeID), + dependencyRecord.relativePath + ); } - return result.Values.OrderBy(static value => value.persistentId).ToArray(); + return result.Values.OrderBy(static value => value.persistentID).ToArray(); } private void ValidateImportDependenciesLocked(AssetMeta candidate) @@ -173,7 +176,8 @@ private void ValidateImportDependenciesLocked(AssetMeta candidate) { m_importGraph.ReplaceDependencies(node, previous); throw new InvalidOperationException( - $"Asset import dependency cycle detected: {string.Join(" -> ", cycle)}."); + $"Asset import dependency cycle detected: {string.Join(" -> ", cycle)}." + ); } } @@ -182,76 +186,92 @@ private void ValidateImportDependencySnapshotsLocked(AssetMeta candidate) for (int i = 0; i < candidate.importDependencies.Length; i++) { AssetImportDependencyData dependency = candidate.importDependencies[i]; - string fingerprint = ComputeImportDependencyFingerprintLocked( - ref dependency, - out bool metadataChanged); + string fingerprint = ComputeImportDependencyFingerprintLocked(ref dependency, out bool metadataChanged); if (!string.Equals(dependency.fingerprint, fingerprint, StringComparison.Ordinal)) { throw new IOException( - $"Import dependency '{dependency.key}' changed while " + - $"'{candidate.relativePath}' was importing."); + $"Import dependency '{dependency.key}' changed while " + + $"'{candidate.relativePath}' was importing." + ); } if (metadataChanged) + { candidate.importDependencies[i] = dependency; + } } } private IReadOnlyList GetDependenciesLocked( - Guid persistentId, + Guid persistentID, bool recursive ) { - if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) - return Array.Empty(); + if (!m_recordsByID.TryGetValue(persistentID, out AssetRecord? record)) + { + return []; + } IEnumerable ids = recursive - ? m_runtimeGraph.GetDependencies(persistentId, recursive: true) - : m_runtimeGraph.GetDependencies(persistentId); - return ids.Select(id => m_recordsById.TryGetValue(id, out AssetRecord? dependency) - ? new AssetDependency(id, new TypeRef(dependency.stableTypeId), dependency.relativePath) - : FindDescriptor(record.meta, id)) - .Where(static descriptor => descriptor.persistentId != Guid.Empty) + ? m_runtimeGraph.GetDependencies(persistentID, recursive: true) + : m_runtimeGraph.GetDependencies(persistentID); + return ids + .Select(id => ( + m_recordsByID.TryGetValue(id, out AssetRecord? dependency) + ? new AssetDependency(id, new TypeRef(dependency.stableTypeID), dependency.relativePath) + : FindDescriptor(record.meta, id) + )) + .Where(static descriptor => descriptor.persistentID != Guid.Empty) .ToArray(); } private AssetReferenceInfo GetReferenceInfoLocked(AssetObject asset) { - Guid id = asset.identity.persistentId; - var locations = new List(); - foreach (Guid dependentId in m_runtimeGraph.GetDependents(id)) + Guid id = asset.identity.persistentID; + List locations = []; + foreach (Guid dependentID in m_runtimeGraph.GetDependents(id)) { - if (!m_recordsById.TryGetValue(dependentId, out AssetRecord? dependent)) + if (!m_recordsByID.TryGetValue(dependentID, out AssetRecord? dependent)) + { continue; - locations.Add(new AssetReferenceLocation( - AssetReferenceKind.AssetDependency, - dependentId, - dependent.relativePath, - "runtimeDependencies")); + } + locations.Add( + new AssetReferenceLocation( + AssetReferenceKind.AssetDependency, + dependentID, + dependent.relativePath, + "runtimeDependencies" + ) + ); } - m_recordsById.TryGetValue(id, out AssetRecord? record); + m_recordsByID.TryGetValue(id, out AssetRecord? record); return new AssetReferenceInfo( id, asset.assetPath, asset.contentVersion, record?.asset is not null, record?.lastSweepReachability, - locations.ToArray()); + locations.ToArray() + ); } private void UpdateGraphsLocked(AssetRecord record) { m_runtimeGraph.ReplaceDependencies( - record.persistentId, - record.meta.runtimeDependencies.Select(static value => value.persistentId)); + record.persistentID, + record.meta.runtimeDependencies.Select(static value => value.persistentId) + ); m_importGraph.ReplaceDependencies( record.relativePath, record.meta.importDependencies .Where(static value => (AssetImportDependencyKind)value.kind == AssetImportDependencyKind.Source) - .Select(static value => value.key)); + .Select(static value => value.key) + ); } private AssetRecord? FindDependencyRecordLocked(AssetDependency dependency) { - if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) + if (m_recordsByID.TryGetValue(dependency.persistentID, out AssetRecord? record)) + { return record; + } return null; } @@ -260,7 +280,9 @@ private AssetImportDependencyData CreateImportDependencyDataLocked( AssetImportDependency dependency ) { if (dependency.kind == AssetImportDependencyKind.Source) + { ValidateSourceReferenceLocked(ownerPath, NormalizeRelativePath(dependency.key)); + } var result = new AssetImportDependencyData { kind = (int)dependency.kind, @@ -277,21 +299,29 @@ string dependencyPath ) { AssetPath owner = AssetPath.Parse(ownerPath); AssetPath dependency = AssetPath.Parse(dependencyPath); - if (owner.source == dependency.source || owner.source == AssetSourceId.project) + if (owner.source == dependency.source || owner.source == AssetSourceID.project) + { return; - if (dependency.source == AssetSourceId.project) + } + if (dependency.source == AssetSourceID.project) { throw new InvalidOperationException( - $"Plugin source '{owner.source}' cannot reference project asset '{dependency.localPath}'."); + $"Plugin source '{owner.source}' cannot reference project asset '{dependency.localPath}'." + ); } if (!m_mounts.TryGetValue(owner.source, out AssetSourceMount? ownerMount)) + { throw new InvalidOperationException($"Asset source '{owner.source}' is not mounted."); + } if (!m_mounts.ContainsKey(dependency.source)) + { throw new InvalidOperationException($"Asset source dependency '{dependency.source}' is not mounted."); - if (!ownerMount.dependencySourceIds.Contains(dependency.source)) + } + if (!ownerMount.dependencySourceIDs.Contains(dependency.source)) { throw new InvalidOperationException( - $"Plugin source '{owner.source}' did not declare dependency '{dependency.source}'."); + $"Plugin source '{owner.source}' did not declare dependency '{dependency.source}'." + ); } } @@ -306,10 +336,14 @@ out bool metadataChanged { string sourcePath = GetSourcePath(NormalizeRelativePath(dependency.key)); if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { return "MISSING"; + } bool stampChanged = !SourceStampMatches(dependency, sourceStamp); if (GetMount(dependency.key).isReadOnly && !stampChanged) + { return dependency.fingerprint; + } string hash = ReadStableSourceHash(sourcePath, out sourceStamp); if (stampChanged) { @@ -319,10 +353,10 @@ out bool metadataChanged return hash; } case AssetImportDependencyKind.Artifact: - return Guid.TryParse(dependency.key, out Guid id) && - m_recordsById.TryGetValue(id, out AssetRecord? record) - ? record.meta.artifactKey - : "MISSING"; + return Guid.TryParse(dependency.key, out Guid id) + && m_recordsByID.TryGetValue(id, out AssetRecord? record) + ? record.meta.artifactKey + : "MISSING"; case AssetImportDependencyKind.Custom: return dependency.fingerprint; default: @@ -334,11 +368,11 @@ private static AssetDependency[] GetDirectDependencies(AssetMeta meta) => meta.runtimeDependencies.Select(static value => new AssetDependency( value.persistentId, new TypeRef(value.stableTypeId), - value.lastKnownPath)).ToArray(); + value.lastKnownPath + )).ToArray(); private sealed class AssetDependencySet(AssetObject[] assets) { internal AssetObject[] assets { get; } = assets; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs index ede735863..41caf268e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Captures the current failure identity of every writable source without exposing catalog internals. @@ -33,19 +32,23 @@ sealed partial class AssetLoader /// An immutable health snapshot suitable for validating a later candidate generation. /// public AssetImportHealthSnapshot CaptureWritableImportHealth() - => new(Execute(() => m_recordsByPath.Values - .Where(record => - IsMounted(record.relativePath) - && !GetMount(record.relativePath).isReadOnly - && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) - .Select(static record => new AssetImportFailureFingerprint( - record.relativePath, - record.meta.importStatus, - record.meta.sourceHash, - record.meta.importerId, - string.Join("\n", record.meta.diagnostics))) - .ToHashSet())); + => new( + Execute(() => m_recordsByPath.Values + .Where(record => ( + IsMounted(record.relativePath) + && !GetMount(record.relativePath).isReadOnly + && record.meta.importStatus is (int)AssetImportStatus.Failed + or (int)AssetImportStatus.Conflict + )) + .Select(static record => new AssetImportFailureFingerprint( + record.relativePath, + record.meta.importStatus, + record.meta.sourceHash, + record.meta.importerId, + string.Join("\n", record.meta.diagnostics) + )) + .ToHashSet()) + ); /// /// Finds writable-source failures that are new or changed relative to an earlier health snapshot. @@ -60,22 +63,22 @@ public IReadOnlyList FindIntroducedImportFailures(AssetImpor { ArgumentNullException.ThrowIfNull(baseline); return Execute(() => m_recordsByPath.Values - .Where(record => + .Where(record => ( IsMounted(record.relativePath) && !GetMount(record.relativePath).isReadOnly && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) + or (int)AssetImportStatus.Conflict + )) .Select(static record => new AssetImportFailureFingerprint( record.relativePath, record.meta.importStatus, record.meta.sourceHash, record.meta.importerId, - string.Join("\n", record.meta.diagnostics))) + string.Join("\n", record.meta.diagnostics) + )) .Where(failure => !baseline.failures.Contains(failure)) .OrderBy(static failure => failure.relativePath, StringComparer.Ordinal) - .Select(static failure => new AssetImportFailure( - failure.relativePath, - failure.diagnostics)) + .Select(static failure => new AssetImportFailure(failure.relativePath, failure.diagnostics)) .ToArray()); } @@ -83,7 +86,7 @@ private void RecordImportFailureLocked( string relativePath, byte[] sourceBytes, AssetImporter importer, - Guid persistentId, + Guid persistentID, Exception exception, AssetSourceFileStamp sourceStamp = default, AssetImportContext? attemptedContext = null @@ -91,7 +94,7 @@ private void RecordImportFailureLocked( AssetRecord record = FindRecordLocked(relativePath) ?? new AssetRecord { relativePath = relativePath, - persistentId = persistentId + persistentID = persistentID }; string sourceHash = sourceBytes.Length == 0 ? string.Empty : ComputeSha256Hex(sourceBytes); string settingsHash; @@ -101,8 +104,8 @@ private void RecordImportFailureLocked( settingsHash = ComputeSha256Hex(ReadImportSettingsBytesLocked(relativePath, importer)); } catch (Exception secondaryFailure) when ( - secondaryFailure is not OutOfMemoryException && - RetirementPendingException.Find(secondaryFailure) is null) + secondaryFailure is not OutOfMemoryException + && RetirementPendingException.Find(secondaryFailure) is null) { settingsHash = string.Empty; settingsFailure = $"{secondaryFailure.GetType().Name}: {secondaryFailure.Message}"; @@ -114,33 +117,38 @@ secondaryFailure is not OutOfMemoryException && .ToArray() ?? []; string diagnostic = $"{exception.GetType().Name}: {exception.Message}"; if (settingsFailure is not null) + { diagnostic += $" Import settings could not be inspected: {settingsFailure}"; + } bool repeatedFailure = record.meta.importStatus == (int)AssetImportStatus.Failed - && string.Equals(record.meta.sourceHash, sourceHash, StringComparison.Ordinal) - && string.Equals(record.meta.importerSettingsHash, settingsHash, StringComparison.Ordinal) - && record.importerGeneration == m_importers.GetGeneration(importer.importerId) - && string.Equals(record.meta.importerImplementationFingerprint, - GetImporterImplementationFingerprint(importer), StringComparison.Ordinal) - && record.meta.diagnostics.Length == 1 - && string.Equals(record.meta.diagnostics[0], diagnostic, StringComparison.Ordinal) - && record.meta.importDependencies.SequenceEqual(dependencies); + && string.Equals(record.meta.sourceHash, sourceHash, StringComparison.Ordinal) + && string.Equals(record.meta.importerSettingsHash, settingsHash, StringComparison.Ordinal) + && record.importerGeneration == m_importers.GetGeneration(importer.importerID) + && string.Equals( + record.meta.importerImplementationFingerprint, + GetImporterImplementationFingerprint(importer), + StringComparison.Ordinal + ) + && record.meta.diagnostics.Length == 1 + && string.Equals(record.meta.diagnostics[0], diagnostic, StringComparison.Ordinal) + && record.meta.importDependencies.SequenceEqual(dependencies); record.relativePath = relativePath; - record.persistentId = persistentId; + record.persistentID = persistentID; record.meta.relativePath = relativePath; - record.meta.persistentId = persistentId; + record.meta.persistentId = persistentID; record.meta.sourceHash = sourceHash; - record.meta.importerId = importer.importerId; + record.meta.importerId = importer.importerID; record.meta.importerImplementationFingerprint = GetImporterImplementationFingerprint(importer); record.meta.importerSettingsHash = settingsHash; record.meta.importDependencies = dependencies; - record.importerGeneration = m_importers.GetGeneration(importer.importerId); + record.importerGeneration = m_importers.GetGeneration(importer.importerID); ApplySourceStamp(record.meta, sourceStamp); record.meta.deploymentScope = (int)importer.deploymentScope; - if (record.meta.stableAssetTypeId == Guid.Empty && - m_types.TryGetTypeRef(importer.targetAssetType, out TypeRef importerTypeRef)) - { - record.meta.stableAssetTypeId = importerTypeRef.stableId; - record.stableTypeId = importerTypeRef.stableId; + if (record.meta.stableAssetTypeId == Guid.Empty + && m_types.TryGetTypeRef(importer.targetAssetType, out TypeRef importerTypeRef) + ) { + record.meta.stableAssetTypeId = importerTypeRef.stableID; + record.stableTypeID = importerTypeRef.stableID; } AssetImportExtensionUnavailableException? unavailable = exception as AssetImportExtensionUnavailableException; bool extensionUnavailable = unavailable is not null; @@ -148,30 +156,33 @@ secondaryFailure is not OutOfMemoryException && record.meta.importStatus = (int)(pending ? AssetImportStatus.Pending : AssetImportStatus.Failed); record.failedTypeGeneration = m_types.current.version; record.meta.diagnostics = [pending - ? $"Waiting for authoring extension publication (or recovery after compilation failure). {exception.Message}" + - (settingsFailure is null ? string.Empty : $" Import settings could not be inspected: {settingsFailure}") + ? $"Waiting for authoring extension publication (or recovery after compilation failure). {exception.Message}" + + (settingsFailure is null ? string.Empty : $" Import settings could not be inspected: {settingsFailure}") : diagnostic]; AddOrReplaceRecordLocked(record); // Failure belongs to the writable catalog, not the immutable source being rejected. - if (!GetMount(relativePath).isReadOnly && - (ReadMetadata(GetMetaPath(relativePath)) is null || TryReadSourceMeta(GetMetaPath(relativePath), out _))) + if (!GetMount(relativePath).isReadOnly + && (ReadMetadata(GetMetaPath(relativePath)) is null || TryReadSourceMeta(GetMetaPath(relativePath), out _)) + ) { WriteSourceMeta(record.meta); + } CommitCatalogLocked(); if (extensionUnavailable) { AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp pendingSourceStamp); AssetSourceFileStamp.TryCapture(GetMetaPath(relativePath), out AssetSourceFileStamp metadataStamp); m_unavailableImports[relativePath] = (m_types.current.version, pendingSourceStamp, metadataStamp, - unavailable!.extensionKind, unavailable.extensionId); + unavailable!.extensionKind, unavailable.extensionID); } else + { m_unavailableImports.Remove(relativePath); + } if (pending || repeatedFailure) + { return; - m_log.Write( - LogLevel.Error, - "Asset import for '{0}' failed: {1}", - [relativePath, exception]); + } + m_log.Write(LogLevel.Error, "Asset import for '{0}' failed: {1}", [relativePath, exception]); } private AssetImportDependencyData? TryCaptureFailedImportDependency( @@ -202,21 +213,23 @@ private void TrackUnsupportedSourceLocked(string relativePath) // cataloged source verbatim so a scan cannot erase its persistent identity, stable type, // dependency graph, or immutable artifact closure. A source that has never been imported // still follows the Unsupported path below. - if (record.persistentId != Guid.Empty && - !record.meta.isTombstone && - !string.IsNullOrWhiteSpace(record.meta.importerId)) - { + if (record.persistentID != Guid.Empty + && !record.meta.isTombstone + && !string.IsNullOrWhiteSpace(record.meta.importerId) + ) { record.relativePath = relativePath; record.meta.relativePath = relativePath; AddOrReplaceRecordLocked(record); UpdateGraphsLocked(record); return; } - if (record.persistentId != Guid.Empty) - m_recordsById.Remove(record.persistentId); + if (record.persistentID != Guid.Empty) + { + m_recordsByID.Remove(record.persistentID); + } record.relativePath = relativePath; - record.persistentId = Guid.Empty; - record.stableTypeId = Guid.Empty; + record.persistentID = Guid.Empty; + record.stableTypeID = Guid.Empty; record.meta.relativePath = relativePath; record.meta.persistentId = Guid.Empty; record.meta.importerId = string.Empty; @@ -233,15 +246,15 @@ int matchCount ) { AssetRecord? record = FindRecordLocked(relativePath); if (record is null) + { return; - string diagnostic = - $"Warning: source '{relativePath}' matched {matchCount} removed assets; " + - "a new persistent identity was assigned instead of guessing a rename."; + } + string diagnostic = $"Warning: source '{relativePath}' matched {matchCount} removed assets; " + + "a new persistent identity was assigned instead of guessing a rename."; record.meta.diagnostics = record.meta.diagnostics .Append(diagnostic) .Distinct(StringComparer.Ordinal) .ToArray(); CommitCatalogLocked(); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs index 50f8f1946..bcafa4d9e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; @@ -37,7 +36,8 @@ public AssetImportSettingsSnapshot GetImportSettings(AssetPath path) byte[] settings = ReadImportSettingsBytes(importer, metadata); return new AssetImportSettingsSnapshot( RestoreImportSettingsLocked(importer, settings, null, normalized), - ComputeSha256Hex(metadata ?? [])); + ComputeSha256Hex(metadata ?? []) + ); }); /// @@ -69,82 +69,98 @@ public bool SaveImportSettings( AssetPath path, ISerializable? settings, string expectedFingerprint - ) - => Execute(() => + ) => Execute(() => + { + ArgumentException.ThrowIfNullOrWhiteSpace(expectedFingerprint); + string normalized = NormalizeAssetPath(path); + if (m_sourceMetadataStage is not null || GetMount(normalized).isReadOnly) { - ArgumentException.ThrowIfNullOrWhiteSpace(expectedFingerprint); - string normalized = NormalizeAssetPath(path); - if (m_sourceMetadataStage is not null || GetMount(normalized).isReadOnly) - throw new InvalidOperationException("Import settings can only be edited in the active writable source mount."); - AssetImporter importer = RequireSettingsImporterLocked(normalized); - ISerializable? defaults = importer.CreateImportSettings(); - if (settings is not null && (defaults is null || settings.GetType() != defaults.GetType())) - throw new ArgumentException($"Settings do not match importer '{importer.importerId}'.", nameof(settings)); - byte[] encoded = settings is null ? [] : CaptureImportSettingsLocked(settings, normalized, null); - string metaPath = GetMetaPath(normalized); - byte[]? metadata = ReadMetadata(metaPath); - if (!string.Equals(expectedFingerprint, ComputeSha256Hex(metadata ?? []), StringComparison.Ordinal)) - throw new IOException($"Import settings for '{normalized}' changed externally. Reload before saving."); - AssetSourceMeta source = metadata is null - ? new AssetSourceMeta - { - persistentId = FindRecordLocked(normalized)?.persistentId ?? Guid.NewGuid(), - importerId = importer.importerId - } - : m_serialization.Deserialize(metadata); - if (source.persistentId == Guid.Empty || - !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal)) - throw new InvalidDataException($"Source metadata for '{normalized}' does not match its importer."); - source.importerSettingsBytes = encoded; - WriteAtomic(metaPath, m_serialization.Serialize(source)); + throw new InvalidOperationException("Import settings can only be edited in the active writable source mount."); + } + AssetImporter importer = RequireSettingsImporterLocked(normalized); + ISerializable? defaults = importer.CreateImportSettings(); + if (settings is not null && (defaults is null || settings.GetType() != defaults.GetType())) + { + throw new ArgumentException($"Settings do not match importer '{importer.importerID}'.", nameof(settings)); + } + byte[] encoded = settings is null ? [] : CaptureImportSettingsLocked(settings, normalized, null); + string metaPath = GetMetaPath(normalized); + byte[]? metadata = ReadMetadata(metaPath); + if (!string.Equals(expectedFingerprint, ComputeSha256Hex(metadata ?? []), StringComparison.Ordinal)) + { + throw new IOException($"Import settings for '{normalized}' changed externally. Reload before saving."); + } + AssetSourceMeta source = metadata is null + ? new AssetSourceMeta + { + persistentId = FindRecordLocked(normalized)?.persistentID ?? Guid.NewGuid(), + importerId = importer.importerID + } + : m_serialization.Deserialize(metadata); + if (source.persistentId == Guid.Empty + || !string.Equals(source.importerId, importer.importerID, StringComparison.Ordinal) + ) { + throw new InvalidDataException($"Source metadata for '{normalized}' does not match its importer."); + } + source.importerSettingsBytes = encoded; + WriteAtomic(metaPath, m_serialization.Serialize(source)); + try + { + return ImportLocked(normalized); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) + { + // A reported failed import is a saved authoring state. An exceptional transaction is not: + // restore the exact sidecar and refresh its old publication before the history caller retries. try { - return ImportLocked(normalized); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is null) - { - // A reported failed import is a saved authoring state. An exceptional transaction is not: - // restore the exact sidecar and refresh its old publication before the history caller retries. - try + if (metadata is null) { - if (metadata is null) - System.IO.File.Delete(metaPath); - else - WriteAtomic(metaPath, metadata); - _ = ImportLocked(normalized); + File.Delete(metaPath); } - catch (Exception rollback) + else { - throw new AggregateException("Import settings rollback failed.", failure, rollback); + WriteAtomic(metaPath, metadata); } - throw; + _ = ImportLocked(normalized); } - }); + catch (Exception rollback) + { + throw new AggregateException("Import settings rollback failed.", failure, rollback); + } + throw; + } + }); private AssetImporter RequireSettingsImporterLocked(string path) { - if (!System.IO.File.Exists(GetSourcePath(path))) + if (!File.Exists(GetSourcePath(path))) + { throw new FileNotFoundException($"Import settings source '{path}' does not exist."); + } return m_importers.FindByPath(path) - ?? throw new NotSupportedException($"No importer is registered for '{path}'."); + ?? throw new NotSupportedException($"No importer is registered for '{path}'."); } private byte[] ReadImportSettingsBytesLocked( string path, AssetImporter importer - ) - => ReadImportSettingsBytes(importer, ReadMetadata(GetMetaPath(path))); + ) => ReadImportSettingsBytes(importer, ReadMetadata(GetMetaPath(path))); private byte[] ReadImportSettingsBytes( AssetImporter importer, byte[]? metadata ) { if (metadata is null) + { return []; + } AssetSourceMeta source = m_serialization.Deserialize(metadata); - if (source.importerSettingsBytes.Length > 0 && - !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal)) - throw new InvalidDataException($"Stored import settings belong to '{source.importerId}', not '{importer.importerId}'."); + if (source.importerSettingsBytes.Length > 0 + && !string.Equals(source.importerId, importer.importerID, StringComparison.Ordinal) + ) { + throw new InvalidDataException($"Stored import settings belong to '{source.importerId}', not '{importer.importerID}'."); + } return source.importerSettingsBytes; } @@ -159,15 +175,19 @@ private byte[] ReadImportSettingsBytes( if (value is null) { if (bytes.Length != 0) - throw new InvalidDataException($"Importer '{importer.importerId}' no longer declares the persisted settings type."); + { + throw new InvalidDataException($"Importer '{importer.importerID}' no longer declares the persisted settings type."); + } return null; } - Guid typeId = m_types.GetTypeRef(value.GetType()).stableId; + Guid typeID = m_types.GetTypeRef(value.GetType()).stableID; if (bytes.Length > 0) { SerializedImportSettings saved = m_serialization.Deserialize(bytes); - if (saved.stableTypeId != typeId) - throw new InvalidDataException($"Import settings type '{saved.stableTypeId}' does not match '{typeId}'."); + if (saved.stableTypeId != typeID) + { + throw new InvalidDataException($"Import settings type '{saved.stableTypeId}' does not match '{typeID}'."); + } DeclareSettingsDependenciesLocked(saved.dependencies, ownerPath, null); m_serialization.Decode(saved.properties, reader => { @@ -186,13 +206,15 @@ private byte[] CaptureImportSettingsLocked( AssetImportContext? context ) { var dependencies = new AssetDependencyCollection(); - byte[] properties = m_serialization.Encode(writer => writer.WriteProperties(settings), - AssetSerializationContext.Create(this, dependencies)); + byte[] properties = m_serialization.Encode( + writer => writer.WriteProperties(settings), + AssetSerializationContext.Create(this, dependencies) + ); AssetDependency[] descriptors = dependencies.dependencies.ToArray(); DeclareSettingsDependenciesLocked(descriptors, ownerPath, context); return m_serialization.Serialize(new SerializedImportSettings { - stableTypeId = m_types.GetTypeRef(settings.GetType()).stableId, + stableTypeId = m_types.GetTypeRef(settings.GetType()).stableID, properties = properties, dependencies = descriptors }); @@ -205,14 +227,14 @@ private void DeclareSettingsDependenciesLocked( ) { foreach (AssetDependency dependency in dependencies) { - AssetRecord? record = FindRecordByIdWithoutLoading(dependency.persistentId); + AssetRecord? record = FindRecordByIDWithoutLoading(dependency.persistentID); string path = record?.relativePath ?? dependency.lastKnownPath; if (!string.IsNullOrWhiteSpace(path)) { ValidateSourceReferenceLocked(ownerPath, NormalizeRelativePath(path)); context?.DependsOnSource(AssetPath.Parse(path)); } - context?.DependsOnArtifact(dependency.persistentId); + context?.DependsOnArtifact(dependency.persistentID); } } @@ -223,29 +245,38 @@ AssetImporter importer string path = GetMetaPath(record.relativePath); bool exists = AssetSourceFileStamp.TryCapture(path, out AssetSourceFileStamp stamp); if (m_sourceMetadataStage is null && exists && record.settingsStamp.Equals(stamp)) + { return false; + } string hash; try { hash = ComputeSha256Hex(ReadImportSettingsBytesLocked(record.relativePath, importer)); } catch (Exception exception) when ( - exception is IOException or ArgumentException or InvalidOperationException or FormatException && - RetirementPendingException.Find(exception) is null) + exception is IOException or ArgumentException or InvalidOperationException or FormatException + && RetirementPendingException.Find(exception) is null) { // Reimport owns the diagnostic and last-good policy; a read check never repairs source bytes. return true; } if (!string.Equals(hash, record.meta.importerSettingsHash, StringComparison.Ordinal)) + { return true; + } record.settingsStamp = stamp; return false; } private sealed class SerializedImportSettings : ISerializable { - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal byte[] properties { get; set; } = []; - [SerializableProperty] internal AssetDependency[] dependencies { get; set; } = []; + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal byte[] properties { get; set; } = []; + + [SerializableProperty] + internal AssetDependency[] dependencies { get; set; } = []; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs index f25bec383..924488ab5 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Imports one isolated source file into metadata and a runtime artifact. @@ -59,36 +58,36 @@ public ValueTask BuildAsync( ) { ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(inputs); - Guid targetId = definition.identity.persistentId; + Guid targetID = definition.identity.persistentID; string displayName = string.IsNullOrWhiteSpace(definition.assetPath.ToString()) - ? definition.GetType().Name - : definition.assetPath.ToString(); + ? definition.GetType().Name + : definition.assetPath.ToString(); AssetArtifactKey key = Execute(() => { try { AssetBuildProcessor processor = m_buildProcessors.Find(definition.GetType()) - ?? throw new InvalidOperationException( - $"No asset build processor accepts '{definition.GetType().FullName}'."); + ?? throw new InvalidOperationException( + $"No asset build processor accepts '{definition.GetType().FullName}'." + ); var output = new AssetArtifactWriter(); processor.BuildInternalAsync(definition, inputs, output, cancellationToken) .AsTask() .GetAwaiter() .GetResult(); if (output.outputs.Count == 0) + { throw new InvalidOperationException("An asset build processor produced no outputs."); + } string fingerprint = CreateBuildFingerprint(processor, definition, inputs); AssetArtifactKey result = m_artifacts.Commit(fingerprint, output.outputs, output.authoringOutputs); - m_diagnostics.PublishBuild(targetId, displayName, output.diagnostics); + m_diagnostics.PublishBuild(targetID, displayName, output.diagnostics); return result; } catch (Exception exception) { - m_diagnostics.PublishBuildFailure(targetId, displayName, exception); - m_log.Write( - LogLevel.Error, - "Asset build for '{0}' failed: {1}", - [displayName, exception]); + m_diagnostics.PublishBuildFailure(targetID, displayName, exception); + m_log.Write(LogLevel.Error, "Asset build for '{0}' failed: {1}", [displayName, exception]); throw; } }); @@ -100,54 +99,68 @@ private bool ImportLocked( bool force = false ) { if (m_activeImports.Contains(relativePath)) + { return true; + } if (!force && IsExtensionImportUnchanged(relativePath)) + { return false; + } if (IsSourceIgnored(relativePath, isDirectory: false)) + { return false; + } string sourcePath = GetSourcePath(relativePath); if (!IOFile.Exists(sourcePath)) + { return false; + } AssetImporter? importer = m_importers.FindByPath(relativePath); if (importer is null) + { return false; + } AssetRecord? existingRecord = FindRecordLocked(relativePath); AssetSourceMount sourceMount = GetMount(relativePath); if (sourceMount.isReadOnly && !IOFile.Exists(GetMetaPath(relativePath))) { throw new InvalidDataException( - $"Read-only source '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar."); + $"Read-only source '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar." + ); } - Guid persistentId = existingRecord?.persistentId - ?? m_pendingImportIds.GetValueOrDefault(relativePath); - if (persistentId == Guid.Empty && - TryReadSourceMeta(GetMetaPath(relativePath), out AssetSourceMeta sourceMeta)) - { - persistentId = sourceMeta.persistentId; - AssetRecord? sameId = FindRecordByIdWithoutLoading(persistentId); - if (sameId is not null && - !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase)) - { - if (sameId.meta.isTombstone) + Guid persistentID = existingRecord?.persistentID + ?? m_pendingImportIDs.GetValueOrDefault(relativePath); + if (persistentID == Guid.Empty + && TryReadSourceMeta(GetMetaPath(relativePath), out AssetSourceMeta sourceMeta) + ) { + persistentID = sourceMeta.persistentId; + AssetRecord? sameID = FindRecordByIDWithoutLoading(persistentID); + if (sameID is not null + && !string.Equals(sameID.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + ) { + if (sameID.meta.isTombstone) { - RebindTombstoneLocked(sameId, relativePath); - existingRecord = sameId; + RebindTombstoneLocked(sameID, relativePath); + existingRecord = sameID; } else if (sourceMount.isReadOnly) { throw new InvalidDataException( - $"Read-only source '{relativePath}' duplicates persistent ID '{persistentId}'."); + $"Read-only source '{relativePath}' duplicates persistent ID '{persistentID}'." + ); } else { - persistentId = Guid.NewGuid(); + persistentID = Guid.NewGuid(); } } } - if (persistentId == Guid.Empty) - persistentId = Guid.NewGuid(); - m_pendingImportIds[relativePath] = persistentId; + if (persistentID == Guid.Empty) + { + persistentID = Guid.NewGuid(); + } + m_pendingImportIDs[relativePath] = persistentID; m_activeImports.Add(relativePath); try { @@ -159,18 +172,24 @@ private bool ImportLocked( relativePath, sourceBytes, importer, - persistentId, + persistentID, sourceStamp, - context => attemptedContext = context); + context => attemptedContext = context + ); try { CommitBuildLocked(build, writeSource: false, sourceBytes); - if (m_unavailableImports.Remove(relativePath, out var recovered)) - { + if (m_unavailableImports.Remove( + relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) recovered + )) { foreach (string dependent in m_unavailableImports .Where(pair => pair.Value.kind == recovered.kind && pair.Value.id == recovered.id) - .Select(static pair => pair.Key).ToArray()) + .Select(static pair => pair.Key) + .ToArray() + ) { m_unavailableImports.Remove(dependent); + } } } finally @@ -185,48 +204,60 @@ private bool ImportLocked( relativePath, sourceBytes, importer, - persistentId, + persistentID, exception, sourceStamp, - attemptedContext); + attemptedContext + ); return false; } } catch (IOException exception) { - RecordImportFailureLocked(relativePath, [], importer, persistentId, exception); + RecordImportFailureLocked(relativePath, [], importer, persistentID, exception); return false; } catch (UnauthorizedAccessException exception) { - RecordImportFailureLocked(relativePath, [], importer, persistentId, exception); + RecordImportFailureLocked(relativePath, [], importer, persistentID, exception); return false; } finally { m_activeImports.Remove(relativePath); - m_pendingImportIds.Remove(relativePath); + m_pendingImportIDs.Remove(relativePath); } } private bool IsExtensionImportUnchanged(string relativePath) { - if (!m_unavailableImports.TryGetValue(relativePath, out var previous) || - previous.generation != m_types.current.version || - !AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp sourceStamp) || - sourceStamp != previous.source) + if (!m_unavailableImports.TryGetValue( + relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) previous + ) + || previous.generation != m_types.current.version + || !AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp sourceStamp) + || sourceStamp != previous.source + ) { return false; + } AssetSourceFileStamp.TryCapture(GetMetaPath(relativePath), out AssetSourceFileStamp metadataStamp); if (metadataStamp != previous.metadata) + { return false; + } AssetRecord? record = FindRecordLocked(relativePath); if (record is null) + { return false; + } foreach (AssetImportDependencyData value in record.meta.importDependencies) { AssetImportDependencyData dependency = value; if (ComputeImportDependencyFingerprintLocked(ref dependency, out _) != value.fingerprint) + { return false; + } } return true; } @@ -235,7 +266,7 @@ private ImportBuild BuildImportLocked( string relativePath, byte[] sourceBytes, AssetImporter importer, - Guid persistentId, + Guid persistentID, AssetSourceFileStamp sourceStamp = default, Action? onContextCreated = null ) { @@ -245,7 +276,7 @@ private ImportBuild BuildImportLocked( GetSourcePath(relativePath), sourceBytes, sourceHash, - persistentId, + persistentID, m_types, m_serialization, this, @@ -267,10 +298,13 @@ private ImportBuild BuildImportLocked( { throw new FileNotFoundException( $"Import source dependency '{normalizedDependency}' does not exist.", - physicalPath); + physicalPath + ); } return ReadStableSourceBytes(physicalPath, out _); - }, this); + }, + this + ); onContextCreated?.Invoke(context); byte[] settingsBytes = ReadImportSettingsBytesLocked(relativePath, importer); context.importSettings = RestoreImportSettingsLocked(importer, settingsBytes, context); @@ -283,29 +317,34 @@ private ImportBuild BuildImportLocked( if (!Enum.IsDefined(deploymentScope)) { throw new InvalidOperationException( - $"Importer '{importer.GetType().FullName}' declares an unsupported deployment scope."); + $"Importer '{importer.GetType().FullName}' declares an unsupported deployment scope." + ); } bool hasRuntimeOutput = product.outputs.ContainsKey("runtime"); if (deploymentScope == AssetDeploymentScope.Runtime && !hasRuntimeOutput) { throw new InvalidOperationException( - $"Runtime importer '{importer.GetType().FullName}' must write a 'runtime' artifact output."); + $"Runtime importer '{importer.GetType().FullName}' must write a 'runtime' artifact output." + ); } if (deploymentScope == AssetDeploymentScope.AuthoringOnly && hasRuntimeOutput) { throw new InvalidOperationException( - $"Authoring-only importer '{importer.GetType().FullName}' cannot write a 'runtime' artifact output."); + $"Authoring-only importer '{importer.GetType().FullName}' cannot write a 'runtime' artifact output." + ); } if (!importer.targetAssetType.IsInstanceOfType(product.asset)) { throw new InvalidOperationException( - $"Importer '{importer.GetType().FullName}' returned '{product.asset.GetType().FullName}' " + - $"instead of '{importer.targetAssetType.FullName}'."); + $"Importer '{importer.GetType().FullName}' returned '{product.asset.GetType().FullName}' " + + $"instead of '{importer.targetAssetType.FullName}'." + ); } if (!m_types.TryGetTypeRef(product.asset.GetType(), out TypeRef assetTypeRef)) { throw new InvalidOperationException( - $"Imported asset type '{product.asset.GetType().FullName}' requires a StableTypeId."); + $"Imported asset type '{product.asset.GetType().FullName}' requires a StableTypeID." + ); } AssetDependency[] runtimeDependencies = ResolveDeclaredDependenciesLocked(context); @@ -316,19 +355,22 @@ private ImportBuild BuildImportLocked( sourceHash, product.runtimePayload, false, - 1); + 1 + ); var outputs = new Dictionary>(product.outputs, StringComparer.Ordinal); if (!outputs.TryAdd("asset-state", state)) + { throw new InvalidOperationException("The artifact output name 'asset-state' is reserved."); + } string implementationFingerprint = GetImporterImplementationFingerprint(importer); var meta = new AssetMeta { - persistentId = persistentId, + persistentId = persistentID, relativePath = relativePath, sourceHash = sourceHash, - importerId = importer.importerId, + importerId = importer.importerID, deploymentScope = (int)deploymentScope, - stableAssetTypeId = assetTypeRef.stableId, + stableAssetTypeId = assetTypeRef.stableID, assetStateBytes = state, runtimeDependencies = runtimeDependencies.Select(ToData).ToArray(), importDependencies = context.importDependencies @@ -347,7 +389,8 @@ private ImportBuild BuildImportLocked( product.runtimePayload.ToArray(), outputs, product.authoringOutputs, - runtimeDependencies); + runtimeDependencies + ); } private void CommitBuildLocked( @@ -356,7 +399,9 @@ private void CommitBuildLocked( byte[] sourceBytes ) { if (writeSource && m_sourceMetadataStage is not null) + { throw new InvalidOperationException("An isolated Asset candidate cannot edit authoring source content."); + } AssetRecord? existing = FindRecordLocked(build.meta.relativePath); AssetObject? canonical = existing?.asset; byte[]? previousState = null; @@ -376,7 +421,8 @@ byte[] sourceBytes build.meta.sourceHash, replaced.runtimePayload, true, - replaced.contentVersion + 1); + replaced.contentVersion + 1 + ); m_runtimeOwner.Release(replaced); m_identities.Unregister(replaced); existing!.asset = null; @@ -401,7 +447,8 @@ byte[] sourceBytes build.meta.sourceHash, build.payload, false, - previousVersion + 1); + previousVersion + 1 + ); } catch { @@ -412,7 +459,8 @@ byte[] sourceBytes previousPath, previousHash, previousMissing, - previousVersion); + previousVersion + ); throw; } } @@ -424,24 +472,33 @@ byte[] sourceBytes try { if (writeSource) + { WriteAtomic(sourcePath, sourceBytes); + } if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { throw new IOException($"Source '{build.meta.relativePath}' changed while its import was committing."); + } if (!writeSource && !SourceStampMatches(build.meta, sourceStamp)) { - throw new IOException( - $"Source '{build.meta.relativePath}' changed while its importer was running."); + throw new IOException($"Source '{build.meta.relativePath}' changed while its importer was running."); } ApplySourceStamp(build.meta, sourceStamp); - if (!string.Equals(build.meta.importerSettingsHash, - ComputeSha256Hex(ReadImportSettingsBytesLocked(build.meta.relativePath, - m_importers.FindById(build.meta.importerId)!)), StringComparison.Ordinal)) + if (!string.Equals( + build.meta.importerSettingsHash, + ComputeSha256Hex( + ReadImportSettingsBytesLocked(build.meta.relativePath, m_importers.FindByID(build.meta.importerId)!) + ), + StringComparison.Ordinal + )) { throw new IOException($"Import settings for '{build.meta.relativePath}' changed during import."); + } ValidateImportDependencySnapshotsLocked(build.meta); AssetArtifactKey artifactKey = m_artifacts.Commit( CreateImportFingerprint(build.meta), build.outputs, - build.authoringOutputs); + build.authoringOutputs + ); build.meta.artifactKey = artifactKey.value; build.meta.lastSuccessfulArtifactKey = artifactKey.value; WriteSourceMeta(build.meta); @@ -449,7 +506,9 @@ byte[] sourceBytes catch { if (writeSource) + { RestoreFile(sourcePath, sourceSnapshot); + } RestoreFile(metaPath, metaSnapshot); if (canonical is not null && previousState is not null && previousPayload is not null) { @@ -460,20 +519,23 @@ byte[] sourceBytes previousPath, previousHash, previousMissing, - previousVersion); + previousVersion + ); } throw; } AssetRecord record = existing ?? new AssetRecord(); record.relativePath = build.meta.relativePath; - record.persistentId = build.meta.persistentId; - record.stableTypeId = build.meta.stableAssetTypeId; + record.persistentID = build.meta.persistentId; + record.stableTypeID = build.meta.stableAssetTypeId; record.meta = build.meta; record.payload = build.payload; record.importerGeneration = m_importers.GetGeneration(build.meta.importerId); if (canonical is not null) + { record.asset = canonical; + } AddOrReplaceRecordLocked(record); UpdateGraphsLocked(record); CommitCatalogLocked(); @@ -492,5 +554,4 @@ private readonly record struct ImportBuild( IReadOnlySet authoringOutputs, AssetDependency[] dependencies ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs index 3e8bf4f1d..d7e9157ed 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Loads a canonical asset by isolated source path. @@ -51,6 +50,26 @@ Type requestedAssetType return Execute(() => LoadPathLocked(NormalizeAssetPath(path), requestedAssetType)); } + /// + /// Loads a canonical asset by persistent identity. + /// + /// + /// The persistent asset identity. + /// + /// + /// The required assignable asset type. + /// + /// + /// The canonical asset, or when unavailable or incompatible. + /// + public AssetObject? Load( + Guid persistentID, + Type requestedAssetType + ) { + ArgumentNullException.ThrowIfNull(requestedAssetType); + return Execute(() => LoadIDLocked(persistentID, requestedAssetType)); + } + /// /// Tries to load a canonical asset by isolated source path. /// @@ -75,30 +94,10 @@ out AssetObject? asset return asset is not null; } - /// - /// Loads a canonical asset by persistent identity. - /// - /// - /// The persistent asset identity. - /// - /// - /// The required assignable asset type. - /// - /// - /// The canonical asset, or when unavailable or incompatible. - /// - public AssetObject? Load( - Guid persistentId, - Type requestedAssetType - ) { - ArgumentNullException.ThrowIfNull(requestedAssetType); - return Execute(() => LoadIdLocked(persistentId, requestedAssetType)); - } - /// /// Tries to load a canonical asset by persistent identity. /// - /// + /// /// The persistent asset identity. /// /// @@ -111,11 +110,11 @@ Type requestedAssetType /// when a compatible asset was loaded. /// public bool TryLoad( - Guid persistentId, + Guid persistentID, Type requestedAssetType, out AssetObject? asset ) { - asset = Load(persistentId, requestedAssetType); + asset = Load(persistentID, requestedAssetType); return asset is not null; } @@ -153,16 +152,17 @@ out AssetObject? asset _ => RemovePathOperation(normalized, operation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + TaskScheduler.Default + ); } } - return AwaitSharedLoad(operation, requestedAssetType, cancellationToken); + return AwaitSharedLoadAsync(operation, requestedAssetType, cancellationToken); } /// /// Asynchronously loads a canonical asset by persistent identity. /// - /// + /// /// The persistent asset identity. /// /// @@ -175,7 +175,7 @@ out AssetObject? asset /// The canonical asset, or when unavailable or incompatible. /// public ValueTask LoadAsync( - Guid persistentId, + Guid persistentID, Type requestedAssetType, CancellationToken cancellationToken = default ) { @@ -184,27 +184,28 @@ out AssetObject? asset lock (m_asyncSync) { ObjectDisposedException.ThrowIf(m_disposeRequested, this); - if (!m_inFlightIdLoads.TryGetValue(persistentId, out operation!)) + if (!m_inFlightIDLoads.TryGetValue(persistentID, out operation!)) { - operation = Task.Run(() => Load(persistentId, typeof(AssetObject))); - m_inFlightIdLoads.Add(persistentId, operation); + operation = Task.Run(() => Load(persistentID, typeof(AssetObject))); + m_inFlightIDLoads.Add(persistentID, operation); _ = operation.ContinueWith( - _ => RemoveIdOperation(persistentId, operation), + _ => RemoveIDOperation(persistentID, operation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + TaskScheduler.Default + ); } } - return AwaitSharedLoad(operation, requestedAssetType, cancellationToken); + return AwaitSharedLoadAsync(operation, requestedAssetType, cancellationToken); } /// /// Resolves a serialized reference or creates a persistent missing placeholder. /// - /// + /// /// The referenced persistent identity. /// - /// + /// /// The referenced stable asset type identity. /// /// @@ -217,27 +218,29 @@ out AssetObject? asset /// A compatible canonical asset or missing placeholder. /// public AssetObject ResolveReference( - Guid persistentId, - Guid stableTypeId, + Guid persistentID, + Guid stableTypeID, string lastKnownPath, Type expectedType ) { ArgumentNullException.ThrowIfNull(expectedType); - if (persistentId == Guid.Empty) + if (persistentID == Guid.Empty) + { throw new InvalidOperationException("A serialized asset reference has an empty persistent identity."); - return Execute(() => ResolveReferenceLocked(persistentId, stableTypeId, lastKnownPath, expectedType)); + } + return Execute(() => ResolveReferenceLocked(persistentID, stableTypeID, lastKnownPath, expectedType)); } AssetObject IAssetReferenceResolver.Resolve( - Guid persistentId, - Guid stableTypeId, + Guid persistentID, + Guid stableTypeID, string lastKnownPath, Type expectedType, string propertyPath ) { try { - return ResolveReference(persistentId, stableTypeId, lastKnownPath, expectedType); + return ResolveReference(persistentID, stableTypeID, lastKnownPath, expectedType); } catch (AssetImportExtensionUnavailableException) { @@ -246,9 +249,10 @@ string propertyPath catch (Exception exception) { throw new InvalidOperationException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + - $"'{expectedType.FullName}'.", - exception); + $"Asset reference '{persistentID:D}' at '{propertyPath}' cannot be resolved as " + + $"'{expectedType.FullName}'.", + exception + ); } } @@ -273,7 +277,9 @@ Type requestedAssetType } } if (catalogChanged && !stale) + { CommitCatalogLocked(); + } if (record is null || stale) { if (!ImportLocked(relativePath)) @@ -286,23 +292,27 @@ record = FindRecordLocked(relativePath); return record is null ? null : LoadRecordLocked(record, requestedAssetType); } - private AssetObject? LoadIdLocked( - Guid persistentId, + private AssetObject? LoadIDLocked( + Guid persistentID, Type requestedAssetType ) { - if (persistentId == Guid.Empty) + if (persistentID == Guid.Empty) + { return null; - if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) + } + if (!m_recordsByID.TryGetValue(persistentID, out AssetRecord? record)) { LoadCatalogLocked(); - if (!m_recordsById.TryGetValue(persistentId, out record)) + if (!m_recordsByID.TryGetValue(persistentID, out record)) + { return null; + } } if (record.meta.isTombstone) { return record.asset is null - ? null - : LoadRecordLocked(record, requestedAssetType); + ? null + : LoadRecordLocked(record, requestedAssetType); } // A source-side identity can be indexed before its body is imported. Route identity loads @@ -310,11 +320,11 @@ Type requestedAssetType // or stale artifact merely because their sidecar was discovered first. The sidecar check // keeps a newly created asset at the same path from satisfying an older identity lookup. bool ownsCurrentSource = IOFile.Exists(GetSourcePath(record.relativePath)) - && TryReadSourceMeta(GetMetaPath(record.relativePath), out AssetSourceMeta sourceMeta) - && sourceMeta.persistentId == persistentId; + && TryReadSourceMeta(GetMetaPath(record.relativePath), out AssetSourceMeta sourceMeta) + && sourceMeta.persistentId == persistentID; return ownsCurrentSource - ? LoadPathLocked(record.relativePath, requestedAssetType) - : LoadRecordLocked(record, requestedAssetType); + ? LoadPathLocked(record.relativePath, requestedAssetType) + : LoadRecordLocked(record, requestedAssetType); } private AssetObject? LoadRecordLocked( @@ -323,24 +333,38 @@ Type requestedAssetType ) { if (string.IsNullOrEmpty(record.meta.artifactKey) && record.meta.assetStateBytes.Length == 0) { - if (m_activeImports.Count != 0 && m_unavailableImports.TryGetValue(record.relativePath, out var unavailable)) + if (m_activeImports.Count != 0 + && m_unavailableImports.TryGetValue( + record.relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) unavailable + ) + ) { throw new AssetImportExtensionUnavailableException(unavailable.kind, unavailable.id); + } return null; } Type? actualType = ResolveRecordType(record); if (actualType is null || !requestedAssetType.IsAssignableFrom(actualType)) + { return null; + } if (record.asset is not null) + { return requestedAssetType.IsInstanceOfType(record.asset) ? record.asset : null; + } var transaction = new AssetLoadTransaction(); try { PrepareShellsLocked(record, transaction); foreach (AssetRecord created in transaction.createdRecords) + { HydrateRecordLocked(created); + } foreach (AssetRecord created in transaction.createdRecords) + { AttachDependenciesLocked(created); + } return record.asset; } catch @@ -355,24 +379,31 @@ private void PrepareShellsLocked( AssetLoadTransaction transaction ) { if (record.asset is not null) + { return; + } Type type = ResolveRecordType(record) - ?? throw new InvalidOperationException( - $"Asset '{record.relativePath}' has unknown stable type '{record.stableTypeId}'."); + ?? throw new InvalidOperationException( + $"Asset '{record.relativePath}' has unknown stable type '{record.stableTypeID}'." + ); AssetObject shell; try { shell = (AssetObject)(Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException("Activator returned null.")); + ?? throw new InvalidOperationException("Activator returned null.")); } catch (Exception exception) { throw new InvalidOperationException( - $"Asset type '{type.FullName}' requires a parameterless constructor.", exception); + $"Asset type '{type.FullName}' requires a parameterless constructor.", + exception + ); } - m_identities.InitializePersistentIdentity(shell, record.persistentId); + m_identities.InitializePersistentIdentity(shell, record.persistentID); if (m_identitiesActive) - m_identities.Register(shell, record.persistentId); + { + m_identities.Register(shell, record.persistentID); + } record.asset = shell; transaction.createdRecords.Add(record); @@ -383,9 +414,11 @@ AssetLoadTransaction transaction // activated yet. Do not let that temporary type gap abort the entire object graph; // AttachDependenciesLocked installs the identity-preserving placeholder and a later // registry generation rehydrates the reference from the retained catalog record. - if (dependencyRecord is not null && ResolveRecordType(dependencyRecord) is not null && - (dependencyRecord.meta.assetStateBytes.Length != 0 || !string.IsNullOrEmpty(dependencyRecord.meta.artifactKey))) + if (dependencyRecord is not null && ResolveRecordType(dependencyRecord) is not null + && (dependencyRecord.meta.assetStateBytes.Length != 0 || !string.IsNullOrEmpty(dependencyRecord.meta.artifactKey)) + ) { PrepareShellsLocked(dependencyRecord, transaction); + } } } @@ -393,11 +426,11 @@ private void HydrateRecordLocked(AssetRecord record) { AssetObject asset = record.asset!; RestoreAssetState(asset, record.meta.assetStateBytes); - byte[] payload = m_artifacts.Read( - new AssetArtifactKey(record.meta.artifactKey), - "runtime"); + byte[] payload = m_artifacts.Read(new AssetArtifactKey(record.meta.artifactKey), "runtime"); if (payload.Length == 0 && record.payload.Length > 0) + { payload = record.payload; + } record.payload = payload; bool isMissing = record.meta.importStatus == (int)AssetImportStatus.Missing; m_runtimeOwner.Initialize( @@ -406,54 +439,62 @@ private void HydrateRecordLocked(AssetRecord record) record.meta.sourceHash, payload, isMissing, - 1); + 1 + ); } private AssetObject ResolveReferenceLocked( - Guid persistentId, - Guid stableTypeId, + Guid persistentID, + Guid stableTypeID, string lastKnownPath, Type expectedType ) { - AssetObject? loaded = LoadIdLocked(persistentId, expectedType); + AssetObject? loaded = LoadIDLocked(persistentID, expectedType); if (loaded is not null) + { return loaded; + } // A cataloged source whose importer/type belongs to a later module generation is // unavailable, not missing. Startup and atomic reload may legitimately observe this // state before the corresponding generation is activated; publishing a missing-reference // diagnostic here would turn a healthy last-good asset into a false warning. - if (!IsSourceBackedTypeUnavailableLocked(persistentId)) - m_diagnostics.PublishMissingReference(persistentId, lastKnownPath, expectedType); - if (m_missingAssets.TryGetValue(persistentId, out WeakReference? weak) && - weak.TryGetTarget(out AssetObject? existing) && expectedType.IsInstanceOfType(existing)) + if (!IsSourceBackedTypeUnavailableLocked(persistentID)) { + m_diagnostics.PublishMissingReference(persistentID, lastKnownPath, expectedType); + } + if (m_missingAssets.TryGetValue(persistentID, out WeakReference? weak) + && weak.TryGetTarget(out AssetObject? existing) && expectedType.IsInstanceOfType(existing) + ) { return existing; } Type type = ResolveDependencyExpectedType( - new AssetDependency(persistentId, new TypeRef(stableTypeId), lastKnownPath)); - if (type == typeof(MissingAsset) && - !expectedType.IsAbstract && - !expectedType.IsInterface && - typeof(AssetObject).IsAssignableFrom(expectedType)) - { + new AssetDependency(persistentID, new TypeRef(stableTypeID), lastKnownPath) + ); + if (type == typeof(MissingAsset) + && !expectedType.IsAbstract + && !expectedType.IsInterface + && typeof(AssetObject).IsAssignableFrom(expectedType) + ) { type = expectedType; } if (!expectedType.IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Missing asset type '{type.FullName}' cannot be assigned to '{expectedType.FullName}'."); + $"Missing asset type '{type.FullName}' cannot be assigned to '{expectedType.FullName}'." + ); } AssetObject missing = (AssetObject)(Activator.CreateInstance(type, nonPublic: true) ?? throw new InvalidOperationException($"Missing asset type '{type.FullName}' cannot be created.")); - m_identities.InitializePersistentIdentity(missing, persistentId); + m_identities.InitializePersistentIdentity(missing, persistentID); m_runtimeOwner.Initialize( missing, AssetPath.Parse(lastKnownPath), string.Empty, ReadOnlyMemory.Empty, true, - 0); - m_missingAssets[persistentId] = new WeakReference(missing); + 0 + ); + m_missingAssets[persistentID] = new WeakReference(missing); return missing; } @@ -472,8 +513,10 @@ private void RollbackLoadLocked(AssetLoadTransaction transaction) private T Execute(Func action) { - if (ReferenceEquals(t_activeLoader, this)) + if (ReferenceEquals(s_activeLoader, this)) + { return action(); + } using IDisposable generation = m_types.AcquireOperation("access Asset loader"); lock (m_asyncSync) { @@ -483,22 +526,24 @@ private T Execute(Func action) try { m_operationGate.Wait(); - AssetLoader? previous = t_activeLoader; - t_activeLoader = this; + AssetLoader? previous = s_activeLoader; + s_activeLoader = this; try { return action(); } finally { - t_activeLoader = previous; + s_activeLoader = previous; m_operationGate.Release(); } } finally { lock (m_asyncSync) + { m_admittedOperations--; + } } } @@ -509,46 +554,45 @@ private void Execute(Action action) return 0; }); - private static async ValueTask AwaitSharedLoad( - Task operation, - Type requestedAssetType, - CancellationToken cancellationToken - ) { - AssetObject? asset = await operation.WaitAsync(cancellationToken).ConfigureAwait(false); - return asset is not null && requestedAssetType.IsInstanceOfType(asset) ? asset : null; - } - private void RemovePathOperation( string relativePath, Task operation ) { lock (m_asyncSync) { - if (m_inFlightPathLoads.TryGetValue(relativePath, out Task? current) && - ReferenceEquals(current, operation)) - { + if (m_inFlightPathLoads.TryGetValue(relativePath, out Task? current) + && ReferenceEquals(current, operation) + ) { m_inFlightPathLoads.Remove(relativePath); } } } - private void RemoveIdOperation( - Guid persistentId, + private void RemoveIDOperation( + Guid persistentID, Task operation ) { lock (m_asyncSync) { - if (m_inFlightIdLoads.TryGetValue(persistentId, out Task? current) && - ReferenceEquals(current, operation)) - { - m_inFlightIdLoads.Remove(persistentId); + if (m_inFlightIDLoads.TryGetValue(persistentID, out Task? current) + && ReferenceEquals(current, operation) + ) { + m_inFlightIDLoads.Remove(persistentID); } } } + private static async ValueTask AwaitSharedLoadAsync( + Task operation, + Type requestedAssetType, + CancellationToken cancellationToken + ) { + AssetObject? asset = await operation.WaitAsync(cancellationToken).ConfigureAwait(false); + return asset is not null && requestedAssetType.IsInstanceOfType(asset) ? asset : null; + } + private sealed class AssetLoadTransaction { internal List createdRecords { get; } = []; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs index 1033ac3bd..b742a5a1c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs @@ -7,85 +7,48 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { - private bool IsSourceBackedTypeUnavailableLocked(Guid persistentId) - { - if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record) || - record.meta.isTombstone || - record.persistentId == Guid.Empty || - string.IsNullOrWhiteSpace(record.meta.importerId) || - !IsMounted(record.relativePath) || - !IOFile.Exists(GetSourcePath(record.relativePath))) - { - return false; - } - return ResolveRecordType(record) is null || m_unavailableImports.ContainsKey(record.relativePath); - } - - private void RefreshLoadedAssetReferencesLocked() - { - AssetRecord[] loaded = m_recordsByPath.Values - .Where(static record => record.asset is not null) - .ToArray(); - for (int i = 0; i < loaded.Length; i++) - { - AssetRecord record = loaded[i]; - AssetObject asset = record.asset!; - if (record.meta.assetStateBytes.Length == 0) - continue; - byte[] rollback = CaptureAssetState(asset); - try - { - RestoreAssetState(asset, record.meta.assetStateBytes); - } - catch - { - RestoreAssetState(asset, rollback); - throw; - } - } - for (int i = 0; i < loaded.Length; i++) - AttachDependenciesLocked(loaded[i]); - } - internal IReadOnlyList CaptureRecoveryStates() => Execute(() => { var states = new Dictionary(); - foreach (AssetRecord record in m_recordsById.Values) + foreach (AssetRecord record in m_recordsByID.Values) { // Catalog tombstones preserve source identity, but they are not live reference // roots. Only a materialized canonical asset belongs to the active generation; // retained missing placeholders are captured separately below. if (record.asset is not null) - Capture(record.persistentId, record.relativePath, record.stableTypeId, record.meta.assetStateBytes); + { + Capture(record.persistentID, record.relativePath, record.stableTypeID, record.meta.assetStateBytes); + } } foreach ((Guid id, SerializedMissingState state) in m_preservedMissingStates) + { states.TryAdd(id, state); + } foreach ((Guid id, WeakReference reference) in m_missingAssets) { if (!states.ContainsKey(id) && reference.TryGetTarget(out AssetObject? missing)) { - m_recordsById.TryGetValue(id, out AssetRecord? record); - Capture(id, missing.assetPath.ToString(), record?.stableTypeId ?? Guid.Empty, record?.meta.assetStateBytes ?? []); + m_recordsByID.TryGetValue(id, out AssetRecord? record); + Capture(id, missing.assetPath.ToString(), record?.stableTypeID ?? Guid.Empty, record?.meta.assetStateBytes ?? []); } } return (IReadOnlyList)Array.AsReadOnly(states.Values.ToArray()); @@ -93,13 +56,16 @@ internal IReadOnlyList CaptureRecoveryStates() void Capture( Guid id, string path, - Guid stableTypeId, + Guid stableTypeID, byte[] payload - ) { - states.Add(id, new SerializedMissingState(new ReferenceKey(id, "$asset"), - new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeId, - lastKnownPath: path), payload)); - } + ) => states.Add( + id, + new SerializedMissingState( + new ReferenceKey(id, "$asset"), + new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeID, lastKnownPath: path), + payload + ) + ); }); internal void PreserveMissingRecoveryStates(IReadOnlyList changes) @@ -109,31 +75,41 @@ internal void PreserveMissingRecoveryStates(IReadOnlyList Execute(() => IsSourceBackedTypeUnavailableLocked(persistentId)); + internal bool IsSourceBackedTypeUnavailable(Guid persistentID) => Execute(() => IsSourceBackedTypeUnavailableLocked(persistentID)); internal void SetIdentitiesActive(bool active) => Execute(() => { if (m_identitiesActive == active) + { return; - var attempted = new List(); + } + List attempted = []; try { - foreach (AssetRecord record in m_recordsById.Values) + foreach (AssetRecord record in m_recordsByID.Values) { if (record.asset is null) + { continue; + } attempted.Add(record.asset); if (active) - m_identities.Register(record.asset, record.persistentId); + { + m_identities.Register(record.asset, record.persistentID); + } else + { m_identities.Unregister(record.asset); + } } m_identitiesActive = active; m_diagnostics.SetActive(active); @@ -150,9 +126,13 @@ internal void SetIdentitiesActive(bool active) try { if (active) + { m_identities.Unregister(asset); + } else - m_identities.Register(asset, asset.identity.persistentId); + { + m_identities.Register(asset, asset.identity.persistentID); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -164,11 +144,56 @@ internal void SetIdentitiesActive(bool active) } } if (failures.Count > 1) + { throw new AggregateException("Asset identity publication and compensation failed.", failures); + } throw; } }); - private sealed class MissingAsset : AssetObject; + private bool IsSourceBackedTypeUnavailableLocked(Guid persistentID) + { + if (!m_recordsByID.TryGetValue(persistentID, out AssetRecord? record) + || record.meta.isTombstone + || record.persistentID == Guid.Empty + || string.IsNullOrWhiteSpace(record.meta.importerId) + || !IsMounted(record.relativePath) + || !IOFile.Exists(GetSourcePath(record.relativePath)) + ) { + return false; + } + return ResolveRecordType(record) is null || m_unavailableImports.ContainsKey(record.relativePath); + } + + private void RefreshLoadedAssetReferencesLocked() + { + AssetRecord[] loaded = m_recordsByPath.Values + .Where(static record => record.asset is not null) + .ToArray(); + for (int i = 0; i < loaded.Length; i++) + { + AssetRecord record = loaded[i]; + AssetObject asset = record.asset!; + if (record.meta.assetStateBytes.Length == 0) + { + continue; + } + byte[] rollback = CaptureAssetState(asset); + try + { + RestoreAssetState(asset, record.meta.assetStateBytes); + } + catch + { + RestoreAssetState(asset, rollback); + throw; + } + } + for (int i = 0; i < loaded.Length; i++) + { + AttachDependenciesLocked(loaded[i]); + } + } + private sealed class MissingAsset : AssetObject; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs index 7722488fe..7c4d61059 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Collects unreachable content-addressed artifacts. @@ -41,25 +40,25 @@ sealed partial class AssetLoader public int CollectArtifacts( TimeSpan gracePeriod, long maximumSizeBytes - ) { - return Execute(() => + ) => Execute(() => + { + HashSet reachable = []; + foreach (AssetArtifactKey retained in m_artifactRetention.GetRetainedKeys()) { - HashSet reachable = []; - foreach (AssetArtifactKey retained in m_artifactRetention.GetRetainedKeys()) - AddArtifactKey(reachable, retained.value); - foreach (AssetRecord record in m_recordsByPath.Values) - { - AddArtifactKey(reachable, record.meta.artifactKey); - AddArtifactKey(reachable, record.meta.lastSuccessfulArtifactKey); - } - return m_artifacts.Collect(reachable, gracePeriod, maximumSizeBytes); - }); - } + AddArtifactKey(reachable, retained.value); + } + foreach (AssetRecord record in m_recordsByPath.Values) + { + AddArtifactKey(reachable, record.meta.artifactKey); + AddArtifactKey(reachable, record.meta.lastSuccessfulArtifactKey); + } + return m_artifacts.Collect(reachable, gracePeriod, maximumSizeBytes); + }); /// /// Tries to resolve a named output from the current artifact bundle. /// - /// + /// /// The stable persistent identity used for lookup. /// /// @@ -72,20 +71,23 @@ long maximumSizeBytes /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact ) { AssetArtifactInfo? result = Execute(() => { - if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) + if (!m_recordsByID.TryGetValue(persistentID, out AssetRecord? record)) + { return null; + } return m_artifacts.TryGet( new AssetArtifactKey(record.meta.artifactKey), outputName, - out AssetArtifactInfo? found) - ? found - : null; + out AssetArtifactInfo? found + ) + ? found + : null; }); artifact = result; return result is not null; @@ -94,7 +96,7 @@ out AssetArtifactInfo? artifact /// /// Acquires an immutable output while excluding concurrent artifact collection. /// - /// + /// /// The source asset's persistent identity. /// /// @@ -107,15 +109,16 @@ out AssetArtifactInfo? artifact /// No current output can be resolved. /// public ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName - ) - => Execute(() => + ) => Execute(() => + { + if (!TryGetArtifact(persistentID, outputName, out AssetArtifactInfo? artifact) || artifact is null) { - if (!TryGetArtifact(persistentId, outputName, out AssetArtifactInfo? artifact) || artifact is null) - throw new InvalidOperationException($"Asset '{persistentId:D}' has no output '{outputName}'."); - return m_artifactRetention.Retain(artifact, m_artifacts.CreateReadFactory(artifact)); - }); + throw new InvalidOperationException($"Asset '{persistentID:D}' has no output '{outputName}'."); + } + return m_artifactRetention.Retain(artifact, m_artifacts.CreateReadFactory(artifact)); + }); /// /// Collects canonical assets that have no external managed references. @@ -130,7 +133,9 @@ private int UnloadUnusedAssetsLocked() { SweepCandidate[] candidates = DetachSweepCandidatesLocked(); if (candidates.Length == 0) + { return 0; + } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); @@ -153,11 +158,13 @@ private int UnloadUnusedAssetsLocked() [MethodImpl(MethodImplOptions.NoInlining)] private SweepCandidate[] DetachSweepCandidatesLocked() { - var result = new List(); + List result = []; foreach (AssetRecord record in m_recordsByPath.Values) { if (record.asset is null) + { continue; + } result.Add(new SweepCandidate(record, new WeakReference(record.asset))); record.asset = null; } @@ -169,12 +176,13 @@ private static void AddArtifactKey( string value ) { if (!string.IsNullOrWhiteSpace(value)) + { reachable.Add(value.ToUpperInvariant()); + } } private readonly record struct SweepCandidate( AssetRecord record, WeakReference reference ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs index a9f8beafb..fcc09e312 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Stops new loads and releases canonical assets before their registries and diagnostics. @@ -40,35 +39,41 @@ public void Dispose() lock (m_asyncSync) { if (m_disposed) + { return; + } m_disposeRequested = true; bool pending = m_inFlightPathLoads.Values - .Concat(m_inFlightIdLoads.Values) + .Concat(m_inFlightIDLoads.Values) .Any(static task => !task.IsCompleted); if (pending || m_admittedOperations > 0 || m_retirementActive) + { throw new RetirementPendingException("Asset operations must complete before their loader retires."); + } m_retirementActive = true; } - AssetLoader? previous = t_activeLoader; - t_activeLoader = this; + AssetLoader? previous = s_activeLoader; + s_activeLoader = this; try { DisposeLocked(); } finally { - t_activeLoader = previous; + s_activeLoader = previous; if (m_disposed) + { m_operationGate.Dispose(); + } lock (m_asyncSync) + { m_retirementActive = false; + } } } private void RetireUnmountedRecordLocked(AssetRecord record) - => RetireRecordLocked( - record, - $"Asset source mount for '{record.relativePath}' is not active."); + => RetireRecordLocked(record, $"Asset source mount for '{record.relativePath}' is not active."); private void RetireRecordLocked( AssetRecord record, @@ -77,7 +82,7 @@ string diagnostic string recordPath = record.relativePath; m_recordsByPath.Remove(recordPath); m_importGraph.RemoveNode(recordPath); - if (record.persistentId == Guid.Empty) + if (record.persistentID == Guid.Empty) { return; } @@ -88,7 +93,7 @@ string diagnostic record.meta.artifactKey = string.Empty; // Tombstones retain neutral intent; only live payload and object retention retire. record.payload = []; - m_runtimeGraph.ReplaceDependencies(record.persistentId, []); + m_runtimeGraph.ReplaceDependencies(record.persistentID, []); if (record.asset is null) { return; @@ -101,7 +106,8 @@ string diagnostic record.meta.sourceHash, ReadOnlyMemory.Empty, true, - record.asset.contentVersion + 1); + record.asset.contentVersion + 1 + ); PublishReloaded(record.asset); } @@ -112,14 +118,16 @@ private bool ReleaseRetiredCanonicalAssetsLocked() { AssetObject? asset = record.asset; if (asset is null) + { continue; + } bool isCurrent = m_types.TryGetTypeRef(asset.GetType(), out _); - TypeRef persistedType = new(record.stableTypeId); - if (isCurrent && - (record.stableTypeId == Guid.Empty || - !m_types.TryResolve(persistedType, out Type? resolvedType) || - resolvedType == asset.GetType())) - { + var persistedType = new TypeRef(record.stableTypeID); + if (isCurrent + && (record.stableTypeID == Guid.Empty + || !m_types.TryResolve(persistedType, out Type? resolvedType) + || resolvedType == asset.GetType()) + ) { continue; } @@ -135,7 +143,8 @@ private bool ReleaseRetiredCanonicalAssetsLocked() m_log.Write( LogLevel.Error, "Retired asset '{0}' was released, but an identity observer failed: {1}", - [record.relativePath, exception]); + [record.relativePath, exception] + ); } finally { @@ -149,17 +158,21 @@ private bool ReleaseRetiredCanonicalAssetsLocked() private void DisposeLocked() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new LifetimeScope(); m_retirement.Own(m_buildProcessors); m_retirement.Own(m_importers); m_retirement.Own(m_diagnostics); - foreach (AssetRecord record in m_recordsById.Values) + foreach (AssetRecord record in m_recordsByID.Values) { if (record.asset is not null) + { m_retirement.Own(new AssetRecordRetirement(this, record)); + } } } try @@ -183,7 +196,7 @@ private void CompleteRetirement() m_disposed = true; m_sourceMetadataStage = null; m_recordsByPath.Clear(); - m_recordsById.Clear(); + m_recordsByID.Clear(); m_runtimeGraph.Clear(); m_importGraph.Clear(); m_missingAssets.Clear(); @@ -191,7 +204,7 @@ private void CompleteRetirement() lock (m_asyncSync) { m_inFlightPathLoads.Clear(); - m_inFlightIdLoads.Clear(); + m_inFlightIDLoads.Clear(); } } @@ -200,8 +213,8 @@ private sealed class AssetRecordRetirement( AssetRecord record ) : IDisposable { - private bool m_released; private readonly List m_failures = []; + private bool m_released; /// /// Keeps the canonical registration until its unload hook has actually quiesced. @@ -209,7 +222,9 @@ AssetRecord record public void Dispose() { if (record.asset is null) + { return; + } if (!m_released) { try @@ -240,8 +255,9 @@ public void Dispose() } record.asset = null; if (m_failures.Count > 0) + { throw new AggregateException("Canonical Asset retirement failed after releasing its registration.", m_failures); + } } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs index 4dd6e5dac..436a50ba4 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Writes a source-free runtime catalog and its exact immutable artifact closure. @@ -66,8 +65,7 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationLibraryR public AssetRuntimeContentInfo ExportRuntimeArtifacts( string destinationLibraryRoot, CancellationToken cancellationToken - ) - => Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken)); + ) => Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken)); internal AssetRuntimeContentInfo ExportRuntimeArtifacts( string destinationLibraryRoot, @@ -75,10 +73,7 @@ internal AssetRuntimeContentInfo ExportRuntimeArtifacts( CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(serialization); - return Execute(() => ExportRuntimeArtifactsLocked( - destinationLibraryRoot, - cancellationToken, - serialization)); + return Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken, serialization)); } private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( @@ -90,16 +85,19 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( ArgumentException.ThrowIfNullOrWhiteSpace(destinationLibraryRoot); string destination = Path.GetFullPath(destinationLibraryRoot); if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any()) + { throw new IOException("Runtime asset content destination must be empty."); + } AssetRecord[] imported = m_recordsByPath.Values - .Where(static record => + .Where(static record => ( !record.meta.isDirectory && !record.meta.isTombstone && !AssetSample.IsRuntimeExcluded(AssetPath.Parse(record.relativePath), isDirectory: false) && (record.meta.importStatus == (int)AssetImportStatus.Imported || !string.IsNullOrEmpty(record.meta.artifactKey) || (!string.IsNullOrEmpty(record.meta.importerId) - && record.meta.importStatus is (int)AssetImportStatus.Pending or (int)AssetImportStatus.Failed))) + && record.meta.importStatus is (int)AssetImportStatus.Pending or (int)AssetImportStatus.Failed)) + )) .OrderBy(static record => record.relativePath, StringComparer.Ordinal) .ToArray(); AssetRecord? invalidScope = imported.FirstOrDefault(static record => @@ -107,14 +105,17 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( if (invalidScope is not null) { throw new InvalidOperationException( - $"Asset '{invalidScope.relativePath}' has an invalid deployment scope."); + $"Asset '{invalidScope.relativePath}' has an invalid deployment scope." + ); } AssetRecord[] exported = imported .Where(static record => record.meta.deploymentScope == (int)AssetDeploymentScope.Runtime) .ToArray(); var validated = new HashSet(); foreach (AssetRecord record in exported) + { ValidateExportInputsLocked(record, record.relativePath, validated, cancellationToken); + } string[] keys = exported .Select(static record => record.meta.artifactKey) .Distinct(StringComparer.Ordinal) @@ -122,42 +123,51 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( .ToArray(); foreach (AssetRecord record in exported) { - AssetArtifactKey key = new(record.meta.artifactKey); + var key = new AssetArtifactKey(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", serialization, out _) - || !m_artifacts.TryGet(key, "runtime", serialization, out _)) - { + || !m_artifacts.TryGet(key, "runtime", serialization, out _) + ) { throw new InvalidOperationException( - $"Asset '{record.relativePath}' has no complete runtime artifact bundle '{key}'."); + $"Asset '{record.relativePath}' has no complete runtime artifact bundle '{key}'." + ); } } - HashSet exportedIds = exported - .Select(static record => record.persistentId) + HashSet exportedIDs = exported + .Select(static record => record.persistentID) .ToHashSet(); foreach (AssetRecord record in exported) { AssetDependencyData unavailable = record.meta.runtimeDependencies - .FirstOrDefault(dependency => !exportedIds.Contains(dependency.persistentId)); + .FirstOrDefault(dependency => !exportedIDs.Contains(dependency.persistentId)); if (unavailable.persistentId != Guid.Empty) { throw new InvalidOperationException( - $"Runtime asset '{record.relativePath}' depends on non-runtime asset " + - $"'{unavailable.lastKnownPath}'."); + $"Runtime asset '{record.relativePath}' depends on non-runtime asset " + + $"'{unavailable.lastKnownPath}'." + ); } } Directory.CreateDirectory(destination); AssetCatalogStore catalog = serialization is null - ? new AssetCatalogStore(destination, m_serialization) - : new AssetCatalogStore(destination, serialization); + ? new AssetCatalogStore(destination, m_serialization) + : new AssetCatalogStore(destination, serialization); var destinationArtifacts = new AssetArtifactStore(destination, m_serialization); var projectedKeys = new Dictionary(StringComparer.Ordinal); foreach (string key in keys) - projectedKeys.Add(key, m_artifacts.ExportRuntime(new(key), destinationArtifacts, serialization, cancellationToken)); - var deployed = new List(); + { + projectedKeys.Add( + key, + m_artifacts.ExportRuntime(new AssetArtifactKey(key), destinationArtifacts, serialization, cancellationToken) + ); + } + List deployed = []; foreach (AssetRecord record in exported) { byte[] bytes = serialization is null ? m_serialization.Serialize(record.meta) : serialization.Serialize(record.meta); - AssetMeta meta = serialization is null ? m_serialization.Deserialize(bytes) : serialization.Deserialize(bytes); + AssetMeta meta = serialization is null + ? m_serialization.Deserialize(bytes) + : serialization.Deserialize(bytes); meta.artifactKey = projectedKeys[record.meta.artifactKey].value; meta.lastSuccessfulArtifactKey = meta.artifactKey; meta.importDependencies = []; @@ -167,16 +177,19 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( long totalBytes = Directory .EnumerateFiles(Path.Combine(destination, "AssetDatabase"), "*", SearchOption.AllDirectories) .Sum(static path => new FileInfo(path).Length); - totalBytes += Directory.EnumerateFiles(destinationArtifacts.root, "*", SearchOption.AllDirectories).Sum(static path => new FileInfo(path).Length); + totalBytes += Directory.EnumerateFiles(destinationArtifacts.root, "*", SearchOption.AllDirectories) + .Sum(static path => new FileInfo(path).Length); - AssetSourceId[] sources = exported + AssetSourceID[] sources = exported .Select(static record => AssetPath.Parse(record.relativePath).source) - .Append(AssetSourceId.project) + .Append(AssetSourceID.project) .Distinct() .OrderBy(static source => source.value, StringComparer.Ordinal) .ToArray(); - foreach (AssetSourceId source in sources) + foreach (AssetSourceID source in sources) + { Directory.CreateDirectory(Path.Combine(destination, "Sources", source.value)); + } return new AssetRuntimeContentInfo(sources, exported.Length, keys.Length, totalBytes); } @@ -187,14 +200,17 @@ private void ValidateExportInputsLocked( CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); - if (!validated.Add(record.persistentId)) + if (!validated.Add(record.persistentID)) + { return; + } if (record.meta.isTombstone || record.meta.importStatus != (int)AssetImportStatus.Imported) { throw new InvalidOperationException( - $"Runtime export requires successful current inputs: {dependencyChain}. " + - $"Status: {(AssetImportStatus)record.meta.importStatus}. " + - string.Join(" | ", record.meta.diagnostics)); + $"Runtime export requires successful current inputs: {dependencyChain}. " + + $"Status: {(AssetImportStatus)record.meta.importStatus}. " + + string.Join(" | ", record.meta.diagnostics) + ); } // Validate authoring inputs as well as deployed references. Editor last-good artifacts @@ -202,12 +218,15 @@ CancellationToken cancellationToken foreach (AssetImportDependencyData dependency in record.meta.importDependencies) { if ((AssetImportDependencyKind)dependency.kind != AssetImportDependencyKind.Artifact) + { continue; + } if (!Guid.TryParse(dependency.key, out Guid id) - || !m_recordsById.TryGetValue(id, out AssetRecord? input)) - { + || !m_recordsByID.TryGetValue(id, out AssetRecord? input) + ) { throw new InvalidOperationException( - $"Runtime export has a missing artifact input: {dependencyChain} -> {dependency.key}."); + $"Runtime export has a missing artifact input: {dependencyChain} -> {dependency.key}." + ); } ValidateExportInputsLocked(input, $"{dependencyChain} -> {input.relativePath}", validated, cancellationToken); } @@ -216,7 +235,8 @@ CancellationToken cancellationToken if (IsStale(record, out _)) { throw new InvalidOperationException( - $"Runtime export has stale source inputs: {dependencyChain}. Reimport current sources and rebuild."); + $"Runtime export has stale source inputs: {dependencyChain}. Reimport current sources and rebuild." + ); } } @@ -227,26 +247,32 @@ private void ValidateRuntimeArtifactsLocked() if (!IsMounted(record.relativePath)) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' references an undeclared source mount."); + $"Runtime asset '{record.relativePath}' references an undeclared source mount." + ); } if (record.meta.isDirectory || record.meta.isTombstone) + { continue; + } if (record.meta.deploymentScope != (int)AssetDeploymentScope.Runtime) { throw new InvalidDataException( - $"Runtime catalog contains authoring-only asset '{record.relativePath}'."); + $"Runtime catalog contains authoring-only asset '{record.relativePath}'." + ); } if (record.meta.importStatus != (int)AssetImportStatus.Imported) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' was not successfully imported before export."); + $"Runtime asset '{record.relativePath}' was not successfully imported before export." + ); } - AssetArtifactKey key = new(record.meta.artifactKey); + var key = new AssetArtifactKey(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", out _) - || !m_artifacts.TryGet(key, "runtime", out _)) - { + || !m_artifacts.TryGet(key, "runtime", out _) + ) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' has an incomplete artifact bundle '{key}'."); + $"Runtime asset '{record.relativePath}' has an incomplete artifact bundle '{key}'." + ); } } } @@ -254,10 +280,11 @@ private void ValidateRuntimeArtifactsLocked() private void EnsureReadOnlyImportsSucceededLocked() { AssetRecord[] failed = m_recordsByPath.Values - .Where(record => + .Where(record => ( GetMount(record.relativePath).isReadOnly && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) + or (int)AssetImportStatus.Conflict + )) .OrderBy(static record => record.relativePath, StringComparer.Ordinal) .ToArray(); if (failed.Length == 0) @@ -267,10 +294,8 @@ private void EnsureReadOnlyImportsSucceededLocked() string details = string.Join( "; ", - failed.Select(record => - $"{record.relativePath}: {string.Join(" | ", record.meta.diagnostics)}")); - throw new InvalidDataException( - $"Read-only Asset Source candidate contains failed imports: {details}"); + failed.Select(record => $"{record.relativePath}: {string.Join(" | ", record.meta.diagnostics)}") + ); + throw new InvalidDataException($"Read-only Asset Source candidate contains failed imports: {details}"); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs index 55cfee824..c171d4152 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Saves an asset back to its current source path. @@ -39,7 +38,9 @@ public bool Save(AssetObject asset) { ArgumentNullException.ThrowIfNull(asset); if (string.IsNullOrWhiteSpace(asset.assetPath.ToString())) + { throw new InvalidOperationException("An unsaved asset requires an explicit source-relative path."); + } return Save(asset.assetPath, asset); } @@ -69,53 +70,60 @@ private bool SaveLocked( AssetObject asset ) { if (GetMount(relativePath).isReadOnly) - throw new InvalidOperationException($"Asset source '{relativePath}' is read-only."); - if (!string.IsNullOrWhiteSpace(asset.assetPath.ToString()) && - !string.Equals(NormalizeRelativePath(asset.assetPath.ToString()), relativePath, StringComparison.OrdinalIgnoreCase)) { + throw new InvalidOperationException($"Asset source '{relativePath}' is read-only."); + } + if (!string.IsNullOrWhiteSpace(asset.assetPath.ToString()) + && !string.Equals(NormalizeRelativePath(asset.assetPath.ToString()), relativePath, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException( - $"Asset '{asset.assetPath.ToString()}' cannot be saved to unrelated path '{relativePath}' without creating a new asset."); + $"Asset '{asset.assetPath.ToString()}' cannot be saved to unrelated path '{relativePath}' without creating a new asset." + ); } AssetImporter? importer = m_importers.FindByPath(relativePath); if (importer is null || !importer.targetAssetType.IsInstanceOfType(asset)) + { return false; + } ReadOnlyMemory? exported = importer - .ExportInternalAsync( - new AssetExportContext(m_types, m_serialization, this), - asset, - CancellationToken.None) + .ExportInternalAsync(new AssetExportContext(m_types, m_serialization, this), asset, CancellationToken.None) .AsTask() .GetAwaiter() .GetResult(); if (exported is null) + { return false; + } byte[] sourceBytes = exported.Value.ToArray(); AssetRecord? destinationRecord = FindRecordLocked(relativePath); bool destinationOwnsIdentity = destinationRecord is not null - && destinationRecord.persistentId != Guid.Empty; - Guid persistentId = destinationOwnsIdentity - ? destinationRecord!.persistentId - : asset.identity.persistentId; - if (persistentId == Guid.Empty) - persistentId = Guid.NewGuid(); - if (asset.identity.runtimeId is not null && asset.identity.persistentId != persistentId) + && destinationRecord.persistentID != Guid.Empty; + Guid persistentID = destinationOwnsIdentity + ? destinationRecord!.persistentID + : asset.identity.persistentID; + if (persistentID == Guid.Empty) + { + persistentID = Guid.NewGuid(); + } + if (asset.identity.runtimeID is not null && asset.identity.persistentID != persistentID) { throw new InvalidOperationException( - $"Registered asset '{asset.identity.persistentId:D}' cannot replace destination identity " + - $"'{persistentId:D}' at '{relativePath}'."); + $"Registered asset '{asset.identity.persistentID:D}' cannot replace destination identity " + + $"'{persistentID:D}' at '{relativePath}'." + ); } - ImportBuild build = BuildImportLocked(relativePath, sourceBytes, importer, persistentId); + ImportBuild build = BuildImportLocked(relativePath, sourceBytes, importer, persistentID); AssetRecord? provisionalRecord = null; bool registeredHere = false; if (string.IsNullOrWhiteSpace(asset.assetPath.ToString()) && !destinationOwnsIdentity) { - m_identities.InitializePersistentIdentity(asset, persistentId); - registeredHere = m_identitiesActive && m_identities.Register(asset, persistentId); + m_identities.InitializePersistentIdentity(asset, persistentID); + registeredHere = m_identitiesActive && m_identities.Register(asset, persistentID); provisionalRecord = new AssetRecord { relativePath = relativePath, - persistentId = persistentId, - stableTypeId = build.meta.stableAssetTypeId, + persistentID = persistentID, + stableTypeID = build.meta.stableAssetTypeId, meta = build.meta, payload = build.payload, asset = asset @@ -136,26 +144,35 @@ AssetObject asset catch { if (provisionalRecord is not null) + { RemoveRecordLocked(provisionalRecord, removeGeneratedFiles: false); + } if (registeredHere) + { m_identities.Unregister(asset); + } throw; } AssetRecord committed = m_recordsByPath[relativePath]; if (committed.asset is null) { - if (asset.identity.persistentId != persistentId) - m_identities.InitializePersistentIdentity(asset, persistentId); + if (asset.identity.persistentID != persistentID) + { + m_identities.InitializePersistentIdentity(asset, persistentID); + } committed.asset = asset; - if (m_identitiesActive && asset.identity.runtimeId is null) - m_identities.Register(asset, persistentId); + if (m_identitiesActive && asset.identity.runtimeID is null) + { + m_identities.Register(asset, persistentID); + } m_runtimeOwner.Initialize( asset, AssetPath.Parse(relativePath), build.meta.sourceHash, build.payload, false, - 1); + 1 + ); AttachDependenciesLocked(committed); } return true; @@ -171,29 +188,18 @@ private void RestoreCanonical( long version ) { RestoreAssetState(canonical, state); - m_runtimeOwner.Initialize( - canonical, - AssetPath.Parse(sourcePath), - sourceHash, - payload, - isMissing, - version); + m_runtimeOwner.Initialize(canonical, AssetPath.Parse(sourcePath), sourceHash, payload, isMissing, version); } private byte[] CaptureAssetState(AssetObject asset) - => m_serialization.Encode( - writer => writer.WriteProperties(asset), - m_serializationContext); + => m_serialization.Encode(writer => writer.WriteProperties(asset), m_serializationContext); private void RestoreAssetState( AssetObject asset, ReadOnlySpan state - ) { - m_serialization.Decode(state, reader => - { - reader.RestoreProperties(asset); - return true; - }, m_serializationContext); - } - + ) => m_serialization.Decode(state, reader => + { + reader.RestoreProperties(asset); + return true; + }, m_serializationContext); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs index 4359eba75..b9d5bbcee 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Reconciles source files, metadata, artifacts and the in-memory catalog. @@ -67,15 +66,16 @@ private void RescanLocked() { m_importCancellation.ThrowIfCancellationRequested(); LoadCatalogLocked(); - bool registriesChanged = - m_importerRegistryVersion != m_importers.snapshotVersion || - m_buildProcessorRegistryVersion != m_buildProcessors.snapshotVersion; + bool registriesChanged = m_importerRegistryVersion != m_importers.snapshotVersion + || m_buildProcessorRegistryVersion != m_buildProcessors.snapshotVersion; bool releasedRetiredAssets = ReleaseRetiredCanonicalAssetsLocked(); if (m_runtimeArtifactsOnly) { ValidateRuntimeArtifactsLocked(); if (releasedRetiredAssets || registriesChanged) + { RefreshLoadedAssetReferencesLocked(); + } m_importerRegistryVersion = m_importers.snapshotVersion; m_buildProcessorRegistryVersion = m_buildProcessors.snapshotVersion; return; @@ -83,9 +83,7 @@ private void RescanLocked() EnsureDirectoryMetadataLocked(); AssetPath[] sourceFiles = m_mounts.Values .SelectMany(mount => Directory.GetFiles(mount.rootPath, "*", SearchOption.AllDirectories) - .Select(path => new AssetPath( - mount.id, - Path.GetRelativePath(mount.rootPath, path).Replace('\\', '/')))) + .Select(path => new AssetPath(mount.id, Path.GetRelativePath(mount.rootPath, path).Replace('\\', '/')))) .Where(path => !IsSourceIgnored(path, isDirectory: false)) .ToArray(); foreach (AssetPath sourceFile in sourceFiles) @@ -101,14 +99,15 @@ private void RescanLocked() } TryAssociateUntrackedRenameLocked(relative, absoluteSource); AssetRecord? record = FindRecordLocked(relative); - if (record is null || - record.asset?.isMissing == true || - IsStale(record, out _) || - (record.meta.importStatus == (int)AssetImportStatus.Imported && !m_artifacts.TryGet( + if (record is null + || record.asset?.isMissing == true + || IsStale(record, out _) + || (record.meta.importStatus == (int)AssetImportStatus.Imported && !m_artifacts.TryGet( new AssetArtifactKey(record.meta.artifactKey), "asset-state", - out _))) - { + out _ + )) + ) { ImportLocked(relative); } } @@ -121,13 +120,17 @@ private void RescanLocked() continue; } - if (IOFile.Exists(GetSourcePath(record.relativePath)) || - Directory.Exists(GetSourcePath(record.relativePath))) + if (IOFile.Exists(GetSourcePath(record.relativePath)) + || Directory.Exists(GetSourcePath(record.relativePath)) + ) { continue; + } HandleDeletedLocked(record.relativePath); } if (releasedRetiredAssets || registriesChanged) + { RefreshLoadedAssetReferencesLocked(); + } CommitCatalogLocked(); EnsureReadOnlyImportsSucceededLocked(); m_importerRegistryVersion = m_importers.snapshotVersion; @@ -138,10 +141,11 @@ private void RescanLocked() private void ApplySourceChangesLocked(IReadOnlyList changes) { - if (changes.Any(change => - IsSampleChangePath(change.relativePath) || - IsSampleChangePath(change.oldRelativePath))) - { + if (changes.Any(change => ( + IsSampleChangePath(change.relativePath) + || IsSampleChangePath(change.oldRelativePath) + )) + ) { RescanLocked(); return; } @@ -153,11 +157,15 @@ private void ApplySourceChangesLocked(IReadOnlyList changes) string ownerPath = NormalizeRelativePath(change.relativePath[..^C_META_POSTFIX.Length]); AssetRecord? owner = FindRecordLocked(ownerPath); if (owner is not null && !owner.meta.isDirectory && IsStale(owner, out _)) + { ImportLocked(ownerPath); + } continue; } if (IsInternalGeneratedPath(change.relativePath)) + { continue; + } if (change.changeType.HasFlag(WatcherChangeTypes.Renamed)) { HandleRenameLocked(change.oldRelativePath, change.relativePath); @@ -171,7 +179,9 @@ private void ApplySourceChangesLocked(IReadOnlyList changes) ImportLocked(NormalizeRelativePath(change.relativePath)); } foreach ((string path, int matchCount) in ambiguousRenames) + { RecordAmbiguousRenameDiagnosticLocked(path, matchCount); + } } private void HandleRenameLocked( @@ -193,21 +203,23 @@ string newPath } string oldMeta = GetMetaPath(oldNormalized); string newMeta = GetMetaPath(newNormalized); - if (TryReadSourceMeta(newMeta, out AssetSourceMeta targetMeta) && - targetMeta.persistentId != record.persistentId) - { + if (TryReadSourceMeta(newMeta, out AssetSourceMeta targetMeta) + && targetMeta.persistentId != record.persistentID + ) { record.meta.importStatus = (int)AssetImportStatus.Conflict; record.meta.diagnostics = [ - $"Rename target '{newNormalized}' already owns persistent id " + - $"'{targetMeta.persistentId}'." + $"Rename target '{newNormalized}' already owns persistent id " + + $"'{targetMeta.persistentId}'." ]; CommitCatalogLocked(); return; } if (IOFile.Exists(oldMeta) && !IOFile.Exists(newMeta)) + { MoveGeneratedFile(oldMeta, newMeta); + } m_recordsByPath.Remove(oldNormalized); m_importGraph.RemoveNode(oldNormalized); record.relativePath = newNormalized; @@ -229,7 +241,8 @@ string newPath record.meta.sourceHash, ReadOnlyMemory.Empty, true, - replaced.contentVersion + 1); + replaced.contentVersion + 1 + ); m_runtimeOwner.Release(replaced); m_identities.Unregister(replaced); record.asset = null; @@ -241,22 +254,26 @@ string newPath record.meta.importStatus = (int)AssetImportStatus.Imported; record.meta.diagnostics = []; if (record.asset is not null) + { m_runtimeOwner.UpdateAssetPath(record.asset, AssetPath.Parse(newNormalized)); + } } m_recordsByPath[newNormalized] = record; // A renamed source may deliberately carry a different importer and its matching settings. // The source sidecar is authoritative; cached importer state must not relabel those bytes. if (ReadMetadata(newMeta) is null) + { WriteSourceMeta(record.meta); + } UpdateGraphsLocked(record); CommitCatalogLocked(); bool catalogChanged = false; bool stale = importer is not null && IsStale(record, out catalogChanged); - if (importer is not null && - (!string.Equals(importer.importerId, record.meta.importerId, StringComparison.Ordinal) || - stale)) - { + if (importer is not null + && (!string.Equals(importer.importerID, record.meta.importerId, StringComparison.Ordinal) + || stale) + ) { ImportLocked(newNormalized); } else if (catalogChanged) @@ -270,13 +287,16 @@ private void HandleDeletedLocked(string relativePath) string normalized = NormalizeRelativePath(relativePath); string prefix = normalized + "/"; AssetRecord[] records = m_recordsByPath.Values - .Where(record => - string.Equals(record.relativePath, normalized, StringComparison.OrdinalIgnoreCase) || - record.relativePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Where(record => ( + string.Equals(record.relativePath, normalized, StringComparison.OrdinalIgnoreCase) + || record.relativePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + )) .OrderByDescending(static record => record.relativePath.Length) .ToArray(); if (records.Length == 0) + { return; + } for (int i = 0; i < records.Length; i++) { @@ -286,8 +306,10 @@ private void HandleDeletedLocked(string relativePath) m_recordsByPath.Remove(recordPath); m_importGraph.RemoveNode(recordPath); - if (record.persistentId == Guid.Empty) + if (record.persistentID == Guid.Empty) + { continue; + } record.meta.isTombstone = true; record.meta.importStatus = (int)AssetImportStatus.Missing; @@ -295,7 +317,7 @@ private void HandleDeletedLocked(string relativePath) record.meta.artifactKey = string.Empty; // A returning source must be recoverable without the retired managed generation. record.payload = []; - m_runtimeGraph.ReplaceDependencies(record.persistentId, []); + m_runtimeGraph.ReplaceDependencies(record.persistentID, []); if (record.asset is not null) { m_dependencyRetention.Remove(record.asset); @@ -305,7 +327,8 @@ private void HandleDeletedLocked(string relativePath) record.meta.sourceHash, ReadOnlyMemory.Empty, true, - record.asset.contentVersion + 1); + record.asset.contentVersion + 1 + ); PublishReloaded(record.asset); } } @@ -317,16 +340,21 @@ private int TryAssociateUntrackedRenameLocked( string absoluteSourcePath ) { if (m_recordsByPath.ContainsKey(relativePath) || IOFile.Exists(GetMetaPath(relativePath))) + { return 0; + } string fingerprint = ComputeSha256Hex(IOFile.ReadAllBytes(absoluteSourcePath)); AssetRecord[] matches = m_recordsByPath.Values - .Where(record => - !record.meta.isDirectory && - !IOFile.Exists(GetSourcePath(record.relativePath)) && - string.Equals(record.meta.sourceHash, fingerprint, StringComparison.Ordinal)) + .Where(record => ( + !record.meta.isDirectory + && !IOFile.Exists(GetSourcePath(record.relativePath)) + && string.Equals(record.meta.sourceHash, fingerprint, StringComparison.Ordinal) + )) .ToArray(); if (matches.Length == 1) + { HandleRenameLocked(matches[0].relativePath, relativePath); + } return matches.Length; } @@ -336,10 +364,10 @@ private IReadOnlyDictionary AssociateUntrackedRenamesLocked(IReadOn for (int i = 0; i < changes.Count; i++) { AssetChangedEvent change = changes[i]; - if (change.changeType.HasFlag(WatcherChangeTypes.Deleted) || - change.changeType.HasFlag(WatcherChangeTypes.Renamed) || - IsInternalGeneratedPath(change.relativePath)) - { + if (change.changeType.HasFlag(WatcherChangeTypes.Deleted) + || change.changeType.HasFlag(WatcherChangeTypes.Renamed) + || IsInternalGeneratedPath(change.relativePath) + ) { continue; } @@ -349,7 +377,9 @@ private IReadOnlyDictionary AssociateUntrackedRenamesLocked(IReadOn { int matches = TryAssociateUntrackedRenameLocked(relativePath, absolutePath); if (matches > 1) + { ambiguous[relativePath] = matches; + } } } return ambiguous; @@ -361,9 +391,10 @@ string newPath ) { string oldPrefix = oldPath + "/"; AssetRecord[] records = m_recordsByPath.Values - .Where(record => - string.Equals(record.relativePath, oldPath, StringComparison.OrdinalIgnoreCase) || - record.relativePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase)) + .Where(record => ( + string.Equals(record.relativePath, oldPath, StringComparison.OrdinalIgnoreCase) + || record.relativePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase) + )) .OrderBy(static record => record.relativePath.Length) .ToArray(); if (records.Length == 0) @@ -376,14 +407,16 @@ string newPath string oldFolderMeta = GetMetaPath(oldPath); string newFolderMeta = GetMetaPath(newPath); if (IOFile.Exists(oldFolderMeta) && !IOFile.Exists(newFolderMeta)) + { MoveGeneratedFile(oldFolderMeta, newFolderMeta); + } for (int i = 0; i < records.Length; i++) { AssetRecord record = records[i]; string suffix = record.relativePath.Length == oldPath.Length - ? string.Empty - : record.relativePath[oldPath.Length..]; + ? string.Empty + : record.relativePath[oldPath.Length..]; string destination = newPath + suffix; m_recordsByPath.Remove(record.relativePath); m_importGraph.RemoveNode(record.relativePath); @@ -392,7 +425,9 @@ string newPath record.meta.importStatus = (int)AssetImportStatus.Imported; record.meta.diagnostics = []; if (record.asset is not null) + { m_runtimeOwner.UpdateAssetPath(record.asset, AssetPath.Parse(destination)); + } m_recordsByPath[destination] = record; UpdateGraphsLocked(record); } @@ -413,7 +448,9 @@ bool isDirectory for (int i = 0; i < segments.Length - (isDirectory ? 0 : 1); i++) { if (m_sourcePolicy.IsIgnored(segments[i], isDirectory: true)) + { return true; + } } return m_sourcePolicy.IsIgnored(localPath, isDirectory); } @@ -421,9 +458,10 @@ bool isDirectory private static bool IsSampleChangePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return false; + } AssetPath path = AssetPath.Parse(relativePath); return AssetSample.IsRoot(path) || AssetSample.Contains(path, isDirectory: false); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs index 8d62ba4be..8cc57cee6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs @@ -7,24 +7,23 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { private bool IsStale( AssetRecord record, @@ -33,47 +32,61 @@ out bool catalogChanged catalogChanged = false; string sourcePath = GetSourcePath(record.relativePath); if (!IOFile.Exists(sourcePath)) + { return true; - AssetImporter? importer = m_importers.FindById(record.meta.importerId); - if (importer is null || - !string.Equals( + } + AssetImporter? importer = m_importers.FindByID(record.meta.importerId); + if (importer is null + || !string.Equals( record.meta.importerImplementationFingerprint, GetImporterImplementationFingerprint(importer), - StringComparison.Ordinal)) - { + StringComparison.Ordinal + ) + ) { return true; } if (record.importerGeneration != m_importers.GetGeneration(record.meta.importerId)) + { return true; - if (record.meta.importStatus != (int)AssetImportStatus.Imported && - record.meta.importStatus != (int)AssetImportStatus.Failed) + } + if (record.meta.importStatus != (int)AssetImportStatus.Imported + && record.meta.importStatus != (int)AssetImportStatus.Failed + ) { return true; + } // A failed dependency can recover when another extension becomes available, even when // this importer's implementation and source bytes are unchanged. Retry once per catalog // generation; the transient observation deliberately does not survive a loader restart. if (record.meta.importStatus == (int)AssetImportStatus.Failed - && record.failedTypeGeneration != m_types.current.version) + && record.failedTypeGeneration != m_types.current.version + ) { return true; - if (record.meta.importStatus == (int)AssetImportStatus.Failed && - record.meta.diagnostics.Any(static diagnostic => - diagnostic.StartsWith("IOException:", StringComparison.Ordinal) || - diagnostic.StartsWith("UnauthorizedAccessException:", StringComparison.Ordinal))) - { + } + if (record.meta.importStatus == (int)AssetImportStatus.Failed + && record.meta.diagnostics.Any(static diagnostic => ( + diagnostic.StartsWith("IOException:", StringComparison.Ordinal) + || diagnostic.StartsWith("UnauthorizedAccessException:", StringComparison.Ordinal) + )) + ) { // File locks and access checks may clear without any source or importer change. return true; } if (AreImportSettingsStaleLocked(record, importer)) + { return true; + } if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { return true; + } bool stampChanged = !SourceStampMatches(record.meta, sourceStamp); if (!GetMount(record.relativePath).isReadOnly || stampChanged) { if (!string.Equals( - record.meta.sourceHash, - ReadStableSourceHash(sourcePath, out sourceStamp), - StringComparison.Ordinal)) - { + record.meta.sourceHash, + ReadStableSourceHash(sourcePath, out sourceStamp), + StringComparison.Ordinal + )) { return true; } if (stampChanged) @@ -86,12 +99,11 @@ out bool catalogChanged { AssetImportDependencyData dependency = record.meta.importDependencies[i]; if (record.meta.importStatus == (int)AssetImportStatus.Failed - && dependency.fingerprint.StartsWith(C_REJECTED_SOURCE_REFERENCE, StringComparison.Ordinal)) - { + && dependency.fingerprint.StartsWith(C_REJECTED_SOURCE_REFERENCE, StringComparison.Ordinal) + ) { try { - ValidateSourceReferenceLocked(record.relativePath, - NormalizeRelativePath(dependency.key)); + ValidateSourceReferenceLocked(record.relativePath, NormalizeRelativePath(dependency.key)); return true; } catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) @@ -99,18 +111,13 @@ out bool catalogChanged continue; } } - string fingerprint = ComputeImportDependencyFingerprintLocked( - ref dependency, - out bool dependencyChanged); + string fingerprint = ComputeImportDependencyFingerprintLocked(ref dependency, out bool dependencyChanged); if (dependencyChanged) { record.meta.importDependencies[i] = dependency; catalogChanged = true; } - if (!string.Equals( - dependency.fingerprint, - fingerprint, - StringComparison.Ordinal)) + if (!string.Equals(dependency.fingerprint, fingerprint, StringComparison.Ordinal)) { return true; } @@ -121,7 +128,9 @@ out bool catalogChanged private string NormalizeRelativePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { throw new ArgumentException("An asset-relative path is required.", nameof(relativePath)); + } AssetPath path = AssetPath.Parse(relativePath); _ = GetMount(path); return path.ToString(); @@ -130,7 +139,9 @@ private string NormalizeRelativePath(string relativePath) private string NormalizeAssetPath(AssetPath path) { if (!path.isValid || string.IsNullOrWhiteSpace(path.localPath)) + { throw new ArgumentException("An isolated asset path is required.", nameof(path)); + } _ = GetMount(path); return path.ToString(); } @@ -139,15 +150,14 @@ private void EnsureDirectoryMetadataLocked() { foreach (AssetSourceMount mount in m_mounts.Values) { - foreach (string directoryPath in Directory.GetDirectories( - mount.rootPath, - "*", - SearchOption.AllDirectories)) + foreach (string directoryPath in Directory.GetDirectories(mount.rootPath, "*", SearchOption.AllDirectories)) { string localPath = Path.GetRelativePath(mount.rootPath, directoryPath).Replace('\\', '/'); string relativePath = new AssetPath(mount.id, localPath).ToString(); if (IsSourceIgnored(new AssetPath(mount.id, localPath), isDirectory: true)) + { continue; + } string metaPath = GetMetaPath(relativePath); AssetSourceMeta sourceMeta; if (!TryReadSourceMeta(metaPath, out sourceMeta!)) @@ -155,7 +165,8 @@ private void EnsureDirectoryMetadataLocked() if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source directory '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar."); + $"Read-only source directory '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar." + ); } sourceMeta = new AssetSourceMeta { @@ -165,15 +176,16 @@ private void EnsureDirectoryMetadataLocked() WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); } - AssetRecord? record = FindRecordByIdWithoutLoading(sourceMeta.persistentId); - if (record is not null && - !string.Equals(record.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) && - Directory.Exists(GetSourcePath(record.relativePath))) - { + AssetRecord? record = FindRecordByIDWithoutLoading(sourceMeta.persistentId); + if (record is not null + && !string.Equals(record.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + && Directory.Exists(GetSourcePath(record.relativePath)) + ) { if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source directory '{relativePath}' duplicates persistent ID '{sourceMeta.persistentId}'."); + $"Read-only source directory '{relativePath}' duplicates persistent ID '{sourceMeta.persistentId}'." + ); } sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); @@ -181,7 +193,7 @@ record = null; } record ??= new AssetRecord(); record.relativePath = relativePath; - record.persistentId = sourceMeta.persistentId; + record.persistentID = sourceMeta.persistentId; record.meta.relativePath = relativePath; record.meta.persistentId = sourceMeta.persistentId; record.meta.isDirectory = true; @@ -198,13 +210,14 @@ private void WriteSourceMeta(AssetMeta meta) string metaPath = GetMetaPath(meta.relativePath); byte[]? existingBytes = ReadMetadata(metaPath); AssetSourceMeta? existing = existingBytes is null - ? null : m_serialization.Deserialize(existingBytes); + ? null + : m_serialization.Deserialize(existingBytes); var sourceMeta = new AssetSourceMeta { persistentId = meta.persistentId, sourceKind = meta.isDirectory - ? (int)AssetSourceKind.Directory - : (int)AssetSourceKind.File, + ? (int)AssetSourceKind.Directory + : (int)AssetSourceKind.File, importerId = meta.importerId, importerSettingsBytes = existing?.importerSettingsBytes ?? [] }; @@ -214,7 +227,8 @@ private void WriteSourceMeta(AssetMeta meta) if (!IOFile.Exists(metaPath) || !IOFile.ReadAllBytes(metaPath).AsSpan().SequenceEqual(data)) { throw new InvalidDataException( - $"Read-only source metadata for '{meta.relativePath}' is missing or inconsistent."); + $"Read-only source metadata for '{meta.relativePath}' is missing or inconsistent." + ); } return; } @@ -228,39 +242,44 @@ out AssetSourceMeta sourceMeta sourceMeta = null!; byte[]? bytes = ReadMetadata(metaPath); if (bytes is null) + { return false; + } try { sourceMeta = m_serialization.Deserialize(bytes); return sourceMeta.persistentId != Guid.Empty; } - catch + catch (Exception) { + // Metadata that cannot be deserialized is reported as unreadable. return false; } } private string CreateImportFingerprint(AssetMeta meta) { - var parts = new List - { + List parts = + [ "Inno.AssetImport", meta.sourceHash, meta.importerId, meta.importerImplementationFingerprint, meta.importerSettingsHash - }; + ]; foreach (AssetDependencyData dependency in meta.runtimeDependencies - .OrderBy(static value => value.persistentId)) - { + .OrderBy(static value => value.persistentId) + ) { parts.Add(dependency.persistentId.ToString("D")); - if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) + if (m_recordsByID.TryGetValue(dependency.persistentId, out AssetRecord? record)) + { parts.Add(record.meta.artifactKey); + } } foreach (AssetImportDependencyData dependency in meta.importDependencies - .OrderBy(static value => value.kind) - .ThenBy(static value => value.key, StringComparer.Ordinal)) - { + .OrderBy(static value => value.kind) + .ThenBy(static value => value.key, StringComparer.Ordinal) + ) { parts.Add(dependency.kind.ToString()); parts.Add(dependency.key); parts.Add(dependency.fingerprint); @@ -268,30 +287,26 @@ private string CreateImportFingerprint(AssetMeta meta) return string.Join("\n", parts); } - private static string GetImporterImplementationFingerprint(AssetImporter importer) - => $"{importer.GetType().Assembly.ManifestModule.ModuleVersionId:D}:" + - $"{importer.GetType().FullName}:{importer.deploymentScope}"; - private string CreateBuildFingerprint( AssetBuildProcessor processor, AssetObject definition, IReadOnlyList inputs ) { - var parts = new List - { + List parts = + [ "Inno.AssetBuild", - processor.processorId, + processor.processorID, processor.GetType().Assembly.ManifestModule.ModuleVersionId.ToString("D"), - definition.identity.persistentId.ToString("D"), + definition.identity.persistentID.ToString("D"), definition.GetType().Assembly.ManifestModule.ModuleVersionId.ToString("D"), definition.GetType().FullName ?? definition.GetType().Name, m_runtimeOwner.GetSourceHash(definition), ComputeSha256Hex(CaptureAssetState(definition)), ComputeSha256Hex(definition.runtimePayload.ToArray()) - }; - foreach (AssetInfo input in inputs.OrderBy(static value => value.persistentId)) + ]; + foreach (AssetInfo input in inputs.OrderBy(static value => value.persistentID)) { - parts.Add(input.persistentId.ToString("D")); + parts.Add(input.persistentID.ToString("D")); parts.Add(input.artifactKey.value); } return string.Join("\n", parts); @@ -307,11 +322,102 @@ private string GetSourcePath(string relativePath) private AssetSourceMount GetMount(AssetPath path) => m_mounts.TryGetValue(path.source, out AssetSourceMount? mount) - ? mount - : throw new ArgumentException($"Asset source mount '{path.source}' is not active.", nameof(path)); + ? mount + : throw new ArgumentException($"Asset source mount '{path.source}' is not active.", nameof(path)); private string GetMetaPath(string relativePath) => GetSourcePath(relativePath) + C_META_POSTFIX; + private bool IsInternalGeneratedPath(string relativePath) => AssetSourcePolicy.IsGeneratedPath(relativePath); + + private byte[]? ReadMetadata(string path) + => m_sourceMetadataStage is not null + ? m_sourceMetadataStage.Read(path) + : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; + + private bool IsStagedMetadata(string path) + => m_sourceMetadataStage is not null && path.EndsWith(C_META_POSTFIX, StringComparison.Ordinal); + + private void WriteAtomic( + string targetPath, + byte[] bytes + ) { + if (IsStagedMetadata(targetPath)) + { + m_sourceMetadataStage!.Write(targetPath, bytes); + } + else + { + AtomicFile.WriteAllBytes(targetPath, bytes); + } + } + + private FileSnapshot CaptureFile(string path) + { + byte[]? bytes = IsStagedMetadata(path) ? ReadMetadata(path) : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; + return bytes is null ? new FileSnapshot(false, []) : new FileSnapshot(true, bytes); + } + + private void RestoreFile( + string path, + FileSnapshot snapshot + ) { + if (snapshot.existed) + { + WriteAtomic(path, snapshot.bytes); + return; + } + + DeleteIfExists(path); + } + + private void MoveGeneratedFile( + string sourcePath, + string targetPath + ) { + if (IsStagedMetadata(sourcePath)) + { + byte[]? bytes = ReadMetadata(sourcePath); + if (bytes is null) + { + return; + } + if (ReadMetadata(targetPath) is not null) + { + throw new IOException($"Generated metadata target '{targetPath}' already exists."); + } + m_sourceMetadataStage!.Write(targetPath, bytes); + m_sourceMetadataStage.Write(sourcePath, null); + return; + } + if (!IOFile.Exists(sourcePath)) + { + return; + } + Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!); + if (IOFile.Exists(targetPath)) + { + throw new IOException($"Generated metadata target '{targetPath}' already exists."); + } + IOFile.Move(sourcePath, targetPath); + } + + private void DeleteIfExists(string path) + { + if (IsStagedMetadata(path)) + { + m_sourceMetadataStage!.Write(path, null); + return; + } + if (IOFile.Exists(path)) + { + IOFile.Delete(path); + } + } + + private static string GetImporterImplementationFingerprint(AssetImporter importer) + => $"{importer.GetType().Assembly.ManifestModule.ModuleVersionId:D}:" + + $"{importer.GetType().FullName}:{importer.deploymentScope}"; + private static string ReadStableSourceHash( string sourcePath, out AssetSourceFileStamp sourceStamp @@ -320,12 +426,14 @@ out AssetSourceFileStamp sourceStamp for (int attempt = 0; attempt < C_MAX_ATTEMPTS; attempt++) { if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp before)) + { throw new FileNotFoundException("Asset source is unavailable.", sourcePath); + } using FileStream source = IOFile.OpenRead(sourcePath); string hash = Convert.ToHexString(SHA256.HashData(source)); if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) - && before == after && source.Length == after.length) - { + && before == after && source.Length == after.length + ) { sourceStamp = after; return hash; } @@ -341,12 +449,14 @@ out AssetSourceFileStamp sourceStamp for (int attempt = 0; attempt < C_MAX_ATTEMPTS; attempt++) { if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp before)) + { throw new FileNotFoundException("Asset source is unavailable.", sourcePath); + } byte[] bytes = IOFile.ReadAllBytes(sourcePath); - if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) && - before == after && - bytes.LongLength == after.length) - { + if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) + && before == after + && bytes.LongLength == after.length + ) { sourceStamp = after; return bytes; } @@ -358,21 +468,19 @@ out AssetSourceFileStamp sourceStamp private static bool SourceStampMatches( AssetMeta meta, AssetSourceFileStamp sourceStamp - ) - => sourceStamp.isValid && - meta.sourceLength == sourceStamp.length && - meta.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks && - meta.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; + ) => sourceStamp.isValid + && meta.sourceLength == sourceStamp.length + && meta.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks + && meta.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; private static bool SourceStampMatches( AssetImportDependencyData dependency, AssetSourceFileStamp sourceStamp - ) - => dependency.sourceStampValid && - sourceStamp.isValid && - dependency.sourceLength == sourceStamp.length && - dependency.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks && - dependency.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; + ) => dependency.sourceStampValid + && sourceStamp.isValid + && dependency.sourceLength == sourceStamp.length + && dependency.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks + && dependency.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; private static void ApplySourceStamp( AssetMeta meta, @@ -403,83 +511,11 @@ AssetSourceFileStamp sourceStamp private static string ComputeSha256Hex(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)); - private bool IsInternalGeneratedPath(string relativePath) => AssetSourcePolicy.IsGeneratedPath(relativePath); - - private byte[]? ReadMetadata(string path) - => m_sourceMetadataStage is not null - ? m_sourceMetadataStage.Read(path) - : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; - - private bool IsStagedMetadata(string path) - => m_sourceMetadataStage is not null && path.EndsWith(C_META_POSTFIX, StringComparison.Ordinal); - - private void WriteAtomic( - string targetPath, - byte[] bytes - ) { - if (IsStagedMetadata(targetPath)) - m_sourceMetadataStage!.Write(targetPath, bytes); - else - AtomicFile.WriteAllBytes(targetPath, bytes); - } - - private FileSnapshot CaptureFile(string path) + private static AssetDependencyData ToData(AssetDependency dependency) + => new() { - byte[]? bytes = IsStagedMetadata(path) ? ReadMetadata(path) : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; - return bytes is null ? new FileSnapshot(false, []) : new FileSnapshot(true, bytes); - } - - private void RestoreFile( - string path, - FileSnapshot snapshot - ) { - if (snapshot.existed) - { - WriteAtomic(path, snapshot.bytes); - return; - } - - DeleteIfExists(path); - } - - private void MoveGeneratedFile( - string sourcePath, - string targetPath - ) { - if (IsStagedMetadata(sourcePath)) - { - byte[]? bytes = ReadMetadata(sourcePath); - if (bytes is null) - return; - if (ReadMetadata(targetPath) is not null) - throw new IOException($"Generated metadata target '{targetPath}' already exists."); - m_sourceMetadataStage!.Write(targetPath, bytes); - m_sourceMetadataStage.Write(sourcePath, null); - return; - } - if (!IOFile.Exists(sourcePath)) - return; - Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!); - if (IOFile.Exists(targetPath)) - throw new IOException($"Generated metadata target '{targetPath}' already exists."); - IOFile.Move(sourcePath, targetPath); - } - - private void DeleteIfExists(string path) - { - if (IsStagedMetadata(path)) - { - m_sourceMetadataStage!.Write(path, null); - return; - } - if (IOFile.Exists(path)) - IOFile.Delete(path); - } - - private static AssetDependencyData ToData(AssetDependency dependency) => new() - { - persistentId = dependency.persistentId, - stableTypeId = dependency.type.stableId, + persistentId = dependency.persistentID, + stableTypeId = dependency.type.stableID, lastKnownPath = dependency.lastKnownPath }; @@ -487,5 +523,4 @@ private readonly record struct FileSnapshot( bool existed, byte[] bytes ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs index 5b385cbc4..1bf825c15 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -34,28 +33,31 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, private const string C_REJECTED_SOURCE_REFERENCE = "REJECTED_SOURCE_REFERENCE:"; [ThreadStatic] - private static AssetLoader? t_activeLoader; + private static AssetLoader? s_activeLoader; private readonly AssetRuntimeOwner m_runtimeOwner; private readonly ArtifactRetention m_artifactRetention = new(); private readonly SemaphoreSlim m_operationGate = new(1, 1); private readonly object m_asyncSync = new(); - private readonly Dictionary> m_inFlightPathLoads = - new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary> m_inFlightIdLoads = []; + + private readonly Dictionary> m_inFlightPathLoads = new(StringComparer.OrdinalIgnoreCase); + + private readonly Dictionary> m_inFlightIDLoads = []; private readonly AssetImporterRegistry m_importers; private readonly AssetBuildProcessorRegistry m_buildProcessors; private readonly Dictionary m_recordsByPath = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary m_recordsById = []; + private readonly Dictionary m_recordsByID = []; private readonly Dictionary> m_missingAssets = []; private readonly Dictionary m_preservedMissingStates = []; private readonly DependencyGraph m_runtimeGraph = new(); private readonly DependencyGraph m_importGraph = new(StringComparer.OrdinalIgnoreCase); private readonly ConditionalWeakTable m_dependencyRetention = new(); private readonly HashSet m_activeImports = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary m_pendingImportIds = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_pendingImportIDs = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_unavailableImports = new(StringComparer.OrdinalIgnoreCase); + private readonly AssetArtifactStore m_artifacts; private readonly AssetCatalogStore m_catalog; private readonly AssetDiagnosticPublisher m_diagnostics; @@ -67,7 +69,7 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, private readonly SerializationContext m_serializationContext; private readonly AssetSourcePolicy m_sourcePolicy; private readonly TypeCatalog m_types; - private readonly IReadOnlyDictionary m_mounts; + private readonly IReadOnlyDictionary m_mounts; private readonly bool m_runtimeArtifactsOnly; private CancellationToken m_importCancellation; @@ -83,38 +85,6 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, private long m_importerRegistryVersion = -1; private long m_buildProcessorRegistryVersion = -1; - /// - /// Restores serialized properties to the existing asset object. - /// - /// - /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// Serialized asset object type receiving restored properties. - /// - public void RestoreProperties( - Guid stableTypeId, - byte[] propertyData, - TValue target - ) where TValue : class, ISerializable - { - ObjectDisposedException.ThrowIf(m_disposed || m_disposeRequested, this); - ArgumentNullException.ThrowIfNull(target); - if (m_types.GetTypeRef(target.GetType()).stableId != stableTypeId) - throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); - m_serialization.Decode(propertyData, reader => - { - reader.RestoreProperties(target); - return true; - }, m_serializationContext); - } - /// /// Creates an asset loader for one source and Library root pair. /// @@ -127,12 +97,12 @@ TValue target /// /// The identity allocator that owns every canonical asset loaded by this instance. /// - /// - /// The explicitly owned router receiving importer and catalog diagnostics. - /// /// /// The diagnostic hub that owns import, build, catalog, and reference reports. /// + /// + /// The explicitly owned router receiving importer and catalog diagnostics. + /// /// /// The absolute source root. /// @@ -151,18 +121,16 @@ public AssetLoader( string assetRoot, string libraryRoot, AssetSourcePolicy? sourcePolicy = null - ) - : this( - types, - serialization, - identities, - diagnostics, - logs, - [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], - libraryRoot, - sourcePolicy) - { - } + ) : this( + types, + serialization, + identities, + diagnostics, + logs, + [new AssetSourceMount(AssetSourceID.project, assetRoot, isReadOnly: false)], + libraryRoot, + sourcePolicy + ) {} /// /// Creates an asset loader over one project source and zero or more isolated sources. @@ -176,12 +144,12 @@ [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], /// /// The identity allocator that owns every canonical asset loaded by this instance. /// - /// - /// The explicitly owned router receiving importer and catalog diagnostics. - /// /// /// The diagnostic hub that owns import, build, catalog, and reference reports. /// + /// + /// The explicitly owned router receiving importer and catalog diagnostics. + /// /// /// Complete isolated source mount snapshot. /// @@ -204,20 +172,18 @@ public AssetLoader( string libraryRoot, AssetSourcePolicy? sourcePolicy = null, bool runtimeArtifactsOnly = false - ) - : this( - types, - serialization, - identities, - diagnostics, - logs, - mounts, - libraryRoot, - libraryRoot, - sourcePolicy, - runtimeArtifactsOnly) - { - } + ) : this( + types, + serialization, + identities, + diagnostics, + logs, + mounts, + libraryRoot, + libraryRoot, + sourcePolicy, + runtimeArtifactsOnly + ) {} internal AssetLoader( TypeCatalog types, @@ -239,22 +205,31 @@ internal AssetLoader( ArgumentNullException.ThrowIfNull(logs); ArgumentNullException.ThrowIfNull(mounts); if (mounts.Count == 0) + { throw new ArgumentException("At least one asset source mount is required.", nameof(mounts)); + } if (string.IsNullOrWhiteSpace(libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(libraryRoot)); + } if (string.IsNullOrWhiteSpace(catalogLibraryRoot)) + { throw new ArgumentException("Catalog Library root is required.", nameof(catalogLibraryRoot)); - Dictionary byId = mounts.ToDictionary(static mount => mount.id); - if (byId.Count != mounts.Count) - throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); - if (!byId.TryGetValue(AssetSourceId.project, out AssetSourceMount? project) - || project.isReadOnly && !runtimeArtifactsOnly) + } + Dictionary byID = mounts.ToDictionary(static mount => mount.id); + if (byID.Count != mounts.Count) { + throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } + if (!byID.TryGetValue(AssetSourceID.project, out AssetSourceMount? project) + || project.isReadOnly && !runtimeArtifactsOnly + ) { throw new ArgumentException( runtimeArtifactsOnly - ? "A project asset source mount is required." - : "A writable project asset source mount is required.", - nameof(mounts)); + ? "A project asset source mount is required." + : "A writable project asset source mount is required.", + nameof(mounts) + ); } m_types = types; @@ -267,16 +242,15 @@ internal AssetLoader( m_log = logs.CreateLogger(); m_importers = new AssetImporterRegistry(types); m_buildProcessors = new AssetBuildProcessorRegistry(types); - m_mounts = byId; + m_mounts = byID; m_runtimeArtifactsOnly = runtimeArtifactsOnly; - assetRoot = project.rootPath; + this.assetRoot = project.rootPath; this.libraryRoot = Path.GetFullPath(libraryRoot); foreach (AssetSourceMount mount in mounts) { if (mount.isReadOnly && !Directory.Exists(mount.rootPath)) { - throw new DirectoryNotFoundException( - $"Read-only asset source root '{mount.rootPath}' does not exist."); + throw new DirectoryNotFoundException($"Read-only asset source root '{mount.rootPath}' does not exist."); } Directory.CreateDirectory(mount.rootPath); @@ -305,35 +279,46 @@ internal AssetLoader( /// /// Occurs after a loaded canonical asset is updated in place. /// - public event Action? AssetReloaded; + public event Action? assetReloaded; - internal void DeferUnavailableExtensions() => Execute(() => + /// + /// Restores serialized properties to the existing asset object. + /// + /// + /// Serialized asset object type receiving restored properties. + /// + /// + /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The existing target that receives the validated result. + /// + public void RestoreProperties( + Guid stableTypeID, + byte[] propertyData, + TValue target + ) where TValue : class, ISerializable { - m_deferUnavailableExtensions = true; - }); - - internal void CompleteExtensionDiscovery() - => Execute(() => + ObjectDisposedException.ThrowIf(m_disposed || m_disposeRequested, this); + ArgumentNullException.ThrowIfNull(target); + if (m_types.GetTypeRef(target.GetType()).stableID != stableTypeID) { - if (!m_deferUnavailableExtensions) - return; - m_deferUnavailableExtensions = false; - m_unavailableImports.Clear(); - RescanLocked(); - }); - - internal void ActivateExtensionDiscovery() - { - // Assembly discovery may publish built-in catalogs before the initial script compilation. - // Only the composition host can close that initial discovery boundary. - if (!m_preserveInitialExtensionDiscovery) - CompleteExtensionDiscovery(); + throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } + m_serialization.Decode(propertyData, reader => + { + reader.RestoreProperties(target); + return true; + }, m_serializationContext); } /// /// Waits for pending import and build work. /// - public void WaitForIdle() => Execute(static () => { }); + public void WaitForIdle() => Execute(static () => {}); /// /// Refreshes extension registries and reimports affected sources when their snapshot changed. @@ -342,31 +327,61 @@ internal void ActivateExtensionDiscovery() /// when the importer registry changed. /// public bool RefreshRegistries() - { - return Execute(() => + => Execute(() => { long version = m_importers.snapshotVersion; long buildVersion = m_buildProcessors.snapshotVersion; - if (version == m_importerRegistryVersion && - buildVersion == m_buildProcessorRegistryVersion) + if (version == m_importerRegistryVersion + && buildVersion == m_buildProcessorRegistryVersion + ) { return false; + } RescanLocked(); return true; }); + + internal void DeferUnavailableExtensions() + => Execute(() => + { + m_deferUnavailableExtensions = true; + }); + + internal void CompleteExtensionDiscovery() + => Execute(() => + { + if (!m_deferUnavailableExtensions) + { + return; + } + m_deferUnavailableExtensions = false; + m_unavailableImports.Clear(); + RescanLocked(); + }); + + internal void ActivateExtensionDiscovery() + { + // Assembly discovery may publish built-in catalogs before the initial script compilation. + // Only the composition host can close that initial discovery boundary. + if (!m_preserveInitialExtensionDiscovery) + { + CompleteExtensionDiscovery(); + } } private void PublishReloaded(AssetObject asset) { - Action? handlers = AssetReloaded; + Action? handlers = assetReloaded; if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try { ((Action)handler)(asset); } - catch + catch (Exception) { // Observer failures cannot roll back an already committed asset transaction. } @@ -375,11 +390,11 @@ private void PublishReloaded(AssetObject asset) private static AssetDependency FindDescriptor( AssetMeta meta, - Guid persistentId + Guid persistentID ) { - AssetDependencyData data = meta.runtimeDependencies.FirstOrDefault(value => value.persistentId == persistentId); + AssetDependencyData data = meta.runtimeDependencies.FirstOrDefault(value => value.persistentId == persistentID); return data.persistentId == Guid.Empty - ? default - : new AssetDependency(data.persistentId, new TypeRef(data.stableTypeId), data.lastKnownPath); + ? default + : new AssetDependency(data.persistentId, new TypeRef(data.stableTypeId), data.lastKnownPath); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs index cb4c4ecf8..34ca1004c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -16,26 +15,16 @@ public sealed class AssetSerializationServices private readonly SerializationRegistry m_serialization; private readonly TypeCatalog m_types; - internal IAssetReferenceResolver references - => m_references - ?? throw new InvalidOperationException( - "Asset reference resolution is unavailable outside an import transaction."); - - internal SerializationRegistry serialization => m_serialization; - - internal TypeCatalog types => m_types; - - internal SerializationContext context => m_references is null - ? SerializationContext.empty : AssetSerializationContext.Create(m_references); - internal AssetSerializationServices( TypeCatalog types, SerializationRegistry serialization, IAssetReferenceResolver? references, Action? dependencySink ) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + m_types = types; + m_serialization = serialization; m_references = references; m_dependencySink = dependencySink; } @@ -52,7 +41,7 @@ internal AssetSerializationServices( /// /// Thrown when has no stable type registration. /// - public Guid GetStableTypeId() => m_types.GetTypeRef(typeof(TValue)).stableId; + public Guid GetStableTypeID() => m_types.GetTypeRef(typeof(TValue)).stableID; /// /// Captures typed properties and their references as one neutral, owner-independent value. @@ -66,16 +55,21 @@ internal AssetSerializationServices( /// /// Frozen native properties with exact stable type identity and collected direct dependencies. /// - public AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable + public AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable { ArgumentNullException.ThrowIfNull(value); using IDisposable operation = m_types.AcquireOperation("Capture asset properties"); var dependencies = new AssetDependencyCollection(); byte[] data = m_serialization.Encode(writer => writer.WriteProperties(value), context.With(dependencies)); if (m_dependencySink is not null) + { foreach (AssetDependency dependency in dependencies.dependencies) + { m_dependencySink(dependency); - return new(m_types.GetTypeRef(value.GetType()).stableId, data, dependencies.dependencies); + } + } + return new(m_types.GetTypeRef(value.GetType()).stableID, data, dependencies.dependencies); } /// @@ -103,7 +97,9 @@ public byte[] Serialize(TValue value) if (m_dependencySink is not null) { foreach (AssetDependency dependency in dependencies.dependencies) + { m_dependencySink(dependency); + } } return result; } @@ -127,8 +123,23 @@ public TValue Deserialize(ReadOnlySpan bytes) where TValue : class, ISerializable { SerializationContext context = m_references is null - ? SerializationContext.empty - : AssetSerializationContext.Create(m_references); + ? SerializationContext.empty + : AssetSerializationContext.Create(m_references); return m_serialization.Deserialize(bytes, context); } + + internal IAssetReferenceResolver references + => m_references + ?? throw new InvalidOperationException( + "Asset reference resolution is unavailable outside an import transaction." + ); + + internal SerializationRegistry serialization => m_serialization; + + internal TypeCatalog types => m_types; + + internal SerializationContext context + => m_references is null + ? SerializationContext.empty + : AssetSerializationContext.Create(m_references); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs index 7e83c7221..dca763156 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using Inno.Core.IO; + using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; @@ -24,15 +25,19 @@ internal void Commit(Action publishCatalog) foreach (Entry entry in snapshot) { if (!Equal(entry.original, ReadPhysical(entry.path))) + { throw new IOException($"Asset source metadata '{entry.path}' changed while its candidate was being prepared."); + } } - var applied = new List(); + List applied = []; try { foreach (Entry entry in snapshot) { if (Equal(entry.original, entry.value)) + { continue; + } applied.Add(entry); WritePhysical(entry.path, entry.value); } @@ -41,7 +46,7 @@ internal void Commit(Action publishCatalog) } catch (Exception failure) { - var failures = new List { failure }; + List failures = [failure]; for (int index = applied.Count - 1; index >= 0; index--) { try @@ -54,7 +59,9 @@ internal void Commit(Action publishCatalog) } } if (failures.Count > 1) + { throw new AggregateException("Asset catalog publication and source metadata compensation failed.", failures); + } throw; } } @@ -73,8 +80,7 @@ private Entry GetEntry(string path) private static bool Equal( byte[]? left, byte[]? right - ) - => left is null ? right is null : right is not null && left.AsSpan().SequenceEqual(right); + ) => left is null ? right is null : right is not null && left.AsSpan().SequenceEqual(right); private static byte[]? ReadPhysical(string path) => IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; @@ -83,9 +89,13 @@ private static void WritePhysical( byte[]? value ) { if (value is not null) + { AtomicFile.WriteAllBytes(path, value); + } else if (IOFile.Exists(path)) + { IOFile.Delete(path); + } } private sealed class Entry( diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs index 5f06fa501..fdddf6c90 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -11,7 +10,8 @@ namespace Inno.Assets.Pipeline; /// /// The build definition asset type. /// -public sealed class AssetBuildContext where TDefinition : AssetObject +public sealed class AssetBuildContext + where TDefinition : AssetObject { /// /// Creates a build context. @@ -26,8 +26,10 @@ public AssetBuildContext( TDefinition definition, IReadOnlyList inputs ) { - this.definition = definition ?? throw new ArgumentNullException(nameof(definition)); - this.inputs = inputs ?? throw new ArgumentNullException(nameof(inputs)); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(inputs); + this.definition = definition; + this.inputs = inputs; } /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs index 9fffd0928..037fc48e0 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs @@ -3,47 +3,23 @@ using System.Threading; using System.Threading.Tasks; -using Inno.Assets; - namespace Inno.Assets.Pipeline; -/// -/// Declares the immutable cache protocol identity of an automatically discovered asset build processor. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetBuildProcessorAttribute : Attribute -{ - /// - /// Creates build-processor discovery metadata. - /// - /// - /// Globally stable build processor identifier. - /// - public AssetBuildProcessorAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id.Trim(); - } - - /// - /// Gets the globally stable build processor identifier. - /// - public string id { get; } -} - /// /// Defines an automatically discovered aggregate asset build processor. /// public abstract class AssetBuildProcessor { - private string? m_processorId; + private string? m_processorID; /// /// Gets the stable processor identifier used by build cache keys. /// - public string processorId => m_processorId - ?? throw new InvalidOperationException( - $"Asset build processor '{GetType().FullName}' has not been bound to discovery metadata."); + public string processorID + => m_processorID + ?? throw new InvalidOperationException( + $"Asset build processor '{GetType().FullName}' has not been bound to discovery metadata." + ); /// /// Gets the definition type accepted by this processor. @@ -57,15 +33,16 @@ internal abstract ValueTask BuildInternalAsync( CancellationToken cancellationToken ); - internal void BindProcessorId(string id) + internal void BindProcessorID(string id) { ArgumentException.ThrowIfNullOrWhiteSpace(id); - if (m_processorId is not null && !string.Equals(m_processorId, id, StringComparison.Ordinal)) + if (m_processorID is not null && !string.Equals(m_processorID, id, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Asset build processor '{GetType().FullName}' cannot be bound to more than one protocol ID."); + $"Asset build processor '{GetType().FullName}' cannot be bound to more than one protocol ID." + ); } - m_processorId = id; + m_processorID = id; } } @@ -114,7 +91,8 @@ CancellationToken cancellationToken { throw new ArgumentException( $"Build definition must be assignable to '{typeof(TDefinition).FullName}'.", - nameof(definition)); + nameof(definition) + ); } return BuildAsync(new AssetBuildContext(typed, inputs), output, cancellationToken); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs new file mode 100644 index 000000000..26f900ea9 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Declares the immutable cache protocol identity of an automatically discovered asset build processor. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetBuildProcessorAttribute : Attribute +{ + /// + /// Creates build-processor discovery metadata. + /// + /// + /// Globally stable build processor identifier. + /// + public AssetBuildProcessorAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id.Trim(); + } + + /// + /// Gets the globally stable build processor identifier. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs index 96332757e..f459fa586 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs @@ -3,13 +3,11 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline; -internal sealed class AssetBuildProcessorRegistry - : TypeRegistry +internal sealed class AssetBuildProcessorRegistry : TypeRegistry { private readonly TypeCatalog m_types; @@ -19,8 +17,6 @@ internal AssetBuildProcessorRegistry(TypeCatalog types) m_types = types; } - internal AssetBuildProcessor? Find(Type definitionType) => current.byDefinitionType.GetValueOrDefault(definitionType); - internal long snapshotVersion { get @@ -50,25 +46,29 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(AssetBuildProcessor).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Asset build processor metadata on '{type.FullName}' requires a concrete {nameof(AssetBuildProcessor)} subtype."); + $"Asset build processor metadata on '{type.FullName}' requires a concrete {nameof(AssetBuildProcessor)} subtype." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }).ToArray(); - string? duplicateId = registrations + string? duplicateID = registrations .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; - if (duplicateId is not null) - throw new InvalidOperationException($"Asset build processor ID '{duplicateId}' is registered more than once."); + if (duplicateID is not null) + { + throw new InvalidOperationException($"Asset build processor ID '{duplicateID}' is registered more than once."); + } var processors = new Dictionary(); - foreach ((Type type, string processorId) in registrations) + foreach ((Type type, string processorID) in registrations) { AssetBuildProcessor processor = CreateExtension(type); - processor.BindProcessorId(processorId); + processor.BindProcessorID(processorID); if (!processors.TryAdd(processor.definitionType, processor)) { throw new InvalidOperationException( - $"Asset build definition '{processor.definitionType.FullName}' has multiple processors."); + $"Asset build definition '{processor.definitionType.FullName}' has multiple processors." + ); } } return new Snapshot(processors.ToFrozenDictionary()); @@ -82,5 +82,7 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.byDefinitionType.Values); + internal AssetBuildProcessor? Find(Type definitionType) => current.byDefinitionType.GetValueOrDefault(definitionType); + internal sealed record Snapshot(FrozenDictionary byDefinitionType); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs index fa2b92f7f..ee0698dcb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs @@ -4,6 +4,9 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetCatalogSnapshot : ISerializable { - [SerializableProperty] internal long revision { get; set; } - [SerializableProperty] internal byte[][] entries { get; set; } = []; + [SerializableProperty] + internal long revision { get; set; } + + [SerializableProperty] + internal byte[][] entries { get; set; } = []; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs index 0b54eec6e..8769e0023 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -46,17 +45,22 @@ internal AssetMeta[] Load() { string path = IOFile.Exists(m_journalPath) ? m_journalPath : m_snapshotPath; if (!IOFile.Exists(path)) + { return []; + } try { AssetCatalogSnapshot snapshot = Deserialize(IOFile.ReadAllBytes(path)); m_revision = snapshot.revision; if (string.Equals(path, m_journalPath, StringComparison.Ordinal)) + { Commit(DeserializeEntries(snapshot.entries)); + } return DeserializeEntries(snapshot.entries); } - catch + catch (Exception) { + // An unreadable catalog is treated as empty. return []; } } @@ -72,7 +76,9 @@ internal void Commit(AssetMeta[] entries) AtomicFile.WriteAllBytes(m_journalPath, bytes); AtomicFile.WriteAllBytes(m_snapshotPath, bytes); if (IOFile.Exists(m_journalPath)) + { IOFile.Delete(m_journalPath); + } } internal void CopyLatestTo(string destinationLibraryRoot) @@ -80,12 +86,12 @@ internal void CopyLatestTo(string destinationLibraryRoot) ArgumentException.ThrowIfNullOrWhiteSpace(destinationLibraryRoot); string? sourcePath = LatestPathOrNull(); if (sourcePath is null) + { return; + } string destinationRoot = GetDatabaseRoot(destinationLibraryRoot); Directory.CreateDirectory(destinationRoot); - AtomicFile.WriteAllBytes( - Path.Combine(destinationRoot, "Catalog.snapshot"), - IOFile.ReadAllBytes(sourcePath)); + AtomicFile.WriteAllBytes(Path.Combine(destinationRoot, "Catalog.snapshot"), IOFile.ReadAllBytes(sourcePath)); } internal void PromoteTo(string destinationLibraryRoot) @@ -102,9 +108,13 @@ internal void PromoteTo(string destinationLibraryRoot) try { if (candidate is null) + { IOFile.Delete(destinationSnapshot); + } else + { AtomicFile.WriteAllBytes(destinationSnapshot, candidate); + } snapshotChanged = true; IOFile.Delete(destinationJournal); } @@ -115,9 +125,13 @@ internal void PromoteTo(string destinationLibraryRoot) try { if (previous is null) + { IOFile.Delete(destinationSnapshot); + } else + { AtomicFile.WriteAllBytes(destinationSnapshot, previous); + } } catch (Exception rollback) { @@ -145,17 +159,19 @@ private void Bind(string libraryRoot) private string? LatestPathOrNull() { if (IOFile.Exists(m_journalPath)) + { return m_journalPath; + } return IOFile.Exists(m_snapshotPath) ? m_snapshotPath : null; } - private static string GetDatabaseRoot(string libraryRoot) => Path.Combine(Path.GetFullPath(libraryRoot), "AssetDatabase"); - private byte[][] SerializeEntries(AssetMeta[] entries) { var result = new byte[entries.Length][]; for (int i = 0; i < entries.Length; i++) + { result[i] = Serialize(entries[i]); + } return result; } @@ -163,19 +179,23 @@ private AssetMeta[] DeserializeEntries(byte[][] entries) { var result = new AssetMeta[entries.Length]; for (int i = 0; i < entries.Length; i++) + { result[i] = Deserialize(entries[i]); + } return result; } private byte[] Serialize(T value) where T : class, ISerializable - => m_serializationGeneration is null - ? m_serialization!.Serialize(value) - : m_serializationGeneration.Serialize(value); + => m_serializationGeneration is null + ? m_serialization!.Serialize(value) + : m_serializationGeneration.Serialize(value); private T Deserialize(ReadOnlySpan bytes) where T : class, ISerializable - => m_serializationGeneration is null - ? m_serialization!.Deserialize(bytes) - : m_serializationGeneration.Deserialize(bytes); + => m_serializationGeneration is null + ? m_serialization!.Deserialize(bytes) + : m_serializationGeneration.Deserialize(bytes); + + private static string GetDatabaseRoot(string libraryRoot) => Path.Combine(Path.GetFullPath(libraryRoot), "AssetDatabase"); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs index d5a030391..492057051 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs @@ -13,44 +13,7 @@ long creationTimeUtcTicks this.length = length; this.lastWriteUtcTicks = lastWriteUtcTicks; this.creationTimeUtcTicks = creationTimeUtcTicks; - isValid = true; - } - - internal bool isValid { get; } - internal long length { get; } - internal long lastWriteUtcTicks { get; } - internal long creationTimeUtcTicks { get; } - - internal static bool TryCapture( - string path, - out AssetSourceFileStamp stamp - ) { - try - { - var info = new FileInfo(path); - info.Refresh(); - if (!info.Exists) - { - stamp = default; - return false; - } - - stamp = new AssetSourceFileStamp( - info.Length, - info.LastWriteTimeUtc.Ticks, - info.CreationTimeUtc.Ticks); - return true; - } - catch (IOException) - { - stamp = default; - return false; - } - catch (UnauthorizedAccessException) - { - stamp = default; - return false; - } + this.isValid = true; } /// @@ -63,10 +26,10 @@ out AssetSourceFileStamp stamp /// when the requested condition is satisfied; otherwise, . /// public bool Equals(AssetSourceFileStamp other) - => isValid == other.isValid && - length == other.length && - lastWriteUtcTicks == other.lastWriteUtcTicks && - creationTimeUtcTicks == other.creationTimeUtcTicks; + => isValid == other.isValid + && length == other.length + && lastWriteUtcTicks == other.lastWriteUtcTicks + && creationTimeUtcTicks == other.creationTimeUtcTicks; /// /// Determines whether this value and the supplied value represent the same logical state. @@ -120,4 +83,38 @@ AssetSourceFileStamp right AssetSourceFileStamp left, AssetSourceFileStamp right ) => !left.Equals(right); + + internal bool isValid { get; } + internal long length { get; } + internal long lastWriteUtcTicks { get; } + internal long creationTimeUtcTicks { get; } + + internal static bool TryCapture( + string path, + out AssetSourceFileStamp stamp + ) { + try + { + var info = new FileInfo(path); + info.Refresh(); + if (!info.Exists) + { + stamp = default; + return false; + } + + stamp = new AssetSourceFileStamp(info.Length, info.LastWriteTimeUtc.Ticks, info.CreationTimeUtc.Ticks); + return true; + } + catch (IOException) + { + stamp = default; + return false; + } + catch (UnauthorizedAccessException) + { + stamp = default; + return false; + } + } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs index 02c1c7f2f..16f35bb0b 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; @@ -7,8 +6,15 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetSourceMeta : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal int sourceKind { get; set; } = (int)AssetSourceKind.File; - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal byte[] importerSettingsBytes { get; set; } = []; + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal int sourceKind { get; set; } = (int)AssetSourceKind.File; + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal byte[] importerSettingsBytes { get; set; } = []; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs index 8844dc72e..0a3c1505b 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; - using Inno.Assets; using Inno.Core.Diagnostics; @@ -30,39 +29,56 @@ internal AssetDiagnosticPublisher(DiagnosticHub diagnostics) m_diagnostics = diagnostics; } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + SetActive(false); + m_reports.Clear(); + m_catalogState = string.Empty; + m_importStates.Clear(); + m_buildStates.Clear(); + m_referenceStates.Clear(); + } + internal void SynchronizeImports(IReadOnlyList entries) { ArgumentNullException.ThrowIfNull(entries); - var currentIds = new HashSet(); + var currentIDs = new HashSet(); for (int i = 0; i < entries.Count; i++) { AssetMeta entry = entries[i]; if (entry.persistentId == Guid.Empty || entry.isDirectory) + { continue; + } if (entry.importStatus != (int)AssetImportStatus.Missing) + { ResolveReference(entry.persistentId); + } Diagnostic[] diagnostics = CreateImportDiagnostics(entry); if (diagnostics.Length == 0) + { continue; + } - currentIds.Add(entry.persistentId); + currentIDs.Add(entry.persistentId); string state = CreateState(entry, diagnostics); - if (m_importStates.TryGetValue(entry.persistentId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_importStates.TryGetValue(entry.persistentId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { continue; } - Set( - CreateSource(C_IMPORT_GROUP, entry.persistentId, entry.relativePath), - diagnostics); + Set(CreateSource(C_IMPORT_GROUP, entry.persistentId, entry.relativePath), diagnostics); m_importStates[entry.persistentId] = state; } Guid[] resolved = m_importStates.Keys - .Where(id => !currentIds.Contains(id)) + .Where(id => !currentIDs.Contains(id)) .ToArray(); for (int i = 0; i < resolved.Length; i++) { @@ -72,16 +88,18 @@ internal void SynchronizeImports(IReadOnlyList entries) } internal void PublishBuild( - Guid targetId, + Guid targetID, string displayName, IReadOnlyList messages ) { ArgumentNullException.ThrowIfNull(messages); - if (targetId == Guid.Empty) + if (targetID == Guid.Empty) + { return; + } if (messages.Count == 0) { - ResolveBuild(targetId); + ResolveBuild(targetID); return; } @@ -91,38 +109,38 @@ IReadOnlyList messages .ToArray(); if (diagnostics.Length == 0) { - ResolveBuild(targetId); + ResolveBuild(targetID); return; } string state = string.Join('\n', diagnostics.Select(static diagnostic => diagnostic.message)); - if (m_buildStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_buildStates.TryGetValue(targetID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } - Set(CreateSource(C_BUILD_GROUP, targetId, displayName), diagnostics); - m_buildStates[targetId] = state; + Set(CreateSource(C_BUILD_GROUP, targetID, displayName), diagnostics); + m_buildStates[targetID] = state; } internal void PublishBuildFailure( - Guid targetId, + Guid targetID, string displayName, Exception exception ) { ArgumentNullException.ThrowIfNull(exception); - if (targetId == Guid.Empty) + if (targetID == Guid.Empty) + { return; + } string state = exception.ToString(); - if (m_buildStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_buildStates.TryGetValue(targetID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } - Set( - CreateSource(C_BUILD_GROUP, targetId, displayName), - [Diagnostic.Error("ASSET-BUILD", exception.Message)]); - m_buildStates[targetId] = state; + Set(CreateSource(C_BUILD_GROUP, targetID, displayName), [Diagnostic.Error("ASSET-BUILD", exception.Message)]); + m_buildStates[targetID] = state; } internal bool PublishCatalogFailure(Exception exception) @@ -130,74 +148,73 @@ internal bool PublishCatalogFailure(Exception exception) ArgumentNullException.ThrowIfNull(exception); string state = exception.ToString(); if (string.Equals(m_catalogState, state, StringComparison.Ordinal)) + { return false; - Set( - CreateSource(C_CATALOG_GROUP), - [Diagnostic.Error("ASSET-CATALOG", exception.Message)]); + } + Set(CreateSource(C_CATALOG_GROUP), [Diagnostic.Error("ASSET-CATALOG", exception.Message)]); m_catalogState = state; return true; } internal void PublishMissingReference( - Guid targetId, + Guid targetID, string displayName, Type expectedType ) { - if (targetId == Guid.Empty) + if (targetID == Guid.Empty) + { return; + } ArgumentNullException.ThrowIfNull(expectedType); string resolvedDisplayName = string.IsNullOrWhiteSpace(displayName) - ? targetId.ToString() - : displayName; + ? targetID.ToString() + : displayName; string state = $"{resolvedDisplayName}:{expectedType.FullName}"; - if (m_referenceStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_referenceStates.TryGetValue(targetID, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } Set( - CreateSource(C_REFERENCE_GROUP, targetId, resolvedDisplayName), + CreateSource(C_REFERENCE_GROUP, targetID, resolvedDisplayName), [Diagnostic.Warning( "ASSET-REFERENCE", - $"Asset '{resolvedDisplayName}' required as '{expectedType.FullName}' is missing.")]); - m_referenceStates[targetId] = state; + $"Asset '{resolvedDisplayName}' required as '{expectedType.FullName}' is missing." + )] + ); + m_referenceStates[targetID] = state; } internal void ResolveCatalog() { if (string.IsNullOrEmpty(m_catalogState)) + { return; + } Clear(CreateSource(C_CATALOG_GROUP)); m_catalogState = string.Empty; } - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - SetActive(false); - m_reports.Clear(); - m_catalogState = string.Empty; - m_importStates.Clear(); - m_buildStates.Clear(); - m_referenceStates.Clear(); - } - internal void SetActive(bool active) { if (m_active == active) + { return; + } m_active = active; if (active) { foreach (Report report in m_reports.Values) + { Publish(report); + } } else { foreach (DiagnosticReporter reporter in m_reporters.Values) + { reporter.Dispose(); + } m_reporters.Clear(); } } @@ -207,77 +224,89 @@ private void Set( IReadOnlyList diagnostics ) { if (m_reporters.Remove(source.id, out DiagnosticReporter? previous)) + { previous.Dispose(); + } var report = new Report(source, diagnostics.ToArray()); m_reports[source.id] = report; if (m_active) + { Publish(report); + } } private void Clear(DiagnosticSource source) { m_reports.Remove(source.id); if (m_reporters.Remove(source.id, out DiagnosticReporter? reporter)) + { reporter.Dispose(); + } } private void Publish(Report report) { DiagnosticReporter reporter = m_diagnostics.CreateReporter(report.source); m_reporters.Add(report.source.id, reporter); - reporter.Replace(report.diagnostics.Select(static ( - issue, - index - ) => new Diagnostic( - issue.code, issue.message, issue.severity, index.ToString(CultureInfo.InvariantCulture), - issue.objectId, issue.location))); + reporter.Replace( + report.diagnostics.Select(static ( + issue, + index + ) => new Diagnostic( + issue.code, + issue.message, + issue.severity, + index.ToString(CultureInfo.InvariantCulture), + issue.objectID, + issue.location + )) + ); } - private sealed record Report( - DiagnosticSource source, - Diagnostic[] diagnostics - ); - - private void ResolveBuild(Guid targetId) + private void ResolveBuild(Guid targetID) { - if (!m_buildStates.Remove(targetId)) + if (!m_buildStates.Remove(targetID)) + { return; - Clear(CreateSource(C_BUILD_GROUP, targetId)); + } + Clear(CreateSource(C_BUILD_GROUP, targetID)); } - private void ResolveReference(Guid targetId) + private void ResolveReference(Guid targetID) { - if (!m_referenceStates.Remove(targetId)) + if (!m_referenceStates.Remove(targetID)) + { return; - Clear(CreateSource(C_REFERENCE_GROUP, targetId)); + } + Clear(CreateSource(C_REFERENCE_GROUP, targetID)); } private static DiagnosticSource CreateSource( string group, - Guid? targetId = null, + Guid? targetID = null, string? displayName = null ) { - string id = targetId.HasValue - ? $"inno.assets.pipeline/{group}/{targetId.Value:N}" - : $"inno.assets.pipeline/{group}"; - return new DiagnosticSource( - id, - string.IsNullOrWhiteSpace(displayName) ? group : displayName); + string id = targetID.HasValue + ? $"inno.assets.pipeline/{group}/{targetID.Value:N}" + : $"inno.assets.pipeline/{group}"; + return new DiagnosticSource(id, string.IsNullOrWhiteSpace(displayName) ? group : displayName); } private static Diagnostic[] CreateImportDiagnostics(AssetMeta entry) { AssetImportStatus status = Enum.IsDefined(typeof(AssetImportStatus), entry.importStatus) - ? (AssetImportStatus)entry.importStatus - : AssetImportStatus.Failed; + ? (AssetImportStatus)entry.importStatus + : AssetImportStatus.Failed; DiagnosticLocation? location = string.IsNullOrWhiteSpace(entry.relativePath) - ? null - : new DiagnosticLocation(entry.relativePath); + ? null + : new DiagnosticLocation(entry.relativePath); string[] messages = entry.diagnostics .Where(static message => !string.IsNullOrWhiteSpace(message)) .ToArray(); if (messages.Length == 0 || status == AssetImportStatus.Missing) + { return []; + } return messages.Select(message => status switch { AssetImportStatus.Pending => Diagnostic.Info("ASSET-IMPORT-PENDING", message, location), @@ -290,6 +319,10 @@ private static Diagnostic[] CreateImportDiagnostics(AssetMeta entry) private static string CreateState( AssetMeta entry, IReadOnlyList diagnostics - ) - => $"{entry.importStatus}:{entry.relativePath}:{string.Join('\n', diagnostics.Select(static value => value.message))}"; + ) => $"{entry.importStatus}:{entry.relativePath}:{string.Join('\n', diagnostics.Select(static value => value.message))}"; + + private sealed record Report( + DiagnosticSource source, + Diagnostic[] diagnostics + ); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs index 51f76ba86..aa1280d61 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -39,7 +38,7 @@ CancellationToken cancellationToken byte[] payload = context.sourceBytes.ToArray(); var asset = new BinaryAsset(payload.Length); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -61,6 +60,5 @@ CancellationToken cancellationToken AssetExportContext context, BinaryAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(asset.runtimePayload); + ) => ValueTask.FromResult?>(asset.runtimePayload); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs index 631470847..ad7568f62 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs @@ -3,7 +3,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -54,7 +53,8 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", Encoding.UTF8.GetBytes(content), - cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); } /// @@ -76,6 +76,5 @@ await output.WriteArtifactAsync( AssetExportContext context, TextAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.content)); + ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.content)); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs index 9ce73acc9..2c611ec39 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -13,18 +12,21 @@ namespace Inno.Assets.Pipeline; /// /// The imported asset type. /// -public sealed class AssetImportWriter where TAsset : AssetObject +public sealed class AssetImportWriter + where TAsset : AssetObject { private readonly AssetImportContext m_context; - private readonly Dictionary> m_outputs = - new(StringComparer.Ordinal); + + private readonly Dictionary> m_outputs = new(StringComparer.Ordinal); + private readonly List m_diagnostics = []; private readonly HashSet m_authoringOutputs = new(StringComparer.Ordinal); private AssetDeploymentScope? m_deploymentScope; internal AssetImportWriter(AssetImportContext context) { - m_context = context ?? throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(context); + m_context = context; } /// @@ -43,9 +45,13 @@ internal AssetImportWriter(AssetImportContext context) public void SetDeploymentScope(AssetDeploymentScope deploymentScope) { if (!Enum.IsDefined(deploymentScope)) + { throw new ArgumentOutOfRangeException(nameof(deploymentScope)); + } if (m_deploymentScope.HasValue) + { throw new InvalidOperationException("An importer can select its deployment scope only once."); + } m_deploymentScope = deploymentScope; } @@ -59,7 +65,9 @@ public void SetAsset(TAsset asset) { ArgumentNullException.ThrowIfNull(asset); if (this.asset is not null) + { throw new InvalidOperationException("An importer can assign its asset only once."); + } this.asset = asset; } @@ -72,30 +80,39 @@ public void SetAsset(TAsset asset) /// /// The output content. /// - /// - /// Cancellation for the write operation. - /// /// /// Whether this output is retained in runtime packages. Runtime payload and asset state cannot be authoring-only. /// + /// + /// Cancellation for the write operation. + /// /// /// A completed operation after the output has been staged. /// public ValueTask WriteArtifactAsync( string outputName, ReadOnlyMemory bytes, - CancellationToken cancellationToken = default, - AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime + AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime, + CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) + { throw new ArgumentException("An artifact output name is required.", nameof(outputName)); - if (!Enum.IsDefined(deploymentScope) || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state")) + } + if (!Enum.IsDefined(deploymentScope) + || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state") + ) { throw new ArgumentException("The output deployment scope is invalid.", nameof(deploymentScope)); + } if (!m_outputs.TryAdd(outputName, bytes.ToArray())) + { throw new InvalidOperationException($"Artifact output '{outputName}' was written more than once."); + } if (deploymentScope == AssetDeploymentScope.AuthoringOnly) + { m_authoringOutputs.Add(outputName); + } return ValueTask.CompletedTask; } @@ -126,10 +143,10 @@ public ValueTask WriteArtifactAsync( /// /// Declares an asset artifact input that invalidates this import. /// - /// + /// /// The stable persistent identity used for lookup. /// - public void DependsOnArtifact(Guid persistentId) => m_context.DependsOnArtifact(persistentId); + public void DependsOnArtifact(Guid persistentID) => m_context.DependsOnArtifact(persistentID); /// /// Declares a custom deterministic import input. @@ -154,14 +171,18 @@ string fingerprint public void ReportDiagnostic(string message) { if (string.IsNullOrWhiteSpace(message)) + { throw new ArgumentException("A diagnostic message is required.", nameof(message)); + } m_diagnostics.Add(message); } internal AssetImportProduct Complete() { if (asset is null) + { throw new InvalidOperationException("The importer did not assign an asset."); + } return new AssetImportProduct(asset, m_outputs, m_diagnostics, m_authoringOutputs, m_deploymentScope); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs new file mode 100644 index 000000000..f01722fc6 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetDependencyData +{ + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal string lastKnownPath { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs new file mode 100644 index 000000000..c87469f26 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs @@ -0,0 +1,27 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetImportDependencyData +{ + [SerializableProperty] + internal int kind { get; set; } + + [SerializableProperty] + internal string key { get; set; } + + [SerializableProperty] + internal string fingerprint { get; set; } + + [SerializableProperty] + internal bool sourceStampValid { get; set; } + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportFailureFingerprint.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportFailureFingerprint.cs index 90b4d02cd..66369a2db 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportFailureFingerprint.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportFailureFingerprint.cs @@ -4,6 +4,6 @@ internal readonly record struct AssetImportFailureFingerprint( string relativePath, int status, string sourceHash, - string importerId, + string importerID, string diagnostics ); diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs index acab6a270..756e9396d 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs @@ -1,16 +1,14 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline; -internal sealed class AssetImporterRegistry - : TypeRegistry +internal sealed class AssetImporterRegistry : TypeRegistry { private readonly object m_generationSync = new(); private readonly TypeCatalog m_types; @@ -23,21 +21,6 @@ internal AssetImporterRegistry(TypeCatalog types) m_types = types; } - internal AssetImporter? FindByPath(string relativePath) - { - string extension = Path.GetExtension(relativePath).ToLowerInvariant(); - return current.byExtension.GetValueOrDefault(extension); - } - - internal AssetImporter? FindById(string importerId) => current.byId.GetValueOrDefault(importerId); - - internal long GetGeneration(string importerId) - { - _ = current; - lock (m_generationSync) - return m_generations.GetValueOrDefault(importerId); - } - internal long snapshotVersion { get @@ -67,25 +50,28 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(AssetImporter).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Asset importer metadata on '{type.FullName}' requires a concrete {nameof(AssetImporter)} subtype."); + $"Asset importer metadata on '{type.FullName}' requires a concrete {nameof(AssetImporter)} subtype." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }).ToArray(); - string? duplicateId = registrations + string? duplicateID = registrations .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; - if (duplicateId is not null) - throw new InvalidOperationException($"Asset importer id '{duplicateId}' is registered by multiple importers."); + if (duplicateID is not null) + { + throw new InvalidOperationException($"Asset importer id '{duplicateID}' is registered by multiple importers."); + } var byExtension = new Dictionary(StringComparer.OrdinalIgnoreCase); - var byId = new Dictionary(StringComparer.Ordinal); - var typesById = new Dictionary(StringComparer.Ordinal); - foreach ((Type type, string importerId) in registrations) + var byID = new Dictionary(StringComparer.Ordinal); + var typesByID = new Dictionary(StringComparer.Ordinal); + foreach ((Type type, string importerID) in registrations) { AssetImporter importer = CreateExtension(type); - importer.BindImporterId(importerId); - byId.Add(importerId, importer); - typesById.Add(importerId, type); + importer.BindImporterID(importerID); + byID.Add(importerID, importer); + typesByID.Add(importerID, type); foreach (string declaredExtension in importer.supportedExtensions) { @@ -93,16 +79,18 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (!byExtension.TryAdd(extension, importer)) { throw new InvalidOperationException( - $"Asset extension '{extension}' is registered by both " + - $"'{byExtension[extension].GetType().FullName}' and '{type.FullName}'."); + $"Asset extension '{extension}' is registered by both " + + $"'{byExtension[extension].GetType().FullName}' and '{type.FullName}'." + ); } } } return new Snapshot( byExtension.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase), - byId.ToFrozenDictionary(StringComparer.Ordinal), - typesById.ToFrozenDictionary(StringComparer.Ordinal)); + byID.ToFrozenDictionary(StringComparer.Ordinal), + typesByID.ToFrozenDictionary(StringComparer.Ordinal) + ); } /// @@ -121,13 +109,13 @@ Snapshot candidate lock (m_generationSync) { m_generationRollback = new Dictionary(m_generations, StringComparer.Ordinal); - foreach ((string importerId, Type importerType) in candidate.typesById) + foreach ((string importerID, Type importerType) in candidate.typesByID) { - if (previous is null || - !previous.typesById.TryGetValue(importerId, out Type? previousType) || - previousType != importerType) - { - m_generations[importerId] = m_generations.GetValueOrDefault(importerId) + 1; + if (previous is null + || !previous.typesByID.TryGetValue(importerID, out Type? previousType) + || previousType != importerType + ) { + m_generations[importerID] = m_generations.GetValueOrDefault(importerID) + 1; } } } @@ -149,10 +137,14 @@ Snapshot candidate lock (m_generationSync) { if (m_generationRollback is null) + { return; + } m_generations.Clear(); - foreach ((string importerId, long generation) in m_generationRollback) - m_generations.Add(importerId, generation); + foreach ((string importerID, long generation) in m_generationRollback) + { + m_generations.Add(importerID, generation); + } m_generationRollback = null; } } @@ -171,7 +163,9 @@ protected override void OnActivationCompleted( Snapshot currentSnapshot ) { lock (m_generationSync) + { m_generationRollback = null; + } } /// @@ -180,19 +174,38 @@ Snapshot currentSnapshot /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.byId.Values); + protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.byID.Values); + + internal AssetImporter? FindByPath(string relativePath) + { + string extension = Path.GetExtension(relativePath).ToLowerInvariant(); + return current.byExtension.GetValueOrDefault(extension); + } + + internal AssetImporter? FindByID(string importerID) => current.byID.GetValueOrDefault(importerID); + + internal long GetGeneration(string importerID) + { + _ = current; + lock (m_generationSync) + { + return m_generations.GetValueOrDefault(importerID); + } + } private static string NormalizeExtension(string extension) { if (string.IsNullOrWhiteSpace(extension)) + { throw new InvalidOperationException("Asset importer extensions cannot be empty."); + } string normalized = extension.Trim().ToLowerInvariant(); return normalized[0] == '.' ? normalized : "." + normalized; } internal sealed record Snapshot( FrozenDictionary byExtension, - FrozenDictionary byId, - FrozenDictionary typesById + FrozenDictionary byID, + FrozenDictionary typesByID ); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs index 56207f144..fd90d75e4 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs @@ -1,48 +1,67 @@ using System; - -using Inno.Assets; using Inno.Core.Serialization; namespace Inno.Assets.Pipeline; internal sealed class AssetMeta : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal string relativePath { get; set; } = string.Empty; - [SerializableProperty] internal string sourceHash { get; set; } = string.Empty; - [SerializableProperty] internal long sourceLength { get; set; } = -1; - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal int deploymentScope { get; set; } = (int)AssetDeploymentScope.Runtime; - [SerializableProperty] internal Guid stableAssetTypeId { get; set; } - [SerializableProperty] internal byte[] assetStateBytes { get; set; } = []; - [SerializableProperty] internal AssetDependencyData[] runtimeDependencies { get; set; } = []; - [SerializableProperty] internal AssetImportDependencyData[] importDependencies { get; set; } = []; - [SerializableProperty] internal int importStatus { get; set; } = (int)AssetImportStatus.Pending; - [SerializableProperty] internal string importerImplementationFingerprint { get; set; } = string.Empty; - [SerializableProperty] internal string importerSettingsHash { get; set; } = string.Empty; - [SerializableProperty] internal string artifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string[] diagnostics { get; set; } = []; - [SerializableProperty] internal bool isDirectory { get; set; } - [SerializableProperty] internal bool isTombstone { get; set; } -} + [SerializableProperty] + internal Guid persistentId { get; set; } -internal struct AssetDependencyData -{ - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal string lastKnownPath { get; set; } -} + [SerializableProperty] + internal string relativePath { get; set; } = string.Empty; -internal struct AssetImportDependencyData -{ - [SerializableProperty] internal int kind { get; set; } - [SerializableProperty] internal string key { get; set; } - [SerializableProperty] internal string fingerprint { get; set; } - [SerializableProperty] internal bool sourceStampValid { get; set; } - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } + [SerializableProperty] + internal string sourceHash { get; set; } = string.Empty; + + [SerializableProperty] + internal long sourceLength { get; set; } = -1; + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal int deploymentScope { get; set; } = (int)AssetDeploymentScope.Runtime; + + [SerializableProperty] + internal Guid stableAssetTypeId { get; set; } + + [SerializableProperty] + internal byte[] assetStateBytes { get; set; } = []; + + [SerializableProperty] + internal AssetDependencyData[] runtimeDependencies { get; set; } = []; + + [SerializableProperty] + internal AssetImportDependencyData[] importDependencies { get; set; } = []; + + [SerializableProperty] + internal int importStatus { get; set; } = (int)AssetImportStatus.Pending; + + [SerializableProperty] + internal string importerImplementationFingerprint { get; set; } = string.Empty; + + [SerializableProperty] + internal string importerSettingsHash { get; set; } = string.Empty; + + [SerializableProperty] + internal string artifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string[] diagnostics { get; set; } = []; + + [SerializableProperty] + internal bool isDirectory { get; set; } + + [SerializableProperty] + internal bool isTombstone { get; set; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs b/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs index a4e518ea6..ee1c7126a 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Assets.Pipeline; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Assets", - "Inno.Assets.Pipeline", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Assets", "Inno.Assets.Pipeline", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetImportContext), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetImportExtensionUnavailableException), ScriptingApiScope.Editor)] diff --git a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs index 58dfc2246..dd3878312 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs @@ -30,20 +30,17 @@ public static partial class NativeAssetSourceSerialization public static byte[] Export( TAsset asset, AssetSerializationServices services - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(asset); ArgumentNullException.ThrowIfNull(services); TypeRef type = services.types.GetTypeRef(asset.GetType()); var dependencies = new AssetDependencyCollection(); SerializationContext context = services.context.With(dependencies); - byte[] propertyData = services.serialization.Encode( - writer => writer.WriteProperties(asset), - context); + byte[] propertyData = services.serialization.Encode(writer => writer.WriteProperties(asset), context); return services.serialization.Serialize(new NativeAssetSourceDocument { - stableAssetTypeId = type.stableId, + stableAssetTypeId = type.stableID, propertyData = propertyData, dependencies = dependencies.dependencies.ToArray() }); @@ -58,12 +55,12 @@ AssetSerializationServices services /// /// Native source bytes. /// - /// - /// Receives persistent dependencies discovered during export. - /// /// /// The generation-bound serialization and reference services supplied by the import context. /// + /// + /// Receives persistent dependencies discovered during export. + /// /// /// A detached asset ready for an import transaction. /// @@ -74,20 +71,20 @@ public static TAsset Import( ReadOnlySpan bytes, AssetSerializationServices services, out IReadOnlyList dependencies - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(services); NativeAssetSourceDocument document = services.serialization.Deserialize(bytes); TypeRef expectedType = services.types.GetTypeRef(typeof(TAsset)); - if (document.stableAssetTypeId != expectedType.stableId) + if (document.stableAssetTypeId != expectedType.stableID) { throw new InvalidOperationException( - $"Native asset source type '{document.stableAssetTypeId:D}' does not match " + - $"'{expectedType.stableId:D}'."); + $"Native asset source type '{document.stableAssetTypeId:D}' does not match " + + $"'{expectedType.stableID:D}'." + ); } - var asset = (TAsset)(Activator.CreateInstance(typeof(TAsset), nonPublic: true) - ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); + TAsset asset = (TAsset)(Activator.CreateInstance(typeof(TAsset), nonPublic: true) + ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); SerializationContext context = AssetSerializationContext.Create(services.references); _ = services.serialization.Decode(document.propertyData, reader => { diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs index 886cd0a0a..0f24d9cdd 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs @@ -24,7 +24,9 @@ public static AssetChangedEvent[] Normalize( IReadOnlyList rawBatch ) { if (rawBatch.Count == 0) + { return []; + } var byPath = new Dictionary(StringComparer.OrdinalIgnoreCase); var renameOldPaths = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -34,10 +36,14 @@ IReadOnlyList rawBatch AssetChangedEvent e = rawBatch[i]; string path = NormalizeRelativePath(e.relativePath); if (string.IsNullOrWhiteSpace(path)) + { continue; + } if (!byPath.TryGetValue(path, out Accumulator acc)) + { acc = new Accumulator(path); + } if (!string.IsNullOrWhiteSpace(e.oldRelativePath)) { @@ -51,13 +57,21 @@ IReadOnlyList rawBatch WatcherChangeTypes type = e.changeType; if (type.HasFlag(WatcherChangeTypes.Renamed)) + { acc.renamed = true; + } if (type.HasFlag(WatcherChangeTypes.Created)) + { acc.created = true; + } if (type.HasFlag(WatcherChangeTypes.Changed)) + { acc.changed = true; + } if (type.HasFlag(WatcherChangeTypes.Deleted)) + { acc.deleted = true; + } byPath[path] = acc; } @@ -66,10 +80,14 @@ IReadOnlyList rawBatch foreach (Accumulator acc in byPath.Values) { if (renameOldPaths.Contains(acc.path) && !acc.renamed) + { continue; + } if (TryBuildNormalized(rootPath, acc, out AssetChangedEvent normalizedEvent)) + { normalized.Add(normalizedEvent); + } } return normalized @@ -88,9 +106,13 @@ out AssetChangedEvent normalized { WatcherChangeTypes type = WatcherChangeTypes.Renamed; if (acc.changed) + { type |= WatcherChangeTypes.Changed; + } if (acc.created) + { type |= WatcherChangeTypes.Created; + } normalized = new AssetChangedEvent(acc.path, type, acc.renameOldPath); return true; @@ -100,17 +122,29 @@ out AssetChangedEvent normalized WatcherChangeTypes foldedType; if (acc.deleted && (acc.created || acc.changed)) + { foldedType = exists ? WatcherChangeTypes.Changed : WatcherChangeTypes.Deleted; + } else if (acc.deleted) + { foldedType = WatcherChangeTypes.Deleted; + } else if (acc.created && acc.changed) + { foldedType = WatcherChangeTypes.Created | WatcherChangeTypes.Changed; + } else if (acc.created) + { foldedType = WatcherChangeTypes.Created; + } else if (acc.changed) + { foldedType = WatcherChangeTypes.Changed; + } else + { foldedType = 0; + } if (foldedType == 0) { @@ -127,21 +161,29 @@ private static bool ExistsAt( string relativePath ) { string full = Path.Combine(rootPath, relativePath); - return System.IO.File.Exists(full) || Directory.Exists(full); + return File.Exists(full) || Directory.Exists(full); } private static string NormalizeRelativePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return string.Empty; + } string path = relativePath.Replace('\\', '/').Trim(); while (path.StartsWith("./", StringComparison.Ordinal)) + { path = path[2..]; + } while (path.StartsWith("/", StringComparison.Ordinal)) + { path = path[1..]; + } while (path.EndsWith("/", StringComparison.Ordinal)) + { path = path[..^1]; + } return path == "." ? string.Empty : path; } @@ -152,22 +194,27 @@ private struct Accumulator(string path) /// The path value used as part of this type's public representation. /// public string path = path; + /// /// The created value used as part of this type's public representation. /// public bool created; + /// /// The changed value used as part of this type's public representation. /// public bool changed; + /// /// The deleted value used as part of this type's public representation. /// public bool deleted; + /// /// The renamed value used as part of this type's public representation. /// public bool renamed; + /// /// The rename old path value used as part of this type's public representation. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs index 39fbfd2e7..ce21ae981 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs @@ -1,5 +1,4 @@ using System.IO; - using Inno.Assets; using Inno.Core.Identity; @@ -13,11 +12,12 @@ public sealed class AssetFileEntry : IdentityObject /// /// Gets the final source path segment, or the semantic mount-root label when this entry is a source root. /// - public string name => string.IsNullOrEmpty(assetPath.localPath) - ? assetPath.source == AssetSourceId.project - ? "Assets" - : assetPath.source.value - : Path.GetFileName(assetPath.localPath); + public string name + => string.IsNullOrEmpty(assetPath.localPath) + ? assetPath.source == AssetSourceID.project + ? "Assets" + : assetPath.source.value + : Path.GetFileName(assetPath.localPath); /// /// Gets the final source path segment without its last extension. @@ -32,7 +32,7 @@ public sealed class AssetFileEntry : IdentityObject /// /// Gets the owning source mount identity. /// - public AssetSourceId source => assetPath.source; + public AssetSourceID source => assetPath.source; /// /// Gets whether source mutations are forbidden. @@ -58,6 +58,7 @@ public sealed class AssetFileEntry : IdentityObject /// Gets whether the entry represents a directory. /// public bool isDirectory { get; internal set; } + /// /// Gets the normalized lower-case file extension. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs index 60a9ceca2..2a5681b40 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs @@ -5,10 +5,9 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Inno.Assets; -using Inno.Core.Identity; using Inno.Core.Collections; +using Inno.Core.Identity; namespace Inno.Assets.Pipeline; @@ -26,28 +25,11 @@ public sealed class AssetFileSystem : IDisposable private readonly Lock m_sync = new(); private readonly AssetWatcher m_watcher; private readonly AssetSourcePolicy m_sourcePolicy; - private readonly IReadOnlyDictionary m_mounts; + private readonly IReadOnlyDictionary m_mounts; private readonly Func? m_persistentIdentityResolver; private bool m_identitiesActive; private bool m_disposed; - private readonly record struct SourceEntry( - AssetPath path, - Guid persistentId, - bool isReadOnly, - bool isDirectory - ); - - /// - /// Gets the absolute source asset root. - /// - public string assetRoot { get; } - - /// - /// Gets whether source file watching is active. - /// - public bool isWatching => m_watcher.isWatching; - /// /// Creates an indexed source file system. /// @@ -68,18 +50,16 @@ public AssetFileSystem( bool autoStart = true, int flushDelayMs = 80, AssetSourcePolicy? sourcePolicy = null - ) - : this( - [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], - autoStart, - flushDelayMs, - sourcePolicy, - requireWritableProject: true, - identities: new IdentityAllocator(), - persistentIdentityResolver: null, - activateIdentities: true) - { - } + ) : this( + [new AssetSourceMount(AssetSourceID.project, assetRoot, isReadOnly: false)], + autoStart, + flushDelayMs, + sourcePolicy, + requireWritableProject: true, + identities: new IdentityAllocator(), + persistentIdentityResolver: null, + activateIdentities: true + ) {} /// /// Creates an indexed file system over isolated source mounts. @@ -106,18 +86,16 @@ public AssetFileSystem( int flushDelayMs = 80, AssetSourcePolicy? sourcePolicy = null, bool requireWritableProject = true - ) - : this( - mounts, - autoStart, - flushDelayMs, - sourcePolicy, - requireWritableProject, - identities: new IdentityAllocator(), - persistentIdentityResolver: null, - activateIdentities: true) - { - } + ) : this( + mounts, + autoStart, + flushDelayMs, + sourcePolicy, + requireWritableProject, + identities: new IdentityAllocator(), + persistentIdentityResolver: null, + activateIdentities: true + ) {} internal AssetFileSystem( IReadOnlyList mounts, @@ -132,29 +110,38 @@ bool activateIdentities ArgumentNullException.ThrowIfNull(mounts); ArgumentNullException.ThrowIfNull(identities); if (mounts.Count == 0) + { throw new ArgumentException("At least one asset source mount is required.", nameof(mounts)); - Dictionary byId = mounts.ToDictionary(static mount => mount.id); - if (byId.Count != mounts.Count) - throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); - if (!byId.TryGetValue(AssetSourceId.project, out AssetSourceMount? project) - || project.isReadOnly && requireWritableProject) + } + Dictionary byID = mounts.ToDictionary(static mount => mount.id); + if (byID.Count != mounts.Count) { + throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } + if (!byID.TryGetValue(AssetSourceID.project, out AssetSourceMount? project) + || project.isReadOnly && requireWritableProject + ) { throw new ArgumentException( requireWritableProject - ? "A writable project asset source mount is required." - : "A project asset source mount is required.", - nameof(mounts)); + ? "A writable project asset source mount is required." + : "A project asset source mount is required.", + nameof(mounts) + ); } if (project.isReadOnly && autoStart) + { throw new ArgumentException("A read-only project source cannot be watched for authoring changes.", nameof(autoStart)); + } - assetRoot = project.rootPath; + this.assetRoot = project.rootPath; m_identities = identities; - m_mounts = byId; + m_mounts = byID; m_persistentIdentityResolver = persistentIdentityResolver; m_identitiesActive = activateIdentities; foreach (AssetSourceMount mount in mounts) + { Directory.CreateDirectory(mount.rootPath); + } m_sourcePolicy = sourcePolicy ?? AssetSourcePolicy.defaultPolicy; m_pathKey = m_entries.DefineKey("filesystem.path", IndexedObjectKeyFlags.Unique); @@ -166,9 +153,21 @@ bool activateIdentities m_watcher = new AssetWatcher(assetRoot, flushDelayMs); if (autoStart) + { m_watcher.Start(); + } } + /// + /// Gets the absolute source asset root. + /// + public string assetRoot { get; } + + /// + /// Gets whether source file watching is active. + /// + public bool isWatching => m_watcher.isWatching; + /// /// Starts source file watching. /// @@ -184,7 +183,9 @@ public void Start() public void Stop() { if (m_disposed) + { return; + } m_watcher.Stop(); } @@ -215,24 +216,28 @@ public void Refresh() { List candidate = CollectEntries(); AssetFileEntry[] previous = m_entries.All().ToArray(); - Dictionary existing = previous.ToDictionary(static entry => entry.identity.persistentId); + Dictionary existing = previous.ToDictionary(static entry => entry.identity.persistentID); var prepared = new List<(SourceEntry source, AssetFileEntry entry)>(candidate.Count); - var registered = new List(); + List registered = []; try { foreach (SourceEntry source in candidate) { - if (!existing.TryGetValue(source.persistentId, out AssetFileEntry? entry)) + if (!existing.TryGetValue(source.persistentID, out AssetFileEntry? entry)) { entry = new AssetFileEntry(); if (m_identitiesActive) { - if (!m_identities.Register(entry, source.persistentId)) + if (!m_identities.Register(entry, source.persistentID)) + { throw new InvalidOperationException($"Asset source entry '{source.path}' could not acquire its identity."); + } registered.Add(entry); } else - m_identities.InitializePersistentIdentity(entry, source.persistentId); + { + m_identities.InitializePersistentIdentity(entry, source.persistentID); + } } prepared.Add((source, entry)); } @@ -240,18 +245,24 @@ public void Refresh() catch { foreach (AssetFileEntry entry in registered) + { _ = m_identities.Unregister(entry); + } throw; } m_entries.RemoveAll(); foreach ((SourceEntry source, AssetFileEntry entry) in prepared) { IndexEntry(entry, source); - existing.Remove(source.persistentId); + existing.Remove(source.persistentID); } if (m_identitiesActive) + { foreach (AssetFileEntry removed in existing.Values) + { _ = m_identities.Unregister(removed); + } + } } } @@ -321,8 +332,8 @@ public IReadOnlyList GetEntries(bool includeDirectories = true) lock (m_sync) { IReadOnlyList all = includeDirectories - ? m_entries.All() - : m_entries.Find(m_isDirectoryKey, false); + ? m_entries.All() + : m_entries.Find(m_isDirectoryKey, false); return all .OrderBy(static x => x.assetPath.ToString(), StringComparer.OrdinalIgnoreCase) @@ -379,7 +390,9 @@ public IReadOnlyList PollChanges(out bool requiresFullRescan) WatcherPollResult result = m_watcher.Poll(force: false); requiresFullRescan = result.requiresFullRescan; if (result.changes.Count > 0 || requiresFullRescan) + { RefreshSafely(); + } return result.changes; } @@ -407,13 +420,15 @@ public IReadOnlyList WaitForIdle(out bool requiresFullRescan) if (!m_watcher.isWatching) { requiresFullRescan = false; - return Array.Empty(); + return []; } WatcherPollResult result = m_watcher.WaitForIdle(); requiresFullRescan = result.requiresFullRescan; if (result.changes.Count > 0 || requiresFullRescan) + { RefreshSafely(); + } return result.changes; } @@ -423,7 +438,9 @@ public IReadOnlyList WaitForIdle(out bool requiresFullRescan) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_watcher.Dispose(); @@ -440,16 +457,19 @@ internal void ActivateIdentities() lock (m_sync) { if (m_identitiesActive) + { return; - var registered = new List(); + } + List registered = []; try { foreach (AssetFileEntry entry in m_entries.All()) { - if (!m_identities.Register(entry, entry.identity.persistentId)) + if (!m_identities.Register(entry, entry.identity.persistentID)) { throw new InvalidOperationException( - $"Asset source entry '{entry.assetPath}' was already registered."); + $"Asset source entry '{entry.assetPath}' was already registered." + ); } registered.Add(entry); } @@ -458,7 +478,9 @@ internal void ActivateIdentities() catch { foreach (AssetFileEntry entry in registered) + { _ = m_identities.Unregister(entry); + } throw; } } @@ -467,13 +489,17 @@ internal void ActivateIdentities() internal void DeactivateIdentities() { lock (m_sync) + { DeactivateIdentitiesLocked(); + } } private void RefreshSafely() { if (m_disposed) + { return; + } try { @@ -494,7 +520,7 @@ private void RefreshSafely() private List CollectEntries() { - var entries = new List(); + List entries = []; var identities = new HashSet(); foreach (AssetSourceMount mount in m_mounts.Values.OrderBy(static value => value.id.value, StringComparer.Ordinal)) { @@ -508,13 +534,17 @@ private List CollectEntries() { string path = CombineLocalPath(directory, Path.GetFileName(child)); if (!m_sourcePolicy.IsIgnored(path, isDirectory: true)) + { pending.Push(path); + } } foreach (string child in Directory.EnumerateFiles(absoluteDirectory)) { string path = CombineLocalPath(directory, Path.GetFileName(child)); if (!m_sourcePolicy.IsIgnored(path, isDirectory: false)) + { Add(new AssetPath(mount.id, path), mount.isReadOnly, isDirectory: false); + } } } } @@ -525,11 +555,13 @@ void Add( bool isReadOnly, bool isDirectory ) { - Guid sourceId = m_persistentIdentityResolver?.Invoke(path) ?? CreateFallbackPersistentId(path.ToString()); - Guid entryId = CreateEntryPersistentId(sourceId); - if (!identities.Add(entryId)) + Guid sourceID = m_persistentIdentityResolver?.Invoke(path) ?? CreateFallbackPersistentID(path.ToString()); + Guid entryID = CreateEntryPersistentID(sourceID); + if (!identities.Add(entryID)) + { throw new InvalidDataException($"Asset source path '{path}' duplicates a persistent entry identity."); - entries.Add(new(path, entryId, isReadOnly, isDirectory)); + } + entries.Add(new SourceEntry(path, entryID, isReadOnly, isDirectory)); } } @@ -547,8 +579,8 @@ SourceEntry source existing.parentAssetPath = AssetPath.Parse(GetParentPath(path)); existing.isDirectory = isDirectory; existing.extension = isDirectory - ? string.Empty - : Path.GetExtension(path).ToLowerInvariant(); + ? string.Empty + : Path.GetExtension(path).ToLowerInvariant(); m_entries.Add(existing) .Set(m_pathKey, existing.assetPath.ToString()) @@ -557,46 +589,65 @@ SourceEntry source .Set(m_extensionKey, existing.extension); } - private static Guid CreateFallbackPersistentId(string path) + private void UnregisterEntries() + { + foreach (AssetFileEntry entry in m_entries.All()) + { + _ = m_identities.Unregister(entry); + } + } + + private void DeactivateIdentitiesLocked() + { + if (!m_identitiesActive) + { + return; + } + UnregisterEntries(); + m_identitiesActive = false; + } + + private string NormalizeAssetPath(AssetPath path) + { + if (!path.isValid) + { + throw new ArgumentException("An isolated asset path is required.", nameof(path)); + } + if (!m_mounts.ContainsKey(path.source)) + { + throw new ArgumentException($"Asset source mount '{path.source}' is not indexed.", nameof(path)); + } + return path.ToString(); + } + + private static Guid CreateFallbackPersistentID(string path) { byte[] pathBytes = Encoding.UTF8.GetBytes(path); Span namespaceBytes = stackalloc byte[16]; new Guid("eac730be-e359-49f7-86c9-b3b09da457cc").TryWriteBytes(namespaceBytes); - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); hash.AppendData(namespaceBytes); hash.AppendData(pathBytes); return new Guid(hash.GetHashAndReset().AsSpan(0, 16)); } - private static Guid CreateEntryPersistentId(Guid sourcePersistentId) + private static Guid CreateEntryPersistentID(Guid sourcePersistentID) { Span input = stackalloc byte[32]; - sourcePersistentId.TryWriteBytes(input[..16]); + sourcePersistentID.TryWriteBytes(input[..16]); new Guid("f42622a8-893d-4d5d-b1c0-30910cf5378e").TryWriteBytes(input[16..]); Span hash = stackalloc byte[32]; SHA256.HashData(input, hash); return new Guid(hash[..16]); } - private void UnregisterEntries() - { - foreach (AssetFileEntry entry in m_entries.All()) - _ = m_identities.Unregister(entry); - } - - private void DeactivateIdentitiesLocked() - { - if (!m_identitiesActive) - return; - UnregisterEntries(); - m_identitiesActive = false; - } - private static string GetParentPath(string relativePath) { AssetPath path = AssetPath.Parse(relativePath ?? string.Empty); if (string.IsNullOrWhiteSpace(path.localPath)) + { return string.Empty; + } int lastSeparator = path.localPath.LastIndexOf('/'); string parent = lastSeparator < 0 ? string.Empty : path.localPath[..lastSeparator]; @@ -607,18 +658,15 @@ private static string GetParentPath(string relativePath) private static string CombineLocalPath( string a, string b - ) - => NormalizeLocalPath(Path.Combine(NormalizeLocalPath(a), NormalizeLocalPath(b))); - - private string NormalizeAssetPath(AssetPath path) - { - if (!path.isValid) - throw new ArgumentException("An isolated asset path is required.", nameof(path)); - if (!m_mounts.ContainsKey(path.source)) - throw new ArgumentException($"Asset source mount '{path.source}' is not indexed.", nameof(path)); - return path.ToString(); - } + ) => NormalizeLocalPath(Path.Combine(NormalizeLocalPath(a), NormalizeLocalPath(b))); private static string NormalizeLocalPath(string relativePath) - => new AssetPath(AssetSourceId.project, relativePath ?? string.Empty).localPath; + => new AssetPath(AssetSourceID.project, relativePath ?? string.Empty).localPath; + + private readonly record struct SourceEntry( + AssetPath path, + Guid persistentID, + bool isReadOnly, + bool isDirectory + ); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs index 479d14350..ee5a78ca6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs @@ -4,13 +4,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; -using Inno.Scripting.Api; using Inno.Extensibility.Reload; using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -22,10 +21,6 @@ public sealed partial class AssetPipeline private AssetSampleImportTransaction? m_sampleImport; private bool m_reconcileSampleImport; - internal bool isSampleImportFaulted => m_generations.state == GenerationState.Faulted; - - internal void FaultSampleImport(Exception failure) => m_generations.Fault(failure); - /// /// Starts a private background sample clone without waiting for file copying or transformation. /// @@ -50,34 +45,48 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) EnsureOwnerThread(); m_generations.EnsureReady("import an Asset sample"); if (m_sourceMountCandidate is not null) + { throw new InvalidOperationException("A source-mount candidate is already pending."); + } AssetFileSystem fileSystem = GetFileSystem(); if (!fileSystem.TryGetEntry(source, out AssetFileEntry entry) || !entry.isDirectory || !entry.isSample) + { throw new ArgumentException($"Asset source '{source}' is not an installed Plugin sample directory.", nameof(source)); + } AssetPath target = AssetPath.Project(AssetSample.GetImportName(source)); RequireSampleDestination(target); AssetSourceMount sourceMount = sourceMounts.Single(mount => mount.id == source.source); string transactionRoot = Path.Combine(libraryRoot, "AssetDatabase", "Transactions", Guid.NewGuid().ToString("N")); IDisposable generation = m_generations.AcquireRead("import an Asset sample"); SerializationGeneration? serialization = null; - var rewriters = new List(); + List rewriters = []; try { serialization = m_serialization.CaptureGeneration(); foreach (Type type in m_types.GetTypesWithAttribute() - .Select(reference => reference.Resolve(m_types)) - .OrderBy(type => type.GetCustomAttributes(typeof(AssetSampleSourceRewriterAttribute), false) - .Cast().Single().id, StringComparer.Ordinal)) - { + .Select(reference => reference.Resolve(m_types)) + .OrderBy(type => type.GetCustomAttributes(typeof(AssetSampleSourceRewriterAttribute), false) + .Cast() + .Single().id, StringComparer.Ordinal) + ) { if (type.IsAbstract || !typeof(IAssetSampleSourceRewriter).IsAssignableFrom(type) - || Activator.CreateInstance(type) is not IAssetSampleSourceRewriter rewriter) + || Activator.CreateInstance(type) is not IAssetSampleSourceRewriter rewriter + ) { throw new InvalidOperationException($"Sample transformer '{type.FullName}' is not a concrete source rewriter."); + } rewriters.Add(rewriter); } m_sampleImport = new AssetSampleImportTransaction( - this, source, target, sourceMount.Resolve(source.localPath), transactionRoot, + this, + source, + target, + sourceMount.Resolve(source.localPath), + transactionRoot, m_options.sourcePolicy ?? AssetSourcePolicy.defaultPolicy, - generation, serialization, rewriters.ToArray()); + generation, + serialization, + rewriters.ToArray() + ); return m_sampleImport; } catch (Exception failure) @@ -85,9 +94,13 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) var cleanup = new LifetimeScope(); cleanup.Own(generation); if (serialization is not null) + { cleanup.Own(serialization); + } foreach (IDisposable rewriter in rewriters.OfType()) + { cleanup.Own(rewriter); + } try { cleanup.Dispose(); @@ -100,11 +113,17 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) } } + internal bool isSampleImportFaulted => m_generations.state == GenerationState.Faulted; + + internal void FaultSampleImport(Exception failure) => m_generations.Fault(failure); + internal void EnsureSampleImportOwner(AssetSampleImportTransaction transaction) { EnsureInitializationThread(); if (!ReferenceEquals(m_sampleImport, transaction)) + { throw new InvalidOperationException("The sample transaction no longer belongs to this pipeline."); + } } internal Task PrepareSampleCatalogAsync( @@ -120,9 +139,9 @@ CancellationToken cancellationToken string destination = Path.Combine(assetRoot, transaction.target.localPath); Directory.Move(transaction.stagedSource, destination); transaction.sourceMoved = true; - if (System.IO.File.Exists(transaction.stagedSource + ".imeta")) + if (File.Exists(transaction.stagedSource + ".imeta")) { - System.IO.File.Move(transaction.stagedSource + ".imeta", destination + ".imeta"); + File.Move(transaction.stagedSource + ".imeta", destination + ".imeta"); transaction.metaMoved = true; } AssetLoader activeLoader = GetLoader(); @@ -139,10 +158,14 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); AssetPath candidate = AssetPath.Project(localPath); if (!loader.TryGetAssetType(candidate, out Type? assetType) || assetType is null) + { continue; + } AssetObject? imported = loader.Load(candidate, assetType); if (imported is null || imported.isMissing) + { throw new InvalidDataException($"Sample asset '{candidate}' failed pre-publication import validation."); + } } cancellationToken.ThrowIfCancellationRequested(); return prepared; @@ -179,16 +202,20 @@ internal void CommitSampleImport( EnsureSampleImportOwner(transaction); var changes = new List(transaction.entries.Count + 1) { - new(transaction.target.localPath, WatcherChangeTypes.Created) + new AssetChangedEvent(transaction.target.localPath, WatcherChangeTypes.Created) }; changes.AddRange(transaction.entries.Select(static path => new AssetChangedEvent(path, WatcherChangeTypes.Created))); AssetChange[] committed = CreateCommittedChanges( - transaction.candidate!.candidateLoader, changes, new Dictionary(StringComparer.OrdinalIgnoreCase), requiresFullRescan: false); + transaction.candidate!.candidateLoader, + changes, + new Dictionary(StringComparer.OrdinalIgnoreCase), + requiresFullRescan: false + ); transaction.candidate!.Activate(); beforePublish?.Invoke(transaction.target); transaction.candidate.Complete(); FinishSampleImport(transaction); - InvokeObservers(Changed, new AssetChangeSet(m_revision, committed)); + InvokeObservers(changed, new AssetChangeSet(m_revision, committed)); } internal void RollbackSampleImport(AssetSampleImportTransaction transaction) @@ -196,9 +223,9 @@ internal void RollbackSampleImport(AssetSampleImportTransaction transaction) EnsureSampleImportOwner(transaction); transaction.candidate?.Rollback(); string destination = Path.Combine(assetRoot, transaction.target.localPath); - if (transaction.metaMoved && System.IO.File.Exists(destination + ".imeta")) + if (transaction.metaMoved && File.Exists(destination + ".imeta")) { - System.IO.File.Move(destination + ".imeta", transaction.stagedSource + ".imeta"); + File.Move(destination + ".imeta", transaction.stagedSource + ".imeta"); transaction.metaMoved = false; } if (transaction.sourceMoved && Directory.Exists(destination)) @@ -207,7 +234,9 @@ internal void RollbackSampleImport(AssetSampleImportTransaction transaction) transaction.sourceMoved = false; } if (!transaction.TryCleanPrivateCopy()) + { throw new RetirementPendingException("Sample import private storage is still being removed."); + } FinishSampleImport(transaction); } @@ -229,7 +258,9 @@ private void FinishSampleImport(AssetSampleImportTransaction transaction) private void RequireSampleDestination(AssetPath target) { string destination = Path.Combine(assetRoot, target.localPath); - if (Directory.Exists(destination) || System.IO.File.Exists(destination) || System.IO.File.Exists(destination + ".imeta")) + if (Directory.Exists(destination) || File.Exists(destination) || File.Exists(destination + ".imeta")) + { throw new IOException($"Sample import target '{target}' already exists."); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs index 4b700f5e8..170f8f7d3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs @@ -1,22 +1,21 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; - -using Inno.Assets; -using Inno.Core.Execution; -using Inno.References; -using System.IO; using System.Threading.Tasks; +using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -25,125 +24,6 @@ namespace Inno.Assets.Pipeline; /// public sealed partial class AssetPipeline { - private AssetSourceMountTransaction PrepareSourceMountsCore(IReadOnlyList mounts) - { - using IDisposable operationScope = AcquireOperation(); - lock (m_lifecycleLock) - { - m_generations.EnsureRetirementSafe(); - if (m_failedPreparation is not null || m_shutdown is not null) - throw new InvalidOperationException("The Asset Pipeline is retiring and cannot prepare a source candidate."); - if (m_sourceMountCandidate is not null) - throw new InvalidOperationException("Another source-mount candidate is already pending."); - AssetSourceMount[] snapshot = mounts.ToArray(); - AssetSourceMount projectMount = snapshot.SingleOrDefault(static mount => mount.id == AssetSourceId.project) - ?? throw new ArgumentException("A project asset source mount is required.", nameof(mounts)); - if (projectMount.isReadOnly) - throw new ArgumentException("The project asset source mount must be writable.", nameof(mounts)); - if (snapshot.Select(static mount => mount.id).Distinct().Count() != snapshot.Length) - throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); - PreparedSourceMounts prepared = PrepareSourceMountCatalog(GetLoader(), snapshot, CancellationToken.None); - try - { - return AdoptSourceMountCatalog(prepared, GetLoader().CaptureRecoveryStates()); - } - catch (Exception failure) - { - try - { - DiscardSourceMountCatalog(prepared); - } - catch (Exception cleanup) - { - throw new AggregateException("Asset source adoption and retirement failed.", failure, cleanup); - } - throw; - } - } - } - - private PreparedSourceMounts PrepareSourceMountCatalog( - AssetLoader activeLoader, - AssetSourceMount[] mounts, - CancellationToken cancellationToken - ) { - AssetCatalogCandidate? catalog = null; - AssetFileSystem? files = null; - try - { - cancellationToken.ThrowIfCancellationRequested(); - catalog = activeLoader.PrepareCatalogCandidate(mounts, m_options.sourcePolicy); - AssetLoader loader = catalog.loader; - files = new AssetFileSystem( - mounts, autoStart: false, m_options.fileWatcherFlushDelayMs, m_options.sourcePolicy, - requireWritableProject: true, m_identities, - persistentIdentityResolver: path => loader.TryGetPersistentId(path, out Guid id) ? id : null, - activateIdentities: false); - loader.Rescan(cancellationToken); - files.Refresh(); - cancellationToken.ThrowIfCancellationRequested(); - return new PreparedSourceMounts(mounts, catalog, files); - } - catch (Exception failure) - { - try - { - RetireSourcePreparation(catalog, files); - } - catch (Exception cleanup) - { - throw new AggregateException("Asset source preparation and retirement failed.", failure, cleanup); - } - throw; - } - } - - private AssetSourceMountTransaction AdoptSourceMountCatalog( - PreparedSourceMounts prepared, - IReadOnlyList recovery - ) { - EnsureInitializationThread(); - if (m_sourceMountCandidate is not null) - throw new InvalidOperationException("Another source-mount candidate is already pending."); - var transaction = new AssetSourceMountTransaction( - this, prepared.mounts, prepared.catalog, prepared.files, recovery, Math.Max(1, m_revision + 1)); - m_sourceMountCandidate = transaction; - return transaction; - } - - private void DiscardSourceMountCatalog(PreparedSourceMounts prepared) - => RetireSourcePreparation(prepared.catalog, prepared.files); - - private void RetireSourcePreparation( - AssetCatalogCandidate? catalog, - AssetFileSystem? files - ) { - var resources = new LifetimeScope(); - if (catalog is not null) - { - resources.Own(catalog); - resources.Own(catalog.loader); - } - if (files is not null) - resources.Own(files); - try - { - Retire(resources, new RetirementBarrier("Asset source preparation")); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - lock (m_lifecycleLock) - m_failedPreparation = resources; - throw; - } - } - - internal sealed record PreparedSourceMounts( - AssetSourceMount[] mounts, - AssetCatalogCandidate catalog, - AssetFileSystem files - ); - /// /// Validates and atomically replaces the complete source-mount generation while preserving the active /// generation after any candidate failure. @@ -185,7 +65,9 @@ internal void ActivatePreparedSourceMounts(AssetSourceMountTransaction transacti { EnsurePendingSourceMountTransaction(transaction); if (transaction.isActivated) + { return; + } transaction.candidateLoader.ActivateExtensionDiscovery(); _ = transaction.candidateLoader.RefreshRegistries(); transaction.candidateFileSystem.Refresh(); @@ -193,14 +75,19 @@ internal void ActivatePreparedSourceMounts(AssetSourceMountTransaction transacti transaction.previousFileSystem = m_fileSystem; transaction.previousMounts = sourceMounts; transaction.previousOptions = m_options; - SwitchSourceIdentities(transaction.previousLoader!, transaction.previousFileSystem!, - transaction.candidateLoader, transaction.candidateFileSystem); - transaction.candidateLoader.AssetReloaded += OnAssetReloaded; + SwitchSourceIdentities( + transaction.previousLoader!, + transaction.previousFileSystem!, + transaction.candidateLoader, + transaction.candidateFileSystem + ); + transaction.candidateLoader.assetReloaded += OnAssetReloaded; m_loader = transaction.candidateLoader; m_fileSystem = transaction.candidateFileSystem; sourceMounts = transaction.sourceMounts; AssetSourceMount project = transaction.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceID.project + ); assetRoot = project.rootPath; m_options = m_options with { assetRoot = assetRoot, sourceMounts = transaction.sourceMounts }; m_revision++; @@ -219,12 +106,16 @@ internal void CompletePreparedSourceMounts(AssetSourceMountTransaction transacti m_generations.EnsureRetirementSafe(); EnsurePendingSourceMountTransaction(transaction); if (!transaction.isActivated) + { throw new InvalidOperationException("A source-mount candidate must be activated before completion."); + } try { transaction.catalogCandidate.Commit(); if (m_options.enableFileSystemWatcher) + { transaction.candidateFileSystem.Start(); + } } catch (Exception failure) { @@ -235,13 +126,15 @@ internal void CompletePreparedSourceMounts(AssetSourceMountTransaction transacti transaction.retirement.Own(transaction.catalogCandidate); if (transaction.previousLoader is not null) { - transaction.previousLoader.AssetReloaded -= OnAssetReloaded; + transaction.previousLoader.assetReloaded -= OnAssetReloaded; transaction.retirement.Own(transaction.previousLoader); } if (transaction.previousFileSystem is not null) + { transaction.retirement.Own(transaction.previousFileSystem); + } RetireSourceMounts(transaction); - changed = SourceMountsChanged; + changed = sourceMountsChanged; } InvokeObservers(changed); } @@ -250,7 +143,9 @@ internal void RollbackPreparedSourceMounts(AssetSourceMountTransaction transacti { ArgumentNullException.ThrowIfNull(transaction); if (transaction.isFinished) + { return; + } EnsureInitializationThread(); using IDisposable operationScope = AcquireOperation(); lock (m_lifecycleLock) @@ -259,15 +154,20 @@ internal void RollbackPreparedSourceMounts(AssetSourceMountTransaction transacti EnsurePendingSourceMountTransaction(transaction); if (transaction.isActivated) { - transaction.candidateLoader.AssetReloaded -= OnAssetReloaded; - SwitchSourceIdentities(transaction.candidateLoader, transaction.candidateFileSystem, - transaction.previousLoader!, transaction.previousFileSystem!); + transaction.candidateLoader.assetReloaded -= OnAssetReloaded; + SwitchSourceIdentities( + transaction.candidateLoader, + transaction.candidateFileSystem, + transaction.previousLoader!, + transaction.previousFileSystem! + ); m_loader = transaction.previousLoader; m_fileSystem = transaction.previousFileSystem; sourceMounts = transaction.previousMounts ?? []; m_options = transaction.previousOptions; AssetSourceMount? project = sourceMounts.SingleOrDefault( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceID.project + ); assetRoot = project?.rootPath ?? string.Empty; m_revision++; transaction.isActivated = false; @@ -280,6 +180,144 @@ internal void RollbackPreparedSourceMounts(AssetSourceMountTransaction transacti } } + private AssetSourceMountTransaction PrepareSourceMountsCore(IReadOnlyList mounts) + { + using IDisposable operationScope = AcquireOperation(); + lock (m_lifecycleLock) + { + m_generations.EnsureRetirementSafe(); + if (m_failedPreparation is not null || m_shutdown is not null) + { + throw new InvalidOperationException("The Asset Pipeline is retiring and cannot prepare a source candidate."); + } + if (m_sourceMountCandidate is not null) + { + throw new InvalidOperationException("Another source-mount candidate is already pending."); + } + AssetSourceMount[] snapshot = mounts.ToArray(); + AssetSourceMount projectMount = snapshot.SingleOrDefault(static mount => mount.id == AssetSourceID.project) + ?? throw new ArgumentException("A project asset source mount is required.", nameof(mounts)); + if (projectMount.isReadOnly) + { + throw new ArgumentException("The project asset source mount must be writable.", nameof(mounts)); + } + if (snapshot.Select(static mount => mount.id).Distinct().Count() != snapshot.Length) + { + throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } + PreparedSourceMounts prepared = PrepareSourceMountCatalog(GetLoader(), snapshot, CancellationToken.None); + try + { + return AdoptSourceMountCatalog(prepared, GetLoader().CaptureRecoveryStates()); + } + catch (Exception failure) + { + try + { + DiscardSourceMountCatalog(prepared); + } + catch (Exception cleanup) + { + throw new AggregateException("Asset source adoption and retirement failed.", failure, cleanup); + } + throw; + } + } + } + + private PreparedSourceMounts PrepareSourceMountCatalog( + AssetLoader activeLoader, + AssetSourceMount[] mounts, + CancellationToken cancellationToken + ) { + AssetCatalogCandidate? catalog = null; + AssetFileSystem? files = null; + try + { + cancellationToken.ThrowIfCancellationRequested(); + catalog = activeLoader.PrepareCatalogCandidate(mounts, m_options.sourcePolicy); + AssetLoader loader = catalog.loader; + files = new AssetFileSystem( + mounts, + autoStart: false, + m_options.fileWatcherFlushDelayMs, + m_options.sourcePolicy, + requireWritableProject: true, + m_identities, + persistentIdentityResolver: path => loader.TryGetPersistentID(path, out Guid id) ? id : null, + activateIdentities: false + ); + loader.Rescan(cancellationToken); + files.Refresh(); + cancellationToken.ThrowIfCancellationRequested(); + return new PreparedSourceMounts(mounts, catalog, files); + } + catch (Exception failure) + { + try + { + RetireSourcePreparation(catalog, files); + } + catch (Exception cleanup) + { + throw new AggregateException("Asset source preparation and retirement failed.", failure, cleanup); + } + throw; + } + } + + private AssetSourceMountTransaction AdoptSourceMountCatalog( + PreparedSourceMounts prepared, + IReadOnlyList recovery + ) { + EnsureInitializationThread(); + if (m_sourceMountCandidate is not null) + { + throw new InvalidOperationException("Another source-mount candidate is already pending."); + } + var transaction = new AssetSourceMountTransaction( + this, + prepared.mounts, + prepared.catalog, + prepared.files, + recovery, + Math.Max(1, m_revision + 1) + ); + m_sourceMountCandidate = transaction; + return transaction; + } + + private void DiscardSourceMountCatalog(PreparedSourceMounts prepared) + => RetireSourcePreparation(prepared.catalog, prepared.files); + + private void RetireSourcePreparation( + AssetCatalogCandidate? catalog, + AssetFileSystem? files + ) { + var resources = new LifetimeScope(); + if (catalog is not null) + { + resources.Own(catalog); + resources.Own(catalog.loader); + } + if (files is not null) + { + resources.Own(files); + } + try + { + Retire(resources, new RetirementBarrier("Asset source preparation")); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + lock (m_lifecycleLock) + { + m_failedPreparation = resources; + } + throw; + } + } + private void RetireSourceMounts(AssetSourceMountTransaction transaction) { try @@ -327,7 +365,9 @@ private void DeleteCandidateCatalogRoots(string activeLibraryRoot) { string root = Path.Combine(activeLibraryRoot, "AssetDatabase", "Candidates"); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } private void SwitchSourceIdentities( @@ -370,7 +410,10 @@ AssetFileSystem candidateFiles } if (failures.Count > 1) { - var aggregate = new AggregateException("Asset identity publication could not restore its previous domain.", failures); + var aggregate = new AggregateException( + "Asset identity publication could not restore its previous domain.", + failures + ); m_generations.Fault(aggregate); throw aggregate; } @@ -389,6 +432,14 @@ Action compensate private void EnsurePendingSourceMountTransaction(AssetSourceMountTransaction transaction) { if (!ReferenceEquals(m_sourceMountCandidate, transaction)) + { throw new InvalidOperationException("The source-mount transaction is not the current candidate."); + } } + + internal sealed record PreparedSourceMounts( + AssetSourceMount[] mounts, + AssetCatalogCandidate catalog, + AssetFileSystem files + ); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs index 985a9a868..50e02e61e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -13,7 +12,7 @@ public static class AssetSample /// /// Gets the logical File Browser type used for a sample directory. /// - public const string fileType = ".isample"; + public const string C_FILE_TYPE = ".isample"; /// /// Determines whether the final path segment uses the sample-directory naming convention. @@ -28,7 +27,9 @@ public static class AssetSample public static bool HasSampleDirectoryName(AssetPath path) { if (!path.isValid || string.IsNullOrEmpty(path.localPath)) + { return false; + } return Path.GetFileName(path.localPath).StartsWith('~'); } @@ -43,10 +44,7 @@ public static bool HasSampleDirectoryName(AssetPath path) /// segment starts with ~. A Project directory with the same name remains normal writable /// authoring content. /// - public static bool IsRoot(AssetPath path) - { - return path.source != AssetSourceId.project && HasSampleDirectoryName(path); - } + public static bool IsRoot(AssetPath path) => path.source != AssetSourceID.project && HasSampleDirectoryName(path); /// /// Determines whether a source path is a sample directory or is contained by one. @@ -64,9 +62,7 @@ public static bool IsRoot(AssetPath path) public static bool Contains( AssetPath path, bool isDirectory - ) { - return path.source != AssetSourceId.project && ContainsTildeDirectory(path, isDirectory); - } + ) => path.source != AssetSourceID.project && ContainsTildeDirectory(path, isDirectory); /// /// Gets the original sample directory name for a writable Project copy. @@ -84,10 +80,14 @@ bool isDirectory public static string GetImportName(AssetPath path) { if (!IsRoot(path)) + { throw new ArgumentException("The path must identify an installed Plugin sample directory.", nameof(path)); + } string name = Path.GetFileName(path.localPath); if (string.IsNullOrWhiteSpace(name.TrimStart('~'))) + { throw new ArgumentException("A sample directory requires a name after its '~' prefix.", nameof(path)); + } return name; } @@ -115,13 +115,17 @@ private static bool ContainsTildeDirectory( bool isDirectory ) { if (!path.isValid || string.IsNullOrEmpty(path.localPath)) + { return false; + } string[] segments = path.localPath.Split('/', StringSplitOptions.RemoveEmptyEntries); int directoryCount = isDirectory ? segments.Length : segments.Length - 1; for (int index = 0; index < directoryCount; index++) { if (segments[index].StartsWith('~')) + { return true; + } } return false; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs index 84b602c41..2a70ed423 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; +using System.IO; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; @@ -53,7 +53,9 @@ IAssetSampleSourceRewriter[] rewriters foreach (IAssetSampleSourceRewriter rewriter in rewriters) { if (rewriter is IDisposable disposable) + { m_preparationResources.Own(disposable); + } } m_preparation = m_lifetime.RunAsync(async cancellationToken => { @@ -62,16 +64,27 @@ IAssetSampleSourceRewriter[] rewriters return await Task.Run(() => { List entries = AssetSampleSnapshot.Capture( - absoluteSource, stagedSource, target.localPath, policy, cancellationToken); + absoluteSource, + stagedSource, + target.localPath, + policy, + cancellationToken + ); AssetSampleSnapshot.RemapIdentities( - stagedSource, source, target, serialization, context => + stagedSource, + source, + target, + serialization, + context => { foreach (IAssetSampleSourceRewriter rewriter in rewriters) { cancellationToken.ThrowIfCancellationRequested(); rewriter.Transform(context); } - }, cancellationToken); + }, + cancellationToken + ); return new Preparation(entries, null); }, cancellationToken).ConfigureAwait(false); } @@ -115,14 +128,20 @@ public bool Advance() EnsureOpen(); m_owner.EnsureSampleImportOwner(this); if (isIndexed) + { return true; + } Task preparation = m_preparation!; if (!preparation.IsCompleted) + { return false; + } Preparation outcome = preparation.GetAwaiter().GetResult(); m_preparationResources.Dispose(); if (outcome.failure is not null) + { ExceptionDispatchInfo.Capture(outcome.failure).Throw(); + } entries = outcome.entries; if (m_indexing is null) { @@ -131,7 +150,9 @@ public bool Advance() try { AssetPipeline.PreparedSourceMounts prepared = await m_owner.PrepareSampleCatalogAsync( - this, cancellationToken).ConfigureAwait(false); + this, + cancellationToken + ).ConfigureAwait(false); return new Indexing(prepared, null); } catch (Exception failure) @@ -143,10 +164,14 @@ public bool Advance() return false; } if (!m_indexing.IsCompleted) + { return false; + } Indexing indexed = m_indexing.GetAwaiter().GetResult(); if (indexed.failure is not null) + { ExceptionDispatchInfo.Capture(indexed.failure).Throw(); + } m_owner.AdoptSampleCatalog(this, indexed.prepared!); isIndexed = true; return true; @@ -170,7 +195,9 @@ public void BeginValidation(Func(async cancellationToken => { try @@ -205,10 +232,14 @@ public void Commit(Action? beforePublish = null) EnsureOpen(); m_owner.EnsureSampleImportOwner(this); if (!isValidationComplete) + { throw new InvalidOperationException("Sample validation has not completed."); + } Exception? failure = m_validation!.GetAwaiter().GetResult(); if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } m_lifetime.cancellationToken.ThrowIfCancellationRequested(); m_owner.CommitSampleImport(this, beforePublish); } @@ -230,7 +261,9 @@ public void Commit(Action? beforePublish = null) public void Rollback() { if (m_finished) + { return; + } m_owner.EnsureSampleImportOwner(this); Cancel(); try @@ -238,20 +271,26 @@ public void Rollback() if (!m_retirement.TryComplete(() => { if (!m_lifetime.isQuiescent) + { throw new RetirementPendingException("Sample import work must drain before rollback releases its generation."); + } if (candidate is null && m_indexing is { IsCompletedSuccessfully: true }) { Indexing indexed = m_indexing.GetAwaiter().GetResult(); if (indexed.prepared is not null) + { m_owner.DiscardSampleCatalog(indexed.prepared); + } m_indexing = null; } m_owner.RollbackSampleImport(this); - })) + }) + ) { throw new RetirementPendingException("Sample import retirement is waiting for canceled work."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not RetirementTimeoutException - && RetirementPendingException.Find(pending) is not null) + && RetirementPendingException.Find(pending) is not null) { throw; } @@ -273,7 +312,7 @@ public void Rollback() internal IReadOnlyList recovery { get; set; } = []; internal AssetSourceMountTransaction? candidate { get; set; } internal string transactionRoot { get; } - internal string stagedSource => System.IO.Path.Combine(transactionRoot, "sample"); + internal string stagedSource => Path.Combine(transactionRoot, "sample"); internal List entries { get; private set; } = []; internal bool isIndexed { get; private set; } internal bool sourceMoved { get; set; } @@ -309,23 +348,31 @@ internal bool TryCleanPrivateCopy() } }); if (!m_cleanup.IsCompleted) + { return false; + } Exception? failure = m_cleanup.GetAwaiter().GetResult(); if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } return true; } private void EnsureOpen() { if (m_finished) + { throw new InvalidOperationException("The sample import transaction is finished."); + } } private void EnsureFailureDrained(Exception failure) { if (RetirementPendingException.Find(failure) is null) + { return; + } // A completed task reporting pending ownership must stay retained by the Core lifetime. m_owner.FaultSampleImport(failure); ExceptionDispatchInfo.Capture(failure).Throw(); @@ -346,15 +393,15 @@ out AssetInfo? info ) => candidate.TryGetInfo(path, out info); ArtifactLease IAssetArtifactLookup.AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName - ) => candidate.AcquireArtifact(persistentId, outputName); + ) => candidate.AcquireArtifact(persistentID, outputName); bool IAssetArtifactLookup.TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact - ) => candidate.TryGetArtifact(persistentId, outputName, out artifact); + ) => candidate.TryGetArtifact(persistentID, outputName, out artifact); } private sealed record Indexing( diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs index 5f2a22d9f..2950f60df 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs @@ -21,7 +21,9 @@ CancellationToken cancellationToken List copied = CopyDirectory(source, target, targetLocalPath, sourcePolicy, cancellationToken); string sourceMeta = source + ".imeta"; if (File.Exists(sourceMeta)) + { CopyStableFile(sourceMeta, target + ".imeta", cancellationToken); + } return copied; } @@ -35,45 +37,65 @@ CancellationToken cancellationToken ) { var identities = new Dictionary(); var paths = new Dictionary(StringComparer.Ordinal); - var sourceIdentities = new Dictionary(StringComparer.Ordinal); + var sourceIdentities = new Dictionary(StringComparer.Ordinal); string[] metadata = Directory.GetFiles(stagedSource, "*.imeta", SearchOption.AllDirectories); if (File.Exists(stagedSource + ".imeta")) + { metadata = [.. metadata, stagedSource + ".imeta"]; + } foreach (string path in metadata.Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); AssetSourceMeta meta = serialization.Deserialize(File.ReadAllBytes(path)); if (meta.persistentId == Guid.Empty) + { throw new InvalidDataException($"Sample metadata '{path}' has no persistent identity."); + } if (!identities.TryAdd(meta.persistentId, Guid.NewGuid())) + { throw new InvalidDataException($"Sample contains duplicate persistent identity '{meta.persistentId:D}'."); - Guid oldId = meta.persistentId; - meta.persistentId = identities[oldId]; + } + Guid oldID = meta.persistentId; + meta.persistentId = identities[oldID]; File.WriteAllBytes(path, serialization.Serialize(meta)); string relative = Path.GetRelativePath(stagedSource, path); string suffix = string.Equals(path, stagedSource + ".imeta", StringComparison.Ordinal) - ? string.Empty - : relative[..^".imeta".Length].Replace('\\', '/'); - sourceIdentities.Add(suffix, (oldId, meta.persistentId)); + ? string.Empty + : relative[..^".imeta".Length].Replace('\\', '/'); + sourceIdentities.Add(suffix, (oldID, meta.persistentId)); string oldLocal = string.IsNullOrEmpty(suffix) - ? source.localPath : source.localPath + "/" + suffix; + ? source.localPath + : source.localPath + "/" + suffix; string newLocal = string.IsNullOrEmpty(suffix) - ? target.localPath : target.localPath + "/" + suffix; + ? target.localPath + : target.localPath + "/" + suffix; paths[new AssetPath(source.source, oldLocal).ToString()] = newLocal; paths[oldLocal] = newLocal; } - transform(new AssetSampleTransformContext( - stagedSource, source, target, identities, sourceIdentities, cancellationToken)); + transform( + new AssetSampleTransformContext( + stagedSource, + source, + target, + identities, + sourceIdentities, + cancellationToken + ) + ); IEnumerable stagedFiles = Directory.GetFiles(stagedSource, "*", SearchOption.AllDirectories); if (File.Exists(stagedSource + ".imeta")) + { stagedFiles = stagedFiles.Append(stagedSource + ".imeta"); + } foreach (string path in stagedFiles) { cancellationToken.ThrowIfCancellationRequested(); byte[] original = File.ReadAllBytes(path); byte[] rewritten = SerializedIdentityRemapper.Rewrite(original, identities, paths); if (!original.AsSpan().SequenceEqual(rewritten)) + { File.WriteAllBytes(path, rewritten); + } } } @@ -95,25 +117,30 @@ CancellationToken cancellationToken .Where(path => ShouldCopyFile(path, sourcePolicy)) .Order(StringComparer.Ordinal) .ToArray(); - var copied = new List(); + List copied = []; for (int index = 0; index < directories.Length; index++) { string name = Path.GetFileName(directories[index]); string childLocalPath = targetLocalPath + "/" + name; copied.Add(childLocalPath); - copied.AddRange(CopyDirectory( - directories[index], - Path.Combine(target, name), - childLocalPath, - sourcePolicy, - cancellationToken)); + copied.AddRange( + CopyDirectory( + directories[index], + Path.Combine(target, name), + childLocalPath, + sourcePolicy, + cancellationToken + ) + ); } for (int index = 0; index < files.Length; index++) { string name = Path.GetFileName(files[index]); CopyStableFile(files[index], Path.Combine(target, name), cancellationToken); if (!AssetSourcePolicy.IsGeneratedPath(name)) + { copied.Add(targetLocalPath + "/" + name); + } } string[] currentDirectories = Directory.GetDirectories(source) @@ -124,9 +151,9 @@ CancellationToken cancellationToken .Where(path => ShouldCopyFile(path, sourcePolicy)) .Order(StringComparer.Ordinal) .ToArray(); - if (!directories.SequenceEqual(currentDirectories, StringComparer.Ordinal) || - !files.SequenceEqual(currentFiles, StringComparer.Ordinal)) - { + if (!directories.SequenceEqual(currentDirectories, StringComparer.Ordinal) + || !files.SequenceEqual(currentFiles, StringComparer.Ordinal) + ) { throw new IOException($"Sample source '{source}' changed while it was being imported."); } return copied; @@ -138,9 +165,13 @@ AssetSourcePolicy sourcePolicy ) { string name = Path.GetFileName(path); if (name.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + { return true; + } if (name.EndsWith(".abin", StringComparison.OrdinalIgnoreCase)) + { return false; + } return !sourcePolicy.IsIgnored(name, isDirectory: false); } @@ -150,14 +181,14 @@ private static void CopyStableFile( CancellationToken cancellationToken ) { EnsureRegularFile(source); - FileInfo before = new(source); + var before = new FileInfo(source); long beforeLength = before.Length; DateTime beforeWriteTime = before.LastWriteTimeUtc; Directory.CreateDirectory(Path.GetDirectoryName(target)!); using (FileStream input = File.OpenRead(source)) - using (FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { - byte[] buffer = new byte[81920]; + var buffer = new byte[81_920]; int count; while ((count = input.Read(buffer)) != 0) { @@ -166,13 +197,17 @@ CancellationToken cancellationToken } } EnsureRegularFile(source); - FileInfo after = new(source); + var after = new FileInfo(source); if (after.Length != beforeLength || after.LastWriteTimeUtc != beforeWriteTime) + { throw new IOException($"Sample source file '{source}' changed while it was being imported."); + } byte[] sourceHash = HashFile(source, cancellationToken); byte[] targetHash = HashFile(target, cancellationToken); if (!sourceHash.AsSpan().SequenceEqual(targetHash)) + { throw new IOException($"Sample source file '{source}' changed while it was being imported."); + } } private static byte[] HashFile( @@ -181,7 +216,7 @@ CancellationToken cancellationToken ) { using FileStream stream = File.OpenRead(path); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - byte[] buffer = new byte[81920]; + var buffer = new byte[81_920]; int count; while ((count = stream.Read(buffer)) != 0) { @@ -194,16 +229,24 @@ CancellationToken cancellationToken private static void EnsureRegularDirectory(string path) { if (!Directory.Exists(path)) + { throw new DirectoryNotFoundException($"Sample directory '{path}' does not exist."); + } if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Sample directory '{path}' cannot be a symbolic link."); + } } private static void EnsureRegularFile(string path) { if (!File.Exists(path)) + { throw new FileNotFoundException("Sample source file does not exist.", path); + } if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Sample source file '{path}' cannot be a symbolic link."); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs new file mode 100644 index 000000000..417574f33 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Registers a source-language sample transformer through the reloadable type catalog. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetSampleSourceRewriterAttribute : Attribute +{ + /// + /// Creates one ordered source-language transformer declaration. + /// + /// + /// Stable extension identity used for diagnostics and ordering. + /// + public AssetSampleSourceRewriterAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the stable extension identity. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs similarity index 58% rename from src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs rename to src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs index f9ceb4a48..53cec08e5 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Threading; -using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -12,14 +11,14 @@ namespace Inno.Assets.Pipeline; public sealed class AssetSampleTransformContext { private readonly Dictionary m_identityMap; - private readonly IReadOnlyDictionary m_sourceIdentities; + private readonly IReadOnlyDictionary m_sourceIdentities; internal AssetSampleTransformContext( string stagedRoot, AssetPath source, AssetPath target, Dictionary identityMap, - IReadOnlyDictionary sourceIdentities, + IReadOnlyDictionary sourceIdentities, CancellationToken cancellationToken ) { this.stagedRoot = stagedRoot; @@ -61,10 +60,10 @@ CancellationToken cancellationToken /// /// Slash-separated source-local file path below the sample directory. /// - /// + /// /// Receives the installed source identity. /// - /// + /// /// Receives the writable clone identity. /// /// @@ -72,83 +71,45 @@ CancellationToken cancellationToken /// public bool TryGetSourceIdentity( string relativePath, - out Guid oldId, - out Guid newId + out Guid oldID, + out Guid newID ) { ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); - if (m_sourceIdentities.TryGetValue(relativePath.Replace('\\', '/'), out var pair)) + if (m_sourceIdentities.TryGetValue(relativePath.Replace('\\', '/'), out (Guid oldID, Guid newID) pair)) { - oldId = pair.oldId; - newId = pair.newId; + oldID = pair.oldID; + newID = pair.newID; return true; } - oldId = default; - newId = default; + oldID = default; + newID = default; return false; } /// /// Registers one source-language type replacement for subsequent structured asset rewriting. /// - /// + /// /// The type identity stored in installed sample assets. /// - /// + /// /// The type identity declared by the cloned source. /// /// /// A source identity is reused inconsistently. /// public void MapType( - Guid oldId, - Guid newId + Guid oldID, + Guid newID ) { - if (oldId == Guid.Empty || newId == Guid.Empty) + if (oldID == Guid.Empty || newID == Guid.Empty) + { throw new ArgumentException("Sample type identities must be non-empty."); - if (m_identityMap.TryGetValue(oldId, out Guid existing) && existing != newId) - throw new InvalidDataException($"Sample type identity '{oldId:D}' has conflicting clone mappings."); - m_identityMap[oldId] = newId; - } -} - -/// -/// Rewrites a source language in a private sample clone before source assets are published. -/// -public interface IAssetSampleSourceRewriter -{ - /// - /// Rewrites staged source files and registers any changed serialized type identities. - /// - /// - /// Runs on a worker with a pinned extension generation. Access only transaction-owned files - /// and context data, observe cancellation, and do not access live Assets or Editor state. - /// - /// - /// The transaction-owned staged clone. - /// - void Transform(AssetSampleTransformContext context); -} - -/// -/// Registers a source-language sample transformer through the reloadable type catalog. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetSampleSourceRewriterAttribute : Attribute -{ - /// - /// Creates one ordered source-language transformer declaration. - /// - /// - /// Stable extension identity used for diagnostics and ordering. - /// - public AssetSampleSourceRewriterAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; + } + if (m_identityMap.TryGetValue(oldID, out Guid existing) && existing != newID) + { + throw new InvalidDataException($"Sample type identity '{oldID:D}' has conflicting clone mappings."); + } + m_identityMap[oldID] = newID; } - - /// - /// Gets the stable extension identity. - /// - public string id { get; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs index f7e5528b1..f56db4fe3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.IO; using System.Linq; using Inno.Assets; @@ -29,18 +29,20 @@ public sealed class AssetSourceMount /// Other read-only sources this source may reference. /// public AssetSourceMount( - AssetSourceId id, + AssetSourceID id, string rootPath, bool isReadOnly, - IEnumerable? dependencies = null + IEnumerable? dependencies = null ) { if (!id.isValid) + { throw new ArgumentException("An asset source ID must be valid.", nameof(id)); + } ArgumentException.ThrowIfNullOrWhiteSpace(rootPath); this.id = id; this.rootPath = Path.GetFullPath(rootPath); this.isReadOnly = isReadOnly; - dependencySourceIds = (dependencies ?? []) + this.dependencySourceIDs = (dependencies ?? []) .Where(dependency => dependency.isValid && dependency != id) .ToFrozenSet(); } @@ -48,7 +50,7 @@ public AssetSourceMount( /// /// Gets the stable source identity. /// - public AssetSourceId id { get; } + public AssetSourceID id { get; } /// /// Gets the controlled physical source root. @@ -63,7 +65,7 @@ public AssetSourceMount( /// /// Gets explicitly declared cross-source dependencies. /// - public IReadOnlySet dependencySourceIds { get; } + public IReadOnlySet dependencySourceIDs { get; } /// /// Resolves a source-local path and rejects physical root escape. @@ -76,7 +78,7 @@ public AssetSourceMount( /// public string Resolve(string localPath) { - AssetPath path = new(id, localPath); + var path = new AssetPath(id, localPath); try { return PathBoundary.Resolve(rootPath, path.localPath); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs index 243eaabd5..980305b81 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs @@ -10,7 +10,7 @@ namespace Inno.Assets.Pipeline; /// public sealed class AssetSourcePolicy { - private static readonly string[] S_DEFAULT_FILE_NAMES = + private static readonly string[] DEFAULT_FILE_NAMES = [ ".DS_Store", ".directory", @@ -20,7 +20,7 @@ public sealed class AssetSourcePolicy "Thumbs.db" ]; - private static readonly string[] S_DEFAULT_DIRECTORY_NAMES = + private static readonly string[] DEFAULT_DIRECTORY_NAMES = [ ".git", ".hg", @@ -33,8 +33,9 @@ public sealed class AssetSourcePolicy "obj" ]; - private static readonly string[] S_DEFAULT_PREFIXES = [".#", "._", "~$"]; - private static readonly string[] S_DEFAULT_SUFFIXES = + private static readonly string[] DEFAULT_PREFIXES = [".#", "._", "~$"]; + + private static readonly string[] DEFAULT_SUFFIXES = [".bak", ".deps.json", ".orig", ".pdb", ".swo", ".swp", ".temp", ".tmp", "~"]; private readonly HashSet m_fileNames; @@ -46,9 +47,7 @@ public sealed class AssetSourcePolicy /// Creates a source policy using the engine's default noise filters. /// public AssetSourcePolicy() - : this(null, null, null, null) - { - } + : this(null, null, null, null) {} /// /// Creates a source policy with additional ignored names and affixes. @@ -71,12 +70,12 @@ public AssetSourcePolicy( IEnumerable? ignoredPrefixes, IEnumerable? ignoredSuffixes ) { - m_fileNames = new HashSet(S_DEFAULT_FILE_NAMES, StringComparer.OrdinalIgnoreCase); - m_directoryNames = new HashSet(S_DEFAULT_DIRECTORY_NAMES, StringComparer.OrdinalIgnoreCase); + m_fileNames = new HashSet(DEFAULT_FILE_NAMES, StringComparer.OrdinalIgnoreCase); + m_directoryNames = new HashSet(DEFAULT_DIRECTORY_NAMES, StringComparer.OrdinalIgnoreCase); AddNonEmpty(m_fileNames, ignoredFileNames); AddNonEmpty(m_directoryNames, ignoredDirectoryNames); - m_prefixes = Combine(S_DEFAULT_PREFIXES, ignoredPrefixes); - m_suffixes = Combine(S_DEFAULT_SUFFIXES, ignoredSuffixes); + m_prefixes = Combine(DEFAULT_PREFIXES, ignoredPrefixes); + m_suffixes = Combine(DEFAULT_SUFFIXES, ignoredSuffixes); } /// @@ -102,20 +101,30 @@ bool isDirectory ) { string name = Path.GetFileName(relativePath); if (string.IsNullOrEmpty(name)) + { return false; + } if (isDirectory && m_directoryNames.Contains(name)) + { return true; + } if (!isDirectory && (m_fileNames.Contains(name) || IsGeneratedPath(name) || AtomicFile.IsCandidatePath(name))) + { return true; + } for (int i = 0; i < m_prefixes.Length; i++) { if (name.StartsWith(m_prefixes[i], StringComparison.OrdinalIgnoreCase)) + { return true; + } } for (int i = 0; i < m_suffixes.Length; i++) { if (name.EndsWith(m_suffixes[i], StringComparison.OrdinalIgnoreCase)) + { return true; + } } return false; } @@ -130,19 +139,23 @@ bool isDirectory /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool IsGeneratedPath(string relativePath) - => relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) || - relativePath.EndsWith(".abin", StringComparison.OrdinalIgnoreCase); + => relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + || relativePath.EndsWith(".abin", StringComparison.OrdinalIgnoreCase); private static void AddNonEmpty( HashSet target, IEnumerable? values ) { if (values is null) + { return; + } foreach (string value in values) { if (!string.IsNullOrWhiteSpace(value)) + { target.Add(value.Trim()); + } } } @@ -156,7 +169,9 @@ private static string[] Combine( foreach (string value in additional) { if (!string.IsNullOrWhiteSpace(value)) + { values.Add(value.Trim()); + } } } return values.ToArray(); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs new file mode 100644 index 000000000..697218937 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs @@ -0,0 +1,19 @@ +namespace Inno.Assets.Pipeline; + +/// +/// Rewrites a source language in a private sample clone before source assets are published. +/// +public interface IAssetSampleSourceRewriter +{ + /// + /// Rewrites staged source files and registers any changed serialized type identities. + /// + /// + /// The transaction-owned staged clone. + /// + /// + /// Runs on a worker with a pinned extension generation. Access only transaction-owned files + /// and context data, observe cancellation, and do not access live Assets or Editor state. + /// + void Transform(AssetSampleTransformContext context); +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs index c6d02e17a..33571b922 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -45,7 +44,8 @@ public interface IAssetSourceSnapshot : IAssetArtifactLookup /// /// No compatible asset can be loaded from this view. /// - TAsset Load(AssetPath path) where TAsset : AssetObject; + TAsset Load(AssetPath path) + where TAsset : AssetObject; /// /// Resolves immutable catalog information by source path. @@ -63,5 +63,4 @@ bool TryGetInfo( AssetPath path, out AssetInfo? info ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs index 4110039b8..ea1c73beb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs @@ -11,7 +11,7 @@ namespace Inno.Assets.Pipeline; /// internal sealed class AssetWatcher : IDisposable { - private static readonly TimeSpan S_DEFAULT_IDLE_WAIT_TIMEOUT = TimeSpan.FromSeconds(10); + private static readonly TimeSpan DEFAULT_IDLE_WAIT_TIMEOUT = TimeSpan.FromSeconds(10); private readonly string m_root; private readonly FileSystemWatcher m_watcher; @@ -27,7 +27,8 @@ internal AssetWatcher( string assetRoot, int flushDelayMs ) { - m_root = assetRoot ?? throw new ArgumentNullException(nameof(assetRoot)); + ArgumentNullException.ThrowIfNull(assetRoot); + m_root = assetRoot; m_flushDelayMs = Math.Max(flushDelayMs, 1); m_watcher = new FileSystemWatcher(assetRoot) { @@ -41,6 +42,30 @@ int flushDelayMs m_watcher.Error += OnError; } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + m_watcher.EnableRaisingEvents = false; + m_watcher.Changed -= OnChanged; + m_watcher.Created -= OnChanged; + m_watcher.Deleted -= OnChanged; + m_watcher.Renamed -= OnRenamed; + m_watcher.Error -= OnError; + m_watcher.Dispose(); + lock (m_sync) + { + m_pending.Clear(); + m_requiresFullRescan = false; + } + } + internal bool isWatching => m_watcher.EnableRaisingEvents; internal void Start() @@ -52,7 +77,9 @@ internal void Start() internal void Stop() { if (!m_disposed) + { m_watcher.EnableRaisingEvents = false; + } } internal WatcherPollResult Poll(bool force) @@ -63,7 +90,9 @@ internal WatcherPollResult Poll(bool force) lock (m_sync) { if (!force && m_pending.Count > 0 && !HasQuietPeriodElapsed()) - return new WatcherPollResult(Array.Empty(), false); + { + return new WatcherPollResult([], false); + } raw = m_pending.ToArray(); m_pending.Clear(); requiresFullRescan = m_requiresFullRescan; @@ -82,51 +111,31 @@ internal WatcherPollResult WaitForIdle() lock (m_sync) { if ((m_pending.Count > 0 || m_requiresFullRescan) && HasQuietPeriodElapsed()) - return PollWhileLocked(); - if (m_pending.Count == 0 && - !m_requiresFullRescan && - stopwatch.ElapsedMilliseconds >= Math.Max(m_flushDelayMs * 2L, 50L)) { - return new WatcherPollResult(Array.Empty(), false); + return PollWhileLocked(); + } + if (m_pending.Count == 0 + && !m_requiresFullRescan + && stopwatch.ElapsedMilliseconds >= Math.Max(m_flushDelayMs * 2L, 50L) + ) { + return new WatcherPollResult([], false); } } - if (stopwatch.Elapsed > S_DEFAULT_IDLE_WAIT_TIMEOUT) + if (stopwatch.Elapsed > DEFAULT_IDLE_WAIT_TIMEOUT) + { throw new TimeoutException("Timed out waiting for AssetWatcher to become idle."); + } Thread.Sleep(Math.Min(m_flushDelayMs, 20)); } } - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - m_watcher.EnableRaisingEvents = false; - m_watcher.Changed -= OnChanged; - m_watcher.Created -= OnChanged; - m_watcher.Deleted -= OnChanged; - m_watcher.Renamed -= OnRenamed; - m_watcher.Error -= OnError; - m_watcher.Dispose(); - lock (m_sync) - { - m_pending.Clear(); - m_requiresFullRescan = false; - } - } - private WatcherPollResult PollWhileLocked() { AssetChangedEvent[] raw = m_pending.ToArray(); m_pending.Clear(); bool requiresFullRescan = m_requiresFullRescan; m_requiresFullRescan = false; - return new WatcherPollResult( - AssetChangeBatchNormalizer.Normalize(m_root, raw), - requiresFullRescan); + return new WatcherPollResult(AssetChangeBatchNormalizer.Normalize(m_root, raw), requiresFullRescan); } private bool HasQuietPeriodElapsed() @@ -155,7 +164,9 @@ ErrorEventArgs args lock (m_sync) { if (m_disposed) + { return; + } m_requiresFullRescan = true; m_lastEventTimestamp = Stopwatch.GetTimestamp(); } @@ -167,25 +178,27 @@ private void Enqueue( string oldRelativePath = "" ) { if (m_disposed) + { return; + } string relativePath = NormalizeRelativePath(Path.GetRelativePath(m_root, fullPath)); - if (AssetSourcePolicy.IsGeneratedPath(relativePath) && - !relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + if (AssetSourcePolicy.IsGeneratedPath(relativePath) + && !relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + ) { return; + } lock (m_sync) { if (m_disposed) + { return; + } m_pending.Add(new AssetChangedEvent(relativePath, changeType, oldRelativePath)); m_lastEventTimestamp = Stopwatch.GetTimestamp(); } } - private void ThrowIfDisposed() - { - if (m_disposed) - throw new ObjectDisposedException(nameof(AssetWatcher)); - } + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); private static string NormalizeRelativePath(string relativePath) { @@ -193,11 +206,3 @@ private static string NormalizeRelativePath(string relativePath) return path == "." ? string.Empty : path; } } - -internal readonly struct WatcherPollResult( - IReadOnlyList changes, - bool requiresFullRescan -) { - internal IReadOnlyList changes { get; } = changes ?? Array.Empty(); - internal bool requiresFullRescan { get; } = requiresFullRescan; -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs new file mode 100644 index 000000000..6c5d34692 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace Inno.Assets.Pipeline; + +internal readonly struct WatcherPollResult( + IReadOnlyList changes, + bool requiresFullRescan +) { + internal IReadOnlyList changes { get; } = changes ?? []; + internal bool requiresFullRescan { get; } = requiresFullRescan; +} diff --git a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs index 811ce2596..2aa2d083a 100644 --- a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs +++ b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; +using System.Threading; using Inno.Core.IO; namespace Inno.Assets; @@ -20,32 +21,22 @@ public sealed class ArtifactRetention : AssetResidencyProvider /// /// Verified immutable metadata; the provider must serialize acquisition with collection. /// - /// - /// A lease that releases exactly one reference, including when disposed from another thread. - /// /// /// Opens immutable bytes; this retention owner adds an independent stream pin before invoking it. /// + /// + /// A lease that releases exactly one reference, including when disposed from another thread. + /// public ArtifactLease Retain( AssetArtifactInfo artifact, Func openRead - ) - { + ) { ArgumentNullException.ThrowIfNull(artifact); ArgumentNullException.ThrowIfNull(openRead); AddPin(artifact.key); return CreateArtifactLease(artifact, () => OpenPinned(artifact.key, openRead), () => Release(artifact.key)); } - private void AddPin(AssetArtifactKey key) - { - lock (m_sync) - { - m_counts.TryGetValue(key, out int count); - m_counts[key] = checked(count + 1); - } - } - /// /// Captures the keys a collector must preserve regardless of catalog reachability. /// @@ -55,7 +46,18 @@ private void AddPin(AssetArtifactKey key) public IReadOnlyList GetRetainedKeys() { lock (m_sync) + { return Array.AsReadOnly(m_counts.Keys.ToArray()); + } + } + + private void AddPin(AssetArtifactKey key) + { + lock (m_sync) + { + m_counts.TryGetValue(key, out int count); + m_counts[key] = checked(count + 1); + } } private Stream OpenPinned( @@ -80,9 +82,13 @@ private void Release(AssetArtifactKey key) { int remaining = m_counts[key] - 1; if (remaining == 0) + { m_counts.Remove(key); + } else + { m_counts[key] = remaining; + } } } @@ -93,6 +99,6 @@ AssetArtifactKey key { private ArtifactRetention? m_owner = owner; - public void Dispose() => System.Threading.Interlocked.Exchange(ref m_owner, null)?.Release(key); + public void Dispose() => Interlocked.Exchange(ref m_owner, null)?.Release(key); } } diff --git a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs index 04de82183..e0a1b677b 100644 --- a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs +++ b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs @@ -22,15 +22,21 @@ namespace Inno.Assets; public AssetArtifactKey(string value) { string normalized = string.IsNullOrWhiteSpace(value) - ? string.Empty - : value.Trim().ToUpperInvariant(); + ? string.Empty + : value.Trim().ToUpperInvariant(); if (normalized.Length != 0) { if (normalized.Length != C_SHA256_HEX_LENGTH) + { throw new ArgumentException("An artifact key must be a complete SHA-256 hexadecimal fingerprint.", nameof(value)); + } foreach (char digit in normalized) + { if (digit is not (>= '0' and <= '9') and not (>= 'A' and <= 'F')) + { throw new ArgumentException("An artifact key cannot contain non-hexadecimal characters.", nameof(value)); + } + } } m_value = normalized; } @@ -53,23 +59,23 @@ public AssetArtifactKey(string value) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(AssetArtifactKey other) => string.Equals(value, other.value, StringComparison.Ordinal); /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is AssetArtifactKey other && Equals(other); /// diff --git a/src/content/assets/Inno.Assets/Artifacts/AssetRuntimeContentInfo.cs b/src/content/assets/Inno.Assets/Artifacts/AssetRuntimeContentInfo.cs index 8db21600c..cecc72134 100644 --- a/src/content/assets/Inno.Assets/Artifacts/AssetRuntimeContentInfo.cs +++ b/src/content/assets/Inno.Assets/Artifacts/AssetRuntimeContentInfo.cs @@ -28,7 +28,7 @@ public sealed class AssetRuntimeContentInfo /// The source inventory is absent. /// public AssetRuntimeContentInfo( - IReadOnlyList sources, + IReadOnlyList sources, int assetCount, int artifactBundleCount, long totalBytes @@ -43,7 +43,7 @@ long totalBytes /// /// Gets the source identities represented by the deployed catalog. /// - public IReadOnlyList sources { get; } + public IReadOnlyList sources { get; } /// /// Gets the number of runtime-scoped assets in the deployed catalog. diff --git a/src/content/assets/Inno.Assets/Artifacts/IAssetArtifactLookup.cs b/src/content/assets/Inno.Assets/Artifacts/IAssetArtifactLookup.cs index a0088205d..89d10be33 100644 --- a/src/content/assets/Inno.Assets/Artifacts/IAssetArtifactLookup.cs +++ b/src/content/assets/Inno.Assets/Artifacts/IAssetArtifactLookup.cs @@ -10,7 +10,7 @@ public interface IAssetArtifactLookup /// /// Retains one verified output so cache collection cannot remove an active generation. /// - /// + /// /// The persistent asset identity. /// /// @@ -23,14 +23,14 @@ public interface IAssetArtifactLookup /// The requested output is unavailable or invalid. /// ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName ); /// /// Tries to resolve one named immutable artifact output by persistent asset identity. /// - /// + /// /// Persistent identity of the artifact owner. /// /// @@ -43,7 +43,7 @@ string outputName /// when the artifact output exists and passes integrity validation. /// bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact ); diff --git a/src/content/assets/Inno.Assets/AssetDependency.cs b/src/content/assets/Inno.Assets/AssetDependency.cs index 6a95d47d6..ec8421018 100644 --- a/src/content/assets/Inno.Assets/AssetDependency.cs +++ b/src/content/assets/Inno.Assets/AssetDependency.cs @@ -1,5 +1,4 @@ using System; - using Inno.Extensibility.Types; using Inno.Scripting.Api; @@ -13,7 +12,7 @@ namespace Inno.Assets; /// /// Creates an asset dependency descriptor. /// - /// + /// /// The persistent identity of the referenced asset. /// /// @@ -23,17 +22,19 @@ namespace Inno.Assets; /// The last known source-relative path. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// [ScriptingApiIgnore] public AssetDependency( - Guid persistentId, + Guid persistentID, TypeRef type, string lastKnownPath ) { - if (persistentId == Guid.Empty) - throw new ArgumentException("An asset dependency requires a persistent identity.", nameof(persistentId)); - this.persistentId = persistentId; + if (persistentID == Guid.Empty) + { + throw new ArgumentException("An asset dependency requires a persistent identity.", nameof(persistentID)); + } + this.persistentID = persistentID; this.type = type; this.lastKnownPath = lastKnownPath ?? string.Empty; } @@ -41,7 +42,7 @@ string lastKnownPath /// /// Gets the persistent identity of the referenced asset. /// - public Guid persistentId { get; } + public Guid persistentID { get; } /// /// Gets the reload-safe identity of the expected asset type. @@ -63,17 +64,17 @@ string lastKnownPath /// /// when both values represent the same logical state; otherwise, . /// - public bool Equals(AssetDependency other) => persistentId == other.persistentId; + public bool Equals(AssetDependency other) => persistentID == other.persistentID; /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is AssetDependency other && Equals(other); /// @@ -82,7 +83,7 @@ string lastKnownPath /// /// A hash code consistent with the implemented equality contract. /// - public override int GetHashCode() => persistentId.GetHashCode(); + public override int GetHashCode() => persistentID.GetHashCode(); /// /// Determines whether two descriptors refer to the same persistent asset. diff --git a/src/content/assets/Inno.Assets/AssetImportStatus.cs b/src/content/assets/Inno.Assets/AssetImportStatus.cs index c1cecdc4b..a569d6e7b 100644 --- a/src/content/assets/Inno.Assets/AssetImportStatus.cs +++ b/src/content/assets/Inno.Assets/AssetImportStatus.cs @@ -9,27 +9,22 @@ public enum AssetImportStatus /// No importer currently accepts the source. /// Unsupported, - /// /// The source is waiting for import or commit. /// Pending, - /// /// A valid artifact is committed for the source. /// Imported, - /// /// The latest import failed and diagnostics are available. /// Failed, - /// /// The source is unavailable while its persistent identity is retained. /// Missing, - /// /// The source cannot be reconciled without resolving an identity conflict. /// diff --git a/src/content/assets/Inno.Assets/AssetInfo.cs b/src/content/assets/Inno.Assets/AssetInfo.cs index 4277d9a04..59ce296ad 100644 --- a/src/content/assets/Inno.Assets/AssetInfo.cs +++ b/src/content/assets/Inno.Assets/AssetInfo.cs @@ -11,7 +11,7 @@ public sealed class AssetInfo /// /// Creates an asset information snapshot. /// - /// + /// /// Persistent identity assigned to the source asset. /// /// @@ -23,10 +23,10 @@ public sealed class AssetInfo /// /// Current import status. /// - /// + /// /// Stable importer identifier, or an empty value when none applies. /// - /// + /// /// Stable imported asset type identity. /// /// @@ -42,33 +42,35 @@ public sealed class AssetInfo /// Thrown when is invalid. /// public AssetInfo( - Guid persistentId, + Guid persistentID, AssetPath assetPath, AssetSourceKind sourceKind, AssetImportStatus status, - string importerId, - Guid stableAssetTypeId, + string importerID, + Guid stableAssetTypeID, AssetArtifactKey artifactKey, AssetArtifactKey lastSuccessfulArtifactKey, IReadOnlyList? diagnostics = null ) { - this.persistentId = persistentId; + this.persistentID = persistentID; if (!assetPath.isValid) + { throw new ArgumentException("An asset information snapshot requires a valid path.", nameof(assetPath)); + } this.assetPath = assetPath; this.sourceKind = sourceKind; this.status = status; - this.importerId = importerId ?? string.Empty; - this.stableAssetTypeId = stableAssetTypeId; + this.importerID = importerID ?? string.Empty; + this.stableAssetTypeID = stableAssetTypeID; this.artifactKey = artifactKey; this.lastSuccessfulArtifactKey = lastSuccessfulArtifactKey; - this.diagnostics = diagnostics ?? Array.Empty(); + this.diagnostics = diagnostics ?? []; } /// /// Gets the persistent asset identity. /// - public Guid persistentId { get; } + public Guid persistentID { get; } /// /// Gets the current isolated source path. @@ -88,12 +90,12 @@ public AssetInfo( /// /// Gets the selected importer identifier. /// - public string importerId { get; } + public string importerID { get; } /// /// Gets the stable imported asset type identity. /// - public Guid stableAssetTypeId { get; } + public Guid stableAssetTypeID { get; } /// /// Gets the current committed artifact key. diff --git a/src/content/assets/Inno.Assets/AssetObject.cs b/src/content/assets/Inno.Assets/AssetObject.cs index 1906d3ef4..36a2fb796 100644 --- a/src/content/assets/Inno.Assets/AssetObject.cs +++ b/src/content/assets/Inno.Assets/AssetObject.cs @@ -1,6 +1,6 @@ using System; using System.IO; - +using System.Threading; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; @@ -29,9 +29,10 @@ public abstract class AssetObject : IdentityObject, ISerializable /// /// Gets a display name derived from the source-local path. /// - public string name => string.IsNullOrWhiteSpace(assetPath.localPath) - ? GetType().Name - : Path.GetFileName(assetPath.localPath); + public string name + => string.IsNullOrWhiteSpace(assetPath.localPath) + ? GetType().Name + : Path.GetFileName(assetPath.localPath); /// /// Gets whether this instance represents an unavailable persistent asset. @@ -54,7 +55,7 @@ public abstract class AssetObject : IdentityObject, ISerializable /// /// Current settings contract with a stable type identity. /// - /// + /// /// Persisted settings type identity. /// /// @@ -67,16 +68,22 @@ public abstract class AssetObject : IdentityObject, ISerializable /// The asset is unowned, retired, or lacks property-state services. /// public void RestoreProperties( - Guid stableTypeId, + Guid stableTypeID, byte[] propertyData, TValue target ) where TValue : class, ISerializable { - if (m_runtimeResourcesReleased || m_propertyStateOwner is null || !m_propertyStateOwner.TryGetTarget(out var owner)) + if (m_runtimeResourcesReleased + || m_propertyStateOwner is null + || !m_propertyStateOwner.TryGetTarget(out IAssetPropertyStateResolver? owner) + ) { throw new InvalidOperationException("The asset's property-state owner is unavailable."); - owner.RestoreProperties(stableTypeId, propertyData, target); + } + owner.RestoreProperties(stableTypeID, propertyData, target); } + internal string sourceHash => m_sourceHash; + /// /// Called after a new runtime payload has been committed to this instance. /// @@ -89,32 +96,29 @@ TValue target protected virtual void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - } + ) {} /// /// Releases the runtime resources owned by this asset without clearing its payload before quiescence. /// + /// + /// Owned work has not quiesced; runtime payload and ownership must remain intact until a later attempt. + /// /// /// An unfinished release may throw RetirementPendingException. The owner retains the asset and retries /// this hook; completed steps must not be repeated. Other failures are terminal and are reported by the owner. /// - /// - /// Owned work has not quiesced; runtime payload and ownership must remain intact until a later attempt. - /// - protected virtual void OnUnloading() - { - } - - internal string sourceHash => m_sourceHash; + protected virtual void OnUnloading() {} internal void ClaimRuntimeOwner( object authority, WeakReference? properties ) { - object? previous = System.Threading.Interlocked.CompareExchange(ref m_runtimeOwner, authority, null); + object? previous = Interlocked.CompareExchange(ref m_runtimeOwner, authority, null); if (previous is not null && !ReferenceEquals(previous, authority)) + { throw new InvalidOperationException("The asset belongs to another runtime owner."); + } m_propertyStateOwner = properties; } @@ -153,15 +157,14 @@ long version } } - internal void UpdateAssetPath(AssetPath assetPath) - { - this.assetPath = assetPath; - } + internal void UpdateAssetPath(AssetPath assetPath) => this.assetPath = assetPath; internal void ReleaseRuntimeResources() { if (m_runtimeResourcesReleased) + { return; + } try { OnUnloading(); diff --git a/src/content/assets/Inno.Assets/AssetPath.cs b/src/content/assets/Inno.Assets/AssetPath.cs index 858cc1495..003c894b1 100644 --- a/src/content/assets/Inno.Assets/AssetPath.cs +++ b/src/content/assets/Inno.Assets/AssetPath.cs @@ -4,57 +4,6 @@ namespace Inno.Assets; -/// -/// Identifies one isolated asset source mount. -/// -public record struct AssetSourceId -{ - /// - /// Gets the writable project source identifier. - /// - public static AssetSourceId project => new("project"); - - /// - /// Creates a globally stable source identifier. - /// - /// - /// Lowercase project or Plugin source identity. - /// - public AssetSourceId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - if (normalized.Any(static character => - !(character is >= 'a' and <= 'z' - || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { - throw new ArgumentException( - "An asset source ID may contain lowercase ASCII letters, digits, '.', '_', and '-' only.", - nameof(value)); - } - this.value = normalized; - } - - /// - /// Gets or sets the globally stable source value. - /// - public string value { get; set; } - - /// - /// Gets whether the source identity has a usable value. - /// - public readonly bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public readonly override string ToString() => value ?? string.Empty; -} - /// /// Addresses one asset without conflating isolated source mounts. /// @@ -72,11 +21,13 @@ public record struct AssetPath /// Source-local path using forward slashes. /// public AssetPath( - AssetSourceId source, + AssetSourceID source, string localPath ) { if (!source.isValid) + { throw new ArgumentException("An asset source ID must be valid.", nameof(source)); + } this.source = source; this.localPath = NormalizeLocalPath(localPath); } @@ -84,7 +35,7 @@ string localPath /// /// Gets or sets the owning source mount. /// - public AssetSourceId source { get; set; } + public AssetSourceID source { get; set; } /// /// Gets or sets the source-local path. @@ -97,15 +48,26 @@ string localPath public readonly bool isValid => source.isValid && localPath is not null; /// - /// Creates a path in the writable project source. + /// Formats this value as a human-readable representation. /// /// - /// A project-owned asset path. + /// The human-readable representation of this value. /// + public override readonly string ToString() + => source == AssetSourceID.project + ? localPath ?? string.Empty + : $"{source}{C_SOURCE_SEPARATOR}{localPath}"; + + /// + /// Creates a path in the writable project source. + /// /// /// The local path text validated by the project operation. /// - public static AssetPath Project(string localPath) => new(AssetSourceId.project, localPath); + /// + /// A project-owned asset path. + /// + public static AssetPath Project(string localPath) => new(AssetSourceID.project, localPath); /// /// Parses a canonical path, treating an unqualified value as project-owned. @@ -121,38 +83,29 @@ public static AssetPath Parse(string value) ArgumentNullException.ThrowIfNull(value); int separator = value.IndexOf(C_SOURCE_SEPARATOR, StringComparison.Ordinal); return separator < 0 - ? Project(value) - : new AssetPath(new AssetSourceId(value[..separator]), value[(separator + C_SOURCE_SEPARATOR.Length)..]); + ? Project(value) + : new AssetPath(new AssetSourceID(value[..separator]), value[(separator + C_SOURCE_SEPARATOR.Length)..]); } - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public readonly override string ToString() - => source == AssetSourceId.project - ? localPath ?? string.Empty - : $"{source}{C_SOURCE_SEPARATOR}{localPath}"; - private static string NormalizeLocalPath(string value) { ArgumentNullException.ThrowIfNull(value); if (Path.IsPathRooted(value) || value.StartsWith("/", StringComparison.Ordinal) || value.StartsWith('\\') - || value.Length >= 2 && char.IsAsciiLetter(value[0]) && value[1] == ':') - { + || value.Length >= 2 && char.IsAsciiLetter(value[0]) && value[1] == ':' + ) { throw new ArgumentException("An asset path must be source-relative.", nameof(value)); } string path = value.Replace('\\', '/').Trim(); while (path.StartsWith("./", StringComparison.Ordinal)) + { path = path[2..]; + } path = path.Trim('/'); if (path.Split('/', StringSplitOptions.RemoveEmptyEntries) - .Any(static segment => segment is "." or "..")) - { + .Any(static segment => segment is "." or "..") + ) { throw new ArgumentException("An asset path cannot contain traversal segments.", nameof(value)); } return path; diff --git a/src/content/assets/Inno.Assets/AssetReferenceInfo.cs b/src/content/assets/Inno.Assets/AssetReferenceInfo.cs index fdd351a6e..f77d851aa 100644 --- a/src/content/assets/Inno.Assets/AssetReferenceInfo.cs +++ b/src/content/assets/Inno.Assets/AssetReferenceInfo.cs @@ -16,7 +16,7 @@ public sealed class AssetReferenceInfo /// /// Freezes one diagnostic view of the engine-known references to an asset. /// - /// + /// /// The persistent asset identity. /// /// @@ -35,14 +35,14 @@ public sealed class AssetReferenceInfo /// Reference locations copied into this immutable snapshot. /// public AssetReferenceInfo( - Guid persistentId, + Guid persistentID, AssetPath assetPath, long contentVersion, bool isLoaded, bool? lastSweepReachability, IReadOnlyList references ) { - this.persistentId = persistentId; + this.persistentID = persistentID; this.assetPath = assetPath; this.contentVersion = contentVersion; this.isLoaded = isLoaded; @@ -54,7 +54,7 @@ IReadOnlyList references /// /// Gets the persistent asset identity. /// - public Guid persistentId { get; } + public Guid persistentID { get; } /// /// Gets the current mount-qualified asset path. diff --git a/src/content/assets/Inno.Assets/AssetReferenceKind.cs b/src/content/assets/Inno.Assets/AssetReferenceKind.cs index a95d7459b..f0a8335b4 100644 --- a/src/content/assets/Inno.Assets/AssetReferenceKind.cs +++ b/src/content/assets/Inno.Assets/AssetReferenceKind.cs @@ -1,4 +1,5 @@ using Inno.Runtime.Contracts; + namespace Inno.Assets; /// diff --git a/src/content/assets/Inno.Assets/AssetReferenceLocation.cs b/src/content/assets/Inno.Assets/AssetReferenceLocation.cs index cecbf1845..98de1feea 100644 --- a/src/content/assets/Inno.Assets/AssetReferenceLocation.cs +++ b/src/content/assets/Inno.Assets/AssetReferenceLocation.cs @@ -13,7 +13,7 @@ public sealed class AssetReferenceLocation /// /// The category of reference owner. /// - /// + /// /// The owner's persistent identity. /// /// @@ -24,12 +24,12 @@ public sealed class AssetReferenceLocation /// public AssetReferenceLocation( AssetReferenceKind kind, - Guid ownerId, + Guid ownerID, string ownerName, string propertyPath ) { this.kind = kind; - this.ownerId = ownerId; + this.ownerID = ownerID; this.ownerName = ownerName ?? string.Empty; this.propertyPath = propertyPath ?? string.Empty; } @@ -42,7 +42,7 @@ string propertyPath /// /// Gets the persistent identity of the known owner, when available. /// - public Guid ownerId { get; } + public Guid ownerID { get; } /// /// Gets the display name of the known owner. diff --git a/src/content/assets/Inno.Assets/AssetSourceID.cs b/src/content/assets/Inno.Assets/AssetSourceID.cs new file mode 100644 index 000000000..0d1a8c73d --- /dev/null +++ b/src/content/assets/Inno.Assets/AssetSourceID.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; + +namespace Inno.Assets; + +/// +/// Identifies one isolated asset source mount. +/// +public record struct AssetSourceID +{ + /// + /// Creates a globally stable source identifier. + /// + /// + /// Lowercase project or Plugin source identity. + /// + public AssetSourceID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + if (normalized.Any(static character => + !(character is >= 'a' and <= 'z' + || character is >= '0' and <= '9' + || character is '.' or '_' or '-')) + ) { + throw new ArgumentException( + "An asset source ID may contain lowercase ASCII letters, digits, '.', '_', and '-' only.", + nameof(value) + ); + } + this.value = normalized; + } + + /// + /// Gets the writable project source identifier. + /// + public static AssetSourceID project => new("project"); + + /// + /// Gets or sets the globally stable source value. + /// + public string value { get; set; } + + /// + /// Gets whether the source identity has a usable value. + /// + public readonly bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override readonly string ToString() => value ?? string.Empty; +} diff --git a/src/content/assets/Inno.Assets/AssetSourceKind.cs b/src/content/assets/Inno.Assets/AssetSourceKind.cs index c49702179..fbeed432d 100644 --- a/src/content/assets/Inno.Assets/AssetSourceKind.cs +++ b/src/content/assets/Inno.Assets/AssetSourceKind.cs @@ -9,7 +9,6 @@ public enum AssetSourceKind /// A regular imported source file. /// File, - /// /// A source directory with persistent identity but no runtime artifact. /// diff --git a/src/content/assets/Inno.Assets/Changes/AssetChange.cs b/src/content/assets/Inno.Assets/Changes/AssetChange.cs index 8bea8d21f..f258d4acf 100644 --- a/src/content/assets/Inno.Assets/Changes/AssetChange.cs +++ b/src/content/assets/Inno.Assets/Changes/AssetChange.cs @@ -13,7 +13,7 @@ public readonly struct AssetChange /// /// Committed change kind. /// - /// + /// /// Persistent identity affected by the change, or empty for a catalog-wide change. /// /// @@ -24,12 +24,12 @@ public readonly struct AssetChange /// public AssetChange( AssetChangeKind kind, - Guid persistentId, + Guid persistentID, AssetPath assetPath, AssetPath? previousAssetPath = null ) { this.kind = kind; - this.persistentId = persistentId; + this.persistentID = persistentID; this.assetPath = assetPath; this.previousAssetPath = previousAssetPath; } @@ -42,7 +42,7 @@ public AssetChange( /// /// Gets the persistent identity affected by the change. /// - public Guid persistentId { get; } + public Guid persistentID { get; } /// /// Gets the current isolated source path. diff --git a/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs b/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs index 5a57a4618..815bc378e 100644 --- a/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs +++ b/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs @@ -9,32 +9,26 @@ public enum AssetChangeKind /// A source was added to the database. /// Added, - /// /// An existing source or artifact changed. /// Modified, - /// /// A source moved while retaining its persistent identity. /// Moved, - /// /// A source and its persistent metadata were removed. /// Removed, - /// /// A source became unavailable while retaining its identity. /// Missing, - /// /// A canonical runtime object was replaced by an incompatible imported type. /// Replaced, - /// /// An import status or diagnostic changed without replacing the source. /// diff --git a/src/content/assets/Inno.Assets/Changes/AssetChangeSet.cs b/src/content/assets/Inno.Assets/Changes/AssetChangeSet.cs index 20f775fd7..1366517f5 100644 --- a/src/content/assets/Inno.Assets/Changes/AssetChangeSet.cs +++ b/src/content/assets/Inno.Assets/Changes/AssetChangeSet.cs @@ -22,7 +22,7 @@ public AssetChangeSet( IReadOnlyList? changes ) { this.revision = revision; - this.changes = changes ?? Array.Empty(); + this.changes = changes ?? []; } /// diff --git a/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs b/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs index 65e762588..6f71ef99e 100644 --- a/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs +++ b/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Assets; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Assets", - "Inno.Assets", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Assets", "Inno.Assets", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetDependency), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetPropertySnapshot), ScriptingApiScope.Runtime)] @@ -21,7 +18,7 @@ [assembly: ScriptingApiExport(typeof(RetentionScope), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetResidencyStatistics), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Assets), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AssetSourceId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AssetSourceID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetPath), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetReferenceInfo), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetReferenceKind), ScriptingApiScope.Runtime)] diff --git a/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs b/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs new file mode 100644 index 000000000..721a1c2bd --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Keeps one verified immutable artifact generation available for an explicit lifetime. +/// +public sealed class ArtifactLease : IDisposable +{ + private readonly ResidencyLease m_residency; + private readonly object m_sync = new(); + private Func? m_openRead; + + internal ArtifactLease( + AssetArtifactInfo artifact, + Func openRead, + Action release + ) { + ArgumentNullException.ThrowIfNull(openRead); + m_residency = new ResidencyLease(artifact, release); + m_openRead = openRead; + } + + /// + /// Gets verified metadata for the retained artifact. + /// + public AssetArtifactInfo info => m_residency.value; + + /// + /// Opens a read-only stream over the retained immutable artifact. + /// + /// + /// A new independently owned read stream. + /// + public Stream OpenRead() + { + lock (m_sync) + { + _ = m_residency.value; + return (m_openRead ?? throw new ObjectDisposedException(nameof(ArtifactLease)))(); + } + } + + /// + /// Reads one indexed payload through this lease's independently pinned stream. + /// + /// + /// Newly owned bytes with the exact indexed length; oversized or truncated payloads fail explicitly. + /// + /// + /// The payload exceeds the supported array size or does not have its indexed length. + /// + public byte[] ReadAllBytes() + { + long length = info.length; + if (length < 0 || length > Array.MaxLength) + { + throw new InvalidDataException("The artifact payload exceeds the supported array budget."); + } + using Stream input = OpenRead(); + var bytes = new byte[(int)length]; + input.ReadExactly(bytes); + if (input.ReadByte() != -1) + { + throw new InvalidDataException("The artifact payload exceeds its indexed length."); + } + return bytes; + } + + /// + /// Releases artifact ownership, retaining metadata and callback while the provider reports Pending. + /// + /// + /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. + /// + /// + /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. + /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// New reads stop when release begins; already opened streams retain their independent provider pins. + /// + public void Dispose() + { + lock (m_sync) + { + m_openRead = null; + } + m_residency.Dispose(); + } +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs index c74485b1a..3d42989d0 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs @@ -35,8 +35,18 @@ public AssetPreparationStatistics preparationStatistics get { lock (m_sync) - return new(m_pendingLoads.Count, m_peakPendingLoads, m_rejectedLoads, m_payloadReads.Count, - m_payloadReadsStarted, m_payloadReadsShared, m_preparingBytes, m_peakPreparingBytes); + { + return new( + m_pendingLoads.Count, + m_peakPendingLoads, + m_rejectedLoads, + m_payloadReads.Count, + m_payloadReadsStarted, + m_payloadReadsShared, + m_preparingBytes, + m_peakPreparingBytes + ); + } } } @@ -48,7 +58,9 @@ public long preparingBytes get { lock (m_sync) + { return m_preparingBytes; + } } } @@ -91,7 +103,7 @@ public int CompletePendingLoads(int completionBudget = 8) } } - private ValueTask> QueueAcquisition( + private ValueTask> QueueAcquisitionAsync( RuntimeAssetRecord record, CancellationToken cancellationToken ) where TAsset : AssetObject @@ -110,13 +122,15 @@ CancellationToken cancellationToken throw new InvalidOperationException("Runtime asset preparation is at capacity; retry after the next completion safety point."); } if (!typeof(TAsset).IsAssignableFrom(ResolveType(record))) + { throw new InvalidOperationException($"Runtime asset '{record.path}' is not compatible with '{typeof(TAsset).FullName}'."); + } - if (!m_preparations.TryGetValue(record.persistentId, out SharedPreparation? shared)) + if (!m_preparations.TryGetValue(record.persistentID, out SharedPreparation? shared)) { // Only immutable paths, hashes and IDs cross into IO; serializers and identities stay here. List reads = []; - CollectPayloadReads(record, new HashSet(), reads); + CollectPayloadReads(record, [], reads); long bytes = reads.Where(read => !m_payloadReads.ContainsKey(read)).Sum(static read => read.length); if (bytes > m_preparationBudgetBytes - m_preparingBytes) { @@ -136,31 +150,46 @@ CancellationToken cancellationToken m_payloadReadsStarted++; } else + { m_payloadReadsShared++; + } payload.owners++; payloads.Add(payload); } - shared = new SharedPreparation(StartPayloadPreparation(payloads.ToArray()), payloads.ToArray()); - m_preparations.Add(record.persistentId, shared); + shared = new SharedPreparation(StartPayloadPreparationAsync(payloads.ToArray()), payloads.ToArray()); + m_preparations.Add(record.persistentID, shared); m_peakPreparingBytes = Math.Max(m_peakPreparingBytes, m_preparingBytes); } catch { foreach (SharedPayload payload in payloads) + { ReleasePayload(payload); + } throw; } } shared.waiters++; - var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); - m_pendingLoads.Add(new PendingAcquisition(shared.preparation, cancellationToken, payloads => - { - TAsset asset = LoadRecord(record, pin: false, payloads); - record.leaseCount++; - completion.SetResult(CreateResidencyLease(record, asset)); - }, exception => completion.TrySetException(exception), - () => completion.TrySetCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)), - () => ReleasePreparation(record.persistentId, shared))); + var completion = new TaskCompletionSource>( + TaskCreationOptions.RunContinuationsAsynchronously + ); + m_pendingLoads.Add( + new PendingAcquisition( + shared.preparation, + payloads => + { + TAsset asset = LoadRecord(record, pin: false, payloads); + record.leaseCount++; + completion.SetResult(CreateResidencyLease(record, asset)); + }, + exception => completion.TrySetException(exception), + () => completion.TrySetCanceled( + cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true) + ), + () => ReleasePreparation(record.persistentID, shared), + cancellationToken + ) + ); m_peakPendingLoads = Math.Max(m_peakPendingLoads, m_pendingLoads.Count); return new ValueTask>(completion.Task); } @@ -168,8 +197,7 @@ CancellationToken cancellationToken private AssetLease CreateResidencyLease( RuntimeAssetRecord record, TAsset asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { bool released = false; return CreateAssetLease(asset, () => ReleaseLease(record, ref released)); @@ -180,70 +208,39 @@ private void CollectPayloadReads( HashSet visited, List reads ) { - if (!visited.Add(record.persistentId)) + if (!visited.Add(record.persistentID)) + { return; + } RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => candidate.name == "runtime"); if (output.length < 0 || output.length > int.MaxValue) - throw new InvalidDataException("A runtime payload length is outside the supported allocation range."); - reads.Add(new PayloadRead(record.persistentId, - GetVerifiedOutputKey(record, output), output.length, output.contentHash)); - foreach (AssetDependency dependency in record.dependencies) - CollectPayloadReads(m_recordsById[dependency.persistentId], visited, reads); - } - - private static async Task ReadPayloadAsync( - PayloadRead read, - ContentReadLease lease, - CancellationToken token, - SemaphoreSlim slots - ) { - await slots.WaitAsync(token).ConfigureAwait(false); - try { - return await ReadPayloadContentAsync(read, lease, token).ConfigureAwait(false); + throw new InvalidDataException("A runtime payload length is outside the supported allocation range."); } - finally + reads.Add( + new PayloadRead( + record.persistentID, + GetVerifiedOutputKey(record, output), + output.length, + output.contentHash + ) + ); + foreach (AssetDependency dependency in record.dependencies) { - slots.Release(); + CollectPayloadReads(m_recordsByID[dependency.persistentID], visited, reads); } } - private static async Task ReadPayloadContentAsync( - PayloadRead read, - ContentReadLease lease, - CancellationToken token - ) { - using Stream stream = lease.OpenRead(); - byte[] bytes = new byte[checked((int)read.length)]; - await stream.ReadExactlyAsync(bytes, token).ConfigureAwait(false); - token.ThrowIfCancellationRequested(); - if (stream.ReadByte() != -1 || bytes.LongLength != read.length || - !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), read.hash, StringComparison.OrdinalIgnoreCase)) - throw new InvalidDataException($"Runtime payload '{read.id:D}' failed integrity verification."); - return bytes; - } - - private static Task> StartPayloadPreparation(SharedPayload[] reads) - { - if (ExecutionContext.IsFlowSuppressed()) - return AssemblePayloadsAsync(reads); - using (ExecutionContext.SuppressFlow()) - return AssemblePayloadsAsync(reads); - } - - private static async Task> AssemblePayloadsAsync(SharedPayload[] reads) - { - // WhenAll observes every shared IO task before a failed closure relinquishes its reservations. - await Task.WhenAll(reads.Select(static read => read.preparation)).ConfigureAwait(false); - return reads.ToDictionary(static read => read.read.id, static read => read.preparation.GetAwaiter().GetResult()); - } - private void CancelPendingLoads() { foreach (SharedPayload preparation in m_payloadReads.Values) + { preparation.cancellation.Cancel(); + } foreach (PendingAcquisition request in m_pendingLoads) + { request.Cancel(); + } m_pendingLoads.Clear(); } @@ -252,22 +249,31 @@ private void ReleasePreparation( SharedPreparation preparation ) { if (--preparation.waiters != 0) + { return; + } m_preparations.Remove(id); foreach (SharedPayload payload in preparation.payloads) + { ReleasePayload(payload); + } } private void ReleasePayload(SharedPayload payload) { if (--payload.owners != 0) + { return; + } payload.cancellation.Cancel(); try { payload.preparation.GetAwaiter().GetResult(); } - catch (Exception) { /* The acquisition reports IO failures; rollback only drains ownership. */ } + catch (Exception) + { + // The acquisition reports IO failures; rollback only drains ownership. + } m_payloadReads.Remove(payload.read); m_preparingBytes -= payload.read.length; payload.cancellation.Dispose(); @@ -276,7 +282,62 @@ private void ReleasePayload(SharedPayload payload) private void EnsureResidencyOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Runtime asset acquisition and publication require the database owner thread."); + } + } + + private static async Task ReadPayloadAsync( + PayloadRead read, + ContentReadLease lease, + SemaphoreSlim slots, + CancellationToken cancellationToken + ) { + await slots.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await ReadPayloadContentAsync(read, lease, cancellationToken).ConfigureAwait(false); + } + finally + { + slots.Release(); + } + } + + private static async Task ReadPayloadContentAsync( + PayloadRead read, + ContentReadLease lease, + CancellationToken cancellationToken + ) { + using Stream stream = lease.OpenRead(); + var bytes = new byte[checked((int)read.length)]; + await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + if (stream.ReadByte() != -1 || bytes.LongLength != read.length + || !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), read.hash, StringComparison.OrdinalIgnoreCase) + ) { + throw new InvalidDataException($"Runtime payload '{read.id:D}' failed integrity verification."); + } + return bytes; + } + + private static Task> StartPayloadPreparationAsync(SharedPayload[] reads) + { + if (ExecutionContext.IsFlowSuppressed()) + { + return AssemblePayloadsAsync(reads); + } + using (ExecutionContext.SuppressFlow()) + { + return AssemblePayloadsAsync(reads); + } + } + + private static async Task> AssemblePayloadsAsync(SharedPayload[] reads) + { + // WhenAll observes every shared IO task before a failed closure relinquishes its reservations. + await Task.WhenAll(reads.Select(static read => read.preparation)).ConfigureAwait(false); + return reads.ToDictionary(static read => read.read.id, static read => read.preparation.GetAwaiter().GetResult()); } private sealed record PayloadRead( @@ -306,11 +367,15 @@ SemaphoreSlim slots try { if (ExecutionContext.IsFlowSuppressed()) - preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + { + this.preparation = Task.Run(() => PrepareAsync(read, lease, slots, cancellation.Token)); + } else { using (ExecutionContext.SuppressFlow()) - preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + { + this.preparation = Task.Run(() => PrepareAsync(read, lease, slots, cancellation.Token)); + } } } catch @@ -329,21 +394,23 @@ SemaphoreSlim slots private static async Task PrepareAsync( PayloadRead read, ContentReadLease lease, - CancellationToken cancellation, - SemaphoreSlim slots + SemaphoreSlim slots, + CancellationToken cancellationToken ) { using (lease) - return await ReadPayloadAsync(read, lease, cancellation, slots).ConfigureAwait(false); + { + return await ReadPayloadAsync(read, lease, slots, cancellationToken).ConfigureAwait(false); + } } } private sealed class PendingAcquisition( Task> preparation, - CancellationToken cancellation, Action> publish, Action fail, Action cancel, - Action release + Action release, + CancellationToken cancellationToken ) { internal Task> preparation { get; } = preparation; @@ -351,7 +418,7 @@ internal void Complete() { try { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); publish(preparation.GetAwaiter().GetResult()); } catch (OperationCanceledException) @@ -374,7 +441,10 @@ internal void Cancel() { preparation.GetAwaiter().GetResult(); } - catch (Exception) { /* The retiring owner reports cancellation instead of publishing. */ } + catch (Exception) + { + // The retiring owner reports cancellation instead of publishing. + } cancel(); release(); } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs index 5480227d3..0efa9f8ff 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs @@ -6,11 +6,11 @@ using System.Threading; using System.Threading.Tasks; using Inno.Assets; +using Inno.Content; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Content; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -32,52 +32,20 @@ public sealed partial class AssetDatabase : AssetResidencyProvider, private readonly AssetRuntimeOwner m_runtimeOwner; private readonly object m_sync = new(); private readonly Dictionary m_recordsByPath = []; - private readonly Dictionary m_recordsById = []; + private readonly Dictionary m_recordsByID = []; private readonly Dictionary m_dependencyRetention = []; private readonly SerializationGeneration m_serialization; private readonly SerializationContext m_serializationContext; - private TypeCacheSnapshot? m_types; private readonly IdentityAllocator m_identities; private readonly IRuntimeContentStore m_content; private readonly long m_residencyBudgetBytes; private readonly long m_preparationBudgetBytes; + private TypeCacheSnapshot? m_types; private long m_accessSequence; private long m_residentBytes; private bool m_disposed; private LifetimeScope? m_retirement; - /// - /// Restores serialized properties to the existing asset object. - /// - /// - /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// Serialized asset object type receiving restored properties. - /// - public void RestoreProperties( - Guid stableTypeId, - byte[] propertyData, - TValue target - ) where TValue : class, ISerializable - { - ObjectDisposedException.ThrowIf(m_disposed, this); - ArgumentNullException.ThrowIfNull(target); - if (m_types!.GetTypeRef(target.GetType()).stableId != stableTypeId) - throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); - m_serialization.Decode(propertyData, reader => - { - reader.RestoreProperties(target); - return true; - }, m_serializationContext); - } - /// /// Creates a read-only runtime asset database from one verified immutable content store. /// @@ -87,12 +55,12 @@ TValue target /// /// The immutable converter generation pinned by the owning runtime session. /// - /// - /// The session-owned allocator used for canonical runtime asset identities. - /// /// /// The immutable type generation pinned by this runtime session, without refreshing authoring registries. /// + /// + /// The session-owned allocator used for canonical runtime asset identities. + /// /// /// Maximum unpinned runtime payload bytes retained after lease release. /// @@ -128,31 +96,90 @@ public AssetDatabase( m_residencyBudgetBytes = residencyBudgetBytes; m_preparationBudgetBytes = preparationBudgetBytes; RuntimeAssetCatalog catalog = m_serialization.Deserialize( - ReadContent(new ContentKey("AssetDatabase/Catalog.snapshot"))); + ReadContent(new ContentKey("AssetDatabase/Catalog.snapshot")) + ); for (int index = 0; index < catalog.entries.Length; index++) { RuntimeAssetData data = m_serialization.Deserialize(catalog.entries[index]); RuntimeAssetRecord record = ValidateRecord(data, index); if (!m_recordsByPath.TryAdd(record.path, record)) + { throw new InvalidDataException($"Runtime catalog repeats asset path '{record.path}'."); - if (!m_recordsById.TryAdd(record.persistentId, record)) - throw new InvalidDataException($"Runtime catalog repeats asset identity '{record.persistentId:D}'."); + } + if (!m_recordsByID.TryAdd(record.persistentID, record)) + { + throw new InvalidDataException($"Runtime catalog repeats asset identity '{record.persistentID:D}'."); + } } foreach (RuntimeAssetRecord record in m_recordsByPath.Values) { for (int index = 0; index < record.dependencies.Length; index++) { - if (!m_recordsById.ContainsKey(record.dependencies[index].persistentId)) + if (!m_recordsByID.ContainsKey(record.dependencies[index].persistentID)) { throw new InvalidDataException( - $"Runtime asset '{record.path}' depends on missing asset " + - $"'{record.dependencies[index].persistentId:D}'."); + $"Runtime asset '{record.path}' depends on missing asset " + + $"'{record.dependencies[index].persistentID:D}'." + ); } } ValidateArtifactBundle(record); } } + /// + /// Gets current materialized asset count, payload bytes, and the configured budget. + /// + public AssetResidencyStatistics residencyStatistics + { + get + { + lock (m_sync) + { + EnsureActive(); + return new AssetResidencyStatistics( + m_recordsByPath.Values.Count(static record => record.asset is not null), + m_residentBytes, + m_residencyBudgetBytes + ); + } + } + } + + /// + /// Restores serialized properties to the existing asset object. + /// + /// + /// Serialized asset object type receiving restored properties. + /// + /// + /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The property data consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The existing target that receives the validated result. + /// + public void RestoreProperties( + Guid stableTypeID, + byte[] propertyData, + TValue target + ) where TValue : class, ISerializable + { + ObjectDisposedException.ThrowIf(m_disposed, this); + ArgumentNullException.ThrowIfNull(target); + if (m_types!.GetTypeRef(target.GetType()).stableID != stableTypeID) + { + throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } + m_serialization.Decode(propertyData, reader => + { + reader.RestoreProperties(target); + return true; + }, m_serializationContext); + } + /// /// Loads the canonical asset at one catalog path. /// @@ -179,7 +206,9 @@ public TAsset Load(AssetPath path) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record)) + { throw new InvalidOperationException($"Runtime asset '{path}' is not present in the deployed catalog."); + } return LoadRecord(record, pin: true); } } @@ -190,7 +219,7 @@ public TAsset Load(AssetPath path) /// /// The required runtime asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -203,14 +232,16 @@ public TAsset Load(AssetPath path) /// /// Thrown when this database has been disposed. /// - public TAsset Load(Guid persistentId) + public TAsset Load(Guid persistentID) where TAsset : AssetObject { lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) - throw new InvalidOperationException($"Runtime asset '{persistentId:D}' is not present in the deployed catalog."); + if (!m_recordsByID.TryGetValue(persistentID, out RuntimeAssetRecord? record)) + { + throw new InvalidOperationException($"Runtime asset '{persistentID:D}' is not present in the deployed catalog."); + } return LoadRecord(record, pin: true); } } @@ -237,15 +268,14 @@ public TAsset Load(Guid persistentId) public bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { lock (m_sync) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record) - || !typeof(TAsset).IsAssignableFrom(ResolveType(record))) - { + || !typeof(TAsset).IsAssignableFrom(ResolveType(record)) + ) { asset = null; return false; } @@ -260,7 +290,7 @@ out TAsset? asset /// /// The required runtime asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -274,17 +304,16 @@ out TAsset? asset /// Thrown when this database has been disposed. /// public bool TryLoad( - Guid persistentId, + Guid persistentID, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record) - || !typeof(TAsset).IsAssignableFrom(ResolveType(record))) - { + if (!m_recordsByID.TryGetValue(persistentID, out RuntimeAssetRecord? record) + || !typeof(TAsset).IsAssignableFrom(ResolveType(record)) + ) { asset = null; return false; } @@ -293,24 +322,6 @@ out TAsset? asset } } - /// - /// Gets current materialized asset count, payload bytes, and the configured budget. - /// - public AssetResidencyStatistics residencyStatistics - { - get - { - lock (m_sync) - { - EnsureActive(); - return new AssetResidencyStatistics( - m_recordsByPath.Values.Count(static record => record.asset is not null), - m_residentBytes, - m_residencyBudgetBytes); - } - } - } - /// /// Acquires a canonical runtime asset by path for an explicit residency lifetime. /// @@ -329,16 +340,17 @@ public AssetResidencyStatistics residencyStatistics public ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); lock (m_sync) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record)) + { throw new InvalidOperationException($"Runtime asset '{path}' is not present in the deployed catalog."); - return QueueAcquisition(record, cancellationToken); + } + return QueueAcquisitionAsync(record, cancellationToken); } } @@ -348,7 +360,7 @@ public ValueTask> AcquireAsync( /// /// Required runtime asset contract. /// - /// + /// /// Persistent asset identity. /// /// @@ -358,21 +370,21 @@ public ValueTask> AcquireAsync( /// A lease completed after verified preparation and owner-thread publication. /// public ValueTask> AcquireAsync( - Guid persistentId, + Guid persistentID, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) + if (!m_recordsByID.TryGetValue(persistentID, out RuntimeAssetRecord? record)) { throw new InvalidOperationException( - $"Runtime asset '{persistentId:D}' is not present in the deployed catalog."); + $"Runtime asset '{persistentID:D}' is not present in the deployed catalog." + ); } - return QueueAcquisition(record, cancellationToken); + return QueueAcquisitionAsync(record, cancellationToken); } } @@ -397,9 +409,9 @@ public IReadOnlyList GetDependencies(AssetObject asset) lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(asset.identity.persistentId, out RuntimeAssetRecord? record) - || !ReferenceEquals(record.asset, asset)) - { + if (!m_recordsByID.TryGetValue(asset.identity.persistentID, out RuntimeAssetRecord? record) + || !ReferenceEquals(record.asset, asset) + ) { throw new InvalidOperationException("Only an asset owned by this database has runtime dependencies."); } return record.dependencies.ToArray(); @@ -409,7 +421,7 @@ public IReadOnlyList GetDependencies(AssetObject asset) /// /// Tries to resolve one named immutable artifact output by persistent asset identity. /// - /// + /// /// The persistent identity of the artifact owner. /// /// @@ -426,7 +438,7 @@ public IReadOnlyList GetDependencies(AssetObject asset) /// Thrown when this database has been disposed. /// public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact ) { @@ -435,18 +447,23 @@ out AssetArtifactInfo? artifact { EnsureActive(); artifact = null; - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) + if (!m_recordsByID.TryGetValue(persistentID, out RuntimeAssetRecord? record)) + { return false; + } RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.FirstOrDefault(candidate => string.Equals(candidate.name, outputName, StringComparison.Ordinal)); if (string.IsNullOrWhiteSpace(output.name)) + { return false; + } _ = GetVerifiedOutputKey(record, output); artifact = new AssetArtifactInfo( new AssetArtifactKey(record.artifactKey), output.name, output.contentHash, - output.length); + output.length + ); return true; } } @@ -454,7 +471,7 @@ out AssetArtifactInfo? artifact /// /// Acquires one verified immutable artifact output for an explicit lifetime. /// - /// + /// /// Persistent identity of the artifact owner. /// /// @@ -464,17 +481,18 @@ out AssetArtifactInfo? artifact /// A lease over the verified deployed artifact. /// public ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName ) { lock (m_sync) { - if (!TryGetArtifact(persistentId, outputName, out AssetArtifactInfo? artifact) || artifact is null) + if (!TryGetArtifact(persistentID, outputName, out AssetArtifactInfo? artifact) || artifact is null) { throw new InvalidOperationException( - $"Runtime asset '{persistentId:D}' has no verified artifact output '{outputName}'."); + $"Runtime asset '{persistentID:D}' has no verified artifact output '{outputName}'." + ); } - RuntimeAssetRecord record = m_recordsById[persistentId]; + RuntimeAssetRecord record = m_recordsByID[persistentID]; RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => candidate.name == outputName); ContentReadLease content = m_content.Acquire(GetVerifiedOutputKey(record, output)); return CreateArtifactLease(artifact, content.OpenRead, content.Dispose); @@ -510,14 +528,20 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new LifetimeScope(); m_retirement.Own(m_payloadReadSlots); - foreach (RuntimeAssetRecord record in m_recordsById.Values) + foreach (RuntimeAssetRecord record in m_recordsByID.Values) + { if (record.asset is not null) + { m_retirement.Own(new RuntimeAssetRetirement(this, record)); + } + } } CancelPendingLoads(); try @@ -537,11 +561,19 @@ public void Dispose() } } + AssetObject IAssetReferenceResolver.Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ) => ResolveReference(persistentID, stableTypeID, expectedType, propertyPath, requirePrepared: false); + private void FinishRetirement() { m_dependencyRetention.Clear(); m_recordsByPath.Clear(); - m_recordsById.Clear(); + m_recordsByID.Clear(); m_residentBytes = 0; m_types = null; m_disposed = true; @@ -551,30 +583,38 @@ private TAsset LoadRecord( RuntimeAssetRecord record, bool pin, IReadOnlyDictionary? preparedPayloads = null - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { if (record.isRetiring) + { Evict(record); + } Type actualType = ResolveType(record); if (!typeof(TAsset).IsAssignableFrom(actualType)) { throw new InvalidOperationException( - $"Runtime asset '{record.path}' has type '{actualType.FullName}', not '{typeof(TAsset).FullName}'."); + $"Runtime asset '{record.path}' has type '{actualType.FullName}', not '{typeof(TAsset).FullName}'." + ); } record.isPinned |= pin; record.lastAccess = ++m_accessSequence; if (record.asset is TAsset loaded) + { return loaded; + } - var created = new List(); + List created = []; try { PrepareShells(record, created); for (int index = 0; index < created.Count; index++) + { Hydrate(created[index], preparedPayloads); + } for (int index = 0; index < created.Count; index++) + { RetainDependencies(created[index]); + } return (TAsset)record.asset!; } catch @@ -583,7 +623,9 @@ private TAsset LoadRecord( { RuntimeAssetRecord createdRecord = created[index]; if (createdRecord.asset is null) + { continue; + } m_dependencyRetention.Remove(createdRecord.asset); m_residentBytes -= createdRecord.runtimeBytes; createdRecord.runtimeBytes = 0; @@ -600,7 +642,9 @@ private void PrepareShells( ICollection created ) { if (record.asset is not null) + { return; + } Type type = ResolveType(record); AssetObject asset; try @@ -611,14 +655,17 @@ ICollection created { throw new InvalidOperationException( $"Runtime asset type '{type.FullName}' requires a parameterless constructor.", - exception); + exception + ); } - m_identities.InitializePersistentIdentity(asset, record.persistentId); - m_identities.Register(asset, record.persistentId); + m_identities.InitializePersistentIdentity(asset, record.persistentID); + m_identities.Register(asset, record.persistentID); record.asset = asset; created.Add(record); for (int index = 0; index < record.dependencies.Length; index++) - PrepareShells(m_recordsById[record.dependencies[index].persistentId], created); + { + PrepareShells(m_recordsByID[record.dependencies[index].persistentID], created); + } } private void Hydrate( @@ -633,7 +680,9 @@ private void Hydrate( }, m_serializationContext); byte[] payload; if (preparedPayloads is not null) - payload = preparedPayloads[record.persistentId]; + { + payload = preparedPayloads[record.persistentID]; + } else { RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => @@ -648,8 +697,10 @@ private void Hydrate( private void RetainDependencies(RuntimeAssetRecord record) { AssetObject[] dependencies = record.dependencies - .Select(dependency => m_recordsById[dependency.persistentId].asset - ?? throw new InvalidOperationException("A runtime dependency was not prepared.")) + .Select(dependency => ( + m_recordsByID[dependency.persistentID].asset + ?? throw new InvalidOperationException("A runtime dependency was not prepared.") + )) .ToArray(); m_dependencyRetention[record.asset!] = dependencies; } @@ -661,11 +712,15 @@ ref bool released lock (m_sync) { if (m_disposed || m_retirement is not null) + { return; + } if (!released) { if (record.leaseCount <= 0) + { throw new InvalidOperationException("Runtime asset residency has no matching lease to release."); + } record.leaseCount--; released = true; record.lastAccess = ++m_accessSequence; @@ -685,7 +740,9 @@ private int TrimToBudgetLocked() .ThenBy(static record => record.path.ToString(), StringComparer.Ordinal) .FirstOrDefault(); if (candidate is null) + { break; + } Evict(candidate); released++; } @@ -696,11 +753,15 @@ private bool CanEvict(RuntimeAssetRecord record) { AssetObject? asset = record.asset; if (asset is null || record.isPinned || record.leaseCount != 0) + { return false; + } foreach ((AssetObject owner, AssetObject[] dependencies) in m_dependencyRetention) { if (!ReferenceEquals(owner, asset) && dependencies.Contains(asset, ReferenceEqualityComparer.Instance)) + { return false; + } } return true; } @@ -708,7 +769,7 @@ private bool CanEvict(RuntimeAssetRecord record) private void Evict(RuntimeAssetRecord record) { AssetObject asset = record.asset - ?? throw new InvalidOperationException("Only a materialized asset can be evicted."); + ?? throw new InvalidOperationException("Only a materialized asset can be evicted."); record.isRetiring = true; List failures = []; try @@ -741,21 +802,14 @@ private void Evict(RuntimeAssetRecord record) record.runtimeBytes = 0; record.isRetiring = false; if (failures.Count > 0) + { throw new AggregateException("Runtime asset retirement failed after releasing its registration.", failures); + } } - AssetObject IAssetReferenceResolver.Resolve( - Guid persistentId, - Guid stableTypeId, - string lastKnownPath, - Type expectedType, - string propertyPath - ) - => ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: false); - private AssetObject ResolveReference( - Guid persistentId, - Guid stableTypeId, + Guid persistentID, + Guid stableTypeID, Type expectedType, string propertyPath, bool requirePrepared @@ -763,16 +817,25 @@ bool requirePrepared lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record) || - (requirePrepared && record.asset is null)) + if (!m_recordsByID.TryGetValue(persistentID, out RuntimeAssetRecord? record) + || (requirePrepared && record.asset is null) + ) { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' is outside the deployed runtime closure."); - if (stableTypeId != Guid.Empty && record.stableTypeId != stableTypeId) + $"Asset reference '{persistentID:D}' at '{propertyPath}' is outside the deployed runtime closure." + ); + } + if (stableTypeID != Guid.Empty && record.stableTypeID != stableTypeID) + { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' has a mismatched stable type identity."); + $"Asset reference '{persistentID:D}' at '{propertyPath}' has a mismatched stable type identity." + ); + } if (!expectedType.IsAssignableFrom(ResolveType(record))) + { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' is incompatible with '{expectedType.FullName}'."); + $"Asset reference '{persistentID:D}' at '{propertyPath}' is incompatible with '{expectedType.FullName}'." + ); + } return requirePrepared ? record.asset! : LoadRecord(record, pin: true); } } @@ -782,17 +845,29 @@ private RuntimeAssetRecord ValidateRecord( int index ) { if (data.persistentId == Guid.Empty) + { throw new InvalidDataException($"Runtime catalog entry {index} has no persistent identity."); + } if (data.stableAssetTypeId == Guid.Empty) + { throw new InvalidDataException($"Runtime catalog entry {index} has no stable asset type identity."); + } if (data.isDirectory || data.isTombstone) + { throw new InvalidDataException($"Runtime catalog entry {index} is not a live deployable asset."); + } if (data.deploymentScope != 0 || data.importStatus != (int)AssetImportStatus.Imported) + { throw new InvalidDataException($"Runtime catalog entry {index} is not a successfully imported runtime asset."); + } if (data.assetStateBytes.Length == 0) + { throw new InvalidDataException($"Runtime catalog entry {index} has no serialized asset state."); + } if (data.artifactKey.Length != 64 || data.artifactKey.Any(static character => !Uri.IsHexDigit(character))) + { throw new InvalidDataException($"Runtime catalog entry {index} has an invalid artifact identity."); + } AssetPath path; try { @@ -805,7 +880,8 @@ int index AssetDependency[] dependencies = data.runtimeDependencies.Select(dependency => new AssetDependency( dependency.persistentId, new TypeRef(dependency.stableTypeId), - dependency.lastKnownPath ?? string.Empty)).ToArray(); + dependency.lastKnownPath ?? string.Empty + )).ToArray(); return new RuntimeAssetRecord( data.persistentId, path, @@ -813,16 +889,18 @@ int index data.stableAssetTypeId, data.artifactKey.ToUpperInvariant(), data.assetStateBytes, - dependencies); + dependencies + ); } private Type ResolveType(RuntimeAssetRecord record) { - Type type = new TypeRef(record.stableTypeId).Resolve(m_types!); + Type type = new TypeRef(record.stableTypeID).Resolve(m_types!); if (!typeof(AssetObject).IsAssignableFrom(type) || type.IsAbstract) { throw new InvalidDataException( - $"Runtime asset '{record.path}' resolves to invalid type '{type.FullName}'."); + $"Runtime asset '{record.path}' resolves to invalid type '{type.FullName}'." + ); } return type; } @@ -831,22 +909,27 @@ private void ValidateArtifactBundle(RuntimeAssetRecord record) { RuntimeArtifactManifest manifest = ReadArtifactManifest(record); if (!string.Equals(manifest.key, record.artifactKey, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidDataException($"Runtime artifact bundle '{record.artifactKey}' has a mismatched manifest identity."); + } string[] names = manifest.outputs.Select(static output => output.name).ToArray(); if (names.Distinct(StringComparer.Ordinal).Count() != names.Length || !names.Contains("asset-state", StringComparer.Ordinal) - || !names.Contains("runtime", StringComparer.Ordinal)) - { + || !names.Contains("runtime", StringComparer.Ordinal) + ) { throw new InvalidDataException( - $"Runtime artifact bundle '{record.artifactKey}' does not contain one complete asset-state/runtime pair."); + $"Runtime artifact bundle '{record.artifactKey}' does not contain one complete asset-state/runtime pair." + ); } foreach (RuntimeArtifactOutput output in manifest.outputs) + { _ = GetVerifiedOutputKey(record, output); + } } private RuntimeArtifactManifest ReadArtifactManifest(RuntimeAssetRecord record) { - ContentKey key = new(GetBundleRoot(record.artifactKey) + "/manifest"); + var key = new ContentKey(GetBundleRoot(record.artifactKey) + "/manifest"); return m_serialization.Deserialize(ReadContent(key)); } @@ -855,48 +938,60 @@ private ContentKey GetVerifiedOutputKey( RuntimeArtifactOutput output ) { if (string.IsNullOrWhiteSpace(output.name) || string.IsNullOrWhiteSpace(output.fileName) - || output.fileName.Contains('/') || output.fileName.Contains('\\')) - { + || output.fileName.Contains('/') || output.fileName.Contains('\\') + ) { throw new InvalidDataException($"Runtime artifact bundle '{record.artifactKey}' contains an invalid output path."); } - ContentKey key = new(GetBundleRoot(record.artifactKey) + "/outputs/" + output.fileName); + var key = new ContentKey(GetBundleRoot(record.artifactKey) + "/outputs/" + output.fileName); if (!m_content.index.TryGetEntry(key, out ContentEntry? entry)) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' is missing."); + } if (entry!.length != output.length) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' has an invalid length."); + } if (!string.Equals(entry.contentHash, output.contentHash, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' failed hash verification."); + } return key; } - private static string GetBundleRoot(string key) - => "Artifacts/" + key[..2].ToLowerInvariant() + "/" + key[2..4].ToLowerInvariant() + "/" + key; - private byte[] ReadContent(ContentKey key) { using ContentReadLease lease = m_content.Acquire(key); if (lease.entry.length > Array.MaxLength) + { throw new InvalidDataException($"Content '{key}' exceeds the supported array budget."); + } using Stream input = lease.OpenRead(); - byte[] bytes = new byte[(int)lease.entry.length]; + var bytes = new byte[(int)lease.entry.length]; input.ReadExactly(bytes); - if (input.ReadByte() != -1 || !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), - lease.entry.contentHash, StringComparison.Ordinal)) + if (input.ReadByte() != -1 || !string.Equals( + Convert.ToHexString(SHA256.HashData(bytes)), + lease.entry.contentHash, + StringComparison.Ordinal + )) { throw new InvalidDataException($"Content '{key}' failed integrity verification."); + } return bytes; } private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); + private static string GetBundleRoot(string key) + => "Artifacts/" + key[..2].ToLowerInvariant() + "/" + key[2..4].ToLowerInvariant() + "/" + key; + private sealed class PreparedAssetResolver(AssetDatabase owner) : IAssetReferenceResolver { /// /// Resolves only shells already prepared from the importing asset's declared runtime closure. /// - /// + /// /// The preserved asset identity. /// - /// + /// /// The expected stable asset type. /// /// @@ -912,13 +1007,12 @@ private sealed class PreparedAssetResolver(AssetDatabase owner) : IAssetReferenc /// The already prepared canonical shell, or an exception for an undeclared reference. /// public AssetObject Resolve( - Guid persistentId, - Guid stableTypeId, + Guid persistentID, + Guid stableTypeID, string lastKnownPath, Type expectedType, string propertyPath - ) - => owner.ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: true); + ) => owner.ResolveReference(persistentID, stableTypeID, expectedType, propertyPath, requirePrepared: true); } private sealed class RuntimeAssetRetirement( @@ -932,23 +1026,25 @@ RuntimeAssetRecord record public void Dispose() { if (record.asset is not null) + { owner.Evict(record); + } } } private sealed class RuntimeAssetRecord( - Guid persistentId, + Guid persistentID, AssetPath path, string sourceHash, - Guid stableTypeId, + Guid stableTypeID, string artifactKey, byte[] assetState, AssetDependency[] dependencies ) { - internal Guid persistentId { get; } = persistentId; + internal Guid persistentID { get; } = persistentID; internal AssetPath path { get; } = path; internal string sourceHash { get; } = sourceHash; - internal Guid stableTypeId { get; } = stableTypeId; + internal Guid stableTypeID { get; } = stableTypeID; internal string artifactKey { get; } = artifactKey; internal byte[] assetState { get; } = assetState; internal AssetDependency[] dependencies { get; } = dependencies; @@ -971,56 +1067,121 @@ private sealed class RuntimeAssetCatalog : ISerializable private sealed class RuntimeAssetData : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal string relativePath { get; set; } = string.Empty; - [SerializableProperty] internal string sourceHash { get; set; } = string.Empty; - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal int deploymentScope { get; set; } - [SerializableProperty] internal Guid stableAssetTypeId { get; set; } - [SerializableProperty] internal byte[] assetStateBytes { get; set; } = []; - [SerializableProperty] internal RuntimeDependencyData[] runtimeDependencies { get; set; } = []; - [SerializableProperty] internal RuntimeImportDependencyData[] importDependencies { get; set; } = []; - [SerializableProperty] internal int importStatus { get; set; } - [SerializableProperty] internal string importerImplementationFingerprint { get; set; } = string.Empty; - [SerializableProperty] internal string artifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string[] diagnostics { get; set; } = []; - [SerializableProperty] internal bool isDirectory { get; set; } - [SerializableProperty] internal bool isTombstone { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal string relativePath { get; set; } = string.Empty; + + [SerializableProperty] + internal string sourceHash { get; set; } = string.Empty; + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal int deploymentScope { get; set; } + + [SerializableProperty] + internal Guid stableAssetTypeId { get; set; } + + [SerializableProperty] + internal byte[] assetStateBytes { get; set; } = []; + + [SerializableProperty] + internal RuntimeDependencyData[] runtimeDependencies { get; set; } = []; + + [SerializableProperty] + internal RuntimeImportDependencyData[] importDependencies { get; set; } = []; + + [SerializableProperty] + internal int importStatus { get; set; } + + [SerializableProperty] + internal string importerImplementationFingerprint { get; set; } = string.Empty; + + [SerializableProperty] + internal string artifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string[] diagnostics { get; set; } = []; + + [SerializableProperty] + internal bool isDirectory { get; set; } + + [SerializableProperty] + internal bool isTombstone { get; set; } } private struct RuntimeDependencyData { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal string lastKnownPath { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal string lastKnownPath { get; set; } } private struct RuntimeImportDependencyData { - [SerializableProperty] internal int kind { get; set; } - [SerializableProperty] internal string key { get; set; } - [SerializableProperty] internal string fingerprint { get; set; } - [SerializableProperty] internal bool sourceStampValid { get; set; } - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } + [SerializableProperty] + internal int kind { get; set; } + + [SerializableProperty] + internal string key { get; set; } + + [SerializableProperty] + internal string fingerprint { get; set; } + + [SerializableProperty] + internal bool sourceStampValid { get; set; } + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } } private sealed class RuntimeArtifactManifest : ISerializable { - [SerializableProperty] internal string key { get; set; } = string.Empty; - [SerializableProperty] internal RuntimeArtifactOutput[] outputs { get; set; } = []; + [SerializableProperty] + internal string key { get; set; } = string.Empty; + + [SerializableProperty] + internal RuntimeArtifactOutput[] outputs { get; set; } = []; } private struct RuntimeArtifactOutput { - [SerializableProperty] internal string name { get; set; } - [SerializableProperty] internal string fileName { get; set; } - [SerializableProperty] internal string contentHash { get; set; } - [SerializableProperty] internal long length { get; set; } + [SerializableProperty] + internal string name { get; set; } + + [SerializableProperty] + internal string fileName { get; set; } + + [SerializableProperty] + internal string contentHash { get; set; } + + [SerializableProperty] + internal long length { get; set; } } } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs b/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs index 72872f766..06e8aa9a0 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Assets; @@ -13,7 +13,7 @@ namespace Inno.Assets; /// public static class AssetExecutionContext { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("assets"); + private static readonly ExecutionSlot CURRENT_SCOPE = new("assets"); /// /// Gets the asset lookup bound to the current asynchronous execution context. @@ -21,7 +21,7 @@ public static class AssetExecutionContext /// /// Thrown when no asset lookup is active for the caller. /// - public static IAssetLookup current => S_CURRENT_SCOPE.current; + public static IAssetLookup current => CURRENT_SCOPE.current; /// /// Binds an asset lookup until the returned strict last-in-first-out scope is disposed. @@ -38,7 +38,6 @@ public static class AssetExecutionContext public static IDisposable EnterScope(IAssetLookup assets) { ArgumentNullException.ThrowIfNull(assets); - return S_CURRENT_SCOPE.Enter(assets); + return CURRENT_SCOPE.Enter(assets); } - } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetLease.cs b/src/content/assets/Inno.Assets/Runtime/AssetLease.cs new file mode 100644 index 000000000..5f541e946 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetLease.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Keeps one canonical asset generation resident for an explicit lifetime. +/// +/// +/// Concrete retained asset type. +/// +public sealed class AssetLease : IDisposable + where TAsset : AssetObject +{ + private readonly ResidencyLease m_residency; + + internal AssetLease( + TAsset asset, + Action release + ) { + m_residency = new ResidencyLease(asset, release); + } + + /// + /// Gets the retained canonical asset while this lease is active. + /// + /// + /// Thrown after the lease has been released. + /// + public TAsset asset => m_residency.value; + + /// + /// Releases this caller's residency ownership, retaining its value and callback while the provider reports Pending. + /// + /// + /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. + /// + /// + /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. + /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// + public void Dispose() => m_residency.Dispose(); +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs deleted file mode 100644 index d1209c872..000000000 --- a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs +++ /dev/null @@ -1,331 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Execution; - -namespace Inno.Assets; - -/// -/// Exposes explicit asynchronous asset and artifact residency ownership. -/// -public interface IAssetResidency -{ - /// - /// Acquires a canonical asset by logical path and keeps it resident until the lease is released. - /// - /// - /// Required asset contract. - /// - /// - /// Mount-qualified logical asset path. - /// - /// - /// Cancellation for this caller's asynchronous wait. - /// - /// - /// A lease that owns residency for the canonical asset. - /// - ValueTask> AcquireAsync( - AssetPath path, - CancellationToken cancellationToken = default - ) - where TAsset : AssetObject; - - /// - /// Acquires a canonical asset by persistent identity and keeps it resident until release. - /// - /// - /// Required asset contract. - /// - /// - /// Non-empty persistent asset identity. - /// - /// - /// Cancellation for this caller's asynchronous wait. - /// - /// - /// A lease that owns residency for the canonical asset. - /// - ValueTask> AcquireAsync( - Guid persistentId, - CancellationToken cancellationToken = default - ) - where TAsset : AssetObject; - - /// - /// Acquires one verified immutable artifact output. - /// - /// - /// Persistent identity of the artifact owner. - /// - /// - /// Stable artifact output name. - /// - /// - /// A lease that keeps the artifact generation available to the caller. - /// - /// - /// Thrown when the requested artifact does not exist or fails verification. - /// - ArtifactLease AcquireArtifact( - Guid persistentId, - string outputName - ); -} - -/// -/// Provides controlled lease construction to concrete asset residency implementations. -/// -public abstract class AssetResidencyProvider -{ - /// - /// Creates one strongly typed asset residency lease. - /// - /// - /// Concrete canonical asset type. - /// - /// - /// Canonical asset retained by the lease. - /// - /// - /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. - /// - /// - /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. - /// - protected static AssetLease CreateAssetLease( - TAsset asset, - Action release - ) - where TAsset : AssetObject - => new(asset, release); - - /// - /// Creates one immutable artifact residency lease. - /// - /// - /// Verified artifact metadata retained by the lease. - /// - /// - /// Opens immutable bytes with an independent provider pin owned by the returned stream. - /// - /// - /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. - /// - /// - /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. - /// - protected static ArtifactLease CreateArtifactLease( - AssetArtifactInfo artifact, - Func openRead, - Action release - ) => new(artifact, openRead, release); -} - -/// -/// Keeps one canonical asset generation resident for an explicit lifetime. -/// -/// -/// Concrete retained asset type. -/// -public sealed class AssetLease : IDisposable - where TAsset : AssetObject -{ - private readonly ResidencyLease m_residency; - - internal AssetLease( - TAsset asset, - Action release - ) { - m_residency = new ResidencyLease(asset, release); - } - - /// - /// Gets the retained canonical asset while this lease is active. - /// - /// - /// Thrown after the lease has been released. - /// - public TAsset asset => m_residency.value; - - /// - /// Releases this caller's residency ownership, retaining its value and callback while the provider reports Pending. - /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// - /// - /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. - /// - /// - /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. - /// - public void Dispose() => m_residency.Dispose(); -} - -/// -/// Keeps one verified immutable artifact generation available for an explicit lifetime. -/// -public sealed class ArtifactLease : IDisposable -{ - private readonly ResidencyLease m_residency; - private readonly object m_sync = new(); - private Func? m_openRead; - - internal ArtifactLease( - AssetArtifactInfo artifact, - Func openRead, - Action release - ) { - m_residency = new ResidencyLease(artifact, release); - m_openRead = openRead ?? throw new ArgumentNullException(nameof(openRead)); - } - - /// - /// Gets verified metadata for the retained artifact. - /// - public AssetArtifactInfo info => m_residency.value; - - /// - /// Opens a read-only stream over the retained immutable artifact. - /// - /// - /// A new independently owned read stream. - /// - public Stream OpenRead() - { - lock (m_sync) - { - _ = m_residency.value; - return (m_openRead ?? throw new ObjectDisposedException(nameof(ArtifactLease)))(); - } - } - - /// - /// Reads one indexed payload through this lease's independently pinned stream. - /// - /// - /// Newly owned bytes with the exact indexed length; oversized or truncated payloads fail explicitly. - /// - /// - /// The payload exceeds the supported array size or does not have its indexed length. - /// - public byte[] ReadAllBytes() - { - long length = info.length; - if (length < 0 || length > Array.MaxLength) - throw new InvalidDataException("The artifact payload exceeds the supported array budget."); - using Stream input = OpenRead(); - byte[] bytes = new byte[(int)length]; - input.ReadExactly(bytes); - if (input.ReadByte() != -1) - throw new InvalidDataException("The artifact payload exceeds its indexed length."); - return bytes; - } - - /// - /// Releases artifact ownership, retaining metadata and callback while the provider reports Pending. - /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// New reads stop when release begins; already opened streams retain their independent provider pins. - /// - /// - /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. - /// - /// - /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. - /// - public void Dispose() - { - lock (m_sync) - m_openRead = null; - m_residency.Dispose(); - } -} - -/// -/// Owns multiple asset, artifact, or subsystem leases as one reverse-order lifetime. -/// -public sealed class RetentionScope : IDisposable -{ - private readonly LifetimeScope m_lifetime = new(); - - /// - /// Transfers one lease into this scope. - /// - /// - /// Disposable lease type. - /// - /// - /// Lease whose disposal ownership transfers to this scope. - /// - /// - /// The same lease for convenient initialization. - /// - /// - /// Retirement has begun and the scope cannot accept another lease. - /// - public TLease Retain(TLease lease) - where TLease : IDisposable - { - return m_lifetime.Own(lease); - } - - /// - /// Releases all retained leases in reverse acquisition order. - /// - /// - /// Thrown after every lease is attempted when one or more releases fail. - /// - /// - /// A lease is not retired. The current and remaining dependencies are retained for retry. - /// - public void Dispose() => m_lifetime.Dispose(); -} - -/// -/// Reports current explicit runtime asset residency accounting. -/// -public readonly record struct AssetResidencyStatistics -{ - /// - /// Creates one immutable residency snapshot. - /// - /// - /// Number of currently materialized canonical assets. - /// - /// - /// Runtime payload bytes retained by materialized assets. - /// - /// - /// Configured runtime payload budget. - /// - public AssetResidencyStatistics( - int residentAssetCount, - long residentBytes, - long budgetBytes - ) { - this.residentAssetCount = residentAssetCount; - this.residentBytes = residentBytes; - this.budgetBytes = budgetBytes; - } - - /// - /// Gets the number of materialized canonical assets. - /// - public int residentAssetCount { get; } - - /// - /// Gets retained runtime payload bytes. - /// - public long residentBytes { get; } - - /// - /// Gets the configured runtime payload budget. - /// - public long budgetBytes { get; } -} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs new file mode 100644 index 000000000..ba2eb2b8f --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; + +namespace Inno.Assets; + +/// +/// Provides controlled lease construction to concrete asset residency implementations. +/// +public abstract class AssetResidencyProvider +{ + /// + /// Creates one strongly typed asset residency lease. + /// + /// + /// Concrete canonical asset type. + /// + /// + /// Canonical asset retained by the lease. + /// + /// + /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. + /// + /// + /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. + /// + protected static AssetLease CreateAssetLease( + TAsset asset, + Action release + ) where TAsset : AssetObject + => new(asset, release); + + /// + /// Creates one immutable artifact residency lease. + /// + /// + /// Verified artifact metadata retained by the lease. + /// + /// + /// Opens immutable bytes with an independent provider pin owned by the returned stream. + /// + /// + /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. + /// + /// + /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. + /// + protected static ArtifactLease CreateArtifactLease( + AssetArtifactInfo artifact, + Func openRead, + Action release + ) => new(artifact, openRead, release); +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs new file mode 100644 index 000000000..dd531b4a2 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs @@ -0,0 +1,44 @@ +namespace Inno.Assets; + +/// +/// Reports current explicit runtime asset residency accounting. +/// +public readonly record struct AssetResidencyStatistics +{ + /// + /// Creates one immutable residency snapshot. + /// + /// + /// Number of currently materialized canonical assets. + /// + /// + /// Runtime payload bytes retained by materialized assets. + /// + /// + /// Configured runtime payload budget. + /// + public AssetResidencyStatistics( + int residentAssetCount, + long residentBytes, + long budgetBytes + ) { + this.residentAssetCount = residentAssetCount; + this.residentBytes = residentBytes; + this.budgetBytes = budgetBytes; + } + + /// + /// Gets the number of materialized canonical assets. + /// + public int residentAssetCount { get; } + + /// + /// Gets retained runtime payload bytes. + /// + public long residentBytes { get; } + + /// + /// Gets the configured runtime payload budget. + /// + public long budgetBytes { get; } +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs b/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs index 24d9727de..704d1f4b9 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs @@ -21,7 +21,10 @@ public sealed class AssetRuntimeOwner /// /// Owner resolver, weakly referenced so stale assets cannot retain a retired database. /// - public AssetRuntimeOwner(IAssetPropertyStateResolver? properties = null) => m_properties = properties is null ? null : new(properties); + public AssetRuntimeOwner(IAssetPropertyStateResolver? properties = null) + { + m_properties = properties is null ? null : new WeakReference(properties); + } /// /// Reads the source fingerprint of an asset claimed by this owner. diff --git a/src/content/assets/Inno.Assets/Runtime/Assets.cs b/src/content/assets/Inno.Assets/Runtime/Assets.cs index d04393cce..ba53094ab 100644 --- a/src/content/assets/Inno.Assets/Runtime/Assets.cs +++ b/src/content/assets/Inno.Assets/Runtime/Assets.cs @@ -39,8 +39,10 @@ public static AssetPath LocalPath( ArgumentNullException.ThrowIfNull(localPath); ArgumentNullException.ThrowIfNull(sourceFile); if (!sourceFile.Contains("::", StringComparison.Ordinal)) + { throw new InvalidOperationException("Source-local Asset paths require a compiler-supplied canonical source location."); - AssetSourceId source; + } + AssetSourceID source; try { source = AssetPath.Parse(sourceFile).source; @@ -69,7 +71,7 @@ public static AssetPath LocalPath( /// public static TAsset Load(AssetPath path) where TAsset : AssetObject - => AssetExecutionContext.current.Load(path); + => AssetExecutionContext.current.Load(path); /// /// Loads the canonical asset with a persistent identity in the current session. @@ -77,7 +79,7 @@ public static TAsset Load(AssetPath path) /// /// The required asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -86,9 +88,9 @@ public static TAsset Load(AssetPath path) /// /// Thrown when no asset lookup is active, the asset does not exist, or its type is incompatible. /// - public static TAsset Load(Guid persistentId) + public static TAsset Load(Guid persistentID) where TAsset : AssetObject - => AssetExecutionContext.current.Load(persistentId); + => AssetExecutionContext.current.Load(persistentID); /// /// Tries to load the canonical asset at a logical catalog path in the current session. @@ -112,8 +114,7 @@ public static TAsset Load(Guid persistentId) public static bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => AssetExecutionContext.current.TryLoad(path, out asset); /// @@ -122,7 +123,7 @@ out TAsset? asset /// /// The required asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -136,11 +137,10 @@ out TAsset? asset /// Thrown when no asset lookup is active for the caller. /// public static bool TryLoad( - Guid persistentId, + Guid persistentID, out TAsset? asset - ) - where TAsset : AssetObject - => AssetExecutionContext.current.TryLoad(persistentId, out asset); + ) where TAsset : AssetObject + => AssetExecutionContext.current.TryLoad(persistentID, out asset); /// /// Acquires a canonical asset and explicitly retains it until the returned lease is disposed. @@ -160,8 +160,7 @@ out TAsset? asset public static ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => GetResidency().AcquireAsync(path, cancellationToken); /// @@ -170,7 +169,7 @@ public static ValueTask> AcquireAsync( /// /// Required asset contract. /// - /// + /// /// Persistent asset identity. /// /// @@ -180,16 +179,15 @@ public static ValueTask> AcquireAsync( /// A lease that owns residency for the canonical asset. /// public static ValueTask> AcquireAsync( - Guid persistentId, + Guid persistentID, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject - => GetResidency().AcquireAsync(persistentId, cancellationToken); + ) where TAsset : AssetObject + => GetResidency().AcquireAsync(persistentID, cancellationToken); /// /// Acquires one verified immutable artifact output for an explicit lifetime. /// - /// + /// /// Persistent identity of the artifact owner. /// /// @@ -199,13 +197,13 @@ public static ValueTask> AcquireAsync( /// A lease over verified artifact metadata and bytes. /// public static ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName - ) - => GetResidency().AcquireArtifact(persistentId, outputName); + ) => GetResidency().AcquireArtifact(persistentID, outputName); private static IAssetResidency GetResidency() => AssetExecutionContext.current as IAssetResidency - ?? throw new InvalidOperationException( - "The current asset lookup does not provide explicit residency ownership."); + ?? throw new InvalidOperationException( + "The current asset lookup does not provide explicit residency ownership." + ); } diff --git a/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs b/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs index f8f3e3ba0..235d658aa 100644 --- a/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs +++ b/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs @@ -31,7 +31,7 @@ TAsset Load(AssetPath path) /// /// The required asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -40,7 +40,7 @@ TAsset Load(AssetPath path) /// /// Thrown when the asset does not exist or has an incompatible concrete type. /// - TAsset Load(Guid persistentId) + TAsset Load(Guid persistentID) where TAsset : AssetObject; /// @@ -62,8 +62,7 @@ TAsset Load(Guid persistentId) bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; /// /// Tries to load the canonical asset with a persistent identity. @@ -71,7 +70,7 @@ out TAsset? asset /// /// The required asset contract. /// - /// + /// /// The non-empty persistent asset identity. /// /// @@ -82,8 +81,7 @@ out TAsset? asset /// . /// bool TryLoad( - Guid persistentId, + Guid persistentID, out TAsset? asset - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; } diff --git a/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs new file mode 100644 index 000000000..2e7fee9c4 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets; + +/// +/// Exposes explicit asynchronous asset and artifact residency ownership. +/// +public interface IAssetResidency +{ + /// + /// Acquires a canonical asset by logical path and keeps it resident until the lease is released. + /// + /// + /// Required asset contract. + /// + /// + /// Mount-qualified logical asset path. + /// + /// + /// Cancellation for this caller's asynchronous wait. + /// + /// + /// A lease that owns residency for the canonical asset. + /// + ValueTask> AcquireAsync( + AssetPath path, + CancellationToken cancellationToken = default + ) where TAsset : AssetObject; + + /// + /// Acquires a canonical asset by persistent identity and keeps it resident until release. + /// + /// + /// Required asset contract. + /// + /// + /// Non-empty persistent asset identity. + /// + /// + /// Cancellation for this caller's asynchronous wait. + /// + /// + /// A lease that owns residency for the canonical asset. + /// + ValueTask> AcquireAsync( + Guid persistentID, + CancellationToken cancellationToken = default + ) where TAsset : AssetObject; + + /// + /// Acquires one verified immutable artifact output. + /// + /// + /// Persistent identity of the artifact owner. + /// + /// + /// Stable artifact output name. + /// + /// + /// A lease that keeps the artifact generation available to the caller. + /// + /// + /// Thrown when the requested artifact does not exist or fails verification. + /// + ArtifactLease AcquireArtifact( + Guid persistentID, + string outputName + ); +} diff --git a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs index d9bd15f9d..f0a5e0544 100644 --- a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs +++ b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs @@ -4,7 +4,8 @@ namespace Inno.Assets; -internal sealed class ResidencyLease : IDisposable where TValue : class +internal sealed class ResidencyLease : IDisposable + where TValue : class { private readonly object m_sync = new(); private TValue? m_value; @@ -16,17 +17,10 @@ internal ResidencyLease( TValue value, Action release ) { - m_value = value ?? throw new ArgumentNullException(nameof(value)); - m_release = release ?? throw new ArgumentNullException(nameof(release)); - } - - internal TValue value - { - get - { - lock (m_sync) - return m_value ?? throw new ObjectDisposedException("Residency lease"); - } + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(release); + m_value = value; + m_release = release; } /// @@ -41,9 +35,13 @@ public void Dispose() lock (m_sync) { if (m_release is null) + { return; + } if (m_releasing) + { throw new RetirementPendingException("Residency release is already being advanced by another invocation."); + } m_releasing = true; release = m_release; } @@ -56,7 +54,9 @@ public void Dispose() m_completedFailures ??= []; RetirementPendingException.CollectCompletedFailures(pendingRetirement, m_completedFailures); lock (m_sync) + { m_releasing = false; + } throw; } catch (Exception exception) @@ -71,7 +71,20 @@ public void Dispose() } Finish(); if (m_completedFailures is { Count: > 0 }) + { throw TakeCompletedFailure(); + } + } + + internal TValue value + { + get + { + lock (m_sync) + { + return m_value ?? throw new ObjectDisposedException("Residency lease"); + } + } } private void Finish() @@ -86,7 +99,10 @@ private void Finish() private AggregateException TakeCompletedFailure() { - var failure = new AggregateException("Residency release completed with earlier cleanup failures.", m_completedFailures!); + var failure = new AggregateException( + "Residency release completed with earlier cleanup failures.", + m_completedFailures! + ); m_completedFailures = null; return failure; } diff --git a/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs b/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs new file mode 100644 index 000000000..73b34103f --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Owns multiple asset, artifact, or subsystem leases as one reverse-order lifetime. +/// +public sealed class RetentionScope : IDisposable +{ + private readonly LifetimeScope m_lifetime = new(); + + /// + /// Transfers one lease into this scope. + /// + /// + /// Disposable lease type. + /// + /// + /// Lease whose disposal ownership transfers to this scope. + /// + /// + /// The same lease for convenient initialization. + /// + /// + /// Retirement has begun and the scope cannot accept another lease. + /// + public TLease Retain(TLease lease) + where TLease : IDisposable => m_lifetime.Own(lease); + + /// + /// Releases all retained leases in reverse acquisition order. + /// + /// + /// Thrown after every lease is attempted when one or more releases fail. + /// + /// + /// A lease is not retired. The current and remaining dependencies are retained for retry. + /// + public void Dispose() => m_lifetime.Dispose(); +} diff --git a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs index 5931938c6..de73ed3e9 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -22,9 +21,7 @@ public sealed class AssetDependencyCollection /// Creates a dependency collector that preserves last-known source paths in serialized references. /// public AssetDependencyCollection() - : this(includeLastKnownPaths: true) - { - } + : this(includeLastKnownPaths: true) {} /// /// Creates a dependency collector with an explicit location-hint policy. @@ -48,8 +45,25 @@ public AssetDependencyCollection(bool includeLastKnownPaths) /// public IReadOnlyList dependencies => m_dependencies is null || m_dependencies.Count == 0 - ? Array.Empty() - : m_dependencies.Values.OrderBy(static dependency => dependency.persistentId).ToArray(); + ? [] + : m_dependencies.Values.OrderBy(static dependency => dependency.persistentID).ToArray(); + + /// + /// Includes a dependency already captured inside a neutral nested property payload. + /// + /// + /// Stable asset/type identity and optional location hint. + /// + public void Add(AssetDependency dependency) + { + if (dependency.persistentID == Guid.Empty) + { + throw new ArgumentException("A dependency requires a persistent asset identity.", nameof(dependency)); + } + (m_dependencies ??= [])[dependency.persistentID] = includeLastKnownPaths + ? dependency + : new AssetDependency(dependency.persistentID, dependency.type, string.Empty); + } internal void Add( AssetObject asset, @@ -57,32 +71,22 @@ TypeCatalog types ) { ArgumentNullException.ThrowIfNull(asset); ArgumentNullException.ThrowIfNull(types); - Guid persistentId = asset.identity.persistentId; - if (persistentId == Guid.Empty) + Guid persistentID = asset.identity.persistentID; + if (persistentID == Guid.Empty) + { throw new InvalidOperationException($"Asset '{asset.GetType().FullName}' has no persistent identity."); + } if (!types.TryGetTypeRef(asset.GetType(), out TypeRef typeRef)) { throw new InvalidOperationException( - $"Asset type '{asset.GetType().FullName}' requires a StableTypeId before it can be referenced persistently."); + $"Asset type '{asset.GetType().FullName}' requires a StableTypeID before it can be referenced persistently." + ); } - (m_dependencies ??= [])[persistentId] = new AssetDependency( - persistentId, + (m_dependencies ??= [])[persistentID] = new AssetDependency( + persistentID, typeRef, - includeLastKnownPaths ? asset.assetPath.ToString() : string.Empty); - } - - /// - /// Includes a dependency already captured inside a neutral nested property payload. - /// - /// - /// Stable asset/type identity and optional location hint. - /// - public void Add(AssetDependency dependency) - { - if (dependency.persistentId == Guid.Empty) - throw new ArgumentException("A dependency requires a persistent asset identity.", nameof(dependency)); - (m_dependencies ??= [])[dependency.persistentId] = includeLastKnownPaths ? dependency - : new AssetDependency(dependency.persistentId, dependency.type, string.Empty); + includeLastKnownPaths ? asset.assetPath.ToString() : string.Empty + ); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs b/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs index bf31909b5..e6adb85bc 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs @@ -1,9 +1,8 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -23,8 +22,8 @@ public override void Write( AssetDependency value ) { ArgumentNullException.ThrowIfNull(writer); - writer.Write("persistentId", value.persistentId); - writer.Write("stableTypeId", value.type.stableId); + writer.Write("persistentId", value.persistentID); + writer.Write("stableTypeId", value.type.stableID); writer.Write("lastKnownPath", value.lastKnownPath); } @@ -43,6 +42,7 @@ public override AssetDependency Read(SerializationReader reader) return new AssetDependency( reader.Read("persistentId"), new TypeRef(reader.Read("stableTypeId")), - reader.Read("lastKnownPath")); + reader.Read("lastKnownPath") + ); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs b/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs index d77cc4b77..c9e701a33 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs @@ -1,9 +1,8 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -28,26 +27,31 @@ AssetObject value ) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(value); - Guid persistentId = value.identity.persistentId; - if (persistentId == Guid.Empty) + Guid persistentID = value.identity.persistentID; + if (persistentID == Guid.Empty) + { throw new InvalidOperationException($"Asset '{value.GetType().FullName}' has no persistent identity at '{writer.path}'."); + } TypeCacheSnapshot types = writer.typeSnapshot; if (!types.TryGetTypeRef(value.GetType(), out TypeRef typeRef)) { throw new InvalidOperationException( - $"Asset type '{value.GetType().FullName}' requires a StableTypeId at '{writer.path}'."); + $"Asset type '{value.GetType().FullName}' requires a StableTypeID at '{writer.path}'." + ); } - bool hasDependencies = writer.context.TryGet(out AssetDependencyCollection? dependencies) && - dependencies is not null; + bool hasDependencies = writer.context.TryGet(out AssetDependencyCollection? dependencies) + && dependencies is not null; string lastKnownPath = !hasDependencies || dependencies!.includeLastKnownPaths - ? value.assetPath.ToString() - : string.Empty; - writer.Write(C_PERSISTENT_ID, persistentId); - writer.Write(C_STABLE_TYPE_ID, typeRef.stableId); + ? value.assetPath.ToString() + : string.Empty; + writer.Write(C_PERSISTENT_ID, persistentID); + writer.Write(C_STABLE_TYPE_ID, typeRef.stableID); writer.Write(C_LAST_KNOWN_PATH, lastKnownPath); if (hasDependencies) - dependencies!.Add(new AssetDependency(persistentId, typeRef, lastKnownPath)); + { + dependencies!.Add(new AssetDependency(persistentID, typeRef, lastKnownPath)); + } } /// @@ -67,6 +71,7 @@ public override AssetObject Read(SerializationReader reader) reader.Read(C_STABLE_TYPE_ID), reader.Read(C_LAST_KNOWN_PATH), reader.valueType, - reader.path); + reader.path + ); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs b/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs index ddd26ed3a..40caa9918 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs @@ -10,10 +10,11 @@ namespace Inno.Assets; public sealed class AssetPropertySnapshot { private readonly byte[] m_data; + /// /// Freezes a complete owner-produced property value. /// - /// + /// /// Persistent identity of the exact serialized settings type. /// /// @@ -23,25 +24,30 @@ public sealed class AssetPropertySnapshot /// Direct dependencies collected during the same serialization operation. /// public AssetPropertySnapshot( - Guid stableTypeId, + Guid stableTypeID, ReadOnlySpan data, IEnumerable dependencies ) { - if (stableTypeId == Guid.Empty) - throw new ArgumentException("A property snapshot requires a stable type identity.", nameof(stableTypeId)); + if (stableTypeID == Guid.Empty) + { + throw new ArgumentException("A property snapshot requires a stable type identity.", nameof(stableTypeID)); + } ArgumentNullException.ThrowIfNull(dependencies); - this.stableTypeId = stableTypeId; + this.stableTypeID = stableTypeID; m_data = data.ToArray(); this.dependencies = Array.AsReadOnly(dependencies.ToArray()); } + /// /// Gets the persistent settings type identity. /// - public Guid stableTypeId { get; } + public Guid stableTypeID { get; } + /// /// Gets the frozen native property bytes. /// public ReadOnlyMemory data => m_data; + /// /// Gets the frozen direct dependency declarations. /// diff --git a/src/content/assets/Inno.Assets/Serialization/AssetReferenceProtocol.cs b/src/content/assets/Inno.Assets/Serialization/AssetReferenceProtocol.cs index 943c5efa7..d39099375 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetReferenceProtocol.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetReferenceProtocol.cs @@ -10,5 +10,5 @@ public static class AssetReferenceProtocol /// /// Gets the stable asset reference kind registered in shared reference catalogs. /// - public static ReferenceKindId id { get; } = new("inno.reference.asset"); + public static ReferenceKindID id { get; } = new("inno.reference.asset"); } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs b/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs index 54380530c..a35c3359a 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; namespace Inno.Assets; diff --git a/src/content/assets/Inno.Assets/Serialization/IAssetPropertyStateResolver.cs b/src/content/assets/Inno.Assets/Serialization/IAssetPropertyStateResolver.cs index 53666cf0f..f263e6c86 100644 --- a/src/content/assets/Inno.Assets/Serialization/IAssetPropertyStateResolver.cs +++ b/src/content/assets/Inno.Assets/Serialization/IAssetPropertyStateResolver.cs @@ -14,7 +14,7 @@ public interface IAssetPropertyStateResolver /// /// Declared native property contract. /// - /// + /// /// Stable identity captured with the properties. /// /// @@ -24,7 +24,7 @@ public interface IAssetPropertyStateResolver /// Detached destination. Referenced assets resolve in this owner. /// void RestoreProperties( - Guid stableTypeId, + Guid stableTypeID, byte[] propertyData, TValue target ) where TValue : class, ISerializable; diff --git a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs index d8a6f08fd..64a2b0972 100644 --- a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs +++ b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs @@ -1,8 +1,8 @@ using System; - +using System.IO; using Inno.Assets; -using Inno.Core.Identity; using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.References; namespace Inno.Assets; @@ -15,7 +15,39 @@ public interface IAssetReferenceResolver : IReferenceResolver /// /// Gets the stable open protocol identifier for persistent asset references. /// - ReferenceKindId IReferenceResolver.kindId => AssetReferenceProtocol.id; + ReferenceKindID IReferenceResolver.kindID => AssetReferenceProtocol.id; + + /// + /// Resolves one serialized asset reference to the canonical object owned by this resolver. + /// + /// + /// The persistent asset identity encoded in the reference. + /// + /// + /// The stable concrete asset type identity encoded in the reference. + /// + /// + /// The optional logical path retained for diagnostics and authoring recovery. + /// + /// + /// The declared property type that the resolved object must satisfy. + /// + /// + /// The serialization property path used when reporting resolution failures. + /// + /// + /// The canonical compatible asset owned by this resolver's generation. + /// + /// + /// Thrown when the reference cannot be resolved to a compatible asset. + /// + AssetObject Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ); /// /// Resolves a backend-neutral reference descriptor through this asset generation. @@ -32,89 +64,60 @@ public interface IAssetReferenceResolver : IReferenceResolver ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) { ArgumentNullException.ThrowIfNull(descriptor); - if (descriptor.kindId != AssetReferenceProtocol.id) + if (descriptor.kindID != AssetReferenceProtocol.id) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Invalid, - diagnostic: $"Asset resolver cannot process reference kind '{descriptor.kindId}'."); + diagnostic: $"Asset resolver cannot process reference kind '{descriptor.kindID}'." + ); } if (descriptor.isUnassigned) + { return new ReferenceResolution(descriptor, ReferenceResolutionState.Unassigned); + } try { AssetObject asset = Resolve( - descriptor.targetPersistentId, - descriptor.expectedStableTypeId, + descriptor.targetPersistentID, + descriptor.expectedStableTypeID, descriptor.lastKnownPath ?? string.Empty, typeof(AssetObject), - "$reference"); - if (asset.identity.persistentId != descriptor.targetPersistentId) + "$reference" + ); + if (asset.identity.persistentID != descriptor.targetPersistentID) { - return new ReferenceResolution(descriptor, ReferenceResolutionState.Invalid, - diagnostic: "The asset resolver returned a different persistent identity."); + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.Invalid, + diagnostic: "The asset resolver returned a different persistent identity." + ); } if (asset.isMissing) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Missing, - diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is unavailable in the current generation."); + diagnostic: $"Asset '{descriptor.targetPersistentID:D}' is unavailable in the current generation." + ); } if (asset.identity.runtimeIdentity is not RuntimeIdentity runtimeIdentity) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Invalid, - diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is not registered in a runtime identity domain."); + diagnostic: $"Asset '{descriptor.targetPersistentID:D}' is not registered in a runtime identity domain." + ); } - return new ReferenceResolution( - descriptor, - ReferenceResolutionState.Resolved, - runtimeIdentity); + return new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { throw; } - catch (Exception exception) when (exception is InvalidOperationException or System.IO.InvalidDataException) + catch (Exception exception) when (exception is InvalidOperationException or InvalidDataException) { - return new ReferenceResolution( - descriptor, - ReferenceResolutionState.Missing, - diagnostic: exception.Message); + return new ReferenceResolution(descriptor, ReferenceResolutionState.Missing, diagnostic: exception.Message); } } - - /// - /// Resolves one serialized asset reference to the canonical object owned by this resolver. - /// - /// - /// The persistent asset identity encoded in the reference. - /// - /// - /// The stable concrete asset type identity encoded in the reference. - /// - /// - /// The optional logical path retained for diagnostics and authoring recovery. - /// - /// - /// The declared property type that the resolved object must satisfy. - /// - /// - /// The serialization property path used when reporting resolution failures. - /// - /// - /// The canonical compatible asset owned by this resolver's generation. - /// - /// - /// Thrown when the reference cannot be resolved to a compatible asset. - /// - AssetObject Resolve( - Guid persistentId, - Guid stableTypeId, - string lastKnownPath, - Type expectedType, - string propertyPath - ); } diff --git a/src/content/assets/Inno.Assets/Types/BinaryAsset.cs b/src/content/assets/Inno.Assets/Types/BinaryAsset.cs index cfc3120df..1cfeb5638 100644 --- a/src/content/assets/Inno.Assets/Types/BinaryAsset.cs +++ b/src/content/assets/Inno.Assets/Types/BinaryAsset.cs @@ -1,27 +1,19 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Assets; /// /// Describes an imported opaque binary payload. /// -[StableTypeId("5298dd91-e9a7-4298-a343-bf8a6c5fc779")] +[StableTypeID("5298dd91-e9a7-4298-a343-bf8a6c5fc779")] public sealed class BinaryAsset : AssetObject { - /// - /// Gets the imported payload length in bytes. - /// - [SerializableProperty] - public int byteLength { get; private set; } - /// /// Creates an empty binary asset descriptor. /// - public BinaryAsset() - { - } + public BinaryAsset() {} /// /// Creates a binary asset descriptor with a byte length. @@ -33,4 +25,10 @@ public BinaryAsset(int byteLength) { this.byteLength = byteLength; } + + /// + /// Gets the imported payload length in bytes. + /// + [SerializableProperty] + public int byteLength { get; private set; } } diff --git a/src/content/assets/Inno.Assets/Types/TextAsset.cs b/src/content/assets/Inno.Assets/Types/TextAsset.cs index 3e0afe351..68583eb1f 100644 --- a/src/content/assets/Inno.Assets/Types/TextAsset.cs +++ b/src/content/assets/Inno.Assets/Types/TextAsset.cs @@ -1,33 +1,19 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Assets; /// /// Stores decoded text content and its language hint. /// -[StableTypeId("907c91cf-215b-42f4-9243-26d9666b231a")] +[StableTypeID("907c91cf-215b-42f4-9243-26d9666b231a")] public sealed class TextAsset : AssetObject { - /// - /// Gets the decoded text content. - /// - [SerializableProperty] - public string content { get; private set; } = string.Empty; - - /// - /// Gets the language or format hint associated with the text. - /// - [SerializableProperty] - public string languageHint { get; private set; } = "plain"; - /// /// Creates an empty text asset. /// - public TextAsset() - { - } + public TextAsset() {} /// /// Creates a text asset with content and an optional language hint. @@ -45,4 +31,16 @@ public TextAsset( this.content = content ?? string.Empty; this.languageHint = languageHint ?? "plain"; } + + /// + /// Gets the decoded text content. + /// + [SerializableProperty] + public string content { get; private set; } = string.Empty; + + /// + /// Gets the language or format hint associated with the text. + /// + [SerializableProperty] + public string languageHint { get; private set; } = "plain"; } diff --git a/src/content/deployment/Inno.Content/ContentEntry.cs b/src/content/deployment/Inno.Content/ContentEntry.cs index 1cf4636c6..f35587f1b 100644 --- a/src/content/deployment/Inno.Content/ContentEntry.cs +++ b/src/content/deployment/Inno.Content/ContentEntry.cs @@ -28,7 +28,9 @@ public ContentEntry( string contentHash ) { if (key.value is null) + { throw new ArgumentException("Content metadata requires an assigned key.", nameof(key)); + } ArgumentOutOfRangeException.ThrowIfNegative(length); this.key = key; this.length = length; @@ -53,11 +55,15 @@ string contentHash internal static string NormalizeHash(string value) { if (value is not { Length: 64 }) + { throw new ArgumentException("Content identity requires a SHA-256 value.", nameof(value)); + } foreach (char character in value) { if (!Uri.IsHexDigit(character)) + { throw new ArgumentException("Content identity requires hexadecimal digits.", nameof(value)); + } } return value.ToUpperInvariant(); } diff --git a/src/content/deployment/Inno.Content/ContentKey.cs b/src/content/deployment/Inno.Content/ContentKey.cs index 661999990..1ae512ac2 100644 --- a/src/content/deployment/Inno.Content/ContentKey.cs +++ b/src/content/deployment/Inno.Content/ContentKey.cs @@ -22,12 +22,16 @@ public ContentKey(string value) foreach (string segment in value.Split('/')) { if (segment.Length == 0 || segment is "." or ".." || segment.EndsWith('.') - || segment.EndsWith(' ') || IsReserved(segment)) + || segment.EndsWith(' ') || IsReserved(segment) + ) { throw new ArgumentException("Content keys require portable relative segments.", nameof(value)); + } foreach (char character in segment) { if (char.IsControl(character) || character is '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|') + { throw new ArgumentException("Content keys contain a nonportable character.", nameof(value)); + } } } this.value = value; @@ -38,7 +42,7 @@ public ContentKey(string value) /// public string? value { get; } - /// + /// public override string ToString() => value ?? string.Empty; private static bool IsReserved(string segment) @@ -46,13 +50,15 @@ private static bool IsReserved(string segment) ReadOnlySpan stem = segment.AsSpan(); int extension = stem.IndexOf('.'); if (extension >= 0) + { stem = stem[..extension]; + } return stem.Equals("CON", StringComparison.OrdinalIgnoreCase) - || stem.Equals("PRN", StringComparison.OrdinalIgnoreCase) - || stem.Equals("AUX", StringComparison.OrdinalIgnoreCase) - || stem.Equals("NUL", StringComparison.OrdinalIgnoreCase) - || (stem.Length == 4 && stem[3] is >= '1' and <= '9' - && (stem[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) - || stem[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))); + || stem.Equals("PRN", StringComparison.OrdinalIgnoreCase) + || stem.Equals("AUX", StringComparison.OrdinalIgnoreCase) + || stem.Equals("NUL", StringComparison.OrdinalIgnoreCase) + || (stem.Length == 4 && stem[3] is >= '1' and <= '9' + && (stem[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) + || stem[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))); } } diff --git a/src/content/deployment/Inno.Content/ContentPackDescriptor.cs b/src/content/deployment/Inno.Content/ContentPackDescriptor.cs index 98f29e932..91ebf26fb 100644 --- a/src/content/deployment/Inno.Content/ContentPackDescriptor.cs +++ b/src/content/deployment/Inno.Content/ContentPackDescriptor.cs @@ -25,7 +25,9 @@ string fileName ) { this.contentHash = ContentEntry.NormalizeHash(contentHash); if (!string.Equals(fileName, $"content-{this.contentHash}.pack", StringComparison.Ordinal)) + { throw new ArgumentException("The pack file name must match its content identity.", nameof(fileName)); + } this.fileName = fileName; } diff --git a/src/content/deployment/Inno.Content/ContentPackIndex.cs b/src/content/deployment/Inno.Content/ContentPackIndex.cs index 93c242125..8c2ce3010 100644 --- a/src/content/deployment/Inno.Content/ContentPackIndex.cs +++ b/src/content/deployment/Inno.Content/ContentPackIndex.cs @@ -29,17 +29,19 @@ public sealed class ContentPackIndex public ContentPackIndex(IEnumerable entries) { ArgumentNullException.ThrowIfNull(entries); - m_byKey = new(); - HashSet folded = new(StringComparer.OrdinalIgnoreCase) { C_INDEX_KEY }; + m_byKey = []; + var folded = new HashSet(StringComparer.OrdinalIgnoreCase) { C_INDEX_KEY }; List ordered = []; foreach (ContentEntry entry in entries) { ArgumentNullException.ThrowIfNull(entry); if (!folded.Add(entry.key.value!)) + { throw new ArgumentException($"Content repeats a reserved or ambiguous key '{entry.key}'.", nameof(entries)); + } m_byKey.Add(entry.key, entry); ordered.Add(entry); - totalLength = checked(totalLength + entry.length); + this.totalLength = checked(totalLength + entry.length); } ordered.Sort(static ( left, @@ -86,7 +88,9 @@ private static void ValidateTree(List entries) for (int separator = key.IndexOf('/'); separator >= 0; separator = key.IndexOf('/', separator + 1)) { if (files.Contains(key[..separator])) + { throw new ArgumentException($"Content uses '{key[..separator]}' as both a file and directory.", nameof(entries)); + } } } } diff --git a/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs b/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs index 96bfa11c7..102e80697 100644 --- a/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs +++ b/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs @@ -28,15 +28,19 @@ SerializationGeneration serialization ) { ArgumentNullException.ThrowIfNull(index); ArgumentNullException.ThrowIfNull(serialization); - return serialization.Encode(writer => writer.WriteObjectArray("entries", index.entries, + return serialization.Encode(writer => writer.WriteObjectArray( + "entries", + index.entries, static ( entryWriter, entry - ) => { + ) => + { entryWriter.Write("key", entry.key.value!); entryWriter.Write("length", entry.length); entryWriter.Write("hash", entry.contentHash); - })); + } + )); } /// @@ -61,9 +65,14 @@ SerializationGeneration serialization ArgumentNullException.ThrowIfNull(serialization); try { - return serialization.Decode(data, reader => new ContentPackIndex(reader.ReadObjectArray("entries") - .Select(static entry => new ContentEntry(new ContentKey(entry.Read("key")), - entry.Read("length"), entry.Read("hash"))))); + return serialization.Decode(data, reader => new ContentPackIndex( + reader.ReadObjectArray("entries") + .Select(static entry => new ContentEntry( + new ContentKey(entry.Read("key")), + entry.Read("length"), + entry.Read("hash") + )) + )); } catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or OverflowException) { diff --git a/src/content/deployment/Inno.Content/ContentPackReader.cs b/src/content/deployment/Inno.Content/ContentPackReader.cs index 948c2058f..dfa815686 100644 --- a/src/content/deployment/Inno.Content/ContentPackReader.cs +++ b/src/content/deployment/Inno.Content/ContentPackReader.cs @@ -57,41 +57,59 @@ public static PackContentStore Open( limits ??= new ContentReadLimits(); cancellationToken.ThrowIfCancellationRequested(); if (!pack.CanRead || !pack.CanSeek) + { throw new ArgumentException("A content pack requires an owned readable seekable stream.", nameof(pack)); + } if (pack.Length > limits.packBytes) + { throw new InvalidDataException("The encoded content pack exceeds its reading budget."); + } pack.Position = 0; string actualHash = Hash(pack, pack.Length, cancellationToken); if (!string.Equals(actualHash, descriptor.contentHash, StringComparison.Ordinal)) + { throw new InvalidDataException("The complete pack bytes do not match their content identity."); + } pack.Position = 0; archive = new ZipArchive(pack, ZipArchiveMode.Read, leaveOpen: false); Dictionary payloads = ReadInventory(archive, limits); - ContentKey indexKey = new(ContentPackIndex.C_INDEX_KEY); + var indexKey = new ContentKey(ContentPackIndex.C_INDEX_KEY); if (!payloads.Remove(indexKey, out ZipArchiveEntry? indexEntry)) + { throw new InvalidDataException("The content pack has no inventory document."); + } if (indexEntry.Length > limits.indexBytes) + { throw new InvalidDataException("The content inventory exceeds its reading budget."); - byte[] indexBytes = new byte[checked((int)indexEntry.Length)]; + } + var indexBytes = new byte[checked((int)indexEntry.Length)]; using (Stream indexStream = indexEntry.Open()) { indexStream.ReadExactly(indexBytes); if (indexStream.ReadByte() != -1) + { throw new InvalidDataException("The content inventory exceeds its declared length."); + } } ContentPackIndex index = ContentPackIndexCodec.Decode(indexBytes, serialization); if (index.entries.Count != payloads.Count || index.entries.Count > limits.entryCount - || index.totalLength > limits.totalBytes) + || index.totalLength > limits.totalBytes + ) { throw new InvalidDataException("The content inventory is incomplete or exceeds its expansion budget."); + } foreach (ContentEntry entry in index.entries) { cancellationToken.ThrowIfCancellationRequested(); if (!payloads.TryGetValue(entry.key, out ZipArchiveEntry? payload) - || payload.Length != entry.length || entry.length > limits.entryBytes) + || payload.Length != entry.length || entry.length > limits.entryBytes + ) { throw new InvalidDataException($"Content entry '{entry.key}' is missing or has an invalid length."); + } using Stream input = payload.Open(); if (!string.Equals(Hash(input, entry.length, cancellationToken), entry.contentHash, StringComparison.Ordinal)) + { throw new InvalidDataException($"Content entry '{entry.key}' does not match its decoded identity."); + } } cancellationToken.ThrowIfCancellationRequested(); return new PackContentStore(archive, descriptor, index, payloads); @@ -99,9 +117,13 @@ public static PackContentStore Open( catch { if (archive is not null) + { archive.Dispose(); + } else + { pack.Dispose(); + } throw; } } @@ -111,14 +133,18 @@ private static Dictionary ReadInventory( ContentReadLimits limits ) { if (archive.Entries.Count > limits.entryCount + 1L) + { throw new InvalidDataException("The archive contains too many entries."); - Dictionary entries = new(); - HashSet folded = new(StringComparer.OrdinalIgnoreCase); + } + Dictionary entries = []; + var folded = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (ZipArchiveEntry entry in archive.Entries) { int mode = (entry.ExternalAttributes >> 16) & 0xF000; if ((mode != 0 && mode != 0x8000) || (entry.ExternalAttributes & 0x10) != 0) + { throw new InvalidDataException($"Archive entry '{entry.FullName}' is not a regular file."); + } ContentKey key; try { @@ -129,7 +155,9 @@ ContentReadLimits limits throw new InvalidDataException($"Archive entry '{entry.FullName}' is not portable.", failure); } if (!folded.Add(key.value!) || !entries.TryAdd(key, entry)) + { throw new InvalidDataException($"The archive repeats an ambiguous content key '{key}'."); + } } return entries; } @@ -149,13 +177,17 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); int read = input.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining)); if (read == 0) + { throw new InvalidDataException("Content ended before its declared length."); + } hash.AppendData(buffer.AsSpan(0, read)); remaining -= read; } cancellationToken.ThrowIfCancellationRequested(); if (input.ReadByte() != -1) + { throw new InvalidDataException("Content exceeds its declared length."); + } return Convert.ToHexString(hash.GetHashAndReset()); } finally diff --git a/src/content/deployment/Inno.Content/ContentReadLease.cs b/src/content/deployment/Inno.Content/ContentReadLease.cs index 6146fca5b..a34274671 100644 --- a/src/content/deployment/Inno.Content/ContentReadLease.cs +++ b/src/content/deployment/Inno.Content/ContentReadLease.cs @@ -29,9 +29,12 @@ public ContentReadLease( Func openRead, Action release ) { - this.entry = entry ?? throw new ArgumentNullException(nameof(entry)); - m_openRead = openRead ?? throw new ArgumentNullException(nameof(openRead)); - m_release = release ?? throw new ArgumentNullException(nameof(release)); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(openRead); + ArgumentNullException.ThrowIfNull(release); + this.entry = entry; + m_openRead = openRead; + m_release = release; } /// @@ -57,7 +60,7 @@ public Stream OpenRead() { Func openRead = m_openRead ?? throw new ObjectDisposedException(nameof(ContentReadLease)); Stream input = openRead() - ?? throw new InvalidOperationException("The content provider returned a null stream."); + ?? throw new InvalidOperationException("The content provider returned a null stream."); if (!input.CanRead) { input.Dispose(); diff --git a/src/content/deployment/Inno.Content/PackContentStore.cs b/src/content/deployment/Inno.Content/PackContentStore.cs index a9a405f56..c684d5931 100644 --- a/src/content/deployment/Inno.Content/PackContentStore.cs +++ b/src/content/deployment/Inno.Content/PackContentStore.cs @@ -28,20 +28,22 @@ Dictionary entries this.index = index; } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } - /// + /// public ContentReadLease Acquire(ContentKey key) { lock (m_sync) { ObjectDisposedException.ThrowIf(m_closed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException($"Content '{key}' does not exist in pack '{descriptor.contentHash}'."); + } m_pins = checked(m_pins + 1); return new ContentReadLease(entry!, () => OpenPinned(key), ReleasePin); } @@ -55,7 +57,9 @@ public void Dispose() lock (m_sync) { if (m_closed) + { return; + } m_closed = true; ReleasePin(); } @@ -76,7 +80,9 @@ private void ReleasePin() lock (m_sync) { if (--m_pins == 0) + { m_archive.Dispose(); + } } } @@ -93,59 +99,70 @@ Stream input m_input = input; } - /// + /// public override bool CanRead => m_input is not null; - /// + + /// public override bool CanSeek => false; - /// + + /// public override bool CanWrite => false; - /// + + /// public override long Length => throw new NotSupportedException(); - /// + + /// public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - /// - public override int Read( - byte[] buffer, - int offset, - int count - ) => Read(buffer.AsSpan(offset, count)); - - /// + /// public override int Read(Span buffer) { lock (m_owner.m_sync) + { return (m_input ?? throw new ObjectDisposedException(nameof(EntryReadStream))).Read(buffer); + } } - /// + /// + public override int Read( + byte[] buffer, + int offset, + int count + ) => Read(buffer.AsSpan(offset, count)); + + /// public override int ReadByte() { lock (m_owner.m_sync) + { return (m_input ?? throw new ObjectDisposedException(nameof(EntryReadStream))).ReadByte(); + } } - /// + /// public override void Flush() => throw new NotSupportedException(); - /// + + /// public override long Seek( long offset, SeekOrigin origin ) => throw new NotSupportedException(); - /// + + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) diff --git a/src/content/references/Inno.References/ContentReadScope.cs b/src/content/references/Inno.References/ContentReadScope.cs index 982012a27..c58079621 100644 --- a/src/content/references/Inno.References/ContentReadScope.cs +++ b/src/content/references/Inno.References/ContentReadScope.cs @@ -36,11 +36,17 @@ public ContentReadScope( ArgumentNullException.ThrowIfNull(contents); Identity[] snapshot = contents.ToArray(); if (snapshot.Any(static identity => identity.runtimeIdentity is null)) + { throw new ArgumentException("Content roots must belong to live identity domains.", nameof(contents)); - if (snapshot.Select(static identity => identity.persistentId).Distinct().Count() != snapshot.Length) + } + if (snapshot.Select(static identity => identity.persistentID).Distinct().Count() != snapshot.Length) + { throw new ArgumentException("Content root persistent identities must be unique.", nameof(contents)); - if (activeContent is Guid active && !snapshot.Any(identity => identity.persistentId == active)) + } + if (activeContent is Guid active && !snapshot.Any(identity => identity.persistentID == active)) + { throw new ArgumentException("The active content must belong to this scope.", nameof(activeContent)); + } m_contents = Array.AsReadOnly(snapshot); this.activeContent = activeContent; } @@ -75,11 +81,15 @@ public ContentReadScope( /// /// Lookup occurs off the owning control thread. /// - public IReadOnlyList GetValues() where TValue : IdentityObject + public IReadOnlyList GetValues() + where TValue : IdentityObject { EnsureActive(); - return Array.AsReadOnly(m_contents.Select(static identity => identity.Resolve()) - .OfType().ToArray()); + return Array.AsReadOnly( + m_contents.Select(static identity => identity.Resolve()) + .OfType() + .ToArray() + ); } /// @@ -111,8 +121,10 @@ out TValue? value EnsureActive(); foreach (Identity identity in m_contents) { - if (identity.persistentId != id) + if (identity.persistentID != id) + { continue; + } value = identity.Resolve(); return value is not null; } @@ -129,6 +141,8 @@ private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Content lookup requires its owning control thread."); + } } } diff --git a/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs b/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs index de411a4fd..2efd98eb8 100644 --- a/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs +++ b/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs @@ -15,5 +15,4 @@ public interface IReferenceRecoveryParticipant : IGenerationChange /// The complete immutable set of candidate recovery changes; optional missing slots remain preserved. /// void Validate(IReadOnlyList changes); - } diff --git a/src/content/references/Inno.References/IReferenceResolver.cs b/src/content/references/Inno.References/IReferenceResolver.cs index 9ace13611..d1325262d 100644 --- a/src/content/references/Inno.References/IReferenceResolver.cs +++ b/src/content/references/Inno.References/IReferenceResolver.cs @@ -8,13 +8,13 @@ public interface IReferenceResolver /// /// Gets the unique reference kind implemented by this resolver. /// - ReferenceKindId kindId { get; } + ReferenceKindID kindID { get; } /// /// Resolves a descriptor without mutating its owner or the authoritative catalog. /// /// - /// The descriptor whose matches this resolver. + /// The descriptor whose matches this resolver. /// /// /// A complete resolution result that preserves the supplied descriptor. diff --git a/src/content/references/Inno.References/ReferenceCatalog.cs b/src/content/references/Inno.References/ReferenceCatalog.cs index 02ee68e77..762f67953 100644 --- a/src/content/references/Inno.References/ReferenceCatalog.cs +++ b/src/content/references/Inno.References/ReferenceCatalog.cs @@ -8,11 +8,11 @@ namespace Inno.References; /// public sealed class ReferenceCatalog { - private readonly IReadOnlyDictionary m_resolvers; + private readonly IReadOnlyDictionary m_resolvers; private ReferenceCatalog( long generation, - IReadOnlyDictionary resolvers + IReadOnlyDictionary resolvers ) { this.generation = generation; m_resolvers = resolvers; @@ -21,13 +21,52 @@ IReadOnlyDictionary resolvers /// /// Gets an empty initial reference catalog. /// - public static ReferenceCatalog empty { get; } = new(0, new Dictionary()); + public static ReferenceCatalog empty { get; } = new(0, new Dictionary()); /// /// Gets the owner-assigned generation represented by this snapshot. /// public long generation { get; } + /// + /// Resolves a persistent descriptor using the resolver selected by its kind. + /// + /// + /// The descriptor to resolve. + /// + /// + /// The resolver result, an unassigned result for an empty target, or a missing result when no resolver is installed. + /// + /// + /// Thrown when is null. + /// + /// + /// Thrown when a resolver returns a result for a different descriptor. + /// + public ReferenceResolution Resolve(ReferenceDescriptor descriptor) + { + ArgumentNullException.ThrowIfNull(descriptor); + if (descriptor.isUnassigned) + { + return new ReferenceResolution(descriptor, ReferenceResolutionState.Unassigned); + } + if (!m_resolvers.TryGetValue(descriptor.kindID, out IReferenceResolver? resolver)) + { + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.Missing, + diagnostic: $"No resolver for reference kind '{descriptor.kindID}' is active in generation {generation}." + ); + } + ReferenceResolution result = resolver.Resolve(descriptor) + ?? throw new InvalidOperationException($"Reference resolver '{descriptor.kindID}' returned null."); + if (!ReferenceEquals(result.descriptor, descriptor)) + { + throw new InvalidOperationException($"Reference resolver '{descriptor.kindID}' replaced the supplied descriptor."); + } + return result; + } + /// /// Builds a complete resolver generation and rejects duplicate protocol identifiers. /// @@ -54,51 +93,23 @@ public static ReferenceCatalog Create( IEnumerable resolvers ) { if (generation <= 0) + { throw new ArgumentOutOfRangeException(nameof(generation), "A published reference catalog requires a positive generation."); + } ArgumentNullException.ThrowIfNull(resolvers); - var byKind = new Dictionary(); + var byKind = new Dictionary(); foreach (IReferenceResolver? resolver in resolvers) { ArgumentNullException.ThrowIfNull(resolver); - if (!resolver.kindId.isValid) + if (!resolver.kindID.isValid) + { throw new InvalidOperationException("A reference resolver declared an invalid kind identifier."); - if (!byKind.TryAdd(resolver.kindId, resolver)) - throw new InvalidOperationException($"Reference kind '{resolver.kindId}' has more than one resolver."); + } + if (!byKind.TryAdd(resolver.kindID, resolver)) + { + throw new InvalidOperationException($"Reference kind '{resolver.kindID}' has more than one resolver."); + } } return new ReferenceCatalog(generation, byKind); } - - /// - /// Resolves a persistent descriptor using the resolver selected by its kind. - /// - /// - /// The descriptor to resolve. - /// - /// - /// The resolver result, an unassigned result for an empty target, or a missing result when no resolver is installed. - /// - /// - /// Thrown when is null. - /// - /// - /// Thrown when a resolver returns a result for a different descriptor. - /// - public ReferenceResolution Resolve(ReferenceDescriptor descriptor) - { - ArgumentNullException.ThrowIfNull(descriptor); - if (descriptor.isUnassigned) - return new ReferenceResolution(descriptor, ReferenceResolutionState.Unassigned); - if (!m_resolvers.TryGetValue(descriptor.kindId, out IReferenceResolver? resolver)) - { - return new ReferenceResolution( - descriptor, - ReferenceResolutionState.Missing, - diagnostic: $"No resolver for reference kind '{descriptor.kindId}' is active in generation {generation}."); - } - ReferenceResolution result = resolver.Resolve(descriptor) - ?? throw new InvalidOperationException($"Reference resolver '{descriptor.kindId}' returned null."); - if (!ReferenceEquals(result.descriptor, descriptor)) - throw new InvalidOperationException($"Reference resolver '{descriptor.kindId}' replaced the supplied descriptor."); - return result; - } } diff --git a/src/content/references/Inno.References/ReferenceDescriptor.cs b/src/content/references/Inno.References/ReferenceDescriptor.cs index a159add7a..2ff0195c2 100644 --- a/src/content/references/Inno.References/ReferenceDescriptor.cs +++ b/src/content/references/Inno.References/ReferenceDescriptor.cs @@ -10,13 +10,13 @@ public sealed class ReferenceDescriptor /// /// Creates a persistent reference descriptor. /// - /// + /// /// The open protocol used to resolve the target. /// - /// + /// /// The target object's persistent identity, or an empty value for an explicitly unassigned slot. /// - /// + /// /// An optional stable type constraint interpreted by the resolver. /// /// @@ -26,20 +26,22 @@ public sealed class ReferenceDescriptor /// Optional non-authoritative source path retained for diagnostics. /// /// - /// Thrown when is invalid. + /// Thrown when is invalid. /// public ReferenceDescriptor( - ReferenceKindId kindId, - Guid targetPersistentId, - Guid expectedStableTypeId = default, + ReferenceKindID kindID, + Guid targetPersistentID, + Guid expectedStableTypeID = default, string? lastKnownName = null, string? lastKnownPath = null ) { - if (!kindId.isValid) - throw new ArgumentException("A reference descriptor requires a valid kind identifier.", nameof(kindId)); - this.kindId = kindId; - this.targetPersistentId = targetPersistentId; - this.expectedStableTypeId = expectedStableTypeId; + if (!kindID.isValid) + { + throw new ArgumentException("A reference descriptor requires a valid kind identifier.", nameof(kindID)); + } + this.kindID = kindID; + this.targetPersistentID = targetPersistentID; + this.expectedStableTypeID = expectedStableTypeID; this.lastKnownName = lastKnownName; this.lastKnownPath = lastKnownPath; } @@ -47,17 +49,17 @@ public ReferenceDescriptor( /// /// Gets the protocol used to resolve this reference. /// - public ReferenceKindId kindId { get; } + public ReferenceKindID kindID { get; } /// /// Gets the persistent identity of the intended target, or an empty value when unassigned. /// - public Guid targetPersistentId { get; } + public Guid targetPersistentID { get; } /// /// Gets the optional stable type constraint interpreted by the selected resolver. /// - public Guid expectedStableTypeId { get; } + public Guid expectedStableTypeID { get; } /// /// Gets optional display text retained only for diagnostics and missing-state presentation. @@ -72,5 +74,5 @@ public ReferenceDescriptor( /// /// Gets whether the user explicitly left this reference unassigned. /// - public bool isUnassigned => targetPersistentId == Guid.Empty; + public bool isUnassigned => targetPersistentID == Guid.Empty; } diff --git a/src/content/references/Inno.References/ReferenceKey.cs b/src/content/references/Inno.References/ReferenceKey.cs index 576a6963b..9966bcb94 100644 --- a/src/content/references/Inno.References/ReferenceKey.cs +++ b/src/content/references/Inno.References/ReferenceKey.cs @@ -10,7 +10,7 @@ namespace Inno.References; /// /// Creates a key for one reference slot. /// - /// + /// /// The persistent identity of the object that owns the slot. /// /// @@ -20,21 +20,25 @@ namespace Inno.References; /// Thrown when the owner identity or path is empty. /// public ReferenceKey( - Guid ownerPersistentId, + Guid ownerPersistentID, string path ) { - if (ownerPersistentId == Guid.Empty) - throw new ArgumentException("A reference key requires a non-empty owner identity.", nameof(ownerPersistentId)); + if (ownerPersistentID == Guid.Empty) + { + throw new ArgumentException("A reference key requires a non-empty owner identity.", nameof(ownerPersistentID)); + } if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A reference key requires a non-empty stable path.", nameof(path)); - this.ownerPersistentId = ownerPersistentId; + } + this.ownerPersistentID = ownerPersistentID; this.path = path; } /// /// Gets the persistent identity of the object that owns this reference slot. /// - public Guid ownerPersistentId { get; } + public Guid ownerPersistentID { get; } /// /// Gets the stable property or structural path inside the owner. @@ -51,7 +55,7 @@ string path /// when the owner identity and path are equal; otherwise, . /// public bool Equals(ReferenceKey other) - => ownerPersistentId == other.ownerPersistentId && string.Equals(path, other.path, StringComparison.Ordinal); + => ownerPersistentID == other.ownerPersistentID && string.Equals(path, other.path, StringComparison.Ordinal); /// /// Determines whether an object identifies the same owner slot. @@ -70,7 +74,7 @@ public bool Equals(ReferenceKey other) /// /// A hash code consistent with reference-key equality. /// - public override int GetHashCode() => HashCode.Combine(ownerPersistentId, StringComparer.Ordinal.GetHashCode(path ?? string.Empty)); + public override int GetHashCode() => HashCode.Combine(ownerPersistentID, StringComparer.Ordinal.GetHashCode(path ?? string.Empty)); /// /// Formats this slot identity for diagnostics. @@ -78,7 +82,7 @@ public bool Equals(ReferenceKey other) /// /// The owner identity followed by the stable slot path. /// - public override string ToString() => $"{ownerPersistentId:D}:{path}"; + public override string ToString() => $"{ownerPersistentID:D}:{path}"; /// /// Determines whether two reference keys are equal. diff --git a/src/content/references/Inno.References/ReferenceKindId.cs b/src/content/references/Inno.References/ReferenceKindID.cs similarity index 90% rename from src/content/references/Inno.References/ReferenceKindId.cs rename to src/content/references/Inno.References/ReferenceKindID.cs index ace24aa1c..a796f0475 100644 --- a/src/content/references/Inno.References/ReferenceKindId.cs +++ b/src/content/references/Inno.References/ReferenceKindID.cs @@ -5,7 +5,7 @@ namespace Inno.References; /// /// Identifies an open reference-resolution protocol independently of its current implementation. /// -public readonly struct ReferenceKindId : IEquatable +public readonly struct ReferenceKindID : IEquatable { /// /// Creates a stable reference kind identifier. @@ -16,10 +16,12 @@ namespace Inno.References; /// /// Thrown when is empty or contains surrounding whitespace. /// - public ReferenceKindId(string value) + public ReferenceKindID(string value) { if (string.IsNullOrWhiteSpace(value) || !string.Equals(value, value.Trim(), StringComparison.Ordinal)) + { throw new ArgumentException("A reference kind identifier must be non-empty and trimmed.", nameof(value)); + } this.value = value; } @@ -42,7 +44,7 @@ public ReferenceKindId(string value) /// /// when the identifiers are equal; otherwise, . /// - public bool Equals(ReferenceKindId other) => string.Equals(value, other.value, StringComparison.Ordinal); + public bool Equals(ReferenceKindID other) => string.Equals(value, other.value, StringComparison.Ordinal); /// /// Determines whether an object contains the same reference kind identifier. @@ -53,7 +55,7 @@ public ReferenceKindId(string value) /// /// when the object is an equal identifier; otherwise, . /// - public override bool Equals(object? obj) => obj is ReferenceKindId other && Equals(other); + public override bool Equals(object? obj) => obj is ReferenceKindID other && Equals(other); /// /// Computes an ordinal hash code for this identifier. @@ -84,8 +86,8 @@ public ReferenceKindId(string value) /// when the identifiers are equal; otherwise, . /// public static bool operator ==( - ReferenceKindId left, - ReferenceKindId right + ReferenceKindID left, + ReferenceKindID right ) => left.Equals(right); /// @@ -101,7 +103,7 @@ ReferenceKindId right /// when the identifiers are different; otherwise, . /// public static bool operator !=( - ReferenceKindId left, - ReferenceKindId right + ReferenceKindID left, + ReferenceKindID right ) => !left.Equals(right); } diff --git a/src/content/references/Inno.References/ReferenceRecoveryChange.cs b/src/content/references/Inno.References/ReferenceRecoveryChange.cs index 1240f5f00..e80512417 100644 --- a/src/content/references/Inno.References/ReferenceRecoveryChange.cs +++ b/src/content/references/Inno.References/ReferenceRecoveryChange.cs @@ -1,3 +1,5 @@ +using System; + namespace Inno.References; /// @@ -21,8 +23,8 @@ public ReferenceRecoveryChange( SerializedMissingState missingState, ReferenceResolution resolution ) { - System.ArgumentNullException.ThrowIfNull(missingState); - System.ArgumentNullException.ThrowIfNull(resolution); + ArgumentNullException.ThrowIfNull(missingState); + ArgumentNullException.ThrowIfNull(resolution); this.missingState = missingState; this.resolution = resolution; } diff --git a/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs b/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs index fd5685cd4..dc0d8b665 100644 --- a/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs +++ b/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs @@ -22,7 +22,7 @@ public sealed class ReferenceRecoveryTransaction : IGenerationChange private Phase m_phase; private int m_preparedCount; private Exception? m_retirementFailure; - private IReadOnlyList m_changes = Array.Empty(); + private IReadOnlyList m_changes = []; /// /// Captures neutral slots and ordered domain owners without resolving or mutating live state. @@ -56,12 +56,16 @@ IEnumerable participants foreach (SerializedMissingState state in m_states) { ArgumentNullException.ThrowIfNull(state); - if (state.key.ownerPersistentId == Guid.Empty || string.IsNullOrWhiteSpace(state.key.path) || - !keys.Add(state.key)) + if (state.key.ownerPersistentID == Guid.Empty || string.IsNullOrWhiteSpace(state.key.path) + || !keys.Add(state.key) + ) { throw new ArgumentException($"Invalid or duplicate recovery slot '{state.key}'.", nameof(missingStates)); + } } foreach (IReferenceRecoveryParticipant participant in m_participants) + { ArgumentNullException.ThrowIfNull(participant); + } m_catalog = catalog; } @@ -99,11 +103,16 @@ public void Apply() RequirePhase(Phase.Prepared); m_phase = Phase.Applying; foreach (IReferenceRecoveryParticipant participant in m_participants) + { Invoke(participant.Apply); - Invoke(() => m_changes = Array.AsReadOnly(m_states.Select(state => - new ReferenceRecoveryChange(state, m_catalog!.Resolve(state.descriptor))).ToArray())); + } + Invoke(() => m_changes = Array.AsReadOnly( + m_states.Select(state => new ReferenceRecoveryChange(state, m_catalog!.Resolve(state.descriptor))).ToArray() + )); foreach (IReferenceRecoveryParticipant participant in m_participants) + { Invoke(() => participant.Validate(m_changes)); + } m_phase = Phase.Applied; } @@ -142,15 +151,21 @@ public void RollbackStructure() { EnsureOwner(); if (m_phase == Phase.RolledBack) + { return; + } if (m_phase is Phase.Finished or Phase.Finalizing or Phase.RollingBack) + { throw new InvalidOperationException("A completed recovery transaction cannot be rolled back."); + } m_phase = Phase.RollingBack; List failures = []; for (int index = m_preparedCount - 1; index >= 0; index--) + { Attempt(m_participants[index].RollbackStructure, failures); + } m_phase = Phase.RolledBack; - m_changes = Array.Empty(); + m_changes = []; ThrowFailures(failures, "Reference recovery structure rollback failed."); } @@ -179,12 +194,16 @@ private void RunTerminalPhase(bool restore) if (restore) { for (int index = m_preparedCount - 1; index >= 0; index--) + { Attempt(m_participants[index].RestorePreviousState, failures); + } } else { foreach (IReferenceRecoveryParticipant participant in m_participants) + { Attempt(participant.Complete, failures); + } } m_phase = Phase.Finished; m_catalog = null; @@ -218,7 +237,10 @@ ICollection failures { if (failures.Count > 0) { - m_retirementFailure = new AggregateException("Reference recovery remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + m_retirementFailure = new AggregateException( + "Reference recovery remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); throw m_retirementFailure; } throw; @@ -229,27 +251,35 @@ ICollection failures } } - private static void ThrowFailures( - List failures, - string message - ) { - if (failures.Count > 0) - throw new AggregateException(message, failures); - } - private void RequirePhase(Phase phase) { EnsureOwner(); if (m_phase != phase) + { throw new InvalidOperationException($"Recovery phase is '{m_phase}', expected '{phase}'."); + } } private void EnsureOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Reference recovery must run on its capture thread."); + } if (m_retirementFailure is not null) + { throw m_retirementFailure; + } + } + + private static void ThrowFailures( + List failures, + string message + ) { + if (failures.Count > 0) + { + throw new AggregateException(message, failures); + } } private enum Phase { Captured, Preparing, Prepared, Applying, Applied, RollingBack, RolledBack, Finalizing, Finished } diff --git a/src/content/references/Inno.References/ReferenceResolution.cs b/src/content/references/Inno.References/ReferenceResolution.cs index 8fc087be3..73b3b5154 100644 --- a/src/content/references/Inno.References/ReferenceResolution.cs +++ b/src/content/references/Inno.References/ReferenceResolution.cs @@ -37,7 +37,9 @@ public ReferenceResolution( ) { ArgumentNullException.ThrowIfNull(descriptor); if ((state == ReferenceResolutionState.Resolved) != runtimeIdentity.HasValue) + { throw new ArgumentException("Only a resolved reference can carry a runtime identity.", nameof(runtimeIdentity)); + } this.descriptor = descriptor; this.state = state; this.runtimeIdentity = runtimeIdentity; diff --git a/src/content/references/Inno.References/ReferenceResolutionState.cs b/src/content/references/Inno.References/ReferenceResolutionState.cs index e72f69010..bae901c56 100644 --- a/src/content/references/Inno.References/ReferenceResolutionState.cs +++ b/src/content/references/Inno.References/ReferenceResolutionState.cs @@ -9,22 +9,18 @@ public enum ReferenceResolutionState /// The slot has no assigned target. /// Unassigned, - /// /// The current generation resolved a compatible live target. /// Resolved, - /// /// The intended target is temporarily unavailable. /// Missing, - /// /// The intended target exists but does not satisfy the stable type constraint. /// TypeMismatch, - /// /// The descriptor or authoritative source is invalid. /// diff --git a/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs b/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs index 4c2f4792a..fc8cbfd7c 100644 --- a/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs +++ b/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; @@ -24,9 +23,12 @@ internal void Validate(string expectedKind) if (!string.Equals(resourceKind, expectedKind, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Engine resource kind '{resourceKind}' does not match expected kind '{expectedKind}'."); + $"Engine resource kind '{resourceKind}' does not match expected kind '{expectedKind}'." + ); } if (payload.Length == 0) + { throw new InvalidOperationException($"Engine resource '{resourceKind}' has an empty graph payload."); + } } } diff --git a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs index 6f28d9d2c..45984b8b3 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -16,12 +15,12 @@ namespace Inno.Scene.Assets.Importers; [AssetImporter("inno.engine.prefab")] internal sealed class PrefabAssetImporter : AssetImporter { - private static readonly IReadOnlyList s_extensions = new[] { ".iprefab" }; + private static readonly IReadOnlyList EXTENSIONS = new[] { ".iprefab" }; /// /// Gets the normalized source extensions accepted by this importer. /// - public override IReadOnlyList supportedExtensions => s_extensions; + public override IReadOnlyList supportedExtensions => EXTENSIONS; /// /// Imports source content into a validated runtime asset and artifact set. @@ -44,43 +43,49 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { EngineResourceEnvelope envelope = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); envelope.Validate(EngineResourceEnvelope.C_PREFAB_KIND); AssetDependency[] dependencies = envelope.dependencies; PrefabAsset asset = PrefabAsset.CreateImported(envelope.payload, dependencies); for (int i = 0; i < dependencies.Length; i++) + { output.DependsOnAsset(dependencies[i]); + } output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Writes a validated asset representation to its writable source mount. /// + /// + /// The generation-bound source export services. + /// /// /// The validated asset instance exported by this operation. /// - /// - /// The generation-bound source export services. + /// + /// The token that cancels the operation before it commits. /// /// /// An asynchronous operation that completes after all requested work has finished. /// - /// - /// The token that cancels the operation before it commits. - /// protected override ValueTask?> ExportAsync( AssetExportContext context, PrefabAsset asset, CancellationToken cancellationToken ) { EngineAssetContent content = asset.CaptureContent(); - return ValueTask.FromResult?>(context.serialization.Serialize( - new EngineResourceEnvelope - { - resourceKind = EngineResourceEnvelope.C_PREFAB_KIND, - payload = content.GetPayload(), - dependencies = content.GetDependencies() - })); + return ValueTask.FromResult?>( + context.serialization.Serialize( + new EngineResourceEnvelope + { + resourceKind = EngineResourceEnvelope.C_PREFAB_KIND, + payload = content.GetPayload(), + dependencies = content.GetDependencies() + } + ) + ); } } diff --git a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs index cad2100bf..e9832d483 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -16,12 +15,12 @@ namespace Inno.Scene.Assets.Importers; [AssetImporter("inno.engine.scene")] internal sealed class SceneAssetImporter : AssetImporter { - private static readonly IReadOnlyList s_extensions = new[] { ".iscene" }; + private static readonly IReadOnlyList EXTENSIONS = new[] { ".iscene" }; /// /// Gets the normalized source extensions accepted by this importer. /// - public override IReadOnlyList supportedExtensions => s_extensions; + public override IReadOnlyList supportedExtensions => EXTENSIONS; /// /// Imports source content into a validated runtime asset and artifact set. @@ -44,43 +43,49 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { EngineResourceEnvelope envelope = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); envelope.Validate(EngineResourceEnvelope.C_SCENE_KIND); AssetDependency[] dependencies = envelope.dependencies; SceneAsset asset = SceneAsset.CreateImported(envelope.payload, dependencies); for (int i = 0; i < dependencies.Length; i++) + { output.DependsOnAsset(dependencies[i]); + } output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Writes a validated asset representation to its writable source mount. /// + /// + /// The generation-bound source export services. + /// /// /// The validated asset instance exported by this operation. /// - /// - /// The generation-bound source export services. + /// + /// The token that cancels the operation before it commits. /// /// /// An asynchronous operation that completes after all requested work has finished. /// - /// - /// The token that cancels the operation before it commits. - /// protected override ValueTask?> ExportAsync( AssetExportContext context, SceneAsset asset, CancellationToken cancellationToken ) { EngineAssetContent content = asset.CaptureContent(); - return ValueTask.FromResult?>(context.serialization.Serialize( - new EngineResourceEnvelope - { - resourceKind = EngineResourceEnvelope.C_SCENE_KIND, - payload = content.GetPayload(), - dependencies = content.GetDependencies() - })); + return ValueTask.FromResult?>( + context.serialization.Serialize( + new EngineResourceEnvelope + { + resourceKind = EngineResourceEnvelope.C_SCENE_KIND, + payload = content.GetPayload(), + dependencies = content.GetDependencies() + } + ) + ); } } diff --git a/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs b/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs index a608a7b55..0d7757ea2 100644 --- a/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs +++ b/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs @@ -31,7 +31,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Engine asset content cannot be empty.", nameof(payload)); + } m_payload = payload.ToArray(); m_dependencies = dependencies.ToArray(); } diff --git a/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs b/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs index b2ddcb9b3..7f8865f59 100644 --- a/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs +++ b/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene.Components; using Inno.Scripting.Api; @@ -14,46 +13,10 @@ namespace Inno.Scene; /// /// Stores a persistent game object subtree that can be instantiated repeatedly. /// -[StableTypeId("21d5a292-cc2a-4c79-879d-e4ca5ca6844f")] +[StableTypeID("21d5a292-cc2a-4c79-879d-e4ca5ca6844f")] public sealed class PrefabAsset : AssetObject { private byte[] m_pendingPayload = []; - [SerializableProperty] - internal AssetDependency[] sourceDependencies { get; set; } = []; - - /// - /// Captures a game object subtree into a new unsaved prefab asset. - /// - /// - /// Prefab source root. - /// - /// - /// The serialization registry that owns the active prefab converter generation. - /// - /// - /// The runtime asset generation used to resolve persistent references in the prefab graph. - /// - /// - /// A prefab asset ready to save. - /// - [ScriptingApiIgnore] - public static PrefabAsset Capture( - GameObject root, - SerializationRegistry serialization, - IAssetReferenceResolver assets - ) { - ArgumentNullException.ThrowIfNull(root); - ArgumentNullException.ThrowIfNull(serialization); - ArgumentNullException.ThrowIfNull(assets); - var dependencyCollection = new AssetDependencyCollection(); - SerializationContext context = AssetSerializationContext.Create(assets, dependencyCollection); - byte[] payload = serialization.Serialize(root, context); - return new PrefabAsset - { - m_pendingPayload = payload, - sourceDependencies = dependencyCollection.dependencies.ToArray() - }; - } /// /// Instantiates this prefab into a scene using newly generated object identities. @@ -84,18 +47,67 @@ public GameObject Instantiate( ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new InvalidOperationException("The prefab parent must belong to the target scene."); + } SerializationContext context = AssetSerializationContext.Create(assets) .With(scene) .With(this); GameObject root = serialization.Deserialize(GetPayload(), context); if (parent is not null) + { scene.SetParent(root.transform, parent, worldPositionStays: false); + } if (!string.IsNullOrWhiteSpace(assetPath.localPath)) + { root.name = Path.GetFileNameWithoutExtension(assetPath.localPath); + } return root; } + /// + /// Captures the immutable runtime payload and dependency descriptors required by the prefab asset pipeline. + /// + /// + /// A detached authoring-content snapshot owned by the caller. + /// + [ScriptingApiIgnore] + public EngineAssetContent CaptureContent() => new(GetPayload(), sourceDependencies); + + /// + /// Captures a game object subtree into a new unsaved prefab asset. + /// + /// + /// Prefab source root. + /// + /// + /// The serialization registry that owns the active prefab converter generation. + /// + /// + /// The runtime asset generation used to resolve persistent references in the prefab graph. + /// + /// + /// A prefab asset ready to save. + /// + [ScriptingApiIgnore] + public static PrefabAsset Capture( + GameObject root, + SerializationRegistry serialization, + IAssetReferenceResolver assets + ) { + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(assets); + var dependencyCollection = new AssetDependencyCollection(); + SerializationContext context = AssetSerializationContext.Create(assets, dependencyCollection); + byte[] payload = serialization.Serialize(root, context); + return new PrefabAsset + { + m_pendingPayload = payload, + sourceDependencies = dependencyCollection.dependencies.ToArray() + }; + } + /// /// Creates an imported prefab asset from validated runtime content produced by the prefab asset pipeline. /// @@ -115,7 +127,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Imported prefab content cannot be empty.", nameof(payload)); + } return new PrefabAsset { m_pendingPayload = payload.ToArray(), @@ -123,22 +137,19 @@ IReadOnlyList dependencies }; } - /// - /// Captures the immutable runtime payload and dependency descriptors required by the prefab asset pipeline. - /// - /// - /// A detached authoring-content snapshot owned by the caller. - /// - [ScriptingApiIgnore] - public EngineAssetContent CaptureContent() => new(GetPayload(), sourceDependencies); + [SerializableProperty] + internal AssetDependency[] sourceDependencies { get; set; } = []; private byte[] GetPayload() { if (!runtimePayload.IsEmpty) + { return runtimePayload.ToArray(); + } if (m_pendingPayload.Length != 0) + { return (byte[])m_pendingPayload.Clone(); + } throw new InvalidOperationException($"Prefab asset '{assetPath}' does not contain an imported or pending prefab payload."); } - } diff --git a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs index a447a4100..deb80d32b 100644 --- a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs +++ b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs @@ -2,48 +2,20 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; + namespace Inno.Scene; /// /// Stores imported scene source that can create independent runtime scenes. /// -[StableTypeId("56815f6e-87bb-421b-af5f-c43b9171ce84")] +[StableTypeID("56815f6e-87bb-421b-af5f-c43b9171ce84")] public sealed class SceneAsset : AssetObject { private byte[] m_pendingPayload = []; - [SerializableProperty] - internal AssetDependency[] sourceDependencies { get; set; } = []; - - /// - /// Captures a runtime scene into a new unsaved scene asset. - /// - /// - /// Scene to capture. - /// - /// - /// The serialization registry that owns the active scene converter generation. - /// - /// - /// The asset database generation used to resolve references while collecting dependencies. - /// - /// - /// A detached scene asset that an authoring asset database can save. - /// - [ScriptingApiIgnore] - public static SceneAsset Capture( - GameScene scene, - SerializationRegistry serialization, - IAssetReferenceResolver assets - ) { - var asset = new SceneAsset(); - asset.CaptureFrom(scene, serialization, assets); - return asset; - } /// /// Replaces the pending source content with a fresh capture while preserving this asset identity. @@ -75,15 +47,15 @@ IAssetReferenceResolver assets /// /// Creates an unloaded runtime scene and acquires its hard asset dependencies. /// - /// - /// A newly allocated scene. - /// /// /// The serialization registry that owns the active scene converter generation. /// /// /// The runtime asset generation used to resolve persistent references in the scene graph. /// + /// + /// A newly allocated scene. + /// [ScriptingApiIgnore] public GameScene Instantiate( SerializationRegistry serialization, @@ -95,10 +67,47 @@ IAssetReferenceResolver assets .With(this); GameScene scene = serialization.Deserialize(GetPayload(), context); if (!string.IsNullOrWhiteSpace(assetPath.localPath)) + { scene.name = Path.GetFileNameWithoutExtension(assetPath.localPath); + } return scene; } + /// + /// Captures the immutable runtime payload and dependency descriptors required by the scene asset pipeline. + /// + /// + /// A detached authoring-content snapshot owned by the caller. + /// + [ScriptingApiIgnore] + public EngineAssetContent CaptureContent() => new(GetPayload(), sourceDependencies); + + /// + /// Captures a runtime scene into a new unsaved scene asset. + /// + /// + /// Scene to capture. + /// + /// + /// The serialization registry that owns the active scene converter generation. + /// + /// + /// The asset database generation used to resolve references while collecting dependencies. + /// + /// + /// A detached scene asset that an authoring asset database can save. + /// + [ScriptingApiIgnore] + public static SceneAsset Capture( + GameScene scene, + SerializationRegistry serialization, + IAssetReferenceResolver assets + ) { + var asset = new SceneAsset(); + asset.CaptureFrom(scene, serialization, assets); + return asset; + } + /// /// Creates an imported scene asset from validated runtime content produced by the scene asset pipeline. /// @@ -118,7 +127,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Imported scene content cannot be empty.", nameof(payload)); + } return new SceneAsset { m_pendingPayload = payload.ToArray(), @@ -126,23 +137,8 @@ IReadOnlyList dependencies }; } - /// - /// Captures the immutable runtime payload and dependency descriptors required by the scene asset pipeline. - /// - /// - /// A detached authoring-content snapshot owned by the caller. - /// - [ScriptingApiIgnore] - public EngineAssetContent CaptureContent() => new(GetPayload(), sourceDependencies); - - private byte[] GetPayload() - { - if (m_pendingPayload.Length != 0) - return (byte[])m_pendingPayload.Clone(); - if (!runtimePayload.IsEmpty) - return runtimePayload.ToArray(); - throw new InvalidOperationException($"Scene asset '{assetPath}' does not contain an imported or pending scene payload."); - } + [SerializableProperty] + internal AssetDependency[] sourceDependencies { get; set; } = []; /// /// Rebuilds runtime-derived state after the serialized asset payload changes. @@ -156,7 +152,18 @@ private byte[] GetPayload() protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_pendingPayload = []; + ) => m_pendingPayload = []; + + private byte[] GetPayload() + { + if (m_pendingPayload.Length != 0) + { + return (byte[])m_pendingPayload.Clone(); + } + if (!runtimePayload.IsEmpty) + { + return runtimePayload.ToArray(); + } + throw new InvalidOperationException($"Scene asset '{assetPath}' does not contain an imported or pending scene payload."); } } diff --git a/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs b/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs index e6c78fbb4..7e740e5fa 100644 --- a/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs +++ b/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -14,14 +13,14 @@ namespace Inno.Scene; /// The scene serializer and script reload pipeline create this placeholder automatically. It does not retain /// the unavailable managed or any object from its collectible assembly load context. /// -[StableTypeId("5f53a311-d54f-4ad1-9f2d-a9bd0da90844")] +[StableTypeID("5f53a311-d54f-4ad1-9f2d-a9bd0da90844")] [AllowMultipleComponent] public sealed class MissingGameComponent : GameComponent { private byte[] m_serializedState; private AssetDependency[] m_dependencies; - private IReadOnlyDictionary m_referenceAliases = - new Dictionary(); + + private IReadOnlyDictionary m_referenceAliases = new Dictionary(); internal MissingGameComponent( TypeRef missingType, @@ -29,12 +28,14 @@ internal MissingGameComponent( ReadOnlySpan serializedState, IReadOnlyList? dependencies = null ) { - if (missingType.stableId == Guid.Empty) + if (missingType.stableID == Guid.Empty) + { throw new ArgumentException("The missing component type identity cannot be empty.", nameof(missingType)); + } this.missingType = missingType; this.missingTypeName = string.IsNullOrWhiteSpace(missingTypeName) - ? missingType.stableId.ToString("D") - : missingTypeName; + ? missingType.stableID.ToString("D") + : missingTypeName; m_serializedState = serializedState.ToArray(); m_dependencies = dependencies?.ToArray() ?? []; } @@ -49,6 +50,10 @@ internal MissingGameComponent( /// public string missingTypeName { get; } + internal IReadOnlyDictionary referenceAliases => m_referenceAliases; + + internal IReadOnlyList dependencies => m_dependencies; + internal byte[] CaptureSerializedState() => (byte[])m_serializedState.Clone(); internal void RestoreState(SceneElementState state) @@ -61,10 +66,6 @@ internal void RestoreState(SceneElementState state) m_referenceAliases = aliases; } - internal IReadOnlyDictionary referenceAliases => m_referenceAliases; - - internal IReadOnlyList dependencies => m_dependencies; - internal void SetReferenceAliases(IReadOnlyDictionary aliases) { ArgumentNullException.ThrowIfNull(aliases); diff --git a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs index 24ccc44eb..72fa424af 100644 --- a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs +++ b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -14,14 +13,14 @@ namespace Inno.Scene; /// The scene serializer and script reload pipeline create this placeholder automatically. It remains disabled /// and does not retain the unavailable managed or its collectible assembly load context. /// -[StableTypeId("99342f4e-fb2e-49f9-a6a4-3f4e59d23457")] +[StableTypeID("99342f4e-fb2e-49f9-a6a4-3f4e59d23457")] [AllowMultipleSystem] public sealed class MissingGameSystem : GameSystem { private byte[] m_serializedState; private AssetDependency[] m_dependencies; - private IReadOnlyDictionary m_referenceAliases = - new Dictionary(); + + private IReadOnlyDictionary m_referenceAliases = new Dictionary(); internal MissingGameSystem( TypeRef missingType, @@ -29,15 +28,17 @@ internal MissingGameSystem( ReadOnlySpan serializedState, IReadOnlyList? dependencies = null ) { - if (missingType.stableId == Guid.Empty) + if (missingType.stableID == Guid.Empty) + { throw new ArgumentException("The missing system type identity cannot be empty.", nameof(missingType)); + } this.missingType = missingType; this.missingTypeName = string.IsNullOrWhiteSpace(missingTypeName) - ? missingType.stableId.ToString("D") - : missingTypeName; + ? missingType.stableID.ToString("D") + : missingTypeName; m_serializedState = serializedState.ToArray(); m_dependencies = dependencies?.ToArray() ?? []; - enabled = false; + this.enabled = false; } /// @@ -50,6 +51,10 @@ internal MissingGameSystem( /// public string missingTypeName { get; } + internal IReadOnlyDictionary referenceAliases => m_referenceAliases; + + internal IReadOnlyList dependencies => m_dependencies; + internal byte[] CaptureSerializedState() => (byte[])m_serializedState.Clone(); internal void RestoreState(SceneElementState state) @@ -62,10 +67,6 @@ internal void RestoreState(SceneElementState state) m_referenceAliases = aliases; } - internal IReadOnlyDictionary referenceAliases => m_referenceAliases; - - internal IReadOnlyList dependencies => m_dependencies; - internal void SetReferenceAliases(IReadOnlyDictionary aliases) { ArgumentNullException.ThrowIfNull(aliases); diff --git a/src/content/scene/Inno.Scene/Concrete/Transform.cs b/src/content/scene/Inno.Scene/Concrete/Transform.cs index c5d6cad09..35239c229 100644 --- a/src/content/scene/Inno.Scene/Concrete/Transform.cs +++ b/src/content/scene/Inno.Scene/Concrete/Transform.cs @@ -1,23 +1,22 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; - using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene.Components; /// /// Stores local transform data and exposes the scene hierarchy relationship. /// -[StableTypeId("39a944b8-f021-4ac9-9f66-506f15a96848")] +[StableTypeID("39a944b8-f021-4ac9-9f66-506f15a96848")] [SerializationRevision("m_serializationRevision")] public sealed class Transform : GameComponent { - private ulong? m_serializationRevision = 0; private readonly List m_children = []; private readonly ReadOnlyCollection m_readOnlyChildren; + private ulong? m_serializationRevision = 0; private Transform? m_parent; private Vector3 m_localPosition = Vector3.ZERO; private Quaternion m_localRotation = Quaternion.identity; @@ -222,7 +221,9 @@ internal bool IsDescendantOf(Transform ancestor) for (Transform? current = m_parent; current is not null; current = current.m_parent) { if (ReferenceEquals(current, ancestor)) + { return true; + } } return false; } @@ -232,7 +233,9 @@ internal bool IsDescendantOf(Transform ancestor) internal void AddChildDirect(Transform child) { if (!m_children.Contains(child)) + { m_children.Add(child); + } } internal void RemoveChildDirect(Transform child) => m_children.Remove(child); @@ -271,7 +274,8 @@ Vector3 scale m_localScale = new Vector3( SafeDivide(scale.x, parentScale.x), SafeDivide(scale.y, parentScale.y), - SafeDivide(scale.z, parentScale.z)); + SafeDivide(scale.z, parentScale.z) + ); } RecomputeWorldFromLocal(); @@ -291,53 +295,57 @@ internal void RecomputeWorldFromLocal(bool notifyChildren = true) m_worldScale = new Vector3( m_localScale.x * m_parent.m_worldScale.x, m_localScale.y * m_parent.m_worldScale.y, - m_localScale.z * m_parent.m_worldScale.z); + m_localScale.z * m_parent.m_worldScale.z + ); } RecomputeMatrixFromLocal(); - m_worldPosition = new Vector3( - m_localToWorldMatrix.m14, - m_localToWorldMatrix.m24, - m_localToWorldMatrix.m34); + m_worldPosition = new Vector3(m_localToWorldMatrix.m14, m_localToWorldMatrix.m24, m_localToWorldMatrix.m34); if (notifyChildren) + { NotifyChildrenWorldChanged(); + } } private void AdvanceCaptureRevision() { if (m_serializationRevision is { } revision) + { m_serializationRevision = revision == ulong.MaxValue ? null : revision + 1; + } } private void RecomputeMatrixFromLocal() { Matrix localMatrix = Matrix.CreateTranslation(m_localPosition) - * Matrix.CreateFromQuaternion(m_localRotation) - * Matrix.CreateScale(m_localScale); + * Matrix.CreateFromQuaternion(m_localRotation) + * Matrix.CreateScale(m_localScale); m_localToWorldMatrix = m_parent is null - ? localMatrix - : m_parent.m_localToWorldMatrix * localMatrix; + ? localMatrix + : m_parent.m_localToWorldMatrix * localMatrix; } private void NotifyChildrenWorldChanged() { for (int i = 0; i < m_children.Count; i++) + { m_children[i].RecomputeWorldFromLocal(); + } } private static float SafeDivide( float numerator, float denominator - ) - => MathHelper.AlmostEquals(denominator, 0f) ? 0f : numerator / denominator; + ) => MathHelper.AlmostEquals(denominator, 0f) ? 0f : numerator / denominator; private static void EnsureInvertible(Matrix matrix) { if (MathF.Abs(Matrix.Determinant(matrix)) < MathHelper.C_TOLERANCE) { throw new InvalidOperationException( - "A transform hierarchy with zero scale cannot be converted from world space."); + "A transform hierarchy with zero scale cannot be converted from world space." + ); } } } diff --git a/src/content/scene/Inno.Scene/Content/SceneContentSource.cs b/src/content/scene/Inno.Scene/Content/SceneContentSource.cs index c6b94979c..1acedaf12 100644 --- a/src/content/scene/Inno.Scene/Content/SceneContentSource.cs +++ b/src/content/scene/Inno.Scene/Content/SceneContentSource.cs @@ -42,6 +42,6 @@ public static ContentReadScope CreateScope( GameScene? activeScene ) { ArgumentNullException.ThrowIfNull(scenes); - return new ContentReadScope(scenes.Select(static scene => scene.identity), activeScene?.identity.persistentId); + return new ContentReadScope(scenes.Select(static scene => scene.identity), activeScene?.identity.persistentID); } } diff --git a/src/content/scene/Inno.Scene/Core/EngineObject.cs b/src/content/scene/Inno.Scene/Core/EngineObject.cs index 2f5f8886b..848b3457f 100644 --- a/src/content/scene/Inno.Scene/Core/EngineObject.cs +++ b/src/content/scene/Inno.Scene/Core/EngineObject.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.CompilerServices; - using Inno.Core.Identity; namespace Inno.Scene; @@ -17,6 +16,25 @@ public abstract class EngineObject : IdentityObject /// public bool isDestroyed => m_isDestroyed; + /// + /// Compares this instance to another object using reference identity. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when is this instance. + /// + public override bool Equals(object? obj) => ReferenceEquals(this, obj); + + /// + /// Returns a stable runtime reference hash code. + /// + /// + /// The reference hash code. + /// + public override int GetHashCode() => RuntimeHelpers.GetHashCode(this); + /// /// Compares engine objects using reference identity and destroyed-object null semantics. /// @@ -34,11 +52,17 @@ public abstract class EngineObject : IdentityObject EngineObject? right ) { if (ReferenceEquals(left, right)) + { return true; + } if (ReferenceEquals(left, null)) + { return right!.m_isDestroyed; + } if (ReferenceEquals(right, null)) + { return left.m_isDestroyed; + } return ReferenceEquals(left, right); } @@ -59,37 +83,24 @@ public abstract class EngineObject : IdentityObject EngineObject? right ) => !(left == right); - /// - /// Compares this instance to another object using reference identity. - /// - /// - /// when is this instance. - /// - /// - /// The object to compare with this instance. - /// - public override bool Equals(object? obj) => ReferenceEquals(this, obj); - - /// - /// Returns a stable runtime reference hash code. - /// - /// - /// The reference hash code. - /// - public override int GetHashCode() => RuntimeHelpers.GetHashCode(this); - - internal void RegisterIdentity(Guid? persistentId = null) + internal void RegisterIdentity(Guid? persistentID = null) { if (m_isDestroyed) + { throw new InvalidOperationException($"Destroyed object '{GetType().FullName}' cannot be registered."); - if (!IdentityAllocator.current.Register(this, persistentId)) + } + if (!IdentityAllocator.current.Register(this, persistentID)) + { throw new InvalidOperationException($"Identity registration failed for '{GetType().FullName}'."); + } } internal void MarkDestroyed() { if (m_isDestroyed) + { return; + } try { IdentityAllocator.current.Unregister(this); @@ -103,24 +114,29 @@ internal void MarkDestroyed() internal Guid ReleaseIdentityForReplacement() { ValidateIdentityForReplacement(); - Guid persistentId = identity.persistentId; + Guid persistentID = identity.persistentID; if (!IdentityAllocator.current.Unregister(this)) + { throw new InvalidOperationException($"Identity release failed for '{GetType().FullName}'."); - return persistentId; + } + return persistentID; } internal void ValidateIdentityForReplacement() { if (m_isDestroyed) + { throw new InvalidOperationException($"Destroyed object '{GetType().FullName}' cannot be replaced."); + } RuntimeIdentity? owner = identity.runtimeIdentity; IdentityAllocator allocator = IdentityAllocator.current; - if (owner is not RuntimeIdentity registered || registered.domainId != allocator.domainId - || !ReferenceEquals(allocator.Get(registered), this)) - { + if (owner is not RuntimeIdentity registered || registered.domainID != allocator.domainID + || !ReferenceEquals(allocator.Get(registered), this) + ) { throw new InvalidOperationException( $"Identity replacement for '{GetType().FullName}' requires its owning domain " - + $"'{owner?.domainId.ToString() ?? "detached"}', but the current domain is '{allocator.domainId}'."); + + $"'{owner?.domainID.ToString() ?? "detached"}', but the current domain is '{allocator.domainID}'." + ); } } } diff --git a/src/content/scene/Inno.Scene/Core/GameBehavior.cs b/src/content/scene/Inno.Scene/Core/GameBehavior.cs index de35eb4ad..33bae7568 100644 --- a/src/content/scene/Inno.Scene/Core/GameBehavior.cs +++ b/src/content/scene/Inno.Scene/Core/GameBehavior.cs @@ -25,11 +25,15 @@ public bool enabled set { if (m_enabled == value) + { return; + } m_enabled = value; GameObject? owner = ownerOrNull; if (owner is { isRuntimeValid: true }) + { owner.scene.NotifyGameBehaviorActivationChanged(this); + } } } @@ -38,102 +42,102 @@ public bool enabled /// public bool isActiveAndEnabled => !isDestroyed && ownerOrNull is { activeInHierarchy: true } && m_enabled; + bool ISceneLifecycleObject.lifecycleAwakeCalled + { + get => lifecycleAwakeCalled; + set => lifecycleAwakeCalled = value; + } + + bool ISceneLifecycleObject.lifecycleStartCalled + { + get => lifecycleStartCalled; + set => lifecycleStartCalled = value; + } + + bool ISceneLifecycleObject.lifecycleDestroyCalled + { + get => lifecycleDestroyCalled; + set => lifecycleDestroyCalled = value; + } + + bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; + bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; + + bool ISceneLifecycleObject.lifecycleWasEnabled + { + get => lifecycleWasEnabled; + set => lifecycleWasEnabled = value; + } + + void ISceneLifecycleObject.DispatchAwake() => Awake(); + + void ISceneLifecycleObject.DispatchStart() => Start(); + + void ISceneLifecycleObject.DispatchEnable() => OnEnable(); + + void ISceneLifecycleObject.DispatchDisable() => OnDisable(); + + void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); + + internal bool lifecycleAwakeCalled { get; set; } + internal bool lifecycleStartCalled { get; set; } + internal bool lifecycleWasEnabled { get; set; } + internal bool lifecycleDestroyCalled { get; set; } + internal GameBehaviorLifecyclePhase lifecyclePhases { get; set; } + /// /// Called once before this behavior first becomes active. /// - protected virtual void Awake() - { - } + protected virtual void Awake() {} /// /// Called once immediately before the first update of this behavior. /// - protected virtual void Start() - { - } + protected virtual void Start() {} /// /// Called when this component becomes active and enabled. /// - protected virtual void OnEnable() - { - } + protected virtual void OnEnable() {} /// /// Called when this component stops being active and enabled. /// - protected virtual void OnDisable() - { - } + protected virtual void OnDisable() {} /// /// Called during the variable-rate update stage. Use Time.deltaTime for frame timing. /// - protected virtual void Update() - { - } + protected virtual void Update() {} /// /// Called during the fixed-rate update stage. Use Time.fixedDeltaTime for step timing. /// - protected virtual void FixedUpdate() - { - } + protected virtual void FixedUpdate() {} /// /// Called during the late update stage. Use Time.deltaTime for frame timing. /// - protected virtual void LateUpdate() - { - } + protected virtual void LateUpdate() {} /// /// Called immediately before this behavior is detached and destroyed. /// - protected virtual void OnDestroy() - { - } - - internal bool lifecycleAwakeCalled { get; set; } - internal bool lifecycleStartCalled { get; set; } - internal bool lifecycleWasEnabled { get; set; } - internal bool lifecycleDestroyCalled { get; set; } - internal GameBehaviorLifecyclePhase lifecyclePhases { get; set; } + protected virtual void OnDestroy() {} internal void DispatchAwake() => Awake(); + internal void DispatchStart() => Start(); + internal void DispatchEnable() => OnEnable(); + internal void DispatchDisable() => OnDisable(); + internal void DispatchUpdate() => Update(); + internal void DispatchFixedUpdate() => FixedUpdate(); + internal void DispatchLateUpdate() => LateUpdate(); - internal void DispatchDestroy() => OnDestroy(); - bool ISceneLifecycleObject.lifecycleAwakeCalled - { - get => lifecycleAwakeCalled; - set => lifecycleAwakeCalled = value; - } - bool ISceneLifecycleObject.lifecycleStartCalled - { - get => lifecycleStartCalled; - set => lifecycleStartCalled = value; - } - bool ISceneLifecycleObject.lifecycleDestroyCalled - { - get => lifecycleDestroyCalled; - set => lifecycleDestroyCalled = value; - } - bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; - bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; - bool ISceneLifecycleObject.lifecycleWasEnabled - { - get => lifecycleWasEnabled; - set => lifecycleWasEnabled = value; - } - void ISceneLifecycleObject.DispatchAwake() => Awake(); - void ISceneLifecycleObject.DispatchStart() => Start(); - void ISceneLifecycleObject.DispatchEnable() => OnEnable(); - void ISceneLifecycleObject.DispatchDisable() => OnDisable(); - void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); + internal void DispatchDestroy() => OnDestroy(); } diff --git a/src/content/scene/Inno.Scene/Core/GameComponent.cs b/src/content/scene/Inno.Scene/Core/GameComponent.cs index 254a47d36..9ebcc7f37 100644 --- a/src/content/scene/Inno.Scene/Core/GameComponent.cs +++ b/src/content/scene/Inno.Scene/Core/GameComponent.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; using Inno.Scene.Components; @@ -20,8 +19,8 @@ public abstract class GameComponent : EngineObject, ISerializable /// public GameObject gameObject => m_gameObject is not null && !isDestroyed - ? m_gameObject - : throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is detached or destroyed."); + ? m_gameObject + : throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is detached or destroyed."); /// /// Gets the owning game object's transform. @@ -31,20 +30,20 @@ public GameObject gameObject /// public Transform transform => gameObject.transform; + internal GameObject? ownerOrNull => m_gameObject; + /// /// Restores this component to its default state when it is added or explicitly reset. /// - protected virtual void Reset() - { - } - - internal GameObject? ownerOrNull => m_gameObject; + protected virtual void Reset() {} internal void Attach(GameObject owner) { ArgumentNullException.ThrowIfNull(owner); if (m_gameObject is not null) + { throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is already attached."); + } m_gameObject = owner; } diff --git a/src/content/scene/Inno.Scene/Core/GameObject.cs b/src/content/scene/Inno.Scene/Core/GameObject.cs index e3b9aed50..2281b76cf 100644 --- a/src/content/scene/Inno.Scene/Core/GameObject.cs +++ b/src/content/scene/Inno.Scene/Core/GameObject.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Serialization; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -17,7 +16,7 @@ public sealed class GameObject : EngineObject, ISerializable /// /// Defines the tag assigned to newly created game objects. /// - public const string defaultTag = "Untagged"; + public const string C_DEFAULT_TAG = "Untagged"; private ulong? m_serializationRevision = 0; private GameScene? m_scene; @@ -26,7 +25,7 @@ public sealed class GameObject : EngineObject, ISerializable private PrefabInstanceInfo? m_prefabInstance; private PrefabConnectionRecord? m_prefabConnection; private string m_name; - private string m_tag = defaultTag; + private string m_tag = C_DEFAULT_TAG; private GameLayer m_layer = GameLayer.defaultLayer; private bool m_activeSelf = true; private bool m_activeInHierarchy = true; @@ -35,7 +34,8 @@ internal GameObject( GameScene scene, string name ) { - m_scene = scene ?? throw new ArgumentNullException(nameof(scene)); + ArgumentNullException.ThrowIfNull(scene); + m_scene = scene; m_name = name ?? string.Empty; } @@ -67,7 +67,9 @@ public string name GameScene owner = EnsureAlive(); string requestedName = value ?? string.Empty; if (string.Equals(m_name, requestedName, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_name = requestedName; owner.NotifyObjectMetadataChanged(this); @@ -77,13 +79,13 @@ public string name /// /// Gets or sets the ordinal tag used to categorize and query this game object. /// + /// + /// Thrown when the assigned tag is empty or contains only white-space characters. + /// /// /// Tag definitions are project configuration stored separately from scene data. Scene and prefab /// serialization persist the assigned ordinal value even when its current project definition is absent. /// - /// - /// Thrown when the assigned tag is empty or contains only white-space characters. - /// public string tag { get @@ -96,7 +98,9 @@ public string tag GameScene owner = EnsureAlive(); string requestedTag = NormalizeTag(value); if (string.Equals(m_tag, requestedTag, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_tag = requestedTag; owner.NotifyObjectMetadataChanged(this); @@ -121,7 +125,9 @@ public GameLayer layer { GameScene owner = EnsureAlive(); if (m_layer == value) + { return; + } AdvanceCaptureRevision(); m_layer = value; owner.NotifyObjectMetadataChanged(this); @@ -192,7 +198,8 @@ public bool activeSelf /// /// The attached component. /// - public TComponent AddComponent() where TComponent : GameComponent => (TComponent)AddComponent(typeof(TComponent)); + public TComponent AddComponent() + where TComponent : GameComponent => (TComponent)AddComponent(typeof(TComponent)); /// /// Creates and attaches a component of the requested runtime type. @@ -204,7 +211,7 @@ public bool activeSelf /// The attached component. /// public GameComponent AddComponent(Type componentType) - => EnsureAlive().AddComponent(this, componentType, persistentId: null, invokeReset: true); + => EnsureAlive().AddComponent(this, componentType, persistentID: null, invokeReset: true); /// /// Gets the first attached component assignable to the requested type. @@ -218,11 +225,16 @@ public GameComponent AddComponent(Type componentType) /// /// Thrown when no matching component exists. /// - public TComponent GetComponent() where TComponent : GameComponent + public TComponent GetComponent() + where TComponent : GameComponent { if (TryGetComponent(out TComponent? component) && component is not null) + { return component; - throw new InvalidOperationException($"GameObject '{m_name}' does not contain component '{typeof(TComponent).FullName}'. Add it explicitly before calling GetComponent."); + } + throw new InvalidOperationException( + $"GameObject '{m_name}' does not contain component '{typeof(TComponent).FullName}'. Add it explicitly before calling GetComponent." + ); } /// @@ -241,8 +253,12 @@ public GameComponent GetComponent(Type componentType) { ArgumentNullException.ThrowIfNull(componentType); if (EnsureAlive().TryGetComponent(this, componentType, out GameComponent? component) && component is not null) + { return component; - throw new InvalidOperationException($"GameObject '{m_name}' does not contain component '{componentType.FullName}'. Add it explicitly before calling GetComponent."); + } + throw new InvalidOperationException( + $"GameObject '{m_name}' does not contain component '{componentType.FullName}'. Add it explicitly before calling GetComponent." + ); } /// @@ -257,7 +273,8 @@ public GameComponent GetComponent(Type componentType) /// /// when a matching component exists. /// - public bool TryGetComponent(out TComponent? component) where TComponent : GameComponent + public bool TryGetComponent(out TComponent? component) + where TComponent : GameComponent { if (!isRuntimeValid) { @@ -277,7 +294,8 @@ public bool TryGetComponent(out TComponent? component) where TCompon /// /// when a matching component exists. /// - public bool HasComponent() where TComponent : GameComponent => TryGetComponent(out _); + public bool HasComponent() + where TComponent : GameComponent => TryGetComponent(out _); /// /// Gets all attached components assignable to the requested type in attachment order. @@ -288,8 +306,9 @@ public bool TryGetComponent(out TComponent? component) where TCompon /// /// A stable component snapshot. /// - public IReadOnlyList GetComponents() where TComponent : GameComponent - => EnsureAlive().GetComponents(this); + public IReadOnlyList GetComponents() + where TComponent : GameComponent + => EnsureAlive().GetComponents(this); /// /// Gets all attached components in attachment order. @@ -377,7 +396,9 @@ public bool RemoveComponent(GameComponent component) internal void BindTransform(Transform transform) { if (m_transform is not null) + { throw new InvalidOperationException("GameObject transform is already initialized."); + } m_transform = transform; } @@ -385,7 +406,9 @@ internal void SetNameDirect(string value) { string requestedName = value ?? string.Empty; if (string.Equals(m_name, requestedName, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_name = requestedName; m_scene?.NotifyObjectMetadataChanged(this); @@ -395,7 +418,9 @@ internal void SetTagDirect(string value) { string requestedTag = NormalizeTag(value); if (string.Equals(m_tag, requestedTag, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_tag = requestedTag; m_scene?.NotifyObjectMetadataChanged(this); @@ -404,7 +429,9 @@ internal void SetTagDirect(string value) internal void SetLayerDirect(GameLayer value) { if (m_layer == value) + { return; + } AdvanceCaptureRevision(); m_layer = value; m_scene?.NotifyObjectMetadataChanged(this); @@ -415,6 +442,7 @@ internal void SetActiveSelfDirect(bool value) AdvanceCaptureRevision(); m_activeSelf = value; } + internal void SetActiveInHierarchyDirect(bool value) => m_activeInHierarchy = value; /// @@ -426,19 +454,25 @@ internal void SetActiveSelfDirect(bool value) internal void AttachRecord(SceneObjectRecord record) { if (m_attachment is not null) + { throw new InvalidOperationException("The object already owns a scene-store attachment."); + } m_attachment = record; } internal void ReleaseRecord(SceneObjectRecord record) { if (!ReferenceEquals(m_attachment, record)) + { throw new InvalidOperationException("The object no longer owns the retiring scene-store attachment."); + } m_attachment = null; } internal void SetSceneDirect(GameScene scene) => m_scene = scene ?? throw new ArgumentNullException(nameof(scene)); + internal void SetPrefabInstanceDirect(PrefabInstanceInfo? value) => m_prefabInstance = value; + internal void SetPrefabConnectionDirect(PrefabConnectionRecord? value) => m_prefabConnection = value; internal void DestroyDirect() @@ -450,13 +484,6 @@ internal void DestroyDirect() MarkDestroyed(); } - private GameScene EnsureAlive() - { - if (isDestroyed || m_scene is null || !m_scene.Contains(this)) - throw new InvalidOperationException($"GameObject '{m_name}' is destroyed or detached from its scene."); - return m_scene; - } - /// /// Validates and normalizes a tag used by runtime storage and serialization. /// @@ -474,11 +501,21 @@ internal static string NormalizeTag(string value) ArgumentException.ThrowIfNullOrWhiteSpace(value); return value.Trim(); } + + private GameScene EnsureAlive() + { + if (isDestroyed || m_scene is null || !m_scene.Contains(this)) + { + throw new InvalidOperationException($"GameObject '{m_name}' is destroyed or detached from its scene."); + } + return m_scene; + } + private void AdvanceCaptureRevision() { if (m_serializationRevision is { } revision) + { m_serializationRevision = revision == ulong.MaxValue ? null : revision + 1; + } } - - } diff --git a/src/content/scene/Inno.Scene/Core/GameScene.cs b/src/content/scene/Inno.Scene/Core/GameScene.cs index 3a3fc8cf1..1a3f3e40a 100644 --- a/src/content/scene/Inno.Scene/Core/GameScene.cs +++ b/src/content/scene/Inno.Scene/Core/GameScene.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -34,21 +33,20 @@ public sealed class GameScene : EngineObject, ISerializable /// Initial scene name. /// public GameScene(string name = "Untitled Scene") - : this(SceneWorld.current.typeCatalog, name, persistentId: null) - { - } + : this(SceneWorld.current.typeCatalog, name, persistentID: null) {} internal GameScene( SceneTypeCatalog types, string name, - Guid? persistentId + Guid? persistentID ) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types); + m_types = types; m_name = name ?? string.Empty; m_store = new SceneStore(types); m_hierarchy = new HierarchyService(this); m_systems = new SceneSystemScheduler(this, types); - RegisterIdentity(persistentId); + RegisterIdentity(persistentID); } /// @@ -78,9 +76,6 @@ public string name /// public ulong hierarchyRevision => m_hierarchy.revision; - internal SceneTypeCatalog typeCatalog => m_types; - internal long structureRevision => m_store.structureRevision; - /// /// Creates a game object with a mandatory transform component. /// @@ -91,7 +86,7 @@ public string name /// The created game object. /// public GameObject CreateObject(string name = "GameObject") - => CreateObject(name, persistentId: null, transformPersistentId: null, invokeReset: true); + => CreateObject(name, persistentID: null, transformPersistentID: null, invokeReset: true); /// /// Creates a connected instance of an imported prefab in this loaded scene. @@ -114,9 +109,8 @@ public GameObject CreateObject(string name = "GameObject") public GameObject InstantiatePrefab( PrefabAsset prefab, Transform? parent = null - ) - => (m_ownerWorld ?? throw new InvalidOperationException("The scene is not loaded in a world.")) - .InstantiatePrefab(prefab, this, parent); + ) => (m_ownerWorld ?? throw new InvalidOperationException("The scene is not loaded in a world.")) + .InstantiatePrefab(prefab, this, parent); /// /// Recursively destroys a game object and its complete child subtree. @@ -131,8 +125,10 @@ public bool DestroyObject(GameObject gameObject) { ArgumentNullException.ThrowIfNull(gameObject); if (!Contains(gameObject)) + { return false; - Guid persistentId = gameObject.identity.persistentId; + } + Guid persistentID = gameObject.identity.persistentID; Exception? firstException = null; Transform[] children = gameObject.transform.children.ToArray(); @@ -156,7 +152,9 @@ public bool DestroyObject(GameObject gameObject) try { if (removed[i].wasCommitted && component is GameBehavior behavior) + { m_systems.DestroyGameBehavior(behavior); + } } catch (Exception exception) { @@ -165,14 +163,18 @@ public bool DestroyObject(GameObject gameObject) finally { if (!component.isDestroyed) + { component.Detach(); + } } } m_systems.NotifyGameBehaviorStructureChanged(); gameObject.DestroyDirect(); if (firstException is not null) - throw new InvalidOperationException($"A destruction callback failed for GameObject '{persistentId}'.", firstException); + { + throw new InvalidOperationException($"A destruction callback failed for GameObject '{persistentID}'.", firstException); + } return true; } @@ -294,7 +296,8 @@ public IReadOnlyList FindObjectsWithLayers(GameLayerMask layers) /// /// The registered system. /// - public TSystem AddSystem() where TSystem : GameSystem, new() + public TSystem AddSystem() + where TSystem : GameSystem, new() { EnsureNotDestroyed(); return m_systems.Add(); @@ -316,9 +319,10 @@ public GameSystem AddSystem(Type systemType) { throw new ArgumentException( $"{nameof(MissingGameSystem)} instances are created only by scene restoration.", - nameof(systemType)); + nameof(systemType) + ); } - return m_systems.Add(systemType, persistentId: null, invokeReset: true); + return m_systems.Add(systemType, persistentID: null, invokeReset: true); } /// @@ -410,26 +414,24 @@ int systemIndex m_systems.SetIndex(system, systemIndex); } + internal SceneTypeCatalog typeCatalog => m_types; + internal long structureRevision => m_store.structureRevision; + + internal bool canDispatch => m_isLoaded && !m_isUnloading && !isDestroyed; + internal GameSystem AddSystem( Type systemType, - Guid? persistentId, + Guid? persistentID, bool invokeReset - ) - => m_systems.Add(systemType, persistentId, invokeReset); + ) => m_systems.Add(systemType, persistentID, invokeReset); internal MissingGameSystem AddMissingSystem( TypeRef missingType, string missingTypeName, ReadOnlySpan serializedState, - Guid? persistentId, + Guid? persistentID, IReadOnlyList? dependencies = null - ) - => m_systems.AddMissing( - missingType, - missingTypeName, - serializedState, - persistentId, - dependencies); + ) => m_systems.AddMissing(missingType, missingTypeName, serializedState, persistentID, dependencies); internal bool Contains(GameObject gameObject) => !isDestroyed && m_store.Contains(gameObject); @@ -442,7 +444,7 @@ internal void NotifyObjectMetadataChanged(GameObject gameObject) internal GameComponent AddComponent( GameObject owner, Type componentType, - Guid? persistentId, + Guid? persistentID, bool invokeReset ) { EnsureOwned(owner); @@ -451,29 +453,35 @@ bool invokeReset { throw new ArgumentException( $"{nameof(MissingGameComponent)} instances are created only by scene restoration.", - nameof(componentType)); + nameof(componentType) + ); } if (!typeof(GameComponent).IsAssignableFrom(componentType)) + { throw new ArgumentException($"Type '{componentType.FullName}' is not a scene component.", nameof(componentType)); + } - if (!m_types.TryGetComponent(componentType, out SceneComponentTypeDescriptor? descriptor) || - !descriptor!.isConcrete) - { + if (!m_types.TryGetComponent(componentType, out SceneComponentTypeDescriptor? descriptor) + || !descriptor!.isConcrete + ) { throw new ArgumentException( $"Type '{componentType.FullName}' is not an active concrete scene component.", - nameof(componentType)); + nameof(componentType) + ); } bool allowsMultiple = descriptor.allowsMultiple; GameComponent component = ComponentFactory.Create(componentType, m_types.snapshot); if (component is GameBehavior createdBehavior) + { createdBehavior.lifecyclePhases = descriptor.behaviorPhases; + } component.Attach(owner); bool addedToStore = false; bool registeredHierarchy = false; try { - component.RegisterIdentity(persistentId); + component.RegisterIdentity(persistentID); m_store.AddComponent(owner, component, descriptor, allowsMultiple); addedToStore = true; if (component is Transform transform) @@ -485,19 +493,29 @@ bool invokeReset } if (invokeReset) + { component.DispatchReset(); + } if (component is GameBehavior behavior) + { m_systems.NotifyGameBehaviorActivationChanged(behavior); + } return component; } catch { if (registeredHierarchy && component is Transform transform) + { m_hierarchy.Unregister(transform); + } if (addedToStore) + { m_store.RemoveComponent(owner, component); + } if (!component.isDestroyed) + { component.Detach(); + } throw; } } @@ -508,22 +526,32 @@ GameComponent component ) { EnsureOwned(owner); if (!ReferenceEquals(component.ownerOrNull, owner)) + { return false; + } if (component is Transform) + { throw new InvalidOperationException("The mandatory Transform component cannot be removed."); + } SceneStoreRemovalKind removal = m_store.RemoveComponent(owner, component); if (removal == SceneStoreRemovalKind.None) + { return false; + } try { if (removal == SceneStoreRemovalKind.RemovedCommitted && component is GameBehavior behavior) + { m_systems.DestroyGameBehavior(behavior); + } } finally { if (!component.isDestroyed) + { component.Detach(); + } m_systems.NotifyGameBehaviorStructureChanged(); } return true; @@ -534,20 +562,16 @@ internal MissingGameComponent AddMissingComponent( TypeRef missingType, string missingTypeName, ReadOnlySpan serializedState, - Guid? persistentId, + Guid? persistentID, IReadOnlyList? dependencies = null ) { EnsureOwned(owner); - var component = new MissingGameComponent( - missingType, - missingTypeName, - serializedState, - dependencies); + var component = new MissingGameComponent(missingType, missingTypeName, serializedState, dependencies); component.Attach(owner); bool addedToStore = false; try { - component.RegisterIdentity(persistentId); + component.RegisterIdentity(persistentID); SceneComponentTypeDescriptor descriptor = m_types.GetComponent(typeof(MissingGameComponent)); m_store.AddComponent(owner, component, descriptor, allowsMultiple: true); addedToStore = true; @@ -556,9 +580,13 @@ internal MissingGameComponent AddMissingComponent( catch { if (addedToStore) + { m_store.RemoveComponent(owner, component); + } if (!component.isDestroyed) + { component.Detach(); + } throw; } } @@ -570,16 +598,31 @@ GameComponent component EnsureOwned(owner); ArgumentNullException.ThrowIfNull(component); if (!ReferenceEquals(component.ownerOrNull, owner)) - throw new InvalidOperationException($"GameComponent '{component.GetType().FullName}' is not attached to GameObject '{owner.name}'."); + { + throw new InvalidOperationException( + $"GameComponent '{component.GetType().FullName}' is not attached to GameObject '{owner.name}'." + ); + } component.DispatchReset(); } + internal IReadOnlyList GetComponents() + where TComponent : GameComponent + => m_store.GetComponents(m_types.GetComponent(typeof(TComponent))); + internal IReadOnlyList GetComponents(GameObject owner) { EnsureOwned(owner); return m_store.GetComponents(owner); } + internal IReadOnlyList GetComponents(GameObject owner) + where TComponent : GameComponent + { + EnsureOwned(owner); + return m_store.GetComponents(owner, m_types.GetComponent(typeof(TComponent))); + } + internal int GetComponentIndex( GameObject owner, GameComponent component @@ -597,27 +640,13 @@ int componentIndex m_store.SetComponentIndex(owner, component, componentIndex); } - internal IReadOnlyList GetComponents(GameObject owner) - where TComponent : GameComponent - { - EnsureOwned(owner); - return m_store.GetComponents(owner, m_types.GetComponent(typeof(TComponent))); - } - - internal IReadOnlyList GetComponents() where TComponent : GameComponent - => m_store.GetComponents(m_types.GetComponent(typeof(TComponent))); - internal bool TryGetComponent( GameObject owner, out TComponent? component - ) - where TComponent : GameComponent + ) where TComponent : GameComponent { EnsureOwned(owner); - return m_store.TryGetComponent( - owner, - m_types.GetComponent(typeof(TComponent)), - out component); + return m_store.TryGetComponent(owner, m_types.GetComponent(typeof(TComponent)), out component); } internal bool TryGetComponent( @@ -635,23 +664,23 @@ out GameComponent? component return m_store.TryGetComponent(owner, descriptor!, out component); } - internal IReadOnlyList Query() where T1 : GameComponent => m_store.Query(m_types.GetComponent(typeof(T1))); + internal IReadOnlyList Query() + where T1 : GameComponent => m_store.Query(m_types.GetComponent(typeof(T1))); internal IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent - => m_store.Query( - m_types.GetComponent(typeof(T1)), - m_types.GetComponent(typeof(T2))); + => m_store.Query(m_types.GetComponent(typeof(T1)), m_types.GetComponent(typeof(T2))); internal IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent where T3 : GameComponent - => m_store.Query( - m_types.GetComponent(typeof(T1)), - m_types.GetComponent(typeof(T2)), - m_types.GetComponent(typeof(T3))); + => m_store.Query( + m_types.GetComponent(typeof(T1)), + m_types.GetComponent(typeof(T2)), + m_types.GetComponent(typeof(T3)) + ); internal IDisposable BeginExecutionPhase() => m_store.BeginExecutionPhase(); @@ -659,44 +688,52 @@ internal IReadOnlyList Query() internal IReadOnlyList GetOwnedObjects() => m_store.GetOwnedObjects(); - internal GameObject? FindObject(Guid persistentId) => m_store.FindObject(persistentId); + internal GameObject? FindObject(Guid persistentID) => m_store.FindObject(persistentID); - internal GameComponent? FindComponent(Guid persistentId) => m_store.FindComponent(persistentId); + internal GameComponent? FindComponent(Guid persistentID) => m_store.FindComponent(persistentID); internal void ReplaceComponentForReload( GameComponent previous, GameComponent replacement, - int replacementRuntimeTypeId + int replacementRuntimeTypeID ) { GameObject owner = previous.ownerOrNull - ?? throw new InvalidOperationException("The component being replaced is detached."); + ?? throw new InvalidOperationException("The component being replaced is detached."); if (!Contains(owner) || previous is Transform || replacement is Transform) + { throw new InvalidOperationException("Only attached non-Transform components can be hot reloaded."); + } previous.ValidateIdentityForReplacement(); - if (replacement.identity.runtimeId is not null) + if (replacement.identity.runtimeID is not null) + { throw new InvalidOperationException("The replacement component already has a registered identity."); + } bool attachedHere = replacement.ownerOrNull is null; if (attachedHere) + { replacement.Attach(owner); + } else if (!ReferenceEquals(replacement.ownerOrNull, owner)) + { throw new InvalidOperationException("The replacement component belongs to another GameObject."); - Guid persistentId = previous.identity.persistentId; + } + Guid persistentID = previous.identity.persistentID; try { - if (replacement is GameBehavior replacementBehavior && - m_types.TryGetComponent(replacement.GetType(), out SceneComponentTypeDescriptor? replacementDescriptor)) - { + if (replacement is GameBehavior replacementBehavior + && m_types.TryGetComponent(replacement.GetType(), out SceneComponentTypeDescriptor? replacementDescriptor) + ) { replacementBehavior.lifecyclePhases = replacementDescriptor!.behaviorPhases; } _ = previous.ReleaseIdentityForReplacement(); - replacement.RegisterIdentity(persistentId); - m_store.ReplaceComponent(previous, replacement, replacementRuntimeTypeId); + replacement.RegisterIdentity(persistentID); + m_store.ReplaceComponent(previous, replacement, replacementRuntimeTypeID); m_systems.NotifyGameBehaviorStructureChanged(); } catch (Exception exception) { List? rollbackFailures = null; - if (replacement.identity.runtimeId is not null) + if (replacement.identity.runtimeID is not null) { try { @@ -708,11 +745,11 @@ int replacementRuntimeTypeId rollbackFailures.Add(rollbackFailure); } } - if (previous.identity.runtimeId is null) + if (previous.identity.runtimeID is null) { try { - previous.RegisterIdentity(persistentId); + previous.RegisterIdentity(persistentID); } catch (Exception rollbackFailure) { @@ -733,21 +770,21 @@ int replacementRuntimeTypeId } } if (rollbackFailures is null) + { throw; + } throw new InvalidOperationException( "Component hot-reload replacement failed and its identity rollback was incomplete.", - new AggregateException([exception, .. rollbackFailures])); + new AggregateException([exception, .. rollbackFailures]) + ); } } internal void ReplaceSystemForReload( GameSystem previous, GameSystem replacement, - int replacementRuntimeTypeId - ) - => m_systems.ReplaceForReload(previous, replacement, replacementRuntimeTypeId); - - internal bool canDispatch => m_isLoaded && !m_isUnloading && !isDestroyed; + int replacementRuntimeTypeID + ) => m_systems.ReplaceForReload(previous, replacement, replacementRuntimeTypeID); internal void SetSourceAsset(AssetObject sourceAsset) { @@ -755,22 +792,27 @@ internal void SetSourceAsset(AssetObject sourceAsset) m_sourceAsset = sourceAsset; } - internal void PrepareRestoreTarget(Guid persistentId) + internal void PrepareRestoreTarget(Guid persistentID) { EnsureNotDestroyed(); - if (identity.persistentId != persistentId) + if (identity.persistentID != persistentID) { throw new InvalidOperationException( - $"Scene identity '{identity.persistentId}' does not match serialized identity '{persistentId}'."); + $"Scene identity '{identity.persistentID}' does not match serialized identity '{persistentID}'." + ); } foreach (GameSystem system in GetSystems().ToArray()) + { RemoveSystem(system); + } GameObject[] objects = GetObjects().ToArray(); for (int i = 0; i < objects.Length; i++) { if (objects[i].isRuntimeValid) + { DestroyObject(objects[i]); + } } } @@ -796,14 +838,18 @@ internal void NotifyGameBehaviorActivationChanged(GameBehavior behavior) { ArgumentNullException.ThrowIfNull(behavior); if (behavior.ownerOrNull is GameObject owner && Contains(owner)) + { m_systems.NotifyGameBehaviorActivationChanged(behavior); + } } internal void NotifyGameSystemActivationChanged(GameSystem system) { ArgumentNullException.ThrowIfNull(system); if (ReferenceEquals(system.ownerScene, this)) + { m_systems.NotifyGameSystemActivationChanged(system); + } } internal void SetParent( @@ -837,12 +883,15 @@ GameScene destination ArgumentNullException.ThrowIfNull(destination); destination.EnsureNotDestroyed(); if (ReferenceEquals(this, destination)) - return; - if (m_store.isExecuting || m_store.hasPendingChanges || - destination.m_store.isExecuting || destination.m_store.hasPendingChanges) { + return; + } + if (m_store.isExecuting || m_store.hasPendingChanges + || destination.m_store.isExecuting || destination.m_store.hasPendingChanges + ) { throw new InvalidOperationException( - "A GameObject cannot move between scenes during a scene execution phase or while structural changes are pending."); + "A GameObject cannot move between scenes during a scene execution phase or while structural changes are pending." + ); } Transform rootTransform = gameObject.transform; @@ -851,10 +900,14 @@ GameScene destination GameObject[] subtree = EnumerateSubtree(rootTransform).ToArray(); var components = new Dictionary(ReferenceEqualityComparer.Instance); for (int i = 0; i < subtree.Length; i++) + { components.Add(subtree[i], m_store.GetComponents(subtree[i]).ToArray()); + } if (previousParent is not null) + { m_hierarchy.SetParent(rootTransform, parent: null, worldPositionStays: true); + } m_hierarchy.Unregister(rootTransform); int transferredCount = 0; @@ -875,7 +928,8 @@ GameScene destination current, component, m_types.GetComponent(component.GetType()), - allowsMultiple: true); + allowsMultiple: true + ); } current.SetSceneDirect(destination); } @@ -887,7 +941,9 @@ GameScene destination catch { if (registeredDestinationHierarchy) + { destination.m_hierarchy.Unregister(rootTransform); + } for (int i = transferredCount - 1; i >= 0; i--) { GameObject current = subtree[i]; @@ -901,14 +957,17 @@ GameScene destination current, component, m_types.GetComponent(component.GetType()), - allowsMultiple: true); + allowsMultiple: true + ); } current.SetSceneDirect(this); } m_hierarchy.Register(rootTransform); if (previousParent is not null) + { m_hierarchy.SetParent(rootTransform, previousParent, worldPositionStays: true); + } m_hierarchy.SetSiblingIndex(rootTransform, previousSiblingIndex); m_activation.RecomputeSubtree(gameObject); throw; @@ -917,25 +976,29 @@ GameScene destination internal GameObject CreateObject( string name, - Guid? persistentId, - Guid? transformPersistentId, + Guid? persistentID, + Guid? transformPersistentID, bool invokeReset ) { EnsureNotDestroyed(); var gameObject = new GameObject(this, name); - gameObject.RegisterIdentity(persistentId); + gameObject.RegisterIdentity(persistentID); try { m_store.AddObject(gameObject); - AddComponent(gameObject, typeof(Transform), transformPersistentId, invokeReset); + AddComponent(gameObject, typeof(Transform), transformPersistentID, invokeReset); return gameObject; } catch { if (Contains(gameObject)) + { DestroyObject(gameObject); + } else if (!gameObject.isDestroyed) + { gameObject.DestroyDirect(); + } throw; } } @@ -945,7 +1008,9 @@ internal void Load(SceneWorld ownerWorld) ArgumentNullException.ThrowIfNull(ownerWorld); EnsureNotDestroyed(); if (m_isLoaded) + { throw new InvalidOperationException($"Scene '{m_name}' is already loaded."); + } m_ownerWorld = ownerWorld; m_isLoaded = true; m_systems.NotifyHierarchyActivationChanged(); @@ -954,7 +1019,9 @@ internal void Load(SceneWorld ownerWorld) internal void Unload() { if (isDestroyed || m_isUnloading) + { return; + } m_isUnloading = true; m_isLoaded = false; @@ -966,7 +1033,9 @@ internal void Unload() try { if (Contains(objects[i])) + { DestroyObject(objects[i]); + } } catch (Exception exception) { @@ -980,25 +1049,33 @@ internal void Unload() m_sourceAsset = null; MarkDestroyed(); if (firstException is not null) + { throw new InvalidOperationException($"Scene '{m_name}' encountered an error while unloading.", firstException); + } } internal void FixedUpdate(float fixedDeltaTime) { if (canDispatch) + { m_systems.FixedUpdate(); + } } internal void Update(float deltaTime) { if (canDispatch) + { m_systems.Update(); + } } internal void LateUpdate(float deltaTime) { if (canDispatch) + { m_systems.LateUpdate(); + } } private void EnsureOwned(GameObject gameObject) @@ -1006,13 +1083,17 @@ private void EnsureOwned(GameObject gameObject) ArgumentNullException.ThrowIfNull(gameObject); EnsureNotDestroyed(); if (!m_store.Contains(gameObject)) + { throw new InvalidOperationException($"GameObject does not belong to scene '{m_name}'."); + } } private void EnsureNotDestroyed() { if (isDestroyed) + { throw new InvalidOperationException($"Scene '{m_name}' has been destroyed and cannot be reused."); + } } private static IEnumerable EnumerateSubtree(Transform root) @@ -1022,7 +1103,9 @@ private static IEnumerable EnumerateSubtree(Transform root) for (int i = 0; i < children.Count; i++) { foreach (GameObject descendant in EnumerateSubtree(children[i])) + { yield return descendant; + } } } } diff --git a/src/content/scene/Inno.Scene/Core/GameSystem.cs b/src/content/scene/Inno.Scene/Core/GameSystem.cs index 8a7c8e9c1..6571b509b 100644 --- a/src/content/scene/Inno.Scene/Core/GameSystem.cs +++ b/src/content/scene/Inno.Scene/Core/GameSystem.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; - -using Inno.Scripting.Api; using Inno.Core.Serialization; +using Inno.Scripting.Api; namespace Inno.Scene; @@ -26,10 +25,14 @@ public bool enabled { bool next = value && this is not MissingGameSystem; if (m_enabled == next) + { return; + } m_enabled = next; if (m_scene is { isLoaded: true }) + { m_scene.NotifyGameSystemActivationChanged(this); + } } } @@ -43,75 +46,101 @@ public bool enabled /// public virtual int order => 0; + bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; + bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; + + bool ISceneLifecycleObject.lifecycleAwakeCalled + { + get => lifecycleAwakeCalled; + set => lifecycleAwakeCalled = value; + } + + bool ISceneLifecycleObject.lifecycleStartCalled + { + get => lifecycleStartCalled; + set => lifecycleStartCalled = value; + } + + bool ISceneLifecycleObject.lifecycleWasEnabled + { + get => lifecycleWasEnabled; + set => lifecycleWasEnabled = value; + } + + bool ISceneLifecycleObject.lifecycleDestroyCalled + { + get => lifecycleDestroyCalled; + set => lifecycleDestroyCalled = value; + } + + void ISceneLifecycleObject.DispatchAwake() => Awake(); + + void ISceneLifecycleObject.DispatchStart() => Start(); + + void ISceneLifecycleObject.DispatchEnable() => OnEnable(); + + void ISceneLifecycleObject.DispatchDisable() => OnDisable(); + + void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); + /// /// Gets the owning scene after this system has been registered. /// protected GameScene scene => m_scene ?? throw new InvalidOperationException( - $"System '{GetType().FullName}' is not registered with a scene."); + $"System '{GetType().FullName}' is not registered with a scene." + ); + + internal bool lifecycleAwakeCalled { get; set; } + internal bool lifecycleStartCalled { get; set; } + internal bool lifecycleWasEnabled { get; set; } + internal bool lifecycleDestroyCalled { get; set; } + internal GameScene? ownerScene => m_scene; /// /// Restores this system to defaults when added or explicitly reset. /// - protected virtual void Reset() - { - } + protected virtual void Reset() {} /// /// Called once before the system first becomes active. /// - protected virtual void Awake() - { - } + protected virtual void Awake() {} /// /// Called once immediately before the first update. /// - protected virtual void Start() - { - } + protected virtual void Start() {} /// /// Called when the system becomes active and enabled. /// - protected virtual void OnEnable() - { - } + protected virtual void OnEnable() {} /// /// Called when the system stops being active and enabled. /// - protected virtual void OnDisable() - { - } + protected virtual void OnDisable() {} /// /// Called before a system that entered runtime lifecycle is destroyed. /// - protected virtual void OnDestroy() - { - } + protected virtual void OnDestroy() {} /// /// Called during the fixed-rate scene stage. Use Time.fixedDeltaTime for step timing. /// - protected virtual void OnFixedUpdate() - { - } + protected virtual void OnFixedUpdate() {} /// /// Called during the variable-rate scene stage. Use Time.deltaTime for frame timing. /// - protected virtual void OnUpdate() - { - } + protected virtual void OnUpdate() {} /// /// Called during the late scene stage. Use Time.deltaTime for frame timing. /// - protected virtual void OnLateUpdate() - { - } + protected virtual void OnLateUpdate() {} /// /// Gets all scene components assignable to a requested type. @@ -122,7 +151,8 @@ protected virtual void OnLateUpdate() /// /// An immutable snapshot of the values selected by the operation. /// - protected IReadOnlyList GetComponents() where TComponent : GameComponent => scene.GetComponents(); + protected IReadOnlyList GetComponents() + where TComponent : GameComponent => scene.GetComponents(); /// /// Gets all committed live game objects in deterministic scene storage order. @@ -141,7 +171,8 @@ protected virtual void OnLateUpdate() /// /// An immutable snapshot of the values selected by the operation. /// - protected IReadOnlyList Query() where T1 : GameComponent => scene.Query(); + protected IReadOnlyList Query() + where T1 : GameComponent => scene.Query(); /// /// Queries game objects containing two required component types. @@ -158,7 +189,7 @@ protected virtual void OnLateUpdate() protected IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent - => scene.Query(); + => scene.Query(); /// /// Queries game objects containing three required component types. @@ -179,19 +210,15 @@ protected IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent where T3 : GameComponent - => scene.Query(); - - internal bool lifecycleAwakeCalled { get; set; } - internal bool lifecycleStartCalled { get; set; } - internal bool lifecycleWasEnabled { get; set; } - internal bool lifecycleDestroyCalled { get; set; } - internal GameScene? ownerScene => m_scene; + => scene.Query(); internal void Attach(GameScene owner) { ArgumentNullException.ThrowIfNull(owner); if (m_scene is not null) + { throw new InvalidOperationException($"System '{GetType().FullName}' is already registered."); + } m_scene = owner; } @@ -202,35 +229,10 @@ internal void Detach() } internal void DispatchReset() => Reset(); + internal void DispatchFixedUpdate() => OnFixedUpdate(); + internal void DispatchUpdate() => OnUpdate(); - internal void DispatchLateUpdate() => OnLateUpdate(); - bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; - bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; - bool ISceneLifecycleObject.lifecycleAwakeCalled - { - get => lifecycleAwakeCalled; - set => lifecycleAwakeCalled = value; - } - bool ISceneLifecycleObject.lifecycleStartCalled - { - get => lifecycleStartCalled; - set => lifecycleStartCalled = value; - } - bool ISceneLifecycleObject.lifecycleWasEnabled - { - get => lifecycleWasEnabled; - set => lifecycleWasEnabled = value; - } - bool ISceneLifecycleObject.lifecycleDestroyCalled - { - get => lifecycleDestroyCalled; - set => lifecycleDestroyCalled = value; - } - void ISceneLifecycleObject.DispatchAwake() => Awake(); - void ISceneLifecycleObject.DispatchStart() => Start(); - void ISceneLifecycleObject.DispatchEnable() => OnEnable(); - void ISceneLifecycleObject.DispatchDisable() => OnDisable(); - void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); + internal void DispatchLateUpdate() => OnLateUpdate(); } diff --git a/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs b/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs index 3275706aa..a858f7eb3 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs @@ -1,32 +1,31 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Scene; /// /// Stores the project-wide tag definitions used to author and validate scene object assignments. /// -[StableTypeId("5bd9122b-8ce7-4ddd-8c47-32e4235f819e")] -[ProjectSettingDefinition(GameTagCatalog.settingProtocolId)] +[StableTypeID("5bd9122b-8ce7-4ddd-8c47-32e4235f819e")] +[ProjectSettingDefinition(GameTagCatalog.C_SETTING_PROTOCOL_ID)] public sealed class GameTagCatalog : ISerializable { /// /// Gets the immutable project-setting protocol value used by discovery metadata. /// - public const string settingProtocolId = "inno.scene.tags"; + public const string C_SETTING_PROTOCOL_ID = "inno.scene.tags"; [SerializableProperty] - private string[] m_tags = [GameObject.defaultTag]; + private string[] m_tags = [GameObject.C_DEFAULT_TAG]; /// /// Gets the stable project setting protocol for the project-wide tag catalog. /// - public static ProjectSettingId settingId => new(settingProtocolId); + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); /// /// Gets the defined tags with the immutable default tag first. @@ -49,18 +48,20 @@ public IReadOnlyList GetTags() /// /// The deterministic local identity. /// - public ProjectLocalId GetLocalId(string tag) + public ProjectLocalID GetLocalID(string tag) { string normalized = Normalize(tag); if (!IsDefined(normalized)) + { throw new KeyNotFoundException($"Game tag '{normalized}' is not defined."); - return ProjectLocalId.FromName(normalized); + } + return ProjectLocalID.FromName(normalized); } /// /// Gets the complete project-scoped identity of a defined tag. /// - /// + /// /// The current project namespace. /// /// @@ -69,10 +70,10 @@ public ProjectLocalId GetLocalId(string tag) /// /// The canonical projectId.name identity. /// - public ProjectScopedId GetId( - ProjectId projectId, + public ProjectScopedID GetID( + ProjectID projectID, string tag - ) => projectId.Qualify(GetLocalId(tag)); + ) => projectID.Qualify(GetLocalID(tag)); /// /// Determines whether an ordinal tag is defined by the project. @@ -110,10 +111,12 @@ public bool Add(string tag) string normalized = Normalize(tag); ValidateState(); if (m_tags.Contains(normalized, StringComparer.Ordinal)) + { return false; + } m_tags = m_tags .Append(normalized) - .OrderBy(static value => string.Equals(value, GameObject.defaultTag, StringComparison.Ordinal) ? 0 : 1) + .OrderBy(static value => string.Equals(value, GameObject.C_DEFAULT_TAG, StringComparison.Ordinal) ? 0 : 1) .ThenBy(static value => value, StringComparer.Ordinal) .ToArray(); return true; @@ -135,13 +138,18 @@ public bool Remove(string tag) { string normalized = Normalize(tag); ValidateState(); - if (string.Equals(normalized, GameObject.defaultTag, StringComparison.Ordinal)) + if (string.Equals(normalized, GameObject.C_DEFAULT_TAG, StringComparison.Ordinal)) + { return false; + } int index = Array.FindIndex( m_tags, - candidate => string.Equals(candidate, normalized, StringComparison.Ordinal)); + candidate => string.Equals(candidate, normalized, StringComparison.Ordinal) + ); if (index < 0) + { return false; + } m_tags = m_tags.Where(candidate => !string.Equals(candidate, normalized, StringComparison.Ordinal)).ToArray(); return true; } @@ -158,37 +166,46 @@ public GameTagCatalog Clone() return new GameTagCatalog { m_tags = (string[])m_tags.Clone() }; } - [OnSerializableRestored] - private void OnSerializableRestored() => ValidateState(); - internal static string Normalize(string tag) { ArgumentException.ThrowIfNullOrWhiteSpace(tag); string normalized = tag.Trim(); if (normalized.Contains('\r') || normalized.Contains('\n')) + { throw new ArgumentException("Tags cannot contain line breaks.", nameof(tag)); + } return normalized; } + [OnSerializableRestored] + private void OnSerializableRestored() => ValidateState(); + private void ValidateState() { if (m_tags is null || m_tags.Length == 0) + { throw new InvalidOperationException("A tag catalog must contain the built-in default tag."); + } string[] normalized = m_tags .Select(Normalize) - .OrderBy(static value => string.Equals(value, GameObject.defaultTag, StringComparison.Ordinal) ? 0 : 1) + .OrderBy(static value => string.Equals(value, GameObject.C_DEFAULT_TAG, StringComparison.Ordinal) ? 0 : 1) .ThenBy(static value => value, StringComparer.Ordinal) .ToArray(); - if (!string.Equals(normalized[0], GameObject.defaultTag, StringComparison.Ordinal)) + if (!string.Equals(normalized[0], GameObject.C_DEFAULT_TAG, StringComparison.Ordinal)) + { throw new InvalidOperationException("The built-in default tag must be the first project tag."); + } if (normalized.Distinct(StringComparer.Ordinal).Count() != normalized.Length) + { throw new InvalidOperationException("Project tag definitions must be unique."); - if (normalized.Select(ProjectLocalId.FromName).Distinct().Count() != normalized.Length) + } + if (normalized.Select(ProjectLocalID.FromName).Distinct().Count() != normalized.Length) { - throw new InvalidOperationException( - "Project tag names must produce unique project-local identities."); + throw new InvalidOperationException("Project tag names must produce unique project-local identities."); } if (!normalized.SequenceEqual(m_tags, StringComparer.Ordinal)) + { throw new InvalidOperationException("Project tag definitions are not normalized and deterministically ordered."); + } } } diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs new file mode 100644 index 000000000..3e7d9b216 --- /dev/null +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using Inno.Core.Serialization; + +namespace Inno.Scene; + +/// +/// Stores sparse semantic operations for one GameTag setting contribution. +/// +internal sealed class GameTagSettingContribution : ISerializable +{ + [SerializableProperty] + internal string[] additions { get; set; } = []; + + [SerializableProperty] + internal string[] removals { get; set; } = []; + + internal void Validate() + { + if (additions is null || removals is null) + { + throw new InvalidOperationException("GameTag contribution arrays cannot be null."); + } + string[] normalizedAdditions = additions.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); + string[] normalizedRemovals = removals.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); + if (!normalizedAdditions.SequenceEqual(additions, StringComparer.Ordinal) + || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length + ) { + throw new InvalidOperationException("GameTag additions must be unique, normalized, and ordered."); + } + if (!normalizedRemovals.SequenceEqual(removals, StringComparer.Ordinal) + || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length + ) { + throw new InvalidOperationException("GameTag removals must be unique, normalized, and ordered."); + } + if (normalizedAdditions.Intersect(normalizedRemovals, StringComparer.Ordinal).Any()) + { + throw new InvalidOperationException("A GameTag contribution cannot add and remove the same tag."); + } + } +} diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs index cf55dfeee..11e7b8038 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Core.Serialization; using Inno.Core.Settings; namespace Inno.Scene; @@ -11,8 +9,7 @@ namespace Inno.Scene; /// Composes sparse tag additions and removals from multiple setting contributors. /// [ProjectSettingComposer("inno.scene.tags")] -internal sealed class GameTagSettingsComposer - : ProjectSettingComposer +internal sealed class GameTagSettingsComposer : ProjectSettingComposer { /// /// Captures the contribution introduced by the supplied project setting value. @@ -67,67 +64,41 @@ protected override void Compose( GameTagCatalog target, IReadOnlyList> contributions ) { - var owners = target.GetTags().ToDictionary(static tag => tag, static _ => "host", StringComparer.Ordinal); + Dictionary owners = target.GetTags().ToDictionary(static tag => tag, static _ => "host", StringComparer.Ordinal); foreach (ProjectSettingContribution contribution in contributions) { contribution.value.Validate(); foreach (string tag in contribution.value.removals) { if (!target.IsDefined(tag)) + { continue; + } string owner = owners[tag]; if (!contribution.context.CanOverride(owner)) { throw new InvalidOperationException( - $"GameTag contribution '{contribution.context.contributorId}' cannot remove tag '{tag}' " + - $"owned by '{owner}'."); + $"GameTag contribution '{contribution.context.contributorID}' cannot remove tag '{tag}' " + + $"owned by '{owner}'." + ); } if (!target.Remove(tag)) { throw new InvalidOperationException( - $"GameTag contribution '{contribution.context.contributorId}' cannot remove built-in tag '{tag}'."); + $"GameTag contribution '{contribution.context.contributorID}' cannot remove built-in tag '{tag}'." + ); } owners.Remove(tag); } foreach (string tag in contribution.value.additions) { if (target.IsDefined(tag)) + { continue; + } _ = target.Add(tag); - owners.Add(tag, contribution.context.contributorId); + owners.Add(tag, contribution.context.contributorID); } } } } - -/// -/// Stores sparse semantic operations for one GameTag setting contribution. -/// -internal sealed class GameTagSettingContribution : ISerializable -{ - [SerializableProperty] - internal string[] additions { get; set; } = []; - - [SerializableProperty] - internal string[] removals { get; set; } = []; - - internal void Validate() - { - if (additions is null || removals is null) - throw new InvalidOperationException("GameTag contribution arrays cannot be null."); - string[] normalizedAdditions = additions.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); - string[] normalizedRemovals = removals.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); - if (!normalizedAdditions.SequenceEqual(additions, StringComparer.Ordinal) - || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length) - { - throw new InvalidOperationException("GameTag additions must be unique, normalized, and ordered."); - } - if (!normalizedRemovals.SequenceEqual(removals, StringComparer.Ordinal) - || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length) - { - throw new InvalidOperationException("GameTag removals must be unique, normalized, and ordered."); - } - if (normalizedAdditions.Intersect(normalizedRemovals, StringComparer.Ordinal).Any()) - throw new InvalidOperationException("A GameTag contribution cannot add and remove the same tag."); - } -} diff --git a/src/content/scene/Inno.Scene/Layers/GameLayer.cs b/src/content/scene/Inno.Scene/Layers/GameLayer.cs index 8a47248ed..dc2d44b9b 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayer.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; namespace Inno.Scene.Layers; @@ -12,11 +13,6 @@ namespace Inno.Scene.Layers; /// public const int C_MAX_COUNT = 32; - /// - /// Gets the built-in default layer stored in slot zero. - /// - public static GameLayer defaultLayer { get; } = new(0); - /// /// Creates a layer identifier from a zero-based layer index. /// @@ -29,10 +25,17 @@ namespace Inno.Scene.Layers; public GameLayer(int index) { if ((uint)index >= C_MAX_COUNT) + { throw new ArgumentOutOfRangeException(nameof(index), index, "A layer index must be between 0 and 31."); + } this.index = index; } + /// + /// Gets the built-in default layer stored in slot zero. + /// + public static GameLayer defaultLayer { get; } = new(0); + /// /// Gets the zero-based layer index. /// @@ -41,12 +44,12 @@ public GameLayer(int index) /// /// Compares this layer with another layer by index. /// - /// - /// A signed value describing the relative index ordering. - /// /// /// The value to compare with this instance. /// + /// + /// A signed value describing the relative index ordering. + /// public int CompareTo(GameLayer other) => index.CompareTo(other.index); /// @@ -63,12 +66,12 @@ public GameLayer(int index) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is GameLayer other && Equals(other); /// @@ -85,7 +88,7 @@ public GameLayer(int index) /// /// The human-readable representation of this value. /// - public override string ToString() => index.ToString(System.Globalization.CultureInfo.InvariantCulture); + public override string ToString() => index.ToString(CultureInfo.InvariantCulture); /// /// Determines whether two layer identifiers contain the same index. diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs b/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs index 6e0736953..b06850a64 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; @@ -13,14 +12,14 @@ namespace Inno.Scene.Layers; /// Stores the named layer catalog and symmetric layer-interaction matrix used by a project. /// [RequiresSerializationConverter] -[StableTypeId("bd64db72-60b2-4c79-af70-c6276202ad48")] -[ProjectSettingDefinition(GameLayerCatalog.settingProtocolId)] +[StableTypeID("bd64db72-60b2-4c79-af70-c6276202ad48")] +[ProjectSettingDefinition(GameLayerCatalog.C_SETTING_PROTOCOL_ID)] public sealed class GameLayerCatalog : ISerializable { /// /// Gets the immutable project-setting protocol value used by discovery metadata. /// - public const string settingProtocolId = "inno.scene.layers"; + public const string C_SETTING_PROTOCOL_ID = "inno.scene.layers"; private const string C_DEFAULT_LAYER_NAME = "Default"; @@ -33,11 +32,6 @@ public sealed class GameLayerCatalog : ISerializable [SerializableProperty] private uint[] m_interactionMasks; - /// - /// Gets the stable project setting protocol for the project-wide layer catalog. - /// - public static ProjectSettingId settingId => new(settingProtocolId); - /// /// Creates a layer stack containing the immutable default layer. /// @@ -50,6 +44,11 @@ public GameLayerCatalog() m_interactionMasks = Enumerable.Repeat(uint.MaxValue, GameLayer.C_MAX_COUNT).ToArray(); } + /// + /// Gets the stable project setting protocol for the project-wide layer catalog. + /// + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); + /// /// Gets the number of currently named layer slots. /// @@ -71,15 +70,12 @@ public int count public IReadOnlyList GetDefinitions() { ValidateState(); - var result = new List(); + List result = []; for (int index = 0; index < m_names.Length; index++) { if (m_names[index] is string name) { - result.Add(new GameLayerDefinition( - new ProjectLocalId(m_localIds[index]!), - new GameLayer(index), - name)); + result.Add(new GameLayerDefinition(new ProjectLocalID(m_localIds[index]!), new GameLayer(index), name)); } } return result; @@ -124,17 +120,17 @@ public bool IsDefined(GameLayer layer) /// /// The local identity, or . /// - public ProjectLocalId? GetLocalId(GameLayer layer) + public ProjectLocalID? GetLocalID(GameLayer layer) { ValidateState(); string? value = m_localIds[layer.index]; - return value is null ? null : new ProjectLocalId(value); + return value is null ? null : new ProjectLocalID(value); } /// /// Gets the complete identity assigned to a layer slot. /// - /// + /// /// The current project namespace. /// /// @@ -143,18 +139,18 @@ public bool IsDefined(GameLayer layer) /// /// The qualified identity, or . /// - public GameLayerId? GetId( - ProjectId projectId, + public GameLayerID? GetID( + ProjectID projectID, GameLayer layer ) { - ProjectLocalId? localId = GetLocalId(layer); - return localId is ProjectLocalId value ? new GameLayerId(projectId, value) : null; + ProjectLocalID? localID = GetLocalID(layer); + return localID is ProjectLocalID value ? new GameLayerID(projectID, value) : null; } /// /// Tries to resolve a local identity to its compact runtime slot. /// - /// + /// /// The stable project-local identity. /// /// @@ -164,16 +160,20 @@ GameLayer layer /// when the identity is defined. /// public bool TryGetLayer( - ProjectLocalId localId, + ProjectLocalID localID, out GameLayer layer ) { - if (string.IsNullOrEmpty(localId.value)) - throw new ArgumentException("A valid project-local layer ID is required.", nameof(localId)); + if (string.IsNullOrEmpty(localID.value)) + { + throw new ArgumentException("A valid project-local layer ID is required.", nameof(localID)); + } ValidateState(); for (int index = 0; index < m_localIds.Length; index++) { - if (!string.Equals(m_localIds[index], localId.value, StringComparison.Ordinal)) + if (!string.Equals(m_localIds[index], localID.value, StringComparison.Ordinal)) + { continue; + } layer = new GameLayer(index); return true; } @@ -182,35 +182,29 @@ out GameLayer layer } /// - /// Tries to resolve a qualified identity to its compact runtime slot. + /// Tries to resolve an ordinal layer name to its compact slot. /// - /// - /// The current project namespace. - /// - /// - /// The complete layer identity. + /// + /// The layer name to find. /// /// - /// The resolved runtime slot. + /// The resolved layer. /// /// - /// when the identity belongs to this project and is defined. + /// when a matching layer exists. /// public bool TryGetLayer( - ProjectId projectId, - GameLayerId id, + string name, out GameLayer layer ) { - if (!id.isValid) - throw new ArgumentException("A valid GameLayer ID is required.", nameof(id)); + string normalized = NormalizeName(name); ValidateState(); - for (int index = 0; index < m_localIds.Length; index++) + for (int index = 0; index < m_names.Length; index++) { - if (m_localIds[index] is not string local) - continue; - var candidate = new GameLayerId(projectId, new ProjectLocalId(local)); - if (candidate != id) + if (!string.Equals(m_names[index], normalized, StringComparison.Ordinal)) + { continue; + } layer = new GameLayer(index); return true; } @@ -219,27 +213,41 @@ out GameLayer layer } /// - /// Tries to resolve an ordinal layer name to its compact slot. + /// Tries to resolve a qualified identity to its compact runtime slot. /// - /// - /// The layer name to find. + /// + /// The current project namespace. + /// + /// + /// The complete layer identity. /// /// - /// The resolved layer. + /// The resolved runtime slot. /// /// - /// when a matching layer exists. + /// when the identity belongs to this project and is defined. /// public bool TryGetLayer( - string name, + ProjectID projectID, + GameLayerID id, out GameLayer layer ) { - string normalized = NormalizeName(name); + if (!id.isValid) + { + throw new ArgumentException("A valid GameLayer ID is required.", nameof(id)); + } ValidateState(); - for (int index = 0; index < m_names.Length; index++) + for (int index = 0; index < m_localIds.Length; index++) { - if (!string.Equals(m_names[index], normalized, StringComparison.Ordinal)) + if (m_localIds[index] is not string local) + { + continue; + } + var candidate = new GameLayerID(projectID, new ProjectLocalID(local)); + if (candidate != id) + { continue; + } layer = new GameLayer(index); return true; } @@ -259,7 +267,9 @@ out GameLayer layer public GameLayer GetLayer(string name) { if (TryGetLayer(name, out GameLayer layer)) + { return layer; + } throw new KeyNotFoundException($"GameLayer '{name}' is not defined."); } @@ -277,7 +287,9 @@ public GameLayerMask GetMask(IEnumerable names) ArgumentNullException.ThrowIfNull(names); GameLayerMask result = GameLayerMask.none; foreach (string name in names) + { result = result.With(GetLayer(name)); + } return result; } @@ -294,45 +306,9 @@ public void Define( GameLayer layer, string name ) { - ProjectLocalId localId = GetLocalId(layer) - ?? new ProjectLocalId($"layer.{layer.index.ToString("00", CultureInfo.InvariantCulture)}"); - DefineLocal(layer, localId, name); - } - - internal void DefineLocal( - GameLayer layer, - ProjectLocalId localId, - string name - ) { - if (string.IsNullOrEmpty(localId.value)) - throw new ArgumentException("A valid project-local layer ID is required.", nameof(localId)); - string normalized = NormalizeName(name); - ValidateState(); - for (int index = 0; index < m_names.Length; index++) - { - if (index != layer.index - && string.Equals(m_localIds[index], localId.value, StringComparison.Ordinal)) - { - throw new ArgumentException( - $"GameLayer local ID '{localId}' is already assigned to slot {index}.", - nameof(localId)); - } - if (index != layer.index - && string.Equals(m_names[index], normalized, StringComparison.Ordinal)) - { - throw new ArgumentException( - $"GameLayer name '{normalized}' is already assigned to slot {index}.", - nameof(name)); - } - } - if (layer == GameLayer.defaultLayer - && (localId != new ProjectLocalId("default") - || !string.Equals(normalized, C_DEFAULT_LAYER_NAME, StringComparison.Ordinal))) - { - throw new ArgumentException("The built-in default layer cannot be replaced.", nameof(layer)); - } - m_localIds[layer.index] = localId.value; - m_names[layer.index] = normalized; + ProjectLocalID localID = GetLocalID(layer) + ?? new ProjectLocalID($"layer.{layer.index.ToString("00", CultureInfo.InvariantCulture)}"); + DefineLocal(layer, localID, name); } /// @@ -348,9 +324,13 @@ public bool Remove(GameLayer layer) { ValidateState(); if (layer == GameLayer.defaultLayer) + { throw new InvalidOperationException("The built-in default layer cannot be removed."); + } if (m_names[layer.index] is null) + { return false; + } m_localIds[layer.index] = null; m_names[layer.index] = null; return true; @@ -440,16 +420,47 @@ public GameLayerCatalog Clone() }; } - internal static string NormalizeName(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - string normalized = name.Trim(); - if (normalized.Contains('\r') || normalized.Contains('\n')) - throw new ArgumentException("GameLayer names cannot contain line breaks.", nameof(name)); - return normalized; + internal void DefineLocal( + GameLayer layer, + ProjectLocalID localID, + string name + ) { + if (string.IsNullOrEmpty(localID.value)) + { + throw new ArgumentException("A valid project-local layer ID is required.", nameof(localID)); + } + string normalized = NormalizeName(name); + ValidateState(); + for (int index = 0; index < m_names.Length; index++) + { + if (index != layer.index + && string.Equals(m_localIds[index], localID.value, StringComparison.Ordinal) + ) { + throw new ArgumentException( + $"GameLayer local ID '{localID}' is already assigned to slot {index}.", + nameof(localID) + ); + } + if (index != layer.index + && string.Equals(m_names[index], normalized, StringComparison.Ordinal) + ) { + throw new ArgumentException( + $"GameLayer name '{normalized}' is already assigned to slot {index}.", + nameof(name) + ); + } + } + if (layer == GameLayer.defaultLayer + && (localID != new ProjectLocalID("default") + || !string.Equals(normalized, C_DEFAULT_LAYER_NAME, StringComparison.Ordinal)) + ) { + throw new ArgumentException("The built-in default layer cannot be replaced.", nameof(layer)); + } + m_localIds[layer.index] = localID.value; + m_names[layer.index] = normalized; } - internal string?[] CaptureLocalIds() + internal string?[] CaptureLocalIDs() { ValidateState(); return (string?[])m_localIds.Clone(); @@ -467,17 +478,28 @@ internal uint[] CaptureInteractionMasks() return (uint[])m_interactionMasks.Clone(); } + internal static string NormalizeName(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + string normalized = name.Trim(); + if (normalized.Contains('\r') || normalized.Contains('\n')) + { + throw new ArgumentException("GameLayer names cannot contain line breaks.", nameof(name)); + } + return normalized; + } + internal static GameLayerCatalog Restore( - string?[] localIds, + string?[] localIDs, string?[] names, uint[] interactionMasks ) { - ArgumentNullException.ThrowIfNull(localIds); + ArgumentNullException.ThrowIfNull(localIDs); ArgumentNullException.ThrowIfNull(names); ArgumentNullException.ThrowIfNull(interactionMasks); var stack = new GameLayerCatalog { - m_localIds = (string?[])localIds.Clone(), + m_localIds = (string?[])localIDs.Clone(), m_names = (string?[])names.Clone(), m_interactionMasks = (uint[])interactionMasks.Clone() }; @@ -488,14 +510,20 @@ uint[] interactionMasks private void ValidateState() { if (m_localIds is null || m_localIds.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two local ID slots."); + } if (m_names is null || m_names.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two name slots."); + } if (m_interactionMasks is null || m_interactionMasks.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two interaction masks."); + } if (!string.Equals(m_localIds[0], "default", StringComparison.Ordinal) - || !string.Equals(m_names[0], C_DEFAULT_LAYER_NAME, StringComparison.Ordinal)) - { + || !string.Equals(m_names[0], C_DEFAULT_LAYER_NAME, StringComparison.Ordinal) + ) { throw new InvalidOperationException("GameLayer slot zero must contain the built-in Default layer."); } @@ -503,20 +531,30 @@ private void ValidateState() var names = new HashSet(StringComparer.Ordinal); for (int index = 0; index < m_names.Length; index++) { - string? localId = m_localIds[index]; + string? localID = m_localIds[index]; string? name = m_names[index]; - if ((localId is null) != (name is null)) + if ((localID is null) != (name is null)) + { throw new InvalidOperationException($"GameLayer slot {index} must define both a local ID and a name."); - if (localId is null || name is null) + } + if (localID is null || name is null) + { continue; - var normalizedId = new ProjectLocalId(localId); - if (!ids.Add(normalizedId.value)) - throw new InvalidOperationException($"GameLayer local ID '{localId}' is assigned more than once."); + } + var normalizedID = new ProjectLocalID(localID); + if (!ids.Add(normalizedID.value)) + { + throw new InvalidOperationException($"GameLayer local ID '{localID}' is assigned more than once."); + } string normalizedName = NormalizeName(name); if (!string.Equals(name, normalizedName, StringComparison.Ordinal)) + { throw new InvalidOperationException($"GameLayer name in slot {index} is not normalized."); + } if (!names.Add(name)) + { throw new InvalidOperationException($"GameLayer name '{name}' is assigned more than once."); + } } for (int first = 0; first < m_interactionMasks.Length; first++) { @@ -527,7 +565,8 @@ private void ValidateState() if (forward != reverse) { throw new InvalidOperationException( - $"GameLayer interaction between slots {first} and {second} is not symmetric."); + $"GameLayer interaction between slots {first} and {second} is not symmetric." + ); } } } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs index 65e4d955d..cf48c738c 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs @@ -1,9 +1,8 @@ using System; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; @@ -27,12 +26,8 @@ GameLayerCatalog value ) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(value); - writer.Write( - "localIds", - value.CaptureLocalIds().Select(static id => id ?? string.Empty).ToArray()); - writer.Write( - "names", - value.CaptureNames().Select(static name => name ?? string.Empty).ToArray()); + writer.Write("localIds", value.CaptureLocalIDs().Select(static id => id ?? string.Empty).ToArray()); + writer.Write("names", value.CaptureNames().Select(static name => name ?? string.Empty).ToArray()); writer.Write("interactionMasks", value.CaptureInteractionMasks()); } @@ -48,12 +43,12 @@ GameLayerCatalog value public override GameLayerCatalog Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); - string?[] localIds = reader.Read("localIds") + string?[] localIDs = reader.Read("localIds") .Select(static id => string.IsNullOrEmpty(id) ? null : id) .ToArray(); string?[] names = reader.Read("names") .Select(static name => string.IsNullOrEmpty(name) ? null : name) .ToArray(); - return GameLayerCatalog.Restore(localIds, names, reader.Read("interactionMasks")); + return GameLayerCatalog.Restore(localIDs, names, reader.Read("interactionMasks")); } } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs index 44d6d3e6e..941089625 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs @@ -1,8 +1,7 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs b/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs index 1d6fed578..8d967b245 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -12,7 +11,7 @@ public sealed class GameLayerDefinition /// /// Creates an immutable layer definition. /// - /// + /// /// The stable project-independent identity. /// /// @@ -22,13 +21,15 @@ public sealed class GameLayerDefinition /// The non-empty display and lookup name. /// public GameLayerDefinition( - ProjectLocalId localId, + ProjectLocalID localID, GameLayer layer, string name ) { - if (string.IsNullOrEmpty(localId.value)) - throw new ArgumentException("A layer definition requires a valid local identity.", nameof(localId)); - this.localId = localId; + if (string.IsNullOrEmpty(localID.value)) + { + throw new ArgumentException("A layer definition requires a valid local identity.", nameof(localID)); + } + this.localID = localID; this.layer = layer; this.name = GameLayerCatalog.NormalizeName(name); } @@ -36,7 +37,7 @@ string name /// /// Gets the stable project-independent identity. /// - public ProjectLocalId localId { get; } + public ProjectLocalID localID { get; } /// /// Gets the layer slot represented by this definition. @@ -51,11 +52,11 @@ string name /// /// Resolves the complete identity under a project namespace. /// - /// + /// /// The current project namespace. /// /// /// The canonical project-scoped layer identity. /// - public GameLayerId GetId(ProjectId projectId) => new(projectId, localId); + public GameLayerID GetID(ProjectID projectID) => new(projectID, localID); } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerId.cs b/src/content/scene/Inno.Scene/Layers/GameLayerID.cs similarity index 85% rename from src/content/scene/Inno.Scene/Layers/GameLayerId.cs rename to src/content/scene/Inno.Scene/Layers/GameLayerID.cs index 7ef968808..a18527b7f 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerId.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerID.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -7,7 +6,7 @@ namespace Inno.Scene.Layers; /// /// Identifies one project-scoped game layer independently from its compact runtime slot. /// -public readonly record struct GameLayerId +public readonly record struct GameLayerID { /// /// Creates a project-scoped layer identity. @@ -15,36 +14,23 @@ public readonly record struct GameLayerId /// /// The canonical qualified identity. /// - public GameLayerId(ProjectScopedId value) + public GameLayerID(ProjectScopedID value) { if (string.IsNullOrEmpty(value.name.value)) + { throw new ArgumentException("A GameLayer ID requires a valid project-local name.", nameof(value)); + } this.value = value.value; } - /// - /// Creates a project-scoped layer identity from its project and local parts. - /// - /// - /// The current project identity. - /// - /// - /// The stable project-local layer identity. - /// - public GameLayerId( - ProjectId projectId, - ProjectLocalId name - ) - : this(projectId.Qualify(name)) - { - } - - internal GameLayerId(string value) + internal GameLayerID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); string normalized = value.Trim(); if (!normalized.Contains('.', StringComparison.Ordinal)) + { throw new ArgumentException("A GameLayer ID must contain project and local name segments.", nameof(value)); + } for (int index = 0; index < normalized.Length; index++) { char character = normalized[index]; @@ -52,11 +38,27 @@ internal GameLayerId(string value) || character is >= '0' and <= '9' || character is '.' or '-' or '_'; if (!valid) + { throw new ArgumentException("A GameLayer ID is not portable.", nameof(value)); + } } this.value = normalized; } + /// + /// Creates a project-scoped layer identity from its project and local parts. + /// + /// + /// The current project identity. + /// + /// + /// The stable project-local layer identity. + /// + public GameLayerID( + ProjectID projectID, + ProjectLocalID name + ) : this(projectID.Qualify(name)) {} + /// /// Gets the canonical projectId.name identity string. /// diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerIDConverter.cs similarity index 83% rename from src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs rename to src/content/scene/Inno.Scene/Layers/GameLayerIDConverter.cs index 019cc059e..cb07fddbc 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerIDConverter.cs @@ -1,15 +1,14 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; /// /// Converts a logical layer identity through its stable string value. /// -internal sealed class GameLayerIdConverter : SerializationConverter +internal sealed class GameLayerIDConverter : SerializationConverter { /// /// Writes the complete value through the configured serialization contract. @@ -22,7 +21,7 @@ internal sealed class GameLayerIdConverter : SerializationConverter /// public override void Write( SerializationWriter writer, - GameLayerId value + GameLayerID value ) { ArgumentNullException.ThrowIfNull(writer); writer.Write("value", value.value); @@ -37,9 +36,9 @@ GameLayerId value /// /// The validated game layer id that represents the completed operation. /// - public override GameLayerId Read(SerializationReader reader) + public override GameLayerID Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); - return new GameLayerId(reader.Read("value")); + return new GameLayerID(reader.Read("value")); } } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs index b49ef99d8..4665e4318 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs @@ -8,16 +8,6 @@ namespace Inno.Scene.Layers; /// public readonly struct GameLayerMask : IEquatable { - /// - /// Gets a mask containing no layers. - /// - public static GameLayerMask none { get; } = new(0u); - - /// - /// Gets a mask containing every supported layer. - /// - public static GameLayerMask everything { get; } = new(uint.MaxValue); - /// /// Creates a mask from its raw thirty-two-bit representation. /// @@ -30,62 +20,51 @@ public GameLayerMask(uint value) } /// - /// Gets the raw thirty-two-bit mask value. + /// Gets a mask containing no layers. /// - public uint value { get; } + public static GameLayerMask none { get; } = new(0u); /// - /// Creates a mask containing the supplied layers. + /// Gets a mask containing every supported layer. /// - /// - /// The layers whose bits should be enabled. - /// - /// - /// A mask containing every supplied layer. - /// - /// - /// Thrown when is . - /// - public static GameLayerMask FromLayers(IEnumerable layers) - { - ArgumentNullException.ThrowIfNull(layers); - uint bits = 0u; - foreach (GameLayer layer in layers) - bits |= 1u << layer.index; - return new GameLayerMask(bits); - } + public static GameLayerMask everything { get; } = new(uint.MaxValue); + + /// + /// Gets the raw thirty-two-bit mask value. + /// + public uint value { get; } /// /// Determines whether the supplied layer is contained in this mask. /// - /// - /// when the layer bit is enabled. - /// /// /// The layer consumed by contains; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when the layer bit is enabled. + /// public bool Contains(GameLayer layer) => (value & (1u << layer.index)) != 0u; /// /// Returns a mask with the supplied layer enabled. /// - /// - /// The updated immutable mask. - /// /// /// The layer consumed by with; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The updated immutable mask. + /// public GameLayerMask With(GameLayer layer) => new(value | (1u << layer.index)); /// /// Returns a mask with the supplied layer disabled. /// - /// - /// The updated immutable mask. - /// /// /// The layer consumed by without; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The updated immutable mask. + /// public GameLayerMask Without(GameLayer layer) => new(value & ~(1u << layer.index)); /// @@ -102,12 +81,12 @@ public static GameLayerMask FromLayers(IEnumerable layers) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is GameLayerMask other && Equals(other); /// @@ -126,6 +105,29 @@ public static GameLayerMask FromLayers(IEnumerable layers) /// public override string ToString() => $"0x{value:X8}"; + /// + /// Creates a mask containing the supplied layers. + /// + /// + /// The layers whose bits should be enabled. + /// + /// + /// A mask containing every supplied layer. + /// + /// + /// Thrown when is . + /// + public static GameLayerMask FromLayers(IEnumerable layers) + { + ArgumentNullException.ThrowIfNull(layers); + uint bits = 0u; + foreach (GameLayer layer in layers) + { + bits |= 1u << layer.index; + } + return new GameLayerMask(bits); + } + /// /// Combines the enabled bits from two masks. /// diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs index 26d36aadb..6bba57529 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs @@ -1,8 +1,7 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs b/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs new file mode 100644 index 000000000..ccbc23fa9 --- /dev/null +++ b/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Serialization; +using Inno.Core.Settings; + +namespace Inno.Scene.Layers; + +/// +/// Stores sparse semantic operations for one GameLayer setting contribution. +/// +internal sealed class GameLayerSettingContribution : ISerializable +{ + [SerializableProperty] + internal int[] removedSlots { get; set; } = []; + + [SerializableProperty] + internal string[] removedLocalIds { get; set; } = []; + + [SerializableProperty] + internal int[] upsertSlots { get; set; } = []; + + [SerializableProperty] + internal string[] upsertLocalIds { get; set; } = []; + + [SerializableProperty] + internal string[] upsertNames { get; set; } = []; + + [SerializableProperty] + internal int[] interactionFirstSlots { get; set; } = []; + + [SerializableProperty] + internal int[] interactionSecondSlots { get; set; } = []; + + [SerializableProperty] + internal bool[] interactionValues { get; set; } = []; + + internal void Validate() + { + if (removedSlots is null + || removedLocalIds is null + || upsertSlots is null + || upsertLocalIds is null + || upsertNames is null + || interactionFirstSlots is null + || interactionSecondSlots is null + || interactionValues is null + ) { + throw new InvalidOperationException("GameLayer contribution arrays cannot be null."); + } + if (removedSlots.Length != removedLocalIds.Length) + { + throw new InvalidOperationException("GameLayer removal contribution arrays must have equal lengths."); + } + if (upsertSlots.Length != upsertLocalIds.Length || upsertSlots.Length != upsertNames.Length) + { + throw new InvalidOperationException("GameLayer upsert contribution arrays must have equal lengths."); + } + if (interactionFirstSlots.Length != interactionSecondSlots.Length + || interactionFirstSlots.Length != interactionValues.Length + ) { + throw new InvalidOperationException("GameLayer interaction contribution arrays must have equal lengths."); + } + + var slots = new HashSet(); + for (int index = 0; index < removedSlots.Length; index++) + { + _ = new GameLayer(removedSlots[index]); + _ = new ProjectLocalID(removedLocalIds[index]); + if (!slots.Add(removedSlots[index])) + { + throw new InvalidOperationException($"GameLayer slot {removedSlots[index]} is removed more than once."); + } + } + slots.Clear(); + for (int index = 0; index < upsertSlots.Length; index++) + { + _ = new GameLayer(upsertSlots[index]); + _ = new ProjectLocalID(upsertLocalIds[index]); + _ = GameLayerCatalog.NormalizeName(upsertNames[index]); + if (!slots.Add(upsertSlots[index])) + { + throw new InvalidOperationException($"GameLayer slot {upsertSlots[index]} is upserted more than once."); + } + } + var pairs = new HashSet<(int first, int second)>(); + for (int index = 0; index < interactionFirstSlots.Length; index++) + { + int first = interactionFirstSlots[index]; + int second = interactionSecondSlots[index]; + _ = new GameLayer(first); + _ = new GameLayer(second); + if (first > second) + { + throw new InvalidOperationException("GameLayer interaction pairs must use canonical slot order."); + } + if (!pairs.Add((first, second))) + { + throw new InvalidOperationException( + $"GameLayer interaction ({first}, {second}) is contributed more than once." + ); + } + } + } +} diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs index 95a3ee12d..31f9515d5 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; - -using Inno.Core.Serialization; using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -10,8 +8,7 @@ namespace Inno.Scene.Layers; /// Composes sparse project-local layer and interaction contributions into one compact runtime stack. /// [ProjectSettingComposer("inno.scene.layers")] -internal sealed class GameLayerSettingsComposer - : ProjectSettingComposer +internal sealed class GameLayerSettingsComposer : ProjectSettingComposer { /// /// Captures project-local layer and interaction changes relative to the baseline stack. @@ -29,36 +26,36 @@ protected override GameLayerSettingContribution CaptureContribution( GameLayerCatalog baseline, GameLayerCatalog value ) { - var removedSlots = new List(); - var removedLocalIds = new List(); - var upsertSlots = new List(); - var upsertLocalIds = new List(); - var upsertNames = new List(); + List removedSlots = []; + List removedLocalIDs = []; + List upsertSlots = []; + List upsertLocalIDs = []; + List upsertNames = []; for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) { var layer = new GameLayer(index); - ProjectLocalId? baselineId = baseline.GetLocalId(layer); - ProjectLocalId? valueId = value.GetLocalId(layer); + ProjectLocalID? baselineID = baseline.GetLocalID(layer); + ProjectLocalID? valueID = value.GetLocalID(layer); string? baselineName = baseline.GetName(layer); string? valueName = value.GetName(layer); - if (baselineId is ProjectLocalId oldId && oldId != valueId) + if (baselineID is ProjectLocalID oldID && oldID != valueID) { removedSlots.Add(index); - removedLocalIds.Add(oldId.value); + removedLocalIDs.Add(oldID.value); } - if (valueId is ProjectLocalId newId - && (baselineId != valueId - || !string.Equals(baselineName, valueName, StringComparison.Ordinal))) - { + if (valueID is ProjectLocalID newID + && (baselineID != valueID + || !string.Equals(baselineName, valueName, StringComparison.Ordinal)) + ) { upsertSlots.Add(index); - upsertLocalIds.Add(newId.value); + upsertLocalIDs.Add(newID.value); upsertNames.Add(valueName!); } } - var interactionFirstSlots = new List(); - var interactionSecondSlots = new List(); - var interactionValues = new List(); + List interactionFirstSlots = []; + List interactionSecondSlots = []; + List interactionValues = []; for (int first = 0; first < GameLayer.C_MAX_COUNT; first++) { for (int second = first; second < GameLayer.C_MAX_COUNT; second++) @@ -68,7 +65,9 @@ GameLayerCatalog value bool baselineValue = baseline.CanInteract(firstLayer, secondLayer); bool authoredValue = value.CanInteract(firstLayer, secondLayer); if (baselineValue == authoredValue) + { continue; + } interactionFirstSlots.Add(first); interactionSecondSlots.Add(second); interactionValues.Add(authoredValue); @@ -78,9 +77,9 @@ GameLayerCatalog value return new GameLayerSettingContribution { removedSlots = removedSlots.ToArray(), - removedLocalIds = removedLocalIds.ToArray(), + removedLocalIds = removedLocalIDs.ToArray(), upsertSlots = upsertSlots.ToArray(), - upsertLocalIds = upsertLocalIds.ToArray(), + upsertLocalIds = upsertLocalIDs.ToArray(), upsertNames = upsertNames.ToArray(), interactionFirstSlots = interactionFirstSlots.ToArray(), interactionSecondSlots = interactionSecondSlots.ToArray(), @@ -119,25 +118,27 @@ protected override void Compose( IReadOnlyList> contributions ) { var slotOwners = new string?[GameLayer.C_MAX_COUNT]; - var localIdOwners = new Dictionary(); + var localIDOwners = new Dictionary(); var interactionOwners = new string[GameLayer.C_MAX_COUNT, GameLayer.C_MAX_COUNT]; for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) { var layer = new GameLayer(index); - if (target.GetLocalId(layer) is ProjectLocalId localId) + if (target.GetLocalID(layer) is ProjectLocalID localID) { slotOwners[index] = "host"; - localIdOwners.Add(localId, "host"); + localIDOwners.Add(localID, "host"); } for (int second = 0; second < GameLayer.C_MAX_COUNT; second++) + { interactionOwners[index, second] = "host"; + } } foreach (ProjectSettingContribution contribution in contributions) { contribution.value.Validate(); - ApplyRemovals(target, contribution, slotOwners, localIdOwners); - ApplyUpserts(target, contribution, slotOwners, localIdOwners); + ApplyRemovals(target, contribution, slotOwners, localIDOwners); + ApplyUpserts(target, contribution, slotOwners, localIDOwners); ApplyInteractions(target, contribution, interactionOwners); } } @@ -146,27 +147,32 @@ private static void ApplyRemovals( GameLayerCatalog target, ProjectSettingContribution contribution, string?[] slotOwners, - Dictionary localIdOwners + Dictionary localIDOwners ) { for (int index = 0; index < contribution.value.removedSlots.Length; index++) { var layer = new GameLayer(contribution.value.removedSlots[index]); - var expected = new ProjectLocalId(contribution.value.removedLocalIds[index]); - ProjectLocalId? current = target.GetLocalId(layer); + var expected = new ProjectLocalID(contribution.value.removedLocalIds[index]); + ProjectLocalID? current = target.GetLocalID(layer); if (current is null) + { continue; + } if (current != expected) { throw Conflict( contribution.context, - $"cannot remove layer '{expected}' from slot {layer.index} because it contains '{current}'."); + $"cannot remove layer '{expected}' from slot {layer.index} because it contains '{current}'." + ); } string owner = slotOwners[layer.index] ?? "host"; if (!contribution.context.CanOverride(owner)) + { throw Conflict(contribution.context, $"cannot remove layer '{expected}' owned by '{owner}'."); + } _ = target.Remove(layer); slotOwners[layer.index] = null; - localIdOwners.Remove(expected); + localIDOwners.Remove(expected); } } @@ -174,46 +180,50 @@ private static void ApplyUpserts( GameLayerCatalog target, ProjectSettingContribution contribution, string?[] slotOwners, - Dictionary localIdOwners + Dictionary localIDOwners ) { for (int index = 0; index < contribution.value.upsertSlots.Length; index++) { var layer = new GameLayer(contribution.value.upsertSlots[index]); - var localId = new ProjectLocalId(contribution.value.upsertLocalIds[index]); + var localID = new ProjectLocalID(contribution.value.upsertLocalIds[index]); string name = contribution.value.upsertNames[index]; - ProjectLocalId? currentId = target.GetLocalId(layer); + ProjectLocalID? currentID = target.GetLocalID(layer); string? currentName = target.GetName(layer); - if (currentId == localId && string.Equals(currentName, name, StringComparison.Ordinal)) + if (currentID == localID && string.Equals(currentName, name, StringComparison.Ordinal)) + { continue; + } - if (target.TryGetLayer(localId, out GameLayer existingLayer) && existingLayer != layer) + if (target.TryGetLayer(localID, out GameLayer existingLayer) && existingLayer != layer) { - string existingOwner = slotOwners[existingLayer.index] ?? localIdOwners[localId]; + string existingOwner = slotOwners[existingLayer.index] ?? localIDOwners[localID]; if (!contribution.context.CanOverride(existingOwner)) { throw Conflict( contribution.context, - $"cannot move layer '{localId}' from slot {existingLayer.index}; it is owned by '{existingOwner}'."); + $"cannot move layer '{localID}' from slot {existingLayer.index}; it is owned by '{existingOwner}'." + ); } _ = target.Remove(existingLayer); slotOwners[existingLayer.index] = null; - localIdOwners.Remove(localId); + localIDOwners.Remove(localID); } - if (currentId is ProjectLocalId replacedId) + if (currentID is ProjectLocalID replacedID) { - string owner = slotOwners[layer.index] ?? localIdOwners[replacedId]; + string owner = slotOwners[layer.index] ?? localIDOwners[replacedID]; if (!contribution.context.CanOverride(owner)) { throw Conflict( contribution.context, - $"cannot replace slot {layer.index} layer '{replacedId}' owned by '{owner}'."); + $"cannot replace slot {layer.index} layer '{replacedID}' owned by '{owner}'." + ); } - localIdOwners.Remove(replacedId); + localIDOwners.Remove(replacedID); } - target.DefineLocal(layer, localId, name); - slotOwners[layer.index] = contribution.context.contributorId; - localIdOwners[localId] = contribution.context.contributorId; + target.DefineLocal(layer, localID, name); + slotOwners[layer.index] = contribution.context.contributorID; + localIDOwners[localID] = contribution.context.contributorID; } } @@ -228,110 +238,25 @@ private static void ApplyInteractions( var second = new GameLayer(contribution.value.interactionSecondSlots[index]); bool value = contribution.value.interactionValues[index]; if (target.CanInteract(first, second) == value) + { continue; + } string owner = interactionOwners[first.index, second.index]; if (!contribution.context.CanOverride(owner)) { throw Conflict( contribution.context, - $"cannot replace interaction ({first.index}, {second.index}) owned by '{owner}'."); + $"cannot replace interaction ({first.index}, {second.index}) owned by '{owner}'." + ); } target.SetInteraction(first, second, value); - interactionOwners[first.index, second.index] = contribution.context.contributorId; - interactionOwners[second.index, first.index] = contribution.context.contributorId; + interactionOwners[first.index, second.index] = contribution.context.contributorID; + interactionOwners[second.index, first.index] = contribution.context.contributorID; } } private static InvalidOperationException Conflict( ProjectSettingContributionContext context, string message - ) - => new($"GameLayer contribution '{context.contributorId}' {message}"); -} - -/// -/// Stores sparse semantic operations for one GameLayer setting contribution. -/// -internal sealed class GameLayerSettingContribution : ISerializable -{ - [SerializableProperty] - internal int[] removedSlots { get; set; } = []; - - [SerializableProperty] - internal string[] removedLocalIds { get; set; } = []; - - [SerializableProperty] - internal int[] upsertSlots { get; set; } = []; - - [SerializableProperty] - internal string[] upsertLocalIds { get; set; } = []; - - [SerializableProperty] - internal string[] upsertNames { get; set; } = []; - - [SerializableProperty] - internal int[] interactionFirstSlots { get; set; } = []; - - [SerializableProperty] - internal int[] interactionSecondSlots { get; set; } = []; - - [SerializableProperty] - internal bool[] interactionValues { get; set; } = []; - - internal void Validate() - { - if (removedSlots is null - || removedLocalIds is null - || upsertSlots is null - || upsertLocalIds is null - || upsertNames is null - || interactionFirstSlots is null - || interactionSecondSlots is null - || interactionValues is null) - { - throw new InvalidOperationException("GameLayer contribution arrays cannot be null."); - } - if (removedSlots.Length != removedLocalIds.Length) - throw new InvalidOperationException("GameLayer removal contribution arrays must have equal lengths."); - if (upsertSlots.Length != upsertLocalIds.Length || upsertSlots.Length != upsertNames.Length) - throw new InvalidOperationException("GameLayer upsert contribution arrays must have equal lengths."); - if (interactionFirstSlots.Length != interactionSecondSlots.Length - || interactionFirstSlots.Length != interactionValues.Length) - { - throw new InvalidOperationException("GameLayer interaction contribution arrays must have equal lengths."); - } - - var slots = new HashSet(); - for (int index = 0; index < removedSlots.Length; index++) - { - _ = new GameLayer(removedSlots[index]); - _ = new ProjectLocalId(removedLocalIds[index]); - if (!slots.Add(removedSlots[index])) - throw new InvalidOperationException($"GameLayer slot {removedSlots[index]} is removed more than once."); - } - slots.Clear(); - for (int index = 0; index < upsertSlots.Length; index++) - { - _ = new GameLayer(upsertSlots[index]); - _ = new ProjectLocalId(upsertLocalIds[index]); - _ = GameLayerCatalog.NormalizeName(upsertNames[index]); - if (!slots.Add(upsertSlots[index])) - throw new InvalidOperationException($"GameLayer slot {upsertSlots[index]} is upserted more than once."); - } - var pairs = new HashSet<(int first, int second)>(); - for (int index = 0; index < interactionFirstSlots.Length; index++) - { - int first = interactionFirstSlots[index]; - int second = interactionSecondSlots[index]; - _ = new GameLayer(first); - _ = new GameLayer(second); - if (first > second) - throw new InvalidOperationException("GameLayer interaction pairs must use canonical slot order."); - if (!pairs.Add((first, second))) - { - throw new InvalidOperationException( - $"GameLayer interaction ({first}, {second}) is contributed more than once."); - } - } - } + ) => new($"GameLayer contribution '{context.contributorID}' {message}"); } diff --git a/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs b/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs index 9e6358f6e..4547216a6 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs @@ -33,10 +33,14 @@ internal void FixedUpdate() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (behavior.isActiveAndEnabled) + { behavior.DispatchFixedUpdate(); + } } } @@ -49,10 +53,14 @@ internal void Update() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (!behavior.isActiveAndEnabled || !behavior.lifecycleStartCalled) + { continue; + } behavior.DispatchUpdate(); } } @@ -65,10 +73,14 @@ internal void LateUpdate() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (behavior.isActiveAndEnabled && behavior.lifecycleStartCalled) + { behavior.DispatchLateUpdate(); + } } } @@ -77,7 +89,9 @@ internal void Refresh(GameBehavior behavior) EnsureIndexes(); GameBehaviorLifecyclePhase phases = GetPhases(behavior); if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { SynchronizeActivation(behavior); + } UpdateStartEligibility(behavior, phases); } @@ -85,7 +99,9 @@ internal void RefreshAll() { EnsureIndexes(); for (int index = 0; index < m_activationBehaviors.Length; index++) + { SynchronizeActivation(m_activationBehaviors[index]); + } for (int index = 0; index < m_variableFrameBehaviors.Length; index++) { GameBehavior behavior = m_variableFrameBehaviors[index]; @@ -97,7 +113,9 @@ internal void Destroy(GameBehavior behavior) { GameBehaviorLifecyclePhase phases = GetPhases(behavior); if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { SceneLifecycle.Destroy(behavior); + } } internal void Invalidate() @@ -118,7 +136,9 @@ internal void Invalidate() private void PreparePendingActivation() { if (m_pendingActivation.Count == 0) + { return; + } GameBehavior[] pending = [.. m_pendingActivation]; m_pendingActivation.Clear(); @@ -128,23 +148,31 @@ private void PreparePendingActivation() if (!m_scene.canDispatch) { for (; index < pending.Length; index++) + { QueueActivation(pending[index]); + } break; } GameBehavior behavior = pending[index]; if (!NeedsActivationPreparation(behavior)) + { continue; + } _ = SceneLifecycle.Prepare(behavior, m_scene); if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } } } private void DispatchPendingStart() { if (m_pendingStart.Count == 0) + { return; + } GameBehavior[] pending = [.. m_pendingStart]; m_pendingStart.Clear(); @@ -154,13 +182,17 @@ private void DispatchPendingStart() if (!m_scene.canDispatch) { for (; index < pending.Length; index++) + { UpdateStartEligibility(pending[index], GetPhases(pending[index])); + } break; } GameBehavior behavior = pending[index]; if (behavior.isDestroyed || behavior.lifecycleStartCalled || !behavior.isActiveAndEnabled) + { continue; + } behavior.lifecycleStartCalled = true; behavior.DispatchStart(); } @@ -171,30 +203,44 @@ private void EnsureIndexes() long sceneRevision = m_scene.structureRevision; long typeGeneration = m_scene.typeCatalog.generation; if (m_indexedSceneRevision == sceneRevision && m_indexedTypeGeneration == typeGeneration) + { return; + } IReadOnlyList behaviors = m_scene.GetComponents(); - var activation = new List(); - var variableFrame = new List(); - var update = new List(); - var fixedUpdate = new List(); - var lateUpdate = new List(); + List activation = []; + List variableFrame = []; + List update = []; + List fixedUpdate = []; + List lateUpdate = []; for (int index = 0; index < behaviors.Count; index++) { GameBehavior behavior = behaviors[index]; GameBehaviorLifecyclePhase phases = GetPhases(behavior); if (phases == GameBehaviorLifecyclePhase.None) + { continue; + } if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { activation.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.VariableFrame) != 0) + { variableFrame.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.Update) != 0) + { update.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.FixedUpdate) != 0) + { fixedUpdate.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.LateUpdate) != 0) + { lateUpdate.Add(behavior); + } } m_pendingActivation.Clear(); @@ -210,7 +256,9 @@ private void EnsureIndexes() { GameBehavior behavior = m_activationBehaviors[index]; if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } } for (int index = 0; index < m_variableFrameBehaviors.Length; index++) { @@ -231,41 +279,51 @@ private void SynchronizeActivation(GameBehavior behavior) _ = SceneLifecycle.Prepare(behavior, m_scene); if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } else + { m_pendingActivationSet.Remove(behavior); + } } private void UpdateStartEligibility( GameBehavior behavior, GameBehaviorLifecyclePhase phases ) { - if ((phases & GameBehaviorLifecyclePhase.VariableFrame) == 0 || - behavior.isDestroyed || - behavior.lifecycleStartCalled || - !behavior.isActiveAndEnabled) - { + if ((phases & GameBehaviorLifecyclePhase.VariableFrame) == 0 + || behavior.isDestroyed + || behavior.lifecycleStartCalled + || !behavior.isActiveAndEnabled + ) { m_pendingStartSet.Remove(behavior); return; } if (m_pendingStartSet.Add(behavior)) + { m_pendingStart.Add(behavior); + } } private void QueueActivation(GameBehavior behavior) { if (!behavior.isDestroyed && m_pendingActivationSet.Add(behavior)) + { m_pendingActivation.Add(behavior); + } } + private GameBehaviorLifecyclePhase GetPhases(GameBehavior behavior) => behavior.lifecyclePhases; + private static bool NeedsActivationPreparation(GameBehavior behavior) { if (behavior.isDestroyed || behavior.lifecycleDestroyCalled) + { return false; + } bool active = behavior.isActiveAndEnabled; return (active && !behavior.lifecycleAwakeCalled) || active != behavior.lifecycleWasEnabled; } - - private GameBehaviorLifecyclePhase GetPhases(GameBehavior behavior) => behavior.lifecyclePhases; } diff --git a/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs b/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs index 9ad20455d..13e827f5d 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs @@ -21,10 +21,12 @@ internal interface ISceneLifecycleObject /// Gets or sets whether the one-time Awake callback has already been dispatched. /// bool lifecycleAwakeCalled { get; set; } + /// /// Gets or sets whether the one-time Start callback has already been dispatched. /// bool lifecycleStartCalled { get; set; } + /// /// Gets or sets whether the terminal destruction callback has already been dispatched. /// diff --git a/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs b/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs index 981ea1a20..ff8f37d9f 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs @@ -7,7 +7,9 @@ internal static bool Prepare( GameScene scene ) { if (target.lifecycleIsDestroyed || target.lifecycleDestroyCalled) + { return false; + } bool active = target.lifecycleIsActive; if (active && !target.lifecycleAwakeCalled) @@ -15,12 +17,34 @@ GameScene scene target.lifecycleAwakeCalled = true; target.DispatchAwake(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } return PrepareActivation(target, scene); } + internal static void DisableForReload(ISceneLifecycleObject target) => Disable(target); + + internal static void Destroy(ISceneLifecycleObject target) + { + if (target.lifecycleDestroyCalled) + { + return; + } + target.lifecycleDestroyCalled = true; + if (target.lifecycleWasEnabled) + { + target.lifecycleWasEnabled = false; + target.DispatchDisable(); + } + if (target.lifecycleAwakeCalled) + { + target.DispatchDestroy(); + } + } + private static bool PrepareActivation( ISceneLifecycleObject target, GameScene scene @@ -31,41 +55,30 @@ GameScene scene target.lifecycleWasEnabled = true; target.DispatchEnable(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } else if (!active && target.lifecycleWasEnabled) { target.lifecycleWasEnabled = false; target.DispatchDisable(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } return true; } - internal static void DisableForReload(ISceneLifecycleObject target) => Disable(target); - private static void Disable(ISceneLifecycleObject target) { if (!target.lifecycleWasEnabled) + { return; + } target.lifecycleWasEnabled = false; target.DispatchDisable(); } - - internal static void Destroy(ISceneLifecycleObject target) - { - if (target.lifecycleDestroyCalled) - return; - target.lifecycleDestroyCalled = true; - if (target.lifecycleWasEnabled) - { - target.lifecycleWasEnabled = false; - target.DispatchDisable(); - } - if (target.lifecycleAwakeCalled) - target.DispatchDestroy(); - } - } diff --git a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs index 3db87882b..38127275f 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Collections; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -19,7 +18,7 @@ internal sealed class SceneSystemScheduler private readonly GameBehaviorLifecycleRunner m_behaviors; private readonly IndexedObjectStore m_systems = new(); private readonly IndexedObjectKey m_systemKey; - private readonly IndexedObjectKey m_persistentIdKey; + private readonly IndexedObjectKey m_persistentIDKey; private readonly IndexedObjectKey m_typeKey; private readonly List m_displayOrder = []; private ReadOnlyCollection? m_displayView; @@ -33,68 +32,62 @@ SceneTypeCatalog types m_types = types; m_behaviors = new GameBehaviorLifecycleRunner(scene); m_systemKey = m_systems.DefineKey("scene.system", IndexedObjectKeyFlags.Unique); - m_persistentIdKey = m_systems.DefineKey( - "scene.system.persistent-id", - IndexedObjectKeyFlags.Unique); + m_persistentIDKey = m_systems.DefineKey("scene.system.persistent-id", IndexedObjectKeyFlags.Unique); m_typeKey = m_systems.DefineKey("scene.system.type"); } - internal TSystem Add() where TSystem : GameSystem, new() - => (TSystem)Add(typeof(TSystem), persistentId: null, invokeReset: true); + internal TSystem Add() + where TSystem : GameSystem, new() + => (TSystem)Add(typeof(TSystem), persistentID: null, invokeReset: true); internal GameSystem Add( Type systemType, - Guid? persistentId, + Guid? persistentID, bool invokeReset ) { ArgumentNullException.ThrowIfNull(systemType); - if (!m_types.TryGetSystem(systemType, out SceneSystemTypeDescriptor? descriptor) || - !descriptor!.isConcrete) - { + if (!m_types.TryGetSystem(systemType, out SceneSystemTypeDescriptor? descriptor) + || !descriptor!.isConcrete + ) { throw new ArgumentException( $"Type '{systemType.FullName}' is not an active concrete GameSystem.", - nameof(systemType)); + nameof(systemType) + ); } - var system = (GameSystem)m_types.snapshot.CreateInstance(systemType); - Add(system, descriptor, persistentId, invokeReset); + GameSystem system = (GameSystem)m_types.snapshot.CreateInstance(systemType); + Add(system, descriptor, persistentID, invokeReset); return system; } + internal void Add( + GameSystem system, + Guid? persistentID = null, + bool invokeReset = true + ) { + ArgumentNullException.ThrowIfNull(system); + SceneSystemTypeDescriptor descriptor = m_types.GetSystem(system.GetType()); + Add(system, descriptor, persistentID, invokeReset); + } + internal MissingGameSystem AddMissing( TypeRef missingType, string missingTypeName, ReadOnlySpan serializedState, - Guid? persistentId, + Guid? persistentID, IReadOnlyList? dependencies = null ) { - var system = new MissingGameSystem( - missingType, - missingTypeName, - serializedState, - dependencies); - Add( - system, - m_types.GetSystem(typeof(MissingGameSystem)), - persistentId, - invokeReset: false); + var system = new MissingGameSystem(missingType, missingTypeName, serializedState, dependencies); + Add(system, m_types.GetSystem(typeof(MissingGameSystem)), persistentID, invokeReset: false); return system; } - internal void Add( - GameSystem system, - Guid? persistentId = null, - bool invokeReset = true - ) { - ArgumentNullException.ThrowIfNull(system); - SceneSystemTypeDescriptor descriptor = m_types.GetSystem(system.GetType()); - Add(system, descriptor, persistentId, invokeReset); - } - internal bool Remove(GameSystem system) { if (!TryGetEntry(system, out SystemEntry? entry)) + { return false; + } m_systems.Remove(entry!); m_displayOrder.Remove(entry!); RefreshDisplayIndices(); @@ -106,7 +99,9 @@ internal bool Remove(GameSystem system) finally { if (!system.isDestroyed) + { system.Detach(); + } } return true; } @@ -114,25 +109,33 @@ internal bool Remove(GameSystem system) internal void Reset(GameSystem system) { if (!TryGetEntry(system, out _)) + { throw new InvalidOperationException($"GameSystem '{system.GetType().FullName}' is not registered."); + } system.DispatchReset(); } internal IReadOnlyList GetSystems() { if (m_displayView is not null) + { return m_displayView; + } var snapshot = new GameSystem[m_displayOrder.Count]; for (int i = 0; i < snapshot.Length; i++) + { snapshot[i] = m_displayOrder[i].system; + } return m_displayView = Array.AsReadOnly(snapshot); } internal int GetIndex(GameSystem system) { if (!TryGetEntry(system, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem is not registered with this scene."); + } return entry!.displayIndex; } @@ -141,11 +144,15 @@ internal void SetIndex( int systemIndex ) { if (!TryGetEntry(system, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem is not registered with this scene."); + } int currentIndex = entry!.displayIndex; int targetIndex = Math.Clamp(systemIndex, 0, m_displayOrder.Count - 1); if (currentIndex == targetIndex) + { return; + } m_displayOrder.RemoveAt(currentIndex); m_displayOrder.Insert(targetIndex, entry); RefreshDisplayIndices(); @@ -155,37 +162,47 @@ int systemIndex internal void ReplaceForReload( GameSystem previous, GameSystem replacement, - int replacementRuntimeTypeId + int replacementRuntimeTypeID ) { if (!TryGetEntry(previous, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem being replaced is not registered."); + } if (TryGetEntry(replacement, out _)) + { throw new InvalidOperationException("The replacement GameSystem is already registered."); + } previous.ValidateIdentityForReplacement(); - if (replacement.identity.runtimeId is not null) + if (replacement.identity.runtimeID is not null) + { throw new InvalidOperationException("The replacement GameSystem already has a registered identity."); + } bool attachedHere = replacement.ownerScene is null; if (attachedHere) + { replacement.Attach(m_scene); + } else if (!ReferenceEquals(replacement.ownerScene, m_scene)) + { throw new InvalidOperationException("The replacement GameSystem belongs to another scene."); - Guid persistentId = previous.identity.persistentId; + } + Guid persistentID = previous.identity.persistentID; try { _ = previous.ReleaseIdentityForReplacement(); - replacement.RegisterIdentity(persistentId); + replacement.RegisterIdentity(persistentID); m_systems.Add(entry!) .Set(m_systemKey, replacement) - .Set(m_typeKey, replacementRuntimeTypeId); + .Set(m_typeKey, replacementRuntimeTypeID); entry!.system = replacement; - entry.runtimeTypeId = replacementRuntimeTypeId; + entry.runtimeTypeID = replacementRuntimeTypeID; InvalidateSnapshots(); } catch (Exception exception) { List? rollbackFailures = null; - if (replacement.identity.runtimeId is not null) + if (replacement.identity.runtimeID is not null) { try { @@ -197,11 +214,11 @@ int replacementRuntimeTypeId rollbackFailures.Add(rollbackFailure); } } - if (previous.identity.runtimeId is null) + if (previous.identity.runtimeID is null) { try { - previous.RegisterIdentity(persistentId); + previous.RegisterIdentity(persistentID); } catch (Exception rollbackFailure) { @@ -222,10 +239,13 @@ int replacementRuntimeTypeId } } if (rollbackFailures is null) + { throw; + } throw new InvalidOperationException( "GameSystem hot-reload replacement failed and its identity rollback was incomplete.", - new AggregateException([exception, .. rollbackFailures])); + new AggregateException([exception, .. rollbackFailures]) + ); } } @@ -234,7 +254,9 @@ int replacementRuntimeTypeId internal void NotifyGameSystemActivationChanged(GameSystem system) { if (TryGetEntry(system, out _)) + { _ = SceneLifecycle.Prepare(system, m_scene); + } } internal void NotifyHierarchyActivationChanged() => m_behaviors.RefreshAll(); @@ -252,9 +274,13 @@ internal void FixedUpdate() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) + { break; + } if (SceneLifecycle.Prepare(system, m_scene) && system.isActiveAndEnabled) + { system.DispatchFixedUpdate(); + } } } @@ -267,15 +293,21 @@ internal void Update() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) + { break; + } if (!SceneLifecycle.Prepare(system, m_scene) || !system.isActiveAndEnabled) + { continue; + } if (!system.lifecycleStartCalled) { system.lifecycleStartCalled = true; ((ISceneLifecycleObject)system).DispatchStart(); if (!m_scene.canDispatch || system.isDestroyed) + { break; + } } system.DispatchUpdate(); } @@ -290,11 +322,13 @@ internal void LateUpdate() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) - break; - if (SceneLifecycle.Prepare(system, m_scene) && - system.isActiveAndEnabled && - system.lifecycleStartCalled) { + break; + } + if (SceneLifecycle.Prepare(system, m_scene) + && system.isActiveAndEnabled + && system.lifecycleStartCalled + ) { system.DispatchLateUpdate(); } } @@ -316,7 +350,9 @@ internal void Clear() finally { if (!system.isDestroyed) + { system.Detach(); + } } } } @@ -324,34 +360,38 @@ internal void Clear() private void Add( GameSystem system, SceneSystemTypeDescriptor descriptor, - Guid? persistentId, + Guid? persistentID, bool invokeReset ) { if (TryGetEntry(system, out _)) { throw new InvalidOperationException( - $"System '{descriptor.displayName}' is already registered with scene '{m_scene.name}'."); + $"System '{descriptor.displayName}' is already registered with scene '{m_scene.name}'." + ); } - if (!descriptor.allowsMultiple && m_systems.First(m_typeKey, descriptor.runtimeTypeId) is not null) + if (!descriptor.allowsMultiple && m_systems.First(m_typeKey, descriptor.runtimeTypeID) is not null) { throw new InvalidOperationException( - $"Scene '{m_scene.name}' already contains GameSystem '{descriptor.displayName}'."); + $"Scene '{m_scene.name}' already contains GameSystem '{descriptor.displayName}'." + ); } system.Attach(m_scene); SystemEntry? entry = null; try { - system.RegisterIdentity(persistentId); - entry = new SystemEntry(system, descriptor.runtimeTypeId, m_displayOrder.Count); + system.RegisterIdentity(persistentID); + entry = new SystemEntry(system, descriptor.runtimeTypeID, m_displayOrder.Count); m_systems.Add(entry) .Set(m_systemKey, system) - .Set(m_persistentIdKey, system.identity.persistentId) - .Set(m_typeKey, descriptor.runtimeTypeId); + .Set(m_persistentIDKey, system.identity.persistentID) + .Set(m_typeKey, descriptor.runtimeTypeID); m_displayOrder.Add(entry); InvalidateSnapshots(); if (invokeReset) + { system.DispatchReset(); + } } catch { @@ -363,7 +403,9 @@ bool invokeReset InvalidateSnapshots(); } if (!system.isDestroyed) + { system.Detach(); + } throw; } } @@ -379,7 +421,9 @@ out SystemEntry? entry private SystemEntry[] GetExecutionSnapshot() { if (m_executionSnapshot is null) + { m_executionSnapshot = [.. m_displayOrder]; + } bool needsSort = false; for (int i = 0; i < m_executionSnapshot.Length; i++) @@ -387,29 +431,25 @@ private SystemEntry[] GetExecutionSnapshot() SystemEntry entry = m_executionSnapshot[i]; int executionOrder = entry.system.order; if (entry.executionOrder == executionOrder) + { continue; + } entry.executionOrder = executionOrder; needsSort = true; } if (needsSort || !IsExecutionOrderValid(m_executionSnapshot)) - Array.Sort(m_executionSnapshot, SystemEntryExecutionComparer.instance); - return m_executionSnapshot; - } - - private static bool IsExecutionOrderValid(SystemEntry[] entries) - { - for (int i = 1; i < entries.Length; i++) { - if (SystemEntryExecutionComparer.instance.Compare(entries[i - 1], entries[i]) > 0) - return false; + Array.Sort(m_executionSnapshot, SystemEntryExecutionComparer.instance); } - return true; + return m_executionSnapshot; } private void RefreshDisplayIndices() { for (int i = 0; i < m_displayOrder.Count; i++) + { m_displayOrder[i].displayIndex = i; + } } private void InvalidateSnapshots() @@ -418,21 +458,31 @@ private void InvalidateSnapshots() m_executionSnapshot = null; } + private static bool IsExecutionOrderValid(SystemEntry[] entries) + { + for (int i = 1; i < entries.Length; i++) + { + if (SystemEntryExecutionComparer.instance.Compare(entries[i - 1], entries[i]) > 0) + { + return false; + } + } + return true; + } + private sealed class SystemEntry( GameSystem system, - int runtimeTypeId, + int runtimeTypeID, int displayIndex ) { internal GameSystem system { get; set; } = system; - internal int runtimeTypeId { get; set; } = runtimeTypeId; + internal int runtimeTypeID { get; set; } = runtimeTypeID; internal int displayIndex { get; set; } = displayIndex; internal int executionOrder { get; set; } = system.order; } private sealed class SystemEntryExecutionComparer : IComparer { - internal static SystemEntryExecutionComparer instance { get; } = new(); - /// /// Compares two values according to the deterministic ordering used by this collection. /// @@ -450,15 +500,23 @@ public int Compare( SystemEntry? right ) { if (ReferenceEquals(left, right)) + { return 0; + } if (left is null) + { return -1; + } if (right is null) + { return 1; + } int orderComparison = left.executionOrder.CompareTo(right.executionOrder); return orderComparison != 0 - ? orderComparison - : left.displayIndex.CompareTo(right.displayIndex); + ? orderComparison + : left.displayIndex.CompareTo(right.displayIndex); } + + internal static SystemEntryExecutionComparer instance { get; } = new(); } } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs index 37dacf8a5..bbd058491 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Scene; @@ -12,39 +11,41 @@ internal sealed class PrefabConnectionRecord internal PrefabConnectionRecord( AssetObject sourceAsset, - Guid sourceRootId, + Guid sourceRootID, bool isVariant, PrefabOverrideSet? overrides = null ) { - this.sourceAsset = sourceAsset ?? throw new ArgumentNullException(nameof(sourceAsset)); - this.sourceRootId = sourceRootId; + ArgumentNullException.ThrowIfNull(sourceAsset); + this.sourceAsset = sourceAsset; + this.sourceRootID = sourceRootID; this.isVariant = isVariant; this.overrides = overrides ?? new PrefabOverrideSet(); } internal AssetObject sourceAsset { get; } - internal Guid sourceRootId { get; } + internal Guid sourceRootID { get; } internal bool isVariant { get; } internal PrefabOverrideSet overrides { get; set; } internal IReadOnlyDictionary objectIdentities => m_objectIdentities; internal IReadOnlyDictionary componentIdentities => m_componentIdentities; internal void MapObject( - Guid sourceId, + Guid sourceID, GameObject gameObject ) { ArgumentNullException.ThrowIfNull(gameObject); - m_objectIdentities[sourceId] = gameObject.identity.persistentId; + m_objectIdentities[sourceID] = gameObject.identity.persistentID; } internal void MapComponent( - Guid sourceId, + Guid sourceID, GameComponent component ) { ArgumentNullException.ThrowIfNull(component); - m_componentIdentities[sourceId] = component.identity.persistentId; + m_componentIdentities[sourceID] = component.identity.persistentID; } - internal void RemoveObject(Guid sourceId) => m_objectIdentities.Remove(sourceId); - internal void RemoveComponent(Guid sourceId) => m_componentIdentities.Remove(sourceId); + internal void RemoveObject(Guid sourceID) => m_objectIdentities.Remove(sourceID); + + internal void RemoveComponent(Guid sourceID) => m_componentIdentities.Remove(sourceID); } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs index 9b8f97b2f..01f2c33e8 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; namespace Inno.Scene; @@ -10,8 +9,8 @@ namespace Inno.Scene; public sealed class PrefabInstanceInfo { internal PrefabInstanceInfo( - Guid sourceAssetId, - Guid sourceObjectId, + Guid sourceAssetID, + Guid sourceObjectID, GameObject instanceRoot, bool isRoot, bool isVariant, @@ -20,26 +19,27 @@ internal PrefabInstanceInfo( int orphanedOverrideCount, AssetObject sourceAsset ) { - this.sourceAssetId = sourceAssetId; - this.sourceObjectId = sourceObjectId; + ArgumentNullException.ThrowIfNull(sourceAsset); + this.sourceAssetID = sourceAssetID; + this.sourceObjectID = sourceObjectID; this.instanceRoot = instanceRoot; this.isRoot = isRoot; this.isVariant = isVariant; this.isMissing = isMissing; this.overrideCount = overrideCount; this.orphanedOverrideCount = orphanedOverrideCount; - this.sourceAsset = sourceAsset ?? throw new ArgumentNullException(nameof(sourceAsset)); + this.sourceAsset = sourceAsset; } /// /// Gets the persistent identity of the source prefab asset. /// - public Guid sourceAssetId { get; } + public Guid sourceAssetID { get; } /// /// Gets the source-local identity represented by this object. /// - public Guid sourceObjectId { get; } + public Guid sourceObjectID { get; } /// /// Gets the root object of this prefab instance connection. diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs index 03b3755a4..2a72aae5e 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs @@ -6,8 +6,9 @@ namespace Inno.Scene; internal sealed class PrefabOverrideSet { - private readonly Dictionary<(Guid sourceComponentId, string propertyName), PrefabPropertyOverride> + private readonly Dictionary<(Guid sourceComponentID, string propertyName), PrefabPropertyOverride> m_properties = []; + private readonly Dictionary m_structures = []; private readonly HashSet m_removedObjects = []; private readonly HashSet m_removedComponents = []; @@ -20,49 +21,54 @@ internal sealed class PrefabOverrideSet internal IReadOnlyCollection removedComponents => m_removedComponents; internal IReadOnlyCollection addedObjects => m_addedObjects; internal IReadOnlyCollection addedComponents => m_addedComponents; - internal int count => - m_properties.Count + m_structures.Count + - m_removedObjects.Count + m_removedComponents.Count + - m_addedObjects.Count + m_addedComponents.Count; - internal int orphanedCount => - m_properties.Values.Count(static item => item.isOrphaned) + - m_structures.Values.Count(static item => item.isOrphaned); + + internal int count + => m_properties.Count + m_structures.Count + + m_removedObjects.Count + m_removedComponents.Count + + m_addedObjects.Count + m_addedComponents.Count; + + internal int orphanedCount + => m_properties.Values.Count(static item => item.isOrphaned) + + m_structures.Values.Count(static item => item.isOrphaned); internal bool IsPropertyOverridden( - Guid sourceComponentId, + Guid sourceComponentID, string propertyName - ) - => m_properties.ContainsKey((sourceComponentId, propertyName)); + ) => m_properties.ContainsKey((sourceComponentID, propertyName)); - internal PrefabObjectOverrideKind GetStructureOverride(Guid sourceObjectId) - => m_structures.TryGetValue(sourceObjectId, out PrefabStructureOverride? value) - ? value.kind - : PrefabObjectOverrideKind.None; + internal PrefabObjectOverrideKind GetStructureOverride(Guid sourceObjectID) + => m_structures.TryGetValue(sourceObjectID, out PrefabStructureOverride? value) + ? value.kind + : PrefabObjectOverrideKind.None; internal void SetProperty(PrefabPropertyOverride value) { ArgumentNullException.ThrowIfNull(value); - m_properties[(value.sourceComponentId, value.propertyName)] = value; + m_properties[(value.sourceComponentID, value.propertyName)] = value; } internal void SetStructure( - Guid sourceObjectId, + Guid sourceObjectID, PrefabObjectOverrideKind kind, bool isOrphaned = false ) { if (kind == PrefabObjectOverrideKind.None) { - m_structures.Remove(sourceObjectId); + m_structures.Remove(sourceObjectID); return; } - m_structures[sourceObjectId] = new PrefabStructureOverride(sourceObjectId, kind, isOrphaned); + m_structures[sourceObjectID] = new PrefabStructureOverride(sourceObjectID, kind, isOrphaned); } - internal void MarkObjectRemoved(Guid sourceObjectId) => m_removedObjects.Add(sourceObjectId); - internal void MarkComponentRemoved(Guid sourceComponentId) => m_removedComponents.Add(sourceComponentId); - internal void MarkObjectAdded(Guid instanceObjectId) => m_addedObjects.Add(instanceObjectId); - internal void MarkComponentAdded(Guid instanceComponentId) => m_addedComponents.Add(instanceComponentId); + internal void MarkObjectRemoved(Guid sourceObjectID) => m_removedObjects.Add(sourceObjectID); + + internal void MarkComponentRemoved(Guid sourceComponentID) => m_removedComponents.Add(sourceComponentID); + + internal void MarkObjectAdded(Guid instanceObjectID) => m_addedObjects.Add(instanceObjectID); + + internal void MarkComponentAdded(Guid instanceComponentID) => m_addedComponents.Add(instanceComponentID); + + internal bool IsObjectRemoved(Guid sourceObjectID) => m_removedObjects.Contains(sourceObjectID); - internal bool IsObjectRemoved(Guid sourceObjectId) => m_removedObjects.Contains(sourceObjectId); - internal bool IsComponentRemoved(Guid sourceComponentId) => m_removedComponents.Contains(sourceComponentId); + internal bool IsComponentRemoved(Guid sourceComponentID) => m_removedComponents.Contains(sourceComponentID); } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabPropertyOverride.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabPropertyOverride.cs index 9012845c4..56d5883ae 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabPropertyOverride.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabPropertyOverride.cs @@ -3,7 +3,7 @@ namespace Inno.Scene; internal sealed record PrefabPropertyOverride( - Guid sourceComponentId, + Guid sourceComponentID, string propertyName, byte[] value, bool isOrphaned = false diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs index 931804777..0b8b6a8d5 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs @@ -2,6 +2,12 @@ namespace Inno.Scene; +internal sealed record PrefabStructureOverride( + Guid sourceObjectID, + PrefabObjectOverrideKind kind, + bool isOrphaned = false +); + [Flags] internal enum PrefabObjectOverrideKind { @@ -10,11 +16,5 @@ internal enum PrefabObjectOverrideKind ActiveSelf = 1 << 1, Parent = 1 << 2, SiblingIndex = 1 << 3, - Tag = 1 << 4, + Tag = 1 << 4 } - -internal sealed record PrefabStructureOverride( - Guid sourceObjectId, - PrefabObjectOverrideKind kind, - bool isOrphaned = false -); diff --git a/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs b/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs index dff7af06d..703e3ef29 100644 --- a/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs +++ b/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs @@ -1,20 +1,11 @@ -using Inno.Scripting.Api; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene", - ScriptingApiScope.Runtime)] -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene.Components", - ScriptingApiScope.Runtime)] -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene.Layers", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene", ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene.Components", ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene.Layers", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AllowMultipleComponentAttribute), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AllowMultipleSystemAttribute), ScriptingApiScope.Runtime)] @@ -31,7 +22,7 @@ [assembly: ScriptingApiExport(typeof(Transform), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GameLayer), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GameLayerDefinition), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(GameLayerId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(GameLayerID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GameLayerMask), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GameLayerCatalog), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GameTagCatalog), ScriptingApiScope.Runtime)] diff --git a/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs b/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs index ede0b9487..82cbe65c3 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs @@ -9,20 +9,30 @@ internal sealed class SceneElementReferenceResolver( TypeCacheSnapshot types ) : IReferenceResolver { - internal static ReferenceKindId id { get; } = new("inno.reference.scene-element"); - - ReferenceKindId IReferenceResolver.kindId => id; + ReferenceKindID IReferenceResolver.kindID => id; ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) { - EngineObject? target = world.Find(descriptor.targetPersistentId); + EngineObject? target = world.Find(descriptor.targetPersistentID); if (target is null || target.isDestroyed || target is MissingGameComponent or MissingGameSystem) - return new ReferenceResolution(descriptor, ReferenceResolutionState.Missing, - diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' or its type is unavailable."); - if (descriptor.expectedStableTypeId != Guid.Empty && - types.GetTypeRef(target.GetType()).stableId != descriptor.expectedStableTypeId) - return new ReferenceResolution(descriptor, ReferenceResolutionState.TypeMismatch, - diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' does not implement stable type '{descriptor.expectedStableTypeId:D}'."); + { + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.Missing, + diagnostic: $"Scene element '{descriptor.targetPersistentID:D}' or its type is unavailable." + ); + } + if (descriptor.expectedStableTypeID != Guid.Empty + && types.GetTypeRef(target.GetType()).stableID != descriptor.expectedStableTypeID + ) { + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.TypeMismatch, + diagnostic: $"Scene element '{descriptor.targetPersistentID:D}' does not implement stable type '{descriptor.expectedStableTypeID:D}'." + ); + } return new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, target.identity.runtimeIdentity); } + + internal static ReferenceKindID id { get; } = new("inno.reference.scene-element"); } diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs index 8f8857662..5269cd75c 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs @@ -1,5 +1,5 @@ -using Inno.Core.Diagnostics; using System; +using Inno.Core.Diagnostics; namespace Inno.Scene; @@ -12,8 +12,8 @@ internal SceneReloadDiagnostic( string code, DiagnosticSeverity severity, string message, - Guid scenePersistentId, - Guid objectPersistentId, + Guid scenePersistentID, + Guid objectPersistentID, string propertyName, string previousPropertyType, string currentPropertyType @@ -21,8 +21,8 @@ string currentPropertyType this.code = code; this.severity = severity; this.message = message; - this.scenePersistentId = scenePersistentId; - this.objectPersistentId = objectPersistentId; + this.scenePersistentID = scenePersistentID; + this.objectPersistentID = objectPersistentID; this.propertyName = propertyName; this.previousPropertyType = previousPropertyType; this.currentPropertyType = currentPropertyType; @@ -46,12 +46,12 @@ string currentPropertyType /// /// Gets the persistent identity of the affected scene. /// - public Guid scenePersistentId { get; } + public Guid scenePersistentID { get; } /// /// Gets the persistent identity of the affected component or system. /// - public Guid objectPersistentId { get; } + public Guid objectPersistentID { get; } /// /// Gets the incompatible serialized property name. diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs index 62da62f2a..aa49913f5 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs @@ -12,7 +12,7 @@ internal sealed class SceneReloadRecovery : ISceneReloadStateTransfer { private readonly ReferenceRecoveryTransaction m_recovery; private SceneReloadStateTransfer? m_transfer; - private IReadOnlyList m_diagnostics = Array.Empty(); + private IReadOnlyList m_diagnostics = []; internal SceneReloadRecovery( SceneReloadStateTransfer transfer, @@ -22,22 +22,31 @@ IAssetReferenceResolver assets ) { m_transfer = transfer; m_recovery = new ReferenceRecoveryTransaction( - ReferenceCatalog.Create(context.candidate.version, - [new SceneElementReferenceResolver(world, context.candidate), assets]), - transfer.CaptureRecoveryStates(), [transfer]); + ReferenceCatalog.Create( + context.candidate.version, + [new SceneElementReferenceResolver(world, context.candidate), assets] + ), + transfer.CaptureRecoveryStates(), + [transfer] + ); } - IReadOnlyList ISceneReloadStateTransfer.retiredObjects => m_transfer?.retiredObjects ?? Array.Empty(); + IReadOnlyList ISceneReloadStateTransfer.retiredObjects => m_transfer?.retiredObjects ?? []; IReadOnlyList ISceneReloadStateTransfer.diagnostics => m_diagnostics; IReadOnlyList ISceneReloadStateTransfer.recoveryChanges => m_recovery.changes; + void ISceneReloadStateTransfer.PrepareForActivation() => m_recovery.PrepareForActivation(); + void ISceneReloadStateTransfer.Apply() { m_recovery.Apply(); CaptureDiagnostics(); } + void ISceneReloadStateTransfer.RollbackStructure() => m_recovery.RollbackStructure(); + void ISceneReloadStateTransfer.RestorePreviousState() => FinalizeRecovery(restore: true); + void ISceneReloadStateTransfer.Complete() => FinalizeRecovery(restore: false); private void FinalizeRecovery(bool restore) @@ -46,9 +55,13 @@ private void FinalizeRecovery(bool restore) try { if (restore) + { m_recovery.RestorePreviousState(); + } else + { m_recovery.Complete(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -59,13 +72,17 @@ private void FinalizeRecovery(bool restore) { CaptureDiagnostics(); if (!pending) + { m_transfer = null; + } } } private void CaptureDiagnostics() { if (m_transfer is not null) + { m_diagnostics = Array.AsReadOnly(m_transfer.diagnostics.ToArray()); + } } } diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs index 5da57bb9e..c3e347325 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs @@ -1,8 +1,7 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -18,12 +17,12 @@ public sealed class SceneReloadService /// /// Creates a scene reload service bound to one serialization generation owner. /// - /// - /// The serialization registry used to capture and restore scene state. - /// /// /// The isolated scene world whose active generation is captured. /// + /// + /// The serialization registry used to capture and restore scene state. + /// /// /// The asset reference generation used throughout capture, activation, and rollback. /// @@ -36,9 +35,12 @@ public SceneReloadService( SerializationRegistry serialization, IAssetReferenceResolver assets ) { - m_world = world ?? throw new ArgumentNullException(nameof(world)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(assets); + m_world = world; + m_serialization = serialization; + m_assets = assets; } /// @@ -55,6 +57,9 @@ public ISceneReloadStateTransfer Capture(TypeCacheReloadContext context) ArgumentNullException.ThrowIfNull(context); return new SceneReloadRecovery( SceneReloadStateTransfer.Capture(m_world, context, m_serialization, m_assets), - m_world, context, m_assets); + m_world, + context, + m_assets + ); } } diff --git a/src/content/scene/Inno.Scene/SceneManager.cs b/src/content/scene/Inno.Scene/SceneManager.cs index 577845bf8..57a4473e2 100644 --- a/src/content/scene/Inno.Scene/SceneManager.cs +++ b/src/content/scene/Inno.Scene/SceneManager.cs @@ -72,8 +72,7 @@ int sceneIndex public static void LoadSceneAdditive( GameScene scene, bool makeActive = true - ) - => SceneWorld.current.LoadSceneAdditive(scene, makeActive); + ) => SceneWorld.current.LoadSceneAdditive(scene, makeActive); /// /// Creates and loads a new active scene in the current runtime session. @@ -101,8 +100,7 @@ public static void LoadSceneAdditive( public static GameScene LoadNewSceneAdditive( string name = "Untitled Scene", bool makeActive = true - ) - => SceneWorld.current.LoadNewSceneAdditive(name, makeActive); + ) => SceneWorld.current.LoadNewSceneAdditive(name, makeActive); /// /// Makes a loaded scene active in the current runtime session. @@ -124,8 +122,7 @@ public static GameScene LoadNewSceneAdditive( public static void MoveGameObjectToScene( GameObject gameObject, GameScene destination - ) - => SceneWorld.current.MoveGameObjectToScene(gameObject, destination); + ) => SceneWorld.current.MoveGameObjectToScene(gameObject, destination); /// /// Unloads the active scene in the current runtime session when one exists. diff --git a/src/content/scene/Inno.Scene/SceneWorld.cs b/src/content/scene/Inno.Scene/SceneWorld.cs index 8a4d98f1e..9ce904e45 100644 --- a/src/content/scene/Inno.Scene/SceneWorld.cs +++ b/src/content/scene/Inno.Scene/SceneWorld.cs @@ -1,12 +1,13 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Threading; +using Inno.Assets; +using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; -using Inno.Assets; using Inno.Extensibility.Types; using Inno.Scene.Components; +using Inno.Scripting.Api; namespace Inno.Scene; @@ -15,7 +16,7 @@ namespace Inno.Scene; /// public sealed class SceneWorld : IDisposable { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("scene world"); + private static readonly ExecutionSlot CURRENT_SCOPE = new("scene world"); private readonly List m_loadedScenes = []; private readonly IdentityAllocator m_identities; @@ -42,20 +43,26 @@ public SceneWorld( IdentityAllocator identities, TypeCatalog types ) { - m_identities = identities ?? throw new ArgumentNullException(nameof(identities)); + ArgumentNullException.ThrowIfNull(identities); + m_identities = identities; ArgumentNullException.ThrowIfNull(types); m_types = new SceneTypeCatalog(types); } /// - /// Gets the active world bound to the current asynchronous execution context. + /// Gets the scene currently selected for unqualified scene operations. /// - /// - /// Thrown when the caller is outside a scene execution scope. - /// - internal static SceneWorld current => S_CURRENT_SCOPE.current; + public GameScene? activeScene => m_activeScene; - internal SceneTypeCatalog typeCatalog => m_types; + /// + /// Gets whether this world contains an active scene. + /// + public bool hasActiveScene => m_activeScene is not null; + + /// + /// Gets an immutable snapshot of loaded scenes in hierarchy order. + /// + public IReadOnlyList loadedScenes => Array.AsReadOnly(GetLoadedSceneSnapshot()); /// /// Binds the session-owned serialization and asset generations used by scene prefab instances. @@ -69,7 +76,7 @@ TypeCatalog types /// /// The binding was already configured. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void ConfigurePrefabInstantiation( SerializationRegistry serialization, IAssetReferenceResolver assets @@ -78,59 +85,28 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (m_prefabSerialization is not null) + { throw new InvalidOperationException("Prefab instantiation is already configured for this scene world."); + } m_prefabSerialization = serialization; m_prefabAssets = assets; } - internal GameObject InstantiatePrefab( - PrefabAsset prefab, - GameScene scene, - Transform? parent - ) { - EnsureActive(); - ArgumentNullException.ThrowIfNull(prefab); - ArgumentNullException.ThrowIfNull(scene); - if (!m_loadedScenes.Contains(scene)) - throw new InvalidOperationException("A prefab can only be instantiated into a loaded scene in the current world."); - SerializationRegistry serialization = m_prefabSerialization - ?? throw new InvalidOperationException("The current scene world has no prefab serialization context."); - IAssetReferenceResolver assets = m_prefabAssets - ?? throw new InvalidOperationException("The current scene world has no prefab asset resolver."); - using IDisposable scope = EnterScope(); - return prefab.Instantiate(scene, serialization, assets, parent); - } - - /// - /// Gets the scene currently selected for unqualified scene operations. - /// - public GameScene? activeScene => m_activeScene; - - /// - /// Gets whether this world contains an active scene. - /// - public bool hasActiveScene => m_activeScene is not null; - - /// - /// Gets an immutable snapshot of loaded scenes in hierarchy order. - /// - public IReadOnlyList loadedScenes => Array.AsReadOnly(GetLoadedSceneSnapshot()); - /// /// Resolves a live scene object by its persistent identity within this world. /// /// /// The required scene object contract. /// - /// + /// /// The persistent identity to resolve. /// /// /// The live compatible object, or when this world does not own one. /// - public TObject? Find(Guid persistentId) + public TObject? Find(Guid persistentID) where TObject : IdentityObject - => m_identities.Get(persistentId); + => m_identities.Get(persistentID); /// /// Binds this world and its identity allocator to the current asynchronous execution context. @@ -145,7 +121,7 @@ public IDisposable EnterScope() { EnsureActive(); IDisposable identityScope = m_identities.EnterScope(); - return new Scope(S_CURRENT_SCOPE.Enter(this), identityScope); + return new Scope(CURRENT_SCOPE.Enter(this), identityScope); } /// @@ -166,8 +142,8 @@ public int GetSceneIndex(GameScene scene) ArgumentNullException.ThrowIfNull(scene); int index = m_loadedScenes.IndexOf(scene); return index >= 0 - ? index - : throw new InvalidOperationException("Only a loaded scene has a hierarchy index."); + ? index + : throw new InvalidOperationException("Only a loaded scene has a hierarchy index."); } /// @@ -190,10 +166,14 @@ int sceneIndex ArgumentNullException.ThrowIfNull(scene); int currentIndex = m_loadedScenes.IndexOf(scene); if (currentIndex < 0) + { throw new InvalidOperationException("Only a loaded scene can be reordered."); + } int targetIndex = Math.Clamp(sceneIndex, 0, m_loadedScenes.Count - 1); if (currentIndex == targetIndex) + { return; + } m_loadedScenes.RemoveAt(currentIndex); m_loadedScenes.Insert(targetIndex, scene); InvalidateSnapshot(); @@ -210,7 +190,9 @@ public void LoadScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (ReferenceEquals(m_activeScene, scene) && m_loadedScenes.Count == 1) + { return; + } UnloadAllScenes(); m_loadedScenes.Add(scene); InvalidateSnapshot(); @@ -240,7 +222,9 @@ public void LoadSceneAdditive( scene.Load(this); } if (makeActive || m_activeScene is null) + { m_activeScene = scene; + } } /// @@ -255,7 +239,7 @@ public void LoadSceneAdditive( public GameScene LoadNewScene(string name = "Untitled Scene") { EnsureActive(); - var scene = new GameScene(m_types, name, persistentId: null); + var scene = new GameScene(m_types, name, persistentID: null); LoadScene(scene); return scene; } @@ -277,7 +261,7 @@ public GameScene LoadNewSceneAdditive( bool makeActive = true ) { EnsureActive(); - var scene = new GameScene(m_types, name, persistentId: null); + var scene = new GameScene(m_types, name, persistentID: null); LoadSceneAdditive(scene, makeActive); return scene; } @@ -296,7 +280,9 @@ public void SetActiveScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (!m_loadedScenes.Contains(scene)) + { throw new InvalidOperationException("Only a loaded scene can become active."); + } m_activeScene = scene; } @@ -320,12 +306,18 @@ GameScene destination ArgumentNullException.ThrowIfNull(gameObject); ArgumentNullException.ThrowIfNull(destination); if (!gameObject.isRuntimeValid) + { throw new InvalidOperationException("Only a live GameObject can move between scenes."); + } GameScene source = gameObject.scene; if (!m_loadedScenes.Contains(source) || !m_loadedScenes.Contains(destination)) + { throw new InvalidOperationException("Both source and destination scenes must be loaded by this world."); + } if (!ReferenceEquals(source, destination)) + { source.TransferObjectTo(gameObject, destination); + } } /// @@ -335,7 +327,9 @@ public void UnloadActiveScene() { EnsureActive(); if (m_activeScene is GameScene scene) + { UnloadScene(scene); + } } /// @@ -352,7 +346,9 @@ public bool UnloadScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (!m_loadedScenes.Remove(scene)) + { return false; + } InvalidateSnapshot(); try { @@ -361,7 +357,9 @@ public bool UnloadScene(GameScene scene) finally { if (ReferenceEquals(m_activeScene, scene)) + { m_activeScene = m_loadedScenes.Count > 0 ? m_loadedScenes[^1] : null; + } } return true; } @@ -388,7 +386,9 @@ public void UnloadAllScenes() InvalidateSnapshot(); m_activeScene = null; if (firstException is not null) + { throw new InvalidOperationException("One or more scenes failed while unloading.", firstException); + } } /// @@ -402,7 +402,9 @@ public void FixedUpdate(float fixedDeltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].FixedUpdate(fixedDeltaTime); + } } /// @@ -416,7 +418,9 @@ public void Update(float deltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].Update(deltaTime); + } } /// @@ -430,7 +434,9 @@ public void LateUpdate(float deltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].LateUpdate(deltaTime); + } } /// @@ -439,7 +445,9 @@ public void LateUpdate(float deltaTime) public void Dispose() { if (m_disposed) + { return; + } using IDisposable scope = EnterScope(); try { @@ -452,6 +460,36 @@ public void Dispose() } } + /// + /// Gets the active world bound to the current asynchronous execution context. + /// + /// + /// Thrown when the caller is outside a scene execution scope. + /// + internal static SceneWorld current => CURRENT_SCOPE.current; + + internal SceneTypeCatalog typeCatalog => m_types; + + internal GameObject InstantiatePrefab( + PrefabAsset prefab, + GameScene scene, + Transform? parent + ) { + EnsureActive(); + ArgumentNullException.ThrowIfNull(prefab); + ArgumentNullException.ThrowIfNull(scene); + if (!m_loadedScenes.Contains(scene)) + { + throw new InvalidOperationException("A prefab can only be instantiated into a loaded scene in the current world."); + } + SerializationRegistry serialization = m_prefabSerialization + ?? throw new InvalidOperationException("The current scene world has no prefab serialization context."); + IAssetReferenceResolver assets = m_prefabAssets + ?? throw new InvalidOperationException("The current scene world has no prefab asset resolver."); + using IDisposable scope = EnterScope(); + return prefab.Instantiate(scene, serialization, assets, parent); + } + private GameScene[] GetLoadedSceneSnapshot() => m_loadedSceneSnapshot ??= [.. m_loadedScenes]; private void InvalidateSnapshot() => m_loadedSceneSnapshot = null; @@ -471,7 +509,9 @@ IDisposable identityScope public void Dispose() { if (m_disposed) + { return; + } worldScope.Dispose(); m_disposed = true; identityScope.Dispose(); diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs index dfd05f4ae..ac80fdb9e 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -26,7 +25,7 @@ GameComponent value ArgumentNullException.ThrowIfNull(value); EngineReferenceToken token = SceneReferenceScope.current.Capture(value, writer.path); writer.Write("kind", (int)token.kind); - writer.Write("sourceId", token.sourceId); + writer.Write("sourceId", token.sourceID); } /// @@ -43,9 +42,12 @@ public override GameComponent Read(SerializationReader reader) ArgumentNullException.ThrowIfNull(reader); var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameComponent) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameComponent reference."); + } return (GameComponent)SceneReferenceScope.current.Resolve(token, reader.valueType, reader.path); } } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs index 3cf6d2ffd..c2a2c93e7 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; @@ -37,9 +36,11 @@ GameObject value } if (!value.isRuntimeValid) + { throw new InvalidOperationException("A destroyed or detached GameObject cannot be captured as a prefab root."); + } - var subtree = new List(); + List subtree = []; CollectSubtree(value, subtree); SceneStructureSnapshot snapshot = value.scene.CaptureStructure(); var included = new HashSet(subtree, ReferenceEqualityComparer.Instance); @@ -49,35 +50,41 @@ GameObject value EngineObject[] engineObjects = entries .SelectMany(static entry => entry.components.Cast().Prepend(entry.gameObject)) .ToArray(); - var sourceIds = new Dictionary(ReferenceEqualityComparer.Instance); + var sourceIDs = new Dictionary(ReferenceEqualityComparer.Instance); PrefabConnectionRecord? existingConnection = value.prefabConnection; - var mappedIds = new Dictionary(); + var mappedIDs = new Dictionary(); if (existingConnection is not null) { - foreach ((Guid sourceId, Guid runtimeId) in existingConnection.objectIdentities) - mappedIds[runtimeId] = sourceId; - foreach ((Guid sourceId, Guid runtimeId) in existingConnection.componentIdentities) - mappedIds[runtimeId] = sourceId; + foreach ((Guid sourceID, Guid runtimeID) in existingConnection.objectIdentities) + { + mappedIDs[runtimeID] = sourceID; + } + foreach ((Guid sourceID, Guid runtimeID) in existingConnection.componentIdentities) + { + mappedIDs[runtimeID] = sourceID; + } } for (int i = 0; i < engineObjects.Length; i++) { - sourceIds.Add( + sourceIDs.Add( engineObjects[i], - mappedIds.TryGetValue(engineObjects[i].identity.persistentId, out Guid mappedId) - ? mappedId - : Guid.NewGuid()); + mappedIDs.TryGetValue(engineObjects[i].identity.persistentID, out Guid mappedID) + ? mappedID + : Guid.NewGuid() + ); } - var references = new SceneGraphReferenceMap(value.scene, sourceIds, value); - writer.Write(C_SOURCE_ROOT_ID_KEY, sourceIds[value]); + var references = new SceneGraphReferenceMap(value.scene, sourceIDs, value); + writer.Write(C_SOURCE_ROOT_ID_KEY, sourceIDs[value]); using (references.Enter()) { SceneGraphSerialization.WriteObjects( writer, entries, - sourceIds, + sourceIDs, included.Contains, - preserveRootSiblingOrder: false); + preserveRootSiblingOrder: false + ); } } @@ -94,14 +101,20 @@ public override GameObject Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); if (SceneReferenceScope.TryGetCurrent(out SceneReferenceScope? activeReferences)) + { return (GameObject)ReadReference(reader, activeReferences!); + } GameScene scene = reader.context.GetRequired(); Transform? parent = null; if (reader.context.TryGet(out Transform? configuredParent)) + { parent = configuredParent; + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new InvalidOperationException("The prefab parent must belong to the target scene."); + } ValidatePrefab(reader); var existingObjects = new HashSet(scene.GetOwnedObjects(), ReferenceEqualityComparer.Instance); @@ -111,76 +124,88 @@ public override GameObject Read(SerializationReader reader) RestoredSceneGraph restored = SceneGraphSerialization.RestoreObjects( scene, reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY), - preservePersistentIds: false, + preservePersistentIDs: false, references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), - reader.context); - Guid sourceRootId = reader.Read(C_SOURCE_ROOT_ID_KEY); - if (!restored.objects.TryGetValue(sourceRootId, out GameObject? root)) - throw new InvalidDataException($"Prefab root '{sourceRootId}' is missing at '{reader.path}'."); + reader.context + ); + Guid sourceRootID = reader.Read(C_SOURCE_ROOT_ID_KEY); + if (!restored.objects.TryGetValue(sourceRootID, out GameObject? root)) + { + throw new InvalidDataException($"Prefab root '{sourceRootID}' is missing at '{reader.path}'."); + } if (reader.context.TryGet(out AssetObject? sourceAsset) && sourceAsset is not null) { PrefabConnectionRecord? embeddedConnection = root.prefabConnection; - bool sourceRepresentsVariant = embeddedConnection is not null && - root.prefabInstance?.isRoot == true; + bool sourceRepresentsVariant = embeddedConnection is not null + && root.prefabInstance?.isRoot == true; if (sourceRepresentsVariant) { - PrefabOverrideProcessor.Reconcile( - embeddedConnection!, - root, - reader.context); + PrefabOverrideProcessor.Reconcile(embeddedConnection!, root, reader.context); + } + var connection = new PrefabConnectionRecord(sourceAsset, sourceRootID, sourceRepresentsVariant); + foreach ((Guid sourceObjectID, GameObject gameObject) in restored.objects) + { + connection.MapObject(sourceObjectID, gameObject); + } + foreach ((Guid sourceComponentID, GameComponent component) in restored.components) + { + connection.MapComponent(sourceComponentID, component); } - var connection = new PrefabConnectionRecord( - sourceAsset, - sourceRootId, - sourceRepresentsVariant); - foreach ((Guid sourceObjectId, GameObject gameObject) in restored.objects) - connection.MapObject(sourceObjectId, gameObject); - foreach ((Guid sourceComponentId, GameComponent component) in restored.components) - connection.MapComponent(sourceComponentId, component); if (sourceRepresentsVariant) { - foreach ((Guid sourceObjectId, Guid runtimeId) in embeddedConnection!.objectIdentities) + foreach ((Guid sourceObjectID, Guid runtimeID) in embeddedConnection!.objectIdentities) { - GameObject? mappedObject = scene.FindObject(runtimeId); + GameObject? mappedObject = scene.FindObject(runtimeID); if (mappedObject is not null) - connection.MapObject(sourceObjectId, mappedObject); + { + connection.MapObject(sourceObjectID, mappedObject); + } } - foreach ((Guid sourceComponentId, Guid runtimeId) in embeddedConnection.componentIdentities) + foreach ((Guid sourceComponentID, Guid runtimeID) in embeddedConnection.componentIdentities) { - GameComponent? mappedComponent = scene.FindComponent(runtimeId); + GameComponent? mappedComponent = scene.FindComponent(runtimeID); if (mappedComponent is not null) - connection.MapComponent(sourceComponentId, mappedComponent); + { + connection.MapComponent(sourceComponentID, mappedComponent); + } } } root.SetPrefabConnectionDirect(connection); - foreach ((Guid sourceObjectId, Guid runtimeId) in connection.objectIdentities) + foreach ((Guid sourceObjectID, Guid runtimeID) in connection.objectIdentities) { - GameObject? gameObject = scene.FindObject(runtimeId); + GameObject? gameObject = scene.FindObject(runtimeID); if (gameObject is null) + { continue; + } PrefabInstanceInfo? existingConnection = gameObject.prefabInstance; - if (existingConnection is not null && - !ReferenceEquals(existingConnection.instanceRoot, root)) - { + if (existingConnection is not null + && !ReferenceEquals(existingConnection.instanceRoot, root) + ) { continue; } - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - sourceAsset.identity.persistentId, - sourceObjectId, - root, - ReferenceEquals(gameObject, root), - sourceRepresentsVariant, - sourceAsset.isMissing, - existingConnection?.overrideCount ?? 0, - existingConnection?.orphanedOverrideCount ?? 0, - sourceAsset)); + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + sourceAsset.identity.persistentID, + sourceObjectID, + root, + ReferenceEquals(gameObject, root), + sourceRepresentsVariant, + sourceAsset.isMissing, + existingConnection?.overrideCount ?? 0, + existingConnection?.orphanedOverrideCount ?? 0, + sourceAsset + ) + ); } } SceneGraphSerialization.ReconcilePrefabConnections(scene, reader.context, root); if (parent is not null) + { scene.SetParent(root.transform, parent, worldPositionStays: false); + } return root; } catch @@ -191,7 +216,9 @@ public override GameObject Read(SerializationReader reader) for (int i = 0; i < createdObjects.Length; i++) { if (createdObjects[i].isRuntimeValid) + { scene.DestroyObject(createdObjects[i]); + } } throw; } @@ -204,7 +231,7 @@ GameObject gameObject ) { EngineReferenceToken token = references.Capture(gameObject, writer.path); writer.Write("kind", (int)token.kind); - writer.Write("sourceId", token.sourceId); + writer.Write("sourceId", token.sourceID); } private static EngineObject ReadReference( @@ -213,25 +240,30 @@ SceneReferenceScope references ) { var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameObject) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameObject reference."); + } return references.Resolve(token, reader.valueType, reader.path); } private static void ValidatePrefab(SerializationReader reader) { SceneGraphSerialization.ValidateMissingReferenceAliases(reader); - Guid rootId = reader.Read(C_SOURCE_ROOT_ID_KEY); - if (rootId == Guid.Empty) + Guid rootID = reader.Read(C_SOURCE_ROOT_ID_KEY); + if (rootID == Guid.Empty) + { throw new InvalidDataException($"Prefab source root identity at '{reader.path}' cannot be empty."); - IReadOnlyList objectReaders = - reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY); + } + IReadOnlyList objectReaders = reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY); SceneGraphSerialization.ValidateObjects(objectReaders); - if (!objectReaders.Any(objectReader => - objectReader.Read(SceneGraphSerialization.C_OBJECT_ID_KEY) == rootId)) - { - throw new InvalidDataException($"Prefab root '{rootId}' is missing at '{reader.path}'."); + if (!objectReaders.Any(objectReader => ( + objectReader.Read(SceneGraphSerialization.C_OBJECT_ID_KEY) == rootID + )) + ) { + throw new InvalidDataException($"Prefab root '{rootID}' is missing at '{reader.path}'."); } } @@ -242,6 +274,8 @@ ICollection result result.Add(gameObject); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { CollectSubtree(children[i].gameObject, result); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs index 89c5378a2..6b7396b56 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; @@ -27,24 +26,27 @@ GameScene value ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(value); if (value.isDestroyed) + { throw new InvalidOperationException("A destroyed scene cannot be serialized."); + } SceneStructureSnapshot snapshot = value.CaptureStructure(); IReadOnlyList systems = value.GetSystems(); - var sourceIds = new SceneGraphSourceIds(snapshot.CaptureObjectSourceIds(), systems); - var references = new SceneGraphReferenceMap(value, sourceIds); + var sourceIDs = new SceneGraphSourceIDs(snapshot.CaptureObjectSourceIDs(), systems); + var references = new SceneGraphReferenceMap(value, sourceIDs); - writer.Write(SceneGraphSerialization.C_SCENE_ID_KEY, value.identity.persistentId); + writer.Write(SceneGraphSerialization.C_SCENE_ID_KEY, value.identity.persistentID); writer.Write(SceneGraphSerialization.C_NAME_KEY, value.name); using (references.Enter()) { SceneGraphSerialization.WriteObjects( writer, snapshot.objects, - sourceIds, - gameObject => sourceIds.ContainsKey(gameObject), - preserveRootSiblingOrder: true); - SceneGraphSerialization.WriteSystems(writer, systems, sourceIds); + sourceIDs, + gameObject => sourceIDs.ContainsKey(gameObject), + preserveRootSiblingOrder: true + ); + SceneGraphSerialization.WriteSystems(writer, systems, sourceIDs); } } @@ -61,30 +63,33 @@ public override GameScene Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); SceneGraphSerialization.ValidateScene(reader); - Guid sceneId = reader.Read(SceneGraphSerialization.C_SCENE_ID_KEY); + Guid sceneID = reader.Read(SceneGraphSerialization.C_SCENE_ID_KEY); bool instantiateFromAsset = reader.context.TryGet(out AssetObject? sourceAsset) && sourceAsset is not null; var scene = new GameScene( SceneWorld.current.typeCatalog, reader.Read(SceneGraphSerialization.C_NAME_KEY), - instantiateFromAsset ? null : sceneId); + instantiateFromAsset ? null : sceneID + ); if (sourceAsset is not null) + { scene.SetSourceAsset(sourceAsset); + } try { - RestoreSceneGraph(scene, reader, preservePersistentIds: !instantiateFromAsset); + RestoreSceneGraph(scene, reader, preservePersistentIDs: !instantiateFromAsset); SceneGraphSerialization.ReconcilePrefabConnections(scene, reader.context); return scene; } catch { if (!scene.isDestroyed) + { scene.Unload(); + } throw; } } - - /// /// Restores the supplied snapshot while preserving current invariants. /// @@ -101,23 +106,27 @@ GameScene target ArgumentNullException.ThrowIfNull(reader); ArgumentNullException.ThrowIfNull(target); SceneGraphSerialization.ValidateScene(reader); - Guid sceneId = reader.Read(SceneGraphSerialization.C_SCENE_ID_KEY); - target.PrepareRestoreTarget(sceneId); + Guid sceneID = reader.Read(SceneGraphSerialization.C_SCENE_ID_KEY); + target.PrepareRestoreTarget(sceneID); target.name = reader.Read(SceneGraphSerialization.C_NAME_KEY); try { - RestoreSceneGraph(target, reader, preservePersistentIds: true); + RestoreSceneGraph(target, reader, preservePersistentIDs: true); SceneGraphSerialization.ReconcilePrefabConnections(target, reader.context); } catch { foreach (GameSystem system in target.GetSystems().ToArray()) + { target.RemoveSystem(system); + } GameObject[] createdObjects = target.GetObjects().ToArray(); for (int i = 0; i < createdObjects.Length; i++) { if (createdObjects[i].isRuntimeValid) + { target.DestroyObject(createdObjects[i]); + } } throw; } @@ -126,38 +135,42 @@ GameScene target private static void RestoreSceneGraph( GameScene scene, SerializationReader reader, - bool preservePersistentIds + bool preservePersistentIDs ) { var references = new SceneGraphReferenceMap(scene); RestoredSceneGraph graph = SceneGraphSerialization.RestoreObjects( scene, reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY), - preservePersistentIds, + preservePersistentIDs, references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), reader.context, - restoreProperties: false); - IReadOnlyList systemReaders = - reader.ReadObjectArray(SceneGraphSerialization.C_SYSTEMS_KEY); - var missingPlaceholders = graph.missingPlaceholders.ToList(); - IReadOnlyList<(GameSystem system, byte[] state)> systemStates = - SceneGraphSerialization.CreateSystems( - scene, - systemReaders, - preservePersistentIds, - references, - missingPlaceholders); + restoreProperties: false + ); + IReadOnlyList systemReaders = reader.ReadObjectArray(SceneGraphSerialization.C_SYSTEMS_KEY); + List missingPlaceholders = graph.missingPlaceholders.ToList(); + IReadOnlyList<(GameSystem system, byte[] state)> systemStates = SceneGraphSerialization.CreateSystems( + scene, + systemReaders, + preservePersistentIDs, + references, + missingPlaceholders + ); SceneGraphSerialization.RestoreMissingReferenceAliases( graph with { missingPlaceholders = missingPlaceholders }, - references); + references + ); using (references.Enter()) { SerializationRegistry serialization = reader.context.GetRequired(); foreach ((GameComponent component, byte[] state) in graph.componentStates) + { serialization.RestorePropertiesData(component, state, context: reader.context); + } foreach ((GameSystem system, byte[] state) in systemStates) + { serialization.RestorePropertiesData(system, state, context: reader.context); + } } } - } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs index 6b99c30ac..eb9db03cb 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -26,7 +25,7 @@ GameSystem value ArgumentNullException.ThrowIfNull(value); EngineReferenceToken token = SceneReferenceScope.current.Capture(value, writer.path); writer.Write("kind", (int)token.kind); - writer.Write("sourceId", token.sourceId); + writer.Write("sourceId", token.sourceID); } /// @@ -43,9 +42,12 @@ public override GameSystem Read(SerializationReader reader) ArgumentNullException.ThrowIfNull(reader); var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameSystem) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameSystem reference."); + } return (GameSystem)SceneReferenceScope.current.Resolve(token, reader.valueType, reader.path); } } diff --git a/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs b/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs index 4cddbbacc..20af5449c 100644 --- a/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs +++ b/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs @@ -2,14 +2,14 @@ namespace Inno.Scene; +internal readonly record struct EngineReferenceToken( + EngineReferenceKind kind, + Guid sourceID +); + internal enum EngineReferenceKind { GameObject = 1, GameComponent = 2, GameSystem = 3 } - -internal readonly record struct EngineReferenceToken( - EngineReferenceKind kind, - Guid sourceId -); diff --git a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs index e1f528530..c20090613 100644 --- a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs +++ b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -23,22 +22,18 @@ SceneReferenceScope storageReferences ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(storageReferences); if (connection.sourceAsset.isMissing || connection.sourceAsset.runtimePayload.IsEmpty) + { return connection.overrides; + } - (GameScene sourceScene, _, PrefabConnectionRecord sourceConnection) = - InstantiateSource(connection.sourceAsset, context); + (GameScene sourceScene, _, PrefabConnectionRecord sourceConnection) = InstantiateSource(connection.sourceAsset, context); try { SceneGraphReferenceMap currentReferences = CreateComparisonReferences(scene, connection); SceneGraphReferenceMap sourceReferences = CreateComparisonReferences(sourceScene, sourceConnection); var overrides = new PrefabOverrideSet(); - CaptureObjectOverrides( - connection, - sourceConnection, - scene, - sourceScene, - overrides); + CaptureObjectOverrides(connection, sourceConnection, scene, sourceScene, overrides); CaptureAdditions(connection, scene, overrides); CaptureComponentOverrides( connection, @@ -49,7 +44,8 @@ SceneReferenceScope storageReferences currentReferences, sourceReferences, storageReferences, - overrides); + overrides + ); PreserveOrphanedOverrides(connection.overrides, sourceConnection, overrides); connection.overrides = overrides; return overrides; @@ -57,7 +53,9 @@ SceneReferenceScope storageReferences finally { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } } } @@ -76,8 +74,7 @@ SerializationContext context } GameScene scene = instanceRoot.scene; - (GameScene sourceScene, _, PrefabConnectionRecord sourceConnection) = - InstantiateSource(connection.sourceAsset, context); + (GameScene sourceScene, _, PrefabConnectionRecord sourceConnection) = InstantiateSource(connection.sourceAsset, context); try { MarkOrphanedOverrides(connection, sourceConnection, sourceScene, context); @@ -95,14 +92,17 @@ SerializationContext context sourceScene, context, sourceReferences, - targetReferences); + targetReferences + ); RestoreSourceObjectState(connection, sourceConnection, scene, sourceScene, instanceRoot); RefreshInstanceInfo(connection, instanceRoot); } finally { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } } } @@ -113,32 +113,44 @@ private static void CaptureObjectOverrides( GameScene sourceScene, PrefabOverrideSet overrides ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.objectIdentities) { - GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); - GameObject? currentObject = connection.objectIdentities.TryGetValue(sourceId, out Guid currentRuntimeId) - ? scene.FindObject(currentRuntimeId) - : null; + GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeID); + GameObject? currentObject = connection.objectIdentities.TryGetValue(sourceID, out Guid currentRuntimeID) + ? scene.FindObject(currentRuntimeID) + : null; if (sourceObject is null) + { continue; + } if (currentObject is null) { - overrides.MarkObjectRemoved(sourceId); + overrides.MarkObjectRemoved(sourceID); continue; } PrefabObjectOverrideKind kind = PrefabObjectOverrideKind.None; if (!string.Equals(currentObject.name, sourceObject.name, StringComparison.Ordinal)) + { kind |= PrefabObjectOverrideKind.Name; + } if (!string.Equals(currentObject.tag, sourceObject.tag, StringComparison.Ordinal)) + { kind |= PrefabObjectOverrideKind.Tag; + } if (currentObject.activeSelf != sourceObject.activeSelf) + { kind |= PrefabObjectOverrideKind.ActiveSelf; - if (GetMappedParentId(currentObject, connection) != GetMappedParentId(sourceObject, sourceConnection)) + } + if (GetMappedParentID(currentObject, connection) != GetMappedParentID(sourceObject, sourceConnection)) + { kind |= PrefabObjectOverrideKind.Parent; + } if (currentObject.transform.siblingIndex != sourceObject.transform.siblingIndex) + { kind |= PrefabObjectOverrideKind.SiblingIndex; - overrides.SetStructure(sourceId, kind); + } + overrides.SetStructure(sourceID, kind); } } @@ -153,22 +165,26 @@ private static void CaptureComponentOverrides( SceneReferenceScope storageReferences, PrefabOverrideSet overrides ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.componentIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.componentIdentities) { - GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeId); - GameComponent? currentComponent = connection.componentIdentities.TryGetValue(sourceId, out Guid currentRuntimeId) - ? scene.FindComponent(currentRuntimeId) - : null; + GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeID); + GameComponent? currentComponent = connection.componentIdentities.TryGetValue(sourceID, out Guid currentRuntimeID) + ? scene.FindComponent(currentRuntimeID) + : null; if (sourceComponent is null) + { continue; + } if (currentComponent is null || currentComponent.GetType() != sourceComponent.GetType()) { - overrides.MarkComponentRemoved(sourceId); + overrides.MarkComponentRemoved(sourceID); continue; } - IReadOnlyList members = - SerializedPropertyValueCodec.GetMembers(sourceComponent.GetType(), context); + IReadOnlyList members = SerializedPropertyValueCodec.GetMembers( + sourceComponent.GetType(), + context + ); for (int memberIndex = 0; memberIndex < members.Count; memberIndex++) { SerializationMemberMetadata member = members[memberIndex]; @@ -180,23 +196,28 @@ PrefabOverrideSet overrides member, sourceComponent, context, - sourceReferences); + sourceReferences + ); currentValue = SerializedPropertyValueCodec.Encode( member, currentComponent, context, - currentReferences); + currentReferences + ); } catch (Exception exception) { throw new InvalidOperationException( - $"Failed to compare prefab override for GameComponent " + - $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + - $"'{currentComponent.gameObject.name}'.", - exception); + $"Failed to compare prefab override for GameComponent " + + $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + + $"'{currentComponent.gameObject.name}'.", + exception + ); } if (sourceValue.AsSpan().SequenceEqual(currentValue)) + { continue; + } byte[] persistedValue; try { @@ -204,17 +225,19 @@ PrefabOverrideSet overrides member, currentComponent, context, - storageReferences); + storageReferences + ); } catch (Exception exception) { throw new InvalidOperationException( - $"Failed to persist prefab override for GameComponent " + - $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + - $"'{currentComponent.gameObject.name}'.", - exception); + $"Failed to persist prefab override for GameComponent " + + $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + + $"'{currentComponent.gameObject.name}'.", + exception + ); } - overrides.SetProperty(new PrefabPropertyOverride(sourceId, member.name, persistedValue)); + overrides.SetProperty(new PrefabPropertyOverride(sourceID, member.name, persistedValue)); } } } @@ -224,27 +247,37 @@ private static void CaptureAdditions( GameScene scene, PrefabOverrideSet overrides ) { - if (!connection.objectIdentities.TryGetValue(connection.sourceRootId, out Guid rootRuntimeId)) + if (!connection.objectIdentities.TryGetValue(connection.sourceRootID, out Guid rootRuntimeID)) + { return; - GameObject? root = scene.FindObject(rootRuntimeId); + } + GameObject? root = scene.FindObject(rootRuntimeID); if (root is null) + { return; - var mappedObjectIds = connection.objectIdentities.Values.ToHashSet(); - var mappedComponentIds = connection.componentIdentities.Values.ToHashSet(); + } + HashSet mappedObjectIDs = connection.objectIdentities.Values.ToHashSet(); + HashSet mappedComponentIDs = connection.componentIdentities.Values.ToHashSet(); var stack = new Stack(); stack.Push(root); while (stack.Count != 0) { GameObject gameObject = stack.Pop(); - if (!mappedObjectIds.Contains(gameObject.identity.persistentId)) - overrides.MarkObjectAdded(gameObject.identity.persistentId); + if (!mappedObjectIDs.Contains(gameObject.identity.persistentID)) + { + overrides.MarkObjectAdded(gameObject.identity.persistentID); + } foreach (GameComponent component in gameObject.GetComponents()) { - if (!mappedComponentIds.Contains(component.identity.persistentId)) - overrides.MarkComponentAdded(component.identity.persistentId); + if (!mappedComponentIDs.Contains(component.identity.persistentID)) + { + overrides.MarkComponentAdded(component.identity.persistentID); + } } foreach (Transform child in gameObject.transform.children) + { stack.Push(child.gameObject); + } } } @@ -255,19 +288,23 @@ PrefabOverrideSet current ) { foreach (PrefabPropertyOverride property in previous.properties) { - if (!sourceConnection.componentIdentities.ContainsKey(property.sourceComponentId)) + if (!sourceConnection.componentIdentities.ContainsKey(property.sourceComponentID)) { - current.SetProperty(property with - { - value = (byte[])property.value.Clone(), - isOrphaned = true - }); + current.SetProperty( + property with + { + value = (byte[])property.value.Clone(), + isOrphaned = true + } + ); } } foreach (PrefabStructureOverride structure in previous.structures) { - if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectId)) - current.SetStructure(structure.sourceObjectId, structure.kind, isOrphaned: true); + if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectID)) + { + current.SetStructure(structure.sourceObjectID, structure.kind, isOrphaned: true); + } } } @@ -280,29 +317,23 @@ SerializationContext context foreach (PrefabPropertyOverride property in connection.overrides.properties.ToArray()) { bool hasProperty = false; - if (sourceConnection.componentIdentities.TryGetValue( - property.sourceComponentId, - out Guid sourceRuntimeId) && - sourceScene.FindComponent(sourceRuntimeId) is GameComponent sourceComponent) - { + if (sourceConnection.componentIdentities.TryGetValue(property.sourceComponentID, out Guid sourceRuntimeID) + && sourceScene.FindComponent(sourceRuntimeID) is GameComponent sourceComponent + ) { hasProperty = SerializedPropertyValueCodec.GetMembers(sourceComponent.GetType(), context) - .Any(member => string.Equals( - member.name, - property.propertyName, - StringComparison.Ordinal)); + .Any(member => string.Equals(member.name, property.propertyName, StringComparison.Ordinal)); } if (!hasProperty && !property.isOrphaned) + { connection.overrides.SetProperty(property with { isOrphaned = true }); + } } foreach (PrefabStructureOverride structure in connection.overrides.structures.ToArray()) { - if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectId) && - !structure.isOrphaned) - { - connection.overrides.SetStructure( - structure.sourceObjectId, - structure.kind, - isOrphaned: true); + if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectID) + && !structure.isOrphaned + ) { + connection.overrides.SetStructure(structure.sourceObjectID, structure.kind, isOrphaned: true); } } } @@ -313,28 +344,35 @@ private static void RemoveDeletedSourceObjects( GameScene scene, GameObject instanceRoot ) { - Guid[] removedSourceIds = connection.objectIdentities.Keys - .Where(sourceId => - connection.overrides.IsObjectRemoved(sourceId) || - !sourceConnection.objectIdentities.ContainsKey(sourceId)) + Guid[] removedSourceIDs = connection.objectIdentities.Keys + .Where(sourceID => ( + connection.overrides.IsObjectRemoved(sourceID) + || !sourceConnection.objectIdentities.ContainsKey(sourceID) + )) .ToArray(); - for (int i = 0; i < removedSourceIds.Length; i++) + for (int i = 0; i < removedSourceIDs.Length; i++) { - Guid sourceId = removedSourceIds[i]; - if (!connection.objectIdentities.TryGetValue(sourceId, out Guid runtimeId)) + Guid sourceID = removedSourceIDs[i]; + if (!connection.objectIdentities.TryGetValue(sourceID, out Guid runtimeID)) + { continue; - GameObject? target = scene.FindObject(runtimeId); + } + GameObject? target = scene.FindObject(runtimeID); if (target is null || ReferenceEquals(target, instanceRoot)) + { continue; + } GameObject[] addedChildren = target.transform.children .Select(static child => child.gameObject) - .Where(child => !connection.objectIdentities.Values.Contains(child.identity.persistentId)) + .Where(child => !connection.objectIdentities.Values.Contains(child.identity.persistentID)) .ToArray(); for (int childIndex = 0; childIndex < addedChildren.Length; childIndex++) + { scene.SetParent(addedChildren[childIndex].transform, instanceRoot.transform, worldPositionStays: false); + } scene.DestroyObject(target); - connection.RemoveObject(sourceId); + connection.RemoveObject(sourceID); } } @@ -344,24 +382,28 @@ private static void CreateNewSourceObjects( GameScene scene, GameScene sourceScene ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.objectIdentities) { - if (connection.objectIdentities.ContainsKey(sourceId) || connection.overrides.IsObjectRemoved(sourceId)) + if (connection.objectIdentities.ContainsKey(sourceID) || connection.overrides.IsObjectRemoved(sourceID)) + { continue; - GameObject sourceObject = sourceScene.FindObject(sourceRuntimeId) - ?? throw new InvalidOperationException($"Prefab source object '{sourceId}' disappeared during reconciliation."); + } + GameObject sourceObject = sourceScene.FindObject(sourceRuntimeID) + ?? throw new InvalidOperationException($"Prefab source object '{sourceID}' disappeared during reconciliation."); GameObject target = scene.CreateObject( sourceObject.name, - persistentId: null, - transformPersistentId: null, - invokeReset: false); + persistentID: null, + transformPersistentID: null, + invokeReset: false + ); target.SetTagDirect(sourceObject.tag); target.SetActiveSelfDirect(sourceObject.activeSelf); - connection.MapObject(sourceId, target); + connection.MapObject(sourceID, target); - Guid sourceTransformId = sourceConnection.componentIdentities.Single( - pair => pair.Value == sourceObject.transform.identity.persistentId).Key; - connection.MapComponent(sourceTransformId, target.transform); + Guid sourceTransformID = sourceConnection.componentIdentities.Single( + pair => pair.Value == sourceObject.transform.identity.persistentID + ).Key; + connection.MapComponent(sourceTransformID, target.transform); } } @@ -370,20 +412,25 @@ private static void RemoveDeletedSourceComponents( PrefabConnectionRecord sourceConnection, GameScene scene ) { - Guid[] removedSourceIds = connection.componentIdentities.Keys - .Where(sourceId => - connection.overrides.IsComponentRemoved(sourceId) || - !sourceConnection.componentIdentities.ContainsKey(sourceId)) + Guid[] removedSourceIDs = connection.componentIdentities.Keys + .Where(sourceID => ( + connection.overrides.IsComponentRemoved(sourceID) + || !sourceConnection.componentIdentities.ContainsKey(sourceID) + )) .ToArray(); - for (int i = 0; i < removedSourceIds.Length; i++) + for (int i = 0; i < removedSourceIDs.Length; i++) { - Guid sourceId = removedSourceIds[i]; - if (!connection.componentIdentities.TryGetValue(sourceId, out Guid runtimeId)) + Guid sourceID = removedSourceIDs[i]; + if (!connection.componentIdentities.TryGetValue(sourceID, out Guid runtimeID)) + { continue; - GameComponent? target = scene.FindComponent(runtimeId); + } + GameComponent? target = scene.FindComponent(runtimeID); if (target is not null && target is not Transform) + { scene.RemoveComponent(target.gameObject, target); - connection.RemoveComponent(sourceId); + } + connection.RemoveComponent(sourceID); } } @@ -393,25 +440,28 @@ private static void CreateNewSourceComponents( GameScene scene, GameScene sourceScene ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.componentIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.componentIdentities) { - if (connection.componentIdentities.ContainsKey(sourceId) || - connection.overrides.IsComponentRemoved(sourceId)) - { + if (connection.componentIdentities.ContainsKey(sourceID) + || connection.overrides.IsComponentRemoved(sourceID) + ) { continue; } - GameComponent sourceComponent = sourceScene.FindComponent(sourceRuntimeId) - ?? throw new InvalidOperationException($"Prefab source component '{sourceId}' disappeared during reconciliation."); - Guid sourceOwnerId = sourceConnection.objectIdentities.Single( - pair => pair.Value == sourceComponent.gameObject.identity.persistentId).Key; - if (!connection.objectIdentities.TryGetValue(sourceOwnerId, out Guid targetOwnerId)) + GameComponent sourceComponent = sourceScene.FindComponent(sourceRuntimeID) + ?? throw new InvalidOperationException($"Prefab source component '{sourceID}' disappeared during reconciliation."); + Guid sourceOwnerID = sourceConnection.objectIdentities.Single( + pair => pair.Value == sourceComponent.gameObject.identity.persistentID + ).Key; + if (!connection.objectIdentities.TryGetValue(sourceOwnerID, out Guid targetOwnerID)) + { continue; - GameObject targetOwner = scene.FindObject(targetOwnerId) - ?? throw new InvalidOperationException($"Prefab target owner for source object '{sourceOwnerId}' is unavailable."); + } + GameObject targetOwner = scene.FindObject(targetOwnerID) + ?? throw new InvalidOperationException($"Prefab target owner for source object '{sourceOwnerID}' is unavailable."); GameComponent target = sourceComponent is Transform - ? targetOwner.transform - : scene.AddComponent(targetOwner, sourceComponent.GetType(), persistentId: null, invokeReset: false); - connection.MapComponent(sourceId, target); + ? targetOwner.transform + : scene.AddComponent(targetOwner, sourceComponent.GetType(), persistentID: null, invokeReset: false); + connection.MapComponent(sourceID, target); } } @@ -424,36 +474,33 @@ private static void RestoreSourceProperties( SceneGraphReferenceMap sourceReferences, SceneGraphReferenceMap targetReferences ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.componentIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.componentIdentities) { - if (!connection.componentIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) - continue; - GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeId); - GameComponent? targetComponent = scene.FindComponent(targetRuntimeId); - if (sourceComponent is null || targetComponent is null || - sourceComponent.GetType() != targetComponent.GetType()) + if (!connection.componentIdentities.TryGetValue(sourceID, out Guid targetRuntimeID)) { continue; } + GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeID); + GameComponent? targetComponent = scene.FindComponent(targetRuntimeID); + if (sourceComponent is null || targetComponent is null + || sourceComponent.GetType() != targetComponent.GetType() + ) { + continue; + } - IReadOnlyList members = - SerializedPropertyValueCodec.GetMembers(sourceComponent.GetType(), context); + IReadOnlyList members = SerializedPropertyValueCodec.GetMembers( + sourceComponent.GetType(), + context + ); for (int memberIndex = 0; memberIndex < members.Count; memberIndex++) { SerializationMemberMetadata member = members[memberIndex]; - if (connection.overrides.IsPropertyOverridden(sourceId, member.name)) + if (connection.overrides.IsPropertyOverridden(sourceID, member.name)) + { continue; - byte[] value = SerializedPropertyValueCodec.Encode( - member, - sourceComponent, - context, - sourceReferences); - SerializedPropertyValueCodec.Decode( - member, - targetComponent, - value, - context, - targetReferences); + } + byte[] value = SerializedPropertyValueCodec.Encode(member, sourceComponent, context, sourceReferences); + SerializedPropertyValueCodec.Decode(member, targetComponent, value, context, targetReferences); } } } @@ -465,48 +512,64 @@ private static void RestoreSourceObjectState( GameScene sourceScene, GameObject instanceRoot ) { - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.objectIdentities) { - if (!connection.objectIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) + if (!connection.objectIdentities.TryGetValue(sourceID, out Guid targetRuntimeID)) + { continue; - GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); - GameObject? targetObject = scene.FindObject(targetRuntimeId); + } + GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeID); + GameObject? targetObject = scene.FindObject(targetRuntimeID); if (sourceObject is null || targetObject is null) + { continue; + } - PrefabObjectOverrideKind kind = connection.overrides.GetStructureOverride(sourceId); + PrefabObjectOverrideKind kind = connection.overrides.GetStructureOverride(sourceID); if ((kind & PrefabObjectOverrideKind.Name) == 0) + { targetObject.SetNameDirect(sourceObject.name); + } if ((kind & PrefabObjectOverrideKind.Tag) == 0) + { targetObject.SetTagDirect(sourceObject.tag); + } if ((kind & PrefabObjectOverrideKind.ActiveSelf) == 0) + { targetObject.SetActiveSelfDirect(sourceObject.activeSelf); - if (!ReferenceEquals(targetObject, instanceRoot) && - (kind & PrefabObjectOverrideKind.Parent) == 0) - { - Guid sourceParentId = GetMappedParentId(sourceObject, sourceConnection); - Transform? targetParent = sourceParentId == Guid.Empty - ? instanceRoot.transform - : connection.objectIdentities.TryGetValue(sourceParentId, out Guid parentRuntimeId) - ? scene.FindObject(parentRuntimeId)?.transform - : null; + } + if (!ReferenceEquals(targetObject, instanceRoot) + && (kind & PrefabObjectOverrideKind.Parent) == 0 + ) { + Guid sourceParentID = GetMappedParentID(sourceObject, sourceConnection); + Transform? targetParent = sourceParentID == Guid.Empty + ? instanceRoot.transform + : connection.objectIdentities.TryGetValue(sourceParentID, out Guid parentRuntimeID) + ? scene.FindObject(parentRuntimeID)?.transform + : null; scene.SetParent(targetObject.transform, targetParent, worldPositionStays: false); } } - foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities - .OrderBy(pair => sourceScene.FindObject(pair.Value)?.transform.siblingIndex ?? int.MaxValue)) - { - if (!connection.objectIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) + foreach ((Guid sourceID, Guid sourceRuntimeID) in sourceConnection.objectIdentities + .OrderBy(pair => sourceScene.FindObject(pair.Value)?.transform.siblingIndex ?? int.MaxValue) + ) { + if (!connection.objectIdentities.TryGetValue(sourceID, out Guid targetRuntimeID)) + { continue; - GameObject? targetObject = scene.FindObject(targetRuntimeId); + } + GameObject? targetObject = scene.FindObject(targetRuntimeID); if (targetObject is null || ReferenceEquals(targetObject, instanceRoot)) + { continue; - if ((connection.overrides.GetStructureOverride(sourceId) & PrefabObjectOverrideKind.SiblingIndex) == 0) + } + if ((connection.overrides.GetStructureOverride(sourceID) & PrefabObjectOverrideKind.SiblingIndex) == 0) { - GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); + GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeID); if (sourceObject is not null) + { scene.SetSiblingIndex(targetObject.transform, sourceObject.transform.siblingIndex); + } } scene.RecomputeActiveSubtree(targetObject); } @@ -518,21 +581,26 @@ private static void RefreshInstanceInfo( GameObject instanceRoot ) { GameScene scene = instanceRoot.scene; - foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) + foreach ((Guid sourceID, Guid runtimeID) in connection.objectIdentities) { - GameObject? gameObject = scene.FindObject(runtimeId); + GameObject? gameObject = scene.FindObject(runtimeID); if (gameObject is null) + { continue; - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - connection.sourceAsset.identity.persistentId, - sourceId, - instanceRoot, - ReferenceEquals(gameObject, instanceRoot), - connection.isVariant, - connection.sourceAsset.isMissing, - connection.overrides.count, - connection.overrides.orphanedCount, - connection.sourceAsset)); + } + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + connection.sourceAsset.identity.persistentID, + sourceID, + instanceRoot, + ReferenceEquals(gameObject, instanceRoot), + connection.isVariant, + connection.sourceAsset.isMissing, + connection.overrides.count, + connection.overrides.orphanedCount, + connection.sourceAsset + ) + ); } instanceRoot.SetPrefabConnectionDirect(connection); } @@ -546,18 +614,24 @@ PrefabConnectionRecord connection .ToArray(); var ids = new Dictionary(ReferenceEqualityComparer.Instance); for (int objectIndex = 0; objectIndex < allObjects.Length; objectIndex++) - ids.Add(allObjects[objectIndex], allObjects[objectIndex].identity.persistentId); - foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) { - GameObject? gameObject = scene.FindObject(runtimeId); + ids.Add(allObjects[objectIndex], allObjects[objectIndex].identity.persistentID); + } + foreach ((Guid sourceID, Guid runtimeID) in connection.objectIdentities) + { + GameObject? gameObject = scene.FindObject(runtimeID); if (gameObject is not null) - ids[gameObject] = sourceId; + { + ids[gameObject] = sourceID; + } } - foreach ((Guid sourceId, Guid runtimeId) in connection.componentIdentities) + foreach ((Guid sourceID, Guid runtimeID) in connection.componentIdentities) { - GameComponent? component = scene.FindComponent(runtimeId); + GameComponent? component = scene.FindComponent(runtimeID); if (component is not null) - ids[component] = sourceId; + { + ids[component] = sourceID; + } } return new SceneGraphReferenceMap(scene, ids); } @@ -567,45 +641,50 @@ private static SceneGraphReferenceMap CreateTargetReferences( PrefabConnectionRecord connection ) { SceneGraphReferenceMap references = CreateComparisonReferences(scene, connection); - foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) + foreach ((Guid sourceID, Guid runtimeID) in connection.objectIdentities) { - GameObject? gameObject = scene.FindObject(runtimeId); + GameObject? gameObject = scene.FindObject(runtimeID); if (gameObject is not null) - references.Register(sourceId, gameObject); + { + references.Register(sourceID, gameObject); + } } - foreach ((Guid sourceId, Guid runtimeId) in connection.componentIdentities) + foreach ((Guid sourceID, Guid runtimeID) in connection.componentIdentities) { - GameComponent? component = scene.FindComponent(runtimeId); + GameComponent? component = scene.FindComponent(runtimeID); if (component is not null) - references.Register(sourceId, component); + { + references.Register(sourceID, component); + } } return references; } - private static Guid GetMappedParentId( + private static Guid GetMappedParentID( GameObject gameObject, PrefabConnectionRecord connection ) { Transform? parent = gameObject.transform.parent; if (parent is null) + { return Guid.Empty; - Guid parentRuntimeId = parent.gameObject.identity.persistentId; - foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) + } + Guid parentRuntimeID = parent.gameObject.identity.persistentID; + foreach ((Guid sourceID, Guid runtimeID) in connection.objectIdentities) { - if (runtimeId == parentRuntimeId) - return sourceId; + if (runtimeID == parentRuntimeID) + { + return sourceID; + } } - return parentRuntimeId; + return parentRuntimeID; } private static (GameScene scene, GameObject root, PrefabConnectionRecord connection) InstantiateSource( AssetObject sourceAsset, SerializationContext context ) { - var sourceScene = new GameScene( - SceneWorld.current.typeCatalog, - "Prefab Source Comparison", - persistentId: null); + var sourceScene = new GameScene(SceneWorld.current.typeCatalog, "Prefab Source Comparison", persistentID: null); SerializationContext sourceContext = context .With(sourceScene) .With(sourceAsset); @@ -615,19 +694,25 @@ SerializationContext context { GameObject sourceRoot = context.GetRequired().Deserialize( sourceAsset.runtimePayload.Span, - sourceContext); + sourceContext + ); if (!string.IsNullOrWhiteSpace(sourceAsset.assetPath.ToString())) + { sourceRoot.name = Path.GetFileNameWithoutExtension(sourceAsset.assetPath.ToString()); + } PrefabConnectionRecord connection = sourceRoot.prefabConnection ?? throw new InvalidOperationException( - $"Prefab source asset '{sourceAsset.identity.persistentId}' did not create a source mapping."); + $"Prefab source asset '{sourceAsset.identity.persistentID}' did not create a source mapping." + ); return (sourceScene, sourceRoot, connection); } } catch { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } throw; } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs index 291d2a29d..679dd3fc9 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs @@ -1,11 +1,10 @@ using System; using System.IO; using System.Runtime.ExceptionServices; - using Inno.Assets; using Inno.Core.Identity; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Scene; @@ -48,7 +47,7 @@ IAssetReferenceResolver assets var state = new SceneElementState(); if (target is MissingGameComponent component) { - state.typeId = component.missingType.stableId; + state.typeId = component.missingType.stableID; state.typeName = component.missingTypeName; state.properties = component.CaptureSerializedState(); state.SetDependencies(component.dependencies); @@ -56,7 +55,7 @@ IAssetReferenceResolver assets } else if (target is MissingGameSystem system) { - state.typeId = system.missingType.stableId; + state.typeId = system.missingType.stableID; state.typeName = system.missingTypeName; state.properties = system.CaptureSerializedState(); state.SetDependencies(system.dependencies); @@ -65,13 +64,19 @@ IAssetReferenceResolver assets else { if (target is not GameComponent and not GameSystem) + { throw new ArgumentException("Element state requires a component or system.", nameof(target)); - state.typeId = scene.typeCatalog.GetTypeRef(target.GetType()).stableId; + } + state.typeId = scene.typeCatalog.GetTypeRef(target.GetType()).stableID; state.typeName = target.GetType().FullName ?? target.GetType().Name; var dependencies = new AssetDependencyCollection(); using (ScenePropertySerialization.CreateReferences(scene).Enter()) - state.properties = serialization.CapturePropertiesData((ISerializable)target, - AssetSerializationContext.Create(assets, dependencies)); + { + state.properties = serialization.CapturePropertiesData( + (ISerializable)target, + AssetSerializationContext.Create(assets, dependencies) + ); + } state.SetDependencies(dependencies.dependencies); } return serialization.Serialize(state, AssetSerializationContext.Create(assets)); @@ -109,20 +114,33 @@ IAssetReferenceResolver assets GameScene scene = ScenePropertySerialization.ResolveScene(target); Guid logicalType = target switch { - MissingGameComponent missing => missing.missingType.stableId, - MissingGameSystem missing => missing.missingType.stableId, - _ => scene.typeCatalog.GetTypeRef(target.GetType()).stableId + MissingGameComponent missing => missing.missingType.stableID, + MissingGameSystem missing => missing.missingType.stableID, + _ => scene.typeCatalog.GetTypeRef(target.GetType()).stableID }; RequireType(state, logicalType); if (target is MissingGameComponent component) + { component.RestoreState(state); + } else if (target is MissingGameSystem system) + { system.RestoreState(state); + } else { using (ScenePropertySerialization.CreateReferences(scene, state.GetAliases()).Enter()) - RequireComplete(serialization.RestorePropertiesData((ISerializable)target, state.properties, - SerializationPropertyRestoreMode.Strict, AssetSerializationContext.Create(assets)), "element"); + { + RequireComplete( + serialization.RestorePropertiesData( + (ISerializable)target, + state.properties, + SerializationPropertyRestoreMode.Strict, + AssetSerializationContext.Create(assets) + ), + "element" + ); + } } } @@ -135,7 +153,7 @@ IAssetReferenceResolver assets /// /// The reload-safe identity of the current component implementation. /// - /// + /// /// The component instance identity to preserve. /// /// @@ -166,7 +184,7 @@ IAssetReferenceResolver assets public static GameComponent RestoreComponent( GameObject owner, TypeRef type, - Guid persistentId, + Guid persistentID, int componentIndex, ReadOnlySpan stateData, SerializationRegistry serialization, @@ -176,12 +194,18 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); SceneElementState state = ReadState(stateData, serialization, assets); - RequireType(state, type.stableId); + RequireType(state, type.stableID); Type? componentType = ResolveType(owner.scene.typeCatalog, type, "component"); GameComponent component = componentType is null - ? owner.scene.AddMissingComponent(owner, new TypeRef(state.typeId), state.typeName, - state.properties, persistentId, state.GetDependencies()) - : owner.scene.AddComponent(owner, componentType, persistentId, invokeReset: false); + ? owner.scene.AddMissingComponent( + owner, + new TypeRef(state.typeId), + state.typeName, + state.properties, + persistentID, + state.GetDependencies() + ) + : owner.scene.AddComponent(owner, componentType, persistentID, invokeReset: false); try { owner.SetComponentIndex(component, componentIndex); @@ -190,11 +214,7 @@ IAssetReferenceResolver assets } catch (Exception exception) { - RethrowAfterCleanup( - exception, - component, - () => owner.RemoveComponent(component), - "component"); + RethrowAfterCleanup(exception, component, () => owner.RemoveComponent(component), "component"); throw; } } @@ -208,7 +228,7 @@ IAssetReferenceResolver assets /// /// The reload-safe identity of the current system implementation. /// - /// + /// /// The system instance identity to preserve. /// /// @@ -239,7 +259,7 @@ IAssetReferenceResolver assets public static GameSystem RestoreSystem( GameScene scene, TypeRef type, - Guid persistentId, + Guid persistentID, int systemIndex, ReadOnlySpan stateData, SerializationRegistry serialization, @@ -249,11 +269,11 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); SceneElementState state = ReadState(stateData, serialization, assets); - RequireType(state, type.stableId); + RequireType(state, type.stableID); Type? systemType = ResolveType(scene.typeCatalog, type, "system"); GameSystem system = systemType is null - ? scene.AddMissingSystem(new TypeRef(state.typeId), state.typeName, state.properties, persistentId, state.GetDependencies()) - : scene.AddSystem(systemType, persistentId, invokeReset: false); + ? scene.AddMissingSystem(new TypeRef(state.typeId), state.typeName, state.properties, persistentID, state.GetDependencies()) + : scene.AddSystem(systemType, persistentID, invokeReset: false); try { scene.SetSystemIndex(system, systemIndex); @@ -262,34 +282,18 @@ IAssetReferenceResolver assets } catch (Exception exception) { - RethrowAfterCleanup( - exception, - system, - () => scene.RemoveSystem(system), - "system"); + RethrowAfterCleanup(exception, system, () => scene.RemoveSystem(system), "system"); throw; } } - private static void RequireComplete( - SerializationPropertyRestoreResult result, - string kind - ) { - if (result.success && result.ignoredCount == 0) - return; - throw new InvalidOperationException( - $"Scene {kind} property restoration was incomplete: " + - $"{result.restoredCount} restored, {result.ignoredCount} ignored, " + - $"{result.failures.Count} failed."); - } - internal static void RethrowAfterCleanup( Exception restoreFailure, EngineObject element, Func remove, string kind ) { - Guid persistentId = element.identity.persistentId; + Guid persistentID = element.identity.persistentID; Exception? cleanupFailure = null; bool reportedRemoved = false; if (!element.isDestroyed) @@ -303,22 +307,39 @@ string kind cleanupFailure = exception; } } - bool remainsRegistered = ReferenceEquals( - IdentityAllocator.current.Get(persistentId), - element); + bool remainsRegistered = ReferenceEquals(IdentityAllocator.current.Get(persistentID), element); if ((!element.isDestroyed || remainsRegistered) && cleanupFailure is null) { cleanupFailure = new InvalidOperationException( reportedRemoved - ? $"The partially restored scene {kind} reported successful removal but did not reach the destroyed and unregistered postcondition." - : $"The partially restored scene {kind} could not be fully destroyed and unregistered."); + ? $"The partially restored scene {kind} reported successful removal but did not reach the destroyed and unregistered postcondition." + : $"The partially restored scene {kind} could not be fully destroyed and unregistered." + ); } if (cleanupFailure is null) + { ExceptionDispatchInfo.Capture(restoreFailure).Throw(); + } throw new InvalidOperationException( $"Scene {kind} restoration failed and its cleanup did not complete successfully.", - new AggregateException(restoreFailure, cleanupFailure)); + new AggregateException(restoreFailure, cleanupFailure) + ); + } + + private static void RequireComplete( + SerializationPropertyRestoreResult result, + string kind + ) { + if (result.success && result.ignoredCount == 0) + { + return; + } + throw new InvalidOperationException( + $"Scene {kind} property restoration was incomplete: " + + $"{result.restoredCount} restored, {result.ignoredCount} ignored, " + + $"{result.failures.Count} failed." + ); } private static SceneElementState ReadState( @@ -329,25 +350,26 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); SceneElementState state = serialization.Deserialize(bytes, AssetSerializationContext.Create(assets)) - ?? throw new InvalidDataException("Scene element state is null."); + ?? throw new InvalidDataException("Scene element state is null."); state.Validate(); return state; } private static void RequireType( SceneElementState state, - Guid typeId + Guid typeID ) { - if (state.typeId != typeId) - throw new InvalidDataException($"Element state type '{state.typeId}' does not match logical type '{typeId}'."); + if (state.typeId != typeID) + { + throw new InvalidDataException($"Element state type '{state.typeId}' does not match logical type '{typeID}'."); + } } private static Type? ResolveType( SceneTypeCatalog types, TypeRef typeRef, string kind - ) - where TElement : EngineObject + ) where TElement : EngineObject { Type type; try @@ -361,7 +383,8 @@ string kind if (!typeof(TElement).IsAssignableFrom(type) || type.IsAbstract) { throw new InvalidDataException( - $"Stable type id '{typeRef.stableId}' resolves to invalid scene {kind} '{type.FullName}'."); + $"Stable type id '{typeRef.stableID}' resolves to invalid scene {kind} '{type.FullName}'." + ); } return type; } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs index 4519e52f8..48bbdd0ad 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs @@ -4,25 +4,41 @@ using System.Linq; using Inno.Assets; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene; internal sealed class SceneElementState : ISerializable { - [SerializableProperty] internal Guid typeId { get; set; } - [SerializableProperty] internal string typeName { get; set; } = string.Empty; - [SerializableProperty] internal byte[] properties { get; set; } = []; - [SerializableProperty] internal Guid[] dependencyIds { get; set; } = []; - [SerializableProperty] internal Guid[] dependencyTypes { get; set; } = []; - [SerializableProperty] internal string[] dependencyPaths { get; set; } = []; - [SerializableProperty] internal Guid[] aliasIds { get; set; } = []; - [SerializableProperty] internal Guid[] aliasTargets { get; set; } = []; + [SerializableProperty] + internal Guid typeId { get; set; } + + [SerializableProperty] + internal string typeName { get; set; } = string.Empty; + + [SerializableProperty] + internal byte[] properties { get; set; } = []; + + [SerializableProperty] + internal Guid[] dependencyIds { get; set; } = []; + + [SerializableProperty] + internal Guid[] dependencyTypes { get; set; } = []; + + [SerializableProperty] + internal string[] dependencyPaths { get; set; } = []; + + [SerializableProperty] + internal Guid[] aliasIds { get; set; } = []; + + [SerializableProperty] + internal Guid[] aliasTargets { get; set; } = []; internal void SetDependencies(IEnumerable dependencies) { - AssetDependency[] snapshot = dependencies.OrderBy(static value => value.persistentId).ToArray(); - dependencyIds = snapshot.Select(static value => value.persistentId).ToArray(); - dependencyTypes = snapshot.Select(static value => value.type.stableId).ToArray(); + AssetDependency[] snapshot = dependencies.OrderBy(static value => value.persistentID).ToArray(); + dependencyIds = snapshot.Select(static value => value.persistentID).ToArray(); + dependencyTypes = snapshot.Select(static value => value.type.stableID).ToArray(); dependencyPaths = snapshot.Select(static value => value.lastKnownPath).ToArray(); } @@ -37,8 +53,7 @@ internal AssetDependency[] GetDependencies() => dependencyIds.Select(( id, index - ) => new AssetDependency(id, - new Inno.Extensibility.Types.TypeRef(dependencyTypes[index]), dependencyPaths[index])).ToArray(); + ) => new AssetDependency(id, new TypeRef(dependencyTypes[index]), dependencyPaths[index])).ToArray(); internal IReadOnlyDictionary GetAliases() => aliasIds.Select(( @@ -48,15 +63,17 @@ internal IReadOnlyDictionary GetAliases() internal void Validate() { - if (typeId == Guid.Empty || string.IsNullOrWhiteSpace(typeName) || properties is null || - dependencyIds is null || dependencyTypes is null || dependencyPaths is null || - aliasIds is null || aliasTargets is null || - dependencyIds.Length != dependencyTypes.Length || dependencyIds.Length != dependencyPaths.Length || - aliasIds.Length != aliasTargets.Length || - dependencyIds.Any(static id => id == Guid.Empty) || - dependencyIds.Distinct().Count() != dependencyIds.Length || - aliasIds.Any(static id => id == Guid.Empty) || aliasTargets.Any(static id => id == Guid.Empty) || - aliasIds.Distinct().Count() != aliasIds.Length) + if (typeId == Guid.Empty || string.IsNullOrWhiteSpace(typeName) || properties is null + || dependencyIds is null || dependencyTypes is null || dependencyPaths is null + || aliasIds is null || aliasTargets is null + || dependencyIds.Length != dependencyTypes.Length || dependencyIds.Length != dependencyPaths.Length + || aliasIds.Length != aliasTargets.Length + || dependencyIds.Any(static id => id == Guid.Empty) + || dependencyIds.Distinct().Count() != dependencyIds.Length + || aliasIds.Any(static id => id == Guid.Empty) || aliasTargets.Any(static id => id == Guid.Empty) + || aliasIds.Distinct().Count() != aliasIds.Length + ) { throw new InvalidDataException("Scene element state contains invalid type, dependency or alias metadata."); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs index 91d2f75f9..1c270e0ee 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scene; namespace Inno.Scene; diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs index 292656f14..91a8303b6 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scene; namespace Inno.Scene; @@ -10,59 +9,63 @@ namespace Inno.Scene; /// internal sealed class SceneGraphReferenceMap : SceneReferenceScope { - private readonly IReadOnlyDictionary? m_sourceIdByObject; - private readonly Dictionary m_objectBySourceId = new(); + private readonly IReadOnlyDictionary? m_sourceIDByObject; + private readonly Dictionary m_objectBySourceID = []; internal SceneGraphReferenceMap( GameScene scene, - IReadOnlyDictionary? sourceIds = null, + IReadOnlyDictionary? sourceIDs = null, GameObject? captureRoot = null - ) : base(scene, captureRoot) { + ) : base(scene, captureRoot) + { // Capture callers own the complete map and keep it fixed for this synchronous scope. - m_sourceIdByObject = sourceIds; + m_sourceIDByObject = sourceIDs; } + /// + protected override bool TryGetSourceID( + EngineObject engineObject, + out Guid sourceID + ) { + sourceID = default; + return m_sourceIDByObject is not null && m_sourceIDByObject.TryGetValue(engineObject, out sourceID); + } + + /// + protected override bool TryResolve( + Guid sourceID, + out EngineObject? engineObject + ) => m_objectBySourceID.TryGetValue(sourceID, out engineObject); + internal void Register( - Guid sourceId, + Guid sourceID, EngineObject engineObject ) { - if (!m_objectBySourceId.TryAdd(sourceId, engineObject) && - !ReferenceEquals(m_objectBySourceId[sourceId], engineObject)) - { - throw new InvalidOperationException($"Duplicate scene graph local identity '{sourceId}'."); + if (!m_objectBySourceID.TryAdd(sourceID, engineObject) + && !ReferenceEquals(m_objectBySourceID[sourceID], engineObject) + ) { + throw new InvalidOperationException($"Duplicate scene graph local identity '{sourceID}'."); } } internal Dictionary CaptureRemappedAliases() { var aliases = new Dictionary(); - foreach ((Guid sourceId, EngineObject engineObject) in m_objectBySourceId) + foreach ((Guid sourceID, EngineObject engineObject) in m_objectBySourceID) { - Guid persistentId = engineObject.identity.persistentId; - if (sourceId != persistentId) - aliases.Add(sourceId, persistentId); + Guid persistentID = engineObject.identity.persistentID; + if (sourceID != persistentID) + { + aliases.Add(sourceID, persistentID); + } } return aliases; } - internal EngineObject GetRegistered(Guid sourceId) - => m_objectBySourceId.TryGetValue(sourceId, out EngineObject? engineObject) - ? engineObject - : throw new InvalidOperationException( - $"Scene graph reference alias target '{sourceId}' could not be resolved."); - - /// - protected override bool TryGetSourceId( - EngineObject engineObject, - out Guid sourceId - ) { - sourceId = default; - return m_sourceIdByObject is not null && m_sourceIdByObject.TryGetValue(engineObject, out sourceId); - } - - /// - protected override bool TryResolve( - Guid sourceId, - out EngineObject? engineObject - ) => m_objectBySourceId.TryGetValue(sourceId, out engineObject); + internal EngineObject GetRegistered(Guid sourceID) + => m_objectBySourceID.TryGetValue(sourceID, out EngineObject? engineObject) + ? engineObject + : throw new InvalidOperationException( + $"Scene graph reference alias target '{sourceID}' could not be resolved." + ); } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs index 1f515d513..a8dadbf1e 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -60,103 +59,111 @@ internal static class SceneGraphSerialization internal static void WriteObjects( SerializationWriter writer, IReadOnlyCollection entries, - IReadOnlyDictionary sourceIds, + IReadOnlyDictionary sourceIDs, Predicate containsObject, bool preserveRootSiblingOrder ) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(entries); - ArgumentNullException.ThrowIfNull(sourceIds); + ArgumentNullException.ThrowIfNull(sourceIDs); ArgumentNullException.ThrowIfNull(containsObject); Action writeComponent = ( componentWriter, component - ) => WriteComponent(componentWriter, component, sourceIds); - WriteMissingReferenceAliases(writer, sourceIds); - writer.WriteObjectArray(C_OBJECTS_KEY, entries, ( - objectWriter, - entry - ) => - { - GameObject gameObject = entry.gameObject; - Transform? parent = gameObject.transform.parent; - bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); - objectWriter.Write(C_OBJECT_ID_KEY, GetSourceId(sourceIds, gameObject)); - objectWriter.Write(C_NAME_KEY, gameObject.name); - objectWriter.Write(C_TAG_KEY, gameObject.tag); - objectWriter.Write(C_LAYER_KEY, gameObject.layer.index); - objectWriter.Write(C_ACTIVE_SELF_KEY, gameObject.activeSelf); - objectWriter.Write( - C_PARENT_ID_KEY, - parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty); - objectWriter.Write( - C_SIBLING_INDEX_KEY, - parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0); - PrefabInstanceInfo? prefab = gameObject.prefabInstance; - bool hasPrefabConnection = prefab is not null && containsObject(prefab.instanceRoot); - objectWriter.Write(C_HAS_PREFAB_CONNECTION_KEY, hasPrefabConnection); - if (hasPrefabConnection) + ) => WriteComponent(componentWriter, component, sourceIDs); + WriteMissingReferenceAliases(writer, sourceIDs); + writer.WriteObjectArray( + C_OBJECTS_KEY, + entries, + ( + objectWriter, + entry + ) => { - AssetObject sourceAsset = prefab!.sourceAsset; - objectWriter.Write(C_PREFAB_SOURCE_ASSET_KEY, sourceAsset); - objectWriter.Write(C_PREFAB_SOURCE_ASSET_ID_KEY, prefab!.sourceAssetId); - objectWriter.Write(C_PREFAB_SOURCE_OBJECT_ID_KEY, prefab.sourceObjectId); - objectWriter.Write(C_PREFAB_INSTANCE_ROOT_ID_KEY, GetSourceId(sourceIds, prefab.instanceRoot)); - objectWriter.Write(C_PREFAB_IS_VARIANT_KEY, prefab.isVariant); - objectWriter.Write(C_PREFAB_IS_MISSING_KEY, prefab.isMissing); - PrefabOverrideSet? capturedOverrides = null; - if (prefab.isRoot) - { - PrefabConnectionRecord connection = gameObject.prefabConnection - ?? throw new InvalidOperationException( - $"Prefab instance root '{gameObject.identity.persistentId}' has no connection mapping."); - capturedOverrides = PrefabOverrideProcessor.Capture( - connection, - gameObject.scene, - objectWriter.context, - SceneReferenceScope.current); - WritePrefabConnection( - objectWriter, - connection, - capturedOverrides, - sourceIds, - gameObject.scene); - } + GameObject gameObject = entry.gameObject; + Transform? parent = gameObject.transform.parent; + bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); + objectWriter.Write(C_OBJECT_ID_KEY, GetSourceID(sourceIDs, gameObject)); + objectWriter.Write(C_NAME_KEY, gameObject.name); + objectWriter.Write(C_TAG_KEY, gameObject.tag); + objectWriter.Write(C_LAYER_KEY, gameObject.layer.index); + objectWriter.Write(C_ACTIVE_SELF_KEY, gameObject.activeSelf); objectWriter.Write( - C_PREFAB_OVERRIDE_COUNT_KEY, - capturedOverrides?.count ?? prefab.overrideCount); + C_PARENT_ID_KEY, + parentIsIncluded ? GetSourceID(sourceIDs, parent!.gameObject) : Guid.Empty + ); objectWriter.Write( - C_PREFAB_ORPHANED_OVERRIDE_COUNT_KEY, - capturedOverrides?.orphanedCount ?? prefab.orphanedOverrideCount); - } - objectWriter.WriteObjectArray(C_COMPONENTS_KEY, entry.components, writeComponent); - }, captureKey: ( - entry, - key - ) => { - GameObject gameObject = entry.gameObject; - if (gameObject.prefabInstance is not null || !key.TryAddOwner(gameObject, gameObject.captureRevision)) - return false; - Transform? parent = gameObject.transform.parent; - bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); - key.AddValue(GetSourceId(sourceIds, gameObject)); - key.AddValue(parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty); - key.AddValue((ulong)(parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0)); - for (int componentIndex = 0; componentIndex < entry.components.Count; componentIndex++) - { - GameComponent component = entry.components[componentIndex]; - if (component is MissingGameComponent || !key.TryAddProperties(component)) + C_SIBLING_INDEX_KEY, + parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0 + ); + PrefabInstanceInfo? prefab = gameObject.prefabInstance; + bool hasPrefabConnection = prefab is not null && containsObject(prefab.instanceRoot); + objectWriter.Write(C_HAS_PREFAB_CONNECTION_KEY, hasPrefabConnection); + if (hasPrefabConnection) + { + AssetObject sourceAsset = prefab!.sourceAsset; + objectWriter.Write(C_PREFAB_SOURCE_ASSET_KEY, sourceAsset); + objectWriter.Write(C_PREFAB_SOURCE_ASSET_ID_KEY, prefab!.sourceAssetID); + objectWriter.Write(C_PREFAB_SOURCE_OBJECT_ID_KEY, prefab.sourceObjectID); + objectWriter.Write(C_PREFAB_INSTANCE_ROOT_ID_KEY, GetSourceID(sourceIDs, prefab.instanceRoot)); + objectWriter.Write(C_PREFAB_IS_VARIANT_KEY, prefab.isVariant); + objectWriter.Write(C_PREFAB_IS_MISSING_KEY, prefab.isMissing); + PrefabOverrideSet? capturedOverrides = null; + if (prefab.isRoot) + { + PrefabConnectionRecord connection = gameObject.prefabConnection + ?? throw new InvalidOperationException( + $"Prefab instance root '{gameObject.identity.persistentID}' has no connection mapping." + ); + capturedOverrides = PrefabOverrideProcessor.Capture( + connection, + gameObject.scene, + objectWriter.context, + SceneReferenceScope.current + ); + WritePrefabConnection(objectWriter, connection, capturedOverrides, sourceIDs, gameObject.scene); + } + objectWriter.Write(C_PREFAB_OVERRIDE_COUNT_KEY, capturedOverrides?.count ?? prefab.overrideCount); + objectWriter.Write( + C_PREFAB_ORPHANED_OVERRIDE_COUNT_KEY, + capturedOverrides?.orphanedCount ?? prefab.orphanedOverrideCount + ); + } + objectWriter.WriteObjectArray(C_COMPONENTS_KEY, entry.components, writeComponent); + }, + captureKey: ( + entry, + key + ) => + { + GameObject gameObject = entry.gameObject; + if (gameObject.prefabInstance is not null || !key.TryAddOwner(gameObject, gameObject.captureRevision)) + { return false; - key.AddValue(GetSourceId(sourceIds, component)); + } + Transform? parent = gameObject.transform.parent; + bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); + key.AddValue(GetSourceID(sourceIDs, gameObject)); + key.AddValue(parentIsIncluded ? GetSourceID(sourceIDs, parent!.gameObject) : Guid.Empty); + key.AddValue((ulong)(parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0)); + for (int componentIndex = 0; componentIndex < entry.components.Count; componentIndex++) + { + GameComponent component = entry.components[componentIndex]; + if (component is MissingGameComponent || !key.TryAddProperties(component)) + { + return false; + } + key.AddValue(GetSourceID(sourceIDs, component)); + } + return true; } - return true; - }); + ); } internal static RestoredSceneGraph RestoreObjects( GameScene scene, IReadOnlyList objectReaders, - bool preservePersistentIds, + bool preservePersistentIDs, SceneGraphReferenceMap references, IReadOnlyList> missingReferenceAliases, SerializationContext context, @@ -167,51 +174,51 @@ internal static RestoredSceneGraph RestoreObjects( ArgumentNullException.ThrowIfNull(references); ValidateObjects(objectReaders); - var gameObjectBySourceId = new Dictionary(); - var componentBySourceId = new Dictionary(); - var componentRestores = new List<(GameComponent component, byte[] state)>(); - var missingPlaceholders = new List(); + var gameObjectBySourceID = new Dictionary(); + var componentBySourceID = new Dictionary(); + List<(GameComponent component, byte[] state)> componentRestores = []; + List missingPlaceholders = []; for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { SerializationReader objectReader = objectReaders[objectIndex]; - Guid sourceObjectId = objectReader.Read(C_OBJECT_ID_KEY); + Guid sourceObjectID = objectReader.Read(C_OBJECT_ID_KEY); IReadOnlyList componentReaders = objectReader.ReadObjectArray(C_COMPONENTS_KEY); SerializationReader transformReader = componentReaders.Single(IsTransform); - Guid sourceTransformId = transformReader.Read(C_COMPONENT_ID_KEY); + Guid sourceTransformID = transformReader.Read(C_COMPONENT_ID_KEY); GameObject gameObject = scene.CreateObject( objectReader.Read(C_NAME_KEY), - preservePersistentIds ? sourceObjectId : null, - preservePersistentIds ? sourceTransformId : null, - invokeReset: false); - gameObject.SetTagDirect( - objectReader.Read(C_TAG_KEY)); + preservePersistentIDs ? sourceObjectID : null, + preservePersistentIDs ? sourceTransformID : null, + invokeReset: false + ); + gameObject.SetTagDirect(objectReader.Read(C_TAG_KEY)); gameObject.SetLayerDirect(new GameLayer(objectReader.Read(C_LAYER_KEY))); gameObject.SetActiveSelfDirect(objectReader.Read(C_ACTIVE_SELF_KEY)); - gameObjectBySourceId.Add(sourceObjectId, gameObject); - componentBySourceId.Add(sourceTransformId, gameObject.transform); + gameObjectBySourceID.Add(sourceObjectID, gameObject); + componentBySourceID.Add(sourceTransformID, gameObject.transform); componentRestores.Add((gameObject.transform, transformReader.Read(C_STATE_KEY))); } for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { SerializationReader objectReader = objectReaders[objectIndex]; - Guid sourceObjectId = objectReader.Read(C_OBJECT_ID_KEY); - GameObject gameObject = gameObjectBySourceId[sourceObjectId]; + Guid sourceObjectID = objectReader.Read(C_OBJECT_ID_KEY); + GameObject gameObject = gameObjectBySourceID[sourceObjectID]; IReadOnlyList componentReaders = objectReader.ReadObjectArray(C_COMPONENTS_KEY); int transformIndex = -1; for (int componentIndex = 0; componentIndex < componentReaders.Count; componentIndex++) { SerializationReader componentReader = componentReaders[componentIndex]; - Guid stableTypeId = componentReader.Read(C_STABLE_TYPE_ID_KEY); - if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) && - componentType == typeof(Transform)) - { + Guid stableTypeID = componentReader.Read(C_STABLE_TYPE_ID_KEY); + if (TryResolveComponentType(stableTypeID, componentReader.context, out Type? componentType) + && componentType == typeof(Transform) + ) { transformIndex = componentIndex; continue; } - Guid sourceComponentId = componentReader.Read(C_COMPONENT_ID_KEY); + Guid sourceComponentID = componentReader.Read(C_COMPONENT_ID_KEY); byte[] state = componentReader.Read(C_STATE_KEY); AssetDependency[] dependencies = ReadStateDependencies(componentReader); GameComponent component; @@ -219,11 +226,12 @@ internal static RestoredSceneGraph RestoreObjects( { component = scene.AddMissingComponent( gameObject, - new TypeRef(stableTypeId), + new TypeRef(stableTypeID), componentReader.Read(C_TYPE_NAME_KEY), state, - preservePersistentIds ? sourceComponentId : null, - dependencies); + preservePersistentIDs ? sourceComponentID : null, + dependencies + ); missingPlaceholders.Add(component); } else @@ -231,24 +239,30 @@ internal static RestoredSceneGraph RestoreObjects( component = scene.AddComponent( gameObject, componentType, - preservePersistentIds ? sourceComponentId : null, - invokeReset: false); + preservePersistentIDs ? sourceComponentID : null, + invokeReset: false + ); componentRestores.Add((component, state)); } - componentBySourceId.Add(sourceComponentId, component); + componentBySourceID.Add(sourceComponentID, component); } if (transformIndex < 0) { throw new InvalidDataException( - $"Scene graph object '{sourceObjectId}' does not contain its validated Transform component."); + $"Scene graph object '{sourceObjectID}' does not contain its validated Transform component." + ); } gameObject.SetComponentIndex(gameObject.transform, transformIndex); } - foreach ((Guid sourceId, GameObject gameObject) in gameObjectBySourceId) - references.Register(sourceId, gameObject); - foreach ((Guid sourceId, GameComponent component) in componentBySourceId) - references.Register(sourceId, component); + foreach ((Guid sourceID, GameObject gameObject) in gameObjectBySourceID) + { + references.Register(sourceID, gameObject); + } + foreach ((Guid sourceID, GameComponent component) in componentBySourceID) + { + references.Register(sourceID, component); + } if (restoreProperties) { @@ -261,7 +275,8 @@ internal static RestoredSceneGraph RestoreObjects( serialization.RestorePropertiesData( componentRestores[i].component, componentRestores[i].state, - context: context); + context: context + ); } } } @@ -269,50 +284,58 @@ internal static RestoredSceneGraph RestoreObjects( for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { SerializationReader objectReader = objectReaders[objectIndex]; - Guid sourceObjectId = objectReader.Read(C_OBJECT_ID_KEY); - Guid parentId = objectReader.Read(C_PARENT_ID_KEY); - Transform? parent = parentId == Guid.Empty - ? null - : gameObjectBySourceId.TryGetValue(parentId, out GameObject? parentObject) - ? parentObject.transform - : throw new InvalidDataException( - $"Parent object '{parentId}' for object '{sourceObjectId}' is outside the restored boundary."); - scene.SetParent(gameObjectBySourceId[sourceObjectId].transform, parent, worldPositionStays: false); + Guid sourceObjectID = objectReader.Read(C_OBJECT_ID_KEY); + Guid parentID = objectReader.Read(C_PARENT_ID_KEY); + Transform? parent = parentID == Guid.Empty + ? null + : gameObjectBySourceID.TryGetValue(parentID, out GameObject? parentObject) + ? parentObject.transform + : throw new InvalidDataException( + $"Parent object '{parentID}' for object '{sourceObjectID}' is outside the restored boundary." + ); + scene.SetParent(gameObjectBySourceID[sourceObjectID].transform, parent, worldPositionStays: false); } foreach (IGrouping siblingGroup in objectReaders.GroupBy( - objectReader => objectReader.Read(C_PARENT_ID_KEY))) - { + objectReader => objectReader.Read(C_PARENT_ID_KEY) + )) { foreach (SerializationReader objectReader in siblingGroup.OrderBy( - reader => reader.Read(C_SIBLING_INDEX_KEY))) - { + reader => reader.Read(C_SIBLING_INDEX_KEY) + )) { scene.SetSiblingIndex( - gameObjectBySourceId[objectReader.Read(C_OBJECT_ID_KEY)].transform, - objectReader.Read(C_SIBLING_INDEX_KEY)); + gameObjectBySourceID[objectReader.Read(C_OBJECT_ID_KEY)].transform, + objectReader.Read(C_SIBLING_INDEX_KEY) + ); } } - var connectionByRootId = new Dictionary(); + var connectionByRootID = new Dictionary(); for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { SerializationReader objectReader = objectReaders[objectIndex]; if (!objectReader.Read(C_HAS_PREFAB_CONNECTION_KEY)) + { continue; - Guid serializedObjectId = objectReader.Read(C_OBJECT_ID_KEY); - Guid instanceRootId = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); - if (serializedObjectId != instanceRootId) + } + Guid serializedObjectID = objectReader.Read(C_OBJECT_ID_KEY); + Guid instanceRootID = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); + if (serializedObjectID != instanceRootID) + { continue; - if (!gameObjectBySourceId.TryGetValue(instanceRootId, out GameObject? instanceRoot)) + } + if (!gameObjectBySourceID.TryGetValue(instanceRootID, out GameObject? instanceRoot)) { throw new InvalidDataException( - $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' is outside the restored graph."); + $"Prefab instance root '{instanceRootID}' at '{objectReader.path}' is outside the restored graph." + ); } AssetObject sourceAsset = objectReader.Read(C_PREFAB_SOURCE_ASSET_KEY); - Guid sourceAssetId = objectReader.Read(C_PREFAB_SOURCE_ASSET_ID_KEY); - if (sourceAsset.identity.persistentId != sourceAssetId) + Guid sourceAssetID = objectReader.Read(C_PREFAB_SOURCE_ASSET_ID_KEY); + if (sourceAsset.identity.persistentID != sourceAssetID) { throw new InvalidDataException( - $"Prefab source token and source identity disagree at '{objectReader.path}'."); + $"Prefab source token and source identity disagree at '{objectReader.path}'." + ); } PrefabOverrideSet overrides = ReadPrefabOverrides(objectReader); @@ -320,20 +343,22 @@ internal static RestoredSceneGraph RestoreObjects( sourceAsset, objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY), objectReader.Read(C_PREFAB_IS_VARIANT_KEY), - overrides); + overrides + ); foreach (SerializationReader mappingReader in - objectReader.ReadObjectArray(C_PREFAB_COMPONENT_MAPPINGS_KEY)) - { - Guid componentSourceId = mappingReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY); - Guid componentInstanceId = mappingReader.Read(C_PREFAB_MAPPING_INSTANCE_ID_KEY); - if (!componentBySourceId.TryGetValue(componentInstanceId, out GameComponent? component)) + objectReader.ReadObjectArray(C_PREFAB_COMPONENT_MAPPINGS_KEY) + ) { + Guid componentSourceID = mappingReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY); + Guid componentInstanceID = mappingReader.Read(C_PREFAB_MAPPING_INSTANCE_ID_KEY); + if (!componentBySourceID.TryGetValue(componentInstanceID, out GameComponent? component)) { throw new InvalidDataException( - $"Prefab component mapping '{componentInstanceId}' at '{mappingReader.path}' does not resolve."); + $"Prefab component mapping '{componentInstanceID}' at '{mappingReader.path}' does not resolve." + ); } - connection.MapComponent(componentSourceId, component); + connection.MapComponent(componentSourceID, component); } - connectionByRootId.Add(instanceRootId, connection); + connectionByRootID.Add(instanceRootID, connection); instanceRoot.SetPrefabConnectionDirect(connection); } @@ -341,46 +366,53 @@ internal static RestoredSceneGraph RestoreObjects( { SerializationReader objectReader = objectReaders[objectIndex]; if (!objectReader.Read(C_HAS_PREFAB_CONNECTION_KEY)) - continue; - Guid serializedObjectId = objectReader.Read(C_OBJECT_ID_KEY); - Guid instanceRootId = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); - if (!gameObjectBySourceId.TryGetValue(instanceRootId, out GameObject? instanceRoot) || - !connectionByRootId.TryGetValue(instanceRootId, out PrefabConnectionRecord? connection)) { + continue; + } + Guid serializedObjectID = objectReader.Read(C_OBJECT_ID_KEY); + Guid instanceRootID = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); + if (!gameObjectBySourceID.TryGetValue(instanceRootID, out GameObject? instanceRoot) + || !connectionByRootID.TryGetValue(instanceRootID, out PrefabConnectionRecord? connection) + ) { throw new InvalidDataException( - $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' has no connection record."); - } - GameObject gameObject = gameObjectBySourceId[serializedObjectId]; - Guid prefabSourceObjectId = objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY); - connection.MapObject(prefabSourceObjectId, gameObject); - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - connection.sourceAsset.identity.persistentId, - prefabSourceObjectId, - instanceRoot, - ReferenceEquals(gameObject, instanceRoot), - connection.isVariant, - connection.sourceAsset.isMissing, - connection.overrides.count, - connection.overrides.orphanedCount, - connection.sourceAsset)); - } - - foreach (GameObject root in gameObjectBySourceId.Values.Where( - static candidate => candidate.transform.parent is null)) - { + $"Prefab instance root '{instanceRootID}' at '{objectReader.path}' has no connection record." + ); + } + GameObject gameObject = gameObjectBySourceID[serializedObjectID]; + Guid prefabSourceObjectID = objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY); + connection.MapObject(prefabSourceObjectID, gameObject); + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + connection.sourceAsset.identity.persistentID, + prefabSourceObjectID, + instanceRoot, + ReferenceEquals(gameObject, instanceRoot), + connection.isVariant, + connection.sourceAsset.isMissing, + connection.overrides.count, + connection.overrides.orphanedCount, + connection.sourceAsset + ) + ); + } + + foreach (GameObject root in gameObjectBySourceID.Values.Where( + static candidate => candidate.transform.parent is null + )) { scene.RecomputeActiveSubtree(root); } return new RestoredSceneGraph( - gameObjectBySourceId, - componentBySourceId, + gameObjectBySourceID, + componentBySourceID, componentRestores, missingPlaceholders, - missingReferenceAliases); + missingReferenceAliases + ); } internal static void ValidateScene(SerializationReader reader) { - EnsurePersistentId(reader.Read(C_SCENE_ID_KEY), $"{reader.path}.{C_SCENE_ID_KEY}"); + EnsurePersistentID(reader.Read(C_SCENE_ID_KEY), $"{reader.path}.{C_SCENE_ID_KEY}"); _ = reader.Read(C_NAME_KEY); ValidateMissingReferenceAliases(reader); ValidateObjects(reader.ReadObjectArray(C_OBJECTS_KEY)); @@ -390,33 +422,31 @@ internal static void ValidateScene(SerializationReader reader) internal static void WriteSystems( SerializationWriter writer, IReadOnlyCollection systems, - IReadOnlyDictionary sourceIds - ) { - writer.WriteObjectArray(C_SYSTEMS_KEY, systems, ( - systemWriter, - system - ) => - { - systemWriter.Write(C_SYSTEM_ID_KEY, GetSourceId(sourceIds, system)); + IReadOnlyDictionary sourceIDs + ) => writer.WriteObjectArray(C_SYSTEMS_KEY, systems, ( + systemWriter, + system + ) => + { + systemWriter.Write(C_SYSTEM_ID_KEY, GetSourceID(sourceIDs, system)); if (system is MissingGameSystem missing) { - systemWriter.Write(C_STABLE_TYPE_ID_KEY, missing.missingType.stableId); + systemWriter.Write(C_STABLE_TYPE_ID_KEY, missing.missingType.stableID); systemWriter.Write(C_TYPE_NAME_KEY, missing.missingTypeName); systemWriter.Write(C_STATE_KEY, missing.CaptureSerializedState()); WriteStateDependencies(systemWriter, missing.dependencies); return; } - systemWriter.Write(C_STABLE_TYPE_ID_KEY, systemWriter.typeSnapshot.GetTypeRef(system.GetType()).stableId); + systemWriter.Write(C_STABLE_TYPE_ID_KEY, systemWriter.typeSnapshot.GetTypeRef(system.GetType()).stableID); systemWriter.Write(C_TYPE_NAME_KEY, system.GetType().FullName ?? system.GetType().Name); AssetDependency[] dependencies = WriteState(systemWriter, system); WriteStateDependencies(systemWriter, dependencies); }); - } internal static IReadOnlyList<(GameSystem system, byte[] state)> CreateSystems( GameScene scene, IReadOnlyList systemReaders, - bool preservePersistentIds, + bool preservePersistentIDs, SceneGraphReferenceMap references, ICollection? missingPlaceholders = null ) { @@ -424,30 +454,28 @@ IReadOnlyDictionary sourceIds var result = new List<(GameSystem, byte[])>(systemReaders.Count); foreach (SerializationReader systemReader in systemReaders) { - Guid sourceId = systemReader.Read(C_SYSTEM_ID_KEY); - Guid stableTypeId = systemReader.Read(C_STABLE_TYPE_ID_KEY); + Guid sourceID = systemReader.Read(C_SYSTEM_ID_KEY); + Guid stableTypeID = systemReader.Read(C_STABLE_TYPE_ID_KEY); byte[] state = systemReader.Read(C_STATE_KEY); AssetDependency[] dependencies = ReadStateDependencies(systemReader); GameSystem system; - if (!TryResolveSystemType(stableTypeId, systemReader.context, out Type? systemType) || systemType is null) + if (!TryResolveSystemType(stableTypeID, systemReader.context, out Type? systemType) || systemType is null) { system = scene.AddMissingSystem( - new TypeRef(stableTypeId), - systemReader.Read(C_TYPE_NAME_KEY), - state, - preservePersistentIds ? sourceId : null, - dependencies); + new TypeRef(stableTypeID), + systemReader.Read(C_TYPE_NAME_KEY), + state, + preservePersistentIDs ? sourceID : null, + dependencies + ); missingPlaceholders?.Add(system); } else { - system = scene.AddSystem( - systemType, - preservePersistentIds ? sourceId : null, - invokeReset: false); + system = scene.AddSystem(systemType, preservePersistentIDs ? sourceID : null, invokeReset: false); result.Add((system, state)); } - references.Register(sourceId, system); + references.Register(sourceID, system); } return result; } @@ -455,26 +483,7 @@ IReadOnlyDictionary sourceIds internal static void RestoreMissingReferenceAliases( RestoredSceneGraph graph, SceneGraphReferenceMap references - ) - => RestoreMissingReferenceAliases(graph.missingReferenceAliases, references, graph.missingPlaceholders); - - private static void ValidateSystems(IReadOnlyList systemReaders) - { - var identities = new HashSet(); - foreach (SerializationReader systemReader in systemReaders) - { - Guid systemId = systemReader.Read(C_SYSTEM_ID_KEY); - EnsurePersistentId(systemId, $"{systemReader.path}.{C_SYSTEM_ID_KEY}"); - if (!identities.Add(systemId)) - throw new InvalidDataException($"Duplicate GameSystem identity '{systemId}' at '{systemReader.path}'."); - Guid stableTypeId = systemReader.Read(C_STABLE_TYPE_ID_KEY); - EnsurePersistentId(stableTypeId, $"{systemReader.path}.{C_STABLE_TYPE_ID_KEY}"); - _ = TryResolveSystemType(stableTypeId, systemReader.context, out _); - EnsureTypeName(systemReader.Read(C_TYPE_NAME_KEY), systemReader.path); - _ = systemReader.Read(C_STATE_KEY); - _ = ReadStateDependencies(systemReader); - } - } + ) => RestoreMissingReferenceAliases(graph.missingReferenceAliases, references, graph.missingPlaceholders); internal static void ReconcilePrefabConnections( GameScene scene, @@ -485,56 +494,39 @@ internal static void ReconcilePrefabConnections( ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(context); IEnumerable candidates = restoredRoot is null - ? scene.GetOwnedObjects() - : EnumerateRestoredObjects(restoredRoot, includeRestoredRoot); + ? scene.GetOwnedObjects() + : EnumerateRestoredObjects(restoredRoot, includeRestoredRoot); GameObject[] roots = candidates - .Where(gameObject => - gameObject.prefabInstance?.isRoot == true && - gameObject.prefabConnection is not null) + .Where(gameObject => gameObject.prefabInstance?.isRoot == true && gameObject.prefabConnection is not null) .ToArray(); for (int i = 0; i < roots.Length; i++) { if (!roots[i].isRuntimeValid || roots[i].prefabConnection is null) + { continue; + } PrefabOverrideProcessor.Reconcile(roots[i].prefabConnection!, roots[i], context); } } - private static IEnumerable EnumerateRestoredObjects( - GameObject root, - bool includeRoot - ) { - var pending = new Stack(); - if (includeRoot) - pending.Push(root.transform); - else - { - foreach (Transform child in root.transform.children) - pending.Push(child); - } - while (pending.Count != 0) - { - Transform current = pending.Pop(); - yield return current.gameObject; - foreach (Transform child in current.children) - pending.Push(child); - } - } - internal static void ValidateObjects(IReadOnlyList objectReaders) { - var objectIds = new HashSet(); - var componentIds = new HashSet(); + var objectIDs = new HashSet(); + var componentIDs = new HashSet(); for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { SerializationReader objectReader = objectReaders[objectIndex]; - Guid objectId = objectReader.Read(C_OBJECT_ID_KEY); - EnsurePersistentId(objectId, $"{objectReader.path}.{C_OBJECT_ID_KEY}"); - if (!objectIds.Add(objectId)) - throw new InvalidDataException($"Duplicate GameObject local identity '{objectId}' at '{objectReader.path}'."); + Guid objectID = objectReader.Read(C_OBJECT_ID_KEY); + EnsurePersistentID(objectID, $"{objectReader.path}.{C_OBJECT_ID_KEY}"); + if (!objectIDs.Add(objectID)) + { + throw new InvalidDataException($"Duplicate GameObject local identity '{objectID}' at '{objectReader.path}'."); + } _ = objectReader.Read(C_NAME_KEY); if (objectReader.Contains(C_TAG_KEY)) + { _ = GameObject.NormalizeTag(objectReader.Read(C_TAG_KEY)); + } _ = objectReader.Read(C_ACTIVE_SELF_KEY); _ = objectReader.Read(C_PARENT_ID_KEY); _ = objectReader.Read(C_SIBLING_INDEX_KEY); @@ -543,23 +535,25 @@ internal static void ValidateObjects(IReadOnlyList objectRe { if (!objectReader.Contains(C_PREFAB_SOURCE_ASSET_KEY)) { - throw new InvalidDataException( - $"Prefab source token is missing at '{objectReader.path}'."); + throw new InvalidDataException($"Prefab source token is missing at '{objectReader.path}'."); } - EnsurePersistentId( + EnsurePersistentID( objectReader.Read(C_PREFAB_SOURCE_ASSET_ID_KEY), - $"{objectReader.path}.{C_PREFAB_SOURCE_ASSET_ID_KEY}"); - EnsurePersistentId( + $"{objectReader.path}.{C_PREFAB_SOURCE_ASSET_ID_KEY}" + ); + EnsurePersistentID( objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY), - $"{objectReader.path}.{C_PREFAB_SOURCE_OBJECT_ID_KEY}"); - EnsurePersistentId( + $"{objectReader.path}.{C_PREFAB_SOURCE_OBJECT_ID_KEY}" + ); + EnsurePersistentID( objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY), - $"{objectReader.path}.{C_PREFAB_INSTANCE_ROOT_ID_KEY}"); + $"{objectReader.path}.{C_PREFAB_INSTANCE_ROOT_ID_KEY}" + ); _ = objectReader.Read(C_PREFAB_IS_VARIANT_KEY); _ = objectReader.Read(C_PREFAB_IS_MISSING_KEY); _ = objectReader.Read(C_PREFAB_OVERRIDE_COUNT_KEY); _ = objectReader.Read(C_PREFAB_ORPHANED_OVERRIDE_COUNT_KEY); - if (objectId == objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY)) + if (objectID == objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY)) { _ = objectReader.ReadObjectArray(C_PREFAB_COMPONENT_MAPPINGS_KEY); _ = objectReader.ReadObjectArray(C_PREFAB_PROPERTY_OVERRIDES_KEY); @@ -576,15 +570,19 @@ internal static void ValidateObjects(IReadOnlyList objectRe for (int componentIndex = 0; componentIndex < componentReaders.Count; componentIndex++) { SerializationReader componentReader = componentReaders[componentIndex]; - Guid componentId = componentReader.Read(C_COMPONENT_ID_KEY); - EnsurePersistentId(componentId, $"{componentReader.path}.{C_COMPONENT_ID_KEY}"); - if (!componentIds.Add(componentId)) - throw new InvalidDataException($"Duplicate GameComponent local identity '{componentId}' at '{componentReader.path}'."); - Guid stableTypeId = componentReader.Read(C_STABLE_TYPE_ID_KEY); - EnsurePersistentId(stableTypeId, $"{componentReader.path}.{C_STABLE_TYPE_ID_KEY}"); - if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) && - componentType == typeof(Transform)) + Guid componentID = componentReader.Read(C_COMPONENT_ID_KEY); + EnsurePersistentID(componentID, $"{componentReader.path}.{C_COMPONENT_ID_KEY}"); + if (!componentIDs.Add(componentID)) + { + throw new InvalidDataException($"Duplicate GameComponent local identity '{componentID}' at '{componentReader.path}'."); + } + Guid stableTypeID = componentReader.Read(C_STABLE_TYPE_ID_KEY); + EnsurePersistentID(stableTypeID, $"{componentReader.path}.{C_STABLE_TYPE_ID_KEY}"); + if (TryResolveComponentType(stableTypeID, componentReader.context, out Type? componentType) + && componentType == typeof(Transform) + ) { transformCount++; + } EnsureTypeName(componentReader.Read(C_TYPE_NAME_KEY), componentReader.path); _ = componentReader.Read(C_STATE_KEY); _ = ReadStateDependencies(componentReader); @@ -593,35 +591,114 @@ internal static void ValidateObjects(IReadOnlyList objectRe if (transformCount != 1) { throw new InvalidDataException( - $"Scene graph object '{objectId}' must contain exactly one Transform, but found '{transformCount}'."); + $"Scene graph object '{objectID}' must contain exactly one Transform, but found '{transformCount}'." + ); } } for (int objectIndex = 0; objectIndex < objectReaders.Count; objectIndex++) { - Guid parentId = objectReaders[objectIndex].Read(C_PARENT_ID_KEY); - if (parentId != Guid.Empty && !objectIds.Contains(parentId)) + Guid parentID = objectReaders[objectIndex].Read(C_PARENT_ID_KEY); + if (parentID != Guid.Empty && !objectIDs.Contains(parentID)) { throw new InvalidDataException( - $"Parent object '{parentId}' at '{objectReaders[objectIndex].path}' is outside the serialized boundary."); + $"Parent object '{parentID}' at '{objectReaders[objectIndex].path}' is outside the serialized boundary." + ); + } + } + } + + internal static IReadOnlyList> ReadMissingReferenceAliases(SerializationReader rootReader) + { + Guid[] aliases = rootReader.Read(C_MISSING_REFERENCE_SOURCE_IDS_KEY); + Guid[] targets = rootReader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); + var result = new KeyValuePair[aliases.Length]; + for (int i = 0; i < aliases.Length; i++) + { + result[i] = new KeyValuePair(aliases[i], targets[i]); + } + return result; + } + + internal static void ValidateMissingReferenceAliases(SerializationReader reader) + { + Guid[] aliases = reader.Read(C_MISSING_REFERENCE_SOURCE_IDS_KEY); + Guid[] targets = reader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); + if (aliases.Length != targets.Length) + { + throw new InvalidDataException($"Missing scene reference alias arrays disagree at '{reader.path}'."); + } + if (aliases.Any(static value => value == Guid.Empty) || targets.Any(static value => value == Guid.Empty)) + { + throw new InvalidDataException($"Missing scene reference aliases contain an empty identity at '{reader.path}'."); + } + if (aliases.Distinct().Count() != aliases.Length) + { + throw new InvalidDataException($"Missing scene reference aliases contain duplicates at '{reader.path}'."); + } + } + + private static void ValidateSystems(IReadOnlyList systemReaders) + { + var identities = new HashSet(); + foreach (SerializationReader systemReader in systemReaders) + { + Guid systemID = systemReader.Read(C_SYSTEM_ID_KEY); + EnsurePersistentID(systemID, $"{systemReader.path}.{C_SYSTEM_ID_KEY}"); + if (!identities.Add(systemID)) + { + throw new InvalidDataException($"Duplicate GameSystem identity '{systemID}' at '{systemReader.path}'."); } + Guid stableTypeID = systemReader.Read(C_STABLE_TYPE_ID_KEY); + EnsurePersistentID(stableTypeID, $"{systemReader.path}.{C_STABLE_TYPE_ID_KEY}"); + _ = TryResolveSystemType(stableTypeID, systemReader.context, out _); + EnsureTypeName(systemReader.Read(C_TYPE_NAME_KEY), systemReader.path); + _ = systemReader.Read(C_STATE_KEY); + _ = ReadStateDependencies(systemReader); } } - private static Guid GetSourceId( - IReadOnlyDictionary sourceIds, + private static IEnumerable EnumerateRestoredObjects( + GameObject root, + bool includeRoot + ) { + var pending = new Stack(); + if (includeRoot) + { + pending.Push(root.transform); + } + else + { + foreach (Transform child in root.transform.children) + { + pending.Push(child); + } + } + while (pending.Count != 0) + { + Transform current = pending.Pop(); + yield return current.gameObject; + foreach (Transform child in current.children) + { + pending.Push(child); + } + } + } + + private static Guid GetSourceID( + IReadOnlyDictionary sourceIDs, EngineObject engineObject - ) - => sourceIds.TryGetValue(engineObject, out Guid sourceId) - ? sourceId - : throw new InvalidOperationException( - $"Engine object '{engineObject.identity.persistentId}' has no source-local identity."); + ) => sourceIDs.TryGetValue(engineObject, out Guid sourceID) + ? sourceID + : throw new InvalidOperationException( + $"Engine object '{engineObject.identity.persistentID}' has no source-local identity." + ); private static void WriteMissingReferenceAliases( SerializationWriter writer, - IReadOnlyDictionary sourceIds + IReadOnlyDictionary sourceIDs ) { - EngineObject[] missing = sourceIds.Keys + EngineObject[] missing = sourceIDs.Keys .Where(static engineObject => engineObject is MissingGameComponent or MissingGameSystem) .ToArray(); if (missing.Length == 0) @@ -631,14 +708,17 @@ IReadOnlyDictionary sourceIds return; } - var targetByPersistentId = sourceIds.Keys.ToDictionary( - static engineObject => engineObject.identity.persistentId, - engineObject => sourceIds[engineObject]); + Dictionary targetByPersistentID = sourceIDs.Keys.ToDictionary( + static engineObject => engineObject.identity.persistentID, + engineObject => sourceIDs[engineObject] + ); var aliases = new Dictionary(); - foreach ((Guid persistentId, Guid sourceId) in targetByPersistentId) + foreach ((Guid persistentID, Guid sourceID) in targetByPersistentID) { - if (persistentId != sourceId) - aliases[persistentId] = sourceId; + if (persistentID != sourceID) + { + aliases[persistentID] = sourceID; + } } for (int i = 0; i < missing.Length; i++) { @@ -648,12 +728,12 @@ IReadOnlyDictionary sourceIds MissingGameSystem system => system.referenceAliases, _ => throw new InvalidOperationException("Unknown missing scene element.") }; - foreach ((Guid alias, Guid runtimePersistentId) in retained) + foreach ((Guid alias, Guid runtimePersistentID) in retained) { - if (targetByPersistentId.TryGetValue(runtimePersistentId, out Guid targetSourceId) && - alias != targetSourceId) - { - aliases[alias] = targetSourceId; + if (targetByPersistentID.TryGetValue(runtimePersistentID, out Guid targetSourceID) + && alias != targetSourceID + ) { + aliases[alias] = targetSourceID; } } } @@ -664,54 +744,36 @@ IReadOnlyDictionary sourceIds writer.Write(C_MISSING_REFERENCE_TARGET_IDS_KEY, ordered.Select(static pair => pair.Value).ToArray()); } - internal static IReadOnlyList> ReadMissingReferenceAliases(SerializationReader rootReader) - { - Guid[] aliases = rootReader.Read(C_MISSING_REFERENCE_SOURCE_IDS_KEY); - Guid[] targets = rootReader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); - var result = new KeyValuePair[aliases.Length]; - for (int i = 0; i < aliases.Length; i++) - result[i] = new KeyValuePair(aliases[i], targets[i]); - return result; - } - private static void RestoreMissingReferenceAliases( IReadOnlyList> aliases, SceneGraphReferenceMap references, IReadOnlyList missingPlaceholders ) { Dictionary retained = references.CaptureRemappedAliases(); - foreach ((Guid alias, Guid targetSourceId) in aliases) + foreach ((Guid alias, Guid targetSourceID) in aliases) { - EngineObject target = references.GetRegistered(targetSourceId); + EngineObject target = references.GetRegistered(targetSourceID); references.Register(alias, target); - retained[alias] = target.identity.persistentId; + retained[alias] = target.identity.persistentID; } for (int i = 0; i < missingPlaceholders.Count; i++) { if (missingPlaceholders[i] is MissingGameComponent component) + { component.SetReferenceAliases(retained); + } else if (missingPlaceholders[i] is MissingGameSystem system) + { system.SetReferenceAliases(retained); + } } } - internal static void ValidateMissingReferenceAliases(SerializationReader reader) - { - Guid[] aliases = reader.Read(C_MISSING_REFERENCE_SOURCE_IDS_KEY); - Guid[] targets = reader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); - if (aliases.Length != targets.Length) - throw new InvalidDataException($"Missing scene reference alias arrays disagree at '{reader.path}'."); - if (aliases.Any(static value => value == Guid.Empty) || targets.Any(static value => value == Guid.Empty)) - throw new InvalidDataException($"Missing scene reference aliases contain an empty identity at '{reader.path}'."); - if (aliases.Distinct().Count() != aliases.Length) - throw new InvalidDataException($"Missing scene reference aliases contain duplicates at '{reader.path}'."); - } - private static void WritePrefabConnection( SerializationWriter writer, PrefabConnectionRecord connection, PrefabOverrideSet overrides, - IReadOnlyDictionary serializedIds, + IReadOnlyDictionary serializedIDs, GameScene scene ) { KeyValuePair[] liveComponentMappings = connection.componentIdentities @@ -727,8 +789,9 @@ GameScene scene { GameComponent component = scene.FindComponent(pair.Value)!; mappingWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, pair.Key); - mappingWriter.Write(C_PREFAB_MAPPING_INSTANCE_ID_KEY, GetSourceId(serializedIds, component)); - }); + mappingWriter.Write(C_PREFAB_MAPPING_INSTANCE_ID_KEY, GetSourceID(serializedIDs, component)); + } + ); writer.WriteObjectArray( C_PREFAB_PROPERTY_OVERRIDES_KEY, overrides.properties, @@ -737,11 +800,12 @@ GameScene scene property ) => { - overrideWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, property.sourceComponentId); + overrideWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, property.sourceComponentID); overrideWriter.Write(C_PREFAB_PROPERTY_NAME_KEY, property.propertyName); overrideWriter.Write(C_PREFAB_PROPERTY_VALUE_KEY, property.value); overrideWriter.Write(C_PREFAB_OVERRIDE_ORPHANED_KEY, property.isOrphaned); - }); + } + ); writer.WriteObjectArray( C_PREFAB_STRUCTURE_OVERRIDES_KEY, overrides.structures, @@ -750,10 +814,11 @@ GameScene scene structure ) => { - overrideWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, structure.sourceObjectId); + overrideWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, structure.sourceObjectID); overrideWriter.Write(C_PREFAB_STRUCTURE_KIND_KEY, (int)structure.kind); overrideWriter.Write(C_PREFAB_OVERRIDE_ORPHANED_KEY, structure.isOrphaned); - }); + } + ); writer.Write(C_PREFAB_REMOVED_OBJECTS_KEY, overrides.removedObjects.ToArray()); writer.Write(C_PREFAB_REMOVED_COMPONENTS_KEY, overrides.removedComponents.ToArray()); writer.Write(C_PREFAB_ADDED_OBJECTS_KEY, overrides.addedObjects.ToArray()); @@ -764,66 +829,82 @@ private static PrefabOverrideSet ReadPrefabOverrides(SerializationReader reader) { var result = new PrefabOverrideSet(); foreach (SerializationReader propertyReader in - reader.ReadObjectArray(C_PREFAB_PROPERTY_OVERRIDES_KEY)) - { - result.SetProperty(new PrefabPropertyOverride( - propertyReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), - propertyReader.Read(C_PREFAB_PROPERTY_NAME_KEY), - propertyReader.Read(C_PREFAB_PROPERTY_VALUE_KEY), - propertyReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY))); + reader.ReadObjectArray(C_PREFAB_PROPERTY_OVERRIDES_KEY) + ) { + result.SetProperty( + new PrefabPropertyOverride( + propertyReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), + propertyReader.Read(C_PREFAB_PROPERTY_NAME_KEY), + propertyReader.Read(C_PREFAB_PROPERTY_VALUE_KEY), + propertyReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY) + ) + ); } foreach (SerializationReader structureReader in - reader.ReadObjectArray(C_PREFAB_STRUCTURE_OVERRIDES_KEY)) - { + reader.ReadObjectArray(C_PREFAB_STRUCTURE_OVERRIDES_KEY) + ) { result.SetStructure( structureReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), (PrefabObjectOverrideKind)structureReader.Read(C_PREFAB_STRUCTURE_KIND_KEY), - structureReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY)); - } - foreach (Guid sourceId in reader.Read(C_PREFAB_REMOVED_OBJECTS_KEY)) - result.MarkObjectRemoved(sourceId); - foreach (Guid sourceId in reader.Read(C_PREFAB_REMOVED_COMPONENTS_KEY)) - result.MarkComponentRemoved(sourceId); - foreach (Guid instanceId in reader.Read(C_PREFAB_ADDED_OBJECTS_KEY)) - result.MarkObjectAdded(instanceId); - foreach (Guid instanceId in reader.Read(C_PREFAB_ADDED_COMPONENTS_KEY)) - result.MarkComponentAdded(instanceId); + structureReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY) + ); + } + foreach (Guid sourceID in reader.Read(C_PREFAB_REMOVED_OBJECTS_KEY)) + { + result.MarkObjectRemoved(sourceID); + } + foreach (Guid sourceID in reader.Read(C_PREFAB_REMOVED_COMPONENTS_KEY)) + { + result.MarkComponentRemoved(sourceID); + } + foreach (Guid instanceID in reader.Read(C_PREFAB_ADDED_OBJECTS_KEY)) + { + result.MarkObjectAdded(instanceID); + } + foreach (Guid instanceID in reader.Read(C_PREFAB_ADDED_COMPONENTS_KEY)) + { + result.MarkComponentAdded(instanceID); + } return result; } private static bool IsTransform(SerializationReader reader) - => TryResolveComponentType( - reader.Read(C_STABLE_TYPE_ID_KEY), - reader.context, - out Type? type) && - type == typeof(Transform); + => TryResolveComponentType(reader.Read(C_STABLE_TYPE_ID_KEY), reader.context, out Type? type) + && type == typeof(Transform); private static bool TryResolveComponentType( - Guid stableTypeId, + Guid stableTypeID, SerializationContext context, out Type? componentType ) { - if (!TryResolve(new TypeRef(stableTypeId), context, out componentType)) + if (!TryResolve(new TypeRef(stableTypeID), context, out componentType)) + { return false; + } Type resolved = componentType!; if (!typeof(GameComponent).IsAssignableFrom(resolved) || resolved.IsAbstract) { throw new InvalidDataException( - $"Stable type id '{stableTypeId}' resolves to invalid component type '{resolved.FullName}'."); + $"Stable type id '{stableTypeID}' resolves to invalid component type '{resolved.FullName}'." + ); } return true; } private static bool TryResolveSystemType( - Guid stableTypeId, + Guid stableTypeID, SerializationContext context, out Type? systemType ) { - if (!TryResolve(new TypeRef(stableTypeId), context, out systemType)) + if (!TryResolve(new TypeRef(stableTypeID), context, out systemType)) + { return false; + } Type resolved = systemType!; if (!typeof(GameSystem).IsAssignableFrom(resolved) || resolved.IsAbstract) - throw new InvalidDataException($"Stable type id '{stableTypeId}' resolves to invalid system '{resolved.FullName}'."); + { + throw new InvalidDataException($"Stable type id '{stableTypeID}' resolves to invalid system '{resolved.FullName}'."); + } return true; } @@ -831,25 +912,23 @@ private static bool TryResolve( TypeRef typeRef, SerializationContext context, out Type? type - ) { - return context.GetRequired().TryResolve(typeRef, out type); - } + ) => context.GetRequired().TryResolve(typeRef, out type); private static void WriteComponent( SerializationWriter writer, GameComponent component, - IReadOnlyDictionary sourceIds + IReadOnlyDictionary sourceIDs ) { - writer.Write(C_COMPONENT_ID_KEY, GetSourceId(sourceIds, component)); + writer.Write(C_COMPONENT_ID_KEY, GetSourceID(sourceIDs, component)); if (component is MissingGameComponent missing) { - writer.Write(C_STABLE_TYPE_ID_KEY, missing.missingType.stableId); + writer.Write(C_STABLE_TYPE_ID_KEY, missing.missingType.stableID); writer.Write(C_TYPE_NAME_KEY, missing.missingTypeName); writer.Write(C_STATE_KEY, missing.CaptureSerializedState()); WriteStateDependencies(writer, missing.dependencies); return; } - writer.Write(C_STABLE_TYPE_ID_KEY, writer.typeSnapshot.GetTypeRef(component.GetType()).stableId); + writer.Write(C_STABLE_TYPE_ID_KEY, writer.typeSnapshot.GetTypeRef(component.GetType()).stableID); writer.Write(C_TYPE_NAME_KEY, component.GetType().FullName ?? component.GetType().Name); GameObject gameObject = component.gameObject; try @@ -860,9 +939,10 @@ IReadOnlyDictionary sourceIds catch (Exception exception) { throw new InvalidOperationException( - $"Failed to serialize GameComponent '{component.GetType().FullName}' on " + - $"GameObject '{gameObject.name}' at '{writer.path}'. {exception.Message}", - exception); + $"Failed to serialize GameComponent '{component.GetType().FullName}' on " + + $"GameObject '{gameObject.name}' at '{writer.path}'. {exception.Message}", + exception + ); } } @@ -871,9 +951,9 @@ private static AssetDependency[] WriteState( ISerializable value ) { SerializationContext outerContext = writer.context; - bool includeLastKnownPaths = !outerContext.TryGet(out AssetDependencyCollection? outerDependencies) || - outerDependencies is null || - outerDependencies.includeLastKnownPaths; + bool includeLastKnownPaths = !outerContext.TryGet(out AssetDependencyCollection? outerDependencies) + || outerDependencies is null + || outerDependencies.includeLastKnownPaths; var dependencies = new AssetDependencyCollection(includeLastKnownPaths); writer.WritePropertiesData(C_STATE_KEY, value, outerContext.With(dependencies)); return dependencies.dependencies.ToArray(); @@ -895,11 +975,12 @@ IReadOnlyList dependencies { AssetDependency dependency = dependencies[index]; assets[index] = resolver.Resolve( - dependency.persistentId, - dependency.type.stableId, + dependency.persistentID, + dependency.type.stableID, dependency.lastKnownPath, typeof(AssetObject), - "scene.state.dependencies"); + "scene.state.dependencies" + ); } writer.Write(C_STATE_DEPENDENCY_ASSETS_KEY, assets); } @@ -911,25 +992,29 @@ private static AssetDependency[] ReadStateDependencies(SerializationReader reade if (dependencies.Length != assets.Length) { throw new InvalidDataException( - $"Scene state dependency descriptors and assets disagree at '{reader.path}'."); + $"Scene state dependency descriptors and assets disagree at '{reader.path}'." + ); } for (int i = 0; i < dependencies.Length; i++) { - if (dependencies[i].persistentId != assets[i].identity.persistentId) + if (dependencies[i].persistentID != assets[i].identity.persistentID) { throw new InvalidDataException( - $"Scene state dependency '{dependencies[i].persistentId}' does not match its asset token at '{reader.path}'."); + $"Scene state dependency '{dependencies[i].persistentID}' does not match its asset token at '{reader.path}'." + ); } } return dependencies; } - private static void EnsurePersistentId( - Guid persistentId, + private static void EnsurePersistentID( + Guid persistentID, string path ) { - if (persistentId == Guid.Empty) + if (persistentID == Guid.Empty) + { throw new InvalidDataException($"Persistent or local identity at '{path}' cannot be empty."); + } } private static void EnsureTypeName( @@ -937,7 +1022,8 @@ private static void EnsureTypeName( string path ) { if (string.IsNullOrWhiteSpace(typeName)) + { throw new InvalidDataException($"Scene element type name at '{path}' cannot be empty."); + } } - } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIDs.cs similarity index 82% rename from src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs rename to src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIDs.cs index df1b197e8..bf3cfa734 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIDs.cs @@ -7,63 +7,75 @@ namespace Inno.Scene; /// /// Combines frozen structural identities with systems borrowed only by the current graph write. /// -internal sealed class SceneGraphSourceIds : IReadOnlyDictionary +internal sealed class SceneGraphSourceIDs : IReadOnlyDictionary { private readonly IReadOnlyDictionary m_objects; private readonly Dictionary? m_systems; - internal SceneGraphSourceIds( + internal SceneGraphSourceIDs( IReadOnlyDictionary objects, IReadOnlyList systems ) { m_objects = objects; // Systems have a separate lifecycle owner; the structural cache must not retain them. if (systems.Count == 0) + { return; + } m_systems = new Dictionary(systems.Count, ReferenceEqualityComparer.Instance); for (int index = 0; index < systems.Count; index++) { GameSystem system = systems[index]; - m_systems.Add(system, system.identity.persistentId); + m_systems.Add(system, system.identity.persistentID); } } - /// + /// public int Count => checked(m_objects.Count + (m_systems?.Count ?? 0)); - /// + /// public IEnumerable Keys => EnumerateKeys(); - /// + /// public IEnumerable Values => EnumerateValues(); - /// + /// public Guid this[EngineObject key] => TryGetValue(key, out Guid value) ? value : throw new KeyNotFoundException(); - /// + /// public bool ContainsKey(EngineObject key) => TryGetValue(key, out _); - /// + /// public bool TryGetValue( EngineObject key, out Guid value ) { if (m_objects.TryGetValue(key, out value)) + { return true; + } if (m_systems is not null) + { return m_systems.TryGetValue(key, out value); + } value = default; return false; } - /// + /// public IEnumerator> GetEnumerator() { foreach (KeyValuePair entry in m_objects) + { yield return entry; + } if (m_systems is not null) + { foreach (KeyValuePair entry in m_systems) + { yield return entry; + } + } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -71,12 +83,16 @@ public IEnumerator> GetEnumerator() private IEnumerable EnumerateKeys() { foreach (KeyValuePair entry in this) + { yield return entry.Key; + } } private IEnumerable EnumerateValues() { foreach (KeyValuePair entry in this) + { yield return entry.Value; + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs index 1b98620ee..afa625b62 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs @@ -16,66 +16,81 @@ internal sealed class ScenePropertyReferenceScope : SceneReferenceScope internal ScenePropertyReferenceScope( GameScene scene, IReadOnlyDictionary? aliases = null - ) : base(scene) { + ) : base(scene) + { m_identities = IdentityAllocator.current; - if (scene.identity.runtimeIdentity is not { } owner || owner.domainId != m_identities.domainId || - scene.isDestroyed || !ReferenceEquals(m_identities.Get(owner), scene)) + if (scene.identity.runtimeIdentity is not { } owner || owner.domainID != m_identities.domainID + || scene.isDestroyed || !ReferenceEquals(m_identities.Get(owner), scene) + ) { throw new InvalidOperationException("Scene property serialization requires its current owning identity domain."); + } m_sceneIdentity = owner; if (aliases is not { Count: > 0 }) + { return; + } m_aliases = new Dictionary(aliases.Count); - foreach ((Guid alias, Guid targetId) in aliases) + foreach ((Guid alias, Guid targetID) in aliases) { - EngineObject? target = m_identities.Get(targetId); + EngineObject? target = m_identities.Get(targetID); if (target is null || !BelongsToScene(target)) - throw new InvalidOperationException($"Scene reference alias '{alias}' targets missing object '{targetId}'."); + { + throw new InvalidOperationException($"Scene reference alias '{alias}' targets missing object '{targetID}'."); + } EngineObject? previous = m_identities.Get(alias); if (previous is not null && BelongsToScene(previous) && !ReferenceEquals(previous, target)) + { throw new InvalidOperationException($"Duplicate scene graph local identity '{alias}'."); - m_aliases.Add(alias, targetId); + } + m_aliases.Add(alias, targetID); } } - /// /// /// The current allocator must still own the Scene and the exact registered object in that Scene. /// - protected override bool TryGetSourceId( + /// + protected override bool TryGetSourceID( EngineObject engineObject, - out Guid sourceId + out Guid sourceID ) { - sourceId = default; - if (!HasCurrentOwner() || engineObject.identity.runtimeIdentity is not { } identity || - identity.domainId != m_identities.domainId || !ReferenceEquals(m_identities.Get(identity), engineObject) || - !BelongsToScene(engineObject)) + sourceID = default; + if (!HasCurrentOwner() || engineObject.identity.runtimeIdentity is not { } identity + || identity.domainID != m_identities.domainID || !ReferenceEquals(m_identities.Get(identity), engineObject) + || !BelongsToScene(engineObject) + ) { return false; - sourceId = engineObject.identity.persistentId; + } + sourceID = engineObject.identity.persistentID; return true; } - /// /// /// Neutral aliases resolve to current Core identities; destroyed or foreign Scene objects are rejected. /// + /// protected override bool TryResolve( - Guid sourceId, + Guid sourceID, out EngineObject? engineObject ) { engineObject = null; if (!HasCurrentOwner()) + { return false; - Guid target = m_aliases is not null && m_aliases.TryGetValue(sourceId, out Guid alias) ? alias : sourceId; + } + Guid target = m_aliases is not null && m_aliases.TryGetValue(sourceID, out Guid alias) ? alias : sourceID; EngineObject? candidate = m_identities.Get(target); if (candidate is null || !BelongsToScene(candidate)) + { return false; + } engineObject = candidate; return true; } private bool HasCurrentOwner() - => IdentityAllocator.hasCurrent && ReferenceEquals(IdentityAllocator.current, m_identities) && - !scene.isDestroyed && ReferenceEquals(m_identities.Get(m_sceneIdentity), scene); + => IdentityAllocator.hasCurrent && ReferenceEquals(IdentityAllocator.current, m_identities) + && !scene.isDestroyed && ReferenceEquals(m_identities.Get(m_sceneIdentity), scene); private bool BelongsToScene(EngineObject value) => !value.isDestroyed && value switch diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs index 91ca42435..d7534a574 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs @@ -8,7 +8,7 @@ namespace Inno.Scene; /// internal abstract class SceneReferenceScope { - private static readonly ExecutionSlot C_CURRENT = new("scene graph references"); + private static readonly ExecutionSlot CURRENT = new("scene graph references"); private readonly GameObject? m_captureRoot; /// @@ -27,48 +27,83 @@ protected SceneReferenceScope( GameScene scene, GameObject? captureRoot = null ) { - this.scene = scene ?? throw new ArgumentNullException(nameof(scene)); + ArgumentNullException.ThrowIfNull(scene); + this.scene = scene; m_captureRoot = captureRoot; } - internal static SceneReferenceScope current => C_CURRENT.current; /// /// Gets the Scene that owns the references admitted by this boundary. /// protected GameScene scene { get; } - internal static bool TryGetCurrent(out SceneReferenceScope? references) - => C_CURRENT.TryGet(out references); + internal static SceneReferenceScope current => CURRENT.current; - internal static IDisposable Suspend() => C_CURRENT.Suspend(); + /// + /// Looks up the identifier assigned to an object by this reference boundary. + /// + /// + /// The non-null object being captured within the synchronous owner operation. + /// + /// + /// The admitted identifier, or the empty GUID when the boundary rejects the object. + /// + /// + /// True when the boundary maps the object; false when it lies outside the admitted scope. + /// + protected abstract bool TryGetSourceID( + EngineObject engineObject, + out Guid sourceID + ); + + /// + /// Resolves one identifier within the frozen or current owner boundary. + /// + /// + /// The reference identifier from the current serialized payload. + /// + /// + /// The mapped object, or null when the boundary cannot resolve the identifier. + /// + /// + /// True when the boundary contains the identifier; false without publishing a replacement object. + /// + protected abstract bool TryResolve( + Guid sourceID, + out EngineObject? engineObject + ); - internal IDisposable Enter() => C_CURRENT.Enter(this, threadAffine: true); + internal IDisposable Enter() => CURRENT.Enter(this, threadAffine: true); internal EngineReferenceToken Capture( EngineObject engineObject, string path ) { ArgumentNullException.ThrowIfNull(engineObject); - if (engineObject.isDestroyed || !TryGetSourceId(engineObject, out Guid sourceId)) + if (engineObject.isDestroyed || !TryGetSourceID(engineObject, out Guid sourceID)) { throw new InvalidOperationException( - $"Reference to '{engineObject.GetType().FullName}' with identity " + - $"'{engineObject.identity.persistentId}' at '{path}' is outside the serialized graph boundary" + - (m_captureRoot is null - ? "." - : $" rooted at GameObject '{m_captureRoot.name}' ({m_captureRoot.identity.persistentId}).")); + $"Reference to '{engineObject.GetType().FullName}' with identity " + + $"'{engineObject.identity.persistentID}' at '{path}' is outside the serialized graph boundary" + + (m_captureRoot is null + ? "." + : $" rooted at GameObject '{m_captureRoot.name}' ({m_captureRoot.identity.persistentID}).") + ); } GameScene ownerScene = engineObject switch { GameObject gameObject => gameObject.scene, GameComponent component => component.gameObject.scene, GameSystem system => system.ownerScene - ?? throw new InvalidOperationException($"Detached GameSystem reference at '{path}' cannot be serialized."), + ?? throw new InvalidOperationException($"Detached GameSystem reference at '{path}' cannot be serialized."), _ => throw new InvalidOperationException( - $"Engine object type '{engineObject.GetType().FullName}' cannot be serialized as a scene reference at '{path}'.") + $"Engine object type '{engineObject.GetType().FullName}' cannot be serialized as a scene reference at '{path}'." + ) }; if (!ReferenceEquals(ownerScene, scene)) + { throw new InvalidOperationException($"Cross-scene object reference at '{path}' cannot be serialized."); + } EngineReferenceKind kind = engineObject switch { GameObject => EngineReferenceKind.GameObject, @@ -76,7 +111,7 @@ string path GameSystem => EngineReferenceKind.GameSystem, _ => throw new InvalidOperationException($"Unsupported scene reference at '{path}'.") }; - return new EngineReferenceToken(kind, sourceId); + return new EngineReferenceToken(kind, sourceID); } internal EngineObject Resolve( @@ -84,48 +119,21 @@ internal EngineObject Resolve( Type expectedType, string path ) { - if (!TryResolve(token.sourceId, out EngineObject? engineObject) || engineObject is null) - throw new InvalidOperationException($"Scene graph reference '{token.sourceId}' at '{path}' could not be resolved."); + if (!TryResolve(token.sourceID, out EngineObject? engineObject) || engineObject is null) + { + throw new InvalidOperationException($"Scene graph reference '{token.sourceID}' at '{path}' could not be resolved."); + } if (!expectedType.IsInstanceOfType(engineObject)) { throw new InvalidOperationException( - $"Scene graph reference '{token.sourceId}' at '{path}' resolves to " + - $"'{engineObject.GetType().FullName}', expected '{expectedType.FullName}'."); + $"Scene graph reference '{token.sourceID}' at '{path}' resolves to " + + $"'{engineObject.GetType().FullName}', expected '{expectedType.FullName}'." + ); } return engineObject; } - /// - /// Looks up the identifier assigned to an object by this reference boundary. - /// - /// - /// The non-null object being captured within the synchronous owner operation. - /// - /// - /// The admitted identifier, or the empty GUID when the boundary rejects the object. - /// - /// - /// True when the boundary maps the object; false when it lies outside the admitted scope. - /// - protected abstract bool TryGetSourceId( - EngineObject engineObject, - out Guid sourceId - ); + internal static bool TryGetCurrent(out SceneReferenceScope? references) => CURRENT.TryGet(out references); - /// - /// Resolves one identifier within the frozen or current owner boundary. - /// - /// - /// The reference identifier from the current serialized payload. - /// - /// - /// The mapped object, or null when the boundary cannot resolve the identifier. - /// - /// - /// True when the boundary contains the identifier; false without publishing a replacement object. - /// - protected abstract bool TryResolve( - Guid sourceId, - out EngineObject? engineObject - ); + internal static IDisposable Suspend() => CURRENT.Suspend(); } diff --git a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs index 8870b8345..a8eb9eb13 100644 --- a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -55,11 +54,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CapturePropertyData(serializable, propertyName, context); + } } /// @@ -92,11 +95,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CapturePropertiesData(serializable, context); + } } /// @@ -123,11 +130,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CaptureProperties(serializable, context); + } } /// @@ -139,15 +150,15 @@ IAssetReferenceResolver assets /// /// Bytes produced by or . /// - /// - /// The policy applied to unavailable or mismatched current properties. - /// /// /// The serialization registry that owns the active converter generation. /// /// /// The resolver used to materialize canonical asset references in restored values. /// + /// + /// The policy applied to unavailable or mismatched current properties. + /// /// /// A summary of restored, ignored, and incompatible properties. /// @@ -168,11 +179,15 @@ public static SerializationPropertyRestoreResult RestoreProperties( ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.RestorePropertiesData(serializable, data, mode, context); + } } internal static ScenePropertyReferenceScope CreateReferences( @@ -183,7 +198,9 @@ internal static ScenePropertyReferenceScope CreateReferences( internal static GameScene ResolveScene(EngineObject target) { if (target.isDestroyed) - throw new InvalidOperationException($"Destroyed scene object '{target.identity.persistentId}' cannot be serialized."); + { + throw new InvalidOperationException($"Destroyed scene object '{target.identity.persistentID}' cannot be serialized."); + } return target switch { GameScene scene when scene.isLoaded => scene, @@ -191,8 +208,8 @@ internal static GameScene ResolveScene(EngineObject target) GameComponent component when !component.isDestroyed => component.gameObject.scene, GameSystem system when system.ownerScene is { isLoaded: true } owner => owner, _ => throw new InvalidOperationException( - $"Scene object '{target.identity.persistentId}' is not owned by a loaded scene.") + $"Scene object '{target.identity.persistentID}' is not owned by a loaded scene." + ) }; } - } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs b/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs index 098123d90..f7d81c369 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs @@ -1,13 +1,12 @@ -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.References; namespace Inno.Scene; @@ -35,58 +34,46 @@ List scenes m_scenes = scenes; } - internal IReadOnlyList retiredObjects => m_scenes - .SelectMany(static scene => scene.states) - .Where(state => m_context.IsRetired(state.activeType)) - .Select(static state => (object)state.target) - .ToArray(); + void IGenerationChange.PrepareForActivation() => PrepareForActivation(); - internal IReadOnlyList diagnostics => m_diagnostics; + void IGenerationChange.Apply() => Apply(); - internal static SceneReloadStateTransfer Capture( - SceneWorld world, - TypeCacheReloadContext context, - SerializationRegistry serialization, - IAssetReferenceResolver assets - ) { - ArgumentNullException.ThrowIfNull(world); - ArgumentNullException.ThrowIfNull(context); - ArgumentNullException.ThrowIfNull(serialization); - ArgumentNullException.ThrowIfNull(assets); - var scenes = new List(); - foreach (GameScene scene in world.loadedScenes) + void IGenerationChange.RollbackStructure() => RollbackStructure(); + + void IGenerationChange.RestorePreviousState() => RestorePreviousState(); + + void IGenerationChange.Complete() => Complete(); + + void IReferenceRecoveryParticipant.Validate(IReadOnlyList changes) + { + foreach (ReferenceRecoveryChange change in changes) { - SceneStructureSnapshot structure = scene.CaptureStructure(); - EngineObject[] engineObjects = structure.objects - .SelectMany(static entry => entry.components.Cast().Prepend(entry.gameObject)) - .Concat(scene.GetSystems()) - .ToArray(); - var sourceIds = new Dictionary(ReferenceEqualityComparer.Instance); - foreach (EngineObject target in engineObjects) - sourceIds.Add(target, target.identity.persistentId); - var references = new SceneGraphReferenceMap(scene, sourceIds); - var states = new List(); - using (references.Enter()) + ReferenceResolution resolution = change.resolution; + if (resolution.state is ReferenceResolutionState.Invalid or ReferenceResolutionState.TypeMismatch) { - foreach (GameComponent component in structure.objects.SelectMany(static entry => entry.components)) - states.Add(CaptureState(component, context.previous, serialization, assets)); - foreach (GameSystem system in scene.GetSystems()) - states.Add(CaptureState(system, context.previous, serialization, assets)); + throw new InvalidOperationException($"Recovery slot '{change.missingState.key}': {resolution.diagnostic}"); } - - ValidateMultiplicity(scene, structure, context); - scenes.Add(new SceneState(scene, engineObjects, sourceIds, states)); } - return new SceneReloadStateTransfer(context, serialization, assets, scenes); } + internal IReadOnlyList retiredObjects + => m_scenes + .SelectMany(static scene => scene.states) + .Where(state => m_context.IsRetired(state.activeType)) + .Select(static state => (object)state.target) + .ToArray(); + + internal IReadOnlyList diagnostics => m_diagnostics; + internal void PrepareForActivation() { EnsureActive(); foreach (ObjectState state in RetiredStates()) { if (state.target is ISceneLifecycleObject lifecycle) + { SceneLifecycle.DisableForReload(lifecycle); + } } } @@ -94,45 +81,49 @@ internal void Apply() { EnsureActive(); if (m_applied) + { return; + } foreach (SceneState sceneState in m_scenes) { foreach (ObjectState state in sceneState.states) { Type? replacementType = ResolveCandidateType(state, m_context); bool retired = m_context.IsRetired(state.activeType); - bool recovering = state.target is MissingGameComponent or MissingGameSystem && - replacementType is not null; + bool recovering = state.target is MissingGameComponent or MissingGameSystem + && replacementType is not null; if (!retired && !recovering) + { continue; + } Type effectiveType = replacementType ?? (state.target is GameSystem - ? typeof(MissingGameSystem) - : typeof(MissingGameComponent)); + ? typeof(MissingGameSystem) + : typeof(MissingGameComponent)); TypeRef replacementTypeRef = m_context.candidate.GetTypeRef(effectiveType); EngineObject replacement = CreateReplacement(state, effectiveType); if (replacement is not MissingGameComponent and not MissingGameSystem) + { CopyLifecycle(state.target, replacement); + } if (state.target is GameComponent previousComponent) { sceneState.scene.ReplaceComponentForReload( previousComponent, (GameComponent)replacement, - replacementTypeRef.runtimeId); + replacementTypeRef.runtimeID + ); } else { sceneState.scene.ReplaceSystemForReload( (GameSystem)state.target, (GameSystem)replacement, - replacementTypeRef.runtimeId); + replacementTypeRef.runtimeID + ); } state.currentTarget = replacement; - m_replacements.Add(new Replacement( - sceneState.scene, - state.target, - replacement, - state.activeType)); + m_replacements.Add(new Replacement(sceneState.scene, state.target, replacement, state.activeType)); } RestoreState(sceneState, useCurrentTargets: true); } @@ -142,7 +133,9 @@ internal void Apply() internal void RollbackStructure() { if (m_finished) + { return; + } for (int i = m_replacements.Count - 1; i >= 0; i--) { Replacement replacement = m_replacements[i]; @@ -151,20 +144,24 @@ internal void RollbackStructure() replacement.scene.ReplaceComponentForReload( (GameComponent)replacement.current, previousComponent, - replacement.previousType.runtimeId); + replacement.previousType.runtimeID + ); } else { replacement.scene.ReplaceSystemForReload( (GameSystem)replacement.current, (GameSystem)replacement.previous, - replacement.previousType.runtimeId); + replacement.previousType.runtimeID + ); } } foreach (SceneState sceneState in m_scenes) { foreach (ObjectState state in sceneState.states) + { state.currentTarget = state.target; + } } m_replacements.Clear(); m_applied = false; @@ -192,7 +189,9 @@ internal void RestorePreviousState() RestorePreviousLifecycleState(sceneState, ref failures); } if (failures is not null) + { throw new AggregateException("Previous scene state restoration was incomplete.", failures); + } } internal void Complete() @@ -204,9 +203,13 @@ internal void Complete() try { if (replacement.previous is GameComponent component && !component.isDestroyed) + { component.Detach(); + } else if (replacement.previous is GameSystem system && !system.isDestroyed) + { system.Detach(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -215,22 +218,27 @@ internal void Complete() catch (Exception exception) { failures.Add(exception); - m_diagnostics.Add(new SceneReloadDiagnostic( - "INNOHR0004", - DiagnosticSeverity.Error, - $"Retired scene element '{replacement.previous.GetType().FullName}' failed during cleanup: {exception.Message}", - replacement.scene.identity.persistentId, - replacement.previous.identity.persistentId, - string.Empty, - replacement.previous.GetType().FullName ?? replacement.previous.GetType().Name, - string.Empty)); + m_diagnostics.Add( + new SceneReloadDiagnostic( + "INNOHR0004", + DiagnosticSeverity.Error, + $"Retired scene element '{replacement.previous.GetType().FullName}' failed during cleanup: {exception.Message}", + replacement.scene.identity.persistentID, + replacement.previous.identity.persistentID, + string.Empty, + replacement.previous.GetType().FullName ?? replacement.previous.GetType().Name, + string.Empty + ) + ); } } m_replacements.Clear(); m_scenes.Clear(); m_finished = true; if (failures.Count > 0) + { throw new AggregateException("Retired scene elements failed cleanup after all elements were attempted.", failures); + } } internal IEnumerable CaptureRecoveryStates() @@ -239,35 +247,227 @@ internal IEnumerable CaptureRecoveryStates() { foreach (ObjectState state in sceneState.states) { - Guid elementId = state.target.identity.persistentId; + Guid elementID = state.target.identity.persistentID; yield return new SerializedMissingState( - new ReferenceKey(elementId, "element"), - new ReferenceDescriptor(SceneElementReferenceResolver.id, elementId, - state.logicalType.stableId, state.typeName), state.data); + new ReferenceKey(elementID, "element"), + new ReferenceDescriptor( + SceneElementReferenceResolver.id, + elementID, + state.logicalType.stableID, + state.typeName + ), + state.data + ); foreach (AssetDependency dependency in state.dependencies.Distinct()) { yield return new SerializedMissingState( - new ReferenceKey(elementId, $"assets/{dependency.persistentId:D}"), - new ReferenceDescriptor(AssetReferenceProtocol.id, dependency.persistentId, - dependency.type.stableId, lastKnownPath: dependency.lastKnownPath), []); + new ReferenceKey(elementID, $"assets/{dependency.persistentID:D}"), + new ReferenceDescriptor( + AssetReferenceProtocol.id, + dependency.persistentID, + dependency.type.stableID, + lastKnownPath: dependency.lastKnownPath + ), + [] + ); } } } } - void IGenerationChange.PrepareForActivation() => PrepareForActivation(); - void IGenerationChange.Apply() => Apply(); - void IGenerationChange.RollbackStructure() => RollbackStructure(); - void IGenerationChange.RestorePreviousState() => RestorePreviousState(); - void IGenerationChange.Complete() => Complete(); + internal static SceneReloadStateTransfer Capture( + SceneWorld world, + TypeCacheReloadContext context, + SerializationRegistry serialization, + IAssetReferenceResolver assets + ) { + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(assets); + List scenes = []; + foreach (GameScene scene in world.loadedScenes) + { + SceneStructureSnapshot structure = scene.CaptureStructure(); + EngineObject[] engineObjects = structure.objects + .SelectMany(static entry => entry.components.Cast().Prepend(entry.gameObject)) + .Concat(scene.GetSystems()) + .ToArray(); + var sourceIDs = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (EngineObject target in engineObjects) + { + sourceIDs.Add(target, target.identity.persistentID); + } + var references = new SceneGraphReferenceMap(scene, sourceIDs); + List states = []; + using (references.Enter()) + { + foreach (GameComponent component in structure.objects.SelectMany(static entry => entry.components)) + { + states.Add(CaptureState(component, context.previous, serialization, assets)); + } + foreach (GameSystem system in scene.GetSystems()) + { + states.Add(CaptureState(system, context.previous, serialization, assets)); + } + } - void IReferenceRecoveryParticipant.Validate(IReadOnlyList changes) + ValidateMultiplicity(scene, structure, context); + scenes.Add(new SceneState(scene, engineObjects, sourceIDs, states)); + } + return new SceneReloadStateTransfer(context, serialization, assets, scenes); + } + + private EngineObject CreateReplacement( + ObjectState state, + Type replacementType + ) { + if (replacementType == typeof(MissingGameComponent)) + { + return new MissingGameComponent(state.logicalType, state.typeName, state.data, state.dependencies); + } + if (replacementType == typeof(MissingGameSystem)) + { + return new MissingGameSystem(state.logicalType, state.typeName, state.data, state.dependencies); + } + try + { + return state.target is GameComponent + ? ComponentFactory.Create(replacementType, m_context.candidate) + : (EngineObject)m_context.candidate.CreateInstance(replacementType); + } + catch (Exception exception) + { + throw new InvalidOperationException( + $"Hot-reload replacement '{replacementType.FullName}' requires a parameterless constructor.", + exception + ); + } + } + + private void RestoreState( + SceneState sceneState, + bool useCurrentTargets + ) { + EngineObject[] currentObjects = sceneState.engineObjects + .Select(engineObject => ( + sceneState.states.FirstOrDefault(state => ReferenceEquals(state.target, engineObject)) + is ObjectState state + ? useCurrentTargets ? state.currentTarget : state.target + : engineObject + )) + .ToArray(); + var references = new SceneGraphReferenceMap(sceneState.scene); + var currentByPersistentID = new Dictionary(); + for (int i = 0; i < currentObjects.Length; i++) + { + references.Register(sceneState.engineObjects[i].identity.persistentID, currentObjects[i]); + currentByPersistentID[currentObjects[i].identity.persistentID] = currentObjects[i]; + } + foreach (ObjectState state in sceneState.states) + { + IReadOnlyDictionary? aliases = state.target switch + { + MissingGameComponent component => component.referenceAliases, + MissingGameSystem system => system.referenceAliases, + _ => null + }; + if (aliases is null) + { + continue; + } + foreach ((Guid alias, Guid targetPersistentID) in aliases) + { + if (!currentByPersistentID.TryGetValue(targetPersistentID, out EngineObject? target)) + { + throw new InvalidOperationException( + $"Missing scene state reference alias '{alias}' targets unavailable identity '{targetPersistentID}'." + ); + } + references.Register(alias, target); + } + } + List? restoreFailures = null; + using (references.Enter()) + { + foreach (ObjectState state in sceneState.states) + { + ISerializable target = (ISerializable)(useCurrentTargets ? state.currentTarget : state.target); + if (target is MissingGameComponent or MissingGameSystem) + { + continue; + } + SerializationPropertyRestoreResult result; + try + { + result = m_serialization.RestorePropertiesData( + target, + state.data, + useCurrentTargets && state.target is not MissingGameComponent and not MissingGameSystem + ? SerializationPropertyRestoreMode.CollectFailures + : SerializationPropertyRestoreMode.Strict, + AssetSerializationContext.Create(m_assets) + ); + } + catch (Exception exception) when (!useCurrentTargets && exception is not RetirementPendingException) + { + restoreFailures ??= []; + restoreFailures.Add( + new InvalidOperationException( + $"Previous state restoration failed for '{target.GetType().FullName}'.", + exception + ) + ); + continue; + } + if (!useCurrentTargets) + { + continue; + } + if (state.target is MissingGameComponent or MissingGameSystem + && (!result.success || result.ignoredCount != 0) + ) { + throw new InvalidOperationException( + $"Missing scene element '{state.target.identity.persistentID}' could not restore its complete preserved state." + ); + } + for (int i = 0; i < result.failures.Count; i++) + { + SerializationPropertyRestoreFailure failure = result.failures[i]; + string previousType = GetTypeDisplayName(failure.previousPropertyType); + string currentType = GetTypeDisplayName(failure.currentPropertyType); + m_diagnostics.Add( + new SceneReloadDiagnostic( + "INNOHR0001", + DiagnosticSeverity.Warning, + $"Hot reload skipped '{target.GetType().FullName}.{failure.name}' because " + + $"serialized type '{previousType}' is incompatible with '{currentType}'. " + + $"The new member default value was preserved. {failure.message}", + sceneState.scene.identity.persistentID, + ((EngineObject)target).identity.persistentID, + failure.name, + previousType, + currentType + ) + ); + } + } + } + if (restoreFailures is not null) + { + throw new AggregateException("One or more previous scene objects could not be restored.", restoreFailures); + } + } + + private IEnumerable RetiredStates() + => m_scenes.SelectMany(static scene => scene.states) + .Where(state => m_context.IsRetired(state.activeType)); + + private void EnsureActive() { - foreach (ReferenceRecoveryChange change in changes) + if (m_finished) { - ReferenceResolution resolution = change.resolution; - if (resolution.state is ReferenceResolutionState.Invalid or ReferenceResolutionState.TypeMismatch) - throw new InvalidOperationException($"Recovery slot '{change.missingState.key}': {resolution.diagnostic}"); + throw new InvalidOperationException("Scene hot-reload migration is already finished."); } } @@ -286,7 +486,8 @@ IAssetReferenceResolver assets missingComponent.missingType, missingComponent.missingTypeName, missingComponent.CaptureSerializedState(), - missingComponent.dependencies.ToArray()); + missingComponent.dependencies.ToArray() + ); } if (target is MissingGameSystem missingSystem) { @@ -296,19 +497,22 @@ IAssetReferenceResolver assets missingSystem.missingType, missingSystem.missingTypeName, missingSystem.CaptureSerializedState(), - missingSystem.dependencies.ToArray()); + missingSystem.dependencies.ToArray() + ); } var dependencies = new AssetDependencyCollection(); byte[] data = serialization.CapturePropertiesData( (ISerializable)target, - AssetSerializationContext.Create(assets, dependencies)); + AssetSerializationContext.Create(assets, dependencies) + ); return new ObjectState( target, activeType, activeType, target.GetType().FullName ?? target.GetType().Name, data, - dependencies.dependencies.ToArray()); + dependencies.dependencies.ToArray() + ); } private static void RestorePreviousLifecycleState( @@ -317,9 +521,9 @@ ref List? failures ) { foreach (ObjectState state in sceneState.states) { - if (state.target is not ISceneLifecycleObject lifecycle || - lifecycle.lifecycleWasEnabled == state.lifecycleWasEnabled) - { + if (state.target is not ISceneLifecycleObject lifecycle + || lifecycle.lifecycleWasEnabled == state.lifecycleWasEnabled + ) { continue; } @@ -327,9 +531,13 @@ ref List? failures try { if (state.lifecycleWasEnabled) + { lifecycle.DispatchEnable(); + } else + { lifecycle.DispatchDisable(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -338,43 +546,16 @@ ref List? failures catch (Exception exception) { failures ??= []; - failures.Add(new InvalidOperationException( - $"Lifecycle compensation failed for '{state.target.GetType().FullName}'.", - exception)); + failures.Add( + new InvalidOperationException( + $"Lifecycle compensation failed for '{state.target.GetType().FullName}'.", + exception + ) + ); } } } - private EngineObject CreateReplacement( - ObjectState state, - Type replacementType - ) { - if (replacementType == typeof(MissingGameComponent)) - return new MissingGameComponent( - state.logicalType, - state.typeName, - state.data, - state.dependencies); - if (replacementType == typeof(MissingGameSystem)) - return new MissingGameSystem( - state.logicalType, - state.typeName, - state.data, - state.dependencies); - try - { - return state.target is GameComponent - ? ComponentFactory.Create(replacementType, m_context.candidate) - : (EngineObject)m_context.candidate.CreateInstance(replacementType); - } - catch (Exception exception) - { - throw new InvalidOperationException( - $"Hot-reload replacement '{replacementType.FullName}' requires a parameterless constructor.", - exception); - } - } - private static void CopyLifecycle( EngineObject previous, EngineObject replacement @@ -408,19 +589,26 @@ TypeCacheReloadContext context { ActiveTypeInfo type = ResolveActiveType(component, context); if (!groups.TryGetValue(type.typeRef, out MultiplicityGroup? group)) + { groups.Add(type.typeRef, new MultiplicityGroup(type.displayName, type.allowsMultiple)); + } else + { group.count++; + } } foreach (MultiplicityGroup group in groups.Values) { if (group.count <= 1 || group.allowsMultiple) + { continue; + } throw new InvalidOperationException( - $"Script reload would leave GameObject '{entry.gameObject.name}' " + - $"({entry.gameObject.identity.persistentId}) with {group.count} instances of unique component " + - $"'{group.displayName}'. Remove duplicate components or restore " + - $"[{nameof(AllowMultipleComponentAttribute)}] before reloading."); + $"Script reload would leave GameObject '{entry.gameObject.name}' " + + $"({entry.gameObject.identity.persistentID}) with {group.count} instances of unique component " + + $"'{group.displayName}'. Remove duplicate components or restore " + + $"[{nameof(AllowMultipleComponentAttribute)}] before reloading." + ); } } @@ -429,18 +617,25 @@ TypeCacheReloadContext context { ActiveTypeInfo type = ResolveActiveType(system, context); if (!systemGroups.TryGetValue(type.typeRef, out MultiplicityGroup? group)) + { systemGroups.Add(type.typeRef, new MultiplicityGroup(type.displayName, type.allowsMultiple)); + } else + { group.count++; + } } foreach (MultiplicityGroup group in systemGroups.Values) { if (group.count <= 1 || group.allowsMultiple) + { continue; + } throw new InvalidOperationException( - $"Script reload would leave scene '{scene.name}' ({scene.identity.persistentId}) with " + - $"{group.count} instances of unique system '{group.displayName}'. Remove duplicate systems or restore " + - $"[{nameof(AllowMultipleSystemAttribute)}] before reloading."); + $"Script reload would leave scene '{scene.name}' ({scene.identity.persistentID}) with " + + $"{group.count} instances of unique system '{group.displayName}'. Remove duplicate systems or restore " + + $"[{nameof(AllowMultipleSystemAttribute)}] before reloading." + ); } } @@ -454,14 +649,14 @@ TypeCacheReloadContext context if (target is MissingGameComponent missingComponent) { activeType = TryResolve(missingComponent.missingType, context.candidate, out Type? recovered) - ? recovered! - : typeof(MissingGameComponent); + ? recovered! + : typeof(MissingGameComponent); } else if (target is MissingGameSystem missingSystem) { activeType = TryResolve(missingSystem.missingType, context.candidate, out Type? recovered) - ? recovered! - : typeof(MissingGameSystem); + ? recovered! + : typeof(MissingGameSystem); } else { @@ -469,129 +664,70 @@ TypeCacheReloadContext context if (context.IsRetired(previousType)) { activeType = context.TryResolveReplacement(previousType, out TypeRef replacement) - ? replacement.Resolve(context.candidate) - : isSystem ? typeof(MissingGameSystem) : typeof(MissingGameComponent); + ? replacement.Resolve(context.candidate) + : isSystem ? typeof(MissingGameSystem) : typeof(MissingGameComponent); } } TypeRef activeTypeRef = context.candidate.GetTypeRef(activeType); bool allowsMultiple = activeType.IsDefined( isSystem ? typeof(AllowMultipleSystemAttribute) : typeof(AllowMultipleComponentAttribute), - inherit: !isSystem); - return new ActiveTypeInfo( - activeTypeRef, - activeType.FullName ?? activeType.Name, - allowsMultiple); + inherit: !isSystem + ); + return new ActiveTypeInfo(activeTypeRef, activeType.FullName ?? activeType.Name, allowsMultiple); } - private void RestoreState( - SceneState sceneState, - bool useCurrentTargets + private static string GetTypeDisplayName(Type type) => type.FullName ?? type.Name; + + private static Type? ResolveCandidateType( + ObjectState state, + TypeCacheReloadContext context ) { - EngineObject[] currentObjects = sceneState.engineObjects - .Select(engineObject => sceneState.states.FirstOrDefault(state => ReferenceEquals(state.target, engineObject)) - is ObjectState state - ? useCurrentTargets ? state.currentTarget : state.target - : engineObject) - .ToArray(); - var references = new SceneGraphReferenceMap(sceneState.scene); - var currentByPersistentId = new Dictionary(); - for (int i = 0; i < currentObjects.Length; i++) + Type requiredBase = state.target is GameSystem ? typeof(GameSystem) : typeof(GameComponent); + Type? candidate = null; + if (state.target is MissingGameComponent or MissingGameSystem) { - references.Register(sceneState.engineObjects[i].identity.persistentId, currentObjects[i]); - currentByPersistentId[currentObjects[i].identity.persistentId] = currentObjects[i]; + _ = TryResolve(state.logicalType, context.candidate, out candidate); } - foreach (ObjectState state in sceneState.states) - { - IReadOnlyDictionary? aliases = state.target switch - { - MissingGameComponent component => component.referenceAliases, - MissingGameSystem system => system.referenceAliases, - _ => null - }; - if (aliases is null) - continue; - foreach ((Guid alias, Guid targetPersistentId) in aliases) - { - if (!currentByPersistentId.TryGetValue(targetPersistentId, out EngineObject? target)) - { - throw new InvalidOperationException( - $"Missing scene state reference alias '{alias}' targets unavailable identity '{targetPersistentId}'."); - } - references.Register(alias, target); - } + else if (context.IsRetired(state.activeType) + && context.TryResolveReplacement(state.activeType, out TypeRef replacement) + ) { + candidate = replacement.Resolve(context.candidate); } - List? restoreFailures = null; - using (references.Enter()) + if (candidate is null) { - foreach (ObjectState state in sceneState.states) - { - ISerializable target = (ISerializable)(useCurrentTargets ? state.currentTarget : state.target); - if (target is MissingGameComponent or MissingGameSystem) - continue; - SerializationPropertyRestoreResult result; - try - { - result = m_serialization.RestorePropertiesData( - target, - state.data, - useCurrentTargets && state.target is not MissingGameComponent and not MissingGameSystem - ? SerializationPropertyRestoreMode.CollectFailures - : SerializationPropertyRestoreMode.Strict, - AssetSerializationContext.Create(m_assets)); - } - catch (Exception exception) when (!useCurrentTargets && exception is not RetirementPendingException) - { - restoreFailures ??= []; - restoreFailures.Add(new InvalidOperationException( - $"Previous state restoration failed for '{target.GetType().FullName}'.", - exception)); - continue; - } - if (!useCurrentTargets) - continue; - if (state.target is MissingGameComponent or MissingGameSystem && - (!result.success || result.ignoredCount != 0)) - throw new InvalidOperationException( - $"Missing scene element '{state.target.identity.persistentId}' could not restore its complete preserved state."); - for (int i = 0; i < result.failures.Count; i++) - { - SerializationPropertyRestoreFailure failure = result.failures[i]; - string previousType = GetTypeDisplayName(failure.previousPropertyType); - string currentType = GetTypeDisplayName(failure.currentPropertyType); - m_diagnostics.Add(new SceneReloadDiagnostic( - "INNOHR0001", - DiagnosticSeverity.Warning, - $"Hot reload skipped '{target.GetType().FullName}.{failure.name}' because " + - $"serialized type '{previousType}' is incompatible with '{currentType}'. " + - $"The new member default value was preserved. {failure.message}", - sceneState.scene.identity.persistentId, - ((EngineObject)target).identity.persistentId, - failure.name, - previousType, - currentType)); - } - } + return null; } - if (restoreFailures is not null) - throw new AggregateException("One or more previous scene objects could not be restored.", restoreFailures); + if (!requiredBase.IsAssignableFrom(candidate) || candidate.IsAbstract + || candidate == typeof(MissingGameComponent) || candidate == typeof(MissingGameSystem) + ) { + throw new InvalidOperationException( + $"Stable type id '{state.logicalType.stableID:D}' resolves to invalid replacement '{candidate.FullName}'." + ); + } + return candidate; } - private static string GetTypeDisplayName(Type type) => type.FullName ?? type.Name; - - private IEnumerable RetiredStates() - => m_scenes.SelectMany(static scene => scene.states) - .Where(state => m_context.IsRetired(state.activeType)); - - private void EnsureActive() - { - if (m_finished) - throw new InvalidOperationException("Scene hot-reload migration is already finished."); + private static bool TryResolve( + TypeRef typeRef, + TypeCacheSnapshot snapshot, + out Type? type + ) { + try + { + type = typeRef.Resolve(snapshot); + return true; + } + catch (InvalidOperationException) + { + type = null; + return false; + } } private sealed record SceneState( GameScene scene, EngineObject[] engineObjects, - IReadOnlyDictionary sourceIds, + IReadOnlyDictionary sourceIDs, List states ); @@ -609,8 +745,9 @@ AssetDependency[] dependencies internal string typeName { get; } = typeName; internal byte[] data { get; } = data; internal AssetDependency[] dependencies { get; } = dependencies; - internal bool lifecycleWasEnabled { get; } = - target is ISceneLifecycleObject lifecycle && lifecycle.lifecycleWasEnabled; + + internal bool lifecycleWasEnabled { get; } = target is ISceneLifecycleObject lifecycle && lifecycle.lifecycleWasEnabled; + internal EngineObject currentTarget { get; set; } = target; } @@ -635,43 +772,4 @@ private readonly record struct ActiveTypeInfo( string displayName, bool allowsMultiple ); - - private static Type? ResolveCandidateType( - ObjectState state, - TypeCacheReloadContext context - ) { - Type requiredBase = state.target is GameSystem ? typeof(GameSystem) : typeof(GameComponent); - Type? candidate = null; - if (state.target is MissingGameComponent or MissingGameSystem) - _ = TryResolve(state.logicalType, context.candidate, out candidate); - else if (context.IsRetired(state.activeType) && - context.TryResolveReplacement(state.activeType, out TypeRef replacement)) - candidate = replacement.Resolve(context.candidate); - if (candidate is null) - return null; - if (!requiredBase.IsAssignableFrom(candidate) || candidate.IsAbstract || - candidate == typeof(MissingGameComponent) || candidate == typeof(MissingGameSystem)) - { - throw new InvalidOperationException( - $"Stable type id '{state.logicalType.stableId:D}' resolves to invalid replacement '{candidate.FullName}'."); - } - return candidate; - } - - private static bool TryResolve( - TypeRef typeRef, - TypeCacheSnapshot snapshot, - out Type? type - ) { - try - { - type = typeRef.Resolve(snapshot); - return true; - } - catch (InvalidOperationException) - { - type = null; - return false; - } - } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs b/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs index 69a83728b..c2f473dfb 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; - using Inno.Core.Identity; using Inno.Scene; @@ -29,7 +28,9 @@ string description { GameObject gameObject = created[i]; if (!gameObject.isRuntimeValid) + { continue; + } try { _ = scene.DestroyObject(gameObject); @@ -43,36 +44,45 @@ string description var survivorSet = new HashSet( created.Where(static gameObject => gameObject.isRuntimeValid), - ReferenceEqualityComparer.Instance); + ReferenceEqualityComparer.Instance + ); survivorSet.UnionWith(scene.GetObjects().Where(gameObject => !existing.Contains(gameObject))); GameObject[] survivors = [.. survivorSet]; for (int i = 0; i < created.Length; i++) { GameObject gameObject = created[i]; if (!ReferenceEquals( - IdentityAllocator.current.Get(gameObject.identity.persistentId), - gameObject)) - { + IdentityAllocator.current.Get(gameObject.identity.persistentID), + gameObject + )) { continue; } if (!survivors.Contains(gameObject, ReferenceEqualityComparer.Instance)) + { survivors = [.. survivors, gameObject]; + } } if (survivors.Length != 0) { cleanupFailures ??= []; - cleanupFailures.Add(new InvalidOperationException( - $"{description} left {survivors.Length} created GameObject(s) live or identity-registered.")); + cleanupFailures.Add( + new InvalidOperationException( + $"{description} left {survivors.Length} created GameObject(s) live or identity-registered." + ) + ); } if (cleanupFailures is null) + { ExceptionDispatchInfo.Capture(restoreFailure).Throw(); + } throw new InvalidOperationException( survivors.Length == 0 - ? $"{description} failed; created objects were removed, but one or more destruction callbacks also failed." - : $"{description} failed and could not restore the exact prior scene state.", - new AggregateException([restoreFailure, .. cleanupFailures])); + ? $"{description} failed; created objects were removed, but one or more destruction callbacks also failed." + : $"{description} failed and could not restore the exact prior scene state.", + new AggregateException([restoreFailure, .. cleanupFailures]) + ); } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs index a782395ac..5ae52f3f4 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -43,7 +42,9 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (!root.isRuntimeValid) + { throw new InvalidOperationException("A destroyed or detached GameObject subtree cannot be captured."); + } SerializationContext context = AssetSerializationContext.Create(assets); return serialization.Serialize(new SceneSubtreeState(root), context); } @@ -57,18 +58,18 @@ IAssetReferenceResolver assets /// /// Bytes created by . /// - /// - /// The optional external parent restored after the subtree is created. - /// - /// - /// The requested sibling index under or at the scene root. - /// /// /// The serialization registry that owns the active converter generation. /// /// /// The asset-reference resolver used to restore referenced asset identities. /// + /// + /// The optional external parent restored after the subtree is created. + /// + /// + /// The requested sibling index under or at the scene root. + /// /// /// The restored subtree root. /// @@ -90,12 +91,14 @@ int siblingIndex ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (!scene.isLoaded || scene.isDestroyed) + { throw new InvalidOperationException("A scene subtree can only be restored into a live loaded scene."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The requested parent belongs to another scene.", nameof(parent)); - var existing = new HashSet( - scene.GetObjects(), - ReferenceEqualityComparer.Instance); + } + var existing = new HashSet(scene.GetObjects(), ReferenceEqualityComparer.Instance); try { SerializationContext context = AssetSerializationContext.Create(assets) @@ -111,7 +114,8 @@ int siblingIndex exception, scene, existing, - "Scene subtree restoration"); + "Scene subtree restoration" + ); throw; } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs index 9faa25916..86a57ac19 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -38,20 +37,23 @@ SceneSubtreeState value .Where(entry => included.Contains(entry.gameObject)) .ToArray(); EngineObject[] allObjects = GetAllObjects(scene); - var sourceIds = new Dictionary(ReferenceEqualityComparer.Instance); + var sourceIDs = new Dictionary(ReferenceEqualityComparer.Instance); for (int i = 0; i < allObjects.Length; i++) - sourceIds.Add(allObjects[i], allObjects[i].identity.persistentId); - var references = new SceneGraphReferenceMap(scene, sourceIds, root); + { + sourceIDs.Add(allObjects[i], allObjects[i].identity.persistentID); + } + var references = new SceneGraphReferenceMap(scene, sourceIDs, root); - writer.Write(C_ROOT_ID_KEY, root.identity.persistentId); + writer.Write(C_ROOT_ID_KEY, root.identity.persistentID); using (references.Enter()) { SceneGraphSerialization.WriteObjects( writer, entries, - sourceIds, + sourceIDs, included.Contains, - preserveRootSiblingOrder: true); + preserveRootSiblingOrder: true + ); } } @@ -68,9 +70,8 @@ public override SceneSubtreeState Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); GameScene scene = reader.context.GetRequired(); - Guid rootId = reader.Read(C_ROOT_ID_KEY); - IReadOnlyList objectReaders = - reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY); + Guid rootID = reader.Read(C_ROOT_ID_KEY); + IReadOnlyList objectReaders = reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY); SceneGraphSerialization.ValidateMissingReferenceAliases(reader); SceneGraphSerialization.ValidateObjects(objectReaders); var existing = new HashSet(scene.GetObjects(), ReferenceEqualityComparer.Instance); @@ -79,21 +80,22 @@ public override SceneSubtreeState Read(SerializationReader reader) var references = new SceneGraphReferenceMap(scene); EngineObject[] externalObjects = GetAllObjects(scene); for (int i = 0; i < externalObjects.Length; i++) - references.Register(externalObjects[i].identity.persistentId, externalObjects[i]); + { + references.Register(externalObjects[i].identity.persistentID, externalObjects[i]); + } RestoredSceneGraph restored = SceneGraphSerialization.RestoreObjects( scene, objectReaders, - preservePersistentIds: true, + preservePersistentIDs: true, references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), - reader.context); - if (!restored.objects.TryGetValue(rootId, out GameObject? root)) - throw new InvalidDataException($"Scene subtree root '{rootId}' is missing."); - SceneGraphSerialization.ReconcilePrefabConnections( - scene, - reader.context, - root, - includeRestoredRoot: true); + reader.context + ); + if (!restored.objects.TryGetValue(rootID, out GameObject? root)) + { + throw new InvalidDataException($"Scene subtree root '{rootID}' is missing."); + } + SceneGraphSerialization.ReconcilePrefabConnections(scene, reader.context, root, includeRestoredRoot: true); return new SceneSubtreeState(root); } catch (Exception exception) @@ -102,15 +104,15 @@ public override SceneSubtreeState Read(SerializationReader reader) exception, scene, existing, - "Scene subtree deserialization"); + "Scene subtree deserialization" + ); throw; } } private static EngineObject[] GetAllObjects(GameScene scene) => scene.GetObjects() - .SelectMany(static gameObject => - gameObject.GetComponents().Cast().Prepend(gameObject)) + .SelectMany(static gameObject => gameObject.GetComponents().Cast().Prepend(gameObject)) .Concat(scene.GetSystems()) .ToArray(); @@ -121,6 +123,8 @@ ISet result _ = result.Add(gameObject); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { CollectSubtree(children[i].gameObject, result); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs b/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs index 5f419b06a..47a142d2d 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs @@ -11,32 +11,33 @@ public sealed class SceneTypeResolutionException : Exception /// /// Creates an exception for one unresolved serialized scene type. /// - /// + /// /// The stable identity stored by the serialized scene element. /// /// /// The human-readable scene element kind, such as component or system. /// /// - /// Thrown when is empty or is empty. + /// Thrown when is empty or is empty. /// public SceneTypeResolutionException( - Guid stableTypeId, + Guid stableTypeID, string elementKind - ) - : base($"Scene {elementKind} stable type id '{stableTypeId}' is not loaded.") + ) : base($"Scene {elementKind} stable type id '{stableTypeID}' is not loaded.") { - if (stableTypeId == Guid.Empty) - throw new ArgumentException("A stable scene type identity is required.", nameof(stableTypeId)); + if (stableTypeID == Guid.Empty) + { + throw new ArgumentException("A stable scene type identity is required.", nameof(stableTypeID)); + } ArgumentException.ThrowIfNullOrWhiteSpace(elementKind); - this.stableTypeId = stableTypeId; + this.stableTypeID = stableTypeID; this.elementKind = elementKind; } /// /// Gets the unresolved stable type identity. /// - public Guid stableTypeId { get; } + public Guid stableTypeID { get; } /// /// Gets the scene element kind that expected the missing type. diff --git a/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs b/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs index ddb43ad1d..cece7dd36 100644 --- a/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs +++ b/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs @@ -13,9 +13,11 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(componentType); ArgumentNullException.ThrowIfNull(context); - const PropertyVisibility persistent = PropertyVisibility.Serialize | PropertyVisibility.Deserialize; - return context.GetRequired().GetMetadata(componentType).members - .Where(static member => (member.visibility & persistent) == persistent).ToArray(); + const PropertyVisibility C_PERSISTENT = PropertyVisibility.Serialize | PropertyVisibility.Deserialize; + return context.GetRequired() + .GetMetadata(componentType).members + .Where(static member => (member.visibility & C_PERSISTENT) == C_PERSISTENT) + .ToArray(); } internal static byte[] Encode( @@ -31,7 +33,9 @@ SceneReferenceScope references object? value = member.GetValue(component); SerializationRegistry serialization = context.GetRequired(); using (references.Enter()) + { return serialization.Encode(writer => writer.Write("value", value, member.type), context); + } } internal static void Decode( diff --git a/src/content/scene/Inno.Scene/Service/ActivationService.cs b/src/content/scene/Inno.Scene/Service/ActivationService.cs index b4ff9e9a0..71111c77b 100644 --- a/src/content/scene/Inno.Scene/Service/ActivationService.cs +++ b/src/content/scene/Inno.Scene/Service/ActivationService.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Inno.Scene.Components; namespace Inno.Scene; @@ -14,7 +13,9 @@ internal void SetActive( bool active ) { if (gameObject.activeSelf == active) + { return; + } gameObject.SetActiveSelfDirect(active); RecomputeSubtree(gameObject); } @@ -33,6 +34,8 @@ bool parentActive gameObject.SetActiveInHierarchyDirect(active); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { Recompute(children[i].gameObject, active); + } } } diff --git a/src/content/scene/Inno.Scene/Service/HierarchyService.cs b/src/content/scene/Inno.Scene/Service/HierarchyService.cs index 0308770d5..35d75a9ba 100644 --- a/src/content/scene/Inno.Scene/Service/HierarchyService.cs +++ b/src/content/scene/Inno.Scene/Service/HierarchyService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Mathematics; using Inno.Scene.Components; @@ -35,9 +34,13 @@ internal void Unregister(Transform transform) { Transform? parent = transform.parent; if (parent is null) + { RemoveRoot(transform); + } else + { parent.RemoveChildDirect(transform); + } transform.SetParentDirect(null); revision++; } @@ -49,19 +52,28 @@ bool worldPositionStays ) { ArgumentNullException.ThrowIfNull(transform); if (ReferenceEquals(transform, parent)) + { throw new InvalidOperationException("A transform cannot parent itself."); + } if (parent is not null && parent.IsDescendantOf(transform)) + { throw new InvalidOperationException("The requested transform parent would create a hierarchy cycle."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, m_scene)) + { throw new InvalidOperationException("Transforms from different scenes cannot share a hierarchy."); + } if (ReferenceEquals(transform.parent, parent)) + { return; + } if (worldPositionStays && parent is not null - && MathF.Abs(Matrix.Determinant(parent.localToWorldMatrix)) < MathHelper.C_TOLERANCE) - { + && MathF.Abs(Matrix.Determinant(parent.localToWorldMatrix)) < MathHelper.C_TOLERANCE + ) { throw new InvalidOperationException( - "A transform cannot preserve world space under a parent hierarchy with zero scale."); + "A transform cannot preserve world space under a parent hierarchy with zero scale." + ); } Vector3 worldPosition = transform.worldPosition; @@ -73,15 +85,23 @@ bool worldPositionStays Transform? previousParent = transform.parent; if (previousParent is null) + { RemoveRoot(transform); + } else + { previousParent.RemoveChildDirect(transform); + } transform.SetParentDirect(parent); if (parent is null) + { Register(transform); + } else + { parent.AddChildDirect(transform); + } if (worldPositionStays) { @@ -102,7 +122,9 @@ bool worldPositionStays internal int GetSiblingIndex(Transform transform) { if (transform.parent is Transform parent) + { return parent.IndexOfChild(transform); + } return m_rootIndices.GetValueOrDefault(transform, -1); } @@ -114,7 +136,9 @@ int siblingIndex { int current = parent.IndexOfChild(transform); if (current < 0) + { throw new InvalidOperationException("Transform is missing from its parent child collection."); + } int target = Math.Clamp(siblingIndex, 0, parent.children.Count - 1); if (current != target) { @@ -126,10 +150,14 @@ int siblingIndex int rootIndex = m_rootIndices.GetValueOrDefault(transform, -1); if (rootIndex < 0) + { throw new InvalidOperationException("Transform is missing from the scene hierarchy index."); + } int rootTarget = Math.Clamp(siblingIndex, 0, m_roots.Count - 1); if (rootIndex == rootTarget) + { return; + } m_roots.RemoveAt(rootIndex); m_roots.Insert(rootTarget, transform); RefreshRootIndices(Math.Min(rootIndex, rootTarget), Math.Max(rootIndex, rootTarget) + 1); @@ -146,7 +174,9 @@ internal void Clear() private void RemoveRoot(Transform transform) { if (!m_rootIndices.Remove(transform, out int index)) + { return; + } m_roots.RemoveAt(index); RefreshRootIndices(index, m_roots.Count); } @@ -156,6 +186,8 @@ private void RefreshRootIndices( int end ) { for (int index = start; index < end; index++) + { m_rootIndices[m_roots[index]] = index; + } } } diff --git a/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs b/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs index 9e11a811e..d60645558 100644 --- a/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs +++ b/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs @@ -15,7 +15,9 @@ TypeCacheSnapshot types ArgumentNullException.ThrowIfNull(componentType); ArgumentNullException.ThrowIfNull(types); if (!typeof(GameComponent).IsAssignableFrom(componentType) || componentType.IsAbstract || !componentType.IsClass) + { throw new ArgumentException($"Type '{componentType.FullName}' is not a concrete GameComponent.", nameof(componentType)); + } return (GameComponent)types.CreateInstance(componentType); } } diff --git a/src/content/scene/Inno.Scene/Storage/SceneStore.cs b/src/content/scene/Inno.Scene/Storage/SceneStore.cs index cf794091c..581ccafc9 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStore.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStore.cs @@ -3,46 +3,20 @@ using System.Collections.ObjectModel; using System.Linq; using System.Threading; - -using Inno.Extensibility.Types; using Inno.Core.Collections; using Inno.Scene.Layers; namespace Inno.Scene; -/// -/// Describes the structural result of removing a component. -/// -internal enum SceneStoreRemovalKind -{ - /// - /// The none key. - /// - None, - /// - /// The canceled pending addition key. - /// - CanceledPendingAddition, - /// - /// The removed committed key. - /// - RemovedCommitted, -} - -internal readonly record struct SceneStoreRemovedComponent( - GameComponent component, - bool wasCommitted -); - internal sealed class SceneStore { - private readonly SceneTypeCatalog m_types; - private static readonly Lock S_TYPE_CACHE_SYNC = new(); - private static readonly List> S_STORES = []; + private static readonly Lock TYPE_CACHE_SYNC = new(); + private static readonly List> STORES = []; + private readonly SceneTypeCatalog m_types; private readonly IndexedObjectStore m_objects = new(); private readonly IndexedObjectKey m_objectKey; - private readonly IndexedObjectKey m_objectPersistentIdKey; + private readonly IndexedObjectKey m_objectPersistentIDKey; private readonly IndexedObjectKey m_objectNameKey; private readonly IndexedObjectKey m_objectTagKey; private readonly IndexedObjectKey m_objectLayerKey; @@ -51,7 +25,7 @@ internal sealed class SceneStore private readonly IndexedObjectStore m_components = new(); private readonly IndexedObjectKey m_componentKey; - private readonly IndexedObjectKey m_componentPersistentIdKey; + private readonly IndexedObjectKey m_componentPersistentIDKey; private readonly IndexedObjectKey m_componentOwnerKey; private readonly IndexedObjectKey m_componentTypeKey; private readonly IndexedObjectKey m_componentCommittedKey; @@ -72,15 +46,16 @@ internal sealed class SceneStore internal SceneStore(SceneTypeCatalog types) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); - lock (S_TYPE_CACHE_SYNC) + ArgumentNullException.ThrowIfNull(types); + m_types = types; + lock (TYPE_CACHE_SYNC) { - S_STORES.RemoveAll(static reference => !reference.TryGetTarget(out _)); - S_STORES.Add(new WeakReference(this)); + STORES.RemoveAll(static reference => !reference.TryGetTarget(out _)); + STORES.Add(new WeakReference(this)); } m_objectKey = m_objects.DefineKey("scene.object", IndexedObjectKeyFlags.Unique); - m_objectPersistentIdKey = m_objects.DefineKey("scene.object.persistent-id", IndexedObjectKeyFlags.Unique); + m_objectPersistentIDKey = m_objects.DefineKey("scene.object.persistent-id", IndexedObjectKeyFlags.Unique); m_objectNameKey = m_objects.DefineKey("scene.object.name"); m_objectTagKey = m_objects.DefineKey("scene.object.tag"); m_objectLayerKey = m_objects.DefineKey("scene.object.layer"); @@ -88,12 +63,14 @@ internal SceneStore(SceneTypeCatalog types) m_objectOrderKey = m_objects.DefineKey( "scene.object.order", IndexedObjectKeyFlags.Ordered | IndexedObjectKeyFlags.Unique, - Comparer.Default); + Comparer.Default + ); m_componentKey = m_components.DefineKey("scene.component", IndexedObjectKeyFlags.Unique); - m_componentPersistentIdKey = m_components.DefineKey( + m_componentPersistentIDKey = m_components.DefineKey( "scene.component.persistent-id", - IndexedObjectKeyFlags.Unique); + IndexedObjectKeyFlags.Unique + ); m_componentOwnerKey = m_components.DefineKey("scene.component.owner"); m_componentTypeKey = m_components.DefineKey("scene.component.type"); m_componentCommittedKey = m_components.DefineKey("scene.component.committed"); @@ -101,12 +78,13 @@ internal SceneStore(SceneTypeCatalog types) internal bool isExecuting => m_executionDepth != 0; internal long structureRevision => m_structureRevision; - internal bool hasPendingChanges => - m_pendingObjectAdditions.Count != 0 || - m_pendingObjectRemovals.Count != 0 || - m_pendingComponentAdditions.Count != 0 || - m_pendingComponentRemovals.Count != 0 || - m_clearRequested; + + internal bool hasPendingChanges + => m_pendingObjectAdditions.Count != 0 + || m_pendingObjectRemovals.Count != 0 + || m_pendingComponentAdditions.Count != 0 + || m_pendingComponentRemovals.Count != 0 + || m_clearRequested; internal void AddObject(GameObject gameObject) { @@ -114,7 +92,8 @@ internal void AddObject(GameObject gameObject) if (TryGetRecord(gameObject, out _)) { throw new InvalidOperationException( - $"GameObject '{gameObject.identity.persistentId}' is already owned by this scene store."); + $"GameObject '{gameObject.identity.persistentID}' is already owned by this scene store." + ); } var record = new SceneObjectRecord(this, gameObject); @@ -124,7 +103,7 @@ internal void AddObject(GameObject gameObject) { m_objects.Add(record) .Set(m_objectKey, gameObject) - .Set(m_objectPersistentIdKey, gameObject.identity.persistentId) + .Set(m_objectPersistentIDKey, gameObject.identity.persistentID) .Set(m_objectNameKey, gameObject.storedName) .Set(m_objectTagKey, gameObject.storedTag) .Set(m_objectLayerKey, gameObject.storedLayer) @@ -158,31 +137,33 @@ bool allowsMultiple if (TryGetEntry(component, out _)) { throw new InvalidOperationException( - $"GameComponent '{descriptor.displayName}' is already owned by this scene store."); + $"GameComponent '{descriptor.displayName}' is already owned by this scene store." + ); } if (!allowsMultiple) { ComponentEntry? duplicate = m_components.Query() .Find(m_componentOwnerKey, record) - .Find(m_componentTypeKey, descriptor.runtimeTypeId) + .Find(m_componentTypeKey, descriptor.runtimeTypeID) .First(); if (duplicate is { isAlive: true }) { throw new InvalidOperationException( - $"GameObject '{owner.identity.persistentId}' already owns unique component " + - $"'{descriptor.displayName}'."); + $"GameObject '{owner.identity.persistentID}' already owns unique component " + + $"'{descriptor.displayName}'." + ); } } - var entry = new ComponentEntry(record, component, descriptor.runtimeTypeId); + var entry = new ComponentEntry(record, component, descriptor.runtimeTypeID); try { m_components.Add(entry) .Set(m_componentKey, component) - .Set(m_componentPersistentIdKey, component.identity.persistentId) + .Set(m_componentPersistentIDKey, component.identity.persistentID) .Set(m_componentOwnerKey, record) - .Set(m_componentTypeKey, descriptor.runtimeTypeId) + .Set(m_componentTypeKey, descriptor.runtimeTypeID) .Set(m_componentCommittedKey, false); record.components.Add(component); } @@ -204,12 +185,12 @@ internal SceneStoreRemovalKind RemoveComponent( GameObject owner, GameComponent component ) { - if (!TryGetRecord(owner, out SceneObjectRecord? record) || - !record!.isAlive || - !TryGetEntry(component, out ComponentEntry? entry) || - !entry!.isAlive || - !ReferenceEquals(entry.owner, record)) - { + if (!TryGetRecord(owner, out SceneObjectRecord? record) + || !record!.isAlive + || !TryGetEntry(component, out ComponentEntry? entry) + || !entry!.isAlive + || !ReferenceEquals(entry.owner, record) + ) { return SceneStoreRemovalKind.None; } @@ -223,35 +204,47 @@ GameComponent component } if (isExecuting) + { m_pendingComponentRemovals.Add(new PendingComponentRemoval(entry)); + } else + { CommitComponentRemoval(entry); + } return SceneStoreRemovalKind.RemovedCommitted; } internal void ReplaceComponent( GameComponent previous, GameComponent replacement, - int replacementRuntimeTypeId + int replacementRuntimeTypeID ) { ArgumentNullException.ThrowIfNull(previous); ArgumentNullException.ThrowIfNull(replacement); if (isExecuting || hasPendingChanges) + { throw new InvalidOperationException("Components cannot be replaced during a scene execution phase."); + } if (!TryGetEntry(previous, out ComponentEntry? entry) || !entry!.isAlive) + { throw new InvalidOperationException("The component being replaced is not attached to this scene."); + } if (TryGetEntry(replacement, out _)) + { throw new InvalidOperationException("The replacement component is already attached to this scene."); + } int index = entry.owner.components.IndexOf(previous); if (index < 0) + { throw new InvalidOperationException("The component attachment order is inconsistent."); + } m_components.Add(entry) .Set(m_componentKey, replacement) - .Set(m_componentTypeKey, replacementRuntimeTypeId); + .Set(m_componentTypeKey, replacementRuntimeTypeID); entry.component = replacement; - entry.runtimeTypeId = replacementRuntimeTypeId; + entry.runtimeTypeID = replacementRuntimeTypeID; entry.owner.components[index] = replacement; InvalidateStructureCaches(); } @@ -259,7 +252,9 @@ int replacementRuntimeTypeId internal IReadOnlyList RemoveObject(GameObject gameObject) { if (!TryGetRecord(gameObject, out SceneObjectRecord? record) || !record!.isAlive) - return Array.Empty(); + { + return []; + } record.isAlive = false; gameObject.ReleaseRecord(record); @@ -281,9 +276,13 @@ internal IReadOnlyList RemoveObject(GameObject gameO } if (isExecuting) + { m_pendingObjectRemovals.Add(new PendingObjectRemoval(record)); + } else + { CommitObjectRemoval(record); + } return removed; } @@ -292,7 +291,9 @@ internal IReadOnlyList RemoveObject(GameObject gameO internal IReadOnlyList GetObjects() { if (m_objectSnapshotCache is not null) + { return m_objectSnapshotCache; + } IReadOnlyList records = m_objects.Query() .Find(m_objectCommittedKey, true) @@ -301,14 +302,16 @@ internal IReadOnlyList GetObjects() .Get(); var result = new GameObject[records.Count]; for (int i = 0; i < records.Count; i++) + { result[i] = records[i].gameObject; + } m_objectSnapshotCache = result; return result; } - internal GameObject? FindObject(Guid persistentId) + internal GameObject? FindObject(Guid persistentID) { - SceneObjectRecord? record = m_objects.First(m_objectPersistentIdKey, persistentId); + SceneObjectRecord? record = m_objects.First(m_objectPersistentIDKey, persistentID); return record is { isAlive: true } ? record.gameObject : null; } @@ -329,12 +332,14 @@ internal IReadOnlyList GetObjects() .First()?.gameObject; internal IReadOnlyList FindObjectsWithTag(string tag) - => SelectObjects(m_objects.Query() - .Find(m_objectTagKey, tag) - .Find(m_objectCommittedKey, true) - .Where(static record => record.isAlive) - .OrderBy(m_objectOrderKey) - .Get()); + => SelectObjects( + m_objects.Query() + .Find(m_objectTagKey, tag) + .Find(m_objectCommittedKey, true) + .Where(static record => record.isAlive) + .OrderBy(m_objectOrderKey) + .Get() + ); internal GameObject? FindObjectWithLayer(GameLayer layer) => m_objects.Query() @@ -345,17 +350,21 @@ internal IReadOnlyList FindObjectsWithTag(string tag) .First()?.gameObject; internal IReadOnlyList FindObjectsWithLayer(GameLayer layer) - => SelectObjects(m_objects.Query() - .Find(m_objectLayerKey, layer) - .Find(m_objectCommittedKey, true) - .Where(static record => record.isAlive) - .OrderBy(m_objectOrderKey) - .Get()); + => SelectObjects( + m_objects.Query() + .Find(m_objectLayerKey, layer) + .Find(m_objectCommittedKey, true) + .Where(static record => record.isAlive) + .OrderBy(m_objectOrderKey) + .Get() + ); internal IReadOnlyList FindObjectsWithLayers(GameLayerMask layers) { if (layers == GameLayerMask.none) - return Array.Empty(); + { + return []; + } return GetObjects().Where(gameObject => layers.Contains(gameObject.layer)).ToArray(); } @@ -374,15 +383,54 @@ internal IReadOnlyList GetOwnedObjects() .Select(static record => record.gameObject) .ToArray(); - internal GameComponent? FindComponent(Guid persistentId) + internal GameComponent? FindComponent(Guid persistentID) { - ComponentEntry? entry = m_components.First(m_componentPersistentIdKey, persistentId); + ComponentEntry? entry = m_components.First(m_componentPersistentIDKey, persistentID); return entry is { isAlive: true } && entry.owner.isAlive ? entry.component : null; } internal IReadOnlyList GetComponents(GameObject owner) => GetAliveRecord(owner).components.Where(IsLocallyVisible).ToArray(); + internal IReadOnlyList GetComponents( + SceneComponentTypeDescriptor requestedType) where TComponent : GameComponent + { + if (m_typedComponentQueryCache.TryGetValue(requestedType.runtimeTypeID, out object? cached)) + { + return (ReadOnlyCollection)cached; + } + + GameComponent[] untyped = GetCommittedComponents(requestedType); + var typed = new TComponent[untyped.Length]; + for (int i = 0; i < untyped.Length; i++) + { + typed[i] = (TComponent)untyped[i]; + } + ReadOnlyCollection view = Array.AsReadOnly(typed); + m_typedComponentQueryCache.Add(requestedType.runtimeTypeID, view); + return view; + } + + internal IReadOnlyList GetComponents( + GameObject owner, + SceneComponentTypeDescriptor requestedType + ) where TComponent : GameComponent + { + SceneObjectRecord record = GetAliveRecord(owner); + var result = new List(record.components.Count); + for (int i = 0; i < record.components.Count; i++) + { + GameComponent candidate = record.components[i]; + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeID) + ) { + result.Add((TComponent)candidate); + } + } + return result; + } + internal bool TryGetComponent( GameObject owner, SceneComponentTypeDescriptor requestedType, @@ -393,10 +441,10 @@ out TComponent? component for (int i = 0; i < record.components.Count; i++) { GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeID) + ) { component = (TComponent)candidate; return true; } @@ -414,10 +462,10 @@ out GameComponent? component for (int i = 0; i < record.components.Count; i++) { GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeID) + ) { component = candidate; return true; } @@ -434,8 +482,8 @@ GameComponent component SceneObjectRecord record = GetAliveRecord(owner); int index = record.components.IndexOf(component); return index >= 0 && IsLocallyVisible(component) - ? index - : throw new InvalidOperationException("The component is not attached to the requested GameObject."); + ? index + : throw new InvalidOperationException("The component is not attached to the requested GameObject."); } internal void SetComponentIndex( @@ -445,125 +493,40 @@ int componentIndex ) { SceneObjectRecord record = GetAliveRecord(owner); if (record.isCommitted && (isExecuting || hasPendingChanges)) + { throw new InvalidOperationException("Components cannot be reordered during a scene execution phase."); + } int currentIndex = GetComponentIndex(owner, component); int targetIndex = Math.Clamp(componentIndex, 0, record.components.Count - 1); if (currentIndex == targetIndex) + { return; + } record.components.RemoveAt(currentIndex); record.components.Insert(targetIndex, component); m_structureSnapshotCache = null; } - internal IReadOnlyList GetComponents( - GameObject owner, - SceneComponentTypeDescriptor requestedType - ) where TComponent : GameComponent - { - SceneObjectRecord record = GetAliveRecord(owner); - var result = new List(record.components.Count); - for (int i = 0; i < record.components.Count; i++) - { - GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { - result.Add((TComponent)candidate); - } - } - return result; - } - - internal IReadOnlyList GetComponents( - SceneComponentTypeDescriptor requestedType) where TComponent : GameComponent - { - if (m_typedComponentQueryCache.TryGetValue(requestedType.runtimeTypeId, out object? cached)) - return (ReadOnlyCollection)cached; - - GameComponent[] untyped = GetCommittedComponents(requestedType); - var typed = new TComponent[untyped.Length]; - for (int i = 0; i < untyped.Length; i++) - typed[i] = (TComponent)untyped[i]; - ReadOnlyCollection view = Array.AsReadOnly(typed); - m_typedComponentQueryCache.Add(requestedType.runtimeTypeId, view); - return view; - } - internal IReadOnlyList Query(SceneComponentTypeDescriptor requestedType) - => Query(ComponentQueryKey.Create(requestedType.runtimeTypeId)); + => Query(ComponentQueryKey.Create(requestedType.runtimeTypeID)); internal IReadOnlyList Query( SceneComponentTypeDescriptor first, SceneComponentTypeDescriptor second - ) - => Query(ComponentQueryKey.Create(first.runtimeTypeId, second.runtimeTypeId)); + ) => Query(ComponentQueryKey.Create(first.runtimeTypeID, second.runtimeTypeID)); internal IReadOnlyList Query( SceneComponentTypeDescriptor first, SceneComponentTypeDescriptor second, SceneComponentTypeDescriptor third - ) - => Query(ComponentQueryKey.Create( - first.runtimeTypeId, - second.runtimeTypeId, - third.runtimeTypeId)); - - private IReadOnlyList Query(ComponentQueryKey query) - { - if (m_objectQueryCache.TryGetValue(query, out ReadOnlyCollection? cached)) - return cached; - - SceneComponentTypeDescriptor first = m_types.GetComponent(query.first); - SceneComponentTypeDescriptor? second = query.count >= 2 - ? m_types.GetComponent(query.second) - : null; - SceneComponentTypeDescriptor? third = query.count >= 3 - ? m_types.GetComponent(query.third) - : null; - GameComponent[] candidates = GetCommittedComponents(first); - if (second is not null) - { - GameComponent[] secondCandidates = GetCommittedComponents(second); - if (secondCandidates.Length < candidates.Length) - candidates = secondCandidates; - } - if (third is not null) - { - GameComponent[] thirdCandidates = GetCommittedComponents(third); - if (thirdCandidates.Length < candidates.Length) - candidates = thirdCandidates; - } - - var seen = new HashSet(ReferenceEqualityComparer.Instance); - var result = new List(); - for (int i = 0; i < candidates.Length; i++) - { - GameComponent candidate = candidates[i]; - if (!TryGetEntry(candidate, out ComponentEntry? entry) || - !IsVisible(entry!) || - !seen.Add(entry!.owner.gameObject)) - { - continue; - } - - if (HasVisibleComponent(entry.owner, first) && - (second is null || HasVisibleComponent(entry.owner, second)) && - (third is null || HasVisibleComponent(entry.owner, third))) - { - result.Add(entry.owner.gameObject); - } - } - - cached = Array.AsReadOnly(result.ToArray()); - m_objectQueryCache.Add(query, cached); - return cached; - } + ) => Query(ComponentQueryKey.Create(first.runtimeTypeID, second.runtimeTypeID, third.runtimeTypeID)); internal IDisposable BeginExecutionPhase() { if (m_clearRequested) + { throw new InvalidOperationException("A scene execution phase cannot begin while the store is pending clear."); + } m_executionDepth++; return new ExecutionScope(this); } @@ -573,11 +536,14 @@ internal SceneStructureSnapshot CaptureStructure() if (isExecuting || hasPendingChanges) { throw new InvalidOperationException( - "A scene cannot be captured during an execution phase with uncommitted structural changes."); + "A scene cannot be captured during an execution phase with uncommitted structural changes." + ); } if (m_structureSnapshotCache is not null) + { return m_structureSnapshotCache; + } SceneObjectStructureSnapshot[] objects = GetObjects() .Select(gameObject => new SceneObjectStructureSnapshot(gameObject, GetComponents(gameObject))) .ToArray(); @@ -591,51 +557,114 @@ internal void InvalidateTypeCaches() m_objectQueryCache.Clear(); } + internal void Clear() + { + InvalidateStructureCaches(); + if (isExecuting) + { + m_clearRequested = true; + return; + } + ClearImmediately(); + } + internal static void InvalidateAllTypeCaches() { - lock (S_TYPE_CACHE_SYNC) + lock (TYPE_CACHE_SYNC) { - for (int i = S_STORES.Count - 1; i >= 0; i--) + for (int i = STORES.Count - 1; i >= 0; i--) { - if (S_STORES[i].TryGetTarget(out SceneStore? store)) + if (STORES[i].TryGetTarget(out SceneStore? store)) + { store.InvalidateTypeCaches(); + } else - S_STORES.RemoveAt(i); + { + STORES.RemoveAt(i); + } } } } - internal void Clear() + private IReadOnlyList Query(ComponentQueryKey query) { - InvalidateStructureCaches(); - if (isExecuting) + if (m_objectQueryCache.TryGetValue(query, out ReadOnlyCollection? cached)) { - m_clearRequested = true; - return; + return cached; } - ClearImmediately(); + + SceneComponentTypeDescriptor first = m_types.GetComponent(query.first); + SceneComponentTypeDescriptor? second = query.count >= 2 + ? m_types.GetComponent(query.second) + : null; + SceneComponentTypeDescriptor? third = query.count >= 3 + ? m_types.GetComponent(query.third) + : null; + GameComponent[] candidates = GetCommittedComponents(first); + if (second is not null) + { + GameComponent[] secondCandidates = GetCommittedComponents(second); + if (secondCandidates.Length < candidates.Length) + { + candidates = secondCandidates; + } + } + if (third is not null) + { + GameComponent[] thirdCandidates = GetCommittedComponents(third); + if (thirdCandidates.Length < candidates.Length) + { + candidates = thirdCandidates; + } + } + + var seen = new HashSet(ReferenceEqualityComparer.Instance); + List result = []; + for (int i = 0; i < candidates.Length; i++) + { + GameComponent candidate = candidates[i]; + if (!TryGetEntry(candidate, out ComponentEntry? entry) + || !IsVisible(entry!) + || !seen.Add(entry!.owner.gameObject) + ) { + continue; + } + + if (HasVisibleComponent(entry.owner, first) + && (second is null || HasVisibleComponent(entry.owner, second)) + && (third is null || HasVisibleComponent(entry.owner, third)) + ) { + result.Add(entry.owner.gameObject); + } + } + + cached = Array.AsReadOnly(result.ToArray()); + m_objectQueryCache.Add(query, cached); + return cached; } private GameComponent[] GetCommittedComponents(SceneComponentTypeDescriptor requestedType) { - if (m_componentQueryCache.TryGetValue(requestedType.runtimeTypeId, out GameComponent[]? cached)) + if (m_componentQueryCache.TryGetValue(requestedType.runtimeTypeID, out GameComponent[]? cached)) + { return cached; + } - var result = new List(); - int[] concreteTypes = requestedType.assignableConcreteRuntimeTypeIds; + List result = []; + int[] concreteTypes = requestedType.assignableConcreteRuntimeTypeIDs; for (int i = 0; i < concreteTypes.Length; i++) { - foreach (ComponentEntry entry in m_components.FindFast( - m_componentTypeKey, - concreteTypes[i])) + foreach (ComponentEntry entry in m_components.FindFast(m_componentTypeKey, concreteTypes[i])) { if (IsVisible(entry)) + { result.Add(entry.component); + } } } cached = result.ToArray(); - m_componentQueryCache.Add(requestedType.runtimeTypeId, cached); + m_componentQueryCache.Add(requestedType.runtimeTypeID, cached); return cached; } @@ -645,10 +674,10 @@ SceneComponentTypeDescriptor requestedType ) { for (int i = 0; i < owner.components.Count; i++) { - if (TryGetEntry(owner.components[i], out ComponentEntry? entry) && - IsVisible(entry!) && - requestedType.IsAssignableFrom(entry!.runtimeTypeId)) - { + if (TryGetEntry(owner.components[i], out ComponentEntry? entry) + && IsVisible(entry!) + && requestedType.IsAssignableFrom(entry!.runtimeTypeID) + ) { return true; } } @@ -666,7 +695,8 @@ private SceneObjectRecord GetAliveRecord(GameObject owner) if (!TryGetRecord(owner, out SceneObjectRecord? record) || !record!.isAlive) { throw new InvalidOperationException( - $"GameObject '{owner.identity.persistentId}' does not belong to this scene store."); + $"GameObject '{owner.identity.persistentID}' does not belong to this scene store." + ); } return record; } @@ -692,7 +722,9 @@ private void RemoveComponentEntry( GameComponent component ) { if (!TryGetEntry(component, out ComponentEntry? entry) || !entry!.isAlive) + { return; + } entry.isAlive = false; record.components.Remove(component); @@ -703,9 +735,13 @@ GameComponent component } if (isExecuting) + { m_pendingComponentRemovals.Add(new PendingComponentRemoval(entry)); + } else + { CommitComponentRemoval(entry); + } } private void CommitPendingChanges() @@ -714,25 +750,33 @@ private void CommitPendingChanges() { SceneObjectRecord record = m_pendingObjectAdditions[i].record; if (record.isAlive && !record.isCommitted) + { CommitObjectAddition(record); + } } for (int i = 0; i < m_pendingComponentAdditions.Count; i++) { ComponentEntry entry = m_pendingComponentAdditions[i].entry; if (entry.isAlive && entry.owner.isAlive && !entry.isCommitted) + { CommitComponentAddition(entry); + } } for (int i = 0; i < m_pendingComponentRemovals.Count; i++) { ComponentEntry entry = m_pendingComponentRemovals[i].entry; if (entry.isCommitted) + { CommitComponentRemoval(entry); + } } for (int i = 0; i < m_pendingObjectRemovals.Count; i++) { SceneObjectRecord record = m_pendingObjectRemovals[i].record; if (record.isCommitted) + { CommitObjectRemoval(record); + } } m_pendingObjectAdditions.Clear(); @@ -780,15 +824,23 @@ private void InvalidateStructureCaches() private void EndExecutionPhase() { if (m_executionDepth <= 0) + { throw new InvalidOperationException("Scene execution phase scopes are unbalanced."); + } m_executionDepth--; if (m_executionDepth != 0) + { return; + } if (m_clearRequested) + { ClearImmediately(); + } else + { CommitPendingChanges(); + } } private void ClearImmediately() @@ -816,7 +868,9 @@ private static IReadOnlyList SelectObjects(IReadOnlyList first == second - ? Create(first) - : Compare(first, second) < 0 - ? new ComponentQueryKey(first, second, default, 2) - : new ComponentQueryKey(second, first, default, 2); + ) => first == second + ? Create(first) + : Compare(first, second) < 0 + ? new ComponentQueryKey(first, second, default, 2) + : new ComponentQueryKey(second, first, default, 2); internal static ComponentQueryKey Create( int first, @@ -868,17 +924,29 @@ internal static ComponentQueryKey Create( int third ) { if (Compare(first, second) > 0) + { (first, second) = (second, first); + } if (Compare(second, third) > 0) + { (second, third) = (third, second); + } if (Compare(first, second) > 0) + { (first, second) = (second, first); + } if (first == third) + { return Create(first); + } if (first == second) + { return Create(first, third); + } if (second == third) + { return Create(first, second); + } return new ComponentQueryKey(first, second, third, 3); } @@ -907,3 +975,27 @@ public void Dispose() } } } + +/// +/// Describes the structural result of removing a component. +/// +internal enum SceneStoreRemovalKind +{ + /// + /// The none key. + /// + None, + /// + /// The canceled pending addition key. + /// + CanceledPendingAddition, + /// + /// The removed committed key. + /// + RemovedCommitted +} + +internal readonly record struct SceneStoreRemovedComponent( + GameComponent component, + bool wasCommitted +); diff --git a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs index 5ec9d6a3e..8c98817d7 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs @@ -4,63 +4,74 @@ namespace Inno.Scene; -/// -/// Captures the stable attachment order for one scene object. -/// -/// -/// The game object used to initialize this instance. -/// -/// -/// The components used to initialize this instance. -/// -internal sealed record SceneObjectStructureSnapshot( - GameObject gameObject, - IReadOnlyList components -); - /// /// Owns one attachment snapshot and its frozen object/component serialization identities. /// internal sealed class SceneStructureSnapshot { - private Dictionary? m_sourceIds; - private IReadOnlyDictionary? m_frozenSourceIds; + private Dictionary? m_sourceIDs; + private IReadOnlyDictionary? m_frozenSourceIDs; - internal SceneStructureSnapshot(IReadOnlyList objects) => this.objects = objects; + internal SceneStructureSnapshot(IReadOnlyList objects) + { + this.objects = objects; + } internal IReadOnlyList objects { get; } - internal IReadOnlyDictionary CaptureObjectSourceIds() + internal IReadOnlyDictionary CaptureObjectSourceIDs() { - if (m_sourceIds is not null && HasCurrentIdentities(m_sourceIds)) - return m_frozenSourceIds!; + if (m_sourceIDs is not null && HasCurrentIdentities(m_sourceIDs)) + { + return m_frozenSourceIDs!; + } int count = objects.Count; foreach (SceneObjectStructureSnapshot entry in objects) + { count = checked(count + entry.components.Count); - var sourceIds = new Dictionary(count, ReferenceEqualityComparer.Instance); + } + var sourceIDs = new Dictionary(count, ReferenceEqualityComparer.Instance); foreach (SceneObjectStructureSnapshot entry in objects) { - sourceIds.Add(entry.gameObject, entry.gameObject.identity.persistentId); + sourceIDs.Add(entry.gameObject, entry.gameObject.identity.persistentID); for (int index = 0; index < entry.components.Count; index++) { GameComponent component = entry.components[index]; - sourceIds.Add(component, component.identity.persistentId); + sourceIDs.Add(component, component.identity.persistentID); } } // Replace the projection so an already borrowed graph write keeps its original identities. - var frozen = new ReadOnlyDictionary(sourceIds); - m_sourceIds = sourceIds; - m_frozenSourceIds = frozen; + var frozen = new ReadOnlyDictionary(sourceIDs); + m_sourceIDs = sourceIDs; + m_frozenSourceIDs = frozen; return frozen; } - private static bool HasCurrentIdentities(Dictionary sourceIds) + private static bool HasCurrentIdentities(Dictionary sourceIDs) { // Core registry rebinding can replace an identity without changing the structural snapshot. - foreach ((EngineObject value, Guid persistentId) in sourceIds) - if (value.identity.persistentId != persistentId) + foreach ((EngineObject value, Guid persistentID) in sourceIDs) + { + if (value.identity.persistentID != persistentID) + { return false; + } + } return true; } } + +/// +/// Captures the stable attachment order for one scene object. +/// +/// +/// The game object used to initialize this instance. +/// +/// +/// The components used to initialize this instance. +/// +internal sealed record SceneObjectStructureSnapshot( + GameObject gameObject, + IReadOnlyList components +); diff --git a/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs b/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs index a42d80432..7765ad701 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs @@ -3,10 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -22,34 +20,47 @@ internal SceneTypeCatalog(TypeCatalog types) m_registry = new SceneTypeRegistry(types); } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() => m_registry.Dispose(); + + internal TypeCacheSnapshot snapshot => m_types.current; + + internal long generation => m_registry.snapshot.generation; + internal bool TryGetComponent( Type type, out SceneComponentTypeDescriptor? descriptor ) { ArgumentNullException.ThrowIfNull(type); descriptor = null; - return m_types.TryGetTypeRef(type, out TypeRef typeRef) && - m_registry.snapshot.componentsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); + return m_types.TryGetTypeRef(type, out TypeRef typeRef) + && m_registry.snapshot.componentsByRuntimeID.TryGetValue(typeRef.runtimeID, out descriptor); } internal SceneComponentTypeDescriptor GetComponent(Type type) { if (TryGetComponent(type, out SceneComponentTypeDescriptor? descriptor)) + { return descriptor!; + } throw new InvalidOperationException( - $"GameComponent type '{type.FullName}' is not part of the active TypeCache generation."); + $"GameComponent type '{type.FullName}' is not part of the active TypeCache generation." + ); } - internal SceneComponentTypeDescriptor GetComponent(int runtimeTypeId) + internal SceneComponentTypeDescriptor GetComponent(int runtimeTypeID) { - if (m_registry.snapshot.componentsByRuntimeId.TryGetValue( - runtimeTypeId, - out SceneComponentTypeDescriptor? descriptor)) - { + if (m_registry.snapshot.componentsByRuntimeID.TryGetValue( + runtimeTypeID, + out SceneComponentTypeDescriptor? descriptor + )) { return descriptor; } throw new InvalidOperationException( - $"Component runtime type ID '{runtimeTypeId}' is not part of the active TypeCache generation."); + $"Component runtime type ID '{runtimeTypeID}' is not part of the active TypeCache generation." + ); } internal bool TryGetSystem( @@ -58,35 +69,29 @@ out SceneSystemTypeDescriptor? descriptor ) { ArgumentNullException.ThrowIfNull(type); descriptor = null; - return m_types.TryGetTypeRef(type, out TypeRef typeRef) && - m_registry.snapshot.systemsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); + return m_types.TryGetTypeRef(type, out TypeRef typeRef) + && m_registry.snapshot.systemsByRuntimeID.TryGetValue(typeRef.runtimeID, out descriptor); } internal SceneSystemTypeDescriptor GetSystem(Type type) { if (TryGetSystem(type, out SceneSystemTypeDescriptor? descriptor)) + { return descriptor!; + } throw new InvalidOperationException( - $"GameSystem type '{type.FullName}' is not part of the active TypeCache generation."); + $"GameSystem type '{type.FullName}' is not part of the active TypeCache generation." + ); } internal Type Resolve(TypeRef typeRef) => m_types.Resolve(typeRef); - internal TypeRef GetTypeRef(Type type) => m_types.GetTypeRef(type); - internal TypeCacheSnapshot snapshot => m_types.current; - internal long generation => m_registry.snapshot.generation; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() => m_registry.Dispose(); + internal TypeRef GetTypeRef(Type type) => m_types.GetTypeRef(type); private sealed class SceneTypeRegistry : TypeRegistry { internal SceneTypeRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal SceneTypeSnapshot snapshot => current; @@ -109,47 +114,50 @@ protected override SceneTypeSnapshot Build(TypeCacheSnapshot types) .Where(static type => type.IsClass && !type.IsAbstract) .ToArray(); - var componentsByRuntimeId = new Dictionary(componentTypes.Length); + var componentsByRuntimeID = new Dictionary(componentTypes.Length); foreach (Type componentType in componentTypes) { TypeRef componentTypeRef = types.GetTypeRef(componentType); - int[] assignableConcreteRuntimeTypeIds = concreteComponentTypes + int[] assignableConcreteRuntimeTypeIDs = concreteComponentTypes .Where(componentType.IsAssignableFrom) .OrderBy(static type => type.FullName, StringComparer.Ordinal) .Select(types.GetTypeRef) - .Select(static typeRef => typeRef.runtimeId) + .Select(static typeRef => typeRef.runtimeID) .ToArray(); var descriptor = new SceneComponentTypeDescriptor( - componentTypeRef.runtimeId, + componentTypeRef.runtimeID, componentType.FullName ?? componentType.Name, componentType.IsClass && !componentType.IsAbstract, types.GetAttribute(componentTypeRef, inherit: true) is not null, GetBehaviorPhases(types.GetMetadata(componentTypeRef)), - assignableConcreteRuntimeTypeIds, - assignableConcreteRuntimeTypeIds.ToFrozenSet()); - componentsByRuntimeId.Add(descriptor.runtimeTypeId, descriptor); + assignableConcreteRuntimeTypeIDs, + assignableConcreteRuntimeTypeIDs.ToFrozenSet() + ); + componentsByRuntimeID.Add(descriptor.runtimeTypeID, descriptor); } Type[] systemTypes = types.types .Select(typeRef => typeRef.Resolve(types)) .Where(static type => typeof(GameSystem).IsAssignableFrom(type)) .ToArray(); - var systemsByRuntimeId = new Dictionary(systemTypes.Length); + var systemsByRuntimeID = new Dictionary(systemTypes.Length); foreach (Type systemType in systemTypes) { TypeRef systemTypeRef = types.GetTypeRef(systemType); var descriptor = new SceneSystemTypeDescriptor( - systemTypeRef.runtimeId, + systemTypeRef.runtimeID, systemType.FullName ?? systemType.Name, systemType.IsClass && !systemType.IsAbstract, - types.GetAttribute(systemTypeRef, inherit: false) is not null); - systemsByRuntimeId.Add(descriptor.runtimeTypeId, descriptor); + types.GetAttribute(systemTypeRef, inherit: false) is not null + ); + systemsByRuntimeID.Add(descriptor.runtimeTypeID, descriptor); } return new SceneTypeSnapshot( types.version, - componentsByRuntimeId.ToFrozenDictionary(), - systemsByRuntimeId.ToFrozenDictionary()); + componentsByRuntimeID.ToFrozenDictionary(), + systemsByRuntimeID.ToFrozenDictionary() + ); } /// @@ -164,8 +172,7 @@ protected override SceneTypeSnapshot Build(TypeCacheSnapshot types) protected override void OnActivating( SceneTypeSnapshot? previous, SceneTypeSnapshot candidate - ) - => SceneStore.InvalidateAllTypeCaches(); + ) => SceneStore.InvalidateAllTypeCaches(); /// /// Restores state retained for the previous snapshot after candidate activation fails. @@ -179,13 +186,14 @@ SceneTypeSnapshot candidate protected override void OnActivationRolledBack( SceneTypeSnapshot? previous, SceneTypeSnapshot candidate - ) - => SceneStore.InvalidateAllTypeCaches(); + ) => SceneStore.InvalidateAllTypeCaches(); private static GameBehaviorLifecyclePhase GetBehaviorPhases(TypeCatalogMetadata metadata) { if (!typeof(GameBehavior).IsAssignableFrom(metadata.type)) + { return GameBehaviorLifecyclePhase.None; + } GameBehaviorLifecyclePhase phases = GameBehaviorLifecyclePhase.None; AddOverride("Awake", GameBehaviorLifecyclePhase.Awake); @@ -208,26 +216,25 @@ GameBehaviorLifecyclePhase phase } } } - } } internal sealed record SceneTypeSnapshot( long generation, - FrozenDictionary componentsByRuntimeId, - FrozenDictionary systemsByRuntimeId + FrozenDictionary componentsByRuntimeID, + FrozenDictionary systemsByRuntimeID ); internal sealed record SceneComponentTypeDescriptor( - int runtimeTypeId, + int runtimeTypeID, string displayName, bool isConcrete, bool allowsMultiple, GameBehaviorLifecyclePhase behaviorPhases, - int[] assignableConcreteRuntimeTypeIds, - FrozenSet assignableConcreteRuntimeTypeIdSet + int[] assignableConcreteRuntimeTypeIDs, + FrozenSet assignableConcreteRuntimeTypeIDSet ) { - internal bool IsAssignableFrom(int concreteRuntimeTypeId) => assignableConcreteRuntimeTypeIdSet.Contains(concreteRuntimeTypeId); + internal bool IsAssignableFrom(int concreteRuntimeTypeID) => assignableConcreteRuntimeTypeIDSet.Contains(concreteRuntimeTypeID); } [Flags] @@ -248,7 +255,7 @@ internal enum GameBehaviorLifecyclePhase } internal sealed record SceneSystemTypeDescriptor( - int runtimeTypeId, + int runtimeTypeID, string displayName, bool isConcrete, bool allowsMultiple diff --git a/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs b/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs index 3b2fde4a3..7f2468e78 100644 --- a/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs +++ b/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs @@ -16,52 +16,9 @@ namespace Inno.Core.Collections; /// dependency. The graph accepts cycles; operations that require an acyclic graph, /// such as , report them explicitly. /// -public sealed class DependencyGraph where TKey : notnull +public sealed class DependencyGraph + where TKey : notnull { - private sealed class Node - { - internal required long order; - internal HashSet dependencies = null!; - internal HashSet dependents = null!; - } - - private sealed class NodePriorityComparer(IComparer? orderingComparer) : IComparer - { - /// - /// Compares two values according to the deterministic ordering used by this collection. - /// - /// - /// The horizontal or first component. - /// - /// - /// The vertical or second component. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public int Compare( - NodePriority x, - NodePriority y - ) { - if (orderingComparer is not null) - { - int keyComparison = orderingComparer.Compare(x.key, y.key); - if (keyComparison != 0) - return keyComparison; - } - - return x.order.CompareTo(y.order); - } - } - - private readonly struct NodePriority( - TKey key, - long order - ) { - internal TKey key { get; } = key; - internal long order { get; } = order; - } - private readonly Dictionary m_nodes; private readonly IEqualityComparer m_equalityComparer; private readonly IComparer? m_orderingComparer; @@ -167,7 +124,9 @@ public bool AddNode(TKey node) try { if (!AddNodeLocked(node)) + { return false; + } m_version++; return true; @@ -193,18 +152,24 @@ public bool RemoveNode(TKey node) try { if (!m_nodes.Remove(node, out Node? removed)) + { return false; + } foreach (TKey dependency in removed.dependencies) { if (m_nodes.TryGetValue(dependency, out Node? dependencyNode)) + { dependencyNode.dependents.Remove(node); + } } foreach (TKey dependent in removed.dependents) { if (m_nodes.TryGetValue(dependent, out Node? dependentNode)) + { dependentNode.dependencies.Remove(node); + } } m_version++; @@ -238,7 +203,9 @@ TKey dependency AddNodeLocked(node); AddNodeLocked(dependency); if (!m_nodes[node].dependencies.Add(dependency)) + { return false; + } m_nodes[dependency].dependents.Add(node); m_version++; @@ -269,14 +236,16 @@ TKey dependency m_sync.EnterWriteLock(); try { - if (!m_nodes.TryGetValue(node, out Node? dependentNode) || - !dependentNode.dependencies.Remove(dependency)) - { + if (!m_nodes.TryGetValue(node, out Node? dependentNode) + || !dependentNode.dependencies.Remove(dependency) + ) { return false; } if (m_nodes.TryGetValue(dependency, out Node? dependencyNode)) + { dependencyNode.dependents.Remove(node); + } m_version++; return true; @@ -311,14 +280,20 @@ IEnumerable dependencies { bool changed = AddNodeLocked(node); foreach (TKey dependency in replacement) + { changed |= AddNodeLocked(dependency); + } Node target = m_nodes[node]; if (!changed && target.dependencies.SetEquals(replacement)) + { return; + } foreach (TKey previous in target.dependencies) + { m_nodes[previous].dependents.Remove(node); + } target.dependencies.Clear(); foreach (TKey dependency in replacement) @@ -350,8 +325,7 @@ IEnumerable dependencies public IReadOnlyList GetDependencies( TKey node, bool recursive = false - ) - => GetConnectedNodes(node, recursive, static value => value.dependencies); + ) => GetConnectedNodes(node, recursive, static value => value.dependencies); /// /// Gets direct or transitive dependents of a node. @@ -368,8 +342,7 @@ public IReadOnlyList GetDependencies( public IReadOnlyList GetDependents( TKey node, bool recursive = false - ) - => GetConnectedNodes(node, recursive, static value => value.dependents); + ) => GetConnectedNodes(node, recursive, static value => value.dependents); /// /// Determines whether one node directly or transitively depends on another. @@ -395,9 +368,13 @@ public bool DependsOn( try { if (!m_nodes.TryGetValue(node, out Node? start)) + { return false; + } if (!recursive) + { return start.dependencies.Contains(dependency); + } var visited = new HashSet(m_equalityComparer); var pending = new Stack(start.dependencies); @@ -405,11 +382,17 @@ public bool DependsOn( { TKey current = pending.Pop(); if (m_equalityComparer.Equals(current, dependency)) + { return true; + } if (!visited.Add(current) || !m_nodes.TryGetValue(current, out Node? currentNode)) + { continue; + } foreach (TKey next in currentNode.dependencies) + { pending.Push(next); + } } return false; @@ -440,7 +423,9 @@ public IReadOnlyList TopologicalSort() { remaining.Add(key, value.dependencies.Count); if (value.dependencies.Count == 0) + { ready.Enqueue(key, new NodePriority(key, value.order)); + } } var result = new List(m_nodes.Count); @@ -450,18 +435,21 @@ public IReadOnlyList TopologicalSort() foreach (TKey dependent in OrderNodes(m_nodes[current].dependents)) { if (--remaining[dependent] != 0) + { continue; + } Node dependentNode = m_nodes[dependent]; ready.Enqueue(dependent, new NodePriority(dependent, dependentNode.order)); } } if (result.Count == m_nodes.Count) + { return result.ToArray(); + } IReadOnlyList cycle = FindCycleLocked(); - throw new InvalidOperationException( - $"Dependency graph contains a cycle: {string.Join(" -> ", cycle)}."); + throw new InvalidOperationException($"Dependency graph contains a cycle: {string.Join(" -> ", cycle)}."); } finally { @@ -508,12 +496,14 @@ public IReadOnlyList> GetStronglyConnectedComponents() var lowLinks = new Dictionary(m_nodes.Count, m_equalityComparer); var active = new HashSet(m_equalityComparer); var stack = new Stack(); - var components = new List>(); + List> components = []; foreach (TKey node in OrderNodes(m_nodes.Keys)) { if (!indexes.ContainsKey(node)) + { Visit(node); + } } components.Sort(( @@ -544,9 +534,11 @@ void Visit(TKey node) } if (lowLinks[node] != indexes[node]) + { return; + } - var component = new List(); + List component = []; TKey current; do { @@ -575,7 +567,9 @@ public void Clear() try { if (m_nodes.Count == 0) + { return; + } m_nodes.Clear(); m_version++; } @@ -588,7 +582,9 @@ public void Clear() private bool AddNodeLocked(TKey node) { if (m_nodes.ContainsKey(node)) + { return false; + } m_nodes.Add(node, new Node { order = m_nextNodeOrder++, @@ -607,9 +603,13 @@ Func> selector try { if (!m_nodes.TryGetValue(node, out Node? start)) - return Array.Empty(); + { + return []; + } if (!recursive) + { return OrderNodes(selector(start)); + } var result = new HashSet(m_equalityComparer); var pending = new Stack(selector(start)); @@ -617,9 +617,13 @@ Func> selector { TKey current = pending.Pop(); if (!result.Add(current) || !m_nodes.TryGetValue(current, out Node? currentNode)) + { continue; + } foreach (TKey connected in selector(currentNode)) + { pending.Push(connected); + } } result.Remove(node); @@ -634,15 +638,17 @@ Func> selector private IReadOnlyList FindCycleLocked() { var states = new Dictionary(m_nodes.Count, m_equalityComparer); - var path = new List(); + List path = []; var pathIndexes = new Dictionary(m_nodes.Count, m_equalityComparer); foreach (TKey node in OrderNodes(m_nodes.Keys)) { if (!states.ContainsKey(node) && Visit(node, out IReadOnlyList? cycle)) + { return cycle; + } } - return Array.Empty(); + return []; bool Visit( TKey node, @@ -656,14 +662,18 @@ out IReadOnlyList cycle if (!states.TryGetValue(dependency, out byte state)) { if (Visit(dependency, out cycle)) + { return true; + } } else if (state == 1) { int start = pathIndexes[dependency]; var found = new List(path.Count - start + 1); for (int i = start; i < path.Count; i++) + { found.Add(path[i]); + } found.Add(dependency); cycle = found.ToArray(); return true; @@ -673,7 +683,7 @@ out IReadOnlyList cycle states[node] = 2; pathIndexes.Remove(node); path.RemoveAt(path.Count - 1); - cycle = Array.Empty(); + cycle = []; return false; } } @@ -693,8 +703,56 @@ TKey right { int comparison = m_orderingComparer.Compare(left, right); if (comparison != 0) + { return comparison; + } } return m_nodes[left].order.CompareTo(m_nodes[right].order); } + + private sealed class Node + { + internal required long order; + internal HashSet dependencies = null!; + internal HashSet dependents = null!; + } + + private sealed class NodePriorityComparer(IComparer? orderingComparer) : IComparer + { + /// + /// Compares two values according to the deterministic ordering used by this collection. + /// + /// + /// The horizontal or first component. + /// + /// + /// The vertical or second component. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public int Compare( + NodePriority x, + NodePriority y + ) { + if (orderingComparer is not null) + { + int keyComparison = orderingComparer.Compare(x.key, y.key); + if (keyComparison != 0) + { + return keyComparison; + } + } + + return x.order.CompareTo(y.order); + } + } + + private readonly struct NodePriority( + TKey key, + long order + ) { + internal TKey key { get; } = key; + internal long order { get; } = order; + } } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs new file mode 100644 index 000000000..28fe7069f --- /dev/null +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Collections; + +internal interface IIndexedObjectIndex + where T : class +{ + /// + /// Gets the human-readable name used for presentation and diagnostics. + /// + string name { get; } + + /// + /// Gets the key type accepted by this index implementation. + /// + Type keyType { get; } + + /// + /// Adds a new keyed value or atomically replaces the existing value for that key. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + void AddOrUpdate( + T item, + object key + ); + + /// + /// Removes the requested value while preserving the collection's invariants. + /// + /// + /// The stored item associated with the validated handle. + /// + void Remove(T item); + + /// + /// Removes all retained entries and returns the instance to an empty reusable state. + /// + void Clear(); + + /// + /// Retrieves the requested count value from current authoritative state. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + int GetCount(object key); + + /// + /// Attempts to get single without changing state when the operation cannot complete. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool TryGetSingle( + object key, + out T? item + ); + + /// + /// Determines whether current state contains the requested value value. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool Contains( + object key, + T item + ); + + /// + /// Retrieves the requested set value from current authoritative state. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The validated hash sett? that represents the completed operation. + /// + HashSet? GetSet(object key); +} diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs new file mode 100644 index 000000000..618595feb --- /dev/null +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Core.Collections; + +/// +/// Internal store validation surface for IndexedObjectKey. +/// +internal interface IIndexedObjectStore +{ + /// + /// Determines whether the key belongs to a live slot in the current storage generation. + /// + /// + /// The stable identity used to locate the requested value. + /// + /// + /// The key type consumed by is valid key; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool IsValidKey( + int id, + Type keyType + ); +} diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs index c9e5f20dc..051afc07e 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs @@ -8,7 +8,8 @@ namespace Inno.Core.Collections; /// /// Item type. /// -public readonly struct IndexedObjectEntry where T : class +public readonly struct IndexedObjectEntry + where T : class { private readonly IndexedObjectStore m_store; private readonly T m_item; diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs index b562731c0..e1eb0dc9c 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs @@ -4,114 +4,15 @@ namespace Inno.Core.Collections; -internal interface IIndexedObjectIndex where T : class -{ - /// - /// Gets the human-readable name used for presentation and diagnostics. - /// - string name { get; } - /// - /// Gets the key type accepted by this index implementation. - /// - Type keyType { get; } - /// - /// Adds a new keyed value or atomically replaces the existing value for that key. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - void AddOrUpdate( - T item, - object key - ); - /// - /// Removes the requested value while preserving the collection's invariants. - /// - /// - /// The stored item associated with the validated handle. - /// - void Remove(T item); - /// - /// Removes all retained entries and returns the instance to an empty reusable state. - /// - void Clear(); - /// - /// Retrieves the requested count value from current authoritative state. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - int GetCount(object key); - /// - /// Attempts to get single without changing state when the operation cannot complete. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool TryGetSingle( - object key, - out T? item - ); - /// - /// Determines whether current state contains the requested value value. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool Contains( - object key, - T item - ); - /// - /// Retrieves the requested set value from current authoritative state. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The validated hash sett? that represents the completed operation. - /// - HashSet? GetSet(object key); -} - -internal sealed class IndexedObjectIndex : IIndexedObjectIndex where T : class where TKey : notnull +internal sealed class IndexedObjectIndex : IIndexedObjectIndex + where T : class + where TKey : notnull { private readonly IKeyStorage m_storage; private readonly IKeyOrdering m_ordering; private readonly IComparer m_orderComparer; private readonly Dictionary m_keyByItem; - /// - /// Gets the human-readable name used for presentation and diagnostics. - /// - public string name { get; } - /// - /// Gets the key type accepted by this index implementation. - /// - public Type keyType => typeof(TKey); - /// - /// Gets the index capabilities supported by this key declaration. - /// - public IndexedObjectKeyFlags flags { get; } - internal IndexedObjectIndex( string name, IndexedObjectKeyFlags flags, @@ -121,46 +22,31 @@ internal IndexedObjectIndex( this.flags = flags; m_storage = (flags & IndexedObjectKeyFlags.Unique) != 0 - ? new UniqueKeyStorage() - : new MultiKeyStorage(); + ? new UniqueKeyStorage() + : new MultiKeyStorage(); m_orderComparer = orderComparer ?? Comparer.Default; m_ordering = (flags & IndexedObjectKeyFlags.Ordered) != 0 - ? new SortedKeyOrdering(m_orderComparer) - : new NullKeyOrdering(); + ? new SortedKeyOrdering(m_orderComparer) + : new NullKeyOrdering(); m_keyByItem = new Dictionary(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); } - void IIndexedObjectIndex.AddOrUpdate( - T item, - object key - ) - => AddOrUpdate(item, (TKey)key); - - void IIndexedObjectIndex.Remove(T item) - => Remove(item); - - void IIndexedObjectIndex.Clear() - => Clear(); - - int IIndexedObjectIndex.GetCount(object key) - => GetCount((TKey)key); - - bool IIndexedObjectIndex.TryGetSingle( - object key, - out T? item - ) - => TryGetSingle((TKey)key, out item); + /// + /// Gets the human-readable name used for presentation and diagnostics. + /// + public string name { get; } - bool IIndexedObjectIndex.Contains( - object key, - T item - ) - => Contains((TKey)key, item); + /// + /// Gets the key type accepted by this index implementation. + /// + public Type keyType => typeof(TKey); - HashSet? IIndexedObjectIndex.GetSet(object key) - => FindUnsafe((TKey)key); + /// + /// Gets the index capabilities supported by this key declaration. + /// + public IndexedObjectKeyFlags flags { get; } /// /// Adds a new keyed value or atomically replaces the existing value for that key. @@ -175,24 +61,32 @@ public void AddOrUpdate( T item, TKey key ) { - if (m_keyByItem.TryGetValue(item, out var oldKey)) + if (m_keyByItem.TryGetValue(item, out TKey? oldKey)) { if (EqualityComparer.Default.Equals(oldKey, key)) + { return; + } // Add first so a rejected unique key leaves the previous mapping intact. bool addedKey = m_storage.Add(key, item); m_storage.Remove(oldKey, item); if (m_storage.IsKeyEmpty(oldKey)) + { m_ordering.RemoveKey(oldKey); + } if (addedKey) + { m_ordering.AddKey(key); + } m_keyByItem[item] = key; return; } if (m_storage.Add(key, item)) + { m_ordering.AddKey(key); + } m_keyByItem[item] = key; } @@ -204,13 +98,17 @@ TKey key /// public void Remove(T item) { - if (!m_keyByItem.TryGetValue(item, out var key)) + if (!m_keyByItem.TryGetValue(item, out TKey? key)) + { return; + } m_keyByItem.Remove(item); m_storage.Remove(key, item); if (m_storage.IsKeyEmpty(key)) + { m_ordering.RemoveKey(key); + } } /// @@ -241,6 +139,29 @@ public bool TryGetSingle( out T? item ) => m_storage.TryGetSingle(key, out item); + void IIndexedObjectIndex.AddOrUpdate( + T item, + object key + ) => AddOrUpdate(item, (TKey)key); + + void IIndexedObjectIndex.Remove(T item) => Remove(item); + + void IIndexedObjectIndex.Clear() => Clear(); + + int IIndexedObjectIndex.GetCount(object key) => GetCount((TKey)key); + + bool IIndexedObjectIndex.TryGetSingle( + object key, + out T? item + ) => TryGetSingle((TKey)key, out item); + + bool IIndexedObjectIndex.Contains( + object key, + T item + ) => Contains((TKey)key, item); + + HashSet? IIndexedObjectIndex.GetSet(object key) => FindUnsafe((TKey)key); + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal HashSet? FindUnsafe(TKey key) => m_storage.GetSet(key); diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs index 9d44625a6..832e3bb6d 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs @@ -3,26 +3,6 @@ namespace Inno.Core.Collections; -/// -/// Defines indexing and cardinality behavior for an object-store key. -/// -[Flags] -public enum IndexedObjectKeyFlags -{ - /// - /// Uses hash-based lookup without key ordering. - /// - Unordered = 1 << 0, - /// - /// Maintains key ordering using the supplied comparer. - /// - Ordered = 1 << 1, - /// - /// Allows at most one item for each key value. - /// - Unique = 1 << 2, -} - /// /// Opaque handle used to query a key without exposing its implementation. /// @@ -33,12 +13,22 @@ public readonly struct IndexedObjectKey { internal readonly WeakReference? storeRef; internal readonly int id; - + /// /// Key name /// public readonly string name; - + + internal IndexedObjectKey( + WeakReference storeRef, + int id, + string name + ) { + this.storeRef = storeRef; + this.id = id; + this.name = name; + } + /// /// Returns true if the store key is still valid in its owning store. /// @@ -47,20 +37,32 @@ public bool isValid [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - if (storeRef == null || !storeRef.TryGetTarget(out var store)) + if (storeRef is null || !storeRef.TryGetTarget(out IIndexedObjectStore? store)) + { return false; + } return store.IsValidKey(id, typeof(TKey)); } } +} - internal IndexedObjectKey( - WeakReference storeRef, - int id, - string name - ) { - this.storeRef = storeRef; - this.id = id; - this.name = name; - } +/// +/// Defines indexing and cardinality behavior for an object-store key. +/// +[Flags] +public enum IndexedObjectKeyFlags +{ + /// + /// Uses hash-based lookup without key ordering. + /// + Unordered = 1 << 0, + /// + /// Maintains key ordering using the supplied comparer. + /// + Ordered = 1 << 1, + /// + /// Allows at most one item for each key value. + /// + Unique = 1 << 2 } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs index 7588262e9..07555e3b3 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs @@ -9,10 +9,11 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public sealed class IndexedObjectQuery where T : class +public sealed class IndexedObjectQuery + where T : class { private readonly IndexedObjectStore m_store; - private readonly List> m_conditions = new(); + private readonly List> m_conditions = []; private Func>? m_orderedFastExec; private Func>? m_orderedSnapshotExec; private Func? m_orderedFirstExec; @@ -33,8 +34,7 @@ internal IndexedObjectQuery(IndexedObjectStore store) /// public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) { - if (condition == null) - throw new ArgumentNullException(nameof(condition)); + ArgumentNullException.ThrowIfNull(condition); m_conditions.Add(condition); return this; @@ -50,7 +50,7 @@ public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) /// The same query instance. /// public IndexedObjectQuery Where(Func predicate) => Where(new IndexedObjectPredicateCondition(predicate)); - + /// /// Adds a key equality condition. /// @@ -60,12 +60,12 @@ public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) /// /// Key handle. /// - /// - /// The same query instance. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// The same query instance. + /// public IndexedObjectQuery Find( IndexedObjectKey key, TKey value @@ -83,10 +83,13 @@ TKey value /// /// The same query instance. /// - public IndexedObjectQuery OrderBy(IndexedObjectKey key) where TKey : notnull + public IndexedObjectQuery OrderBy(IndexedObjectKey key) + where TKey : notnull { if (!m_store.IsOrderedKey(key)) + { throw new InvalidOperationException($"Key '{key.name}' is not ordered."); + } m_orderedFastExec = () => m_store.ExecuteOrderedQueryFast(key, m_conditions); m_orderedSnapshotExec = () => m_store.ExecuteOrderedQuerySnapshot(key, m_conditions); @@ -97,13 +100,13 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) where TKe /// /// Executes the query and returns a lazy fail-fast enumerable of results. /// - /// - /// Enumeration is fail-fast and throws if the store is modified during iteration. - /// /// /// Lazy fail-fast enumerable of matching items. /// - public IEnumerable GetFast() => m_orderedFastExec != null ? m_orderedFastExec() : m_store.ExecuteQueryFast(m_conditions); + /// + /// Enumeration is fail-fast and throws if the store is modified during iteration. + /// + public IEnumerable GetFast() => m_orderedFastExec is not null ? m_orderedFastExec() : m_store.ExecuteQueryFast(m_conditions); /// /// Executes the query and returns a stable snapshot. @@ -111,7 +114,8 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) where TKe /// /// A snapshot list detached from subsequent store mutations. /// - public IReadOnlyList Get() => m_orderedSnapshotExec != null ? m_orderedSnapshotExec() : m_store.ExecuteQuerySnapshot(m_conditions); + public IReadOnlyList Get() + => m_orderedSnapshotExec is not null ? m_orderedSnapshotExec() : m_store.ExecuteQuerySnapshot(m_conditions); /// /// Executes the query and returns the first matching item or null. @@ -119,5 +123,5 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) where TKe /// /// The first matching item or null. /// - public T? First() => m_orderedFirstExec != null ? m_orderedFirstExec() : m_store.ExecuteFirst(m_conditions); + public T? First() => m_orderedFirstExec is not null ? m_orderedFirstExec() : m_store.ExecuteFirst(m_conditions); } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs index 2acff0ec4..73873489b 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs @@ -5,14 +5,16 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore -where T : class +public sealed partial class IndexedObjectStore + where T : class { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsValidItem(T item) { - if (item == null) + if (item is null) + { return false; + } m_lock.EnterReadLock(); try @@ -41,7 +43,7 @@ internal bool TryGetHandle( T item, out IndexedObjectRuntimeHandle handle ) { - if (item == null) + if (item is null) { handle = default; return false; @@ -146,13 +148,16 @@ private bool IsHandleValidNoLock(IndexedObjectRuntimeHandle handle) { int slot = handle.slot; if ((uint)slot >= (uint)m_generations.Count) + { return false; + } if (m_generations[slot] != handle.generation) + { return false; + } int denseIndex = m_sparseToDense[slot]; return denseIndex >= 0 && denseIndex < m_activeList.Count; } - } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs index 336b7248f..7c707b10f 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs @@ -5,8 +5,8 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore -where T : class +public sealed partial class IndexedObjectStore + where T : class { /// /// Defines a query key over stored items. @@ -33,19 +33,28 @@ public IndexedObjectKey DefineKey( ) where TKey : notnull { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("Key name is required.", nameof(name)); + } m_lock.EnterWriteLock(); try { if (m_indexByName.TryGetValue(name, out _)) + { throw new InvalidOperationException($"Key '{name}' already exists."); + } - if ((flags & IndexedObjectKeyFlags.Ordered) != 0 && orderComparer == null) - throw new ArgumentNullException(nameof(orderComparer), $"{nameof(orderComparer)} cannot be null when {nameof(flags)} is set to {nameof(IndexedObjectKeyFlags.Ordered)}.)"); + if ((flags & IndexedObjectKeyFlags.Ordered) != 0 && orderComparer is null) + { + throw new ArgumentNullException( + nameof(orderComparer), + $"{nameof(orderComparer)} cannot be null when {nameof(flags)} is set to {nameof(IndexedObjectKeyFlags.Ordered)}.)" + ); + } var index = new IndexedObjectIndex(name, flags, orderComparer); - var id = m_nextIndexId++; + int id = m_nextIndexID++; m_indexes[id] = index; m_indexByName[name] = id; BumpVersion(); @@ -75,8 +84,10 @@ public bool RemoveKey(IndexedObjectKey key) m_lock.EnterWriteLock(); try { - if (!m_indexes.Remove(key.id, out var removed)) + if (!m_indexes.Remove(key.id, out IIndexedObjectIndex? removed)) + { return false; + } m_indexByName.Remove(removed.name); BumpVersion(); @@ -109,18 +120,20 @@ out IndexedObjectKey key ) where TKey : notnull { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("Key name is required.", nameof(name)); + } m_lock.EnterReadLock(); try { - if (!m_indexByName.TryGetValue(name, out var id)) + if (!m_indexByName.TryGetValue(name, out int id)) { key = default; return false; } - if (!m_indexes.TryGetValue(id, out var index) || index.keyType != typeof(TKey)) + if (!m_indexes.TryGetValue(id, out IIndexedObjectIndex? index) || index.keyType != typeof(TKey)) { key = default; return false; @@ -135,6 +148,17 @@ out IndexedObjectKey key } } + /// + /// Gets all defined key names as a lazy enumerable. + /// + /// + /// Lazy enumerable of key names. + /// + /// + /// Enumeration is fail-fast and throws if the store is modified during iteration. + /// + public IEnumerable GetAllKeys() => EnumerateKeys(); + bool IIndexedObjectStore.IsValidKey( int id, Type keyType @@ -142,7 +166,7 @@ Type keyType m_lock.EnterReadLock(); try { - return m_indexes.TryGetValue(id, out var index) && index.keyType == keyType; + return m_indexes.TryGetValue(id, out IIndexedObjectIndex? index) && index.keyType == keyType; } finally { @@ -150,44 +174,10 @@ Type keyType } } - /// - /// Gets all defined key names as a lazy enumerable. - /// - /// - /// Enumeration is fail-fast and throws if the store is modified during iteration. - /// - /// - /// Lazy enumerable of key names. - /// - public IEnumerable GetAllKeys() => EnumerateKeys(); - - private IEnumerable EnumerateKeys() - { - var version = Volatile.Read(ref m_version); - foreach (var name in m_indexByName.Keys) - { - EnsureVersion(version); - yield return name; - } - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool IsOrderedKey(IndexedObjectKey key) where TKey : notnull - => (GetIndex(key).flags & IndexedObjectKeyFlags.Ordered) != 0; - - private IndexedObjectIndex GetIndex(IndexedObjectKey handle) where TKey : notnull - { - if (handle.storeRef == null || !handle.storeRef.TryGetTarget(out var owner) || !ReferenceEquals(owner, this)) - throw new InvalidOperationException($"Key '{handle.name}' does not belong to this store."); - - if (!m_indexes.TryGetValue(handle.id, out var index)) - throw new InvalidOperationException($"Key '{handle.name}' not found."); - - if (index.keyType != typeof(TKey)) - throw new InvalidOperationException($"Key '{handle.name}' type mismatch."); - - return (IndexedObjectIndex)index; - } + internal bool IsOrderedKey(IndexedObjectKey key) + where TKey : notnull + => (GetIndex(key).flags & IndexedObjectKeyFlags.Ordered) != 0; internal void SetKey( T item, @@ -199,7 +189,9 @@ TKey value try { if (!m_activeIndex.ContainsKey(item)) + { throw new InvalidOperationException("Item is not in the store."); + } GetIndex(key).AddOrUpdate(item, value); BumpVersion(); @@ -236,4 +228,34 @@ internal bool ContainsInSet( T item ) where TKey : notnull => GetIndex(key).Contains(value, item); + private IEnumerable EnumerateKeys() + { + int version = Volatile.Read(ref m_version); + foreach (string name in m_indexByName.Keys) + { + EnsureVersion(version); + yield return name; + } + } + + private IndexedObjectIndex GetIndex(IndexedObjectKey handle) + where TKey : notnull + { + if (handle.storeRef is null || !handle.storeRef.TryGetTarget(out IIndexedObjectStore? owner) || !ReferenceEquals(owner, this)) + { + throw new InvalidOperationException($"Key '{handle.name}' does not belong to this store."); + } + + if (!m_indexes.TryGetValue(handle.id, out IIndexedObjectIndex? index)) + { + throw new InvalidOperationException($"Key '{handle.name}' not found."); + } + + if (index.keyType != typeof(TKey)) + { + throw new InvalidOperationException($"Key '{handle.name}' type mismatch."); + } + + return (IndexedObjectIndex)index; + } } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs index 20fd94e13..37907797d 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs @@ -5,8 +5,8 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore -where T : class +public sealed partial class IndexedObjectStore + where T : class { internal IEnumerable ExecuteOrderedQueryFast( IndexedObjectKey orderKey, @@ -22,14 +22,16 @@ List> conditions m_lock.EnterReadLock(); try { - var index = GetIndex(orderKey); + IndexedObjectIndex index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); } if (TryBuildOrderedCandidates(index, conditions, out List>? candidates)) + { return SelectOrderedItems(candidates); + } return ScanOrderedSnapshot(index, conditions); } @@ -39,15 +41,77 @@ List> conditions } } + internal T? ExecuteOrderedFirst( + IndexedObjectKey orderKey, + List> conditions + ) where TKey : notnull + { + m_lock.EnterReadLock(); + try + { + IndexedObjectIndex index = GetIndex(orderKey); + if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) + { + throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); + } + + if (TryGetOrderedCandidateSeed(conditions, out int seedIndex, out int seedCount)) + { + if (seedCount == 0) + { + return null; + } + if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) + { + return ValidateConditions(conditions, single) ? single : null; + } + + HashSet? seed = conditions[seedIndex].GetSet(this); + if (seed is not null) + { + T? first = null; + TKey firstKey = default!; + int firstDenseIndex = int.MaxValue; + foreach (T item in seed) + { + if (!ValidateConditions(conditions, item) + || !index.TryGetKey(item, out TKey itemKey) + || !m_activeIndex.TryGetValue(item, out int denseIndex) + ) { + continue; + } + + int comparison = first is null ? -1 : index.CompareKeys(itemKey, firstKey); + if (comparison < 0 || comparison == 0 && denseIndex < firstDenseIndex) + { + first = item; + firstKey = itemKey; + firstDenseIndex = denseIndex; + } + } + return first; + } + } + + return ScanOrderedFirst(index, conditions); + } + finally + { + m_lock.ExitReadLock(); + } + } + private IEnumerable EnumerateOrderedQuery( IndexedObjectKey orderKey, List> conditions ) where TKey : notnull { - var version = Volatile.Read(ref m_version); - var index = GetIndex(orderKey); + int version = Volatile.Read(ref m_version); + IndexedObjectIndex index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) + { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); + } if (TryBuildOrderedCandidates(index, conditions, out List>? candidates)) { @@ -59,10 +123,10 @@ List> conditions yield break; } - foreach (var key in index.EnumerateOrderedKeys()) + foreach (TKey key in index.EnumerateOrderedKeys()) { EnsureVersion(version); - if (index.TryGetSingle(key, out var single) && single != null) + if (index.TryGetSingle(key, out T? single) && single is not null) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -75,16 +139,20 @@ List> conditions } if (ok) + { yield return single; + } continue; } - var set = index.FindUnsafe(key); - if (set == null || set.Count == 0) + HashSet? set = index.FindUnsafe(key); + if (set is null || set.Count == 0) + { continue; + } - foreach (var item in set) + foreach (T item in set) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -105,62 +173,6 @@ List> conditions } } - internal T? ExecuteOrderedFirst( - IndexedObjectKey orderKey, - List> conditions - ) where TKey : notnull - { - m_lock.EnterReadLock(); - try - { - var index = GetIndex(orderKey); - if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) - throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); - - if (TryGetOrderedCandidateSeed(conditions, out int seedIndex, out int seedCount)) - { - if (seedCount == 0) - return null; - if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) - { - return ValidateConditions(conditions, single) ? single : null; - } - - HashSet? seed = conditions[seedIndex].GetSet(this); - if (seed is not null) - { - T? first = null; - TKey firstKey = default!; - int firstDenseIndex = int.MaxValue; - foreach (T item in seed) - { - if (!ValidateConditions(conditions, item) || - !index.TryGetKey(item, out TKey itemKey) || - !m_activeIndex.TryGetValue(item, out int denseIndex)) - { - continue; - } - - int comparison = first is null ? -1 : index.CompareKeys(itemKey, firstKey); - if (comparison < 0 || comparison == 0 && denseIndex < firstDenseIndex) - { - first = item; - firstKey = itemKey; - firstDenseIndex = denseIndex; - } - } - return first; - } - } - - return ScanOrderedFirst(index, conditions); - } - finally - { - m_lock.ExitReadLock(); - } - } - private bool TryBuildOrderedCandidates( IndexedObjectIndex orderIndex, List> conditions, @@ -169,9 +181,13 @@ out List> candidates { candidates = []; if (!TryGetOrderedCandidateSeed(conditions, out int seedIndex, out int seedCount)) + { return false; + } if (seedCount == 0) + { return true; + } if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { @@ -181,9 +197,13 @@ out List> candidates HashSet? seed = conditions[seedIndex].GetSet(this); if (seed is null) + { return false; + } foreach (T item in seed) + { AddOrderedCandidate(orderIndex, conditions, candidates, item); + } SortOrderedCandidates(orderIndex, candidates); return true; } @@ -199,7 +219,9 @@ out int seedCount { int candidateCount = conditions[i].GetCandidateCount(this); if (candidateCount >= seedCount) + { continue; + } seedCount = candidateCount; seedIndex = i; } @@ -213,44 +235,42 @@ private void AddOrderedCandidate( T item ) where TKey : notnull { - if (ValidateConditions(conditions, item) && - orderIndex.TryGetKey(item, out TKey itemKey) && - m_activeIndex.TryGetValue(item, out int denseIndex)) - { + if (ValidateConditions(conditions, item) + && orderIndex.TryGetKey(item, out TKey itemKey) + && m_activeIndex.TryGetValue(item, out int denseIndex) + ) { candidates.Add(new OrderedCandidate(item, itemKey, denseIndex)); } } - private static IReadOnlyList SelectOrderedItems(List> candidates) where TKey : notnull - { - var result = new T[candidates.Count]; - for (int i = 0; i < candidates.Count; i++) - result[i] = candidates[i].item; - return result; - } - private IReadOnlyList ScanOrderedSnapshot( IndexedObjectIndex index, List> conditions ) where TKey : notnull { - var result = new List(); + List result = []; foreach (TKey key in index.EnumerateOrderedKeys()) { if (index.TryGetSingle(key, out T? single) && single is not null) { if (ValidateConditions(conditions, single)) + { result.Add(single); + } continue; } HashSet? set = index.FindUnsafe(key); if (set is null) + { continue; + } foreach (T item in set) { if (ValidateConditions(conditions, item)) + { result.Add(item); + } } } return result; @@ -266,22 +286,39 @@ List> conditions if (index.TryGetSingle(key, out T? single) && single is not null) { if (ValidateConditions(conditions, single)) + { return single; + } continue; } HashSet? set = index.FindUnsafe(key); if (set is null) + { continue; + } foreach (T item in set) { if (ValidateConditions(conditions, item)) + { return item; + } } } return null; } + private static IReadOnlyList SelectOrderedItems(List> candidates) + where TKey : notnull + { + var result = new T[candidates.Count]; + for (int i = 0; i < candidates.Count; i++) + { + result[i] = candidates[i].item; + } + return result; + } + private static void SortOrderedCandidates( IndexedObjectIndex index, List> candidates @@ -293,15 +330,13 @@ List> candidates { int comparison = index.CompareKeys(left.key, right.key); return comparison != 0 - ? comparison - : left.denseIndex.CompareTo(right.denseIndex); + ? comparison + : left.denseIndex.CompareTo(right.denseIndex); }); private readonly record struct OrderedCandidate( T item, TKey key, int denseIndex - ) - where TKey : notnull; - + ) where TKey : notnull; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs index bafe5caee..86baa4ba7 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs @@ -5,15 +5,12 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore -where T : class +public sealed partial class IndexedObjectStore + where T : class { /// /// Finds items by key and returns a lazy fail-fast enumerable. /// - /// - /// Enumeration throws if the store is modified during iteration. - /// /// /// Key type. /// @@ -26,21 +23,21 @@ sealed partial class IndexedObjectStore /// /// Lazy fail-fast enumerable of matching items. /// + /// + /// Enumeration throws if the store is modified during iteration. + /// public IEnumerable FindFast( IndexedObjectKey key, TKey value ) where TKey : notnull { - var index = GetIndex(key); + IndexedObjectIndex index = GetIndex(key); return EnumerateFind(index, value); } /// /// Finds items by key and returns a stable snapshot. /// - /// - /// The returned list is detached from subsequent store mutations. - /// /// /// Key type. /// @@ -53,6 +50,9 @@ TKey value /// /// A stable snapshot list of matching items. /// + /// + /// The returned list is detached from subsequent store mutations. + /// public IReadOnlyList Find( IndexedObjectKey key, TKey value @@ -61,7 +61,7 @@ TKey value m_lock.EnterReadLock(); try { - var index = GetIndex(key); + IndexedObjectIndex index = GetIndex(key); return BuildFindSnapshot(index, value); } finally @@ -70,56 +70,6 @@ TKey value } } - private IEnumerable EnumerateFind( - IndexedObjectIndex index, - TKey value - ) where TKey : notnull - { - var version = Volatile.Read(ref m_version); - if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out var single) && single != null) - { - EnsureVersion(version); - yield return single; - yield break; - } - - var set = index.FindUnsafe(value); - if (set == null || set.Count == 0) - yield break; - - foreach (var item in set) - { - EnsureVersion(version); - yield return item; - } - } - - private List BuildFindSnapshot( - IndexedObjectIndex index, - TKey value - ) where TKey : notnull - { - var result = new List(); - if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out var single) && single != null) - { - result.Add(single); - return result; - } - - var set = index.FindUnsafe(value); - if (set == null || set.Count == 0) - { - return result; - } - - foreach (var item in set) - { - result.Add(item); - } - - return result; - } - /// /// Returns the first item by key or null if none exists. /// @@ -143,8 +93,10 @@ TKey value m_lock.EnterReadLock(); try { - if (GetIndex(key).TryGetSingle(value, out var item)) + if (GetIndex(key).TryGetSingle(value, out T? item)) + { return item; + } return null; } finally @@ -156,12 +108,12 @@ TKey value /// /// Returns all stored items as a stable snapshot. /// - /// - /// The returned list is detached from subsequent store mutations. - /// /// /// A snapshot list of all stored items. /// + /// + /// The returned list is detached from subsequent store mutations. + /// public IReadOnlyList All() { m_lock.EnterReadLock(); @@ -180,16 +132,16 @@ public IReadOnlyList All() /// /// Returns all stored items as a lazy fail-fast enumerable. /// - /// - /// Enumeration throws if the store is modified during iteration. - /// /// /// Lazy fail-fast enumerable of all stored items. /// + /// + /// Enumeration throws if the store is modified during iteration. + /// public IEnumerable AllFast() { - var version = Volatile.Read(ref m_version); - foreach (var item in m_activeList) + int version = Volatile.Read(ref m_version); + foreach (T item in m_activeList) { EnsureVersion(version); yield return item; @@ -211,7 +163,7 @@ internal IReadOnlyList ExecuteQuerySnapshot(List(); + List result = []; if (conditions.Count == 0) { result.AddRange(m_activeList); @@ -235,7 +187,7 @@ internal IReadOnlyList ExecuteQuerySnapshot(List ExecuteQuerySnapshot(List? seed = conditions[seedIndex].GetSet(this); + if (seed is null) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -279,7 +231,7 @@ internal IReadOnlyList ExecuteQuerySnapshot(List ExecuteQuerySnapshot(List> conditions) + { + m_lock.EnterReadLock(); + try + { + if (conditions.Count == 0) + { + return m_activeList.Count > 0 ? m_activeList[0] : null; + } + + int seedIndex = 0; + int seedCount = conditions[0].GetCandidateCount(this); + + for (int i = 1; i < conditions.Count; i++) + { + int candidateCount = conditions[i].GetCandidateCount(this); + if (candidateCount < seedCount) + { + seedCount = candidateCount; + seedIndex = i; + } + } + + if (seedCount == 0) + { + return null; + } + + if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) + { + for (int i = 0; i < conditions.Count; i++) + { + if (!conditions[i].Validate(this, single)) + { + return null; + } + } + + return single; + } + + HashSet? seed = conditions[seedIndex].GetSet(this); + if (seed is null) + { + foreach (T item in m_activeList) + { + bool ok = true; + for (int i = 0; i < conditions.Count; i++) + { + if (!conditions[i].Validate(this, item)) + { + ok = false; + break; + } + } + + if (ok) + { + return item; + } + } + + return null; + } + + if (seed.Count == 0) + { + return null; + } + + foreach (T item in seed) + { + bool ok = true; + for (int i = 0; i < conditions.Count; i++) + { + if (!conditions[i].Validate(this, item)) + { + ok = false; + break; + } + } + + if (ok) + { + return item; + } + } + + return null; + } + finally + { + m_lock.ExitReadLock(); + } + } + + private IEnumerable EnumerateFind( + IndexedObjectIndex index, + TKey value + ) where TKey : notnull + { + int version = Volatile.Read(ref m_version); + if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out T? single) && single is not null) + { + EnsureVersion(version); + yield return single; + yield break; + } + + HashSet? set = index.FindUnsafe(value); + if (set is null || set.Count == 0) + { + yield break; + } + + foreach (T item in set) + { + EnsureVersion(version); + yield return item; + } + } + + private List BuildFindSnapshot( + IndexedObjectIndex index, + TKey value + ) where TKey : notnull + { + List result = []; + if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out T? single) && single is not null) + { + result.Add(single); + return result; + } + + HashSet? set = index.FindUnsafe(value); + if (set is null || set.Count == 0) + { + return result; + } + + foreach (T item in set) + { + result.Add(item); + } + + return result; + } + private IEnumerable EnumerateQuery(List> conditions) { - var version = Volatile.Read(ref m_version); + int version = Volatile.Read(ref m_version); if (conditions.Count == 0) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { EnsureVersion(version); yield return item; @@ -323,7 +423,7 @@ private IEnumerable EnumerateQuery(List> cond for (int i = 1; i < conditions.Count; i++) { - var candidateCount = conditions[i].GetCandidateCount(this); + int candidateCount = conditions[i].GetCandidateCount(this); if (candidateCount < seedCount) { seedCount = candidateCount; @@ -332,9 +432,11 @@ private IEnumerable EnumerateQuery(List> cond } if (seedCount == 0) + { yield break; + } - if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) + if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -347,15 +449,17 @@ private IEnumerable EnumerateQuery(List> cond } if (ok) + { yield return single; + } yield break; } - var seed = conditions[seedIndex].GetSet(this); - if (seed == null) + HashSet? seed = conditions[seedIndex].GetSet(this); + if (seed is null) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -378,9 +482,11 @@ private IEnumerable EnumerateQuery(List> cond } if (seed.Count == 0) + { yield break; + } - foreach (var item in seed) + foreach (T item in seed) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -400,90 +506,6 @@ private IEnumerable EnumerateQuery(List> cond } } - internal T? ExecuteFirst(List> conditions) - { - m_lock.EnterReadLock(); - try - { - if (conditions.Count == 0) - return m_activeList.Count > 0 ? m_activeList[0] : null; - - int seedIndex = 0; - int seedCount = conditions[0].GetCandidateCount(this); - - for (int i = 1; i < conditions.Count; i++) - { - var candidateCount = conditions[i].GetCandidateCount(this); - if (candidateCount < seedCount) - { - seedCount = candidateCount; - seedIndex = i; - } - } - - if (seedCount == 0) - return null; - - if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) - { - for (int i = 0; i < conditions.Count; i++) - { - if (!conditions[i].Validate(this, single)) - return null; - } - - return single; - } - - var seed = conditions[seedIndex].GetSet(this); - if (seed == null) - { - foreach (var item in m_activeList) - { - bool ok = true; - for (int i = 0; i < conditions.Count; i++) - { - if (!conditions[i].Validate(this, item)) - { - ok = false; - break; - } - } - - if (ok) - return item; - } - - return null; - } - - if (seed.Count == 0) - return null; - - foreach (var item in seed) - { - bool ok = true; - for (int i = 0; i < conditions.Count; i++) - { - if (!conditions[i].Validate(this, item)) - { - ok = false; - break; - } - } - - if (ok) - return item; - } - - return null; - } - finally - { - m_lock.ExitReadLock(); - } - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool ValidateConditions( List> conditions, @@ -492,9 +514,10 @@ T item for (int i = 0; i < conditions.Count; i++) { if (!conditions[i].Validate(this, item)) + { return false; + } } return true; } - } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs index cf86b683a..c121b275f 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs @@ -5,49 +5,27 @@ namespace Inno.Core.Collections; -/// -/// Internal store validation surface for IndexedObjectKey. -/// -internal interface IIndexedObjectStore -{ - /// - /// Determines whether the key belongs to a live slot in the current storage generation. - /// - /// - /// The stable identity used to locate the requested value. - /// - /// - /// The key type consumed by is valid key; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool IsValidKey( - int id, - Type keyType - ); -} - /// /// Thread-safe object store with optional query keys over stored items. /// /// /// The stored reference type. /// -public sealed partial class IndexedObjectStore : IIndexedObjectStore where T : class +public sealed partial class IndexedObjectStore : IIndexedObjectStore + where T : class { private readonly WeakReference m_storeRef; - private readonly List m_activeList = new(); + private readonly List m_activeList = []; private readonly Dictionary m_activeIndex = new(ReferenceEqualityComparer.INSTANCE); private readonly Dictionary m_handleByItem = new(ReferenceEqualityComparer.INSTANCE); - private readonly List m_sparseToDense = new(); - private readonly List m_generations = new(); - private readonly List m_denseToSlot = new(); - private Stack m_freeSlots = new(); - private readonly Dictionary> m_indexes = new(); + private readonly List m_sparseToDense = []; + private readonly List m_generations = []; + private readonly List m_denseToSlot = []; + private readonly Dictionary> m_indexes = []; private readonly Dictionary m_indexByName = new(StringComparer.Ordinal); private readonly ReaderWriterLockSlim m_lock = new(LockRecursionPolicy.NoRecursion); - private int m_nextIndexId = 1; + private Stack m_freeSlots = new(); + private int m_nextIndexID = 1; private int m_version; /// @@ -97,7 +75,7 @@ public void Clear() m_freeSlots = new Stack(); m_indexes.Clear(); m_indexByName.Clear(); - m_nextIndexId = 1; + m_nextIndexID = 1; BumpVersion(); } finally @@ -129,8 +107,10 @@ public void RemoveAll() m_activeIndex.Clear(); m_handleByItem.Clear(); m_denseToSlot.Clear(); - foreach (var index in m_indexes.Values) + foreach (IIndexedObjectIndex index in m_indexes.Values) + { index.Clear(); + } BumpVersion(); } finally @@ -150,8 +130,7 @@ public void RemoveAll() /// public IndexedObjectEntry Add(T item) { - if (item == null) - throw new ArgumentNullException(nameof(item)); + ArgumentNullException.ThrowIfNull(item); m_lock.EnterWriteLock(); try @@ -187,22 +166,25 @@ public IndexedObjectEntry Add(T item) /// public bool Remove(T item) { - if (item == null) - throw new ArgumentNullException(nameof(item)); + ArgumentNullException.ThrowIfNull(item); m_lock.EnterWriteLock(); try { - if (!m_activeIndex.TryGetValue(item, out var index)) + if (!m_activeIndex.TryGetValue(item, out int index)) + { return false; + } - foreach (var objectIndex in m_indexes.Values) + foreach (IIndexedObjectIndex objectIndex in m_indexes.Values) + { objectIndex.Remove(item); + } - var lastIndex = m_activeList.Count - 1; - var lastItem = m_activeList[lastIndex]; - var removedSlot = m_denseToSlot[index]; - var lastSlot = m_denseToSlot[lastIndex]; + int lastIndex = m_activeList.Count - 1; + T lastItem = m_activeList[lastIndex]; + int removedSlot = m_denseToSlot[index]; + int lastSlot = m_denseToSlot[lastIndex]; m_activeList.RemoveAt(lastIndex); m_denseToSlot.RemoveAt(lastIndex); m_activeIndex.Remove(item); @@ -233,10 +215,13 @@ public bool Remove(T item) private void EnsureVersion(int expected) { if (Volatile.Read(ref m_version) != expected) + { throw new InvalidOperationException("Collection was modified during enumeration."); + } } - internal sealed class ReferenceEqualityComparer : IEqualityComparer where TItem : class + internal sealed class ReferenceEqualityComparer : IEqualityComparer + where TItem : class { /// /// The instance value used as part of this type's public representation. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs index d5a0d04cd..7daf4f976 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal interface IKeyOrdering where TKey : notnull +internal interface IKeyOrdering + where TKey : notnull { /// /// Adds one key to the indexed membership set. @@ -11,6 +12,7 @@ internal interface IKeyOrdering where TKey : notnull /// The backend-neutral physical key associated with this event. /// void AddKey(TKey key); + /// /// Removes one key from the indexed membership set. /// @@ -18,10 +20,12 @@ internal interface IKeyOrdering where TKey : notnull /// The backend-neutral physical key associated with this event. /// void RemoveKey(TKey key); + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// void Clear(); + /// /// Enumerates a stable view of the currently indexed keys. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs index 757bb3b35..7ae8aecaf 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal sealed class NullKeyOrdering : IKeyOrdering where TKey : notnull +internal sealed class NullKeyOrdering : IKeyOrdering + where TKey : notnull { /// /// Adds one key to the indexed membership set. @@ -10,18 +11,21 @@ internal sealed class NullKeyOrdering : IKeyOrdering where TKey : no /// /// The backend-neutral physical key associated with this event. /// - public void AddKey(TKey key) { } + public void AddKey(TKey key) {} + /// /// Removes one key from the indexed membership set. /// /// /// The backend-neutral physical key associated with this event. /// - public void RemoveKey(TKey key) { } + public void RemoveKey(TKey key) {} + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// - public void Clear() { } + public void Clear() {} + /// /// Enumerates a stable view of the currently indexed keys. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs index b8b874a47..53aef8dcb 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal sealed class SortedKeyOrdering : IKeyOrdering where TKey : notnull +internal sealed class SortedKeyOrdering : IKeyOrdering + where TKey : notnull { private readonly SortedSet m_keys; @@ -46,7 +47,9 @@ public SortedKeyOrdering(IComparer comparer) /// public IEnumerable Enumerate() { - foreach (var key in m_keys) + foreach (TKey key in m_keys) + { yield return key; + } } } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs index 63ad64a69..e48811d70 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs @@ -2,7 +2,9 @@ namespace Inno.Core.Collections; -internal interface IKeyStorage where T : class where TKey : notnull +internal interface IKeyStorage + where T : class + where TKey : notnull { /// /// Adds the supplied value while preserving the collection's invariants. @@ -20,6 +22,7 @@ bool Add( TKey key, T item ); + /// /// Removes the requested value while preserving the collection's invariants. /// @@ -33,6 +36,7 @@ void Remove( TKey key, T item ); + /// /// Attempts to get single without changing state when the operation cannot complete. /// @@ -49,6 +53,7 @@ bool TryGetSingle( TKey key, out T? item ); + /// /// Retrieves the requested count value from current authoritative state. /// @@ -59,6 +64,7 @@ out T? item /// The scalar result calculated from the supplied inputs. /// int GetCount(TKey key); + /// /// Determines whether current state contains the requested value value. /// @@ -75,6 +81,7 @@ bool Contains( TKey key, T item ); + /// /// Determines whether a key currently has no indexed values. /// @@ -85,6 +92,7 @@ T item /// when the requested condition is satisfied; otherwise, . /// bool IsKeyEmpty(TKey key); + /// /// Retrieves the requested set value from current authoritative state. /// @@ -95,6 +103,7 @@ T item /// The validated hash sett? that represents the completed operation. /// HashSet? GetSet(TKey key); + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs index 32f8d6afa..e0d124693 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs @@ -3,11 +3,14 @@ namespace Inno.Core.Collections; -internal sealed class MultiKeyStorage : IKeyStorage where T : class where TKey : notnull +internal sealed class MultiKeyStorage : IKeyStorage + where T : class + where TKey : notnull { - private readonly Dictionary> m_map = new(EqualityComparer.Default); private static readonly HashSet EMPTY_SET = new(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); + private readonly Dictionary> m_map = new(EqualityComparer.Default); + /// /// Adds the supplied value while preserving the collection's invariants. /// @@ -24,13 +27,13 @@ public bool Add( TKey key, T item ) { - if (!m_map.TryGetValue(key, out var set)) + if (!m_map.TryGetValue(key, out HashSet? set)) { set = new HashSet(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); m_map[key] = set; } - var added = set.Add(item); + bool added = set.Add(item); return added && set.Count == 1; } @@ -47,12 +50,16 @@ public void Remove( TKey key, T item ) { - if (!m_map.TryGetValue(key, out var set)) + if (!m_map.TryGetValue(key, out HashSet? set)) + { return; + } set.Remove(item); if (set.Count == 0) + { m_map.Remove(key); + } } /// @@ -72,12 +79,16 @@ public bool TryGetSingle( out T? item ) { item = null; - if (!m_map.TryGetValue(key, out var set) || set.Count == 0) + if (!m_map.TryGetValue(key, out HashSet? set) || set.Count == 0) + { return false; + } - using var e = set.GetEnumerator(); + using HashSet.Enumerator e = set.GetEnumerator(); if (!e.MoveNext()) + { return false; + } item = e.Current; return true; @@ -93,7 +104,7 @@ out T? item /// The scalar result calculated from the supplied inputs. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetCount(TKey key) => m_map.TryGetValue(key, out var set) ? set.Count : 0; + public int GetCount(TKey key) => m_map.TryGetValue(key, out HashSet? set) ? set.Count : 0; /// /// Determines whether current state contains the requested value value. @@ -111,7 +122,7 @@ out T? item public bool Contains( TKey key, T item - ) => m_map.TryGetValue(key, out var set) && set.Contains(item); + ) => m_map.TryGetValue(key, out HashSet? set) && set.Contains(item); /// /// Determines whether a key currently has no indexed values. @@ -123,7 +134,7 @@ T item /// when the requested condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool IsKeyEmpty(TKey key) => !m_map.TryGetValue(key, out var set) || set.Count == 0; + public bool IsKeyEmpty(TKey key) => !m_map.TryGetValue(key, out HashSet? set) || set.Count == 0; /// /// Retrieves the requested set value from current authoritative state. @@ -135,7 +146,7 @@ T item /// The validated hash sett? that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public HashSet? GetSet(TKey key) => m_map.TryGetValue(key, out var set) ? set : EMPTY_SET; + public HashSet? GetSet(TKey key) => m_map.TryGetValue(key, out HashSet? set) ? set : EMPTY_SET; /// /// Removes all retained entries and returns the instance to an empty reusable state. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs index 54dbe6f4b..d463afed1 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs @@ -4,7 +4,9 @@ namespace Inno.Core.Collections; -internal sealed class UniqueKeyStorage : IKeyStorage where T : class where TKey : notnull +internal sealed class UniqueKeyStorage : IKeyStorage + where T : class + where TKey : notnull { private readonly Dictionary m_map = new(EqualityComparer.Default); @@ -24,8 +26,10 @@ public bool Add( TKey key, T item ) { - if (m_map.TryGetValue(key, out var existing) && !ReferenceEquals(existing, item)) + if (m_map.TryGetValue(key, out T? existing) && !ReferenceEquals(existing, item)) + { throw new InvalidOperationException($"Duplicate key '{key}' in unique index."); + } m_map[key] = item; return true; @@ -44,8 +48,10 @@ public void Remove( TKey key, T item ) { - if (m_map.TryGetValue(key, out var existing) && ReferenceEquals(existing, item)) + if (m_map.TryGetValue(key, out T? existing) && ReferenceEquals(existing, item)) + { m_map.Remove(key); + } } /// @@ -93,7 +99,7 @@ out T? item public bool Contains( TKey key, T item - ) => m_map.TryGetValue(key, out var existing) && ReferenceEquals(existing, item); + ) => m_map.TryGetValue(key, out T? existing) && ReferenceEquals(existing, item); /// /// Determines whether a key currently has no indexed values. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs index 2b442b274..13b2e86f3 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs @@ -8,7 +8,8 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public interface IIndexedObjectQueryCondition where T : class +public interface IIndexedObjectQueryCondition + where T : class { /// /// Returns the estimated match count for this condition. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs index 4d90cd2b8..aa51f78dd 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs @@ -12,7 +12,9 @@ namespace Inno.Core.Collections; /// /// The indexed key type. /// -public sealed class IndexedObjectKeyCondition : IIndexedObjectQueryCondition where T : class where TKey : notnull +public sealed class IndexedObjectKeyCondition : IIndexedObjectQueryCondition + where T : class + where TKey : notnull { private readonly IndexedObjectKey m_key; private readonly TKey m_value; @@ -37,12 +39,12 @@ TKey value /// /// Gets a candidate count required by the implemented contract. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The store consumed by get candidate count; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetCandidateCount(IndexedObjectStore store) => store.GetCountUnsafe(m_key, m_value); @@ -63,7 +65,7 @@ public bool TryGetSingle( IndexedObjectStore store, out T item ) { - if (store.TryGetSingleUnsafe(m_key, m_value, out var found) && found != null) + if (store.TryGetSingleUnsafe(m_key, m_value, out T? found) && found is not null) { item = found; return true; @@ -76,12 +78,12 @@ out T item /// /// Gets a set required by the implemented contract. /// - /// - /// The validated hash sett? that represents the completed operation. - /// /// /// The store consumed by get set; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The validated hash sett? that represents the completed operation. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public HashSet? GetSet(IndexedObjectStore store) => store.GetSetUnsafe(m_key, m_value); @@ -91,12 +93,12 @@ out T item /// /// The store consumed by validate; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The stored item associated with the validated handle. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Validate( IndexedObjectStore store, diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs index 579df11fe..87ed88892 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs @@ -10,7 +10,8 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public sealed class IndexedObjectPredicateCondition : IIndexedObjectQueryCondition where T : class +public sealed class IndexedObjectPredicateCondition : IIndexedObjectQueryCondition + where T : class { private readonly Func m_predicate; @@ -76,12 +77,12 @@ out T item /// /// The store consumed by validate; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The stored item associated with the validated handle. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Validate( IndexedObjectStore store, diff --git a/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs b/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs index 5587df7e8..364263196 100644 --- a/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs +++ b/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs @@ -41,10 +41,8 @@ public bool isValid } internal bool IsOwnedBy(CoroutineScheduler scheduler) - { - return m_id > 0 - && m_schedulerRef is not null - && m_schedulerRef.TryGetTarget(out CoroutineScheduler? target) - && ReferenceEquals(target, scheduler); - } + => m_id > 0 + && m_schedulerRef is not null + && m_schedulerRef.TryGetTarget(out CoroutineScheduler? target) + && ReferenceEquals(target, scheduler); } diff --git a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs index c8a108e49..750ec7b15 100644 --- a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs +++ b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs @@ -14,12 +14,12 @@ namespace Inno.Core.Coroutines; public sealed class CoroutineScheduler : IDisposable { private readonly ConcurrentQueue m_commands = new(); - private readonly ConcurrentDictionary m_liveIds = new(); - private readonly Dictionary m_states = new(); - private readonly List m_active = new(); + private readonly ConcurrentDictionary m_liveIDs = new(); + private readonly Dictionary m_states = []; + private readonly List m_active = []; private readonly Lock m_tickGate = new(); private readonly WeakReference m_selfRef; - private long m_nextId; + private long m_nextID; private int m_disposed; private double m_now; private ulong m_frame; @@ -46,10 +46,7 @@ public CoroutineScheduler() /// /// Coroutine handle. /// - public CoroutineHandle StartCoroutine(IEnumerator routine) - { - return StartCoroutine(null, routine); - } + public CoroutineHandle StartCoroutine(IEnumerator routine) => StartCoroutine(null, routine); /// /// Starts a coroutine with an owner token. @@ -73,8 +70,8 @@ IEnumerator routine { ObjectDisposedException.ThrowIf(Volatile.Read(ref m_disposed) != 0, this); - long id = Interlocked.Increment(ref m_nextId); - m_liveIds[id] = 0; + long id = Interlocked.Increment(ref m_nextID); + m_liveIDs[id] = 0; m_commands.Enqueue(Command.Start(id, owner, routine)); return new CoroutineHandle(id, m_selfRef); } @@ -100,6 +97,19 @@ public bool StopCoroutine(CoroutineHandle handle) return true; } + /// + /// Requests stopping all active coroutines. + /// + public void StopAllCoroutines() + { + if (Volatile.Read(ref m_disposed) != 0) + { + return; + } + + m_commands.Enqueue(Command.StopAll()); + } + /// /// Stops owned coroutines and disposes their nested enumerators in reverse order. /// Reentrant calls defer cleanup of an executing callback until that callback returns. @@ -133,19 +143,6 @@ public void StopAllCoroutines(object owner) } } - /// - /// Requests stopping all active coroutines. - /// - public void StopAllCoroutines() - { - if (Volatile.Read(ref m_disposed) != 0) - { - return; - } - - m_commands.Enqueue(Command.StopAll()); - } - /// /// Closes admission and disposes all active and pending enumerators. /// Reentrant disposal retires the executing enumerator after its callback returns. @@ -158,7 +155,9 @@ public void Dispose() lock (m_tickGate) { if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { return; + } m_operationDepth++; try @@ -174,9 +173,6 @@ public void Dispose() } } - internal double now => m_now; - internal ulong frame => m_frame; - /// /// Advances coroutine execution by one frame. /// @@ -204,7 +200,9 @@ public void Tick(float deltaTime) ObjectDisposedException.ThrowIf(Volatile.Read(ref m_disposed) != 0, this); if (m_ticking || m_operationDepth != 0) + { throw new InvalidOperationException("A coroutine callback cannot recursively advance its scheduler."); + } m_operationDepth++; m_ticking = true; @@ -224,6 +222,9 @@ public void Tick(float deltaTime) } } + internal double now => m_now; + internal ulong frame => m_frame; + internal bool Contains(CoroutineHandle handle) { if (handle.IsOwnedBy(this)) @@ -234,16 +235,15 @@ internal bool Contains(CoroutineHandle handle) return handle.isValid; } - internal bool IsHandleValid(long id) - { - return Volatile.Read(ref m_disposed) == 0 && id > 0 && m_liveIds.ContainsKey(id); - } + internal bool IsHandleValid(long id) => Volatile.Read(ref m_disposed) == 0 && id > 0 && m_liveIDs.ContainsKey(id); private void ApplyPendingCommands() { // Cleanup callbacks may enqueue commands, but must not recursively drain the queue. if (m_applyingCommands) + { return; + } m_applyingCommands = true; try @@ -254,23 +254,31 @@ private void ApplyPendingCommands() { case CommandKind.Start: if (cmd.routine is null) + { break; - CoroutineState state = new(cmd.id, cmd.owner, cmd.routine); + } + var state = new CoroutineState(cmd.id, cmd.owner, cmd.routine); m_states.Add(state.id, state); m_active.Add(state.id); if (Volatile.Read(ref m_disposed) != 0) + { Retire(state); + } break; case CommandKind.Stop: if (m_states.TryGetValue(cmd.id, out CoroutineState? stopped)) + { Retire(stopped); + } break; case CommandKind.StopByOwner: for (int i = 0; i < m_active.Count; i++) { if (m_states.TryGetValue(m_active[i], out CoroutineState? owned) - && ReferenceEquals(owned.owner, cmd.owner)) + && ReferenceEquals(owned.owner, cmd.owner) + ) { Retire(owned); + } } break; case CommandKind.StopAll: @@ -283,7 +291,9 @@ private void ApplyPendingCommands() { m_applyingCommands = false; if (!m_ticking) + { PruneInactive(); + } } } @@ -295,13 +305,17 @@ private void TickActiveCoroutines() for (int i = 0; i < count; i++) { if (!m_states.TryGetValue(m_active[i], out CoroutineState? state)) + { continue; + } state.executing = true; try { if (!StepCoroutine(state)) + { Retire(state); + } } catch (Exception failure) { @@ -312,7 +326,9 @@ private void TickActiveCoroutines() { state.executing = false; if (state.retired) + { DisposeStack(state); + } } } } @@ -324,9 +340,13 @@ private bool StepCoroutine(CoroutineState state) { bool waiting = state.waiter.Invoke(this); if (state.retired) + { return false; + } if (waiting) + { return true; + } state.waiter = null; } @@ -340,18 +360,24 @@ private bool AdvanceCoroutine(CoroutineState state) IEnumerator current = state.stack.Peek(); bool moved = current.MoveNext(); if (state.retired) + { return false; + } if (!moved) { state.stack.Pop(); if (!DisposeEnumerator(current)) + { return false; + } continue; } object? yielded = current.Current; if (state.retired) + { return false; + } if (yielded is null) { ulong targetFrame = m_frame + 1; @@ -364,7 +390,9 @@ private bool AdvanceCoroutine(CoroutineState state) foreach (IEnumerator ancestor in state.stack) { if (ReferenceEquals(ancestor, nested)) + { throw new InvalidOperationException("A coroutine cannot yield an enumerator already on its stack."); + } } state.stack.Push(nested); continue; @@ -397,14 +425,18 @@ private bool AdvanceCoroutine(CoroutineState state) private void Retire(CoroutineState state) { if (state.retired) + { return; + } state.retired = true; m_needsPruning = true; m_states.Remove(state.id); - m_liveIds.TryRemove(state.id, out _); + m_liveIDs.TryRemove(state.id, out _); state.waiter = null; if (!state.executing) + { DisposeStack(state); + } } private void RetireAll() @@ -412,7 +444,9 @@ private void RetireAll() for (int i = 0; i < m_active.Count; i++) { if (m_states.TryGetValue(m_active[i], out CoroutineState? state)) + { Retire(state); + } } } @@ -424,7 +458,9 @@ private void DisposeStack(CoroutineState state) try { while (state.stack.TryPop(out IEnumerator? routine)) + { DisposeEnumerator(routine); + } } finally { @@ -436,7 +472,9 @@ private void DisposeStack(CoroutineState state) private bool DisposeEnumerator(IEnumerator routine) { if (routine is not IDisposable disposable) + { return true; + } try { disposable.Dispose(); @@ -452,16 +490,22 @@ private bool DisposeEnumerator(IEnumerator routine) private void PruneInactive() { if (!m_needsPruning || m_ticking || m_applyingCommands) + { return; + } int retained = 0; for (int i = 0; i < m_active.Count; i++) { long id = m_active[i]; if (m_states.ContainsKey(id)) + { m_active[retained++] = id; + } } if (retained != m_active.Count) + { m_active.RemoveRange(retained, m_active.Count - retained); + } m_needsPruning = false; } @@ -470,7 +514,9 @@ private void PruneInactive() private void CompleteOperation() { if (--m_operationDepth != 0 || m_failures is null) + { return; + } List failures = m_failures; m_failures = null; throw new AggregateException("Coroutine execution or retirement failed; all eligible cleanup was attempted.", failures); @@ -494,14 +540,17 @@ private readonly struct Command( /// Gets the operation kind that determines how this value is interpreted. /// public CommandKind kind { get; } = kind; + /// /// Gets the stable identity used to reference this value across subsystem boundaries. /// public long id { get; } = id; + /// /// Gets the object that owns the coroutine lifetime. /// public object? owner { get; } = owner; + /// /// Gets the root enumerator advanced by this coroutine. /// @@ -568,22 +617,27 @@ IEnumerator routine /// Gets the stable identity used to reference this value across subsystem boundaries. /// public long id { get; } = id; + /// /// Gets the object that owns the coroutine lifetime. /// public object? owner { get; set; } = owner; + /// /// Gets the nested enumerator stack retained by this coroutine. /// public Stack stack { get; } = new([routine]); + /// /// Gets the current continuation predicate, or null when the coroutine can advance. /// public CoroutineWaitDelegate? waiter { get; set; } + /// /// Gets whether a user callback is borrowing the enumerator stack. /// public bool executing { get; set; } + /// /// Gets whether call admission has closed and the remaining stack must retire. /// diff --git a/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs b/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs index a9c6a7b8b..4bf5440b6 100644 --- a/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs +++ b/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs @@ -1,7 +1,5 @@ namespace Inno.Core.Coroutines; -internal delegate bool CoroutineWaitDelegate(CoroutineScheduler scheduler); - /// /// Base type for the scheduler's built-in coroutine wait instructions. /// @@ -16,3 +14,5 @@ internal abstract CoroutineWaitDelegate CreateWaiter( ulong frame ); } + +internal delegate bool CoroutineWaitDelegate(CoroutineScheduler scheduler); diff --git a/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs b/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs index f479adc90..70cbbd92f 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs @@ -7,6 +7,19 @@ namespace Inno.Core.Diagnostics; /// public sealed class Diagnostic { + private Diagnostic( + DiagnosticSeverity severity, + string code, + string message, + DiagnosticLocation? location + ) { + ArgumentNullException.ThrowIfNull(message); + this.severity = severity; + this.code = code ?? string.Empty; + this.message = message; + this.location = location; + } + /// /// Creates a neutral diagnostic while keeping protocol, object and file identities distinct. /// @@ -19,10 +32,10 @@ public sealed class Diagnostic /// /// The common engine impact classification. /// - /// + /// /// An optional extension or protocol identifier, never interpreted as a file path. /// - /// + /// /// An optional persistent object identity, never a runtime handle. /// /// @@ -38,28 +51,49 @@ public Diagnostic( string code, string message, DiagnosticSeverity severity, - string? semanticId = null, - Guid? objectId = null, + string? semanticID = null, + Guid? objectID = null, DiagnosticLocation? location = null - ) - : this(severity, code, message, location) + ) : this(severity, code, message, location) { ArgumentException.ThrowIfNullOrWhiteSpace(code); - if (objectId == Guid.Empty) - throw new ArgumentException("A diagnostic object identity cannot be empty.", nameof(objectId)); - this.semanticId = semanticId; - this.objectId = objectId; + if (objectID == Guid.Empty) + { + throw new ArgumentException("A diagnostic object identity cannot be empty.", nameof(objectID)); + } + this.semanticID = semanticID; + this.objectID = objectID; } /// /// Gets the related protocol identifier without treating it as a source file. /// - public string? semanticId { get; } + public string? semanticID { get; } /// /// Gets the related persistent object identity, or null for a non-object issue. /// - public Guid? objectId { get; } + public Guid? objectID { get; } + + /// + /// Gets the diagnostic severity. + /// + public DiagnosticSeverity severity { get; } + + /// + /// Gets the stable producer-defined code, or an empty string when unavailable. + /// + public string code { get; } + + /// + /// Gets the human-readable diagnostic message. + /// + public string message { get; } + + /// + /// Gets the related source location, or when unavailable. + /// + public DiagnosticLocation? location { get; } /// /// Creates an informational diagnostic value without publishing it. @@ -83,8 +117,7 @@ public static Diagnostic Info( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Info, code, message, location); + ) => new(DiagnosticSeverity.Info, code, message, location); /// /// Creates a warning diagnostic value without publishing it. @@ -108,8 +141,7 @@ public static Diagnostic Warning( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Warning, code, message, location); + ) => new(DiagnosticSeverity.Warning, code, message, location); /// /// Creates an error diagnostic value without publishing it. @@ -133,39 +165,5 @@ public static Diagnostic Error( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Error, code, message, location); - - private Diagnostic( - DiagnosticSeverity severity, - string code, - string message, - DiagnosticLocation? location - ) { - ArgumentNullException.ThrowIfNull(message); - this.severity = severity; - this.code = code ?? string.Empty; - this.message = message; - this.location = location; - } - - /// - /// Gets the diagnostic severity. - /// - public DiagnosticSeverity severity { get; } - - /// - /// Gets the stable producer-defined code, or an empty string when unavailable. - /// - public string code { get; } - - /// - /// Gets the human-readable diagnostic message. - /// - public string message { get; } - - /// - /// Gets the related source location, or when unavailable. - /// - public DiagnosticLocation? location { get; } + ) => new(DiagnosticSeverity.Error, code, message, location); } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs index 94ce98331..280349fd9 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs @@ -7,28 +7,25 @@ namespace Inno.Core.Diagnostics; internal static class DiagnosticCallerResolver { - private sealed class CallerInfo - { - internal required string sourcePrefix { get; init; } - } - private static readonly ConditionalWeakTable CALLERS = new(); [MethodImpl(MethodImplOptions.NoInlining)] internal static DiagnosticSource Resolve( string group, - Guid? targetId = null, + Guid? targetID = null, string? displayName = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(group); - if (targetId == Guid.Empty) - throw new ArgumentException("A diagnostic target identifier cannot be empty.", nameof(targetId)); + if (targetID == Guid.Empty) + { + throw new ArgumentException("A diagnostic target identifier cannot be empty.", nameof(targetID)); + } Type callerType = ResolveCallerType(); CallerInfo caller = CALLERS.GetValue(callerType, static type => { string assemblyName = type.Assembly.GetName().Name - ?? throw new InvalidOperationException("The diagnostic caller assembly has no simple name."); + ?? throw new InvalidOperationException("The diagnostic caller assembly has no simple name."); string typeName = type.FullName ?? type.Name; return new CallerInfo { @@ -36,12 +33,12 @@ internal static DiagnosticSource Resolve( }; }); - string id = targetId.HasValue - ? $"{caller.sourcePrefix}/{group}/{targetId.Value:N}" - : $"{caller.sourcePrefix}/{group}"; + string id = targetID.HasValue + ? $"{caller.sourcePrefix}/{group}/{targetID.Value:N}" + : $"{caller.sourcePrefix}/{group}"; string resolvedDisplayName = string.IsNullOrWhiteSpace(displayName) - ? group - : displayName; + ? group + : displayName; return new DiagnosticSource(id, resolvedDisplayName); } @@ -55,7 +52,9 @@ private static Type ResolveCallerType() { Type? declaringType = frames[i].GetMethod()?.DeclaringType; if (declaringType is null || declaringType.Assembly == infrastructureAssembly) + { continue; + } return NormalizeCompilerGeneratedType(declaringType); } @@ -65,11 +64,16 @@ private static Type ResolveCallerType() private static Type NormalizeCompilerGeneratedType(Type type) { Type current = type; - while (current.DeclaringType is not null && - current.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) - { + while (current.DeclaringType is not null + && current.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false) + ) { current = current.DeclaringType; } return current; } + + private sealed class CallerInfo + { + internal required string sourcePrefix { get; init; } + } } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs index c32486827..8d6f61bce 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs @@ -1,8 +1,8 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Diagnostics; @@ -11,17 +11,13 @@ namespace Inno.Core.Diagnostics; /// public sealed class DiagnosticHub { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("hub"); + private static readonly ExecutionSlot CURRENT_SCOPE = new("hub"); private readonly Dictionary m_reports = new(StringComparer.Ordinal); private readonly Dictionary m_producerEpochs = new(StringComparer.Ordinal); - private long m_nextProducerEpoch; private readonly List m_sinks = []; private readonly object m_sync = new(); - - internal static DiagnosticHub current => S_CURRENT_SCOPE.current; - - internal object synchronizationRoot => m_sync; + private long m_nextProducerEpoch; /// /// Occurs when a diagnostic presentation sink fails and is quarantined. @@ -57,42 +53,13 @@ public DiagnosticReporter CreateReporter(DiagnosticSource source) } } - internal void SetOwned( - DiagnosticSource source, - long epoch, - IReadOnlyList diagnostics - ) { - lock (m_sync) - { - if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) - throw new ObjectDisposedException(nameof(DiagnosticReporter), "The diagnostic producer generation has retired."); - Set(source, diagnostics); - } - } - - internal void ReleaseOwned( - DiagnosticSource source, - long epoch - ) { - lock (m_sync) - { - if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) - return; - m_producerEpochs.Remove(source.id); - Clear(source); - } - } - /// /// Binds this hub to the current asynchronous execution context. /// /// /// A strict last-in-first-out scope owned by the caller. /// - public IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } + public IDisposable EnterScope() => CURRENT_SCOPE.Enter(this); /// /// Registers a sink and synchronously replays every active report before registration completes. @@ -112,17 +79,22 @@ public void RegisterSink(IDiagnosticSink sink) lock (m_sync) { if (m_sinks.Contains(sink)) + { return; + } try { foreach (DiagnosticReport report in m_reports.Values) + { sink.Replace(report); + } } catch (Exception exception) { throw new InvalidOperationException( "The diagnostic sink rejected the active snapshot and was not registered.", - exception); + exception + ); } m_sinks.Add(sink); } @@ -141,7 +113,9 @@ public void UnregisterSink(IDiagnosticSink sink) { ArgumentNullException.ThrowIfNull(sink); lock (m_sync) + { m_sinks.Remove(sink); + } } /// @@ -172,7 +146,9 @@ IEnumerable diagnostics return; } if (entries.Any(static diagnostic => diagnostic is null)) + { throw new ArgumentException("A diagnostic collection cannot contain null entries.", nameof(diagnostics)); + } var report = new DiagnosticReport(source, Array.AsReadOnly(entries), DateTime.Now); lock (m_sync) { @@ -199,7 +175,9 @@ public void Clear(DiagnosticSource source) lock (m_sync) { if (!m_reports.Remove(source.id, out DiagnosticReport? report)) + { return; + } NotifySinks(static ( sink, value @@ -207,6 +185,40 @@ public void Clear(DiagnosticSource source) } } + internal static DiagnosticHub current => CURRENT_SCOPE.current; + + internal object synchronizationRoot => m_sync; + + internal void SetOwned( + DiagnosticSource source, + long epoch, + IReadOnlyList diagnostics + ) { + lock (m_sync) + { + if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) + { + throw new ObjectDisposedException(nameof(DiagnosticReporter), "The diagnostic producer generation has retired."); + } + Set(source, diagnostics); + } + } + + internal void ReleaseOwned( + DiagnosticSource source, + long epoch + ) { + lock (m_sync) + { + if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) + { + return; + } + m_producerEpochs.Remove(source.id); + Clear(source); + } + } + private void NotifySinks( Action callback, TValue value @@ -223,7 +235,9 @@ TValue value m_sinks.Remove(sinks[index]); Action? observer = sinkFailed; if (observer is null) + { Console.Error.WriteLine($"Diagnostic sink failed and was quarantined: {exception}"); + } else { foreach (Action handler in observer.GetInvocationList()) @@ -245,7 +259,8 @@ TValue value private static void ValidateSource(DiagnosticSource source) { if (string.IsNullOrWhiteSpace(source.id)) + { throw new ArgumentException("A valid diagnostic source is required.", nameof(source)); + } } - } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs index c8ef6458f..166d591a9 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs @@ -31,11 +31,17 @@ public DiagnosticLocation( int column = 0 ) { if (string.IsNullOrWhiteSpace(sourcePath)) + { throw new ArgumentException("A diagnostic source path is required.", nameof(sourcePath)); + } if (line < 0) + { throw new ArgumentOutOfRangeException(nameof(line), "A diagnostic line cannot be negative."); + } if (column < 0) + { throw new ArgumentOutOfRangeException(nameof(column), "A diagnostic column cannot be negative."); + } this.sourcePath = sourcePath; this.line = line; this.column = column; @@ -59,26 +65,26 @@ public DiagnosticLocation( /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(DiagnosticLocation other) - => string.Equals(sourcePath, other.sourcePath, StringComparison.Ordinal) && - line == other.line && - column == other.column; + => string.Equals(sourcePath, other.sourcePath, StringComparison.Ordinal) + && line == other.line + && column == other.column; /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is DiagnosticLocation other && Equals(other); /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs index c30584143..29abfed0d 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs @@ -25,6 +25,7 @@ long epoch m_source = source; m_epoch = epoch; } + /// /// Replaces the issue with the same code and target, without using its message as identity. /// @@ -40,28 +41,29 @@ public void Publish(Diagnostic diagnostic) lock (m_sync) { DiagnosticHub hub = GetHub(); - var key = new IssueKey(diagnostic.code, diagnostic.semanticId, diagnostic.objectId); + var key = new IssueKey(diagnostic.code, diagnostic.semanticID, diagnostic.objectID); if (m_issues.TryGetValue(key, out Diagnostic? current) && current.severity == diagnostic.severity && string.Equals(current.message, diagnostic.message, StringComparison.Ordinal) - && Nullable.Equals(current.location, diagnostic.location)) - { + && Nullable.Equals(current.location, diagnostic.location) + ) { return; } m_issues[key] = diagnostic; hub.SetOwned(m_source, m_epoch, Ordered()); } } + /// /// Resolves an issue after the represented condition no longer exists. /// /// /// The stable issue code. /// - /// + /// /// The optional protocol identifier used at publication. /// - /// + /// /// The optional persistent object identity used at publication. /// /// @@ -69,18 +71,21 @@ public void Publish(Diagnostic diagnostic) /// public void Resolve( string code, - string? semanticId = null, - Guid? objectId = null + string? semanticID = null, + Guid? objectID = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(code); lock (m_sync) { DiagnosticHub hub = GetHub(); - if (!m_issues.Remove(new(code, semanticId, objectId))) + if (!m_issues.Remove(new IssueKey(code, semanticID, objectID))) + { return; + } hub.SetOwned(m_source, m_epoch, Ordered()); } } + /// /// Atomically replaces this producer's complete current issue set. /// @@ -100,16 +105,20 @@ public void Replace(IEnumerable diagnostics) foreach (Diagnostic diagnostic in diagnostics) { ArgumentNullException.ThrowIfNull(diagnostic); - if (!candidate.TryAdd(new(diagnostic.code, diagnostic.semanticId, diagnostic.objectId), diagnostic)) + if (!candidate.TryAdd(new IssueKey(diagnostic.code, diagnostic.semanticID, diagnostic.objectID), diagnostic)) + { throw new ArgumentException("A complete diagnostic report contains duplicate issue identities.", nameof(diagnostics)); + } } lock (m_sync) { DiagnosticHub hub = GetHub(); hub.SetOwned(m_source, m_epoch, candidate.Values.ToArray()); m_issues.Clear(); - foreach (var entry in candidate) + foreach (KeyValuePair entry in candidate) + { m_issues.Add(entry.Key, entry.Value); + } } } @@ -129,14 +138,16 @@ public void Dispose() private DiagnosticHub GetHub() => m_hub ?? throw new ObjectDisposedException(nameof(DiagnosticReporter)); - private Diagnostic[] Ordered() => m_issues.Values - .OrderBy(static issue => issue.code, StringComparer.Ordinal) - .ThenBy(static issue => issue.semanticId, StringComparer.Ordinal) - .ThenBy(static issue => issue.objectId).ToArray(); + private Diagnostic[] Ordered() + => m_issues.Values + .OrderBy(static issue => issue.code, StringComparer.Ordinal) + .ThenBy(static issue => issue.semanticID, StringComparer.Ordinal) + .ThenBy(static issue => issue.objectID) + .ToArray(); private readonly record struct IssueKey( string code, - string? semanticId, - Guid? objectId + string? semanticID, + Guid? objectID ); } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs index 9d910e7db..ca48fc974 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs @@ -9,12 +9,10 @@ public enum DiagnosticSeverity /// Describes useful information that does not indicate a problem. /// Info, - /// /// Describes a recoverable issue that should be reviewed. /// Warning, - /// /// Describes an issue that prevents the associated operation from succeeding. /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs index efb8c92a6..dae4ed24f 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs @@ -24,9 +24,13 @@ public DiagnosticSource( string displayName ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("A diagnostic source identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(displayName)) + { throw new ArgumentException("A diagnostic source display name is required.", nameof(displayName)); + } this.id = id; this.displayName = displayName; } @@ -44,23 +48,23 @@ string displayName /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(DiagnosticSource other) => string.Equals(id, other.id, StringComparison.Ordinal); /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is DiagnosticSource other && Equals(other); /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs b/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs index 461973c57..c5b240555 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs @@ -54,15 +54,13 @@ public static void Set( IEnumerable diagnostics ) { ArgumentNullException.ThrowIfNull(diagnostics); - DiagnosticHub.current.Set( - DiagnosticCallerResolver.Resolve(group), - diagnostics); + DiagnosticHub.current.Set(DiagnosticCallerResolver.Resolve(group), diagnostics); } /// /// Atomically sets the complete current state of one targeted diagnostic group owned by the calling type. /// - /// + /// /// The stable identity of the asset, scene element, or other dynamic target. /// /// @@ -75,26 +73,26 @@ IEnumerable diagnostics /// The optional target name presented by diagnostic consumers. /// /// - /// Thrown when is empty or is empty. + /// Thrown when is empty or is empty. /// /// /// Thrown when is . /// [MethodImpl(MethodImplOptions.NoInlining)] public static void Set( - Guid targetId, + Guid targetID, string group, Diagnostic diagnostic, string? displayName = null ) { ArgumentNullException.ThrowIfNull(diagnostic); - Set(targetId, group, [diagnostic], displayName); + Set(targetID, group, [diagnostic], displayName); } /// /// Atomically sets the complete current state of one targeted diagnostic group owned by the calling type. /// - /// + /// /// The stable identity of the asset, scene element, or other dynamic target. /// /// @@ -107,22 +105,20 @@ public static void Set( /// The optional target name presented by diagnostic consumers. /// /// - /// Thrown when is empty, is empty, or the collection contains a null entry. + /// Thrown when is empty, is empty, or the collection contains a null entry. /// /// /// Thrown when is . /// [MethodImpl(MethodImplOptions.NoInlining)] public static void Set( - Guid targetId, + Guid targetID, string group, IEnumerable diagnostics, string? displayName = null ) { ArgumentNullException.ThrowIfNull(diagnostics); - DiagnosticHub.current.Set( - DiagnosticCallerResolver.Resolve(group, targetId, displayName), - diagnostics); + DiagnosticHub.current.Set(DiagnosticCallerResolver.Resolve(group, targetID, displayName), diagnostics); } /// @@ -140,18 +136,18 @@ public static void Set( /// /// Clears one targeted diagnostic group owned by the calling type. /// - /// + /// /// The stable identity of the asset, scene element, or other dynamic target. /// /// /// The non-empty responsibility name scoped to the calling type and target. /// /// - /// Thrown when is empty or is empty. + /// Thrown when is empty or is empty. /// [MethodImpl(MethodImplOptions.NoInlining)] public static void Clear( - Guid targetId, + Guid targetID, string group - ) => DiagnosticHub.current.Clear(DiagnosticCallerResolver.Resolve(group, targetId)); + ) => DiagnosticHub.current.Clear(DiagnosticCallerResolver.Resolve(group, targetID)); } diff --git a/src/foundation/core/Inno.Core.Diagnostics/IDiagnosticReporter.cs b/src/foundation/core/Inno.Core.Diagnostics/IDiagnosticReporter.cs index e939c57b6..b4ae4e7fb 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/IDiagnosticReporter.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/IDiagnosticReporter.cs @@ -22,16 +22,16 @@ public interface IDiagnosticReporter /// /// The stable issue code. /// - /// + /// /// The optional protocol identifier used at publication. /// - /// + /// /// The optional persistent object identity used at publication. /// void Resolve( string code, - string? semanticId = null, - Guid? objectId = null + string? semanticID = null, + Guid? objectID = null ); /// diff --git a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs index b749c6b09..fa61446a3 100644 --- a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs +++ b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs @@ -13,22 +13,12 @@ public sealed class EventDispatcher { private readonly ConcurrentQueue m_queue = new(); private readonly Lock m_hubsGate = new(); - private EventHub[] m_hubsSnapshot = []; - private long m_nextHubSequence; private readonly int m_queueCapacity; private readonly int m_flushBudget; + private EventHub[] m_hubsSnapshot = []; + private long m_nextHubSequence; private int m_pendingCount; - /// - /// Observes an event after its ordered hub dispatch has completed, including globally consumed events. - /// - /// - /// Observers run synchronously on the dispatching thread and do not participate in consumption. - /// They must not change consumption or call HandleInHub. Observer failures propagate to the caller. - /// Owners must unsubscribe before retiring their callbacks or extensions. - /// - public event Action? dispatched; - /// /// Creates a dispatcher with bounded pending work and a finite per-flush budget. /// @@ -42,13 +32,11 @@ public sealed class EventDispatcher /// A budget is not positive. /// public EventDispatcher( - int queueCapacity = 65536, + int queueCapacity = 65_536, int flushBudget = 4096 ) { - if (queueCapacity <= 0) - throw new ArgumentOutOfRangeException(nameof(queueCapacity)); - if (flushBudget <= 0) - throw new ArgumentOutOfRangeException(nameof(flushBudget)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(queueCapacity); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(flushBudget); m_queueCapacity = queueCapacity; m_flushBudget = flushBudget; } @@ -58,6 +46,16 @@ public EventDispatcher( /// public int pendingCount => Volatile.Read(ref m_pendingCount); + /// + /// Observes an event after its ordered hub dispatch has completed, including globally consumed events. + /// + /// + /// Observers run synchronously on the dispatching thread and do not participate in consumption. + /// They must not change consumption or call HandleInHub. Observer failures propagate to the caller. + /// Owners must unsubscribe before retiring their callbacks or extensions. + /// + public event Action? dispatched; + /// /// Creates a new hub attached to this dispatcher. /// @@ -71,7 +69,7 @@ public EventHub CreateHub(int order = 0) { lock (m_hubsGate) { - EventHub hub = new(this, order, m_nextHubSequence++); + var hub = new EventHub(this, order, m_nextHubSequence++); List hubs = [..m_hubsSnapshot, hub]; SortHubs(hubs); Volatile.Write(ref m_hubsSnapshot, [..hubs]); @@ -91,7 +89,9 @@ public EventHub CreateHub(int order = 0) public void Enqueue(Event e) { if (!TryEnqueue(e)) + { throw new InvalidOperationException("The event queue is full; the producer must defer or reject this operation explicitly."); + } } /// @@ -151,13 +151,13 @@ public int DiscardPending() /// /// Immediately dispatches an event to all valid hubs in priority order. /// + /// + /// The event instance to dispatch. + /// /// /// Hub dispatch stops when the event is marked globally handled. Completion observers are still notified. /// A failed hub propagates its exception without reporting successful completion. /// - /// - /// The event instance to dispatch. - /// public void Emit(Event e) { ArgumentNullException.ThrowIfNull(e); @@ -168,11 +168,15 @@ public void Emit(Event e) { EventHub hub = hubs[i]; if (!hub.isValid) + { continue; + } hub.Dispatch(e); if (e.isGlobalHandled) + { break; + } } } dispatched?.Invoke(e); @@ -200,19 +204,17 @@ internal void NotifyHubOrderChanged() } private static void SortHubs(List hubs) - { - hubs.Sort(static ( + => hubs.Sort(static ( a, b ) => { - int byOrder = b.order.CompareTo(a.order); - if (byOrder != 0) - { - return byOrder; - } - - return a.sequence.CompareTo(b.sequence); - }); - } + int byOrder = b.order.CompareTo(a.order); + if (byOrder != 0) + { + return byOrder; + } + + return a.sequence.CompareTo(b.sequence); + }); } diff --git a/src/foundation/core/Inno.Core.Events/EventHub.cs b/src/foundation/core/Inno.Core.Events/EventHub.cs index 8e6456ef0..7197e0a02 100644 --- a/src/foundation/core/Inno.Core.Events/EventHub.cs +++ b/src/foundation/core/Inno.Core.Events/EventHub.cs @@ -16,7 +16,7 @@ public sealed class EventHub : IDisposable { private readonly WeakReference m_dispatcherRef; private readonly object m_gate = new(); - private HubState m_state = HubState.Empty; + private HubState m_state = HubState.EMPTY; private long m_nextListenerOrder; private int m_disposed; private int m_attached = 1; @@ -70,8 +70,6 @@ public bool isValid } } - internal long sequence { get; } - /// /// Subscribes a listener for the specified event type. /// @@ -91,8 +89,7 @@ public bool isValid public IDisposable Listen( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { ThrowIfInvalid(); ArgumentNullException.ThrowIfNull(handler); @@ -106,9 +103,9 @@ public IDisposable Listen( listenerOrder = m_nextListenerOrder++; Action invoker = e => handler((TEvent)e); - Listener listener = new(invoker, priority, listenerOrder); + var listener = new Listener(invoker, priority, listenerOrder); - Dictionary nextBuckets = new(Volatile.Read(ref m_state).buckets); + var nextBuckets = new Dictionary(Volatile.Read(ref m_state).buckets); Listener[] existing = nextBuckets.TryGetValue(eventType, out Listener[]? items) ? items : []; nextBuckets[eventType] = ListenerBucket.InsertSorted(existing, listener); Volatile.Write(ref m_state, new HubState(nextBuckets)); @@ -136,13 +133,12 @@ public IDisposable Listen( public IDisposable ListenOnce( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { ThrowIfInvalid(); ArgumentNullException.ThrowIfNull(handler); - OneShotSubscription oneShot = new(handler); + var oneShot = new OneShotSubscription(handler); IDisposable subscription = Listen(oneShot.Invoke, priority); oneShot.Bind(subscription); return oneShot; @@ -151,13 +147,13 @@ public IDisposable ListenOnce( /// /// Immediately dispatches an event inside this hub only. /// + /// + /// The event instance to dispatch locally. + /// /// /// This does not route through the dispatcher hub chain. /// Only listeners registered on this hub are invoked. /// - /// - /// The event instance to dispatch locally. - /// public void Announce(Event e) { ThrowIfInvalid(); @@ -179,7 +175,7 @@ public void Dispose() lock (m_gate) { - Volatile.Write(ref m_state, HubState.Empty); + Volatile.Write(ref m_state, HubState.EMPTY); } if (m_dispatcherRef.TryGetTarget(out EventDispatcher? dispatcher)) @@ -188,6 +184,8 @@ public void Dispose() } } + internal long sequence { get; } + internal void Dispatch(Event e) { if (!isValid || e.isGlobalHandled) @@ -246,7 +244,7 @@ long listenerOrder return; } - Dictionary nextBuckets = new(Volatile.Read(ref m_state).buckets); + var nextBuckets = new Dictionary(Volatile.Read(ref m_state).buckets); if (!nextBuckets.TryGetValue(eventType, out Listener[]? existing)) { return; @@ -311,6 +309,7 @@ long order /// Gets the scalar measurement or identity associated with the current state. /// public int priority { get; } = priority; + /// /// Gets the scalar measurement or identity associated with the current state. /// @@ -413,7 +412,7 @@ public static Listener[] InsertSorted( Listener[] source, Listener listener ) { - Listener[] result = new Listener[source.Length + 1]; + var result = new Listener[source.Length + 1]; int index = 0; while (index < source.Length) { @@ -484,7 +483,7 @@ long listenerOrder return []; } - Listener[] result = new Listener[source.Length - 1]; + var result = new Listener[source.Length - 1]; if (index > 0) { Array.Copy(source, 0, result, 0, index); @@ -504,7 +503,8 @@ private sealed class HubState(Dictionary buckets) /// /// The empty value used as part of this type's public representation. /// - public static readonly HubState Empty = new(new Dictionary()); + public static readonly HubState EMPTY = new([]); + /// /// Gets the immutable listener buckets captured for one dispatch operation. /// diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs new file mode 100644 index 000000000..e47fc69db --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Events; + +/// +/// Base class for application lifecycle events. +/// +public abstract class ApplicationEvent : Event; diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs deleted file mode 100644 index 782d622c2..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Inno.Core.Events; - -/// -/// Base class for application lifecycle events. -/// -public abstract class ApplicationEvent : Event -{ -} - -/// -/// Raised when the application requests shutdown. -/// -public class ApplicationQuitEvent : ApplicationEvent -{ -} diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs new file mode 100644 index 000000000..7aeeec5da --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the application requests shutdown. +/// +public sealed class ApplicationQuitEvent : ApplicationEvent; diff --git a/src/foundation/core/Inno.Core.Events/Events/Event.cs b/src/foundation/core/Inno.Core.Events/Events/Event.cs index 8205b1d70..c32527121 100644 --- a/src/foundation/core/Inno.Core.Events/Events/Event.cs +++ b/src/foundation/core/Inno.Core.Events/Events/Event.cs @@ -8,15 +8,19 @@ namespace Inno.Core.Events; /// public abstract class Event { + [ThreadStatic] + private static HubFrameStack? s_hubFrames; + private readonly Event m_consumptionOwner; private int m_globalHandled; - [ThreadStatic] - private static HubFrameStack? t_hubFrames; /// /// Creates an event with an independent global consumption lifetime. /// - protected Event() => m_consumptionOwner = this; + protected Event() + { + m_consumptionOwner = this; + } /// /// Creates a routed representation that shares global consumption with its source event. @@ -44,24 +48,21 @@ protected Event(Event source) /// /// Global handling stops dispatch in the current hub and all following hubs. /// - public void HandleInGlobal() - { - Volatile.Write(ref m_consumptionOwner.m_globalHandled, 1); - } + public void HandleInGlobal() => Volatile.Write(ref m_consumptionOwner.m_globalHandled, 1); /// /// Marks this event as handled in the current hub only. /// + /// + /// Thrown when called outside a valid hub dispatch context for this event. + /// /// /// Hub handling stops remaining listeners in the current hub /// but does not affect following hubs. /// - /// - /// Thrown when called outside a valid hub dispatch context for this event. - /// public void HandleInHub() { - HubFrameStack? frames = t_hubFrames; + HubFrameStack? frames = s_hubFrames; if (frames is null || !frames.IsCurrent(this)) { throw new InvalidOperationException("HandleInHub can only be used while this event is being dispatched in a hub."); @@ -72,11 +73,11 @@ public void HandleInHub() internal HubDispatchScope BeginHubDispatchScope() { - HubFrameStack? frames = t_hubFrames; + HubFrameStack? frames = s_hubFrames; if (frames is null) { frames = new HubFrameStack(4); - t_hubFrames = frames; + s_hubFrames = frames; } frames.Push(this); @@ -85,7 +86,7 @@ internal HubDispatchScope BeginHubDispatchScope() internal bool IsHandledInCurrentHub() { - HubFrameStack? frames = t_hubFrames; + HubFrameStack? frames = s_hubFrames; return frames is not null && frames.IsCurrentHandled(this); } @@ -97,10 +98,7 @@ Event eventRef /// /// Releases the resources owned by this instance. /// - public void Dispose() - { - frames.PopIfCurrent(eventRef); - } + public void Dispose() => frames.PopIfCurrent(eventRef); } internal sealed class HubFrameStack @@ -144,10 +142,7 @@ public void Push(Event e) /// /// when the requested condition is satisfied; otherwise, . /// - public bool IsCurrent(Event e) - { - return m_count > 0 && ReferenceEquals(m_events[m_count - 1], e); - } + public bool IsCurrent(Event e) => m_count > 0 && ReferenceEquals(m_events[m_count - 1], e); /// /// Marks the current event handled without changing another event context. @@ -170,11 +165,9 @@ public void MarkHandledCurrent() /// when the requested condition is satisfied; otherwise, . /// public bool IsCurrentHandled(Event e) - { - return m_count > 0 - && ReferenceEquals(m_events[m_count - 1], e) - && m_handled[m_count - 1]; - } + => m_count > 0 + && ReferenceEquals(m_events[m_count - 1], e) + && m_handled[m_count - 1]; /// /// Removes the supplied event only when it is the current execution context. diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs new file mode 100644 index 000000000..6da42180c --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs @@ -0,0 +1,37 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Base class for keyboard events. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +public abstract class KeyEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None +) : Event +{ + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } = windowID; + + /// + /// Gets the key code for this keyboard event. + /// + public KeyCode key { get; } = key; + + /// + /// Gets active key modifiers for this keyboard event. + /// + public KeyModifier modifiers { get; } = modifiers; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs b/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs deleted file mode 100644 index ad5a3f025..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; - -using Inno.Core.Input; - -namespace Inno.Core.Events; - -/// -/// Base class for keyboard events. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -public abstract class KeyEvent( - uint windowId, - KeyCode key, - KeyModifier modifiers = KeyModifier.None -) - : Event -{ - /// - /// Gets the source window id for this event. - /// - public uint windowId { get; } = windowId; - - /// - /// Gets the key code for this keyboard event. - /// - public KeyCode key { get; } = key; - - /// - /// Gets active key modifiers for this keyboard event. - /// - public KeyModifier modifiers { get; } = modifiers; -} - -/// -/// Raised when a key is pressed. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -/// -/// The repeat used to initialize this instance. -/// -public class KeyPressedEvent( - uint windowId, - KeyCode key, - KeyModifier modifiers = KeyModifier.None, - bool repeat = false -) - : KeyEvent(windowId, key, modifiers) -{ - /// - /// Gets whether this key press is an auto-repeat event. - /// - public bool repeat { get; } = repeat; -} - -/// -/// Raised when a key is released. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -public class KeyReleasedEvent( - uint windowId, - KeyCode key, - KeyModifier modifiers = KeyModifier.None -) - : KeyEvent(windowId, key, modifiers) -{ -} - -/// -/// Raised when the platform commits UTF-8 text through keyboard, IME, or virtual-keyboard input. -/// -/// -/// The source window identifier. -/// -/// -/// The committed Unicode text. -/// -public sealed class TextInputEvent( - uint windowId, - string text -) : Event -{ - /// - /// Gets the source window identifier. - /// - public uint windowId { get; } = windowId; - - /// - /// Gets the committed Unicode text. - /// - public string text { get; } = string.IsNullOrEmpty(text) - ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) - : text; -} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs new file mode 100644 index 000000000..b63345dd7 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs @@ -0,0 +1,31 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a key is pressed. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +/// +/// The repeat used to initialize this instance. +/// +public sealed class KeyPressedEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None, + bool repeat = false +) : KeyEvent(windowID, key, modifiers) +{ + /// + /// Gets whether this key press is an auto-repeat event. + /// + public bool repeat { get; } = repeat; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs new file mode 100644 index 000000000..b088e70e7 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs @@ -0,0 +1,21 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a key is released. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +public sealed class KeyReleasedEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None +) : KeyEvent(windowID, key, modifiers); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs new file mode 100644 index 000000000..de1171e9f --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs @@ -0,0 +1,23 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Base class for mouse button events. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public abstract class MouseButtonEvent( + uint windowID, + MouseButton button +) : MouseEvent(windowID) +{ + /// + /// Gets the mouse button for this event. + /// + public MouseButton button { get; } = button; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs new file mode 100644 index 000000000..dc13fd7df --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs @@ -0,0 +1,17 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a mouse button is pressed. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public sealed class MouseButtonPressedEvent( + uint windowID, + MouseButton button +) : MouseButtonEvent(windowID, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs new file mode 100644 index 000000000..e183ac3fd --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs @@ -0,0 +1,17 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a mouse button is released. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public sealed class MouseButtonReleasedEvent( + uint windowID, + MouseButton button +) : MouseButtonEvent(windowID, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs new file mode 100644 index 000000000..4d6623f47 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs @@ -0,0 +1,38 @@ +namespace Inno.Core.Events; + +/// +/// Base class for mouse events. +/// +public abstract class MouseEvent : Event +{ + /// + /// Creates an independent mouse event belonging to one platform window. + /// + /// + /// The platform window that produced the event. + /// + protected MouseEvent(uint windowID) + { + this.windowID = windowID; + } + + /// + /// Creates a routed mouse event sharing its source's window and global consumption. + /// + /// + /// The mouse event whose input lifetime remains authoritative. + /// + /// + /// The source event is null. + /// + protected MouseEvent(MouseEvent source) + : base(source) + { + this.windowID = source.windowID; + } + + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs deleted file mode 100644 index c47345aa9..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs +++ /dev/null @@ -1,178 +0,0 @@ -using Inno.Core.Input; - -namespace Inno.Core.Events; - -/// -/// Base class for mouse events. -/// -public abstract class MouseEvent : Event -{ - /// - /// Creates an independent mouse event belonging to one platform window. - /// - /// - /// The platform window that produced the event. - /// - protected MouseEvent(uint windowId) => this.windowId = windowId; - - /// - /// Creates a routed mouse event sharing its source's window and global consumption. - /// - /// - /// The mouse event whose input lifetime remains authoritative. - /// - /// - /// The source event is null. - /// - protected MouseEvent(MouseEvent source) : base(source) => windowId = source.windowId; - - /// - /// Gets the source window id for this event. - /// - public uint windowId { get; } -} - - -/// -/// Raised when the cursor moves. -/// -public class MouseMovedEvent : MouseEvent -{ - /// - /// Creates a pointer movement in platform-window coordinates. - /// - /// - /// The platform window that produced the movement. - /// - /// - /// The horizontal pointer coordinate in logical pixels. - /// - /// - /// The vertical pointer coordinate in logical pixels. - /// - public MouseMovedEvent( - uint windowId, - float x, - float y - ) : base(windowId) { - this.x = x; - this.y = y; - } - - /// - /// Gets cursor X coordinate. - /// - public float x { get; } - - /// - /// Gets cursor Y coordinate. - /// - public float y { get; } - - /// - /// Repositions this movement without starting a new global consumption lifetime. - /// - /// - /// The routed horizontal coordinate in logical pixels. - /// - /// - /// The routed vertical coordinate in logical pixels. - /// - /// - /// A new coordinate representation sharing global consumption with this movement. - /// - public MouseMovedEvent WithPosition( - float x, - float y - ) => new(this, x, y); - - private MouseMovedEvent( - MouseMovedEvent source, - float x, - float y - ) : base(source) { - this.x = x; - this.y = y; - } -} - -/// -/// Raised when mouse wheel scrolls. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The offset x used to initialize this instance. -/// -/// -/// The offset y used to initialize this instance. -/// -public class MouseScrolledEvent( - uint windowId, - float offsetX, - float offsetY -) : MouseEvent(windowId) -{ - /// - /// Gets horizontal scroll offset. - /// - public float offsetX { get; } = offsetX; - - /// - /// Gets vertical scroll offset. - /// - public float offsetY { get; } = offsetY; -} - -/// -/// Base class for mouse button events. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public abstract class MouseButtonEvent( - uint windowId, - MouseButton button -) : MouseEvent(windowId) -{ - /// - /// Gets the mouse button for this event. - /// - public MouseButton button { get; } = button; -} - -/// -/// Raised when a mouse button is pressed. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public class MouseButtonPressedEvent( - uint windowId, - MouseButton button -) : MouseButtonEvent(windowId, button) -{ -} - -/// -/// Raised when a mouse button is released. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public class MouseButtonReleasedEvent( - uint windowId, - MouseButton button -) : MouseButtonEvent(windowId, button) -{ -} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs new file mode 100644 index 000000000..81a0c2324 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs @@ -0,0 +1,66 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the cursor moves. +/// +public sealed class MouseMovedEvent : MouseEvent +{ + /// + /// Creates a pointer movement in platform-window coordinates. + /// + /// + /// The platform window that produced the movement. + /// + /// + /// The horizontal pointer coordinate in logical pixels. + /// + /// + /// The vertical pointer coordinate in logical pixels. + /// + public MouseMovedEvent( + uint windowID, + float x, + float y + ) : base(windowID) + { + this.x = x; + this.y = y; + } + + private MouseMovedEvent( + MouseMovedEvent source, + float x, + float y + ) : base(source) + { + this.x = x; + this.y = y; + } + + /// + /// Gets cursor X coordinate. + /// + public float x { get; } + + /// + /// Gets cursor Y coordinate. + /// + public float y { get; } + + /// + /// Repositions this movement without starting a new global consumption lifetime. + /// + /// + /// The routed horizontal coordinate in logical pixels. + /// + /// + /// The routed vertical coordinate in logical pixels. + /// + /// + /// A new coordinate representation sharing global consumption with this movement. + /// + public MouseMovedEvent WithPosition( + float x, + float y + ) => new(this, x, y); +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs new file mode 100644 index 000000000..f1b43f3c9 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs @@ -0,0 +1,30 @@ +namespace Inno.Core.Events; + +/// +/// Raised when mouse wheel scrolls. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The offset x used to initialize this instance. +/// +/// +/// The offset y used to initialize this instance. +/// +public sealed class MouseScrolledEvent( + uint windowID, + float offsetX, + float offsetY +) : MouseEvent(windowID) +{ + /// + /// Gets horizontal scroll offset. + /// + public float offsetX { get; } = offsetX; + + /// + /// Gets vertical scroll offset. + /// + public float offsetY { get; } = offsetY; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs b/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs new file mode 100644 index 000000000..a6b762e6f --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs @@ -0,0 +1,30 @@ +using System; + +namespace Inno.Core.Events; + +/// +/// Raised when the platform commits UTF-8 text through keyboard, IME, or virtual-keyboard input. +/// +/// +/// The source window identifier. +/// +/// +/// The committed Unicode text. +/// +public sealed class TextInputEvent( + uint windowID, + string text +) : Event +{ + /// + /// Gets the source window identifier. + /// + public uint windowID { get; } = windowID; + + /// + /// Gets the committed Unicode text. + /// + public string text { get; } = string.IsNullOrEmpty(text) + ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) + : text; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs new file mode 100644 index 000000000..b71ac02bb --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs @@ -0,0 +1,9 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the window requests close. +/// +/// +/// The window id used to initialize this instance. +/// +public sealed class WindowCloseEvent(uint windowID) : WindowEvent(windowID); diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs new file mode 100644 index 000000000..1417e4308 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs @@ -0,0 +1,15 @@ +namespace Inno.Core.Events; + +/// +/// Base class for window lifecycle events. +/// +/// +/// The window id used to initialize this instance. +/// +public abstract class WindowEvent(uint windowID) : Event +{ + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } = windowID; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs b/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs deleted file mode 100644 index d26700d3e..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs +++ /dev/null @@ -1,75 +0,0 @@ -namespace Inno.Core.Events; - -/// -/// Base class for window lifecycle events. -/// -/// -/// The window id used to initialize this instance. -/// -public abstract class WindowEvent(uint windowId) : Event -{ - /// - /// Gets the source window id for this event. - /// - public uint windowId { get; } = windowId; -} - - -/// -/// Raised when the window size changes. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The width in logical units or pixels required by this operation. -/// -/// -/// The height in logical units or pixels required by this operation. -/// -public class WindowResizeEvent( - uint windowId, - int width, - int height -) : WindowEvent(windowId) -{ - /// - /// Gets the new window width. - /// - public int width { get; } = width; - - /// - /// Gets the new window height. - /// - public int height { get; } = height; -} - -/// -/// Raised when the window requests close. -/// -/// -/// The window id used to initialize this instance. -/// -public class WindowCloseEvent(uint windowId) : WindowEvent(windowId) -{ -} - -/// -/// Raised when a window gains or loses input focus. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The is focused used to initialize this instance. -/// -public class WindowFocusChangedEvent( - uint windowId, - bool isFocused -) : WindowEvent(windowId) -{ - /// - /// Gets whether the window has input focus after the change. - /// - public bool isFocused { get; } = isFocused; -} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs new file mode 100644 index 000000000..f11fe4035 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs @@ -0,0 +1,21 @@ +namespace Inno.Core.Events; + +/// +/// Raised when a window gains or loses input focus. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The is focused used to initialize this instance. +/// +public sealed class WindowFocusChangedEvent( + uint windowID, + bool isFocused +) : WindowEvent(windowID) +{ + /// + /// Gets whether the window has input focus after the change. + /// + public bool isFocused { get; } = isFocused; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs new file mode 100644 index 000000000..983d7bc1a --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs @@ -0,0 +1,30 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the window size changes. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The width in logical units or pixels required by this operation. +/// +/// +/// The height in logical units or pixels required by this operation. +/// +public sealed class WindowResizeEvent( + uint windowID, + int width, + int height +) : WindowEvent(windowID) +{ + /// + /// Gets the new window width. + /// + public int width { get; } = width; + + /// + /// Gets the new window height. + /// + public int height { get; } = height; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowVisibilityChangedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowVisibilityChangedEvent.cs index 5efed7aca..618cde5a0 100644 --- a/src/foundation/core/Inno.Core.Events/Events/WindowVisibilityChangedEvent.cs +++ b/src/foundation/core/Inno.Core.Events/Events/WindowVisibilityChangedEvent.cs @@ -3,16 +3,16 @@ namespace Inno.Core.Events; /// /// Reports whether a platform window can present visible content. /// -/// +/// /// The application-local identity of the affected window. /// /// /// Whether the window is shown and not minimized. /// public sealed class WindowVisibilityChangedEvent( - uint windowId, + uint windowID, bool isVisible -) : WindowEvent(windowId) +) : WindowEvent(windowID) { /// /// Gets whether the window can present visible content after this notification. diff --git a/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs b/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs index 1b5e7a2fc..4240b76f9 100644 --- a/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs +++ b/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs @@ -36,9 +36,10 @@ public ExecutionSlot(string name) /// /// No live binding exists on the permitted thread. /// - public TValue current => TryGet(out TValue? value) - ? value - : throw new InvalidOperationException($"No active '{m_name}' execution scope is available to this caller."); + public TValue current + => TryGet(out TValue? value) + ? value + : throw new InvalidOperationException($"No active '{m_name}' execution scope is available to this caller."); /// /// Binds a value until the returned scope is retired in strict last-in-first-out order. @@ -91,7 +92,9 @@ public bool TryGet([MaybeNullWhen(false)] out TValue value) { Binding? binding = m_current.Value; if (binding is not null) + { return binding.TryGet(out value); + } value = default; return false; } @@ -100,7 +103,7 @@ private sealed class Binding : IDisposable { private readonly ExecutionSlot m_slot; private readonly object m_sync = new(); - private readonly int m_threadId; + private readonly int m_threadID; private readonly bool m_assigned; private Binding? m_parent; private TValue m_value; @@ -116,24 +119,10 @@ internal Binding( m_slot = slot; m_value = value; m_parent = parent; - m_threadId = threadAffine ? Environment.CurrentManagedThreadId : 0; + m_threadID = threadAffine ? Environment.CurrentManagedThreadId : 0; m_assigned = assigned; } - internal bool TryGet([MaybeNullWhen(false)] out TValue value) - { - lock (m_sync) - { - if (m_active && m_assigned && (m_threadId == 0 || m_threadId == Environment.CurrentManagedThreadId)) - { - value = m_value; - return true; - } - value = default; - return false; - } - } - /// /// Revokes this binding only at the top of its execution stack and clears retained values. /// @@ -145,16 +134,36 @@ public void Dispose() lock (m_sync) { if (!m_active) + { return; + } if (!ReferenceEquals(m_slot.m_current.Value, this)) + { throw new InvalidOperationException($"'{m_slot.m_name}' scopes must retire in last-in-first-out order."); - if (m_threadId != 0 && m_threadId != Environment.CurrentManagedThreadId) + } + if (m_threadID != 0 && m_threadID != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"'{m_slot.m_name}' must retire on its owner thread."); + } m_slot.m_current.Value = m_parent; m_active = false; m_value = default!; m_parent = null; } } + + internal bool TryGet([MaybeNullWhen(false)] out TValue value) + { + lock (m_sync) + { + if (m_active && m_assigned && (m_threadID == 0 || m_threadID == Environment.CurrentManagedThreadId)) + { + value = m_value; + return true; + } + value = default; + return false; + } + } } } diff --git a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs index 5a773d0cd..bb9496710 100644 --- a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs +++ b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs @@ -16,12 +16,12 @@ public sealed class LifetimeScope : IDisposable, IAsyncDisposable private readonly List m_resources = []; private readonly List m_tasks = []; private readonly List m_retirementFailures = []; + private readonly int m_maxTrackedWork; private Exception? m_blockedWorkFailure; private bool m_canceling; private bool m_disposing; private bool m_stopping; private bool m_disposed; - private readonly int m_maxTrackedWork; private int m_peakTrackedWork; private long m_rejectedWork; @@ -48,9 +48,12 @@ public int trackedWorkCount get { lock (m_sync) + { return m_tasks.Count(static task => !task.IsCompletedSuccessfully && !task.IsCanceled); + } } } + /// /// Gets the largest simultaneous retained work count. /// @@ -59,9 +62,12 @@ public int peakTrackedWorkCount get { lock (m_sync) + { return m_peakTrackedWork; + } } } + /// /// Gets work registrations rejected before ownership transfer by finite capacity. /// @@ -70,7 +76,9 @@ public long rejectedWorkCount get { lock (m_sync) + { return m_rejectedWork; + } } } @@ -87,8 +95,11 @@ public bool isQuiescent get { lock (m_sync) - return !m_canceling && !m_disposing && m_blockedWorkFailure is null && m_tasks.All(static task => - task.IsCompleted && (task.Exception is not Exception failure || RetirementPendingException.Find(failure) is null)); + { + return !m_canceling && !m_disposing && m_blockedWorkFailure is null && m_tasks.All(static task => ( + task.IsCompleted && (task.Exception is not Exception failure || RetirementPendingException.Find(failure) is null) + )); + } } } @@ -110,7 +121,8 @@ public bool isQuiescent /// /// Retirement has already started. /// - public TResource Own(TResource resource) where TResource : IDisposable + public TResource Own(TResource resource) + where TResource : IDisposable { ArgumentNullException.ThrowIfNull(resource); lock (m_sync) @@ -160,28 +172,32 @@ public Task RunAsync( ArgumentNullException.ThrowIfNull(operation); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); TrackCore(completion.Task, observeCompletion: false); - _ = CompleteOperationAsync(operation, cancellationToken, completion); + _ = CompleteOperationAsync(operation, completion, cancellationToken); return completion.Task; } /// /// Stops new registrations and invokes cancellation callbacks on the calling thread. /// + /// + /// One or more cancellation callbacks fail. + /// /// /// Callbacks must return promptly. Dependent resources remain owned while cancellation callbacks execute, /// including when another thread attempts disposal. A callback reporting pending work permanently blocks release. /// - /// - /// One or more cancellation callbacks fail. - /// public void Cancel() { lock (m_sync) { if (m_blockedWorkFailure is not null) + { throw m_blockedWorkFailure; + } if (m_disposed || m_stopping) + { return; + } m_stopping = true; m_canceling = true; } @@ -192,45 +208,57 @@ public void Cancel() catch (Exception exception) when (RetirementPendingException.Find(exception) is not null) { lock (m_sync) + { m_blockedWorkFailure = exception; + } throw; } catch (Exception exception) { lock (m_sync) + { RetirementPendingException.CollectCompletedFailures(exception, m_retirementFailures); + } throw; } finally { lock (m_sync) + { m_canceling = false; + } } } /// /// Releases a quiescent lifetime in reverse registration order, continuing after ordinary cleanup failures. /// - /// - /// Pending retirement retains the current resource and all remaining dependencies for a later attempt. - /// Concurrent or reentrant retirement reports pending work without invoking a resource twice. - /// /// /// Tracked work remains active; drain it before retrying. /// /// /// Cancellation, work or resource retirement fails. /// + /// + /// Pending retirement retains the current resource and all remaining dependencies for a later attempt. + /// Concurrent or reentrant retirement reports pending work without invoking a resource twice. + /// public void Dispose() { lock (m_sync) { if (m_blockedWorkFailure is not null) + { throw m_blockedWorkFailure; + } if (m_disposed) + { return; + } if (m_disposing) + { throw new RetirementPendingException("Another retirement attempt still owns this lifetime's resources."); + } m_disposing = true; } try @@ -243,29 +271,34 @@ public void Dispose() { throw; } - catch (Exception) { /* Cancel retained ordinary callback failures for the final report. */ } + catch (Exception) + { + // Cancel retained ordinary callback failures for the final report. + } RetireResources(); } finally { lock (m_sync) + { m_disposing = false; + } } } /// /// Cancels and asynchronously drains tracked work before reverse-order release. /// - /// - /// Only use asynchronous disposal for thread-neutral resources. Control-thread owners must await their work - /// and call synchronous disposal at their own safe point; this method does not marshal to an owner thread. - /// /// /// A task that completes only after work and resource retirement finish. /// /// /// Cancellation, work or resource retirement fails. /// + /// + /// Only use asynchronous disposal for thread-neutral resources. Control-thread owners must await their work + /// and call synchronous disposal at their own safe point; this method does not marshal to an owner thread. + /// public async ValueTask DisposeAsync() { try @@ -276,15 +309,23 @@ public async ValueTask DisposeAsync() { throw; } - catch (Exception) { /* Cancel retained ordinary callback failures for the final report. */ } + catch (Exception) + { + // Cancel retained ordinary callback failures for the final report. + } Task[] pending; lock (m_sync) + { pending = m_tasks.ToArray(); + } try { await Task.WhenAll(pending).ConfigureAwait(false); } - catch { /* Dispose observes every fault after all work has completed. */ } + catch (Exception) + { + // Dispose observes every fault after all work has completed. + } Dispose(); } @@ -293,9 +334,13 @@ private void RetireResources() lock (m_sync) { if (m_disposed) + { return; + } if (m_canceling || m_tasks.Any(static task => !task.IsCompleted)) + { throw new RetirementPendingException("Lifetime work is still active. Drain it before releasing its resources."); + } foreach (Task task in m_tasks) { if (task.Exception is not null) @@ -316,7 +361,9 @@ private void RetireResources() lock (m_sync) { if (m_resources.Count == 0) + { break; + } resource = m_resources[^1]; } try @@ -333,14 +380,21 @@ private void RetireResources() m_retirementFailures.Add(exception); } lock (m_sync) + { m_resources.RemoveAt(m_resources.Count - 1); + } } lock (m_sync) + { m_disposed = true; + } m_cancellation.Dispose(); if (m_retirementFailures.Count > 0) { - var failure = new AggregateException("Lifetime retirement failed after all resources were attempted.", m_retirementFailures); + var failure = new AggregateException( + "Lifetime retirement failed after all resources were attempted.", + m_retirementFailures + ); m_retirementFailures.Clear(); throw failure; } @@ -356,18 +410,26 @@ bool observeCompletion EnsureAccepting(); m_tasks.RemoveAll(static completed => completed.IsCompletedSuccessfully || completed.IsCanceled); if (m_tasks.Contains(task)) + { return; + } if (m_tasks.Count >= m_maxTrackedWork) { m_rejectedWork++; - throw new InvalidOperationException("The lifetime's asynchronous work capacity has been reached; ownership was not transferred."); + throw new InvalidOperationException( + "The lifetime's asynchronous work capacity has been reached; ownership was not transferred." + ); } m_tasks.Add(task); m_peakTrackedWork = Math.Max(m_peakTrackedWork, m_tasks.Count); if (!observeCompletion) + { return; + } if (ExecutionContext.IsFlowSuppressed()) + { ObserveCompletion(task); + } else { using AsyncFlowControl flow = ExecutionContext.SuppressFlow(); @@ -383,28 +445,38 @@ private void ObserveCompletion(Task task) ) => { if (!completed.IsCompletedSuccessfully && !completed.IsCanceled) + { return; - var owner = (LifetimeScope)state!; + } + LifetimeScope owner = (LifetimeScope)state!; lock (owner.m_sync) + { owner.m_tasks.Remove(completed); + } }, this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); private void EnsureAccepting() { if (m_stopping || m_disposed) + { throw new InvalidOperationException("A retiring lifetime cannot accept resources or work."); + } } private async Task CompleteOperationAsync( Func> operation, - CancellationToken cancellationToken, - TaskCompletionSource completion + TaskCompletionSource completion, + CancellationToken cancellationToken ) { try { TResult result; - using (var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, m_cancellation.Token)) + using (CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + m_cancellation.Token + )) { result = await operation(linked.Token).ConfigureAwait(false); + } lock (m_sync) { completion.SetResult(result); diff --git a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs index 627d337a3..9df2a2916 100644 --- a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs +++ b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs @@ -43,7 +43,7 @@ public static TResult Run(Func> operation) try { Task completion = operation() - ?? throw new InvalidOperationException("The owned operation returned a null task."); + ?? throw new InvalidOperationException("The owned operation returned a null task."); context.Pump(completion); return completion.GetAwaiter().GetResult(); } @@ -56,9 +56,9 @@ public static TResult Run(Func> operation) private sealed class OwnerContext : SynchronizationContext, IDisposable { private readonly BlockingCollection m_callbacks = new(); - private readonly int m_threadId = Environment.CurrentManagedThreadId; + private readonly int m_threadID = Environment.CurrentManagedThreadId; - /// + /// public override void Post( SendOrPostCallback callback, object? state @@ -67,13 +67,13 @@ public override void Post( m_callbacks.Add(() => callback(state)); } - /// + /// public override void Send( SendOrPostCallback callback, object? state ) { ArgumentNullException.ThrowIfNull(callback); - if (Environment.CurrentManagedThreadId == m_threadId) + if (Environment.CurrentManagedThreadId == m_threadID) { callback(state); return; @@ -99,20 +99,26 @@ public override void Send( failure?.Throw(); } - /// + /// public override SynchronizationContext CreateCopy() => this; - /// + /// public void Dispose() => m_callbacks.Dispose(); internal void Pump(Task completion) { bool notified = false; - Task notification = completion.ContinueWith(_ => m_callbacks.Add(() => notified = true), - CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + Task notification = completion.ContinueWith( + _ => m_callbacks.Add(() => notified = true), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default + ); // Observe completion on the owner, after the wake-up item has actually been consumed. while (!notified || m_callbacks.Count != 0) + { m_callbacks.Take()(); + } notification.GetAwaiter().GetResult(); } } diff --git a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs index c84f50e94..91bfdf311 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs @@ -13,9 +13,9 @@ public sealed class RetirementBarrier private readonly string m_owner; private readonly TimeSpan m_timeout; private readonly int m_ownerThread = Environment.CurrentManagedThreadId; + private readonly List m_completedFailures = []; private Stopwatch? m_elapsed; private Exception? m_failure; - private readonly List m_completedFailures = []; private bool m_completed; /// @@ -38,7 +38,9 @@ public RetirementBarrier( m_owner = owner; m_timeout = timeout ?? TimeSpan.FromSeconds(30); if (m_timeout <= TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } } /// @@ -50,10 +52,6 @@ public RetirementBarrier( /// /// True after retirement completes, or false while work remains within its deadline. /// - /// - /// Wrapped pending failures retain their ownership semantics. A nested timeout is rethrown in its original - /// exception tree. Ordinary sibling failures survive retries and are reported once retirement completes. - /// /// /// Retirement completed after earlier ordinary failures, or the owner reported a wrapped terminal timeout. /// @@ -63,15 +61,25 @@ public RetirementBarrier( /// /// The caller is not the thread that created this barrier. /// + /// + /// Wrapped pending failures retain their ownership semantics. A nested timeout is rethrown in its original + /// exception tree. Ordinary sibling failures survive retries and are reported once retirement completes. + /// public bool TryComplete(Action retire) { ArgumentNullException.ThrowIfNull(retire); if (m_ownerThread != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException("Retirement must advance on its owner thread."); + } if (m_failure is not null) + { throw m_failure; + } if (m_completed) + { return true; + } m_elapsed ??= Stopwatch.StartNew(); try { @@ -87,24 +95,33 @@ public bool TryComplete(Action retire) throw; } if (m_elapsed.Elapsed < m_timeout) + { return false; + } m_failure = new RetirementTimeoutException( $"Owner '{m_owner}' could not retire within {m_timeout}: {pending.Message}", m_completedFailures.Count == 0 ? exception : new AggregateException( - "Retirement has unfinished work and earlier completed failures.", [.. m_completedFailures, exception])); + "Retirement has unfinished work and earlier completed failures.", + [.. m_completedFailures, exception] + ) + ); throw m_failure; } catch (Exception exception) { m_completed = true; if (m_completedFailures.Count == 0) + { throw; + } RetirementPendingException.CollectCompletedFailures(exception, m_completedFailures); throw TakeCompletedFailure(); } m_completed = true; if (m_completedFailures.Count > 0) + { throw TakeCompletedFailure(); + } return true; } @@ -120,12 +137,17 @@ public bool TryComplete(Action retire) public void Wait(Action retire) { while (!TryComplete(retire)) + { Thread.Sleep(1); + } } private AggregateException TakeCompletedFailure() { - var failure = new AggregateException($"Owner '{m_owner}' retired with completed cleanup failures.", m_completedFailures); + var failure = new AggregateException( + $"Owner '{m_owner}' retired with completed cleanup failures.", + m_completedFailures + ); m_completedFailures.Clear(); return failure; } diff --git a/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs b/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs index f09efe466..fdd884c62 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs @@ -6,6 +6,9 @@ namespace Inno.Core.Execution; /// /// Reports that cancellation has begun but the owner must retain its dependencies until work drains. /// +/// +/// More specific retirement failures derive from this class so that callers can catch every pending retirement with one handler. +/// public class RetirementPendingException : InvalidOperationException { /// @@ -20,7 +23,7 @@ public class RetirementPendingException : InvalidOperationException public RetirementPendingException( string message, Exception? innerException = null - ) : base(message, innerException) { } + ) : base(message, innerException) {} /// /// Finds unfinished retirement in an exception tree without discarding its contextual or sibling failures. @@ -39,16 +42,23 @@ public RetirementPendingException( { ArgumentNullException.ThrowIfNull(exception); if (exception is RetirementPendingException pending) + { return pending.InnerException is Exception detail && Find(detail) is RetirementTimeoutException terminal - ? terminal : pending; + ? terminal + : pending; + } if (exception is not AggregateException aggregate) + { return exception.InnerException is Exception cause ? Find(cause) : null; + } RetirementPendingException? result = null; foreach (Exception inner in aggregate.InnerExceptions) { RetirementPendingException? found = Find(inner); if (found is RetirementTimeoutException) + { return found; + } result ??= found; } return result; @@ -75,13 +85,17 @@ ICollection failures if (exception is RetirementPendingException pending) { if (pending.InnerException is Exception detail) + { CollectCompletedFailures(detail, failures); + } return; } if (exception is AggregateException aggregate) { foreach (Exception inner in aggregate.InnerExceptions) + { CollectCompletedFailures(inner, failures); + } return; } if (Find(exception) is not null && exception.InnerException is Exception cause) @@ -90,8 +104,12 @@ ICollection failures return; } foreach (Exception previous in failures) + { if (ReferenceEquals(previous, exception)) + { return; + } + } failures.Add(exception); } } diff --git a/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs b/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs index 8d1958787..b95e82e5c 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs @@ -19,5 +19,5 @@ public sealed class RetirementTimeoutException : RetirementPendingException public RetirementTimeoutException( string message, Exception? innerException = null - ) : base(message, innerException) { } + ) : base(message, innerException) {} } diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs b/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs deleted file mode 100644 index 994b9c1a0..000000000 --- a/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Inno.Core.Graphs; - -/// -/// Declares the direction in which values flow through a graph port. -/// -public enum GraphPortDirection -{ - /// - /// Receives a value from another node. - /// - Input, - /// - /// Produces a value for another node. - /// - Output -} - -/// -/// Declares how many edges may connect to a graph port. -/// -public enum GraphPortCapacity -{ - /// - /// At most one edge may connect to the port. - /// - Single, - /// - /// Any number of edges may connect to the port. - /// - Multiple -} - -/// -/// Describes one dynamically or statically resolved node port. -/// -public sealed class GraphPortDefinition -{ - /// - /// Creates a graph port definition. - /// - /// - /// Stable node-local port identifier. - /// - /// - /// Artist-facing display name. - /// - /// - /// Stable value type identifier. - /// - /// - /// Value-flow direction. - /// - /// - /// Allowed edge capacity. - /// - /// - /// Whether an input must be connected. - /// - public GraphPortDefinition( - GraphPortId id, - string displayName, - string valueTypeId, - GraphPortDirection direction, - GraphPortCapacity capacity = GraphPortCapacity.Single, - bool required = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(displayName); - ArgumentException.ThrowIfNullOrWhiteSpace(valueTypeId); - this.id = id; - this.displayName = displayName; - this.valueTypeId = valueTypeId; - this.direction = direction; - this.capacity = capacity; - this.required = required; - } - - /// - /// Gets the stable node-local port identifier. - /// - public GraphPortId id { get; } - - /// - /// Gets the artist-facing display name. - /// - public string displayName { get; } - - /// - /// Gets the stable value type identifier. - /// - public string valueTypeId { get; } - - /// - /// Gets the value-flow direction. - /// - public GraphPortDirection direction { get; } - - /// - /// Gets the allowed edge capacity. - /// - public GraphPortCapacity capacity { get; } - - /// - /// Gets whether an input must be connected. - /// - public bool required { get; } -} - -/// -/// Describes node presentation and resolves ports without entering graph persistence. -/// -public abstract class GraphNodeDefinition -{ - /// - /// Creates a graph node definition. - /// - /// - /// Globally stable definition identifier. - /// - /// - /// Artist-facing display name. - /// - /// - /// Search-menu category path. - /// - protected GraphNodeDefinition( - string id, - string displayName, - string category - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(displayName); - ArgumentException.ThrowIfNullOrWhiteSpace(category); - this.id = id; - this.displayName = displayName; - this.category = category; - } - - /// - /// Gets the globally stable definition identifier. - /// - public string id { get; } - - /// - /// Gets the artist-facing display name. - /// - public string displayName { get; } - - /// - /// Gets the search-menu category path. - /// - public string category { get; } - - /// - /// Resolves ports for one node record, including any data-driven dynamic ports. - /// - /// - /// Neutral node record to inspect. - /// - /// - /// The complete port definitions for the current node state. - /// - public abstract IReadOnlyList GetPorts(GraphNodeRecord node); -} - -/// -/// Resolves generation-scoped node definitions by stable identifier. -/// -public interface IGraphNodeDefinitionResolver -{ - /// - /// Tries to resolve an active node definition. - /// - /// - /// Stable definition identifier. - /// - /// - /// Receives the generation-scoped definition. - /// - /// - /// when active; otherwise . - /// - bool TryResolve( - string definitionId, - out GraphNodeDefinition? definition - ); -} - -/// -/// Determines whether one graph value type can be converted to another. -/// -public interface IGraphTypeConversion -{ - /// - /// Tests a directed value conversion. - /// - /// - /// Source value type identifier. - /// - /// - /// Destination value type identifier. - /// - /// - /// when the conversion is valid; otherwise . - /// - bool CanConvert( - string sourceTypeId, - string destinationTypeId - ); -} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs b/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs new file mode 100644 index 000000000..51a58650f --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs @@ -0,0 +1,69 @@ +using System; +using Inno.Core.Diagnostics; + +namespace Inno.Core.Graphs; + +/// +/// Reports one graph validation problem using stable document identifiers. +/// +public sealed class GraphDiagnostic +{ + /// + /// Creates a graph diagnostic. + /// + /// + /// Stable machine-readable diagnostic code. + /// + /// + /// Artist-facing diagnostic text. + /// + /// + /// Diagnostic impact. + /// + /// + /// Optional related node identifier. + /// + /// + /// Optional related edge identifier. + /// + public GraphDiagnostic( + string code, + string message, + DiagnosticSeverity severity, + GraphNodeID? nodeID = null, + GraphEdgeID? edgeID = null + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + this.code = code; + this.message = message; + this.severity = severity; + this.nodeID = nodeID; + this.edgeID = edgeID; + } + + /// + /// Gets the stable machine-readable diagnostic code. + /// + public string code { get; } + + /// + /// Gets the artist-facing diagnostic text. + /// + public string message { get; } + + /// + /// Gets the diagnostic impact. + /// + public DiagnosticSeverity severity { get; } + + /// + /// Gets the related node identifier, if any. + /// + public GraphNodeID? nodeID { get; } + + /// + /// Gets the related edge identifier, if any. + /// + public GraphEdgeID? edgeID { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs index dfe498956..74fddfdd0 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs @@ -4,183 +4,6 @@ namespace Inno.Core.Graphs; -/// -/// Stores one node without retaining a CLR type or runtime extension instance. -/// -public sealed class GraphNodeRecord -{ - private readonly Dictionary m_values = new(StringComparer.Ordinal); - private readonly ReadOnlyDictionary m_valueView; - - /// - /// Creates a graph node record. - /// - /// - /// Stable identifier within the document. - /// - /// - /// Stable node definition identifier. - /// - public GraphNodeRecord( - GraphNodeId id, - string definitionId - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(definitionId); - this.id = id; - this.definitionId = definitionId; - m_valueView = new(m_values); - } - - /// - /// Gets the stable node identifier. - /// - public GraphNodeId id { get; } - - /// - /// Gets the stable node definition identifier. - /// - public string definitionId { get; } - - /// - /// Gets or sets the graph-space node position. - /// - public GraphPosition position { get; set; } - - /// - /// Gets neutral serialized property values keyed by stable property identifier. - /// - public IReadOnlyDictionary values => m_valueView; - - /// - /// Creates or replaces a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// Serialized value. - /// - public void SetValue( - string propertyId, - GraphSerializedValue value - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyId); - ArgumentNullException.ThrowIfNull(value); - m_values[propertyId] = value; - } - - /// - /// Tries to read a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// Receives the value when present. - /// - /// - /// when the property exists; otherwise . - /// - public bool TryGetValue( - string propertyId, - out GraphSerializedValue? value - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyId); - return m_values.TryGetValue(propertyId, out value); - } - - /// - /// Removes a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// when a property was removed; otherwise . - /// - public bool RemoveValue(string propertyId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyId); - return m_values.Remove(propertyId); - } -} - -/// -/// Identifies one endpoint of a graph edge. -/// -public readonly record struct GraphEndpoint -{ - /// - /// Creates a graph edge endpoint. - /// - /// - /// Owning node identifier. - /// - /// - /// Port identifier within the node definition. - /// - public GraphEndpoint( - GraphNodeId nodeId, - GraphPortId portId - ) { - this.nodeId = nodeId; - this.portId = portId; - } - - /// - /// Gets the owning node identifier. - /// - public GraphNodeId nodeId { get; } - - /// - /// Gets the node-local port identifier. - /// - public GraphPortId portId { get; } -} - -/// -/// Stores one typed connection between two graph endpoints. -/// -public sealed class GraphEdgeRecord -{ - /// - /// Creates a graph edge record. - /// - /// - /// Stable edge identifier within the document. - /// - /// - /// Source endpoint. - /// - /// - /// Destination endpoint. - /// - public GraphEdgeRecord( - GraphEdgeId id, - GraphEndpoint output, - GraphEndpoint input - ) { - this.id = id; - this.output = output; - this.input = input; - } - - /// - /// Gets the stable edge identifier. - /// - public GraphEdgeId id { get; } - - /// - /// Gets the source endpoint. - /// - public GraphEndpoint output { get; } - - /// - /// Gets the destination endpoint. - /// - public GraphEndpoint input { get; } -} - /// /// Owns neutral graph records and graph-level canvas metadata. /// @@ -189,7 +12,7 @@ public sealed class GraphDocument private readonly List m_nodes = []; private readonly List m_edges = []; private readonly Dictionary m_metadata = new(StringComparer.Ordinal); - private readonly Dictionary m_nodeIndex = []; + private readonly Dictionary m_nodeIndex = []; private readonly ReadOnlyCollection m_nodeView; private readonly ReadOnlyCollection m_edgeView; private readonly ReadOnlyDictionary m_metadataView; @@ -250,16 +73,16 @@ public void ReplaceContents(GraphDocument source) } List nodes = []; - Dictionary nodeIndex = []; + Dictionary nodeIndex = []; foreach (GraphNodeRecord sourceNode in source.nodes) { - var node = new GraphNodeRecord(sourceNode.id, sourceNode.definitionId) + var node = new GraphNodeRecord(sourceNode.id, sourceNode.definitionID) { position = sourceNode.position }; - foreach ((string propertyId, GraphSerializedValue value) in sourceNode.values) + foreach ((string propertyID, GraphSerializedValue value) in sourceNode.values) { - node.SetValue(propertyId, value.Clone()); + node.SetValue(propertyID, value.Clone()); } nodes.Add(node); @@ -272,7 +95,7 @@ public void ReplaceContents(GraphDocument source) edges.Add(new GraphEdgeRecord(sourceEdge.id, sourceEdge.output, sourceEdge.input)); } - Dictionary metadata = new(StringComparer.Ordinal); + var metadata = new Dictionary(StringComparer.Ordinal); foreach ((string key, GraphSerializedValue value) in source.metadata) { metadata.Add(key, value.Clone()); @@ -281,8 +104,10 @@ public void ReplaceContents(GraphDocument source) m_nodes.Clear(); m_nodes.AddRange(nodes); m_nodeIndex.Clear(); - foreach ((GraphNodeId id, GraphNodeRecord node) in nodeIndex) + foreach ((GraphNodeID id, GraphNodeRecord node) in nodeIndex) + { m_nodeIndex.Add(id, node); + } m_edges.Clear(); m_edges.AddRange(edges); m_metadata.Clear(); @@ -315,34 +140,34 @@ public void AddNode(GraphNodeRecord node) /// /// Removes a node and every edge connected to it. /// - /// + /// /// Node identifier to remove. /// /// /// when the node existed; otherwise . /// - public bool RemoveNode(GraphNodeId nodeId) + public bool RemoveNode(GraphNodeID nodeID) { - if (!m_nodeIndex.Remove(nodeId, out GraphNodeRecord? node)) + if (!m_nodeIndex.Remove(nodeID, out GraphNodeRecord? node)) { return false; } m_nodes.Remove(node); - m_edges.RemoveAll(edge => edge.output.nodeId == nodeId || edge.input.nodeId == nodeId); + m_edges.RemoveAll(edge => edge.output.nodeID == nodeID || edge.input.nodeID == nodeID); return true; } /// /// Finds a node by stable identifier. /// - /// + /// /// Node identifier to find. /// /// /// The node record, or when absent. /// - public GraphNodeRecord? FindNode(GraphNodeId nodeId) => m_nodeIndex.GetValueOrDefault(nodeId); + public GraphNodeRecord? FindNode(GraphNodeID nodeID) => m_nodeIndex.GetValueOrDefault(nodeID); /// /// Adds an edge while preserving document order. @@ -367,15 +192,15 @@ public void AddEdge(GraphEdgeRecord edge) /// /// Removes an edge by stable identifier. /// - /// + /// /// Edge identifier to remove. /// /// /// when the edge existed; otherwise . /// - public bool RemoveEdge(GraphEdgeId edgeId) + public bool RemoveEdge(GraphEdgeID edgeID) { - int index = m_edges.FindIndex(edge => edge.id == edgeId); + int index = m_edges.FindIndex(edge => edge.id == edgeID); if (index < 0) { return false; diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs index d470d1bb4..bfe187711 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs @@ -35,7 +35,7 @@ SerializationRegistry serialization ) => { nodeWriter.Write("id", node.id.value); - nodeWriter.Write("definition", node.definitionId); + nodeWriter.Write("definition", node.definitionID); nodeWriter.Write("positionX", node.position.x); nodeWriter.Write("positionY", node.position.y); nodeWriter.WriteObjectArray( @@ -48,7 +48,8 @@ SerializationRegistry serialization { valueWriter.Write("id", pair.Key); valueWriter.Write("data", pair.Value.ToArray()); - }); + } + ); }); writer.WriteObjectArray("edges", document.edges, static ( edgeWriter, @@ -56,10 +57,10 @@ SerializationRegistry serialization ) => { edgeWriter.Write("id", edge.id.value); - edgeWriter.Write("outputNode", edge.output.nodeId.value); - edgeWriter.Write("outputPort", edge.output.portId.value); - edgeWriter.Write("inputNode", edge.input.nodeId.value); - edgeWriter.Write("inputPort", edge.input.portId.value); + edgeWriter.Write("outputNode", edge.output.nodeID.value); + edgeWriter.Write("outputPort", edge.output.portID.value); + edgeWriter.Write("inputNode", edge.input.nodeID.value); + edgeWriter.Write("inputPort", edge.input.portID.value); }); writer.WriteObjectArray( "metadata", @@ -71,7 +72,8 @@ SerializationRegistry serialization { metadataWriter.Write("id", pair.Key); metadataWriter.Write("data", pair.Value.ToArray()); - }); + } + ); }); } @@ -98,37 +100,46 @@ SerializationRegistry serialization foreach (SerializationReader nodeReader in reader.ReadObjectArray("nodes")) { var node = new GraphNodeRecord( - new GraphNodeId(nodeReader.Read("id")), - nodeReader.Read("definition")) + new GraphNodeID(nodeReader.Read("id")), + nodeReader.Read("definition") + ) { position = new GraphPosition( nodeReader.Read("positionX"), - nodeReader.Read("positionY")) + nodeReader.Read("positionY") + ) }; foreach (SerializationReader valueReader in nodeReader.ReadObjectArray("values")) { node.SetValue( valueReader.Read("id"), - new GraphSerializedValue(valueReader.Read("data"))); + new GraphSerializedValue(valueReader.Read("data")) + ); } document.AddNode(node); } foreach (SerializationReader edgeReader in reader.ReadObjectArray("edges")) { - document.AddEdge(new GraphEdgeRecord( - new GraphEdgeId(edgeReader.Read("id")), - new GraphEndpoint( - new GraphNodeId(edgeReader.Read("outputNode")), - new GraphPortId(edgeReader.Read("outputPort"))), - new GraphEndpoint( - new GraphNodeId(edgeReader.Read("inputNode")), - new GraphPortId(edgeReader.Read("inputPort"))))); + document.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(edgeReader.Read("id")), + new GraphEndpoint( + new GraphNodeID(edgeReader.Read("outputNode")), + new GraphPortID(edgeReader.Read("outputPort")) + ), + new GraphEndpoint( + new GraphNodeID(edgeReader.Read("inputNode")), + new GraphPortID(edgeReader.Read("inputPort")) + ) + ) + ); } foreach (SerializationReader metadataReader in reader.ReadObjectArray("metadata")) { document.SetMetadata( metadataReader.Read("id"), - new GraphSerializedValue(metadataReader.Read("data"))); + new GraphSerializedValue(metadataReader.Read("data")) + ); } return document; }); diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs b/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs new file mode 100644 index 000000000..e99d635a2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies an edge within one graph document using a stable serialized value. +/// +public readonly record struct GraphEdgeID +{ + /// + /// Creates a stable graph edge identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphEdgeID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs b/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs new file mode 100644 index 000000000..7811ecbde --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs @@ -0,0 +1,44 @@ +namespace Inno.Core.Graphs; + +/// +/// Stores one typed connection between two graph endpoints. +/// +public sealed class GraphEdgeRecord +{ + /// + /// Creates a graph edge record. + /// + /// + /// Stable edge identifier within the document. + /// + /// + /// Source endpoint. + /// + /// + /// Destination endpoint. + /// + public GraphEdgeRecord( + GraphEdgeID id, + GraphEndpoint output, + GraphEndpoint input + ) { + this.id = id; + this.output = output; + this.input = input; + } + + /// + /// Gets the stable edge identifier. + /// + public GraphEdgeID id { get; } + + /// + /// Gets the source endpoint. + /// + public GraphEndpoint output { get; } + + /// + /// Gets the destination endpoint. + /// + public GraphEndpoint input { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs b/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs new file mode 100644 index 000000000..111ea7a4c --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs @@ -0,0 +1,34 @@ +namespace Inno.Core.Graphs; + +/// +/// Identifies one endpoint of a graph edge. +/// +public readonly record struct GraphEndpoint +{ + /// + /// Creates a graph edge endpoint. + /// + /// + /// Owning node identifier. + /// + /// + /// Port identifier within the node definition. + /// + public GraphEndpoint( + GraphNodeID nodeID, + GraphPortID portID + ) { + this.nodeID = nodeID; + this.portID = portID; + } + + /// + /// Gets the owning node identifier. + /// + public GraphNodeID nodeID { get; } + + /// + /// Gets the node-local port identifier. + /// + public GraphPortID portID { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphIds.cs b/src/foundation/core/Inno.Core.Graphs/GraphIds.cs deleted file mode 100644 index af217abd4..000000000 --- a/src/foundation/core/Inno.Core.Graphs/GraphIds.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; - -namespace Inno.Core.Graphs; - -/// -/// Identifies a node within one graph document using a stable serialized value. -/// -public readonly record struct GraphNodeId -{ - /// - /// Creates a stable graph node identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphNodeId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Identifies an edge within one graph document using a stable serialized value. -/// -public readonly record struct GraphEdgeId -{ - /// - /// Creates a stable graph edge identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphEdgeId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Identifies a port within its owning node definition. -/// -public readonly record struct GraphPortId -{ - /// - /// Creates a stable graph port identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphPortId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Stores a graph-space position independently from any editor UI framework. -/// -public readonly record struct GraphPosition -{ - /// - /// Creates a graph-space position. - /// - /// - /// Horizontal graph-space coordinate. - /// - /// - /// Vertical graph-space coordinate. - /// - public GraphPosition( - float x, - float y - ) { - this.x = x; - this.y = y; - } - - /// - /// Gets the horizontal graph-space coordinate. - /// - public float x { get; } - - /// - /// Gets the vertical graph-space coordinate. - /// - public float y { get; } -} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs new file mode 100644 index 000000000..acaf7c84b --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Graphs; + +/// +/// Describes node presentation and resolves ports without entering graph persistence. +/// +public abstract class GraphNodeDefinition +{ + /// + /// Creates a graph node definition. + /// + /// + /// Globally stable definition identifier. + /// + /// + /// Artist-facing display name. + /// + /// + /// Search-menu category path. + /// + protected GraphNodeDefinition( + string id, + string displayName, + string category + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + ArgumentException.ThrowIfNullOrWhiteSpace(category); + this.id = id; + this.displayName = displayName; + this.category = category; + } + + /// + /// Gets the globally stable definition identifier. + /// + public string id { get; } + + /// + /// Gets the artist-facing display name. + /// + public string displayName { get; } + + /// + /// Gets the search-menu category path. + /// + public string category { get; } + + /// + /// Resolves ports for one node record, including any data-driven dynamic ports. + /// + /// + /// Neutral node record to inspect. + /// + /// + /// The complete port definitions for the current node state. + /// + public abstract IReadOnlyList GetPorts(GraphNodeRecord node); +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs new file mode 100644 index 000000000..93801570a --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies a node within one graph document using a stable serialized value. +/// +public readonly record struct GraphNodeID +{ + /// + /// Creates a stable graph node identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphNodeID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs new file mode 100644 index 000000000..7d508e88d --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Core.Graphs; + +/// +/// Stores one node without retaining a CLR type or runtime extension instance. +/// +public sealed class GraphNodeRecord +{ + private readonly Dictionary m_values = new(StringComparer.Ordinal); + private readonly ReadOnlyDictionary m_valueView; + + /// + /// Creates a graph node record. + /// + /// + /// Stable identifier within the document. + /// + /// + /// Stable node definition identifier. + /// + public GraphNodeRecord( + GraphNodeID id, + string definitionID + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); + this.id = id; + this.definitionID = definitionID; + m_valueView = new(m_values); + } + + /// + /// Gets the stable node identifier. + /// + public GraphNodeID id { get; } + + /// + /// Gets the stable node definition identifier. + /// + public string definitionID { get; } + + /// + /// Gets or sets the graph-space node position. + /// + public GraphPosition position { get; set; } + + /// + /// Gets neutral serialized property values keyed by stable property identifier. + /// + public IReadOnlyDictionary values => m_valueView; + + /// + /// Creates or replaces a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// Serialized value. + /// + public void SetValue( + string propertyID, + GraphSerializedValue value + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + ArgumentNullException.ThrowIfNull(value); + m_values[propertyID] = value; + } + + /// + /// Tries to read a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// Receives the value when present. + /// + /// + /// when the property exists; otherwise . + /// + public bool TryGetValue( + string propertyID, + out GraphSerializedValue? value + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + return m_values.TryGetValue(propertyID, out value); + } + + /// + /// Removes a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// when a property was removed; otherwise . + /// + public bool RemoveValue(string propertyID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + return m_values.Remove(propertyID); + } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs new file mode 100644 index 000000000..8d2264cf3 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Graphs; + +/// +/// Declares how many edges may connect to a graph port. +/// +public enum GraphPortCapacity +{ + /// + /// At most one edge may connect to the port. + /// + Single, + /// + /// Any number of edges may connect to the port. + /// + Multiple +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs new file mode 100644 index 000000000..d86a54848 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs @@ -0,0 +1,78 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Describes one dynamically or statically resolved node port. +/// +public sealed class GraphPortDefinition +{ + /// + /// Creates a graph port definition. + /// + /// + /// Stable node-local port identifier. + /// + /// + /// Artist-facing display name. + /// + /// + /// Stable value type identifier. + /// + /// + /// Value-flow direction. + /// + /// + /// Allowed edge capacity. + /// + /// + /// Whether an input must be connected. + /// + public GraphPortDefinition( + GraphPortID id, + string displayName, + string valueTypeID, + GraphPortDirection direction, + GraphPortCapacity capacity = GraphPortCapacity.Single, + bool required = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + ArgumentException.ThrowIfNullOrWhiteSpace(valueTypeID); + this.id = id; + this.displayName = displayName; + this.valueTypeID = valueTypeID; + this.direction = direction; + this.capacity = capacity; + this.required = required; + } + + /// + /// Gets the stable node-local port identifier. + /// + public GraphPortID id { get; } + + /// + /// Gets the artist-facing display name. + /// + public string displayName { get; } + + /// + /// Gets the stable value type identifier. + /// + public string valueTypeID { get; } + + /// + /// Gets the value-flow direction. + /// + public GraphPortDirection direction { get; } + + /// + /// Gets the allowed edge capacity. + /// + public GraphPortCapacity capacity { get; } + + /// + /// Gets whether an input must be connected. + /// + public bool required { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs new file mode 100644 index 000000000..839df0ee6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Graphs; + +/// +/// Declares the direction in which values flow through a graph port. +/// +public enum GraphPortDirection +{ + /// + /// Receives a value from another node. + /// + Input, + /// + /// Produces a value for another node. + /// + Output +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs new file mode 100644 index 000000000..409bf8938 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies a port within its owning node definition. +/// +public readonly record struct GraphPortID +{ + /// + /// Creates a stable graph port identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphPortID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs b/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs new file mode 100644 index 000000000..4f9f9a7d8 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs @@ -0,0 +1,34 @@ +namespace Inno.Core.Graphs; + +/// +/// Stores a graph-space position independently from any editor UI framework. +/// +public readonly record struct GraphPosition +{ + /// + /// Creates a graph-space position. + /// + /// + /// Horizontal graph-space coordinate. + /// + /// + /// Vertical graph-space coordinate. + /// + public GraphPosition( + float x, + float y + ) { + this.x = x; + this.y = y; + } + + /// + /// Gets the horizontal graph-space coordinate. + /// + public float x { get; } + + /// + /// Gets the vertical graph-space coordinate. + /// + public float y { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs b/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs index b53620f4c..4f5d1b50f 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs @@ -23,7 +23,9 @@ public sealed class GraphSerializedValue public GraphSerializedValue(ReadOnlySpan data) { if (data.IsEmpty) + { throw new ArgumentException("A graph value payload cannot be empty.", nameof(data)); + } m_data = data.ToArray(); } @@ -32,30 +34,6 @@ public GraphSerializedValue(ReadOnlySpan data) /// public ReadOnlyMemory data => m_data; - /// - /// Serializes a neutral graph property through the common Inno serializer. - /// - /// - /// Declared serializable value type. - /// - /// - /// Value to serialize. - /// - /// - /// The serialization registry that owns the converter generation for this operation. - /// - /// - /// A detached graph value containing native serialization bytes. - /// - [ScriptingApiIgnore] - public static GraphSerializedValue From( - T value, - SerializationRegistry serialization - ) { - ArgumentNullException.ThrowIfNull(serialization); - return new GraphSerializedValue(serialization.Encode(writer => writer.Write("value", value))); - } - /// /// Deserializes this value through the common Inno serializer. /// @@ -90,4 +68,28 @@ public T Deserialize(SerializationRegistry serialization) /// A new byte array containing the complete native value. /// public byte[] ToArray() => (byte[])m_data.Clone(); + + /// + /// Serializes a neutral graph property through the common Inno serializer. + /// + /// + /// Declared serializable value type. + /// + /// + /// Value to serialize. + /// + /// + /// The serialization registry that owns the converter generation for this operation. + /// + /// + /// A detached graph value containing native serialization bytes. + /// + [ScriptingApiIgnore] + public static GraphSerializedValue From( + T value, + SerializationRegistry serialization + ) { + ArgumentNullException.ThrowIfNull(serialization); + return new GraphSerializedValue(serialization.Encode(writer => writer.Write("value", value))); + } } diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs deleted file mode 100644 index f0869d9b1..000000000 --- a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs +++ /dev/null @@ -1,365 +0,0 @@ -using Inno.Core.Diagnostics; -using System; -using System.Linq; -using System.Collections.Generic; - -using Inno.Core.Collections; - -namespace Inno.Core.Graphs; - -/// -/// Reports one graph validation problem using stable document identifiers. -/// -public sealed class GraphDiagnostic -{ - /// - /// Creates a graph diagnostic. - /// - /// - /// Stable machine-readable diagnostic code. - /// - /// - /// Artist-facing diagnostic text. - /// - /// - /// Diagnostic impact. - /// - /// - /// Optional related node identifier. - /// - /// - /// Optional related edge identifier. - /// - public GraphDiagnostic( - string code, - string message, - DiagnosticSeverity severity, - GraphNodeId? nodeId = null, - GraphEdgeId? edgeId = null - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(code); - ArgumentException.ThrowIfNullOrWhiteSpace(message); - this.code = code; - this.message = message; - this.severity = severity; - this.nodeId = nodeId; - this.edgeId = edgeId; - } - - /// - /// Gets the stable machine-readable diagnostic code. - /// - public string code { get; } - - /// - /// Gets the artist-facing diagnostic text. - /// - public string message { get; } - - /// - /// Gets the diagnostic impact. - /// - public DiagnosticSeverity severity { get; } - - /// - /// Gets the related node identifier, if any. - /// - public GraphNodeId? nodeId { get; } - - /// - /// Gets the related edge identifier, if any. - /// - public GraphEdgeId? edgeId { get; } -} - -/// -/// Contains deterministic graph validation diagnostics. -/// -public sealed class GraphValidationResult -{ - private readonly IReadOnlyList m_diagnostics; - - /// - /// Creates a graph validation result. - /// - /// - /// Diagnostics in deterministic validation order. - /// - public GraphValidationResult(IReadOnlyList diagnostics) - { - ArgumentNullException.ThrowIfNull(diagnostics); - m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets diagnostics in deterministic validation order. - /// - public IReadOnlyList diagnostics => m_diagnostics; - - /// - /// Gets whether no error diagnostic is present. - /// - public bool isValid - { - get - { - foreach (GraphDiagnostic diagnostic in m_diagnostics) - { - if (diagnostic.severity == DiagnosticSeverity.Error) - { - return false; - } - } - - return true; - } - } -} - -/// -/// Validates neutral graph topology against generation-scoped node definitions. -/// -public static class GraphValidator -{ - /// - /// Validates node availability, ports, edge types, capacity, required inputs and cycles. - /// - /// - /// Graph document to validate without modifying it. - /// - /// - /// Active node definition resolver. - /// - /// - /// Optional directed type conversion policy. - /// - /// - /// Whether directed cycles are permitted. - /// - /// - /// A deterministic validation result. Missing definitions remain warnings so documents stay editable. - /// - public static GraphValidationResult Validate( - GraphDocument document, - IGraphNodeDefinitionResolver resolver, - IGraphTypeConversion? conversion = null, - bool allowCycles = false - ) { - ArgumentNullException.ThrowIfNull(document); - ArgumentNullException.ThrowIfNull(resolver); - - List diagnostics = []; - Dictionary> portsByNode = []; - - ResolvePorts(document, resolver, portsByNode, diagnostics); - ValidateEdges(document, portsByNode, conversion, diagnostics); - ValidateRequiredInputs(document, portsByNode, diagnostics); - - if (!allowCycles) - { - ValidateCycles(document, diagnostics); - } - - return new GraphValidationResult(diagnostics); - } - - private static void ResolvePorts( - GraphDocument document, - IGraphNodeDefinitionResolver resolver, - Dictionary> portsByNode, - List diagnostics - ) { - foreach (GraphNodeRecord node in document.nodes) - { - if (!resolver.TryResolve(node.definitionId, out GraphNodeDefinition? definition) || definition is null) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_NODE", - $"Node definition '{node.definitionId}' is not active. The node and its connections were preserved.", - DiagnosticSeverity.Warning, - node.id)); - continue; - } - - try - { - Dictionary ports = []; - foreach (GraphPortDefinition port in definition.GetPorts(node)) - { - if (!ports.TryAdd(port.id, port)) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_DUPLICATE_PORT", - $"Node definition '{node.definitionId}' returned duplicate port '{port.id}'.", - DiagnosticSeverity.Error, - node.id)); - } - } - - portsByNode[node.id] = ports; - } - catch (Exception exception) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_NODE_RESOLUTION_FAILED", - $"Node '{node.id}' could not resolve its ports: {exception.Message}", - DiagnosticSeverity.Error, - node.id)); - } - } - } - - private static void ValidateEdges( - GraphDocument document, - IReadOnlyDictionary> portsByNode, - IGraphTypeConversion? conversion, - List diagnostics - ) { - Dictionary connectionCounts = []; - - foreach (GraphEdgeRecord edge in document.edges) - { - GraphNodeRecord? outputNode = document.FindNode(edge.output.nodeId); - GraphNodeRecord? inputNode = document.FindNode(edge.input.nodeId); - if (outputNode is null || inputNode is null) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_ENDPOINT_NODE", - $"Edge '{edge.id}' references a node that is not present in the document.", - DiagnosticSeverity.Error, - edgeId: edge.id)); - continue; - } - - if (!TryGetPort(portsByNode, edge.output, out GraphPortDefinition outputPort) - || !TryGetPort(portsByNode, edge.input, out GraphPortDefinition inputPort)) - { - if (portsByNode.ContainsKey(edge.output.nodeId) && portsByNode.ContainsKey(edge.input.nodeId)) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_ENDPOINT_PORT", - $"Edge '{edge.id}' references a port that is not active on its node.", - DiagnosticSeverity.Error, - edgeId: edge.id)); - } - - continue; - } - - if (outputPort.direction != GraphPortDirection.Output || inputPort.direction != GraphPortDirection.Input) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_INVALID_DIRECTION", - $"Edge '{edge.id}' must connect an output port to an input port.", - DiagnosticSeverity.Error, - edgeId: edge.id)); - } - - bool compatible = StringComparer.Ordinal.Equals(outputPort.valueTypeId, inputPort.valueTypeId) - || (conversion?.CanConvert(outputPort.valueTypeId, inputPort.valueTypeId) ?? false); - if (!compatible) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_INCOMPATIBLE_TYPES", - $"Edge '{edge.id}' cannot convert '{outputPort.valueTypeId}' to '{inputPort.valueTypeId}'.", - DiagnosticSeverity.Error, - edgeId: edge.id)); - } - - CountConnection(edge.output, outputPort, connectionCounts, edge.id, diagnostics); - CountConnection(edge.input, inputPort, connectionCounts, edge.id, diagnostics); - } - } - - private static void CountConnection( - GraphEndpoint endpoint, - GraphPortDefinition port, - Dictionary connectionCounts, - GraphEdgeId edgeId, - List diagnostics - ) { - connectionCounts.TryGetValue(endpoint, out int currentCount); - currentCount++; - connectionCounts[endpoint] = currentCount; - if (port.capacity == GraphPortCapacity.Single && currentCount > 1) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_PORT_CAPACITY", - $"Port '{endpoint.portId}' accepts only one connection.", - DiagnosticSeverity.Error, - endpoint.nodeId, - edgeId)); - } - } - - private static void ValidateRequiredInputs( - GraphDocument document, - IReadOnlyDictionary> portsByNode, - List diagnostics - ) { - HashSet connectedInputs = []; - foreach (GraphEdgeRecord edge in document.edges) - { - connectedInputs.Add(edge.input); - } - - foreach ((GraphNodeId nodeId, IReadOnlyDictionary ports) in portsByNode) - { - foreach (GraphPortDefinition port in ports.Values) - { - if (port.direction == GraphPortDirection.Input - && port.required - && !connectedInputs.Contains(new GraphEndpoint(nodeId, port.id))) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_REQUIRED_INPUT", - $"Required input '{port.displayName}' is not connected.", - DiagnosticSeverity.Error, - nodeId)); - } - } - } - } - - private static void ValidateCycles( - GraphDocument document, - List diagnostics - ) { - var graph = new DependencyGraph(); - foreach (GraphNodeRecord node in document.nodes) - graph.AddNode(node.id); - - foreach (GraphEdgeRecord edge in document.edges) - { - if (graph.ContainsNode(edge.output.nodeId) && graph.ContainsNode(edge.input.nodeId)) - graph.AddDependency(edge.input.nodeId, edge.output.nodeId); - } - - if (graph.TryFindCycle(out IReadOnlyList cycle)) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_CYCLE", - "The graph contains a directed cycle.", - DiagnosticSeverity.Error, - cycle[0])); - } - } - - private static bool TryGetPort( - IReadOnlyDictionary> portsByNode, - GraphEndpoint endpoint, - out GraphPortDefinition port - ) { - if (portsByNode.TryGetValue( - endpoint.nodeId, - out IReadOnlyDictionary? ports) - && ports.TryGetValue(endpoint.portId, out GraphPortDefinition? resolved)) - { - port = resolved; - return true; - } - - port = null!; - return false; - } -} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs new file mode 100644 index 000000000..98ced9e75 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Core.Graphs; + +/// +/// Contains deterministic graph validation diagnostics. +/// +public sealed class GraphValidationResult +{ + private readonly IReadOnlyList m_diagnostics; + + /// + /// Creates a graph validation result. + /// + /// + /// Diagnostics in deterministic validation order. + /// + public GraphValidationResult(IReadOnlyList diagnostics) + { + ArgumentNullException.ThrowIfNull(diagnostics); + m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets diagnostics in deterministic validation order. + /// + public IReadOnlyList diagnostics => m_diagnostics; + + /// + /// Gets whether no error diagnostic is present. + /// + public bool isValid + { + get + { + foreach (GraphDiagnostic diagnostic in m_diagnostics) + { + if (diagnostic.severity == DiagnosticSeverity.Error) + { + return false; + } + } + + return true; + } + } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidator.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidator.cs new file mode 100644 index 000000000..d8900e956 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphValidator.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Collections; +using Inno.Core.Diagnostics; + +namespace Inno.Core.Graphs; + +/// +/// Validates neutral graph topology against generation-scoped node definitions. +/// +public static class GraphValidator +{ + /// + /// Validates node availability, ports, edge types, capacity, required inputs and cycles. + /// + /// + /// Graph document to validate without modifying it. + /// + /// + /// Active node definition resolver. + /// + /// + /// Optional directed type conversion policy. + /// + /// + /// Whether directed cycles are permitted. + /// + /// + /// A deterministic validation result. Missing definitions remain warnings so documents stay editable. + /// + public static GraphValidationResult Validate( + GraphDocument document, + IGraphNodeDefinitionResolver resolver, + IGraphTypeConversion? conversion = null, + bool allowCycles = false + ) { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(resolver); + + List diagnostics = []; + Dictionary> portsByNode = []; + + ResolvePorts(document, resolver, portsByNode, diagnostics); + ValidateEdges(document, portsByNode, conversion, diagnostics); + ValidateRequiredInputs(document, portsByNode, diagnostics); + + if (!allowCycles) + { + ValidateCycles(document, diagnostics); + } + + return new GraphValidationResult(diagnostics); + } + + private static void ResolvePorts( + GraphDocument document, + IGraphNodeDefinitionResolver resolver, + Dictionary> portsByNode, + List diagnostics + ) { + foreach (GraphNodeRecord node in document.nodes) + { + if (!resolver.TryResolve(node.definitionID, out GraphNodeDefinition? definition) || definition is null) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_NODE", + $"Node definition '{node.definitionID}' is not active. The node and its connections were preserved.", + DiagnosticSeverity.Warning, + node.id + ) + ); + continue; + } + + try + { + Dictionary ports = []; + foreach (GraphPortDefinition port in definition.GetPorts(node)) + { + if (!ports.TryAdd(port.id, port)) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_DUPLICATE_PORT", + $"Node definition '{node.definitionID}' returned duplicate port '{port.id}'.", + DiagnosticSeverity.Error, + node.id + ) + ); + } + } + + portsByNode[node.id] = ports; + } + catch (Exception exception) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_NODE_RESOLUTION_FAILED", + $"Node '{node.id}' could not resolve its ports: {exception.Message}", + DiagnosticSeverity.Error, + node.id + ) + ); + } + } + } + + private static void ValidateEdges( + GraphDocument document, + IReadOnlyDictionary> portsByNode, + IGraphTypeConversion? conversion, + List diagnostics + ) { + Dictionary connectionCounts = []; + + foreach (GraphEdgeRecord edge in document.edges) + { + GraphNodeRecord? outputNode = document.FindNode(edge.output.nodeID); + GraphNodeRecord? inputNode = document.FindNode(edge.input.nodeID); + if (outputNode is null || inputNode is null) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_ENDPOINT_NODE", + $"Edge '{edge.id}' references a node that is not present in the document.", + DiagnosticSeverity.Error, + edgeID: edge.id + ) + ); + continue; + } + + if (!TryGetPort(portsByNode, edge.output, out GraphPortDefinition outputPort) + || !TryGetPort(portsByNode, edge.input, out GraphPortDefinition inputPort) + ) { + if (portsByNode.ContainsKey(edge.output.nodeID) && portsByNode.ContainsKey(edge.input.nodeID)) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_ENDPOINT_PORT", + $"Edge '{edge.id}' references a port that is not active on its node.", + DiagnosticSeverity.Error, + edgeID: edge.id + ) + ); + } + + continue; + } + + if (outputPort.direction != GraphPortDirection.Output || inputPort.direction != GraphPortDirection.Input) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_INVALID_DIRECTION", + $"Edge '{edge.id}' must connect an output port to an input port.", + DiagnosticSeverity.Error, + edgeID: edge.id + ) + ); + } + + bool compatible = StringComparer.Ordinal.Equals(outputPort.valueTypeID, inputPort.valueTypeID) + || (conversion?.CanConvert(outputPort.valueTypeID, inputPort.valueTypeID) ?? false); + if (!compatible) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_INCOMPATIBLE_TYPES", + $"Edge '{edge.id}' cannot convert '{outputPort.valueTypeID}' to '{inputPort.valueTypeID}'.", + DiagnosticSeverity.Error, + edgeID: edge.id + ) + ); + } + + CountConnection(edge.output, outputPort, connectionCounts, edge.id, diagnostics); + CountConnection(edge.input, inputPort, connectionCounts, edge.id, diagnostics); + } + } + + private static void CountConnection( + GraphEndpoint endpoint, + GraphPortDefinition port, + Dictionary connectionCounts, + GraphEdgeID edgeID, + List diagnostics + ) { + connectionCounts.TryGetValue(endpoint, out int currentCount); + currentCount++; + connectionCounts[endpoint] = currentCount; + if (port.capacity == GraphPortCapacity.Single && currentCount > 1) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_PORT_CAPACITY", + $"Port '{endpoint.portID}' accepts only one connection.", + DiagnosticSeverity.Error, + endpoint.nodeID, + edgeID + ) + ); + } + } + + private static void ValidateRequiredInputs( + GraphDocument document, + IReadOnlyDictionary> portsByNode, + List diagnostics + ) { + HashSet connectedInputs = []; + foreach (GraphEdgeRecord edge in document.edges) + { + connectedInputs.Add(edge.input); + } + + foreach ((GraphNodeID nodeID, IReadOnlyDictionary ports) in portsByNode) + { + foreach (GraphPortDefinition port in ports.Values) + { + if (port.direction == GraphPortDirection.Input + && port.required + && !connectedInputs.Contains(new GraphEndpoint(nodeID, port.id)) + ) { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_REQUIRED_INPUT", + $"Required input '{port.displayName}' is not connected.", + DiagnosticSeverity.Error, + nodeID + ) + ); + } + } + } + } + + private static void ValidateCycles( + GraphDocument document, + List diagnostics + ) { + var graph = new DependencyGraph(); + foreach (GraphNodeRecord node in document.nodes) + { + graph.AddNode(node.id); + } + + foreach (GraphEdgeRecord edge in document.edges) + { + if (graph.ContainsNode(edge.output.nodeID) && graph.ContainsNode(edge.input.nodeID)) + { + graph.AddDependency(edge.input.nodeID, edge.output.nodeID); + } + } + + if (graph.TryFindCycle(out IReadOnlyList cycle)) + { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_CYCLE", + "The graph contains a directed cycle.", + DiagnosticSeverity.Error, + cycle[0] + ) + ); + } + } + + private static bool TryGetPort( + IReadOnlyDictionary> portsByNode, + GraphEndpoint endpoint, + out GraphPortDefinition port + ) { + if (portsByNode.TryGetValue(endpoint.nodeID, out IReadOnlyDictionary? ports) + && ports.TryGetValue(endpoint.portID, out GraphPortDefinition? resolved) + ) { + port = resolved; + return true; + } + + port = null!; + return false; + } +} diff --git a/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs b/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs new file mode 100644 index 000000000..67acad2f2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs @@ -0,0 +1,24 @@ +namespace Inno.Core.Graphs; + +/// +/// Resolves generation-scoped node definitions by stable identifier. +/// +public interface IGraphNodeDefinitionResolver +{ + /// + /// Tries to resolve an active node definition. + /// + /// + /// Stable definition identifier. + /// + /// + /// Receives the generation-scoped definition. + /// + /// + /// when active; otherwise . + /// + bool TryResolve( + string definitionID, + out GraphNodeDefinition? definition + ); +} diff --git a/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs b/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs new file mode 100644 index 000000000..51dd8d143 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs @@ -0,0 +1,24 @@ +namespace Inno.Core.Graphs; + +/// +/// Determines whether one graph value type can be converted to another. +/// +public interface IGraphTypeConversion +{ + /// + /// Tests a directed value conversion. + /// + /// + /// Source value type identifier. + /// + /// + /// Destination value type identifier. + /// + /// + /// when the conversion is valid; otherwise . + /// + bool CanConvert( + string sourceTypeID, + string destinationTypeID + ); +} diff --git a/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs index 3c3fefa98..7d34a3dbb 100644 --- a/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs @@ -2,14 +2,11 @@ using Inno.Core.Graphs; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Graphs", - "Inno.Core.Graphs", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Graphs", "Inno.Core.Graphs", ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(GraphNodeId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(GraphEdgeId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(GraphPortId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(GraphNodeID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(GraphEdgeID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(GraphPortID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GraphPosition), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GraphSerializedValue), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GraphNodeRecord), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs index 34f20eca0..f062764ed 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs @@ -21,11 +21,6 @@ public static class AtomicDirectory /// /// Cancels preparation or bounded waits before the rename commits. /// - /// - /// Windows access and sharing failures are retried for at most two seconds to tolerate temporary readers. - /// Cancellation observed after a blocked rename takes precedence over its timeout error. - /// Failure preserves the candidate and any existing destination. A committed rename is not canceled afterward. - /// /// /// A path is blank or the two directory trees overlap. /// @@ -41,6 +36,11 @@ public static class AtomicDirectory /// /// Cancellation is observed before publication, including while handling a failed rename. /// + /// + /// Windows access and sharing failures are retried for at most two seconds to tolerate temporary readers. + /// Cancellation observed after a blocked rename takes precedence over its timeout error. + /// Failure preserves the candidate and any existing destination. A committed rename is not canceled afterward. + /// public static void Publish( string source, string destination, @@ -52,13 +52,19 @@ public static void Publish( string candidate = Path.GetFullPath(source); string target = Path.GetFullPath(destination); if (IsContained(Path.GetRelativePath(candidate, target)) - || IsContained(Path.GetRelativePath(target, candidate))) + || IsContained(Path.GetRelativePath(target, candidate)) + ) { throw new ArgumentException("The candidate and destination directory trees must be disjoint.", nameof(destination)); + } if (!Directory.Exists(candidate)) + { throw new DirectoryNotFoundException($"Directory candidate '{candidate}' does not exist."); + } string? parent = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(parent)) + { throw new IOException($"Directory path '{target}' has no owning directory."); + } Directory.CreateDirectory(parent); FileSystemRename.MoveDirectory(candidate, target, cancellationToken); } @@ -75,13 +81,6 @@ public static void Publish( /// /// Cancels preparation or bounded rename waits before the candidate commits. /// - /// - /// The caller must serialize readers and writers while the two directory moves run. - /// Cancellation before commit restores the previous destination without canceling rollback. - /// Cancellation observed after a blocked rename takes precedence over its timeout error. - /// A committed candidate is not canceled afterward. - /// Backup cleanup runs after commit; its failure preserves the installed candidate and remaining backup. - /// /// /// Either path is blank, or the candidate and destination trees overlap. /// @@ -103,6 +102,13 @@ public static void Publish( /// /// Cancellation is observed before the candidate commits, including while handling a failed rename. Any moved previous tree is restored. /// + /// + /// The caller must serialize readers and writers while the two directory moves run. + /// Cancellation before commit restores the previous destination without canceling rollback. + /// Cancellation observed after a blocked rename takes precedence over its timeout error. + /// A committed candidate is not canceled afterward. + /// Backup cleanup runs after commit; its failure preserves the installed candidate and remaining backup. + /// public static void Install( string source, string destination, @@ -116,17 +122,25 @@ public static void Install( string relativeTarget = Path.GetRelativePath(candidate, target); string relativeCandidate = Path.GetRelativePath(target, candidate); if (IsContained(relativeTarget) || IsContained(relativeCandidate)) + { throw new ArgumentException("The candidate and destination directory trees must be disjoint.", nameof(destination)); + } if (!Directory.Exists(candidate)) + { throw new DirectoryNotFoundException($"Atomic directory candidate '{candidate}' does not exist."); + } string? parent = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(parent)) + { throw new IOException($"Directory path '{target}' has no owning directory."); + } Directory.CreateDirectory(parent); string backup = target + ".backup-" + Guid.NewGuid().ToString("N"); if (Directory.Exists(target)) + { FileSystemRename.MoveDirectory(target, backup, cancellationToken); + } try { FileSystemRename.MoveDirectory(candidate, target, cancellationToken); @@ -144,14 +158,17 @@ public static void Install( throw new AggregateException( $"Directory installation failed; the previous tree remains at '{backup}' and could not be restored to '{target}'.", installationFailure, - restorationFailure); + restorationFailure + ); } } throw; } if (!Directory.Exists(backup)) + { return; + } try { Directory.Delete(backup, recursive: true); diff --git a/src/foundation/core/Inno.Core.IO/AtomicFile.cs b/src/foundation/core/Inno.Core.IO/AtomicFile.cs index 9d6d72289..b0f79260e 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicFile.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicFile.cs @@ -19,19 +19,19 @@ public static class AtomicFile /// /// True for a nonempty destination name followed by the reserved marker and a complete hexadecimal operation identity. /// - /// - /// Recognition excludes transient payloads from source discovery. It does not establish ownership or authorize deletion. - /// /// /// The path is null. /// + /// + /// Recognition excludes transient payloads from source discovery. It does not establish ownership or authorize deletion. + /// public static bool IsCandidatePath(string path) { ArgumentNullException.ThrowIfNull(path); ReadOnlySpan name = Path.GetFileName(path.AsSpan()); int marker = name.Length - C_CANDIDATE_MARKER.Length - 32; return marker > 0 && name.Slice(marker, C_CANDIDATE_MARKER.Length).SequenceEqual(C_CANDIDATE_MARKER) - && Guid.TryParseExact(name[(marker + C_CANDIDATE_MARKER.Length)..], "N", out _); + && Guid.TryParseExact(name[(marker + C_CANDIDATE_MARKER.Length)..], "N", out _); } /// @@ -63,13 +63,13 @@ public static void WriteAllBytes( try { using (var stream = new FileStream( - candidate, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 32 * 1024, - FileOptions.WriteThrough)) - { + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 32 * 1024, + FileOptions.WriteThrough + )) { stream.Write(data); stream.Flush(flushToDisk: true); } @@ -78,7 +78,9 @@ public static void WriteAllBytes( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } @@ -94,12 +96,6 @@ public static void WriteAllBytes( /// /// Whether an existing destination may be replaced; false never overwrites an external creator. /// - /// - /// A failed create-only publication preserves the candidate. After successful publication the - /// candidate is removed; a subsequent cleanup failure reports that the complete target exists. - /// Unix create-only publication requires same-directory hard-link support. The caller must own - /// the candidate and parent directory until the operation completes. - /// /// /// Publication fails, create-only mode finds an existing destination, or candidate retirement /// fails after the complete destination has been published. @@ -107,6 +103,12 @@ public static void WriteAllBytes( /// /// The host does not provide an atomic create-only filesystem primitive. /// + /// + /// A failed create-only publication preserves the candidate. After successful publication the + /// candidate is removed; a subsequent cleanup failure reports that the complete target exists. + /// Unix create-only publication requires same-directory hard-link support. The caller must own + /// the candidate and parent directory until the operation completes. + /// public static void Install( string source, string destination, @@ -116,16 +118,23 @@ public static void Install( string candidate = Path.GetFullPath(source); string target = NormalizeDestination(destination); if (!File.Exists(candidate)) + { throw new FileNotFoundException("The atomic file candidate does not exist.", candidate); + } if (string.Equals(candidate, target, StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("The atomic file candidate and destination must be different paths.", nameof(source)); + } string candidateDirectory = Path.GetDirectoryName(candidate)!; string targetDirectory = Path.GetDirectoryName(target)!; if (!string.Equals(candidateDirectory, targetDirectory, StringComparison.Ordinal)) + { throw new ArgumentException( "Atomic file installation requires the candidate and destination to share a directory.", - nameof(source)); + nameof(source) + ); + } FileSystemRename.MoveFile(candidate, target, overwrite); } @@ -136,9 +145,10 @@ private static string NormalizeDestination(string path) string destination = Path.GetFullPath(path); string? directory = Path.GetDirectoryName(destination); if (string.IsNullOrEmpty(directory)) + { throw new IOException($"File path '{destination}' has no owning directory."); + } Directory.CreateDirectory(directory); return destination; } - } diff --git a/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs b/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs index e1926d922..6b3497f81 100644 --- a/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs +++ b/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs @@ -22,6 +22,26 @@ FileLease leaf m_leaf = leaf; } + /// + /// Releases the leaf before its persistent owner gate; neither file is deleted. + /// + public void Dispose() + { + FileLease? leaf = Interlocked.Exchange(ref m_leaf, null); + if (leaf is null) + { + return; + } + try + { + leaf.Dispose(); + } + finally + { + m_owner.Dispose(); + } + } + /// /// Acquires owner reading rights before opening or waiting for a leaf lease. /// @@ -60,26 +80,36 @@ public static async ValueTask AcquireAsync( CancellationToken cancellationToken = default ) { if (!Path.IsPathFullyQualified(coordinationPath) || !Path.IsPathFullyQualified(leafPath)) + { throw new ArgumentException("Coordinated leases require absolute owner and leaf paths."); + } string ownerPath = Path.GetFullPath(coordinationPath); string leaf = Path.GetFullPath(leafPath); string root = Path.GetDirectoryName(ownerPath)!; PathBoundary.RequireUnlinkedPath(root, leaf); if (string.Equals(ownerPath, leaf, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + { throw new ArgumentException("The leaf must differ from its persistent owner gate.", nameof(leafPath)); + } if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } Stopwatch elapsed = Stopwatch.StartNew(); if (!File.Exists(ownerPath)) + { using (await FileLease.AcquireAsync(ownerPath, Remaining(), cancellationToken).ConfigureAwait(false)) { } + } FileLease owner = await FileLease.AcquireSharedAsync(ownerPath, Remaining(), cancellationToken).ConfigureAwait(false); try { if (shared && !File.Exists(leaf)) + { using (await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false)) { } + } FileLease acquired = shared - ? await FileLease.AcquireSharedAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false) - : await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false); + ? await FileLease.AcquireSharedAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false) + : await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false); return new(owner, acquired); } catch @@ -88,25 +118,9 @@ public static async ValueTask AcquireAsync( throw; } - TimeSpan Remaining() => timeout == Timeout.InfiniteTimeSpan ? timeout - : timeout > elapsed.Elapsed ? timeout - elapsed.Elapsed : TimeSpan.Zero; - } - - /// - /// Releases the leaf before its persistent owner gate; neither file is deleted. - /// - public void Dispose() - { - FileLease? leaf = Interlocked.Exchange(ref m_leaf, null); - if (leaf is null) - return; - try - { - leaf.Dispose(); - } - finally - { - m_owner.Dispose(); - } + TimeSpan Remaining() + => timeout == Timeout.InfiniteTimeSpan + ? timeout + : timeout > elapsed.Elapsed ? timeout - elapsed.Elapsed : TimeSpan.Zero; } } diff --git a/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs b/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs index 2b96829d2..173d8e814 100644 --- a/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs +++ b/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs @@ -13,8 +13,12 @@ internal DirectoryCleanupException( string installedDirectory, string backupDirectory, Exception cleanupFailure - ) : base($"Directory '{installedDirectory}' was installed, but backup cleanup failed. " - + $"The remaining backup is at '{backupDirectory}'.", cleanupFailure) { + ) : base( + $"Directory '{installedDirectory}' was installed, but backup cleanup failed. " + + $"The remaining backup is at '{backupDirectory}'.", + cleanupFailure + ) + { this.installedDirectory = installedDirectory; this.backupDirectory = backupDirectory; } diff --git a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs index 9c8695b7d..c9839b0ef 100644 --- a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs @@ -23,30 +23,32 @@ public FileByteDocumentStore(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A file document requires an absolute path.", nameof(path)); + } m_path = Path.GetFullPath(path); } - /// + /// public string documentName => m_path; - /// + /// public bool canWrite => true; - /// + /// public bool exists => File.Exists(m_path); - /// - /// - /// One rename-compatible handle pins the selected complete publication until its owned bytes are read. - /// Writers must atomically replace the document rather than modify the selected file in place. - /// /// /// The document cannot be read completely or exceeds the maximum supported byte-array size. /// /// /// The selected location denies reading or names a directory instead of a document. /// + /// + /// One rename-compatible handle pins the selected complete publication until its owned bytes are read. + /// Writers must atomically replace the document rather than modify the selected file in place. + /// + /// public byte[]? Read() { try @@ -54,7 +56,9 @@ public FileByteDocumentStore(string path) using var stream = new FileStream(m_path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); long length = stream.Length; if (length > Array.MaxLength) + { throw new IOException("The file document exceeds the maximum supported byte-array size."); + } byte[] data = GC.AllocateUninitializedArray((int)length); stream.ReadExactly(data); return data; @@ -69,6 +73,6 @@ public FileByteDocumentStore(string path) } } - /// + /// public void Write(ReadOnlySpan data) => AtomicFile.WriteAllBytes(m_path, data); } diff --git a/src/foundation/core/Inno.Core.IO/FileLease.cs b/src/foundation/core/Inno.Core.IO/FileLease.cs index 5ca5b19b2..f4fb7bfec 100644 --- a/src/foundation/core/Inno.Core.IO/FileLease.cs +++ b/src/foundation/core/Inno.Core.IO/FileLease.cs @@ -13,7 +13,15 @@ public sealed class FileLease : IDisposable { private readonly FileStream m_stream; - private FileLease(FileStream stream) => m_stream = stream; + private FileLease(FileStream stream) + { + m_stream = stream; + } + + /// + /// Releases ownership; repeated disposal has no effect and the lease file is retained. + /// + public void Dispose() => m_stream.Dispose(); /// /// Waits for exclusive ownership without blocking an owner thread or changing shared data. @@ -30,10 +38,6 @@ public sealed class FileLease : IDisposable /// /// The exclusive lease whose disposal permits the next participant to acquire ownership. /// - /// - /// Lease files remain after disposal. Removing them would let Unix processes lock different - /// inodes for the same path while an earlier participant still owns the original inode. - /// /// /// The path is empty or relative, or the timeout is negative and not infinite. /// @@ -49,12 +53,22 @@ public sealed class FileLease : IDisposable /// /// The operating system denies access to the lease path. /// + /// + /// Lease files remain after disposal. Removing them would let Unix processes lock different + /// inodes for the same path while an earlier participant still owns the original inode. + /// public static async ValueTask AcquireAsync( string path, TimeSpan timeout, CancellationToken cancellationToken = default - ) => await AcquireCoreAsync(path, timeout, FileMode.OpenOrCreate, FileAccess.ReadWrite, - FileShare.None, cancellationToken).ConfigureAwait(false); + ) => await AcquireCoreAsync( + path, + timeout, + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + FileShare.None, + cancellationToken + ).ConfigureAwait(false); /// /// Pins an existing generation against exclusive retirement while permitting other readers. @@ -84,13 +98,14 @@ public static async ValueTask AcquireSharedAsync( string path, TimeSpan timeout, CancellationToken cancellationToken = default - ) => await AcquireCoreAsync(path, timeout, FileMode.Open, FileAccess.Read, - FileShare.Read, cancellationToken).ConfigureAwait(false); - - /// - /// Releases ownership; repeated disposal has no effect and the lease file is retained. - /// - public void Dispose() => m_stream.Dispose(); + ) => await AcquireCoreAsync( + path, + timeout, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + cancellationToken + ).ConfigureAwait(false); private static async ValueTask AcquireCoreAsync( string path, @@ -102,9 +117,13 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A file lease requires an absolute path.", nameof(path)); + } if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } cancellationToken.ThrowIfCancellationRequested(); Directory.CreateDirectory(Path.GetDirectoryName(path)!); Stopwatch elapsed = Stopwatch.StartNew(); @@ -113,7 +132,7 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); try { - FileStream stream = new(path, mode, access, sharing); + var stream = new FileStream(path, mode, access, sharing); if (cancellationToken.IsCancellationRequested) { stream.Dispose(); @@ -124,19 +143,25 @@ CancellationToken cancellationToken catch (IOException failure) when (IsCompetingOwnership(failure)) { if (timeout != Timeout.InfiniteTimeSpan && elapsed.Elapsed >= timeout) + { throw new TimeoutException($"File ownership timed out at '{path}'.", failure); + } TimeSpan delay = TimeSpan.FromMilliseconds(20); if (timeout != Timeout.InfiniteTimeSpan && timeout - elapsed.Elapsed < delay) + { delay = timeout - elapsed.Elapsed; + } if (delay > TimeSpan.Zero) + { await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } } } } private static bool IsCompetingOwnership(IOException failure) // .NET reports Unix flock contention as raw errno; Darwin uses EWOULDBLOCK 35. - => OperatingSystem.IsWindows() ? (failure.HResult & 0xffff) is 32 or 33 - : failure.HResult == (OperatingSystem.IsMacOS() ? 35 : 11); - + => OperatingSystem.IsWindows() + ? (failure.HResult & 0xFFFF) is 32 or 33 + : failure.HResult == (OperatingSystem.IsMacOS() ? 35 : 11); } diff --git a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs index 41cb8e0cd..fa875bbe1 100644 --- a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs +++ b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs @@ -48,14 +48,18 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (Stopwatch.GetElapsedTime(started).TotalMilliseconds >= C_RETRY_WINDOW_MILLISECONDS) + { throw; + } // Windows readers and indexers may briefly open files without delete sharing. // Retry only the atomic rename; permanent access failures retain their original exception. if (cancellationToken.CanBeCanceled) { if (cancellationToken.WaitHandle.WaitOne(C_RETRY_INTERVAL_MILLISECONDS)) + { cancellationToken.ThrowIfCancellationRequested(); + } } else { @@ -68,6 +72,6 @@ CancellationToken cancellationToken private static bool IsTemporarilyBlocked(Exception exception) => OperatingSystem.IsWindows() && exception is IOException or UnauthorizedAccessException - && exception.HResult is unchecked((int)0x80070005) - or unchecked((int)0x80070020) or unchecked((int)0x80070021); + && exception.HResult is unchecked((int)0x8007_0005) + or unchecked((int)0x8007_0020) or unchecked((int)0x8007_0021); } diff --git a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs index eb142ee3b..f71ad8190 100644 --- a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs +++ b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs @@ -34,65 +34,79 @@ IDisposable owner ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(owner); if (!input.CanRead) + { throw new ArgumentException("An owned read stream requires readable input.", nameof(input)); + } m_input = input; m_owner = owner; } - /// + /// public override bool CanRead => !m_inputClosed && m_input.CanRead; - /// + + /// public override bool CanSeek => !m_inputClosed && m_input.CanSeek; - /// + + /// public override bool CanWrite => false; - /// + + /// public override long Length => m_input.Length; - /// + + /// public override long Position { get => m_input.Position; set => m_input.Position = value; } - /// + /// + public override int Read(Span buffer) => m_input.Read(buffer); + + /// public override int Read( byte[] buffer, int offset, int count ) => m_input.Read(buffer, offset, count); - /// - public override int Read(Span buffer) => m_input.Read(buffer); - /// + + /// public override int ReadByte() => m_input.ReadByte(); - /// + + /// public override ValueTask ReadAsync( Memory buffer, CancellationToken cancellationToken = default ) => m_input.ReadAsync(buffer, cancellationToken); - /// + + /// public override Task ReadAsync( byte[] buffer, int offset, int count, CancellationToken cancellationToken ) => m_input.ReadAsync(buffer, offset, count, cancellationToken); - /// + + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); - /// + + /// public override void Flush() => throw new NotSupportedException(); - /// + + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) diff --git a/src/foundation/core/Inno.Core.IO/PathBoundary.cs b/src/foundation/core/Inno.Core.IO/PathBoundary.cs index dab3ee47d..dd0c0e009 100644 --- a/src/foundation/core/Inno.Core.IO/PathBoundary.cs +++ b/src/foundation/core/Inno.Core.IO/PathBoundary.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; namespace Inno.Core.IO; @@ -33,7 +33,9 @@ string relativePath ArgumentException.ThrowIfNullOrWhiteSpace(root); ArgumentNullException.ThrowIfNull(relativePath); if (Path.IsPathRooted(relativePath)) + { throw new ArgumentException("A contained path must be relative.", nameof(relativePath)); + } string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); string candidate = Path.GetFullPath(relativePath.Length == 0 ? "." : relativePath, normalizedRoot); EnsureContains(normalizedRoot, candidate); @@ -94,7 +96,8 @@ string path if (!string.Equals(normalizedRoot, candidate, StringComparison.Ordinal)) { string prefix = Path.EndsInDirectorySeparator(normalizedRoot) - ? normalizedRoot : normalizedRoot + Path.DirectorySeparatorChar; + ? normalizedRoot + : normalizedRoot + Path.DirectorySeparatorChar; string relative = candidate[prefix.Length..]; foreach (string segment in relative.Split(Path.DirectorySeparatorChar)) { @@ -135,7 +138,9 @@ public static IEnumerable EnumerateFiles(string root) ArgumentException.ThrowIfNullOrWhiteSpace(root); string normalizedRoot = Path.GetFullPath(root); if (!Directory.Exists(normalizedRoot)) + { throw new DirectoryNotFoundException($"Owned directory '{normalizedRoot}' does not exist."); + } var pending = new Stack(); pending.Push(normalizedRoot); while (pending.Count > 0) @@ -146,9 +151,13 @@ public static IEnumerable EnumerateFiles(string root) { FileAttributes attributes = RequireRegularEntry(entry); if ((attributes & FileAttributes.Directory) != 0) + { pending.Push(entry); + } else + { yield return entry; + } } } } @@ -157,7 +166,9 @@ private static FileAttributes RequireRegularEntry(string path) { FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Owned filesystem entry '{path}' cannot be a link or reparse point."); + } return attributes; } @@ -167,8 +178,8 @@ string candidate ) { string prefix = Path.EndsInDirectorySeparator(root) ? root : root + Path.DirectorySeparatorChar; if (!string.Equals(candidate, root, StringComparison.Ordinal) - && !candidate.StartsWith(prefix, StringComparison.Ordinal)) - { + && !candidate.StartsWith(prefix, StringComparison.Ordinal) + ) { throw new IOException($"Path '{candidate}' escapes filesystem boundary '{root}'."); } } diff --git a/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs b/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs index 188c07d30..6e3d54a8c 100644 --- a/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs +++ b/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs @@ -61,9 +61,13 @@ public string Resolve(string path) private string ResolveCore(string path) { if (m_paths.TryGetValue(path, out string? cached)) + { return cached; + } if (!m_resolving.Add(path)) + { throw new IOException($"Filesystem alias '{path}' forms a resolution cycle."); + } try { string? parent = Path.GetDirectoryName(path); @@ -79,9 +83,14 @@ private string ResolveCore(string path) if ((attributes & FileAttributes.ReparsePoint) != 0) { FileSystemInfo entry = (attributes & FileAttributes.Directory) != 0 - ? new DirectoryInfo(candidate) : new FileInfo(candidate); - resolved = ResolveCore(Path.GetFullPath(entry.ResolveLinkTarget(returnFinalTarget: true)?.FullName - ?? throw new IOException($"Filesystem alias '{candidate}' has no resolvable target."))); + ? new DirectoryInfo(candidate) + : new FileInfo(candidate); + resolved = ResolveCore( + Path.GetFullPath( + entry.ResolveLinkTarget(returnFinalTarget: true)?.FullName + ?? throw new IOException($"Filesystem alias '{candidate}' has no resolvable target.") + ) + ); } m_paths.Add(path, resolved); return resolved; diff --git a/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs b/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs index 517daad74..3f4206bee 100644 --- a/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs +++ b/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs @@ -18,15 +18,19 @@ string destination } catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException or PlatformNotSupportedException) { - throw new PlatformNotSupportedException("The host does not provide atomic create-only file publication through POSIX link.", exception); + throw new PlatformNotSupportedException( + "The host does not provide atomic create-only file publication through POSIX link.", + exception + ); } if (result != 0) { int error = Marshal.GetLastPInvokeError(); throw new IOException( - $"Atomic create-only publication of '{source}' at '{destination}' failed (errno {error}). " + - "The destination was not replaced; the filesystem must support same-directory hard links.", - new Win32Exception(error)); + $"Atomic create-only publication of '{source}' at '{destination}' failed (errno {error}). " + + "The destination was not replaced; the filesystem must support same-directory hard links.", + new Win32Exception(error) + ); } try diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs index e2c98986d..ea4fe322e 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs @@ -28,7 +28,7 @@ private ProcessOwnedDirectory( CoordinatedFileLease lease ) { m_root = root; - directory = path; + this.directory = path; m_record = record; m_owner = owner; m_lease = lease; @@ -39,6 +39,44 @@ CoordinatedFileLease lease /// public string directory { get; } + /// + /// Releases only this directory after its other recorded process lifetimes have exited. + /// + /// + /// Removal failed; its explicit claim remains available for later retirement. + /// + public void Dispose() + { + CoordinatedFileLease? lease = m_lease; + if (lease is null) + { + return; + } + m_lease = null; + lease.Dispose(); + try + { + using CoordinatedFileLease retirement = CoordinatedFileLease + .AcquireAsync(Path.Combine(m_root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(5)) + .AsTask() + .GetAwaiter() + .GetResult(); + if (QueryOwners(m_record, m_owner) != ProcessOwnerState.Exited) + { + throw new IOException("A temporary directory still has an active or unverifiable subprocess owner."); + } + if (Directory.Exists(directory)) + { + Directory.Delete(PathBoundary.RequireUnlinkedPath(m_root, directory), recursive: true); + } + // The claim authorizes later leaf retirement under the owner's exclusive gate. + } + catch (TimeoutException failure) + { + throw new IOException("A temporary directory still has a registering subprocess reader.", failure); + } + } + /// /// Creates a directory protected by this process lifetime when the caller can retain only file metadata. /// Payload consumers in other processes must register their lifetimes before using it. @@ -72,25 +110,38 @@ public static async ValueTask CreateForProcessAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(root); if (!Path.IsPathFullyQualified(root) || identity is null || identity.Length != 32 - || identity.Any(static character => !Uri.IsHexDigit(character))) + || identity.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new ArgumentException("Process storage requires an absolute producer root and current operation identity."); + } root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); if (root == Path.GetPathRoot(root)) + { throw new ArgumentException("Process storage cannot manage a filesystem root.", nameof(root)); + } string path = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, identity)); string record = RecordPath(root, identity); - using CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false); + using CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false); if (File.Exists(record)) { Claim claim = ReadClaim(record); if (claim.directory != identity || QueryOwners(record, null) != ProcessOwnerState.Active) + { throw new InvalidDataException("Process storage cannot reuse an exited or unverifiable operation claim."); + } RegisterProcess(root, path); } else { if (Directory.Exists(path)) + { throw new InvalidDataException("An existing unregistered process directory cannot be adopted."); + } ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); WriteClaim(record, new Claim(identity, owner.processId, owner.startedUtcTicks)); Directory.CreateDirectory(path); @@ -125,23 +176,38 @@ public static async ValueTask CreateAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(root); if (!Path.IsPathFullyQualified(root) || Path.TrimEndingDirectorySeparator(root) == Path.GetPathRoot(root)) + { throw new ArgumentException("Temporary ownership requires an explicit child root.", nameof(root)); + } root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); PathBoundary.RequireUnlinkedPath(root, root); string relative = Guid.NewGuid().ToString("N"); string path = Path.Combine(root, relative); string record = RecordPath(root, relative); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(path) || File.Exists(record)) + { throw new IOException("A fresh temporary identity already exists and cannot be adopted."); + } ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); WriteClaim(record, new Claim(relative, owner.processId, owner.startedUtcTicks)); Directory.CreateDirectory(path); lease.Dispose(); - CoordinatedFileLease reading = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), shared: true, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease reading = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + shared: true, + cancellationToken: cancellationToken + ).ConfigureAwait(false); return new(root, path, record, owner, reading); } catch @@ -174,8 +240,16 @@ public static void RegisterCurrentProcess( string directory ) { PathBoundary.RequireUnlinkedPath(root, directory); - using CoordinatedFileLease reading = CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(30), shared: true) - .AsTask().GetAwaiter().GetResult(); + using CoordinatedFileLease reading = CoordinatedFileLease + .AcquireAsync( + Path.Combine(root, "owner.lock"), + directory + ".work.lock", + TimeSpan.FromSeconds(30), + shared: true + ) + .AsTask() + .GetAwaiter() + .GetResult(); RegisterProcess(root, directory); } @@ -201,52 +275,28 @@ public static IReadOnlyList ReadClaims( string root, CancellationToken cancellationToken = default ) { - var result = new List(); + List result = []; if (!Directory.Exists(root)) + { return result; + } foreach (string record in Directory.EnumerateFiles(root, "*.work.json")) { cancellationToken.ThrowIfCancellationRequested(); Claim claim = ReadClaim(record); string path = PathBoundary.Resolve(root, claim.directory); if (record != RecordPath(root, claim.directory)) + { throw new InvalidDataException("Temporary ownership has an inconsistent identity."); + } if (Directory.Exists(path)) - result.Add(new(path, path + ".work.lock", QueryOwners(record, null))); + { + result.Add(new ProcessOwnedDirectoryDescriptor(path, path + ".work.lock", QueryOwners(record, null))); + } } return result; } - /// - /// Releases only this directory after its other recorded process lifetimes have exited. - /// - /// - /// Removal failed; its explicit claim remains available for later retirement. - /// - public void Dispose() - { - CoordinatedFileLease? lease = m_lease; - if (lease is null) - return; - m_lease = null; - lease.Dispose(); - try - { - using CoordinatedFileLease retirement = CoordinatedFileLease.AcquireAsync(Path.Combine(m_root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(5)) - .AsTask().GetAwaiter().GetResult(); - if (QueryOwners(m_record, m_owner) != ProcessOwnerState.Exited) - throw new IOException("A temporary directory still has an active or unverifiable subprocess owner."); - if (Directory.Exists(directory)) - Directory.Delete(PathBoundary.RequireUnlinkedPath(m_root, directory), recursive: true); - // The claim authorizes later leaf retirement under the owner's exclusive gate. - - } - catch (TimeoutException failure) - { - throw new IOException("A temporary directory still has a registering subprocess reader.", failure); - } - } - /// /// Retires claims for absent payloads while the caller exclusively owns the persistent root gate. /// @@ -268,22 +318,32 @@ public static int RetireMetadataUnderOwnership( ) { int retired = 0; if (!Directory.Exists(root)) + { return retired; + } foreach (string record in Directory.EnumerateFiles(root, "*.work.json").Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); Claim claim = ReadClaim(PathBoundary.RequireUnlinkedPath(root, record)); if (record != RecordPath(root, claim.directory)) + { throw new InvalidDataException("Temporary ownership has an inconsistent identity."); + } string path = PathBoundary.Resolve(root, claim.directory); if (Directory.Exists(path)) + { continue; + } if (QueryOwners(record, null) == ProcessOwnerState.Unknown) + { throw new InvalidDataException("Temporary metadata has an unverifiable process owner."); + } string leaf = PathBoundary.RequireUnlinkedPath(root, path + ".work.lock"); using (FileLease.AcquireAsync(leaf, TimeSpan.Zero, cancellationToken).AsTask().GetAwaiter().GetResult()) { } foreach (string marker in Directory.EnumerateFiles(root, Path.GetFileName(record) + ".*.process")) + { File.Delete(PathBoundary.RequireUnlinkedPath(root, marker)); + } File.Delete(leaf); File.Delete(record); retired++; @@ -298,8 +358,10 @@ string directory string relative = RequireClaim(root, directory); ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); string record = RecordPath(root, relative); - WriteClaim(record + "." + owner.processId + ".process", - new Claim(relative, owner.processId, owner.startedUtcTicks)); + WriteClaim( + record + "." + owner.processId + ".process", + new Claim(relative, owner.processId, owner.startedUtcTicks) + ); } private static string RequireClaim( @@ -310,7 +372,9 @@ string directory string relative = Path.GetRelativePath(root, directory); Claim claim = ReadClaim(RecordPath(root, relative)); if (claim.directory != relative || !Directory.Exists(directory)) + { throw new InvalidDataException("The temporary directory has no matching current owner claim."); + } return relative; } @@ -326,17 +390,21 @@ private static Claim ReadClaim(string path) if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("directory", out JsonElement directory) || directory.ValueKind != JsonValueKind.String - || !root.TryGetProperty("processId", out JsonElement processId) - || processId.ValueKind != JsonValueKind.Number - || !processId.TryGetInt32(out int id) + || !root.TryGetProperty("processId", out JsonElement processID) + || processID.ValueKind != JsonValueKind.Number + || !processID.TryGetInt32(out int id) || !root.TryGetProperty("startedUtcTicks", out JsonElement startedUtcTicks) || startedUtcTicks.ValueKind != JsonValueKind.Number - || !startedUtcTicks.TryGetInt64(out long ticks)) + || !startedUtcTicks.TryGetInt64(out long ticks) + ) { throw new InvalidDataException("Temporary ownership is incomplete."); + } var claim = new Claim(directory.GetString()!, id, ticks); if (claim.directory is null || claim.directory.Length != 32 || claim.directory.Any(static character => !Uri.IsHexDigit(character))) + { throw new InvalidDataException("Temporary ownership requires its current explicit directory identity."); - _ = new ProcessOwnerStamp(claim.processId, claim.startedUtcTicks); + } + _ = new ProcessOwnerStamp(claim.processID, claim.startedUtcTicks); return claim; } @@ -349,7 +417,7 @@ Claim claim { writer.WriteStartObject(); writer.WriteString("directory", claim.directory); - writer.WriteNumber("processId", claim.processId); + writer.WriteNumber("processId", claim.processID); writer.WriteNumber("startedUtcTicks", claim.startedUtcTicks); writer.WriteEndObject(); } @@ -361,21 +429,32 @@ private static ProcessOwnerState QueryOwners( ProcessOwnerStamp? excluded ) { ProcessOwnerState combined = ProcessOwnerState.Exited; - foreach (string marker in new[] { record }.Concat(Directory.EnumerateFiles(Path.GetDirectoryName(record)!, Path.GetFileName(record) + ".*.process"))) - { + foreach (string marker in new[] { record }.Concat( + Directory.EnumerateFiles(Path.GetDirectoryName(record)!, Path.GetFileName(record) + ".*.process") + )) { try { Claim claim = ReadClaim(marker); - var stamp = new ProcessOwnerStamp(claim.processId, claim.startedUtcTicks); + var stamp = new ProcessOwnerStamp(claim.processID, claim.startedUtcTicks); if (stamp == excluded) + { continue; + } ProcessOwnerState state = stamp.Query(); if (state == ProcessOwnerState.Active) + { return state; + } if (state == ProcessOwnerState.Unknown) + { combined = state; + } } - catch (Exception exception) when (exception is IOException or InvalidDataException or JsonException or ArgumentException or UnauthorizedAccessException) + catch (Exception exception) when (exception is IOException + or InvalidDataException + or JsonException + or ArgumentException + or UnauthorizedAccessException) { combined = ProcessOwnerState.Unknown; } @@ -385,7 +464,7 @@ private static ProcessOwnerState QueryOwners( private sealed record Claim( string directory, - int processId, + int processID, long startedUtcTicks ); } diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs index 7255a0012..c68b701bd 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs @@ -27,8 +27,7 @@ long startedUtcTicks ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(processId); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(startedUtcTicks); - if (startedUtcTicks > DateTime.MaxValue.Ticks) - throw new ArgumentOutOfRangeException(nameof(startedUtcTicks)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(startedUtcTicks, DateTime.MaxValue.Ticks); this.processId = processId; this.startedUtcTicks = startedUtcTicks; } @@ -43,24 +42,6 @@ long startedUtcTicks /// public long startedUtcTicks { get; } - /// - /// Captures the current process lifetime and releases its temporary inspection handle. - /// - /// - /// The current process identifier and UTC start timestamp. - /// - /// - /// The operating system cannot provide the current process start timestamp. - /// - /// - /// The execution environment does not expose operating-system process lifetimes. - /// - public static ProcessOwnerStamp CaptureCurrent() - { - using Process process = Process.GetCurrentProcess(); - return new(process.Id, process.StartTime.ToUniversalTime().Ticks); - } - /// /// Checks the exact lifetime conservatively without holding an operating-system handle afterwards. /// @@ -71,17 +52,51 @@ public static ProcessOwnerStamp CaptureCurrent() public ProcessOwnerState Query() { if (processId <= 0 || startedUtcTicks <= 0) + { return ProcessOwnerState.Unknown; + } try { using Process process = Process.GetProcessById(processId); if (process.HasExited || process.StartTime.ToUniversalTime().Ticks != startedUtcTicks) + { return ProcessOwnerState.Exited; + } return ProcessOwnerState.Active; } - catch (ArgumentException) { return ProcessOwnerState.Exited; } - catch (InvalidOperationException) { return ProcessOwnerState.Unknown; } - catch (Win32Exception) { return ProcessOwnerState.Unknown; } - catch (NotSupportedException) { return ProcessOwnerState.Unknown; } + catch (ArgumentException) + { + return ProcessOwnerState.Exited; + } + catch (InvalidOperationException) + { + return ProcessOwnerState.Unknown; + } + catch (Win32Exception) + { + return ProcessOwnerState.Unknown; + } + catch (NotSupportedException) + { + return ProcessOwnerState.Unknown; + } + } + + /// + /// Captures the current process lifetime and releases its temporary inspection handle. + /// + /// + /// The current process identifier and UTC start timestamp. + /// + /// + /// The operating system cannot provide the current process start timestamp. + /// + /// + /// The execution environment does not expose operating-system process lifetimes. + /// + public static ProcessOwnerStamp CaptureCurrent() + { + using Process process = Process.GetCurrentProcess(); + return new(process.Id, process.StartTime.ToUniversalTime().Ticks); } } diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs index 65cb3475a..e18df3732 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs @@ -9,12 +9,10 @@ public enum ProcessOwnerState /// The matching process lifetime is still running. /// Active, - /// /// The process exited or its identifier now belongs to another lifetime. /// Exited, - /// /// Ownership cannot be verified; dependent files must remain protected. /// diff --git a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs index db732f70b..594824218 100644 --- a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs @@ -27,19 +27,19 @@ ReadOnlySpan data m_data = data.ToArray(); } - /// + /// public string documentName { get; } - /// + /// public bool canWrite => false; - /// + /// public bool exists => true; - /// + /// public byte[] Read() => (byte[])m_data.Clone(); - /// - public void Write(ReadOnlySpan data) => throw new NotSupportedException( - $"Document '{documentName}' is read-only."); + /// + public void Write(ReadOnlySpan data) + => throw new NotSupportedException($"Document '{documentName}' is read-only."); } diff --git a/src/foundation/core/Inno.Core.Identity/Identity.cs b/src/foundation/core/Inno.Core.Identity/Identity.cs index 453ec0f26..46e7c5e9e 100644 --- a/src/foundation/core/Inno.Core.Identity/Identity.cs +++ b/src/foundation/core/Inno.Core.Identity/Identity.cs @@ -10,7 +10,7 @@ public struct Identity /// /// Gets the stable identifier preserved by serialization and runtime reconstruction. /// - public Guid persistentId { get; private set; } + public Guid persistentID { get; private set; } /// /// Gets the identifier assigned by the currently bound runtime registry. @@ -18,14 +18,16 @@ public struct Identity /// /// The value is while this identity is not bound to a live registry. /// - public int? runtimeId + public int? runtimeID { get { - if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + if (m_registryRef is null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + { return null; + } - return registry.TryGetRuntimeId(this, out int runtimeId) ? runtimeId : null; + return registry.TryGetRuntimeID(this, out int runtimeID) ? runtimeID : null; } } @@ -39,53 +41,57 @@ public RuntimeIdentity? runtimeIdentity { get { - if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + if (m_registryRef is null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + { return null; - return registry.TryGetRuntimeId(this, out int runtimeId) - ? new RuntimeIdentity(registry.domainId, runtimeId) - : null; + } + return registry.TryGetRuntimeID(this, out int runtimeID) + ? new RuntimeIdentity(registry.domainID, runtimeID) + : null; } } - private int m_runtimeId; + private int m_runtimeID; private WeakReference? m_registryRef; /// /// Creates an unbound identity with the supplied persistent identifier. /// - /// + /// /// The stable identifier to preserve across serialization boundaries. /// - public Identity(Guid persistentId) + public Identity(Guid persistentID) { - this.persistentId = persistentId; - m_runtimeId = 0; + this.persistentID = persistentID; + m_runtimeID = 0; m_registryRef = null; } internal void Bind( IdentityRegistry registry, - int runtimeId + int runtimeID ) { - if (persistentId == Guid.Empty) - persistentId = Guid.NewGuid(); + if (persistentID == Guid.Empty) + { + persistentID = Guid.NewGuid(); + } - m_runtimeId = runtimeId; + m_runtimeID = runtimeID; m_registryRef = new WeakReference(registry); } internal void Unbind(IdentityRegistry registry) { - if (m_registryRef != null && - m_registryRef.TryGetTarget(out IdentityRegistry? current) && - ReferenceEquals(current, registry)) - { - m_runtimeId = 0; + if (m_registryRef is not null + && m_registryRef.TryGetTarget(out IdentityRegistry? current) + && ReferenceEquals(current, registry) + ) { + m_runtimeID = 0; m_registryRef = null; } } - internal int rawRuntimeId => m_runtimeId; + internal int rawRuntimeID => m_runtimeID; /// /// Resolves this transient snapshot through its original weak identity registry. @@ -96,8 +102,9 @@ internal void Unbind(IdentityRegistry registry) /// /// The current object, or null if the registry retired, the slot changed generation, or the type differs. /// - public TObject? Resolve() where TObject : IdentityObject - => m_registryRef is not null && m_registryRef.TryGetTarget(out IdentityRegistry? registry) - ? registry.Get(m_runtimeId) - : null; + public TObject? Resolve() + where TObject : IdentityObject + => m_registryRef is not null && m_registryRef.TryGetTarget(out IdentityRegistry? registry) + ? registry.Get(m_runtimeID) + : null; } diff --git a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs index 392b0f47a..5a9bf1052 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs @@ -1,7 +1,7 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Identity; @@ -10,8 +10,8 @@ namespace Inno.Core.Identity; /// public sealed class IdentityAllocator { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("allocator"); - private static int S_NEXT_DOMAIN_ID; + private static readonly ExecutionSlot CURRENT_SCOPE = new("allocator"); + private static int s_nextDomainID; private readonly IdentityRegistry m_registry; @@ -23,17 +23,19 @@ public sealed class IdentityAllocator /// public IdentityAllocator() { - int nextDomainId = Interlocked.Increment(ref S_NEXT_DOMAIN_ID); - if (nextDomainId <= 0) + int nextDomainID = Interlocked.Increment(ref s_nextDomainID); + if (nextDomainID <= 0) + { throw new InvalidOperationException("The process exhausted available identity domains."); - domainId = new IdentityDomainId(nextDomainId); - m_registry = new IdentityRegistry(domainId); + } + this.domainID = new IdentityDomainID(nextDomainID); + m_registry = new IdentityRegistry(domainID); } /// /// Gets whether the current asynchronous execution context is bound to an allocator. /// - public static bool hasCurrent => S_CURRENT_SCOPE.TryGet(out _); + public static bool hasCurrent => CURRENT_SCOPE.TryGet(out _); /// /// Gets the allocator bound to the current asynchronous execution context. @@ -41,7 +43,7 @@ public IdentityAllocator() /// /// Thrown when the caller is outside a runtime session execution scope. /// - public static IdentityAllocator current => S_CURRENT_SCOPE.current; + public static IdentityAllocator current => CURRENT_SCOPE.current; /// /// Gets the number of currently registered identity entries. @@ -55,7 +57,7 @@ public IdentityAllocator() /// /// Gets the process-unique domain that qualifies every runtime identity allocated here. /// - public IdentityDomainId domainId { get; } + public IdentityDomainID domainID { get; } /// /// Occurs after an object has been permanently removed from this allocator. @@ -64,7 +66,7 @@ public IdentityAllocator() /// Every observer is invoked. Multiple observer failures are reported as one /// after notification completes. /// - public event Action? ObjectUnregistered; + public event Action? objectUnregistered; /// /// Binds this allocator to the current asynchronous execution context until the returned scope is disposed. @@ -75,10 +77,7 @@ public IdentityAllocator() /// /// Thrown when scopes are disposed out of order. /// - public IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } + public IDisposable EnterScope() => CURRENT_SCOPE.Enter(this); /// /// Registers an object and assigns its session-local runtime identity. @@ -86,7 +85,7 @@ public IDisposable EnterScope() /// /// The identity object owned by this runtime session. /// - /// + /// /// An optional persistent identity override. When omitted, the object's existing persistent identity is retained. /// An empty resolved identity is replaced with a newly generated identity. /// @@ -101,8 +100,8 @@ public IDisposable EnterScope() /// public bool Register( IdentityObject obj, - Guid? persistentId = null - ) => m_registry.Register(obj, persistentId); + Guid? persistentID = null + ) => m_registry.Register(obj, persistentID); /// /// Assigns a persistent identity to a detached object without allocating a runtime identity. @@ -110,28 +109,32 @@ public bool Register( /// /// The detached identity object to initialize. /// - /// + /// /// The non-empty persistent identity to assign. /// /// /// Thrown when is null. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// /// /// Thrown when the object already has a live runtime identity. /// public void InitializePersistentIdentity( IdentityObject obj, - Guid persistentId + Guid persistentID ) { ArgumentNullException.ThrowIfNull(obj); - if (persistentId == Guid.Empty) - throw new ArgumentException("A detached persistent identity cannot be empty.", nameof(persistentId)); - if (obj.identity.runtimeId is not null) + if (persistentID == Guid.Empty) + { + throw new ArgumentException("A detached persistent identity cannot be empty.", nameof(persistentID)); + } + if (obj.identity.runtimeID is not null) + { throw new InvalidOperationException("A registered identity object cannot be reinitialized."); - obj.SetIdentity(new Identity(persistentId)); + } + obj.SetIdentity(new Identity(persistentID)); } /// @@ -153,10 +156,14 @@ public bool Unregister(IdentityObject obj) { ArgumentNullException.ThrowIfNull(obj); if (!m_registry.Unregister(obj)) + { return false; - Action? handlers = ObjectUnregistered; + } + Action? handlers = objectUnregistered; if (handlers is null) + { return true; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -171,7 +178,9 @@ public bool Unregister(IdentityObject obj) } } if (failures is not null) + { throw new AggregateException("One or more identity unregistration observers failed.", failures); + } return true; } @@ -181,15 +190,15 @@ public bool Unregister(IdentityObject obj) /// /// The required identity object contract. /// - /// + /// /// The packed runtime identity allocated by this instance. /// /// /// The live compatible object, or when no matching object exists. /// - public TIdentity? Get(int runtimeId) + public TIdentity? Get(int runtimeID) where TIdentity : IdentityObject - => m_registry.Get(runtimeId); + => m_registry.Get(runtimeID); /// /// Resolves a domain-qualified runtime identity without allowing cross-session aliasing. @@ -205,9 +214,9 @@ public bool Unregister(IdentityObject obj) /// public TIdentity? Get(RuntimeIdentity identity) where TIdentity : IdentityObject - => identity.domainId == domainId - ? m_registry.Get(identity.runtimeId) - : null; + => identity.domainID == domainID + ? m_registry.Get(identity.runtimeID) + : null; /// /// Resolves a registered object by its persistent identity. @@ -215,14 +224,13 @@ public bool Unregister(IdentityObject obj) /// /// The required identity object contract. /// - /// + /// /// The non-empty persistent identity to resolve. /// /// /// The live compatible object, or when no matching object exists. /// - public TIdentity? Get(Guid persistentId) + public TIdentity? Get(Guid persistentID) where TIdentity : IdentityObject - => m_registry.Get(persistentId); - + => m_registry.Get(persistentID); } diff --git a/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs b/src/foundation/core/Inno.Core.Identity/IdentityDomainID.cs similarity index 87% rename from src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs rename to src/foundation/core/Inno.Core.Identity/IdentityDomainID.cs index 535a64c74..a9d53d054 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityDomainID.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; namespace Inno.Core.Identity; @@ -8,9 +9,9 @@ namespace Inno.Core.Identity; /// /// Domain identifiers are runtime-only values. They must never be serialized or used as persistent object identity. /// -public readonly struct IdentityDomainId : IEquatable +public readonly struct IdentityDomainID : IEquatable { - internal IdentityDomainId(int value) + internal IdentityDomainID(int value) { this.value = value; } @@ -34,7 +35,7 @@ internal IdentityDomainId(int value) /// /// when both values identify the same domain; otherwise, . /// - public bool Equals(IdentityDomainId other) => value == other.value; + public bool Equals(IdentityDomainID other) => value == other.value; /// /// Determines whether an object represents the same runtime domain. @@ -45,7 +46,7 @@ internal IdentityDomainId(int value) /// /// when the object is an equal domain identifier; otherwise, . /// - public override bool Equals(object? obj) => obj is IdentityDomainId other && Equals(other); + public override bool Equals(object? obj) => obj is IdentityDomainID other && Equals(other); /// /// Computes a hash code for this runtime domain identifier. @@ -61,7 +62,7 @@ internal IdentityDomainId(int value) /// /// The numeric domain value, or <invalid> when the value is not allocated. /// - public override string ToString() => isValid ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : ""; + public override string ToString() => isValid ? value.ToString(CultureInfo.InvariantCulture) : ""; /// /// Determines whether two values identify the same runtime domain. @@ -76,8 +77,8 @@ internal IdentityDomainId(int value) /// when the values are equal; otherwise, . /// public static bool operator ==( - IdentityDomainId left, - IdentityDomainId right + IdentityDomainID left, + IdentityDomainID right ) => left.Equals(right); /// @@ -93,7 +94,7 @@ IdentityDomainId right /// when the values are different; otherwise, . /// public static bool operator !=( - IdentityDomainId left, - IdentityDomainId right + IdentityDomainID left, + IdentityDomainID right ) => !left.Equals(right); } diff --git a/src/foundation/core/Inno.Core.Identity/IdentityObject.cs b/src/foundation/core/Inno.Core.Identity/IdentityObject.cs index 66376bba1..da046a2a2 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityObject.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityObject.cs @@ -1,3 +1,5 @@ +using System; + namespace Inno.Core.Identity; /// @@ -5,7 +7,7 @@ namespace Inno.Core.Identity; /// public abstract class IdentityObject { - private Identity m_identity = new(System.Guid.NewGuid()); + private Identity m_identity = new(Guid.NewGuid()); /// /// Gets this object's current persistent and optional session-local identity snapshot. diff --git a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs index 21619b08b..1f99b28c4 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs @@ -16,20 +16,18 @@ internal sealed class IdentityRegistry private readonly ConditionalWeakTable m_slotByObject = new(); - private readonly List m_denseToSlot = new(); - private readonly List m_sparseToDense = new(); - private readonly List m_generations = new(); + private readonly List m_denseToSlot = []; + private readonly List m_sparseToDense = []; + private readonly List m_generations = []; private readonly Stack m_freeSlots = new(); - private readonly Dictionary m_slotByPersistent = new(); + private readonly Dictionary m_slotByPersistent = []; - internal IdentityRegistry(IdentityDomainId domainId) + internal IdentityRegistry(IdentityDomainID domainID) { - this.domainId = domainId; + this.domainID = domainID; } - internal IdentityDomainId domainId { get; } - /// /// Gets the number of values in the current immutable view. /// @@ -55,7 +53,7 @@ public int count /// /// Identity object to register. /// - /// + /// /// Preferred persistent id. When null, uses object's current identity persistent id. /// /// @@ -63,7 +61,7 @@ public int count /// public bool Register( IdentityObject obj, - Guid? persistentId = null + Guid? persistentID = null ) { ArgumentNullException.ThrowIfNull(obj); @@ -71,10 +69,10 @@ public bool Register( try { Identity identity = obj.identity; - Guid resolvedPersistentId = persistentId.GetValueOrDefault(identity.persistentId); - if (resolvedPersistentId == Guid.Empty) + Guid resolvedPersistentID = persistentID.GetValueOrDefault(identity.persistentID); + if (resolvedPersistentID == Guid.Empty) { - resolvedPersistentId = Guid.NewGuid(); + resolvedPersistentID = Guid.NewGuid(); } if (TryGetSlotByObjectNoLock(obj, out int objectSlot)) @@ -87,13 +85,14 @@ public bool Register( RemoveSlotByObjectNoLock(obj, objectSlot); } - if (TryGetSlotByPersistentNoLock(resolvedPersistentId, out int existingSlot)) + if (TryGetSlotByPersistentNoLock(resolvedPersistentID, out int existingSlot)) { if (TryGetLiveObjectBySlotNoLock(existingSlot, out IdentityObject? existing, out _) - && !ReferenceEquals(existing, obj)) - { + && !ReferenceEquals(existing, obj) + ) { throw new InvalidOperationException( - $"Persistent id '{resolvedPersistentId}' is already registered."); + $"Persistent id '{resolvedPersistentID}' is already registered." + ); } RemoveSlotBySlotNoLock(existingSlot); @@ -101,19 +100,19 @@ public bool Register( int slot = AllocateSlot(); int generation = m_generations[slot]; - int runtimeId = RuntimeIdCodec.Pack(slot, generation); + int runtimeID = RuntimeIDCodec.Pack(slot, generation); int denseIndex = m_active.Count; - m_active.Add(new RegistryEntry(obj, resolvedPersistentId)); + m_active.Add(new RegistryEntry(obj, resolvedPersistentID)); m_slotByObject.Remove(obj); m_slotByObject.Add(obj, new RegistrySlot(slot)); m_denseToSlot.Add(slot); m_sparseToDense[slot] = denseIndex; - m_slotByPersistent[resolvedPersistentId] = slot; + m_slotByPersistent[resolvedPersistentID] = slot; - identity = new Identity(resolvedPersistentId); - identity.Bind(this, runtimeId); + identity = new Identity(resolvedPersistentID); + identity.Bind(this, runtimeID); obj.SetIdentity(identity); return true; } @@ -159,7 +158,9 @@ public bool Unregister(IdentityObject obj) } if (!ReferenceEquals(activeObject, obj)) + { return false; + } RemoveSlotBySlotNoLock(objectSlot); identity.Unbind(this); @@ -178,13 +179,13 @@ public bool Unregister(IdentityObject obj) /// /// The caller-selected tidentity type whose declared constraints are enforced by this operation. /// - /// + /// /// The runtime id consumed by get; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The validated tidentity? that represents the completed operation. /// - public TIdentity? Get(int runtimeId) + public TIdentity? Get(int runtimeID) where TIdentity : IdentityObject { int slot = -1; @@ -193,7 +194,7 @@ public bool Unregister(IdentityObject obj) m_lock.EnterReadLock(); try { - if (!TryResolveDenseIndexNoLock(runtimeId, out int denseIndex)) + if (!TryResolveDenseIndexNoLock(runtimeID, out int denseIndex)) { return null; } @@ -240,16 +241,16 @@ public bool Unregister(IdentityObject obj) /// /// The caller-selected tidentity type whose declared constraints are enforced by this operation. /// - /// + /// /// The stable persistent identity used for lookup. /// /// /// The validated tidentity? that represents the completed operation. /// - public TIdentity? Get(Guid persistentId) + public TIdentity? Get(Guid persistentID) where TIdentity : IdentityObject { - if (persistentId == Guid.Empty) + if (persistentID == Guid.Empty) { return null; } @@ -260,7 +261,7 @@ public bool Unregister(IdentityObject obj) m_lock.EnterReadLock(); try { - if (!m_slotByPersistent.TryGetValue(persistentId, out slot)) + if (!m_slotByPersistent.TryGetValue(persistentID, out slot)) { return null; } @@ -305,18 +306,22 @@ public bool Unregister(IdentityObject obj) return result; } - internal bool TryGetRuntimeId( + internal IdentityDomainID domainID { get; } + + internal bool TryGetRuntimeID( in Identity identity, - out int runtimeId + out int runtimeID ) { - runtimeId = 0; - if (identity.persistentId == Guid.Empty || identity.rawRuntimeId == 0) + runtimeID = 0; + if (identity.persistentID == Guid.Empty || identity.rawRuntimeID == 0) + { return false; + } m_lock.EnterReadLock(); try { - if (!TryGetDenseIndexByRuntimeIdNoLock(identity.rawRuntimeId, out int denseIndex)) + if (!TryGetDenseIndexByRuntimeIDNoLock(identity.rawRuntimeID, out int denseIndex)) { return false; } @@ -326,12 +331,12 @@ out int runtimeId return false; } - if (entry!.persistentId != identity.persistentId) + if (entry!.persistentID != identity.persistentID) { return false; } - runtimeId = identity.rawRuntimeId; + runtimeID = identity.rawRuntimeID; return true; } finally @@ -343,7 +348,9 @@ out int runtimeId private int AllocateSlot() { if (m_freeSlots.Count > 0) + { return m_freeSlots.Pop(); + } int slot = m_generations.Count; m_generations.Add(1); @@ -353,11 +360,11 @@ private int AllocateSlot() [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryResolveDenseIndexNoLock( - int runtimeId, + int runtimeID, out int denseIndex ) { - int slot = RuntimeIdCodec.UnpackSlot(runtimeId); - int generation = RuntimeIdCodec.UnpackGeneration(runtimeId); + int slot = RuntimeIDCodec.UnpackSlot(runtimeID); + int generation = RuntimeIDCodec.UnpackGeneration(runtimeID); if ((uint)slot >= (uint)m_generations.Count) { denseIndex = -1; @@ -388,12 +395,10 @@ out int denseIndex return denseIndex >= 0 && denseIndex < m_active.Count; } - private bool TryGetDenseIndexByRuntimeIdNoLock( - int runtimeId, + private bool TryGetDenseIndexByRuntimeIDNoLock( + int runtimeID, out int denseIndex - ) { - return TryResolveDenseIndexNoLock(runtimeId, out denseIndex) && TryGetEntryByDenseNoLock(denseIndex, out _); - } + ) => TryResolveDenseIndexNoLock(runtimeID, out denseIndex) && TryGetEntryByDenseNoLock(denseIndex, out _); private bool TryGetEntryByDenseNoLock( int denseIndex, @@ -472,10 +477,10 @@ out int slot } private bool TryGetSlotByPersistentNoLock( - Guid persistentId, + Guid persistentID, out int slot ) { - if (!m_slotByPersistent.TryGetValue(persistentId, out slot)) + if (!m_slotByPersistent.TryGetValue(persistentID, out slot)) { return false; } @@ -492,38 +497,40 @@ out int slot private bool TryGetLiveObject( RegistryEntry entry, out IdentityObject? obj - ) { - return entry.TryGetObject(out obj); - } + ) => entry.TryGetObject(out obj); private void CleanupStaleSlotBySlotNoLock(int slot) { if (!TryGetDenseIndexBySlotNoLock(slot, out int denseIndex)) { - m_slotByPersistent.Remove(GetPersistentIdBySlotNoLock(slot)); + m_slotByPersistent.Remove(GetPersistentIDBySlotNoLock(slot)); m_sparseToDense[slot] = -1; return; } - if (TryGetEntryByDenseNoLock(denseIndex, out RegistryEntry? entry) && - entry!.TryGetObject(out _)) - { + if (TryGetEntryByDenseNoLock(denseIndex, out RegistryEntry? entry) + && entry!.TryGetObject(out _) + ) { return; } RemoveSlotBySlotNoLock(slot, denseIndex); } - private Guid GetPersistentIdBySlotNoLock(int slot) + private Guid GetPersistentIDBySlotNoLock(int slot) { if (slot < 0 || slot >= m_sparseToDense.Count) + { return Guid.Empty; + } int denseIndex = m_sparseToDense[slot]; if (denseIndex < 0 || denseIndex >= m_active.Count) + { return Guid.Empty; + } - return m_active[denseIndex].persistentId; + return m_active[denseIndex].persistentID; } private void RemoveSlotByObjectNoLock( @@ -561,10 +568,10 @@ int denseIndex m_slotByObject.Remove(removedObj!); } - if (m_slotByPersistent.TryGetValue(removed.persistentId, out int mappedSlot) && - mappedSlot == slot) - { - m_slotByPersistent.Remove(removed.persistentId); + if (m_slotByPersistent.TryGetValue(removed.persistentID, out int mappedSlot) + && mappedSlot == slot + ) { + m_slotByPersistent.Remove(removed.persistentID); } m_active.RemoveAt(lastIndex); @@ -572,7 +579,7 @@ int denseIndex m_sparseToDense[slot] = -1; int nextGeneration = m_generations[slot] + 1; - if (nextGeneration > RuntimeIdCodec.GENERATION_MASK) + if (nextGeneration > RuntimeIDCodec.C_GENERATION_MASK) { nextGeneration = 1; } @@ -602,11 +609,12 @@ private sealed class RegistryEntry /// /// The m object ref value used as part of this type's public representation. /// - public WeakReference m_objectRef; + public WeakReference objectRef; + /// /// The persistent id value used as part of this type's public representation. /// - public Guid persistentId; + public Guid persistentID; /// /// Creates a validated registry entry instance. @@ -614,15 +622,15 @@ private sealed class RegistryEntry /// /// The object compared with this value. /// - /// + /// /// The stable persistent identity used for lookup. /// public RegistryEntry( IdentityObject obj, - Guid persistentId + Guid persistentID ) { - m_objectRef = new WeakReference(obj); - this.persistentId = persistentId; + this.objectRef = new WeakReference(obj); + this.persistentID = persistentID; } /// @@ -634,7 +642,7 @@ Guid persistentId /// /// when the requested condition is satisfied; otherwise, . /// - public bool TryGetObject(out IdentityObject? obj) => m_objectRef.TryGetTarget(out obj); + public bool TryGetObject(out IdentityObject? obj) => objectRef.TryGetTarget(out obj); } private sealed class RegistrySlot @@ -650,6 +658,9 @@ private sealed class RegistrySlot /// /// The dense storage slot encoded in this runtime handle. /// - public RegistrySlot(int slot) => this.slot = slot; + public RegistrySlot(int slot) + { + this.slot = slot; + } } } diff --git a/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs index 8a88b3204..5df7fc852 100644 --- a/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs @@ -1,12 +1,9 @@ using Inno.Core.Identity; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Core", - "Inno.Core.Identity", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Core", "Inno.Core.Identity", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(IdentityObject), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Identity), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(IdentityDomainId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(IdentityDomainID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RuntimeIdentity), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs b/src/foundation/core/Inno.Core.Identity/RuntimeIDCodec.cs similarity index 74% rename from src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs rename to src/foundation/core/Inno.Core.Identity/RuntimeIDCodec.cs index 0a5187d43..0b0dd90f9 100644 --- a/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs +++ b/src/foundation/core/Inno.Core.Identity/RuntimeIDCodec.cs @@ -5,25 +5,27 @@ namespace Inno.Core.Identity; /// /// Packs and unpacks runtime ids into a single using slot + generation. /// -internal static class RuntimeIdCodec +internal static class RuntimeIDCodec { /// /// The slot bits value used as part of this type's public representation. /// - public const int SLOT_BITS = 20; + public const int C_SLOT_BITS = 20; + /// /// The generation bits value used as part of this type's public representation. /// - public const int GENERATION_BITS = 12; + public const int C_GENERATION_BITS = 12; /// /// The slot mask value used as part of this type's public representation. /// - public const int SLOT_MASK = (1 << SLOT_BITS) - 1; + public const int C_SLOT_MASK = (1 << C_SLOT_BITS) - 1; + /// /// The generation mask value used as part of this type's public representation. /// - public const int GENERATION_MASK = (1 << GENERATION_BITS) - 1; + public const int C_GENERATION_MASK = (1 << C_GENERATION_BITS) - 1; /// /// Packs a storage slot and generation into one opaque runtime identifier. @@ -41,33 +43,37 @@ public static int Pack( int slot, int generation ) { - if ((uint)slot > SLOT_MASK) + if ((uint)slot > C_SLOT_MASK) + { throw new ArgumentOutOfRangeException(nameof(slot)); - if ((uint)generation > GENERATION_MASK) + } + if ((uint)generation > C_GENERATION_MASK) + { throw new ArgumentOutOfRangeException(nameof(generation)); + } - return (generation << SLOT_BITS) | (slot & SLOT_MASK); + return (generation << C_SLOT_BITS) | (slot & C_SLOT_MASK); } /// /// Extracts the storage slot encoded in an opaque runtime identifier. /// - /// + /// /// The runtime id consumed by unpack slot; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The scalar result calculated from the supplied inputs. /// - public static int UnpackSlot(int runtimeId) => runtimeId & SLOT_MASK; + public static int UnpackSlot(int runtimeID) => runtimeID & C_SLOT_MASK; /// /// Extracts the owner generation encoded in an opaque runtime identifier. /// - /// + /// /// The runtime id consumed by unpack generation; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The scalar result calculated from the supplied inputs. /// - public static int UnpackGeneration(int runtimeId) => (runtimeId >> SLOT_BITS) & GENERATION_MASK; + public static int UnpackGeneration(int runtimeID) => (runtimeID >> C_SLOT_BITS) & C_GENERATION_MASK; } diff --git a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs index 249408555..eecdfe173 100644 --- a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs +++ b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs @@ -7,43 +7,47 @@ namespace Inno.Core.Identity; /// /// /// This value is suitable for transient interaction payloads only and must never be persisted. - /// Equality compares the stored domain and runtime identifier; it does not verify that an object is still live. +/// Equality compares the stored domain and runtime identifier; it does not verify that an object is still live. /// public readonly struct RuntimeIdentity : IEquatable { /// /// Creates a runtime identity from its domain and generation-safe object identifier. /// - /// + /// /// The identity domain that owns the runtime identifier. /// - /// + /// /// The generation-safe runtime identifier allocated inside the domain. /// /// /// Thrown when either value is invalid. /// public RuntimeIdentity( - IdentityDomainId domainId, - int runtimeId + IdentityDomainID domainID, + int runtimeID ) { - if (!domainId.isValid) - throw new ArgumentException("A runtime identity requires a valid domain.", nameof(domainId)); - if (runtimeId <= 0) - throw new ArgumentException("A runtime identity requires a positive runtime identifier.", nameof(runtimeId)); - this.domainId = domainId; - this.runtimeId = runtimeId; + if (!domainID.isValid) + { + throw new ArgumentException("A runtime identity requires a valid domain.", nameof(domainID)); + } + if (runtimeID <= 0) + { + throw new ArgumentException("A runtime identity requires a positive runtime identifier.", nameof(runtimeID)); + } + this.domainID = domainID; + this.runtimeID = runtimeID; } /// /// Gets the identity domain that owns this runtime identifier. /// - public IdentityDomainId domainId { get; } + public IdentityDomainID domainID { get; } /// - /// Gets the generation-safe identifier interpreted inside . + /// Gets the generation-safe identifier interpreted inside . /// - public int runtimeId { get; } + public int runtimeID { get; } /// /// Determines whether this value and another value address the same live identity slot. @@ -54,7 +58,7 @@ int runtimeId /// /// when both the domain and runtime identifier are equal; otherwise, . /// - public bool Equals(RuntimeIdentity other) => domainId == other.domainId && runtimeId == other.runtimeId; + public bool Equals(RuntimeIdentity other) => domainID == other.domainID && runtimeID == other.runtimeID; /// /// Determines whether an object addresses the same live identity slot. @@ -73,7 +77,7 @@ int runtimeId /// /// A hash code consistent with runtime identity equality. /// - public override int GetHashCode() => HashCode.Combine(domainId, runtimeId); + public override int GetHashCode() => HashCode.Combine(domainID, runtimeID); /// /// Formats this transient identity for diagnostics. @@ -81,7 +85,7 @@ int runtimeId /// /// A domain-qualified runtime identifier. /// - public override string ToString() => $"{domainId}:{runtimeId}"; + public override string ToString() => $"{domainID}:{runtimeID}"; /// /// Determines whether two runtime identities are equal. diff --git a/src/foundation/core/Inno.Core.Input/KeyCode.cs b/src/foundation/core/Inno.Core.Input/KeyCode.cs index e39642f95..419512da1 100644 --- a/src/foundation/core/Inno.Core.Input/KeyCode.cs +++ b/src/foundation/core/Inno.Core.Input/KeyCode.cs @@ -9,7 +9,6 @@ public enum KeyCode /// No recognized physical key. /// Unknown = 0, - /// /// The A letter key. /// @@ -114,7 +113,6 @@ public enum KeyCode /// The Z letter key. /// Z = 90, - /// /// The 0 key on the primary keyboard row. /// @@ -155,7 +153,6 @@ public enum KeyCode /// The 9 key on the primary keyboard row. /// D9 = 57, - /// /// The escape key. /// @@ -176,7 +173,6 @@ public enum KeyCode /// The backspace key. /// Backspace = 8, - /// /// The left arrow key. /// @@ -193,11 +189,10 @@ public enum KeyCode /// The down arrow key. /// DownArrow = 40, - /// /// The left super key. /// - LeftSuper = 91, + LeftSuper = 91, /// /// The right super key. /// @@ -226,7 +221,6 @@ public enum KeyCode /// The right alt key. /// RightAlt = 165, - /// /// The caps lock key. /// @@ -255,7 +249,6 @@ public enum KeyCode /// The page down key. /// PageDown = 34, - /// /// The 0 key on the numeric keypad. /// @@ -296,7 +289,6 @@ public enum KeyCode /// The 9 key on the numeric keypad. /// NumPad9 = 105, - /// /// The num lock key. /// @@ -305,7 +297,6 @@ public enum KeyCode /// The scroll lock key. /// ScrollLock = 145, - /// /// The F1 function key. /// @@ -354,49 +345,59 @@ public enum KeyCode /// The F12 function key. /// F12 = 123, - /// /// The plus key. /// - Plus = 187, // '+' key + // '+' key + Plus = 187, /// /// The comma key. /// - Comma = 188, // ',' key + // ',' key + Comma = 188, /// /// The minus key. /// - Minus = 189, // '-' key + // '-' key + Minus = 189, /// /// The period key. /// - Period = 190, // '.' key + // '.' key + Period = 190, /// /// The slash key. /// - Slash = 191, // '/' key + // '/' key + Slash = 191, /// /// The tilde key. /// - Tilde = 192, // '`' key + // '`' key + Tilde = 192, /// /// The backslash key. /// - Backslash = 220, // '\' key + // '\' key + Backslash = 220, /// /// The semicolon key. /// - Semicolon = 186, // ';' key + // ';' key + Semicolon = 186, /// /// The quote key. /// - Quote = 222, // ''' key + // ''' key + Quote = 222, /// /// The left bracket key. /// - LeftBracket = 219, // '[' key + // '[' key + LeftBracket = 219, /// /// The right bracket key. /// - RightBracket = 221 // ']' key -} \ No newline at end of file + // ']' key + RightBracket = 221 +} diff --git a/src/foundation/core/Inno.Core.Input/KeyModifier.cs b/src/foundation/core/Inno.Core.Input/KeyModifier.cs index 8a958fda8..e81c06611 100644 --- a/src/foundation/core/Inno.Core.Input/KeyModifier.cs +++ b/src/foundation/core/Inno.Core.Input/KeyModifier.cs @@ -27,5 +27,5 @@ public enum KeyModifier /// /// The super key. /// - Super = 8, -} \ No newline at end of file + Super = 8 +} diff --git a/src/foundation/core/Inno.Core.Input/MouseButton.cs b/src/foundation/core/Inno.Core.Input/MouseButton.cs index 50a4006fb..eb984c912 100644 --- a/src/foundation/core/Inno.Core.Input/MouseButton.cs +++ b/src/foundation/core/Inno.Core.Input/MouseButton.cs @@ -25,4 +25,4 @@ public enum MouseButton /// The xbutton2 key. /// XButton2 = 4 -} \ No newline at end of file +} diff --git a/src/foundation/core/Inno.Core.Input/MouseCursor.cs b/src/foundation/core/Inno.Core.Input/MouseCursor.cs index 1d6d70b47..669b87735 100644 --- a/src/foundation/core/Inno.Core.Input/MouseCursor.cs +++ b/src/foundation/core/Inno.Core.Input/MouseCursor.cs @@ -9,7 +9,6 @@ public enum MouseCursor /// No concrete cursor shape; the consuming host defines visibility behavior. /// None = -1, - /// /// The standard arrow pointer. /// @@ -45,5 +44,5 @@ public enum MouseCursor /// /// A cursor indicating that an operation is unavailable. /// - NotAllowed = 8, + NotAllowed = 8 } diff --git a/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs index 06abb83a6..6cf4633cb 100644 --- a/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Core.Input; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Input", - "Inno.Core.Input", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Input", "Inno.Core.Input", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(KeyCode), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(KeyModifier), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs b/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs index fa776a5f1..a9db4e931 100644 --- a/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs +++ b/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs @@ -79,10 +79,10 @@ private int CountNoLock() private void GrowNoLock() { - var oldBuffer = m_buffer; + T[] oldBuffer = m_buffer; var newBuffer = new T[oldBuffer.Length * 2]; - var count = CountNoLock(); - for (var i = 0; i < count; i++) + int count = CountNoLock(); + for (int i = 0; i < count; i++) { newBuffer[i] = oldBuffer[(m_head + i) % oldBuffer.Length]; } diff --git a/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs b/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs index 55af51831..0d1ebc291 100644 --- a/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs +++ b/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs @@ -5,15 +5,15 @@ namespace Inno.Core.Jobs.Internal; internal sealed class WorkerRuntime { internal WorkerRuntime( - int workerId, + int workerID, ThreadStart loopBody ) { - id = workerId; - localQueue = new WorkStealingDeque(); - thread = new Thread(loopBody) + this.id = workerID; + this.localQueue = new WorkStealingDeque(); + this.thread = new Thread(loopBody) { IsBackground = true, - Name = $"Inno.JobWorker.{workerId}" + Name = $"Inno.JobWorker.{workerID}" }; } diff --git a/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs b/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs index 02b593ffb..fefe5dce6 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs @@ -9,7 +9,6 @@ public enum JobExecutionMode /// Executes jobs deterministically on the scheduler owner thread. /// SingleThread, - /// /// Executes ready jobs on a bounded work-stealing worker pool. /// diff --git a/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs b/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs index fc1a6cd6d..2784f7040 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs @@ -84,8 +84,7 @@ public JobHandle Schedule( Action job, object? state, ReadOnlySpan dependencies - ) - => m_implementation.Schedule(job, state, dependencies); + ) => m_implementation.Schedule(job, state, dependencies); /// /// Creates one handle that completes after every supplied dependency. diff --git a/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs b/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs index 4cbf0284c..9d3b37967 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs @@ -7,7 +7,7 @@ namespace Inno.Core.Jobs; /// public readonly struct JobSchedulerOptions { - private const int DEFAULT_MAX_WORKER_THREADS = 64; + private const int C_DEFAULT_MAX_WORKER_THREADS = 64; /// /// Gets the worker-pool thread count, clamped to 1 through 64 for positive values. @@ -31,18 +31,10 @@ public readonly struct JobSchedulerOptions /// public int mainThreadDrainBudget { get; init; } - internal int ResolveFrameCapacity() => ResolvePositive(maxFrameJobs, 65536); + internal int ResolveFrameCapacity() => ResolvePositive(maxFrameJobs, 65_536); internal MainThreadWorkQueue CreateMainThreadQueue() - => new(ResolvePositive(mainThreadCapacity, 65536), ResolvePositive(mainThreadDrainBudget, 4096)); - - private static int ResolvePositive( - int value, - int defaultValue - ) { - ArgumentOutOfRangeException.ThrowIfNegative(value); - return value == 0 ? defaultValue : value; - } + => new(ResolvePositive(mainThreadCapacity, 65_536), ResolvePositive(mainThreadDrainBudget, 4096)); internal int ResolveWorkerCount() { @@ -53,11 +45,19 @@ internal int ResolveWorkerCount() if (workerCount == 0) { - var cpuCount = Environment.ProcessorCount; - var resolved = cpuCount > 1 ? cpuCount - 1 : 1; - return Math.Clamp(resolved, 1, DEFAULT_MAX_WORKER_THREADS); + int cpuCount = Environment.ProcessorCount; + int resolved = cpuCount > 1 ? cpuCount - 1 : 1; + return Math.Clamp(resolved, 1, C_DEFAULT_MAX_WORKER_THREADS); } - return Math.Clamp(workerCount, 1, DEFAULT_MAX_WORKER_THREADS); + return Math.Clamp(workerCount, 1, C_DEFAULT_MAX_WORKER_THREADS); + } + + private static int ResolvePositive( + int value, + int defaultValue + ) { + ArgumentOutOfRangeException.ThrowIfNegative(value); + return value == 0 ? defaultValue : value; } } diff --git a/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs b/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs index a38023bf2..4d12508d9 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs @@ -9,26 +9,32 @@ public readonly record struct JobSchedulerStatistics /// Gets jobs admitted in the current frame, including completed jobs awaiting EndFrame. /// public int frameJobs { get; init; } + /// /// Gets the largest admitted frame since scheduler creation. /// public int peakFrameJobs { get; init; } + /// /// Gets rejected job admissions caused by the finite frame capacity. /// public long rejectedJobs { get; init; } + /// /// Gets queued or retirement-pending owner-thread callbacks. /// public int mainThreadPending { get; init; } + /// /// Gets the largest simultaneous owner-thread queue occupancy. /// public int mainThreadPeak { get; init; } + /// /// Gets callbacks rejected because the queue was full or closed. /// public long mainThreadRejected { get; init; } + /// /// Gets accepted callbacks canceled before execution during shutdown. /// diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs b/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs index a4781d8c8..f8be7e9c2 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs @@ -10,9 +10,9 @@ int drainBudget ) { private readonly object m_sync = new(); private readonly Queue m_actions = []; + private readonly List m_failures = []; private bool m_closed; private bool m_executing; - private readonly List m_failures = []; private Action? m_pending; private RetirementBarrier? m_barrier; private int m_peak; @@ -24,11 +24,15 @@ internal JobSchedulerStatistics statistics get { lock (m_sync) + { return new JobSchedulerStatistics { mainThreadPending = m_actions.Count + (m_pending is null ? 0 : 1), - mainThreadPeak = m_peak, mainThreadRejected = m_rejected, mainThreadCanceled = m_canceled + mainThreadPeak = m_peak, + mainThreadRejected = m_rejected, + mainThreadCanceled = m_canceled }; + } } } @@ -64,17 +68,23 @@ internal void Drain() } int count; lock (m_sync) + { count = Math.Min(drainBudget, m_actions.Count); + } for (int index = 0; index < count; index++) { Action action; lock (m_sync) { if (!m_actions.TryDequeue(out action!)) + { break; + } } lock (m_sync) + { m_pending = action; + } try { CompletePending(); @@ -82,7 +92,9 @@ internal void Drain() catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (m_failures.Count > 0) + { throw new AggregateException("Callbacks remain pending after completed failures.", [.. m_failures, pending]); + } throw; } catch (Exception exception) @@ -119,7 +131,9 @@ internal void Close() private void ReportFailures() { if (m_failures.Count == 0) + { return; + } var failure = new AggregateException("Main-thread callbacks completed with failures.", m_failures); m_failures.Clear(); throw failure; @@ -128,18 +142,26 @@ private void ReportFailures() private void CompletePending() { if (m_executing) + { throw new RetirementPendingException("A main-thread callback cannot retire itself reentrantly."); + } Action? action; lock (m_sync) + { action = m_pending; + } if (action is null) + { return; + } m_barrier ??= new RetirementBarrier("Job main-thread callback"); m_executing = true; try { if (!m_barrier.TryComplete(action)) + { throw new RetirementPendingException("An owner-thread job callback has unfinished retirement."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -160,7 +182,9 @@ private void CompletePending() private void ClearPending() { lock (m_sync) + { m_pending = null; + } m_barrier = null; } } diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs index 495641acc..21b6b72db 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs @@ -1,7 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Concurrent; using System.Collections.Generic; +using Inno.Core.Execution; using Inno.Core.Jobs.Internal; namespace Inno.Core.Jobs; @@ -11,27 +11,28 @@ namespace Inno.Core.Jobs; /// internal sealed class SingleThreadJobSystem : IJobSystem { - private static readonly Action s_noop = static _ => { }; - private static readonly Action s_actionInvoker = static state => ((Action?)state)?.Invoke(); - private static readonly Action s_parallelRangeInvoker = static state => + private static readonly Action NOOP = static _ => {}; + private static readonly Action ACTION_INVOKER = static state => ((Action?)state)?.Invoke(); + + private static readonly Action PARALLEL_RANGE_INVOKER = static state => { - var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ParallelForRangeState rangeState = (ParallelForRangeState?)state + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; private readonly object m_jobsGate = new(); private readonly MainThreadWorkQueue m_mainThreadQueue; private readonly int m_maxFrameJobs; - private int m_peakFrameJobs; - private long m_rejectedJobs; private readonly List m_shutdownFailures = []; private readonly Queue m_readyQueue = new(); private readonly List m_jobs = []; private readonly Stack m_freeIndices = []; private readonly List m_frameJobs = []; - private readonly int m_mainThreadId; + private readonly int m_mainThreadID; + private int m_peakFrameJobs; + private long m_rejectedJobs; private bool m_frameActive; private bool m_disposed; @@ -42,7 +43,7 @@ internal SingleThreadJobSystem(JobSchedulerOptions options) { m_mainThreadQueue = options.CreateMainThreadQueue(); m_maxFrameJobs = options.ResolveFrameCapacity(); - m_mainThreadId = Environment.CurrentManagedThreadId; + m_mainThreadID = Environment.CurrentManagedThreadId; } /// @@ -53,10 +54,14 @@ public JobSchedulerStatistics statistics get { lock (m_jobsGate) + { return m_mainThreadQueue.statistics with { - frameJobs = m_frameJobs.Count, peakFrameJobs = m_peakFrameJobs, rejectedJobs = m_rejectedJobs + frameJobs = m_frameJobs.Count, + peakFrameJobs = m_peakFrameJobs, + rejectedJobs = m_rejectedJobs }; + } } } @@ -102,10 +107,10 @@ public void EndFrame() } handles.Capacity = m_frameJobs.Count; - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -115,7 +120,7 @@ public void EndFrame() } List? faults = null; - for (var i = 0; i < handles.Count; i++) + for (int i = 0; i < handles.Count; i++) { try { @@ -134,10 +139,10 @@ public void EndFrame() lock (m_jobsGate) { - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -173,7 +178,7 @@ public void EndFrame() public JobHandle Schedule(Action job) { ArgumentNullException.ThrowIfNull(job); - return Schedule(s_actionInvoker, job, ReadOnlySpan.Empty); + return Schedule(ACTION_INVOKER, job, []); } /// @@ -209,22 +214,24 @@ ReadOnlySpan dependencies foreach (JobHandle dependency in dependencies) { if (!dependency.isValid) + { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); + } _ = ResolveHandleNoLock(dependency); } - var index = AllocateJobIndexNoLock(job, state); - var record = m_jobs[index]; + int index = AllocateJobIndexNoLock(job, state); + JobRecord record = m_jobs[index]; - var dependencyCount = 0; - for (var i = 0; i < dependencies.Length; i++) + int dependencyCount = 0; + for (int i = 0; i < dependencies.Length; i++) { - var dependency = dependencies[i]; + JobHandle dependency = dependencies[i]; if (!dependency.isValid) { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); } - var dependencyRecord = ResolveHandleNoLock(dependency); + JobRecord dependencyRecord = ResolveHandleNoLock(dependency); if (dependencyRecord.executionState == JobExecutionState.Completed) { continue; @@ -262,10 +269,7 @@ ReadOnlySpan dependencies /// /// The validated job handle that represents the completed operation. /// - public JobHandle CombineDependencies(ReadOnlySpan dependencies) - { - return Schedule(s_noop, null, dependencies); - } + public JobHandle CombineDependencies(ReadOnlySpan dependencies) => Schedule(NOOP, null, dependencies); /// /// Schedules the indexed range in batches and returns its completion handle. @@ -300,22 +304,22 @@ Action body if (length == 0) { - return Schedule(s_noop, null, ReadOnlySpan.Empty); + return Schedule(NOOP, null, []); } ThrowIfDisposed(); lock (m_jobsGate) { EnsureFrameActiveNoLock(); - var chunkCount = 1 + (length - 1) / batchSize; + int chunkCount = 1 + (length - 1) / batchSize; RequireCapacityNoLock(checked(chunkCount + 1)); var handles = new JobHandle[chunkCount]; - var chunkIndex = 0; - for (var start = 0; start < length;) + int chunkIndex = 0; + for (int start = 0; start < length;) { - var end = start + Math.Min(batchSize, length - start); + int end = start + Math.Min(batchSize, length - start); var state = new ParallelForRangeState(body, start, end); - handles[chunkIndex++] = Schedule(s_parallelRangeInvoker, state, ReadOnlySpan.Empty); + handles[chunkIndex++] = Schedule(PARALLEL_RANGE_INVOKER, state, []); start = end; } @@ -341,7 +345,7 @@ public void Complete(JobHandle handle) while (true) { - if (TryGetCompletion(handle, out var exception)) + if (TryGetCompletion(handle, out Exception? exception)) { if (exception is not null) { @@ -366,7 +370,7 @@ public void Complete(JobHandle handle) /// public void CompleteAll(ReadOnlySpan handles) { - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { Complete(handles[i]); } @@ -383,7 +387,9 @@ public void EnqueueMainThread(Action action) ArgumentNullException.ThrowIfNull(action); ThrowIfDisposed(); if (!m_mainThreadQueue.TryEnqueue(action)) + { throw new InvalidOperationException("The main-thread callback queue is at capacity or retiring."); + } } /// @@ -403,12 +409,16 @@ public void DrainMainThreadQueue() public void Dispose() { if (m_disposed) + { return; + } EnsureMainThread(); try { if (m_frameActive) + { EndFrame(); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -454,7 +464,7 @@ private bool TryExecuteSingleQueuedJob() } index = m_readyQueue.Dequeue(); - if (!TryGetActiveRecordNoLock(index, out var record) || record.executionState != JobExecutionState.Queued) + if (!TryGetActiveRecordNoLock(index, out JobRecord record) || record.executionState != JobExecutionState.Queued) { return false; } @@ -466,7 +476,7 @@ private bool TryExecuteSingleQueuedJob() object? state; lock (m_jobsGate) { - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; callback = record.callback; state = record.state; } @@ -484,7 +494,7 @@ private bool TryExecuteSingleQueuedJob() List? readyIndices = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(index, out var record)) + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { return true; } @@ -500,10 +510,10 @@ private bool TryExecuteSingleQueuedJob() if (record.dependents is { Count: > 0 }) { readyIndices = []; - for (var i = 0; i < record.dependents.Count; i++) + for (int i = 0; i < record.dependents.Count; i++) { - var dependentIndex = record.dependents[i]; - if (!TryGetActiveRecordNoLock(dependentIndex, out var dependent)) + int dependentIndex = record.dependents[i]; + if (!TryGetActiveRecordNoLock(dependentIndex, out JobRecord dependent)) { continue; } @@ -532,7 +542,7 @@ private void QueueReadyJobs(List readyIndices) { lock (m_jobsGate) { - for (var i = 0; i < readyIndices.Count; i++) + for (int i = 0; i < readyIndices.Count; i++) { m_readyQueue.Enqueue(readyIndices[i]); } @@ -564,7 +574,7 @@ private int AllocateJobIndexNoLock( m_jobs.Add(new JobRecord()); } - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; record.ResetForAllocation(callback, state); m_frameJobs.Add(index); m_peakFrameJobs = Math.Max(m_peakFrameJobs, m_frameJobs.Count); @@ -577,7 +587,7 @@ out Exception? exception ) { lock (m_jobsGate) { - var record = ResolveHandleNoLock(handle); + JobRecord record = ResolveHandleNoLock(handle); if (record.executionState != JobExecutionState.Completed) { exception = null; @@ -596,7 +606,7 @@ private JobRecord ResolveHandleNoLock(JobHandle handle) throw new InvalidOperationException("Job handle index is out of range."); } - var record = m_jobs[handle.index]; + JobRecord record = m_jobs[handle.index]; if (!record.inUse || record.version != handle.version) { throw new InvalidOperationException("Job handle is stale or no longer valid."); @@ -629,19 +639,13 @@ private void EnsureFrameActiveNoLock() private void EnsureMainThread() { - if (Environment.CurrentManagedThreadId != m_mainThreadId) + if (Environment.CurrentManagedThreadId != m_mainThreadID) { throw new InvalidOperationException("This operation must be executed on the main thread."); } } - private void ThrowIfDisposed() - { - if (m_disposed) - { - throw new ObjectDisposedException(nameof(SingleThreadJobSystem)); - } - } + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); private sealed class ParallelForRangeState { diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs index 7d93df797..1af9bcf81 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs @@ -1,8 +1,8 @@ using System; -using Inno.Core.Execution; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; +using Inno.Core.Execution; using Inno.Core.Jobs.Internal; namespace Inno.Core.Jobs; @@ -12,12 +12,13 @@ namespace Inno.Core.Jobs; /// internal sealed class WorkStealingJobSystem : IJobSystem { - private static readonly Action s_noop = static _ => { }; - private static readonly Action s_actionInvoker = static state => ((Action?)state)?.Invoke(); - private static readonly Action s_parallelRangeInvoker = static state => + private static readonly Action NOOP = static _ => {}; + private static readonly Action ACTION_INVOKER = static state => ((Action?)state)?.Invoke(); + + private static readonly Action PARALLEL_RANGE_INVOKER = static state => { - var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ParallelForRangeState rangeState = (ParallelForRangeState?)state + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; @@ -25,20 +26,20 @@ internal sealed class WorkStealingJobSystem : IJobSystem private readonly ConcurrentQueue m_globalInjectQueue = new(); private readonly MainThreadWorkQueue m_mainThreadQueue; private readonly int m_maxFrameJobs; - private int m_peakFrameJobs; - private long m_rejectedJobs; private readonly List m_shutdownFailures = []; private readonly ManualResetEventSlim m_completionSignal = new(false); private readonly SemaphoreSlim m_wakeSignal = new(0); - private readonly ThreadLocal m_currentWorkerId = new(() => -1, trackAllValues: false); + private readonly ThreadLocal m_currentWorkerID = new(() => -1, trackAllValues: false); private readonly WorkerRuntime[] m_workers; private readonly List m_jobs = []; private readonly Stack m_freeIndices = []; private readonly List m_frameJobs = []; - private readonly int m_mainThreadId; + private readonly int m_mainThreadID; private readonly int m_workerCount; + private int m_peakFrameJobs; + private long m_rejectedJobs; private bool m_disposed; private bool m_frameActive; private int m_running; @@ -47,9 +48,7 @@ internal sealed class WorkStealingJobSystem : IJobSystem /// Creates a job system with default options. /// internal WorkStealingJobSystem() - : this(new JobSchedulerOptions()) - { - } + : this(new JobSchedulerOptions()) {} /// /// Creates a job system with explicit options. @@ -58,7 +57,7 @@ internal WorkStealingJobSystem(JobSchedulerOptions options) { m_mainThreadQueue = options.CreateMainThreadQueue(); m_maxFrameJobs = options.ResolveFrameCapacity(); - m_mainThreadId = Environment.CurrentManagedThreadId; + m_mainThreadID = Environment.CurrentManagedThreadId; m_workerCount = options.ResolveWorkerCount(); m_workers = new WorkerRuntime[m_workerCount]; m_running = 1; @@ -66,23 +65,29 @@ internal WorkStealingJobSystem(JobSchedulerOptions options) int started = 0; try { - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { - var workerId = i; - m_workers[i] = new WorkerRuntime(workerId, () => WorkerLoop(workerId)); + int workerID = i; + m_workers[i] = new WorkerRuntime(workerID, () => WorkerLoop(workerID)); } for (; started < m_workers.Length; started++) + { m_workers[started].thread.Start(); + } } catch { Interlocked.Exchange(ref m_running, 0); for (int index = 0; index < started; index++) + { m_wakeSignal.Release(); + } // No work can have been admitted before construction returns. for (int index = 0; index < started; index++) + { m_workers[index].thread.Join(); - m_currentWorkerId.Dispose(); + } + m_currentWorkerID.Dispose(); m_wakeSignal.Dispose(); m_completionSignal.Dispose(); throw; @@ -97,10 +102,14 @@ public JobSchedulerStatistics statistics get { lock (m_jobsGate) + { return m_mainThreadQueue.statistics with { - frameJobs = m_frameJobs.Count, peakFrameJobs = m_peakFrameJobs, rejectedJobs = m_rejectedJobs + frameJobs = m_frameJobs.Count, + peakFrameJobs = m_peakFrameJobs, + rejectedJobs = m_rejectedJobs }; + } } } @@ -143,10 +152,10 @@ public void EndFrame() } handles.Capacity = m_frameJobs.Count; - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -156,7 +165,7 @@ public void EndFrame() } List? exceptions = null; - for (var i = 0; i < handles.Count; i++) + for (int i = 0; i < handles.Count; i++) { try { @@ -175,10 +184,10 @@ public void EndFrame() lock (m_jobsGate) { - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -214,7 +223,7 @@ public void EndFrame() public JobHandle Schedule(Action job) { ArgumentNullException.ThrowIfNull(job); - return Schedule(s_actionInvoker, job, ReadOnlySpan.Empty); + return Schedule(ACTION_INVOKER, job, []); } /// @@ -249,22 +258,24 @@ ReadOnlySpan dependencies foreach (JobHandle dependency in dependencies) { if (!dependency.isValid) + { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); + } _ = ResolveHandleNoLock(dependency); } - var index = AllocateJobIndexNoLock(job, state); - var record = m_jobs[index]; + int index = AllocateJobIndexNoLock(job, state); + JobRecord record = m_jobs[index]; - var dependencyCount = 0; - for (var i = 0; i < dependencies.Length; i++) + int dependencyCount = 0; + for (int i = 0; i < dependencies.Length; i++) { - var dependency = dependencies[i]; + JobHandle dependency = dependencies[i]; if (!dependency.isValid) { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); } - var dependencyRecord = ResolveHandleNoLock(dependency); + JobRecord dependencyRecord = ResolveHandleNoLock(dependency); if (dependencyRecord.executionState == JobExecutionState.Completed) { continue; @@ -302,10 +313,7 @@ ReadOnlySpan dependencies /// /// The validated job handle that represents the completed operation. /// - public JobHandle CombineDependencies(ReadOnlySpan dependencies) - { - return Schedule(s_noop, null, dependencies); - } + public JobHandle CombineDependencies(ReadOnlySpan dependencies) => Schedule(NOOP, null, dependencies); /// /// Schedules the indexed range in batches and returns its completion handle. @@ -340,22 +348,22 @@ Action body if (length == 0) { - return Schedule(s_noop, null, ReadOnlySpan.Empty); + return Schedule(NOOP, null, []); } ThrowIfDisposed(); lock (m_jobsGate) { EnsureFrameActiveNoLock(); - var chunkCount = 1 + (length - 1) / batchSize; + int chunkCount = 1 + (length - 1) / batchSize; RequireCapacityNoLock(checked(chunkCount + 1)); var chunkHandles = new JobHandle[chunkCount]; - var chunkIndex = 0; - for (var start = 0; start < length;) + int chunkIndex = 0; + for (int start = 0; start < length;) { - var end = start + Math.Min(batchSize, length - start); + int end = start + Math.Min(batchSize, length - start); var rangeState = new ParallelForRangeState(body, start, end); - chunkHandles[chunkIndex++] = Schedule(s_parallelRangeInvoker, rangeState, ReadOnlySpan.Empty); + chunkHandles[chunkIndex++] = Schedule(PARALLEL_RANGE_INVOKER, rangeState, []); start = end; } @@ -381,7 +389,7 @@ public void Complete(JobHandle handle) var spinner = new SpinWait(); while (true) { - if (TryGetCompletion(handle, out var exception)) + if (TryGetCompletion(handle, out Exception? exception)) { if (exception is not null) { @@ -417,7 +425,7 @@ public void Complete(JobHandle handle) /// public void CompleteAll(ReadOnlySpan handles) { - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { Complete(handles[i]); } @@ -434,7 +442,9 @@ public void EnqueueMainThread(Action action) ArgumentNullException.ThrowIfNull(action); ThrowIfDisposed(); if (!m_mainThreadQueue.TryEnqueue(action)) + { throw new InvalidOperationException("The main-thread callback queue is at capacity or retiring."); + } } /// @@ -462,7 +472,9 @@ public void Dispose() try { if (m_frameActive) + { EndFrame(); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -487,17 +499,17 @@ public void Dispose() m_disposed = true; Interlocked.Exchange(ref m_running, 0); - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { m_wakeSignal.Release(); } - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { m_workers[i].thread.Join(); } - m_currentWorkerId.Dispose(); + m_currentWorkerID.Dispose(); m_wakeSignal.Dispose(); m_completionSignal.Dispose(); m_mainThreadQueue.Close(); @@ -513,9 +525,9 @@ public void Dispose() } } - private void WorkerLoop(int workerId) + private void WorkerLoop(int workerID) { - m_currentWorkerId.Value = workerId; + m_currentWorkerID.Value = workerID; while (Volatile.Read(ref m_running) != 0) { m_wakeSignal.Wait(50); @@ -532,7 +544,7 @@ private void WorkerLoop(int workerId) private bool TryExecuteOneAvailableJob() { - if (!TryDequeueWorkItem(out var jobIndex)) + if (!TryDequeueWorkItem(out int jobIndex)) { return false; } @@ -541,7 +553,7 @@ private bool TryExecuteOneAvailableJob() object? state = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(jobIndex, out var record)) + if (!TryGetActiveRecordNoLock(jobIndex, out JobRecord record)) { return false; } @@ -569,7 +581,7 @@ private bool TryExecuteOneAvailableJob() List? readyIndices = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(jobIndex, out var record)) + if (!TryGetActiveRecordNoLock(jobIndex, out JobRecord record)) { return true; } @@ -585,10 +597,10 @@ private bool TryExecuteOneAvailableJob() if (record.dependents is { Count: > 0 }) { readyIndices = []; - for (var i = 0; i < record.dependents.Count; i++) + for (int i = 0; i < record.dependents.Count; i++) { - var dependentIndex = record.dependents[i]; - if (!TryGetActiveRecordNoLock(dependentIndex, out var dependent)) + int dependentIndex = record.dependents[i]; + if (!TryGetActiveRecordNoLock(dependentIndex, out JobRecord dependent)) { continue; } @@ -616,10 +628,10 @@ private bool TryExecuteOneAvailableJob() private bool TryDequeueWorkItem(out int jobIndex) { - var workerId = m_currentWorkerId.Value; - if (workerId >= 0) + int workerID = m_currentWorkerID.Value; + if (workerID >= 0) { - if (m_workers[workerId].localQueue.TryPopBottom(out jobIndex)) + if (m_workers[workerID].localQueue.TryPopBottom(out jobIndex)) { return true; } @@ -630,12 +642,12 @@ private bool TryDequeueWorkItem(out int jobIndex) return true; } - if (workerId >= 0) + if (workerID >= 0) { - var startVictim = (workerId + 1) % m_workers.Length; - for (var i = 0; i < m_workers.Length - 1; i++) + int startVictim = (workerID + 1) % m_workers.Length; + for (int i = 0; i < m_workers.Length - 1; i++) { - var victim = (startVictim + i) % m_workers.Length; + int victim = (startVictim + i) % m_workers.Length; if (m_workers[victim].localQueue.TryStealTop(out jobIndex)) { return true; @@ -644,7 +656,7 @@ private bool TryDequeueWorkItem(out int jobIndex) } else { - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { if (m_workers[i].localQueue.TryStealTop(out jobIndex)) { @@ -659,13 +671,13 @@ private bool TryDequeueWorkItem(out int jobIndex) private void QueueReadyJobs(List readyIndices) { - var workerId = m_currentWorkerId.Value; - for (var i = 0; i < readyIndices.Count; i++) + int workerID = m_currentWorkerID.Value; + for (int i = 0; i < readyIndices.Count; i++) { - var index = readyIndices[i]; - if (workerId >= 0) + int index = readyIndices[i]; + if (workerID >= 0) { - m_workers[workerId].localQueue.PushBottom(index); + m_workers[workerID].localQueue.PushBottom(index); } else { @@ -701,7 +713,7 @@ private int AllocateJobIndexNoLock( m_jobs.Add(new JobRecord()); } - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; record.ResetForAllocation(callback, state); m_frameJobs.Add(index); m_peakFrameJobs = Math.Max(m_peakFrameJobs, m_frameJobs.Count); @@ -714,7 +726,7 @@ out Exception? exception ) { lock (m_jobsGate) { - var record = ResolveHandleNoLock(handle); + JobRecord record = ResolveHandleNoLock(handle); if (record.executionState != JobExecutionState.Completed) { exception = null; @@ -733,7 +745,7 @@ private JobRecord ResolveHandleNoLock(JobHandle handle) throw new InvalidOperationException("Job handle index is out of range."); } - var record = m_jobs[handle.index]; + JobRecord record = m_jobs[handle.index]; if (!record.inUse || record.version != handle.version) { throw new InvalidOperationException("Job handle is stale or no longer valid."); @@ -766,19 +778,13 @@ private void EnsureFrameActiveNoLock() private void EnsureMainThread() { - if (Environment.CurrentManagedThreadId != m_mainThreadId) + if (Environment.CurrentManagedThreadId != m_mainThreadID) { throw new InvalidOperationException("This operation must be executed on the main thread."); } } - private void ThrowIfDisposed() - { - if (m_disposed) - { - throw new ObjectDisposedException(nameof(WorkStealingJobSystem)); - } - } + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); private sealed class ParallelForRangeState { diff --git a/src/foundation/core/Inno.Core.Layers/Layer.cs b/src/foundation/core/Inno.Core.Layers/Layer.cs index 67e12497d..9e772fc0c 100644 --- a/src/foundation/core/Inno.Core.Layers/Layer.cs +++ b/src/foundation/core/Inno.Core.Layers/Layer.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; - using Inno.Core.Events; using Inno.Core.Execution; @@ -29,7 +28,9 @@ public abstract class Layer protected Layer(string name = "Layer") { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A layer name is required.", nameof(name)); + } this.name = name; } @@ -41,9 +42,7 @@ protected Layer(string name = "Layer") /// /// Runs after the layer has received its event scope and joined a stack. /// - public virtual void OnAttach() - { - } + public virtual void OnAttach() {} /// /// Runs while the layer is leaving its stack and before its event scope is released. @@ -53,9 +52,7 @@ public virtual void OnAttach() /// retains ownership and permits a later cleanup retry. /// Completed cleanup steps must not be repeated on that retry. /// - public virtual void OnDetach() - { - } + public virtual void OnDetach() {} /// /// Advances fixed-step work for this layer. @@ -63,9 +60,7 @@ public virtual void OnDetach() /// /// The fixed simulation interval in seconds. /// - public virtual void OnFixedUpdate(float fixedDeltaTime) - { - } + public virtual void OnFixedUpdate(float fixedDeltaTime) {} /// /// Advances variable-step work for this layer. @@ -73,9 +68,7 @@ public virtual void OnFixedUpdate(float fixedDeltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnUpdate(float deltaTime) - { - } + public virtual void OnUpdate(float deltaTime) {} /// /// Advances work that must run after the regular update phase. @@ -83,9 +76,7 @@ public virtual void OnUpdate(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnLateUpdate(float deltaTime) - { - } + public virtual void OnLateUpdate(float deltaTime) {} /// /// Prepares frame-scoped rendering state before render work is submitted. @@ -93,9 +84,7 @@ public virtual void OnLateUpdate(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnBeforeRender(float deltaTime) - { - } + public virtual void OnBeforeRender(float deltaTime) {} /// /// Submits rendering work without presenting a concrete graphics backend. @@ -103,23 +92,21 @@ public virtual void OnBeforeRender(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnRender(float deltaTime) - { - } + public virtual void OnRender(float deltaTime) {} /// /// Completes frame-scoped rendering state after render submission. /// + /// + /// The elapsed frame time in seconds. + /// /// /// A invokes this callback in reverse order for every layer whose /// callback completed successfully, including when later work fails. /// - /// - /// The elapsed frame time in seconds. - /// - public virtual void OnAfterRender(float deltaTime) - { - } + public virtual void OnAfterRender(float deltaTime) {} + + internal bool isAttached => m_events is not null; /// /// Subscribes to an event for the lifetime of this layer attachment. @@ -142,8 +129,7 @@ public virtual void OnAfterRender(float deltaTime) protected IDisposable Listen( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { EventHub events = RequireActiveEvents(); IDisposable subscription = events.Listen(handler, priority); @@ -172,8 +158,7 @@ protected IDisposable Listen( protected IDisposable ListenOnce( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { EventHub events = RequireActiveEvents(); IDisposable subscription = events.ListenOnce(handler, priority); @@ -197,13 +182,13 @@ protected void Announce(Event evnt) events.Announce(evnt); } - internal bool isAttached => m_events is not null; - internal void Attach(EventHub events) { ArgumentNullException.ThrowIfNull(events); if (m_events is not null) + { throw new InvalidOperationException($"Layer '{name}' is already attached."); + } m_events = events; OnAttach(); @@ -212,7 +197,9 @@ internal void Attach(EventHub events) internal void Detach() { if (m_events is null) + { throw new InvalidOperationException($"Layer '{name}' is not attached."); + } if (!m_detaching) { @@ -238,16 +225,20 @@ internal void Detach() List? failures = m_detachFailures; m_detachFailures = null; if (failures is null) + { return; + } if (failures.Count == 1) + { ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } throw new AggregateException($"Layer '{name}' encountered multiple detach failures.", failures); } private EventHub RequireActiveEvents() => !m_detaching && m_events is not null - ? m_events - : throw new InvalidOperationException("The layer has no active event scope or is already detaching."); + ? m_events + : throw new InvalidOperationException("The layer has no active event scope or is already detaching."); private List? ReleaseSubscriptions() { diff --git a/src/foundation/core/Inno.Core.Layers/LayerStack.cs b/src/foundation/core/Inno.Core.Layers/LayerStack.cs index 0e27bd9d7..1f126316c 100644 --- a/src/foundation/core/Inno.Core.Layers/LayerStack.cs +++ b/src/foundation/core/Inno.Core.Layers/LayerStack.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; - using Inno.Core.Events; using Inno.Core.Execution; @@ -30,7 +29,8 @@ public sealed class LayerStack : IDisposable /// public LayerStack(Func eventHubFactory) { - m_eventHubFactory = eventHubFactory ?? throw new ArgumentNullException(nameof(eventHubFactory)); + ArgumentNullException.ThrowIfNull(eventHubFactory); + m_eventHubFactory = eventHubFactory; } /// @@ -67,10 +67,7 @@ public LayerStack(Func eventHubFactory) /// /// Thrown when this stack has been disposed. /// - public void PushLayer(Layer layer) - { - Insert(layer, m_baseLayerCount, isBaseLayer: true); - } + public void PushLayer(Layer layer) => Insert(layer, m_baseLayerCount, isBaseLayer: true); /// /// Attaches an overlay above all base layers and existing overlays. @@ -110,7 +107,9 @@ public bool PopLayer(Layer layer) ArgumentNullException.ThrowIfNull(layer); int index = Find(layer); if (index < 0 || index >= m_baseLayerCount) + { return false; + } Remove(index); return true; } @@ -136,7 +135,9 @@ public bool PopOverlay(Layer overlay) ArgumentNullException.ThrowIfNull(overlay); int index = Find(overlay); if (index < m_baseLayerCount) + { return false; + } Remove(index); return true; } @@ -154,7 +155,9 @@ public void OnFixedUpdate(float fixedDeltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnFixedUpdate(fixedDeltaTime); + } } /// @@ -170,7 +173,9 @@ public void OnUpdate(float deltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnUpdate(deltaTime); + } } /// @@ -186,7 +191,9 @@ public void OnLateUpdate(float deltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnLateUpdate(deltaTime); + } } /// @@ -209,9 +216,13 @@ public void RenderFrame(float deltaTime) try { for (; preparedCount < m_layers.Count; preparedCount++) + { m_layers[preparedCount].layer.OnBeforeRender(deltaTime); + } for (int index = 0; index < preparedCount; index++) + { m_layers[index].layer.OnRender(deltaTime); + } } catch (Exception exception) { @@ -268,7 +279,9 @@ public void Clear() public void Dispose() { if (m_disposed) + { return; + } List? failures = DetachAll(); m_disposed = true; ThrowFailures(failures, "One or more layers failed to detach while disposing the stack."); @@ -282,13 +295,17 @@ bool isBaseLayer EnsureActive(); ArgumentNullException.ThrowIfNull(layer); if (layer.isAttached || Find(layer) >= 0) + { throw new InvalidOperationException($"Layer '{layer.name}' is already attached to this stack."); + } EventHub events = m_eventHubFactory() - ?? throw new InvalidOperationException("The layer event hub factory returned null."); + ?? throw new InvalidOperationException("The layer event hub factory returned null."); m_layers.Insert(index, new Entry(layer, events)); if (isBaseLayer) + { m_baseLayerCount++; + } try { UpdateEventOrder(); @@ -321,7 +338,9 @@ private void Remove(int index) try { if (entry.layer.isAttached) + { entry.layer.Detach(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -342,7 +361,9 @@ private void Remove(int index) } m_layers.RemoveAt(index); if (index < m_baseLayerCount) + { m_baseLayerCount--; + } UpdateEventOrder(); ThrowFailures(failures, "Layer detachment and event-scope retirement failed."); } @@ -375,7 +396,9 @@ private int Find(Layer layer) for (int index = 0; index < m_layers.Count; index++) { if (ReferenceEquals(m_layers[index].layer, layer)) + { return index; + } } return -1; } @@ -383,14 +406,18 @@ private int Find(Layer layer) private void UpdateEventOrder() { for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].events.order = index; + } } private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("Layer retirement is pending; resume Clear or Dispose before using this stack."); + } } private static void ThrowFailures( @@ -398,9 +425,13 @@ private static void ThrowFailures( string message ) { if (failures is null) + { return; + } if (failures.Count == 1) + { ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } throw new AggregateException(message, failures); } diff --git a/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs b/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs index 9e4ed03e1..16a5625f4 100644 --- a/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs @@ -5,7 +5,7 @@ namespace Inno.Core.Logging; /// /// Writes log entries to the process console, using level-based colors when a terminal is available. /// -public class ConsoleLogSink : ILogSink +public sealed class ConsoleLogSink : ILogSink { private readonly bool m_useColors; @@ -15,7 +15,10 @@ public class ConsoleLogSink : ILogSink /// /// Whether the host supports console colors; redirected output always uses plain text. /// - public ConsoleLogSink(bool useColors = false) => m_useColors = useColors; + public ConsoleLogSink(bool useColors = false) + { + m_useColors = useColors; + } /// /// Writes the specified entry to standard output. diff --git a/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs b/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs index 0fe2e163f..cff2475b6 100644 --- a/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs @@ -29,10 +29,13 @@ public DiagnosticLogSink( DiagnosticHub hub, LogRouter logs ) { - m_hub = hub ?? throw new ArgumentNullException(nameof(hub)); - m_logs = logs ?? throw new ArgumentNullException(nameof(logs)); + ArgumentNullException.ThrowIfNull(hub); + ArgumentNullException.ThrowIfNull(logs); + m_hub = hub; + m_logs = logs; m_hub.RegisterSink(this); } + /// /// Replaces the current report for one diagnostic source. /// @@ -45,23 +48,36 @@ public void Replace(DiagnosticReport report) Diagnostic[] previous = m_previous.GetValueOrDefault(report.source.id, []); foreach (Diagnostic issue in report.diagnostics) { - if (previous.Any(old => old.code == issue.code && old.semanticId == issue.semanticId && - old.objectId == issue.objectId && old.message == issue.message && old.severity == issue.severity && - Equals(old.location, issue.location))) + if (previous.Any(old => ( + old.code == issue.code && old.semanticID == issue.semanticID + && old.objectID == issue.objectID && old.message == issue.message && old.severity == issue.severity + && Equals(old.location, issue.location) + ))) { continue; + } LogLevel level = issue.severity switch { DiagnosticSeverity.Error => LogLevel.Error, DiagnosticSeverity.Warning => LogLevel.Warn, _ => LogLevel.Info }; - m_logs.Dispatch(new LogEntry(level, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - report.source.displayName, $"{issue.code}: {issue.message}", - issue.location?.sourcePath ?? string.Empty, issue.location?.line ?? 0, - string.Empty, LogSessionContext.current)); + m_logs.Dispatch( + new LogEntry( + level, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + report.source.displayName, + $"{issue.code}: {issue.message}", + issue.location?.sourcePath ?? string.Empty, + issue.location?.line ?? 0, + string.Empty, + LogSessionContext.current + ) + ); } m_previous[report.source.id] = report.diagnostics.ToArray(); } + /// /// Removes the current report for one diagnostic source. /// @@ -76,7 +92,9 @@ public void Replace(DiagnosticReport report) public void Dispose() { if (m_disposed) + { return; + } m_hub.UnregisterSink(this); m_disposed = true; m_previous.Clear(); diff --git a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs index 56350ae22..f3832c87c 100644 --- a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs @@ -8,7 +8,7 @@ namespace Inno.Core.Logging; /// /// Writes complete log entries to uniquely named rotating files under the router's delivery policy. /// -public class FileLogSink : ILogSink, IDisposable +public sealed class FileLogSink : ILogSink, IDisposable { /// /// Prefix used for generated log file names. @@ -16,8 +16,8 @@ public class FileLogSink : ILogSink, IDisposable public const string C_LOG_FILE_PREFIX = "log_"; private const string C_LOG_FILE_EXTENSION = ".log"; - private static readonly UTF8Encoding S_ENCODING = new(encoderShouldEmitUTF8Identifier: false); - private static readonly int S_NEWLINE_BYTES = S_ENCODING.GetByteCount(Environment.NewLine); + private static readonly UTF8Encoding ENCODING = new(encoderShouldEmitUTF8Identifier: false); + private static readonly int NEWLINE_BYTES = ENCODING.GetByteCount(Environment.NewLine); private readonly string m_logDirectory; private readonly long m_maxFileSize; @@ -82,10 +82,6 @@ public FileLogSink( /// /// The immutable entry to persist. /// - /// - /// The router owns scheduling and backpressure. Write failures propagate to its sink quarantine. - /// Retention cannot remove files locked by another active writer and retries them on later rotation. - /// /// /// The sink has been disposed. /// @@ -98,17 +94,23 @@ public FileLogSink( /// /// A previous failed rotation left no writable file. /// + /// + /// The router owns scheduling and backpressure. Write failures propagate to its sink quarantine. + /// Retention cannot remove files locked by another active writer and retries them on later rotation. + /// public void Receive(LogEntry entry) { lock (m_lifecycleSync) { ObjectDisposedException.ThrowIf(m_disposed, this); string line = FormatEntry(entry); - int bytes = S_ENCODING.GetByteCount(line) + S_NEWLINE_BYTES; + int bytes = ENCODING.GetByteCount(line) + NEWLINE_BYTES; if (m_currentSize > 0 && bytes > m_maxFileSize - m_currentSize) + { RotateFile(); + } StreamWriter writer = m_writer - ?? throw new InvalidOperationException("The file log sink has no writable file after a failed rotation."); + ?? throw new InvalidOperationException("The file log sink has no writable file after a failed rotation."); writer.WriteLine(line); writer.Flush(); m_currentSize += bytes; @@ -126,7 +128,9 @@ public void Dispose() lock (m_lifecycleSync) { if (m_disposed) + { return; + } m_disposed = true; CloseWriter(); } @@ -160,7 +164,8 @@ private void CleanupOldFiles() FileAccess.Read, FileShare.None, bufferSize: 1, - FileOptions.DeleteOnClose); + FileOptions.DeleteOnClose + ); } catch (IOException) { @@ -173,9 +178,6 @@ private void CleanupOldFiles() } } - private static string FormatEntry(LogEntry entry) - => $"[{entry.time:yyyy-MM-dd HH:mm:ss.fff}] [{entry.domain}/{entry.scope}] [{entry.level}]: {entry.message} ({entry.file}:{entry.line})"; - private void OpenWriter() { string timestamp = DateTime.UtcNow.ToString("yyyyMMdd_HHmmssfffffff"); @@ -186,10 +188,11 @@ private void OpenWriter() FileAccess.Write, FileShare.Read, bufferSize: 16 * 1024, - FileOptions.SequentialScan); + FileOptions.SequentialScan + ); try { - m_writer = new StreamWriter(stream, S_ENCODING); + m_writer = new StreamWriter(stream, ENCODING); m_currentSize = 0; } catch @@ -205,4 +208,7 @@ private void CloseWriter() m_writer = null; writer?.Dispose(); } + + private static string FormatEntry(LogEntry entry) + => $"[{entry.time:yyyy-MM-dd HH:mm:ss.fff}] [{entry.domain}/{entry.scope}] [{entry.level}]: {entry.message} ({entry.file}:{entry.line})"; } diff --git a/src/foundation/core/Inno.Core.Logging/Log.cs b/src/foundation/core/Inno.Core.Logging/Log.cs index 834088b72..1dfdd1ea1 100644 --- a/src/foundation/core/Inno.Core.Logging/Log.cs +++ b/src/foundation/core/Inno.Core.Logging/Log.cs @@ -354,33 +354,40 @@ int lineNumber ArgumentNullException.ThrowIfNull(sourceType); LogRouter router = LogRouter.current; if (!router.IsEnabled(level)) + { return; + } AssemblyDomain domain = sourceType.Assembly.GetInnoAssemblyDomain(); AssemblyScope scope = sourceType.Assembly.GetInnoAssemblyScope(); string category = GetCategory(filePath); string rendered = arguments is null || arguments.Count == 0 - ? message : string.Format(message, arguments.ToArray()); - router.Dispatch(new LogEntry( - level, - domain, - scope, - category, - rendered, - string.IsNullOrWhiteSpace(filePath) ? C_DEFAULT_CATEGORY : filePath, - lineNumber, - new StackTrace(2, true).ToString(), - LogSessionContext.current)); + ? message + : string.Format(message, arguments.ToArray()); + router.Dispatch( + new LogEntry( + level, + domain, + scope, + category, + rendered, + string.IsNullOrWhiteSpace(filePath) ? C_DEFAULT_CATEGORY : filePath, + lineNumber, + new StackTrace(2, true).ToString(), + LogSessionContext.current + ) + ); } private static string GetCategory(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) + { return C_DEFAULT_CATEGORY; + } // Compiler source paths belong to the authoring host, which can differ from the runtime host. int fileNameStart = Math.Max(filePath.LastIndexOf('/'), filePath.LastIndexOf('\\')) + 1; return Path.GetFileNameWithoutExtension(filePath.AsSpan(fileNameStart)).ToString(); } - } diff --git a/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs b/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs index 47d169ae6..5b0f2c115 100644 --- a/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs +++ b/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs @@ -9,7 +9,6 @@ public enum LogDeliveryMode /// Delivers queued entries through a dedicated background worker. /// Background, - /// /// Delivers entries synchronously on the producer's thread. /// diff --git a/src/foundation/core/Inno.Core.Logging/LogEntry.cs b/src/foundation/core/Inno.Core.Logging/LogEntry.cs index 68b9b27db..75cc44974 100644 --- a/src/foundation/core/Inno.Core.Logging/LogEntry.cs +++ b/src/foundation/core/Inno.Core.Logging/LogEntry.cs @@ -1,5 +1,4 @@ using System; - using Inno.Extensibility.Modules; namespace Inno.Core.Logging; @@ -31,8 +30,8 @@ namespace Inno.Core.Logging; /// /// The captured managed stack trace, or an empty string when no trace is available. /// -/// -/// The isolated runtime session that produced the entry, or for process-level work. +/// +/// The isolated runtime session that produced the entry, or for process-level work. /// public readonly struct LogEntry( LogLevel level, @@ -43,7 +42,7 @@ public readonly struct LogEntry( string file, int line, string stackTrace, - LogSessionId sessionId + LogSessionID sessionID ) { /// /// Gets the severity of this entry. @@ -93,5 +92,5 @@ LogSessionId sessionId /// /// Gets the isolated runtime session that produced this entry. /// - public readonly LogSessionId sessionId = sessionId; + public readonly LogSessionID sessionID = sessionID; } diff --git a/src/foundation/core/Inno.Core.Logging/LogLevel.cs b/src/foundation/core/Inno.Core.Logging/LogLevel.cs index dd2b0dd5c..41eb3d861 100644 --- a/src/foundation/core/Inno.Core.Logging/LogLevel.cs +++ b/src/foundation/core/Inno.Core.Logging/LogLevel.cs @@ -9,22 +9,18 @@ public enum LogLevel /// Diagnostic logs intended for local debugging. /// Debug, - /// /// Informational logs for normal runtime flow. /// Info, - /// /// Warning logs for recoverable problems. /// Warn, - /// /// Error logs for failures that should be investigated. /// Error, - /// /// Fatal logs for unrecoverable failures. /// diff --git a/src/foundation/core/Inno.Core.Logging/LogRouter.cs b/src/foundation/core/Inno.Core.Logging/LogRouter.cs index b33bbb89c..04dadd3a9 100644 --- a/src/foundation/core/Inno.Core.Logging/LogRouter.cs +++ b/src/foundation/core/Inno.Core.Logging/LogRouter.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; - using Inno.Core.Execution; using Inno.Extensibility.Modules; @@ -14,7 +13,7 @@ namespace Inno.Core.Logging; /// public sealed class LogRouter : IDisposable { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("router"); + private static readonly ExecutionSlot CURRENT_SCOPE = new("router"); private readonly List m_sinks = []; private readonly Lock m_sinksLock = new(); @@ -29,19 +28,9 @@ public sealed class LogRouter : IDisposable private volatile bool m_running = true; private volatile LogLevel m_minimumLevel = LogLevel.Debug; private volatile bool m_disposed; - private int m_deliveryThreadId; + private int m_deliveryThreadID; private ILogSink[] m_sinkSnapshot = []; - /// - /// Occurs after a failing sink has been quarantined from this router. - /// - /// - /// Quarantine removes the sink from delivery but does not dispose it. The host must retain - /// responsibility for safely releasing a removed sink. Observers run within delivery and - /// must not flush or dispose this router from their callback. - /// - public event Action? sinkFailed; - /// /// Creates an isolated logging router with an explicit delivery policy. /// @@ -58,14 +47,16 @@ public sealed class LogRouter : IDisposable /// A capacity or budget is not positive, or the delivery policy is not a defined mode. /// public LogRouter( - int queueCapacity = 65536, + int queueCapacity = 65_536, int drainBudget = 4096, LogDeliveryMode deliveryMode = LogDeliveryMode.Background ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(queueCapacity); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(drainBudget); if (!Enum.IsDefined(deliveryMode)) + { throw new ArgumentOutOfRangeException(nameof(deliveryMode)); + } m_queueCapacity = queueCapacity; m_drainBudget = drainBudget; if (deliveryMode == LogDeliveryMode.Background) @@ -79,7 +70,15 @@ public LogRouter( } } - internal static LogRouter current => S_CURRENT_SCOPE.current; + /// + /// Occurs after a failing sink has been quarantined from this router. + /// + /// + /// Quarantine removes the sink from delivery but does not dispose it. The host must retain + /// responsibility for safely releasing a removed sink. Observers run within delivery and + /// must not flush or dispose this router from their callback. + /// + public event Action? sinkFailed; /// /// Binds this router to the current asynchronous execution context. @@ -93,7 +92,7 @@ public LogRouter( public IDisposable EnterScope() { ObjectDisposedException.ThrowIf(m_disposed, this); - return S_CURRENT_SCOPE.Enter(this); + return CURRENT_SCOPE.Enter(this); } /// @@ -126,24 +125,26 @@ public void RegisterSink(ILogSink sink) /// /// Removes a sink from subsequent delivery snapshots without disposing it. /// - /// - /// An in-flight batch may still borrow the previous snapshot. This operation does not wait - /// for its callbacks; the host must coordinate quiescence before releasing sink resources. - /// Router disposal releases only sinks that remain registered. - /// /// /// The sink to remove when registered. /// /// /// Thrown when is null. /// + /// + /// An in-flight batch may still borrow the previous snapshot. This operation does not wait + /// for its callbacks; the host must coordinate quiescence before releasing sink resources. + /// Router disposal releases only sinks that remain registered. + /// public void UnregisterSink(ILogSink sink) { ArgumentNullException.ThrowIfNull(sink); lock (m_sinksLock) { if (m_sinks.Remove(sink)) + { Volatile.Write(ref m_sinkSnapshot, m_sinks.ToArray()); + } } } @@ -182,7 +183,8 @@ public Logger CreateLogger() this, ownerType.Assembly.GetInnoAssemblyDomain(), ownerType.Assembly.GetInnoAssemblyScope(), - ownerType.Name); + ownerType.Name + ); } /// @@ -200,7 +202,9 @@ public Logger CreateLogger() public void Dispatch(LogEntry entry) { if (!TryDispatch(entry)) + { throw new InvalidOperationException("The log queue is full; the producer must apply backpressure."); + } } /// @@ -212,26 +216,32 @@ public void Dispatch(LogEntry entry) /// /// True when accepted or filtered by policy; false when bounded queue capacity is exhausted. /// + /// + /// The router has stopped accepting work. + /// /// /// Inline callers serialize delivery. Entries written by a sink callback are queued until /// every sink has received the current entry, without recursively invoking callbacks. /// - /// - /// The router has stopped accepting work. - /// public bool TryDispatch(LogEntry entry) { lock (m_queueSync) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!IsEnabled(entry.level)) + { return true; + } if (m_queue.Count >= m_queueCapacity) + { return false; + } Enqueue(WorkItem.ForEntry(entry)); } if (m_worker is null) + { DrainInline(); + } return true; } @@ -253,11 +263,15 @@ public void Flush() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_queue.Count >= m_queueCapacity) + { throw new InvalidOperationException("The log queue is full; retry the flush after the worker drains pending entries."); + } Enqueue(WorkItem.ForBarrier(completion)); } if (m_worker is null) + { DrainInline(); + } completion.Wait(); } @@ -274,9 +288,13 @@ public void Dispose() { EnsureOutsideDelivery("dispose"); lock (m_disposalSync) + { DisposeCore(); + } } + internal static LogRouter current => CURRENT_SCOPE.current; + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsEnabled(LogLevel level) => level >= m_minimumLevel; @@ -285,14 +303,18 @@ private void DisposeCore() lock (m_queueSync) { if (m_disposed) + { return; + } m_disposed = true; m_running = false; m_signal.Release(); } m_worker?.Join(); if (m_worker is null) + { DrainInline(); + } ILogSink[] sinks; lock (m_sinksLock) { @@ -305,7 +327,9 @@ private void DisposeCore() for (int index = 0; index < sinks.Length; index++) { if (sinks[index] is not IDisposable disposable) + { continue; + } try { disposable.Dispose(); @@ -318,12 +342,14 @@ private void DisposeCore() } m_signal.Dispose(); if (failures is not null) + { throw new AggregateException("One or more log sinks failed to dispose.", failures); + } } private void ProcessQueue() { - Volatile.Write(ref m_deliveryThreadId, Environment.CurrentManagedThreadId); + Volatile.Write(ref m_deliveryThreadID, Environment.CurrentManagedThreadId); try { while (true) @@ -331,12 +357,14 @@ private void ProcessQueue() m_signal.Wait(); DrainQueue(); if (!m_running && m_queue.IsEmpty) + { return; + } } } finally { - Volatile.Write(ref m_deliveryThreadId, 0); + Volatile.Write(ref m_deliveryThreadID, 0); } } @@ -344,32 +372,40 @@ private void DrainInline() { lock (m_inlineDeliverySync) { - if (m_deliveryThreadId != 0) + if (m_deliveryThreadID != 0) + { return; - Volatile.Write(ref m_deliveryThreadId, Environment.CurrentManagedThreadId); + } + Volatile.Write(ref m_deliveryThreadID, Environment.CurrentManagedThreadId); try { while (!m_queue.IsEmpty) + { DrainQueue(); + } } finally { - Volatile.Write(ref m_deliveryThreadId, 0); + Volatile.Write(ref m_deliveryThreadID, 0); } } } private void EnsureOutsideDelivery(string operation) { - if (Volatile.Read(ref m_deliveryThreadId) == Environment.CurrentManagedThreadId) + if (Volatile.Read(ref m_deliveryThreadID) == Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"A log delivery callback cannot {operation} its own router."); + } } private void Enqueue(WorkItem item) { m_queue.Enqueue(item); if (m_worker is not null) + { m_signal.Release(); + } } private void DrainQueue() @@ -387,7 +423,9 @@ private void DrainQueue() for (int index = 0; index < sinks.Length; index++) { if (quarantined?.Contains(sinks[index]) == true) + { continue; + } try { sinks[index].Receive(item.entry); @@ -413,8 +451,7 @@ Exception exception Action? handlers = sinkFailed; if (handlers is null) { - ReportFailureToConsole( - $"Log sink '{sink.GetType().FullName}' failed and was quarantined: {exception}"); + ReportFailureToConsole($"Log sink '{sink.GetType().FullName}' failed and was quarantined: {exception}"); return; } foreach (Delegate handler in handlers.GetInvocationList()) @@ -426,7 +463,8 @@ Exception exception catch (Exception observerFailure) { ReportFailureToConsole( - $"Log sink failure observer '{handler.Method.DeclaringType?.FullName}' failed: {observerFailure}"); + $"Log sink failure observer '{handler.Method.DeclaringType?.FullName}' failed: {observerFailure}" + ); } } } @@ -451,5 +489,4 @@ private readonly record struct WorkItem( internal static WorkItem ForBarrier(ManualResetEventSlim completion) => new(default, completion); } - } diff --git a/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs b/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs index 9862b2f02..f9f8b1496 100644 --- a/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs +++ b/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Logging; @@ -9,30 +9,31 @@ namespace Inno.Core.Logging; /// public static class LogSessionContext { - - private static readonly ExecutionSlot S_CURRENT = new("sessionId"); + private static readonly ExecutionSlot CURRENT = new("sessionId"); /// /// Gets the runtime session associated with the current asynchronous execution flow. /// - public static LogSessionId current => S_CURRENT.TryGet(out LogSessionId session) ? session : LogSessionId.none; + public static LogSessionID current => CURRENT.TryGet(out LogSessionID session) ? session : LogSessionID.none; /// /// Enters a nested execution scope whose emitted logs belong to the supplied runtime session. /// - /// + /// /// The non-empty identifier of the runtime session receiving execution. /// /// /// A scope that restores the previous session when disposed in reverse creation order. /// /// - /// Thrown when does not identify a runtime session. + /// Thrown when does not identify a runtime session. /// - public static IDisposable Enter(LogSessionId sessionId) + public static IDisposable Enter(LogSessionID sessionID) { - if (!sessionId.isAssigned) - throw new ArgumentException("A runtime log session identifier is required.", nameof(sessionId)); - return S_CURRENT.Enter(sessionId); + if (!sessionID.isAssigned) + { + throw new ArgumentException("A runtime log session identifier is required.", nameof(sessionID)); + } + return CURRENT.Enter(sessionID); } } diff --git a/src/foundation/core/Inno.Core.Logging/LogSessionId.cs b/src/foundation/core/Inno.Core.Logging/LogSessionID.cs similarity index 84% rename from src/foundation/core/Inno.Core.Logging/LogSessionId.cs rename to src/foundation/core/Inno.Core.Logging/LogSessionID.cs index 182c9e439..373e31823 100644 --- a/src/foundation/core/Inno.Core.Logging/LogSessionId.cs +++ b/src/foundation/core/Inno.Core.Logging/LogSessionID.cs @@ -5,11 +5,11 @@ namespace Inno.Core.Logging; /// /// Identifies the isolated runtime session that produced a log entry. /// -public readonly record struct LogSessionId +public readonly record struct LogSessionID { private readonly Guid m_value; - private LogSessionId(Guid value) + private LogSessionID(Guid value) { m_value = value; } @@ -17,7 +17,7 @@ private LogSessionId(Guid value) /// /// Gets an identifier that represents process-level work outside an isolated runtime session. /// - public static LogSessionId none => default; + public static LogSessionID none => default; /// /// Gets whether this identifier names an isolated runtime session. @@ -25,18 +25,18 @@ private LogSessionId(Guid value) public bool isAssigned => m_value != Guid.Empty; /// - /// Creates a unique identifier for a new isolated runtime session. + /// Returns the stable textual representation used by diagnostics and persisted logs. /// /// - /// A newly allocated non-empty session identifier. + /// The lowercase hexadecimal identifier, or an empty string for process-level work. /// - public static LogSessionId Create() => new(Guid.NewGuid()); + public override string ToString() => m_value == Guid.Empty ? string.Empty : m_value.ToString("N"); /// - /// Returns the stable textual representation used by diagnostics and persisted logs. + /// Creates a unique identifier for a new isolated runtime session. /// /// - /// The lowercase hexadecimal identifier, or an empty string for process-level work. + /// A newly allocated non-empty session identifier. /// - public override string ToString() => m_value == Guid.Empty ? string.Empty : m_value.ToString("N"); + public static LogSessionID Create() => new(Guid.NewGuid()); } diff --git a/src/foundation/core/Inno.Core.Logging/Logger.cs b/src/foundation/core/Inno.Core.Logging/Logger.cs index 7ae0906c8..fd42e895b 100644 --- a/src/foundation/core/Inno.Core.Logging/Logger.cs +++ b/src/foundation/core/Inno.Core.Logging/Logger.cs @@ -42,18 +42,18 @@ string category /// /// Optional composite-format arguments. /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown after the owning router has been disposed. - /// /// /// Source file supplied by the caller information attribute. /// /// /// Source line supplied by the caller information attribute. /// + /// + /// Thrown when is empty. + /// + /// + /// Thrown after the owning router has been disposed. + /// public void Write( LogLevel level, string message, @@ -63,19 +63,24 @@ public void Write( ) { ArgumentException.ThrowIfNullOrWhiteSpace(message); if (!m_router.IsEnabled(level)) + { return; + } string rendered = arguments is null || arguments.Count == 0 - ? message - : string.Format(message, arguments.ToArray()); - m_router.Dispatch(new LogEntry( - level, - m_domain, - m_scope, - m_category, - rendered, - string.IsNullOrWhiteSpace(filePath) ? "Unknown" : Path.GetFullPath(filePath), - lineNumber, - new StackTrace(1, true).ToString(), - LogSessionContext.current)); + ? message + : string.Format(message, arguments.ToArray()); + m_router.Dispatch( + new LogEntry( + level, + m_domain, + m_scope, + m_category, + rendered, + string.IsNullOrWhiteSpace(filePath) ? "Unknown" : Path.GetFullPath(filePath), + lineNumber, + new StackTrace(1, true).ToString(), + LogSessionContext.current + ) + ); } } diff --git a/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs index 951761f51..fbd4b457e 100644 --- a/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Core.Logging; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Logging", - "Inno.Core.Logging", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Logging", "Inno.Core.Logging", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Log), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(LogSessionId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(LogSessionID), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Mathematics/Color.cs b/src/foundation/core/Inno.Core.Mathematics/Color.cs index 0b39f96a4..9a71bdd3e 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Color.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Color.cs @@ -12,18 +12,106 @@ namespace Inno.Core.Mathematics; /// public struct Color : IEquatable { + /// + /// The transparent value used as part of this type's public representation. + /// + public static readonly Color TRANSPARENT = new(0, 0, 0, 0); + + /// + /// The white value used as part of this type's public representation. + /// + public static readonly Color WHITE = new(1, 1, 1, 1); + + /// + /// The black value used as part of this type's public representation. + /// + public static readonly Color BLACK = new(0, 0, 0, 1); + + /// + /// The red value used as part of this type's public representation. + /// + public static readonly Color RED = FromBytes(255, 0, 0); + + /// + /// The green value used as part of this type's public representation. + /// + public static readonly Color GREEN = FromBytes(0, 255, 0); + + /// + /// The blue value used as part of this type's public representation. + /// + public static readonly Color BLUE = FromBytes(0, 0, 255); + + /// + /// The yellow value used as part of this type's public representation. + /// + public static readonly Color YELLOW = FromBytes(255, 255, 0); + + /// + /// The magenta value used as part of this type's public representation. + /// + public static readonly Color MAGENTA = FromBytes(255, 0, 255); + + /// + /// The cyan value used as part of this type's public representation. + /// + public static readonly Color CYAN = FromBytes(0, 255, 255); + + /// + /// The gray value used as part of this type's public representation. + /// + public static readonly Color GRAY = FromBytes(128, 128, 128); + + /// + /// The lightgray value used as part of this type's public representation. + /// + public static readonly Color LIGHTGRAY = FromBytes(211, 211, 211); + + /// + /// The darkgray value used as part of this type's public representation. + /// + public static readonly Color DARKGRAY = FromBytes(64, 64, 64); + + /// + /// The orange value used as part of this type's public representation. + /// + public static readonly Color ORANGE = FromBytes(255, 165, 0); + + /// + /// The pink value used as part of this type's public representation. + /// + public static readonly Color PINK = FromBytes(255, 192, 203); + + /// + /// The purple value used as part of this type's public representation. + /// + public static readonly Color PURPLE = FromBytes(128, 0, 128); + + /// + /// The brown value used as part of this type's public representation. + /// + public static readonly Color BROWN = FromBytes(139, 69, 19); + + /// + /// The cornflowerblue value used as part of this type's public representation. + /// + public static readonly Color CORNFLOWERBLUE = FromBytes(100, 149, 237); + /// /// The red color component. /// public float r; + /// /// The green color component. /// public float g; + /// /// The blue color component. /// public float b; + /// /// The alpha color component. /// @@ -50,55 +138,26 @@ public Color( float b, float a = 1f ) { - this.r = Math.Clamp(r, 0.0f, 1.0f); - this.g = Math.Clamp(g, 0.0f, 1.0f); - this.b = Math.Clamp(b, 0.0f, 1.0f); - this.a = Math.Clamp(a, 0.0f, 1.0f); + this.r = Math.Clamp(r, 0f, 1f); + this.g = Math.Clamp(g, 0f, 1f); + this.b = Math.Clamp(b, 0f, 1f); + this.a = Math.Clamp(a, 0f, 1f); } - /// - /// Creates a normalized color from byte channel values. - /// - /// - /// The red byte channel. - /// - /// - /// The green byte channel. - /// - /// - /// The blue byte channel. - /// - /// - /// The alpha byte channel; 255 is opaque. - /// - /// - /// A color with each byte channel divided by 255. - /// - public static Color FromBytes( - byte r, - byte g, - byte b, - byte a = 255 - ) { - return new Color(r / 255f, g / 255f, b / 255f, a / 255f); - } - /// /// Converts normalized color channels to bytes by multiplying by 255 and truncating. /// /// /// Red, green, blue and alpha bytes. Inputs must already be finite and in [0, 1]; conversion does not clamp field writes. /// - public (byte R, byte G, byte B, byte A) ToBytes() - { - return ( - (byte)(r * 255), - (byte)(g * 255), - (byte)(b * 255), - (byte)(a * 255) - ); - } - + public (byte r, byte g, byte b, byte a) ToBytes() + => ( + (byte)(r * 255), + (byte)(g * 255), + (byte)(b * 255), + (byte)(a * 255) + ); + /// /// Packs normalized channels into the existing unsigned 0xAABBGGRR representation. /// @@ -118,6 +177,7 @@ public uint ToUInt32ARGB() return (uint)((alpha << 24) | (blue << 16) | (green << 8) | red); } + /// /// Formats this value as a human-readable component list. /// @@ -125,78 +185,63 @@ public uint ToUInt32ARGB() /// The validated text representation owned by the caller. /// - public override string ToString() => $"Color({r:F2}, {g:F2}, {b:F2}, {a:F2})"; - - /// - /// The transparent value used as part of this type's public representation. - /// - public static readonly Color TRANSPARENT = new(0, 0, 0, 0); - /// - /// The white value used as part of this type's public representation. - /// - public static readonly Color WHITE = new(1, 1, 1, 1); - /// - /// The black value used as part of this type's public representation. - /// - public static readonly Color BLACK = new(0, 0, 0, 1); - /// - /// The red value used as part of this type's public representation. - /// - public static readonly Color RED = FromBytes(255, 0, 0); - /// - /// The green value used as part of this type's public representation. - /// - public static readonly Color GREEN = FromBytes(0, 255, 0); - /// - /// The blue value used as part of this type's public representation. - /// - public static readonly Color BLUE = FromBytes(0, 0, 255); - /// - /// The yellow value used as part of this type's public representation. - /// - public static readonly Color YELLOW = FromBytes(255, 255, 0); - /// - /// The magenta value used as part of this type's public representation. - /// - public static readonly Color MAGENTA = FromBytes(255, 0, 255); - /// - /// The cyan value used as part of this type's public representation. - /// - public static readonly Color CYAN = FromBytes(0, 255, 255); - /// - /// The gray value used as part of this type's public representation. - /// - public static readonly Color GRAY = FromBytes(128, 128, 128); - /// - /// The lightgray value used as part of this type's public representation. - /// - public static readonly Color LIGHTGRAY = FromBytes(211, 211, 211); - /// - /// The darkgray value used as part of this type's public representation. - /// - public static readonly Color DARKGRAY = FromBytes(64, 64, 64); - /// - /// The orange value used as part of this type's public representation. - /// - public static readonly Color ORANGE = FromBytes(255, 165, 0); + /// - /// The pink value used as part of this type's public representation. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Color PINK = FromBytes(255, 192, 203); + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Color other && Equals(other); + /// - /// The purple value used as part of this type's public representation. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Color PURPLE = FromBytes(128, 0, 128); + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Color other) => this == other; + /// - /// The brown value used as part of this type's public representation. + /// Computes a hash code consistent with the implemented equality contract. /// - public static readonly Color BROWN = FromBytes(139, 69, 19); + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(r, g, b, a); + /// - /// The cornflowerblue value used as part of this type's public representation. + /// Creates a normalized color from byte channel values. /// - public static readonly Color CORNFLOWERBLUE = FromBytes(100, 149, 237); - + /// + /// The red byte channel. + /// + /// + /// The green byte channel. + /// + /// + /// The blue byte channel. + /// + /// + /// The alpha byte channel; 255 is opaque. + /// + /// + /// A color with each byte channel divided by 255. + /// + public static Color FromBytes( + byte r, + byte g, + byte b, + byte a = 255 + ) => new Color(r / 255f, g / 255f, b / 255f, a / 255f); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -212,14 +257,7 @@ public uint ToUInt32ARGB() public static Color operator *( Color c, float factor - ) { - return new Color( - c.r * factor, - c.g * factor, - c.b * factor, - c.a * factor - ); - } + ) => new Color(c.r * factor, c.g * factor, c.b * factor, c.a * factor); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -237,12 +275,10 @@ float factor public static bool operator ==( Color a, Color b - ) { - return MathHelper.AlmostEquals(a.r, b.r) && - MathHelper.AlmostEquals(a.g, b.g) && - MathHelper.AlmostEquals(a.b, b.b) && - MathHelper.AlmostEquals(a.a, b.a); - } + ) => MathHelper.AlmostEquals(a.r, b.r) + && MathHelper.AlmostEquals(a.g, b.g) + && MathHelper.AlmostEquals(a.b, b.b) + && MathHelper.AlmostEquals(a.a, b.a); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -261,34 +297,4 @@ Color b Color a, Color b ) => !(a == b); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Color other && Equals(other); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Color other) => this == other; - - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(r, g, b, a); } diff --git a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs index b56daccbe..78138760a 100644 --- a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs +++ b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Runtime.CompilerServices; @@ -14,91 +12,89 @@ public static class MathHelper /// The c tolerance value used as part of this type's public representation. /// public const float C_TOLERANCE = 1e-6f; - - /// - /// Determines whether two floating-point numbers are approximately equal, - /// using a relative tolerance based on the magnitude of the numbers. - /// This is useful for comparing floats where rounding errors may occur. - /// - /// - /// The first float value to compare. - /// - /// - /// The second float value to compare. - /// - /// - /// The relative tolerance allowed between and . - /// Default is 1e-6. The comparison checks if the difference is within - /// relTolerance * max(|a|, |b|). - /// - /// - /// true if the absolute difference between and - /// is less than or equal to the relative tolerance multiplied by the larger magnitude of the two values; - /// otherwise, false. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AlmostEquals( - float a, - float b, - float relTolerance = C_TOLERANCE - ) { - return MathF.Abs(a - b) <= relTolerance * MathF.Max(MathF.Abs(a), MathF.Abs(b)); - } - - /// - /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. - /// - /// - /// The coordinate on one axis of vertex 1 of the defining triangle. - /// - /// - /// The coordinate on the same axis of vertex 2 of the defining triangle. - /// - /// - /// The coordinate on the same axis of vertex 3 of the defining triangle. - /// - /// - /// The normalized barycentric (areal) coordinate b2, equal to the weighting factor for vertex 2, the coordinate of which is specified in value2. - /// - /// - /// The normalized barycentric (areal) coordinate b3, equal to the weighting factor for vertex 3, the coordinate of which is specified in value3. - /// - /// - /// Cartesian coordinate of the specified point with respect to the axis being used. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Barycentric( - float value1, - float value2, - float value3, - float amount1, - float amount2 - ) { - return (float) ((double) value1 + ((double) value2 - (double) value1) * (double) amount1 + ((double) value3 - (double) value1) * (double) amount2); - } - /// - /// Performs a Catmull-Rom interpolation using the specified positions. - /// - /// - /// The first position in the interpolation. - /// - /// - /// The second position in the interpolation. - /// - /// - /// The third position in the interpolation. - /// - /// - /// The fourth position in the interpolation. - /// - /// - /// Weighting factor. - /// - /// - /// A position that is the result of the Catmull-Rom interpolation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] + /// + /// Determines whether two floating-point numbers are approximately equal, + /// using a relative tolerance based on the magnitude of the numbers. + /// This is useful for comparing floats where rounding errors may occur. + /// + /// + /// The first float value to compare. + /// + /// + /// The second float value to compare. + /// + /// + /// The relative tolerance allowed between and . + /// Default is 1e-6. The comparison checks if the difference is within + /// relTolerance * max(|a|, |b|). + /// + /// + /// true if the absolute difference between and + /// is less than or equal to the relative tolerance multiplied by the larger magnitude of the two values; + /// otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AlmostEquals( + float a, + float b, + float relTolerance = C_TOLERANCE + ) => MathF.Abs(a - b) <= relTolerance * MathF.Max(MathF.Abs(a), MathF.Abs(b)); + + /// + /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. + /// + /// + /// The coordinate on one axis of vertex 1 of the defining triangle. + /// + /// + /// The coordinate on the same axis of vertex 2 of the defining triangle. + /// + /// + /// The coordinate on the same axis of vertex 3 of the defining triangle. + /// + /// + /// The normalized barycentric (areal) coordinate b2, equal to the weighting factor for vertex 2, the coordinate of which is specified in value2. + /// + /// + /// The normalized barycentric (areal) coordinate b3, equal to the weighting factor for vertex 3, the coordinate of which is specified in value3. + /// + /// + /// Cartesian coordinate of the specified point with respect to the axis being used. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Barycentric( + float value1, + float value2, + float value3, + float amount1, + float amount2 + ) => (float)((double)value1 + + ((double)value2 - (double)value1) * (double)amount1 + + ((double)value3 - (double)value1) * (double)amount2); + + /// + /// Performs a Catmull-Rom interpolation using the specified positions. + /// + /// + /// The first position in the interpolation. + /// + /// + /// The second position in the interpolation. + /// + /// + /// The third position in the interpolation. + /// + /// + /// The fourth position in the interpolation. + /// + /// + /// Weighting factor. + /// + /// + /// A position that is the result of the Catmull-Rom interpolation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float CatmullRom( float value1, float value2, @@ -108,7 +104,11 @@ float amount ) { double num1 = (double) amount * (double) amount; double num2 = num1 * (double) amount; - return (float) (0.5 * (2.0 * (double) value2 + ((double) value3 - (double) value1) * (double) amount + (2.0 * (double) value1 - 5.0 * (double) value2 + 4.0 * (double) value3 - (double) value4) * num1 + (3.0 * (double) value2 - (double) value1 - 3.0 * (double) value3 + (double) value4) * num2)); + return (float) (0.5 + * (2.0 * (double) value2 + + ((double) value3 - (double) value1) * (double) amount + + (2.0 * (double) value1 - 5.0 * (double) value2 + 4.0 * (double) value3 - (double) value4) * num1 + + (3.0 * (double) value2 - (double) value1 - 3.0 * (double) value3 + (double) value4) * num2)); } /// @@ -117,12 +117,12 @@ float amount /// /// Source value. /// - /// - /// Distance between the two values. - /// /// /// The value2 consumed by distance; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// Distance between the two values. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance( float value1, @@ -165,122 +165,125 @@ float amount double num5 = (double) amount; double num6 = num5 * num5 * num5; double num7 = num5 * num5; - return (double) amount != 0.0 ? ((double) amount != 1.0 ? (float) ((2.0 * num1 - 2.0 * num2 + num4 + num3) * num6 + (3.0 * num2 - 3.0 * num1 - 2.0 * num3 - num4) * num7 + num3 * num5 + num1) : value2) : value1; + return (double) amount != 0.0 + ? ((double) amount != 1.0 + ? (float) ((2.0 * num1 - 2.0 * num2 + num4 + num3) * num6 + + (3.0 * num2 - 3.0 * num1 - 2.0 * num3 - num4) * num7 + + num3 * num5 + + num1) + : value2) + : value1; } - /// - /// Linearly interpolates between two values. - /// - /// - /// Source value. - /// - /// - /// Destination value. - /// - /// - /// Value between 0 and 1 indicating the weight of value2. - /// - /// - /// Interpolated value. - /// - /// This method performs the linear interpolation based on the following formula: - /// value1 + (value2 - value1) * amount - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// See for a less efficient version with more precision around edge cases. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Lerp( - float value1, - float value2, - float amount - ) { - return value1 + (value2 - value1) * amount; - } + /// + /// Linearly interpolates between two values. + /// + /// + /// Source value. + /// + /// + /// Destination value. + /// + /// + /// Value between 0 and 1 indicating the weight of value2. + /// + /// + /// Interpolated value. + /// + /// + /// This method performs the linear interpolation based on the following formula: + /// value1 + (value2 - value1) * amount + /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. + /// See for a less efficient version with more precision around edge cases. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Lerp( + float value1, + float value2, + float amount + ) => value1 + (value2 - value1) * amount; - /// - /// Linearly interpolates between two values without clamping the amount. - /// - /// - /// The value1 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The value2 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The amount consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float LerpUnclamped( - float value1, - float value2, - float amount - ) { - return value1 + (value2 - value1) * amount; - } + /// + /// Linearly interpolates between two values without clamping the amount. + /// + /// + /// The value1 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The value2 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The amount consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float LerpUnclamped( + float value1, + float value2, + float amount + ) => value1 + (value2 - value1) * amount; - /// - /// Linearly interpolates between two values. - /// This method is a less efficient, more precise version of . - /// See remarks for more info. - /// - /// - /// Source value. - /// - /// - /// Destination value. - /// - /// - /// Value between 0 and 1 indicating the weight of value2. - /// - /// - /// Interpolated value. - /// - /// This method performs the linear interpolation based on the following formula: - /// ((1 - amount) * value1) + (value2 * amount). - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// This method does not have the floating point precision issue that has. - /// i.e. If there is a big gap between value1 and value2 in magnitude (e.g. value1=10000000000000000, value2=1), - /// right at the edge of the interpolation range (amount=1), will return 0 (whereas it should return 1). - /// This also holds for value1=10^17, value2=10; value1=10^18,value2=10^2... so on. - /// For an in depth explanation of the issue, see below references: - /// Relevant Wikipedia Article: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support - /// Relevant StackOverflow Answer: http://stackoverflow.com/questions/4353525/floating-point-linear-interpolation#answer-23716956 - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float LerpPrecise( - float value1, - float value2, - float amount - ) { - return (float) ((1.0 - (double) amount) * (double) value1 + (double) value2 * (double) amount); - } + /// + /// Linearly interpolates between two values. + /// This method is a less efficient, more precise version of . + /// See remarks for more info. + /// + /// + /// Source value. + /// + /// + /// Destination value. + /// + /// + /// Value between 0 and 1 indicating the weight of value2. + /// + /// + /// Interpolated value. + /// + /// + /// This method performs the linear interpolation based on the following formula: + /// ((1 - amount) * value1) + (value2 * amount). + /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. + /// This method does not have the floating point precision issue that has. + /// i.e. If there is a big gap between value1 and value2 in magnitude (e.g. value1=10000000000000000, value2=1), + /// right at the edge of the interpolation range (amount=1), will return 0 (whereas it should return 1). + /// This also holds for value1=10^17, value2=10; value1=10^18,value2=10^2... so on. + /// For an in depth explanation of the issue, see below references: + /// Relevant Wikipedia Article: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support + /// Relevant StackOverflow Answer: http://stackoverflow.com/questions/4353525/floating-point-linear-interpolation#answer-23716956 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float LerpPrecise( + float value1, + float value2, + float amount + ) => (float)((1.0 - (double)amount) * (double)value1 + (double)value2 * (double)amount); - /// - /// Interpolates between two values using a cubic equation. - /// - /// - /// Source value. - /// - /// - /// Source value. - /// - /// - /// Weighting value. - /// - /// - /// Interpolated value. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] + /// + /// Interpolates between two values using a cubic equation. + /// + /// + /// Source value. + /// + /// + /// Source value. + /// + /// + /// Weighting value. + /// + /// + /// Interpolated value. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SmoothStep( float value1, float value2, float amount ) { - float amount1 = Math.Clamp(amount, 0.0f, 1f); - return Hermite(value1, 0.0f, value2, 0.0f, amount1); + float amount1 = Math.Clamp(amount, 0f, 1f); + return Hermite(value1, 0f, value2, 0f, amount1); } /// @@ -303,6 +306,9 @@ float amount /// /// Converts degrees to radians. /// + /// + /// The degrees consumed by to radians; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// The angle in radians. /// @@ -311,9 +317,6 @@ float amount /// though it returns single float /// Factor = pi / 180 /// - /// - /// The degrees consumed by to radians; ownership remains with the caller unless explicitly stated otherwise. - /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ToRadians(float degrees) => degrees * ((float) MathF.PI / 180f); @@ -326,12 +329,12 @@ float amount /// /// The min consumed by clamp; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The max consumed by clamp; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp( float value, @@ -342,24 +345,24 @@ float max /// /// Clamps a value to the inclusive range [0, 1]. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Saturate(float value) => Math.Clamp(value, 0f, 1f); /// /// Returns true if the value is finite (not NaN or infinity). /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float value) => !float.IsNaN(value) && !float.IsInfinity(value); @@ -376,22 +379,26 @@ float max public static float WrapAngle(float angle) { if ((double) angle > -3.1415927410125732 && (double) angle <= 3.1415927410125732) + { return angle; + } angle %= 6.2831855f; if ((double) angle <= -3.1415927410125732) + { return angle + 6.2831855f; + } return (double) angle > 3.1415927410125732 ? angle - 6.2831855f : angle; } /// /// Determines if value is powered by two. /// - /// - /// true if value is powered by two; otherwise false. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// if value is powered by two; otherwise . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPowerOfTwo(int value) => value > 0 && (value & value - 1) == 0; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs index 8a339f870..b1f98aa48 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs @@ -1,8 +1,9 @@ using System; -using System.Runtime.Serialization; +using System.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; namespace Inno.Core.Mathematics; @@ -26,79 +27,101 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Matrix : IEquatable { - #region Data (Row-major) - /// /// Row 1, Column 1. /// - [DataMember] public float m11; + [DataMember] + public float m11; + /// /// Row 1, Column 2. /// - [DataMember] public float m12; + [DataMember] + public float m12; + /// /// Row 1, Column 3. /// - [DataMember] public float m13; + [DataMember] + public float m13; + /// /// Row 1, Column 4. /// - [DataMember] public float m14; + [DataMember] + public float m14; /// /// Row 2, Column 1. /// - [DataMember] public float m21; + [DataMember] + public float m21; + /// /// Row 2, Column 2. /// - [DataMember] public float m22; + [DataMember] + public float m22; + /// /// Row 2, Column 3. /// - [DataMember] public float m23; + [DataMember] + public float m23; + /// /// Row 2, Column 4. /// - [DataMember] public float m24; + [DataMember] + public float m24; /// /// Row 3, Column 1. /// - [DataMember] public float m31; + [DataMember] + public float m31; + /// /// Row 3, Column 2. /// - [DataMember] public float m32; + [DataMember] + public float m32; + /// /// Row 3, Column 3. /// - [DataMember] public float m33; + [DataMember] + public float m33; + /// /// Row 3, Column 4. /// - [DataMember] public float m34; + [DataMember] + public float m34; /// /// Row 4, Column 1 (translation X component for affine transforms). /// - [DataMember] public float m41; + [DataMember] + public float m41; + /// /// Row 4, Column 2 (translation Y component for affine transforms). /// - [DataMember] public float m42; + [DataMember] + public float m42; + /// /// Row 4, Column 3 (translation Z component for affine transforms). /// - [DataMember] public float m43; + [DataMember] + public float m43; + /// /// Row 4, Column 4. /// - [DataMember] public float m44; - - #endregion - - #region Construction + [DataMember] + public float m44; /// /// Initializes a 4x4 matrix with explicit row-major elements. @@ -178,15 +201,116 @@ float m44 /// /// Gets the identity matrix. /// - public static Matrix identity => new Matrix( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + public static Matrix identity => new Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - #endregion + /// + /// Copies matrix elements into an array in column-major order. + /// Useful for APIs like bgfx that expect column-major float[16]. + /// + /// + /// Destination array. + /// + /// + /// Start index in the destination array. + /// + public void CopyToColumnMajor( + float[] destination, + int startIndex = 0 + ) { + ArgumentNullException.ThrowIfNull(destination); - #region Common Factories + if (startIndex < 0 || destination.Length - startIndex < 16) + { + throw new ArgumentOutOfRangeException(nameof(startIndex)); + } + + destination[startIndex + 0] = m11; + destination[startIndex + 1] = m21; + destination[startIndex + 2] = m31; + destination[startIndex + 3] = m41; + destination[startIndex + 4] = m12; + destination[startIndex + 5] = m22; + destination[startIndex + 6] = m32; + destination[startIndex + 7] = m42; + destination[startIndex + 8] = m13; + destination[startIndex + 9] = m23; + destination[startIndex + 10] = m33; + destination[startIndex + 11] = m43; + destination[startIndex + 12] = m14; + destination[startIndex + 13] = m24; + destination[startIndex + 14] = m34; + destination[startIndex + 15] = m44; + } + + /// + /// Returns a new array containing matrix elements in column-major order. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public float[] ToColumnMajorArray() + { + var data = new float[16]; + CopyToColumnMajor(data, 0); + return data; + } + + /// + /// Determines whether this instance is equal to another matrix. + /// + /// + /// Other matrix. + /// + /// + /// if equal. + /// + public bool Equals(Matrix other) => this == other; + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => obj is Matrix other && Equals(other); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() + => m11.GetHashCode() + m12.GetHashCode() + m13.GetHashCode() + m14.GetHashCode() + + m21.GetHashCode() + m22.GetHashCode() + m23.GetHashCode() + m24.GetHashCode() + + m31.GetHashCode() + m32.GetHashCode() + m33.GetHashCode() + m34.GetHashCode() + + m41.GetHashCode() + m42.GetHashCode() + m43.GetHashCode() + m44.GetHashCode(); + + /// + /// Returns a multi-line string representation of the matrix in row-major layout. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() + => $"[{m11}, {m12}, {m13}, {m14}]\n" + + $"[{m21}, {m22}, {m23}, {m24}]\n" + + $"[{m31}, {m32}, {m33}, {m34}]\n" + + $"[{m41}, {m42}, {m43}, {m44}]"; + + /// + /// Creates a translation matrix. + /// + /// + /// The concrete value read or transformed by this operation. + /// + /// + /// A translation matrix. + /// + public static Matrix CreateTranslation(Vector3 v) => CreateTranslation(v.x, v.y, v.z); /// /// Creates a translation matrix. @@ -207,35 +331,29 @@ public static Matrix CreateTranslation( float x, float y, float z - ) { - return new Matrix( - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1); - } + ) => new Matrix(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); /// - /// Creates a translation matrix. + /// Creates a uniform scale matrix. /// + /// + /// The scale consumed by create scale; ownership remains with the caller unless explicitly stated otherwise. + /// /// - /// A translation matrix. + /// A scale matrix. /// - /// - /// The concrete value read or transformed by this operation. - /// - public static Matrix CreateTranslation(Vector3 v) => CreateTranslation(v.x, v.y, v.z); + public static Matrix CreateScale(float scale) => CreateScale(scale, scale, scale); /// - /// Creates a uniform scale matrix. + /// Creates a non-uniform scale matrix. /// + /// + /// The concrete value read or transformed by this operation. + /// /// /// A scale matrix. /// - /// - /// The scale consumed by create scale; ownership remains with the caller unless explicitly stated otherwise. - /// - public static Matrix CreateScale(float scale) => CreateScale(scale, scale, scale); + public static Matrix CreateScale(Vector3 v) => CreateScale(v.x, v.y, v.z); /// /// Creates a non-uniform scale matrix. @@ -256,24 +374,7 @@ public static Matrix CreateScale( float x, float y, float z - ) { - return new Matrix( - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1); - } - - /// - /// Creates a non-uniform scale matrix. - /// - /// - /// A scale matrix. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public static Matrix CreateScale(Vector3 v) => CreateScale(v.x, v.y, v.z); + ) => new Matrix(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); /// /// Creates a rotation matrix around the X axis (radians). @@ -288,11 +389,7 @@ public static Matrix CreateRotationX(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - 1, 0, 0, 0, - 0, c, -s, 0, - 0, s, c, 0, - 0, 0, 0, 1); + return new Matrix(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); } /// @@ -308,11 +405,7 @@ public static Matrix CreateRotationY(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - c, 0, s, 0, - 0, 1, 0, 0, - -s, 0, c, 0, - 0, 0, 0, 1); + return new Matrix(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); } /// @@ -328,11 +421,7 @@ public static Matrix CreateRotationZ(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - c, -s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + return new Matrix(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } /// @@ -346,21 +435,36 @@ public static Matrix CreateRotationZ(float radians) /// public static Matrix CreateFromQuaternion(Quaternion q) { - float xx = q.x * q.x, yy = q.y * q.y, zz = q.z * q.z; - float xy = q.x * q.y, xz = q.x * q.z, yz = q.y * q.z; - float wx = q.w * q.x, wy = q.w * q.y, wz = q.w * q.z; + float xx = q.x * q.x; + float yy = q.y * q.y; + float zz = q.z * q.z; + float xy = q.x * q.y; + float xz = q.x * q.z; + float yz = q.y * q.z; + float wx = q.w * q.x; + float wy = q.w * q.y; + float wz = q.w * q.z; return new Matrix( - 1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0, - 2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0, - 2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1); + 1 - 2 * (yy + zz), + 2 * (xy - wz), + 2 * (xz + wy), + 0, + 2 * (xy + wz), + 1 - 2 * (xx + zz), + 2 * (yz - wx), + 0, + 2 * (xz - wy), + 2 * (yz + wx), + 1 - 2 * (xx + yy), + 0, + 0, + 0, + 0, + 1 + ); } - #endregion - - #region Projection - /// /// Creates a left-handed, perspective projection matrix ( depth range 0..1). /// @@ -388,11 +492,7 @@ float far float f = 1f / MathF.Tan(fov * 0.5f); float nf = 1f / (far - near); - return new Matrix( - f / aspect, 0, 0, 0, - 0, f, 0, 0, - 0, 0, far * nf, -near * far * nf, - 0, 0, 1, 0); + return new Matrix(f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far * nf, -near * far * nf, 0, 0, 1, 0); } /// @@ -422,11 +522,7 @@ float far float f = 1f / MathF.Tan(fov * 0.5f); float nf = 1f / (near - far); - return new Matrix( - f / aspect, 0, 0, 0, - 0, f, 0, 0, - 0, 0, far * nf, near * far * nf, - 0, 0, -1, 0); + return new Matrix(f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far * nf, near * far * nf, 0, 0, -1, 0); } /// @@ -452,15 +548,7 @@ public static Matrix CreateOrthographic( float height, float near, float far - ) { - return CreateOrthographicOffCenter( - -width * 0.5f, - width * 0.5f, - -height * 0.5f, - height * 0.5f, - near, - far); - } + ) => CreateOrthographicOffCenter(-width * 0.5f, width * 0.5f, -height * 0.5f, height * 0.5f, near, far); /// /// Creates an off-center orthographic projection matrix (depth range 0..1). @@ -501,18 +589,9 @@ float far float m24 = -(top + bottom) / (top - bottom); float m34 = -near / (far - near); - return new Matrix( - m00, 0, 0, m14, - 0, m11, 0, m24, - 0, 0, m22, m34, - 0, 0, 0, 1 - ); + return new Matrix(m00, 0, 0, m14, 0, m11, 0, m24, 0, 0, m22, m34, 0, 0, 0, 1); } - #endregion - - #region View - /// /// Creates a left-handed view matrix that looks from to . /// @@ -534,15 +613,31 @@ public static Matrix CreateLookAt( Vector3 up ) { // LH: forward points from eye to target - Vector3 z = (target - eye).normalized; // forward (+Z) - Vector3 x = Vector3.Cross(up, z).normalized; // right - Vector3 y = Vector3.Cross(z, x); // up + // forward (+Z) + Vector3 z = (target - eye).normalized; + // right + Vector3 x = Vector3.Cross(up, z).normalized; + // up + Vector3 y = Vector3.Cross(z, x); return new Matrix( - x.x, x.y, x.z, -Vector3.Dot(x, eye), - y.x, y.y, y.z, -Vector3.Dot(y, eye), - z.x, z.y, z.z, -Vector3.Dot(z, eye), - 0, 0, 0, 1); + x.x, + x.y, + x.z, + -Vector3.Dot(x, eye), + y.x, + y.y, + y.z, + -Vector3.Dot(y, eye), + z.x, + z.y, + z.z, + -Vector3.Dot(z, eye), + 0, + 0, + 0, + 1 + ); } /// @@ -566,22 +661,33 @@ public static Matrix CreateLookAtRH( Vector3 up ) { // RH: forward points from eye to target but is -Z in view space - Vector3 z = (eye - target).normalized; // forward (-Z) - Vector3 x = Vector3.Cross(up, z).normalized; // right - Vector3 y = Vector3.Cross(z, x); // up + // forward (-Z) + Vector3 z = (eye - target).normalized; + // right + Vector3 x = Vector3.Cross(up, z).normalized; + // up + Vector3 y = Vector3.Cross(z, x); return new Matrix( - x.x, x.y, x.z, -Vector3.Dot(x, eye), - y.x, y.y, y.z, -Vector3.Dot(y, eye), - z.x, z.y, z.z, -Vector3.Dot(z, eye), - 0, 0, 0, 1); + x.x, + x.y, + x.z, + -Vector3.Dot(x, eye), + y.x, + y.y, + y.z, + -Vector3.Dot(y, eye), + z.x, + z.y, + z.z, + -Vector3.Dot(z, eye), + 0, + 0, + 0, + 1 + ); } - - #endregion - - #region Operations - /// /// Multiplies two matrices using standard matrix multiplication. /// @@ -600,15 +706,15 @@ Matrix b ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var col0 = Vector128.Create(b.m11, b.m21, b.m31, b.m41); - var col1 = Vector128.Create(b.m12, b.m22, b.m32, b.m42); - var col2 = Vector128.Create(b.m13, b.m23, b.m33, b.m43); - var col3 = Vector128.Create(b.m14, b.m24, b.m34, b.m44); + Vector128 col0 = Vector128.Create(b.m11, b.m21, b.m31, b.m41); + Vector128 col1 = Vector128.Create(b.m12, b.m22, b.m32, b.m42); + Vector128 col2 = Vector128.Create(b.m13, b.m23, b.m33, b.m43); + Vector128 col3 = Vector128.Create(b.m14, b.m24, b.m34, b.m44); - var row0 = Vector128.Create(a.m11, a.m12, a.m13, a.m14); - var row1 = Vector128.Create(a.m21, a.m22, a.m23, a.m24); - var row2 = Vector128.Create(a.m31, a.m32, a.m33, a.m34); - var row3 = Vector128.Create(a.m41, a.m42, a.m43, a.m44); + Vector128 row0 = Vector128.Create(a.m11, a.m12, a.m13, a.m14); + Vector128 row1 = Vector128.Create(a.m21, a.m22, a.m23, a.m24); + Vector128 row2 = Vector128.Create(a.m31, a.m32, a.m33, a.m34); + Vector128 row3 = Vector128.Create(a.m41, a.m42, a.m43, a.m44); return new Matrix( SimdMath.Dot4(row0, col0), @@ -667,10 +773,22 @@ Matrix b /// public static float Determinant(Matrix m) { - float a00 = m.m11, a01 = m.m12, a02 = m.m13, a03 = m.m14; - float a10 = m.m21, a11 = m.m22, a12 = m.m23, a13 = m.m24; - float a20 = m.m31, a21 = m.m32, a22 = m.m33, a23 = m.m34; - float a30 = m.m41, a31 = m.m42, a32 = m.m43, a33 = m.m44; + float a00 = m.m11; + float a01 = m.m12; + float a02 = m.m13; + float a03 = m.m14; + float a10 = m.m21; + float a11 = m.m22; + float a12 = m.m23; + float a13 = m.m24; + float a20 = m.m31; + float a21 = m.m32; + float a22 = m.m33; + float a23 = m.m34; + float a30 = m.m41; + float a31 = m.m42; + float a32 = m.m43; + float a33 = m.m44; float b00 = a00 * a11 - a01 * a10; float b01 = a00 * a12 - a02 * a10; @@ -715,9 +833,9 @@ out Vector3 translation ) { translation = new Vector3(m.m14, m.m24, m.m34); - Vector3 col0 = new Vector3(m.m11, m.m21, m.m31); - Vector3 col1 = new Vector3(m.m12, m.m22, m.m32); - Vector3 col2 = new Vector3(m.m13, m.m23, m.m33); + var col0 = new Vector3(m.m11, m.m21, m.m31); + var col1 = new Vector3(m.m12, m.m22, m.m32); + var col2 = new Vector3(m.m13, m.m23, m.m33); float sx = col0.Length(); float sy = col1.Length(); @@ -737,10 +855,23 @@ out Vector3 translation } var rot = new Matrix( - col0.x / scale.x, col1.x / scale.y, col2.x / scale.z, 0f, - col0.y / scale.x, col1.y / scale.y, col2.y / scale.z, 0f, - col0.z / scale.x, col1.z / scale.y, col2.z / scale.z, 0f, - 0f, 0f, 0f, 1f); + col0.x / scale.x, + col1.x / scale.y, + col2.x / scale.z, + 0f, + col0.y / scale.x, + col1.y / scale.y, + col2.y / scale.z, + 0f, + col0.z / scale.x, + col1.z / scale.y, + col2.z / scale.z, + 0f, + 0f, + 0f, + 0f, + 1f + ); rotation = Quaternion.FromRotationMatrix(rot); return true; @@ -755,15 +886,7 @@ out Vector3 translation /// /// A matrix representing the 2D transform embedded in . /// - public static Matrix Extract2DTransform(Matrix m) - { - return new Matrix( - m.m11, m.m12, 0, m.m14, - m.m21, m.m22, 0, m.m24, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); - } + public static Matrix Extract2DTransform(Matrix m) => new Matrix(m.m11, m.m12, 0, m.m14, m.m21, m.m22, 0, m.m24, 0, 0, 1, 0, 0, 0, 0, 1); /// /// Returns the transpose of a matrix. @@ -775,14 +898,24 @@ public static Matrix Extract2DTransform(Matrix m) /// Transposed matrix. /// public static Matrix Transpose(Matrix a) - { - return new Matrix( - a.m11, a.m21, a.m31, a.m41, - a.m12, a.m22, a.m32, a.m42, - a.m13, a.m23, a.m33, a.m43, - a.m14, a.m24, a.m34, a.m44 + => new Matrix( + a.m11, + a.m21, + a.m31, + a.m41, + a.m12, + a.m22, + a.m32, + a.m42, + a.m13, + a.m23, + a.m33, + a.m43, + a.m14, + a.m24, + a.m34, + a.m44 ); - } /// /// Returns the inverse, or identity when the absolute determinant is below the default tolerance. @@ -795,10 +928,22 @@ public static Matrix Transpose(Matrix a) /// public static Matrix Invert(Matrix m) { - float a00 = m.m11, a01 = m.m12, a02 = m.m13, a03 = m.m14; - float a10 = m.m21, a11 = m.m22, a12 = m.m23, a13 = m.m24; - float a20 = m.m31, a21 = m.m32, a22 = m.m33, a23 = m.m34; - float a30 = m.m41, a31 = m.m42, a32 = m.m43, a33 = m.m44; + float a00 = m.m11; + float a01 = m.m12; + float a02 = m.m13; + float a03 = m.m14; + float a10 = m.m21; + float a11 = m.m22; + float a12 = m.m23; + float a13 = m.m24; + float a20 = m.m31; + float a21 = m.m32; + float a22 = m.m33; + float a23 = m.m34; + float a30 = m.m41; + float a31 = m.m42; + float a32 = m.m43; + float a33 = m.m44; float b00 = a00 * a11 - a01 * a10; float b01 = a00 * a12 - a02 * a10; @@ -815,7 +960,9 @@ public static Matrix Invert(Matrix m) float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (MathF.Abs(det) < MathHelper.C_TOLERANCE) + { return identity; + } float invDet = 1f / det; @@ -842,69 +989,6 @@ public static Matrix Invert(Matrix m) ); } - #endregion - - #region Interop - - /// - /// Copies matrix elements into an array in column-major order. - /// Useful for APIs like bgfx that expect column-major float[16]. - /// - /// - /// Destination array. - /// - /// - /// Start index in the destination array. - /// - public void CopyToColumnMajor( - float[] destination, - int startIndex = 0 - ) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (startIndex < 0 || destination.Length - startIndex < 16) - { - throw new ArgumentOutOfRangeException(nameof(startIndex)); - } - - destination[startIndex + 0] = m11; - destination[startIndex + 1] = m21; - destination[startIndex + 2] = m31; - destination[startIndex + 3] = m41; - destination[startIndex + 4] = m12; - destination[startIndex + 5] = m22; - destination[startIndex + 6] = m32; - destination[startIndex + 7] = m42; - destination[startIndex + 8] = m13; - destination[startIndex + 9] = m23; - destination[startIndex + 10] = m33; - destination[startIndex + 11] = m43; - destination[startIndex + 12] = m14; - destination[startIndex + 13] = m24; - destination[startIndex + 14] = m34; - destination[startIndex + 15] = m44; - } - - /// - /// Returns a new array containing matrix elements in column-major order. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public float[] ToColumnMajorArray() - { - var data = new float[16]; - CopyToColumnMajor(data, 0); - return data; - } - - #endregion - - #region Operators - /// /// Multiplies two matrices. /// @@ -932,30 +1016,27 @@ Matrix b /// Second matrix. /// /// - /// true if all elements are approximately equal. + /// if all elements are approximately equal. /// public static bool operator ==( Matrix matrix1, Matrix matrix2 - ) { - return - MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) && - MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) && - MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) && - MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) && - MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) && - MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) && - MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) && - MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) && - MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) && - MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) && - MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) && - MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) && - MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) && - MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) && - MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) && - MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); - } + ) => MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) + && MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) + && MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) + && MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) + && MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) + && MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) + && MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) + && MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) + && MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) + && MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) + && MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) + && MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) + && MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) + && MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) + && MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) + && MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); /// /// Tests matrices for inequality. @@ -967,7 +1048,7 @@ Matrix matrix2 /// Second matrix. /// /// - /// true if matrices are not equal. + /// if matrices are not equal. /// public static bool operator !=( Matrix a, @@ -984,15 +1065,25 @@ Matrix b /// /// The validated system.numerics.matrix4x4 that represents the completed operation. /// - public static implicit operator System.Numerics.Matrix4x4(Matrix m) - { - return new System.Numerics.Matrix4x4( - m.m11, m.m12, m.m13, m.m14, - m.m21, m.m22, m.m23, m.m24, - m.m31, m.m32, m.m33, m.m34, - m.m41, m.m42, m.m43, m.m44 + public static implicit operator Matrix4x4(Matrix m) + => new Matrix4x4( + m.m11, + m.m12, + m.m13, + m.m14, + m.m21, + m.m22, + m.m23, + m.m24, + m.m31, + m.m32, + m.m33, + m.m34, + m.m41, + m.m42, + m.m43, + m.m44 ); - } /// /// Converts from preserving element order. @@ -1004,71 +1095,24 @@ public static implicit operator System.Numerics.Matrix4x4(Matrix m) /// /// The validated matrix that represents the completed operation. /// - public static implicit operator Matrix(System.Numerics.Matrix4x4 m) - { - return new Matrix - { - m11 = m.M11, m12 = m.M12, m13 = m.M13, m14 = m.M14, - m21 = m.M21, m22 = m.M22, m23 = m.M23, m24 = m.M24, - m31 = m.M31, m32 = m.M32, m33 = m.M33, m34 = m.M34, - m41 = m.M41, m42 = m.M42, m43 = m.M43, m44 = m.M44 - }; - } - - #endregion - - #region Equality / Formatting - - /// - /// Determines whether this instance is equal to another matrix. - /// - /// - /// Other matrix. - /// - /// - /// true if equal. - /// - public bool Equals(Matrix other) => this == other; - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - /// - /// The object to compare with this instance. - /// - public override bool Equals(object? obj) => obj is Matrix other && Equals(other); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() - { - return this.m11.GetHashCode() + this.m12.GetHashCode() + this.m13.GetHashCode() + this.m14.GetHashCode() + - this.m21.GetHashCode() + this.m22.GetHashCode() + this.m23.GetHashCode() + this.m24.GetHashCode() + - this.m31.GetHashCode() + this.m32.GetHashCode() + this.m33.GetHashCode() + this.m34.GetHashCode() + - this.m41.GetHashCode() + this.m42.GetHashCode() + this.m43.GetHashCode() + this.m44.GetHashCode(); - } - - - /// - /// Returns a multi-line string representation of the matrix in row-major layout. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() + public static implicit operator Matrix(Matrix4x4 m) + => new Matrix { - return $"[{m11}, {m12}, {m13}, {m14}]\n" + - $"[{m21}, {m22}, {m23}, {m24}]\n" + - $"[{m31}, {m32}, {m33}, {m34}]\n" + - $"[{m41}, {m42}, {m43}, {m44}]"; - } - - #endregion + m11 = m.M11, + m12 = m.M12, + m13 = m.M13, + m14 = m.M14, + m21 = m.M21, + m22 = m.M22, + m23 = m.M23, + m24 = m.M24, + m31 = m.M31, + m32 = m.M32, + m33 = m.M33, + m34 = m.M34, + m41 = m.M41, + m42 = m.M42, + m43 = m.M43, + m44 = m.M44 + }; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs index cdf4ea6cf..e89a0d9a4 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Core.Mathematics; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Mathematics", - "Inno.Core.Mathematics", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Mathematics", "Inno.Core.Mathematics", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Color), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(MathHelper), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs index 149e260d1..12b1557a2 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs @@ -2,6 +2,8 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; +using NumericsQuaternion = System.Numerics.Quaternion; + namespace Inno.Core.Mathematics; /// @@ -13,19 +15,26 @@ public struct Quaternion : IEquatable /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; + /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; + /// /// The depth or third component. /// - [DataMember] public float z; + [DataMember] + public float z; + /// /// The homogeneous or fourth component. /// - [DataMember] public float w; + [DataMember] + public float w; /// /// Creates a validated quaternion instance. @@ -59,6 +68,11 @@ float w /// public static Quaternion identity => new Quaternion(0, 0, 0, 1); + /// + /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// + public Quaternion normalized => Normalize(this); + /// /// Calculates the Euclidean magnitude of this value. /// @@ -78,9 +92,129 @@ float w public float LengthSquared() => SimdMath.Dot4(x, y, z, w, x, y, z, w); /// - /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// Converts this quaternion to a rotation matrix. /// - public Quaternion normalized => Normalize(this); + /// + /// The validated matrix that represents the completed operation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Matrix ToMatrix() => Matrix.CreateFromQuaternion(this); + + /// + /// Converts this value to its euler angles xyz representation. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + public Vector3 ToEulerAnglesXYZ() + { + Quaternion normalized = this.normalized; + float sinY = Math.Clamp(2f * (normalized.x * normalized.z + normalized.w * normalized.y), -1f, 1f); + float angleY = MathF.Asin(sinY); + float angleX = MathF.Atan2( + 2f * (normalized.w * normalized.x - normalized.y * normalized.z), + 1f - 2f * (normalized.x * normalized.x + normalized.y * normalized.y) + ); + float angleZ = MathF.Atan2( + 2f * (normalized.w * normalized.z - normalized.x * normalized.y), + 1f - 2f * (normalized.y * normalized.y + normalized.z * normalized.z) + ); + return new Vector3(angleX, angleY, angleZ); + } + + /// + /// Converts this value to its euler angles xyzdegrees representation. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + public Vector3 ToEulerAnglesXYZDegrees() => ToEulerAnglesXYZ() * (180f / MathF.PI); + + /// + /// Converts this value to its euler angles zyx representation. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + public Vector3 ToEulerAnglesZYX() + { + float sinrCosp = 2 * (w * z + x * y); + float cosrCosp = 1 - 2 * (y * y + z * z); + float angleZ = MathF.Atan2(sinrCosp, cosrCosp); + + float sinp = 2 * (w * y - z * x); + float angleY = MathF.Abs(sinp) >= 1 + ? MathF.CopySign(MathF.PI / 2, sinp) + : MathF.Asin(sinp); + + float sinyCosp = 2 * (w * x + y * z); + float cosyCosp = 1 - 2 * (x * x + y * y); + float angleX = MathF.Atan2(sinyCosp, cosyCosp); + + return new Vector3(angleX, angleY, angleZ); + } + + /// + /// Converts this value to its euler angles zyxdegrees representation. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + public Vector3 ToEulerAnglesZYXDegrees() + { + float sinrCosp = 2 * (w * z + x * y); + float cosrCosp = 1 - 2 * (y * y + z * z); + float angleZ = MathF.Atan2(sinrCosp, cosrCosp); + + float sinp = 2 * (w * y - z * x); + float angleY = MathF.Abs(sinp) >= 1 + ? MathF.CopySign(MathF.PI / 2, sinp) + : MathF.Asin(sinp); + + float sinyCosp = 2 * (w * x + y * z); + float cosyCosp = 1 - 2 * (x * x + y * y); + float angleX = MathF.Atan2(sinyCosp, cosyCosp); + + return new Vector3(angleX * 180f / MathF.PI, angleY * 180f / MathF.PI, angleZ * 180f / MathF.PI); + } + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Quaternion q && this == q; + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Quaternion other) => this == other; + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, z, w); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x:F3}, {y:F3}, {z:F3}, {w:F3})"; /// /// Returns a unit-length value while handling degenerate input according to the method contract. @@ -96,7 +230,9 @@ public static Quaternion Normalize(Quaternion q) { float len = q.Length(); if (len < 1e-6f) + { return identity; + } return new Quaternion(q.x / len, q.y / len, q.z / len, q.w / len); } @@ -126,8 +262,10 @@ public static Quaternion Inverse(Quaternion q) { float lenSq = q.LengthSquared(); if (lenSq < 1e-6f) + { return identity; - var conj = Conjugate(q); + } + Quaternion conj = Conjugate(q); return new Quaternion(conj.x / lenSq, conj.y / lenSq, conj.z / lenSq, conj.w / lenSq); } @@ -162,7 +300,7 @@ float t if (dot > 0.9995f) { // Linear interpolation fallback - Quaternion result = new Quaternion( + var result = new Quaternion( a.x + t * (b.x - a.x), a.y + t * (b.y - a.y), a.z + t * (b.z - a.z), @@ -179,12 +317,7 @@ float t float s0 = MathF.Cos(theta) - dot * sinTheta / sinTheta0; float s1 = sinTheta / sinTheta0; - return new Quaternion( - a.x * s0 + b.x * s1, - a.y * s0 + b.y * s1, - a.z * s0 + b.z * s1, - a.w * s0 + b.w * s1 - ); + return new Quaternion(a.x * s0 + b.x * s1, a.y * s0 + b.y * s1, a.z * s0 + b.z * s1, a.w * s0 + b.w * s1); } /// @@ -207,12 +340,7 @@ float angle axis = axis.normalized; float halfAngle = angle * 0.5f; float sin = MathF.Sin(halfAngle); - return new Quaternion( - axis.x * sin, - axis.y * sin, - axis.z * sin, - MathF.Cos(halfAngle) - ); + return new Quaternion(axis.x * sin, axis.y * sin, axis.z * sin, MathF.Cos(halfAngle)); } /// @@ -232,42 +360,39 @@ public static Quaternion FromRotationMatrix(Matrix m) { float s = MathF.Sqrt(trace + 1f) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - (m.m32 - m.m23) * invS, - (m.m13 - m.m31) * invS, - (m.m21 - m.m12) * invS, - 0.25f * s)); + return Normalize( + new Quaternion((m.m32 - m.m23) * invS, (m.m13 - m.m31) * invS, (m.m21 - m.m12) * invS, 0.25f * s) + ); } if (m.m11 > m.m22 && m.m11 > m.m33) { float s = MathF.Sqrt(1f + m.m11 - m.m22 - m.m33) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - 0.25f * s, - (m.m12 + m.m21) * invS, - (m.m13 + m.m31) * invS, - (m.m32 - m.m23) * invS)); + return Normalize( + new Quaternion(0.25f * s, (m.m12 + m.m21) * invS, (m.m13 + m.m31) * invS, (m.m32 - m.m23) * invS) + ); } if (m.m22 > m.m33) { float s = MathF.Sqrt(1f + m.m22 - m.m11 - m.m33) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - (m.m12 + m.m21) * invS, - 0.25f * s, - (m.m23 + m.m32) * invS, - (m.m13 - m.m31) * invS)); + return Normalize( + new Quaternion((m.m12 + m.m21) * invS, 0.25f * s, (m.m23 + m.m32) * invS, (m.m13 - m.m31) * invS) + ); } float sFinal = MathF.Sqrt(1f + m.m33 - m.m11 - m.m22) * 2f; float invFinal = 1f / sFinal; - return Normalize(new Quaternion( - (m.m13 + m.m31) * invFinal, - (m.m23 + m.m32) * invFinal, - 0.25f * sFinal, - (m.m21 - m.m12) * invFinal)); + return Normalize( + new Quaternion( + (m.m13 + m.m31) * invFinal, + (m.m23 + m.m32) * invFinal, + 0.25f * sFinal, + (m.m21 - m.m12) * invFinal + ) + ); } /// @@ -291,24 +416,11 @@ Vector3 up Vector3 x = Vector3.NormalizeSafe(Vector3.Cross(up, z)); Vector3 y = Vector3.Cross(z, x); - var m = new Matrix( - x.x, y.x, z.x, 0f, - x.y, y.y, z.y, 0f, - x.z, y.z, z.z, 0f, - 0f, 0f, 0f, 1f); + var m = new Matrix(x.x, y.x, z.x, 0f, x.y, y.y, z.y, 0f, x.z, y.z, z.z, 0f, 0f, 0f, 0f, 1f); return FromRotationMatrix(m); } - /// - /// Converts this quaternion to a rotation matrix. - /// - /// - /// The validated matrix that represents the completed operation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Matrix ToMatrix() => Matrix.CreateFromQuaternion(this); - /// /// Creates and validates a caller-owned from yaw pitch roll value. /// @@ -329,91 +441,7 @@ public static Quaternion CreateFromYawPitchRoll( float yaw, float pitch, float roll - ) - => FromEulerAnglesZYX(new Vector3(pitch, yaw, roll)); - - /// - /// Converts this value to its euler angles xyz representation. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - public Vector3 ToEulerAnglesXYZ() - { - Quaternion normalized = this.normalized; - float sinY = Math.Clamp( - 2f * (normalized.x * normalized.z + normalized.w * normalized.y), - -1f, - 1f); - float angleY = MathF.Asin(sinY); - float angleX = MathF.Atan2( - 2f * (normalized.w * normalized.x - normalized.y * normalized.z), - 1f - 2f * (normalized.x * normalized.x + normalized.y * normalized.y)); - float angleZ = MathF.Atan2( - 2f * (normalized.w * normalized.z - normalized.x * normalized.y), - 1f - 2f * (normalized.y * normalized.y + normalized.z * normalized.z)); - return new Vector3(angleX, angleY, angleZ); - } - - /// - /// Converts this value to its euler angles xyzdegrees representation. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - public Vector3 ToEulerAnglesXYZDegrees() => ToEulerAnglesXYZ() * (180f / MathF.PI); - - /// - /// Converts this value to its euler angles zyx representation. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - public Vector3 ToEulerAnglesZYX() - { - float sinrCosp = 2 * (w * z + x * y); - float cosrCosp = 1 - 2 * (y * y + z * z); - float angleZ = MathF.Atan2(sinrCosp, cosrCosp); - - float sinp = 2 * (w * y - z * x); - float angleY = MathF.Abs(sinp) >= 1 - ? MathF.CopySign(MathF.PI / 2, sinp) - : MathF.Asin(sinp); - - float sinyCosp = 2 * (w * x + y * z); - float cosyCosp = 1 - 2 * (x * x + y * y); - float angleX = MathF.Atan2(sinyCosp, cosyCosp); - - return new Vector3(angleX, angleY, angleZ); - } - - /// - /// Converts this value to its euler angles zyxdegrees representation. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - public Vector3 ToEulerAnglesZYXDegrees() - { - float sinrCosp = 2 * (w * z + x * y); - float cosrCosp = 1 - 2 * (y * y + z * z); - float angleZ = MathF.Atan2(sinrCosp, cosrCosp); - - float sinp = 2 * (w * y - z * x); - float angleY = MathF.Abs(sinp) >= 1 - ? MathF.CopySign(MathF.PI / 2, sinp) - : MathF.Asin(sinp); - - float sinyCosp = 2 * (w * x + y * z); - float cosyCosp = 1 - 2 * (x * x + y * y); - float angleX = MathF.Atan2(sinyCosp, cosyCosp); - - return new Vector3( - angleX * 180f / MathF.PI, - angleY * 180f / MathF.PI, - angleZ * 180f / MathF.PI - ); - } + ) => FromEulerAnglesZYX(new Vector3(pitch, yaw, roll)); /// /// Creates the target representation from the supplied euler angles xyz value. @@ -441,7 +469,7 @@ public static Quaternion FromEulerAnglesXYZ(Vector3 euler) cx * cy * cz - sx * sy * sz ); } - + /// /// Creates the target representation from the supplied euler angles xyzdegrees value. /// @@ -454,7 +482,7 @@ public static Quaternion FromEulerAnglesXYZ(Vector3 euler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion FromEulerAnglesXYZDegrees(Vector3 eulerDegrees) { - var euler = eulerDegrees * (MathF.PI / 180f); + Vector3 euler = eulerDegrees * (MathF.PI / 180f); float cx = MathF.Cos(euler.x * 0.5f); float sx = MathF.Sin(euler.x * 0.5f); @@ -497,7 +525,7 @@ public static Quaternion FromEulerAnglesZYX(Vector3 euler) cx * cy * cz + sx * sy * sz ); } - + /// /// Creates the target representation from the supplied euler angles zyxdegrees value. /// @@ -510,7 +538,7 @@ public static Quaternion FromEulerAnglesZYX(Vector3 euler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion FromEulerAnglesZYXDegrees(Vector3 eulerDegrees) { - var euler = eulerDegrees * (MathF.PI / 180f); + Vector3 euler = eulerDegrees * (MathF.PI / 180f); float cz = MathF.Cos(euler.z * 0.5f); float sz = MathF.Sin(euler.z * 0.5f); @@ -542,14 +570,12 @@ public static Quaternion FromEulerAnglesZYXDegrees(Vector3 eulerDegrees) public static Quaternion operator *( Quaternion a, Quaternion b - ) { - return new Quaternion( - a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, - a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z - ); - } + ) => new Quaternion( + a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z + ); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -566,11 +592,10 @@ Quaternion b public static bool operator ==( Quaternion a, Quaternion b - ) - => MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z) && - MathHelper.AlmostEquals(a.w, b.w); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z) + && MathHelper.AlmostEquals(a.w, b.w); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -588,7 +613,7 @@ Quaternion b Quaternion a, Quaternion b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -598,7 +623,8 @@ Quaternion b /// /// The validated system.numerics.quaternion that represents the completed operation. /// - public static implicit operator System.Numerics.Quaternion(Quaternion q) => new(q.x, q.y, q.z, q.w); + public static implicit operator NumericsQuaternion(Quaternion q) => new(q.x, q.y, q.z, q.w); + /// /// Converts the supplied value to . /// @@ -608,43 +634,5 @@ Quaternion b /// /// The validated quaternion that represents the completed operation. /// - public static implicit operator Quaternion(System.Numerics.Quaternion q) => new(q.X, q.Y, q.Z, q.W); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Quaternion q && this == q; - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Quaternion other) => this == other; - - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, z, w); - - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x:F3}, {y:F3}, {z:F3}, {w:F3})"; + public static implicit operator Quaternion(NumericsQuaternion q) => new(q.X, q.Y, q.Z, q.W); } diff --git a/src/foundation/core/Inno.Core.Mathematics/Rect.cs b/src/foundation/core/Inno.Core.Mathematics/Rect.cs index ca59e0775..8de52af59 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Rect.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Rect.cs @@ -1,6 +1,8 @@ using System; using System.Runtime.CompilerServices; +using NumericsVector4 = System.Numerics.Vector4; + namespace Inno.Core.Mathematics; /// @@ -10,43 +12,24 @@ namespace Inno.Core.Mathematics; public struct Rect : IEquatable { /// - /// The horizontal or first component. + /// The horizontal position of the origin corner. /// - public float x, y, width, height; + public float x; /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public float left => x; - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public float right => x + width; - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public float top => y; - /// - /// Gets the scalar measurement or identity associated with the current state. + /// The vertical position of the origin corner. /// - public float bottom => y + height; + public float y; /// - /// Gets the minimum corner of this axis-aligned rectangle. - /// - public Vector2 min => new(x, y); - /// - /// Gets the maximum corner of this axis-aligned rectangle. - /// - public Vector2 max => new(x + width, y + height); - /// - /// Gets the width and height derived from the rectangle bounds. + /// The horizontal extent. /// - public Vector2 size => new(width, height); + public float width; + /// - /// Gets the midpoint derived from the rectangle bounds. + /// The vertical extent. /// - public Vector2 center => new(x + width * 0.5f, y + height * 0.5f); + public float height; /// /// Creates a validated rect instance. @@ -75,6 +58,46 @@ float height this.height = height; } + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public float left => x; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public float right => x + width; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public float top => y; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public float bottom => y + height; + + /// + /// Gets the minimum corner of this axis-aligned rectangle. + /// + public Vector2 min => new(x, y); + + /// + /// Gets the maximum corner of this axis-aligned rectangle. + /// + public Vector2 max => new(x + width, y + height); + + /// + /// Gets the width and height derived from the rectangle bounds. + /// + public Vector2 size => new(width, height); + + /// + /// Gets the midpoint derived from the rectangle bounds. + /// + public Vector2 center => new(x + width * 0.5f, y + height * 0.5f); + /// /// Checks if this rectangle overlaps another rectangle. /// @@ -85,13 +108,10 @@ float height /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Overlaps(Rect other) - { - return !(right <= other.left || - left >= other.right || - bottom <= other.top || - top >= other.bottom); - } + public bool Overlaps(Rect other) => !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); /// /// Checks if this rectangle fully contains another rectangle. @@ -103,13 +123,22 @@ public bool Overlaps(Rect other) /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(Rect other) - { - return left <= other.left && - top <= other.top && - right >= other.right && - bottom >= other.bottom; - } + public bool Contains(Rect other) => left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; + + /// + /// Determines whether current state contains the requested value value. + /// + /// + /// The p consumed by contains; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(Vector2 p) => Contains(p.x, p.y); /// /// Checks if this rectangle contains a point. @@ -127,22 +156,50 @@ public bool Contains(Rect other) public bool Contains( float px, float py - ) { - return px >= left && px < right && - py >= top && py < bottom; - } + ) => px >= left && px < right + && py >= top && py < bottom; /// - /// Determines whether current state contains the requested value value. + /// Determines whether this value and the supplied value represent the same logical state. /// - /// - /// The p consumed by contains; ownership remains with the caller unless explicitly stated otherwise. + /// + /// The object compared with this value. /// /// /// when the requested condition is satisfied; otherwise, . /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(Vector2 p) => Contains(p.x, p.y); + public override bool Equals(object? obj) => obj is Rect r && Equals(r); + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Rect other) + => MathHelper.AlmostEquals(x, other.x) + && MathHelper.AlmostEquals(y, other.y) + && MathHelper.AlmostEquals(width, other.width) + && MathHelper.AlmostEquals(height, other.height); + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, width, height); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {width}, {height})"; /// /// Creates a rectangle from minimum and maximum boundaries; point containment excludes the maximum boundary. @@ -160,9 +217,7 @@ float py public static Rect FromMinMax( Vector2 min, Vector2 max - ) { - return new Rect(min.x, min.y, max.x - min.x, max.y - min.y); - } + ) => new Rect(min.x, min.y, max.x - min.x, max.y - min.y); /// /// Returns the smallest axis-aligned rectangle containing both supplied rectangles. @@ -241,6 +296,7 @@ out Rect intersection Rect a, Rect b ) => a.Equals(b); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -305,7 +361,8 @@ Rect b /// The validated system.numerics.vector4 that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator System.Numerics.Vector4(Rect r) => new System.Numerics.Vector4(r.x, r.y, r.width, r.height); + public static implicit operator NumericsVector4(Rect r) => new NumericsVector4(r.x, r.y, r.width, r.height); + /// /// Converts the supplied value to . /// @@ -316,44 +373,5 @@ Rect b /// The validated rect that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Rect(System.Numerics.Vector4 v) => new Rect(v.X, v.Y, v.Z, v.W); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Rect r && Equals(r); - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Rect other) => - MathHelper.AlmostEquals(x, other.x) && - MathHelper.AlmostEquals(y, other.y) && - MathHelper.AlmostEquals(width, other.width) && - MathHelper.AlmostEquals(height, other.height); - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, width, height); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {width}, {height})"; + public static implicit operator Rect(NumericsVector4 v) => new Rect(v.X, v.Y, v.Z, v.W); } diff --git a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs index acf5671ca..931dc6347 100644 --- a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs +++ b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs @@ -11,43 +11,24 @@ namespace Inno.Core.Mathematics; public struct RectInt : IEquatable { /// - /// The horizontal or first component. + /// The horizontal position of the origin corner. /// - public int x, y, width, height; + public int x; /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int left => x; - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int right => x + width; - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int top => y; - /// - /// Gets the scalar measurement or identity associated with the current state. + /// The vertical position of the origin corner. /// - public int bottom => y + height; + public int y; /// - /// Gets the minimum corner of this axis-aligned rectangle. - /// - public Vector2Int min => new(x, y); - /// - /// Gets the maximum corner of this axis-aligned rectangle. - /// - public Vector2Int max => new(x + width, y + height); - /// - /// Gets the width and height derived from the rectangle bounds. + /// The horizontal extent. /// - public Vector2Int size => new(width, height); + public int width; + /// - /// Gets the midpoint derived from the rectangle bounds. + /// The vertical extent. /// - public Vector2Int center => new(x + width / 2, y + height / 2); + public int height; /// /// Creates a validated rect int instance. @@ -76,6 +57,46 @@ int height this.height = height; } + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int left => x; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int right => x + width; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int top => y; + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int bottom => y + height; + + /// + /// Gets the minimum corner of this axis-aligned rectangle. + /// + public Vector2Int min => new(x, y); + + /// + /// Gets the maximum corner of this axis-aligned rectangle. + /// + public Vector2Int max => new(x + width, y + height); + + /// + /// Gets the width and height derived from the rectangle bounds. + /// + public Vector2Int size => new(width, height); + + /// + /// Gets the midpoint derived from the rectangle bounds. + /// + public Vector2Int center => new(x + width / 2, y + height / 2); + /// /// Checks if this rectangle overlaps another rectangle. /// @@ -86,13 +107,10 @@ int height /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Overlaps(RectInt other) - { - return !(right <= other.left || - left >= other.right || - bottom <= other.top || - top >= other.bottom); - } + public bool Overlaps(RectInt other) => !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); /// /// Checks if this rectangle fully contains another rectangle. @@ -104,13 +122,22 @@ public bool Overlaps(RectInt other) /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(RectInt other) - { - return left <= other.left && - top <= other.top && - right >= other.right && - bottom >= other.bottom; - } + public bool Contains(RectInt other) => left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; + + /// + /// Determines whether current state contains the requested value value. + /// + /// + /// The p consumed by contains; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(Vector2Int p) => Contains(p.x, p.y); /// /// Checks if this rectangle contains a point. @@ -128,22 +155,46 @@ public bool Contains(RectInt other) public bool Contains( int px, int py - ) { - return px >= left && px < right && - py >= top && py < bottom; - } + ) => px >= left && px < right + && py >= top && py < bottom; /// - /// Determines whether current state contains the requested value value. + /// Determines whether this value and the supplied value represent the same logical state. /// - /// - /// The p consumed by contains; ownership remains with the caller unless explicitly stated otherwise. + /// + /// The object compared with this value. /// /// /// when the requested condition is satisfied; otherwise, . /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(Vector2Int p) => Contains(p.x, p.y); + public override bool Equals(object? obj) => obj is RectInt r && Equals(r); + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(RectInt other) => x == other.x && y == other.y && width == other.width && height == other.height; + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, width, height); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {width}, {height})"; /// /// Creates a rectangle from minimum and maximum boundaries; point containment excludes the maximum boundary. @@ -161,9 +212,7 @@ int py public static RectInt FromMinMax( Vector2Int min, Vector2Int max - ) { - return new RectInt(min.x, min.y, max.x - min.x, max.y - min.y); - } + ) => new RectInt(min.x, min.y, max.x - min.x, max.y - min.y); /// /// Returns the smallest axis-aligned rectangle containing both supplied rectangles. @@ -242,6 +291,7 @@ out RectInt intersection RectInt a, RectInt b ) => a.Equals(b); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -343,39 +393,4 @@ RectInt b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator RectInt(Vector4Int v) => new RectInt(v.x, v.y, v.z, v.w); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is RectInt r && Equals(r); - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(RectInt other) => x == other.x && y == other.y && width == other.width && height == other.height; - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, width, height); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {width}, {height})"; } diff --git a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs index a31428efd..3c191a3dd 100644 --- a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs +++ b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs @@ -26,175 +26,175 @@ Vector128 b ) { if (Sse.IsSupported) { - var mul = Sse.Multiply(a, b); + Vector128 mul = Sse.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } if (AdvSimd.IsSupported) { - var mul = AdvSimd.Multiply(a, b); + Vector128 mul = AdvSimd.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } return a.GetElement(0) * b.GetElement(0) - + a.GetElement(1) * b.GetElement(1) - + a.GetElement(2) * b.GetElement(2) - + a.GetElement(3) * b.GetElement(3); + + a.GetElement(1) * b.GetElement(1) + + a.GetElement(2) * b.GetElement(2) + + a.GetElement(3) * b.GetElement(3); } /// - /// Calculates a two-component scalar dot product. + /// Calculates a four-component scalar dot product. /// /// - /// The ax consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. + /// The ax consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The ay consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. + /// The ay consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The az consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The aw consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The bx consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. + /// The bx consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The by consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. + /// The by consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The bz consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The bw consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The scalar result calculated from the supplied inputs. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Dot2( + public static float Dot4( float ax, float ay, + float az, + float aw, float bx, - float by + float by, + float bz, + float bw ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, 0f, 0f); - var b = Vector128.Create(bx, by, 0f, 0f); - var mul = Sse.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1); + Vector128 a = Vector128.Create(ax, ay, az, aw); + Vector128 b = Vector128.Create(bx, by, bz, bw); + Vector128 mul = Sse.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, 0f, 0f); - var b = Vector128.Create(bx, by, 0f, 0f); - var mul = AdvSimd.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1); + Vector128 a = Vector128.Create(ax, ay, az, aw); + Vector128 b = Vector128.Create(bx, by, bz, bw); + Vector128 mul = AdvSimd.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } - return (ax * bx) + (ay * by); + return (ax * bx) + (ay * by) + (az * bz) + (aw * bw); } /// - /// Calculates a three-component scalar dot product. + /// Calculates a two-component scalar dot product. /// /// - /// The ax consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. + /// The ax consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The ay consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The az consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. + /// The ay consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The bx consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. + /// The bx consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The by consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The bz consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. + /// The by consumed by dot2; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The scalar result calculated from the supplied inputs. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Dot3( + public static float Dot2( float ax, float ay, - float az, float bx, - float by, - float bz + float by ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, az, 0f); - var b = Vector128.Create(bx, by, bz, 0f); - var mul = Sse.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); + Vector128 a = Vector128.Create(ax, ay, 0f, 0f); + Vector128 b = Vector128.Create(bx, by, 0f, 0f); + Vector128 mul = Sse.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, az, 0f); - var b = Vector128.Create(bx, by, bz, 0f); - var mul = AdvSimd.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); + Vector128 a = Vector128.Create(ax, ay, 0f, 0f); + Vector128 b = Vector128.Create(bx, by, 0f, 0f); + Vector128 mul = AdvSimd.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1); } - return (ax * bx) + (ay * by) + (az * bz); + return (ax * bx) + (ay * by); } /// - /// Calculates a four-component scalar dot product. + /// Calculates a three-component scalar dot product. /// /// - /// The ax consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The ax consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The ay consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The ay consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The az consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The aw consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The az consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The bx consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The bx consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The by consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The by consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// - /// The bz consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The bw consumed by dot4; ownership remains with the caller unless explicitly stated otherwise. + /// The bz consumed by dot3; ownership remains with the caller unless explicitly stated otherwise. /// /// /// The scalar result calculated from the supplied inputs. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Dot4( + public static float Dot3( float ax, float ay, float az, - float aw, float bx, float by, - float bz, - float bw + float bz ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, az, aw); - var b = Vector128.Create(bx, by, bz, bw); - var mul = Sse.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); + Vector128 a = Vector128.Create(ax, ay, az, 0f); + Vector128 b = Vector128.Create(bx, by, bz, 0f); + Vector128 mul = Sse.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, az, aw); - var b = Vector128.Create(bx, by, bz, bw); - var mul = AdvSimd.Multiply(a, b); - return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); + Vector128 a = Vector128.Create(ax, ay, az, 0f); + Vector128 b = Vector128.Create(bx, by, bz, 0f); + Vector128 mul = AdvSimd.Multiply(a, b); + return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); } - return (ax * bx) + (ay * by) + (az * bz) + (aw * bw); + return (ax * bx) + (ay * by) + (az * bz); } } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs index 38cd00183..f47b4cc62 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs @@ -2,6 +2,8 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; +using NumericsVector2 = System.Numerics.Vector2; + namespace Inno.Core.Mathematics; /// @@ -10,14 +12,37 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector2 : IEquatable { + /// + /// A value whose components are all zero. + /// + public static readonly Vector2 ZERO = new(0f, 0f); + + /// + /// A value whose components are all one. + /// + public static readonly Vector2 ONE = new(1f, 1f); + + /// + /// A unit value aligned with the x axis. + /// + public static readonly Vector2 UNIT_X = new(1f, 0f); + + /// + /// A unit value aligned with the y axis. + /// + public static readonly Vector2 UNIT_Y = new(0f, 1f); + /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; + /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; /// /// Creates a vector from explicit component values. @@ -37,21 +62,16 @@ float y } /// - /// A value whose components are all zero. - /// - public static readonly Vector2 ZERO = new(0f, 0f); - /// - /// A value whose components are all one. - /// - public static readonly Vector2 ONE = new(1f, 1f); - /// - /// A unit value aligned with the x axis. - /// - public static readonly Vector2 UNIT_X = new(1f, 0f); - /// - /// A unit value aligned with the y axis. + /// Gets a unit-length copy, or the zero value when normalization is undefined. /// - public static readonly Vector2 UNIT_Y = new(0f, 1f); + public Vector2 normalized + { + get + { + float len = Length(); + return len > 0f ? this / len : ZERO; + } + } /// /// Calculates the Euclidean magnitude of this value. @@ -72,16 +92,42 @@ float y public float LengthSquared() => SimdMath.Dot2(x, y, x, y); /// - /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// Determines whether this value and the supplied value represent the same logical state. /// - public Vector2 normalized - { - get - { - float len = Length(); - return len > 0f ? this / len : ZERO; - } - } + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Vector2 other && Equals(other); + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector2 other) => MathHelper.AlmostEquals(x, other.x) && MathHelper.AlmostEquals(y, other.y); + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x:F2}, {y:F2})"; /// /// Returns a unit-length value while handling degenerate input according to the method contract. @@ -273,7 +319,7 @@ public static Vector2 Reflect( Vector2 v, Vector2 n ) => v - 2f * Dot(v, n) * n; - + /// /// Transforms the supplied value by the requested transformation. /// @@ -319,11 +365,12 @@ Quaternion rotation float w = rotation.w; return new Vector2( value.x * (1f - 2f * (y * y + z * z)) - + value.y * (2f * (x * y - z * w)), + + value.y * (2f * (x * y - z * w)), value.x * (2f * (x * y + z * w)) - + value.y * (1f - 2f * (x * x + z * z)) + + value.y * (1f - 2f * (x * x + z * z)) ); } + /// /// Adds the supplied values component by component. /// @@ -343,6 +390,19 @@ Quaternion rotation Vector2 a, Vector2 b ) => new Vector2(a.x + b.x, a.y + b.y); + + /// + /// Subtracts or negates the supplied value component by component. + /// + /// + /// The concrete value read or transformed by this operation. + /// + /// + /// The validated vector2 that represents the completed operation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector2 operator -(Vector2 v) => new Vector2(-v.x, -v.y); + /// /// Subtracts or negates the supplied value component by component. /// @@ -360,17 +420,7 @@ Vector2 b Vector2 a, Vector2 b ) => new Vector2(a.x - b.x, a.y - b.y); - /// - /// Subtracts or negates the supplied value component by component. - /// - /// - /// The concrete value read or transformed by this operation. - /// - /// - /// The validated vector2 that represents the completed operation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector2 operator -(Vector2 v) => new Vector2(-v.x, -v.y); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -388,6 +438,7 @@ Vector2 b Vector2 v, float scalar ) => new Vector2(v.x * scalar, v.y * scalar); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -405,6 +456,7 @@ float scalar float scalar, Vector2 v ) => v * scalar; + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -440,6 +492,7 @@ float scalar Vector2 a, Vector2 b ) => MathHelper.AlmostEquals(a.x, b.x) && MathHelper.AlmostEquals(a.y, b.y); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -457,7 +510,7 @@ Vector2 b Vector2 a, Vector2 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -467,7 +520,8 @@ Vector2 b /// /// The validated system.numerics.vector2 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector2(Vector2 v) => new(v.x, v.y); + public static implicit operator NumericsVector2(Vector2 v) => new(v.x, v.y); + /// /// Converts the supplied value to . /// @@ -477,40 +531,5 @@ Vector2 b /// /// The validated vector2 that represents the completed operation. /// - public static implicit operator Vector2(System.Numerics.Vector2 v) => new(v.X, v.Y); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Vector2 other && Equals(other); - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector2 other) => MathHelper.AlmostEquals(x, other.x) && MathHelper.AlmostEquals(y, other.y); - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x:F2}, {y:F2})"; + public static implicit operator Vector2(NumericsVector2 v) => new(v.X, v.Y); } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs index 6bc86461b..3ef90ea19 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs @@ -10,14 +10,39 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector2Int : IEquatable { + /// + /// A value whose components are all zero. + /// + + // Common constants + public static readonly Vector2Int ZERO = new(0, 0); + + /// + /// A value whose components are all one. + /// + public static readonly Vector2Int ONE = new(1, 1); + + /// + /// A unit value aligned with the x axis. + /// + public static readonly Vector2Int UNIT_X = new(1, 0); + + /// + /// A unit value aligned with the y axis. + /// + public static readonly Vector2Int UNIT_Y = new(0, 1); + /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; + /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; /// /// Creates a vector from explicit component values. @@ -35,24 +60,47 @@ int y this.x = x; this.y = y; } + /// - /// A value whose components are all zero. + /// Determines whether this value and the supplied value represent the same logical state. /// + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + + // Equality + public override bool Equals(object? obj) => obj is Vector2Int other && Equals(other); - // Common constants - public static readonly Vector2Int ZERO = new(0, 0); /// - /// A value whose components are all one. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Vector2Int ONE = new(1, 1); + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector2Int other) => x == other.x && y == other.y; + /// - /// A unit value aligned with the x axis. + /// Computes a hash code consistent with the implemented equality contract. /// - public static readonly Vector2Int UNIT_X = new(1, 0); + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y); + /// - /// A unit value aligned with the y axis. + /// Formats this value as a human-readable component list. /// - public static readonly Vector2Int UNIT_Y = new(0, 1); + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y})"; + /// /// Adds the supplied values component by component. /// @@ -76,32 +124,32 @@ Vector2Int b /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The first operand or interpolation endpoint. - /// - /// - /// The second operand or interpolation endpoint. + /// + /// The concrete value read or transformed by this operation. /// /// /// The validated vector2int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector2Int operator -( - Vector2Int a, - Vector2Int b - ) => new(a.x - b.x, a.y - b.y); + public static Vector2Int operator -(Vector2Int v) => new(-v.x, -v.y); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The concrete value read or transformed by this operation. + /// + /// The first operand or interpolation endpoint. + /// + /// + /// The second operand or interpolation endpoint. /// /// /// The validated vector2int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector2Int operator -(Vector2Int v) => new(-v.x, -v.y); + public static Vector2Int operator -( + Vector2Int a, + Vector2Int b + ) => new(a.x - b.x, a.y - b.y); /// /// Multiplies the supplied values according to their algebraic contract. @@ -192,6 +240,7 @@ Vector2Int b Vector2Int a, Vector2Int b ) => !(a == b); + /// /// Converts the supplied value to . /// @@ -217,43 +266,4 @@ Vector2Int b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector2Int(Vector2 v) => new((int)v.x, (int)v.y); - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - - // Equality - public override bool Equals(object? obj) => obj is Vector2Int other && Equals(other); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector2Int other) => x == other.x && y == other.y; - - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y); - - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y})"; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs index 27a3e90f0..33c9090a7 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs @@ -1,9 +1,11 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; + +using NumericsVector3 = System.Numerics.Vector3; namespace Inno.Core.Mathematics; @@ -13,74 +15,100 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector3 : IEquatable { - /// - /// The horizontal or first component. - /// - [DataMember] public float x; - /// - /// The vertical or second component. - /// - [DataMember] public float y; - /// - /// The depth or third component. - /// - [DataMember] public float z; - - /// - /// Creates a vector from explicit component values. - /// - /// - /// The horizontal or first component. - /// - /// - /// The vertical or second component. - /// - /// - /// The depth or third component. - /// - public Vector3( - float x, - float y, - float z - ) { - this.x = x; - this.y = y; - this.z = z; - } /// /// A value whose components are all zero. /// // Common static vectors public static readonly Vector3 ZERO = new(0, 0, 0); + /// /// A value whose components are all one. /// public static readonly Vector3 ONE = new(1, 1, 1); + /// /// The up value used as part of this type's public representation. /// public static readonly Vector3 UP = new(0, 1, 0); + /// /// The down value used as part of this type's public representation. /// public static readonly Vector3 DOWN = new(0, -1, 0); + /// /// The left value used as part of this type's public representation. /// public static readonly Vector3 LEFT = new(-1, 0, 0); + /// /// The right value used as part of this type's public representation. /// public static readonly Vector3 RIGHT = new(1, 0, 0); + /// /// The forward value used as part of this type's public representation. /// public static readonly Vector3 FORWARD = new(0, 0, 1); + /// /// The back value used as part of this type's public representation. /// public static readonly Vector3 BACK = new(0, 0, -1); + + /// + /// The horizontal or first component. + /// + [DataMember] + public float x; + + /// + /// The vertical or second component. + /// + [DataMember] + public float y; + + /// + /// The depth or third component. + /// + [DataMember] + public float z; + + /// + /// Creates a vector from explicit component values. + /// + /// + /// The horizontal or first component. + /// + /// + /// The vertical or second component. + /// + /// + /// The depth or third component. + /// + public Vector3( + float x, + float y, + float z + ) { + this.x = x; + this.y = y; + this.z = z; + } + + /// + /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// + public Vector3 normalized + { + get + { + float len = Length(); + return len > 0 ? this / len : ZERO; + } + } + /// /// Calculates the Euclidean magnitude of this value. /// @@ -102,16 +130,42 @@ float z public float LengthSquared() => SimdMath.Dot3(x, y, z, x, y, z); /// - /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// Determines whether this value and the supplied value represent the same logical state. /// - public Vector3 normalized - { - get - { - float len = Length(); - return len > 0 ? this / len : ZERO; - } - } + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Vector3 other && this == other; + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector3 other) => this == other; + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, z); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {z})"; /// /// Returns a unit-length value while handling degenerate input according to the method contract. @@ -133,6 +187,7 @@ public static Vector3 NormalizeSafe( float len = value.Length(); return len > epsilon ? value / len : ZERO; } + /// /// Calculates the scalar dot product of two values. /// @@ -233,6 +288,7 @@ Vector3 onto return onto * (Dot(vector, onto) / denom); } + /// /// Calculates the vector perpendicular to both supplied vectors. /// @@ -251,11 +307,8 @@ Vector3 onto public static Vector3 Cross( Vector3 a, Vector3 b - ) => new( - a.y * b.z - a.z * b.y, - a.z * b.x - a.x * b.z, - a.x * b.y - a.y * b.x - ); + ) => new(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); + /// /// Calculates the Euclidean distance between two points. /// @@ -275,6 +328,7 @@ public static float Distance( Vector3 a, Vector3 b ) => (a - b).Length(); + /// /// Interpolates linearly after clamping the interpolation factor to [0, 1]. /// @@ -297,8 +351,8 @@ public static Vector3 Lerp( Vector3 a, Vector3 b, float t - ) => - a + (b - a) * Math.Clamp(t, 0f, 1f); + ) => a + (b - a) * Math.Clamp(t, 0f, 1f); + /// /// Reflects an incident value across the supplied normal. /// @@ -317,21 +371,20 @@ float t public static Vector3 Reflect( Vector3 dir, Vector3 normal - ) => - dir - 2f * Dot(dir, normal) * normal; - + ) => dir - 2f * Dot(dir, normal) * normal; + /// /// Transforms a position as a column vector with an implicit homogeneous coordinate of one. /// - /// - /// The transformed XYZ components, including translation. No perspective divide is performed. - /// /// /// The input position. /// /// /// The transformation matrix applied to the supplied value. /// + /// + /// The transformed XYZ components, including translation. No perspective divide is performed. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform( Vector3 position, @@ -339,10 +392,10 @@ Matrix matrix ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var v = Vector128.Create(position.x, position.y, position.z, 1f); - var row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, matrix.m14); - var row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, matrix.m24); - var row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, matrix.m34); + Vector128 v = Vector128.Create(position.x, position.y, position.z, 1f); + Vector128 row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, matrix.m14); + Vector128 row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, matrix.m24); + Vector128 row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, matrix.m34); float x = SimdMath.Dot4(row1, v); float y = SimdMath.Dot4(row2, v); @@ -356,6 +409,42 @@ Matrix matrix return new Vector3(tx, ty, tz); } + /// + /// Transforms the supplied value by the requested transformation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + /// + /// The rotation applied to the supplied value. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Transform( + Vector3 value, + Quaternion rotation + ) { + float x = value.x; + float y = value.y; + float z = value.z; + float qx = rotation.x; + float qy = rotation.y; + float qz = rotation.z; + float qw = rotation.w; + + float num1 = 2f * (qy * z - qz * y); + float num2 = 2f * (qz * x - qx * z); + float num3 = 2f * (qx * y - qy * x); + + float rx = x + num1 * qw + (qy * num3 - qz * num2); + float ry = y + num2 * qw + (qz * num1 - qx * num3); + float rz = z + num3 * qw + (qx * num2 - qy * num1); + + return new Vector3(rx, ry, rz); + } + /// /// Applies the matrix's upper-left 3-by-3 linear transform without translation. /// @@ -375,10 +464,10 @@ Matrix matrix ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var v = Vector128.Create(normal.x, normal.y, normal.z, 0f); - var row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, 0f); - var row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, 0f); - var row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, 0f); + Vector128 v = Vector128.Create(normal.x, normal.y, normal.z, 0f); + Vector128 row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, 0f); + Vector128 row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, 0f); + Vector128 row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, 0f); float x = SimdMath.Dot4(row1, v); float y = SimdMath.Dot4(row2, v); @@ -391,37 +480,7 @@ Matrix matrix float tz = matrix.m31 * normal.x + matrix.m32 * normal.y + matrix.m33 * normal.z; return new Vector3(tx, ty, tz); } - - /// - /// Transforms the supplied value by the requested transformation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - /// - /// The rotation applied to the supplied value. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector3 Transform( - Vector3 value, - Quaternion rotation - ) { - float x = value.x, y = value.y, z = value.z; - float qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w; - - float num1 = 2f * (qy * z - qz * y); - float num2 = 2f * (qz * x - qx * z); - float num3 = 2f * (qx * y - qy * x); - - float rx = x + num1 * qw + (qy * num3 - qz * num2); - float ry = y + num2 * qw + (qz * num1 - qx * num3); - float rz = z + num3 * qw + (qx * num2 - qy * num1); - return new Vector3(rx, ry, rz); - } /// /// Adds the supplied values component by component. /// @@ -441,6 +500,19 @@ Quaternion rotation Vector3 a, Vector3 b ) => new(a.x + b.x, a.y + b.y, a.z + b.z); + + /// + /// Subtracts or negates the supplied value component by component. + /// + /// + /// The concrete value read or transformed by this operation. + /// + /// + /// The validated vector3 that represents the completed operation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 operator -(Vector3 v) => new(-v.x, -v.y, -v.z); + /// /// Subtracts or negates the supplied value component by component. /// @@ -458,17 +530,7 @@ Vector3 b Vector3 a, Vector3 b ) => new(a.x - b.x, a.y - b.y, a.z - b.z); - /// - /// Subtracts or negates the supplied value component by component. - /// - /// - /// The concrete value read or transformed by this operation. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector3 operator -(Vector3 v) => new(-v.x, -v.y, -v.z); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -486,6 +548,7 @@ Vector3 b Vector3 v, float s ) => new(v.x * s, v.y * s, v.z * s); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -503,6 +566,7 @@ float s float s, Vector3 v ) => v * s; + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -537,10 +601,9 @@ float s public static bool operator ==( Vector3 a, Vector3 b - ) => - MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -559,7 +622,7 @@ Vector3 b Vector3 a, Vector3 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -569,7 +632,8 @@ Vector3 b /// /// The validated system.numerics.vector3 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector3(Vector3 v) => new(v.x, v.y, v.z); + public static implicit operator NumericsVector3(Vector3 v) => new(v.x, v.y, v.z); + /// /// Converts the supplied value to . /// @@ -579,40 +643,5 @@ Vector3 b /// /// The validated vector3 that represents the completed operation. /// - public static implicit operator Vector3(System.Numerics.Vector3 v) => new(v.X, v.Y, v.Z); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Vector3 other && this == other; - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector3 other) => this == other; - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, z); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {z})"; + public static implicit operator Vector3(NumericsVector3 v) => new(v.X, v.Y, v.Z); } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs index 045a890bd..ff782201b 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs @@ -10,18 +10,63 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector3Int : IEquatable { + /// + /// A value whose components are all zero. + /// + public static readonly Vector3Int ZERO = new(0, 0, 0); + + /// + /// A value whose components are all one. + /// + public static readonly Vector3Int ONE = new(1, 1, 1); + + /// + /// The up value used as part of this type's public representation. + /// + public static readonly Vector3Int UP = new(0, 1, 0); + + /// + /// The down value used as part of this type's public representation. + /// + public static readonly Vector3Int DOWN = new(0, -1, 0); + + /// + /// The left value used as part of this type's public representation. + /// + public static readonly Vector3Int LEFT = new(-1, 0, 0); + + /// + /// The right value used as part of this type's public representation. + /// + public static readonly Vector3Int RIGHT = new(1, 0, 0); + + /// + /// The forward value used as part of this type's public representation. + /// + public static readonly Vector3Int FORWARD = new(0, 0, 1); + + /// + /// The back value used as part of this type's public representation. + /// + public static readonly Vector3Int BACK = new(0, 0, -1); + /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; + /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; + /// /// The depth or third component. /// - [DataMember] public int z; + [DataMember] + public int z; /// /// Creates a vector from explicit component values. @@ -46,37 +91,42 @@ int z } /// - /// A value whose components are all zero. - /// - public static readonly Vector3Int ZERO = new(0, 0, 0); - /// - /// A value whose components are all one. - /// - public static readonly Vector3Int ONE = new(1, 1, 1); - /// - /// The up value used as part of this type's public representation. - /// - public static readonly Vector3Int UP = new(0, 1, 0); - /// - /// The down value used as part of this type's public representation. - /// - public static readonly Vector3Int DOWN = new(0, -1, 0); - /// - /// The left value used as part of this type's public representation. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Vector3Int LEFT = new(-1, 0, 0); + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Vector3Int other && Equals(other); + /// - /// The right value used as part of this type's public representation. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Vector3Int RIGHT = new(1, 0, 0); + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector3Int other) => x == other.x && y == other.y && z == other.z; + /// - /// The forward value used as part of this type's public representation. + /// Computes a hash code consistent with the implemented equality contract. /// - public static readonly Vector3Int FORWARD = new(0, 0, 1); + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, z); + /// - /// The back value used as part of this type's public representation. + /// Formats this value as a human-readable component list. /// - public static readonly Vector3Int BACK = new(0, 0, -1); + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {z})"; /// /// Adds the supplied values component by component. @@ -99,32 +149,32 @@ Vector3Int b /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The first operand or interpolation endpoint. - /// - /// - /// The second operand or interpolation endpoint. + /// + /// The concrete value read or transformed by this operation. /// /// /// The validated vector3int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector3Int operator -( - Vector3Int a, - Vector3Int b - ) => new(a.x - b.x, a.y - b.y, a.z - b.z); + public static Vector3Int operator -(Vector3Int v) => new(-v.x, -v.y, -v.z); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The concrete value read or transformed by this operation. + /// + /// The first operand or interpolation endpoint. + /// + /// + /// The second operand or interpolation endpoint. /// /// /// The validated vector3int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector3Int operator -(Vector3Int v) => new(-v.x, -v.y, -v.z); + public static Vector3Int operator -( + Vector3Int a, + Vector3Int b + ) => new(a.x - b.x, a.y - b.y, a.z - b.z); /// /// Multiplies the supplied values according to their algebraic contract. @@ -239,42 +289,4 @@ Vector3Int b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector3Int(Vector3 v) => new((int)v.x, (int)v.y, (int)v.z); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Vector3Int other && Equals(other); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector3Int other) => x == other.x && y == other.y && z == other.z; - - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, z); - - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {z})"; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs index 5d1581066..938a4bfc3 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs @@ -1,9 +1,11 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; + +using NumericsVector4 = System.Numerics.Vector4; namespace Inno.Core.Mathematics; @@ -13,22 +15,61 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector4 : IEquatable { + /// + /// A value whose components are all zero. + /// + + // Common vectors + public static readonly Vector4 ZERO = new(0, 0, 0, 0); + + /// + /// A value whose components are all one. + /// + public static readonly Vector4 ONE = new(1, 1, 1, 1); + + /// + /// A unit value aligned with the x axis. + /// + public static readonly Vector4 UNIT_X = new(1, 0, 0, 0); + + /// + /// A unit value aligned with the y axis. + /// + public static readonly Vector4 UNIT_Y = new(0, 1, 0, 0); + + /// + /// A unit value aligned with the z axis. + /// + public static readonly Vector4 UNIT_Z = new(0, 0, 1, 0); + + /// + /// A unit value aligned with the w axis. + /// + public static readonly Vector4 UNIT_W = new(0, 0, 0, 1); + /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; + /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; + /// /// The depth or third component. /// - [DataMember] public float z; + [DataMember] + public float z; + /// /// The homogeneous or fourth component. /// - [DataMember] public float w; + [DataMember] + public float w; /// /// Creates a vector from explicit component values. @@ -56,32 +97,19 @@ float w this.z = z; this.w = w; } - /// - /// A value whose components are all zero. - /// - // Common vectors - public static readonly Vector4 ZERO = new(0, 0, 0, 0); - /// - /// A value whose components are all one. - /// - public static readonly Vector4 ONE = new(1, 1, 1, 1); - /// - /// A unit value aligned with the x axis. - /// - public static readonly Vector4 UNIT_X = new(1, 0, 0, 0); /// - /// A unit value aligned with the y axis. - /// - public static readonly Vector4 UNIT_Y = new(0, 1, 0, 0); - /// - /// A unit value aligned with the z axis. - /// - public static readonly Vector4 UNIT_Z = new(0, 0, 1, 0); - /// - /// A unit value aligned with the w axis. + /// Gets a unit-length copy, or the zero value when normalization is undefined. /// - public static readonly Vector4 UNIT_W = new(0, 0, 0, 1); + public Vector4 normalized + { + get + { + float len = Length(); + return len > 0 ? this / len : ZERO; + } + } + /// /// Calculates the Euclidean magnitude of this value. /// @@ -103,16 +131,62 @@ float w public float LengthSquared() => SimdMath.Dot4(x, y, z, w, x, y, z, w); /// - /// Gets a unit-length copy, or the zero value when normalization is undefined. + /// Projects the supplied value onto the requested dimensional space. /// - public Vector4 normalized + /// + /// The validated vector3 that represents the completed operation. + /// + + // Project (useful in homogeneous coordinate systems) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 ProjectToVector3() { - get + if (w == 0f) { - float len = Length(); - return len > 0 ? this / len : ZERO; + // Avoid division by zero + return new Vector3(x, y, z); } + return new Vector3(x / w, y / w, z / w); } + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Vector4 other && this == other; + + /// + /// Determines whether this value and the supplied value represent the same logical state. + /// + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector4 other) => this == other; + + /// + /// Computes a hash code consistent with the implemented equality contract. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, z, w); + + /// + /// Formats this value as a human-readable component list. + /// + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {z}, {w})"; + /// /// Calculates the scalar dot product of two values. /// @@ -131,8 +205,8 @@ public Vector4 normalized public static float Dot( Vector4 a, Vector4 b - ) => - SimdMath.Dot4(a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w); + ) => SimdMath.Dot4(a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w); + /// /// Interpolates linearly after clamping the interpolation factor to [0, 1]. /// @@ -155,8 +229,8 @@ public static Vector4 Lerp( Vector4 a, Vector4 b, float t - ) => - a + (b - a) * Math.Clamp(t, 0f, 1f); + ) => a + (b - a) * Math.Clamp(t, 0f, 1f); + /// /// Reflects an incident value across the supplied normal. /// @@ -175,8 +249,8 @@ float t public static Vector4 Reflect( Vector4 vec, Vector4 normal - ) => - vec - 2f * Dot(vec, normal) * normal; + ) => vec - 2f * Dot(vec, normal) * normal; + /// /// Transforms the supplied value by the requested transformation. /// @@ -198,11 +272,11 @@ Matrix m ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var vec = Vector128.Create(v.x, v.y, v.z, v.w); - var row1 = Vector128.Create(m.m11, m.m12, m.m13, m.m14); - var row2 = Vector128.Create(m.m21, m.m22, m.m23, m.m24); - var row3 = Vector128.Create(m.m31, m.m32, m.m33, m.m34); - var row4 = Vector128.Create(m.m41, m.m42, m.m43, m.m44); + Vector128 vec = Vector128.Create(v.x, v.y, v.z, v.w); + Vector128 row1 = Vector128.Create(m.m11, m.m12, m.m13, m.m14); + Vector128 row2 = Vector128.Create(m.m21, m.m22, m.m23, m.m24); + Vector128 row3 = Vector128.Create(m.m31, m.m32, m.m33, m.m34); + Vector128 row4 = Vector128.Create(m.m41, m.m42, m.m43, m.m44); float tx = SimdMath.Dot4(row1, vec); float ty = SimdMath.Dot4(row2, vec); @@ -217,21 +291,7 @@ Matrix m float sw = m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w; return new Vector4(sx, sy, sz, sw); } - /// - /// Projects the supplied value onto the requested dimensional space. - /// - /// - /// The validated vector3 that represents the completed operation. - /// - // Project (useful in homogeneous coordinate systems) - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Vector3 ProjectToVector3() - { - if (w == 0f) - return new Vector3(x, y, z); // Avoid division by zero - return new Vector3(x / w, y / w, z / w); - } /// /// Adds the supplied values component by component. /// @@ -250,40 +310,37 @@ public Vector3 ProjectToVector3() public static Vector4 operator +( Vector4 a, Vector4 b - ) => - new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + ) => new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The first operand or interpolation endpoint. - /// - /// - /// The second operand or interpolation endpoint. + /// + /// The concrete value read or transformed by this operation. /// /// /// The validated vector4 that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4 operator -( - Vector4 a, - Vector4 b - ) => - new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + public static Vector4 operator -(Vector4 v) => new(-v.x, -v.y, -v.z, -v.w); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The concrete value read or transformed by this operation. + /// + /// The first operand or interpolation endpoint. + /// + /// + /// The second operand or interpolation endpoint. /// /// /// The validated vector4 that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4 operator -(Vector4 v) => - new(-v.x, -v.y, -v.z, -v.w); + public static Vector4 operator -( + Vector4 a, + Vector4 b + ) => new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); /// /// Multiplies the supplied values according to their algebraic contract. @@ -301,8 +358,7 @@ Vector4 b public static Vector4 operator *( Vector4 v, float s - ) => - new(v.x * s, v.y * s, v.z * s, v.w * s); + ) => new(v.x * s, v.y * s, v.z * s, v.w * s); /// /// Multiplies the supplied values according to their algebraic contract. @@ -321,7 +377,7 @@ float s float s, Vector4 v ) => v * s; - + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -338,14 +394,12 @@ Vector4 v public static Vector4 operator *( Matrix m, Vector4 v - ) { - return new Vector4( - m.m11 * v.x + m.m12 * v.y + m.m13 * v.z + m.m14 * v.w, - m.m21 * v.x + m.m22 * v.y + m.m23 * v.z + m.m24 * v.w, - m.m31 * v.x + m.m32 * v.y + m.m33 * v.z + m.m34 * v.w, - m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w - ); - } + ) => new Vector4( + m.m11 * v.x + m.m12 * v.y + m.m13 * v.z + m.m14 * v.w, + m.m21 * v.x + m.m22 * v.y + m.m23 * v.z + m.m24 * v.w, + m.m31 * v.x + m.m32 * v.y + m.m33 * v.z + m.m34 * v.w, + m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w + ); /// /// Divides the supplied value by the scalar divisor component by component. @@ -363,8 +417,7 @@ Vector4 v public static Vector4 operator /( Vector4 v, float s - ) => - new(v.x / s, v.y / s, v.z / s, v.w / s); + ) => new(v.x / s, v.y / s, v.z / s, v.w / s); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -382,11 +435,10 @@ float s public static bool operator ==( Vector4 a, Vector4 b - ) => - MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z) && - MathHelper.AlmostEquals(a.w, b.w); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z) + && MathHelper.AlmostEquals(a.w, b.w); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -405,7 +457,7 @@ Vector4 b Vector4 a, Vector4 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -415,7 +467,8 @@ Vector4 b /// /// The validated system.numerics.vector4 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector4(Vector4 v) => new(v.x, v.y, v.z, v.w); + public static implicit operator NumericsVector4(Vector4 v) => new(v.x, v.y, v.z, v.w); + /// /// Converts the supplied value to . /// @@ -425,40 +478,5 @@ Vector4 b /// /// The validated vector4 that represents the completed operation. /// - public static implicit operator Vector4(System.Numerics.Vector4 v) => new(v.X, v.Y, v.Z, v.W); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Vector4 other && this == other; - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector4 other) => this == other; - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, z, w); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {z}, {w})"; + public static implicit operator Vector4(NumericsVector4 v) => new(v.X, v.Y, v.Z, v.W); } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs index ea883a424..b87945830 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs @@ -10,22 +10,61 @@ namespace Inno.Core.Mathematics; [DataContract] public struct Vector4Int : IEquatable { + /// + /// A value whose components are all zero. + /// + + // Common vectors + public static readonly Vector4Int ZERO = new(0, 0, 0, 0); + + /// + /// A value whose components are all one. + /// + public static readonly Vector4Int ONE = new(1, 1, 1, 1); + + /// + /// A unit value aligned with the x axis. + /// + public static readonly Vector4Int UNIT_X = new(1, 0, 0, 0); + + /// + /// A unit value aligned with the y axis. + /// + public static readonly Vector4Int UNIT_Y = new(0, 1, 0, 0); + + /// + /// A unit value aligned with the z axis. + /// + public static readonly Vector4Int UNIT_Z = new(0, 0, 1, 0); + + /// + /// A unit value aligned with the w axis. + /// + public static readonly Vector4Int UNIT_W = new(0, 0, 0, 1); + /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; + /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; + /// /// The depth or third component. /// - [DataMember] public int z; + [DataMember] + public int z; + /// /// The homogeneous or fourth component. /// - [DataMember] public int w; + [DataMember] + public int w; /// /// Creates a vector from explicit component values. @@ -53,32 +92,45 @@ int w this.z = z; this.w = w; } - /// - /// A value whose components are all zero. - /// - // Common vectors - public static readonly Vector4Int ZERO = new(0, 0, 0, 0); /// - /// A value whose components are all one. - /// - public static readonly Vector4Int ONE = new(1, 1, 1, 1); - /// - /// A unit value aligned with the x axis. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Vector4Int UNIT_X = new(1, 0, 0, 0); + /// + /// The object compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public override bool Equals(object? obj) => obj is Vector4Int other && Equals(other); + /// - /// A unit value aligned with the y axis. + /// Determines whether this value and the supplied value represent the same logical state. /// - public static readonly Vector4Int UNIT_Y = new(0, 1, 0, 0); + /// + /// The strongly typed value compared with this value. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool Equals(Vector4Int other) => this == other; + /// - /// A unit value aligned with the z axis. + /// Computes a hash code consistent with the implemented equality contract. /// - public static readonly Vector4Int UNIT_Z = new(0, 0, 1, 0); + /// + /// The scalar result calculated from the supplied inputs. + /// + public override int GetHashCode() => HashCode.Combine(x, y, z, w); + /// - /// A unit value aligned with the w axis. + /// Formats this value as a human-readable component list. /// - public static readonly Vector4Int UNIT_W = new(0, 0, 0, 1); + /// + /// The validated text representation owned by the caller. + /// + public override string ToString() => $"({x}, {y}, {z}, {w})"; + /// /// Calculates the scalar dot product of two values. /// @@ -97,8 +149,8 @@ int w public static int Dot( Vector4Int a, Vector4Int b - ) => - a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + ) => a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + /// /// Clamps the interpolation factor to [0, 1] and truncates each interpolated component to an integer. /// @@ -130,6 +182,7 @@ float t (int)(a.w + (b.w - a.w) * t) ); } + /// /// Reflects an incident value across the supplied normal. /// @@ -152,6 +205,7 @@ Vector4Int normal int dot = Dot(vec, normal); return vec - 2 * dot * normal; } + /// /// Transforms the supplied value by the requested transformation. /// @@ -177,6 +231,7 @@ Matrix m int tw = (int)(m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w); return new Vector4Int(tx, ty, tz, tw); } + /// /// Adds the supplied values component by component. /// @@ -195,40 +250,37 @@ Matrix m public static Vector4Int operator +( Vector4Int a, Vector4Int b - ) => - new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + ) => new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The first operand or interpolation endpoint. - /// - /// - /// The second operand or interpolation endpoint. + /// + /// The concrete value read or transformed by this operation. /// /// /// The validated vector4int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4Int operator -( - Vector4Int a, - Vector4Int b - ) => - new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + public static Vector4Int operator -(Vector4Int v) => new(-v.x, -v.y, -v.z, -v.w); /// /// Subtracts or negates the supplied value component by component. /// - /// - /// The concrete value read or transformed by this operation. + /// + /// The first operand or interpolation endpoint. + /// + /// + /// The second operand or interpolation endpoint. /// /// /// The validated vector4int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4Int operator -(Vector4Int v) => - new(-v.x, -v.y, -v.z, -v.w); + public static Vector4Int operator -( + Vector4Int a, + Vector4Int b + ) => new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); /// /// Multiplies the supplied values according to their algebraic contract. @@ -246,8 +298,7 @@ Vector4Int b public static Vector4Int operator *( Vector4Int v, int s - ) => - new(v.x * s, v.y * s, v.z * s, v.w * s); + ) => new(v.x * s, v.y * s, v.z * s, v.w * s); /// /// Multiplies the supplied values according to their algebraic contract. @@ -266,7 +317,7 @@ int s int s, Vector4Int v ) => v * s; - + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -283,8 +334,7 @@ Vector4Int v public static Vector4Int operator /( Vector4Int v, int s - ) => - new(v.x / s, v.y / s, v.z / s, v.w / s); + ) => new(v.x / s, v.y / s, v.z / s, v.w / s); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -302,8 +352,7 @@ int s public static bool operator ==( Vector4Int a, Vector4Int b - ) => - a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; + ) => a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -322,6 +371,7 @@ Vector4Int b Vector4Int a, Vector4Int b ) => !(a == b); + /// /// Converts the supplied value to . /// @@ -334,8 +384,7 @@ Vector4Int b // Conversions [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Vector4(Vector4Int v) => - new(v.x, v.y, v.z, v.w); + public static explicit operator Vector4(Vector4Int v) => new(v.x, v.y, v.z, v.w); /// /// Converts the supplied value to . @@ -347,41 +396,5 @@ public static explicit operator Vector4(Vector4Int v) => /// The validated vector4int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Vector4Int(Vector4 v) => - new((int)v.x, (int)v.y, (int)v.z, (int)v.w); - - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The object compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public override bool Equals(object? obj) => obj is Vector4Int other && Equals(other); - /// - /// Determines whether this value and the supplied value represent the same logical state. - /// - /// - /// The strongly typed value compared with this value. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool Equals(Vector4Int other) => this == other; - /// - /// Computes a hash code consistent with the implemented equality contract. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - public override int GetHashCode() => HashCode.Combine(x, y, z, w); - /// - /// Formats this value as a human-readable component list. - /// - /// - /// The validated text representation owned by the caller. - /// - public override string ToString() => $"({x}, {y}, {z}, {w})"; + public static explicit operator Vector4Int(Vector4 v) => new((int)v.x, (int)v.y, (int)v.z, (int)v.w); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs index 9ed38b39e..50b690959 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs @@ -19,34 +19,46 @@ ref int index if (type is IArrayTypeSymbol array) { if (array.Rank != 1) + { return null; + } pending.Enqueue(array.ElementType); string element = Name(array.ElementType); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + element - + "), null, static values => BuildArray<" + element + ">(values), null, null)"; + + "), null, static values => BuildArray<" + element + ">(values), null, null)"; } if (type is not INamedTypeSymbol named || type.SpecialType == SpecialType.System_String) + { return null; + } INamedTypeSymbol[] contracts = new[] { named }.Concat(named.AllInterfaces).ToArray(); - INamedTypeSymbol? map = contracts.FirstOrDefault(static contract => + INamedTypeSymbol? map = contracts.FirstOrDefault(static contract => ( contract.OriginalDefinition.ToDisplayString() is "System.Collections.Generic.IDictionary" - or "System.Collections.Generic.IReadOnlyDictionary"); - INamedTypeSymbol? sequence = contracts.FirstOrDefault(static contract => - contract.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T); + or "System.Collections.Generic.IReadOnlyDictionary" + )); + INamedTypeSymbol? sequence = contracts.FirstOrDefault(static contract => ( + contract.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T + )); if (map is null && sequence?.TypeArguments[0] is INamedTypeSymbol entry - && entry.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.KeyValuePair") + && entry.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.KeyValuePair" + ) { map = entry; + } if (map is not null) { ITypeSymbol key = map.TypeArguments[0]; ITypeSymbol value = map.TypeArguments[1]; pending.Enqueue(key); pending.Enqueue(value); - INamedTypeSymbol dictionary = compilation.GetTypeByMetadataName("System.Collections.Generic.Dictionary`2")!.Construct(key, value); + INamedTypeSymbol dictionary = compilation + .GetTypeByMetadataName("System.Collections.Generic.Dictionary`2")! + .Construct(key, value); INamedTypeSymbol pair = compilation.GetTypeByMetadataName("System.Collections.Generic.KeyValuePair`2")!.Construct(key, value); string? construction = Construct(named, dictionary, [key, value], pair, compilation, accessors, ref index); if (construction is null) + { return null; + } string keyName = Name(key); string valueName = Name(value); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + valueName @@ -56,20 +68,26 @@ ref int index + Name(pair) + ">)value) result.Add(new(entry.Key, entry.Value)); return result; })"; } if (sequence is null) + { return null; + } ITypeSymbol elementType = sequence.TypeArguments[0]; pending.Enqueue(elementType); INamedTypeSymbol standard = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1")!.Construct(elementType); if (named.TypeKind == TypeKind.Interface && !compilation.ClassifyConversion(standard, named).IsImplicit) + { standard = compilation.GetTypeByMetadataName("System.Collections.Generic.HashSet`1")!.Construct(elementType); + } string? result = Construct(named, standard, [elementType], elementType, compilation, accessors, ref index); if (result is null) + { return null; + } string elementName = Name(elementType); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + elementName - + "), null, static values => { var result = new " + Name(standard) - + "(); foreach (var value in values) result.Add((" + elementName - + ")value!); return " + result + "; }, null, null)"; + + "), null, static values => { var result = new " + Name(standard) + + "(); foreach (var value in values) result.Add((" + elementName + + ")value!); return " + result + "; }, null, null)"; } private static string? Construct( @@ -82,64 +100,111 @@ ref int index ref int index ) { if (compilation.ClassifyConversion(standard, type).IsImplicit) + { return "result"; + } if (type.TypeKind == TypeKind.Interface || type.IsAbstract) + { return null; + } foreach (IMethodSymbol constructor in type.InstanceConstructors.Where(static constructor => constructor.Parameters.Length == 1)) { if (!compilation.ClassifyConversion(standard, constructor.Parameters[0].Type).IsImplicit) + { continue; + } if (IsAccessible(constructor, compilation)) + { return "new " + Name(type) + "(result)"; + } if (SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly)) { string name = "ConstructCollection" + index++; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" private static extern ").Append(Name(type)).Append(' ').Append(name).Append('(') - .Append(Name(constructor.Parameters[0].Type)).Append(" values);\n"); + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" private static extern ") + .Append(Name(type)) + .Append(' ') + .Append(name) + .Append('(') + .Append(Name(constructor.Parameters[0].Type)) + .Append(" values);\n"); return name + "(result)"; } } - foreach (IMethodSymbol factory in type.GetMembers().OfType().Where(static method => - method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 1 && method.Name is "CreateRange" or "Create")) - { + foreach (IMethodSymbol factory in type.GetMembers().OfType().Where(static method => ( + method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 1 && method.Name is "CreateRange" or "Create" + )) + ) { if (IsAccessible(factory, compilation) && compilation.ClassifyConversion(standard, factory.Parameters[0].Type).IsImplicit - && compilation.ClassifyConversion(factory.ReturnType, type).IsImplicit) + && compilation.ClassifyConversion(factory.ReturnType, type).IsImplicit + ) { return Name(type) + ".@" + factory.Name + "(result)"; + } } string definition = type.OriginalDefinition.ToDisplayString(); if (definition == "System.Collections.Immutable.ImmutableArray") + { return "global::System.Collections.Immutable.ImmutableArray.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableList") + { return "global::System.Collections.Immutable.ImmutableList.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableHashSet") + { return "global::System.Collections.Immutable.ImmutableHashSet.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableDictionary") + { return "global::System.Collections.Immutable.ImmutableDictionary.CreateRange(result)"; + } - IMethodSymbol? emptyConstructor = type.InstanceConstructors.FirstOrDefault(static constructor => constructor.Parameters.Length == 0); + IMethodSymbol? emptyConstructor = type.InstanceConstructors.FirstOrDefault( + static constructor => constructor.Parameters.Length == 0 + ); if (emptyConstructor is null || !IsAccessible(emptyConstructor, compilation)) + { return null; - IMethodSymbol? add = Ancestors(type).SelectMany(static owner => owner.GetMembers("Add")).OfType() - .FirstOrDefault(method => !method.IsStatic && !method.IsGenericMethod && IsAccessible(method, compilation) + } + IMethodSymbol? add = Ancestors(type).SelectMany(static owner => owner.GetMembers("Add")) + .OfType() + .FirstOrDefault(method => ( + !method.IsStatic && !method.IsGenericMethod && IsAccessible(method, compilation) && method.Parameters.Length == addArguments.Length - && method.Parameters.Select(static parameter => parameter.Type).SequenceEqual(addArguments, SymbolEqualityComparer.Default)); + && method.Parameters + .Select(static parameter => parameter.Type) + .SequenceEqual(addArguments, SymbolEqualityComparer.Default) + )); INamedTypeSymbol? addContract = null; if (add is null) { string contractName = addArguments.Length == 2 ? "System.Collections.Generic.IDictionary`2" : "System.Collections.Generic.ICollection`1"; INamedTypeSymbol contract = compilation.GetTypeByMetadataName(contractName)!.Construct(addArguments); if (!compilation.ClassifyConversion(type, contract).IsImplicit) + { return null; + } addContract = contract; } string builder = "BuildCollection" + index++; string receiver = addContract is null ? "value" : "((" + Name(addContract) + ")value)"; string addCall = addArguments.Length == 2 ? "entry.Key, entry.Value" : "entry"; - accessors.Append(" private static ").Append(Name(type)).Append(' ').Append(builder).Append('(') - .Append(Name(standard)).Append(" values)\n {\n var value = new ").Append(Name(type)) - .Append("();\n foreach (var entry in values)\n ").Append(receiver).Append(".Add(") - .Append(addCall).Append(");\n return value;\n }\n"); + accessors.Append(" private static ") + .Append(Name(type)) + .Append(' ') + .Append(builder) + .Append('(') + .Append(Name(standard)) + .Append(" values)\n {\n var value = new ") + .Append(Name(type)) + .Append("();\n foreach (var entry in values)\n ") + .Append(receiver) + .Append(".Add(") + .Append(addCall) + .Append(");\n return value;\n }\n"); return builder + "(result)"; } @@ -147,15 +212,18 @@ private static bool IsAccessible( ISymbol symbol, Compilation compilation ) => symbol.DeclaredAccessibility == Accessibility.Public - || symbol.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedOrInternal + || symbol.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedOrInternal && SymbolEqualityComparer.Default.Equals(symbol.ContainingAssembly, compilation.Assembly); private static IEnumerable Ancestors(INamedTypeSymbol type) { for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { yield return current; + } } - private static string Name(ITypeSymbol type) => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) - .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + private static string Name(ITypeSymbol type) + => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) + .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs index 8f6c95119..5193d8de4 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs @@ -3,7 +3,6 @@ using System.Collections.Immutable; using System.Linq; using System.Text; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; @@ -16,44 +15,47 @@ namespace Inno.Core.Serialization.Generators; [Generator(LanguageNames.CSharp)] public sealed class SerializationConverterGenerator : IIncrementalGenerator { - private const string C_GENERATE_ATTRIBUTE = - "Inno.Core.Serialization.GenerateSerializationConverterAttribute"; - private const string C_PROPERTY_ATTRIBUTE = - "Inno.Core.Serialization.SerializablePropertyAttribute"; - private const string C_SERIALIZABLE_INTERFACE = - "Inno.Core.Serialization.ISerializable"; - - private static readonly DiagnosticDescriptor s_invalidType = new( + private const string C_GENERATE_ATTRIBUTE = "Inno.Core.Serialization.GenerateSerializationConverterAttribute"; + + private const string C_PROPERTY_ATTRIBUTE = "Inno.Core.Serialization.SerializablePropertyAttribute"; + + private const string C_SERIALIZABLE_INTERFACE = "Inno.Core.Serialization.ISerializable"; + + private static readonly DiagnosticDescriptor INVALID_TYPE = new( "INNOSER001", "Invalid generated serialization type", "Type '{0}' must be a non-abstract, non-generic class implementing ISerializable", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); - private static readonly DiagnosticDescriptor s_missingConstructor = new( + private static readonly DiagnosticDescriptor MISSING_CONSTRUCTOR = new( "INNOSER002", "Generated serialization type requires a constructor", "Type '{0}' must expose a parameterless constructor accessible to generated code", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); - private static readonly DiagnosticDescriptor s_invalidMember = new( + private static readonly DiagnosticDescriptor INVALID_MEMBER = new( "INNOSER003", "Invalid generated serialization member", "Member '{0}' cannot participate in generated {1}", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); - private static readonly DiagnosticDescriptor s_duplicateKey = new( + private static readonly DiagnosticDescriptor DUPLICATE_KEY = new( "INNOSER004", "Duplicate generated serialization key", "Type '{0}' declares serialization key '{1}' more than once across its inheritance chain", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); /// /// Registers the incremental syntax and source-production pipeline. @@ -73,7 +75,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( attributeContext, _ - ) => (INamedTypeSymbol)attributeContext.TargetSymbol); + ) => (INamedTypeSymbol)attributeContext.TargetSymbol + ); context.RegisterSourceOutput(types, static ( productionContext, @@ -92,25 +95,35 @@ private static void GenerateCatalog( ImmutableArray types ) { if (types.IsEmpty) + { return; + } var source = new StringBuilder("// \n#nullable enable\n"); - source.Append("namespace ").Append(compilation.AssemblyName).Append(".Generated;\n") + source.Append("namespace ") + .Append(compilation.AssemblyName) + .Append(".Generated;\n") .Append("/// \n/// Contributes generated serialization declarations and direct factories.\n/// \n") .Append("public static class RuntimeSerializationCatalog\n{\n") - .Append(" /// \n /// Registers this assembly's generated converters without reflection discovery.\n /// \n") + .Append( + " /// \n /// Registers this assembly's generated converters without reflection discovery.\n /// \n" + ) .Append(" /// \n /// The composition callback; it is not retained.\n /// \n") .Append(" public static void Register(global::Inno.Extensibility.Catalogs.ITypeCatalogRegistrar register)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n"); foreach (INamedTypeSymbol type in types.Distinct(SymbolEqualityComparer.Default) - .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal)) - { + .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal) + ) { string converter = "global::" + GetNamespace(type) + ".__InnoGeneratedSerializationConverter_" + GetGeneratedName(type); source.Append(" register.Register(new global::Inno.Extensibility.Catalogs.TypeCatalogMetadata(typeof(") - .Append(converter).Append("), new global::System.Type[] { typeof(global::Inno.Core.Serialization.Converters.SerializationConverter<") + .Append(converter) + .Append("), new global::System.Type[] { typeof(global::Inno.Core.Serialization.Converters.SerializationConverter<") .Append(type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) .Append(" >), typeof(global::Inno.Core.Serialization.Converters.SerializationConverter) }, ") - .Append("global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty<(string, global::System.Type)>()), static () => new ") - .Append(converter).Append("());\n"); + .Append( + "global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty<(string, global::System.Type)>()), static () => new " + ) + .Append(converter) + .Append("());\n"); } source.Append(" }\n}\n"); output.AddSource("Registration/RuntimeSerialization.g.cs", source.ToString()); @@ -125,29 +138,27 @@ INamedTypeSymbol type || type.IsAbstract || type.IsGenericType || !ImplementsSerializable(type) - || !IsTypeAccessible(type)) - { - context.ReportDiagnostic(Diagnostic.Create(s_invalidType, location, type.ToDisplayString())); + || !IsTypeAccessible(type) + ) { + context.ReportDiagnostic(Diagnostic.Create(INVALID_TYPE, location, type.ToDisplayString())); return; } if (!HasAccessibleParameterlessConstructor(type)) { - context.ReportDiagnostic(Diagnostic.Create(s_missingConstructor, location, type.ToDisplayString())); + context.ReportDiagnostic(Diagnostic.Create(MISSING_CONSTRUCTOR, location, type.ToDisplayString())); return; } ImmutableArray members = CollectMembers(type); bool failed = false; foreach (IGrouping duplicate in members - .GroupBy(static member => member.name, StringComparer.Ordinal) - .Where(static group => group.Count() > 1)) - { - context.ReportDiagnostic(Diagnostic.Create( - s_duplicateKey, - duplicate.First().location, - type.ToDisplayString(), - duplicate.Key)); + .GroupBy(static member => member.name, StringComparer.Ordinal) + .Where(static group => group.Count() > 1) + ) { + context.ReportDiagnostic( + Diagnostic.Create(DUPLICATE_KEY, duplicate.First().location, type.ToDisplayString(), duplicate.Key) + ); failed = true; } @@ -155,26 +166,34 @@ INamedTypeSymbol type { if (member.serialize && !member.canRead) { - context.ReportDiagnostic(Diagnostic.Create( - s_invalidMember, - member.location, - member.displayName, - "serialization because it is not readable by generated code")); + context.ReportDiagnostic( + Diagnostic.Create( + INVALID_MEMBER, + member.location, + member.displayName, + "serialization because it is not readable by generated code" + ) + ); failed = true; } if (member.deserialize && !member.canWrite) { - context.ReportDiagnostic(Diagnostic.Create( - s_invalidMember, - member.location, - member.displayName, - "deserialization because it is not writable by generated code")); + context.ReportDiagnostic( + Diagnostic.Create( + INVALID_MEMBER, + member.location, + member.displayName, + "deserialization because it is not writable by generated code" + ) + ); failed = true; } } if (failed) + { return; + } string source = BuildSource(type, members); context.AddSource(GetGeneratedName(type) + ".g.cs", SourceText.From(source, Encoding.UTF8)); @@ -184,47 +203,58 @@ private static ImmutableArray CollectMembers(INamedTypeSymbo { var hierarchy = new Stack(); for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { hierarchy.Push(current); + } - var members = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder members = ImmutableArray.CreateBuilder(); while (hierarchy.Count > 0) { INamedTypeSymbol current = hierarchy.Pop(); foreach (ISymbol symbol in current.GetMembers().OrderBy(GetSourceOrder)) { - AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(static candidate => - candidate.AttributeClass?.ToDisplayString() == C_PROPERTY_ATTRIBUTE); + AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(static candidate => ( + candidate.AttributeClass?.ToDisplayString() == C_PROPERTY_ATTRIBUTE + )); if (attribute is null) + { continue; + } int visibility = attribute.ConstructorArguments.Length == 0 - ? 15 - : (int)(attribute.ConstructorArguments[0].Value ?? 15); + ? 15 + : (int)(attribute.ConstructorArguments[0].Value ?? 15); bool serialize = (visibility & 1) != 0; bool deserialize = (visibility & 2) != 0; switch (symbol) { case IPropertySymbol property: - members.Add(new SerializableMember( - property.Name, - property.ToDisplayString(), - property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - serialize, - deserialize, - IsAccessible(property.GetMethod), - IsAccessible(property.SetMethod) && !property.IsReadOnly, - property.Locations.FirstOrDefault() ?? Location.None)); + members.Add( + new SerializableMember( + property.Name, + property.ToDisplayString(), + property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + serialize, + deserialize, + IsAccessible(property.GetMethod), + IsAccessible(property.SetMethod) && !property.IsReadOnly, + property.Locations.FirstOrDefault() ?? Location.None + ) + ); break; case IFieldSymbol field: - members.Add(new SerializableMember( - field.Name, - field.ToDisplayString(), - field.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - serialize, - deserialize, - IsAccessible(field), - IsAccessible(field) && !field.IsReadOnly && !field.IsConst, - field.Locations.FirstOrDefault() ?? Location.None)); + members.Add( + new SerializableMember( + field.Name, + field.ToDisplayString(), + field.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + serialize, + deserialize, + IsAccessible(field), + IsAccessible(field) && !field.IsReadOnly && !field.IsConst, + field.Locations.FirstOrDefault() ?? Location.None + ) + ); break; } } @@ -245,23 +275,32 @@ ImmutableArray members source.AppendLine("namespace " + GetNamespace(type)); source.AppendLine("{"); source.AppendLine(" [global::System.CodeDom.Compiler.GeneratedCode(\"Inno.Core.Serialization.Generators\", \"1\")]"); - source.Append(" internal sealed class ").Append(converterName) + source.Append(" internal sealed class ") + .Append(converterName) .Append(" : global::Inno.Core.Serialization.Converters.SerializationConverter<") - .Append(targetType).AppendLine(">"); + .Append(targetType) + .AppendLine(">"); source.AppendLine(" {"); source.Append(" public override void Write(global::Inno.Core.Serialization.SerializationWriter writer, ") - .Append(targetType).AppendLine(" value)"); + .Append(targetType) + .AppendLine(" value)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(writer);"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(value);"); foreach (SerializableMember member in members.Where(static member => member.serialize)) { - source.Append(" writer.Write<").Append(member.typeName).Append(">(\"") - .Append(Escape(member.name)).Append("\", value.").Append(member.name).AppendLine(");"); + source.Append(" writer.Write<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .Append("\", value.") + .Append(member.name) + .AppendLine(");"); } source.AppendLine(" }"); source.AppendLine(); - source.Append(" public override ").Append(targetType) + source.Append(" public override ") + .Append(targetType) .AppendLine(" Read(global::Inno.Core.Serialization.SerializationReader reader)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(reader);"); @@ -271,14 +310,20 @@ ImmutableArray members source.AppendLine(" }"); source.AppendLine(); source.Append(" public override void Restore(global::Inno.Core.Serialization.SerializationReader reader, ") - .Append(targetType).AppendLine(" target)"); + .Append(targetType) + .AppendLine(" target)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(reader);"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(target);"); foreach (SerializableMember member in members.Where(static member => member.deserialize)) { - source.Append(" target.").Append(member.name).Append(" = reader.Read<") - .Append(member.typeName).Append(">(\"").Append(Escape(member.name)).AppendLine("\");"); + source.Append(" target.") + .Append(member.name) + .Append(" = reader.Read<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .AppendLine("\");"); } source.AppendLine(" }"); source.AppendLine(" }"); @@ -292,8 +337,13 @@ ImmutableArray members ) { foreach (SerializableMember member in members.Where(static member => member.deserialize)) { - source.Append(" value.").Append(member.name).Append(" = reader.Read<") - .Append(member.typeName).Append(">(\"").Append(Escape(member.name)).AppendLine("\");"); + source.Append(" value.") + .Append(member.name) + .Append(" = reader.Read<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .AppendLine("\");"); } } @@ -301,8 +351,9 @@ private static bool ImplementsSerializable(INamedTypeSymbol type) => type.AllInterfaces.Any(static contract => contract.ToDisplayString() == C_SERIALIZABLE_INTERFACE); private static bool HasAccessibleParameterlessConstructor(INamedTypeSymbol type) - => type.InstanceConstructors.Any(static constructor => - constructor.Parameters.Length == 0 && IsAccessible(constructor)); + => type.InstanceConstructors.Any(static constructor => ( + constructor.Parameters.Length == 0 && IsAccessible(constructor) + )); private static bool IsTypeAccessible(INamedTypeSymbol type) { @@ -310,8 +361,8 @@ private static bool IsTypeAccessible(INamedTypeSymbol type) { if (current.DeclaredAccessibility is Accessibility.Private or Accessibility.Protected - or Accessibility.ProtectedAndInternal) - { + or Accessibility.ProtectedAndInternal + ) { return false; } } @@ -320,23 +371,25 @@ or Accessibility.Protected private static bool IsAccessible(ISymbol? symbol) => symbol?.DeclaredAccessibility is Accessibility.Public - or Accessibility.Internal - or Accessibility.ProtectedOrInternal; + or Accessibility.Internal + or Accessibility.ProtectedOrInternal; private static int GetSourceOrder(ISymbol symbol) => symbol.Locations.FirstOrDefault(static location => location.IsInSource)?.SourceSpan.Start ?? int.MaxValue; private static string GetNamespace(INamedTypeSymbol type) => type.ContainingNamespace.IsGlobalNamespace - ? "InnoGeneratedSerialization" - : type.ContainingNamespace.ToDisplayString(); + ? "InnoGeneratedSerialization" + : type.ContainingNamespace.ToDisplayString(); private static string GetGeneratedName(INamedTypeSymbol type) { string name = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); var result = new StringBuilder(name.Length); foreach (char character in name) + { result.Append(char.IsLetterOrDigit(character) ? character : '_'); + } return result.ToString(); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs index f47a9933a..20b4787b4 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs @@ -17,50 +17,77 @@ public sealed class SerializationMetadataGenerator : IIncrementalGenerator private const string C_SERIALIZABLE = "Inno.Core.Serialization.ISerializable"; private const string C_PROPERTY = "Inno.Core.Serialization.SerializablePropertyAttribute"; private const string C_RESTORED = "Inno.Core.Serialization.OnSerializableRestored"; - private static readonly DiagnosticDescriptor InvalidMember = new( - "INNOSER010", "Invalid static serialization declaration", "Serialization member '{0}' cannot supply its declared access: {1}", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); - private static readonly DiagnosticDescriptor InvalidHook = new( - "INNOSER011", "Invalid static restoration callback", "Restoration declaration '{0}' must contain at most one nonstatic, nonvirtual void hook with zero arguments or one SerializationContext argument", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); - private static readonly DiagnosticDescriptor InvalidOwner = new( - "INNOSER012", "Inaccessible static serialization declaration", + private static readonly DiagnosticDescriptor INVALID_MEMBER = new( + "INNOSER010", + "Invalid static serialization declaration", + "Serialization member '{0}' cannot supply its declared access: {1}", + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); + + private static readonly DiagnosticDescriptor INVALID_HOOK = new( + "INNOSER011", + "Invalid static restoration callback", + "Restoration declaration '{0}' must contain at most one nonstatic, nonvirtual void hook with zero arguments or one SerializationContext argument", + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); + + private static readonly DiagnosticDescriptor INVALID_OWNER = new( + "INNOSER012", + "Inaccessible static serialization declaration", "Serialization declaration '{0}' requires a nongeneric partial containing owner; '{1}' cannot host its generated accessors", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); - /// + /// public void Initialize(IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(context.CompilationProvider, static ( + => context.RegisterSourceOutput(context.CompilationProvider, static ( output, compilation ) => Generate(output, compilation)); - } private static void Generate( SourceProductionContext output, Compilation compilation ) { if (compilation.AssemblyName is null || compilation.GetTypeByMetadataName(C_SERIALIZABLE) is null) + { return; + } var pending = new Queue(); foreach (INamedTypeSymbol type in EnumerateTypes(compilation.Assembly.GlobalNamespace)) + { if (IsSerializable(type)) + { pending.Enqueue(type); + } + } INamespaceSymbol serializationNamespace = compilation.GlobalNamespace.GetNamespaceMembers() - .Single(static scope => scope.Name == "Inno").GetNamespaceMembers() - .Single(static scope => scope.Name == "Core").GetNamespaceMembers() + .Single(static scope => scope.Name == "Inno") + .GetNamespaceMembers() + .Single(static scope => scope.Name == "Core") + .GetNamespaceMembers() .Single(static scope => scope.Name == "Serialization"); - var genericMethodNames = new HashSet(EnumerateTypes(serializationNamespace) - .SelectMany(static type => type.GetMembers().OfType()) - .Where(static method => method.IsGenericMethod).Select(static method => method.Name), StringComparer.Ordinal); + var genericMethodNames = new HashSet( + EnumerateTypes(serializationNamespace) + .SelectMany(static type => type.GetMembers().OfType()) + .Where(static method => method.IsGenericMethod) + .Select(static method => method.Name), + StringComparer.Ordinal + ); foreach (SyntaxTree tree in compilation.SyntaxTrees) { SemanticModel model = compilation.GetSemanticModel(tree); - foreach (InvocationExpressionSyntax syntax in tree.GetRoot(output.CancellationToken).DescendantNodes() - .OfType()) - { + foreach (InvocationExpressionSyntax syntax in tree.GetRoot(output.CancellationToken) + .DescendantNodes() + .OfType() + ) { string? methodName = syntax.Expression switch { SimpleNameSyntax name => name.Identifier.ValueText, @@ -69,12 +96,18 @@ Compilation compilation _ => null }; if (methodName is null || !genericMethodNames.Contains(methodName)) + { continue; + } if (model.GetSymbolInfo(syntax, output.CancellationToken).Symbol is IMethodSymbol method && (method.ContainingNamespace.ToDisplayString() == "Inno.Core.Serialization" - || method.ContainingNamespace.ToDisplayString().StartsWith("Inno.Core.Serialization.", StringComparison.Ordinal))) + || method.ContainingNamespace.ToDisplayString().StartsWith("Inno.Core.Serialization.", StringComparison.Ordinal)) + ) { foreach (ITypeSymbol argument in method.TypeArguments) + { pending.Enqueue(argument); + } + } } } var shapes = new HashSet(SymbolEqualityComparer.Default); @@ -85,26 +118,36 @@ Compilation compilation { ITypeSymbol type = pending.Dequeue().WithNullableAnnotation(NullableAnnotation.NotAnnotated); if (!shapes.Add(type) || ContainsParameters(type) || type is INamedTypeSymbol { IsRefLikeType: true }) + { continue; + } if (type is INamedTypeSymbol nullable && nullable.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) { pending.Enqueue(nullable.TypeArguments[0]); continue; } if (type.SpecialType != SpecialType.None || type.ToDisplayString() is "System.Guid" or "System.Decimal") + { continue; + } if (IsSerializable(type) && !SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly)) + { continue; + } ISymbol[] members = type is INamedTypeSymbol declaration ? CollectMembers(declaration, [declaration]).ToArray() : []; SerializationMetadataScope? scope = ResolveScope(type, members, compilation, root, scopes, rejectedOwners, output); if (scope is null) + { continue; + } GenerateMetadata(type, members, scope, compilation, pending, output); } output.AddSource("Registration/RuntimeSerializationMetadata.g.cs", root.Emit(compilation.AssemblyName)); int scopeIndex = 0; foreach (SerializationMetadataScope scope in scopes.Values) + { output.AddSource("Registration/RuntimeSerializationOwner" + scopeIndex++ + ".g.cs", scope.Emit(compilation.AssemblyName)); + } } private static void GenerateMetadata( @@ -119,28 +162,42 @@ SourceProductionContext output string typeName = Name(type); string? collection = SerializationCollectionGenerator.Generate(type, compilation, pending, accessors, ref scope.index); if (collection is null && !IsSerializable(type) && type.TypeKind != TypeKind.Struct) + { return; + } string creator = "CreateMetadata" + scope.index++; if (type is not INamedTypeSymbol named) { scope.registrations.Append(" register(").Append(creator).Append("());\n"); scope.creators.Append(" private static global::Inno.Core.Serialization.SerializationTypeMetadata ") - .Append(creator).Append("() => new(typeof(").Append(typeName) - .Append("), [], null, collection: ").Append(collection).Append(");\n"); + .Append(creator) + .Append("() => new(typeof(") + .Append(typeName) + .Append("), [], null, collection: ") + .Append(collection) + .Append(");\n"); scope.lookup.Append(" if (type == typeof(").Append(typeName).Append(")) return ").Append(creator).Append("();\n"); return; } if (members.Length == 0 && !IsSerializable(type) && collection is null) + { return; - var memberCode = new List(); + } + List memberCode = []; var keys = new HashSet(StringComparer.Ordinal); foreach (ISymbol member in members) { ITypeSymbol valueType = MemberType(member); if (!keys.Add(member.Name)) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, member.Locations.FirstOrDefault(), - member.ToDisplayString(), "duplicate key")); + output.ReportDiagnostic( + Diagnostic.Create( + INVALID_MEMBER, + member.Locations.FirstOrDefault(), + member.ToDisplayString(), + "duplicate key" + ) + ); continue; } pending.Enqueue(valueType); @@ -149,33 +206,56 @@ SourceProductionContext output string? setter = (visibility & 10) != 0 ? CreateAccessor(member, false, scope.index++, accessors) : null; if (((visibility & 5) != 0 && getter is null) || ((visibility & 10) != 0 && setter is null)) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, member.Locations.FirstOrDefault(), - member.ToDisplayString(), "required getter or writable setter is absent")); + output.ReportDiagnostic( + Diagnostic.Create( + INVALID_MEMBER, + member.Locations.FirstOrDefault(), + member.ToDisplayString(), + "required getter or writable setter is absent" + ) + ); continue; } - memberCode.Add("new global::Inno.Core.Serialization.SerializationMemberMetadata(" + Quote(member.Name) + memberCode.Add( + "new global::Inno.Core.Serialization.SerializationMemberMetadata(" + Quote(member.Name) + ", typeof(" + Name(valueType) + "), (global::Inno.Core.Serialization.PropertyVisibility)" - + visibility + ", " + (getter ?? "null") + ", " + (setter ?? "null") + ")"); + + visibility + ", " + (getter ?? "null") + ", " + (setter ?? "null") + ")" + ); } string factory = GenerateFactory(named, scope.index++, accessors); string hooks = GenerateHooks([named], ref scope.index, accessors, output); - bool requiresConverter = Ancestors(named).Any(static ancestor => ancestor.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.RequiresSerializationConverterAttribute")); + bool requiresConverter = Ancestors(named).Any(static ancestor => ancestor.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.RequiresSerializationConverterAttribute" + ))); string inherited = "null"; if (named.BaseType is INamedTypeSymbol baseType && IsSerializable(baseType)) { if (SymbolEqualityComparer.Default.Equals(baseType.ContainingAssembly, compilation.Assembly)) + { pending.Enqueue(baseType); + } inherited = "global::" + baseType.ContainingAssembly.Name - + ".Generated.RuntimeSerializationMetadataCatalog.GetMetadata(typeof(" + Name(baseType) + "))"; + + ".Generated.RuntimeSerializationMetadataCatalog.GetMetadata(typeof(" + Name(baseType) + "))"; } scope.registrations.Append(" register(").Append(creator).Append("());\n"); scope.lookup.Append(" if (type == typeof(").Append(typeName).Append(")) return ").Append(creator).Append("();\n"); scope.creators.Append(" private static global::Inno.Core.Serialization.SerializationTypeMetadata ") - .Append(creator).Append("() => new(typeof(") - .Append(typeName).Append("), [").Append(string.Join(", ", memberCode)).Append("], ") - .Append(factory).Append(", ").Append(hooks).Append(", ").Append(collection ?? "null") - .Append(", ").Append(requiresConverter ? "true" : "false").Append(", ").Append(inherited).Append(");\n"); + .Append(creator) + .Append("() => new(typeof(") + .Append(typeName) + .Append("), [") + .Append(string.Join(", ", memberCode)) + .Append("], ") + .Append(factory) + .Append(", ") + .Append(hooks) + .Append(", ") + .Append(collection ?? "null") + .Append(", ") + .Append(requiresConverter ? "true" : "false") + .Append(", ") + .Append(inherited) + .Append(");\n"); } private static SerializationMetadataScope? ResolveScope( @@ -189,15 +269,25 @@ SourceProductionContext output ) { ITypeSymbol[] referencedTypes = new[] { type }.Concat(members.Select(MemberType)).ToArray(); if (referencedTypes.All(value => IsAccessible(value, compilation.Assembly))) + { return root; + } INamedTypeSymbol? owner = FindInaccessibleOwner(type, compilation.Assembly) - ?? (type as INamedTypeSymbol); + ?? (type as INamedTypeSymbol); while (owner is not null && !referencedTypes.All(value => compilation.IsSymbolAccessibleWithin(value, owner))) + { owner = owner.ContainingType; + } if (owner is null) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, type.Locations.FirstOrDefault(), - type.ToDisplayString(), "no source owner can access all serialized member types")); + output.ReportDiagnostic( + Diagnostic.Create( + INVALID_MEMBER, + type.Locations.FirstOrDefault(), + type.ToDisplayString(), + "no source owner can access all serialized member types" + ) + ); return null; } var chain = new Stack(); @@ -206,8 +296,16 @@ SourceProductionContext output if (!SerializationMetadataScope.CanExtend(current)) { if (rejectedOwners.Add(current)) - output.ReportDiagnostic(Diagnostic.Create(InvalidOwner, current.Locations.FirstOrDefault(), - type.ToDisplayString(), current.ToDisplayString())); + { + output.ReportDiagnostic( + Diagnostic.Create( + INVALID_OWNER, + current.Locations.FirstOrDefault(), + type.ToDisplayString(), + current.ToDisplayString() + ) + ); + } return null; } chain.Push(current); @@ -231,12 +329,20 @@ SourceProductionContext output IAssemblySymbol assembly ) { if (type is IArrayTypeSymbol array) + { return FindInaccessibleOwner(array.ElementType, assembly); + } if (type is not INamedTypeSymbol named) + { return null; + } foreach (ITypeSymbol argument in named.TypeArguments) + { if (FindInaccessibleOwner(argument, assembly) is INamedTypeSymbol owner) + { return owner; + } + } return IsAccessible(named, assembly) ? null : named.ContainingType; } @@ -249,26 +355,32 @@ IEnumerable hierarchy ) { foreach (INamedTypeSymbol ancestor in hierarchy.Reverse()) { - foreach (ISymbol member in ancestor.GetMembers().Where(static member => !member.IsStatic) - .OrderBy(GetOrder).ThenBy(static member => member.Locations.FirstOrDefault()?.SourceSpan.Start ?? int.MaxValue)) - { + foreach (ISymbol member in ancestor.GetMembers() + .Where(static member => !member.IsStatic) + .OrderBy(GetOrder) + .ThenBy(static member => member.Locations.FirstOrDefault()?.SourceSpan.Start ?? int.MaxValue) + ) { bool annotated = member.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY); bool defaultStructMember = type.TypeKind == TypeKind.Struct && (member is IFieldSymbol { DeclaredAccessibility: Accessibility.Public, IsReadOnly: false, IsConst: false } || member is IPropertySymbol { GetMethod.DeclaredAccessibility: Accessibility.Public, SetMethod.DeclaredAccessibility: Accessibility.Public, IsIndexer: false }); if ((annotated || defaultStructMember) && member is IFieldSymbol or IPropertySymbol { IsIndexer: false }) + { yield return member; + } } } } private static int GetOrder(ISymbol member) - => member.GetAttributes().FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) + => member.GetAttributes() + .FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) ?.NamedArguments.FirstOrDefault(static argument => argument.Key == "order").Value.Value as int? ?? int.MaxValue; private static int GetVisibility(ISymbol member) - => member.GetAttributes().FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) + => member.GetAttributes() + .FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) ?.ConstructorArguments.FirstOrDefault().Value as int? ?? 15; private static string? CreateAccessor( @@ -281,35 +393,65 @@ StringBuilder accessors ITypeSymbol valueType = member is IFieldSymbol field ? field.Type : ((IPropertySymbol)member).Type; string value = Name(valueType); bool isStruct = member.ContainingType.IsValueType; - string target = isStruct ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" - : "(" + declaring + ")target"; + string target = isStruct + ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" + : "(" + declaring + ")target"; if (member is IFieldSymbol fieldMember) { if (!read && (fieldMember.IsReadOnly || fieldMember.IsConst)) + { return null; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = ") - .Append(Quote(member.Name)).Append(")]\n private static extern ref ").Append(value) - .Append(" Access").Append(index).Append("(").Append(isStruct ? "ref " : "").Append(declaring).Append(" target);\n"); - return read ? "static target => Access" + index + "(" + target + ")" - : "static (target, value) => Access" + index + "(" + target + ") = (" + value + ")value!"; + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = " + ) + .Append(Quote(member.Name)) + .Append(")]\n private static extern ref ") + .Append(value) + .Append(" Access") + .Append(index) + .Append("(") + .Append(isStruct ? "ref " : string.Empty) + .Append(declaring) + .Append(" target);\n"); + return read + ? "static target => Access" + index + "(" + target + ")" + : "static (target, value) => Access" + index + "(" + target + ") = (" + value + ")value!"; } IPropertySymbol property = (IPropertySymbol)member; IMethodSymbol? method = read ? property.GetMethod : property.SetMethod; if (method is null || (!read && method.IsInitOnly)) + { return null; + } if (method.DeclaredAccessibility == Accessibility.Public) { - string receiver = isStruct ? "global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" - : "((" + declaring + ")target)"; - return read ? "static target => " + receiver + ".@" + member.Name - : "static (target, value) => " + receiver + ".@" + member.Name + " = (" + value + ")value!"; - } - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = ") - .Append(Quote(method.MetadataName)).Append(")]\n private static extern ").Append(read ? value : "void") - .Append(" Access").Append(index).Append("(").Append(isStruct ? "ref " : "").Append(declaring).Append(" target") - .Append(read ? "" : ", " + value + " value").Append(");\n"); - return read ? "static target => Access" + index + "(" + target + ")" - : "static (target, value) => Access" + index + "(" + target + ", (" + value + ")value!)"; + string receiver = isStruct + ? "global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" + : "((" + declaring + ")target)"; + return read + ? "static target => " + receiver + ".@" + member.Name + : "static (target, value) => " + receiver + ".@" + member.Name + " = (" + value + ")value!"; + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = " + ) + .Append(Quote(method.MetadataName)) + .Append(")]\n private static extern ") + .Append(read ? value : "void") + .Append(" Access") + .Append(index) + .Append("(") + .Append(isStruct ? "ref " : string.Empty) + .Append(declaring) + .Append(" target") + .Append(read ? string.Empty : ", " + value + " value") + .Append(");\n"); + return read + ? "static target => Access" + index + "(" + target + ")" + : "static (target, value) => Access" + index + "(" + target + ", (" + value + ")value!)"; } private static string GenerateFactory( @@ -318,17 +460,34 @@ private static string GenerateFactory( StringBuilder accessors ) { if (type.IsValueType) + { return "static () => default(" + Name(type) + ")"; + } if (type.IsAbstract || type.TypeKind != TypeKind.Class || Ancestors(type).Any(static ancestor => - ancestor.GetMembers().Any(static member => member is IPropertySymbol { IsRequired: true } or IFieldSymbol { IsRequired: true }))) + ancestor + .GetMembers() + .Any(static member => member is IPropertySymbol { IsRequired: true } or IFieldSymbol { IsRequired: true })) + ) { return "null"; + } IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static constructor => constructor.Parameters.Length == 0); if (constructor is null) + { return "null"; + } if (constructor.DeclaredAccessibility == Accessibility.Public) + { return "static () => new " + Name(type) + "()"; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" private static extern ").Append(Name(type)).Append(" Construct").Append(index).Append("();\n"); + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" private static extern ") + .Append(Name(type)) + .Append(" Construct") + .Append(index) + .Append("();\n"); return "static () => Construct" + index + "()"; } @@ -338,32 +497,43 @@ private static string GenerateHooks( StringBuilder accessors, SourceProductionContext output ) { - var calls = new List(); + List calls = []; foreach (INamedTypeSymbol ancestor in hierarchy.Reverse()) { IMethodSymbol[] hooks = ancestor.GetMembers().OfType().Where(static method => method.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == C_RESTORED)).ToArray(); if (hooks.Length > 1) - output.ReportDiagnostic(Diagnostic.Create(InvalidHook, ancestor.Locations.FirstOrDefault(), ancestor.ToDisplayString())); + { + output.ReportDiagnostic(Diagnostic.Create(INVALID_HOOK, ancestor.Locations.FirstOrDefault(), ancestor.ToDisplayString())); + } foreach (IMethodSymbol hook in hooks) { if (hook.IsStatic || hook.IsVirtual || hook.IsOverride || hook.IsAbstract || hook.IsGenericMethod || !hook.ReturnsVoid || hook.Parameters.Length > 1 || hook.Parameters.Length == 1 && (hook.Parameters[0].RefKind != RefKind.None - || hook.Parameters[0].Type.ToDisplayString() != "Inno.Core.Serialization.SerializationContext")) - { - output.ReportDiagnostic(Diagnostic.Create(InvalidHook, hook.Locations.FirstOrDefault(), hook.ToDisplayString())); + || hook.Parameters[0].Type.ToDisplayString() != "Inno.Core.Serialization.SerializationContext") + ) { + output.ReportDiagnostic(Diagnostic.Create(INVALID_HOOK, hook.Locations.FirstOrDefault(), hook.ToDisplayString())); continue; } string name = "Restore" + index++; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = ") - .Append(Quote(hook.MetadataName)).Append(")]\n private static extern void ").Append(name) - .Append("(").Append(ancestor.IsValueType ? "ref " : "").Append(Name(ancestor)).Append(" target") - .Append(hook.Parameters.Length == 0 ? "" : ", global::Inno.Core.Serialization.SerializationContext context") + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = " + ) + .Append(Quote(hook.MetadataName)) + .Append(")]\n private static extern void ") + .Append(name) + .Append("(") + .Append(ancestor.IsValueType ? "ref " : string.Empty) + .Append(Name(ancestor)) + .Append(" target") + .Append(hook.Parameters.Length == 0 ? string.Empty : ", global::Inno.Core.Serialization.SerializationContext context") .Append(");\n"); - string target = ancestor.IsValueType ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + Name(ancestor) + ">(target)" - : "(" + Name(ancestor) + ")target"; - calls.Add(name + "(" + target + (hook.Parameters.Length == 0 ? "" : ", context") + ");"); + string target = ancestor.IsValueType + ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + Name(ancestor) + ">(target)" + : "(" + Name(ancestor) + ")target"; + calls.Add(name + "(" + target + (hook.Parameters.Length == 0 ? string.Empty : ", context") + ");"); } } return calls.Count == 0 ? "null" : "static (target, context) => { " + string.Join(" ", calls) + " }"; @@ -371,8 +541,11 @@ SourceProductionContext output private static IEnumerable Ancestors(INamedTypeSymbol type) { - for (INamedTypeSymbol? current = type; current is not null && current.SpecialType != SpecialType.System_Object; current = current.BaseType) + for (INamedTypeSymbol? current = type; current is not null + && current.SpecialType != SpecialType.System_Object; current = current.BaseType + ) { yield return current; + } } private static IEnumerable EnumerateTypes(INamespaceOrTypeSymbol scope) @@ -380,10 +553,16 @@ private static IEnumerable EnumerateTypes(INamespaceOrTypeSymb foreach (ISymbol member in scope.GetMembers()) { if (member is INamedTypeSymbol type) + { yield return type; + } if (member is INamespaceOrTypeSymbol nested) + { foreach (INamedTypeSymbol nestedType in EnumerateTypes(nested)) + { yield return nestedType; + } + } } } @@ -392,27 +571,36 @@ private static bool IsSerializable(ITypeSymbol type) private static bool ContainsParameters(ITypeSymbol type) => type.TypeKind == TypeKind.TypeParameter || type is INamedTypeSymbol named && (named.TypeArguments.Any(ContainsParameters) - || named.ContainingType is not null && ContainsParameters(named.ContainingType)) - || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); + || named.ContainingType is not null && ContainsParameters(named.ContainingType)) + || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); private static bool IsAccessible( ITypeSymbol type, IAssemblySymbol assembly ) { if (type is IArrayTypeSymbol array) + { return IsAccessible(array.ElementType, assembly); + } if (type is not INamedTypeSymbol named) + { return false; + } for (INamedTypeSymbol? current = named; current is not null; current = current.ContainingType) + { if (current.IsFileLocal || current.DeclaredAccessibility != Accessibility.Public && (current.ContainingAssembly is null || !SymbolEqualityComparer.Default.Equals(current.ContainingAssembly, assembly) - || current.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal))) + || current.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal)) + ) { return false; + } + } return named.TypeArguments.All(argument => argument.TypeKind == TypeKind.TypeParameter || IsAccessible(argument, assembly)); } - private static string Name(ITypeSymbol type) => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) - .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + private static string Name(ITypeSymbol type) + => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) + .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); private static string Quote(string value) => SymbolDisplay.FormatLiteral(value, quote: true); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs index d07ee5f0c..1155fa8c0 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs @@ -13,7 +13,10 @@ internal sealed class SerializationMetadataScope private readonly List m_children = []; private int m_index; - internal SerializationMetadataScope(INamedTypeSymbol? owner) => this.owner = owner; + internal SerializationMetadataScope(INamedTypeSymbol? owner) + { + this.owner = owner; + } internal INamedTypeSymbol? owner { get; } internal StringBuilder registrations { get; } = new(); @@ -29,66 +32,103 @@ internal string Emit(string assemblyName) var code = new StringBuilder("// \n#nullable enable\n"); var owners = new Stack(); for (INamedTypeSymbol? current = owner; current is not null; current = current.ContainingType) + { owners.Push(current); - string namespaceName = owner is null ? assemblyName + ".Generated" - : owner.ContainingNamespace.IsGlobalNamespace ? "" : owner.ContainingNamespace.ToDisplayString(); + } + string namespaceName = owner is null + ? assemblyName + ".Generated" + : owner.ContainingNamespace.IsGlobalNamespace ? string.Empty : owner.ContainingNamespace.ToDisplayString(); if (namespaceName.Length > 0) + { code.Append("namespace ").Append(namespaceName).Append(";\n"); + } foreach (INamedTypeSymbol declaration in owners) + { code.Append(Declaration(declaration)).Append("\n{\n"); + } bool root = owner is null; if (root) + { code.Append("/// \n/// Supplies closed serialization access and construction for this assembly.\n/// \n"); - code.Append(root ? "public" : "internal").Append(" static class ") - .Append(root ? "RuntimeSerializationMetadataCatalog" : C_CATALOG).Append("\n{\n") - .Append(" /// \n /// Contributes generated metadata without retaining the composition callback.\n /// \n") + } + code.Append(root ? "public" : "internal") + .Append(" static class ") + .Append(root ? "RuntimeSerializationMetadataCatalog" : C_CATALOG) + .Append("\n{\n") + .Append( + " /// \n /// Contributes generated metadata without retaining the composition callback.\n /// \n" + ) .Append(" /// \n /// The composition-owned registration callback.\n /// \n") - .Append(" /// \n /// The callback is null.\n /// \n") - .Append(" ").Append(root ? "public" : "internal") - .Append(" static void Register(global::System.Action register)\n {\n") + .Append( + " /// \n /// The callback is null.\n /// \n" + ) + .Append(" ") + .Append(root ? "public" : "internal") + .Append( + " static void Register(global::System.Action register)\n {\n" + ) .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n") .Append(registrations); foreach (SerializationMetadataScope child in m_children) + { code.Append(" ").Append(ChildName(child, root)).Append(".Register(register);\n"); + } code.Append(" }\n") .Append(" /// \n /// Creates metadata through its declaration's generated accessors.\n /// \n") .Append(" /// \n /// The exact closed declaration.\n /// \n") .Append(" /// \n /// Complete access metadata for an owned declaration.\n /// \n") - .Append(" /// \n /// The declaration is null.\n /// \n") - .Append(" ").Append(root ? "public" : "internal") + .Append( + " /// \n /// The declaration is null.\n /// \n" + ) + .Append(" ") + .Append(root ? "public" : "internal") .Append(" static global::Inno.Core.Serialization.SerializationTypeMetadata") - .Append(root ? " GetMetadata" : "? FindMetadata").Append("(global::System.Type type)\n {\n") + .Append(root ? " GetMetadata" : "? FindMetadata") + .Append("(global::System.Type type)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(type);\n") .Append(lookup); if (m_children.Count > 0) { code.Append(" global::Inno.Core.Serialization.SerializationTypeMetadata? metadata;\n"); foreach (SerializationMetadataScope child in m_children) - code.Append(" metadata = ").Append(ChildName(child, root)).Append(".FindMetadata(type);\n") + { + code.Append(" metadata = ") + .Append(ChildName(child, root)) + .Append(".FindMetadata(type);\n") .Append(" if (metadata is not null) return metadata;\n"); + } } - code.Append(root + code + .Append( + root ? " throw new global::System.ArgumentException(\"The serialization declaration is not registered.\", nameof(type));\n" - : " return null;\n") - .Append(" }\n").Append(creators).Append(accessors) + : " return null;\n" + ) + .Append(" }\n") + .Append(creators) + .Append(accessors) .Append(" private static T[] BuildArray(global::System.Collections.Generic.IReadOnlyList values)\n {\n") .Append(" var result = new T[values.Count];\n for (int index = 0; index < result.Length; index++)\n") .Append(" result[index] = (T)values[index]!;\n return result;\n }\n}\n"); foreach (INamedTypeSymbol _ in owners) + { code.Append("}\n"); + } return code.ToString(); } internal static bool CanExtend(INamedTypeSymbol owner) => owner.TypeParameters.Length == 0 && !owner.IsFileLocal && owner.DeclaringSyntaxReferences.Length > 0 - && owner.DeclaringSyntaxReferences.All(static reference => reference.GetSyntax() is TypeDeclarationSyntax syntax - && syntax.Modifiers.Any(SyntaxKind.PartialKeyword)); + && owner.DeclaringSyntaxReferences.All(static reference => ( + reference.GetSyntax() is TypeDeclarationSyntax syntax + && syntax.Modifiers.Any(SyntaxKind.PartialKeyword) + )); private static string ChildName( SerializationMetadataScope child, bool root ) => (root ? child.owner!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) : "@" + child.owner!.Name) - + "." + C_CATALOG; + + "." + C_CATALOG; private static string Declaration(INamedTypeSymbol type) { @@ -101,9 +141,10 @@ private static string Declaration(INamedTypeSymbol type) Accessibility.ProtectedAndInternal => "private protected", _ => "internal" }; - string modifiers = type.IsStatic ? " static" : type.IsReadOnly ? " readonly" : ""; - string kind = type.IsRecord ? type.IsValueType ? "record struct" : "record class" - : type.TypeKind == TypeKind.Struct ? "struct" : "class"; + string modifiers = type.IsStatic ? " static" : type.IsReadOnly ? " readonly" : string.Empty; + string kind = type.IsRecord + ? type.IsValueType ? "record struct" : "record class" + : type.TypeKind == TypeKind.Struct ? "struct" : "class"; return visibility + modifiers + " partial " + kind + " @" + type.Name; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs b/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs index d491dd6e6..be5ea888d 100644 --- a/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs +++ b/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs @@ -11,6 +11,17 @@ namespace Inno.Core.Serialization; [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class SerializablePropertyAttribute : Attribute { + /// + /// Initializes a new instance of the class. + /// + /// + /// The member visibility in the serialization graph. + /// + public SerializablePropertyAttribute(PropertyVisibility visibility = PropertyVisibility.Show) + { + this.propertyVisibility = visibility; + } + /// /// Gets or sets the member order within its declaring type. /// @@ -23,15 +34,4 @@ public sealed class SerializablePropertyAttribute : Attribute /// Gets the visibility of the annotated member. /// public PropertyVisibility propertyVisibility { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The member visibility in the serialization graph. - /// - public SerializablePropertyAttribute(PropertyVisibility visibility = PropertyVisibility.Show) - { - propertyVisibility = visibility; - } } diff --git a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs index 6b5262e40..8ecad617b 100644 --- a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs +++ b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs @@ -4,6 +4,8 @@ using Inno.Core.Identity; using Inno.Core.Serialization.Converters; +using CoreIdentity = Inno.Core.Identity.Identity; + namespace Inno.Core.Serialization; /// @@ -21,7 +23,7 @@ public sealed class SerializationCaptureKeyBuilder private const byte C_GUARD = 4; internal const byte C_GUID = 5; - private readonly int m_threadId = Environment.CurrentManagedThreadId; + private readonly int m_threadID = Environment.CurrentManagedThreadId; private SerializationCaptureIdentity[] m_identities = []; private int m_identityCount; private SerializationOperation? m_operation; @@ -31,28 +33,29 @@ public sealed class SerializationCaptureKeyBuilder private int m_capacity; private bool m_unavailable; + internal SerializationCaptureKeyBuilder( + SerializationOperation operation, + SerializationCaptureKey? previous + ) { + m_operation = operation; + m_previous = previous; + Add(new SerializationCaptureKeyPart(C_GUARD, default, 0, operation.converters.captureIdentity, null)); + } + internal SerializationCaptureKeyBuilder( SerializationOperation operation, Type rootType, - Inno.Core.Identity.Identity source, + CoreIdentity source, SerializationCaptureKey? previous - ) : this(operation, previous) { + ) : this(operation, previous) + { if (source.runtimeIdentity is not { } identity) { m_unavailable = true; return; } - Add(new(C_GUARD, identity, 0, operation.GetMetadata(rootType).captureIdentity, null)); - AddIdentity(new(source, identity)); - } - - internal SerializationCaptureKeyBuilder( - SerializationOperation operation, - SerializationCaptureKey? previous - ) { - m_operation = operation; - m_previous = previous; - Add(new(C_GUARD, default, 0, operation.converters.captureIdentity, null)); + Add(new SerializationCaptureKeyPart(C_GUARD, identity, 0, operation.GetMetadata(rootType).captureIdentity, null)); + AddIdentity(new SerializationCaptureIdentity(source, identity)); } /// @@ -108,11 +111,13 @@ public bool TryAddOwner( ) { RequireOperation(); ArgumentNullException.ThrowIfNull(source); - Inno.Core.Identity.Identity snapshot = source.identity; + CoreIdentity snapshot = source.identity; if (!revision.HasValue || snapshot.runtimeIdentity is not { } identity) + { return Decline(); - Add(new(C_OWNER, identity, revision.Value, default, null)); - AddIdentity(new(snapshot, identity)); + } + Add(new SerializationCaptureKeyPart(C_OWNER, identity, revision.Value, default, null)); + AddIdentity(new SerializationCaptureIdentity(snapshot, identity)); return true; } @@ -136,25 +141,37 @@ public bool TryAddProperties(ISerializable source) SerializationOperation operation = RequireOperation(); ArgumentNullException.ThrowIfNull(source); if (source is not IdentityObject identified) + { return Decline(); - Inno.Core.Identity.Identity snapshot = identified.identity; + } + CoreIdentity snapshot = identified.identity; if (snapshot.runtimeIdentity is not { } identity) + { return Decline(); + } ISerializationMetadataSource provider = operation.context.GetRequired(); SerializationTypeMetadata metadata = provider.GetMetadata(source.GetType()); if (metadata.captureRevision is null) { foreach (SerializationMemberMetadata member in metadata.members) + { if ((member.visibility & PropertyVisibility.Serialize) != 0) + { return Decline(); + } + } } if (!operation.converters.CanReuseRevision(metadata, provider)) + { return Decline(); + } ulong? revision = metadata.captureRevision is { } readRevision ? readRevision(source) : 0; if (!revision.HasValue) + { return Decline(); - Add(new(C_OWNER, identity, revision.Value, metadata.captureIdentity, null)); - AddIdentity(new(snapshot, identity)); + } + Add(new SerializationCaptureKeyPart(C_OWNER, identity, revision.Value, metadata.captureIdentity, null)); + AddIdentity(new SerializationCaptureIdentity(snapshot, identity)); return true; } @@ -167,7 +184,7 @@ public bool TryAddProperties(ISerializable source) /// /// The callback has retired or is accessed from another thread. /// - public void AddValue(ulong value) => Add(new(C_VALUE, default, value, default, null)); + public void AddValue(ulong value) => Add(new SerializationCaptureKeyPart(C_VALUE, default, value, default, null)); /// /// Adds an exact neutral identifier without hashing or allocating text. @@ -178,7 +195,7 @@ public bool TryAddProperties(ISerializable source) /// /// The callback has retired or is accessed from another thread. /// - public void AddValue(Guid value) => Add(new(C_GUID, default, 0, value, null)); + public void AddValue(Guid value) => Add(new SerializationCaptureKeyPart(C_GUID, default, 0, value, null)); /// /// Adds exact ordinal text, preserving the distinction between null and empty. @@ -189,19 +206,25 @@ public bool TryAddProperties(ISerializable source) /// /// The callback has retired or is accessed from another thread. /// - public void AddText(string? value) => Add(new(C_TEXT, default, 0, default, value)); + public void AddText(string? value) => Add(new SerializationCaptureKeyPart(C_TEXT, default, 0, default, value)); internal SerializationCaptureAttempt Complete() { RequireOperation(); if (m_unavailable || m_identityCount == 0) - return SerializationCaptureAttempt.empty; + { + return SerializationCaptureAttempt.EMPTY; + } SerializationCaptureKey key = m_parts is null && m_previous is not null && m_previous.parts.Length == m_count - ? m_previous - : new(m_parts is not null ? m_parts.ToArray() : m_previous!.parts.AsSpan(0, m_count).ToArray()); + ? m_previous + : new SerializationCaptureKey( + m_parts is not null ? m_parts.ToArray() : m_previous!.parts.AsSpan(0, m_count).ToArray() + ); ReadOnlySpan identities = m_identities.AsSpan(0, m_identityCount); foreach (SerializationCaptureIdentity identity in identities) + { identity.Validate(); + } return new(key, ReferenceEquals(key, m_previous) ? [] : identities.ToArray()); } @@ -215,14 +238,19 @@ internal void Retire() m_identities = []; m_identityCount = 0; if (identities.Length > 0) + { ArrayPool.Shared.Return(identities, clearArray: true); + } } private SerializationOperation RequireOperation() { - SerializationOperation operation = m_operation ?? throw new InvalidOperationException("The serialization key callback has retired."); - if (Environment.CurrentManagedThreadId != m_threadId) + SerializationOperation operation = m_operation + ?? throw new InvalidOperationException("The serialization key callback has retired."); + if (Environment.CurrentManagedThreadId != m_threadID) + { throw new InvalidOperationException("The serialization key callback belongs to another thread."); + } operation.EnsureActive(); return operation; } @@ -242,13 +270,17 @@ private void AddIdentity(SerializationCaptureIdentity identity) private void EnsureIdentityCapacity(int capacity) { if (capacity <= m_identities.Length) + { return; + } SerializationCaptureIdentity[] identities = ArrayPool.Shared.Rent(capacity); m_identities.AsSpan(0, m_identityCount).CopyTo(identities); SerializationCaptureIdentity[] previous = m_identities; m_identities = identities; if (previous.Length > 0) + { ArrayPool.Shared.Return(previous, clearArray: true); + } } private void Add(SerializationCaptureKeyPart part) @@ -263,8 +295,12 @@ private void Add(SerializationCaptureKeyPart part) { m_parts = new(Math.Max(m_capacity, m_count + 1)); if (m_previous is not null) + { for (int index = 0; index < m_count; index++) + { m_parts.Add(m_previous.parts[index]); + } + } } m_parts.Add(part); m_count++; @@ -276,15 +312,19 @@ internal sealed record SerializationCaptureKey(SerializationCaptureKeyPart[] par internal bool HasSameInputs(SerializationCaptureKey other) { if (parts.Length != other.parts.Length) + { return false; + } for (int index = 0; index < parts.Length; index++) { SerializationCaptureKeyPart before = parts[index]; SerializationCaptureKeyPart after = other.parts[index]; - if (before.kind != after.kind || before.identity != after.identity || - before.revision != after.revision || !string.Equals(before.text, after.text, StringComparison.Ordinal) || - before.kind == SerializationCaptureKeyBuilder.C_GUID && before.metadata != after.metadata) + if (before.kind != after.kind || before.identity != after.identity + || before.revision != after.revision || !string.Equals(before.text, after.text, StringComparison.Ordinal) + || before.kind == SerializationCaptureKeyBuilder.C_GUID && before.metadata != after.metadata + ) { return false; + } } return true; } @@ -294,7 +334,29 @@ internal readonly record struct SerializationCaptureAttempt( SerializationCaptureKey? key, SerializationCaptureIdentity[] identities ) { - internal static readonly SerializationCaptureAttempt empty = new(null, []); + internal static readonly SerializationCaptureAttempt EMPTY = new(null, []); + + internal SerializationCaptureKey? Verify(SerializationCaptureAttempt after) + { + if (key is null || after.key is null || !key.HasSameInputs(after.key)) + { + throw new InvalidOperationException("The declared serialization capture inputs changed during the write."); + } + // Fresh equivalent metadata preserves ordinary capture without publishing a reusable hint. + return ReferenceEquals(after.key, key) ? key : null; + } + + internal void ValidateIdentities() + { + if (identities is null) + { + return; + } + foreach (SerializationCaptureIdentity identity in identities) + { + identity.Validate(); + } + } internal static SerializationCaptureAttempt Capture( SerializationOperation operation, @@ -305,50 +367,44 @@ internal static SerializationCaptureAttempt Capture( Func? captureKey = null ) { if (!operation.isSnapshotCapture) - return empty; + { + return EMPTY; + } SerializationCaptureKeyBuilder builder; if (captureKey is not null) + { builder = new(operation, previous); + } else if (value is IdentityObject identified && identified.identity.runtimeIdentity is not null) + { builder = new(operation, valueType, identified.identity, previous); + } else - return empty; + { + return EMPTY; + } try { bool complete = captureKey is not null ? captureKey(value, builder) : converter!.CaptureKey(value, builder); - return complete ? builder.Complete() : empty; + return complete ? builder.Complete() : EMPTY; } finally { builder.Retire(); } } - - internal SerializationCaptureKey? Verify(SerializationCaptureAttempt after) - { - if (key is null || after.key is null || !key.HasSameInputs(after.key)) - throw new InvalidOperationException("The declared serialization capture inputs changed during the write."); - // Fresh equivalent metadata preserves ordinary capture without publishing a reusable hint. - return ReferenceEquals(after.key, key) ? key : null; - } - - internal void ValidateIdentities() - { - if (identities is null) - return; - foreach (SerializationCaptureIdentity identity in identities) - identity.Validate(); - } } internal readonly record struct SerializationCaptureIdentity( - Inno.Core.Identity.Identity identity, + CoreIdentity identity, RuntimeIdentity expected ) { internal void Validate() { if (identity.runtimeIdentity != expected) + { throw new InvalidOperationException($"Core identity '{expected}' changed during serialization capture."); + } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs index 4e9b73008..3b8d16289 100644 --- a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs +++ b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs @@ -35,17 +35,22 @@ private SerializationContext(KeyValuePair[] values) /// /// Thrown when is null. /// - public SerializationContext With(TContext value) where TContext : class + public SerializationContext With(TContext value) + where TContext : class { ArgumentNullException.ThrowIfNull(value); Type key = typeof(TContext); for (int index = 0; index < m_values.Length; index++) { if (m_values[index].Key != key) + { continue; + } if (ReferenceEquals(m_values[index].Value, value)) + { return new SerializationContext(m_values); - var updated = (KeyValuePair[])m_values.Clone(); + } + KeyValuePair[] updated = (KeyValuePair[])m_values.Clone(); updated[index] = new(key, value); return new SerializationContext(updated); } @@ -67,7 +72,8 @@ public SerializationContext With(TContext value) where TContext : clas /// /// when a value is registered; otherwise, . /// - public bool TryGet(out TContext? value) where TContext : class + public bool TryGet(out TContext? value) + where TContext : class { foreach (KeyValuePair pair in m_values) { @@ -94,9 +100,11 @@ public bool TryGet(out TContext? value) where TContext : class /// /// Thrown when the requested context was not registered. /// - public TContext GetRequired() where TContext : class - => TryGet(out TContext? value) && value is not null - ? value - : throw new InvalidOperationException( - $"Serialization context '{typeof(TContext).FullName}' is not registered."); + public TContext GetRequired() + where TContext : class + => TryGet(out TContext? value) && value is not null + ? value + : throw new InvalidOperationException( + $"Serialization context '{typeof(TContext).FullName}' is not registered." + ); } diff --git a/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs b/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs index 44468ae38..28a55112d 100644 --- a/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs +++ b/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs @@ -58,9 +58,9 @@ T value public virtual void Restore( SerializationReader reader, T target - ) - => throw new NotSupportedException( - $"Serialization converter '{GetType().FullName}' does not support restoring existing '{typeof(T).FullName}' values."); + ) => throw new NotSupportedException( + $"Serialization converter '{GetType().FullName}' does not support restoring existing '{typeof(T).FullName}' values." + ); /// /// Optionally declares every input to a snapshot capture without writing data. diff --git a/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs b/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs index 766b124cf..5eff771da 100644 --- a/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs +++ b/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs @@ -1,7 +1,6 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Core.Serialization; @@ -21,7 +20,7 @@ public override void Write( TypeRef value ) { ArgumentNullException.ThrowIfNull(writer); - writer.Write("stableId", value.stableId); + writer.Write("stableId", value.stableID); } /// diff --git a/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs b/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs index 1017a968d..0971f4889 100644 --- a/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs +++ b/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs @@ -97,12 +97,7 @@ Type declaredType ) { ArgumentNullException.ThrowIfNull(declaredType); SerializationNode node = GetRequiredNode(name); - return ValuePipeline.Read( - node, - declaredType, - m_operation, - AppendPath(name), - allowDefaultObject: false); + return ValuePipeline.Read(node, declaredType, m_operation, AppendPath(name), allowDefaultObject: false); } /// @@ -136,7 +131,8 @@ out TValue value typeof(TValue), m_operation, AppendPath(name), - allowDefaultObject: false)!; + allowDefaultObject: false + )!; return true; } @@ -153,7 +149,9 @@ public SerializationReader ReadObject(string name) { SerializationNode node = GetRequiredNode(name); if (node is not ObjectSerializationNode child) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}' must be an object."); + } return new SerializationReader(m_operation, child, AppendPath(name), typeof(object)); } @@ -170,13 +168,17 @@ public IReadOnlyList ReadObjectArray(string name) { SerializationNode node = GetRequiredNode(name); if (node is not ArraySerializationNode array) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}' must be an array."); + } var readers = new SerializationReader[array.values.Count]; for (int i = 0; i < array.values.Count; i++) { if (array.values[i] is not ObjectSerializationNode child) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}[{i}]' must be an object."); + } readers[i] = new SerializationReader(m_operation, child, $"{AppendPath(name)}[{i}]", typeof(object)); } @@ -218,9 +220,13 @@ private SerializationNode GetRequiredNode(string name) { m_operation.EnsureActive(); if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A non-empty serialization member name is required.", nameof(name)); + } if (!m_node.values.TryGetValue(name, out SerializationNode? node)) + { throw new InvalidOperationException($"Required serialization value '{AppendPath(name)}' is missing."); + } return node; } diff --git a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs index d2c427c8e..ae4a30205 100644 --- a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs +++ b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs @@ -29,7 +29,9 @@ Type valueType m_operationGeneration = operation.writerGeneration; m_previous = previous; if (previous is null) + { m_node = new ObjectSerializationNode(); + } this.path = path; this.valueType = valueType; } @@ -42,13 +44,13 @@ Type valueType /// /// Borrows the immutable type snapshot pinned by this operation's converter generation. /// + /// + /// The writer no longer belongs to an active capture. + /// /// /// Use this snapshot for consistent type identities during a complete capture. It must not be retained beyond /// the writer's operation; keeping it would retain its collectible types after the converter lease is released. /// - /// - /// The writer no longer belongs to an active capture. - /// [ScriptingApiIgnore] public TypeCacheSnapshot typeSnapshot { @@ -96,10 +98,10 @@ TValue value if (m_previous is not null && m_previous.values.Count <= 64 && m_writtenCount < m_previous.values.Count) { KeyValuePair entry = m_previous.values.GetAt(m_writtenCount); - if (string.Equals(entry.Key, name, StringComparison.Ordinal) && entry.Value is ScalarSerializationNode scalar && - scalar.value.GetType() == typeof(TValue) && m_operation.ResolveConverter(typeof(TValue)) is null && - SerializationNodeReuse.SameScalar(value, scalar.value)) - { + if (string.Equals(entry.Key, name, StringComparison.Ordinal) && entry.Value is ScalarSerializationNode scalar + && scalar.value.GetType() == typeof(TValue) && m_operation.ResolveConverter(typeof(TValue)) is null + && SerializationNodeReuse.SameScalar(value, scalar.value) + ) { MarkWritten(name, m_writtenCount); return; } @@ -137,8 +139,10 @@ Type declaredType ValidateName(name); EnsureActive(); SerializationNode? previous = Previous(name); - AddNode(name, ValuePipeline.Write(value, declaredType, m_operation, AppendPath(name), - allowDefaultObject: false, previous)); + AddNode( + name, + ValuePipeline.Write(value, declaredType, m_operation, AppendPath(name), allowDefaultObject: false, previous) + ); } /// @@ -161,7 +165,12 @@ Action write ValidateName(name); EnsureActive(); SerializationNode? previous = Previous(name); - var child = new SerializationWriter(m_operation, previous as ObjectSerializationNode, AppendPath(name), typeof(object)); + var child = new SerializationWriter( + m_operation, + previous as ObjectSerializationNode, + AppendPath(name), + typeof(object) + ); AddNode(name, previous ?? child.m_node!); write(child); ReplaceNode(name, child.Complete()); @@ -187,11 +196,6 @@ Action write /// a current Core identity owner and return true only for a complete proof. Snapshot capture alone /// can reuse a matching element; ordinary serialization always executes writeElement. /// - /// - /// The key builder belongs only to its synchronous callback. Uncertified rows and rows that invoke - /// nested converters execute the ordinary element writer on every capture. Callback failures and - /// changed declared inputs abort publication without modifying a previous snapshot. - /// /// /// Values or writeElement is null. /// @@ -201,6 +205,11 @@ Action write /// /// The writer has retired, a member is duplicated, or declared capture inputs change during writing. /// + /// + /// The key builder belongs only to its synchronous callback. Uncertified rows and rows that invoke + /// nested converters execute the ordinary element writer on every capture. Callback failures and + /// changed declared inputs abort publication without modifying a previous snapshot. + /// public void WriteObjectArray( string name, IEnumerable values, @@ -219,17 +228,24 @@ public void WriteObjectArray( if (values is TValue[] items) { for (int itemIndex = 0; itemIndex < items.Length; itemIndex++) + { WriteElement(items[itemIndex]); + } } else + { foreach (TValue value in values) + { WriteElement(value); + } + } ReplaceNode(name, array.Complete()); void WriteElement(TValue value) { - ObjectSerializationNode? prior = array.Next as ObjectSerializationNode; - SerializationCaptureAttempt attempt = captureKey is null ? SerializationCaptureAttempt.empty + ObjectSerializationNode? prior = array.next as ObjectSerializationNode; + SerializationCaptureAttempt attempt = captureKey is null + ? SerializationCaptureAttempt.EMPTY : SerializationCaptureAttempt.Capture(m_operation, typeof(TValue), value, prior?.captureKey, captureKey: captureKey); SerializationCaptureKey? key = attempt.key; if (key is not null && ReferenceEquals(key, prior?.captureKey)) @@ -238,8 +254,12 @@ void WriteElement(TValue value) index++; return; } - var child = new SerializationWriter(m_operation, prior, - array.Next?.capturePath ?? $"{AppendPath(name)}[{index}]", typeof(TValue)); + var child = new SerializationWriter( + m_operation, + prior, + array.next?.capturePath ?? $"{AppendPath(name)}[{index}]", + typeof(TValue) + ); long converterWrites = m_operation.converterWrites; writeElement(child, value); ObjectSerializationNode result = child.Complete(); @@ -248,10 +268,14 @@ void WriteElement(TValue value) attempt.ValidateIdentities(); key = attempt.Verify(SerializationCaptureAttempt.Capture(m_operation, typeof(TValue), value, key, captureKey: captureKey)); if (m_operation.converterWrites != converterWrites) + { key = null; + } } if (ReferenceEquals(result, prior) && prior!.captureKey is null) + { key = null; + } array.Add(SerializationNodeReuse.WithCaptureKey(result, prior, key)); index++; } @@ -324,7 +348,9 @@ internal ObjectSerializationNode Complete() { string name = m_previous.values.GetAt(index).Key; if (m_previous.values.Count <= 64 ? (m_writtenMask & (1UL << index)) == 0 : m_writtenNames?.Contains(name) != true) + { m_node!.values.Remove(name); + } } } ObjectSerializationNode result = m_node ?? m_previous ?? new ObjectSerializationNode(); @@ -334,9 +360,11 @@ internal ObjectSerializationNode Complete() private SerializationNode? Previous(string name) { - if (m_previous is not null && m_writtenCount < m_previous.values.Count && - string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal)) + if (m_previous is not null && m_writtenCount < m_previous.values.Count + && string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal) + ) { return m_previous.values.GetAt(m_writtenCount).Value; + } return m_previous is not null && m_previous.values.TryGetValue(name, out SerializationNode? value) ? value : null; } @@ -349,17 +377,23 @@ SerializationNode node { m_node ??= new ObjectSerializationNode(); if (!m_node.values.TryAdd(name, node)) + { throw new InvalidOperationException($"Serialization object '{path}' already contains key '{name}'."); + } return; } int index = -1; if (m_previous.values.Count <= 64) { - if (m_writtenCount < m_previous.values.Count && - string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal)) + if (m_writtenCount < m_previous.values.Count + && string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal) + ) { index = m_writtenCount; + } else + { index = m_previous.values.IndexOf(name); + } } SerializationNode? previous = index >= 0 ? m_previous.values.GetAt(index).Value : Previous(name); MarkWritten(name, index); @@ -382,16 +416,22 @@ int previousIndex m_writtenMask |= bit; } else + { duplicate = !(m_writtenNames ??= new(StringComparer.Ordinal)).Add(name); + } if (duplicate) + { throw new InvalidOperationException($"Serialization object '{path}' already contains key '{name}'."); + } m_writtenCount++; } private void EnsureMutable() { if (m_node is not null) + { return; + } m_node = m_previous is null ? new ObjectSerializationNode() : SerializationNodeReuse.CopyObject(m_previous); } @@ -411,9 +451,13 @@ private void EnsureActive() { m_operation.EnsureActive(); if (m_operationGeneration != m_operation.writerGeneration) + { throw new InvalidOperationException("The serialization writer belongs to a completed property capture."); + } if (m_completed && m_operation.isSnapshotCapture) + { throw new InvalidOperationException("The serialization writer callback has already completed."); + } } private string AppendPath(string name) => Previous(name)?.capturePath ?? (path == "$" ? $"$.{name}" : $"{path}.{name}"); @@ -421,6 +465,8 @@ private void EnsureActive() private static void ValidateName(string name) { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A non-empty serialization member name is required.", nameof(name)); + } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs new file mode 100644 index 000000000..78714f3e5 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization; + +internal sealed record ArraySerializationNode : SerializationNode +{ + internal ArraySerializationNode() + : this([]) {} + + internal ArraySerializationNode(List values) + { + this.values = values; + } + + internal List values { get; } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs index 5268a03c6..918c9f49a 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs @@ -9,9 +9,13 @@ internal static partial class BinarySerializationFormat private static byte[]? TryGetEncodedCapture(ObjectSerializationNode node) { if (node.encodedCapture is { } encoded) + { return encoded; + } if (node.captureKey is null || node.encodingTooLarge) + { return null; + } int length; try { diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs index 668d72703..e0806546d 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs @@ -11,7 +11,9 @@ internal static partial class BinarySerializationFormat private static int GetEncodedSize(SerializationNode node) { if (node is ObjectSerializationNode { encodedCapture: { } encoded }) + { return encoded.Length; + } int payload = node switch { NullSerializationNode => 0, @@ -25,7 +27,8 @@ private static int GetEncodedSize(SerializationNode node) return checked(sizeof(byte) + payload); } - private static int GetScalarSize(object value) => value switch + private static int GetScalarSize(object value) + => value switch { bool or byte or sbyte => 1, short or ushort => 2, @@ -47,7 +50,9 @@ private static int GetObjectSize(ObjectSerializationNode node) { int size = sizeof(int); foreach (KeyValuePair member in node.values) + { size = checked(size + GetEncodedStringSize(member.Key) + GetEncodedSize(member.Value)); + } return size; } @@ -55,7 +60,9 @@ private static int GetArraySize(ArraySerializationNode node) { int size = sizeof(int); foreach (SerializationNode value in node.values) + { size = checked(size + GetEncodedSize(value)); + } return size; } @@ -63,7 +70,9 @@ private static int GetMapSize(MapSerializationNode node) { int size = sizeof(int); foreach (KeyValuePair entry in node.values) + { size = checked(size + GetEncodedSize(entry.Key) + GetEncodedSize(entry.Value)); + } return size; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs index be6a56795..1e28021a8 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs @@ -10,8 +10,7 @@ internal static partial class BinarySerializationFormat private const string C_MAGIC = "INNO-BINARY-CURRENT"; private const int C_MAX_COLLECTION_COUNT = 16_777_216; - internal static byte[] Encode(SerializationNode root) - => Encode(root, includeMagic: true); + internal static byte[] Encode(SerializationNode root) => Encode(root, includeMagic: true); internal static void WriteTo( Stream destination, @@ -31,11 +30,15 @@ internal static SerializationNode Decode(ReadOnlySpan bytes) using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); string magic = reader.ReadString(); if (!string.Equals(magic, C_MAGIC, StringComparison.Ordinal)) + { throw new InvalidDataException($"Invalid serialization magic '{magic}'."); + } SerializationNode root = ReadNode(reader, "$"); if (stream.Position != stream.Length) + { throw new InvalidDataException("Serialization payload at '$' contains trailing data."); + } return root; } catch (InvalidDataException) @@ -86,7 +89,9 @@ private static void WriteNode( writer.Write((byte)NodeKind.Array); writer.Write(array.values.Count); for (int i = 0; i < array.values.Count; i++) + { WriteNode(writer, array.values[i]); + } return; case MapSerializationNode map: writer.Write((byte)NodeKind.Map); @@ -143,19 +148,58 @@ object value ) { switch (value) { - case bool typed: writer.Write((byte)NodeKind.Boolean); writer.Write(typed); return; - case byte typed: writer.Write((byte)NodeKind.Byte); writer.Write(typed); return; - case sbyte typed: writer.Write((byte)NodeKind.SByte); writer.Write(typed); return; - case short typed: writer.Write((byte)NodeKind.Int16); writer.Write(typed); return; - case ushort typed: writer.Write((byte)NodeKind.UInt16); writer.Write(typed); return; - case int typed: writer.Write((byte)NodeKind.Int32); writer.Write(typed); return; - case uint typed: writer.Write((byte)NodeKind.UInt32); writer.Write(typed); return; - case long typed: writer.Write((byte)NodeKind.Int64); writer.Write(typed); return; - case ulong typed: writer.Write((byte)NodeKind.UInt64); writer.Write(typed); return; - case float typed: writer.Write((byte)NodeKind.Single); writer.Write(typed); return; - case double typed: writer.Write((byte)NodeKind.Double); writer.Write(typed); return; - case decimal typed: writer.Write((byte)NodeKind.Decimal); writer.Write(typed); return; - case string typed: writer.Write((byte)NodeKind.String); writer.Write(typed); return; + case bool typed: + writer.Write((byte)NodeKind.Boolean); + writer.Write(typed); + return; + case byte typed: + writer.Write((byte)NodeKind.Byte); + writer.Write(typed); + return; + case sbyte typed: + writer.Write((byte)NodeKind.SByte); + writer.Write(typed); + return; + case short typed: + writer.Write((byte)NodeKind.Int16); + writer.Write(typed); + return; + case ushort typed: + writer.Write((byte)NodeKind.UInt16); + writer.Write(typed); + return; + case int typed: + writer.Write((byte)NodeKind.Int32); + writer.Write(typed); + return; + case uint typed: + writer.Write((byte)NodeKind.UInt32); + writer.Write(typed); + return; + case long typed: + writer.Write((byte)NodeKind.Int64); + writer.Write(typed); + return; + case ulong typed: + writer.Write((byte)NodeKind.UInt64); + writer.Write(typed); + return; + case float typed: + writer.Write((byte)NodeKind.Single); + writer.Write(typed); + return; + case double typed: + writer.Write((byte)NodeKind.Double); + writer.Write(typed); + return; + case decimal typed: + writer.Write((byte)NodeKind.Decimal); + writer.Write(typed); + return; + case string typed: + writer.Write((byte)NodeKind.String); + writer.Write(typed); + return; case Guid typed: Span bytes = stackalloc byte[16]; _ = typed.TryWriteBytes(bytes); @@ -178,7 +222,9 @@ string path string name = reader.ReadString(); string memberPath = AppendPath(path, name); if (!node.values.TryAdd(name, ReadNode(reader, memberPath))) + { throw new InvalidDataException($"Serialization object at '{path}' contains duplicate key '{name}'."); + } } return node; } @@ -191,7 +237,9 @@ string path var node = new ArraySerializationNode(); node.values.Capacity = count; for (int i = 0; i < count; i++) + { node.values.Add(ReadNode(reader, $"{path}[{i}]")); + } return node; } @@ -204,9 +252,12 @@ string path node.values.Capacity = count; for (int i = 0; i < count; i++) { - node.values.Add(new KeyValuePair( - ReadNode(reader, $"{path}[{i}].key"), - ReadNode(reader, $"{path}[{i}].value"))); + node.values.Add( + new KeyValuePair( + ReadNode(reader, $"{path}[{i}].key"), + ReadNode(reader, $"{path}[{i}].value") + ) + ); } return node; } @@ -218,7 +269,9 @@ string path int count = ReadCount(reader, "binary byte", path); byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new InvalidDataException($"Serialization binary value at '{path}' is truncated."); + } return bytes; } @@ -228,7 +281,9 @@ string path ) { byte[] bytes = reader.ReadBytes(16); if (bytes.Length != 16) + { throw new InvalidDataException($"Serialization Guid value at '{path}' is truncated."); + } return new Guid(bytes); } @@ -239,7 +294,9 @@ string path ) { int count = reader.ReadInt32(); if (count < 0 || count > C_MAX_COLLECTION_COUNT) + { throw new InvalidDataException($"Invalid serialization {kind} count {count} at '{path}'."); + } return count; } @@ -248,8 +305,7 @@ private static string AppendPath( string name ) => path == "$" ? $"$.{name}" : $"{path}.{name}"; - private static byte[] EncodeNode(SerializationNode node) - => Encode(node, includeMagic: false); + private static byte[] EncodeNode(SerializationNode node) => Encode(node, includeMagic: false); private static byte[] Encode( SerializationNode node, @@ -261,11 +317,15 @@ private static byte[] Encode( using var stream = new MemoryStream(data, writable: true); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); if (includeMagic) + { writer.Write(C_MAGIC); + } WriteNode(writer, node, useObjectCache); writer.Flush(); if (stream.Position != length) + { throw new InvalidDataException("The serialization encoder did not fill its calculated output size."); + } return data; } @@ -278,7 +338,9 @@ byte[] right { int comparison = left[i].CompareTo(right[i]); if (comparison != 0) + { return comparison; + } } return left.Length.CompareTo(right.Length); } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs new file mode 100644 index 000000000..a633f8b66 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs @@ -0,0 +1,153 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization; + +internal abstract class ConverterInvoker +{ + /// + /// Creates a validated converter invoker instance. + /// + /// + /// The target type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The converter type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. + /// + protected ConverterInvoker( + Type targetType, + Type converterType + ) { + this.targetType = targetType; + this.converterType = converterType; + } + + internal Type targetType { get; } + + internal Type converterType { get; } + + internal abstract SerializationNode Write( + SerializationOperation operation, + string path, + Type valueType, + object value, + SerializationNode? previous + ); + + internal abstract object Read( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node + ); + + internal abstract void Restore( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node, + object target + ); +} + +internal sealed class ConverterInvoker : ConverterInvoker +{ + private readonly SerializationConverter m_converter; + + internal ConverterInvoker( + SerializationConverter converter, + Type converterType + ) : base(typeof(T), converterType) + { + m_converter = converter; + } + + internal override SerializationNode Write( + SerializationOperation operation, + string path, + Type valueType, + object value, + SerializationNode? previous + ) { + if (value is not T typed) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'." + ); + } + + ObjectSerializationNode? prior = previous as ObjectSerializationNode; + operation.RecordConverterWrite(); + long converterWrites = operation.converterWrites; + SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture( + operation, + valueType, + typed, + prior?.captureKey, + m_converter + ); + SerializationCaptureKey? key = attempt.key; + if (key is not null && ReferenceEquals(key, prior?.captureKey)) + { + return prior!; + } + var writer = new SerializationWriter(operation, prior, path, valueType); + m_converter.Write(writer, typed); + ObjectSerializationNode result = writer.Complete(); + if (key is not null) + { + attempt.ValidateIdentities(); + key = attempt.Verify(SerializationCaptureAttempt.Capture(operation, valueType, typed, key, m_converter)); + if (operation.converterWrites != converterWrites) + { + key = null; + } + } + return SerializationNodeReuse.WithCaptureKey(result, prior, key); + } + + internal override object Read( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node + ) { + T result = m_converter.Read(new SerializationReader(operation, node, path, valueType)); + if (result is null) + { + throw new InvalidOperationException($"Converter '{converterType.FullName}' returned null at '{path}'."); + } + if (!valueType.IsInstanceOfType(result)) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'." + ); + } + if (result is ISerializable serializable) + { + operation.ScheduleRestoredObject(serializable); + } + return result; + } + + internal override void Restore( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node, + object target + ) { + if (target is not T typed) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'." + ); + } + + m_converter.Restore(new SerializationReader(operation, node, path, valueType), typed); + if (target is ISerializable serializable) + { + operation.ScheduleRestoredObject(serializable); + } + } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs index 1a8346ca3..e0f07430f 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs @@ -3,11 +3,9 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Reflection; using System.Threading; - -using Inno.Extensibility.Types; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Core.Serialization; @@ -23,19 +21,21 @@ internal ConverterRegistry(TypeCatalog types) m_registry.Refresh(); } - internal void Refresh() => RequireRegistry().Refresh(); - /// /// Releases the resources owned by this instance. /// public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_registry.Dispose(); } + internal void Refresh() => RequireRegistry().Refresh(); + internal ConverterInvoker? Resolve(Type valueType) { using ConverterRegistryLease lease = Capture(); @@ -48,15 +48,19 @@ public void Dispose() ConverterRegistrySnapshot snapshot, Type valueType ) { - var candidates = new List(); + List candidates = []; for (int i = 0; i < snapshot.registrations.Count; i++) { if (TryCreateCandidate(snapshot, snapshot.registrations[i], valueType, out ConverterCandidate? candidate)) + { candidates.Add(candidate!); + } } if (candidates.Count == 0) + { return null; + } int bestDistance = candidates.Min(static candidate => candidate.distance); ConverterCandidate[] best = candidates @@ -66,13 +70,19 @@ Type valueType if (best.Length > 1) { throw new InvalidOperationException( - $"Serialization type '{valueType.FullName}' has ambiguous converters " + - $"'{best[0].converterType.FullName}' and '{best[1].converterType.FullName}' at distance {bestDistance}."); + $"Serialization type '{valueType.FullName}' has ambiguous converters " + + $"'{best[0].converterType.FullName}' and '{best[1].converterType.FullName}' at distance {bestDistance}." + ); } return best[0].invoker; } + private ConverterTypeRegistry RequireRegistry() + => !m_disposed + ? m_registry + : throw new ObjectDisposedException(nameof(ConverterRegistry)); + private static bool TryCreateCandidate( ConverterRegistrySnapshot snapshot, Type registeredType, @@ -81,45 +91,57 @@ out ConverterCandidate? candidate ) { candidate = null; if (!TryGetConverterTargetPattern(registeredType, out Type targetPattern)) + { throw new InvalidOperationException( - $"Serialization extension '{registeredType.FullName}' must inherit SerializationConverter."); + $"Serialization extension '{registeredType.FullName}' must inherit SerializationConverter." + ); + } Type closedConverterType = registeredType; if (registeredType.ContainsGenericParameters) { if (!registeredType.IsGenericTypeDefinition) + { return false; + } var bindings = new Dictionary(); if (!TryUnify(targetPattern, valueType, bindings)) + { return false; + } Type[] parameters = registeredType.GetGenericArguments(); var arguments = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { if (!bindings.TryGetValue(parameters[i], out Type? argument)) + { return false; + } arguments[i] = argument; } Type? construction = snapshot.ConstructGenericType(registeredType, arguments); if (construction is null) + { return false; + } closedConverterType = construction; } if (!TryGetConverterTargetPattern(closedConverterType, out Type targetType) || targetType.ContainsGenericParameters) + { return false; + } if (!targetType.IsAssignableFrom(valueType)) + { return false; + } - var converter = (SerializationConverter)GetOrCreateConverter(snapshot, closedConverterType); + SerializationConverter converter = (SerializationConverter)GetOrCreateConverter(snapshot, closedConverterType); ConverterInvoker invoker = converter.CreateInvoker(); - candidate = new ConverterCandidate( - closedConverterType, - GetTypeDistance(valueType, targetType), - invoker); + candidate = new ConverterCandidate(closedConverterType, GetTypeDistance(valueType, targetType), invoker); return true; } @@ -128,7 +150,9 @@ private static object GetOrCreateConverter( Type converterType ) { if (snapshot.converterInstances.TryGetValue(converterType, out object? converter)) + { return converter; + } try { @@ -138,7 +162,8 @@ Type converterType { throw new InvalidOperationException( $"Serialization converter '{converterType.FullName}' must have a parameterless constructor.", - exception); + exception + ); } snapshot.converterInstances.Add(converterType, converter); @@ -152,7 +177,9 @@ out Type targetPattern for (Type? current = converterType; current is not null; current = current.BaseType) { if (!current.IsGenericType || current.GetGenericTypeDefinition() != typeof(SerializationConverter<>)) + { continue; + } targetPattern = current.GetGenericArguments()[0]; return true; @@ -170,29 +197,37 @@ Dictionary bindings if (pattern.IsGenericParameter) { if (bindings.TryGetValue(pattern, out Type? existing)) + { return existing == concrete; + } bindings.Add(pattern, concrete); return true; } if (pattern.IsArray) { - return concrete.IsArray && - pattern.GetArrayRank() == concrete.GetArrayRank() && - TryUnify(pattern.GetElementType()!, concrete.GetElementType()!, bindings); + return concrete.IsArray + && pattern.GetArrayRank() == concrete.GetArrayRank() + && TryUnify(pattern.GetElementType()!, concrete.GetElementType()!, bindings); } if (!pattern.IsGenericType) + { return pattern == concrete; + } if (!concrete.IsGenericType || pattern.GetGenericTypeDefinition() != concrete.GetGenericTypeDefinition()) + { return false; + } Type[] patternArguments = pattern.GetGenericArguments(); Type[] concreteArguments = concrete.GetGenericArguments(); for (int i = 0; i < patternArguments.Length; i++) { if (!TryUnify(patternArguments[i], concreteArguments[i], bindings)) + { return false; + } } return true; @@ -203,17 +238,23 @@ private static int GetTypeDistance( Type targetType ) { if (derivedType == targetType) + { return 0; + } // Assignability was validated by the caller. Implemented interfaces share one rank, // including variant constructions; class inheritance retains its exact depth. if (targetType.IsInterface) + { return 1; + } int distance = 1; for (Type? current = derivedType.BaseType; current is not null; current = current.BaseType) { if (current == targetType) + { return distance; + } distance++; } @@ -229,19 +270,7 @@ ConverterInvoker invoker private sealed class ConverterTypeRegistry : TypeRegistry { internal ConverterTypeRegistry(TypeCatalog types) - : base(types) - { - } - - internal ConverterRegistryLease Capture() - { - while (true) - { - ConverterRegistrySnapshot snapshot = current; - if (snapshot.TryAcquire()) - return new ConverterRegistryLease(snapshot); - } - } + : base(types) {} /// /// Builds a validated result from the current immutable input snapshot. @@ -264,7 +293,8 @@ protected override ConverterRegistrySnapshot Build(TypeCacheSnapshot types) if (!TryGetConverterTargetPattern(registrations[i], out _)) { throw new InvalidOperationException( - $"Serialization extension '{registrations[i].FullName}' must inherit SerializationConverter."); + $"Serialization extension '{registrations[i].FullName}' must inherit SerializationConverter." + ); } } @@ -278,23 +308,29 @@ protected override ConverterRegistrySnapshot Build(TypeCacheSnapshot types) /// The immutable state snapshot consumed by this operation. /// protected override void DisposeSnapshot(ConverterRegistrySnapshot snapshot) => snapshot.Release(); - } - private ConverterTypeRegistry RequireRegistry() - => !m_disposed - ? m_registry - : throw new ObjectDisposedException(nameof(ConverterRegistry)); + internal ConverterRegistryLease Capture() + { + while (true) + { + ConverterRegistrySnapshot snapshot = current; + if (snapshot.TryAcquire()) + { + return new ConverterRegistryLease(snapshot); + } + } + } + } internal sealed class ConverterRegistrySnapshot( IReadOnlyList registrations, TypeCacheSnapshot types - ) - { - private TypeCacheSnapshot? m_types = types; + ) { internal readonly Guid captureIdentity = Guid.NewGuid(); internal readonly Lock sync = new(); internal readonly ConcurrentDictionary cache = new(); internal readonly Dictionary converterInstances = []; + private TypeCacheSnapshot? m_types = types; internal IReadOnlyList registrations = registrations; private int m_referenceCount = 1; @@ -314,7 +350,9 @@ internal bool TryAcquire() lock (sync) { if (m_referenceCount == 0) + { return false; + } m_referenceCount++; return true; } @@ -326,12 +364,16 @@ internal void Release() lock (sync) { if (m_referenceCount <= 0) + { throw new InvalidOperationException("The serialization converter generation was released twice."); + } m_referenceCount--; dispose = m_referenceCount == 0; } if (!dispose) + { return; + } foreach (object converter in converterInstances.Values.Distinct(ReferenceEqualityComparer.Instance)) { @@ -346,7 +388,8 @@ internal void Release() Trace.TraceError( "Serialization converter '{0}' failed while being disposed: {1}", converter.GetType().FullName, - exception); + exception + ); } } } @@ -354,238 +397,9 @@ internal void Release() { cache.Clear(); converterInstances.Clear(); - registrations = Array.Empty(); + registrations = []; m_types = null; } } } } - -internal sealed class ConverterRegistryLease : IDisposable -{ - private ConcurrentDictionary? m_revisionPlans; - private ConverterRegistry.ConverterRegistrySnapshot? m_snapshot; - - internal ConverterRegistryLease(ConverterRegistry.ConverterRegistrySnapshot snapshot) - { - m_snapshot = snapshot; - } - - internal TypeCacheSnapshot types => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).types; - internal Guid captureIdentity => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).captureIdentity; - - internal bool CanReuseRevision( - SerializationTypeMetadata metadata, - ISerializationMetadataSource source - ) { - var plans = Volatile.Read(ref m_revisionPlans); - if (plans is null) - { - var created = new ConcurrentDictionary(); - plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; - } - if (plans.TryGetValue(metadata, out var known) && ReferenceEquals(known.source, source)) - return known.eligible; - bool eligible = !metadata.requiresConverter; - foreach (SerializationMemberMetadata member in metadata.members) - { - if (!eligible) - break; - if ((member.visibility & PropertyVisibility.Serialize) == 0) - continue; - if (!IsKnownDefault(member.type)) - { - eligible = false; - break; - } - if (ValuePipeline.IsPrimitive(member.type) || member.type.IsEnum) - continue; - SerializationTypeMetadata nested = source.GetMetadata(member.type); - if (!nested.hasPureFieldAccess) - { - eligible = false; - break; - } - foreach (SerializationMemberMetadata field in nested.members) - if ((field.visibility & PropertyVisibility.Serialize) != 0 && !IsKnownDefault(field.type)) - { - eligible = false; - break; - } - } - // An unresolved fact can become known through an ordinary write in this same operation. - // Cache only positive proofs; a key query still never invokes the resolver itself. - if (eligible) - plans[metadata] = (source, true); - return eligible; - } - internal ConverterInvoker? Resolve(Type valueType) - { - ArgumentNullException.ThrowIfNull(valueType); - ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); - Type normalizedType = Nullable.GetUnderlyingType(valueType) ?? valueType; - if (snapshot.cache.TryGetValue(normalizedType, out ConverterInvoker? cached)) - return cached; - lock (snapshot.sync) - { - if (snapshot.cache.TryGetValue(normalizedType, out cached)) - return cached; - ConverterInvoker? resolved = ConverterRegistry.ResolveSnapshot(snapshot, normalizedType); - if (!snapshot.cache.TryAdd(normalizedType, resolved)) - throw new InvalidOperationException("The serialization converter resolution was published twice."); - return resolved; - } - } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - ConverterRegistry.ConverterRegistrySnapshot? snapshot = Interlocked.Exchange(ref m_snapshot, null); - m_revisionPlans?.Clear(); - snapshot?.Release(); - } - - private bool IsKnownDefault(Type type) - { - ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); - Type normalized = Nullable.GetUnderlyingType(type) ?? type; - // Reuse only facts established by the authoritative resolver. A key query must not - // construct converters, change their execution order, or introduce another resolver. - return snapshot.cache.TryGetValue(normalized, out ConverterInvoker? converter) && converter is null; - } -} - -internal abstract class ConverterInvoker -{ - /// - /// Creates a validated converter invoker instance. - /// - /// - /// The target type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The converter type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. - /// - protected ConverterInvoker( - Type targetType, - Type converterType - ) { - this.targetType = targetType; - this.converterType = converterType; - } - - internal Type targetType { get; } - - internal Type converterType { get; } - - internal abstract SerializationNode Write( - SerializationOperation operation, - string path, - Type valueType, - object value, - SerializationNode? previous - ); - - internal abstract object Read( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node - ); - - internal abstract void Restore( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node, - object target - ); -} - -internal sealed class ConverterInvoker : ConverterInvoker -{ - private readonly SerializationConverter m_converter; - - internal ConverterInvoker( - SerializationConverter converter, - Type converterType - ) - : base(typeof(T), converterType) - { - m_converter = converter; - } - - internal override SerializationNode Write( - SerializationOperation operation, - string path, - Type valueType, - object value, - SerializationNode? previous - ) { - if (value is not T typed) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'."); - } - - ObjectSerializationNode? prior = previous as ObjectSerializationNode; - operation.RecordConverterWrite(); - long converterWrites = operation.converterWrites; - SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture(operation, valueType, typed, prior?.captureKey, m_converter); - SerializationCaptureKey? key = attempt.key; - if (key is not null && ReferenceEquals(key, prior?.captureKey)) - return prior!; - var writer = new SerializationWriter(operation, prior, path, valueType); - m_converter.Write(writer, typed); - ObjectSerializationNode result = writer.Complete(); - if (key is not null) - { - attempt.ValidateIdentities(); - key = attempt.Verify(SerializationCaptureAttempt.Capture(operation, valueType, typed, key, m_converter)); - if (operation.converterWrites != converterWrites) - key = null; - } - return SerializationNodeReuse.WithCaptureKey(result, prior, key); - } - - internal override object Read( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node - ) { - T result = m_converter.Read(new SerializationReader(operation, node, path, valueType)); - if (result is null) - throw new InvalidOperationException($"Converter '{converterType.FullName}' returned null at '{path}'."); - if (!valueType.IsInstanceOfType(result)) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'."); - } - if (result is ISerializable serializable) - operation.ScheduleRestoredObject(serializable); - return result; - } - - internal override void Restore( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node, - object target - ) { - if (target is not T typed) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'."); - } - - m_converter.Restore(new SerializationReader(operation, node, path, valueType), typed); - if (target is ISerializable serializable) - operation.ScheduleRestoredObject(serializable); - } -} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs new file mode 100644 index 000000000..5ac8b785e --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using Inno.Extensibility.Types; + +namespace Inno.Core.Serialization; + +internal sealed class ConverterRegistryLease : IDisposable +{ + private ConcurrentDictionary? m_revisionPlans; + private ConverterRegistry.ConverterRegistrySnapshot? m_snapshot; + + internal ConverterRegistryLease(ConverterRegistry.ConverterRegistrySnapshot snapshot) + { + m_snapshot = snapshot; + } + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + ConverterRegistry.ConverterRegistrySnapshot? snapshot = Interlocked.Exchange(ref m_snapshot, null); + m_revisionPlans?.Clear(); + snapshot?.Release(); + } + + internal TypeCacheSnapshot types => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).types; + internal Guid captureIdentity => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).captureIdentity; + + internal bool CanReuseRevision( + SerializationTypeMetadata metadata, + ISerializationMetadataSource source + ) { + ConcurrentDictionary? plans = Volatile.Read( + ref m_revisionPlans + ); + if (plans is null) + { + var created = new ConcurrentDictionary(); + plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; + } + if (plans.TryGetValue(metadata, out (ISerializationMetadataSource source, bool eligible) known) + && ReferenceEquals(known.source, source) + ) { + return known.eligible; + } + bool eligible = !metadata.requiresConverter; + foreach (SerializationMemberMetadata member in metadata.members) + { + if (!eligible) + { + break; + } + if ((member.visibility & PropertyVisibility.Serialize) == 0) + { + continue; + } + if (!IsKnownDefault(member.type)) + { + eligible = false; + break; + } + if (ValuePipeline.IsPrimitive(member.type) || member.type.IsEnum) + { + continue; + } + SerializationTypeMetadata nested = source.GetMetadata(member.type); + if (!nested.hasPureFieldAccess) + { + eligible = false; + break; + } + foreach (SerializationMemberMetadata field in nested.members) + { + if ((field.visibility & PropertyVisibility.Serialize) != 0 && !IsKnownDefault(field.type)) + { + eligible = false; + break; + } + } + } + // An unresolved fact can become known through an ordinary write in this same operation. + // Cache only positive proofs; a key query still never invokes the resolver itself. + if (eligible) + { + plans[metadata] = (source, true); + } + return eligible; + } + + internal ConverterInvoker? Resolve(Type valueType) + { + ArgumentNullException.ThrowIfNull(valueType); + ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + Type normalizedType = Nullable.GetUnderlyingType(valueType) ?? valueType; + if (snapshot.cache.TryGetValue(normalizedType, out ConverterInvoker? cached)) + { + return cached; + } + lock (snapshot.sync) + { + if (snapshot.cache.TryGetValue(normalizedType, out cached)) + { + return cached; + } + ConverterInvoker? resolved = ConverterRegistry.ResolveSnapshot(snapshot, normalizedType); + if (!snapshot.cache.TryAdd(normalizedType, resolved)) + { + throw new InvalidOperationException("The serialization converter resolution was published twice."); + } + return resolved; + } + } + + private bool IsKnownDefault(Type type) + { + ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + Type normalized = Nullable.GetUnderlyingType(type) ?? type; + // Reuse only facts established by the authoritative resolver. A key query must not + // construct converters, change their execution order, or introduce another resolver. + return snapshot.cache.TryGetValue(normalized, out ConverterInvoker? converter) && converter is null; + } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs new file mode 100644 index 000000000..c305d2543 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization; + +internal sealed record MapSerializationNode : SerializationNode +{ + internal List> values { get; } = []; +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs new file mode 100644 index 000000000..f7010c0c6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization; + +internal sealed record NullSerializationNode : SerializationNode +{ + private NullSerializationNode() {} + + internal static NullSerializationNode instance { get; } = new(); +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs new file mode 100644 index 000000000..7e6ce6ca6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Inno.Core.Serialization; + +internal sealed record ObjectSerializationNode : SerializationNode +{ + private byte[]? m_encodedCapture; + private int m_encodingTooLarge; + + internal SerializationCaptureKey? captureKey { get; set; } + internal OrderedDictionary values { get; } = new(StringComparer.Ordinal); + internal byte[]? encodedCapture => Volatile.Read(ref m_encodedCapture); + internal bool encodingTooLarge => Volatile.Read(ref m_encodingTooLarge) != 0; + + internal byte[] PublishEncodedCapture(byte[] data) => Interlocked.CompareExchange(ref m_encodedCapture, data, null) ?? data; + + internal void RejectEncodedCapture() => Volatile.Write(ref m_encodingTooLarge, 1); +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs index e35ad6fa5..9c144772e 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs @@ -15,7 +15,7 @@ internal static byte[] Encode(IReadOnlyList member in members) { byte[] data = BinarySerializationFormat.Encode(member.Value); writer.Write(member.Key); @@ -49,24 +49,34 @@ internal static IReadOnlyList Decode(ReadOnlySpan using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); string magic = reader.ReadString(); if (!string.Equals(magic, C_MAGIC, StringComparison.Ordinal)) + { throw new InvalidDataException($"Invalid property snapshot magic '{magic}'."); + } int count = reader.ReadInt32(); if (count < 0) + { throw new InvalidDataException("Property snapshot count cannot be negative."); + } var snapshots = new SerializationPropertySnapshot[count]; for (int i = 0; i < count; i++) { string name = reader.ReadString(); int length = reader.ReadInt32(); if (length < 0 || length > stream.Length - stream.Position) + { throw new InvalidDataException($"Property snapshot '{name}' length is invalid."); + } byte[] data = reader.ReadBytes(length); if (data.Length != length) + { throw new EndOfStreamException($"Property snapshot '{name}' is truncated."); + } snapshots[i] = new SerializationPropertySnapshot(name, typeof(object), data); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Property snapshot data contains trailing bytes."); + } return snapshots; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs index 93572b9cb..06c3ae726 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; namespace Inno.Core.Serialization; @@ -11,7 +12,9 @@ internal static BinarySerializationNode CaptureData( ConverterRegistryLease converters, BinarySerializationNode? previous ) { - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; KeyValuePair[]? before = previous?.properties?.members; List>? captured = before is null ? [] : null; int count = 0; @@ -22,20 +25,28 @@ internal static BinarySerializationNode CaptureData( { SerializationMemberMetadata member = members[index]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; - SerializationNode? prior = before is not null && count < before.Length && - string.Equals(before[count].Key, member.name, StringComparison.Ordinal) - ? before[count].Value - : null; - SerializationNode node = ValuePipeline.Write(member.GetValue(value), member.type, operation, - prior?.capturePath ?? AppendPath(member.name), allowDefaultObject: false, prior); + } + SerializationNode? prior = before is not null && count < before.Length + && string.Equals(before[count].Key, member.name, StringComparison.Ordinal) + ? before[count].Value + : null; + SerializationNode node = ValuePipeline.Write( + member.GetValue(value), + member.type, + operation, + prior?.capturePath ?? AppendPath(member.name), + allowDefaultObject: false, + prior + ); operation.RetireCaptureMember(); if (captured is null && !ReferenceEquals(node, prior)) { - captured = new(before!); + captured = [.. before!]; captured.RemoveRange(count, captured.Count - count); } - captured?.Add(new(member.name, node)); + captured?.Add(new KeyValuePair(member.name, node)); count++; } } @@ -44,14 +55,17 @@ internal static BinarySerializationNode CaptureData( operation.Fail(); } if (captured is null && before is not null && count == before.Length) - return previous!.properties!.hasConverters == (operation.converterWrites != 0) ? previous - : new BinarySerializationNode(previous.value) - { - properties = new(before) { hasConverters = operation.converterWrites != 0 } - }; + { + return previous!.properties!.hasConverters == (operation.converterWrites != 0) + ? previous + : new BinarySerializationNode(previous.value) + { + properties = new(before) { hasConverters = operation.converterWrites != 0 } + }; + } if (captured is null) { - captured = new(before!); + captured = [.. before!]; captured.RemoveRange(count, captured.Count - count); } var state = new PropertyDataCapture([.. captured]) { hasConverters = operation.converterWrites != 0 }; @@ -65,17 +79,22 @@ internal static SerializationPropertySnapshot CaptureProperty( ConverterRegistryLease converters ) { ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; for (int index = 0; index < members.Count; index++) { SerializationMemberMetadata member = members[index]; - if ((member.visibility & PropertyVisibility.Serialize) != 0 && - string.Equals(member.name, propertyName, StringComparison.Ordinal)) + if ((member.visibility & PropertyVisibility.Serialize) != 0 + && string.Equals(member.name, propertyName, StringComparison.Ordinal) + ) { return CaptureMember(value, member, context, converters); + } } throw new ArgumentException( $"Serializable property '{propertyName}' was not found on '{value.GetType().FullName}'.", - nameof(propertyName)); + nameof(propertyName) + ); } internal static IReadOnlyList Capture( @@ -83,13 +102,17 @@ internal static IReadOnlyList Capture( SerializationContext context, ConverterRegistryLease converters ) { - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; var snapshots = new List(members.Count); for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } snapshots.Add(CaptureMember(value, member, context, converters)); } @@ -103,17 +126,21 @@ internal static SerializationPropertyRestoreResult Restore( SerializationContext context, ConverterRegistryLease converters ) { - IReadOnlyList members = context.GetRequired().GetMetadata(target.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(target.GetType()).members; var membersByName = new Dictionary(members.Count, StringComparer.Ordinal); for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Deserialize) != 0) + { membersByName.Add(member.name, member); + } } ValidateSnapshots(snapshots); - var failures = new List(); + List failures = []; int restoredCount = 0; int ignoredCount = 0; var operation = new SerializationOperation(context, converters); @@ -137,20 +164,24 @@ ConverterRegistryLease converters member.type, operation, AppendPath(member.name), - allowDefaultObject: false); + allowDefaultObject: false + ); member.SetValue(target, value); restoredCount++; } catch (Exception exception) when ( - mode == SerializationPropertyRestoreMode.CollectFailures && - IsRecoverable(exception)) + mode == SerializationPropertyRestoreMode.CollectFailures + && IsRecoverable(exception)) { operation.Rollback(checkpoint); - failures.Add(new SerializationPropertyRestoreFailure( - member.name, - snapshot.propertyType, - member.type, - Unwrap(exception).Message)); + failures.Add( + new SerializationPropertyRestoreFailure( + member.name, + snapshot.propertyType, + member.type, + Unwrap(exception).Message + ) + ); } } @@ -176,7 +207,8 @@ private static void ValidateSnapshots(IReadOnlyList exception is not OutOfMemoryException and - not StackOverflowException and - not AccessViolationException and - not OperationCanceledException; + => exception is not OutOfMemoryException + and not StackOverflowException + and not AccessViolationException + and not OperationCanceledException; private static Exception Unwrap(Exception exception) - => exception is System.Reflection.TargetInvocationException { InnerException: not null } invocation - ? invocation.InnerException! - : exception; + => exception is TargetInvocationException { InnerException: not null } invocation + ? invocation.InnerException! + : exception; private static string AppendPath(string name) => "$." + name; } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs index 327c1118a..435c348b2 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs @@ -8,24 +8,33 @@ internal struct SerializationArrayCapture(ArraySerializationNode? previous) private List? m_values; private int m_count; - internal SerializationNode? Next => previous is not null && m_count < previous.values.Count - ? previous.values[m_count] - : null; + internal SerializationNode? next + => previous is not null && m_count < previous.values.Count + ? previous.values[m_count] + : null; internal ArraySerializationNode? initialNode => m_initialNode; internal void Add(SerializationNode value) { if (m_initialNode is not null) + { m_values = m_initialNode.values; - if (m_values is null && !ReferenceEquals(Next, value)) - m_values = previous is null ? [] : new(previous.values); + } + if (m_values is null && !ReferenceEquals(next, value)) + { + m_values = previous is null ? [] : new List(previous.values); + } if (m_values is not null) { if (m_count < m_values.Count) + { m_values[m_count] = value; + } else + { m_values.Add(value); + } } m_count++; } @@ -33,12 +42,18 @@ internal void Add(SerializationNode value) internal ArraySerializationNode Complete() { if (m_initialNode is not null) + { return m_initialNode; + } if (previous is not null && m_count == previous.values.Count && m_values is null) + { return previous; - m_values ??= previous is null ? [] : new(previous.values); + } + m_values ??= previous is null ? [] : new List(previous.values); if (m_values.Count > m_count) + { m_values.RemoveRange(m_count, m_values.Count - m_count); + } return new ArraySerializationNode(m_values); } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs index 236ccaa0f..568f5fb49 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using System.Threading; namespace Inno.Core.Serialization; @@ -13,16 +11,9 @@ internal abstract record SerializationNode internal void RememberPath(string path) { if (this is not NullSerializationNode) + { Interlocked.CompareExchange(ref m_capturePath, path, null); - } -} - -internal sealed record NullSerializationNode : SerializationNode -{ - internal static NullSerializationNode instance { get; } = new(); - - private NullSerializationNode() - { + } } } @@ -32,31 +23,3 @@ internal sealed record BinarySerializationNode(byte[] value) : SerializationNode { internal PropertyDataCapture? properties { get; init; } } - -internal sealed record ObjectSerializationNode : SerializationNode -{ - private byte[]? m_encodedCapture; - private int m_encodingTooLarge; - - internal SerializationCaptureKey? captureKey { get; set; } - internal OrderedDictionary values { get; } = new(StringComparer.Ordinal); - internal byte[]? encodedCapture => Volatile.Read(ref m_encodedCapture); - internal bool encodingTooLarge => Volatile.Read(ref m_encodingTooLarge) != 0; - - internal byte[] PublishEncodedCapture(byte[] data) => Interlocked.CompareExchange(ref m_encodedCapture, data, null) ?? data; - internal void RejectEncodedCapture() => Volatile.Write(ref m_encodingTooLarge, 1); -} - -internal sealed record ArraySerializationNode : SerializationNode -{ - internal ArraySerializationNode() : this([]) { } - - internal ArraySerializationNode(List values) => this.values = values; - - internal List values { get; } -} - -internal sealed record MapSerializationNode : SerializationNode -{ - internal List> values { get; } = []; -} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs index 098fdd46d..427966e50 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs @@ -14,7 +14,9 @@ internal static ObjectSerializationNode WithCaptureKey( if (!ReferenceEquals(result.captureKey, key)) { if (ReferenceEquals(result, previous)) + { result = CopyObject(result); + } result.captureKey = key; } return result; @@ -25,47 +27,36 @@ internal static bool SameScalar( object previous ) { if (typeof(T) == typeof(float)) + { return BitConverter.SingleToInt32Bits(Unsafe.As(ref value)) == BitConverter.SingleToInt32Bits((float)previous); + } if (typeof(T) == typeof(double)) + { return BitConverter.DoubleToInt64Bits(Unsafe.As(ref value)) == BitConverter.DoubleToInt64Bits((double)previous); + } if (typeof(T) == typeof(decimal)) + { return SameScalar((object)Unsafe.As(ref value), previous); + } return EqualityComparer.Default.Equals(value, (T)previous); } - internal static ObjectSerializationNode CopyObject(ObjectSerializationNode previous) - { - var result = new ObjectSerializationNode(); - result.values.EnsureCapacity(previous.values.Count); - foreach (var pair in previous.values) - result.values.Add(pair.Key, pair.Value); - return result; - } - - internal static SerializationNode Scalar( - object value, - SerializationNode? previous - ) => previous is ScalarSerializationNode scalar && SameScalar(value, scalar.value) - ? scalar - : new ScalarSerializationNode(value); - - internal static SerializationNode Binary( - byte[] value, - SerializationNode? previous - ) => previous is BinarySerializationNode binary && value.AsSpan().SequenceEqual(binary.value) - ? binary - : new BinarySerializationNode((byte[])value.Clone()); - internal static bool SameScalar( object value, object previous ) { if (value.GetType() != previous.GetType()) + { return false; + } if (value is float number) + { return BitConverter.SingleToInt32Bits(number) == BitConverter.SingleToInt32Bits((float)previous); + } if (value is double real) + { return BitConverter.DoubleToInt64Bits(real) == BitConverter.DoubleToInt64Bits((double)previous); + } if (value is decimal precision) { Span left = stackalloc int[4]; @@ -76,4 +67,29 @@ object previous } return value.Equals(previous); } + + internal static ObjectSerializationNode CopyObject(ObjectSerializationNode previous) + { + var result = new ObjectSerializationNode(); + result.values.EnsureCapacity(previous.values.Count); + foreach (KeyValuePair pair in previous.values) + { + result.values.Add(pair.Key, pair.Value); + } + return result; + } + + internal static SerializationNode Scalar( + object value, + SerializationNode? previous + ) => previous is ScalarSerializationNode scalar && SameScalar(value, scalar.value) + ? scalar + : new ScalarSerializationNode(value); + + internal static SerializationNode Binary( + byte[] value, + SerializationNode? previous + ) => previous is BinarySerializationNode binary && value.AsSpan().SequenceEqual(binary.value) + ? binary + : new BinarySerializationNode((byte[])value.Clone()); } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs index 83fbdfc1e..dfd5506b3 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs @@ -23,7 +23,7 @@ internal SerializationOperation( ArgumentNullException.ThrowIfNull(converters); this.context = context; m_converters = converters; - isSnapshotCapture = snapshotCapture; + this.isSnapshotCapture = snapshotCapture; } internal ConverterRegistryLease converters => m_converters; @@ -55,7 +55,9 @@ internal SerializationTypeMetadata GetMetadata(Type type) internal void EnsureActive() { if (!m_isActive) + { throw new InvalidOperationException("The serialization reader or writer is no longer active."); + } } internal void RecordConverterWrite() => m_converterWrites = checked(m_converterWrites + 1); @@ -68,7 +70,9 @@ internal BinarySerializationNode CapturePropertyData( EnsureActive(); BinarySerializationNode captured = PropertySnapshotPipeline.CaptureData(value, context, m_converters, previous); if (captured.properties?.hasConverters == true) + { RecordConverterWrite(); + } return captured; } @@ -83,12 +87,16 @@ internal void ScheduleRestoredObject(ISerializable value) { EnsureActive(); if (!(m_scheduledObjects ??= new(ReferenceEqualityComparer.Instance)).Add(value)) + { return; + } (m_scheduledObjectOrder ??= []).Add(value); Action? callback = GetMetadata(value.GetType()).restored; if (callback is not null) + { (m_completionCallbacks ??= []).Add(() => callback(value, context)); + } } internal void EnterCapture( @@ -100,7 +108,8 @@ string path if (captures.TryGetValue(value, out string? existingPath)) { throw new InvalidOperationException( - $"Serialization cycle detected at '{path}'. The same object is already being written at '{existingPath}'."); + $"Serialization cycle detected at '{path}'. The same object is already being written at '{existingPath}'." + ); } captures.Add(value, path); @@ -115,16 +124,18 @@ internal Checkpoint CreateCheckpoint() internal void Rollback(Checkpoint checkpoint) { EnsureActive(); - if (checkpoint.callbackCount < 0 || - checkpoint.callbackCount > (m_completionCallbacks?.Count ?? 0) || - checkpoint.scheduledObjectCount < 0 || - checkpoint.scheduledObjectCount > (m_scheduledObjectOrder?.Count ?? 0)) - { + if (checkpoint.callbackCount < 0 + || checkpoint.callbackCount > (m_completionCallbacks?.Count ?? 0) + || checkpoint.scheduledObjectCount < 0 + || checkpoint.scheduledObjectCount > (m_scheduledObjectOrder?.Count ?? 0) + ) { throw new InvalidOperationException("The serialization operation checkpoint is invalid."); } if (m_completionCallbacks is { } callbacks && callbacks.Count > checkpoint.callbackCount) + { callbacks.RemoveRange(checkpoint.callbackCount, callbacks.Count - checkpoint.callbackCount); + } if (m_scheduledObjectOrder is { } order) { for (int i = order.Count - 1; i >= checkpoint.scheduledObjectCount; i--) @@ -138,7 +149,9 @@ internal void Rollback(Checkpoint checkpoint) internal void ExitCapture(object value) { if (m_isActive) + { m_capturePaths?.Remove(value); + } } internal void Complete() @@ -147,8 +160,12 @@ internal void Complete() try { if (m_completionCallbacks is { } callbacks) + { for (int i = 0; i < callbacks.Count; i++) + { callbacks[i](); + } + } } finally { @@ -163,7 +180,9 @@ internal void Complete() internal void Fail() { if (!m_isActive) + { return; + } m_isActive = false; m_completionCallbacks?.Clear(); @@ -176,5 +195,4 @@ internal readonly record struct Checkpoint( int callbackCount, int scheduledObjectCount ); - } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs index 321ff7368..f9f2578da 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs @@ -18,15 +18,21 @@ internal static SerializationNode WriteRoot( { ConverterInvoker? converter = operation.ResolveConverter(declaredType); if (converter is not null) + { return converter.Write(operation, "$", declaredType, value, previous); + } if (operation.GetMetadata(declaredType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter." + ); + } if (value.GetType() != declaredType) { throw new InvalidOperationException( - $"Default root serialization requires exact type '{declaredType.FullName}', but the runtime value is '{value.GetType().FullName}'. Mark the root type with RequiresSerializationConverter and register a converter for polymorphism."); + $"Default root serialization requires exact type '{declaredType.FullName}', but the runtime value is '{value.GetType().FullName}'. Mark the root type with RequiresSerializationConverter and register a converter for polymorphism." + ); } EnsureDefaultSerializableType(declaredType, operation); var writer = new SerializationWriter(operation, previous as ObjectSerializationNode, "$", declaredType); @@ -46,10 +52,15 @@ SerializationOperation operation ) { ConverterInvoker? converter = operation.ResolveConverter(declaredType); if (converter is not null) + { return converter.Read(operation, "$", declaredType, RequireObject(node, declaredType, "$")); + } if (operation.GetMetadata(declaredType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter." + ); + } EnsureDefaultSerializableType(declaredType, operation); ISerializable instance = CreateSerializable(declaredType, operation); @@ -70,8 +81,11 @@ SerializationOperation operation return; } if (operation.GetMetadata(targetType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{targetType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{targetType.FullName}' requires an explicit serialization converter." + ); + } EnsureDefaultSerializableType(targetType, operation); RestoreProperties(target, RequireObject(node, targetType, "$"), operation, "$" ); @@ -86,80 +100,17 @@ internal static SerializationNode Write( SerializationNode? previous = null ) { operation.EnsureActive(); - if (previous is ScalarSerializationNode scalar && value is not null && - scalar.value.GetType() == declaredType && value.GetType() == declaredType && - operation.ResolveConverter(declaredType) is null && SerializationNodeReuse.SameScalar(value, scalar.value)) + if (previous is ScalarSerializationNode scalar && value is not null + && scalar.value.GetType() == declaredType && value.GetType() == declaredType + && operation.ResolveConverter(declaredType) is null && SerializationNodeReuse.SameScalar(value, scalar.value) + ) { return scalar; + } SerializationNode node = WriteValue(value, declaredType, operation, path, allowDefaultObject, previous); node.RememberPath(path); return node; } - private static SerializationNode WriteValue( - object? value, - Type declaredType, - SerializationOperation operation, - string path, - bool allowDefaultObject, - SerializationNode? previous = null - ) { - operation.EnsureActive(); - Type? nullableType = Nullable.GetUnderlyingType(declaredType); - Type valueType = nullableType ?? declaredType; - if (value is null) - { - if (valueType.IsValueType && nullableType is null) - throw new InvalidOperationException($"Non-nullable value '{path}' of type '{valueType.FullName}' cannot be null."); - return NullSerializationNode.instance; - } - - bool trackReference = !value.GetType().IsValueType && value is not string && value is not byte[]; - if (trackReference) - operation.EnterCapture(value, path); - try - { - ConverterInvoker? converter = operation.ResolveConverter(valueType); - if (converter is not null) - return converter.Write(operation, path, valueType, value, previous); - - if (IsPrimitive(valueType)) - return SerializationNodeReuse.Scalar(NormalizePrimitive(value, valueType, path), previous); - if (valueType.IsEnum) - return SerializationNodeReuse.Scalar(Convert.ToInt64(value, CultureInfo.InvariantCulture), previous); - if (valueType == typeof(byte[])) - return SerializationNodeReuse.Binary((byte[])value, previous); - if (valueType.IsArray) - return WriteArray((Array)value, valueType, operation, path, previous as ArraySerializationNode); - if (operation.GetMetadata(valueType).collection is { keyType: not null } map) - return WriteMap(value, valueType, map.keyType, map.elementType, operation, path, previous); - if (operation.GetMetadata(valueType).collection is { keyType: null } sequence) - return WriteSequence(value, sequence.elementType, operation, path, previous as ArraySerializationNode); - if (valueType.IsValueType) - return WriteStruct(value, valueType, operation, path, previous as ObjectSerializationNode); - - if (allowDefaultObject && value is ISerializable serializable) - { - if (value.GetType() != valueType) - { - throw new InvalidOperationException( - $"Default serialization at '{path}' requires exact type '{valueType.FullName}', but the runtime value is '{value.GetType().FullName}'. Register a converter for polymorphic values."); - } - EnsureDefaultSerializableType(valueType, operation); - var writer = new SerializationWriter(operation, previous as ObjectSerializationNode, path, valueType); - WriteProperties(serializable, writer, operation); - return writer.Complete(); - } - - throw new InvalidOperationException( - $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>."); - } - finally - { - if (trackReference) - operation.ExitCapture(value); - } - } - internal static object? Read( SerializationNode node, Type declaredType, @@ -173,30 +124,48 @@ bool allowDefaultObject if (node is NullSerializationNode) { if (!valueType.IsValueType || nullableType is not null) + { return null; + } throw new InvalidOperationException($"Non-nullable value '{path}' of type '{valueType.FullName}' cannot be null."); } ConverterInvoker? converter = operation.ResolveConverter(valueType); if (converter is not null) + { return converter.Read(operation, path, valueType, RequireObject(node, valueType, path)); + } if (IsPrimitive(valueType)) + { return ReadPrimitive(node, valueType, path); + } if (valueType.IsEnum) + { return Enum.ToObject(valueType, Convert.ToInt64(ReadScalar(node, path), CultureInfo.InvariantCulture)); + } if (valueType == typeof(byte[])) + { return node is BinarySerializationNode binary - ? (byte[])binary.value.Clone() - : throw TypeMismatch(path, "binary", node); + ? (byte[])binary.value.Clone() + : throw TypeMismatch(path, "binary", node); + } if (valueType.IsArray) + { return ReadArray(node, valueType, operation, path); + } if (operation.GetMetadata(valueType).collection is { keyType: not null } map) + { return ReadMap(node, valueType, map.keyType, map.elementType, operation, path); + } if (operation.GetMetadata(valueType).collection is { keyType: null } sequence) + { return ReadSequence(node, valueType, sequence.elementType, operation, path); + } if (valueType.IsValueType) + { return ReadStruct(node, valueType, operation, path); + } if (allowDefaultObject && typeof(ISerializable).IsAssignableFrom(valueType)) { @@ -207,7 +176,8 @@ bool allowDefaultObject } throw new InvalidOperationException( - $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>."); + $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>." + ); } internal static void WriteProperties( @@ -220,7 +190,9 @@ SerializationOperation operation { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } writer.Write(member.name, member.GetValue(value), member.type); } } @@ -235,20 +207,126 @@ string path for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; - if ((member.visibility & PropertyVisibility.Deserialize) == 0 || - !node.values.TryGetValue(member.name, out SerializationNode? memberNode)) - { + if ((member.visibility & PropertyVisibility.Deserialize) == 0 + || !node.values.TryGetValue(member.name, out SerializationNode? memberNode) + ) { continue; } member.SetValue( target, - Read(memberNode, member.type, operation, AppendPath(path, member.name), allowDefaultObject: false)); + Read(memberNode, member.type, operation, AppendPath(path, member.name), allowDefaultObject: false) + ); } operation.ScheduleRestoredObject(target); } + internal static bool IsPrimitive(Type type) + => type == typeof(bool) + || type == typeof(byte) + || type == typeof(sbyte) + || type == typeof(short) + || type == typeof(ushort) + || type == typeof(int) + || type == typeof(uint) + || type == typeof(long) + || type == typeof(ulong) + || type == typeof(float) + || type == typeof(double) + || type == typeof(decimal) + || type == typeof(string) + || type == typeof(Guid); + + private static SerializationNode WriteValue( + object? value, + Type declaredType, + SerializationOperation operation, + string path, + bool allowDefaultObject, + SerializationNode? previous = null + ) { + operation.EnsureActive(); + Type? nullableType = Nullable.GetUnderlyingType(declaredType); + Type valueType = nullableType ?? declaredType; + if (value is null) + { + if (valueType.IsValueType && nullableType is null) + { + throw new InvalidOperationException($"Non-nullable value '{path}' of type '{valueType.FullName}' cannot be null."); + } + return NullSerializationNode.instance; + } + + bool trackReference = !value.GetType().IsValueType && value is not string && value is not byte[]; + if (trackReference) + { + operation.EnterCapture(value, path); + } + try + { + ConverterInvoker? converter = operation.ResolveConverter(valueType); + if (converter is not null) + { + return converter.Write(operation, path, valueType, value, previous); + } + + if (IsPrimitive(valueType)) + { + return SerializationNodeReuse.Scalar(NormalizePrimitive(value, valueType, path), previous); + } + if (valueType.IsEnum) + { + return SerializationNodeReuse.Scalar(Convert.ToInt64(value, CultureInfo.InvariantCulture), previous); + } + if (valueType == typeof(byte[])) + { + return SerializationNodeReuse.Binary((byte[])value, previous); + } + if (valueType.IsArray) + { + return WriteArray((Array)value, valueType, operation, path, previous as ArraySerializationNode); + } + if (operation.GetMetadata(valueType).collection is { keyType: not null } map) + { + return WriteMap(value, valueType, map.keyType, map.elementType, operation, path, previous); + } + if (operation.GetMetadata(valueType).collection is { keyType: null } sequence) + { + return WriteSequence(value, sequence.elementType, operation, path, previous as ArraySerializationNode); + } + if (valueType.IsValueType) + { + return WriteStruct(value, valueType, operation, path, previous as ObjectSerializationNode); + } + + if (allowDefaultObject && value is ISerializable serializable) + { + if (value.GetType() != valueType) + { + throw new InvalidOperationException( + $"Default serialization at '{path}' requires exact type '{valueType.FullName}', but the runtime value is '{value.GetType().FullName}'. Register a converter for polymorphic values." + ); + } + EnsureDefaultSerializableType(valueType, operation); + var writer = new SerializationWriter(operation, previous as ObjectSerializationNode, path, valueType); + WriteProperties(serializable, writer, operation); + return writer.Complete(); + } + + throw new InvalidOperationException( + $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>." + ); + } + finally + { + if (trackReference) + { + operation.ExitCapture(value); + } + } + } + private static SerializationNode WriteArray( Array value, Type arrayType, @@ -257,11 +335,15 @@ private static SerializationNode WriteArray( ArraySerializationNode? previous ) { if (arrayType.GetArrayRank() != 1) + { throw new InvalidOperationException($"Only one-dimensional arrays are supported at '{path}'."); + } Type elementType = arrayType.GetElementType()!; var capture = new SerializationArrayCapture(previous); for (int i = 0; i < value.Length; i++) - capture.Add(Write(value.GetValue(i), elementType, operation, capture.Next?.capturePath ?? $"{path}[{i}]", false, capture.Next)); + { + capture.Add(Write(value.GetValue(i), elementType, operation, capture.next?.capturePath ?? $"{path}[{i}]", false, capture.next)); + } return capture.Complete(); } @@ -272,13 +354,19 @@ private static object ReadArray( string path ) { if (arrayType.GetArrayRank() != 1) + { throw new InvalidOperationException($"Only one-dimensional arrays are supported at '{path}'."); + } if (node is not ArraySerializationNode array) + { throw TypeMismatch(path, "array", node); + } Type elementType = arrayType.GetElementType()!; var values = new object?[array.values.Count]; for (int i = 0; i < values.Length; i++) + { values[i] = Read(array.values[i], elementType, operation, $"{path}[{i}]", false); + } return operation.GetMetadata(arrayType).collection!.buildSequence!(values); } @@ -290,12 +378,14 @@ private static SerializationNode WriteSequence( ArraySerializationNode? previous ) { if (value is not IEnumerable enumerable) + { throw new InvalidOperationException($"Sequence value '{path}' is not enumerable."); + } var capture = new SerializationArrayCapture(previous); int index = 0; foreach (object? element in enumerable) { - capture.Add(Write(element, elementType, operation, capture.Next?.capturePath ?? $"{path}[{index}]", false, capture.Next)); + capture.Add(Write(element, elementType, operation, capture.next?.capturePath ?? $"{path}[{index}]", false, capture.next)); index++; } return capture.Complete(); @@ -309,10 +399,14 @@ private static object ReadSequence( string path ) { if (node is not ArraySerializationNode array) + { throw TypeMismatch(path, "array", node); + } var values = new object?[array.values.Count]; for (int i = 0; i < values.Length; i++) + { values[i] = Read(array.values[i], elementType, operation, $"{path}[{i}]", false); + } return operation.GetMetadata(sequenceType).collection!.buildSequence!(values); } @@ -331,15 +425,20 @@ private static SerializationNode WriteMap( { KeyValuePair entry = entries[i]; if (entry.Key is null) + { throw new InvalidOperationException($"Map key '{path}[{i}].key' cannot be null."); - node.values.Add(new KeyValuePair( - Write(entry.Key, keyType, operation, $"{path}[{i}].key", false), - Write(entry.Value, mapValueType, operation, $"{path}[{i}].value", false))); - } - return previous is MapSerializationNode && - BinarySerializationFormat.Encode(node).AsSpan().SequenceEqual(BinarySerializationFormat.Encode(previous)) - ? previous - : node; + } + node.values.Add( + new KeyValuePair( + Write(entry.Key, keyType, operation, $"{path}[{i}].key", false), + Write(entry.Value, mapValueType, operation, $"{path}[{i}].value", false) + ) + ); + } + return previous is MapSerializationNode + && BinarySerializationFormat.Encode(node).AsSpan().SequenceEqual(BinarySerializationFormat.Encode(previous)) + ? previous + : node; } private static object ReadMap( @@ -351,13 +450,16 @@ private static object ReadMap( string path ) { if (node is not MapSerializationNode map) + { throw TypeMismatch(path, "map", node); + } var entries = new KeyValuePair[map.values.Count]; for (int i = 0; i < entries.Length; i++) { entries[i] = new KeyValuePair( Read(map.values[i].Key, keyType, operation, $"{path}[{i}].key", false), - Read(map.values[i].Value, mapValueType, operation, $"{path}[{i}].value", false)); + Read(map.values[i].Value, mapValueType, operation, $"{path}[{i}].value", false) + ); } return operation.GetMetadata(mapType).collection!.buildMap!(entries); } @@ -376,12 +478,20 @@ private static SerializationNode WriteStruct( { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } SerializationNode? prior = previous is not null && previous.values.TryGetValue(member.name, out SerializationNode? found) - ? found - : null; - SerializationNode captured = Write(member.GetValue(value), member.type, operation, - prior?.capturePath ?? AppendPath(path, member.name), false, prior); + ? found + : null; + SerializationNode captured = Write( + member.GetValue(value), + member.type, + operation, + prior?.capturePath ?? AppendPath(path, member.name), + false, + prior + ); if (!ReferenceEquals(prior, captured)) { node ??= SerializationNodeReuse.CopyObject(previous!); @@ -396,13 +506,17 @@ private static SerializationNode WriteStruct( { bool included = false; for (int index = 0; index < members.Count; index++) + { if (members[index].name == name && (members[index].visibility & PropertyVisibility.Serialize) != 0) { included = true; break; } + } if (!included) + { node.values.Remove(name); + } } } return node ?? previous!; @@ -420,9 +534,9 @@ string path for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; - if ((member.visibility & PropertyVisibility.Deserialize) == 0 || - !objectNode.values.TryGetValue(member.name, out SerializationNode? memberNode)) - { + if ((member.visibility & PropertyVisibility.Deserialize) == 0 + || !objectNode.values.TryGetValue(member.name, out SerializationNode? memberNode) + ) { continue; } member.SetValue(result, Read(memberNode, member.type, operation, AppendPath(path, member.name), false)); @@ -440,19 +554,23 @@ private static void EnsureDefaultSerializableType( SerializationOperation operation ) { if (!typeof(ISerializable).IsAssignableFrom(valueType)) + { throw new InvalidOperationException($"Type '{valueType.FullName}' does not implement ISerializable."); + } if (valueType.IsAbstract || valueType.IsInterface || operation.GetMetadata(valueType).requiresConverter) + { throw new InvalidOperationException($"Serializable type '{valueType.FullName}' requires an explicit converter."); + } } private static ObjectSerializationNode RequireObject( SerializationNode node, Type valueType, string path - ) - => node as ObjectSerializationNode - ?? throw new InvalidOperationException( - $"Serialization value '{path}' for '{valueType.FullName}' must be an object, but was '{GetNodeKind(node)}'."); + ) => node as ObjectSerializationNode + ?? throw new InvalidOperationException( + $"Serialization value '{path}' for '{valueType.FullName}' must be an object, but was '{GetNodeKind(node)}'." + ); private static object ReadPrimitive( SerializationNode node, @@ -461,11 +579,17 @@ string path ) { object scalar = ReadScalar(node, path); if (valueType == typeof(string)) + { return scalar is string text ? text : throw TypeMismatch(path, "string", node); + } if (valueType == typeof(Guid)) + { return scalar is Guid guid ? guid : throw TypeMismatch(path, "Guid", node); + } if (scalar.GetType() == valueType) + { return scalar; + } try { return Convert.ChangeType(scalar, valueType, CultureInfo.InvariantCulture)!; @@ -474,17 +598,17 @@ string path { throw new InvalidOperationException( $"Serialization scalar '{path}' cannot be converted from '{scalar.GetType().FullName}' to '{valueType.FullName}'.", - exception); + exception + ); } } private static object ReadScalar( SerializationNode node, string path - ) - => node is ScalarSerializationNode scalar - ? scalar.value - : throw TypeMismatch(path, "scalar", node); + ) => node is ScalarSerializationNode scalar + ? scalar.value + : throw TypeMismatch(path, "scalar", node); private static object NormalizePrimitive( object value, @@ -492,7 +616,9 @@ private static object NormalizePrimitive( string path ) { if (value.GetType() == valueType) + { return value; + } try { return Convert.ChangeType(value, valueType, CultureInfo.InvariantCulture)!; @@ -501,44 +627,28 @@ string path { throw new InvalidOperationException( $"Primitive value '{path}' cannot be converted to '{valueType.FullName}'.", - exception); + exception + ); } } - internal static bool IsPrimitive(Type type) - => type == typeof(bool) || - type == typeof(byte) || - type == typeof(sbyte) || - type == typeof(short) || - type == typeof(ushort) || - type == typeof(int) || - type == typeof(uint) || - type == typeof(long) || - type == typeof(ulong) || - type == typeof(float) || - type == typeof(double) || - type == typeof(decimal) || - type == typeof(string) || - type == typeof(Guid); - private static InvalidOperationException TypeMismatch( string path, string expected, SerializationNode actual - ) - => new($"Serialization value '{path}' must be {expected}, but was '{GetNodeKind(actual)}'."); + ) => new($"Serialization value '{path}' must be {expected}, but was '{GetNodeKind(actual)}'."); private static string GetNodeKind(SerializationNode node) => node switch - { - NullSerializationNode => "null", - ScalarSerializationNode => "scalar", - BinarySerializationNode => "binary", - ObjectSerializationNode => "object", - ArraySerializationNode => "array", - MapSerializationNode => "map", - _ => node.GetType().Name - }; + { + NullSerializationNode => "null", + ScalarSerializationNode => "scalar", + BinarySerializationNode => "binary", + ObjectSerializationNode => "object", + ArraySerializationNode => "array", + MapSerializationNode => "map", + _ => node.GetType().Name + }; private static string AppendPath( string path, diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs index aed8c7ab6..054812f65 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs @@ -16,55 +16,45 @@ public enum PropertyVisibility /// No participation in serialization, deserialization, or runtime access. /// None = 0, - /// /// Participates in serialization output. /// Serialize = 1 << 0, - /// /// Participates in deserialization (restore/read). /// Deserialize = 1 << 1, - /// /// Allows runtime retrieval through the API. /// RuntimeGet = 1 << 2, - /// /// Allows runtime assignment through the API. /// RuntimeSet = 1 << 3, - /// /// Can serialize, deserialize, and allow runtime get/set. /// Show = Serialize | Deserialize | RuntimeGet | RuntimeSet, - /// /// Can serialize and deserialize, but runtime code cannot get or set through . /// Hide = Serialize | Deserialize, - /// /// Can serialize and deserialize, runtime can get but cannot set. /// Runtime set attempts should be rejected (see behavior). /// Readonly = Serialize | Deserialize | RuntimeGet, - /// /// Does not participate in serialization or deserialization, but runtime can get/set. /// Transient = RuntimeGet | RuntimeSet, - /// /// Participates in serialization only (no deserialization), runtime can get/set. /// SerializeOnly = Serialize | RuntimeGet | RuntimeSet, - /// /// Participates in deserialization only (no serialization), runtime can get/set. /// - DeserializeOnly = Deserialize | RuntimeGet | RuntimeSet, + DeserializeOnly = Deserialize | RuntimeGet | RuntimeSet } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs index d74ce36aa..1a861978c 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs @@ -37,9 +37,12 @@ public SerializationCollectionMetadata( Func>>? enumerateMap ) { ArgumentNullException.ThrowIfNull(elementType); - if (keyType is null ? buildSequence is null || buildMap is not null || enumerateMap is not null - : buildSequence is not null || buildMap is null || enumerateMap is null) + if (keyType is null + ? buildSequence is null || buildMap is not null || enumerateMap is not null + : buildSequence is not null || buildMap is null || enumerateMap is null + ) { throw new ArgumentException("Collection metadata requires one complete sequence or map shape."); + } this.elementType = elementType; this.keyType = keyType; this.buildSequence = buildSequence; diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs index 8516cf784..7a0478fa8 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs @@ -41,9 +41,13 @@ public SerializationMemberMetadata( ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(type); if ((visibility & (PropertyVisibility.Serialize | PropertyVisibility.RuntimeGet)) != 0 && getter is null) + { throw new ArgumentException("Readable metadata requires a getter.", nameof(getter)); + } if ((visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0 && setter is null) + { throw new ArgumentException("Writable metadata requires a setter.", nameof(setter)); + } this.name = name; this.type = type; this.visibility = visibility; @@ -79,8 +83,9 @@ public SerializationMemberMetadata( /// Reading is not permitted by this metadata. /// public object? GetValue(object target) - => m_getter is not null ? m_getter(target) - : throw new InvalidOperationException($"Serialization member '{name}' does not permit reads."); + => m_getter is not null + ? m_getter(target) + : throw new InvalidOperationException($"Serialization member '{name}' does not permit reads."); /// /// Writes a value through the selected declaration accessor. @@ -99,7 +104,9 @@ public void SetValue( object? value ) { if (m_setter is null) + { throw new InvalidOperationException($"Serialization member '{name}' does not permit writes."); + } m_setter(target, value); } } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs index 58ffff6fe..e79d07c67 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Identity; namespace Inno.Core.Serialization; @@ -50,22 +51,29 @@ public SerializationTypeMetadata( ) { ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(members); - SerializationMemberMetadata[] completeMembers = inherited is null ? members.ToArray() - : inherited.members.Concat(members).ToArray(); + SerializationMemberMetadata[] completeMembers = inherited is null + ? members.ToArray() + : inherited.members.Concat(members).ToArray(); var names = new HashSet(StringComparer.Ordinal); foreach (SerializationMemberMetadata member in completeMembers) + { if (member is null || !names.Add(member.name)) + { throw new ArgumentException("Serialization metadata requires nonnull members with unique keys.", nameof(members)); + } + } this.type = type; this.members = Array.AsReadOnly(completeMembers); - this.restored = inherited?.restored is not Action baseRestored ? restored - : restored is null ? baseRestored : ( - value, - context - ) => { - baseRestored(value, context); - restored(value, context); - }; + this.restored = inherited?.restored is not Action baseRestored + ? restored + : restored is null ? baseRestored : ( + value, + context + ) => + { + baseRestored(value, context); + restored(value, context); + }; this.collection = collection; this.requiresConverter = requiresConverter || inherited?.requiresConverter == true; m_factory = factory; @@ -107,9 +115,15 @@ public SerializationTypeMetadata( /// public SerializationTypeMetadata WithPureFieldAccess() { - if (!type.IsValueType || requiresConverter || collection is not null || - members.Any(static member => (member.visibility & PropertyVisibility.Serialize) != 0 && !ValuePipeline.IsPrimitive(member.type))) - throw new InvalidOperationException("Pure field capture requires a default value type containing only primitive serialized fields."); + if (!type.IsValueType || requiresConverter || collection is not null + || members.Any( + static member => (member.visibility & PropertyVisibility.Serialize) != 0 && !ValuePipeline.IsPrimitive(member.type) + ) + ) { + throw new InvalidOperationException( + "Pure field capture requires a default value type containing only primitive serialized fields." + ); + } return new SerializationTypeMetadata(type, members, m_factory, restored, collection, requiresConverter) { hasPureFieldAccess = true @@ -134,11 +148,12 @@ public SerializationTypeMetadata WithPureFieldAccess() public SerializationTypeMetadata WithCaptureRevision(Func readRevision) { ArgumentNullException.ThrowIfNull(readRevision); - if (!type.IsSealed || type.IsValueType || !typeof(ISerializable).IsAssignableFrom(type) || - !typeof(Inno.Core.Identity.IdentityObject).IsAssignableFrom(type)) - { + if (!type.IsSealed || type.IsValueType || !typeof(ISerializable).IsAssignableFrom(type) + || !typeof(IdentityObject).IsAssignableFrom(type) + ) { throw new InvalidOperationException( - "Capture revision metadata requires a sealed serializable Core identity source."); + "Capture revision metadata requires a sealed serializable Core identity source." + ); } return new SerializationTypeMetadata(type, members, m_factory, restored, collection, requiresConverter) { @@ -159,7 +174,11 @@ public SerializationTypeMetadata WithCaptureRevision(Func readRe public object CreateInstance() { if (m_factory is null) - throw new InvalidOperationException($"Serialization type '{type}' requires a parameterless constructor or an explicit converter."); + { + throw new InvalidOperationException( + $"Serialization type '{type}' requires a parameterless constructor or an explicit converter." + ); + } try { return m_factory(); diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs index 5fa15cdf5..bbce6bda8 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs @@ -7,14 +7,26 @@ namespace Inno.Core.Serialization; /// public sealed class SerializedProperty { - #region Backing Delegates - private readonly Func m_getter; private readonly Action m_setter; - #endregion - - #region Public State + internal SerializedProperty( + string name, + Type propertyType, + Func getter, + Action setter, + PropertyVisibility visibility, + bool canRead, + bool canWrite + ) { + this.name = name; + this.propertyType = propertyType; + this.visibility = visibility; + this.canRead = canRead; + this.canWrite = canWrite; + m_getter = getter; + m_setter = setter; + } /// /// Gets the display and serialization key name. @@ -41,32 +53,6 @@ public sealed class SerializedProperty /// public bool canWrite { get; } - #endregion - - #region Construction - - internal SerializedProperty( - string name, - Type propertyType, - Func getter, - Action setter, - PropertyVisibility visibility, - bool canRead, - bool canWrite - ) { - this.name = name; - this.propertyType = propertyType; - this.visibility = visibility; - this.canRead = canRead; - this.canWrite = canWrite; - m_getter = getter; - m_setter = setter; - } - - #endregion - - #region Public API - /// /// Gets the current value. /// @@ -79,7 +65,9 @@ bool canWrite public object? GetValue() { if (!canRead) + { throw new InvalidOperationException($"Serialized property '{name}' does not permit runtime reads."); + } return m_getter(); } @@ -95,9 +83,9 @@ bool canWrite public void SetValue(object? value) { if (!canWrite) + { throw new InvalidOperationException($"Serialized property '{name}' does not permit runtime writes."); + } m_setter(value); } - - #endregion } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs index 2eb944c41..a22737c60 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs @@ -29,30 +29,37 @@ public StaticSerializationMetadataSource(IReadOnlyList + /// public SerializationTypeMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); - return m_metadata.TryGetValue(type, out SerializationTypeMetadata? metadata) ? metadata - : throw new InvalidOperationException($"Serialization type '{type}' has no generated closed shape."); + return m_metadata.TryGetValue(type, out SerializationTypeMetadata? metadata) + ? metadata + : throw new InvalidOperationException($"Serialization type '{type}' has no generated closed shape."); } private void Register(SerializationTypeMetadata metadata) { ArgumentNullException.ThrowIfNull(metadata); if (m_metadata.TryAdd(metadata.type, metadata)) + { return; + } SerializationTypeMetadata existing = m_metadata[metadata.type]; if (existing.requiresConverter != metadata.requiresConverter || existing.members.Count != metadata.members.Count || existing.collection?.elementType != metadata.collection?.elementType - || existing.collection?.keyType != metadata.collection?.keyType) + || existing.collection?.keyType != metadata.collection?.keyType + ) { throw new ArgumentException($"Generated serialization shape '{metadata.type}' is inconsistent."); + } for (int index = 0; index < existing.members.Count; index++) { SerializationMemberMetadata left = existing.members[index]; SerializationMemberMetadata right = metadata.members[index]; if (left.name != right.name || left.type != right.type || left.visibility != right.visibility) + { throw new ArgumentException($"Generated serialization member '{metadata.type}.{left.name}' is inconsistent."); + } } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Serialization/Properties/ScriptingApi.cs index 0e7e0a458..41f55f2f2 100644 --- a/src/foundation/core/Inno.Core.Serialization/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Serialization/Properties/ScriptingApi.cs @@ -1,15 +1,13 @@ -using Inno.Scripting.Api; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Serialization", - "Inno.Core.Serialization", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Serialization", "Inno.Core.Serialization", ScriptingApiScope.Runtime)] [assembly: ScriptingApiNamespace( "InnoEngine.Serialization", "Inno.Core.Serialization.Converters", - ScriptingApiScope.Runtime)] + ScriptingApiScope.Runtime +)] [assembly: ScriptingApiExport(typeof(ISerializable), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(OnSerializableRestored), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Serialization/PropertyRestoration/SerializationPropertyRestoreMode.cs b/src/foundation/core/Inno.Core.Serialization/PropertyRestoration/SerializationPropertyRestoreMode.cs index d259800b0..48deff368 100644 --- a/src/foundation/core/Inno.Core.Serialization/PropertyRestoration/SerializationPropertyRestoreMode.cs +++ b/src/foundation/core/Inno.Core.Serialization/PropertyRestoration/SerializationPropertyRestoreMode.cs @@ -9,7 +9,6 @@ public enum SerializationPropertyRestoreMode /// Stops at the first property that cannot be restored into the current object. /// Strict, - /// /// Continues restoring independent properties and reports every rejected value. /// diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs b/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs index 170086068..54aeed17e 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs @@ -48,8 +48,7 @@ ConverterRegistryLease converters public byte[] Serialize( T value, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable => m_owner.Serialize(value, GetConverters(), context); /// @@ -73,8 +72,7 @@ public byte[] Serialize( public T Deserialize( ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable => m_owner.Deserialize(bytes, GetConverters(), context); /// @@ -98,8 +96,7 @@ public T Deserialize( public byte[] Encode( Action write, SerializationContext? context = null - ) - => m_owner.Encode(write, GetConverters(), context); + ) => m_owner.Encode(write, GetConverters(), context); /// /// Decodes a manually defined structured root using the converter generation captured by this instance. @@ -129,8 +126,7 @@ public TResult Decode( ReadOnlySpan bytes, Func read, SerializationContext? context = null - ) - => m_owner.Decode(bytes, read, GetConverters(), context); + ) => m_owner.Decode(bytes, read, GetConverters(), context); /// /// Releases the pinned converter generation and every collectible type reference owned by this lease. diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs index 90ac448cc..8431cb36b 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs @@ -22,20 +22,21 @@ public sealed class SerializationRegistry : IDisposable /// /// The type catalog that owns converter extension generations. /// - /// - /// Thrown when is null. - /// /// /// The declaration access provider selected by the same composition root. /// + /// + /// Thrown when is null. + /// [ScriptingApiIgnore] public SerializationRegistry( TypeCatalog types, ISerializationMetadataSource metadata ) { ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(metadata); m_types = types; - m_metadata = metadata ?? throw new ArgumentNullException(nameof(metadata)); + m_metadata = metadata; m_converters = new ConverterRegistry(types); } @@ -45,7 +46,9 @@ ISerializationMetadataSource metadata public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_converters.Dispose(); GC.SuppressFinalize(this); @@ -116,10 +119,20 @@ public IReadOnlyList GetProperties(ISerializable value) foreach (SerializationMemberMetadata member in members) { if ((member.visibility & PropertyVisibility.RuntimeGet) == 0) + { continue; - properties.Add(new SerializedProperty(member.name, member.type, - () => member.GetValue(value), propertyValue => member.SetValue(value, propertyValue), - member.visibility, true, (member.visibility & PropertyVisibility.RuntimeSet) != 0)); + } + properties.Add( + new SerializedProperty( + member.name, + member.type, + () => member.GetValue(value), + propertyValue => member.SetValue(value, propertyValue), + member.visibility, + true, + (member.visibility & PropertyVisibility.RuntimeSet) != 0 + ) + ); } return properties; } @@ -189,7 +202,8 @@ public byte[] CapturePropertyData( value, propertyName, CreateContext(context), - converters); + converters + ); return PropertySnapshotBinaryFormat.Encode([snapshot]); } @@ -279,14 +293,11 @@ public SerializationPropertyRestoreResult RestoreProperties( ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(snapshots); if (!Enum.IsDefined(mode)) + { throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown property restore mode."); + } using ConverterRegistryLease converters = m_converters.Capture(); - return PropertySnapshotPipeline.Restore( - target, - snapshots, - mode, - CreateContext(context), - converters); + return PropertySnapshotPipeline.Restore(target, snapshots, mode, CreateContext(context), converters); } /// @@ -329,14 +340,17 @@ public SerializationPropertyRestoreResult RestorePropertiesData( EnsureInitialized(); ArgumentNullException.ThrowIfNull(target); if (!Enum.IsDefined(mode)) + { throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown property restore mode."); + } using ConverterRegistryLease converters = m_converters.Capture(); return PropertySnapshotPipeline.Restore( target, PropertySnapshotBinaryFormat.Decode(data), mode, CreateContext(context), - converters); + converters + ); } /// @@ -363,8 +377,7 @@ public SerializationPropertyRestoreResult RestorePropertiesData( public byte[] Serialize( T value, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); ArgumentNullException.ThrowIfNull(value); @@ -392,12 +405,6 @@ public byte[] Serialize( /// Reference equality proves unchanged bytes; different instances may still encode identically. /// Ordinary serialization and snapshot encoding produce identical bytes. Capture failure publishes no snapshot. /// - /// - /// Writers borrowed by a snapshot converter belong to its synchronous callback and must not be used after it returns. - /// Default capture evaluates getters and converters in full. An explicitly opted-in converter may - /// reuse its prior node only after every current capture-key input has been verified. Ordinary - /// serialization never uses these keys; incomplete or unavailable declarations retain complete capture. - /// /// /// The source value is null. /// @@ -407,12 +414,19 @@ public byte[] Serialize( /// /// A converter, unsupported value or reference context prevents capture. /// + /// + /// Writers borrowed by a snapshot converter belong to its synchronous callback and must not be used after it returns. + /// Default capture evaluates getters and converters in full. An explicitly opted-in converter may + /// reuse its prior node only after every current capture-key input has been verified. Ordinary + /// serialization never uses these keys; incomplete or unavailable declarations retain complete capture. + /// [ScriptingApiIgnore] public SerializationSnapshot CaptureSnapshot( T value, SerializationContext? context = null, SerializationSnapshot? previous = null - ) where T : class, ISerializable { + ) where T : class, ISerializable + { EnsureInitialized(); ArgumentNullException.ThrowIfNull(value); using ConverterRegistryLease converters = m_converters.Capture(); @@ -428,27 +442,6 @@ public SerializationSnapshot CaptureSnapshot( } } - internal byte[] Serialize( - T value, - ConverterRegistryLease converters, - SerializationContext? context = null - ) - where T : class, ISerializable - { - ArgumentNullException.ThrowIfNull(value); - ArgumentNullException.ThrowIfNull(converters); - var operation = new SerializationOperation(CreateContext(context), converters); - try - { - SerializationNode root = ValuePipeline.WriteRoot(value, typeof(T), operation); - return BinarySerializationFormat.Encode(root); - } - finally - { - operation.Fail(); - } - } - /// /// Deserializes a new serializable root object from deterministic binary data. /// @@ -470,37 +463,13 @@ internal byte[] Serialize( public T Deserialize( ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); using ConverterRegistryLease converters = m_converters.Capture(); return Deserialize(bytes, converters, context); } - internal T Deserialize( - ReadOnlySpan bytes, - ConverterRegistryLease converters, - SerializationContext? context = null - ) - where T : class, ISerializable - { - ArgumentNullException.ThrowIfNull(converters); - SerializationNode root = BinarySerializationFormat.Decode(bytes); - var operation = new SerializationOperation(CreateContext(context), converters); - try - { - T result = (T)ValuePipeline.ReadRoot(root, typeof(T), operation); - operation.Complete(); - return result; - } - catch - { - operation.Fail(); - throw; - } - } - /// /// Restores deterministic binary data into an existing serializable root object. /// @@ -526,8 +495,7 @@ public void Restore( T target, ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); ArgumentNullException.ThrowIfNull(target); @@ -574,26 +542,6 @@ public byte[] Encode( return Encode(write, converters, context); } - internal byte[] Encode( - Action write, - ConverterRegistryLease converters, - SerializationContext? context = null - ) { - ArgumentNullException.ThrowIfNull(write); - ArgumentNullException.ThrowIfNull(converters); - var operation = new SerializationOperation(CreateContext(context), converters); - try - { - var writer = new SerializationWriter(operation, null, "$", typeof(object)); - write(writer); - return BinarySerializationFormat.Encode(writer.Complete()); - } - finally - { - operation.Fail(); - } - } - /// /// Decodes a manually defined structured schema from deterministic binary data. /// @@ -629,6 +577,68 @@ public TResult Decode( return Decode(bytes, read, converters, context); } + internal byte[] Serialize( + T value, + ConverterRegistryLease converters, + SerializationContext? context = null + ) where T : class, ISerializable + { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(converters); + var operation = new SerializationOperation(CreateContext(context), converters); + try + { + SerializationNode root = ValuePipeline.WriteRoot(value, typeof(T), operation); + return BinarySerializationFormat.Encode(root); + } + finally + { + operation.Fail(); + } + } + + internal T Deserialize( + ReadOnlySpan bytes, + ConverterRegistryLease converters, + SerializationContext? context = null + ) where T : class, ISerializable + { + ArgumentNullException.ThrowIfNull(converters); + SerializationNode root = BinarySerializationFormat.Decode(bytes); + var operation = new SerializationOperation(CreateContext(context), converters); + try + { + T result = (T)ValuePipeline.ReadRoot(root, typeof(T), operation); + operation.Complete(); + return result; + } + catch + { + operation.Fail(); + throw; + } + } + + internal byte[] Encode( + Action write, + ConverterRegistryLease converters, + SerializationContext? context = null + ) { + ArgumentNullException.ThrowIfNull(write); + ArgumentNullException.ThrowIfNull(converters); + var operation = new SerializationOperation(CreateContext(context), converters); + try + { + var writer = new SerializationWriter(operation, null, "$", typeof(object)); + write(writer); + return BinarySerializationFormat.Encode(writer.Complete()); + } + finally + { + operation.Fail(); + } + } + internal TResult Decode( ReadOnlySpan bytes, Func read, @@ -639,7 +649,9 @@ internal TResult Decode( ArgumentNullException.ThrowIfNull(converters); SerializationNode decoded = BinarySerializationFormat.Decode(bytes); if (decoded is not ObjectSerializationNode root) + { throw new InvalidOperationException("The advanced serialization root must be an object."); + } var operation = new SerializationOperation(CreateContext(context), converters); try @@ -655,21 +667,18 @@ internal TResult Decode( } } - private void EnsureInitialized() - { - if (m_disposed) - { - throw new ObjectDisposedException(nameof(SerializationRegistry)); - } - } + private void EnsureInitialized() => ObjectDisposedException.ThrowIf(m_disposed, this); private SerializationContext CreateContext(SerializationContext? context) { context ??= SerializationContext.empty; if (context.TryGet(out TypeCatalog? types) && ReferenceEquals(types, m_types) && context.TryGet(out SerializationRegistry? registry) && ReferenceEquals(registry, this) - && context.TryGet(out ISerializationMetadataSource? metadata) && ReferenceEquals(metadata, m_metadata)) + && context.TryGet(out ISerializationMetadataSource? metadata) + && ReferenceEquals(metadata, m_metadata) + ) { return context; + } return context.With(m_types).With(this).With(m_metadata); } } diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs index 4c03dc4d3..f3de7573d 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs @@ -13,7 +13,10 @@ namespace Inno.Core.Serialization; /// public sealed class SerializationSnapshot { - internal SerializationSnapshot(SerializationNode root) => this.root = root; + internal SerializationSnapshot(SerializationNode root) + { + this.root = root; + } /// /// Encodes this capture using the same deterministic binary format as ordinary serialization. @@ -29,10 +32,6 @@ public sealed class SerializationSnapshot /// /// The writable caller-owned stream, which remains open. /// - /// - /// Immutable keyed objects may retain canonical encoded blocks of at most 64 KiB each. Larger - /// objects remain streamed, and cached bytes never contain source objects or generation references. - /// /// /// The destination is null. /// @@ -42,11 +41,17 @@ public sealed class SerializationSnapshot /// /// The destination rejects a write; its partial bytes remain the caller's responsibility. /// + /// + /// Immutable keyed objects may retain canonical encoded blocks of at most 64 KiB each. Larger + /// objects remain streamed, and cached bytes never contain source objects or generation references. + /// public void WriteTo(Stream destination) { ArgumentNullException.ThrowIfNull(destination); if (!destination.CanWrite) + { throw new ArgumentException("A writable serialization destination is required.", nameof(destination)); + } BinarySerializationFormat.WriteTo(destination, root); } diff --git a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs index 81a73b941..ad8ee75c8 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs @@ -10,8 +10,8 @@ namespace Inno.Core.Serialization; /// public static class SerializedIdentityRemapper { - private static readonly byte[] s_valueMagic = Encoding.UTF8.GetBytes("INNO-BINARY-CURRENT"); - private static readonly byte[] s_propertyMagic = Encoding.UTF8.GetBytes("INNO-PROPERTY-SNAPSHOT-CURRENT"); + private static readonly byte[] VALUE_MAGIC = Encoding.UTF8.GetBytes("INNO-BINARY-CURRENT"); + private static readonly byte[] PROPERTY_MAGIC = Encoding.UTF8.GetBytes("INNO-PROPERTY-SNAPSHOT-CURRENT"); /// /// Replaces exact Guid and string values while retaining the binary serialization structure. @@ -37,14 +37,21 @@ public static byte[] Rewrite( IReadOnlyDictionary? paths = null ) { ArgumentNullException.ThrowIfNull(identities); - if (HasMagic(source, s_valueMagic)) + if (HasMagic(source, VALUE_MAGIC)) + { return BinarySerializationFormat.Encode(RewriteNode(BinarySerializationFormat.Decode(source), identities, paths)); - if (HasMagic(source, s_propertyMagic)) + } + if (HasMagic(source, PROPERTY_MAGIC)) { IReadOnlyList snapshots = PropertySnapshotBinaryFormat.Decode(source); - return PropertySnapshotBinaryFormat.Encode(snapshots.Select(snapshot => - new SerializationPropertySnapshot(snapshot.name, snapshot.propertyType, - Rewrite(snapshot.dataSpan, identities, paths))).ToArray()); + return PropertySnapshotBinaryFormat.Encode( + snapshots.Select(snapshot => + new SerializationPropertySnapshot( + snapshot.name, + snapshot.propertyType, + Rewrite(snapshot.dataSpan, identities, paths) + )).ToArray() + ); } return source.ToArray(); } @@ -59,31 +66,40 @@ private static SerializationNode RewriteNode( case ScalarSerializationNode { value: Guid id } when identities.TryGetValue(id, out Guid replacement): return new ScalarSerializationNode(replacement); case ScalarSerializationNode { value: string path } when paths is not null - && paths.TryGetValue(path, out string? replacement): + && paths.TryGetValue(path, out string? replacement): return new ScalarSerializationNode(replacement); case BinarySerializationNode binary: return new BinarySerializationNode(Rewrite(binary.value, identities, paths)); case ObjectSerializationNode value: { - var rewritten = new ObjectSerializationNode(); + var rewritten = new ObjectSerializationNode(); foreach ((string name, SerializationNode child) in value.values) + { rewritten.values.Add(name, RewriteNode(child, identities, paths)); + } return rewritten; } case ArraySerializationNode value: { - var rewritten = new ArraySerializationNode(); + var rewritten = new ArraySerializationNode(); foreach (SerializationNode child in value.values) + { rewritten.values.Add(RewriteNode(child, identities, paths)); + } return rewritten; } case MapSerializationNode value: { - var rewritten = new MapSerializationNode(); + var rewritten = new MapSerializationNode(); foreach (KeyValuePair entry in value.values) - rewritten.values.Add(new KeyValuePair( - RewriteNode(entry.Key, identities, paths), - RewriteNode(entry.Value, identities, paths))); + { + rewritten.values.Add( + new KeyValuePair( + RewriteNode(entry.Key, identities, paths), + RewriteNode(entry.Value, identities, paths) + ) + ); + } return rewritten; } default: @@ -94,7 +110,6 @@ private static SerializationNode RewriteNode( private static bool HasMagic( ReadOnlySpan source, ReadOnlySpan magic - ) - => source.Length > magic.Length && source[0] == magic.Length - && source.Slice(1, magic.Length).SequenceEqual(magic); + ) => source.Length > magic.Length && source[0] == magic.Length + && source.Slice(1, magic.Length).SequenceEqual(magic); } diff --git a/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs b/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs index 996e8515d..f910be133 100644 --- a/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs +++ b/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs @@ -11,7 +11,7 @@ public interface IProjectSettingsLookup /// /// Gets the unique lifetime identity of this settings owner; revisions from different owners are not interchangeable. /// - Guid ownerId { get; } + Guid ownerID { get; } /// /// Gets the revision of the active effective settings snapshot, paired with ownerId. @@ -31,7 +31,7 @@ public interface IProjectSettingsLookup /// /// An independently owned effective setting snapshot. /// - TSetting Get(ProjectSettingId id) + TSetting Get(ProjectSettingID id) where TSetting : class, ISerializable; /// @@ -51,8 +51,7 @@ TSetting Get(ProjectSettingId id) /// . /// bool TryGet( - ProjectSettingId id, + ProjectSettingID id, out TSetting? setting - ) - where TSetting : class, ISerializable; + ) where TSetting : class, ISerializable; } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectID.cs b/src/foundation/core/Inno.Core.Settings/ProjectID.cs new file mode 100644 index 000000000..99e451597 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectID.cs @@ -0,0 +1,129 @@ +using System; +using System.Text; + +namespace Inno.Core.Settings; + +/// +/// Identifies one project namespace used to qualify project-authored logical names. +/// +public readonly record struct ProjectID +{ + /// + /// Creates a portable project identifier. + /// + /// + /// Lowercase ASCII namespace segments. + /// + public ProjectID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + ValidatePortable(normalized, "Project ID", nameof(value)); + this.value = normalized; + } + + /// + /// Gets the canonical identifier text. + /// + public string value { get; } + + /// + /// Gets whether the value contains a usable identifier. + /// + public bool isValid => !string.IsNullOrEmpty(value); + + /// + /// Qualifies a local project name beneath this project namespace. + /// + /// + /// The portable local name. + /// + /// + /// The complete project-scoped identity. + /// + public ProjectScopedID Qualify(ProjectLocalID name) => new(this, name); + + /// + /// Formats the canonical identifier. + /// + /// + /// The canonical identifier text. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Creates a portable initial project identifier from a user-facing project name. + /// + /// + /// The project name used to derive the initial namespace. + /// + /// + /// A portable initial project identifier. + /// + public static ProjectID FromName(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var builder = new StringBuilder(name.Length); + bool pendingSeparator = false; + foreach (char character in name.Trim()) + { + if (character is >= 'A' and <= 'Z') + { + Append((char)(character + ('a' - 'A'))); + } + else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') + { + Append(character); + } + else + { + pendingSeparator = builder.Length > 0; + } + } + string value = builder.Length == 0 ? "inno.project" : builder.ToString(); + return new ProjectID(string.Equals(value, "project", StringComparison.Ordinal) ? "inno.project" : value); + + void Append(char character) + { + if (pendingSeparator) + { + builder.Append('-'); + } + pendingSeparator = false; + builder.Append(character); + } + } + + internal static void ValidatePortable( + string value, + string label, + string parameterName + ) { + if (value.Length > 128) + { + throw new ArgumentException($"{label} cannot exceed 128 characters.", parameterName); + } + for (int index = 0; index < value.Length; index++) + { + char character = value[index]; + bool valid = character is >= 'a' and <= 'z' + || character is >= '0' and <= '9' + || character is '.' or '-' or '_'; + if (!valid) + { + throw new ArgumentException( + $"{label} must use lowercase ASCII letters, digits, dots, hyphens, or underscores.", + parameterName + ); + } + } + if (value[0] is '.' or '-' or '_' || value[^1] is '.' or '-' or '_') + { + throw new ArgumentException($"{label} must begin and end with a letter or digit.", parameterName); + } + if (value.Contains("..", StringComparison.Ordinal)) + { + throw new ArgumentException($"{label} cannot contain empty namespace segments.", parameterName); + } + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs b/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs deleted file mode 100644 index 848c621f2..000000000 --- a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs +++ /dev/null @@ -1,299 +0,0 @@ -using System; -using System.Text; - -using Inno.Core.Serialization; -using Inno.Extensibility.Types; - -namespace Inno.Core.Settings; - -/// -/// Identifies one project namespace used to qualify project-authored logical names. -/// -public readonly record struct ProjectId -{ - /// - /// Creates a portable project identifier. - /// - /// - /// Lowercase ASCII namespace segments. - /// - public ProjectId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - ValidatePortable(normalized, "Project ID", nameof(value)); - this.value = normalized; - } - - /// - /// Creates a portable initial project identifier from a user-facing project name. - /// - /// - /// The project name used to derive the initial namespace. - /// - /// - /// A portable initial project identifier. - /// - public static ProjectId FromName(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - var builder = new StringBuilder(name.Length); - bool pendingSeparator = false; - foreach (char character in name.Trim()) - { - if (character is >= 'A' and <= 'Z') - Append((char)(character + ('a' - 'A'))); - else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') - Append(character); - else - pendingSeparator = builder.Length > 0; - } - string value = builder.Length == 0 ? "inno.project" : builder.ToString(); - return new ProjectId(string.Equals(value, "project", StringComparison.Ordinal) - ? "inno.project" - : value); - - void Append(char character) - { - if (pendingSeparator) - builder.Append('-'); - pendingSeparator = false; - builder.Append(character); - } - } - - /// - /// Gets the canonical identifier text. - /// - public string value { get; } - - /// - /// Gets whether the value contains a usable identifier. - /// - public bool isValid => !string.IsNullOrEmpty(value); - - /// - /// Qualifies a local project name beneath this project namespace. - /// - /// - /// The portable local name. - /// - /// - /// The complete project-scoped identity. - /// - public ProjectScopedId Qualify(ProjectLocalId name) => new(this, name); - - /// - /// Formats the canonical identifier. - /// - /// - /// The canonical identifier text. - /// - public override string ToString() => value ?? string.Empty; - - internal static void ValidatePortable( - string value, - string label, - string parameterName - ) { - if (value.Length > 128) - throw new ArgumentException($"{label} cannot exceed 128 characters.", parameterName); - for (int index = 0; index < value.Length; index++) - { - char character = value[index]; - bool valid = character is >= 'a' and <= 'z' - || character is >= '0' and <= '9' - || character is '.' or '-' or '_'; - if (!valid) - { - throw new ArgumentException( - $"{label} must use lowercase ASCII letters, digits, dots, hyphens, or underscores.", - parameterName); - } - } - if (value[0] is '.' or '-' or '_' || value[^1] is '.' or '-' or '_') - throw new ArgumentException($"{label} must begin and end with a letter or digit.", parameterName); - if (value.Contains("..", StringComparison.Ordinal)) - throw new ArgumentException($"{label} cannot contain empty namespace segments.", parameterName); - } -} - -/// -/// Stores the project-independent portion of one project-scoped identity. -/// -public readonly record struct ProjectLocalId -{ - /// - /// Creates a portable local identity. - /// - /// - /// Lowercase ASCII local namespace segments. - /// - public ProjectLocalId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - ProjectId.ValidatePortable(normalized, "Project-local ID", nameof(value)); - this.value = normalized; - } - - /// - /// Gets the canonical local identity text. - /// - public string value { get; } - - /// - /// Creates a deterministic portable local identity from a display name. - /// - /// - /// The user-facing name. - /// - /// - /// The normalized local identity. - /// - public static ProjectLocalId FromName(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - var builder = new StringBuilder(name.Length); - bool pendingSeparator = false; - foreach (char character in name.Trim()) - { - if (character is >= 'A' and <= 'Z') - { - AppendSeparator(builder, ref pendingSeparator); - builder.Append((char)(character + ('a' - 'A'))); - } - else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') - { - AppendSeparator(builder, ref pendingSeparator); - builder.Append(character); - } - else if (character is ' ' or '\t' or '.' or '-' or '_') - { - pendingSeparator = builder.Length > 0; - } - else - { - throw new ArgumentException( - "A project-scoped name must use ASCII letters, digits, spaces, dots, hyphens, or underscores.", - nameof(name)); - } - } - if (builder.Length == 0) - throw new ArgumentException("A project-scoped name must contain a letter or digit.", nameof(name)); - return new ProjectLocalId(builder.ToString()); - } - - /// - /// Formats the canonical local identity. - /// - /// - /// The canonical local identity text. - /// - public override string ToString() => value ?? string.Empty; - - private static void AppendSeparator( - StringBuilder builder, - ref bool pendingSeparator - ) { - if (pendingSeparator && builder.Length > 0) - builder.Append('-'); - pendingSeparator = false; - } -} - -/// -/// Combines a mutable project namespace with a stable project-independent local identity. -/// -public readonly record struct ProjectScopedId -{ - /// - /// Creates a qualified project identity. - /// - /// - /// The current project namespace. - /// - /// - /// The stable local identity. - /// - public ProjectScopedId( - ProjectId projectId, - ProjectLocalId name - ) { - if (!projectId.isValid) - throw new ArgumentException("A valid Project ID is required.", nameof(projectId)); - if (string.IsNullOrEmpty(name.value)) - throw new ArgumentException("A valid project-local ID is required.", nameof(name)); - this.projectId = projectId; - this.name = name; - } - - /// - /// Gets the project namespace. - /// - public ProjectId projectId { get; } - - /// - /// Gets the project-independent local identity. - /// - public ProjectLocalId name { get; } - - /// - /// Gets the canonical projectId.name representation. - /// - public string value => $"{projectId.value}.{name.value}"; - - /// - /// Formats the canonical qualified identity. - /// - /// - /// The projectId.name representation. - /// - public override string ToString() => value; -} - -/// -/// Stores the editable identity namespace of the current project. -/// -[StableTypeId("d5f90462-506d-4ff7-aa9f-0f14da28b9c3")] -[ProjectSettingDefinition(ProjectIdentitySettings.settingProtocolId, allowPluginContributions: false)] -public sealed class ProjectIdentitySettings : ISerializable -{ - /// - /// Gets the immutable project-setting protocol value used by discovery metadata. - /// - public const string settingProtocolId = "inno.project.identity"; - - private string m_projectId = "inno.project"; - - /// - /// Gets the stable project setting protocol identity. - /// - public static ProjectSettingId settingId => new(settingProtocolId); - - /// - /// Gets or sets the editable project namespace. - /// - [SerializableProperty] - public string projectId - { - get => m_projectId; - set => m_projectId = new ProjectId(value).value; - } - - /// - /// Gets the validated project identifier. - /// - public ProjectId id => new(m_projectId); - - /// - /// Qualifies a display name under the current project identifier. - /// - /// - /// The project-local display name. - /// - /// - /// The complete project-scoped identity. - /// - public ProjectScopedId Qualify(string name) => id.Qualify(ProjectLocalId.FromName(name)); -} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs b/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs new file mode 100644 index 000000000..9a1b646f2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs @@ -0,0 +1,50 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Core.Settings; + +/// +/// Stores the editable identity namespace of the current project. +/// +[StableTypeID("d5f90462-506d-4ff7-aa9f-0f14da28b9c3")] +[ProjectSettingDefinition(ProjectIdentitySettings.C_SETTING_PROTOCOL_ID, allowPluginContributions: false)] +public sealed class ProjectIdentitySettings : ISerializable +{ + /// + /// Gets the immutable project-setting protocol value used by discovery metadata. + /// + public const string C_SETTING_PROTOCOL_ID = "inno.project.identity"; + + private string m_projectID = "inno.project"; + + /// + /// Gets the stable project setting protocol identity. + /// + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); + + /// + /// Gets or sets the editable project namespace. + /// + [SerializableProperty] + public string projectId + { + get => m_projectID; + set => m_projectID = new ProjectID(value).value; + } + + /// + /// Gets the validated project identifier. + /// + public ProjectID id => new(m_projectID); + + /// + /// Qualifies a display name under the current project identifier. + /// + /// + /// The project-local display name. + /// + /// + /// The complete project-scoped identity. + /// + public ProjectScopedID Qualify(string name) => id.Qualify(ProjectLocalID.FromName(name)); +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs b/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs new file mode 100644 index 000000000..91ef890fb --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs @@ -0,0 +1,93 @@ +using System; +using System.Text; + +namespace Inno.Core.Settings; + +/// +/// Stores the project-independent portion of one project-scoped identity. +/// +public readonly record struct ProjectLocalID +{ + /// + /// Creates a portable local identity. + /// + /// + /// Lowercase ASCII local namespace segments. + /// + public ProjectLocalID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + ProjectID.ValidatePortable(normalized, "Project-local ID", nameof(value)); + this.value = normalized; + } + + /// + /// Gets the canonical local identity text. + /// + public string value { get; } + + /// + /// Formats the canonical local identity. + /// + /// + /// The canonical local identity text. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Creates a deterministic portable local identity from a display name. + /// + /// + /// The user-facing name. + /// + /// + /// The normalized local identity. + /// + public static ProjectLocalID FromName(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var builder = new StringBuilder(name.Length); + bool pendingSeparator = false; + foreach (char character in name.Trim()) + { + if (character is >= 'A' and <= 'Z') + { + AppendSeparator(builder, ref pendingSeparator); + builder.Append((char)(character + ('a' - 'A'))); + } + else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') + { + AppendSeparator(builder, ref pendingSeparator); + builder.Append(character); + } + else if (character is ' ' or '\t' or '.' or '-' or '_') + { + pendingSeparator = builder.Length > 0; + } + else + { + throw new ArgumentException( + "A project-scoped name must use ASCII letters, digits, spaces, dots, hyphens, or underscores.", + nameof(name) + ); + } + } + if (builder.Length == 0) + { + throw new ArgumentException("A project-scoped name must contain a letter or digit.", nameof(name)); + } + return new ProjectLocalID(builder.ToString()); + } + + private static void AppendSeparator( + StringBuilder builder, + ref bool pendingSeparator + ) { + if (pendingSeparator && builder.Length > 0) + { + builder.Append('-'); + } + pendingSeparator = false; + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs b/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs new file mode 100644 index 000000000..256f0904f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs @@ -0,0 +1,57 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Combines a mutable project namespace with a stable project-independent local identity. +/// +public readonly record struct ProjectScopedID +{ + /// + /// Creates a qualified project identity. + /// + /// + /// The current project namespace. + /// + /// + /// The stable local identity. + /// + public ProjectScopedID( + ProjectID projectID, + ProjectLocalID name + ) { + if (!projectID.isValid) + { + throw new ArgumentException("A valid Project ID is required.", nameof(projectID)); + } + if (string.IsNullOrEmpty(name.value)) + { + throw new ArgumentException("A valid project-local ID is required.", nameof(name)); + } + this.projectID = projectID; + this.name = name; + } + + /// + /// Gets the project namespace. + /// + public ProjectID projectID { get; } + + /// + /// Gets the project-independent local identity. + /// + public ProjectLocalID name { get; } + + /// + /// Gets the canonical projectId.name representation. + /// + public string value => $"{projectID.value}.{name.value}"; + + /// + /// Formats the canonical qualified identity. + /// + /// + /// The projectId.name representation. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs similarity index 50% rename from src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs rename to src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs index 636d6e137..1d4fb8bbb 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs @@ -1,133 +1,9 @@ using System; using System.Collections.Generic; - using Inno.Core.Serialization; namespace Inno.Core.Settings; -/// -/// Declares the protocol-owned composer used to combine contributions for one project setting. -/// Settings without a composer retain the default whole-value replacement behavior. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ProjectSettingComposerAttribute : Attribute -{ - /// - /// Creates a composer declaration for one stable setting protocol. - /// - /// - /// The setting protocol composed by the attributed type. - /// - public ProjectSettingComposerAttribute(string settingId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(settingId); - this.settingId = new ProjectSettingId(settingId); - } - - /// - /// Gets the stable setting protocol composed by the attributed type. - /// - public ProjectSettingId settingId { get; } -} - -/// -/// Identifies where one setting contribution originated. -/// -public enum ProjectSettingContributionSource -{ - /// - /// The contribution is a default supplied by an activated Plugin. - /// - Plugin, - - /// - /// The contribution is the project-authored delta with highest precedence. - /// - Project -} - -/// -/// Exposes ownership and dependency information while a protocol-owned composer combines one contribution. -/// -public sealed class ProjectSettingContributionContext -{ - private readonly IReadOnlySet m_dependencies; - private readonly IReadOnlySet m_overrides; - - internal ProjectSettingContributionContext( - string contributorId, - ProjectSettingContributionSource source, - IReadOnlySet dependencies, - IReadOnlySet overrides - ) { - this.contributorId = contributorId; - this.source = source; - m_dependencies = dependencies; - m_overrides = overrides; - } - - /// - /// Gets the stable Plugin ID, or project for the project-authored contribution. - /// - public string contributorId { get; } - - /// - /// Gets the contribution source. - /// - public ProjectSettingContributionSource source { get; } - - /// - /// Gets whether this is the project-authored highest-precedence contribution. - /// - public bool isProject => source == ProjectSettingContributionSource.Project; - - /// - /// Gets whether this contribution may explicitly replace data owned by another contributor. - /// - /// - /// The stable owner whose data would be replaced. - /// - /// - /// for project data, or when the Plugin both depends on and explicitly overrides - /// . - /// - public bool CanOverride(string ownerId) - { - ArgumentException.ThrowIfNullOrWhiteSpace(ownerId); - return isProject - || string.Equals(ownerId, "host", StringComparison.Ordinal) - || (m_dependencies.Contains(ownerId) && m_overrides.Contains(ownerId)); - } -} - -/// -/// Provides one decoded contribution and its immutable composition context. -/// -/// -/// The protocol-owned neutral contribution type. -/// -public sealed class ProjectSettingContribution - where TContribution : class, ISerializable -{ - internal ProjectSettingContribution( - ProjectSettingContributionContext context, - TContribution value - ) { - this.context = context; - this.value = value; - } - - /// - /// Gets the ownership and dependency context for this contribution. - /// - public ProjectSettingContributionContext context { get; } - - /// - /// Gets the decoded protocol-owned contribution value. - /// - public TContribution value { get; } -} - /// /// Defines the non-generic base for a protocol-owned project setting composer. /// @@ -164,6 +40,8 @@ public abstract class ProjectSettingComposer : ProjectS where TSetting : class, ISerializable where TContribution : class, ISerializable { + internal sealed override Type settingType => typeof(TSetting); + /// /// Captures the contribution introduced by the supplied project setting value. /// @@ -206,8 +84,6 @@ protected abstract void Compose( IReadOnlyList> contributions ); - internal sealed override Type settingType => typeof(TSetting); - internal sealed override bool TryCapture( SerializationRegistry serialization, SerializationContext serializationContext, @@ -218,11 +94,11 @@ out byte[] contributionData if (baseline is not TSetting typedBaseline || value is not TSetting typedValue) { throw new ArgumentException( - $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'."); + $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'." + ); } TContribution contribution = CaptureContribution(typedBaseline, typedValue) - ?? throw new InvalidOperationException( - $"Composer '{GetType().FullName}' returned a null contribution."); + ?? throw new InvalidOperationException($"Composer '{GetType().FullName}' returned a null contribution."); if (IsEmpty(contribution)) { contributionData = []; @@ -242,7 +118,8 @@ IReadOnlyList contributions { throw new ArgumentException( $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'.", - nameof(hostDefault)); + nameof(hostDefault) + ); } var decoded = new List>(contributions.Count); foreach (ProjectSettingCompositionEntry contribution in contributions) @@ -251,19 +128,13 @@ IReadOnlyList contributions if (IsEmpty(value)) { throw new InvalidOperationException( - $"Composer '{GetType().FullName}' received an empty persisted contribution from " + - $"'{contribution.context.contributorId}'."); + $"Composer '{GetType().FullName}' received an empty persisted contribution from " + + $"'{contribution.context.contributorID}'." + ); } - decoded.Add(new ProjectSettingContribution( - contribution.context, - value)); + decoded.Add(new ProjectSettingContribution(contribution.context, value)); } Compose(target, decoded); return target; } } - -internal sealed record ProjectSettingCompositionEntry( - ProjectSettingContributionContext context, - byte[] data -); diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs new file mode 100644 index 000000000..550d59c42 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Declares the protocol-owned composer used to combine contributions for one project setting. +/// Settings without a composer retain the default whole-value replacement behavior. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ProjectSettingComposerAttribute : Attribute +{ + /// + /// Creates a composer declaration for one stable setting protocol. + /// + /// + /// The setting protocol composed by the attributed type. + /// + public ProjectSettingComposerAttribute(string settingID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(settingID); + this.settingID = new ProjectSettingID(settingID); + } + + /// + /// Gets the stable setting protocol composed by the attributed type. + /// + public ProjectSettingID settingID { get; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs new file mode 100644 index 000000000..4326f9fe8 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Settings; + +internal sealed record ProjectSettingCompositionEntry( + ProjectSettingContributionContext context, + byte[] data +); diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs deleted file mode 100644 index 52d4c653f..000000000 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Core.Serialization; - -namespace Inno.Core.Settings; - -/// -/// Identifies one host-neutral project setting protocol. -/// -public record struct ProjectSettingId -{ - /// - /// Creates a project setting identifier. - /// - /// - /// Globally stable setting value. - /// - public ProjectSettingId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets or sets the globally stable setting value. - /// - public string value { get; set; } - - /// - /// Gets whether the identifier has a usable value. - /// - public readonly bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public readonly override string ToString() => value ?? string.Empty; -} - -/// -/// Declares a reloadable settings type under one stable protocol identity. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ProjectSettingDefinitionAttribute : Attribute -{ - /// - /// Creates a project setting declaration. - /// - /// - /// Globally stable setting identifier. - /// - /// - /// Whether Plugin packages may contribute values to this protocol. - /// - public ProjectSettingDefinitionAttribute( - string id, - bool allowPluginContributions = true - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.allowPluginContributions = allowPluginContributions; - } - - /// - /// Gets the globally stable setting identifier. - /// - public string id { get; } - - /// - /// Gets whether Plugin packages may contribute values to this protocol. - /// - public bool allowPluginContributions { get; } -} - -/// -/// Stores one protocol-owned neutral setting contribution for persistence and composition. -/// -public struct ProjectSettingRecord -{ - /// - /// Creates a setting record. - /// - /// - /// Stable setting identity. - /// - /// - /// Stable settings type identity. - /// - /// - /// Composer-owned contribution bytes, or complete property bytes for replacement settings. - /// - public ProjectSettingRecord( - ProjectSettingId id, - Guid stableTypeId, - ReadOnlySpan propertyData - ) { - if (!id.isValid) - throw new ArgumentException("A project setting ID must be valid.", nameof(id)); - if (stableTypeId == Guid.Empty) - throw new ArgumentException("A project setting requires a stable type ID.", nameof(stableTypeId)); - this.id = id; - this.stableTypeId = stableTypeId; - this.propertyData = propertyData.ToArray(); - } - - /// - /// Gets or sets the stable setting identity. - /// - public ProjectSettingId id { get; set; } - - /// - /// Gets or sets the stable settings type identity. - /// - public Guid stableTypeId { get; set; } - - /// - /// Gets or sets the composer-owned payload or default complete-property payload. - /// - public byte[] propertyData { get; set; } -} - -/// -/// Stores project-authored setting contributions in one native document. -/// -public sealed class ProjectSettingsDocument : ISerializable -{ - /// - /// Gets or sets project-authored protocol contributions. - /// - [SerializableProperty] - public ProjectSettingRecord[] overrides { get; set; } = []; -} - -/// -/// Describes one dependency-ordered provider of default setting values. -/// -public sealed class ProjectSettingsContributor -{ - private readonly ProjectSettingRecord[] m_settings; - - /// - /// Creates one settings contributor. - /// - /// - /// Stable contributor identity. - /// - /// - /// Contributors that must precede this contributor. - /// - /// - /// Dependencies whose defaults may be explicitly replaced. - /// - /// - /// Default setting contributions. - /// - public ProjectSettingsContributor( - string id, - IEnumerable dependencies, - IEnumerable overrides, - IEnumerable settings - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentNullException.ThrowIfNull(dependencies); - ArgumentNullException.ThrowIfNull(overrides); - ArgumentNullException.ThrowIfNull(settings); - this.id = id; - this.dependencies = Array.AsReadOnly(dependencies.ToArray()); - this.overrides = Array.AsReadOnly(overrides.ToArray()); - m_settings = settings.Select(Clone).ToArray(); - } - - /// - /// Gets the stable contributor identity. - /// - public string id { get; } - - /// - /// Gets contributors that must precede this contributor. - /// - public IReadOnlyList dependencies { get; } - - /// - /// Gets dependencies whose defaults may be replaced. - /// - public IReadOnlyList overrides { get; } - - /// - /// Gets a detached read-only contribution snapshot, including independently owned payload bytes. - /// - public IReadOnlyList settings => Array.AsReadOnly(m_settings.Select(Clone).ToArray()); - - private static ProjectSettingRecord Clone(ProjectSettingRecord record) - => new() - { - id = record.id, - stableTypeId = record.stableTypeId, - propertyData = record.propertyData?.ToArray()! - }; -} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs new file mode 100644 index 000000000..9530bcd8f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; + +namespace Inno.Core.Settings; + +/// +/// Provides one decoded contribution and its immutable composition context. +/// +/// +/// The protocol-owned neutral contribution type. +/// +public sealed class ProjectSettingContribution + where TContribution : class, ISerializable +{ + internal ProjectSettingContribution( + ProjectSettingContributionContext context, + TContribution value + ) { + this.context = context; + this.value = value; + } + + /// + /// Gets the ownership and dependency context for this contribution. + /// + public ProjectSettingContributionContext context { get; } + + /// + /// Gets the decoded protocol-owned contribution value. + /// + public TContribution value { get; } +} + +/// +/// Identifies where one setting contribution originated. +/// +public enum ProjectSettingContributionSource +{ + /// + /// The contribution is a default supplied by an activated Plugin. + /// + Plugin, + /// + /// The contribution is the project-authored delta with highest precedence. + /// + Project +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs new file mode 100644 index 000000000..dda7cc226 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Settings; + +/// +/// Exposes ownership and dependency information while a protocol-owned composer combines one contribution. +/// +public sealed class ProjectSettingContributionContext +{ + private readonly IReadOnlySet m_dependencies; + private readonly IReadOnlySet m_overrides; + + internal ProjectSettingContributionContext( + string contributorID, + ProjectSettingContributionSource source, + IReadOnlySet dependencies, + IReadOnlySet overrides + ) { + this.contributorID = contributorID; + this.source = source; + m_dependencies = dependencies; + m_overrides = overrides; + } + + /// + /// Gets the stable Plugin ID, or project for the project-authored contribution. + /// + public string contributorID { get; } + + /// + /// Gets the contribution source. + /// + public ProjectSettingContributionSource source { get; } + + /// + /// Gets whether this is the project-authored highest-precedence contribution. + /// + public bool isProject => source == ProjectSettingContributionSource.Project; + + /// + /// Gets whether this contribution may explicitly replace data owned by another contributor. + /// + /// + /// The stable owner whose data would be replaced. + /// + /// + /// for project data, or when the Plugin both depends on and explicitly overrides + /// . + /// + public bool CanOverride(string ownerID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(ownerID); + return isProject + || string.Equals(ownerID, "host", StringComparison.Ordinal) + || (m_dependencies.Contains(ownerID) && m_overrides.Contains(ownerID)); + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs new file mode 100644 index 000000000..6964202ff --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Declares a reloadable settings type under one stable protocol identity. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ProjectSettingDefinitionAttribute : Attribute +{ + /// + /// Creates a project setting declaration. + /// + /// + /// Globally stable setting identifier. + /// + /// + /// Whether Plugin packages may contribute values to this protocol. + /// + public ProjectSettingDefinitionAttribute( + string id, + bool allowPluginContributions = true + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.allowPluginContributions = allowPluginContributions; + } + + /// + /// Gets the globally stable setting identifier. + /// + public string id { get; } + + /// + /// Gets whether Plugin packages may contribute values to this protocol. + /// + public bool allowPluginContributions { get; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs new file mode 100644 index 000000000..8c56e988c --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Identifies one host-neutral project setting protocol. +/// +public record struct ProjectSettingID +{ + /// + /// Creates a project setting identifier. + /// + /// + /// Globally stable setting value. + /// + public ProjectSettingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets or sets the globally stable setting value. + /// + public string value { get; set; } + + /// + /// Gets whether the identifier has a usable value. + /// + public readonly bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override readonly string ToString() => value ?? string.Empty; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs new file mode 100644 index 000000000..6acf8a24f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Stores one protocol-owned neutral setting contribution for persistence and composition. +/// +public struct ProjectSettingRecord +{ + /// + /// Creates a setting record. + /// + /// + /// Stable setting identity. + /// + /// + /// Stable settings type identity. + /// + /// + /// Composer-owned contribution bytes, or complete property bytes for replacement settings. + /// + public ProjectSettingRecord( + ProjectSettingID id, + Guid stableTypeID, + ReadOnlySpan propertyData + ) { + if (!id.isValid) + { + throw new ArgumentException("A project setting ID must be valid.", nameof(id)); + } + if (stableTypeID == Guid.Empty) + { + throw new ArgumentException("A project setting requires a stable type ID.", nameof(stableTypeID)); + } + this.id = id; + this.stableTypeId = stableTypeID; + this.propertyData = propertyData.ToArray(); + } + + /// + /// Gets or sets the stable setting identity. + /// + public ProjectSettingID id { get; set; } + + /// + /// Gets or sets the stable settings type identity. + /// + public Guid stableTypeId { get; set; } + + /// + /// Gets or sets the composer-owned payload or default complete-property payload. + /// + public byte[] propertyData { get; set; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs index 47db38115..e0fd6bed0 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; - -using Inno.Extensibility.Types; -using Inno.Core.Serialization; using Inno.Core.Collections; using Inno.Core.IO; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Core.Settings; @@ -16,11 +15,11 @@ namespace Inno.Core.Settings; public sealed class ProjectSettings : IDisposable { private readonly SettingsDocumentStore m_documents; - private readonly ProjectId m_defaultProjectId; + private readonly ProjectID m_defaultProjectID; private readonly SerializationRegistry m_serialization; private readonly SerializationContext m_serializationContext; private readonly ProjectSettingsRegistry m_registry; - private readonly Dictionary m_effective = []; + private readonly Dictionary m_effective = []; private ProjectSettingsDocument m_document; private bool m_disposed; @@ -36,15 +35,15 @@ public sealed class ProjectSettings : IDisposable /// /// The serialization registry used for settings documents and contribution payloads. /// - /// + /// /// The project namespace used when the document has no authored identity override. /// - /// - /// Dependency-ordered default contributors. - /// /// /// The owner's complete reference resolver context, used for defaults, contributions and returned snapshots. /// + /// + /// Dependency-ordered default contributors. + /// /// /// A required service or the owner's serialization context is null. /// @@ -52,25 +51,28 @@ public ProjectSettings( IByteDocumentStore documentStore, TypeCatalog types, SerializationRegistry serialization, - ProjectId defaultProjectId, + ProjectID defaultProjectID, SerializationContext serializationContext, IReadOnlyList? contributors = null ) { ArgumentNullException.ThrowIfNull(documentStore); ArgumentNullException.ThrowIfNull(types); - if (!defaultProjectId.isValid) - throw new ArgumentException("A default Project ID is required.", nameof(defaultProjectId)); + if (!defaultProjectID.isValid) + { + throw new ArgumentException("A default Project ID is required.", nameof(defaultProjectID)); + } ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(serializationContext); m_serialization = serialization; m_serializationContext = serializationContext; - m_defaultProjectId = defaultProjectId; + m_defaultProjectID = defaultProjectID; m_registry = new ProjectSettingsRegistry(types); m_documents = new SettingsDocumentStore( documentStore, serialization, static () => new ProjectSettingsDocument(), - ValidateDocument); + ValidateDocument + ); m_document = m_documents.Load(); Rebuild(contributors ?? [], allowUnresolvedContributions: true); } @@ -93,13 +95,17 @@ public ProjectSettings( /// /// Thrown when the definition does not implement the requested contract. /// - public TSetting Get(ProjectSettingId id) where TSetting : class, ISerializable + public TSetting Get(ProjectSettingID id) + where TSetting : class, ISerializable { ObjectDisposedException.ThrowIf(m_disposed, this); if (!TryClone(id, out ISerializable? value) || value is null) + { throw new KeyNotFoundException($"Project setting '{id}' is not defined."); + } return value as TSetting ?? throw new InvalidCastException( - $"Project setting '{id}' is '{value.GetType().FullName}', not '{typeof(TSetting).FullName}'."); + $"Project setting '{id}' is '{value.GetType().FullName}', not '{typeof(TSetting).FullName}'." + ); } /// @@ -118,10 +124,9 @@ public TSetting Get(ProjectSettingId id) where TSetting : class, ISeri /// when a compatible definition exists. /// public bool TryGet( - ProjectSettingId id, + ProjectSettingID id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable { ObjectDisposedException.ThrowIf(m_disposed, this); if (!TryClone(id, out ISerializable? value)) @@ -139,7 +144,7 @@ out TSetting? setting /// /// Stable setting identifier. /// - /// + /// /// Stable identity of the Plugin being exported. /// /// @@ -162,20 +167,22 @@ out TSetting? setting /// permitted by the declared dependency and override ownership. /// public bool TryCapture( - ProjectSettingId id, - string contributorId, + ProjectSettingID id, + string contributorID, IReadOnlySet declaredDependencies, IReadOnlySet declaredOverrides, IReadOnlyList contributors, out ProjectSettingRecord record ) { ObjectDisposedException.ThrowIf(m_disposed, this); - ArgumentException.ThrowIfNullOrWhiteSpace(contributorId); + ArgumentException.ThrowIfNullOrWhiteSpace(contributorID); ArgumentNullException.ThrowIfNull(declaredDependencies); ArgumentNullException.ThrowIfNull(declaredOverrides); ArgumentNullException.ThrowIfNull(contributors); if (!declaredOverrides.All(declaredDependencies.Contains)) + { throw new ArgumentException("Every explicit override must identify a direct dependency.", nameof(declaredOverrides)); + } ValidateContributorOrder(contributors); ProjectSettingsRegistry.Snapshot registry = m_registry.settings; if (!registry.TryGet(id, out ProjectSettingsRegistry.Definition? definition)) @@ -196,16 +203,18 @@ record = default; } ValidateRecord(id, definition, authored); - if (contributors.Any(contributor => string.Equals(contributor.id, contributorId, StringComparison.Ordinal))) + if (contributors.Any(contributor => string.Equals(contributor.id, contributorID, StringComparison.Ordinal))) { throw new InvalidOperationException( - $"Cannot export Plugin '{contributorId}' while a Plugin with the same ID is active."); + $"Cannot export Plugin '{contributorID}' while a Plugin with the same ID is active." + ); } var prospective = new ProjectSettingsContributor( - contributorId, + contributorID, declaredDependencies, declaredOverrides, - [authored]); + [authored] + ); ProjectSettingsContributor[] validationContributors = [.. contributors, prospective]; _ = ComposeSetting(id, definition, validationContributors, projectRecord: null); @@ -232,7 +241,7 @@ record = default; /// /// when a project contribution record exists. /// - public bool HasProjectOverride(ProjectSettingId id) + public bool HasProjectOverride(ProjectSettingID id) { ObjectDisposedException.ThrowIf(m_disposed, this); return m_document.overrides.Any(candidate => candidate.id == id); @@ -251,14 +260,14 @@ public bool HasProjectOverride(ProjectSettingId id) /// when the setting is defined. /// public bool TryClone( - ProjectSettingId id, + ProjectSettingID id, out ISerializable? setting ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_effective.TryGetValue(id, out ProjectSettingRecord value) || !m_registry.settings.TryGet(id, out ProjectSettingsRegistry.Definition? definition) - || definition.stableTypeId != value.stableTypeId) - { + || definition.stableTypeID != value.stableTypeId + ) { setting = null; return false; } @@ -283,7 +292,7 @@ out ISerializable? setting /// when the setting is defined. /// public bool TryCloneComposedDefault( - ProjectSettingId id, + ProjectSettingID id, IReadOnlyList contributors, out ISerializable? setting ) { @@ -335,47 +344,42 @@ public void Rebuild( if (!registry.TryGet(setting.id, out ProjectSettingsRegistry.Definition? definition)) { if (!allowUnresolvedContributions) + { throw new InvalidOperationException($"Project setting '{setting.id}' has no active definition."); + } continue; } if (!definition.allowPluginContributions) { throw new InvalidOperationException( - $"Project setting '{setting.id}' does not accept Plugin contributions."); + $"Project setting '{setting.id}' does not accept Plugin contributions." + ); } } } - var candidate = new Dictionary(); - foreach ((ProjectSettingId id, ProjectSettingsRegistry.Definition definition) in registry.definitions) + var candidate = new Dictionary(); + foreach ((ProjectSettingID id, ProjectSettingsRegistry.Definition definition) in registry.definitions) { ProjectSettingRecord? projectRecord = FindRecord(m_document.overrides, id); ISerializable value = ComposeSetting(id, definition, contributors, projectRecord); - candidate.Add(id, new ProjectSettingRecord(id, definition.stableTypeId, - m_serialization.CapturePropertiesData(value, m_serializationContext))); + candidate.Add( + id, + new ProjectSettingRecord( + id, + definition.stableTypeID, + m_serialization.CapturePropertiesData(value, m_serializationContext) + ) + ); } m_effective.Clear(); - foreach ((ProjectSettingId id, ProjectSettingRecord value) in candidate) + foreach ((ProjectSettingID id, ProjectSettingRecord value) in candidate) + { m_effective.Add(id, value); + } } - internal ProjectSettingRecord[] CaptureEffective() - => m_effective.Values.Select(static record => new ProjectSettingRecord( - record.id, record.stableTypeId, record.propertyData)).ToArray(); - - internal void RestoreEffective(IEnumerable records) - { - m_effective.Clear(); - foreach (ProjectSettingRecord record in records) - m_effective.Add(record.id, new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)); - } - - internal IReadOnlyList GetUnavailable(IReadOnlyList contributors) - => Array.AsReadOnly(m_document.overrides.Concat(contributors.SelectMany(static item => item.settings)) - .Where(record => !m_registry.settings.TryGet(record.id, out _)) - .Select(static record => new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)).ToArray()); - /// /// Persists one project-authored semantic contribution and rebuilds the effective value. /// @@ -389,15 +393,14 @@ internal IReadOnlyList GetUnavailable(IReadOnlyList public void SetProjectOverride( - ProjectSettingId id, + ProjectSettingID id, ISerializable value, IReadOnlyList contributors - ) { - _ = ApplyProjectOverrides( - new Dictionary { [id] = value }, - resets: null, - contributors); - } + ) => _ = ApplyProjectOverrides( + new Dictionary { [id] = value }, + resets: null, + contributors + ); /// /// Applies multiple project contributions and removals as one atomic document update. @@ -415,8 +418,8 @@ IReadOnlyList contributors /// when the project document changed. /// public bool ApplyProjectOverrides( - IReadOnlyDictionary values, - IReadOnlySet? resets, + IReadOnlyDictionary values, + IReadOnlySet? resets, IReadOnlyList contributors ) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -425,25 +428,27 @@ IReadOnlyList contributors ValidateContributorOrder(contributors); ProjectSettingsRegistry.Snapshot registry = m_registry.settings; - var records = m_document.overrides.ToDictionary(static record => record.id); + Dictionary records = m_document.overrides.ToDictionary(static record => record.id); bool changed = false; if (resets is not null) { - foreach (ProjectSettingId id in resets) + foreach (ProjectSettingID id in resets) + { changed |= records.Remove(id); + } } - foreach ((ProjectSettingId id, ISerializable value) in values) + foreach ((ProjectSettingID id, ISerializable value) in values) { ArgumentNullException.ThrowIfNull(value); if (resets?.Contains(id) == true) + { continue; + } if (!registry.TryGet(id, out ProjectSettingsRegistry.Definition? definition) - || definition.runtimeType != value.GetType()) - { - throw new ArgumentException( - $"Value type does not match project setting '{id}'.", - nameof(values)); + || definition.runtimeType != value.GetType() + ) { + throw new ArgumentException($"Value type does not match project setting '{id}'.", nameof(values)); } ISerializable baseline = ComposeSetting(id, definition, contributors, projectRecord: null); if (!TryCreateRecord(id, definition, baseline, value, out ProjectSettingRecord candidate)) @@ -452,13 +457,17 @@ IReadOnlyList contributors continue; } if (records.TryGetValue(id, out ProjectSettingRecord current) && RecordsEqual(current, candidate)) + { continue; + } records[id] = candidate; changed = true; } if (!changed) + { return false; + } var candidateDocument = new ProjectSettingsDocument { overrides = records.Values @@ -494,50 +503,37 @@ IReadOnlyList contributors public void Dispose() { if (m_disposed) + { return; + } m_effective.Clear(); m_registry.Dispose(); m_disposed = true; } - private static ProjectSettingRecord? FindRecord( - ProjectSettingsContributor contributor, - ProjectSettingId id - ) - => FindRecord(contributor.settings, id); + internal ProjectSettingRecord[] CaptureEffective() + => m_effective.Values.Select(static record => new ProjectSettingRecord( + record.id, + record.stableTypeId, + record.propertyData + )).ToArray(); - private static ProjectSettingRecord? FindRecord( - IEnumerable records, - ProjectSettingId id - ) { - ProjectSettingRecord? result = null; + internal void RestoreEffective(IEnumerable records) + { + m_effective.Clear(); foreach (ProjectSettingRecord record in records) { - if (record.id != id) - continue; - if (result is not null) - throw new InvalidOperationException($"Project setting '{id}' is contributed more than once by one owner."); - result = record; + m_effective.Add(record.id, new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)); } - return result; } - private static IReadOnlySet ExpandContributorClosure( - IReadOnlySet directDependencies, - IReadOnlyList contributors - ) { - var byId = contributors.ToDictionary(static contributor => contributor.id, StringComparer.Ordinal); - var result = new HashSet(StringComparer.Ordinal); - DependencyGraph graph = CreateContributorGraph(contributors); - foreach (string id in directDependencies) - { - if (!byId.ContainsKey(id)) - throw new InvalidOperationException($"Declared Plugin dependency '{id}' is not active."); - result.Add(id); - result.UnionWith(graph.GetDependencies(id, recursive: true)); - } - return result; - } + internal IReadOnlyList GetUnavailable(IReadOnlyList contributors) + => Array.AsReadOnly( + m_document.overrides.Concat(contributors.SelectMany(static item => item.settings)) + .Where(record => !m_registry.settings.TryGet(record.id, out _)) + .Select(static record => new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)) + .ToArray() + ); internal static void ValidateContributorOrder(IReadOnlyList contributors) { @@ -552,104 +548,80 @@ internal static void ValidateContributorOrder(IReadOnlyList contributor.id).SequenceEqual(ordered, StringComparer.Ordinal)) - throw new InvalidOperationException("Project settings contributors are not dependency-ordered."); - } - - private static DependencyGraph CreateContributorGraph(IReadOnlyList contributors) - { - var graph = new DependencyGraph(StringComparer.Ordinal); - var ids = new HashSet(StringComparer.Ordinal); - foreach (ProjectSettingsContributor contributor in contributors) - { - if (!ids.Add(contributor.id)) - throw new InvalidOperationException($"Settings contributor '{contributor.id}' is declared more than once."); - graph.AddNode(contributor.id); - } - foreach (ProjectSettingsContributor contributor in contributors) { - foreach (string dependency in contributor.dependencies) - { - if (!ids.Contains(dependency)) - { - throw new InvalidOperationException( - $"Settings contributor '{contributor.id}' requires inactive dependency '{dependency}'."); - } - graph.AddDependency(contributor.id, dependency); - } + throw new InvalidOperationException("Project settings contributors are not dependency-ordered."); } - return graph; - } - - private static bool RecordsEqual( - ProjectSettingRecord left, - ProjectSettingRecord right - ) - => left.id == right.id - && left.stableTypeId == right.stableTypeId - && (left.propertyData ?? []).AsSpan().SequenceEqual(right.propertyData ?? []); - - private static void ValidateRecord( - ProjectSettingId id, - ProjectSettingsRegistry.Definition definition, - ProjectSettingRecord record - ) { - if (record.stableTypeId != definition.stableTypeId) - throw new InvalidOperationException($"Project setting '{id}' has an incompatible stable type."); - if (record.propertyData is null || record.propertyData.Length == 0) - throw new InvalidOperationException($"Project setting '{id}' contains an empty contribution payload."); } private ISerializable ComposeSetting( - ProjectSettingId id, + ProjectSettingID id, ProjectSettingsRegistry.Definition definition, IReadOnlyList contributors, ProjectSettingRecord? projectRecord ) { if (definition.composer is null) + { return ComposeReplacement(id, definition, contributors, projectRecord); + } - var entries = new List(); + List entries = []; foreach (ProjectSettingsContributor contributor in contributors) { ProjectSettingRecord? record = FindRecord(contributor, id); if (record is not ProjectSettingRecord contribution) + { continue; + } ValidateRecord(id, definition, contribution); - entries.Add(new ProjectSettingCompositionEntry( - new ProjectSettingContributionContext( - contributor.id, - ProjectSettingContributionSource.Plugin, - contributor.dependencies.ToHashSet(StringComparer.Ordinal), - contributor.overrides.ToHashSet(StringComparer.Ordinal)), - contribution.propertyData)); + entries.Add( + new ProjectSettingCompositionEntry( + new ProjectSettingContributionContext( + contributor.id, + ProjectSettingContributionSource.Plugin, + contributor.dependencies.ToHashSet(StringComparer.Ordinal), + contributor.overrides.ToHashSet(StringComparer.Ordinal) + ), + contribution.propertyData + ) + ); } if (projectRecord is ProjectSettingRecord project) { ValidateRecord(id, definition, project); - entries.Add(new ProjectSettingCompositionEntry( - new ProjectSettingContributionContext( - "project", - ProjectSettingContributionSource.Project, - new HashSet(StringComparer.Ordinal), - new HashSet(StringComparer.Ordinal)), - project.propertyData)); - } - return definition.composer.Compose(m_serialization, m_serializationContext, - CreateHostDefault(id, definition), entries); + entries.Add( + new ProjectSettingCompositionEntry( + new ProjectSettingContributionContext( + "project", + ProjectSettingContributionSource.Project, + new HashSet(StringComparer.Ordinal), + new HashSet(StringComparer.Ordinal) + ), + project.propertyData + ) + ); + } + return definition.composer.Compose( + m_serialization, + m_serializationContext, + CreateHostDefault(id, definition), + entries + ); } private ISerializable CreateHostDefault( - ProjectSettingId id, + ProjectSettingID id, ProjectSettingsRegistry.Definition definition ) { ISerializable value = definition.Create(); - if (id == ProjectIdentitySettings.settingId && value is ProjectIdentitySettings identity) - identity.projectId = m_defaultProjectId.value; + if (id == ProjectIdentitySettings.settingID && value is ProjectIdentitySettings identity) + { + identity.projectId = m_defaultProjectID.value; + } return value; } private ISerializable ComposeReplacement( - ProjectSettingId id, + ProjectSettingID id, ProjectSettingsRegistry.Definition definition, IReadOnlyList contributors, ProjectSettingRecord? projectRecord @@ -660,14 +632,17 @@ private ISerializable ComposeReplacement( { ProjectSettingRecord? record = FindRecord(contributor, id); if (record is not ProjectSettingRecord contribution) + { continue; + } ValidateRecord(id, definition, contribution); if (owner != "host" && (!contributor.dependencies.Contains(owner, StringComparer.Ordinal) - || !contributor.overrides.Contains(owner, StringComparer.Ordinal))) - { + || !contributor.overrides.Contains(owner, StringComparer.Ordinal)) + ) { throw new InvalidOperationException( - $"Settings contributors '{owner}' and '{contributor.id}' conflict on '{id}'."); + $"Settings contributors '{owner}' and '{contributor.id}' conflict on '{id}'." + ); } owner = contributor.id; selected = contribution; @@ -680,19 +655,23 @@ private ISerializable ComposeReplacement( ISerializable result = CreateHostDefault(id, definition); if (selected is ProjectSettingRecord value) + { _ = m_serialization.RestorePropertiesData(result, value.propertyData, context: m_serializationContext); + } return result; } private bool TryCreateRecord( - ProjectSettingId id, + ProjectSettingID id, ProjectSettingsRegistry.Definition definition, ISerializable baseline, ISerializable value, out ProjectSettingRecord record ) { if (definition.runtimeType != baseline.GetType() || definition.runtimeType != value.GetType()) + { throw new ArgumentException($"Value type does not match project setting '{id}'.", nameof(value)); + } byte[] payload; if (definition.composer is null) @@ -710,17 +689,10 @@ record = default; record = default; return false; } - record = new ProjectSettingRecord(id, definition.stableTypeId, payload); + record = new ProjectSettingRecord(id, definition.stableTypeID, payload); return true; } - private static void ValidateDocument(ProjectSettingsDocument document) - { - ArgumentNullException.ThrowIfNull(document); - if (document.overrides is null) - throw new InvalidDataException("A project Settings document requires an override collection."); - } - private void ReplaceDocument( ProjectSettingsDocument candidate, IReadOnlyList contributors @@ -742,4 +714,110 @@ IReadOnlyList contributors throw; } } + + private static ProjectSettingRecord? FindRecord( + ProjectSettingsContributor contributor, + ProjectSettingID id + ) => FindRecord(contributor.settings, id); + + private static ProjectSettingRecord? FindRecord( + IEnumerable records, + ProjectSettingID id + ) { + ProjectSettingRecord? result = null; + foreach (ProjectSettingRecord record in records) + { + if (record.id != id) + { + continue; + } + if (result is not null) + { + throw new InvalidOperationException($"Project setting '{id}' is contributed more than once by one owner."); + } + result = record; + } + return result; + } + + private static IReadOnlySet ExpandContributorClosure( + IReadOnlySet directDependencies, + IReadOnlyList contributors + ) { + Dictionary byID = contributors.ToDictionary( + static contributor => contributor.id, + StringComparer.Ordinal + ); + var result = new HashSet(StringComparer.Ordinal); + DependencyGraph graph = CreateContributorGraph(contributors); + foreach (string id in directDependencies) + { + if (!byID.ContainsKey(id)) + { + throw new InvalidOperationException($"Declared Plugin dependency '{id}' is not active."); + } + result.Add(id); + result.UnionWith(graph.GetDependencies(id, recursive: true)); + } + return result; + } + + private static DependencyGraph CreateContributorGraph(IReadOnlyList contributors) + { + var graph = new DependencyGraph(StringComparer.Ordinal); + var ids = new HashSet(StringComparer.Ordinal); + foreach (ProjectSettingsContributor contributor in contributors) + { + if (!ids.Add(contributor.id)) + { + throw new InvalidOperationException($"Settings contributor '{contributor.id}' is declared more than once."); + } + graph.AddNode(contributor.id); + } + foreach (ProjectSettingsContributor contributor in contributors) + { + foreach (string dependency in contributor.dependencies) + { + if (!ids.Contains(dependency)) + { + throw new InvalidOperationException( + $"Settings contributor '{contributor.id}' requires inactive dependency '{dependency}'." + ); + } + graph.AddDependency(contributor.id, dependency); + } + } + return graph; + } + + private static bool RecordsEqual( + ProjectSettingRecord left, + ProjectSettingRecord right + ) => left.id == right.id + && left.stableTypeId == right.stableTypeId + && (left.propertyData ?? []).AsSpan().SequenceEqual(right.propertyData ?? []); + + private static void ValidateRecord( + ProjectSettingID id, + ProjectSettingsRegistry.Definition definition, + ProjectSettingRecord record + ) { + if (record.stableTypeId != definition.stableTypeID) + { + throw new InvalidOperationException($"Project setting '{id}' has an incompatible stable type."); + } + if (record.propertyData is null || record.propertyData.Length == 0) + { + throw new InvalidOperationException($"Project setting '{id}' contains an empty contribution payload."); + } + } + + private static void ValidateDocument(ProjectSettingsDocument document) + { + ArgumentNullException.ThrowIfNull(document); + if (document.overrides is null) + { + throw new InvalidDataException("A project Settings document requires an override collection."); + } + } } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs new file mode 100644 index 000000000..aec17433a --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Core.Settings; + +/// +/// Describes one dependency-ordered provider of default setting values. +/// +public sealed class ProjectSettingsContributor +{ + private readonly ProjectSettingRecord[] m_settings; + + /// + /// Creates one settings contributor. + /// + /// + /// Stable contributor identity. + /// + /// + /// Contributors that must precede this contributor. + /// + /// + /// Dependencies whose defaults may be explicitly replaced. + /// + /// + /// Default setting contributions. + /// + public ProjectSettingsContributor( + string id, + IEnumerable dependencies, + IEnumerable overrides, + IEnumerable settings + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(dependencies); + ArgumentNullException.ThrowIfNull(overrides); + ArgumentNullException.ThrowIfNull(settings); + this.id = id; + this.dependencies = Array.AsReadOnly(dependencies.ToArray()); + this.overrides = Array.AsReadOnly(overrides.ToArray()); + m_settings = settings.Select(Clone).ToArray(); + } + + /// + /// Gets the stable contributor identity. + /// + public string id { get; } + + /// + /// Gets contributors that must precede this contributor. + /// + public IReadOnlyList dependencies { get; } + + /// + /// Gets dependencies whose defaults may be replaced. + /// + public IReadOnlyList overrides { get; } + + /// + /// Gets a detached read-only contribution snapshot, including independently owned payload bytes. + /// + public IReadOnlyList settings => Array.AsReadOnly(m_settings.Select(Clone).ToArray()); + + private static ProjectSettingRecord Clone(ProjectSettingRecord record) + => new() + { + id = record.id, + stableTypeId = record.stableTypeId, + propertyData = record.propertyData?.ToArray()! + }; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs new file mode 100644 index 000000000..5dd117b25 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Core.Settings; + +/// +/// Stores project-authored setting contributions in one native document. +/// +public sealed class ProjectSettingsDocument : ISerializable +{ + /// + /// Gets or sets project-authored protocol contributions. + /// + [SerializableProperty] + public ProjectSettingRecord[] overrides { get; set; } = []; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs index ab4bbec39..6432974c2 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Settings; @@ -13,7 +13,7 @@ namespace Inno.Core.Settings; /// public static class ProjectSettingsExecutionContext { - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("settings"); + private static readonly ExecutionSlot CURRENT_SCOPE = new("settings"); /// /// Gets the settings lookup bound to the current asynchronous execution context. @@ -21,7 +21,7 @@ public static class ProjectSettingsExecutionContext /// /// Thrown when no settings lookup is active for the caller. /// - public static IProjectSettingsLookup current => S_CURRENT_SCOPE.current; + public static IProjectSettingsLookup current => CURRENT_SCOPE.current; /// /// Binds a settings lookup until the returned strict last-in-first-out scope is disposed. @@ -38,7 +38,6 @@ public static class ProjectSettingsExecutionContext public static IDisposable EnterScope(IProjectSettingsLookup settings) { ArgumentNullException.ThrowIfNull(settings); - return S_CURRENT_SCOPE.Enter(settings); + return CURRENT_SCOPE.Enter(settings); } - } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs index d4b6c6370..2b0d9a582 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs @@ -1,18 +1,16 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Core.Settings; internal sealed class ProjectSettingsRegistry : TypeRegistry { internal ProjectSettingsRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot settings => current; @@ -27,70 +25,89 @@ internal ProjectSettingsRegistry(TypeCatalog types) /// protected override Snapshot Build(TypeCacheSnapshot types) { - var settingTypes = new Dictionary(); + var settingTypes = new Dictionary(); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) { Type type = typeRef.Resolve(types); if (type.IsAbstract || !typeof(ISerializable).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Project setting type '{type.FullName}' must be a non-abstract ISerializable class."); + $"Project setting type '{type.FullName}' must be a non-abstract ISerializable class." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Project setting type '{type.FullName}' requires a factory in the current type catalog."); + $"Project setting type '{type.FullName}' requires a factory in the current type catalog." + ); } if (!types.TryGetTypeRef(type, out TypeRef stableType)) - throw new InvalidOperationException($"Project setting type '{type.FullName}' requires StableTypeId."); - ProjectSettingDefinitionAttribute attribute = - types.GetAttribute(typeRef, inherit: false)!; - var id = new ProjectSettingId(attribute.id); - if (!settingTypes.TryAdd(id, (stableType.stableId, type, attribute.allowPluginContributions))) + { + throw new InvalidOperationException($"Project setting type '{type.FullName}' requires StableTypeID."); + } + ProjectSettingDefinitionAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; + var id = new ProjectSettingID(attribute.id); + if (!settingTypes.TryAdd(id, (stableType.stableID, type, attribute.allowPluginContributions))) + { throw new InvalidOperationException($"Project setting ID '{id}' is declared more than once."); + } } - var composers = new Dictionary(); + var composers = new Dictionary(); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) { Type type = typeRef.Resolve(types); if (type.IsAbstract || !typeof(ProjectSettingComposer).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' must be a non-abstract ProjectSettingComposer."); + $"Project setting composer '{type.FullName}' must be a non-abstract ProjectSettingComposer." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' requires a factory in the current type catalog."); + $"Project setting composer '{type.FullName}' requires a factory in the current type catalog." + ); } - ProjectSettingComposerAttribute attribute = - types.GetAttribute(typeRef, inherit: false)!; - if (!settingTypes.TryGetValue(attribute.settingId, out var setting)) - { + ProjectSettingComposerAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; + if (!settingTypes.TryGetValue( + attribute.settingID, + out (Guid stableTypeID, Type runtimeType, bool allowPluginContributions) setting + )) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' targets undefined setting '{attribute.settingId}'."); + $"Project setting composer '{type.FullName}' targets undefined setting '{attribute.settingID}'." + ); } - var composer = OwnCandidateExtension((ProjectSettingComposer)types.CreateInstance(type)); + ProjectSettingComposer composer = OwnCandidateExtension((ProjectSettingComposer)types.CreateInstance(type)); if (composer.settingType != setting.runtimeType) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' expects '{composer.settingType.FullName}', " + - $"but '{attribute.settingId}' is '{setting.runtimeType.FullName}'."); + $"Project setting composer '{type.FullName}' expects '{composer.settingType.FullName}', " + + $"but '{attribute.settingID}' is '{setting.runtimeType.FullName}'." + ); } - if (!composers.TryAdd(attribute.settingId, composer)) + if (!composers.TryAdd(attribute.settingID, composer)) { throw new InvalidOperationException( - $"Project setting '{attribute.settingId}' declares more than one composer."); + $"Project setting '{attribute.settingID}' declares more than one composer." + ); } } - var definitions = new Dictionary(); - foreach ((ProjectSettingId id, (Guid stableTypeId, Type runtimeType, bool allowPluginContributions)) in settingTypes) + var definitions = new Dictionary(); + foreach ((ProjectSettingID id, (Guid stableTypeID, Type runtimeType, bool allowPluginContributions)) in settingTypes) { composers.TryGetValue(id, out ProjectSettingComposer? composer); - definitions.Add(id, new Definition(stableTypeId, runtimeType, composer, allowPluginContributions, - () => (ISerializable)types.CreateInstance(runtimeType))); + definitions.Add( + id, + new Definition( + stableTypeID, + runtimeType, + composer, + allowPluginContributions, + () => (ISerializable)types.CreateInstance(runtimeType) + ) + ); } return new Snapshot(types.version, definitions.ToFrozenDictionary()); } @@ -106,11 +123,11 @@ protected override void DisposeSnapshot(Snapshot snapshot) internal sealed class Snapshot { - private readonly FrozenDictionary m_definitions; + private readonly FrozenDictionary m_definitions; internal Snapshot( long typeCacheVersion, - FrozenDictionary definitions + FrozenDictionary definitions ) { this.typeCacheVersion = typeCacheVersion; m_definitions = definitions; @@ -118,16 +135,16 @@ FrozenDictionary definitions internal long typeCacheVersion { get; } - internal IEnumerable> definitions => m_definitions; + internal IEnumerable> definitions => m_definitions; internal bool TryGet( - ProjectSettingId id, + ProjectSettingID id, out Definition definition ) => m_definitions.TryGetValue(id, out definition!); } internal sealed record Definition( - Guid stableTypeId, + Guid stableTypeID, Type runtimeType, ProjectSettingComposer? composer, bool allowPluginContributions, diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs index 6d9cdbfe8..b05e69a40 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; -using Inno.Extensibility.Reload; +using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Scripting.Api; -using Inno.Core.IO; namespace Inno.Core.Settings; @@ -19,10 +19,6 @@ public sealed class ProjectSettingsStore : IDisposable, IProjectSettingsLookup private IReadOnlyList m_contributors = []; private ProjectSettings? m_current; private long m_revision; - /// - /// Gets the unique, non-persistent lifetime identity used with the effective snapshot revision. - /// - public Guid ownerId { get; } = Guid.NewGuid(); /// /// Creates a project settings store from one type and serialization generation owner. @@ -36,7 +32,7 @@ public sealed class ProjectSettingsStore : IDisposable, IProjectSettingsLookup /// /// The serialization registry used for documents and contribution payloads. /// - /// + /// /// The project namespace used until an authored identity override is saved. /// /// @@ -49,7 +45,7 @@ public ProjectSettingsStore( IByteDocumentStore documentStore, TypeCatalog types, SerializationRegistry serialization, - ProjectId defaultProjectId, + ProjectID defaultProjectID, SerializationContext serializationContext ) { ArgumentNullException.ThrowIfNull(documentStore); @@ -57,10 +53,15 @@ SerializationContext serializationContext ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(serializationContext); m_serialization = serialization; - m_current = new ProjectSettings(documentStore, types, serialization, defaultProjectId, serializationContext); + m_current = new ProjectSettings(documentStore, types, serialization, defaultProjectID, serializationContext); m_revision = 1; } + /// + /// Gets the unique, non-persistent lifetime identity used with the effective snapshot revision. + /// + public Guid ownerID { get; } = Guid.NewGuid(); + /// /// Gets detached neutral contributions whose setting definitions are currently Missing. /// @@ -70,35 +71,16 @@ public IReadOnlyList unavailableSettings get { lock (m_sync) + { return RequireCurrent().GetUnavailable(m_contributors); + } } } - /// - /// Creates a five-phase settings change for the host's shared generation transaction. - /// - /// - /// An owner-thread change that captures neutral effective values before publication, rebuilds against candidate - /// types, and restores exact previous values and contributors without writing the project document on rollback. - /// - [ScriptingApiIgnore] - public IGenerationChange CreateReloadChange() => new SettingsChange(this); - /// /// Gets the current project namespace. /// - public ProjectId projectId => Get(ProjectIdentitySettings.settingId).id; - - /// - /// Qualifies one local name under the current project namespace. - /// - /// - /// The local display name. - /// - /// - /// The canonical projectId.name identity. - /// - public ProjectScopedId QualifyId(string name) => projectId.Qualify(ProjectLocalId.FromName(name)); + public ProjectID projectID => Get(ProjectIdentitySettings.settingID).id; /// /// Gets whether project settings are initialized. @@ -108,7 +90,9 @@ public bool isInitialized get { lock (m_sync) + { return m_current is not null; + } } } @@ -125,10 +109,33 @@ public long revision get { lock (m_sync) + { return m_revision; + } } } + /// + /// Creates a five-phase settings change for the host's shared generation transaction. + /// + /// + /// An owner-thread change that captures neutral effective values before publication, rebuilds against candidate + /// types, and restores exact previous values and contributors without writing the project document on rollback. + /// + [ScriptingApiIgnore] + public IGenerationChange CreateReloadChange() => new SettingsChange(this); + + /// + /// Qualifies one local name under the current project namespace. + /// + /// + /// The local display name. + /// + /// + /// The canonical projectId.name identity. + /// + public ProjectScopedID QualifyID(string name) => projectID.Qualify(ProjectLocalID.FromName(name)); + /// /// Binds this settings store to the current asynchronous script execution context. /// @@ -159,11 +166,13 @@ public IDisposable EnterExecutionScope() /// /// An independently owned effective setting snapshot. /// - public TSetting Get(ProjectSettingId id) + public TSetting Get(ProjectSettingID id) where TSetting : class, ISerializable { lock (m_sync) + { return RequireCurrent().Get(id); + } } /// @@ -182,10 +191,9 @@ public TSetting Get(ProjectSettingId id) /// when a compatible setting exists. /// public bool TryGet( - ProjectSettingId id, + ProjectSettingID id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable { lock (m_sync) { @@ -208,10 +216,12 @@ out TSetting? setting /// when the project owns an override record. /// [ScriptingApiIgnore] - public bool HasProjectOverride(ProjectSettingId id) + public bool HasProjectOverride(ProjectSettingID id) { lock (m_sync) + { return RequireCurrent().HasProjectOverride(id); + } } /// @@ -220,7 +230,7 @@ public bool HasProjectOverride(ProjectSettingId id) /// /// Stable setting protocol identity. /// - /// + /// /// Stable identity of the Plugin being exported. /// /// @@ -237,24 +247,25 @@ public bool HasProjectOverride(ProjectSettingId id) /// [ScriptingApiIgnore] public bool TryCapture( - ProjectSettingId id, - string contributorId, + ProjectSettingID id, + string contributorID, IReadOnlySet declaredDependencies, IReadOnlySet declaredOverrides, out ProjectSettingRecord record ) { - ArgumentException.ThrowIfNullOrWhiteSpace(contributorId); + ArgumentException.ThrowIfNullOrWhiteSpace(contributorID); ArgumentNullException.ThrowIfNull(declaredDependencies); ArgumentNullException.ThrowIfNull(declaredOverrides); lock (m_sync) { return RequireCurrent().TryCapture( id, - contributorId, + contributorID, declaredDependencies, declaredOverrides, m_contributors, - out record); + out record + ); } } @@ -272,7 +283,7 @@ out ProjectSettingRecord record /// [ScriptingApiIgnore] public bool TryClone( - ProjectSettingId id, + ProjectSettingID id, out ISerializable? setting ) { lock (m_sync) @@ -300,7 +311,7 @@ out ISerializable? setting /// [ScriptingApiIgnore] public bool TryCloneComposedDefault( - ProjectSettingId id, + ProjectSettingID id, out ISerializable? setting ) { lock (m_sync) @@ -324,7 +335,9 @@ out ISerializable? setting public byte[] CaptureDocument() { lock (m_sync) + { return RequireCurrent().CaptureDocument(); + } } /// @@ -395,7 +408,7 @@ public void RebuildCurrent(bool allowUnresolvedContributions = false) /// [ScriptingApiIgnore] public void SetProjectOverride( - ProjectSettingId id, + ProjectSettingID id, ISerializable value, IReadOnlyList contributors ) { @@ -422,15 +435,17 @@ IReadOnlyList contributors /// [ScriptingApiIgnore] public bool ApplyProjectOverrides( - IReadOnlyDictionary values, - IReadOnlySet? resets = null + IReadOnlyDictionary values, + IReadOnlySet? resets = null ) { ArgumentNullException.ThrowIfNull(values); lock (m_sync) { bool changed = RequireCurrent().ApplyProjectOverrides(values, resets, m_contributors); if (changed) + { m_revision++; + } return changed; } } @@ -478,6 +493,7 @@ public void Dispose() private ProjectSettings RequireCurrent() => m_current ?? throw new InvalidOperationException("ProjectSettingsStore is not initialized."); + private sealed class SettingsChange(ProjectSettingsStore owner) : IGenerationChange { private ProjectSettingRecord[]? m_previous; @@ -492,7 +508,9 @@ public void PrepareForActivation() lock (owner.m_sync) { if (m_previous is not null) + { throw new InvalidOperationException("Settings change was already prepared."); + } m_previous = owner.RequireCurrent().CaptureEffective(); m_contributors = owner.m_contributors.ToArray(); m_revision = owner.m_revision; @@ -505,7 +523,9 @@ public void PrepareForActivation() public void Apply() { if (m_previous is null) + { throw new InvalidOperationException("Settings change was not prepared."); + } owner.RebuildCurrent(allowUnresolvedContributions: true); } @@ -521,7 +541,7 @@ public void Complete() /// /// Restores the state that existed before candidate activation began. /// - public void RollbackStructure() { } + public void RollbackStructure() {} /// /// Restores the state that existed before candidate activation began. @@ -529,7 +549,9 @@ public void RollbackStructure() { } public void RestorePreviousState() { if (m_previous is null) + { return; + } lock (owner.m_sync) { owner.RequireCurrent().RestoreEffective(m_previous); diff --git a/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs index e54f13a3a..c756b7598 100644 --- a/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs @@ -1,15 +1,12 @@ -using Inno.Scripting.Api; using Inno.Core.Settings; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Settings", - "Inno.Core.Settings", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Settings", "Inno.Core.Settings", ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ProjectSettingId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ProjectId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ProjectLocalId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ProjectScopedId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ProjectSettingID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ProjectID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ProjectLocalID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ProjectScopedID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ProjectIdentitySettings), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ProjectSettingDefinitionAttribute), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ProjectSettingComposerAttribute), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Settings/Settings.cs b/src/foundation/core/Inno.Core.Settings/Settings.cs index 34989670a..62fa474b7 100644 --- a/src/foundation/core/Inno.Core.Settings/Settings.cs +++ b/src/foundation/core/Inno.Core.Settings/Settings.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; namespace Inno.Core.Settings; @@ -16,18 +15,7 @@ public static class Settings /// /// Gets the current project namespace used to qualify project-authored logical names. /// - public static ProjectId projectId => Get(ProjectIdentitySettings.settingId).id; - - /// - /// Creates one complete project identity from a display or local name. - /// - /// - /// The project-local name. - /// - /// - /// The canonical projectId.name identity. - /// - public static ProjectScopedId QualifyId(string name) => projectId.Qualify(ProjectLocalId.FromName(name)); + public static ProjectID projectID => Get(ProjectIdentitySettings.settingID).id; /// /// Gets the revision of the settings snapshot active in the current execution context. @@ -40,7 +28,18 @@ public static class Settings /// /// Gets the current owner's lifetime identity. Pair it with revision when caching an isolated settings snapshot. /// - public static Guid ownerId => ProjectSettingsExecutionContext.current.ownerId; + public static Guid ownerID => ProjectSettingsExecutionContext.current.ownerID; + + /// + /// Creates one complete project identity from a display or local name. + /// + /// + /// The project-local name. + /// + /// + /// The canonical projectId.name identity. + /// + public static ProjectScopedID QualifyID(string name) => projectID.Qualify(ProjectLocalID.FromName(name)); /// /// Gets an isolated effective setting from the current extension generation. @@ -63,9 +62,9 @@ public static class Settings /// /// Thrown by the standard project settings store when the setting does not implement the requested contract. /// - public static TSetting Get(ProjectSettingId id) + public static TSetting Get(ProjectSettingID id) where TSetting : class, ISerializable - => ProjectSettingsExecutionContext.current.Get(id); + => ProjectSettingsExecutionContext.current.Get(id); /// /// Tries to get an isolated effective setting from the current extension generation. @@ -87,9 +86,8 @@ public static TSetting Get(ProjectSettingId id) /// Thrown when no project settings lookup is active for the caller. /// public static bool TryGet( - ProjectSettingId id, + ProjectSettingID id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable => ProjectSettingsExecutionContext.current.TryGet(id, out setting); } diff --git a/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs b/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs index 694c8c185..b81c7e545 100644 --- a/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs +++ b/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -47,7 +46,7 @@ public SettingsDocumentStore( m_document = document; m_serialization = serialization; m_createDefault = createDefault; - m_validate = validate ?? (static _ => { }); + m_validate = validate ?? (static _ => {}); } /// @@ -87,7 +86,8 @@ public TDocument Load() public TDocument LoadRequired() { byte[] data = m_document.Read() ?? throw new InvalidDataException( - $"Required settings document '{documentName}' does not exist."); + $"Required settings document '{documentName}' does not exist." + ); return Deserialize(data); } @@ -138,13 +138,14 @@ public TDocument Deserialize(ReadOnlySpan data) return document; } catch (Exception exception) when (exception is ArgumentException - or InvalidDataException - or InvalidOperationException - or NotSupportedException) + or InvalidDataException + or InvalidOperationException + or NotSupportedException) { throw new InvalidDataException( $"Settings document '{documentName}' is not a valid current-format {typeof(TDocument).Name}.", - exception); + exception + ); } } diff --git a/src/foundation/core/Inno.Core.Settings/SettingsFileNames.cs b/src/foundation/core/Inno.Core.Settings/SettingsFileNames.cs index ac694751d..a1f868931 100644 --- a/src/foundation/core/Inno.Core.Settings/SettingsFileNames.cs +++ b/src/foundation/core/Inno.Core.Settings/SettingsFileNames.cs @@ -8,15 +8,15 @@ public static class SettingsFileNames /// /// Gets the machine/editor preference document name. /// - public const string editor = "Settings.Editor.inno"; + public const string C_EDITOR = "Settings.Editor.inno"; /// /// Gets the runtime project settings document name. /// - public const string project = "Settings.Project.inno"; + public const string C_PROJECT = "Settings.Project.inno"; /// /// Gets the authoring build-default document name. /// - public const string build = "Settings.Build.inno"; + public const string C_BUILD = "Settings.Build.inno"; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs b/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs index d34311ac0..2518e0f8a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs @@ -44,12 +44,12 @@ void Register( /// /// The type is not a fully closed generic construction. /// - /// - /// Repeated registrations of the same closed construction are idempotent; the first factory is retained. - /// /// /// The caller runs on another thread or retained this registrar after catalog composition completed. /// + /// + /// Repeated registrations of the same closed construction are idempotent; the first factory is retained. + /// void RegisterFactory( Type type, Func factory @@ -64,10 +64,6 @@ Func factory /// /// The complete closed argument set. The registrar copies this collection during registration. /// - /// - /// This fact lets static resolution skip an inapplicable converter without attempting dynamic generic creation. - /// Unknown constructions remain explicit deployment errors. Repeated rejections are idempotent. - /// /// /// The declaration or argument set is incomplete, open, or conflicts with a registered factory. /// @@ -77,6 +73,10 @@ Func factory /// /// The caller runs on another thread or retained this registrar after catalog composition completed. /// + /// + /// This fact lets static resolution skip an inapplicable converter without attempting dynamic generic creation. + /// Unknown constructions remain explicit deployment errors. Repeated rejections are idempotent. + /// void RejectGenericConstruction( Type definition, IReadOnlyList arguments diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs index 53a298bed..d97cb10c4 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; namespace Inno.Extensibility.Modules; @@ -18,9 +17,9 @@ internal CatalogParticipantRegistration Register(IAssemblyCatalogParticipant par { RemoveCollectedParticipants(); var registration = new CatalogParticipantRegistration(this, Guid.NewGuid()); - m_participants.Add(new ParticipantReference( - registration.id, - new WeakReference(participant))); + m_participants.Add( + new ParticipantReference(registration.id, new WeakReference(participant)) + ); return registration; } } @@ -39,7 +38,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) foreach (ParticipantReference registration in m_participants) { if (registration.participant.TryGetTarget(out IAssemblyCatalogParticipant? participant)) + { participants.Add(participant); + } } } @@ -47,7 +48,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) try { foreach (IAssemblyCatalogParticipant participant in participants) + { transactions.Add(participant.Prepare(catalog)); + } return new AssemblyCatalogRefreshSet(transactions); } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -67,7 +70,10 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { - m_retirementFailure = new AggregateException("Catalog preparation failed and rollback remains pending.", [.. failures, failure]); + m_retirementFailure = new AggregateException( + "Catalog preparation failed and rollback remains pending.", + [.. failures, failure] + ); m_retainedPreparation = (participants, transactions); throw m_retirementFailure; } @@ -77,15 +83,19 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) } } if (failures.Count > 1) + { throw new AggregateException("Assembly catalog preparation and rollback failed.", failures); + } throw; } } - internal void Unregister(Guid registrationId) + internal void Unregister(Guid registrationID) { lock (m_sync) - m_participants.RemoveAll(registration => registration.id == registrationId); + { + m_participants.RemoveAll(registration => registration.id == registrationID); + } } private void RemoveCollectedParticipants() @@ -96,130 +106,3 @@ private readonly record struct ParticipantReference( WeakReference participant ); } - -internal sealed class CatalogParticipantRegistration( - AssemblyCatalogCoordinator owner, - Guid id -) : IDisposable -{ - private bool m_disposed; - - internal Guid id { get; } = id; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - owner.Unregister(id); - } -} - -internal sealed class AssemblyCatalogRefreshSet(IReadOnlyList transactions) -{ - private int m_activatedCount; - private bool m_finished; - private Exception? m_failure; - - internal IReadOnlyList contexts - { - get - { - var result = new List(transactions.Count); - foreach (IAssemblyCatalogTransaction transaction in transactions) - { - if (transaction.context is not null) - result.Add(transaction.context); - } - return result; - } - } - - internal void Activate() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - throw new InvalidOperationException("Assembly catalog refresh set is already finished."); - try - { - for (; m_activatedCount < transactions.Count; m_activatedCount++) - transactions[m_activatedCount].Activate(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failure; - throw; - } - catch (Exception activationFailure) - { - try - { - Rollback(); - } - catch (Exception rollbackFailure) - { - var combined = new AggregateException("Assembly catalog activation and rollback failed.", activationFailure, rollbackFailure); - if (RetirementPendingException.Find(combined) is not null) - m_failure = combined; - throw combined; - } - throw; - } - } - - internal void Complete() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - return; - List failures = []; - for (int i = 0; i < transactions.Count; i++) - TryCleanup(transactions[i].Complete, failures); - m_finished = true; - transactions = Array.Empty(); - if (failures.Count > 0) - throw new AggregateException("Assembly catalog completion failed after all participants were attempted.", failures); - } - - internal void Rollback() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - return; - List failures = []; - for (int i = transactions.Count - 1; i >= 0; i--) - TryCleanup(transactions[i].Rollback, failures); - m_finished = true; - transactions = Array.Empty(); - if (failures.Count > 0) - throw new AggregateException("Assembly catalog rollback failed after all participants were attempted.", failures); - } - - private void TryCleanup( - Action cleanup, - List failures - ) { - try - { - cleanup(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failures.Count == 0 ? failure : new AggregateException( - "Catalog cleanup remains pending after earlier failures.", [.. failures, failure]); - if (ReferenceEquals(m_failure, failure)) - throw; - throw m_failure; - } - catch (Exception exception) - { - failures.Add(exception); - } - } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs new file mode 100644 index 000000000..87d8f902c --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Execution; + +namespace Inno.Extensibility.Modules; + +internal sealed class AssemblyCatalogRefreshSet(IReadOnlyList transactions) +{ + private int m_activatedCount; + private bool m_finished; + private Exception? m_failure; + + internal IReadOnlyList contexts + { + get + { + var result = new List(transactions.Count); + foreach (IAssemblyCatalogTransaction transaction in transactions) + { + if (transaction.context is not null) + { + result.Add(transaction.context); + } + } + return result; + } + } + + internal void Activate() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + throw new InvalidOperationException("Assembly catalog refresh set is already finished."); + } + try + { + for (; m_activatedCount < transactions.Count; m_activatedCount++) + { + transactions[m_activatedCount].Activate(); + } + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failure; + throw; + } + catch (Exception activationFailure) + { + try + { + Rollback(); + } + catch (Exception rollbackFailure) + { + var combined = new AggregateException( + "Assembly catalog activation and rollback failed.", + activationFailure, + rollbackFailure + ); + if (RetirementPendingException.Find(combined) is not null) + { + m_failure = combined; + } + throw combined; + } + throw; + } + } + + internal void Complete() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = 0; i < transactions.Count; i++) + { + TryCleanup(transactions[i].Complete, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Assembly catalog completion failed after all participants were attempted.", failures); + } + } + + internal void Rollback() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = transactions.Count - 1; i >= 0; i--) + { + TryCleanup(transactions[i].Rollback, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Assembly catalog rollback failed after all participants were attempted.", failures); + } + } + + private void TryCleanup( + Action cleanup, + List failures + ) { + try + { + cleanup(); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failures.Count == 0 ? failure : new AggregateException( + "Catalog cleanup remains pending after earlier failures.", + [.. failures, failure] + ); + if (ReferenceEquals(m_failure, failure)) + { + throw; + } + throw m_failure; + } + catch (Exception exception) + { + failures.Add(exception); + } + } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs new file mode 100644 index 000000000..21a6332b8 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Extensibility.Modules; + +internal sealed class CatalogParticipantRegistration( + AssemblyCatalogCoordinator owner, + Guid id +) : IDisposable +{ + private bool m_disposed; + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + owner.Unregister(id); + } + + internal Guid id { get; } = id; +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs index c44defcaa..10ae21095 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs @@ -10,11 +10,15 @@ namespace Inno.Extensibility.Modules; internal sealed class CompositeAssemblyUnloadProbe : IAssemblyUnloadProbe { private readonly IAssemblyUnloadProbe[] m_children; + internal CompositeAssemblyUnloadProbe(IReadOnlyList children) - => m_children = children.ToArray(); - /// + { + m_children = children.ToArray(); + } + + /// public string description => string.Join(", ", m_children.Select(static child => child.description)); - /// + /// public bool isCompleted => m_children.All(static child => child.isCompleted); } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs index 15189de8e..938e41291 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs @@ -16,6 +16,7 @@ public interface IAssemblyCatalogSource : IDisposable /// Notifies the owner that the host assembly snapshot should be refreshed at a safe point. /// event Action? changed; + /// /// Gets the complete host assemblies that participate in extension discovery. /// @@ -23,6 +24,7 @@ public interface IAssemblyCatalogSource : IDisposable /// The current host snapshot; the caller must not retain it beyond its catalog generation. /// IReadOnlyList GetAssemblies(); + /// /// Gets host contracts and framework assemblies available to candidate modules. /// @@ -30,6 +32,7 @@ public interface IAssemblyCatalogSource : IDisposable /// A snapshot of shareable assemblies owned by the host implementation. /// IReadOnlyList GetSharedAssemblies(); + /// /// Determines whether a referenced simple name belongs to the selected managed framework. /// @@ -40,6 +43,7 @@ public interface IAssemblyCatalogSource : IDisposable /// Whether the framework owns this dependency. /// bool IsFrameworkReference(string assemblyName); + /// /// Determines whether an assembly is a framework contract rather than a contributed module. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs index 15456a3c5..d94cdd44c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs @@ -16,26 +16,32 @@ public interface IModuleSource /// Gets the stable logical name used by dependency ordering and replacement transactions. /// string moduleName { get; } + /// /// Gets the ownership domain of the contribution. /// AssemblyDomain domain { get; } + /// /// Gets the default dependency scope of contributed assemblies. /// AssemblyScope scope { get; } + /// /// Gets whether retirement can release this source's code generation. /// bool collectible { get; } + /// /// Gets the explicit logical upstream module names. /// IReadOnlyList upstreamModuleNames { get; } + /// /// Gets explicit scope overrides keyed by contributed assembly simple name. /// IReadOnlyDictionary assemblyScopes { get; } + /// /// Reads the complete owned assembly identities before any generation is acquired. /// @@ -43,6 +49,7 @@ public interface IModuleSource /// Distinct, nonempty simple names; invalid or unavailable source data causes an exception. /// IReadOnlyList GetAssemblyNames(); + /// /// Acquires a validated candidate and transfers its lifetime to the caller on success. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs index c40acbb8d..693094e3c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs @@ -47,39 +47,48 @@ public ModuleCatalogContribution( ArgumentException.ThrowIfNullOrWhiteSpace(moduleName); ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(assemblyScopes); - if (assemblies.Count == 0 || assemblies.Any(static value => value is null || value.IsDynamic) || - assemblies.Distinct().Count() != assemblies.Count || - assemblies.Any(assembly => !assemblyScopes.ContainsKey(assembly)) || - assemblyScopes.Count != assemblies.Count) + if (assemblies.Count == 0 || assemblies.Any(static value => value is null || value.IsDynamic) + || assemblies.Distinct().Count() != assemblies.Count + || assemblies.Any(assembly => !assemblyScopes.ContainsKey(assembly)) + || assemblyScopes.Count != assemblies.Count + ) { throw new ArgumentException("A contribution requires distinct assemblies with complete scopes."); + } this.moduleName = moduleName; this.domain = domain; this.scope = scope; this.assemblies = Array.AsReadOnly(assemblies.ToArray()); this.assemblyScopes = new ReadOnlyDictionary( - assemblyScopes.ToDictionary(static pair => pair.Key, static pair => pair.Value)); + assemblyScopes.ToDictionary(static pair => pair.Key, static pair => pair.Value) + ); this.lifetime = lifetime; } + /// /// Gets the stable module name. /// public string moduleName { get; } + /// /// Gets the ownership domain. /// public AssemblyDomain domain { get; } + /// /// Gets the default dependency scope. /// public AssemblyScope scope { get; } + /// /// Gets the immutable owned assembly set. /// public IReadOnlyList assemblies { get; } + /// /// Gets the complete per-assembly scope map. /// public IReadOnlyDictionary assemblyScopes { get; } + /// /// Gets the owned generation lifetime, or null for externally owned code. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs index f03009749..84e937a68 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs @@ -27,30 +27,40 @@ Action trackRetirement this.upstreamModules = Array.AsReadOnly(upstreamModules.ToArray()); this.activeModules = Array.AsReadOnly(activeModules.ToArray()); this.plannedAssemblies = new ReadOnlyDictionary( - plannedAssemblies.ToDictionary(static pair => pair.Key, static pair => pair.Value, - StringComparer.OrdinalIgnoreCase)); + plannedAssemblies.ToDictionary( + static pair => pair.Key, + static pair => pair.Value, + StringComparer.OrdinalIgnoreCase + ) + ); m_trackRetirement = trackRetirement; } + /// /// Gets the candidate generation number. /// public int generation { get; } + /// /// Gets the borrowed host contract source. /// public IAssemblyCatalogSource host { get; } + /// /// Gets the validated direct upstream contributions for this candidate. /// public IReadOnlyList upstreamModules { get; } + /// /// Gets active contributions used to reject forbidden downstream references. /// public IReadOnlyList activeModules { get; } + /// /// Gets identities and classifications for the complete candidate closure. /// public IReadOnlyDictionary plannedAssemblies { get; } + /// /// Transfers a failed acquisition's non-owning retirement probe to the shared generation gate. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs index 5f4f71f32..aa14ee65d 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs @@ -9,12 +9,10 @@ public enum AssemblyDomain /// The assembly is engine-owned and remains in the default load context. /// InnoInternal, - /// /// The assembly contains project scripting code in a collectible load context. /// InnoScripting, - /// /// The assembly belongs to the project's unified collectible plugin generation. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs index 239f0caa8..290a55609 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs @@ -12,7 +12,7 @@ public static class AssemblyExtensions private const string C_ASSEMBLY_DOMAIN_KEY = "Inno.AssemblyDomain"; private const string C_ASSEMBLY_SCOPE_KEY = "Inno.AssemblyScope"; - private static readonly ConditionalWeakTable S_CACHE = new(); + private static readonly ConditionalWeakTable CACHE = new(); /// /// Resolves the reload domain declared by an assembly. @@ -34,7 +34,8 @@ public static AssemblyDomain GetInnoAssemblyDomain(this Assembly assembly) ArgumentNullException.ThrowIfNull(assembly); AssemblyClassification classification = GetClassification(assembly); return classification.domain ?? throw new InvalidOperationException( - $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_DOMAIN_KEY} metadata."); + $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_DOMAIN_KEY} metadata." + ); } /// @@ -57,7 +58,8 @@ public static AssemblyScope GetInnoAssemblyScope(this Assembly assembly) ArgumentNullException.ThrowIfNull(assembly); AssemblyClassification classification = GetClassification(assembly); return classification.scope ?? throw new InvalidOperationException( - $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_SCOPE_KEY} metadata."); + $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_SCOPE_KEY} metadata." + ); } /// @@ -93,11 +95,11 @@ internal static void RegisterInnoAssemblyClassification( AssemblyScope scope ) { ArgumentNullException.ThrowIfNull(assembly); - S_CACHE.AddOrUpdate(assembly, new AssemblyClassification(domain, scope)); + CACHE.AddOrUpdate(assembly, new AssemblyClassification(domain, scope)); } private static AssemblyClassification GetClassification(Assembly assembly) - => S_CACHE.GetValue(assembly, static value => ResolveClassification(value)); + => CACHE.GetValue(assembly, static value => ResolveClassification(value)); private static AssemblyClassification ResolveClassification(Assembly assembly) { @@ -108,12 +110,14 @@ private static AssemblyClassification ResolveClassification(Assembly assembly) if (string.Equals(metadata.Key, C_ASSEMBLY_DOMAIN_KEY, StringComparison.Ordinal)) { if (Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyDomain parsedDomain)) + { domain = parsedDomain; + } continue; } - if (string.Equals(metadata.Key, C_ASSEMBLY_SCOPE_KEY, StringComparison.Ordinal) && - Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyScope parsedScope)) - { + if (string.Equals(metadata.Key, C_ASSEMBLY_SCOPE_KEY, StringComparison.Ordinal) + && Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyScope parsedScope) + ) { scope = parsedScope; } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs index d6dcc7aad..5f42eac7e 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs @@ -9,7 +9,6 @@ public enum AssemblyScope /// The assembly is available to runtime and editor consumers. /// Runtime, - /// /// The assembly is available only to editor consumers. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs index 1b9a29a35..97b082e6c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Reflection; - using Inno.Core.Collections; using Inno.Core.Execution; using Inno.Extensibility.Reload; @@ -31,33 +30,6 @@ public sealed class ModuleHost : IDisposable private Exception? m_retirementFailure; private object? m_retainedRetirement; - /// - /// Gets whether this module host can accept catalog operations. - /// - public bool isInitialized { get; private set; } - - /// - /// Gets the admission gate and retirement owner shared by all module and host generation changes. - /// - public GenerationCoordinator generations { get; } = new(); - - /// - /// Gets non-owning information about active managed and external modules. - /// - public IReadOnlyList modules - { - get - { - lock (m_sync) - { - return m_modules.Values - .OrderBy(static module => module.moduleName, StringComparer.Ordinal) - .Select(static module => module.CreateInfo()) - .ToArray(); - } - } - } - /// /// Creates a module host from the explicitly supplied assembly source and publishes its first catalog. /// @@ -77,7 +49,7 @@ public ModuleHost(ModuleHostOptions options) ArgumentNullException.ThrowIfNull(m_options.catalogSource); m_options.catalogSource.changed += OnAssemblyLoaded; m_assemblyLoadSubscribed = true; - isInitialized = true; + this.isInitialized = true; m_hostCatalogDirty = true; try { @@ -91,6 +63,33 @@ public ModuleHost(ModuleHostOptions options) } } + /// + /// Gets whether this module host can accept catalog operations. + /// + public bool isInitialized { get; private set; } + + /// + /// Gets the admission gate and retirement owner shared by all module and host generation changes. + /// + public GenerationCoordinator generations { get; } = new(); + + /// + /// Gets non-owning information about active managed and external modules. + /// + public IReadOnlyList modules + { + get + { + lock (m_sync) + { + return m_modules.Values + .OrderBy(static module => module.moduleName, StringComparer.Ordinal) + .Select(static module => module.CreateInfo()) + .ToArray(); + } + } + } + /// /// Registers a transactional consumer of the assembly catalog and initializes it from the /// currently active generation. @@ -124,7 +123,8 @@ public IDisposable RegisterCatalogParticipant(IAssemblyCatalogParticipant partic Trace.TraceError( "Assembly catalog participant '{0}' failed during initial cleanup: {1}", participant.GetType().FullName, - exception); + exception + ); throw; } return registration; @@ -151,7 +151,8 @@ public IDisposable RegisterCatalogParticipant(IAssemblyCatalogParticipant partic Trace.TraceError( "Assembly catalog participant '{0}' failed during initial rollback: {1}", participant.GetType().FullName, - exception); + exception + ); } registration.Dispose(); throw; @@ -177,17 +178,19 @@ public AssemblyModuleHandle Load(IModuleSource request) EnsureNoReloadInProgress(); ValidateUniqueModuleName(request.moduleName); if (request.domain != AssemblyDomain.InnoPlugin) + { ValidateUniqueReloadBoundary(request.domain, request.scope); + } - AssemblyModuleHandle handle = new(Guid.NewGuid()); - IReadOnlyDictionary plannedAssemblies = - BuildPlannedAssemblyMap([request]); + var handle = new AssemblyModuleHandle(Guid.NewGuid()); + IReadOnlyDictionary plannedAssemblies = BuildPlannedAssemblyMap([request]); AssemblyModuleEntry module = StageModule( handle, request, generation: 1, upstreamModules: GetUpstreamModules(request, []), - plannedAssemblies); + plannedAssemblies + ); m_modules.Add(handle, module); try { @@ -220,12 +223,18 @@ public AssemblyModuleHandle Register( IReadOnlyList assemblies ) { if (string.IsNullOrWhiteSpace(moduleName)) + { throw new ArgumentException("Module name is required.", nameof(moduleName)); + } ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Count == 0) + { throw new ArgumentException("At least one assembly is required.", nameof(assemblies)); + } if (assemblies.Any(static assembly => assembly is null || assembly.IsDynamic)) + { throw new ArgumentException("External modules must contain non-dynamic assemblies.", nameof(assemblies)); + } lock (m_sync) { @@ -233,22 +242,23 @@ IReadOnlyList assemblies EnsureNoReloadInProgress(); ValidateUniqueModuleName(moduleName); - if (!assemblies[0].TryGetInnoAssemblyClassification( - out AssemblyDomain domain, - out AssemblyScope scope) || - assemblies.Any(assembly => + if (!assemblies[0].TryGetInnoAssemblyClassification(out AssemblyDomain domain, out AssemblyScope scope) + || assemblies.Any(assembly => ( !assembly.TryGetInnoAssemblyClassification( out AssemblyDomain candidateDomain, - out AssemblyScope candidateScope) || - candidateDomain != domain || - candidateScope != scope)) - { + out AssemblyScope candidateScope + ) + || candidateDomain != domain + || candidateScope != scope + )) + ) { throw new ArgumentException( "Every externally owned module assembly must declare the same valid domain and scope metadata.", - nameof(assemblies)); + nameof(assemblies) + ); } - AssemblyModuleHandle handle = new(Guid.NewGuid()); + var handle = new AssemblyModuleHandle(Guid.NewGuid()); var module = new AssemblyModuleEntry { handle = handle, @@ -260,9 +270,13 @@ IReadOnlyList assemblies scope = scope, assemblies = assemblies.Distinct().ToArray(), assemblyScopes = assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope), - contribution = new ModuleCatalogContribution(moduleName, domain, scope, + contribution = new ModuleCatalogContribution( + moduleName, + domain, + scope, assemblies.Distinct().ToArray(), - assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope)) + assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope) + ) }; m_modules.Add(handle, module); try @@ -278,6 +292,33 @@ IReadOnlyList assemblies } } + /// + /// Stages a dependency-ordered set of module additions or replacements as one atomic transaction. + /// Existing modules are matched by their stable module names; an unknown name creates a new module. + /// + /// + /// The complete reverse-dependency reload closure. + /// + /// + /// A session that publishes or rolls back every candidate together. + /// + /// + /// Thrown when is . + /// + /// + /// Thrown when the request set is empty or contains duplicate module names. + /// + public AssemblyReloadSession BeginReload(IReadOnlyList requests) + { + ArgumentNullException.ThrowIfNull(requests); + lock (m_sync) + { + EnsureInitialized(); + EnsureNoReloadInProgress(); + return BeginReloadLocked(requests, removedModuleNames: [], forcedHandles: null); + } + } + /// /// Stages and validates a replacement generation without publishing it. /// @@ -300,46 +341,22 @@ IModuleSource request EnsureInitialized(); EnsureNoReloadInProgress(); if (!m_modules.TryGetValue(module, out AssemblyModuleEntry? previous)) + { throw new ArgumentException("The assembly module is not active.", nameof(module)); + } if (!string.Equals(previous.moduleName, request.moduleName, StringComparison.Ordinal)) { throw new ArgumentException( $"Reload request module name '{request.moduleName}' does not match '{previous.moduleName}'.", - nameof(request)); + nameof(request) + ); } return BeginReloadLocked( [request], removedModuleNames: [], - new Dictionary( - StringComparer.Ordinal) { [request.moduleName] = module }); - } - } - - /// - /// Stages a dependency-ordered set of module additions or replacements as one atomic transaction. - /// Existing modules are matched by their stable module names; an unknown name creates a new module. - /// - /// - /// The complete reverse-dependency reload closure. - /// - /// - /// A session that publishes or rolls back every candidate together. - /// - /// - /// Thrown when is . - /// - /// - /// Thrown when the request set is empty or contains duplicate module names. - /// - public AssemblyReloadSession BeginReload(IReadOnlyList requests) - { - ArgumentNullException.ThrowIfNull(requests); - lock (m_sync) - { - EnsureInitialized(); - EnsureNoReloadInProgress(); - return BeginReloadLocked(requests, removedModuleNames: [], forcedHandles: null); + new Dictionary(StringComparer.Ordinal) { [request.moduleName] = module } + ); } } @@ -392,7 +409,9 @@ public IAssemblyUnloadProbe Unload(AssemblyModuleHandle module) EnsureNoReloadInProgress(); ValidateUnloadClosure([module]); if (!m_modules.Remove(module, out AssemblyModuleEntry? removed)) + { throw new ArgumentException("The assembly module is not active.", nameof(module)); + } try { RebuildLocked(); @@ -430,17 +449,23 @@ public IAssemblyUnloadProbe Unload(IReadOnlyList modules) EnsureInitialized(); EnsureNoReloadInProgress(); if (modules.Distinct().Count() != modules.Count) + { throw new ArgumentException("Module handles must be distinct.", nameof(modules)); + } ValidateUnloadClosure(modules); var removed = new List(modules.Count); foreach (AssemblyModuleHandle handle in modules) { if (!m_modules.TryGetValue(handle, out AssemblyModuleEntry? module)) + { throw new ArgumentException("An assembly module is not active.", nameof(modules)); + } removed.Add(module); } foreach (AssemblyModuleEntry module in removed) + { m_modules.Remove(module.handle); + } try { RebuildLocked(); @@ -448,19 +473,23 @@ public IAssemblyUnloadProbe Unload(IReadOnlyList modules) catch { foreach (AssemblyModuleEntry module in removed) + { m_modules.Add(module.handle, module); + } throw; } AssemblyModuleEntry[] unloadOrder = removed - .OrderByDescending(static module => module.domain == AssemblyDomain.InnoPlugin + .OrderByDescending(static module => ( + module.domain == AssemblyDomain.InnoPlugin ? 0 - : module.scope == AssemblyScope.Runtime ? 1 : 2) + : module.scope == AssemblyScope.Runtime ? 1 : 2 + )) .ToArray(); - var monitors = unloadOrder.Select(BeginUnload).ToArray(); + IAssemblyUnloadProbe[] monitors = unloadOrder.Select(BeginUnload).ToArray(); return monitors.Length == 1 - ? monitors[0] - : new CompositeAssemblyUnloadProbe(monitors); + ? monitors[0] + : new CompositeAssemblyUnloadProbe(monitors); } } @@ -509,7 +538,9 @@ public void Rebuild() public void Dispose() { lock (m_sync) + { ShutdownLocked(); + } GC.SuppressFinalize(this); } @@ -519,12 +550,18 @@ internal void Activate(ReloadState state) { EnsureActiveState(state); if (state.activated) + { return; + } foreach (AssemblyModuleEntry removed in state.removedModules) + { m_modules.Remove(removed.handle); + } for (int i = 0; i < state.candidateModules.Length; i++) + { m_modules[state.candidateModules[i].handle] = state.candidateModules[i]; + } m_currentCatalog = state.candidateCatalog; try { @@ -543,7 +580,9 @@ internal void Activate(ReloadState state) state.finished = true; m_reloadInProgress = false; if (activationFailure is AggregateException) + { generations.Fault(activationFailure); + } try { state.refresh.Rollback(); @@ -555,14 +594,20 @@ internal void Activate(ReloadState state) } catch (Exception rollbackFailure) { - var failure = new AggregateException("Module activation and rollback failed.", activationFailure, rollbackFailure); + var failure = new AggregateException( + "Module activation and rollback failed.", + activationFailure, + rollbackFailure + ); generations.Fault(failure); throw failure; } finally { if (m_retirementFailure is null) + { BeginUnloadReverse(state.candidateModules); + } } throw; } @@ -575,7 +620,9 @@ internal IAssemblyUnloadProbe Complete(ReloadState state) { EnsureActiveState(state); if (!state.activated) + { throw new InvalidOperationException("The reload session must be activated before completion."); + } state.finished = true; m_reloadInProgress = false; @@ -599,9 +646,15 @@ internal IAssemblyUnloadProbe Complete(ReloadState state) .OfType() .Concat(state.removedModules) .Distinct() - .ToArray()); + .ToArray() + ); if (cleanupFailure is not null) - throw new InvalidOperationException("The module generation committed but retirement failed; restart the host.", cleanupFailure); + { + throw new InvalidOperationException( + "The module generation committed but retirement failed; restart the host.", + cleanupFailure + ); + } return monitor; } } @@ -612,7 +665,9 @@ internal void Rollback(ReloadState state) { EnsureRetirementSafe(); if (state.finished) + { return; + } if (state.activated) { RestorePreviousModules(state); @@ -638,7 +693,9 @@ internal void Rollback(ReloadState state) finally { if (m_retirementFailure is null) + { BeginUnloadReverse(state.candidateModules); + } } } } @@ -649,33 +706,39 @@ private AssemblyReloadSession BeginReloadLocked( IReadOnlyDictionary? forcedHandles ) { if (requests.Count == 0 && removedModuleNames.Count == 0) + { throw new ArgumentException("At least one module change is required.", nameof(requests)); + } if (requests.Any(static request => request is null)) + { throw new ArgumentException("Module reload requests cannot contain null entries.", nameof(requests)); + } IModuleSource[] orderedRequests = OrderReloadRequests(requests); - if (orderedRequests.Select(static request => request.moduleName).Distinct(StringComparer.Ordinal).Count() != - orderedRequests.Length) - { + if (orderedRequests.Select(static request => request.moduleName).Distinct(StringComparer.Ordinal).Count() + != orderedRequests.Length + ) { throw new ArgumentException("A reload plan cannot contain duplicate module names.", nameof(requests)); } - if (removedModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) || - removedModuleNames.Distinct(StringComparer.Ordinal).Count() != removedModuleNames.Count) - { + if (removedModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) + || removedModuleNames.Distinct(StringComparer.Ordinal).Count() != removedModuleNames.Count + ) { throw new ArgumentException("Removed module names must be non-empty and distinct.", nameof(removedModuleNames)); } if (orderedRequests.Any(request => removedModuleNames.Contains(request.moduleName, StringComparer.Ordinal))) + { throw new ArgumentException("A module cannot be replaced and removed together.", nameof(removedModuleNames)); + } AssemblyModuleEntry[] removedModules = removedModuleNames.Select(name => { AssemblyModuleEntry? module = m_modules.Values.SingleOrDefault(candidate => string.Equals(candidate.moduleName, name, StringComparison.Ordinal)); return module ?? throw new ArgumentException( $"Removed assembly module '{name}' is not active.", - nameof(removedModuleNames)); + nameof(removedModuleNames) + ); }).ToArray(); ValidateReloadClosure(orderedRequests, removedModules); - IReadOnlyDictionary plannedAssemblies = - BuildPlannedAssemblyMap(orderedRequests); + IReadOnlyDictionary plannedAssemblies = BuildPlannedAssemblyMap(orderedRequests); var previousModules = new AssemblyModuleEntry?[orderedRequests.Length]; var candidates = new List(orderedRequests.Length); @@ -692,11 +755,12 @@ private AssemblyReloadSession BeginReloadLocked( candidates.Add(StageModule(handle, request, generation, upstream, plannedAssemblies)); } - var replacements = candidates.ToDictionary(static module => module.handle); + Dictionary replacements = candidates.ToDictionary(static module => module.handle); AssemblyCatalogSnapshot previousCatalog = m_currentCatalog; AssemblyCatalogSnapshot candidateCatalog = BuildCatalog( replacements, - removedModules.Select(static module => module.handle).ToHashSet()); + removedModules.Select(static module => module.handle).ToHashSet() + ); AssemblyCatalogRefreshSet refresh = m_catalogs.Prepare(candidateCatalog); m_reloadInProgress = true; return new AssemblyReloadSession(this, new ReloadState @@ -726,15 +790,22 @@ private AssemblyReloadSession BeginReloadLocked( IReadOnlyDictionary? forcedHandles ) { if (forcedHandles is not null && forcedHandles.TryGetValue(request.moduleName, out AssemblyModuleHandle handle)) + { return m_modules[handle]; + } AssemblyModuleEntry? previous = m_modules.Values.SingleOrDefault(module => string.Equals(module.moduleName, request.moduleName, StringComparison.Ordinal)); if (previous is null && request.domain != AssemblyDomain.InnoPlugin) + { ValidateUniqueReloadBoundary(request.domain, request.scope); - else if (previous is not null && - (previous.domain != request.domain || previous.scope != request.scope)) + } + else if (previous is not null + && (previous.domain != request.domain || previous.scope != request.scope) + ) { throw new InvalidOperationException( - $"Module '{request.moduleName}' cannot change its domain or scope across generations."); + $"Module '{request.moduleName}' cannot change its domain or scope across generations." + ); + } return previous; } @@ -746,17 +817,21 @@ IReadOnlyList stagedCandidates .Where(active => stagedCandidates.All(candidate => candidate.handle != active.handle)) .Concat(stagedCandidates); if (request.upstreamModuleNames.Count == 0) + { return []; + } Dictionary byName = effectiveModules.ToDictionary( static module => module.moduleName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); return request.upstreamModuleNames.Select(name => { if (!byName.TryGetValue(name, out AssemblyModuleEntry? module)) { throw new InvalidOperationException( - $"Module '{request.moduleName}' requires unavailable upstream module '{name}'."); + $"Module '{request.moduleName}' requires unavailable upstream module '{name}'." + ); } return module; }).ToArray(); @@ -764,18 +839,19 @@ IReadOnlyList stagedCandidates private int GetReloadOrder(IModuleSource request) => request.domain switch - { - AssemblyDomain.InnoPlugin => 0, - AssemblyDomain.InnoScripting when request.scope == AssemblyScope.Runtime => 1, - AssemblyDomain.InnoScripting => 2, - _ => throw new ArgumentException("InnoInternal assemblies cannot be loaded into a collectible module.") - }; + { + AssemblyDomain.InnoPlugin => 0, + AssemblyDomain.InnoScripting when request.scope == AssemblyScope.Runtime => 1, + AssemblyDomain.InnoScripting => 2, + _ => throw new ArgumentException("InnoInternal assemblies cannot be loaded into a collectible module.") + }; private IModuleSource[] OrderReloadRequests(IReadOnlyList requests) { Dictionary byName = requests.ToDictionary( static request => request.moduleName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); IComparer ordering = Comparer.Create(( left, right @@ -783,23 +859,26 @@ private IModuleSource[] OrderReloadRequests(IReadOnlyList request { int domainOrder = GetReloadOrder(byName[left]).CompareTo(GetReloadOrder(byName[right])); return domainOrder != 0 - ? domainOrder - : StringComparer.Ordinal.Compare(left, right); + ? domainOrder + : StringComparer.Ordinal.Compare(left, right); }); var graph = new DependencyGraph(StringComparer.Ordinal, ordering); foreach (IModuleSource request in requests) { graph.AddNode(request.moduleName); foreach (string dependencyName in request.upstreamModuleNames - .OrderBy(static value => value, StringComparer.Ordinal)) - { + .OrderBy(static value => value, StringComparer.Ordinal) + ) { if (!byName.TryGetValue(dependencyName, out IModuleSource? dependency)) + { continue; + } if (GetReloadOrder(dependency) > GetReloadOrder(request)) { throw new ArgumentException( $"Module '{request.moduleName}' cannot depend on downstream module '{dependencyName}'.", - nameof(requests)); + nameof(requests) + ); } graph.AddDependency(request.moduleName, dependencyName); } @@ -821,12 +900,18 @@ private void RestorePreviousModules(ReloadState state) AssemblyModuleEntry candidate = state.candidateModules[i]; AssemblyModuleEntry? previous = state.previousModules[i]; if (previous is null) + { m_modules.Remove(candidate.handle); + } else + { m_modules[candidate.handle] = previous; + } } foreach (AssemblyModuleEntry removed in state.removedModules) + { m_modules[removed.handle] = removed; + } m_currentCatalog = state.previousCatalog; } @@ -843,7 +928,9 @@ private void RebuildLocked(bool deferWhileBusy = false) { m_hostCatalogDirty = true; if (deferWhileBusy) + { return; + } throw new InvalidOperationException("Catalog publication is blocked by a generation owner operation."); } using IDisposable publication = reservation!; @@ -870,7 +957,8 @@ private void RebuildOnceLocked() try { AssemblyCatalogSnapshot candidate = BuildCatalog( - new Dictionary()); + new Dictionary() + ); AssemblyCatalogRefreshSet refresh = m_catalogs.Prepare(candidate); m_currentCatalog = candidate; bool activated = false; @@ -888,7 +976,9 @@ private void RebuildOnceLocked() catch (Exception failure) { if (activated) + { generations.Fault(failure); + } else { m_currentCatalog = previous; @@ -903,7 +993,11 @@ private void RebuildOnceLocked() } catch (Exception rollbackFailure) { - var aggregate = new AggregateException("Catalog activation and rollback failed.", failure, rollbackFailure); + var aggregate = new AggregateException( + "Catalog activation and rollback failed.", + failure, + rollbackFailure + ); generations.Fault(aggregate); throw aggregate; } @@ -914,7 +1008,9 @@ private void RebuildOnceLocked() catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { if (m_retirementFailure is null) + { RetainFailedRetirement(failure, (m_catalogs, previous)); + } throw; } } @@ -940,11 +1036,6 @@ IReadOnlySet removed return host.Concat(moduleAssemblies).Distinct().ToArray(); } - - - - - private AssemblyModuleEntry StageModule( AssemblyModuleHandle handle, IModuleSource source, @@ -954,34 +1045,50 @@ IReadOnlyDictionary plannedAssemblies ) { ValidateRequest(source); var context = new ModuleSourceContext( - generation, m_options.catalogSource, + generation, + m_options.catalogSource, upstreamModules.Select(static module => module.contribution).ToArray(), m_modules.Values.Select(static module => module.contribution).ToArray(), - plannedAssemblies.ToDictionary(static pair => pair.Key, + plannedAssemblies.ToDictionary( + static pair => pair.Key, static pair => new ModuleAssemblyDescriptor(pair.Value.domain, pair.Value.scope), - StringComparer.OrdinalIgnoreCase), - generations.TrackRetirement); + StringComparer.OrdinalIgnoreCase + ), + generations.TrackRetirement + ); ModuleCatalogContribution contribution = source.Prepare(context); try { - if (contribution.moduleName != source.moduleName || contribution.domain != source.domain || - contribution.scope != source.scope || (contribution.lifetime is not null) != source.collectible) + if (contribution.moduleName != source.moduleName || contribution.domain != source.domain + || contribution.scope != source.scope || (contribution.lifetime is not null) != source.collectible + ) { throw new InvalidOperationException("A module source changed its declared ownership during preparation."); + } foreach (Assembly assembly in contribution.assemblies) + { assembly.RegisterInnoAssemblyClassification(contribution.domain, contribution.assemblyScopes[assembly]); + } return new AssemblyModuleEntry { - handle = handle, moduleName = source.moduleName, generation = generation, - externallyOwned = contribution.lifetime is null, collectible = source.collectible, - domain = source.domain, scope = source.scope, assemblies = contribution.assemblies.ToArray(), - assemblyScopes = contribution.assemblyScopes, upstreamModuleNames = source.upstreamModuleNames.ToArray(), + handle = handle, + moduleName = source.moduleName, + generation = generation, + externallyOwned = contribution.lifetime is null, + collectible = source.collectible, + domain = source.domain, + scope = source.scope, + assemblies = contribution.assemblies.ToArray(), + assemblyScopes = contribution.assemblyScopes, + upstreamModuleNames = source.upstreamModuleNames.ToArray(), contribution = contribution }; } catch { if (contribution.lifetime is not null) + { generations.TrackRetirement(contribution.lifetime.BeginRetirement()); + } throw; } } @@ -991,7 +1098,7 @@ IReadOnlyDictionary plannedAssemblies private IAssemblyUnloadProbe BeginUnload(AssemblyModuleEntry module) { IAssemblyUnloadProbe probe = module.contribution.lifetime?.BeginRetirement() - ?? new CompositeAssemblyUnloadProbe([]); + ?? new CompositeAssemblyUnloadProbe([]); generations.TrackRetirement(probe); return probe; } @@ -1000,30 +1107,37 @@ private IAssemblyUnloadProbe BeginUnloadReverse(IReadOnlyList(modules.Count); for (int i = modules.Count - 1; i >= 0; i--) + { monitors.Add(BeginUnload(modules[i])); + } return monitors.Count == 1 - ? monitors[0] - : new CompositeAssemblyUnloadProbe(monitors); + ? monitors[0] + : new CompositeAssemblyUnloadProbe(monitors); } - - private void ValidateRequest(IModuleSource request) { if (string.IsNullOrWhiteSpace(request.moduleName)) + { throw new ArgumentException("Module name is required.", nameof(request)); + } if (!Enum.IsDefined(request.domain) || request.domain == AssemblyDomain.InnoInternal) + { throw new ArgumentException("A reloadable module must belong to InnoPlugin or InnoScripting.", nameof(request)); + } if (!Enum.IsDefined(request.scope) || request.assemblyScopes.Values.Any(static scope => !Enum.IsDefined(scope))) - throw new ArgumentException("A reloadable module contains an invalid assembly scope.", nameof(request)); - if (request.upstreamModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) || - request.upstreamModuleNames.Distinct(StringComparer.Ordinal).Count() != - request.upstreamModuleNames.Count || - request.upstreamModuleNames.Contains(request.moduleName, StringComparer.Ordinal)) { + throw new ArgumentException("A reloadable module contains an invalid assembly scope.", nameof(request)); + } + if (request.upstreamModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) + || request.upstreamModuleNames.Distinct(StringComparer.Ordinal).Count() + != request.upstreamModuleNames.Count + || request.upstreamModuleNames.Contains(request.moduleName, StringComparer.Ordinal) + ) { throw new ArgumentException( "Upstream module names must be non-empty, distinct, and cannot reference the owning module.", - nameof(request)); + nameof(request) + ); } _ = request.GetAssemblyNames(); @@ -1041,26 +1155,31 @@ private IReadOnlyDictionary BuildPlannedAssemblyMap(IRe ownedNames.Add(name); AssemblyScope scope = request.assemblyScopes.GetValueOrDefault(name, request.scope); if (!result.TryAdd(name, new PlannedAssembly(request.domain, scope))) + { throw new InvalidDataException($"Reload plan contains duplicate managed assembly name '{name}'."); + } } string? unknownScope = request.assemblyScopes.Keys.FirstOrDefault(name => !ownedNames.Contains(name)); if (unknownScope is not null) { throw new InvalidDataException( - $"Module '{request.moduleName}' declares a scope for unknown assembly '{unknownScope}'."); + $"Module '{request.moduleName}' declares a scope for unknown assembly '{unknownScope}'." + ); } } return result; } - - private void ValidateUniqueModuleName(string moduleName) { if (string.IsNullOrWhiteSpace(moduleName)) + { throw new ArgumentException("Module name is required.", nameof(moduleName)); + } if (m_modules.Values.Any(module => string.Equals(module.moduleName, moduleName, StringComparison.Ordinal))) + { throw new InvalidOperationException($"Assembly module '{moduleName}' is already active."); + } } private void ValidateUniqueReloadBoundary( @@ -1068,11 +1187,12 @@ private void ValidateUniqueReloadBoundary( AssemblyScope scope ) { if (domain == AssemblyDomain.InnoPlugin) + { return; + } if (m_modules.Values.Any(module => module.domain == domain && module.scope == scope)) { - throw new InvalidOperationException( - $"Only one {scope} scripting module can be active."); + throw new InvalidOperationException($"Only one {scope} scripting module can be active."); } } @@ -1080,32 +1200,39 @@ private void ValidateReloadClosure( IReadOnlyList requests, IReadOnlyList removedModules ) { - bool reloadsPlugins = requests.Any(static request => request.domain == AssemblyDomain.InnoPlugin) || - removedModules.Any(static module => module.domain == AssemblyDomain.InnoPlugin); - bool reloadsRuntime = requests.Any(static request => - request.domain == AssemblyDomain.InnoScripting && - request.scope == AssemblyScope.Runtime) || - removedModules.Any(static module => - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Runtime); - bool reloadsEditor = requests.Any(static request => - request.domain == AssemblyDomain.InnoScripting && - request.scope == AssemblyScope.Editor) || - removedModules.Any(static module => - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Editor); - if (reloadsPlugins && m_modules.Values.Any(static module => module.domain == AssemblyDomain.InnoScripting) && - (!reloadsRuntime || !reloadsEditor)) - { + bool reloadsPlugins = requests.Any(static request => request.domain == AssemblyDomain.InnoPlugin) + || removedModules.Any(static module => module.domain == AssemblyDomain.InnoPlugin); + bool reloadsRuntime = requests.Any(static request => ( + request.domain == AssemblyDomain.InnoScripting + && request.scope == AssemblyScope.Runtime + )) + || removedModules.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Runtime + )); + bool reloadsEditor = requests.Any(static request => ( + request.domain == AssemblyDomain.InnoScripting + && request.scope == AssemblyScope.Editor + )) + || removedModules.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Editor + )); + if (reloadsPlugins && m_modules.Values.Any(static module => module.domain == AssemblyDomain.InnoScripting) + && (!reloadsRuntime || !reloadsEditor) + ) { throw new InvalidOperationException( - "Reloading plugins requires both dependent scripting modules in the same transaction."); + "Reloading plugins requires both dependent scripting modules in the same transaction." + ); } - if (reloadsRuntime && m_modules.Values.Any(static module => - module.domain == AssemblyDomain.InnoScripting && module.scope == AssemblyScope.Editor) && - !reloadsEditor) - { + if (reloadsRuntime && m_modules.Values.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting && module.scope == AssemblyScope.Editor + )) + && !reloadsEditor + ) { throw new InvalidOperationException( - "Reloading runtime scripts requires the editor scripting module in the same transaction."); + "Reloading runtime scripts requires the editor scripting module in the same transaction." + ); } HashSet reloadedNames = requests .Select(static request => request.moduleName) @@ -1115,102 +1242,114 @@ IReadOnlyList removedModules .Where(static request => request.domain == AssemblyDomain.InnoPlugin) .Select(static request => request.moduleName) .ToHashSet(StringComparer.Ordinal); - reloadedPlugins.UnionWith(removedModules - .Where(static module => module.domain == AssemblyDomain.InnoPlugin) - .Select(static module => module.moduleName)); - string? omittedDependent = m_modules.Values.FirstOrDefault(module => - module.domain == AssemblyDomain.InnoPlugin && - !reloadedNames.Contains(module.moduleName) && - module.upstreamModuleNames.Any(reloadedPlugins.Contains))?.moduleName; + reloadedPlugins.UnionWith( + removedModules + .Where(static module => module.domain == AssemblyDomain.InnoPlugin) + .Select(static module => module.moduleName) + ); + string? omittedDependent = m_modules.Values.FirstOrDefault(module => ( + module.domain == AssemblyDomain.InnoPlugin + && !reloadedNames.Contains(module.moduleName) + && module.upstreamModuleNames.Any(reloadedPlugins.Contains) + ))?.moduleName; if (omittedDependent is not null) { throw new InvalidOperationException( - $"Reloading a Plugin module also requires dependent module '{omittedDependent}'."); + $"Reloading a Plugin module also requires dependent module '{omittedDependent}'." + ); } } private void ValidateUnloadClosure(IReadOnlyList handles) { - var removed = handles.ToHashSet(); - bool removesPlugin = m_modules.Values.Any(module => - removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoPlugin); - bool removesRuntime = m_modules.Values.Any(module => - removed.Contains(module.handle) && - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Runtime); - if (removesPlugin && m_modules.Values.Any(module => - !removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoScripting)) - { + HashSet removed = handles.ToHashSet(); + bool removesPlugin = m_modules.Values.Any(module => ( + removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoPlugin + )); + bool removesRuntime = m_modules.Values.Any(module => ( + removed.Contains(module.handle) + && module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Runtime + )); + if (removesPlugin && m_modules.Values.Any(module => ( + !removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoScripting + )) + ) { throw new InvalidOperationException( - "Plugin unload requires all dependent scripting modules in the same transaction."); + "Plugin unload requires all dependent scripting modules in the same transaction." + ); } HashSet removedNames = m_modules.Values .Where(module => removed.Contains(module.handle)) .Select(static module => module.moduleName) .ToHashSet(StringComparer.Ordinal); - if (m_modules.Values.Any(module => - !removed.Contains(module.handle) && - module.upstreamModuleNames.Any(removedNames.Contains))) - { - throw new InvalidOperationException( - "A module cannot unload while an active module depends on it."); + if (m_modules.Values.Any(module => ( + !removed.Contains(module.handle) + && module.upstreamModuleNames.Any(removedNames.Contains) + )) + ) { + throw new InvalidOperationException("A module cannot unload while an active module depends on it."); } - if (removesRuntime && m_modules.Values.Any(module => - !removed.Contains(module.handle) && - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Editor)) - { + if (removesRuntime && m_modules.Values.Any(module => ( + !removed.Contains(module.handle) + && module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Editor + )) + ) { throw new InvalidOperationException( - "Runtime scripting unload requires the editor scripting module in the same transaction."); + "Runtime scripting unload requires the editor scripting module in the same transaction." + ); } } private void EnsureInitialized() { if (!isInitialized) + { throw new InvalidOperationException("ModuleHost is not initialized."); + } } private void EnsureNoReloadInProgress() { generations.EnsureReady("change the module generation"); if (m_reloadInProgress) + { throw new InvalidOperationException("Another assembly reload transaction is already active."); + } } private void EnsureActiveState(ReloadState state) { EnsureRetirementSafe(); if (state.finished) + { throw new InvalidOperationException("The reload session is already finished."); + } if (!m_reloadInProgress) + { throw new InvalidOperationException("The reload session is no longer current."); + } for (int i = 0; i < state.candidateModules.Length; i++) { AssemblyModuleEntry candidate = state.candidateModules[i]; AssemblyModuleEntry? expected = state.activated ? candidate : state.previousModules[i]; bool exists = m_modules.TryGetValue(candidate.handle, out AssemblyModuleEntry? current); if (expected is null ? exists : !exists || !ReferenceEquals(current, expected)) + { throw new InvalidOperationException("The reload session is no longer current."); + } } foreach (AssemblyModuleEntry removed in state.removedModules) { bool exists = m_modules.TryGetValue(removed.handle, out AssemblyModuleEntry? current); if (state.activated ? exists : !exists || !ReferenceEquals(current, removed)) + { throw new InvalidOperationException("The reload session removal set is no longer current."); + } } } - - - - - private readonly record struct PlannedAssembly( - AssemblyDomain domain, - AssemblyScope scope - ); - - private void ShutdownLocked() { if (m_assemblyLoadSubscribed) @@ -1236,10 +1375,12 @@ private void ShutdownLocked() } foreach (AssemblyModuleEntry module in m_modules.Values - .OrderByDescending(static value => value.domain == AssemblyDomain.InnoPlugin - ? 0 - : value.scope == AssemblyScope.Runtime ? 1 : 2)) - { + .OrderByDescending(static value => ( + value.domain == AssemblyDomain.InnoPlugin + ? 0 + : value.scope == AssemblyScope.Runtime ? 1 : 2 + )) + ) { BeginUnload(module); } m_modules.Clear(); @@ -1271,4 +1412,9 @@ private void EnsureRetirementSafe() } generations.EnsureRetirementSafe(); } + + private readonly record struct PlannedAssembly( + AssemblyDomain domain, + AssemblyScope scope + ); } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs index b517f8265..f9c718288 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs @@ -32,8 +32,9 @@ internal AssemblyModuleInfo CreateInfo() assemblies .Select(static assembly => assembly.GetName().Name ?? assembly.FullName ?? "Unknown") .OrderBy(static name => name, StringComparer.Ordinal) - .ToArray()) - { - upstreamModuleNames = upstreamModuleNames - }; + .ToArray() + ) + { + upstreamModuleNames = upstreamModuleNames + }; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs index 3b7e2e47c..59e3af5d2 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs @@ -1,19 +1,7 @@ -using System; using System.Collections.Generic; namespace Inno.Extensibility.Modules; -/// -/// Describes the catalog state of a published assembly module generation. -/// -public enum AssemblyModuleStatus -{ - /// - /// The module generation is visible to assembly catalog participants. - /// - Active -} - /// /// Provides non-owning diagnostic information about an active assembly module. /// @@ -58,5 +46,16 @@ IReadOnlyList assemblyNames /// /// Gets stable module dependencies used by this active generation. /// - public IReadOnlyList upstreamModuleNames { get; init; } = Array.Empty(); + public IReadOnlyList upstreamModuleNames { get; init; } = []; +} + +/// +/// Describes the catalog state of a published assembly module generation. +/// +public enum AssemblyModuleStatus +{ + /// + /// The module generation is visible to assembly catalog participants. + /// + Active } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs index 65ed8d473..7f6967f92 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs @@ -56,12 +56,16 @@ IReadOnlyList participantContexts /// /// Thrown when no participant supplied the requested context or the reload has completed. /// - public TContext GetContext() where TContext : class + public TContext GetContext() + where TContext : class { if (TryGetContext(out TContext? context)) + { return context!; + } throw new InvalidOperationException( - $"No assembly catalog participant supplied context '{typeof(TContext).FullName}'."); + $"No assembly catalog participant supplied context '{typeof(TContext).FullName}'." + ); } /// @@ -76,18 +80,22 @@ public TContext GetContext() where TContext : class /// /// when exactly one matching context exists. /// - public bool TryGetContext(out TContext? context) where TContext : class + public bool TryGetContext(out TContext? context) + where TContext : class { IReadOnlyList contexts = m_participantContexts ?? throw CreateCompletedException(); context = null; foreach (object candidate in contexts) { if (candidate is not TContext match) + { continue; + } if (context is not null) { throw new InvalidOperationException( - $"Multiple assembly catalog participants supplied context '{typeof(TContext).FullName}'."); + $"Multiple assembly catalog participants supplied context '{typeof(TContext).FullName}'." + ); } context = match; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs index da965da85..f09cf3e01 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs @@ -1,6 +1,5 @@ using System; using System.Linq; - using Inno.Core.Execution; using Inno.Extensibility.Reload; @@ -22,11 +21,12 @@ ReloadState state ) { m_owner = owner; m_state = state; - context = new AssemblyReloadContext( + this.context = new AssemblyReloadContext( state.previousCatalog, state.candidateCatalog, state.candidateModules.Select(static module => module.handle).ToArray(), - state.refresh.contexts); + state.refresh.contexts + ); } /// @@ -95,7 +95,9 @@ public void Rollback() { EnsureRetirementSafe(); if (m_disposed) + { return; + } try { m_owner.Rollback(m_state!); @@ -131,18 +133,8 @@ public void Dispose() private void EnsureRetirementSafe() { if (m_retirementFailure is not null) + { throw m_retirementFailure; + } } } - -internal sealed class ReloadState -{ - internal required AssemblyModuleEntry?[] previousModules { get; init; } - internal required AssemblyModuleEntry[] removedModules { get; init; } - internal required AssemblyModuleEntry[] candidateModules { get; init; } - internal required AssemblyCatalogSnapshot previousCatalog { get; init; } - internal required AssemblyCatalogSnapshot candidateCatalog { get; init; } - internal required AssemblyCatalogRefreshSet refresh { get; init; } - internal bool activated { get; set; } - internal bool finished { get; set; } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs new file mode 100644 index 000000000..e276c12fe --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs @@ -0,0 +1,13 @@ +namespace Inno.Extensibility.Modules; + +internal sealed class ReloadState +{ + internal required AssemblyModuleEntry?[] previousModules { get; init; } + internal required AssemblyModuleEntry[] removedModules { get; init; } + internal required AssemblyModuleEntry[] candidateModules { get; init; } + internal required AssemblyCatalogSnapshot previousCatalog { get; init; } + internal required AssemblyCatalogSnapshot candidateCatalog { get; init; } + internal required AssemblyCatalogRefreshSet refresh { get; init; } + internal bool activated { get; set; } + internal bool finished { get; set; } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs index e19f5e153..d1e376964 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs @@ -43,21 +43,27 @@ public AssemblyUnloadBarrier( ArgumentNullException.ThrowIfNull(probes); m_probes = probes.ToArray(); if (m_probes.Any(static probe => probe is null)) + { throw new ArgumentNullException(nameof(probes), "Unload probe collections cannot contain null values."); + } options ??= new AssemblyUnloadBarrierOptions(); if (options.collectionInterval < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(options), "The collection interval cannot be negative."); + } if (options.retentionTimeout <= TimeSpan.Zero && options.retentionTimeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(options), "The retention timeout must be positive or infinite."); + } m_collectionIntervalMilliseconds = checked((long)options.collectionInterval.TotalMilliseconds); m_retentionTimeoutMilliseconds = options.retentionTimeout == Timeout.InfiniteTimeSpan - ? long.MaxValue - : checked((long)options.retentionTimeout.TotalMilliseconds); + ? long.MaxValue + : checked((long)options.retentionTimeout.TotalMilliseconds); m_startedTimestamp = Environment.TickCount64; m_nextCollectionTimestamp = m_startedTimestamp; m_state = m_probes.All(static probe => probe.isCompleted) - ? AssemblyUnloadBarrierState.Completed - : AssemblyUnloadBarrierState.AwaitingCollection; + ? AssemblyUnloadBarrierState.Completed + : AssemblyUnloadBarrierState.AwaitingCollection; } /// @@ -68,7 +74,9 @@ public AssemblyUnloadBarrierState state get { lock (m_sync) + { return m_state; + } } } @@ -80,7 +88,9 @@ public int collectionAttempts get { lock (m_sync) + { return m_collectionAttempts; + } } } @@ -92,7 +102,9 @@ public AssemblyUnloadException? failure get { lock (m_sync) + { return m_failure; + } } } @@ -112,9 +124,13 @@ public bool Advance() lock (m_sync) { if (m_state == AssemblyUnloadBarrierState.Completed) + { return true; + } if (m_failure is not null) + { throw m_failure; + } now = Environment.TickCount64; collect = now >= m_nextCollectionTimestamp; if (collect) @@ -125,7 +141,9 @@ public bool Advance() } if (collect) + { ForceFullCollection(); + } lock (m_sync) { @@ -136,7 +154,9 @@ public bool Advance() } TimeSpan elapsed = TimeSpan.FromMilliseconds(Math.Max(0, now - m_startedTimestamp)); if (elapsed.TotalMilliseconds < m_retentionTimeoutMilliseconds) + { return false; + } string[] retained = m_probes .Where(static probe => !probe.isCompleted) .Select(static probe => probe.description) diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs index 197b5b982..b3d6f0930 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs @@ -9,12 +9,10 @@ public enum AssemblyUnloadBarrierState /// At least one retired collectible generation remains reachable. /// AwaitingCollection, - /// /// Every retired generation is unreachable and cleaned up. /// Completed, - /// /// The retention threshold was reached and the owning reload subsystem must stop accepting work. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs index 7489e85ae..5b093934b 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs @@ -31,12 +31,13 @@ public AssemblyUnloadException( IReadOnlyList retainedGenerations, TimeSpan elapsed, int collectionAttempts - ) - : base(CreateMessage(retainedGenerations, elapsed, collectionAttempts)) + ) : base(CreateMessage(retainedGenerations, elapsed, collectionAttempts)) { ArgumentNullException.ThrowIfNull(retainedGenerations); if (retainedGenerations.Count == 0) + { throw new ArgumentException("An unload failure requires at least one retained generation.", nameof(retainedGenerations)); + } this.retainedGenerations = retainedGenerations.ToArray(); this.elapsed = elapsed; this.collectionAttempts = collectionAttempts; @@ -64,11 +65,13 @@ int collectionAttempts ) { ArgumentNullException.ThrowIfNull(retainedGenerations); if (retainedGenerations.Count == 0) + { throw new ArgumentException("An unload failure requires at least one retained generation.", nameof(retainedGenerations)); + } return - $"Retired assembly generations remained reachable for {elapsed.TotalSeconds:F1} seconds across " + - $"{collectionAttempts} full garbage-collection attempts: {string.Join(", ", retainedGenerations)}. " + - "A Type, object, delegate, extension, task, subscription, thread, native callback, or other generation-bound " + - "reference is still retained. The reload subsystem is faulted and requires a host restart."; + $"Retired assembly generations remained reachable for {elapsed.TotalSeconds:F1} seconds across " + + $"{collectionAttempts} full garbage-collection attempts: {string.Join(", ", retainedGenerations)}. " + + "A Type, object, delegate, extension, task, subscription, thread, native callback, or other generation-bound " + + "reference is still retained. The reload subsystem is faulted and requires a host restart."; } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs index d58c68383..2c3c74178 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; - using Inno.Core.Execution; + namespace Inno.Extensibility.Reload; /// @@ -32,7 +32,9 @@ public GenerationState state get { lock (m_sync) + { return m_state; + } } } @@ -44,7 +46,9 @@ public Exception? failure get { lock (m_sync) + { return m_failure; + } } } @@ -63,11 +67,13 @@ public void Configure(AssemblyUnloadBarrierOptions options) _ = new AssemblyUnloadBarrier([], options); EnsureReady("configure unload verification"); lock (m_sync) + { m_options = new AssemblyUnloadBarrierOptions { collectionInterval = options.collectionInterval, retentionTimeout = options.retentionTimeout }; + } } /// @@ -83,15 +89,23 @@ public void EnsureReady(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); if (state == GenerationState.AwaitingCollection) + { _ = Advance(); + } lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: the generation owner is Faulted and must restart.", m_failure); + } if (m_state != GenerationState.Ready) + { throw new InvalidOperationException($"Cannot {operation}: generation state is {m_state}."); + } if (m_readers > 0) + { throw new InvalidOperationException($"Cannot {operation}: an owner operation holds a generation read lease."); + } } } @@ -111,11 +125,15 @@ public IDisposable AcquireRead(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); if (state == GenerationState.AwaitingCollection) + { _ = Advance(); + } lock (m_sync) { if (m_state != GenerationState.Ready || m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: generation state is {m_state}.", m_failure); + } m_readers++; return new ReadLease(this); } @@ -130,16 +148,16 @@ public IDisposable AcquireRead(string operation) /// /// A scope for the entire operation, or a borrowed scope inside publication on its own control thread. /// - /// - /// Published data remains readable while old contexts await collection. This scope does not authorize Play, - /// Build, Export or a new generation transaction; those owners must still use their strict admission boundary. - /// /// /// Another thread is publishing or the owner is Faulted. /// /// /// Retirement has failed without releasing its dependent owners. /// + /// + /// Published data remains readable while old contexts await collection. This scope does not authorize Play, + /// Build, Export or a new generation transaction; those owners must still use their strict admission boundary. + /// public IDisposable AcquireOperation(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); @@ -147,11 +165,15 @@ public IDisposable AcquireOperation(string operation) lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: the generation owner is Faulted.", m_failure); + } if (m_state == GenerationState.Transitioning) { if (m_publicationThread != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"Cannot {operation}: another thread is publishing a generation."); + } return new ReadLease(null); } m_readers++; @@ -182,10 +204,14 @@ out IDisposable? reservation lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: restart the Faulted generation owner.", m_failure); + } reservation = null; if (m_state != GenerationState.Ready || m_readers != 0) + { return false; + } m_state = GenerationState.Transitioning; m_publicationThread = Environment.CurrentManagedThreadId; reservation = new ChangeReservation(this); @@ -205,10 +231,14 @@ public void TrackRetirement(IAssemblyUnloadProbe probe) lock (m_sync) { if (probe.isCompleted || m_pending.Contains(probe)) + { return; + } m_pending.Add(probe); if (m_state == GenerationState.Ready) + { m_state = GenerationState.AwaitingCollection; + } } } @@ -246,12 +276,16 @@ IReadOnlyList changes ArgumentNullException.ThrowIfNull(changes); IGenerationChange[] snapshot = changes.ToArray(); if (snapshot.Any(static change => change is null)) + { throw new ArgumentException("Generation changes cannot contain null entries.", nameof(changes)); + } EnsureReady(operation); lock (m_sync) { if (m_state != GenerationState.Ready || m_readers != 0 || m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: generation admission changed while preparing the transaction."); + } m_state = GenerationState.Transitioning; m_publicationThread = Environment.CurrentManagedThreadId; } @@ -261,18 +295,26 @@ IReadOnlyList changes try { while (preparedCount < snapshot.Length) + { snapshot[preparedCount++].PrepareForActivation(); + } publication.Activate(); foreach (IGenerationChange change in snapshot) + { change.Apply(); + } committed = true; TProbe probe = publication.Complete(); TrackRetirement(probe); List cleanup = []; foreach (IGenerationChange change in snapshot) + { Attempt(change.Complete, cleanup); + } if (cleanup.Count > 0) + { throw new AggregateException($"Generation '{operation}' committed but retirement cleanup failed.", cleanup); + } return probe; } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -292,21 +334,32 @@ IReadOnlyList changes try { for (int index = preparedCount - 1; index >= 0; index--) + { Attempt(snapshot[index].RollbackStructure, rollback); + } Attempt(publication.Rollback, rollback); for (int index = preparedCount - 1; index >= 0; index--) + { Attempt(snapshot[index].RestorePreviousState, rollback); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { retirementBlocked = true; - var combined = new AggregateException($"Generation '{operation}' failed and rollback remains pending.", error, failure); + var combined = new AggregateException( + $"Generation '{operation}' failed and rollback remains pending.", + error, + failure + ); RetainFailedRetirement(combined, (publication, snapshot)); throw combined; } if (rollback.Count > 0) { - var failure = new AggregateException($"Generation '{operation}' failed and rollback was incomplete.", [error, .. rollback]); + var failure = new AggregateException( + $"Generation '{operation}' failed and rollback was incomplete.", + [error, .. rollback] + ); Fault(failure); throw failure; } @@ -316,12 +369,16 @@ IReadOnlyList changes finally { if (!retirementBlocked) + { Array.Clear(snapshot); + } lock (m_sync) { m_publicationThread = 0; if (m_state != GenerationState.Faulted) + { m_state = m_pending.Count == 0 ? GenerationState.Ready : GenerationState.AwaitingCollection; + } } } } @@ -344,9 +401,13 @@ public bool Advance() lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException("Generation retirement failed; restart the host.", m_failure); + } if (m_state == GenerationState.Transitioning || m_advancing) + { return false; + } if (m_pending.Count == 0) { m_state = GenerationState.Ready; @@ -367,7 +428,9 @@ public bool Advance() m_barrier = null; } if (m_pending.Count == 0) + { m_state = GenerationState.Ready; + } return m_pending.Count == 0; } } @@ -379,7 +442,9 @@ public bool Advance() finally { lock (m_sync) + { m_advancing = false; + } } } @@ -421,20 +486,34 @@ public void Fault(Exception exception) /// /// Rejects dependency destruction after a generation owner reported unfinished retirement. /// + /// + /// A failed generation still owns live work; its dependencies must remain owned until host restart. + /// /// /// Ordinary terminal cleanup failures do not prevent remaining cleanup. Unfinished retirement remains /// blocking even if an earlier ordinary error is the primary diagnostic failure. /// - /// - /// A failed generation still owns live work; its dependencies must remain owned until host restart. - /// public void EnsureRetirementSafe() { lock (m_sync) { if (m_retirementFailure is not null) + { throw m_retirementFailure; + } + } + } + + private void RetainFailedRetirement( + Exception failure, + object transaction + ) { + lock (m_sync) + { + m_retainedTransaction = transaction; } + Fault(failure); + GC.KeepAlive(m_retainedTransaction); } private static void Attempt( @@ -448,7 +527,12 @@ ICollection failures catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures.Count > 0) - throw new AggregateException("Generation retirement remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Generation retirement remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -457,16 +541,6 @@ ICollection failures } } - private void RetainFailedRetirement( - Exception failure, - object transaction - ) { - lock (m_sync) - m_retainedTransaction = transaction; - Fault(failure); - GC.KeepAlive(m_retainedTransaction); - } - private sealed class ChangeReservation(GenerationCoordinator owner) : IDisposable { private GenerationCoordinator? m_owner = owner; @@ -478,12 +552,16 @@ public void Dispose() { GenerationCoordinator? current = Interlocked.Exchange(ref m_owner, null); if (current is null) + { return; + } lock (current.m_sync) { current.m_publicationThread = 0; if (current.m_state != GenerationState.Faulted) + { current.m_state = current.m_pending.Count == 0 ? GenerationState.Ready : GenerationState.AwaitingCollection; + } } } } @@ -491,6 +569,7 @@ public void Dispose() private sealed class ReadLease(GenerationCoordinator? owner) : IDisposable { private GenerationCoordinator? m_owner = owner; + /// /// Releases this owner's registrations and resources exactly once. /// @@ -498,9 +577,13 @@ public void Dispose() { GenerationCoordinator? current = Interlocked.Exchange(ref m_owner, null); if (current is null) + { return; + } lock (current.m_sync) + { current.m_readers--; + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs index c37d855f3..8e08c55f9 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs @@ -9,18 +9,22 @@ public interface IGenerationChange /// Quiesces old instances while the old publication remains active. /// void PrepareForActivation(); + /// /// Applies captured state after candidate publication; partial changes must be rollback-safe. /// void Apply(); + /// /// Releases old instances after irreversible publication; cleanup failures fault the owner. /// void Complete(); + /// /// Removes provisional structures before restoring the old publication. /// void RollbackStructure(); + /// /// Restores old values and lifecycle after the previous publication has been restored. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs index b2837226d..35ef43eaf 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs @@ -6,16 +6,19 @@ namespace Inno.Extensibility.Reload; /// /// The non-owning probe used to verify retired collectible contexts. /// -public interface IGenerationPublication where TProbe : IAssemblyUnloadProbe +public interface IGenerationPublication + where TProbe : IAssemblyUnloadProbe { /// /// Makes the fully prepared candidate provisionally visible at an owner-thread safe point. /// void Activate(); + /// /// Restores the previous publication and retires discarded candidates. /// void Rollback(); + /// /// Commits publication after all dependent changes apply successfully. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs new file mode 100644 index 000000000..1d85fbca9 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs @@ -0,0 +1,15 @@ +namespace Inno.Extensibility.Types; + +internal interface ITypeRegistry +{ + /// + /// Builds and validates candidate state without changing the active generation. + /// + /// + /// The active type catalog generation used for extension resolution. + /// + /// + /// The validated itype registry transaction that represents the completed operation. + /// + ITypeRegistryTransaction Prepare(TypeCacheSnapshot types); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs new file mode 100644 index 000000000..207b02866 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs @@ -0,0 +1,19 @@ +namespace Inno.Extensibility.Types; + +internal interface ITypeRegistryTransaction +{ + /// + /// Makes the prepared value active at the owning subsystem's safety point. + /// + void Activate(); + + /// + /// Finalizes candidate activation and releases temporary transaction state. + /// + void Complete(); + + /// + /// Restores the state captured before the current transaction began. + /// + void Rollback(); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs b/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs index 623509ddf..1b36024e4 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs @@ -1,9 +1,6 @@ using Inno.Extensibility.Types; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Reflection", - "Inno.Extensibility.Types", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Reflection", "Inno.Extensibility.Types", ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(StableTypeIdAttribute), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(StableTypeIDAttribute), ScriptingApiScope.Runtime)] diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIdAttribute.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIDAttribute.cs similarity index 89% rename from src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIdAttribute.cs rename to src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIDAttribute.cs index 82a94ae72..f0a2f9afe 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIdAttribute.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/Attributes/StableTypeIDAttribute.cs @@ -9,7 +9,7 @@ namespace Inno.Extensibility.Types; /// The stable identity used to locate the requested value. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum, Inherited = false)] -public sealed class StableTypeIdAttribute(string id) : Attribute +public sealed class StableTypeIDAttribute(string id) : Attribute { /// /// Stable type id as Guid string. diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs index 882344d7c..8ea32e8f8 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs index 2743f2777..04b75ba3f 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs @@ -20,8 +20,7 @@ public sealed class TypeCacheBuildException : Exception public TypeCacheBuildException( string message, IReadOnlyList loaderExceptions - ) - : base(message, loaderExceptions.Count > 0 ? loaderExceptions[0] : null) + ) : base(message, loaderExceptions.Count > 0 ? loaderExceptions[0] : null) { this.loaderExceptions = loaderExceptions; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs index 99a1d1411..af5c7d04a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs @@ -40,7 +40,9 @@ TypeCacheSnapshot candidate public bool IsRetired(TypeRef typeRef) { if (!previous.TryResolve(typeRef, out Type? previousType)) + { return false; + } return !candidate.TryResolve(typeRef, out Type? replacement) || replacement != previousType; } @@ -60,10 +62,10 @@ public bool TryResolveReplacement( TypeRef previousType, out TypeRef replacement ) { - if (!previous.TryResolve(previousType, out Type? previousRuntimeType) || - !candidate.TryResolve(previousType, out Type? replacementType) || - replacementType == previousRuntimeType) - { + if (!previous.TryResolve(previousType, out Type? previousRuntimeType) + || !candidate.TryResolve(previousType, out Type? replacementType) + || replacementType == previousRuntimeType + ) { replacement = default; return false; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs index 490ca681a..01ee6250a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -17,8 +16,6 @@ namespace Inno.Extensibility.Types; /// public sealed class TypeCacheSnapshot { - internal static TypeCacheSnapshot empty { get; } = CreateEmpty(); - private readonly ITypeCatalogSource? m_source; private readonly Dictionary m_metadata; private readonly Type[] m_types; @@ -88,12 +85,16 @@ public IReadOnlyList GetTypesImplementing() /// /// An immutable snapshot of the values selected by the operation. /// - public IReadOnlyList GetTypesWithAttribute() where TAttribute : Attribute - => m_queryRegistry.GetTypesWithAttribute(m_identityRegistry); + public IReadOnlyList GetTypesWithAttribute() + where TAttribute : Attribute + => m_queryRegistry.GetTypesWithAttribute(m_identityRegistry); /// /// Gets the reference for a CLR type in this snapshot. /// + /// + /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// The logical and generation-local identity of . /// @@ -103,9 +104,6 @@ public IReadOnlyList GetTypesWithAttribute() where TAttribu /// /// Thrown when the type does not belong to this snapshot. /// - /// - /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. - /// public TypeRef GetTypeRef(Type type) => m_identityRegistry.GetTypeRef(type); /// @@ -154,7 +152,9 @@ public object CreateInstance(Type type) ArgumentNullException.ThrowIfNull(type); Type declaration = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; if (!m_identityRegistry.TryGetTypeRef(declaration, out _)) + { throw new InvalidOperationException($"Type '{type}' does not belong to this generation."); + } return m_source!.CreateInstance(type); } @@ -183,7 +183,9 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!m_identityRegistry.TryGetTypeRef(definition, out _)) + { throw new InvalidOperationException($"Type '{definition}' does not belong to this generation."); + } return m_source!.ConstructGenericType(definition, arguments); } @@ -220,9 +222,12 @@ IReadOnlyList arguments { TypeCatalogMetadata metadata = GetMetadata(type); return (inherit ? metadata.inheritedAttributes : metadata.declaredAttributes) - .OfType().SingleOrDefault(); + .OfType() + .SingleOrDefault(); } + internal static TypeCacheSnapshot empty { get; } = CreateEmpty(); + internal IReadOnlyList runtimeTypes => m_types; internal bool TryResolve( @@ -238,13 +243,15 @@ long version ) { ArgumentNullException.ThrowIfNull(assemblies); - var discoveredTypes = new List(); + List discoveredTypes = []; var typesByAssembly = new Dictionary(ReferenceEqualityComparer.Instance); - var loaderExceptions = new List(); + List loaderExceptions = []; foreach (Assembly assembly in assemblies.Where(static value => !value.IsDynamic)) { if (typesByAssembly.ContainsKey(assembly)) + { continue; + } if (previous is not null && previous.m_typesByAssembly.TryGetValue(assembly, out Type[]? cachedTypes)) { typesByAssembly.Add(assembly, cachedTypes); @@ -275,7 +282,8 @@ long version { throw new TypeCacheBuildException( $"Type discovery failed with {loaderExceptions.Count} loader error(s).", - loaderExceptions); + loaderExceptions + ); } Type[] types = discoveredTypes @@ -284,9 +292,14 @@ long version .ThenBy(static type => type.FullName, StringComparer.Ordinal) .ToArray(); var identities = new TypeIdentityRegistry(); - Dictionary metadata = types.ToDictionary(static type => type, - type => previous is not null && previous.m_metadata.TryGetValue(type, out TypeCatalogMetadata? existing) - ? existing : source.GetMetadata(type)); + Dictionary metadata = types.ToDictionary( + static type => type, + type => ( + previous is not null && previous.m_metadata.TryGetValue(type, out TypeCatalogMetadata? existing) + ? existing + : source.GetMetadata(type) + ) + ); identities.Rebuild(metadata.Values, previous?.m_identityRegistry); var queries = new TypeQueryRegistry(); queries.Rebuild(metadata.Values, identities); @@ -299,6 +312,6 @@ private static TypeCacheSnapshot CreateEmpty() identities.Rebuild([], previous: null); var queries = new TypeQueryRegistry(); queries.Rebuild([], identities); - return new TypeCacheSnapshot(0, null, [], [], new Dictionary(), identities, queries); + return new TypeCacheSnapshot(0, null, [], [], [], identities, queries); } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs index d5a381386..0db94e66b 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading; - using Inno.Core.Execution; using Inno.Extensibility.Modules; @@ -31,15 +30,15 @@ public sealed class TypeCatalog : IDisposable /// /// The module host that owns the assembly generations visible to this catalog. /// + /// + /// The metadata provider selected by the composition root for every contributed assembly. + /// /// /// Thrown when is null. /// /// /// Thrown when has already been disposed. /// - /// - /// The metadata provider selected by the composition root for every contributed assembly. - /// public TypeCatalog( ModuleHost modules, ITypeCatalogSource source @@ -47,7 +46,9 @@ ITypeCatalogSource source ArgumentNullException.ThrowIfNull(modules); ArgumentNullException.ThrowIfNull(source); if (!modules.isInitialized) + { throw new InvalidOperationException("The module host must be active before creating a type catalog."); + } m_modules = modules; m_source = source; m_participant = new TypeCacheCatalogParticipant(this); @@ -59,6 +60,22 @@ ITypeCatalogSource source /// public bool isInitialized => !m_disposed && m_modules.isInitialized; + /// + /// Gets the current immutable type snapshot after applying pending host assembly changes. + /// + public TypeCacheSnapshot current + { + get + { + EnsureInitialized(); + m_modules.Refresh(); + lock (m_sync) + { + return m_current; + } + } + } + /// /// Defers automatic assembly publication until a synchronous typed operation releases its current owners. /// @@ -80,20 +97,6 @@ public IDisposable AcquireOperation(string operation) return m_modules.generations.AcquireOperation(operation); } - /// - /// Gets the current immutable type snapshot after applying pending host assembly changes. - /// - public TypeCacheSnapshot current - { - get - { - EnsureInitialized(); - m_modules.Refresh(); - lock (m_sync) - return m_current; - } - } - /// /// Rebuilds the assembly catalog, type snapshot, and every registered type registry. /// @@ -118,7 +121,9 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_disposed = true; registries = m_registries.Prepare(TypeCacheSnapshot.empty); m_current = TypeCacheSnapshot.empty; @@ -167,12 +172,16 @@ public void Dispose() /// /// The matching concrete types in stable catalog order. /// - public IReadOnlyList GetTypesWithAttribute() where TAttribute : Attribute - => current.GetTypesWithAttribute(); + public IReadOnlyList GetTypesWithAttribute() + where TAttribute : Attribute + => current.GetTypesWithAttribute(); /// /// Gets the reference for an active CLR type. /// + /// + /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// Its logical and generation-local identity. /// @@ -182,9 +191,6 @@ public IReadOnlyList GetTypesWithAttribute() where TAttribu /// /// Thrown when the type does not belong to the active catalog. /// - /// - /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. - /// public TypeRef GetTypeRef(Type type) => current.GetTypeRef(type); /// @@ -242,12 +248,15 @@ out Type? type /// public Type Resolve(TypeRef typeRef) { - if (typeRef.stableId != Guid.Empty && TryResolve(typeRef, out Type? type)) + if (typeRef.stableID != Guid.Empty && TryResolve(typeRef, out Type? type)) + { return type!; + } throw new InvalidOperationException( - typeRef.stableId == Guid.Empty - ? "An empty type reference cannot be resolved." - : $"Type reference '{typeRef.stableId:D}' is not available in the active type cache."); + typeRef.stableID == Guid.Empty + ? "An empty type reference cannot be resolved." + : $"Type reference '{typeRef.stableID:D}' is not available in the active type cache." + ); } internal TypeRegistryRegistration Register(ITypeRegistry registry) @@ -271,7 +280,9 @@ internal void EnsureRetirementSafe() private void EnsureInitialized() { if (!isInitialized) + { throw new InvalidOperationException("TypeCatalog is not initialized."); + } } private void RetainFailedRetirement( @@ -299,12 +310,15 @@ public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) owner.EnsureRetirementSafe(); TypeCacheSnapshot previous; lock (owner.m_sync) + { previous = owner.m_current; + } TypeCacheSnapshot candidate = TypeCacheSnapshot.Build( catalog.assemblies, owner.m_source, previous, - Interlocked.Increment(ref owner.m_nextVersion)); + Interlocked.Increment(ref owner.m_nextVersion) + ); TypeRegistryRefreshSet registries = owner.m_registries.Prepare(candidate); return new TypeCacheCatalogTransaction(owner, previous, candidate, registries); } @@ -334,7 +348,9 @@ public void Activate() owner.EnsureRetirementSafe(); EnsureNotFinished(); lock (owner.m_sync) + { owner.m_current = candidate; + } try { registries.Activate(); @@ -348,7 +364,9 @@ public void Activate() catch { lock (owner.m_sync) + { owner.m_current = previous; + } registries.Rollback(); m_finished = true; m_context.Release(); @@ -364,7 +382,9 @@ public void Complete() owner.EnsureRetirementSafe(); EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Type cache transaction has not been activated."); + } m_finished = true; try { @@ -378,7 +398,9 @@ public void Complete() finally { if (owner.m_retirementFailure is null) + { m_context.Release(); + } } } @@ -389,11 +411,15 @@ public void Rollback() { owner.EnsureRetirementSafe(); if (m_finished) + { return; + } if (m_activated) { lock (owner.m_sync) + { owner.m_current = previous; + } } m_finished = true; try @@ -408,14 +434,18 @@ public void Rollback() finally { if (owner.m_retirementFailure is null) + { m_context.Release(); + } } } private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Type cache transaction is already finished."); + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs index 468ac089a..609b8b5eb 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -15,10 +14,12 @@ namespace Inno.Extensibility.Types; /// internal sealed class TypeIdentityRegistry { - // RFC 4122 DNS namespace UUID, used to build deterministic UUIDv5 for auto stable ids. - private static readonly Guid C_STABLE_NAMESPACE_GUID = Guid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); private const string C_GENERATED_STABLE_TYPE_METADATA_KEY = "Inno.StableTypeId"; - private static int S_NEXT_RUNTIME_TYPE_ID; + + // RFC 4122 DNS namespace UUID, used to build deterministic UUIDv5 for auto stable ids. + private static readonly Guid STABLE_NAMESPACE_GUID = Guid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + + private static int s_nextRuntimeTypeID; private readonly Lock m_sync = new(); private Dictionary m_stableByType = []; @@ -75,47 +76,51 @@ public void Rebuild( var stableByType = new Dictionary(); var typeByStable = new Dictionary(); - IReadOnlyDictionary> mappings = - BuildGeneratedMappings(sourceTypes); + IReadOnlyDictionary> mappings = BuildGeneratedMappings( + sourceTypes + ); foreach (Type type in sourceTypes) { - StableTypeIdAttribute? attr = metadata[type].declaredAttributes.OfType().SingleOrDefault(); + StableTypeIDAttribute? attr = metadata[type].declaredAttributes.OfType().SingleOrDefault(); GeneratedStableTypeMapping? mapping = null; - Guid stableId; + Guid stableID; if (attr is not null) { - if (!Guid.TryParse(attr.id, out stableId)) + if (!Guid.TryParse(attr.id, out stableID)) { throw new InvalidOperationException( - $"Type '{type.FullName}' has invalid StableTypeId '{attr.id}'."); + $"Type '{type.FullName}' has invalid StableTypeID '{attr.id}'." + ); } } - else if (mappings.TryGetValue(type.Assembly, out IReadOnlyDictionary? assemblyMappings) && - assemblyMappings.TryGetValue(type.FullName ?? type.Name, out mapping)) - { - if (!Guid.TryParse(mapping.id, out stableId)) + else if (mappings.TryGetValue(type.Assembly, out IReadOnlyDictionary? assemblyMappings) + && assemblyMappings.TryGetValue(type.FullName ?? type.Name, out mapping) + ) { + if (!Guid.TryParse(mapping.id, out stableID)) { throw new InvalidOperationException( - $"Type '{type.FullName}' has invalid generated StableTypeId '{mapping.id}'."); + $"Type '{type.FullName}' has invalid generated StableTypeID '{mapping.id}'." + ); } } else { - stableId = CreateDeterministicStableId(type); + stableID = CreateDeterministicStableID(type); } - if (!typeByStable.TryAdd(stableId, type)) + if (!typeByStable.TryAdd(stableID, type)) { - Type existing = typeByStable[stableId]; + Type existing = typeByStable[stableID]; throw new InvalidOperationException( - $"StableTypeId '{stableId}' conflicts between '{existing.FullName}' and '{type.FullName}'."); + $"StableTypeID '{stableID}' conflicts between '{existing.FullName}' and '{type.FullName}'." + ); } - stableByType[type] = stableId; + stableByType[type] = stableID; } - var orderedTypes = sourceTypes + Type[] orderedTypes = sourceTypes .OrderBy(t => t.Assembly.GetName().Name, StringComparer.Ordinal) .ThenBy(t => t.FullName, StringComparer.Ordinal) .ToArray(); @@ -124,7 +129,9 @@ public void Rebuild( if (previous is not null) { lock (previous.m_sync) + { previousRuntimeByType = new Dictionary(previous.m_runtimeByType); + } } var runtimeByType = new Dictionary(orderedTypes.Length); @@ -132,12 +139,14 @@ public void Rebuild( for (int i = 0; i < orderedTypes.Length; i++) { Type type = orderedTypes[i]; - int runtimeId; - if (!previousRuntimeByType.TryGetValue(type, out runtimeId)) - runtimeId = AllocateRuntimeTypeId(); + int runtimeID; + if (!previousRuntimeByType.TryGetValue(type, out runtimeID)) + { + runtimeID = AllocateRuntimeTypeID(); + } - runtimeByType[type] = runtimeId; - typeByRuntime[runtimeId] = type; + runtimeByType[type] = runtimeID; + typeByRuntime[runtimeID] = type; } lock (m_sync) @@ -156,21 +165,21 @@ public void Rebuild( /// /// The type consumed by try get stable type id; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The stable type id consumed by try get stable type id; ownership remains with the caller unless explicitly stated otherwise. /// /// /// when the requested condition is satisfied; otherwise, . /// - public bool TryGetStableTypeId( + public bool TryGetStableTypeID( Type type, - out Guid stableTypeId + out Guid stableTypeID ) { ArgumentNullException.ThrowIfNull(type); lock (m_sync) { - return m_stableByType.TryGetValue(type, out stableTypeId); + return m_stableByType.TryGetValue(type, out stableTypeID); } } @@ -194,10 +203,10 @@ out TypeRef typeRef lock (m_sync) { - if (m_stableByType.TryGetValue(type, out Guid stableId) && - m_runtimeByType.TryGetValue(type, out int runtimeId)) - { - typeRef = new TypeRef(stableId, runtimeId); + if (m_stableByType.TryGetValue(type, out Guid stableID) + && m_runtimeByType.TryGetValue(type, out int runtimeID) + ) { + typeRef = new TypeRef(stableID, runtimeID); return true; } } @@ -218,14 +227,16 @@ out TypeRef typeRef public TypeRef GetTypeRef(Type type) { if (TryGetTypeRef(type, out TypeRef typeRef)) + { return typeRef; + } throw new InvalidOperationException($"Type '{type.FullName}' does not belong to this type-cache snapshot."); } /// /// Attempts to resolve type without changing state when the operation cannot complete. /// - /// + /// /// The stable type id consumed by try resolve type; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -235,12 +246,12 @@ public TypeRef GetTypeRef(Type type) /// when the requested condition is satisfied; otherwise, . /// public bool TryResolveType( - Guid stableTypeId, + Guid stableTypeID, out Type? type ) { lock (m_sync) { - if (m_typeByStable.TryGetValue(stableTypeId, out Type? resolved)) + if (m_typeByStable.TryGetValue(stableTypeID, out Type? resolved)) { type = resolved; return true; @@ -251,27 +262,69 @@ out Type? type return false; } + /// + /// Attempts to resolve type without changing state when the operation cannot complete. + /// + /// + /// The type ref consumed by try resolve type; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The type consumed by try resolve type; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + public bool TryResolveType( + TypeRef typeRef, + out Type? type + ) { + lock (m_sync) + { + if (typeRef.stableID == Guid.Empty) + { + type = null; + return false; + } + if (typeRef.runtimeID > 0 + && m_typeByRuntime.TryGetValue(typeRef.runtimeID, out Type? runtimeType) + && m_stableByType.TryGetValue(runtimeType, out Guid runtimeStableID) + && runtimeStableID == typeRef.stableID + ) { + type = runtimeType; + return true; + } + if (m_typeByStable.TryGetValue(typeRef.stableID, out Type? stableType)) + { + type = stableType; + return true; + } + } + + type = null; + return false; + } + /// /// Attempts to get runtime type id without changing state when the operation cannot complete. /// /// /// The type consumed by try get runtime type id; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The runtime type id consumed by try get runtime type id; ownership remains with the caller unless explicitly stated otherwise. /// /// /// when the requested condition is satisfied; otherwise, . /// - public bool TryGetRuntimeTypeId( + public bool TryGetRuntimeTypeID( Type type, - out int runtimeTypeId + out int runtimeTypeID ) { ArgumentNullException.ThrowIfNull(type); lock (m_sync) { - return m_runtimeByType.TryGetValue(type, out runtimeTypeId); + return m_runtimeByType.TryGetValue(type, out runtimeTypeID); } } @@ -284,7 +337,7 @@ out int runtimeTypeId /// /// The scalar result calculated from the supplied inputs. /// - public int GetOrAddRuntimeTypeId(Type type) + public int GetOrAddRuntimeTypeID(Type type) { ArgumentNullException.ThrowIfNull(type); @@ -295,17 +348,17 @@ public int GetOrAddRuntimeTypeId(Type type) return existing; } - int runtimeId = AllocateRuntimeTypeId(); - m_runtimeByType[type] = runtimeId; - m_typeByRuntime[runtimeId] = type; - return runtimeId; + int runtimeID = AllocateRuntimeTypeID(); + m_runtimeByType[type] = runtimeID; + m_typeByRuntime[runtimeID] = type; + return runtimeID; } } /// /// Attempts to resolve runtime type without changing state when the operation cannot complete. /// - /// + /// /// The runtime type id consumed by try resolve runtime type; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -315,12 +368,12 @@ public int GetOrAddRuntimeTypeId(Type type) /// when the requested condition is satisfied; otherwise, . /// public bool TryResolveRuntimeType( - int runtimeTypeId, + int runtimeTypeID, out Type? type ) { lock (m_sync) { - if (m_typeByRuntime.TryGetValue(runtimeTypeId, out Type? resolved)) + if (m_typeByRuntime.TryGetValue(runtimeTypeID, out Type? resolved)) { type = resolved; return true; @@ -331,56 +384,6 @@ out Type? type return false; } - /// - /// Attempts to resolve type without changing state when the operation cannot complete. - /// - /// - /// The type ref consumed by try resolve type; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The type consumed by try resolve type; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - public bool TryResolveType( - TypeRef typeRef, - out Type? type - ) { - lock (m_sync) - { - if (typeRef.stableId == Guid.Empty) - { - type = null; - return false; - } - if (typeRef.runtimeId > 0 && - m_typeByRuntime.TryGetValue(typeRef.runtimeId, out Type? runtimeType) && - m_stableByType.TryGetValue(runtimeType, out Guid runtimeStableId) && - runtimeStableId == typeRef.stableId) - { - type = runtimeType; - return true; - } - if (m_typeByStable.TryGetValue(typeRef.stableId, out Type? stableType)) - { - type = stableType; - return true; - } - } - - type = null; - return false; - } - - private static int AllocateRuntimeTypeId() - { - int runtimeId = Interlocked.Increment(ref S_NEXT_RUNTIME_TYPE_ID); - if (runtimeId <= 0) - throw new InvalidOperationException("The process-wide runtime type identity space is exhausted."); - return runtimeId; - } - /// /// Retrieves the requested stable type map snapshot value from current authoritative state. /// @@ -392,10 +395,10 @@ public IReadOnlyDictionary GetStableTypeMapSnapshot() lock (m_sync) { var snapshot = new SortedDictionary(StringComparer.Ordinal); - foreach ((Type type, Guid stableId) in m_stableByType) + foreach ((Type type, Guid stableID) in m_stableByType) { string typeKey = GetTypeLockKey(type); - snapshot[typeKey] = stableId; + snapshot[typeKey] = stableID; } return snapshot; @@ -418,10 +421,20 @@ public static string GetTypeLockKey(Type type) return $"{assemblyName}:{typeName}"; } - private static Guid CreateDeterministicStableId(Type type) + private static int AllocateRuntimeTypeID() + { + int runtimeID = Interlocked.Increment(ref s_nextRuntimeTypeID); + if (runtimeID <= 0) + { + throw new InvalidOperationException("The process-wide runtime type identity space is exhausted."); + } + return runtimeID; + } + + private static Guid CreateDeterministicStableID(Type type) { string key = GetTypeLockKey(type); - return CreateGuidV5(C_STABLE_NAMESPACE_GUID, key); + return CreateGuidV5(STABLE_NAMESPACE_GUID, key); } private static IReadOnlyDictionary> @@ -435,32 +448,38 @@ private static IReadOnlyDictionary string.Equals( attribute.Key, C_GENERATED_STABLE_TYPE_METADATA_KEY, - StringComparison.Ordinal)) + StringComparison.Ordinal + )) .ToArray(); if (attributes.Length == 0) + { continue; + } - var availableTypes = group.ToDictionary( - static type => type.FullName ?? type.Name, - StringComparer.Ordinal); + Dictionary availableTypes = group.ToDictionary(static type => type.FullName ?? type.Name, StringComparer.Ordinal); var mappings = new Dictionary(StringComparer.Ordinal); foreach (AssemblyMetadataAttribute attribute in attributes) { GeneratedStableTypeMapping mapping = ParseGeneratedMapping( group.Key.GetName().Name ?? string.Empty, - attribute.Value); + attribute.Value + ); if (string.IsNullOrWhiteSpace(mapping.typeName)) - throw new InvalidOperationException("A generated StableTypeId mapping requires a type name."); + { + throw new InvalidOperationException("A generated StableTypeID mapping requires a type name."); + } if (!availableTypes.ContainsKey(mapping.typeName)) { throw new InvalidOperationException( - $"Generated StableTypeId mapping refers to missing type '{mapping.typeName}' " + - $"in assembly '{group.Key.GetName().Name}'."); + $"Generated StableTypeID mapping refers to missing type '{mapping.typeName}' " + + $"in assembly '{group.Key.GetName().Name}'." + ); } if (!mappings.TryAdd(mapping.typeName, mapping)) { throw new InvalidOperationException( - $"Type '{mapping.typeName}' has more than one generated StableTypeId mapping."); + $"Type '{mapping.typeName}' has more than one generated StableTypeID mapping." + ); } } result.Add(group.Key, mappings); @@ -476,20 +495,21 @@ private static GeneratedStableTypeMapping ParseGeneratedMapping( if (parts.Length != 2) { throw new InvalidOperationException( - $"Assembly '{assemblyName}' has invalid generated StableTypeId metadata '{value}'."); + $"Assembly '{assemblyName}' has invalid generated StableTypeID metadata '{value}'." + ); } return new GeneratedStableTypeMapping(parts[1], parts[0]); } private static Guid CreateGuidV5( - Guid namespaceId, + Guid namespaceID, string name ) { - byte[] ns = namespaceId.ToByteArray(); + byte[] ns = namespaceID.ToByteArray(); SwapGuidByteOrder(ns); byte[] nameBytes = Encoding.UTF8.GetBytes(name); - byte[] data = new byte[ns.Length + nameBytes.Length]; + var data = new byte[ns.Length + nameBytes.Length]; Buffer.BlockCopy(ns, 0, data, 0, ns.Length); Buffer.BlockCopy(nameBytes, 0, data, ns.Length, nameBytes.Length); diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs index 8419d474b..8c04b9b9d 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -77,12 +76,10 @@ TypeIdentityRegistry typeIdentityRegistry /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentityRegistry) - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(T), out int keyId) && - m_subclassCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + => typeIdentityRegistry.TryGetRuntimeTypeID(typeof(T), out int keyID) + && m_subclassCache.TryGetValue(keyID, out IReadOnlyList? set) + ? set + : []; /// /// Retrieves the requested types implementing value from current authoritative state. @@ -97,12 +94,10 @@ public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentity /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetTypesImplementing(TypeIdentityRegistry typeIdentityRegistry) - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TInterface), out int keyId) && - m_interfaceCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + => typeIdentityRegistry.TryGetRuntimeTypeID(typeof(TInterface), out int keyID) + && m_interfaceCache.TryGetValue(keyID, out IReadOnlyList? set) + ? set + : []; /// /// Retrieves the requested types with attribute value from current authoritative state. @@ -117,13 +112,10 @@ public IReadOnlyList GetTypesImplementing(TypeIdentityRegis /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetTypesWithAttribute(TypeIdentityRegistry typeIdentityRegistry) - where TAttr : Attribute - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TAttr), out int keyId) && - m_attributeCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + where TAttr : Attribute => typeIdentityRegistry.TryGetRuntimeTypeID(typeof(TAttr), out int keyID) + && m_attributeCache.TryGetValue(keyID, out IReadOnlyList? set) + ? set + : []; private static void AddToIndex( Dictionary> index, @@ -131,11 +123,11 @@ private static void AddToIndex( Type valueType, TypeIdentityRegistry typeIdentityRegistry ) { - int keyId = typeIdentityRegistry.GetOrAddRuntimeTypeId(keyType); - if (!index.TryGetValue(keyId, out HashSet? set)) + int keyID = typeIdentityRegistry.GetOrAddRuntimeTypeID(keyType); + if (!index.TryGetValue(keyID, out HashSet? set)) { - set = new HashSet(); - index[keyId] = set; + set = []; + index[keyID] = set; } set.Add(valueType); @@ -148,9 +140,7 @@ TypeIdentityRegistry typeIdentityRegistry var frozen = new Dictionary>(index.Count); foreach ((int key, HashSet value) in index) { - frozen[key] = Array.AsReadOnly(value - .Select(typeIdentityRegistry.GetTypeRef) - .ToArray()); + frozen[key] = Array.AsReadOnly(value.Select(typeIdentityRegistry.GetTypeRef).ToArray()); } return frozen; diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs index 1c5fefcff..fe7c2f339 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs @@ -6,7 +6,7 @@ namespace Inno.Extensibility.Types; /// Identifies one logical runtime type without retaining its assembly or load context. /// /// -/// Equality and persistence use . The is only a +/// Equality and persistence use . The is only a /// generation-local resolution hint and can become stale after an assembly reload. /// public readonly struct TypeRef : IEquatable @@ -14,26 +14,24 @@ namespace Inno.Extensibility.Types; /// /// Creates an unresolved type reference from its persistent identity. /// - /// + /// /// The persistent type identity, or an empty value for an invalid reference. /// - public TypeRef(Guid stableId) - : this(stableId, runtimeId: 0) - { - } + public TypeRef(Guid stableID) + : this(stableID, runtimeID: 0) {} internal TypeRef( - Guid stableId, - int runtimeId + Guid stableID, + int runtimeID ) { - this.stableId = stableId; - this.runtimeId = runtimeId; + this.stableID = stableID; + this.runtimeID = runtimeID; } /// /// Gets the persistent identity used across assembly generations and process launches. /// - public Guid stableId { get; } + public Guid stableID { get; } /// /// Gets the generation-local lookup hint captured when this value was created. @@ -41,7 +39,7 @@ int runtimeId /// /// This value must not be persisted or used as logical type identity. /// - public int runtimeId { get; } + public int runtimeID { get; } /// /// Determines whether one type catalog currently resolves this reference. @@ -58,7 +56,7 @@ int runtimeId public bool IsValid(TypeCatalog catalog) { ArgumentNullException.ThrowIfNull(catalog); - return stableId != Guid.Empty && catalog.TryResolve(this, out _); + return stableID != Guid.Empty && catalog.TryResolve(this, out _); } /// @@ -100,8 +98,10 @@ public Type Resolve(TypeCatalog catalog) public Type Resolve(TypeCacheSnapshot snapshot) { ArgumentNullException.ThrowIfNull(snapshot); - if (stableId != Guid.Empty && snapshot.TryResolve(this, out Type? type)) + if (stableID != Guid.Empty && snapshot.TryResolve(this, out Type? type)) + { return type!; + } throw CreateResolutionException(snapshot.version); } @@ -114,17 +114,17 @@ public Type Resolve(TypeCacheSnapshot snapshot) /// /// when both values represent the same logical state; otherwise, . /// - public bool Equals(TypeRef other) => stableId == other.stableId; + public bool Equals(TypeRef other) => stableID == other.stableID; /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is TypeRef other && Equals(other); /// @@ -133,7 +133,7 @@ public Type Resolve(TypeCacheSnapshot snapshot) /// /// A hash code consistent with the implemented equality contract. /// - public override int GetHashCode() => stableId.GetHashCode(); + public override int GetHashCode() => stableID.GetHashCode(); /// /// Formats this value as a human-readable representation. @@ -141,7 +141,7 @@ public Type Resolve(TypeCacheSnapshot snapshot) /// /// The human-readable representation of this value. /// - public override string ToString() => stableId == Guid.Empty ? "" : stableId.ToString("D"); + public override string ToString() => stableID == Guid.Empty ? "" : stableID.ToString("D"); /// /// Determines whether two references identify the same logical type. @@ -180,11 +180,12 @@ TypeRef right private InvalidOperationException CreateResolutionException(long? snapshotVersion = null) { string generation = snapshotVersion is long version - ? $" in type-cache snapshot {version}" - : string.Empty; + ? $" in type-cache snapshot {version}" + : string.Empty; return new InvalidOperationException( - stableId == Guid.Empty - ? "An empty type reference cannot be resolved." - : $"Type reference '{stableId:D}' is not available{generation}."); + stableID == Guid.Empty + ? "An empty type reference cannot be resolved." + : $"Type reference '{stableID:D}' is not available{generation}." + ); } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs index 6c30faaf1..8c1d7d2ef 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; - using Inno.Core.Execution; namespace Inno.Extensibility.Types; @@ -20,14 +19,13 @@ public abstract class TypeRegistry : IDisposable private readonly TypeCatalog m_types; private readonly RegistryAdapter m_registryAdapter; private readonly TypeRegistryRegistration m_registration; - + private readonly TimeSpan m_retirementTimeout; private TSnapshot? m_current; private long m_typeCacheVersion = -1; private bool m_activationInProgress; private bool m_disposed; private List? m_candidateResources; private TypeCacheSnapshot? m_candidateTypes; - private readonly TimeSpan m_retirementTimeout; private Exception? m_retirementFailure; private object? m_retainedRetirement; @@ -53,7 +51,9 @@ protected TypeRegistry( ArgumentNullException.ThrowIfNull(types); m_retirementTimeout = retirementTimeout ?? TimeSpan.FromSeconds(30); if (m_retirementTimeout <= TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(retirementTimeout)); + } m_types = types; m_registryAdapter = new RegistryAdapter(this); m_registration = types.Register(m_registryAdapter); @@ -67,7 +67,9 @@ public bool isInitialized get { lock (m_sync) + { return m_current is not null; + } } } @@ -84,9 +86,7 @@ public void Refresh() ObjectDisposedException.ThrowIf(m_disposed, this); while (true) { - ITypeRegistryTransaction transaction = Prepare( - m_types.current, - allowDisposed: false); + ITypeRegistryTransaction transaction = Prepare(m_types.current, allowDisposed: false); try { transaction.Activate(); @@ -112,9 +112,9 @@ public void Refresh() TypeCacheSnapshot latest = m_types.current; lock (m_sync) { - if (m_activationInProgress || - m_current is not null && m_typeCacheVersion == latest.version) - { + if (m_activationInProgress + || m_current is not null && m_typeCacheVersion == latest.version + ) { return; } } @@ -137,7 +137,8 @@ public void Clear() if (m_activationInProgress) { throw new InvalidOperationException( - "A registry snapshot cannot be cleared while a refresh transaction is active."); + "A registry snapshot cannot be cleared while a refresh transaction is active." + ); } snapshot = m_current; } @@ -145,7 +146,9 @@ public void Clear() try { if (snapshot is not null) + { ReleaseSnapshot(snapshot); + } } finally { @@ -173,7 +176,9 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_disposed = true; snapshot = m_activationInProgress ? null : m_current; } @@ -181,7 +186,9 @@ public void Dispose() try { if (snapshot is not null) + { ReleaseSnapshot(snapshot); + } } finally { @@ -210,12 +217,16 @@ protected TSnapshot current lock (m_sync) { if (m_current is not null && m_typeCacheVersion == types.version) + { return m_current; + } } Refresh(); lock (m_sync) + { return m_current ?? throw new InvalidOperationException("Registry refresh produced no snapshot."); + } } } @@ -246,8 +257,7 @@ protected TSnapshot current protected virtual void OnActivating( TSnapshot? previous, TSnapshot candidate - ) { - } + ) {} /// /// Reverses lifecycle work performed while activating a candidate snapshot. @@ -265,8 +275,7 @@ TSnapshot candidate protected virtual void OnActivationRolledBack( TSnapshot? previous, TSnapshot candidate - ) { - } + ) {} /// /// Finalizes a successfully activated candidate after every coordinated registry has activated. @@ -284,8 +293,7 @@ TSnapshot candidate protected virtual void OnActivationCompleted( TSnapshot? previous, TSnapshot currentSnapshot - ) { - } + ) {} /// /// Releases resources owned by a registry snapshot. @@ -296,7 +304,9 @@ TSnapshot currentSnapshot protected virtual void DisposeSnapshot(TSnapshot snapshot) { if (snapshot is IDisposable disposable) + { disposable.Dispose(); + } } /// @@ -315,12 +325,7 @@ protected virtual void DisposeSnapshot(TSnapshot snapshot) protected virtual void OnCleanupFailed( string phase, Exception exception - ) - => Trace.TraceError( - "Type registry '{0}' failed during {1}: {2}", - GetType().FullName, - phase, - exception); + ) => Trace.TraceError("Type registry '{0}' failed during {1}: {2}", GetType().FullName, phase, exception); /// /// Faults the shared generation gate when a resource composed from this registry cannot retire safely. @@ -352,7 +357,8 @@ protected TExtension CreateExtension(Type type) if (type.IsAbstract || !typeof(TExtension).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Extension '{type.FullName}' must be a non-abstract {typeof(TExtension).FullName}."); + $"Extension '{type.FullName}' must be a non-abstract {typeof(TExtension).FullName}." + ); } try @@ -364,7 +370,8 @@ protected TExtension CreateExtension(Type type) { throw new InvalidOperationException( $"Extension '{type.FullName}' requires a parameterless constructor.", - exception); + exception + ); } } @@ -387,9 +394,13 @@ protected TExtension OwnCandidateExtension(TExtension extension) { ArgumentNullException.ThrowIfNull(extension); if (m_candidateResources is null) + { throw new InvalidOperationException("Candidate resources may only be owned while building a registry snapshot."); + } if (extension is IDisposable) + { m_candidateResources.Add(extension); + } return extension; } @@ -410,7 +421,9 @@ protected void DisposeExtensions(IEnumerable extensions) ArgumentNullException.ThrowIfNull(extensions); var resources = new LifetimeScope(); foreach (IDisposable resource in extensions.Distinct(ReferenceEqualityComparer.Instance).OfType()) + { resources.Own(resource); + } RetireResource("extension batch", resources.Dispose); } @@ -454,13 +467,19 @@ bool allowDisposed if (m_disposed) { if (allowDisposed) + { return TypeRegistryNoopTransaction.instance; + } throw new ObjectDisposedException(GetType().FullName); } if (m_activationInProgress) + { return TypeRegistryNoopTransaction.instance; + } if (m_current is not null && m_typeCacheVersion == types.version) + { return TypeRegistryNoopTransaction.instance; + } m_activationInProgress = true; m_candidateResources = []; @@ -468,12 +487,7 @@ bool allowDisposed try { TSnapshot candidate = Build(types); - return new RegistryTransaction( - this, - candidate, - types.version, - m_current, - m_typeCacheVersion); + return new RegistryTransaction(this, candidate, types.version, m_current, m_typeCacheVersion); } catch (Exception failure) { @@ -564,8 +578,9 @@ Exception exception { OnCleanupFailed(phase, exception); } - catch + catch (Exception) { + // The cleanup failure is already reported to the type catalog. A failing observer must not hide it. } } @@ -577,7 +592,9 @@ private void EnsureRetirementSafe() throw m_retirementFailure; } if (!m_disposed) + { m_types.EnsureRetirementSafe(); + } } private void RetainFailedRetirement( @@ -645,7 +662,9 @@ public void Activate() { owner.OnActivating(previous, candidate); lock (owner.m_sync) + { ObjectDisposedException.ThrowIf(owner.m_disposed, owner); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { @@ -660,9 +679,15 @@ public void Activate() } catch (Exception rollbackFailure) { - var combined = new AggregateException("Registry activation and rollback failed.", activationFailure, rollbackFailure); + var combined = new AggregateException( + "Registry activation and rollback failed.", + activationFailure, + rollbackFailure + ); if (RetirementPendingException.Find(combined) is not null) + { owner.RetainFailedRetirement(combined, this, "activation rollback"); + } throw combined; } throw; @@ -679,9 +704,13 @@ public void Complete() lock (owner.m_sync) { if (m_finished) + { return; + } if (!m_activated) + { throw new InvalidOperationException("Registry transaction has not been activated."); + } m_finished = true; snapshotToRelease = previous; } @@ -689,7 +718,9 @@ public void Complete() List failures = []; Attempt(() => owner.CompleteActivation(previous, candidate), failures); if (snapshotToRelease is not null) + { Attempt(() => owner.ReleaseSnapshot(snapshotToRelease), failures); + } bool releaseCandidate; lock (owner.m_sync) { @@ -697,7 +728,9 @@ public void Complete() owner.m_activationInProgress = false; } if (releaseCandidate) + { Attempt(() => owner.ReleaseSnapshot(candidate), failures); + } previous = null; candidate = null!; ThrowCleanupFailures(failures); @@ -713,7 +746,9 @@ public void Rollback() lock (owner.m_sync) { if (m_finished) + { return; + } ownerWasDisposed = owner.m_disposed; if (m_activated && !ownerWasDisposed) { @@ -731,15 +766,27 @@ public void Rollback() List failures = []; if (m_activationStarted) + { Attempt(() => owner.RollbackActivation(previous, candidate), failures); + } Attempt(() => owner.ReleaseSnapshot(candidate), failures); if (ownerWasDisposed && previous is not null) + { Attempt(() => owner.ReleaseSnapshot(previous), failures); + } previous = null; candidate = null!; ThrowCleanupFailures(failures); } + private void EnsureNotFinished() + { + if (m_finished) + { + throw new InvalidOperationException("Registry transaction is already finished."); + } + } + private static void Attempt( Action action, List failures @@ -751,7 +798,12 @@ List failures catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures.Count > 0) - throw new AggregateException("Registry retirement remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Registry retirement remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -763,13 +815,9 @@ List failures private static void ThrowCleanupFailures(List failures) { if (failures.Count > 0) + { throw new AggregateException("Registry retirement or rollback failed after every resource was attempted.", failures); - } - - private void EnsureNotFinished() - { - if (m_finished) - throw new InvalidOperationException("Registry transaction is already finished."); + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs index 61bfe9e35..741bdbfcd 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs @@ -1,66 +1,9 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; namespace Inno.Extensibility.Types; -internal interface ITypeRegistry -{ - /// - /// Builds and validates candidate state without changing the active generation. - /// - /// - /// The active type catalog generation used for extension resolution. - /// - /// - /// The validated itype registry transaction that represents the completed operation. - /// - ITypeRegistryTransaction Prepare(TypeCacheSnapshot types); -} - -internal interface ITypeRegistryTransaction -{ - /// - /// Makes the prepared value active at the owning subsystem's safety point. - /// - void Activate(); - /// - /// Finalizes candidate activation and releases temporary transaction state. - /// - void Complete(); - /// - /// Restores the state captured before the current transaction began. - /// - void Rollback(); -} - -internal sealed class TypeRegistryNoopTransaction : ITypeRegistryTransaction -{ - internal static TypeRegistryNoopTransaction instance { get; } = new(); - - /// - /// Makes the prepared value active at the owning subsystem's safety point. - /// - public void Activate() - { - } - - /// - /// Finalizes candidate activation and releases temporary transaction state. - /// - public void Complete() - { - } - - /// - /// Restores the state captured before the current transaction began. - /// - public void Rollback() - { - } -} - internal sealed class TypeRegistryCoordinator { private readonly object m_sync = new(); @@ -74,9 +17,7 @@ internal TypeRegistryRegistration Register(ITypeRegistry registry) { RemoveCollectedRegistries(); var registration = new TypeRegistryRegistration(this, Guid.NewGuid()); - m_registries.Add(new RegistryReference( - registration.id, - new WeakReference(registry))); + m_registries.Add(new RegistryReference(registration.id, new WeakReference(registry))); return registration; } } @@ -95,7 +36,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) foreach (RegistryReference registration in m_registries) { if (registration.registry.TryGetTarget(out ITypeRegistry? registry)) + { registries.Add(registry); + } } } @@ -103,7 +46,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) try { foreach (ITypeRegistry registry in registries) + { transactions.Add(registry.Prepare(types)); + } return new TypeRegistryRefreshSet(transactions); } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -123,7 +68,10 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { - m_retirementFailure = new AggregateException("Registry preparation failed and rollback remains pending.", [.. failures, failure]); + m_retirementFailure = new AggregateException( + "Registry preparation failed and rollback remains pending.", + [.. failures, failure] + ); m_retainedPreparation = (registries, transactions); throw m_retirementFailure; } @@ -133,15 +81,19 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) } } if (failures.Count > 1) + { throw new AggregateException("Type registry preparation and rollback failed.", failures); + } throw; } } - internal void Unregister(Guid registrationId) + internal void Unregister(Guid registrationID) { lock (m_sync) - m_registries.RemoveAll(registration => registration.id == registrationId); + { + m_registries.RemoveAll(registration => registration.id == registrationID); + } } private void RemoveCollectedRegistries() => m_registries.RemoveAll(static registration => !registration.registry.TryGetTarget(out _)); @@ -151,116 +103,3 @@ private readonly record struct RegistryReference( WeakReference registry ); } - -internal sealed class TypeRegistryRegistration( - TypeRegistryCoordinator owner, - Guid id -) : IDisposable -{ - private bool m_disposed; - - internal Guid id { get; } = id; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - owner.Unregister(id); - } -} - -internal sealed class TypeRegistryRefreshSet(IReadOnlyList transactions) -{ - private int m_activatedCount; - private bool m_finished; - private Exception? m_failure; - - internal void Activate() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - throw new InvalidOperationException("Type registry refresh set is already finished."); - try - { - for (; m_activatedCount < transactions.Count; m_activatedCount++) - transactions[m_activatedCount].Activate(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failure; - throw; - } - catch (Exception activationFailure) - { - try - { - Rollback(); - } - catch (Exception rollbackFailure) - { - var combined = new AggregateException("Type registry activation and rollback failed.", activationFailure, rollbackFailure); - if (RetirementPendingException.Find(combined) is not null) - m_failure = combined; - throw combined; - } - throw; - } - } - - internal void Complete() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - return; - List failures = []; - for (int i = 0; i < transactions.Count; i++) - TryCleanup(transactions[i].Complete, failures); - m_finished = true; - transactions = Array.Empty(); - if (failures.Count > 0) - throw new AggregateException("Type registry completion failed after all participants were attempted.", failures); - } - - internal void Rollback() - { - if (m_failure is not null) - throw m_failure; - if (m_finished) - return; - List failures = []; - for (int i = transactions.Count - 1; i >= 0; i--) - TryCleanup(transactions[i].Rollback, failures); - m_finished = true; - transactions = Array.Empty(); - if (failures.Count > 0) - throw new AggregateException("Type registry rollback failed after all participants were attempted.", failures); - } - - private void TryCleanup( - Action cleanup, - List failures - ) { - try - { - cleanup(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failures.Count == 0 ? failure : new AggregateException( - "Registry cleanup remains pending after earlier failures.", [.. failures, failure]); - if (ReferenceEquals(m_failure, failure)) - throw; - throw m_failure; - } - catch (Exception exception) - { - failures.Add(exception); - } - } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs new file mode 100644 index 000000000..05090b41f --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs @@ -0,0 +1,21 @@ +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryNoopTransaction : ITypeRegistryTransaction +{ + /// + /// Makes the prepared value active at the owning subsystem's safety point. + /// + public void Activate() {} + + /// + /// Finalizes candidate activation and releases temporary transaction state. + /// + public void Complete() {} + + /// + /// Restores the state captured before the current transaction began. + /// + public void Rollback() {} + + internal static TypeRegistryNoopTransaction instance { get; } = new(); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs new file mode 100644 index 000000000..f05856586 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Execution; + +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryRefreshSet(IReadOnlyList transactions) +{ + private int m_activatedCount; + private bool m_finished; + private Exception? m_failure; + + internal void Activate() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + throw new InvalidOperationException("Type registry refresh set is already finished."); + } + try + { + for (; m_activatedCount < transactions.Count; m_activatedCount++) + { + transactions[m_activatedCount].Activate(); + } + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failure; + throw; + } + catch (Exception activationFailure) + { + try + { + Rollback(); + } + catch (Exception rollbackFailure) + { + var combined = new AggregateException( + "Type registry activation and rollback failed.", + activationFailure, + rollbackFailure + ); + if (RetirementPendingException.Find(combined) is not null) + { + m_failure = combined; + } + throw combined; + } + throw; + } + } + + internal void Complete() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = 0; i < transactions.Count; i++) + { + TryCleanup(transactions[i].Complete, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Type registry completion failed after all participants were attempted.", failures); + } + } + + internal void Rollback() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = transactions.Count - 1; i >= 0; i--) + { + TryCleanup(transactions[i].Rollback, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Type registry rollback failed after all participants were attempted.", failures); + } + } + + private void TryCleanup( + Action cleanup, + List failures + ) { + try + { + cleanup(); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failures.Count == 0 ? failure : new AggregateException( + "Registry cleanup remains pending after earlier failures.", + [.. failures, failure] + ); + if (ReferenceEquals(m_failure, failure)) + { + throw; + } + throw m_failure; + } + catch (Exception exception) + { + failures.Add(exception); + } + } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs new file mode 100644 index 000000000..d247ec82c --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryRegistration( + TypeRegistryCoordinator owner, + Guid id +) : IDisposable +{ + private bool m_disposed; + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + owner.Unregister(id); + } + + internal Guid id { get; } = id; +} diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs index 8f1c843f4..458fc2a26 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs @@ -28,10 +28,7 @@ public sealed class ScriptingApiExportAttribute : Attribute public ScriptingApiExportAttribute( Type type, ScriptingApiScope scope - ) - : this(type, GetDefaultName(type), scope) - { - } + ) : this(type, GetDefaultName(type), scope) {} /// /// Creates an explicit script API export with a script-facing type name. @@ -56,9 +53,12 @@ public ScriptingApiExportAttribute( string name, ScriptingApiScope scope ) { - this.type = type ?? throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); + this.type = type; if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A script-facing type name is required.", nameof(name)); + } this.name = name; this.scope = scope; } @@ -81,7 +81,9 @@ ScriptingApiScope scope private static string GetDefaultName(Type? type) { if (type is null) + { return string.Empty; + } int aritySeparator = type.Name.IndexOf('`'); return aritySeparator < 0 ? type.Name : type.Name[..aritySeparator]; } diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs index dc0f1c499..a70087dc3 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs @@ -6,13 +6,12 @@ namespace Inno.Scripting.Api; /// Explicitly excludes one otherwise visible member from generated scripting reference assemblies. /// [AttributeUsage( - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Property | - AttributeTargets.Field | - AttributeTargets.Event, + AttributeTargets.Constructor + | AttributeTargets.Method + | AttributeTargets.Property + | AttributeTargets.Field + | AttributeTargets.Event, AllowMultiple = false, - Inherited = false)] -public sealed class ScriptingApiIgnoreAttribute : Attribute -{ -} + Inherited = false +)] +public sealed class ScriptingApiIgnoreAttribute : Attribute; diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs index 6f8d303c4..f8890d24b 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs @@ -32,9 +32,13 @@ public ScriptingApiNamespaceAttribute( ScriptingApiScope scope ) { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A script API namespace is required.", nameof(name)); + } if (string.IsNullOrWhiteSpace(implementationNamespace)) + { throw new ArgumentException("An implementation namespace is required.", nameof(implementationNamespace)); + } this.name = name; this.implementationNamespace = implementationNamespace; this.scope = scope; diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs index c3bdbd8ea..d72e5959e 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs @@ -9,12 +9,10 @@ public enum ScriptingApiScope /// Exposes the API to both game and editor scripts. /// Runtime, - /// /// Exposes the API only to editor scripts. /// Editor, - /// /// Exposes compile-time annotations to game and editor scripts. Player compilation erases /// their applications and derived annotation declarations before binding to target assemblies. diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityId.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityID.cs similarity index 92% rename from src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityId.cs rename to src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityID.cs index eb4c51179..abf732450 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityId.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeCapabilityID.cs @@ -5,7 +5,7 @@ namespace Inno.Runtime.Contracts; /// /// Identifies a backend-neutral capability supplied by composition, not an object or native handle. /// -public readonly record struct RuntimeCapabilityId +public readonly record struct RuntimeCapabilityID { /// /// Creates an open capability protocol identifier. @@ -16,7 +16,7 @@ public readonly record struct RuntimeCapabilityId /// /// The identifier is empty. /// - public RuntimeCapabilityId(string value) + public RuntimeCapabilityID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs index 2cec1be5f..0507f0fde 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs @@ -24,25 +24,23 @@ public abstract class RuntimeSubsystem : IRuntimeSubsystem /// public bool isStarted => m_started && !m_disposed && !m_stopping; - /// - /// Gets resources and cancellation owned exclusively by this subsystem. - /// - protected LifetimeScope lifetime => m_lifetime; /// /// Acquires session resources after every dependency has attached. /// + /// + /// The subsystem is already started. + /// /// /// The caller must own this instance before attachment. Failed attachment stops admission but leaves partial /// resources with that owner, which must drive Dispose through any pending retirement. /// - /// - /// The subsystem is already started. - /// public void Attach() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { throw new InvalidOperationException("A subsystem cannot be attached to multiple owners."); + } m_ownerThread = Environment.CurrentManagedThreadId; m_started = true; try @@ -56,6 +54,7 @@ public void Attach() throw; } } + /// /// Begins one frame before event dispatch and simulation. /// @@ -66,7 +65,9 @@ public void BeginFrame(RuntimeFrame frame) { EnsureStarted(); if (m_frameOpen) + { throw new InvalidOperationException("A subsystem frame is already open."); + } m_frameOpen = true; try { @@ -85,6 +86,7 @@ public void BeginFrame(RuntimeFrame frame) throw; } } + /// /// Advances one deterministic simulation step. /// @@ -96,6 +98,7 @@ public void FixedUpdate(RuntimeFixedFrame frame) EnsureFrame(); OnFixedUpdate(frame); } + /// /// Advances variable simulation state. /// @@ -107,6 +110,7 @@ public void Update(RuntimeFrame frame) EnsureFrame(); OnUpdate(frame); } + /// /// Advances state that depends on completed variable simulation. /// @@ -118,6 +122,7 @@ public void LateUpdate(RuntimeFrame frame) EnsureFrame(); OnLateUpdate(frame); } + /// /// Prepares frame output after simulation has completed. /// @@ -129,6 +134,7 @@ public void BeforeRender(RuntimeFrame frame) EnsureFrame(); OnPrepareOutput(frame); } + /// /// Produces frame output owned by this subsystem. /// @@ -140,6 +146,7 @@ public void Render(RuntimeFrame frame) EnsureFrame(); OnProduceOutput(frame); } + /// /// Finalizes frame output even when rendering fails. /// @@ -151,6 +158,7 @@ public void AfterRender(RuntimeFrame frame) EnsureFrame(); OnCompleteOutput(frame); } + /// /// Ends one frame and releases frame-scoped state. /// @@ -160,20 +168,26 @@ public void AfterRender(RuntimeFrame frame) public void EndFrame(RuntimeFrame frame) { if (!m_frameOpen) + { return; + } EnsureThread(); List failures = []; TryRelease(() => OnEndFrame(frame), failures); for (int index = m_frameScopes.Count - 1; index >= 0; index--) + { TryRelease(m_frameScopes[index].Dispose, failures); + } m_frameScopes.Clear(); m_frameOpen = false; ThrowFailures(failures); } + /// /// Releases attached session resources before dependencies detach. /// public void Detach() => Dispose(); + /// /// Releases this owner's registrations and resources exactly once. /// @@ -186,13 +200,19 @@ public void EndFrame(RuntimeFrame frame) public void Dispose() { if (m_disposed) + { return; + } EnsureThread(); m_stopping = true; TryRelease(() => EndFrame(default), m_retirementFailures); TryRelease(m_lifetime.Cancel, m_retirementFailures); if (!m_lifetime.isQuiescent) - throw new RetirementPendingException("Subsystem retirement is pending: tracked work must finish before domain resources can be released."); + { + throw new RetirementPendingException( + "Subsystem retirement is pending: tracked work must finish before domain resources can be released." + ); + } if (!m_stopCompleted) { TryRetire(OnStop); @@ -203,9 +223,16 @@ public void Dispose() Exception[] failures = m_retirementFailures.ToArray(); m_retirementFailures.Clear(); if (failures.Length > 0) + { throw new AggregateException("Subsystem retirement failed after all cleanup stages were attempted.", failures); + } } + /// + /// Gets resources and cancellation owned exclusively by this subsystem. + /// + protected LifetimeScope lifetime => m_lifetime; + /// /// Registers a binding that must close even when a frame hook fails. /// @@ -225,101 +252,108 @@ protected void OwnFrameScope(IDisposable scope) /// /// Acquires resources after dependencies have started. /// - protected virtual void OnStart() { } + protected virtual void OnStart() {} + /// /// Captures snapshots and binds service façades. /// /// /// The variable frame timing. /// - protected virtual void OnBeginFrame(RuntimeFrame frame) { } + protected virtual void OnBeginFrame(RuntimeFrame frame) {} + /// /// Advances one deterministic fixed step. /// /// /// The fixed-step timing. /// - protected virtual void OnFixedUpdate(RuntimeFixedFrame frame) { } + protected virtual void OnFixedUpdate(RuntimeFixedFrame frame) {} + /// /// Advances domain state on the variable clock. /// /// /// The variable frame timing. /// - protected virtual void OnUpdate(RuntimeFrame frame) { } + protected virtual void OnUpdate(RuntimeFrame frame) {} + /// /// Updates state that depends on completed simulation. /// /// /// The variable frame timing. /// - protected virtual void OnLateUpdate(RuntimeFrame frame) { } + protected virtual void OnLateUpdate(RuntimeFrame frame) {} + /// /// Opens resources required for this frame's output. /// /// /// The variable frame timing. /// - protected virtual void OnPrepareOutput(RuntimeFrame frame) { } + protected virtual void OnPrepareOutput(RuntimeFrame frame) {} + /// /// Collects output commands without executing managed code on a native realtime callback. /// /// /// The variable frame timing. /// - protected virtual void OnProduceOutput(RuntimeFrame frame) { } + protected virtual void OnProduceOutput(RuntimeFrame frame) {} + /// /// Submits output and closes output-specific temporary resources. /// /// /// The variable frame timing. /// - protected virtual void OnCompleteOutput(RuntimeFrame frame) { } + protected virtual void OnCompleteOutput(RuntimeFrame frame) {} + /// /// Finalizes control-thread frame state before execution bindings are revoked. /// /// /// The frame being closed. /// - protected virtual void OnEndFrame(RuntimeFrame frame) { } + protected virtual void OnEndFrame(RuntimeFrame frame) {} + /// /// Releases domain resources, including allocations made before attachment. /// - protected virtual void OnStop() { } + protected virtual void OnStop() {} private void EnsureStarted() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The subsystem is retiring and cannot accept new work."); + } EnsureThread(); if (!m_started) + { throw new InvalidOperationException("The subsystem has not been attached."); + } } + private void EnsureFrame() { EnsureStarted(); if (!m_frameOpen) + { throw new InvalidOperationException("No subsystem frame is active."); + } } + private void EnsureThread() { if (m_ownerThread != 0 && m_ownerThread != Environment.CurrentManagedThreadId) - throw new InvalidOperationException("Subsystem lifecycle operations require the owner thread."); - } - private static void TryRelease( - Action release, - List failures - ) { - try { - release(); - } - catch (Exception exception) - { - failures.Add(exception); + throw new InvalidOperationException("Subsystem lifecycle operations require the owner thread."); } } + private void TryRetire(Action release) { try @@ -335,9 +369,26 @@ private void TryRetire(Action release) m_retirementFailures.Add(exception); } } + + private static void TryRelease( + Action release, + List failures + ) { + try + { + release(); + } + catch (Exception exception) + { + failures.Add(exception); + } + } + private static void ThrowFailures(List failures) { if (failures.Count > 0) + { throw new AggregateException("Subsystem retirement failed after all cleanup stages were attempted.", failures); + } } } diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs index 37748c22e..12bce3637 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; using Inno.Core.Events; @@ -53,44 +53,57 @@ public RuntimeSubsystemContext( LifetimeScope resources, RuntimeSubsystemLifetime lifetime, bool isEditMode = false, - IEnumerable? capabilities = null + IEnumerable? capabilities = null ) { - this.events = events ?? throw new ArgumentNullException(nameof(events)); - this.diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); - this.identities = identities ?? throw new ArgumentNullException(nameof(identities)); - this.types = types ?? throw new ArgumentNullException(nameof(types)); - this.resources = resources ?? throw new ArgumentNullException(nameof(resources)); + ArgumentNullException.ThrowIfNull(events); + ArgumentNullException.ThrowIfNull(diagnostics); + ArgumentNullException.ThrowIfNull(identities); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(resources); + this.events = events; + this.diagnostics = diagnostics; + this.identities = identities; + this.types = types; + this.resources = resources; this.lifetime = lifetime; this.isEditMode = isEditMode; this.capabilities = (capabilities ?? []).ToFrozenSet(); if (this.capabilities.Any(static capability => !capability.isValid)) + { throw new ArgumentException("Available capabilities must be valid.", nameof(capabilities)); + } } /// /// Gets the owner-thread event dispatcher. /// public EventDispatcher events { get; } + /// /// Gets the shared diagnostic state owner. /// public DiagnosticHub diagnostics { get; } + /// /// Gets the isolated live-object identity domain. /// public IdentityAllocator identities { get; } + /// /// Gets the current foundation type catalog. /// public TypeCatalog types { get; } + /// /// Gets resources owned by this pipeline, not by a global container. /// public LifetimeScope resources { get; } + /// /// Gets the owner scope used to validate factory lifetimes. /// public RuntimeSubsystemLifetime lifetime { get; } + /// /// Gets whether scaled simulation should be disabled for authoring. /// @@ -99,5 +112,5 @@ public RuntimeSubsystemContext( /// /// Gets the immutable capabilities verified by the owner, never a mutable service container. /// - public IReadOnlySet capabilities { get; } + public IReadOnlySet capabilities { get; } } diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs index dbc7329b6..02ea34791 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs @@ -34,29 +34,43 @@ public sealed class RuntimeSubsystemDescriptor /// Thrown when is invalid or a dependency is invalid, duplicated, or self-referential. /// public RuntimeSubsystemDescriptor( - RuntimeSubsystemId id, + RuntimeSubsystemID id, int order = 0, - IReadOnlyList? dependencies = null, + IReadOnlyList? dependencies = null, RuntimeSubsystemLifetime lifetime = RuntimeSubsystemLifetime.Session, RuntimeSubsystemRequirement requirement = RuntimeSubsystemRequirement.Required, - IReadOnlyList? requiredCapabilities = null + IReadOnlyList? requiredCapabilities = null ) { if (!id.isValid) + { throw new ArgumentException("A runtime subsystem requires a valid ID.", nameof(id)); + } if (!Enum.IsDefined(lifetime)) + { throw new ArgumentOutOfRangeException(nameof(lifetime)); + } if (!Enum.IsDefined(requirement)) + { throw new ArgumentOutOfRangeException(nameof(requirement)); - RuntimeCapabilityId[] capabilities = requiredCapabilities?.ToArray() ?? []; + } + RuntimeCapabilityID[] capabilities = requiredCapabilities?.ToArray() ?? []; if (capabilities.Any(static capability => !capability.isValid) || capabilities.Distinct().Count() != capabilities.Length) + { throw new ArgumentException("Required capabilities must be valid and unique.", nameof(requiredCapabilities)); - RuntimeSubsystemId[] dependencySnapshot = dependencies?.ToArray() ?? []; + } + RuntimeSubsystemID[] dependencySnapshot = dependencies?.ToArray() ?? []; if (dependencySnapshot.Any(static dependency => !dependency.isValid)) + { throw new ArgumentException("Runtime subsystem dependencies must be valid.", nameof(dependencies)); + } if (dependencySnapshot.Contains(id)) + { throw new ArgumentException("A runtime subsystem cannot depend on itself.", nameof(dependencies)); + } if (dependencySnapshot.Distinct().Count() != dependencySnapshot.Length) + { throw new ArgumentException("Runtime subsystem dependencies must be unique.", nameof(dependencies)); + } this.id = id; this.order = order; this.dependencies = Array.AsReadOnly(dependencySnapshot); @@ -68,7 +82,7 @@ public RuntimeSubsystemDescriptor( /// /// Gets the unique subsystem protocol identifier. /// - public RuntimeSubsystemId id { get; } + public RuntimeSubsystemID id { get; } /// /// Gets the exclusive owner scope required by this subsystem. @@ -83,7 +97,7 @@ public RuntimeSubsystemDescriptor( /// /// Gets the immutable required-subsystem identifiers. /// - public IReadOnlyList dependencies { get; } + public IReadOnlyList dependencies { get; } /// /// Gets whether this subsystem must start for its owner to become available. @@ -93,5 +107,5 @@ public RuntimeSubsystemDescriptor( /// /// Gets the immutable capability prerequisites checked before allocating subsystem resources. /// - public IReadOnlyList requiredCapabilities { get; } + public IReadOnlyList requiredCapabilities { get; } } diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemId.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemID.cs similarity index 92% rename from src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemId.cs rename to src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemID.cs index ddfb57582..b81b0c3d8 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemId.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemID.cs @@ -5,7 +5,7 @@ namespace Inno.Runtime.Contracts; /// /// Identifies one backend-neutral runtime subsystem protocol. /// -public readonly record struct RuntimeSubsystemId +public readonly record struct RuntimeSubsystemID { /// /// Creates a stable runtime subsystem identifier. @@ -16,7 +16,7 @@ public readonly record struct RuntimeSubsystemId /// /// Thrown when is empty. /// - public RuntimeSubsystemId(string value) + public RuntimeSubsystemID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs index f72badedd..65dec2fe0 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs @@ -9,7 +9,6 @@ public enum RuntimeSubsystemRequirement /// Missing capabilities, dependencies or failed startup reject the entire owner. /// Required, - /// /// A fully compensated startup may remain unavailable with diagnostics; cleanup failures still reject the owner. /// diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs index b9816dc16..263284995 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs @@ -27,13 +27,23 @@ public GameCodeDeployment(IReadOnlyList modules) foreach (GameCodeModule module in modules) { if (module is null || !accepted.Add(module.name)) + { throw new InvalidDataException("A code deployment contains a null or duplicate module."); + } foreach (string dependency in module.dependencies) + { if (!accepted.Contains(dependency)) + { throw new InvalidDataException($"Code module '{module.name}' precedes dependency '{dependency}'."); + } + } foreach (GameCodeAssembly assembly in module.assemblies) + { if (!assemblies.Add(assembly.name)) + { throw new InvalidDataException($"Code assembly '{assembly.name}' has multiple module owners."); + } + } } this.modules = Array.AsReadOnly(modules.ToArray()); } @@ -43,32 +53,6 @@ public GameCodeDeployment(IReadOnlyList modules) /// public IReadOnlyList modules { get; } - /// - /// Freezes validated manifest declarations without retaining their mutable arrays or entries. - /// - /// - /// Current-format runtime manifest declarations. - /// - /// - /// An immutable logical deployment; invalid declarations fail before activation. - /// - /// - /// A declaration or its ownership and dependencies are invalid. - /// - public static GameCodeDeployment FromManifest(IReadOnlyList modules) - { - ArgumentNullException.ThrowIfNull(modules); - return new GameCodeDeployment(modules.Select(static module => - { - if (module is null) - throw new InvalidDataException("A code deployment contains a null module declaration."); - module.Validate(); - return new GameCodeModule(module.name, module.domain, - module.assemblies.Select(static assembly => new GameCodeAssembly( - assembly.name, assembly.contentFingerprint)).ToArray(), module.dependencies); - }).ToArray()); - } - /// /// Rejects a manifest that differs from the code closure linked by the build. /// @@ -82,15 +66,55 @@ public void ValidateMatches(GameCodeDeployment expected) { ArgumentNullException.ThrowIfNull(expected); if (modules.Count != expected.modules.Count) + { throw new InvalidDataException("The deployed code module count differs from the linked composition."); + } for (int index = 0; index < modules.Count; index++) { GameCodeModule actual = modules[index]; GameCodeModule linked = expected.modules[index]; if (actual.name != linked.name || actual.domain != linked.domain || !actual.dependencies.SequenceEqual(linked.dependencies, StringComparer.Ordinal) - || !actual.assemblies.SequenceEqual(linked.assemblies)) + || !actual.assemblies.SequenceEqual(linked.assemblies) + ) { throw new InvalidDataException($"Code module '{actual.name}' differs from the linked composition."); + } } } + + /// + /// Freezes validated manifest declarations without retaining their mutable arrays or entries. + /// + /// + /// Current-format runtime manifest declarations. + /// + /// + /// An immutable logical deployment; invalid declarations fail before activation. + /// + /// + /// A declaration or its ownership and dependencies are invalid. + /// + public static GameCodeDeployment FromManifest(IReadOnlyList modules) + { + ArgumentNullException.ThrowIfNull(modules); + return new GameCodeDeployment( + modules.Select(static module => + { + if (module is null) + { + throw new InvalidDataException("A code deployment contains a null module declaration."); + } + module.Validate(); + return new GameCodeModule( + module.name, + module.domain, + module.assemblies.Select(static assembly => new GameCodeAssembly( + assembly.name, + assembly.contentFingerprint + )).ToArray(), + module.dependencies + ); + }).ToArray() + ); + } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs index 0da619a24..62f348170 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Inno.Extensibility.Modules; @@ -37,7 +38,9 @@ IReadOnlyList dependencies ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(dependencies); if (assemblies.Any(static assembly => assembly is null)) - throw new System.IO.InvalidDataException("A code module contains a null assembly identity."); + { + throw new InvalidDataException("A code module contains a null assembly identity."); + } var declaration = new GameRuntimeModule { name = name, diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs index a3480152e..114cea188 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs @@ -32,10 +32,14 @@ public sealed class GameRuntimeAssembly : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(name) - || name.Any(static character => !(char.IsAsciiLetterOrDigit(character) || character is '.' or '_' or '-'))) + || name.Any(static character => !(char.IsAsciiLetterOrDigit(character) || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("A code assembly requires a portable simple name."); + } if (contentFingerprint is null || contentFingerprint.Length != 64 - || contentFingerprint.Any(static character => !(character is >= '0' and <= '9' or >= 'a' and <= 'f'))) + || contentFingerprint.Any(static character => !(character is >= '0' and <= '9' or >= 'a' and <= 'f')) + ) { throw new InvalidDataException($"Code assembly '{name}' requires a lowercase SHA-256 fingerprint."); + } } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs index 8763b6a14..244f718e7 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs @@ -72,52 +72,71 @@ public void Validate() || applicationId.Any(static character => !(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { + || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("A game application ID must use lowercase portable identifier characters."); } if (string.IsNullOrWhiteSpace(productName)) + { throw new InvalidDataException("A game product name is required."); + } if (persistentDataPath is null) + { throw new InvalidDataException("Game persistent data path cannot be null."); + } RuntimeManifestEnvelope.ValidatePersistentDataPath( - persistentDataPath.Length == 0 ? applicationId : persistentDataPath); + persistentDataPath.Length == 0 ? applicationId : persistentDataPath + ); if (string.IsNullOrWhiteSpace(startupScene)) + { throw new InvalidDataException("A game startup scene is required."); + } if (windowWidth <= 0 || windowHeight <= 0) + { throw new InvalidDataException("Game window dimensions must be positive."); + } if (plugins is null || modules is null) + { throw new InvalidDataException("Game Plugin contributions and runtime modules cannot be null."); + } var accepted = new HashSet(StringComparer.Ordinal); foreach (GameRuntimePlugin plugin in plugins) { plugin.Validate(); if (!accepted.Add(plugin.id)) + { throw new InvalidDataException($"Game Plugin '{plugin.id}' is declared more than once."); + } string? missing = plugin.dependencies.FirstOrDefault(dependency => !accepted.Contains(dependency)); if (missing is not null) { - throw new InvalidDataException( - $"Game Plugin '{plugin.id}' appears before dependency '{missing}'."); + throw new InvalidDataException($"Game Plugin '{plugin.id}' appears before dependency '{missing}'."); } } if (modules.Length == 0) + { throw new InvalidDataException("A game runtime manifest requires a managed module generation."); + } accepted.Clear(); foreach (GameRuntimeModule module in modules) { if (module is null) + { throw new InvalidDataException("A game runtime manifest contains a null module."); + } module.Validate(); if (!accepted.Add(module.name)) + { throw new InvalidDataException($"Runtime module '{module.name}' is declared more than once."); + } string? missing = module.dependencies.FirstOrDefault(dependency => !accepted.Contains(dependency)); if (missing is not null) { throw new InvalidDataException( - $"Runtime module '{module.name}' appears before dependency '{missing}'."); + $"Runtime module '{module.name}' appears before dependency '{missing}'." + ); } } _ = GameCodeDeployment.FromManifest(modules); @@ -136,6 +155,7 @@ public IReadOnlyList CreateSettingContributors() plugin.id, plugin.dependencies, plugin.overrides, - plugin.settings)).ToArray(); + plugin.settings + )).ToArray(); } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs index 524cc7844..e89390759 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs @@ -45,26 +45,35 @@ public sealed class GameRuntimeModule : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(name)) + { throw new InvalidDataException("A runtime module requires a stable name."); + } if (domain is not (AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting)) + { throw new InvalidDataException($"Runtime module '{name}' has an invalid ownership domain."); + } if (assemblies is null || dependencies is null || assemblies.Length == 0) + { throw new InvalidDataException($"Runtime module '{name}' requires code and dependency collections."); + } foreach (GameRuntimeAssembly assembly in assemblies) { if (assembly is null) + { throw new InvalidDataException($"Runtime module '{name}' contains a null code identity."); + } assembly.Validate(); } if (assemblies.Select(static assembly => assembly.name).Distinct(StringComparer.OrdinalIgnoreCase).Count() - != assemblies.Length) + != assemblies.Length + ) { throw new InvalidDataException($"Runtime module '{name}' contains duplicate code identities."); + } if (dependencies.Any(string.IsNullOrWhiteSpace) || dependencies.Contains(name, StringComparer.Ordinal) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length) - { + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length + ) { throw new InvalidDataException($"Runtime module '{name}' contains invalid dependencies."); } } - } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs index b4822cbf0..5332a3de6 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs @@ -45,24 +45,33 @@ public sealed class GameRuntimePlugin : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(id)) + { throw new InvalidDataException("A runtime Plugin contribution requires an ID."); + } if (dependencies is null || overrides is null || settings is null) + { throw new InvalidDataException($"Runtime Plugin '{id}' contains a null collection."); + } if (dependencies.Any(string.IsNullOrWhiteSpace) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length) - { + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length + ) { throw new InvalidDataException($"Runtime Plugin '{id}' has invalid dependencies."); } if (overrides.Any(dependency => !dependencies.Contains(dependency, StringComparer.Ordinal))) + { throw new InvalidDataException($"Runtime Plugin '{id}' overrides an undeclared dependency."); + } if (settings.Select(static setting => setting.id).Distinct().Count() != settings.Length) - throw new InvalidDataException($"Runtime Plugin '{id}' has duplicate setting contributions."); - if (settings.Any(static setting => - !setting.id.isValid - || setting.stableTypeId == Guid.Empty - || setting.propertyData is null - || setting.propertyData.Length == 0)) { + throw new InvalidDataException($"Runtime Plugin '{id}' has duplicate setting contributions."); + } + if (settings.Any(static setting => ( + !setting.id.isValid + || setting.stableTypeId == Guid.Empty + || setting.propertyData is null + || setting.propertyData.Length == 0 + )) + ) { throw new InvalidDataException($"Runtime Plugin '{id}' has an invalid setting contribution."); } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs index 1829573f8..6dc6d7299 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs @@ -55,11 +55,17 @@ public sealed class RuntimeContentCatalog : ISerializable public void Validate() { if (!IsSha256(contentHash) || !IsSha256(snapshotFingerprint)) + { throw new InvalidDataException("Runtime content identities must be SHA-256 values."); + } if (!string.Equals(packFileName, $"content-{contentHash}.pack", StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime content pack file name does not match its content identity."); + } if (assetCount < 0 || artifactBundleCount < 0 || runtimeAssemblyCount <= 0) + { throw new InvalidDataException("Runtime content catalog contains invalid deployment counts."); + } } private static bool IsSha256(string value) => value is { Length: 64 } && value.All(static character => Uri.IsHexDigit(character)); diff --git a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs index c21ce9fe2..ad18b9047 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs @@ -11,8 +11,6 @@ namespace Inno.Runtime; /// public static class RuntimeManifestEnvelope { - private static ReadOnlySpan magic => "INNORTM\0"u8; - /// /// Encodes a validated runtime manifest into the strict deployment envelope. /// @@ -38,19 +36,20 @@ SerializationGeneration serialization ArgumentNullException.ThrowIfNull(manifest); ArgumentNullException.ThrowIfNull(serialization); manifest.Validate(); - byte[] applicationId = Encoding.UTF8.GetBytes(manifest.applicationId); + byte[] applicationID = Encoding.UTF8.GetBytes(manifest.applicationId); byte[] persistentDataPath = Encoding.UTF8.GetBytes( - manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); + manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath + ); byte[] payload = serialization.Serialize(manifest); - byte[] result = new byte[checked(magic.Length + sizeof(int) * 3 + - applicationId.Length + persistentDataPath.Length + payload.Length)]; + var result = new byte[checked(magic.Length + sizeof(int) * 3 + + applicationID.Length + persistentDataPath.Length + payload.Length)]; int offset = 0; magic.CopyTo(result); offset += magic.Length; - BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(offset), applicationId.Length); + BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(offset), applicationID.Length); offset += sizeof(int); - applicationId.CopyTo(result, offset); - offset += applicationId.Length; + applicationID.CopyTo(result, offset); + offset += applicationID.Length; BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(offset), persistentDataPath.Length); offset += sizeof(int); persistentDataPath.CopyTo(result, offset); @@ -73,11 +72,11 @@ SerializationGeneration serialization /// /// Thrown when the envelope is truncated, malformed, or contains an invalid application identity. /// - public static string ReadApplicationId(ReadOnlySpan data) + public static string ReadApplicationID(ReadOnlySpan data) { - Parse(data, out string applicationId, out _, out _); - ValidateApplicationId(applicationId); - return applicationId; + Parse(data, out string applicationID, out _, out _); + ValidateApplicationID(applicationID); + return applicationID; } /// @@ -94,8 +93,8 @@ public static string ReadApplicationId(ReadOnlySpan data) /// public static string ReadPersistentDataPath(ReadOnlySpan data) { - Parse(data, out string applicationId, out string persistentDataPath, out _); - ValidateApplicationId(applicationId); + Parse(data, out string applicationID, out string persistentDataPath, out _); + ValidateApplicationID(applicationID); ValidatePersistentDataPath(persistentDataPath); return persistentDataPath; } @@ -120,48 +119,83 @@ public static GameRuntimeManifest Decode( SerializationGeneration serialization ) { ArgumentNullException.ThrowIfNull(serialization); - Parse(data, out string applicationId, out string persistentDataPath, out ReadOnlySpan payload); - ValidateApplicationId(applicationId); + Parse(data, out string applicationID, out string persistentDataPath, out ReadOnlySpan payload); + ValidateApplicationID(applicationID); ValidatePersistentDataPath(persistentDataPath); GameRuntimeManifest manifest = serialization.Deserialize(payload); manifest.Validate(); - if (!string.Equals(applicationId, manifest.applicationId, StringComparison.Ordinal)) + if (!string.Equals(applicationID, manifest.applicationId, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest application identities do not match."); + } string expectedPath = manifest.persistentDataPath.Length == 0 - ? manifest.applicationId : manifest.persistentDataPath; + ? manifest.applicationId + : manifest.persistentDataPath; if (!string.Equals(persistentDataPath, expectedPath, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest persistent data paths do not match."); + } return manifest; } + internal static void ValidatePersistentDataPath(string persistentDataPath) + { + if (persistentDataPath is null) + { + throw new InvalidDataException("Runtime manifest requires a persistent data path value."); + } + if (persistentDataPath.Length == 0) + { + return; + } + foreach (string segment in persistentDataPath.Split('/')) + { + string stem = segment.Split('.', 2)[0]; + if (segment is "." or ".." || string.IsNullOrEmpty(segment) || segment.EndsWith('.') + || stem is "con" or "prn" or "aux" or "nul" + || (stem.Length == 4 && (stem.StartsWith("com", StringComparison.Ordinal) + || stem.StartsWith("lpt", StringComparison.Ordinal)) && stem[3] is >= '1' and <= '9') + ) { + throw new InvalidDataException("Runtime manifest contains an invalid persistent data folder."); + } + ValidateApplicationID(segment); + } + } + + private static ReadOnlySpan magic => "INNORTM\0"u8; + private static void Parse( ReadOnlySpan data, - out string applicationId, + out string applicationID, out string persistentDataPath, out ReadOnlySpan payload ) { int minimumLength = magic.Length + sizeof(int) * 3; if (data.Length < minimumLength || !data[..magic.Length].SequenceEqual(magic)) + { throw new InvalidDataException("Runtime manifest envelope has an invalid header."); + } int offset = magic.Length; - int applicationIdLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); + int applicationIDLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); - if (applicationIdLength <= 0 || applicationIdLength > 255 || applicationIdLength > data.Length - offset - sizeof(int) * 2) + if (applicationIDLength <= 0 || applicationIDLength > 255 || applicationIDLength > data.Length - offset - sizeof(int) * 2) + { throw new InvalidDataException("Runtime manifest envelope has an invalid application identity length."); + } try { - applicationId = new UTF8Encoding(false, true).GetString(data.Slice(offset, applicationIdLength)); + applicationID = new UTF8Encoding(false, true).GetString(data.Slice(offset, applicationIDLength)); } catch (DecoderFallbackException exception) { throw new InvalidDataException("Runtime manifest application identity is not valid UTF-8.", exception); } - offset += applicationIdLength; + offset += applicationIDLength; int persistentDataPathLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); - if (persistentDataPathLength <= 0 || persistentDataPathLength > 1024 || - persistentDataPathLength > data.Length - offset - sizeof(int)) - { + if (persistentDataPathLength <= 0 || persistentDataPathLength > 1024 + || persistentDataPathLength > data.Length - offset - sizeof(int) + ) { throw new InvalidDataException("Runtime manifest envelope has an invalid persistent data path length."); } try @@ -176,40 +210,26 @@ out ReadOnlySpan payload int payloadLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); if (payloadLength <= 0 || payloadLength != data.Length - offset) + { throw new InvalidDataException("Runtime manifest envelope has an invalid payload length."); + } payload = data[offset..]; } - private static void ValidateApplicationId(string applicationId) + private static void ValidateApplicationID(string applicationID) { - if (string.IsNullOrWhiteSpace(applicationId)) + if (string.IsNullOrWhiteSpace(applicationID)) + { throw new InvalidDataException("Runtime manifest requires an application identity."); - foreach (char character in applicationId) + } + foreach (char character in applicationID) { if (!(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-')) - { + || character is '.' or '_' or '-') + ) { throw new InvalidDataException("Runtime manifest contains an invalid application identity."); } } } - - internal static void ValidatePersistentDataPath(string persistentDataPath) - { - if (persistentDataPath is null) - throw new InvalidDataException("Runtime manifest requires a persistent data path value."); - if (persistentDataPath.Length == 0) - return; - foreach (string segment in persistentDataPath.Split('/')) - { - string stem = segment.Split('.', 2)[0]; - if (segment is "." or ".." || string.IsNullOrEmpty(segment) || segment.EndsWith('.') - || stem is "con" or "prn" or "aux" or "nul" - || (stem.Length == 4 && (stem.StartsWith("com", StringComparison.Ordinal) - || stem.StartsWith("lpt", StringComparison.Ordinal)) && stem[3] is >= '1' and <= '9')) - throw new InvalidDataException("Runtime manifest contains an invalid persistent data folder."); - ValidateApplicationId(segment); - } - } } diff --git a/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs b/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs new file mode 100644 index 000000000..dcc8e5ab6 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Core.Execution; +using Inno.Runtime.Contracts; + +namespace Inno.Runtime; + +internal sealed class RuntimeClock +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("clock"); + + internal static RuntimeClock current => CURRENT_SCOPE.current; + + internal float time { get; private set; } + + internal float deltaTime { get; private set; } + + internal float unscaledTime { get; private set; } + + internal float unscaledDeltaTime { get; private set; } + + internal float fixedTime { get; private set; } + + internal float fixedDeltaTime { get; private set; } + + internal float timeScale { get; private set; } = 1f; + + internal bool isPaused { get; private set; } + + internal long frameCount { get; private set; } + + internal long fixedStepCount { get; private set; } + + internal IDisposable EnterScope() => CURRENT_SCOPE.Enter(this); + + internal RuntimeFrame Update(float unscaledDeltaTime) + { + this.unscaledDeltaTime = unscaledDeltaTime; + unscaledTime += unscaledDeltaTime; + deltaTime = isPaused ? 0f : unscaledDeltaTime * timeScale; + time += deltaTime; + var frame = new RuntimeFrame(frameCount, time, unscaledTime, deltaTime, unscaledDeltaTime, timeScale, isPaused); + frameCount++; + return frame; + } + + internal RuntimeFixedFrame BeginFixedStep(float fixedDeltaTime) + { + this.fixedDeltaTime = fixedDeltaTime; + fixedTime += fixedDeltaTime; + var frame = new RuntimeFixedFrame(fixedStepCount, fixedTime, fixedDeltaTime); + fixedStepCount++; + return frame; + } + + internal void SetTimeScale(float value) + { + if (!float.IsFinite(value) || value < 0f) + { + throw new ArgumentOutOfRangeException(nameof(value), "Time scale must be finite and non-negative."); + } + timeScale = value; + } + + internal void SetPaused(bool value) => isPaused = value; +} diff --git a/src/runtime/engine/Inno.Runtime/Execution/Time.cs b/src/runtime/engine/Inno.Runtime/Execution/Time.cs index f451733ae..254f47cd9 100644 --- a/src/runtime/engine/Inno.Runtime/Execution/Time.cs +++ b/src/runtime/engine/Inno.Runtime/Execution/Time.cs @@ -1,7 +1,4 @@ -using Inno.Runtime.Contracts; -using Inno.Core.Execution; using System; -using System.Threading; namespace Inno.Runtime; @@ -94,72 +91,3 @@ public static bool isPaused /// public static long frameCount => RuntimeClock.current.frameCount; } - -internal sealed class RuntimeClock -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("clock"); - - internal static RuntimeClock current => S_CURRENT_SCOPE.current; - - internal float time { get; private set; } - - internal float deltaTime { get; private set; } - - internal float unscaledTime { get; private set; } - - internal float unscaledDeltaTime { get; private set; } - - internal float fixedTime { get; private set; } - - internal float fixedDeltaTime { get; private set; } - - internal float timeScale { get; private set; } = 1f; - - internal bool isPaused { get; private set; } - - internal long frameCount { get; private set; } - - internal long fixedStepCount { get; private set; } - - internal IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } - - internal RuntimeFrame Update(float unscaledDeltaTime) - { - this.unscaledDeltaTime = unscaledDeltaTime; - unscaledTime += unscaledDeltaTime; - deltaTime = isPaused ? 0f : unscaledDeltaTime * timeScale; - time += deltaTime; - var frame = new RuntimeFrame( - frameCount, - time, - unscaledTime, - deltaTime, - unscaledDeltaTime, - timeScale, - isPaused); - frameCount++; - return frame; - } - - internal RuntimeFixedFrame BeginFixedStep(float fixedDeltaTime) - { - this.fixedDeltaTime = fixedDeltaTime; - fixedTime += fixedDeltaTime; - var frame = new RuntimeFixedFrame(fixedStepCount, fixedTime, fixedDeltaTime); - fixedStepCount++; - return frame; - } - - internal void SetTimeScale(float value) - { - if (!float.IsFinite(value) || value < 0f) - throw new ArgumentOutOfRangeException(nameof(value), "Time scale must be finite and non-negative."); - timeScale = value; - } - - internal void SetPaused(bool value) => isPaused = value; - -} diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs index 5f7f23e2c..178b86bc8 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs @@ -1,16 +1,15 @@ using System; using System.Collections.Generic; - -using Inno.Extensibility.Modules; using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.Runtime.Contracts; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -35,16 +34,16 @@ internal EngineHost( ISerializationMetadataSource serializationMetadata ) { this.retirementTimeout = retirementTimeout; - logs = new LogRouter(deliveryMode: logDeliveryMode); - diagnostics = new DiagnosticHub(); + this.logs = new LogRouter(deliveryMode: logDeliveryMode); + this.diagnostics = new DiagnosticHub(); try { - modules = new ModuleHost(new ModuleHostOptions + this.modules = new ModuleHost(new ModuleHostOptions { catalogSource = moduleSource }); - types = new TypeCatalog(modules, typeSource); - serialization = new SerializationRegistry(types, serializationMetadata); + this.types = new TypeCatalog(modules, typeSource); + this.serialization = new SerializationRegistry(types, serializationMetadata); } catch { @@ -108,7 +107,9 @@ public RuntimeSession CreateSession(RuntimeSessionOptions options) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The engine host is retiring and cannot acquire new owners."); + } generations.EnsureReady("create a runtime session"); var session = new RuntimeSession(this, options); m_sessions.Add(session); @@ -142,17 +143,26 @@ public RuntimeSession CreateSession(RuntimeSessionOptions options) /// public RuntimeSubsystemPipeline CreateHostPipeline( IReadOnlyList factories, - IReadOnlyList? capabilities = null + IReadOnlyList? capabilities = null ) { ArgumentNullException.ThrowIfNull(factories); lock (m_sync) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The engine host is retiring and cannot acquire new owners."); + } generations.EnsureReady("create a host subsystem pipeline"); - var context = new RuntimeSubsystemContext(new EventDispatcher(), diagnostics, - new IdentityAllocator(), types, new LifetimeScope(), RuntimeSubsystemLifetime.Host, capabilities: capabilities); + var context = new RuntimeSubsystemContext( + new EventDispatcher(), + diagnostics, + new IdentityAllocator(), + types, + new LifetimeScope(), + RuntimeSubsystemLifetime.Host, + capabilities: capabilities + ); var pipeline = new RuntimeSubsystemPipeline(context, retirementTimeout, generations); m_hostPipelines.Add(pipeline); try @@ -178,14 +188,18 @@ public RuntimeSubsystemPipeline CreateHostPipeline( public void Dispose() { if (m_disposed) + { return; + } generations.EnsureRetirementSafe(); try { // Metadata-only hosts are thread-neutral; attached subsystems enforce their own control thread. m_retirement ??= new RetirementBarrier("EngineHost", retirementTimeout); if (!m_retirement.TryComplete(DisposeCore)) + { throw new RetirementPendingException("EngineHost is still draining owned sessions or pipelines."); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -203,13 +217,25 @@ public void Dispose() } } + internal TimeSpan retirementTimeout { get; } + + internal void Release(RuntimeSession session) + { + lock (m_sync) + { + m_sessions.Remove(session); + } + } + private void DisposeCore() { RuntimeSession[] sessions; lock (m_sync) { if (m_disposed) + { return; + } m_stopping = true; sessions = [.. m_sessions]; } @@ -280,28 +306,25 @@ private void DisposeCore() } if (m_retirementFailures is not null) { - var failure = new AggregateException("Engine host disposal encountered one or more failures.", m_retirementFailures); + var failure = new AggregateException( + "Engine host disposal encountered one or more failures.", + m_retirementFailures + ); m_retirementFailures = null; throw failure; } generations.Wait(); } - internal TimeSpan retirementTimeout { get; } - - internal void Release(RuntimeSession session) - { - lock (m_sync) - m_sessions.Remove(session); - } - private void RetireFailedStartup( IDisposable owner, Exception startupFailure ) { IDisposable? reservation = null; if (generations.state == GenerationState.Ready) + { _ = generations.TryAcquireChange("retire failed runtime startup", out reservation); + } using IDisposable? generationReservation = reservation; try { @@ -312,7 +335,9 @@ Exception startupFailure var failure = new AggregateException("Runtime startup and retirement failed.", startupFailure, cleanupFailure); generations.Fault(failure); if (RetirementPendingException.Find(cleanupFailure) is not null) + { throw; + } throw failure; } } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs index 1220cd696..520c9e203 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs @@ -31,8 +31,7 @@ public sealed class EngineHostBuilder /// public EngineHostBuilder UseRetirementTimeout(TimeSpan timeout) { - if (timeout <= TimeSpan.Zero) - throw new ArgumentOutOfRangeException(nameof(timeout)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(timeout, TimeSpan.Zero); m_retirementTimeout = timeout; return this; } @@ -46,9 +45,16 @@ public EngineHostBuilder UseRetirementTimeout(TimeSpan timeout) public EngineHost Build() { if (m_moduleSource is null || m_typeSource is null || m_serializationMetadata is null) + { throw new InvalidOperationException("The composition root must select module, type and serialization metadata sources."); - EngineHost host = new(m_retirementTimeout, m_logDeliveryMode, - m_moduleSource, m_typeSource, m_serializationMetadata); + } + var host = new EngineHost( + m_retirementTimeout, + m_logDeliveryMode, + m_moduleSource, + m_typeSource, + m_serializationMetadata + ); m_moduleSource = null; m_typeSource = null; m_serializationMetadata = null; @@ -64,12 +70,12 @@ public EngineHost Build() /// /// The type metadata provider corresponding to the same code deployment strategy. /// - /// - /// This builder for fluent composition. - /// /// /// The declaration access provider corresponding to the same managed deployment. /// + /// + /// This builder for fluent composition. + /// public EngineHostBuilder UseMetadataSources( IAssemblyCatalogSource modules, ITypeCatalogSource types, @@ -79,7 +85,9 @@ ISerializationMetadataSource serialization ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(serialization); if (m_moduleSource is not null) + { throw new InvalidOperationException("Metadata sources have already been selected."); + } m_moduleSource = modules; m_typeSource = types; m_serializationMetadata = serialization; @@ -101,7 +109,9 @@ ISerializationMetadataSource serialization public EngineHostBuilder UseLogDelivery(LogDeliveryMode deliveryMode) { if (!Enum.IsDefined(deliveryMode)) + { throw new ArgumentOutOfRangeException(nameof(deliveryMode)); + } m_logDeliveryMode = deliveryMode; return this; } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs index 24f8d97e5..7b35d0b06 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs @@ -9,7 +9,6 @@ public enum RuntimeJobExecutionMode /// Executes jobs deterministically on the session owner thread. /// SingleThread, - /// /// Executes ready jobs on a bounded worker pool owned by the session. /// diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs index ba9eaca98..9414261e7 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs @@ -1,4 +1,3 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Linq; @@ -12,6 +11,7 @@ using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.References; +using Inno.Runtime.Contracts; using Inno.Scene; namespace Inno.Runtime; @@ -23,15 +23,15 @@ public sealed class RuntimeSession : IDisposable { private readonly EngineHost m_host; private readonly IdentityAllocator m_identities; - private JobScheduler m_jobs = null!; private readonly CoroutineScheduler m_coroutines; private readonly RuntimeClock m_clock = new(); + private readonly RetirementBarrier m_retirement; + private JobScheduler m_jobs = null!; private RuntimeSubsystemPipeline? m_subsystems; private SerializationGeneration? m_serialization; private SessionLogSink? m_sessionLog; private AssetDatabase? m_assets; private ReferenceCatalog m_references = ReferenceCatalog.empty; - private readonly RetirementBarrier m_retirement; private List? m_retirementFailures; private float m_fixedAccumulator; private bool m_disposed; @@ -42,64 +42,11 @@ RuntimeSessionOptions options ) { m_host = host; this.options = Validate(options); - sessionId = LogSessionId.Create(); + this.sessionID = LogSessionID.Create(); m_identities = new IdentityAllocator(); m_coroutines = new CoroutineScheduler(); - events = new EventDispatcher(); - m_retirement = new RetirementBarrier($"Runtime session {sessionId}", host.retirementTimeout); - } - - internal void Start() - { - m_jobs = new JobScheduler( - options.jobExecutionMode switch - { - RuntimeJobExecutionMode.SingleThread => JobExecutionMode.SingleThread, - RuntimeJobExecutionMode.WorkerPool => JobExecutionMode.WorkerPool, - _ => throw new ArgumentOutOfRangeException( - nameof(options), - options.jobExecutionMode, - "Unknown runtime job execution mode.") - }, - new JobSchedulerOptions - { - workerCount = options.jobWorkerCount - }); - scenes = new SceneWorld(m_identities, m_host.types); - if (options.createLogSink is not null) - { - ILogSink sink = options.createLogSink(sessionId) - ?? throw new InvalidOperationException("The session log factory returned no sink."); - m_sessionLog = new SessionLogSink(sessionId, sink); - m_host.logs.RegisterSink(m_sessionLog); - } - using IDisposable scope = EnterExecutionScope(); - if (options.contentStore is not null) - { - m_serialization = m_host.serialization.CaptureGeneration(); - m_assets = new AssetDatabase( - options.contentStore, - m_serialization, - m_host.types.current, - m_identities, - options.assetResidencyBudgetBytes, - options.assetPreparationBudgetBytes); - } - IReferenceResolver[] referenceResolvers = m_assets is IReferenceResolver assetResolver - ? [.. options.referenceResolvers, assetResolver] - : [.. options.referenceResolvers]; - IAssetReferenceResolver? prefabAssets = m_assets - ?? options.referenceResolvers.OfType().SingleOrDefault(); - if (prefabAssets is not null) - scenes.ConfigurePrefabInstantiation(m_host.serialization, prefabAssets); - m_references = referenceResolvers.Length == 0 - ? ReferenceCatalog.empty - : ReferenceCatalog.Create(1, referenceResolvers); - var context = new RuntimeSubsystemContext(events, m_host.diagnostics, m_identities, m_host.types, - new LifetimeScope(), RuntimeSubsystemLifetime.Session, - options.kind == RuntimeSessionKind.Edit, options.capabilities); - m_subsystems = new RuntimeSubsystemPipeline(context, m_host.retirementTimeout, m_host.generations); - m_subsystems.Start([new SceneRuntimeSubsystemFactory(scenes, options.kind), .. options.createSubsystems(this)]); + this.events = new EventDispatcher(); + m_retirement = new RetirementBarrier($"Runtime session {sessionID}", host.retirementTimeout); } /// @@ -110,7 +57,7 @@ internal void Start() /// /// Gets the unique logging identity assigned to this session. /// - public LogSessionId sessionId { get; } + public LogSessionID sessionID { get; } /// /// Gets the event dispatcher owned by this session. @@ -167,7 +114,8 @@ public bool isPaused /// public AssetDatabase assets => m_assets ?? throw new InvalidOperationException( - "This runtime session was created without a deployed asset database."); + "This runtime session was created without a deployed asset database." + ); /// /// Binds this session's script façades to the current asynchronous execution context. @@ -186,17 +134,21 @@ public IDisposable EnterExecutionScope() { scopes.Add(m_host.logs.EnterScope()); scopes.Add(m_host.diagnostics.EnterScope()); - scopes.Add(LogSessionContext.Enter(sessionId)); + scopes.Add(LogSessionContext.Enter(sessionID)); scopes.Add(scenes.EnterScope()); scopes.Add(m_clock.EnterScope()); if (m_assets is not null) + { scopes.Add(AssetExecutionContext.EnterScope(m_assets)); + } return new ExecutionScope(scopes); } catch { for (int index = scopes.Count - 1; index >= 0; index--) + { scopes[index].Dispose(); + } throw; } } @@ -233,16 +185,16 @@ public void Tick(float deltaTime) m_fixedAccumulator += frame.deltaTime; int steps = 0; while (m_fixedAccumulator >= options.fixedDeltaTime - && steps < options.maxFixedStepsPerFrame) - { + && steps < options.maxFixedStepsPerFrame + ) { RuntimeFixedFrame fixedFrame = m_clock.BeginFixedStep(options.fixedDeltaTime); subsystems.FixedUpdate(fixedFrame); m_fixedAccumulator -= options.fixedDeltaTime; steps++; } if (steps == options.maxFixedStepsPerFrame - && m_fixedAccumulator >= options.fixedDeltaTime) - { + && m_fixedAccumulator >= options.fixedDeltaTime + ) { m_fixedAccumulator = 0f; } } @@ -255,7 +207,9 @@ public void Tick(float deltaTime) try { if (subsystemFrameActive) + { subsystems.EndFrame(frame); + } } finally { @@ -305,8 +259,75 @@ public void Dispose() finally { if (m_disposed) + { m_host.Release(this); + } + } + } + + internal void Start() + { + m_jobs = new JobScheduler( + options.jobExecutionMode switch + { + RuntimeJobExecutionMode.SingleThread => JobExecutionMode.SingleThread, + RuntimeJobExecutionMode.WorkerPool => JobExecutionMode.WorkerPool, + _ => throw new ArgumentOutOfRangeException( + nameof(options), + options.jobExecutionMode, + "Unknown runtime job execution mode." + ) + }, + new JobSchedulerOptions + { + workerCount = options.jobWorkerCount + } + ); + scenes = new SceneWorld(m_identities, m_host.types); + if (options.createLogSink is not null) + { + ILogSink sink = options.createLogSink(sessionID) + ?? throw new InvalidOperationException("The session log factory returned no sink."); + m_sessionLog = new SessionLogSink(sessionID, sink); + m_host.logs.RegisterSink(m_sessionLog); + } + using IDisposable scope = EnterExecutionScope(); + if (options.contentStore is not null) + { + m_serialization = m_host.serialization.CaptureGeneration(); + m_assets = new AssetDatabase( + options.contentStore, + m_serialization, + m_host.types.current, + m_identities, + options.assetResidencyBudgetBytes, + options.assetPreparationBudgetBytes + ); } + IReferenceResolver[] referenceResolvers = m_assets is IReferenceResolver assetResolver + ? [.. options.referenceResolvers, assetResolver] + : [.. options.referenceResolvers]; + IAssetReferenceResolver? prefabAssets = m_assets + ?? options.referenceResolvers.OfType().SingleOrDefault(); + if (prefabAssets is not null) + { + scenes.ConfigurePrefabInstantiation(m_host.serialization, prefabAssets); + } + m_references = referenceResolvers.Length == 0 + ? ReferenceCatalog.empty + : ReferenceCatalog.Create(1, referenceResolvers); + var context = new RuntimeSubsystemContext( + events, + m_host.diagnostics, + m_identities, + m_host.types, + new LifetimeScope(), + RuntimeSubsystemLifetime.Session, + options.kind == RuntimeSessionKind.Edit, + options.capabilities + ); + m_subsystems = new RuntimeSubsystemPipeline(context, m_host.retirementTimeout, m_host.generations); + m_subsystems.Start([new SceneRuntimeSubsystemFactory(scenes, options.kind), .. options.createSubsystems(this)]); } internal void DisposeFromHost() => Retire(); @@ -314,12 +335,16 @@ public void Dispose() private void Retire() { if (m_disposed) + { return; + } m_host.generations.EnsureRetirementSafe(); try { if (!m_retirement.TryComplete(DisposeCore)) - throw new RetirementPendingException($"Runtime session {sessionId} is still draining owned work."); + { + throw new RetirementPendingException($"Runtime session {sessionID} is still draining owned work."); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -340,16 +365,24 @@ private void Retire() private void DisposeCore() { if (m_disposed) + { return; + } try { using IDisposable? scope = scenes is null ? null : EnterExecutionScope(); if (m_subsystems is not null) + { DisposeStage(m_subsystems, ref m_retirementFailures); + } if (m_assets is not null) + { DisposeStage(m_assets, ref m_retirementFailures); + } if (scenes is not null) + { DisposeStage(scenes, ref m_retirementFailures); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -363,9 +396,13 @@ private void DisposeCore() m_disposed = true; DisposeStage(m_coroutines, ref m_retirementFailures); if (m_jobs is not null) + { DisposeStage(m_jobs, ref m_retirementFailures); + } if (m_serialization is not null) + { DisposeStage(m_serialization, ref m_retirementFailures); + } if (m_sessionLog is not null) { m_host.logs.UnregisterSink(m_sessionLog); @@ -373,7 +410,10 @@ private void DisposeCore() } if (m_retirementFailures is not null) { - var failure = new AggregateException("Runtime session disposal encountered one or more failures.", m_retirementFailures); + var failure = new AggregateException( + "Runtime session disposal encountered one or more failures.", + m_retirementFailures + ); m_retirementFailures = null; throw failure; } @@ -382,17 +422,27 @@ private void DisposeCore() private static RuntimeSessionOptions Validate(RuntimeSessionOptions options) { ArgumentNullException.ThrowIfNull(options); - ArgumentException.ThrowIfNullOrWhiteSpace(options.applicationId); + ArgumentException.ThrowIfNullOrWhiteSpace(options.applicationID); if (!float.IsFinite(options.fixedDeltaTime) || options.fixedDeltaTime <= 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Fixed delta time must be positive."); + } if (options.assetResidencyBudgetBytes < 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Asset residency budget cannot be negative."); + } if (options.assetPreparationBudgetBytes <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Asset preparation budget must be positive."); + } if (!float.IsFinite(options.maxFrameDeltaTime) || options.maxFrameDeltaTime <= 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Maximum frame delta time must be positive."); + } if (options.maxFixedStepsPerFrame <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Maximum fixed steps must be positive."); + } if (options.kind == RuntimeSessionKind.Player && options.contentStore is null) { throw new ArgumentException("A Player session requires an immutable content store.", nameof(options)); @@ -400,7 +450,7 @@ private static RuntimeSessionOptions Validate(RuntimeSessionOptions options) return new RuntimeSessionOptions { kind = options.kind, - applicationId = options.applicationId, + applicationID = options.applicationID, contentStore = options.contentStore, createLogSink = options.createLogSink, assetResidencyBudgetBytes = options.assetResidencyBudgetBytes, @@ -411,11 +461,13 @@ private static RuntimeSessionOptions Validate(RuntimeSessionOptions options) jobExecutionMode = options.jobExecutionMode, jobWorkerCount = options.jobWorkerCount, createSubsystems = options.createSubsystems - ?? throw new ArgumentException("Runtime subsystem factories cannot be null.", nameof(options)), - capabilities = Array.AsReadOnly(options.capabilities?.ToArray() - ?? throw new ArgumentException("Runtime capabilities cannot be null.", nameof(options))), + ?? throw new ArgumentException("Runtime subsystem factories cannot be null.", nameof(options)), + capabilities = Array.AsReadOnly( + options.capabilities?.ToArray() + ?? throw new ArgumentException("Runtime capabilities cannot be null.", nameof(options)) + ), referenceResolvers = options.referenceResolvers?.ToArray() - ?? throw new ArgumentException("Runtime reference resolvers cannot be null.", nameof(options)) + ?? throw new ArgumentException("Runtime reference resolvers cannot be null.", nameof(options)) }; } @@ -448,11 +500,14 @@ private sealed class ExecutionScope(IReadOnlyList scopes) : IDispos public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; for (int index = scopes.Count - 1; index >= 0; index--) + { scopes[index].Dispose(); + } } } - } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs index 5e33da03d..5ca061cb4 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs @@ -9,12 +9,10 @@ public enum RuntimeSessionKind /// An authoring session whose scene world remains editable. /// Edit, - /// /// A disposable Editor play-test session created from an immutable start snapshot. /// Play, - /// /// A deployed standalone game session backed only by runtime artifacts. /// diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs index 9a20efe8e..c239c4748 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs @@ -1,10 +1,9 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; - -using Inno.References; using Inno.Content; using Inno.Core.Logging; +using Inno.References; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -21,7 +20,7 @@ public sealed class RuntimeSessionOptions /// /// Gets or initializes the stable application identifier used to isolate persistent data. /// - public string applicationId { get; init; } = "inno.application"; + public string applicationID { get; init; } = "inno.application"; /// /// Gets or initializes the immutable content store borrowed for the session lifetime. @@ -40,7 +39,7 @@ public sealed class RuntimeSessionOptions /// and is disposed during retirement when it implements IDisposable. /// A null factory leaves logging to the host router's existing sinks. /// - public Func? createLogSink { get; init; } + public Func? createLogSink { get; init; } /// /// Gets or initializes the runtime asset payload residency budget in bytes. @@ -80,13 +79,12 @@ public sealed class RuntimeSessionOptions /// /// Gets or initializes the backend-neutral subsystem factories composed into each session. /// - public Func> createSubsystems { get; init; } - = static _ => Array.Empty(); + public Func> createSubsystems { get; init; } = static _ => []; /// /// Gets or initializes capabilities verified by composition for this session's selected services. /// - public IReadOnlyList capabilities { get; init; } = Array.Empty(); + public IReadOnlyList capabilities { get; init; } = []; /// /// Gets or initializes owner-provided resolvers included in this session's immutable reference catalog. @@ -94,6 +92,5 @@ public sealed class RuntimeSessionOptions /// /// A deployed AssetDatabase automatically contributes its asset resolver and must not be repeated here. /// - public IReadOnlyList referenceResolvers { get; init; } - = Array.Empty(); + public IReadOnlyList referenceResolvers { get; init; } = []; } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs index a5502c45e..46caf728d 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs @@ -5,29 +5,33 @@ namespace Inno.Runtime; internal sealed class SessionLogSink : ILogSink, IDisposable { - private readonly LogSessionId m_sessionId; + private readonly LogSessionID m_sessionID; private ILogSink? m_sink; internal SessionLogSink( - LogSessionId sessionId, + LogSessionID sessionID, ILogSink sink ) { - m_sessionId = sessionId; + m_sessionID = sessionID; m_sink = sink; } - /// + /// public void Receive(LogEntry entry) { - if (entry.sessionId == m_sessionId) + if (entry.sessionID == m_sessionID) + { m_sink?.Receive(entry); + } } - /// + /// public void Dispose() { if (m_sink is IDisposable owner) + { owner.Dispose(); + } m_sink = null; } } diff --git a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs index 660ae681b..f9d138106 100644 --- a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs +++ b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; @@ -10,19 +9,19 @@ namespace Inno.Runtime; /// Defines the project-wide game presentation area shared by Editor previews and deployed Players. /// [GenerateSerializationConverter] -[StableTypeId("4068d172-87ac-41b3-ae64-247d25889336")] -[ProjectSettingDefinition(GamePresentationSettings.settingProtocolId)] +[StableTypeID("4068d172-87ac-41b3-ae64-247d25889336")] +[ProjectSettingDefinition(GamePresentationSettings.C_SETTING_PROTOCOL_ID)] public sealed class GamePresentationSettings : ISerializable { /// /// Gets the immutable project-setting protocol value used by discovery metadata. /// - public const string settingProtocolId = "inno.runtime.game-presentation"; + public const string C_SETTING_PROTOCOL_ID = "inno.runtime.game-presentation"; /// /// Gets the stable project-setting identity for game presentation. /// - public static ProjectSettingId settingId => new(settingProtocolId); + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); /// /// Gets or sets whether the complete reference frame is fitted inside the available surface. @@ -66,7 +65,9 @@ int availableHeight ArgumentOutOfRangeException.ThrowIfNegativeOrZero(referenceWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(referenceHeight); if (!preserveAspectRatio) + { return new GamePresentationViewport(0, 0, availableWidth, availableHeight); + } double targetAspect = referenceWidth / (double)referenceHeight; int width = availableWidth; @@ -81,63 +82,7 @@ int availableHeight (availableWidth - width) / 2, (availableHeight - height) / 2, width, - height); - } -} - -/// -/// Stores one centered game-content region within a presentation surface. -/// -public readonly record struct GamePresentationViewport -{ - /// - /// Creates a validated game presentation viewport. - /// - /// - /// Non-negative horizontal offset. - /// - /// - /// Non-negative vertical offset. - /// - /// - /// Positive content width. - /// - /// - /// Positive content height. - /// - public GamePresentationViewport( - int x, - int y, - int width, - int height - ) { - ArgumentOutOfRangeException.ThrowIfNegative(x); - ArgumentOutOfRangeException.ThrowIfNegative(y); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - this.x = x; - this.y = y; - this.width = width; - this.height = height; + height + ); } - - /// - /// Gets the horizontal content offset. - /// - public int x { get; } - - /// - /// Gets the vertical content offset. - /// - public int y { get; } - - /// - /// Gets the content width. - /// - public int width { get; } - - /// - /// Gets the content height. - /// - public int height { get; } } diff --git a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs new file mode 100644 index 000000000..8fc7e1487 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Runtime; + +/// +/// Stores one centered game-content region within a presentation surface. +/// +public readonly record struct GamePresentationViewport +{ + /// + /// Creates a validated game presentation viewport. + /// + /// + /// Non-negative horizontal offset. + /// + /// + /// Non-negative vertical offset. + /// + /// + /// Positive content width. + /// + /// + /// Positive content height. + /// + public GamePresentationViewport( + int x, + int y, + int width, + int height + ) { + ArgumentOutOfRangeException.ThrowIfNegative(x); + ArgumentOutOfRangeException.ThrowIfNegative(y); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + /// + /// Gets the horizontal content offset. + /// + public int x { get; } + + /// + /// Gets the vertical content offset. + /// + public int y { get; } + + /// + /// Gets the content width. + /// + public int width { get; } + + /// + /// Gets the content height. + /// + public int height { get; } +} diff --git a/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs b/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs index ed98d10eb..5a385c4c3 100644 --- a/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs +++ b/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs @@ -1,11 +1,6 @@ -using Inno.Scripting.Api; using Inno.Runtime; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Core", - "Inno.Runtime", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Core", "Inno.Runtime", ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport( - typeof(Time), - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(Time), ScriptingApiScope.Runtime)] diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs index 804abdfed..d5e64deea 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs @@ -33,8 +33,10 @@ IReadOnlyList frameworkAssemblies ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(frameworkAssemblies); if (assemblies.Any(static assembly => assembly is null || assembly.IsCollectible) - || frameworkAssemblies.Any(static assembly => assembly is null || assembly.IsCollectible)) + || frameworkAssemblies.Any(static assembly => assembly is null || assembly.IsCollectible) + ) { throw new ArgumentException("A static catalog requires noncollectible linked assemblies.", nameof(assemblies)); + } m_assemblies = Array.AsReadOnly(assemblies.Distinct().ToArray()); m_framework = frameworkAssemblies.ToHashSet(); m_frameworkNames = frameworkAssemblies.Select(static assembly => assembly.GetName().Name!) @@ -42,41 +44,43 @@ IReadOnlyList frameworkAssemblies m_sharedAssemblies = Array.AsReadOnly(m_assemblies.Concat(frameworkAssemblies).Distinct().ToArray()); } - /// + /// public event Action? changed { - add { ObjectDisposedException.ThrowIf(m_disposed, this); } - remove { } + add => ObjectDisposedException.ThrowIf(m_disposed, this); + remove {} } - /// + /// public IReadOnlyList GetAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); return m_assemblies; } - /// + /// public IReadOnlyList GetSharedAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); return m_sharedAssemblies; } - /// + /// public bool IsFrameworkReference(string assemblyName) { ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentException.ThrowIfNullOrWhiteSpace(assemblyName); return m_frameworkNames.Contains(assemblyName); } - /// + + /// public bool IsFrameworkAssembly(Assembly assembly) { ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(assembly); return m_framework.Contains(assembly); } - /// + + /// public void Dispose() => m_disposed = true; } diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs index eaf0a1eb1..b768dfd77 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs @@ -42,30 +42,45 @@ IReadOnlyList dependencies ArgumentNullException.ThrowIfNull(dependencies); ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Any(static assembly => assembly is null || assembly.IsCollectible)) + { throw new ArgumentException("A static module requires noncollectible linked assemblies.", nameof(assemblies)); - m_contribution = new ModuleCatalogContribution(moduleName, domain, scope, assemblies, - assemblies.ToDictionary(static assembly => assembly, _ => scope)); - upstreamModuleNames = Array.AsReadOnly(dependencies.ToArray()); - assemblyScopes = new ReadOnlyDictionary( - assemblies.ToDictionary(static assembly => assembly.GetName().Name!, _ => scope, StringComparer.OrdinalIgnoreCase)); + } + m_contribution = new ModuleCatalogContribution( + moduleName, + domain, + scope, + assemblies, + assemblies.ToDictionary(static assembly => assembly, _ => scope) + ); + this.upstreamModuleNames = Array.AsReadOnly(dependencies.ToArray()); + this.assemblyScopes = new ReadOnlyDictionary( + assemblies.ToDictionary(static assembly => assembly.GetName().Name!, _ => scope, StringComparer.OrdinalIgnoreCase) + ); } - /// + /// public string moduleName => m_contribution.moduleName; - /// + + /// public AssemblyDomain domain => m_contribution.domain; - /// + + /// public AssemblyScope scope => m_contribution.scope; - /// + + /// public bool collectible => false; - /// + + /// public IReadOnlyList upstreamModuleNames { get; } - /// + + /// public IReadOnlyDictionary assemblyScopes { get; } - /// + + /// public IReadOnlyList GetAssemblyNames() => m_contribution.assemblies.Select(static assembly => assembly.GetName().Name!).ToArray(); - /// + + /// public ModuleCatalogContribution Prepare(ModuleSourceContext context) { ArgumentNullException.ThrowIfNull(context); diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs index 779ca707d..045c39cde 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Runtime; @@ -52,7 +51,9 @@ public StaticTypeCatalogSource(IReadOnlyList> cata foreach (Type type in m_factories.Keys.Where(static type => type.IsConstructedGenericType)) { if (!m_metadata.ContainsKey(type.GetGenericTypeDefinition())) + { throw new ArgumentException($"Linked construction '{type}' has no registered declaration.", nameof(catalogs)); + } } m_constructions = m_factories.Keys.Where(static type => type.IsConstructedGenericType) .GroupBy(static type => type.GetGenericTypeDefinition()) @@ -60,30 +61,40 @@ public StaticTypeCatalogSource(IReadOnlyList> cata foreach ((Type definition, List arguments) in m_rejectedConstructions) { if (!m_metadata.ContainsKey(definition)) + { throw new ArgumentException($"Rejected construction '{definition}' has no registered declaration.", nameof(catalogs)); - if (m_constructions.TryGetValue(definition, out Type[]? constructions) && - constructions.Any(construction => arguments.Any(values => construction.GenericTypeArguments.SequenceEqual(values)))) + } + if (m_constructions.TryGetValue(definition, out Type[]? constructions) + && constructions.Any(construction => arguments.Any(values => construction.GenericTypeArguments.SequenceEqual(values))) + ) { throw new ArgumentException($"A linked construction of '{definition}' is also recorded as rejected.", nameof(catalogs)); + } } m_types = m_metadata.Keys.GroupBy(static type => type.Assembly).ToDictionary( static group => group.Key, - static group => (IReadOnlyList)Array.AsReadOnly(group.OrderBy(static type => type.FullName, - StringComparer.Ordinal).ToArray())); + static group => (IReadOnlyList)Array.AsReadOnly( + group.OrderBy(static type => type.FullName, StringComparer.Ordinal).ToArray() + ) + ); foreach (Assembly assembly in assemblies) - m_types.TryAdd(assembly, Array.Empty()); + { + m_types.TryAdd(assembly, []); + } } - /// + /// public IReadOnlyList GetTypes(Assembly assembly) - => m_types.TryGetValue(assembly, out IReadOnlyList? types) ? types - : throw new InvalidOperationException($"Linked assembly '{assembly.GetName().Name}' has no generated type catalog."); + => m_types.TryGetValue(assembly, out IReadOnlyList? types) + ? types + : throw new InvalidOperationException($"Linked assembly '{assembly.GetName().Name}' has no generated type catalog."); - /// + /// public TypeCatalogMetadata GetMetadata(Type type) - => m_metadata.TryGetValue(type, out TypeCatalogMetadata? metadata) ? metadata - : throw new InvalidOperationException($"Linked declaration '{type}' has no generated metadata."); + => m_metadata.TryGetValue(type, out TypeCatalogMetadata? metadata) + ? metadata + : throw new InvalidOperationException($"Linked declaration '{type}' has no generated metadata."); - /// + /// public Type? ConstructGenericType( Type definition, IReadOnlyList arguments @@ -91,33 +102,42 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); ValidateArguments(definition, arguments); - if (m_rejectedConstructions.TryGetValue(definition, out List? rejected) && - rejected.Any(values => values.SequenceEqual(arguments))) + if (m_rejectedConstructions.TryGetValue(definition, out List? rejected) + && rejected.Any(values => values.SequenceEqual(arguments)) + ) { return null; + } if (m_constructions.TryGetValue(definition, out Type[]? constructions)) { foreach (Type construction in constructions) { if (construction.GenericTypeArguments.SequenceEqual(arguments)) + { return construction; + } } } - throw new NotSupportedException($"Generic construction '{definition}' with arguments " + - $"'{string.Join(", ", arguments)}' is absent from the linked factory catalog."); + throw new NotSupportedException( + $"Generic construction '{definition}' with arguments " + + $"'{string.Join(", ", arguments)}' is absent from the linked factory catalog." + ); } - /// + /// public bool CanCreateInstance(Type type) => m_factories.TryGetValue(type, out Func? factory) && factory is not null; - /// + /// public object CreateInstance(Type type) { if (!m_factories.TryGetValue(type, out Func? factory) || factory is null) + { throw new InvalidOperationException($"Linked type '{type}' has no generated parameterless factory."); + } object instance = factory(); - return type.IsInstanceOfType(instance) ? instance - : throw new InvalidOperationException($"The linked factory for '{type}' returned an incompatible instance."); + return type.IsInstanceOfType(instance) + ? instance + : throw new InvalidOperationException($"The linked factory for '{type}' returned an incompatible instance."); } private static void ValidateArguments( @@ -127,10 +147,14 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!definition.IsGenericTypeDefinition) + { throw new ArgumentException("The declaration must be a generic type definition.", nameof(definition)); - if (arguments.Count != definition.GetGenericArguments().Length || - arguments.Any(static argument => argument is null || argument.ContainsGenericParameters)) + } + if (arguments.Count != definition.GetGenericArguments().Length + || arguments.Any(static argument => argument is null || argument.ContainsGenericParameters) + ) { throw new ArgumentException("The complete closed type argument set is required.", nameof(arguments)); + } } private sealed class Registration : ITypeCatalogRegistrar @@ -138,10 +162,10 @@ private sealed class Registration : ITypeCatalogRegistrar internal readonly Dictionary?> factories = []; internal readonly Dictionary metadata = []; internal readonly Dictionary> rejectedConstructions = []; - private bool m_sealed; private readonly int m_ownerThread = Environment.CurrentManagedThreadId; + private bool m_sealed; - /// + /// public void Register( TypeCatalogMetadata metadata, Func? factory @@ -149,11 +173,13 @@ public void Register( RequireOpen(); ArgumentNullException.ThrowIfNull(metadata); if (!this.metadata.TryAdd(metadata.type, metadata)) + { throw new ArgumentException($"Static declaration '{metadata.type}' is registered more than once."); + } factories.Add(metadata.type, factory); } - /// + /// public void RegisterFactory( Type type, Func factory @@ -162,12 +188,14 @@ Func factory ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(factory); if (!type.IsConstructedGenericType || type.ContainsGenericParameters) + { throw new ArgumentException("A linked factory requires a fully closed generic type.", nameof(type)); + } // Different assembly-local catalogs can link the same closed construction. factories.TryAdd(type, factory); } - /// + /// public void RejectGenericConstruction( Type definition, IReadOnlyList arguments @@ -175,9 +203,13 @@ IReadOnlyList arguments RequireOpen(); ValidateArguments(definition, arguments); if (!rejectedConstructions.TryGetValue(definition, out List? rejected)) + { rejectedConstructions.Add(definition, rejected = []); + } if (!rejected.Any(values => values.SequenceEqual(arguments))) + { rejected.Add(arguments.ToArray()); + } } internal void Seal() => m_sealed = true; @@ -185,9 +217,13 @@ IReadOnlyList arguments private void RequireOpen() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Type catalog contributions must run on the composition thread."); + } if (m_sealed) + { throw new InvalidOperationException("The type catalog contribution has already completed."); + } } } } diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs index 1c58b9aa9..06f196539 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs @@ -1,10 +1,11 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.ExceptionServices; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Extensibility.Reload; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -18,9 +19,9 @@ public sealed class RuntimeSubsystemPipeline : IDisposable private readonly RuntimeSubsystemContext m_context; private readonly List m_retirementFailures = []; private readonly List m_startupDiagnostics = []; - private DiagnosticReporter? m_reporter; private readonly TimeSpan m_retirementTimeout; private readonly GenerationCoordinator m_generations; + private DiagnosticReporter? m_reporter; private int m_begunEntryCount; private bool m_frameOpen; private bool m_disposed; @@ -51,67 +52,6 @@ GenerationCoordinator generations m_generations = generations; } - internal void Start(IReadOnlyList configuredFactories) - { - ArgumentNullException.ThrowIfNull(configuredFactories); - try - { - IRuntimeSubsystemFactory[] ordered = Order(configuredFactories.Select(static factory => - (IRuntimeSubsystemFactory)new FactorySnapshot(factory)).ToArray()); - if (ordered.Any(factory => factory.descriptor.lifetime != m_context.lifetime)) - throw new InvalidOperationException($"Subsystem lifetime does not match its {m_context.lifetime} owner."); - m_reporter = m_resources.Own(m_context.diagnostics.CreateReporter(new DiagnosticSource( - $"inno.runtime.subsystems.{m_context.identities.domainId}", "Runtime subsystems"))); - foreach (IRuntimeSubsystemFactory factory in ordered) - { - RuntimeSubsystemDescriptor descriptor = factory.descriptor; - string? unavailable = UnavailableReason(descriptor); - if (unavailable is not null) - { - RejectOrReport(descriptor, unavailable); - continue; - } - var entry = new Entry(descriptor); - m_entries.Add(entry); - try - { - var context = new RuntimeSubsystemContext(m_context.events, m_context.diagnostics, - m_context.identities, m_context.types, entry.resources, m_context.lifetime, - m_context.isEditMode, m_context.capabilities); - entry.subsystem = factory.Create(context) - ?? throw new InvalidOperationException($"Runtime subsystem factory '{descriptor.id}' returned null."); - entry.subsystem.Attach(); - entry.isAttached = true; - } - catch (Exception failure) when (descriptor.requirement == RuntimeSubsystemRequirement.Optional - && failure is not RetirementPendingException - && m_generations.state != GenerationState.Faulted) - { - // Optional startup can degrade only after the exact candidate owner has retired completely. - try - { - new RetirementBarrier($"Optional subsystem {descriptor.id}", m_retirementTimeout) - .Wait(() => RetireEntry(entry)); - } - catch (Exception cleanupFailure) - { - m_generations.Fault(new AggregateException( - $"Optional subsystem '{descriptor.id}' could not compensate startup.", failure, cleanupFailure)); - throw; - } - m_entries.RemoveAt(m_entries.Count - 1); - RejectOrReport(descriptor, $"Startup failed: {failure.Message}"); - } - } - m_started = true; - } - catch - { - m_stopping = true; - throw; - } - } - /// /// Gets the active immutable subsystem descriptors in execution order. /// @@ -148,10 +88,10 @@ public TFeature GetRequiredSubsystem() return matches.Length switch { 1 => matches[0], - 0 => throw new InvalidOperationException( - $"No runtime subsystem implements '{typeof(TFeature).FullName}'."), + 0 => throw new InvalidOperationException($"No runtime subsystem implements '{typeof(TFeature).FullName}'."), _ => throw new InvalidOperationException( - $"Multiple runtime subsystems implement '{typeof(TFeature).FullName}'.") + $"Multiple runtime subsystems implement '{typeof(TFeature).FullName}'." + ) }; } @@ -165,7 +105,9 @@ public void BeginFrame(RuntimeFrame frame) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("A runtime subsystem frame is already active."); + } m_frameOpen = true; m_begunEntryCount = 0; for (int index = 0; index < m_entries.Count; index++) @@ -261,16 +203,21 @@ public void RenderFrame( state ) => subsystem.AfterRender(state), frame, - preparedCount); + preparedCount + ); } catch (Exception failure) { failures.Add(failure); } if (failures.Count == 1) - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failures[0]).Throw(); + { + ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } if (failures.Count > 1) + { throw new AggregateException("Subsystem output and cleanup failed.", failures); + } } /// @@ -282,7 +229,9 @@ public void RenderFrame( public void EndFrame(RuntimeFrame frame) { if (!m_frameOpen) + { return; + } try { ExecuteReverse( @@ -291,7 +240,8 @@ public void EndFrame(RuntimeFrame frame) state ) => subsystem.EndFrame(state), frame, - m_begunEntryCount); + m_begunEntryCount + ); } finally { @@ -309,7 +259,9 @@ public void EndFrame(RuntimeFrame frame) public void Dispose() { if (m_disposed) + { return; + } m_stopping = true; m_frameOpen = false; Release(); @@ -334,43 +286,244 @@ public void Dispose() } } + internal void Start(IReadOnlyList configuredFactories) + { + ArgumentNullException.ThrowIfNull(configuredFactories); + try + { + IRuntimeSubsystemFactory[] ordered = Order( + configuredFactories.Select(static factory => + (IRuntimeSubsystemFactory)new FactorySnapshot(factory)).ToArray() + ); + if (ordered.Any(factory => factory.descriptor.lifetime != m_context.lifetime)) + { + throw new InvalidOperationException($"Subsystem lifetime does not match its {m_context.lifetime} owner."); + } + m_reporter = m_resources.Own( + m_context.diagnostics.CreateReporter( + new DiagnosticSource( + $"inno.runtime.subsystems.{m_context.identities.domainID}", + "Runtime subsystems" + ) + ) + ); + foreach (IRuntimeSubsystemFactory factory in ordered) + { + RuntimeSubsystemDescriptor descriptor = factory.descriptor; + string? unavailable = UnavailableReason(descriptor); + if (unavailable is not null) + { + RejectOrReport(descriptor, unavailable); + continue; + } + var entry = new Entry(descriptor); + m_entries.Add(entry); + try + { + var context = new RuntimeSubsystemContext( + m_context.events, + m_context.diagnostics, + m_context.identities, + m_context.types, + entry.resources, + m_context.lifetime, + m_context.isEditMode, + m_context.capabilities + ); + entry.subsystem = factory.Create(context) + ?? throw new InvalidOperationException($"Runtime subsystem factory '{descriptor.id}' returned null."); + entry.subsystem.Attach(); + entry.isAttached = true; + } + catch (Exception failure) when (descriptor.requirement == RuntimeSubsystemRequirement.Optional + && failure is not RetirementPendingException + && m_generations.state != GenerationState.Faulted) + { + // Optional startup can degrade only after the exact candidate owner has retired completely. + try + { + new RetirementBarrier($"Optional subsystem {descriptor.id}", m_retirementTimeout) + .Wait(() => RetireEntry(entry)); + } + catch (Exception cleanupFailure) + { + m_generations.Fault( + new AggregateException( + $"Optional subsystem '{descriptor.id}' could not compensate startup.", + failure, + cleanupFailure + ) + ); + throw; + } + m_entries.RemoveAt(m_entries.Count - 1); + RejectOrReport(descriptor, $"Startup failed: {failure.Message}"); + } + } + m_started = true; + } + catch + { + m_stopping = true; + throw; + } + } + + private void Release() + { + while (m_entries.Count > 0) + { + Entry entry = m_entries[^1]; + try + { + RetireEntry(entry); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception exception) + { + m_retirementFailures.Add(exception); + } + m_entries.RemoveAt(m_entries.Count - 1); + } + } + + private string? UnavailableReason(RuntimeSubsystemDescriptor descriptor) + { + RuntimeCapabilityID[] missing = descriptor.requiredCapabilities.Where(id => !m_context.capabilities.Contains(id)).ToArray(); + if (missing.Length > 0) + { + return $"Missing capabilities: {string.Join(", ", missing)}."; + } + RuntimeSubsystemID[] dependencies = descriptor.dependencies + .Where(id => !m_entries.Any(entry => entry.descriptor.id == id && entry.isAttached)) + .ToArray(); + return dependencies.Length == 0 ? null : $"Unavailable dependencies: {string.Join(", ", dependencies)}."; + } + + private void RejectOrReport( + RuntimeSubsystemDescriptor descriptor, + string reason + ) { + if (descriptor.requirement == RuntimeSubsystemRequirement.Required) + { + throw new InvalidOperationException($"Required subsystem '{descriptor.id}' cannot start: {reason}"); + } + var diagnostic = new Diagnostic( + "runtime.subsystem.unavailable", + reason, + DiagnosticSeverity.Warning, + semanticID: descriptor.id.value + ); + m_startupDiagnostics.Add(diagnostic); + m_reporter!.Publish(diagnostic); + } + + private void ExecuteForward( + Action action, + TState state + ) { + foreach (Entry entry in m_entries) + { + action(entry.subsystem, state); + } + } + + private void ExecuteReverse( + Action action, + TState state, + int count + ) { + List? failures = null; + for (int index = count - 1; index >= 0; index--) + { + try + { + action(m_entries[index].subsystem, state); + } + catch (Exception exception) + { + failures ??= []; + failures.Add(exception); + } + } + if (failures is not null) + { + throw new AggregateException("One or more runtime subsystem phases failed.", failures); + } + } + + private void EnsureActive() + { + ObjectDisposedException.ThrowIf(m_disposed, this); + if (m_stopping) + { + throw new InvalidOperationException("The subsystem pipeline is retiring and cannot execute new work."); + } + if (!m_started) + { + throw new InvalidOperationException("The subsystem pipeline has not finished startup."); + } + } + + private void EnsureFrame() + { + EnsureActive(); + if (!m_frameOpen) + { + throw new InvalidOperationException("No runtime subsystem frame is active."); + } + } + private static IRuntimeSubsystemFactory[] Order(IReadOnlyList factories) { - var byId = new Dictionary(); + var byID = new Dictionary(); foreach (IRuntimeSubsystemFactory factory in factories) { ArgumentNullException.ThrowIfNull(factory); RuntimeSubsystemDescriptor descriptor = factory.descriptor ?? throw new InvalidOperationException("A runtime subsystem factory returned a null descriptor."); - if (!byId.TryAdd(descriptor.id, factory)) + if (!byID.TryAdd(descriptor.id, factory)) + { throw new InvalidOperationException($"Runtime subsystem ID '{descriptor.id}' is duplicated."); + } } foreach (IRuntimeSubsystemFactory factory in factories) { - foreach (RuntimeSubsystemId dependency in factory.descriptor.dependencies) + foreach (RuntimeSubsystemID dependency in factory.descriptor.dependencies) { - if (!byId.ContainsKey(dependency) && factory.descriptor.requirement == RuntimeSubsystemRequirement.Required) + if (!byID.ContainsKey(dependency) && factory.descriptor.requirement == RuntimeSubsystemRequirement.Required) { throw new InvalidOperationException( - $"Runtime subsystem '{factory.descriptor.id}' requires missing subsystem '{dependency}'."); + $"Runtime subsystem '{factory.descriptor.id}' requires missing subsystem '{dependency}'." + ); } } } - var incoming = factories.ToDictionary( + Dictionary incoming = factories.ToDictionary( static factory => factory.descriptor.id, - factory => factory.descriptor.dependencies.Count(byId.ContainsKey)); - var dependants = factories.ToDictionary( + factory => factory.descriptor.dependencies.Count(byID.ContainsKey) + ); + Dictionary> dependants = factories.ToDictionary( static factory => factory.descriptor.id, - static _ => new List()); + static _ => new List() + ); foreach (IRuntimeSubsystemFactory factory in factories) { - foreach (RuntimeSubsystemId dependency in factory.descriptor.dependencies) + foreach (RuntimeSubsystemID dependency in factory.descriptor.dependencies) + { if (dependants.TryGetValue(dependency, out List? consumers)) + { consumers.Add(factory); + } + } } var ready = new List( - factories.Where(factory => incoming[factory.descriptor.id] == 0)); + factories.Where(factory => incoming[factory.descriptor.id] == 0) + ); var result = new List(factories.Count); while (ready.Count > 0) { @@ -382,7 +535,9 @@ private static IRuntimeSubsystemFactory[] Order(IReadOnlyList pair.Value > 0) .Select(static pair => pair.Key.value) - .Order(StringComparer.Ordinal)); + .Order(StringComparer.Ordinal) + ); throw new InvalidOperationException($"Runtime subsystem dependencies contain a cycle: {unresolved}."); } return result.ToArray(); @@ -403,29 +559,8 @@ IRuntimeSubsystemFactory right ) { int order = left.descriptor.order.CompareTo(right.descriptor.order); return order != 0 - ? order - : StringComparer.Ordinal.Compare(left.descriptor.id.value, right.descriptor.id.value); - } - - private void Release() - { - while (m_entries.Count > 0) - { - Entry entry = m_entries[^1]; - try - { - RetireEntry(entry); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception exception) - { - m_retirementFailures.Add(exception); - } - m_entries.RemoveAt(m_entries.Count - 1); - } + ? order + : StringComparer.Ordinal.Compare(left.descriptor.id.value, right.descriptor.id.value); } private static void RetireEntry(Entry entry) @@ -482,74 +617,6 @@ private static void RetireEntry(Entry entry) } } - private string? UnavailableReason(RuntimeSubsystemDescriptor descriptor) - { - RuntimeCapabilityId[] missing = descriptor.requiredCapabilities.Where(id => !m_context.capabilities.Contains(id)).ToArray(); - if (missing.Length > 0) - return $"Missing capabilities: {string.Join(", ", missing)}."; - RuntimeSubsystemId[] dependencies = descriptor.dependencies - .Where(id => !m_entries.Any(entry => entry.descriptor.id == id && entry.isAttached)).ToArray(); - return dependencies.Length == 0 ? null : $"Unavailable dependencies: {string.Join(", ", dependencies)}."; - } - - private void RejectOrReport( - RuntimeSubsystemDescriptor descriptor, - string reason - ) { - if (descriptor.requirement == RuntimeSubsystemRequirement.Required) - throw new InvalidOperationException($"Required subsystem '{descriptor.id}' cannot start: {reason}"); - var diagnostic = new Diagnostic("runtime.subsystem.unavailable", reason, DiagnosticSeverity.Warning, - semanticId: descriptor.id.value); - m_startupDiagnostics.Add(diagnostic); - m_reporter!.Publish(diagnostic); - } - - private void ExecuteForward( - Action action, - TState state - ) { - foreach (Entry entry in m_entries) - action(entry.subsystem, state); - } - - private void ExecuteReverse( - Action action, - TState state, - int count - ) { - List? failures = null; - for (int index = count - 1; index >= 0; index--) - { - try - { - action(m_entries[index].subsystem, state); - } - catch (Exception exception) - { - failures ??= []; - failures.Add(exception); - } - } - if (failures is not null) - throw new AggregateException("One or more runtime subsystem phases failed.", failures); - } - - private void EnsureActive() - { - ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_stopping) - throw new InvalidOperationException("The subsystem pipeline is retiring and cannot execute new work."); - if (!m_started) - throw new InvalidOperationException("The subsystem pipeline has not finished startup."); - } - - private void EnsureFrame() - { - EnsureActive(); - if (!m_frameOpen) - throw new InvalidOperationException("No runtime subsystem frame is active."); - } - private sealed class Entry(RuntimeSubsystemDescriptor descriptor) { internal RuntimeSubsystemDescriptor descriptor { get; } = descriptor; @@ -569,8 +636,9 @@ private sealed class FactorySnapshot : IRuntimeSubsystemFactory internal FactorySnapshot(IRuntimeSubsystemFactory factory) { - m_factory = factory ?? throw new ArgumentNullException(nameof(factory)); - descriptor = factory.descriptor ?? throw new InvalidOperationException("A subsystem descriptor cannot be null."); + ArgumentNullException.ThrowIfNull(factory); + m_factory = factory; + this.descriptor = factory.descriptor ?? throw new InvalidOperationException("A subsystem descriptor cannot be null."); } /// diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs index 972d38d14..a736b8015 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs @@ -3,30 +3,6 @@ namespace Inno.Runtime; -internal sealed class SceneRuntimeSubsystemFactory( - SceneWorld scenes, - RuntimeSessionKind kind -) : IRuntimeSubsystemFactory -{ - internal static readonly RuntimeSubsystemId subsystemId = new("inno.runtime.scene"); - - /// - /// Gets the stable descriptor for the built-in scene simulation subsystem. - /// - public RuntimeSubsystemDescriptor descriptor { get; } = new(subsystemId, order: 0); - - /// - /// Creates the scene subsystem for the isolated runtime session. - /// - /// - /// The session context that supplies the scene world and session kind. - /// - /// - /// A new subsystem that advances the context's scene world. - /// - public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new SceneRuntimeSubsystem(scenes, kind); -} - internal sealed class SceneRuntimeSubsystem( SceneWorld scenes, RuntimeSessionKind sessionKind @@ -41,7 +17,9 @@ RuntimeSessionKind sessionKind protected override void OnFixedUpdate(RuntimeFixedFrame frame) { if (sessionKind != RuntimeSessionKind.Edit) + { scenes.FixedUpdate(frame.deltaTime); + } } /// @@ -53,7 +31,9 @@ protected override void OnFixedUpdate(RuntimeFixedFrame frame) protected override void OnUpdate(RuntimeFrame frame) { if (sessionKind != RuntimeSessionKind.Edit && !frame.isPaused) + { scenes.Update(frame.deltaTime); + } } /// @@ -65,6 +45,8 @@ protected override void OnUpdate(RuntimeFrame frame) protected override void OnLateUpdate(RuntimeFrame frame) { if (sessionKind != RuntimeSessionKind.Edit && !frame.isPaused) + { scenes.LateUpdate(frame.deltaTime); + } } } diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs new file mode 100644 index 000000000..7ec9f0a82 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs @@ -0,0 +1,28 @@ +using Inno.Runtime.Contracts; +using Inno.Scene; + +namespace Inno.Runtime; + +internal sealed class SceneRuntimeSubsystemFactory( + SceneWorld scenes, + RuntimeSessionKind kind +) : IRuntimeSubsystemFactory +{ + internal static readonly RuntimeSubsystemID SUBSYSTEM_ID = new("inno.runtime.scene"); + + /// + /// Gets the stable descriptor for the built-in scene simulation subsystem. + /// + public RuntimeSubsystemDescriptor descriptor { get; } = new(SUBSYSTEM_ID, order: 0); + + /// + /// Creates the scene subsystem for the isolated runtime session. + /// + /// + /// The session context that supplies the scene world and session kind. + /// + /// + /// A new subsystem that advances the context's scene world. + /// + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new SceneRuntimeSubsystem(scenes, kind); +} diff --git a/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs b/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs index 84d68659d..9efaa88d3 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs @@ -4,14 +4,25 @@ namespace Inno.Runtime.Generators; internal static class RuntimeRegistrationDiagnostics { - private static readonly DiagnosticDescriptor UnavailableConstruction = new( - "INNORUN002", "Static converter construction is unavailable", - "Serialization converter '{0}' cannot be linked: {1}", "Architecture", DiagnosticSeverity.Error, true); + private static readonly DiagnosticDescriptor UNAVAILABLE_CONSTRUCTION = new( + "INNORUN002", + "Static converter construction is unavailable", + "Serialization converter '{0}' cannot be linked: {1}", + "Architecture", + DiagnosticSeverity.Error, + true + ); internal static void ReportUnavailable( SourceProductionContext output, INamedTypeSymbol type, string reason - ) => output.ReportDiagnostic(Diagnostic.Create(UnavailableConstruction, - type.Locations.Length == 0 ? Location.None : type.Locations[0], type.ToDisplayString(), reason)); + ) => output.ReportDiagnostic( + Diagnostic.Create( + UNAVAILABLE_CONSTRUCTION, + type.Locations.Length == 0 ? Location.None : type.Locations[0], + type.ToDisplayString(), + reason + ) + ); } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs index 1d62bd425..ce92f0f85 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; namespace Inno.Runtime.Generators; @@ -12,18 +13,23 @@ namespace Inno.Runtime.Generators; [Generator] public sealed class RuntimeFactoryGenerator : IIncrementalGenerator { - /// + /// public void Initialize(IncrementalGeneratorInitializationContext context) { - var inputs = context.CompilationProvider.Combine(context.AnalyzerConfigOptionsProvider); + IncrementalValueProvider<(Compilation left, AnalyzerConfigOptionsProvider right)> inputs = context.CompilationProvider.Combine( + context.AnalyzerConfigOptionsProvider + ); context.RegisterSourceOutput(inputs, static ( output, input - ) => { - if (!input.Right.GlobalOptions.TryGetValue("build_property.InnoGeneratePlayerComposition", out string? enabled) - || !string.Equals(enabled, "true", StringComparison.OrdinalIgnoreCase)) + ) => + { + if (!input.right.GlobalOptions.TryGetValue("build_property.InnoGeneratePlayerComposition", out string? enabled) + || !string.Equals(enabled, "true", StringComparison.OrdinalIgnoreCase) + ) { return; - Generate(output, input.Left); + } + Generate(output, input.left); }); } @@ -33,15 +39,20 @@ Compilation compilation ) { string assemblyName = compilation.AssemblyName!; string? deploymentDefinition = compilation.GetTypeByMetadataName( - assemblyName + ".Generated.PlayerDeploymentDefinition")?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - var catalogs = new List<(string name, bool host)>(); + assemblyName + ".Generated.PlayerDeploymentDefinition" + )?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + List<(string name, bool host)> catalogs = []; foreach (IAssemblySymbol assembly in compilation.SourceModule.ReferencedAssemblySymbols) { if (assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is null) + { continue; + } string? domain = assembly.GetAttributes() - .Where(static attribute => attribute.AttributeClass?.ToDisplayString() - == "System.Reflection.AssemblyMetadataAttribute" && attribute.ConstructorArguments.Length == 2) + .Where(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "System.Reflection.AssemblyMetadataAttribute" + && attribute.ConstructorArguments.Length == 2 + )) .Where(static attribute => attribute.ConstructorArguments[0].Value as string == "Inno.AssemblyDomain") .Select(static attribute => attribute.ConstructorArguments[1].Value as string) .FirstOrDefault(); @@ -53,37 +64,58 @@ Compilation compilation right ) => StringComparer.Ordinal.Compare(left.name, right.name)); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(assemblyName).Append(".Generated;\n\n") + code.Append("namespace ") + .Append(assemblyName) + .Append(".Generated;\n\n") .Append("internal static class PlayerMetadataComposition\n{\n") .Append(" internal static global::Inno.Extensibility.Modules.IAssemblyCatalogSource CreateModules() =>\n") .Append(" new global::Inno.Runtime.StaticAssemblyCatalogSource([\n"); - foreach (var catalog in catalogs.Where(static catalog => catalog.host)) + foreach ((string name, bool host) catalog in catalogs.Where(static catalog => catalog.host)) + { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.assembly,\n"); + } code.Append(" ], [typeof(object).Assembly]);\n\n") .Append(" internal static global::Inno.Extensibility.Types.ITypeCatalogSource CreateTypes() =>\n") .Append(" new global::Inno.Runtime.StaticTypeCatalogSource([\n"); - foreach (var catalog in catalogs) + foreach ((string name, bool host) catalog in catalogs) + { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.Register,\n"); + } code.Append(" ]);\n\n") .Append(" internal static global::Inno.Core.Serialization.ISerializationMetadataSource CreateSerialization() =>\n") .Append(" new global::Inno.Core.Serialization.StaticSerializationMetadataSource([\n"); foreach (IAssemblySymbol assembly in compilation.SourceModule.ReferencedAssemblySymbols - .OrderBy(static assembly => assembly.Name, StringComparer.Ordinal)) + .OrderBy(static assembly => assembly.Name, StringComparer.Ordinal) + ) { if (assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeSerializationMetadataCatalog") is not null) - code.Append(" global::").Append(assembly.Name).Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n"); - code.Append(" global::").Append(assemblyName).Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n") + { + code + .Append(" global::") + .Append(assembly.Name) + .Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n"); + } + } + code.Append(" global::") + .Append(assemblyName) + .Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n") .Append(" ]);\n\n") .Append(" internal static global::Inno.Player.Runtime.IPlayerModuleActivator CreateActivator() =>\n") .Append(" new global::Inno.Player.Runtime.StaticPlayerModuleActivator(\n"); if (deploymentDefinition is null) { code.Append(" new global::Inno.Runtime.GameCodeDeployment([]),\n") - .Append(" new global::System.Collections.Generic.Dictionary>());\n"); + .Append( + " new global::System.Collections.Generic.Dictionary>());\n" + ); } else { - code.Append(" ").Append(deploymentDefinition).Append(".CreateDeployment(),\n") - .Append(" ").Append(deploymentDefinition).Append(".CreateAssemblies());\n"); + code.Append(" ") + .Append(deploymentDefinition) + .Append(".CreateDeployment(),\n") + .Append(" ") + .Append(deploymentDefinition) + .Append(".CreateAssemblies());\n"); } code.Append("}\n"); output.AddSource("Registration/RuntimeFactories.g.cs", code.ToString()); diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs index 8ed0f4665..a7db0a26d 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs @@ -20,34 +20,42 @@ public sealed class RuntimeModuleCatalogGenerator : IIncrementalGenerator /// The compiler's incremental registration boundary. /// public void Initialize(IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(context.CompilationProvider, static ( + => context.RegisterSourceOutput(context.CompilationProvider, static ( output, compilation ) => Generate(output, compilation)); - } private static void Generate( SourceProductionContext output, Compilation compilation ) { if (compilation.AssemblyName is null) + { return; + } INamedTypeSymbol[] types = EnumerateTypes(compilation.Assembly.GlobalNamespace) .Where(IsAccessible) .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal) .ToArray(); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(compilation.AssemblyName).Append(".Generated;\n\n") - .Append("/// \n/// Publishes this assembly's explicit static metadata without scanning its runtime types.\n/// \n") + code.Append("namespace ") + .Append(compilation.AssemblyName) + .Append(".Generated;\n\n") + .Append( + "/// \n/// Publishes this assembly's explicit static metadata without scanning its runtime types.\n/// \n" + ) .Append("public static class RuntimeModuleCatalog\n{\n") .Append(" /// \n /// Gets the assembly owning these declarations.\n /// \n") .Append(" public static global::System.Reflection.Assembly assembly => typeof(RuntimeModuleCatalog).Assembly;\n\n") - .Append(" /// \n /// Contributes declared types and available parameterless factories to one composition.\n /// \n") - .Append(" /// \n /// The composition-owned callback; this catalog does not retain it.\n /// \n") + .Append( + " /// \n /// Contributes declared types and available parameterless factories to one composition.\n /// \n" + ) + .Append( + " /// \n /// The composition-owned callback; this catalog does not retain it.\n /// \n" + ) .Append(" public static void Register(global::Inno.Extensibility.Catalogs.ITypeCatalogRegistrar register)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n"); - var constructors = new List(); + List constructors = []; foreach (INamedTypeSymbol type in types) { string typeName = GetTypeName(type); @@ -56,8 +64,8 @@ Compilation compilation { IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static value => value.Parameters.Length == 0); if (constructor is not null && constructor.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) - { + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { factory = FormatConstructorCall(type, constructors.Count); constructors.Add(type); } @@ -67,27 +75,48 @@ Compilation compilation } } code.Append(" register.Register(new global::Inno.Extensibility.Catalogs.TypeCatalogMetadata(typeof(") - .Append(typeName).Append(")") - .Append(", ").Append(FormatTypes(GetBaseTypes(type))) - .Append(", ").Append(FormatTypes(type.AllInterfaces)) - .Append(", ").Append(FormatAttributes(type.GetAttributes())) - .Append(", ").Append(FormatAttributes(GetInheritedAttributes(type))) - .Append(", ").Append(FormatOverrides(type)).Append("), ").Append(factory).Append(");\n"); + .Append(typeName) + .Append(")") + .Append(", ") + .Append(FormatTypes(GetBaseTypes(type))) + .Append(", ") + .Append(FormatTypes(type.AllInterfaces)) + .Append(", ") + .Append(FormatAttributes(type.GetAttributes())) + .Append(", ") + .Append(FormatAttributes(GetInheritedAttributes(type))) + .Append(", ") + .Append(FormatOverrides(type)) + .Append("), ") + .Append(factory) + .Append(");\n"); + } + ( + IReadOnlyList factories, + IReadOnlyList<(INamedTypeSymbol definition, ITypeSymbol[] arguments)> rejected + ) constructions = RuntimeTypeCatalogGenerator.Analyze(compilation, output); + foreach (INamedTypeSymbol type in constructions.factories.Where(static type => ( + !CanConstruct(type) + && GetBaseTypes(type).Any(static parent => ( + parent.OriginalDefinition.ToDisplayString() + == "Inno.Core.Serialization.Converters.SerializationConverter" + )) + )) + ) { + RuntimeRegistrationDiagnostics.ReportUnavailable( + output, + type, + "a nonabstract converter with a parameterless constructor is required" + ); } - var constructions = RuntimeTypeCatalogGenerator.Analyze(compilation, output); - foreach (INamedTypeSymbol type in constructions.factories.Where(static type => !CanConstruct(type) && - GetBaseTypes(type).Any(static parent => parent.OriginalDefinition.ToDisplayString() == - "Inno.Core.Serialization.Converters.SerializationConverter"))) - RuntimeRegistrationDiagnostics.ReportUnavailable(output, type, - "a nonabstract converter with a parameterless constructor is required"); foreach (INamedTypeSymbol type in constructions.factories.Where(CanConstruct)) { string name = GetTypeName(type); IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static value => value.Parameters.Length == 0); string factory; if (constructor is not null && constructor.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) - { + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { factory = FormatConstructorCall(type, constructors.Count); constructors.Add(type); } @@ -97,31 +126,46 @@ Compilation compilation } code.Append(" register.RegisterFactory(typeof(").Append(name).Append("), ").Append(factory).Append(");\n"); } - foreach (var rejection in constructions.rejected) + foreach ((INamedTypeSymbol definition, ITypeSymbol[] arguments) rejection in constructions.rejected) { - code.Append(" register.RejectGenericConstruction(typeof(").Append(GetTypeName(rejection.definition)) + code.Append(" register.RejectGenericConstruction(typeof(") + .Append(GetTypeName(rejection.definition)) .Append("), new global::System.Type[] { ") .Append(string.Join(", ", rejection.arguments.Select(argument => "typeof(" + FormatType(argument) + ")"))) .Append(" });\n"); } - if (types.Any(static type => type.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.GenerateSerializationConverterAttribute"))) - { - code.Append(" global::").Append(compilation.AssemblyName) + if (types.Any(static type => type.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.GenerateSerializationConverterAttribute" + ))) + ) { + code.Append(" global::") + .Append(compilation.AssemblyName) .Append(".Generated.RuntimeSerializationCatalog.Register(register);\n"); } code.Append(" }\n"); - code.Append("\n /// \n /// Resolves an explicitly registered declaration by its CLR metadata name.\n /// \n") + code + .Append( + "\n /// \n /// Resolves an explicitly registered declaration by its CLR metadata name.\n /// \n" + ) .Append(" /// \n /// The exact name emitted by the owning catalog.\n /// \n") - .Append(" /// \n /// The linked declaration; unknown names throw instead of probing assemblies.\n /// \n") - .Append(" /// \n /// The declaration is absent from this catalog.\n /// \n") + .Append( + " /// \n /// The linked declaration; unknown names throw instead of probing assemblies.\n /// \n" + ) + .Append( + " /// \n /// The declaration is absent from this catalog.\n /// \n" + ) .Append(" public static global::System.Type ResolveType(string metadataName) => metadataName switch\n {\n"); foreach (INamedTypeSymbol type in types) { - code.Append(" ").Append(Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) - .Append(" => typeof(").Append(GetTypeName(type)).Append("),\n"); + code.Append(" ") + .Append(SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) + .Append(" => typeof(") + .Append(GetTypeName(type)) + .Append("),\n"); } - code.Append(" _ => throw new global::System.ArgumentException(\"The declaration is not registered in this assembly.\", nameof(metadataName))\n };\n"); + code.Append( + " _ => throw new global::System.ArgumentException(\"The declaration is not registered in this assembly.\", nameof(metadataName))\n };\n" + ); for (int index = 0; index < constructors.Count; index++) { AppendConstructor(code, constructors[index], index); @@ -135,13 +179,17 @@ private static IEnumerable EnumerateTypes(INamespaceSymbol sou foreach (INamespaceSymbol child in source.GetNamespaceMembers()) { foreach (INamedTypeSymbol type in EnumerateTypes(child)) + { yield return type; + } } foreach (INamedTypeSymbol type in source.GetTypeMembers()) { yield return type; foreach (INamedTypeSymbol nested in EnumerateNestedTypes(type)) + { yield return nested; + } } } @@ -151,7 +199,9 @@ private static IEnumerable EnumerateNestedTypes(INamedTypeSymb { yield return type; foreach (INamedTypeSymbol nested in EnumerateNestedTypes(type)) + { yield return nested; + } } } @@ -160,10 +210,14 @@ private static bool IsAccessible(INamedTypeSymbol type) for (INamedTypeSymbol? current = type; current is not null; current = current.ContainingType) { if (current.IsExtension) + { return false; + } if (current.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) || current.IsFileLocal) + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) || current.IsFileLocal + ) { return false; + } } return !type.IsImplicitlyDeclared && type.TypeKind != TypeKind.Error; } @@ -173,13 +227,17 @@ private static bool CanConstruct(INamedTypeSymbol type) for (INamedTypeSymbol? current = type; current is not null; current = current.ContainingType) { if (HasOpenArguments(current)) + { return false; + } } - return !type.IsAbstract && !type.IsStatic && type.TypeKind is TypeKind.Class or TypeKind.Struct && - !type.IsRefLikeType && !GetBaseTypes(type).Append(type).Any(static current => - current.GetMembers().Any(static member => member is IPropertySymbol { IsRequired: true } - or IFieldSymbol { IsRequired: true })) && - type.InstanceConstructors.Any(static constructor => constructor.Parameters.Length == 0); + return !type.IsAbstract && !type.IsStatic && type.TypeKind is TypeKind.Class or TypeKind.Struct + && !type.IsRefLikeType && !GetBaseTypes(type).Append(type).Any(static current => + current.GetMembers().Any(static member => ( + member is IPropertySymbol { IsRequired: true } + or IFieldSymbol { IsRequired: true } + ))) + && type.InstanceConstructors.Any(static constructor => constructor.Parameters.Length == 0); } private static string FormatConstructorCall( @@ -187,8 +245,9 @@ private static string FormatConstructorCall( int index ) { ITypeSymbol[] arguments = GetConstructionArguments(type).ToArray(); - return "static () => Constructor" + index + (arguments.Length == 0 ? string.Empty : - "<" + string.Join(", ", arguments.Select(FormatType)) + ">") + ".Create()"; + return "static () => Constructor" + index + (arguments.Length == 0 + ? string.Empty + : "<" + string.Join(", ", arguments.Select(FormatType)) + ">") + ".Create()"; } private static IEnumerable GetConstructionArguments(INamedTypeSymbol type) @@ -196,10 +255,14 @@ private static IEnumerable GetConstructionArguments(INamedTypeSymbo if (type.ContainingType is not null) { foreach (ITypeSymbol argument in GetConstructionArguments(type.ContainingType)) + { yield return argument; + } } foreach (ITypeSymbol argument in type.TypeArguments) + { yield return argument; + } } private static void AppendConstructor( @@ -211,84 +274,119 @@ int index ITypeParameterSymbol[] parameters = GetConstructionArguments(definition).Cast().ToArray(); var names = new Dictionary(SymbolEqualityComparer.Default); for (int parameterIndex = 0; parameterIndex < parameters.Length; parameterIndex++) + { names.Add(parameters[parameterIndex], "T" + parameterIndex); + } code.Append("\n private static class Constructor").Append(index); if (parameters.Length > 0) + { code.Append('<').Append(string.Join(", ", parameters.Select(parameter => names[parameter]))).Append('>'); + } foreach (ITypeParameterSymbol parameter in parameters) { - var constraints = new List(); + List constraints = []; if (parameter.HasUnmanagedTypeConstraint) + { constraints.Add("unmanaged"); + } else if (parameter.HasValueTypeConstraint) + { constraints.Add("struct"); + } else if (parameter.HasReferenceTypeConstraint) + { constraints.Add(parameter.ReferenceTypeConstraintNullableAnnotation == NullableAnnotation.Annotated ? "class?" : "class"); + } else if (parameter.HasNotNullConstraint) + { constraints.Add("notnull"); + } constraints.AddRange(parameter.ConstraintTypes.Select(constraint => FormatConstructionType(constraint, names))); if (parameter.HasConstructorConstraint) + { constraints.Add("new()"); + } if (constraints.Count > 0) + { code.Append("\n where ").Append(names[parameter]).Append(" : ").Append(string.Join(", ", constraints)); + } } code.Append("\n {\n") - .Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" internal static extern ").Append(FormatConstructionType(definition, names)) + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" internal static extern ") + .Append(FormatConstructionType(definition, names)) .Append(" Create();\n }\n"); } private static string FormatConstructionType( ITypeSymbol type, Dictionary names - ) => string.Concat(type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat).Select(part => - part.Symbol is not null && names.TryGetValue(part.Symbol, out string? name) ? name : part.ToString())); + ) => string.Concat( + type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat).Select(part => ( + part.Symbol is not null && names.TryGetValue(part.Symbol, out string? name) ? name : part.ToString() + )) + ); private static IEnumerable GetBaseTypes(INamedTypeSymbol type) { for (INamedTypeSymbol? current = type.BaseType; current is not null && current.SpecialType != SpecialType.System_Object; - current = current.BaseType) + current = current.BaseType + ) { yield return current; + } } private static string FormatTypes(IEnumerable types) - => "new global::System.Type[] { " + string.Join(", ", types.Where(IsAccessible) - .Select(FormatTypeReference)) + " }"; + => "new global::System.Type[] { " + string.Join( + ", ", + types.Where(IsAccessible) + .Select(FormatTypeReference) + ) + " }"; private static string FormatTypeReference(INamedTypeSymbol type) { bool isInternal = type.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedAndInternal; - if (isInternal && !type.Locations.Any(static location => location.IsInSource) && - type.ContainingAssembly.Name.StartsWith("Inno.", StringComparison.Ordinal)) - { - return "global::" + type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog.ResolveType(" + - Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; + if (isInternal && !type.Locations.Any(static location => location.IsInSource) + && type.ContainingAssembly.Name.StartsWith("Inno.", StringComparison.Ordinal) + ) { + return "global::" + type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog.ResolveType(" + + SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; } return "typeof(" + GetTypeName(type) + ")"; } private static string GetMetadataName(INamedTypeSymbol type) - => type.ContainingType is not null ? GetMetadataName(type.ContainingType) + "+" + type.MetadataName - : (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString() + ".") + - type.MetadataName; + => type.ContainingType is not null + ? GetMetadataName(type.ContainingType) + "+" + type.MetadataName + : (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString() + ".") + + type.MetadataName; private static string FormatOverrides(INamedTypeSymbol type) { var seen = new HashSet(StringComparer.Ordinal); - var declarations = new List(); + List declarations = []; foreach (INamedTypeSymbol owner in new[] { type }.Concat(GetBaseTypes(type))) { - foreach (IMethodSymbol method in owner.GetMembers().OfType().Where(static method => - !method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 0 && - method.MethodKind == MethodKind.Ordinary)) - { + foreach (IMethodSymbol method in owner.GetMembers().OfType().Where(static method => ( + !method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 0 + && method.MethodKind == MethodKind.Ordinary + )) + ) { if (!seen.Add(method.Name) || !method.IsOverride) + { continue; + } IMethodSymbol root = method; while (root.OverriddenMethod is not null) + { root = root.OverriddenMethod; - declarations.Add("(" + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(method.Name, quote: true) + - ", typeof(" + GetTypeName(root.ContainingType) + "))"); + } + declarations.Add( + "(" + SymbolDisplay.FormatLiteral(method.Name, quote: true) + + ", typeof(" + GetTypeName(root.ContainingType) + "))" + ); } } return "new (string, global::System.Type)[] { " + string.Join(", ", declarations) + " }"; @@ -303,16 +401,24 @@ private static IEnumerable GetInheritedAttributes(INamedTypeSymbo foreach (AttributeData attribute in declaration.GetAttributes()) { if (attribute.AttributeClass is not INamedTypeSymbol attributeType) + { continue; + } AttributeData? usage = new[] { attributeType }.Concat(GetBaseTypes(attributeType)) .SelectMany(static source => source.GetAttributes()) .FirstOrDefault(static value => value.AttributeClass?.ToDisplayString() == "System.AttributeUsageAttribute"); - bool allowMultiple = usage?.NamedArguments.Any(static pair => pair.Key == "AllowMultiple" && - pair.Value.Value is true) ?? false; - bool canInherit = !(usage?.NamedArguments.Any(static pair => pair.Key == "Inherited" && - pair.Value.Value is false) ?? false); + bool allowMultiple = usage?.NamedArguments.Any(static pair => ( + pair.Key == "AllowMultiple" + && pair.Value.Value is true + )) ?? false; + bool canInherit = !(usage?.NamedArguments.Any(static pair => ( + pair.Key == "Inherited" + && pair.Value.Value is false + )) ?? false); if (inherited && (!canInherit || !allowMultiple && seen.Contains(attributeType))) + { continue; + } seen.Add(attributeType); yield return attribute; } @@ -321,52 +427,82 @@ private static IEnumerable GetInheritedAttributes(INamedTypeSymbo } private static string FormatAttributes(IEnumerable attributes) - => "new global::System.Attribute[] { " + string.Join(", ", attributes - .Where(static attribute => attribute.AttributeClass is not null && IsAccessible(attribute.AttributeClass) && - attribute.AttributeConstructor?.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal) - .Select(static attribute => "new " + GetTypeName(attribute.AttributeClass!) + "(" + - string.Join(", ", attribute.ConstructorArguments.Select(FormatConstant)) + ")" + - (attribute.NamedArguments.Length == 0 ? string.Empty : " { " + string.Join(", ", attribute.NamedArguments - .Select(static pair => pair.Key + " = " + FormatConstant(pair.Value))) + " }"))) + " }"; + => "new global::System.Attribute[] { " + string.Join( + ", ", + attributes + .Where(static attribute => ( + attribute.AttributeClass is not null && IsAccessible(attribute.AttributeClass) + && attribute.AttributeConstructor?.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + )) + .Select(static attribute => ( + "new " + GetTypeName(attribute.AttributeClass!) + "(" + + string.Join(", ", attribute.ConstructorArguments.Select(FormatConstant)) + ")" + + (attribute.NamedArguments.Length == 0 ? string.Empty : " { " + string.Join( + ", ", + attribute.NamedArguments + .Select(static pair => pair.Key + " = " + FormatConstant(pair.Value)) + ) + " }") + )) + ) + " }"; private static string FormatConstant(TypedConstant constant) { if (constant.IsNull) + { return "null"; + } if (constant.Kind == TypedConstantKind.Type && constant.Value is ITypeSymbol type) + { return "typeof(" + FormatType(type) + ")"; + } if (constant.Kind == TypedConstantKind.Array && constant.Type is IArrayTypeSymbol array) - return "new " + array.ElementType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "[] { " + - string.Join(", ", constant.Values.Select(FormatConstant)) + " }"; - string literal = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatPrimitive(constant.Value!, quoteStrings: true, - useHexadecimalNumbers: false) ?? throw new InvalidOperationException("The attribute constant cannot be represented as a C# literal."); - return constant.Kind == TypedConstantKind.Enum ? "(" + - constant.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")" + literal : literal; + { + return "new " + array.ElementType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "[] { " + + string.Join(", ", constant.Values.Select(FormatConstant)) + " }"; + } + string literal = SymbolDisplay.FormatPrimitive( + constant.Value!, + quoteStrings: true, + useHexadecimalNumbers: false + ) ?? throw new InvalidOperationException("The attribute constant cannot be represented as a C# literal."); + return constant.Kind == TypedConstantKind.Enum + ? "(" + + constant.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")" + literal + : literal; } private static string GetTypeName(INamedTypeSymbol type) { if (!HasOpenArguments(type)) + { return type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } string arguments = type.Arity == 0 ? string.Empty : "<" + new string(',', type.Arity - 1) + ">"; if (type.ContainingType is not null) + { return GetTypeName(type.ContainingType) + "." + type.Name + arguments; + } if (type.Arity > 0) - return "global::" + (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : - type.ContainingNamespace.ToDisplayString() + ".") + type.Name + arguments; + { + return "global::" + (type.ContainingNamespace.IsGlobalNamespace + ? string.Empty + : type.ContainingNamespace.ToDisplayString() + ".") + type.Name + arguments; + } return type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); } private static bool HasOpenArguments(INamedTypeSymbol type) - => type.IsUnboundGenericType || type.TypeArguments.Any(static argument => argument is ITypeParameterSymbol || - argument is INamedTypeSymbol named && HasOpenArguments(named)) || - type.ContainingType is not null && HasOpenArguments(type.ContainingType); + => type.IsUnboundGenericType || type.TypeArguments.Any(static argument => ( + argument is ITypeParameterSymbol + || argument is INamedTypeSymbol named && HasOpenArguments(named) + )) + || type.ContainingType is not null && HasOpenArguments(type.ContainingType); private static string FormatType(ITypeSymbol type) => type switch - { - INamedTypeSymbol named => GetTypeName(named), - IArrayTypeSymbol array => FormatType(array.ElementType) + "[" + new string(',', array.Rank - 1) + "]", - _ => type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - }; + { + INamedTypeSymbol named => GetTypeName(named), + IArrayTypeSymbol array => FormatType(array.ElementType) + "[" + new string(',', array.Rank - 1) + "]", + _ => type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + }; } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs index 644edb5e1..9ddf04d7a 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs @@ -18,9 +18,10 @@ SourceProductionContext output var values = new HashSet(SymbolEqualityComparer.Default); foreach (INamedTypeSymbol owner in EnumerateTypes(compilation.Assembly.GlobalNamespace)) { - foreach (ISymbol member in owner.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute"))) - { + foreach (ISymbol member in owner.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute" + ))) + ) { ITypeSymbol? value = member switch { IPropertySymbol property => property.Type, @@ -28,7 +29,9 @@ SourceProductionContext output _ => null }; if (value is not null && !ContainsParameters(value)) + { AddValueClosure(value, values); + } } } foreach (SyntaxTree tree in compilation.SyntaxTrees) @@ -37,52 +40,73 @@ SourceProductionContext output foreach (GenericNameSyntax syntax in tree.GetRoot(output.CancellationToken).DescendantNodes().OfType()) { if (model.GetTypeInfo(syntax, output.CancellationToken).Type is INamedTypeSymbol type && !ContainsParameters(type)) + { AddValueClosure(type, values); + } if (model.GetSymbolInfo(syntax, output.CancellationToken).Symbol is IMethodSymbol method) { foreach (ITypeSymbol argument in method.TypeArguments.Where(static argument => !ContainsParameters(argument))) + { AddValueClosure(argument, values); + } } } } INamedTypeSymbol[] converters = new[] { compilation.Assembly } - .Concat(compilation.SourceModule.ReferencedAssemblySymbols.Where(static assembly => - assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is not null)) + .Concat( + compilation.SourceModule.ReferencedAssemblySymbols.Where(static assembly => ( + assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is not null + )) + ) .SelectMany(static assembly => EnumerateTypes(assembly.GlobalNamespace)) .Where(static type => type.IsGenericType && type.TypeParameters.Length != 0 && GetConverterPattern(type) is not null) .ToArray(); var factories = new HashSet(SymbolEqualityComparer.Default); - var rejected = new List<(INamedTypeSymbol definition, ITypeSymbol[] arguments)>(); + List<(INamedTypeSymbol definition, ITypeSymbol[] arguments)> rejected = []; foreach (ITypeSymbol value in values) { if (value is INamedTypeSymbol { IsGenericType: true } named && IsAvailable(named, compilation)) + { factories.Add(named); + } foreach (INamedTypeSymbol converter in converters) { var bindings = new Dictionary(SymbolEqualityComparer.Default); - if (!Unify(GetConverterPattern(converter)!, value, bindings) || - converter.TypeParameters.Any(parameter => !bindings.ContainsKey(parameter))) + if (!Unify(GetConverterPattern(converter)!, value, bindings) + || converter.TypeParameters.Any(parameter => !bindings.ContainsKey(parameter)) + ) { continue; + } ITypeSymbol[] arguments = converter.TypeParameters.Select(parameter => bindings[parameter]).ToArray(); if (SatisfiesConstraints(converter, bindings, compilation)) { INamedTypeSymbol construction = converter.Construct(arguments); if (IsAvailable(construction, compilation)) + { factories.Add(construction); + } else - RuntimeRegistrationDiagnostics.ReportUnavailable(output, construction, - "the converter or an argument is inaccessible from the generated assembly catalog"); + { + RuntimeRegistrationDiagnostics.ReportUnavailable( + output, + construction, + "the converter or an argument is inaccessible from the generated assembly catalog" + ); + } } - else if (IsAvailable(converter, compilation) && - arguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation))) - { + else if (IsAvailable(converter, compilation) + && arguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)) + ) { rejected.Add((converter, arguments)); } } } return (factories.OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal).ToArray(), rejected.OrderBy(static value => value.definition.ToDisplayString(), StringComparer.Ordinal) - .ThenBy(static value => string.Join(",", value.arguments.Select(static argument => argument.ToDisplayString())), StringComparer.Ordinal) + .ThenBy( + static value => string.Join(",", value.arguments.Select(static argument => argument.ToDisplayString())), + StringComparer.Ordinal + ) .ToArray()); } @@ -91,16 +115,23 @@ private static void AddValueClosure( HashSet values ) { if (!values.Add(type)) + { return; + } if (type is IArrayTypeSymbol array) + { AddValueClosure(array.ElementType, values); + } if (type is INamedTypeSymbol named) { foreach (ITypeSymbol argument in named.TypeArguments) - AddValueClosure(argument, values); - foreach (ISymbol member in named.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute"))) { + AddValueClosure(argument, values); + } + foreach (ISymbol member in named.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute" + ))) + ) { ITypeSymbol? value = member switch { IPropertySymbol property => property.Type, @@ -108,7 +139,9 @@ HashSet values _ => null }; if (value is not null && !ContainsParameters(value)) + { AddValueClosure(value, values); + } } } } @@ -117,17 +150,23 @@ private static bool IsAvailable( INamedTypeSymbol type, Compilation compilation ) { - if (!SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly) && - type.ContainingAssembly.GetTypeByMetadataName(type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog") is null) + if (!SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly) + && type.ContainingAssembly.GetTypeByMetadataName(type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog") is null + ) { return false; + } for (INamedTypeSymbol? owner = type; owner is not null; owner = owner.ContainingType) { if (owner.IsFileLocal || owner.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { return false; - if (owner.DeclaredAccessibility != Accessibility.Public && - !SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly)) + } + if (owner.DeclaredAccessibility != Accessibility.Public + && !SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) + ) { return false; + } } return type.TypeArguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)); } @@ -138,10 +177,12 @@ Compilation compilation ) { for (INamedTypeSymbol? owner = type; owner is not null; owner = owner.ContainingType) { - if (owner.IsFileLocal || owner.DeclaredAccessibility != Accessibility.Public && - (!SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) || - owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal))) + if (owner.IsFileLocal || owner.DeclaredAccessibility != Accessibility.Public + && (!SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) + || owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal)) + ) { return false; + } } return type.TypeArguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)); } @@ -151,7 +192,9 @@ owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.Prot for (INamedTypeSymbol? current = type.BaseType; current is not null; current = current.BaseType) { if (current.OriginalDefinition.ToDisplayString() == "Inno.Core.Serialization.Converters.SerializationConverter") + { return current.TypeArguments[0]; + } } return null; } @@ -164,22 +207,28 @@ Dictionary bindings if (pattern is ITypeParameterSymbol parameter) { if (bindings.TryGetValue(parameter, out ITypeSymbol? existing)) + { return SymbolEqualityComparer.Default.Equals(existing, value); + } bindings.Add(parameter, value); return true; } if (pattern is IArrayTypeSymbol array) - return value is IArrayTypeSymbol other && array.Rank == other.Rank && Unify(array.ElementType, other.ElementType, bindings); - if (pattern is INamedTypeSymbol named && value is INamedTypeSymbol concrete && - SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, concrete.OriginalDefinition)) { + return value is IArrayTypeSymbol other && array.Rank == other.Rank && Unify(array.ElementType, other.ElementType, bindings); + } + if (pattern is INamedTypeSymbol named && value is INamedTypeSymbol concrete + && SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, concrete.OriginalDefinition) + ) { for (int index = 0; index < named.TypeArguments.Length; index++) { if (!Unify(named.TypeArguments[index], concrete.TypeArguments[index], bindings)) + { return false; + } } - return named.ContainingType is null || concrete.ContainingType is not null && - Unify(named.ContainingType, concrete.ContainingType, bindings); + return named.ContainingType is null || concrete.ContainingType is not null + && Unify(named.ContainingType, concrete.ContainingType, bindings); } return SymbolEqualityComparer.Default.Equals(pattern, value); } @@ -192,18 +241,25 @@ Compilation compilation foreach (ITypeParameterSymbol parameter in definition.TypeParameters) { ITypeSymbol argument = bindings[parameter]; - if (parameter.HasReferenceTypeConstraint && !argument.IsReferenceType || - parameter.HasValueTypeConstraint && (!argument.IsValueType || argument.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) || - parameter.HasUnmanagedTypeConstraint && !argument.IsUnmanagedType || - parameter.HasConstructorConstraint && !argument.IsValueType && - (argument is not INamedTypeSymbol named || named.IsAbstract || !named.InstanceConstructors.Any(static constructor => - constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public))) + if (parameter.HasReferenceTypeConstraint && !argument.IsReferenceType + || parameter.HasValueTypeConstraint + && (!argument.IsValueType || argument.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) + || + parameter.HasUnmanagedTypeConstraint && !argument.IsUnmanagedType + || parameter.HasConstructorConstraint && !argument.IsValueType + && (argument is not INamedTypeSymbol named || named.IsAbstract || !named.InstanceConstructors.Any(static constructor => ( + constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public + ))) + ) { return false; + } foreach (ITypeSymbol constraint in parameter.ConstraintTypes) { ITypeSymbol substituted = Substitute(constraint, bindings, compilation); if (!compilation.ClassifyCommonConversion(argument, substituted).IsImplicit) + { return false; + } } } return true; @@ -217,16 +273,19 @@ Compilation compilation { ITypeParameterSymbol parameter => bindings[parameter], IArrayTypeSymbol array => compilation.CreateArrayTypeSymbol(Substitute(array.ElementType, bindings, compilation), array.Rank), - INamedTypeSymbol { IsGenericType: true } named => named.OriginalDefinition.Construct(named.TypeArguments - .Select(argument => Substitute(argument, bindings, compilation)).ToArray()), + INamedTypeSymbol { IsGenericType: true } named => named.OriginalDefinition.Construct( + named.TypeArguments + .Select(argument => Substitute(argument, bindings, compilation)) + .ToArray() + ), _ => type }; private static bool ContainsParameters(ITypeSymbol type) - => type is ITypeParameterSymbol || type is INamedTypeSymbol named && - (named.IsUnboundGenericType || named.TypeArguments.Any(ContainsParameters) || - named.ContainingType is not null && ContainsParameters(named.ContainingType)) || - type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); + => type is ITypeParameterSymbol || type is INamedTypeSymbol named + && (named.IsUnboundGenericType || named.TypeArguments.Any(ContainsParameters) + || named.ContainingType is not null && ContainsParameters(named.ContainingType)) + || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); private static IEnumerable EnumerateTypes(INamespaceOrTypeSymbol scope) { @@ -234,13 +293,19 @@ private static IEnumerable EnumerateTypes(INamespaceOrTypeSymb { // Extension declarations group members but cannot be named as runtime types. if (member is INamedTypeSymbol { IsExtension: true }) + { continue; + } if (member is INamedTypeSymbol type) + { yield return type; + } if (member is INamespaceOrTypeSymbol child) { foreach (INamedTypeSymbol nested in EnumerateTypes(child)) + { yield return nested; + } } } } diff --git a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs index a773be6d4..7a670f8ba 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs @@ -14,8 +14,14 @@ namespace Inno.Runtime.Generators; [Generator] public sealed class RuntimeSubsystemGenerator : IIncrementalGenerator { - private static readonly DiagnosticDescriptor S_INVALID = new("INNORUN001", "Invalid subsystem composition", - "{0}", "Architecture", DiagnosticSeverity.Error, true); + private static readonly DiagnosticDescriptor INVALID = new( + "INNORUN001", + "Invalid subsystem composition", + "{0}", + "Architecture", + DiagnosticSeverity.Error, + true + ); /// /// Registers incremental discovery of composition methods and catalog declarations. @@ -25,7 +31,7 @@ public sealed class RuntimeSubsystemGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - var registrations = context.SyntaxProvider.ForAttributeWithMetadataName( + IncrementalValueProvider> registrations = context.SyntaxProvider.ForAttributeWithMetadataName( "Inno.Runtime.Contracts.RuntimeSubsystemRegistrationAttribute", static ( node, @@ -34,9 +40,12 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( entry, _ - ) => new Registration((IMethodSymbol)entry.TargetSymbol, - entry.Attributes[0].ConstructorArguments[0].Value as string ?? string.Empty)).Collect(); - var catalogs = context.SyntaxProvider.ForAttributeWithMetadataName( + ) => new Registration( + (IMethodSymbol)entry.TargetSymbol, + entry.Attributes[0].ConstructorArguments[0].Value as string ?? string.Empty + ) + ).Collect(); + IncrementalValueProvider> catalogs = context.SyntaxProvider.ForAttributeWithMetadataName( "Inno.Runtime.Contracts.RuntimeSubsystemCatalogAttribute", static ( node, @@ -45,12 +54,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( entry, _ - ) => (IMethodSymbol)entry.TargetSymbol).Collect(); - context.RegisterSourceOutput(catalogs.Combine(registrations), + ) => (IMethodSymbol)entry.TargetSymbol + ).Collect(); + context.RegisterSourceOutput( + catalogs.Combine(registrations), static ( output, data - ) => Generate(output, data.Left, data.Right)); + ) => Generate(output, data.Left, data.Right) + ); } private static void Generate( @@ -61,30 +73,50 @@ ImmutableArray registrations foreach (Registration registration in registrations) { if (!IsFactory(registration.method) || string.IsNullOrWhiteSpace(registration.id)) - Report(output, registration.method, "A subsystem declaration must be an accessible static method taking one composition parameter and returning IRuntimeSubsystemFactory with a non-empty ID."); + { + Report( + output, + registration.method, + "A subsystem declaration must be an accessible static method taking one composition parameter and returning IRuntimeSubsystemFactory with a non-empty ID." + ); + } } foreach (IMethodSymbol catalog in catalogs) { - if (!catalog.IsStatic || catalog.IsGenericMethod || catalog.Parameters.Length != 1 || - catalog.Parameters[0].RefKind != RefKind.None || catalog.Parameters[0].IsParams || - catalog.ContainingType.ContainingType is not null || catalog.ContainingType.Arity != 0 || - !catalog.ContainingType.IsStatic || catalog.ContainingNamespace.IsGlobalNamespace || - catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal) || - !catalog.IsPartialDefinition || catalog.ReturnType.ToDisplayString() != - "System.Collections.Generic.IReadOnlyList") - { - Report(output, catalog, "A catalog must be a static partial method on a non-nested partial class, take one composition parameter and return IReadOnlyList."); + if (!catalog.IsStatic || catalog.IsGenericMethod || catalog.Parameters.Length != 1 + || catalog.Parameters[0].RefKind != RefKind.None || catalog.Parameters[0].IsParams + || catalog.ContainingType.ContainingType is not null || catalog.ContainingType.Arity != 0 + || !catalog.ContainingType.IsStatic || catalog.ContainingNamespace.IsGlobalNamespace + || catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal) + || !catalog.IsPartialDefinition + || catalog.ReturnType.ToDisplayString() + != "System.Collections.Generic.IReadOnlyList" + ) { + Report( + output, + catalog, + "A catalog must be a static partial method on a non-nested partial class, take one composition parameter and return IReadOnlyList." + ); continue; } - Registration[] matches = registrations.Where(registration => IsFactory(registration.method) && - SymbolEqualityComparer.Default.Equals(registration.method.Parameters[0].Type, catalog.Parameters[0].Type)) - .OrderBy(static registration => registration.id, StringComparer.Ordinal).ToArray(); - var duplicate = matches.GroupBy(static registration => registration.id, StringComparer.Ordinal) + Registration[] matches = registrations + .Where(registration => ( + IsFactory(registration.method) + && SymbolEqualityComparer.Default.Equals(registration.method.Parameters[0].Type, catalog.Parameters[0].Type) + )) + .OrderBy(static registration => registration.id, StringComparer.Ordinal) + .ToArray(); + IGrouping duplicate = matches.GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1); if (matches.Length == 0 || duplicate is not null) { - Report(output, catalog, duplicate is null ? "A subsystem catalog has no declarations." : - $"Subsystem ID '{duplicate.Key}' is duplicated in this composition."); + Report( + output, + catalog, + duplicate is null + ? "A subsystem catalog has no declarations." + : $"Subsystem ID '{duplicate.Key}' is duplicated in this composition." + ); continue; } string typeName = Escape(catalog.ContainingType.Name); @@ -94,34 +126,65 @@ catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Inte string parameterType = catalog.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); string parameterName = Escape(catalog.Parameters[0].Name); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(ns).Append(";\n").Append(typeAccess).Append(" static partial class ") - .Append(typeName).Append("\n{\n ").Append(access) - .Append(" static partial global::System.Collections.Generic.IReadOnlyList ") - .Append(Escape(catalog.Name)).Append('(').Append(parameterType).Append(' ').Append(parameterName).Append(")\n {\n") - .Append(" global::System.ArgumentNullException.ThrowIfNull(").Append(parameterName).Append(");\n") + code.Append("namespace ") + .Append(ns) + .Append(";\n") + .Append(typeAccess) + .Append(" static partial class ") + .Append(typeName) + .Append("\n{\n ") + .Append(access) + .Append( + " static partial global::System.Collections.Generic.IReadOnlyList " + ) + .Append(Escape(catalog.Name)) + .Append('(') + .Append(parameterType) + .Append(' ') + .Append(parameterName) + .Append(")\n {\n") + .Append(" global::System.ArgumentNullException.ThrowIfNull(") + .Append(parameterName) + .Append(");\n") .Append(" var factories = new global::Inno.Runtime.Contracts.IRuntimeSubsystemFactory[]\n {\n"); foreach (Registration match in matches) - code.Append(" ").Append(match.method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) - .Append('.').Append(Escape(match.method.Name)).Append('(').Append(parameterName).Append("),\n"); + { + code.Append(" ") + .Append(match.method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) + .Append('.') + .Append(Escape(match.method.Name)) + .Append('(') + .Append(parameterName) + .Append("),\n"); + } code.Append(" };\n"); for (int index = 0; index < matches.Length; index++) { - string id = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(matches[index].id, true); - code.Append(" if (factories[").Append(index).Append("].descriptor.id.value != ").Append(id) - .Append(")\n throw new global::System.InvalidOperationException(\"A subsystem declaration disagrees with its factory descriptor.\");\n"); + string id = SymbolDisplay.FormatLiteral(matches[index].id, true); + code.Append(" if (factories[") + .Append(index) + .Append("].descriptor.id.value != ") + .Append(id) + .Append( + ")\n throw new global::System.InvalidOperationException(\"A subsystem declaration disagrees with its factory descriptor.\");\n" + ); } code.Append(" return global::System.Array.AsReadOnly(factories);\n }\n}\n"); - output.AddSource(ns + "." + catalog.ContainingType.Name + "." + catalog.Name + "." + - catalogs.IndexOf(catalog) + ".g.cs", code.ToString()); + output.AddSource( + ns + "." + catalog.ContainingType.Name + "." + catalog.Name + "." + + catalogs.IndexOf(catalog) + ".g.cs", + code.ToString() + ); } } - private static bool IsFactory(IMethodSymbol method) => method.IsStatic && !method.IsGenericMethod && - method.ContainingType.Arity == 0 && method.ContainingType.ContainingType is null && - method.ContainingType.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal && - method.Parameters.Length == 1 && method.Parameters[0].RefKind == RefKind.None && !method.Parameters[0].IsParams && - method.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal && - method.ReturnType.ToDisplayString() == "Inno.Runtime.Contracts.IRuntimeSubsystemFactory"; + private static bool IsFactory(IMethodSymbol method) + => method.IsStatic && !method.IsGenericMethod + && method.ContainingType.Arity == 0 && method.ContainingType.ContainingType is null + && method.ContainingType.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + && method.Parameters.Length == 1 && method.Parameters[0].RefKind == RefKind.None && !method.Parameters[0].IsParams + && method.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + && method.ReturnType.ToDisplayString() == "Inno.Runtime.Contracts.IRuntimeSubsystemFactory"; private static string Escape(string name) => SyntaxFacts.GetKeywordKind(name) == SyntaxKind.None ? name : "@" + name; @@ -129,8 +192,7 @@ private static void Report( SourceProductionContext context, IMethodSymbol method, string message - ) - => context.ReportDiagnostic(Diagnostic.Create(S_INVALID, method.Locations.FirstOrDefault(), message)); + ) => context.ReportDiagnostic(Diagnostic.Create(INVALID, method.Locations.FirstOrDefault(), message)); private sealed class Registration( IMethodSymbol method, diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs new file mode 100644 index 000000000..35be76c2b --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs @@ -0,0 +1,75 @@ +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Settings; + +namespace Inno.Plugins.Authoring; + +/// +/// Describes one validated installed Plugin source candidate. +/// +public sealed class PluginCandidate +{ + private readonly PluginManifest m_manifest; + + internal PluginCandidate( + string sourcePath, + PluginSourceKind sourceKind, + string contentHash, + PluginManifest manifest, + AssetSourceMount sourceMount, + bool containsCode + ) { + this.sourcePath = sourcePath; + this.sourceKind = sourceKind; + this.contentHash = contentHash; + m_manifest = CloneManifest(manifest); + this.sourceMount = sourceMount; + this.containsCode = containsCode; + } + + /// + /// Gets the installed .iplugin package path. + /// + public string sourcePath { get; } + + /// + /// Gets the physical source container kind. + /// + public PluginSourceKind sourceKind { get; } + + /// + /// Gets the deterministic complete source-content hash. + /// + public string contentHash { get; } + + /// + /// Gets a detached copy of the validated native manifest, including its nested contribution payloads. + /// + public PluginManifest manifest => CloneManifest(m_manifest); + + /// + /// Gets the isolated read-only asset source mount. + /// + public AssetSourceMount sourceMount { get; } + + /// + /// Gets whether source code exists in this Plugin. + /// + public bool containsCode { get; } + + private static PluginManifest CloneManifest(PluginManifest value) + => new() + { + pluginId = value.pluginId, + displayName = value.displayName, + dependencies = value.dependencies.ToArray(), + overrides = value.overrides.ToArray(), + contentRoots = value.contentRoots.ToArray(), + assemblyDefinitions = value.assemblyDefinitions.ToArray(), + settingContributions = value.settingContributions.Select(static record => new ProjectSettingRecord( + record.id, + record.stableTypeId, + record.propertyData + )).ToArray() + }; +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs index 0cb51c042..c63213c80 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Core.Execution; @@ -13,14 +13,9 @@ namespace Inno.Plugins.Authoring; internal sealed class PluginCatalog { private readonly object m_sync = new(); - private Snapshot s_current = Snapshot.empty; - private PluginScanResult s_discovery = new([], []); - private long s_revision; - - /// - /// Occurs after installed discovery or active Plugin state changes. - /// - public event Action? Changed; + private Snapshot m_current = Snapshot.empty; + private PluginScanResult m_discovery = new([], []); + private long m_revision; /// /// Gets dependency-ordered active Plugins. @@ -30,7 +25,9 @@ public IReadOnlyList activePlugins get { lock (m_sync) - return s_current.ordered; + { + return m_current.ordered; + } } } @@ -42,7 +39,9 @@ public long revision get { lock (m_sync) - return s_revision; + { + return m_revision; + } } } @@ -54,10 +53,17 @@ public PluginScanResult discovery get { lock (m_sync) - return s_discovery; + { + return m_discovery; + } } } + /// + /// Occurs after installed discovery or active Plugin state changes. + /// + public event Action? changed; + /// /// Tries to resolve the active Plugin that owns an asset source. /// @@ -71,11 +77,13 @@ public PluginScanResult discovery /// when the source belongs to an active Plugin. /// public bool TryGet( - AssetSourceId source, + AssetSourceID source, out PluginCandidate? plugin ) { lock (m_sync) - return s_current.bySource.TryGetValue(source, out plugin); + { + return m_current.bySource.TryGetValue(source, out plugin); + } } /// @@ -88,18 +96,19 @@ public void Activate(PluginScanResult result) { ArgumentNullException.ThrowIfNull(result); PluginCandidate[] ordered = PluginSourceService.GetActivatableCandidates(result).ToArray(); - var bySource = ordered.ToFrozenDictionary( + FrozenDictionary bySource = ordered.ToFrozenDictionary( static candidate => candidate.sourceMount.id, - static candidate => candidate); - Action? changed; + static candidate => candidate + ); + Action? handlers; lock (m_sync) { - s_discovery = result; - s_current = new Snapshot(Array.AsReadOnly(ordered), bySource); - s_revision++; - changed = Changed; + m_discovery = result; + m_current = new Snapshot(Array.AsReadOnly(ordered), bySource); + m_revision++; + handlers = changed; } - InvokeObservers(changed); + InvokeObservers(handlers); } /// @@ -111,13 +120,13 @@ public void Activate(PluginScanResult result) public void PublishDiscovery(PluginScanResult result) { ArgumentNullException.ThrowIfNull(result); - Action? changed; + Action? handlers; lock (m_sync) { - s_discovery = result; - changed = Changed; + m_discovery = result; + handlers = changed; } - InvokeObservers(changed); + InvokeObservers(handlers); } /// @@ -127,17 +136,19 @@ public void Shutdown() { lock (m_sync) { - s_current = Snapshot.empty; - s_discovery = new PluginScanResult([], []); - s_revision++; - Changed = null; + m_current = Snapshot.empty; + m_discovery = new PluginScanResult([], []); + m_revision++; + changed = null; } } private static void InvokeObservers(Action? handlers) { if (handlers is null) + { return; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -148,7 +159,12 @@ private static void InvokeObservers(Action? handlers) catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures is not null) - throw new AggregateException("Plugin catalog observers reported unfinished retirement.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Plugin catalog observers reported unfinished retirement.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -159,18 +175,17 @@ private static void InvokeObservers(Action? handlers) } if (failures is not null) { - throw new AggregateException( - "One or more Plugin catalog observers failed after publication.", - failures); + throw new AggregateException("One or more Plugin catalog observers failed after publication.", failures); } } private sealed record Snapshot( IReadOnlyList ordered, - FrozenDictionary bySource + FrozenDictionary bySource ) { internal static Snapshot empty { get; } = new( [], - new Dictionary().ToFrozenDictionary()); + new Dictionary().ToFrozenDictionary() + ); } } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs new file mode 100644 index 000000000..155f3c94d --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs @@ -0,0 +1,34 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Reports one Plugin discovery, validation, or dependency problem. +/// +public sealed class PluginDiagnostic +{ + /// + /// Creates a Plugin source diagnostic. + /// + /// + /// Related .iplugin package path or invalid installation entry. + /// + /// + /// Actionable problem description. + /// + public PluginDiagnostic( + string sourcePath, + string message + ) { + this.sourcePath = sourcePath ?? string.Empty; + this.message = message ?? string.Empty; + } + + /// + /// Gets the related .iplugin package path or invalid installation entry. + /// + public string sourcePath { get; } + + /// + /// Gets the actionable problem description. + /// + public string message { get; } +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs index 54f8909a0..0baa247be 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs @@ -8,11 +8,11 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Execution; -using Inno.Scripting.Api; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Reload; using Inno.References; +using Inno.Scripting.Api; namespace Inno.Plugins.Authoring; @@ -44,49 +44,6 @@ public sealed class PluginEnvironment : IDisposable private Task? m_reconciliation; private PendingActivation? m_pending; - /// - /// Occurs after a validated Plugin generation is staged for script compilation but before it becomes active. - /// - [ScriptingApiIgnore] - public event Action? ActivationCandidateChanged; - - /// - /// Gets whether project Plugin management is initialized. - /// - [ScriptingApiIgnore] - public bool isInitialized - { - get - { - lock (m_sync) - return m_sources is not null; - } - } - - /// - /// Gets the dependency-ordered active Plugin generation. - /// - public IReadOnlyList activePlugins => m_catalog.activePlugins; - - /// - /// Gets the monotonic identity of the active Plugin generation. - /// - public long revision => m_catalog.revision; - - /// - /// Gets the latest installed Plugin discovery and isolated diagnostics. - /// - public PluginScanResult discovery => m_catalog.discovery; - - /// - /// Occurs after discovery diagnostics or the active Plugin generation changes. - /// - public event Action? Changed - { - add => m_catalog.Changed += value; - remove => m_catalog.Changed -= value; - } - /// /// Creates automatic Plugin discovery around one asset pipeline and project settings store. /// @@ -127,10 +84,13 @@ GenerationCoordinator generations ArgumentException.ThrowIfNullOrWhiteSpace(pluginRoot); ArgumentException.ThrowIfNullOrWhiteSpace(libraryRoot); ArgumentNullException.ThrowIfNull(initialScan); + ArgumentNullException.ThrowIfNull(generations); if (!assets.isInitialized) + { throw new InvalidOperationException("PluginEnvironment requires AssetPipeline to be initialized first."); + } m_assets = assets; - m_generations = generations ?? throw new ArgumentNullException(nameof(generations)); + m_generations = generations; m_settings = settings; lock (m_sync) { @@ -148,6 +108,98 @@ GenerationCoordinator generations } } + /// + /// Gets whether project Plugin management is initialized. + /// + [ScriptingApiIgnore] + public bool isInitialized + { + get + { + lock (m_sync) + { + return m_sources is not null; + } + } + } + + /// + /// Gets the dependency-ordered active Plugin generation. + /// + public IReadOnlyList activePlugins => m_catalog.activePlugins; + + /// + /// Gets the monotonic identity of the active Plugin generation. + /// + public long revision => m_catalog.revision; + + /// + /// Gets the latest installed Plugin discovery and isolated diagnostics. + /// + public PluginScanResult discovery => m_catalog.discovery; + + /// + /// Gets whether a source-mount candidate is waiting for successful script generation activation. + /// + [ScriptingApiIgnore] + public bool hasPendingActivation + { + get + { + lock (m_sync) + { + return m_pending is not null; + } + } + } + + /// + /// Gets the isolated Asset candidate used by the next Plugin script compilation. + /// + [ScriptingApiIgnore] + public AssetSourceMountTransaction? compilationAssets + { + get + { + lock (m_sync) + { + return m_pending?.assets; + } + } + } + + /// + /// Gets the Plugin candidates visible to the next script compilation. + /// + [ScriptingApiIgnore] + public IReadOnlyList compilationPlugins + { + get + { + lock (m_sync) + { + return m_pending is null + ? m_catalog.activePlugins + : PluginSourceService.GetActivatableCandidates(m_pending.candidateScan).ToArray(); + } + } + } + + /// + /// Occurs after a validated Plugin generation is staged for script compilation but before it becomes active. + /// + [ScriptingApiIgnore] + public event Action? activationCandidateChanged; + + /// + /// Occurs after discovery diagnostics or the active Plugin generation changes. + /// + public event Action? changed + { + add => m_catalog.changed += value; + remove => m_catalog.changed -= value; + } + /// /// Processes debounced Plugin source notifications and completed background reconciliation. /// @@ -160,13 +212,17 @@ public void Update() lock (m_sync) { if (m_sources is null) + { return; + } long now = Environment.TickCount64; StartReconciliationLocked(now); refresh = m_refreshRequested - && now - m_lastChangeTimestamp >= C_CHANGE_DEBOUNCE_MILLISECONDS; + && now - m_lastChangeTimestamp >= C_CHANGE_DEBOUNCE_MILLISECONDS; if (!refresh) + { return; + } m_refreshRequested = false; } _ = Refresh(); @@ -185,26 +241,30 @@ public bool Refresh() ObjectDisposedException.ThrowIf(m_stopping, this); PluginSourceService sources; lock (m_sync) + { sources = m_sources ?? throw new InvalidOperationException("PluginEnvironment is not initialized."); + } PluginScanResult scan = sources.Scan(); m_catalog.PublishDiscovery(scan); string activeFingerprint = ComputeActiveFingerprint(scan); lock (m_sync) { if (m_pending is not null) + { return false; + } if (string.Equals(activeFingerprint, m_activeFingerprint, StringComparison.Ordinal)) + { return false; + } } PluginScanResult previous = CreateActiveScanSnapshot(); - AssetSourceMount project = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount project = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceID.project); AssetSourceMountTransaction assets; try { - assets = m_assets.PrepareSourceMounts( - [project, .. PluginSourceService.GetActivatableMounts(scan)]); + assets = m_assets.PrepareSourceMounts([project, .. PluginSourceService.GetActivatableMounts(scan)]); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -218,17 +278,23 @@ public bool Refresh() .. scan.diagnostics, new PluginDiagnostic( m_pluginRoot, - $"Plugin Asset candidate validation failed; the installed Plugin generation is unavailable: " + - exception.Message) - ]); + $"Plugin Asset candidate validation failed; the installed Plugin generation is unavailable: " + + exception.Message + ) + ] + ); m_catalog.PublishDiscovery(scan); activeFingerprint = ComputeActiveFingerprint(scan); lock (m_sync) { if (m_pending is not null) + { return false; + } if (string.Equals(activeFingerprint, m_activeFingerprint, StringComparison.Ordinal)) + { return false; + } } assets = m_assets.PrepareSourceMounts([project]); } @@ -239,13 +305,10 @@ public bool Refresh() lock (m_sync) { if (m_pending is not null) + { throw new InvalidOperationException("Another Plugin activation candidate is already pending."); - m_pending = new PendingActivation( - previous, - scan, - assets, - m_activeFingerprint, - activeFingerprint); + } + m_pending = new PendingActivation(previous, scan, assets, m_activeFingerprint, activeFingerprint); pendingAssigned = true; } if (!requiresCodeReload) @@ -265,7 +328,9 @@ public bool Refresh() catch (Exception candidateFailure) { if (m_generations.state == GenerationState.Faulted) + { throw; + } try { if (pendingAssigned) @@ -273,7 +338,9 @@ public bool Refresh() RollbackPending(); } else + { assets.Rollback(); + } } catch (Exception rollbackFailure) { @@ -291,8 +358,11 @@ public bool Refresh() /// [ScriptingApiIgnore] public IGenerationChange CreateReloadChange() - => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - [new PluginRecoveryParticipant(this, m_assets, m_settings)]); + => new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + [new PluginRecoveryParticipant(this, m_assets, m_settings)] + ); /// /// Commits a non-code availability change using the same generation gate and recovery phases as script reload. @@ -303,49 +373,6 @@ public IGenerationChange CreateReloadChange() [ScriptingApiIgnore] public void ApplyPendingChange() => m_generations.Execute("Plugin availability", new AvailabilityPublication(), [CreateReloadChange()]); - /// - /// Gets whether a source-mount candidate is waiting for successful script generation activation. - /// - [ScriptingApiIgnore] - public bool hasPendingActivation - { - get - { - lock (m_sync) - return m_pending is not null; - } - } - - /// - /// Gets the isolated Asset candidate used by the next Plugin script compilation. - /// - [ScriptingApiIgnore] - public AssetSourceMountTransaction? compilationAssets - { - get - { - lock (m_sync) - return m_pending?.assets; - } - } - - /// - /// Gets the Plugin candidates visible to the next script compilation. - /// - [ScriptingApiIgnore] - public IReadOnlyList compilationPlugins - { - get - { - lock (m_sync) - { - return m_pending is null - ? m_catalog.activePlugins - : PluginSourceService.GetActivatableCandidates(m_pending.candidateScan).ToArray(); - } - } - } - /// /// Resolves a Plugin owned by the active or pending script-compilation generation. /// @@ -360,7 +387,7 @@ public IReadOnlyList compilationPlugins /// [ScriptingApiIgnore] public bool TryGetCompilationPlugin( - AssetSourceId source, + AssetSourceID source, out PluginCandidate? plugin ) { plugin = compilationPlugins.FirstOrDefault(candidate => candidate.sourceMount.id == source); @@ -380,7 +407,7 @@ out PluginCandidate? plugin /// when an active Plugin owns the source. /// public bool TryGet( - AssetSourceId source, + AssetSourceID source, out PluginCandidate? plugin ) => m_catalog.TryGet(source, out plugin); @@ -392,9 +419,13 @@ public void ActivatePending() { PendingActivation? pending; lock (m_sync) + { pending = m_pending; + } if (pending is null || pending.isActivated) + { return; + } // The shared generation coordinator restores publication before participant state. // Retain the candidate on failure; local compensation here would violate that ordering. pending.assets.Activate(); @@ -414,15 +445,21 @@ public void CommitPending() { pending = m_pending; if (pending is null) + { return; + } if (!pending.isActivated) + { throw new InvalidOperationException("A Plugin candidate must be activated before commit."); + } } pending.assets.Complete(); lock (m_sync) { if (!ReferenceEquals(m_pending, pending)) + { throw new InvalidOperationException("The pending Plugin candidate changed during commit."); + } m_activeFingerprint = pending.candidateFingerprint; m_pending = null; } @@ -436,9 +473,13 @@ public void RollbackPending() { PendingActivation? pending; lock (m_sync) + { pending = m_pending; + } if (pending is null) + { return; + } pending.assets.Rollback(); if (pending.isActivated) { @@ -449,7 +490,9 @@ public void RollbackPending() lock (m_sync) { if (!ReferenceEquals(m_pending, pending)) + { throw new InvalidOperationException("The pending Plugin candidate changed during rollback."); + } m_activeFingerprint = pending.previousFingerprint; m_pending = null; } @@ -490,7 +533,7 @@ public void Dispose() m_lastReconciliationTimestamp = 0; m_refreshRequested = false; m_reconciliation = null; - ActivationCandidateChanged = null; + activationCandidateChanged = null; } try { @@ -503,7 +546,9 @@ public void Dispose() m_catalog.Shutdown(); GC.SuppressFinalize(this); if (failures.Count > 0) + { throw new AggregateException("Plugin environment shutdown failed after its work retired.", failures); + } } private FileSystemWatcher CreateWatcher(string pluginRoot) @@ -512,9 +557,9 @@ private FileSystemWatcher CreateWatcher(string pluginRoot) { IncludeSubdirectories = false, NotifyFilter = NotifyFilters.FileName - | NotifyFilters.DirectoryName - | NotifyFilters.LastWrite - | NotifyFilters.Size, + | NotifyFilters.DirectoryName + | NotifyFilters.LastWrite + | NotifyFilters.Size, Filter = "*" }; watcher.Changed += OnPluginSourceChanged; @@ -535,7 +580,9 @@ FileSystemEventArgs arguments lock (m_sync) { if (m_sources is null || m_stopping) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64; } @@ -550,7 +597,9 @@ ErrorEventArgs arguments lock (m_sync) { if (m_sources is null || m_stopping) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64 - C_CHANGE_DEBOUNCE_MILLISECONDS; m_lastReconciliationTimestamp = 0; @@ -560,8 +609,8 @@ ErrorEventArgs arguments private void StartReconciliationLocked(long now) { if (m_reconciliation is not null - || now - m_lastReconciliationTimestamp < C_RECONCILIATION_INTERVAL_MILLISECONDS) - { + || now - m_lastReconciliationTimestamp < C_RECONCILIATION_INTERVAL_MILLISECONDS + ) { return; } string pluginRoot = m_pluginRoot; @@ -587,7 +636,9 @@ private void CompleteReconciliation() { reconciliation = m_reconciliation; if (reconciliation is null || !reconciliation.IsCompleted) + { return; + } m_reconciliation = null; } @@ -597,7 +648,9 @@ private void CompleteReconciliation() lock (m_sync) { if (m_sources is null) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64 - C_CHANGE_DEBOUNCE_MILLISECONDS; } @@ -607,8 +660,8 @@ private void CompleteReconciliation() lock (m_sync) { if (m_sources is null - || string.Equals(fingerprint, m_reconciledFingerprint, StringComparison.Ordinal)) - { + || string.Equals(fingerprint, m_reconciledFingerprint, StringComparison.Ordinal) + ) { return; } m_reconciledFingerprint = fingerprint; @@ -624,14 +677,18 @@ private void PublishContributors(PluginScanResult scan) candidate.manifest.pluginId, candidate.manifest.dependencies, candidate.manifest.overrides, - candidate.manifest.settingContributions)) - .ToArray()); + candidate.manifest.settingContributions + )) + .ToArray() + ); private void InvokeCandidateObservers() { - Action? handlers = ActivationCandidateChanged; + Action? handlers = activationCandidateChanged; if (handlers is null) + { return; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -642,7 +699,12 @@ private void InvokeCandidateObservers() catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures is not null) - throw new AggregateException("Plugin candidate observers reported unfinished retirement.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Plugin candidate observers reported unfinished retirement.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -655,18 +717,17 @@ private void InvokeCandidateObservers() { throw new AggregateException( "One or more Plugin candidate observers rejected the staged generation.", - failures); + failures + ); } } private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) { - AssetSourceMount project = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount project = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceID.project); try { - m_assets.ReplaceSourceMounts( - [project, .. PluginSourceService.GetActivatableMounts(initialScan)]); + m_assets.ReplaceSourceMounts([project, .. PluginSourceService.GetActivatableMounts(initialScan)]); m_catalog.Activate(initialScan); PublishContributors(initialScan); m_settings.RebuildCurrent(allowUnresolvedContributions: true); @@ -678,16 +739,10 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) } catch (Exception candidateFailure) { - var rollbackFailures = new List { candidateFailure }; - TryInitialRollback( - () => m_assets.ReplaceSourceMounts([project]), - "asset mount rollback", - rollbackFailures); + List rollbackFailures = [candidateFailure]; + TryInitialRollback(() => m_assets.ReplaceSourceMounts([project]), "asset mount rollback", rollbackFailures); var empty = new PluginScanResult([], []); - TryInitialRollback( - () => m_catalog.Activate(empty), - "Plugin catalog rollback", - rollbackFailures); + TryInitialRollback(() => m_catalog.Activate(empty), "Plugin catalog rollback", rollbackFailures); TryInitialRollback( () => { @@ -695,12 +750,14 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) m_settings.RebuildCurrent(allowUnresolvedContributions: true); }, "project settings rollback", - rollbackFailures); + rollbackFailures + ); if (rollbackFailures.Count > 1) { throw new AggregateException( "Initial Plugin activation failed and the host-only generation could not be restored.", - rollbackFailures); + rollbackFailures + ); } var discovery = new PluginScanResult( @@ -709,8 +766,10 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) .. initialScan.diagnostics, new PluginDiagnostic( m_pluginRoot, - $"Initial Plugin candidate activation failed and was isolated: {candidateFailure.Message}") - ]); + $"Initial Plugin candidate activation failed and was isolated: {candidateFailure.Message}" + ) + ] + ); m_catalog.PublishDiscovery(discovery); return empty; } @@ -748,13 +807,15 @@ PluginScanResult candidate .Where(static plugin => plugin.containsCode) .ToDictionary(static plugin => plugin.manifest.pluginId, static plugin => plugin.contentHash, StringComparer.Ordinal); return oldCode.Count != newCode.Count - || oldCode.Any(pair => !newCode.TryGetValue(pair.Key, out string? hash) - || !string.Equals(pair.Value, hash, StringComparison.Ordinal)); + || oldCode.Any(pair => ( + !newCode.TryGetValue(pair.Key, out string? hash) + || !string.Equals(pair.Value, hash, StringComparison.Ordinal) + )); } private string ComputeActiveFingerprint(PluginScanResult scan) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (PluginCandidate candidate in PluginSourceService.GetActivatableCandidates(scan)) { hash.AppendData(Encoding.UTF8.GetBytes(candidate.manifest.pluginId)); @@ -766,25 +827,22 @@ private string ComputeActiveFingerprint(PluginScanResult scan) private static string ComputeInstallationFingerprint(string pluginRoot) { Directory.CreateDirectory(pluginRoot); - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - string[] paths = Directory.EnumerateFileSystemEntries( - pluginRoot, - "*", - SearchOption.TopDirectoryOnly) + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + string[] paths = Directory.EnumerateFileSystemEntries(pluginRoot, "*", SearchOption.TopDirectoryOnly) .ToArray(); foreach (string path in paths.OrderBy(static value => value, StringComparer.OrdinalIgnoreCase)) { - FileAttributes attributes = System.IO.File.GetAttributes(path); + FileAttributes attributes = File.GetAttributes(path); string relative = Path.GetRelativePath(pluginRoot, path).Replace('\\', '/'); hash.AppendData(Encoding.UTF8.GetBytes(relative)); hash.AppendData(BitConverter.GetBytes((int)attributes)); if ((attributes & FileAttributes.Directory) != 0) { - DirectoryInfo directory = new(path); + var directory = new DirectoryInfo(path); hash.AppendData(BitConverter.GetBytes(directory.LastWriteTimeUtc.Ticks)); continue; } - FileInfo file = new(path); + var file = new FileInfo(path); hash.AppendData(BitConverter.GetBytes(file.Length)); hash.AppendData(BitConverter.GetBytes(file.LastWriteTimeUtc.Ticks)); } @@ -805,24 +863,29 @@ string candidateFingerprint internal string candidateFingerprint { get; } = candidateFingerprint; internal bool isActivated { get; set; } } + private sealed class AvailabilityPublication : IGenerationPublication, IAssemblyUnloadProbe { /// /// Gets the user-facing explanation of this feature or setting. /// public string description => "Plugin content publication without assembly retirement"; + /// /// Gets whether this implementation is completed. /// public bool isCompleted => true; + /// /// Leaves assembly publication unchanged while the content participant publishes its candidate. /// - public void Activate() { } + public void Activate() {} + /// /// Restores the state that existed before candidate activation began. /// - public void Rollback() { } + public void Rollback() {} + /// /// Completes the committed operation and releases temporary state. /// diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs index 734b5d1ed..e552828f9 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs @@ -53,8 +53,10 @@ public void Apply() public void Validate(IReadOnlyList changes) { if (m_owner.activePlugins.Select(static plugin => plugin.sourceMount.id).Distinct().Count() - != m_owner.activePlugins.Count) + != m_owner.activePlugins.Count + ) { throw new InvalidOperationException("Plugin publication contains duplicate source identities."); + } // Setting and Plugin IDs identify protocols, not live objects. Asset slots are validated by the mount // transaction; composing settings above restores their references with the owner's complete context. } @@ -80,7 +82,9 @@ public void RestorePreviousState() { m_owner.RollbackPending(); if (!m_prepared) + { return; + } m_assets.Update(); m_settings.RestorePreviousState(); } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs new file mode 100644 index 000000000..91825bb9b --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Plugins.Authoring; + +/// +/// Contains a complete immutable Plugin discovery result. +/// +public sealed class PluginScanResult +{ + internal PluginScanResult( + IReadOnlyList candidates, + IReadOnlyList diagnostics + ) { + this.candidates = Array.AsReadOnly(candidates.ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets dependency-ordered valid candidates. + /// + public IReadOnlyList candidates { get; } + + /// + /// Gets isolated diagnostics for rejected candidates. + /// + public IReadOnlyList diagnostics { get; } +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs new file mode 100644 index 000000000..83581dfe5 --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs @@ -0,0 +1,16 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Identifies how an .iplugin package participates in one installation. +/// +public enum PluginSourceKind +{ + /// + /// The Plugin is installed as one top-level .iplugin package. + /// + Package, + /// + /// The Plugin is embedded as one complete .iplugin dependency package. + /// + EmbeddedPackage +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs new file mode 100644 index 000000000..49b86e9dc --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs @@ -0,0 +1,42 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Controls bounded validation and archive extraction for installed Plugin packages. +/// +public sealed class PluginSourceLimits +{ + /// + /// Gets default conservative local Plugin limits. + /// + public static PluginSourceLimits defaults { get; } = new(); + + /// + /// Gets or initializes the maximum number of source entries. + /// + public int maximumEntryCount { get; init; } = 100_000; + + /// + /// Gets or initializes the maximum size of one source file. + /// + public long maximumFileBytes { get; init; } = 64L * 1024 * 1024; + + /// + /// Gets or initializes the maximum total source size. + /// + public long maximumTotalBytes { get; init; } = 1024L * 1024 * 1024; + + /// + /// Gets or initializes the maximum accepted archive uncompressed-to-compressed ratio. + /// + public double maximumCompressionRatio { get; init; } = 200d; + + /// + /// Gets or initializes the maximum number of embedded dependency packages in one installation. + /// + public int maximumEmbeddedPluginCount { get; init; } = 256; + + /// + /// Gets or initializes the maximum nested embedded dependency depth. + /// + public int maximumEmbeddedDepth { get; init; } = 16; +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs deleted file mode 100644 index e2f57e6b9..000000000 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Core.Settings; -using Inno.Assets.Pipeline; -using Inno.Plugins; - -namespace Inno.Plugins.Authoring; - -/// -/// Identifies how an .iplugin package participates in one installation. -/// -public enum PluginSourceKind -{ - /// - /// The Plugin is installed as one top-level .iplugin package. - /// - Package, - - /// - /// The Plugin is embedded as one complete .iplugin dependency package. - /// - EmbeddedPackage -} - -/// -/// Controls bounded validation and archive extraction for installed Plugin packages. -/// -public sealed class PluginSourceLimits -{ - /// - /// Gets default conservative local Plugin limits. - /// - public static PluginSourceLimits defaults { get; } = new(); - - /// - /// Gets or initializes the maximum number of source entries. - /// - public int maximumEntryCount { get; init; } = 100_000; - - /// - /// Gets or initializes the maximum size of one source file. - /// - public long maximumFileBytes { get; init; } = 64L * 1024 * 1024; - - /// - /// Gets or initializes the maximum total source size. - /// - public long maximumTotalBytes { get; init; } = 1024L * 1024 * 1024; - - /// - /// Gets or initializes the maximum accepted archive uncompressed-to-compressed ratio. - /// - public double maximumCompressionRatio { get; init; } = 200d; - - /// - /// Gets or initializes the maximum number of embedded dependency packages in one installation. - /// - public int maximumEmbeddedPluginCount { get; init; } = 256; - - /// - /// Gets or initializes the maximum nested embedded dependency depth. - /// - public int maximumEmbeddedDepth { get; init; } = 16; -} - -/// -/// Describes one validated installed Plugin source candidate. -/// -public sealed class PluginCandidate -{ - private readonly PluginManifest m_manifest; - internal PluginCandidate( - string sourcePath, - PluginSourceKind sourceKind, - string contentHash, - PluginManifest manifest, - AssetSourceMount sourceMount, - bool containsCode - ) { - this.sourcePath = sourcePath; - this.sourceKind = sourceKind; - this.contentHash = contentHash; - m_manifest = CloneManifest(manifest); - this.sourceMount = sourceMount; - this.containsCode = containsCode; - } - - /// - /// Gets the installed .iplugin package path. - /// - public string sourcePath { get; } - - /// - /// Gets the physical source container kind. - /// - public PluginSourceKind sourceKind { get; } - - /// - /// Gets the deterministic complete source-content hash. - /// - public string contentHash { get; } - - /// - /// Gets a detached copy of the validated native manifest, including its nested contribution payloads. - /// - public PluginManifest manifest => CloneManifest(m_manifest); - - /// - /// Gets the isolated read-only asset source mount. - /// - public AssetSourceMount sourceMount { get; } - - /// - /// Gets whether source code exists in this Plugin. - /// - public bool containsCode { get; } - - private static PluginManifest CloneManifest(PluginManifest value) => new() - { - pluginId = value.pluginId, displayName = value.displayName, - dependencies = value.dependencies.ToArray(), overrides = value.overrides.ToArray(), - contentRoots = value.contentRoots.ToArray(), assemblyDefinitions = value.assemblyDefinitions.ToArray(), - settingContributions = value.settingContributions.Select(static record => new ProjectSettingRecord( - record.id, record.stableTypeId, record.propertyData)).ToArray() - }; - -} - -/// -/// Reports one Plugin discovery, validation, or dependency problem. -/// -public sealed class PluginDiagnostic -{ - /// - /// Creates a Plugin source diagnostic. - /// - /// - /// Related .iplugin package path or invalid installation entry. - /// - /// - /// Actionable problem description. - /// - public PluginDiagnostic( - string sourcePath, - string message - ) { - this.sourcePath = sourcePath ?? string.Empty; - this.message = message ?? string.Empty; - } - - /// - /// Gets the related .iplugin package path or invalid installation entry. - /// - public string sourcePath { get; } - - /// - /// Gets the actionable problem description. - /// - public string message { get; } -} - -/// -/// Contains a complete immutable Plugin discovery result. -/// -public sealed class PluginScanResult -{ - internal PluginScanResult( - IReadOnlyList candidates, - IReadOnlyList diagnostics - ) { - this.candidates = Array.AsReadOnly(candidates.ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets dependency-ordered valid candidates. - /// - public IReadOnlyList candidates { get; } - - /// - /// Gets isolated diagnostics for rejected candidates. - /// - public IReadOnlyList diagnostics { get; } -} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs index d65acc458..bee290041 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs @@ -7,11 +7,11 @@ using System.Security.Cryptography; using System.Text; using Inno.Assets; -using Inno.Plugins; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.IO; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Plugins; namespace Inno.Plugins.Authoring; @@ -20,11 +20,12 @@ namespace Inno.Plugins.Authoring; /// public sealed class PluginSourceService { - private static readonly HashSet S_FORBIDDEN_BINARY_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet FORBIDDEN_BINARY_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) { ".dll", ".exe", ".dylib", ".so", ".a", ".lib" }; - private static readonly HashSet S_IGNORED_SYSTEM_FILE_NAMES = new(StringComparer.OrdinalIgnoreCase) + + private static readonly HashSet IGNORED_SYSTEM_FILE_NAMES = new(StringComparer.OrdinalIgnoreCase) { ".DS_Store", "Thumbs.db", "desktop.ini" }; @@ -74,13 +75,16 @@ public PluginSourceService( /// public PluginScanResult Scan() { - var candidates = new List(); - var diagnostics = new List(); + List candidates = []; + List diagnostics = []; foreach (string unsupported in DiscoverUnsupportedSources()) { - diagnostics.Add(new PluginDiagnostic( - unsupported, - "Plugin installations must be .iplugin package files; directories and other file extensions are not supported.")); + diagnostics.Add( + new PluginDiagnostic( + unsupported, + "Plugin installations must be .iplugin package files; directories and other file extensions are not supported." + ) + ); } foreach (string packagePath in DiscoverPackages()) { @@ -127,30 +131,29 @@ public static IReadOnlyList GetActivatableCandidates(PluginScan } private IEnumerable DiscoverPackages() - { - return Directory + => Directory .EnumerateFiles(m_pluginRoot, "*", SearchOption.TopDirectoryOnly) .Where(static path => string.Equals( Path.GetExtension(path), ".iplugin", - StringComparison.OrdinalIgnoreCase)) + StringComparison.OrdinalIgnoreCase + )) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); - } private IEnumerable DiscoverUnsupportedSources() - { - return Directory + => Directory .EnumerateFileSystemEntries(m_pluginRoot, "*", SearchOption.TopDirectoryOnly) .Where(path => { string name = Path.GetFileName(path); - if (name.StartsWith(".", StringComparison.Ordinal) || S_IGNORED_SYSTEM_FILE_NAMES.Contains(name)) + if (name.StartsWith(".", StringComparison.Ordinal) || IGNORED_SYSTEM_FILE_NAMES.Contains(name)) + { return false; + } return Directory.Exists(path) - || !string.Equals(Path.GetExtension(path), ".iplugin", StringComparison.OrdinalIgnoreCase); + || !string.Equals(Path.GetExtension(path), ".iplugin", StringComparison.OrdinalIgnoreCase); }) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); - } private IReadOnlyList ValidatePackage(string packagePath) { @@ -165,7 +168,9 @@ private IReadOnlyList ValidatePackage( ref int embeddedCount ) { if (depth > m_limits.maximumEmbeddedDepth) + { throw new InvalidDataException("Plugin dependency packages exceed the configured nesting limit."); + } using ZipArchive archive = ZipFile.OpenRead(packagePath); ValidatedPackageEntry[] entries = ValidatePackageEntries(archive).ToArray(); ValidatedPackageEntry manifestEntry = entries.SingleOrDefault(static value => value.path == "Plugin.inno") @@ -178,40 +183,39 @@ ref int embeddedCount string destinationRoot = Path.Combine(m_cacheRoot, manifest.pluginId, contentHash); string contentRoot = Path.Combine(destinationRoot, "Assets"); if (!Directory.Exists(contentRoot)) + { ExtractAtomically(archive, entries, destinationRoot); + } ValidateMaterializedSnapshot(entries, destinationRoot); bool containsCode = ContainsCode(entries.Select(static entry => entry.path)); - var candidates = new List - { - CreateCandidate( - packagePath, - sourceKind, - contentHash, - manifest, - contentRoot, - containsCode) - }; - foreach (ValidatedPackageEntry dependency in entries.Where(static entry => - entry.path.StartsWith("Dependencies/", StringComparison.Ordinal) - && entry.path.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase))) - { + List candidates = [CreateCandidate(packagePath, sourceKind, contentHash, manifest, contentRoot, containsCode)]; + foreach (ValidatedPackageEntry dependency in entries.Where(static entry => ( + entry.path.StartsWith("Dependencies/", StringComparison.Ordinal) + && entry.path.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase) + )) + ) { embeddedCount++; if (embeddedCount > m_limits.maximumEmbeddedPluginCount) + { throw new InvalidDataException("Plugin installation exceeds the embedded package-count limit."); + } string extractedPath = Path.Combine( destinationRoot, - dependency.path.Replace('/', Path.DirectorySeparatorChar)); + dependency.path.Replace('/', Path.DirectorySeparatorChar) + ); IReadOnlyList embedded = ValidatePackage( extractedPath, PluginSourceKind.EmbeddedPackage, depth + 1, - ref embeddedCount); + ref embeddedCount + ); PluginCandidate direct = embedded[0]; if (!manifest.dependencies.Contains(direct.manifest.pluginId, StringComparer.Ordinal)) { throw new InvalidDataException( - $"Embedded Plugin '{direct.manifest.pluginId}' is not declared by '{manifest.pluginId}'."); + $"Embedded Plugin '{direct.manifest.pluginId}' is not declared by '{manifest.pluginId}'." + ); } candidates.AddRange(embedded); } @@ -225,23 +229,26 @@ private PluginCandidate CreateCandidate( PluginManifest manifest, string contentRoot, bool containsCode - ) - => new( - Path.GetFullPath(sourcePath), - sourceKind, - contentHash, - manifest, - new AssetSourceMount( - new AssetSourceId(manifest.pluginId), - contentRoot, - isReadOnly: true, - manifest.dependencies.Select(static dependency => new AssetSourceId(dependency))), - containsCode); + ) => new( + Path.GetFullPath(sourcePath), + sourceKind, + contentHash, + manifest, + new AssetSourceMount( + new AssetSourceID(manifest.pluginId), + contentRoot, + isReadOnly: true, + manifest.dependencies.Select(static dependency => new AssetSourceID(dependency)) + ), + containsCode + ); private IEnumerable ValidatePackageEntries(ZipArchive archive) { if (archive.Entries.Count > m_limits.maximumEntryCount) + { throw new InvalidDataException("The .iplugin package exceeds the configured entry-count limit."); + } var paths = new PortablePathSet(".iplugin package"); long totalBytes = 0; @@ -249,18 +256,24 @@ private IEnumerable ValidatePackageEntries(ZipArchive arc { string path = ValidatePortablePath(entry.FullName); if (IsSymbolicLink(entry)) + { throw new InvalidDataException($"Plugin package entry '{path}' is a symbolic link."); + } if (IsIgnoredSystemFile(path)) + { continue; + } paths.Add(path); ValidateFileSize(path, entry.Length, ref totalBytes); if (entry.Length > 0) { double ratio = entry.CompressedLength == 0 - ? double.PositiveInfinity - : (double)entry.Length / entry.CompressedLength; + ? double.PositiveInfinity + : (double)entry.Length / entry.CompressedLength; if (ratio > m_limits.maximumCompressionRatio) + { throw new InvalidDataException($"Plugin package entry '{path}' exceeds the compression-ratio limit."); + } } ValidateSourceExtension(path); yield return new ValidatedPackageEntry(path, entry); @@ -273,17 +286,82 @@ private void ValidateFileSize( ref long totalBytes ) { if (length > m_limits.maximumFileBytes) + { throw new InvalidDataException($"Plugin source '{path}' exceeds the file-size limit."); + } totalBytes = checked(totalBytes + length); if (totalBytes > m_limits.maximumTotalBytes) + { throw new InvalidDataException("Plugin source exceeds the total uncompressed-size limit."); + } + } + + private PluginManifest ReadManifest(ZipArchiveEntry entry) + { + try + { + using Stream stream = entry.Open(); + using var memory = new MemoryStream(); + stream.CopyTo(memory); + return m_serialization.Deserialize(memory.ToArray()); + } + catch (Exception exception) when (IsManifestDataFailure(exception)) + { + throw new InvalidDataException("Plugin.inno is malformed or incompatible with the current contract.", exception); + } + } + + private void ExtractAtomically( + ZipArchive archive, + IReadOnlyList entries, + string destinationRoot + ) { + string stagingRoot = Path.Combine(m_cacheRoot, ".staging", Guid.NewGuid().ToString("N")); + try + { + foreach (ValidatedPackageEntry item in entries) + { + string target = ResolveContainedPath(stagingRoot, item.path.TrimEnd('/')); + if (item.path.EndsWith("/", StringComparison.Ordinal)) + { + Directory.CreateDirectory(target); + continue; + } + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + using Stream source = item.entry.Open(); + using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None); + source.CopyTo(output); + } + + Directory.CreateDirectory(Path.GetDirectoryName(destinationRoot)!); + if (!Directory.Exists(destinationRoot)) + { + try + { + AtomicDirectory.Publish(stagingRoot, destinationRoot); + } + catch (IOException) when (Directory.Exists(destinationRoot)) + { + // A concurrent publisher may have committed the same immutable snapshot. + // Accept it only after checking its exact files and bytes against this archive. + ValidateMaterializedSnapshot(entries, destinationRoot); + } + } + } + finally + { + if (Directory.Exists(stagingRoot)) + { + Directory.Delete(stagingRoot, recursive: true); + } + } } private static void ValidateSourceExtension(string path) { if (!path.EndsWith("/", StringComparison.Ordinal) - && S_FORBIDDEN_BINARY_EXTENSIONS.Contains(Path.GetExtension(path))) - { + && FORBIDDEN_BINARY_EXTENSIONS.Contains(Path.GetExtension(path)) + ) { throw new InvalidDataException($"Plugin source '{path}' is a forbidden prebuilt binary."); } } @@ -299,35 +377,47 @@ private static void ValidateContent(IReadOnlyList entries) foreach (string path in paths) { if (path is "Plugin.inno" or "Assets/" or "Dependencies/" - || path.EndsWith("/", StringComparison.Ordinal)) + || path.EndsWith("/", StringComparison.Ordinal) + ) { continue; + } if (path.StartsWith("Dependencies/", StringComparison.Ordinal)) { string local = path["Dependencies/".Length..]; if (local.Contains('/') - || !local.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase)) - { + || !local.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidDataException( - $"Plugin dependency entry '{path}' must be one direct .iplugin package."); + $"Plugin dependency entry '{path}' must be one direct .iplugin package." + ); } continue; } if (!path.StartsWith("Assets/", StringComparison.Ordinal)) + { throw new InvalidDataException($"Unexpected root .iplugin package entry '{path}'."); + } if (path.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + { continue; + } if (!paths.Contains(path + ".imeta")) + { throw new InvalidDataException($"Plugin source '{path}' is missing its required .imeta sidecar."); + } } - foreach (string directory in paths.Where(static value => - value.StartsWith("Assets/", StringComparison.Ordinal) - && value.EndsWith("/", StringComparison.Ordinal) - && value != "Assets/")) - { + foreach (string directory in paths.Where(static value => ( + value.StartsWith("Assets/", StringComparison.Ordinal) + && value.EndsWith("/", StringComparison.Ordinal) + && value != "Assets/" + )) + ) { string sidecar = directory.TrimEnd('/') + ".imeta"; if (!paths.Contains(sidecar)) + { throw new InvalidDataException($"Plugin directory '{directory}' is missing its required .imeta sidecar."); + } } } @@ -335,36 +425,36 @@ private static IReadOnlyList ValidateDependencyGraph( IReadOnlyList candidates, List diagnostics ) { - var byId = new Dictionary(StringComparer.Ordinal); + var byID = new Dictionary(StringComparer.Ordinal); var rejected = new HashSet(StringComparer.Ordinal); foreach (IGrouping group in candidates.GroupBy( - static candidate => candidate.manifest.pluginId, - StringComparer.Ordinal)) - { + static candidate => candidate.manifest.pluginId, + StringComparer.Ordinal + )) { PluginCandidate[] installed = group.ToArray(); if (installed.Length == 1) { - byId.Add(group.Key, installed[0]); + byID.Add(group.Key, installed[0]); continue; } rejected.Add(group.Key); foreach (PluginCandidate duplicate in installed) { - diagnostics.Add(new PluginDiagnostic( - duplicate.sourcePath, - $"Plugin ID '{group.Key}' is installed more than once.")); + diagnostics.Add( + new PluginDiagnostic(duplicate.sourcePath, $"Plugin ID '{group.Key}' is installed more than once.") + ); } } foreach (PluginCandidate candidate in candidates.Where(candidate => - !rejected.Contains(candidate.manifest.pluginId))) - { - string? missing = candidate.manifest.dependencies.FirstOrDefault(id => !byId.ContainsKey(id)); + !rejected.Contains(candidate.manifest.pluginId)) + ) { + string? missing = candidate.manifest.dependencies.FirstOrDefault(id => !byID.ContainsKey(id)); if (missing is not null) { rejected.Add(candidate.manifest.pluginId); - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency '{missing}' is not installed.")); + diagnostics.Add( + new PluginDiagnostic(candidate.sourcePath, $"Plugin dependency '{missing}' is not installed.") + ); } } @@ -372,29 +462,35 @@ List diagnostics do { rejectionChanged = false; - foreach (PluginCandidate candidate in byId.Values) + foreach (PluginCandidate candidate in byID.Values) { if (rejected.Contains(candidate.manifest.pluginId)) + { continue; + } string? blocked = candidate.manifest.dependencies.FirstOrDefault(rejected.Contains); if (blocked is null) + { continue; + } rejected.Add(candidate.manifest.pluginId); rejectionChanged = true; - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency '{blocked}' is unavailable.")); + diagnostics.Add( + new PluginDiagnostic(candidate.sourcePath, $"Plugin dependency '{blocked}' is unavailable.") + ); } } while (rejectionChanged); var graph = new DependencyGraph(StringComparer.Ordinal, StringComparer.Ordinal); - foreach (PluginCandidate candidate in byId.Values.Where(candidate => - !rejected.Contains(candidate.manifest.pluginId))) - { + foreach (PluginCandidate candidate in byID.Values.Where(candidate => + !rejected.Contains(candidate.manifest.pluginId)) + ) { graph.AddNode(candidate.manifest.pluginId); foreach (string dependency in candidate.manifest.dependencies) + { graph.AddDependency(candidate.manifest.pluginId, dependency); + } } string[] cyclic = graph.GetStronglyConnectedComponents() .Where(component => component.Count > 1 || graph.DependsOn(component[0], component[0])) @@ -403,71 +499,70 @@ List diagnostics .ToArray(); var cycleBlocked = new HashSet(cyclic, StringComparer.Ordinal); foreach (string node in cyclic) - cycleBlocked.UnionWith(graph.GetDependents(node, recursive: true)); - foreach (string pluginId in cycleBlocked.OrderBy(static value => value, StringComparer.Ordinal)) - { - PluginCandidate candidate = byId[pluginId]; - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency cycle prevents '{pluginId}' from loading.")); - graph.RemoveNode(pluginId); - } - return graph.TopologicalSort().Select(pluginId => byId[pluginId]).ToArray(); - } - - private PluginManifest ReadManifest(ZipArchiveEntry entry) - { - try { - using Stream stream = entry.Open(); - using var memory = new MemoryStream(); - stream.CopyTo(memory); - return m_serialization.Deserialize(memory.ToArray()); + cycleBlocked.UnionWith(graph.GetDependents(node, recursive: true)); } - catch (Exception exception) when (IsManifestDataFailure(exception)) + foreach (string pluginID in cycleBlocked.OrderBy(static value => value, StringComparer.Ordinal)) { - throw new InvalidDataException("Plugin.inno is malformed or incompatible with the current contract.", exception); + PluginCandidate candidate = byID[pluginID]; + diagnostics.Add( + new PluginDiagnostic( + candidate.sourcePath, + $"Plugin dependency cycle prevents '{pluginID}' from loading." + ) + ); + graph.RemoveNode(pluginID); } + return graph.TopologicalSort().Select(pluginID => byID[pluginID]).ToArray(); } private static bool IsManifestDataFailure(Exception exception) => exception is InvalidDataException - or InvalidOperationException - or ArgumentException - or NotSupportedException - or OverflowException; + or InvalidOperationException + or ArgumentException + or NotSupportedException + or OverflowException; private static bool ContainsCode(IEnumerable paths) - => paths.Any(static path => + => paths.Any(static path => ( path.StartsWith("Assets/", StringComparison.Ordinal) - && string.Equals(Path.GetExtension(path), ".cs", StringComparison.OrdinalIgnoreCase)); + && string.Equals(Path.GetExtension(path), ".cs", StringComparison.OrdinalIgnoreCase) + )); private static bool IsIgnoredSystemFile(string path) { if (path.EndsWith("/", StringComparison.Ordinal)) + { return false; + } int separator = path.LastIndexOf('/'); string fileName = separator < 0 ? path : path[(separator + 1)..]; - return S_IGNORED_SYSTEM_FILE_NAMES.Contains(fileName); + return IGNORED_SYSTEM_FILE_NAMES.Contains(fileName); } private static string ValidatePortablePath(string value) { if (string.IsNullOrWhiteSpace(value)) + { throw new InvalidDataException("Plugin source contains an empty entry path."); + } if (value.Contains('\\') || value.StartsWith("/", StringComparison.Ordinal) || Path.IsPathRooted(value)) + { throw new InvalidDataException($"Plugin source entry '{value}' is not a portable relative path."); + } string path = value.Normalize(NormalizationForm.FormC); if (!string.Equals(path, value, StringComparison.Ordinal)) + { throw new InvalidDataException($"Plugin source entry '{value}' is not Unicode-normalized."); + } string[] segments = path.TrimEnd('/').Split('/'); foreach (string segment in segments) { if (segment is "" or "." or ".." || segment.EndsWith(' ') || segment.EndsWith('.') || segment.IndexOfAny(['<', '>', ':', '"', '|', '?', '*']) >= 0 - || IsWindowsDeviceName(segment)) - { + || IsWindowsDeviceName(segment) + ) { throw new InvalidDataException($"Plugin source entry '{value}' has a non-portable segment."); } } @@ -478,82 +573,48 @@ private static bool IsWindowsDeviceName(string segment) { string name = Path.GetFileNameWithoutExtension(segment).ToUpperInvariant(); return name is "CON" or "PRN" or "AUX" or "NUL" - || name.Length == 4 - && (name.StartsWith("COM", StringComparison.Ordinal) || name.StartsWith("LPT", StringComparison.Ordinal)) - && name[3] is >= '1' and <= '9'; + || name.Length == 4 + && (name.StartsWith("COM", StringComparison.Ordinal) || name.StartsWith("LPT", StringComparison.Ordinal)) + && name[3] is >= '1' and <= '9'; } private static bool IsSymbolicLink(ZipArchiveEntry entry) => ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000; - private void ExtractAtomically( - ZipArchive archive, - IReadOnlyList entries, - string destinationRoot - ) { - string stagingRoot = Path.Combine(m_cacheRoot, ".staging", Guid.NewGuid().ToString("N")); - try - { - foreach (ValidatedPackageEntry item in entries) - { - string target = ResolveContainedPath(stagingRoot, item.path.TrimEnd('/')); - if (item.path.EndsWith("/", StringComparison.Ordinal)) - { - Directory.CreateDirectory(target); - continue; - } - Directory.CreateDirectory(Path.GetDirectoryName(target)!); - using Stream source = item.entry.Open(); - using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None); - source.CopyTo(output); - } - - Directory.CreateDirectory(Path.GetDirectoryName(destinationRoot)!); - if (!Directory.Exists(destinationRoot)) - { - try - { - AtomicDirectory.Publish(stagingRoot, destinationRoot); - } - catch (IOException) when (Directory.Exists(destinationRoot)) - { - // A concurrent publisher may have committed the same immutable snapshot. - // Accept it only after checking its exact files and bytes against this archive. - ValidateMaterializedSnapshot(entries, destinationRoot); - } - } - } - finally - { - if (Directory.Exists(stagingRoot)) - Directory.Delete(stagingRoot, recursive: true); - } - } - private static void ValidateMaterializedSnapshot( IReadOnlyList entries, string destinationRoot ) { ValidatedPackageEntry[] files = entries.Where(static item => !item.path.EndsWith("/", StringComparison.Ordinal)) - .OrderBy(static item => item.path, StringComparer.Ordinal).ToArray(); + .OrderBy(static item => item.path, StringComparer.Ordinal) + .ToArray(); string[] actual = PathBoundary.EnumerateFiles(destinationRoot) .Select(path => Path.GetRelativePath(destinationRoot, path).Replace('\\', '/')) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (!actual.SequenceEqual(files.Select(static item => item.path), StringComparer.Ordinal)) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has an incomplete or unexpected file set."); + } foreach (ValidatedPackageEntry item in entries.Where(static item => item.path.EndsWith("/", StringComparison.Ordinal))) { if (!Directory.Exists(ResolveContainedPath(destinationRoot, item.path.TrimEnd('/')))) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' is missing directory '{item.path}'."); + } } foreach (ValidatedPackageEntry item in files) { string physical = ResolveContainedPath(destinationRoot, item.path); if (new FileInfo(physical).Length != item.entry.Length) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has an invalid length for '{item.path}'."); + } using Stream expected = item.entry.Open(); - using FileStream materialized = new(physical, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + using var materialized = new FileStream(physical, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); if (!SHA256.HashData(materialized).AsSpan().SequenceEqual(SHA256.HashData(expected))) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has invalid bytes for '{item.path}'."); + } } } @@ -567,20 +628,20 @@ string relativePath } catch (Exception exception) when (exception is ArgumentException or IOException) { - throw new InvalidDataException( - "Plugin source entry escaped its generation snapshot root.", - exception); + throw new InvalidDataException("Plugin source entry escaped its generation snapshot root.", exception); } } private static string ComputePackageContentHash(IReadOnlyList entries) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (ValidatedPackageEntry item in entries.OrderBy(static entry => entry.path, StringComparer.Ordinal)) { AppendPath(hash, item.path); if (item.path.EndsWith("/", StringComparison.Ordinal)) + { continue; + } using Stream stream = item.entry.Open(); AppendStream(hash, stream); } @@ -602,10 +663,12 @@ private static void AppendStream( IncrementalHash hash, Stream stream ) { - byte[] buffer = new byte[64 * 1024]; + var buffer = new byte[64 * 1024]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + { hash.AppendData(buffer.AsSpan(0, read)); + } } private sealed class PortablePathSet(string sourceDescription) @@ -618,10 +681,11 @@ internal void Add(string path) { if (!m_ordinal.Add(path) || !m_portable.Add(path) - || !m_decomposed.Add(path.Normalize(NormalizationForm.FormD))) - { + || !m_decomposed.Add(path.Normalize(NormalizationForm.FormD)) + ) { throw new InvalidDataException( - $"Plugin {sourceDescription} contains a duplicate or non-portable path '{path}'."); + $"Plugin {sourceDescription} contains a duplicate or non-portable path '{path}'." + ); } } } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs b/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs index 34f29919b..ab700a4d9 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs @@ -1,6 +1,3 @@ using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Plugins", - "Inno.Plugins.Authoring", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Plugins", "Inno.Plugins.Authoring", ScriptingApiScope.Editor)] diff --git a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs index 5bf329d50..fd3e0b599 100644 --- a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs +++ b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs @@ -1,8 +1,9 @@ using System; using System.IO; using System.Linq; -using Inno.Core.Settings; +using Inno.Assets; using Inno.Core.Serialization; +using Inno.Core.Settings; namespace Inno.Plugins; @@ -63,52 +64,72 @@ public void Validate() { try { - _ = new Inno.Assets.AssetSourceId(pluginId); + _ = new AssetSourceID(pluginId); } catch (ArgumentException exception) { throw new InvalidDataException("Plugin.inno contains an invalid Plugin ID.", exception); } - if (string.Equals(pluginId, Inno.Assets.AssetSourceId.project.value, StringComparison.Ordinal)) + if (string.Equals(pluginId, AssetSourceID.project.value, StringComparison.Ordinal)) + { throw new InvalidDataException("Plugin ID 'project' is reserved by the writable project source."); + } if (string.IsNullOrWhiteSpace(displayName)) + { throw new InvalidDataException("Plugin.inno requires a display name."); - EnsureUniquePluginIds(dependencies, nameof(dependencies)); - EnsureUniquePluginIds(overrides, nameof(overrides)); + } + EnsureUniquePluginIDs(dependencies, nameof(dependencies)); + EnsureUniquePluginIDs(overrides, nameof(overrides)); EnsureUniquePaths(contentRoots, nameof(contentRoots)); EnsureUniquePaths(assemblyDefinitions, nameof(assemblyDefinitions)); if (dependencies.Contains(pluginId, StringComparer.Ordinal)) + { throw new InvalidDataException("A Plugin cannot depend on itself."); + } if (overrides.Any(value => !dependencies.Contains(value, StringComparer.Ordinal))) + { throw new InvalidDataException("Every explicit override must identify a declared dependency."); + } if (settingContributions is null) + { throw new InvalidDataException("Plugin setting contributions cannot be null."); + } if (settingContributions.Select(static value => value.id).Distinct().Count() != settingContributions.Length) + { throw new InvalidDataException("Plugin setting contributions must use unique setting IDs."); + } foreach (ProjectSettingRecord contribution in settingContributions) { if (!contribution.id.isValid || contribution.stableTypeId == Guid.Empty || contribution.propertyData is null - || contribution.propertyData.Length == 0) - { + || contribution.propertyData.Length == 0 + ) { throw new InvalidDataException("Plugin setting contribution contains invalid identity or payload data."); } } if (contentRoots.Length != 1 || !string.Equals(contentRoots[0], "Assets", StringComparison.Ordinal)) + { throw new InvalidDataException("The current local Plugin container requires the single content root 'Assets'."); + } } - private static void EnsureUniquePluginIds( + private static void EnsureUniquePluginIDs( string[] values, string name ) { if (values is null || values.Any(string.IsNullOrWhiteSpace)) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains an empty value."); + } if (values.Distinct(StringComparer.Ordinal).Count() != values.Length) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains duplicate values."); + } foreach (string value in values) - _ = new Inno.Assets.AssetSourceId(value); + { + _ = new AssetSourceID(value); + } } private static void EnsureUniquePaths( @@ -116,17 +137,25 @@ private static void EnsureUniquePaths( string name ) { if (values is null || values.Any(string.IsNullOrWhiteSpace)) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains an empty path."); + } string[] normalized = values.Select(static value => { if (value.Contains('\\') || value.StartsWith("/", StringComparison.Ordinal)) + { throw new InvalidDataException("Plugin manifest paths must be portable container-relative paths."); + } string path = value.Trim('/'); if (path.Split('/').Any(static segment => segment is "" or "." or "..")) + { throw new InvalidDataException("Plugin manifest paths cannot contain traversal segments."); + } return path; }).ToArray(); if (normalized.Distinct(StringComparer.OrdinalIgnoreCase).Count() != normalized.Length) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains duplicate paths."); + } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs index b52485954..d75a90aaa 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs @@ -1,59 +1,20 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scripting.Compiler; /// /// Defines one project script assembly and its compilation policy. /// -[StableTypeId("038c096e-81e9-41dd-a8fb-fd0200ca2acb")] +[StableTypeID("038c096e-81e9-41dd-a8fb-fd0200ca2acb")] public sealed class ScriptAssemblyDefinitionAsset : AssetObject { - /// - /// Gets the stable assembly name. - /// - [SerializableProperty] - public string assemblyName { get; private set; } = string.Empty; - - /// - /// Gets the assembly API scope. - /// - [SerializableProperty] - public ScriptAssemblyScope scope { get; private set; } - - /// - /// Gets referenced script assembly names. - /// - [SerializableProperty] - public string[] references { get; private set; } = []; - - /// - /// Gets preprocessor symbols applied to this assembly. - /// - [SerializableProperty] - public string[] defines { get; private set; } = []; - - /// - /// Gets whether nullable reference analysis is enabled. - /// - [SerializableProperty] - public bool nullable { get; private set; } = true; - - /// - /// Gets whether unsafe source is permitted. - /// - [SerializableProperty] - public bool allowUnsafe { get; private set; } - /// /// Creates an empty definition asset for deserialization. /// - public ScriptAssemblyDefinitionAsset() - { - } + public ScriptAssemblyDefinitionAsset() {} /// /// Creates a configured script assembly definition for native asset export. @@ -95,4 +56,40 @@ public ScriptAssemblyDefinitionAsset( this.nullable = nullable; this.allowUnsafe = allowUnsafe; } + + /// + /// Gets the stable assembly name. + /// + [SerializableProperty] + public string assemblyName { get; private set; } = string.Empty; + + /// + /// Gets the assembly API scope. + /// + [SerializableProperty] + public ScriptAssemblyScope scope { get; private set; } + + /// + /// Gets referenced script assembly names. + /// + [SerializableProperty] + public string[] references { get; private set; } = []; + + /// + /// Gets preprocessor symbols applied to this assembly. + /// + [SerializableProperty] + public string[] defines { get; private set; } = []; + + /// + /// Gets whether nullable reference analysis is enabled. + /// + [SerializableProperty] + public bool nullable { get; private set; } = true; + + /// + /// Gets whether unsafe source is permitted. + /// + [SerializableProperty] + public bool allowUnsafe { get; private set; } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs index b6356b307..91d6ddff5 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs @@ -9,7 +9,6 @@ public enum ScriptAssemblyScope /// The assembly can use runtime scripting APIs only. /// Runtime, - /// /// The assembly can use runtime and editor scripting APIs. /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs index fdb84cb9d..f9e6c7f47 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs @@ -1,15 +1,30 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scripting.Compiler; /// /// Describes an imported C# source snapshot and its parse diagnostics. /// -[StableTypeId("10de711f-c33e-4ae2-a2e3-df285a86e976")] +[StableTypeID("10de711f-c33e-4ae2-a2e3-df285a86e976")] public sealed class ScriptSourceAsset : AssetObject { + /// + /// Creates an empty script source asset for deserialization. + /// + public ScriptSourceAsset() {} + + internal ScriptSourceAsset( + ScriptAssemblyScope scope, + string[] declaredTypeNames, + string[] parseDiagnostics + ) { + this.scope = scope; + this.declaredTypeNames = declaredTypeNames; + this.parseDiagnostics = parseDiagnostics; + } + /// /// Gets the default assembly scope inferred for the source. /// @@ -27,21 +42,4 @@ public sealed class ScriptSourceAsset : AssetObject /// [SerializableProperty] public string[] parseDiagnostics { get; private set; } = []; - - /// - /// Creates an empty script source asset for deserialization. - /// - public ScriptSourceAsset() - { - } - - internal ScriptSourceAsset( - ScriptAssemblyScope scope, - string[] declaredTypeNames, - string[] parseDiagnostics - ) { - this.scope = scope; - this.declaredTypeNames = declaredTypeNames; - this.parseDiagnostics = parseDiagnostics; - } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs new file mode 100644 index 000000000..c4bb9c7a0 --- /dev/null +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs @@ -0,0 +1,61 @@ +namespace Inno.Scripting.Compiler; + +internal struct ScriptSourceTypeDeclaration +{ + /// + /// Creates a validated script source type declaration instance. + /// + /// + /// The type name text validated by the script source type declaration operation. + /// + /// + /// The declaration kind text validated by the script source type declaration operation. + /// + /// + /// Whether partial behavior is enabled while script source type declaration executes. + /// + /// + /// The line consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The column consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. + /// + public ScriptSourceTypeDeclaration( + string typeName, + string declarationKind, + bool partial, + int line, + int column + ) { + this.typeName = typeName; + this.declarationKind = declarationKind; + this.partial = partial; + this.line = line; + this.column = column; + } + + /// + /// Gets text used for stable identity, presentation, or diagnostics by this contract. + /// + public string typeName { get; set; } + + /// + /// Gets text used for stable identity, presentation, or diagnostics by this contract. + /// + public string declarationKind { get; set; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool partial { get; set; } + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int line { get; set; } + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int column { get; set; } +} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs index 4f97870d2..b98d80101 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs @@ -8,14 +8,12 @@ internal sealed class ScriptSourceTypeManifest : ISerializable /// /// Creates a validated script source type manifest instance. /// - public ScriptSourceTypeManifest() - { - } + public ScriptSourceTypeManifest() {} /// /// Creates a validated script source type manifest instance. /// - /// + /// /// The source persistent id consumed by script source type manifest; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -25,11 +23,11 @@ public ScriptSourceTypeManifest() /// The declarations consumed by script source type manifest; ownership remains with the caller unless explicitly stated otherwise. /// public ScriptSourceTypeManifest( - Guid sourcePersistentId, + Guid sourcePersistentID, string sourcePath, ScriptSourceTypeDeclaration[] declarations ) { - this.sourcePersistentId = sourcePersistentId; + this.sourcePersistentId = sourcePersistentID; this.sourcePath = sourcePath; this.declarations = declarations; } @@ -52,59 +50,3 @@ ScriptSourceTypeDeclaration[] declarations [SerializableProperty] public ScriptSourceTypeDeclaration[] declarations { get; set; } = []; } - -internal struct ScriptSourceTypeDeclaration -{ - /// - /// Creates a validated script source type declaration instance. - /// - /// - /// The type name text validated by the script source type declaration operation. - /// - /// - /// The declaration kind text validated by the script source type declaration operation. - /// - /// - /// Whether partial behavior is enabled while script source type declaration executes. - /// - /// - /// The line consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The column consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. - /// - public ScriptSourceTypeDeclaration( - string typeName, - string declarationKind, - bool partial, - int line, - int column - ) { - this.typeName = typeName; - this.declarationKind = declarationKind; - this.partial = partial; - this.line = line; - this.column = column; - } - - /// - /// Gets text used for stable identity, presentation, or diagnostics by this contract. - /// - public string typeName { get; set; } - /// - /// Gets text used for stable identity, presentation, or diagnostics by this contract. - /// - public string declarationKind { get; set; } - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool partial { get; set; } - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int line { get; set; } - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int column { get; set; } -} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs index 916a943f2..83934bfb8 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs @@ -3,10 +3,10 @@ using System.IO; using System.Linq; using System.Text; -using Inno.Assets.Pipeline; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Assets.Pipeline; namespace Inno.Scripting.Compiler; @@ -26,24 +26,34 @@ public void Transform(AssetSampleTransformContext context) { ArgumentNullException.ThrowIfNull(context); foreach (string path in Directory.GetFiles(context.stagedRoot, "*.cs", SearchOption.AllDirectories) - .Order(StringComparer.Ordinal)) - { + .Order(StringComparer.Ordinal) + ) { context.cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(context.stagedRoot, path).Replace('\\', '/'); - if (!context.TryGetSourceIdentity(relative, out Guid oldSourceId, out Guid newSourceId)) + if (!context.TryGetSourceIdentity(relative, out Guid oldSourceID, out Guid newSourceID)) + { throw new InvalidDataException($"Sample C# source '{relative}' has no asset identity metadata."); - context.MapType(ScriptTypeIdentity.CreateCanonical(oldSourceId), - ScriptTypeIdentity.CreateCanonical(newSourceId)); + } + context.MapType( + ScriptTypeIdentity.CreateCanonical(oldSourceID), + ScriptTypeIdentity.CreateCanonical(newSourceID) + ); byte[] bytes = File.ReadAllBytes(path); bool hasBom = bytes.AsSpan().StartsWith(Encoding.UTF8.GetPreamble()); string source = File.ReadAllText(path, Encoding.UTF8); SyntaxNode root = CSharpSyntaxTree.ParseText( - source, cancellationToken: context.cancellationToken).GetRoot(context.cancellationToken); - AttributeSyntax[] attributes = root.DescendantNodes().OfType() - .Where(static attribute => IsStableTypeId(attribute.Name.ToString())).ToArray(); + source, + cancellationToken: context.cancellationToken + ).GetRoot(context.cancellationToken); + AttributeSyntax[] attributes = root.DescendantNodes() + .OfType() + .Where(static attribute => IsStableTypeID(attribute.Name.ToString())) + .ToArray(); if (attributes.Length == 0) + { continue; + } SyntaxNode rewritten = root.ReplaceNodes(attributes, ( original, _ @@ -53,23 +63,28 @@ public void Transform(AssetSampleTransformContext context) if (attribute.ArgumentList?.Arguments is not { Count: 1 } arguments || arguments[0].Expression is not LiteralExpressionSyntax literal || !literal.IsKind(SyntaxKind.StringLiteralExpression) - || !Guid.TryParse(literal.Token.ValueText, out Guid oldId)) - { + || !Guid.TryParse(literal.Token.ValueText, out Guid oldID) + ) { throw new InvalidDataException( - $"Sample C# source '{relative}' has a StableTypeId that cannot be cloned safely."); + $"Sample C# source '{relative}' has a StableTypeID that cannot be cloned safely." + ); } - Guid newId = context.identityMap.TryGetValue(oldId, out Guid mapped) - ? mapped : Guid.NewGuid(); - context.MapType(oldId, newId); - LiteralExpressionSyntax replacement = SyntaxFactory.LiteralExpression( - SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newId.ToString("D"))) + Guid newID = context.identityMap.TryGetValue(oldID, out Guid mapped) + ? mapped + : Guid.NewGuid(); + context.MapType(oldID, newID); + LiteralExpressionSyntax replacement = SyntaxFactory + .LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newID.ToString("D"))) .WithTriviaFrom(literal); - return attribute.WithArgumentList(attribute.ArgumentList.WithArguments( - SyntaxFactory.SingletonSeparatedList(arguments[0].WithExpression(replacement)))); + return attribute.WithArgumentList( + attribute.ArgumentList.WithArguments( + SyntaxFactory.SingletonSeparatedList(arguments[0].WithExpression(replacement)) + ) + ); }); File.WriteAllText(path, rewritten.ToFullString(), new UTF8Encoding(hasBom)); } } - private static bool IsStableTypeId(string name) => name.Split('.').Last() is "StableTypeId" or "StableTypeIdAttribute"; + private static bool IsStableTypeID(string name) => name.Split('.').Last() is "StableTypeID" or "StableTypeIDAttribute"; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs index 8e51a2565..aa3bf1bb7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs @@ -6,7 +6,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -19,9 +18,9 @@ internal static ScriptCompilationEnvironment Resolve( CancellationToken cancellationToken = default ) { ScriptCompilationInputs inputs = provider.Capture(cancellationToken); - var references = new List(); + List references = []; var names = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Private.CoreLib" }; - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string identity in new[] { ScriptCompilationEnvironment.C_TARGET_FRAMEWORK, @@ -30,8 +29,8 @@ internal static ScriptCompilationEnvironment Resolve( typeof(FrameworkReferenceResolver).Module.ModuleVersionId.ToString("N"), inputs.sdkIdentity, string.Join(";", inputs.predefinedSymbols) - }) - { + } + ) { hash.AppendData(Encoding.UTF8.GetBytes(identity)); hash.AppendData([0]); } @@ -42,12 +41,16 @@ internal static ScriptCompilationEnvironment Resolve( hash.AppendData([0]); byte[] image = File.ReadAllBytes(path); hash.AppendData(SHA256.HashData(image)); - references.Add(MetadataReference.CreateFromImage( - ImmutableCollectionsMarshal.AsImmutableArray(image), filePath: path)); + references.Add( + MetadataReference.CreateFromImage(ImmutableCollectionsMarshal.AsImmutableArray(image), filePath: path) + ); names.Add(Path.GetFileNameWithoutExtension(path)); } return new ScriptCompilationEnvironment( - references.AsReadOnly(), names, Convert.ToHexStringLower(hash.GetHashAndReset()), inputs); + references.AsReadOnly(), + names, + Convert.ToHexStringLower(hash.GetHashAndReset()), + inputs + ); } - } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs index 40bcbf818..636f9ab5c 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -14,57 +14,60 @@ namespace Inno.Scripting.Compiler; /// Enforces logical scripting namespaces and rejects direct implementation namespace access. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] -[System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1041", - Justification = "This analyzer is loaded only by the .NET 10 SDK compiler shared by authoring and generated IDE projects.")] +[SuppressMessage( + "MicrosoftCodeAnalysisCorrectness", + "RS1041", + Justification = "This analyzer is loaded only by the .NET 10 SDK compiler shared by authoring and generated IDE projects." +)] public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer { /// /// Diagnostic identifier for direct implementation namespace access. /// - public const string directImplementationNamespaceDiagnosticId = "INNO2001"; + public const string C_DIRECT_IMPLEMENTATION_NAMESPACE_DIAGNOSTIC_ID = "INNO2001"; /// /// Diagnostic identifier for a missing logical namespace import. /// - public const string missingLogicalNamespaceDiagnosticId = "INNO2002"; + public const string C_MISSING_LOGICAL_NAMESPACE_DIAGNOSTIC_ID = "INNO2002"; /// /// Diagnostic identifier for a forbidden compilation-wide namespace import. /// - public const string compilationWideUsingDiagnosticId = "INNO2003"; + public const string C_COMPILATION_WIDE_USING_DIAGNOSTIC_ID = "INNO2003"; - private static readonly DiagnosticDescriptor s_directImplementationNamespace = new( - directImplementationNamespaceDiagnosticId, + private static readonly DiagnosticDescriptor DIRECT_IMPLEMENTATION_NAMESPACE = new( + C_DIRECT_IMPLEMENTATION_NAMESPACE_DIAGNOSTIC_ID, "Implementation namespace is not part of the scripting API", "Use scripting namespace '{0}' instead of implementation namespace '{1}'", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); - private static readonly DiagnosticDescriptor s_missingLogicalNamespace = new( - missingLogicalNamespaceDiagnosticId, + private static readonly DiagnosticDescriptor MISSING_LOGICAL_NAMESPACE = new( + C_MISSING_LOGICAL_NAMESPACE_DIAGNOSTIC_ID, "Scripting API namespace is not imported", "Type '{0}' requires 'using {1};'", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); - private static readonly DiagnosticDescriptor s_compilationWideUsing = new( - compilationWideUsingDiagnosticId, + private static readonly DiagnosticDescriptor COMPILATION_WIDE_USING = new( + C_COMPILATION_WIDE_USING_DIAGNOSTIC_ID, "Compilation-wide namespace imports are not supported", "Use an ordinary using directive in each source file", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); /// /// Gets the complete compiler diagnostic set enforced by this analyzer. /// public override ImmutableArray SupportedDiagnostics - => ImmutableArray.Create( - s_directImplementationNamespace, - s_missingLogicalNamespace, - s_compilationWideUsing); + => [DIRECT_IMPLEMENTATION_NAMESPACE, MISSING_LOGICAL_NAMESPACE, COMPILATION_WIDE_USING]; /// /// Initializes owned resources and establishes the instance's active lifetime. @@ -78,64 +81,75 @@ public override void Initialize(AnalysisContext context) context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(startContext => { - startContext.RegisterSyntaxNodeAction( - AnalyzeCompilationWideUsing, - SyntaxKind.UsingDirective); - ScriptApiMap map = ScriptApiMap.Read( - startContext.Options.AdditionalFiles, - startContext.CancellationToken); + startContext.RegisterSyntaxNodeAction(AnalyzeCompilationWideUsing, SyntaxKind.UsingDirective); + ScriptApiMap map = ScriptApiMap.Read(startContext.Options.AdditionalFiles, startContext.CancellationToken); if (map.namespaces.IsDefaultOrEmpty) + { return; + } startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeUsing(nodeContext, map), - SyntaxKind.UsingDirective); + SyntaxKind.UsingDirective + ); startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeTypeReference(nodeContext, map), SyntaxKind.IdentifierName, - SyntaxKind.GenericName); + SyntaxKind.GenericName + ); startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeQualifiedTypeReference(nodeContext, map), SyntaxKind.QualifiedName, - SyntaxKind.AliasQualifiedName); + SyntaxKind.AliasQualifiedName + ); }); } private static void AnalyzeCompilationWideUsing(SyntaxNodeAnalysisContext context) { - var usingDirective = (UsingDirectiveSyntax)context.Node; + UsingDirectiveSyntax usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.GlobalKeyword == default) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_compilationWideUsing, - usingDirective.GlobalKeyword.GetLocation())); + } + context.ReportDiagnostic(Diagnostic.Create(COMPILATION_WIDE_USING, usingDirective.GlobalKeyword.GetLocation())); } private static void AnalyzeUsing( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - var usingDirective = (UsingDirectiveSyntax)context.Node; + UsingDirectiveSyntax usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.Name is null) + { return; + } string namespaceName = usingDirective.Name.ToString(); ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, namespaceName); if (mapping is null) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_directImplementationNamespace, - usingDirective.Name.GetLocation(), - mapping.apiNamespace, - namespaceName)); + } + context.ReportDiagnostic( + Diagnostic.Create( + DIRECT_IMPLEMENTATION_NAMESPACE, + usingDirective.Name.GetLocation(), + mapping.apiNamespace, + namespaceName + ) + ); } private static void AnalyzeTypeReference( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - if (context.Node.AncestorsAndSelf().OfType().Any() || - context.Node.Ancestors().Any(static ancestor => - ancestor is QualifiedNameSyntax or AliasQualifiedNameSyntax)) + if (context.Node.AncestorsAndSelf().OfType().Any() + || context.Node.Ancestors().Any(static ancestor => ( + ancestor is QualifiedNameSyntax or AliasQualifiedNameSyntax + )) + ) { return; + } ISymbol? symbol = context.SemanticModel.GetSymbolInfo(context.Node, context.CancellationToken).Symbol; INamedTypeSymbol? type = symbol switch { @@ -144,68 +158,87 @@ ScriptApiMap map _ => null }; if (type is null) + { return; + } string implementationNamespace = type.ContainingNamespace?.ToDisplayString() ?? string.Empty; ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, implementationNamespace); if (mapping is null || HasLogicalUsing(context.Node, mapping.apiNamespace)) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_missingLogicalNamespace, - context.Node.GetLocation(), - type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), - mapping.apiNamespace)); + } + context.ReportDiagnostic( + Diagnostic.Create( + MISSING_LOGICAL_NAMESPACE, + context.Node.GetLocation(), + type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + mapping.apiNamespace + ) + ); } private static void AnalyzeQualifiedTypeReference( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - if (context.Node.AncestorsAndSelf().OfType().Any() || - context.Node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax) - { + if (context.Node.AncestorsAndSelf().OfType().Any() + || context.Node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax + ) { return; } if (context.SemanticModel.GetSymbolInfo(context.Node, context.CancellationToken).Symbol - is not INamedTypeSymbol type) - { + is not INamedTypeSymbol type + ) { return; } string implementationNamespace = type.ContainingNamespace?.ToDisplayString() ?? string.Empty; ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, implementationNamespace); if (mapping is null) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_directImplementationNamespace, - context.Node.GetLocation(), - mapping.apiNamespace, - implementationNamespace)); + } + context.ReportDiagnostic( + Diagnostic.Create( + DIRECT_IMPLEMENTATION_NAMESPACE, + context.Node.GetLocation(), + mapping.apiNamespace, + implementationNamespace + ) + ); } private static ScriptApiNamespaceMap? FindByImplementationNamespace( ScriptApiMap map, string namespaceName - ) - => map.namespaces - .SelectMany(mapping => mapping.implementationNamespaces.Select( - implementation => new { mapping, implementation })) - .Where(candidate => string.Equals(namespaceName, candidate.implementation, StringComparison.Ordinal) || - namespaceName.StartsWith(candidate.implementation + ".", StringComparison.Ordinal)) - .OrderByDescending(static candidate => candidate.implementation.Length) - .Select(static candidate => candidate.mapping) - .FirstOrDefault(); + ) => map.namespaces + .SelectMany(mapping => mapping.implementationNamespaces.Select( + implementation => new { mapping, implementation } + )) + .Where(candidate => ( + string.Equals(namespaceName, candidate.implementation, StringComparison.Ordinal) + || namespaceName.StartsWith(candidate.implementation + ".", StringComparison.Ordinal) + )) + .OrderByDescending(static candidate => candidate.implementation.Length) + .Select(static candidate => candidate.mapping) + .FirstOrDefault(); private static bool HasLogicalUsing( SyntaxNode node, string apiNamespace ) { - var usings = new List(); + List usings = []; if (node.SyntaxTree.GetRoot() is CompilationUnitSyntax compilationUnit) + { usings.AddRange(compilationUnit.Usings); + } foreach (BaseNamespaceDeclarationSyntax declaration in node.Ancestors().OfType()) + { usings.AddRange(declaration.Usings); - return usings.Any(usingDirective => - usingDirective.Alias is null && - usingDirective.Name is not null && - string.Equals(usingDirective.Name.ToString(), apiNamespace, StringComparison.Ordinal)); + } + return usings.Any(usingDirective => ( + usingDirective.Alias is null + && usingDirective.Name is not null + && string.Equals(usingDirective.Name.ToString(), apiNamespace, StringComparison.Ordinal) + )); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs index 0380ca252..b859aa2fa 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs @@ -8,15 +8,17 @@ namespace Inno.Scripting.Compiler; internal static class ScriptApiArtifactCache { private const long C_MAXIMUM_SIZE = 512L * 1024 * 1024; - private static readonly TimeSpan S_GRACE_PERIOD = TimeSpan.FromDays(7); + private static readonly TimeSpan GRACE_PERIOD = TimeSpan.FromDays(7); internal static int Collect( string root, IEnumerable protectedDirectories ) { if (!Directory.Exists(root)) + { return 0; - var protectedPaths = protectedDirectories + } + HashSet protectedPaths = protectedDirectories .Where(static path => !string.IsNullOrWhiteSpace(path)) .Select(static path => Path.GetFullPath(path!)) .ToHashSet(StringComparer.OrdinalIgnoreCase); @@ -27,13 +29,13 @@ internal static int Collect( .OrderBy(static entry => entry.lastWriteUtc) .ToArray(); long totalSize = entries.Sum(static entry => entry.size); - DateTime cutoff = DateTime.UtcNow - S_GRACE_PERIOD; + DateTime cutoff = DateTime.UtcNow - GRACE_PERIOD; int removed = 0; foreach (Entry entry in entries) { - if (protectedPaths.Contains(entry.path) || - entry.lastWriteUtc > cutoff && totalSize <= C_MAXIMUM_SIZE) - { + if (protectedPaths.Contains(entry.path) + || entry.lastWriteUtc > cutoff && totalSize <= C_MAXIMUM_SIZE + ) { continue; } try diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs index 362af54a2..89f66e458 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs @@ -4,61 +4,24 @@ using System.Linq; using System.Reflection; using System.Runtime.Loader; - +using Microsoft.CodeAnalysis.CSharp; using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; -internal sealed record ScriptApiAssembly( - Assembly assembly, - IReadOnlyList exports -); - -internal sealed record ScriptApiTypeExport( - Type type, - string name -); - -internal sealed record ScriptApiNamespaceMapping( - string apiNamespace, - string implementationNamespace -); - -internal sealed record ScriptApiTypeMapping( - string apiNamespace, - string apiName, - string implementationNamespace, - string implementationName, - int arity -); - -internal sealed record ScriptApiAttachableType( - string implementationName, - string kind -); - -internal sealed record ScriptApiProfile( - string name, - IReadOnlyList exports, - IReadOnlyList implementationAssemblies, - IReadOnlyList apiNamespaces, - IReadOnlyList namespaceMappings, - IReadOnlyList typeMappings, - IReadOnlyList attachableTypes -); - internal static class ScriptApiCatalog { internal static ScriptApiProfile Build(bool includeEditor) { LoadReferencedInnoAssemblies(); Assembly[] loaded = AppDomain.CurrentDomain.GetAssemblies() - .Where(static assembly => - !assembly.IsDynamic && - !string.IsNullOrWhiteSpace(assembly.Location) && - AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default) + .Where(static assembly => ( + !assembly.IsDynamic + && !string.IsNullOrWhiteSpace(assembly.Location) + && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default + )) .ToArray(); - var byName = loaded + Dictionary byName = loaded .Where(static assembly => assembly.GetName().Name is not null) .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); @@ -67,18 +30,13 @@ internal static ScriptApiProfile Build(bool includeEditor) .SelectMany(assembly => assembly .GetCustomAttributes() .Where(attribute => Includes(attribute.scope, includeEditor)) - .Select(attribute => new NamespaceMapping( - attribute.name, - attribute.implementationNamespace, - assembly))) + .Select(attribute => new NamespaceMapping(attribute.name, attribute.implementationNamespace, assembly))) .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) .ThenBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal) .ToArray(); ValidateNamespaceMappings(declaredNamespaceMappings); NamespaceMapping[] namespaceMappings = declaredNamespaceMappings - .GroupBy(static mapping => ( - mapping.apiNamespace, - mapping.implementationNamespace)) + .GroupBy(static mapping => (mapping.apiNamespace, mapping.implementationNamespace)) .Select(static group => group.First()) .ToArray(); @@ -86,22 +44,19 @@ internal static ScriptApiProfile Build(bool includeEditor) .SelectMany(declarationAssembly => declarationAssembly .GetCustomAttributes() .Where(attribute => Includes(attribute.scope, includeEditor)) - .Select(attribute => new DeclaredTypeExport( - declarationAssembly, - attribute.type, - attribute.name))) + .Select(attribute => new DeclaredTypeExport(declarationAssembly, attribute.type, attribute.name))) .OrderBy(static export => export.type.Assembly.GetName().Name, StringComparer.Ordinal) .ThenBy(static export => export.type.FullName, StringComparer.Ordinal) .ThenBy(static export => export.name, StringComparer.Ordinal) .ToArray(); ValidateExports(declaredExports, namespaceMappings); - var exports = new List(); + List exports = []; var implementationAssemblies = new HashSet(); foreach (IGrouping implementationGroup in declaredExports - .GroupBy(static export => export.type.Assembly) - .OrderBy(static group => group.Key.GetName().Name, StringComparer.Ordinal)) - { + .GroupBy(static export => export.type.Assembly) + .OrderBy(static group => group.Key.GetName().Name, StringComparer.Ordinal) + ) { ScriptApiTypeExport[] assemblyExports = implementationGroup .Select(static export => new ScriptApiTypeExport(export.type, export.name)) .Distinct() @@ -120,7 +75,8 @@ internal static ScriptApiProfile Build(bool includeEditor) ScriptApiNamespaceMapping[] publicMappings = namespaceMappings .Select(static mapping => new ScriptApiNamespaceMapping( mapping.apiNamespace, - mapping.implementationNamespace)) + mapping.implementationNamespace + )) .Distinct() .ToArray(); ScriptApiTypeMapping[] allTypeMappings = CreateTypeMappings(exports, namespaceMappings); @@ -134,8 +90,9 @@ internal static ScriptApiProfile Build(bool includeEditor) .Where(static value => value.metadata is not null) .Select(static value => new ScriptApiAttachableType( value.type.FullName - ?? throw new InvalidOperationException("An attachable scripting API type has no full name."), - value.metadata!.kind)) + ?? throw new InvalidOperationException("An attachable scripting API type has no full name."), + value.metadata!.kind + )) .Distinct() .OrderBy(static value => value.implementationName, StringComparer.Ordinal) .ToArray(); @@ -149,14 +106,14 @@ internal static ScriptApiProfile Build(bool includeEditor) apiNamespaces, publicMappings, typeMappings, - attachableTypes); + attachableTypes + ); } private static bool Includes( ScriptingApiScope scope, bool includeEditor - ) - => scope is ScriptingApiScope.Runtime or ScriptingApiScope.Authoring || includeEditor && scope == ScriptingApiScope.Editor; + ) => scope is ScriptingApiScope.Runtime or ScriptingApiScope.Authoring || includeEditor && scope == ScriptingApiScope.Editor; private static void ValidateExports( IReadOnlyList exports, @@ -167,34 +124,40 @@ IReadOnlyList mappings if (group.Select(static export => export.name).Distinct(StringComparer.Ordinal).Skip(1).Any()) { throw new InvalidOperationException( - $"Script API type '{group.Key.FullName}' cannot be exported with multiple names."); + $"Script API type '{group.Key.FullName}' cannot be exported with multiple names." + ); } } foreach (DeclaredTypeExport export in exports) { Type type = export.type; if (!type.IsPublic && !type.IsNestedPublic) + { throw new InvalidOperationException($"Script API type '{type.FullName}' must be public."); - if (!Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier(export.name)) + } + if (!SyntaxFacts.IsValidIdentifier(export.name)) { throw new InvalidOperationException( - $"Script API name '{export.name}' for type '{type.FullName}' is not a valid C# identifier."); + $"Script API name '{export.name}' for type '{type.FullName}' is not a valid C# identifier." + ); } if (type.IsGenericTypeDefinition && !string.Equals( - export.name, - GetTypeName(type), - StringComparison.Ordinal)) - { + export.name, + GetTypeName(type), + StringComparison.Ordinal + )) { throw new InvalidOperationException( - $"Generic script API type '{type.FullName}' cannot use a script-facing alias."); + $"Generic script API type '{type.FullName}' cannot use a script-facing alias." + ); } string implementationNamespace = type.Namespace ?? string.Empty; if (!mappings.Any(mapping => - string.Equals(mapping.implementationNamespace, implementationNamespace, StringComparison.Ordinal))) - { + string.Equals(mapping.implementationNamespace, implementationNamespace, StringComparison.Ordinal)) + ) { throw new InvalidOperationException( - $"Script API type '{type.FullName}' exported by " + - $"'{export.declarationAssembly.GetName().Name}' is not assigned to a declared script API namespace."); + $"Script API type '{type.FullName}' exported by " + + $"'{export.declarationAssembly.GetName().Name}' is not assigned to a declared script API namespace." + ); } } } @@ -202,41 +165,42 @@ IReadOnlyList mappings private static ScriptApiTypeMapping[] CreateTypeMappings( IReadOnlyList exports, IReadOnlyList namespaceMappings - ) - => exports - .SelectMany(assemblyExport => assemblyExport.exports.Select(typeExport => - { - NamespaceMapping mapping = namespaceMappings.Single(value => - string.Equals( - value.implementationNamespace, - typeExport.type.Namespace ?? string.Empty, - StringComparison.Ordinal)); - return new ScriptApiTypeMapping( - mapping.apiNamespace, - typeExport.name, + ) => exports + .SelectMany(assemblyExport => assemblyExport.exports.Select(typeExport => + { + NamespaceMapping mapping = namespaceMappings.Single(value => + string.Equals( + value.implementationNamespace, typeExport.type.Namespace ?? string.Empty, - GetTypeName(typeExport.type), - typeExport.type.IsGenericTypeDefinition - ? typeExport.type.GetGenericArguments().Length - : 0); - })) - .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) - .ThenBy(static mapping => mapping.apiName, StringComparer.Ordinal) - .ToArray(); + StringComparison.Ordinal + )); + return new ScriptApiTypeMapping( + mapping.apiNamespace, + typeExport.name, + typeExport.type.Namespace ?? string.Empty, + GetTypeName(typeExport.type), + typeExport.type.IsGenericTypeDefinition + ? typeExport.type.GetGenericArguments().Length + : 0 + ); + })) + .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) + .ThenBy(static mapping => mapping.apiName, StringComparer.Ordinal) + .ToArray(); private static void ValidateTypeMappings(IReadOnlyList mappings) { foreach (IGrouping<(string apiNamespace, string apiName, int arity), ScriptApiTypeMapping> group in mappings - .GroupBy(static mapping => (mapping.apiNamespace, mapping.apiName, mapping.arity))) - { - if (group.Select(static mapping => - (mapping.implementationNamespace, mapping.implementationName)) + .GroupBy(static mapping => (mapping.apiNamespace, mapping.apiName, mapping.arity)) + ) { + if (group.Select(static mapping => (mapping.implementationNamespace, mapping.implementationName)) .Distinct() .Skip(1) - .Any()) - { + .Any() + ) { throw new InvalidOperationException( - $"Script API type name '{group.Key.apiNamespace}.{group.Key.apiName}' maps to multiple runtime types."); + $"Script API type name '{group.Key.apiNamespace}.{group.Key.apiName}' maps to multiple runtime types." + ); } } } @@ -250,8 +214,8 @@ private static string GetTypeName(Type type) private static void ValidateNamespaceMappings(IReadOnlyList mappings) { foreach (IGrouping group in mappings - .GroupBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal)) - { + .GroupBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal) + ) { string[] apiNamespaces = group .Select(static mapping => mapping.apiNamespace) .Distinct(StringComparer.Ordinal) @@ -262,10 +226,12 @@ private static void ValidateNamespaceMappings(IReadOnlyList ma ", ", group.Select(static mapping => mapping.declarationAssembly.GetName().Name) .Distinct(StringComparer.Ordinal) - .OrderBy(static name => name, StringComparer.Ordinal)); + .OrderBy(static name => name, StringComparer.Ordinal) + ); throw new InvalidOperationException( - $"Implementation namespace '{group.Key}' maps to multiple script API namespaces " + - $"across declarations in: {declarations}."); + $"Implementation namespace '{group.Key}' maps to multiple script API namespaces " + + $"across declarations in: {declarations}." + ); } } } @@ -276,22 +242,27 @@ private static void AddWithDependencies( ISet selected ) { if (!selected.Add(assembly)) + { return; + } foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) { if (reference.Name is not null && byName.TryGetValue(reference.Name, out Assembly? dependency)) + { AddWithDependencies(dependency, byName, selected); + } } } private static void LoadReferencedInnoAssemblies() { Assembly[] loaded = AppDomain.CurrentDomain.GetAssemblies() - .Where(static assembly => - !assembly.IsDynamic && - AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default) + .Where(static assembly => ( + !assembly.IsDynamic + && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default + )) .ToArray(); - var byName = loaded + Dictionary byName = loaded .Where(static assembly => assembly.GetName().Name is not null) .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); @@ -303,7 +274,9 @@ private static void LoadReferencedInnoAssemblies() { string name = reference.Name ?? string.Empty; if (!name.StartsWith("Inno.", StringComparison.Ordinal) || byName.ContainsKey(name)) + { continue; + } try { Assembly dependency = Assembly.Load(reference); @@ -330,3 +303,41 @@ private sealed record DeclaredTypeExport( string name ); } + +internal sealed record ScriptApiAssembly( + Assembly assembly, + IReadOnlyList exports +); + +internal sealed record ScriptApiTypeExport( + Type type, + string name +); + +internal sealed record ScriptApiNamespaceMapping( + string apiNamespace, + string implementationNamespace +); + +internal sealed record ScriptApiTypeMapping( + string apiNamespace, + string apiName, + string implementationNamespace, + string implementationName, + int arity +); + +internal sealed record ScriptApiAttachableType( + string implementationName, + string kind +); + +internal sealed record ScriptApiProfile( + string name, + IReadOnlyList exports, + IReadOnlyList implementationAssemblies, + IReadOnlyList apiNamespaces, + IReadOnlyList namespaceMappings, + IReadOnlyList typeMappings, + IReadOnlyList attachableTypes +); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs index 9347bfc35..db8730f70 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs @@ -13,22 +13,20 @@ internal static class ScriptApiDocumentationBuilder { internal const string C_SCHEMA = "inno-script-documentation/2"; - internal sealed record Inputs( - string identity, - IReadOnlyDictionary documents - ); - internal static Inputs Capture(IReadOnlyList exports) { var documents = new Dictionary(StringComparer.Ordinal); var identity = new StringBuilder(C_SCHEMA); - foreach (Assembly assembly in exports.Select(static export => export.type.Assembly).Distinct() - .OrderBy(static assembly => assembly.GetName().Name, StringComparer.Ordinal)) - { + foreach (Assembly assembly in exports.Select(static export => export.type.Assembly) + .Distinct() + .OrderBy(static assembly => assembly.GetName().Name, StringComparer.Ordinal) + ) { string path = Path.ChangeExtension(assembly.Location, ".xml"); byte[]? bytes = File.Exists(path) ? File.ReadAllBytes(path) : null; documents.Add(path, bytes); - identity.Append('\n').Append(assembly.GetName().Name).Append(':') + identity.Append('\n') + .Append(assembly.GetName().Name) + .Append(':') .Append(bytes is null ? "missing" : Convert.ToHexStringLower(SHA256.HashData(bytes))); } return new(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity.ToString()))), documents); @@ -36,11 +34,13 @@ internal static Inputs Capture(IReadOnlyList exports) internal static void Verify(Inputs inputs) { - foreach (var input in inputs.documents) + foreach (KeyValuePair input in inputs.documents) { bool exists = File.Exists(input.Key); if (exists != (input.Value is not null) || exists && !File.ReadAllBytes(input.Key).AsSpan().SequenceEqual(input.Value)) + { throw new IOException("Script API source documentation changed during reference preparation: " + input.Key); + } } } @@ -52,16 +52,18 @@ internal static void Write( IReadOnlyList typeMappings, Inputs inputs ) { - var outputMembers = new List(); + List outputMembers = []; var emittedNames = new HashSet(StringComparer.Ordinal); (string source, string target)[] replacements = CreateIdentityReplacements(namespaceMappings, typeMappings); foreach (IGrouping group in exports.GroupBy( - static export => export.type.Assembly)) - { + static export => export.type.Assembly + )) { string documentationPath = Path.ChangeExtension(group.Key.Location, ".xml"); byte[]? bytes = inputs.documents[documentationPath]; if (bytes is null) + { continue; + } using var stream = new MemoryStream(bytes, writable: false); XDocument source = XDocument.Load(stream, LoadOptions.PreserveWhitespace); XElement[] members = source.Root? @@ -78,60 +80,78 @@ Inputs inputs RewriteDocumentationIdentities(copy, replacements); string? name = copy.Attribute("name")?.Value; if (name is not null && emittedNames.Add(name)) + { outputMembers.Add(copy); + } } } } foreach (ScriptApiTypeExport export in exports.Where(export => !string.Equals( - export.name, - GetRuntimeTypeName(export.type), - StringComparison.Ordinal))) - { - ScriptApiTypeMapping mapping = typeMappings.Single(value => + export.name, + GetRuntimeTypeName(export.type), + StringComparison.Ordinal + ))) { + ScriptApiTypeMapping mapping = typeMappings.Single(value => ( string.Equals( value.implementationNamespace, export.type.Namespace ?? string.Empty, - StringComparison.Ordinal) && - string.Equals(value.implementationName, GetRuntimeTypeName(export.type), StringComparison.Ordinal) && - string.Equals(value.apiName, export.name, StringComparison.Ordinal)); + StringComparison.Ordinal + ) + && string.Equals(value.implementationName, GetRuntimeTypeName(export.type), StringComparison.Ordinal) + && string.Equals(value.apiName, export.name, StringComparison.Ordinal) + )); string facadeTypeName = mapping.apiNamespace + "." + mapping.apiName; AddFallbackDocumentation( outputMembers, emittedNames, "T:" + facadeTypeName, - $"Provides the {mapping.apiName} values exposed by the script API."); + $"Provides the {mapping.apiName} values exposed by the script API." + ); foreach (FieldInfo field in export.type.GetFields( - BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) - { + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly + )) { AddFallbackDocumentation( outputMembers, emittedNames, "F:" + facadeTypeName + "." + field.Name, - $"Provides the {field.Name} value from {mapping.apiName}."); + $"Provides the {field.Name} value from {mapping.apiName}." + ); } } // Origin data is emitted from the same resolved exports as the logical facade. // Documentation consumers must still select members from the actual reference assembly. - var origins = exports.Select(export => + IOrderedEnumerable origins = exports.Select(export => { - string sourceId = "T:" + GetDocumentationTypeName(export.type); - string logicalId = sourceId; + string sourceID = "T:" + GetDocumentationTypeName(export.type); + string logicalID = sourceID; foreach ((string sourceName, string targetName) in replacements) - logicalId = logicalId.Replace(sourceName, targetName, StringComparison.Ordinal); - return new XElement("type", new XAttribute("id", logicalId), - new XAttribute("source", sourceId), - new XAttribute("assembly", export.type.Assembly.GetName().Name - ?? throw new InvalidOperationException("An exported type has no assembly identity."))); + { + logicalID = logicalID.Replace(sourceName, targetName, StringComparison.Ordinal); + } + return new XElement( + "type", + new XAttribute("id", logicalID), + new XAttribute("source", sourceID), + new XAttribute( + "assembly", + export.type.Assembly.GetName().Name + ?? throw new InvalidOperationException("An exported type has no assembly identity.") + ) + ); }).OrderBy(static origin => (string?)origin.Attribute("id"), StringComparer.Ordinal); var document = new XDocument( new XDeclaration("1.0", "utf-8", null), - new XElement("doc", + new XElement( + "doc", new XElement("assembly", new XElement("name", assemblyName)), new XElement("provenance", new XAttribute("format", C_SCHEMA), origins), - new XElement("members", outputMembers.OrderBy( - static member => member.Attribute("name")?.Value, - StringComparer.Ordinal)))); + new XElement( + "members", + outputMembers.OrderBy(static member => member.Attribute("name")?.Value, StringComparer.Ordinal) + ) + ) + ); string temporaryPath = outputPath + ".tmp"; document.Save(temporaryPath); File.Move(temporaryPath, outputPath, overwrite: true); @@ -143,13 +163,15 @@ string typeName ) { string? name = member.Attribute("name")?.Value; if (string.IsNullOrEmpty(name) || name.Length < 3 || name[1] != ':') + { return false; + } ReadOnlySpan declarationName = name.AsSpan(2); return name[0] == 'T' - ? declarationName.Equals(typeName, StringComparison.Ordinal) - : declarationName.Length > typeName.Length && - declarationName[typeName.Length] == '.' && - declarationName.StartsWith(typeName, StringComparison.Ordinal); + ? declarationName.Equals(typeName, StringComparison.Ordinal) + : declarationName.Length > typeName.Length + && declarationName[typeName.Length] == '.' + && declarationName.StartsWith(typeName, StringComparison.Ordinal); } private static string GetDocumentationTypeName(Type type) => (type.FullName ?? type.Name).Replace('+', '.'); @@ -167,11 +189,10 @@ private static void AddFallbackDocumentation( string summary ) { if (!emittedNames.Add(memberName)) + { return; - outputMembers.Add(new XElement( - "member", - new XAttribute("name", memberName), - new XElement("summary", summary))); + } + outputMembers.Add(new XElement("member", new XAttribute("name", memberName), new XElement("summary", summary))); } private static void RewriteDocumentationIdentities( @@ -181,10 +202,14 @@ private static void RewriteDocumentationIdentities( foreach (XAttribute attribute in member.DescendantsAndSelf().Attributes()) { if (attribute.Name.LocalName is not ("name" or "cref")) + { continue; + } string value = attribute.Value; foreach ((string source, string target) in replacements) + { value = value.Replace(source, target, StringComparison.Ordinal); + } attribute.Value = value; } } @@ -192,17 +217,23 @@ private static void RewriteDocumentationIdentities( private static (string source, string target)[] CreateIdentityReplacements( IReadOnlyDictionary namespaceMappings, IReadOnlyList typeMappings - ) { + ) => // Freeze the ordered rewrite once per document; unchanged names need no replacement. - return namespaceMappings + namespaceMappings .OrderByDescending(static pair => pair.Key.Length) .Select(static pair => (source: pair.Key, target: pair.Value)) - .Concat(typeMappings - .OrderByDescending(static mapping => mapping.apiNamespace.Length + mapping.implementationName.Length) - .Select(static mapping => ( - source: mapping.apiNamespace + "." + mapping.implementationName, - target: mapping.apiNamespace + "." + mapping.apiName))) + .Concat( + typeMappings + .OrderByDescending(static mapping => mapping.apiNamespace.Length + mapping.implementationName.Length) + .Select(static mapping => ( + source: mapping.apiNamespace + "." + mapping.implementationName, + target: mapping.apiNamespace + "." + mapping.apiName)) + ) .Where(static replacement => !string.Equals(replacement.source, replacement.target, StringComparison.Ordinal)) .ToArray(); - } + + internal sealed record Inputs( + string identity, + IReadOnlyDictionary documents + ); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs index 5fef33a11..fed727b87 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Threading; - using Microsoft.CodeAnalysis; namespace Inno.Scripting.Compiler; @@ -28,16 +27,22 @@ CancellationToken cancellationToken foreach (AdditionalText file in additionalFiles) { if (!file.Path.EndsWith(C_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase)) + { continue; + } string text = file.GetText(cancellationToken)?.ToString() ?? string.Empty; using var reader = new StringReader(text); while (reader.ReadLine() is { } line) { if (string.IsNullOrWhiteSpace(line) || line[0] == '#') + { continue; + } string[] parts = line.Split('\t'); if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]) || string.IsNullOrWhiteSpace(parts[1])) + { continue; + } if (!mappings.TryGetValue(parts[0], out HashSet? implementations)) { implementations = new HashSet(StringComparer.Ordinal); @@ -51,22 +56,9 @@ CancellationToken cancellationToken .OrderBy(static pair => pair.Key, StringComparer.Ordinal) .Select(static pair => new ScriptApiNamespaceMap( pair.Key, - pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToImmutableArray())) + pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToImmutableArray() + )) .ToImmutableArray(); return new ScriptApiMap(namespaces); } } - -internal sealed class ScriptApiNamespaceMap -{ - internal ScriptApiNamespaceMap( - string apiNamespace, - ImmutableArray implementationNamespaces - ) { - this.apiNamespace = apiNamespace; - this.implementationNamespaces = implementationNamespaces; - } - - internal string apiNamespace { get; } - internal ImmutableArray implementationNamespaces { get; } -} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs index 657fa12cd..ae5e78366 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs @@ -12,10 +12,10 @@ internal static string Build(ScriptApiProfile profile) { var source = new StringBuilder("# Script namespace\tImplementation namespace\n"); foreach (ScriptApiNamespaceMapping mapping in profile.namespaceMappings - .Distinct() - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal)) - { + .Distinct() + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + ) { source.Append(mapping.apiNamespace) .Append('\t') .Append(mapping.implementationNamespace) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs new file mode 100644 index 000000000..54e703eab --- /dev/null +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; + +namespace Inno.Scripting.Compiler; + +internal sealed class ScriptApiNamespaceMap +{ + internal ScriptApiNamespaceMap( + string apiNamespace, + ImmutableArray implementationNamespaces + ) { + this.apiNamespace = apiNamespace; + this.implementationNamespaces = implementationNamespaces; + } + + internal string apiNamespace { get; } + internal ImmutableArray implementationNamespaces { get; } +} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs index 31bcfbeca..0c371d162 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; @@ -14,18 +12,9 @@ namespace Inno.Scripting.Compiler; -internal sealed record ScriptApiReferenceSet( - IReadOnlyList runtimeReferencePaths, - IReadOnlyList ideReferencePaths, - string contractFingerprint, - string artifactFingerprint, - ScriptCompilationEnvironment environment, - string cacheDirectory -); - internal static class ScriptApiReferenceBuilder { - private static readonly SemaphoreSlim S_BUILD_GATE = new(1, 1); + private static readonly SemaphoreSlim BUILD_GATE = new(1, 1); internal static ScriptApiReferenceSet Build( ScriptCompilerOptions options, @@ -35,17 +24,31 @@ internal static ScriptApiReferenceSet Build( ScriptApiReferenceSet? baseReferences = null, CancellationToken cancellationToken = default ) { - S_BUILD_GATE.Wait(cancellationToken); + BUILD_GATE.Wait(cancellationToken); try { return BuildLocked(options, profile, environment, baseProfile, baseReferences, cancellationToken); } finally { - S_BUILD_GATE.Release(); + BUILD_GATE.Release(); } } + internal static string[] GetImplementationPaths( + ScriptApiProfile profile, + ScriptCompilationEnvironment environment + ) { + IReadOnlySet frameworkAssemblyNames = environment.frameworkAssemblyNames; + return profile.implementationAssemblies + .Where(assembly => !frameworkAssemblyNames.Contains(assembly.GetName().Name ?? string.Empty)) + .Select(static assembly => assembly.Location) + .Where(static path => !string.IsNullOrWhiteSpace(path)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(static path => path, StringComparer.Ordinal) + .ToArray(); + } + private static ScriptApiReferenceSet BuildLocked( ScriptCompilerOptions options, ScriptApiProfile profile, @@ -60,9 +63,19 @@ CancellationToken cancellationToken .ToArray(); ScriptApiDocumentationBuilder.Inputs documentationInputs = ScriptApiDocumentationBuilder.Capture(allExports); string contractFingerprint = CreateFingerprint(profile); - string fingerprint = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( - string.Join('|', contractFingerprint, environment.fingerprint, baseReferences?.artifactFingerprint ?? string.Empty, - documentationInputs.identity)))); + string fingerprint = Convert.ToHexStringLower( + SHA256.HashData( + Encoding.UTF8.GetBytes( + string.Join( + '|', + contractFingerprint, + environment.fingerprint, + baseReferences?.artifactFingerprint ?? string.Empty, + documentationInputs.identity + ) + ) + ) + ); string directory = Path.Combine(options.scriptApiDirectory, profile.name, fingerprint); Directory.CreateDirectory(directory); string[] implementationPaths = GetImplementationPaths(profile, environment); @@ -76,11 +89,19 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); string assemblyName = export.assembly.GetName().Name - ?? throw new InvalidOperationException("A script API assembly has no simple name."); + ?? throw new InvalidOperationException("A script API assembly has no simple name."); string referencePath = Path.Combine(runtimeDirectory, assemblyName + ".dll"); if (!File.Exists(referencePath)) + { EmitImplementationReferenceAssembly( - export, referencePath, implementationPaths, exportedTypes, environment, cancellationToken); + export, + referencePath, + implementationPaths, + exportedTypes, + environment, + cancellationToken + ); + } runtimeReferencePaths.Add(referencePath); } @@ -92,9 +113,11 @@ CancellationToken cancellationToken .Where(export => !baseTypes.Contains(export.type)) .OrderBy(static export => export.type.FullName, StringComparer.Ordinal) .ToArray(); - var ideReferencePaths = new List(); + List ideReferencePaths = []; if (baseReferences is not null) + { ideReferencePaths.AddRange(baseReferences.ideReferencePaths); + } if (logicalExports.Length > 0) { string logicalDirectory = Path.Combine(directory, "IDE"); @@ -111,7 +134,8 @@ CancellationToken cancellationToken profile.namespaceMappings, baseReferences?.ideReferencePaths ?? [], environment, - cancellationToken); + cancellationToken + ); } string documentationPath = Path.ChangeExtension(referencePath, ".xml"); if (!File.Exists(documentationPath)) @@ -122,21 +146,21 @@ CancellationToken cancellationToken logicalExports, profile.namespaceMappings, profile.typeMappings, - documentationInputs); + documentationInputs + ); } ideReferencePaths.Add(referencePath); } ScriptApiDocumentationBuilder.Verify(documentationInputs); - ScriptApiArtifactCache.Collect( - options.scriptApiDirectory, - new[] { directory, baseReferences?.cacheDirectory }); + ScriptApiArtifactCache.Collect(options.scriptApiDirectory, new[] { directory, baseReferences?.cacheDirectory }); return new ScriptApiReferenceSet( runtimeReferencePaths, ideReferencePaths, contractFingerprint, fingerprint, environment, - directory); + directory + ); } private static void EmitImplementationReferenceAssembly( @@ -153,20 +177,23 @@ CancellationToken cancellationToken SourceText.From(source, Encoding.UTF8), new CSharpParseOptions(LanguageVersion.CSharp14), $"<{assemblyName}.ScriptApi.g.cs>", - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in environment.frameworkReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { references[reference.Display!] = reference; + } } foreach (string implementationPath in implementationPaths) { if (string.Equals( - Path.GetFileNameWithoutExtension(implementationPath), - assemblyName, - StringComparison.OrdinalIgnoreCase)) - { + Path.GetFileNameWithoutExtension(implementationPath), + assemblyName, + StringComparison.OrdinalIgnoreCase + )) { continue; } references[implementationPath] = MetadataReference.CreateFromFile(implementationPath); @@ -183,10 +210,16 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, nullableContextOptions: NullableContextOptions.Enable, - metadataImportOptions: MetadataImportOptions.Public)); + metadataImportOptions: MetadataImportOptions.Public + ) + ); EmitReferenceAssembly( - compilation, referencePath, source, - $"Failed to build script API reference assembly '{assemblyName}'.", cancellationToken); + compilation, + referencePath, + source, + $"Failed to build script API reference assembly '{assemblyName}'.", + cancellationToken + ); } private static void EmitLogicalReferenceAssembly( @@ -204,21 +237,27 @@ CancellationToken cancellationToken .ToDictionary( static group => group.Key, static group => group.First().apiNamespace, - StringComparer.Ordinal); + StringComparer.Ordinal + ); string source = ScriptApiStubSourceBuilder.BuildLogical(exports, exportedTypes, mappings); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( SourceText.From(source, Encoding.UTF8), new CSharpParseOptions(LanguageVersion.CSharp14), $"<{assemblyName}.g.cs>", - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in environment.frameworkReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { references[reference.Display!] = reference; + } } foreach (string baseReferencePath in baseReferencePaths) + { references[baseReferencePath] = MetadataReference.CreateFromFile(baseReferencePath); + } CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, @@ -231,10 +270,16 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, nullableContextOptions: NullableContextOptions.Enable, - metadataImportOptions: MetadataImportOptions.Public)); + metadataImportOptions: MetadataImportOptions.Public + ) + ); EmitReferenceAssembly( - compilation, referencePath, source, - $"Failed to build logical script API assembly '{assemblyName}'.", cancellationToken); + compilation, + referencePath, + source, + $"Failed to build logical script API assembly '{assemblyName}'.", + cancellationToken + ); } private static void EmitReferenceAssembly( @@ -252,16 +297,19 @@ CancellationToken cancellationToken EmitResult result = compilation.Emit( peStream: stream, options: new EmitOptions(metadataOnly: true, includePrivateMembers: false), - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); if (!result.Success) { string errors = string.Join( Environment.NewLine, result.Diagnostics .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) - .Select(static diagnostic => diagnostic.ToString())); + .Select(static diagnostic => diagnostic.ToString()) + ); throw new InvalidOperationException( - failureMessage + $"{Environment.NewLine}{errors}{Environment.NewLine}{source}"); + failureMessage + $"{Environment.NewLine}{errors}{Environment.NewLine}{source}" + ); } } cancellationToken.ThrowIfCancellationRequested(); @@ -270,7 +318,9 @@ CancellationToken cancellationToken finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } @@ -289,7 +339,9 @@ string referencePath finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } @@ -306,14 +358,16 @@ ScriptApiDocumentationBuilder.Inputs documentationInputs .ToDictionary( static group => group.Key, static group => group.First().apiNamespace, - StringComparer.Ordinal); + StringComparer.Ordinal + ); ScriptApiDocumentationBuilder.Write( Path.ChangeExtension(referencePath, ".xml"), assemblyName, exports, mappings, typeMappings, - documentationInputs); + documentationInputs + ); } private static string CreateFingerprint(ScriptApiProfile profile) @@ -324,34 +378,36 @@ private static string CreateFingerprint(ScriptApiProfile profile) HashSet exportedTypes = allExports .Select(static export => export.type) .ToHashSet(); - var builder = new StringBuilder("Inno.ScriptApi.PublicContract") + StringBuilder builder = new StringBuilder("Inno.ScriptApi.PublicContract") .Append('|') .Append(profile.name); foreach (ScriptApiAssembly export in profile.exports - .OrderBy(static value => value.assembly.GetName().Name, StringComparer.Ordinal)) - { + .OrderBy(static value => value.assembly.GetName().Name, StringComparer.Ordinal) + ) { builder.Append("|implementation:") .Append(export.assembly.GetName().Name) .Append('|') .Append(ScriptApiStubSourceBuilder.BuildImplementation(export, exportedTypes)); } foreach (string apiNamespace in profile.apiNamespaces.OrderBy(static value => value, StringComparer.Ordinal)) + { builder.Append('|').Append(apiNamespace); + } foreach (ScriptApiNamespaceMapping mapping in profile.namespaceMappings - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal)) - { + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + ) { builder.Append('|') .Append(mapping.apiNamespace) .Append('>') .Append(mapping.implementationNamespace); } foreach (ScriptApiTypeMapping mapping in profile.typeMappings - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.apiName, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationName, StringComparer.Ordinal)) - { + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.apiName, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationName, StringComparer.Ordinal) + ) { builder.Append('|') .Append(mapping.apiNamespace) .Append('.') @@ -364,8 +420,8 @@ private static string CreateFingerprint(ScriptApiProfile profile) .Append(mapping.arity); } foreach (ScriptApiAttachableType attachableType in profile.attachableTypes - .OrderBy(static value => value.implementationName, StringComparer.Ordinal)) - { + .OrderBy(static value => value.implementationName, StringComparer.Ordinal) + ) { builder.Append('|') .Append(attachableType.implementationName) .Append('>') @@ -374,19 +430,13 @@ private static string CreateFingerprint(ScriptApiProfile profile) byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(builder.ToString())); return Convert.ToHexStringLower(hash); } - - internal static string[] GetImplementationPaths( - ScriptApiProfile profile, - ScriptCompilationEnvironment environment - ) { - IReadOnlySet frameworkAssemblyNames = environment.frameworkAssemblyNames; - return profile.implementationAssemblies - .Where(assembly => !frameworkAssemblyNames.Contains(assembly.GetName().Name ?? string.Empty)) - .Select(static assembly => assembly.Location) - .Where(static path => !string.IsNullOrWhiteSpace(path)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(static path => path, StringComparer.Ordinal) - .ToArray(); - } - } + +internal sealed record ScriptApiReferenceSet( + IReadOnlyList runtimeReferencePaths, + IReadOnlyList ideReferencePaths, + string contractFingerprint, + string artifactFingerprint, + ScriptCompilationEnvironment environment, + string cacheDirectory +); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs index 2cee33a0e..cfaef6fcb 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs @@ -3,20 +3,52 @@ using System.Globalization; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; - using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; internal static class ScriptApiStubSourceBuilder { - private const BindingFlags C_DECLARED_MEMBERS = - BindingFlags.Public | - BindingFlags.NonPublic | - BindingFlags.Instance | - BindingFlags.Static | - BindingFlags.DeclaredOnly; + private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.Instance + | BindingFlags.Static + | BindingFlags.DeclaredOnly; + + private static readonly HashSet KEYWORDS = new(StringComparer.Ordinal) + { + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", + "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", + "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", + "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", + "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", + "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", + "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", + "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", + "void", "volatile", "while" + }; + + private static readonly IReadOnlyDictionary TYPE_ALIASES = new Dictionary + { + [typeof(void)] = "void", + [typeof(bool)] = "bool", + [typeof(byte)] = "byte", + [typeof(sbyte)] = "sbyte", + [typeof(short)] = "short", + [typeof(ushort)] = "ushort", + [typeof(int)] = "int", + [typeof(uint)] = "uint", + [typeof(long)] = "long", + [typeof(ulong)] = "ulong", + [typeof(char)] = "char", + [typeof(float)] = "float", + [typeof(double)] = "double", + [typeof(decimal)] = "decimal", + [typeof(string)] = "string", + [typeof(object)] = "object" + }; [ThreadStatic] private static IReadOnlySet? s_exportedTypes; @@ -33,25 +65,25 @@ internal static class ScriptApiStubSourceBuilder internal static string BuildImplementation( ScriptApiAssembly export, IReadOnlySet exportedTypes - ) - => Build( - export.exports.Select(static value => value.type).ToArray(), - exportedTypes, - export.assembly.GetName().Version ?? new Version(1, 0, 0, 0), - namespaceMappings: null, - typeNames: null); + ) => Build( + export.exports.Select(static value => value.type).ToArray(), + exportedTypes, + export.assembly.GetName().Version ?? new Version(1, 0, 0, 0), + namespaceMappings: null, + typeNames: null + ); internal static string BuildLogical( IReadOnlyList exports, IReadOnlySet exportedTypes, IReadOnlyDictionary namespaceMappings - ) - => Build( - exports.Select(static value => value.type).ToArray(), - exportedTypes, - new Version(1, 0, 0, 0), - namespaceMappings, - exports.ToDictionary(static value => value.type, static value => value.name)); + ) => Build( + exports.Select(static value => value.type).ToArray(), + exportedTypes, + new Version(1, 0, 0, 0), + namespaceMappings, + exports.ToDictionary(static value => value.type, static value => value.name) + ); private static string Build( IReadOnlyList types, @@ -112,13 +144,19 @@ Type type if (type.IsClass) { if (type.IsAbstract && type.IsSealed) + { builder.Append("static "); + } else { if (type.IsAbstract) + { builder.Append("abstract "); + } if (type.IsSealed) + { builder.Append("sealed "); + } } builder.Append("class "); } @@ -128,8 +166,10 @@ Type type } else { - if (type.IsDefined(typeof(System.Runtime.CompilerServices.IsReadOnlyAttribute), inherit: false)) + if (type.IsDefined(typeof(IsReadOnlyAttribute), inherit: false)) + { builder.Append("readonly "); + } builder.Append("struct "); } AppendNamedType(builder, type); @@ -149,9 +189,11 @@ private static void AppendAttributeUsage( Type type ) { if (!typeof(Attribute).IsAssignableFrom(type)) + { return; + } AttributeUsageAttribute usage = type.GetCustomAttribute(inherit: true) - ?? new AttributeUsageAttribute(AttributeTargets.All); + ?? new AttributeUsageAttribute(AttributeTargets.All); builder.Append("[global::System.AttributeUsage((global::System.AttributeTargets)") .Append(((int)usage.ValidOn).ToString(CultureInfo.InvariantCulture)) .Append(", AllowMultiple = ") @@ -188,7 +230,7 @@ private static void AppendDelegate( Type type ) { MethodInfo invoke = type.GetMethod("Invoke") - ?? throw new InvalidOperationException($"Delegate '{type.FullName}' has no Invoke method."); + ?? throw new InvalidOperationException($"Delegate '{type.FullName}' has no Invoke method."); builder.Append("public delegate ") .Append(FormatParameterType(invoke.ReturnParameter)) .Append(' '); @@ -209,18 +251,26 @@ Type type .Where(static argument => argument.DeclaringMethod is null) .ToArray(); if (arguments.Length == 0) + { return; + } builder.Append('<'); for (int i = 0; i < arguments.Length; i++) { if (i > 0) + { builder.Append(", "); - GenericParameterAttributes variance = arguments[i].GenericParameterAttributes & - GenericParameterAttributes.VarianceMask; + } + GenericParameterAttributes variance = arguments[i].GenericParameterAttributes + & GenericParameterAttributes.VarianceMask; if (variance == GenericParameterAttributes.Covariant) + { builder.Append("out "); + } else if (variance == GenericParameterAttributes.Contravariant) + { builder.Append("in "); + } builder.Append(arguments[i].Name); } builder.Append('>'); @@ -230,26 +280,28 @@ private static void AppendBaseTypes( StringBuilder builder, Type type ) { - var baseTypes = new List(); - if (type.IsClass && - !type.IsStaticClass() && - type.BaseType is not null && - type.BaseType != typeof(object) && - IsApiType(type.BaseType)) - { + List baseTypes = []; + if (type.IsClass + && !type.IsStaticClass() + && type.BaseType is not null + && type.BaseType != typeof(object) + && IsApiType(type.BaseType) + ) { baseTypes.Add(type.BaseType); } foreach (Type interfaceType in type.GetInterfaces()) { - if ((interfaceType.IsPublic || interfaceType.IsNestedPublic) && - IsApiType(interfaceType) && - CanExposeInterface(type, interfaceType)) - { + if ((interfaceType.IsPublic || interfaceType.IsNestedPublic) + && IsApiType(interfaceType) + && CanExposeInterface(type, interfaceType) + ) { baseTypes.Add(interfaceType); } } if (baseTypes.Count == 0) + { return; + } builder.Append(" : ") .Append(string.Join(", ", baseTypes.Distinct().Select(FormatType))); } @@ -259,7 +311,9 @@ private static bool CanExposeInterface( Type interfaceType ) { if (type.IsInterface) + { return true; + } InterfaceMapping mapping = type.GetInterfaceMap(interfaceType); return mapping.TargetMethods.All(IsVisible); } @@ -271,18 +325,26 @@ IEnumerable genericParameters foreach (Type parameter in genericParameters) { GenericParameterAttributes attributes = parameter.GenericParameterAttributes; - var constraints = new List(); + List constraints = []; if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) + { constraints.Add("class"); + } bool isStruct = (attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; if (isStruct) + { constraints.Add("struct"); - constraints.AddRange(parameter - .GetGenericParameterConstraints() - .Where(constraint => constraint != typeof(ValueType)) - .Select(FormatType)); + } + constraints.AddRange( + parameter + .GetGenericParameterConstraints() + .Where(constraint => constraint != typeof(ValueType)) + .Select(FormatType) + ); if (!isStruct && (attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0) + { constraints.Add("new()"); + } if (constraints.Count > 0) { builder.Append(" where ") @@ -300,7 +362,9 @@ Type type foreach (FieldInfo field in type.GetFields(C_DECLARED_MEMBERS)) { if (!IsVisible(field) || field.IsSpecialName) + { continue; + } if (!IsApiType(field.FieldType)) { RejectUnclosedMember(field, field.FieldType); @@ -310,19 +374,34 @@ Type type .Append(GetAccessibility(field)) .Append(' '); if (field.IsLiteral) + { builder.Append("const "); + } else { if (field.IsStatic) + { builder.Append("static "); + } if (field.IsInitOnly) + { builder.Append("readonly "); + } } - builder.Append(FormatType(field.FieldType, s_nullability!.Create(field), new(field.GetCustomAttributesData(), field))) + builder + .Append( + FormatType( + field.FieldType, + s_nullability!.Create(field), + new NullableAnnotations(field.GetCustomAttributesData(), field) + ) + ) .Append(' ') .Append(EscapeIdentifier(field.Name)); if (field.IsLiteral) + { builder.Append(" = ").Append(FormatConstant(field.GetRawConstantValue(), field.FieldType)); + } builder.AppendLine(";"); } } @@ -332,11 +411,15 @@ private static void AppendConstructors( Type type ) { if (type.IsStaticClass() || type.IsInterface) + { return; + } foreach (ConstructorInfo constructor in type.GetConstructors(C_DECLARED_MEMBERS)) { if (!IsVisible(constructor) || type.IsValueType && constructor.GetParameters().Length == 0) + { continue; + } if (!AreApiParameters(constructor.GetParameters())) { RejectUnclosedMember(constructor, constructor.GetParameters().Select(static value => value.ParameterType)); @@ -362,13 +445,17 @@ Type type MethodInfo? setter = IsVisible(property.SetMethod) ? property.SetMethod : null; MethodInfo? representative = MoreVisible(getter, setter); if (representative is null) + { continue; + } if (!IsApiType(property.PropertyType) || !AreApiParameters(property.GetIndexParameters())) { RejectUnclosedMember( property, new[] { property.PropertyType }.Concat( - property.GetIndexParameters().Select(static value => value.ParameterType))); + property.GetIndexParameters().Select(static value => value.ParameterType) + ) + ); continue; } string accessibility = GetAccessibility(representative); @@ -376,7 +463,15 @@ Type type .Append(accessibility) .Append(' '); AppendMethodModifiers(builder, representative, type.IsInterface); - builder.Append(FormatType(property.PropertyType, s_nullability!.Create(property), new(property.GetCustomAttributesData(), property))).Append(' '); + builder + .Append( + FormatType( + property.PropertyType, + s_nullability!.Create(property), + new NullableAnnotations(property.GetCustomAttributesData(), property) + ) + ) + .Append(' '); ParameterInfo[] indexParameters = property.GetIndexParameters(); if (indexParameters.Length > 0) { @@ -402,16 +497,24 @@ private static void AppendAccessor( string propertyAccessibility ) { if (method is null) + { return; + } builder.Append(" "); string accessibility = GetAccessibility(method); if (!string.Equals(accessibility, propertyAccessibility, StringComparison.Ordinal)) + { builder.Append(accessibility).Append(' '); + } builder.Append(keyword); if (method.IsAbstract) + { builder.AppendLine(";"); + } else + { builder.AppendLine(" => throw new global::System.NotImplementedException();"); + } } private static void AppendEvents( @@ -422,7 +525,9 @@ Type type { MethodInfo? accessor = MoreVisible(eventInfo.AddMethod, eventInfo.RemoveMethod); if (!IsVisible(accessor)) + { continue; + } if (!IsApiType(eventInfo.EventHandlerType!)) { RejectUnclosedMember(eventInfo, eventInfo.EventHandlerType!); @@ -432,9 +537,17 @@ Type type .Append(GetAccessibility(accessor!)) .Append(' '); if (accessor!.IsStatic) + { builder.Append("static "); + } builder.Append("event ") - .Append(FormatType(eventInfo.EventHandlerType!, s_nullability!.Create(eventInfo), new(eventInfo.GetCustomAttributesData(), eventInfo))) + .Append( + FormatType( + eventInfo.EventHandlerType!, + s_nullability!.Create(eventInfo), + new NullableAnnotations(eventInfo.GetCustomAttributesData(), eventInfo) + ) + ) .Append(' ') .Append(EscapeIdentifier(eventInfo.Name)) .AppendLine(";"); @@ -447,14 +560,16 @@ Type type ) { foreach (MethodInfo method in type.GetMethods(C_DECLARED_MEMBERS)) { - if (!IsVisible(method) || - method.Name == "Finalize" && method.GetParameters().Length == 0 || - method.Name.Contains('<', StringComparison.Ordinal)) + if (!IsVisible(method) + || method.Name == "Finalize" && method.GetParameters().Length == 0 + || method.Name.Contains('<', StringComparison.Ordinal) + ) { continue; - if (method.IsSpecialName && - method.Name is not "op_Implicit" and not "op_Explicit" && - !TryGetOperator(method.Name, out _)) - { + } + if (method.IsSpecialName + && method.Name is not "op_Implicit" and not "op_Explicit" + && !TryGetOperator(method.Name, out _) + ) { continue; } if (!IsApiMethod(method)) @@ -463,16 +578,23 @@ method.Name is not "op_Implicit" and not "op_Explicit" && method, new[] { method.ReturnType } .Concat(method.GetParameters().Select(static value => value.ParameterType)) - .Concat(method.GetGenericArguments() - .SelectMany(static argument => argument.GetGenericParameterConstraints()))); + .Concat( + method.GetGenericArguments() + .SelectMany(static argument => argument.GetGenericParameterConstraints()) + ) + ); continue; } if (method.IsSpecialName) { if (method.Name is "op_Implicit" or "op_Explicit") + { AppendConversionOperator(builder, method); + } else if (TryGetOperator(method.Name, out string? symbol)) + { AppendOperator(builder, method, symbol!); + } continue; } builder.Append(" ") @@ -484,7 +606,9 @@ method.Name is not "op_Implicit" and not "op_Explicit" && .Append(EscapeIdentifier(method.Name)); Type[] genericArguments = method.GetGenericArguments(); if (genericArguments.Length > 0) + { builder.Append('<').Append(string.Join(", ", genericArguments.Select(static value => value.Name))).Append('>'); + } builder.Append('('); AppendParameters(builder, method.GetParameters()); builder.Append(')'); @@ -531,17 +655,25 @@ bool declaringTypeIsInterface return; } if (declaringTypeIsInterface) + { return; + } if (method.IsAbstract) + { builder.Append("abstract "); + } else if (method.GetBaseDefinition() != method) { if (method.IsFinal) + { builder.Append("sealed "); + } builder.Append("override "); } else if (method.IsVirtual && !method.IsFinal) + { builder.Append("virtual "); + } } private static void AppendMethodBody( @@ -549,9 +681,13 @@ private static void AppendMethodBody( MethodInfo method ) { if (method.IsAbstract) + { builder.AppendLine(";"); + } else + { builder.AppendLine(" => throw new global::System.NotImplementedException();"); + } } private static void AppendParameters( @@ -561,51 +697,71 @@ IReadOnlyList parameters for (int i = 0; i < parameters.Count; i++) { if (i > 0) + { builder.Append(", "); + } ParameterInfo parameter = parameters[i]; AppendFlowAttributes(builder, parameter.GetCustomAttributesData()); if (parameter.IsDefined(typeof(ParamArrayAttribute), inherit: false)) + { builder.Append("params "); + } Type parameterType = parameter.ParameterType; if (parameterType.IsByRef) { if (parameter.IsOut) + { builder.Append("out "); + } else if (parameter.IsIn) + { builder.Append("in "); + } else + { builder.Append("ref "); + } parameterType = parameterType.GetElementType()!; } builder.Append(FormatParameterType(parameter)) .Append(' ') .Append(EscapeIdentifier(parameter.Name ?? "value")); if (parameter.IsOptional) + { builder.Append(" = ").Append(FormatConstant(parameter.DefaultValue, parameterType)); + } } } private static bool IsVisible(MethodBase? method) - => method is not null && - (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); + => method is not null + && (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); private static bool IsVisible(FieldInfo field) => field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly; private static string GetAccessibility(MethodBase method) { if (method.IsPublic) + { return "public"; + } if (method.IsFamilyOrAssembly) + { return "protected internal"; + } return "protected"; } private static string GetAccessibility(FieldInfo field) { if (field.IsPublic) + { return "public"; + } if (field.IsFamilyOrAssembly) + { return "protected internal"; + } return "protected"; } @@ -614,9 +770,13 @@ private static string GetAccessibility(FieldInfo field) MethodInfo? second ) { if (!IsVisible(first)) + { return IsVisible(second) ? second : null; + } if (!IsVisible(second)) + { return first; + } return VisibilityRank(first!) >= VisibilityRank(second!) ? first : second; } @@ -624,36 +784,6 @@ private static string GetAccessibility(FieldInfo field) private static string FormatType(Type type) => FormatType(type, null); - private static string FormatParameterType(ParameterInfo parameter) - => FormatType(parameter.ParameterType, s_nullability!.Create(parameter), new(parameter.GetCustomAttributesData(), parameter.Member)); - - private static void AppendFlowAttributes( - StringBuilder builder, - IEnumerable attributes - ) { - foreach (CustomAttributeData attribute in attributes) - { - if (attribute.AttributeType.Namespace == "System.Runtime.CompilerServices" - && attribute.AttributeType.Name is "CallerFilePathAttribute" or "CallerLineNumberAttribute" - or "CallerMemberNameAttribute" or "CallerArgumentExpressionAttribute") - { - builder.Append("[global::").Append(attribute.AttributeType.FullName).Append('(') - .Append(string.Join(", ", attribute.ConstructorArguments.Select(static argument => - FormatConstant(argument.Value, argument.ArgumentType)))) - .Append(")] "); - continue; - } - if (attribute.AttributeType.Namespace != "System.Diagnostics.CodeAnalysis" - || attribute.AttributeType.Name is not ("AllowNullAttribute" or "DisallowNullAttribute" - or "MaybeNullAttribute" or "NotNullAttribute" or "NotNullWhenAttribute" - or "MaybeNullWhenAttribute" or "NotNullIfNotNullAttribute" or "DoesNotReturnIfAttribute")) - continue; - builder.Append("[global::").Append(attribute.AttributeType.FullName).Append('(') - .Append(string.Join(", ", attribute.ConstructorArguments.Select(static argument => FormatConstant(argument.Value, argument.ArgumentType)))) - .Append(")] "); - } - } - private static string FormatType( Type type, NullabilityInfo? nullability, @@ -670,58 +800,85 @@ private static string FormatType( bool nullable = type.IsGenericParameter ? flag == 2 : nullability?.ReadState == NullabilityState.Nullable; string annotation = !type.IsValueType && nullable ? "?" : string.Empty; if (type.IsArray) - return FormatType(type.GetElementType()!, nullability?.ElementType, annotations) + "[" + new string(',', type.GetArrayRank() - 1) + "]" + annotation; + { + return FormatType(type.GetElementType()!, nullability?.ElementType, annotations) + + "[" + + new string(',', type.GetArrayRank() - 1) + + "]" + + annotation; + } if (type.IsGenericParameter) + { return type.Name + annotation; - if (C_TYPE_ALIASES.TryGetValue(type, out string? alias)) + } + if (TYPE_ALIASES.TryGetValue(type, out string? alias)) + { return alias + annotation; + } if (!type.IsGenericType) + { return "global::" + FormatNamedTypeName(type, removeGenericArities: false) + annotation; + } Type definition = type.GetGenericTypeDefinition(); string name = FormatNamedTypeName(definition, removeGenericArities: true); - return "global::" + name + "<" + - string.Join(", ", type.GetGenericArguments().Select(( - argument, - index - ) => - FormatType(argument, nullability?.GenericTypeArguments.ElementAtOrDefault(index), annotations))) + ">" + annotation; + return "global::" + name + "<" + + string.Join( + ", ", + type.GetGenericArguments().Select(( + argument, + index + ) => + FormatType(argument, nullability?.GenericTypeArguments.ElementAtOrDefault(index), annotations)) + ) + ">" + annotation; } - private sealed class NullableAnnotations - { - private readonly byte[] m_flags; - private readonly byte m_context; - private int m_index; - - internal NullableAnnotations( - IEnumerable attributes, - MemberInfo owner - ) { - CustomAttributeData? transform = attributes.FirstOrDefault(static attribute => - attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute"); - m_flags = transform?.ConstructorArguments[0].Value switch - { - byte flag => [flag], - IEnumerable flags => flags.Select(static value => (byte)value.Value!).ToArray(), - _ => [] - }; - for (MemberInfo? current = owner; current is not null; current = current.DeclaringType) - { - CustomAttributeData? context = current.GetCustomAttributesData().FirstOrDefault(static attribute => - attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); - if (context is null) - continue; - m_context = (byte)context.ConstructorArguments[0].Value!; - break; - } - } + private static string FormatParameterType(ParameterInfo parameter) + => FormatType( + parameter.ParameterType, + s_nullability!.Create(parameter), + new NullableAnnotations(parameter.GetCustomAttributesData(), parameter.Member) + ); - internal byte Next(Type type) + private static void AppendFlowAttributes( + StringBuilder builder, + IEnumerable attributes + ) { + foreach (CustomAttributeData attribute in attributes) { - if (type.IsValueType && !type.IsGenericType) - return 0; - int index = m_index++; - return index < m_flags.Length ? m_flags[index] : m_context; + if (attribute.AttributeType.Namespace == "System.Runtime.CompilerServices" + && attribute.AttributeType.Name is "CallerFilePathAttribute" or "CallerLineNumberAttribute" + or "CallerMemberNameAttribute" or "CallerArgumentExpressionAttribute" + ) { + builder.Append("[global::") + .Append(attribute.AttributeType.FullName) + .Append('(') + .Append( + string.Join( + ", ", + attribute.ConstructorArguments.Select(static argument => + FormatConstant(argument.Value, argument.ArgumentType)) + ) + ) + .Append(")] "); + continue; + } + if (attribute.AttributeType.Namespace != "System.Diagnostics.CodeAnalysis" + || attribute.AttributeType.Name is not ("AllowNullAttribute" or "DisallowNullAttribute" + or "MaybeNullAttribute" or "NotNullAttribute" or "NotNullWhenAttribute" + or "MaybeNullWhenAttribute" or "NotNullIfNotNullAttribute" or "DoesNotReturnIfAttribute") + ) { + continue; + } + builder.Append("[global::") + .Append(attribute.AttributeType.FullName) + .Append('(') + .Append( + string.Join( + ", ", + attribute.ConstructorArguments.Select(static argument => FormatConstant(argument.Value, argument.ArgumentType)) + ) + ) + .Append(")] "); } } @@ -734,37 +891,41 @@ bool removeGenericArities { string aliasNamespace = ResolveNamespace(implementationNamespace); return string.IsNullOrEmpty(aliasNamespace) - ? typeName - : aliasNamespace + "." + typeName; + ? typeName + : aliasNamespace + "." + typeName; } string fullName = type.FullName ?? type.Name; string relativeName = string.IsNullOrEmpty(implementationNamespace) - ? fullName - : fullName[(implementationNamespace.Length + 1)..]; + ? fullName + : fullName[(implementationNamespace.Length + 1)..]; if (removeGenericArities) + { relativeName = RemoveGenericArities(relativeName); + } relativeName = relativeName.Replace('+', '.'); string targetNamespace = ResolveNamespace(implementationNamespace); return string.IsNullOrEmpty(targetNamespace) - ? relativeName - : targetNamespace + "." + relativeName; + ? relativeName + : targetNamespace + "." + relativeName; } private static string ResolveNamespace(string implementationNamespace) - => s_namespaceMappings is not null && - s_namespaceMappings.TryGetValue(implementationNamespace, out string? apiNamespace) - ? apiNamespace - : implementationNamespace; + => s_namespaceMappings is not null + && s_namespaceMappings.TryGetValue(implementationNamespace, out string? apiNamespace) + ? apiNamespace + : implementationNamespace; private static string GetTypeName(Type type) => s_typeNames is not null && s_typeNames.TryGetValue(type, out string? name) - ? name - : RemoveArity(type.Name); + ? name + : RemoveArity(type.Name); private static bool IsApiMethod(MethodInfo method) { if (!IsApiType(method.ReturnType) || !AreApiParameters(method.GetParameters())) + { return false; + } return method.GetGenericArguments() .SelectMany(static argument => argument.GetGenericParameterConstraints()) .All(IsApiType); @@ -776,15 +937,21 @@ private static bool AreApiParameters(IEnumerable parameters) private static bool IsApiType(Type type) { if (type.IsByRef || type.IsPointer || type.IsArray) + { return IsApiType(type.GetElementType()!); + } if (type.IsGenericParameter) + { return type.GetGenericParameterConstraints().All(IsApiType); - if (C_TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + } + if (TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + { return true; + } if (type.IsGenericType) { - return IsApiNamedType(type.GetGenericTypeDefinition()) && - type.GetGenericArguments().All(IsApiType); + return IsApiNamedType(type.GetGenericTypeDefinition()) + && type.GetGenericArguments().All(IsApiType); } return IsApiNamedType(type); } @@ -799,18 +966,22 @@ private static void RejectUnclosedMember( IEnumerable dependencies ) { if (member.IsDefined(typeof(ScriptingApiIgnoreAttribute), inherit: false)) + { return; + } string missing = string.Join( ", ", dependencies .SelectMany(GetUnexportedTypes) .Select(static type => type.FullName ?? type.Name) .Distinct(StringComparer.Ordinal) - .OrderBy(static name => name, StringComparer.Ordinal)); + .OrderBy(static name => name, StringComparer.Ordinal) + ); throw new InvalidOperationException( - $"Scripting API member '{member.DeclaringType?.FullName}.{member.Name}' depends on " + - $"unexported type(s): {missing}. Export the dependency or mark the member with " + - $"{nameof(ScriptingApiIgnoreAttribute)}."); + $"Scripting API member '{member.DeclaringType?.FullName}.{member.Name}' depends on " + + $"unexported type(s): {missing}. Export the dependency or mark the member with " + + $"{nameof(ScriptingApiIgnoreAttribute)}." + ); } private static IEnumerable GetUnexportedTypes(Type type) @@ -818,39 +989,55 @@ private static IEnumerable GetUnexportedTypes(Type type) if (type.IsByRef || type.IsPointer || type.IsArray) { foreach (Type missing in GetUnexportedTypes(type.GetElementType()!)) + { yield return missing; + } yield break; } if (type.IsGenericParameter) { foreach (Type constraint in type.GetGenericParameterConstraints()) + { foreach (Type missing in GetUnexportedTypes(constraint)) + { yield return missing; + } + } yield break; } - if (C_TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + if (TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + { yield break; + } if (type.IsGenericType) { if (!IsApiNamedType(type.GetGenericTypeDefinition())) + { yield return type.GetGenericTypeDefinition(); + } foreach (Type argument in type.GetGenericArguments()) + { foreach (Type missing in GetUnexportedTypes(argument)) + { yield return missing; + } + } yield break; } if (!IsApiNamedType(type)) + { yield return type; + } } private static bool IsApiNamedType(Type type) { Assembly assembly = type.Assembly; string name = assembly.GetName().Name ?? string.Empty; - if (assembly == typeof(object).Assembly || - name.StartsWith("System.", StringComparison.Ordinal) || - name.StartsWith("Microsoft.", StringComparison.Ordinal)) - { + if (assembly == typeof(object).Assembly + || name.StartsWith("System.", StringComparison.Ordinal) + || name.StartsWith("Microsoft.", StringComparison.Ordinal) + ) { return true; } return s_exportedTypes?.Contains(type) == true; @@ -861,13 +1048,12 @@ private static string FormatConstant( Type type ) { if (value is null || value == DBNull.Value || value == Missing.Value) + { return "default"; + } if (type.IsEnum) { - object numeric = Convert.ChangeType( - value, - Enum.GetUnderlyingType(type), - CultureInfo.InvariantCulture); + object numeric = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture); return "(" + FormatType(type) + ")" + FormatNumericConstant(numeric); } return value switch @@ -918,7 +1104,7 @@ out string? symbol return symbol is not null; } - private static string EscapeIdentifier(string value) => C_KEYWORDS.Contains(value) ? "@" + value : value; + private static string EscapeIdentifier(string value) => KEYWORDS.Contains(value) ? "@" + value : value; private static string RemoveArity(string value) { @@ -937,44 +1123,56 @@ private static string RemoveGenericArities(string value) continue; } while (i + 1 < value.Length && char.IsDigit(value[i + 1])) + { i++; + } } return builder.ToString(); } private static bool IsStaticClass(this Type type) => type.IsAbstract && type.IsSealed; - private static readonly HashSet C_KEYWORDS = new(StringComparer.Ordinal) + private sealed class NullableAnnotations { - "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", - "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", - "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", - "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", - "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", - "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", - "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", - "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", - "void", "volatile", "while" - }; + private readonly byte[] m_flags; + private readonly byte m_context; + private int m_index; - private static readonly IReadOnlyDictionary C_TYPE_ALIASES = - new Dictionary - { - [typeof(void)] = "void", - [typeof(bool)] = "bool", - [typeof(byte)] = "byte", - [typeof(sbyte)] = "sbyte", - [typeof(short)] = "short", - [typeof(ushort)] = "ushort", - [typeof(int)] = "int", - [typeof(uint)] = "uint", - [typeof(long)] = "long", - [typeof(ulong)] = "ulong", - [typeof(char)] = "char", - [typeof(float)] = "float", - [typeof(double)] = "double", - [typeof(decimal)] = "decimal", - [typeof(string)] = "string", - [typeof(object)] = "object" - }; + internal NullableAnnotations( + IEnumerable attributes, + MemberInfo owner + ) { + CustomAttributeData? transform = attributes.FirstOrDefault(static attribute => ( + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute" + )); + m_flags = transform?.ConstructorArguments[0].Value switch + { + byte flag => [flag], + IEnumerable flags => flags.Select(static value => (byte)value.Value!).ToArray(), + _ => [] + }; + for (MemberInfo? current = owner; current is not null; current = current.DeclaringType) + { + CustomAttributeData? context = current.GetCustomAttributesData().FirstOrDefault(static attribute => ( + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute" + )); + if (context is null) + { + continue; + } + m_context = (byte)context.ConstructorArguments[0].Value!; + break; + } + } + + internal byte Next(Type type) + { + if (type.IsValueType && !type.IsGenericType) + { + return 0; + } + int index = m_index++; + return index < m_flags.Length ? m_flags[index] : m_context; + } + } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs index 6df053951..da8b843e8 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -13,8 +12,8 @@ internal sealed class ScriptApiUsingRewriter : CSharpSyntaxRewriter private readonly IReadOnlyDictionary m_mappings; private readonly IReadOnlyDictionary m_typeMappings; private readonly IReadOnlyDictionary m_qualifiedTypeMappings; - private IReadOnlyDictionary m_activeSimpleTypeMappings = - new Dictionary(StringComparer.Ordinal); + + private IReadOnlyDictionary m_activeSimpleTypeMappings = new Dictionary(StringComparer.Ordinal); internal ScriptApiUsingRewriter( IReadOnlyList mappings, @@ -29,7 +28,8 @@ IReadOnlyList typeMappings .Distinct(StringComparer.Ordinal) .OrderBy(static value => value, StringComparer.Ordinal) .ToArray(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); m_typeMappings = typeMappings .Where(static mapping => mapping.arity == 0) .GroupBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) @@ -40,22 +40,23 @@ IReadOnlyList typeMappings static mapping => ( mapping.apiName, mapping.implementationNamespace, - mapping.implementationName)) + mapping.implementationName) + ) .Select(static mappings => mappings.First()) .OrderBy(static mapping => mapping.apiName, StringComparer.Ordinal) .ToArray(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); m_qualifiedTypeMappings = typeMappings - .GroupBy( - static mapping => mapping.apiNamespace + "." + mapping.apiName, - StringComparer.Ordinal) + .GroupBy(static mapping => mapping.apiNamespace + "." + mapping.apiName, StringComparer.Ordinal) .ToDictionary( static group => group.Key, static group => group .Select(static mapping => mapping.implementationNamespace + "." + mapping.implementationName) .Distinct(StringComparer.Ordinal) .Single(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); } /// @@ -68,9 +69,7 @@ IReadOnlyList typeMappings /// The rewritten compilation unit, or when the base visitor removes it. /// public override SyntaxNode? VisitCompilationUnit(CompilationUnitSyntax node) - => VisitWithUsings( - node.Usings, - () => base.VisitCompilationUnit(node.WithUsings(RewriteUsings(node.Usings)))); + => VisitWithUsings(node.Usings, () => base.VisitCompilationUnit(node.WithUsings(RewriteUsings(node.Usings)))); /// /// Rewrites logical API imports and type expressions declared inside a file-scoped namespace. @@ -84,7 +83,8 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitWithUsings( node.Usings, - () => base.VisitFileScopedNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings)))); + () => base.VisitFileScopedNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings))) + ); /// /// Rewrites logical API imports and type expressions declared inside a block-scoped namespace. @@ -98,7 +98,8 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitWithUsings( node.Usings, - () => base.VisitNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings)))); + () => base.VisitNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings))) + ); /// /// Replaces a fully qualified logical API type with its implementation type identity. @@ -112,7 +113,9 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitQualifiedName(QualifiedNameSyntax node) { if (m_qualifiedTypeMappings.TryGetValue(node.ToString(), out string? implementationName)) + { return SyntaxFactory.ParseName(implementationName).WithTriviaFrom(node); + } return base.VisitQualifiedName(node); } @@ -127,16 +130,20 @@ IReadOnlyList typeMappings /// public override SyntaxNode? VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { - if (node.Expression is IdentifierNameSyntax identifier && - m_activeSimpleTypeMappings.TryGetValue(identifier.Identifier.ValueText, out string? simpleType)) - { - return base.VisitMemberAccessExpression(node.WithExpression( - SyntaxFactory.ParseExpression("global::" + simpleType).WithTriviaFrom(node.Expression))); + if (node.Expression is IdentifierNameSyntax identifier + && m_activeSimpleTypeMappings.TryGetValue(identifier.Identifier.ValueText, out string? simpleType) + ) { + return base.VisitMemberAccessExpression( + node.WithExpression( + SyntaxFactory.ParseExpression("global::" + simpleType).WithTriviaFrom(node.Expression) + ) + ); } if (m_qualifiedTypeMappings.TryGetValue(node.Expression.ToString(), out string? implementationName)) { - return base.VisitMemberAccessExpression(node.WithExpression( - SyntaxFactory.ParseExpression(implementationName).WithTriviaFrom(node.Expression))); + return base.VisitMemberAccessExpression( + node.WithExpression(SyntaxFactory.ParseExpression(implementationName).WithTriviaFrom(node.Expression)) + ); } return base.VisitMemberAccessExpression(node); } @@ -161,24 +168,24 @@ private IReadOnlyDictionary CreateSimpleTypeMappings( SyntaxList usings, IReadOnlyDictionary inherited ) { - var candidates = inherited + Dictionary candidates = inherited .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal); var ambiguous = new HashSet(StringComparer.Ordinal); foreach (UsingDirectiveSyntax usingDirective in usings) { - if (usingDirective.Alias is not null || - usingDirective.StaticKeyword != default || - usingDirective.Name is null || - !m_typeMappings.TryGetValue(usingDirective.Name.ToString(), out ScriptApiTypeMapping[]? mappings)) - { + if (usingDirective.Alias is not null + || usingDirective.StaticKeyword != default + || usingDirective.Name is null + || !m_typeMappings.TryGetValue(usingDirective.Name.ToString(), out ScriptApiTypeMapping[]? mappings) + ) { continue; } foreach (ScriptApiTypeMapping mapping in mappings) { string implementation = mapping.implementationNamespace + "." + mapping.implementationName; - if (candidates.TryGetValue(mapping.apiName, out string? existing) && - !string.Equals(existing, implementation, StringComparison.Ordinal)) - { + if (candidates.TryGetValue(mapping.apiName, out string? existing) + && !string.Equals(existing, implementation, StringComparison.Ordinal) + ) { ambiguous.Add(mapping.apiName); continue; } @@ -186,7 +193,9 @@ usingDirective.Name is null || } } foreach (string name in ambiguous) + { candidates.Remove(name); + } return candidates; } @@ -195,12 +204,12 @@ private SyntaxList RewriteUsings(SyntaxList(usings.Count); foreach (UsingDirectiveSyntax usingDirective in usings) { - if (usingDirective.Alias is not null || - usingDirective.StaticKeyword != default || - usingDirective.Name is null || - !m_mappings.TryGetValue(usingDirective.Name.ToString(), out string[]? implementations) || - implementations.Length == 0) - { + if (usingDirective.Alias is not null + || usingDirective.StaticKeyword != default + || usingDirective.Name is null + || !m_mappings.TryGetValue(usingDirective.Name.ToString(), out string[]? implementations) + || implementations.Length == 0 + ) { result.Add(usingDirective); continue; } @@ -209,18 +218,26 @@ usingDirective.Name is null || { foreach (ScriptApiTypeMapping alias in aliases) { - result.Add(SyntaxFactory.UsingDirective( - SyntaxFactory.ParseName( - "global::" + alias.implementationNamespace + "." + alias.implementationName)) - .WithAlias(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(alias.apiName)))); + result.Add( + SyntaxFactory + .UsingDirective( + SyntaxFactory.ParseName( + "global::" + alias.implementationNamespace + "." + alias.implementationName + ) + ) + .WithAlias(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(alias.apiName))) + ); } } for (int i = 0; i < implementations.Length; i++) { UsingDirectiveSyntax rewritten = usingDirective.WithName( - SyntaxFactory.ParseName(implementations[i]).WithTriviaFrom(usingDirective.Name)); + SyntaxFactory.ParseName(implementations[i]).WithTriviaFrom(usingDirective.Name) + ); if (i > 0) + { rewritten = rewritten.WithLeadingTrivia(default(SyntaxTriviaList)); + } result.Add(rewritten); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs index 72b71c6f5..71c549f75 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs @@ -9,7 +9,7 @@ internal sealed class ScriptArtifactCache { private const int C_BUILD_KEY_LENGTH = 64; private const long C_DEFAULT_MAXIMUM_SIZE = 4L * 1024 * 1024 * 1024; - private static readonly TimeSpan S_DEFAULT_GRACE_PERIOD = TimeSpan.FromDays(7); + private static readonly TimeSpan DEFAULT_GRACE_PERIOD = TimeSpan.FromDays(7); private readonly string m_root; @@ -21,20 +21,24 @@ internal ScriptArtifactCache(string root) internal int Collect(IEnumerable protectedDirectories) { - var protectedPaths = protectedDirectories + HashSet protectedPaths = protectedDirectories .Where(static value => !string.IsNullOrWhiteSpace(value)) .Select(static value => Path.GetFullPath(value!)) .ToHashSet(StringComparer.OrdinalIgnoreCase); - DateTime cutoff = DateTime.UtcNow - S_DEFAULT_GRACE_PERIOD; + DateTime cutoff = DateTime.UtcNow - DEFAULT_GRACE_PERIOD; string assemblyRoot = Path.Combine(m_root, ".assemblies"); IEnumerable candidates = Directory.EnumerateDirectories(m_root); if (Directory.Exists(assemblyRoot)) + { candidates = candidates.Concat(Directory.EnumerateDirectories(assemblyRoot)); - var discoveredEntries = new List(); + } + List discoveredEntries = []; foreach (string path in candidates.Where(IsArtifactDirectory)) { if (TryCreateEntry(path, out Entry entry)) + { discoveredEntries.Add(entry); + } } Entry[] entries = discoveredEntries .OrderBy(static entry => entry.lastWriteUtc) @@ -44,9 +48,13 @@ internal int Collect(IEnumerable protectedDirectories) foreach (Entry entry in entries) { if (protectedPaths.Contains(entry.path)) + { continue; + } if (entry.lastWriteUtc > cutoff && totalSize <= C_DEFAULT_MAXIMUM_SIZE) + { continue; + } try { Directory.Delete(entry.path, recursive: true); @@ -72,7 +80,9 @@ private static int CollectStaleStaging( DateTime cutoff ) { if (!Directory.Exists(root)) + { return 0; + } int removed = 0; foreach (string path in Directory.EnumerateDirectories(root)) @@ -80,7 +90,9 @@ DateTime cutoff try { if (Directory.GetLastWriteTimeUtc(path) > cutoff) + { continue; + } Directory.Delete(path, recursive: true); removed++; } @@ -99,8 +111,8 @@ DateTime cutoff private static bool IsArtifactDirectory(string path) { string name = Path.GetFileName(path); - return name.Length == C_BUILD_KEY_LENGTH && - name.All(static character => char.IsAsciiHexDigit(character)); + return name.Length == C_BUILD_KEY_LENGTH + && name.All(static character => char.IsAsciiHexDigit(character)); } private static bool TryCreateEntry( @@ -112,10 +124,7 @@ out Entry entry long size = new DirectoryInfo(path) .EnumerateFiles("*", SearchOption.AllDirectories) .Sum(static file => file.Length); - entry = new Entry( - Path.GetFullPath(path), - Directory.GetLastWriteTimeUtc(path), - size); + entry = new Entry(Path.GetFullPath(path), Directory.GetLastWriteTimeUtc(path), size); return true; } catch (IOException) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs index c13fe2e59..6b6cff33d 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Scripting.Api; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; @@ -27,25 +27,6 @@ internal sealed class ScriptAuthoringAnnotationRewriter( HashSet annotationNamespaces ) : CSharpSyntaxRewriter { - internal static SyntaxTree[] Erase( - CSharpCompilation compilation, - ScriptApiProfile api, - CancellationToken cancellationToken - ) { - Type[] types = api.exports.SelectMany(export => export.assembly - .GetCustomAttributes(typeof(ScriptingApiExportAttribute), false) - .Cast()) - .Where(export => export.scope == ScriptingApiScope.Authoring) - .Select(export => export.type).Distinct().ToArray(); - var names = types.Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); - var namespaces = types.Select(type => type.Namespace!).ToHashSet(StringComparer.Ordinal); - return compilation.SyntaxTrees.Select(tree => - { - var rewriter = new ScriptAuthoringAnnotationRewriter(compilation.GetSemanticModel(tree), names, namespaces); - return tree.WithRootAndOptions(rewriter.Visit(tree.GetRoot(cancellationToken))!, tree.Options); - }).ToArray(); - } - /// /// Visits attribute list in deterministic order using the supplied visitor. /// @@ -88,14 +69,41 @@ CancellationToken cancellationToken ISymbol? symbol = node.Name is null ? null : semanticModel.GetSymbolInfo(node.Name).Symbol; return symbol is INamedTypeSymbol type && IsAnnotation(type) || symbol is INamespaceSymbol ns && annotationNamespaces.Contains(ns.ToDisplayString()) - ? null : base.VisitUsingDirective(node); + ? null + : base.VisitUsingDirective(node); + } + + internal static SyntaxTree[] Erase( + CSharpCompilation compilation, + ScriptApiProfile api, + CancellationToken cancellationToken + ) { + Type[] types = api.exports + .SelectMany(export => export.assembly + .GetCustomAttributes(typeof(ScriptingApiExportAttribute), false) + .Cast()) + .Where(export => export.scope == ScriptingApiScope.Authoring) + .Select(export => export.type) + .Distinct() + .ToArray(); + HashSet names = types.Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); + HashSet namespaces = types.Select(type => type.Namespace!).ToHashSet(StringComparer.Ordinal); + return compilation.SyntaxTrees.Select(tree => + { + var rewriter = new ScriptAuthoringAnnotationRewriter(compilation.GetSemanticModel(tree), names, namespaces); + return tree.WithRootAndOptions(rewriter.Visit(tree.GetRoot(cancellationToken))!, tree.Options); + }).ToArray(); } private bool IsAnnotation(INamedTypeSymbol? type) { for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { if (annotationTypes.Contains(current.ToDisplayString())) + { return true; + } + } return false; } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs index 071093458..b7004c3ef 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -25,14 +24,17 @@ internal ScriptCompilationResult( this.diagnostics = diagnostics; this.outputDirectory = outputDirectory; this.moduleDeployments = Array.AsReadOnly((moduleDeployments ?? []).ToArray()); - runtimeAssemblyPaths = this.moduleDeployments + this.runtimeAssemblyPaths = this.moduleDeployments .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths) - .Where(path => request.assemblyScopes.TryGetValue( + .Where(path => ( + request.assemblyScopes.TryGetValue( Path.GetFileNameWithoutExtension(path), - out AssemblyScope scope) + out AssemblyScope scope + ) ? scope == AssemblyScope.Runtime - : request.scope == AssemblyScope.Runtime)) + : request.scope == AssemblyScope.Runtime + ))) .Distinct(StringComparer.OrdinalIgnoreCase) .Order(StringComparer.OrdinalIgnoreCase) .ToArray(); @@ -97,7 +99,8 @@ public static ScriptCompilationResult Failure(ScriptDiagnostic diagnostic) success: false, [diagnostic], outputDirectory: null, - moduleDeployments: null); + moduleDeployments: null + ); } internal IReadOnlyList compiledAssemblies { get; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs index a1ddbd1d0..a42f90165 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs @@ -27,9 +27,13 @@ public ScriptCompilationStageTiming( TimeSpan elapsed ) { if (string.IsNullOrWhiteSpace(stage)) + { throw new ArgumentException("A compilation stage name is required.", nameof(stage)); + } if (elapsed < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(elapsed), "Stage duration cannot be negative."); + } this.stage = stage; this.elapsed = elapsed; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs index dcea597a1..1324a315c 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs @@ -1,15 +1,15 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.IO; using System.Text; +using Inno.Core.Diagnostics; namespace Inno.Scripting.Compiler; internal static class ScriptCompilerCacheSerialization { - private const int C_DIAGNOSTIC_MAGIC = 0x494E4447; - private const int C_TYPE_MANIFEST_MAGIC = 0x494E544D; + private const int C_DIAGNOSTIC_MAGIC = 0x494E_4447; + private const int C_TYPE_MANIFEST_MAGIC = 0x494E_544D; private const int C_MAX_ENTRY_COUNT = 1_000_000; internal static byte[] EncodeDiagnostics(IEnumerable diagnostics) @@ -17,8 +17,8 @@ internal static byte[] EncodeDiagnostics(IEnumerable diagnosti ArgumentNullException.ThrowIfNull(diagnostics); ScriptDiagnostic[] entries = diagnostics as ScriptDiagnostic[] ?? [.. diagnostics]; - using MemoryStream stream = new(); - using BinaryWriter writer = new(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(C_DIAGNOSTIC_MAGIC); writer.Write(entries.Length); foreach (ScriptDiagnostic diagnostic in entries) @@ -42,11 +42,11 @@ internal static byte[] EncodeDiagnostics(IEnumerable diagnosti internal static ScriptDiagnostic[] DecodeDiagnostics(ReadOnlySpan bytes) { - using MemoryStream stream = new(bytes.ToArray(), writable: false); - using BinaryReader reader = new(stream, Encoding.UTF8, leaveOpen: false); + using var stream = new MemoryStream(bytes.ToArray(), writable: false); + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); ValidateMagic(reader, C_DIAGNOSTIC_MAGIC, "script diagnostic cache"); int count = ReadCount(reader, "diagnostic"); - ScriptDiagnostic[] diagnostics = new ScriptDiagnostic[count]; + var diagnostics = new ScriptDiagnostic[count]; for (int index = 0; index < count; index++) { string id = reader.ReadString(); @@ -65,8 +65,8 @@ internal static ScriptDiagnostic[] DecodeDiagnostics(ReadOnlySpan bytes) internal static byte[] EncodeTypeManifest(ScriptTypeManifest manifest) { ArgumentNullException.ThrowIfNull(manifest); - using MemoryStream stream = new(); - using BinaryWriter writer = new(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(C_TYPE_MANIFEST_MAGIC); writer.Write(manifest.assemblyName); writer.Write(manifest.types.Count); @@ -74,8 +74,8 @@ internal static byte[] EncodeTypeManifest(ScriptTypeManifest manifest) { writer.Write(type.typeName); writer.Write(type.kind); - writer.Write(type.stableTypeId.ToByteArray()); - writer.Write(type.sourcePersistentId.ToByteArray()); + writer.Write(type.stableTypeID.ToByteArray()); + writer.Write(type.sourcePersistentID.ToByteArray()); writer.Write(type.sourcePath); writer.Write(type.line); writer.Write(type.column); @@ -89,12 +89,12 @@ internal static byte[] EncodeTypeManifest(ScriptTypeManifest manifest) internal static ScriptTypeManifest DecodeTypeManifest(ReadOnlySpan bytes) { - using MemoryStream stream = new(bytes.ToArray(), writable: false); - using BinaryReader reader = new(stream, Encoding.UTF8, leaveOpen: false); + using var stream = new MemoryStream(bytes.ToArray(), writable: false); + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); ValidateMagic(reader, C_TYPE_MANIFEST_MAGIC, "script type manifest cache"); string assemblyName = reader.ReadString(); int count = ReadCount(reader, "type manifest"); - ScriptTypeManifestEntry[] types = new ScriptTypeManifestEntry[count]; + var types = new ScriptTypeManifestEntry[count]; for (int index = 0; index < count; index++) { types[index] = new ScriptTypeManifestEntry( @@ -106,7 +106,8 @@ internal static ScriptTypeManifest DecodeTypeManifest(ReadOnlySpan bytes) reader.ReadInt32(), reader.ReadInt32(), reader.ReadBoolean(), - reader.ReadBoolean()); + reader.ReadBoolean() + ); } ValidateEndOfArtifact(stream, "script type manifest cache"); @@ -132,7 +133,9 @@ string fieldName ) { byte[] bytes = reader.ReadBytes(16); if (bytes.Length != 16) + { throw new InvalidDataException($"The script compiler cache truncated its {fieldName}."); + } return new Guid(bytes); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs index 02ef21cff..f1c905d94 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs @@ -5,23 +5,25 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; -using Inno.Runtime.Generators; -using Inno.Core.IO; -using Inno.Core.Serialization.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.IO; +using Inno.Core.Serialization.Generators; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; +using Inno.Runtime.Generators; + +using EngineSeverity = Inno.Core.Diagnostics.DiagnosticSeverity; namespace Inno.Scripting.Compiler; @@ -32,7 +34,7 @@ internal static class ScriptCompilerEngine private const string C_RUNTIME_MODULE_NAME = "RuntimeScripts"; private const string C_EDITOR_MODULE_NAME = "EditorScripts"; private const string C_EDITOR_COMPILATION_SYMBOL = "INNO_EDITOR"; - private static readonly object S_CACHE_SYNC = new(); + private static readonly object CACHE_SYNC = new(); internal static async ValueTask CompileAsync( ScriptCompilerOptions options, @@ -48,16 +50,25 @@ internal static async ValueTask CompileAsync( { throw new ArgumentException( includeEditor - ? "Authoring compilation cannot bind to a Player runtime." - : "Runtime deployment compilation requires a target Player runtime directory.", - nameof(targetRuntimeDirectory)); + ? "Authoring compilation cannot bind to a Player runtime." + : "Runtime deployment compilation requires a target Player runtime directory.", + nameof(targetRuntimeDirectory) + ); } cancellationToken.ThrowIfCancellationRequested(); reportProgress?.Invoke(0f, "Discovering project scripts..."); ScriptSourceSet sources = ScriptSourceSet.Discover(assets, plugins, includeEditor, sourceSnapshot); - return await Task.Run(() => CompileCapturedAsync( - options, sources, includeEditor, targetRuntimeDirectory, reportProgress, cancellationToken).AsTask(), - cancellationToken).ConfigureAwait(false); + return await Task.Run( + () => CompileCapturedAsync( + options, + sources, + includeEditor, + targetRuntimeDirectory, + reportProgress, + cancellationToken + ).AsTask(), + cancellationToken + ).ConfigureAwait(false); } private static async ValueTask CompileCapturedAsync( @@ -70,32 +81,38 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); var progress = new CompilationProgress( - sources.assemblies.Sum(static assembly => assembly.sources.Count) + - sources.assemblies.Count * 6 + - 8, + sources.assemblies.Sum(static assembly => assembly.sources.Count) + + sources.assemblies.Count * 6 + + 8, reportProgress, - initialCompleted: 1); + initialCompleted: 1 + ); progress.Complete("Project scripts discovered."); progress.Begin("Building the script API profile..."); ScriptApiProfile runtimeApi = ScriptApiCatalog.Build(includeEditor: false); ScriptApiProfile? editorApi = includeEditor - ? ScriptApiCatalog.Build(includeEditor: true) - : null; + ? ScriptApiCatalog.Build(includeEditor: true) + : null; progress.Complete("Script API profile built."); progress.Begin("Resolving script references..."); ScriptCompilationEnvironment environment = FrameworkReferenceResolver.Resolve(options.compilationEnvironment, cancellationToken); ScriptApiReferenceSet runtimeApiReferences = ScriptApiReferenceBuilder.Build( - options, runtimeApi, environment, cancellationToken: cancellationToken); + options, + runtimeApi, + environment, + cancellationToken: cancellationToken + ); ScriptApiReferenceSet? editorApiReferences = editorApi is null - ? null - : ScriptApiReferenceBuilder.Build( - options, - editorApi, - environment, - runtimeApi, - runtimeApiReferences, - cancellationToken); + ? null + : ScriptApiReferenceBuilder.Build( + options, + editorApi, + environment, + runtimeApi, + runtimeApiReferences, + cancellationToken + ); progress.Complete("Script references resolved."); ScriptDeploymentReferenceSet? deploymentReferences = null; if (!includeEditor) @@ -108,25 +125,19 @@ CancellationToken cancellationToken foreach (ScriptAssemblyInput assembly in sources.assemblies) { ScriptApiReferenceSet api = assembly.scope == ScriptAssemblyScope.Editor - ? editorApiReferences ?? throw new InvalidOperationException( - "A runtime deployment cannot contain an editor script assembly.") - : runtimeApiReferences; + ? editorApiReferences ?? throw new InvalidOperationException( + "A runtime deployment cannot contain an editor script assembly." + ) + : runtimeApiReferences; IReadOnlyList defines = GetCompilationDefines(assembly, includeEditor, environment.inputs.predefinedSymbols); assemblyKeys.Add( assembly.name, - ComputeAssemblyBuildKey( - assembly, - api, - deploymentReferences?.fingerprint, - assemblyKeys, - defines)); + ComputeAssemblyBuildKey(assembly, api, deploymentReferences?.fingerprint, assemblyKeys, defines) + ); } string buildKey = ComputeGenerationBuildKey(sources, assemblyKeys); string outputDirectory = Path.Combine(options.outputDirectory, buildKey); - if (TryCreateCachedResult( - outputDirectory, - sources, - out ScriptCompilationResult? cachedResult)) + if (TryCreateCachedResult(outputDirectory, sources, out ScriptCompilationResult? cachedResult)) { progress.Complete("Reused cached script assembly artifact."); return new ScriptCompilationResult( @@ -136,7 +147,8 @@ CancellationToken cancellationToken cachedResult.moduleDeployments, compiledAssemblies: [], reusedAssemblies: sources.assemblies.Select(static assembly => assembly.name).ToArray(), - stageTimings: progress.Snapshot()); + stageTimings: progress.Snapshot() + ); } IReadOnlyList platformReferences = environment.frameworkReferences; @@ -144,9 +156,9 @@ CancellationToken cancellationToken string stagingRoot = Path.Combine(options.outputDirectory, ".staging"); using var generationStaging = new TemporaryDirectory(stagingRoot); string stagingDirectory = generationStaging.path; - var diagnostics = new List(); - var compiledAssemblies = new List(); - var reusedAssemblies = new List(); + List diagnostics = []; + List compiledAssemblies = []; + List reusedAssemblies = []; progress.Begin("Preparing isolated Plugin module boundaries..."); progress.Complete("Isolated Plugin module boundaries prepared."); @@ -155,24 +167,27 @@ CancellationToken cancellationToken { bool editor = assembly.scope == ScriptAssemblyScope.Editor; ScriptApiProfile api = editor - ? editorApi ?? throw new InvalidOperationException( - "A runtime deployment cannot contain an editor script assembly.") - : runtimeApi; + ? editorApi ?? throw new InvalidOperationException( + "A runtime deployment cannot contain an editor script assembly." + ) + : runtimeApi; ScriptApiReferenceSet apiReferences = editor - ? editorApiReferences ?? throw new InvalidOperationException( - "A runtime deployment cannot contain editor API references.") - : runtimeApiReferences; + ? editorApiReferences ?? throw new InvalidOperationException( + "A runtime deployment cannot contain editor API references." + ) + : runtimeApiReferences; string assemblyPath = Path.Combine(stagingDirectory, assembly.name + ".dll"); string assemblyCacheDirectory = Path.Combine( options.outputDirectory, ".assemblies", - assemblyKeys[assembly.name]); + assemblyKeys[assembly.name] + ); if (TryCopyCachedAssembly( - assemblyCacheDirectory, - assembly.name, - stagingDirectory, - out ScriptDiagnostic[] cachedDiagnostics)) - { + assemblyCacheDirectory, + assembly.name, + stagingDirectory, + out ScriptDiagnostic[] cachedDiagnostics + )) { diagnostics.AddRange(cachedDiagnostics); compiledPaths.Add(assembly.name, assemblyPath); reusedAssemblies.Add(assembly.name); @@ -197,14 +212,15 @@ CancellationToken cancellationToken assemblyStagingPath, assembly.scope, assembly.domain, - string.IsNullOrEmpty(assembly.ownerPluginId) - ? AssetSourceId.project.value - : assembly.ownerPluginId, + string.IsNullOrEmpty(assembly.ownerPluginID) + ? AssetSourceID.project.value + : assembly.ownerPluginID, GetCompilationDefines(assembly, includeEditor, environment.inputs.predefinedSymbols), assembly.nullable, assembly.allowUnsafe, progress, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); diagnostics.AddRange(result.diagnostics); if (!result.success) { @@ -215,21 +231,15 @@ CancellationToken cancellationToken diagnostics, outputDirectory: null, moduleDeployments: null, - stageTimings: progress.Snapshot()); + stageTimings: progress.Snapshot() + ); } File.WriteAllBytes( GetDiagnosticsPath(assemblyStagingDirectory), - ScriptCompilerCacheSerialization.EncodeDiagnostics(result.diagnostics)); - CommitAssemblyCache( - assemblyStagingDirectory, - assemblyCacheDirectory, - assembly.name, - cancellationToken); - if (!TryCopyCachedAssembly( - assemblyCacheDirectory, - assembly.name, - stagingDirectory, - out _)) + ScriptCompilerCacheSerialization.EncodeDiagnostics(result.diagnostics) + ); + CommitAssemblyCache(assemblyStagingDirectory, assemblyCacheDirectory, assembly.name, cancellationToken); + if (!TryCopyCachedAssembly(assemblyCacheDirectory, assembly.name, stagingDirectory, out _)) { DeleteStagingDirectory(stagingDirectory); throw new IOException($"Committed script assembly cache '{assembly.name}' is incomplete."); @@ -240,13 +250,12 @@ CancellationToken cancellationToken File.WriteAllBytes( GetDiagnosticsPath(stagingDirectory), - ScriptCompilerCacheSerialization.EncodeDiagnostics(diagnostics)); + ScriptCompilerCacheSerialization.EncodeDiagnostics(diagnostics) + ); CommitGenerationCache(stagingDirectory, outputDirectory, sources, cancellationToken); progress.Begin("Preparing the script reload..."); - IReadOnlyList requests = CreateModuleDeployments( - outputDirectory, - sources); + IReadOnlyList requests = CreateModuleDeployments(outputDirectory, sources); progress.Complete("Script reload prepared."); return new ScriptCompilationResult( true, @@ -255,7 +264,8 @@ CancellationToken cancellationToken requests, compiledAssemblies, reusedAssemblies, - progress.Snapshot()); + progress.Snapshot() + ); } private static async ValueTask CompileAssemblyAsync( @@ -268,7 +278,7 @@ private static async ValueTask CompileAssemblyAsync( string outputPath, ScriptAssemblyScope scope, AssemblyDomain domain, - string assetSourceId, + string assetSourceID, IReadOnlyList defines, bool nullable, bool allowUnsafe, @@ -282,7 +292,8 @@ CancellationToken cancellationToken preprocessorSymbols: defines .Concat(["DEBUG", "TRACE"]) .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal)); + .OrderBy(static value => value, StringComparer.Ordinal) + ); var syntaxTrees = new List(sources.Count + 1); for (int sourceIndex = 0; sourceIndex < sources.Count; sourceIndex++) { @@ -290,37 +301,44 @@ CancellationToken cancellationToken progress.Begin($"Parsing {assemblyName} sources ({sourceIndex + 1}/{sources.Count})..."); cancellationToken.ThrowIfCancellationRequested(); string source = sourceInput.snapshotSource; - syntaxTrees.Add(CSharpSyntaxTree.ParseText( - SourceText.From(source, Encoding.UTF8), - parseOptions, - sourceInput.sourcePath, - cancellationToken)); + syntaxTrees.Add( + CSharpSyntaxTree.ParseText( + SourceText.From(source, Encoding.UTF8), + parseOptions, + sourceInput.sourcePath, + cancellationToken + ) + ); progress.Complete($"Parsed {assemblyName} source {sourceIndex + 1}/{sources.Count}."); } progress.Begin($"Preparing generated {assemblyName} sources..."); - syntaxTrees.Add(CSharpSyntaxTree.ParseText( - SourceText.From( - CreateGeneratedSource( - assemblyName, - scope == ScriptAssemblyScope.Editor, - domain, - assetSourceId), - Encoding.UTF8), - parseOptions, - $"<{assemblyName}.Generated.g.cs>", - cancellationToken)); + syntaxTrees.Add( + CSharpSyntaxTree.ParseText( + SourceText.From( + CreateGeneratedSource(assemblyName, scope == ScriptAssemblyScope.Editor, domain, assetSourceID), + Encoding.UTF8 + ), + parseOptions, + $"<{assemblyName}.Generated.g.cs>", + cancellationToken + ) + ); progress.Complete($"Prepared generated {assemblyName} sources."); var validationReferences = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in platformReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { validationReferences[reference.Display!] = reference; + } } foreach (string referencePath in apiReferences.runtimeReferencePaths) + { validationReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); + } - var validationCompilation = CSharpCompilation.Create( + CSharpCompilation validationCompilation = CSharpCompilation.Create( assemblyName, syntaxTrees, validationReferences.Values, @@ -332,15 +350,21 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, sourceReferenceResolver: new SourceFileResolver( - [], Environment.CurrentDirectory, ScriptSourceLocations.CreatePathMap(sources)), + [], + Environment.CurrentDirectory, + ScriptSourceLocations.CreatePathMap(sources) + ), nullableContextOptions: nullable - ? NullableContextOptions.Enable - : NullableContextOptions.Disable)); + ? NullableContextOptions.Enable + : NullableContextOptions.Disable + ) + ); var apiMapFile = new InMemoryAdditionalText( assemblyName + ScriptApiMapBuilder.C_FILE_EXTENSION, - ScriptApiMapBuilder.Build(api)); - var analyzerOptions = new AnalyzerOptions(ImmutableArray.Create(apiMapFile)); - var analyzers = ImmutableArray.Create(new LogicalScriptingApiAnalyzer()); + ScriptApiMapBuilder.Build(api) + ); + var analyzerOptions = new AnalyzerOptions([apiMapFile]); + ImmutableArray analyzers = [new LogicalScriptingApiAnalyzer()]; progress.Begin($"Validating the {assemblyName} API surface..."); ImmutableArray analyzerDiagnostics = await validationCompilation .WithAnalyzers(analyzers, analyzerOptions) @@ -354,43 +378,70 @@ CancellationToken cancellationToken analyzerDiagnostics .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) .Select(ToDiagnostic) - .ToArray()); + .ToArray() + ); } var usingRewriter = new ScriptApiUsingRewriter(api.namespaceMappings, api.typeMappings); var propertyOrderRewriter = new SerializablePropertyOrderRewriter(); var logicalReferences = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in platformReferences) + { if (!string.IsNullOrWhiteSpace(reference.Display)) + { logicalReferences[reference.Display!] = reference; + } + } foreach (string referencePath in apiReferences.ideReferencePaths) + { logicalReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); - var logicalBindings = CSharpCompilation.Create(assemblyName, syntaxTrees, logicalReferences.Values, validationCompilation.Options); + } + CSharpCompilation logicalBindings = CSharpCompilation.Create( + assemblyName, + syntaxTrees, + logicalReferences.Values, + validationCompilation.Options + ); SyntaxTree[] runtimeTrees = syntaxTrees .Select(tree => CSharpSyntaxTree.Create( (CSharpSyntaxNode)usingRewriter.Visit( - propertyOrderRewriter.Visit(new ScriptStaticMemberRewriter(logicalBindings.GetSemanticModel(tree)) - .Visit(tree.GetRoot(cancellationToken))))!, + propertyOrderRewriter.Visit( + new ScriptStaticMemberRewriter(logicalBindings.GetSemanticModel(tree)) + .Visit(tree.GetRoot(cancellationToken)) + ) + )!, parseOptions, tree.FilePath, - Encoding.UTF8)) + Encoding.UTF8 + )) .ToArray(); - var contractCompilation = CSharpCompilation.Create( - assemblyName, runtimeTrees, validationReferences.Values, validationCompilation.Options); + CSharpCompilation contractCompilation = CSharpCompilation.Create( + assemblyName, + runtimeTrees, + validationReferences.Values, + validationCompilation.Options + ); Diagnostic[] contractErrors = contractCompilation.GetDiagnostics(cancellationToken) - .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).ToArray(); + .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .ToArray(); if (contractErrors.Length > 0) + { return new CompilationResult(false, contractErrors.Select(ToDiagnostic).ToArray()); + } IReadOnlyCollection runtimeReferences; if (deploymentReferences is null) { // User code has passed the same trimmed contract used by IDE projects. // Generated registration alone needs the owning assemblies' implementation metadata. - var implementationReferences = platformReferences.ToDictionary( - static reference => reference.Display!, StringComparer.OrdinalIgnoreCase); + Dictionary implementationReferences = platformReferences.ToDictionary( + static reference => reference.Display!, + StringComparer.OrdinalIgnoreCase + ); foreach (string path in ScriptApiReferenceBuilder.GetImplementationPaths(api, apiReferences.environment)) + { implementationReferences[path] = MetadataReference.CreateFromFile(path); + } runtimeReferences = implementationReferences.Values; } else @@ -400,17 +451,22 @@ CancellationToken cancellationToken foreach (MetadataReference reference in platformReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { targetReferences[reference.Display!] = reference; + } } foreach (string referencePath in deploymentReferences.paths) + { targetReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); + } runtimeReferences = targetReferences.Values; } - var runtimeCompilation = CSharpCompilation.Create( + CSharpCompilation runtimeCompilation = CSharpCompilation.Create( assemblyName, runtimeTrees, runtimeReferences, - validationCompilation.Options); + validationCompilation.Options + ); progress.Begin($"Resolving {assemblyName} script type identities..."); ScriptTypeAnalysisResult typeAnalysis = ScriptTypeAnalyzer.Analyze( runtimeCompilation, @@ -418,31 +474,39 @@ CancellationToken cancellationToken api.attachableTypes.ToDictionary( static value => value.implementationName, static value => value.kind, - StringComparer.Ordinal), - cancellationToken); + StringComparer.Ordinal + ), + cancellationToken + ); if (typeAnalysis.mappings.Count > 0) { SyntaxTree mappingTree = CSharpSyntaxTree.ParseText( - SourceText.From( - ScriptTypeAnalyzer.CreateMappingSource(typeAnalysis.mappings), - Encoding.UTF8), + SourceText.From(ScriptTypeAnalyzer.CreateMappingSource(typeAnalysis.mappings), Encoding.UTF8), parseOptions, $"<{assemblyName}.ScriptTypeIds.g.cs>", - cancellationToken); + cancellationToken + ); runtimeCompilation = runtimeCompilation.AddSyntaxTrees(mappingTree); } progress.Complete($"Resolved {assemblyName} script type identities."); - if (typeAnalysis.diagnostics.Any(static diagnostic => - diagnostic.severity == Inno.Core.Diagnostics.DiagnosticSeverity.Error)) - { + if (typeAnalysis.diagnostics.Any(static diagnostic => (diagnostic.severity == EngineSeverity.Error)) + ) { return new CompilationResult(false, typeAnalysis.diagnostics); } GeneratorDriver registration = CSharpGeneratorDriver.Create( - [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), - new SerializationConverterGenerator().AsSourceGenerator(), new SerializationMetadataGenerator().AsSourceGenerator()], - parseOptions: parseOptions); - registration.RunGeneratorsAndUpdateCompilation(runtimeCompilation, out Compilation registeredCompilation, - out ImmutableArray registrationDiagnostics, cancellationToken); + [ + new RuntimeModuleCatalogGenerator().AsSourceGenerator(), + new SerializationConverterGenerator().AsSourceGenerator(), + new SerializationMetadataGenerator().AsSourceGenerator() + ], + parseOptions: parseOptions + ); + registration.RunGeneratorsAndUpdateCompilation( + runtimeCompilation, + out Compilation registeredCompilation, + out ImmutableArray registrationDiagnostics, + cancellationToken + ); runtimeCompilation = (CSharpCompilation)registeredCompilation; progress.Begin($"Checking {assemblyName} compilation diagnostics..."); Diagnostic[] preEmitDiagnostics = runtimeCompilation @@ -450,7 +514,7 @@ [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), .Concat(analyzerDiagnostics) .Concat(registrationDiagnostics) .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) - .Distinct(DiagnosticComparer.Instance) + .Distinct(DiagnosticComparer.INSTANCE) .ToArray(); progress.Complete($"Checked {assemblyName} compilation diagnostics."); if (preEmitDiagnostics.Any(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) @@ -459,7 +523,8 @@ [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), false, typeAnalysis.diagnostics .Concat(preEmitDiagnostics.Select(ToDiagnostic)) - .ToArray()); + .ToArray() + ); } string pdbPath = Path.ChangeExtension(outputPath, ".pdb"); @@ -473,75 +538,29 @@ [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), pdbStream, xmlDocumentationStream: documentationStream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); if (emit.Success) { await File.WriteAllBytesAsync( GetTypeManifestPath(outputPath), ScriptCompilerCacheSerialization.EncodeTypeManifest(typeAnalysis.manifest), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } progress.Complete($"Emitted {assemblyName}."); ScriptDiagnostic[] diagnostics = typeAnalysis.diagnostics - .Concat(preEmitDiagnostics - .Concat(emit.Diagnostics) - .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) - .Distinct(DiagnosticComparer.Instance) - .Select(ToDiagnostic)) + .Concat( + preEmitDiagnostics + .Concat(emit.Diagnostics) + .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) + .Distinct(DiagnosticComparer.INSTANCE) + .Select(ToDiagnostic) + ) .ToArray(); return new CompilationResult(emit.Success, diagnostics); } - private sealed class CompilationProgress - { - private readonly Action? m_report; - private readonly List m_timings = []; - private readonly Stopwatch m_stageStopwatch = new(); - private readonly int m_total; - private string? m_stage; - private int m_completed; - - internal CompilationProgress( - int total, - Action? report, - int initialCompleted = 0 - ) { - m_total = Math.Max(1, total); - m_report = report; - m_completed = Math.Clamp(initialCompleted, 0, m_total); - } - - internal void Begin(string status) - { - FinishCurrentStage(); - m_stage = status; - m_stageStopwatch.Restart(); - m_report?.Invoke((float)m_completed / m_total, status); - } - - internal void Complete(string status) - { - FinishCurrentStage(); - m_completed++; - m_report?.Invoke(Math.Min(1f, (float)m_completed / m_total), status); - } - - internal IReadOnlyList Snapshot() - { - FinishCurrentStage(); - return m_timings.ToArray(); - } - - private void FinishCurrentStage() - { - if (m_stage is null) - return; - m_stageStopwatch.Stop(); - m_timings.Add(new ScriptCompilationStageTiming(m_stage, m_stageStopwatch.Elapsed)); - m_stage = null; - } - } - private static string ComputeAssemblyBuildKey( ScriptAssemblyInput assembly, ScriptApiReferenceSet api, @@ -549,22 +568,24 @@ private static string ComputeAssemblyBuildKey( IReadOnlyDictionary dependencyKeys, IReadOnlyList defines ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); AppendHash(hash, "Inno.ScriptAssemblyArtifact.SourceOwned"); AppendHash(hash, typeof(ScriptCompilerEngine).Module.ModuleVersionId.ToString("N")); AppendHash(hash, typeof(RuntimeModuleCatalogGenerator).Module.ModuleVersionId.ToString("N")); AppendHash(hash, typeof(SerializationConverterGenerator).Module.ModuleVersionId.ToString("N")); - AppendHash(hash, System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); + AppendHash(hash, RuntimeInformation.FrameworkDescription); AppendHash(hash, Environment.Version.ToString()); AppendHash(hash, assembly.name); AppendHash(hash, assembly.scope.ToString()); AppendHash(hash, assembly.domain.ToString()); - AppendHash(hash, assembly.ownerPluginId); + AppendHash(hash, assembly.ownerPluginID); AppendHash(hash, assembly.definitionHash); AppendHash(hash, assembly.nullable.ToString()); AppendHash(hash, assembly.allowUnsafe.ToString()); foreach (string define in defines.OrderBy(static value => value, StringComparer.Ordinal)) + { AppendHash(hash, define); + } foreach (ScriptSourceInput source in assembly.sources.OrderBy(static value => value.relativePath, StringComparer.Ordinal)) { AppendHash(hash, source.relativePath); @@ -588,19 +609,19 @@ IReadOnlyList predefinedSymbols ) { ArgumentNullException.ThrowIfNull(assembly); return includeEditor - ? assembly.defines.Concat(predefinedSymbols) - .Append(C_EDITOR_COMPILATION_SYMBOL) - .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal) - .ToArray() - : assembly.defines.Concat(predefinedSymbols).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + ? assembly.defines.Concat(predefinedSymbols) + .Append(C_EDITOR_COMPILATION_SYMBOL) + .Distinct(StringComparer.Ordinal) + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray() + : assembly.defines.Concat(predefinedSymbols).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); } private static string ComputeGenerationBuildKey( ScriptSourceSet sources, IReadOnlyDictionary assemblyKeys ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); AppendHash(hash, "Inno.ScriptGenerationArtifact.Incremental"); foreach (ScriptAssemblyInput assembly in sources.assemblies) { @@ -627,18 +648,20 @@ out ScriptDiagnostic[] diagnostics ]; string diagnosticsPath = GetDiagnosticsPath(cacheDirectory); if (!IsCachedAssemblyComplete(cacheDirectory, assemblyName)) + { return false; + } try { - diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(diagnosticsPath)); + diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics(File.ReadAllBytes(diagnosticsPath)); Directory.CreateDirectory(destinationDirectory); for (int i = 0; i < sourcePaths.Length; i++) { File.Copy( sourcePaths[i], Path.Combine(destinationDirectory, Path.GetFileName(sourcePaths[i])), - overwrite: true); + overwrite: true + ); } TryTouchCacheDirectory(cacheDirectory); return true; @@ -663,7 +686,7 @@ private static void CommitAssemblyCache( string assemblyName, CancellationToken cancellationToken ) { - lock (S_CACHE_SYNC) + lock (CACHE_SYNC) { cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(cacheDirectory)) @@ -686,35 +709,36 @@ private static bool IsCachedAssemblyComplete( string assemblyName ) { string assemblyPath = Path.Combine(cacheDirectory, assemblyName + ".dll"); - if (!File.Exists(assemblyPath) || - !File.Exists(Path.ChangeExtension(assemblyPath, ".pdb")) || - !File.Exists(Path.ChangeExtension(assemblyPath, ".xml")) || - !File.Exists(GetTypeManifestPath(assemblyPath)) || - !File.Exists(GetDiagnosticsPath(cacheDirectory))) - { + if (!File.Exists(assemblyPath) + || !File.Exists(Path.ChangeExtension(assemblyPath, ".pdb")) + || !File.Exists(Path.ChangeExtension(assemblyPath, ".xml")) + || !File.Exists(GetTypeManifestPath(assemblyPath)) + || !File.Exists(GetDiagnosticsPath(cacheDirectory)) + ) { return false; } try { if (!HasExpectedAssemblyIdentity(assemblyPath, assemblyName)) + { return false; + } _ = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(GetDiagnosticsPath(cacheDirectory))); + File.ReadAllBytes(GetDiagnosticsPath(cacheDirectory)) + ); ScriptTypeManifest manifest = ScriptCompilerCacheSerialization.DecodeTypeManifest( - File.ReadAllBytes(GetTypeManifestPath(assemblyPath))); - if (!string.Equals( - manifest.assemblyName, - assemblyName, - StringComparison.Ordinal)) + File.ReadAllBytes(GetTypeManifestPath(assemblyPath)) + ); + if (!string.Equals(manifest.assemblyName, assemblyName, StringComparison.Ordinal)) { return false; } return true; } catch (Exception exception) when (exception is - InvalidOperationException or - IOException or - BadImageFormatException) + InvalidOperationException + or IOException + or BadImageFormatException) { return false; } @@ -726,7 +750,7 @@ private static void CommitGenerationCache( ScriptSourceSet sources, CancellationToken cancellationToken ) { - lock (S_CACHE_SYNC) + lock (CACHE_SYNC) { cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(outputDirectory)) @@ -752,12 +776,13 @@ out ScriptCompilationResult? result result = null; string diagnosticsPath = GetDiagnosticsPath(outputDirectory); if (!File.Exists(diagnosticsPath)) + { return false; + } ScriptDiagnostic[] diagnostics; try { - diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(diagnosticsPath)); + diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics(File.ReadAllBytes(diagnosticsPath)); } catch (InvalidOperationException) { @@ -770,15 +795,16 @@ out ScriptCompilationResult? result foreach (ScriptAssemblyInput assembly in sources.assemblies) { if (!IsCachedAssemblyComplete(outputDirectory, assembly.name)) + { return false; + } } result = new ScriptCompilationResult( success: true, diagnostics: diagnostics, outputDirectory: outputDirectory, - moduleDeployments: CreateModuleDeployments( - outputDirectory, - sources)); + moduleDeployments: CreateModuleDeployments(outputDirectory, sources) + ); TryTouchCacheDirectory(outputDirectory); return true; } @@ -788,7 +814,9 @@ private static void DeleteStagingDirectory(string path) try { if (Directory.Exists(path)) + { Directory.Delete(path, recursive: true); + } } catch (IOException) { @@ -831,23 +859,6 @@ string assemblyName } } - private sealed class TemporaryDirectory : IDisposable - { - internal TemporaryDirectory(string root) - { - Directory.CreateDirectory(root); - path = Path.Combine(root, Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(path); - } - - internal string path { get; } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() => DeleteStagingDirectory(path); - } - private static string GetDiagnosticsPath(string outputDirectory) => Path.Combine(outputDirectory, "diagnostics.cache"); private static string GetTypeManifestPath(string assemblyPath) => Path.ChangeExtension(assemblyPath, ".types.cache"); @@ -865,7 +876,7 @@ private static string CreateGeneratedSource( string assemblyName, bool isEditorAssembly, AssemblyDomain domain, - string assetSourceId + string assetSourceID ) { string assemblyScope = isEditorAssembly ? "Editor" : "Runtime"; return $""" @@ -873,7 +884,7 @@ string assetSourceId [assembly: System.Reflection.AssemblyMetadata("Inno.AssemblyDomain", "{domain}")] [assembly: System.Reflection.AssemblyMetadata("Inno.AssemblyScope", "{assemblyScope}")] [assembly: System.Reflection.AssemblyMetadata("Inno.ScriptAssembly", "{assemblyName}")] - [assembly: System.Reflection.AssemblyMetadata("Inno.AssetSource", "{assetSourceId}")] + [assembly: System.Reflection.AssemblyMetadata("Inno.AssetSource", "{assetSourceID}")] """; } @@ -886,20 +897,18 @@ ScriptSourceSet sources .ToArray(); string AssemblyPath(string name) => Path.Combine(outputDirectory, name + ".dll"); Dictionary pluginModules = pluginAssemblies - .Select(static assembly => assembly.ownerPluginId) + .Select(static assembly => assembly.ownerPluginID) .Distinct(StringComparer.Ordinal) - .ToDictionary( - static pluginId => pluginId, - static pluginId => "Plugin." + pluginId, - StringComparer.Ordinal); + .ToDictionary(static pluginID => pluginID, static pluginID => "Plugin." + pluginID, StringComparer.Ordinal); Dictionary assembliesByName = sources.assemblies.ToDictionary( static assembly => assembly.name, - StringComparer.OrdinalIgnoreCase); - var requests = new List(); + StringComparer.OrdinalIgnoreCase + ); + List requests = []; foreach (IGrouping group in pluginAssemblies - .GroupBy(static assembly => assembly.ownerPluginId, StringComparer.Ordinal) - .OrderBy(static group => group.Key, StringComparer.Ordinal)) - { + .GroupBy(static assembly => assembly.ownerPluginID, StringComparer.Ordinal) + .OrderBy(static group => group.Key, StringComparer.Ordinal) + ) { ScriptAssemblyInput[] owned = group .OrderBy(static assembly => assembly.scope) .ThenBy(static assembly => assembly.name, StringComparer.Ordinal) @@ -907,37 +916,49 @@ ScriptSourceSet sources ScriptAssemblyInput main = owned[0]; string[] dependencies = owned .SelectMany(static assembly => assembly.references) - .Select(reference => assembliesByName[reference].ownerPluginId) - .Where(owner => !string.IsNullOrEmpty(owner) && - !string.Equals(owner, group.Key, StringComparison.Ordinal)) + .Select(reference => assembliesByName[reference].ownerPluginID) + .Where(owner => ( + !string.IsNullOrEmpty(owner) + && !string.Equals(owner, group.Key, StringComparison.Ordinal) + )) .Distinct(StringComparer.Ordinal) .OrderBy(static value => value, StringComparer.Ordinal) .Select(owner => pluginModules[owner]) .ToArray(); - requests.Add(new ScriptModuleDeployment( - pluginModules[group.Key], - AssemblyPath(main.name), - AssemblyDomain.InnoPlugin, - main.scope == ScriptAssemblyScope.Editor ? AssemblyScope.Editor : AssemblyScope.Runtime, - owned - .Where(assembly => !ReferenceEquals(assembly, main)) - .Select(assembly => AssemblyPath(assembly.name)) - .ToArray(), - dependencies, - owned.ToDictionary( - static assembly => assembly.name, - static assembly => assembly.scope == ScriptAssemblyScope.Editor - ? AssemblyScope.Editor - : AssemblyScope.Runtime, - StringComparer.OrdinalIgnoreCase))); + requests.Add( + new ScriptModuleDeployment( + pluginModules[group.Key], + AssemblyPath(main.name), + AssemblyDomain.InnoPlugin, + main.scope == ScriptAssemblyScope.Editor ? AssemblyScope.Editor : AssemblyScope.Runtime, + owned + .Where(assembly => !ReferenceEquals(assembly, main)) + .Select(assembly => AssemblyPath(assembly.name)) + .ToArray(), + dependencies, + owned.ToDictionary( + static assembly => assembly.name, + static assembly => ( + assembly.scope == ScriptAssemblyScope.Editor + ? AssemblyScope.Editor + : AssemblyScope.Runtime + ), + StringComparer.OrdinalIgnoreCase + ) + ) + ); } ScriptAssemblyInput[] runtimeAssemblies = sources.assemblies - .Where(static assembly => assembly.domain == AssemblyDomain.InnoScripting - && assembly.scope == ScriptAssemblyScope.Runtime) + .Where(static assembly => ( + assembly.domain == AssemblyDomain.InnoScripting + && assembly.scope == ScriptAssemblyScope.Runtime + )) .ToArray(); ScriptAssemblyInput[] editorAssemblies = sources.assemblies - .Where(static assembly => assembly.domain == AssemblyDomain.InnoScripting - && assembly.scope == ScriptAssemblyScope.Editor) + .Where(static assembly => ( + assembly.domain == AssemblyDomain.InnoScripting + && assembly.scope == ScriptAssemblyScope.Editor + )) .ToArray(); string[] pluginModuleNames = pluginModules.Values .OrderBy(static value => value, StringComparer.Ordinal) @@ -952,7 +973,9 @@ ScriptSourceSet sources .Where(static assembly => assembly.name != C_GAME_ASSEMBLY_NAME) .Select(assembly => AssemblyPath(assembly.name)) .ToArray(), - pluginModuleNames)); + pluginModuleNames + ) + ); if (sources.includesEditor) { requests.Add( @@ -969,7 +992,10 @@ ScriptSourceSet sources editorAssemblies.ToDictionary( static assembly => assembly.name, static _ => AssemblyScope.Editor, - StringComparer.OrdinalIgnoreCase))); + StringComparer.OrdinalIgnoreCase + ) + ) + ); } return requests; } @@ -981,14 +1007,84 @@ private static ScriptDiagnostic ToDiagnostic(Diagnostic diagnostic) diagnostic.Id, diagnostic.Severity switch { - DiagnosticSeverity.Error => Inno.Core.Diagnostics.DiagnosticSeverity.Error, - DiagnosticSeverity.Warning => Inno.Core.Diagnostics.DiagnosticSeverity.Warning, - _ => Inno.Core.Diagnostics.DiagnosticSeverity.Info + DiagnosticSeverity.Error => EngineSeverity.Error, + DiagnosticSeverity.Warning => EngineSeverity.Warning, + _ => EngineSeverity.Info }, diagnostic.GetMessage(), string.IsNullOrWhiteSpace(location.Path) ? null : location.Path, location.IsValid ? location.StartLinePosition.Line + 1 : 0, - location.IsValid ? location.StartLinePosition.Character + 1 : 0); + location.IsValid ? location.StartLinePosition.Character + 1 : 0 + ); + } + + private sealed class CompilationProgress + { + private readonly Action? m_report; + private readonly List m_timings = []; + private readonly Stopwatch m_stageStopwatch = new(); + private readonly int m_total; + private string? m_stage; + private int m_completed; + + internal CompilationProgress( + int total, + Action? report, + int initialCompleted = 0 + ) { + m_total = Math.Max(1, total); + m_report = report; + m_completed = Math.Clamp(initialCompleted, 0, m_total); + } + + internal void Begin(string status) + { + FinishCurrentStage(); + m_stage = status; + m_stageStopwatch.Restart(); + m_report?.Invoke((float)m_completed / m_total, status); + } + + internal void Complete(string status) + { + FinishCurrentStage(); + m_completed++; + m_report?.Invoke(Math.Min(1f, (float)m_completed / m_total), status); + } + + internal IReadOnlyList Snapshot() + { + FinishCurrentStage(); + return m_timings.ToArray(); + } + + private void FinishCurrentStage() + { + if (m_stage is null) + { + return; + } + m_stageStopwatch.Stop(); + m_timings.Add(new ScriptCompilationStageTiming(m_stage, m_stageStopwatch.Elapsed)); + m_stage = null; + } + } + + private sealed class TemporaryDirectory : IDisposable + { + internal TemporaryDirectory(string root) + { + Directory.CreateDirectory(root); + this.path = Path.Combine(root, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(path); + } + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() => DeleteStagingDirectory(path); + + internal string path { get; } } private sealed record CompilationResult( @@ -1004,7 +1100,7 @@ internal InMemoryAdditionalText( string path, string text ) { - Path = path; + this.Path = path; m_text = SourceText.From(text, Encoding.UTF8); } @@ -1027,7 +1123,7 @@ string text private sealed class DiagnosticComparer : IEqualityComparer { - internal static readonly DiagnosticComparer Instance = new(); + internal static readonly DiagnosticComparer INSTANCE = new(); /// /// Determines whether this value and the supplied value represent the same logical state. @@ -1046,15 +1142,19 @@ public bool Equals( Diagnostic? right ) { if (ReferenceEquals(left, right)) + { return true; + } if (left is null || right is null) + { return false; + } FileLinePositionSpan leftLocation = left.Location.GetLineSpan(); FileLinePositionSpan rightLocation = right.Location.GetLineSpan(); - return string.Equals(left.Id, right.Id, StringComparison.Ordinal) && - string.Equals(left.GetMessage(), right.GetMessage(), StringComparison.Ordinal) && - string.Equals(leftLocation.Path, rightLocation.Path, StringComparison.Ordinal) && - leftLocation.StartLinePosition.Equals(rightLocation.StartLinePosition); + return string.Equals(left.Id, right.Id, StringComparison.Ordinal) + && string.Equals(left.GetMessage(), right.GetMessage(), StringComparison.Ordinal) + && string.Equals(leftLocation.Path, rightLocation.Path, StringComparison.Ordinal) + && leftLocation.StartLinePosition.Equals(rightLocation.StartLinePosition); } /// @@ -1069,11 +1169,7 @@ public bool Equals( public int GetHashCode(Diagnostic diagnostic) { FileLinePositionSpan location = diagnostic.Location.GetLineSpan(); - return HashCode.Combine( - diagnostic.Id, - diagnostic.GetMessage(), - location.Path, - location.StartLinePosition); + return HashCode.Combine(diagnostic.Id, diagnostic.GetMessage(), location.Path, location.StartLinePosition); } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs index 7dd0a495e..acdc08ee6 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs @@ -8,11 +8,6 @@ namespace Inno.Scripting.Compiler; -internal sealed record ScriptDeploymentReferenceSet( - IReadOnlyList paths, - string fingerprint -); - internal static class ScriptDeploymentReferenceResolver { internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) @@ -22,7 +17,8 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) if (!Directory.Exists(normalizedDirectory)) { throw new DirectoryNotFoundException( - $"The target Player runtime directory '{normalizedDirectory}' does not exist."); + $"The target Player runtime directory '{normalizedDirectory}' does not exist." + ); } string[] paths = Directory @@ -32,11 +28,12 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) if (paths.Length == 0) { throw new InvalidDataException( - $"The target Player runtime directory '{normalizedDirectory}' contains no Inno runtime assemblies."); + $"The target Player runtime directory '{normalizedDirectory}' contains no Inno runtime assemblies." + ); } var identities = new HashSet(StringComparer.OrdinalIgnoreCase); - using var fingerprint = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash fingerprint = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Append(fingerprint, "Inno.ScriptDeploymentReferences"); foreach (string path in paths) { @@ -49,16 +46,19 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) { throw new InvalidDataException( $"Target Player runtime assembly '{Path.GetFileName(path)}' is not valid managed metadata.", - exception); + exception + ); } string simpleName = identity.Name - ?? throw new InvalidDataException( - $"Target Player runtime assembly '{Path.GetFileName(path)}' has no assembly identity."); + ?? throw new InvalidDataException( + $"Target Player runtime assembly '{Path.GetFileName(path)}' has no assembly identity." + ); if (!identities.Add(simpleName)) { throw new InvalidDataException( - $"The target Player runtime contains more than one '{simpleName}' assembly identity."); + $"The target Player runtime contains more than one '{simpleName}' assembly identity." + ); } Append(fingerprint, Path.GetFileName(path)); @@ -66,9 +66,7 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) fingerprint.AppendData(SHA256.HashData(stream)); } - return new ScriptDeploymentReferenceSet( - paths, - Convert.ToHexString(fingerprint.GetHashAndReset())); + return new ScriptDeploymentReferenceSet(paths, Convert.ToHexString(fingerprint.GetHashAndReset())); } private static void Append( @@ -80,3 +78,8 @@ string value hash.AppendData(bytes); } } + +internal sealed record ScriptDeploymentReferenceSet( + IReadOnlyList paths, + string fingerprint +); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs index 74200ca70..abb55b93d 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs @@ -1,4 +1,5 @@ using Inno.Core.Diagnostics; + namespace Inno.Scripting.Compiler; /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs index 3a267ce3b..2227b14b7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs @@ -4,12 +4,11 @@ using System.Linq; using System.Security.Cryptography; using System.Text; - -using Inno.Extensibility.Modules; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; +using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -26,16 +25,21 @@ ScriptApiReferenceSet editorApi foreach (ScriptAssemblyInput assembly in sources.assemblies) { if (assembly.domain != AssemblyDomain.InnoPlugin) + { continue; + } ScriptApiReferenceSet api = assembly.scope == ScriptAssemblyScope.Editor - ? editorApi - : runtimeApi; + ? editorApi + : runtimeApi; string[] dependencies = assembly.references - .Select(name => results.TryGetValue(name, out string? path) + .Select(name => ( + results.TryGetValue(name, out string? path) ? path : throw new InvalidDataException( - $"IDE Plugin dependency '{name}' for '{assembly.name}' is unavailable.")) + $"IDE Plugin dependency '{name}' for '{assembly.name}' is unavailable." + ) + )) .ToArray(); string fingerprint = CreateFingerprint(assembly, api, dependencies); string directory = Path.Combine(root, fingerprint); @@ -55,17 +59,20 @@ private static string CreateFingerprint( ScriptApiReferenceSet api, IReadOnlyList dependencies ) { - string input = string.Join('\n', new[] - { - assembly.name, - assembly.definitionHash, - api.artifactFingerprint, - assembly.scope.ToString(), - assembly.nullable.ToString(), - assembly.allowUnsafe.ToString() - }.Concat(assembly.defines) - .Concat(assembly.sources.Select(static source => source.contentHash)) - .Concat(dependencies)); + string input = string.Join( + '\n', + new[] + { + assembly.name, + assembly.definitionHash, + api.artifactFingerprint, + assembly.scope.ToString(), + assembly.nullable.ToString(), + assembly.allowUnsafe.ToString() + }.Concat(assembly.defines) + .Concat(assembly.sources.Select(static source => source.contentHash)) + .Concat(dependencies) + ); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))); } @@ -84,12 +91,14 @@ string outputPath LanguageVersion.CSharp14, DocumentationMode.Parse, SourceCodeKind.Regular, - preprocessorSymbols: symbols); + preprocessorSymbols: symbols + ); SyntaxTree[] trees = assembly.sources.Select(source => CSharpSyntaxTree.ParseText( SourceText.From(source.snapshotSource, Encoding.UTF8), parseOptions, - source.sourcePath)).ToArray(); + source.sourcePath + )).ToArray(); IEnumerable references = api.environment.frameworkReferences .Concat(api.ideReferencePaths.Select(static path => MetadataReference.CreateFromFile(path))) .Concat(dependencies.Select(static path => MetadataReference.CreateFromFile(path))); @@ -103,8 +112,10 @@ string outputPath allowUnsafe: assembly.allowUnsafe, deterministic: true, nullableContextOptions: assembly.nullable - ? NullableContextOptions.Enable - : NullableContextOptions.Disable)); + ? NullableContextOptions.Enable + : NullableContextOptions.Disable + ) + ); string temporaryPath = outputPath + ".tmp-" + Guid.NewGuid().ToString("N"); try { @@ -112,15 +123,19 @@ string outputPath { EmitResult result = compilation.Emit( stream, - options: new EmitOptions(metadataOnly: true, includePrivateMembers: false)); + options: new EmitOptions(metadataOnly: true, includePrivateMembers: false) + ); if (!result.Success) { - string errors = string.Join(Environment.NewLine, + string errors = string.Join( + Environment.NewLine, result.Diagnostics .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) - .Select(static diagnostic => diagnostic.ToString())); + .Select(static diagnostic => diagnostic.ToString()) + ); throw new InvalidDataException( - $"Failed to generate IDE Plugin reference '{assembly.name}':{Environment.NewLine}{errors}"); + $"Failed to generate IDE Plugin reference '{assembly.name}':{Environment.NewLine}{errors}" + ); } } try @@ -135,7 +150,9 @@ string outputPath finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs index fe1e5ab5a..64680b9e6 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; - using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -30,8 +29,9 @@ internal ScriptModuleDeployment( this.upstreamModuleNames = Array.AsReadOnly(upstreamModuleNames.ToArray()); this.assemblyScopes = new ReadOnlyDictionary( assemblyScopes is null - ? new Dictionary(StringComparer.OrdinalIgnoreCase) - : new Dictionary(assemblyScopes, StringComparer.OrdinalIgnoreCase)); + ? new Dictionary(StringComparer.OrdinalIgnoreCase) + : new Dictionary(assemblyScopes, StringComparer.OrdinalIgnoreCase) + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs index d81f4b087..77e51179a 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs @@ -7,15 +7,16 @@ using System.Xml.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; namespace Inno.Scripting.Compiler; internal static class ScriptProjectGenerator { private const string C_EDITOR_COMPILATION_SYMBOL = "INNO_EDITOR"; - private static readonly IReadOnlyList C_IDE_CONTENT_FILE_EXTENSIONS = + + private static readonly IReadOnlyList IDE_CONTENT_FILE_EXTENSIONS = [ ".ishadersource" ]; @@ -40,9 +41,14 @@ PluginEnvironment plugins editorApi, environment, runtimeApi, - runtimeApiReferences); + runtimeApiReferences + ); IReadOnlyDictionary pluginReferences = ScriptIdePluginReferenceBuilder.Build( - options, sources, runtimeApiReferences, editorApiReferences); + options, + sources, + runtimeApiReferences, + editorApiReferences + ); string apiMapDirectory = Path.Combine(options.ideDirectory, "ScriptApiMaps"); Directory.CreateDirectory(apiMapDirectory); string codeAnalysisPath = CopyCodeAnalysisAssembly(options.ideDirectory); @@ -51,40 +57,39 @@ PluginEnvironment plugins bool editor = assembly.scope == ScriptAssemblyScope.Editor; ScriptApiProfile api = editor ? editorApi : runtimeApi; ScriptApiReferenceSet references = editor ? editorApiReferences : runtimeApiReferences; - string apiMapPath = Path.Combine( - apiMapDirectory, - assembly.name + ScriptApiMapBuilder.C_FILE_EXTENSION); + string apiMapPath = Path.Combine(apiMapDirectory, assembly.name + ScriptApiMapBuilder.C_FILE_EXTENSION); File.WriteAllText(apiMapPath, ScriptApiMapBuilder.Build(api)); CreateProject( - assembly.name, - ToProjectRelativePaths( - options, - assembly.sources.Select(static source => source.sourcePath).ToArray()), - api, - references, - ResolvePluginReferences(sources, assembly, pluginReferences), - apiMapPath, - codeAnalysisPath, - assembly.references - .Where(reference => userAssemblies.Any(candidate => string.Equals( - candidate.name, - reference, - StringComparison.OrdinalIgnoreCase))) - .Select(static reference => reference + ".csproj") - .ToArray(), - assembly.defines - .Concat(editor ? [C_EDITOR_COMPILATION_SYMBOL] : []) - .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal) - .ToArray(), - assembly.nullable, - assembly.allowUnsafe, - ScriptSourceLocations.CreateProjectPathMap(assembly.sources)) + assembly.name, + ToProjectRelativePaths(options, assembly.sources.Select(static source => source.sourcePath).ToArray()), + api, + references, + ResolvePluginReferences(sources, assembly, pluginReferences), + apiMapPath, + codeAnalysisPath, + assembly.references + .Where(reference => userAssemblies.Any(candidate => string.Equals( + candidate.name, + reference, + StringComparison.OrdinalIgnoreCase + ))) + .Select(static reference => reference + ".csproj") + .ToArray(), + assembly.defines + .Concat(editor ? [C_EDITOR_COMPILATION_SYMBOL] : []) + .Distinct(StringComparer.Ordinal) + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray(), + assembly.nullable, + assembly.allowUnsafe, + ScriptSourceLocations.CreateProjectPathMap(assembly.sources) + ) .Save(Path.Combine(options.projectRootDirectory, assembly.name + ".csproj")); } File.WriteAllText( Path.Combine(options.projectRootDirectory, "InnoProject.sln"), - CreateSolution(userAssemblies)); + CreateSolution(userAssemblies) + ); } private static string[] ResolvePluginReferences( @@ -94,21 +99,30 @@ IReadOnlyDictionary pluginReferences ) { IReadOnlyDictionary assemblies = sources.assemblies.ToDictionary( static assembly => assembly.name, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); var pending = new Queue(userAssembly.references); var visited = new HashSet(StringComparer.OrdinalIgnoreCase); - var references = new List(); + List references = []; while (pending.Count > 0) { string name = pending.Dequeue(); if (!visited.Add(name) || !assemblies.TryGetValue(name, out ScriptAssemblyInput? dependency)) + { continue; + } foreach (string transitiveReference in dependency.references) + { pending.Enqueue(transitiveReference); + } if (dependency.domain != AssemblyDomain.InnoPlugin) + { continue; + } if (!pluginReferences.TryGetValue(dependency.name, out string? path)) + { throw new InvalidDataException($"IDE Plugin reference '{dependency.name}' was not generated."); + } references.Add(path); } return references @@ -120,20 +134,22 @@ IReadOnlyDictionary pluginReferences private static void RemoveStalePluginProjectionFiles(ScriptCompilerOptions options) { foreach (string path in Directory.EnumerateFiles( - options.projectRootDirectory, - "Inno.Plugin.*.csproj", - SearchOption.TopDirectoryOnly)) - { + options.projectRootDirectory, + "Inno.Plugin.*.csproj", + SearchOption.TopDirectoryOnly + )) { File.Delete(path); } string apiMapDirectory = Path.Combine(options.ideDirectory, "ScriptApiMaps"); if (!Directory.Exists(apiMapDirectory)) + { return; + } foreach (string path in Directory.EnumerateFiles( - apiMapDirectory, - "Inno.Plugin.*" + ScriptApiMapBuilder.C_FILE_EXTENSION, - SearchOption.TopDirectoryOnly)) - { + apiMapDirectory, + "Inno.Plugin.*" + ScriptApiMapBuilder.C_FILE_EXTENSION, + SearchOption.TopDirectoryOnly + )) { File.Delete(path); } } @@ -162,15 +178,21 @@ private static XDocument CreateProject( bool allowUnsafe, string sourcePathMap ) { - string frozenDefines = string.Join(";", defines.Concat(apiReferences.environment.inputs.predefinedSymbols).Distinct(StringComparer.Ordinal)); - var earlyPropertyGroup = new XElement("PropertyGroup", + string frozenDefines = string.Join( + ";", + defines.Concat(apiReferences.environment.inputs.predefinedSymbols).Distinct(StringComparer.Ordinal) + ); + var earlyPropertyGroup = new XElement( + "PropertyGroup", new XElement("ImportDirectoryBuildProps", "false"), new XElement("ImportDirectoryBuildTargets", "false"), new XElement("BaseOutputPath", "Library/IDE/bin/" + assemblyName + "/"), new XElement("BaseIntermediateOutputPath", "Library/IDE/obj/" + assemblyName + "/"), new XElement("MSBuildProjectExtensionsPath", "Library/IDE/obj/" + assemblyName + "/"), - new XElement("RestoreOutputPath", "Library/IDE/obj/" + assemblyName + "/")); - var propertyGroup = new XElement("PropertyGroup", + new XElement("RestoreOutputPath", "Library/IDE/obj/" + assemblyName + "/") + ); + var propertyGroup = new XElement( + "PropertyGroup", new XElement("TargetFramework", ScriptCompilationEnvironment.C_TARGET_FRAMEWORK), new XElement("AssemblyName", assemblyName), new XElement("DefaultItemExcludes", "$(DefaultItemExcludes);Library/**"), @@ -185,100 +207,138 @@ string sourcePathMap new XElement("NoStdLib", "true"), new XElement("DefineConstants", frozenDefines), new XElement("PathMap", sourcePathMap), - new XElement("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION)); + new XElement("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION) + ); var compileGroup = new XElement( "ItemGroup", - sourcePaths.Select(static path => - new XElement("Compile", new XAttribute("Include", path)))); + sourcePaths.Select(static path => new XElement("Compile", new XAttribute("Include", path))) + ); var contentGroup = new XElement( "ItemGroup", - C_IDE_CONTENT_FILE_EXTENSIONS.Select(static extension => - new XElement("None", new XAttribute("Include", $"Assets/**/*{extension}")))); + IDE_CONTENT_FILE_EXTENSIONS.Select(static extension => + new XElement("None", new XAttribute("Include", $"Assets/**/*{extension}"))) + ); var referenceGroup = new XElement("ItemGroup"); foreach (string path in apiReferences.ideReferencePaths.Concat(apiReferences.environment.inputs.frameworkReferences)) + { AddReference(referenceGroup, path); + } foreach (string path in plugins - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(static value => value, StringComparer.Ordinal)) - { + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(static value => value, StringComparer.Ordinal) + ) { AddReference(referenceGroup, path); } - var folderGroup = new XElement("ItemGroup", - new XElement("Folder", new XAttribute("Include", "Assets/"))); - var codeAnalysisGroup = new XElement("ItemGroup", - new XElement("Analyzer", - new XAttribute("Include", codeAnalysisPath), - new XElement("Visible", "false")), - new XElement("AdditionalFiles", - new XAttribute("Include", apiMapPath), - new XElement("Visible", "false"))); - var project = new XElement("Project", + var folderGroup = new XElement("ItemGroup", new XElement("Folder", new XAttribute("Include", "Assets/"))); + var codeAnalysisGroup = new XElement( + "ItemGroup", + new XElement("Analyzer", new XAttribute("Include", codeAnalysisPath), new XElement("Visible", "false")), + new XElement("AdditionalFiles", new XAttribute("Include", apiMapPath), new XElement("Visible", "false")) + ); + var project = new XElement( + "Project", earlyPropertyGroup, - new XElement("Import", - new XAttribute("Project", "Sdk.props"), - new XAttribute("Sdk", "Microsoft.NET.Sdk")), + new XElement("Import", new XAttribute("Project", "Sdk.props"), new XAttribute("Sdk", "Microsoft.NET.Sdk")), propertyGroup, compileGroup, contentGroup, referenceGroup, - codeAnalysisGroup); - project.Add(new XElement("Target", new XAttribute("Name", "ValidateInnoScriptSdk"), - new XAttribute("BeforeTargets", "ResolveReferences"), - new XElement("Error", new XAttribute("Condition", "'$(NETCoreSdkVersion)' != '" + apiReferences.environment.inputs.sdkIdentity + "'"), - new XAttribute("Text", "The IDE selected a different SDK from the active script compilation. Regenerate project files with the intended SDK selection.")))); + codeAnalysisGroup + ); + project.Add( + new XElement( + "Target", + new XAttribute("Name", "ValidateInnoScriptSdk"), + new XAttribute("BeforeTargets", "ResolveReferences"), + new XElement( + "Error", + new XAttribute( + "Condition", + "'$(NETCoreSdkVersion)' != '" + apiReferences.environment.inputs.sdkIdentity + "'" + ), + new XAttribute( + "Text", + "The IDE selected a different SDK from the active script compilation. Regenerate project files with the intended SDK selection." + ) + ) + ) + ); XElement validation = project.Elements("Target").Single(); foreach ((string property, string expected) in new[] { ("TargetFramework", ScriptCompilationEnvironment.C_TARGET_FRAMEWORK), ("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION), - ("ImplicitUsings", "disable"), ("DisableImplicitFrameworkReferences", "true"), - ("DisableImplicitFrameworkDefines", "true"), ("NoStdLib", "true"), + ("ImplicitUsings", "disable"), + ("DisableImplicitFrameworkReferences", "true"), + ("DisableImplicitFrameworkDefines", "true"), + ("NoStdLib", "true"), ("DisableImplicitConfigurationDefines", "true"), - ("Nullable", nullable ? "enable" : "disable"), ("AllowUnsafeBlocks", allowUnsafe ? "true" : "false"), + ("Nullable", nullable ? "enable" : "disable"), + ("AllowUnsafeBlocks", allowUnsafe ? "true" : "false"), ("DefineConstants", frozenDefines) - }) - { + }) { string condition = property == "DefineConstants" - ? "$([System.String]::CompareOrdinal('$(DefineConstants)', '" + expected + "')) != 0" - : "'$(" + property + ")' != '" + expected + "'"; - validation.Add(new XElement("Error", new XAttribute("Condition", condition), - new XAttribute("Text", "The IDE compiler input '" + property + "' differs from the active script contract. Actual: '$(" + property + ")'. Expected: '" + expected + "'. Regenerate project files instead of overriding derived compiler inputs."))); + ? "$([System.String]::CompareOrdinal('$(DefineConstants)', '" + expected + "')) != 0" + : "'$(" + property + ")' != '" + expected + "'"; + validation.Add( + new XElement( + "Error", + new XAttribute("Condition", condition), + new XAttribute( + "Text", + "The IDE compiler input '" + + property + + "' differs from the active script contract. Actual: '$(" + + property + + ")'. Expected: '" + + expected + + "'. Regenerate project files instead of overriding derived compiler inputs." + ) + ) + ); } project.Add(folderGroup); if (projectReferences.Count > 0) { - project.Add(new XElement("ItemGroup", - projectReferences.Select(static reference => - new XElement("ProjectReference", new XAttribute("Include", reference))))); + project.Add( + new XElement( + "ItemGroup", + projectReferences.Select(static reference => + new XElement("ProjectReference", new XAttribute("Include", reference))) + ) + ); } - project.Add(new XElement("Import", - new XAttribute("Project", "Sdk.targets"), - new XAttribute("Sdk", "Microsoft.NET.Sdk"))); + project.Add( + new XElement("Import", new XAttribute("Project", "Sdk.targets"), new XAttribute("Sdk", "Microsoft.NET.Sdk")) + ); return new XDocument(project); } private static string[] ToProjectRelativePaths( ScriptCompilerOptions options, IReadOnlyList absolutePaths - ) - => absolutePaths - .Select(path => Path.GetRelativePath(options.projectRootDirectory, path).Replace('\\', '/')) - .OrderBy(static path => path, StringComparer.Ordinal) - .ToArray(); + ) => absolutePaths + .Select(path => Path.GetRelativePath(options.projectRootDirectory, path).Replace('\\', '/')) + .OrderBy(static path => path, StringComparer.Ordinal) + .ToArray(); private static void AddReference( XElement group, string path ) { - var reference = new XElement("Reference", + var reference = new XElement( + "Reference", new XAttribute("Include", Path.GetFileNameWithoutExtension(path)), new XElement("HintPath", path), - new XElement("Private", "false")); + new XElement("Private", "false") + ); string documentationPath = Path.ChangeExtension(path, ".xml"); if (File.Exists(documentationPath)) + { reference.Add(new XElement("DocumentationFile", documentationPath)); + } group.Add(reference); } @@ -291,10 +351,11 @@ private static string CreateSolution(IReadOnlyList assembli builder.AppendLine("MinimumVisualStudioVersion = 10.0.40219.1"); foreach (ScriptAssemblyInput assembly in assemblies) { - string id = FormatProjectId(assembly.name); + string id = FormatProjectID(assembly.name); builder.AppendLine( - $"Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = " + - $"\"{assembly.name}\", \"{assembly.name}.csproj\", \"{id}\""); + $"Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = " + + $"\"{assembly.name}\", \"{assembly.name}.csproj\", \"{id}\"" + ); builder.AppendLine("EndProject"); } builder.AppendLine("Global"); @@ -304,7 +365,7 @@ private static string CreateSolution(IReadOnlyList assembli builder.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution"); foreach (ScriptAssemblyInput assembly in assemblies) { - string id = FormatProjectId(assembly.name); + string id = FormatProjectID(assembly.name); builder.AppendLine($"\t\t{id}.Debug|Any CPU.ActiveCfg = Debug|Any CPU"); builder.AppendLine($"\t\t{id}.Debug|Any CPU.Build.0 = Debug|Any CPU"); } @@ -313,7 +374,7 @@ private static string CreateSolution(IReadOnlyList assembli return builder.ToString(); } - private static string FormatProjectId(string assemblyName) + private static string FormatProjectID(string assemblyName) { byte[] bytes = SHA256.HashData(Encoding.UTF8.GetBytes("Inno.ScriptProject:" + assemblyName)); return "{" + new Guid(bytes.AsSpan(0, 16)).ToString().ToUpperInvariant() + "}"; diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs index b368aa366..82bc70db7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs @@ -9,10 +9,12 @@ namespace Inno.Scripting.Compiler; internal static class ScriptSourceLocations { internal static ImmutableArray> CreatePathMap(IReadOnlyList sources) - => sources.Select(static source => new KeyValuePair( + => sources + .Select(static source => new KeyValuePair( Path.GetDirectoryName(source.sourcePath)!, source.assetPath.source.value + "::./" - + (Path.GetDirectoryName(source.assetPath.localPath) ?? string.Empty).Replace('\\', '/'))) + + (Path.GetDirectoryName(source.assetPath.localPath) ?? string.Empty).Replace('\\', '/') + )) .Distinct() .OrderByDescending(static mapping => mapping.Key.Length) .ThenBy(static mapping => mapping.Key, StringComparer.Ordinal) @@ -20,8 +22,12 @@ internal static ImmutableArray> CreatePathMap(IRead internal static string CreateProjectPathMap(IReadOnlyList sources) { - string value = string.Join(",", CreatePathMap(sources).Select(static mapping => - EscapeSeparators(mapping.Key) + "=" + EscapeSeparators(mapping.Value))); + string value = string.Join( + ",", + CreatePathMap(sources).Select(static mapping => ( + EscapeSeparators(mapping.Key) + "=" + EscapeSeparators(mapping.Value) + )) + ); return value.Replace("%", "%25", StringComparison.Ordinal) .Replace("$", "%24", StringComparison.Ordinal) .Replace("@", "%40", StringComparison.Ordinal) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs index 7472867e8..e45ee964d 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; using System.Text; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; using Inno.Core.Collections; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; namespace Inno.Scripting.Compiler; @@ -31,19 +31,23 @@ internal static ScriptSourceSet Discover( ArgumentNullException.ThrowIfNull(assets); ArgumentNullException.ThrowIfNull(plugins); if (!assets.isInitialized) + { throw new InvalidOperationException("Script discovery requires the Asset Database."); + } IAssetSourceSnapshot? candidateAssets = sourceSnapshot ?? plugins.compilationAssets; AssetFileEntry[] entries = (candidateAssets?.GetFileSystemEntries(includeDirectories: false) - ?? assets.GetFileSystemEntries(includeDirectories: false)) + ?? assets.GetFileSystemEntries(includeDirectories: false)) .Where(entry => includeEditor || !entry.isSampleContent) .Where(entry => includeEditor || !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) .OrderBy(static entry => entry.assetPath.source.value, StringComparer.Ordinal) .ThenBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) .ToArray(); ScriptAssemblyDefinition[] explicitDefinitions = entries - .Where(static entry => !entry.isSampleContent && - string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase)) + .Where(static entry => ( + !entry.isSampleContent + && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase) + )) .Select(entry => ParseDefinition(entry, candidateAssets, assets)) .OrderBy(static definition => definition.source.value, StringComparer.Ordinal) .ThenBy(static definition => definition.directory, StringComparer.Ordinal) @@ -51,17 +55,21 @@ internal static ScriptSourceSet Discover( var builders = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (ScriptAssemblyDefinition definition in explicitDefinitions) + { AddBuilder(builders, definition); + } if (builders.ContainsKey(C_GAME_ASSEMBLY_NAME) || builders.ContainsKey(C_EDITOR_ASSEMBLY_NAME)) { throw new InvalidDataException( - $"Assembly definitions cannot use the reserved {C_GAME_ASSEMBLY_NAME} or {C_EDITOR_ASSEMBLY_NAME} names."); + $"Assembly definitions cannot use the reserved {C_GAME_ASSEMBLY_NAME} or {C_EDITOR_ASSEMBLY_NAME} names." + ); } PluginCandidate[] codePlugins = plugins.compilationPlugins - .Where(candidate => entries.Any(entry => + .Where(candidate => entries.Any(entry => ( entry.assetPath.source == candidate.sourceMount.id - && string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase))) + && string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase) + ))) .ToArray(); ValidateManifestDefinitions(entries, explicitDefinitions, codePlugins); @@ -71,89 +79,118 @@ internal static ScriptSourceSet Discover( string runtimeName = CreatePluginAssemblyName(plugin.manifest.pluginId); string editorName = runtimeName + ".Editor"; string samplesName = runtimeName + ".Samples"; - pluginDefaultNames.Add(plugin.manifest.pluginId, - new PluginDefaultNames(runtimeName, editorName, samplesName)); - AddBuilder(builders, CreateDefaultDefinition( - runtimeName, - plugin.sourceMount.id, - ScriptAssemblyScope.Runtime, - AssemblyDomain.InnoPlugin, + pluginDefaultNames.Add( plugin.manifest.pluginId, - "plugin-default-runtime")); - AddBuilder(builders, CreateDefaultDefinition( - editorName, - plugin.sourceMount.id, - ScriptAssemblyScope.Editor, - AssemblyDomain.InnoPlugin, - plugin.manifest.pluginId, - "plugin-default-editor")); - if (includeEditor) - AddBuilder(builders, CreateDefaultDefinition( - samplesName, + new PluginDefaultNames(runtimeName, editorName, samplesName) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + runtimeName, + plugin.sourceMount.id, + ScriptAssemblyScope.Runtime, + AssemblyDomain.InnoPlugin, + plugin.manifest.pluginId, + "plugin-default-runtime" + ) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + editorName, plugin.sourceMount.id, ScriptAssemblyScope.Editor, AssemblyDomain.InnoPlugin, plugin.manifest.pluginId, - "plugin-authoring-samples")); + "plugin-default-editor" + ) + ); + if (includeEditor) + { + AddBuilder( + builders, + CreateDefaultDefinition( + samplesName, + plugin.sourceMount.id, + ScriptAssemblyScope.Editor, + AssemblyDomain.InnoPlugin, + plugin.manifest.pluginId, + "plugin-authoring-samples" + ) + ); + } } - AddBuilder(builders, CreateDefaultDefinition( - C_GAME_ASSEMBLY_NAME, - AssetSourceId.project, - ScriptAssemblyScope.Runtime, - AssemblyDomain.InnoScripting, - string.Empty, - "project-default-runtime")); - AddBuilder(builders, CreateDefaultDefinition( - C_EDITOR_ASSEMBLY_NAME, - AssetSourceId.project, - ScriptAssemblyScope.Editor, - AssemblyDomain.InnoScripting, - string.Empty, - "project-default-editor")); + AddBuilder( + builders, + CreateDefaultDefinition( + C_GAME_ASSEMBLY_NAME, + AssetSourceID.project, + ScriptAssemblyScope.Runtime, + AssemblyDomain.InnoScripting, + string.Empty, + "project-default-runtime" + ) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + C_EDITOR_ASSEMBLY_NAME, + AssetSourceID.project, + ScriptAssemblyScope.Editor, + AssemblyDomain.InnoScripting, + string.Empty, + "project-default-editor" + ) + ); ConfigureDefaultReferences(builders, explicitDefinitions, codePlugins, pluginDefaultNames); foreach (AssetFileEntry entry in entries.Where(static entry => - string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase))) - { + string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase)) + ) { if (entry.isSampleContent) { - if (entry.assetPath.source == AssetSourceId.project) + if (entry.assetPath.source == AssetSourceID.project) + { continue; + } if (!plugins.TryGetCompilationPlugin(entry.assetPath.source, out PluginCandidate? samplePlugin) || samplePlugin is null - || !pluginDefaultNames.TryGetValue(samplePlugin.manifest.pluginId, - out PluginDefaultNames sampleNames)) + || !pluginDefaultNames.TryGetValue( + samplePlugin.manifest.pluginId, + out PluginDefaultNames sampleNames + ) + ) { throw new InvalidDataException($"Sample script '{entry.assetPath}' has no active Plugin."); + } builders[sampleNames.samples].sources.Add(CreateSourceInput(entry, candidateAssets, assets)); continue; } ScriptAssemblyDefinition? definition = FindNearestDefinition(entry.assetPath, explicitDefinitions); ScriptAssemblyScope scope = definition?.scope - ?? (entry.assetPath.localPath.EndsWith(".editor.cs", StringComparison.OrdinalIgnoreCase) - ? ScriptAssemblyScope.Editor - : ScriptAssemblyScope.Runtime); + ?? (entry.assetPath.localPath.EndsWith(".editor.cs", StringComparison.OrdinalIgnoreCase) + ? ScriptAssemblyScope.Editor + : ScriptAssemblyScope.Runtime); AssemblyBuilder builder; if (definition is not null) { builder = builders[definition.name]; } - else if (entry.assetPath.source == AssetSourceId.project) + else if (entry.assetPath.source == AssetSourceID.project) { builder = builders[scope == ScriptAssemblyScope.Editor - ? C_EDITOR_ASSEMBLY_NAME - : C_GAME_ASSEMBLY_NAME]; + ? C_EDITOR_ASSEMBLY_NAME + : C_GAME_ASSEMBLY_NAME]; } else { - if (!plugins.TryGetCompilationPlugin( - entry.assetPath.source, - out PluginCandidate? plugin) + if (!plugins.TryGetCompilationPlugin(entry.assetPath.source, out PluginCandidate? plugin) || plugin is null - || !pluginDefaultNames.TryGetValue(plugin.manifest.pluginId, out PluginDefaultNames names)) - { + || !pluginDefaultNames.TryGetValue(plugin.manifest.pluginId, out PluginDefaultNames names) + ) { throw new InvalidDataException( - $"Script '{entry.assetPath}' does not belong to an active Plugin source."); + $"Script '{entry.assetPath}' does not belong to an active Plugin source." + ); } builder = builders[scope == ScriptAssemblyScope.Editor ? names.editor : names.runtime]; } @@ -164,22 +201,21 @@ internal static ScriptSourceSet Discover( ? builders : builders .Where(static pair => pair.Value.definition.scope == ScriptAssemblyScope.Runtime) - .ToDictionary( - static pair => pair.Key, - static pair => pair.Value, - StringComparer.OrdinalIgnoreCase); + .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase); ScriptAssemblyInput[] assemblies = ValidateAndOrderAssemblies(compilationBuilders, plugins); return new ScriptSourceSet( builders[C_GAME_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray(), includeEditor - ? builders[C_EDITOR_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray() - : [], + ? builders[C_EDITOR_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray() + : [], includeEditor - ? explicitDefinitions - : explicitDefinitions.Where(static definition => - definition.scope == ScriptAssemblyScope.Runtime).ToArray(), + ? explicitDefinitions + : explicitDefinitions.Where(static definition => ( + definition.scope == ScriptAssemblyScope.Runtime + )).ToArray(), assemblies, - includeEditor); + includeEditor + ); } private static ScriptAssemblyDefinition ParseDefinition( @@ -188,14 +224,16 @@ private static ScriptAssemblyDefinition ParseDefinition( AssetPipeline assets ) { ScriptAssemblyDefinitionAsset asset = candidateAssets is null - ? assets.Load(entry.assetPath) - : candidateAssets.Load(entry.assetPath); + ? assets.Load(entry.assetPath) + : candidateAssets.Load(entry.assetPath); bool hasInfo = candidateAssets is null - ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) - : candidateAssets.TryGetInfo(entry.assetPath, out info); + ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + : candidateAssets.TryGetInfo(entry.assetPath, out info); if (!hasInfo || info is null) + { throw new InvalidDataException($"Script assembly definition '{entry.assetPath}' has no metadata."); - bool isPlugin = entry.assetPath.source != AssetSourceId.project; + } + bool isPlugin = entry.assetPath.source != AssetSourceID.project; return new ScriptAssemblyDefinition( asset.assemblyName, entry.assetPath.source, @@ -207,7 +245,8 @@ AssetPipeline assets asset.defines, asset.nullable, asset.allowUnsafe, - ComputeDefinitionHash(asset)); + ComputeDefinitionHash(asset) + ); } private static ScriptSourceInput CreateSourceInput( @@ -216,30 +255,31 @@ private static ScriptSourceInput CreateSourceInput( AssetPipeline assets ) { bool hasInfo = candidateAssets is null - ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) - : candidateAssets.TryGetInfo(entry.assetPath, out info); + ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + : candidateAssets.TryGetInfo(entry.assetPath, out info); if (!hasInfo || info is null - || info.persistentId == Guid.Empty + || info.persistentID == Guid.Empty || !(candidateAssets is null - ? assets.TryGetArtifact(info.persistentId, "source", out AssetArtifactInfo? source) - : candidateAssets.TryGetArtifact(info.persistentId, "source", out source)) - || source is null) - { + ? assets.TryGetArtifact(info.persistentID, "source", out AssetArtifactInfo? source) + : candidateAssets.TryGetArtifact(info.persistentID, "source", out source)) + || source is null + ) { throw new InvalidDataException($"Script source '{entry.assetPath}' has no committed source artifact."); } IReadOnlyList mounts = candidateAssets?.sourceMounts ?? assets.sourceMounts; AssetSourceMount mount = mounts.Single(candidate => candidate.id == entry.assetPath.source); using ArtifactLease lease = candidateAssets is null - ? assets.AcquireArtifact(info.persistentId, "source") - : candidateAssets.AcquireArtifact(info.persistentId, "source"); - using StreamReader reader = new(lease.OpenRead(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + ? assets.AcquireArtifact(info.persistentID, "source") + : candidateAssets.AcquireArtifact(info.persistentID, "source"); + using var reader = new StreamReader(lease.OpenRead(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); return new ScriptSourceInput( entry.assetPath, mount.Resolve(entry.assetPath.localPath), reader.ReadToEnd(), - info.persistentId, - source.contentHash); + info.persistentID, + source.contentHash + ); } private static string ComputeDefinitionHash(ScriptAssemblyDefinitionAsset asset) @@ -253,10 +293,10 @@ private static string ComputeDefinitionHash(ScriptAssemblyDefinitionAsset asset) asset.nullable.ToString(), asset.allowUnsafe.ToString() } - .Concat(asset.references.OrderBy(static value => value, StringComparer.Ordinal)) - .Concat(asset.defines.OrderBy(static value => value, StringComparer.Ordinal))); - return Convert.ToHexString( - System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); + .Concat(asset.references.OrderBy(static value => value, StringComparer.Ordinal)) + .Concat(asset.defines.OrderBy(static value => value, StringComparer.Ordinal)) + ); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); } private static void ValidateManifestDefinitions( @@ -268,22 +308,27 @@ IReadOnlyList plugins foreach (PluginCandidate plugin in plugins) { string[] declared = plugin.manifest.assemblyDefinitions - .Select(static path => path.StartsWith("Assets/", StringComparison.Ordinal) + .Select(static path => ( + path.StartsWith("Assets/", StringComparison.Ordinal) ? path["Assets/".Length..] - : path) + : path + )) .OrderBy(static path => path, StringComparer.Ordinal) .ToArray(); string[] discovered = entries - .Where(entry => entry.assetPath.source == plugin.sourceMount.id + .Where(entry => ( + entry.assetPath.source == plugin.sourceMount.id && !entry.isSampleContent - && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase)) + && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase) + )) .Select(static entry => entry.assetPath.localPath) .OrderBy(static path => path, StringComparer.Ordinal) .ToArray(); if (!declared.SequenceEqual(discovered, StringComparer.Ordinal)) { throw new InvalidDataException( - $"Plugin '{plugin.manifest.pluginId}' assemblyDefinitions do not match its imported .iasmdef sources."); + $"Plugin '{plugin.manifest.pluginId}' assemblyDefinitions do not match its imported .iasmdef sources." + ); } } } @@ -308,17 +353,20 @@ IReadOnlyDictionary defaultNames samples.references.Add(names.runtime); samples.references.Add(names.editor); } - foreach (string dependencyId in plugin.manifest.dependencies) + foreach (string dependencyID in plugin.manifest.dependencies) { - foreach (ScriptAssemblyDefinition dependency in explicitDefinitions.Where(definition => - definition.ownerPluginId == dependencyId)) - { + foreach (ScriptAssemblyDefinition dependency in explicitDefinitions.Where(definition => ( + definition.ownerPluginID == dependencyID + )) + ) { if (dependency.scope == ScriptAssemblyScope.Runtime) + { runtime.references.Add(dependency.name); + } pluginEditor.references.Add(dependency.name); samples?.references.Add(dependency.name); } - if (defaultNames.TryGetValue(dependencyId, out PluginDefaultNames dependencyDefaults)) + if (defaultNames.TryGetValue(dependencyID, out PluginDefaultNames dependencyDefaults)) { runtime.references.Add(dependencyDefaults.runtime); pluginEditor.references.Add(dependencyDefaults.runtime); @@ -330,11 +378,14 @@ IReadOnlyDictionary defaultNames game.references.Add(names.runtime); editor.references.Add(names.runtime); editor.references.Add(names.editor); - foreach (ScriptAssemblyDefinition definition in explicitDefinitions.Where(candidate => - candidate.ownerPluginId == plugin.manifest.pluginId)) - { + foreach (ScriptAssemblyDefinition definition in explicitDefinitions.Where(candidate => ( + candidate.ownerPluginID == plugin.manifest.pluginId + )) + ) { if (definition.scope == ScriptAssemblyScope.Runtime) + { game.references.Add(definition.name); + } editor.references.Add(definition.name); } } @@ -369,27 +420,31 @@ PluginEnvironment plugins if (!builders.TryGetValue(reference, out AssemblyBuilder? dependency)) { throw new InvalidDataException( - $"Script assembly '{builder.definition.name}' references unknown assembly '{reference}'."); + $"Script assembly '{builder.definition.name}' references unknown assembly '{reference}'." + ); } if (builder.definition.scope == ScriptAssemblyScope.Runtime - && dependency.definition.scope == ScriptAssemblyScope.Editor) - { + && dependency.definition.scope == ScriptAssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime script assembly '{builder.definition.name}' cannot reference editor assembly '{reference}'."); + $"Runtime script assembly '{builder.definition.name}' cannot reference editor assembly '{reference}'." + ); } ValidateDomainDependency(builder.definition, dependency.definition, plugins); } } - var graph = new DependencyGraph( - StringComparer.OrdinalIgnoreCase, - StringComparer.Ordinal); + var graph = new DependencyGraph(StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal); foreach (string name in builders.Keys) + { graph.AddNode(name); + } foreach ((string name, string[] references) in referencesByAssembly) { foreach (string reference in references) + { graph.AddDependency(name, reference); + } } IReadOnlyList order; try @@ -407,13 +462,14 @@ PluginEnvironment plugins builder.definition.name, builder.definition.scope, builder.definition.domain, - builder.definition.ownerPluginId, + builder.definition.ownerPluginID, builder.sources.OrderBy(static value => value.assetPath.ToString(), StringComparer.Ordinal).ToArray(), referencesByAssembly[name], builder.definition.defines, builder.definition.nullable, builder.definition.allowUnsafe, - builder.definition.configurationHash); + builder.definition.configurationHash + ); }).ToArray(); } @@ -423,63 +479,71 @@ private static void ValidateDomainDependency( PluginEnvironment plugins ) { if (assembly.domain != AssemblyDomain.InnoPlugin) + { return; + } if (dependency.domain != AssemblyDomain.InnoPlugin) { throw new InvalidDataException( - $"Plugin assembly '{assembly.name}' cannot reference project assembly '{dependency.name}'."); + $"Plugin assembly '{assembly.name}' cannot reference project assembly '{dependency.name}'." + ); } - if (string.Equals(assembly.ownerPluginId, dependency.ownerPluginId, StringComparison.Ordinal)) + if (string.Equals(assembly.ownerPluginID, dependency.ownerPluginID, StringComparison.Ordinal)) + { return; - if (!plugins.TryGetCompilationPlugin( - new AssetSourceId(assembly.ownerPluginId), - out PluginCandidate? owner) + } + if (!plugins.TryGetCompilationPlugin(new AssetSourceID(assembly.ownerPluginID), out PluginCandidate? owner) || owner is null - || !owner.manifest.dependencies.Contains(dependency.ownerPluginId, StringComparer.Ordinal)) - { + || !owner.manifest.dependencies.Contains(dependency.ownerPluginID, StringComparer.Ordinal) + ) { throw new InvalidDataException( - $"Plugin '{assembly.ownerPluginId}' must declare dependency '{dependency.ownerPluginId}' " + - $"before assembly '{assembly.name}' can reference '{dependency.name}'."); + $"Plugin '{assembly.ownerPluginID}' must declare dependency '{dependency.ownerPluginID}' " + + $"before assembly '{assembly.name}' can reference '{dependency.name}'." + ); } } private static ScriptAssemblyDefinition CreateDefaultDefinition( string name, - AssetSourceId source, + AssetSourceID source, ScriptAssemblyScope scope, AssemblyDomain domain, - string ownerPluginId, + string ownerPluginID, string configurationHash - ) - => new( - name, - source, - string.Empty, - scope, - domain, - ownerPluginId, - [], - ["DEBUG", "TRACE"], - nullable: true, - allowUnsafe: false, - configurationHash); + ) => new( + name, + source, + string.Empty, + scope, + domain, + ownerPluginID, + [], + ["DEBUG", "TRACE"], + nullable: true, + allowUnsafe: false, + configurationHash + ); private static void AddBuilder( IDictionary builders, ScriptAssemblyDefinition definition ) { if (!builders.TryAdd(definition.name, new AssemblyBuilder(definition))) + { throw new InvalidDataException($"Script assembly name '{definition.name}' is declared more than once."); + } } - private static string CreatePluginAssemblyName(string pluginId) + private static string CreatePluginAssemblyName(string pluginID) { var builder = new StringBuilder("Inno.Plugin."); - foreach (string segment in pluginId.Split(['.', '-', '_'], StringSplitOptions.RemoveEmptyEntries)) + foreach (string segment in pluginID.Split(['.', '-', '_'], StringSplitOptions.RemoveEmptyEntries)) { builder.Append(char.ToUpperInvariant(segment[0])); for (int i = 1; i < segment.Length; i++) + { builder.Append(char.IsLetterOrDigit(segment[i]) ? segment[i] : '_'); + } } return builder.ToString(); } @@ -487,10 +551,9 @@ private static string CreatePluginAssemblyName(string pluginId) private static bool IsWithin( string directory, string ancestor - ) - => string.IsNullOrEmpty(ancestor) - || string.Equals(directory, ancestor, StringComparison.OrdinalIgnoreCase) - || directory.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + ) => string.IsNullOrEmpty(ancestor) + || string.Equals(directory, ancestor, StringComparison.OrdinalIgnoreCase) + || directory.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); private sealed class AssemblyBuilder { @@ -514,11 +577,11 @@ string samples internal sealed record ScriptAssemblyDefinition( string name, - AssetSourceId source, + AssetSourceID source, string directory, ScriptAssemblyScope scope, AssemblyDomain domain, - string ownerPluginId, + string ownerPluginID, IReadOnlyList references, IReadOnlyList defines, bool nullable, @@ -530,7 +593,7 @@ internal sealed record ScriptAssemblyInput( string name, ScriptAssemblyScope scope, AssemblyDomain domain, - string ownerPluginId, + string ownerPluginID, IReadOnlyList sources, IReadOnlyList references, IReadOnlyList defines, @@ -543,7 +606,7 @@ internal sealed record ScriptSourceInput( AssetPath assetPath, string sourcePath, string snapshotSource, - Guid persistentId, + Guid persistentID, string contentHash ) { internal string relativePath => assetPath.ToString(); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs index 519354792..ced354238 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs @@ -33,13 +33,19 @@ internal sealed class ScriptStaticMemberRewriter(SemanticModel model) : CSharpSy private SyntaxNode? Qualify(SimpleNameSyntax node) { if (node.Parent is MemberAccessExpressionSyntax member && member.Name == node - || node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax) + || node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax + ) { return null; + } if (model.GetSymbolInfo(node).Symbol is not IMethodSymbol { IsStatic: true, MethodKind: MethodKind.Ordinary } method - || !SymbolEqualityComparer.Default.Equals(method.ContainingAssembly, model.Compilation.Assembly)) + || !SymbolEqualityComparer.Default.Equals(method.ContainingAssembly, model.Compilation.Assembly) + ) { return null; - return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, + } + return SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)), - node.WithoutTrivia()).WithTriviaFrom(node); + node.WithoutTrivia() + ).WithTriviaFrom(node); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs index 4d7901e31..26f6b39bf 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs @@ -1,19 +1,20 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using EngineSeverity = Inno.Core.Diagnostics.DiagnosticSeverity; + namespace Inno.Scripting.Compiler; internal static class ScriptTypeAnalyzer { - private const string C_STABLE_TYPE_ID_ATTRIBUTE = - "Inno.Extensibility.Types.StableTypeIdAttribute"; + private const string C_STABLE_TYPE_ID_ATTRIBUTE = "Inno.Extensibility.Types.StableTypeIDAttribute"; internal static ScriptTypeAnalysisResult Analyze( CSharpCompilation compilation, @@ -21,26 +22,28 @@ internal static ScriptTypeAnalysisResult Analyze( IReadOnlyDictionary attachableTypes, CancellationToken cancellationToken ) { - var sourcesByPath = sources.ToDictionary( + Dictionary sourcesByPath = sources.ToDictionary( static source => source.sourcePath, - StringComparer.OrdinalIgnoreCase); - var discovered = new Dictionary( - SymbolEqualityComparer.Default); + StringComparer.OrdinalIgnoreCase + ); + var discovered = new Dictionary(SymbolEqualityComparer.Default); foreach (SyntaxTree tree in compilation.SyntaxTrees) { if (!sourcesByPath.TryGetValue(tree.FilePath, out ScriptSourceInput? source)) + { continue; + } SemanticModel semanticModel = compilation.GetSemanticModel(tree); foreach (TypeDeclarationSyntax declaration in tree.GetRoot(cancellationToken) - .DescendantNodes() - .OfType()) - { - if (semanticModel.GetDeclaredSymbol(declaration, cancellationToken) is not INamedTypeSymbol symbol || - symbol.TypeKind != TypeKind.Class || - symbol.IsAbstract || - symbol.IsGenericType || - !TryGetAttachableKind(symbol, attachableTypes, out string kind)) - { + .DescendantNodes() + .OfType() + ) { + if (semanticModel.GetDeclaredSymbol(declaration, cancellationToken) is not INamedTypeSymbol symbol + || symbol.TypeKind != TypeKind.Class + || symbol.IsAbstract + || symbol.IsGenericType + || !TryGetAttachableKind(symbol, attachableTypes, out string kind) + ) { continue; } @@ -53,43 +56,43 @@ CancellationToken cancellationToken } } - var diagnostics = new List(); - var manifestEntries = new List(); - var mappings = new List(); - var implicitTypesBySource = discovered.Values - .Where(static type => GetExplicitStableTypeId(type.symbol) is null) - .SelectMany(static type => type.declarations - .Select(declaration => (declaration.source.persistentId, type))) - .GroupBy(static value => value.persistentId) + List diagnostics = []; + List manifestEntries = []; + List mappings = []; + Dictionary implicitTypesBySource = discovered.Values + .Where(static type => GetExplicitStableTypeID(type.symbol) is null) + .SelectMany(static type => type.declarations.Select(declaration => (declaration.source.persistentID, type))) + .GroupBy(static value => value.persistentID) .ToDictionary( static group => group.Key, static group => group.Select(static value => value.type) .Distinct() - .Count()); + .Count() + ); foreach (MutableScriptType type in discovered.Values - .OrderBy(static value => GetMetadataTypeName(value.symbol), StringComparer.Ordinal)) - { + .OrderBy(static value => GetMetadataTypeName(value.symbol), StringComparer.Ordinal) + ) { string typeName = GetMetadataTypeName(type.symbol); - string? explicitIdValue = GetExplicitStableTypeId(type.symbol); - if (explicitIdValue is not null) + string? explicitIDValue = GetExplicitStableTypeID(type.symbol); + if (explicitIDValue is not null) { ScriptDeclaration declaration = SelectManifestDeclaration(type); - if (!Guid.TryParse(explicitIdValue, out Guid explicitId)) + if (!Guid.TryParse(explicitIDValue, out Guid explicitID)) { - diagnostics.Add(CreateDiagnostic( - "INNO2000", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Type '{typeName}' has invalid StableTypeId '{explicitIdValue}'.", - declaration)); + diagnostics.Add( + CreateDiagnostic( + "INNO2000", + EngineSeverity.Error, + $"Type '{typeName}' has invalid StableTypeID '{explicitIDValue}'.", + declaration + ) + ); continue; } - manifestEntries.Add(CreateManifestEntry( - type, - declaration, - explicitId, - explicitIdentity: true, - canonicalSource: true)); + manifestEntries.Add( + CreateManifestEntry(type, declaration, explicitID, explicitIdentity: true, canonicalSource: true) + ); continue; } @@ -97,8 +100,9 @@ CancellationToken cancellationToken .Where(declaration => string.Equals( GetCanonicalFileName(declaration.source.sourcePath), type.symbol.Name, - StringComparison.Ordinal)) - .GroupBy(static declaration => declaration.source.persistentId) + StringComparison.Ordinal + )) + .GroupBy(static declaration => declaration.source.persistentID) .Select(static group => group.First()) .ToArray(); ScriptDeclaration? canonical = null; @@ -108,76 +112,88 @@ CancellationToken cancellationToken } else if (matchingDeclarations.Length > 1) { - diagnostics.Add(CreateDiagnostic( - "INNO2003", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Partial type '{typeName}' has more than one source file matching its type name. " + - "Keep one canonical source or add an explicit StableTypeId.", - matchingDeclarations[0])); + diagnostics.Add( + CreateDiagnostic( + "INNO2003", + EngineSeverity.Error, + $"Partial type '{typeName}' has more than one source file matching its type name. " + + "Keep one canonical source or add an explicit StableTypeID.", + matchingDeclarations[0] + ) + ); } else { ScriptDeclaration[] distinctSources = type.declarations - .GroupBy(static declaration => declaration.source.persistentId) + .GroupBy(static declaration => declaration.source.persistentID) .Select(static group => group.First()) .ToArray(); - if (distinctSources.Length == 1 && - implicitTypesBySource.GetValueOrDefault(distinctSources[0].source.persistentId) == 1) - { + if (distinctSources.Length == 1 + && implicitTypesBySource.GetValueOrDefault(distinctSources[0].source.persistentID) == 1 + ) { canonical = distinctSources[0]; - diagnostics.Add(CreateDiagnostic( - "INNO2002", - Inno.Core.Diagnostics.DiagnosticSeverity.Warning, - $"Attachable type '{typeName}' does not match its canonical script file name. " + - "Its source identity is preserved, but matching names are recommended.", - canonical)); + diagnostics.Add( + CreateDiagnostic( + "INNO2002", + EngineSeverity.Warning, + $"Attachable type '{typeName}' does not match its canonical script file name. " + + "Its source identity is preserved, but matching names are recommended.", + canonical + ) + ); } else { ScriptDeclaration declaration = distinctSources[0]; - diagnostics.Add(CreateDiagnostic( - "INNO2001", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Attachable type '{typeName}' has no unambiguous canonical script source. " + - "Move it to a matching file or add an explicit StableTypeId.", - declaration)); + diagnostics.Add( + CreateDiagnostic( + "INNO2001", + EngineSeverity.Error, + $"Attachable type '{typeName}' has no unambiguous canonical script source. " + + "Move it to a matching file or add an explicit StableTypeID.", + declaration + ) + ); } } if (canonical is null) + { continue; - Guid stableTypeId = ScriptTypeIdentity.CreateCanonical(canonical.source.persistentId); - mappings.Add(new ScriptTypeMapping(typeName, stableTypeId)); - manifestEntries.Add(CreateManifestEntry( - type, - canonical, - stableTypeId, - explicitIdentity: false, - canonicalSource: true)); + } + Guid stableTypeID = ScriptTypeIdentity.CreateCanonical(canonical.source.persistentID); + mappings.Add(new ScriptTypeMapping(typeName, stableTypeID)); + manifestEntries.Add( + CreateManifestEntry(type, canonical, stableTypeID, explicitIdentity: false, canonicalSource: true) + ); } foreach (IGrouping collision in mappings - .GroupBy(static mapping => mapping.stableTypeId) - .Where(static group => group.Count() > 1)) - { + .GroupBy(static mapping => mapping.stableTypeID) + .Where(static group => group.Count() > 1) + ) { ScriptTypeMapping[] conflicting = collision.ToArray(); ScriptTypeManifestEntry entry = manifestEntries.First(value => string.Equals(value.typeName, conflicting[0].typeName, StringComparison.Ordinal)); - diagnostics.Add(new ScriptDiagnostic( - "INNO2004", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Script source '{entry.sourcePath}' owns more than one attachable type identity: " + - string.Join(", ", conflicting.Select(static value => value.typeName)) + - ". Keep one canonical type or add explicit StableTypeId attributes.", - entry.sourcePath, - entry.line, - entry.column)); + diagnostics.Add( + new ScriptDiagnostic( + "INNO2004", + EngineSeverity.Error, + $"Script source '{entry.sourcePath}' owns more than one attachable type identity: " + + string.Join(", ", conflicting.Select(static value => value.typeName)) + + ". Keep one canonical type or add explicit StableTypeID attributes.", + entry.sourcePath, + entry.line, + entry.column + ) + ); } return new ScriptTypeAnalysisResult( new ScriptTypeManifest(compilation.AssemblyName ?? string.Empty, manifestEntries), mappings, - diagnostics); + diagnostics + ); } internal static string CreateMappingSource(IReadOnlyList mappings) @@ -185,7 +201,7 @@ internal static string CreateMappingSource(IReadOnlyList mapp var source = new StringBuilder("#nullable enable\n"); foreach (ScriptTypeMapping mapping in mappings.OrderBy(static value => value.typeName, StringComparer.Ordinal)) { - string value = $"{mapping.stableTypeId:D}|{mapping.typeName}"; + string value = $"{mapping.stableTypeID:D}|{mapping.typeName}"; source.Append("[assembly: global::System.Reflection.AssemblyMetadataAttribute(") .Append(SymbolDisplay.FormatLiteral("Inno.StableTypeId", quote: true)) .Append(", ") @@ -212,34 +228,37 @@ out string kind return false; } - private static string? GetExplicitStableTypeId(INamedTypeSymbol symbol) + private static string? GetExplicitStableTypeID(INamedTypeSymbol symbol) { AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(value => string.Equals( value.AttributeClass?.ToDisplayString(), C_STABLE_TYPE_ID_ATTRIBUTE, - StringComparison.Ordinal)); + StringComparison.Ordinal + )); return attribute?.ConstructorArguments.Length > 0 - ? attribute.ConstructorArguments[0].Value as string - : null; + ? attribute.ConstructorArguments[0].Value as string + : null; } private static string GetMetadataTypeName(INamedTypeSymbol symbol) { var typeNames = new Stack(); for (INamedTypeSymbol? current = symbol; current is not null; current = current.ContainingType) + { typeNames.Push(current.MetadataName); + } string nestedName = string.Join("+", typeNames); return symbol.ContainingNamespace.IsGlobalNamespace - ? nestedName - : symbol.ContainingNamespace.ToDisplayString() + "." + nestedName; + ? nestedName + : symbol.ContainingNamespace.ToDisplayString() + "." + nestedName; } private static string GetCanonicalFileName(string sourcePath) { - string name = System.IO.Path.GetFileNameWithoutExtension(sourcePath); + string name = Path.GetFileNameWithoutExtension(sourcePath); return name.EndsWith(".editor", StringComparison.OrdinalIgnoreCase) - ? name[..^".editor".Length] - : name; + ? name[..^".editor".Length] + : name; } private static ScriptDeclaration SelectManifestDeclaration(MutableScriptType type) @@ -247,14 +266,15 @@ private static ScriptDeclaration SelectManifestDeclaration(MutableScriptType typ .OrderByDescending(declaration => string.Equals( GetCanonicalFileName(declaration.source.sourcePath), type.symbol.Name, - StringComparison.Ordinal)) + StringComparison.Ordinal + )) .ThenBy(static declaration => declaration.source.relativePath, StringComparer.Ordinal) .First(); private static ScriptTypeManifestEntry CreateManifestEntry( MutableScriptType type, ScriptDeclaration declaration, - Guid stableTypeId, + Guid stableTypeID, bool explicitIdentity, bool canonicalSource ) { @@ -262,18 +282,19 @@ bool canonicalSource return new ScriptTypeManifestEntry( GetMetadataTypeName(type.symbol), type.kind, - stableTypeId, - declaration.source.persistentId, + stableTypeID, + declaration.source.persistentID, declaration.source.relativePath, span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, explicitIdentity, - canonicalSource); + canonicalSource + ); } private static ScriptDiagnostic CreateDiagnostic( string id, - Inno.Core.Diagnostics.DiagnosticSeverity severity, + EngineSeverity severity, string message, ScriptDeclaration declaration ) { @@ -284,7 +305,8 @@ ScriptDeclaration declaration message, declaration.source.sourcePath, span.StartLinePosition.Line + 1, - span.StartLinePosition.Character + 1); + span.StartLinePosition.Character + 1 + ); } private sealed class MutableScriptType( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs index 69ec571ca..38c3ec6f7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs @@ -6,24 +6,25 @@ namespace Inno.Scripting.Compiler; internal static class ScriptTypeIdentity { - private static readonly Guid C_SCRIPT_SOURCE_NAMESPACE = - Guid.Parse("6ca29f90-69d4-4f27-b42b-fdad7cc10e6a"); + private static readonly Guid SCRIPT_SOURCE_NAMESPACE = Guid.Parse("6ca29f90-69d4-4f27-b42b-fdad7cc10e6a"); - internal static Guid CreateCanonical(Guid sourcePersistentId) + internal static Guid CreateCanonical(Guid sourcePersistentID) { - if (sourcePersistentId == Guid.Empty) - throw new ArgumentException("A script source identity is required.", nameof(sourcePersistentId)); - return CreateGuidV5(C_SCRIPT_SOURCE_NAMESPACE, sourcePersistentId.ToString("D")); + if (sourcePersistentID == Guid.Empty) + { + throw new ArgumentException("A script source identity is required.", nameof(sourcePersistentID)); + } + return CreateGuidV5(SCRIPT_SOURCE_NAMESPACE, sourcePersistentID.ToString("D")); } private static Guid CreateGuidV5( - Guid namespaceId, + Guid namespaceID, string name ) { - byte[] namespaceBytes = namespaceId.ToByteArray(); + byte[] namespaceBytes = namespaceID.ToByteArray(); SwapGuidByteOrder(namespaceBytes); byte[] nameBytes = Encoding.UTF8.GetBytes(name); - byte[] data = new byte[namespaceBytes.Length + nameBytes.Length]; + var data = new byte[namespaceBytes.Length + nameBytes.Length]; Buffer.BlockCopy(namespaceBytes, 0, data, 0, namespaceBytes.Length); Buffer.BlockCopy(nameBytes, 0, data, namespaceBytes.Length, nameBytes.Length); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeManifest.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeManifest.cs index fb71d3f6e..c71d1c9c7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeManifest.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeManifest.cs @@ -11,8 +11,8 @@ IReadOnlyList types internal sealed record ScriptTypeManifestEntry( string typeName, string kind, - Guid stableTypeId, - Guid sourcePersistentId, + Guid stableTypeID, + Guid sourcePersistentID, string sourcePath, int line, int column, @@ -22,7 +22,7 @@ bool canonicalSource internal sealed record ScriptTypeMapping( string typeName, - Guid stableTypeId + Guid stableTypeID ); internal sealed record ScriptTypeAnalysisResult( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs index 6225592fd..d5a7dbb05 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs @@ -1,6 +1,6 @@ +using System; using System.Collections.Generic; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -27,7 +27,9 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter public override SyntaxNode? Visit(SyntaxNode? node) { if (node is not TypeDeclarationSyntax) + { return base.Visit(node); + } m_nextOrders.Push(0); try @@ -50,9 +52,7 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter /// The validated syntax node? that represents the completed operation. /// public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) - { - return base.VisitFieldDeclaration(RewriteMember(node, node.AttributeLists)); - } + => base.VisitFieldDeclaration(RewriteMember(node, node.AttributeLists)); /// /// Visits property declaration in deterministic order using the supplied visitor. @@ -64,30 +64,30 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter /// The validated syntax node? that represents the completed operation. /// public override SyntaxNode? VisitPropertyDeclaration(PropertyDeclarationSyntax node) - { - return base.VisitPropertyDeclaration(RewriteMember(node, node.AttributeLists)); - } + => base.VisitPropertyDeclaration(RewriteMember(node, node.AttributeLists)); private TMember RewriteMember( TMember member, SyntaxList attributeLists - ) - where TMember : MemberDeclarationSyntax + ) where TMember : MemberDeclarationSyntax { if (m_nextOrders.Count == 0 || !TryFindSerializableAttribute(attributeLists, out AttributeSyntax attribute)) + { return member; + } int order = m_nextOrders.Pop(); m_nextOrders.Push(order + 1); if (HasExplicitOrder(attribute)) + { return member; + } AttributeArgumentSyntax orderArgument = SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals(C_ORDER_PROPERTY_NAME), nameColon: null, - SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(order))); + SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(order)) + ); AttributeArgumentListSyntax argumentList = attribute.ArgumentList ?? SyntaxFactory.AttributeArgumentList(); AttributeSyntax rewrittenAttribute = attribute.WithArgumentList(argumentList.AddArguments(orderArgument)); return member.ReplaceNode(attribute, rewrittenAttribute); @@ -112,20 +112,19 @@ out AttributeSyntax result } private static bool HasExplicitOrder(AttributeSyntax attribute) - { - return attribute.ArgumentList?.Arguments.Any(static argument => - string.Equals(argument.NameEquals?.Name.Identifier.ValueText, C_ORDER_PROPERTY_NAME, - System.StringComparison.Ordinal)) == true; - } + => attribute.ArgumentList?.Arguments.Any(static argument => + string.Equals( + argument.NameEquals?.Name.Identifier.ValueText, + C_ORDER_PROPERTY_NAME, + StringComparison.Ordinal + )) == true; private static string GetRightmostName(NameSyntax name) + => name switch { - return name switch - { - IdentifierNameSyntax identifier => identifier.Identifier.ValueText, - QualifiedNameSyntax qualified => GetRightmostName(qualified.Right), - AliasQualifiedNameSyntax alias => alias.Name.Identifier.ValueText, - _ => name.ToString() - }; - } + IdentifierNameSyntax identifier => identifier.Identifier.ValueText, + QualifiedNameSyntax qualified => GetRightmostName(qualified.Right), + AliasQualifiedNameSyntax alias => alias.Name.Identifier.ValueText, + _ => name.ToString() + }; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs index dff34b19d..90fd1e906 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs @@ -4,12 +4,11 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets.Pipeline; -using Inno.Core.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Assets.Pipeline; +using Inno.Core.Serialization; namespace Inno.Scripting.Compiler; @@ -20,6 +19,7 @@ internal sealed class CSharpScriptImporter : AssetImporter /// Gets whether imported output is deployed to runtime, editor, or both domains. /// public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Gets the normalized source extensions accepted by this importer. /// @@ -51,7 +51,8 @@ CancellationToken cancellationToken new CSharpParseOptions(LanguageVersion.CSharp14, DocumentationMode.Parse), context.assetPath.ToString(), Encoding.UTF8, - cancellationToken); + cancellationToken + ); BaseTypeDeclarationSyntax[] declarations = tree.GetRoot(cancellationToken) .DescendantNodes() .OfType() @@ -67,26 +68,31 @@ CancellationToken cancellationToken .ToArray(); ScriptAssemblyScope scope = context.assetPath.localPath.EndsWith( ".editor.cs", - StringComparison.OrdinalIgnoreCase) - ? ScriptAssemblyScope.Editor - : ScriptAssemblyScope.Runtime; + StringComparison.OrdinalIgnoreCase + ) + ? ScriptAssemblyScope.Editor + : ScriptAssemblyScope.Runtime; output.SetAsset(new ScriptSourceAsset(scope, declaredTypes, diagnostics)); await output.WriteArtifactAsync( "source", Encoding.UTF8.GetBytes(source), - cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); await output.WriteArtifactAsync( "diagnostics", Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, diagnostics)), - cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); var typeManifest = new ScriptSourceTypeManifest( - context.persistentId, + context.persistentID, context.assetPath.ToString(), - declarations.Select(CreateTypeDeclaration).ToArray()); + declarations.Select(CreateTypeDeclaration).ToArray() + ); await output.WriteArtifactAsync( "type-manifest", context.serialization.Serialize(typeManifest), - cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); } private static ScriptSourceTypeDeclaration CreateTypeDeclaration(BaseTypeDeclarationSyntax declaration) @@ -97,7 +103,8 @@ private static ScriptSourceTypeDeclaration CreateTypeDeclaration(BaseTypeDeclara declaration.Kind().ToString(), declaration.Modifiers.Any(static modifier => modifier.IsKind(SyntaxKind.PartialKeyword)), span.StartLinePosition.Line + 1, - span.StartLinePosition.Character + 1); + span.StartLinePosition.Character + 1 + ); } private static string GetDeclaredTypeName(BaseTypeDeclarationSyntax declaration) @@ -115,7 +122,7 @@ private static string GetDeclaredTypeName(BaseTypeDeclarationSyntax declaration) .Select(static value => value.Name.ToString()) .ToArray(); return namespaces.Length == 0 - ? nestedTypeName - : string.Join(".", namespaces) + "." + nestedTypeName; + ? nestedTypeName + : string.Join(".", namespaces) + "." + nestedTypeName; } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs index fc80a46ca..a7a4250a1 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -15,6 +14,7 @@ internal sealed class ScriptAssemblyDefinitionImporter : AssetImporter public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Gets the normalized source extensions accepted by this importer. /// @@ -43,15 +43,22 @@ CancellationToken cancellationToken ScriptAssemblyDefinitionAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } if (string.IsNullOrWhiteSpace(asset.assemblyName)) + { throw new InvalidOperationException("Assembly definition name is required."); + } if (!Enum.IsDefined(asset.scope)) + { throw new InvalidOperationException("Assembly definition scope must be Runtime or Editor."); + } output.SetAsset(asset); - await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } @@ -77,9 +84,11 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(asset.assemblyName)) + { throw new InvalidOperationException("Assembly definition name is required."); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + } + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs index d3cbdc0ed..5354f6ffd 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs @@ -38,10 +38,14 @@ IEnumerable predefinedSymbols ArgumentNullException.ThrowIfNull(predefinedSymbols); string[] references = frameworkReferences.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); if (references.Length == 0 || references.Any(static path => !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("SDK framework references must be a nonempty set of absolute paths.", nameof(frameworkReferences)); + } this.sdkIdentity = sdkIdentity; this.frameworkReferences = Array.AsReadOnly(references); - this.predefinedSymbols = Array.AsReadOnly(predefinedSymbols.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()); + this.predefinedSymbols = Array.AsReadOnly( + predefinedSymbols.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs index 71fb666cf..912c7fd90 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs @@ -3,7 +3,6 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Plugins.Authoring; @@ -19,6 +18,7 @@ public sealed class ScriptCompiler private readonly ScriptArtifactCache m_artifacts; private readonly ScriptCompilerOptions m_options; private readonly PluginEnvironment m_plugins; + /// /// Creates a compiler over explicit authoring services owned by one host. /// @@ -49,7 +49,7 @@ PluginEnvironment plugins ArgumentException.ThrowIfNullOrWhiteSpace(options.projectRootDirectory); m_options = new ScriptCompilerOptions { - projectRootDirectory = System.IO.Path.GetFullPath(options.projectRootDirectory), + projectRootDirectory = Path.GetFullPath(options.projectRootDirectory), compilationEnvironment = options.compilationEnvironment }; m_assets = assets; @@ -63,27 +63,18 @@ PluginEnvironment plugins /// /// Thrown when the authoring asset pipeline is not initialized. /// - public void GenerateProjectFiles() - { - ScriptProjectGenerator.Generate( - m_options, - m_assets, - m_plugins); - } + public void GenerateProjectFiles() => ScriptProjectGenerator.Generate(m_options, m_assets, m_plugins); /// /// Compiles a complete runtime and editor candidate generation without activating it. /// - /// - /// Source discovery captures live inputs on the owner thread. Reference generation, Roslyn and - /// artifact writes run in the background; progress observers must accept callbacks from either thread. - /// Retain the source generation until the returned operation drains, including after cancellation. - /// Complete cache trees use Core IO atomic publication and replacement. A committed cache remains - /// valid if cleanup of its previous tree fails; compilation does not activate either generation. - /// /// /// Optional observer for monotonic compiler progress. /// + /// + /// Optional isolated authoring sources. Capture on its owner thread and keep its transaction + /// alive until compilation drains; null selects the current Plugin candidate or active sources. + /// /// /// The token that cancels compilation before an artifact generation is committed. /// @@ -102,38 +93,36 @@ public void GenerateProjectFiles() /// /// Cache replacement and restoration both fail; the exception identifies the preserved previous tree. /// - /// - /// Optional isolated authoring sources. Capture on its owner thread and keep its transaction - /// alive until compilation drains; null selects the current Plugin candidate or active sources. - /// + /// + /// Source discovery captures live inputs on the owner thread. Reference generation, Roslyn and + /// artifact writes run in the background; progress observers must accept callbacks from either thread. + /// Retain the source generation until the returned operation drains, including after cancellation. + /// Complete cache trees use Core IO atomic publication and replacement. A committed cache remains + /// valid if cleanup of its previous tree fails; compilation does not activate either generation. + /// public ValueTask CompileAuthoringGenerationAsync( IProgress? progress = null, - CancellationToken cancellationToken = default, - IAssetSourceSnapshot? sourceSnapshot = null - ) - => ScriptCompilerEngine.CompileAsync( - m_options, - m_assets, - m_plugins, - includeEditor: true, - targetRuntimeDirectory: null, - progress is null - ? null - : ( - fraction, - stage - ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), - cancellationToken, - sourceSnapshot); + IAssetSourceSnapshot? sourceSnapshot = null, + CancellationToken cancellationToken = default + ) => ScriptCompilerEngine.CompileAsync( + m_options, + m_assets, + m_plugins, + includeEditor: true, + targetRuntimeDirectory: null, + progress is null + ? null + : ( + fraction, + stage + ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), + cancellationToken, + sourceSnapshot + ); /// /// Compiles only the runtime assembly closure required by a deployed Player and binds it to that Player runtime. /// - /// - /// Complete cache trees use Core IO atomic publication and replacement. Cancellation before commit - /// preserves the previous tree; cancellation does not undo a committed cache. Cleanup failure after - /// commit preserves the installed tree and remaining backup without activating a generation. - /// /// /// The verified Player Support Pack directory whose runtime assemblies will execute the emitted scripts. /// @@ -167,6 +156,11 @@ progress is null /// /// Cache replacement and restoration both fail; the exception identifies the preserved previous tree. /// + /// + /// Complete cache trees use Core IO atomic publication and replacement. Cancellation before commit + /// preserves the previous tree; cancellation does not undo a committed cache. Cleanup failure after + /// commit preserves the installed tree and remaining backup without activating a generation. + /// public ValueTask CompileRuntimeDeploymentAsync( string targetRuntimeDirectory, IProgress? progress = null, @@ -180,12 +174,13 @@ public ValueTask CompileRuntimeDeploymentAsync( includeEditor: false, targetRuntimeDirectory: targetRuntimeDirectory, progress is null - ? null - : ( - fraction, - stage - ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), - cancellationToken); + ? null + : ( + fraction, + stage + ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), + cancellationToken + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs b/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs index c0364f739..1977b490e 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs @@ -1,6 +1,5 @@ -using Inno.Extensibility.Reload; - using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; namespace Inno.Scripting.Reload; diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs index 98300a910..84ae18cb0 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs @@ -1,19 +1,21 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Reflection; using System.Runtime.ExceptionServices; using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Core.Diagnostics; +using Inno.Core.Settings; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Inno.Core.Settings; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; namespace Inno.Scripting.Reload; @@ -39,19 +41,21 @@ public sealed class ScriptReloadHost : IDisposable private readonly Func m_moduleSourceFactory; private readonly SemaphoreSlim m_compileGate = new(1, 1); private readonly CancellationTokenSource m_lifetimeCancellation = new(); + private readonly TaskCompletionSource m_disposalCompleted = new( - TaskCreationOptions.RunContinuationsAsynchronously); - private readonly CancellationToken m_lifetimeToken; + TaskCreationOptions.RunContinuationsAsynchronously + ); + private readonly CancellationToken m_lifetimeToken; + private readonly Dictionary m_pluginModules = new(StringComparer.Ordinal); + private readonly Dictionary m_activeModuleFingerprints = new(StringComparer.Ordinal); private CancellationTokenSource? m_activeCompilationCancellation; private ScriptCompilationResult? m_activeCompilation; private PendingReload? m_pendingCompilation; private ScriptCompilationResult? m_lastCompilation; - private readonly Dictionary m_pluginModules = new(StringComparer.Ordinal); private AssemblyModuleHandle? m_runtimeScriptModule; private AssemblyModuleHandle? m_editorScriptModule; private string? m_activeCompilationDirectory; - private readonly Dictionary m_activeModuleFingerprints = new(StringComparer.Ordinal); private ScriptReloadProgress m_progress = new(0, 0f, "Waiting for script changes.", false); private long m_progressOperation; private long m_activeProgressOperation; @@ -120,22 +124,28 @@ Func moduleSourceFactory ArgumentNullException.ThrowIfNull(reloads); ArgumentNullException.ThrowIfNull(moduleSourceFactory); if (options.debounceMilliseconds < 0) - throw new ArgumentOutOfRangeException(nameof(options), "Debounce duration cannot be negative."); - if (options.compilationWarningTimeout <= TimeSpan.Zero && - options.compilationWarningTimeout != Timeout.InfiniteTimeSpan) { + throw new ArgumentOutOfRangeException(nameof(options), "Debounce duration cannot be negative."); + } + if (options.compilationWarningTimeout <= TimeSpan.Zero + && options.compilationWarningTimeout != Timeout.InfiniteTimeSpan + ) { throw new ArgumentOutOfRangeException( nameof(options), - "Compilation warning timeout must be positive or infinite."); + "Compilation warning timeout must be positive or infinite." + ); } if (options.unloadCollectionInterval < TimeSpan.Zero) - throw new ArgumentOutOfRangeException(nameof(options), "Unload collection interval cannot be negative."); - if (options.unloadRetentionTimeout <= TimeSpan.Zero && - options.unloadRetentionTimeout != Timeout.InfiniteTimeSpan) { + throw new ArgumentOutOfRangeException(nameof(options), "Unload collection interval cannot be negative."); + } + if (options.unloadRetentionTimeout <= TimeSpan.Zero + && options.unloadRetentionTimeout != Timeout.InfiniteTimeSpan + ) { throw new ArgumentOutOfRangeException( nameof(options), - "Unload retention timeout must be positive or infinite."); + "Unload retention timeout must be positive or infinite." + ); } m_assets = assets; m_compiler = compiler; @@ -173,7 +183,9 @@ public bool isCompilationPending get { lock (m_sync) + { return m_requestedReload != ScriptReloadRequest.None; + } } } @@ -191,8 +203,8 @@ public TimeSpan compilationElapsed { long started = Volatile.Read(ref m_compilationStartedTimestamp); return isCompiling && started != 0 - ? TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)) - : m_lastCompilationElapsed; + ? TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)) + : m_lastCompilationElapsed; } } @@ -200,9 +212,9 @@ public TimeSpan compilationElapsed /// Gets whether the active compilation exceeded the configured warning duration. /// public bool isCompilationTakingLong - => isCompiling && - m_options.compilationWarningTimeout != Timeout.InfiniteTimeSpan && - compilationElapsed >= m_options.compilationWarningTimeout; + => isCompiling + && m_options.compilationWarningTimeout != Timeout.InfiniteTimeSpan + && compilationElapsed >= m_options.compilationWarningTimeout; /// /// Gets the most recently completed compilation. @@ -212,7 +224,9 @@ public ScriptCompilationResult? lastCompilation get { lock (m_sync) + { return m_lastCompilation; + } } } @@ -224,7 +238,9 @@ public bool isUnloadVerificationPending get { lock (m_sync) + { return m_modules.generations.state == GenerationState.AwaitingCollection; + } } } @@ -236,7 +252,9 @@ public bool isFaulted get { lock (m_sync) + { return m_modules.generations.state == GenerationState.Faulted; + } } } @@ -247,29 +265,33 @@ public void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_assets.isInitialized) + { throw new InvalidOperationException("ScriptReloadHost requires AssetPipeline to be initialized first."); + } m_assets.Update(); - m_assets.Changed -= OnAssetDatabaseChanged; - m_assets.Changed += OnAssetDatabaseChanged; - m_assets.SourceMountsChanged -= OnSourceMountsChanged; - m_assets.SourceMountsChanged += OnSourceMountsChanged; - m_plugins.ActivationCandidateChanged -= OnPluginActivationCandidateChanged; - m_plugins.ActivationCandidateChanged += OnPluginActivationCandidateChanged; + m_assets.changed -= OnAssetDatabaseChanged; + m_assets.changed += OnAssetDatabaseChanged; + m_assets.sourceMountsChanged -= OnSourceMountsChanged; + m_assets.sourceMountsChanged += OnSourceMountsChanged; + m_plugins.activationCandidateChanged -= OnPluginActivationCandidateChanged; + m_plugins.activationCandidateChanged += OnPluginActivationCandidateChanged; if (m_options.autoCompile) { lock (m_sync) { - bool hasActiveScripting = m_modules.isInitialized && - m_modules.modules.Any(static module => module.domain == AssemblyDomain.InnoScripting); + bool hasActiveScripting = m_modules.isInitialized + && m_modules.modules.Any(static module => module.domain == AssemblyDomain.InnoScripting); m_requestedReload = m_plugins.hasPendingActivation - ? ScriptReloadRequest.ReloadPlugins - : hasActiveScripting - ? ScriptReloadRequest.Recompile - : ScriptReloadRequest.ReloadScripting; + ? ScriptReloadRequest.ReloadPlugins + : hasActiveScripting + ? ScriptReloadRequest.Recompile + : ScriptReloadRequest.ReloadScripting; m_initialCompileRequested = true; m_lastCompileRequestTimestamp = Environment.TickCount64; - Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f, - "Initial scripting cache probe queued.", false)); + Volatile.Write( + ref m_progress, + new ScriptReloadProgress(++m_progressOperation, 0f, "Initial scripting cache probe queued.", false) + ); } } } @@ -277,29 +299,35 @@ public void Start() /// /// Requests cancellation of the active compilation without changing the active script generation. /// + /// + /// The observed request; a stale cancellation is rejected. + /// /// /// when an active compilation received the request. /// /// /// Thrown after the manager has been disposed. /// - /// - /// The observed request; a stale cancellation is rejected. - /// - public bool CancelCompilation(long operationId) + public bool CancelCompilation(long operationID) { ObjectDisposedException.ThrowIf(m_disposed, this); CancellationTokenSource? cancellation; lock (m_sync) { - if (operationId != m_progress.operationId || operationId != m_activeProgressOperation) + if (operationID != m_progress.operationID || operationID != m_activeProgressOperation) + { return false; + } cancellation = m_activeCompilationCancellation; if (cancellation is not null) - SetCompilationProgress(m_progress.fraction, "Canceling script compilation...", operationId, cancellationRequested: true); + { + SetCompilationProgress(m_progress.fraction, "Canceling script compilation...", operationID, cancellationRequested: true); + } } if (cancellation is null) + { return false; + } try { cancellation.Cancel(); @@ -317,10 +345,7 @@ public bool CancelCompilation(long operationId) /// /// Thrown after the manager has been disposed. /// - public void RecompileScripting() - { - QueueReload(ScriptReloadRequest.Recompile); - } + public void RecompileScripting() => QueueReload(ScriptReloadRequest.Recompile); /// /// Queues a complete rebuild of both scripting load contexts while retaining the plugin generation. @@ -343,15 +368,15 @@ public void RecompileScripting() /// /// Starts a pending compilation after the configured quiet period has elapsed. /// - /// - /// The initial automatic request is immediately ready and does not observe the debounce duration. - /// /// /// The started compilation task, or when none was ready. /// /// /// when a pending compilation was started. /// + /// + /// The initial automatic request is immediately ready and does not observe the debounce duration. + /// public bool TryCompilePending(out Task? compilation) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -372,137 +397,29 @@ public bool TryCompilePending(out Task? compilation) return false; } long elapsed = Environment.TickCount64 - m_lastCompileRequestTimestamp; - if (m_requestedReload == ScriptReloadRequest.None || - isCompiling || - !m_initialCompileRequested && elapsed < m_options.debounceMilliseconds) - { + if (m_requestedReload == ScriptReloadRequest.None + || isCompiling + || !m_initialCompileRequested && elapsed < m_options.debounceMilliseconds + ) { compilation = null; return false; } request = m_requestedReload; - operation = m_progress.operationId; + operation = m_progress.operationID; m_requestedReload = ScriptReloadRequest.None; m_initialCompileRequested = false; } if (m_assets.isInitialized) + { m_assets.Update(); + } PluginUnavailabilityPlan? unavailability = request == ScriptReloadRequest.ReloadPlugins - ? CapturePluginUnavailabilityPlan() - : null; + ? CapturePluginUnavailabilityPlan() + : null; compilation = CompileAsync(request, unavailability, operation).AsTask(); return true; } - private async ValueTask CompileAsync( - ScriptReloadRequest request, - PluginUnavailabilityPlan? unavailability, - long operation, - CancellationToken cancellationToken = default - ) { - ObjectDisposedException.ThrowIf(m_disposed, this); - using CancellationTokenSource linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource( - cancellationToken, - m_lifetimeToken); - CancellationToken effectiveCancellation = linkedCancellation.Token; - await m_compileGate.WaitAsync(effectiveCancellation).ConfigureAwait(false); - try - { - effectiveCancellation.ThrowIfCancellationRequested(); - ObjectDisposedException.ThrowIf(m_disposed, this); - Volatile.Write(ref m_isCompiling, 1); - Volatile.Write(ref m_compilationStartedTimestamp, Environment.TickCount64); - lock (m_sync) - { - m_activeCompilationCancellation = linkedCancellation; - m_activeProgressOperation = operation; - m_acceptCompilerProgress = true; - } - SetCompilationProgress(0f, "Preparing script compilation...", operation, canCancel: true); - ScriptCompilationResult result; - try - { - result = await m_compiler - .CompileAuthoringGenerationAsync( - new ScriptProgressObserver(( - progress, - status - ) => SetCompilationProgress( - progress * C_COMPILATION_PROGRESS_SHARE, - progress >= 1f ? "Compilation finished; waiting for generation activation and state recovery." : status, - operation, isCompilerUpdate: true)), - effectiveCancellation) - .ConfigureAwait(false); - } - catch (OperationCanceledException) when (effectiveCancellation.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - result = ScriptCompilationResult.Failure( - new ScriptDiagnostic( - "INNO0001", - DiagnosticSeverity.Error, - exception.ToString(), - filePath: null, - line: 0, - column: 0)); - } - lock (m_sync) - { - if (!m_disposed) - { - m_acceptCompilerProgress = false; - m_lastCompilation = result; - if (m_requestedReload != ScriptReloadRequest.None) - { - if (request > m_requestedReload) - m_requestedReload = request; - m_pendingCompilation = null; - } - else if (result.success || unavailability is not null) - { - m_pendingCompilation = new PendingReload( - result, - request, - operation, - result.success ? null : unavailability); - } - SetCompilationProgress( - result.success || unavailability is not null ? C_COMPILATION_PROGRESS_SHARE : progress.fraction, - m_requestedReload != ScriptReloadRequest.None - ? "Compilation superseded by a queued reload request." - : result.success - ? "Script compilation completed; waiting for generation activation and state recovery." - : unavailability is not null - ? "Compilation failed after a Plugin availability change; the unavailable " + - "generation is ready to activate." - : "Script compilation failed.", operation); - } - } - return result; - } - finally - { - long started = Interlocked.Exchange(ref m_compilationStartedTimestamp, 0); - if (started != 0) - { - m_lastCompilationElapsed = TimeSpan.FromMilliseconds( - Math.Max(0, Environment.TickCount64 - started)); - } - lock (m_sync) - { - if (ReferenceEquals(m_activeCompilationCancellation, linkedCancellation)) - { - m_activeCompilationCancellation = null; - m_acceptCompilerProgress = false; - } - } - Volatile.Write(ref m_isCompiling, 0); - m_compileGate.Release(); - } - } - /// /// Applies the latest compiled generation, or commits a Plugin-unavailability generation when changed /// Plugin code cannot produce a replacement, at a caller-controlled main-thread safe point. @@ -521,18 +438,26 @@ public bool ApplyPendingReload() { ThrowIfFaultedLocked(); if (m_modules.generations.state == GenerationState.AwaitingCollection) - throw new InvalidOperationException("A new script generation cannot activate before the previous unload barrier completes."); + { + throw new InvalidOperationException( + "A new script generation cannot activate before the previous unload barrier completes." + ); + } pending = m_pendingCompilation; if (pending is not null && m_requestedReload != ScriptReloadRequest.None) { if (pending.request > m_requestedReload) + { m_requestedReload = pending.request; + } m_pendingCompilation = null; pending = null; } } if (pending is null) + { return false; + } ReloadPlan plan = SelectReloadPlan(pending); if (plan.requests.Count == 0 && plan.removedModuleNames.Count == 0) @@ -540,35 +465,36 @@ public bool ApplyPendingReload() m_plugins.ApplyPendingChange(); CompletePendingReload(pending); m_reloads.RefreshDiagnostics(); - SetCompilationProgress(1f, "No scripting changes detected.", pending.operationId); + SetCompilationProgress(1f, "No scripting changes detected.", pending.operationID); return false; } - SetCompilationProgress(C_STAGING_PROGRESS, "Staging script reload candidates...", pending.operationId); + SetCompilationProgress(C_STAGING_PROGRESS, "Staging script reload candidates...", pending.operationID); using AssemblyReloadSession reload = m_modules.BeginReload( plan.requests.Select(m_moduleSourceFactory).ToArray(), - plan.removedModuleNames); - SetCompilationProgress(C_MIGRATION_PROGRESS, "Restoring active editor state...", pending.operationId); + plan.removedModuleNames + ); + SetCompilationProgress(C_MIGRATION_PROGRESS, "Restoring active editor state...", pending.operationID); IAssemblyUnloadProbe unload = PublishGeneration(reload); m_modules.generations.TrackRetirement(unload); - m_retiringProgressOperation = pending.operationId; + m_retiringProgressOperation = pending.operationID; m_activeCompilationDirectory = pending.unavailability is null - ? pending.compilation.outputDirectory - : null; - _ = m_compiler.CollectArtifacts(m_activeCompilationDirectory is null - ? Array.Empty() - : [m_activeCompilationDirectory]); + ? pending.compilation.outputDirectory + : null; + _ = m_compiler.CollectArtifacts(m_activeCompilationDirectory is null ? [] : [m_activeCompilationDirectory]); RefreshModuleHandles(); UpdateActiveFingerprints(plan); string completedStatus = pending.unavailability is null - ? "Script reload completed." - : "Plugin availability change committed. Unavailable scene types are preserved as Missing until their " + - "Stable IDs return."; + ? "Script reload completed." + : "Plugin availability change committed. Unavailable scene types are preserved as Missing until their " + + "Stable IDs return."; SetCompilationProgress( !isUnloadVerificationPending ? 1f : C_UNLOAD_VERIFICATION_PROGRESS, !isUnloadVerificationPending - ? completedStatus - : completedStatus + " Verifying retired assembly unload...", pending.operationId); + ? completedStatus + : completedStatus + " Verifying retired assembly unload...", + pending.operationID + ); m_reloads.RefreshDiagnostics(); CompletePendingReload(pending); return true; @@ -601,7 +527,9 @@ public void Dispose() { Exception? previousFailure = m_disposalCompleted.Task.GetAwaiter().GetResult(); if (previousFailure is not null) + { ExceptionDispatchInfo.Capture(previousFailure).Throw(); + } return; } Exception? disposalFailure = null; @@ -614,10 +542,10 @@ public void Dispose() { if (m_assets.isInitialized) { - m_assets.Changed -= OnAssetDatabaseChanged; - m_assets.SourceMountsChanged -= OnSourceMountsChanged; + m_assets.changed -= OnAssetDatabaseChanged; + m_assets.sourceMountsChanged -= OnSourceMountsChanged; } - m_plugins.ActivationCandidateChanged -= OnPluginActivationCandidateChanged; + m_plugins.activationCandidateChanged -= OnPluginActivationCandidateChanged; lock (m_sync) { m_requestedReload = ScriptReloadRequest.None; @@ -635,12 +563,16 @@ public void Dispose() .. m_pluginModules.Values ]; if (modules.Length > 0) + { _ = m_modules.Unload(modules); + } m_pluginModules.Clear(); m_runtimeScriptModule = null; m_editorScriptModule = null; if (modules.Length > 0 && m_assets.isInitialized) + { m_assets.Rescan(); + } } m_activeCompilationDirectory = null; m_activeCompilation = null; @@ -677,14 +609,21 @@ public bool AdvanceUnloadVerification(out Exception? failure) failure = m_modules.generations.failure; if (failure is not null) { - SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload."); + SetCompilationProgress( + progress.fraction, + "Generation retirement failed. Restart the host before Play, Build, Export or reload." + ); return true; } try { if (!m_modules.generations.Advance()) { - SetCompilationProgress(C_UNLOAD_VERIFICATION_PROGRESS, "Verifying retired generation unload...", m_retiringProgressOperation); + SetCompilationProgress( + C_UNLOAD_VERIFICATION_PROGRESS, + "Verifying retired generation unload...", + m_retiringProgressOperation + ); return false; } SetCompilationProgress(1f, "Generation publication and retired assembly unload completed.", m_retiringProgressOperation); @@ -693,25 +632,154 @@ public bool AdvanceUnloadVerification(out Exception? failure) catch (Exception exception) { failure = exception; - SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload."); + SetCompilationProgress( + progress.fraction, + "Generation retirement failed. Restart the host before Play, Build, Export or reload." + ); return true; } } + private async ValueTask CompileAsync( + ScriptReloadRequest request, + PluginUnavailabilityPlan? unavailability, + long operation, + CancellationToken cancellationToken = default + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + using CancellationTokenSource linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + m_lifetimeToken + ); + CancellationToken effectiveCancellation = linkedCancellation.Token; + await m_compileGate.WaitAsync(effectiveCancellation).ConfigureAwait(false); + try + { + effectiveCancellation.ThrowIfCancellationRequested(); + ObjectDisposedException.ThrowIf(m_disposed, this); + Volatile.Write(ref m_isCompiling, 1); + Volatile.Write(ref m_compilationStartedTimestamp, Environment.TickCount64); + lock (m_sync) + { + m_activeCompilationCancellation = linkedCancellation; + m_activeProgressOperation = operation; + m_acceptCompilerProgress = true; + } + SetCompilationProgress(0f, "Preparing script compilation...", operation, canCancel: true); + ScriptCompilationResult result; + try + { + result = await m_compiler + .CompileAuthoringGenerationAsync( + new ScriptProgressObserver(( + progress, + status + ) => SetCompilationProgress( + progress * C_COMPILATION_PROGRESS_SHARE, + progress >= 1f ? "Compilation finished; waiting for generation activation and state recovery." : status, + operation, + isCompilerUpdate: true + )), + cancellationToken: effectiveCancellation + ) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (effectiveCancellation.IsCancellationRequested) + { + throw; + } + catch (Exception exception) + { + result = ScriptCompilationResult.Failure( + new ScriptDiagnostic( + "INNO0001", + DiagnosticSeverity.Error, + exception.ToString(), + filePath: null, + line: 0, + column: 0 + ) + ); + } + lock (m_sync) + { + if (!m_disposed) + { + m_acceptCompilerProgress = false; + m_lastCompilation = result; + if (m_requestedReload != ScriptReloadRequest.None) + { + if (request > m_requestedReload) + { + m_requestedReload = request; + } + m_pendingCompilation = null; + } + else if (result.success || unavailability is not null) + { + m_pendingCompilation = new PendingReload( + result, + request, + operation, + result.success ? null : unavailability + ); + } + SetCompilationProgress( + result.success || unavailability is not null ? C_COMPILATION_PROGRESS_SHARE : progress.fraction, + m_requestedReload != ScriptReloadRequest.None + ? "Compilation superseded by a queued reload request." + : result.success + ? "Script compilation completed; waiting for generation activation and state recovery." + : unavailability is not null + ? "Compilation failed after a Plugin availability change; the unavailable " + + "generation is ready to activate." + : "Script compilation failed.", + operation + ); + } + } + return result; + } + finally + { + long started = Interlocked.Exchange(ref m_compilationStartedTimestamp, 0); + if (started != 0) + { + m_lastCompilationElapsed = TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)); + } + lock (m_sync) + { + if (ReferenceEquals(m_activeCompilationCancellation, linkedCancellation)) + { + m_activeCompilationCancellation = null; + m_acceptCompilerProgress = false; + } + } + Volatile.Write(ref m_isCompiling, 0); + m_compileGate.Release(); + } + } + private void OnAssetDatabaseChanged(AssetChangeSet changeSet) { if (m_disposed || !m_options.autoCompile) + { return; + } for (int i = 0; i < changeSet.changes.Count; i++) { AssetChange change = changeSet.changes[i]; string path = change.assetPath.ToString(); string previousPath = change.previousAssetPath?.ToString() ?? string.Empty; if (!IsScriptInput(path) && !IsScriptInput(previousPath)) + { continue; - QueueReload(IsPluginInput(path) || IsPluginInput(previousPath) + } + QueueReload( + IsPluginInput(path) || IsPluginInput(previousPath) ? ScriptReloadRequest.ReloadPlugins - : ScriptReloadRequest.Recompile); + : ScriptReloadRequest.Recompile + ); return; } } @@ -719,9 +787,13 @@ private void OnAssetDatabaseChanged(AssetChangeSet changeSet) private void OnSourceMountsChanged() { if (m_disposed || !m_options.autoCompile || m_publishingGeneration) + { return; + } if (m_plugins.hasPendingActivation) + { return; + } QueueReload(ScriptReloadRequest.ReloadPlugins); } @@ -743,14 +815,16 @@ private IAssemblyUnloadProbe PublishGeneration(AssemblyReloadSession reload) private void OnPluginActivationCandidateChanged() { if (m_disposed || !m_options.autoCompile) + { return; + } QueueReload(ScriptReloadRequest.ReloadPlugins); } private void SetCompilationProgress( float fraction, string stage, - long? operationId = null, + long? operationID = null, bool cancellationRequested = false, bool isCompilerUpdate = false, bool canCancel = false @@ -758,14 +832,25 @@ private void SetCompilationProgress( lock (m_sync) { ScriptReloadProgress current = m_progress; - if (m_disposed || (operationId is long expected && expected != current.operationId)) + if (m_disposed || (operationID is long expected && expected != current.operationID)) + { return; + } if (isCompilerUpdate && (!m_acceptCompilerProgress || current.cancellationRequested)) + { return; - Volatile.Write(ref m_progress, new ScriptReloadProgress(current.operationId, - Math.Clamp(fraction, 0f, 1f), stage, current.cancellationRequested || cancellationRequested, - m_activeCompilationCancellation is not null && m_activeProgressOperation == current.operationId && - (canCancel || isCompilerUpdate) && !current.cancellationRequested && !cancellationRequested)); + } + Volatile.Write( + ref m_progress, + new ScriptReloadProgress( + current.operationID, + Math.Clamp(fraction, 0f, 1f), + stage, + current.cancellationRequested || cancellationRequested, + m_activeCompilationCancellation is not null && m_activeProgressOperation == current.operationID + && (canCancel || isCompilerUpdate) && !current.cancellationRequested && !cancellationRequested + ) + ); } } @@ -776,14 +861,24 @@ private void QueueReload(ScriptReloadRequest request) { ThrowIfFaultedLocked(); if (request > m_requestedReload) + { m_requestedReload = request; + } m_lastCompileRequestTimestamp = Environment.TickCount64; - Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f, m_requestedReload switch - { - ScriptReloadRequest.ReloadPlugins => "Plugin and scripting reload queued.", - ScriptReloadRequest.ReloadScripting => "Full scripting reload queued.", - _ => "Scripting recompile queued." - }, false)); + Volatile.Write( + ref m_progress, + new ScriptReloadProgress( + ++m_progressOperation, + 0f, + m_requestedReload switch + { + ScriptReloadRequest.ReloadPlugins => "Plugin and scripting reload queued.", + ScriptReloadRequest.ReloadScripting => "Full scripting reload queued.", + _ => "Scripting recompile queued." + }, + false + ) + ); } } @@ -791,9 +886,7 @@ private ReloadPlan SelectReloadPlan(PendingReload pending) { if (pending.unavailability is not null) { - return new ReloadPlan( - Array.Empty(), - pending.unavailability.removedModuleNames); + return new ReloadPlan([], pending.unavailability.removedModuleNames); } IReadOnlyList requests = pending.compilation.moduleDeployments; @@ -802,118 +895,110 @@ private ReloadPlan SelectReloadPlan(PendingReload pending) .Select(static request => request.moduleName) .ToArray(); string[] removedPlugins = pending.request == ScriptReloadRequest.ReloadPlugins - ? m_pluginModules.Keys.Except(candidatePlugins, StringComparer.Ordinal).ToArray() - : []; - if (m_runtimeScriptModule is null || m_editorScriptModule is null || - candidatePlugins.Any(plugin => !m_pluginModules.ContainsKey(plugin))) - { + ? m_pluginModules.Keys.Except(candidatePlugins, StringComparer.Ordinal).ToArray() + : []; + if (m_runtimeScriptModule is null || m_editorScriptModule is null + || candidatePlugins.Any(plugin => !m_pluginModules.ContainsKey(plugin)) + ) { return new ReloadPlan(requests, removedPlugins); } if (pending.request == ScriptReloadRequest.ReloadPlugins) + { return new ReloadPlan(requests, removedPlugins); + } if (pending.request == ScriptReloadRequest.ReloadScripting) { return new ReloadPlan( requests.Where(static request => request.domain == AssemblyDomain.InnoScripting).ToArray(), - []); + [] + ); } if (string.Equals( - pending.compilation.outputDirectory, - m_activeCompilationDirectory, - StringComparison.OrdinalIgnoreCase)) - { + pending.compilation.outputDirectory, + m_activeCompilationDirectory, + StringComparison.OrdinalIgnoreCase + )) { return new ReloadPlan([], []); } - var compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase); - var selected = requests - .Where(request => GetOwnedAssemblyNames(request).Any(compiled.Contains) || - !m_activeModuleFingerprints.TryGetValue( - request.moduleName, - out string? activeFingerprint) || - !string.Equals( - ComputeRequestFingerprint(request), - activeFingerprint, - StringComparison.Ordinal)) + HashSet compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase); + HashSet selected = requests + .Where(request => ( + GetOwnedAssemblyNames(request).Any(compiled.Contains) + || !m_activeModuleFingerprints.TryGetValue(request.moduleName, out string? activeFingerprint) + || !string.Equals(ComputeRequestFingerprint(request), activeFingerprint, StringComparison.Ordinal) + )) .Select(static request => request.moduleName) .ToHashSet(StringComparer.Ordinal); - if (selected.Any(name => requests.Any(request => - request.domain == AssemblyDomain.InnoPlugin && - string.Equals(request.moduleName, name, StringComparison.Ordinal)))) - { + if (selected.Any(name => requests.Any(request => ( + request.domain == AssemblyDomain.InnoPlugin + && string.Equals(request.moduleName, name, StringComparison.Ordinal) + ))) + ) { bool changed; do { changed = false; - foreach (ScriptModuleDeployment request in requests.Where(static request => - request.domain == AssemblyDomain.InnoPlugin)) - { + foreach (ScriptModuleDeployment request in requests.Where(static request => ( + request.domain == AssemblyDomain.InnoPlugin + )) + ) { if (!selected.Contains(request.moduleName) && request.upstreamModuleNames.Any(selected.Contains)) + { changed |= selected.Add(request.moduleName); + } } } while (changed); - selected.UnionWith(requests - .Where(static request => request.domain == AssemblyDomain.InnoScripting) - .Select(static request => request.moduleName)); + selected.UnionWith( + requests + .Where(static request => request.domain == AssemblyDomain.InnoScripting) + .Select(static request => request.moduleName) + ); } // Closed generic editor extensions over project runtime types can create CLR loader // allocator dependencies in both directions even though assembly references are one-way. // Project scripts therefore retire as one authoring generation, preserving scene state // through the same candidate transaction used for runtime-source changes. - if (requests.Any(request => request.domain == AssemblyDomain.InnoScripting && - selected.Contains(request.moduleName))) - { - selected.UnionWith(requests - .Where(static request => request.domain == AssemblyDomain.InnoScripting) - .Select(static request => request.moduleName)); + if (requests.Any(request => ( + request.domain == AssemblyDomain.InnoScripting + && selected.Contains(request.moduleName) + )) + ) { + selected.UnionWith( + requests + .Where(static request => request.domain == AssemblyDomain.InnoScripting) + .Select(static request => request.moduleName) + ); } - return new ReloadPlan( - requests.Where(request => selected.Contains(request.moduleName)).ToArray(), - []); + return new ReloadPlan(requests.Where(request => selected.Contains(request.moduleName)).ToArray(), []); } private void RefreshModuleHandles() { IReadOnlyList modules = m_modules.modules; m_pluginModules.Clear(); - foreach (AssemblyModuleInfo module in modules.Where(static module => - module.domain == AssemblyDomain.InnoPlugin && - module.moduleName.StartsWith("Plugin.", StringComparison.Ordinal))) - { + foreach (AssemblyModuleInfo module in modules.Where(static module => ( + module.domain == AssemblyDomain.InnoPlugin + && module.moduleName.StartsWith("Plugin.", StringComparison.Ordinal) + )) + ) { m_pluginModules.Add(module.moduleName, module.handle); } - m_runtimeScriptModule = modules.SingleOrDefault(static module => - module.moduleName == "RuntimeScripts")?.handle; - m_editorScriptModule = modules.SingleOrDefault(static module => - module.moduleName == "EditorScripts")?.handle; + m_runtimeScriptModule = modules.SingleOrDefault(static module => module.moduleName == "RuntimeScripts")?.handle; + m_editorScriptModule = modules.SingleOrDefault(static module => module.moduleName == "EditorScripts")?.handle; } private void UpdateActiveFingerprints(ReloadPlan plan) { foreach (string removed in plan.removedModuleNames) + { m_activeModuleFingerprints.Remove(removed); + } foreach (ScriptModuleDeployment request in plan.requests) - m_activeModuleFingerprints[request.moduleName] = ComputeRequestFingerprint(request); - } - - private static IEnumerable GetOwnedAssemblyNames(ScriptModuleDeployment request) - => new[] { request.mainAssemblyPath } - .Concat(request.preloadAssemblyPaths) - .Select(static path => System.Reflection.AssemblyName.GetAssemblyName(path).Name ?? string.Empty); - - private static string ComputeRequestFingerprint(ScriptModuleDeployment request) - { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - foreach (string path in new[] { request.mainAssemblyPath } - .Concat(request.preloadAssemblyPaths) - .OrderBy(static value => value, StringComparer.OrdinalIgnoreCase)) { - byte[] name = System.Text.Encoding.UTF8.GetBytes(System.IO.Path.GetFileName(path)); - hash.AppendData(name); - hash.AppendData(System.IO.File.ReadAllBytes(path)); + m_activeModuleFingerprints[request.moduleName] = ComputeRequestFingerprint(request); } - return Convert.ToHexString(hash.GetHashAndReset()); } private void CompletePendingReload(PendingReload applied) @@ -921,38 +1006,42 @@ private void CompletePendingReload(PendingReload applied) lock (m_sync) { m_activeCompilation = applied.unavailability is null - ? applied.compilation - : null; + ? applied.compilation + : null; if (ReferenceEquals(m_pendingCompilation, applied)) + { m_pendingCompilation = null; + } } } private PluginUnavailabilityPlan? CapturePluginUnavailabilityPlan() { if (!m_plugins.hasPendingActivation || m_pluginModules.Count == 0) + { return null; + } Dictionary candidatePluginHashes = m_plugins.compilationPlugins .Where(static plugin => plugin.containsCode) .ToDictionary( static plugin => plugin.manifest.pluginId, static plugin => plugin.contentHash, - StringComparer.Ordinal); - var removedModuleNames = m_plugins.activePlugins + StringComparer.Ordinal + ); + HashSet removedModuleNames = m_plugins.activePlugins .Where(static plugin => plugin.containsCode) - .Where(plugin => !candidatePluginHashes.TryGetValue( - plugin.manifest.pluginId, - out string? candidateHash) || - !string.Equals( - plugin.contentHash, - candidateHash, - StringComparison.Ordinal)) + .Where(plugin => ( + !candidatePluginHashes.TryGetValue(plugin.manifest.pluginId, out string? candidateHash) + || !string.Equals(plugin.contentHash, candidateHash, StringComparison.Ordinal) + )) .Select(static plugin => "Plugin." + plugin.manifest.pluginId) .Where(m_pluginModules.ContainsKey) .ToHashSet(StringComparer.Ordinal); if (removedModuleNames.Count == 0) + { return null; + } AssemblyModuleInfo[] activeModules = m_modules.modules.ToArray(); bool changed; @@ -961,9 +1050,9 @@ private void CompletePendingReload(PendingReload applied) changed = false; foreach (AssemblyModuleInfo module in activeModules) { - if (removedModuleNames.Contains(module.moduleName) || - !module.upstreamModuleNames.Any(removedModuleNames.Contains)) - { + if (removedModuleNames.Contains(module.moduleName) + || !module.upstreamModuleNames.Any(removedModuleNames.Contains) + ) { continue; } changed |= removedModuleNames.Add(module.moduleName); @@ -974,20 +1063,50 @@ private void CompletePendingReload(PendingReload applied) return new PluginUnavailabilityPlan( removedModuleNames .OrderBy(static moduleName => moduleName, StringComparer.Ordinal) - .ToArray()); + .ToArray() + ); + } + + private void ThrowIfFaultedLocked() + { + if (m_modules.generations.state == GenerationState.Faulted) + { + throw new InvalidOperationException("The generation owner is Faulted; restart the host.", m_modules.generations.failure); + } + } + + private static IEnumerable GetOwnedAssemblyNames(ScriptModuleDeployment request) + => new[] { request.mainAssemblyPath } + .Concat(request.preloadAssemblyPaths) + .Select(static path => AssemblyName.GetAssemblyName(path).Name ?? string.Empty); + + private static string ComputeRequestFingerprint(ScriptModuleDeployment request) + { + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + foreach (string path in new[] { request.mainAssemblyPath } + .Concat(request.preloadAssemblyPaths) + .OrderBy(static value => value, StringComparer.OrdinalIgnoreCase) + ) { + byte[] name = Encoding.UTF8.GetBytes(Path.GetFileName(path)); + hash.AppendData(name); + hash.AppendData(File.ReadAllBytes(path)); + } + return Convert.ToHexString(hash.GetHashAndReset()); } private static bool IsScriptInput(string path) - => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || - path.EndsWith(".iasmdef", StringComparison.OrdinalIgnoreCase); + => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + || path.EndsWith(".iasmdef", StringComparison.OrdinalIgnoreCase); private static bool IsPluginInput(string path) { if (string.IsNullOrWhiteSpace(path) || !IsScriptInput(path)) + { return false; + } try { - return AssetPath.Parse(path).source != AssetSourceId.project; + return AssetPath.Parse(path).source != AssetSourceID.project; } catch (ArgumentException) { @@ -995,16 +1114,10 @@ private static bool IsPluginInput(string path) } } - private void ThrowIfFaultedLocked() - { - if (m_modules.generations.state == GenerationState.Faulted) - throw new InvalidOperationException("The generation owner is Faulted; restart the host.", m_modules.generations.failure); - } - private sealed record PendingReload( ScriptCompilationResult compilation, ScriptReloadRequest request, - long operationId, + long operationID, PluginUnavailabilityPlan? unavailability = null ); @@ -1015,8 +1128,7 @@ private sealed record ReloadPlan( IReadOnlyList removedModuleNames ); - private sealed class ScriptProgressObserver(Action report) - : IProgress + private sealed class ScriptProgressObserver(Action report) : IProgress { /// /// Publishes one progress update to the receiving workflow. diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs index 8cccdbcef..de6204898 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs @@ -1,4 +1,5 @@ using System; + namespace Inno.Scripting.Reload; /// diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadProgress.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadProgress.cs index 1386ba8dd..f414543b5 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadProgress.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadProgress.cs @@ -3,7 +3,7 @@ namespace Inno.Scripting.Reload; /// /// Atomically published progress owned by one reload request, containing no runtime or extension objects. /// -/// +/// /// The host-local reload request sequence; zero precedes the first request. /// /// @@ -19,7 +19,7 @@ namespace Inno.Scripting.Reload; /// Whether this exact operation currently admits cancellation. /// public sealed record ScriptReloadProgress( - long operationId, + long operationID, float fraction, string stage, bool cancellationRequested, diff --git a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs index 31c9592c7..dddf87640 100644 --- a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs +++ b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs @@ -50,14 +50,17 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", AudioClipMetadataCodec.Encode(metadata), - cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("audio-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); + await output.WriteArtifactAsync("audio-data", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) { if (bytes.Length < 12 || !bytes[..4].SequenceEqual("RIFF"u8) || !bytes[8..12].SequenceEqual("WAVE"u8)) + { throw new InvalidDataException("The WAV source has an invalid RIFF header."); + } int channels = 0; int sampleRate = 0; @@ -66,28 +69,36 @@ private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) int offset = 12; while (offset <= bytes.Length - 8) { - ReadOnlySpan chunkId = bytes.Slice(offset, 4); + ReadOnlySpan chunkID = bytes.Slice(offset, 4); uint chunkLengthValue = BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(offset + 4, 4)); if (chunkLengthValue > int.MaxValue) + { throw new InvalidDataException("The WAV source contains an oversized chunk."); + } int chunkLength = (int)chunkLengthValue; int chunkStart = checked(offset + 8); int chunkEnd = checked(chunkStart + chunkLength); if (chunkEnd > bytes.Length) + { throw new InvalidDataException("The WAV source contains a truncated chunk."); + } - if (chunkId.SequenceEqual("fmt "u8)) + if (chunkID.SequenceEqual("fmt "u8)) { if (chunkLength < 16) + { throw new InvalidDataException("The WAV format chunk is truncated."); + } ushort format = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart, 2)); - if (format is not 1 and not 3 and not 0xfffe) + if (format is not 1 and not 3 and not 0xFFFE) + { throw new InvalidDataException($"The WAV format code '{format}' is not supported."); + } channels = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart + 2, 2)); sampleRate = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(chunkStart + 4, 4))); blockAlignment = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart + 12, 2)); } - else if (chunkId.SequenceEqual("data"u8)) + else if (chunkID.SequenceEqual("data"u8)) { dataLength = chunkLength; } @@ -96,19 +107,18 @@ private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) } if (channels <= 0 || sampleRate <= 0 || blockAlignment <= 0 || dataLength < 0) + { throw new InvalidDataException("The WAV source is missing valid format or data chunks."); - return new AudioClipMetadata( - AudioCodecId.wav, - channels, - sampleRate, - dataLength / blockAlignment, - bytes.Length); + } + return new AudioClipMetadata(AudioCodecID.wav, channels, sampleRate, dataLength / blockAlignment, bytes.Length); } private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) { if (bytes.Length < 42 || !bytes[..4].SequenceEqual("fLaC"u8)) + { throw new InvalidDataException("The FLAC source has an invalid stream marker."); + } int offset = 4; bool foundStreamInfo = false; int channels = 0; @@ -117,35 +127,43 @@ private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) while (offset <= bytes.Length - 4) { byte header = bytes[offset]; - int blockType = header & 0x7f; + int blockType = header & 0x7F; int length = (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; int dataStart = checked(offset + 4); int dataEnd = checked(dataStart + length); if (dataEnd > bytes.Length) + { throw new InvalidDataException("The FLAC source contains a truncated metadata block."); + } if (blockType == 0) { if (foundStreamInfo || length != 34) + { throw new InvalidDataException("The FLAC STREAMINFO block is invalid."); + } ReadOnlySpan packed = bytes.Slice(dataStart + 10, 8); ulong value = BinaryPrimitives.ReadUInt64BigEndian(packed); - sampleRate = (int)((value >> 44) & 0xfffff); + sampleRate = (int)((value >> 44) & 0xF_FFFF); channels = (int)((value >> 41) & 0x7) + 1; - frameCount = (long)(value & 0xfffffffffUL); + frameCount = (long)(value & 0xF_FFFF_FFFFUL); foundStreamInfo = true; } offset = dataEnd; if ((header & 0x80) != 0) + { break; + } } if (!foundStreamInfo || channels <= 0 || sampleRate <= 0 || frameCount <= 0) + { throw new InvalidDataException("The FLAC source is missing valid STREAMINFO metadata."); - return new AudioClipMetadata(AudioCodecId.flac, channels, sampleRate, frameCount, bytes.Length); + } + return new AudioClipMetadata(AudioCodecID.flac, channels, sampleRate, frameCount, bytes.Length); } private static AudioClipMetadata ReadMp3(ReadOnlySpan bytes) { - int offset = SkipId3(bytes); + int offset = SkipID3(bytes); int channels = 0; int sampleRate = 0; long frameCount = 0; @@ -163,7 +181,9 @@ private static AudioClipMetadata ReadMp3(ReadOnlySpan bytes) break; } if (offset + frameLength > bytes.Length) + { throw new InvalidDataException("The MP3 source contains a truncated audio frame."); + } sampleRate = frameSampleRate; channels = frameChannels; frameCount += samples; @@ -171,23 +191,31 @@ private static AudioClipMetadata ReadMp3(ReadOnlySpan bytes) offset += frameLength; } if (encodedFrameCount == 0) + { throw new InvalidDataException("The MP3 source contains no valid Layer III frame."); - return new AudioClipMetadata(AudioCodecId.mp3, channels, sampleRate, frameCount, bytes.Length); + } + return new AudioClipMetadata(AudioCodecID.mp3, channels, sampleRate, frameCount, bytes.Length); } - private static int SkipId3(ReadOnlySpan bytes) + private static int SkipID3(ReadOnlySpan bytes) { if (bytes.Length < 10 || !bytes[..3].SequenceEqual("ID3"u8)) + { return 0; + } for (int index = 6; index < 10; index++) { if ((bytes[index] & 0x80) != 0) + { throw new InvalidDataException("The MP3 ID3 size is invalid."); + } } int size = (bytes[6] << 21) | (bytes[7] << 14) | (bytes[8] << 7) | bytes[9]; int offset = checked(10 + size); if (offset > bytes.Length) + { throw new InvalidDataException("The MP3 ID3 tag is truncated."); + } return offset; } @@ -202,27 +230,35 @@ out int channels sampleRate = 0; samples = 0; channels = 0; - if ((header & 0xffe00000) != 0xffe00000) + if ((header & 0xFFE0_0000) != 0xFFE0_0000) + { return false; + } int mpegBits = (int)((header >> 19) & 0x3); int layerBits = (int)((header >> 17) & 0x3); - int bitrateIndex = (int)((header >> 12) & 0xf); + int bitrateIndex = (int)((header >> 12) & 0xF); int sampleRateIndex = (int)((header >> 10) & 0x3); if (mpegBits == 1 || layerBits != 1 || bitrateIndex is 0 or 15 || sampleRateIndex == 3) + { return false; + } - int[] sampleRates = [44100, 48000, 32000]; + int[] sampleRates = [44_100, 48_000, 32_000]; sampleRate = sampleRates[sampleRateIndex]; bool mpegOne = mpegBits == 3; if (mpegBits == 2) + { sampleRate /= 2; + } else if (mpegBits == 0) + { sampleRate /= 4; + } int[] mpegOneBitrates = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]; int[] lowerBitrates = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; int bitrate = (mpegOne ? mpegOneBitrates : lowerBitrates)[bitrateIndex]; int padding = (int)((header >> 9) & 1); - frameLength = ((mpegOne ? 144000 : 72000) * bitrate / sampleRate) + padding; + frameLength = ((mpegOne ? 144_000 : 72_000) * bitrate / sampleRate) + padding; samples = mpegOne ? 1152 : 576; channels = ((header >> 6) & 0x3) == 3 ? 1 : 2; return frameLength > 4; diff --git a/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs b/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs index eb747907f..0008e9848 100644 --- a/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs +++ b/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs @@ -5,12 +5,12 @@ namespace Inno.Audio.Runtime; internal sealed class ArtifactAudioClipSource(ArtifactLease artifact) : IAudioClipSource { - /// + /// public string contentHash => artifact.info.contentHash; - /// + /// public long length => artifact.info.length; - /// + /// public Stream OpenRead() => artifact.OpenRead(); } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs b/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs index 8db5397f3..c15eb3bd7 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs @@ -30,6 +30,41 @@ Action retireResources m_retireResources = retireResources; } + /// + /// Cancels waiters and releases every native clip and immutable artifact owned by this device cache. + /// + public void Dispose() + { + foreach (PendingPreload preload in m_preloads) + { + preload.completion.TrySetCanceled(); + } + m_preloads.Clear(); + foreach (ClipCacheEntry clip in m_clips.Values.ToArray()) + { + try + { + clip.Dispose(); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception exception) + { + m_retirementFailures.Add(exception); + } + m_clips.Remove(clip.key); + } + m_clips.Clear(); + if (m_retirementFailures.Count > 0) + { + Exception[] failures = m_retirementFailures.ToArray(); + m_retirementFailures.Clear(); + throw new AggregateException("Audio cache retirement failed after every clip and artifact was attempted.", failures); + } + } + internal int count => m_clips.Count; internal long decodedBytes => m_clips.Values.Sum(static clip => clip.decodedByteLength); @@ -41,14 +76,18 @@ internal ValueTask PreloadAsync( ArgumentNullException.ThrowIfNull(clip); cancellationToken.ThrowIfCancellationRequested(); if (!Enum.IsDefined(loadMode)) + { throw new ArgumentOutOfRangeException(nameof(loadMode)); + } if (m_preloads.Count >= m_options.maxPendingPreloads) + { throw new InvalidOperationException("Audio preload waiters are at capacity; retry after an update safety point."); + } var request = new AudioClipRequest(clip, m_artifacts); Exception? preparationFailure = null; try { - return PreparePreload(request, loadMode, cancellationToken); + return PreparePreloadAsync(request, loadMode, cancellationToken); } catch (Exception exception) { @@ -67,80 +106,105 @@ internal ValueTask PreloadAsync( } catch (Exception cleanup) when (preparationFailure is not null) { - throw new AggregateException("Audio preload preparation and request retirement failed.", - preparationFailure, cleanup); + throw new AggregateException( + "Audio preload preparation and request retirement failed.", + preparationFailure, + cleanup + ); } } } + internal void ReleasePreload(AudioClipAsset clip) { ArgumentNullException.ThrowIfNull(clip); - ClipCacheEntry? retiring = m_clips.Values.FirstOrDefault(entry => - entry.key.persistentId == clip.identity.persistentId && entry.isRetiring); + ClipCacheEntry? retiring = m_clips.Values.FirstOrDefault(entry => ( + entry.key.persistentID == clip.identity.persistentID && entry.isRetiring + )); if (retiring is not null) { TryReleaseClip(retiring); return; } ClipCacheEntry? entry = m_clips - .Where(pair => pair.Key.persistentId == clip.identity.persistentId && - pair.Value.preloadReferences > pair.Value.pendingPreloadReferences) + .Where(pair => ( + pair.Key.persistentID == clip.identity.persistentID + && pair.Value.preloadReferences > pair.Value.pendingPreloadReferences + )) .Select(static pair => pair.Value) .FirstOrDefault(); if (entry is null) + { return; + } entry.preloadReferences--; TryReleaseClip(entry); } + internal ClipCacheEntry GetOrCreateClip( AudioClipRequest clip, AudioClipLoadMode requestedMode ) { AudioClipMetadata metadata = clip.metadata - ?? throw new InvalidOperationException("The audio clip has no imported runtime metadata."); + ?? throw new InvalidOperationException("The audio clip has no imported runtime metadata."); AssetArtifactInfo artifact = clip.artifact; AudioClipLoadMode resolvedMode = requestedMode == AudioClipLoadMode.Automatic - ? (artifact.length >= m_options.automaticStreamingThresholdBytes || - WouldExceedDecodedBudget(EstimateDecodedByteLength(metadata, artifact.length)) - ? AudioClipLoadMode.Stream - : AudioClipLoadMode.Decode) - : requestedMode; - var key = new ClipCacheKey(clip.persistentId, clip.contentVersion, artifact.key, resolvedMode); + ? (artifact.length >= m_options.automaticStreamingThresholdBytes + || WouldExceedDecodedBudget(EstimateDecodedByteLength(metadata, artifact.length)) + ? AudioClipLoadMode.Stream + : AudioClipLoadMode.Decode) + : requestedMode; + var key = new ClipCacheKey(clip.persistentID, clip.contentVersion, artifact.key, resolvedMode); if (m_clips.TryGetValue(key, out ClipCacheEntry? cached)) { if (!cached.isRetiring) + { return cached; + } TryReleaseClip(cached); } long decodedByteLength = resolvedMode == AudioClipLoadMode.Decode - ? EstimateDecodedByteLength(metadata, artifact.length) - : 0; + ? EstimateDecodedByteLength(metadata, artifact.length) + : 0; if (resolvedMode == AudioClipLoadMode.Decode && WouldExceedDecodedBudget(decodedByteLength)) { throw new InvalidOperationException( - $"Decoded audio clip '{clip.assetPath}' exceeds the configured cache budget."); + $"Decoded audio clip '{clip.assetPath}' exceeds the configured cache budget." + ); } - AudioClipHandle handle = m_device.CreateClip(new AudioClipDescriptor( - metadata.codec, - resolvedMode, - metadata.channels, - metadata.sampleRate, - metadata.frameCount, - artifact.length), clip.source); + AudioClipHandle handle = m_device.CreateClip( + new AudioClipDescriptor( + metadata.codec, + resolvedMode, + metadata.channels, + metadata.sampleRate, + metadata.frameCount, + artifact.length + ), + clip.source + ); if (!handle.isValid) + { throw new InvalidOperationException("The audio backend rejected clip creation."); + } var entry = new ClipCacheEntry(key, handle, decodedByteLength, clip.TakeArtifact(), m_device); m_clips.Add(key, entry); return entry; } + internal void TryReleaseClip(ClipCacheEntry entry) { if (entry.preloadReferences > 0 || entry.voiceReferences > 0) + { return; + } entry.Dispose(); if (m_clips.TryGetValue(entry.key, out ClipCacheEntry? current) && ReferenceEquals(current, entry)) + { m_clips.Remove(entry.key); + } } + internal void CompletePreloads() { for (int index = m_preloads.Count - 1; index >= 0; index--) @@ -151,12 +215,16 @@ internal void CompletePreloads() AudioClipState state = m_device.GetClipState(pending.clip.handle); pending.canceled = pending.cancellationToken.IsCancellationRequested; if (!pending.canceled && state == AudioClipState.Preparing) + { continue; + } pending.failed = state == AudioClipState.Failed; pending.completing = true; pending.clip.pendingPreloadReferences--; if (pending.canceled || pending.failed) + { pending.clip.preloadReferences--; + } } if (pending.canceled || pending.failed) { @@ -164,9 +232,13 @@ internal void CompletePreloads() { TryReleaseClip(pending.clip); if (pending.canceled) + { pending.completion.TrySetCanceled(pending.cancellationToken); + } else + { pending.completion.TrySetException(new InvalidOperationException("Native audio preparation failed.")); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -180,44 +252,15 @@ internal void CompletePreloads() } } else + { pending.completion.TrySetResult(); + } m_preloads.RemoveAt(index); } DrainRetiringClips(); } - /// - /// Cancels waiters and releases every native clip and immutable artifact owned by this device cache. - /// - public void Dispose() - { - foreach (PendingPreload preload in m_preloads) - preload.completion.TrySetCanceled(); - m_preloads.Clear(); - foreach (ClipCacheEntry clip in m_clips.Values.ToArray()) - { - try - { - clip.Dispose(); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception exception) - { - m_retirementFailures.Add(exception); - } - m_clips.Remove(clip.key); - } - m_clips.Clear(); - if (m_retirementFailures.Count > 0) - { - Exception[] failures = m_retirementFailures.ToArray(); - m_retirementFailures.Clear(); - throw new AggregateException("Audio cache retirement failed after every clip and artifact was attempted.", failures); - } - } - private ValueTask PreparePreload( + + private ValueTask PreparePreloadAsync( AudioClipRequest request, AudioClipLoadMode loadMode, CancellationToken cancellationToken @@ -228,7 +271,9 @@ CancellationToken cancellationToken { state = m_device.GetClipState(entry.handle); if (state == AudioClipState.Failed) + { throw new InvalidOperationException("Native audio clip preparation failed."); + } } catch (Exception failure) { @@ -248,24 +293,33 @@ CancellationToken cancellationToken } entry.preloadReferences++; if (state == AudioClipState.Ready) + { return ValueTask.CompletedTask; + } var pending = new PendingPreload(entry, cancellationToken); entry.pendingPreloadReferences++; m_preloads.Add(pending); return new ValueTask(pending.completion.Task); } + private void DrainRetiringClips() { foreach (ClipCacheEntry clip in m_clips.Values.Where(static clip => clip.isRetiring).ToArray()) + { TryReleaseClip(clip); + } } + private bool WouldExceedDecodedBudget(long additionalBytes) { if (additionalBytes > m_options.decodedCacheBudgetBytes) + { return true; + } long currentBytes = m_clips.Values.Sum(static clip => clip.decodedByteLength); return currentBytes > m_options.decodedCacheBudgetBytes - additionalBytes; } + private static long EstimateDecodedByteLength( AudioClipMetadata metadata, long encodedByteLength @@ -280,12 +334,14 @@ long encodedByteLength return long.MaxValue; } } + internal readonly record struct ClipCacheKey( - Guid persistentId, + Guid persistentID, long contentVersion, AssetArtifactKey artifactKey, AudioClipLoadMode loadMode ); + internal sealed class ClipCacheEntry : IDisposable { private readonly LifetimeScope m_lifetime = new(); @@ -321,6 +377,7 @@ public void Dispose() internal int pendingPreloadReferences { get; set; } internal int voiceReferences { get; set; } } + private sealed class NativeClipRetirement( IAudioDevice device, AudioClipHandle handle @@ -332,9 +389,12 @@ AudioClipHandle handle public void Dispose() { if (!device.DestroyClip(handle)) + { throw new InvalidOperationException("The audio backend refused clip retirement."); + } } } + private sealed class PendingPreload( ClipCacheEntry clip, CancellationToken cancellationToken diff --git a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs index 967a4474d..35212c54c 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs @@ -6,22 +6,24 @@ namespace Inno.Audio.Runtime; internal sealed class AudioClipRequest : IDisposable { - private ArtifactLease? m_artifact; private readonly string? m_failure; + private ArtifactLease? m_artifact; internal AudioClipRequest( AudioClipAsset clip, IAssetArtifactLookup artifacts ) { - persistentId = clip.identity.persistentId; - contentVersion = clip.contentVersion; - assetPath = clip.assetPath; - metadata = clip.metadata; + this.persistentID = clip.identity.persistentID; + this.contentVersion = clip.contentVersion; + this.assetPath = clip.assetPath; + this.metadata = clip.metadata; try { if (clip.isMissing || metadata is null) + { throw new InvalidOperationException("The audio clip or its imported metadata is missing."); - m_artifact = artifacts.AcquireArtifact(persistentId, "audio-data"); + } + m_artifact = artifacts.AcquireArtifact(persistentID, "audio-data"); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -33,15 +35,29 @@ IAssetArtifactLookup artifacts } } - internal Guid persistentId { get; } + /// + /// Releases an artifact that was not transferred into the native clip cache. + /// + public void Dispose() + { + m_artifact?.Dispose(); + m_artifact = null; + } + + internal Guid persistentID { get; } internal long contentVersion { get; } internal AssetPath assetPath { get; } internal AudioClipMetadata? metadata { get; } - internal AssetArtifactInfo artifact => m_artifact?.info - ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released."); - internal IAudioClipSource source => new ArtifactAudioClipSource(m_artifact - ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released.")); + internal AssetArtifactInfo artifact + => m_artifact?.info + ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released."); + + internal IAudioClipSource source + => new ArtifactAudioClipSource( + m_artifact + ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released.") + ); internal ArtifactLease TakeArtifact() { @@ -50,13 +66,4 @@ internal ArtifactLease TakeArtifact() m_artifact = null; return result; } - - /// - /// Releases an artifact that was not transferred into the native clip cache. - /// - public void Dispose() - { - m_artifact?.Dispose(); - m_artifact = null; - } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs index 1b7719328..67ab31f09 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs @@ -10,15 +10,15 @@ namespace Inno.Audio.Runtime; internal sealed class AudioContentOwner : IDisposable { private readonly Dictionary m_emitters = []; - private readonly HashSet m_providerDiagnosticIds = new(StringComparer.Ordinal); - private AudioListenerHandle m_listener; - private Guid m_listenerId; - private Guid m_listenerDiagnosticId; + private readonly HashSet m_providerDiagnosticIDs = new(StringComparer.Ordinal); private readonly IAudioDevice m_device; private readonly AudioVoiceOwner m_voices; private readonly IDiagnosticReporter m_diagnostics; private readonly Func? m_contentScopeProvider; private readonly int m_capacity; + private AudioListenerHandle m_listener; + private Guid m_listenerID; + private Guid m_listenerDiagnosticID; internal AudioContentOwner( IAudioDevice device, @@ -32,31 +32,37 @@ int capacity m_diagnostics = diagnostics; m_contentScopeProvider = contentScopeProvider; m_capacity = capacity; - statistics = new AudioContentStatistics(capacity, 0, 0); + this.statistics = new AudioContentStatistics(capacity, 0, 0); } - internal AudioContentStatistics statistics { get; private set; } - - internal void ClearEmitters() => m_emitters.Clear(); - /// /// Releases the listener and clears neutral synchronization state before the device can retire. /// public void Dispose() { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = default; - m_listenerId = Guid.Empty; + m_listenerID = Guid.Empty; m_emitters.Clear(); - foreach (string id in m_providerDiagnosticIds) + foreach (string id in m_providerDiagnosticIDs) + { m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", id); - m_providerDiagnosticIds.Clear(); - if (m_listenerDiagnosticId != Guid.Empty) - m_diagnostics.Resolve("AUDIO_LISTENER_PRIORITY_TIE", m_listenerDiagnosticId.ToString("D")); - m_listenerDiagnosticId = Guid.Empty; + } + m_providerDiagnosticIDs.Clear(); + if (m_listenerDiagnosticID != Guid.Empty) + { + m_diagnostics.Resolve("AUDIO_LISTENER_PRIORITY_TIE", m_listenerDiagnosticID.ToString("D")); + } + m_listenerDiagnosticID = Guid.Empty; } + internal AudioContentStatistics statistics { get; private set; } + + internal void ClearEmitters() => m_emitters.Clear(); + internal void Update( AudioExtensionRegistry.ProviderGeneration providers, float deltaTime @@ -77,19 +83,21 @@ float deltaTime "AUDIO_CONTENT_SCOPE_FAILED", $"The host audio content scope failed; an empty scope is used for this update: {exception.Message}", DiagnosticSeverity.Error, - "AudioRuntime"); + "AudioRuntime" + ); content = ContentReadScope.empty; } using ContentReadScope contentScope = content; - var emitters = new List(); - var listeners = new List(); + List emitters = []; + List listeners = []; var ids = new HashSet(); int rejectedProviders = 0; - foreach (string retiredId in m_providerDiagnosticIds - .Where(id => !providers.providers.Any(entry => entry.id == id)).ToArray()) - { - m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", retiredId); - m_providerDiagnosticIds.Remove(retiredId); + foreach (string retiredID in m_providerDiagnosticIDs + .Where(id => !providers.providers.Any(entry => entry.id == id)) + .ToArray() + ) { + m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", retiredID); + m_providerDiagnosticIDs.Remove(retiredID); } foreach (AudioExtensionRegistry.ProviderEntry entry in providers.providers) { @@ -99,9 +107,11 @@ float deltaTime entry.provider.Submit(context); IReadOnlyList contributionEmitters = context.emitters; IReadOnlyList contributionListeners = context.listeners; - if (contributionEmitters.Any(emitter => ids.Contains(emitter.id)) || - contributionListeners.Any(listener => ids.Contains(listener.id))) + if (contributionEmitters.Any(emitter => ids.Contains(emitter.id)) + || contributionListeners.Any(listener => ids.Contains(listener.id)) + ) { throw new ArgumentException("The contribution repeats an identity already accepted from another provider."); + } foreach (AudioEmitterSnapshot emitter in contributionEmitters) { ids.Add(emitter.id); @@ -113,7 +123,7 @@ float deltaTime listeners.Add(listener); } m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", entry.id); - m_providerDiagnosticIds.Remove(entry.id); + m_providerDiagnosticIDs.Remove(entry.id); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -122,12 +132,13 @@ float deltaTime catch (Exception exception) { rejectedProviders++; - m_providerDiagnosticIds.Add(entry.id); + m_providerDiagnosticIDs.Add(entry.id); Publish( "AUDIO_CONTENT_PROVIDER_FAILED", $"Audio content provider '{entry.id}' was isolated for this update: {exception.Message}", DiagnosticSeverity.Error, - entry.id); + entry.id + ); } } statistics = new AudioContentStatistics(m_capacity, ids.Count, rejectedProviders); @@ -144,20 +155,23 @@ private void SynchronizeEmitters(IReadOnlyList snapshots) if (!snapshot.shouldPlay) { if (m_emitters.Remove(snapshot.id, out EmitterRecord? inactive)) + { _ = m_voices.Stop(inactive.voice); + } continue; } if (m_emitters.TryGetValue(snapshot.id, out EmitterRecord? current)) { - if (current.clipId != snapshot.clip.identity.persistentId || - current.contentVersion != snapshot.clip.contentVersion || - current.playbackRevision != snapshot.playbackRevision) - { + if (current.clipID != snapshot.clip.identity.persistentID + || current.contentVersion != snapshot.clip.contentVersion + || current.playbackRevision != snapshot.playbackRevision + ) { _ = m_voices.Stop(current.voice); current = new EmitterRecord( snapshot.clip, snapshot.playbackRevision, - m_voices.Play(snapshot.clip, snapshot.options)); + m_voices.Play(snapshot.clip, snapshot.options) + ); m_emitters[snapshot.id] = current; } else @@ -168,13 +182,16 @@ private void SynchronizeEmitters(IReadOnlyList snapshots) snapshot.options.volume, snapshot.options.pitch, snapshot.options.pan, - snapshot.options.spatial)); + snapshot.options.spatial + ) + ); } continue; } m_emitters.Add( snapshot.id, - new EmitterRecord(snapshot.clip, snapshot.playbackRevision, m_voices.Play(snapshot.clip, snapshot.options))); + new EmitterRecord(snapshot.clip, snapshot.playbackRevision, m_voices.Play(snapshot.clip, snapshot.options)) + ); } foreach (Guid id in m_emitters.Keys.Where(id => !seen.Contains(id)).ToArray()) { @@ -185,10 +202,10 @@ private void SynchronizeEmitters(IReadOnlyList snapshots) private void SynchronizeListener(IReadOnlyList snapshots) { - if (m_listenerDiagnosticId != Guid.Empty) + if (m_listenerDiagnosticID != Guid.Empty) { - m_diagnostics.Resolve("AUDIO_LISTENER_PRIORITY_TIE", m_listenerDiagnosticId.ToString("D")); - m_listenerDiagnosticId = Guid.Empty; + m_diagnostics.Resolve("AUDIO_LISTENER_PRIORITY_TIE", m_listenerDiagnosticID.ToString("D")); + m_listenerDiagnosticID = Guid.Empty; } AudioListenerSnapshot[] active = snapshots .Where(static listener => listener.active) @@ -198,48 +215,52 @@ private void SynchronizeListener(IReadOnlyList snapshots) if (active.Length == 0) { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = default; - m_listenerId = Guid.Empty; + m_listenerID = Guid.Empty; return; } AudioListenerSnapshot selected = active[0]; if (active.Length > 1 && active[1].priority == selected.priority) { - m_listenerDiagnosticId = selected.id; + m_listenerDiagnosticID = selected.id; Publish( "AUDIO_LISTENER_PRIORITY_TIE", "Multiple active listeners share the highest priority; stable identity selected the winner.", DiagnosticSeverity.Warning, - selected.id.ToString("D")); + selected.id.ToString("D") + ); } - if (!m_listener.isValid || m_listenerId != selected.id) + if (!m_listener.isValid || m_listenerID != selected.id) { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = m_device.CreateListener(selected.state); - m_listenerId = selected.id; + m_listenerID = selected.id; return; } _ = m_device.SetListener(m_listener, selected.state); } + private void Publish( + string code, + string message, + DiagnosticSeverity severity, + string? source + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + private sealed class EmitterRecord( AudioClipAsset clip, ulong playbackRevision, AudioVoiceHandle voice ) { - internal Guid clipId { get; } = clip.identity.persistentId; + internal Guid clipID { get; } = clip.identity.persistentID; internal long contentVersion { get; } = clip.contentVersion; internal ulong playbackRevision { get; } = playbackRevision; internal AudioVoiceHandle voice { get; } = voice; } - - private void Publish( - string code, - string message, - DiagnosticSeverity severity, - string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs index b2179e401..8053bdc6f 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs @@ -10,14 +10,9 @@ internal sealed class AudioDeviceCandidate : IDisposable private IAudioDevice? m_device; private AudioMixerOwner? m_mixer; - internal AudioDeviceCandidate(IAudioDevice device) => m_device = device; - - internal AudioMixerOwner Prepare(AudioMixerOwner previous) => m_mixer = previous.PrepareReplacement(m_device!); - - internal void Commit() + internal AudioDeviceCandidate(IAudioDevice device) { - m_mixer = null; - m_device = null; + m_device = device; } /// @@ -52,9 +47,19 @@ public void Dispose() } m_device = null; if (m_failures.Count == 0) + { return; + } Exception[] failures = m_failures.ToArray(); m_failures.Clear(); throw new AggregateException("Audio candidate retirement failed after every owner was attempted.", failures); } + + internal AudioMixerOwner Prepare(AudioMixerOwner previous) => m_mixer = previous.PrepareReplacement(m_device!); + + internal void Commit() + { + m_mixer = null; + m_device = null; + } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs index f779b92da..78c6a2e59 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs @@ -12,37 +12,10 @@ internal sealed class AudioExtensionRegistry : TypeRegistry current; - internal void RetireBackend(Action retire) - { - try - { - RetireResource("audio device generation", retire); - } - catch (Exception exception) - { - Fault(exception); - throw; - } - } - - internal void Fault(Exception exception) - { - m_retirementFailure ??= exception; - ReportRetirementFailure(exception); - } - - internal void EnsureHealthy() - { - if (m_retirementFailure is not null) - throw new InvalidOperationException("The audio generation owner is Faulted and requires a host restart.", m_retirementFailure); - } - /// /// Revokes audio admission when candidate or active registry cleanup faults the shared generation. /// @@ -55,9 +28,7 @@ internal void EnsureHealthy() protected override void OnCleanupFailed( string phase, Exception exception - ) { - m_retirementFailure ??= exception; - } + ) => m_retirementFailure ??= exception; /// /// Builds a complete validated audio extension snapshot from one type generation. @@ -76,15 +47,42 @@ protected override Snapshot Build(TypeCacheSnapshot types) Discover(types, static value => value.id, "mixer"), Discover(types, static value => value.id, "mixer feature"), Discover(types, static value => value.id, "content provider"), - CreateExtension); + CreateExtension + ); + } + + internal void RetireBackend(Action retire) + { + try + { + RetireResource("audio device generation", retire); + } + catch (Exception exception) + { + Fault(exception); + throw; + } + } + + internal void Fault(Exception exception) + { + m_retirementFailure ??= exception; + ReportRetirementFailure(exception); + } + + internal void EnsureHealthy() + { + if (m_retirementFailure is not null) + { + throw new InvalidOperationException("The audio generation owner is Faulted and requires a host restart.", m_retirementFailure); + } } private static Dictionary Discover( TypeCacheSnapshot types, - Func getId, + Func getID, string kind - ) - where TAttribute : Attribute + ) where TAttribute : Attribute { var result = new Dictionary(StringComparer.Ordinal); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) @@ -93,18 +91,20 @@ string kind if (type.IsAbstract || !typeof(TContract).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Audio {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}."); + $"Audio {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException($"Audio {kind} '{type.FullName}' requires a parameterless constructor."); } TAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; - string id = getId(attribute); + string id = getID(attribute); if (!result.TryAdd(id, type)) { throw new InvalidOperationException( - $"Audio {kind} ID '{id}' is declared by both '{result[id].FullName}' and '{type.FullName}'."); + $"Audio {kind} ID '{id}' is declared by both '{result[id].FullName}' and '{type.FullName}'." + ); } } return result; @@ -112,10 +112,10 @@ string kind internal sealed class Snapshot : IDisposable { - private TypeCacheSnapshot? m_types; private readonly IReadOnlyDictionary m_features; private readonly IReadOnlyDictionary m_mixers; private readonly IReadOnlyDictionary m_providers; + private TypeCacheSnapshot? m_types; internal Snapshot( TypeCacheSnapshot types, @@ -125,17 +125,13 @@ internal Snapshot( Func createProvider ) { m_types = types; - typeCacheVersion = types.version; + this.typeCacheVersion = types.version; m_mixers = mixers; m_features = features; m_providers = providers; this.providers = CreateProviders(createProvider); } - internal long typeCacheVersion { get; } - - internal ProviderGeneration providers { get; } - /// /// Retires the provider instances with their owning type-catalog snapshot. /// @@ -145,25 +141,9 @@ public void Dispose() m_types = null; } - private ProviderGeneration CreateProviders(Func createProvider) - { - var entries = new List(m_providers.Count); - foreach ((string id, Type type) in m_providers) - { - AudioContentProviderExtensionAttribute attribute = - m_types!.GetAttribute(m_types.GetTypeRef(type), inherit: false)!; - entries.Add(new ProviderEntry(id, attribute.priority, createProvider(type))); - } - entries.Sort(static ( - left, - right - ) => - { - int priority = left.priority.CompareTo(right.priority); - return priority != 0 ? priority : string.CompareOrdinal(left.id, right.id); - }); - return new ProviderGeneration(typeCacheVersion, entries); - } + internal long typeCacheVersion { get; } + + internal ProviderGeneration providers { get; } internal bool TryBuildMixer( AudioMixerAsset asset, @@ -185,9 +165,13 @@ out AudioMixer? mixer foreach (AudioMixerFeatureConfiguration configuration in asset.features) { if (!configuration.enabled) + { continue; + } if (string.IsNullOrWhiteSpace(configuration.featureTypeId) || !configured.Add(configuration.featureTypeId)) + { throw new InvalidOperationException("Enabled audio mixer features require unique stable identifiers."); + } if (!m_features.TryGetValue(configuration.featureTypeId, out Type? featureType)) { mixer = null; @@ -199,7 +183,30 @@ out AudioMixer? mixer return true; } - private TContract Create(Type type) where TContract : class + private ProviderGeneration CreateProviders(Func createProvider) + { + var entries = new List(m_providers.Count); + foreach ((string id, Type type) in m_providers) + { + AudioContentProviderExtensionAttribute attribute = m_types!.GetAttribute( + m_types.GetTypeRef(type), + inherit: false + )!; + entries.Add(new ProviderEntry(id, attribute.priority, createProvider(type))); + } + entries.Sort(static ( + left, + right + ) => + { + int priority = left.priority.CompareTo(right.priority); + return priority != 0 ? priority : string.CompareOrdinal(left.id, right.id); + }); + return new ProviderGeneration(typeCacheVersion, entries); + } + + private TContract Create(Type type) + where TContract : class { try { @@ -214,8 +221,8 @@ private TContract Create(Type type) where TContract : class internal sealed class ProviderGeneration : IDisposable { - private bool m_disposed; private readonly LifetimeScope m_lifetime = new(); + private bool m_disposed; internal ProviderGeneration( long typeCacheVersion, @@ -224,20 +231,20 @@ IReadOnlyList providers this.typeCacheVersion = typeCacheVersion; this.providers = Array.AsReadOnly(providers.ToArray()); foreach (ProviderEntry entry in providers) + { m_lifetime.Own(entry.provider); + } } - internal long typeCacheVersion { get; } - - internal IReadOnlyList providers { get; private set; } - /// /// Releases every provider instance retained by this candidate generation. /// public void Dispose() { if (m_disposed) + { return; + } try { m_lifetime.Dispose(); @@ -248,13 +255,17 @@ public void Dispose() } catch { - providers = Array.Empty(); + providers = []; m_disposed = true; throw; } - providers = Array.Empty(); + providers = []; m_disposed = true; } + + internal long typeCacheVersion { get; } + + internal IReadOnlyList providers { get; private set; } } internal sealed record ProviderEntry( diff --git a/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs index 1f911d93c..7a89821b5 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs @@ -1,7 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Linq; +using Inno.Core.Execution; namespace Inno.Audio.Runtime; @@ -11,9 +11,9 @@ internal sealed class AudioMixerOwner : IDisposable private readonly Action m_retirementFailed; private readonly Action m_retire; private readonly List m_retirementFailures = []; - private readonly Dictionary m_buses = []; - private readonly Dictionary m_busControls = []; - private readonly List> m_retiredBuses = []; + private readonly Dictionary m_buses = []; + private readonly Dictionary m_busControls = []; + private readonly List> m_retiredBuses = []; private readonly Dictionary m_retiredMasterPauses = []; private AudioMixer m_activeMixer; private bool m_suspended; @@ -22,13 +22,12 @@ internal AudioMixerOwner( IAudioDevice device, Action retirementFailed, Action retire - ) - : this(device, new AudioMixerBuilder().Build(), null, false, retirementFailed, retire) { } + ) : this(device, new AudioMixerBuilder().Build(), null, false, retirementFailed, retire) {} private AudioMixerOwner( IAudioDevice device, AudioMixer mixer, - IReadOnlyDictionary? controls, + IReadOnlyDictionary? controls, bool suspended, Action retirementFailed, Action retire @@ -38,32 +37,79 @@ Action retire m_retire = retire; m_activeMixer = mixer; m_suspended = suspended; - foreach ((AudioBusId id, AudioBusHandle handle) in CreateBusSet(device, mixer, controls)) + foreach ((AudioBusID id, AudioBusHandle handle) in CreateBusSet(device, mixer, controls)) + { m_buses.Add(id, handle); + } foreach (AudioBusDefinition bus in mixer.buses) { BusControlState state = controls is not null && controls.TryGetValue(bus.id, out BusControlState? current) - ? current : new BusControlState(bus.volume, bus.muted, paused: false); + ? current + : new BusControlState(bus.volume, bus.muted, paused: false); m_busControls.Add(bus.id, new BusControlState(state.volume, state.muted, state.paused)); } } + /// + /// Retires the active graph and all retained graph generations after their voices have stopped. + /// + public void Dispose() + { + try + { + DestroyBusSet(m_device, m_buses); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception error) + { + m_retirementFailures.Add(error); + } + while (m_retiredBuses.Count > 0) + { + try + { + DestroyBusSet(m_device, m_retiredBuses[^1]); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch (Exception error) + { + m_retirementFailures.Add(error); + } + m_retiredBuses.RemoveAt(m_retiredBuses.Count - 1); + } + m_busControls.Clear(); + m_retiredMasterPauses.Clear(); + if (m_retirementFailures.Count == 0) + { + return; + } + Exception[] failures = m_retirementFailures.ToArray(); + m_retirementFailures.Clear(); + throw new AggregateException("Audio mixer retirement failed after every graph was attempted.", failures); + } + internal AudioMixerOwner PrepareReplacement(IAudioDevice device) => new(device, m_activeMixer, m_busControls, m_suspended, m_retirementFailed, m_retire); internal bool TryGetBus( - AudioBusId id, + AudioBusID id, out AudioBusHandle handle ) => m_buses.TryGetValue(id, out handle); internal bool SetBusVolume( - AudioBusId bus, + AudioBusID bus, float volume ) { - if (volume < 0f || !float.IsFinite(volume) || - !m_buses.TryGetValue(bus, out AudioBusHandle handle) || - !m_device.SetBusVolume(handle, volume)) - { + if (volume < 0f || !float.IsFinite(volume) + || !m_buses.TryGetValue(bus, out AudioBusHandle handle) + || !m_device.SetBusVolume(handle, volume) + ) { return false; } m_busControls[bus].volume = volume; @@ -71,22 +117,26 @@ float volume } internal bool SetBusMuted( - AudioBusId bus, + AudioBusID bus, bool muted ) { if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) || !m_device.SetBusMuted(handle, muted)) + { return false; + } m_busControls[bus].muted = muted; return true; } internal bool SetBusPaused( - AudioBusId bus, + AudioBusID bus, bool paused ) { - if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) || - !m_device.SetBusPaused(handle, paused || bus == AudioBusId.master && m_suspended)) + if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) + || !m_device.SetBusPaused(handle, paused || bus == AudioBusID.master && m_suspended) + ) { return false; + } m_busControls[bus].paused = paused; return true; } @@ -94,10 +144,12 @@ bool paused internal void SetSuspended(bool suspended) { if (suspended == m_suspended) + { return; + } var masters = new List>(m_retiredMasterPauses) { - new(m_buses[AudioBusId.master], m_busControls[AudioBusId.master].paused) + new KeyValuePair(m_buses[AudioBusID.master], m_busControls[AudioBusID.master].paused) }; int applied = 0; try @@ -105,7 +157,9 @@ internal void SetSuspended(bool suspended) foreach ((AudioBusHandle handle, bool paused) in masters) { if (!m_device.SetBusPaused(handle, paused || suspended)) + { throw new InvalidOperationException("The audio backend rejected application suspension."); + } applied++; } } @@ -118,7 +172,9 @@ internal void SetSuspended(bool suspended) { KeyValuePair master = masters[index]; if (!m_device.SetBusPaused(master.Key, master.Value || m_suspended)) + { throw new InvalidOperationException("The audio backend rejected suspension rollback."); + } } catch (Exception rollback) { @@ -141,18 +197,22 @@ internal void Install( IEnumerable usedBuses ) { CollectRetiredBuses(usedBuses); - IReadOnlyDictionary candidate = CreateBusSet(m_device, mixer, null); + IReadOnlyDictionary candidate = CreateBusSet(m_device, mixer, null); if (m_buses.Count > 0) { - m_retiredBuses.Add(new Dictionary(m_buses)); - m_retiredMasterPauses.Add(m_buses[AudioBusId.master], m_busControls[AudioBusId.master].paused); + m_retiredBuses.Add(new Dictionary(m_buses)); + m_retiredMasterPauses.Add(m_buses[AudioBusID.master], m_busControls[AudioBusID.master].paused); } m_buses.Clear(); - foreach ((AudioBusId id, AudioBusHandle handle) in candidate) + foreach ((AudioBusID id, AudioBusHandle handle) in candidate) + { m_buses.Add(id, handle); + } m_busControls.Clear(); foreach (AudioBusDefinition bus in mixer.buses) + { m_busControls.Add(bus.id, new BusControlState(bus.volume, bus.muted, paused: false)); + } m_activeMixer = mixer; } @@ -161,12 +221,14 @@ internal void CollectRetiredBuses(IEnumerable usedBuses) HashSet retained = usedBuses.ToHashSet(); for (int index = m_retiredBuses.Count - 1; index >= 0; index--) { - Dictionary retired = m_retiredBuses[index]; + Dictionary retired = m_retiredBuses[index]; if (retired.Values.Any(retained.Contains)) + { continue; + } try { - AudioBusHandle master = retired[AudioBusId.master]; + AudioBusHandle master = retired[AudioBusID.master]; DestroyBusSet(m_device, retired); m_retiredMasterPauses.Remove(master); m_retiredBuses.RemoveAt(index); @@ -179,79 +241,41 @@ internal void CollectRetiredBuses(IEnumerable usedBuses) } } - /// - /// Retires the active graph and all retained graph generations after their voices have stopped. - /// - public void Dispose() - { - try - { - DestroyBusSet(m_device, m_buses); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception error) - { - m_retirementFailures.Add(error); - } - while (m_retiredBuses.Count > 0) - { - try - { - DestroyBusSet(m_device, m_retiredBuses[^1]); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch (Exception error) - { - m_retirementFailures.Add(error); - } - m_retiredBuses.RemoveAt(m_retiredBuses.Count - 1); - } - m_busControls.Clear(); - m_retiredMasterPauses.Clear(); - if (m_retirementFailures.Count == 0) - return; - Exception[] failures = m_retirementFailures.ToArray(); - m_retirementFailures.Clear(); - throw new AggregateException("Audio mixer retirement failed after every graph was attempted.", failures); - } - - private IReadOnlyDictionary CreateBusSet( + private IReadOnlyDictionary CreateBusSet( IAudioDevice device, AudioMixer mixer, - IReadOnlyDictionary? controls + IReadOnlyDictionary? controls ) { - var candidate = new Dictionary(); + var candidate = new Dictionary(); try { foreach (AudioBusDefinition bus in mixer.buses) { - AudioBusHandle parent = bus.parent is AudioBusId parentId - ? candidate[parentId] - : default; + AudioBusHandle parent = bus.parent is AudioBusID parentID + ? candidate[parentID] + : default; AudioBusHandle handle = device.CreateBus(bus.id, parent); if (!handle.isValid) + { throw new InvalidOperationException($"The backend rejected audio bus '{bus.id}'."); + } candidate.Add(bus.id, handle); BusControlState state = controls is not null && controls.TryGetValue(bus.id, out BusControlState? current) - ? current - : new BusControlState(bus.volume, bus.muted, paused: false); - if (!device.SetBusVolume(handle, state.volume) || - !device.SetBusMuted(handle, state.muted) || - (state.paused || bus.id == AudioBusId.master && m_suspended) && - !device.SetBusPaused(handle, paused: true)) - { + ? current + : new BusControlState(bus.volume, bus.muted, paused: false); + if (!device.SetBusVolume(handle, state.volume) + || !device.SetBusMuted(handle, state.muted) + || (state.paused || bus.id == AudioBusID.master && m_suspended) + && !device.SetBusPaused(handle, paused: true) + ) { throw new InvalidOperationException($"The backend rejected parameters for audio bus '{bus.id}'."); } foreach (AudioProcessorConfiguration processor in bus.processors) { if (!device.AddBusProcessor(handle, processor)) + { throw new InvalidOperationException($"The backend rejected processor '{processor.id}'."); + } } } return candidate; @@ -277,15 +301,17 @@ private IReadOnlyDictionary CreateBusSet( private static void DestroyBusSet( IAudioDevice device, - Dictionary buses + Dictionary buses ) { List failures = []; - foreach ((AudioBusId id, AudioBusHandle bus) in buses.Reverse().ToArray()) + foreach ((AudioBusID id, AudioBusHandle bus) in buses.Reverse().ToArray()) { try { if (!device.DestroyBus(bus)) + { throw new InvalidOperationException("The backend refused audio bus retirement."); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -298,7 +324,9 @@ Dictionary buses buses.Remove(id); } if (failures.Count > 0) + { throw new AggregateException("Audio bus retirement failed after every bus was attempted.", failures); + } } private sealed class BusControlState( diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs index 0ca7665c4..b47b83385 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs @@ -1,15 +1,15 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Inno.Assets; +using Inno.Core.Diagnostics; using Inno.Core.Events; +using Inno.Core.Execution; using Inno.Extensibility.Types; +using Inno.References; +using Inno.Runtime.Contracts; namespace Inno.Audio.Runtime; @@ -24,11 +24,11 @@ public sealed class AudioRuntime : RuntimeSubsystem, IAudioService private readonly IDiagnosticReporter m_diagnostics; private readonly EventDispatcher m_events; private readonly AudioExtensionRegistry m_extensions; + private readonly AudioRuntimeOptions m_options; + private readonly List m_retirementFailures = []; private AudioClipCache m_clipCache; private AudioVoiceOwner m_voices; private AudioContentOwner m_content; - private readonly AudioRuntimeOptions m_options; - private IAudioDevice m_device; private AudioMixerOwner m_mixer; private string? m_mixerDiagnosticSource; @@ -39,7 +39,6 @@ public sealed class AudioRuntime : RuntimeSubsystem, IAudioService private bool m_stopping; private bool m_extensionsRetired; private int m_retirementStage; - private readonly List m_retirementFailures = []; private AudioDeviceCandidate? m_candidateRetirement; /// @@ -86,10 +85,14 @@ public AudioRuntime( Func? deviceRecoveryFactory = null ) { ArgumentNullException.ThrowIfNull(types); - m_device = device ?? throw new ArgumentNullException(nameof(device)); - m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - m_events = events ?? throw new ArgumentNullException(nameof(events)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(device); + ArgumentNullException.ThrowIfNull(artifacts); + ArgumentNullException.ThrowIfNull(events); + ArgumentNullException.ThrowIfNull(diagnostics); + m_device = device; + m_artifacts = artifacts; + m_events = events; + m_diagnostics = diagnostics; m_options = (options ?? new AudioRuntimeOptions()).Validate(); m_contentScopeProvider = contentScopeProvider; m_deviceRecoveryFactory = deviceRecoveryFactory; @@ -108,7 +111,16 @@ public AudioRuntime( m_extensions.Dispose(); throw; } - m_voices = new AudioVoiceOwner(m_device, m_artifacts, m_clipCache, m_mixer, m_events, m_diagnostics, m_options, m_extensions.RetireBackend); + m_voices = new AudioVoiceOwner( + m_device, + m_artifacts, + m_clipCache, + m_mixer, + m_events, + m_diagnostics, + m_options, + m_extensions.RetireBackend + ); m_content = new AudioContentOwner(m_device, m_voices, m_diagnostics, m_contentScopeProvider, m_options.maxContentSnapshots); if (m_device.state == AudioDeviceState.Muted) { @@ -116,7 +128,8 @@ public AudioRuntime( "AUDIO_NO_DEVICE", "Audio is running in explicit muted mode because no output device is active.", DiagnosticSeverity.Warning, - m_device.GetType().FullName); + m_device.GetType().FullName + ); } } @@ -135,35 +148,11 @@ public AudioRuntime( /// public double dspTime => m_device.dspTime; - /// - protected override void OnStart() - { - m_events.dispatched += OnEventDispatched; - } - /// - /// Captures snapshots and binds service façades. - /// - /// - /// The variable frame timing. - /// - protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(EnterExecutionScope()); - /// - /// Advances domain state on the variable clock. - /// - /// - /// The variable frame timing. - /// - protected override void OnUpdate(RuntimeFrame frame) => Update(frame.unscaledDeltaTime); - /// /// Gets current runtime resource statistics. /// public AudioStatistics statistics - => new( - m_voices.count, - m_clipCache.count, - m_clipCache.decodedBytes, - m_stolenVoiceCount + m_voices.stolenCount); + => new(m_voices.count, m_clipCache.count, m_clipCache.decodedBytes, m_stolenVoiceCount + m_voices.stolenCount); /// /// Gets bounded provider admission counts from the most recent content collection on this device generation. @@ -240,7 +229,9 @@ public AudioVoiceHandle PlayScheduled( AudioPlayOptions options ) { if (double.IsNaN(scheduledDspTime) || double.IsInfinity(scheduledDspTime) || scheduledDspTime < 0d) + { throw new ArgumentOutOfRangeException(nameof(scheduledDspTime)); + } EnsureActive(); return m_voices.Play(clip, options, scheduledDspTime); } @@ -363,7 +354,7 @@ out AudioPlaybackState playbackState /// when the active mixer contains the bus. /// public bool SetBusVolume( - AudioBusId bus, + AudioBusID bus, float volume ) { EnsureActive(); @@ -383,7 +374,7 @@ float volume /// when the active mixer contains the bus. /// public bool SetBusMuted( - AudioBusId bus, + AudioBusID bus, bool muted ) { EnsureActive(); @@ -403,7 +394,7 @@ bool muted /// when the active mixer contains the bus. /// public bool SetBusPaused( - AudioBusId bus, + AudioBusID bus, bool paused ) { EnsureActive(); @@ -473,7 +464,8 @@ public bool ApplyMixer(AudioMixerAsset asset) "AUDIO_MIXER_EXTENSION_MISSING", "The candidate audio mixer references an unavailable extension; the last-good mixer remains active.", DiagnosticSeverity.Error, - asset.mixerTypeId); + asset.mixerTypeId + ); return false; } m_mixer.Install(mixer, m_voices.usedBuses); @@ -486,7 +478,8 @@ public bool ApplyMixer(AudioMixerAsset asset) "AUDIO_MIXER_CANDIDATE_FAILED", $"The candidate audio mixer failed validation; the last-good mixer remains active: {exception.Message}", DiagnosticSeverity.Error, - asset.mixerTypeId); + asset.mixerTypeId + ); return false; } } @@ -508,7 +501,9 @@ public void ReplaceDevice(IAudioDevice replacement) EnsureActive(); ArgumentNullException.ThrowIfNull(replacement); if (ReferenceEquals(replacement, m_device)) + { throw new ArgumentException("The replacement must be a different device instance.", nameof(replacement)); + } AudioMixerOwner replacementMixer; m_candidateRetirement = new AudioDeviceCandidate(replacement); try @@ -554,7 +549,10 @@ public void ReplaceDevice(IAudioDevice replacement) failures.Add(error); } m_candidateRetirement = null; - var failure = new AggregateException("Audio device retirement failed; the previous generation cannot resume.", failures); + var failure = new AggregateException( + "Audio device retirement failed; the previous generation cannot resume.", + failures + ); m_extensions.Fault(failure); throw failure; } @@ -566,7 +564,17 @@ public void ReplaceDevice(IAudioDevice replacement) m_device = replacement; m_clipCache = new AudioClipCache(m_device, m_artifacts, m_options, m_extensions.RetireBackend); m_mixer = replacementMixer; - m_voices = new AudioVoiceOwner(m_device, m_artifacts, m_clipCache, m_mixer, m_events, m_diagnostics, m_options, m_extensions.RetireBackend, m_voices); + m_voices = new AudioVoiceOwner( + m_device, + m_artifacts, + m_clipCache, + m_mixer, + m_events, + m_diagnostics, + m_options, + m_extensions.RetireBackend, + m_voices + ); m_content = new AudioContentOwner(m_device, m_voices, m_diagnostics, m_contentScopeProvider, m_options.maxContentSnapshots); m_deviceRecoveryElapsed = 0f; m_deviceLossReported = false; @@ -590,13 +598,15 @@ public bool TryRecoverDevice(Func deviceFactory) EnsureActive(); ArgumentNullException.ThrowIfNull(deviceFactory); if (m_device.state == AudioDeviceState.Ready) + { return true; + } IAudioDevice? candidate = null; try { candidate = deviceFactory() - ?? throw new InvalidOperationException("The audio recovery factory returned null."); + ?? throw new InvalidOperationException("The audio recovery factory returned null."); if (candidate.state != AudioDeviceState.Ready) { IAudioDevice rejected = candidate; @@ -614,7 +624,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERY_FAILED", "The replacement audio device did not reach the ready state; muted playback remains active.", DiagnosticSeverity.Warning, - "AudioRuntime"); + "AudioRuntime" + ); return false; } string? recoveredSource = candidate.GetType().FullName; @@ -625,7 +636,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERED", "The audio output device recovered with a new generation.", DiagnosticSeverity.Info, - recoveredSource); + recoveredSource + ); return true; } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) @@ -637,7 +649,9 @@ public bool TryRecoverDevice(Func deviceFactory) try { if (candidate is not null) + { m_extensions.RetireBackend(candidate.Dispose); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -653,7 +667,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERY_FAILED", $"The audio output recovery candidate failed; muted playback remains active: {exception.Message}", DiagnosticSeverity.Warning, - "AudioRuntime"); + "AudioRuntime" + ); return false; } } @@ -671,7 +686,9 @@ public void Update(float deltaTime) { EnsureActive(); if (!float.IsFinite(deltaTime) || deltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } m_content.Update(m_extensions.extensions.providers, deltaTime); m_voices.PrepareVoices(); m_device.Update(deltaTime); @@ -689,7 +706,8 @@ public void Update(float deltaTime) "AUDIO_DEVICE_LOST", "The audio output device was lost; active voices are completing and recovery will retry at safe points.", DiagnosticSeverity.Warning, - m_device.GetType().FullName); + m_device.GetType().FullName + ); } m_voices.CompleteAll(AudioCompletionReason.DeviceLost); m_content.ClearEmitters(); @@ -697,13 +715,34 @@ public void Update(float deltaTime) AdvanceDeviceRecovery(deltaTime); } + /// + protected override void OnStart() => m_events.dispatched += OnEventDispatched; + + /// + /// Captures snapshots and binds service façades. + /// + /// + /// The variable frame timing. + /// + protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(EnterExecutionScope()); + + /// + /// Advances domain state on the variable clock. + /// + /// + /// The variable frame timing. + /// + protected override void OnUpdate(RuntimeFrame frame) => Update(frame.unscaledDeltaTime); + /// /// Stops voices and releases providers, cache entries, mixer generations, and the owned backend device. /// protected override void OnStop() { if (m_disposed) + { return; + } m_stopping = true; m_events.dispatched -= OnEventDispatched; if (!m_extensionsRetired) @@ -738,13 +777,17 @@ protected override void OnStop() m_candidateRetirement = null; m_disposed = true; if (failures.Count > 0) + { throw new AggregateException("Audio retirement failed after all resource owners were attempted.", failures); + } } private void OnEventDispatched(Event e) { if (e is ApplicationSuspensionChangedEvent suspension) + { m_mixer.SetSuspended(suspension.isSuspended); + } } private List RetireBackend(AudioCompletionReason reason) @@ -755,11 +798,21 @@ private List RetireBackend(AudioCompletionReason reason) { switch (m_retirementStage) { - case 0: m_voices.CompleteAll(reason); break; - case 1: m_content.Dispose(); break; - case 2: m_clipCache.Dispose(); break; - case 3: m_mixer.Dispose(); break; - case 4: m_device.Dispose(); break; + case 0: + m_voices.CompleteAll(reason); + break; + case 1: + m_content.Dispose(); + break; + case 2: + m_clipCache.Dispose(); + break; + case 3: + m_mixer.Dispose(); + break; + case 4: + m_device.Dispose(); + break; } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) @@ -786,10 +839,14 @@ private void AdvanceDeviceRecovery(float deltaTime) return; } if (m_deviceRecoveryFactory is null) + { return; + } m_deviceRecoveryElapsed += deltaTime; if (m_deviceRecoveryElapsed < m_options.deviceRecoveryIntervalSeconds) + { return; + } m_deviceRecoveryElapsed = 0f; _ = TryRecoverDevice(m_deviceRecoveryFactory); } @@ -799,14 +856,15 @@ private void Publish( string message, DiagnosticSeverity severity, string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping || m_retirementStage != 0) + { throw new InvalidOperationException("Audio retirement has started; no new work can be accepted."); + } m_extensions.EnsureHealthy(); } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs index 34a7746e2..5d3db7519 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Audio.Runtime; @@ -20,16 +19,18 @@ public sealed class AudioRuntimeFactory : IRuntimeSubsystemFactory /// public AudioRuntimeFactory(Func runtimeFactory) { - m_runtimeFactory = runtimeFactory ?? throw new ArgumentNullException(nameof(runtimeFactory)); + ArgumentNullException.ThrowIfNull(runtimeFactory); + m_runtimeFactory = runtimeFactory; } /// /// Gets stable ordering metadata that updates audio after scene simulation. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.audio"), + new RuntimeSubsystemID("inno.runtime.audio"), order: 500, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemID("inno.runtime.scene")] + ); /// /// Creates an audio feature over a newly allocated runtime layer. @@ -44,7 +45,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); AudioRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The audio runtime factory returned null."); + ?? throw new InvalidOperationException("The audio runtime factory returned null."); return runtime; } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs index c561e0aab..a7ae1925f 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs @@ -45,7 +45,9 @@ internal AudioRuntimeOptions Validate() ArgumentOutOfRangeException.ThrowIfNegative(decodedCacheBudgetBytes); ArgumentOutOfRangeException.ThrowIfNegative(automaticStreamingThresholdBytes); if (!float.IsFinite(deviceRecoveryIntervalSeconds) || deviceRecoveryIntervalSeconds <= 0f) + { throw new ArgumentOutOfRangeException(nameof(deviceRecoveryIntervalSeconds)); + } return new AudioRuntimeOptions { maxVoices = maxVoices, diff --git a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs index 27d70ae4b..b8d9c788e 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs @@ -14,7 +14,6 @@ internal sealed class AudioVoiceOwner private readonly Queue m_terminalVoiceOrder = []; private readonly Dictionary m_voices = []; private readonly AudioVoiceAllocator m_voiceAllocator = new(); - private long m_nextVoiceSequence; private readonly IAudioDevice m_device; private readonly IAssetArtifactLookup m_artifacts; private readonly AudioClipCache m_clipCache; @@ -23,8 +22,9 @@ internal sealed class AudioVoiceOwner private readonly IDiagnosticReporter m_diagnostics; private readonly AudioRuntimeOptions m_options; private readonly Action m_retireResources; - private long m_stolenVoiceCount; private readonly List m_retirementFailures = []; + private long m_nextVoiceSequence; + private long m_stolenVoiceCount; internal AudioVoiceOwner( IAudioDevice device, @@ -59,13 +59,17 @@ internal AudioVoiceOwner( internal void RefreshStates() { foreach (VoiceRecord voice in m_voices.Values) + { UpdateVoiceState(voice); + } } internal bool Stop(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } if (!record.backendVoice.isValid) { FinishVoice(record, AudioCompletionReason.Stopped); @@ -73,7 +77,9 @@ internal bool Stop(AudioVoiceHandle voice) } record.completionOverride = AudioCompletionReason.Stopped; if (m_device.Stop(record.backendVoice)) + { return true; + } FinishVoice(record, AudioCompletionReason.Stopped); return true; } @@ -81,7 +87,9 @@ internal bool Stop(AudioVoiceHandle voice) internal bool Pause(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.pauseRequested = true; if (!record.backendVoice.isValid) { @@ -90,14 +98,18 @@ internal bool Pause(AudioVoiceHandle voice) } bool result = m_device.Pause(record.backendVoice); if (result) + { record.state = AudioPlaybackState.Paused; + } return result; } internal bool Resume(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record) || !record.pauseRequested) + { return false; + } record.pauseRequested = false; if (!record.backendVoice.isValid) { @@ -106,7 +118,9 @@ internal bool Resume(AudioVoiceHandle voice) } bool result = m_device.Resume(record.backendVoice); if (result) + { UpdateVoiceState(record); + } return result; } @@ -115,7 +129,9 @@ internal bool Seek( TimeSpan position ) { if (position < TimeSpan.Zero || !m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.seekPosition = position; return !record.backendVoice.isValid || m_device.Seek(record.backendVoice, position); } @@ -125,9 +141,13 @@ internal bool SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.parameters = parameters; return !record.backendVoice.isValid || m_device.SetVoiceParameters(record.backendVoice, parameters); } @@ -158,7 +178,9 @@ internal AudioVoiceHandle Play( ) { ArgumentNullException.ThrowIfNull(clip); if (!options.bus.isValid) + { throw new ArgumentException("Playback options must be initialized.", nameof(options)); + } var request = new AudioClipRequest(clip, m_artifacts); AudioVoiceHandle handle; try @@ -166,7 +188,9 @@ internal AudioVoiceHandle Play( handle = m_voiceAllocator.Allocate(); var record = new VoiceRecord(handle, request, options, scheduledDspTime, m_nextVoiceSequence++); while (m_voices.Count >= m_options.maxVoices) + { StealVoice(); + } m_voices.Add(handle, record); } catch (Exception failure) @@ -188,28 +212,12 @@ internal AudioVoiceHandle Play( return handle; } - private void StealVoice() - { - VoiceRecord victim = m_voices.Values - .OrderBy(static voice => voice.options.priority) - .ThenBy(static voice => voice.sequence) - .First(); - if (victim.finishingReason is AudioCompletionReason finishingReason) - { - FinishVoice(victim, finishingReason); - return; - } - if (victim.backendVoice.isValid) - _ = m_device.Stop(victim.backendVoice); - m_stolenVoiceCount++; - FinishVoice(victim, AudioCompletionReason.Stolen); - } - internal void PrepareVoices() { - foreach (VoiceRecord voice in m_voices.Values.Where(static voice => - !voice.backendVoice.isValid && voice.finishingReason is null).ToArray()) - { + foreach (VoiceRecord voice in m_voices.Values.Where(static voice => ( + !voice.backendVoice.isValid && voice.finishingReason is null + )).ToArray() + ) { try { AudioClipCache.ClipCacheEntry clip; @@ -221,25 +229,39 @@ internal void PrepareVoices() voice.clip.Dispose(); } else + { clip = voice.clipCache; + } AudioClipState preparation = m_device.GetClipState(clip.handle); if (preparation == AudioClipState.Preparing) + { continue; + } if (preparation == AudioClipState.Failed) + { throw new InvalidOperationException("Native audio preparation failed."); + } if (!m_mixer.TryGetBus(voice.options.bus, out AudioBusHandle bus)) + { throw new InvalidOperationException($"Audio bus '{voice.options.bus}' is not present in the active mixer."); + } voice.backendVoice = m_device.Play(clip.handle, bus, voice.options, voice.scheduledDspTime); voice.backendBus = bus; if (!voice.backendVoice.isValid) + { throw new InvalidOperationException("The audio backend rejected voice creation."); + } if (voice.seekPosition is TimeSpan seek) + { _ = m_device.Seek(voice.backendVoice, seek); + } _ = m_device.SetVoiceParameters(voice.backendVoice, voice.parameters); if (voice.pauseRequested) + { _ = m_device.Pause(voice.backendVoice); + } UpdateVoiceState(voice); - m_diagnostics.Resolve("AUDIO_CLIP_PREPARATION_FAILED", voice.clip.persistentId.ToString("D")); + m_diagnostics.Resolve("AUDIO_CLIP_PREPARATION_FAILED", voice.clip.persistentID.ToString("D")); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -251,63 +273,31 @@ internal void PrepareVoices() "AUDIO_CLIP_PREPARATION_FAILED", $"Audio clip '{voice.clip.assetPath}' could not be prepared: {exception.Message}", DiagnosticSeverity.Error, - voice.clip.persistentId.ToString("D")); + voice.clip.persistentID.ToString("D") + ); FinishVoice(voice, AudioCompletionReason.DecodeFailed); } } } - private void FinishVoice( - VoiceRecord voice, - AudioCompletionReason reason - ) { - if (!m_voices.ContainsKey(voice.handle)) - return; - voice.finishingReason ??= reason; - voice.clip.Dispose(); - if (voice.clipCache is not null) - { - if (!voice.cacheReferenceReleased) - { - voice.clipCache.voiceReferences--; - voice.cacheReferenceReleased = true; - } - m_clipCache.TryReleaseClip(voice.clipCache); - voice.clipCache = null; - } - m_events.Enqueue(new AudioVoiceCompletedEvent(voice.handle, voice.finishingReason.Value)); - m_voices.Remove(voice.handle); - if (m_terminalVoices.Add(voice.handle)) - m_terminalVoiceOrder.Enqueue(voice.handle); - int terminalCapacity = m_options.maxVoices > int.MaxValue / 2 - ? int.MaxValue - : Math.Max(64, m_options.maxVoices * 2); - while (m_terminalVoiceOrder.Count > terminalCapacity) - m_terminalVoices.Remove(m_terminalVoiceOrder.Dequeue()); - } - internal void DrainCompletions() { foreach (VoiceRecord pending in m_voices.Values.Where(static voice => voice.finishingReason is not null).ToArray()) + { FinishVoice(pending, pending.finishingReason!.Value); + } long budget = Math.Max(64L, 2L * m_options.maxVoices); while (budget-- > 0 && m_device.TryDequeueCompletion(out AudioDeviceCompletion completion)) { VoiceRecord? voice = m_voices.Values.FirstOrDefault(candidate => candidate.backendVoice == completion.voice); if (voice is null) + { continue; + } FinishVoice(voice, voice.completionOverride ?? completion.reason); } } - private void UpdateVoiceState(VoiceRecord voice) - { - if (!voice.backendVoice.isValid) - return; - if (m_device.TryGetVoiceState(voice.backendVoice, out AudioPlaybackState state)) - voice.state = state; - } - internal void CompleteAll(AudioCompletionReason reason) { foreach (VoiceRecord voice in m_voices.Values.ToArray()) @@ -315,7 +305,9 @@ internal void CompleteAll(AudioCompletionReason reason) try { if (voice.backendVoice.isValid && voice.finishingReason is null) + { _ = m_device.Stop(voice.backendVoice); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -339,12 +331,87 @@ internal void CompleteAll(AudioCompletionReason reason) } } if (m_retirementFailures.Count == 0) + { return; + } Exception[] failures = m_retirementFailures.ToArray(); m_retirementFailures.Clear(); throw new AggregateException("Audio voice retirement failed after every voice was attempted.", failures); } + private void StealVoice() + { + VoiceRecord victim = m_voices.Values + .OrderBy(static voice => voice.options.priority) + .ThenBy(static voice => voice.sequence) + .First(); + if (victim.finishingReason is AudioCompletionReason finishingReason) + { + FinishVoice(victim, finishingReason); + return; + } + if (victim.backendVoice.isValid) + { + _ = m_device.Stop(victim.backendVoice); + } + m_stolenVoiceCount++; + FinishVoice(victim, AudioCompletionReason.Stolen); + } + + private void FinishVoice( + VoiceRecord voice, + AudioCompletionReason reason + ) { + if (!m_voices.ContainsKey(voice.handle)) + { + return; + } + voice.finishingReason ??= reason; + voice.clip.Dispose(); + if (voice.clipCache is not null) + { + if (!voice.cacheReferenceReleased) + { + voice.clipCache.voiceReferences--; + voice.cacheReferenceReleased = true; + } + m_clipCache.TryReleaseClip(voice.clipCache); + voice.clipCache = null; + } + m_events.Enqueue(new AudioVoiceCompletedEvent(voice.handle, voice.finishingReason.Value)); + m_voices.Remove(voice.handle); + if (m_terminalVoices.Add(voice.handle)) + { + m_terminalVoiceOrder.Enqueue(voice.handle); + } + int terminalCapacity = m_options.maxVoices > int.MaxValue / 2 + ? int.MaxValue + : Math.Max(64, m_options.maxVoices * 2); + while (m_terminalVoiceOrder.Count > terminalCapacity) + { + m_terminalVoices.Remove(m_terminalVoiceOrder.Dequeue()); + } + } + + private void UpdateVoiceState(VoiceRecord voice) + { + if (!voice.backendVoice.isValid) + { + return; + } + if (m_device.TryGetVoiceState(voice.backendVoice, out AudioPlaybackState state)) + { + voice.state = state; + } + } + + private void Publish( + string code, + string message, + DiagnosticSeverity severity, + string? source + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + private sealed class VoiceRecord { internal VoiceRecord( @@ -359,7 +426,7 @@ long sequence this.options = options; this.scheduledDspTime = scheduledDspTime; this.sequence = sequence; - parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); + this.parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); } internal AudioVoiceHandle handle { get; } @@ -378,12 +445,4 @@ long sequence internal AudioCompletionReason? finishingReason { get; set; } internal bool cacheReferenceReleased { get; set; } } - - private void Publish( - string code, - string message, - DiagnosticSeverity severity, - string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); } diff --git a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs index d6cde8305..d6f40f58c 100644 --- a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs +++ b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs @@ -11,7 +11,7 @@ namespace Inno.Audio.Runtime; /// public sealed class MutedAudioDevice : AudioDevice, IAudioDevice { - private static uint S_NEXT_GENERATION; + private static uint s_nextGeneration; private readonly AudioDeviceLimits m_limits; private readonly Dictionary m_clips = []; @@ -33,15 +33,17 @@ public sealed class MutedAudioDevice : AudioDevice, IAudioDevice /// Optional finite device resource capacities. /// public MutedAudioDevice( - int sampleRate = 48000, + int sampleRate = 48_000, AudioDeviceLimits? limits = null ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); m_limits = limits ?? new AudioDeviceLimits(); - generation = unchecked(++S_NEXT_GENERATION); + this.generation = unchecked(++s_nextGeneration); if (generation == 0) - generation = unchecked(++S_NEXT_GENERATION); - capabilities = new AudioCapabilities(true, true, true, 4, sampleRate); + { + this.generation = unchecked(++s_nextGeneration); + } + this.capabilities = new AudioCapabilities(true, true, true, 4, sampleRate); } /// @@ -67,12 +69,24 @@ public MutedAudioDevice( /// /// Gets current logical resource statistics. /// - public AudioStatistics statistics - => new( - ActiveVoiceCount(), - m_clips.Count, - 0, - 0); + public AudioStatistics statistics => new(ActiveVoiceCount(), m_clips.Count, 0, 0); + + /// + /// Releases all logical clips, voices, buses, and listeners. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + m_clips.Clear(); + m_voices.Clear(); + m_buses.Clear(); + m_listeners.Clear(); + m_completions.Clear(); + } AudioClipHandle IAudioDevice.CreateClip( AudioClipDescriptor descriptor, @@ -81,7 +95,9 @@ IAudioClipSource source EnsureActive(); ArgumentNullException.ThrowIfNull(source); if (m_clips.Count >= m_limits.clips) + { return default; + } ulong id = m_nextIdentity++; m_clips.Add(id, descriptor); return CreateClipHandle(id, generation); @@ -91,7 +107,8 @@ AudioClipState IAudioDevice.GetClipState(AudioClipHandle clip) { DeviceHandleIdentity identity = GetHandleIdentity(clip); return identity.generation == generation && m_clips.ContainsKey(identity.value) - ? AudioClipState.Ready : AudioClipState.Failed; + ? AudioClipState.Ready + : AudioClipState.Failed; } bool IAudioDevice.DestroyClip(AudioClipHandle clip) @@ -99,7 +116,9 @@ bool IAudioDevice.DestroyClip(AudioClipHandle clip) EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(clip); if (identity.generation != generation || HasActiveVoiceForClip(identity.value)) + { return false; + } return m_clips.Remove(identity.value); } @@ -111,36 +130,47 @@ AudioDeviceVoiceHandle IAudioDevice.Play( ) { EnsureActive(); if (m_voices.Count >= m_limits.voices) + { return default; + } if (!options.bus.isValid || scheduledDspTime is double startTime && (!double.IsFinite(startTime) || startTime < 0)) + { return default; + } DeviceHandleIdentity clipIdentity = GetHandleIdentity(clip); DeviceHandleIdentity busIdentity = GetHandleIdentity(bus); if (clipIdentity.generation != generation || !m_clips.TryGetValue(clipIdentity.value, out AudioClipDescriptor descriptor)) + { return default; + } if (busIdentity.generation != generation || !m_buses.ContainsKey(busIdentity.value)) + { return default; + } ulong id = m_nextIdentity++; AudioPlaybackState playbackState = scheduledDspTime is double start && start > m_dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; - m_voices.Add(id, new VoiceRecord( - clipIdentity.value, - descriptor.frameCount / (double)descriptor.sampleRate, - options, - playbackState, - scheduledDspTime ?? m_dspTime)); + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; + m_voices.Add( + id, + new VoiceRecord( + clipIdentity.value, + descriptor.frameCount / (double)descriptor.sampleRate, + options, + playbackState, + scheduledDspTime ?? m_dspTime + ) + ); return CreateVoiceHandle(id, generation); } - bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) - => CompleteVoice(voice, AudioCompletionReason.Stopped); + bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) => CompleteVoice(voice, AudioCompletionReason.Stopped); bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) { - if (!TryGetVoice(voice, out VoiceRecord record) || - record.state is AudioPlaybackState.Completed or AudioPlaybackState.Paused) - { + if (!TryGetVoice(voice, out VoiceRecord record) + || record.state is AudioPlaybackState.Completed or AudioPlaybackState.Paused + ) { return false; } record.state = AudioPlaybackState.Paused; @@ -150,10 +180,12 @@ bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) bool IAudioDevice.Resume(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out VoiceRecord record) || record.state != AudioPlaybackState.Paused) + { return false; + } record.state = record.scheduledDspTime > m_dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; return true; } @@ -161,9 +193,9 @@ bool IAudioDevice.Seek( AudioDeviceVoiceHandle voice, TimeSpan position ) { - if (position < TimeSpan.Zero || !TryGetVoice(voice, out VoiceRecord record) || - record.state == AudioPlaybackState.Completed) - { + if (position < TimeSpan.Zero || !TryGetVoice(voice, out VoiceRecord record) + || record.state == AudioPlaybackState.Completed + ) { return false; } record.position = position.TotalSeconds; @@ -175,9 +207,13 @@ bool IAudioDevice.SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!TryGetVoice(voice, out VoiceRecord record) || record.state == AudioPlaybackState.Completed) + { return false; + } record.parameters = parameters; return true; } @@ -196,15 +232,19 @@ out AudioPlaybackState playbackState } AudioBusHandle IAudioDevice.CreateBus( - AudioBusId id, + AudioBusID id, AudioBusHandle parent ) { EnsureActive(); if (!id.isValid || m_buses.Count >= m_limits.buses) + { return default; + } DeviceHandleIdentity parentIdentity = GetHandleIdentity(parent); if (parent.isValid && (parentIdentity.generation != generation || !m_buses.ContainsKey(parentIdentity.value))) + { return default; + } ulong identity = m_nextIdentity++; m_buses.Add(identity, new BusRecord(id, parentIdentity.value)); return CreateBusHandle(identity, generation); @@ -215,7 +255,9 @@ bool IAudioDevice.DestroyBus(AudioBusHandle bus) EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(bus); if (identity.generation != generation) + { return false; + } return m_buses.Remove(identity.value); } @@ -224,7 +266,9 @@ bool IAudioDevice.SetBusVolume( float volume ) { if (!float.IsFinite(volume) || volume < 0f || !TryGetBus(bus, out BusRecord record)) + { return false; + } record.volume = volume; return true; } @@ -234,7 +278,9 @@ bool IAudioDevice.SetBusMuted( bool muted ) { if (!TryGetBus(bus, out BusRecord record)) + { return false; + } record.muted = muted; return true; } @@ -244,7 +290,9 @@ bool IAudioDevice.SetBusPaused( bool paused ) { if (!TryGetBus(bus, out BusRecord record)) + { return false; + } record.paused = paused; return true; } @@ -261,7 +309,9 @@ AudioListenerHandle IAudioDevice.CreateListener(AudioListenerState state) { EnsureActive(); if (m_listeners.Count >= capabilities.maxListeners) + { return default; + } ulong id = m_nextIdentity++; m_listeners.Add(id, new ListenerRecord(state)); return CreateListenerHandle(id, generation); @@ -273,7 +323,9 @@ AudioListenerState state ) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.TryGetValue(identity.value, out ListenerRecord? record)) + { return false; + } record.state = state; return true; } @@ -288,21 +340,27 @@ void IAudioDevice.Update(float deltaTime) { EnsureActive(); if (deltaTime < 0f) + { deltaTime = 0f; + } m_dspTime += deltaTime; foreach ((ulong id, VoiceRecord voice) in m_voices) { if (voice.state == AudioPlaybackState.Scheduled && voice.scheduledDspTime <= m_dspTime) + { voice.state = AudioPlaybackState.Playing; + } if (voice.state != AudioPlaybackState.Playing) + { continue; + } voice.position += deltaTime * voice.parameters.pitch; if (!voice.loop && voice.duration > 0d && voice.position >= voice.duration) { voice.state = AudioPlaybackState.Completed; - m_completions.Enqueue(new AudioDeviceCompletion( - CreateVoiceHandle(id, generation), - AudioCompletionReason.NaturalEnd)); + m_completions.Enqueue( + new AudioDeviceCompletion(CreateVoiceHandle(id, generation), AudioCompletionReason.NaturalEnd) + ); } else if (voice.loop && voice.duration > 0d && voice.position >= voice.duration) { @@ -314,34 +372,25 @@ void IAudioDevice.Update(float deltaTime) bool IAudioDevice.TryDequeueCompletion(out AudioDeviceCompletion completion) { if (!m_completions.TryDequeue(out completion)) + { return false; + } DeviceHandleIdentity identity = GetHandleIdentity(completion.voice); if (identity.generation == generation) + { m_voices.Remove(identity.value); + } return true; } - /// - /// Releases all logical clips, voices, buses, and listeners. - /// - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - m_clips.Clear(); - m_voices.Clear(); - m_buses.Clear(); - m_listeners.Clear(); - m_completions.Clear(); - } - private bool CompleteVoice( AudioDeviceVoiceHandle voice, AudioCompletionReason reason ) { if (!TryGetVoice(voice, out VoiceRecord record) || record.state == AudioPlaybackState.Completed) + { return false; + } record.state = AudioPlaybackState.Completed; m_completions.Enqueue(new AudioDeviceCompletion(voice, reason)); return true; @@ -383,7 +432,9 @@ private int ActiveVoiceCount() foreach (VoiceRecord voice in m_voices.Values) { if (voice.state != AudioPlaybackState.Completed) + { count++; + } } return count; } @@ -393,7 +444,9 @@ private bool HasActiveVoiceForClip(ulong clip) foreach (VoiceRecord voice in m_voices.Values) { if (voice.clip == clip && voice.state != AudioPlaybackState.Completed) + { return true; + } } return false; } @@ -401,10 +454,10 @@ private bool HasActiveVoiceForClip(ulong clip) private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); private sealed class BusRecord( - AudioBusId id, + AudioBusID id, ulong parent ) { - internal AudioBusId id { get; } = id; + internal AudioBusID id { get; } = id; internal ulong parent { get; } = parent; internal float volume { get; set; } = 1f; internal bool muted { get; set; } @@ -427,8 +480,8 @@ double scheduledDspTime ) { this.clip = clip; this.duration = duration; - loop = options.loop; - parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); + this.loop = options.loop; + this.parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); this.state = state; this.scheduledDspTime = scheduledDspTime; } diff --git a/src/services/audio/Inno.Audio/Audio.cs b/src/services/audio/Inno.Audio/Audio.cs index 38086f727..c3623976e 100644 --- a/src/services/audio/Inno.Audio/Audio.cs +++ b/src/services/audio/Inno.Audio/Audio.cs @@ -1,45 +1,9 @@ -using Inno.Core.Execution; using System; using System.Threading; using System.Threading.Tasks; namespace Inno.Audio; -/// -/// Binds one host-owned audio service to the current asynchronous execution context. -/// -public static class AudioExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("audio"); - - /// - /// Gets the audio service bound to the current asynchronous execution context. - /// - /// - /// Thrown when no audio service is active for the caller. - /// - public static IAudioService current => S_CURRENT_SCOPE.current; - - /// - /// Binds an audio service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// Host-owned audio service exposed to script-facing operations. - /// - /// - /// A strict last-in-first-out scope owned by the caller. - /// - /// - /// Thrown when is . - /// - public static IDisposable EnterScope(IAudioService audio) - { - ArgumentNullException.ThrowIfNull(audio); - return S_CURRENT_SCOPE.Enter(audio); - } - -} - /// /// Provides script-friendly access to the audio service in the current execution context. /// @@ -112,8 +76,7 @@ public static AudioVoiceHandle PlayScheduled( AudioClipAsset clip, double scheduledDspTime, AudioPlayOptions options - ) - => AudioExecutionContext.current.PlayScheduled(clip, scheduledDspTime, options); + ) => AudioExecutionContext.current.PlayScheduled(clip, scheduledDspTime, options); /// /// Stops a live voice. @@ -180,8 +143,7 @@ TimeSpan position public static bool SetVoiceParameters( AudioVoiceHandle voice, AudioVoiceParameters parameters - ) - => AudioExecutionContext.current.SetVoiceParameters(voice, parameters); + ) => AudioExecutionContext.current.SetVoiceParameters(voice, parameters); /// /// Queries the current state of a voice. @@ -198,8 +160,7 @@ AudioVoiceParameters parameters public static bool TryGetVoiceState( AudioVoiceHandle voice, out AudioPlaybackState playbackState - ) - => AudioExecutionContext.current.TryGetVoiceState(voice, out playbackState); + ) => AudioExecutionContext.current.TryGetVoiceState(voice, out playbackState); /// /// Updates linear gain for a semantic mixer bus. @@ -214,7 +175,7 @@ out AudioPlaybackState playbackState /// when the bus exists and was updated. /// public static bool SetBusVolume( - AudioBusId bus, + AudioBusID bus, float volume ) => AudioExecutionContext.current.SetBusVolume(bus, volume); @@ -231,7 +192,7 @@ float volume /// when the bus exists and was updated. /// public static bool SetBusMuted( - AudioBusId bus, + AudioBusID bus, bool muted ) => AudioExecutionContext.current.SetBusMuted(bus, muted); @@ -248,7 +209,7 @@ bool muted /// when the bus exists and was updated. /// public static bool SetBusPaused( - AudioBusId bus, + AudioBusID bus, bool paused ) => AudioExecutionContext.current.SetBusPaused(bus, paused); @@ -271,8 +232,7 @@ public static ValueTask PreloadAsync( AudioClipAsset clip, AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, CancellationToken cancellationToken = default - ) - => AudioExecutionContext.current.PreloadAsync(clip, loadMode, cancellationToken); + ) => AudioExecutionContext.current.PreloadAsync(clip, loadMode, cancellationToken); /// /// Releases one explicit preload retention without interrupting active voices. diff --git a/src/services/audio/Inno.Audio/AudioBusDefinition.cs b/src/services/audio/Inno.Audio/AudioBusDefinition.cs new file mode 100644 index 000000000..4803a1f3e --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusDefinition.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Describes one bus and its ordered processor chain in a compiled mixer graph. +/// +public sealed class AudioBusDefinition +{ + private readonly AudioProcessorConfiguration[] m_processors; + + /// + /// Creates an immutable mixer bus definition. + /// + /// + /// Stable bus identifier. + /// + /// + /// Parent bus identifier, or only for the master bus. + /// + /// + /// Non-negative linear bus gain. + /// + /// + /// Whether output from the bus is initially silenced. + /// + /// + /// Ordered processor chain. + /// + public AudioBusDefinition( + AudioBusID id, + AudioBusID? parent, + float volume, + bool muted, + IEnumerable? processors = null + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid bus identifier is required.", nameof(id)); + } + if (volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (id == AudioBusID.master && parent is not null) + { + throw new ArgumentException("The master bus cannot have a parent.", nameof(parent)); + } + if (id != AudioBusID.master && (parent is null || !parent.Value.isValid)) + { + throw new ArgumentException("A non-master bus requires a valid parent.", nameof(parent)); + } + this.id = id; + this.parent = parent; + this.volume = volume; + this.muted = muted; + m_processors = processors?.ToArray() ?? []; + } + + /// + /// Gets the stable bus identifier. + /// + public AudioBusID id { get; } + + /// + /// Gets the parent bus, or for the master bus. + /// + public AudioBusID? parent { get; } + + /// + /// Gets the initial linear bus gain. + /// + public float volume { get; } + + /// + /// Gets whether output from the bus is initially silenced. + /// + public bool muted { get; } + + /// + /// Gets the ordered immutable processor chain. + /// + public IReadOnlyList processors => Array.AsReadOnly(m_processors); +} diff --git a/src/services/audio/Inno.Audio/AudioBusHandle.cs b/src/services/audio/Inno.Audio/AudioBusHandle.cs new file mode 100644 index 000000000..954a70ecd --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one backend mixer bus within a device generation. +/// +public readonly record struct AudioBusHandle +{ + internal AudioBusHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioBusID.cs b/src/services/audio/Inno.Audio/AudioBusID.cs new file mode 100644 index 000000000..d95bd8cda --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusID.cs @@ -0,0 +1,44 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies a mixer bus without imposing a closed bus catalog. +/// +public readonly record struct AudioBusID +{ + /// + /// Creates an open mixer bus identifier. + /// + /// + /// Globally stable bus protocol value. + /// + public AudioBusID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the mandatory root bus identifier. + /// + public static AudioBusID master { get; } = new("inno.audio.bus.master"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioCapabilities.cs b/src/services/audio/Inno.Audio/AudioCapabilities.cs new file mode 100644 index 000000000..dd5305d21 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCapabilities.cs @@ -0,0 +1,68 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes backend-neutral features and limits for one device generation. +/// +public sealed record AudioCapabilities +{ + /// + /// Creates an immutable audio capability snapshot. + /// + /// + /// Whether clips can be decoded incrementally. + /// + /// + /// Whether voices can start against the audio clock. + /// + /// + /// Whether listener-relative spatial playback is available. + /// + /// + /// Maximum simultaneously active listeners. + /// + /// + /// Device output sample rate in frames per second. + /// + public AudioCapabilities( + bool supportsStreaming, + bool supportsScheduledPlayback, + bool supportsSpatialAudio, + int maxListeners, + int sampleRate + ) { + ArgumentOutOfRangeException.ThrowIfNegative(maxListeners); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); + this.supportsStreaming = supportsStreaming; + this.supportsScheduledPlayback = supportsScheduledPlayback; + this.supportsSpatialAudio = supportsSpatialAudio; + this.maxListeners = maxListeners; + this.sampleRate = sampleRate; + } + + /// + /// Gets whether clips can be decoded incrementally. + /// + public bool supportsStreaming { get; } + + /// + /// Gets whether voices can start against the audio clock. + /// + public bool supportsScheduledPlayback { get; } + + /// + /// Gets whether listener-relative spatial playback is available. + /// + public bool supportsSpatialAudio { get; } + + /// + /// Gets the maximum simultaneously active listener count. + /// + public int maxListeners { get; } + + /// + /// Gets the output sample rate in frames per second. + /// + public int sampleRate { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioClipAsset.cs b/src/services/audio/Inno.Audio/AudioClipAsset.cs index 646708505..41abee7e4 100644 --- a/src/services/audio/Inno.Audio/AudioClipAsset.cs +++ b/src/services/audio/Inno.Audio/AudioClipAsset.cs @@ -1,157 +1,13 @@ using System; -using System.Buffers.Binary; -using System.Text; using Inno.Assets; using Inno.Extensibility.Types; namespace Inno.Audio; -/// -/// Describes imported encoded audio independently from its runtime storage path. -/// -public readonly record struct AudioClipMetadata -{ - /// - /// Creates imported audio metadata. - /// - /// - /// Codec protocol of the encoded artifact. - /// - /// - /// Encoded channel count. - /// - /// - /// Sample rate in frames per second. - /// - /// - /// Total decoded frame count. - /// - /// - /// Encoded artifact length in bytes. - /// - public AudioClipMetadata( - AudioCodecId codec, - int channels, - int sampleRate, - long frameCount, - long encodedByteLength - ) { - if (!codec.isValid) - throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); - ArgumentOutOfRangeException.ThrowIfNegative(frameCount); - ArgumentOutOfRangeException.ThrowIfNegative(encodedByteLength); - this.codec = codec; - this.channels = channels; - this.sampleRate = sampleRate; - this.frameCount = frameCount; - this.encodedByteLength = encodedByteLength; - } - - /// - /// Gets the codec protocol of the encoded artifact. - /// - public AudioCodecId codec { get; } - - /// - /// Gets the encoded channel count. - /// - public int channels { get; } - - /// - /// Gets the sample rate in frames per second. - /// - public int sampleRate { get; } - - /// - /// Gets the total decoded frame count. - /// - public long frameCount { get; } - - /// - /// Gets the encoded artifact length in bytes. - /// - public long encodedByteLength { get; } - - /// - /// Gets the clip duration derived from frame count and sample rate. - /// - public TimeSpan duration => TimeSpan.FromSeconds((double)frameCount / sampleRate); -} - -/// -/// Encodes the compact runtime header shared by audio importers and runtime asset loading. -/// -public static class AudioClipMetadataCodec -{ - private const uint C_MAGIC = 0x44554149; - private const int C_FIXED_SIZE = 32; - - /// - /// Encodes audio metadata into a compact deterministic runtime header. - /// - /// - /// Valid metadata to encode. - /// - /// - /// Newly allocated runtime header bytes. - /// - public static byte[] Encode(AudioClipMetadata metadata) - { - byte[] codec = Encoding.UTF8.GetBytes(metadata.codec.value); - if (codec.Length > byte.MaxValue) - throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); - byte[] output = new byte[C_FIXED_SIZE + codec.Length]; - BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); - output[4] = (byte)codec.Length; - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(8, 4), metadata.channels); - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(12, 4), metadata.sampleRate); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(16, 8), metadata.frameCount); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(24, 8), metadata.encodedByteLength); - codec.CopyTo(output.AsSpan(C_FIXED_SIZE)); - return output; - } - - /// - /// Decodes and validates one compact audio runtime header. - /// - /// - /// Complete runtime header bytes. - /// - /// - /// Valid imported audio metadata. - /// - /// - /// Thrown when the header is truncated, corrupt, or semantically invalid. - /// - public static AudioClipMetadata Decode(ReadOnlySpan payload) - { - if (payload.Length < C_FIXED_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) - throw new InvalidOperationException("The audio runtime header is invalid."); - int codecLength = payload[4]; - if (payload.Length != C_FIXED_SIZE + codecLength || codecLength == 0) - throw new InvalidOperationException("The audio runtime header length is invalid."); - try - { - return new AudioClipMetadata( - new AudioCodecId(Encoding.UTF8.GetString(payload[C_FIXED_SIZE..])), - BinaryPrimitives.ReadInt32LittleEndian(payload[8..12]), - BinaryPrimitives.ReadInt32LittleEndian(payload[12..16]), - BinaryPrimitives.ReadInt64LittleEndian(payload[16..24]), - BinaryPrimitives.ReadInt64LittleEndian(payload[24..32])); - } - catch (ArgumentException exception) - { - throw new InvalidOperationException("The audio runtime header contains invalid metadata.", exception); - } - } -} - /// /// Represents one imported audio source and its compact runtime metadata. /// -[StableTypeId("c64bbcb2-f7ee-48f2-85df-4506dc7b86d5")] +[StableTypeID("c64bbcb2-f7ee-48f2-85df-4506dc7b86d5")] public sealed class AudioClipAsset : AssetObject { private AudioClipMetadata? m_metadata; @@ -178,9 +34,7 @@ public sealed class AudioClipAsset : AssetObject protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_metadata = currentPayload.IsEmpty - ? null - : AudioClipMetadataCodec.Decode(currentPayload.Span); - } + ) => m_metadata = currentPayload.IsEmpty + ? null + : AudioClipMetadataCodec.Decode(currentPayload.Span); } diff --git a/src/services/audio/Inno.Audio/AudioClipDescriptor.cs b/src/services/audio/Inno.Audio/AudioClipDescriptor.cs index 134980051..55774c856 100644 --- a/src/services/audio/Inno.Audio/AudioClipDescriptor.cs +++ b/src/services/audio/Inno.Audio/AudioClipDescriptor.cs @@ -32,7 +32,7 @@ public readonly record struct AudioClipDescriptor /// The load mode is undefined or a channel, rate, frame, or byte count is outside its valid range. /// public AudioClipDescriptor( - AudioCodecId codec, + AudioCodecID codec, AudioClipLoadMode loadMode, int channels, int sampleRate, @@ -40,9 +40,13 @@ public AudioClipDescriptor( long encodedByteLength ) { if (!codec.isValid) + { throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); + } if (!Enum.IsDefined(loadMode)) + { throw new ArgumentOutOfRangeException(nameof(loadMode)); + } ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); ArgumentOutOfRangeException.ThrowIfNegative(frameCount); @@ -58,7 +62,7 @@ long encodedByteLength /// /// Gets the encoded codec protocol. /// - public AudioCodecId codec { get; } + public AudioCodecID codec { get; } /// /// Gets the required storage strategy. @@ -84,5 +88,4 @@ long encodedByteLength /// Gets the encoded artifact length in bytes. /// public long encodedByteLength { get; } - } diff --git a/src/services/audio/Inno.Audio/AudioClipHandle.cs b/src/services/audio/Inno.Audio/AudioClipHandle.cs new file mode 100644 index 000000000..12837a1c7 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one backend clip allocation within a device generation. +/// +public readonly record struct AudioClipHandle +{ + internal AudioClipHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioClipLoadMode.cs b/src/services/audio/Inno.Audio/AudioClipLoadMode.cs new file mode 100644 index 000000000..67c146c3d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipLoadMode.cs @@ -0,0 +1,20 @@ +namespace Inno.Audio; + +/// +/// Selects how encoded clip data is prepared for playback. +/// +public enum AudioClipLoadMode +{ + /// + /// Lets the runtime choose between decoded and streamed storage. + /// + Automatic, + /// + /// Decodes the complete clip before playback. + /// + Decode, + /// + /// Decodes encoded data incrementally while playback advances. + /// + Stream +} diff --git a/src/services/audio/Inno.Audio/AudioClipMetadata.cs b/src/services/audio/Inno.Audio/AudioClipMetadata.cs new file mode 100644 index 000000000..f2464ce52 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipMetadata.cs @@ -0,0 +1,79 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes imported encoded audio independently from its runtime storage path. +/// +public readonly record struct AudioClipMetadata +{ + /// + /// Creates imported audio metadata. + /// + /// + /// Codec protocol of the encoded artifact. + /// + /// + /// Encoded channel count. + /// + /// + /// Sample rate in frames per second. + /// + /// + /// Total decoded frame count. + /// + /// + /// Encoded artifact length in bytes. + /// + public AudioClipMetadata( + AudioCodecID codec, + int channels, + int sampleRate, + long frameCount, + long encodedByteLength + ) { + if (!codec.isValid) + { + throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); + } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); + ArgumentOutOfRangeException.ThrowIfNegative(frameCount); + ArgumentOutOfRangeException.ThrowIfNegative(encodedByteLength); + this.codec = codec; + this.channels = channels; + this.sampleRate = sampleRate; + this.frameCount = frameCount; + this.encodedByteLength = encodedByteLength; + } + + /// + /// Gets the codec protocol of the encoded artifact. + /// + public AudioCodecID codec { get; } + + /// + /// Gets the encoded channel count. + /// + public int channels { get; } + + /// + /// Gets the sample rate in frames per second. + /// + public int sampleRate { get; } + + /// + /// Gets the total decoded frame count. + /// + public long frameCount { get; } + + /// + /// Gets the encoded artifact length in bytes. + /// + public long encodedByteLength { get; } + + /// + /// Gets the clip duration derived from frame count and sample rate. + /// + public TimeSpan duration => TimeSpan.FromSeconds((double)frameCount / sampleRate); +} diff --git a/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs b/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs new file mode 100644 index 000000000..7e7dd17d3 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs @@ -0,0 +1,80 @@ +using System; +using System.Buffers.Binary; +using System.Text; + +namespace Inno.Audio; + +/// +/// Encodes the compact runtime header shared by audio importers and runtime asset loading. +/// +public static class AudioClipMetadataCodec +{ + private const uint C_MAGIC = 0x4455_4149; + private const int C_FIXED_SIZE = 32; + + /// + /// Encodes audio metadata into a compact deterministic runtime header. + /// + /// + /// Valid metadata to encode. + /// + /// + /// Newly allocated runtime header bytes. + /// + public static byte[] Encode(AudioClipMetadata metadata) + { + byte[] codec = Encoding.UTF8.GetBytes(metadata.codec.value); + if (codec.Length > byte.MaxValue) + { + throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); + } + var output = new byte[C_FIXED_SIZE + codec.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); + output[4] = (byte)codec.Length; + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(8, 4), metadata.channels); + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(12, 4), metadata.sampleRate); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(16, 8), metadata.frameCount); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(24, 8), metadata.encodedByteLength); + codec.CopyTo(output.AsSpan(C_FIXED_SIZE)); + return output; + } + + /// + /// Decodes and validates one compact audio runtime header. + /// + /// + /// Complete runtime header bytes. + /// + /// + /// Valid imported audio metadata. + /// + /// + /// Thrown when the header is truncated, corrupt, or semantically invalid. + /// + public static AudioClipMetadata Decode(ReadOnlySpan payload) + { + if (payload.Length < C_FIXED_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { + throw new InvalidOperationException("The audio runtime header is invalid."); + } + int codecLength = payload[4]; + if (payload.Length != C_FIXED_SIZE + codecLength || codecLength == 0) + { + throw new InvalidOperationException("The audio runtime header length is invalid."); + } + try + { + return new AudioClipMetadata( + new AudioCodecID(Encoding.UTF8.GetString(payload[C_FIXED_SIZE..])), + BinaryPrimitives.ReadInt32LittleEndian(payload[8..12]), + BinaryPrimitives.ReadInt32LittleEndian(payload[12..16]), + BinaryPrimitives.ReadInt64LittleEndian(payload[16..24]), + BinaryPrimitives.ReadInt64LittleEndian(payload[24..32]) + ); + } + catch (ArgumentException exception) + { + throw new InvalidOperationException("The audio runtime header contains invalid metadata.", exception); + } + } +} diff --git a/src/services/audio/Inno.Audio/AudioCodecID.cs b/src/services/audio/Inno.Audio/AudioCodecID.cs new file mode 100644 index 000000000..b44c11a76 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCodecID.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies encoded audio data without constraining codec providers to a closed enum. +/// +public readonly record struct AudioCodecID +{ + /// + /// Creates an open codec identifier. + /// + /// + /// Globally stable codec protocol value. + /// + public AudioCodecID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard Waveform Audio codec identifier. + /// + public static AudioCodecID wav { get; } = new("audio/wav"); + + /// + /// Gets the standard Free Lossless Audio Codec identifier. + /// + public static AudioCodecID flac { get; } = new("audio/flac"); + + /// + /// Gets the standard MPEG Layer III codec identifier. + /// + public static AudioCodecID mp3 { get; } = new("audio/mpeg"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioCompletionReason.cs b/src/services/audio/Inno.Audio/AudioCompletionReason.cs new file mode 100644 index 000000000..2c7fe4f25 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCompletionReason.cs @@ -0,0 +1,28 @@ +namespace Inno.Audio; + +/// +/// Explains why a voice stopped accepting playback commands. +/// +public enum AudioCompletionReason +{ + /// + /// The clip reached its natural end. + /// + NaturalEnd, + /// + /// A caller explicitly stopped the voice. + /// + Stopped, + /// + /// The runtime reclaimed the voice to satisfy its voice budget. + /// + Stolen, + /// + /// Encoded data could not be prepared or decoded. + /// + DecodeFailed, + /// + /// Playback ended because the owning device generation was lost. + /// + DeviceLost +} diff --git a/src/services/audio/Inno.Audio/AudioContentProvider.cs b/src/services/audio/Inno.Audio/AudioContentProvider.cs index 09cd4ec3c..181dc8134 100644 --- a/src/services/audio/Inno.Audio/AudioContentProvider.cs +++ b/src/services/audio/Inno.Audio/AudioContentProvider.cs @@ -1,251 +1,8 @@ -using Inno.References; using System; -using System.Collections.Generic; using Inno.Core.Execution; namespace Inno.Audio; -/// -/// Marks a reloadable provider that converts host content into immutable audio snapshots. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioContentProviderExtensionAttribute : Attribute -{ - /// - /// Creates an audio content provider declaration. - /// - /// - /// Globally stable provider identifier. - /// - /// - /// Provider invocation priority; lower values run first. - /// - public AudioContentProviderExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable provider identifier. - /// - public string id { get; } - - /// - /// Gets the provider invocation priority. - /// - public int priority { get; } -} - -/// -/// Collects one bounded, atomic provider contribution on the owning control thread. -/// -/// -/// The host disposes this borrowed context when the provider returns. A rejected submission invalidates the -/// entire contribution, even if the provider catches the exception. The context does not own the content scope. -/// -public sealed class AudioContentProviderContext : IDisposable -{ - private readonly List m_emitters = []; - private readonly List m_listeners = []; - private readonly HashSet m_ids = []; - private readonly int m_ownerThread = Environment.CurrentManagedThreadId; - private ContentReadScope? m_content; - private bool m_rejected; - - /// - /// Opens a control-thread snapshot collector over one content read scope. - /// - /// - /// The caller-owned identity read scope. - /// - /// - /// Finite non-negative time elapsed since the previous update. - /// - /// - /// Maximum combined emitter and listener count accepted by this contribution. Zero permits an empty contribution only. - /// - /// - /// The elapsed time is invalid or capacity is negative. - /// - /// - /// The borrowed content scope is null. - /// - public AudioContentProviderContext( - ContentReadScope content, - float deltaTime, - int capacity = 1024 - ) { - ArgumentNullException.ThrowIfNull(content); - if (!float.IsFinite(deltaTime) || deltaTime < 0f) - throw new ArgumentOutOfRangeException(nameof(deltaTime)); - ArgumentOutOfRangeException.ThrowIfNegative(capacity); - m_content = content; - this.deltaTime = deltaTime; - this.capacity = capacity; - } - - /// - /// Gets explicit host content visible during this update. - /// - /// - /// This provider invocation has ended. - /// - /// - /// Access occurs off the owning control thread or a submission was rejected. - /// - public ContentReadScope content - { - get - { - EnsureActive(); - return m_content!; - } - } - - /// - /// Gets non-negative elapsed frame time in seconds. - /// - public float deltaTime { get; } - - /// - /// Gets the immutable combined snapshot budget assigned to this invocation. - /// - public int capacity { get; } - - /// - /// Submits one immutable emitter snapshot for runtime synchronization. - /// - /// - /// Current state for one stable emitter identity. - /// - /// - /// The emitter is uninitialized or its identity duplicates a submission in this contribution. - /// - /// - /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. - /// - /// - /// This provider invocation has ended. - /// - public void Submit(AudioEmitterSnapshot emitter) - { - EnsureActive(); - if (emitter.clip is null || !emitter.options.bus.isValid) - { - m_rejected = true; - throw new ArgumentException("An audio emitter requires an initialized clip and playback options.", nameof(emitter)); - } - Admit(emitter.id); - m_emitters.Add(emitter); - } - - /// - /// Submits one immutable listener snapshot for runtime selection. - /// - /// - /// Current state for one stable listener identity. - /// - /// - /// The listener is uninitialized or its identity duplicates a submission in this contribution. - /// - /// - /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. - /// - /// - /// This provider invocation has ended. - /// - public void Submit(AudioListenerSnapshot listener) - { - EnsureActive(); - Admit(listener.id); - m_listeners.Add(listener); - } - - /// - /// Gets a frozen copy of submitted source state in provider order. - /// - /// - /// This provider invocation has ended. - /// - /// - /// The contribution was rejected or access occurs off the owning control thread. - /// - public IReadOnlyList emitters - { - get - { - EnsureActive(); - return Array.AsReadOnly(m_emitters.ToArray()); - } - } - - /// - /// Gets a frozen copy of submitted listener state in provider order. - /// - /// - /// This provider invocation has ended. - /// - /// - /// The contribution was rejected or access occurs off the owning control thread. - /// - public IReadOnlyList listeners - { - get - { - EnsureActive(); - return Array.AsReadOnly(m_listeners.ToArray()); - } - } - - /// - /// Revokes submission and releases collected references without disposing the borrowed content scope. - /// - /// - /// Disposal occurs off the owning control thread. - /// - public void Dispose() - { - EnsureOwnerThread(); - m_content = null; - m_emitters.Clear(); - m_listeners.Clear(); - m_ids.Clear(); - } - - private void Admit(Guid id) - { - if (id == Guid.Empty || m_ids.Contains(id)) - { - m_rejected = true; - throw new ArgumentException($"Audio content identity '{id:D}' is empty or duplicated."); - } - if (m_ids.Count >= capacity) - { - m_rejected = true; - throw new InvalidOperationException("The audio content contribution exceeds its snapshot capacity."); - } - m_ids.Add(id); - } - - private void EnsureActive() - { - EnsureOwnerThread(); - ObjectDisposedException.ThrowIf(m_content is null, this); - if (m_rejected) - throw new InvalidOperationException("The audio content contribution contains a rejected submission."); - } - - private void EnsureOwnerThread() - { - if (Environment.CurrentManagedThreadId != m_ownerThread) - throw new InvalidOperationException("Audio content collection requires its owning control thread."); - } -} - /// /// Converts arbitrary host-owned content into backend-neutral emitter and listener snapshots. /// @@ -270,7 +27,9 @@ public abstract class AudioContentProvider : IDisposable public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -294,7 +53,5 @@ public void Dispose() /// /// Always for explicit disposal. /// - protected virtual void Dispose(bool disposing) - { - } + protected virtual void Dispose(bool disposing) {} } diff --git a/src/services/audio/Inno.Audio/AudioContentProviderContext.cs b/src/services/audio/Inno.Audio/AudioContentProviderContext.cs new file mode 100644 index 000000000..99e6c2464 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioContentProviderContext.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using Inno.References; + +namespace Inno.Audio; + +/// +/// Collects one bounded, atomic provider contribution on the owning control thread. +/// +/// +/// The host disposes this borrowed context when the provider returns. A rejected submission invalidates the +/// entire contribution, even if the provider catches the exception. The context does not own the content scope. +/// +public sealed class AudioContentProviderContext : IDisposable +{ + private readonly List m_emitters = []; + private readonly List m_listeners = []; + private readonly HashSet m_ids = []; + private readonly int m_ownerThread = Environment.CurrentManagedThreadId; + private ContentReadScope? m_content; + private bool m_rejected; + + /// + /// Opens a control-thread snapshot collector over one content read scope. + /// + /// + /// The caller-owned identity read scope. + /// + /// + /// Finite non-negative time elapsed since the previous update. + /// + /// + /// Maximum combined emitter and listener count accepted by this contribution. Zero permits an empty contribution only. + /// + /// + /// The elapsed time is invalid or capacity is negative. + /// + /// + /// The borrowed content scope is null. + /// + public AudioContentProviderContext( + ContentReadScope content, + float deltaTime, + int capacity = 1024 + ) { + ArgumentNullException.ThrowIfNull(content); + if (!float.IsFinite(deltaTime) || deltaTime < 0f) + { + throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); + m_content = content; + this.deltaTime = deltaTime; + this.capacity = capacity; + } + + /// + /// Gets explicit host content visible during this update. + /// + /// + /// This provider invocation has ended. + /// + /// + /// Access occurs off the owning control thread or a submission was rejected. + /// + public ContentReadScope content + { + get + { + EnsureActive(); + return m_content!; + } + } + + /// + /// Gets non-negative elapsed frame time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets the immutable combined snapshot budget assigned to this invocation. + /// + public int capacity { get; } + + /// + /// Gets a frozen copy of submitted source state in provider order. + /// + /// + /// This provider invocation has ended. + /// + /// + /// The contribution was rejected or access occurs off the owning control thread. + /// + public IReadOnlyList emitters + { + get + { + EnsureActive(); + return Array.AsReadOnly(m_emitters.ToArray()); + } + } + + /// + /// Gets a frozen copy of submitted listener state in provider order. + /// + /// + /// This provider invocation has ended. + /// + /// + /// The contribution was rejected or access occurs off the owning control thread. + /// + public IReadOnlyList listeners + { + get + { + EnsureActive(); + return Array.AsReadOnly(m_listeners.ToArray()); + } + } + + /// + /// Submits one immutable emitter snapshot for runtime synchronization. + /// + /// + /// Current state for one stable emitter identity. + /// + /// + /// The emitter is uninitialized or its identity duplicates a submission in this contribution. + /// + /// + /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. + /// + /// + /// This provider invocation has ended. + /// + public void Submit(AudioEmitterSnapshot emitter) + { + EnsureActive(); + if (emitter.clip is null || !emitter.options.bus.isValid) + { + m_rejected = true; + throw new ArgumentException("An audio emitter requires an initialized clip and playback options.", nameof(emitter)); + } + Admit(emitter.id); + m_emitters.Add(emitter); + } + + /// + /// Submits one immutable listener snapshot for runtime selection. + /// + /// + /// Current state for one stable listener identity. + /// + /// + /// The listener is uninitialized or its identity duplicates a submission in this contribution. + /// + /// + /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. + /// + /// + /// This provider invocation has ended. + /// + public void Submit(AudioListenerSnapshot listener) + { + EnsureActive(); + Admit(listener.id); + m_listeners.Add(listener); + } + + /// + /// Revokes submission and releases collected references without disposing the borrowed content scope. + /// + /// + /// Disposal occurs off the owning control thread. + /// + public void Dispose() + { + EnsureOwnerThread(); + m_content = null; + m_emitters.Clear(); + m_listeners.Clear(); + m_ids.Clear(); + } + + private void Admit(Guid id) + { + if (id == Guid.Empty || m_ids.Contains(id)) + { + m_rejected = true; + throw new ArgumentException($"Audio content identity '{id:D}' is empty or duplicated."); + } + if (m_ids.Count >= capacity) + { + m_rejected = true; + throw new InvalidOperationException("The audio content contribution exceeds its snapshot capacity."); + } + m_ids.Add(id); + } + + private void EnsureActive() + { + EnsureOwnerThread(); + ObjectDisposedException.ThrowIf(m_content is null, this); + if (m_rejected) + { + throw new InvalidOperationException("The audio content contribution contains a rejected submission."); + } + } + + private void EnsureOwnerThread() + { + if (Environment.CurrentManagedThreadId != m_ownerThread) + { + throw new InvalidOperationException("Audio content collection requires its owning control thread."); + } + } +} diff --git a/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs new file mode 100644 index 000000000..ac7b1be50 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable provider that converts host content into immutable audio snapshots. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioContentProviderExtensionAttribute : Attribute +{ + /// + /// Creates an audio content provider declaration. + /// + /// + /// Globally stable provider identifier. + /// + /// + /// Provider invocation priority; lower values run first. + /// + public AudioContentProviderExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable provider identifier. + /// + public string id { get; } + + /// + /// Gets the provider invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioDevice.cs b/src/services/audio/Inno.Audio/AudioDevice.cs index a371b6e6e..6ce7904ff 100644 --- a/src/services/audio/Inno.Audio/AudioDevice.cs +++ b/src/services/audio/Inno.Audio/AudioDevice.cs @@ -5,20 +5,6 @@ namespace Inno.Audio; /// public abstract class AudioDevice { - /// - /// Stores one decoded device-owned identity. - /// - /// - /// Non-zero backend resource identity. - /// - /// - /// Device generation that owns the resource. - /// - protected readonly record struct DeviceHandleIdentity( - ulong value, - uint generation - ); - /// /// Encodes a clip identity into a backend-neutral handle. /// @@ -130,4 +116,18 @@ uint generation /// Backend identity and owning generation. /// protected static DeviceHandleIdentity GetHandleIdentity(AudioListenerHandle handle) => new(handle.value, handle.deviceGeneration); + + /// + /// Stores one decoded device-owned identity. + /// + /// + /// Non-zero backend resource identity. + /// + /// + /// Device generation that owns the resource. + /// + protected readonly record struct DeviceHandleIdentity( + ulong value, + uint generation + ); } diff --git a/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs b/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs new file mode 100644 index 000000000..ba05cfcbb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs @@ -0,0 +1,40 @@ +using System; + +namespace Inno.Audio; + +/// +/// Reports one backend-detected terminal voice transition. +/// +public readonly record struct AudioDeviceCompletion +{ + /// + /// Creates a backend voice completion record. + /// + /// + /// Voice that reached a terminal state. + /// + /// + /// Reason playback ended. + /// + public AudioDeviceCompletion( + AudioDeviceVoiceHandle voice, + AudioCompletionReason reason + ) { + if (!voice.isValid) + { + throw new ArgumentException("A valid voice handle is required.", nameof(voice)); + } + this.voice = voice; + this.reason = reason; + } + + /// + /// Gets the completed voice handle. + /// + public AudioDeviceVoiceHandle voice { get; } + + /// + /// Gets the terminal playback reason. + /// + public AudioCompletionReason reason { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs index 48cc6d838..4073ec4b8 100644 --- a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs +++ b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs @@ -23,8 +23,8 @@ public sealed class AudioDeviceLimits /// A capacity is not positive. /// public AudioDeviceLimits( - int clips = 16384, - int voices = 65536, + int clips = 16_384, + int voices = 65_536, int buses = 4096 ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(clips); @@ -39,10 +39,12 @@ public AudioDeviceLimits( /// Gets the maximum retained clip count. /// public int clips { get; } + /// /// Gets the combined voice and undelivered completion capacity. /// public int voices { get; } + /// /// Gets the maximum retained bus count. /// diff --git a/src/services/audio/Inno.Audio/AudioDeviceState.cs b/src/services/audio/Inno.Audio/AudioDeviceState.cs new file mode 100644 index 000000000..18052e5ba --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDeviceState.cs @@ -0,0 +1,28 @@ +namespace Inno.Audio; + +/// +/// Describes the availability of the active audio output generation. +/// +public enum AudioDeviceState +{ + /// + /// The device has not completed initialization. + /// + Initializing, + /// + /// The device is available for audible playback. + /// + Ready, + /// + /// Playback is advancing without an output device. + /// + Muted, + /// + /// The active output device was lost and recovery is pending. + /// + Lost, + /// + /// The device has been released and cannot accept work. + /// + Disposed +} diff --git a/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs b/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs index 5423cf792..2dde924d1 100644 --- a/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs +++ b/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs @@ -14,10 +14,12 @@ uint deviceGeneration } internal ulong value { get; } + /// /// Gets the backend device generation that owns this voice. /// public uint deviceGeneration { get; } + /// /// Gets whether this value identifies a backend allocation. /// diff --git a/src/services/audio/Inno.Audio/AudioDistanceModel.cs b/src/services/audio/Inno.Audio/AudioDistanceModel.cs new file mode 100644 index 000000000..5a81cb270 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDistanceModel.cs @@ -0,0 +1,24 @@ +namespace Inno.Audio; + +/// +/// Selects the distance attenuation model for one spatial voice. +/// +public enum AudioDistanceModel +{ + /// + /// Disables distance attenuation while retaining spatial direction. + /// + None, + /// + /// Uses inverse-distance attenuation. + /// + Inverse, + /// + /// Uses linear-distance attenuation. + /// + Linear, + /// + /// Uses exponential-distance attenuation. + /// + Exponential +} diff --git a/src/services/audio/Inno.Audio/AudioContent.cs b/src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs similarity index 56% rename from src/services/audio/Inno.Audio/AudioContent.cs rename to src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs index 3f78606a7..9219f23f8 100644 --- a/src/services/audio/Inno.Audio/AudioContent.cs +++ b/src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs @@ -32,10 +32,13 @@ public AudioEmitterSnapshot( bool shouldPlay, ulong playbackRevision = 0 ) { + ArgumentNullException.ThrowIfNull(clip); if (id == Guid.Empty) + { throw new ArgumentException("An emitter identity cannot be empty.", nameof(id)); + } this.id = id; - this.clip = clip ?? throw new ArgumentNullException(nameof(clip)); + this.clip = clip; this.options = options; this.shouldPlay = shouldPlay; this.playbackRevision = playbackRevision; @@ -66,58 +69,3 @@ public AudioEmitterSnapshot( /// public ulong playbackRevision { get; } } - -/// -/// Describes one immutable listener candidate produced by a content provider. -/// -public readonly record struct AudioListenerSnapshot -{ - /// - /// Creates an immutable listener snapshot. - /// - /// - /// Stable listener identity across updates. - /// - /// - /// Selection priority; larger values win. - /// - /// - /// Current listener transform. - /// - /// - /// Whether the listener is eligible for selection. - /// - public AudioListenerSnapshot( - Guid id, - int priority, - AudioListenerState state, - bool active - ) { - if (id == Guid.Empty) - throw new ArgumentException("A listener identity cannot be empty.", nameof(id)); - this.id = id; - this.priority = priority; - this.state = state; - this.active = active; - } - - /// - /// Gets the stable listener identity. - /// - public Guid id { get; } - - /// - /// Gets the selection priority. - /// - public int priority { get; } - - /// - /// Gets the current listener transform. - /// - public AudioListenerState state { get; } - - /// - /// Gets whether the listener is eligible for selection. - /// - public bool active { get; } -} diff --git a/src/services/audio/Inno.Audio/AudioExecutionContext.cs b/src/services/audio/Inno.Audio/AudioExecutionContext.cs new file mode 100644 index 000000000..571a84b10 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioExecutionContext.cs @@ -0,0 +1,38 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Audio; + +/// +/// Binds one host-owned audio service to the current asynchronous execution context. +/// +public static class AudioExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("audio"); + + /// + /// Gets the audio service bound to the current asynchronous execution context. + /// + /// + /// Thrown when no audio service is active for the caller. + /// + public static IAudioService current => CURRENT_SCOPE.current; + + /// + /// Binds an audio service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// Host-owned audio service exposed to script-facing operations. + /// + /// + /// A strict last-in-first-out scope owned by the caller. + /// + /// + /// Thrown when is . + /// + public static IDisposable EnterScope(IAudioService audio) + { + ArgumentNullException.ThrowIfNull(audio); + return CURRENT_SCOPE.Enter(audio); + } +} diff --git a/src/services/audio/Inno.Audio/AudioHandles.cs b/src/services/audio/Inno.Audio/AudioHandles.cs deleted file mode 100644 index e16b4820b..000000000 --- a/src/services/audio/Inno.Audio/AudioHandles.cs +++ /dev/null @@ -1,105 +0,0 @@ -namespace Inno.Audio; - -/// -/// Identifies one backend clip allocation within a device generation. -/// -public readonly record struct AudioClipHandle -{ - internal AudioClipHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies one playback voice within a device generation. -/// -public readonly record struct AudioVoiceHandle -{ - internal AudioVoiceHandle( - ulong value, - uint ownerGeneration - ) { - this.value = value; - this.ownerGeneration = ownerGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint ownerGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && ownerGeneration != 0; -} - -/// -/// Identifies one backend mixer bus within a device generation. -/// -public readonly record struct AudioBusHandle -{ - internal AudioBusHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies one spatial listener within a device generation. -/// -public readonly record struct AudioListenerHandle -{ - internal AudioListenerHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} diff --git a/src/services/audio/Inno.Audio/AudioListenerHandle.cs b/src/services/audio/Inno.Audio/AudioListenerHandle.cs new file mode 100644 index 000000000..349d7744e --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one spatial listener within a device generation. +/// +public readonly record struct AudioListenerHandle +{ + internal AudioListenerHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs b/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs new file mode 100644 index 000000000..7fd6c540a --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes one immutable listener candidate produced by a content provider. +/// +public readonly record struct AudioListenerSnapshot +{ + /// + /// Creates an immutable listener snapshot. + /// + /// + /// Stable listener identity across updates. + /// + /// + /// Selection priority; larger values win. + /// + /// + /// Current listener transform. + /// + /// + /// Whether the listener is eligible for selection. + /// + public AudioListenerSnapshot( + Guid id, + int priority, + AudioListenerState state, + bool active + ) { + if (id == Guid.Empty) + { + throw new ArgumentException("A listener identity cannot be empty.", nameof(id)); + } + this.id = id; + this.priority = priority; + this.state = state; + this.active = active; + } + + /// + /// Gets the stable listener identity. + /// + public Guid id { get; } + + /// + /// Gets the selection priority. + /// + public int priority { get; } + + /// + /// Gets the current listener transform. + /// + public AudioListenerState state { get; } + + /// + /// Gets whether the listener is eligible for selection. + /// + public bool active { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioListenerState.cs b/src/services/audio/Inno.Audio/AudioListenerState.cs new file mode 100644 index 000000000..029e78e0c --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerState.cs @@ -0,0 +1,64 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Audio; + +/// +/// Contains one listener transform used by backend spatialization. +/// +public readonly record struct AudioListenerState +{ + /// + /// Creates a listener transform snapshot. + /// + /// + /// World-space listener position. + /// + /// + /// World-space listener forward direction. + /// + /// + /// World-space listener up direction. + /// + /// + /// World-space listener velocity. + /// + /// + /// Any position, direction, up, or velocity component is non-finite. + /// + public AudioListenerState( + Vector3 position, + Vector3 direction, + Vector3 up, + Vector3 velocity + ) { + AudioValueValidation.RequireFinite(position, nameof(position)); + AudioValueValidation.RequireFinite(direction, nameof(direction)); + AudioValueValidation.RequireFinite(up, nameof(up)); + AudioValueValidation.RequireFinite(velocity, nameof(velocity)); + this.position = position; + this.direction = direction; + this.up = up; + this.velocity = velocity; + } + + /// + /// Gets the world-space listener position. + /// + public Vector3 position { get; } + + /// + /// Gets the world-space listener forward direction. + /// + public Vector3 direction { get; } + + /// + /// Gets the world-space listener up direction. + /// + public Vector3 up { get; } + + /// + /// Gets the world-space listener velocity. + /// + public Vector3 velocity { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioMixer.cs b/src/services/audio/Inno.Audio/AudioMixer.cs index f61b43145..50051dd59 100644 --- a/src/services/audio/Inno.Audio/AudioMixer.cs +++ b/src/services/audio/Inno.Audio/AudioMixer.cs @@ -1,159 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Assets; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; namespace Inno.Audio; -/// -/// Stores one neutral numeric parameter assigned to an audio processor. -/// -public readonly record struct AudioProcessorParameter -{ - /// - /// Creates a processor parameter value. - /// - /// - /// Open parameter identifier understood by the processor protocol. - /// - /// - /// Neutral numeric value interpreted by the processor. - /// - public AudioProcessorParameter( - AudioParameterId id, - float value - ) { - if (!id.isValid) - throw new ArgumentException("A valid parameter identifier is required.", nameof(id)); - this.id = id; - this.value = value; - } - - /// - /// Gets the open parameter identifier. - /// - public AudioParameterId id { get; } - - /// - /// Gets the neutral numeric value. - /// - public float value { get; } -} - -/// -/// Describes one ordered processor instance attached to a mixer bus. -/// -public sealed class AudioProcessorConfiguration -{ - private readonly AudioProcessorParameter[] m_parameters; - - /// - /// Creates an immutable processor configuration. - /// - /// - /// Open processor protocol identifier. - /// - /// - /// Complete processor parameter set. - /// - public AudioProcessorConfiguration( - AudioProcessorId id, - IEnumerable? parameters = null - ) { - if (!id.isValid) - throw new ArgumentException("A valid processor identifier is required.", nameof(id)); - this.id = id; - m_parameters = parameters?.ToArray() ?? []; - if (m_parameters.Select(static parameter => parameter.id).Distinct().Count() != m_parameters.Length) - throw new ArgumentException("Processor parameter identifiers must be unique.", nameof(parameters)); - } - - /// - /// Gets the open processor protocol identifier. - /// - public AudioProcessorId id { get; } - - /// - /// Gets the immutable processor parameter set. - /// - public IReadOnlyList parameters => Array.AsReadOnly(m_parameters); -} - -/// -/// Describes one bus and its ordered processor chain in a compiled mixer graph. -/// -public sealed class AudioBusDefinition -{ - private readonly AudioProcessorConfiguration[] m_processors; - - /// - /// Creates an immutable mixer bus definition. - /// - /// - /// Stable bus identifier. - /// - /// - /// Parent bus identifier, or only for the master bus. - /// - /// - /// Non-negative linear bus gain. - /// - /// - /// Whether output from the bus is initially silenced. - /// - /// - /// Ordered processor chain. - /// - public AudioBusDefinition( - AudioBusId id, - AudioBusId? parent, - float volume, - bool muted, - IEnumerable? processors = null - ) { - if (!id.isValid) - throw new ArgumentException("A valid bus identifier is required.", nameof(id)); - if (volume < 0f) - throw new ArgumentOutOfRangeException(nameof(volume)); - if (id == AudioBusId.master && parent is not null) - throw new ArgumentException("The master bus cannot have a parent.", nameof(parent)); - if (id != AudioBusId.master && (parent is null || !parent.Value.isValid)) - throw new ArgumentException("A non-master bus requires a valid parent.", nameof(parent)); - this.id = id; - this.parent = parent; - this.volume = volume; - this.muted = muted; - m_processors = processors?.ToArray() ?? []; - } - - /// - /// Gets the stable bus identifier. - /// - public AudioBusId id { get; } - - /// - /// Gets the parent bus, or for the master bus. - /// - public AudioBusId? parent { get; } - - /// - /// Gets the initial linear bus gain. - /// - public float volume { get; } - - /// - /// Gets whether output from the bus is initially silenced. - /// - public bool muted { get; } - - /// - /// Gets the ordered immutable processor chain. - /// - public IReadOnlyList processors => Array.AsReadOnly(m_processors); -} - /// /// Contains one validated backend-neutral mixer graph. /// @@ -171,242 +21,3 @@ internal AudioMixer(IEnumerable buses) /// public IReadOnlyList buses => Array.AsReadOnly(m_buses); } - -/// -/// Builds and validates an open backend-neutral mixer graph. -/// -public sealed class AudioMixerBuilder -{ - private readonly Dictionary m_buses = new() - { - [AudioBusId.master] = new(AudioBusId.master, null, 1f, false) - }; - - /// - /// Adds one semantic bus to the graph. - /// - /// - /// Stable bus identifier. - /// - /// - /// Parent bus identifier. - /// - /// - /// Initial non-negative linear gain. - /// - /// - /// Whether output is initially silenced. - /// - /// - /// Thrown when the bus identifier is invalid or duplicated. - /// - public void AddBus( - AudioBusId id, - AudioBusId parent, - float volume = 1f, - bool muted = false - ) { - if (!id.isValid || id == AudioBusId.master) - throw new ArgumentException("A valid non-master bus identifier is required.", nameof(id)); - if (m_buses.ContainsKey(id)) - throw new ArgumentException($"Audio bus '{id}' is already defined.", nameof(id)); - m_buses.Add(id, new AudioBusDefinition(id, parent, volume, muted)); - } - - /// - /// Appends one processor to an existing bus chain. - /// - /// - /// Existing bus identifier. - /// - /// - /// Immutable processor configuration to append. - /// - /// - /// Thrown when the bus is not defined. - /// - public void AddProcessor( - AudioBusId bus, - AudioProcessorConfiguration processor - ) { - ArgumentNullException.ThrowIfNull(processor); - if (!m_buses.TryGetValue(bus, out AudioBusDefinition? definition)) - throw new KeyNotFoundException($"Audio bus '{bus}' is not defined."); - m_buses[bus] = new AudioBusDefinition( - definition.id, - definition.parent, - definition.volume, - definition.muted, - definition.processors.Append(processor)); - } - - /// - /// Validates the graph and returns an immutable parent-before-child snapshot. - /// - /// - /// A validated mixer graph containing the mandatory master bus. - /// - /// - /// Thrown when a parent is missing or bus routing contains a cycle. - /// - public AudioMixer Build() - { - var order = new List(m_buses.Count); - var visiting = new HashSet(); - var visited = new HashSet(); - Visit(AudioBusId.master, order, visiting, visited); - foreach (AudioBusId id in m_buses.Keys.OrderBy(static id => id.value, StringComparer.Ordinal)) - Visit(id, order, visiting, visited); - return new AudioMixer(order); - } - - private void Visit( - AudioBusId id, - ICollection order, - ISet visiting, - ISet visited - ) { - if (visited.Contains(id)) - return; - if (!m_buses.TryGetValue(id, out AudioBusDefinition? definition)) - throw new InvalidOperationException($"Audio mixer references missing bus '{id}'."); - if (!visiting.Add(id)) - throw new InvalidOperationException($"Audio mixer bus routing contains a cycle at '{id}'."); - if (definition.parent is AudioBusId parent) - Visit(parent, order, visiting, visited); - visiting.Remove(id); - visited.Add(id); - order.Add(definition); - } -} - -/// -/// Stores reload-safe configuration for one mixer or feature extension generation. -/// -public struct SerializedAudioExtensionState -{ - /// - /// Creates empty extension state for deserialization. - /// - public SerializedAudioExtensionState() - { - propertyData = []; - } - - /// - /// Creates neutral extension state. - /// - /// - /// Stable settings type identity, or empty when no typed settings exist. - /// - /// - /// Neutral serialized property bytes. - /// - public SerializedAudioExtensionState( - Guid stableTypeId, - ReadOnlySpan propertyData - ) { - this.stableTypeId = stableTypeId; - this.propertyData = propertyData.ToArray(); - } - - /// - /// Gets or sets the stable settings type identity. - /// - [SerializableProperty] - public Guid stableTypeId { get; set; } - - /// - /// Gets or sets neutral serialized property bytes. - /// - [SerializableProperty] - public byte[] propertyData { get; set; } -} - -/// -/// Stores one ordered mixer feature selection using only stable data. -/// -public struct AudioMixerFeatureConfiguration -{ - /// - /// Creates an empty feature configuration for deserialization. - /// - public AudioMixerFeatureConfiguration() - { - } - - /// - /// Creates a mixer feature configuration. - /// - /// - /// Globally stable feature extension identifier. - /// - /// - /// Optional reload-safe feature state. - /// - /// - /// Whether the feature participates in graph construction. - /// - public AudioMixerFeatureConfiguration( - string featureTypeId, - SerializedAudioExtensionState? state = null, - bool enabled = true - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeId); - this.featureTypeId = featureTypeId; - this.state = state ?? new SerializedAudioExtensionState(); - this.enabled = enabled; - } - - /// - /// Gets or sets the stable feature extension identifier. - /// - [SerializableProperty] - public string featureTypeId { get; set; } = string.Empty; - - /// - /// Gets or sets reload-safe feature settings. - /// - [SerializableProperty] - public SerializedAudioExtensionState state { get; set; } - - /// - /// Gets or sets whether the feature participates in graph construction. - /// - [SerializableProperty] - public bool enabled { get; set; } = true; -} - -/// -/// Selects a mixer extension and ordered features without defining a game-specific mixing model. -/// -[StableTypeId("6e167326-d078-45e9-ad33-993300ee5fed")] -public sealed class AudioMixerAsset : AssetObject -{ - - /// - /// Gets or sets the globally stable mixer extension identifier. - /// - [SerializableProperty] - public string mixerTypeId { get; set; } = string.Empty; - - /// - /// Gets or sets reload-safe mixer settings. - /// - [SerializableProperty] - public SerializedAudioExtensionState mixerState { get; set; } = new(); - - /// - /// Gets or sets ordered feature configurations. - /// - [SerializableProperty] - public AudioMixerFeatureConfiguration[] features - { - get; - set - { - ArgumentNullException.ThrowIfNull(value); - field = value.ToArray(); - } - } = []; -} diff --git a/src/services/audio/Inno.Audio/AudioMixerAsset.cs b/src/services/audio/Inno.Audio/AudioMixerAsset.cs new file mode 100644 index 000000000..7af6acbc9 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerAsset.cs @@ -0,0 +1,40 @@ +using System; +using System.Linq; +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Audio; + +/// +/// Selects a mixer extension and ordered features without defining a game-specific mixing model. +/// +[StableTypeID("6e167326-d078-45e9-ad33-993300ee5fed")] +public sealed class AudioMixerAsset : AssetObject +{ + /// + /// Gets or sets the globally stable mixer extension identifier. + /// + [SerializableProperty] + public string mixerTypeId { get; set; } = string.Empty; + + /// + /// Gets or sets reload-safe mixer settings. + /// + [SerializableProperty] + public SerializedAudioExtensionState mixerState { get; set; } = new(); + + /// + /// Gets or sets ordered feature configurations. + /// + [SerializableProperty] + public AudioMixerFeatureConfiguration[] features + { + get; + set + { + ArgumentNullException.ThrowIfNull(value); + field = value.ToArray(); + } + } = []; +} diff --git a/src/services/audio/Inno.Audio/AudioMixerBuilder.cs b/src/services/audio/Inno.Audio/AudioMixerBuilder.cs new file mode 100644 index 000000000..5fb76328d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerBuilder.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Builds and validates an open backend-neutral mixer graph. +/// +public sealed class AudioMixerBuilder +{ + private readonly Dictionary m_buses = new() + { + [AudioBusID.master] = new(AudioBusID.master, null, 1f, false) + }; + + /// + /// Adds one semantic bus to the graph. + /// + /// + /// Stable bus identifier. + /// + /// + /// Parent bus identifier. + /// + /// + /// Initial non-negative linear gain. + /// + /// + /// Whether output is initially silenced. + /// + /// + /// Thrown when the bus identifier is invalid or duplicated. + /// + public void AddBus( + AudioBusID id, + AudioBusID parent, + float volume = 1f, + bool muted = false + ) { + if (!id.isValid || id == AudioBusID.master) + { + throw new ArgumentException("A valid non-master bus identifier is required.", nameof(id)); + } + if (m_buses.ContainsKey(id)) + { + throw new ArgumentException($"Audio bus '{id}' is already defined.", nameof(id)); + } + m_buses.Add(id, new AudioBusDefinition(id, parent, volume, muted)); + } + + /// + /// Appends one processor to an existing bus chain. + /// + /// + /// Existing bus identifier. + /// + /// + /// Immutable processor configuration to append. + /// + /// + /// Thrown when the bus is not defined. + /// + public void AddProcessor( + AudioBusID bus, + AudioProcessorConfiguration processor + ) { + ArgumentNullException.ThrowIfNull(processor); + if (!m_buses.TryGetValue(bus, out AudioBusDefinition? definition)) + { + throw new KeyNotFoundException($"Audio bus '{bus}' is not defined."); + } + m_buses[bus] = new AudioBusDefinition( + definition.id, + definition.parent, + definition.volume, + definition.muted, + definition.processors.Append(processor) + ); + } + + /// + /// Validates the graph and returns an immutable parent-before-child snapshot. + /// + /// + /// A validated mixer graph containing the mandatory master bus. + /// + /// + /// Thrown when a parent is missing or bus routing contains a cycle. + /// + public AudioMixer Build() + { + var order = new List(m_buses.Count); + var visiting = new HashSet(); + var visited = new HashSet(); + Visit(AudioBusID.master, order, visiting, visited); + foreach (AudioBusID id in m_buses.Keys.OrderBy(static id => id.value, StringComparer.Ordinal)) + { + Visit(id, order, visiting, visited); + } + return new AudioMixer(order); + } + + private void Visit( + AudioBusID id, + ICollection order, + ISet visiting, + ISet visited + ) { + if (visited.Contains(id)) + { + return; + } + if (!m_buses.TryGetValue(id, out AudioBusDefinition? definition)) + { + throw new InvalidOperationException($"Audio mixer references missing bus '{id}'."); + } + if (!visiting.Add(id)) + { + throw new InvalidOperationException($"Audio mixer bus routing contains a cycle at '{id}'."); + } + if (definition.parent is AudioBusID parent) + { + Visit(parent, order, visiting, visited); + } + visiting.Remove(id); + visited.Add(id); + order.Add(definition); + } +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtension.cs b/src/services/audio/Inno.Audio/AudioMixerExtension.cs new file mode 100644 index 000000000..f99ac3c60 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerExtension.cs @@ -0,0 +1,21 @@ +namespace Inno.Audio; + +/// +/// Builds a base mixer graph on the host control thread. +/// +public abstract class AudioMixerExtension +{ + /// + /// Adds base buses and processors to a candidate mixer graph. + /// + /// + /// Candidate graph builder valid only for this invocation. + /// + /// + /// Reload-safe neutral extension state. + /// + public abstract void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ); +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs new file mode 100644 index 000000000..09a153afb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable extension that creates the base audio mixer graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioMixerExtensionAttribute : Attribute +{ + /// + /// Creates a mixer extension declaration. + /// + /// + /// Globally stable mixer extension identifier. + /// + public AudioMixerExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the globally stable mixer extension identifier. + /// + public string id { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtensions.cs b/src/services/audio/Inno.Audio/AudioMixerExtensions.cs deleted file mode 100644 index fc4168032..000000000 --- a/src/services/audio/Inno.Audio/AudioMixerExtensions.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; - -namespace Inno.Audio; - -/// -/// Marks a reloadable extension that creates the base audio mixer graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioMixerExtensionAttribute : Attribute -{ - /// - /// Creates a mixer extension declaration. - /// - /// - /// Globally stable mixer extension identifier. - /// - public AudioMixerExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the globally stable mixer extension identifier. - /// - public string id { get; } -} - -/// -/// Marks a reloadable extension that contributes to an audio mixer graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioMixerFeatureExtensionAttribute : Attribute -{ - /// - /// Creates a mixer feature declaration. - /// - /// - /// Globally stable feature extension identifier. - /// - /// - /// Feature invocation priority; lower values build first. - /// - public AudioMixerFeatureExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable feature extension identifier. - /// - public string id { get; } - - /// - /// Gets the feature invocation priority. - /// - public int priority { get; } -} - -/// -/// Builds a base mixer graph on the host control thread. -/// -public abstract class AudioMixerExtension -{ - /// - /// Adds base buses and processors to a candidate mixer graph. - /// - /// - /// Candidate graph builder valid only for this invocation. - /// - /// - /// Reload-safe neutral extension state. - /// - public abstract void Build( - AudioMixerBuilder builder, - SerializedAudioExtensionState state - ); -} - -/// -/// Contributes optional buses and processors to a candidate mixer graph. -/// -public abstract class AudioMixerFeature -{ - /// - /// Adds feature-owned graph declarations on the host control thread. - /// - /// - /// Candidate graph builder valid only for this invocation. - /// - /// - /// Reload-safe neutral feature state. - /// - public abstract void Build( - AudioMixerBuilder builder, - SerializedAudioExtensionState state - ); -} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeature.cs b/src/services/audio/Inno.Audio/AudioMixerFeature.cs new file mode 100644 index 000000000..3c1ad0edb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeature.cs @@ -0,0 +1,21 @@ +namespace Inno.Audio; + +/// +/// Contributes optional buses and processors to a candidate mixer graph. +/// +public abstract class AudioMixerFeature +{ + /// + /// Adds feature-owned graph declarations on the host control thread. + /// + /// + /// Candidate graph builder valid only for this invocation. + /// + /// + /// Reload-safe neutral feature state. + /// + public abstract void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ); +} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs b/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs new file mode 100644 index 000000000..69f80c1bf --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs @@ -0,0 +1,56 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Audio; + +/// +/// Stores one ordered mixer feature selection using only stable data. +/// +public struct AudioMixerFeatureConfiguration +{ + /// + /// Creates an empty feature configuration for deserialization. + /// + public AudioMixerFeatureConfiguration() {} + + /// + /// Creates a mixer feature configuration. + /// + /// + /// Globally stable feature extension identifier. + /// + /// + /// Optional reload-safe feature state. + /// + /// + /// Whether the feature participates in graph construction. + /// + public AudioMixerFeatureConfiguration( + string featureTypeID, + SerializedAudioExtensionState? state = null, + bool enabled = true + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeID); + this.featureTypeId = featureTypeID; + this.state = state ?? new SerializedAudioExtensionState(); + this.enabled = enabled; + } + + /// + /// Gets or sets the stable feature extension identifier. + /// + [SerializableProperty] + public string featureTypeId { get; set; } = string.Empty; + + /// + /// Gets or sets reload-safe feature settings. + /// + [SerializableProperty] + public SerializedAudioExtensionState state { get; set; } + + /// + /// Gets or sets whether the feature participates in graph construction. + /// + [SerializableProperty] + public bool enabled { get; set; } = true; +} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs new file mode 100644 index 000000000..56e8aae81 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable extension that contributes to an audio mixer graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioMixerFeatureExtensionAttribute : Attribute +{ + /// + /// Creates a mixer feature declaration. + /// + /// + /// Globally stable feature extension identifier. + /// + /// + /// Feature invocation priority; lower values build first. + /// + public AudioMixerFeatureExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable feature extension identifier. + /// + public string id { get; } + + /// + /// Gets the feature invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioParameterID.cs b/src/services/audio/Inno.Audio/AudioParameterID.cs new file mode 100644 index 000000000..6096c3356 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioParameterID.cs @@ -0,0 +1,69 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies one processor parameter without imposing a processor-specific enum. +/// +public readonly record struct AudioParameterID +{ + /// + /// Creates an open processor parameter identifier. + /// + /// + /// Stable parameter name within its processor protocol. + /// + public AudioParameterID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard cutoff or center-frequency parameter in hertz. + /// + public static AudioParameterID frequency { get; } = new("inno.audio.parameter.frequency-hz"); + + /// + /// Gets the standard filter quality-factor parameter. + /// + public static AudioParameterID quality { get; } = new("inno.audio.parameter.quality"); + + /// + /// Gets the standard equalizer gain parameter in decibels. + /// + public static AudioParameterID gainDecibels { get; } = new("inno.audio.parameter.gain-db"); + + /// + /// Gets the standard equalizer shelf-slope parameter. + /// + public static AudioParameterID shelfSlope { get; } = new("inno.audio.parameter.shelf-slope"); + + /// + /// Gets the standard delay duration parameter in milliseconds. + /// + public static AudioParameterID delayMilliseconds { get; } = new("inno.audio.parameter.delay-ms"); + + /// + /// Gets the standard delay feedback decay factor. + /// + public static AudioParameterID decay { get; } = new("inno.audio.parameter.decay"); + + /// + /// Gets the stable parameter protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioPlayOptions.cs b/src/services/audio/Inno.Audio/AudioPlayOptions.cs new file mode 100644 index 000000000..ef607d0a1 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioPlayOptions.cs @@ -0,0 +1,134 @@ +using System; + +namespace Inno.Audio; + +/// +/// Contains immutable parameters used to create one playback voice. +/// +public readonly record struct AudioPlayOptions +{ + /// + /// Creates default playback parameters. + /// + public AudioPlayOptions() + : this(1f, 1f, 0f, false, 0, AudioBusID.master, AudioClipLoadMode.Automatic, null) {} + + /// + /// Creates playback parameters. + /// + /// + /// Linear gain applied to the voice. + /// + /// + /// Playback-rate multiplier. + /// + /// + /// Stereo pan from negative one to positive one. + /// + /// + /// Whether playback restarts after reaching the clip end. + /// + /// + /// Voice retention priority; larger values are retained first. + /// + /// + /// Destination mixer bus. + /// + /// + /// Clip preparation override. + /// + /// + /// Optional spatial playback parameters. + /// + /// + /// Gain, pitch, or pan is non-finite or outside its valid range, or the load mode is undefined. + /// + /// + /// The supplied destination bus is uninitialized. + /// + public AudioPlayOptions( + float volume = 1f, + float pitch = 1f, + float pan = 0f, + bool loop = false, + int priority = 0, + AudioBusID? bus = null, + AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, + AudioSpatialOptions? spatial = null + ) { + if (!float.IsFinite(volume) || volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (!float.IsFinite(pitch) || pitch <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pitch)); + } + if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(pan)); + } + if (!Enum.IsDefined(loadMode)) + { + throw new ArgumentOutOfRangeException(nameof(loadMode)); + } + AudioBusID resolvedBus = bus ?? AudioBusID.master; + if (!resolvedBus.isValid) + { + throw new ArgumentException("A valid destination bus is required.", nameof(bus)); + } + this.volume = volume; + this.pitch = pitch; + this.pan = pan; + this.loop = loop; + this.priority = priority; + this.bus = resolvedBus; + this.loadMode = loadMode; + this.spatial = spatial; + } + + /// + /// Gets the default playback parameters. + /// + public static AudioPlayOptions defaultValue { get; } = new(); + + /// + /// Gets the linear voice gain. + /// + public float volume { get; } + + /// + /// Gets the playback-rate multiplier. + /// + public float pitch { get; } + + /// + /// Gets the stereo pan value. + /// + public float pan { get; } + + /// + /// Gets whether playback loops at the clip end. + /// + public bool loop { get; } + + /// + /// Gets the voice retention priority. + /// + public int priority { get; } + + /// + /// Gets the destination mixer bus. + /// + public AudioBusID bus { get; } + + /// + /// Gets the clip preparation override. + /// + public AudioClipLoadMode loadMode { get; } + + /// + /// Gets optional spatial playback parameters. + /// + public AudioSpatialOptions? spatial { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioPlaybackState.cs b/src/services/audio/Inno.Audio/AudioPlaybackState.cs new file mode 100644 index 000000000..018bf0d9d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioPlaybackState.cs @@ -0,0 +1,32 @@ +namespace Inno.Audio; + +/// +/// Describes the observable lifecycle of one playback voice. +/// +public enum AudioPlaybackState +{ + /// + /// The voice is waiting for clip preparation. + /// + Preparing, + /// + /// The voice is scheduled against the audio clock. + /// + Scheduled, + /// + /// The voice is actively advancing. + /// + Playing, + /// + /// The voice is paused at its current cursor. + /// + Paused, + /// + /// The voice has completed and no longer accepts control commands. + /// + Completed, + /// + /// The handle is invalid, stale, or unknown to the active runtime. + /// + Invalid +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs b/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs new file mode 100644 index 000000000..bcf5fc3ec --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Describes one ordered processor instance attached to a mixer bus. +/// +public sealed class AudioProcessorConfiguration +{ + private readonly AudioProcessorParameter[] m_parameters; + + /// + /// Creates an immutable processor configuration. + /// + /// + /// Open processor protocol identifier. + /// + /// + /// Complete processor parameter set. + /// + public AudioProcessorConfiguration( + AudioProcessorID id, + IEnumerable? parameters = null + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid processor identifier is required.", nameof(id)); + } + this.id = id; + m_parameters = parameters?.ToArray() ?? []; + if (m_parameters.Select(static parameter => parameter.id).Distinct().Count() != m_parameters.Length) + { + throw new ArgumentException("Processor parameter identifiers must be unique.", nameof(parameters)); + } + } + + /// + /// Gets the open processor protocol identifier. + /// + public AudioProcessorID id { get; } + + /// + /// Gets the immutable processor parameter set. + /// + public IReadOnlyList parameters => Array.AsReadOnly(m_parameters); +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorID.cs b/src/services/audio/Inno.Audio/AudioProcessorID.cs new file mode 100644 index 000000000..db2439269 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorID.cs @@ -0,0 +1,79 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies an audio processor implementation without imposing a closed effect catalog. +/// +public readonly record struct AudioProcessorID +{ + /// + /// Creates an open processor identifier. + /// + /// + /// Globally stable processor protocol value. + /// + public AudioProcessorID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard low-pass filter processor identifier. + /// + public static AudioProcessorID lowPass { get; } = new("inno.audio.processor.low-pass"); + + /// + /// Gets the standard high-pass filter processor identifier. + /// + public static AudioProcessorID highPass { get; } = new("inno.audio.processor.high-pass"); + + /// + /// Gets the standard band-pass filter processor identifier. + /// + public static AudioProcessorID bandPass { get; } = new("inno.audio.processor.band-pass"); + + /// + /// Gets the standard notch filter processor identifier. + /// + public static AudioProcessorID notch { get; } = new("inno.audio.processor.notch"); + + /// + /// Gets the standard peak equalizer processor identifier. + /// + public static AudioProcessorID peak { get; } = new("inno.audio.processor.peak"); + + /// + /// Gets the standard low-shelf equalizer processor identifier. + /// + public static AudioProcessorID lowShelf { get; } = new("inno.audio.processor.low-shelf"); + + /// + /// Gets the standard high-shelf equalizer processor identifier. + /// + public static AudioProcessorID highShelf { get; } = new("inno.audio.processor.high-shelf"); + + /// + /// Gets the standard delay processor identifier. + /// + public static AudioProcessorID delay { get; } = new("inno.audio.processor.delay"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorParameter.cs b/src/services/audio/Inno.Audio/AudioProcessorParameter.cs new file mode 100644 index 000000000..910631791 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorParameter.cs @@ -0,0 +1,40 @@ +using System; + +namespace Inno.Audio; + +/// +/// Stores one neutral numeric parameter assigned to an audio processor. +/// +public readonly record struct AudioProcessorParameter +{ + /// + /// Creates a processor parameter value. + /// + /// + /// Open parameter identifier understood by the processor protocol. + /// + /// + /// Neutral numeric value interpreted by the processor. + /// + public AudioProcessorParameter( + AudioParameterID id, + float value + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid parameter identifier is required.", nameof(id)); + } + this.id = id; + this.value = value; + } + + /// + /// Gets the open parameter identifier. + /// + public AudioParameterID id { get; } + + /// + /// Gets the neutral numeric value. + /// + public float value { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioProjectSettings.cs b/src/services/audio/Inno.Audio/AudioProjectSettings.cs index 39e76d39c..cbf1e1c88 100644 --- a/src/services/audio/Inno.Audio/AudioProjectSettings.cs +++ b/src/services/audio/Inno.Audio/AudioProjectSettings.cs @@ -7,19 +7,19 @@ namespace Inno.Audio; /// /// Stores portable project-wide defaults for audio playback and caching. /// -[StableTypeId("29f99b3b-a9f3-45f4-888a-f4b13cb3504c")] -[ProjectSettingDefinition(AudioProjectSettings.settingProtocolId)] +[StableTypeID("29f99b3b-a9f3-45f4-888a-f4b13cb3504c")] +[ProjectSettingDefinition(AudioProjectSettings.C_SETTING_PROTOCOL_ID)] public sealed class AudioProjectSettings : ISerializable { /// /// Gets the immutable project-setting protocol value used by discovery metadata. /// - public const string settingProtocolId = "inno.audio.runtime"; + public const string C_SETTING_PROTOCOL_ID = "inno.audio.runtime"; /// /// Gets the stable project-setting identity for audio runtime defaults. /// - public static ProjectSettingId settingId => new(settingProtocolId); + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); /// /// Gets or sets the default mixer asset, or for the master-only graph. diff --git a/src/services/audio/Inno.Audio/AudioProtocolIds.cs b/src/services/audio/Inno.Audio/AudioProtocolIds.cs deleted file mode 100644 index 2ca626303..000000000 --- a/src/services/audio/Inno.Audio/AudioProtocolIds.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System; - -namespace Inno.Audio; - -/// -/// Identifies a mixer bus without imposing a closed bus catalog. -/// -public readonly record struct AudioBusId -{ - /// - /// Creates an open mixer bus identifier. - /// - /// - /// Globally stable bus protocol value. - /// - public AudioBusId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the mandatory root bus identifier. - /// - public static AudioBusId master { get; } = new("inno.audio.bus.master"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies an audio processor implementation without imposing a closed effect catalog. -/// -public readonly record struct AudioProcessorId -{ - /// - /// Creates an open processor identifier. - /// - /// - /// Globally stable processor protocol value. - /// - public AudioProcessorId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard low-pass filter processor identifier. - /// - public static AudioProcessorId lowPass { get; } = new("inno.audio.processor.low-pass"); - - /// - /// Gets the standard high-pass filter processor identifier. - /// - public static AudioProcessorId highPass { get; } = new("inno.audio.processor.high-pass"); - - /// - /// Gets the standard band-pass filter processor identifier. - /// - public static AudioProcessorId bandPass { get; } = new("inno.audio.processor.band-pass"); - - /// - /// Gets the standard notch filter processor identifier. - /// - public static AudioProcessorId notch { get; } = new("inno.audio.processor.notch"); - - /// - /// Gets the standard peak equalizer processor identifier. - /// - public static AudioProcessorId peak { get; } = new("inno.audio.processor.peak"); - - /// - /// Gets the standard low-shelf equalizer processor identifier. - /// - public static AudioProcessorId lowShelf { get; } = new("inno.audio.processor.low-shelf"); - - /// - /// Gets the standard high-shelf equalizer processor identifier. - /// - public static AudioProcessorId highShelf { get; } = new("inno.audio.processor.high-shelf"); - - /// - /// Gets the standard delay processor identifier. - /// - public static AudioProcessorId delay { get; } = new("inno.audio.processor.delay"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies one processor parameter without imposing a processor-specific enum. -/// -public readonly record struct AudioParameterId -{ - /// - /// Creates an open processor parameter identifier. - /// - /// - /// Stable parameter name within its processor protocol. - /// - public AudioParameterId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard cutoff or center-frequency parameter in hertz. - /// - public static AudioParameterId frequency { get; } = new("inno.audio.parameter.frequency-hz"); - - /// - /// Gets the standard filter quality-factor parameter. - /// - public static AudioParameterId quality { get; } = new("inno.audio.parameter.quality"); - - /// - /// Gets the standard equalizer gain parameter in decibels. - /// - public static AudioParameterId gainDecibels { get; } = new("inno.audio.parameter.gain-db"); - - /// - /// Gets the standard equalizer shelf-slope parameter. - /// - public static AudioParameterId shelfSlope { get; } = new("inno.audio.parameter.shelf-slope"); - - /// - /// Gets the standard delay duration parameter in milliseconds. - /// - public static AudioParameterId delayMilliseconds { get; } = new("inno.audio.parameter.delay-ms"); - - /// - /// Gets the standard delay feedback decay factor. - /// - public static AudioParameterId decay { get; } = new("inno.audio.parameter.decay"); - - /// - /// Gets the stable parameter protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies encoded audio data without constraining codec providers to a closed enum. -/// -public readonly record struct AudioCodecId -{ - /// - /// Creates an open codec identifier. - /// - /// - /// Globally stable codec protocol value. - /// - public AudioCodecId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard Waveform Audio codec identifier. - /// - public static AudioCodecId wav { get; } = new("audio/wav"); - - /// - /// Gets the standard Free Lossless Audio Codec identifier. - /// - public static AudioCodecId flac { get; } = new("audio/flac"); - - /// - /// Gets the standard MPEG Layer III codec identifier. - /// - public static AudioCodecId mp3 { get; } = new("audio/mpeg"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} diff --git a/src/services/audio/Inno.Audio/AudioSpatialOptions.cs b/src/services/audio/Inno.Audio/AudioSpatialOptions.cs new file mode 100644 index 000000000..0169ff8e7 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioSpatialOptions.cs @@ -0,0 +1,158 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Audio; + +/// +/// Contains listener-relative positioning and attenuation parameters for one voice. +/// +public readonly record struct AudioSpatialOptions +{ + /// + /// Creates spatial playback parameters. + /// + /// + /// World-space source position. + /// + /// + /// World-space source forward direction. + /// + /// + /// World-space source velocity used for Doppler calculation. + /// + /// + /// Distance attenuation model. + /// + /// + /// Distance at which attenuation begins. + /// + /// + /// Distance beyond which attenuation is clamped. + /// + /// + /// Attenuation strength for the selected distance model. + /// + /// + /// Full-volume source cone angle in degrees. + /// + /// + /// Outer source cone angle in degrees. + /// + /// + /// Gain outside the outer cone. + /// + /// + /// Doppler effect multiplier. + /// + /// + /// A vector or scalar is non-finite, a spatial bound is invalid, or the distance model is undefined. + /// + public AudioSpatialOptions( + Vector3 position, + Vector3 direction, + Vector3 velocity, + AudioDistanceModel distanceModel = AudioDistanceModel.Inverse, + float minDistance = 1f, + float maxDistance = 100f, + float rolloff = 1f, + float coneInnerAngle = 360f, + float coneOuterAngle = 360f, + float coneOuterGain = 1f, + float dopplerFactor = 1f + ) { + AudioValueValidation.RequireFinite(position, nameof(position)); + AudioValueValidation.RequireFinite(direction, nameof(direction)); + AudioValueValidation.RequireFinite(velocity, nameof(velocity)); + if (!Enum.IsDefined(distanceModel)) + { + throw new ArgumentOutOfRangeException(nameof(distanceModel)); + } + if (!float.IsFinite(minDistance) || !float.IsFinite(maxDistance) || minDistance < 0f || maxDistance < minDistance) + { + throw new ArgumentOutOfRangeException(nameof(minDistance), "Spatial distance bounds are invalid."); + } + if (!float.IsFinite(rolloff) || rolloff < 0f) + { + throw new ArgumentOutOfRangeException(nameof(rolloff)); + } + if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) + || coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f + ) { + throw new ArgumentOutOfRangeException(nameof(coneOuterAngle), "Spatial cone angles are invalid."); + } + if (!float.IsFinite(coneOuterGain) || coneOuterGain is < 0f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(coneOuterGain)); + } + if (!float.IsFinite(dopplerFactor) || dopplerFactor < 0f) + { + throw new ArgumentOutOfRangeException(nameof(dopplerFactor)); + } + this.position = position; + this.direction = direction; + this.velocity = velocity; + this.distanceModel = distanceModel; + this.minDistance = minDistance; + this.maxDistance = maxDistance; + this.rolloff = rolloff; + this.coneInnerAngle = coneInnerAngle; + this.coneOuterAngle = coneOuterAngle; + this.coneOuterGain = coneOuterGain; + this.dopplerFactor = dopplerFactor; + } + + /// + /// Gets the world-space source position. + /// + public Vector3 position { get; } + + /// + /// Gets the world-space source forward direction. + /// + public Vector3 direction { get; } + + /// + /// Gets the world-space source velocity. + /// + public Vector3 velocity { get; } + + /// + /// Gets the distance attenuation model. + /// + public AudioDistanceModel distanceModel { get; } + + /// + /// Gets the distance at which attenuation begins. + /// + public float minDistance { get; } + + /// + /// Gets the distance beyond which attenuation is clamped. + /// + public float maxDistance { get; } + + /// + /// Gets the distance attenuation strength. + /// + public float rolloff { get; } + + /// + /// Gets the full-volume cone angle in degrees. + /// + public float coneInnerAngle { get; } + + /// + /// Gets the outer cone angle in degrees. + /// + public float coneOuterAngle { get; } + + /// + /// Gets the gain outside the outer cone. + /// + public float coneOuterGain { get; } + + /// + /// Gets the Doppler effect multiplier. + /// + public float dopplerFactor { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioStatistics.cs b/src/services/audio/Inno.Audio/AudioStatistics.cs new file mode 100644 index 000000000..2a9af245f --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioStatistics.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Audio; + +/// +/// Reports an immutable snapshot of runtime and backend resource usage. +/// +public readonly record struct AudioStatistics +{ + /// + /// Creates an audio statistics snapshot. + /// + /// + /// Voices that currently consume runtime budget. + /// + /// + /// Clip allocations held by the backend. + /// + /// + /// Approximate decoded clip bytes held in memory. + /// + /// + /// Voices reclaimed since runtime creation. + /// + public AudioStatistics( + int activeVoices, + int loadedClips, + long decodedBytes, + long stolenVoiceCount + ) { + ArgumentOutOfRangeException.ThrowIfNegative(activeVoices); + ArgumentOutOfRangeException.ThrowIfNegative(loadedClips); + ArgumentOutOfRangeException.ThrowIfNegative(decodedBytes); + ArgumentOutOfRangeException.ThrowIfNegative(stolenVoiceCount); + this.activeVoices = activeVoices; + this.loadedClips = loadedClips; + this.decodedBytes = decodedBytes; + this.stolenVoiceCount = stolenVoiceCount; + } + + /// + /// Gets voices that currently consume runtime budget. + /// + public int activeVoices { get; } + + /// + /// Gets clip allocations held by the backend. + /// + public int loadedClips { get; } + + /// + /// Gets approximate decoded clip bytes held in memory. + /// + public long decodedBytes { get; } + + /// + /// Gets voices reclaimed since runtime creation. + /// + public long stolenVoiceCount { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioTypes.cs b/src/services/audio/Inno.Audio/AudioTypes.cs deleted file mode 100644 index 31012d045..000000000 --- a/src/services/audio/Inno.Audio/AudioTypes.cs +++ /dev/null @@ -1,658 +0,0 @@ -using System; -using Inno.Core.Mathematics; - -namespace Inno.Audio; - -/// -/// Selects how encoded clip data is prepared for playback. -/// -public enum AudioClipLoadMode -{ - /// - /// Lets the runtime choose between decoded and streamed storage. - /// - Automatic, - - /// - /// Decodes the complete clip before playback. - /// - Decode, - - /// - /// Decodes encoded data incrementally while playback advances. - /// - Stream -} - -/// -/// Describes the availability of the active audio output generation. -/// -public enum AudioDeviceState -{ - /// - /// The device has not completed initialization. - /// - Initializing, - - /// - /// The device is available for audible playback. - /// - Ready, - - /// - /// Playback is advancing without an output device. - /// - Muted, - - /// - /// The active output device was lost and recovery is pending. - /// - Lost, - - /// - /// The device has been released and cannot accept work. - /// - Disposed -} - -/// -/// Describes the observable lifecycle of one playback voice. -/// -public enum AudioPlaybackState -{ - /// - /// The voice is waiting for clip preparation. - /// - Preparing, - - /// - /// The voice is scheduled against the audio clock. - /// - Scheduled, - - /// - /// The voice is actively advancing. - /// - Playing, - - /// - /// The voice is paused at its current cursor. - /// - Paused, - - /// - /// The voice has completed and no longer accepts control commands. - /// - Completed, - - /// - /// The handle is invalid, stale, or unknown to the active runtime. - /// - Invalid -} - -/// -/// Explains why a voice stopped accepting playback commands. -/// -public enum AudioCompletionReason -{ - /// - /// The clip reached its natural end. - /// - NaturalEnd, - - /// - /// A caller explicitly stopped the voice. - /// - Stopped, - - /// - /// The runtime reclaimed the voice to satisfy its voice budget. - /// - Stolen, - - /// - /// Encoded data could not be prepared or decoded. - /// - DecodeFailed, - - /// - /// Playback ended because the owning device generation was lost. - /// - DeviceLost -} - -/// -/// Selects the distance attenuation model for one spatial voice. -/// -public enum AudioDistanceModel -{ - /// - /// Disables distance attenuation while retaining spatial direction. - /// - None, - - /// - /// Uses inverse-distance attenuation. - /// - Inverse, - - /// - /// Uses linear-distance attenuation. - /// - Linear, - - /// - /// Uses exponential-distance attenuation. - /// - Exponential -} - -/// -/// Describes backend-neutral features and limits for one device generation. -/// -public sealed record AudioCapabilities -{ - /// - /// Creates an immutable audio capability snapshot. - /// - /// - /// Whether clips can be decoded incrementally. - /// - /// - /// Whether voices can start against the audio clock. - /// - /// - /// Whether listener-relative spatial playback is available. - /// - /// - /// Maximum simultaneously active listeners. - /// - /// - /// Device output sample rate in frames per second. - /// - public AudioCapabilities( - bool supportsStreaming, - bool supportsScheduledPlayback, - bool supportsSpatialAudio, - int maxListeners, - int sampleRate - ) { - ArgumentOutOfRangeException.ThrowIfNegative(maxListeners); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); - this.supportsStreaming = supportsStreaming; - this.supportsScheduledPlayback = supportsScheduledPlayback; - this.supportsSpatialAudio = supportsSpatialAudio; - this.maxListeners = maxListeners; - this.sampleRate = sampleRate; - } - - /// - /// Gets whether clips can be decoded incrementally. - /// - public bool supportsStreaming { get; } - - /// - /// Gets whether voices can start against the audio clock. - /// - public bool supportsScheduledPlayback { get; } - - /// - /// Gets whether listener-relative spatial playback is available. - /// - public bool supportsSpatialAudio { get; } - - /// - /// Gets the maximum simultaneously active listener count. - /// - public int maxListeners { get; } - - /// - /// Gets the output sample rate in frames per second. - /// - public int sampleRate { get; } -} - -/// -/// Reports an immutable snapshot of runtime and backend resource usage. -/// -public readonly record struct AudioStatistics -{ - /// - /// Creates an audio statistics snapshot. - /// - /// - /// Voices that currently consume runtime budget. - /// - /// - /// Clip allocations held by the backend. - /// - /// - /// Approximate decoded clip bytes held in memory. - /// - /// - /// Voices reclaimed since runtime creation. - /// - public AudioStatistics( - int activeVoices, - int loadedClips, - long decodedBytes, - long stolenVoiceCount - ) { - ArgumentOutOfRangeException.ThrowIfNegative(activeVoices); - ArgumentOutOfRangeException.ThrowIfNegative(loadedClips); - ArgumentOutOfRangeException.ThrowIfNegative(decodedBytes); - ArgumentOutOfRangeException.ThrowIfNegative(stolenVoiceCount); - this.activeVoices = activeVoices; - this.loadedClips = loadedClips; - this.decodedBytes = decodedBytes; - this.stolenVoiceCount = stolenVoiceCount; - } - - /// - /// Gets voices that currently consume runtime budget. - /// - public int activeVoices { get; } - - /// - /// Gets clip allocations held by the backend. - /// - public int loadedClips { get; } - - /// - /// Gets approximate decoded clip bytes held in memory. - /// - public long decodedBytes { get; } - - /// - /// Gets voices reclaimed since runtime creation. - /// - public long stolenVoiceCount { get; } -} - -/// -/// Contains listener-relative positioning and attenuation parameters for one voice. -/// -public readonly record struct AudioSpatialOptions -{ - /// - /// Creates spatial playback parameters. - /// - /// - /// World-space source position. - /// - /// - /// World-space source forward direction. - /// - /// - /// World-space source velocity used for Doppler calculation. - /// - /// - /// Distance attenuation model. - /// - /// - /// Distance at which attenuation begins. - /// - /// - /// Distance beyond which attenuation is clamped. - /// - /// - /// Attenuation strength for the selected distance model. - /// - /// - /// Full-volume source cone angle in degrees. - /// - /// - /// Outer source cone angle in degrees. - /// - /// - /// Gain outside the outer cone. - /// - /// - /// Doppler effect multiplier. - /// - /// - /// A vector or scalar is non-finite, a spatial bound is invalid, or the distance model is undefined. - /// - public AudioSpatialOptions( - Vector3 position, - Vector3 direction, - Vector3 velocity, - AudioDistanceModel distanceModel = AudioDistanceModel.Inverse, - float minDistance = 1f, - float maxDistance = 100f, - float rolloff = 1f, - float coneInnerAngle = 360f, - float coneOuterAngle = 360f, - float coneOuterGain = 1f, - float dopplerFactor = 1f - ) { - AudioValueValidation.RequireFinite(position, nameof(position)); - AudioValueValidation.RequireFinite(direction, nameof(direction)); - AudioValueValidation.RequireFinite(velocity, nameof(velocity)); - if (!Enum.IsDefined(distanceModel)) - throw new ArgumentOutOfRangeException(nameof(distanceModel)); - if (!float.IsFinite(minDistance) || !float.IsFinite(maxDistance) || minDistance < 0f || maxDistance < minDistance) - throw new ArgumentOutOfRangeException(nameof(minDistance), "Spatial distance bounds are invalid."); - if (!float.IsFinite(rolloff) || rolloff < 0f) - throw new ArgumentOutOfRangeException(nameof(rolloff)); - if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) || - coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f) - throw new ArgumentOutOfRangeException(nameof(coneOuterAngle), "Spatial cone angles are invalid."); - if (!float.IsFinite(coneOuterGain) || coneOuterGain is < 0f or > 1f) - throw new ArgumentOutOfRangeException(nameof(coneOuterGain)); - if (!float.IsFinite(dopplerFactor) || dopplerFactor < 0f) - throw new ArgumentOutOfRangeException(nameof(dopplerFactor)); - this.position = position; - this.direction = direction; - this.velocity = velocity; - this.distanceModel = distanceModel; - this.minDistance = minDistance; - this.maxDistance = maxDistance; - this.rolloff = rolloff; - this.coneInnerAngle = coneInnerAngle; - this.coneOuterAngle = coneOuterAngle; - this.coneOuterGain = coneOuterGain; - this.dopplerFactor = dopplerFactor; - } - - /// - /// Gets the world-space source position. - /// - public Vector3 position { get; } - - /// - /// Gets the world-space source forward direction. - /// - public Vector3 direction { get; } - - /// - /// Gets the world-space source velocity. - /// - public Vector3 velocity { get; } - - /// - /// Gets the distance attenuation model. - /// - public AudioDistanceModel distanceModel { get; } - - /// - /// Gets the distance at which attenuation begins. - /// - public float minDistance { get; } - - /// - /// Gets the distance beyond which attenuation is clamped. - /// - public float maxDistance { get; } - - /// - /// Gets the distance attenuation strength. - /// - public float rolloff { get; } - - /// - /// Gets the full-volume cone angle in degrees. - /// - public float coneInnerAngle { get; } - - /// - /// Gets the outer cone angle in degrees. - /// - public float coneOuterAngle { get; } - - /// - /// Gets the gain outside the outer cone. - /// - public float coneOuterGain { get; } - - /// - /// Gets the Doppler effect multiplier. - /// - public float dopplerFactor { get; } -} - -/// -/// Contains immutable parameters used to create one playback voice. -/// -public readonly record struct AudioPlayOptions -{ - /// - /// Creates default playback parameters. - /// - public AudioPlayOptions() - : this(1f, 1f, 0f, false, 0, AudioBusId.master, AudioClipLoadMode.Automatic, null) - { - } - - /// - /// Creates playback parameters. - /// - /// - /// Linear gain applied to the voice. - /// - /// - /// Playback-rate multiplier. - /// - /// - /// Stereo pan from negative one to positive one. - /// - /// - /// Whether playback restarts after reaching the clip end. - /// - /// - /// Voice retention priority; larger values are retained first. - /// - /// - /// Destination mixer bus. - /// - /// - /// Clip preparation override. - /// - /// - /// Optional spatial playback parameters. - /// - /// - /// Gain, pitch, or pan is non-finite or outside its valid range, or the load mode is undefined. - /// - /// - /// The supplied destination bus is uninitialized. - /// - public AudioPlayOptions( - float volume = 1f, - float pitch = 1f, - float pan = 0f, - bool loop = false, - int priority = 0, - AudioBusId? bus = null, - AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, - AudioSpatialOptions? spatial = null - ) { - if (!float.IsFinite(volume) || volume < 0f) - throw new ArgumentOutOfRangeException(nameof(volume)); - if (!float.IsFinite(pitch) || pitch <= 0f) - throw new ArgumentOutOfRangeException(nameof(pitch)); - if (!float.IsFinite(pan) || pan is < -1f or > 1f) - throw new ArgumentOutOfRangeException(nameof(pan)); - if (!Enum.IsDefined(loadMode)) - throw new ArgumentOutOfRangeException(nameof(loadMode)); - AudioBusId resolvedBus = bus ?? AudioBusId.master; - if (!resolvedBus.isValid) - throw new ArgumentException("A valid destination bus is required.", nameof(bus)); - this.volume = volume; - this.pitch = pitch; - this.pan = pan; - this.loop = loop; - this.priority = priority; - this.bus = resolvedBus; - this.loadMode = loadMode; - this.spatial = spatial; - } - - /// - /// Gets the default playback parameters. - /// - public static AudioPlayOptions defaultValue { get; } = new(); - - /// - /// Gets the linear voice gain. - /// - public float volume { get; } - - /// - /// Gets the playback-rate multiplier. - /// - public float pitch { get; } - - /// - /// Gets the stereo pan value. - /// - public float pan { get; } - - /// - /// Gets whether playback loops at the clip end. - /// - public bool loop { get; } - - /// - /// Gets the voice retention priority. - /// - public int priority { get; } - - /// - /// Gets the destination mixer bus. - /// - public AudioBusId bus { get; } - - /// - /// Gets the clip preparation override. - /// - public AudioClipLoadMode loadMode { get; } - - /// - /// Gets optional spatial playback parameters. - /// - public AudioSpatialOptions? spatial { get; } -} - -/// -/// Contains mutable voice parameters that can be changed after playback begins. -/// -public readonly record struct AudioVoiceParameters -{ - /// - /// Creates a voice parameter snapshot. - /// - /// - /// Linear voice gain. - /// - /// - /// Playback-rate multiplier. - /// - /// - /// Stereo pan from negative one to positive one. - /// - /// - /// Optional spatial playback parameters. - /// - /// - /// Gain, pitch, or pan is non-finite or outside its valid range. - /// - public AudioVoiceParameters( - float volume, - float pitch, - float pan, - AudioSpatialOptions? spatial = null - ) { - if (!float.IsFinite(volume) || volume < 0f) - throw new ArgumentOutOfRangeException(nameof(volume)); - if (!float.IsFinite(pitch) || pitch <= 0f) - throw new ArgumentOutOfRangeException(nameof(pitch)); - if (!float.IsFinite(pan) || pan is < -1f or > 1f) - throw new ArgumentOutOfRangeException(nameof(pan)); - this.volume = volume; - this.pitch = pitch; - this.pan = pan; - this.spatial = spatial; - } - - /// - /// Gets the linear voice gain. - /// - public float volume { get; } - - /// - /// Gets the playback-rate multiplier. - /// - public float pitch { get; } - - /// - /// Gets the stereo pan value. - /// - public float pan { get; } - - /// - /// Gets optional spatial playback parameters. - /// - public AudioSpatialOptions? spatial { get; } -} - -/// -/// Contains one listener transform used by backend spatialization. -/// -public readonly record struct AudioListenerState -{ - /// - /// Creates a listener transform snapshot. - /// - /// - /// World-space listener position. - /// - /// - /// World-space listener forward direction. - /// - /// - /// World-space listener up direction. - /// - /// - /// World-space listener velocity. - /// - /// - /// Any position, direction, up, or velocity component is non-finite. - /// - public AudioListenerState( - Vector3 position, - Vector3 direction, - Vector3 up, - Vector3 velocity - ) { - AudioValueValidation.RequireFinite(position, nameof(position)); - AudioValueValidation.RequireFinite(direction, nameof(direction)); - AudioValueValidation.RequireFinite(up, nameof(up)); - AudioValueValidation.RequireFinite(velocity, nameof(velocity)); - this.position = position; - this.direction = direction; - this.up = up; - this.velocity = velocity; - } - - /// - /// Gets the world-space listener position. - /// - public Vector3 position { get; } - - /// - /// Gets the world-space listener forward direction. - /// - public Vector3 direction { get; } - - /// - /// Gets the world-space listener up direction. - /// - public Vector3 up { get; } - - /// - /// Gets the world-space listener velocity. - /// - public Vector3 velocity { get; } -} diff --git a/src/services/audio/Inno.Audio/AudioValueValidation.cs b/src/services/audio/Inno.Audio/AudioValueValidation.cs index ba8507dd8..b86d15bb8 100644 --- a/src/services/audio/Inno.Audio/AudioValueValidation.cs +++ b/src/services/audio/Inno.Audio/AudioValueValidation.cs @@ -10,6 +10,8 @@ internal static void RequireFinite( string parameterName ) { if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z)) + { throw new ArgumentOutOfRangeException(parameterName, "Audio vectors must contain finite components."); + } } } diff --git a/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs b/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs index fccbb00b6..d888bb6e9 100644 --- a/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs +++ b/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs @@ -8,7 +8,7 @@ namespace Inno.Audio; /// public sealed class AudioVoiceAllocator { - private static int S_NEXT_GENERATION; + private static int s_nextGeneration; private readonly uint m_generation; private ulong m_nextIdentity; @@ -20,9 +20,11 @@ public sealed class AudioVoiceAllocator /// public AudioVoiceAllocator() { - int generation = Interlocked.Increment(ref S_NEXT_GENERATION); + int generation = Interlocked.Increment(ref s_nextGeneration); if (generation <= 0) + { throw new InvalidOperationException("Audio playback owner generations are exhausted."); + } m_generation = (uint)generation; } diff --git a/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs b/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs index bce06314b..424527f06 100644 --- a/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs +++ b/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs @@ -22,7 +22,9 @@ public AudioVoiceCompletedEvent( AudioCompletionReason reason ) { if (!voice.isValid) + { throw new ArgumentException("A valid voice handle is required.", nameof(voice)); + } this.voice = voice; this.reason = reason; } diff --git a/src/services/audio/Inno.Audio/AudioVoiceHandle.cs b/src/services/audio/Inno.Audio/AudioVoiceHandle.cs new file mode 100644 index 000000000..8a7bd8bbf --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioVoiceHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one playback voice within a device generation. +/// +public readonly record struct AudioVoiceHandle +{ + internal AudioVoiceHandle( + ulong value, + uint ownerGeneration + ) { + this.value = value; + this.ownerGeneration = ownerGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint ownerGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && ownerGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioVoiceParameters.cs b/src/services/audio/Inno.Audio/AudioVoiceParameters.cs new file mode 100644 index 000000000..25b06db0c --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioVoiceParameters.cs @@ -0,0 +1,71 @@ +using System; + +namespace Inno.Audio; + +/// +/// Contains mutable voice parameters that can be changed after playback begins. +/// +public readonly record struct AudioVoiceParameters +{ + /// + /// Creates a voice parameter snapshot. + /// + /// + /// Linear voice gain. + /// + /// + /// Playback-rate multiplier. + /// + /// + /// Stereo pan from negative one to positive one. + /// + /// + /// Optional spatial playback parameters. + /// + /// + /// Gain, pitch, or pan is non-finite or outside its valid range. + /// + public AudioVoiceParameters( + float volume, + float pitch, + float pan, + AudioSpatialOptions? spatial = null + ) { + if (!float.IsFinite(volume) || volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (!float.IsFinite(pitch) || pitch <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pitch)); + } + if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(pan)); + } + this.volume = volume; + this.pitch = pitch; + this.pan = pan; + this.spatial = spatial; + } + + /// + /// Gets the linear voice gain. + /// + public float volume { get; } + + /// + /// Gets the playback-rate multiplier. + /// + public float pitch { get; } + + /// + /// Gets the stereo pan value. + /// + public float pan { get; } + + /// + /// Gets optional spatial playback parameters. + /// + public AudioSpatialOptions? spatial { get; } +} diff --git a/src/services/audio/Inno.Audio/IAudioDevice.cs b/src/services/audio/Inno.Audio/IAudioDevice.cs index 95b258a09..271913c0f 100644 --- a/src/services/audio/Inno.Audio/IAudioDevice.cs +++ b/src/services/audio/Inno.Audio/IAudioDevice.cs @@ -2,57 +2,11 @@ namespace Inno.Audio; -/// -/// Reports one backend-detected terminal voice transition. -/// -public readonly record struct AudioDeviceCompletion -{ - /// - /// Creates a backend voice completion record. - /// - /// - /// Voice that reached a terminal state. - /// - /// - /// Reason playback ended. - /// - public AudioDeviceCompletion( - AudioDeviceVoiceHandle voice, - AudioCompletionReason reason - ) { - if (!voice.isValid) - throw new ArgumentException("A valid voice handle is required.", nameof(voice)); - this.voice = voice; - this.reason = reason; - } - - /// - /// Gets the completed voice handle. - /// - public AudioDeviceVoiceHandle voice { get; } - - /// - /// Gets the terminal playback reason. - /// - public AudioCompletionReason reason { get; } -} - /// /// Owns one replaceable audio backend generation and all device-side audio objects. /// public interface IAudioDevice : IDisposable { - /// - /// Queries asynchronous clip preparation without blocking the owner thread. - /// - /// - /// A handle created by this device generation. - /// - /// - /// The preparation state, or Failed for a retired or invalid handle. - /// - AudioClipState GetClipState(AudioClipHandle clip); - /// /// Gets immutable capabilities for the active device generation. /// @@ -78,6 +32,17 @@ public interface IAudioDevice : IDisposable /// AudioStatistics statistics { get; } + /// + /// Queries asynchronous clip preparation without blocking the owner thread. + /// + /// + /// A handle created by this device generation. + /// + /// + /// The preparation state, or Failed for a retired or invalid handle. + /// + AudioClipState GetClipState(AudioClipHandle clip); + /// /// Starts preparation of one decoded or streamed clip from immutable encoded content. /// @@ -229,7 +194,7 @@ out AudioPlaybackState playbackState /// A bus handle owned by the current device generation. /// AudioBusHandle CreateBus( - AudioBusId id, + AudioBusID id, AudioBusHandle parent = default ); diff --git a/src/services/audio/Inno.Audio/IAudioService.cs b/src/services/audio/Inno.Audio/IAudioService.cs index 508f44f6b..5b3c04f9e 100644 --- a/src/services/audio/Inno.Audio/IAudioService.cs +++ b/src/services/audio/Inno.Audio/IAudioService.cs @@ -178,7 +178,7 @@ out AudioPlaybackState playbackState /// when the bus exists and was updated. /// bool SetBusVolume( - AudioBusId bus, + AudioBusID bus, float volume ); @@ -195,7 +195,7 @@ float volume /// when the bus exists and was updated. /// bool SetBusMuted( - AudioBusId bus, + AudioBusID bus, bool muted ); @@ -212,7 +212,7 @@ bool muted /// when the bus exists and was updated. /// bool SetBusPaused( - AudioBusId bus, + AudioBusID bus, bool paused ); diff --git a/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs b/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs index fe945bdcc..9766f553c 100644 --- a/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs +++ b/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Audio; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Audio", - "Inno.Audio", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Audio", "Inno.Audio", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Audio), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioClipAsset), ScriptingApiScope.Runtime)] @@ -24,10 +21,10 @@ [assembly: ScriptingApiExport(typeof(AudioVoiceHandle), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioBusHandle), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioListenerHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AudioBusId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AudioProcessorId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AudioParameterId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(AudioCodecId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AudioBusID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AudioProcessorID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AudioParameterID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(AudioCodecID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioVoiceCompletedEvent), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioProcessorParameter), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioProcessorConfiguration), ScriptingApiScope.Runtime)] diff --git a/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs b/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs new file mode 100644 index 000000000..ba67c3318 --- /dev/null +++ b/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs @@ -0,0 +1,47 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Audio; + +/// +/// Stores reload-safe configuration for one mixer or feature extension generation. +/// +public struct SerializedAudioExtensionState +{ + /// + /// Creates empty extension state for deserialization. + /// + public SerializedAudioExtensionState() + { + this.propertyData = []; + } + + /// + /// Creates neutral extension state. + /// + /// + /// Stable settings type identity, or empty when no typed settings exist. + /// + /// + /// Neutral serialized property bytes. + /// + public SerializedAudioExtensionState( + Guid stableTypeID, + ReadOnlySpan propertyData + ) { + this.stableTypeId = stableTypeID; + this.propertyData = propertyData.ToArray(); + } + + /// + /// Gets or sets the stable settings type identity. + /// + [SerializableProperty] + public Guid stableTypeId { get; set; } + + /// + /// Gets or sets neutral serialized property bytes. + /// + [SerializableProperty] + public byte[] propertyData { get; set; } +} diff --git a/src/services/input/Inno.Input.Runtime/InputRuntime.cs b/src/services/input/Inno.Input.Runtime/InputRuntime.cs index ac4ebe768..d7f798026 100644 --- a/src/services/input/Inno.Input.Runtime/InputRuntime.cs +++ b/src/services/input/Inno.Input.Runtime/InputRuntime.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Input.Runtime; @@ -20,7 +19,8 @@ public sealed class InputRuntime : RuntimeSubsystem, IInputService /// public InputRuntime(IInputBackend backend) { - m_backend = backend ?? throw new ArgumentNullException(nameof(backend)); + ArgumentNullException.ThrowIfNull(backend); + m_backend = backend; } /// @@ -39,6 +39,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) snapshot = m_backend.Capture(frame.frameIndex); OwnFrameScope(InputExecutionContext.EnterScope(this)); } + /// /// Releases the input backend after its frame scope and owned work have quiesced. /// diff --git a/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs b/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs index e9074130f..bf828b0da 100644 --- a/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs +++ b/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Input.Runtime; @@ -20,15 +19,17 @@ public sealed class InputRuntimeFactory : IRuntimeSubsystemFactory /// public InputRuntimeFactory(Func backendFactory) { - m_backendFactory = backendFactory ?? throw new ArgumentNullException(nameof(backendFactory)); + ArgumentNullException.ThrowIfNull(backendFactory); + m_backendFactory = backendFactory; } /// /// Gets stable ordering metadata for the frame-scoped input service. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.input"), - order: -1000); + new RuntimeSubsystemID("inno.runtime.input"), + order: -1000 + ); /// /// Creates an input feature over a newly allocated session backend. @@ -43,7 +44,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); IInputBackend backend = m_backendFactory(context) - ?? throw new InvalidOperationException("The input backend factory returned null."); + ?? throw new InvalidOperationException("The input backend factory returned null."); return new InputRuntime(backend); } } diff --git a/src/services/input/Inno.Input/Input.cs b/src/services/input/Inno.Input/Input.cs index b4499ca69..8672df558 100644 --- a/src/services/input/Inno.Input/Input.cs +++ b/src/services/input/Inno.Input/Input.cs @@ -1,55 +1,8 @@ -using Inno.Core.Execution; -using System; -using System.Threading; - using Inno.Core.Input; using Inno.Core.Mathematics; namespace Inno.Input; -/// -/// Binds one input service to the current asynchronous execution context. -/// -public static class InputExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("input"); - - /// - /// Gets the input service bound to the current execution context. - /// - /// - /// Thrown when no input scope is active. - /// - public static IInputService current => S_CURRENT_SCOPE.current; - - /// - /// Tries to read input when a host has installed an input subsystem for this frame. - /// - /// - /// Bound service, or null when unavailable. - /// - /// - /// Whether a live input service is bound. - /// - public static bool TryGet(out IInputService? input) => S_CURRENT_SCOPE.TryGet(out input); - - /// - /// Binds an input service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned input service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IInputService input) - { - ArgumentNullException.ThrowIfNull(input); - return S_CURRENT_SCOPE.Enter(input); - } - -} - /// /// Provides script-friendly access to the current frame's input snapshot. /// diff --git a/src/services/input/Inno.Input/InputExecutionContext.cs b/src/services/input/Inno.Input/InputExecutionContext.cs new file mode 100644 index 000000000..f307c623b --- /dev/null +++ b/src/services/input/Inno.Input/InputExecutionContext.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Input; + +/// +/// Binds one input service to the current asynchronous execution context. +/// +public static class InputExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("input"); + + /// + /// Gets the input service bound to the current execution context. + /// + /// + /// Thrown when no input scope is active. + /// + public static IInputService current => CURRENT_SCOPE.current; + + /// + /// Tries to read input when a host has installed an input subsystem for this frame. + /// + /// + /// Bound service, or null when unavailable. + /// + /// + /// Whether a live input service is bound. + /// + public static bool TryGet(out IInputService? input) => CURRENT_SCOPE.TryGet(out input); + + /// + /// Binds an input service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned input service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IInputService input) + { + ArgumentNullException.ThrowIfNull(input); + return CURRENT_SCOPE.Enter(input); + } +} diff --git a/src/services/input/Inno.Input/InputSnapshot.cs b/src/services/input/Inno.Input/InputSnapshot.cs index fcb2c4373..fbe973196 100644 --- a/src/services/input/Inno.Input/InputSnapshot.cs +++ b/src/services/input/Inno.Input/InputSnapshot.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Input; using Inno.Core.Mathematics; @@ -73,8 +72,7 @@ public InputSnapshot( KeyModifier modifiers = KeyModifier.None, IEnumerable? textInput = null ) { - if (frameIndex < 0) - throw new ArgumentOutOfRangeException(nameof(frameIndex)); + ArgumentOutOfRangeException.ThrowIfNegative(frameIndex); this.frameIndex = frameIndex; m_keysDown = Copy(keysDown); m_keysPressed = Copy(keysPressed); @@ -212,5 +210,5 @@ public InputSnapshot( private static HashSet Copy(IEnumerable? values) where TValue : struct, Enum - => values is null ? [] : values.ToHashSet(); + => values is null ? [] : values.ToHashSet(); } diff --git a/src/services/platform/Inno.Platform/IPlatformWindow.cs b/src/services/platform/Inno.Platform/IPlatformWindow.cs index aa71a1e12..9ee76f6dd 100644 --- a/src/services/platform/Inno.Platform/IPlatformWindow.cs +++ b/src/services/platform/Inno.Platform/IPlatformWindow.cs @@ -10,7 +10,7 @@ public interface IPlatformWindow : IDisposable /// /// Gets the application-local identifier of this window. /// - uint windowId { get; } + uint windowID { get; } /// /// Gets the title captured when the window was created. diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs new file mode 100644 index 000000000..dbd9c091a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Contains an immutable target shader artifact and expected reflected interface. +/// +[StableTypeID("25e556fe-a071-58b2-8e70-0e41bd434d83")] +public sealed class CompiledShaderArtifact +{ + private readonly byte[] m_definitionData; + + /// + /// Creates a compiled shader artifact. + /// + /// + /// Artist-facing shader name. + /// + /// + /// Stable target cache key. + /// + /// + /// Static keyword variant. + /// + /// + /// Manifest-derived binding contract. + /// + /// + /// Compiled pass binaries. + /// + /// + /// Native-serialized runtime definition captured before asynchronous compilation. + /// + public CompiledShaderArtifact( + string shaderName, + string targetKey, + RenderShaderVariant variant, + ShaderInterface shaderInterface, + IReadOnlyList passes, + ReadOnlySpan definitionData + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(shaderName); + ArgumentException.ThrowIfNullOrWhiteSpace(targetKey); + ArgumentNullException.ThrowIfNull(shaderInterface); + ArgumentNullException.ThrowIfNull(passes); + this.shaderName = shaderName; + this.targetKey = targetKey; + this.variant = variant; + this.shaderInterface = shaderInterface; + this.passes = Array.AsReadOnly(passes.ToArray()); + if (definitionData.IsEmpty) + { + throw new ArgumentException("Compiled programs require a captured runtime contract.", nameof(definitionData)); + } + m_definitionData = definitionData.ToArray(); + } + + /// + /// Gets the artist-facing shader name. + /// + public string shaderName { get; } + + /// + /// Gets the stable target cache key. + /// + public string targetKey { get; } + + /// + /// Gets the static keyword variant. + /// + public RenderShaderVariant variant { get; } + + /// + /// Gets the manifest-derived binding contract. + /// + public ShaderInterface shaderInterface { get; } + + /// + /// Gets compiled pass binaries. + /// + public IReadOnlyList passes { get; } + + /// + /// Creates the source-free deployment artifact consumed by Editor preview sessions and Players. + /// + /// + /// A deep immutable runtime artifact containing only target binaries, fixed-function state, and binding contracts. + /// + public RenderShaderArtifact CreateRuntimeArtifact() + => new( + shaderName, + targetKey, + variant, + shaderInterface, + passes.Select(static pass => new RenderShaderPassArtifact( + pass.definition.name, + pass.definition.programKind, + ConvertRasterState(pass.definition.renderState), + pass.shaderInterface, + pass.stages.Select(static stage => new RenderShaderStageArtifact( + stage.stage, + stage.bytes.Span + )).ToArray() + )).ToArray(), + m_definitionData + ); + + private static RenderRasterState ConvertRasterState(ShaderRenderState source) + => new() + { + topology = source.topology, + cull = source.cull switch + { + ShaderCullMode.None => RenderCullMode.None, + ShaderCullMode.Front => RenderCullMode.Front, + ShaderCullMode.Back => RenderCullMode.Back, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + frontFace = source.frontFace, + depthCompare = source.depthCompare switch + { + ShaderCompareFunction.Never => RenderDepthCompare.Never, + ShaderCompareFunction.Less => RenderDepthCompare.Less, + ShaderCompareFunction.Equal => RenderDepthCompare.Equal, + ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, + ShaderCompareFunction.Greater => RenderDepthCompare.Greater, + ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, + ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, + ShaderCompareFunction.Always => RenderDepthCompare.Always, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + depthWrite = source.depthWrite, + blend = source.blend, + colorWriteMask = source.colorWriteMask, + multisampling = source.multisampling + }; +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs new file mode 100644 index 000000000..8886dc240 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Stores all compiled stages and state for one shader pass. +/// +[StableTypeID("6a66aac0-d44d-5d90-a801-d92605a92c91")] +public sealed class CompiledShaderPass +{ + private readonly ShaderPassDefinition m_definition; + + /// + /// Creates a compiled pass artifact. + /// + /// + /// Stable pass definition. + /// + /// + /// Compiled target stages. + /// + /// + /// Pass-local manifest binding contract. + /// + public CompiledShaderPass( + ShaderPassDefinition definition, + IReadOnlyList stages, + ShaderInterface shaderInterface + ) { + ArgumentNullException.ThrowIfNull(stages); + ArgumentNullException.ThrowIfNull(shaderInterface); + definition.metadata = definition.metadata?.ToArray() ?? []; + m_definition = definition; + this.stages = Array.AsReadOnly(stages.ToArray()); + this.shaderInterface = shaderInterface; + } + + /// + /// Gets the stable pass definition. + /// + public ShaderPassDefinition definition + { + get + { + ShaderPassDefinition value = m_definition; + value.metadata = value.metadata.ToArray(); + return value; + } + } + + /// + /// Gets compiled target stages. + /// + public IReadOnlyList stages { get; } + + /// + /// Gets the pass-local manifest binding contract. + /// + public ShaderInterface shaderInterface { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs new file mode 100644 index 000000000..fe00c6e18 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Defines a backend-owned target compiler used by the common Shader IR pipeline. +/// +[StableTypeID("00437bae-b212-505f-8017-d59fd29fb005")] +public interface IShaderCompilerToolchain +{ + /// + /// Gets the stable source implementation identity paired with this rendering adapter. + /// + string implementationID { get; } + + /// + /// Gets the explicit source-language identities accepted by this adapter's typed IR generator. + /// + IReadOnlyList supportedSourceLanguages { get; } + + /// + /// Generates and compiles one typed stage, including its frozen function modules and resource layout. + /// + /// + /// Typed stage and exact target profile. + /// + /// + /// Cancellation before publishing the candidate. + /// + /// + /// Immutable compiled bytes, generated binding names and structured diagnostics. + /// + ValueTask CompileAsync( + ShaderStageToolRequest request, + CancellationToken cancellationToken + ); + + /// + /// Creates a target supported by this toolchain and capability snapshot. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether compiler debug information is emitted. + /// + /// + /// A stable target description accepted by this toolchain. + /// + ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs similarity index 90% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs index 0cd66d6ed..44cf9c516 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs @@ -1,16 +1,15 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Extensibility.Types; namespace Inno.Rendering.Assets.Authoring; /// /// Converts supported artist texture sources into a validated portable runtime container. /// -[Inno.Extensibility.Types.StableTypeId("01400c3b-21c2-5193-ae8f-3cf3665f4261")] +[StableTypeID("01400c3b-21c2-5193-ae8f-3cf3665f4261")] public interface ITextureTargetCompiler { /// @@ -37,4 +36,3 @@ ValueTask CompileKtxAsync( CancellationToken cancellationToken = default ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs new file mode 100644 index 000000000..37d8773ea --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Describes the artifact selected after evaluating a candidate compilation. +/// +[StableTypeID("2cbb2378-91ef-5c66-866e-e651e80a79a7")] +public sealed class ShaderArtifactSelection +{ + /// + /// Creates an artifact selection result. + /// + /// + /// Selected candidate or last-good artifact. + /// + /// + /// Whether the candidate replaced active state. + /// + /// + /// Whether a previous artifact was preserved. + /// + /// + /// Candidate diagnostics. + /// + public ShaderArtifactSelection( + CompiledShaderArtifact? artifact, + bool candidateSucceeded, + bool usingLastGood, + IReadOnlyList diagnostics + ) { + ArgumentNullException.ThrowIfNull(diagnostics); + this.artifact = artifact; + this.candidateSucceeded = candidateSucceeded; + this.usingLastGood = usingLastGood; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the selected candidate or last-good artifact. + /// + public CompiledShaderArtifact? artifact { get; } + + /// + /// Gets whether the candidate replaced active state. + /// + public bool candidateSucceeded { get; } + + /// + /// Gets whether a previous artifact was preserved. + /// + public bool usingLastGood { get; } + + /// + /// Gets candidate diagnostics. + /// + public IReadOnlyList diagnostics { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs deleted file mode 100644 index 54e64f0e0..000000000 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs +++ /dev/null @@ -1,447 +0,0 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Inno.Rendering.Assets.Authoring; - -/// -/// Selects one renderer profile and compilation policy. -/// -[Inno.Extensibility.Types.StableTypeId("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] -public sealed class ShaderCompileTarget -{ - /// - /// Creates a shader compilation target. - /// - /// - /// Backend compiler-owned stable profile key. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether shader debug information is emitted. - /// - public ShaderCompileTarget( - string profileKey, - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(profileKey); - ArgumentNullException.ThrowIfNull(capabilities); - this.profileKey = profileKey; - this.capabilities = capabilities; - this.optimize = optimize; - this.debugInformation = debugInformation; - } - - /// - /// Gets the backend compiler-owned stable profile key. - /// - public string profileKey { get; } - - /// - /// Gets target renderer capabilities. - /// - public GraphicsCapabilities capabilities { get; } - - /// - /// Gets whether release optimization is enabled. - /// - public bool optimize { get; } - - /// - /// Gets whether shader debug information is emitted. - /// - public bool debugInformation { get; } - - /// - /// Gets a stable target cache-key fragment. - /// - public string key => $"{profileKey}:opt={optimize}:debug={debugInformation}"; -} - -/// -/// Stores one immutable target stage binary. -/// -[Inno.Extensibility.Types.StableTypeId("7de46626-7dd7-5112-b098-ef3eb53a0cda")] -public sealed class ShaderStageArtifact -{ - private readonly byte[] m_bytes; - - /// - /// Creates a stage artifact. - /// - /// - /// Single compiled shader stage. - /// - /// - /// Target binary bytes. - /// - /// - /// Original source mapping. - /// - public ShaderStageArtifact( - ShaderStage stage, - ReadOnlySpan bytes, - ShaderSourceLocation sourceLocation - ) { - if (bytes.IsEmpty) - { - throw new ArgumentException("A compiled shader stage cannot be empty.", nameof(bytes)); - } - - this.stage = stage; - m_bytes = bytes.ToArray(); - this.sourceLocation = sourceLocation; - } - - /// - /// Gets the compiled shader stage. - /// - public ShaderStage stage { get; } - - /// - /// Gets immutable target binary bytes. - /// - public ReadOnlyMemory bytes => m_bytes; - - /// - /// Gets the original source mapping. - /// - public ShaderSourceLocation sourceLocation { get; } -} - -/// -/// Stores all compiled stages and state for one shader pass. -/// -[Inno.Extensibility.Types.StableTypeId("6a66aac0-d44d-5d90-a801-d92605a92c91")] -public sealed class CompiledShaderPass -{ - private readonly ShaderPassDefinition m_definition; - /// - /// Creates a compiled pass artifact. - /// - /// - /// Stable pass definition. - /// - /// - /// Compiled target stages. - /// - /// - /// Pass-local manifest binding contract. - /// - public CompiledShaderPass( - ShaderPassDefinition definition, - IReadOnlyList stages, - ShaderInterface shaderInterface - ) { - ArgumentNullException.ThrowIfNull(stages); - ArgumentNullException.ThrowIfNull(shaderInterface); - definition.metadata = definition.metadata?.ToArray() ?? []; - m_definition = definition; - this.stages = Array.AsReadOnly(stages.ToArray()); - this.shaderInterface = shaderInterface; - } - - /// - /// Gets the stable pass definition. - /// - public ShaderPassDefinition definition - { - get - { - ShaderPassDefinition value = m_definition; - value.metadata = value.metadata.ToArray(); - return value; - } - } - - /// - /// Gets compiled target stages. - /// - public IReadOnlyList stages { get; } - - /// - /// Gets the pass-local manifest binding contract. - /// - public ShaderInterface shaderInterface { get; } -} - -/// -/// Contains an immutable target shader artifact and expected reflected interface. -/// -[Inno.Extensibility.Types.StableTypeId("25e556fe-a071-58b2-8e70-0e41bd434d83")] -public sealed class CompiledShaderArtifact -{ - private readonly byte[] m_definitionData; - /// - /// Creates a compiled shader artifact. - /// - /// - /// Artist-facing shader name. - /// - /// - /// Stable target cache key. - /// - /// - /// Static keyword variant. - /// - /// - /// Manifest-derived binding contract. - /// - /// - /// Compiled pass binaries. - /// - /// - /// Native-serialized runtime definition captured before asynchronous compilation. - /// - public CompiledShaderArtifact( - string shaderName, - string targetKey, - RenderShaderVariant variant, - ShaderInterface shaderInterface, - IReadOnlyList passes, - ReadOnlySpan definitionData - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(shaderName); - ArgumentException.ThrowIfNullOrWhiteSpace(targetKey); - ArgumentNullException.ThrowIfNull(shaderInterface); - ArgumentNullException.ThrowIfNull(passes); - this.shaderName = shaderName; - this.targetKey = targetKey; - this.variant = variant; - this.shaderInterface = shaderInterface; - this.passes = Array.AsReadOnly(passes.ToArray()); - if (definitionData.IsEmpty) - throw new ArgumentException("Compiled programs require a captured runtime contract.", nameof(definitionData)); - m_definitionData = definitionData.ToArray(); - } - - /// - /// Gets the artist-facing shader name. - /// - public string shaderName { get; } - - /// - /// Gets the stable target cache key. - /// - public string targetKey { get; } - - /// - /// Gets the static keyword variant. - /// - public RenderShaderVariant variant { get; } - - /// - /// Gets the manifest-derived binding contract. - /// - public ShaderInterface shaderInterface { get; } - - /// - /// Gets compiled pass binaries. - /// - public IReadOnlyList passes { get; } - - /// - /// Creates the source-free deployment artifact consumed by Editor preview sessions and Players. - /// - /// - /// A deep immutable runtime artifact containing only target binaries, fixed-function state, and binding contracts. - /// - public RenderShaderArtifact CreateRuntimeArtifact() - => new( - shaderName, - targetKey, - variant, - shaderInterface, - passes.Select(static pass => new RenderShaderPassArtifact( - pass.definition.name, - pass.definition.programKind, - ConvertRasterState(pass.definition.renderState), - pass.shaderInterface, - pass.stages.Select(static stage => new RenderShaderStageArtifact( - stage.stage, - stage.bytes.Span)).ToArray())).ToArray(), - m_definitionData); - - private static RenderRasterState ConvertRasterState(ShaderRenderState source) - => new() - { - topology = source.topology, - cull = source.cull switch - { - ShaderCullMode.None => RenderCullMode.None, - ShaderCullMode.Front => RenderCullMode.Front, - ShaderCullMode.Back => RenderCullMode.Back, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - frontFace = source.frontFace, - depthCompare = source.depthCompare switch - { - ShaderCompareFunction.Never => RenderDepthCompare.Never, - ShaderCompareFunction.Less => RenderDepthCompare.Less, - ShaderCompareFunction.Equal => RenderDepthCompare.Equal, - ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, - ShaderCompareFunction.Greater => RenderDepthCompare.Greater, - ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, - ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, - ShaderCompareFunction.Always => RenderDepthCompare.Always, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - depthWrite = source.depthWrite, - blend = source.blend, - colorWriteMask = source.colorWriteMask, - multisampling = source.multisampling - }; -} - -/// -/// Returns a candidate artifact and structured diagnostics without mutating active state. -/// -[Inno.Extensibility.Types.StableTypeId("72b304de-8a2b-5c08-b899-b4aef05be149")] -public sealed class ShaderCompilationResult -{ - /// - /// Creates a shader compilation result. - /// - /// - /// Candidate artifact, or after failure. - /// - /// - /// Validation and compiler diagnostics. - /// - public ShaderCompilationResult( - CompiledShaderArtifact? artifact, - IReadOnlyList diagnostics - ) { - ArgumentNullException.ThrowIfNull(diagnostics); - this.artifact = artifact; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the candidate artifact, or after failure. - /// - public CompiledShaderArtifact? artifact { get; } - - /// - /// Gets validation and compiler diagnostics. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets whether a complete candidate artifact was produced. - /// - public bool succeeded => artifact is not null - && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} - -/// -/// Defines a backend-owned target compiler used by the common Shader IR pipeline. -/// -[Inno.Extensibility.Types.StableTypeId("00437bae-b212-505f-8017-d59fd29fb005")] -public interface IShaderCompilerToolchain -{ - /// - /// Gets the stable source implementation identity paired with this rendering adapter. - /// - string implementationId { get; } - - /// - /// Gets the explicit source-language identities accepted by this adapter's typed IR generator. - /// - IReadOnlyList supportedSourceLanguages { get; } - - /// - /// Generates and compiles one typed stage, including its frozen function modules and resource layout. - /// - /// - /// Typed stage and exact target profile. - /// - /// - /// Cancellation before publishing the candidate. - /// - /// - /// Immutable compiled bytes, generated binding names and structured diagnostics. - /// - ValueTask CompileAsync( - ShaderStageToolRequest request, - CancellationToken cancellationToken - ); - - /// - /// Creates a target supported by this toolchain and capability snapshot. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether compiler debug information is emitted. - /// - /// - /// A stable target description accepted by this toolchain. - /// - ShaderCompileTarget CreateTarget( - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ); - -} - -/// -/// Compiles validated Shader IR through one target toolchain. -/// -[Inno.Extensibility.Types.StableTypeId("85c9086c-63d5-51e6-82ec-548ad39702e2")] -public sealed partial class ShaderCompiler -{ - private readonly IShaderCompilerToolchain m_toolchain; - - /// - /// Creates a common IR compiler with one backend-owned target toolchain. - /// - /// - /// Backend compiler implementation. - /// - public ShaderCompiler(IShaderCompilerToolchain toolchain) - { - m_toolchain = toolchain ?? throw new ArgumentNullException(nameof(toolchain)); - } - - /// - /// Creates a target supported by the configured backend compiler. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether compiler debug information is emitted. - /// - /// - /// A stable target description accepted by this compiler. - /// - public ShaderCompileTarget CreateTarget( - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ) - => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); - -} - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs new file mode 100644 index 000000000..6117fcc80 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Returns a candidate artifact and structured diagnostics without mutating active state. +/// +[StableTypeID("72b304de-8a2b-5c08-b899-b4aef05be149")] +public sealed class ShaderCompilationResult +{ + /// + /// Creates a shader compilation result. + /// + /// + /// Candidate artifact, or after failure. + /// + /// + /// Validation and compiler diagnostics. + /// + public ShaderCompilationResult( + CompiledShaderArtifact? artifact, + IReadOnlyList diagnostics + ) { + ArgumentNullException.ThrowIfNull(diagnostics); + this.artifact = artifact; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the candidate artifact, or after failure. + /// + public CompiledShaderArtifact? artifact { get; } + + /// + /// Gets validation and compiler diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a complete candidate artifact was produced. + /// + public bool succeeded + => artifact is not null + && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs new file mode 100644 index 000000000..3cee16c93 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Selects one renderer profile and compilation policy. +/// +[StableTypeID("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] +public sealed class ShaderCompileTarget +{ + /// + /// Creates a shader compilation target. + /// + /// + /// Backend compiler-owned stable profile key. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether shader debug information is emitted. + /// + public ShaderCompileTarget( + string profileKey, + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(profileKey); + ArgumentNullException.ThrowIfNull(capabilities); + this.profileKey = profileKey; + this.capabilities = capabilities; + this.optimize = optimize; + this.debugInformation = debugInformation; + } + + /// + /// Gets the backend compiler-owned stable profile key. + /// + public string profileKey { get; } + + /// + /// Gets target renderer capabilities. + /// + public GraphicsCapabilities capabilities { get; } + + /// + /// Gets whether release optimization is enabled. + /// + public bool optimize { get; } + + /// + /// Gets whether shader debug information is emitted. + /// + public bool debugInformation { get; } + + /// + /// Gets a stable target cache-key fragment. + /// + public string key => $"{profileKey}:opt={optimize}:debug={debugInformation}"; +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs similarity index 61% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs index 15b68fec4..b5cf3e683 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs @@ -1,14 +1,13 @@ -using Inno.Core.Diagnostics; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Core.Diagnostics; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; @@ -18,101 +17,133 @@ namespace Inno.Rendering.Assets.Authoring; public sealed partial class ShaderCompiler { /// - /// Captures an imported graph in the current owner generation, then starts native compilation without retaining its asset. + /// Compiles an immutable import or preview candidate without reading or mutating a canonical Shader asset. /// - /// - /// Committed graph-backed shader asset. + /// + /// Frozen target-expanded graph and source bundles. /// /// - /// Target policy and device capabilities. + /// Target policy and capabilities. /// /// - /// Exact material keyword selection. + /// Exact keyword selection. /// /// - /// Shared authoring type generation owner. + /// Current authoring generation. /// /// /// Owner converter registry. /// /// - /// Complete owner asset/reference context. - /// - /// - /// Authoring artifact owner supplying the graph output, which is absent from runtime packages. + /// Complete owner references captured before asynchronous native work. /// /// - /// Cancellation before candidate publication. + /// Cancellation of this candidate. /// /// - /// A native compilation task for the captured graph, or graph diagnostics without any native work. + /// A complete immutable compilation result, never published by this method. /// public ValueTask CompileGraphAsync( - ShaderAsset shader, + ReadOnlyMemory artifact, ShaderCompileTarget target, RenderShaderVariant variant, TypeCatalog types, SerializationRegistry serialization, SerializationContext context, - Inno.Assets.IAssetArtifactLookup artifacts, CancellationToken cancellationToken = default ) { - ArgumentNullException.ThrowIfNull(shader); - return CompileGraphAsync(ShaderGraphArtifact.Read(shader, artifacts), target, variant, types, serialization, context, cancellationToken); + using IDisposable operation = types.AcquireOperation("Capture shader graph compilation"); + using var nodes = new ShaderNodeCompilerRegistry(types); + using var frontends = new ShaderSourceFrontendRegistry(types); + ShaderDefinition definition = ShaderGraphArtifact.ReadDefinition(artifact.Span, serialization, context); + List diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); + if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { + return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } + Dictionary keywords = definition.keywords.ToDictionary( + static value => value.id, + StringComparer.Ordinal + ); + foreach ((string id, string value) in variant.options) + { + if (!keywords.TryGetValue(id, out ShaderKeywordDefinition keyword) || !keyword.options.Contains(value, StringComparer.Ordinal)) + { + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_VARIANT_INVALID", + DiagnosticSeverity.Error, + $"Shader variant selects undeclared option '{id}={value}'." + ) + ); + } + } + if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { + return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } + ShaderGraphProgramResult program = ShaderGraphArtifact.Lower( + artifact.Span, + m_toolchain.implementationID, + nodes, + frontends, + serialization, + context, + variant.options + ); + return CompileAsync(definition, program, target, variant, serialization, context, cancellationToken); } /// - /// Compiles an immutable import or preview candidate without reading or mutating a canonical Shader asset. + /// Captures an imported graph in the current owner generation, then starts native compilation without retaining its asset. /// - /// - /// Frozen target-expanded graph and source bundles. + /// + /// Committed graph-backed shader asset. /// /// - /// Target policy and capabilities. + /// Target policy and device capabilities. /// /// - /// Exact keyword selection. + /// Exact material keyword selection. /// /// - /// Current authoring generation. + /// Shared authoring type generation owner. /// /// /// Owner converter registry. /// /// - /// Complete owner references captured before asynchronous native work. + /// Complete owner asset/reference context. + /// + /// + /// Authoring artifact owner supplying the graph output, which is absent from runtime packages. /// /// - /// Cancellation of this candidate. + /// Cancellation before candidate publication. /// /// - /// A complete immutable compilation result, never published by this method. + /// A native compilation task for the captured graph, or graph diagnostics without any native work. /// public ValueTask CompileGraphAsync( - ReadOnlyMemory artifact, + ShaderAsset shader, ShaderCompileTarget target, RenderShaderVariant variant, TypeCatalog types, SerializationRegistry serialization, SerializationContext context, + IAssetArtifactLookup artifacts, CancellationToken cancellationToken = default ) { - using IDisposable operation = types.AcquireOperation("Capture shader graph compilation"); - using var nodes = new ShaderNodeCompilerRegistry(types); - using var frontends = new ShaderSourceFrontendRegistry(types); - ShaderDefinition definition = ShaderGraphArtifact.ReadDefinition(artifact.Span, serialization, context); - var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); - if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); - var keywords = definition.keywords.ToDictionary(static value => value.id, StringComparer.Ordinal); - foreach ((string id, string value) in variant.options) - if (!keywords.TryGetValue(id, out ShaderKeywordDefinition keyword) || !keyword.options.Contains(value, StringComparer.Ordinal)) - diagnostics.Add(new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.")); - if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); - ShaderGraphProgramResult program = ShaderGraphArtifact.Lower(artifact.Span, m_toolchain.implementationId, - nodes, frontends, serialization, context, variant.options); - return CompileAsync(definition, program, target, variant, serialization, context, cancellationToken); + ArgumentNullException.ThrowIfNull(shader); + return CompileGraphAsync( + ShaderGraphArtifact.Read(shader, artifacts), + target, + variant, + types, + serialization, + context, + cancellationToken + ); } /// @@ -156,23 +187,56 @@ public ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(program); ArgumentNullException.ThrowIfNull(target); - var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); + List diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } foreach ((string id, string value) in variant.options) + { if (!definition.keywords.Any(keyword => keyword.id == id && keyword.options.Contains(value, StringComparer.Ordinal))) - diagnostics.Add(new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.")); + { + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_VARIANT_INVALID", + DiagnosticSeverity.Error, + $"Shader variant selects undeclared option '{id}={value}'." + ) + ); + } + } if (diagnostics.Count != 0 && diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } byte[] definitionData = serialization.Serialize(definition, context); - var captured = new ShaderDefinition(definition.name, - definition.properties.Select(static value => new ShaderPropertyDefinition(value.id, value.displayName, - value.type, value.stages, default, value.bindingKind, value.storageAccess, value.bindingOwner)), + var captured = new ShaderDefinition( + definition.name, + definition.properties.Select(static value => new ShaderPropertyDefinition( + value.id, + value.displayName, + value.type, + value.stages, + default, + value.bindingKind, + value.storageAccess, + value.bindingOwner + )), definition.keywords.Select(static value => new ShaderKeywordDefinition(value.id, value.options.ToArray())), - definition.passes.Select(static value => new ShaderPassDefinition(value.name, value.programKind, - value.requiredFeatures, value.renderState, value.metadata)), - definition.techniques.Select(static value => new ShaderTechniqueDefinition(value.id, value.contract, - value.passes.ToArray(), value.requiredFeatures))); + definition.passes.Select(static value => new ShaderPassDefinition( + value.name, + value.programKind, + value.requiredFeatures, + value.renderState, + value.metadata + )), + definition.techniques.Select(static value => new ShaderTechniqueDefinition( + value.id, + value.contract, + value.passes.ToArray(), + value.requiredFeatures + )) + ); return CompileCapturedAsync(captured, definitionData, program, target, variant, cancellationToken); } @@ -187,70 +251,144 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(program); ArgumentNullException.ThrowIfNull(target); - var diagnostics = program.diagnostics.Select(static value => new ShaderDiagnostic(value.code, value.severity, value.message)).ToList(); + List diagnostics = program.diagnostics + .Select(static value => new ShaderDiagnostic(value.code, value.severity, value.message)) + .ToList(); diagnostics.AddRange(ShaderDefinitionValidator.Validate(definition, target.capabilities)); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new(null, diagnostics); + } if (!program.succeeded) + { return new(null, diagnostics); + } string shaderName = definition.name; // Only value contracts cross the asynchronous native compiler boundary. Texture defaults remain owned by the imported asset. - ShaderPropertyDefinition[] properties = definition.properties.Select(static value => new ShaderPropertyDefinition(value.id, - value.displayName, value.type, value.stages, default, value.bindingKind, value.storageAccess, value.bindingOwner)).ToArray(); - var passes = definition.passes.Select(static value => new ShaderPassDefinition(value.name, value.programKind, - requiredFeatures: value.requiredFeatures, renderState: value.renderState, metadata: value.metadata)).ToDictionary(static value => value.name, StringComparer.Ordinal); - var compiledPasses = new List(); + ShaderPropertyDefinition[] properties = definition.properties.Select(static value => new ShaderPropertyDefinition( + value.id, + value.displayName, + value.type, + value.stages, + default, + value.bindingKind, + value.storageAccess, + value.bindingOwner + )).ToArray(); + Dictionary passes = definition.passes.Select(static value => new ShaderPassDefinition( + value.name, + value.programKind, + requiredFeatures: value.requiredFeatures, + renderState: value.renderState, + metadata: value.metadata + )).ToDictionary(static value => value.name, StringComparer.Ordinal); + List compiledPasses = []; var allBindings = new Dictionary(StringComparer.Ordinal); foreach (ShaderGraphPass pass in program.passes) { cancellationToken.ThrowIfCancellationRequested(); if (!passes.TryGetValue(pass.name, out ShaderPassDefinition passDefinition)) + { throw new InvalidOperationException($"The graph produced undeclared pass '{pass.name}'."); + } if ((passDefinition.requiredFeatures & ~target.capabilities.features) != 0) + { continue; - var binaries = new List(); + } + List binaries = []; var bindings = new Dictionary(StringComparer.Ordinal); foreach (ShaderIrStage stage in pass.stages) { ShaderStageToolResult result = await CompileAsync(stage, target, cancellationToken).ConfigureAwait(false); - diagnostics.AddRange(result.diagnostics.Select(value => new ShaderDiagnostic(value.code, value.severity, value.message, - new ShaderSourceLocation(value.location.assetPath, pass.name, stage.stage, value.location.line, value.location.column)))); + diagnostics.AddRange( + result.diagnostics.Select(value => new ShaderDiagnostic( + value.code, + value.severity, + value.message, + new ShaderSourceLocation( + value.location.assetPath, + pass.name, + stage.stage, + value.location.line, + value.location.column + ) + )) + ); if (!result.succeeded) + { return new(null, diagnostics); - binaries.Add(new(stage.stage, result.bytes.Span, new ShaderSourceLocation(shaderName, pass.name, stage.stage))); + } + binaries.Add( + new ShaderStageArtifact(stage.stage, result.bytes.Span, new ShaderSourceLocation(shaderName, pass.name, stage.stage)) + ); foreach (ShaderStageBinding generated in result.bindings) { ShaderPropertyDefinition[] matches = properties.Where(value => value.id.value == generated.id).ToArray(); if (matches.Length != 1) { - diagnostics.Add(new("SHADER_GRAPH_BINDING", DiagnosticSeverity.Error, - $"Generated binding '{generated.id}' requires exactly one declared shader property.")); + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_GRAPH_BINDING", + DiagnosticSeverity.Error, + $"Generated binding '{generated.id}' requires exactly one declared shader property." + ) + ); continue; } ShaderPropertyDefinition property = matches[0]; ShaderIrStageInput input = stage.inputs.Single(value => value.id == generated.id); if ((property.stages & stage.stage) == 0 || !Matches(property, input)) { - diagnostics.Add(new("SHADER_GRAPH_BINDING_TYPE", DiagnosticSeverity.Error, - $"Property '{generated.id}' does not match the {stage.stage} graph binding's type, access or visibility.")); + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_GRAPH_BINDING_TYPE", + DiagnosticSeverity.Error, + $"Property '{generated.id}' does not match the {stage.stage} graph binding's type, access or visibility." + ) + ); continue; } - var binding = new ShaderInterfaceBinding(property.id, property.type, stage.stage, + var binding = new ShaderInterfaceBinding( + property.id, + property.type, + stage.stage, input.type.elementType is null ? 1 : input.type.elementCount, - property.bindingKind, property.storageAccess, generated.nativeName, - property.bindingKind == ShaderPropertyBindingKind.Uniform ? null : generated.location); + property.bindingKind, + property.storageAccess, + generated.nativeName, + property.bindingKind == ShaderPropertyBindingKind.Uniform ? null : generated.location + ); Merge(bindings, binding); Merge(allBindings, binding); } } - compiledPasses.Add(new(passDefinition, binaries, new(bindings.Values.ToArray()))); + compiledPasses.Add(new CompiledShaderPass(passDefinition, binaries, new ShaderInterface(bindings.Values.ToArray()))); } if (compiledPasses.Count == 0) - diagnostics.Add(new("SHADER_NO_SUPPORTED_PASS", DiagnosticSeverity.Error, - $"Shader '{shaderName}' has no pass supported by '{target.key}'.")); + { + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_NO_SUPPORTED_PASS", + DiagnosticSeverity.Error, + $"Shader '{shaderName}' has no pass supported by '{target.key}'." + ) + ); + } if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new(null, diagnostics); - return new(new(shaderName, target.key, variant, new(allBindings.Values.ToArray()), compiledPasses, definitionData), diagnostics); + } + return new( + new CompiledShaderArtifact( + shaderName, + target.key, + variant, + new ShaderInterface(allBindings.Values.ToArray()), + compiledPasses, + definitionData + ), + diagnostics + ); } private static bool Matches( @@ -258,11 +396,21 @@ private static bool Matches( ShaderIrStageInput input ) { if (property.bindingKind == ShaderPropertyBindingKind.StorageBuffer) - return input.kind == ShaderIrInputKind.Storage && input.type.storage is { isImage: false } buffer && buffer.access == property.storageAccess; + { + return input.kind == ShaderIrInputKind.Storage + && input.type.storage is { isImage: false } buffer + && buffer.access == property.storageAccess; + } if (property.bindingKind == ShaderPropertyBindingKind.StorageTexture) - return input.kind == ShaderIrInputKind.Storage && input.type.storage is { isImage: true } image && image.access == property.storageAccess; + { + return input.kind == ShaderIrInputKind.Storage + && input.type.storage is { isImage: true } image + && image.access == property.storageAccess; + } if ((property.bindingKind == ShaderPropertyBindingKind.SampledTexture) != (input.kind == ShaderIrInputKind.SampledTexture)) + { return false; + } string type = (input.type.elementType ?? input.type).id; return property.type switch { @@ -286,12 +434,25 @@ ShaderInterfaceBinding binding if (target.TryGetValue(binding.id.value, out ShaderInterfaceBinding? previous)) { if (previous.type != binding.type || previous.arrayCount != binding.arrayCount || previous.bindingKind != binding.bindingKind - || previous.storageAccess != binding.storageAccess || previous.nativeName != binding.nativeName || previous.location != binding.location) - throw new InvalidOperationException($"Shader binding '{binding.id}' has inconsistent native layouts between stages or passes."); - binding = new(binding.id, binding.type, previous.stages | binding.stages, binding.arrayCount, binding.bindingKind, - binding.storageAccess, binding.nativeName, binding.location); + || previous.storageAccess != binding.storageAccess + || previous.nativeName != binding.nativeName + || previous.location != binding.location + ) { + throw new InvalidOperationException( + $"Shader binding '{binding.id}' has inconsistent native layouts between stages or passes." + ); + } + binding = new( + binding.id, + binding.type, + previous.stages | binding.stages, + binding.arrayCount, + binding.bindingKind, + binding.storageAccess, + binding.nativeName, + binding.location + ); } target[binding.id.value] = binding; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs new file mode 100644 index 000000000..36f60c9dc --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Carries validated inputs and outputs for one shader compilation stage. +/// +public sealed partial class ShaderCompiler +{ + private readonly object m_stageCacheLock = new(); + private readonly Dictionary<(string stage, string target, GraphicsCapabilities capabilities), ShaderStageToolResult> m_stageCache = []; + private long m_stageCacheBytes; + + /// + /// Compiles a typed stage through the configured adapter without an intermediate complete-source authoring asset. + /// + /// + /// Typed stage and frozen function modules. + /// + /// + /// Configured target capability/profile snapshot. + /// + /// + /// Cancellation before publishing the candidate. + /// + /// + /// Compiled stage bytes, exact generated binding names and structured diagnostics. + /// + public async ValueTask CompileAsync( + ShaderIrStage stage, + ShaderCompileTarget target, + CancellationToken cancellationToken = default + ) { + ArgumentNullException.ThrowIfNull(stage); + ArgumentNullException.ThrowIfNull(target); + cancellationToken.ThrowIfCancellationRequested(); + (string contentHash, string key, GraphicsCapabilities capabilities) key = (stage.contentHash, target.key, target.capabilities); + lock (m_stageCacheLock) + { + if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) + { + return previous; + } + } + ShaderStageToolResult result = await m_toolchain.CompileAsync( + new ShaderStageToolRequest(stage, target), + cancellationToken + ).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + // The bounded cache contains immutable backend results only, never IR, providers or source assets. + // Failed and cancelled requests are not cached, and layout-only graph edits reuse the semantic key. + if (result.succeeded && result.bytes.Length <= 32 * 1024 * 1024) + { + lock (m_stageCacheLock) + { + if (m_stageCache.Count >= 256 || m_stageCacheBytes + result.bytes.Length > 32 * 1024 * 1024) + { + m_stageCache.Clear(); + m_stageCacheBytes = 0; + } + if (m_stageCache.TryAdd(key, result)) + { + m_stageCacheBytes += result.bytes.Length; + } + } + } + return result; + } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs new file mode 100644 index 000000000..ec81bb505 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Compiles validated Shader IR through one target toolchain. +/// +[StableTypeID("85c9086c-63d5-51e6-82ec-548ad39702e2")] +public sealed partial class ShaderCompiler +{ + private readonly IShaderCompilerToolchain m_toolchain; + + /// + /// Creates a common IR compiler with one backend-owned target toolchain. + /// + /// + /// Backend compiler implementation. + /// + public ShaderCompiler(IShaderCompilerToolchain toolchain) + { + ArgumentNullException.ThrowIfNull(toolchain); + m_toolchain = toolchain; + } + + /// + /// Creates a target supported by the configured backend compiler. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether compiler debug information is emitted. + /// + /// + /// A stable target description accepted by this compiler. + /// + public ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs index 30a2c6b03..58d945b78 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs @@ -1,27 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using Inno.Assets; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Threading; namespace Inno.Rendering.Assets.Authoring; /// /// Persists graph and frozen function inputs as an authoring artifact; Player export removes this payload. /// -[Inno.Extensibility.Types.StableTypeId("1bb0d88f-b8ca-5d43-a91c-8d6d4ac0f0c2")] +[StableTypeID("1bb0d88f-b8ca-5d43-a91c-8d6d4ac0f0c2")] public static partial class ShaderGraphArtifact { /// /// Identifies the authoring-only graph and frozen source output. /// - public const string outputName = "shader-graph"; + public const string C_OUTPUT_NAME = "shader-graph"; /// /// Freezes an authored graph and its target-expanded function dependencies without publishing an asset. @@ -41,12 +42,12 @@ public static partial class ShaderGraphArtifact /// /// Reads an immutable function bundle by stable identity and diagnostic last-known path. /// - /// - /// Cancellation before node expansion, target expansion and dependency reads. - /// /// /// Reads an authored Shader graph used as a reusable node, when the graph contains one. /// + /// + /// Cancellation before node expansion, target expansion and dependency reads. + /// /// /// Native immutable authoring artifact bytes usable by import or isolated preview compilation. /// @@ -56,36 +57,33 @@ public static byte[] Capture( SerializationRegistry serialization, SerializationContext context, Func readSource, - CancellationToken cancellationToken = default, - Func? readGraph = null + Func? readGraph = null, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(readSource); using IDisposable operation = types.AcquireOperation("Capture shader authoring candidate"); using var targets = new ShaderTargetRegistry(types); GraphDocument expanded = ShaderGraphNodes.Expand(graph, readGraph ?? MissingGraphResolver, serialization, context); GraphDocument program = targets.Expand(expanded, serialization, context, cancellationToken); - var sources = new Dictionary(); + var sources = new Dictionary(); foreach (GraphNodeRecord node in program.nodes) { cancellationToken.ThrowIfCancellationRequested(); - if (node.definitionId != "inno.shader.source") + if (node.definitionID != "inno.shader.source") + { continue; + } Guid id = ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, serialization, context); if (id == Guid.Empty) + { continue; - string path = ShaderGraphDocument.Read(node, "sourcePath", "", serialization, context); + } + string path = ShaderGraphDocument.Read(node, "sourcePath", string.Empty, serialization, context); sources.Add(node.id, readSource(id, path)); } return Encode(graph, sources, serialization, program); } - private static GraphDocument MissingGraphResolver( - Guid id, - string path - ) - => throw new InvalidOperationException( - $"Shader graph node '{id}' at '{path}' requires a graph resolver during artifact capture."); - /// /// Reads the target-expanded runtime interface from the same frozen candidate as its computations. /// @@ -105,8 +103,11 @@ public static ShaderDefinition ReadDefinition( ReadOnlySpan bytes, SerializationRegistry serialization, SerializationContext context - ) - => ShaderGraphDocument.ReadDefinition(GraphDocumentCodec.Decode(serialization.Deserialize(bytes).program, serialization), serialization, context); + ) => ShaderGraphDocument.ReadDefinition( + GraphDocumentCodec.Decode(serialization.Deserialize(bytes).program, serialization), + serialization, + context + ); /// /// Reads a retained immutable authoring snapshot through its explicit artifact owner. @@ -122,11 +123,11 @@ SerializationContext context /// public static byte[] Read( ShaderAsset shader, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { ArgumentNullException.ThrowIfNull(shader); ArgumentNullException.ThrowIfNull(artifacts); - using Inno.Assets.ArtifactLease lease = artifacts.AcquireArtifact(shader.identity.persistentId, outputName); + using ArtifactLease lease = artifacts.AcquireArtifact(shader.identity.persistentID, C_OUTPUT_NAME); return lease.ReadAllBytes(); } @@ -152,10 +153,14 @@ SerializationRegistry serialization { node.position = default; foreach (string key in node.values.Keys.Where(static key => key.StartsWith("inno.editor.", StringComparison.Ordinal)).ToArray()) + { node.RemoveValue(key); + } } foreach (string key in graph.metadata.Keys.Where(static key => key.StartsWith("inno.editor.", StringComparison.Ordinal)).ToArray()) + { graph.RemoveMetadata(key); + } data.document = []; data.program = GraphDocumentCodec.Encode(graph, serialization); return Convert.ToHexString(SHA256.HashData(serialization.Serialize(data))); @@ -181,17 +186,17 @@ SerializationRegistry serialization /// public static byte[] Encode( GraphDocument graph, - IReadOnlyDictionary sources, + IReadOnlyDictionary sources, SerializationRegistry serialization, GraphDocument? program = null - ) - => serialization.Serialize(new ArtifactData - { - document = GraphDocumentCodec.Encode(graph, serialization), - program = GraphDocumentCodec.Encode(program ?? graph, serialization), - sources = sources.OrderBy(static pair => pair.Key.value, StringComparer.Ordinal) - .Select(static pair => new SourceData { node = pair.Key.value, bundle = pair.Value.ToArray() }).ToArray() - }); + ) => serialization.Serialize(new ArtifactData + { + document = GraphDocumentCodec.Encode(graph, serialization), + program = GraphDocumentCodec.Encode(program ?? graph, serialization), + sources = sources.OrderBy(static pair => pair.Key.value, StringComparer.Ordinal) + .Select(static pair => new SourceData { node = pair.Key.value, bundle = pair.Value.ToArray() }) + .ToArray() + }); /// /// Restores the imported graph for authoring or source export. @@ -208,8 +213,7 @@ public static byte[] Encode( public static GraphDocument ReadDocument( ReadOnlySpan bytes, SerializationRegistry serialization - ) - => GraphDocumentCodec.Decode(serialization.Deserialize(bytes).document, serialization); + ) => GraphDocumentCodec.Decode(serialization.Deserialize(bytes).document, serialization); /// /// Analyzes frozen functions and lowers the graph in the owner's active generation. @@ -217,7 +221,7 @@ SerializationRegistry serialization /// /// Committed authoring artifact bytes. /// - /// + /// /// Selected adapter implementation identity. /// /// @@ -240,7 +244,7 @@ SerializationRegistry serialization /// public static ShaderGraphProgramResult Lower( ReadOnlySpan bytes, - string implementationId, + string implementationID, ShaderNodeCompilerRegistry nodes, ShaderSourceFrontendRegistry frontends, SerializationRegistry serialization, @@ -249,45 +253,63 @@ public static ShaderGraphProgramResult Lower( ) { ArtifactData data = serialization.Deserialize(bytes); GraphDocument graph = GraphDocumentCodec.Decode(data.program, serialization); - var sources = data.sources.ToDictionary(static source => new GraphNodeId(source.node), source => - { - GraphNodeRecord node = graph.FindNode(new(source.node)) - ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); - string function = ShaderGraphDocument.Read(node, "function", "", serialization, context); - if (string.IsNullOrWhiteSpace(function)) - throw new InvalidOperationException($"Source node '{source.node}' has no exported function selection."); - return frontends.AnalyzeModule(ShaderSourceBundle.Decode(source.bundle, function, serialization, defines)); - }); - return new ShaderGraphProgramCompiler(nodes).Lower(graph, implementationId, sources, serialization, context); + Dictionary sources = data.sources.ToDictionary( + static source => new GraphNodeID(source.node), + source => + { + GraphNodeRecord node = graph.FindNode(new GraphNodeID(source.node)) + ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); + string function = ShaderGraphDocument.Read(node, "function", string.Empty, serialization, context); + if (string.IsNullOrWhiteSpace(function)) + { + throw new InvalidOperationException($"Source node '{source.node}' has no exported function selection."); + } + return frontends.AnalyzeModule(ShaderSourceBundle.Decode(source.bundle, function, serialization, defines)); + } + ); + return new ShaderGraphProgramCompiler(nodes).Lower(graph, implementationID, sources, serialization, context); } - [Inno.Extensibility.Types.StableTypeId("16182a41-f19b-5a28-a66f-5310360f8a32")] + private static GraphDocument MissingGraphResolver( + Guid id, + string path + ) => throw new InvalidOperationException( + $"Shader graph node '{id}' at '{path}' requires a graph resolver during artifact capture." + ); + + [StableTypeID("16182a41-f19b-5a28-a66f-5310360f8a32")] private sealed class ArtifactData : ISerializable { /// /// Gets or sets native graph bytes. /// - [SerializableProperty] public byte[] document { get; set; } = []; + [SerializableProperty] + public byte[] document { get; set; } = []; + /// /// Gets or sets explicit target-expanded stage graph bytes. /// - [SerializableProperty] public byte[] program { get; set; } = []; + [SerializableProperty] + public byte[] program { get; set; } = []; + /// /// Gets or sets frozen functions by node identity. /// - [SerializableProperty] public SourceData[] sources { get; set; } = []; + [SerializableProperty] + public SourceData[] sources { get; set; } = []; } - [Inno.Extensibility.Types.StableTypeId("91d54277-1257-5bf0-904d-165e8092fe4a")] + + [StableTypeID("91d54277-1257-5bf0-904d-165e8092fe4a")] private struct SourceData { /// /// Gets or sets the stable source node identity. /// public string node { get; set; } + /// /// Gets or sets native frozen function bytes. /// public byte[] bundle { get; set; } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs index 1113bba20..24cce1508 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs @@ -1,70 +1,13 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; -using System.Linq; +using Inno.Extensibility.Types; namespace Inno.Rendering.Assets.Authoring; -/// -/// Describes the artifact selected after evaluating a candidate compilation. -/// -[Inno.Extensibility.Types.StableTypeId("2cbb2378-91ef-5c66-866e-e651e80a79a7")] -public sealed class ShaderArtifactSelection -{ - /// - /// Creates an artifact selection result. - /// - /// - /// Selected candidate or last-good artifact. - /// - /// - /// Whether the candidate replaced active state. - /// - /// - /// Whether a previous artifact was preserved. - /// - /// - /// Candidate diagnostics. - /// - public ShaderArtifactSelection( - CompiledShaderArtifact? artifact, - bool candidateSucceeded, - bool usingLastGood, - IReadOnlyList diagnostics - ) { - ArgumentNullException.ThrowIfNull(diagnostics); - this.artifact = artifact; - this.candidateSucceeded = candidateSucceeded; - this.usingLastGood = usingLastGood; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the selected candidate or last-good artifact. - /// - public CompiledShaderArtifact? artifact { get; } - - /// - /// Gets whether the candidate replaced active state. - /// - public bool candidateSucceeded { get; } - - /// - /// Gets whether a previous artifact was preserved. - /// - public bool usingLastGood { get; } - - /// - /// Gets candidate diagnostics. - /// - public IReadOnlyList diagnostics { get; } -} - /// /// Atomically preserves last-good CPU shader artifacts by asset, target and variant. /// -[Inno.Extensibility.Types.StableTypeId("b238055f-335a-528f-bdee-cf0044f8e75e")] +[StableTypeID("b238055f-335a-528f-bdee-cf0044f8e75e")] public sealed class ShaderLastGoodStore { private readonly object m_gate = new(); @@ -73,7 +16,7 @@ public sealed class ShaderLastGoodStore /// /// Commits a complete candidate or returns the current last-good artifact after failure. /// - /// + /// /// Persistent shader asset identity. /// /// @@ -89,19 +32,19 @@ public sealed class ShaderLastGoodStore /// The artifact safe to use for rendering. /// public ShaderArtifactSelection Select( - Guid shaderId, + Guid shaderID, string targetKey, RenderShaderVariant variant, ShaderCompilationResult candidate ) { - if (shaderId == Guid.Empty) + if (shaderID == Guid.Empty) { - throw new ArgumentException("A persistent shader identity is required.", nameof(shaderId)); + throw new ArgumentException("A persistent shader identity is required.", nameof(shaderID)); } ArgumentException.ThrowIfNullOrWhiteSpace(targetKey); ArgumentNullException.ThrowIfNull(candidate); - var key = new ArtifactKey(shaderId, targetKey, variant.value); + var key = new ArtifactKey(shaderID, targetKey, variant.value); lock (m_gate) { if (candidate.succeeded) @@ -111,7 +54,8 @@ ShaderCompilationResult candidate candidate.artifact, candidateSucceeded: true, usingLastGood: false, - candidate.diagnostics); + candidate.diagnostics + ); } m_artifacts.TryGetValue(key, out CompiledShaderArtifact? lastGood); @@ -119,22 +63,23 @@ ShaderCompilationResult candidate lastGood, candidateSucceeded: false, usingLastGood: lastGood is not null, - candidate.diagnostics); + candidate.diagnostics + ); } } /// /// Removes all CPU artifacts associated with one persistent shader. /// - /// + /// /// Persistent shader asset identity. /// /// /// The number of removed variants. /// - public int Remove(Guid shaderId) + public int Remove(Guid shaderID) { - if (shaderId == Guid.Empty) + if (shaderID == Guid.Empty) { return 0; } @@ -144,7 +89,7 @@ public int Remove(Guid shaderId) int removed = 0; foreach (ArtifactKey key in new List(m_artifacts.Keys)) { - if (key.shaderId == shaderId && m_artifacts.Remove(key)) + if (key.shaderID == shaderID && m_artifacts.Remove(key)) { removed++; } @@ -155,9 +100,8 @@ public int Remove(Guid shaderId) } private readonly record struct ArtifactKey( - Guid shaderId, + Guid shaderID, string targetKey, string variantKey ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs index 93009db73..7e8269d4d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs @@ -1,22 +1,24 @@ -using Inno.Core.Serialization; -using Inno.Rendering; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.Linq; +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; /// /// Persists only frozen function compilation inputs, never a parser, live asset, resolver or generated main function. /// -[Inno.Extensibility.Types.StableTypeId("3387d371-94f4-5f59-a571-aa552e7eef0a")] +[StableTypeID("3387d371-94f4-5f59-a571-aa552e7eef0a")] public static partial class ShaderSourceBundle { /// /// Identifies the authoring-only frozen function module output. /// - public const string outputName = "shader-function"; + public const string C_OUTPUT_NAME = "shader-function"; /// /// Reads an immutable function snapshot through its explicit artifact owner. @@ -32,11 +34,11 @@ public static partial class ShaderSourceBundle /// public static byte[] Read( ShaderFunctionAsset function, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { ArgumentNullException.ThrowIfNull(function); ArgumentNullException.ThrowIfNull(artifacts); - using Inno.Assets.ArtifactLease lease = artifacts.AcquireArtifact(function.identity.persistentId, outputName); + using ArtifactLease lease = artifacts.AcquireArtifact(function.identity.persistentID, C_OUTPUT_NAME); return lease.ReadAllBytes(); } @@ -59,7 +61,9 @@ SerializationRegistry serialization ArgumentNullException.ThrowIfNull(functions); ArgumentNullException.ThrowIfNull(serialization); if (functions.Count == 0 || functions.Any(static pair => string.IsNullOrWhiteSpace(pair.Key) || pair.Value is null)) + { throw new ArgumentException("A shader source library requires named function analyses.", nameof(functions)); + } return serialization.Serialize(new BundleData { functions = functions.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => new FunctionData @@ -67,13 +71,17 @@ SerializationRegistry serialization name = pair.Key, implementations = pair.Value.implementations.Select(static value => new ImplementationData { - id = value.implementationId, language = value.languageId, root = value.sourcePath, entry = value.entryPoint, + id = value.implementationID, + language = value.languageID, + root = value.sourcePath, + entry = value.entryPoint, paths = value.sources.Select(static file => file.assetPath).ToArray(), texts = value.sources.Select(static file => file.text).ToArray(), includeOwners = value.includes.Select(static edge => edge.includingFile).ToArray(), includeNames = value.includes.Select(static edge => edge.include).ToArray(), includePaths = value.includes.Select(static edge => edge.resolvedPath).ToArray(), - defineNames = value.defines.Keys.ToArray(), defineValues = value.defines.Values.ToArray() + defineNames = value.defines.Keys.ToArray(), + defineValues = value.defines.Values.ToArray() }).ToArray() }).ToArray() }); @@ -108,37 +116,51 @@ public static IReadOnlyList Decode( BundleData data = serialization.Deserialize(bytes); FunctionData selected = (data.functions ?? []).SingleOrDefault(value => value.name == function); if (selected.implementations is null) - throw new InvalidOperationException($"Shader source library does not export function '{function}'."); - return Array.AsReadOnly(selected.implementations.Select(value => { - if (value.paths is null || value.texts is null || value.includeOwners is null || value.includeNames is null - || value.includePaths is null || value.defineNames is null || value.defineValues is null) - throw new InvalidOperationException("The frozen shader source bundle is missing required collections."); - if (value.paths.Length != value.texts.Length || value.includeOwners.Length != value.includeNames.Length - || value.includeOwners.Length != value.includePaths.Length || value.defineNames.Length != value.defineValues.Length) - throw new InvalidOperationException("The frozen shader source bundle has inconsistent collection lengths."); - var files = value.paths.Select(( - path, - index - ) => new ShaderSourceFile(path, value.texts[index])).ToDictionary(static file => file.assetPath, StringComparer.Ordinal); - var edges = value.includeOwners.Select(( - owner, - index - ) => new ShaderSourceInclude(owner, value.includeNames[index], value.includePaths[index])) - .ToDictionary(static edge => (edge.includingFile, edge.include)); - var macros = value.defineNames.Select(( - name, - index - ) => new KeyValuePair(name, value.defineValues[index])).ToDictionary(StringComparer.Ordinal); - foreach ((string name, string text) in defines ?? new Dictionary()) + throw new InvalidOperationException($"Shader source library does not export function '{function}'."); + } + return Array.AsReadOnly( + selected.implementations.Select(value => { - if (macros.TryGetValue(name, out string? previous) && previous != text) - throw new InvalidOperationException($"The target changes recorded source definition '{name}'."); - macros[name] = text; - } - return new ShaderSourceImplementationRequest(value.id, value.language, - new(files[value.root], value.entry, new FrozenResolver(files, edges), macros)); - }).ToArray()); + if (value.paths is null || value.texts is null || value.includeOwners is null || value.includeNames is null + || value.includePaths is null || value.defineNames is null || value.defineValues is null + ) { + throw new InvalidOperationException("The frozen shader source bundle is missing required collections."); + } + if (value.paths.Length != value.texts.Length || value.includeOwners.Length != value.includeNames.Length + || value.includeOwners.Length != value.includePaths.Length || value.defineNames.Length != value.defineValues.Length + ) { + throw new InvalidOperationException("The frozen shader source bundle has inconsistent collection lengths."); + } + Dictionary files = value.paths.Select(( + path, + index + ) => new ShaderSourceFile(path, value.texts[index])).ToDictionary(static file => file.assetPath, StringComparer.Ordinal); + Dictionary<(string includingFile, string include), ShaderSourceInclude> edges = value.includeOwners + .Select(( + owner, + index + ) => new ShaderSourceInclude(owner, value.includeNames[index], value.includePaths[index])) + .ToDictionary(static edge => (edge.includingFile, edge.include)); + Dictionary macros = value.defineNames.Select(( + name, + index + ) => new KeyValuePair(name, value.defineValues[index])).ToDictionary(StringComparer.Ordinal); + foreach ((string name, string text) in defines ?? new Dictionary()) + { + if (macros.TryGetValue(name, out string? previous) && previous != text) + { + throw new InvalidOperationException($"The target changes recorded source definition '{name}'."); + } + macros[name] = text; + } + return new ShaderSourceImplementationRequest( + value.id, + value.language, + new ShaderSourceRequest(files[value.root], value.entry, new FrozenResolver(files, edges), macros) + ); + }).ToArray() + ); } private sealed class FrozenResolver( @@ -161,78 +183,92 @@ private sealed class FrozenResolver( public ShaderSourceFile ReadInclude( string includingFile, string include - ) - => edges.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && files.TryGetValue(edge.resolvedPath, out ShaderSourceFile? file) - ? file : throw new InvalidOperationException($"Source dependency '{include}' from '{includingFile}' was not captured by import."); + ) => edges.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) + && files.TryGetValue(edge.resolvedPath, out ShaderSourceFile? file) + ? file + : throw new InvalidOperationException($"Source dependency '{include}' from '{includingFile}' was not captured by import."); } - [Inno.Extensibility.Types.StableTypeId("0e035881-9850-5f9c-8037-283168890d0d")] + [StableTypeID("0e035881-9850-5f9c-8037-283168890d0d")] private sealed class BundleData : ISerializable { /// /// Gets the ordered shader functions in this source bundle. /// - [SerializableProperty] public FunctionData[] functions { get; set; } = []; + [SerializableProperty] + public FunctionData[] functions { get; set; } = []; } - [Inno.Extensibility.Types.StableTypeId("3c78ad4e-deb3-547b-984e-18de97667641")] + + [StableTypeID("3c78ad4e-deb3-547b-984e-18de97667641")] private struct FunctionData { /// /// Gets the human-readable name used for presentation and diagnostics. /// public string name { get; set; } + /// /// Gets the shader implementations associated with these functions. /// public ImplementationData[] implementations { get; set; } } - [Inno.Extensibility.Types.StableTypeId("4f51d0e8-599b-5fd7-b4cc-4694fe18e922")] + + [StableTypeID("4f51d0e8-599b-5fd7-b4cc-4694fe18e922")] private struct ImplementationData { /// /// Gets the stable identity used to reference this value across subsystem boundaries. /// public string id { get; set; } + /// /// Gets the language text used by the current instance. /// public string language { get; set; } + /// /// Gets the root text used by the current instance. /// public string root { get; set; } + /// /// Gets the entry text used by the current instance. /// public string entry { get; set; } + /// /// Gets the source paths in this shader bundle. /// public string[] paths { get; set; } + /// /// Gets the source text corresponding to each path. /// public string[] texts { get; set; } + /// /// Gets the source that owns each included file. /// public string[] includeOwners { get; set; } + /// /// Gets the names used to reference included files. /// public string[] includeNames { get; set; } + /// /// Gets the resolved paths of included files. /// public string[] includePaths { get; set; } + /// /// Gets the names of compilation defines. /// public string[] defineNames { get; set; } + /// /// Gets the values corresponding to compilation defines. /// public string[] defineValues { get; set; } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs new file mode 100644 index 000000000..f3632c902 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs @@ -0,0 +1,55 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Stores one immutable target stage binary. +/// +[StableTypeID("7de46626-7dd7-5112-b098-ef3eb53a0cda")] +public sealed class ShaderStageArtifact +{ + private readonly byte[] m_bytes; + + /// + /// Creates a stage artifact. + /// + /// + /// Single compiled shader stage. + /// + /// + /// Target binary bytes. + /// + /// + /// Original source mapping. + /// + public ShaderStageArtifact( + ShaderStage stage, + ReadOnlySpan bytes, + ShaderSourceLocation sourceLocation + ) { + if (bytes.IsEmpty) + { + throw new ArgumentException("A compiled shader stage cannot be empty.", nameof(bytes)); + } + + this.stage = stage; + m_bytes = bytes.ToArray(); + this.sourceLocation = sourceLocation; + } + + /// + /// Gets the compiled shader stage. + /// + public ShaderStage stage { get; } + + /// + /// Gets immutable target binary bytes. + /// + public ReadOnlyMemory bytes => m_bytes; + + /// + /// Gets the original source mapping. + /// + public ShaderSourceLocation sourceLocation { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs new file mode 100644 index 000000000..c424801ed --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs @@ -0,0 +1,22 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Maps one logical binding to the adapter-generated native name, without exposing a GPU handle. +/// +/// +/// Stable logical binding identity from the typed stage. +/// +/// +/// Generated name used for reflection and runtime uniform binding. +/// +/// +/// Assigned texture slot; uniform locations are resolved by the runtime. +/// +[StableTypeID("00dff34d-f800-51e6-8a37-0141761958c8")] +public sealed record ShaderStageBinding( + string id, + string nativeName, + int location +); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs deleted file mode 100644 index bc4e2d4b1..000000000 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs +++ /dev/null @@ -1,151 +0,0 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Inno.Rendering.Assets.Authoring; - -/// -/// Supplies typed stage semantics and frozen source modules to a target compiler. -/// -/// -/// Typed stage with target-assigned interface/resource locations. -/// -/// -/// Exact toolchain profile and capability snapshot. -/// -[Inno.Extensibility.Types.StableTypeId("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] -public sealed record ShaderStageToolRequest( - ShaderIrStage stage, - ShaderCompileTarget target -); - -/// -/// Maps one logical binding to the adapter-generated native name, without exposing a GPU handle. -/// -/// -/// Stable logical binding identity from the typed stage. -/// -/// -/// Generated name used for reflection and runtime uniform binding. -/// -/// -/// Assigned texture slot; uniform locations are resolved by the runtime. -/// -[Inno.Extensibility.Types.StableTypeId("00dff34d-f800-51e6-8a37-0141761958c8")] -public sealed record ShaderStageBinding( - string id, - string nativeName, - int location -); - -/// -/// Returns a frozen typed-stage compilation candidate; failure never carries a usable artifact. -/// -[Inno.Extensibility.Types.StableTypeId("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] -public sealed class ShaderStageToolResult -{ - private readonly byte[] m_bytes; - - /// - /// Creates a candidate result from adapter-owned generation, compilation and diagnostics. - /// - /// - /// Compiled binary, or empty after failure. - /// - /// - /// Logical-to-native resource layout used by this exact binary. - /// - /// - /// Structured adapter diagnostics with original source positions. - /// - public ShaderStageToolResult( - ReadOnlySpan bytes, - IEnumerable bindings, - IEnumerable diagnostics - ) { - ArgumentNullException.ThrowIfNull(bindings); - ArgumentNullException.ThrowIfNull(diagnostics); - this.bindings = Array.AsReadOnly(bindings.ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - if (!bytes.IsEmpty && this.diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - throw new ArgumentException("A failed candidate cannot publish compiled bytes.", nameof(bytes)); - m_bytes = bytes.ToArray(); - } - - /// - /// Gets immutable target binary data, empty on failure. - /// - public ReadOnlyMemory bytes => m_bytes; - /// - /// Gets the exact generated logical-to-native resource layout. - /// - public IReadOnlyList bindings { get; } - /// - /// Gets generation and native compiler diagnostics. - /// - public IReadOnlyList diagnostics { get; } - /// - /// Gets whether a nonempty binary was compiled without error diagnostics. - /// - public bool succeeded => !bytes.IsEmpty && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} - -/// -/// Carries validated inputs and outputs for one shader compilation stage. -/// -public sealed partial class ShaderCompiler -{ - private readonly object m_stageCacheLock = new(); - private readonly Dictionary<(string stage, string target, GraphicsCapabilities capabilities), ShaderStageToolResult> m_stageCache = []; - private long m_stageCacheBytes; - /// - /// Compiles a typed stage through the configured adapter without an intermediate complete-source authoring asset. - /// - /// - /// Typed stage and frozen function modules. - /// - /// - /// Configured target capability/profile snapshot. - /// - /// - /// Cancellation before publishing the candidate. - /// - /// - /// Compiled stage bytes, exact generated binding names and structured diagnostics. - /// - public async ValueTask CompileAsync( - ShaderIrStage stage, - ShaderCompileTarget target, - CancellationToken cancellationToken = default - ) { - ArgumentNullException.ThrowIfNull(stage); - ArgumentNullException.ThrowIfNull(target); - cancellationToken.ThrowIfCancellationRequested(); - var key = (stage.contentHash, target.key, target.capabilities); - lock (m_stageCacheLock) - if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) - return previous; - ShaderStageToolResult result = await m_toolchain.CompileAsync(new ShaderStageToolRequest(stage, target), cancellationToken).ConfigureAwait(false); - cancellationToken.ThrowIfCancellationRequested(); - // The bounded cache contains immutable backend results only, never IR, providers or source assets. - // Failed and cancelled requests are not cached, and layout-only graph edits reuse the semantic key. - if (result.succeeded && result.bytes.Length <= 32 * 1024 * 1024) - lock (m_stageCacheLock) - { - if (m_stageCache.Count >= 256 || m_stageCacheBytes + result.bytes.Length > 32 * 1024 * 1024) - { - m_stageCache.Clear(); - m_stageCacheBytes = 0; - } - if (m_stageCache.TryAdd(key, result)) - m_stageCacheBytes += result.bytes.Length; - } - return result; - } -} - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs new file mode 100644 index 000000000..61e31bf37 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs @@ -0,0 +1,19 @@ +using Inno.Extensibility.Types; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Supplies typed stage semantics and frozen source modules to a target compiler. +/// +/// +/// Typed stage with target-assigned interface/resource locations. +/// +/// +/// Exact toolchain profile and capability snapshot. +/// +[StableTypeID("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] +public sealed record ShaderStageToolRequest( + ShaderIrStage stage, + ShaderCompileTarget target +); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs new file mode 100644 index 000000000..fbd884cc6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Returns a frozen typed-stage compilation candidate; failure never carries a usable artifact. +/// +[StableTypeID("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] +public sealed class ShaderStageToolResult +{ + private readonly byte[] m_bytes; + + /// + /// Creates a candidate result from adapter-owned generation, compilation and diagnostics. + /// + /// + /// Compiled binary, or empty after failure. + /// + /// + /// Logical-to-native resource layout used by this exact binary. + /// + /// + /// Structured adapter diagnostics with original source positions. + /// + public ShaderStageToolResult( + ReadOnlySpan bytes, + IEnumerable bindings, + IEnumerable diagnostics + ) { + ArgumentNullException.ThrowIfNull(bindings); + ArgumentNullException.ThrowIfNull(diagnostics); + this.bindings = Array.AsReadOnly(bindings.ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + if (!bytes.IsEmpty && this.diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { + throw new ArgumentException("A failed candidate cannot publish compiled bytes.", nameof(bytes)); + } + m_bytes = bytes.ToArray(); + } + + /// + /// Gets immutable target binary data, empty on failure. + /// + public ReadOnlyMemory bytes => m_bytes; + + /// + /// Gets the exact generated logical-to-native resource layout. + /// + public IReadOnlyList bindings { get; } + + /// + /// Gets generation and native compiler diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a nonempty binary was compiled without error diagnostics. + /// + public bool succeeded => !bytes.IsEmpty && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs new file mode 100644 index 000000000..05c07cf1a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs @@ -0,0 +1,38 @@ +using Inno.Core.Graphs; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Contains detached graph source state, not a compiled or live runtime asset. +/// +[StableTypeID("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] +public sealed class ShaderGraphSourceSnapshot +{ + private readonly GraphDocument m_document; + + internal ShaderGraphSourceSnapshot( + GraphDocument document, + string hash, + bool readOnly + ) { + m_document = document; + this.contentHash = hash; + this.isReadOnly = readOnly; + } + + /// + /// Gets a detached copy of authored graph records. + /// + public GraphDocument document => m_document.Clone(); + + /// + /// Gets the source fingerprint used to reject external-edit conflicts. + /// + public string contentHash { get; } + + /// + /// Gets whether the source belongs to an immutable installation mount. + /// + public bool isReadOnly { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs index 31081563d..2e41aee4c 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs @@ -1,17 +1,17 @@ +using System; +using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Inno.Rendering; -using System; -using System.IO; +using Inno.Extensibility.Types; namespace Inno.Rendering.Assets.Authoring; /// /// Reads and atomically saves the sole shader graph source format without requiring successful compilation. /// -[Inno.Extensibility.Types.StableTypeId("dcfd81b7-a22d-5b35-a79a-a608e69b7ad8")] +[StableTypeID("dcfd81b7-a22d-5b35-a79a-a608e69b7ad8")] public sealed class ShaderGraphSourceStore { private readonly AssetSourceStore m_sources; @@ -31,8 +31,9 @@ public ShaderGraphSourceStore( SerializationRegistry serialization ) { ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(serialization); m_sources = assets.CreateSourceStore(); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); + m_serialization = serialization; } /// @@ -85,38 +86,8 @@ public string Save( private static void Validate(AssetPath path) { if (!path.isValid || !path.localPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("A shader graph source must use the .ishader extension.", nameof(path)); + } } - } - -/// -/// Contains detached graph source state, not a compiled or live runtime asset. -/// -[Inno.Extensibility.Types.StableTypeId("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] -public sealed class ShaderGraphSourceSnapshot -{ - private readonly GraphDocument m_document; - internal ShaderGraphSourceSnapshot( - GraphDocument document, - string hash, - bool readOnly - ) { - m_document = document; - contentHash = hash; - isReadOnly = readOnly; - } - /// - /// Gets a detached copy of authored graph records. - /// - public GraphDocument document => m_document.Clone(); - /// - /// Gets the source fingerprint used to reject external-edit conflicts. - /// - public string contentHash { get; } - /// - /// Gets whether the source belongs to an immutable installation mount. - /// - public bool isReadOnly { get; } -} - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs index 22f519678..1d4a2d113 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs @@ -1,18 +1,19 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.geometry")] -[Inno.Extensibility.Types.StableTypeId("a7278025-7d95-5fb3-a309-25458cef8765")] +[StableTypeID("a7278025-7d95-5fb3-a309-25458cef8765")] internal sealed class GeometryAssetImporter : AssetImporter { /// @@ -54,13 +55,15 @@ byte[] ReadDependency(string relativePath) context.sourceBytes.Span, isBinary: false, ReadDependency, - path => output.DependsOnSource(AssetPath.Parse(path))), + path => output.DependsOnSource(AssetPath.Parse(path)) + ), ".glb" => MeshSourceParser.ParseGltf( context.assetPath.ToString(), context.sourceBytes.Span, isBinary: true, ReadDependency, - path => output.DependsOnSource(AssetPath.Parse(path))), + path => output.DependsOnSource(AssetPath.Parse(path)) + ), _ => throw new RenderingAssetFormatException(context.assetPath.ToString(), "Unsupported geometry container.") }; (Vector3 boundsCenter, Vector3 boundsExtents) = CalculateBounds(data); @@ -69,11 +72,12 @@ byte[] ReadDependency(string relativePath) data.indices.Count, data.sections.Count, boundsCenter, - boundsExtents); + boundsExtents + ); output.SetAsset(asset); byte[] artifact = GeometryArtifact.Encode(data); - await output.WriteArtifactAsync("runtime", artifact, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("geometry", artifact, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", artifact, cancellationToken: cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("geometry", artifact, cancellationToken: cancellationToken).ConfigureAwait(false); } private static (Vector3 center, Vector3 extents) CalculateBounds(GeometryData data) @@ -91,15 +95,15 @@ private static (Vector3 center, Vector3 extents) CalculateBounds(GeometryData da minimum = new Vector3( MathF.Min(minimum.x, position.x), MathF.Min(minimum.y, position.y), - MathF.Min(minimum.z, position.z)); + MathF.Min(minimum.z, position.z) + ); maximum = new Vector3( MathF.Max(maximum.x, position.x), MathF.Max(maximum.y, position.y), - MathF.Max(maximum.z, position.z)); + MathF.Max(maximum.z, position.z) + ); } return ((minimum + maximum) * 0.5f, (maximum - minimum) * 0.5f); } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs index 1ea4b8f68..54802724b 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs @@ -1,10 +1,11 @@ -using Inno.Rendering; using System; using System.Text.Json; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("d5d5c69c-6d36-541f-bdd6-305af58d8e18")] +[StableTypeID("d5d5c69c-6d36-541f-bdd6-305af58d8e18")] internal static class GltfJson { internal static JsonElement RequireObject( @@ -20,7 +21,9 @@ internal static string RequireString( string path ) { if (element.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(element.GetString())) + { throw new RenderingAssetFormatException(path, "A non-empty string is required."); + } return element.GetString()!; } @@ -30,26 +33,25 @@ internal static void RequireKind( string path ) { if (element.ValueKind != kind) + { throw new RenderingAssetFormatException(path, $"Expected {kind}, found {element.ValueKind}."); + } } internal static bool RequireBoolean( JsonElement element, string path - ) - => element.ValueKind switch - { - JsonValueKind.True => true, - JsonValueKind.False => false, - _ => throw new RenderingAssetFormatException(path, "A boolean is required.") - }; + ) => element.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => throw new RenderingAssetFormatException(path, "A boolean is required.") + }; internal static int RequireInt32( JsonElement element, string path - ) - => element.TryGetInt32(out int result) - ? result - : throw new RenderingAssetFormatException(path, "A 32-bit integer is required."); + ) => element.TryGetInt32(out int result) + ? result + : throw new RenderingAssetFormatException(path, "A 32-bit integer is required."); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs index 1e1c28438..24fe897ac 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs @@ -1,17 +1,18 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.material")] -[Inno.Extensibility.Types.StableTypeId("64229f7a-85a7-5d65-9a50-3c8ea5bc3585")] +[StableTypeID("64229f7a-85a7-5d65-9a50-3c8ea5bc3585")] internal sealed class MaterialAssetImporter : AssetImporter { /// @@ -42,12 +43,15 @@ CancellationToken cancellationToken MaterialAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } Validate(asset); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } @@ -73,32 +77,36 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); Validate(asset); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } private static void Validate(MaterialAsset asset) { ShaderDefinition definition = asset.shader?.definition - ?? throw new InvalidOperationException("A material requires a shader with a committed definition."); - Dictionary properties = definition.properties + ?? throw new InvalidOperationException("A material requires a shader with a committed definition."); + Dictionary properties = definition.properties .ToDictionary(static property => property.id); foreach (MaterialPropertyEntry property in asset.properties) { if (!properties.TryGetValue(property.id, out ShaderPropertyDefinition shaderProperty)) + { throw new InvalidOperationException($"Material property '{property.id}' is not declared by its shader."); + } if (shaderProperty.bindingKind is ShaderPropertyBindingKind.StorageTexture - or ShaderPropertyBindingKind.StorageBuffer) - { + or ShaderPropertyBindingKind.StorageBuffer + ) { throw new InvalidOperationException( - $"Material property '{property.id}' is Pipeline-owned storage state and cannot be persisted by a material."); + $"Material property '{property.id}' is Pipeline-owned storage state and cannot be persisted by a material." + ); } if (!IsCompatible(shaderProperty.type, property.value.kind)) { throw new InvalidOperationException( - $"Material property '{property.id}' value '{property.value.kind}' is incompatible with " + - $"shader type '{shaderProperty.type}'."); + $"Material property '{property.id}' value '{property.value.kind}' is incompatible with " + + $"shader type '{shaderProperty.type}'." + ); } } HashSet options = definition.keywords @@ -106,26 +114,26 @@ private static void Validate(MaterialAsset asset) .ToHashSet(StringComparer.Ordinal); string? unknownKeyword = asset.keywords.FirstOrDefault(keyword => !options.Contains(keyword)); if (unknownKeyword is not null) + { throw new InvalidOperationException($"Material keyword '{unknownKeyword}' is not declared by its shader."); + } } private static bool IsCompatible( ShaderPropertyType propertyType, MaterialValueKind valueKind - ) - => propertyType switch - { - ShaderPropertyType.Float => valueKind == MaterialValueKind.Float, - ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => - valueKind == MaterialValueKind.Vector, - ShaderPropertyType.Color => valueKind == MaterialValueKind.Color, - ShaderPropertyType.Matrix4x4 => valueKind == MaterialValueKind.Matrix, - ShaderPropertyType.Texture2D - or ShaderPropertyType.Texture2DArray - or ShaderPropertyType.Texture3D - or ShaderPropertyType.TextureCube => - valueKind == MaterialValueKind.Texture, - _ => false - }; + ) => propertyType switch + { + ShaderPropertyType.Float => valueKind == MaterialValueKind.Float, + ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => + valueKind == MaterialValueKind.Vector, + ShaderPropertyType.Color => valueKind == MaterialValueKind.Color, + ShaderPropertyType.Matrix4x4 => valueKind == MaterialValueKind.Matrix, + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => + valueKind == MaterialValueKind.Texture, + _ => false + }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs similarity index 79% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs index 95edcbd98..a6882ca92 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs @@ -1,22 +1,19 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Buffers.Binary; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; using System.Text.Json; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("c2a6add7-0201-527c-87a4-137904623ee6")] +[StableTypeID("c2a6add7-0201-527c-87a4-137904623ee6")] internal static partial class MeshSourceParser { - private const uint C_GLB_MAGIC = 0x46546c67; - private const uint C_JSON_CHUNK = 0x4e4f534a; - private const uint C_BIN_CHUNK = 0x004e4942; + private const uint C_GLB_MAGIC = 0x4654_6C67; + private const uint C_JSON_CHUNK = 0x4E4F_534A; + private const uint C_BIN_CHUNK = 0x004E_4942; internal static GeometryData ParseGltf( string sourcePath, @@ -40,12 +37,7 @@ Action dependencySink using JsonDocument document = JsonDocument.Parse(jsonBytes); JsonElement root = GltfJson.RequireObject(document.RootElement, "$gltf"); - byte[][] buffers = ReadBuffers( - sourcePath, - root, - binaryChunk, - dependencyReader, - dependencySink); + byte[][] buffers = ReadBuffers(sourcePath, root, binaryChunk, dependencyReader, dependencySink); BufferView[] bufferViews = ReadBufferViews(root, buffers); Accessor[] accessors = ReadAccessors(root, bufferViews); return ReadMeshes(sourcePath, root, accessors); @@ -109,14 +101,15 @@ Action dependencySink GltfJson.RequireKind(bufferArray, JsonValueKind.Array, "$gltf.buffers"); string directory = GetProjectDirectory(sourcePath); - var buffers = new List(); + List buffers = []; int index = 0; foreach (JsonElement buffer in bufferArray.EnumerateArray()) { GltfJson.RequireObject(buffer, $"$gltf.buffers[{index}]"); int byteLength = GltfJson.RequireInt32( buffer.GetProperty("byteLength"), - $"$gltf.buffers[{index}].byteLength"); + $"$gltf.buffers[{index}].byteLength" + ); byte[] bytes; if (buffer.TryGetProperty("uri", out JsonElement uriElement)) { @@ -128,7 +121,8 @@ Action dependencySink { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}].uri", - "Only base64 data URIs are supported."); + "Only base64 data URIs are supported." + ); } bytes = Convert.FromBase64String(uri[(separator + 1)..]); @@ -137,7 +131,8 @@ Action dependencySink { string dependency = NormalizeProjectPath( CombineProjectPath(directory, Uri.UnescapeDataString(uri)), - $"$gltf.buffers[{index}].uri"); + $"$gltf.buffers[{index}].uri" + ); dependencySink(dependency); bytes = dependencyReader(dependency); } @@ -150,14 +145,16 @@ Action dependencySink { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}]", - "A URI or matching GLB binary chunk is required."); + "A URI or matching GLB binary chunk is required." + ); } if (byteLength < 0 || bytes.Length < byteLength) { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}].byteLength", - "Buffer content is shorter than its declared byte length."); + "Buffer content is shorter than its declared byte length." + ); } buffers.Add(bytes); @@ -177,29 +174,29 @@ IReadOnlyList buffers } GltfJson.RequireKind(viewArray, JsonValueKind.Array, "$gltf.bufferViews"); - var result = new List(); + List result = []; int index = 0; foreach (JsonElement view in viewArray.EnumerateArray()) { - int bufferIndex = GltfJson.RequireInt32( - view.GetProperty("buffer"), - $"$gltf.bufferViews[{index}].buffer"); + int bufferIndex = GltfJson.RequireInt32(view.GetProperty("buffer"), $"$gltf.bufferViews[{index}].buffer"); int offset = view.TryGetProperty("byteOffset", out JsonElement offsetElement) - ? GltfJson.RequireInt32(offsetElement, $"$gltf.bufferViews[{index}].byteOffset") - : 0; + ? GltfJson.RequireInt32(offsetElement, $"$gltf.bufferViews[{index}].byteOffset") + : 0; int length = GltfJson.RequireInt32( view.GetProperty("byteLength"), - $"$gltf.bufferViews[{index}].byteLength"); + $"$gltf.bufferViews[{index}].byteLength" + ); int stride = view.TryGetProperty("byteStride", out JsonElement strideElement) - ? GltfJson.RequireInt32(strideElement, $"$gltf.bufferViews[{index}].byteStride") - : 0; + ? GltfJson.RequireInt32(strideElement, $"$gltf.bufferViews[{index}].byteStride") + : 0; if (bufferIndex < 0 || bufferIndex >= buffers.Count || offset < 0 || length < 0 || offset + length > buffers[bufferIndex].Length - || stride < 0) - { + || stride < 0 + ) { throw new RenderingAssetFormatException( $"$gltf.bufferViews[{index}]", - "Buffer view bounds are invalid."); + "Buffer view bounds are invalid." + ); } result.Add(new BufferView(buffers[bufferIndex], offset, length, stride)); @@ -219,7 +216,7 @@ IReadOnlyList views } GltfJson.RequireKind(accessorArray, JsonValueKind.Array, "$gltf.accessors"); - var result = new List(); + List result = []; int index = 0; foreach (JsonElement accessor in accessorArray.EnumerateArray()) { @@ -227,31 +224,28 @@ IReadOnlyList views { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}].sparse", - "Sparse accessors are not supported by the first mesh importer."); + "Sparse accessors are not supported by the first mesh importer." + ); } int viewIndex = GltfJson.RequireInt32( accessor.GetProperty("bufferView"), - $"$gltf.accessors[{index}].bufferView"); + $"$gltf.accessors[{index}].bufferView" + ); int offset = accessor.TryGetProperty("byteOffset", out JsonElement offsetElement) - ? GltfJson.RequireInt32(offsetElement, $"$gltf.accessors[{index}].byteOffset") - : 0; + ? GltfJson.RequireInt32(offsetElement, $"$gltf.accessors[{index}].byteOffset") + : 0; int componentType = GltfJson.RequireInt32( accessor.GetProperty("componentType"), - $"$gltf.accessors[{index}].componentType"); - int count = GltfJson.RequireInt32( - accessor.GetProperty("count"), - $"$gltf.accessors[{index}].count"); - string type = GltfJson.RequireString( - accessor.GetProperty("type"), - $"$gltf.accessors[{index}].type"); + $"$gltf.accessors[{index}].componentType" + ); + int count = GltfJson.RequireInt32(accessor.GetProperty("count"), $"$gltf.accessors[{index}].count"); + string type = GltfJson.RequireString(accessor.GetProperty("type"), $"$gltf.accessors[{index}].type"); bool normalized = accessor.TryGetProperty("normalized", out JsonElement normalizedElement) - && GltfJson.RequireBoolean(normalizedElement, $"$gltf.accessors[{index}].normalized"); + && GltfJson.RequireBoolean(normalizedElement, $"$gltf.accessors[{index}].normalized"); if (viewIndex < 0 || viewIndex >= views.Count || offset < 0 || count <= 0) { - throw new RenderingAssetFormatException( - $"$gltf.accessors[{index}]", - "Accessor bounds are invalid."); + throw new RenderingAssetFormatException($"$gltf.accessors[{index}]", "Accessor bounds are invalid."); } result.Add(new Accessor(views[viewIndex], offset, componentType, count, type, normalized)); @@ -272,9 +266,9 @@ IReadOnlyList accessors } GltfJson.RequireKind(meshes, JsonValueKind.Array, "$gltf.meshes"); - var vertices = new List(); - var indices = new List(); - var sections = new List(); + List vertices = []; + List indices = []; + List sections = []; foreach (JsonElement mesh in meshes.EnumerateArray()) { JsonElement primitives = mesh.GetProperty("primitives"); @@ -282,19 +276,21 @@ IReadOnlyList accessors foreach (JsonElement primitive in primitives.EnumerateArray()) { int mode = primitive.TryGetProperty("mode", out JsonElement modeElement) - ? GltfJson.RequireInt32(modeElement, "$gltf.meshes[].primitives[].mode") - : 4; + ? GltfJson.RequireInt32(modeElement, "$gltf.meshes[].primitives[].mode") + : 4; if (mode != 4) { throw new RenderingAssetFormatException( "$gltf.meshes[].primitives[].mode", - "Only triangle-list primitives are supported."); + "Only triangle-list primitives are supported." + ); } JsonElement attributes = primitive.GetProperty("attributes"); int positionAccessor = GltfJson.RequireInt32( attributes.GetProperty("POSITION"), - "$gltf.meshes[].primitives[].attributes.POSITION"); + "$gltf.meshes[].primitives[].attributes.POSITION" + ); float[][] positions = ReadFloatAccessor(accessors, positionAccessor, 3, "POSITION"); float[][]? normals = TryReadAttribute(attributes, "NORMAL", accessors, 3); float[][]? textureCoordinates = TryReadAttribute(attributes, "TEXCOORD_0", accessors, 2); @@ -314,28 +310,30 @@ IReadOnlyList accessors { position = new Vector3(position[0], position[1], -position[2]), normal = normal is null - ? default - : new Vector3(normal[0], normal[1], -normal[2]), + ? default + : new Vector3(normal[0], normal[1], -normal[2]), hasNormal = normal is not null, textureCoordinate = uv is null ? default : new Vector2(uv[0], uv[1]), tangent = tangent is null - ? default - : new Vector3(tangent[0], tangent[1], -tangent[2]), + ? default + : new Vector3(tangent[0], tangent[1], -tangent[2]), tangentW = tangent is null ? 1f : -tangent[3], hasTangent = tangent is not null }); } uint[] localIndices = primitive.TryGetProperty("indices", out JsonElement indexElement) - ? ReadIndexAccessor( - accessors, - GltfJson.RequireInt32(indexElement, "$gltf.meshes[].primitives[].indices")) - : Enumerable.Range(0, positions.Length).Select(static value => checked((uint)value)).ToArray(); + ? ReadIndexAccessor( + accessors, + GltfJson.RequireInt32(indexElement, "$gltf.meshes[].primitives[].indices") + ) + : Enumerable.Range(0, positions.Length).Select(static value => checked((uint)value)).ToArray(); if (localIndices.Length % 3 != 0) { throw new RenderingAssetFormatException( "$gltf.meshes[].primitives[].indices", - "Triangle index count must be divisible by three."); + "Triangle index count must be divisible by three." + ); } int firstIndex = indices.Count; @@ -363,7 +361,8 @@ IReadOnlyList accessors value.position, Vector3.NormalizeSafe(value.normal), ToTangent(value.tangent, value.tangentW), - value.textureCoordinate)).ToArray(); + value.textureCoordinate + )).ToArray(); return new GeometryData(normalizedVertices, [.. indices], [.. sections]); } @@ -372,14 +371,9 @@ IReadOnlyList accessors string name, IReadOnlyList accessors, int components - ) - => attributes.TryGetProperty(name, out JsonElement accessor) - ? ReadFloatAccessor( - accessors, - GltfJson.RequireInt32(accessor, $"$gltf.attributes.{name}"), - components, - name) - : null; + ) => attributes.TryGetProperty(name, out JsonElement accessor) + ? ReadFloatAccessor(accessors, GltfJson.RequireInt32(accessor, $"$gltf.attributes.{name}"), components, name) + : null; private static float[][] ReadFloatAccessor( IReadOnlyList accessors, @@ -392,7 +386,8 @@ string semantic { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - $"Attribute '{semantic}' must contain {expectedComponents} components."); + $"Attribute '{semantic}' must contain {expectedComponents} components." + ); } int componentSize = ComponentSize(accessor.componentType); @@ -410,7 +405,8 @@ string semantic accessor.view.buffer, offset + component * componentSize, accessor.componentType, - accessor.normalized); + accessor.normalized + ); } } @@ -423,11 +419,12 @@ int index ) { Accessor accessor = GetAccessor(accessors, index, "indices"); if (!string.Equals(accessor.type, "SCALAR", StringComparison.Ordinal) - || accessor.componentType is not (5121 or 5123 or 5125)) - { + || accessor.componentType is not (5121 or 5123 or 5125) + ) { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - "Indices require an unsigned SCALAR accessor."); + "Indices require an unsigned SCALAR accessor." + ); } int elementSize = ComponentSize(accessor.componentType); @@ -454,24 +451,22 @@ private static float ReadComponent( int offset, int componentType, bool normalized - ) - => componentType switch - { - 5120 => normalized ? Math.Max((sbyte)buffer[offset] / 127f, -1f) : (sbyte)buffer[offset], - 5121 => normalized ? buffer[offset] / 255f : buffer[offset], - 5122 => normalized + ) => componentType switch + { + 5120 => normalized ? Math.Max((sbyte)buffer[offset] / 127f, -1f) : (sbyte)buffer[offset], + 5121 => normalized ? buffer[offset] / 255f : buffer[offset], + 5122 => normalized ? Math.Max(BinaryPrimitives.ReadInt16LittleEndian(buffer.AsSpan(offset, 2)) / 32767f, -1f) : BinaryPrimitives.ReadInt16LittleEndian(buffer.AsSpan(offset, 2)), - 5123 => normalized + 5123 => normalized ? BinaryPrimitives.ReadUInt16LittleEndian(buffer.AsSpan(offset, 2)) / 65535f : BinaryPrimitives.ReadUInt16LittleEndian(buffer.AsSpan(offset, 2)), - 5125 => normalized + 5125 => normalized ? BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset, 4)) / (float)uint.MaxValue : BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset, 4)), - 5126 => BitConverter.Int32BitsToSingle( - BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(offset, 4))), - _ => throw new RenderingAssetFormatException("$gltf.accessor", $"Unsupported component type '{componentType}'.") - }; + 5126 => BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(offset, 4))), + _ => throw new RenderingAssetFormatException("$gltf.accessor", $"Unsupported component type '{componentType}'.") + }; private static void ValidateAccessorBounds( Accessor accessor, @@ -484,7 +479,8 @@ int index { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - "Accessor exceeds its buffer view or uses an invalid stride."); + "Accessor exceeds its buffer view or uses an invalid stride." + ); } } @@ -492,31 +488,28 @@ private static Accessor GetAccessor( IReadOnlyList accessors, int index, string semantic - ) - => index >= 0 && index < accessors.Count - ? accessors[index] - : throw new RenderingAssetFormatException( - $"$gltf.{semantic}", - $"Accessor index '{index}' is out of range."); + ) => index >= 0 && index < accessors.Count + ? accessors[index] + : throw new RenderingAssetFormatException($"$gltf.{semantic}", $"Accessor index '{index}' is out of range."); private static int ComponentCount(string type) => type switch - { - "SCALAR" => 1, - "VEC2" => 2, - "VEC3" => 3, - "VEC4" => 4, - _ => throw new RenderingAssetFormatException("$gltf.accessor.type", $"Unsupported accessor type '{type}'.") - }; + { + "SCALAR" => 1, + "VEC2" => 2, + "VEC3" => 3, + "VEC4" => 4, + _ => throw new RenderingAssetFormatException("$gltf.accessor.type", $"Unsupported accessor type '{type}'.") + }; private static int ComponentSize(int type) => type switch - { - 5120 or 5121 => 1, - 5122 or 5123 => 2, - 5125 or 5126 => 4, - _ => throw new RenderingAssetFormatException("$gltf.accessor.componentType", $"Unsupported component type '{type}'.") - }; + { + 5120 or 5121 => 1, + 5122 or 5123 => 2, + 5125 or 5126 => 4, + _ => throw new RenderingAssetFormatException("$gltf.accessor.componentType", $"Unsupported component type '{type}'.") + }; private static void ValidateAttributeCount( int expected, @@ -527,7 +520,8 @@ string semantic { throw new RenderingAssetFormatException( $"$gltf.attributes.{semantic}", - "Attribute count does not match POSITION."); + "Attribute count does not match POSITION." + ); } } @@ -547,8 +541,8 @@ string path ) { string normalized = value.Replace('\\', '/').TrimStart('/'); if (string.IsNullOrWhiteSpace(normalized) - || normalized.Split('/', StringSplitOptions.RemoveEmptyEntries).Contains("..", StringComparer.Ordinal)) - { + || normalized.Split('/', StringSplitOptions.RemoveEmptyEntries).Contains("..", StringComparer.Ordinal) + ) { throw new RenderingAssetFormatException(path, "A project-relative URI without '..' is required."); } @@ -564,8 +558,7 @@ private static string GetProjectDirectory(string sourcePath) private static string CombineProjectPath( string directory, string relative - ) - => string.IsNullOrEmpty(directory) ? relative : $"{directory}/{relative}"; + ) => string.IsNullOrEmpty(directory) ? relative : $"{directory}/{relative}"; private readonly record struct BufferView( byte[] buffer, @@ -573,6 +566,7 @@ private readonly record struct BufferView( int length, int stride ); + private readonly record struct Accessor( BufferView view, int offset, @@ -582,4 +576,3 @@ private readonly record struct Accessor( bool normalized ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs similarity index 78% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs index f3707bc90..6b2330c69 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs @@ -1,10 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using Inno.Core.Mathematics; namespace Inno.Rendering.Assets.Authoring; @@ -14,13 +12,13 @@ internal static GeometryData ParseObj( string sourcePath, string text ) { - var positions = new List(); - var normals = new List(); - var textureCoordinates = new List(); - var vertices = new List(); - var indices = new List(); + List positions = []; + List normals = []; + List textureCoordinates = []; + List vertices = []; + List indices = []; var vertexMap = new Dictionary(); - var sections = new List(); + List sections = []; int subMeshStart = 0; string[] lines = text.Split('\n'); @@ -37,23 +35,34 @@ string text { case "v": RequirePartCount(parts, 4, sourcePath, lineIndex); - positions.Add(new Vector3( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex), - ParseFloat(parts[3], sourcePath, lineIndex))); + positions.Add( + new Vector3( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex), + ParseFloat(parts[3], sourcePath, lineIndex) + ) + ); break; case "vn": RequirePartCount(parts, 4, sourcePath, lineIndex); - normals.Add(Vector3.NormalizeSafe(new Vector3( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex), - ParseFloat(parts[3], sourcePath, lineIndex)))); + normals.Add( + Vector3.NormalizeSafe( + new Vector3( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex), + ParseFloat(parts[3], sourcePath, lineIndex) + ) + ) + ); break; case "vt": RequirePartCount(parts, 3, sourcePath, lineIndex); - textureCoordinates.Add(new Vector2( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex))); + textureCoordinates.Add( + new Vector2( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex) + ) + ); break; case "f": if (parts.Length < 4) @@ -70,7 +79,8 @@ string text normals, textureCoordinates, vertices, - vertexMap)) + vertexMap + )) .ToArray(); for (int corner = 1; corner < polygon.Length - 1; corner++) { @@ -98,7 +108,8 @@ string text value.position, Vector3.NormalizeSafe(value.normal), ToTangent(value.tangent, value.tangentW), - value.textureCoordinate)).ToArray(); + value.textureCoordinate + )).ToArray(); return new GeometryData(resultVertices, [.. indices], [.. sections]); } @@ -118,11 +129,17 @@ IReadOnlyList indices Vector3 edge2 = v2.position - v0.position; Vector3 faceNormal = Vector3.Cross(edge1, edge2); if (!v0.hasNormal) + { v0.normal += faceNormal; + } if (!v1.hasNormal) + { v1.normal += faceNormal; + } if (!v2.hasNormal) + { v2.normal += faceNormal; + } Vector2 uv1 = v1.textureCoordinate - v0.textureCoordinate; Vector2 uv2 = v2.textureCoordinate - v0.textureCoordinate; @@ -132,15 +149,34 @@ IReadOnlyList indices float inverse = 1f / determinant; Vector3 tangent = (edge1 * uv2.y - edge2 * uv1.y) * inverse; if (!v0.hasTangent) + { v0.tangent += tangent; + } if (!v1.hasTangent) + { v1.tangent += tangent; + } if (!v2.hasTangent) + { v2.tangent += tangent; + } } } } + internal static Vector4 ToTangent( + Vector3 value, + float handedness + ) { + Vector3 normalized = Vector3.NormalizeSafe(value); + if (normalized.LengthSquared() <= 1e-8f) + { + normalized = Vector3.RIGHT; + } + + return new Vector4(normalized.x, normalized.y, normalized.z, handedness < 0f ? -1f : 1f); + } + private static uint ResolveObjVertex( string token, string sourcePath, @@ -154,11 +190,11 @@ Dictionary vertexMap string[] values = token.Split('/'); int position = ResolveIndex(values[0], positions.Count, sourcePath, lineIndex, "position"); int texture = values.Length > 1 && values[1].Length != 0 - ? ResolveIndex(values[1], textureCoordinates.Count, sourcePath, lineIndex, "texture coordinate") - : -1; + ? ResolveIndex(values[1], textureCoordinates.Count, sourcePath, lineIndex, "texture coordinate") + : -1; int normal = values.Length > 2 && values[2].Length != 0 - ? ResolveIndex(values[2], normals.Count, sourcePath, lineIndex, "normal") - : -1; + ? ResolveIndex(values[2], normals.Count, sourcePath, lineIndex, "normal") + : -1; var key = new ObjVertexKey(position, texture, normal); if (vertexMap.TryGetValue(key, out uint existing)) { @@ -185,8 +221,8 @@ private static int ResolveIndex( string kind ) { if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) - || parsed == 0) - { + || parsed == 0 + ) { throw Error(sourcePath, lineIndex, $"Invalid OBJ {kind} index '{value}'."); } @@ -203,11 +239,10 @@ private static float ParseFloat( string value, string sourcePath, int lineIndex - ) - => float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float result) - && float.IsFinite(result) - ? result - : throw Error(sourcePath, lineIndex, $"Invalid finite float '{value}'."); + ) => float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float result) + && float.IsFinite(result) + ? result + : throw Error(sourcePath, lineIndex, $"Invalid finite float '{value}'."); private static void RequirePartCount( IReadOnlyList values, @@ -233,25 +268,11 @@ List sections } } - internal static Vector4 ToTangent( - Vector3 value, - float handedness - ) { - Vector3 normalized = Vector3.NormalizeSafe(value); - if (normalized.LengthSquared() <= 1e-8f) - { - normalized = Vector3.RIGHT; - } - - return new Vector4(normalized.x, normalized.y, normalized.z, handedness < 0f ? -1f : 1f); - } - private static RenderingAssetFormatException Error( string path, int lineIndex, string message - ) - => new($"{path}:{lineIndex + 1}", message); + ) => new($"{path}:{lineIndex + 1}", message); private readonly record struct ObjVertexKey( int position, @@ -270,4 +291,3 @@ internal sealed class MutableVertex internal float tangentW = 1f; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs index e3672b000..4f8a78c26 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs @@ -1,17 +1,18 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.pipeline")] -[Inno.Extensibility.Types.StableTypeId("6753d2fb-9773-518d-9673-beae57f6daa7")] +[StableTypeID("6753d2fb-9773-518d-9673-beae57f6daa7")] internal sealed class RenderPipelineAssetImporter : AssetImporter { /// @@ -42,12 +43,15 @@ CancellationToken cancellationToken RenderPipelineAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } Validate(asset); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } @@ -73,9 +77,9 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); Validate(asset); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } private static void Validate(RenderPipelineAsset asset) @@ -85,9 +89,12 @@ private static void Validate(RenderPipelineAsset asset) .GroupBy(static feature => feature.featureTypeId, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Pipeline feature '{duplicate}' is configured more than once."); + } if (asset.features.Any(static feature => feature.enabled && string.IsNullOrWhiteSpace(feature.featureTypeId))) + { throw new InvalidOperationException("Every enabled pipeline feature requires a stable extension ID."); + } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs index ce6398ee7..578c9b3db 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs @@ -1,17 +1,14 @@ -using Inno.Rendering; using System; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("d9c542b3-2def-59a3-a8a5-7115eaa1e0ea")] +[StableTypeID("d9c542b3-2def-59a3-a8a5-7115eaa1e0ea")] internal sealed class RenderingAssetFormatException : FormatException { internal RenderingAssetFormatException( string path, string message - ) - : base($"{path}: {message}") - { - } + ) : base($"{path}: {message}") {} } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs index 2a29ac805..5f605759d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs @@ -1,20 +1,21 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.shader")] -[Inno.Extensibility.Types.StableTypeId("8e87052c-6ea6-52d3-9201-8544c4f75013")] +[StableTypeID("8e87052c-6ea6-52d3-9201-8544c4f75013")] internal sealed class ShaderAssetImporter : AssetImporter { /// @@ -48,52 +49,89 @@ CancellationToken cancellationToken byte[] captured; try { - captured = ShaderGraphArtifact.Capture(graph, context.types, context.serialization, owner, + captured = ShaderGraphArtifact.Capture( + graph, + context.types, + context.serialization, + owner, ( id, path ) => { context.DependsOnArtifact(id); - AssetObject resolved = context.references.Resolve(id, context.services.GetStableTypeId(), - path, typeof(ShaderFunctionAsset), $"shader.sources[{id}]"); + AssetObject resolved = context.references.Resolve( + id, + context.services.GetStableTypeID(), + path, + typeof(ShaderFunctionAsset), + $"shader.sources[{id}]" + ); if (resolved is not ShaderFunctionAsset { isMissing: false } source) + { throw new InvalidDataException($"Shader function '{id}' is unavailable. Its graph reference is preserved."); - using ArtifactLease sourceLease = context.AcquireArtifact(source.identity.persistentId, ShaderSourceBundle.outputName); + } + using ArtifactLease sourceLease = context.AcquireArtifact( + source.identity.persistentID, + ShaderSourceBundle.C_OUTPUT_NAME + ); return sourceLease.ReadAllBytes(); - }, cancellationToken, + }, ( id, path ) => { context.DependsOnArtifact(id); - AssetObject resolved = context.references.Resolve(id, context.services.GetStableTypeId(), - path, typeof(ShaderAsset), $"shader.graphNodes[{id}]"); + AssetObject resolved = context.references.Resolve( + id, + context.services.GetStableTypeID(), + path, + typeof(ShaderAsset), + $"shader.graphNodes[{id}]" + ); if (resolved is not ShaderAsset { isMissing: false } node) + { throw new InvalidDataException($"Shader graph node '{id}' is unavailable. Its graph reference is preserved."); - using ArtifactLease graphLease = context.AcquireArtifact(node.identity.persistentId, ShaderGraphArtifact.outputName); + } + using ArtifactLease graphLease = context.AcquireArtifact(node.identity.persistentID, ShaderGraphArtifact.C_OUTPUT_NAME); return ShaderGraphArtifact.ReadDocument(graphLease.ReadAllBytes(), context.serialization); - }); + }, + cancellationToken + ); } catch (ShaderTargetUnavailableException exception) { - throw new AssetImportExtensionUnavailableException("inno.rendering.shader-target", exception.targetId); + throw new AssetImportExtensionUnavailableException("inno.rendering.shader-target", exception.targetID); } ShaderDefinition definition = ShaderGraphArtifact.ReadDefinition(captured, context.serialization, owner); // Function dependencies are authoring-only; texture defaults remain ordinary runtime references. _ = context.serialization.Serialize(definition, owner); foreach (AssetDependency dependency in dependencies.dependencies) + { output.DependsOnAsset(dependency); + } var asset = new ShaderAsset(); asset.SetDefinition(definition, context.serialization, owner); output.SetAsset(asset); if (definition.passes.Length == 0) + { output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); + } else - await output.WriteArtifactAsync("runtime", ReadOnlyMemory.Empty, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync(ShaderGraphArtifact.outputName, captured, - cancellationToken, AssetDeploymentScope.AuthoringOnly).ConfigureAwait(false); + { + await output.WriteArtifactAsync( + "runtime", + ReadOnlyMemory.Empty, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + } + await output.WriteArtifactAsync( + ShaderGraphArtifact.C_OUTPUT_NAME, + captured, + AssetDeploymentScope.AuthoringOnly, + cancellationToken + ).ConfigureAwait(false); } /// @@ -117,8 +155,14 @@ await output.WriteArtifactAsync(ShaderGraphArtifact.outputName, captured, CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); - return ValueTask.FromResult?>(GraphDocumentCodec.Encode( - ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(asset, context.artifacts), context.serialization), context.serialization)); + return ValueTask.FromResult?>( + GraphDocumentCodec.Encode( + ShaderGraphArtifact.ReadDocument( + ShaderGraphArtifact.Read(asset, context.artifacts), + context.serialization + ), + context.serialization + ) + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs index 185a0224f..cb02cd236 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs @@ -8,28 +8,36 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Represents an authoring-only source-function library; it is never a complete GPU stage or runtime dependency. /// -[StableTypeId("d8b5f6ec-c883-43b9-a5cd-95e7e24d6bba")] +[StableTypeID("d8b5f6ec-c883-43b9-a5cd-95e7e24d6bba")] public sealed class ShaderFunctionAsset : AssetObject { /// /// Gets the configured source language identity. /// - [SerializableProperty] public string languageId { get; internal set; } = string.Empty; + [SerializableProperty] + public string languageId { get; internal set; } = string.Empty; + /// /// Gets the explicitly exported functions available to graph source-function nodes. /// - [SerializableProperty] public string[] exports { get; internal set; } = []; + [SerializableProperty] + public string[] exports { get; internal set; } = []; + /// /// Gets the adapter implementation identity. /// - [SerializableProperty] public string implementationId { get; internal set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; internal set; } = string.Empty; + /// /// Gets the author-declared catalog path used by Shader creation tools. /// - [SerializableProperty] public string catalogPath { get; internal set; } = string.Empty; + [SerializableProperty] + public string catalogPath { get; internal set; } = string.Empty; + /// /// Gets the stable ordering value inside the authoring catalog. /// - [SerializableProperty] public int catalogOrder { get; internal set; } + [SerializableProperty] + public int catalogOrder { get; internal set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs index 158ce9547..a6a6485eb 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs @@ -1,29 +1,32 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Serialization; -using Inno.Rendering; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.shader-function")] -[Inno.Extensibility.Types.StableTypeId("17f67477-6d9c-5b85-9c98-f1c9df4961d3")] +[StableTypeID("17f67477-6d9c-5b85-9c98-f1c9df4961d3")] internal sealed class ShaderFunctionImporter : AssetImporter { /// /// Gets the normalized source extensions accepted by this importer. /// public override IReadOnlyList supportedExtensions { get; } = [".ishadersource"]; + /// /// Gets whether imported output is deployed to runtime, editor, or both domains. /// public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Creates an import settings using this implementation's validated inputs. /// @@ -52,33 +55,51 @@ protected override async ValueTask ImportAsync( AssetImportWriter output, CancellationToken cancellationToken ) { - var settings = context.importSettings as ShaderSourceImportSettings + ShaderSourceImportSettings settings = context.importSettings as ShaderSourceImportSettings ?? throw new InvalidOperationException("Shader source requires its standard import settings."); ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); string[] exports = (settings.exports ?? []).Where(static value => !string.IsNullOrWhiteSpace(value)) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (exports.Length == 0) + { throw new InvalidDataException("Shader source libraries must export at least one named function."); + } var source = new ShaderSourceFile(context.assetPath.ToString(), context.ReadUtf8Text()); using var frontends = new ShaderSourceFrontendRegistry(context.types); var modules = new Dictionary(StringComparer.Ordinal); foreach (string export in exports) { - var requests = new List - { new(settings.implementationId, settings.languageId, new(source, export, new SourceResolver(context))) }; + List requests = [new ShaderSourceImplementationRequest( + settings.implementationId, + settings.languageId, + new ShaderSourceRequest(source, export, new SourceResolver(context)) + )]; foreach (ShaderFunctionAsset implementation in settings.implementations ?? []) { if (implementation is null || implementation.isMissing) - throw new InvalidDataException("An alternate shader implementation is missing; its reference must be repaired before compilation."); - context.DependsOnArtifact(implementation.identity.persistentId); - using ArtifactLease lease = context.AcquireArtifact(implementation.identity.persistentId, ShaderSourceBundle.outputName); + { + throw new InvalidDataException( + "An alternate shader implementation is missing; its reference must be repaired before compilation." + ); + } + context.DependsOnArtifact(implementation.identity.persistentID); + using ArtifactLease lease = context.AcquireArtifact(implementation.identity.persistentID, ShaderSourceBundle.C_OUTPUT_NAME); requests.AddRange(ShaderSourceBundle.Decode(lease.ReadAllBytes(), export, context.serialization)); } ShaderSourceModuleAnalysis module = frontends.AnalyzeModule(requests); if (!module.succeeded) - throw new InvalidDataException(string.Join("\n", module.diagnostics.Select(static diagnostic => - $"{diagnostic.location.assetPath}:{diagnostic.location.line}:{diagnostic.location.column}: {diagnostic.message}"))); + { + throw new InvalidDataException( + string.Join( + "\n", + module.diagnostics.Select(static diagnostic => + $"{diagnostic.location.assetPath}:{diagnostic.location.line}:{diagnostic.location.column}: {diagnostic.message}") + ) + ); + } modules.Add(export, module); } output.SetAsset(new ShaderFunctionAsset @@ -89,13 +110,19 @@ CancellationToken cancellationToken catalogPath = NormalizeCatalogPath(settings.catalogPath), catalogOrder = settings.catalogOrder }); - await output.WriteArtifactAsync(ShaderSourceBundle.outputName, ShaderSourceBundle.Encode(modules, context.serialization), - cancellationToken, AssetDeploymentScope.AuthoringOnly).ConfigureAwait(false); + await output.WriteArtifactAsync( + ShaderSourceBundle.C_OUTPUT_NAME, + ShaderSourceBundle.Encode(modules, context.serialization), + AssetDeploymentScope.AuthoringOnly, + cancellationToken + ).ConfigureAwait(false); } private static string NormalizeCatalogPath(string? value) - => string.Join('/', (value ?? string.Empty).Split('/', - StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + => string.Join( + '/', + (value ?? string.Empty).Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + ); private sealed class SourceResolver(AssetImportContext context) : IShaderSourceResolver { @@ -117,11 +144,15 @@ string include ) { AssetPath owner = AssetPath.Parse(includingFile); string normalized = include.Replace('\\', '/'); - AssetPath path = normalized.Contains("::", StringComparison.Ordinal) ? AssetPath.Parse(normalized) - : new AssetPath(owner.source, (Path.GetDirectoryName(owner.localPath)?.Replace('\\', '/') is { Length: > 0 } directory - ? directory + "/" : "") + normalized); + AssetPath path = normalized.Contains("::", StringComparison.Ordinal) + ? AssetPath.Parse(normalized) + : new AssetPath( + owner.source, + (Path.GetDirectoryName(owner.localPath)?.Replace('\\', '/') is { Length: > 0 } directory + ? directory + "/" + : string.Empty) + normalized + ); return new(path.ToString(), context.ReadSourceUtf8Text(path)); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs index a15ca46e4..acdf05a89 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs @@ -7,32 +7,42 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Configures one source-function library through the standard asset import-settings sidecar. /// -[StableTypeId("59c92a59-ef51-4587-b917-df5d187d2717")] +[StableTypeID("59c92a59-ef51-4587-b917-df5d187d2717")] public sealed class ShaderSourceImportSettings : ISerializable { /// /// Gets or sets the registered language identity; an empty selection is an import error. /// - [SerializableProperty] public string languageId { get; set; } = string.Empty; + [SerializableProperty] + public string languageId { get; set; } = string.Empty; + /// /// Gets or sets the explicitly exported function names. Unlisted helpers remain private to the source library. /// - [SerializableProperty] public string[] exports { get; set; } = ["Evaluate"]; + [SerializableProperty] + public string[] exports { get; set; } = ["Evaluate"]; + /// /// Gets or sets the exact implementation key used by the selected rendering backend. /// - [SerializableProperty] public string implementationId { get; set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; set; } = string.Empty; + /// /// Gets or sets alternate source implementations; all must expose the same public interface with unique backend IDs. /// - [SerializableProperty] public ShaderFunctionAsset[] implementations { get; set; } = []; + [SerializableProperty] + public ShaderFunctionAsset[] implementations { get; set; } = []; + /// /// Gets or sets the slash-delimited authoring catalog path used to group this library in creation UIs. /// - [SerializableProperty] public string catalogPath { get; set; } = string.Empty; + [SerializableProperty] + public string catalogPath { get; set; } = string.Empty; + /// /// Gets or sets the stable ordering value of this library inside its authoring catalog group. /// - [SerializableProperty] public int catalogOrder { get; set; } + [SerializableProperty] + public int catalogOrder { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs index e6fe073d2..c5c7632f4 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs @@ -1,6 +1,3 @@ -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Buffers.Binary; using System.Collections.Generic; @@ -8,11 +5,15 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.texture")] -[Inno.Extensibility.Types.StableTypeId("30731d81-b1e7-54f9-8637-9410a8724647")] +[StableTypeID("30731d81-b1e7-54f9-8637-9410a8724647")] internal sealed partial class TextureAssetImporter : AssetImporter { /// @@ -53,10 +54,11 @@ CancellationToken cancellationToken width, height, context.extension == ".hdr" ? TextureColorSpace.Linear : TextureColorSpace.Srgb, - context.extension.TrimStart('.').ToLowerInvariant()); + context.extension.TrimStart('.').ToLowerInvariant() + ); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } internal static (int width, int height) ReadPngSize(ReadOnlySpan bytes) @@ -74,7 +76,7 @@ internal static (int width, int height) ReadPngSize(ReadOnlySpan bytes) internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) { - if (bytes.Length < 4 || bytes[0] != 0xff || bytes[1] != 0xd8) + if (bytes.Length < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8) { throw new RenderingAssetFormatException("texture.jpg", "Invalid JPEG start marker."); } @@ -82,7 +84,7 @@ internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) int offset = 2; while (offset + 4 <= bytes.Length) { - while (offset < bytes.Length && bytes[offset] == 0xff) + while (offset < bytes.Length && bytes[offset] == 0xFF) { offset++; } @@ -93,7 +95,7 @@ internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) } byte marker = bytes[offset++]; - if (marker is 0xd8 or 0xd9) + if (marker is 0xD8 or 0xD9) { continue; } @@ -139,26 +141,24 @@ internal static (int width, int height) ReadHdrSize(string text) Match match = HdrResolutionPattern().Match(text); if (!match.Success || !int.TryParse(match.Groups[1].Value, out int height) - || !int.TryParse(match.Groups[2].Value, out int width)) - { + || !int.TryParse(match.Groups[2].Value, out int width) + ) { throw new RenderingAssetFormatException("texture.hdr", "Radiance HDR resolution line is missing."); } return RequirePositiveSize(width, height, "texture.hdr"); } - private static bool IsStartOfFrame(byte marker) => marker is >= 0xc0 and <= 0xcf and not (0xc4 or 0xc8 or 0xcc); + private static bool IsStartOfFrame(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC); private static (int width, int height) RequirePositiveSize( int width, int height, string path - ) - => width > 0 && height > 0 - ? (width, height) - : throw new RenderingAssetFormatException(path, "Texture dimensions must be positive."); + ) => width > 0 && height > 0 + ? (width, height) + : throw new RenderingAssetFormatException(path, "Texture dimensions must be positive."); [GeneratedRegex(@"(?m)^[+-]Y\s+(\d+)\s+[+-]X\s+(\d+)\s*$")] private static partial Regex HdrResolutionPattern(); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs index 616829806..df1b4d3f3 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs @@ -1,15 +1,16 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Contains one immutable, source-free shader artifact ready for runtime GPU resource creation. /// -[Inno.Extensibility.Types.StableTypeId("43b40c10-c10b-5e97-b662-9bf9b4c9e34e")] +[StableTypeID("43b40c10-c10b-5e97-b662-9bf9b4c9e34e")] public sealed class RenderShaderArtifact { private readonly byte[] m_definitionData; @@ -33,12 +34,12 @@ public sealed class RenderShaderArtifact /// /// Every source-free pass available to the runtime shader definition. /// - /// - /// Thrown when a required identity is empty, no pass exists, or pass names are duplicated. - /// /// /// Native-serialized material, keyword, technique and pass contract captured with these programs; contains stable asset references only. /// + /// + /// Thrown when a required identity is empty, no pass exists, or pass names are duplicated. + /// public RenderShaderArtifact( string shaderName, string targetKey, @@ -53,18 +54,24 @@ ReadOnlySpan definitionData ArgumentNullException.ThrowIfNull(passes); RenderShaderPassArtifact[] passSnapshot = passes.ToArray(); if (passSnapshot.Length == 0) + { throw new ArgumentException("A deployed shader artifact must contain at least one pass.", nameof(passes)); + } if (passSnapshot.Select(static pass => pass.name).Distinct(StringComparer.Ordinal).Count() != passSnapshot.Length) + { throw new ArgumentException("A deployed shader artifact cannot repeat a pass name.", nameof(passes)); + } this.shaderName = shaderName; this.targetKey = targetKey; this.variant = variant; this.shaderInterface = RenderShaderPassArtifact.CloneInterface(shaderInterface); m_passes = Array.AsReadOnly(passSnapshot); if (definitionData.IsEmpty) + { throw new ArgumentException("A shader publication requires its captured runtime contract.", nameof(definitionData)); + } m_definitionData = definitionData.ToArray(); - contentHash = Convert.ToHexString(SHA256.HashData(RenderShaderArtifactCodec.Encode(this))); + this.contentHash = Convert.ToHexString(SHA256.HashData(RenderShaderArtifactCodec.Encode(this))); } /// @@ -102,4 +109,3 @@ ReadOnlySpan definitionData /// public IReadOnlyList passes => m_passes; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs index e9609edd9..b86d9c56d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs @@ -1,23 +1,24 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Encodes and validates the strict source-free binary format shared by game builds and Players. /// -[Inno.Extensibility.Types.StableTypeId("224813eb-a98c-5afa-a351-92e539a99d61")] +[StableTypeID("224813eb-a98c-5afa-a351-92e539a99d61")] public static class RenderShaderArtifactCodec { private const int C_MAX_BINDINGS = 4096; private const int C_MAX_PASSES = 1024; private const int C_MAX_STAGE_BYTES = 128 * 1024 * 1024; private const int C_MAX_STRING_BYTES = 1024 * 1024; - private static readonly byte[] S_MAGIC = "INNOSHDR"u8.ToArray(); + private static readonly byte[] MAGIC = "INNOSHDR"u8.ToArray(); /// /// Encodes a validated shader artifact into its deterministic runtime deployment representation. @@ -33,7 +34,7 @@ public static byte[] Encode(RenderShaderArtifact artifact) ArgumentNullException.ThrowIfNull(artifact); using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(S_MAGIC); + writer.Write(MAGIC); WriteString(writer, artifact.shaderName); WriteString(writer, artifact.targetKey); WriteString(writer, artifact.variant.value); @@ -87,29 +88,37 @@ RenderShaderVariant expectedVariant { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); - if (!reader.ReadBytes(S_MAGIC.Length).AsSpan().SequenceEqual(S_MAGIC)) + if (!reader.ReadBytes(MAGIC.Length).AsSpan().SequenceEqual(MAGIC)) + { throw new InvalidDataException("Shader artifact magic is invalid."); + } string shaderName = ReadString(reader); if (!string.Equals(shaderName, expectedShaderName, StringComparison.Ordinal)) { throw new InvalidDataException( - $"Shader artifact '{shaderName}' does not match requested shader '{expectedShaderName}'."); + $"Shader artifact '{shaderName}' does not match requested shader '{expectedShaderName}'." + ); } string targetKey = ReadString(reader); RenderShaderVariant variant = RenderShaderVariant.Parse(ReadString(reader)); if (variant != expectedVariant) { throw new InvalidDataException( - $"Shader artifact variant '{variant}' does not match requested variant '{expectedVariant}'."); + $"Shader artifact variant '{variant}' does not match requested variant '{expectedVariant}'." + ); } int definitionLength = ReadCount(reader, C_MAX_STAGE_BYTES, "shader definition byte"); if (definitionLength == 0) + { throw new InvalidDataException("A shader publication has no runtime contract."); + } byte[] definitionData = ReadBytes(reader, definitionLength); ShaderInterface shaderInterface = ReadInterface(reader); int passCount = ReadCount(reader, C_MAX_PASSES, "shader pass"); if (passCount == 0) + { throw new InvalidDataException("Shader artifact contains no pass."); + } var passes = new RenderShaderPassArtifact[passCount]; for (int index = 0; index < passes.Length; index++) { @@ -124,18 +133,17 @@ RenderShaderVariant expectedVariant ShaderStage stage = ReadEnum(reader); int byteCount = ReadCount(reader, C_MAX_STAGE_BYTES, "shader stage byte"); if (byteCount == 0) + { throw new InvalidDataException($"Shader pass '{passName}' contains an empty stage."); + } stages[stageIndex] = new RenderShaderStageArtifact(stage, ReadBytes(reader, byteCount)); } - passes[index] = new RenderShaderPassArtifact( - passName, - programKind, - rasterState, - passInterface, - stages); + passes[index] = new RenderShaderPassArtifact(passName, programKind, rasterState, passInterface, stages); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Shader artifact contains trailing data."); + } return new RenderShaderArtifact(shaderName, targetKey, variant, shaderInterface, passes, definitionData); } catch (InvalidDataException) @@ -143,10 +151,10 @@ RenderShaderVariant expectedVariant throw; } catch (Exception exception) when (exception is EndOfStreamException - or IOException - or ArgumentException - or FormatException - or OverflowException) + or IOException + or ArgumentException + or FormatException + or OverflowException) { throw new InvalidDataException("Shader artifact payload is corrupt.", exception); } @@ -168,7 +176,9 @@ ShaderInterface shaderInterface WriteString(writer, binding.nativeName); writer.Write(binding.location.HasValue); if (binding.location.HasValue) + { writer.Write(binding.location.Value); + } } } @@ -181,24 +191,31 @@ private static ShaderInterface ReadInterface(BinaryReader reader) { string id = ReadString(reader); if (!identities.Add(id)) + { throw new InvalidDataException($"Shader interface repeats binding '{id}'."); + } ShaderPropertyType type = ReadEnum(reader); ShaderStage stages = (ShaderStage)reader.ReadInt32(); - const ShaderStage validStages = ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute; - if (stages == ShaderStage.None || (stages & ~validStages) != 0) + const ShaderStage C_VALID_STAGES = ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute; + if (stages == ShaderStage.None || (stages & ~C_VALID_STAGES) != 0) + { throw new InvalidDataException($"Shader binding '{id}' has an invalid stage mask."); + } int arrayCount = reader.ReadInt32(); if (arrayCount <= 0) + { throw new InvalidDataException($"Shader binding '{id}' has an invalid array count."); + } bindings[index] = new ShaderInterfaceBinding( - new ShaderPropertyId(id), + new ShaderPropertyID(id), type, stages, arrayCount, ReadEnum(reader), ReadEnum(reader), ReadString(reader), - reader.ReadBoolean() ? reader.ReadInt32() : null); + reader.ReadBoolean() ? reader.ReadInt32() : null + ); } return new ShaderInterface(bindings); } @@ -227,27 +244,27 @@ RenderRasterState state private static RenderRasterState ReadRasterState(BinaryReader reader) => new() + { + topology = ReadEnum(reader), + cull = ReadEnum(reader), + frontFace = ReadEnum(reader), + depthCompare = ReadEnum(reader), + depthWrite = reader.ReadBoolean(), + colorWriteMask = reader.ReadByte(), + multisampling = reader.ReadBoolean(), + blend = new RenderBlendState { - topology = ReadEnum(reader), - cull = ReadEnum(reader), - frontFace = ReadEnum(reader), - depthCompare = ReadEnum(reader), - depthWrite = reader.ReadBoolean(), - colorWriteMask = reader.ReadByte(), - multisampling = reader.ReadBoolean(), - blend = new RenderBlendState - { - enabled = reader.ReadBoolean(), - colorSource = ReadEnum(reader), - colorDestination = ReadEnum(reader), - colorEquation = ReadEnum(reader), - alphaSource = ReadEnum(reader), - alphaDestination = ReadEnum(reader), - alphaEquation = ReadEnum(reader), - constantRgba = reader.ReadUInt32(), - alphaToCoverage = reader.ReadBoolean() - } - }; + enabled = reader.ReadBoolean(), + colorSource = ReadEnum(reader), + colorDestination = ReadEnum(reader), + colorEquation = ReadEnum(reader), + alphaSource = ReadEnum(reader), + alphaDestination = ReadEnum(reader), + alphaEquation = ReadEnum(reader), + constantRgba = reader.ReadUInt32(), + alphaToCoverage = reader.ReadBoolean() + } + }; private static void WriteString( BinaryWriter writer, @@ -256,7 +273,9 @@ string value ArgumentNullException.ThrowIfNull(value); byte[] bytes = Encoding.UTF8.GetBytes(value); if (bytes.Length > C_MAX_STRING_BYTES) + { throw new ArgumentException("Shader artifact string exceeds the deployment safety limit.", nameof(value)); + } writer.Write(bytes.Length); writer.Write(bytes); } @@ -274,7 +293,9 @@ string subject ) { int value = reader.ReadInt32(); if (value < 0 || value > maximum) + { throw new InvalidDataException($"Shader artifact {subject} count '{value}' is outside the valid range."); + } return value; } @@ -284,7 +305,9 @@ int count ) { byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new EndOfStreamException("Shader artifact ended before the declared payload length."); + } return bytes; } @@ -293,8 +316,9 @@ private static TEnum ReadEnum(BinaryReader reader) { int value = reader.ReadInt32(); if (!Enum.IsDefined(typeof(TEnum), value)) + { throw new InvalidDataException($"Shader artifact contains invalid {typeof(TEnum).Name} value '{value}'."); + } return (TEnum)Enum.ToObject(typeof(TEnum), value); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs index 80747c1ee..bdd900572 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs @@ -1,15 +1,16 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Carries one immutable compiled shader pass and its reflected runtime bindings. /// -[Inno.Extensibility.Types.StableTypeId("f22a2116-992d-5c69-bf6c-af05c191123b")] +[StableTypeID("f22a2116-992d-5c69-bf6c-af05c191123b")] public sealed class RenderShaderPassArtifact { private readonly IReadOnlyList m_stages; @@ -44,7 +45,9 @@ IReadOnlyList stages ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!Enum.IsDefined(programKind)) + { throw new ArgumentOutOfRangeException(nameof(programKind)); + } ArgumentNullException.ThrowIfNull(rasterState); ArgumentNullException.ThrowIfNull(shaderInterface); ArgumentNullException.ThrowIfNull(stages); @@ -83,28 +86,31 @@ IReadOnlyList stages public IReadOnlyList stages => m_stages; internal static ShaderInterface CloneInterface(ShaderInterface source) - => new(source.bindings.Select(static binding => new ShaderInterfaceBinding( - binding.id, - binding.type, - binding.stages, - binding.arrayCount, - binding.bindingKind, - binding.storageAccess, - binding.nativeName, - binding.location)).ToArray()); + => new( + source.bindings.Select(static binding => new ShaderInterfaceBinding( + binding.id, + binding.type, + binding.stages, + binding.arrayCount, + binding.bindingKind, + binding.storageAccess, + binding.nativeName, + binding.location + )).ToArray() + ); internal static RenderRasterState CloneRasterState(RenderRasterState source) => new() - { - topology = source.topology, - cull = source.cull, - frontFace = source.frontFace, - depthCompare = source.depthCompare, - depthWrite = source.depthWrite, - blend = source.blend, - colorWriteMask = source.colorWriteMask, - multisampling = source.multisampling - }; + { + topology = source.topology, + cull = source.cull, + frontFace = source.frontFace, + depthCompare = source.depthCompare, + depthWrite = source.depthWrite, + blend = source.blend, + colorWriteMask = source.colorWriteMask, + multisampling = source.multisampling + }; private static void ValidateStages( ShaderProgramKind programKind, @@ -112,14 +118,14 @@ IReadOnlyCollection stages ) { ShaderStage[] actual = stages.Select(static value => value.stage).Order().ToArray(); ShaderStage[] expected = programKind == ShaderProgramKind.Raster - ? [ShaderStage.Vertex, ShaderStage.Fragment] - : [ShaderStage.Compute]; + ? [ShaderStage.Vertex, ShaderStage.Fragment] + : [ShaderStage.Compute]; if (!actual.SequenceEqual(expected)) { throw new ArgumentException( $"Program kind '{programKind}' requires stages '{string.Join(", ", expected)}'.", - nameof(stages)); + nameof(stages) + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs index 9cda30256..fae173ca0 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs @@ -1,15 +1,16 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Stores one immutable target shader stage without retaining authoring source or compiler state. /// -[Inno.Extensibility.Types.StableTypeId("617ca942-9bab-528c-8052-e9cfb2ae0df5")] +[StableTypeID("617ca942-9bab-528c-8052-e9cfb2ae0df5")] public sealed class RenderShaderStageArtifact { private readonly byte[] m_bytes; @@ -31,9 +32,13 @@ public RenderShaderStageArtifact( ReadOnlySpan bytes ) { if (stage is not ShaderStage.Vertex and not ShaderStage.Fragment and not ShaderStage.Compute) + { throw new ArgumentException("A deployed shader stage must identify one programmable stage.", nameof(stage)); + } if (bytes.IsEmpty) + { throw new ArgumentException("A deployed shader stage cannot be empty.", nameof(bytes)); + } this.stage = stage; m_bytes = bytes.ToArray(); } @@ -48,4 +53,3 @@ ReadOnlySpan bytes /// public ReadOnlyMemory bytes => m_bytes; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs index d1c78deb3..c9f097973 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs @@ -1,19 +1,21 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Identifies one deterministic selection of static shader keyword options shared by authoring and runtime. /// -[Inno.Extensibility.Types.StableTypeId("c6c7b7a6-5e4f-5822-af8f-e894d7bb2d38")] +[StableTypeID("c6c7b7a6-5e4f-5822-af8f-e894d7bb2d38")] public readonly struct RenderShaderVariant : IEquatable { - private static readonly IReadOnlyDictionary S_EMPTY_OPTIONS = - new ReadOnlyDictionary(new Dictionary()); + private static readonly IReadOnlyDictionary EMPTY_OPTIONS = new ReadOnlyDictionary( + new Dictionary() + ); private readonly IReadOnlyDictionary? m_options; private readonly string? m_value; @@ -36,9 +38,11 @@ public RenderShaderVariant(IReadOnlyDictionary options) ValidatePart(option, nameof(options)); } - m_options = new ReadOnlyDictionary(options - .OrderBy(static value => value.Key, StringComparer.Ordinal) - .ToDictionary(static value => value.Key, static value => value.Value, StringComparer.Ordinal)); + m_options = new ReadOnlyDictionary( + options + .OrderBy(static value => value.Key, StringComparer.Ordinal) + .ToDictionary(static value => value.Key, static value => value.Value, StringComparer.Ordinal) + ); m_value = string.Join(";", m_options.Select(static pair => $"{pair.Key}={pair.Value}")); } @@ -50,13 +54,51 @@ public RenderShaderVariant(IReadOnlyDictionary options) /// /// Gets the immutable stable keyword selections. /// - public IReadOnlyDictionary options => m_options ?? S_EMPTY_OPTIONS; + public IReadOnlyDictionary options => m_options ?? EMPTY_OPTIONS; /// /// Gets the canonical cache-key representation. /// public string value => m_value ?? string.Empty; + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values select identical options; otherwise, . + /// + public bool Equals(RenderShaderVariant other) => string.Equals(value, other.value, StringComparison.Ordinal); + + /// + /// Determines whether this instance and the supplied object represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when the object is an identical variant; otherwise, . + /// + public override bool Equals(object? obj) => obj is RenderShaderVariant other && Equals(other); + + /// + /// Computes a hash code from the canonical variant representation. + /// + /// + /// A hash code consistent with logical equality. + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(value); + + /// + /// Formats this value as its canonical representation. + /// + /// + /// The canonical representation used by caches and deployed artifact paths. + /// + public override string ToString() => value; + /// /// Parses the canonical representation stored in a deployed artifact. /// @@ -73,23 +115,31 @@ public static RenderShaderVariant Parse(string value) { ArgumentNullException.ThrowIfNull(value); if (value.Length == 0) + { return empty; + } var options = new Dictionary(StringComparer.Ordinal); foreach (string selection in value.Split(';', StringSplitOptions.None)) { int separator = selection.IndexOf('=', StringComparison.Ordinal); if (separator <= 0 || separator == selection.Length - 1 || selection.IndexOf('=', separator + 1) >= 0) + { throw new FormatException($"Shader variant selection '{selection}' is malformed."); + } string keyword = selection[..separator]; string option = selection[(separator + 1)..]; if (!options.TryAdd(keyword, option)) + { throw new FormatException($"Shader variant repeats keyword '{keyword}'."); + } } var result = new RenderShaderVariant(options); if (!string.Equals(result.value, value, StringComparison.Ordinal)) + { throw new FormatException("Shader variant selections are not in canonical order."); + } return result; } @@ -109,9 +159,9 @@ public static RenderShaderVariant FromMaterial(MaterialAsset material) { ArgumentNullException.ThrowIfNull(material); ShaderAsset shader = material.shader - ?? throw new InvalidOperationException($"Material '{material.assetPath}' has no shader reference."); + ?? throw new InvalidOperationException($"Material '{material.assetPath}' has no shader reference."); ShaderDefinition definition = shader.definition - ?? throw new InvalidOperationException($"Shader '{shader.assetPath}' has no committed definition."); + ?? throw new InvalidOperationException($"Shader '{shader.assetPath}' has no committed definition."); return FromMaterial(material, definition); } @@ -137,7 +187,9 @@ ShaderDefinition definition ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(definition); if (material.keywords.Count == 0) + { return empty; + } HashSet enabled = material.keywords.ToHashSet(StringComparer.Ordinal); var selections = new Dictionary(StringComparer.Ordinal); foreach (ShaderKeywordDefinition keyword in definition.keywords) @@ -146,52 +198,24 @@ ShaderDefinition definition if (selected.Length > 1) { throw new InvalidOperationException( - $"Material '{material.assetPath}' selects multiple options for keyword '{keyword.id}'."); + $"Material '{material.assetPath}' selects multiple options for keyword '{keyword.id}'." + ); } if (selected.Length == 1) + { selections.Add(keyword.id, selected[0]); + } } string? unknown = enabled.FirstOrDefault(option => !definition.keywords.Any(keyword => keyword.options.Contains(option, StringComparer.Ordinal))); if (unknown is not null) { - throw new InvalidOperationException( - $"Material '{material.assetPath}' enables unknown option '{unknown}'."); + throw new InvalidOperationException($"Material '{material.assetPath}' enables unknown option '{unknown}'."); } return new RenderShaderVariant(selections); } - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values select identical options; otherwise, . - /// - public bool Equals(RenderShaderVariant other) => string.Equals(value, other.value, StringComparison.Ordinal); - - /// - /// Determines whether this instance and the supplied object represent the same logical state. - /// - /// - /// The object to compare with this instance. - /// - /// - /// when the object is an identical variant; otherwise, . - /// - public override bool Equals(object? obj) => obj is RenderShaderVariant other && Equals(other); - - /// - /// Computes a hash code from the canonical variant representation. - /// - /// - /// A hash code consistent with logical equality. - /// - public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(value); - /// /// Determines whether two variants select identical stable options. /// @@ -226,14 +250,6 @@ RenderShaderVariant right RenderShaderVariant right ) => !left.Equals(right); - /// - /// Formats this value as its canonical representation. - /// - /// - /// The canonical representation used by caches and deployed artifact paths. - /// - public override string ToString() => value; - private static void ValidatePart( string value, string parameterName @@ -242,8 +258,8 @@ string parameterName { throw new ArgumentException( "Shader variant identifiers and options must be non-empty and cannot contain ';' or '='.", - parameterName); + parameterName + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs index d81280f92..9fe91c453 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs @@ -1,21 +1,22 @@ -using Inno.Rendering; using System; using System.Globalization; using System.Security.Cryptography; using System.Text; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Defines deterministic relative paths shared by target-artifact producers and runtime consumers. /// -[Inno.Extensibility.Types.StableTypeId("85da30f1-a679-56d0-9cdf-7d6cf19b83f0")] +[StableTypeID("85da30f1-a679-56d0-9cdf-7d6cf19b83f0")] public static class RenderTargetArtifactPath { /// /// Gets the relative deployment path for one target shader variant. /// - /// + /// /// The persistent shader asset identity. /// /// @@ -28,21 +29,25 @@ public static class RenderTargetArtifactPath /// A platform-neutral path beneath the runtime content root. /// /// - /// Thrown when is empty. + /// Thrown when is empty. /// public static string GetShaderPath( - Guid shaderId, + Guid shaderID, GraphicsApi backend, RenderShaderVariant variant ) { - if (shaderId == Guid.Empty) - throw new ArgumentException("A target shader path requires a persistent asset identity.", nameof(shaderId)); - return string.Join('/', + if (shaderID == Guid.Empty) + { + throw new ArgumentException("A target shader path requires a persistent asset identity.", nameof(shaderID)); + } + return string.Join( + '/', "TargetArtifacts", "Shaders", backend.ToString(), - shaderId.ToString("D", CultureInfo.InvariantCulture), - HashVariant(variant.value) + ".shader"); + shaderID.ToString("D", CultureInfo.InvariantCulture), + HashVariant(variant.value) + ".shader" + ); } /// @@ -59,13 +64,17 @@ RenderShaderVariant variant /// public static string GetTexturePath(RenderTextureArtifactReference texture) { - if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + if (texture.assetID == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A target texture path requires a valid artifact reference.", nameof(texture)); - return string.Join('/', + } + return string.Join( + '/', "TargetArtifacts", "Textures", - texture.assetId.ToString("D", CultureInfo.InvariantCulture), - HashSlot(texture.slot.id) + ".ktx"); + texture.assetID.ToString("D", CultureInfo.InvariantCulture), + HashSlot(texture.slot.id) + ".ktx" + ); } private static string HashVariant(string value) @@ -73,4 +82,3 @@ private static string HashVariant(string value) private static string HashSlot(string value) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value))); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs index 724de99d0..bafad2a5d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs @@ -1,18 +1,19 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Encodes and validates the stable backend-neutral geometry artifact shared by import and runtime stages. /// -[Inno.Extensibility.Types.StableTypeId("8dc59951-b7e4-5c80-b34d-d2ce84174b65")] +[StableTypeID("8dc59951-b7e4-5c80-b34d-d2ce84174b65")] public static class GeometryArtifact { - private const ulong C_MAGIC = 0x4853454D4F4E4E49; + private const ulong C_MAGIC = 0x4853_454D_4F4E_4E49; /// /// Encodes normalized geometry into the immutable runtime artifact layout. @@ -105,7 +106,8 @@ public static GeometryData Decode(ReadOnlySpan bytes) new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - new Vector2(reader.ReadSingle(), reader.ReadSingle())); + new Vector2(reader.ReadSingle(), reader.ReadSingle()) + ); } for (int index = 0; index < indices.Length; index++) @@ -142,9 +144,7 @@ public static GeometryData Decode(ReadOnlySpan bytes) private static int RequireCount( int value, string kind - ) - => value >= 0 && value <= 100_000_000 - ? value - : throw new InvalidDataException($"Mesh artifact {kind} count is invalid."); + ) => value >= 0 && value <= 100_000_000 + ? value + : throw new InvalidDataException($"Mesh artifact {kind} count is invalid."); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs index 388d4f0cf..6b31d5883 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs @@ -1,24 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Represents imported geometry without prescribing scene or draw semantics. /// -[StableTypeId("f214637e-0a54-438d-8a72-9d892bd29a56")] +[StableTypeID("f214637e-0a54-438d-8a72-9d892bd29a56")] public sealed class GeometryAsset : AssetObject { - internal GeometryAsset() - { - } + internal GeometryAsset() {} /// /// Creates an immutable imported geometry description. @@ -52,7 +50,9 @@ Vector3 boundsExtents ArgumentOutOfRangeException.ThrowIfNegative(indexCount); ArgumentOutOfRangeException.ThrowIfNegative(sectionCount); if (boundsExtents.x < 0f || boundsExtents.y < 0f || boundsExtents.z < 0f) + { throw new ArgumentOutOfRangeException(nameof(boundsExtents), "Geometry bounds extents cannot be negative."); + } this.vertexCount = vertexCount; this.indexCount = indexCount; this.sectionCount = sectionCount; @@ -90,4 +90,3 @@ Vector3 boundsExtents [SerializableProperty] public Vector3 boundsExtents { get; internal set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs index 5f465d837..46a476868 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs @@ -1,15 +1,16 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Decodes normalized CPU geometry committed by mesh importers. /// -[Inno.Extensibility.Types.StableTypeId("81298da5-7d85-5964-8cb9-6f70a1e0564f")] +[StableTypeID("81298da5-7d85-5964-8cb9-6f70a1e0564f")] public static class GeometryAssetRuntime { /// @@ -30,4 +31,3 @@ public static GeometryData GetGeometryData(GeometryAsset geometry) return GeometryArtifact.Decode(geometry.runtimePayload.Span); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs index 6432e686f..7b33ca1d0 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs @@ -1,15 +1,16 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Contains normalized CPU mesh data ready for backend upload. /// -[Inno.Extensibility.Types.StableTypeId("9590e0d3-f8d2-58b1-9288-d0a20448ceb6")] +[StableTypeID("9590e0d3-f8d2-58b1-9288-d0a20448ceb6")] public sealed class GeometryData { /// @@ -52,4 +53,3 @@ GeometrySection[] sections /// public IReadOnlyList sections { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs index 237992b59..4d419292e 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs @@ -1,15 +1,16 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Identifies a contiguous triangle-index range. /// -[Inno.Extensibility.Types.StableTypeId("5da29d2a-b38b-5d50-b8ee-10e00503c0c5")] +[StableTypeID("5da29d2a-b38b-5d50-b8ee-10e00503c0c5")] public readonly record struct GeometrySection { /// @@ -41,4 +42,3 @@ int indexCount /// public int indexCount { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs index db07d0a29..256ec53c1 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs @@ -1,15 +1,16 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Stores one normalized vertex shared by all rendering backends. /// -[Inno.Extensibility.Types.StableTypeId("cfce5c30-dee4-5d62-9aa3-3e32ea5e7355")] +[StableTypeID("cfce5c30-dee4-5d62-9aa3-3e32ea5e7355")] public readonly record struct GeometryVertex { /// @@ -59,4 +60,3 @@ Vector2 textureCoordinate /// public Vector2 textureCoordinate { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs index ec478ed18..ac443e1d1 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Represents material state keyed by stable shader property identifiers. /// -[StableTypeId("56f1fdc7-dad9-464a-848f-fcae4c33ecf2")] -public class MaterialAsset : AssetObject +[StableTypeID("56f1fdc7-dad9-464a-848f-fcae4c33ecf2")] +public sealed class MaterialAsset : AssetObject { [SerializableProperty(PropertyVisibility.Hide)] private MaterialPropertyEntry[] m_properties = []; @@ -34,7 +34,7 @@ public class MaterialAsset : AssetObject /// Gets or sets an optional explicitly selected technique. /// [SerializableProperty] - public ShaderTechniqueId techniqueId { get; set; } + public ShaderTechniqueID techniqueId { get; set; } /// /// Gets persistent material values in stable insertion order. @@ -61,11 +61,13 @@ public class MaterialAsset : AssetObject /// Neutral material value. /// public void Set( - ShaderPropertyId id, + ShaderPropertyID id, MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } int index = Array.FindIndex(m_properties, candidate => candidate.id == id); if (index < 0) { @@ -87,16 +89,16 @@ public void ReplaceProperties(IEnumerable properties) { ArgumentNullException.ThrowIfNull(properties); MaterialPropertyEntry[] candidate = properties.ToArray(); - var ids = new HashSet(); + var ids = new HashSet(); foreach (MaterialPropertyEntry property in candidate) { if (!property.id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(properties)); + } if (!ids.Add(property.id)) { - throw new ArgumentException( - $"Material property '{property.id}' is duplicated.", - nameof(properties)); + throw new ArgumentException($"Material property '{property.id}' is duplicated.", nameof(properties)); } } m_properties = candidate @@ -117,7 +119,7 @@ public void ReplaceProperties(IEnumerable properties) /// when the property exists. /// public bool TryGet( - ShaderPropertyId id, + ShaderPropertyID id, out MaterialValue value ) { int index = Array.FindIndex(m_properties, candidate => candidate.id == id); @@ -139,11 +141,15 @@ public void SetKeyword( bool enabled ) { ArgumentException.ThrowIfNullOrWhiteSpace(keyword); - var values = m_keywords.ToHashSet(StringComparer.Ordinal); + HashSet values = m_keywords.ToHashSet(StringComparer.Ordinal); if (enabled) + { values.Add(keyword); + } else + { values.Remove(keyword); + } m_keywords = values.OrderBy(static value => value, StringComparer.Ordinal).ToArray(); } @@ -205,24 +211,21 @@ out string? value public bool RemoveMetadata(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); - int index = Array.FindIndex(m_metadata, entry => - string.Equals(entry.key, key, StringComparison.Ordinal)); + int index = Array.FindIndex(m_metadata, entry => string.Equals(entry.key, key, StringComparison.Ordinal)); if (index < 0) + { return false; + } var replacement = new MaterialMetadataEntry[m_metadata.Length - 1]; if (index > 0) + { Array.Copy(m_metadata, 0, replacement, 0, index); + } if (index < m_metadata.Length - 1) { - Array.Copy( - m_metadata, - index + 1, - replacement, - index, - m_metadata.Length - index - 1); + Array.Copy(m_metadata, index + 1, replacement, index, m_metadata.Length - index - 1); } m_metadata = replacement; return true; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs index 84ab29bb4..940e285e9 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Stores one open material metadata key and value. /// -[Inno.Extensibility.Types.StableTypeId("38365af5-31ec-5646-8f17-42c31c98f7c2")] +[StableTypeID("38365af5-31ec-5646-8f17-42c31c98f7c2")] public struct MaterialMetadataEntry { /// @@ -43,4 +43,3 @@ string value /// public string value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs index 8ed87bb8c..533710b20 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Describes one capability-compatible material pass selection. /// -[Inno.Extensibility.Types.StableTypeId("e4a37a17-bfc1-5b29-9c57-f7b387271f9f")] +[StableTypeID("e4a37a17-bfc1-5b29-9c57-f7b387271f9f")] public sealed class MaterialPassResolution { private readonly ShaderTechniqueDefinition m_technique; @@ -45,4 +45,3 @@ ShaderPassDefinition pass /// public ShaderPassDefinition pass => ShaderDefinitionSnapshot.Copy(m_pass); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs index 5cec7791e..f3a53f591 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Resolves materials through open provider-owned shader contracts and roles. /// -[Inno.Extensibility.Types.StableTypeId("dcf92cc9-04c6-52cd-8fd3-b2dc48f73b5a")] +[StableTypeID("dcf92cc9-04c6-52cd-8fd3-b2dc48f73b5a")] public static class MaterialPassResolver { /// @@ -21,10 +21,10 @@ public static class MaterialPassResolver /// /// Material whose shader and technique should be queried. /// - /// + /// /// Rendering-provider contract required by the caller. /// - /// + /// /// Provider-defined pass role required by the caller. /// /// @@ -35,13 +35,13 @@ public static class MaterialPassResolver /// public static MaterialPassResolution? Resolve( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, GraphicsCapabilities capabilities ) { ArgumentNullException.ThrowIfNull(material); ShaderDefinition? definition = material.shader?.definition; - return definition is null ? null : Resolve(definition, material.techniqueId, contractId, passRoleId, capabilities); + return definition is null ? null : Resolve(definition, material.techniqueId, contractID, passRoleID, capabilities); } /// @@ -50,13 +50,13 @@ GraphicsCapabilities capabilities /// /// The immutable publication's detached material contract. /// - /// + /// /// Explicit material technique, or an invalid ID to select the first compatible technique. /// - /// + /// /// Open rendering contract required by the caller. /// - /// + /// /// Open pass role required by the caller. /// /// @@ -70,34 +70,46 @@ GraphicsCapabilities capabilities /// public static MaterialPassResolution? Resolve( ShaderDefinition definition, - ShaderTechniqueId techniqueId, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderTechniqueID techniqueID, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, GraphicsCapabilities capabilities ) { ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(capabilities); - if (!contractId.isValid) - throw new ArgumentException("A shader contract ID must be valid.", nameof(contractId)); - if (!passRoleId.isValid) - throw new ArgumentException("A shader pass role ID must be valid.", nameof(passRoleId)); + if (!contractID.isValid) + { + throw new ArgumentException("A shader contract ID must be valid.", nameof(contractID)); + } + if (!passRoleID.isValid) + { + throw new ArgumentException("A shader pass role ID must be valid.", nameof(passRoleID)); + } foreach (ShaderTechniqueDefinition technique in definition.techniques) { - if (technique.contract != contractId || !capabilities.Supports(technique.requiredFeatures) - || techniqueId.isValid && technique.id != techniqueId) + if (technique.contract != contractID || !capabilities.Supports(technique.requiredFeatures) + || techniqueID.isValid && technique.id != techniqueID + ) { continue; + } foreach (ShaderTechniquePass mapping in technique.passes) { - if (mapping.role != passRoleId) + if (mapping.role != passRoleID) + { continue; + } foreach (ShaderPassDefinition pass in definition.passes) - if (string.Equals(pass.name, mapping.passName, StringComparison.Ordinal) && capabilities.Supports(pass.requiredFeatures)) + { + if (string.Equals(pass.name, mapping.passName, StringComparison.Ordinal) + && capabilities.Supports(pass.requiredFeatures) + ) { return new MaterialPassResolution(technique, pass); + } + } } } return null; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs index 35c985e74..24dd29925 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs @@ -1,21 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Holds frame-local material overrides without modifying a shared asset. /// -[Inno.Extensibility.Types.StableTypeId("aa10e23b-3f29-525e-af70-e48b77746037")] +[StableTypeID("aa10e23b-3f29-525e-af70-e48b77746037")] public sealed class MaterialPropertyBlock { - private readonly Dictionary m_values = []; + private readonly Dictionary m_values = []; /// /// Gets the number of active overrides. @@ -32,11 +32,13 @@ public sealed class MaterialPropertyBlock /// Neutral material value. /// public void Set( - ShaderPropertyId id, + ShaderPropertyID id, MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } m_values[id] = value; } @@ -46,14 +48,14 @@ MaterialValue value /// /// Stable shader property identifier. /// - /// - /// when the override exists. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// when the override exists. + /// public bool TryGet( - ShaderPropertyId id, + ShaderPropertyID id, out MaterialValue value ) => m_values.TryGetValue(id, out value); @@ -65,9 +67,10 @@ out MaterialValue value internal MaterialPropertyBlock Snapshot() { var snapshot = new MaterialPropertyBlock(); - foreach ((ShaderPropertyId id, MaterialValue value) in m_values) + foreach ((ShaderPropertyID id, MaterialValue value) in m_values) + { snapshot.m_values.Add(id, value); + } return snapshot; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs index 99682d8b2..7dcf7c32a 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Stores one persistent material property entry. /// -[Inno.Extensibility.Types.StableTypeId("f4c298ba-cda4-5155-a050-d33f70175c7c")] +[StableTypeID("f4c298ba-cda4-5155-a050-d33f70175c7c")] public struct MaterialPropertyEntry { /// @@ -25,11 +25,13 @@ public struct MaterialPropertyEntry /// Neutral material value. /// public MaterialPropertyEntry( - ShaderPropertyId id, + ShaderPropertyID id, MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } this.id = id; this.value = value; } @@ -37,11 +39,10 @@ MaterialValue value /// /// Gets or sets the stable shader property identifier. /// - public ShaderPropertyId id { get; set; } + public ShaderPropertyID id { get; set; } /// /// Gets or sets the neutral material value. /// public MaterialValue value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs index 4c3433a4a..a6abcf9cb 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs @@ -1,46 +1,13 @@ -using Inno.Assets; +using System; using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; -/// -/// Identifies the neutral value stored by a material property. -/// -[Inno.Extensibility.Types.StableTypeId("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] -public enum MaterialValueKind -{ - /// - /// Scalar floating-point value. - /// - Float, - /// - /// Four-component vector value. - /// - Vector, - /// - /// Linear color value. - /// - Color, - /// - /// Four-by-four matrix value. - /// - Matrix, - /// - /// Texture asset reference. - /// - Texture -} - /// /// Stores one native-serializable material value without a GPU binding. /// -[Inno.Extensibility.Types.StableTypeId("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f")] +[StableTypeID("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f")] public struct MaterialValue { private MaterialValue( @@ -150,7 +117,35 @@ public static MaterialValue FromTexture( default, default, value, - sampler ?? RenderSamplerState.linearClamp); + sampler ?? RenderSamplerState.linearClamp + ); } } +/// +/// Identifies the neutral value stored by a material property. +/// +[StableTypeID("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] +public enum MaterialValueKind +{ + /// + /// Scalar floating-point value. + /// + Float, + /// + /// Four-component vector value. + /// + Vector, + /// + /// Linear color value. + /// + Color, + /// + /// Four-by-four matrix value. + /// + Matrix, + /// + /// Texture asset reference. + /// + Texture +} diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs index d9a4f405f..26d03c5d7 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs @@ -1,31 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Stores one ordered feature extension selection using only stable data. /// -[Inno.Extensibility.Types.StableTypeId("aa788bff-6891-5055-8762-899971ba3bed")] +[StableTypeID("aa788bff-6891-5055-8762-899971ba3bed")] public struct RenderFeatureConfiguration { /// /// Creates an empty feature configuration for deserialization. /// - public RenderFeatureConfiguration() - { - } + public RenderFeatureConfiguration() {} /// /// Creates a feature configuration. /// - /// + /// /// Globally stable feature extension identifier. /// /// @@ -35,12 +33,12 @@ public RenderFeatureConfiguration() /// Whether the feature participates in graph building. /// public RenderFeatureConfiguration( - string featureTypeId, + string featureTypeID, SerializedRenderExtensionState? state = null, bool enabled = true ) { - ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeId); - this.featureTypeId = featureTypeId; + ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeID); + this.featureTypeId = featureTypeID; this.state = state ?? new SerializedRenderExtensionState(); this.enabled = enabled; } @@ -63,4 +61,3 @@ public RenderFeatureConfiguration( [SerializableProperty] public bool enabled { get; set; } = true; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs index 0daa6c44d..cb501d322 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs @@ -1,21 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Selects a pipeline extension and ordered feature configuration without defining a render path. /// -[StableTypeId("b17d289e-62de-4299-9e85-497143911798")] +[StableTypeID("b17d289e-62de-4299-9e85-497143911798")] public sealed class RenderPipelineAsset : AssetObject { - /// /// Gets or sets the globally stable pipeline extension identifier. /// @@ -54,4 +53,3 @@ public void SetFeatures(IEnumerable features) this.features = features.ToArray(); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs index caff618cc..613ffadde 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Stores reload-safe configuration for one pipeline or feature extension generation. /// -[Inno.Extensibility.Types.StableTypeId("8683f095-765d-5aa3-9a9f-fb95777885c5")] +[StableTypeID("8683f095-765d-5aa3-9a9f-fb95777885c5")] public struct SerializedRenderExtensionState { /// @@ -20,40 +20,40 @@ public struct SerializedRenderExtensionState /// public SerializedRenderExtensionState() { - propertyData = []; - dependencies = []; + this.propertyData = []; + this.dependencies = []; + } + + /// + /// Copies an owner-captured property snapshot, preserving its automatic resource dependency declarations. + /// + /// + /// Complete neutral properties produced by the asset authoring services. + /// + public SerializedRenderExtensionState(AssetPropertySnapshot properties) + { + ArgumentNullException.ThrowIfNull(properties); + this.stableTypeId = properties.stableTypeID; + this.propertyData = properties.data.ToArray(); + this.dependencies = properties.dependencies.ToArray(); } /// /// Creates immutable extension state from stable identity and property bytes. /// - /// + /// /// Stable type identity, or empty when the extension has no typed settings. /// /// /// Neutral native property bytes produced by asset serialization. Use the snapshot constructor when settings reference assets. /// public SerializedRenderExtensionState( - Guid stableTypeId, + Guid stableTypeID, ReadOnlySpan propertyData ) { - this.stableTypeId = stableTypeId; + this.stableTypeId = stableTypeID; this.propertyData = propertyData.ToArray(); - dependencies = []; - } - - /// - /// Copies an owner-captured property snapshot, preserving its automatic resource dependency declarations. - /// - /// - /// Complete neutral properties produced by the asset authoring services. - /// - public SerializedRenderExtensionState(AssetPropertySnapshot properties) - { - ArgumentNullException.ThrowIfNull(properties); - stableTypeId = properties.stableTypeId; - propertyData = properties.data.ToArray(); - dependencies = properties.dependencies.ToArray(); + this.dependencies = []; } /// @@ -74,4 +74,3 @@ public SerializedRenderExtensionState(AssetPropertySnapshot properties) [SerializableProperty] public AssetDependency[] dependencies { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs index 799a5c9ce..55b5796da 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs @@ -1,11 +1,13 @@ +using System; using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; -[Inno.Extensibility.Types.StableTypeId("a1b58cb9-3923-52f8-aa05-e9f282e5bdbd")] +[StableTypeID("a1b58cb9-3923-52f8-aa05-e9f282e5bdbd")] internal sealed class SerializedRenderExtensionStateConverter : SerializationConverter { /// @@ -25,8 +27,12 @@ SerializedRenderExtensionState value writer.Write("propertyData", value.propertyData ?? []); writer.Write("dependencies", value.dependencies ?? []); if (writer.context.TryGet(out AssetDependencyCollection? dependencies) && dependencies is not null) + { foreach (AssetDependency dependency in value.dependencies ?? []) + { dependencies.Add(dependency); + } + } } /// @@ -38,11 +44,11 @@ SerializedRenderExtensionState value /// /// The validated serialized render extension state that represents the completed operation. /// - public override SerializedRenderExtensionState Read(SerializationReader reader) => new() + public override SerializedRenderExtensionState Read(SerializationReader reader) + => new() { - stableTypeId = reader.Read("stableTypeId"), + stableTypeId = reader.Read("stableTypeId"), propertyData = reader.Read("propertyData"), dependencies = reader.Read("dependencies") }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Properties/ScriptingApi.cs b/src/services/rendering/Inno.Rendering.Assets/Properties/ScriptingApi.cs index bb0655fae..5942cb1de 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Properties/ScriptingApi.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Properties/ScriptingApi.cs @@ -11,9 +11,9 @@ [assembly: ScriptingApiExport(typeof(ShaderCullMode), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderCompareFunction), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderRenderState), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ShaderContractId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ShaderTechniqueId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ShaderPassRoleId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ShaderContractID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ShaderTechniqueID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ShaderPassRoleID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderMetadataEntry), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderPropertyDefinition), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderKeywordDefinition), ScriptingApiScope.Runtime)] diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs index 5783a8f4b..3e2cc817d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs @@ -1,20 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Represents the runtime contract imported from a shader graph. /// -[StableTypeId("e6672287-145f-4f51-8380-a6aeaf57a801")] -public class ShaderAsset : AssetObject +[StableTypeID("e6672287-145f-4f51-8380-a6aeaf57a801")] +public sealed class ShaderAsset : AssetObject { private ShaderDefinitionSnapshot? m_definition; @@ -62,13 +62,9 @@ SerializationContext context } [OnSerializableRestored] - private void OnSerializableRestored(SerializationContext context) - { - m_definition = m_definitionData.Length == 0 - ? null - : new ShaderDefinitionSnapshot(context.GetRequired().Deserialize( - m_definitionData, - context)); - } + private void OnSerializableRestored(SerializationContext context) => m_definition = m_definitionData.Length == 0 + ? null + : new ShaderDefinitionSnapshot( + context.GetRequired().Deserialize(m_definitionData, context) + ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractID.cs similarity index 83% rename from src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs rename to src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractID.cs index e28ecfa20..1c3da6fec 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractID.cs @@ -1,20 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Identifies an open shader and pipeline compatibility contract. /// -[Inno.Extensibility.Types.StableTypeId("741c24fb-b13e-5582-98b0-c13e12921fda")] -public record struct ShaderContractId +[StableTypeID("741c24fb-b13e-5582-98b0-c13e12921fda")] +public record struct ShaderContractID { /// /// Creates a shader contract identifier. @@ -22,7 +22,7 @@ public record struct ShaderContractId /// /// Globally stable contract value. /// - public ShaderContractId(string value) + public ShaderContractID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; @@ -44,6 +44,5 @@ public ShaderContractId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs index a2a237fd8..a887f0e8d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs @@ -1,27 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Contains the source-of-truth definition shared by shader import and material tooling. /// -[Inno.Extensibility.Types.StableTypeId("5bce7c89-203f-5921-8efc-1bca0f364943")] +[StableTypeID("5bce7c89-203f-5921-8efc-1bca0f364943")] public sealed class ShaderDefinition : ISerializable { /// /// Creates an empty shader definition for native deserialization. /// - public ShaderDefinition() - { - } + public ShaderDefinition() {} /// /// Creates a shader definition. @@ -89,4 +87,3 @@ public ShaderDefinition( [SerializableProperty] public ShaderTechniqueDefinition[] techniques { get; set; } = []; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs index 50297bf81..cb72d37cc 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs @@ -1,10 +1,11 @@ -using Inno.Rendering; using System; using System.Linq; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; -[Inno.Extensibility.Types.StableTypeId("3f7f8f3e-f933-57dd-a513-4165386a62ae")] +[StableTypeID("3f7f8f3e-f933-57dd-a513-4165386a62ae")] internal sealed class ShaderDefinitionSnapshot { private readonly ShaderDefinition m_definition; @@ -12,9 +13,9 @@ internal sealed class ShaderDefinitionSnapshot internal ShaderDefinitionSnapshot(ShaderDefinition definition) { ArgumentNullException.ThrowIfNull(definition); - if (definition.properties is null || definition.keywords is null || - definition.passes is null || definition.techniques is null) - { + if (definition.properties is null || definition.keywords is null + || definition.passes is null || definition.techniques is null + ) { throw new ArgumentException("Shader declaration collections cannot be null.", nameof(definition)); } m_definition = Copy(definition); @@ -36,16 +37,15 @@ internal static ShaderTechniqueDefinition Copy(ShaderTechniqueDefinition definit private static ShaderDefinition Copy(ShaderDefinition definition) => new() + { + name = definition.name, + properties = definition.properties.ToArray(), + keywords = definition.keywords.Select(static keyword => new ShaderKeywordDefinition { - name = definition.name, - properties = definition.properties.ToArray(), - keywords = definition.keywords.Select(static keyword => new ShaderKeywordDefinition - { - id = keyword.id, - options = keyword.options?.ToArray() ?? [] - }).ToArray(), - passes = definition.passes.Select(Copy).ToArray(), - techniques = definition.techniques.Select(Copy).ToArray() - }; + id = keyword.id, + options = keyword.options?.ToArray() ?? [] + }).ToArray(), + passes = definition.passes.Select(Copy).ToArray(), + techniques = definition.techniques.Select(Copy).ToArray() + }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs index e525a9cb7..65403f2b2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs @@ -1,15 +1,16 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Validates the source-free material, pass and technique contract shared by graph compilation and deployed shaders. /// -[Inno.Extensibility.Types.StableTypeId("196d9066-fe0d-5bd7-b763-0395296f7d88")] +[StableTypeID("196d9066-fe0d-5bd7-b763-0395296f7d88")] public static class ShaderDefinitionValidator { /// @@ -32,9 +33,11 @@ public static IReadOnlyList Validate( GraphicsCapabilities? capabilities = null ) { ArgumentNullException.ThrowIfNull(definition); - var diagnostics = new List(); + List diagnostics = []; if (string.IsNullOrWhiteSpace(definition.name)) + { Error("SHADER_NAME_MISSING", "A shader requires a nonempty name."); + } if (definition.properties is null || definition.passes is null || definition.keywords is null || definition.techniques is null) { Error("SHADER_DECLARATIONS_MISSING", "Shader declaration collections cannot be null."); @@ -45,30 +48,50 @@ public static IReadOnlyList Validate( Identifiers(definition.keywords.Select(static value => value.id), "KEYWORD"); Identifiers(definition.techniques.Select(static value => value.id.value), "TECHNIQUE"); if (definition.passes.Length == 0) + { Error("SHADER_PASSES_MISSING", "A shader requires at least one pass."); + } foreach (ShaderPropertyDefinition property in definition.properties) { if (!Enum.IsDefined(property.type) || !ShaderPropertyDefinition.IsBindingKindCompatible(property.type, property.bindingKind)) - Error("SHADER_PROPERTY_BINDING_INCOMPATIBLE", $"Property '{property.id}' has incompatible type '{property.type}' and binding '{property.bindingKind}'."); + { + Error( + "SHADER_PROPERTY_BINDING_INCOMPATIBLE", + $"Property '{property.id}' has incompatible type '{property.type}' and binding '{property.bindingKind}'." + ); + } if (!Enum.IsDefined(property.storageAccess)) + { Error("SHADER_STORAGE_ACCESS_INVALID", $"Property '{property.id}' has invalid storage access."); + } if (!Enum.IsDefined(property.bindingOwner)) + { Error("SHADER_BINDING_OWNER_INVALID", $"Property '{property.id}' has invalid binding ownership."); - if (property.stages == ShaderStage.None || (property.stages & ~(ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute)) != 0) + } + if (property.stages == ShaderStage.None + || (property.stages & ~(ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute)) != 0 + ) { Error("SHADER_PROPERTY_STAGES_INVALID", $"Property '{property.id}' requires valid stage visibility."); + } } foreach (ShaderKeywordDefinition keyword in definition.keywords) { if (keyword.options is null || keyword.options.Length == 0) + { Error("SHADER_KEYWORD_OPTIONS_MISSING", $"Keyword '{keyword.id}' requires selectable options."); + } else + { Identifiers(keyword.options, "KEYWORD_OPTION"); + } } HashSet passes = definition.passes.Select(static value => value.name).ToHashSet(StringComparer.Ordinal); foreach (ShaderTechniqueDefinition technique in definition.techniques) { if (string.IsNullOrWhiteSpace(technique.contract.value)) + { Error("SHADER_TECHNIQUE_CONTRACT_MISSING", $"Technique '{technique.id}' requires a contract ID."); + } if (technique.passes is null) { Error("SHADER_TECHNIQUE_ROLES_MISSING", $"Technique '{technique.id}' requires a role collection."); @@ -76,35 +99,58 @@ public static IReadOnlyList Validate( } Identifiers(technique.passes.Select(static value => value.role.value), "TECHNIQUE_ROLE"); foreach (ShaderTechniquePass binding in technique.passes) + { if (!passes.Contains(binding.passName)) + { Error("SHADER_UNKNOWN_TECHNIQUE_PASS", $"Technique '{technique.id}' refers to absent pass '{binding.passName}'."); + } + } } foreach (ShaderPassDefinition pass in definition.passes) { if (!Enum.IsDefined(pass.programKind)) + { Error("SHADER_PASS_KIND_INVALID", $"Pass '{pass.name}' has invalid program kind."); - if (!Enum.IsDefined(pass.renderState.cull) || !Enum.IsDefined(pass.renderState.depthCompare) || (pass.renderState.colorWriteMask & ~15) != 0) + } + if (!Enum.IsDefined(pass.renderState.cull) + || !Enum.IsDefined(pass.renderState.depthCompare) + || (pass.renderState.colorWriteMask & ~15) != 0 + ) { Error("SHADER_RASTER_STATE_INVALID", $"Pass '{pass.name}' has invalid raster state."); + } if (capabilities is not null && (pass.requiredFeatures & ~capabilities.features) != 0) - diagnostics.Add(new("SHADER_CAPABILITY_UNAVAILABLE", DiagnosticSeverity.Warning, $"Pass '{pass.name}' requires unavailable features '{pass.requiredFeatures & ~capabilities.features}'.")); + { + diagnostics.Add( + new ShaderDiagnostic( + "SHADER_CAPABILITY_UNAVAILABLE", + DiagnosticSeverity.Warning, + $"Pass '{pass.name}' requires unavailable features '{pass.requiredFeatures & ~capabilities.features}'." + ) + ); + } } return diagnostics.AsReadOnly(); void Error( string code, string message - ) => diagnostics.Add(new(code, DiagnosticSeverity.Error, message)); + ) => diagnostics.Add(new ShaderDiagnostic(code, DiagnosticSeverity.Error, message)); void Identifiers( IEnumerable values, string kind ) { var seen = new HashSet(StringComparer.Ordinal); foreach (string id in values) + { if (string.IsNullOrWhiteSpace(id)) + { Error("SHADER_" + kind + "_ID_MISSING", $"A {kind.ToLowerInvariant()} identity is empty."); + } else if (!seen.Add(id)) + { Error("SHADER_DUPLICATE_" + kind, $"The {kind.ToLowerInvariant()} identity '{id}' is repeated."); + } + } } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs index 6e888d2f9..0d2f56ec0 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs @@ -1,15 +1,16 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Reports one structured shader validation or compilation issue. /// -[Inno.Extensibility.Types.StableTypeId("31ce0701-357e-5b45-8364-171f59820d8f")] +[StableTypeID("31ce0701-357e-5b45-8364-171f59820d8f")] public sealed class ShaderDiagnostic { /// @@ -61,4 +62,3 @@ public ShaderDiagnostic( /// public ShaderSourceLocation? location { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs index d59e4aa6e..ba4fda0f4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Declares one static shader keyword that may produce compiled variants. /// -[Inno.Extensibility.Types.StableTypeId("551868bd-dbca-5da5-9dd8-d7e6e2ca7983")] +[StableTypeID("551868bd-dbca-5da5-9dd8-d7e6e2ca7983")] public struct ShaderKeywordDefinition { /// @@ -45,4 +45,3 @@ IEnumerable options /// public string[] options { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs index a7ca542c1..f8e16759e 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Stores one open metadata key and value. /// -[Inno.Extensibility.Types.StableTypeId("239d558b-cead-5efc-82d8-aee339c78f59")] +[StableTypeID("239d558b-cead-5efc-82d8-aee339c78f59")] public struct ShaderMetadataEntry { /// @@ -44,4 +44,3 @@ string value /// public string value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs index 3fe3f6f05..d75269ec9 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Defines one backend-neutral raster or compute shader pass. /// -[Inno.Extensibility.Types.StableTypeId("0f50b92b-4d4b-55f8-a954-953630083303")] +[StableTypeID("0f50b92b-4d4b-55f8-a954-953630083303")] public struct ShaderPassDefinition { /// @@ -83,4 +83,3 @@ public ShaderPassDefinition( /// public ShaderPassDefinition Copy() => ShaderDefinitionSnapshot.Copy(this); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleID.cs similarity index 83% rename from src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs rename to src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleID.cs index 5db2d462e..4cfe9098c 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleID.cs @@ -1,20 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Identifies an open pass purpose defined by a rendering provider. /// -[Inno.Extensibility.Types.StableTypeId("56d381cc-a73a-595b-824c-05191b9ce303")] -public record struct ShaderPassRoleId +[StableTypeID("56d381cc-a73a-595b-824c-05191b9ce303")] +public record struct ShaderPassRoleID { /// /// Creates a shader pass role identifier. @@ -22,7 +22,7 @@ public record struct ShaderPassRoleId /// /// Stable role value within a contract. /// - public ShaderPassRoleId(string value) + public ShaderPassRoleID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; @@ -44,6 +44,5 @@ public ShaderPassRoleId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs index 60f96a172..197713a7b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Identifies which layer supplies a declared shader property's value for each dispatch or draw. /// -[Inno.Extensibility.Types.StableTypeId("0c1a224a-4d13-56de-bda2-93128c1374cb")] +[StableTypeID("0c1a224a-4d13-56de-bda2-93128c1374cb")] public enum ShaderPropertyBindingOwner { /// @@ -25,4 +25,3 @@ public enum ShaderPropertyBindingOwner /// RenderPass } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs index af4793b3f..d3a7db2d8 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Declares one shader property and its reflected stage visibility. /// -[Inno.Extensibility.Types.StableTypeId("4b05e49c-b844-535e-aec9-c2201cfdd93f")] +[StableTypeID("4b05e49c-b844-535e-aec9-c2201cfdd93f")] public struct ShaderPropertyDefinition { /// @@ -45,7 +45,7 @@ public struct ShaderPropertyDefinition /// Layer responsible for supplying the binding value at execution time. /// public ShaderPropertyDefinition( - ShaderPropertyId id, + ShaderPropertyID id, string displayName, ShaderPropertyType type, ShaderStage stages, @@ -55,7 +55,9 @@ public ShaderPropertyDefinition( ShaderPropertyBindingOwner bindingOwner = ShaderPropertyBindingOwner.Material ) { if (!id.isValid) + { throw new ArgumentException("A shader property ID must be valid.", nameof(id)); + } ArgumentException.ThrowIfNullOrWhiteSpace(displayName); this.id = id; this.displayName = displayName; @@ -66,16 +68,20 @@ public ShaderPropertyDefinition( this.storageAccess = storageAccess; this.bindingOwner = bindingOwner; if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } if (!Enum.IsDefined(bindingOwner)) + { throw new ArgumentOutOfRangeException(nameof(bindingOwner)); + } ValidateBindingKind(type, this.bindingKind); } /// /// Gets or sets the stable property identifier. /// - public ShaderPropertyId id { get; set; } + public ShaderPropertyID id { get; set; } /// /// Gets or sets the artist-facing property name. @@ -115,28 +121,27 @@ public ShaderPropertyDefinition( internal static bool IsBindingKindCompatible( ShaderPropertyType type, ShaderPropertyBindingKind bindingKind - ) - => bindingKind switch - { - ShaderPropertyBindingKind.Uniform => !IsTexture(type) && type != ShaderPropertyType.Buffer, - ShaderPropertyBindingKind.SampledTexture => IsTexture(type), - ShaderPropertyBindingKind.StorageTexture => IsTexture(type), - ShaderPropertyBindingKind.StorageBuffer => type == ShaderPropertyType.Buffer, - _ => false - }; + ) => bindingKind switch + { + ShaderPropertyBindingKind.Uniform => !IsTexture(type) && type != ShaderPropertyType.Buffer, + ShaderPropertyBindingKind.SampledTexture => IsTexture(type), + ShaderPropertyBindingKind.StorageTexture => IsTexture(type), + ShaderPropertyBindingKind.StorageBuffer => type == ShaderPropertyType.Buffer, + _ => false + }; private static ShaderPropertyBindingKind InferBindingKind(ShaderPropertyType type) => IsTexture(type) - ? ShaderPropertyBindingKind.SampledTexture - : type == ShaderPropertyType.Buffer - ? ShaderPropertyBindingKind.StorageBuffer - : ShaderPropertyBindingKind.Uniform; + ? ShaderPropertyBindingKind.SampledTexture + : type == ShaderPropertyType.Buffer + ? ShaderPropertyBindingKind.StorageBuffer + : ShaderPropertyBindingKind.Uniform; private static bool IsTexture(ShaderPropertyType type) => type is ShaderPropertyType.Texture2D - or ShaderPropertyType.Texture2DArray - or ShaderPropertyType.Texture3D - or ShaderPropertyType.TextureCube; + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube; private static void ValidateBindingKind( ShaderPropertyType type, @@ -146,8 +151,8 @@ ShaderPropertyBindingKind bindingKind { throw new ArgumentException( $"Shader property type '{type}' is incompatible with binding kind '{bindingKind}'.", - nameof(bindingKind)); + nameof(bindingKind) + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs index a4e541863..a3ba7f061 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs @@ -1,85 +1,18 @@ -using Inno.Assets; -using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; -/// -/// Selects the triangle face rejected by a raster pass. -/// -[Inno.Extensibility.Types.StableTypeId("a0efdb24-2746-512d-aef5-46180c539581")] -public enum ShaderCullMode -{ - /// - /// Does not reject either face orientation. - /// - None, - /// - /// Rejects front-facing triangles. - /// - Front, - /// - /// Rejects back-facing triangles. - /// - Back -} - -/// -/// Selects the comparison used by depth testing. -/// -[Inno.Extensibility.Types.StableTypeId("cababee4-46b3-5bd8-800f-46d58149959b")] -public enum ShaderCompareFunction -{ - /// - /// Always rejects the fragment. - /// - Never, - /// - /// Accepts a fragment with a smaller depth. - /// - Less, - /// - /// Accepts a fragment with an equal depth. - /// - Equal, - /// - /// Accepts a fragment with a smaller or equal depth. - /// - LessEqual, - /// - /// Accepts a fragment with a greater depth. - /// - Greater, - /// - /// Accepts a fragment with a different depth. - /// - NotEqual, - /// - /// Accepts a fragment with a greater or equal depth. - /// - GreaterEqual, - /// - /// Always accepts the fragment. - /// - Always -} - /// /// Declares backend-neutral fixed-function state for one shader pass. /// -[Inno.Extensibility.Types.StableTypeId("1ee6df72-41ef-5fd0-a32a-2a8220164675")] +[StableTypeID("1ee6df72-41ef-5fd0-a32a-2a8220164675")] public struct ShaderRenderState { /// /// Gets the default opaque raster state. /// - public static ShaderRenderState opaque => new() + public static ShaderRenderState opaque + => new() { topology = RenderPrimitiveTopology.TriangleList, cull = ShaderCullMode.Back, @@ -87,7 +20,7 @@ public struct ShaderRenderState depthCompare = ShaderCompareFunction.LessEqual, depthWrite = true, blend = RenderBlendState.opaque, - colorWriteMask = 0x0f, + colorWriteMask = 0x0F, multisampling = true }; @@ -132,3 +65,62 @@ public struct ShaderRenderState public bool multisampling { get; set; } } +/// +/// Selects the triangle face rejected by a raster pass. +/// +[StableTypeID("a0efdb24-2746-512d-aef5-46180c539581")] +public enum ShaderCullMode +{ + /// + /// Does not reject either face orientation. + /// + None, + /// + /// Rejects front-facing triangles. + /// + Front, + /// + /// Rejects back-facing triangles. + /// + Back +} + +/// +/// Selects the comparison used by depth testing. +/// +[StableTypeID("cababee4-46b3-5bd8-800f-46d58149959b")] +public enum ShaderCompareFunction +{ + /// + /// Always rejects the fragment. + /// + Never, + /// + /// Accepts a fragment with a smaller depth. + /// + Less, + /// + /// Accepts a fragment with an equal depth. + /// + Equal, + /// + /// Accepts a fragment with a smaller or equal depth. + /// + LessEqual, + /// + /// Accepts a fragment with a greater depth. + /// + Greater, + /// + /// Accepts a fragment with a different depth. + /// + NotEqual, + /// + /// Accepts a fragment with a greater or equal depth. + /// + GreaterEqual, + /// + /// Always accepts the fragment. + /// + Always +} diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs index 46c767aa1..5f950260d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs @@ -1,15 +1,16 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Maps a shader diagnostic back to an asset, pass, stage, and source position. /// -[Inno.Extensibility.Types.StableTypeId("ab6474ed-51d0-570c-b15d-c477b5e9fecc")] +[StableTypeID("ab6474ed-51d0-570c-b15d-c477b5e9fecc")] public readonly record struct ShaderSourceLocation { /// @@ -72,6 +73,4 @@ public ShaderSourceLocation( /// Gets the one-based column, or zero when unavailable. /// public int column { get; } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs index 5f443c58f..37d6c53b4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Declares one contract-compatible pass mapping selectable by materials. /// -[Inno.Extensibility.Types.StableTypeId("461d82ac-0279-5044-b17b-776085f2ba35")] +[StableTypeID("461d82ac-0279-5044-b17b-776085f2ba35")] public struct ShaderTechniqueDefinition { /// @@ -32,15 +32,19 @@ public struct ShaderTechniqueDefinition /// Capabilities required by the complete technique. /// public ShaderTechniqueDefinition( - ShaderTechniqueId id, - ShaderContractId contract, + ShaderTechniqueID id, + ShaderContractID contract, IEnumerable passes, GraphicsCapability requiredFeatures = GraphicsCapability.None ) { if (!id.isValid) + { throw new ArgumentException("A technique ID must be valid.", nameof(id)); + } if (!contract.isValid) + { throw new ArgumentException("A shader contract ID must be valid.", nameof(contract)); + } ArgumentNullException.ThrowIfNull(passes); this.id = id; this.contract = contract; @@ -51,12 +55,12 @@ public ShaderTechniqueDefinition( /// /// Gets or sets the stable technique identifier. /// - public ShaderTechniqueId id { get; set; } + public ShaderTechniqueID id { get; set; } /// /// Gets or sets the open rendering-provider contract. /// - public ShaderContractId contract { get; set; } + public ShaderContractID contract { get; set; } /// /// Gets or sets role-to-pass mappings. @@ -68,4 +72,3 @@ public ShaderTechniqueDefinition( /// public GraphicsCapability requiredFeatures { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueID.cs similarity index 83% rename from src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs rename to src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueID.cs index d335fad99..fac076a87 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueID.cs @@ -1,20 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Identifies one material-selectable technique in a shader. /// -[Inno.Extensibility.Types.StableTypeId("250032b9-5391-5f1c-a220-c66baf0d15d0")] -public record struct ShaderTechniqueId +[StableTypeID("250032b9-5391-5f1c-a220-c66baf0d15d0")] +public record struct ShaderTechniqueID { /// /// Creates a shader technique identifier. @@ -22,7 +22,7 @@ public record struct ShaderTechniqueId /// /// Stable technique value within a shader. /// - public ShaderTechniqueId(string value) + public ShaderTechniqueID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; @@ -44,6 +44,5 @@ public ShaderTechniqueId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs index dca5e870c..285d7ef3c 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Maps one provider-defined role to one concrete shader pass. /// -[Inno.Extensibility.Types.StableTypeId("5ca78007-1d3e-53a0-a5e3-dce6b61088b4")] +[StableTypeID("5ca78007-1d3e-53a0-a5e3-dce6b61088b4")] public struct ShaderTechniquePass { /// @@ -26,11 +26,13 @@ public struct ShaderTechniquePass /// Concrete pass name within the shader. /// public ShaderTechniquePass( - ShaderPassRoleId role, + ShaderPassRoleID role, string passName ) { if (!role.isValid) + { throw new ArgumentException("A pass role must be valid.", nameof(role)); + } ArgumentException.ThrowIfNullOrWhiteSpace(passName); this.role = role; this.passName = passName; @@ -39,11 +41,10 @@ string passName /// /// Gets or sets the provider-defined role. /// - public ShaderPassRoleId role { get; set; } + public ShaderPassRoleID role { get; set; } /// /// Gets or sets the concrete pass name. /// public string passName { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs index 741a67a87..89111ceb4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs @@ -1,13 +1,14 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Exposes one or more portable image artifacts owned by an imported asset. /// -[Inno.Extensibility.Types.StableTypeId("a067587f-d6a5-56ed-860b-9ad0c9e1f8cb")] +[StableTypeID("a067587f-d6a5-56ed-860b-9ad0c9e1f8cb")] public interface IRenderTextureArtifactSource { /// @@ -15,4 +16,3 @@ public interface IRenderTextureArtifactSource /// IReadOnlyList textureArtifacts { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs index 51847fa8e..07c23a31a 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs @@ -1,19 +1,20 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Identifies one immutable texture source across authoring, deployment, and runtime generations. /// -[Inno.Extensibility.Types.StableTypeId("045f13ba-3cc0-5470-b025-08f9febf40e6")] +[StableTypeID("045f13ba-3cc0-5470-b025-08f9febf40e6")] public readonly record struct RenderTextureArtifactReference { /// /// Creates a reference to one texture slot owned by an imported asset generation. /// - /// + /// /// Persistent identity of the asset that owns the named source artifact. /// /// @@ -23,19 +24,23 @@ public readonly record struct RenderTextureArtifactReference /// Stable texture slot declaration. /// /// - /// Thrown when is empty or is negative. + /// Thrown when is empty or is negative. /// public RenderTextureArtifactReference( - Guid assetId, + Guid assetID, long contentRevision, RenderTextureArtifactSlot slot ) { - if (assetId == Guid.Empty) - throw new ArgumentException("A texture artifact reference requires a persistent asset identity.", nameof(assetId)); + if (assetID == Guid.Empty) + { + throw new ArgumentException("A texture artifact reference requires a persistent asset identity.", nameof(assetID)); + } ArgumentOutOfRangeException.ThrowIfNegative(contentRevision); if (string.IsNullOrWhiteSpace(slot.id) || string.IsNullOrWhiteSpace(slot.sourceOutputName)) + { throw new ArgumentException("A texture artifact reference requires a valid slot.", nameof(slot)); - this.assetId = assetId; + } + this.assetID = assetID; this.contentRevision = contentRevision; this.slot = slot; } @@ -43,7 +48,7 @@ RenderTextureArtifactSlot slot /// /// Gets the persistent identity of the owning asset. /// - public Guid assetId { get; } + public Guid assetID { get; } /// /// Gets the committed owner content revision used for last-good replacement. @@ -54,6 +59,4 @@ RenderTextureArtifactSlot slot /// Gets the referenced stable texture slot. /// public RenderTextureArtifactSlot slot { get; } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs index 930579a9c..9e021514b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs @@ -1,13 +1,14 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Assets; /// /// Declares an immutable source artifact that is compiled into one sampled texture slot. /// -[Inno.Extensibility.Types.StableTypeId("e1b8347a-2b49-5793-b693-f32aba02030e")] +[StableTypeID("e1b8347a-2b49-5793-b693-f32aba02030e")] public readonly record struct RenderTextureArtifactSlot { /// @@ -52,4 +53,3 @@ TextureColorSpace colorSpace /// public TextureColorSpace colorSpace { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs index b5772da33..4b9d7807f 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs @@ -1,29 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Represents imported texture content without owning a GPU handle. /// -[StableTypeId("e174b6eb-f79a-470f-a460-84f88ab49d0e")] +[StableTypeID("e174b6eb-f79a-470f-a460-84f88ab49d0e")] public sealed class TextureAsset : AssetObject, IRenderTextureArtifactSource { - private static readonly RenderTextureArtifactSlot[] S_linearTextureArtifacts = + private static readonly RenderTextureArtifactSlot[] LINEAR_TEXTURE_ARTIFACTS = [new RenderTextureArtifactSlot("main", "source", TextureColorSpace.Linear)]; - private static readonly RenderTextureArtifactSlot[] S_sRgbTextureArtifacts = + + private static readonly RenderTextureArtifactSlot[] RGB_TEXTURE_ARTIFACTS = [new RenderTextureArtifactSlot("main", "source", TextureColorSpace.Srgb)]; - internal TextureAsset() - { - } + internal TextureAsset() {} /// /// Creates an immutable imported texture description. @@ -90,8 +89,8 @@ string sourceFormat /// public IReadOnlyList textureArtifacts => colorSpace == TextureColorSpace.Srgb - ? S_sRgbTextureArtifacts - : S_linearTextureArtifacts; + ? RGB_TEXTURE_ARTIFACTS + : LINEAR_TEXTURE_ARTIFACTS; /// /// Creates a stable reference to this texture's current imported content. @@ -104,10 +103,11 @@ public IReadOnlyList textureArtifacts /// public RenderTextureArtifactReference GetTextureArtifactReference() { - Guid id = identity.persistentId; + Guid id = identity.persistentID; if (id == Guid.Empty) + { throw new InvalidOperationException("Texture must have a persistent asset identity."); + } return new RenderTextureArtifactReference(id, contentVersion, textureArtifacts[0]); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs index 98fc0e7e2..b51660bd6 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs @@ -1,19 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; /// /// Selects how texture samples are decoded for shader use. /// -[Inno.Extensibility.Types.StableTypeId("da42452c-1c45-5a09-8040-e72e37c00361")] +[StableTypeID("da42452c-1c45-5a09-8040-e72e37c00361")] public enum TextureColorSpace { /// @@ -25,4 +25,3 @@ public enum TextureColorSpace /// Srgb } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs index ee7151b5c..d1697c066 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs @@ -1,9 +1,8 @@ using System; -using System.IO; using System.Collections.Generic; -using Inno.Core.Serialization; +using System.IO; using Inno.Content; - +using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; @@ -25,23 +24,26 @@ public sealed class ContentRenderTargetArtifactProvider : IRenderTargetArtifactP /// /// The verified immutable content store, borrowed for this provider's lifetime. /// - /// - /// A required content or serialization service is null. - /// /// /// The runtime owner serialization registry. /// /// /// Complete runtime asset/reference context used to resolve captured texture defaults. /// + /// + /// A required content or serialization service is null. + /// public ContentRenderTargetArtifactProvider( IRuntimeContentStore content, SerializationRegistry serialization, SerializationContext context ) { - m_content = content ?? throw new ArgumentNullException(nameof(content)); - m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); - m_context = context ?? throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(context); + m_content = content; + m_serialization = serialization; + m_context = context; } /// @@ -93,11 +95,14 @@ out RenderShaderArtifact? artifact ArgumentNullException.ThrowIfNull(shader); ArgumentNullException.ThrowIfNull(capabilities); string path = RenderTargetArtifactPath.GetShaderPath( - shader.identity.persistentId, + shader.identity.persistentID, capabilities.backend, - variant); + variant + ); if (m_shaders.TryGetValue(path, out artifact)) + { return RenderTargetArtifactStatus.Ready; + } if (!m_content.index.TryGetEntry(new ContentKey(path), out _)) { artifact = null; @@ -106,12 +111,8 @@ out RenderShaderArtifact? artifact try { ShaderDefinition definition = shader.definition - ?? throw new InvalidDataException( - $"Runtime shader '{shader.assetPath}' has no committed definition."); - artifact = RenderShaderArtifactCodec.Decode( - ReadContent(new ContentKey(path)), - definition.name, - variant); + ?? throw new InvalidDataException($"Runtime shader '{shader.assetPath}' has no committed definition."); + artifact = RenderShaderArtifactCodec.Decode(ReadContent(new ContentKey(path)), definition.name, variant); m_shaders.Add(path, artifact); return RenderTargetArtifactStatus.Ready; } @@ -119,7 +120,8 @@ out RenderShaderArtifact? artifact { throw new InvalidDataException( $"Deployed shader artifact '{path}' failed integrity validation.", - exception); + exception + ); } } @@ -146,8 +148,10 @@ public RenderTargetArtifactStatus GetTextureArtifact( RenderTextureArtifactReference texture, out ReadOnlyMemory artifact ) { - if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + if (texture.assetID == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } string path = RenderTargetArtifactPath.GetTexturePath(texture); if (!m_content.index.TryGetEntry(new ContentKey(path), out _)) { @@ -156,7 +160,9 @@ out ReadOnlyMemory artifact } byte[] bytes = ReadContent(new ContentKey(path)); if (bytes.Length == 0) + { throw new InvalidDataException($"Deployed texture artifact '{path}' is empty."); + } artifact = bytes; return RenderTargetArtifactStatus.Ready; } @@ -165,12 +171,16 @@ private byte[] ReadContent(ContentKey key) { using ContentReadLease lease = m_content.Acquire(key); if (lease.entry.length > Array.MaxLength) + { throw new InvalidDataException($"Target artifact '{key}' exceeds the managed payload limit."); + } using Stream stream = lease.OpenRead(); - byte[] bytes = new byte[checked((int)lease.entry.length)]; + var bytes = new byte[checked((int)lease.entry.length)]; stream.ReadExactly(bytes); if (stream.ReadByte() != -1) + { throw new InvalidDataException($"Target artifact '{key}' exceeds its indexed length."); + } return bytes; } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs index 3a9c7ca83..ec81ca6df 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs @@ -1,13 +1,14 @@ +using System; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; namespace Inno.Rendering.Runtime; /// /// Resolves immutable, source-free target artifacts for the active rendering device. /// -[Inno.Extensibility.Types.StableTypeId("44afaaec-de0d-543a-904d-90a09db07e36")] +[StableTypeID("44afaaec-de0d-543a-904d-90a09db07e36")] public interface IRenderTargetArtifactProvider { /// @@ -74,4 +75,3 @@ RenderTargetArtifactStatus GetTextureArtifact( out ReadOnlyMemory artifact ); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs index d069ba478..06219a4ab 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs @@ -1,3 +1,4 @@ +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -5,27 +6,23 @@ namespace Inno.Rendering.Runtime; /// /// Describes the current availability of one target-specific rendering artifact. /// -[Inno.Extensibility.Types.StableTypeId("f3865bb4-5ff5-55c1-a910-27d7a65f84f2")] +[StableTypeID("f3865bb4-5ff5-55c1-a910-27d7a65f84f2")] public enum RenderTargetArtifactStatus { /// /// A validated artifact is available for immediate use. /// Ready, - /// /// Artifact production is still running and no usable artifact is available yet. /// Pending, - /// /// The active deployment does not contain the requested artifact. /// Unavailable, - /// /// Artifact production completed unsuccessfully and published a specific diagnostic. /// Failed } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs index 90b145fad..95f558929 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs @@ -1,15 +1,12 @@ -using Inno.Core.Execution; -using Inno.Rendering; +using Inno.Extensibility.Types; using Inno.Rendering.Assets; -using System; -using System.Threading; namespace Inno.Rendering.Runtime; /// /// Exposes current rendering configuration and immutable device state. /// -[Inno.Extensibility.Types.StableTypeId("6310eecc-3492-572c-a2f7-e29ec16e65b9")] +[StableTypeID("6310eecc-3492-572c-a2f7-e29ec16e65b9")] public static class GraphicsSettings { /// @@ -31,75 +28,3 @@ public static RenderPipelineAsset? defaultPipeline /// public static RenderFrameStatistics? frameStatistics => GraphicsSettingsExecutionContext.currentOrNull?.frameStatistics; } - -[Inno.Extensibility.Types.StableTypeId("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] -internal sealed class GraphicsSettingsState -{ - private readonly object m_sync = new(); - private RenderPipelineAsset? m_defaultPipeline; - private RenderFrameStatistics? m_frameStatistics; - - internal GraphicsSettingsState(GraphicsCapabilities capabilities) - { - this.capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities)); - } - - internal GraphicsCapabilities capabilities { get; } - - internal RenderPipelineAsset? defaultPipeline - { - get - { - lock (m_sync) - return m_defaultPipeline; - } - set - { - lock (m_sync) - m_defaultPipeline = value; - } - } - - internal RenderFrameStatistics? frameStatistics - { - get - { - lock (m_sync) - return m_frameStatistics; - } - set - { - lock (m_sync) - m_frameStatistics = value; - } - } - - internal void Clear() - { - lock (m_sync) - { - m_defaultPipeline = null; - m_frameStatistics = null; - } - } -} - -[Inno.Extensibility.Types.StableTypeId("0f145d08-b261-54bf-92aa-5ee6605d819e")] -internal static class GraphicsSettingsExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT = new("state"); - - internal static GraphicsSettingsState current - => currentOrNull - ?? throw new InvalidOperationException( - "No rendering runtime is bound to the current execution context."); - - internal static GraphicsSettingsState? currentOrNull => S_CURRENT.TryGet(out GraphicsSettingsState? state) ? state : null; - - internal static IDisposable Enter(GraphicsSettingsState state) - { - ArgumentNullException.ThrowIfNull(state); - return S_CURRENT.Enter(state); - } - -} diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs new file mode 100644 index 000000000..483153033 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs @@ -0,0 +1,23 @@ +using System; +using Inno.Core.Execution; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +[StableTypeID("0f145d08-b261-54bf-92aa-5ee6605d819e")] +internal static class GraphicsSettingsExecutionContext +{ + private static readonly ExecutionSlot CURRENT = new("state"); + + internal static GraphicsSettingsState current + => currentOrNull + ?? throw new InvalidOperationException("No rendering runtime is bound to the current execution context."); + + internal static GraphicsSettingsState? currentOrNull => CURRENT.TryGet(out GraphicsSettingsState? state) ? state : null; + + internal static IDisposable Enter(GraphicsSettingsState state) + { + ArgumentNullException.ThrowIfNull(state); + return CURRENT.Enter(state); + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs new file mode 100644 index 000000000..7f9e4b42f --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs @@ -0,0 +1,66 @@ +using System; +using Inno.Extensibility.Types; +using Inno.Rendering.Assets; + +namespace Inno.Rendering.Runtime; + +[StableTypeID("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] +internal sealed class GraphicsSettingsState +{ + private readonly object m_sync = new(); + private RenderPipelineAsset? m_defaultPipeline; + private RenderFrameStatistics? m_frameStatistics; + + internal GraphicsSettingsState(GraphicsCapabilities capabilities) + { + ArgumentNullException.ThrowIfNull(capabilities); + this.capabilities = capabilities; + } + + internal GraphicsCapabilities capabilities { get; } + + internal RenderPipelineAsset? defaultPipeline + { + get + { + lock (m_sync) + { + return m_defaultPipeline; + } + } + set + { + lock (m_sync) + { + m_defaultPipeline = value; + } + } + } + + internal RenderFrameStatistics? frameStatistics + { + get + { + lock (m_sync) + { + return m_frameStatistics; + } + } + set + { + lock (m_sync) + { + m_frameStatistics = value; + } + } + } + + internal void Clear() + { + lock (m_sync) + { + m_defaultPipeline = null; + m_frameStatistics = null; + } + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs new file mode 100644 index 000000000..fb89e7412 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Encodes a resource-ready draw into the owning model's scene pass. +/// +[StableTypeID("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] +public interface IPreparedViewDrawable +{ + /// + /// Encodes commands while the owning model controls attachments and view state. + /// + /// + /// Backend-neutral scene pass encoder. + /// + void Encode(RenderCommandEncoder commands); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs index e9f72c8be..c4faa6922 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs @@ -1,17 +1,18 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Builds view requests from host output sessions without owning a host window. /// -[Inno.Extensibility.Types.StableTypeId("52f335d4-64e4-5a11-96f3-c52e44295830")] +[StableTypeID("52f335d4-64e4-5a11-96f3-c52e44295830")] public interface IRenderModel : IDisposable { /// @@ -36,4 +37,3 @@ public interface IRenderModel : IDisposable /// RenderModelOutput Build(RenderOutputSession session); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs new file mode 100644 index 000000000..e7cac1ec2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Collects all active world-content sources for one exact view. +/// +[StableTypeID("b8d46505-dda2-52b6-b3c8-133e48641fed")] +public interface IViewContentCollector +{ + /// + /// Collects active source items in deterministic source order. + /// + /// + /// Frame-scoped host content and view. + /// + /// + /// Frame-local items; the caller owns their sort and composition. + /// + IReadOnlyList Collect(ViewContentContext context); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs new file mode 100644 index 000000000..4dcb388e3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Completes frame-local input after every output has routed its views. +/// +[StableTypeID("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] +public interface IViewContentFrameSource +{ + /// + /// Advances retained content once after all output views have supplied input. + /// + /// + /// The shared render frame whose input routing has completed. + /// + void CompleteFrame(ulong frameIndex); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs new file mode 100644 index 000000000..7692b628b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Receives world items without imposing a rendering-model sort key. +/// +[StableTypeID("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] +public interface IViewContentSink +{ + /// + /// Adds an item to the current view. + /// + /// + /// Frame-local content item. + /// + void Submit(ViewContentItem item); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs new file mode 100644 index 000000000..c6ecd62dd --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs @@ -0,0 +1,25 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Contributes model-independent world items to selected views. +/// +[StableTypeID("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] +public interface IViewContentSource : IDisposable +{ + /// + /// Collects items for one exact view. + /// + /// + /// Frame-scoped host content and view. + /// + /// + /// Collector receiving items. + /// + void Collect( + ViewContentContext context, + IViewContentSink sink + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs new file mode 100644 index 000000000..587965189 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs @@ -0,0 +1,31 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Prepares one model-independent drawable for a specific render pass. +/// +[StableTypeID("796c6186-c301-5cb2-a634-d03f8156a039")] +public interface IViewDrawable +{ + /// + /// Resolves reusable resources before render graph execution. + /// + /// + /// Active pipeline build context. + /// + /// + /// View that will draw this item. + /// + /// + /// Prepared frame-local draw when resources are available. + /// + /// + /// Whether the drawable is ready for this pass. + /// + bool TryPrepare( + RenderPipelineContext context, + RenderView view, + out IPreparedViewDrawable? prepared + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs new file mode 100644 index 000000000..d29ef4b9c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs @@ -0,0 +1,69 @@ +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Receives pointer input after the rendering model resolves visible draw order. +/// +[StableTypeID("8d770d54-025c-591a-b49e-9c12c4bde162")] +public interface IViewPointerTarget +{ + /// + /// Gets whether this target retains pointer ownership from an earlier press. + /// Rendering models route captured input before ordinary hit testing. + /// + bool hasPointerCapture { get; } + + /// + /// Gets whether keyboard and text input should continue reaching this target. + /// + bool hasKeyboardFocus { get; } + + /// + /// Changes keyboard focus after the rendering model resolves a pointer press. + /// + /// + /// Whether this target owns subsequent keyboard input. + /// + void SetKeyboardFocus(bool focused); + + /// + /// Maps one output pointer onto this item's local surface. + /// + /// + /// Exact rendered view. + /// + /// + /// Viewport-local input. + /// + /// + /// Local target coordinates when hit. + /// + /// + /// Whether this target is eligible to receive pointer input. + /// + bool TryHit( + RenderView view, + RenderOutputInput input, + out Vector2 localPosition + ); + + /// + /// Advances this target once for the frame with either routed input or an empty snapshot. + /// + /// + /// Routed viewport-local input, or an empty snapshot. + /// + /// + /// Target-local pointer coordinates. + /// + /// + /// Shared output frame index. + /// + void Advance( + RenderOutputInput input, + Vector2 localPosition, + ulong frameIndex + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs index b265e62b5..8cf297c0c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs @@ -1,10 +1,11 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable rendering model with a stable identity. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("eccab85a-0b21-55e1-b581-885c4bbc5192")] +[StableTypeID("eccab85a-0b21-55e1-b581-885c4bbc5192")] public sealed class RenderModelExtensionAttribute : Attribute { /// @@ -32,4 +33,3 @@ public RenderModelExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs index bdcaad772..d8803cfcb 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs @@ -1,17 +1,18 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Gets one model's prepared pipeline data for a host-owned target. /// -[Inno.Extensibility.Types.StableTypeId("3954390f-0d08-5114-82e4-5e35aa777472")] +[StableTypeID("3954390f-0d08-5114-82e4-5e35aa777472")] public sealed class RenderModelOutput { /// @@ -36,8 +37,9 @@ public RenderModelOutput( RenderTextureFormat targetFormat = RenderTextureFormat.RGBA8Srgb ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(pipeline); this.name = name; - this.pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); + this.pipeline = pipeline; this.data = data?.Snapshot() ?? throw new ArgumentNullException(nameof(data)); this.targetFormat = targetFormat; } @@ -46,17 +48,19 @@ public RenderModelOutput( /// Gets the diagnostic name. /// public string name { get; } + /// /// Gets the model's pipeline. /// public RenderPipelineAsset pipeline { get; } + /// /// Gets model frame data. /// public RenderFrameData data { get; } + /// /// Gets required target format. /// public RenderTextureFormat targetFormat { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs index 1132829ee..0135af49e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs @@ -1,15 +1,16 @@ +using System; +using System.Collections.Generic; using Inno.Core.Input; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Frame-local input located in the output viewport's physical pixels. /// -[Inno.Extensibility.Types.StableTypeId("0fe2e29e-4826-5e41-9ebd-a3110e673b5e")] +[StableTypeID("0fe2e29e-4826-5e41-9ebd-a3110e673b5e")] public sealed class RenderOutputInput { /// @@ -57,62 +58,84 @@ public RenderOutputInput( IReadOnlyList textInput, bool interactionEnabled = true ) { + ArgumentNullException.ThrowIfNull(keysPressed); + ArgumentNullException.ThrowIfNull(keysReleased); + ArgumentNullException.ThrowIfNull(buttonsPressed); + ArgumentNullException.ThrowIfNull(buttonsReleased); + ArgumentNullException.ThrowIfNull(textInput); this.pointerPosition = pointerPosition; this.pointerInside = pointerInside; this.scrollDelta = scrollDelta; this.modifiers = modifiers; - this.keysPressed = keysPressed ?? throw new ArgumentNullException(nameof(keysPressed)); - this.keysReleased = keysReleased ?? throw new ArgumentNullException(nameof(keysReleased)); - this.buttonsPressed = buttonsPressed ?? throw new ArgumentNullException(nameof(buttonsPressed)); - this.buttonsReleased = buttonsReleased ?? throw new ArgumentNullException(nameof(buttonsReleased)); - this.textInput = textInput ?? throw new ArgumentNullException(nameof(textInput)); + this.keysPressed = keysPressed; + this.keysReleased = keysReleased; + this.buttonsPressed = buttonsPressed; + this.buttonsReleased = buttonsReleased; + this.textInput = textInput; this.interactionEnabled = interactionEnabled; } /// /// Gets a snapshot with no active input. /// - public static RenderOutputInput empty { get; } = new(default, false, default, - KeyModifier.None, [], [], [], [], []); + public static RenderOutputInput empty { get; } = new(default, false, default, KeyModifier.None, [], [], [], [], []); /// /// Gets a snapshot that clears gameplay interaction while retaining the rendered output. /// - public static RenderOutputInput suspended { get; } = new(default, false, default, - KeyModifier.None, [], [], [], [], [], interactionEnabled: false); + public static RenderOutputInput suspended { get; } = new( + default, + false, + default, + KeyModifier.None, + [], + [], + [], + [], + [], + interactionEnabled: false + ); /// /// Gets viewport-local pointer coordinates. /// public Vector2 pointerPosition { get; } + /// /// Gets whether the pointer is inside this output. /// public bool pointerInside { get; } + /// /// Gets wheel movement. /// public Vector2 scrollDelta { get; } + /// /// Gets active keyboard modifiers. /// public KeyModifier modifiers { get; } + /// /// Gets keys pressed this frame. /// public IReadOnlyCollection keysPressed { get; } + /// /// Gets keys released this frame. /// public IReadOnlyCollection keysReleased { get; } + /// /// Gets buttons pressed this frame. /// public IReadOnlyCollection buttonsPressed { get; } + /// /// Gets buttons released this frame. /// public IReadOnlyCollection buttonsReleased { get; } + /// /// Gets ordered text commits. /// @@ -123,4 +146,3 @@ public RenderOutputInput( /// public bool interactionEnabled { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs index 9949caf95..8e891ed7a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs @@ -1,49 +1,52 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Assigns exactly one rendering model and its world-content sources to an output layer. /// -[Inno.Extensibility.Types.StableTypeId("7bdfe53d-72a0-5e9a-a922-fbc52362618f")] +[StableTypeID("7bdfe53d-72a0-5e9a-a922-fbc52362618f")] public sealed class RenderOutputLayer { /// /// Creates a model layer with explicit, distinct content-source IDs. /// - /// + /// /// Stable render-model or Editor contributor ID. /// - /// + /// /// World-content sources exclusively owned by this layer. /// public RenderOutputLayer( - string modelId, - IEnumerable sourceIds + string modelID, + IEnumerable sourceIDs ) { - ArgumentException.ThrowIfNullOrWhiteSpace(modelId); - ArgumentNullException.ThrowIfNull(sourceIds); - string[] ids = sourceIds.ToArray(); + ArgumentException.ThrowIfNullOrWhiteSpace(modelID); + ArgumentNullException.ThrowIfNull(sourceIDs); + string[] ids = sourceIDs.ToArray(); if (ids.Any(string.IsNullOrWhiteSpace) - || ids.Distinct(StringComparer.Ordinal).Count() != ids.Length) - throw new ArgumentException("A layer requires distinct non-empty source IDs.", nameof(sourceIds)); - this.modelId = modelId; - this.sourceIds = new ReadOnlyCollection(ids); + || ids.Distinct(StringComparer.Ordinal).Count() != ids.Length + ) { + throw new ArgumentException("A layer requires distinct non-empty source IDs.", nameof(sourceIDs)); + } + this.modelID = modelID; + this.sourceIDs = new ReadOnlyCollection(ids); } /// /// Gets the exact rendering model ID. /// - public string modelId { get; } + public string modelID { get; } + /// /// Gets the assigned world-content source IDs. /// - public IReadOnlyList sourceIds { get; } + public IReadOnlyList sourceIDs { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs index f8b9e5f0a..f5d074701 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs @@ -1,17 +1,18 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// States the exact model order and exclusive world-content assignment for one output. /// -[Inno.Extensibility.Types.StableTypeId("313e9d03-9423-53a6-8dd8-f4faad999439")] +[StableTypeID("313e9d03-9423-53a6-8dd8-f4faad999439")] public sealed class RenderOutputRoute { /// @@ -25,11 +26,15 @@ public RenderOutputRoute(IEnumerable layers) ArgumentNullException.ThrowIfNull(layers); RenderOutputLayer[] values = layers.ToArray(); if (values.Length == 0 || values.Any(static layer => layer is null) - || values.Select(static layer => layer.modelId).Distinct(StringComparer.Ordinal).Count() != values.Length) + || values.Select(static layer => layer.modelID).Distinct(StringComparer.Ordinal).Count() != values.Length + ) { throw new ArgumentException("A route requires distinct model layers.", nameof(layers)); - string[] sourceIds = values.SelectMany(static layer => layer.sourceIds).ToArray(); - if (sourceIds.Distinct(StringComparer.Ordinal).Count() != sourceIds.Length) + } + string[] sourceIDs = values.SelectMany(static layer => layer.sourceIDs).ToArray(); + if (sourceIDs.Distinct(StringComparer.Ordinal).Count() != sourceIDs.Length) + { throw new ArgumentException("Each world-content source may be assigned to only one model layer.", nameof(layers)); + } this.layers = new ReadOnlyCollection(values); } @@ -38,4 +43,3 @@ public RenderOutputRoute(IEnumerable layers) /// public IReadOnlyList layers { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs index a34d6ed5d..f511af469 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs @@ -1,17 +1,18 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Declares a host output without naming a camera or scene model. /// -[Inno.Extensibility.Types.StableTypeId("18d40f92-089a-5c0e-94a9-402b68225c2b")] +[StableTypeID("18d40f92-089a-5c0e-94a9-402b68225c2b")] public sealed class RenderOutputSession { /// @@ -52,12 +53,14 @@ public RenderOutputSession( RenderOutputRoute? route = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(viewContent); this.id = id; - this.content = content ?? throw new ArgumentNullException(nameof(content)); + this.content = content; this.viewport = viewport; this.frameIndex = frameIndex; this.deltaTime = deltaTime; - this.viewContent = viewContent ?? throw new ArgumentNullException(nameof(viewContent)); + this.viewContent = viewContent; this.input = input ?? RenderOutputInput.empty; this.route = route; } @@ -66,30 +69,37 @@ public RenderOutputSession( /// Gets the stable host output identity. /// public string id { get; } + /// /// Gets selected content roots. /// public ContentReadScope content { get; } + /// /// Gets the output pixel viewport. /// public RenderViewport viewport { get; } + /// /// Gets the shared output frame index. /// public ulong frameIndex { get; } + /// /// Gets elapsed frame time. /// public float deltaTime { get; } + /// /// Gets the world content collector. /// public IViewContentCollector viewContent { get; } + /// /// Gets viewport-local input. /// public RenderOutputInput input { get; } + /// /// Gets the explicit model route, if configured. /// @@ -107,8 +117,14 @@ public RenderOutputSession( public RenderOutputSession ForLayer(RenderOutputLayer layer) { ArgumentNullException.ThrowIfNull(layer); - return new RenderOutputSession(id, content, viewport, frameIndex, deltaTime, - new SelectedViewContentCollector(viewContent, layer.sourceIds), input); + return new RenderOutputSession( + id, + content, + viewport, + frameIndex, + deltaTime, + new SelectedViewContentCollector(viewContent, layer.sourceIDs), + input + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs new file mode 100644 index 000000000..a07192d7b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs @@ -0,0 +1,70 @@ +using System; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Describes one backend-neutral view produced by a rendering model. +/// +[StableTypeID("eb2ef876-46a8-5155-8c45-c96b14ad2043")] +public readonly record struct RenderView +{ + /// + /// Creates the exact view used to render content into a viewport. + /// + /// + /// Stable identity within the current output session. + /// + /// + /// Destination pixel rectangle. + /// + /// + /// World-to-view transform. + /// + /// + /// View-to-clip transform. + /// + /// + /// Model-defined visible content bits. + /// + public RenderView( + string id, + RenderViewport viewport, + Matrix viewMatrix, + Matrix projectionMatrix, + ulong visibilityMask = ulong.MaxValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.viewport = viewport; + this.viewMatrix = viewMatrix; + this.projectionMatrix = projectionMatrix; + this.visibilityMask = visibilityMask; + } + + /// + /// Gets the view identity within its output session. + /// + public string id { get; } + + /// + /// Gets the destination pixel rectangle. + /// + public RenderViewport viewport { get; } + + /// + /// Gets the world-to-view transform. + /// + public Matrix viewMatrix { get; } + + /// + /// Gets the view-to-clip transform. + /// + public Matrix projectionMatrix { get; } + + /// + /// Gets the model-defined visible content bits. + /// + public ulong visibilityMask { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs new file mode 100644 index 000000000..385ada4ae --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Restricts a neutral world-content collector to an output layer's source IDs. +/// +[StableTypeID("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] +public sealed class SelectedViewContentCollector : IViewContentCollector +{ + private readonly IViewContentCollector m_inner; + private readonly IReadOnlyList m_sourceIDs; + + /// + /// Creates a collector that forwards only the selected source identities. + /// + /// + /// Active generation's source collector. + /// + /// + /// Source IDs exclusively assigned to this layer. + /// + public SelectedViewContentCollector( + IViewContentCollector inner, + IReadOnlyList sourceIDs + ) { + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(sourceIDs); + m_inner = inner; + m_sourceIDs = sourceIDs; + } + + /// + /// Collects only the assigned world-content sources for one exact view. + /// + /// + /// The original model view, output input, and frame timing. + /// + /// + /// Frame-local content emitted by the assigned sources. + /// + public IReadOnlyList Collect(ViewContentContext context) + { + ArgumentNullException.ThrowIfNull(context); + return m_inner.Collect( + new ViewContentContext( + context.content, + context.sessionID, + context.view, + context.frameIndex, + context.deltaTime, + context.input, + context.views, + m_sourceIDs + ) + ); + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs deleted file mode 100644 index b35796395..000000000 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs +++ /dev/null @@ -1,485 +0,0 @@ -using Inno.Core.Identity; -using Inno.Core.Mathematics; -using Inno.References; -using Inno.Rendering; -using System; -using System.Collections.Generic; - -namespace Inno.Rendering.Runtime; - -/// -/// Describes one backend-neutral view produced by a rendering model. -/// -[Inno.Extensibility.Types.StableTypeId("eb2ef876-46a8-5155-8c45-c96b14ad2043")] -public readonly record struct RenderView -{ - /// - /// Creates the exact view used to render content into a viewport. - /// - /// - /// Stable identity within the current output session. - /// - /// - /// Destination pixel rectangle. - /// - /// - /// World-to-view transform. - /// - /// - /// View-to-clip transform. - /// - /// - /// Model-defined visible content bits. - /// - public RenderView( - string id, - RenderViewport viewport, - Matrix viewMatrix, - Matrix projectionMatrix, - ulong visibilityMask = ulong.MaxValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.viewport = viewport; - this.viewMatrix = viewMatrix; - this.projectionMatrix = projectionMatrix; - this.visibilityMask = visibilityMask; - } - - /// - /// Gets the view identity within its output session. - /// - public string id { get; } - - /// - /// Gets the destination pixel rectangle. - /// - public RenderViewport viewport { get; } - - /// - /// Gets the world-to-view transform. - /// - public Matrix viewMatrix { get; } - - /// - /// Gets the view-to-clip transform. - /// - public Matrix projectionMatrix { get; } - - /// - /// Gets the model-defined visible content bits. - /// - public ulong visibilityMask { get; } -} - -/// -/// Supplies one content source with the host-selected scene roots and an exact view. -/// -[Inno.Extensibility.Types.StableTypeId("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] -public sealed class ViewContentContext -{ - /// - /// Creates a frame-scoped content collection context. - /// - /// - /// Ordered roots selected by the host. - /// - /// - /// Stable identity of the host output session. - /// - /// - /// Exact view that will consume the content. - /// - /// - /// Monotonic output frame number. - /// - /// - /// Elapsed frame time in seconds. - /// - /// - /// Pointer and keyboard input in output pixel coordinates. - /// - /// - /// All views in the same model output, used to choose shared content resolution. - /// - /// - /// Optional explicit source allowlist for a routed model layer. - /// - public ViewContentContext( - ContentReadScope content, - string sessionId, - RenderView view, - ulong frameIndex, - float deltaTime, - RenderOutputInput? input = null, - IReadOnlyList? views = null, - IReadOnlyList? sourceIds = null - ) { - this.content = content ?? throw new ArgumentNullException(nameof(content)); - ArgumentException.ThrowIfNullOrWhiteSpace(sessionId); - this.sessionId = sessionId; - this.view = view; - this.frameIndex = frameIndex; - this.deltaTime = deltaTime; - this.input = input ?? RenderOutputInput.empty; - this.views = views ?? [view]; - this.sourceIds = sourceIds; - } - - /// - /// Gets the ordered host-selected content roots. - /// - public ContentReadScope content { get; } - - /// - /// Gets the stable host output session identity. - /// - public string sessionId { get; } - - /// - /// Gets the exact destination view. - /// - public RenderView view { get; } - - /// - /// Gets the monotonic output frame number. - /// - public ulong frameIndex { get; } - - /// - /// Gets elapsed time in seconds. - /// - public float deltaTime { get; } - /// - /// Gets frame-local input for this output. - /// - public RenderOutputInput input { get; } - /// - /// Gets every view in the same model output. - /// - public IReadOnlyList views { get; } - /// - /// Gets the exclusive source allowlist; null collects every active source. - /// - public IReadOnlyList? sourceIds { get; } -} - -/// -/// Prepares one model-independent drawable for a specific render pass. -/// -[Inno.Extensibility.Types.StableTypeId("796c6186-c301-5cb2-a634-d03f8156a039")] -public interface IViewDrawable -{ - /// - /// Resolves reusable resources before render graph execution. - /// - /// - /// Active pipeline build context. - /// - /// - /// View that will draw this item. - /// - /// - /// Prepared frame-local draw when resources are available. - /// - /// - /// Whether the drawable is ready for this pass. - /// - bool TryPrepare( - RenderPipelineContext context, - RenderView view, - out IPreparedViewDrawable? prepared - ); -} - -/// -/// Encodes a resource-ready draw into the owning model's scene pass. -/// -[Inno.Extensibility.Types.StableTypeId("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] -public interface IPreparedViewDrawable -{ - /// - /// Encodes commands while the owning model controls attachments and view state. - /// - /// - /// Backend-neutral scene pass encoder. - /// - void Encode(RenderCommandEncoder commands); -} - -/// -/// Receives pointer input after the rendering model resolves visible draw order. -/// -[Inno.Extensibility.Types.StableTypeId("8d770d54-025c-591a-b49e-9c12c4bde162")] -public interface IViewPointerTarget -{ - /// - /// Gets whether this target retains pointer ownership from an earlier press. - /// Rendering models route captured input before ordinary hit testing. - /// - bool hasPointerCapture { get; } - - /// - /// Gets whether keyboard and text input should continue reaching this target. - /// - bool hasKeyboardFocus { get; } - - /// - /// Changes keyboard focus after the rendering model resolves a pointer press. - /// - /// - /// Whether this target owns subsequent keyboard input. - /// - void SetKeyboardFocus(bool focused); - - /// - /// Maps one output pointer onto this item's local surface. - /// - /// - /// Exact rendered view. - /// - /// - /// Viewport-local input. - /// - /// - /// Local target coordinates when hit. - /// - /// - /// Whether this target is eligible to receive pointer input. - /// - bool TryHit( - RenderView view, - RenderOutputInput input, - out Vector2 localPosition - ); - - /// - /// Advances this target once for the frame with either routed input or an empty snapshot. - /// - /// - /// Routed viewport-local input, or an empty snapshot. - /// - /// - /// Target-local pointer coordinates. - /// - /// - /// Shared output frame index. - /// - void Advance( - RenderOutputInput input, - Vector2 localPosition, - ulong frameIndex - ); -} - -/// -/// One world item supplied to a rendering model without choosing its sort policy. -/// -[Inno.Extensibility.Types.StableTypeId("4aecd31e-d107-56b4-bc92-e07bc89c125b")] -public sealed class ViewContentItem -{ - /// - /// Creates an item whose lifetime is limited to the current frame. - /// - /// - /// Scene object identity used for model-owned sorting and visibility. - /// - /// - /// Exact transform of its local geometry. - /// - /// - /// Local minimum corner for conservative culling. - /// - /// - /// Local maximum corner for conservative culling. - /// - /// - /// Drawable inserted into the model's scene pass. - /// - /// - /// Optional input target routed by the rendering model. - /// - public ViewContentItem( - Identity owner, - Matrix localToWorld, - Vector3 localBoundsMin, - Vector3 localBoundsMax, - IViewDrawable drawable, - IViewPointerTarget? pointerTarget = null - ) { - this.owner = owner; - this.localToWorld = localToWorld; - this.localBoundsMin = localBoundsMin; - this.localBoundsMax = localBoundsMax; - this.drawable = drawable ?? throw new ArgumentNullException(nameof(drawable)); - this.pointerTarget = pointerTarget; - } - - /// - /// Gets the owner identity for model-owned sorting and visibility. - /// - public Identity owner { get; } - - /// - /// Gets the local-to-world transform. - /// - public Matrix localToWorld { get; } - - /// - /// Gets the local minimum corner. - /// - public Vector3 localBoundsMin { get; } - - /// - /// Gets the local maximum corner. - /// - public Vector3 localBoundsMax { get; } - - /// - /// Gets the drawable encoded by the selected rendering model. - /// - public IViewDrawable drawable { get; } - /// - /// Gets the optional pointer target associated with this draw item. - /// - public IViewPointerTarget? pointerTarget { get; } -} - -/// -/// Receives world items without imposing a rendering-model sort key. -/// -[Inno.Extensibility.Types.StableTypeId("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] -public interface IViewContentSink -{ - /// - /// Adds an item to the current view. - /// - /// - /// Frame-local content item. - /// - void Submit(ViewContentItem item); -} - -/// -/// Contributes model-independent world items to selected views. -/// -[Inno.Extensibility.Types.StableTypeId("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] -public interface IViewContentSource : IDisposable -{ - /// - /// Collects items for one exact view. - /// - /// - /// Frame-scoped host content and view. - /// - /// - /// Collector receiving items. - /// - void Collect( - ViewContentContext context, - IViewContentSink sink - ); -} - -/// -/// Completes frame-local input after every output has routed its views. -/// -[Inno.Extensibility.Types.StableTypeId("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] -public interface IViewContentFrameSource -{ - /// - /// Advances retained content once after all output views have supplied input. - /// - /// - /// The shared render frame whose input routing has completed. - /// - void CompleteFrame(ulong frameIndex); -} - -/// -/// Discovers an independently reloadable world-content source. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("9e766605-2b84-5040-858e-ae84b6a5e7c3")] -public sealed class ViewContentSourceExtensionAttribute : Attribute -{ - /// - /// Creates a source declaration with a stable identifier. - /// - /// - /// Globally stable source identifier. - /// - public ViewContentSourceExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the globally stable source identifier. - /// - public string id { get; } -} - -/// -/// Collects all active world-content sources for one exact view. -/// -[Inno.Extensibility.Types.StableTypeId("b8d46505-dda2-52b6-b3c8-133e48641fed")] -public interface IViewContentCollector -{ - /// - /// Collects active source items in deterministic source order. - /// - /// - /// Frame-scoped host content and view. - /// - /// - /// Frame-local items; the caller owns their sort and composition. - /// - IReadOnlyList Collect(ViewContentContext context); -} - -/// -/// Restricts a neutral world-content collector to an output layer's source IDs. -/// -[Inno.Extensibility.Types.StableTypeId("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] -public sealed class SelectedViewContentCollector : IViewContentCollector -{ - private readonly IViewContentCollector m_inner; - private readonly IReadOnlyList m_sourceIds; - - /// - /// Creates a collector that forwards only the selected source identities. - /// - /// - /// Active generation's source collector. - /// - /// - /// Source IDs exclusively assigned to this layer. - /// - public SelectedViewContentCollector( - IViewContentCollector inner, - IReadOnlyList sourceIds - ) { - m_inner = inner ?? throw new ArgumentNullException(nameof(inner)); - m_sourceIds = sourceIds ?? throw new ArgumentNullException(nameof(sourceIds)); - } - - /// - /// Collects only the assigned world-content sources for one exact view. - /// - /// - /// The original model view, output input, and frame timing. - /// - /// - /// Frame-local content emitted by the assigned sources. - /// - public IReadOnlyList Collect(ViewContentContext context) - { - ArgumentNullException.ThrowIfNull(context); - return m_inner.Collect(new ViewContentContext(context.content, context.sessionId, - context.view, context.frameIndex, context.deltaTime, context.input, - context.views, m_sourceIds)); - } -} - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs new file mode 100644 index 000000000..85f014125 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.References; + +namespace Inno.Rendering.Runtime; + +/// +/// Supplies one content source with the host-selected scene roots and an exact view. +/// +[StableTypeID("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] +public sealed class ViewContentContext +{ + /// + /// Creates a frame-scoped content collection context. + /// + /// + /// Ordered roots selected by the host. + /// + /// + /// Stable identity of the host output session. + /// + /// + /// Exact view that will consume the content. + /// + /// + /// Monotonic output frame number. + /// + /// + /// Elapsed frame time in seconds. + /// + /// + /// Pointer and keyboard input in output pixel coordinates. + /// + /// + /// All views in the same model output, used to choose shared content resolution. + /// + /// + /// Optional explicit source allowlist for a routed model layer. + /// + public ViewContentContext( + ContentReadScope content, + string sessionID, + RenderView view, + ulong frameIndex, + float deltaTime, + RenderOutputInput? input = null, + IReadOnlyList? views = null, + IReadOnlyList? sourceIDs = null + ) { + ArgumentNullException.ThrowIfNull(content); + this.content = content; + ArgumentException.ThrowIfNullOrWhiteSpace(sessionID); + this.sessionID = sessionID; + this.view = view; + this.frameIndex = frameIndex; + this.deltaTime = deltaTime; + this.input = input ?? RenderOutputInput.empty; + this.views = views ?? [view]; + this.sourceIDs = sourceIDs; + } + + /// + /// Gets the ordered host-selected content roots. + /// + public ContentReadScope content { get; } + + /// + /// Gets the stable host output session identity. + /// + public string sessionID { get; } + + /// + /// Gets the exact destination view. + /// + public RenderView view { get; } + + /// + /// Gets the monotonic output frame number. + /// + public ulong frameIndex { get; } + + /// + /// Gets elapsed time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets frame-local input for this output. + /// + public RenderOutputInput input { get; } + + /// + /// Gets every view in the same model output. + /// + public IReadOnlyList views { get; } + + /// + /// Gets the exclusive source allowlist; null collects every active source. + /// + public IReadOnlyList? sourceIDs { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs new file mode 100644 index 000000000..d9f6c9b3e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs @@ -0,0 +1,81 @@ +using System; +using Inno.Core.Identity; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// One world item supplied to a rendering model without choosing its sort policy. +/// +[StableTypeID("4aecd31e-d107-56b4-bc92-e07bc89c125b")] +public sealed class ViewContentItem +{ + /// + /// Creates an item whose lifetime is limited to the current frame. + /// + /// + /// Scene object identity used for model-owned sorting and visibility. + /// + /// + /// Exact transform of its local geometry. + /// + /// + /// Local minimum corner for conservative culling. + /// + /// + /// Local maximum corner for conservative culling. + /// + /// + /// Drawable inserted into the model's scene pass. + /// + /// + /// Optional input target routed by the rendering model. + /// + public ViewContentItem( + Identity owner, + Matrix localToWorld, + Vector3 localBoundsMin, + Vector3 localBoundsMax, + IViewDrawable drawable, + IViewPointerTarget? pointerTarget = null + ) { + ArgumentNullException.ThrowIfNull(drawable); + this.owner = owner; + this.localToWorld = localToWorld; + this.localBoundsMin = localBoundsMin; + this.localBoundsMax = localBoundsMax; + this.drawable = drawable; + this.pointerTarget = pointerTarget; + } + + /// + /// Gets the owner identity for model-owned sorting and visibility. + /// + public Identity owner { get; } + + /// + /// Gets the local-to-world transform. + /// + public Matrix localToWorld { get; } + + /// + /// Gets the local minimum corner. + /// + public Vector3 localBoundsMin { get; } + + /// + /// Gets the local maximum corner. + /// + public Vector3 localBoundsMax { get; } + + /// + /// Gets the drawable encoded by the selected rendering model. + /// + public IViewDrawable drawable { get; } + + /// + /// Gets the optional pointer target associated with this draw item. + /// + public IViewPointerTarget? pointerTarget { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs new file mode 100644 index 000000000..aa8342757 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs @@ -0,0 +1,29 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Discovers an independently reloadable world-content source. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[StableTypeID("9e766605-2b84-5040-858e-ae84b6a5e7c3")] +public sealed class ViewContentSourceExtensionAttribute : Attribute +{ + /// + /// Creates a source declaration with a stable identifier. + /// + /// + /// Globally stable source identifier. + /// + public ViewContentSourceExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the globally stable source identifier. + /// + public string id { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs index e8767bd30..1e5d178dd 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs @@ -1,15 +1,16 @@ +using System; using Inno.Assets; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; namespace Inno.Rendering.Runtime; /// /// Restores neutral render settings through the canonical asset's actual owner and pinned references. /// -[Inno.Extensibility.Types.StableTypeId("ad67f148-af5b-5383-ac2d-55a34e305e96")] +[StableTypeID("ad67f148-af5b-5383-ac2d-55a34e305e96")] public sealed class RenderExtensionStateContext { private readonly AssetObject m_owner; @@ -23,7 +24,11 @@ public sealed class RenderExtensionStateContext /// /// It must not outlive the asset generation. Authoring captures use the asset system's property snapshots. /// - public RenderExtensionStateContext(AssetObject owner) => m_owner = owner ?? throw new ArgumentNullException(nameof(owner)); + public RenderExtensionStateContext(AssetObject owner) + { + ArgumentNullException.ThrowIfNull(owner); + m_owner = owner; + } /// /// Restores a matching settings contract with this owner's asset references. @@ -46,4 +51,3 @@ TSettings target m_owner.RestoreProperties(state.stableTypeId, state.propertyData, target); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs index 670388089..0a0f21f3e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs @@ -1,17 +1,18 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Supplies one configured feature with frame-scoped graph services. /// -[Inno.Extensibility.Types.StableTypeId("00810cb8-162a-5a95-9a30-1a01992ac501")] +[StableTypeID("00810cb8-162a-5a95-9a30-1a01992ac501")] public sealed class RenderFeatureContext { /// @@ -27,7 +28,8 @@ public RenderFeatureContext( RenderPipelineContext pipeline, RenderFeatureConfiguration configuration ) { - this.pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); + ArgumentNullException.ThrowIfNull(pipeline); + this.pipeline = pipeline; this.configuration = configuration; } @@ -66,4 +68,3 @@ RenderFeatureConfiguration configuration /// public IRenderFrameUploadService uploads => pipeline.uploads; } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs index 70466bddc..f427a70b6 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs @@ -1,10 +1,11 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable pipeline feature implementation with a stable extension identifier. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("f290f8ca-3a8b-5e90-aa2d-1b0a541cd95a")] +[StableTypeID("f290f8ca-3a8b-5e90-aa2d-1b0a541cd95a")] public sealed class RenderFeatureExtensionAttribute : Attribute { /// @@ -32,4 +33,3 @@ public RenderFeatureExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs index 647284a4a..2aac16a41 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs @@ -1,17 +1,18 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Builds frame-local passes without prescribing a rendering model. /// -[Inno.Extensibility.Types.StableTypeId("f3736feb-4238-54b6-9fe9-c40ffb095134")] +[StableTypeID("f3736feb-4238-54b6-9fe9-c40ffb095134")] public abstract class RenderPipeline : IDisposable { private bool m_disposed; @@ -50,7 +51,9 @@ RenderExtensionStateContext settings public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -80,7 +83,7 @@ public void Dispose() protected virtual void OnConfigure( SerializedRenderExtensionState state, RenderExtensionStateContext settings - ) { } + ) {} /// /// Releases managed generation-scoped state. @@ -91,6 +94,5 @@ RenderExtensionStateContext settings /// /// Retirement cannot complete yet; subsequent calls resume this hook with its remaining owned resources. /// - protected virtual void Dispose(bool disposing) { } + protected virtual void Dispose(bool disposing) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs index 3649800eb..fc60c5d38 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs @@ -1,17 +1,18 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Supplies one request and frame-scoped services to a render pipeline. /// -[Inno.Extensibility.Types.StableTypeId("fe6c1616-212d-521e-b4ab-9e61a72b9c45")] +[StableTypeID("fe6c1616-212d-521e-b4ab-9e61a72b9c45")] public sealed class RenderPipelineContext { /// @@ -142,4 +143,3 @@ public RenderPipelineContext( /// public RenderTextureHandle outputTexture { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs index df2def25a..a101479dc 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs @@ -1,10 +1,11 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable render pipeline implementation with a stable extension identifier. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("bbaa3835-1ee7-5e0f-b690-304d4f6f98ed")] +[StableTypeID("bbaa3835-1ee7-5e0f-b690-304d4f6f98ed")] public sealed class RenderPipelineExtensionAttribute : Attribute { /// @@ -32,4 +33,3 @@ public RenderPipelineExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs index 4e0e2a66e..880d4a7ec 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs @@ -1,17 +1,18 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Adds capability-aware passes without owning frame graph state. /// -[Inno.Extensibility.Types.StableTypeId("a16b9e1e-2bf1-5ba4-85aa-ee24ebda097b")] +[StableTypeID("a16b9e1e-2bf1-5ba4-85aa-ee24ebda097b")] public abstract class RenderPipelineFeature { /// @@ -51,6 +52,5 @@ RenderExtensionStateContext settings protected virtual void OnConfigure( SerializedRenderExtensionState state, RenderExtensionStateContext settings - ) { } + ) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs index f1542b420..e09e62cf4 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs @@ -1,21 +1,22 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; /// /// Stores open semantic graph resources for one pipeline request. /// -[Inno.Extensibility.Types.StableTypeId("f48ab8a3-a1f2-513a-9e4b-396be0f084a8")] +[StableTypeID("f48ab8a3-a1f2-513a-9e4b-396be0f084a8")] public sealed class RenderResourceMap { - private readonly Dictionary m_textures = []; - private readonly Dictionary m_buffers = []; + private readonly Dictionary m_textures = []; + private readonly Dictionary m_buffers = []; /// /// Publishes a texture under a pipeline-defined semantic identifier. @@ -27,13 +28,17 @@ public sealed class RenderResourceMap /// Valid current-graph texture. /// public void PublishTexture( - RenderResourceId id, + RenderResourceID id, RenderTextureHandle texture ) { if (!id.isValid) + { throw new ArgumentException("A render resource identifier must be valid.", nameof(id)); + } if (!texture.isValid) + { throw new ArgumentException("A published texture must be valid.", nameof(texture)); + } m_textures[id] = texture; } @@ -47,13 +52,17 @@ RenderTextureHandle texture /// Valid current-graph buffer. /// public void PublishBuffer( - RenderResourceId id, + RenderResourceID id, RenderBufferHandle buffer ) { if (!id.isValid) + { throw new ArgumentException("A render resource identifier must be valid.", nameof(id)); + } if (!buffer.isValid) + { throw new ArgumentException("A published buffer must be valid.", nameof(buffer)); + } m_buffers[id] = buffer; } @@ -70,7 +79,7 @@ RenderBufferHandle buffer /// when the texture has been published. /// public bool TryGetTexture( - RenderResourceId id, + RenderResourceID id, out RenderTextureHandle texture ) => m_textures.TryGetValue(id, out texture); @@ -87,8 +96,7 @@ out RenderTextureHandle texture /// when the buffer has been published. /// public bool TryGetBuffer( - RenderResourceId id, + RenderResourceID id, out RenderBufferHandle buffer ) => m_buffers.TryGetValue(id, out buffer); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Properties/ScriptingApi.cs b/src/services/rendering/Inno.Rendering.Runtime/Properties/ScriptingApi.cs index 491bbbc4e..d91332f4d 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Properties/ScriptingApi.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Properties/ScriptingApi.cs @@ -29,7 +29,7 @@ [assembly: ScriptingApiExport(typeof(ViewContentSourceExtensionAttribute), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(IViewContentCollector), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(SelectedViewContentCollector), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(RenderPersistentResourceId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(RenderPersistentResourceID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderTextureSubresourceData), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderGeometrySection), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderGeometry), ScriptingApiScope.Runtime)] diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderContributorSnapshot.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderContributorSnapshot.cs index 0ffbfa0a7..cef59a8de 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderContributorSnapshot.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderContributorSnapshot.cs @@ -6,7 +6,7 @@ namespace Inno.Rendering.Runtime; internal sealed class RenderContributorSnapshot { - internal static readonly RenderContributorSnapshot empty = new([]); + internal static readonly RenderContributorSnapshot EMPTY = new([]); internal RenderContributorSnapshot(IReadOnlyList contributors) { diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs index d4b0bf5af..32252351d 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; @@ -15,33 +16,10 @@ internal sealed class RenderExtensionRegistry : TypeRegistry current; - internal void Retire(IDisposable? resource) - { - try - { - if (resource is not null) - RetireResource("render generation", resource.Dispose); - } - catch (Exception exception) - { - m_retirementFailure ??= exception; - ReportRetirementFailure(exception); - throw; - } - } - - internal void EnsureHealthy() - { - if (m_retirementFailure is not null) - throw new InvalidOperationException("The rendering generation owner is Faulted and requires a host restart.", m_retirementFailure); - } - /// /// Revokes rendering admission after the shared registry reports a terminal cleanup failure. /// @@ -54,9 +32,7 @@ internal void EnsureHealthy() protected override void OnCleanupFailed( string phase, Exception exception - ) { - m_retirementFailure ??= exception; - } + ) => m_retirementFailure ??= exception; /// /// Builds a validated result from the current immutable input snapshot. @@ -73,36 +49,68 @@ protected override Snapshot Build(TypeCacheSnapshot types) Dictionary pipelines = Discover( types, static attribute => attribute.id, - "render pipeline"); + "render pipeline" + ); Dictionary features = Discover( types, static attribute => attribute.id, - "render feature"); + "render feature" + ); Dictionary requestProviders = Discover< RenderRequestProviderExtensionAttribute, - RenderRequestProvider>( - types, - static attribute => attribute.id, - "render request provider"); + RenderRequestProvider>(types, static attribute => attribute.id, "render request provider"); Dictionary contentSources = Discover< ViewContentSourceExtensionAttribute, - IViewContentSource>( - types, - static attribute => attribute.id, - "view content source"); + IViewContentSource>(types, static attribute => attribute.id, "view content source"); Dictionary renderModels = Discover< - RenderModelExtensionAttribute, IRenderModel>(types, - static attribute => attribute.id, "render model"); - return new Snapshot(types, pipelines, features, requestProviders, contentSources, renderModels, - CreateExtension, CreateExtension, - CreateExtension, Retire); + RenderModelExtensionAttribute, IRenderModel>(types, static attribute => attribute.id, "render model"); + return new Snapshot( + types, + pipelines, + features, + requestProviders, + contentSources, + renderModels, + CreateExtension, + CreateExtension, + CreateExtension, + Retire + ); + } + + internal void Retire(IDisposable? resource) + { + try + { + if (resource is not null) + { + RetireResource("render generation", resource.Dispose); + } + } + catch (Exception exception) + { + m_retirementFailure ??= exception; + ReportRetirementFailure(exception); + throw; + } + } + + internal void EnsureHealthy() + { + if (m_retirementFailure is not null) + { + throw new InvalidOperationException( + "The rendering generation owner is Faulted and requires a host restart.", + m_retirementFailure + ); + } } internal static string GetConfigurationFingerprint(RenderPipelineAsset asset) { ArgumentNullException.ThrowIfNull(asset); - using var stream = new System.IO.MemoryStream(); - using var writer = new System.IO.BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(asset.pipelineTypeId ?? string.Empty); WriteState(writer, asset.pipelineState); foreach (RenderFeatureConfiguration feature in asset.features) @@ -116,7 +124,7 @@ internal static string GetConfigurationFingerprint(RenderPipelineAsset asset) } private static void WriteState( - System.IO.BinaryWriter writer, + BinaryWriter writer, SerializedRenderExtensionState state ) { writer.Write(state.stableTypeId.ToByteArray()); @@ -127,10 +135,9 @@ SerializedRenderExtensionState state private static Dictionary Discover( TypeCacheSnapshot types, - Func getId, + Func getID, string kind - ) - where TAttribute : Attribute + ) where TAttribute : Attribute { var result = new Dictionary(StringComparer.Ordinal); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) @@ -139,22 +146,25 @@ string kind if (type.IsAbstract || !typeof(TContract).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Reloadable {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}."); + $"Reloadable {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Reloadable {kind} '{type.FullName}' requires a parameterless constructor."); + $"Reloadable {kind} '{type.FullName}' requires a parameterless constructor." + ); } TAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; - string id = getId(attribute); + string id = getID(attribute); if (!result.TryAdd(id, type)) { throw new InvalidOperationException( - $"Reloadable {kind} ID '{id}' is declared by both " + - $"'{result[id].FullName}' and '{type.FullName}'."); + $"Reloadable {kind} ID '{id}' is declared by both " + + $"'{result[id].FullName}' and '{type.FullName}'." + ); } } @@ -163,13 +173,13 @@ string kind internal sealed class Snapshot : IDisposable { - private TypeCacheSnapshot? m_types; private readonly IReadOnlyDictionary m_pipelines; private readonly IReadOnlyDictionary m_features; private readonly IReadOnlyDictionary m_requestProviders; private readonly IReadOnlyDictionary m_contentSources; private readonly IReadOnlyDictionary m_renderModels; private readonly Action m_retire; + private TypeCacheSnapshot? m_types; internal Snapshot( TypeCacheSnapshot types, @@ -184,25 +194,18 @@ internal Snapshot( Action retire ) { m_types = types; - typeCacheVersion = types.version; + this.typeCacheVersion = types.version; m_pipelines = pipelines; m_features = features; m_requestProviders = requestProviders; m_contentSources = contentSources; m_renderModels = renderModels; m_retire = retire; - providers = CreateRequestProviders(createProvider); - sources = CreateContentSources(createSource); - models = CreateRenderModels(createModel); + this.providers = CreateRequestProviders(createProvider); + this.sources = CreateContentSources(createSource); + this.models = CreateRenderModels(createModel); } - internal long typeCacheVersion { get; } - - internal RequestProviderGeneration providers { get; } - - internal ContentSourceGeneration sources { get; } - internal RenderModelGeneration models { get; } - /// /// Releases providers when their owning type snapshot retires. /// @@ -214,41 +217,12 @@ public void Dispose() m_types = null; } - private ContentSourceGeneration CreateContentSources(Func createSource) - { - var sources = new List(m_contentSources.Count); - foreach ((string id, Type type) in m_contentSources.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - sources.Add(new ContentSourceEntry(id, createSource(type))); - return new ContentSourceGeneration(typeCacheVersion, sources); - } + internal long typeCacheVersion { get; } - private RenderModelGeneration CreateRenderModels(Func createModel) - { - var models = new List(m_renderModels.Count); - foreach ((string id, Type type) in m_renderModels.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - models.Add(new RenderModelEntry(id, createModel(type))); - return new RenderModelGeneration(typeCacheVersion, models); - } + internal RequestProviderGeneration providers { get; } - private RequestProviderGeneration CreateRequestProviders(Func createProvider) - { - var providers = new List(m_requestProviders.Count); - foreach ((string id, Type type) in m_requestProviders) - { - RenderRequestProviderExtensionAttribute attribute = - m_types!.GetAttribute(m_types.GetTypeRef(type), inherit: false)!; - providers.Add(new RequestProviderEntry(id, attribute.priority, createProvider(type))); - } - providers.Sort(static ( - left, - right - ) => - { - int priority = left.priority.CompareTo(right.priority); - return priority != 0 ? priority : string.CompareOrdinal(left.id, right.id); - }); - return new RequestProviderGeneration(typeCacheVersion, providers); - } + internal ContentSourceGeneration sources { get; } + internal RenderModelGeneration models { get; } internal bool TryCreateGeneration( RenderPipelineAsset asset, @@ -256,7 +230,9 @@ out RenderPipelineGeneration? generation ) { ArgumentNullException.ThrowIfNull(asset); if (string.IsNullOrWhiteSpace(asset.pipelineTypeId)) + { throw new InvalidOperationException("A render pipeline asset requires a stable pipeline extension ID."); + } if (!m_pipelines.TryGetValue(asset.pipelineTypeId, out Type? pipelineType)) { generation = null; @@ -267,13 +243,18 @@ out RenderPipelineGeneration? generation foreach (RenderFeatureConfiguration configuration in asset.features) { if (!configuration.enabled) + { continue; + } if (string.IsNullOrWhiteSpace(configuration.featureTypeId)) + { throw new InvalidOperationException("An enabled render feature requires a stable extension ID."); + } if (featureTypes.ContainsKey(configuration.featureTypeId)) { throw new InvalidOperationException( - $"Render feature '{configuration.featureTypeId}' is configured more than once."); + $"Render feature '{configuration.featureTypeId}' is configured more than once." + ); } if (!m_features.TryGetValue(configuration.featureTypeId, out Type? featureType)) { @@ -289,10 +270,11 @@ out RenderPipelineGeneration? generation var settings = new RenderExtensionStateContext(asset); candidate.pipeline.Configure(asset.pipelineState, settings); foreach (RenderFeatureConfiguration configuration in asset.features.Where( - static value => value.enabled)) - { + static value => value.enabled + )) { RenderPipelineFeature feature = Create( - featureTypes[configuration.featureTypeId]); + featureTypes[configuration.featureTypeId] + ); candidate.AddFeature(configuration.featureTypeId, feature); feature.Configure(configuration, settings); } @@ -318,7 +300,50 @@ out RenderPipelineGeneration? generation } } - private TContract Create(Type type) where TContract : class + private ContentSourceGeneration CreateContentSources(Func createSource) + { + var sources = new List(m_contentSources.Count); + foreach ((string id, Type type) in m_contentSources.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { + sources.Add(new ContentSourceEntry(id, createSource(type))); + } + return new ContentSourceGeneration(typeCacheVersion, sources); + } + + private RenderModelGeneration CreateRenderModels(Func createModel) + { + var models = new List(m_renderModels.Count); + foreach ((string id, Type type) in m_renderModels.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { + models.Add(new RenderModelEntry(id, createModel(type))); + } + return new RenderModelGeneration(typeCacheVersion, models); + } + + private RequestProviderGeneration CreateRequestProviders(Func createProvider) + { + var providers = new List(m_requestProviders.Count); + foreach ((string id, Type type) in m_requestProviders) + { + RenderRequestProviderExtensionAttribute attribute = m_types!.GetAttribute( + m_types.GetTypeRef(type), + inherit: false + )!; + providers.Add(new RequestProviderEntry(id, attribute.priority, createProvider(type))); + } + providers.Sort(static ( + left, + right + ) => + { + int priority = left.priority.CompareTo(right.priority); + return priority != 0 ? priority : string.CompareOrdinal(left.id, right.id); + }); + return new RequestProviderGeneration(typeCacheVersion, providers); + } + + private TContract Create(Type type) + where TContract : class { try { @@ -328,15 +353,16 @@ private TContract Create(Type type) where TContract : class { throw new InvalidOperationException( $"Rendering extension '{type.FullName}' could not be activated.", - exception); + exception + ); } } } internal sealed class RequestProviderGeneration : IDisposable { - private IReadOnlyList m_providers; private readonly LifetimeScope m_lifetime = new(); + private IReadOnlyList m_providers; internal RequestProviderGeneration( long typeCacheVersion, @@ -345,13 +371,11 @@ IReadOnlyList providers this.typeCacheVersion = typeCacheVersion; m_providers = Array.AsReadOnly(providers.ToArray()); foreach (RequestProviderEntry entry in m_providers) + { m_lifetime.Own(entry.provider); + } } - internal long typeCacheVersion { get; } - - internal IReadOnlyList providers => m_providers; - /// /// Releases the resources owned by this instance. /// @@ -367,11 +391,15 @@ public void Dispose() } catch { - m_providers = Array.Empty(); + m_providers = []; throw; } - m_providers = Array.Empty(); + m_providers = []; } + + internal long typeCacheVersion { get; } + + internal IReadOnlyList providers => m_providers; } internal sealed record RequestProviderEntry( @@ -392,21 +420,23 @@ IReadOnlyList sources this.typeCacheVersion = typeCacheVersion; m_sources = Array.AsReadOnly(sources.ToArray()); foreach (ContentSourceEntry entry in m_sources) + { m_lifetime.Own(entry.source); + } } - internal long typeCacheVersion { get; } - - internal IReadOnlyList sources => m_sources; - /// /// Releases the resources owned by this instance. /// public void Dispose() { m_lifetime.Dispose(); - m_sources = Array.Empty(); + m_sources = []; } + + internal long typeCacheVersion { get; } + + internal IReadOnlyList sources => m_sources; } internal sealed record ContentSourceEntry( @@ -426,25 +456,26 @@ IReadOnlyList models this.typeCacheVersion = typeCacheVersion; m_models = Array.AsReadOnly(models.ToArray()); foreach (RenderModelEntry entry in m_models) + { m_lifetime.Own(entry.model); + } } - internal long typeCacheVersion { get; } - internal IReadOnlyList models => m_models; - /// /// Releases the resources owned by this instance. /// public void Dispose() { m_lifetime.Dispose(); - m_models = Array.Empty(); + m_models = []; } + + internal long typeCacheVersion { get; } + internal IReadOnlyList models => m_models; } internal sealed record RenderModelEntry( string id, IRenderModel model ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs index 87a883182..33093b1ff 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs @@ -1,4 +1,5 @@ using System; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -6,7 +7,7 @@ namespace Inno.Rendering.Runtime; /// /// Reports read-only statistics for the most recently completed render frame. /// -[Inno.Extensibility.Types.StableTypeId("f3924117-1829-5885-9f93-9010066fed48")] +[StableTypeID("f3924117-1829-5885-9f93-9010066fed48")] public sealed class RenderFrameStatistics { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs index 91db02b8a..76e87ea1f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs @@ -1,8 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Linq; - +using Inno.Core.Execution; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -14,13 +13,13 @@ internal sealed class RenderFrameUploadService : RenderFrameUploadProvider, IRen private readonly IRenderDevice m_device; private readonly RenderResourceLimits m_limits; + private readonly Dictionary m_pools = []; private RenderRetirementQueue? m_sweep; private int m_pageCount; private long m_residentBytes; private long m_frameBytes; private long m_peakResidentBytes; private long m_rejected; - private readonly Dictionary m_pools = []; private ulong m_frameIndex; private bool m_frameOpen; private bool m_disposed; @@ -30,7 +29,8 @@ internal RenderFrameUploadService( IRenderDevice device, RenderResourceLimits limits ) { - m_device = device ?? throw new ArgumentNullException(nameof(device)); + ArgumentNullException.ThrowIfNull(device); + m_device = device; m_limits = limits; } @@ -56,14 +56,14 @@ string name ) { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); if (!m_frameOpen) + { throw new InvalidOperationException("Frame uploads are only accepted during an open render frame."); + } ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (data.IsEmpty || data.Length % descriptor.elementStride != 0) { - throw new ArgumentException( - "Upload data must contain one or more complete elements.", - nameof(data)); + throw new ArgumentException("Upload data must contain one or more complete elements.", nameof(data)); } DrainSweep(); @@ -77,7 +77,8 @@ string name descriptor.elementStride, descriptor.usage, descriptor.vertexLayout, - descriptor.indexFormat); + descriptor.indexFormat + ); if (!m_pools.TryGetValue(key, out UploadPool? pool)) { pool = new UploadPool(); @@ -85,10 +86,8 @@ string name bool requiresDedicatedPage = (descriptor.usage & RenderBufferUsage.Storage) != 0; UploadPage? page = requiresDedicatedPage - ? pool.pages.FirstOrDefault(candidate => - !candidate.usedThisFrame && candidate.capacity >= elementCount) - : pool.pages.FirstOrDefault(candidate => - candidate.capacity - candidate.writeOffset >= elementCount); + ? pool.pages.FirstOrDefault(candidate => !candidate.usedThisFrame && candidate.capacity >= elementCount) + : pool.pages.FirstOrDefault(candidate => candidate.capacity - candidate.writeOffset >= elementCount); if (page is null) { int capacity = NextPowerOfTwo(Math.Max(C_MINIMUM_PAGE_ELEMENTS, elementCount)); @@ -102,11 +101,13 @@ string name var bufferDescriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, descriptor.elementStride, usage), descriptor.vertexLayout, - descriptor.indexFormat); + descriptor.indexFormat + ); PersistentBufferHandle handle = m_device.CreateBuffer( bufferDescriptor, - ReadOnlySpan.Empty, - $"{name}/FrameUpload[{pool.pages.Count}]"); + [], + $"{name}/FrameUpload[{pool.pages.Count}]" + ); page = new UploadPage(handle, capacity, bytes); pool.pages.Add(page); m_pools[key] = pool; @@ -121,14 +122,59 @@ string name page.writeOffset = checked(firstElement + elementCount); page.usedThisFrame = true; page.lastUsedFrame = m_frameIndex; - return CreateBufferSlice( - page.handle, - firstElement, - elementCount, - descriptor.usage, - m_frameIndex); + return CreateBufferSlice(page.handle, firstElement, elementCount, descriptor.usage, m_frameIndex); } + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_frameOpen = false; + if (m_retirement is null) + { + m_retirement = new RenderRetirementQueue(); + if (m_sweep is not null) + { + m_retirement.Add(m_sweep.Dispose); + } + foreach (UploadPage page in m_pools.Values.SelectMany(static pool => pool.pages)) + { + m_retirement.Add(() => m_device.DestroyBuffer(page.handle)); + } + } + try + { + m_retirement.Dispose(); + } + catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) + { + throw; + } + catch + { + m_pools.Clear(); + m_residentBytes = 0; + m_pageCount = 0; + m_disposed = true; + throw; + } + m_pools.Clear(); + m_residentBytes = 0; + m_pageCount = 0; + m_disposed = true; + } + + internal int pageCount => m_pageCount; + internal long residentBytes => m_residentBytes; + internal long peakResidentBytes => m_peakResidentBytes; + internal long frameBytes => m_frameBytes; + internal long rejectedCount => m_rejected; + internal void BeginFrame(ulong frameIndex) { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); @@ -146,23 +192,27 @@ internal void BeginFrame(ulong frameIndex) internal void EndFrame() { if (!m_disposed) + { m_frameOpen = false; + } } internal void SweepUnused() { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); if (m_frameIndex < C_UNUSED_FRAME_LIMIT) + { return; + } DrainSweep(); ulong oldest = m_frameIndex - C_UNUSED_FRAME_LIMIT; foreach (UploadPageKey key in m_pools.Keys.ToArray()) { UploadPool pool = m_pools[key]; foreach (UploadPage page in pool.pages - .Where(candidate => candidate.lastUsedFrame < oldest) - .ToArray()) - { + .Where(candidate => candidate.lastUsedFrame < oldest) + .ToArray() + ) { m_sweep ??= new RenderRetirementQueue(); m_sweep.Add(() => m_device.DestroyBuffer(page.handle)); m_sweep.Add(() => @@ -173,59 +223,19 @@ internal void SweepUnused() pool.pages.Remove(page); } if (pool.pages.Count == 0) + { m_pools.Remove(key); + } } DrainSweep(); } - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - return; - m_frameOpen = false; - if (m_retirement is null) - { - m_retirement = new RenderRetirementQueue(); - if (m_sweep is not null) - m_retirement.Add(m_sweep.Dispose); - foreach (UploadPage page in m_pools.Values.SelectMany(static pool => pool.pages)) - m_retirement.Add(() => m_device.DestroyBuffer(page.handle)); - } - try - { - m_retirement.Dispose(); - } - catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) - { - throw; - } - catch - { - m_pools.Clear(); - m_residentBytes = 0; - m_pageCount = 0; - m_disposed = true; - throw; - } - m_pools.Clear(); - m_residentBytes = 0; - m_pageCount = 0; - m_disposed = true; - } - - internal int pageCount => m_pageCount; - internal long residentBytes => m_residentBytes; - internal long peakResidentBytes => m_peakResidentBytes; - internal long frameBytes => m_frameBytes; - internal long rejectedCount => m_rejected; - private void DrainSweep() { if (m_sweep is null) + { return; + } try { m_sweep.Dispose(); @@ -246,7 +256,9 @@ private static int NextPowerOfTwo(int value) { int result = 1; while (result < value) + { result = checked(result * 2); + } return result; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs index b4b9f17c3..40896ee7e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs @@ -28,7 +28,25 @@ int capacity m_entries = new(entry => entry.retirement.Dispose(), capacity); } - internal int count => m_entries.Count; + /// + /// Releases the resources owned by this implementation. + /// + public void Dispose() + { + if (m_retirement is null) + { + m_retirement = new RenderRetirementQueue(); + if (m_allocation is not null) + { + m_retirement.Add(m_allocation.Dispose); + } + m_retirement.Add(m_entries.Dispose); + } + m_retirement.Dispose(); + m_allocation = null; + } + + internal int count => m_entries.count; internal int retiringCount => m_entries.pendingCount; internal long rejectedCount => m_entries.rejectedCount; @@ -58,12 +76,18 @@ out RenderGeometry? geometry Drain(); ArgumentNullException.ThrowIfNull(asset); geometry = null; - Guid id = asset.identity.persistentId; + Guid id = asset.identity.persistentID; string source = asset.assetPath.ToString(); if (id == Guid.Empty) { - m_diagnostics.Publish(new Diagnostic("RENDER_GEOMETRY_ID_MISSING", - "Geometry must have a persistent asset identity.", DiagnosticSeverity.Error, source)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_GEOMETRY_ID_MISSING", + "Geometry must have a persistent asset identity.", + DiagnosticSeverity.Error, + source + ) + ); return false; } m_diagnostics.Resolve("RENDER_GEOMETRY_ID_MISSING", source); @@ -82,11 +106,18 @@ out RenderGeometry? geometry } catch (Exception failure) { - m_diagnostics.Publish(new Diagnostic("RENDER_GEOMETRY_RESOLVE_FAILED", - $"Geometry '{source}' kept its complete last-good buffer pair: {failure.Message}", - DiagnosticSeverity.Error, source)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_GEOMETRY_RESOLVE_FAILED", + $"Geometry '{source}' kept its complete last-good buffer pair: {failure.Message}", + DiagnosticSeverity.Error, + source + ) + ); if (entry is null) + { return false; + } entry.lastUsedFrame = m_frameIndex; geometry = entry.geometry; return true; @@ -101,43 +132,43 @@ out RenderGeometry? geometry return true; } - /// - /// Releases the resources owned by this implementation. - /// - public void Dispose() - { - if (m_retirement is null) - { - m_retirement = new RenderRetirementQueue(); - if (m_allocation is not null) - m_retirement.Add(m_allocation.Dispose); - m_retirement.Add(m_entries.Dispose); - } - m_retirement.Dispose(); - m_allocation = null; - } - private Entry Create(GeometryAsset asset) { GeometryData data = GeometryAssetRuntime.GetGeometryData(asset); RenderVertexLayout layout = CanonicalGeometryLayout(); byte[] vertices = PackVertices(data.vertices); byte[] indices = MemoryMarshal.AsBytes(data.indices.ToArray().AsSpan()).ToArray(); - IReadOnlyList sections = Array.AsReadOnly(data.sections.Select(static section => - new RenderGeometrySection(section.firstIndex, section.indexCount)).ToArray()); + IReadOnlyList sections = Array.AsReadOnly( + data.sections.Select(static section => + new RenderGeometrySection(section.firstIndex, section.indexCount)).ToArray() + ); m_allocation = new RenderRetirementQueue(); try { - PersistentBufferHandle vertex = m_device.CreateBuffer(new PersistentBufferDescriptor( - new RenderBufferDescriptor(data.vertices.Count, layout.stride, RenderBufferUsage.Vertex), layout), - vertices, $"{asset.name}/Vertices"); + PersistentBufferHandle vertex = m_device.CreateBuffer( + new PersistentBufferDescriptor( + new RenderBufferDescriptor(data.vertices.Count, layout.stride, RenderBufferUsage.Vertex), + layout + ), + vertices, + $"{asset.name}/Vertices" + ); m_allocation.Add(() => m_device.DestroyBuffer(vertex)); - PersistentBufferHandle index = m_device.CreateBuffer(new PersistentBufferDescriptor( - new RenderBufferDescriptor(data.indices.Count, sizeof(uint), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt32), indices, $"{asset.name}/Indices"); + PersistentBufferHandle index = m_device.CreateBuffer( + new PersistentBufferDescriptor( + new RenderBufferDescriptor(data.indices.Count, sizeof(uint), RenderBufferUsage.Index), + indexFormat: RenderIndexFormat.UInt32 + ), + indices, + $"{asset.name}/Indices" + ); m_allocation.Add(() => m_device.DestroyBuffer(index)); - var entry = new Entry(CreateGeometry(vertex, index, layout, data.vertices.Count, - data.indices.Count, sections), asset.contentVersion, m_frameIndex, m_allocation); + var entry = new Entry( + CreateGeometry(vertex, index, layout, data.vertices.Count, data.indices.Count, sections), + asset.contentVersion, + m_frameIndex, + m_allocation + ); m_allocation = null; return entry; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs index a6eeeb5f7..3d1fb4894 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs @@ -10,21 +10,24 @@ namespace Inno.Rendering.Runtime; /// internal sealed class RenderLayerCompositor : IDisposable { - private static readonly RenderPhaseId S_PHASE = new("inno.runtime.model-composition"); - private static readonly RenderBindingId S_TEXTURE = new("s_tex"); - private static readonly float[] S_IDENTITY = + private static readonly RenderPhaseID PHASE = new("inno.runtime.model-composition"); + private static readonly RenderBindingID TEXTURE = new("s_tex"); + + private static readonly float[] IDENTITY = [ 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ]; - private static readonly RenderVertexLayout S_VERTEX_LAYOUT = new( - [ - new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + + private static readonly RenderVertexLayout VERTEX_LAYOUT = new( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); private readonly IRenderDevice m_device; private readonly IRenderLayerCompositionProgramProvider? m_programProvider; @@ -38,10 +41,43 @@ internal RenderLayerCompositor( IRenderDevice device, IRenderLayerCompositionProgramProvider? programProvider ) { - m_device = device ?? throw new ArgumentNullException(nameof(device)); + ArgumentNullException.ThrowIfNull(device); + m_device = device; m_programProvider = programProvider; } + /// + /// Releases the engine-owned shader pipeline and fullscreen quad buffers. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + if (m_indices.isValid) + { + m_device.DestroyBuffer(m_indices); + } + if (m_vertices.isValid) + { + m_device.DestroyBuffer(m_vertices); + } + if (m_pipeline.isValid) + { + m_device.DestroyGraphicsPipeline(m_pipeline); + } + if (m_outputTransferPipeline.isValid) + { + m_device.DestroyGraphicsPipeline(m_outputTransferPipeline); + } + m_indices = default; + m_vertices = default; + m_pipeline = default; + m_outputTransferPipeline = default; + m_disposed = true; + } + internal void AddPasses( RenderGraphBuilder graph, string name, @@ -55,11 +91,15 @@ RenderTextureFormat layerFormat ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(layers); if (layers.Count == 0) + { throw new ArgumentException("Composition requires at least one layer.", nameof(layers)); + } EnsureResources(); bool needsOutputTransfer = !output.isValid && !m_device.primaryPresentationEncodesSrgb; if (needsOutputTransfer) + { EnsureOutputTransferPipeline(); + } if (needsOutputTransfer && layers.Count == 1) { AddOutputTransfer(graph, name, layers[0], viewport); @@ -75,91 +115,92 @@ RenderTextureFormat layerFormat viewport.width, viewport.height, layerFormat, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); compositionViewport = new RenderViewport(0, 0, viewport.width, viewport.height); } for (int index = 0; index < layers.Count; index++) { if (!layers[index].isValid) + { throw new ArgumentException("Composition contains an invalid layer.", nameof(layers)); + } var data = new PassData(m_pipeline, m_vertices, m_indices, layers[index], compositionViewport); RasterPassBuilder pass = graph.AddRasterPass( - $"{name}/Layer {index + 1}", S_PHASE, data, + $"{name}/Layer {index + 1}", + PHASE, + data, static ( value, context - ) => DrawFullscreen(value, context)); - pass.SetViewTransform(S_IDENTITY, S_IDENTITY); + ) => DrawFullscreen(value, context) + ); + pass.SetViewTransform(IDENTITY, IDENTITY); pass.ReadTexture(layers[index]); if (compositionTarget.isValid) { - pass.UseColorAttachment(compositionTarget, 0, + pass.UseColorAttachment( + compositionTarget, + 0, index == 0 ? RenderLoadAction.Clear : RenderLoadAction.Load, - RenderStoreAction.Store, default); + RenderStoreAction.Store, + default + ); } else { if (index == 0) + { pass.ClearPresentationTarget(default); + } pass.HasSideEffect(); } } if (needsOutputTransfer) + { AddOutputTransfer(graph, name, compositionTarget, viewport); - } - - /// - /// Releases the engine-owned shader pipeline and fullscreen quad buffers. - /// - public void Dispose() - { - if (m_disposed) - return; - if (m_indices.isValid) - m_device.DestroyBuffer(m_indices); - if (m_vertices.isValid) - m_device.DestroyBuffer(m_vertices); - if (m_pipeline.isValid) - m_device.DestroyGraphicsPipeline(m_pipeline); - if (m_outputTransferPipeline.isValid) - m_device.DestroyGraphicsPipeline(m_outputTransferPipeline); - m_indices = default; - m_vertices = default; - m_pipeline = default; - m_outputTransferPipeline = default; - m_disposed = true; + } } private void EnsureResources() { if (m_pipeline.isValid) + { return; + } IRenderLayerCompositionProgramProvider provider = m_programProvider ?? throw new InvalidOperationException("The rendering host has no layer composition program provider."); - GraphicsPipelineDescriptor descriptor = provider.CreateDescriptor(m_device.capabilities, S_VERTEX_LAYOUT); - GraphicsPipelineHandle pipeline = m_device.CreateGraphicsPipeline( - descriptor, "Render Model Composition"); + GraphicsPipelineDescriptor descriptor = provider.CreateDescriptor(m_device.capabilities, VERTEX_LAYOUT); + GraphicsPipelineHandle pipeline = m_device.CreateGraphicsPipeline(descriptor, "Render Model Composition"); PersistentBufferHandle vertices = default; PersistentBufferHandle indices = default; try { vertices = m_device.CreateBuffer( - new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 20, RenderBufferUsage.Vertex), S_VERTEX_LAYOUT), + new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 20, RenderBufferUsage.Vertex), VERTEX_LAYOUT), CreateVertices(m_device.capabilities.originBottomLeft), - "Render Model Composition Vertices"); + "Render Model Composition Vertices" + ); indices = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(6, sizeof(ushort), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16), + indexFormat: RenderIndexFormat.UInt16 + ), [0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0], - "Render Model Composition Indices"); + "Render Model Composition Indices" + ); } catch { if (indices.isValid) + { m_device.DestroyBuffer(indices); + } if (vertices.isValid) + { m_device.DestroyBuffer(vertices); + } m_device.DestroyGraphicsPipeline(pipeline); throw; } @@ -171,15 +212,16 @@ private void EnsureResources() private void EnsureOutputTransferPipeline() { if (m_outputTransferPipeline.isValid) + { return; + } IRenderLayerCompositionProgramProvider provider = m_programProvider ?? throw new InvalidOperationException("The rendering host has no layer composition program provider."); GraphicsPipelineDescriptor descriptor = provider.CreateOutputTransferDescriptor( m_device.capabilities, - S_VERTEX_LAYOUT); - m_outputTransferPipeline = m_device.CreateGraphicsPipeline( - descriptor, - "Render Model Output Transfer"); + VERTEX_LAYOUT + ); + m_outputTransferPipeline = m_device.CreateGraphicsPipeline(descriptor, "Render Model Output Transfer"); } private void AddOutputTransfer( @@ -191,13 +233,14 @@ RenderViewport viewport var data = new PassData(m_outputTransferPipeline, m_vertices, m_indices, source, viewport); RasterPassBuilder transfer = graph.AddRasterPass( $"{name}/Output Transfer", - S_PHASE, + PHASE, data, static ( value, context - ) => DrawFullscreen(value, context)); - transfer.SetViewTransform(S_IDENTITY, S_IDENTITY); + ) => DrawFullscreen(value, context) + ); + transfer.SetViewTransform(IDENTITY, IDENTITY); transfer.ReadTexture(source); transfer.ClearPresentationTarget(default); transfer.HasSideEffect(); @@ -207,26 +250,18 @@ private static void DrawFullscreen( PassData value, RenderPassContext context ) { - context.commands.SetViewport( - value.viewport.x, - value.viewport.y, - value.viewport.width, - value.viewport.height); - context.commands.SetScissor( - value.viewport.x, - value.viewport.y, - value.viewport.width, - value.viewport.height); + context.commands.SetViewport(value.viewport.x, value.viewport.y, value.viewport.width, value.viewport.height); + context.commands.SetScissor(value.viewport.x, value.viewport.y, value.viewport.width, value.viewport.height); context.commands.BindGraphicsPipeline(value.pipeline); context.commands.BindVertexBuffer(value.vertices); context.commands.BindIndexBuffer(value.indices); - context.commands.BindTexture(S_TEXTURE, value.source); + context.commands.BindTexture(TEXTURE, value.source); context.commands.DrawIndexed(6); } private static byte[] CreateVertices(bool originBottomLeft) { - byte[] bytes = new byte[4 * 20]; + var bytes = new byte[4 * 20]; float top = originBottomLeft ? 1f : 0f; float bottom = originBottomLeft ? 0f : 1f; WriteVertex(0, -1f, 1f, 0f, top); diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs index da9f63b61..ab17a7a25 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs @@ -11,11 +11,6 @@ namespace Inno.Rendering.Runtime; internal sealed class RenderMaterialOwner : RenderResourceProvider, IDisposable { - internal delegate bool TextureResolver( - RenderTextureArtifactReference texture, - out PersistentTextureHandle handle - ); - private readonly IRenderDevice m_device; private readonly IDiagnosticReporter m_diagnostics; private readonly IRenderTargetArtifactProvider? m_targetArtifacts; @@ -45,16 +40,34 @@ int capacity m_programs = new(DestroyPublication, capacity); } + /// + /// Retires every program publication without releasing dependencies before pending native retirement completes. + /// + public void Dispose() + { + m_stopping = true; + if (m_retirement is null) + { + m_retirement = new(); + m_retirement.Add(DrainFailed); + m_retirement.Add(m_programs.Dispose); + } + m_retirement.Dispose(); + } + internal int count { get { int result = 0; - foreach (var pair in m_programs) + foreach (KeyValuePair pair in m_programs) + { result += pair.Value.programs.Count; + } return result; } } + internal int retiringCount => m_programs.pendingCount + m_failedCandidates.Count; internal long rejectedCount => m_programs.rejectedCount; @@ -67,6 +80,7 @@ internal void BeginFrame(ulong frameIndex) } internal void Sweep(ulong oldest) => m_programs.Sweep(entry => entry.lastUsedFrame < oldest); + internal void Drain() { ObjectDisposedException.ThrowIf(m_stopping, this); @@ -74,25 +88,10 @@ internal void Drain() m_programs.Drain(); } - /// - /// Retires every program publication without releasing dependencies before pending native retirement completes. - /// - public void Dispose() - { - m_stopping = true; - if (m_retirement is null) - { - m_retirement = new(); - m_retirement.Add(DrainFailed); - m_retirement.Add(m_programs.Dispose); - } - m_retirement.Dispose(); - } - internal bool TryResolveMaterial( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, ShaderProgramKind expectedKind, RenderVertexLayout? vertexLayout, MaterialPropertyBlock? overrides, @@ -106,18 +105,24 @@ internal bool TryResolveMaterial( diagnostics ??= m_diagnostics; materialPass = null; ShaderAsset? shader = material.shader; - if (shader is null || shader.identity.persistentId == Guid.Empty) + if (shader is null || shader.identity.persistentID == Guid.Empty) { - Publish("RENDER_SHADER_ID_MISSING", "Material requires a shader with a persistent asset identity.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_SHADER_ID_MISSING", + "Material requires a shader with a persistent asset identity.", + material.assetPath.ToString(), + diagnostics + ); return false; } - Guid shaderId = shader.identity.persistentId; + Guid shaderID = shader.identity.persistentID; RenderShaderVariant variant; try { - variant = suppliedArtifact is null ? RenderShaderVariant.FromMaterial(material) - : RenderShaderVariant.FromMaterial(material, m_targetArtifacts!.ReadShaderDefinition(suppliedArtifact)); + variant = suppliedArtifact is null + ? RenderShaderVariant.FromMaterial(material) + : RenderShaderVariant.FromMaterial(material, m_targetArtifacts!.ReadShaderDefinition(suppliedArtifact)); } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -126,16 +131,29 @@ internal bool TryResolveMaterial( catch (Exception failure) { Publish("RENDER_MATERIAL_VARIANT_INVALID", failure.Message, material.assetPath.ToString(), diagnostics); - return TryUseLastGood(material, shaderId, contractId, passRoleId, expectedKind, vertexLayout, overrides, out materialPass, scope, diagnostics); + return TryUseLastGood( + material, + shaderID, + contractID, + passRoleID, + expectedKind, + vertexLayout, + overrides, + out materialPass, + scope, + diagnostics + ); } - ProgramPublication? publication = FindPublication(shaderId, variant, scope); + ProgramPublication? publication = FindPublication(shaderID, variant, scope); ArtifactResult result; if (suppliedArtifact is null) + { result = QueryArtifact(shader, variant); + } else { - var lookup = new LookupKey(shaderId, variant.value, scope); + var lookup = new LookupKey(shaderID, variant.value, scope); if (!m_frameArtifacts.TryGetValue(lookup, out result)) { result = new(RenderTargetArtifactStatus.Ready, suppliedArtifact); @@ -144,33 +162,52 @@ internal bool TryResolveMaterial( } if (result.artifact is { } artifact && result.status == RenderTargetArtifactStatus.Ready && publication?.artifact.contentHash != artifact.contentHash - && !m_failedFrameCandidates.Contains(scope + artifact.contentHash)) - { + && !m_failedFrameCandidates.Contains(scope + artifact.contentHash) + ) { ProgramPublication? candidate = null; bool published = false; try { ShaderDefinition definition = m_targetArtifacts!.ReadShaderDefinition(artifact); ValidatePublication(artifact, definition, variant); - MaterialPassResolution? selected = MaterialPassResolver.Resolve(definition, material.techniqueId, - contractId, passRoleId, m_device.capabilities); + MaterialPassResolution? selected = MaterialPassResolver.Resolve( + definition, + material.techniqueId, + contractID, + passRoleID, + m_device.capabilities + ); if (selected is null) - return Unavailable(material, contractId, passRoleId, diagnostics); + { + return Unavailable(material, contractID, passRoleID, diagnostics); + } if (selected.pass.programKind != expectedKind) + { return WrongKind(material, selected.pass, expectedKind, diagnostics); + } candidate = new(artifact, definition); var required = new HashSet(); if (publication is not null) + { foreach (ProgramLayout layout in publication.programs.Keys) + { if (artifact.passes.Any(pass => pass.name == layout.passName && pass.programKind == layout.kind)) + { required.Add(layout); - required.Add(new(selected.pass.name, expectedKind, vertexLayout)); + } + } + } + required.Add(new ProgramLayout(selected.pass.name, expectedKind, vertexLayout)); if (count - (publication?.programs.Count ?? 0) + required.Count > m_capacity) + { throw new InvalidOperationException("Shader program publication exceeds the configured program capacity."); - var key = new PublicationKey(shaderId, artifact.targetKey, variant.value, scope); + } + var key = new PublicationKey(shaderID, artifact.targetKey, variant.value, scope); m_programs.RequireCapacity(key); foreach (ProgramLayout layout in required) + { candidate.programs.Add(layout, CreateProgram(artifact, layout)); + } candidate.lastUsedFrame = m_frameIndex; m_programs.Replace(key, candidate); publication = candidate; @@ -183,7 +220,9 @@ internal bool TryResolveMaterial( { // Publication has already committed; a retirement failure must never be reported as a rollback. if (published) + { throw; + } if (candidate is not null) { m_failedCandidates.Add(candidate); @@ -197,50 +236,107 @@ internal bool TryResolveMaterial( } } if (RetirementPendingException.Find(failure) is not null) + { throw; + } m_failedFrameCandidates.Add(scope + artifact.contentHash); - Publish("RENDER_PROGRAM_CREATE_FAILED", $"Shader kept its complete last-good publication: {failure.Message}", shader.assetPath.ToString(), diagnostics); + Publish( + "RENDER_PROGRAM_CREATE_FAILED", + $"Shader kept its complete last-good publication: {failure.Message}", + shader.assetPath.ToString(), + diagnostics + ); } } if (publication is null) + { return false; - return TryUsePublication(material, publication, contractId, passRoleId, expectedKind, vertexLayout, overrides, out materialPass, diagnostics); + } + return TryUsePublication( + material, + publication, + contractID, + passRoleID, + expectedKind, + vertexLayout, + overrides, + out materialPass, + diagnostics + ); } internal void ReleaseScope(string scope) { foreach (PublicationKey key in m_programs.Where(pair => pair.Key.scope == scope).Select(pair => pair.Key).ToArray()) + { m_programs.Release(key); + } } internal bool HasScope(string scope) { - foreach (var pair in m_programs) + foreach (KeyValuePair pair in m_programs) + { if (pair.Key.scope == scope) + { return true; + } + } return false; } + internal void ValidateArtifact(RenderShaderArtifact artifact) + { + ArgumentNullException.ThrowIfNull(artifact); + foreach (RenderShaderPassArtifact pass in artifact.passes) + { + ProgramEntry? program = null; + try + { + program = CreateProgram(artifact, new ProgramLayout(pass.name, pass.programKind, null)); + } + finally + { + if (program?.graphicsPipeline.isValid == true) + { + m_device.DestroyGraphicsPipeline(program.graphicsPipeline); + } + if (program?.computePipeline.isValid == true) + { + m_device.DestroyComputePipeline(program.computePipeline); + } + } + } + } + private ArtifactResult QueryArtifact( ShaderAsset shader, RenderShaderVariant variant ) { - var key = new LookupKey(shader.identity.persistentId, variant.value, ""); + var key = new LookupKey(shader.identity.persistentID, variant.value, string.Empty); if (m_frameArtifacts.TryGetValue(key, out ArtifactResult result)) + { return result; + } string source = shader.assetPath.ToString(); try { RenderShaderArtifact? artifact = null; RenderTargetArtifactStatus status = m_targetArtifacts?.GetShaderArtifact(shader, variant, m_device.capabilities, out artifact) - ?? RenderTargetArtifactStatus.Unavailable; + ?? RenderTargetArtifactStatus.Unavailable; if (status == RenderTargetArtifactStatus.Ready && artifact is null) + { throw new InvalidOperationException("The artifact provider returned Ready without a shader publication."); + } result = new(status, artifact); if (status == RenderTargetArtifactStatus.Unavailable) + { Publish("RENDER_SHADER_TARGET_UNAVAILABLE", "No target shader artifact is available for this device and variant.", source); + } else + { m_diagnostics.Resolve("RENDER_SHADER_TARGET_UNAVAILABLE", source); + } m_diagnostics.Resolve("RENDER_SHADER_TARGET_INVALID", source); } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) @@ -257,21 +353,25 @@ RenderShaderVariant variant } private ProgramPublication? FindPublication( - Guid shaderId, + Guid shaderID, RenderShaderVariant variant, string scope ) { foreach ((PublicationKey key, ProgramPublication publication) in m_programs) - if (key.shaderId == shaderId && key.variantKey == variant.value && key.scope == scope) + { + if (key.shaderID == shaderID && key.variantKey == variant.value && key.scope == scope) + { return publication; + } + } return null; } private bool TryUseLastGood( MaterialAsset material, - Guid shaderId, - ShaderContractId contract, - ShaderPassRoleId role, + Guid shaderID, + ShaderContractID contract, + ShaderPassRoleID role, ShaderProgramKind kind, RenderVertexLayout? layout, MaterialPropertyBlock? overrides, @@ -281,8 +381,10 @@ IDiagnosticReporter diagnostics ) { foreach ((PublicationKey key, ProgramPublication publication) in m_programs) { - if (key.shaderId != shaderId || key.scope != scope) + if (key.shaderID != shaderID || key.scope != scope) + { continue; + } RenderShaderVariant variant; try { @@ -293,7 +395,9 @@ IDiagnosticReporter diagnostics continue; } if (variant.value == key.variantKey) + { return TryUsePublication(material, publication, contract, role, kind, layout, overrides, out result, diagnostics); + } } result = null; return false; @@ -302,8 +406,8 @@ IDiagnosticReporter diagnostics private bool TryUsePublication( MaterialAsset material, ProgramPublication publication, - ShaderContractId contract, - ShaderPassRoleId role, + ShaderContractID contract, + ShaderPassRoleID role, ShaderProgramKind kind, RenderVertexLayout? layout, MaterialPropertyBlock? overrides, @@ -311,19 +415,30 @@ private bool TryUsePublication( IDiagnosticReporter diagnostics ) { result = null; - MaterialPassResolution? resolution = MaterialPassResolver.Resolve(publication.definition, material.techniqueId, - contract, role, m_device.capabilities); + MaterialPassResolution? resolution = MaterialPassResolver.Resolve( + publication.definition, + material.techniqueId, + contract, + role, + m_device.capabilities + ); if (resolution is null) + { return Unavailable(material, contract, role, diagnostics); + } if (resolution.pass.programKind != kind) + { return WrongKind(material, resolution.pass, kind, diagnostics); + } var key = new ProgramLayout(resolution.pass.name, kind, layout); if (!publication.programs.TryGetValue(key, out ProgramEntry? program)) { try { if (count >= m_capacity) + { throw new InvalidOperationException("Shader program capacity is exhausted."); + } program = CreateProgram(publication.artifact, key); publication.programs.Add(key, program); } @@ -339,9 +454,17 @@ IDiagnosticReporter diagnostics } publication.lastUsedFrame = m_frameIndex; if (!TryBuildBindings(material, overrides, publication, program.shaderInterface, out MaterialBinding[] bindings, diagnostics)) + { return false; - result = CreateMaterialPass(resolution.pass, program.graphicsPipeline, program.computePipeline, - publication.definition.properties, program.shaderInterface, bindings); + } + result = CreateMaterialPass( + resolution.pass, + program.graphicsPipeline, + program.computePipeline, + publication.definition.properties, + program.shaderInterface, + bindings + ); diagnostics.Resolve("RENDER_MATERIAL_PASS_UNAVAILABLE", material.assetPath.ToString()); diagnostics.Resolve("RENDER_MATERIAL_PASS_KIND_MISMATCH", material.assetPath.ToString()); diagnostics.Resolve("RENDER_MATERIAL_PROPERTY_TYPE_MISMATCH", material.assetPath.ToString()); @@ -350,11 +473,16 @@ IDiagnosticReporter diagnostics private bool Unavailable( MaterialAsset material, - ShaderContractId contract, - ShaderPassRoleId role, + ShaderContractID contract, + ShaderPassRoleID role, IDiagnosticReporter diagnostics ) { - Publish("RENDER_MATERIAL_PASS_UNAVAILABLE", $"Material does not implement contract '{contract}' role '{role}' in its published shader.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_MATERIAL_PASS_UNAVAILABLE", + $"Material does not implement contract '{contract}' role '{role}' in its published shader.", + material.assetPath.ToString(), + diagnostics + ); return false; } @@ -364,7 +492,12 @@ private bool WrongKind( ShaderProgramKind kind, IDiagnosticReporter diagnostics ) { - Publish("RENDER_MATERIAL_PASS_KIND_MISMATCH", $"Published pass '{pass.name}' is {pass.programKind}, not {kind}.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_MATERIAL_PASS_KIND_MISMATCH", + $"Published pass '{pass.name}' is {pass.programKind}, not {kind}.", + material.assetPath.ToString(), + diagnostics + ); return false; } @@ -376,39 +509,34 @@ ProgramLayout layout IReadOnlyList bindings = BuildBindingDescriptors(pass.shaderInterface); if (pass.programKind == ShaderProgramKind.Raster) { - GraphicsPipelineHandle handle = m_device.CreateGraphicsPipeline(new GraphicsPipelineDescriptor( - pass.stages.Single(value => value.stage == ShaderStage.Vertex).bytes.Span, - pass.stages.Single(value => value.stage == ShaderStage.Fragment).bytes.Span, - bindings, layout.vertexLayout, pass.rasterState), artifact.shaderName + "/" + pass.name); + GraphicsPipelineHandle handle = m_device.CreateGraphicsPipeline( + new GraphicsPipelineDescriptor( + pass.stages.Single(value => value.stage == ShaderStage.Vertex).bytes.Span, + pass.stages.Single(value => value.stage == ShaderStage.Fragment).bytes.Span, + bindings, + layout.vertexLayout, + pass.rasterState + ), + artifact.shaderName + "/" + pass.name + ); if (!handle.isValid) + { throw new InvalidOperationException("The rendering device returned an invalid graphics pipeline."); + } return new(handle, default, pass.shaderInterface); } - ComputePipelineHandle compute = m_device.CreateComputePipeline(new ComputePipelineDescriptor( - pass.stages.Single(value => value.stage == ShaderStage.Compute).bytes.Span, bindings), artifact.shaderName + "/" + pass.name); + ComputePipelineHandle compute = m_device.CreateComputePipeline( + new ComputePipelineDescriptor( + pass.stages.Single(value => value.stage == ShaderStage.Compute).bytes.Span, + bindings + ), + artifact.shaderName + "/" + pass.name + ); if (!compute.isValid) - throw new InvalidOperationException("The rendering device returned an invalid compute pipeline."); - return new(default, compute, pass.shaderInterface); - } - - internal void ValidateArtifact(RenderShaderArtifact artifact) - { - ArgumentNullException.ThrowIfNull(artifact); - foreach (RenderShaderPassArtifact pass in artifact.passes) { - ProgramEntry? program = null; - try - { - program = CreateProgram(artifact, new(pass.name, pass.programKind, null)); - } - finally - { - if (program?.graphicsPipeline.isValid == true) - m_device.DestroyGraphicsPipeline(program.graphicsPipeline); - if (program?.computePipeline.isValid == true) - m_device.DestroyComputePipeline(program.computePipeline); - } + throw new InvalidOperationException("The rendering device returned an invalid compute pipeline."); } + return new(default, compute, pass.shaderInterface); } private void ValidatePublication( @@ -417,21 +545,37 @@ private void ValidatePublication( RenderShaderVariant variant ) { if (artifact.variant != variant || definition.name != artifact.shaderName) - throw new InvalidOperationException("The shader program publication does not match its requested variant and captured definition."); + { + throw new InvalidOperationException( + "The shader program publication does not match its requested variant and captured definition." + ); + } foreach (ShaderDiagnostic diagnostic in ShaderDefinitionValidator.Validate(definition, m_device.capabilities)) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { throw new InvalidOperationException(diagnostic.message); - var properties = definition.properties.ToDictionary(static property => property.id); + } + } + Dictionary properties = definition.properties.ToDictionary( + static property => property.id + ); foreach (RenderShaderPassArtifact pass in artifact.passes) { ShaderPassDefinition declared = definition.passes.SingleOrDefault(value => value.name == pass.name); if (declared.name != pass.name || declared.programKind != pass.programKind) + { throw new InvalidOperationException($"Program '{pass.name}' has no matching captured pass contract."); + } foreach (ShaderInterfaceBinding binding in pass.shaderInterface.bindings) + { if (!properties.TryGetValue(binding.id, out ShaderPropertyDefinition property) || property.type != binding.type || property.bindingKind != binding.bindingKind || property.storageAccess != binding.storageAccess - || (binding.stages & ~property.stages) != 0) + || (binding.stages & ~property.stages) != 0 + ) { throw new InvalidOperationException($"Program binding '{binding.id}' does not match its captured material contract."); + } + } } } @@ -455,7 +599,10 @@ private void DrainFailed() } if (m_failedCleanupFailures.Count != 0) { - var failure = new AggregateException("Rejected shader publications retired with completed failures.", m_failedCleanupFailures); + var failure = new AggregateException( + "Rejected shader publications retired with completed failures.", + m_failedCleanupFailures + ); m_failedCleanupFailures.Clear(); throw failure; } @@ -469,14 +616,18 @@ private bool TryBuildBindings( out MaterialBinding[] bindings, IDiagnosticReporter diagnostics ) { - var result = new List(); - Dictionary definitions = publication.properties; + List result = []; + Dictionary definitions = publication.properties; foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { if (!definitions.TryGetValue(binding.id, out ShaderPropertyDefinition property)) + { continue; + } if (property.bindingOwner == ShaderPropertyBindingOwner.RenderPass) + { continue; + } bool supplied = overrides is not null && overrides.TryGet(binding.id, out _); MaterialValue value; if (supplied) @@ -484,47 +635,82 @@ IDiagnosticReporter diagnostics overrides!.TryGet(binding.id, out value); } else if (material.TryGet(binding.id, out value)) + { supplied = true; + } else + { value = property.defaultValue; + } if (binding.bindingKind == ShaderPropertyBindingKind.SampledTexture) { RenderTextureArtifactReference reference; if (supplied && value.kind == MaterialValueKind.Texture && value.texture is not null) + { reference = value.texture.GetTextureArtifactReference(); + } else if (supplied || !publication.textureDefaults.TryGetValue(binding.id, out reference)) + { continue; + } if (!m_textureResolver(reference, out PersistentTextureHandle texture)) { bindings = []; return false; } - result.Add(CreateTextureBinding( - new RenderBindingId(binding.id.value), - texture, - value.sampler)); + result.Add(CreateTextureBinding(new RenderBindingID(binding.id.value), texture, value.sampler)); continue; } if (binding.bindingKind is ShaderPropertyBindingKind.StorageBuffer - or ShaderPropertyBindingKind.StorageTexture) + or ShaderPropertyBindingKind.StorageTexture + ) { continue; + } if (!TryEncodeUniform(binding.type, value, out byte[]? bytes)) { Publish( "RENDER_MATERIAL_PROPERTY_TYPE_MISMATCH", $"Material '{material.assetPath.ToString()}' property '{binding.id}' does not match {binding.type}.", - material.assetPath.ToString(), diagnostics); + material.assetPath.ToString(), + diagnostics + ); bindings = []; return false; } - result.Add(CreateUniformBinding( - new RenderBindingId(binding.id.value), - bytes)); + result.Add(CreateUniformBinding(new RenderBindingID(binding.id.value), bytes)); } bindings = result.ToArray(); return true; } + private void Publish( + string code, + string message, + string? source, + IDiagnosticReporter? diagnostics = null + ) => (diagnostics ?? m_diagnostics).Publish(new Diagnostic(code, message, DiagnosticSeverity.Error, source)); + + private void DestroyPublication(ProgramPublication publication) + { + if (publication.retirement is null) + { + publication.retirement = new(); + foreach (ProgramEntry program in publication.programs.Values) + { + if (program.graphicsPipeline.isValid) + { + publication.retirement.Add(() => m_device.DestroyGraphicsPipeline(program.graphicsPipeline)); + } + if (program.computePipeline.isValid) + { + publication.retirement.Add(() => m_device.DestroyComputePipeline(program.computePipeline)); + } + } + publication.retirement.Add(publication.programs.Clear); + } + publication.retirement.Dispose(); + } + private static bool TryEncodeUniform( ShaderPropertyType type, MaterialValue value, @@ -559,55 +745,75 @@ private static IReadOnlyList BuildBindingDescript foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { if (!binding.location.HasValue || binding.bindingKind == ShaderPropertyBindingKind.Uniform) + { continue; + } HashSet used = binding.bindingKind == ShaderPropertyBindingKind.SampledTexture ? textureSlots : storageSlots; if (!used.Add(binding.location.Value)) - throw new InvalidOperationException($"Shader resource slot '{binding.location}' is assigned more than once in its binding domain."); + { + throw new InvalidOperationException( + $"Shader resource slot '{binding.location}' is assigned more than once in its binding domain." + ); + } } static int Next(HashSet used) { int slot = 0; while (!used.Add(slot)) + { slot++; + } return slot; } foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { - RenderBindingId id = new(binding.id.value); + var id = new RenderBindingID(binding.id.value); switch (binding.bindingKind) { case ShaderPropertyBindingKind.Uniform: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.Uniform, - uniformType: binding.type == ShaderPropertyType.Matrix4x4 - ? RenderUniformType.Matrix4x4 - : RenderUniformType.Vector4, - count: binding.arrayCount, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.Uniform, + uniformType: binding.type == ShaderPropertyType.Matrix4x4 + ? RenderUniformType.Matrix4x4 + : RenderUniformType.Vector4, + count: binding.arrayCount, + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.SampledTexture: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.Texture, - slot: binding.location ?? Next(textureSlots), - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.Texture, + slot: binding.location ?? Next(textureSlots), + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.StorageTexture: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.StorageTexture, - slot: binding.location ?? Next(storageSlots), - storageAccess: binding.storageAccess, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.StorageTexture, + slot: binding.location ?? Next(storageSlots), + storageAccess: binding.storageAccess, + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.StorageBuffer: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.StorageBuffer, - slot: binding.location ?? Next(storageSlots), - storageAccess: binding.storageAccess, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.StorageBuffer, + slot: binding.location ?? Next(storageSlots), + storageAccess: binding.storageAccess, + nativeName: binding.nativeName + ) + ); break; default: throw new ArgumentOutOfRangeException(nameof(binding)); @@ -616,34 +822,10 @@ static int Next(HashSet used) return result; } - private void Publish( - string code, - string message, - string? source, - IDiagnosticReporter? diagnostics = null - ) - => (diagnostics ?? m_diagnostics).Publish(new Diagnostic( - code, - message, - DiagnosticSeverity.Error, - source)); - - private void DestroyPublication(ProgramPublication publication) - { - if (publication.retirement is null) - { - publication.retirement = new(); - foreach (ProgramEntry program in publication.programs.Values) - { - if (program.graphicsPipeline.isValid) - publication.retirement.Add(() => m_device.DestroyGraphicsPipeline(program.graphicsPipeline)); - if (program.computePipeline.isValid) - publication.retirement.Add(() => m_device.DestroyComputePipeline(program.computePipeline)); - } - publication.retirement.Add(publication.programs.Clear); - } - publication.retirement.Dispose(); - } + internal delegate bool TextureResolver( + RenderTextureArtifactReference texture, + out PersistentTextureHandle handle + ); private sealed class ProgramPublication { @@ -658,17 +840,20 @@ ShaderDefinition definition ShaderPropertyDefinition property = definition.properties[index]; MaterialValue value = property.defaultValue; if (value.texture is not null) + { textureDefaults.Add(property.id, value.texture.GetTextureArtifactReference()); + } value.texture = null; property.defaultValue = value; definition.properties[index] = property; properties.Add(property.id, property); } } + internal RenderShaderArtifact artifact { get; } internal ShaderDefinition definition { get; } - internal Dictionary properties { get; } = []; - internal Dictionary textureDefaults { get; } = []; + internal Dictionary properties { get; } = []; + internal Dictionary textureDefaults { get; } = []; internal Dictionary programs { get; } = []; internal ulong lastUsedFrame { get; set; } internal RenderRetirementQueue? retirement { get; set; } @@ -679,22 +864,26 @@ private sealed record ProgramEntry( ComputePipelineHandle computePipeline, ShaderInterface shaderInterface ); + private readonly record struct ProgramLayout( string passName, ShaderProgramKind kind, RenderVertexLayout? vertexLayout ); + private readonly record struct PublicationKey( - Guid shaderId, + Guid shaderID, string targetKey, string variantKey, string scope ); + private readonly record struct LookupKey( - Guid shaderId, + Guid shaderID, string variantKey, string scope ); + private readonly record struct ArtifactResult( RenderTargetArtifactStatus status, RenderShaderArtifact? artifact diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs index f41acbccd..8bcbb1df2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs @@ -16,9 +16,14 @@ RenderPipeline pipeline ) { this.typeCacheVersion = typeCacheVersion; this.pipeline = m_lifetime.Own(pipeline); - features = new ReadOnlyDictionary(m_features); + this.features = new ReadOnlyDictionary(m_features); } + /// + /// Retires features before their pipeline, preserving the remaining ownership while work is pending. + /// + public void Dispose() => m_lifetime.Dispose(); + internal long typeCacheVersion { get; } internal RenderPipeline pipeline { get; } internal IReadOnlyDictionary features { get; } @@ -28,12 +33,9 @@ internal void AddFeature( RenderPipelineFeature feature ) { if (feature is IDisposable resource) + { m_lifetime.Own(resource); + } m_features.Add(id, feature); } - - /// - /// Retires features before their pipeline, preserving the remaining ownership while work is pending. - /// - public void Dispose() => m_lifetime.Dispose(); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs index 2cebbda7d..72b663073 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -15,9 +14,10 @@ internal sealed class RenderPresentationComposer internal bool MustPreserve(RenderRequest request) { ArgumentNullException.ThrowIfNull(request); - return m_initializedRegions.Exists(region => + return m_initializedRegions.Exists(region => ( region.target == request.target - && Overlaps(region.viewport, request.viewport)); + && Overlaps(region.viewport, request.viewport) + )); } internal void Commit(RenderRequest request) @@ -31,11 +31,10 @@ internal void Commit(RenderRequest request) private static bool Overlaps( RenderViewport left, RenderViewport right - ) - => (long)left.x < (long)right.x + right.width - && (long)right.x < (long)left.x + left.width - && (long)left.y < (long)right.y + right.height - && (long)right.y < (long)left.y + left.height; + ) => (long)left.x < (long)right.x + right.width + && (long)right.x < (long)left.x + left.width + && (long)left.y < (long)right.y + right.height + && (long)right.y < (long)left.y + left.height; private readonly record struct PresentationRegion( RenderTarget target, diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs index 046910144..ed298e961 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs @@ -19,25 +19,63 @@ int capacity private int m_peak; private long m_rejected; + /// + /// Releases the resources owned by this implementation. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + if (m_retirement is null) + { + m_retirement = new RenderRetirementQueue(); + foreach ((RenderTextureReadbackHandle handle, PendingReadback pending) in m_pending) + { + m_retirement.Add(() => device.CancelTextureReadback(handle)); + m_retirement.Add(() => pending.completion.TrySetException(new ObjectDisposedException(nameof(RenderReadbackOwner)))); + } + } + try + { + m_retirement.Dispose(); + } + catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) + { + throw; + } + catch + { + m_pending.Clear(); + m_disposed = true; + throw; + } + m_pending.Clear(); + m_disposed = true; + } + internal int count => m_pending.Count; internal int peakCount => m_peak; internal long rejectedCount => m_rejected; - internal ValueTask Read( + internal ValueTask ReadAsync( PersistentTextureHandle texture, int mipLevel, - CancellationToken cancellation + CancellationToken cancellationToken ) { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (!device.capabilities.Supports(GraphicsCapability.TextureReadback)) + { throw new NotSupportedException("The active backend does not support texture readback."); + } if (m_pending.Count >= capacity) { m_rejected++; throw new InvalidOperationException($"Readback capacity {capacity} has been reached."); } - var pending = new PendingReadback(cancellation); + var pending = new PendingReadback(cancellationToken); RenderTextureReadbackHandle handle = device.BeginTextureReadback(texture, mipLevel); m_pending.Add(handle, pending); m_peak = Math.Max(m_peak, m_pending.Count); @@ -54,7 +92,9 @@ internal void Update() try { if (!device.TryGetTextureReadback(handle, out RenderTextureReadbackResult? result)) + { continue; + } m_pending.Remove(handle); pending.completion.TrySetResult(result!); continue; @@ -72,7 +112,9 @@ internal void Update() try { if (!pending.retirement.TryComplete(() => device.CancelTextureReadback(handle))) + { throw new RetirementPendingException("Texture readback cancellation is still pending."); + } } catch (Exception unfinished) when (RetirementPendingException.Find(unfinished) is not null) { @@ -84,51 +126,24 @@ internal void Update() } m_pending.Remove(handle); if (pending.failure is not null) + { pending.completion.TrySetException(pending.failure); + } else - pending.completion.TrySetCanceled(pending.cancellation); - } - } - - /// - /// Releases the resources owned by this implementation. - /// - public void Dispose() - { - if (m_disposed) - return; - if (m_retirement is null) - { - m_retirement = new RenderRetirementQueue(); - foreach ((RenderTextureReadbackHandle handle, PendingReadback pending) in m_pending) { - m_retirement.Add(() => device.CancelTextureReadback(handle)); - m_retirement.Add(() => pending.completion.TrySetException(new ObjectDisposedException(nameof(RenderReadbackOwner)))); + pending.completion.TrySetCanceled(pending.cancellation); } } - try - { - m_retirement.Dispose(); - } - catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) - { - throw; - } - catch - { - m_pending.Clear(); - m_disposed = true; - throw; - } - m_pending.Clear(); - m_disposed = true; } - private sealed class PendingReadback(CancellationToken cancellation) + private sealed class PendingReadback(CancellationToken cancellationToken) { internal Exception? failure { get; set; } internal RetirementBarrier? retirement { get; set; } - internal CancellationToken cancellation { get; } = cancellation; - internal TaskCompletionSource completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal CancellationToken cancellation { get; } = cancellationToken; + + internal TaskCompletionSource completion { get; } = new( + TaskCreationOptions.RunContinuationsAsynchronously + ); } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs index bcf2c6a5c..52650b91d 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs @@ -1,7 +1,7 @@ using System; using System.Collections; -using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Inno.Core.Execution; @@ -10,19 +10,49 @@ namespace Inno.Rendering.Runtime; internal sealed class RenderResourceCache( Action release, int capacity -) - : IEnumerable>, IDisposable where TKey : notnull where TEntry : class +) : IEnumerable>, IDisposable + where TKey : notnull + where TEntry : class { private readonly Dictionary m_entries = []; private readonly Queue m_retiring = []; + private readonly List m_failures = []; private RetirementBarrier? m_barrier; private bool m_stopping; private long m_rejected; private int m_peak; - private readonly List m_failures = []; - internal IEnumerable Values => m_entries.Values; - internal int Count => m_entries.Count; + /// + /// Releases the resources owned by this implementation. + /// + public void Dispose() + { + if (!m_stopping) + { + m_stopping = true; + foreach (TEntry entry in m_entries.Values) + { + m_retiring.Enqueue(entry); + } + m_entries.Clear(); + } + Drain(); + } + + /// + /// Gets an enumerator required by the implemented contract. + /// + /// + /// The validated ienumeratorkey value pairtkey, tentry that represents the completed operation. + /// + public Dictionary.Enumerator GetEnumerator() => m_entries.GetEnumerator(); + + IEnumerator> IEnumerable>.GetEnumerator() => GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + internal IEnumerable values => m_entries.Values; + internal int count => m_entries.Count; internal int pendingCount => m_retiring.Count; internal int peakCount => m_peak; internal long rejectedCount => m_rejected; @@ -48,7 +78,9 @@ internal void Replace( TEntry candidate ) { if (m_entries.TryGetValue(key, out TEntry? previous)) + { m_retiring.Enqueue(previous); + } m_entries[key] = candidate; m_peak = Math.Max(m_peak, m_entries.Count); } @@ -56,7 +88,9 @@ TEntry candidate internal void Release(TKey key) { if (m_entries.Remove(key, out TEntry? entry)) + { m_retiring.Enqueue(entry); + } Drain(); } @@ -64,7 +98,9 @@ internal void Sweep(Func unused) { Drain(); foreach (TKey key in m_entries.Where(pair => unused(pair.Value)).Select(pair => pair.Key).ToArray()) + { Release(key); + } } internal void Drain() @@ -76,12 +112,16 @@ internal void Drain() try { if (!m_barrier.TryComplete(() => release(entry))) + { throw new RetirementPendingException("A retired GPU resource still owns unfinished work."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (failures.Count != 0) + { throw new AggregateException("GPU retirement is pending after completed failures.", [.. failures, pending]); + } throw; } catch (Exception failure) @@ -98,31 +138,4 @@ internal void Drain() throw failure; } } - - /// - /// Releases the resources owned by this implementation. - /// - public void Dispose() - { - if (!m_stopping) - { - m_stopping = true; - foreach (TEntry entry in m_entries.Values) - m_retiring.Enqueue(entry); - m_entries.Clear(); - } - Drain(); - } - - /// - /// Gets an enumerator required by the implemented contract. - /// - /// - /// The validated ienumeratorkey value pairtkey, tentry that represents the completed operation. - /// - public Dictionary.Enumerator GetEnumerator() => m_entries.GetEnumerator(); - - IEnumerator> IEnumerable>.GetEnumerator() => GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs index c0c9375a8..e2dc0f6f2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs @@ -10,7 +10,7 @@ public sealed class RenderResourceLimits /// /// Gets the maximum active entries in each buffer, texture or pipeline cache. /// - public int resourcesPerKind { get; init; } = 16384; + public int resourcesPerKind { get; init; } = 16_384; /// /// Gets the maximum readbacks that can retain GPU resources before owner-thread completion. @@ -21,14 +21,17 @@ public sealed class RenderResourceLimits /// Gets the maximum resident frame-upload pages. /// public int uploadPages { get; init; } = 1024; + /// /// Gets the maximum resident frame-upload bytes, including retired pages. /// public long uploadResidentBytes { get; init; } = 256L * 1024 * 1024; + /// /// Gets the maximum bytes uploaded during one frame. /// public long uploadBytesPerFrame { get; init; } = 64L * 1024 * 1024; + /// /// Gets the offscreen target count and per-frame target allocation capacity. /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs index 8fff3a6b5..5aaa4164a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Rendering; using Inno.Rendering.Assets; @@ -18,14 +18,14 @@ internal sealed class RenderResourceService : RenderResourceProvider, IRenderRes private readonly IRenderDevice m_device; private readonly IDiagnosticReporter m_diagnostics; private readonly IRenderTargetArtifactProvider? m_targetArtifacts; - private readonly RenderResourceCache m_buffers; - private readonly RenderResourceCache m_textures; - private readonly RenderResourceCache m_graphicsPipelines; - private readonly RenderResourceCache m_computePipelines; + private readonly RenderResourceCache m_buffers; + private readonly RenderResourceCache m_textures; + private readonly RenderResourceCache m_graphicsPipelines; + private readonly RenderResourceCache m_computePipelines; private readonly RenderGeometryOwner m_geometry; private readonly RenderMaterialOwner m_materials; private readonly RenderReadbackOwner m_readbacks; - private readonly HashSet m_pendingReleases = []; + private readonly HashSet m_pendingReleases = []; private bool m_mutationAllowed; private ulong m_frameIndex; private bool m_disposed; @@ -38,8 +38,10 @@ internal RenderResourceService( IRenderTargetArtifactProvider? targetArtifacts, RenderResourceLimits limits ) { - m_device = device ?? throw new ArgumentNullException(nameof(device)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + ArgumentNullException.ThrowIfNull(device); + ArgumentNullException.ThrowIfNull(diagnostics); + m_device = device; + m_diagnostics = diagnostics; m_targetArtifacts = targetArtifacts; m_readbacks = new(device, limits.pendingReadbacks); m_buffers = new(entry => m_device.DestroyBuffer(entry.handle), limits.resourcesPerKind); @@ -66,7 +68,9 @@ public void ValidateShaderArtifact(RenderShaderArtifact artifact) ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(artifact); if (!m_mutationAllowed) + { throw new InvalidOperationException("Shader artifact validation requires an open frame before graph execution."); + } m_materials.ValidateArtifact(artifact); } @@ -84,10 +88,12 @@ public RenderTargetArtifactStatus PrewarmMaterial(MaterialAsset material) ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(material); ShaderAsset shader = material.shader - ?? throw new ArgumentException("A material must reference a shader before prewarming.", nameof(material)); + ?? throw new ArgumentException("A material must reference a shader before prewarming.", nameof(material)); RenderShaderVariant variant = RenderShaderVariant.FromMaterial(material); if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact provider is configured for this runtime."); + } return m_targetArtifacts.GetShaderArtifact(shader, variant, m_device.capabilities, out _); } @@ -113,10 +119,14 @@ public void PrewarmTexture(TextureAsset texture) public void PrewarmTextureArtifact(RenderTextureArtifactReference texture) { ThrowIfDisposed(); - if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + if (texture.assetID == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact provider is configured for this runtime."); + } _ = m_targetArtifacts.GetTextureArtifact(texture, out _); } @@ -142,20 +152,20 @@ public void PrewarmTextureArtifact(RenderTextureArtifactReference texture) /// The validated persistent buffer handle that represents the completed operation. /// public PersistentBufferHandle AcquireBuffer( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, PersistentBufferDescriptor descriptor, ReadOnlyMemory initialData, string name ) { ThrowIfDisposed(); - RequireId(id); + RequireID(id); ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_buffers.TryGetValue(id, out BufferEntry? current) && current.revision == revision - && BufferDescriptorsEqual(current.descriptor, descriptor)) - { + && BufferDescriptorsEqual(current.descriptor, descriptor) + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -190,24 +200,26 @@ string name /// The validated persistent texture handle that represents the completed operation. /// public PersistentTextureHandle AcquireTexture( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, RenderTextureDescriptor descriptor, IReadOnlyList subresources, string name ) { ThrowIfDisposed(); - RequireId(id); + RequireID(id); ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(subresources); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (subresources.Count == 0) + { throw new ArgumentException("A raw texture requires at least one subresource upload.", nameof(subresources)); + } if (m_textures.TryGetValue(id, out TextureEntry? current) && current.kind == TextureEntryKind.Raw && current.revision == revision - && descriptor.Equals(current.descriptor)) - { + && descriptor.Equals(current.descriptor) + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -221,17 +233,14 @@ string name if (subresource.mipLevel >= descriptor.mipCount || (subresource.mipLevel < descriptor.mipCount && subresource.arrayLayer - >= descriptor.GetSubresourceLayerCount(subresource.mipLevel))) - { + >= descriptor.GetSubresourceLayerCount(subresource.mipLevel)) + ) { throw new ArgumentException( "A texture upload addresses a mip or layer outside its descriptor.", - nameof(subresources)); + nameof(subresources) + ); } - m_device.UpdateTexture( - candidate, - subresource.data.Span, - subresource.mipLevel, - subresource.arrayLayer); + m_device.UpdateTexture(candidate, subresource.data.Span, subresource.mipLevel, subresource.arrayLayer); } } catch (Exception failure) @@ -240,12 +249,7 @@ string name throw; } - var replacement = new TextureEntry( - candidate, - TextureEntryKind.Raw, - descriptor, - revision, - m_frameIndex); + var replacement = new TextureEntry(candidate, TextureEntryKind.Raw, descriptor, revision, m_frameIndex); m_textures.Replace(id, replacement); m_textures.Drain(); return candidate; @@ -273,22 +277,24 @@ string name /// The validated persistent texture handle that represents the completed operation. /// public PersistentTextureHandle AcquireKtxTexture( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, ReadOnlyMemory containerData, bool sRgb, string name ) { ThrowIfDisposed(); - RequireId(id); + RequireID(id); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (containerData.IsEmpty) + { throw new ArgumentException("A KTX resource cannot be empty.", nameof(containerData)); + } if (m_textures.TryGetValue(id, out TextureEntry? current) && current.kind == TextureEntryKind.Ktx && current.revision == revision - && current.sRgb == sRgb) - { + && current.sRgb == sRgb + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -298,14 +304,16 @@ string name RenderTextureContainer.Ktx, containerData.Span, sRgb, - name); + name + ); var replacement = new TextureEntry( candidate, TextureEntryKind.Ktx, descriptor: null, revision, m_frameIndex, - sRgb); + sRgb + ); m_textures.Replace(id, replacement); m_textures.Drain(); return candidate; @@ -330,9 +338,13 @@ ReadOnlyMemory data ) { ThrowIfDisposed(); if (!texture.isValid) + { throw new ArgumentException("A valid persistent texture is required.", nameof(texture)); + } if (data.IsEmpty) + { throw new ArgumentException("Texture update data cannot be empty.", nameof(data)); + } m_device.UpdateTextureRegion(texture, region, data.Span); } @@ -357,7 +369,7 @@ public ValueTask ReadTextureAsync( CancellationToken cancellationToken = default ) { ThrowIfDisposed(); - return m_readbacks.Read(texture, mipLevel, cancellationToken); + return m_readbacks.ReadAsync(texture, mipLevel, cancellationToken); } /// @@ -366,10 +378,10 @@ public ValueTask ReadTextureAsync( /// /// The material consumed by try resolve graphics material; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The contract id consumed by try resolve graphics material; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The pass role id consumed by try resolve graphics material; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -386,8 +398,8 @@ public ValueTask ReadTextureAsync( /// public bool TryResolveGraphicsMaterial( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, RenderVertexLayout? vertexLayout, MaterialPropertyBlock? overrides, out RenderMaterialPass? materialPass @@ -395,12 +407,13 @@ out RenderMaterialPass? materialPass ThrowIfDisposed(); return m_materials.TryResolveMaterial( material, - contractId, - passRoleId, + contractID, + passRoleID, ShaderProgramKind.Raster, vertexLayout, overrides, - out materialPass); + out materialPass + ); } /// @@ -415,10 +428,10 @@ out RenderMaterialPass? materialPass /// /// The material consumed by try resolve material artifact; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The contract id consumed by try resolve material artifact; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The pass role id consumed by try resolve material artifact; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -440,11 +453,11 @@ out RenderMaterialPass? materialPass /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool TryResolveMaterialArtifact( - RenderPersistentResourceId scope, + RenderPersistentResourceID scope, RenderShaderArtifact artifact, MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, ShaderProgramKind programKind, RenderVertexLayout? vertexLayout, MaterialPropertyBlock? overrides, @@ -452,17 +465,33 @@ public bool TryResolveMaterialArtifact( out RenderMaterialPass? materialPass ) { ThrowIfDisposed(); - RequireId(scope); + RequireID(scope); ArgumentNullException.ThrowIfNull(artifact); ArgumentNullException.ThrowIfNull(diagnostics); if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact decoder is configured."); + } if (!Enum.IsDefined(programKind)) + { throw new ArgumentOutOfRangeException(nameof(programKind)); + } if (programKind == ShaderProgramKind.Compute && vertexLayout is not null) + { throw new ArgumentException("A compute program cannot consume a vertex layout.", nameof(vertexLayout)); - return m_materials.TryResolveMaterial(material, contractId, passRoleId, programKind, vertexLayout, overrides, - out materialPass, artifact, scope.value, diagnostics); + } + return m_materials.TryResolveMaterial( + material, + contractID, + passRoleID, + programKind, + vertexLayout, + overrides, + out materialPass, + artifact, + scope.value, + diagnostics + ); } /// @@ -471,10 +500,10 @@ out RenderMaterialPass? materialPass /// /// The material consumed by try resolve compute material; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The contract id consumed by try resolve compute material; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The pass role id consumed by try resolve compute material; ownership remains with the caller unless explicitly stated otherwise. /// /// @@ -488,20 +517,21 @@ out RenderMaterialPass? materialPass /// public bool TryResolveComputeMaterial( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, MaterialPropertyBlock? overrides, out RenderMaterialPass? materialPass ) { ThrowIfDisposed(); return m_materials.TryResolveMaterial( material, - contractId, - passRoleId, + contractID, + passRoleID, ShaderProgramKind.Compute, vertexLayout: null, overrides, - out materialPass); + out materialPass + ); } /// @@ -542,7 +572,7 @@ out PersistentTextureHandle resolvedTexture ) { ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(texture); - Guid id = texture.identity.persistentId; + Guid id = texture.identity.persistentID; if (id == Guid.Empty) { resolvedTexture = default; @@ -570,16 +600,18 @@ out PersistentTextureHandle resolvedTexture ) { ThrowIfDisposed(); resolvedTexture = default; - if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + if (texture.assetID == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { return false; + } - RenderPersistentResourceId resourceId = new($"asset:{texture.assetId:D}:texture:{texture.slot.id}"); + var resourceID = new RenderPersistentResourceID($"asset:{texture.assetID:D}:texture:{texture.slot.id}"); bool sRgb = texture.slot.colorSpace == TextureColorSpace.Srgb; - if (m_textures.TryGetValue(resourceId, out TextureEntry? current) + if (m_textures.TryGetValue(resourceID, out TextureEntry? current) && current.kind == TextureEntryKind.Ktx && current.revision == texture.contentRevision - && current.sRgb == sRgb) - { + && current.sRgb == sRgb + ) { current.lastUsedFrame = m_frameIndex; resolvedTexture = current.handle; return true; @@ -588,11 +620,13 @@ out PersistentTextureHandle resolvedTexture { ReadOnlyMemory artifact = ReadOnlyMemory.Empty; RenderTargetArtifactStatus status = m_targetArtifacts is null - ? RenderTargetArtifactStatus.Unavailable - : m_targetArtifacts.GetTextureArtifact(texture, out artifact); - string sourceId = $"{texture.assetId:D}:{texture.slot.id}"; + ? RenderTargetArtifactStatus.Unavailable + : m_targetArtifacts.GetTextureArtifact(texture, out artifact); + string sourceID = $"{texture.assetID:D}:{texture.slot.id}"; if (status != RenderTargetArtifactStatus.Unavailable) - m_diagnostics.Resolve("RENDER_TEXTURE_TARGET_UNAVAILABLE", sourceId); + { + m_diagnostics.Resolve("RENDER_TEXTURE_TARGET_UNAVAILABLE", sourceID); + } if (status != RenderTargetArtifactStatus.Ready) { if (status == RenderTargetArtifactStatus.Unavailable) @@ -600,11 +634,12 @@ out PersistentTextureHandle resolvedTexture Publish( "RENDER_TEXTURE_TARGET_UNAVAILABLE", m_targetArtifacts is null - ? "No render target artifact provider is configured for this runtime." - : $"No deployed target texture artifact exists for '{sourceId}'.", - sourceId); + ? "No render target artifact provider is configured for this runtime." + : $"No deployed target texture artifact exists for '{sourceID}'.", + sourceID + ); } - if (m_textures.TryGetValue(resourceId, out TextureEntry? lastGood)) + if (m_textures.TryGetValue(resourceID, out TextureEntry? lastGood)) { lastGood.lastUsedFrame = m_frameIndex; resolvedTexture = lastGood.handle; @@ -615,15 +650,11 @@ m_targetArtifacts is null if (artifact.IsEmpty) { throw new InvalidOperationException( - $"Target artifact provider returned an empty ready texture for '{sourceId}'."); + $"Target artifact provider returned an empty ready texture for '{sourceID}'." + ); } - resolvedTexture = AcquireKtxTexture( - resourceId, - texture.contentRevision, - artifact, - sRgb, - sourceId); - m_diagnostics.Resolve("RENDER_TEXTURE_RESOLVE_FAILED", sourceId); + resolvedTexture = AcquireKtxTexture(resourceID, texture.contentRevision, artifact, sRgb, sourceID); + m_diagnostics.Resolve("RENDER_TEXTURE_RESOLVE_FAILED", sourceID); return true; } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) @@ -634,9 +665,10 @@ m_targetArtifacts is null { Publish( "RENDER_TEXTURE_RESOLVE_FAILED", - $"Texture artifact '{texture.assetId:D}:{texture.slot.id}' kept its last-good GPU resource: {exception.Message}", - $"{texture.assetId:D}:{texture.slot.id}"); - if (m_textures.TryGetValue(resourceId, out TextureEntry? lastGood)) + $"Texture artifact '{texture.assetID:D}:{texture.slot.id}' kept its last-good GPU resource: {exception.Message}", + $"{texture.assetID:D}:{texture.slot.id}" + ); + if (m_textures.TryGetValue(resourceID, out TextureEntry? lastGood)) { lastGood.lastUsedFrame = m_frameIndex; resolvedTexture = lastGood.handle; @@ -665,18 +697,18 @@ m_targetArtifacts is null /// The validated graphics pipeline handle that represents the completed operation. /// public GraphicsPipelineHandle AcquireGraphicsPipeline( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, GraphicsPipelineDescriptor descriptor, string name ) { ThrowIfDisposed(); - RequireId(id); + RequireID(id); ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_graphicsPipelines.TryGetValue(id, out GraphicsPipelineEntry? current) - && current.revision == revision) - { + && current.revision == revision + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -708,18 +740,18 @@ string name /// The validated compute pipeline handle that represents the completed operation. /// public ComputePipelineHandle AcquireComputePipeline( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, ComputePipelineDescriptor descriptor, string name ) { ThrowIfDisposed(); - RequireId(id); + RequireID(id); ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_computePipelines.TryGetValue(id, out ComputePipelineEntry? current) - && current.revision == revision) - { + && current.revision == revision + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -738,43 +770,40 @@ string name /// /// The stable identity used to locate the requested value. /// - public void Release(RenderPersistentResourceId id) + public void Release(RenderPersistentResourceID id) { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); - RequireId(id); + RequireID(id); if (!m_mutationAllowed) { if (m_materials.HasScope(id.value) || m_graphicsPipelines.TryGetValue(id, out _) - || m_computePipelines.TryGetValue(id, out _) || m_buffers.TryGetValue(id, out _) || m_textures.TryGetValue(id, out _)) + || m_computePipelines.TryGetValue(id, out _) || m_buffers.TryGetValue(id, out _) || m_textures.TryGetValue(id, out _) + ) { m_pendingReleases.Add(id); + } return; } ThrowIfDisposed(); ReleaseNow(id); } - private void ReleaseNow(RenderPersistentResourceId id) - { - m_materials.ReleaseScope(id.value); - m_graphicsPipelines.Release(id); - m_computePipelines.Release(id); - m_buffers.Release(id); - m_textures.Release(id); - } - /// /// Releases the resources owned by this instance. /// public void Dispose() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); m_retirement.Add(m_readbacks.Dispose); if (m_failedAllocation is not null) + { m_retirement.Add(m_failedAllocation.Dispose); + } m_retirement.Add(m_materials.Dispose); m_retirement.Add(m_geometry.Dispose); m_retirement.Add(m_graphicsPipelines.Dispose); @@ -798,17 +827,30 @@ public void Dispose() CompleteRetirement(); } - private void CompleteRetirement() - { - m_disposed = true; - } - - internal RenderResourceStatistics statistics => new() + internal RenderResourceStatistics statistics + => new() { - activeResources = m_buffers.Count + m_textures.Count + m_graphicsPipelines.Count + m_computePipelines.Count + m_materials.count + m_geometry.count, - retiringResources = m_buffers.pendingCount + m_textures.pendingCount + m_graphicsPipelines.pendingCount + m_computePipelines.pendingCount + m_materials.retiringCount + m_geometry.retiringCount, - rejectedResources = m_buffers.rejectedCount + m_textures.rejectedCount + m_graphicsPipelines.rejectedCount + m_computePipelines.rejectedCount + m_materials.rejectedCount + m_geometry.rejectedCount, - pendingReadbacks = m_readbacks.count, peakReadbacks = m_readbacks.peakCount, rejectedReadbacks = m_readbacks.rejectedCount + activeResources = m_buffers.count + + m_textures.count + + m_graphicsPipelines.count + + m_computePipelines.count + + m_materials.count + + m_geometry.count, + retiringResources = m_buffers.pendingCount + + m_textures.pendingCount + + m_graphicsPipelines.pendingCount + + m_computePipelines.pendingCount + + m_materials.retiringCount + + m_geometry.retiringCount, + rejectedResources = m_buffers.rejectedCount + + m_textures.rejectedCount + + m_graphicsPipelines.rejectedCount + + m_computePipelines.rejectedCount + + m_materials.rejectedCount + + m_geometry.rejectedCount, + pendingReadbacks = m_readbacks.count, + peakReadbacks = m_readbacks.peakCount, + rejectedReadbacks = m_readbacks.rejectedCount }; internal void BeginFrame(ulong frameIndex) @@ -819,19 +861,24 @@ internal void BeginFrame(ulong frameIndex) m_geometry.BeginFrame(frameIndex); m_materials.BeginFrame(frameIndex); m_readbacks.Update(); - foreach (RenderPersistentResourceId id in m_pendingReleases) + foreach (RenderPersistentResourceID id in m_pendingReleases) + { ReleaseNow(id); + } m_pendingReleases.Clear(); } internal void EndMutation() => m_mutationAllowed = false; + internal void BeginMutation() => m_mutationAllowed = true; internal void SweepUnused() { ThrowIfDisposed(); if (m_frameIndex < C_UNUSED_FRAME_LIMIT) + { return; + } ulong oldest = m_frameIndex - C_UNUSED_FRAME_LIMIT; m_materials.Sweep(oldest); m_geometry.Sweep(oldest); @@ -841,30 +888,22 @@ internal void SweepUnused() m_textures.Sweep(entry => entry.lastUsedFrame < oldest); } - private static bool BufferDescriptorsEqual( - PersistentBufferDescriptor left, - PersistentBufferDescriptor right - ) - => left.buffer.Equals(right.buffer) - && Equals(left.vertexLayout, right.vertexLayout) - && left.indexFormat == right.indexFormat; - - private static void RequireId(RenderPersistentResourceId id) + private void ReleaseNow(RenderPersistentResourceID id) { - if (!id.isValid) - throw new ArgumentException("A persistent render resource ID must be valid.", nameof(id)); + m_materials.ReleaseScope(id.value); + m_graphicsPipelines.Release(id); + m_computePipelines.Release(id); + m_buffers.Release(id); + m_textures.Release(id); } + private void CompleteRetirement() => m_disposed = true; + private void Publish( string code, string message, string? source - ) - => m_diagnostics.Publish(new Diagnostic( - code, - message, - DiagnosticSeverity.Error, - source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, DiagnosticSeverity.Error, source)); private void ThrowIfDisposed() { @@ -899,6 +938,21 @@ Exception failure m_failedAllocation = null; } + private static bool BufferDescriptorsEqual( + PersistentBufferDescriptor left, + PersistentBufferDescriptor right + ) => left.buffer.Equals(right.buffer) + && Equals(left.vertexLayout, right.vertexLayout) + && left.indexFormat == right.indexFormat; + + private static void RequireID(RenderPersistentResourceID id) + { + if (!id.isValid) + { + throw new ArgumentException("A persistent render resource ID must be valid.", nameof(id)); + } + } + private enum TextureEntryKind { Raw, @@ -984,5 +1038,4 @@ ulong lastUsedFrame internal long revision { get; } internal ulong lastUsedFrame { get; set; } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs index a7074ec67..316bacaef 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs @@ -9,50 +9,62 @@ public readonly record struct RenderResourceStatistics /// Gets active persistent buffers, textures, pipelines, material programs and geometry pairs. /// public int activeResources { get; init; } + /// /// Gets resource entries whose native retirement is still pending. /// public int retiringResources { get; init; } + /// /// Gets cache admissions rejected by per-kind capacity. /// public long rejectedResources { get; init; } + /// /// Gets readbacks that still own native operations. /// public int pendingReadbacks { get; init; } + /// /// Gets the largest simultaneous readback occupancy. /// public int peakReadbacks { get; init; } + /// /// Gets readbacks rejected before native allocation. /// public long rejectedReadbacks { get; init; } + /// /// Gets retained upload pages, including pages awaiting retirement. /// public int uploadPages { get; init; } + /// /// Gets resident upload bytes, including pages awaiting retirement. /// public long uploadResidentBytes { get; init; } + /// /// Gets the high-water mark of resident upload bytes. /// public long uploadPeakBytes { get; init; } + /// /// Gets successfully uploaded bytes during the current frame. /// public long uploadedFrameBytes { get; init; } + /// /// Gets upload requests rejected by resident or per-frame limits. /// public long rejectedUploads { get; init; } + /// /// Gets active offscreen targets. /// public int targets { get; init; } + /// /// Gets offscreen target requests rejected by finite capacity. /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs index c01e50a82..fc551d19e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs @@ -10,13 +10,6 @@ internal sealed class RenderRetirementQueue : IDisposable private readonly List m_failures = []; private bool m_stopping; - internal void Add(Action retire) - { - if (m_stopping) - throw new InvalidOperationException("Rendering retirement no longer accepts allocations."); - m_steps.Enqueue(retire); - } - /// /// Drains the captured resource boundary without advancing past pending retirement. /// @@ -41,9 +34,21 @@ public void Dispose() } if (m_failures.Count > 0) { - var failure = new AggregateException("Rendering retirement failed after all quiescent owners were attempted.", m_failures); + var failure = new AggregateException( + "Rendering retirement failed after all quiescent owners were attempted.", + m_failures + ); m_failures.Clear(); throw failure; } } + + internal void Add(Action retire) + { + if (m_stopping) + { + throw new InvalidOperationException("Rendering retirement no longer accepts allocations."); + } + m_steps.Enqueue(retire); + } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs index a25c85cce..c8aff7251 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Registers frame-final work without transferring frame ownership. @@ -35,7 +35,9 @@ public void RegisterContributor(IRenderFrameGraphContributor contributor) lock (m_contributorLock) { if (m_contributors.Contains(contributor)) + { throw new ArgumentException("Frame graph contributor is already registered.", nameof(contributor)); + } m_contributors.Add(contributor); m_contributorSnapshot = new RenderContributorSnapshot(m_contributors); } @@ -56,7 +58,9 @@ public bool UnregisterContributor(IRenderFrameGraphContributor contributor) lock (m_contributorLock) { if (!m_contributors.Remove(contributor)) + { return false; + } m_contributorSnapshot = new RenderContributorSnapshot(m_contributors); return true; } @@ -114,5 +118,4 @@ private void AddContributors( } } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs index b9ae28368..7c8f7f036 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs @@ -1,30 +1,27 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private void PublishModelDiagnostic(string message) - { - PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, - DiagnosticSeverity.Warning)); - } + => PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, DiagnosticSeverity.Warning)); private void PublishFrameIssue(Diagnostic diagnostic) { - var key = new FrameIssueKey(diagnostic.code, diagnostic.semanticId, diagnostic.objectId); + var key = new FrameIssueKey(diagnostic.code, diagnostic.semanticID, diagnostic.objectID); m_currentFrameIssues[key] = diagnostic; m_diagnostics.Publish(diagnostic); } @@ -34,11 +31,15 @@ private void ReconcileFrameIssues() foreach (FrameIssueKey key in m_previousFrameIssues.Keys) { if (!m_currentFrameIssues.ContainsKey(key)) - m_diagnostics.Resolve(key.code, key.semanticId, key.objectId); + { + m_diagnostics.Resolve(key.code, key.semanticID, key.objectID); + } } m_previousFrameIssues.Clear(); foreach ((FrameIssueKey key, Diagnostic diagnostic) in m_currentFrameIssues) + { m_previousFrameIssues.Add(key, diagnostic); + } m_currentFrameIssues.Clear(); } @@ -48,15 +49,18 @@ string source ) { foreach (RenderGraphDiagnostic diagnostic in diagnostics) { - PublishFrameIssue(new Diagnostic( - diagnostic.code, - diagnostic.message, - diagnostic.severity == DiagnosticSeverity.Error + PublishFrameIssue( + new Diagnostic( + diagnostic.code, + diagnostic.message, + diagnostic.severity == DiagnosticSeverity.Error ? DiagnosticSeverity.Error : diagnostic.severity == DiagnosticSeverity.Warning - ? DiagnosticSeverity.Warning - : DiagnosticSeverity.Info, - diagnostic.passName ?? diagnostic.resourceName ?? source)); + ? DiagnosticSeverity.Warning + : DiagnosticSeverity.Info, + diagnostic.passName ?? diagnostic.resourceName ?? source + ) + ); } } @@ -64,17 +68,18 @@ private void PublishContributorFailure( IRenderFrameGraphContributor contributor, string stage, Exception exception - ) - => PublishFrameIssue(new Diagnostic( + ) => PublishFrameIssue( + new Diagnostic( "RENDER_FRAME_CONTRIBUTOR_FAILED", $"Frame contributor '{contributor.GetType().Name}' failed during {stage}: {exception.Message}", DiagnosticSeverity.Error, - contributor.GetType().FullName)); + contributor.GetType().FullName + ) + ); private readonly record struct FrameIssueKey( string code, - string? semanticId, - Guid? objectId + string? semanticID, + Guid? objectID ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs similarity index 95% rename from src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs rename to src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs index abd484cb3..bc57ec8e0 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs @@ -1,10 +1,9 @@ -using Inno.Rendering.Assets; -using System; using System.Collections.Generic; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private sealed class RenderFrameScratch { diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs index 6dcf9a33e..295d82453 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Captures snapshots and binds service façades. @@ -25,9 +25,11 @@ sealed partial class RenderRuntime protected override void OnBeginFrame(RuntimeFrame frame) { m_frameInput = InputExecutionContext.TryGet(out IInputService? input) - ? input!.snapshot : InputSnapshot.empty; + ? input!.snapshot + : InputSnapshot.empty; OwnFrameScope(EnterExecutionScope()); } + /// /// Opens resources required for this frame's output. /// @@ -35,6 +37,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) /// The variable frame timing. /// protected override void OnPrepareOutput(RuntimeFrame frame) => BeginRendering(frame.unscaledDeltaTime); + /// /// Collects output commands without executing managed code on a native realtime callback. /// @@ -42,6 +45,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) /// The variable frame timing. /// protected override void OnProduceOutput(RuntimeFrame frame) => CollectRendering(frame.unscaledDeltaTime); + /// /// Submits output and closes output-specific temporary resources. /// @@ -65,7 +69,9 @@ private void BeginRendering(float deltaTime) m_device.BeginFrame(); m_frameOpen = true; lock (m_contributorLock) + { m_frameContributors = m_contributorSnapshot; + } try { m_resourceService.BeginFrame(m_frameIndex); @@ -73,9 +79,12 @@ private void BeginRendering(float deltaTime) targets.PrepareFrame(); m_primaryPresentationSize = m_device.primaryPresentationSize; if (m_primaryPresentationSize is RenderPresentationSize size && !size.isValid) + { throw new InvalidOperationException("The render device reported an invalid primary presentation extent."); + } m_primaryPresentationViewport = m_primaryPresentationSize is RenderPresentationSize available - ? ResolvePrimaryPresentationViewport(available) : null; + ? ResolvePrimaryPresentationViewport(available) + : null; lock (m_requestLock) { m_currentRequests.Clear(); @@ -89,7 +98,7 @@ private void BeginRendering(float deltaTime) } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { - m_frameContributors = RenderContributorSnapshot.empty; + m_frameContributors = RenderContributorSnapshot.EMPTY; m_scratch.Clear(); throw; } @@ -103,7 +112,7 @@ private void BeginRendering(float deltaTime) { m_resourceService.EndMutation(); m_frameOpen = false; - m_frameContributors = RenderContributorSnapshot.empty; + m_frameContributors = RenderContributorSnapshot.EMPTY; m_scratch.Clear(); } throw; @@ -119,7 +128,9 @@ private void BeginRendering(float deltaTime) private void CollectRendering(float deltaTime) { if (!m_frameOpen || m_requestProviders is null) + { return; + } using IDisposable executionScope = EnterExecutionScope(); using ContentReadScope content = GetFrameContentScope(); @@ -134,10 +145,23 @@ private void CollectRendering(float deltaTime) m_frameIndex, deltaTime, this, - outputInput); + outputInput + ); if (m_primaryModelOutputEnabled && m_primaryPresentationViewport is RenderViewport viewport) - CollectModels(new RenderOutputSession("primary", content, viewport, - m_frameIndex, deltaTime, this, outputInput, m_primaryRoute)); + { + CollectModels( + new RenderOutputSession( + "primary", + content, + viewport, + m_frameIndex, + deltaTime, + this, + outputInput, + m_primaryRoute + ) + ); + } foreach (RenderExtensionRegistry.RequestProviderEntry entry in m_requestProviders.providers) { try @@ -150,11 +174,14 @@ private void CollectRendering(float deltaTime) } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_REQUEST_PROVIDER_FAILED", - $"Render request provider '{entry.id}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_REQUEST_PROVIDER_FAILED", + $"Render request provider '{entry.id}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } } @@ -162,11 +189,13 @@ private void CollectRendering(float deltaTime) private ContentReadScope GetFrameContentScope() { if (m_contentScopeProvider is null) + { return ContentReadScope.empty; + } try { return m_contentScopeProvider() - ?? throw new InvalidOperationException("The host content-scope provider returned null."); + ?? throw new InvalidOperationException("The host content-scope provider returned null."); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -174,11 +203,14 @@ private ContentReadScope GetFrameContentScope() } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_CONTENT_SCOPE_FAILED", - $"The host content scope failed and an empty scope was used for this frame: {exception}", - DiagnosticSeverity.Error, - "RenderRuntime")); + PublishFrameIssue( + new Diagnostic( + "RENDER_CONTENT_SCOPE_FAILED", + $"The host content scope failed and an empty scope was used for this frame: {exception}", + DiagnosticSeverity.Error, + "RenderRuntime" + ) + ); return ContentReadScope.empty; } } @@ -193,7 +225,9 @@ private void CompleteRendering(float deltaTime) { _ = deltaTime; if (!m_frameOpen) + { return; + } int executedViewCount = 0; int culledPassCount = 0; @@ -202,7 +236,9 @@ private void CompleteRendering(float deltaTime) try { lock (m_requestLock) + { m_acceptingCurrentFrame = false; + } RenderGraphBuilder graph = CreateGraph(); AddPrimaryPresentationBackground(graph); @@ -211,9 +247,15 @@ private void CompleteRendering(float deltaTime) int requestIndex = 0; RenderPresentationComposer presentation = m_scratch.presentation; foreach (RenderRequest request in m_currentRequests) + { m_scratch.scheduled.Add(new ScheduledWork(m_scratch.scheduled.Count, request.priority, request.name, request, null)); + } foreach (CompositionRequest composition in m_currentCompositions) - m_scratch.scheduled.Add(new ScheduledWork(m_scratch.scheduled.Count, composition.priority, composition.name, null, composition)); + { + m_scratch.scheduled.Add( + new ScheduledWork(m_scratch.scheduled.Count, composition.priority, composition.name, null, composition) + ); + } m_scratch.scheduled.Sort(static ( left, right @@ -221,7 +263,9 @@ private void CompleteRendering(float deltaTime) { int priority = left.priority.CompareTo(right.priority); if (priority != 0) + { return priority; + } int name = StringComparer.Ordinal.Compare(left.name, right.name); return name != 0 ? name : left.order.CompareTo(right.order); }); @@ -235,7 +279,9 @@ private void CompleteRendering(float deltaTime) RenderRequest request = work.request!; bool preservePresentationTarget = presentation.MustPreserve(request); if (TryBuildRequest(graph, request, requestIndex++, preservePresentationTarget)) + { presentation.Commit(request); + } } AddContributors(graph, m_scratch.contributors); @@ -265,9 +311,11 @@ private void CompleteRendering(float deltaTime) finally { m_scratch.Clear(); - m_frameContributors = RenderContributorSnapshot.empty; + m_frameContributors = RenderContributorSnapshot.EMPTY; if (!retirementPending) + { EndRenderingFrame(executedViewCount, culledPassCount, graphCompileCount); + } } } @@ -303,8 +351,14 @@ void CompleteFrameState() m_currentCompositions.Clear(); m_frameIndex++; m_graphicsSettings.frameStatistics = new RenderFrameStatistics( - m_frameIndex, executedViewCount, counters.drawCount, counters.dispatchCount, culledPassCount, - allocations, graphCompileCount); + m_frameIndex, + executedViewCount, + counters.drawCount, + counters.dispatchCount, + culledPassCount, + allocations, + graphCompileCount + ); } } @@ -313,7 +367,9 @@ private void CompleteViewContentFrame() foreach (RenderExtensionRegistry.ContentSourceEntry entry in m_extensions.extensions.sources.sources) { if (entry.source is not IViewContentFrameSource source) + { continue; + } try { source.CompleteFrame(m_frameIndex); @@ -324,9 +380,14 @@ private void CompleteViewContentFrame() } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_VIEW_CONTENT_FRAME_FAILED", - $"View content source '{entry.id}' failed to complete its frame: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_VIEW_CONTENT_FRAME_FAILED", + $"View content source '{entry.id}' failed to complete its frame: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } } @@ -335,7 +396,9 @@ private RenderGraphBuilder CreateGraph() { m_graphGeneration++; if (m_graphGeneration == 0) + { m_graphGeneration++; + } return new RenderGraphBuilder(m_graphGeneration, m_device.capabilities); } @@ -343,8 +406,6 @@ private sealed class ViewContentSink : IViewContentSink { private readonly List m_items = []; - internal IReadOnlyList items => m_items; - /// /// Submits validated work to the active backend for ordered processing. /// @@ -356,6 +417,7 @@ public void Submit(ViewContentItem item) ArgumentNullException.ThrowIfNull(item); m_items.Add(item); } - } + internal IReadOnlyList items => m_items; + } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs index 1a469aa17..2a3f40b7e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Sets the explicit model composition route for the primary output at a frame boundary. @@ -26,7 +26,9 @@ public void SetPrimaryRoute(RenderOutputRoute? route) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Output routes can only change at a frame boundary."); + } m_primaryRoute = route; } @@ -41,9 +43,10 @@ public void SetPrimaryModelOutputEnabled(bool enabled) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Primary output ownership can only change at a frame boundary."); + } m_primaryModelOutputEnabled = enabled; - } private void CollectModels(RenderOutputSession session) @@ -56,13 +59,20 @@ private void CollectModels(RenderOutputSession session) try { if (entry.model.CanRender(session)) + { applicable.Add(entry); + } } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_MODEL_ACCEPT_FAILED", - $"Render model '{entry.id}' failed to inspect output content: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_MODEL_ACCEPT_FAILED", + $"Render model '{entry.id}' failed to inspect output content: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } if (applicable.Count == 0) @@ -84,7 +94,7 @@ private void CollectModels(RenderOutputSession session) int match = -1; for (int candidate = 0; candidate < applicable.Count; candidate++) { - if (applicable[candidate].id == layer.modelId) + if (applicable[candidate].id == layer.modelID) { match = candidate; break; @@ -100,12 +110,16 @@ private void CollectModels(RenderOutputSession session) } else if (applicable.Count > 1) { - PublishModelDiagnostic("Multiple rendering models accept the primary output; configure a RenderOutputRoute: " - + string.Join(", ", applicable.Select(static entry => entry.id))); + PublishModelDiagnostic( + "Multiple rendering models accept the primary output; configure a RenderOutputRoute: " + + string.Join(", ", applicable.Select(static entry => entry.id)) + ); return; } if (route is null) + { ordered.AddRange(applicable); + } List requests = m_scratch.modelRequests; RenderTextureFormat? format = null; @@ -115,8 +129,8 @@ private void CollectModels(RenderOutputSession session) try { RenderOutputSession modelSession = route is null - ? session - : session.ForLayer(route.layers[index]); + ? session + : session.ForLayer(route.layers[index]); RenderModelOutput model = entry.model.Build(modelSession); if (format is RenderTextureFormat selected && selected != model.targetFormat) { @@ -124,22 +138,45 @@ private void CollectModels(RenderOutputSession session) return; } format ??= model.targetFormat; - requests.Add(new RenderRequest(model.name, RenderTarget.backbuffer, session.viewport, - model.pipeline, model.data, 1000 + index)); + requests.Add( + new RenderRequest( + model.name, + RenderTarget.backbuffer, + session.viewport, + model.pipeline, + model.data, + 1000 + index + ) + ); } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_MODEL_BUILD_FAILED", - $"Render model '{entry.id}' failed to build output: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_MODEL_BUILD_FAILED", + $"Render model '{entry.id}' failed to build output: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); return; } } if (requests.Count == 1 && m_device.primaryPresentationEncodesSrgb) + { Submit(requests[0]); + } else - SubmitComposition($"Output:{session.id}", RenderTarget.backbuffer, - session.viewport, format!.Value, requests, priority: 1000); + { + SubmitComposition( + $"Output:{session.id}", + RenderTarget.backbuffer, + session.viewport, + format!.Value, + requests, + priority: 1000 + ); + } } finally { @@ -148,5 +185,4 @@ private void CollectModels(RenderOutputSession session) m_scratch.modelRequests.Clear(); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs index b6a294e82..9ca3effdd 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Validates and selects a project default while preserving its last-good generation. @@ -33,7 +33,9 @@ public bool TryActivateDefaultPipeline(RenderPipelineAsset pipelineAsset) EnsureActive(); ArgumentNullException.ThrowIfNull(pipelineAsset); if (m_frameOpen) + { throw new InvalidOperationException("A default pipeline can only change at a frame boundary."); + } if (TryGetGeneration(pipelineAsset, out _)) { m_graphicsSettings.defaultPipeline = pipelineAsset; @@ -56,9 +58,13 @@ public IRenderRuntimeReloadTransaction BeginExtensionReload() { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Rendering extensions can only reload at a frame boundary."); + } if (m_reloadSession is not null) + { throw new InvalidOperationException("A rendering extension reload is already active."); + } m_reloadSession = RenderRuntimeReloadSession.Create(this); return m_reloadSession; @@ -82,13 +88,16 @@ out RenderPipelineGeneration? generation catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_REGISTRY_FAILED", - $"Rendering extension discovery kept every last-good generation: {exception.Message}", - DiagnosticSeverity.Error, - asset.pipelineTypeId)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_REGISTRY_FAILED", + $"Rendering extension discovery kept every last-good generation: {exception.Message}", + DiagnosticSeverity.Error, + asset.pipelineTypeId + ) + ); return m_generations.TryGetValue(asset, out GenerationCacheEntry? failedEntry) - && (generation = failedEntry.lastGood) is not null; + && (generation = failedEntry.lastGood) is not null; } m_diagnostics.Resolve("RENDER_EXTENSION_REGISTRY_FAILED", asset.pipelineTypeId); @@ -99,15 +108,15 @@ out RenderPipelineGeneration? generation } if (entry.lastGood is not null - && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion) - { + && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion + ) { m_extensions.Retire(entry.lastGood); entry.lastGood = null; } if (entry.attemptedTypeCacheVersion == snapshot.typeCacheVersion - && string.Equals(entry.attemptedFingerprint, fingerprint, StringComparison.Ordinal)) - { + && string.Equals(entry.attemptedFingerprint, fingerprint, StringComparison.Ordinal) + ) { generation = entry.lastGood; return generation is not null; } @@ -130,11 +139,14 @@ out RenderPipelineGeneration? generation catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_GENERATION_FAILED", - $"Pipeline '{asset.pipelineTypeId}' kept its last-good generation: {exception.Message}", - DiagnosticSeverity.Error, - asset.pipelineTypeId)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_GENERATION_FAILED", + $"Pipeline '{asset.pipelineTypeId}' kept its last-good generation: {exception.Message}", + DiagnosticSeverity.Error, + asset.pipelineTypeId + ) + ); generation = entry.lastGood; return generation is not null; } @@ -146,17 +158,12 @@ out RenderPipelineGeneration? generation return generation is not null; } - private static bool TryCreateGeneration( - RenderExtensionRegistry.Snapshot snapshot, - RenderPipelineAsset asset, - out RenderPipelineGeneration? generation - ) - => snapshot.TryCreateGeneration(asset, out generation); - private void EndReloadSession(RenderRuntimeReloadSession session) { if (ReferenceEquals(m_reloadSession, session)) + { m_reloadSession = null; + } } private void PruneRetiredGenerations() @@ -174,32 +181,38 @@ private void PruneRetiredGenerations() catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_REGISTRY_FAILED", - $"Rendering extension discovery kept the current frame available: {exception.Message}", - DiagnosticSeverity.Error)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_REGISTRY_FAILED", + $"Rendering extension discovery kept the current frame available: {exception.Message}", + DiagnosticSeverity.Error + ) + ); return; } m_diagnostics.Resolve("RENDER_EXTENSION_REGISTRY_FAILED"); if (m_prunedTypeCacheVersion == snapshot.typeCacheVersion) + { return; + } m_scratch.generations.AddRange(m_generations); try { foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in m_scratch.generations) { if (entry.lastGood is not null - && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion) - { + && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion + ) { m_extensions.Retire(entry.lastGood); entry.lastGood = null; } if (entry.attemptedTypeCacheVersion != snapshot.typeCacheVersion) + { m_generations.Remove(asset); + } } - } finally { @@ -207,8 +220,8 @@ private void PruneRetiredGenerations() } if (m_requestProviders is not null - && m_requestProviders.typeCacheVersion != snapshot.typeCacheVersion) - { + && m_requestProviders.typeCacheVersion != snapshot.typeCacheVersion + ) { m_requestProviders = null; } m_prunedTypeCacheVersion = snapshot.typeCacheVersion; @@ -222,8 +235,8 @@ RenderPipelineContext context foreach (RenderFeatureConfiguration configuration in asset.features) { if (!configuration.enabled - || !features.TryGetValue(configuration.featureTypeId, out RenderPipelineFeature? feature)) - { + || !features.TryGetValue(configuration.featureTypeId, out RenderPipelineFeature? feature) + ) { continue; } @@ -239,15 +252,24 @@ RenderPipelineContext context } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_FEATURE_FAILED", - $"Feature '{configuration.featureTypeId}' was rolled back: {exception.Message}", - DiagnosticSeverity.Error, - configuration.featureTypeId)); + PublishFrameIssue( + new Diagnostic( + "RENDER_FEATURE_FAILED", + $"Feature '{configuration.featureTypeId}' was rolled back: {exception.Message}", + DiagnosticSeverity.Error, + configuration.featureTypeId + ) + ); } } } + private static bool TryCreateGeneration( + RenderExtensionRegistry.Snapshot snapshot, + RenderPipelineAsset asset, + out RenderPipelineGeneration? generation + ) => snapshot.TryCreateGeneration(asset, out generation); + private sealed class GenerationCacheEntry(RenderPipelineAsset asset) { internal readonly Identity assetIdentity = asset.identity; @@ -266,13 +288,13 @@ private readonly record struct GenerationState( internal sealed class RenderRuntimeReloadSession : IRenderRuntimeReloadTransaction { private readonly RenderRuntime m_owner; + private readonly Dictionary m_candidates = []; private IReadOnlyDictionary? m_previous; private RenderExtensionRegistry.RequestProviderGeneration? m_previousRequestProviders; private RenderRequest[]? m_previousPendingRequests; private RenderRequest[]? m_previousCurrentRequests; private CompositionRequest[]? m_previousPendingCompositions; private CompositionRequest[]? m_previousCurrentCompositions; - private readonly Dictionary m_candidates = []; private RenderExtensionRegistry.RequestProviderGeneration? m_candidateRequestProviders; private bool m_prepared; private bool m_activated; @@ -296,36 +318,21 @@ CompositionRequest[] previousCurrentCompositions m_previousCurrentCompositions = previousCurrentCompositions; } - internal static RenderRuntimeReloadSession Create(RenderRuntime owner) - { - // Disposed sessions must not contribute obsolete assets to the next extension generation. - owner.PruneRetiredAssets(); - var previous = new Dictionary(); - foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in owner.m_generations) - { - previous.Add(asset, new GenerationState( - entry.attemptedTypeCacheVersion, - entry.attemptedFingerprint, - entry.lastGood)); - } - lock (owner.m_requestLock) - { - return new RenderRuntimeReloadSession( - owner, - previous, - owner.m_requestProviders, - [.. owner.m_pendingRequests], - [.. owner.m_currentRequests], - [.. owner.m_pendingCompositions], - [.. owner.m_currentCompositions]); - } - } + void IRenderRuntimeReloadTransaction.Prepare() => PrepareCandidate(); + + void IRenderRuntimeReloadTransaction.Activate() => Activate(); + + void IRenderRuntimeReloadTransaction.Complete() => Complete(); + + void IRenderRuntimeReloadTransaction.Rollback() => Rollback(); internal void PrepareCandidate() { EnsureNotFinished(); if (m_prepared) + { return; + } RenderExtensionRegistry.Snapshot snapshot = m_owner.m_extensions.extensions; try @@ -335,10 +342,7 @@ internal void PrepareCandidate() { string fingerprint = RenderExtensionRegistry.GetConfigurationFingerprint(asset); _ = TryCreateGeneration(snapshot, asset, out RenderPipelineGeneration? candidate); - m_candidates.Add(asset, new GenerationState( - snapshot.typeCacheVersion, - fingerprint, - candidate)); + m_candidates.Add(asset, new GenerationState(snapshot.typeCacheVersion, fingerprint, candidate)); } m_prepared = true; } @@ -349,14 +353,15 @@ internal void PrepareCandidate() catch (Exception exception) { DisposeCandidates(); - m_owner.m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_RELOAD_REJECTED", - "Rendering extension candidate was rejected and every last-good generation was retained: " + - exception.Message, - DiagnosticSeverity.Error)); - throw new InvalidOperationException( - "Rendering extension candidate activation failed.", - exception); + m_owner.m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_RELOAD_REJECTED", + "Rendering extension candidate was rejected and every last-good generation was retained: " + + exception.Message, + DiagnosticSeverity.Error + ) + ); + throw new InvalidOperationException("Rendering extension candidate activation failed.", exception); } } @@ -364,14 +369,20 @@ internal void Activate() { EnsureNotFinished(); if (!m_prepared) + { throw new InvalidOperationException("Rendering extension candidates have not been prepared."); + } if (m_activated) + { return; + } foreach (RenderPipelineAsset asset in m_candidates.Keys) { if (!m_owner.m_generations.ContainsKey(asset)) + { throw new InvalidOperationException("A tracked rendering generation changed during reload."); + } } foreach ((RenderPipelineAsset asset, GenerationState candidate) in m_candidates) { @@ -396,14 +407,18 @@ internal void Complete() { EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Rendering extension candidates have not been activated."); + } try { var resources = new LifetimeScope(); foreach (GenerationState previous in m_previous!.Values) { if (previous.lastGood is not null) + { resources.Own(previous.lastGood); + } } m_owner.m_extensions.Retire(resources); } @@ -423,14 +438,18 @@ internal void Complete() internal void Rollback() { if (m_finished) + { return; + } if (m_activated) { foreach ((RenderPipelineAsset asset, GenerationState previous) in m_previous!) { if (!m_owner.m_generations.TryGetValue(asset, out GenerationCacheEntry? entry)) + { continue; + } entry.attemptedTypeCacheVersion = previous.attemptedTypeCacheVersion; entry.attemptedFingerprint = previous.attemptedFingerprint; entry.lastGood = previous.lastGood; @@ -464,13 +483,31 @@ internal void Rollback() Finish(); } - void IRenderRuntimeReloadTransaction.Prepare() => PrepareCandidate(); - - void IRenderRuntimeReloadTransaction.Activate() => Activate(); - - void IRenderRuntimeReloadTransaction.Complete() => Complete(); - - void IRenderRuntimeReloadTransaction.Rollback() => Rollback(); + internal static RenderRuntimeReloadSession Create(RenderRuntime owner) + { + // Disposed sessions must not contribute obsolete assets to the next extension generation. + owner.PruneRetiredAssets(); + var previous = new Dictionary(); + foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in owner.m_generations) + { + previous.Add( + asset, + new GenerationState(entry.attemptedTypeCacheVersion, entry.attemptedFingerprint, entry.lastGood) + ); + } + lock (owner.m_requestLock) + { + return new RenderRuntimeReloadSession( + owner, + previous, + owner.m_requestProviders, + [.. owner.m_pendingRequests], + [.. owner.m_currentRequests], + [.. owner.m_pendingCompositions], + [.. owner.m_currentCompositions] + ); + } + } private void DisposeCandidates() { @@ -478,7 +515,9 @@ private void DisposeCandidates() foreach (GenerationState candidate in m_candidates.Values) { if (candidate.lastGood is not null) + { resources.Own(candidate.lastGood); + } } m_owner.m_extensions.Retire(resources); m_candidates.Clear(); @@ -502,8 +541,9 @@ private void Finish() private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Rendering extension reload session is already finished."); + } } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs index 02a118e18..38d5e04dd 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs @@ -1,34 +1,37 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize size) { var fullViewport = new RenderViewport(0, 0, size.width, size.height); if (m_primaryPresentationViewportProvider is null) + { return fullViewport; + } try { RenderViewport viewport = m_primaryPresentationViewportProvider(size); if ((long)viewport.x + viewport.width > size.width - || (long)viewport.y + viewport.height > size.height) - { + || (long)viewport.y + viewport.height > size.height + ) { throw new InvalidOperationException( - "The configured viewport extends beyond the primary presentation surface."); + "The configured viewport extends beyond the primary presentation surface." + ); } return viewport; } @@ -38,11 +41,14 @@ private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_PRESENTATION_VIEWPORT_FAILED", - $"The primary presentation viewport was invalid and the complete surface was used: {exception.Message}", - DiagnosticSeverity.Error, - "RenderRuntime")); + PublishFrameIssue( + new Diagnostic( + "RENDER_PRESENTATION_VIEWPORT_FAILED", + $"The primary presentation viewport was invalid and the complete surface was used: {exception.Message}", + DiagnosticSeverity.Error, + "RenderRuntime" + ) + ); return fullViewport; } } @@ -50,46 +56,64 @@ private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize private RenderOutputInput CreatePrimaryOutputInput(InputSnapshot input) { if (m_primaryPresentationSize is not RenderPresentationSize physicalSize - || m_primaryPresentationViewport is not RenderViewport viewport) + || m_primaryPresentationViewport is not RenderViewport viewport + ) { return RenderOutputInput.suspended; + } Vector2 pointerPosition = input.mousePosition; if (m_primaryInputSurfaceSizeProvider is not null) { RenderPresentationSize? inputSize = m_primaryInputSurfaceSizeProvider(); if (inputSize is not RenderPresentationSize logicalSize) + { return RenderOutputInput.suspended; + } if (!logicalSize.isValid) + { throw new InvalidOperationException("The primary input surface has an invalid logical size."); + } pointerPosition = new Vector2( pointerPosition.x * physicalSize.width / logicalSize.width, - pointerPosition.y * physicalSize.height / logicalSize.height); + pointerPosition.y * physicalSize.height / logicalSize.height + ); } Vector2 pointer = pointerPosition - new Vector2(viewport.x, viewport.y); return new RenderOutputInput( - pointer, pointer.x >= 0f && pointer.y >= 0f && pointer.x < viewport.width && pointer.y < viewport.height, - input.scrollDelta, input.modifiers, input.keysPressed, input.keysReleased, - input.mouseButtonsPressed, input.mouseButtonsReleased, input.textInput); + pointer, + pointer.x >= 0f && pointer.y >= 0f && pointer.x < viewport.width && pointer.y < viewport.height, + input.scrollDelta, + input.modifiers, + input.keysPressed, + input.keysReleased, + input.mouseButtonsPressed, + input.mouseButtonsReleased, + input.textInput + ); } private void AddPrimaryPresentationBackground(RenderGraphBuilder graph) { if (m_primaryPresentationSize is not RenderPresentationSize size - || m_primaryPresentationViewport is not RenderViewport viewport) + || m_primaryPresentationViewport is not RenderViewport viewport + ) { return; + } if (viewport.x == 0 && viewport.y == 0 && viewport.width == size.width && viewport.height == size.height) { return; } - graph.AddRasterPass( + graph + .AddRasterPass( "Primary Presentation Background", - S_PRESENTATION_BACKGROUND_PHASE, + PRESENTATION_BACKGROUND_PHASE, 0, static ( _, _ - ) => { }) - .ClearPresentationTarget(S_PRESENTATION_BACKGROUND_COLOR) + ) => {} + ) + .ClearPresentationTarget(PRESENTATION_BACKGROUND_COLOR) .HasSideEffect(); } @@ -99,38 +123,57 @@ private void BuildComposition( ref int requestIndex ) { if (composition.target.kind == RenderTargetKind.Backbuffer && !m_primaryPresentationSize.HasValue) + { return; + } try { using RenderGraphMutationScope mutation = graph.BeginMutationScope(); - using RenderGraphNameScope names = graph.BeginNameScope( - $"Composition {composition.name}"); + using RenderGraphNameScope names = graph.BeginNameScope($"Composition {composition.name}"); var layers = new List(composition.layers.Length); for (int index = 0; index < composition.layers.Length; index++) { RenderTextureHandle color = graph.CreateTexture( $"Model Layer {index + 1}", new RenderTextureDescriptor( - composition.viewport.width, composition.viewport.height, + composition.viewport.width, + composition.viewport.height, composition.format, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); RenderRequest layer = composition.layers[index]; - var localLayer = new RenderRequest(layer.name, layer.target, + var localLayer = new RenderRequest( + layer.name, + layer.target, new RenderViewport(0, 0, composition.viewport.width, composition.viewport.height), - layer.pipeline, layer.data, layer.priority); - if (!TryBuildRequest(graph, localLayer, requestIndex++, - preservePresentationTarget: false, outputOverride: color)) + layer.pipeline, + layer.data, + layer.priority + ); + if (!TryBuildRequest( + graph, + localLayer, + requestIndex++, + preservePresentationTarget: false, + outputOverride: color + )) { return; + } layers.Add(color); } RenderTextureHandle output = composition.target.kind == RenderTargetKind.Texture - ? targets.Import(graph, composition.target.texture - ?? throw new InvalidOperationException("A texture output requires a RenderTexture.")) - : default; - m_compositor.AddPasses(graph, composition.name, layers, output, - composition.viewport, composition.format); + ? targets.Import( + graph, + composition.target.texture + ?? throw new InvalidOperationException("A texture output requires a RenderTexture.") + ) + : default; + m_compositor.AddPasses(graph, composition.name, layers, output, composition.viewport, composition.format); if (output.isValid) + { graph.MarkOutput(output); + } RenderGraphValidationResult validation = graph.Validate(); if (!validation.isValid) { @@ -145,12 +188,14 @@ ref int requestIndex } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_OUTPUT_COMPOSITION_FAILED", - $"Output composition '{composition.name}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - composition.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_OUTPUT_COMPOSITION_FAILED", + $"Output composition '{composition.name}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + composition.name + ) + ); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs index 361832668..e989cd229 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Submits validated work to the active backend for ordered processing. @@ -36,8 +36,10 @@ public void Submit(RenderRequest request) { EnsureActive(); if (m_currentRequests.Count + m_pendingRequests.Count - + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS) + + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS + ) { throw new InvalidOperationException("The rendering request queue is at capacity."); + } (m_acceptingCurrentFrame ? m_currentRequests : m_pendingRequests).Add(request); } } @@ -80,20 +82,27 @@ public void SubmitComposition( ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(layers); if (layers.Count == 0 || layers.Any(static layer => layer is null)) + { throw new ArgumentException("A composition requires at least one non-null model layer.", nameof(layers)); + } if (layers.Any(layer => layer.viewport != viewport || layer.target != target)) + { throw new ArgumentException("All composition layers must name the same final target and viewport.", nameof(layers)); + } if (!m_device.capabilities.SupportsRenderTarget(format) - || !m_device.capabilities.SupportsSampled(format)) + || !m_device.capabilities.SupportsSampled(format) + ) { throw new ArgumentException($"The device cannot sample and render model layers in '{format}'.", nameof(format)); - var composition = new CompositionRequest(name, target, viewport, format, - layers.ToArray(), priority); + } + var composition = new CompositionRequest(name, target, viewport, format, layers.ToArray(), priority); lock (m_requestLock) { EnsureActive(); if (m_currentRequests.Count + m_pendingRequests.Count - + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS) + + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS + ) { throw new InvalidOperationException("The rendering request queue is at capacity."); + } (m_acceptingCurrentFrame ? m_currentCompositions : m_pendingCompositions).Add(composition); } } @@ -106,36 +115,45 @@ private bool TryBuildRequest( RenderTextureHandle outputOverride = default ) { if (request.target.kind == RenderTargetKind.Backbuffer && !outputOverride.isValid && !m_primaryPresentationSize.HasValue) + { return false; + } RenderPipelineAsset? asset = request.pipeline ?? m_graphicsSettings.defaultPipeline; if (asset is null) { - PublishFrameIssue(new Diagnostic( - "RENDER_PIPELINE_UNAVAILABLE", - $"Render request '{request.name}' has no pipeline. The frame and UI remain active.", - DiagnosticSeverity.Warning, - request.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_PIPELINE_UNAVAILABLE", + $"Render request '{request.name}' has no pipeline. The frame and UI remain active.", + DiagnosticSeverity.Warning, + request.name + ) + ); return false; } if (!TryGetGeneration(asset, out RenderPipelineGeneration? generation)) + { return false; + } try { using RenderGraphMutationScope mutation = graph.BeginMutationScope(); - using RenderGraphNameScope names = graph.BeginNameScope( - $"Request[{requestIndex}] {request.name}"); + using RenderGraphNameScope names = graph.BeginNameScope($"Request[{requestIndex}] {request.name}"); RenderTextureHandle outputTexture = outputOverride.isValid - ? outputOverride - : request.target.kind == RenderTargetKind.Texture - ? targets.Import( - graph, - request.target.texture - ?? throw new InvalidOperationException("A texture target requires a RenderTexture.")) - : default; + ? outputOverride + : request.target.kind == RenderTargetKind.Texture + ? targets.Import( + graph, + request.target.texture + ?? throw new InvalidOperationException("A texture target requires a RenderTexture.") + ) + : default; if (outputTexture.isValid && !outputOverride.isValid) + { graph.MarkOutput(outputTexture); + } var context = new RenderPipelineContext( request, @@ -148,7 +166,8 @@ private bool TryBuildRequest( m_uploads, m_frameIndex, preservePresentationTarget, - outputTexture); + outputTexture + ); generation!.pipeline.Build(context); AddFeatures(asset, generation.features, context); RenderGraphValidationResult validation = graph.Validate(); @@ -166,19 +185,19 @@ private bool TryBuildRequest( } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_REQUEST_FAILED", - $"Render request '{request.name}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - request.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_REQUEST_FAILED", + $"Render request '{request.name}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + request.name + ) + ); return false; } } - private void EnsureRequestProviders() - { - m_requestProviders = m_extensions.extensions.providers; - } + private void EnsureRequestProviders() => m_requestProviders = m_extensions.extensions.providers; private sealed record CompositionRequest( string name, @@ -196,5 +215,4 @@ private readonly record struct ScheduledWork( RenderRequest? request, CompositionRequest? composition ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs index 7b47d446d..f19dba7cf 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs @@ -1,20 +1,20 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Detaches this feature and releases generation-scoped state. @@ -22,7 +22,9 @@ sealed partial class RenderRuntime private void ReleaseRendering() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); @@ -44,8 +46,8 @@ private void ReleaseRendering() lock (m_contributorLock) { m_contributors.Clear(); - m_contributorSnapshot = RenderContributorSnapshot.empty; - m_frameContributors = RenderContributorSnapshot.empty; + m_contributorSnapshot = RenderContributorSnapshot.EMPTY; + m_frameContributors = RenderContributorSnapshot.EMPTY; } m_scratch.Clear(); }); @@ -64,7 +66,9 @@ private void ReleaseRendering() m_retirement.Add(() => { if (m_frameOpen) + { _ = m_device.EndFrame(); + } m_frameOpen = false; }); m_retirement.Add(m_uploads.EndFrame); @@ -91,7 +95,9 @@ private void RetireGenerations() foreach (GenerationCacheEntry entry in m_generations.Values) { if (entry.lastGood is not null) + { resources.Add(entry.lastGood.Dispose); + } } try { @@ -116,7 +122,9 @@ private void PruneRetiredAssets() foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in m_generations) { if (entry.hasAssetOwner && !ReferenceEquals(entry.assetIdentity.Resolve(), asset)) + { m_retiredAssets.Add(asset); + } } foreach (RenderPipelineAsset asset in m_retiredAssets) { @@ -129,5 +137,4 @@ private void PruneRetiredAssets() m_retiredAssets.Clear(); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs index 83993eeaf..e3c755505 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -20,9 +20,10 @@ namespace Inno.Rendering.Runtime; public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink, IViewContentCollector { private const int C_MAX_QUEUED_REQUESTS = 4096; - private static readonly RenderPhaseId S_PRESENTATION_BACKGROUND_PHASE = new( - "inno.runtime.presentation-background"); - private static readonly RenderClearColor S_PRESENTATION_BACKGROUND_COLOR = new(0f, 0f, 0f, 1f); + + private static readonly RenderPhaseID PRESENTATION_BACKGROUND_PHASE = new("inno.runtime.presentation-background"); + + private static readonly RenderClearColor PRESENTATION_BACKGROUND_COLOR = new(0f, 0f, 0f, 1f); private readonly object m_requestLock = new(); private readonly object m_contributorLock = new(); @@ -45,11 +46,11 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink private readonly List m_currentCompositions = []; private readonly List m_contributors = []; private readonly RenderFrameScratch m_scratch = new(); - private RenderContributorSnapshot m_contributorSnapshot = RenderContributorSnapshot.empty; - private RenderContributorSnapshot m_frameContributors = RenderContributorSnapshot.empty; - private long m_prunedTypeCacheVersion = -1; private readonly Dictionary m_previousFrameIssues = []; private readonly Dictionary m_currentFrameIssues = []; + private RenderContributorSnapshot m_contributorSnapshot = RenderContributorSnapshot.EMPTY; + private RenderContributorSnapshot m_frameContributors = RenderContributorSnapshot.EMPTY; + private long m_prunedTypeCacheVersion = -1; private ulong m_frameIndex; private uint m_graphGeneration; private RenderExtensionRegistry.RequestProviderGeneration? m_requestProviders; @@ -67,12 +68,12 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// /// Creates a render runtime without installing any concrete pipeline. /// - /// - /// Active backend-neutral device. - /// /// /// The type catalog that owns render extension generations. /// + /// + /// Active backend-neutral device. + /// /// /// Owner-bound structured diagnostic producer. /// @@ -90,10 +91,6 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// Optional host callback that selects the content region within the primary presentation surface. /// The complete surface is used when omitted. /// - /// - /// The contributor sequence contains a null entry or the same contributor more than once. - /// No rendering generation is registered in this case. - /// /// /// Finite native cache and asynchronous readback limits; omitted values use the engine defaults. /// @@ -106,6 +103,10 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// /// Backend-specific program provider used when the host composites multiple render layers. /// + /// + /// The contributor sequence contains a null entry or the same contributor more than once. + /// No rendering generation is registered in this case. + /// public RenderRuntime( TypeCatalog types, IRenderDevice device, @@ -120,16 +121,20 @@ public RenderRuntime( IRenderLayerCompositionProgramProvider? compositionProgramProvider = null ) { ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(device); + ArgumentNullException.ThrowIfNull(diagnostics); resourceLimits ??= new RenderResourceLimits(); resourceLimits.Validate(); - m_device = device ?? throw new ArgumentNullException(nameof(device)); - m_diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics)); + m_device = device; + m_diagnostics = diagnostics; if (contributors is not null) { foreach (IRenderFrameGraphContributor contributor in contributors) { if (contributor is null || m_contributors.Contains(contributor)) + { throw new ArgumentException("Initial contributors must contain unique non-null instances.", nameof(contributors)); + } m_contributors.Add(contributor); } } @@ -140,14 +145,10 @@ public RenderRuntime( m_primaryPresentationViewportProvider = primaryPresentationViewportProvider; m_extensions = new RenderExtensionRegistry(types); m_graphicsSettings = new GraphicsSettingsState(m_device.capabilities); - m_resourceService = new RenderResourceService( - m_device, - m_diagnostics, - targetArtifacts, - resourceLimits); + m_resourceService = new RenderResourceService(m_device, m_diagnostics, targetArtifacts, resourceLimits); m_uploads = new RenderFrameUploadService(m_device, resourceLimits); m_compositor = new RenderLayerCompositor(m_device, compositionProgramProvider); - targets = new RenderTargetStore(device, resourceLimits.targets); + this.targets = new RenderTargetStore(device, resourceLimits.targets); } /// @@ -170,6 +171,26 @@ public RenderRuntime( /// public ulong currentFrameIndex => m_frameIndex; + /// + /// Gets the non-zero rendering-device generation that owns persistent handles. + /// + public uint deviceGeneration => m_device.generation; + + /// + /// Gets a detached control-thread snapshot of resource occupancy, high-water marks and rejected admissions. + /// + public RenderResourceStatistics resourceStatistics + => m_resourceService.statistics with + { + uploadPages = m_uploads.pageCount, + uploadResidentBytes = m_uploads.residentBytes, + uploadPeakBytes = m_uploads.peakResidentBytes, + uploadedFrameBytes = m_uploads.frameBytes, + rejectedUploads = m_uploads.rejectedCount, + targets = targets.count, + rejectedTargets = targets.rejectedCount + }; + /// /// Collects frame requests from rendering models and registered providers. /// @@ -186,9 +207,11 @@ public IReadOnlyList Collect(ViewContentContext context) var sink = new ViewContentSink(); foreach (RenderExtensionRegistry.ContentSourceEntry entry in m_extensions.extensions.sources.sources) { - if (context.sourceIds is { } sourceIds - && !sourceIds.Contains(entry.id, StringComparer.Ordinal)) + if (context.sourceIDs is { } sourceIDs + && !sourceIDs.Contains(entry.id, StringComparer.Ordinal) + ) { continue; + } try { entry.source.Collect(context, sink); @@ -199,31 +222,19 @@ public IReadOnlyList Collect(ViewContentContext context) } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_VIEW_CONTENT_SOURCE_FAILED", - $"View content source '{entry.id}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_VIEW_CONTENT_SOURCE_FAILED", + $"View content source '{entry.id}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } return sink.items; } - /// - /// Gets the non-zero rendering-device generation that owns persistent handles. - /// - public uint deviceGeneration => m_device.generation; - - /// - /// Gets a detached control-thread snapshot of resource occupancy, high-water marks and rejected admissions. - /// - public RenderResourceStatistics resourceStatistics => m_resourceService.statistics with - { - uploadPages = m_uploads.pageCount, uploadResidentBytes = m_uploads.residentBytes, - uploadPeakBytes = m_uploads.peakResidentBytes, uploadedFrameBytes = m_uploads.frameBytes, - rejectedUploads = m_uploads.rejectedCount, targets = targets.count, rejectedTargets = targets.rejectedCount - }; - /// /// Binds this rendering runtime to script-facing graphics APIs for the current asynchronous execution flow. /// @@ -245,23 +256,21 @@ public IDisposable EnterExecutionScope() /// /// Attaches this feature to its owning runtime generation. /// - protected override void OnStart() - { - EnsureActive(); - } + protected override void OnStart() => EnsureActive(); + + /// + /// Releases every runtime rendering generation, persistent target, upload, and GPU resource + /// owned by this instance. + /// + protected override void OnStop() => ReleaseRendering(); private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_retirement is not null) + { throw new InvalidOperationException("Rendering retirement has started and cannot accept new work."); + } m_extensions.EnsureHealthy(); } - - /// - /// Releases every runtime rendering generation, persistent target, upload, and GPU resource - /// owned by this instance. - /// - protected override void OnStop() => ReleaseRendering(); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs index 2950b6817..7c1dd0a3b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -20,16 +19,18 @@ public sealed class RenderRuntimeFactory : IRuntimeSubsystemFactory /// public RenderRuntimeFactory(Func runtimeFactory) { - m_runtimeFactory = runtimeFactory ?? throw new ArgumentNullException(nameof(runtimeFactory)); + ArgumentNullException.ThrowIfNull(runtimeFactory); + m_runtimeFactory = runtimeFactory; } /// /// Gets stable ordering metadata that places rendering after simulation features. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.rendering"), + new RuntimeSubsystemID("inno.runtime.rendering"), order: 1000, - lifetime: RuntimeSubsystemLifetime.Host); + lifetime: RuntimeSubsystemLifetime.Host + ); /// /// Creates a rendering feature over a newly allocated runtime layer. @@ -44,7 +45,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); RenderRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The rendering runtime factory returned null."); + ?? throw new InvalidOperationException("The rendering runtime factory returned null."); return runtime; } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs index ee3a38e4b..da68861a1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs @@ -12,13 +12,13 @@ public sealed class RenderTargetStore : IDisposable { private readonly IRenderDevice m_device; private readonly int m_capacity; - private int m_frameAllocations; - private long m_rejected; - private RenderRetirementQueue? m_frameRetirement; private readonly Dictionary m_targets = []; private readonly HashSet m_pendingReleases = []; private readonly List m_retireNextFrame = []; private readonly List m_retireFollowingFrame = []; + private int m_frameAllocations; + private long m_rejected; + private RenderRetirementQueue? m_frameRetirement; private bool m_disposed; private RenderRetirementQueue? m_retirement; @@ -35,7 +35,8 @@ public RenderTargetStore( IRenderDevice device, int capacity = 1024 ) { - m_device = device ?? throw new ArgumentNullException(nameof(device)); + ArgumentNullException.ThrowIfNull(device); + m_device = device; ArgumentOutOfRangeException.ThrowIfNegativeOrZero(capacity); m_capacity = capacity; } @@ -73,8 +74,8 @@ RenderTexture target if (!m_targets.TryGetValue(target, out TargetEntry? entry) || entry.revision != target.contentRevision - || !entry.descriptor.Equals(target.descriptor)) - { + || !entry.descriptor.Equals(target.descriptor) + ) { if ((entry is null && m_targets.Count >= m_capacity) || m_frameAllocations >= m_capacity) { m_rejected++; @@ -83,7 +84,9 @@ RenderTexture target PersistentTextureHandle next = m_device.CreateTexture(target.descriptor, target.name); m_frameAllocations++; if (entry is not null) + { Retire(entry.handle); + } entry = new TargetEntry(target.contentRevision, target.descriptor, next); m_targets[target] = entry; } @@ -119,21 +122,6 @@ out PersistentTextureHandle texture return false; } - /// - /// Publishes target availability only after the backend recorded a graph write to its active revision. - /// - /// - /// The graph whose backend command recording completed without an exception. - /// - internal void MarkWrittenOutputs(CompiledRenderGraph graph) - { - ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); - ArgumentNullException.ThrowIfNull(graph); - foreach (TargetEntry entry in m_targets.Values) - if (!entry.hasWritten && WritesTarget(graph, entry.handle)) - entry.hasWritten = true; - } - /// /// Queues one target for frame-safe retirement. /// @@ -145,7 +133,9 @@ public void Release(RenderTexture target) ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); ArgumentNullException.ThrowIfNull(target); if (m_targets.ContainsKey(target)) + { m_pendingReleases.Add(target); + } } /// @@ -162,7 +152,9 @@ public void PrepareFrame() { m_frameRetirement = new RenderRetirementQueue(); foreach (PersistentTextureHandle texture in m_retireFollowingFrame) + { m_frameRetirement.Add(() => m_device.DestroyTexture(texture)); + } m_retireFollowingFrame.Clear(); } try @@ -186,7 +178,9 @@ public void PrepareFrame() foreach (RenderTexture target in m_pendingReleases) { if (m_targets.Remove(target, out TargetEntry? entry)) + { Retire(entry.handle); + } } m_pendingReleases.Clear(); } @@ -203,18 +197,28 @@ public void PrepareFrame() public void Dispose() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); if (m_frameRetirement is not null) + { m_retirement.Add(m_frameRetirement.Dispose); + } foreach (TargetEntry entry in m_targets.Values) + { m_retirement.Add(() => m_device.DestroyTexture(entry.handle)); + } foreach (PersistentTextureHandle texture in m_retireNextFrame) + { m_retirement.Add(() => m_device.DestroyTexture(texture)); + } foreach (PersistentTextureHandle texture in m_retireFollowingFrame) + { m_retirement.Add(() => m_device.DestroyTexture(texture)); + } } try { @@ -232,20 +236,23 @@ public void Dispose() CompleteRetirement(); } - private static bool WritesTarget( - CompiledRenderGraph graph, - PersistentTextureHandle handle - ) { - foreach (CompiledRenderTexture texture in graph.textures) + /// + /// Publishes target availability only after the backend recorded a graph write to its active revision. + /// + /// + /// The graph whose backend command recording completed without an exception. + /// + internal void MarkWrittenOutputs(CompiledRenderGraph graph) + { + ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); + ArgumentNullException.ThrowIfNull(graph); + foreach (TargetEntry entry in m_targets.Values) { - if (!texture.imported || texture.persistentHandle != handle) - continue; - foreach (CompiledRenderPass pass in graph.passes) - foreach (CompiledRenderAttachment attachment in pass.attachments) - if (attachment.texture == texture.handle) - return true; + if (!entry.hasWritten && WritesTarget(graph, entry.handle)) + { + entry.hasWritten = true; + } } - return false; } private void CompleteRetirement() @@ -260,7 +267,33 @@ private void CompleteRetirement() private void Retire(PersistentTextureHandle texture) { if (texture.isValid) + { m_retireNextFrame.Add(texture); + } + } + + private static bool WritesTarget( + CompiledRenderGraph graph, + PersistentTextureHandle handle + ) { + foreach (CompiledRenderTexture texture in graph.textures) + { + if (!texture.imported || texture.persistentHandle != handle) + { + continue; + } + foreach (CompiledRenderPass pass in graph.passes) + { + foreach (CompiledRenderAttachment attachment in pass.attachments) + { + if (attachment.texture == texture.handle) + { + return true; + } + } + } + } + return false; } private sealed record TargetEntry( diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs index 1191dd614..1a7f24442 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs @@ -1,12 +1,13 @@ -using Inno.Rendering; using System; +using Inno.Extensibility.Types; +using Inno.Rendering; namespace Inno.Rendering.Runtime; /// /// Accepts rendering-model-neutral requests without exposing runtime or backend ownership. /// -[Inno.Extensibility.Types.StableTypeId("53812496-61bc-5128-8cf9-2865a9319980")] +[StableTypeID("53812496-61bc-5128-8cf9-2865a9319980")] public interface IRenderRequestSink { /// @@ -17,4 +18,3 @@ public interface IRenderRequestSink /// void Submit(RenderRequest request); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs index 2e7b7c50e..712b520f8 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs @@ -1,7 +1,8 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Values may use reloadable plugin types because a snapshot is retained only until the owning /// render frame completes. Persistent configuration must use stable identifiers and serialized bytes. /// -[Inno.Extensibility.Types.StableTypeId("08a1cd24-757d-5026-a05d-a72ab9fd2b2b")] +[StableTypeID("08a1cd24-757d-5026-a05d-a72ab9fd2b2b")] public sealed class RenderFrameData { private readonly Dictionary m_values = []; @@ -39,15 +40,18 @@ public sealed class RenderFrameData /// Thrown after the data has entered a request. /// public void Set( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelID channel, TValue value - ) - where TValue : notnull + ) where TValue : notnull { if (!channel.isValid) + { throw new ArgumentException("A render data channel must be valid.", nameof(channel)); + } if (m_isReadOnly) + { throw new InvalidOperationException("Submitted render frame data is immutable."); + } ArgumentNullException.ThrowIfNull(value); m_values[new FrameDataKey(channel, typeof(TValue))] = value; } @@ -68,13 +72,13 @@ TValue value /// when the channel contains the exact requested type. /// public bool TryGet( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelID channel, out TValue? value ) { if (channel.isValid && m_values.TryGetValue(new FrameDataKey(channel, typeof(TValue)), out object? stored) - && stored is TValue typed) - { + && stored is TValue typed + ) { value = typed; return true; } @@ -92,7 +96,9 @@ out TValue? value public void Clear() { if (m_isReadOnly) + { throw new InvalidOperationException("Submitted render frame data is immutable."); + } m_values.Clear(); } @@ -100,14 +106,15 @@ internal RenderFrameData Snapshot() { var snapshot = new RenderFrameData(); foreach ((FrameDataKey key, object value) in m_values) + { snapshot.m_values.Add(key, value); + } snapshot.m_isReadOnly = true; return snapshot; } private readonly record struct FrameDataKey( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelID channel, Type type ); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs index 3fb6bb3fa..b64e0acc1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs @@ -1,14 +1,15 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Requests one pipeline-defined rendering operation without prescribing world semantics. /// -[Inno.Extensibility.Types.StableTypeId("b553fd8c-9410-53a7-8d8f-276e2a302e66")] +[StableTypeID("b553fd8c-9410-53a7-8d8f-276e2a302e66")] public sealed class RenderRequest { /// @@ -79,4 +80,3 @@ public RenderRequest( /// public int priority { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs index 3dcf3aeef..0aee1d9ea 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs @@ -1,164 +1,13 @@ -using Inno.Core.Execution; -using Inno.References; -using Inno.Rendering; using System; +using Inno.Core.Execution; +using Inno.Extensibility.Types; namespace Inno.Rendering.Runtime; -/// -/// Marks a reloadable provider that produces model-neutral render requests each frame. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] -public sealed class RenderRequestProviderExtensionAttribute : Attribute -{ - /// - /// Creates a render request provider declaration. - /// - /// - /// Globally stable provider identifier. - /// - /// - /// Provider invocation priority; lower values run first. - /// - public RenderRequestProviderExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable provider identifier. - /// - public string id { get; } - - /// - /// Gets the provider invocation priority. - /// - public int priority { get; } -} - -/// -/// Supplies frame timing, capabilities and the request sink to one provider invocation. -/// -[Inno.Extensibility.Types.StableTypeId("67067617-9592-55b2-bbb0-739c6927984b")] -public sealed class RenderRequestProviderContext -{ - /// - /// Creates a frame-scoped provider context. - /// - /// - /// Sink accepting requests for the current frame. - /// - /// - /// Host-selected content roots visible to request providers this frame. - /// - /// - /// Active backend-neutral capability snapshot. - /// - /// - /// Current primary pixel extent, or null while no primary output is available. - /// - /// - /// Host-selected content region, or null when the primary extent is unavailable. - /// - /// - /// Monotonic render frame index. - /// - /// - /// Elapsed frame time in seconds. - /// - /// - /// Collector for model-independent world items. - /// - /// - /// Viewport-local input for the primary output. - /// - public RenderRequestProviderContext( - IRenderRequestSink requests, - ContentReadScope content, - GraphicsCapabilities capabilities, - RenderPresentationSize? primaryPresentationSize, - RenderViewport? primaryPresentationViewport, - ulong frameIndex, - float deltaTime, - IViewContentCollector viewContent, - RenderOutputInput? input = null - ) { - this.requests = requests ?? throw new ArgumentNullException(nameof(requests)); - this.content = content ?? throw new ArgumentNullException(nameof(content)); - this.capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities)); - this.primaryPresentationSize = primaryPresentationSize; - if (primaryPresentationSize.HasValue != primaryPresentationViewport.HasValue) - throw new ArgumentException("Primary presentation size and viewport must have the same availability."); - if (primaryPresentationSize is RenderPresentationSize size && primaryPresentationViewport is RenderViewport viewport - && (!size.isValid || viewport.width <= 0 || viewport.height <= 0 - || (long)viewport.x + viewport.width > size.width - || (long)viewport.y + viewport.height > size.height)) - { - throw new ArgumentException( - "The primary presentation viewport must fit inside the primary presentation surface.", - nameof(primaryPresentationViewport)); - } - this.primaryPresentationViewport = primaryPresentationViewport; - this.frameIndex = frameIndex; - this.deltaTime = deltaTime; - this.viewContent = viewContent ?? throw new ArgumentNullException(nameof(viewContent)); - this.input = primaryPresentationSize.HasValue ? input ?? RenderOutputInput.empty : RenderOutputInput.suspended; - } - - /// - /// Gets the sink accepting requests for the current frame. - /// - public IRenderRequestSink requests { get; } - - /// - /// Gets the explicit ordered host content visible to request providers this frame. - /// - public ContentReadScope content { get; } - - /// - /// Gets the active backend-neutral capability snapshot. - /// - public GraphicsCapabilities capabilities { get; } - - /// - /// Gets the current primary pixel extent, or null while only offscreen outputs are available. - /// - public RenderPresentationSize? primaryPresentationSize { get; } - - /// - /// Gets the host-selected primary region, or null while no primary output is available. - /// - public RenderViewport? primaryPresentationViewport { get; } - - /// - /// Gets the monotonic render frame index. - /// - public ulong frameIndex { get; } - - /// - /// Gets the elapsed frame time in seconds. - /// - public float deltaTime { get; } - - /// - /// Gets the active generation's world-content collector. - /// - public IViewContentCollector viewContent { get; } - /// - /// Gets viewport-local input for the primary output. - /// - public RenderOutputInput input { get; } -} - /// /// Produces arbitrary render requests without prescribing a scene or rendering model. /// -[Inno.Extensibility.Types.StableTypeId("5c4302ea-8da5-5627-8fbe-f34ee7b2aec1")] +[StableTypeID("5c4302ea-8da5-5627-8fbe-f34ee7b2aec1")] public abstract class RenderRequestProvider : IDisposable { private bool m_disposed; @@ -180,7 +29,9 @@ public abstract class RenderRequestProvider : IDisposable public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -207,6 +58,5 @@ public void Dispose() /// /// Retirement cannot complete yet; subsequent calls resume this hook with its remaining owned resources. /// - protected virtual void Dispose(bool disposing) { } + protected virtual void Dispose(bool disposing) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs new file mode 100644 index 000000000..1a73b0c27 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs @@ -0,0 +1,127 @@ +using System; +using Inno.Extensibility.Types; +using Inno.References; + +namespace Inno.Rendering.Runtime; + +/// +/// Supplies frame timing, capabilities and the request sink to one provider invocation. +/// +[StableTypeID("67067617-9592-55b2-bbb0-739c6927984b")] +public sealed class RenderRequestProviderContext +{ + /// + /// Creates a frame-scoped provider context. + /// + /// + /// Sink accepting requests for the current frame. + /// + /// + /// Host-selected content roots visible to request providers this frame. + /// + /// + /// Active backend-neutral capability snapshot. + /// + /// + /// Current primary pixel extent, or null while no primary output is available. + /// + /// + /// Host-selected content region, or null when the primary extent is unavailable. + /// + /// + /// Monotonic render frame index. + /// + /// + /// Elapsed frame time in seconds. + /// + /// + /// Collector for model-independent world items. + /// + /// + /// Viewport-local input for the primary output. + /// + public RenderRequestProviderContext( + IRenderRequestSink requests, + ContentReadScope content, + GraphicsCapabilities capabilities, + RenderPresentationSize? primaryPresentationSize, + RenderViewport? primaryPresentationViewport, + ulong frameIndex, + float deltaTime, + IViewContentCollector viewContent, + RenderOutputInput? input = null + ) { + ArgumentNullException.ThrowIfNull(requests); + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(capabilities); + ArgumentNullException.ThrowIfNull(viewContent); + this.requests = requests; + this.content = content; + this.capabilities = capabilities; + this.primaryPresentationSize = primaryPresentationSize; + if (primaryPresentationSize.HasValue != primaryPresentationViewport.HasValue) + { + throw new ArgumentException("Primary presentation size and viewport must have the same availability."); + } + if (primaryPresentationSize is RenderPresentationSize size && primaryPresentationViewport is RenderViewport viewport + && (!size.isValid || viewport.width <= 0 || viewport.height <= 0 + || (long)viewport.x + viewport.width > size.width + || (long)viewport.y + viewport.height > size.height) + ) { + throw new ArgumentException( + "The primary presentation viewport must fit inside the primary presentation surface.", + nameof(primaryPresentationViewport) + ); + } + this.primaryPresentationViewport = primaryPresentationViewport; + this.frameIndex = frameIndex; + this.deltaTime = deltaTime; + this.viewContent = viewContent; + this.input = primaryPresentationSize.HasValue ? input ?? RenderOutputInput.empty : RenderOutputInput.suspended; + } + + /// + /// Gets the sink accepting requests for the current frame. + /// + public IRenderRequestSink requests { get; } + + /// + /// Gets the explicit ordered host content visible to request providers this frame. + /// + public ContentReadScope content { get; } + + /// + /// Gets the active backend-neutral capability snapshot. + /// + public GraphicsCapabilities capabilities { get; } + + /// + /// Gets the current primary pixel extent, or null while only offscreen outputs are available. + /// + public RenderPresentationSize? primaryPresentationSize { get; } + + /// + /// Gets the host-selected primary region, or null while no primary output is available. + /// + public RenderViewport? primaryPresentationViewport { get; } + + /// + /// Gets the monotonic render frame index. + /// + public ulong frameIndex { get; } + + /// + /// Gets the elapsed frame time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets the active generation's world-content collector. + /// + public IViewContentCollector viewContent { get; } + + /// + /// Gets viewport-local input for the primary output. + /// + public RenderOutputInput input { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs new file mode 100644 index 000000000..6f098ef8d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs @@ -0,0 +1,40 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Marks a reloadable provider that produces model-neutral render requests each frame. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[StableTypeID("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] +public sealed class RenderRequestProviderExtensionAttribute : Attribute +{ + /// + /// Creates a render request provider declaration. + /// + /// + /// Globally stable provider identifier. + /// + /// + /// Provider invocation priority; lower values run first. + /// + public RenderRequestProviderExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable provider identifier. + /// + public string id { get; } + + /// + /// Gets the provider invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs index ad0cf5e1f..acba8405c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs @@ -1,18 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Resolves neutral assets and provider-owned uploads into opaque resources for the active device generation. /// -[Inno.Extensibility.Types.StableTypeId("8f112b16-5cda-5171-949e-e2c5c4583b34")] +[StableTypeID("8f112b16-5cda-5171-949e-e2c5c4583b34")] public interface IRenderResourceService { /// @@ -87,7 +88,7 @@ public interface IRenderResourceService /// A handle owned by the active device generation. /// PersistentBufferHandle AcquireBuffer( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, PersistentBufferDescriptor descriptor, ReadOnlyMemory initialData, @@ -116,7 +117,7 @@ string name /// A handle owned by the active device generation. /// PersistentTextureHandle AcquireTexture( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, RenderTextureDescriptor descriptor, IReadOnlyList subresources, @@ -145,7 +146,7 @@ string name /// A handle owned by the active device generation. /// PersistentTextureHandle AcquireKtxTexture( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, ReadOnlyMemory containerData, bool sRgb, @@ -210,7 +211,7 @@ ValueTask ReadTextureAsync( /// A graphics pipeline owned by the active device generation. /// GraphicsPipelineHandle AcquireGraphicsPipeline( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, GraphicsPipelineDescriptor descriptor, string name @@ -235,7 +236,7 @@ string name /// A compute pipeline owned by the active device generation. /// ComputePipelineHandle AcquireComputePipeline( - RenderPersistentResourceId id, + RenderPersistentResourceID id, long revision, ComputePipelineDescriptor descriptor, string name @@ -247,10 +248,10 @@ string name /// /// Material asset to resolve. /// - /// + /// /// Provider-owned shader contract. /// - /// + /// /// Provider-owned pass role. /// /// @@ -267,8 +268,8 @@ string name /// bool TryResolveGraphicsMaterial( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, RenderVertexLayout? vertexLayout, MaterialPropertyBlock? overrides, out RenderMaterialPass? materialPass @@ -286,10 +287,10 @@ out RenderMaterialPass? materialPass /// /// Invocation-local values and a persistent Shader reference; neither asset is changed or retained. /// - /// + /// /// Required provider-owned Shader contract. /// - /// + /// /// Required role within the selected Technique. /// /// @@ -314,11 +315,11 @@ out RenderMaterialPass? materialPass /// No artifact decoder is configured, or resource retirement cannot complete. /// bool TryResolveMaterialArtifact( - RenderPersistentResourceId scope, + RenderPersistentResourceID scope, RenderShaderArtifact artifact, MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, ShaderProgramKind programKind, RenderVertexLayout? vertexLayout, MaterialPropertyBlock? overrides, @@ -332,10 +333,10 @@ out RenderMaterialPass? materialPass /// /// Material asset to resolve. /// - /// + /// /// Provider-owned shader contract. /// - /// + /// /// Provider-owned pass role. /// /// @@ -349,8 +350,8 @@ out RenderMaterialPass? materialPass /// bool TryResolveComputeMaterial( MaterialAsset material, - ShaderContractId contractId, - ShaderPassRoleId passRoleId, + ShaderContractID contractID, + ShaderPassRoleID passRoleID, MaterialPropertyBlock? overrides, out RenderMaterialPass? materialPass ); @@ -409,11 +410,12 @@ out PersistentTextureHandle resolvedTexture /// /// Releases cached resources with this provider-owned identifier at a safe GPU mutation point. /// - /// Calls between frames or during graph execution queue neutral identities until the next frame; - /// runtime shutdown also retires them. Calls must occur on the rendering owner thread. Unused identities are ignored. /// /// Stable resource identifier to release. /// - void Release(RenderPersistentResourceId id); + /// + /// Calls between frames or during graph execution queue neutral identities until the next frame; + /// runtime shutdown also retires them. Calls must occur on the rendering owner thread. Unused identities are ignored. + /// + void Release(RenderPersistentResourceID id); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs index 2c8183e08..defeb6e45 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs @@ -1,18 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Provides generation-scoped GPU buffers for an imported geometry helper asset. /// -[Inno.Extensibility.Types.StableTypeId("6ad78a05-1eae-5e6f-a5d2-ab40b6c35075")] +[StableTypeID("6ad78a05-1eae-5e6f-a5d2-ab40b6c35075")] public sealed class RenderGeometry { private readonly IReadOnlyList m_sections; @@ -96,11 +97,12 @@ public void DrawSection( ArgumentNullException.ThrowIfNull(commands); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(instanceCount); if ((uint)sectionIndex >= (uint)m_sections.Count) + { throw new ArgumentOutOfRangeException(nameof(sectionIndex)); + } RenderGeometrySection section = m_sections[sectionIndex]; commands.BindVertexBuffer(vertexBuffer); commands.BindIndexBuffer(indexBuffer, section.firstIndex); commands.DrawIndexed(section.indexCount, instanceCount); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs index 57016556f..47865d2c7 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs @@ -1,18 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Describes one indexed range in resolved backend-neutral geometry. /// -[Inno.Extensibility.Types.StableTypeId("fc4ae91b-3a0b-59d3-b65e-4c0c3533d715")] +[StableTypeID("fc4ae91b-3a0b-59d3-b65e-4c0c3533d715")] public readonly record struct RenderGeometrySection { /// @@ -44,4 +45,3 @@ int indexCount /// public int indexCount { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs index 4d16493b9..cc9a9e52e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs @@ -1,30 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; +using Inno.Extensibility.Types; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; -[Inno.Extensibility.Types.StableTypeId("b5677cc4-c195-5f52-a52f-5efecec8314e")] -internal enum RenderMaterialBindingKind -{ - Uniform, - Texture -} - -[Inno.Extensibility.Types.StableTypeId("702a1ec9-219b-5d44-b322-1a433e7e41b5")] -internal sealed record RenderMaterialBinding( - RenderMaterialBindingKind kind, - RenderBindingId id, - byte[]? uniformData, - PersistentTextureHandle texture, - RenderSamplerState sampler -); - /// /// Represents one frame-resolved material pass and its material-owned bindings. /// @@ -32,12 +13,12 @@ RenderSamplerState sampler /// The instance is scoped to the active render device generation. Pipeline-owned graph textures and /// buffers remain explicit and are bound by the caller after this material state is applied. /// -[Inno.Extensibility.Types.StableTypeId("b1566a8a-dd0a-5dca-8f43-6bb12aa86973")] +[StableTypeID("b1566a8a-dd0a-5dca-8f43-6bb12aa86973")] public sealed class RenderMaterialPass { private readonly ShaderPassDefinition m_definition; - private readonly IReadOnlyDictionary m_declaredBindings; - private readonly IReadOnlySet m_activeBindings; + private readonly IReadOnlyDictionary m_declaredBindings; + private readonly IReadOnlySet m_activeBindings; private readonly IReadOnlyList m_bindings; internal RenderMaterialPass( @@ -54,15 +35,18 @@ IReadOnlyList bindings this.graphicsPipeline = graphicsPipeline; this.computePipeline = computePipeline; m_declaredBindings = declaredBindings.ToDictionary( - static property => new RenderBindingId(property.id.value), - static property => ToRenderBindingKind(property.bindingKind)); + static property => new RenderBindingID(property.id.value), + static property => ToRenderBindingKind(property.bindingKind) + ); m_activeBindings = activeInterface.bindings - .Select(static binding => new RenderBindingId(binding.id.value)) + .Select(static binding => new RenderBindingID(binding.id.value)) .ToHashSet(); - m_bindings = Array.AsReadOnly(bindings.Select(static binding => binding with - { - uniformData = binding.uniformData?.ToArray() - }).ToArray()); + m_bindings = Array.AsReadOnly( + bindings.Select(static binding => binding with + { + uniformData = binding.uniformData?.ToArray() + }).ToArray() + ); } /// @@ -107,19 +91,28 @@ IReadOnlyList bindings /// The binding is not declared by the shader, or its declared kind differs from . /// public bool UsesBinding( - RenderBindingId binding, + RenderBindingID binding, RenderShaderBindingKind kind ) { if (!binding.isValid) + { throw new ArgumentException("A stable shader binding identifier is required.", nameof(binding)); + } if (!Enum.IsDefined(kind)) + { throw new ArgumentOutOfRangeException(nameof(kind)); + } if (!m_declaredBindings.TryGetValue(binding, out RenderShaderBindingKind declaredKind)) + { throw new ArgumentException($"Shader does not declare binding '{binding.value}'.", nameof(binding)); + } if (declaredKind != kind) + { throw new ArgumentException( $"Shader binding '{binding.value}' is declared as {declaredKind}, not {kind}.", - nameof(kind)); + nameof(kind) + ); + } return m_activeBindings.Contains(binding); } @@ -133,29 +126,54 @@ public void Bind(RenderCommandEncoder commands) { ArgumentNullException.ThrowIfNull(commands); if (graphicsPipeline.isValid) + { commands.BindGraphicsPipeline(graphicsPipeline); + } else if (computePipeline.isValid) + { commands.BindComputePipeline(computePipeline); + } else + { throw new InvalidOperationException("A resolved material pass has no active program."); + } foreach (RenderMaterialBinding binding in m_bindings) { if (binding.kind == RenderMaterialBindingKind.Uniform) + { commands.SetUniform(binding.id, binding.uniformData ?? []); + } else + { commands.BindTexture(binding.id, binding.texture, binding.sampler); + } } } private static RenderShaderBindingKind ToRenderBindingKind(ShaderPropertyBindingKind kind) => kind switch - { - ShaderPropertyBindingKind.Uniform => RenderShaderBindingKind.Uniform, - ShaderPropertyBindingKind.SampledTexture => RenderShaderBindingKind.Texture, - ShaderPropertyBindingKind.StorageTexture => RenderShaderBindingKind.StorageTexture, - ShaderPropertyBindingKind.StorageBuffer => RenderShaderBindingKind.StorageBuffer, - _ => throw new ArgumentOutOfRangeException(nameof(kind)) - }; + { + ShaderPropertyBindingKind.Uniform => RenderShaderBindingKind.Uniform, + ShaderPropertyBindingKind.SampledTexture => RenderShaderBindingKind.Texture, + ShaderPropertyBindingKind.StorageTexture => RenderShaderBindingKind.StorageTexture, + ShaderPropertyBindingKind.StorageBuffer => RenderShaderBindingKind.StorageBuffer, + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; +} + +[StableTypeID("b5677cc4-c195-5f52-a52f-5efecec8314e")] +internal enum RenderMaterialBindingKind +{ + Uniform, + Texture } +[StableTypeID("702a1ec9-219b-5d44-b322-1a433e7e41b5")] +internal sealed record RenderMaterialBinding( + RenderMaterialBindingKind kind, + RenderBindingID id, + byte[]? uniformData, + PersistentTextureHandle texture, + RenderSamplerState sampler +); diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceID.cs similarity index 85% rename from src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs rename to src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceID.cs index 713a9680c..543e57238 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceID.cs @@ -1,19 +1,20 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Identifies one provider-owned persistent GPU resource without exposing a native handle. /// -[Inno.Extensibility.Types.StableTypeId("c060d558-f0f1-5653-a77f-526e6b078507")] -public readonly record struct RenderPersistentResourceId +[StableTypeID("c060d558-f0f1-5653-a77f-526e6b078507")] +public readonly record struct RenderPersistentResourceID { /// /// Creates a globally stable persistent resource identifier. @@ -21,7 +22,7 @@ public readonly record struct RenderPersistentResourceId /// /// Provider-qualified stable identifier. /// - public RenderPersistentResourceId(string value) + public RenderPersistentResourceID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; @@ -45,4 +46,3 @@ public RenderPersistentResourceId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs index 8d2739413..4e2285bb6 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs @@ -1,8 +1,9 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -13,22 +14,9 @@ namespace Inno.Rendering.Runtime; /// The boundary lets a runtime resource service create generation-scoped values while their mutable /// representation remains private to the Rendering assembly. /// -[Inno.Extensibility.Types.StableTypeId("c06ff3f1-8280-52cc-a57a-8d864eb358c6")] +[StableTypeID("c06ff3f1-8280-52cc-a57a-8d864eb358c6")] public abstract class RenderResourceProvider { - /// - /// Represents one material binding staged by a derived resource service. - /// - protected readonly struct MaterialBinding - { - internal MaterialBinding(RenderMaterialBinding value) - { - this.value = value; - } - - internal RenderMaterialBinding value { get; } - } - /// /// Creates a protected uniform binding value. /// @@ -42,10 +30,9 @@ internal MaterialBinding(RenderMaterialBinding value) /// A binding token accepted by the material-pass construction helpers. /// protected static MaterialBinding CreateUniformBinding( - RenderBindingId id, + RenderBindingID id, ReadOnlySpan data - ) - => new(new RenderMaterialBinding(RenderMaterialBindingKind.Uniform, id, data.ToArray(), default, default)); + ) => new(new RenderMaterialBinding(RenderMaterialBindingKind.Uniform, id, data.ToArray(), default, default)); /// /// Creates a protected sampled-texture binding value. @@ -63,11 +50,10 @@ ReadOnlySpan data /// A binding token accepted by the material-pass construction helpers. /// protected static MaterialBinding CreateTextureBinding( - RenderBindingId id, + RenderBindingID id, PersistentTextureHandle texture, RenderSamplerState sampler - ) - => new(new RenderMaterialBinding(RenderMaterialBindingKind.Texture, id, null, texture, sampler)); + ) => new(new RenderMaterialBinding(RenderMaterialBindingKind.Texture, id, null, texture, sampler)); /// /// Creates a generation-scoped resolved material pass when no compiled-interface query is required. @@ -93,8 +79,7 @@ protected static RenderMaterialPass CreateMaterialPass( GraphicsPipelineHandle graphicsPipeline, ComputePipelineHandle computePipeline, IReadOnlyList bindings - ) - => CreateMaterialPass(definition, graphicsPipeline, computePipeline, [], new ShaderInterface([]), bindings); + ) => CreateMaterialPass(definition, graphicsPipeline, computePipeline, [], new ShaderInterface([]), bindings); /// /// Creates a generation-scoped resolved material pass. @@ -127,14 +112,14 @@ protected static RenderMaterialPass CreateMaterialPass( IReadOnlyList declaredBindings, ShaderInterface activeInterface, IReadOnlyList bindings - ) - => new( - definition, - graphicsPipeline, - computePipeline, - declaredBindings, - activeInterface, - bindings.Select(static binding => binding.value).ToArray()); + ) => new( + definition, + graphicsPipeline, + computePipeline, + declaredBindings, + activeInterface, + bindings.Select(static binding => binding.value).ToArray() + ); /// /// Creates generation-scoped resolved geometry from persistent buffers and immutable sections. @@ -167,7 +152,18 @@ protected static RenderGeometry CreateGeometry( int vertexCount, int indexCount, IReadOnlyList sections - ) - => new(vertexBuffer, indexBuffer, vertexLayout, vertexCount, indexCount, sections); -} + ) => new(vertexBuffer, indexBuffer, vertexLayout, vertexCount, indexCount, sections); + /// + /// Represents one material binding staged by a derived resource service. + /// + protected readonly struct MaterialBinding + { + internal MaterialBinding(RenderMaterialBinding value) + { + this.value = value; + } + + internal RenderMaterialBinding value { get; } + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs index 865328c42..8050cd821 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs @@ -1,18 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; /// /// Stores one complete texture mip and addressable layer, slice, or cubemap-face upload. /// -[Inno.Extensibility.Types.StableTypeId("22ed6418-30e6-511e-8af3-5d830d3b0ce5")] +[StableTypeID("22ed6418-30e6-511e-8af3-5d830d3b0ce5")] public sealed class RenderTextureSubresourceData { private readonly byte[] m_data; @@ -37,7 +38,9 @@ ReadOnlySpan data ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); if (data.IsEmpty) + { throw new ArgumentException("A texture subresource upload cannot be empty.", nameof(data)); + } this.mipLevel = mipLevel; this.arrayLayer = arrayLayer; m_data = data.ToArray(); @@ -58,4 +61,3 @@ ReadOnlySpan data /// public ReadOnlyMemory data => m_data; } - diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs new file mode 100644 index 000000000..fd4c0d18d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +/// +/// Defines one shader node's typed ports and lowering; drawing belongs to a separate editor extension. +/// +public interface IShaderNodeCompiler +{ + /// + /// Gets the exact graph node definition identity implemented by this compiler. + /// + string definitionID { get; } + + /// + /// Describes ports for the current neutral properties and resolved source/target inputs. + /// + /// + /// Invocation-scoped node properties and frozen source/target data. + /// + /// + /// Complete typed ports; duplicate identities are invalid. + /// + IReadOnlyList GetPorts(ShaderNodeDescriptionContext context); + + /// + /// Lowers the node into the supplied typed builder without generating source strings. + /// + /// + /// Connected typed inputs and the shared region builder. + /// + /// + /// Exactly the declared output ports by stable identity. + /// + IReadOnlyDictionary Lower(ShaderNodeLoweringContext context); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs new file mode 100644 index 000000000..6f237c7fb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers an explicit arithmetic/comparison operation; operation IDs are node configuration, not backend code. +/// +public sealed class ShaderBinaryNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.binary"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); + ShaderIrOperation operation = Operation(context); + return [ + new ShaderNodePort("left", type, GraphPortDirection.Input), + new ShaderNodePort("right", type, GraphPortDirection.Input), + new ShaderNodePort( + "value", + operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, + GraphPortDirection.Output + ) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) + }; + + private static ShaderIrOperation Operation(ShaderNodeDescriptionContext context) + => context.Read("operation", "add") switch + { + "add" => ShaderIrOperation.Add, + "subtract" => ShaderIrOperation.Subtract, + "multiply" => ShaderIrOperation.Multiply, + "divide" => ShaderIrOperation.Divide, + "minimum" => ShaderIrOperation.Minimum, + "maximum" => ShaderIrOperation.Maximum, + "equal" => ShaderIrOperation.Equal, + "less-than" => ShaderIrOperation.LessThan, + _ => throw new InvalidOperationException("Unknown binary shader operation.") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs deleted file mode 100644 index 9f1f8148a..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs +++ /dev/null @@ -1,327 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Core.Graphs; - -namespace Inno.Rendering.Shaders; - -/// -/// Lowers an exact scalar constant; its type/value are native graph properties. -/// -public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.constant"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("value", ShaderSourceType.Atomic(context.Read("type", "float")), GraphPortDirection.Output)]; - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderNodeDescriptionContext node = context.description; - ShaderIrValue value = node.Read("type", "float") switch - { - "float" => context.builder.Constant(node.Read("value", 0f)), - "int" => context.builder.Constant(node.Read("value", 0)), - "uint" => context.builder.Constant(node.Read("value", 0u)), - "bool" => context.builder.Constant(node.Read("value", false)), - _ => throw new InvalidOperationException("A scalar constant must declare float, int, uint or bool.") - }; - return new Dictionary { ["value"] = value }; - } -} - -/// -/// Lowers an explicit arithmetic/comparison operation; operation IDs are node configuration, not backend code. -/// -public sealed class ShaderBinaryNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.binary"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); - ShaderIrOperation operation = Operation(context); - return [new("left", type, GraphPortDirection.Input), new("right", type, GraphPortDirection.Input), - new("value", operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, GraphPortDirection.Output)]; - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) }; - - private static ShaderIrOperation Operation(ShaderNodeDescriptionContext context) - => context.Read("operation", "add") switch - { - "add" => ShaderIrOperation.Add, "subtract" => ShaderIrOperation.Subtract, - "multiply" => ShaderIrOperation.Multiply, "divide" => ShaderIrOperation.Divide, - "minimum" => ShaderIrOperation.Minimum, "maximum" => ShaderIrOperation.Maximum, - "equal" => ShaderIrOperation.Equal, "less-than" => ShaderIrOperation.LessThan, - _ => throw new InvalidOperationException("Unknown binary shader operation.") - }; -} - -/// -/// Constructs a vector or column-major matrix from individually connected scalar components. -/// -public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.construct"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - (ShaderSourceType type, ShaderSourceType scalar, int count) = Shape(context); - return Enumerable.Range(0, count).Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) - .Append(new("value", type, GraphPortDirection.Output)).ToArray(); - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - (ShaderSourceType type, _, int count) = Shape(context.description); - return new Dictionary - { ["value"] = context.builder.Construct(type, Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray()) }; - } - - private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape(ShaderNodeDescriptionContext context) - { - string id = context.Read("type", "float4"); - foreach (string scalar in new[] { "float", "int", "uint", "bool" }) - { - if (id.Length == scalar.Length + 1 && id.StartsWith(scalar, StringComparison.Ordinal) && id[^1] is >= '2' and <= '4') - return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic(scalar), id[^1] - '0'); - } - if (id.Length == 8 && id.StartsWith("float", StringComparison.Ordinal) && id[5] is >= '2' and <= '4' && id[6] == 'x' && id[7] is >= '2' and <= '4') - return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic("float"), (id[5] - '0') * (id[7] - '0')); - throw new InvalidOperationException("Construction requires a numeric vector or floating-point matrix."); - } -} - -/// -/// Reads one target-assigned stage/resource input without choosing a native variable name. -/// -public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.stage-input"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("value", RequireBinding(context).type, GraphPortDirection.Output)]; - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderIrStageInput input = RequireBinding(context.description); - return new Dictionary { ["value"] = context.builder.Input(input.id, input.type) }; - } - private static ShaderIrStageInput RequireBinding(ShaderNodeDescriptionContext context) - => context.stageInput ?? throw new InvalidOperationException("The target has not resolved this stage input binding."); -} - -/// -/// Selects between equal typed values; all producer effects remain evaluated before selection. -/// -public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.select"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); - return [new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), new("true", type, GraphPortDirection.Input), - new("false", type, GraphPortDirection.Input), new("value", type, GraphPortDirection.Output)]; - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) }; -} - -/// -/// Lowers a parsed function module with name-based ports and explicit aggregate/member connection alternatives. -/// -public sealed class ShaderSourceNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.source"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceFunction function = RequireModule(context).function!; - var ports = new List(); - foreach (ShaderSourceParameter parameter in function.parameters) - { - if (parameter.direction != ShaderSourceParameterDirection.Output) - Add("input." + parameter.name, parameter.type, GraphPortDirection.Input); - if (parameter.direction != ShaderSourceParameterDirection.Input) - Add("output." + parameter.name, parameter.type, GraphPortDirection.Output); - } - if (function.returnType.id != "void") - Add("return", function.returnType, GraphPortDirection.Output); - return ports.AsReadOnly(); - void Add( - string name, - ShaderSourceType type, - GraphPortDirection direction - ) { - ports.Add(new(name, type, direction, required: false)); - foreach (ShaderSourceField field in type.fields) - Add(name + "." + field.name, field.type, direction); - } - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderSourceModuleAnalysis module = RequireModule(context.description); - var arguments = new Dictionary(StringComparer.Ordinal); - foreach (ShaderSourceParameter parameter in module.function!.parameters) - if (parameter.direction != ShaderSourceParameterDirection.Output) - arguments.Add(parameter.name, Resolve("input." + parameter.name, parameter.type)); - IReadOnlyDictionary values = context.builder.Call(module, context.description.implementationId, arguments); - var outputs = new Dictionary(StringComparer.Ordinal); - foreach ((string name, ShaderIrValue value) in values) - Add(name, value); - return outputs; - - ShaderIrValue Resolve( - string name, - ShaderSourceType type - ) { - if (context.inputs.TryGetValue(name, out ShaderIrValue? aggregate)) - { - if (context.inputs.Keys.Any(key => key.StartsWith(name + ".", StringComparison.Ordinal))) - throw new InvalidOperationException($"'{name}' connects both its aggregate and a member; choose one representation explicitly."); - return aggregate; - } - if (type.fields.Count == 0) - return context.Input(name); - return context.builder.Construct(type, type.fields.Select(field => Resolve(name + "." + field.name, field.type)).ToArray()); - } - - void Add( - string name, - ShaderIrValue value - ) { - outputs.Add(name, value); - for (int index = 0; index < value.type.fields.Count; index++) - Add(name + "." + value.type.fields[index].name, context.builder.Extract(value, index)); - } - } - - private static ShaderSourceModuleAnalysis RequireModule(ShaderNodeDescriptionContext context) - { - ShaderSourceModuleAnalysis? module = context.sourceModule; - if (module is null) - throw new InvalidOperationException("The source module is unassigned or unavailable; its stored reference and connections must remain intact."); - if (!module.succeeded) - throw new InvalidOperationException("The source module has no valid common interface: " + string.Join("; ", module.diagnostics.Select(static value => value.message))); - return module; - } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs new file mode 100644 index 000000000..78d37c7e0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers an exact scalar constant; its type/value are native graph properties. +/// +public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.constant"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [new ShaderNodePort("value", ShaderSourceType.Atomic(context.Read("type", "float")), GraphPortDirection.Output)]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderNodeDescriptionContext node = context.description; + ShaderIrValue value = node.Read("type", "float") switch + { + "float" => context.builder.Constant(node.Read("value", 0f)), + "int" => context.builder.Constant(node.Read("value", 0)), + "uint" => context.builder.Constant(node.Read("value", 0u)), + "bool" => context.builder.Constant(node.Read("value", false)), + _ => throw new InvalidOperationException("A scalar constant must declare float, int, uint or bool.") + }; + return new Dictionary { ["value"] = value }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs new file mode 100644 index 000000000..f9af4af5a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Constructs a vector or column-major matrix from individually connected scalar components. +/// +public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.construct"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + (ShaderSourceType type, ShaderSourceType scalar, int count) = Shape(context); + return Enumerable.Range(0, count) + .Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) + .Append(new ShaderNodePort("value", type, GraphPortDirection.Output)) + .ToArray(); + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + (ShaderSourceType type, _, int count) = Shape(context.description); + return new Dictionary + { + ["value"] = context.builder.Construct( + type, + Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray() + ) + }; + } + + private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape(ShaderNodeDescriptionContext context) + { + string id = context.Read("type", "float4"); + foreach (string scalar in new[] { "float", "int", "uint", "bool" }) + { + if (id.Length == scalar.Length + 1 && id.StartsWith(scalar, StringComparison.Ordinal) && id[^1] is >= '2' and <= '4') + { + return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic(scalar), id[^1] - '0'); + } + } + if (id.Length == 8 + && id.StartsWith("float", StringComparison.Ordinal) + && id[5] is >= '2' and <= '4' + && id[6] == 'x' + && id[7] is >= '2' and <= '4' + ) { + return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic("float"), (id[5] - '0') * (id[7] - '0')); + } + throw new InvalidOperationException("Construction requires a numeric vector or floating-point matrix."); + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs new file mode 100644 index 000000000..935ad1215 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.discard"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [ + new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), + new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) + ]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + context.builder.Discard(context.Input("condition")); + return new Dictionary { ["then"] = context.builder.Constant(true) }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs new file mode 100644 index 000000000..893704f4b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Extracts one statically selected component from a vector or matrix. +/// +public sealed class ShaderExtractNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.extract"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float4")); + var builder = new ShaderIrBuilder(); + ShaderIrValue member = builder.Extract(builder.Input("input", type), context.Read("index", 0)); + return [ + new ShaderNodePort("input", type, GraphPortDirection.Input), + new ShaderNodePort("value", member.type, GraphPortDirection.Output) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs index f09cac39f..65991639f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using Inno.Core.Diagnostics; using Inno.Core.Graphs; @@ -12,8 +11,6 @@ namespace Inno.Rendering.Shaders; /// public sealed class ShaderGraphLoweringRequest { - internal GraphDocument graph { get; } - /// /// Captures a region without retaining an asset object, source resolver, node provider or UI selection. /// @@ -23,7 +20,7 @@ public sealed class ShaderGraphLoweringRequest /// /// Named region results mapped to stable output endpoints. /// - /// + /// /// Exact source implementation key selected by the target. /// /// @@ -35,38 +32,53 @@ public sealed class ShaderGraphLoweringRequest public ShaderGraphLoweringRequest( GraphDocument graph, IReadOnlyDictionary outputs, - string implementationId, - IReadOnlyDictionary? sourceModules = null, - IReadOnlyDictionary? stageInputs = null + string implementationID, + IReadOnlyDictionary? sourceModules = null, + IReadOnlyDictionary? stageInputs = null ) { ArgumentNullException.ThrowIfNull(graph); ArgumentNullException.ThrowIfNull(outputs); - ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); foreach (string name in outputs.Keys) + { ArgumentException.ThrowIfNullOrWhiteSpace(name); + } this.graph = graph.Clone(); - this.outputs = new ReadOnlyDictionary(new Dictionary(outputs, StringComparer.Ordinal)); - this.implementationId = implementationId; - this.sourceModules = new ReadOnlyDictionary(new Dictionary(sourceModules ?? new Dictionary())); - this.stageInputs = new ReadOnlyDictionary(new Dictionary(stageInputs ?? new Dictionary())); + this.outputs = new ReadOnlyDictionary( + new Dictionary(outputs, StringComparer.Ordinal) + ); + this.implementationID = implementationID; + this.sourceModules = new ReadOnlyDictionary( + new Dictionary( + sourceModules ?? new Dictionary() + ) + ); + this.stageInputs = new ReadOnlyDictionary( + new Dictionary(stageInputs ?? new Dictionary()) + ); } /// /// Gets named region outputs by stable graph endpoint. /// public IReadOnlyDictionary outputs { get; } + /// /// Gets the exact implementation key selected by the target. /// - public string implementationId { get; } + public string implementationID { get; } + /// /// Gets frozen source modules, including unavailable/failed modules for accurate diagnostics. /// - public IReadOnlyDictionary sourceModules { get; } + public IReadOnlyDictionary sourceModules { get; } + /// /// Gets target-assigned input descriptors; they contain no native expressions. /// - public IReadOnlyDictionary stageInputs { get; } + public IReadOnlyDictionary stageInputs { get; } + + internal GraphDocument graph { get; } } /// @@ -81,42 +93,16 @@ public ShaderGraphLoweringRequest( /// /// Human-readable explanation. /// -/// +/// /// Affected node identity when known. /// -/// +/// /// Affected semantic port when known. /// public sealed record ShaderGraphDiagnostic( string code, DiagnosticSeverity severity, string message, - GraphNodeId? nodeId = null, - string? portId = null + GraphNodeID? nodeID = null, + string? portID = null ); - -/// -/// Contains a detached typed region only after all graph, port and node lowering validation succeeds. -/// -public sealed class ShaderGraphLoweringResult -{ - internal ShaderGraphLoweringResult( - ShaderIrBlock? block, - IEnumerable diagnostics - ) { - this.block = block; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - /// - /// Gets the immutable typed region, or null on failure. - /// - public ShaderIrBlock? block { get; } - /// - /// Gets located graph diagnostics, including missing definitions and stale source ports. - /// - public IReadOnlyList diagnostics { get; } - /// - /// Gets whether lowering produced a complete region without errors; native compilation is a separate gate. - /// - public bool succeeded => block is not null && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs new file mode 100644 index 000000000..afc39f480 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering.Shaders; + +/// +/// Contains a detached typed region only after all graph, port and node lowering validation succeeds. +/// +public sealed class ShaderGraphLoweringResult +{ + internal ShaderGraphLoweringResult( + ShaderIrBlock? block, + IEnumerable diagnostics + ) { + this.block = block; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the immutable typed region, or null on failure. + /// + public ShaderIrBlock? block { get; } + + /// + /// Gets located graph diagnostics, including missing definitions and stale source ports. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether lowering produced a complete region without errors; native compilation is a separate gate. + /// + public bool succeeded => block is not null && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs deleted file mode 100644 index b00259c1a..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Inno.Core.Graphs; -using Inno.Core.Serialization; - -namespace Inno.Rendering.Shaders; - -/// -/// Declares a typed shader port independently of editor presentation and backend source syntax. -/// -/// -/// Stable node-local port identity. -/// -/// -/// Complete value type, including all aggregate fields. -/// -/// -/// Input or output value flow. -/// -/// -/// Whether an input must be connected; alternative aggregate/member inputs validate in their compiler. -/// -public sealed record ShaderNodePort( - string id, - ShaderSourceType type, - GraphPortDirection direction, - bool required = true -); - -/// -/// Defines one shader node's typed ports and lowering; drawing belongs to a separate editor extension. -/// -public interface IShaderNodeCompiler -{ - /// - /// Gets the exact graph node definition identity implemented by this compiler. - /// - string definitionId { get; } - /// - /// Describes ports for the current neutral properties and resolved source/target inputs. - /// - /// - /// Invocation-scoped node properties and frozen source/target data. - /// - /// - /// Complete typed ports; duplicate identities are invalid. - /// - IReadOnlyList GetPorts(ShaderNodeDescriptionContext context); - /// - /// Lowers the node into the supplied typed builder without generating source strings. - /// - /// - /// Connected typed inputs and the shared region builder. - /// - /// - /// Exactly the declared output ports by stable identity. - /// - IReadOnlyDictionary Lower(ShaderNodeLoweringContext context); -} - -/// -/// Provides invocation-scoped property decoding through the complete owner serialization context. -/// -public sealed class ShaderNodeDescriptionContext -{ - private readonly GraphNodeRecord m_node; - private readonly SerializationRegistry m_serialization; - private readonly SerializationContext m_context; - - internal ShaderNodeDescriptionContext( - GraphNodeRecord node, - SerializationRegistry serialization, - SerializationContext context, - ShaderSourceModuleAnalysis? sourceModule, - string implementationId, - ShaderIrStageInput? stageInput - ) { - m_node = node; - m_serialization = serialization; - m_context = context; - this.sourceModule = sourceModule; - this.implementationId = implementationId; - this.stageInput = stageInput; - } - - /// - /// Gets the node's stable identity, never its editor runtime handle. - /// - public GraphNodeId nodeId => m_node.id; - /// - /// Gets the node definition's stable identity. - /// - public string definitionId => m_node.definitionId; - /// - /// Gets a frozen module resolved by the asset owner; null means unassigned or unavailable. - /// - public ShaderSourceModuleAnalysis? sourceModule { get; } - /// - /// Gets the exact implementation key chosen by the target. - /// - public string implementationId { get; } - /// - /// Gets the target-assigned stage input for this node, when applicable. - /// - public ShaderIrStageInput? stageInput { get; } - - /// - /// Reads a property using the owner's converter generation and complete reference resolver context. - /// - /// - /// Declared property type supported by the native serializer. - /// - /// - /// Stable property identity. - /// - /// - /// Value used only when the property is absent, never after corrupt-data failure. - /// - /// - /// The deserialized value or the supplied absent-property default. - /// - public T Read( - string id, - T defaultValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - return m_node.TryGetValue(id, out GraphSerializedValue? value) - ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) - : defaultValue; - } -} - -/// -/// Supplies one node's connected values and the region builder during lowering only. -/// -public sealed class ShaderNodeLoweringContext -{ - internal ShaderNodeLoweringContext( - ShaderNodeDescriptionContext description, - ShaderIrBuilder builder, - IReadOnlyDictionary inputs - ) { - this.description = description; - this.builder = builder; - this.inputs = new ReadOnlyDictionary(new Dictionary(inputs, StringComparer.Ordinal)); - } - - /// - /// Gets the invocation-scoped node description. - /// - public ShaderNodeDescriptionContext description { get; } - /// - /// Gets the builder shared by nodes in this typed region. - /// - public ShaderIrBuilder builder { get; } - /// - /// Gets connected values keyed by semantic input port identity, never connection order. - /// - public IReadOnlyDictionary inputs { get; } - /// - /// Requires one connected input without implicit defaults or positional rebinding. - /// - /// - /// Exact semantic input port identity. - /// - /// - /// The connected typed value. - /// - public ShaderIrValue Input(string id) - => inputs.TryGetValue(id, out ShaderIrValue? value) ? value : throw new InvalidOperationException($"Input '{id}' is not connected."); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs index 42dea3300..79869d94f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs @@ -16,7 +16,6 @@ namespace Inno.Rendering.Shaders; public sealed class ShaderNodeCompilerCatalog { private readonly Dictionary m_compilers = new(StringComparer.Ordinal); - internal IReadOnlyList providers { get; } /// /// Validates a complete generation of node compiler registrations. @@ -30,18 +29,20 @@ public ShaderNodeCompilerCatalog(IEnumerable compilers) foreach (IShaderNodeCompiler compiler in compilers) { ArgumentNullException.ThrowIfNull(compiler); - ArgumentException.ThrowIfNullOrWhiteSpace(compiler.definitionId); - if (!m_compilers.TryAdd(compiler.definitionId, compiler)) - throw new ArgumentException($"Duplicate shader node compiler '{compiler.definitionId}'.", nameof(compilers)); + ArgumentException.ThrowIfNullOrWhiteSpace(compiler.definitionID); + if (!m_compilers.TryAdd(compiler.definitionID, compiler)) + { + throw new ArgumentException($"Duplicate shader node compiler '{compiler.definitionID}'.", nameof(compilers)); + } } - providers = Array.AsReadOnly(m_compilers.Values.ToArray()); - definitionIds = Array.AsReadOnly(m_compilers.Keys.Order(StringComparer.Ordinal).ToArray()); + this.providers = Array.AsReadOnly(m_compilers.Values.ToArray()); + this.definitionIDs = Array.AsReadOnly(m_compilers.Keys.Order(StringComparer.Ordinal).ToArray()); } /// /// Gets stable registered definition identities, without exposing providers. /// - public IReadOnlyList definitionIds { get; } + public IReadOnlyList definitionIDs { get; } /// /// Describes current typed ports for editor presentation without exposing the compiler provider. @@ -58,7 +59,7 @@ public ShaderNodeCompilerCatalog(IEnumerable compilers) /// /// Resolved frozen function module, or null. /// - /// + /// /// Selected source implementation. /// /// @@ -72,13 +73,17 @@ public IReadOnlyList DescribePorts( SerializationRegistry serialization, SerializationContext context, ShaderSourceModuleAnalysis? source = null, - string implementationId = "", + string implementationID = "", ShaderIrStageInput? input = null ) { ArgumentNullException.ThrowIfNull(node); - if (!m_compilers.TryGetValue(node.definitionId, out IShaderNodeCompiler? compiler)) - throw new InvalidOperationException($"Node compiler '{node.definitionId}' is unavailable."); - return Array.AsReadOnly(compiler.GetPorts(new(node, serialization, context, source, implementationId, input)).ToArray()); + if (!m_compilers.TryGetValue(node.definitionID, out IShaderNodeCompiler? compiler)) + { + throw new InvalidOperationException($"Node compiler '{node.definitionID}' is unavailable."); + } + return Array.AsReadOnly( + compiler.GetPorts(new ShaderNodeDescriptionContext(node, serialization, context, source, implementationID, input)).ToArray() + ); } /// @@ -110,87 +115,130 @@ public ShaderGraphLoweringResult Lower( ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); - var diagnostics = new List(); - GraphNodeId? activeNode = null; + List diagnostics = []; + GraphNodeID? activeNode = null; try { IReadOnlyList nodes = request.graph.nodes; - var descriptions = new Dictionary(); + var descriptions = new Dictionary(); var ports = new Dictionary(); - var nodePorts = new Dictionary>(); - var nodeIndexes = new Dictionary(); + var nodePorts = new Dictionary>(); + var nodeIndexes = new Dictionary(); for (int index = 0; index < nodes.Count; index++) { cancellationToken.ThrowIfCancellationRequested(); GraphNodeRecord node = nodes[index]; activeNode = node.id; nodeIndexes.Add(node.id, index); - if (!m_compilers.TryGetValue(node.definitionId, out IShaderNodeCompiler? compiler)) + if (!m_compilers.TryGetValue(node.definitionID, out IShaderNodeCompiler? compiler)) { - Error("SHADER_NODE_COMPILER_MISSING", $"Node compiler '{node.definitionId}' is unavailable.", node.id); + Error("SHADER_NODE_COMPILER_MISSING", $"Node compiler '{node.definitionID}' is unavailable.", node.id); continue; } request.sourceModules.TryGetValue(node.id, out ShaderSourceModuleAnalysis? source); request.stageInputs.TryGetValue(node.id, out ShaderIrStageInput? input); - var description = new ShaderNodeDescriptionContext(node, serialization, context, source, request.implementationId, input); + var description = new ShaderNodeDescriptionContext( + node, + serialization, + context, + source, + request.implementationID, + input + ); descriptions.Add(node.id, description); IReadOnlyList describedPorts = compiler.GetPorts(description).ToArray(); nodePorts.Add(node.id, describedPorts); foreach (ShaderNodePort port in describedPorts) { - if (port is null || string.IsNullOrWhiteSpace(port.id) || port.type is null || port.type.id == "void" || !Enum.IsDefined(port.direction)) - throw new InvalidOperationException($"Compiler '{node.definitionId}' returned an invalid port."); - if (!ports.TryAdd(new(node.id, new(port.id)), port)) - throw new InvalidOperationException($"Compiler '{node.definitionId}' returned duplicate port '{port.id}'."); + if (port is null + || string.IsNullOrWhiteSpace(port.id) + || port.type is null + || port.type.id == "void" + || !Enum.IsDefined(port.direction) + ) { + throw new InvalidOperationException($"Compiler '{node.definitionID}' returned an invalid port."); + } + if (!ports.TryAdd(new GraphEndpoint(node.id, new GraphPortID(port.id)), port)) + { + throw new InvalidOperationException($"Compiler '{node.definitionID}' returned duplicate port '{port.id}'."); + } } } activeNode = null; if (diagnostics.Count != 0) + { return new(null, diagnostics); + } var connections = new Dictionary(); var inputDefaults = new Dictionary(); - var nodeConnections = nodes.ToDictionary(static node => node.id, static _ => new List<(string port, GraphEndpoint source)>()); + Dictionary> nodeConnections = nodes.ToDictionary( + static node => node.id, + static _ => new List<(string port, GraphEndpoint source)>() + ); var incoming = new int[nodes.Count]; - var following = Enumerable.Range(0, nodes.Count).Select(static _ => new List()).ToArray(); + List[] following = Enumerable.Range(0, nodes.Count).Select(static _ => new List()).ToArray(); foreach (GraphEdgeRecord edge in request.graph.edges) { if (!ports.TryGetValue(edge.input, out ShaderNodePort? input) || input.direction != GraphPortDirection.Input) { - Error("SHADER_GRAPH_PORT_MISSING", $"Connection '{edge.id}' has an unavailable input; it remains stored for explicit repair.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_PORT_MISSING", + $"Connection '{edge.id}' has an unavailable input; it remains stored for explicit repair.", + edge.input.nodeID, + edge.input.portID.value + ); continue; } if (!ports.TryGetValue(edge.output, out ShaderNodePort? output) || output.direction != GraphPortDirection.Output) { - Error("SHADER_GRAPH_PORT_MISSING", $"Connection '{edge.id}' has an unavailable output; it remains stored for explicit repair.", edge.output.nodeId, edge.output.portId.value); + Error( + "SHADER_GRAPH_PORT_MISSING", + $"Connection '{edge.id}' has an unavailable output; it remains stored for explicit repair.", + edge.output.nodeID, + edge.output.portID.value + ); continue; } if (!input.type.IsEquivalentTo(output.type)) { - Error("SHADER_GRAPH_TYPE", $"Connection '{edge.id}' changed type or aggregate layout; implicit conversion and positional rebinding are forbidden.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_TYPE", + $"Connection '{edge.id}' changed type or aggregate layout; implicit conversion and positional rebinding are forbidden.", + edge.input.nodeID, + edge.input.portID.value + ); continue; } if (!connections.TryAdd(edge.input, edge.output)) { - Error("SHADER_GRAPH_INPUT_CAPACITY", "A value input has more than one connection.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_INPUT_CAPACITY", + "A value input has more than one connection.", + edge.input.nodeID, + edge.input.portID.value + ); continue; } - int target = nodeIndexes[edge.input.nodeId]; - nodeConnections[edge.input.nodeId].Add((edge.input.portId.value, edge.output)); + int target = nodeIndexes[edge.input.nodeID]; + nodeConnections[edge.input.nodeID].Add((edge.input.portID.value, edge.output)); incoming[target]++; - following[nodeIndexes[edge.output.nodeId]].Add(target); + following[nodeIndexes[edge.output.nodeID]].Add(target); } foreach ((GraphEndpoint endpoint, ShaderNodePort port) in ports) { if (port.direction != GraphPortDirection.Input || connections.ContainsKey(endpoint)) + { continue; + } if (port.required) { Error( "SHADER_GRAPH_INPUT_REQUIRED", - $"Required input '{endpoint.portId.value}' on node '{endpoint.nodeId.value}' is not connected. Connect a Constant or another compatible graph output.", - endpoint.nodeId, - endpoint.portId.value); + $"Required input '{endpoint.portID.value}' on node '{endpoint.nodeID.value}' is not connected. Connect a Constant or another compatible graph output.", + endpoint.nodeID, + endpoint.portID.value + ); continue; } try @@ -201,32 +249,51 @@ public ShaderGraphLoweringResult Lower( { Error( "SHADER_GRAPH_OPTIONAL_TYPE", - $"Optional input '{endpoint.portId.value}' cannot represent an automatic zero value and must be required instead.", - endpoint.nodeId, - endpoint.portId.value); + $"Optional input '{endpoint.portID.value}' cannot represent an automatic zero value and must be required instead.", + endpoint.nodeID, + endpoint.portID.value + ); } } activeNode = null; foreach ((string name, GraphEndpoint endpoint) in request.outputs) + { if (!ports.TryGetValue(endpoint, out ShaderNodePort? port) || port.direction != GraphPortDirection.Output) - Error("SHADER_GRAPH_OUTPUT_MISSING", $"Region output '{name}' points to an unavailable output port.", endpoint.nodeId, endpoint.portId.value); + { + Error( + "SHADER_GRAPH_OUTPUT_MISSING", + $"Region output '{name}' points to an unavailable output port.", + endpoint.nodeID, + endpoint.portID.value + ); + } + } if (diagnostics.Count != 0) + { return new(null, diagnostics); + } var ready = new SortedSet(Enumerable.Range(0, nodes.Count).Where(index => incoming[index] == 0)); - var ordered = new List(); + List ordered = []; while (ready.Count != 0) { int index = ready.Min; ready.Remove(index); ordered.Add(index); foreach (int next in following[index]) + { if (--incoming[next] == 0) + { ready.Add(next); + } + } } if (ordered.Count != nodes.Count) { - Error("SHADER_GRAPH_CYCLE", "Value connections contain a cycle; structured control flow must be represented by a control-flow operation."); + Error( + "SHADER_GRAPH_CYCLE", + "Value connections contain a cycle; structured control flow must be represented by a control-flow operation." + ); return new(null, diagnostics); } var builder = new ShaderIrBuilder(); @@ -238,27 +305,45 @@ public ShaderGraphLoweringResult Lower( activeNode = node.id; var inputs = new Dictionary(StringComparer.Ordinal); foreach ((string port, GraphEndpoint source) in nodeConnections[node.id]) + { inputs.Add(port, values[source]); + } foreach (ShaderNodePort port in nodePorts[node.id]) - if (inputDefaults.TryGetValue(new(node.id, new(port.id)), out ShaderGraphLiteral? literal)) + { + if (inputDefaults.TryGetValue(new GraphEndpoint(node.id, new GraphPortID(port.id)), out ShaderGraphLiteral? literal)) + { inputs.Add(port.id, literal.Emit(builder, port.type)); - IReadOnlyDictionary outputs = m_compilers[node.definitionId].Lower(new(descriptions[node.id], builder, inputs)); + } + } + IReadOnlyDictionary outputs = m_compilers[node.definitionID].Lower( + new ShaderNodeLoweringContext(descriptions[node.id], builder, inputs) + ); ShaderNodePort[] expected = nodePorts[node.id].Where(static port => port.direction == GraphPortDirection.Output).ToArray(); if (outputs.Count != expected.Length) + { throw new InvalidOperationException("A node compiler did not return exactly its declared outputs."); + } foreach (ShaderNodePort port in expected) { if (!outputs.TryGetValue(port.id, out ShaderIrValue? value) || !port.type.IsEquivalentTo(value.type)) + { throw new InvalidOperationException($"Node output '{port.id}' is missing or has an incompatible type."); + } builder.RequireOwned(value); - values.Add(new(node.id, new(port.id)), value); + values.Add(new GraphEndpoint(node.id, new GraphPortID(port.id)), value); } } cancellationToken.ThrowIfCancellationRequested(); - return new(builder.Build(request.outputs.ToDictionary(static pair => pair.Key, pair => values[pair.Value], StringComparer.Ordinal)), diagnostics); + return new( + builder.Build(request.outputs.ToDictionary(static pair => pair.Key, pair => values[pair.Value], StringComparer.Ordinal)), + diagnostics + ); } - catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or InvalidDataException or KeyNotFoundException - or FormatException or NotSupportedException && RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (failure is ArgumentException + or InvalidOperationException + or InvalidDataException + or KeyNotFoundException + or FormatException or NotSupportedException && RetirementPendingException.Find(failure) is null) { Error("SHADER_NODE_LOWERING", failure.Message, activeNode); return new(null, diagnostics); @@ -267,9 +352,10 @@ public ShaderGraphLoweringResult Lower( void Error( string code, string message, - GraphNodeId? nodeId = null, - string? portId = null - ) - => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, nodeId, portId)); + GraphNodeID? nodeID = null, + string? portID = null + ) => diagnostics.Add(new ShaderGraphDiagnostic(code, DiagnosticSeverity.Error, message, nodeID, portID)); } + + internal IReadOnlyList providers { get; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs index be3f246a2..1bd678291 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Core.Serialization; using Inno.Core.Graphs; +using Inno.Core.Serialization; using Inno.Extensibility.Types; namespace Inno.Rendering.Shaders; @@ -21,17 +21,21 @@ public sealed class ShaderNodeCompilerRegistry : TypeRegistry /// Owner catalog, which must outlive this registry. /// - public ShaderNodeCompilerRegistry(TypeCatalog types) : base(types) => m_types = types; + public ShaderNodeCompilerRegistry(TypeCatalog types) + : base(types) + { + m_types = types; + } /// /// Gets stable compiler identities without exposing provider instances. /// - public IReadOnlyList definitionIds + public IReadOnlyList definitionIDs { get { using IDisposable operation = m_types.AcquireOperation("Query shader node compilers"); - return current.definitionIds; + return current.definitionIDs; } } @@ -78,7 +82,7 @@ public ShaderGraphLoweringResult Lower( /// /// Resolved frozen source function, or null. /// - /// + /// /// Selected source implementation identity. /// /// @@ -92,11 +96,11 @@ public IReadOnlyList DescribePorts( SerializationRegistry serialization, SerializationContext context, ShaderSourceModuleAnalysis? source = null, - string implementationId = "", + string implementationID = "", ShaderIrStageInput? input = null ) { using IDisposable operation = m_types.AcquireOperation("Describe shader node ports"); - return current.DescribePorts(node, serialization, context, source, implementationId, input); + return current.DescribePorts(node, serialization, context, source, implementationID, input); } /// @@ -110,10 +114,13 @@ public IReadOnlyList DescribePorts( /// protected override ShaderNodeCompilerCatalog Build(TypeCacheSnapshot types) { - var providers = new List(); + List providers = []; foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)).OrderBy(static type => type.FullName, StringComparer.Ordinal)) + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { providers.Add(CreateExtension(type)); + } return new(providers); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs new file mode 100644 index 000000000..0db17c888 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs @@ -0,0 +1,81 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Provides invocation-scoped property decoding through the complete owner serialization context. +/// +public sealed class ShaderNodeDescriptionContext +{ + private readonly GraphNodeRecord m_node; + private readonly SerializationRegistry m_serialization; + private readonly SerializationContext m_context; + + internal ShaderNodeDescriptionContext( + GraphNodeRecord node, + SerializationRegistry serialization, + SerializationContext context, + ShaderSourceModuleAnalysis? sourceModule, + string implementationID, + ShaderIrStageInput? stageInput + ) { + m_node = node; + m_serialization = serialization; + m_context = context; + this.sourceModule = sourceModule; + this.implementationID = implementationID; + this.stageInput = stageInput; + } + + /// + /// Gets the node's stable identity, never its editor runtime handle. + /// + public GraphNodeID nodeID => m_node.id; + + /// + /// Gets the node definition's stable identity. + /// + public string definitionID => m_node.definitionID; + + /// + /// Gets a frozen module resolved by the asset owner; null means unassigned or unavailable. + /// + public ShaderSourceModuleAnalysis? sourceModule { get; } + + /// + /// Gets the exact implementation key chosen by the target. + /// + public string implementationID { get; } + + /// + /// Gets the target-assigned stage input for this node, when applicable. + /// + public ShaderIrStageInput? stageInput { get; } + + /// + /// Reads a property using the owner's converter generation and complete reference resolver context. + /// + /// + /// Declared property type supported by the native serializer. + /// + /// + /// Stable property identity. + /// + /// + /// Value used only when the property is absent, never after corrupt-data failure. + /// + /// + /// The deserialized value or the supplied absent-property default. + /// + public T Read( + string id, + T defaultValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + return m_node.TryGetValue(id, out GraphSerializedValue? value) + ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) + : defaultValue; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs new file mode 100644 index 000000000..ff2fe55e7 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Rendering.Shaders; + +/// +/// Supplies one node's connected values and the region builder during lowering only. +/// +public sealed class ShaderNodeLoweringContext +{ + internal ShaderNodeLoweringContext( + ShaderNodeDescriptionContext description, + ShaderIrBuilder builder, + IReadOnlyDictionary inputs + ) { + this.description = description; + this.builder = builder; + this.inputs = new ReadOnlyDictionary(new Dictionary(inputs, StringComparer.Ordinal)); + } + + /// + /// Gets the invocation-scoped node description. + /// + public ShaderNodeDescriptionContext description { get; } + + /// + /// Gets the builder shared by nodes in this typed region. + /// + public ShaderIrBuilder builder { get; } + + /// + /// Gets connected values keyed by semantic input port identity, never connection order. + /// + public IReadOnlyDictionary inputs { get; } + + /// + /// Requires one connected input without implicit defaults or positional rebinding. + /// + /// + /// Exact semantic input port identity. + /// + /// + /// The connected typed value. + /// + public ShaderIrValue Input(string id) + => inputs.TryGetValue(id, out ShaderIrValue? value) + ? value + : throw new InvalidOperationException($"Input '{id}' is not connected."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs new file mode 100644 index 000000000..448660749 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs @@ -0,0 +1,25 @@ +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares a typed shader port independently of editor presentation and backend source syntax. +/// +/// +/// Stable node-local port identity. +/// +/// +/// Complete value type, including all aggregate fields. +/// +/// +/// Input or output value flow. +/// +/// +/// Whether an input must be connected; alternative aggregate/member inputs validate in their compiler. +/// +public sealed record ShaderNodePort( + string id, + ShaderSourceType type, + GraphPortDirection direction, + bool required = true +); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs index 4175bf9d4..cea326cb4 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs @@ -11,7 +11,8 @@ public sealed class ShaderRerouteNodeCompiler : IShaderNodeCompiler /// /// Gets the definition id text used by the current instance. /// - public string definitionId => "inno.shader.reroute"; + public string definitionID => "inno.shader.reroute"; + /// /// Gets a ports required by the implemented contract. /// @@ -24,8 +25,12 @@ public sealed class ShaderRerouteNodeCompiler : IShaderNodeCompiler public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) { ShaderSourceType type = context.Read("valueType", new ShaderGraphType { id = "float" }).CreateType(); - return [new("input", type, GraphPortDirection.Input, required: false), new("value", type, GraphPortDirection.Output)]; + return [ + new ShaderNodePort("input", type, GraphPortDirection.Input, required: false), + new ShaderNodePort("value", type, GraphPortDirection.Output) + ]; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs new file mode 100644 index 000000000..6aeb24a23 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Samples a graph-connected texture with implicit derivatives or an explicit level of detail. +/// +public sealed class ShaderSampleNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.sample"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + string type = context.Read("type", "sampled-texture2d"); + string coordinate = type switch + { + "sampled-texture2d" => "float2", + "sampled-texture2d-array" or "sampled-texture3d" or "sampled-texture-cube" => "float3", + _ => throw new InvalidOperationException("Unknown sampled texture type.") + }; + List ports = + [ + new ShaderNodePort("texture", ShaderSourceType.Atomic(type), GraphPortDirection.Input), + new ShaderNodePort("coordinate", ShaderSourceType.Atomic(coordinate), GraphPortDirection.Input) + ]; + if (context.Read("explicitLevel", false)) + { + ports.Add(new ShaderNodePort("level", ShaderSourceType.Atomic("float"), GraphPortDirection.Input)); + } + ports.Add(new ShaderNodePort("value", ShaderSourceType.Atomic("float4"), GraphPortDirection.Output)); + return ports; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.description.Read("explicitLevel", false) + ? context.builder.SampleLevel(context.Input("texture"), context.Input("coordinate"), context.Input("level")) + : context.builder.Sample(context.Input("texture"), context.Input("coordinate")) + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs new file mode 100644 index 000000000..37d750504 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Selects between equal typed values; all producer effects remain evaluated before selection. +/// +public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.select"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); + return [ + new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new ShaderNodePort("true", type, GraphPortDirection.Input), + new ShaderNodePort("false", type, GraphPortDirection.Input), + new ShaderNodePort("value", type, GraphPortDirection.Output) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs new file mode 100644 index 000000000..021566b48 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers a parsed function module with name-based ports and explicit aggregate/member connection alternatives. +/// +public sealed class ShaderSourceNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.source"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceFunction function = RequireModule(context).function!; + List ports = []; + foreach (ShaderSourceParameter parameter in function.parameters) + { + if (parameter.direction != ShaderSourceParameterDirection.Output) + { + Add("input." + parameter.name, parameter.type, GraphPortDirection.Input); + } + if (parameter.direction != ShaderSourceParameterDirection.Input) + { + Add("output." + parameter.name, parameter.type, GraphPortDirection.Output); + } + } + if (function.returnType.id != "void") + { + Add("return", function.returnType, GraphPortDirection.Output); + } + return ports.AsReadOnly(); + void Add( + string name, + ShaderSourceType type, + GraphPortDirection direction + ) { + ports.Add(new ShaderNodePort(name, type, direction, required: false)); + foreach (ShaderSourceField field in type.fields) + { + Add(name + "." + field.name, field.type, direction); + } + } + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderSourceModuleAnalysis module = RequireModule(context.description); + var arguments = new Dictionary(StringComparer.Ordinal); + foreach (ShaderSourceParameter parameter in module.function!.parameters) + { + if (parameter.direction != ShaderSourceParameterDirection.Output) + { + arguments.Add(parameter.name, Resolve("input." + parameter.name, parameter.type)); + } + } + IReadOnlyDictionary values = context.builder.Call(module, context.description.implementationID, arguments); + var outputs = new Dictionary(StringComparer.Ordinal); + foreach ((string name, ShaderIrValue value) in values) + { + Add(name, value); + } + return outputs; + + ShaderIrValue Resolve( + string name, + ShaderSourceType type + ) { + if (context.inputs.TryGetValue(name, out ShaderIrValue? aggregate)) + { + if (context.inputs.Keys.Any(key => key.StartsWith(name + ".", StringComparison.Ordinal))) + { + throw new InvalidOperationException( + $"'{name}' connects both its aggregate and a member; choose one representation explicitly." + ); + } + return aggregate; + } + if (type.fields.Count == 0) + { + return context.Input(name); + } + return context.builder.Construct(type, type.fields.Select(field => Resolve(name + "." + field.name, field.type)).ToArray()); + } + + void Add( + string name, + ShaderIrValue value + ) { + outputs.Add(name, value); + for (int index = 0; index < value.type.fields.Count; index++) + { + Add(name + "." + value.type.fields[index].name, context.builder.Extract(value, index)); + } + } + } + + private static ShaderSourceModuleAnalysis RequireModule(ShaderNodeDescriptionContext context) + { + ShaderSourceModuleAnalysis? module = context.sourceModule; + if (module is null) + { + throw new InvalidOperationException( + "The source module is unassigned or unavailable; its stored reference and connections must remain intact." + ); + } + if (!module.succeeded) + { + throw new InvalidOperationException( + "The source module has no valid common interface: " + + string.Join("; ", module.diagnostics.Select(static value => value.message)) + ); + } + return module; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs new file mode 100644 index 000000000..ccd26045d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Reads one target-assigned stage/resource input without choosing a native variable name. +/// +public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.stage-input"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [new ShaderNodePort("value", RequireBinding(context).type, GraphPortDirection.Output)]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderIrStageInput input = RequireBinding(context.description); + return new Dictionary { ["value"] = context.builder.Input(input.id, input.type) }; + } + + private static ShaderIrStageInput RequireBinding(ShaderNodeDescriptionContext context) + => context.stageInput ?? throw new InvalidOperationException("The target has not resolved this stage input binding."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs new file mode 100644 index 000000000..5fa4708bb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-atomic-add"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, true); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary +{ + ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), + ["then"] = context.builder.Constant(true) +}; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs new file mode 100644 index 000000000..4cd536535 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-load"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, false, false); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary +{ + ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), + ["then"] = context.builder.Constant(true) +}; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs deleted file mode 100644 index cc47c4ec5..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Graphs; - -namespace Inno.Rendering.Shaders; - -internal static class StorageNodePorts -{ - internal static ShaderSourceType Resource(ShaderNodeDescriptionContext context) - => context.Read("resource", new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite }).CreateType(); - internal static ShaderSourceType Coordinate(ShaderStorageType storage) - => ShaderSourceType.Atomic(!storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"); - internal static IReadOnlyList Describe( - ShaderNodeDescriptionContext context, - bool write, - bool atomic - ) { - ShaderSourceType type = Resource(context); - ShaderStorageType storage = type.storage ?? throw new ArgumentException("A storage node requires a storage resource descriptor."); - var ports = new List - { - new("resource", type, GraphPortDirection.Input), - new("coordinate", Coordinate(storage), GraphPortDirection.Input), - new("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), - new("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) - }; - if (write) - ports.Add(new("value", storage.valueType, GraphPortDirection.Input)); - if (!write || atomic) - ports.Add(new(atomic ? "previous" : "value", storage.valueType, GraphPortDirection.Output)); - return ports; - } -} - -internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionId => "inno.shader.storage-load"; - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, false, false); - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), - ["then"] = context.builder.Constant(true) - }; -} - -internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionId => "inno.shader.storage-store"; - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, false); - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - context.builder.StoreStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")); - return new Dictionary { ["then"] = context.builder.Constant(true) }; - } -} - -internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionId => "inno.shader.storage-atomic-add"; - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, true); - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), - ["then"] = context.builder.Constant(true) - }; -} - -internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionId => "inno.shader.discard"; - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), - new("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), - new("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output)]; - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - context.builder.Discard(context.Input("condition")); - return new Dictionary { ["then"] = context.builder.Constant(true) }; - } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs new file mode 100644 index 000000000..292b3f01c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-store"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, false); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + context.builder.StoreStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")); + return new Dictionary { ["then"] = context.builder.Constant(true) }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs deleted file mode 100644 index 691299c71..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Graphs; - -namespace Inno.Rendering.Shaders; - -/// -/// Extracts one statically selected component from a vector or matrix. -/// -public sealed class ShaderExtractNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.extract"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float4")); - var builder = new ShaderIrBuilder(); - ShaderIrValue member = builder.Extract(builder.Input("input", type), context.Read("index", 0)); - return [new("input", type, GraphPortDirection.Input), new("value", member.type, GraphPortDirection.Output)]; - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) }; -} - -/// -/// Samples a graph-connected texture with implicit derivatives or an explicit level of detail. -/// -public sealed class ShaderSampleNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => "inno.shader.sample"; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - string type = context.Read("type", "sampled-texture2d"); - string coordinate = type switch { "sampled-texture2d" => "float2", "sampled-texture2d-array" or "sampled-texture3d" or "sampled-texture-cube" => "float3", _ => throw new InvalidOperationException("Unknown sampled texture type.") }; - var ports = new List { new("texture", ShaderSourceType.Atomic(type), GraphPortDirection.Input), new("coordinate", ShaderSourceType.Atomic(coordinate), GraphPortDirection.Input) }; - if (context.Read("explicitLevel", false)) - ports.Add(new("level", ShaderSourceType.Atomic("float"), GraphPortDirection.Input)); - ports.Add(new("value", ShaderSourceType.Atomic("float4"), GraphPortDirection.Output)); - return ports; - } - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.description.Read("explicitLevel", false) - ? context.builder.SampleLevel(context.Input("texture"), context.Input("coordinate"), context.Input("level")) - : context.builder.Sample(context.Input("texture"), context.Input("coordinate")) }; -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs new file mode 100644 index 000000000..cc4400a88 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +internal static class StorageNodePorts +{ + internal static ShaderSourceType Resource(ShaderNodeDescriptionContext context) + => context + .Read( + "resource", + new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } + ) + .CreateType(); + + internal static ShaderSourceType Coordinate(ShaderStorageType storage) + => ShaderSourceType.Atomic( + !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2" + ); + + internal static IReadOnlyList Describe( + ShaderNodeDescriptionContext context, + bool write, + bool atomic + ) { + ShaderSourceType type = Resource(context); + ShaderStorageType storage = type.storage ?? throw new ArgumentException("A storage node requires a storage resource descriptor."); + List ports = + [ + new ShaderNodePort("resource", type, GraphPortDirection.Input), + new ShaderNodePort("coordinate", Coordinate(storage), GraphPortDirection.Input), + new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), + new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) + ]; + if (write) + { + ports.Add(new ShaderNodePort("value", storage.valueType, GraphPortDirection.Input)); + } + if (!write || atomic) + { + ports.Add(new ShaderNodePort(atomic ? "previous" : "value", storage.valueType, GraphPortDirection.Output)); + } + return ports; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs index abe887b38..674a1be96 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs @@ -18,7 +18,7 @@ public static class ShaderGraphBindings /// /// Current shader graph, never mutated by this operation. /// - /// + /// /// Explicitly selected node identities. Deleting an output also deletes its stage contents. /// /// @@ -35,47 +35,83 @@ public static class ShaderGraphBindings /// public static GraphDocument RemoveNodes( GraphDocument graph, - IEnumerable nodeIds, + IEnumerable nodeIDs, SerializationRegistry serialization, SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); - ArgumentNullException.ThrowIfNull(nodeIds); - HashSet removed = [.. nodeIds]; - foreach (GraphNodeId id in removed) + ArgumentNullException.ThrowIfNull(nodeIDs); + HashSet removed = [.. nodeIDs]; + foreach (GraphNodeID id in removed) + { if (graph.FindNode(id) is null) - throw new ArgumentException("A selected shader node is missing.", nameof(nodeIds)); + { + throw new ArgumentException("A selected shader node is missing.", nameof(nodeIDs)); + } + } GraphDocument candidate = graph.Clone(); - HashSet stages = graph.nodes.Where(node => removed.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) - .Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + HashSet stages = graph.nodes + .Where(node => removed.Contains(node.id) && node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .Select(static node => node.id.value) + .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in graph.nodes) - if (stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { + if (stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context))) + { removed.Add(node.id); + } + } - ShaderGraphPassProgram[] programs = graph.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) - ? ShaderGraphPrograms.Read(graph, serialization, context) : []; + ShaderGraphPassProgram[] programs = graph.metadata.ContainsKey(ShaderGraphPrograms.C_BINDINGS_KEY) + ? ShaderGraphPrograms.Read(graph, serialization, context) + : []; HashSet affectedPasses = programs.Where(program => program.stages.Any(stages.Contains)) - .Select(static program => program.pass).ToHashSet(StringComparer.Ordinal); + .Select(static program => program.pass) + .ToHashSet(StringComparer.Ordinal); ShaderGraphPassProgram[] retainedPrograms = programs.Where(program => !affectedPasses.Contains(program.pass)).ToArray(); HashSet retainedStages = retainedPrograms.SelectMany(static program => program.stages).ToHashSet(StringComparer.Ordinal); - foreach (string stage in programs.Where(program => affectedPasses.Contains(program.pass)).SelectMany(static program => program.stages)) + foreach (string stage in programs + .Where(program => affectedPasses.Contains(program.pass)) + .SelectMany(static program => program.stages) + ) { if (!retainedStages.Contains(stage)) + { stages.Add(stage); + } + } foreach (GraphNodeRecord node in graph.nodes) - if (stages.Contains(node.id.value) || stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { + if (stages.Contains(node.id.value) + || stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context)) + ) { removed.Add(node.id); + } + } HashSet affectedBindings = []; - foreach (GraphNodeRecord node in graph.nodes.Where(node => removed.Contains(node.id) && node.definitionId == "inno.shader.stage-input")) - { - ShaderGraphInputSettings input = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); + foreach (GraphNodeRecord node in graph.nodes.Where( + node => removed.Contains(node.id) && node.definitionID == "inno.shader.stage-input" + )) { + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); if (IsBinding(input)) + { affectedBindings.Add(input.id); - affectedBindings.Add(ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context)); + } + affectedBindings.Add(ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context)); } - foreach (GraphNodeId id in removed) + foreach (GraphNodeID id in removed) + { candidate.RemoveNode(id); - if (!candidate.metadata.ContainsKey(ShaderGraphDocument.definitionKey)) + } + if (!candidate.metadata.ContainsKey(ShaderGraphDocument.C_DEFINITION_KEY)) + { return candidate; + } ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); ShaderGraphPrograms.Write(candidate, retainedPrograms, serialization, context); definition.passes = definition.passes.Where(pass => !affectedPasses.Contains(pass.name)).ToArray(); @@ -86,25 +122,44 @@ SerializationContext context definition.techniques[i] = technique; } var remainingBindings = new Dictionary(StringComparer.Ordinal); - foreach (GraphNodeRecord node in candidate.nodes.Where(static node => node.definitionId == "inno.shader.stage-input")) + foreach (GraphNodeRecord node in candidate.nodes.Where(static node => node.definitionID == "inno.shader.stage-input")) { - ShaderGraphInputSettings input = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); - string id = string.IsNullOrWhiteSpace(input.id) ? ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context) : input.id; + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); + string id = string.IsNullOrWhiteSpace(input.id) + ? ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context) + : input.id; if (!IsBinding(input) || !affectedBindings.Contains(id)) + { continue; - string stageId = ShaderGraphDocument.Read(node, "stage", "", serialization, context); - GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); - ShaderStage stage = output is null ? ShaderStage.None : ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; + } + string stageID = ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context); + GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageID) ? null : candidate.FindNode(new GraphNodeID(stageID)); + ShaderStage stage = output is null + ? ShaderStage.None + : ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; remainingBindings[id] = remainingBindings.GetValueOrDefault(id) | stage; } - definition.properties = definition.properties.Where(property => !affectedBindings.Contains(property.id.value) || remainingBindings.ContainsKey(property.id.value)) + definition.properties = definition.properties + .Where(property => !affectedBindings.Contains(property.id.value) || remainingBindings.ContainsKey(property.id.value)) .Select(property => { if (remainingBindings.TryGetValue(property.id.value, out ShaderStage stagesUsed)) + { property.stages = stagesUsed; + } return property; - }).ToArray(); - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + }) + .ToArray(); + candidate.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); return candidate; } @@ -114,7 +169,7 @@ SerializationContext context /// /// Current shader graph, never mutated by this operation. /// - /// + /// /// Stage input node identity. /// /// @@ -134,7 +189,7 @@ SerializationContext context /// public static GraphDocument ChangeInput( GraphDocument graph, - GraphNodeId nodeId, + GraphNodeID nodeID, ShaderGraphInputSettings settings, SerializationRegistry serialization, SerializationContext context @@ -142,60 +197,111 @@ SerializationContext context ArgumentNullException.ThrowIfNull(graph); ArgumentNullException.ThrowIfNull(settings); GraphDocument candidate = graph.Clone(); - GraphNodeRecord node = candidate.FindNode(nodeId) ?? throw new ArgumentException("The stage input node is missing.", nameof(nodeId)); - if (node.definitionId != "inno.shader.stage-input") - throw new ArgumentException("The node is not a stage input.", nameof(nodeId)); - ShaderGraphInputSettings previous = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); + GraphNodeRecord node = candidate.FindNode(nodeID) + ?? throw new ArgumentException("The stage input node is missing.", nameof(nodeID)); + if (node.definitionID != "inno.shader.stage-input") + { + throw new ArgumentException("The node is not a stage input.", nameof(nodeID)); + } + ShaderGraphInputSettings previous = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); // Keep the last declared identity through incomplete text input; clearing a name must not erase its default value. if (string.IsNullOrWhiteSpace(previous.id)) - previous.id = ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context); + { + previous.id = ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context); + } node.SetValue("settings", ShaderGraphDocument.Encode(settings, serialization, context)); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); - var properties = definition.properties.ToList(); - ShaderPropertyDefinition? previousProperty = properties.Where(value => value.id.value == previous.id).Cast().FirstOrDefault(); + List properties = definition.properties.ToList(); + ShaderPropertyDefinition? previousProperty = properties + .Where(value => value.id.value == previous.id) + .Cast() + .FirstOrDefault(); if (IsBinding(previous) && !string.IsNullOrWhiteSpace(previous.id)) + { node.SetValue("bindingIdentity", ShaderGraphDocument.Encode(previous.id, serialization, context)); + } if (IsBinding(previous) && (!IsBinding(settings) || !string.IsNullOrWhiteSpace(settings.id) && previous.id != settings.id) - && !candidate.nodes.Where(value => value.id != nodeId && value.definitionId == "inno.shader.stage-input") + && !candidate.nodes.Where(value => value.id != nodeID && value.definitionID == "inno.shader.stage-input") .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context)) - .Any(value => IsBinding(value) && value.id == previous.id)) + .Any(value => IsBinding(value) && value.id == previous.id) + ) { properties.RemoveAll(value => value.id.value == previous.id); + } if (IsBinding(settings) && !string.IsNullOrWhiteSpace(settings.id) && TryPropertyType(settings.type, out ShaderPropertyType type)) { - ShaderPropertyDefinition? existing = properties.Where(value => value.id.value == settings.id).Cast().FirstOrDefault(); + ShaderPropertyDefinition? existing = properties + .Where(value => value.id.value == settings.id) + .Cast() + .FirstOrDefault(); ShaderPropertyDefinition? source = existing ?? previousProperty; if (type == ShaderPropertyType.Vector4 && source?.type == ShaderPropertyType.Color) + { type = ShaderPropertyType.Color; + } ShaderPropertyBindingKind kind = settings.kind switch { ShaderIrInputKind.SampledTexture => ShaderPropertyBindingKind.SampledTexture, - ShaderIrInputKind.Storage => settings.type.isImage ? ShaderPropertyBindingKind.StorageTexture : ShaderPropertyBindingKind.StorageBuffer, + ShaderIrInputKind.Storage => settings.type.isImage + ? ShaderPropertyBindingKind.StorageTexture + : ShaderPropertyBindingKind.StorageBuffer, _ => ShaderPropertyBindingKind.Uniform }; ShaderStage stages = ShaderStage.None; - foreach (GraphNodeRecord input in candidate.nodes.Where(static value => value.definitionId == "inno.shader.stage-input")) + foreach (GraphNodeRecord input in candidate.nodes.Where(static value => value.definitionID == "inno.shader.stage-input")) { - ShaderGraphInputSettings value = ShaderGraphDocument.Read(input, "settings", new ShaderGraphInputSettings(), serialization, context); + ShaderGraphInputSettings value = ShaderGraphDocument.Read( + input, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); if (value.id != settings.id || !IsBinding(value)) + { continue; - string stageId = ShaderGraphDocument.Read(input, "stage", "", serialization, context); - GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); + } + string stageID = ShaderGraphDocument.Read(input, "stage", string.Empty, serialization, context); + GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageID) ? null : candidate.FindNode(new GraphNodeID(stageID)); if (output is not null) + { stages |= ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; + } } MaterialValue defaultValue = source?.type == type ? source.Value.defaultValue : default; - var declaration = new ShaderPropertyDefinition(new(settings.id), source?.displayName ?? settings.id, type, stages, - defaultValue, kind, settings.type.access, source?.bindingOwner ?? (kind is ShaderPropertyBindingKind.StorageBuffer or ShaderPropertyBindingKind.StorageTexture - ? ShaderPropertyBindingOwner.RenderPass : ShaderPropertyBindingOwner.Material)); + var declaration = new ShaderPropertyDefinition( + new ShaderPropertyID(settings.id), + source?.displayName ?? settings.id, + type, + stages, + defaultValue, + kind, + settings.type.access, + source?.bindingOwner ?? (kind is ShaderPropertyBindingKind.StorageBuffer or ShaderPropertyBindingKind.StorageTexture + ? ShaderPropertyBindingOwner.RenderPass + : ShaderPropertyBindingOwner.Material) + ); int index = properties.FindIndex(value => value.id.value == settings.id); if (index < 0) + { properties.Add(declaration); + } else + { properties[index] = declaration; + } node.SetValue("bindingIdentity", ShaderGraphDocument.Encode(settings.id, serialization, context)); } definition.properties = properties.ToArray(); - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + candidate.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); return candidate; } @@ -206,17 +312,27 @@ private static bool TryPropertyType( ShaderGraphType value, out ShaderPropertyType type ) { - type = value.isStorage ? value.isImage ? value.dimension switch - { - RenderTextureDimension.Texture3D => ShaderPropertyType.Texture3D, - RenderTextureDimension.Cube => ShaderPropertyType.TextureCube, - _ => value.isArray ? ShaderPropertyType.Texture2DArray : ShaderPropertyType.Texture2D - } : ShaderPropertyType.Buffer : (value.element ?? value).id switch + type = value.isStorage + ? value.isImage + ? value.dimension switch +{ + RenderTextureDimension.Texture3D => ShaderPropertyType.Texture3D, + RenderTextureDimension.Cube => ShaderPropertyType.TextureCube, + _ => value.isArray ? ShaderPropertyType.Texture2DArray : ShaderPropertyType.Texture2D +} + : ShaderPropertyType.Buffer + : (value.element ?? value).id switch { - "float" => ShaderPropertyType.Float, "float2" => ShaderPropertyType.Vector2, "float3" => ShaderPropertyType.Vector3, - "float4" => ShaderPropertyType.Vector4, "float4x4" => ShaderPropertyType.Matrix4x4, - "sampled-texture2d" => ShaderPropertyType.Texture2D, "sampled-texture2d-array" => ShaderPropertyType.Texture2DArray, - "sampled-texture3d" => ShaderPropertyType.Texture3D, "sampled-texture-cube" => ShaderPropertyType.TextureCube, _ => (ShaderPropertyType)(-1) + "float" => ShaderPropertyType.Float, + "float2" => ShaderPropertyType.Vector2, + "float3" => ShaderPropertyType.Vector3, + "float4" => ShaderPropertyType.Vector4, + "float4x4" => ShaderPropertyType.Matrix4x4, + "sampled-texture2d" => ShaderPropertyType.Texture2D, + "sampled-texture2d-array" => ShaderPropertyType.Texture2DArray, + "sampled-texture3d" => ShaderPropertyType.Texture3D, + "sampled-texture-cube" => ShaderPropertyType.TextureCube, + _ => (ShaderPropertyType)(-1) }; return Enum.IsDefined(type); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs new file mode 100644 index 000000000..f541682b0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes graph-authored node references before they are expanded or consumed by a Target. +/// +public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_CALL_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphNodes.C_INTERFACE_KEY, new ShaderGraphNodeInterface()).GetPorts(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("A graph-authored node must be expanded or consumed by its Shader Target before lowering."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs index 76d5f1f5c..631eae61c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs @@ -32,17 +32,24 @@ public static class ShaderGraphClipboard /// public static GraphDocument Copy( GraphDocument graph, - IEnumerable nodes, + IEnumerable nodes, SerializationRegistry serialization, SerializationContext context ) { GraphDocument fragment = graph.Clone(); - HashSet selected = [.. nodes]; - HashSet stages = fragment.nodes.Where(node => selected.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) - .Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + HashSet selected = [.. nodes]; + HashSet stages = fragment.nodes + .Where(node => selected.Contains(node.id) && node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .Select(static node => node.id.value) + .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in fragment.nodes.ToArray()) - if (!selected.Contains(node.id) && !stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { + if (!selected.Contains(node.id) + && !stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context)) + ) { fragment.RemoveNode(node.id); + } + } return fragment; } @@ -74,35 +81,51 @@ public static ShaderGraphPasteResult Paste( GraphDocument graph, GraphDocument fragment, bool preserveExternalStageReferences, - GraphNodeId? activeStage, + GraphNodeID? activeStage, SerializationRegistry serialization, SerializationContext context ) { GraphDocument candidate = graph.Clone(); - ShaderDefinition? definition = candidate.metadata.ContainsKey(ShaderGraphDocument.definitionKey) ? ShaderGraphDocument.ReadDefinition(candidate, serialization, context) : null; - ShaderDefinition? source = fragment.metadata.ContainsKey(ShaderGraphDocument.definitionKey) ? ShaderGraphDocument.ReadDefinition(fragment, serialization, context) : null; - Dictionary remap = fragment.nodes.ToDictionary(static node => node.id, static _ => new GraphNodeId(Guid.NewGuid().ToString("N"))); + ShaderDefinition? definition = candidate.metadata.ContainsKey(ShaderGraphDocument.C_DEFINITION_KEY) + ? ShaderGraphDocument.ReadDefinition(candidate, serialization, context) + : null; + ShaderDefinition? source = fragment.metadata.ContainsKey(ShaderGraphDocument.C_DEFINITION_KEY) + ? ShaderGraphDocument.ReadDefinition(fragment, serialization, context) + : null; + Dictionary remap = fragment.nodes.ToDictionary( + static node => node.id, + static _ => new GraphNodeID(Guid.NewGuid().ToString("N")) + ); var passes = new Dictionary(StringComparer.Ordinal); - var programs = candidate.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) - ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() : []; + List programs = candidate.metadata.ContainsKey(ShaderGraphPrograms.C_BINDINGS_KEY) + ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() + : []; if (definition is not null && source is not null) { foreach (ShaderGraphPassProgram program in ShaderGraphPrograms.Read(fragment, serialization, context)) { - GraphNodeId[] copiedStages = program.stages.Select(static id => new GraphNodeId(id)).Where(remap.ContainsKey).ToArray(); + GraphNodeID[] copiedStages = program.stages.Select(static id => new GraphNodeID(id)).Where(remap.ContainsKey).ToArray(); if (copiedStages.Length == 0) + { continue; + } int index = Array.FindIndex(source.passes, pass => pass.name == program.pass); if (index < 0) + { continue; + } string destination = program.pass; for (int suffix = 2; definition.passes.Any(pass => pass.name == destination); suffix++) + { destination = program.pass + " " + suffix; + } passes.Add(program.pass, destination); ShaderPassDefinition pass = source.passes[index]; pass.name = destination; definition.passes = [.. definition.passes, pass]; - programs.Add(new() { pass = destination, stages = copiedStages.Select(id => remap[id].value).ToArray() }); + programs.Add( + new ShaderGraphPassProgram() { pass = destination, stages = copiedStages.Select(id => remap[id].value).ToArray() } + ); } } if (definition is not null && source is not null) @@ -110,78 +133,114 @@ SerializationContext context foreach (ShaderTechniqueDefinition technique in source.techniques) { ShaderTechniquePass[] mappings = technique.passes.Where(mapping => passes.ContainsKey(mapping.passName)) - .Select(mapping => new ShaderTechniquePass(mapping.role, passes[mapping.passName])).ToArray(); + .Select(mapping => new ShaderTechniquePass(mapping.role, passes[mapping.passName])) + .ToArray(); if (mappings.Length == 0) + { continue; + } string id = technique.id.value; for (int suffix = 2; definition.techniques.Any(value => value.id.value == id); suffix++) + { id = technique.id.value + "-" + suffix; - definition.techniques = [.. definition.techniques, new ShaderTechniqueDefinition(new(id), technique.contract, mappings, technique.requiredFeatures)]; + } + definition.techniques = + [ + .. definition.techniques, + new ShaderTechniqueDefinition(new ShaderTechniqueID(id), technique.contract, mappings, technique.requiredFeatures) + ]; } } - GraphNodeId? targetStage = activeStage ?? candidate.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; + GraphNodeID? targetStage = activeStage + ?? candidate.nodes.FirstOrDefault(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID)?.id; foreach (GraphNodeRecord node in fragment.nodes) { - var clone = new GraphNodeRecord(remap[node.id], node.definitionId) { position = new(node.position.x + 32, node.position.y + 32) }; - foreach (var value in node.values) + var clone = new GraphNodeRecord(remap[node.id], node.definitionID) + { + position = new(node.position.x + 32, node.position.y + 32) + }; + foreach (KeyValuePair value in node.values) + { clone.SetValue(value.Key, value.Value.Clone()); - string stage = ShaderGraphDocument.Read(node, "stage", "", serialization, context); + } + string stage = ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context); if (stage.Length != 0) { - if (remap.TryGetValue(new(stage), out GraphNodeId mapped)) + if (remap.TryGetValue(new GraphNodeID(stage), out GraphNodeID mapped)) + { stage = mapped.value; - else if ((!preserveExternalStageReferences || candidate.FindNode(new(stage)) is null) && targetStage is GraphNodeId target) + } + else if ((!preserveExternalStageReferences || candidate.FindNode(new GraphNodeID(stage)) is null) + && targetStage is GraphNodeID target + ) { stage = target.value; + } clone.SetValue("stage", ShaderGraphDocument.Encode(stage, serialization, context)); } candidate.AddNode(clone); } foreach (GraphEdgeRecord edge in fragment.edges) - candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(remap[edge.output.nodeId], edge.output.portId), new(remap[edge.input.nodeId], edge.input.portId))); + { + candidate.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(remap[edge.output.nodeID], edge.output.portID), + new GraphEndpoint(remap[edge.input.nodeID], edge.input.portID) + ) + ); + } if (definition is not null) { - candidate.SetMetadata(ShaderGraphPrograms.bindingsKey, ShaderGraphDocument.Encode(programs.ToArray(), serialization, context)); + candidate.SetMetadata( + ShaderGraphPrograms.C_BINDINGS_KEY, + ShaderGraphDocument.Encode(programs.ToArray(), serialization, context) + ); // Preserve copied defaults. Reject incompatible destination bindings before publishing any edit. if (source is not null) { - HashSet bindings = fragment.nodes.Where(static node => node.definitionId == "inno.shader.stage-input") - .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).id).ToHashSet(StringComparer.Ordinal); - definition.properties = [.. definition.properties, .. source.properties.Where(property => bindings.Contains(property.id.value) - && !definition.properties.Any(existing => existing.id == property.id))]; + HashSet bindings = fragment.nodes.Where(static node => node.definitionID == "inno.shader.stage-input") + .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).id) + .ToHashSet(StringComparer.Ordinal); + definition.properties = + [ + .. definition.properties, + .. source.properties.Where(property => ( + bindings.Contains(property.id.value) + && !definition.properties.Any(existing => existing.id == property.id) + )) + ]; + } + candidate.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); + foreach (GraphNodeRecord node in candidate.nodes + .Where(node => remap.Values.Contains(node.id) && node.definitionID == "inno.shader.stage-input") + .ToArray() + ) { + candidate = ShaderGraphBindings.ChangeInput( + candidate, + node.id, + ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), + serialization, + context + ); } - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); - foreach (GraphNodeRecord node in candidate.nodes.Where(node => remap.Values.Contains(node.id) && node.definitionId == "inno.shader.stage-input").ToArray()) - candidate = ShaderGraphBindings.ChangeInput(candidate, node.id, ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), serialization, context); ShaderDefinition updated = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); foreach (ShaderPropertyDefinition property in definition.properties) { ShaderPropertyDefinition next = updated.properties.Single(value => value.id == property.id); - if (next.type != property.type || next.bindingKind != property.bindingKind || next.storageAccess != property.storageAccess || next.bindingOwner != property.bindingOwner) - throw new InvalidOperationException($"Cannot paste incompatible shader parameter '{property.id.value}'. Rename the copied parameter first."); + if (next.type != property.type + || next.bindingKind != property.bindingKind + || next.storageAccess != property.storageAccess + || next.bindingOwner != property.bindingOwner + ) { + throw new InvalidOperationException( + $"Cannot paste incompatible shader parameter '{property.id.value}'. Rename the copied parameter first." + ); + } } } return new(candidate, remap.Values.ToArray()); } } - -/// -/// Contains a detached paste candidate and its newly allocated node identities. -/// -public sealed class ShaderGraphPasteResult -{ - internal ShaderGraphPasteResult( - GraphDocument graph, - GraphNodeId[] nodes - ) { - document = graph; - insertedNodes = Array.AsReadOnly(nodes); - } - /// - /// Gets the complete detached candidate; the caller owns its subsequent edits. - /// - public GraphDocument document { get; } - /// - /// Gets new identities suitable for selecting the pasted nodes. - /// - public IReadOnlyList insertedNodes { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs index e40ed9cf2..463e8ce69 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs @@ -13,11 +13,32 @@ public static class ShaderGraphDocument /// /// Identifies the graph metadata containing the source-free material and pass contract. /// - public const string definitionKey = "inno.shader.definition"; + public const string C_DEFINITION_KEY = "inno.shader.definition"; + /// /// Identifies the optional domain target; absent means explicitly authored generic stages. /// - public const string targetKey = "inno.shader.target"; + public const string C_TARGET_KEY = "inno.shader.target"; + + /// + /// Identifies a stage output node; its incoming edges name the stage's GPU outputs. + /// + public const string C_OUTPUT_DEFINITION_ID = "inno.shader.stage-output"; + + /// + /// Identifies a node property containing its owning stage output node identity. + /// + public const string C_STAGE_KEY = "stage"; + + /// + /// Identifies the structured settings stored on a stage output node. + /// + public const string C_SETTINGS_KEY = "settings"; + + /// + /// Prefixes stable port IDs storing explicit typed defaults for unconnected inputs. + /// + public const string C_INPUT_DEFAULT_PREFIX = "input-default."; /// /// Reads the stable domain target assignment without resolving extension instances. @@ -38,8 +59,9 @@ public static string ReadTarget( GraphDocument graph, SerializationRegistry serialization, SerializationContext context - ) - => graph.metadata.TryGetValue(targetKey, out GraphSerializedValue? value) ? Decode(value, serialization, context) : ""; + ) => graph.metadata.TryGetValue(C_TARGET_KEY, out GraphSerializedValue? value) + ? Decode(value, serialization, context) + : string.Empty; /// /// Assigns a domain target by stable identity without retaining its current provider. @@ -47,7 +69,7 @@ SerializationContext context /// /// Document being authored. /// - /// + /// /// Stable target identity; empty selects explicit generic stage authoring. /// /// @@ -58,32 +80,20 @@ SerializationContext context /// public static void SetTarget( GraphDocument graph, - string targetId, + string targetID, SerializationRegistry serialization, SerializationContext context ) { - ArgumentNullException.ThrowIfNull(targetId); - if (targetId.Length == 0) - graph.RemoveMetadata(targetKey); + ArgumentNullException.ThrowIfNull(targetID); + if (targetID.Length == 0) + { + graph.RemoveMetadata(C_TARGET_KEY); + } else - graph.SetMetadata(targetKey, Encode(targetId, serialization, context)); + { + graph.SetMetadata(C_TARGET_KEY, Encode(targetID, serialization, context)); + } } - /// - /// Identifies a stage output node; its incoming edges name the stage's GPU outputs. - /// - public const string outputDefinitionId = "inno.shader.stage-output"; - /// - /// Identifies a node property containing its owning stage output node identity. - /// - public const string stageKey = "stage"; - /// - /// Identifies the structured settings stored on a stage output node. - /// - public const string settingsKey = "settings"; - /// - /// Prefixes stable port IDs storing explicit typed defaults for unconnected inputs. - /// - public const string inputDefaultPrefix = "input-default."; /// /// Creates an empty graph with a source-free shader contract; incomplete graphs remain serializable. @@ -107,7 +117,7 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(definition); var graph = new GraphDocument(); - graph.SetMetadata(definitionKey, Encode(serialization.Serialize(definition, context), serialization, context)); + graph.SetMetadata(C_DEFINITION_KEY, Encode(serialization.Serialize(definition, context), serialization, context)); ShaderGraphPrograms.Write(graph, [], serialization, context); return graph; } @@ -133,8 +143,10 @@ public static ShaderDefinition ReadDefinition( SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); - if (!graph.metadata.TryGetValue(definitionKey, out GraphSerializedValue? value)) + if (!graph.metadata.TryGetValue(C_DEFINITION_KEY, out GraphSerializedValue? value)) + { throw new InvalidOperationException("The shader graph has no program definition."); + } return serialization.Deserialize(Decode(value, serialization, context), context); } @@ -225,91 +237,5 @@ public static T Read( T defaultValue, SerializationRegistry serialization, SerializationContext context - ) - => node.TryGetValue(key, out GraphSerializedValue? value) ? Decode(value!, serialization, context) : defaultValue; -} - -/// -/// Stores one stage's explicit output interface and compute dimensions inside its output node. -/// -public sealed class ShaderGraphStageSettings : ISerializable -{ - /// - /// Gets or sets the programmable stage. - /// - [SerializableProperty] public ShaderStage stage { get; set; } = ShaderStage.Fragment; - /// - /// Gets or sets output ports and their GPU destinations. - /// - [SerializableProperty] public ShaderGraphOutput[] outputs { get; set; } = []; - /// - /// Gets or sets compute workgroup width. - /// - [SerializableProperty] public int threadsX { get; set; } = 1; - /// - /// Gets or sets compute workgroup height. - /// - [SerializableProperty] public int threadsY { get; set; } = 1; - /// - /// Gets or sets compute workgroup depth. - /// - [SerializableProperty] public int threadsZ { get; set; } = 1; -} - -/// -/// Stores one stable output port's destination, independent of adapter source syntax. -/// -public struct ShaderGraphOutput -{ - /// - /// Gets or sets the stable input port identity on the stage output node. - /// - public string id { get; set; } - /// - /// Gets or sets the GPU destination category. - /// - public ShaderIrOutputKind kind { get; set; } - /// - /// Gets or sets the varying semantic; empty for fixed position, color or depth outputs. - /// - public string semantic { get; set; } - /// - /// Gets or sets the varying or attachment index. - /// - public int location { get; set; } -} - -/// -/// Stores a stage input node's logical interface without native names or GPU handles. -/// -public sealed class ShaderGraphInputSettings : ISerializable -{ - /// - /// Gets or sets the stable logical binding identity. - /// - [SerializableProperty] public string id { get; set; } = "input"; - /// - /// Gets or sets the complete neutral type descriptor. - /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new(); - /// - /// Gets or sets the stage input category. - /// - [SerializableProperty] public ShaderIrInputKind kind { get; set; } - /// - /// Gets or sets the target semantic, not a native expression. - /// - [SerializableProperty] public string semantic { get; set; } = "position"; - /// - /// Gets or sets the interface index. - /// - [SerializableProperty] public int location { get; set; } - - /// - /// Validates the persisted descriptor and freezes its stage binding. - /// - /// - /// An immutable backend-neutral input binding. - /// - public ShaderIrStageInput CreateBinding() => new(id, type.CreateType(), kind, semantic, location); + ) => node.TryGetValue(key, out GraphSerializedValue? value) ? Decode(value!, serialization, context) : defaultValue; } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs new file mode 100644 index 000000000..d9513b4cb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs @@ -0,0 +1,47 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores a stage input node's logical interface without native names or GPU handles. +/// +public sealed class ShaderGraphInputSettings : ISerializable +{ + /// + /// Gets or sets the stable logical binding identity. + /// + [SerializableProperty] + public string id { get; set; } = "input"; + + /// + /// Gets or sets the complete neutral type descriptor. + /// + [SerializableProperty] + public ShaderGraphType type { get; set; } = new(); + + /// + /// Gets or sets the stage input category. + /// + [SerializableProperty] + public ShaderIrInputKind kind { get; set; } + + /// + /// Gets or sets the target semantic, not a native expression. + /// + [SerializableProperty] + public string semantic { get; set; } = "position"; + + /// + /// Gets or sets the interface index. + /// + [SerializableProperty] + public int location { get; set; } + + /// + /// Validates the persisted descriptor and freezes its stage binding. + /// + /// + /// An immutable backend-neutral input binding. + /// + public ShaderIrStageInput CreateBinding() => new(id, type.CreateType(), kind, semantic, location); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs new file mode 100644 index 000000000..aec6986b6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphInputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphInputSettings value + ) { + writer.Write("id", value.id); + writer.Write("type", value.type); + writer.Write("kind", value.kind); + writer.Write("semantic", value.semantic); + writer.Write("location", value.location); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph input settings that represents the completed operation. + /// + public override ShaderGraphInputSettings Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + type = reader.Read("type"), + kind = reader.Read("kind"), + semantic = reader.Read("semantic"), + location = reader.Read("location") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs index 917616fa9..792c97634 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs @@ -12,31 +12,14 @@ public sealed class ShaderGraphLiteral : ISerializable /// /// Gets or sets the complete value type, including named aggregates and fixed arrays. /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; - /// - /// Gets or sets scalar bit patterns in declaration order; matrices use column-major order. - /// - [SerializableProperty] public uint[] scalarBits { get; set; } = [0]; + [SerializableProperty] + public ShaderGraphType type { get; set; } = new() { id = "float" }; /// - /// Creates an explicit zero value for a supported scalar, vector, matrix, structure or array. + /// Gets or sets scalar bit patterns in declaration order; matrices use column-major order. /// - /// - /// Complete numeric or boolean value type; resources and effect tokens are not values. - /// - /// - /// A detached zero literal with an exact type and component count. - /// - /// - /// The type is opaque or exceeds the bounded literal size. - /// - public static ShaderGraphLiteral Zero(ShaderSourceType type) - { - ArgumentNullException.ThrowIfNull(type); - var scalars = new List(); - Flatten(type, scalars, 0); - return new() { type = ShaderGraphType.Capture(type), scalarBits = new uint[scalars.Count] }; - } + [SerializableProperty] + public uint[] scalarBits { get; set; } = [0]; /// /// Gets the exact scalar type of each stored component for shared Inspector value controls. @@ -47,14 +30,22 @@ public static ShaderGraphLiteral Zero(ShaderSourceType type) public IReadOnlyList GetScalarTypes() { if (type is null || scalarBits is null) + { throw new InvalidOperationException("The input default must retain a type and scalar bits."); - var scalars = new List(); + } + List scalars = []; Flatten(type.CreateType(), scalars, 0); if (scalarBits.Length != scalars.Count) + { throw new InvalidOperationException("The input default's component count does not match its type."); + } for (int i = 0; i < scalars.Count; i++) + { if (scalars[i] == "bool" && scalarBits[i] > 1) + { throw new InvalidOperationException("A boolean input default must contain zero or one."); + } + } return scalars; } @@ -82,7 +73,9 @@ ShaderSourceType expectedType _ = GetScalarTypes(); ShaderSourceType declared = type.CreateType(); if (!declared.IsEquivalentTo(expectedType)) + { throw new InvalidOperationException("The input default type changed; reset or repair it explicitly."); + } int offset = 0; return Build(declared); @@ -103,11 +96,33 @@ ShaderIrValue Build(ShaderSourceType current) ShaderSourceType[] members = Members(current); var values = new ShaderIrValue[members.Length]; for (int i = 0; i < values.Length; i++) + { values[i] = Build(members[i]); + } return builder.Construct(current, values); } } + /// + /// Creates an explicit zero value for a supported scalar, vector, matrix, structure or array. + /// + /// + /// Complete numeric or boolean value type; resources and effect tokens are not values. + /// + /// + /// A detached zero literal with an exact type and component count. + /// + /// + /// The type is opaque or exceeds the bounded literal size. + /// + public static ShaderGraphLiteral Zero(ShaderSourceType type) + { + ArgumentNullException.ThrowIfNull(type); + List scalars = []; + Flatten(type, scalars, 0); + return new() { type = ShaderGraphType.Capture(type), scalarBits = new uint[scalars.Count] }; + } + private static bool IsScalar(string id) => id is "float" or "int" or "uint" or "bool"; private static void Flatten( @@ -116,41 +131,66 @@ private static void Flatten( int depth ) { if (depth > 32 || scalars.Count >= 4096) + { throw new NotSupportedException("An input literal exceeds the bounded aggregate size."); + } if (IsScalar(type.id) && type.fields.Count == 0 && type.elementType is null && type.storage is null) + { scalars.Add(type.id); + } else + { foreach (ShaderSourceType member in Members(type)) + { Flatten(member, scalars, depth + 1); + } + } } private static ShaderSourceType[] Members(ShaderSourceType type) { if (type.storage is not null) + { throw new NotSupportedException("Resource inputs require explicit bindings, not literal defaults."); + } if (type.elementType is not null) { if (type.elementCount > 4096) + { throw new NotSupportedException("An input literal array is too large."); + } var elements = new ShaderSourceType[type.elementCount]; - Array.Fill(elements, type.elementType); return elements; + Array.Fill(elements, type.elementType); + return elements; } if (type.fields.Count != 0) { var fields = new ShaderSourceType[type.fields.Count]; for (int i = 0; i < fields.Length; i++) + { fields[i] = type.fields[i].type; + } return fields; } foreach (string scalar in new[] { "float", "int", "uint", "bool" }) { - string shape = type.id.StartsWith(scalar, StringComparison.Ordinal) ? type.id[scalar.Length..] : ""; - int count = shape.Length == 1 && shape[0] is >= '2' and <= '4' ? shape[0] - '0' - : scalar == "float" && shape.Length == 3 && shape[0] is >= '2' and <= '4' && shape[1] == 'x' && shape[2] is >= '2' and <= '4' - ? (shape[0] - '0') * (shape[2] - '0') : 0; + string shape = type.id.StartsWith(scalar, StringComparison.Ordinal) ? type.id[scalar.Length..] : string.Empty; + int count = shape.Length == 1 && shape[0] is >= '2' and <= '4' + ? shape[0] - '0' + : scalar == "float" + && shape.Length == 3 + && shape[0] is >= '2' and <= '4' + && shape[1] == 'x' + && shape[2] is >= '2' and <= '4' + ? (shape[0] - '0') * (shape[2] - '0') + : 0; if (count == 0) + { continue; - var result = new ShaderSourceType[count]; Array.Fill(result, ShaderSourceType.Atomic(scalar)); return result; + } + var result = new ShaderSourceType[count]; + Array.Fill(result, ShaderSourceType.Atomic(scalar)); + return result; } throw new NotSupportedException($"Input type '{type.id}' has no literal representation."); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs new file mode 100644 index 000000000..5f3a24237 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs @@ -0,0 +1,36 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphLiteralConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphLiteral value + ) { + writer.Write("type", value.type); + writer.Write("scalarBits", value.scalarBits); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph literal that represents the completed operation. + /// + public override ShaderGraphLiteral Read(SerializationReader reader) + => new() { type = reader.Read("type"), scalarBits = reader.Read("scalarBits") }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs new file mode 100644 index 000000000..de1402364 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores values supplied by callers to a graph-authored node. +/// +public sealed class ShaderGraphNodeInputSettings : ISerializable +{ + /// + /// Gets or sets values supplied by callers and exposed as outputs inside the node graph. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs new file mode 100644 index 000000000..b9cc2433e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs @@ -0,0 +1,36 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeInputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeInputSettings value + ) => writer.Write("ports", value.ports); + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node input settings that represents the completed operation. + /// + public override ShaderGraphNodeInputSettings Read(SerializationReader reader) + => new() + { + ports = reader.Read("ports") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs new file mode 100644 index 000000000..c68992d21 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes the multi-port external inputs while editing a graph-authored node asset. +/// +public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_INPUT_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeInputSettings()).ports + .Select(static value => value.ToPort(GraphPortDirection.Output)) + .ToArray(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("Node Inputs exist only inside a graph-authored node definition."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs new file mode 100644 index 000000000..d74120a05 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes the complete public interface resolved from one graph-authored node asset. +/// +public sealed class ShaderGraphNodeInterface : ISerializable +{ + /// + /// Gets or sets the node title displayed to authors. + /// + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; + + /// + /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. + /// + [SerializableProperty] + public string createPath { get; set; } = "General"; + + /// + /// Gets or sets the deterministic order within the creation catalog. + /// + [SerializableProperty] + public int createOrder { get; set; } + + /// + /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. + /// + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } + + /// + /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. + /// + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } + + /// + /// Gets or sets the Target-owned role for a domain output. + /// + [SerializableProperty] + public string role { get; set; } = string.Empty; + + /// + /// Gets or sets externally supplied inputs. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; + + /// + /// Gets or sets externally visible results. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; + + /// + /// Gets detached typed ports in deterministic input-then-output order. + /// + /// + /// A provider-free port snapshot suitable for Editor presentation and validation. + /// + public IReadOnlyList GetPorts() + => inputs.Select(static value => value.ToPort(GraphPortDirection.Input)) + .Concat(outputs.Select(static value => value.ToPort(GraphPortDirection.Output))) + .ToArray(); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs new file mode 100644 index 000000000..df4cc4f8d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs @@ -0,0 +1,52 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeInterfaceConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeInterface value + ) { + writer.Write("displayName", value.displayName); + writer.Write("createPath", value.createPath); + writer.Write("createOrder", value.createOrder); + writer.Write("kind", value.kind); + writer.Write("effect", value.effect); + writer.Write("role", value.role); + writer.Write("inputs", value.inputs); + writer.Write("outputs", value.outputs); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node interface that represents the completed operation. + /// + public override ShaderGraphNodeInterface Read(SerializationReader reader) + => new() + { + displayName = reader.Read("displayName"), + createPath = reader.Read("createPath"), + createOrder = reader.Read("createOrder"), + kind = reader.Read("kind"), + effect = reader.Read("effect"), + role = reader.Read("role"), + inputs = reader.Read("inputs"), + outputs = reader.Read("outputs") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs new file mode 100644 index 000000000..0f3f46129 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores values returned by a graph-authored function node. +/// +public sealed class ShaderGraphNodeOutputSettings : ISerializable +{ + /// + /// Gets or sets values collected inside the node graph and exposed as outputs to callers. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs new file mode 100644 index 000000000..d38439f0e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs @@ -0,0 +1,33 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeOutputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeOutputSettings value + ) => writer.Write("ports", value.ports); + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node output settings that represents the completed operation. + /// + public override ShaderGraphNodeOutputSettings Read(SerializationReader reader) + => new() { ports = reader.Read("ports") }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs new file mode 100644 index 000000000..9b83e15d9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes the multi-port returned values while editing a graph-authored function node asset. +/// +public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_OUTPUT_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeOutputSettings()).ports + .Select(static value => value.ToPort(GraphPortDirection.Input)) + .ToArray(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("Node Outputs exist only inside a graph-authored node definition."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs new file mode 100644 index 000000000..b0424044c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs @@ -0,0 +1,31 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares one stable, typed port on a graph-authored node interface. +/// +public sealed class ShaderGraphNodePortDefinition : ISerializable +{ + /// + /// Gets or sets the stable node-local port identity. + /// + [SerializableProperty] + public string id { get; set; } = "value"; + + /// + /// Gets or sets the complete backend-neutral value type. + /// + [SerializableProperty] + public ShaderGraphType type { get; set; } = new() { id = "float" }; + + /// + /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. + /// + [SerializableProperty] + public bool required { get; set; } = true; + + internal ShaderNodePort ToPort(GraphPortDirection direction) + => new(id, type.CreateType(), direction, direction == GraphPortDirection.Input && required); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs new file mode 100644 index 000000000..3f095cbe8 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs @@ -0,0 +1,42 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodePortDefinitionConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodePortDefinition value + ) { + writer.Write("id", value.id); + writer.Write("type", value.type); + writer.Write("required", value.required); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node port definition that represents the completed operation. + /// + public override ShaderGraphNodePortDefinition Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + type = reader.Read("type"), + required = reader.Read("required") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs new file mode 100644 index 000000000..aba37b9f2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs @@ -0,0 +1,45 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores graph-level identity and catalog metadata for a reusable Shader node. +/// +public sealed class ShaderGraphNodeSettings : ISerializable +{ + /// + /// Gets or sets the node title displayed to authors. + /// + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; + + /// + /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. + /// + [SerializableProperty] + public string createPath { get; set; } = "General"; + + /// + /// Gets or sets the deterministic order within the creation catalog. + /// + [SerializableProperty] + public int createOrder { get; set; } + + /// + /// Gets or sets how a reference to this graph participates in compilation. + /// + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } + + /// + /// Gets or sets the observable computation behavior of an inline function. + /// + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } + + /// + /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. + /// + [SerializableProperty] + public string role { get; set; } = string.Empty; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs new file mode 100644 index 000000000..ce984435e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs @@ -0,0 +1,48 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeSettings value + ) { + writer.Write("displayName", value.displayName); + writer.Write("createPath", value.createPath); + writer.Write("createOrder", value.createOrder); + writer.Write("kind", value.kind); + writer.Write("effect", value.effect); + writer.Write("role", value.role); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node settings that represents the completed operation. + /// + public override ShaderGraphNodeSettings Read(SerializationReader reader) + => new() + { + displayName = reader.Read("displayName"), + createPath = reader.Read("createPath"), + createOrder = reader.Read("createOrder"), + kind = reader.Read("kind"), + effect = reader.Read("effect"), + role = reader.Read("role") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs index eb49744e0..70892d88c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs @@ -7,161 +7,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Chooses whether a graph-authored node is inlined or consumed by a domain Target. -/// -public enum ShaderGraphNodeKind -{ - /// - /// Inlines the node graph into the caller before Target expansion and typed lowering. - /// - Function, - /// - /// Leaves the node as a typed domain boundary for the selected Shader Target. - /// - DomainOutput -} - -/// -/// Declares whether a graph-authored function is pure or intentionally emits ordered effects. -/// -public enum ShaderGraphNodeEffect -{ - /// - /// The function only computes returned values and therefore requires at least one output. - /// - Pure, - /// - /// The function may contain ordered GPU effects and can intentionally expose no returned values. - /// - SideEffect -} - -/// -/// Stores graph-level identity and catalog metadata for a reusable Shader node. -/// -public sealed class ShaderGraphNodeSettings : ISerializable -{ - /// - /// Gets or sets the node title displayed to authors. - /// - [SerializableProperty] public string displayName { get; set; } = "Graph Node"; - /// - /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. - /// - [SerializableProperty] public string createPath { get; set; } = "General"; - /// - /// Gets or sets the deterministic order within the creation catalog. - /// - [SerializableProperty] public int createOrder { get; set; } - /// - /// Gets or sets how a reference to this graph participates in compilation. - /// - [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } - /// - /// Gets or sets the observable computation behavior of an inline function. - /// - [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } - /// - /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. - /// - [SerializableProperty] public string role { get; set; } = ""; -} - -/// -/// Declares one stable, typed port on a graph-authored node interface. -/// -public sealed class ShaderGraphNodePortDefinition : ISerializable -{ - /// - /// Gets or sets the stable node-local port identity. - /// - [SerializableProperty] public string id { get; set; } = "value"; - /// - /// Gets or sets the complete backend-neutral value type. - /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; - /// - /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. - /// - [SerializableProperty] public bool required { get; set; } = true; - - internal ShaderNodePort ToPort(GraphPortDirection direction) - => new(id, type.CreateType(), direction, direction == GraphPortDirection.Input && required); -} - -/// -/// Stores values supplied by callers to a graph-authored node. -/// -public sealed class ShaderGraphNodeInputSettings : ISerializable -{ - /// - /// Gets or sets values supplied by callers and exposed as outputs inside the node graph. - /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] ports { get; set; } = []; -} - -/// -/// Stores values returned by a graph-authored function node. -/// -public sealed class ShaderGraphNodeOutputSettings : ISerializable -{ - /// - /// Gets or sets values collected inside the node graph and exposed as outputs to callers. - /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] ports { get; set; } = []; -} - -/// -/// Freezes the complete public interface resolved from one graph-authored node asset. -/// -public sealed class ShaderGraphNodeInterface : ISerializable -{ - /// - /// Gets or sets the node title displayed to authors. - /// - [SerializableProperty] public string displayName { get; set; } = "Graph Node"; - /// - /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. - /// - [SerializableProperty] public string createPath { get; set; } = "General"; - /// - /// Gets or sets the deterministic order within the creation catalog. - /// - [SerializableProperty] public int createOrder { get; set; } - /// - /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. - /// - [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } - /// - /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. - /// - [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } - /// - /// Gets or sets the Target-owned role for a domain output. - /// - [SerializableProperty] public string role { get; set; } = ""; - /// - /// Gets or sets externally supplied inputs. - /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; - /// - /// Gets or sets externally visible results. - /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; - - /// - /// Gets detached typed ports in deterministic input-then-output order. - /// - /// - /// A provider-free port snapshot suitable for Editor presentation and validation. - /// - public IReadOnlyList GetPorts() - => inputs.Select(static value => value.ToPort(GraphPortDirection.Input)) - .Concat(outputs.Select(static value => value.ToPort(GraphPortDirection.Output))) - .ToArray(); -} - /// /// Reads and expands reusable node graphs without retaining assets or provider instances. /// @@ -170,23 +15,27 @@ public static class ShaderGraphNodes /// /// Identifies the single multi-port node-input interface record. /// - public const string inputDefinitionId = "inno.shader.node-inputs"; + public const string C_INPUT_DEFINITION_ID = "inno.shader.node-inputs"; + /// /// Identifies the optional multi-port node-output interface record. /// - public const string outputDefinitionId = "inno.shader.node-outputs"; + public const string C_OUTPUT_DEFINITION_ID = "inno.shader.node-outputs"; + /// /// Identifies a reference to another Shader graph used as a node. /// - public const string callDefinitionId = "inno.shader.graph-node"; + public const string C_CALL_DEFINITION_ID = "inno.shader.graph-node"; + /// /// Identifies the serialized interface snapshot retained by a graph-node reference. /// - public const string interfaceKey = "interface"; + public const string C_INTERFACE_KEY = "interface"; + /// /// Identifies graph-level reusable-node metadata, independent of either interface direction. /// - public const string settingsKey = "inno.shader.node-settings"; + public const string C_SETTINGS_KEY = "inno.shader.node-settings"; /// /// Determines whether a Shader graph declares a reusable node interface. @@ -200,7 +49,7 @@ public static class ShaderGraphNodes public static bool IsNodeGraph(GraphDocument graph) { ArgumentNullException.ThrowIfNull(graph); - return graph.metadata.ContainsKey(settingsKey); + return graph.metadata.ContainsKey(C_SETTINGS_KEY); } /// @@ -226,7 +75,7 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); ArgumentNullException.ThrowIfNull(settings); - graph.SetMetadata(settingsKey, ShaderGraphDocument.Encode(settings, serialization, context)); + graph.SetMetadata(C_SETTINGS_KEY, ShaderGraphDocument.Encode(settings, serialization, context)); } /// @@ -250,8 +99,10 @@ public static ShaderGraphNodeSettings ReadSettings( SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); - if (!graph.metadata.TryGetValue(settingsKey, out GraphSerializedValue? value)) + if (!graph.metadata.TryGetValue(C_SETTINGS_KEY, out GraphSerializedValue? value)) + { throw new InvalidOperationException("The Shader graph does not declare reusable-node settings."); + } return ShaderGraphDocument.Decode(value, serialization, context); } @@ -277,26 +128,46 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); if (ShaderGraphDocument.ReadTarget(graph, serialization, context).Length != 0) + { throw new InvalidOperationException("A graph-authored node cannot select a Shader Target."); - if (graph.nodes.Any(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)) + } + if (graph.nodes.Any(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID)) + { throw new InvalidOperationException("A graph-authored node cannot contain explicit GPU stage outputs."); - GraphNodeRecord[] inputs = graph.nodes.Where(static node => node.definitionId == inputDefinitionId).ToArray(); - GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionId == outputDefinitionId).ToArray(); + } + GraphNodeRecord[] inputs = graph.nodes.Where(static node => node.definitionID == C_INPUT_DEFINITION_ID).ToArray(); + GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionID == C_OUTPUT_DEFINITION_ID).ToArray(); if (inputs.Length > 1) + { throw new InvalidOperationException("A graph-authored node can contain at most one Function Inputs record."); + } if (outputs.Length > 1) + { throw new InvalidOperationException("A graph-authored node can contain at most one Function Outputs record."); + } if (inputs.Length == 0 && outputs.Length == 0) + { throw new InvalidOperationException("A graph-authored node requires Function Inputs, Function Outputs, or both."); + } ShaderGraphNodeSettings settings = ReadSettings(graph, serialization, context); ShaderGraphNodeInputSettings input = inputs.Length == 0 - ? new() - : ShaderGraphDocument.Read(inputs[0], ShaderGraphDocument.settingsKey, - new ShaderGraphNodeInputSettings(), serialization, context); + ? new ShaderGraphNodeInputSettings() + : ShaderGraphDocument.Read( + inputs[0], + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphNodeInputSettings(), + serialization, + context + ); ShaderGraphNodeOutputSettings output = outputs.Length == 0 - ? new() - : ShaderGraphDocument.Read(outputs[0], ShaderGraphDocument.settingsKey, - new ShaderGraphNodeOutputSettings(), serialization, context); + ? new ShaderGraphNodeOutputSettings() + : ShaderGraphDocument.Read( + outputs[0], + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphNodeOutputSettings(), + serialization, + context + ); var result = new ShaderGraphNodeInterface { displayName = settings.displayName, @@ -333,7 +204,12 @@ public static ShaderGraphNodeInterface ReadCallInterface( SerializationContext context ) { ShaderGraphNodeInterface result = ShaderGraphDocument.Read( - node, interfaceKey, new ShaderGraphNodeInterface(), serialization, context); + node, + C_INTERFACE_KEY, + new ShaderGraphNodeInterface(), + serialization, + context + ); Validate(result, result.inputs.Length == 0 ? 0 : 1, result.outputs.Length == 0 ? 0 : 1); return result; } @@ -376,27 +252,33 @@ private static void Expand( SerializationContext context, HashSet stack ) { - var retainedDomainOutputs = new HashSet(); - while (graph.nodes.FirstOrDefault(node => node.definitionId == callDefinitionId - && !retainedDomainOutputs.Contains(node.id)) is { } call) - { - Guid sourceId = ShaderGraphDocument.Read(call, "sourceId", Guid.Empty, serialization, context); - string sourcePath = ShaderGraphDocument.Read(call, "sourcePath", "", serialization, context); - if (sourceId == Guid.Empty) + var retainedDomainOutputs = new HashSet(); + while (graph.nodes.FirstOrDefault(node => ( + node.definitionID == C_CALL_DEFINITION_ID + && !retainedDomainOutputs.Contains(node.id) + )) is { } call + ) { + Guid sourceID = ShaderGraphDocument.Read(call, "sourceId", Guid.Empty, serialization, context); + string sourcePath = ShaderGraphDocument.Read(call, "sourcePath", string.Empty, serialization, context); + if (sourceID == Guid.Empty) + { throw new InvalidOperationException("A graph-node reference has no Shader asset identity."); - if (!stack.Add(sourceId)) + } + if (!stack.Add(sourceID)) + { throw new InvalidOperationException($"Graph-node references contain a cycle at '{sourcePath}'."); - GraphDocument child = resolve(sourceId, sourcePath).Clone(); + } + GraphDocument child = resolve(sourceID, sourcePath).Clone(); ShaderGraphNodeInterface nodeInterface = ReadInterface(child, serialization, context); if (nodeInterface.kind == ShaderGraphNodeKind.DomainOutput) { - call.SetValue(interfaceKey, ShaderGraphDocument.Encode(nodeInterface, serialization, context)); + call.SetValue(C_INTERFACE_KEY, ShaderGraphDocument.Encode(nodeInterface, serialization, context)); retainedDomainOutputs.Add(call.id); - stack.Remove(sourceId); + stack.Remove(sourceID); continue; } Expand(child, resolve, serialization, context, stack); - stack.Remove(sourceId); + stack.Remove(sourceID); Inline(graph, call, child, nodeInterface, serialization, context); } } @@ -409,91 +291,139 @@ private static void Inline( SerializationRegistry serialization, SerializationContext context ) { - GraphNodeRecord? inputNode = child.nodes.SingleOrDefault(static node => node.definitionId == inputDefinitionId); - GraphNodeRecord? outputNode = child.nodes.SingleOrDefault(static node => node.definitionId == outputDefinitionId); - string stage = ShaderGraphDocument.Read(call, ShaderGraphDocument.stageKey, "", serialization, context); + GraphNodeRecord? inputNode = child.nodes.SingleOrDefault(static node => node.definitionID == C_INPUT_DEFINITION_ID); + GraphNodeRecord? outputNode = child.nodes.SingleOrDefault(static node => node.definitionID == C_OUTPUT_DEFINITION_ID); + string stage = ShaderGraphDocument.Read(call, ShaderGraphDocument.C_STAGE_KEY, string.Empty, serialization, context); MergeDefinition(parent, child, stage, serialization, context); - var map = new Dictionary(); + var map = new Dictionary(); foreach (GraphNodeRecord node in child.nodes.Where(node => node.id != inputNode?.id && node.id != outputNode?.id)) { - var mapped = new GraphNodeId(call.id.value + "/" + node.id.value); + var mapped = new GraphNodeID(call.id.value + "/" + node.id.value); if (parent.FindNode(mapped) is not null) - throw new InvalidOperationException($"Inlining '{nodeInterface.displayName}' produced duplicate node identity '{mapped.value}'."); - var copy = new GraphNodeRecord(mapped, node.definitionId) { position = new(call.position.x + node.position.x, call.position.y + node.position.y) }; + { + throw new InvalidOperationException( + $"Inlining '{nodeInterface.displayName}' produced duplicate node identity '{mapped.value}'." + ); + } + var copy = new GraphNodeRecord(mapped, node.definitionID) + { + position = new(call.position.x + node.position.x, call.position.y + node.position.y) + }; foreach ((string key, GraphSerializedValue value) in node.values) + { copy.SetValue(key, value); + } if (stage.Length != 0) - copy.SetValue(ShaderGraphDocument.stageKey, ShaderGraphDocument.Encode(stage, serialization, context)); + { + copy.SetValue(ShaderGraphDocument.C_STAGE_KEY, ShaderGraphDocument.Encode(stage, serialization, context)); + } parent.AddNode(copy); map.Add(node.id, mapped); } - var incoming = parent.edges.Where(edge => edge.input.nodeId == call.id) - .GroupBy(static edge => edge.input.portId.value, StringComparer.Ordinal) + Dictionary incoming = parent.edges.Where(edge => edge.input.nodeID == call.id) + .GroupBy(static edge => edge.input.portID.value, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); - var outgoing = parent.edges.Where(edge => edge.output.nodeId == call.id) - .GroupBy(static edge => edge.output.portId.value, StringComparer.Ordinal) + Dictionary outgoing = parent.edges.Where(edge => edge.output.nodeID == call.id) + .GroupBy(static edge => edge.output.portID.value, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); - HashSet inputIds = nodeInterface.inputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); - HashSet outputIds = nodeInterface.outputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); - string? missingInput = incoming.Keys.FirstOrDefault(id => !inputIds.Contains(id)); + HashSet inputIDs = nodeInterface.inputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); + HashSet outputIDs = nodeInterface.outputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); + string? missingInput = incoming.Keys.FirstOrDefault(id => !inputIDs.Contains(id)); if (missingInput is not null) + { throw new InvalidOperationException( - $"Graph-node call '{nodeInterface.displayName}' retains unavailable input port '{missingInput}'."); - string? missingOutput = outgoing.Keys.FirstOrDefault(id => !outputIds.Contains(id)); + $"Graph-node call '{nodeInterface.displayName}' retains unavailable input port '{missingInput}'." + ); + } + string? missingOutput = outgoing.Keys.FirstOrDefault(id => !outputIDs.Contains(id)); if (missingOutput is not null) + { throw new InvalidOperationException( - $"Graph-node call '{nodeInterface.displayName}' retains unavailable output port '{missingOutput}'."); + $"Graph-node call '{nodeInterface.displayName}' retains unavailable output port '{missingOutput}'." + ); + } foreach (GraphEdgeRecord[] values in incoming.Values) + { if (values.Length != 1) + { throw new InvalidOperationException("A graph-node input has multiple incoming connections."); + } + } var resolvedInputs = new Dictionary(StringComparer.Ordinal); foreach (ShaderGraphNodePortDefinition port in nodeInterface.inputs) { if (incoming.TryGetValue(port.id, out GraphEdgeRecord[]? edges)) + { resolvedInputs.Add(port.id, edges[0].output); + } else if (!port.required) + { resolvedInputs.Add(port.id, AddOptionalZero(parent, call, port, stage, serialization, context)); + } else + { throw new InvalidOperationException( - $"Required graph-node input '{port.id}' is not connected on '{nodeInterface.displayName}'."); + $"Required graph-node input '{port.id}' is not connected on '{nodeInterface.displayName}'." + ); + } } var resolvedOutputs = new Dictionary(StringComparer.Ordinal); foreach (GraphEdgeRecord edge in child.edges) { - bool fromInput = inputNode is not null && edge.output.nodeId == inputNode.id; - bool toOutput = outputNode is not null && edge.input.nodeId == outputNode.id; + bool fromInput = inputNode is not null && edge.output.nodeID == inputNode.id; + bool toOutput = outputNode is not null && edge.input.nodeID == outputNode.id; GraphEndpoint mappedSource; if (fromInput) { - if (!resolvedInputs.TryGetValue(edge.output.portId.value, out GraphEndpoint source)) + if (!resolvedInputs.TryGetValue(edge.output.portID.value, out GraphEndpoint source)) + { continue; + } mappedSource = source; } else { - if (!map.TryGetValue(edge.output.nodeId, out GraphNodeId sourceNode)) + if (!map.TryGetValue(edge.output.nodeID, out GraphNodeID sourceNode)) + { continue; - mappedSource = new(sourceNode, edge.output.portId); + } + mappedSource = new(sourceNode, edge.output.portID); } if (toOutput) { - if (!resolvedOutputs.TryAdd(edge.input.portId.value, mappedSource)) - throw new InvalidOperationException($"Graph-node output '{edge.input.portId.value}' is connected more than once."); + if (!resolvedOutputs.TryAdd(edge.input.portID.value, mappedSource)) + { + throw new InvalidOperationException($"Graph-node output '{edge.input.portID.value}' is connected more than once."); + } + } + else if (map.TryGetValue(edge.input.nodeID, out GraphNodeID targetNode)) + { + parent.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(call.id.value + "/" + edge.id.value), + mappedSource, + new GraphEndpoint(targetNode, edge.input.portID) + ) + ); } - else if (map.TryGetValue(edge.input.nodeId, out GraphNodeId targetNode)) - parent.AddEdge(new(new(call.id.value + "/" + edge.id.value), mappedSource, new(targetNode, edge.input.portId))); } foreach (ShaderGraphNodePortDefinition port in nodeInterface.outputs) { if (!resolvedOutputs.TryGetValue(port.id, out GraphEndpoint source)) + { throw new InvalidOperationException($"Graph-node output '{port.id}' has no value inside '{nodeInterface.displayName}'."); + } if (!outgoing.TryGetValue(port.id, out GraphEdgeRecord[]? edges)) + { continue; + } foreach (GraphEdgeRecord edge in edges) - parent.AddEdge(new(new(call.id.value + "/return/" + edge.id.value), source, edge.input)); + { + parent.AddEdge(new GraphEdgeRecord(new GraphEdgeID(call.id.value + "/return/" + edge.id.value), source, edge.input)); + } } parent.RemoveNode(call.id); } @@ -501,22 +431,32 @@ SerializationContext context private static void MergeDefinition( GraphDocument parent, GraphDocument child, - string stageId, + string stageID, SerializationRegistry serialization, SerializationContext context ) { ShaderDefinition parentDefinition = ShaderGraphDocument.ReadDefinition(parent, serialization, context); ShaderDefinition childDefinition = ShaderGraphDocument.ReadDefinition(child, serialization, context); ShaderStage callerStage = ShaderStage.None; - if (stageId.Length != 0 && parent.FindNode(new(stageId)) is { definitionId: ShaderGraphDocument.outputDefinitionId } stageNode) - callerStage = ShaderGraphDocument.Read(stageNode, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).stage; - var properties = parentDefinition.properties.ToList(); + if (stageID.Length != 0 + && parent.FindNode(new GraphNodeID(stageID)) is { definitionID: ShaderGraphDocument.C_OUTPUT_DEFINITION_ID } stageNode + ) { + callerStage = ShaderGraphDocument.Read( + stageNode, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphStageSettings(), + serialization, + context + ).stage; + } + List properties = parentDefinition.properties.ToList(); foreach (ShaderPropertyDefinition childPropertyValue in childDefinition.properties) { ShaderPropertyDefinition childProperty = childPropertyValue; if (callerStage != ShaderStage.None) + { childProperty.stages |= callerStage; + } int index = properties.FindIndex(value => value.id.value == childProperty.id.value); if (index < 0) { @@ -525,14 +465,18 @@ SerializationContext context } ShaderPropertyDefinition existing = properties[index]; if (existing.type != childProperty.type || existing.bindingKind != childProperty.bindingKind - || existing.storageAccess != childProperty.storageAccess || existing.bindingOwner != childProperty.bindingOwner) + || existing.storageAccess != childProperty.storageAccess || existing.bindingOwner != childProperty.bindingOwner + ) { throw new InvalidOperationException($"Graph node property '{childProperty.id.value}' conflicts with its caller."); + } existing.stages |= childProperty.stages; properties[index] = existing; } parentDefinition.properties = properties.ToArray(); - parent.SetMetadata(ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(serialization.Serialize(parentDefinition, context), serialization, context)); + parent.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(serialization.Serialize(parentDefinition, context), serialization, context) + ); } private static GraphEndpoint AddOptionalZero( @@ -544,13 +488,15 @@ private static GraphEndpoint AddOptionalZero( SerializationContext context ) { _ = ShaderGraphLiteral.Zero(port.type.CreateType()); - var id = new GraphNodeId(call.id.value + "/default/" + port.id); + var id = new GraphNodeID(call.id.value + "/default/" + port.id); var node = new GraphNodeRecord(id, "inno.shader.reroute") { position = call.position }; node.SetValue("valueType", ShaderGraphDocument.Encode(port.type, serialization, context)); if (stage.Length != 0) - node.SetValue(ShaderGraphDocument.stageKey, ShaderGraphDocument.Encode(stage, serialization, context)); + { + node.SetValue(ShaderGraphDocument.C_STAGE_KEY, ShaderGraphDocument.Encode(stage, serialization, context)); + } graph.AddNode(node); - return new(id, new("value")); + return new(id, new GraphPortID("value")); } private static void Validate( @@ -559,21 +505,39 @@ private static void Validate( int outputRecords ) { if (string.IsNullOrWhiteSpace(value.displayName)) + { throw new InvalidOperationException("A graph-authored node requires a display name."); + } if (!Enum.IsDefined(value.kind)) + { throw new InvalidOperationException("The graph-authored node kind is invalid."); + } if (!Enum.IsDefined(value.effect)) + { throw new InvalidOperationException("The graph-authored node effect is invalid."); + } if (inputRecords is < 0 or > 1 || outputRecords is < 0 or > 1 || inputRecords + outputRecords == 0) - throw new InvalidOperationException("A graph-authored node requires at most one interface record per direction and at least one direction."); + { + throw new InvalidOperationException( + "A graph-authored node requires at most one interface record per direction and at least one direction." + ); + } if (value.inputs.Length + value.outputs.Length == 0) + { throw new InvalidOperationException("A graph-authored node requires at least one public input or output port."); + } if (value.kind == ShaderGraphNodeKind.Function && value.effect == ShaderGraphNodeEffect.Pure && outputRecords == 0) + { throw new InvalidOperationException("A pure graph-authored function requires at least one Function Output."); + } if (value.kind == ShaderGraphNodeKind.DomainOutput && outputRecords != 0) + { throw new InvalidOperationException("A domain output graph node cannot declare returned values."); + } if (value.kind == ShaderGraphNodeKind.DomainOutput && string.IsNullOrWhiteSpace(value.role)) + { throw new InvalidOperationException("A domain output graph node requires a stable Target role."); + } ValidatePorts(value.inputs, "input"); ValidatePorts(value.outputs, "output"); } @@ -583,115 +547,50 @@ private static void ValidatePorts( string direction ) { if (ports is null) + { throw new InvalidOperationException($"The graph-node {direction} port list is missing."); + } var ids = new HashSet(StringComparer.Ordinal); foreach (ShaderGraphNodePortDefinition port in ports) { if (port is null || string.IsNullOrWhiteSpace(port.id) || port.type is null || port.type.CreateType().id == "void") + { throw new InvalidOperationException($"A graph-node {direction} port is invalid."); + } if (!ids.Add(port.id)) + { throw new InvalidOperationException($"A graph-node {direction} port repeats '{port.id}'."); + } } } } /// -/// Describes graph-authored node references before they are expanded or consumed by a Target. -/// -public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => ShaderGraphNodes.callDefinitionId; - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()).GetPorts(); - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("A graph-authored node must be expanded or consumed by its Shader Target before lowering."); -} - -/// -/// Describes the multi-port external inputs while editing a graph-authored node asset. +/// Chooses whether a graph-authored node is inlined or consumed by a domain Target. /// -public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler +public enum ShaderGraphNodeKind { /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => ShaderGraphNodes.inputDefinitionId; - /// - /// Gets a ports required by the implemented contract. + /// Inlines the node graph into the caller before Target expansion and typed lowering. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphDocument.settingsKey, new ShaderGraphNodeInputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Output)).ToArray(); + Function, /// - /// Lowers this graph node to typed shader IR after validating its inputs. + /// Leaves the node as a typed domain boundary for the selected Shader Target. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("Node Inputs exist only inside a graph-authored node definition."); + DomainOutput } /// -/// Describes the multi-port returned values while editing a graph-authored function node asset. +/// Declares whether a graph-authored function is pure or intentionally emits ordered effects. /// -public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler +public enum ShaderGraphNodeEffect { /// - /// Gets the definition id text used by the current instance. - /// - public string definitionId => ShaderGraphNodes.outputDefinitionId; - /// - /// Gets a ports required by the implemented contract. + /// The function only computes returned values and therefore requires at least one output. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphDocument.settingsKey, new ShaderGraphNodeOutputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Input)).ToArray(); + Pure, /// - /// Lowers this graph node to typed shader IR after validating its inputs. + /// The function may contain ordered GPU effects and can intentionally expose no returned values. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("Node Outputs exist only inside a graph-authored node definition."); + SideEffect } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs new file mode 100644 index 000000000..f29715989 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs @@ -0,0 +1,27 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Stores one stable output port's destination, independent of adapter source syntax. +/// +public struct ShaderGraphOutput +{ + /// + /// Gets or sets the stable input port identity on the stage output node. + /// + public string id { get; set; } + + /// + /// Gets or sets the GPU destination category. + /// + public ShaderIrOutputKind kind { get; set; } + + /// + /// Gets or sets the varying semantic; empty for fixed position, color or depth outputs. + /// + public string semantic { get; set; } + + /// + /// Gets or sets the varying or attachment index. + /// + public int location { get; set; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs new file mode 100644 index 000000000..726068292 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes the graph-lowered stages of one material-selectable GPU pass. +/// +public sealed class ShaderGraphPass +{ + /// + /// Captures a pass's ordered typed stages. + /// + /// + /// Exact pass identity in the program contract. + /// + /// + /// Complete raster or compute stage set. + /// + public ShaderGraphPass( + string name, + IEnumerable stages + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(stages); + this.name = name; + this.stages = Array.AsReadOnly(stages.ToArray()); + } + + /// + /// Gets the stable pass identity. + /// + public string name { get; } + + /// + /// Gets immutable graph-lowered stages. + /// + public IReadOnlyList stages { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs new file mode 100644 index 000000000..31300e676 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs @@ -0,0 +1,17 @@ +namespace Inno.Rendering.Shaders; + +/// +/// References shared stage output identities from a material-selectable pass. +/// +public struct ShaderGraphPassProgram +{ + /// + /// Gets or sets the exact pass identity in the runtime shader definition. + /// + public string pass { get; set; } + + /// + /// Gets or sets stable stage output node identities; computation remains owned by those nodes. + /// + public string[] stages { get; set; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs new file mode 100644 index 000000000..5d6ff47ec --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Contains a detached paste candidate and its newly allocated node identities. +/// +public sealed class ShaderGraphPasteResult +{ + internal ShaderGraphPasteResult( + GraphDocument graph, + GraphNodeID[] nodes + ) { + this.document = graph; + this.insertedNodes = Array.AsReadOnly(nodes); + } + + /// + /// Gets the complete detached candidate; the caller owns its subsequent edits. + /// + public GraphDocument document { get; } + + /// + /// Gets new identities suitable for selecting the pasted nodes. + /// + public IReadOnlyList insertedNodes { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs index a4f4c9999..9b83f86c2 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs @@ -26,7 +26,10 @@ public sealed class ShaderGraphProgramCompiler /// The owner-scoped node registry. /// public ShaderGraphProgramCompiler(ShaderNodeCompilerRegistry nodes) - => m_nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); + { + ArgumentNullException.ThrowIfNull(nodes); + m_nodes = nodes; + } /// /// Validates the complete pass/stage graph without deleting invalid or unavailable records. @@ -34,7 +37,7 @@ public ShaderGraphProgramCompiler(ShaderNodeCompilerRegistry nodes) /// /// Authored graph, copied before validation. /// - /// + /// /// Exact adapter implementation identity selected by the caller. /// /// @@ -54,95 +57,170 @@ public ShaderGraphProgramCompiler(ShaderNodeCompilerRegistry nodes) /// public ShaderGraphProgramResult Lower( GraphDocument document, - string implementationId, - IReadOnlyDictionary sources, + string implementationID, + IReadOnlyDictionary sources, SerializationRegistry serialization, SerializationContext context, CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(sources); - var diagnostics = new List(); - var passes = new List(); - GraphNodeId? activeNode = null; + List diagnostics = []; + List passes = []; + GraphNodeID? activeNode = null; try { GraphDocument graph = document.Clone(); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); - diagnostics.AddRange(ShaderDefinitionValidator.Validate(definition).Select(static value => - new ShaderGraphDiagnostic(value.code, value.severity, value.message))); + diagnostics.AddRange( + ShaderDefinitionValidator.Validate(definition).Select(static value => + new ShaderGraphDiagnostic(value.code, value.severity, value.message)) + ); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new([], diagnostics); - ConnectRasterStages(graph, implementationId, sources, serialization, context); - var definitions = definition.passes.ToDictionary(static pass => pass.name, StringComparer.Ordinal); + } + ConnectRasterStages(graph, implementationID, sources, serialization, context); + Dictionary definitions = definition.passes.ToDictionary( + static pass => pass.name, + StringComparer.Ordinal + ); if (definitions.Count == 0) + { throw new InvalidOperationException("A shader graph requires at least one pass."); + } ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, serialization, context); if (programs.Select(static value => value.pass).Distinct(StringComparer.Ordinal).Count() != programs.Length - || programs.Any(value => !definitions.ContainsKey(value.pass))) + || programs.Any(value => !definitions.ContainsKey(value.pass)) + ) { throw new InvalidOperationException("Program references must name unique declared passes."); + } var stages = new Dictionary(StringComparer.Ordinal); - var outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).ToArray(); - var owners = graph.nodes.Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId) - .ToDictionary(static node => node.id, node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context)); - var outputIds = outputs.Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); - foreach ((GraphNodeId node, string owner) in owners) - if (!outputIds.Contains(owner)) + GraphNodeRecord[] outputs = graph.nodes + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .ToArray(); + Dictionary owners = graph.nodes + .Where(static node => node.definitionID != ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .ToDictionary( + static node => node.id, + node => ShaderGraphDocument.Read(node, ShaderGraphDocument.C_STAGE_KEY, string.Empty, serialization, context) + ); + HashSet outputIDs = outputs.Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + foreach ((GraphNodeID node, string owner) in owners) + { + if (!outputIDs.Contains(owner)) + { Error("SHADER_STAGE_MISSING", "The node's stage is missing; its data remains available for repair.", node); + } + } if (diagnostics.Count != 0) + { return new([], diagnostics); + } foreach (GraphNodeRecord output in outputs) { cancellationToken.ThrowIfCancellationRequested(); activeNode = output.id; - ShaderGraphStageSettings settings = ShaderGraphDocument.Read(output, - ShaderGraphDocument.settingsKey, null, serialization, context) + ShaderGraphStageSettings settings = ShaderGraphDocument.Read( + output, + ShaderGraphDocument.C_SETTINGS_KEY, + null, + serialization, + context + ) ?? throw new InvalidOperationException("A stage output node requires its stage settings."); - var region = graph.Clone(); + GraphDocument region = graph.Clone(); foreach (GraphNodeRecord node in graph.nodes) + { if (!owners.TryGetValue(node.id, out string? owner) || owner != output.id.value) + { region.RemoveNode(node.id); - HashSet members = region.nodes.Select(static node => node.id).ToHashSet(); + } + } + HashSet members = region.nodes.Select(static node => node.id).ToHashSet(); var endpoints = new Dictionary(StringComparer.Ordinal); foreach (GraphEdgeRecord edge in graph.edges) { - if (edge.input.nodeId == output.id) + if (edge.input.nodeID == output.id) { - if (!members.Contains(edge.output.nodeId)) - throw new InvalidOperationException("A stage output is connected to another stage; use an explicit varying interface."); - if (!endpoints.TryAdd(edge.input.portId.value, edge.output)) + if (!members.Contains(edge.output.nodeID)) + { + throw new InvalidOperationException( + "A stage output is connected to another stage; use an explicit varying interface." + ); + } + if (!endpoints.TryAdd(edge.input.portID.value, edge.output)) + { throw new InvalidOperationException("A stage output port has multiple incoming connections."); + } } - else if (members.Contains(edge.input.nodeId) != members.Contains(edge.output.nodeId) - && edge.output.nodeId != output.id && edge.input.nodeId != output.id) + else if (members.Contains(edge.input.nodeID) != members.Contains(edge.output.nodeID) + && edge.output.nodeID != output.id && edge.input.nodeID != output.id + ) { throw new InvalidOperationException("A connection crosses incompatible stage boundaries."); - if (edge.output.nodeId == output.id) + } + if (edge.output.nodeID == output.id) + { throw new InvalidOperationException("A GPU stage output node cannot produce graph values."); + } } string[] expected = settings.outputs.Select(static value => value.id).ToArray(); - if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length || !expected.ToHashSet(StringComparer.Ordinal).SetEquals(endpoints.Keys)) - throw new InvalidOperationException("Every stage output must have exactly one connection with its original port identity."); - var inputs = region.nodes.Where(static node => node.definitionId == "inno.shader.stage-input") + if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length + || !expected.ToHashSet(StringComparer.Ordinal).SetEquals(endpoints.Keys) + ) { + throw new InvalidOperationException( + "Every stage output must have exactly one connection with its original port identity." + ); + } + Dictionary inputs = region.nodes + .Where(static node => node.definitionID == "inno.shader.stage-input") .ToDictionary(static node => node.id, node => - (ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, null, serialization, context) + (ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_SETTINGS_KEY, + null, + serialization, + context + ) ?? throw new InvalidOperationException("A stage input requires its interface settings.")).CreateBinding()); - IGrouping>? duplicateInput = inputs + IGrouping>? duplicateInput = inputs .GroupBy(static pair => pair.Value.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1); if (duplicateInput is not null) { string nodes = string.Join(", ", duplicateInput.Select(static pair => $"'{pair.Key.value}'")); throw new InvalidOperationException( - $"Stage '{output.id.value}' contains duplicate input '{duplicateInput.Key}' from graph nodes {nodes}."); + $"Stage '{output.id.value}' contains duplicate input '{duplicateInput.Key}' from graph nodes {nodes}." + ); } - ShaderGraphLoweringResult lowered = m_nodes.Lower(new(region, endpoints, implementationId, - sources.Where(pair => members.Contains(pair.Key)).ToDictionary(), inputs), serialization, context, cancellationToken); + ShaderGraphLoweringResult lowered = m_nodes.Lower( + new ShaderGraphLoweringRequest( + region, + endpoints, + implementationID, + sources.Where(pair => members.Contains(pair.Key)).ToDictionary(), + inputs + ), + serialization, + context, + cancellationToken + ); diagnostics.AddRange(lowered.diagnostics); if (!lowered.succeeded) + { continue; - var stage = new ShaderIrStage(settings.stage, lowered.block!, inputs.Values, - settings.outputs.Select(static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? "", value.location)), - settings.threadsX, settings.threadsY, settings.threadsZ); + } + var stage = new ShaderIrStage( + settings.stage, + lowered.block!, + inputs.Values, + settings.outputs.Select( + static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? string.Empty, value.location) + ), + settings.threadsX, + settings.threadsY, + settings.threadsZ + ); stages.Add(output.id.value, stage); } activeNode = null; @@ -169,7 +247,9 @@ public ShaderGraphProgramResult Lower( continue; } if (!selected.TryAdd(shared.stage, shared)) + { Error("SHADER_PROGRAM_STAGE_DUPLICATE", $"Pass '{pass.name}' repeats stage {shared.stage}."); + } } if (!expected.ToHashSet().SetEquals(selected.Keys)) { @@ -177,12 +257,17 @@ public ShaderGraphProgramResult Lower( continue; } if (pass.programKind == ShaderProgramKind.Raster) + { ValidateVaryings(selected[ShaderStage.Vertex], selected[ShaderStage.Fragment]); - passes.Add(new(pass.name, expected.Select(stage => selected[stage]))); + } + passes.Add(new ShaderGraphPass(pass.name, expected.Select(stage => selected[stage]))); } } - catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or FormatException or NotSupportedException - && RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (failure is ArgumentException + or InvalidOperationException + or FormatException + or NotSupportedException + && RetirementPendingException.Find(failure) is null) { Error("SHADER_GRAPH_PROGRAM", failure.Message, activeNode); } @@ -191,164 +276,241 @@ public ShaderGraphProgramResult Lower( void Error( string code, string message, - GraphNodeId? node = null - ) - => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, node)); + GraphNodeID? node = null + ) => diagnostics.Add(new ShaderGraphDiagnostic(code, DiagnosticSeverity.Error, message, node)); } private void ConnectRasterStages( GraphDocument graph, - string implementationId, - IReadOnlyDictionary sources, + string implementationID, + IReadOnlyDictionary sources, SerializationRegistry serialization, SerializationContext context ) { GraphNodeRecord[] outputs = graph.nodes - .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) .ToArray(); - var outputById = outputs.ToDictionary(static node => node.id.value, StringComparer.Ordinal); - var stageById = outputs.ToDictionary( + Dictionary outputByID = outputs.ToDictionary(static node => node.id.value, StringComparer.Ordinal); + Dictionary stageByID = outputs.ToDictionary( static node => node.id.value, - node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).stage, - StringComparer.Ordinal); + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphStageSettings(), + serialization, + context + ).stage, + StringComparer.Ordinal + ); string Owner(GraphNodeRecord node) - => node.definitionId == ShaderGraphDocument.outputDefinitionId - ? node.id.value - : ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context); + => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + ? node.id.value + : ShaderGraphDocument.Read(node, ShaderGraphDocument.C_STAGE_KEY, string.Empty, serialization, context); - var crossings = graph.edges.Select(edge => - { - GraphNodeRecord source = graph.FindNode(edge.output.nodeId) - ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no source node."); - GraphNodeRecord destination = graph.FindNode(edge.input.nodeId) - ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no destination node."); - return (edge, source, destination, sourceOwner: Owner(source), destinationOwner: Owner(destination)); - }) - .Where(static value => value.sourceOwner.Length != 0 && value.destinationOwner.Length != 0 - && value.sourceOwner != value.destinationOwner) + ( + GraphEdgeRecord edge, + GraphNodeRecord source, + GraphNodeRecord destination, + string sourceOwner, + string destinationOwner + )[] crossings = graph.edges + .Select(edge => + { + GraphNodeRecord source = graph.FindNode(edge.output.nodeID) + ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no source node."); + GraphNodeRecord destination = graph.FindNode(edge.input.nodeID) + ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no destination node."); + return (edge, source, destination, sourceOwner: Owner(source), destinationOwner: Owner(destination)); + }) + .Where(static value => ( + value.sourceOwner.Length != 0 && value.destinationOwner.Length != 0 + && value.sourceOwner != value.destinationOwner + )) .OrderBy(static value => value.sourceOwner, StringComparer.Ordinal) - .ThenBy(static value => value.edge.output.nodeId.value, StringComparer.Ordinal) - .ThenBy(static value => value.edge.output.portId.value, StringComparer.Ordinal) + .ThenBy(static value => value.edge.output.nodeID.value, StringComparer.Ordinal) + .ThenBy(static value => value.edge.output.portID.value, StringComparer.Ordinal) .ThenBy(static value => value.destinationOwner, StringComparer.Ordinal) - .ThenBy(static value => value.edge.input.nodeId.value, StringComparer.Ordinal) - .ThenBy(static value => value.edge.input.portId.value, StringComparer.Ordinal) + .ThenBy(static value => value.edge.input.nodeID.value, StringComparer.Ordinal) + .ThenBy(static value => value.edge.input.portID.value, StringComparer.Ordinal) .ToArray(); if (crossings.Length == 0) + { return; + } var ports = new Dictionary(); - foreach (GraphNodeRecord node in graph.nodes.Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId)) + foreach (GraphNodeRecord node in graph.nodes.Where(static node => node.definitionID != ShaderGraphDocument.C_OUTPUT_DEFINITION_ID)) { sources.TryGetValue(node.id, out ShaderSourceModuleAnalysis? source); - ShaderIrStageInput? input = node.definitionId == "inno.shader.stage-input" - ? ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphInputSettings(), serialization, context).CreateBinding() - : null; - foreach (ShaderNodePort port in m_nodes.DescribePorts(node, serialization, context, source, implementationId, input)) - ports.Add(new(node.id, new(port.id)), port); + ShaderIrStageInput? input = node.definitionID == "inno.shader.stage-input" + ? ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphInputSettings(), + serialization, + context + ).CreateBinding() + : null; + foreach (ShaderNodePort port in m_nodes.DescribePorts(node, serialization, context, source, implementationID, input)) + { + ports.Add(new GraphEndpoint(node.id, new GraphPortID(port.id)), port); + } } - var occupiedLocations = outputs.ToDictionary( + Dictionary> occupiedLocations = outputs.ToDictionary( static node => node.id.value, - node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).outputs - .Where(static output => output.kind == ShaderIrOutputKind.Varying - && string.Equals(output.semantic, "texcoord", StringComparison.Ordinal)) + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphStageSettings(), + serialization, + context + ).outputs + .Where(static output => ( + output.kind == ShaderIrOutputKind.Varying + && string.Equals(output.semantic, "texcoord", StringComparison.Ordinal) + )) .Select(static output => output.location) .ToHashSet(), - StringComparer.Ordinal); - var sourceBridges = new Dictionary(); + StringComparer.Ordinal + ); + var sourceBridges = new Dictionary(); var destinationBridges = new Dictionary<(GraphEndpoint source, string destination), GraphNodeRecord>(); foreach ((GraphEdgeRecord edge, _, _, string sourceOwner, string destinationOwner) in crossings) { - if (!stageById.TryGetValue(sourceOwner, out ShaderStage sourceStage)) + if (!stageByID.TryGetValue(sourceOwner, out ShaderStage sourceStage)) + { throw new InvalidOperationException( - $"Connection '{edge.id.value}' refers to unavailable source stage '{sourceOwner}'."); - if (!stageById.TryGetValue(destinationOwner, out ShaderStage destinationStage)) + $"Connection '{edge.id.value}' refers to unavailable source stage '{sourceOwner}'." + ); + } + if (!stageByID.TryGetValue(destinationOwner, out ShaderStage destinationStage)) + { throw new InvalidOperationException( - $"Connection '{edge.id.value}' refers to unavailable destination stage '{destinationOwner}'."); + $"Connection '{edge.id.value}' refers to unavailable destination stage '{destinationOwner}'." + ); + } if (sourceStage != ShaderStage.Vertex || destinationStage != ShaderStage.Fragment) + { throw new InvalidOperationException( - $"Automatic stage transfer supports Vertex-to-Fragment values only; '{edge.id.value}' connects {sourceStage} to {destinationStage}."); + $"Automatic stage transfer supports Vertex-to-Fragment values only; '{edge.id.value}' connects {sourceStage} to {destinationStage}." + ); + } if (!ports.TryGetValue(edge.output, out ShaderNodePort? sourcePort) - || sourcePort.direction != GraphPortDirection.Output) + || sourcePort.direction != GraphPortDirection.Output + ) { throw new InvalidOperationException($"Connection '{edge.id.value}' has no typed source output."); + } if (sourcePort.type.storage is not null - || sourcePort.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + || sourcePort.type.id.StartsWith("sampled-texture", StringComparison.Ordinal) + ) { throw new InvalidOperationException( - $"Connection '{edge.id.value}' tries to transfer GPU resource type '{sourcePort.type.id}' between stages."); + $"Connection '{edge.id.value}' tries to transfer GPU resource type '{sourcePort.type.id}' between stages." + ); + } - if (!sourceBridges.TryGetValue(edge.output, out (string portId, int location) sourceBridge)) + if (!sourceBridges.TryGetValue(edge.output, out (string portID, int location) sourceBridge)) { - string token = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value)))[..16]; - string edgeId = "__stage-bridge-" + token + "/write"; - if (graph.edges.Any(value => value.id.value == edgeId)) - throw new InvalidOperationException($"Generated stage bridge identity '{edgeId}' collides with an authored connection."); - string portId = "bridge_" + token; - const string semantic = "texcoord"; + string token = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + sourceOwner + "\n" + edge.output.nodeID.value + "\n" + edge.output.portID.value + ) + ) + )[..16]; + string edgeID = "__stage-bridge-" + token + "/write"; + if (graph.edges.Any(value => value.id.value == edgeID)) + { + throw new InvalidOperationException( + $"Generated stage bridge identity '{edgeID}' collides with an authored connection." + ); + } + string portID = "bridge_" + token; + const string C_SEMANTIC = "texcoord"; HashSet occupied = occupiedLocations[sourceOwner]; int location = Enumerable.Range(0, 16).FirstOrDefault(value => !occupied.Contains(value), -1); if (location < 0) + { throw new InvalidOperationException( - "Automatic Vertex-to-Fragment transfer exhausted the portable texcoord varying locations 0 through 15."); + "Automatic Vertex-to-Fragment transfer exhausted the portable texcoord varying locations 0 through 15." + ); + } occupied.Add(location); - GraphNodeRecord sourceOutput = outputById[sourceOwner]; - ShaderGraphStageSettings outputSettings = ShaderGraphDocument.Read(sourceOutput, - ShaderGraphDocument.settingsKey, new ShaderGraphStageSettings(), serialization, context); + GraphNodeRecord sourceOutput = outputByID[sourceOwner]; + ShaderGraphStageSettings outputSettings = ShaderGraphDocument.Read( + sourceOutput, + ShaderGraphDocument.C_SETTINGS_KEY, + new ShaderGraphStageSettings(), + serialization, + context + ); outputSettings.outputs = [ .. outputSettings.outputs, new ShaderGraphOutput { - id = portId, + id = portID, kind = ShaderIrOutputKind.Varying, - semantic = semantic, + semantic = C_SEMANTIC, location = location } ]; - sourceOutput.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(outputSettings, serialization, context)); - graph.AddEdge(new( - new(edgeId), - edge.output, - new(sourceOutput.id, new(portId)))); - sourceBridge = (portId, location); + sourceOutput.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(outputSettings, serialization, context) + ); + graph.AddEdge( + new GraphEdgeRecord(new GraphEdgeID(edgeID), edge.output, new GraphEndpoint(sourceOutput.id, new GraphPortID(portID))) + ); + sourceBridge = (portID, location); sourceBridges.Add(edge.output, sourceBridge); } - var key = (edge.output, destinationOwner); + (GraphEndpoint output, string destinationOwner) key = (edge.output, destinationOwner); if (!destinationBridges.TryGetValue(key, out GraphNodeRecord? inputNode)) { - string token = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value + "\n" + destinationOwner)))[..16]; + string token = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + sourceOwner + "\n" + edge.output.nodeID.value + "\n" + edge.output.portID.value + "\n" + destinationOwner + ) + ) + )[..16]; string id = "__stage-bridge-" + token; - if (graph.FindNode(new(id)) is not null) + if (graph.FindNode(new GraphNodeID(id)) is not null) + { throw new InvalidOperationException($"Generated stage bridge identity '{id}' collides with an authored node."); - inputNode = new(new(id), "inno.shader.stage-input"); - inputNode.SetValue(ShaderGraphDocument.stageKey, - ShaderGraphDocument.Encode(destinationOwner, serialization, context)); - inputNode.SetValue(ShaderGraphDocument.settingsKey, + } + inputNode = new(new GraphNodeID(id), "inno.shader.stage-input"); + inputNode.SetValue( + ShaderGraphDocument.C_STAGE_KEY, + ShaderGraphDocument.Encode(destinationOwner, serialization, context) + ); + inputNode.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, ShaderGraphDocument.Encode(new ShaderGraphInputSettings { - id = sourceBridge.portId, + id = sourceBridge.portID, type = ShaderGraphType.Capture(sourcePort.type), kind = ShaderIrInputKind.Varying, semantic = "texcoord", location = sourceBridge.location - }, serialization, context)); + }, serialization, context) + ); graph.AddNode(inputNode); destinationBridges.Add(key, inputNode); } graph.RemoveEdge(edge.id); - graph.AddEdge(new( - new(inputNode.id.value + "/read/" + edge.id.value), - new(inputNode.id, new("value")), - edge.input)); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(inputNode.id.value + "/read/" + edge.id.value), + new GraphEndpoint(inputNode.id, new GraphPortID("value")), + edge.input + ) + ); } } @@ -358,10 +520,16 @@ ShaderIrStage fragment ) { foreach (ShaderIrStageInput input in fragment.inputs.Where(static input => input.kind == ShaderIrInputKind.Varying)) { - ShaderIrStageOutput? output = vertex.outputs.SingleOrDefault(output => output.kind == ShaderIrOutputKind.Varying - && output.semantic == input.semantic && output.location == input.location); + ShaderIrStageOutput? output = vertex.outputs.SingleOrDefault(output => ( + output.kind == ShaderIrOutputKind.Varying + && output.semantic == input.semantic && output.location == input.location + )); if (output is null || !vertex.body.outputs[output.id].type.IsEquivalentTo(input.type)) - throw new InvalidOperationException($"Fragment varying '{input.semantic}' at {input.location} has no matching vertex output type."); + { + throw new InvalidOperationException( + $"Fragment varying '{input.semantic}' at {input.location} has no matching vertex output type." + ); + } } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs similarity index 54% rename from src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs rename to src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs index 4083f0fd7..f67105029 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs @@ -5,39 +5,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Freezes the graph-lowered stages of one material-selectable GPU pass. -/// -public sealed class ShaderGraphPass -{ - /// - /// Captures a pass's ordered typed stages. - /// - /// - /// Exact pass identity in the program contract. - /// - /// - /// Complete raster or compute stage set. - /// - public ShaderGraphPass( - string name, - IEnumerable stages - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(stages); - this.name = name; - this.stages = Array.AsReadOnly(stages.ToArray()); - } - /// - /// Gets the stable pass identity. - /// - public string name { get; } - /// - /// Gets immutable graph-lowered stages. - /// - public IReadOnlyList stages { get; } -} - /// /// Contains the result of lowering an entire shader graph, before target-native compilation. /// @@ -50,14 +17,17 @@ IEnumerable diagnostics this.passes = Array.AsReadOnly(passes.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); } + /// /// Gets the complete stage set; empty if any stage failed. /// public IReadOnlyList passes { get; } + /// /// Gets stable graph/node diagnostics without provider references. /// public IReadOnlyList diagnostics { get; } + /// /// Gets whether every declared pass was lowered without errors. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs index 5119c6c9d..ebf7f2219 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs @@ -7,21 +7,6 @@ namespace Inno.Rendering.Shaders; -/// -/// References shared stage output identities from a material-selectable pass. -/// -public struct ShaderGraphPassProgram -{ - /// - /// Gets or sets the exact pass identity in the runtime shader definition. - /// - public string pass { get; set; } - /// - /// Gets or sets stable stage output node identities; computation remains owned by those nodes. - /// - public string[] stages { get; set; } -} - /// /// Edits pass-to-program references without copying computation or changing runtime render states. /// @@ -30,7 +15,7 @@ public static class ShaderGraphPrograms /// /// Identifies native metadata holding pass references to shared stage programs. /// - public const string bindingsKey = "inno.shader.programs"; + public const string C_BINDINGS_KEY = "inno.shader.programs"; /// /// Reads detached pass-to-stage references, including unresolved authored identities. @@ -51,10 +36,9 @@ public static ShaderGraphPassProgram[] Read( GraphDocument graph, SerializationRegistry serialization, SerializationContext context - ) - => graph.metadata.TryGetValue(bindingsKey, out GraphSerializedValue? data) - ? ShaderGraphDocument.Decode(data, serialization, context) - : throw new InvalidOperationException("The shader document has no pass-to-program references."); + ) => graph.metadata.TryGetValue(C_BINDINGS_KEY, out GraphSerializedValue? data) + ? ShaderGraphDocument.Decode(data, serialization, context) + : throw new InvalidOperationException("The shader document has no pass-to-program references."); /// /// Assigns existing shared stages to one pass in an atomic detached candidate. @@ -80,28 +64,40 @@ SerializationContext context public static GraphDocument Bind( GraphDocument graph, string pass, - IEnumerable stages, + IEnumerable stages, SerializationRegistry serialization, SerializationContext context ) { ArgumentNullException.ThrowIfNull(stages); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); if (!definition.passes.Any(value => value.name == pass)) + { throw new ArgumentException($"Unknown pass '{pass}'.", nameof(pass)); + } string[] references = stages.Select(static value => value.value).ToArray(); if (references.Distinct(StringComparer.Ordinal).Count() != references.Length) + { throw new ArgumentException("A pass cannot reference the same stage twice.", nameof(stages)); + } foreach (string id in references) - if (graph.FindNode(new(id))?.definitionId != ShaderGraphDocument.outputDefinitionId) + { + if (graph.FindNode(new GraphNodeID(id))?.definitionID != ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + { throw new ArgumentException($"Stage program '{id}' is unavailable.", nameof(stages)); + } + } GraphDocument candidate = graph.Clone(); ShaderGraphPassProgram[] bindings = Read(graph, serialization, context); int index = Array.FindIndex(bindings, value => value.pass == pass); var binding = new ShaderGraphPassProgram { pass = pass, stages = references }; if (index < 0) + { bindings = [.. bindings, binding]; + } else + { bindings[index] = binding; + } Write(candidate, bindings, serialization, context); return candidate; } @@ -132,7 +128,9 @@ SerializationContext context ) { ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); if (!definition.passes.Any(value => value.name == pass)) + { throw new ArgumentException($"Unknown pass '{pass}'.", nameof(pass)); + } ShaderGraphPassProgram[] bindings = Read(graph, serialization, context); string[] removedStages = bindings.Where(value => value.pass == pass).SelectMany(static value => value.stages).ToArray(); ShaderGraphPassProgram[] remaining = bindings.Where(value => value.pass != pass).ToArray(); @@ -145,11 +143,20 @@ SerializationContext context technique.passes = technique.passes.Where(value => value.passName != pass).ToArray(); definition.techniques[index] = technique; } - candidate.SetMetadata(ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + candidate.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); Write(candidate, remaining, serialization, context); - return ShaderGraphBindings.RemoveNodes(candidate, removedStages.Where(id => !retained.Contains(id)) - .Distinct(StringComparer.Ordinal).Select(static id => new GraphNodeId(id)).Where(id => candidate.FindNode(id) is not null), serialization, context); + return ShaderGraphBindings.RemoveNodes( + candidate, + removedStages.Where(id => !retained.Contains(id)) + .Distinct(StringComparer.Ordinal) + .Select(static id => new GraphNodeID(id)) + .Where(id => candidate.FindNode(id) is not null), + serialization, + context + ); } internal static void Write( @@ -157,6 +164,5 @@ internal static void Write( ShaderGraphPassProgram[] programs, SerializationRegistry serialization, SerializationContext context - ) - => graph.SetMetadata(bindingsKey, ShaderGraphDocument.Encode(programs, serialization, context)); + ) => graph.SetMetadata(C_BINDINGS_KEY, ShaderGraphDocument.Encode(programs, serialization, context)); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs new file mode 100644 index 000000000..bc71896d5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs @@ -0,0 +1,39 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores one stage's explicit output interface and compute dimensions inside its output node. +/// +public sealed class ShaderGraphStageSettings : ISerializable +{ + /// + /// Gets or sets the programmable stage. + /// + [SerializableProperty] + public ShaderStage stage { get; set; } = ShaderStage.Fragment; + + /// + /// Gets or sets output ports and their GPU destinations. + /// + [SerializableProperty] + public ShaderGraphOutput[] outputs { get; set; } = []; + + /// + /// Gets or sets compute workgroup width. + /// + [SerializableProperty] + public int threadsX { get; set; } = 1; + + /// + /// Gets or sets compute workgroup height. + /// + [SerializableProperty] + public int threadsY { get; set; } = 1; + + /// + /// Gets or sets compute workgroup depth. + /// + [SerializableProperty] + public int threadsZ { get; set; } = 1; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs new file mode 100644 index 000000000..f5b5ff4bc --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphStageSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphStageSettings value + ) { + writer.Write("stage", value.stage); + writer.Write("outputs", value.outputs); + writer.Write("threadsX", value.threadsX); + writer.Write("threadsY", value.threadsY); + writer.Write("threadsZ", value.threadsZ); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph stage settings that represents the completed operation. + /// + public override ShaderGraphStageSettings Read(SerializationReader reader) + => new() + { + stage = reader.Read("stage"), + outputs = reader.Read("outputs"), + threadsX = reader.Read("threadsX"), + threadsY = reader.Read("threadsY"), + threadsZ = reader.Read("threadsZ") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs index 40bba1490..59b487c0e 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs @@ -27,30 +27,80 @@ public static GraphDocument CreateRaster( SerializationRegistry serialization, SerializationContext context ) { - var pass = new ShaderPassDefinition("Main", ShaderProgramKind.Raster, renderState: new() - { cull = ShaderCullMode.None, depthCompare = ShaderCompareFunction.Always, depthWrite = false, blend = RenderBlendState.alpha, colorWriteMask = 15 }); - var definition = new ShaderDefinition("New Shader", [new(new("color"), "Color", ShaderPropertyType.Color, ShaderStage.Fragment, - MaterialValue.FromVector(new Vector4(1f, 1f, 1f, 1f)))], [], [pass]); + var pass = new ShaderPassDefinition("Main", ShaderProgramKind.Raster, renderState: new ShaderRenderState() + { + cull = ShaderCullMode.None, + depthCompare = ShaderCompareFunction.Always, + depthWrite = false, + blend = RenderBlendState.alpha, + colorWriteMask = 15 + }); + var definition = new ShaderDefinition("New Shader", [new ShaderPropertyDefinition( + new ShaderPropertyID("color"), + "Color", + ShaderPropertyType.Color, + ShaderStage.Fragment, + MaterialValue.FromVector(new Vector4(1f, 1f, 1f, 1f)) + )], [], [pass]); GraphDocument graph = ShaderGraphDocument.Create(definition, serialization, context); - GraphNodeRecord vertex = Node("vertex", ShaderGraphDocument.outputDefinitionId, 770, 50); - Set(vertex, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Vertex, outputs = [new() { id = "position", kind = ShaderIrOutputKind.ClipPosition }] }); - GraphNodeRecord fragment = Node("fragment", ShaderGraphDocument.outputDefinitionId, 770, 640); - Set(fragment, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Fragment, outputs = [new() { id = "color", kind = ShaderIrOutputKind.Color }] }); + GraphNodeRecord vertex = Node("vertex", ShaderGraphDocument.C_OUTPUT_DEFINITION_ID, 770, 50); + Set( + vertex, + "settings", + new ShaderGraphStageSettings + { + stage = ShaderStage.Vertex, + outputs = [new ShaderGraphOutput() { id = "position", kind = ShaderIrOutputKind.ClipPosition }] + } + ); + GraphNodeRecord fragment = Node("fragment", ShaderGraphDocument.C_OUTPUT_DEFINITION_ID, 770, 640); + Set( + fragment, + "settings", + new ShaderGraphStageSettings + { + stage = ShaderStage.Fragment, + outputs = [new ShaderGraphOutput() { id = "color", kind = ShaderIrOutputKind.Color }] + } + ); GraphNodeRecord position = Node("position", "inno.shader.stage-input", 40, 50, vertex); - Set(position, "settings", new ShaderGraphInputSettings { id = "position", type = new() { id = "float2" }, kind = ShaderIrInputKind.VertexAttribute, semantic = "position" }); + Set( + position, + "settings", + new ShaderGraphInputSettings + { + id = "position", + type = new() { id = "float2" }, + kind = ShaderIrInputKind.VertexAttribute, + semantic = "position" + } + ); GraphNodeRecord construct = Node("clip-position", "inno.shader.construct", 480, 50, vertex); Set(construct, "type", "float4"); for (int index = 0; index < 2; index++) { GraphNodeRecord extract = Node("axis-" + index, "inno.shader.extract", 340, 280 + index * 270, vertex); - Set(extract, "type", "float2"); Set(extract, "index", index); - Connect(position, "value", extract, "input"); Connect(extract, "value", construct, "component." + index); + Set(extract, "type", "float2"); + Set(extract, "index", index); + Connect(position, "value", extract, "input"); + Connect(extract, "value", construct, "component." + index); GraphNodeRecord constant = Node("homogeneous-" + index, "inno.shader.constant", 40, 370 + index * 250, vertex); - Set(constant, "value", (float)index); Connect(constant, "value", construct, "component." + (index + 2)); + Set(constant, "value", (float)index); + Connect(constant, "value", construct, "component." + (index + 2)); } Connect(construct, "value", vertex, "position"); GraphNodeRecord color = Node("color", "inno.shader.stage-input", 480, 920, fragment); - Set(color, "settings", new ShaderGraphInputSettings { id = "color", type = new() { id = "float4" }, kind = ShaderIrInputKind.Uniform, semantic = "" }); + Set( + color, + "settings", + new ShaderGraphInputSettings + { + id = "color", + type = new() { id = "float4" }, + kind = ShaderIrInputKind.Uniform, + semantic = string.Empty + } + ); Connect(color, "value", fragment, "color"); return ShaderGraphPrograms.Bind(graph, "Main", [vertex.id, fragment.id], serialization, context); @@ -61,10 +111,13 @@ GraphNodeRecord Node( float y, GraphNodeRecord? stage = null ) { - var node = new GraphNodeRecord(new(id), type) { position = new(x, y) }; + var node = new GraphNodeRecord(new GraphNodeID(id), type) { position = new(x, y) }; if (stage is not null) + { Set(node, "stage", stage.id.value); - graph.AddNode(node); return node; + } + graph.AddNode(node); + return node; } void Set( GraphNodeRecord node, @@ -76,7 +129,12 @@ void Connect( string output, GraphNodeRecord b, string input - ) - => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(a.id, new(output)), new(b.id, new(input)))); + ) => graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(a.id, new GraphPortID(output)), + new GraphEndpoint(b.id, new GraphPortID(input)) + ) + ); } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs index a1890d072..d7e0afe8e 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs @@ -12,51 +12,124 @@ public sealed class ShaderGraphType : ISerializable /// /// Gets or sets the atomic or nominal structure type identity. /// - [SerializableProperty] public string id { get; set; } = "float4"; + [SerializableProperty] + public string id { get; set; } = "float4"; + /// /// Gets or sets the fixed array element type, or null for a non-array. /// - [SerializableProperty] public ShaderGraphType? element { get; set; } + [SerializableProperty] + public ShaderGraphType? element { get; set; } + /// /// Gets or sets the fixed array length. /// - [SerializableProperty] public int length { get; set; } + [SerializableProperty] + public int length { get; set; } + /// /// Gets or sets ordered structure member names. /// - [SerializableProperty] public string[] fieldNames { get; set; } = []; + [SerializableProperty] + public string[] fieldNames { get; set; } = []; + /// /// Gets or sets ordered structure member types. /// - [SerializableProperty] public ShaderGraphType[] fieldTypes { get; set; } = []; + [SerializableProperty] + public ShaderGraphType[] fieldTypes { get; set; } = []; + /// /// Gets or sets whether the descriptor represents a storage binding. /// - [SerializableProperty] public bool isStorage { get; set; } + [SerializableProperty] + public bool isStorage { get; set; } + /// /// Gets or sets whether storage is an image instead of a buffer. /// - [SerializableProperty] public bool isImage { get; set; } + [SerializableProperty] + public bool isImage { get; set; } + /// /// Gets or sets the complete buffer element type. /// - [SerializableProperty] public ShaderGraphType? storageElement { get; set; } + [SerializableProperty] + public ShaderGraphType? storageElement { get; set; } + /// /// Gets or sets storage access. /// - [SerializableProperty] public RenderStorageAccess access { get; set; } + [SerializableProperty] + public RenderStorageAccess access { get; set; } + /// /// Gets or sets the image texel format. /// - [SerializableProperty] public RenderTextureFormat format { get; set; } + [SerializableProperty] + public RenderTextureFormat format { get; set; } + /// /// Gets or sets the image spatial dimension. /// - [SerializableProperty] public RenderTextureDimension dimension { get; set; } = RenderTextureDimension.Texture2D; + [SerializableProperty] + public RenderTextureDimension dimension { get; set; } = RenderTextureDimension.Texture2D; + /// /// Gets or sets whether an image has array layers. /// - [SerializableProperty] public bool isArray { get; set; } + [SerializableProperty] + public bool isArray { get; set; } + + /// + /// Validates and freezes the complete descriptor. + /// + /// + /// An immutable type; contradictory or incomplete descriptors fail explicitly. + /// + public ShaderSourceType CreateType() + { + if (fieldNames.Length != fieldTypes.Length) + { + throw new InvalidOperationException("Shader structure field names and types differ in length."); + } + if (isStorage) + { + if (element is not null || fieldNames.Length != 0 || length != 0) + { + throw new InvalidOperationException("A storage type cannot also be an array or structure."); + } + return ShaderSourceType.Storage( + isImage + ? ShaderStorageType.Image(format, access, dimension, isArray) + : ShaderStorageType.Buffer( + (storageElement ?? throw new InvalidOperationException("A storage buffer requires its element type.")).CreateType(), + access + ) + ); + } + if (element is not null) + { + if (fieldNames.Length != 0) + { + throw new InvalidOperationException("An array cannot also declare structure fields."); + } + return ShaderSourceType.ArrayOf(element.CreateType(), length); + } + if (length != 0 || storageElement is not null) + { + throw new InvalidOperationException("A non-array value contains an unexpected element descriptor."); + } + return fieldNames.Length == 0 + ? ShaderSourceType.Atomic(id) + : ShaderSourceType.Structure( + id, + fieldNames.Select(( + name, + index + ) => new ShaderSourceField(name, fieldTypes[index].CreateType())).ToArray() + ); + } /// /// Captures a full immutable source type as reload-safe authoring data. @@ -70,9 +143,14 @@ public sealed class ShaderGraphType : ISerializable public static ShaderGraphType Capture(ShaderSourceType type) { ArgumentNullException.ThrowIfNull(type); - var result = new ShaderGraphType { id = type.id, element = type.elementType is null ? null : Capture(type.elementType), - length = type.elementCount, fieldNames = type.fields.Select(static field => field.name).ToArray(), - fieldTypes = type.fields.Select(static field => Capture(field.type)).ToArray() }; + var result = new ShaderGraphType + { + id = type.id, + element = type.elementType is null ? null : Capture(type.elementType), + length = type.elementCount, + fieldNames = type.fields.Select(static field => field.name).ToArray(), + fieldTypes = type.fields.Select(static field => Capture(field.type)).ToArray() + }; if (type.storage is ShaderStorageType storage) { result.isStorage = true; @@ -81,43 +159,14 @@ public static ShaderGraphType Capture(ShaderSourceType type) result.dimension = storage.dimension; result.isArray = storage.array; if (storage.isImage) + { result.format = storage.format!.Value; + } else + { result.storageElement = Capture(storage.valueType); + } } return result; } - - /// - /// Validates and freezes the complete descriptor. - /// - /// - /// An immutable type; contradictory or incomplete descriptors fail explicitly. - /// - public ShaderSourceType CreateType() - { - if (fieldNames.Length != fieldTypes.Length) - throw new InvalidOperationException("Shader structure field names and types differ in length."); - if (isStorage) - { - if (element is not null || fieldNames.Length != 0 || length != 0) - throw new InvalidOperationException("A storage type cannot also be an array or structure."); - return ShaderSourceType.Storage(isImage - ? ShaderStorageType.Image(format, access, dimension, isArray) - : ShaderStorageType.Buffer((storageElement ?? throw new InvalidOperationException("A storage buffer requires its element type.")).CreateType(), access)); - } - if (element is not null) - { - if (fieldNames.Length != 0) - throw new InvalidOperationException("An array cannot also declare structure fields."); - return ShaderSourceType.ArrayOf(element.CreateType(), length); - } - if (length != 0 || storageElement is not null) - throw new InvalidOperationException("A non-array value contains an unexpected element descriptor."); - return fieldNames.Length == 0 ? ShaderSourceType.Atomic(id) - : ShaderSourceType.Structure(id, fieldNames.Select(( - name, - index - ) => new ShaderSourceField(name, fieldTypes[index].CreateType())).ToArray()); - } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs new file mode 100644 index 000000000..ad266c9bd --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs @@ -0,0 +1,60 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphTypeConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphType value + ) { + writer.Write("id", value.id); + writer.Write("element", value.element); + writer.Write("length", value.length); + writer.Write("fieldNames", value.fieldNames); + writer.Write("fieldTypes", value.fieldTypes); + writer.Write("isStorage", value.isStorage); + writer.Write("isImage", value.isImage); + writer.Write("storageElement", value.storageElement); + writer.Write("access", value.access); + writer.Write("format", value.format); + writer.Write("dimension", value.dimension); + writer.Write("isArray", value.isArray); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph type that represents the completed operation. + /// + public override ShaderGraphType Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + element = reader.Read("element"), + length = reader.Read("length"), + fieldNames = reader.Read("fieldNames"), + fieldTypes = reader.Read("fieldTypes"), + isStorage = reader.Read("isStorage"), + isImage = reader.Read("isImage"), + storageElement = reader.Read("storageElement"), + access = reader.Read("access"), + format = reader.Read("format"), + dimension = reader.Read("dimension"), + isArray = reader.Read("isArray") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs deleted file mode 100644 index 57148b37e..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs +++ /dev/null @@ -1,356 +0,0 @@ -using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; - -namespace Inno.Rendering.Shaders; - -internal sealed class ShaderGraphLiteralConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphLiteral value - ) { - writer.Write("type", value.type); - writer.Write("scalarBits", value.scalarBits); - } - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph literal that represents the completed operation. - /// - public override ShaderGraphLiteral Read(SerializationReader reader) - => new() { type = reader.Read("type"), scalarBits = reader.Read("scalarBits") }; -} - -internal sealed class ShaderGraphStageSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphStageSettings value - ) { - writer.Write("stage", value.stage); - writer.Write("outputs", value.outputs); - writer.Write("threadsX", value.threadsX); - writer.Write("threadsY", value.threadsY); - writer.Write("threadsZ", value.threadsZ); - } - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph stage settings that represents the completed operation. - /// - public override ShaderGraphStageSettings Read(SerializationReader reader) => new() - { - stage = reader.Read("stage"), - outputs = reader.Read("outputs"), - threadsX = reader.Read("threadsX"), - threadsY = reader.Read("threadsY"), - threadsZ = reader.Read("threadsZ"), - }; -} - -internal sealed class ShaderGraphInputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphInputSettings value - ) { - writer.Write("id", value.id); - writer.Write("type", value.type); - writer.Write("kind", value.kind); - writer.Write("semantic", value.semantic); - writer.Write("location", value.location); - } - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph input settings that represents the completed operation. - /// - public override ShaderGraphInputSettings Read(SerializationReader reader) => new() - { - id = reader.Read("id"), - type = reader.Read("type"), - kind = reader.Read("kind"), - semantic = reader.Read("semantic"), - location = reader.Read("location"), - }; -} - -internal sealed class ShaderGraphNodePortDefinitionConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodePortDefinition value - ) { - writer.Write("id", value.id); - writer.Write("type", value.type); - writer.Write("required", value.required); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node port definition that represents the completed operation. - /// - public override ShaderGraphNodePortDefinition Read(SerializationReader reader) => new() - { - id = reader.Read("id"), - type = reader.Read("type"), - required = reader.Read("required") - }; -} - -internal sealed class ShaderGraphNodeSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeSettings value - ) { - writer.Write("displayName", value.displayName); - writer.Write("createPath", value.createPath); - writer.Write("createOrder", value.createOrder); - writer.Write("kind", value.kind); - writer.Write("effect", value.effect); - writer.Write("role", value.role); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node settings that represents the completed operation. - /// - public override ShaderGraphNodeSettings Read(SerializationReader reader) => new() - { - displayName = reader.Read("displayName"), - createPath = reader.Read("createPath"), - createOrder = reader.Read("createOrder"), - kind = reader.Read("kind"), - effect = reader.Read("effect"), - role = reader.Read("role") - }; -} - -internal sealed class ShaderGraphNodeInputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeInputSettings value - ) => writer.Write("ports", value.ports); - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node input settings that represents the completed operation. - /// - public override ShaderGraphNodeInputSettings Read(SerializationReader reader) => new() - { - ports = reader.Read("ports") - }; -} - -internal sealed class ShaderGraphNodeOutputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeOutputSettings value - ) => writer.Write("ports", value.ports); - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node output settings that represents the completed operation. - /// - public override ShaderGraphNodeOutputSettings Read(SerializationReader reader) - => new() { ports = reader.Read("ports") }; -} - -internal sealed class ShaderGraphNodeInterfaceConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeInterface value - ) { - writer.Write("displayName", value.displayName); - writer.Write("createPath", value.createPath); - writer.Write("createOrder", value.createOrder); - writer.Write("kind", value.kind); - writer.Write("effect", value.effect); - writer.Write("role", value.role); - writer.Write("inputs", value.inputs); - writer.Write("outputs", value.outputs); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node interface that represents the completed operation. - /// - public override ShaderGraphNodeInterface Read(SerializationReader reader) => new() - { - displayName = reader.Read("displayName"), - createPath = reader.Read("createPath"), - createOrder = reader.Read("createOrder"), - kind = reader.Read("kind"), - effect = reader.Read("effect"), - role = reader.Read("role"), - inputs = reader.Read("inputs"), - outputs = reader.Read("outputs") - }; -} - -internal sealed class ShaderGraphTypeConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphType value - ) { - writer.Write("id", value.id); - writer.Write("element", value.element); - writer.Write("length", value.length); - writer.Write("fieldNames", value.fieldNames); - writer.Write("fieldTypes", value.fieldTypes); - writer.Write("isStorage", value.isStorage); - writer.Write("isImage", value.isImage); - writer.Write("storageElement", value.storageElement); - writer.Write("access", value.access); - writer.Write("format", value.format); - writer.Write("dimension", value.dimension); - writer.Write("isArray", value.isArray); - } - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph type that represents the completed operation. - /// - public override ShaderGraphType Read(SerializationReader reader) => new() - { - id = reader.Read("id"), - element = reader.Read("element"), - length = reader.Read("length"), - fieldNames = reader.Read("fieldNames"), - fieldTypes = reader.Read("fieldTypes"), - isStorage = reader.Read("isStorage"), - isImage = reader.Read("isImage"), - storageElement = reader.Read("storageElement"), - access = reader.Read("access"), - format = reader.Read("format"), - dimension = reader.Read("dimension"), - isArray = reader.Read("isArray"), - }; -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs index bd7aa9f7d..ec336d064 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs @@ -6,29 +6,29 @@ namespace Inno.Rendering.Shaders; /// -/// Identifies a typed single-assignment value within one intermediate block. +/// Contains immutable ordered instructions and nested structured regions without retaining builder callbacks. /// -public sealed class ShaderIrValue +public sealed class ShaderIrBlock { - internal ShaderIrValue( - object owner, - int index, - ShaderSourceType type + internal ShaderIrBlock( + IEnumerable instructions, + IReadOnlyDictionary outputs ) { - this.owner = owner; - this.index = index; - this.type = type; + this.instructions = Array.AsReadOnly(instructions.ToArray()); + this.outputs = new ReadOnlyDictionary( + new Dictionary(outputs, StringComparer.Ordinal) + ); } /// - /// Gets the deterministic block-local value index, not a GPU register or resource slot. + /// Gets instructions in evaluation order, including source calls whose outputs are unused. /// - public int index { get; } + public IReadOnlyList instructions { get; } + /// - /// Gets the complete language-independent value type. + /// Gets named values returned to the enclosing stage or region. /// - public ShaderSourceType type { get; } - internal object owner { get; } + public IReadOnlyDictionary outputs { get; } } /// @@ -129,91 +129,3 @@ public enum ShaderIrOperation /// Loop } - -/// -/// Stores one immutable typed instruction without generated stage source or backend expressions. -/// -public sealed class ShaderIrInstruction -{ - internal ShaderIrInstruction( - ShaderIrOperation operation, - IEnumerable inputs, - IEnumerable outputs, - string? inputName = null, - ulong constantBits = 0, - int memberIndex = 0, - ShaderSourceImplementationAnalysis? source = null, - IEnumerable? regions = null - ) { - this.operation = operation; - this.inputs = Array.AsReadOnly(inputs.ToArray()); - this.outputs = Array.AsReadOnly(outputs.ToArray()); - this.inputName = inputName; - this.constantBits = constantBits; - this.memberIndex = memberIndex; - this.source = source; - this.regions = Array.AsReadOnly(regions?.ToArray() ?? []); - } - - /// - /// Gets the semantic operation independent of any source language. - /// - public ShaderIrOperation operation { get; } - /// - /// Gets immutable operands in operation or function-declaration order. - /// - public IReadOnlyList inputs { get; } - /// - /// Gets produced values; a call orders its return value first, then out/inout parameters. - /// - public IReadOnlyList outputs { get; } - /// - /// Gets the stable interface or region-parameter identity, only for Input or RegionInput. - /// - public string? inputName { get; } - /// - /// Gets exact scalar bits for a Constant instruction; the result type determines interpretation. - /// - public ulong constantBits { get; } - /// - /// Gets the zero-based component/member/element ordinal for an Extract instruction. - /// - public int memberIndex { get; } - /// - /// Gets a frozen, analyzed function implementation only for a SourceCall instruction. - /// - public ShaderSourceImplementationAnalysis? source { get; } - /// - /// Gets immutable nested regions: true/false for Branch, or one body for Loop. - /// - public IReadOnlyList regions { get; } - /// - /// Gets whether removing or reordering this instruction may change observable behavior. - /// - public bool hasSideEffects => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad - or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard - or ShaderIrOperation.Branch or ShaderIrOperation.Loop; -} - -/// -/// Contains immutable ordered instructions and nested structured regions without retaining builder callbacks. -/// -public sealed class ShaderIrBlock -{ - internal ShaderIrBlock( - IEnumerable instructions, - IReadOnlyDictionary outputs - ) { - this.instructions = Array.AsReadOnly(instructions.ToArray()); - this.outputs = new ReadOnlyDictionary(new Dictionary(outputs, StringComparer.Ordinal)); - } - - /// - /// Gets instructions in evaluation order, including source calls whose outputs are unused. - /// - public IReadOnlyList instructions { get; } - /// - /// Gets named values returned to the enclosing stage or region. - /// - public IReadOnlyDictionary outputs { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs index 358468e81..ff6f70583 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs @@ -40,7 +40,9 @@ Func> whenFalse ArgumentNullException.ThrowIfNull(whenTrue); ArgumentNullException.ThrowIfNull(whenFalse); if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool"))) + { throw new ArgumentException("A branch condition must be bool.", nameof(condition)); + } int nextValue = m_root.m_nextValue; try { @@ -48,7 +50,7 @@ Func> whenFalse ShaderIrBlock second = BuildRegion(whenFalse); ValidateOutputs(first.outputs, second.outputs); IReadOnlyDictionary outputs = MergeValues(first.outputs); - m_instructions.Add(new(ShaderIrOperation.Branch, [condition], outputs.Values, regions: [first, second])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Branch, [condition], outputs.Values, regions: [first, second])); return outputs; } catch @@ -88,13 +90,18 @@ Func, ArgumentNullException.ThrowIfNull(initialState); ArgumentNullException.ThrowIfNull(body); if (!iterations.type.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) + { throw new ArgumentException("A loop count must be uint.", nameof(iterations)); + } foreach ((string name, ShaderIrValue value) in initialState) { ArgumentException.ThrowIfNullOrWhiteSpace(name); RequireOwned(value); } - var initial = new SortedDictionary(initialState.ToDictionary(static pair => pair.Key, static pair => pair.Value), StringComparer.Ordinal); + var initial = new SortedDictionary( + initialState.ToDictionary(static pair => pair.Key, static pair => pair.Value), + StringComparer.Ordinal + ); int nextValue = m_root.m_nextValue; try { @@ -103,12 +110,21 @@ Func, ShaderIrValue index = builder.RegionInput("iteration", ShaderSourceType.Atomic("uint")); var carried = new Dictionary(StringComparer.Ordinal); foreach ((string name, ShaderIrValue value) in initial) + { carried.Add(name, builder.RegionInput("state." + name, value.type)); + } return body(builder, index, new ReadOnlyDictionary(carried)); }); ValidateOutputs(initial, region.outputs); IReadOnlyDictionary outputs = MergeValues(initial); - m_instructions.Add(new(ShaderIrOperation.Loop, new[] { iterations }.Concat(initial.Values), outputs.Values, regions: [region])); + m_instructions.Add( + new ShaderIrInstruction( + ShaderIrOperation.Loop, + new[] { iterations }.Concat(initial.Values), + outputs.Values, + regions: [region] + ) + ); return outputs; } catch @@ -138,7 +154,7 @@ private ShaderIrValue RegionInput( ShaderSourceType type ) { ShaderIrValue output = NewValue(type); - m_instructions.Add(new(ShaderIrOperation.RegionInput, [], [output], inputName: name)); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.RegionInput, [], [output], inputName: name)); return output; } @@ -148,7 +164,9 @@ private IReadOnlyDictionary MergeValues(IReadOnlyDictiona foreach ((string name, ShaderIrValue value) in contract.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) { if (value.type.storage is not null || value.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Resource bindings cannot be merged or loop-carried as ordinary values."); + } values.Add(name, NewValue(value.type)); } return new ReadOnlyDictionary(values); @@ -158,7 +176,10 @@ private static void ValidateOutputs( IReadOnlyDictionary expected, IReadOnlyDictionary actual ) { - if (expected.Count != actual.Count || expected.Any(pair => !actual.TryGetValue(pair.Key, out ShaderIrValue? value) || !pair.Value.type.IsEquivalentTo(value.type))) + if (expected.Count != actual.Count + || expected.Any(pair => !actual.TryGetValue(pair.Key, out ShaderIrValue? value) || !pair.Value.type.IsEquivalentTo(value.type)) + ) { throw new ArgumentException("Control-flow regions require identical named output types."); + } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs index c98de6941..80d1b3d4c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs @@ -29,7 +29,7 @@ ShaderIrValue coordinate ) { ValidateSample(texture, coordinate); ShaderIrValue output = NewValue(ShaderSourceType.Atomic("float4")); - m_instructions.Add(new(ShaderIrOperation.TextureSample, [texture, coordinate], [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.TextureSample, [texture, coordinate], [output])); return output; } @@ -59,9 +59,11 @@ ShaderIrValue level ValidateSample(texture, coordinate); RequireOwned(level); if (!level.type.IsEquivalentTo(ShaderSourceType.Atomic("float"))) + { throw new ArgumentException("A mip level must be float.", nameof(level)); + } ShaderIrValue output = NewValue(ShaderSourceType.Atomic("float4")); - m_instructions.Add(new(ShaderIrOperation.TextureSampleLevel, [texture, coordinate, level], [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.TextureSampleLevel, [texture, coordinate, level], [output])); return output; } @@ -86,9 +88,11 @@ ShaderIrValue coordinate ) { ShaderStorageType storage = ValidateStorage(resource, coordinate); if (storage.access == RenderStorageAccess.Write) + { throw new ArgumentException("A write-only resource cannot be loaded.", nameof(resource)); + } ShaderIrValue output = NewValue(storage.valueType); - m_instructions.Add(new(ShaderIrOperation.StorageLoad, [resource, coordinate], [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.StorageLoad, [resource, coordinate], [output])); return output; } @@ -115,8 +119,10 @@ ShaderIrValue value ShaderStorageType storage = ValidateStorage(resource, coordinate); RequireOwned(value); if (storage.access == RenderStorageAccess.Read || !storage.valueType.IsEquivalentTo(value.type)) + { throw new ArgumentException("A store requires a writable resource and its exact element type.", nameof(resource)); - m_instructions.Add(new(ShaderIrOperation.StorageStore, [resource, coordinate, value], [])); + } + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.StorageStore, [resource, coordinate, value], [])); } /// @@ -145,11 +151,14 @@ ShaderIrValue value ShaderStorageType storage = ValidateStorage(resource, index); RequireOwned(value); if (storage.isImage || storage.access != RenderStorageAccess.ReadWrite - || !(storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("int")) || storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) - || !storage.valueType.IsEquivalentTo(value.type)) + || !(storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("int")) + || storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) + || !storage.valueType.IsEquivalentTo(value.type) + ) { throw new ArgumentException("Atomic add requires a read-write scalar integer buffer.", nameof(resource)); + } ShaderIrValue output = NewValue(storage.valueType); - m_instructions.Add(new(ShaderIrOperation.StorageAtomicAdd, [resource, index, value], [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.StorageAtomicAdd, [resource, index, value], [output])); return output; } @@ -166,8 +175,10 @@ public void Discard(ShaderIrValue condition) { RequireOwned(condition); if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool"))) + { throw new ArgumentException("Discard requires bool.", nameof(condition)); - m_instructions.Add(new(ShaderIrOperation.Discard, [condition], [])); + } + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Discard, [condition], [])); } private void ValidateSample( @@ -177,7 +188,9 @@ ShaderIrValue coordinate RequireOwned(texture); RequireOwned(coordinate); if (!texture.type.IsEquivalentTo(ShaderSourceType.Atomic(texture.type.id))) + { throw new ArgumentException("A sampled binding cannot be disguised as an aggregate.", nameof(texture)); + } string type = texture.type.id switch { "sampled-texture2d" => "float2", @@ -185,7 +198,9 @@ ShaderIrValue coordinate _ => throw new ArgumentException("Sampling requires a supported sampled texture type.", nameof(texture)) }; if (!coordinate.type.IsEquivalentTo(ShaderSourceType.Atomic(type))) + { throw new ArgumentException($"Sampling requires a {type} coordinate.", nameof(coordinate)); + } } private ShaderStorageType ValidateStorage( @@ -194,10 +209,15 @@ ShaderIrValue coordinate ) { RequireOwned(resource); RequireOwned(coordinate); - ShaderStorageType storage = resource.type.storage ?? throw new ArgumentException("A typed storage binding is required.", nameof(resource)); - string coordinateType = !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"; + ShaderStorageType storage = resource.type.storage + ?? throw new ArgumentException("A typed storage binding is required.", nameof(resource)); + string coordinateType = !storage.isImage + ? "uint" + : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"; if (!coordinate.type.IsEquivalentTo(ShaderSourceType.Atomic(coordinateType))) + { throw new ArgumentException($"This resource requires a {coordinateType} coordinate.", nameof(coordinate)); + } return storage; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs index 157000345..f0f8e941b 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs @@ -23,7 +23,10 @@ public sealed partial class ShaderIrBuilder /// /// Creates an independent typed region builder and value identity scope. /// - public ShaderIrBuilder() => m_root = this; + public ShaderIrBuilder() + { + m_root = this; + } private ShaderIrBuilder(ShaderIrBuilder parent) { @@ -52,18 +55,22 @@ ShaderSourceType type ) { EnsureWritable(); if (m_parent is not null) + { throw new InvalidOperationException("Stage inputs must be declared in the root region and captured by nested regions."); + } ArgumentException.ThrowIfNullOrWhiteSpace(name); RequireValueType(type); if (m_inputs.TryGetValue(name, out ShaderIrValue? previous)) { if (!type.IsEquivalentTo(previous.type)) + { throw new ArgumentException($"Input '{name}' changed type.", nameof(type)); + } return previous; } ShaderIrValue output = NewValue(type); m_inputs.Add(name, output); - m_instructions.Add(new(ShaderIrOperation.Input, [], [output], inputName: name)); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Input, [], [output], inputName: name)); return output; } @@ -82,7 +89,9 @@ ShaderSourceType type public ShaderIrValue Constant(float value) { if (!float.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Shader constants must be finite."); + } return ConstantBits("float", BitConverter.SingleToUInt32Bits(value)); } @@ -145,22 +154,26 @@ ShaderIrValue right RequireOwned(left); RequireOwned(right); if (!left.type.IsEquivalentTo(right.type)) + { throw new ArgumentException("Binary operands require identical types; conversions must be explicit.", nameof(right)); + } bool numeric = TryNumeric(left.type, out string scalar, out int columns, out int rows); bool scalarValue = columns == 1 && rows == 1; bool comparison = operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan; bool permitted = operation switch { ShaderIrOperation.Add or ShaderIrOperation.Subtract or ShaderIrOperation.Multiply or ShaderIrOperation.Divide - or ShaderIrOperation.Minimum or ShaderIrOperation.Maximum => numeric && scalar != "bool", + or ShaderIrOperation.Minimum or ShaderIrOperation.Maximum => numeric && scalar != "bool", ShaderIrOperation.Equal => numeric && scalarValue, ShaderIrOperation.LessThan => numeric && scalarValue && scalar != "bool", _ => false }; if (!permitted) + { throw new ArgumentException($"Operation '{operation}' is not defined for '{left.type.id}'.", nameof(operation)); + } ShaderIrValue output = NewValue(comparison ? ShaderSourceType.Atomic("bool") : left.type); - m_instructions.Add(new(operation, [left, right], [output])); + m_instructions.Add(new ShaderIrInstruction(operation, [left, right], [output])); return output; } @@ -191,11 +204,15 @@ ShaderIrValue whenFalse RequireOwned(whenTrue); RequireOwned(whenFalse); if (whenTrue.type.storage is not null || whenTrue.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Resource bindings cannot be selected as ordinary values.", nameof(whenTrue)); + } if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool")) || !whenTrue.type.IsEquivalentTo(whenFalse.type)) + { throw new ArgumentException("Selection requires a scalar bool and two values of identical type."); + } ShaderIrValue output = NewValue(whenTrue.type); - m_instructions.Add(new(ShaderIrOperation.Select, [condition, whenTrue, whenFalse], [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Select, [condition, whenTrue, whenFalse], [output])); return output; } @@ -221,23 +238,35 @@ params ShaderIrValue[] members RequireValueType(type); ArgumentNullException.ThrowIfNull(members); foreach (ShaderIrValue member in members) + { RequireOwned(member); + } ShaderSourceType[] expected; if (type.elementType is not null) + { expected = Enumerable.Repeat(type.elementType, type.elementCount).ToArray(); + } else if (type.fields.Count != 0) + { expected = type.fields.Select(static field => field.type).ToArray(); + } else if (TryNumeric(type, out string scalar, out int columns, out int rows) && columns * rows > 1) + { expected = Enumerable.Repeat(ShaderSourceType.Atomic(scalar), columns * rows).ToArray(); + } else + { throw new ArgumentException("Construction requires a vector, matrix, structure or array type.", nameof(type)); + } if (expected.Length != members.Length || expected.Where(( value, index - ) => !value.IsEquivalentTo(members[index].type)).Any()) + ) => !value.IsEquivalentTo(members[index].type)).Any() + ) { throw new ArgumentException("Aggregate members do not match the complete type layout.", nameof(members)); + } ShaderIrValue output = NewValue(type); - m_instructions.Add(new(ShaderIrOperation.Construct, members, [output])); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Construct, members, [output])); return output; } @@ -276,8 +305,7 @@ int memberIndex else if (type.fields.Count != 0) { count = type.fields.Count; - if (memberIndex >= count) - throw new ArgumentOutOfRangeException(nameof(memberIndex)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(memberIndex, count); memberType = type.fields[memberIndex].type; } else if (TryNumeric(type, out string scalar, out int columns, out int rows) && columns * rows > 1) @@ -286,11 +314,12 @@ int memberIndex memberType = ShaderSourceType.Atomic(rows == 1 ? scalar : scalar + rows); } else + { throw new ArgumentException("Extraction requires a vector, matrix, structure or array.", nameof(value)); - if (memberIndex >= count) - throw new ArgumentOutOfRangeException(nameof(memberIndex)); + } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(memberIndex, count); ShaderIrValue output = NewValue(memberType); - m_instructions.Add(new(ShaderIrOperation.Extract, [value], [output], memberIndex: memberIndex)); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Extract, [value], [output], memberIndex: memberIndex)); return output; } @@ -300,7 +329,7 @@ int memberIndex /// /// A module whose selected implementations and variants share the same interface. /// - /// + /// /// The exact implementation/configuration selected by the target. /// /// @@ -314,38 +343,56 @@ int memberIndex /// public IReadOnlyDictionary Call( ShaderSourceModuleAnalysis module, - string implementationId, + string implementationID, IReadOnlyDictionary inputs ) { EnsureWritable(); ArgumentNullException.ThrowIfNull(module); - ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); ArgumentNullException.ThrowIfNull(inputs); if (!module.succeeded) + { throw new ArgumentException("A source call requires a fully validated module interface.", nameof(module)); - ShaderSourceImplementationAnalysis source = module.implementations.FirstOrDefault(value => value.implementationId == implementationId) - ?? throw new ArgumentException($"Implementation '{implementationId}' is not part of this module.", nameof(implementationId)); + } + ShaderSourceImplementationAnalysis source = module.implementations.FirstOrDefault( + value => value.implementationID == implementationID + ) + ?? throw new ArgumentException($"Implementation '{implementationID}' is not part of this module.", nameof(implementationID)); ShaderSourceFunction function = source.analysis.function!; - ShaderSourceParameter[] parameters = function.parameters.Where(static value => value.direction != ShaderSourceParameterDirection.Output).ToArray(); + ShaderSourceParameter[] parameters = function.parameters + .Where(static value => value.direction != ShaderSourceParameterDirection.Output) + .ToArray(); if (parameters.Length != inputs.Count) + { throw new ArgumentException("Source inputs must match every input/inout parameter exactly.", nameof(inputs)); - var operands = new List(); + } + List operands = []; foreach (ShaderSourceParameter parameter in parameters) { if (!inputs.TryGetValue(parameter.name, out ShaderIrValue? value)) + { throw new ArgumentException($"Missing source input '{parameter.name}'.", nameof(inputs)); + } RequireOwned(value); if (!value.type.IsEquivalentTo(parameter.type)) + { throw new ArgumentException($"Source input '{parameter.name}' does not match its declared type.", nameof(inputs)); + } operands.Add(value); } var outputs = new Dictionary(StringComparer.Ordinal); if (function.returnType.id != "void") + { outputs.Add("return", NewValue(function.returnType)); + } foreach (ShaderSourceParameter parameter in function.parameters) + { if (parameter.direction != ShaderSourceParameterDirection.Input) + { outputs.Add("output." + parameter.name, NewValue(parameter.type)); - m_instructions.Add(new(ShaderIrOperation.SourceCall, operands, outputs.Values, source: source)); + } + } + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.SourceCall, operands, outputs.Values, source: source)); return new ReadOnlyDictionary(outputs); } @@ -372,12 +419,26 @@ public ShaderIrBlock Build(IReadOnlyDictionary outputs) return new(m_instructions, outputs); } + internal void RequireOwned(ShaderIrValue value) + { + EnsureWritable(); + ArgumentNullException.ThrowIfNull(value); + for (ShaderIrBuilder? scope = this; scope is not null; scope = scope.m_parent) + { + if (ReferenceEquals(value.owner, scope.m_owner)) + { + return; + } + } + throw new ArgumentException("The value is outside this region's visible scope.", nameof(value)); + } + private ShaderIrValue ConstantBits( string type, ulong bits ) { ShaderIrValue output = NewValue(ShaderSourceType.Atomic(type)); - m_instructions.Add(new(ShaderIrOperation.Constant, [], [output], constantBits: bits)); + m_instructions.Add(new ShaderIrInstruction(ShaderIrOperation.Constant, [], [output], constantBits: bits)); return output; } @@ -387,29 +448,25 @@ private ShaderIrValue NewValue(ShaderSourceType type) return new(m_owner, m_root.m_nextValue++, type); } - internal void RequireOwned(ShaderIrValue value) - { - EnsureWritable(); - ArgumentNullException.ThrowIfNull(value); - for (ShaderIrBuilder? scope = this; scope is not null; scope = scope.m_parent) - if (ReferenceEquals(value.owner, scope.m_owner)) - return; - throw new ArgumentException("The value is outside this region's visible scope.", nameof(value)); - } - private void EnsureWritable() { if (m_closed) + { throw new InvalidOperationException("A completed nested region cannot be edited after its callback returns."); + } if (m_buildingChild) + { throw new InvalidOperationException("An enclosing builder cannot be mutated while its nested region is being constructed."); + } } private static void RequireValueType(ShaderSourceType type) { ArgumentNullException.ThrowIfNull(type); if (type.id == "void") + { throw new ArgumentException("Void is not a value type.", nameof(type)); + } } private static bool TryNumeric( @@ -421,11 +478,15 @@ out int rows scalar = string.Empty; columns = rows = 1; if (type.elementType is not null || type.fields.Count != 0) + { return false; + } foreach (string name in new[] { "float", "int", "uint", "bool" }) { if (!type.id.StartsWith(name, StringComparison.Ordinal)) + { continue; + } ReadOnlySpan shape = type.id.AsSpan(name.Length); if (shape.Length == 0) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs new file mode 100644 index 000000000..4796610e5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores one immutable typed instruction without generated stage source or backend expressions. +/// +public sealed class ShaderIrInstruction +{ + internal ShaderIrInstruction( + ShaderIrOperation operation, + IEnumerable inputs, + IEnumerable outputs, + string? inputName = null, + ulong constantBits = 0, + int memberIndex = 0, + ShaderSourceImplementationAnalysis? source = null, + IEnumerable? regions = null + ) { + this.operation = operation; + this.inputs = Array.AsReadOnly(inputs.ToArray()); + this.outputs = Array.AsReadOnly(outputs.ToArray()); + this.inputName = inputName; + this.constantBits = constantBits; + this.memberIndex = memberIndex; + this.source = source; + this.regions = Array.AsReadOnly(regions?.ToArray() ?? []); + } + + /// + /// Gets the semantic operation independent of any source language. + /// + public ShaderIrOperation operation { get; } + + /// + /// Gets immutable operands in operation or function-declaration order. + /// + public IReadOnlyList inputs { get; } + + /// + /// Gets produced values; a call orders its return value first, then out/inout parameters. + /// + public IReadOnlyList outputs { get; } + + /// + /// Gets the stable interface or region-parameter identity, only for Input or RegionInput. + /// + public string? inputName { get; } + + /// + /// Gets exact scalar bits for a Constant instruction; the result type determines interpretation. + /// + public ulong constantBits { get; } + + /// + /// Gets the zero-based component/member/element ordinal for an Extract instruction. + /// + public int memberIndex { get; } + + /// + /// Gets a frozen, analyzed function implementation only for a SourceCall instruction. + /// + public ShaderSourceImplementationAnalysis? source { get; } + + /// + /// Gets immutable nested regions: true/false for Branch, or one body for Loop. + /// + public IReadOnlyList regions { get; } + + /// + /// Gets whether removing or reordering this instruction may change observable behavior. + /// + public bool hasSideEffects + => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad + or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard + or ShaderIrOperation.Branch or ShaderIrOperation.Loop; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs index e3116b7e4..db33911c3 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -46,7 +47,9 @@ void WriteBlock(ShaderIrBlock block) writer.Write((int)instruction.operation); writer.Write(instruction.inputs.Count); foreach (ShaderIrValue input in instruction.inputs) + { writer.Write(input.index); + } writer.Write(instruction.outputs.Count); foreach (ShaderIrValue output in instruction.outputs) { @@ -59,10 +62,12 @@ void WriteBlock(ShaderIrBlock block) writer.Write(instruction.source?.contentHash ?? string.Empty); writer.Write(instruction.regions.Count); foreach (ShaderIrBlock region in instruction.regions) + { WriteBlock(region); + } } writer.Write(block.outputs.Count); - foreach (var output in block.outputs.OrderBy(static value => value.Key, StringComparer.Ordinal)) + foreach (KeyValuePair output in block.outputs.OrderBy(static value => value.Key, StringComparer.Ordinal)) { writer.Write(output.Key); writer.Write(output.Value.index); @@ -75,7 +80,9 @@ void WriteType(ShaderSourceType type) writer.Write(type.elementCount); writer.Write(type.elementType is not null); if (type.elementType is not null) + { WriteType(type.elementType); + } writer.Write(type.fields.Count); foreach (ShaderSourceField field in type.fields) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs index c9912c7b7..34a963793 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs @@ -1,188 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Rendering; namespace Inno.Rendering.Shaders; -/// -/// Identifies the GPU interface through which a stage receives a value. -/// -public enum ShaderIrInputKind -{ - /// - /// A vertex stream attribute, including instance-rate streams. - /// - VertexAttribute, - /// - /// An interpolated value written by the preceding raster stage. - /// - Varying, - /// - /// A material, frame or draw uniform identified by a stable binding identity. - /// - Uniform, - /// - /// A sampled texture binding whose slot is assigned by target resource layout. - /// - SampledTexture, - /// - /// A typed storage buffer or image whose access, shape and layout are explicit. - /// - Storage, - /// - /// A standard GPU stage input identified by a target semantic, not native source text. - /// - Builtin -} - -/// -/// Identifies where a typed stage output is written. -/// -public enum ShaderIrOutputKind -{ - /// - /// The vertex position in homogeneous clip space. - /// - ClipPosition, - /// - /// A value interpolated for the next raster stage. - /// - Varying, - /// - /// A fragment color attachment at its explicit location. - /// - Color, - /// - /// The fragment depth value. - /// - Depth -} - -/// -/// Describes a stage input without embedding native declarations or expressions. -/// -public sealed class ShaderIrStageInput -{ - /// - /// Creates an immutable stage input binding. - /// - /// - /// Stable binding identity, also used by the block's named Input instruction. - /// - /// - /// Complete non-void type. - /// - /// - /// Source of the GPU value. - /// - /// - /// Target semantic, such as position, texcoord, color, instance-data or fragment-coordinate. - /// - /// - /// Attribute/semantic index or assigned texture slot, never a native handle. - /// - public ShaderIrStageInput( - string id, - ShaderSourceType type, - ShaderIrInputKind kind, - string semantic = "", - int location = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentNullException.ThrowIfNull(type); - ArgumentOutOfRangeException.ThrowIfNegative(location); - if (type.id == "void" || !Enum.IsDefined(kind)) - throw new ArgumentException("A stage input requires a value type and defined interface kind."); - if (kind == ShaderIrInputKind.SampledTexture && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null)) - throw new ArgumentException("A sampled texture binding requires an opaque atomic resource type.", nameof(type)); - if (kind is ShaderIrInputKind.VertexAttribute or ShaderIrInputKind.Varying or ShaderIrInputKind.Builtin) - ArgumentException.ThrowIfNullOrWhiteSpace(semantic); - this.id = id; - this.type = type; - this.kind = kind; - this.semantic = semantic; - this.location = location; - } - - /// - /// Gets the logical binding identity. - /// - public string id { get; } - /// - /// Gets the complete typed value received by the stage. - /// - public ShaderSourceType type { get; } - /// - /// Gets the GPU input category. - /// - public ShaderIrInputKind kind { get; } - /// - /// Gets the target semantic; an adapter must reject unsupported semantics. - /// - public string semantic { get; } - /// - /// Gets the target-assigned interface location or sampled-texture slot. - /// - public int location { get; } -} - -/// -/// Describes a named block output's GPU destination. -/// -public sealed class ShaderIrStageOutput -{ - /// - /// Creates an immutable stage output binding. - /// - /// - /// The exact name in the block's output map. - /// - /// - /// GPU output category. - /// - /// - /// Varying semantic matched by the next stage; otherwise empty. - /// - /// - /// Varying index or color attachment index. - /// - public ShaderIrStageOutput( - string id, - ShaderIrOutputKind kind, - string semantic = "", - int location = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentOutOfRangeException.ThrowIfNegative(location); - if (!Enum.IsDefined(kind)) - throw new ArgumentException("A stage output requires a defined destination kind.", nameof(kind)); - if (kind == ShaderIrOutputKind.Varying) - ArgumentException.ThrowIfNullOrWhiteSpace(semantic); - this.id = id; - this.kind = kind; - this.semantic = semantic; - this.location = location; - } - - /// - /// Gets the exact block output identity. - /// - public string id { get; } - /// - /// Gets the GPU output category. - /// - public ShaderIrOutputKind kind { get; } - /// - /// Gets the varying semantic, not native assignment syntax. - /// - public string semantic { get; } - /// - /// Gets the target-assigned varying or attachment index. - /// - public int location { get; } -} - /// /// Freezes a typed GPU stage and its explicit interface. It contains no main function, varying declarations or source expressions. /// Targets own stage/resource layout; adapters translate these semantics into their native language. @@ -226,9 +47,16 @@ public ShaderIrStage( ArgumentNullException.ThrowIfNull(inputs); ArgumentNullException.ThrowIfNull(outputs); if (stage is not (ShaderStage.Vertex or ShaderStage.Fragment or ShaderStage.Compute)) + { throw new ArgumentException("A single programmable stage is required.", nameof(stage)); - if (threadsX <= 0 || threadsY <= 0 || threadsZ <= 0 || (stage != ShaderStage.Compute && (threadsX != 1 || threadsY != 1 || threadsZ != 1))) + } + if (threadsX <= 0 + || threadsY <= 0 + || threadsZ <= 0 + || (stage != ShaderStage.Compute && (threadsX != 1 || threadsY != 1 || threadsZ != 1)) + ) { throw new ArgumentException("Workgroup dimensions must be positive and apply only to compute stages."); + } this.inputs = Array.AsReadOnly(inputs.ToArray()); this.outputs = Array.AsReadOnly(outputs.ToArray()); this.stage = stage; @@ -237,37 +65,44 @@ public ShaderIrStage( this.threadsY = threadsY; this.threadsZ = threadsZ; Validate(); - contentHash = ShaderIrSemanticHash.Compute(this); + this.contentHash = ShaderIrSemanticHash.Compute(this); } /// /// Gets the programmable stage. /// public ShaderStage stage { get; } + /// /// Gets its immutable ordered instructions. /// public ShaderIrBlock body { get; } + /// /// Gets all input bindings. /// public IReadOnlyList inputs { get; } + /// /// Gets all output destinations. /// public IReadOnlyList outputs { get; } + /// /// Gets the compute workgroup X size. /// public int threadsX { get; } + /// /// Gets the compute workgroup Y size. /// public int threadsY { get; } + /// /// Gets the compute workgroup Z size. /// public int threadsZ { get; } + /// /// Gets a deterministic hash of stage semantics, ordered effects, nested regions, complete types, resource layout and frozen sources. /// A compiled artifact cache must additionally include toolchain identity, target capabilities, optimization and variant configuration. @@ -282,25 +117,41 @@ private void Validate() { ArgumentNullException.ThrowIfNull(input); if (!bindings.TryAdd(input.id, input)) + { throw new ArgumentException($"Duplicate stage input '{input.id}'."); + } if ((input.type.storage is not null) != (input.kind == ShaderIrInputKind.Storage)) + { throw new ArgumentException("Storage types require storage bindings, and storage bindings require complete storage types."); + } string semantic = input.kind is ShaderIrInputKind.SampledTexture or ShaderIrInputKind.Storage ? string.Empty : input.semantic; if (input.kind != ShaderIrInputKind.Uniform && !occupied.Add((input.kind, semantic, input.location))) + { throw new ArgumentException($"Two stage inputs alias the same {input.kind} location."); + } if ((input.kind == ShaderIrInputKind.VertexAttribute && stage != ShaderStage.Vertex) - || (input.kind == ShaderIrInputKind.Varying && stage != ShaderStage.Fragment)) + || (input.kind == ShaderIrInputKind.Varying && stage != ShaderStage.Fragment) + ) { throw new ArgumentException($"{input.kind} is not an input of the {stage} stage."); + } } ShaderIrInstruction[] reads = body.instructions.Where(static value => value.operation == ShaderIrOperation.Input).ToArray(); if (reads.Length != bindings.Count) + { throw new ArgumentException("The stage interface must describe exactly every body input."); + } foreach (ShaderIrInstruction read in reads) + { if (!bindings.TryGetValue(read.inputName!, out ShaderIrStageInput? input) || !input.type.IsEquivalentTo(read.outputs[0].type)) + { throw new ArgumentException($"Stage input '{read.inputName}' has a missing or incompatible binding."); + } + } if (stage != ShaderStage.Fragment && RequiresFragment(body)) + { throw new ArgumentException("Implicit-derivative texture sampling and discard are fragment-only operations."); + } var names = new HashSet(StringComparer.Ordinal); var destinations = new HashSet<(ShaderIrOutputKind, string, int)>(); @@ -308,28 +159,105 @@ private void Validate() { ArgumentNullException.ThrowIfNull(output); if (!names.Add(output.id) || !destinations.Add((output.kind, output.semantic, output.location))) + { throw new ArgumentException("Stage output identities and destinations must be unique."); + } if (!body.outputs.TryGetValue(output.id, out ShaderIrValue? value)) + { throw new ArgumentException($"Missing body output '{output.id}'."); + } bool vertexOutput = output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Varying; if (stage == ShaderStage.Compute || vertexOutput != (stage == ShaderStage.Vertex)) + { throw new ArgumentException($"{output.kind} is not an output of the {stage} stage."); - if (output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Color && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float4"))) + } + if (output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Color + && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float4")) + ) { throw new ArgumentException($"{output.kind} requires float4."); + } if (output.kind == ShaderIrOutputKind.Depth && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float"))) + { throw new ArgumentException("Depth requires float."); - if (output.kind is ShaderIrOutputKind.Depth or ShaderIrOutputKind.ClipPosition && (output.location != 0 || output.semantic.Length != 0)) + } + if (output.kind is ShaderIrOutputKind.Depth or ShaderIrOutputKind.ClipPosition + && (output.location != 0 || output.semantic.Length != 0) + ) { throw new ArgumentException("Position and depth have exactly one fixed destination."); + } if (output.kind == ShaderIrOutputKind.Color && output.semantic.Length != 0) + { throw new ArgumentException("Color attachments are addressed only by location."); + } } if (names.Count != body.outputs.Count) + { throw new ArgumentException("Every body output requires a GPU destination."); + } if (stage == ShaderStage.Vertex && !outputs.Any(static value => value.kind == ShaderIrOutputKind.ClipPosition)) + { throw new ArgumentException("A vertex stage must write clip position."); + } } private static bool RequiresFragment(ShaderIrBlock block) - => block.instructions.Any(static instruction => instruction.operation is ShaderIrOperation.TextureSample or ShaderIrOperation.Discard - || instruction.regions.Any(RequiresFragment)); + => block.instructions.Any(static instruction => ( + instruction.operation is ShaderIrOperation.TextureSample + or ShaderIrOperation.Discard + || instruction.regions.Any(RequiresFragment) + )); +} + +/// +/// Identifies the GPU interface through which a stage receives a value. +/// +public enum ShaderIrInputKind +{ + /// + /// A vertex stream attribute, including instance-rate streams. + /// + VertexAttribute, + /// + /// An interpolated value written by the preceding raster stage. + /// + Varying, + /// + /// A material, frame or draw uniform identified by a stable binding identity. + /// + Uniform, + /// + /// A sampled texture binding whose slot is assigned by target resource layout. + /// + SampledTexture, + /// + /// A typed storage buffer or image whose access, shape and layout are explicit. + /// + Storage, + /// + /// A standard GPU stage input identified by a target semantic, not native source text. + /// + Builtin +} + +/// +/// Identifies where a typed stage output is written. +/// +public enum ShaderIrOutputKind +{ + /// + /// The vertex position in homogeneous clip space. + /// + ClipPosition, + /// + /// A value interpolated for the next raster stage. + /// + Varying, + /// + /// A fragment color attachment at its explicit location. + /// + Color, + /// + /// The fragment depth value. + /// + Depth } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs new file mode 100644 index 000000000..b37e5afbe --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs @@ -0,0 +1,82 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes a stage input without embedding native declarations or expressions. +/// +public sealed class ShaderIrStageInput +{ + /// + /// Creates an immutable stage input binding. + /// + /// + /// Stable binding identity, also used by the block's named Input instruction. + /// + /// + /// Complete non-void type. + /// + /// + /// Source of the GPU value. + /// + /// + /// Target semantic, such as position, texcoord, color, instance-data or fragment-coordinate. + /// + /// + /// Attribute/semantic index or assigned texture slot, never a native handle. + /// + public ShaderIrStageInput( + string id, + ShaderSourceType type, + ShaderIrInputKind kind, + string semantic = "", + int location = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(type); + ArgumentOutOfRangeException.ThrowIfNegative(location); + if (type.id == "void" || !Enum.IsDefined(kind)) + { + throw new ArgumentException("A stage input requires a value type and defined interface kind."); + } + if (kind == ShaderIrInputKind.SampledTexture + && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null) + ) { + throw new ArgumentException("A sampled texture binding requires an opaque atomic resource type.", nameof(type)); + } + if (kind is ShaderIrInputKind.VertexAttribute or ShaderIrInputKind.Varying or ShaderIrInputKind.Builtin) + { + ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } + this.id = id; + this.type = type; + this.kind = kind; + this.semantic = semantic; + this.location = location; + } + + /// + /// Gets the logical binding identity. + /// + public string id { get; } + + /// + /// Gets the complete typed value received by the stage. + /// + public ShaderSourceType type { get; } + + /// + /// Gets the GPU input category. + /// + public ShaderIrInputKind kind { get; } + + /// + /// Gets the target semantic; an adapter must reject unsupported semantics. + /// + public string semantic { get; } + + /// + /// Gets the target-assigned interface location or sampled-texture slot. + /// + public int location { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs new file mode 100644 index 000000000..d15e6e1d3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs @@ -0,0 +1,66 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes a named block output's GPU destination. +/// +public sealed class ShaderIrStageOutput +{ + /// + /// Creates an immutable stage output binding. + /// + /// + /// The exact name in the block's output map. + /// + /// + /// GPU output category. + /// + /// + /// Varying semantic matched by the next stage; otherwise empty. + /// + /// + /// Varying index or color attachment index. + /// + public ShaderIrStageOutput( + string id, + ShaderIrOutputKind kind, + string semantic = "", + int location = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentOutOfRangeException.ThrowIfNegative(location); + if (!Enum.IsDefined(kind)) + { + throw new ArgumentException("A stage output requires a defined destination kind.", nameof(kind)); + } + if (kind == ShaderIrOutputKind.Varying) + { + ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } + this.id = id; + this.kind = kind; + this.semantic = semantic; + this.location = location; + } + + /// + /// Gets the exact block output identity. + /// + public string id { get; } + + /// + /// Gets the GPU output category. + /// + public ShaderIrOutputKind kind { get; } + + /// + /// Gets the varying semantic, not native assignment syntax. + /// + public string semantic { get; } + + /// + /// Gets the target-assigned varying or attachment index. + /// + public int location { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs new file mode 100644 index 000000000..e8e7ff30a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs @@ -0,0 +1,29 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Identifies a typed single-assignment value within one intermediate block. +/// +public sealed class ShaderIrValue +{ + internal ShaderIrValue( + object owner, + int index, + ShaderSourceType type + ) { + this.owner = owner; + this.index = index; + this.type = type; + } + + /// + /// Gets the deterministic block-local value index, not a GPU register or resource slot. + /// + public int index { get; } + + /// + /// Gets the complete language-independent value type. + /// + public ShaderSourceType type { get; } + + internal object owner { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs index 672891cd0..2f283379c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs @@ -16,7 +16,9 @@ private ShaderStorageType( bool array ) { if (!Enum.IsDefined(access)) + { throw new ArgumentOutOfRangeException(nameof(access)); + } this.valueType = valueType; this.access = access; this.format = format; @@ -28,27 +30,45 @@ bool array /// Gets the buffer element or image load/store value type; image operations use float4. /// public ShaderSourceType valueType { get; } + /// /// Gets the permitted memory access, independent of Render Graph scheduling. /// public RenderStorageAccess access { get; } + /// /// Gets the exact storage image format, or null for a structured buffer. /// public RenderTextureFormat? format { get; } + /// /// Gets the image dimension; ignored for buffers. /// public RenderTextureDimension dimension { get; } + /// /// Gets whether a two-dimensional storage image has array layers. /// public bool array { get; } + /// /// Gets whether this descriptor denotes an image rather than a structured buffer. /// public bool isImage => format.HasValue; + /// + /// Compares complete access, format, shape and element layout contracts. + /// + /// + /// Candidate resource description. + /// + /// + /// True only when both bindings permit exactly the same operations and values. + /// + public bool IsEquivalentTo(ShaderStorageType? other) + => other is not null && access == other.access && format == other.format && dimension == other.dimension + && array == other.array && valueType.IsEquivalentTo(other.valueType); + /// /// Creates a structured storage buffer with an explicit element layout. /// @@ -100,33 +120,32 @@ public static ShaderStorageType Image( RenderTextureDimension dimension = RenderTextureDimension.Texture2D, bool array = false ) { - if (!Enum.IsDefined(format) || format is RenderTextureFormat.RGBA8Srgb or RenderTextureFormat.Depth24Stencil8 or RenderTextureFormat.Depth32Float) + if (!Enum.IsDefined(format) + || format is RenderTextureFormat.RGBA8Srgb or RenderTextureFormat.Depth24Stencil8 or RenderTextureFormat.Depth32Float + ) { throw new ArgumentException("A storage image requires a linear color format.", nameof(format)); - if (dimension is not (RenderTextureDimension.Texture2D or RenderTextureDimension.Texture3D) || (array && dimension != RenderTextureDimension.Texture2D)) + } + if (dimension is not (RenderTextureDimension.Texture2D or RenderTextureDimension.Texture3D) + || (array && dimension != RenderTextureDimension.Texture2D) + ) { throw new ArgumentException("Storage images support 2D, 2D array or 3D shapes.", nameof(dimension)); + } return new(ShaderSourceType.Atomic("float4"), access, format, dimension, array); } - /// - /// Compares complete access, format, shape and element layout contracts. - /// - /// - /// Candidate resource description. - /// - /// - /// True only when both bindings permit exactly the same operations and values. - /// - public bool IsEquivalentTo(ShaderStorageType? other) - => other is not null && access == other.access && format == other.format && dimension == other.dimension - && array == other.array && valueType.IsEquivalentTo(other.valueType); - private static void ValidateElement(ShaderSourceType type) { if (type.id == "void" || type.storage is not null || type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Storage elements cannot contain void or resource handles."); + } if (type.elementType is not null) + { ValidateElement(type.elementType); + } foreach (ShaderSourceField field in type.fields) + { ValidateElement(field.type); + } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs index 34b064e35..40f261012 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs @@ -1,10 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Inno.Core.Diagnostics; namespace Inno.Rendering.Shaders; +/// +/// Parses one source language into canonical function interfaces; it does not create GPU objects. +/// +public interface IShaderSourceFrontend +{ + /// + /// Gets the open source language identity, distinct from a rendering backend or GPU API. + /// + string languageID { get; } + + /// + /// Analyzes an immutable source candidate with explicit preprocessing inputs. + /// + /// + /// Source, selected function, dependencies, and target inputs. + /// + /// + /// A successful interface or a recoverable set of original-source diagnostics. + /// + ShaderSourceAnalysis Analyze(ShaderSourceRequest request); +} + /// /// Identifies an original source position, not a generated temporary compiler filename. /// @@ -58,146 +77,3 @@ public sealed record ShaderSourceFile( string assetPath, string text ); - -/// -/// Reads dependencies only from the current source candidate and records their import dependencies. -/// -public interface IShaderSourceResolver -{ - /// - /// Resolves and reads an include without bypassing asset mount permissions. - /// - /// - /// Resolved path of the including source. - /// - /// - /// Source-local include spelling. - /// - /// - /// A resolved immutable source snapshot. - /// - ShaderSourceFile ReadInclude( - string includingFile, - string include - ); -} - -/// -/// Carries the immutable inputs required to execute one shader source request. -/// -public sealed class ShaderSourceRequest -{ - /// - /// Creates an analysis request for an explicitly selected function. - /// - /// - /// Root source snapshot. - /// - /// - /// The one public function selected by source import settings. - /// - /// - /// Candidate-scoped include resolver. - /// - /// - /// Target and variant preprocessing inputs, or null for no defines. - /// - public ShaderSourceRequest( - ShaderSourceFile source, - string entryPoint, - IShaderSourceResolver resolver, - IReadOnlyDictionary? defines = null - ) { - this.source = source ?? throw new ArgumentNullException(nameof(source)); - ArgumentException.ThrowIfNullOrWhiteSpace(source.assetPath); - ArgumentNullException.ThrowIfNull(source.text); - ArgumentException.ThrowIfNullOrWhiteSpace(entryPoint); - this.entryPoint = entryPoint; - this.resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); - this.defines = new System.Collections.ObjectModel.ReadOnlyDictionary( - defines is null ? new Dictionary(StringComparer.Ordinal) : new Dictionary(defines, StringComparer.Ordinal)); - } - /// - /// Gets the root source snapshot. - /// - public ShaderSourceFile source { get; } - /// - /// Gets the explicitly selected export function name. - /// - public string entryPoint { get; } - /// - /// Gets the candidate-scoped dependency resolver. - /// - public IShaderSourceResolver resolver { get; } - /// - /// Gets immutable preprocessing inputs included in analysis cache identity. - /// - public IReadOnlyDictionary defines { get; } -} - -/// -/// Returns a recoverable source analysis result and complete original-source dependencies. -/// -public sealed class ShaderSourceAnalysis -{ - /// - /// Captures a completed analysis without retaining compiler objects. - /// - /// - /// Parsed interface, or null when parsing failed. - /// - /// - /// Resolved included sources, excluding the root. - /// - /// - /// All problems discovered by the frontend. - /// - public ShaderSourceAnalysis( - ShaderSourceFunction? function, - IEnumerable dependencies, - IEnumerable diagnostics - ) { - ArgumentNullException.ThrowIfNull(dependencies); - ArgumentNullException.ThrowIfNull(diagnostics); - this.function = function; - this.dependencies = Array.AsReadOnly(dependencies.Distinct(StringComparer.Ordinal).ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - /// - /// Gets the parsed interface, or null after an analysis failure. - /// - public ShaderSourceFunction? function { get; } - /// - /// Gets original source dependencies for invalidation. - /// - public IReadOnlyList dependencies { get; } - /// - /// Gets immutable, provider-neutral diagnostics. - /// - public IReadOnlyList diagnostics { get; } - /// - /// Gets whether a usable interface was found without errors. - /// - public bool succeeded => function is not null && !diagnostics.Any(static item => item.severity == DiagnosticSeverity.Error); -} - -/// -/// Parses one source language into canonical function interfaces; it does not create GPU objects. -/// -public interface IShaderSourceFrontend -{ - /// - /// Gets the open source language identity, distinct from a rendering backend or GPU API. - /// - string languageId { get; } - /// - /// Analyzes an immutable source candidate with explicit preprocessing inputs. - /// - /// - /// Source, selected function, dependencies, and target inputs. - /// - /// - /// A successful interface or a recoverable set of original-source diagnostics. - /// - ShaderSourceAnalysis Analyze(ShaderSourceRequest request); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs new file mode 100644 index 000000000..6e684e79a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs @@ -0,0 +1,24 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Reads dependencies only from the current source candidate and records their import dependencies. +/// +public interface IShaderSourceResolver +{ + /// + /// Resolves and reads an include without bypassing asset mount permissions. + /// + /// + /// Resolved path of the including source. + /// + /// + /// Source-local include spelling. + /// + /// + /// A resolved immutable source snapshot. + /// + ShaderSourceFile ReadInclude( + string includingFile, + string include + ); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs new file mode 100644 index 000000000..8cb05b6e9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering.Shaders; + +/// +/// Returns a recoverable source analysis result and complete original-source dependencies. +/// +public sealed class ShaderSourceAnalysis +{ + /// + /// Captures a completed analysis without retaining compiler objects. + /// + /// + /// Parsed interface, or null when parsing failed. + /// + /// + /// Resolved included sources, excluding the root. + /// + /// + /// All problems discovered by the frontend. + /// + public ShaderSourceAnalysis( + ShaderSourceFunction? function, + IEnumerable dependencies, + IEnumerable diagnostics + ) { + ArgumentNullException.ThrowIfNull(dependencies); + ArgumentNullException.ThrowIfNull(diagnostics); + this.function = function; + this.dependencies = Array.AsReadOnly(dependencies.Distinct(StringComparer.Ordinal).ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the parsed interface, or null after an analysis failure. + /// + public ShaderSourceFunction? function { get; } + + /// + /// Gets original source dependencies for invalidation. + /// + public IReadOnlyList dependencies { get; } + + /// + /// Gets immutable, provider-neutral diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a usable interface was found without errors. + /// + public bool succeeded => function is not null && !diagnostics.Any(static item => item.severity == DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs new file mode 100644 index 000000000..a0afa5445 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs @@ -0,0 +1,45 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes one immutable named structure field. +/// +public sealed class ShaderSourceField +{ + /// + /// Creates a structure field. + /// + /// + /// Stable field name. + /// + /// + /// Complete field type. + /// + /// + /// The field has void type or is an opaque storage binding. + /// + public ShaderSourceField( + string name, + ShaderSourceType type + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(type); + if (type.id == "void" || type.storage is not null) + { + throw new ArgumentException("A structure field cannot have void type or contain an opaque storage binding.", nameof(type)); + } + this.name = name; + this.type = type; + } + + /// + /// Gets the public field name. + /// + public string name { get; } + + /// + /// Gets the complete field type. + /// + public ShaderSourceType type { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs index 55139e46f..6d80d03cb 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs @@ -26,22 +26,25 @@ public ShaderSourceFrontendCatalog(IEnumerable frontends) { ArgumentNullException.ThrowIfNull(frontends); foreach (IShaderSourceFrontend frontend in frontends) - if (frontend is null || string.IsNullOrWhiteSpace(frontend.languageId) || - !m_frontends.TryAdd(frontend.languageId, frontend)) + { + if (frontend is null || string.IsNullOrWhiteSpace(frontend.languageID) + || !m_frontends.TryAdd(frontend.languageID, frontend) + ) { throw new ArgumentException("Source frontends require unique, assigned language IDs.", nameof(frontends)); - languageIds = new ReadOnlyCollection(new List(m_frontends.Keys)); + } + } + this.languageIDs = new ReadOnlyCollection([.. m_frontends.Keys]); } + /// /// Gets registered language identities for source import settings. /// - public IReadOnlyList languageIds { get; } - - internal IEnumerable providers => m_frontends.Values; + public IReadOnlyList languageIDs { get; } /// /// Analyzes source using an explicitly selected language. /// - /// + /// /// Registered language identity, never inferred from the active graphics API. /// /// @@ -54,14 +57,14 @@ public ShaderSourceFrontendCatalog(IEnumerable frontends) /// The requested language provider is unavailable. /// public ShaderSourceAnalysis Analyze( - string languageId, + string languageID, ShaderSourceRequest request ) { - ArgumentException.ThrowIfNullOrWhiteSpace(languageId); + ArgumentException.ThrowIfNullOrWhiteSpace(languageID); ArgumentNullException.ThrowIfNull(request); - return m_frontends.TryGetValue(languageId, out IShaderSourceFrontend? frontend) - ? frontend.Analyze(request) - : throw new NotSupportedException($"Shader source language '{languageId}' is unavailable."); + return m_frontends.TryGetValue(languageID, out IShaderSourceFrontend? frontend) + ? frontend.Analyze(request) + : throw new NotSupportedException($"Shader source language '{languageID}' is unavailable."); } /// @@ -80,50 +83,85 @@ public ShaderSourceModuleAnalysis AnalyzeModule(IEnumerable value is null) || - requests.Select(static value => value.implementationId).Distinct(StringComparer.Ordinal).Count() != requests.Length) + if (requests.Length == 0 || requests.Any(static value => value is null) + || requests.Select(static value => value.implementationID).Distinct(StringComparer.Ordinal).Count() != requests.Length + ) { throw new ArgumentException("A module requires unique, assigned implementation/configuration IDs.", nameof(implementations)); + } - var results = new List(); - var diagnostics = new List(); + List results = []; + List diagnostics = []; ShaderSourceFunction? common = null; - string? commonId = null; - foreach (ShaderSourceImplementationRequest request in requests.OrderBy(static value => value.implementationId, StringComparer.Ordinal)) - { + string? commonID = null; + foreach (ShaderSourceImplementationRequest request in requests.OrderBy( + static value => value.implementationID, + StringComparer.Ordinal + )) { var resolver = new ShaderSourceSnapshotResolver(request.source); ShaderSourceAnalysis analysis; - if (!m_frontends.TryGetValue(request.languageId, out IShaderSourceFrontend? frontend)) - analysis = new(null, [], [new("SHADER_SOURCE_LANGUAGE_MISSING", DiagnosticSeverity.Error, - $"Implementation '{request.implementationId}' requires unavailable language '{request.languageId}'.", - new(request.source.source.assetPath, 1, 1))]); + if (!m_frontends.TryGetValue(request.languageID, out IShaderSourceFrontend? frontend)) + { + analysis = new(null, [], [new ShaderSourceDiagnostic( + "SHADER_SOURCE_LANGUAGE_MISSING", + DiagnosticSeverity.Error, + $"Implementation '{request.implementationID}' requires unavailable language '{request.languageID}'.", + new ShaderSourcePosition(request.source.source.assetPath, 1, 1) + )]); + } else { - analysis = frontend.Analyze(new(request.source.source, request.source.entryPoint, resolver, request.source.defines)) - ?? throw new InvalidOperationException($"Language '{request.languageId}' returned no source analysis."); + analysis = frontend.Analyze( + new ShaderSourceRequest(request.source.source, request.source.entryPoint, resolver, request.source.defines) + ) + ?? throw new InvalidOperationException($"Language '{request.languageID}' returned no source analysis."); var paths = new HashSet(resolver.files.Select(static file => file.assetPath), StringComparer.Ordinal); string[] uncaptured = analysis.dependencies.Where(path => !paths.Contains(path)).ToArray(); if (analysis.succeeded && uncaptured.Length != 0) - analysis = new(analysis.function, analysis.dependencies, analysis.diagnostics.Concat( - uncaptured.Select(path => new ShaderSourceDiagnostic("SHADER_SOURCE_DEPENDENCY_UNCAPTURED", DiagnosticSeverity.Error, - $"Language '{request.languageId}' reported dependency '{path}' without reading it through the source resolver.", - new(request.source.source.assetPath, 1, 1))))); - analysis = new(analysis.function, - analysis.dependencies.Concat(paths.Where(path => path != request.source.source.assetPath)), analysis.diagnostics); + { + analysis = new( + analysis.function, + analysis.dependencies, + analysis.diagnostics.Concat( + uncaptured.Select(path => new ShaderSourceDiagnostic( + "SHADER_SOURCE_DEPENDENCY_UNCAPTURED", + DiagnosticSeverity.Error, + $"Language '{request.languageID}' reported dependency '{path}' without reading it through the source resolver.", + new ShaderSourcePosition(request.source.source.assetPath, 1, 1) + )) + ) + ); + } + analysis = new( + analysis.function, + analysis.dependencies.Concat(paths.Where(path => path != request.source.source.assetPath)), + analysis.diagnostics + ); } - results.Add(new(request, analysis, resolver.files, resolver.includes)); + results.Add(new ShaderSourceImplementationAnalysis(request, analysis, resolver.files, resolver.includes)); diagnostics.AddRange(analysis.diagnostics); if (!analysis.succeeded) + { continue; + } if (common is null) { common = analysis.function; - commonId = request.implementationId; + commonID = request.implementationID; } else if (!common.HasSameInterface(analysis.function)) - diagnostics.Add(new("SHADER_SOURCE_IMPLEMENTATION_INTERFACE", DiagnosticSeverity.Error, - $"Implementation '{request.implementationId}' does not match '{commonId}': public parameter names, directions, order and complete value types must agree.", - analysis.function!.location)); + { + diagnostics.Add( + new ShaderSourceDiagnostic( + "SHADER_SOURCE_IMPLEMENTATION_INTERFACE", + DiagnosticSeverity.Error, + $"Implementation '{request.implementationID}' does not match '{commonID}': public parameter names, directions, order and complete value types must agree.", + analysis.function!.location + ) + ); + } } return new(results, diagnostics); } + + internal IEnumerable providers => m_frontends.Values; } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs index d4280afd7..9daea9352 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Types; namespace Inno.Rendering.Shaders; @@ -19,24 +18,28 @@ public sealed class ShaderSourceFrontendRegistry : TypeRegistry /// The owner type catalog; it must outlive this registry. /// - public ShaderSourceFrontendRegistry(TypeCatalog types) : base(types) => m_types = types; + public ShaderSourceFrontendRegistry(TypeCatalog types) + : base(types) + { + m_types = types; + } /// /// Gets immutable language identities available in the current generation. /// - public IReadOnlyList languageIds + public IReadOnlyList languageIDs { get { using IDisposable operation = m_types.AcquireOperation("Query shader source languages"); - return current.languageIds; + return current.languageIDs; } } /// /// Analyzes source while preventing provider retirement for the complete synchronous operation. /// - /// + /// /// The exact registered language identity. /// /// @@ -49,11 +52,11 @@ public IReadOnlyList languageIds /// The language is not available in the current generation. /// public ShaderSourceAnalysis Analyze( - string languageId, + string languageID, ShaderSourceRequest request ) { using IDisposable operation = m_types.AcquireOperation("Analyze shader source interface"); - return current.Analyze(languageId, request); + return current.Analyze(languageID, request); } /// @@ -85,11 +88,13 @@ public ShaderSourceModuleAnalysis AnalyzeModule(IEnumerable protected override ShaderSourceFrontendCatalog Build(TypeCacheSnapshot types) { - var providers = new List(); + List providers = []; foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { providers.Add(CreateExtension(type)); + } return new ShaderSourceFrontendCatalog(providers); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs index 5645b1fce..3a03a9b7f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs @@ -4,73 +4,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Declares value flow across a source function parameter. -/// -public enum ShaderSourceParameterDirection -{ - /// - /// The caller supplies a value. - /// - Input, - /// - /// The function produces a value. - /// - Output, - /// - /// The caller supplies a value and the function produces its replacement. - /// - InputOutput -} - -/// -/// Describes one parameter parsed from a public source declaration. -/// -public sealed class ShaderSourceParameter -{ - /// - /// Creates a validated function parameter. - /// - /// - /// Public parameter name, used for semantic port matching rather than ordinal matching. - /// - /// - /// Canonical value type. - /// - /// - /// Declared value flow. - /// - /// - /// The parameter has void type. - /// - public ShaderSourceParameter( - string name, - ShaderSourceType type, - ShaderSourceParameterDirection direction - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - if (!Enum.IsDefined(direction)) - throw new ArgumentOutOfRangeException(nameof(direction)); - if (type?.id == "void") - throw new ArgumentException("A parameter cannot have void type.", nameof(type)); - this.name = name; - this.type = type ?? throw new ArgumentNullException(nameof(type)); - this.direction = direction; - } - /// - /// Gets the public parameter name. - /// - public string name { get; } - /// - /// Gets the complete canonical value type. - /// - public ShaderSourceType type { get; } - /// - /// Gets the declared value flow. - /// - public ShaderSourceParameterDirection direction { get; } -} - /// /// Contains the single callable interface exported by a source asset. /// @@ -101,30 +34,39 @@ public ShaderSourceFunction( ShaderSourcePosition location ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(returnType); ArgumentNullException.ThrowIfNull(parameters); if (name == "main") + { throw new ArgumentException("A source module exports a function, not a shader main entry point.", nameof(name)); + } ShaderSourceParameter[] snapshot = parameters.ToArray(); - if (snapshot.Any(static parameter => parameter is null) || - snapshot.Select(static parameter => parameter.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length) + if (snapshot.Any(static parameter => parameter is null) + || snapshot.Select(static parameter => parameter.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length + ) { throw new ArgumentException("A function requires unique parameter names.", nameof(parameters)); + } this.name = name; - this.returnType = returnType ?? throw new ArgumentNullException(nameof(returnType)); + this.returnType = returnType; this.parameters = Array.AsReadOnly(snapshot); this.location = location; } + /// /// Gets the implementation function name. /// public string name { get; } + /// /// Gets the canonical result type. /// public ShaderSourceType returnType { get; } + /// /// Gets the immutable function parameters. /// public IReadOnlyList parameters { get; } + /// /// Gets the original declaration position. /// @@ -142,11 +84,17 @@ ShaderSourcePosition location public bool HasSameInterface(ShaderSourceFunction? other) { if (other is null || !returnType.IsEquivalentTo(other.returnType) || parameters.Count != other.parameters.Count) + { return false; + } for (int i = 0; i < parameters.Count; i++) - if (parameters[i].name != other.parameters[i].name || parameters[i].direction != other.parameters[i].direction || - !parameters[i].type.IsEquivalentTo(other.parameters[i].type)) + { + if (parameters[i].name != other.parameters[i].name || parameters[i].direction != other.parameters[i].direction + || !parameters[i].type.IsEquivalentTo(other.parameters[i].type) + ) { return false; + } + } return true; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs new file mode 100644 index 000000000..e1c9dc1b6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes a parsed implementation and its complete source inputs without retaining a frontend or resolver. +/// +public sealed class ShaderSourceImplementationAnalysis +{ + internal ShaderSourceImplementationAnalysis( + ShaderSourceImplementationRequest request, + ShaderSourceAnalysis analysis, + IEnumerable files, + IEnumerable includes + ) { + this.implementationID = request.implementationID; + this.languageID = request.languageID; + this.sourcePath = request.source.source.assetPath; + this.entryPoint = request.source.entryPoint; + this.defines = request.source.defines; + this.analysis = analysis; + this.sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); + this.includes = Array.AsReadOnly( + includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) + .ThenBy(static edge => edge.include, StringComparer.Ordinal) + .ToArray() + ); + this.contentHash = ComputeContentHash(); + } + + /// + /// Gets the stable implementation/configuration key. + /// + public string implementationID { get; } + + /// + /// Gets the selected source language. + /// + public string languageID { get; } + + /// + /// Gets the root source path in the frozen source set. + /// + public string sourcePath { get; } + + /// + /// Gets the implementation's selected callable function name. + /// + public string entryPoint { get; } + + /// + /// Gets the immutable preprocessing inputs used for this implementation. + /// + public IReadOnlyDictionary defines { get; } + + /// + /// Gets every successfully read source, including the root, ordered by path. + /// + public IReadOnlyList sources { get; } + + /// + /// Gets the original resolver's frozen include edges, including aliases and mounted source paths. + /// + public IReadOnlyList includes { get; } + + /// + /// Gets the parsed interface and implementation-local diagnostics. + /// + public ShaderSourceAnalysis analysis { get; } + + /// + /// Gets a deterministic source-input hash. A compiler cache must additionally include its toolchain, + /// target, graph semantics and binding layout; this hash alone is not a compiled artifact key. + /// + public string contentHash { get; } + + /// + /// Recreates a compiler input backed only by immutable captured sources and resolution edges. + /// + /// + /// A request with no filesystem access or reference to the original frontend, resolver or generation. + /// + public ShaderSourceRequest CreateSourceRequest() + => new(sources.Single(file => file.assetPath == sourcePath), entryPoint, new FrozenResolver(sources, includes), defines); + + private string ComputeContentHash() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + writer.Write(languageID); + writer.Write(sourcePath); + writer.Write(entryPoint); + writer.Write(defines.Count); + foreach ((string key, string value) in defines.OrderBy(static item => item.Key, StringComparer.Ordinal)) + { + writer.Write(key); + writer.Write(value); + } + writer.Write(sources.Count); + foreach (ShaderSourceFile file in sources) + { + writer.Write(file.assetPath); + writer.Write(file.text); + } + writer.Write(includes.Count); + foreach (ShaderSourceInclude edge in includes) + { + writer.Write(edge.includingFile); + writer.Write(edge.include); + writer.Write(edge.resolvedPath); + } + writer.Flush(); + return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))); + } + + private sealed class FrozenResolver( + IReadOnlyList sources, + IReadOnlyList includes + ) : IShaderSourceResolver + { + /// + /// Reads and validates the include value from its authoritative source. + /// + /// + /// The including file text validated by the read include operation. + /// + /// + /// The include text validated by the read include operation. + /// + /// + /// The validated shader source file that represents the completed operation. + /// +public ShaderSourceFile ReadInclude( + string includingFile, + string include +) { + ShaderSourceInclude edge = includes.FirstOrDefault(value => value.includingFile == includingFile && value.include == include) + ?? throw new InvalidOperationException( + $"Include '{include}' from '{includingFile}' was not captured during source analysis." + ); + return sources.Single(file => file.assetPath == edge.resolvedPath); + } + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs new file mode 100644 index 000000000..19a1642f6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs @@ -0,0 +1,49 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Identifies one explicitly selected implementation and preprocessing configuration of a source module. +/// +public sealed class ShaderSourceImplementationRequest +{ + /// + /// Creates a candidate without inferring a language or adapter from its filename. + /// + /// + /// Unique owner-defined key, including the target or variant when applicable. + /// + /// + /// Registered source language identity. + /// + /// + /// Source function and candidate-scoped dependency resolver. + /// + public ShaderSourceImplementationRequest( + string implementationID, + string languageID, + ShaderSourceRequest source + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); + ArgumentException.ThrowIfNullOrWhiteSpace(languageID); + ArgumentNullException.ThrowIfNull(source); + this.implementationID = implementationID; + this.languageID = languageID; + this.source = source; + } + + /// + /// Gets the stable owner-defined implementation/configuration key. + /// + public string implementationID { get; } + + /// + /// Gets the explicitly selected language identity. + /// + public string languageID { get; } + + /// + /// Gets the transient candidate request, which must not be persisted or retained after analysis. + /// + public ShaderSourceRequest source { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs index a65b17a76..a8b764061 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs @@ -1,202 +1,10 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Security.Cryptography; -using System.Text; using Inno.Core.Diagnostics; namespace Inno.Rendering.Shaders; -/// -/// Records an include resolution edge so compilation never reinterprets authoring paths against live files. -/// -/// -/// Source that requested the include. -/// -/// -/// Original include spelling passed to the source resolver. -/// -/// -/// Exact source identity within the frozen file set. -/// -public sealed record ShaderSourceInclude( - string includingFile, - string include, - string resolvedPath -); - -/// -/// Identifies one explicitly selected implementation and preprocessing configuration of a source module. -/// -public sealed class ShaderSourceImplementationRequest -{ - /// - /// Creates a candidate without inferring a language or adapter from its filename. - /// - /// - /// Unique owner-defined key, including the target or variant when applicable. - /// - /// - /// Registered source language identity. - /// - /// - /// Source function and candidate-scoped dependency resolver. - /// - public ShaderSourceImplementationRequest( - string implementationId, - string languageId, - ShaderSourceRequest source - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); - ArgumentException.ThrowIfNullOrWhiteSpace(languageId); - this.implementationId = implementationId; - this.languageId = languageId; - this.source = source ?? throw new ArgumentNullException(nameof(source)); - } - - /// - /// Gets the stable owner-defined implementation/configuration key. - /// - public string implementationId { get; } - /// - /// Gets the explicitly selected language identity. - /// - public string languageId { get; } - /// - /// Gets the transient candidate request, which must not be persisted or retained after analysis. - /// - public ShaderSourceRequest source { get; } -} - -/// -/// Freezes a parsed implementation and its complete source inputs without retaining a frontend or resolver. -/// -public sealed class ShaderSourceImplementationAnalysis -{ - internal ShaderSourceImplementationAnalysis( - ShaderSourceImplementationRequest request, - ShaderSourceAnalysis analysis, - IEnumerable files, - IEnumerable includes - ) { - implementationId = request.implementationId; - languageId = request.languageId; - sourcePath = request.source.source.assetPath; - entryPoint = request.source.entryPoint; - defines = request.source.defines; - this.analysis = analysis; - sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); - this.includes = Array.AsReadOnly(includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) - .ThenBy(static edge => edge.include, StringComparer.Ordinal).ToArray()); - contentHash = ComputeContentHash(); - } - - /// - /// Gets the stable implementation/configuration key. - /// - public string implementationId { get; } - /// - /// Gets the selected source language. - /// - public string languageId { get; } - /// - /// Gets the root source path in the frozen source set. - /// - public string sourcePath { get; } - /// - /// Gets the implementation's selected callable function name. - /// - public string entryPoint { get; } - /// - /// Gets the immutable preprocessing inputs used for this implementation. - /// - public IReadOnlyDictionary defines { get; } - /// - /// Gets every successfully read source, including the root, ordered by path. - /// - public IReadOnlyList sources { get; } - /// - /// Gets the original resolver's frozen include edges, including aliases and mounted source paths. - /// - public IReadOnlyList includes { get; } - /// - /// Gets the parsed interface and implementation-local diagnostics. - /// - public ShaderSourceAnalysis analysis { get; } - /// - /// Gets a deterministic source-input hash. A compiler cache must additionally include its toolchain, - /// target, graph semantics and binding layout; this hash alone is not a compiled artifact key. - /// - public string contentHash { get; } - - /// - /// Recreates a compiler input backed only by immutable captured sources and resolution edges. - /// - /// - /// A request with no filesystem access or reference to the original frontend, resolver or generation. - /// - public ShaderSourceRequest CreateSourceRequest() - => new(sources.Single(file => file.assetPath == sourcePath), entryPoint, new FrozenResolver(sources, includes), defines); - - private string ComputeContentHash() - { - using var stream = new MemoryStream(); - using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(languageId); - writer.Write(sourcePath); - writer.Write(entryPoint); - writer.Write(defines.Count); - foreach ((string key, string value) in defines.OrderBy(static item => item.Key, StringComparer.Ordinal)) - { - writer.Write(key); - writer.Write(value); - } - writer.Write(sources.Count); - foreach (ShaderSourceFile file in sources) - { - writer.Write(file.assetPath); - writer.Write(file.text); - } - writer.Write(includes.Count); - foreach (ShaderSourceInclude edge in includes) - { - writer.Write(edge.includingFile); - writer.Write(edge.include); - writer.Write(edge.resolvedPath); - } - writer.Flush(); - return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))); - } - - private sealed class FrozenResolver( - IReadOnlyList sources, - IReadOnlyList includes - ) : IShaderSourceResolver - { - /// - /// Reads and validates the include value from its authoritative source. - /// - /// - /// The including file text validated by the read include operation. - /// - /// - /// The include text validated by the read include operation. - /// - /// - /// The validated shader source file that represents the completed operation. - /// -public ShaderSourceFile ReadInclude( - string includingFile, - string include -) { - ShaderSourceInclude edge = includes.FirstOrDefault(value => value.includingFile == includingFile && value.include == include) - ?? throw new InvalidOperationException($"Include '{include}' from '{includingFile}' was not captured during source analysis."); - return sources.Single(file => file.assetPath == edge.resolvedPath); - } - } -} - /// /// Reports whether every supplied implementation and variant has the same callable graph interface. /// @@ -208,72 +16,46 @@ IEnumerable diagnostics ) { this.implementations = Array.AsReadOnly(implementations.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - succeeded = this.implementations.Count != 0 && this.implementations.All(static item => item.analysis.succeeded) - && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); - function = succeeded ? this.implementations[0].analysis.function : null; + this.succeeded = this.implementations.Count != 0 && this.implementations.All(static item => item.analysis.succeeded) + && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); + this.function = succeeded ? this.implementations[0].analysis.function : null; } /// /// Gets all implementation snapshots, including failed or unavailable implementations. /// public IReadOnlyList implementations { get; } + /// /// Gets implementation and cross-implementation diagnostics with original source positions. /// public IReadOnlyList diagnostics { get; } + /// /// Gets the common interface only when all supplied implementations agree and are valid. /// public ShaderSourceFunction? function { get; } + /// /// Gets whether interface analysis succeeded; native compilation is a separate gate. /// public bool succeeded { get; } } -internal sealed class ShaderSourceSnapshotResolver : IShaderSourceResolver -{ - private readonly IShaderSourceResolver m_resolver; - private readonly Dictionary m_files = new(StringComparer.Ordinal); - private readonly Dictionary<(string, string), ShaderSourceInclude> m_includes = []; - - internal ShaderSourceSnapshotResolver(ShaderSourceRequest request) - { - m_resolver = request.resolver; - m_files.Add(request.source.assetPath, request.source); - } - - internal IEnumerable files => m_files.Values; - internal IEnumerable includes => m_includes.Values; - - /// - /// Reads and validates the include value from its authoritative source. - /// - /// - /// The including file text validated by the read include operation. - /// - /// - /// The include text validated by the read include operation. - /// - /// - /// The validated shader source file that represents the completed operation. - /// -public ShaderSourceFile ReadInclude( +/// +/// Records an include resolution edge so compilation never reinterprets authoring paths against live files. +/// +/// +/// Source that requested the include. +/// +/// +/// Original include spelling passed to the source resolver. +/// +/// +/// Exact source identity within the frozen file set. +/// +public sealed record ShaderSourceInclude( string includingFile, - string include -) { - if (!m_files.ContainsKey(includingFile)) - throw new InvalidOperationException("An include must originate from an already captured source."); - ShaderSourceFile file = m_resolver.ReadInclude(includingFile, include) - ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); - ArgumentException.ThrowIfNullOrWhiteSpace(file.assetPath); - ArgumentNullException.ThrowIfNull(file.text); - if (m_files.TryGetValue(file.assetPath, out ShaderSourceFile? previous) && previous.text != file.text) - throw new InvalidOperationException($"Source '{file.assetPath}' changed during module analysis."); - if (m_includes.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && edge.resolvedPath != file.assetPath) - throw new InvalidOperationException($"Include '{include}' changed resolution during module analysis."); - m_includes[(includingFile, include)] = new(includingFile, include, file.assetPath); - m_files[file.assetPath] = file; - return file; - } -} + string include, + string resolvedPath +); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs index ddb164750..61fd08710 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs @@ -23,16 +23,22 @@ public ShaderSourceNodeDefinition(ShaderSourceFunction function) : base("inno.shader.source", function?.name ?? throw new ArgumentNullException(nameof(function)), "Code") { this.function = function; - var ports = new List(); + List ports = []; foreach (ShaderSourceParameter parameter in function.parameters) { if (parameter.direction != ShaderSourceParameterDirection.Output) + { Add("input." + parameter.name, parameter.name, parameter.type, GraphPortDirection.Input); + } if (parameter.direction != ShaderSourceParameterDirection.Input) + { Add("output." + parameter.name, parameter.name, parameter.type, GraphPortDirection.Output); + } } if (function.returnType.id != "void") + { Add("return", "Result", function.returnType, GraphPortDirection.Output); + } m_ports = ports.AsReadOnly(); void Add( @@ -41,11 +47,20 @@ void Add( ShaderSourceType type, GraphPortDirection direction ) { - ports.Add(new(new GraphPortId(id), label, TypeIdentity(type), direction, - direction == GraphPortDirection.Input ? GraphPortCapacity.Single : GraphPortCapacity.Multiple)); + ports.Add( + new GraphPortDefinition( + new GraphPortID(id), + label, + TypeIdentity(type), + direction, + direction == GraphPortDirection.Input ? GraphPortCapacity.Single : GraphPortCapacity.Multiple + ) + ); // Aggregate and member ports coexist so collapsing presentation never changes edge identity. foreach (ShaderSourceField field in type.fields) + { Add(id + "." + field.name, label + "." + field.name, field.type, direction); + } } } @@ -72,7 +87,9 @@ public override IReadOnlyList GetPorts(GraphNodeRecord node private static string TypeIdentity(ShaderSourceType type) { if (type.elementType is null && type.fields.Count == 0 && type.storage is null) + { return type.id; + } var canonical = new StringBuilder(); Write(type); return "inno.shader.aggregate." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical.ToString()))); @@ -81,11 +98,21 @@ void Write(ShaderSourceType value) { canonical.Append(value.id.Length).Append(':').Append(value.id).Append('[').Append(value.elementCount).Append(']'); if (value.elementType is not null) + { Write(value.elementType); + } if (value.storage is ShaderStorageType storage) { - canonical.Append('(').Append((int)storage.access).Append(',').Append(storage.format.HasValue ? (int)storage.format.Value : -1) - .Append(',').Append((int)storage.dimension).Append(',').Append(storage.array ? 1 : 0).Append(')'); + canonical + .Append('(') + .Append((int)storage.access) + .Append(',') + .Append(storage.format.HasValue ? (int)storage.format.Value : -1) + .Append(',') + .Append((int)storage.dimension) + .Append(',') + .Append(storage.array ? 1 : 0) + .Append(')'); Write(storage.valueType); } canonical.Append('{'); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs new file mode 100644 index 000000000..680b7271b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs @@ -0,0 +1,78 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes one parameter parsed from a public source declaration. +/// +public sealed class ShaderSourceParameter +{ + /// + /// Creates a validated function parameter. + /// + /// + /// Public parameter name, used for semantic port matching rather than ordinal matching. + /// + /// + /// Canonical value type. + /// + /// + /// Declared value flow. + /// + /// + /// The parameter has void type. + /// + public ShaderSourceParameter( + string name, + ShaderSourceType type, + ShaderSourceParameterDirection direction + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(type); + if (!Enum.IsDefined(direction)) + { + throw new ArgumentOutOfRangeException(nameof(direction)); + } + if (type.id == "void") + { + throw new ArgumentException("A parameter cannot have void type.", nameof(type)); + } + this.name = name; + this.type = type; + this.direction = direction; + } + + /// + /// Gets the public parameter name. + /// + public string name { get; } + + /// + /// Gets the complete canonical value type. + /// + public ShaderSourceType type { get; } + + /// + /// Gets the declared value flow. + /// + public ShaderSourceParameterDirection direction { get; } +} + +/// +/// Declares value flow across a source function parameter. +/// +public enum ShaderSourceParameterDirection +{ + /// + /// The caller supplies a value. + /// + Input, + /// + /// The function produces a value. + /// + Output, + /// + /// The caller supplies a value and the function produces its replacement. + /// + InputOutput +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs new file mode 100644 index 000000000..7c77fc1d9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Rendering.Shaders; + +/// +/// Carries the immutable inputs required to execute one shader source request. +/// +public sealed class ShaderSourceRequest +{ + /// + /// Creates an analysis request for an explicitly selected function. + /// + /// + /// Root source snapshot. + /// + /// + /// The one public function selected by source import settings. + /// + /// + /// Candidate-scoped include resolver. + /// + /// + /// Target and variant preprocessing inputs, or null for no defines. + /// + public ShaderSourceRequest( + ShaderSourceFile source, + string entryPoint, + IShaderSourceResolver resolver, + IReadOnlyDictionary? defines = null + ) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(resolver); + this.source = source; + ArgumentException.ThrowIfNullOrWhiteSpace(source.assetPath); + ArgumentNullException.ThrowIfNull(source.text); + ArgumentException.ThrowIfNullOrWhiteSpace(entryPoint); + this.entryPoint = entryPoint; + this.resolver = resolver; + this.defines = new ReadOnlyDictionary( + defines is null + ? new Dictionary(StringComparer.Ordinal) + : new Dictionary(defines, StringComparer.Ordinal) + ); + } + + /// + /// Gets the root source snapshot. + /// + public ShaderSourceFile source { get; } + + /// + /// Gets the explicitly selected export function name. + /// + public string entryPoint { get; } + + /// + /// Gets the candidate-scoped dependency resolver. + /// + public IShaderSourceResolver resolver { get; } + + /// + /// Gets immutable preprocessing inputs included in analysis cache identity. + /// + public IReadOnlyDictionary defines { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs new file mode 100644 index 000000000..f38512796 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderSourceSnapshotResolver : IShaderSourceResolver +{ + private readonly IShaderSourceResolver m_resolver; + private readonly Dictionary m_files = new(StringComparer.Ordinal); + private readonly Dictionary<(string, string), ShaderSourceInclude> m_includes = []; + + internal ShaderSourceSnapshotResolver(ShaderSourceRequest request) + { + m_resolver = request.resolver; + m_files.Add(request.source.assetPath, request.source); + } + + /// + /// Reads and validates the include value from its authoritative source. + /// + /// + /// The including file text validated by the read include operation. + /// + /// + /// The include text validated by the read include operation. + /// + /// + /// The validated shader source file that represents the completed operation. + /// +public ShaderSourceFile ReadInclude( + string includingFile, + string include +) { + if (!m_files.ContainsKey(includingFile)) + { + throw new InvalidOperationException("An include must originate from an already captured source."); + } + ShaderSourceFile file = m_resolver.ReadInclude(includingFile, include) + ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); + ArgumentException.ThrowIfNullOrWhiteSpace(file.assetPath); + ArgumentNullException.ThrowIfNull(file.text); + if (m_files.TryGetValue(file.assetPath, out ShaderSourceFile? previous) && previous.text != file.text) + { + throw new InvalidOperationException($"Source '{file.assetPath}' changed during module analysis."); + } + if (m_includes.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && edge.resolvedPath != file.assetPath) + { + throw new InvalidOperationException($"Include '{include}' changed resolution during module analysis."); + } + m_includes[(includingFile, include)] = new(includingFile, include, file.assetPath); + m_files[file.assetPath] = file; + return file; + } + + internal IEnumerable files => m_files.Values; + internal IEnumerable includes => m_includes.Values; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs index 79d5378c0..5d34cd727 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs @@ -18,8 +18,8 @@ private ShaderSourceType( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); this.id = id; - elementType = element; - elementCount = count; + this.elementType = element; + this.elementCount = count; this.fields = Array.AsReadOnly(fields); this.storage = storage; } @@ -28,14 +28,17 @@ private ShaderSourceType( /// Gets the open semantic type identifier, independent of source-language spelling. /// public string id { get; } + /// /// Gets the array element type, or null for a non-array value. /// public ShaderSourceType? elementType { get; } + /// /// Gets the fixed array length, or zero for a non-array value. /// public int elementCount { get; } + /// /// Gets immutable structure fields in declaration order. /// @@ -46,6 +49,40 @@ private ShaderSourceType( /// public ShaderStorageType? storage { get; } + /// + /// Checks both nominal identity and complete aggregate layout. + /// + /// + /// Candidate type from another implementation. + /// + /// + /// True only when both descriptors express the same function interface. + /// + public bool IsEquivalentTo(ShaderSourceType? other) + { + if (other is null || id != other.id || elementCount != other.elementCount || fields.Count != other.fields.Count) + { + return false; + } + if ((storage is null) != (other.storage is null) || storage is not null && !storage.IsEquivalentTo(other.storage)) + { + return false; + } + if ((elementType is null) != (other.elementType is null) + || elementType is not null && !elementType.IsEquivalentTo(other.elementType) + ) { + return false; + } + for (int i = 0; i < fields.Count; i++) + { + if (fields[i].name != other.fields[i].name || !fields[i].type.IsEquivalentTo(other.fields[i].type)) + { + return false; + } + } + return true; + } + /// /// Creates an opaque storage binding value with a complete element, format and access contract. /// @@ -91,7 +128,9 @@ int count ArgumentNullException.ThrowIfNull(element); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count); if (element.id == "void" || element.storage is not null) + { throw new ArgumentException("An array cannot contain void values or opaque storage bindings.", nameof(element)); + } return new("array", element, count, []); } @@ -116,72 +155,15 @@ IEnumerable fields ) { ArgumentNullException.ThrowIfNull(fields); if (id == "void") + { throw new ArgumentException("Void is reserved for the absence of a return value.", nameof(id)); + } ShaderSourceField[] snapshot = fields.ToArray(); - if (snapshot.Length == 0 || snapshot.Any(static field => field is null) || - snapshot.Select(static field => field.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length) + if (snapshot.Length == 0 || snapshot.Any(static field => field is null) + || snapshot.Select(static field => field.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length + ) { throw new ArgumentException("A structure requires unique named fields.", nameof(fields)); + } return new(id, null, 0, snapshot); } - - /// - /// Checks both nominal identity and complete aggregate layout. - /// - /// - /// Candidate type from another implementation. - /// - /// - /// True only when both descriptors express the same function interface. - /// - public bool IsEquivalentTo(ShaderSourceType? other) - { - if (other is null || id != other.id || elementCount != other.elementCount || fields.Count != other.fields.Count) - return false; - if ((storage is null) != (other.storage is null) || storage is not null && !storage.IsEquivalentTo(other.storage)) - return false; - if ((elementType is null) != (other.elementType is null) || - elementType is not null && !elementType.IsEquivalentTo(other.elementType)) - return false; - for (int i = 0; i < fields.Count; i++) - if (fields[i].name != other.fields[i].name || !fields[i].type.IsEquivalentTo(other.fields[i].type)) - return false; - return true; - } -} - -/// -/// Describes one immutable named structure field. -/// -public sealed class ShaderSourceField -{ - /// - /// Creates a structure field. - /// - /// - /// Stable field name. - /// - /// - /// Complete field type. - /// - /// - /// The field has void type or is an opaque storage binding. - /// - public ShaderSourceField( - string name, - ShaderSourceType type - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - if (type?.id == "void" || type?.storage is not null) - throw new ArgumentException("A structure field cannot have void type or contain an opaque storage binding.", nameof(type)); - this.name = name; - this.type = type ?? throw new ArgumentNullException(nameof(type)); - } - /// - /// Gets the public field name. - /// - public string name { get; } - /// - /// Gets the complete field type. - /// - public ShaderSourceType type { get; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs index f9f1977c9..e1064cd4d 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs @@ -1,33 +1,8 @@ -using System; using System.Threading; using Inno.Core.Graphs; -using Inno.Core.Serialization; namespace Inno.Rendering.Shaders; -/// -/// Declares the immutable identity used to select a Shader Target from an authored graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderTargetAttribute : Attribute -{ - /// - /// Creates target discovery metadata. - /// - /// - /// Stable target identity persisted by Shader assets. - /// - public ShaderTargetAttribute(string id) - => this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) - : id; - - /// - /// Gets the stable target identity persisted by Shader assets. - /// - public string id { get; } -} - /// /// Expands a domain's surface contract into ordinary graph stages before source dependency capture. /// @@ -50,32 +25,3 @@ public abstract GraphDocument Expand( CancellationToken cancellationToken ); } - -/// -/// Supplies neutral authoring data to a domain target without exposing an adapter or live asset. -/// -public sealed class ShaderTargetContext -{ - internal ShaderTargetContext( - GraphDocument document, - SerializationRegistry serialization, - SerializationContext references - ) { - this.document = document; - this.serialization = serialization; - this.references = references; - } - - /// - /// Gets a private document copy; expansion cannot modify the authored source. - /// - public GraphDocument document { get; } - /// - /// Gets the current owner converter registry, valid only during expansion. - /// - public SerializationRegistry serialization { get; } - /// - /// Gets the complete owner reference context used for generated resource defaults. - /// - public SerializationContext references { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs new file mode 100644 index 000000000..2961ef8d0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares the immutable identity used to select a Shader Target from an authored graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderTargetAttribute : Attribute +{ + /// + /// Creates target discovery metadata. + /// + /// + /// Stable target identity persisted by Shader assets. + /// + public ShaderTargetAttribute(string id) + { + this.id = string.IsNullOrWhiteSpace(id) + ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) + : id; + } + + /// + /// Gets the stable target identity persisted by Shader assets. + /// + public string id { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs new file mode 100644 index 000000000..531065662 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs @@ -0,0 +1,35 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Supplies neutral authoring data to a domain target without exposing an adapter or live asset. +/// +public sealed class ShaderTargetContext +{ + internal ShaderTargetContext( + GraphDocument document, + SerializationRegistry serialization, + SerializationContext references + ) { + this.document = document; + this.serialization = serialization; + this.references = references; + } + + /// + /// Gets a private document copy; expansion cannot modify the authored source. + /// + public GraphDocument document { get; } + + /// + /// Gets the current owner converter registry, valid only during expansion. + /// + public SerializationRegistry serialization { get; } + + /// + /// Gets the complete owner reference context used for generated resource defaults. + /// + public SerializationContext references { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs index 43ed67d90..e8e12b2dd 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs @@ -25,7 +25,8 @@ public sealed class ShaderTargetRegistry : IDisposable /// public ShaderTargetRegistry(TypeCatalog types) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types); + m_types = types; m_registry = new(types); } @@ -78,11 +79,15 @@ public GraphDocument Expand( cancellationToken.ThrowIfCancellationRequested(); string id = ShaderGraphDocument.ReadTarget(document, serialization, context); if (id.Length == 0) + { return document.Clone(); + } if (!m_registry.snapshot.TryGetValue(id, out ShaderTarget? target)) + { throw new ShaderTargetUnavailableException(id); - GraphDocument expanded = target.Expand(new(document.Clone(), serialization, context), cancellationToken) - ?? throw new InvalidOperationException($"Shader target '{id}' returned no program."); + } + GraphDocument expanded = target.Expand(new ShaderTargetContext(document.Clone(), serialization, context), cancellationToken) + ?? throw new InvalidOperationException($"Shader target '{id}' returned no program."); cancellationToken.ThrowIfCancellationRequested(); return expanded.Clone(); } @@ -115,16 +120,19 @@ protected override IReadOnlyDictionary Build(TypeCacheSnap if (type.IsAbstract || !typeof(ShaderTarget).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Shader target '{type.FullName}' must be a concrete {nameof(ShaderTarget)}."); + $"Shader target '{type.FullName}' must be a concrete {nameof(ShaderTarget)}." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }) .ToArray(); - string? duplicateId = registrations + string? duplicateID = registrations .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; - if (duplicateId is not null) - throw new InvalidOperationException($"Duplicate shader target '{duplicateId}'."); + if (duplicateID is not null) + { + throw new InvalidOperationException($"Duplicate shader target '{duplicateID}'."); + } var targets = new Dictionary(StringComparer.Ordinal); foreach ((Type type, string id) in registrations) diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetUnavailableException.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetUnavailableException.cs index 3109e60e0..e8921efd9 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetUnavailableException.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetUnavailableException.cs @@ -10,18 +10,18 @@ public sealed class ShaderTargetUnavailableException : InvalidOperationException /// /// Creates a missing-target diagnostic without retaining extension objects. /// - /// + /// /// The stable authored target identity. /// - public ShaderTargetUnavailableException(string targetId) - : base($"Shader target '{targetId}' is unavailable. The authored graph is retained for recovery.") + public ShaderTargetUnavailableException(string targetID) + : base($"Shader target '{targetID}' is unavailable. The authored graph is retained for recovery.") { - ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - this.targetId = targetId; + ArgumentException.ThrowIfNullOrWhiteSpace(targetID); + this.targetID = targetID; } /// /// Gets the stable target identity required by the authored graph. /// - public string targetId { get; } + public string targetID { get; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs new file mode 100644 index 000000000..d4fe0631e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs @@ -0,0 +1,25 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +[ShaderGraphTemplate(ShaderBuiltInIDs.C_RASTER_TEMPLATE, "Raster")] +internal sealed class RasterShaderGraphTemplate : ShaderGraphTemplate +{ + /// + /// Creates and validates a caller-owned value value. + /// + /// + /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated graph document that represents the completed operation. + /// +public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context +) => ShaderGraphTemplates.CreateRaster(serialization, context); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs new file mode 100644 index 000000000..c0c702660 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs @@ -0,0 +1,61 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; +using Inno.Rendering.Assets; + +namespace Inno.Rendering.Shaders; + +[ShaderGraphTemplate(ShaderBuiltInIDs.C_NODE_TEMPLATE, "Reusable Node")] +internal sealed class ReusableShaderGraphNodeTemplate : ShaderGraphTemplate +{ + /// + /// Creates a value using this implementation's validated inputs. + /// + /// + /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated graph document that represents the completed operation. + /// + public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context + ) { + GraphDocument graph = ShaderGraphDocument.Create(new ShaderDefinition("Graph Node", [], [], []), serialization, context); + ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); + var input = new GraphNodeRecord(new GraphNodeID("node-inputs"), ShaderGraphNodes.C_INPUT_DEFINITION_ID) + { + position = new(40, 120) + }; + input.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings + { + ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); + var output = new GraphNodeRecord(new GraphNodeID("node-outputs"), ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) + { + position = new(620, 120) + }; + output.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings + { + ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); + graph.AddNode(input); + graph.AddNode(output); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("node-value"), + new GraphEndpoint(input.id, new GraphPortID("value")), + new GraphEndpoint(output.id, new GraphPortID("value")) + ) + ); + return graph; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs new file mode 100644 index 000000000..ce6ff58b9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs @@ -0,0 +1,7 @@ +namespace Inno.Rendering.Shaders; + +internal static class ShaderBuiltInIDs +{ + internal const string C_RASTER_TEMPLATE = "inno.shader.raster"; + internal const string C_NODE_TEMPLATE = "inno.shader.node"; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs index 4ec32c7c2..383627445 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs @@ -1,47 +1,8 @@ -using System; using Inno.Core.Graphs; using Inno.Core.Serialization; namespace Inno.Rendering.Shaders; -/// -/// Declares immutable creation metadata for a Shader graph template. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderGraphTemplateAttribute : Attribute -{ - /// - /// Creates Shader graph template discovery metadata. - /// - /// - /// Stable template identity used by creation commands. - /// - /// - /// User-facing creation menu label. - /// - public ShaderGraphTemplateAttribute( - string id, - string displayName - ) { - this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) - : id; - this.displayName = string.IsNullOrWhiteSpace(displayName) - ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) - : displayName; - } - - /// - /// Gets the stable template identity used by creation commands. - /// - public string id { get; } - - /// - /// Gets the user-facing creation menu label. - /// - public string displayName { get; } -} - /// /// Contributes an ordinary shader graph to the shared asset creation workflow. /// @@ -64,75 +25,3 @@ public abstract GraphDocument Create( SerializationContext context ); } - -[ShaderGraphTemplate(ShaderBuiltInIds.rasterTemplate, "Raster")] -internal sealed class RasterShaderGraphTemplate : ShaderGraphTemplate -{ - /// - /// Creates and validates a caller-owned value value. - /// - /// - /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated graph document that represents the completed operation. - /// -public override GraphDocument Create( - SerializationRegistry serialization, - SerializationContext context -) - => ShaderGraphTemplates.CreateRaster(serialization, context); -} - -[ShaderGraphTemplate(ShaderBuiltInIds.nodeTemplate, "Reusable Node")] -internal sealed class ReusableShaderGraphNodeTemplate : ShaderGraphTemplate -{ - /// - /// Creates a value using this implementation's validated inputs. - /// - /// - /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated graph document that represents the completed operation. - /// - public override GraphDocument Create( - SerializationRegistry serialization, - SerializationContext context - ) { - GraphDocument graph = ShaderGraphDocument.Create(new("Graph Node", [], [], []), serialization, context); - ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); - var input = new GraphNodeRecord(new("node-inputs"), ShaderGraphNodes.inputDefinitionId) - { - position = new(40, 120) - }; - input.SetValue(ShaderGraphDocument.settingsKey, ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings - { - ports = [new() { id = "value", type = new() { id = "float" } }] - }, serialization, context)); - var output = new GraphNodeRecord(new("node-outputs"), ShaderGraphNodes.outputDefinitionId) - { - position = new(620, 120) - }; - output.SetValue(ShaderGraphDocument.settingsKey, ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings - { - ports = [new() { id = "value", type = new() { id = "float" } }] - }, serialization, context)); - graph.AddNode(input); - graph.AddNode(output); - graph.AddEdge(new(new("node-value"), new(input.id, new("value")), new(output.id, new("value")))); - return graph; - } -} - -internal static class ShaderBuiltInIds -{ - internal const string rasterTemplate = "inno.shader.raster"; - internal const string nodeTemplate = "inno.shader.node"; -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs new file mode 100644 index 000000000..a58ae9fa5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares immutable creation metadata for a Shader graph template. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderGraphTemplateAttribute : Attribute +{ + /// + /// Creates Shader graph template discovery metadata. + /// + /// + /// Stable template identity used by creation commands. + /// + /// + /// User-facing creation menu label. + /// + public ShaderGraphTemplateAttribute( + string id, + string displayName + ) { + this.id = string.IsNullOrWhiteSpace(id) + ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) + : id; + this.displayName = string.IsNullOrWhiteSpace(displayName) + ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) + : displayName; + } + + /// + /// Gets the stable template identity used by creation commands. + /// + public string id { get; } + + /// + /// Gets the user-facing creation menu label. + /// + public string displayName { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs index 2e927ce8e..2f308cf84 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs @@ -8,20 +8,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Describes a creation menu item without retaining a plugin instance. -/// -/// -/// Stable template identity. -/// -/// -/// User-facing label. -/// -public sealed record ShaderGraphTemplateInfo( - string id, - string displayName -); - /// /// Owns generation-safe template discovery and invocation for editor asset creation. /// @@ -38,7 +24,8 @@ public sealed class ShaderGraphTemplateRegistry : IDisposable /// public ShaderGraphTemplateRegistry(TypeCatalog types) { - m_types = types ?? throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types); + m_types = types; m_registry = new(types); } @@ -50,8 +37,12 @@ public IReadOnlyList templates get { using IDisposable operation = m_types.AcquireOperation("Describe shader templates"); - return Array.AsReadOnly(m_registry.snapshot.Values.Select(static value => value.info) - .OrderBy(static value => value.displayName, StringComparer.Ordinal).ThenBy(static value => value.id, StringComparer.Ordinal).ToArray()); + return Array.AsReadOnly( + m_registry.snapshot.Values.Select(static value => value.info) + .OrderBy(static value => value.displayName, StringComparer.Ordinal) + .ThenBy(static value => value.id, StringComparer.Ordinal) + .ToArray() + ); } } @@ -81,7 +72,9 @@ SerializationContext context ArgumentException.ThrowIfNullOrWhiteSpace(id); using IDisposable operation = m_types.AcquireOperation("Create shader from template"); if (!m_registry.snapshot.TryGetValue(id, out Entry? entry)) + { throw new InvalidOperationException($"Shader template '{id}' is unavailable."); + } return entry.template.Create(serialization, context).Clone(); } @@ -98,6 +91,7 @@ ShaderGraphTemplate template private sealed class Registry(TypeCatalog types) : TypeRegistry>(types) { internal IReadOnlyDictionary snapshot => current; + /// /// Builds a validated result from the current immutable input snapshot. /// @@ -118,16 +112,19 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty if (type.IsAbstract || !typeof(ShaderGraphTemplate).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Shader graph template '{type.FullName}' must be a concrete {nameof(ShaderGraphTemplate)}."); + $"Shader graph template '{type.FullName}' must be a concrete {nameof(ShaderGraphTemplate)}." + ); } return (type, type.GetCustomAttribute(inherit: false)!); }) .ToArray(); - string? duplicateId = registrations + string? duplicateID = registrations .GroupBy(static registration => registration.metadata.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; - if (duplicateId is not null) - throw new InvalidOperationException($"Duplicate shader template '{duplicateId}'."); + if (duplicateID is not null) + { + throw new InvalidOperationException($"Duplicate shader template '{duplicateID}'."); + } var templates = new Dictionary(StringComparer.Ordinal); foreach ((Type type, ShaderGraphTemplateAttribute metadata) in registrations) @@ -138,6 +135,7 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty } return templates; } + /// /// Releases the generation lease retained by an immutable registry snapshot. /// @@ -145,6 +143,20 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty /// The immutable state snapshot consumed by this operation. /// protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) - => DisposeExtensions(snapshot.Values.Select(static value => value.template)); + => DisposeExtensions(snapshot.Values.Select(static value => value.template)); } } + +/// +/// Describes a creation menu item without retaining a plugin instance. +/// +/// +/// Stable template identity. +/// +/// +/// User-facing label. +/// +public sealed record ShaderGraphTemplateInfo( + string id, + string displayName +); diff --git a/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs index 4990cfaf0..7bb05661d 100644 --- a/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs @@ -50,4 +50,3 @@ IReadOnlyList bindings /// public IReadOnlyList bindings => m_bindings; } - diff --git a/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs b/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs new file mode 100644 index 000000000..1e23cc7d3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a backend-neutral compute pipeline object. +/// +public readonly record struct ComputePipelineHandle +{ + internal ComputePipelineHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a compute pipeline. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs new file mode 100644 index 000000000..b5723a271 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs @@ -0,0 +1,142 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies the graphics API family selected by the host without exposing a backend-native enum. +/// Pipelines use this value only for capability-aware choices and target artifact selection; +/// it does not require separate pipeline or shader source implementations. +/// +public readonly record struct GraphicsApi : IComparable +{ + /// + /// Creates an open, stable backend identity without registering a backend implementation. + /// + /// + /// A portable case-sensitive identifier used in target artifact paths. + /// + /// + /// The identifier is empty or contains nonportable characters. + /// + public GraphicsApi(string value) + { + if (!IsPortableIdentifier(value)) + { + throw new ArgumentException( + "Graphics API IDs must begin with a letter or digit and use only portable letters, numbers, dots, underscores or hyphens.", + nameof(value) + ); + } + this.value = value; + } + + /// + /// Headless validation backend. + /// + public static GraphicsApi noop { get; } = new("Noop"); + + /// + /// Direct3D 11 renderer. + /// + public static GraphicsApi direct3D11 { get; } = new("Direct3D11"); + + /// + /// Direct3D 12 renderer. + /// + public static GraphicsApi direct3D12 { get; } = new("Direct3D12"); + + /// + /// Apple Metal renderer. + /// + public static GraphicsApi metal { get; } = new("Metal"); + + /// + /// Khronos Vulkan renderer. + /// + public static GraphicsApi vulkan { get; } = new("Vulkan"); + + /// + /// Desktop OpenGL renderer. + /// + public static GraphicsApi openGL { get; } = new("OpenGL"); + + /// + /// OpenGL ES renderer. + /// + public static GraphicsApi openGLES { get; } = new("OpenGLES"); + + /// + /// WebGPU renderer. + /// + public static GraphicsApi webGPU { get; } = new("WebGPU"); + + /// + /// Gets the stable backend identity used by target artifacts and provider selection. + /// + public string value { get; } + + /// + /// Gets whether this value contains an initialized backend identity. + /// + public bool isValid => !string.IsNullOrEmpty(value); + + /// + /// Compares two backend identities using stable ordinal ordering. + /// + /// + /// The other backend identity. + /// + /// + /// A negative, zero, or positive value according to ordinal identifier order. + /// + public int CompareTo(GraphicsApi other) => string.Compare(value, other.value, StringComparison.Ordinal); + + /// + /// Formats the exact stable backend identity. + /// + /// + /// The identity, or an empty string for an uninitialized value. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Parses an open backend identity without consulting a closed engine-side backend list. + /// + /// + /// The exact stable backend identity. + /// + /// + /// The parsed value, or default when parsing fails. + /// + /// + /// True when the identifier is portable and nonempty. + /// + public static bool TryParse( + string? value, + out GraphicsApi api + ) { + api = default; + if (!IsPortableIdentifier(value)) + { + return false; + } + api = new GraphicsApi(value!); + return true; + } + + private static bool IsPortableIdentifier(string? candidate) + { + if (string.IsNullOrEmpty(candidate) || !char.IsAsciiLetterOrDigit(candidate[0])) + { + return false; + } + foreach (char character in candidate) + { + if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.')) + { + return false; + } + } + return true; + } +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs index 3c9c32955..58c4fb06b 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs @@ -3,276 +3,6 @@ namespace Inno.Rendering; -/// -/// Identifies the graphics API family selected by the host without exposing a backend-native enum. -/// Pipelines use this value only for capability-aware choices and target artifact selection; -/// it does not require separate pipeline or shader source implementations. -/// -public readonly record struct GraphicsApi : IComparable -{ - /// - /// Headless validation backend. - /// - public static GraphicsApi Noop { get; } = new("Noop"); - /// - /// Direct3D 11 renderer. - /// - public static GraphicsApi Direct3D11 { get; } = new("Direct3D11"); - /// - /// Direct3D 12 renderer. - /// - public static GraphicsApi Direct3D12 { get; } = new("Direct3D12"); - /// - /// Apple Metal renderer. - /// - public static GraphicsApi Metal { get; } = new("Metal"); - /// - /// Khronos Vulkan renderer. - /// - public static GraphicsApi Vulkan { get; } = new("Vulkan"); - /// - /// Desktop OpenGL renderer. - /// - public static GraphicsApi OpenGL { get; } = new("OpenGL"); - /// - /// OpenGL ES renderer. - /// - public static GraphicsApi OpenGLES { get; } = new("OpenGLES"); - /// - /// WebGPU renderer. - /// - public static GraphicsApi WebGPU { get; } = new("WebGPU"); - - /// - /// Creates an open, stable backend identity without registering a backend implementation. - /// - /// - /// A portable case-sensitive identifier used in target artifact paths. - /// - /// - /// The identifier is empty or contains nonportable characters. - /// - public GraphicsApi(string value) - { - if (!IsPortableIdentifier(value)) - throw new ArgumentException( - "Graphics API IDs must begin with a letter or digit and use only portable letters, numbers, dots, underscores or hyphens.", - nameof(value)); - this.value = value; - } - - /// - /// Gets the stable backend identity used by target artifacts and provider selection. - /// - public string value { get; } - - /// - /// Gets whether this value contains an initialized backend identity. - /// - public bool isValid => !string.IsNullOrEmpty(value); - - /// - /// Parses an open backend identity without consulting a closed engine-side backend list. - /// - /// - /// The exact stable backend identity. - /// - /// - /// The parsed value, or default when parsing fails. - /// - /// - /// True when the identifier is portable and nonempty. - /// - public static bool TryParse( - string? value, - out GraphicsApi api - ) { - api = default; - if (!IsPortableIdentifier(value)) - return false; - api = new GraphicsApi(value!); - return true; - } - - /// - /// Compares two backend identities using stable ordinal ordering. - /// - /// - /// The other backend identity. - /// - /// - /// A negative, zero, or positive value according to ordinal identifier order. - /// - public int CompareTo(GraphicsApi other) => string.Compare(value, other.value, StringComparison.Ordinal); - - /// - /// Formats the exact stable backend identity. - /// - /// - /// The identity, or an empty string for an uninitialized value. - /// - public override string ToString() => value ?? string.Empty; - - private static bool IsPortableIdentifier(string? candidate) - { - if (string.IsNullOrEmpty(candidate) || !char.IsAsciiLetterOrDigit(candidate[0])) - return false; - foreach (char character in candidate) - if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.')) - return false; - return true; - } -} - -/// -/// Declares backend-neutral optional graphics functionality. -/// -[Flags] -public enum GraphicsCapability -{ - /// - /// No optional feature. - /// - None = 0, - /// - /// Compute shader dispatch. - /// - Compute = 1 << 0, - /// - /// Shader-readable and writable storage buffers. - /// - StorageBuffer = 1 << 1, - /// - /// Indirect draw and dispatch commands. - /// - Indirect = 1 << 2, - /// - /// Independent blend state per color attachment. - /// - IndependentBlend = 1 << 3, - /// - /// Multiple command encoders may record concurrently. - /// - ConcurrentEncoders = 1 << 4, - /// - /// Texture copy operations are supported directly. - /// - TextureBlit = 1 << 5, - /// - /// General GPU buffer copy operations are supported directly. - /// - BufferCopy = 1 << 6, - /// - /// Alpha-to-coverage rasterization is supported. - /// - AlphaToCoverage = 1 << 7, - /// - /// Unsigned 32-bit index buffers are supported. - /// - Index32 = 1 << 8, - /// - /// Instanced draw input is supported. - /// - Instancing = 1 << 9, - /// - /// Additional native presentation surfaces are supported. - /// - SwapChain = 1 << 10, - /// - /// Two-dimensional texture arrays are supported. - /// - Texture2DArray = 1 << 11, - /// - /// Three-dimensional textures are supported. - /// - Texture3D = 1 << 12, - /// - /// Cubemap texture arrays are supported. - /// - TextureCubeArray = 1 << 13, - /// - /// Half-precision vertex attributes are supported. - /// - VertexAttributeHalf = 1 << 14, - /// - /// Packed 10:10:10:2 vertex attributes are supported. - /// - VertexAttributeUInt10 = 1 << 15, - /// - /// Procedural draws using shader vertex identifiers are supported. - /// - ProceduralDraw = 1 << 16, - /// - /// Fragment shaders may write depth explicitly. - /// - FragmentDepth = 1 << 17, - /// - /// Shader-readable and writable storage textures are supported. - /// - StorageTexture = 1 << 18, - /// - /// Asynchronous texture transfer from GPU memory to CPU-visible bytes. - /// - TextureReadback = 1 << 19 -} - -/// -/// Captures device limits used to validate and compile render graphs. -/// -public sealed class GraphicsLimits -{ - /// - /// Creates a graphics limits snapshot. - /// - /// - /// Maximum logical backend views in one frame. - /// - /// - /// Maximum color attachments in one raster pass. - /// - /// - /// Maximum two-dimensional texture extent. - /// - /// - /// Maximum storage bindings in one compute pass. - /// - public GraphicsLimits( - int maxViews, - int maxColorAttachments, - int maxTextureSize, - int maxComputeBindings - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxViews); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxColorAttachments); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTextureSize); - ArgumentOutOfRangeException.ThrowIfNegative(maxComputeBindings); - this.maxViews = maxViews; - this.maxColorAttachments = maxColorAttachments; - this.maxTextureSize = maxTextureSize; - this.maxComputeBindings = maxComputeBindings; - } - - /// - /// Gets the maximum logical backend views in one frame. - /// - public int maxViews { get; } - - /// - /// Gets the maximum color attachments in one raster pass. - /// - public int maxColorAttachments { get; } - - /// - /// Gets the maximum two-dimensional texture extent. - /// - public int maxTextureSize { get; } - - /// - /// Gets the maximum storage bindings in one compute pass. - /// - public int maxComputeBindings { get; } -} - /// /// Provides an immutable capability snapshot for one device generation. /// @@ -345,20 +75,21 @@ public GraphicsCapabilities( ArgumentNullException.ThrowIfNull(storageReadFormats); ArgumentNullException.ThrowIfNull(storageWriteFormats); if (!backend.isValid) + { throw new ArgumentException("Graphics capabilities require a backend identity.", nameof(backend)); + } this.backend = backend; this.features = features; this.limits = limits; this.originBottomLeft = originBottomLeft; this.homogeneousDepth = homogeneousDepth; - m_sampledFormats = new HashSet(sampledFormats); - m_sampled3DFormats = new HashSet(sampled3DFormats ?? []); - m_sampledCubeFormats = new HashSet(sampledCubeFormats ?? []); - m_renderTargetFormats = new HashSet(renderTargetFormats); - m_multisampleRenderTargetFormats = new HashSet( - multisampleRenderTargetFormats ?? []); - m_storageReadFormats = new HashSet(storageReadFormats); - m_storageWriteFormats = new HashSet(storageWriteFormats); + m_sampledFormats = [.. sampledFormats]; + m_sampled3DFormats = [.. sampled3DFormats ?? []]; + m_sampledCubeFormats = [.. sampledCubeFormats ?? []]; + m_renderTargetFormats = [.. renderTargetFormats]; + m_multisampleRenderTargetFormats = [.. multisampleRenderTargetFormats ?? []]; + m_storageReadFormats = [.. storageReadFormats]; + m_storageWriteFormats = [.. storageWriteFormats]; } /// @@ -389,12 +120,12 @@ public GraphicsCapabilities( /// /// Tests whether every requested optional feature is supported. /// - /// - /// when every requested feature is available. - /// /// /// The required consumed by supports; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when every requested feature is available. + /// public bool Supports(GraphicsCapability required) => (features & required) == required; /// @@ -423,24 +154,23 @@ public GraphicsCapabilities( public bool SupportsSampled( RenderTextureFormat format, RenderTextureDimension dimension - ) - => dimension switch - { - RenderTextureDimension.Texture2D => m_sampledFormats.Contains(format), - RenderTextureDimension.Texture3D => m_sampled3DFormats.Contains(format), - RenderTextureDimension.Cube => m_sampledCubeFormats.Contains(format), - _ => false - }; + ) => dimension switch + { + RenderTextureDimension.Texture2D => m_sampledFormats.Contains(format), + RenderTextureDimension.Texture3D => m_sampled3DFormats.Contains(format), + RenderTextureDimension.Cube => m_sampledCubeFormats.Contains(format), + _ => false + }; /// /// Tests whether a format is valid as a raster attachment. /// - /// - /// when the format can be attached. - /// /// /// The format consumed by supports render target; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when the format can be attached. + /// public bool SupportsRenderTarget(RenderTextureFormat format) => m_renderTargetFormats.Contains(format); /// @@ -469,13 +199,104 @@ RenderTextureDimension dimension public bool SupportsStorage( RenderTextureFormat format, RenderStorageAccess access - ) - => access switch - { - RenderStorageAccess.Read => m_storageReadFormats.Contains(format), - RenderStorageAccess.Write => m_storageWriteFormats.Contains(format), - RenderStorageAccess.ReadWrite => m_storageReadFormats.Contains(format) - && m_storageWriteFormats.Contains(format), - _ => false - }; + ) => access switch + { + RenderStorageAccess.Read => m_storageReadFormats.Contains(format), + RenderStorageAccess.Write => m_storageWriteFormats.Contains(format), + RenderStorageAccess.ReadWrite => m_storageReadFormats.Contains(format) + && m_storageWriteFormats.Contains(format), + _ => false + }; +} + +/// +/// Declares backend-neutral optional graphics functionality. +/// +[Flags] +public enum GraphicsCapability +{ + /// + /// No optional feature. + /// + None = 0, + /// + /// Compute shader dispatch. + /// + Compute = 1 << 0, + /// + /// Shader-readable and writable storage buffers. + /// + StorageBuffer = 1 << 1, + /// + /// Indirect draw and dispatch commands. + /// + Indirect = 1 << 2, + /// + /// Independent blend state per color attachment. + /// + IndependentBlend = 1 << 3, + /// + /// Multiple command encoders may record concurrently. + /// + ConcurrentEncoders = 1 << 4, + /// + /// Texture copy operations are supported directly. + /// + TextureBlit = 1 << 5, + /// + /// General GPU buffer copy operations are supported directly. + /// + BufferCopy = 1 << 6, + /// + /// Alpha-to-coverage rasterization is supported. + /// + AlphaToCoverage = 1 << 7, + /// + /// Unsigned 32-bit index buffers are supported. + /// + Index32 = 1 << 8, + /// + /// Instanced draw input is supported. + /// + Instancing = 1 << 9, + /// + /// Additional native presentation surfaces are supported. + /// + SwapChain = 1 << 10, + /// + /// Two-dimensional texture arrays are supported. + /// + Texture2DArray = 1 << 11, + /// + /// Three-dimensional textures are supported. + /// + Texture3D = 1 << 12, + /// + /// Cubemap texture arrays are supported. + /// + TextureCubeArray = 1 << 13, + /// + /// Half-precision vertex attributes are supported. + /// + VertexAttributeHalf = 1 << 14, + /// + /// Packed 10:10:10:2 vertex attributes are supported. + /// + VertexAttributeUInt10 = 1 << 15, + /// + /// Procedural draws using shader vertex identifiers are supported. + /// + ProceduralDraw = 1 << 16, + /// + /// Fragment shaders may write depth explicitly. + /// + FragmentDepth = 1 << 17, + /// + /// Shader-readable and writable storage textures are supported. + /// + StorageTexture = 1 << 18, + /// + /// Asynchronous texture transfer from GPU memory to CPU-visible bytes. + /// + TextureReadback = 1 << 19 } diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs new file mode 100644 index 000000000..c4b57d6bf --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Captures device limits used to validate and compile render graphs. +/// +public sealed class GraphicsLimits +{ + /// + /// Creates a graphics limits snapshot. + /// + /// + /// Maximum logical backend views in one frame. + /// + /// + /// Maximum color attachments in one raster pass. + /// + /// + /// Maximum two-dimensional texture extent. + /// + /// + /// Maximum storage bindings in one compute pass. + /// + public GraphicsLimits( + int maxViews, + int maxColorAttachments, + int maxTextureSize, + int maxComputeBindings + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxViews); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxColorAttachments); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTextureSize); + ArgumentOutOfRangeException.ThrowIfNegative(maxComputeBindings); + this.maxViews = maxViews; + this.maxColorAttachments = maxColorAttachments; + this.maxTextureSize = maxTextureSize; + this.maxComputeBindings = maxComputeBindings; + } + + /// + /// Gets the maximum logical backend views in one frame. + /// + public int maxViews { get; } + + /// + /// Gets the maximum color attachments in one raster pass. + /// + public int maxColorAttachments { get; } + + /// + /// Gets the maximum two-dimensional texture extent. + /// + public int maxTextureSize { get; } + + /// + /// Gets the maximum storage bindings in one compute pass. + /// + public int maxComputeBindings { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs index de39c6464..c3f1ff5a0 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs @@ -90,4 +90,3 @@ private static void EnsureUniqueBindings(IReadOnlyList +/// Identifies a backend-neutral graphics pipeline object. +/// +public readonly record struct GraphicsPipelineHandle +{ + internal GraphicsPipelineHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a graphics pipeline. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs b/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs index 129a26e9b..8f14a80f9 100644 --- a/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs +++ b/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs @@ -2,52 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies a portable encoded texture container accepted by a render device. -/// -public enum RenderTextureContainer -{ - /// - /// Khronos Texture container containing validated GPU texture payloads. - /// - Ktx -} - -/// -/// Contains backend-recorded GPU command submissions for the current frame. -/// -public readonly record struct RenderDeviceFrameCounters -{ - /// - /// Creates immutable device frame counters. - /// - /// - /// Direct and indirect draw commands submitted so far. - /// - /// - /// Direct and indirect compute dispatches submitted so far. - /// - public RenderDeviceFrameCounters( - int drawCount, - int dispatchCount - ) { - ArgumentOutOfRangeException.ThrowIfNegative(drawCount); - ArgumentOutOfRangeException.ThrowIfNegative(dispatchCount); - this.drawCount = drawCount; - this.dispatchCount = dispatchCount; - } - - /// - /// Gets direct and indirect draw commands submitted during the current frame. - /// - public int drawCount { get; } - - /// - /// Gets direct and indirect compute dispatches submitted during the current frame. - /// - public int dispatchCount { get; } -} - /// /// Owns one graphics backend generation and its frame submission boundary. /// @@ -176,8 +130,7 @@ PersistentTextureHandle CreateTexture( ReadOnlySpan data, bool sRgb, string name - ) - => throw new NotSupportedException("This render device does not support encoded texture containers."); + ) => throw new NotSupportedException("This render device does not support encoded texture containers."); /// /// Replaces one complete mip and addressable layer, slice, or cubemap face. @@ -366,3 +319,14 @@ string name /// void DestroyComputePipeline(ComputePipelineHandle pipeline); } + +/// +/// Identifies a portable encoded texture container accepted by a render device. +/// +public enum RenderTextureContainer +{ + /// + /// Khronos Texture container containing validated GPU texture payloads. + /// + Ktx +} diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs index 8cf9269d0..87cfbfb39 100644 --- a/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs @@ -33,8 +33,8 @@ public PersistentBufferDescriptor( } if ((buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - == (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - { + == (RenderBufferUsage.Vertex | RenderBufferUsage.Index) + ) { throw new ArgumentException("A buffer cannot be both vertex and index input.", nameof(buffer)); } @@ -50,8 +50,8 @@ public PersistentBufferDescriptor( int expectedIndexStride = indexFormat == RenderIndexFormat.UInt16 ? 2 : 4; if ((buffer.usage & RenderBufferUsage.Index) != 0 - && buffer.elementStride != expectedIndexStride) - { + && buffer.elementStride != expectedIndexStride + ) { throw new ArgumentException("Index format must match buffer element stride.", nameof(indexFormat)); } @@ -75,4 +75,3 @@ public PersistentBufferDescriptor( /// public RenderIndexFormat indexFormat { get; } } - diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs b/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs new file mode 100644 index 000000000..bfc12f46b --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent device buffer without exposing a backend-native handle. +/// +public readonly record struct PersistentBufferHandle +{ + internal PersistentBufferHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device buffer. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs b/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs new file mode 100644 index 000000000..c2c99c47d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent device texture without exposing a backend-native handle. +/// +public readonly record struct PersistentTextureHandle +{ + internal PersistentTextureHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device texture. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs index 736252934..030a9ae8c 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs @@ -22,7 +22,9 @@ internal sealed class RecordedRenderCommandBuffer : IDisposable public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; byte[] bytes = m_bytes; object?[] references = m_references; @@ -31,9 +33,13 @@ public void Dispose() m_length = 0; m_referenceCount = 0; if (bytes.Length != 0) + { ArrayPool.Shared.Return(bytes); + } if (references.Length != 0) + { ArrayPool.Shared.Return(references, clearArray: true); + } } internal Reader GetReader() @@ -43,7 +49,8 @@ internal Reader GetReader() } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void Write(T value) where T : unmanaged + internal void Write(T value) + where T : unmanaged { int size = Unsafe.SizeOf(); EnsureCapacity(size); @@ -55,7 +62,8 @@ internal void Write(T value) where T : unmanaged internal void WriteInstruction( byte operation, T value - ) where T : unmanaged { + ) where T : unmanaged + { int size = Unsafe.SizeOf(); EnsureCapacity(checked(size + 1)); m_bytes[m_length] = operation; @@ -68,10 +76,13 @@ internal void WriteReference(object? value) if (m_referenceCount == m_references.Length) { object?[] next = ArrayPool.Shared.Rent( - m_references.Length == 0 ? C_INITIAL_REFERENCE_CAPACITY : checked(m_references.Length * 2)); + m_references.Length == 0 ? C_INITIAL_REFERENCE_CAPACITY : checked(m_references.Length * 2) + ); m_references.AsSpan(0, m_referenceCount).CopyTo(next); if (m_references.Length != 0) + { ArrayPool.Shared.Return(m_references, clearArray: true); + } m_references = next; } Write(m_referenceCount); @@ -94,7 +105,9 @@ private void EnsureCapacity(int additionalBytes) ObjectDisposedException.ThrowIf(m_disposed, this); int required = checked(m_length + additionalBytes); if (required > m_bytes.Length) + { Grow(required); + } } private void Grow(int required) @@ -103,7 +116,9 @@ private void Grow(int required) byte[] next = ArrayPool.Shared.Rent(Math.Max(required, capacity)); m_bytes.AsSpan(0, m_length).CopyTo(next); if (m_bytes.Length != 0) + { ArrayPool.Shared.Return(m_bytes); + } m_bytes = next; } @@ -124,7 +139,8 @@ internal Reader( internal readonly bool hasCommands => m_position < m_bytes.Length; [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal T Read() where T : unmanaged + internal T Read() + where T : unmanaged { int size = Unsafe.SizeOf(); T value = MemoryMarshal.Read(m_bytes.Slice(m_position, size)); @@ -132,12 +148,13 @@ internal T Read() where T : unmanaged return value; } - internal T? ReadReference() where T : class => (T?)m_references[Read()]; + internal T? ReadReference() + where T : class => (T?)m_references[Read()]; - internal RenderBindingId ReadBinding() + internal RenderBindingID ReadBinding() { string? value = ReadReference(); - return value is null ? default : new RenderBindingId(value); + return value is null ? default : new RenderBindingID(value); } internal ReadOnlySpan ReadSnapshot() diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs index 705f54531..5c03114d6 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs @@ -11,7 +11,9 @@ internal void Replay(RenderCommandEncoder destination) { ArgumentNullException.ThrowIfNull(destination); if (!m_sealed) + { throw new InvalidOperationException("A render command list must be sealed before replay."); + } RecordedRenderCommandBuffer.Reader reader = m_buffer.GetReader(); while (reader.hasCommands) { @@ -27,40 +29,38 @@ internal void Replay(RenderCommandEncoder destination) destination.BindTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindTexturePersistent: destination.BindTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindStorageTextureGraph: destination.BindStorageTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindStorageTexturePersistent: destination.BindStorageTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindBufferGraph: - destination.BindBuffer( - reader.ReadBinding(), - reader.Read()); + destination.BindBuffer(reader.ReadBinding(), reader.Read()); break; case Operation.BindBufferPersistent: - destination.BindBuffer( - reader.ReadBinding(), - reader.Read()); + destination.BindBuffer(reader.ReadBinding(), reader.Read()); break; case Operation.SetUniform: - destination.SetUniform( - reader.ReadBinding(), - reader.ReadSnapshot()); + destination.SetUniform(reader.ReadBinding(), reader.ReadSnapshot()); break; case Operation.SetTransform: destination.SetTransform(MemoryMarshal.Cast(reader.ReadSnapshot())); @@ -76,111 +76,95 @@ internal void Replay(RenderCommandEncoder destination) reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.SetScissor: destination.SetScissor( reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindVertexBufferGraph: - destination.BindVertexBuffer( - reader.Read(), - reader.Read()); + destination.BindVertexBuffer(reader.Read(), reader.Read()); break; case Operation.BindVertexBufferPersistent: - destination.BindVertexBuffer( - reader.Read(), - reader.Read()); + destination.BindVertexBuffer(reader.Read(), reader.Read()); break; case Operation.BindIndexBufferGraph: - destination.BindIndexBuffer( - reader.Read(), - reader.Read()); + destination.BindIndexBuffer(reader.Read(), reader.Read()); break; case Operation.BindIndexBufferPersistent: - destination.BindIndexBuffer( - reader.Read(), - reader.Read()); + destination.BindIndexBuffer(reader.Read(), reader.Read()); break; case Operation.BindInstanceBufferGraph: destination.BindInstanceBuffer( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindInstanceBufferPersistent: destination.BindInstanceBuffer( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.Draw: DrawArguments draw = reader.Read(); - destination.Draw( - draw.count, - draw.instanceCount); + destination.Draw(draw.count, draw.instanceCount); break; case Operation.DrawProcedural: DrawArguments procedural = reader.Read(); - destination.DrawProcedural( - procedural.count, - procedural.instanceCount); + destination.DrawProcedural(procedural.count, procedural.instanceCount); break; case Operation.DrawIndexed: DrawArguments indexed = reader.Read(); - destination.DrawIndexed( - indexed.count, - indexed.instanceCount); + destination.DrawIndexed(indexed.count, indexed.instanceCount); break; case Operation.DrawIndirectGraph: - destination.DrawIndirect( - reader.Read(), - reader.Read(), - reader.Read()); + destination.DrawIndirect(reader.Read(), reader.Read(), reader.Read()); break; case Operation.DrawIndirectPersistent: destination.DrawIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.Dispatch: - destination.Dispatch( - reader.Read(), - reader.Read(), - reader.Read()); + destination.Dispatch(reader.Read(), reader.Read(), reader.Read()); break; case Operation.DispatchIndirectGraph: destination.DispatchIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.DispatchIndirectPersistent: destination.DispatchIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.CopyTextureGraph: - destination.CopyTexture( - reader.Read(), - reader.Read()); + destination.CopyTexture(reader.Read(), reader.Read()); break; case Operation.BlitTextureGraph: destination.BlitTexture( reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.CopyBufferGraph: - destination.CopyBuffer( - reader.Read(), - reader.Read()); + destination.CopyBuffer(reader.Read(), reader.Read()); break; default: throw new InvalidOperationException("A recorded render command has an invalid operation."); diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs index c204ff1fd..fa58689b8 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs @@ -18,23 +18,23 @@ public void Dispose() m_buffer.Dispose(); } - /// + /// public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) { Begin(Operation.BindGraphicsPipeline); m_buffer.Write(pipeline); } - /// + /// public override void BindComputePipeline(ComputePipelineHandle pipeline) { Begin(Operation.BindComputePipeline); m_buffer.Write(pipeline); } - /// + /// public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, RenderSamplerState sampler ) { @@ -44,9 +44,9 @@ RenderSamplerState sampler m_buffer.Write(sampler); } - /// + /// public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, RenderSamplerState sampler ) { @@ -56,9 +56,9 @@ RenderSamplerState sampler m_buffer.Write(sampler); } - /// + /// public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, int mipLevel = 0 ) { @@ -68,9 +68,9 @@ public override void BindStorageTexture( m_buffer.Write(mipLevel); } - /// + /// public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, int mipLevel = 0 ) { @@ -80,9 +80,9 @@ public override void BindStorageTexture( m_buffer.Write(mipLevel); } - /// + /// public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, RenderBufferHandle buffer ) { Begin(Operation.BindBufferGraph); @@ -90,9 +90,9 @@ RenderBufferHandle buffer m_buffer.Write(buffer); } - /// + /// public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, PersistentBufferHandle buffer ) { Begin(Operation.BindBufferPersistent); @@ -100,12 +100,12 @@ PersistentBufferHandle buffer m_buffer.Write(buffer); } - /// /// /// Copies the borrowed uniform bytes into this recording before returning. /// + /// public override void SetUniform( - RenderBindingId binding, + RenderBindingID binding, ReadOnlySpan value ) { Begin(Operation.SetUniform); @@ -113,17 +113,17 @@ ReadOnlySpan value m_buffer.WriteSnapshot(value); } - /// /// /// Copies the borrowed matrix values into this recording before returning. /// + /// public override void SetTransform(ReadOnlySpan columnMajorMatrix) { Begin(Operation.SetTransform); m_buffer.WriteSnapshot(MemoryMarshal.AsBytes(columnMajorMatrix)); } - /// + /// public override void SetRasterState(RenderRasterState state) { ArgumentNullException.ThrowIfNull(state); @@ -131,7 +131,7 @@ public override void SetRasterState(RenderRasterState state) m_buffer.WriteReference(state); } - /// + /// public override void SetStencil(RenderStencilState state) { ArgumentNullException.ThrowIfNull(state); @@ -139,7 +139,7 @@ public override void SetStencil(RenderStencilState state) m_buffer.WriteReference(state); } - /// + /// public override void SetViewport( int x, int y, @@ -153,7 +153,7 @@ int height m_buffer.Write(height); } - /// + /// public override void SetScissor( int x, int y, @@ -167,7 +167,7 @@ int height m_buffer.Write(height); } - /// + /// public override void BindVertexBuffer( RenderBufferHandle buffer, int firstVertex = 0 @@ -177,7 +177,7 @@ public override void BindVertexBuffer( m_buffer.Write(firstVertex); } - /// + /// public override void BindVertexBuffer( PersistentBufferHandle buffer, int firstVertex = 0 @@ -187,7 +187,7 @@ public override void BindVertexBuffer( m_buffer.Write(firstVertex); } - /// + /// public override void BindIndexBuffer( RenderBufferHandle buffer, int firstIndex = 0 @@ -197,7 +197,7 @@ public override void BindIndexBuffer( m_buffer.Write(firstIndex); } - /// + /// public override void BindIndexBuffer( PersistentBufferHandle buffer, int firstIndex = 0 @@ -207,7 +207,7 @@ public override void BindIndexBuffer( m_buffer.Write(firstIndex); } - /// + /// public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, @@ -219,7 +219,7 @@ int instanceCount m_buffer.Write(instanceCount); } - /// + /// public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, @@ -231,34 +231,28 @@ int instanceCount m_buffer.Write(instanceCount); } - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void Draw( int vertexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.Draw, vertexCount, instanceCount); - } + ) => RecordDraw(Operation.Draw, vertexCount, instanceCount); - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void DrawProcedural( int vertexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.DrawProcedural, vertexCount, instanceCount); - } + ) => RecordDraw(Operation.DrawProcedural, vertexCount, instanceCount); - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void DrawIndexed( int indexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.DrawIndexed, indexCount, instanceCount); - } + ) => RecordDraw(Operation.DrawIndexed, indexCount, instanceCount); - /// + /// public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, @@ -270,7 +264,7 @@ public override void DrawIndirect( m_buffer.Write(commandCount); } - /// + /// public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, @@ -282,7 +276,7 @@ public override void DrawIndirect( m_buffer.Write(commandCount); } - /// + /// public override void Dispatch( int groupCountX, int groupCountY = 1, @@ -294,7 +288,7 @@ public override void Dispatch( m_buffer.Write(groupCountZ); } - /// + /// public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, @@ -306,7 +300,7 @@ public override void DispatchIndirect( m_buffer.Write(commandCount); } - /// + /// public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, @@ -318,7 +312,7 @@ public override void DispatchIndirect( m_buffer.Write(commandCount); } - /// + /// public override void CopyTexture( RenderTextureHandle source, RenderTextureHandle destination @@ -328,7 +322,7 @@ RenderTextureHandle destination m_buffer.Write(destination); } - /// + /// public override void BlitTexture( RenderTextureHandle source, RenderTextureRegion sourceRegion, @@ -342,7 +336,7 @@ RenderTextureRegion destinationRegion m_buffer.Write(destinationRegion); } - /// + /// public override void CopyBuffer( RenderBufferHandle source, RenderBufferHandle destination @@ -375,7 +369,8 @@ int instanceCount private void EnsureWritable() { if (m_sealed) + { throw new InvalidOperationException("A recorded render command list is already sealed."); + } } - } diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs b/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs new file mode 100644 index 000000000..6dd4f7175 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs @@ -0,0 +1,31 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies a shader binding by stable manifest name. +/// +public readonly record struct RenderBindingID +{ + /// + /// Creates a stable shader binding identifier. + /// + /// + /// Stable manifest binding name. + /// + public RenderBindingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the stable manifest binding name. + /// + public string value { get; } + + /// + /// Gets whether the identifier contains a stable manifest name. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs index b2a4e20ab..19c7e773a 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs @@ -1,95 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects one source or destination blend multiplier. -/// -public enum RenderBlendFactor -{ - /// - /// Multiplies by zero. - /// - Zero, - /// - /// Multiplies by one. - /// - One, - /// - /// Multiplies by source color. - /// - SourceColor, - /// - /// Multiplies by one minus source color. - /// - InverseSourceColor, - /// - /// Multiplies by source alpha. - /// - SourceAlpha, - /// - /// Multiplies by one minus source alpha. - /// - InverseSourceAlpha, - /// - /// Multiplies by destination alpha. - /// - DestinationAlpha, - /// - /// Multiplies by one minus destination alpha. - /// - InverseDestinationAlpha, - /// - /// Multiplies by destination color. - /// - DestinationColor, - /// - /// Multiplies by one minus destination color. - /// - InverseDestinationColor, - /// - /// Uses the saturated source-alpha factor. - /// - SourceAlphaSaturate, - /// - /// Multiplies by the packed constant blend color. - /// - Constant, - /// - /// Multiplies by one minus the packed constant blend color. - /// - InverseConstant -} - -/// -/// Selects the arithmetic operation combining source and destination blend terms. -/// -public enum RenderBlendEquation -{ - /// - /// Adds source and destination terms. - /// - Add, - /// - /// Subtracts the destination term from the source term. - /// - Subtract, - /// - /// Subtracts the source term from the destination term. - /// - ReverseSubtract, - /// - /// Selects the component-wise minimum. - /// - Minimum, - /// - /// Selects the component-wise maximum. - /// - Maximum -} - /// /// Describes independent color and alpha blending without backend-native flags. /// @@ -98,7 +8,8 @@ public struct RenderBlendState /// /// Gets the disabled opaque blend state. /// - public static RenderBlendState opaque => new() + public static RenderBlendState opaque + => new() { enabled = false, colorSource = RenderBlendFactor.One, @@ -110,7 +21,8 @@ public struct RenderBlendState /// /// Gets conventional straight-alpha blending. /// - public static RenderBlendState alpha => new() + public static RenderBlendState alpha + => new() { enabled = true, colorSource = RenderBlendFactor.SourceAlpha, @@ -122,7 +34,8 @@ public struct RenderBlendState /// /// Gets additive source-alpha blending. /// - public static RenderBlendState additive => new() + public static RenderBlendState additive + => new() { enabled = true, colorSource = RenderBlendFactor.SourceAlpha, @@ -134,7 +47,8 @@ public struct RenderBlendState /// /// Gets conventional premultiplied-alpha blending. /// - public static RenderBlendState premultiplied => new() + public static RenderBlendState premultiplied + => new() { enabled = true, colorSource = RenderBlendFactor.One, @@ -189,3 +103,88 @@ public struct RenderBlendState public bool alphaToCoverage { get; set; } } +/// +/// Selects one source or destination blend multiplier. +/// +public enum RenderBlendFactor +{ + /// + /// Multiplies by zero. + /// + Zero, + /// + /// Multiplies by one. + /// + One, + /// + /// Multiplies by source color. + /// + SourceColor, + /// + /// Multiplies by one minus source color. + /// + InverseSourceColor, + /// + /// Multiplies by source alpha. + /// + SourceAlpha, + /// + /// Multiplies by one minus source alpha. + /// + InverseSourceAlpha, + /// + /// Multiplies by destination alpha. + /// + DestinationAlpha, + /// + /// Multiplies by one minus destination alpha. + /// + InverseDestinationAlpha, + /// + /// Multiplies by destination color. + /// + DestinationColor, + /// + /// Multiplies by one minus destination color. + /// + InverseDestinationColor, + /// + /// Uses the saturated source-alpha factor. + /// + SourceAlphaSaturate, + /// + /// Multiplies by the packed constant blend color. + /// + Constant, + /// + /// Multiplies by one minus the packed constant blend color. + /// + InverseConstant +} + +/// +/// Selects the arithmetic operation combining source and destination blend terms. +/// +public enum RenderBlendEquation +{ + /// + /// Adds source and destination terms. + /// + Add, + /// + /// Subtracts the destination term from the source term. + /// + Subtract, + /// + /// Subtracts the source term from the destination term. + /// + ReverseSubtract, + /// + /// Selects the component-wise minimum. + /// + Minimum, + /// + /// Selects the component-wise maximum. + /// + Maximum +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs new file mode 100644 index 000000000..04fc0067f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs @@ -0,0 +1,82 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes a render-graph buffer independently from a graphics backend. +/// +public sealed class RenderBufferDescriptor : IEquatable +{ + /// + /// Creates a buffer descriptor. + /// + /// + /// Number of addressable elements. + /// + /// + /// Element size in bytes. + /// + /// + /// Permitted operations. + /// + public RenderBufferDescriptor( + int elementCount, + int elementStride, + RenderBufferUsage usage + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); + this.elementCount = elementCount; + this.elementStride = elementStride; + this.usage = usage; + } + + /// + /// Gets the number of addressable elements. + /// + public int elementCount { get; } + + /// + /// Gets the element size in bytes. + /// + public int elementStride { get; } + + /// + /// Gets permitted operations. + /// + public RenderBufferUsage usage { get; } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderBufferDescriptor? other) + => other is not null + && elementCount == other.elementCount + && elementStride == other.elementStride + && usage == other.usage; + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderBufferDescriptor); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() => HashCode.Combine(elementCount, elementStride, usage); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs new file mode 100644 index 000000000..96e80f674 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering; + +/// +/// Identifies a frame-scoped render-graph buffer. +/// +public readonly record struct RenderBufferHandle +{ + internal RenderBufferHandle( + int index, + uint generation, + ulong allocationID + ) { + this.index = index; + this.generation = generation; + this.allocationID = allocationID; + } + + internal int index { get; } + internal uint generation { get; } + internal ulong allocationID { get; } + + /// + /// Gets whether the handle was created by a render graph. + /// + public bool isValid => index >= 0 && generation != 0 && allocationID != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs new file mode 100644 index 000000000..09afb84db --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs @@ -0,0 +1,44 @@ +namespace Inno.Rendering; + +/// +/// Identifies one range in a frame upload page without exposing its persistent backing buffer. +/// +public readonly record struct RenderBufferSlice +{ + internal RenderBufferSlice( + PersistentBufferHandle buffer, + int firstElement, + int elementCount, + RenderBufferUsage usage, + ulong frameIndex + ) { + this.buffer = buffer; + this.firstElement = firstElement; + this.elementCount = elementCount; + this.usage = usage; + this.frameIndex = frameIndex; + } + + internal PersistentBufferHandle buffer { get; } + internal ulong frameIndex { get; } + + /// + /// Gets the first uploaded element in the backing frame page. + /// + public int firstElement { get; } + + /// + /// Gets the number of uploaded elements. + /// + public int elementCount { get; } + + /// + /// Gets permitted GPU uses for this slice. + /// + public RenderBufferUsage usage { get; } + + /// + /// Gets whether this slice was produced by a frame upload service. + /// + public bool isValid => buffer.isValid && elementCount > 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs similarity index 51% rename from src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs rename to src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs index 663aa0459..88ae2a69f 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs @@ -30,26 +30,30 @@ public RenderBufferUploadDescriptor( ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); RenderBufferUsage allowed = RenderBufferUsage.Vertex - | RenderBufferUsage.Index - | RenderBufferUsage.Storage; + | RenderBufferUsage.Index + | RenderBufferUsage.Storage; if (usage == 0 || (usage & ~allowed) != 0) { - throw new ArgumentException( - "Frame uploads support vertex, index, and storage usage only.", - nameof(usage)); + throw new ArgumentException("Frame uploads support vertex, index, and storage usage only.", nameof(usage)); } if ((usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - == (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - { + == (RenderBufferUsage.Vertex | RenderBufferUsage.Index) + ) { throw new ArgumentException("An upload cannot be both vertex and index input.", nameof(usage)); } if ((usage & RenderBufferUsage.Vertex) != 0 && vertexLayout is null) + { throw new ArgumentException("Vertex uploads require an interleaved layout.", nameof(vertexLayout)); + } if (vertexLayout is not null && vertexLayout.stride != elementStride) + { throw new ArgumentException("Vertex layout stride must match element stride.", nameof(vertexLayout)); + } int indexStride = indexFormat == RenderIndexFormat.UInt16 ? 2 : 4; if ((usage & RenderBufferUsage.Index) != 0 && indexStride != elementStride) + { throw new ArgumentException("Index format must match element stride.", nameof(indexFormat)); + } this.elementStride = elementStride; this.usage = usage; @@ -77,82 +81,3 @@ public RenderBufferUploadDescriptor( /// public RenderIndexFormat indexFormat { get; } } - -/// -/// Identifies one range in a frame upload page without exposing its persistent backing buffer. -/// -public readonly record struct RenderBufferSlice -{ - internal RenderBufferSlice( - PersistentBufferHandle buffer, - int firstElement, - int elementCount, - RenderBufferUsage usage, - ulong frameIndex - ) { - this.buffer = buffer; - this.firstElement = firstElement; - this.elementCount = elementCount; - this.usage = usage; - this.frameIndex = frameIndex; - } - - internal PersistentBufferHandle buffer { get; } - internal ulong frameIndex { get; } - - /// - /// Gets the first uploaded element in the backing frame page. - /// - public int firstElement { get; } - - /// - /// Gets the number of uploaded elements. - /// - public int elementCount { get; } - - /// - /// Gets permitted GPU uses for this slice. - /// - public RenderBufferUsage usage { get; } - - /// - /// Gets whether this slice was produced by a frame upload service. - /// - public bool isValid => buffer.isValid && elementCount > 0; -} - -/// -/// Provides protected slice construction for replaceable frame-upload service implementations. -/// -public abstract class RenderFrameUploadProvider -{ - /// - /// Creates a frame-scoped slice over a provider-owned persistent upload buffer. - /// - /// - /// The persistent upload page backing the slice. - /// - /// - /// The zero-based first uploaded element. - /// - /// - /// The positive number of uploaded elements. - /// - /// - /// The GPU uses supported by the uploaded range. - /// - /// - /// The render frame during which the slice remains valid. - /// - /// - /// An opaque frame-scoped buffer slice. - /// - protected static RenderBufferSlice CreateBufferSlice( - PersistentBufferHandle buffer, - int firstElement, - int elementCount, - RenderBufferUsage usage, - ulong frameIndex - ) - => new(buffer, firstElement, elementCount, usage, frameIndex); -} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs new file mode 100644 index 000000000..ced61e6e3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs @@ -0,0 +1,43 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Declares intended buffer operations for capability and hazard validation. +/// +[Flags] +public enum RenderBufferUsage +{ + /// + /// Vertex input data. + /// + Vertex = 1 << 0, + /// + /// Index input data. + /// + Index = 1 << 1, + /// + /// Read-only shader data. + /// + Uniform = 1 << 2, + /// + /// Shader-readable and writable storage data. + /// + Storage = 1 << 3, + /// + /// Indirect command data. + /// + Indirect = 1 << 4, + /// + /// Copy operation source. + /// + CopySource = 1 << 5, + /// + /// Copy operation destination. + /// + CopyDestination = 1 << 6, + /// + /// Contents may be replaced at frame safety points. + /// + Dynamic = 1 << 7 +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs b/src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs similarity index 75% rename from src/services/rendering/Inno.Rendering/Device/RenderCommands.cs rename to src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs index 2f00b5dd2..89b9c1585 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs @@ -2,168 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies a shader binding by stable manifest name. -/// -public readonly record struct RenderBindingId -{ - /// - /// Creates a stable shader binding identifier. - /// - /// - /// Stable manifest binding name. - /// - public RenderBindingId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the stable manifest binding name. - /// - public string value { get; } - - /// - /// Gets whether the identifier contains a stable manifest name. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); -} - -/// -/// Identifies a backend-neutral graphics pipeline object. -/// -public readonly record struct GraphicsPipelineHandle -{ - internal GraphicsPipelineHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a graphics pipeline. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a backend-neutral compute pipeline object. -/// -public readonly record struct ComputePipelineHandle -{ - internal ComputePipelineHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a compute pipeline. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Describes one texture subresource box for copy and blit commands. -/// -public readonly record struct RenderTextureRegion -{ - /// - /// Creates a texture subresource box. - /// - /// - /// Zero-based mip level. - /// - /// - /// Horizontal texel origin. - /// - /// - /// Vertical texel origin. - /// - /// - /// Array layer or depth-slice origin. - /// - /// - /// Positive texel width. - /// - /// - /// Positive texel height. - /// - /// - /// Positive layer or depth-slice count. - /// - public RenderTextureRegion( - int mip, - int x, - int y, - int layer, - int width, - int height, - int depth = 1 - ) { - ArgumentOutOfRangeException.ThrowIfNegative(mip); - ArgumentOutOfRangeException.ThrowIfNegative(x); - ArgumentOutOfRangeException.ThrowIfNegative(y); - ArgumentOutOfRangeException.ThrowIfNegative(layer); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); - this.mip = mip; - this.x = x; - this.y = y; - this.layer = layer; - this.width = width; - this.height = height; - this.depth = depth; - } - - /// - /// Gets the zero-based mip level. - /// - public int mip { get; } - - /// - /// Gets the horizontal texel origin. - /// - public int x { get; } - - /// - /// Gets the vertical texel origin. - /// - public int y { get; } - - /// - /// Gets the array layer or depth-slice origin. - /// - public int layer { get; } - - /// - /// Gets the texel width. - /// - public int width { get; } - - /// - /// Gets the texel height. - /// - public int height { get; } - - /// - /// Gets the layer or depth-slice count. - /// - public int depth { get; } -} - /// /// Provides backend-neutral draw, dispatch and copy commands for one compiled pass. /// @@ -198,10 +36,23 @@ public abstract class RenderCommandEncoder /// Graph texture to bind. /// public void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture - ) - => BindTexture(binding, texture, RenderSamplerState.linearClamp); + ) => BindTexture(binding, texture, RenderSamplerState.linearClamp); + + /// + /// Binds a persistent texture to a shader interface slot. + /// + /// + /// Stable shader binding identifier. + /// + /// + /// Persistent texture owned by the active device generation. + /// + public void BindTexture( + RenderBindingID binding, + PersistentTextureHandle texture + ) => BindTexture(binding, texture, RenderSamplerState.linearClamp); /// /// Binds a sampled texture and its sampler to a shader binding. @@ -216,26 +67,11 @@ RenderTextureHandle texture /// Sampling state copied by value. /// public abstract void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, RenderSamplerState sampler ); - /// - /// Binds a persistent texture to a shader interface slot. - /// - /// - /// Stable shader binding identifier. - /// - /// - /// Persistent texture owned by the active device generation. - /// - public void BindTexture( - RenderBindingId binding, - PersistentTextureHandle texture - ) - => BindTexture(binding, texture, RenderSamplerState.linearClamp); - /// /// Binds a sampled texture and its sampler to a shader binding. /// @@ -249,7 +85,7 @@ PersistentTextureHandle texture /// Sampling state copied by value. /// public abstract void BindTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, RenderSamplerState sampler ); @@ -267,7 +103,7 @@ RenderSamplerState sampler /// Zero-based mip level used for storage access. /// public abstract void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, int mipLevel = 0 ); @@ -285,7 +121,7 @@ public abstract void BindStorageTexture( /// Zero-based mip level used for storage access. /// public abstract void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, int mipLevel = 0 ); @@ -300,7 +136,7 @@ public abstract void BindStorageTexture( /// Frame-scoped buffer owned by the current graph generation. /// public abstract void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, RenderBufferHandle buffer ); @@ -314,7 +150,7 @@ RenderBufferHandle buffer /// Persistent buffer owned by the current device generation. /// public abstract void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, PersistentBufferHandle buffer ); @@ -328,7 +164,7 @@ PersistentBufferHandle buffer /// Current-frame storage slice. /// public void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, RenderBufferSlice buffer ) { ValidateSlice(buffer, RenderBufferUsage.Storage); @@ -336,7 +172,8 @@ RenderBufferSlice buffer { throw new ArgumentException( "Storage upload slices must begin at the first backing element.", - nameof(buffer)); + nameof(buffer) + ); } BindBuffer(binding, buffer.buffer); } @@ -351,7 +188,7 @@ RenderBufferSlice buffer /// Bytes borrowed for this call. An encoder that defers execution must copy them before returning. /// public abstract void SetUniform( - RenderBindingId binding, + RenderBindingID binding, ReadOnlySpan value ); @@ -423,6 +260,18 @@ public abstract void SetScissor( int height ); + /// + /// Binds a frame-uploaded vertex slice. + /// + /// + /// Current-frame vertex slice. + /// + public void BindVertexBuffer(RenderBufferSlice buffer) + { + ValidateSlice(buffer, RenderBufferUsage.Vertex); + BindVertexBuffer(buffer.buffer, buffer.firstElement); + } + /// /// Selects a vertex buffer and its first vertex for subsequent draws. /// @@ -452,15 +301,15 @@ public abstract void BindVertexBuffer( ); /// - /// Binds a frame-uploaded vertex slice. + /// Binds a frame-uploaded index slice. /// /// - /// Current-frame vertex slice. + /// Current-frame index slice. /// - public void BindVertexBuffer(RenderBufferSlice buffer) + public void BindIndexBuffer(RenderBufferSlice buffer) { - ValidateSlice(buffer, RenderBufferUsage.Vertex); - BindVertexBuffer(buffer.buffer, buffer.firstElement); + ValidateSlice(buffer, RenderBufferUsage.Index); + BindIndexBuffer(buffer.buffer, buffer.firstElement); } /// @@ -492,15 +341,15 @@ public abstract void BindIndexBuffer( ); /// - /// Binds a frame-uploaded index slice. + /// Binds a frame-uploaded vertex slice as per-instance input. /// /// - /// Current-frame index slice. + /// Current-frame instance records. /// - public void BindIndexBuffer(RenderBufferSlice buffer) + public void BindInstanceBuffer(RenderBufferSlice buffer) { - ValidateSlice(buffer, RenderBufferUsage.Index); - BindIndexBuffer(buffer.buffer, buffer.firstElement); + ValidateSlice(buffer, RenderBufferUsage.Vertex); + BindInstanceBuffer(buffer.buffer, buffer.firstElement, buffer.elementCount); } /// @@ -539,18 +388,6 @@ public abstract void BindInstanceBuffer( int instanceCount ); - /// - /// Binds a frame-uploaded vertex slice as per-instance input. - /// - /// - /// Current-frame instance records. - /// - public void BindInstanceBuffer(RenderBufferSlice buffer) - { - ValidateSlice(buffer, RenderBufferUsage.Vertex); - BindInstanceBuffer(buffer.buffer, buffer.firstElement, buffer.elementCount); - } - /// /// Submits a draw using the currently bound pipeline and resources. /// @@ -744,59 +581,22 @@ private void ValidateSlice( RenderBufferUsage requiredUsage ) { if (!buffer.isValid) + { throw new ArgumentException("A frame buffer slice must be valid.", nameof(buffer)); + } if (!m_hasFrameIndex || buffer.frameIndex != m_frameIndex) { throw new ArgumentException( "A frame buffer slice cannot be used outside the frame that uploaded it.", - nameof(buffer)); + nameof(buffer) + ); } if ((buffer.usage & requiredUsage) == 0) { throw new ArgumentException( $"The frame buffer slice does not declare {requiredUsage} usage.", - nameof(buffer)); + nameof(buffer) + ); } } } - -/// -/// Supplies the command encoder and immutable frame identity to a pass callback. -/// -public sealed class RenderPassContext -{ - internal RenderPassContext( - RenderCommandEncoder commands, - ulong frameIndex - ) { - this.commands = commands; - this.frameIndex = frameIndex; - } - - /// - /// Gets the command encoder scoped to the current pass. - /// - public RenderCommandEncoder commands { get; } - - /// - /// Gets the monotonic frame index. - /// - public ulong frameIndex { get; } -} - -/// -/// Executes one frame-scoped pass payload. -/// -/// -/// Neutral pass payload type. -/// -/// -/// Pass payload captured for this frame only. -/// -/// -/// Current pass execution context. -/// -public delegate void RenderPassExecute( - TPassData passData, - RenderPassContext context -); diff --git a/src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs b/src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs new file mode 100644 index 000000000..c05f86ec9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies one pipeline-owned frame-data channel without constraining its payload model. +/// +public readonly record struct RenderDataChannelID +{ + /// + /// Creates an open frame-data channel identifier. + /// + /// + /// Globally stable channel protocol value. + /// + public RenderDataChannelID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether the identifier contains a protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderDevice.cs b/src/services/rendering/Inno.Rendering/Device/RenderDevice.cs index e4900f7ac..196175379 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderDevice.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderDevice.cs @@ -9,34 +9,6 @@ namespace Inno.Rendering; /// public abstract class RenderDevice { - /// - /// Stores one decoded persistent device identity for use inside a concrete backend. - /// - /// - /// The backend-owned non-zero resource identity. - /// - /// - /// The device generation that owns the resource. - /// - protected readonly record struct DeviceHandleIdentity( - ulong value, - uint generation - ); - - /// - /// Stores one decoded frame-scoped graph identity for use inside a concrete backend. - /// - /// - /// The zero-based logical resource index. - /// - /// - /// The render-graph generation that owns the resource. - /// - protected readonly record struct GraphHandleIdentity( - int index, - uint generation - ); - /// /// Encodes a persistent texture identity into a backend-neutral handle. /// @@ -227,4 +199,32 @@ protected static DeviceHandleIdentity GetHandleIdentity(RenderTextureReadbackHan /// The graph resource index and owning graph generation. /// protected static GraphHandleIdentity GetHandleIdentity(RenderBufferHandle handle) => new(handle.index, handle.generation); + + /// + /// Stores one decoded persistent device identity for use inside a concrete backend. + /// + /// + /// The backend-owned non-zero resource identity. + /// + /// + /// The device generation that owns the resource. + /// + protected readonly record struct DeviceHandleIdentity( + ulong value, + uint generation + ); + + /// + /// Stores one decoded frame-scoped graph identity for use inside a concrete backend. + /// + /// + /// The zero-based logical resource index. + /// + /// + /// The render-graph generation that owns the resource. + /// + protected readonly record struct GraphHandleIdentity( + int index, + uint generation + ); } diff --git a/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs b/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs new file mode 100644 index 000000000..0ccc561a2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Contains backend-recorded GPU command submissions for the current frame. +/// +public readonly record struct RenderDeviceFrameCounters +{ + /// + /// Creates immutable device frame counters. + /// + /// + /// Direct and indirect draw commands submitted so far. + /// + /// + /// Direct and indirect compute dispatches submitted so far. + /// + public RenderDeviceFrameCounters( + int drawCount, + int dispatchCount + ) { + ArgumentOutOfRangeException.ThrowIfNegative(drawCount); + ArgumentOutOfRangeException.ThrowIfNegative(dispatchCount); + this.drawCount = drawCount; + this.dispatchCount = dispatchCount; + } + + /// + /// Gets direct and indirect draw commands submitted during the current frame. + /// + public int drawCount { get; } + + /// + /// Gets direct and indirect compute dispatches submitted during the current frame. + /// + public int dispatchCount { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs b/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs new file mode 100644 index 000000000..35cefb0d4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs @@ -0,0 +1,36 @@ +namespace Inno.Rendering; + +/// +/// Provides protected slice construction for replaceable frame-upload service implementations. +/// +public abstract class RenderFrameUploadProvider +{ + /// + /// Creates a frame-scoped slice over a provider-owned persistent upload buffer. + /// + /// + /// The persistent upload page backing the slice. + /// + /// + /// The zero-based first uploaded element. + /// + /// + /// The positive number of uploaded elements. + /// + /// + /// The GPU uses supported by the uploaded range. + /// + /// + /// The render frame during which the slice remains valid. + /// + /// + /// An opaque frame-scoped buffer slice. + /// + protected static RenderBufferSlice CreateBufferSlice( + PersistentBufferHandle buffer, + int firstElement, + int elementCount, + RenderBufferUsage usage, + ulong frameIndex + ) => new(buffer, firstElement, elementCount, usage, frameIndex); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs b/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs new file mode 100644 index 000000000..d607b7617 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs @@ -0,0 +1,25 @@ +namespace Inno.Rendering; + +/// +/// Supplies the command encoder and immutable frame identity to a pass callback. +/// +public sealed class RenderPassContext +{ + internal RenderPassContext( + RenderCommandEncoder commands, + ulong frameIndex + ) { + this.commands = commands; + this.frameIndex = frameIndex; + } + + /// + /// Gets the command encoder scoped to the current pass. + /// + public RenderCommandEncoder commands { get; } + + /// + /// Gets the monotonic frame index. + /// + public ulong frameIndex { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs b/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs new file mode 100644 index 000000000..39c809f54 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs @@ -0,0 +1,18 @@ +namespace Inno.Rendering; + +/// +/// Executes one frame-scoped pass payload. +/// +/// +/// Neutral pass payload type. +/// +/// +/// Pass payload captured for this frame only. +/// +/// +/// Current pass execution context. +/// +public delegate void RenderPassExecute( + TPassData passData, + RenderPassContext context +); diff --git a/src/services/rendering/Inno.Rendering/Device/RenderProtocolIds.cs b/src/services/rendering/Inno.Rendering/Device/RenderProtocolIds.cs deleted file mode 100644 index cbb70b497..000000000 --- a/src/services/rendering/Inno.Rendering/Device/RenderProtocolIds.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; - -namespace Inno.Rendering; - -/// -/// Identifies a pipeline-defined semantic resource without imposing a central resource catalog. -/// -public readonly record struct RenderResourceId -{ - /// - /// Creates an open semantic resource identifier. - /// - /// - /// Globally stable resource protocol value. - /// - public RenderResourceId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether the identifier contains a protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Identifies one pipeline-owned frame-data channel without constraining its payload model. -/// -public readonly record struct RenderDataChannelId -{ - /// - /// Creates an open frame-data channel identifier. - /// - /// - /// Globally stable channel protocol value. - /// - public RenderDataChannelId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether the identifier contains a protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs index b1fa9608a..4a6d0a6b6 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs @@ -1,82 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects triangle culling for a backend-neutral raster pipeline. -/// -public enum RenderCullMode -{ - /// - /// Disables face culling. - /// - None, - /// - /// Culls front-facing triangles. - /// - Front, - /// - /// Culls back-facing triangles. - /// - Back -} - -/// -/// Selects the winding order interpreted as the front face. -/// -public enum RenderFrontFace -{ - /// - /// Clockwise vertices form a front-facing triangle. - /// - Clockwise, - /// - /// Counter-clockwise vertices form a front-facing triangle. - /// - CounterClockwise -} - -/// -/// Selects depth comparison for a backend-neutral raster pipeline. -/// -public enum RenderDepthCompare -{ - /// - /// Always rejects. - /// - Never, - /// - /// Accepts smaller depth. - /// - Less, - /// - /// Accepts equal depth. - /// - Equal, - /// - /// Accepts smaller or equal depth. - /// - LessEqual, - /// - /// Accepts greater depth. - /// - Greater, - /// - /// Accepts unequal depth. - /// - NotEqual, - /// - /// Accepts greater or equal depth. - /// - GreaterEqual, - /// - /// Always accepts. - /// - Always -} - /// /// Stores backend-neutral fixed-function raster state. /// @@ -85,9 +8,7 @@ public sealed class RenderRasterState /// /// Creates the default opaque raster state. /// - public RenderRasterState() - { - } + public RenderRasterState() {} /// /// Creates a complete immutable raster configuration without relying on init-only setters. @@ -169,7 +90,7 @@ RenderPrimitiveTopology topology /// /// Gets the four-bit RGBA write mask. /// - public byte colorWriteMask { get; init; } = 0x0f; + public byte colorWriteMask { get; init; } = 0x0F; /// /// Gets whether multisample rasterization is enabled for compatible targets. @@ -182,3 +103,75 @@ RenderPrimitiveTopology topology public RenderPrimitiveTopology topology { get; init; } = RenderPrimitiveTopology.TriangleList; } +/// +/// Selects triangle culling for a backend-neutral raster pipeline. +/// +public enum RenderCullMode +{ + /// + /// Disables face culling. + /// + None, + /// + /// Culls front-facing triangles. + /// + Front, + /// + /// Culls back-facing triangles. + /// + Back +} + +/// +/// Selects the winding order interpreted as the front face. +/// +public enum RenderFrontFace +{ + /// + /// Clockwise vertices form a front-facing triangle. + /// + Clockwise, + /// + /// Counter-clockwise vertices form a front-facing triangle. + /// + CounterClockwise +} + +/// +/// Selects depth comparison for a backend-neutral raster pipeline. +/// +public enum RenderDepthCompare +{ + /// + /// Always rejects. + /// + Never, + /// + /// Accepts smaller depth. + /// + Less, + /// + /// Accepts equal depth. + /// + Equal, + /// + /// Accepts smaller or equal depth. + /// + LessEqual, + /// + /// Accepts greater depth. + /// + Greater, + /// + /// Accepts unequal depth. + /// + NotEqual, + /// + /// Accepts greater or equal depth. + /// + GreaterEqual, + /// + /// Always accepts. + /// + Always +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs b/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs new file mode 100644 index 000000000..16d21287e --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies a pipeline-defined semantic resource without imposing a central resource catalog. +/// +public readonly record struct RenderResourceID +{ + /// + /// Creates an open semantic resource identifier. + /// + /// + /// Globally stable resource protocol value. + /// + public RenderResourceID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether the identifier contains a protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs deleted file mode 100644 index 0956f4428..000000000 --- a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs +++ /dev/null @@ -1,554 +0,0 @@ -using System; - -namespace Inno.Rendering; - -/// -/// Declares backend-neutral texture storage formats. -/// -public enum RenderTextureFormat -{ - /// - /// Eight-bit single-channel normalized format. - /// - R8, - /// - /// Eight-bit two-channel normalized format. - /// - RG8, - /// - /// Eight-bit four-channel linear normalized format. - /// - RGBA8, - /// - /// Eight-bit four-channel sRGB format. - /// - RGBA8Srgb, - /// - /// Ten-bit RGB and two-bit alpha normalized format. - /// - RGB10A2, - /// - /// Eleven-bit RGB floating-point format. - /// - RG11B10Float, - /// - /// Half-precision four-channel floating-point format. - /// - RGBA16Float, - /// - /// Single-channel 32-bit floating-point format. - /// - R32Float, - /// - /// Twenty-four-bit depth and eight-bit stencil format. - /// - Depth24Stencil8, - /// - /// Thirty-two-bit floating-point depth format. - /// - Depth32Float -} - -/// -/// Identifies the dimensional shape of a backend-neutral texture resource. -/// -public enum RenderTextureDimension -{ - /// - /// Two-dimensional texture with optional array layers. - /// - Texture2D, - /// - /// Three-dimensional volume texture. - /// - Texture3D, - /// - /// Cubemap texture with optional cubemap array layers. - /// - Cube -} - -/// -/// Declares intended texture operations for capability and hazard validation. -/// -[Flags] -public enum RenderTextureUsage -{ - /// - /// Shader-readable texture. - /// - Sampled = 1 << 0, - /// - /// Raster color attachment. - /// - ColorAttachment = 1 << 1, - /// - /// Raster depth or stencil attachment. - /// - DepthStencilAttachment = 1 << 2, - /// - /// Shader-readable and writable unordered texture. - /// - Storage = 1 << 3, - /// - /// Copy operation source. - /// - CopySource = 1 << 4, - /// - /// Copy operation destination. - /// - CopyDestination = 1 << 5, - /// - /// Asynchronous transfer from GPU texture memory to CPU-visible bytes. - /// - Readback = 1 << 6 -} - -/// -/// Declares intended buffer operations for capability and hazard validation. -/// -[Flags] -public enum RenderBufferUsage -{ - /// - /// Vertex input data. - /// - Vertex = 1 << 0, - /// - /// Index input data. - /// - Index = 1 << 1, - /// - /// Read-only shader data. - /// - Uniform = 1 << 2, - /// - /// Shader-readable and writable storage data. - /// - Storage = 1 << 3, - /// - /// Indirect command data. - /// - Indirect = 1 << 4, - /// - /// Copy operation source. - /// - CopySource = 1 << 5, - /// - /// Copy operation destination. - /// - CopyDestination = 1 << 6, - /// - /// Contents may be replaced at frame safety points. - /// - Dynamic = 1 << 7 -} - -/// -/// Describes a render-graph texture independently from a graphics backend. -/// -public sealed class RenderTextureDescriptor : IEquatable -{ - /// - /// Creates a texture descriptor. - /// - /// - /// Texture width in pixels. - /// - /// - /// Texture height in pixels. - /// - /// - /// Storage format. - /// - /// - /// Permitted operations. - /// - /// - /// Number of mip levels. - /// - /// - /// Number of array layers. - /// - /// - /// Raster sample count. - /// - /// - /// Texture dimensional shape. - /// - /// - /// Base mip depth for a three-dimensional texture. - /// - public RenderTextureDescriptor( - int width, - int height, - RenderTextureFormat format, - RenderTextureUsage usage, - int mipCount = 1, - int arrayLayers = 1, - int sampleCount = 1, - RenderTextureDimension dimension = RenderTextureDimension.Texture2D, - int depth = 1 - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(mipCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayLayers); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); - if (sampleCount is not (1 or 2 or 4 or 8 or 16)) - { - throw new ArgumentOutOfRangeException(nameof(sampleCount), "Sample count must be 1, 2, 4, 8, or 16."); - } - - switch (dimension) - { - case RenderTextureDimension.Texture2D when depth != 1: - throw new ArgumentException("A two-dimensional texture must have depth one.", nameof(depth)); - case RenderTextureDimension.Texture3D when arrayLayers != 1: - throw new ArgumentException( - "A three-dimensional texture cannot also declare array layers.", - nameof(arrayLayers)); - case RenderTextureDimension.Texture3D when sampleCount != 1: - throw new ArgumentException( - "A three-dimensional texture cannot be multisampled.", - nameof(sampleCount)); - case RenderTextureDimension.Cube when width != height: - throw new ArgumentException("Cubemap width and height must be equal.", nameof(height)); - case RenderTextureDimension.Cube when depth != 1: - throw new ArgumentException("A cubemap must have depth one.", nameof(depth)); - case RenderTextureDimension.Cube when sampleCount != 1: - throw new ArgumentException("A cubemap cannot be multisampled.", nameof(sampleCount)); - case RenderTextureDimension.Texture2D: - case RenderTextureDimension.Texture3D: - case RenderTextureDimension.Cube: - break; - default: - throw new ArgumentOutOfRangeException(nameof(dimension)); - } - - this.width = width; - this.height = height; - this.format = format; - this.usage = usage; - this.mipCount = mipCount; - this.arrayLayers = arrayLayers; - this.sampleCount = sampleCount; - this.dimension = dimension; - this.depth = depth; - } - - /// - /// Gets the texture width in pixels. - /// - public int width { get; } - - /// - /// Gets the texture height in pixels. - /// - public int height { get; } - - /// - /// Gets the storage format. - /// - public RenderTextureFormat format { get; } - - /// - /// Gets permitted operations. - /// - public RenderTextureUsage usage { get; } - - /// - /// Gets the number of mip levels. - /// - public int mipCount { get; } - - /// - /// Gets the number of array layers. - /// - public int arrayLayers { get; } - - /// - /// Gets the raster sample count. - /// - public int sampleCount { get; } - - /// - /// Gets the dimensional texture shape. - /// - public RenderTextureDimension dimension { get; } - - /// - /// Gets the base mip depth for a three-dimensional texture. - /// - public int depth { get; } - - /// - /// Gets the number of independently addressable layers or slices at one mip level. - /// - /// - /// Zero-based mip level. - /// - /// - /// The array-layer count for 2D textures, six faces per cubemap layer, or the mip depth for 3D textures. - /// - public int GetSubresourceLayerCount(int mipLevel) - { - if ((uint)mipLevel >= (uint)mipCount) - throw new ArgumentOutOfRangeException(nameof(mipLevel)); - return dimension switch - { - RenderTextureDimension.Texture2D => arrayLayers, - RenderTextureDimension.Texture3D => Math.Max(1, depth >> mipLevel), - RenderTextureDimension.Cube => checked(arrayLayers * 6), - _ => throw new ArgumentOutOfRangeException(nameof(dimension)) - }; - } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderTextureDescriptor? other) - => other is not null - && width == other.width - && height == other.height - && format == other.format - && usage == other.usage - && mipCount == other.mipCount - && arrayLayers == other.arrayLayers - && sampleCount == other.sampleCount - && dimension == other.dimension - && depth == other.depth; - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - /// - /// The object to compare with this instance. - /// - public override bool Equals(object? obj) => Equals(obj as RenderTextureDescriptor); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() - { - HashCode hash = new(); - hash.Add(width); - hash.Add(height); - hash.Add(format); - hash.Add(usage); - hash.Add(mipCount); - hash.Add(arrayLayers); - hash.Add(sampleCount); - hash.Add(dimension); - hash.Add(depth); - return hash.ToHashCode(); - } -} - -/// -/// Describes a render-graph buffer independently from a graphics backend. -/// -public sealed class RenderBufferDescriptor : IEquatable -{ - /// - /// Creates a buffer descriptor. - /// - /// - /// Number of addressable elements. - /// - /// - /// Element size in bytes. - /// - /// - /// Permitted operations. - /// - public RenderBufferDescriptor( - int elementCount, - int elementStride, - RenderBufferUsage usage - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); - this.elementCount = elementCount; - this.elementStride = elementStride; - this.usage = usage; - } - - /// - /// Gets the number of addressable elements. - /// - public int elementCount { get; } - - /// - /// Gets the element size in bytes. - /// - public int elementStride { get; } - - /// - /// Gets permitted operations. - /// - public RenderBufferUsage usage { get; } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderBufferDescriptor? other) - => other is not null - && elementCount == other.elementCount - && elementStride == other.elementStride - && usage == other.usage; - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - /// - /// The object to compare with this instance. - /// - public override bool Equals(object? obj) => Equals(obj as RenderBufferDescriptor); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() => HashCode.Combine(elementCount, elementStride, usage); -} - -/// -/// Identifies a frame-scoped render-graph texture. -/// -public readonly record struct RenderTextureHandle -{ - internal RenderTextureHandle( - int index, - uint generation, - ulong allocationId - ) { - this.index = index; - this.generation = generation; - this.allocationId = allocationId; - } - - internal int index { get; } - internal uint generation { get; } - internal ulong allocationId { get; } - - /// - /// Gets whether the handle was created by a render graph. - /// - public bool isValid => index >= 0 && generation != 0 && allocationId != 0; -} - -/// -/// Identifies a frame-scoped render-graph buffer. -/// -public readonly record struct RenderBufferHandle -{ - internal RenderBufferHandle( - int index, - uint generation, - ulong allocationId - ) { - this.index = index; - this.generation = generation; - this.allocationId = allocationId; - } - - internal int index { get; } - internal uint generation { get; } - internal ulong allocationId { get; } - - /// - /// Gets whether the handle was created by a render graph. - /// - public bool isValid => index >= 0 && generation != 0 && allocationId != 0; -} - -/// -/// Identifies a persistent device texture without exposing a backend-native handle. -/// -public readonly record struct PersistentTextureHandle -{ - internal PersistentTextureHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device texture. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a persistent device buffer without exposing a backend-native handle. -/// -public readonly record struct PersistentBufferHandle -{ - internal PersistentBufferHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device buffer. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a persistent presentation surface without exposing a backend framebuffer or swapchain handle. -/// -public readonly record struct RenderSurfaceHandle -{ - internal RenderSurfaceHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a presentation surface. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs index 44f8e4968..4af29f4f2 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs @@ -1,65 +1,12 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; -/// -/// Selects texture filtering independently from a graphics backend. -/// -public enum RenderSamplerFilter -{ - /// - /// Uses nearest-neighbor filtering. - /// - Point, - /// - /// Uses linear filtering. - /// - Linear, - /// - /// Uses anisotropic filtering when supported. - /// - Anisotropic -} - -/// -/// Selects texture addressing independently for each coordinate axis. -/// -public enum RenderSamplerAddressMode -{ - /// - /// Repeats texture coordinates. - /// - Repeat, - /// - /// Mirrors repeated texture coordinates. - /// - Mirror, - /// - /// Clamps coordinates to the texture edge. - /// - Clamp, - /// - /// Samples the backend border color outside the texture. - /// - Border -} - /// /// Describes one native-serializable backend-neutral sampler binding. /// public struct RenderSamplerState : IEquatable { - /// - /// Gets linear filtering with clamped addressing. - /// - public static RenderSamplerState linearClamp => new( - RenderSamplerFilter.Linear, - RenderSamplerAddressMode.Clamp, - RenderSamplerAddressMode.Clamp, - RenderSamplerAddressMode.Clamp); - /// /// Creates a sampler state. /// @@ -87,6 +34,17 @@ RenderSamplerAddressMode addressW this.addressW = addressW; } + /// + /// Gets linear filtering with clamped addressing. + /// + public static RenderSamplerState linearClamp + => new( + RenderSamplerFilter.Linear, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp + ); + /// /// Gets the filter contract. /// @@ -125,12 +83,12 @@ public readonly bool Equals(RenderSamplerState other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override readonly bool Equals(object? obj) => obj is RenderSamplerState other && Equals(other); /// @@ -176,3 +134,44 @@ RenderSamplerState right ) => !left.Equals(right); } +/// +/// Selects texture filtering independently from a graphics backend. +/// +public enum RenderSamplerFilter +{ + /// + /// Uses nearest-neighbor filtering. + /// + Point, + /// + /// Uses linear filtering. + /// + Linear, + /// + /// Uses anisotropic filtering when supported. + /// + Anisotropic +} + +/// +/// Selects texture addressing independently for each coordinate axis. +/// +public enum RenderSamplerAddressMode +{ + /// + /// Repeats texture coordinates. + /// + Repeat, + /// + /// Mirrors repeated texture coordinates. + /// + Mirror, + /// + /// Clamps coordinates to the texture edge. + /// + Clamp, + /// + /// Samples the backend border color outside the texture. + /// + Border +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs index 227b08fb2..828097d9d 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs @@ -1,70 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; -/// -/// Identifies a shader interface binding domain. -/// -public enum RenderShaderBindingKind -{ - /// - /// Vector or matrix uniform data. - /// - Uniform, - /// - /// Sampled texture and sampler state. - /// - Texture, - /// - /// Shader-readable or writable storage texture. - /// - StorageTexture, - /// - /// Compute-readable or writable buffer. - /// - StorageBuffer -} - -/// -/// Identifies the native-independent shape of one uniform binding. -/// -public enum RenderUniformType -{ - /// - /// Four-component 32-bit floating-point vector. - /// - Vector4, - /// - /// Three-by-three 32-bit floating-point matrix. - /// - Matrix3x3, - /// - /// Four-by-four 32-bit floating-point matrix. - /// - Matrix4x4 -} - -/// -/// Selects unordered storage-resource access for one shader binding. -/// -public enum RenderStorageAccess -{ - /// - /// Shader read-only access. - /// - Read, - /// - /// Shader write-only access. - /// - Write, - /// - /// Shader read and write access. - /// - ReadWrite -} - /// /// Declares one manifest-derived shader binding used for reflection validation. /// @@ -95,7 +32,7 @@ public sealed class RenderShaderBindingDescriptor /// Adapter-generated reflected symbol, or null when the logical ID is also the symbol. /// public RenderShaderBindingDescriptor( - RenderBindingId id, + RenderBindingID id, RenderShaderBindingKind kind, int slot = 0, RenderUniformType uniformType = RenderUniformType.Vector4, @@ -111,11 +48,17 @@ public RenderShaderBindingDescriptor( ArgumentOutOfRangeException.ThrowIfNegative(slot); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count); if (!Enum.IsDefined(kind)) + { throw new ArgumentOutOfRangeException(nameof(kind)); + } if (!Enum.IsDefined(uniformType)) + { throw new ArgumentOutOfRangeException(nameof(uniformType)); + } if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } this.id = id; this.kind = kind; this.slot = slot; @@ -129,7 +72,7 @@ public RenderShaderBindingDescriptor( /// /// Gets the stable manifest binding name. /// - public RenderBindingId id { get; } + public RenderBindingID id { get; } /// /// Gets the binding domain. @@ -162,3 +105,63 @@ public RenderShaderBindingDescriptor( public string nativeName { get; } } +/// +/// Identifies a shader interface binding domain. +/// +public enum RenderShaderBindingKind +{ + /// + /// Vector or matrix uniform data. + /// + Uniform, + /// + /// Sampled texture and sampler state. + /// + Texture, + /// + /// Shader-readable or writable storage texture. + /// + StorageTexture, + /// + /// Compute-readable or writable buffer. + /// + StorageBuffer +} + +/// +/// Identifies the native-independent shape of one uniform binding. +/// +public enum RenderUniformType +{ + /// + /// Four-component 32-bit floating-point vector. + /// + Vector4, + /// + /// Three-by-three 32-bit floating-point matrix. + /// + Matrix3x3, + /// + /// Four-by-four 32-bit floating-point matrix. + /// + Matrix4x4 +} + +/// +/// Selects unordered storage-resource access for one shader binding. +/// +public enum RenderStorageAccess +{ + /// + /// Shader read-only access. + /// + Read, + /// + /// Shader write-only access. + /// + Write, + /// + /// Shader read and write access. + /// + ReadWrite +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs b/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs new file mode 100644 index 000000000..e26710174 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs @@ -0,0 +1,54 @@ +namespace Inno.Rendering; + +/// +/// Describes stencil behavior for one triangle face orientation. +/// +public readonly record struct RenderStencilFaceState +{ + /// + /// Creates one face stencil state. + /// + /// + /// Stencil comparison. + /// + /// + /// Operation after stencil comparison failure. + /// + /// + /// Operation after stencil success and depth failure. + /// + /// + /// Operation after stencil and depth success. + /// + public RenderStencilFaceState( + RenderStencilCompare compare, + RenderStencilOperation fail, + RenderStencilOperation depthFail, + RenderStencilOperation pass + ) { + this.compare = compare; + this.fail = fail; + this.depthFail = depthFail; + this.pass = pass; + } + + /// + /// Gets stencil comparison. + /// + public RenderStencilCompare compare { get; } + + /// + /// Gets the stencil-failure operation. + /// + public RenderStencilOperation fail { get; } + + /// + /// Gets the depth-failure operation. + /// + public RenderStencilOperation depthFail { get; } + + /// + /// Gets the complete-pass operation. + /// + public RenderStencilOperation pass { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs index bbd378c92..805c44fd9 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs @@ -1,140 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects the comparison applied to stencil reference and stored values. -/// -public enum RenderStencilCompare -{ - /// - /// Never passes. - /// - Never, - /// - /// Passes when reference is smaller. - /// - Less, - /// - /// Passes when values are equal. - /// - Equal, - /// - /// Passes when reference is smaller or equal. - /// - LessEqual, - /// - /// Passes when reference is greater. - /// - Greater, - /// - /// Passes when values differ. - /// - NotEqual, - /// - /// Passes when reference is greater or equal. - /// - GreaterEqual, - /// - /// Always passes. - /// - Always -} - -/// -/// Selects the update applied to a stencil value. -/// -public enum RenderStencilOperation -{ - /// - /// Keeps the stored value. - /// - Keep, - /// - /// Clears the stored value to zero. - /// - Zero, - /// - /// Replaces the stored value with the reference. - /// - Replace, - /// - /// Increments and clamps the stored value. - /// - IncrementClamp, - /// - /// Increments and wraps the stored value. - /// - IncrementWrap, - /// - /// Decrements and clamps the stored value. - /// - DecrementClamp, - /// - /// Decrements and wraps the stored value. - /// - DecrementWrap, - /// - /// Bitwise-inverts the stored value. - /// - Invert -} - -/// -/// Describes stencil behavior for one triangle face orientation. -/// -public readonly record struct RenderStencilFaceState -{ - /// - /// Creates one face stencil state. - /// - /// - /// Stencil comparison. - /// - /// - /// Operation after stencil comparison failure. - /// - /// - /// Operation after stencil success and depth failure. - /// - /// - /// Operation after stencil and depth success. - /// - public RenderStencilFaceState( - RenderStencilCompare compare, - RenderStencilOperation fail, - RenderStencilOperation depthFail, - RenderStencilOperation pass - ) { - this.compare = compare; - this.fail = fail; - this.depthFail = depthFail; - this.pass = pass; - } - - /// - /// Gets stencil comparison. - /// - public RenderStencilCompare compare { get; } - - /// - /// Gets the stencil-failure operation. - /// - public RenderStencilOperation fail { get; } - - /// - /// Gets the depth-failure operation. - /// - public RenderStencilOperation depthFail { get; } - - /// - /// Gets the complete-pass operation. - /// - public RenderStencilOperation pass { get; } -} - /// /// Describes complete two-sided stencil state for one draw. /// @@ -143,9 +8,7 @@ public sealed class RenderStencilState /// /// Creates the default disabled stencil state. /// - public RenderStencilState() - { - } + public RenderStencilState() {} /// /// Creates a complete immutable stencil configuration without relying on init-only setters. @@ -216,7 +79,8 @@ RenderStencilFaceState back RenderStencilCompare.Always, RenderStencilOperation.Keep, RenderStencilOperation.Keep, - RenderStencilOperation.Keep); + RenderStencilOperation.Keep + ); /// /// Gets back-face stencil behavior. @@ -225,6 +89,84 @@ RenderStencilFaceState back RenderStencilCompare.Always, RenderStencilOperation.Keep, RenderStencilOperation.Keep, - RenderStencilOperation.Keep); + RenderStencilOperation.Keep + ); } +/// +/// Selects the comparison applied to stencil reference and stored values. +/// +public enum RenderStencilCompare +{ + /// + /// Never passes. + /// + Never, + /// + /// Passes when reference is smaller. + /// + Less, + /// + /// Passes when values are equal. + /// + Equal, + /// + /// Passes when reference is smaller or equal. + /// + LessEqual, + /// + /// Passes when reference is greater. + /// + Greater, + /// + /// Passes when values differ. + /// + NotEqual, + /// + /// Passes when reference is greater or equal. + /// + GreaterEqual, + /// + /// Always passes. + /// + Always +} + +/// +/// Selects the update applied to a stencil value. +/// +public enum RenderStencilOperation +{ + /// + /// Keeps the stored value. + /// + Keep, + /// + /// Clears the stored value to zero. + /// + Zero, + /// + /// Replaces the stored value with the reference. + /// + Replace, + /// + /// Increments and clamps the stored value. + /// + IncrementClamp, + /// + /// Increments and wraps the stored value. + /// + IncrementWrap, + /// + /// Decrements and clamps the stored value. + /// + DecrementClamp, + /// + /// Decrements and wraps the stored value. + /// + DecrementWrap, + /// + /// Bitwise-inverts the stored value. + /// + Invert +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs new file mode 100644 index 000000000..f6ad3417c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent presentation surface without exposing a backend framebuffer or swapchain handle. +/// +public readonly record struct RenderSurfaceHandle +{ + internal RenderSurfaceHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a presentation surface. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs new file mode 100644 index 000000000..a9edf563d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs @@ -0,0 +1,218 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes a render-graph texture independently from a graphics backend. +/// +public sealed class RenderTextureDescriptor : IEquatable +{ + /// + /// Creates a texture descriptor. + /// + /// + /// Texture width in pixels. + /// + /// + /// Texture height in pixels. + /// + /// + /// Storage format. + /// + /// + /// Permitted operations. + /// + /// + /// Number of mip levels. + /// + /// + /// Number of array layers. + /// + /// + /// Raster sample count. + /// + /// + /// Texture dimensional shape. + /// + /// + /// Base mip depth for a three-dimensional texture. + /// + public RenderTextureDescriptor( + int width, + int height, + RenderTextureFormat format, + RenderTextureUsage usage, + int mipCount = 1, + int arrayLayers = 1, + int sampleCount = 1, + RenderTextureDimension dimension = RenderTextureDimension.Texture2D, + int depth = 1 + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(mipCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayLayers); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); + if (sampleCount is not (1 or 2 or 4 or 8 or 16)) + { + throw new ArgumentOutOfRangeException(nameof(sampleCount), "Sample count must be 1, 2, 4, 8, or 16."); + } + + switch (dimension) + { + case RenderTextureDimension.Texture2D when depth != 1: + throw new ArgumentException("A two-dimensional texture must have depth one.", nameof(depth)); + case RenderTextureDimension.Texture3D when arrayLayers != 1: + throw new ArgumentException( + "A three-dimensional texture cannot also declare array layers.", + nameof(arrayLayers) + ); + case RenderTextureDimension.Texture3D when sampleCount != 1: + throw new ArgumentException("A three-dimensional texture cannot be multisampled.", nameof(sampleCount)); + case RenderTextureDimension.Cube when width != height: + throw new ArgumentException("Cubemap width and height must be equal.", nameof(height)); + case RenderTextureDimension.Cube when depth != 1: + throw new ArgumentException("A cubemap must have depth one.", nameof(depth)); + case RenderTextureDimension.Cube when sampleCount != 1: + throw new ArgumentException("A cubemap cannot be multisampled.", nameof(sampleCount)); + case RenderTextureDimension.Texture2D: + case RenderTextureDimension.Texture3D: + case RenderTextureDimension.Cube: + break; + default: + throw new ArgumentOutOfRangeException(nameof(dimension)); + } + + this.width = width; + this.height = height; + this.format = format; + this.usage = usage; + this.mipCount = mipCount; + this.arrayLayers = arrayLayers; + this.sampleCount = sampleCount; + this.dimension = dimension; + this.depth = depth; + } + + /// + /// Gets the texture width in pixels. + /// + public int width { get; } + + /// + /// Gets the texture height in pixels. + /// + public int height { get; } + + /// + /// Gets the storage format. + /// + public RenderTextureFormat format { get; } + + /// + /// Gets permitted operations. + /// + public RenderTextureUsage usage { get; } + + /// + /// Gets the number of mip levels. + /// + public int mipCount { get; } + + /// + /// Gets the number of array layers. + /// + public int arrayLayers { get; } + + /// + /// Gets the raster sample count. + /// + public int sampleCount { get; } + + /// + /// Gets the dimensional texture shape. + /// + public RenderTextureDimension dimension { get; } + + /// + /// Gets the base mip depth for a three-dimensional texture. + /// + public int depth { get; } + + /// + /// Gets the number of independently addressable layers or slices at one mip level. + /// + /// + /// Zero-based mip level. + /// + /// + /// The array-layer count for 2D textures, six faces per cubemap layer, or the mip depth for 3D textures. + /// + public int GetSubresourceLayerCount(int mipLevel) + { + if ((uint)mipLevel >= (uint)mipCount) + { + throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } + return dimension switch + { + RenderTextureDimension.Texture2D => arrayLayers, + RenderTextureDimension.Texture3D => Math.Max(1, depth >> mipLevel), + RenderTextureDimension.Cube => checked(arrayLayers * 6), + _ => throw new ArgumentOutOfRangeException(nameof(dimension)) + }; + } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderTextureDescriptor? other) + => other is not null + && width == other.width + && height == other.height + && format == other.format + && usage == other.usage + && mipCount == other.mipCount + && arrayLayers == other.arrayLayers + && sampleCount == other.sampleCount + && dimension == other.dimension + && depth == other.depth; + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderTextureDescriptor); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() + { + var hash = new HashCode(); + hash.Add(width); + hash.Add(height); + hash.Add(format); + hash.Add(usage); + hash.Add(mipCount); + hash.Add(arrayLayers); + hash.Add(sampleCount); + hash.Add(dimension); + hash.Add(depth); + return hash.ToHashCode(); + } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs new file mode 100644 index 000000000..4eca7bbc4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Identifies the dimensional shape of a backend-neutral texture resource. +/// +public enum RenderTextureDimension +{ + /// + /// Two-dimensional texture with optional array layers. + /// + Texture2D, + /// + /// Three-dimensional volume texture. + /// + Texture3D, + /// + /// Cubemap texture with optional cubemap array layers. + /// + Cube +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs new file mode 100644 index 000000000..43bcf28a0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs @@ -0,0 +1,48 @@ +namespace Inno.Rendering; + +/// +/// Declares backend-neutral texture storage formats. +/// +public enum RenderTextureFormat +{ + /// + /// Eight-bit single-channel normalized format. + /// + R8, + /// + /// Eight-bit two-channel normalized format. + /// + RG8, + /// + /// Eight-bit four-channel linear normalized format. + /// + RGBA8, + /// + /// Eight-bit four-channel sRGB format. + /// + RGBA8Srgb, + /// + /// Ten-bit RGB and two-bit alpha normalized format. + /// + RGB10A2, + /// + /// Eleven-bit RGB floating-point format. + /// + RG11B10Float, + /// + /// Half-precision four-channel floating-point format. + /// + RGBA16Float, + /// + /// Single-channel 32-bit floating-point format. + /// + R32Float, + /// + /// Twenty-four-bit depth and eight-bit stencil format. + /// + Depth24Stencil8, + /// + /// Thirty-two-bit floating-point depth format. + /// + Depth32Float +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs new file mode 100644 index 000000000..677dc3a19 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering; + +/// +/// Identifies a frame-scoped render-graph texture. +/// +public readonly record struct RenderTextureHandle +{ + internal RenderTextureHandle( + int index, + uint generation, + ulong allocationID + ) { + this.index = index; + this.generation = generation; + this.allocationID = allocationID; + } + + internal int index { get; } + internal uint generation { get; } + internal ulong allocationID { get; } + + /// + /// Gets whether the handle was created by a render graph. + /// + public bool isValid => index >= 0 && generation != 0 && allocationID != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs new file mode 100644 index 000000000..272669acb --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies one backend-neutral asynchronous texture readback operation. +/// +public readonly record struct RenderTextureReadbackHandle +{ + internal RenderTextureReadbackHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device readback operation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs similarity index 71% rename from src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs rename to src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs index 9c1c3fef3..27931258d 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs @@ -2,28 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies one backend-neutral asynchronous texture readback operation. -/// -public readonly record struct RenderTextureReadbackHandle -{ - internal RenderTextureReadbackHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device readback operation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - /// /// Contains immutable bytes copied from one complete texture mip. /// @@ -55,10 +33,11 @@ ReadOnlySpan data ArgumentNullException.ThrowIfNull(descriptor); ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rowPitch); - if (mipLevel >= descriptor.mipCount) - throw new ArgumentOutOfRangeException(nameof(mipLevel)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(mipLevel, descriptor.mipCount); if (data.IsEmpty) + { throw new ArgumentException("Texture readback data cannot be empty.", nameof(data)); + } this.descriptor = descriptor; this.mipLevel = mipLevel; this.rowPitch = rowPitch; diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs new file mode 100644 index 000000000..5390db5d2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs @@ -0,0 +1,93 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes one texture subresource box for copy and blit commands. +/// +public readonly record struct RenderTextureRegion +{ + /// + /// Creates a texture subresource box. + /// + /// + /// Zero-based mip level. + /// + /// + /// Horizontal texel origin. + /// + /// + /// Vertical texel origin. + /// + /// + /// Array layer or depth-slice origin. + /// + /// + /// Positive texel width. + /// + /// + /// Positive texel height. + /// + /// + /// Positive layer or depth-slice count. + /// + public RenderTextureRegion( + int mip, + int x, + int y, + int layer, + int width, + int height, + int depth = 1 + ) { + ArgumentOutOfRangeException.ThrowIfNegative(mip); + ArgumentOutOfRangeException.ThrowIfNegative(x); + ArgumentOutOfRangeException.ThrowIfNegative(y); + ArgumentOutOfRangeException.ThrowIfNegative(layer); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); + this.mip = mip; + this.x = x; + this.y = y; + this.layer = layer; + this.width = width; + this.height = height; + this.depth = depth; + } + + /// + /// Gets the zero-based mip level. + /// + public int mip { get; } + + /// + /// Gets the horizontal texel origin. + /// + public int x { get; } + + /// + /// Gets the vertical texel origin. + /// + public int y { get; } + + /// + /// Gets the array layer or depth-slice origin. + /// + public int layer { get; } + + /// + /// Gets the texel width. + /// + public int width { get; } + + /// + /// Gets the texel height. + /// + public int height { get; } + + /// + /// Gets the layer or depth-slice count. + /// + public int depth { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs new file mode 100644 index 000000000..bda591e32 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Declares intended texture operations for capability and hazard validation. +/// +[Flags] +public enum RenderTextureUsage +{ + /// + /// Shader-readable texture. + /// + Sampled = 1 << 0, + /// + /// Raster color attachment. + /// + ColorAttachment = 1 << 1, + /// + /// Raster depth or stencil attachment. + /// + DepthStencilAttachment = 1 << 2, + /// + /// Shader-readable and writable unordered texture. + /// + Storage = 1 << 3, + /// + /// Copy operation source. + /// + CopySource = 1 << 4, + /// + /// Copy operation destination. + /// + CopyDestination = 1 << 5, + /// + /// Asynchronous transfer from GPU texture memory to CPU-visible bytes. + /// + Readback = 1 << 6 +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs new file mode 100644 index 000000000..c57f9f15f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs @@ -0,0 +1,71 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes one vertex attribute in stream order. +/// +public readonly record struct RenderVertexAttribute +{ + /// + /// Creates a vertex attribute declaration. + /// + /// + /// Shader input semantic. + /// + /// + /// Packed component representation. + /// + /// + /// Explicit byte offset in the stream, or -1 to place the attribute directly after the preceding attribute. + /// + public RenderVertexAttribute( + RenderVertexSemantic semantic, + RenderVertexFormat format, + int byteOffset = -1 + ) { + ArgumentOutOfRangeException.ThrowIfLessThan(byteOffset, -1); + this.semantic = semantic; + this.format = format; + this.byteOffset = byteOffset; + } + + /// + /// Gets the shader input semantic. + /// + public RenderVertexSemantic semantic { get; } + + /// + /// Gets the packed component representation. + /// + public RenderVertexFormat format { get; } + + /// + /// Gets the explicit byte offset in the resolved stream layout, or -1 before a layout resolves automatic placement. + /// + public int byteOffset { get; } + + /// + /// Gets the packed byte size. + /// + public int byteSize + => format switch + { + RenderVertexFormat.Float1 => 4, + RenderVertexFormat.Float2 => 8, + RenderVertexFormat.Float3 => 12, + RenderVertexFormat.Float4 => 16, + RenderVertexFormat.Half2 => 4, + RenderVertexFormat.Half4 => 8, + RenderVertexFormat.UInt8Normalized2 => 2, + RenderVertexFormat.UInt8Normalized4 => 4, + RenderVertexFormat.UInt8Integer2 => 2, + RenderVertexFormat.UInt8Integer4 => 4, + RenderVertexFormat.UInt10Normalized4 => 4, + RenderVertexFormat.Int16Normalized2 => 4, + RenderVertexFormat.Int16Normalized4 => 8, + RenderVertexFormat.Int16Integer2 => 4, + RenderVertexFormat.Int16Integer4 => 8, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs index 4f8d9ba9f..8967a1418 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs @@ -4,6 +4,121 @@ namespace Inno.Rendering; +/// +/// Defines one interleaved vertex stream independently from a graphics backend. +/// +public sealed class RenderVertexLayout : IEquatable +{ + private readonly IReadOnlyList m_attributes; + + /// + /// Creates an interleaved vertex layout. + /// + /// + /// Unique attributes in ascending byte order. Attributes with offset -1 are packed after the preceding attribute. + /// + /// + /// Explicit positive stream stride, or zero to use the end of the final attribute. A larger stride preserves + /// trailing application-defined padding. + /// + public RenderVertexLayout( + IReadOnlyList attributes, + int stride = 0 + ) { + ArgumentNullException.ThrowIfNull(attributes); + ArgumentOutOfRangeException.ThrowIfNegative(stride); + if (attributes.Count == 0) + { + throw new ArgumentException("A vertex layout requires at least one attribute.", nameof(attributes)); + } + + if (attributes.Select(static value => value.semantic).Distinct().Count() != attributes.Count) + { + throw new ArgumentException("A vertex layout cannot repeat a semantic.", nameof(attributes)); + } + + var resolved = new RenderVertexAttribute[attributes.Count]; + int occupiedEnd = 0; + for (int index = 0; index < attributes.Count; index++) + { + RenderVertexAttribute attribute = attributes[index]; + int offset = attribute.byteOffset < 0 ? occupiedEnd : attribute.byteOffset; + if (offset < occupiedEnd) + { + throw new ArgumentException( + $"Vertex attribute '{attribute.semantic}' overlaps a preceding attribute.", + nameof(attributes) + ); + } + + resolved[index] = new RenderVertexAttribute(attribute.semantic, attribute.format, offset); + occupiedEnd = checked(offset + attribute.byteSize); + } + + if (stride != 0 && stride < occupiedEnd) + { + throw new ArgumentException("Vertex stride cannot end before the final attribute.", nameof(stride)); + } + + m_attributes = Array.AsReadOnly(resolved); + this.stride = stride == 0 ? occupiedEnd : stride; + } + + /// + /// Gets attributes in byte-stream order. + /// + public IReadOnlyList attributes => m_attributes; + + /// + /// Gets the interleaved vertex stride in bytes. + /// + public int stride { get; } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderVertexLayout? other) + => other is not null + && stride == other.stride + && m_attributes.SequenceEqual(other.m_attributes); + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderVertexLayout); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() + { + var hash = new HashCode(); + foreach (RenderVertexAttribute attribute in m_attributes) + { + hash.Add(attribute); + } + + hash.Add(stride); + + return hash.ToHashCode(); + } +} + /// /// Identifies one backend-neutral vertex attribute semantic. /// @@ -150,190 +265,6 @@ public enum RenderVertexFormat Int16Integer4 } -/// -/// Describes one vertex attribute in stream order. -/// -public readonly record struct RenderVertexAttribute -{ - /// - /// Creates a vertex attribute declaration. - /// - /// - /// Shader input semantic. - /// - /// - /// Packed component representation. - /// - /// - /// Explicit byte offset in the stream, or -1 to place the attribute directly after the preceding attribute. - /// - public RenderVertexAttribute( - RenderVertexSemantic semantic, - RenderVertexFormat format, - int byteOffset = -1 - ) { - if (byteOffset < -1) - throw new ArgumentOutOfRangeException(nameof(byteOffset)); - this.semantic = semantic; - this.format = format; - this.byteOffset = byteOffset; - } - - /// - /// Gets the shader input semantic. - /// - public RenderVertexSemantic semantic { get; } - - /// - /// Gets the packed component representation. - /// - public RenderVertexFormat format { get; } - - /// - /// Gets the explicit byte offset in the resolved stream layout, or -1 before a layout resolves automatic placement. - /// - public int byteOffset { get; } - - /// - /// Gets the packed byte size. - /// - public int byteSize => format switch - { - RenderVertexFormat.Float1 => 4, - RenderVertexFormat.Float2 => 8, - RenderVertexFormat.Float3 => 12, - RenderVertexFormat.Float4 => 16, - RenderVertexFormat.Half2 => 4, - RenderVertexFormat.Half4 => 8, - RenderVertexFormat.UInt8Normalized2 => 2, - RenderVertexFormat.UInt8Normalized4 => 4, - RenderVertexFormat.UInt8Integer2 => 2, - RenderVertexFormat.UInt8Integer4 => 4, - RenderVertexFormat.UInt10Normalized4 => 4, - RenderVertexFormat.Int16Normalized2 => 4, - RenderVertexFormat.Int16Normalized4 => 8, - RenderVertexFormat.Int16Integer2 => 4, - RenderVertexFormat.Int16Integer4 => 8, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; -} - -/// -/// Defines one interleaved vertex stream independently from a graphics backend. -/// -public sealed class RenderVertexLayout : IEquatable -{ - private readonly IReadOnlyList m_attributes; - - /// - /// Creates an interleaved vertex layout. - /// - /// - /// Unique attributes in ascending byte order. Attributes with offset -1 are packed after the preceding attribute. - /// - /// - /// Explicit positive stream stride, or zero to use the end of the final attribute. A larger stride preserves - /// trailing application-defined padding. - /// - public RenderVertexLayout( - IReadOnlyList attributes, - int stride = 0 - ) { - ArgumentNullException.ThrowIfNull(attributes); - ArgumentOutOfRangeException.ThrowIfNegative(stride); - if (attributes.Count == 0) - { - throw new ArgumentException("A vertex layout requires at least one attribute.", nameof(attributes)); - } - - if (attributes.Select(static value => value.semantic).Distinct().Count() != attributes.Count) - { - throw new ArgumentException("A vertex layout cannot repeat a semantic.", nameof(attributes)); - } - - var resolved = new RenderVertexAttribute[attributes.Count]; - int occupiedEnd = 0; - for (int index = 0; index < attributes.Count; index++) - { - RenderVertexAttribute attribute = attributes[index]; - int offset = attribute.byteOffset < 0 ? occupiedEnd : attribute.byteOffset; - if (offset < occupiedEnd) - { - throw new ArgumentException( - $"Vertex attribute '{attribute.semantic}' overlaps a preceding attribute.", - nameof(attributes)); - } - - resolved[index] = new RenderVertexAttribute(attribute.semantic, attribute.format, offset); - occupiedEnd = checked(offset + attribute.byteSize); - } - - if (stride != 0 && stride < occupiedEnd) - { - throw new ArgumentException( - "Vertex stride cannot end before the final attribute.", - nameof(stride)); - } - - m_attributes = Array.AsReadOnly(resolved); - this.stride = stride == 0 ? occupiedEnd : stride; - } - - /// - /// Gets attributes in byte-stream order. - /// - public IReadOnlyList attributes => m_attributes; - - /// - /// Gets the interleaved vertex stride in bytes. - /// - public int stride { get; } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderVertexLayout? other) - => other is not null - && stride == other.stride - && m_attributes.SequenceEqual(other.m_attributes); - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - /// - /// The object to compare with this instance. - /// - public override bool Equals(object? obj) => Equals(obj as RenderVertexLayout); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() - { - HashCode hash = new(); - foreach (RenderVertexAttribute attribute in m_attributes) - { - hash.Add(attribute); - } - - hash.Add(stride); - - return hash.ToHashCode(); - } -} - /// /// Selects the integer representation of an index buffer. /// @@ -375,4 +306,3 @@ public enum RenderPrimitiveTopology /// PointList } - diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs new file mode 100644 index 000000000..fb33b101c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs @@ -0,0 +1,71 @@ +namespace Inno.Rendering; + +/// +/// Describes one compiled raster attachment. +/// +public sealed class CompiledRenderAttachment +{ + internal CompiledRenderAttachment(RenderAttachment attachment) + { + this.texture = attachment.texture; + this.slot = attachment.slot; + this.isDepth = attachment.isDepth; + this.mipLevel = attachment.mipLevel; + this.arrayLayer = attachment.arrayLayer; + this.loadAction = attachment.loadAction; + this.storeAction = attachment.storeAction; + this.clearColor = attachment.clearColor; + this.clearDepth = attachment.clearDepth; + this.clearStencil = attachment.clearStencil; + } + + /// + /// Gets the attached graph texture. + /// + public RenderTextureHandle texture { get; } + + /// + /// Gets the zero-based color slot, or zero for a depth attachment. + /// + public int slot { get; } + + /// + /// Gets whether this is a depth or depth-stencil attachment. + /// + public bool isDepth { get; } + + /// + /// Gets the attached mip level. + /// + public int mipLevel { get; } + + /// + /// Gets the attached texture-array layer. + /// + public int arrayLayer { get; } + + /// + /// Gets initial content behavior. + /// + public RenderLoadAction loadAction { get; } + + /// + /// Gets final content behavior. + /// + public RenderStoreAction storeAction { get; } + + /// + /// Gets the linear color clear value. + /// + public RenderClearColor clearColor { get; } + + /// + /// Gets the depth clear value. + /// + public float clearDepth { get; } + + /// + /// Gets the stencil clear value. + /// + public byte clearStencil { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs new file mode 100644 index 000000000..6988e9b8f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs @@ -0,0 +1,53 @@ +namespace Inno.Rendering; + +/// +/// Describes one buffer allocation selected by render-graph compilation. +/// +public sealed class CompiledRenderBuffer +{ + internal CompiledRenderBuffer( + RenderBufferHandle handle, + string name, + RenderBufferDescriptor descriptor, + bool imported, + PersistentBufferHandle persistentHandle, + int physicalSlot + ) { + this.handle = handle; + this.name = name; + this.descriptor = descriptor; + this.imported = imported; + this.persistentHandle = persistentHandle; + this.physicalSlot = physicalSlot; + } + + /// + /// Gets the frame-scoped logical handle. + /// + public RenderBufferHandle handle { get; } + + /// + /// Gets the debug and diagnostic name. + /// + public string name { get; } + + /// + /// Gets buffer requirements. + /// + public RenderBufferDescriptor descriptor { get; } + + /// + /// Gets whether the resource was imported from persistent device state. + /// + public bool imported { get; } + + /// + /// Gets the persistent device buffer for imported resources. + /// + public PersistentBufferHandle persistentHandle { get; } + + /// + /// Gets the aliasing allocation slot, or negative one for imported resources. + /// + public int physicalSlot { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs index 18938eb97..0f9888c19 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; @@ -6,356 +7,6 @@ namespace Inno.Rendering; -/// -/// Stores backend-ready column-major transform matrices for one programmable view. -/// -public sealed class RenderViewTransform -{ - private readonly float[] m_viewMatrix; - private readonly float[] m_projectionMatrix; - - /// - /// Creates a raster view transform. - /// - /// - /// Exactly sixteen column-major world-to-view values. - /// - /// - /// Exactly sixteen column-major projection values. - /// - public RenderViewTransform( - ReadOnlySpan viewMatrix, - ReadOnlySpan projectionMatrix - ) { - if (viewMatrix.Length != 16) - { - throw new ArgumentException("A view matrix requires exactly sixteen values.", nameof(viewMatrix)); - } - - if (projectionMatrix.Length != 16) - { - throw new ArgumentException( - "A projection matrix requires exactly sixteen values.", - nameof(projectionMatrix)); - } - - m_viewMatrix = viewMatrix.ToArray(); - m_projectionMatrix = projectionMatrix.ToArray(); - } - - /// - /// Gets the immutable column-major view matrix. - /// - public ReadOnlyMemory viewMatrix => m_viewMatrix; - - /// - /// Gets the immutable column-major projection matrix. - /// - public ReadOnlyMemory projectionMatrix => m_projectionMatrix; -} - -/// -/// Describes one texture allocation selected by render-graph compilation. -/// -public sealed class CompiledRenderTexture -{ - internal CompiledRenderTexture( - RenderTextureHandle handle, - string name, - RenderTextureDescriptor descriptor, - bool imported, - PersistentTextureHandle persistentHandle, - int physicalSlot - ) { - this.handle = handle; - this.name = name; - this.descriptor = descriptor; - this.imported = imported; - this.persistentHandle = persistentHandle; - this.physicalSlot = physicalSlot; - } - - /// - /// Gets the frame-scoped logical handle. - /// - public RenderTextureHandle handle { get; } - - /// - /// Gets the debug and diagnostic name. - /// - public string name { get; } - - /// - /// Gets texture requirements. - /// - public RenderTextureDescriptor descriptor { get; } - - /// - /// Gets whether the resource was imported from persistent device state. - /// - public bool imported { get; } - - /// - /// Gets the persistent device texture for imported resources. - /// - public PersistentTextureHandle persistentHandle { get; } - - /// - /// Gets the aliasing allocation slot, or negative one for imported resources. - /// - public int physicalSlot { get; } -} - -/// -/// Describes one buffer allocation selected by render-graph compilation. -/// -public sealed class CompiledRenderBuffer -{ - internal CompiledRenderBuffer( - RenderBufferHandle handle, - string name, - RenderBufferDescriptor descriptor, - bool imported, - PersistentBufferHandle persistentHandle, - int physicalSlot - ) { - this.handle = handle; - this.name = name; - this.descriptor = descriptor; - this.imported = imported; - this.persistentHandle = persistentHandle; - this.physicalSlot = physicalSlot; - } - - /// - /// Gets the frame-scoped logical handle. - /// - public RenderBufferHandle handle { get; } - - /// - /// Gets the debug and diagnostic name. - /// - public string name { get; } - - /// - /// Gets buffer requirements. - /// - public RenderBufferDescriptor descriptor { get; } - - /// - /// Gets whether the resource was imported from persistent device state. - /// - public bool imported { get; } - - /// - /// Gets the persistent device buffer for imported resources. - /// - public PersistentBufferHandle persistentHandle { get; } - - /// - /// Gets the aliasing allocation slot, or negative one for imported resources. - /// - public int physicalSlot { get; } -} - -/// -/// Describes one compiled raster attachment. -/// -public sealed class CompiledRenderAttachment -{ - internal CompiledRenderAttachment(RenderAttachment attachment) - { - texture = attachment.texture; - slot = attachment.slot; - isDepth = attachment.isDepth; - mipLevel = attachment.mipLevel; - arrayLayer = attachment.arrayLayer; - loadAction = attachment.loadAction; - storeAction = attachment.storeAction; - clearColor = attachment.clearColor; - clearDepth = attachment.clearDepth; - clearStencil = attachment.clearStencil; - } - - /// - /// Gets the attached graph texture. - /// - public RenderTextureHandle texture { get; } - - /// - /// Gets the zero-based color slot, or zero for a depth attachment. - /// - public int slot { get; } - - /// - /// Gets whether this is a depth or depth-stencil attachment. - /// - public bool isDepth { get; } - - /// - /// Gets the attached mip level. - /// - public int mipLevel { get; } - - /// - /// Gets the attached texture-array layer. - /// - public int arrayLayer { get; } - - /// - /// Gets initial content behavior. - /// - public RenderLoadAction loadAction { get; } - - /// - /// Gets final content behavior. - /// - public RenderStoreAction storeAction { get; } - - /// - /// Gets the linear color clear value. - /// - public RenderClearColor clearColor { get; } - - /// - /// Gets the depth clear value. - /// - public float clearDepth { get; } - - /// - /// Gets the stencil clear value. - /// - public byte clearStencil { get; } -} - -/// -/// Provides immutable backend-facing metadata for one scheduled pass. -/// -public sealed class CompiledRenderPass -{ - private readonly IReadOnlyList m_attachments; - private readonly Action m_execute; - - internal CompiledRenderPass( - string name, - RenderPhaseId phase, - RenderPassKind kind, - int viewIndex, - IReadOnlyList attachments, - RenderSurfaceHandle surface, - bool clearsPresentationTarget, - RenderClearColor presentationClearColor, - RenderViewTransform? viewTransform, - RenderPassRecordingMode recordingMode, - Action execute - ) { - this.name = name; - this.phase = phase; - this.kind = kind; - this.viewIndex = viewIndex; - m_attachments = Array.AsReadOnly(attachments.ToArray()); - this.surface = surface; - this.clearsPresentationTarget = clearsPresentationTarget; - this.presentationClearColor = presentationClearColor; - this.viewTransform = viewTransform; - this.recordingMode = recordingMode; - m_execute = execute; - } - - /// - /// Gets the unique diagnostic name. - /// - public string name { get; } - - /// - /// Gets the open render phase identifier. - /// - public RenderPhaseId phase { get; } - - /// - /// Gets the pass command domain. - /// - public RenderPassKind kind { get; } - - /// - /// Gets the backend-neutral logical view order. - /// - public int viewIndex { get; } - - /// - /// Gets raster attachments in declaration order. - /// - public IReadOnlyList attachments => m_attachments; - - /// - /// Gets the detached presentation surface, or an invalid handle for the primary backbuffer. - /// - public RenderSurfaceHandle surface { get; } - - /// - /// Gets whether this pass clears its presentation target before drawing. - /// - public bool clearsPresentationTarget { get; } - - /// - /// Gets the linear clear color for a presentation target. - /// - public RenderClearColor presentationClearColor { get; } - - /// - /// Gets backend-ready view transforms, or for a matrix-free pass. - /// - public RenderViewTransform? viewTransform { get; } - - /// - /// Gets whether callback recording is serial or worker-thread eligible. - /// - public RenderPassRecordingMode recordingMode { get; } - - internal void Execute(RenderPassContext context) => m_execute(context); -} - -/// -/// Bridges compiled graph execution to a concrete graphics backend. -/// -public interface IRenderGraphBackend -{ - /// - /// Begins execution and prepares transient allocations. - /// - /// - /// Compiled graph to execute. - /// - void BeginGraph(CompiledRenderGraph graph); - - /// - /// Begins one scheduled pass and acquires its command encoder. - /// - /// - /// Scheduled pass metadata. - /// - /// - /// A command encoder scoped to this pass. - /// - RenderCommandEncoder BeginPass(CompiledRenderPass pass); - - /// - /// Ends one scheduled pass and releases its encoder. - /// - /// - /// Scheduled pass metadata. - /// - void EndPass(CompiledRenderPass pass); - - /// - /// Ends graph execution without presenting an additional frame. - /// - /// - /// Compiled graph that finished or failed. - /// - void EndGraph(CompiledRenderGraph graph); -} - /// /// Contains validated, culled and topologically scheduled frame work. /// @@ -425,7 +76,9 @@ ulong frameIndex backend.BeginGraph(this); graphStarted = true; if (m_parallelPasses.Length != 0) + { recorded = RecordParallelPasses(frameIndex); + } foreach (CompiledRenderPass pass in m_passes) { bool passStarted = false; @@ -437,9 +90,13 @@ ulong frameIndex commands.SetFrameIndex(frameIndex); passStarted = true; if (recorded is not null && recorded.TryGetValue(pass, out RecordedRenderCommandEncoder? commandList)) + { commandList.Replay(commands); + } else + { pass.Execute(new RenderPassContext(commands, frameIndex)); + } } catch (Exception exception) { @@ -455,13 +112,16 @@ ulong frameIndex } catch (Exception exception) { - passFailure = passFailure is null ? exception + passFailure = passFailure is null + ? exception : new AggregateException("Render pass execution and cleanup both failed.", passFailure, exception); } } } if (passFailure is not null) + { ExceptionDispatchInfo.Capture(passFailure).Throw(); + } } } catch (Exception exception) @@ -483,8 +143,12 @@ ulong frameIndex } } if (recorded is not null) + { foreach (RecordedRenderCommandEncoder commands in recorded.Values) + { commands.Dispose(); + } + } } if (errors is null) @@ -502,18 +166,14 @@ ulong frameIndex private Dictionary RecordParallelPasses(ulong frameIndex) { - var recorded = new System.Collections.Concurrent.ConcurrentDictionary< - CompiledRenderPass, - RecordedRenderCommandEncoder>(); + var recorded = new ConcurrentDictionary(); try { Parallel.ForEach( m_parallelPasses, new ParallelOptions { - MaxDegreeOfParallelism = Math.Max( - 1, - Math.Min(Environment.ProcessorCount, m_parallelPasses.Length)) + MaxDegreeOfParallelism = Math.Max(1, Math.Min(Environment.ProcessorCount, m_parallelPasses.Length)) }, pass => { @@ -524,60 +184,26 @@ private Dictionary RecordParal pass.Execute(new RenderPassContext(commands, frameIndex)); commands.Seal(); if (!recorded.TryAdd(pass, commands)) + { throw new InvalidOperationException("A parallel render pass was recorded more than once."); + } } catch { commands.Dispose(); throw; } - }); + } + ); return recorded.ToDictionary(static pair => pair.Key, static pair => pair.Value); } catch { foreach (RecordedRenderCommandEncoder commands in recorded.Values) + { commands.Dispose(); + } throw; } } } - -/// -/// Contains render-graph compilation diagnostics and an optional executable graph. -/// -public sealed class RenderGraphCompileResult -{ - private readonly IReadOnlyList m_diagnostics; - - internal RenderGraphCompileResult( - CompiledRenderGraph? graph, - IReadOnlyList diagnostics, - int culledPassCount = 0 - ) { - ArgumentOutOfRangeException.ThrowIfNegative(culledPassCount); - this.graph = graph; - m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - this.culledPassCount = culledPassCount; - } - - /// - /// Gets the executable graph, or when compilation failed. - /// - public CompiledRenderGraph? graph { get; } - - /// - /// Gets deterministic compilation diagnostics. - /// - public IReadOnlyList diagnostics => m_diagnostics; - - /// - /// Gets passes removed because they did not contribute to an output or side effect. - /// - public int culledPassCount { get; } - - /// - /// Gets whether an executable graph was produced. - /// - public bool succeeded => graph is not null; -} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs new file mode 100644 index 000000000..dbcdf2c07 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering; + +/// +/// Provides immutable backend-facing metadata for one scheduled pass. +/// +public sealed class CompiledRenderPass +{ + private readonly IReadOnlyList m_attachments; + private readonly Action m_execute; + + internal CompiledRenderPass( + string name, + RenderPhaseID phase, + RenderPassKind kind, + int viewIndex, + IReadOnlyList attachments, + RenderSurfaceHandle surface, + bool clearsPresentationTarget, + RenderClearColor presentationClearColor, + RenderViewTransform? viewTransform, + RenderPassRecordingMode recordingMode, + Action execute + ) { + this.name = name; + this.phase = phase; + this.kind = kind; + this.viewIndex = viewIndex; + m_attachments = Array.AsReadOnly(attachments.ToArray()); + this.surface = surface; + this.clearsPresentationTarget = clearsPresentationTarget; + this.presentationClearColor = presentationClearColor; + this.viewTransform = viewTransform; + this.recordingMode = recordingMode; + m_execute = execute; + } + + /// + /// Gets the unique diagnostic name. + /// + public string name { get; } + + /// + /// Gets the open render phase identifier. + /// + public RenderPhaseID phase { get; } + + /// + /// Gets the pass command domain. + /// + public RenderPassKind kind { get; } + + /// + /// Gets the backend-neutral logical view order. + /// + public int viewIndex { get; } + + /// + /// Gets raster attachments in declaration order. + /// + public IReadOnlyList attachments => m_attachments; + + /// + /// Gets the detached presentation surface, or an invalid handle for the primary backbuffer. + /// + public RenderSurfaceHandle surface { get; } + + /// + /// Gets whether this pass clears its presentation target before drawing. + /// + public bool clearsPresentationTarget { get; } + + /// + /// Gets the linear clear color for a presentation target. + /// + public RenderClearColor presentationClearColor { get; } + + /// + /// Gets backend-ready view transforms, or for a matrix-free pass. + /// + public RenderViewTransform? viewTransform { get; } + + /// + /// Gets whether callback recording is serial or worker-thread eligible. + /// + public RenderPassRecordingMode recordingMode { get; } + + internal void Execute(RenderPassContext context) => m_execute(context); +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs new file mode 100644 index 000000000..3aaf50bce --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs @@ -0,0 +1,53 @@ +namespace Inno.Rendering; + +/// +/// Describes one texture allocation selected by render-graph compilation. +/// +public sealed class CompiledRenderTexture +{ + internal CompiledRenderTexture( + RenderTextureHandle handle, + string name, + RenderTextureDescriptor descriptor, + bool imported, + PersistentTextureHandle persistentHandle, + int physicalSlot + ) { + this.handle = handle; + this.name = name; + this.descriptor = descriptor; + this.imported = imported; + this.persistentHandle = persistentHandle; + this.physicalSlot = physicalSlot; + } + + /// + /// Gets the frame-scoped logical handle. + /// + public RenderTextureHandle handle { get; } + + /// + /// Gets the debug and diagnostic name. + /// + public string name { get; } + + /// + /// Gets texture requirements. + /// + public RenderTextureDescriptor descriptor { get; } + + /// + /// Gets whether the resource was imported from persistent device state. + /// + public bool imported { get; } + + /// + /// Gets the persistent device texture for imported resources. + /// + public PersistentTextureHandle persistentHandle { get; } + + /// + /// Gets the aliasing allocation slot, or negative one for imported resources. + /// + public int physicalSlot { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs index 71191a2fa..d04156904 100644 --- a/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs @@ -11,8 +11,7 @@ public sealed class ComputePassBuilder : RenderPassBuilder internal ComputePassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Sets backend-ready column-major transform matrices exposed to this compute view. @@ -46,11 +45,7 @@ ReadOnlySpan projectionMatrix /// public ComputePassBuilder ReadStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.Read, - RenderResourceUseKind.StorageRead); + graph.AddUse(pass, texture, RenderResourceAccess.Read, RenderResourceUseKind.StorageRead); return this; } @@ -65,11 +60,7 @@ public ComputePassBuilder ReadStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder WriteStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.Write, - RenderResourceUseKind.StorageWrite); + graph.AddUse(pass, texture, RenderResourceAccess.Write, RenderResourceUseKind.StorageWrite); return this; } @@ -84,11 +75,7 @@ public ComputePassBuilder WriteStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder ReadWriteStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.ReadWrite, - RenderResourceUseKind.StorageReadWrite); + graph.AddUse(pass, texture, RenderResourceAccess.ReadWrite, RenderResourceUseKind.StorageReadWrite); return this; } @@ -103,11 +90,7 @@ public ComputePassBuilder ReadWriteStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder ReadStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.Read, - RenderResourceUseKind.StorageRead); + graph.AddUse(pass, buffer, RenderResourceAccess.Read, RenderResourceUseKind.StorageRead); return this; } @@ -122,11 +105,7 @@ public ComputePassBuilder ReadStorageBuffer(RenderBufferHandle buffer) /// public ComputePassBuilder WriteStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.Write, - RenderResourceUseKind.StorageWrite); + graph.AddUse(pass, buffer, RenderResourceAccess.Write, RenderResourceUseKind.StorageWrite); return this; } @@ -141,12 +120,7 @@ public ComputePassBuilder WriteStorageBuffer(RenderBufferHandle buffer) /// public ComputePassBuilder ReadWriteStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.ReadWrite, - RenderResourceUseKind.StorageReadWrite); + graph.AddUse(pass, buffer, RenderResourceAccess.ReadWrite, RenderResourceUseKind.StorageReadWrite); return this; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs index cbc2f14be..e7e2b5e37 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs @@ -11,8 +11,7 @@ public sealed class CopyPassBuilder : RenderPassBuilder internal CopyPassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Declares one texture copy operation. @@ -30,16 +29,8 @@ public CopyPassBuilder CopyTexture( RenderTextureHandle source, RenderTextureHandle destination ) { - graph.AddUse( - pass, - source, - RenderResourceAccess.Read, - RenderResourceUseKind.CopySource); - graph.AddUse( - pass, - destination, - RenderResourceAccess.Write, - RenderResourceUseKind.CopyDestination); + graph.AddUse(pass, source, RenderResourceAccess.Read, RenderResourceUseKind.CopySource); + graph.AddUse(pass, destination, RenderResourceAccess.Write, RenderResourceUseKind.CopyDestination); return this; } @@ -59,16 +50,8 @@ public CopyPassBuilder CopyBuffer( RenderBufferHandle source, RenderBufferHandle destination ) { - graph.AddUse( - pass, - source, - RenderResourceAccess.Read, - RenderResourceUseKind.CopySource); - graph.AddUse( - pass, - destination, - RenderResourceAccess.Write, - RenderResourceUseKind.CopyDestination); + graph.AddUse(pass, source, RenderResourceAccess.Read, RenderResourceUseKind.CopySource); + graph.AddUse(pass, destination, RenderResourceAccess.Write, RenderResourceUseKind.CopyDestination); return this; } } diff --git a/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs b/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs new file mode 100644 index 000000000..58caf0297 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs @@ -0,0 +1,42 @@ +namespace Inno.Rendering; + +/// +/// Bridges compiled graph execution to a concrete graphics backend. +/// +public interface IRenderGraphBackend +{ + /// + /// Begins execution and prepares transient allocations. + /// + /// + /// Compiled graph to execute. + /// + void BeginGraph(CompiledRenderGraph graph); + + /// + /// Begins one scheduled pass and acquires its command encoder. + /// + /// + /// Scheduled pass metadata. + /// + /// + /// A command encoder scoped to this pass. + /// + RenderCommandEncoder BeginPass(CompiledRenderPass pass); + + /// + /// Ends one scheduled pass and releases its encoder. + /// + /// + /// Scheduled pass metadata. + /// + void EndPass(CompiledRenderPass pass); + + /// + /// Ends graph execution without presenting an additional frame. + /// + /// + /// Compiled graph that finished or failed. + /// + void EndGraph(CompiledRenderGraph graph); +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs index 3c58c532c..51ea72949 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs @@ -11,8 +11,7 @@ public sealed class RasterPassBuilder : RenderPassBuilder internal RasterPassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Sets backend-ready column-major transform matrices for this raster view. @@ -115,17 +114,10 @@ public RasterPassBuilder UseColorAttachment( ArgumentOutOfRangeException.ThrowIfNegative(slot); ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); - graph.AddAttachment(pass, new RenderAttachment( - texture, - slot, - false, - mipLevel, - arrayLayer, - loadAction, - storeAction, - clearColor, - 1f, - 0)); + graph.AddAttachment( + pass, + new RenderAttachment(texture, slot, false, mipLevel, arrayLayer, loadAction, storeAction, clearColor, 1f, 0) + ); return this; } @@ -167,18 +159,21 @@ public RasterPassBuilder UseDepthAttachment( ) { ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); - graph.AddAttachment(pass, new RenderAttachment( - texture, - 0, - true, - mipLevel, - arrayLayer, - loadAction, - storeAction, - default, - clearDepth, - clearStencil)); + graph.AddAttachment( + pass, + new RenderAttachment( + texture, + 0, + true, + mipLevel, + arrayLayer, + loadAction, + storeAction, + default, + clearDepth, + clearStencil + ) + ); return this; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs b/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs new file mode 100644 index 000000000..77fb53aba --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs @@ -0,0 +1,14 @@ +namespace Inno.Rendering; + +internal sealed record RenderAttachment( + RenderTextureHandle texture, + int slot, + bool isDepth, + int mipLevel, + int arrayLayer, + RenderLoadAction loadAction, + RenderStoreAction storeAction, + RenderClearColor clearColor, + float clearDepth, + byte clearStencil +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs new file mode 100644 index 000000000..db4abc2a6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs @@ -0,0 +1,9 @@ +namespace Inno.Rendering; + +internal sealed record RenderBufferRecord( + string name, + RenderBufferDescriptor descriptor, + bool imported, + PersistentBufferHandle persistentHandle, + ulong allocationID +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs b/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs new file mode 100644 index 000000000..fa3696a44 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs @@ -0,0 +1,54 @@ +namespace Inno.Rendering; + +/// +/// Stores a linear clear color without depending on an engine math assembly. +/// +public readonly record struct RenderClearColor +{ + /// + /// Creates a linear clear color. + /// + /// + /// Red channel. + /// + /// + /// Green channel. + /// + /// + /// Blue channel. + /// + /// + /// Alpha channel. + /// + public RenderClearColor( + float r, + float g, + float b, + float a = 1f + ) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + + /// + /// Gets the red channel. + /// + public float r { get; } + + /// + /// Gets the green channel. + /// + public float g { get; } + + /// + /// Gets the blue channel. + /// + public float b { get; } + + /// + /// Gets the alpha channel. + /// + public float a { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs index 39e5d3eb3..7fc1d324b 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs @@ -2,16 +2,20 @@ namespace Inno.Rendering; -sealed partial class RenderGraphBuilder +public sealed partial class RenderGraphBuilder { internal void EnsurePassMutable(RenderPassRecord pass) { EnsureMutating(); if (pass.index < m_frozenPassCount || pass.index >= m_passes.Count - || !ReferenceEquals(m_passes[pass.index], pass)) + || !ReferenceEquals(m_passes[pass.index], pass) + ) { throw new InvalidOperationException("The pass declaration was committed or removed by rollback."); + } if (pass.index < m_analysis.passCount) + { m_analysis.Reset(); + } InvalidateValidation(); } @@ -19,9 +23,13 @@ internal void CommitMutation(RenderGraphMutationScope scope) { EnsureCurrentMutation(scope); if (scope.isCommitted) + { throw new InvalidOperationException("The graph mutation has already been committed."); + } if (!GetValidation().result.isValid) + { throw new InvalidOperationException("Invalid graph additions cannot be committed."); + } m_frozenPassCount = m_passes.Count; scope.isCommitted = true; } @@ -35,10 +43,14 @@ internal void EndMutation(RenderGraphMutationScope scope) m_buffers.RemoveRange(scope.bufferCount, m_buffers.Count - scope.bufferCount); m_passes.RemoveRange(scope.passCount, m_passes.Count - scope.passCount); for (int index = m_addedOutputs.Count - 1; index >= scope.outputCount; index--) + { m_outputs.Remove(m_addedOutputs[index]); + } m_addedOutputs.RemoveRange(scope.outputCount, m_addedOutputs.Count - scope.outputCount); if (m_nameScopes.Count > scope.nameScopeCount) + { m_nameScopes.RemoveRange(scope.nameScopeCount, m_nameScopes.Count - scope.nameScopeCount); + } m_frozenPassCount = Math.Min(m_frozenPassCount, m_passes.Count); InvalidateValidation(); m_analysis.Reset(); @@ -47,29 +59,39 @@ internal void EndMutation(RenderGraphMutationScope scope) } m_mutations.RemoveAt(m_mutations.Count - 1); if (m_mutations.Count == 0) + { m_addedOutputs.Clear(); + } } private void EnsureCurrentMutation(RenderGraphMutationScope scope) { EnsureBuilding(); if (m_mutations.Count == 0 || !ReferenceEquals(m_mutations[^1], scope)) + { throw new InvalidOperationException("Render graph mutations must end in nesting order."); + } } private void EnsureMutating() { EnsureBuilding(); if (m_mutations.Count != 0 && m_mutations[^1].isCommitted) + { throw new InvalidOperationException("End the committed mutation scope before adding graph declarations."); + } } private void MarkOutput(RenderResourceKey key) { if (!m_outputs.Add(key)) + { return; + } if (m_mutations.Count != 0) + { m_addedOutputs.Add(key); + } InvalidateValidation(); } @@ -82,7 +104,9 @@ private void InvalidateValidation() private RenderGraphValidationState GetValidation() { if (m_validation is not null && m_validatedRevision == m_revision) + { return m_validation; + } m_validation = RenderGraphValidator.Validate(m_capabilities, m_textures, m_buffers, m_passes, m_outputs, m_analysis); m_validatedRevision = m_revision; return m_validation; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs index f53c68287..8237c5a36 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scripting.Api; namespace Inno.Rendering; @@ -23,8 +22,8 @@ public sealed partial class RenderGraphBuilder private RenderGraphValidationState? m_validation; private long m_revision; private long m_validatedRevision = -1; - private long m_nextNameScopeId; - private ulong m_nextResourceId; + private long m_nextNameScopeID; + private ulong m_nextResourceID; private int m_frozenPassCount; private bool m_compiled; @@ -69,8 +68,8 @@ RenderTextureDescriptor descriptor ) { EnsureMutating(); ValidateNameAndValue(name, descriptor); - RenderTextureHandle handle = new(m_textures.Count, m_generation, checked(++m_nextResourceId)); - m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, false, default, handle.allocationId)); + var handle = new RenderTextureHandle(m_textures.Count, m_generation, checked(++m_nextResourceID)); + m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, false, default, handle.allocationID)); InvalidateValidation(); return handle; } @@ -102,8 +101,8 @@ RenderTextureDescriptor descriptor throw new ArgumentException("Persistent texture handle is invalid.", nameof(texture)); } - RenderTextureHandle handle = new(m_textures.Count, m_generation, checked(++m_nextResourceId)); - m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, true, texture, handle.allocationId)); + var handle = new RenderTextureHandle(m_textures.Count, m_generation, checked(++m_nextResourceID)); + m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, true, texture, handle.allocationID)); InvalidateValidation(); return handle; } @@ -126,8 +125,8 @@ RenderBufferDescriptor descriptor ) { EnsureMutating(); ValidateNameAndValue(name, descriptor); - RenderBufferHandle handle = new(m_buffers.Count, m_generation, checked(++m_nextResourceId)); - m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, false, default, handle.allocationId)); + var handle = new RenderBufferHandle(m_buffers.Count, m_generation, checked(++m_nextResourceID)); + m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, false, default, handle.allocationID)); InvalidateValidation(); return handle; } @@ -159,8 +158,8 @@ RenderBufferDescriptor descriptor throw new ArgumentException("Persistent buffer handle is invalid.", nameof(buffer)); } - RenderBufferHandle handle = new(m_buffers.Count, m_generation, checked(++m_nextResourceId)); - m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, true, buffer, handle.allocationId)); + var handle = new RenderBufferHandle(m_buffers.Count, m_generation, checked(++m_nextResourceID)); + m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, true, buffer, handle.allocationID)); InvalidateValidation(); return handle; } @@ -200,8 +199,14 @@ public RenderGraphMutationScope BeginMutationScope() EnsureMutating(); m_frozenPassCount = m_passes.Count; var scope = new RenderGraphMutationScope( - this, m_textures.Count, m_buffers.Count, m_passes.Count, m_addedOutputs.Count, m_nameScopes.Count, - m_validatedRevision == m_revision ? m_validation : null); + this, + m_textures.Count, + m_buffers.Count, + m_passes.Count, + m_addedOutputs.Count, + m_nameScopes.Count, + m_validatedRevision == m_revision ? m_validation : null + ); m_mutations.Add(scope); return scope; } @@ -219,7 +224,7 @@ public RenderGraphNameScope BeginNameScope(string name) { EnsureMutating(); ArgumentException.ThrowIfNullOrWhiteSpace(name); - long id = checked(++m_nextNameScopeId); + long id = checked(++m_nextNameScopeID); m_nameScopes.Add((id, name.Trim())); return new RenderGraphNameScope(this, id); } @@ -247,11 +252,10 @@ public RenderGraphNameScope BeginNameScope(string name) /// public RasterPassBuilder AddRasterPass( string name, - RenderPhaseId phase, + RenderPhaseID phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Raster, passData, execute)); /// @@ -277,11 +281,10 @@ RenderPassExecute execute /// public ComputePassBuilder AddComputePass( string name, - RenderPhaseId phase, + RenderPhaseID phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Compute, passData, execute)); /// @@ -307,11 +310,10 @@ RenderPassExecute execute /// public CopyPassBuilder AddCopyPass( string name, - RenderPhaseId phase, + RenderPhaseID phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Copy, passData, execute)); /// @@ -325,7 +327,9 @@ public RenderGraphCompileResult Compile() { EnsureBuilding(); if (m_mutations.Count != 0) + { throw new InvalidOperationException("End all graph mutation scopes before final compilation."); + } RenderGraphValidationState validation = GetValidation(); m_compiled = true; return RenderGraphCompiler.Compile(m_generation, m_textures, m_buffers, m_passes, validation); @@ -348,11 +352,17 @@ internal void EndNameScope(long id) { int index = m_nameScopes.FindIndex(scope => scope.id == id); if (index < 0) + { return; + } if (index != m_nameScopes.Count - 1) + { throw new InvalidOperationException("Render graph name scopes must be disposed in nesting order."); + } if (m_mutations.Count != 0 && index < m_mutations[^1].nameScopeCount) + { throw new InvalidOperationException("A mutation cannot close a name scope owned by an earlier declaration."); + } m_nameScopes.RemoveAt(index); } @@ -389,21 +399,21 @@ RenderAttachment attachment pass, attachment.texture, attachment.loadAction == RenderLoadAction.Load - ? RenderResourceAccess.ReadWrite - : RenderResourceAccess.Write, + ? RenderResourceAccess.ReadWrite + : RenderResourceAccess.Write, attachment.isDepth - ? RenderResourceUseKind.DepthStencilAttachment - : RenderResourceUseKind.ColorAttachment); + ? RenderResourceUseKind.DepthStencilAttachment + : RenderResourceUseKind.ColorAttachment + ); } private RenderPassRecord AddPass( string name, - RenderPhaseId phase, + RenderPhaseID phase, RenderPassKind kind, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull { EnsureMutating(); ArgumentException.ThrowIfNullOrWhiteSpace(name); @@ -414,7 +424,7 @@ RenderPassExecute execute throw new ArgumentException($"Render pass '{qualifiedName}' already exists.", nameof(name)); } - RenderPassRecord pass = new() + var pass = new RenderPassRecord() { index = m_passes.Count, name = qualifiedName, @@ -431,8 +441,8 @@ private void EnsureTexture(RenderTextureHandle handle) { EnsureMutating(); if (handle.generation != m_generation || handle.index < 0 || handle.index >= m_textures.Count - || handle.allocationId != m_textures[handle.index].allocationId) - { + || handle.allocationID != m_textures[handle.index].allocationID + ) { throw new ArgumentException("Texture handle does not belong to this render graph generation.", nameof(handle)); } } @@ -441,8 +451,8 @@ private void EnsureBuffer(RenderBufferHandle handle) { EnsureMutating(); if (handle.generation != m_generation || handle.index < 0 || handle.index >= m_buffers.Count - || handle.allocationId != m_buffers[handle.index].allocationId) - { + || handle.allocationID != m_buffers[handle.index].allocationID + ) { throw new ArgumentException("Buffer handle does not belong to this render graph generation.", nameof(handle)); } } @@ -457,14 +467,13 @@ private void EnsureBuilding() private string QualifyName(string name) => m_nameScopes.Count == 0 - ? name - : $"{string.Join('/', m_nameScopes.ConvertAll(static scope => scope.name))}/{name}"; + ? name + : $"{string.Join('/', m_nameScopes.ConvertAll(static scope => scope.name))}/{name}"; private static void ValidateNameAndValue( string name, T value - ) - where T : class + ) where T : class { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(value); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs new file mode 100644 index 000000000..d82c8a889 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering; + +/// +/// Contains render-graph compilation diagnostics and an optional executable graph. +/// +public sealed class RenderGraphCompileResult +{ + private readonly IReadOnlyList m_diagnostics; + + internal RenderGraphCompileResult( + CompiledRenderGraph? graph, + IReadOnlyList diagnostics, + int culledPassCount = 0 + ) { + ArgumentOutOfRangeException.ThrowIfNegative(culledPassCount); + this.graph = graph; + m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + this.culledPassCount = culledPassCount; + } + + /// + /// Gets the executable graph, or when compilation failed. + /// + public CompiledRenderGraph? graph { get; } + + /// + /// Gets deterministic compilation diagnostics. + /// + public IReadOnlyList diagnostics => m_diagnostics; + + /// + /// Gets passes removed because they did not contribute to an output or side effect. + /// + public int culledPassCount { get; } + + /// + /// Gets whether an executable graph was produced. + /// + public bool succeeded => graph is not null; +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs similarity index 75% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs index 5bdcbda66..6dacc9226 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs @@ -1,4 +1,3 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; @@ -10,33 +9,33 @@ private static int[] AllocateTextureSlots( IReadOnlyList textures, IReadOnlyList passes, IReadOnlyDictionary schedulePositions - ) - => AllocateSlots( - textures.Count, - index => textures[index].imported, - ( - left, - right - ) => textures[left].descriptor.Equals(textures[right].descriptor), - new RenderResourceKey(true, 0), - passes, - schedulePositions); + ) => AllocateSlots( + textures.Count, + index => textures[index].imported, + ( + left, + right + ) => textures[left].descriptor.Equals(textures[right].descriptor), + new RenderResourceKey(true, 0), + passes, + schedulePositions + ); private static int[] AllocateBufferSlots( IReadOnlyList buffers, IReadOnlyList passes, IReadOnlyDictionary schedulePositions - ) - => AllocateSlots( - buffers.Count, - index => buffers[index].imported, - ( - left, - right - ) => buffers[left].descriptor.Equals(buffers[right].descriptor), - new RenderResourceKey(false, 0), - passes, - schedulePositions); + ) => AllocateSlots( + buffers.Count, + index => buffers[index].imported, + ( + left, + right + ) => buffers[left].descriptor.Equals(buffers[right].descriptor), + new RenderResourceKey(false, 0), + passes, + schedulePositions + ); private static int[] AllocateSlots( int resourceCount, @@ -46,9 +45,9 @@ private static int[] AllocateSlots( IReadOnlyList passes, IReadOnlyDictionary schedulePositions ) { - int[] firstUses = new int[resourceCount]; - int[] lastUses = new int[resourceCount]; - int[] slots = new int[resourceCount]; + var firstUses = new int[resourceCount]; + var lastUses = new int[resourceCount]; + var slots = new int[resourceCount]; Array.Fill(firstUses, int.MaxValue); Array.Fill(lastUses, -1); Array.Fill(slots, -1); @@ -88,8 +87,8 @@ IReadOnlyDictionary schedulePositions { (int representative, int lastUse) allocation = allocations[slot]; if (allocation.lastUse < firstUses[resource] - && descriptorsEqual(allocation.representative, resource)) - { + && descriptorsEqual(allocation.representative, resource) + ) { selected = slot; allocations[slot] = (allocation.representative, lastUses[resource]); break; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs index 731ef1a9f..21c58606e 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -14,17 +14,22 @@ internal static RenderGraphCompileResult Compile( RenderGraphValidationState validation ) { if (!validation.result.isValid) + { return new RenderGraphCompileResult(null, validation.result.diagnostics); + } Dictionary schedulePositions = []; for (int index = 0; index < validation.schedule.Length; index++) + { schedulePositions.Add(validation.schedule[index], index); + } int[] textureSlots = AllocateTextureSlots(textures, passes, schedulePositions); int[] bufferSlots = AllocateBufferSlots(buffers, passes, schedulePositions); return new RenderGraphCompileResult( BuildCompiledGraph(generation, textures, buffers, passes, validation.schedule, textureSlots, bufferSlots), validation.result.diagnostics, - validation.result.culledPassCount); + validation.result.culledPassCount + ); } private static CompiledRenderGraph BuildCompiledGraph( @@ -46,44 +51,53 @@ IReadOnlyList bufferSlots attachments.Add(new CompiledRenderAttachment(attachment)); } - compiledPasses.Add(new CompiledRenderPass( - pass.name, - pass.phase, - pass.kind, - viewIndex, - attachments, - pass.surface, - pass.clearsPresentationTarget, - pass.presentationClearColor, - pass.viewTransform, - pass.recordingMode, - pass.execute)); + compiledPasses.Add( + new CompiledRenderPass( + pass.name, + pass.phase, + pass.kind, + viewIndex, + attachments, + pass.surface, + pass.clearsPresentationTarget, + pass.presentationClearColor, + pass.viewTransform, + pass.recordingMode, + pass.execute + ) + ); } List compiledTextures = []; for (int index = 0; index < textures.Count; index++) { RenderTextureRecord texture = textures[index]; - compiledTextures.Add(new CompiledRenderTexture( - new RenderTextureHandle(index, generation, texture.allocationId), - texture.name, - texture.descriptor, - texture.imported, - texture.persistentHandle, - textureSlots[index])); + compiledTextures.Add( + new CompiledRenderTexture( + new RenderTextureHandle(index, generation, texture.allocationID), + texture.name, + texture.descriptor, + texture.imported, + texture.persistentHandle, + textureSlots[index] + ) + ); } List compiledBuffers = []; for (int index = 0; index < buffers.Count; index++) { RenderBufferRecord buffer = buffers[index]; - compiledBuffers.Add(new CompiledRenderBuffer( - new RenderBufferHandle(index, generation, buffer.allocationId), - buffer.name, - buffer.descriptor, - buffer.imported, - buffer.persistentHandle, - bufferSlots[index])); + compiledBuffers.Add( + new CompiledRenderBuffer( + new RenderBufferHandle(index, generation, buffer.allocationID), + buffer.name, + buffer.descriptor, + buffer.imported, + buffer.persistentHandle, + bufferSlots[index] + ) + ); } return new CompiledRenderGraph(generation, compiledPasses, compiledTextures, compiledBuffers); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs new file mode 100644 index 000000000..b675e63c6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs @@ -0,0 +1,69 @@ +using System; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering; + +/// +/// Reports one structured render-graph compilation problem. +/// +public sealed class RenderGraphDiagnostic +{ + /// + /// Creates a render-graph diagnostic. + /// + /// + /// Stable machine-readable code. + /// + /// + /// Actionable diagnostic text. + /// + /// + /// Diagnostic impact. + /// + /// + /// Optional related pass name. + /// + /// + /// Optional related resource name. + /// + public RenderGraphDiagnostic( + string code, + string message, + DiagnosticSeverity severity, + string? passName = null, + string? resourceName = null + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + this.code = code; + this.message = message; + this.severity = severity; + this.passName = passName; + this.resourceName = resourceName; + } + + /// + /// Gets the stable machine-readable code. + /// + public string code { get; } + + /// + /// Gets actionable diagnostic text. + /// + public string message { get; } + + /// + /// Gets diagnostic impact. + /// + public DiagnosticSeverity severity { get; } + + /// + /// Gets the related pass name, if any. + /// + public string? passName { get; } + + /// + /// Gets the related resource name, if any. + /// + public string? resourceName { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs index 7119a79cb..d35438b09 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs @@ -53,7 +53,9 @@ public void Dispose() { RenderGraphBuilder? graph = m_graph; if (graph is null) + { return; + } graph.EndMutation(this); m_graph = null; } diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs index 531394fe9..1497f9603 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs @@ -8,8 +8,8 @@ namespace Inno.Rendering; /// public sealed class RenderGraphNameScope : IDisposable { - private RenderGraphBuilder? m_graph; private readonly long m_id; + private RenderGraphBuilder? m_graph; internal RenderGraphNameScope( RenderGraphBuilder graph, @@ -26,9 +26,10 @@ public void Dispose() { RenderGraphBuilder? graph = m_graph; if (graph is null) + { return; + } graph.EndNameScope(m_id); m_graph = null; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs deleted file mode 100644 index 7f2812ced..000000000 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs +++ /dev/null @@ -1,342 +0,0 @@ -using Inno.Core.Diagnostics; -using System; -using System.Collections.Generic; - -namespace Inno.Rendering; - -/// -/// Identifies an open render phase protocol value. -/// -public readonly record struct RenderPhaseId -{ - /// - /// Creates an open render phase identifier. - /// - /// - /// Globally stable phase value. - /// - public RenderPhaseId(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the globally stable phase value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Distinguishes pass command domains for validation and backend execution. -/// -public enum RenderPassKind -{ - /// - /// Raster draw commands with optional attachments. - /// - Raster, - /// - /// Compute dispatch commands. - /// - Compute, - /// - /// Resource copy commands. - /// - Copy -} - -/// -/// Controls where a frame-local pass callback records backend-neutral commands. -/// -public enum RenderPassRecordingMode -{ - /// - /// Records directly on the graph execution thread. - /// - Serial, - /// - /// Records into an isolated command list on a worker thread, then replays in graph order. - /// - Parallel -} - -/// -/// Controls how existing attachment contents enter a raster pass. -/// -public enum RenderLoadAction -{ - /// - /// Preserves prior attachment contents. - /// - Load, - /// - /// Clears the attachment before rendering. - /// - Clear, - /// - /// Does not require prior attachment contents. - /// - Discard -} - -/// -/// Controls whether attachment contents remain valid after a raster pass. -/// -public enum RenderStoreAction -{ - /// - /// Preserves rendered contents. - /// - Store, - /// - /// Allows the backend to discard rendered contents. - /// - Discard -} - -/// -/// Stores a linear clear color without depending on an engine math assembly. -/// -public readonly record struct RenderClearColor -{ - /// - /// Creates a linear clear color. - /// - /// - /// Red channel. - /// - /// - /// Green channel. - /// - /// - /// Blue channel. - /// - /// - /// Alpha channel. - /// - public RenderClearColor( - float r, - float g, - float b, - float a = 1f - ) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } - - /// - /// Gets the red channel. - /// - public float r { get; } - - /// - /// Gets the green channel. - /// - public float g { get; } - - /// - /// Gets the blue channel. - /// - public float b { get; } - - /// - /// Gets the alpha channel. - /// - public float a { get; } -} - -/// -/// Reports one structured render-graph compilation problem. -/// -public sealed class RenderGraphDiagnostic -{ - /// - /// Creates a render-graph diagnostic. - /// - /// - /// Stable machine-readable code. - /// - /// - /// Actionable diagnostic text. - /// - /// - /// Diagnostic impact. - /// - /// - /// Optional related pass name. - /// - /// - /// Optional related resource name. - /// - public RenderGraphDiagnostic( - string code, - string message, - DiagnosticSeverity severity, - string? passName = null, - string? resourceName = null - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(code); - ArgumentException.ThrowIfNullOrWhiteSpace(message); - this.code = code; - this.message = message; - this.severity = severity; - this.passName = passName; - this.resourceName = resourceName; - } - - /// - /// Gets the stable machine-readable code. - /// - public string code { get; } - - /// - /// Gets actionable diagnostic text. - /// - public string message { get; } - - /// - /// Gets diagnostic impact. - /// - public DiagnosticSeverity severity { get; } - - /// - /// Gets the related pass name, if any. - /// - public string? passName { get; } - - /// - /// Gets the related resource name, if any. - /// - public string? resourceName { get; } -} - -internal enum RenderResourceAccess -{ - Read, - Write, - ReadWrite -} - -internal enum RenderResourceUseKind -{ - GenericRead, - StorageRead, - StorageWrite, - StorageReadWrite, - CopySource, - CopyDestination, - ColorAttachment, - DepthStencilAttachment -} - -internal readonly record struct RenderResourceKey( - bool isTexture, - int index -); - -internal sealed record RenderResourceUse( - RenderResourceKey key, - RenderResourceAccess access, - RenderResourceUseKind kind -); - -internal sealed record RenderAttachment( - RenderTextureHandle texture, - int slot, - bool isDepth, - int mipLevel, - int arrayLayer, - RenderLoadAction loadAction, - RenderStoreAction storeAction, - RenderClearColor clearColor, - float clearDepth, - byte clearStencil -); - -internal sealed class RenderPassRecord -{ - internal required int index { get; init; } - /// - /// Gets the human-readable name used for presentation and diagnostics. - /// - public required string name { get; init; } - /// - /// Gets the render phase that owns this pass declaration. - /// - public required RenderPhaseId phase { get; init; } - /// - /// Gets the operation kind that determines how this value is interpreted. - /// - public required RenderPassKind kind { get; init; } - /// - /// Gets the callback that records commands for this render pass. - /// - public required Action execute { get; init; } - /// - /// Gets the render phases that must execute after this pass. - /// - public List before { get; } = []; - /// - /// Gets the render phases that must execute before this pass. - /// - public List after { get; } = []; - /// - /// Gets the complete resource access declarations used for graph dependency analysis. - /// - public List resources { get; } = []; - /// - /// Gets the color and depth attachments written by this render pass. - /// - public List attachments { get; } = []; - /// - /// Gets the presentation surface targeted by this render pass. - /// - public RenderSurfaceHandle surface { get; set; } - /// - /// Gets the color used when the presentation surface is cleared. - /// - public RenderClearColor presentationClearColor { get; set; } - /// - /// Gets the optional view and projection transform applied by this pass. - /// - public RenderViewTransform? viewTransform { get; set; } - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool clearsPresentationTarget { get; set; } - /// - /// Gets whether this value has side effect. - /// - public bool hasSideEffect { get; set; } - /// - /// Gets whether the pass records graphics, compute, or transfer commands. - /// - public RenderPassRecordingMode recordingMode { get; set; } -} - -internal sealed record RenderTextureRecord( - string name, - RenderTextureDescriptor descriptor, - bool imported, - PersistentTextureHandle persistentHandle, - ulong allocationId -); - -internal sealed record RenderBufferRecord( - string name, - RenderBufferDescriptor descriptor, - bool imported, - PersistentBufferHandle persistentHandle, - ulong allocationId -); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidationWorkspace.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidationWorkspace.cs index 93129a5b4..2e6ce48ee 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidationWorkspace.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidationWorkspace.cs @@ -5,9 +5,6 @@ namespace Inno.Rendering; // Frame-local analysis of the accepted immutable prefix. No callbacks or extension instances are retained. internal sealed class RenderGraphValidationWorkspace { - internal int textureCount; - internal int bufferCount; - internal int passCount; internal readonly Dictionary lastWriters = []; internal readonly Dictionary> readers = []; internal readonly HashSet initialized = []; @@ -21,6 +18,9 @@ internal sealed class RenderGraphValidationWorkspace internal readonly List> dependants = []; internal readonly PriorityQueue ready = new(); internal readonly List schedule = []; + internal int textureCount; + internal int bufferCount; + internal int passCount; internal void Reset() { diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs similarity index 88% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs index 196e30c4b..4019c6e02 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs @@ -1,6 +1,5 @@ -using Inno.Core.Diagnostics; -using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -39,18 +38,23 @@ List diagnostics foreach (RenderResourceUse use in pass.resources) { if (!analysis.uniqueUses.Add(use.key)) + { continue; + } bool reads = use.access is RenderResourceAccess.Read or RenderResourceAccess.ReadWrite; bool writes = use.access is RenderResourceAccess.Write or RenderResourceAccess.ReadWrite; if (reads && !initialized.Contains(use.key)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_UNINITIALIZED_READ", - $"Pass '{passes[passIndex].name}' reads '{GetResourceName(use.key, textures, buffers)}' before it is initialized.", - DiagnosticSeverity.Error, - passes[passIndex].name, - GetResourceName(use.key, textures, buffers))); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_UNINITIALIZED_READ", + $"Pass '{passes[passIndex].name}' reads '{GetResourceName(use.key, textures, buffers)}' before it is initialized.", + DiagnosticSeverity.Error, + passes[passIndex].name, + GetResourceName(use.key, textures, buffers) + ) + ); } if (lastWriters.TryGetValue(use.key, out int writer)) @@ -102,7 +106,6 @@ List diagnostics } } } - } private static bool StoresResult( @@ -113,8 +116,8 @@ RenderResourceKey key { if (key.isTexture && attachment.texture.index == key.index - && attachment.storeAction == RenderStoreAction.Discard) - { + && attachment.storeAction == RenderStoreAction.Discard + ) { return false; } } @@ -155,15 +158,13 @@ private static bool IsImported( RenderResourceKey key, IReadOnlyList textures, IReadOnlyList buffers - ) - => key.isTexture ? textures[key.index].imported : buffers[key.index].imported; + ) => key.isTexture ? textures[key.index].imported : buffers[key.index].imported; private static string GetResourceName( RenderResourceKey key, IReadOnlyList textures, IReadOnlyList buffers - ) - => key.isTexture ? textures[key.index].name : buffers[key.index].name; + ) => key.isTexture ? textures[key.index].name : buffers[key.index].name; private static void AddDependency( int dependency, diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs similarity index 98% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs index 29dad5006..9d64bea70 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs @@ -1,5 +1,3 @@ -using Inno.Core.Diagnostics; -using System; using System.Collections.Generic; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs index 03f0ad95a..f4a7647e6 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -28,43 +28,64 @@ RenderGraphValidationWorkspace analysis analysis.bufferCount = buffers.Count; analysis.passCount = passes.Count; // End-of-graph output and scheduling diagnostics are revision-local, not prefix state. - diagnostics = new List(diagnostics); + diagnostics = [.. diagnostics]; foreach (RenderResourceKey output in outputs) + { if (!analysis.initialized.Contains(output)) - diagnostics.Add(new RenderGraphDiagnostic("RENDER_GRAPH_OUTPUT_UNINITIALIZED", - $"Graph output '{GetResourceName(output, textures, buffers)}' has no stored contents at the end of the graph.", - DiagnosticSeverity.Error, resourceName: GetResourceName(output, textures, buffers))); + { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_OUTPUT_UNINITIALIZED", + $"Graph output '{GetResourceName(output, textures, buffers)}' has no stored contents at the end of the graph.", + DiagnosticSeverity.Error, + resourceName: GetResourceName(output, textures, buffers) + ) + ); + } + } if (ContainsErrors(diagnostics)) + { return CreateState(null); + } HashSet livePasses = FindLivePasses(textures, buffers, passes, outputs, analysis); List? schedule = TopologicalSort(passes.Count, livePasses, analysis); if (schedule is null) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_CYCLE", - "Pass ordering and resource dependencies contain a cycle.", - DiagnosticSeverity.Error)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_CYCLE", + "Pass ordering and resource dependencies contain a cycle.", + DiagnosticSeverity.Error + ) + ); return CreateState(null); } if (schedule.Count > capabilities.limits.maxViews) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_VIEW_LIMIT", - $"Graph requires {schedule.Count} views but the device supports {capabilities.limits.maxViews}.", - DiagnosticSeverity.Error)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_VIEW_LIMIT", + $"Graph requires {schedule.Count} views but the device supports {capabilities.limits.maxViews}.", + DiagnosticSeverity.Error + ) + ); return CreateState(null); } return CreateState(schedule.ToArray()); RenderGraphValidationState CreateState(int[]? orderedPasses) - => new(new RenderGraphValidationResult( - orderedPasses is not null, - diagnostics, - passes.Count, - orderedPasses?.Length ?? 0, - textures.Count, - buffers.Count), orderedPasses ?? []); + => new( + new RenderGraphValidationResult( + orderedPasses is not null, + diagnostics, + passes.Count, + orderedPasses?.Length ?? 0, + textures.Count, + buffers.Count + ), + orderedPasses ?? [] + ); } private static void ValidateResources( @@ -81,90 +102,114 @@ int bufferStart RenderTextureDescriptor descriptor = texture.descriptor; if (descriptor.width > capabilities.limits.maxTextureSize || descriptor.height > capabilities.limits.maxTextureSize - || descriptor.depth > capabilities.limits.maxTextureSize) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_LIMIT", - $"Texture '{texture.name}' exceeds the device texture extent limit.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + || descriptor.depth > capabilities.limits.maxTextureSize + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_LIMIT", + $"Texture '{texture.name}' exceeds the device texture extent limit.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Texture2D && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.Texture2DArray)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED", - $"Texture '{texture.name}' requires two-dimensional texture-array capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.Texture2DArray) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED", + $"Texture '{texture.name}' requires two-dimensional texture-array capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Texture3D - && !capabilities.Supports(GraphicsCapability.Texture3D)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED", - $"Texture '{texture.name}' requires three-dimensional texture capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.Texture3D) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED", + $"Texture '{texture.name}' requires three-dimensional texture capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Cube && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.TextureCubeArray)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_CUBE_ARRAY_UNSUPPORTED", - $"Texture '{texture.name}' requires cubemap-array capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.TextureCubeArray) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_CUBE_ARRAY_UNSUPPORTED", + $"Texture '{texture.name}' requires cubemap-array capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } bool attachmentUsage = (descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0; + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0; if ((descriptor.usage & RenderTextureUsage.Sampled) != 0 - && !capabilities.SupportsSampled(descriptor.format, descriptor.dimension)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported for sampling.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsSampled(descriptor.format, descriptor.dimension) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported for sampling.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (attachmentUsage && !capabilities.SupportsRenderTarget(descriptor.format)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_ATTACHMENT_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported as an attachment.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_ATTACHMENT_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported as an attachment.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (attachmentUsage && descriptor.sampleCount > 1 - && !capabilities.SupportsMultisampleRenderTarget(descriptor.format)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported as a multisampled attachment.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsMultisampleRenderTarget(descriptor.format) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported as a multisampled attachment.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if ((descriptor.usage & RenderTextureUsage.Storage) != 0 && (!capabilities.Supports(GraphicsCapability.Compute) || !capabilities.Supports(GraphicsCapability.StorageTexture) || (!capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Read) - && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write)))) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_STORAGE_UNSUPPORTED", - $"Texture '{texture.name}' cannot be used for unordered shader access on this device.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write))) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_STORAGE_UNSUPPORTED", + $"Texture '{texture.name}' cannot be used for unordered shader access on this device.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } } @@ -172,25 +217,30 @@ int bufferStart { RenderBufferRecord buffer = buffers[bufferIndex]; if ((buffer.descriptor.usage & RenderBufferUsage.Storage) != 0 - && !capabilities.Supports(GraphicsCapability.StorageBuffer)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_STORAGE_BUFFER_UNSUPPORTED", - $"Buffer '{buffer.name}' requires storage-buffer capability.", - DiagnosticSeverity.Error, - resourceName: buffer.name)); + && !capabilities.Supports(GraphicsCapability.StorageBuffer) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_STORAGE_BUFFER_UNSUPPORTED", + $"Buffer '{buffer.name}' requires storage-buffer capability.", + DiagnosticSeverity.Error, + resourceName: buffer.name + ) + ); } - if ((buffer.descriptor.usage & RenderBufferUsage.Index) != 0 && buffer.descriptor.elementStride == sizeof(uint) - && !capabilities.Supports(GraphicsCapability.Index32)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_INDEX32_UNSUPPORTED", - $"Buffer '{buffer.name}' requires unsigned 32-bit index capability.", - DiagnosticSeverity.Error, - resourceName: buffer.name)); + && !capabilities.Supports(GraphicsCapability.Index32) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_INDEX32_UNSUPPORTED", + $"Buffer '{buffer.name}' requires unsigned 32-bit index capability.", + DiagnosticSeverity.Error, + resourceName: buffer.name + ) + ); } } } @@ -208,49 +258,64 @@ int passStart RenderPassRecord pass = passes[passIndex]; if (pass.kind == RenderPassKind.Compute && !capabilities.Supports(GraphicsCapability.Compute)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_COMPUTE_UNSUPPORTED", - $"Compute pass '{pass.name}' requires compute capability.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_COMPUTE_UNSUPPORTED", + $"Compute pass '{pass.name}' requires compute capability.", + DiagnosticSeverity.Error, + pass.name + ) + ); } ValidatePassResourceConflicts(pass, diagnostics); ValidatePassResourceUsage(capabilities, textures, buffers, pass, diagnostics); if (pass.kind != RenderPassKind.Raster && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_DOMAIN", - $"Pass '{pass.name}' is not a raster pass and cannot own attachments.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_DOMAIN", + $"Pass '{pass.name}' is not a raster pass and cannot own attachments.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.surface.isValid && pass.kind != RenderPassKind.Raster) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_SURFACE_DOMAIN", - $"Pass '{pass.name}' is not a raster pass and cannot target a presentation surface.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_SURFACE_DOMAIN", + $"Pass '{pass.name}' is not a raster pass and cannot target a presentation surface.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.surface.isValid && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_SURFACE_ATTACHMENTS", - $"Raster pass '{pass.name}' cannot target a presentation surface and texture attachments together.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_SURFACE_ATTACHMENTS", + $"Raster pass '{pass.name}' cannot target a presentation surface and texture attachments together.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.clearsPresentationTarget && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_PRESENTATION_CLEAR_ATTACHMENTS", - $"Raster pass '{pass.name}' cannot combine a presentation clear with texture attachments.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_PRESENTATION_CLEAR_ATTACHMENTS", + $"Raster pass '{pass.name}' cannot combine a presentation clear with texture attachments.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.attachments.Count == 0) @@ -269,32 +334,38 @@ int passStart RenderTextureDescriptor descriptor = texture.descriptor; if (!attachedTextures.Add(attachment.texture.index)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_DUPLICATE_ATTACHMENT_RESOURCE", - $"Raster pass '{pass.name}' attaches texture '{texture.name}' more than once.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_DUPLICATE_ATTACHMENT_RESOURCE", + $"Raster pass '{pass.name}' attaches texture '{texture.name}' more than once.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if (attachment.mipLevel >= descriptor.mipCount || (attachment.mipLevel < descriptor.mipCount - && attachment.arrayLayer >= descriptor.GetSubresourceLayerCount(attachment.mipLevel))) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_SUBRESOURCE", - $"Raster pass '{pass.name}' attachment subresource is outside texture '{texture.name}'.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + && attachment.arrayLayer >= descriptor.GetSubresourceLayerCount(attachment.mipLevel)) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_SUBRESOURCE", + $"Raster pass '{pass.name}' attachment subresource is outside texture '{texture.name}'.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if (attachment.isDepth) { depthCount++; if ((descriptor.usage & RenderTextureUsage.DepthStencilAttachment) == 0 - || !IsDepthFormat(descriptor.format)) - { + || !IsDepthFormat(descriptor.format) + ) { AddAttachmentUsageError(pass, texture, "depth-stencil", diagnostics); } } @@ -303,17 +374,20 @@ int passStart colorCount++; if (!colorSlots.Add(attachment.slot)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_DUPLICATE_ATTACHMENT", - $"Raster pass '{pass.name}' uses color attachment slot {attachment.slot} more than once.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_DUPLICATE_ATTACHMENT", + $"Raster pass '{pass.name}' uses color attachment slot {attachment.slot} more than once.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if ((descriptor.usage & RenderTextureUsage.ColorAttachment) == 0 - || IsDepthFormat(descriptor.format)) - { + || IsDepthFormat(descriptor.format) + ) { AddAttachmentUsageError(pass, texture, "color", diagnostics); } } @@ -325,24 +399,30 @@ int passStart int firstHeight = MipExtent(firstDescriptor.height, pass.attachments[0].mipLevel); if (firstWidth != attachmentWidth || firstHeight != attachmentHeight - || firstDescriptor.sampleCount != descriptor.sampleCount) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_MISMATCH", - $"Raster pass '{pass.name}' attachments must have equal width, height and sample count.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + || firstDescriptor.sampleCount != descriptor.sampleCount + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_MISMATCH", + $"Raster pass '{pass.name}' attachments must have equal width, height and sample count.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } } if (colorCount > capabilities.limits.maxColorAttachments || depthCount > 1) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_LIMIT", - $"Raster pass '{pass.name}' exceeds the device attachment limit.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_LIMIT", + $"Raster pass '{pass.name}' exceeds the device attachment limit.", + DiagnosticSeverity.Error, + pass.name + ) + ); } } } @@ -370,11 +450,14 @@ List diagnostics continue; } - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_PASS_HAZARD", - $"Pass '{pass.name}' declares conflicting access for one resource. Use an explicit ReadWrite declaration.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_PASS_HAZARD", + $"Pass '{pass.name}' declares conflicting access for one resource. Use an explicit ReadWrite declaration.", + DiagnosticSeverity.Error, + pass.name + ) + ); } } @@ -394,8 +477,8 @@ List diagnostics { RenderResourceUseKind.GenericRead => RenderTextureUsage.Sampled, RenderResourceUseKind.StorageRead - or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite + or RenderResourceUseKind.StorageWrite + or RenderResourceUseKind.StorageReadWrite => RenderTextureUsage.Storage, RenderResourceUseKind.CopySource => RenderTextureUsage.CopySource, RenderResourceUseKind.CopyDestination => RenderTextureUsage.CopyDestination, @@ -411,20 +494,15 @@ or RenderResourceUseKind.StorageReadWrite if (use.kind is RenderResourceUseKind.CopySource or RenderResourceUseKind.CopyDestination - && !capabilities.Supports(GraphicsCapability.TextureBlit)) - { - AddCapabilityError( - pass, - texture.name, - "texture-copy", - GraphicsCapability.TextureBlit, - diagnostics); + && !capabilities.Supports(GraphicsCapability.TextureBlit) + ) { + AddCapabilityError(pass, texture.name, "texture-copy", GraphicsCapability.TextureBlit, diagnostics); } if (use.kind is RenderResourceUseKind.StorageRead or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite) - { + or RenderResourceUseKind.StorageReadWrite + ) { RenderStorageAccess access = use.kind switch { RenderResourceUseKind.StorageRead => RenderStorageAccess.Read, @@ -433,14 +511,17 @@ or RenderResourceUseKind.StorageWrite _ => throw new InvalidOperationException("Unexpected storage texture access.") }; if (!capabilities.Supports(GraphicsCapability.StorageTexture) - || !capabilities.SupportsStorage(texture.descriptor.format, access)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED", - $"Texture '{texture.name}' does not support {access} storage access required by pass '{pass.name}'.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + || !capabilities.SupportsStorage(texture.descriptor.format, access) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED", + $"Texture '{texture.name}' does not support {access} storage access required by pass '{pass.name}'.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } } @@ -450,8 +531,8 @@ or RenderResourceUseKind.StorageWrite RenderBufferUsage requiredBufferUsage = use.kind switch { RenderResourceUseKind.StorageRead - or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite + or RenderResourceUseKind.StorageWrite + or RenderResourceUseKind.StorageReadWrite => RenderBufferUsage.Storage, RenderResourceUseKind.CopySource => RenderBufferUsage.CopySource, RenderResourceUseKind.CopyDestination => RenderBufferUsage.CopyDestination, @@ -460,13 +541,7 @@ or RenderResourceUseKind.StorageReadWrite if (requiredBufferUsage != 0) { // Buffer names and descriptors are validated by the overload below. - ValidateBufferUse( - capabilities, - buffers, - pass, - use, - requiredBufferUsage, - diagnostics); + ValidateBufferUse(capabilities, buffers, pass, use, requiredBufferUsage, diagnostics); } } } @@ -486,14 +561,9 @@ List diagnostics } if (use.kind is RenderResourceUseKind.CopySource or RenderResourceUseKind.CopyDestination - && !capabilities.Supports(GraphicsCapability.BufferCopy)) - { - AddCapabilityError( - pass, - buffer.name, - "buffer-copy", - GraphicsCapability.BufferCopy, - diagnostics); + && !capabilities.Supports(GraphicsCapability.BufferCopy) + ) { + AddCapabilityError(pass, buffer.name, "buffer-copy", GraphicsCapability.BufferCopy, diagnostics); } } @@ -518,28 +588,30 @@ private static void AddAttachmentUsageError( RenderTextureRecord texture, string role, List diagnostics - ) { - diagnostics.Add(new RenderGraphDiagnostic( + ) => diagnostics.Add( + new RenderGraphDiagnostic( "RENDER_GRAPH_ATTACHMENT_USAGE", $"Texture '{texture.name}' is not declared for {role} attachment usage.", DiagnosticSeverity.Error, pass.name, - texture.name)); - } + texture.name + ) + ); private static void AddResourceUsageError( RenderPassRecord pass, string resourceName, string requiredUsage, List diagnostics - ) { - diagnostics.Add(new RenderGraphDiagnostic( + ) => diagnostics.Add( + new RenderGraphDiagnostic( "RENDER_GRAPH_RESOURCE_USAGE", $"Resource '{resourceName}' used by pass '{pass.name}' requires '{requiredUsage}' usage.", DiagnosticSeverity.Error, pass.name, - resourceName)); - } + resourceName + ) + ); private static void AddCapabilityError( RenderPassRecord pass, @@ -547,12 +619,13 @@ private static void AddCapabilityError( string operation, GraphicsCapability requiredFeature, List diagnostics - ) { - diagnostics.Add(new RenderGraphDiagnostic( + ) => diagnostics.Add( + new RenderGraphDiagnostic( "RENDER_GRAPH_CAPABILITY_UNSUPPORTED", $"Pass '{pass.name}' requires '{requiredFeature}' for {operation} operations.", DiagnosticSeverity.Error, pass.name, - resourceName)); - } + resourceName + ) + ); } diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs b/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs new file mode 100644 index 000000000..e3275d185 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Controls how existing attachment contents enter a raster pass. +/// +public enum RenderLoadAction +{ + /// + /// Preserves prior attachment contents. + /// + Load, + /// + /// Clears the attachment before rendering. + /// + Clear, + /// + /// Does not require prior attachment contents. + /// + Discard +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs index 842c672c2..d3b9149e3 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs @@ -19,9 +19,6 @@ RenderPassRecord pass m_pass = pass; } - internal RenderGraphBuilder graph => m_graph; - internal RenderPassRecord pass => m_pass; - /// /// Orders this pass before every pass in a target phase. /// @@ -31,7 +28,7 @@ RenderPassRecord pass /// /// This builder for fluent declarations. /// - public RenderPassBuilder Before(RenderPhaseId phase) + public RenderPassBuilder Before(RenderPhaseID phase) { m_graph.EnsurePassMutable(m_pass); m_pass.before.Add(phase); @@ -47,7 +44,7 @@ public RenderPassBuilder Before(RenderPhaseId phase) /// /// This builder for fluent declarations. /// - public RenderPassBuilder After(RenderPhaseId phase) + public RenderPassBuilder After(RenderPhaseID phase) { m_graph.EnsurePassMutable(m_pass); m_pass.after.Add(phase); @@ -70,13 +67,13 @@ public RenderPassBuilder HasSideEffect() /// /// Opts this pass into worker-thread recording through an isolated backend-neutral command list. /// + /// + /// This builder for fluent declarations. + /// /// /// Pass data and code reached by the callback must be safe for worker-thread access. GPU execution /// and backend view order remain identical to the compiled graph order. /// - /// - /// This builder for fluent declarations. - /// public RenderPassBuilder AllowParallelRecording() { m_graph.EnsurePassMutable(m_pass); @@ -95,11 +92,7 @@ public RenderPassBuilder AllowParallelRecording() /// public RenderPassBuilder ReadTexture(RenderTextureHandle texture) { - m_graph.AddUse( - m_pass, - texture, - RenderResourceAccess.Read, - RenderResourceUseKind.GenericRead); + m_graph.AddUse(m_pass, texture, RenderResourceAccess.Read, RenderResourceUseKind.GenericRead); return this; } @@ -114,12 +107,10 @@ public RenderPassBuilder ReadTexture(RenderTextureHandle texture) /// public RenderPassBuilder ReadBuffer(RenderBufferHandle buffer) { - m_graph.AddUse( - m_pass, - buffer, - RenderResourceAccess.Read, - RenderResourceUseKind.GenericRead); + m_graph.AddUse(m_pass, buffer, RenderResourceAccess.Read, RenderResourceUseKind.GenericRead); return this; } -} + internal RenderGraphBuilder graph => m_graph; + internal RenderPassRecord pass => m_pass; +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs new file mode 100644 index 000000000..7d842312b --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Distinguishes pass command domains for validation and backend execution. +/// +public enum RenderPassKind +{ + /// + /// Raster draw commands with optional attachments. + /// + Raster, + /// + /// Compute dispatch commands. + /// + Compute, + /// + /// Resource copy commands. + /// + Copy +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs new file mode 100644 index 000000000..5b20057c4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering; + +internal sealed class RenderPassRecord +{ + /// + /// Gets the human-readable name used for presentation and diagnostics. + /// + public required string name { get; init; } + + /// + /// Gets the render phase that owns this pass declaration. + /// + public required RenderPhaseID phase { get; init; } + + /// + /// Gets the operation kind that determines how this value is interpreted. + /// + public required RenderPassKind kind { get; init; } + + /// + /// Gets the callback that records commands for this render pass. + /// + public required Action execute { get; init; } + + /// + /// Gets the render phases that must execute after this pass. + /// + public List before { get; } = []; + + /// + /// Gets the render phases that must execute before this pass. + /// + public List after { get; } = []; + + /// + /// Gets the complete resource access declarations used for graph dependency analysis. + /// + public List resources { get; } = []; + + /// + /// Gets the color and depth attachments written by this render pass. + /// + public List attachments { get; } = []; + + /// + /// Gets the presentation surface targeted by this render pass. + /// + public RenderSurfaceHandle surface { get; set; } + + /// + /// Gets the color used when the presentation surface is cleared. + /// + public RenderClearColor presentationClearColor { get; set; } + + /// + /// Gets the optional view and projection transform applied by this pass. + /// + public RenderViewTransform? viewTransform { get; set; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool clearsPresentationTarget { get; set; } + + /// + /// Gets whether this value has side effect. + /// + public bool hasSideEffect { get; set; } + + /// + /// Gets whether the pass records graphics, compute, or transfer commands. + /// + public RenderPassRecordingMode recordingMode { get; set; } + + internal required int index { get; init; } +} + +/// +/// Controls where a frame-local pass callback records backend-neutral commands. +/// +public enum RenderPassRecordingMode +{ + /// + /// Records directly on the graph execution thread. + /// + Serial, + /// + /// Records into an isolated command list on a worker thread, then replays in graph order. + /// + Parallel +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs new file mode 100644 index 000000000..333376290 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs @@ -0,0 +1,34 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies an open render phase protocol value. +/// +public readonly record struct RenderPhaseID +{ + /// + /// Creates an open render phase identifier. + /// + /// + /// Globally stable phase value. + /// + public RenderPhaseID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the globally stable phase value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs new file mode 100644 index 000000000..d5c2dc5ff --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs @@ -0,0 +1,8 @@ +namespace Inno.Rendering; + +internal enum RenderResourceAccess +{ + Read, + Write, + ReadWrite +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs new file mode 100644 index 000000000..f8233ff51 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs @@ -0,0 +1,6 @@ +namespace Inno.Rendering; + +internal readonly record struct RenderResourceKey( + bool isTexture, + int index +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs new file mode 100644 index 000000000..61e59607f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs @@ -0,0 +1,7 @@ +namespace Inno.Rendering; + +internal sealed record RenderResourceUse( + RenderResourceKey key, + RenderResourceAccess access, + RenderResourceUseKind kind +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs new file mode 100644 index 000000000..4e0b99eb3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs @@ -0,0 +1,13 @@ +namespace Inno.Rendering; + +internal enum RenderResourceUseKind +{ + GenericRead, + StorageRead, + StorageWrite, + StorageReadWrite, + CopySource, + CopyDestination, + ColorAttachment, + DepthStencilAttachment +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs b/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs new file mode 100644 index 000000000..74ed44de2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs @@ -0,0 +1,16 @@ +namespace Inno.Rendering; + +/// +/// Controls whether attachment contents remain valid after a raster pass. +/// +public enum RenderStoreAction +{ + /// + /// Preserves rendered contents. + /// + Store, + /// + /// Allows the backend to discard rendered contents. + /// + Discard +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs new file mode 100644 index 000000000..c4dbe479d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs @@ -0,0 +1,9 @@ +namespace Inno.Rendering; + +internal sealed record RenderTextureRecord( + string name, + RenderTextureDescriptor descriptor, + bool imported, + PersistentTextureHandle persistentHandle, + ulong allocationID +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs b/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs new file mode 100644 index 000000000..0cadf0e2c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs @@ -0,0 +1,52 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Stores backend-ready column-major transform matrices for one programmable view. +/// +public sealed class RenderViewTransform +{ + private readonly float[] m_viewMatrix; + private readonly float[] m_projectionMatrix; + + /// + /// Creates a raster view transform. + /// + /// + /// Exactly sixteen column-major world-to-view values. + /// + /// + /// Exactly sixteen column-major projection values. + /// + public RenderViewTransform( + ReadOnlySpan viewMatrix, + ReadOnlySpan projectionMatrix + ) { + if (viewMatrix.Length != 16) + { + throw new ArgumentException("A view matrix requires exactly sixteen values.", nameof(viewMatrix)); + } + + if (projectionMatrix.Length != 16) + { + throw new ArgumentException( + "A projection matrix requires exactly sixteen values.", + nameof(projectionMatrix) + ); + } + + m_viewMatrix = viewMatrix.ToArray(); + m_projectionMatrix = projectionMatrix.ToArray(); + } + + /// + /// Gets the immutable column-major view matrix. + /// + public ReadOnlyMemory viewMatrix => m_viewMatrix; + + /// + /// Gets the immutable column-major projection matrix. + /// + public ReadOnlyMemory projectionMatrix => m_projectionMatrix; +} diff --git a/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs b/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs index efb733e2d..9eaa6d1d9 100644 --- a/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs +++ b/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs @@ -1,5 +1,4 @@ using System; - using Inno.Rendering; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Properties/ScriptingApi.cs b/src/services/rendering/Inno.Rendering/Properties/ScriptingApi.cs index 8b834c9fa..82ef08496 100644 --- a/src/services/rendering/Inno.Rendering/Properties/ScriptingApi.cs +++ b/src/services/rendering/Inno.Rendering/Properties/ScriptingApi.cs @@ -20,7 +20,7 @@ [assembly: ScriptingApiExport(typeof(RenderBufferSlice), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderTextureHandle), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderBufferHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(RenderBindingId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(RenderBindingID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(PersistentTextureHandle), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(PersistentBufferHandle), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderSurfaceHandle), ScriptingApiScope.Runtime)] @@ -59,9 +59,9 @@ [assembly: ScriptingApiExport(typeof(RenderCommandEncoder), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderPassContext), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderPassExecute<>), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(RenderPhaseId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(RenderResourceId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(RenderDataChannelId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(RenderPhaseID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(RenderResourceID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(RenderDataChannelID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderPassKind), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderPassRecordingMode), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(RenderLoadAction), ScriptingApiScope.Runtime)] @@ -84,7 +84,7 @@ [assembly: ScriptingApiExport(typeof(ShaderPropertyType), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderPropertyBindingKind), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderProgramKind), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(ShaderPropertyId), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(ShaderPropertyID), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderInterfaceBinding), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ShaderInterface), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(IRenderFrameUploadService), ScriptingApiScope.Runtime)] diff --git a/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs b/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs index a9abf0a55..4b96f3404 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs @@ -12,8 +12,8 @@ public static class GraphicsProgramArtifactCodec private const int C_MAX_STAGE_BYTES = 128 * 1024 * 1024; private const int C_MAX_BINDINGS = 4096; private const int C_MAX_NAME_BYTES = 8192; - private static readonly UTF8Encoding Utf8 = new(false, true); - private static readonly byte[] Magic = "INNOGPU"u8.ToArray(); + private static readonly UTF8Encoding UTF8 = new(false, true); + private static readonly byte[] MAGIC = "INNOGPU"u8.ToArray(); /// /// Encodes owned program binaries, reflected bindings, and raster state for device distribution. @@ -35,12 +35,14 @@ public static byte[] Encode(GraphicsPipelineDescriptor descriptor) { ArgumentNullException.ThrowIfNull(descriptor); using var output = new MemoryStream(); - using var writer = new BinaryWriter(output, Utf8, leaveOpen: true); - writer.Write(Magic); + using var writer = new BinaryWriter(output, UTF8, leaveOpen: true); + writer.Write(MAGIC); WriteStage(writer, descriptor.vertexShader.Span); WriteStage(writer, descriptor.fragmentShader.Span); if (descriptor.bindings.Count > C_MAX_BINDINGS) + { throw new InvalidDataException("The graphics program contains too many bindings."); + } writer.Write(descriptor.bindings.Count); foreach (RenderShaderBindingDescriptor binding in descriptor.bindings) { @@ -77,13 +79,17 @@ public static GraphicsPipelineDescriptor Decode( RenderVertexLayout? vertexLayout = null ) { if (bytes.Length > 2L * C_MAX_STAGE_BYTES + 2L * C_MAX_BINDINGS * C_MAX_NAME_BYTES + 1024 * 1024) + { throw new InvalidDataException("The graphics program exceeds its input budget."); + } try { using var input = new MemoryStream(bytes.ToArray(), writable: false); - using var reader = new BinaryReader(input, Utf8, leaveOpen: true); - if (!ReadBytes(reader, Magic.Length).AsSpan().SequenceEqual(Magic)) + using var reader = new BinaryReader(input, UTF8, leaveOpen: true); + if (!ReadBytes(reader, MAGIC.Length).AsSpan().SequenceEqual(MAGIC)) + { throw new InvalidDataException("The graphics program magic is invalid."); + } byte[] vertex = ReadBytes(reader, ReadCount(reader, C_MAX_STAGE_BYTES)); byte[] fragment = ReadBytes(reader, ReadCount(reader, C_MAX_STAGE_BYTES)); int count = ReadCount(reader, C_MAX_BINDINGS); @@ -91,20 +97,26 @@ public static GraphicsPipelineDescriptor Decode( for (int index = 0; index < count; index++) { bindings[index] = new RenderShaderBindingDescriptor( - new RenderBindingId(ReadName(reader)), + new RenderBindingID(ReadName(reader)), ReadEnum(reader), reader.ReadInt32(), ReadEnum(reader), reader.ReadInt32(), ReadEnum(reader), - ReadName(reader)); + ReadName(reader) + ); } RenderRasterState raster = ReadRaster(reader); if (input.Position != input.Length) + { throw new InvalidDataException("The graphics program contains trailing data."); + } return new GraphicsPipelineDescriptor(vertex, fragment, bindings, vertexLayout, raster); } - catch (InvalidDataException) { throw; } + catch (InvalidDataException) + { + throw; + } catch (Exception failure) when (failure is IOException or ArgumentException or OverflowException) { throw new InvalidDataException("The graphics program is malformed.", failure); @@ -116,7 +128,9 @@ private static void WriteStage( ReadOnlySpan bytes ) { if (bytes.IsEmpty || bytes.Length > C_MAX_STAGE_BYTES) + { throw new InvalidDataException("A graphics program stage has an invalid length."); + } writer.Write(bytes.Length); writer.Write(bytes); } @@ -125,15 +139,17 @@ private static void WriteName( BinaryWriter writer, string value ) { - byte[] bytes = Utf8.GetBytes(value); + byte[] bytes = UTF8.GetBytes(value); if (bytes.Length == 0 || bytes.Length > C_MAX_NAME_BYTES) + { throw new InvalidDataException("A graphics program binding name has an invalid length."); + } writer.Write(bytes.Length); writer.Write(bytes); } private static string ReadName(BinaryReader reader) - => Utf8.GetString(ReadBytes(reader, ReadCount(reader, C_MAX_NAME_BYTES))); + => UTF8.GetString(ReadBytes(reader, ReadCount(reader, C_MAX_NAME_BYTES))); private static int ReadCount( BinaryReader reader, @@ -141,7 +157,9 @@ int maximum ) { int count = reader.ReadInt32(); if (count < 0 || count > maximum) + { throw new InvalidDataException("A graphics program field exceeds its length budget."); + } return count; } @@ -150,14 +168,19 @@ private static byte[] ReadBytes( int count ) { if (count > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException("The graphics program is truncated."); + } byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new InvalidDataException("The graphics program is truncated."); + } return bytes; } - private static T ReadEnum(BinaryReader reader) where T : struct, Enum + private static T ReadEnum(BinaryReader reader) + where T : struct, Enum { T value = (T)Enum.ToObject(typeof(T), reader.ReadInt32()); return Enum.IsDefined(value) ? value : throw new InvalidDataException("A graphics program enum is invalid."); @@ -165,11 +188,11 @@ private static T ReadEnum(BinaryReader reader) where T : struct, Enum private static bool ReadBoolean(BinaryReader reader) => reader.ReadByte() switch - { - 0 => false, - 1 => true, - _ => throw new InvalidDataException("A graphics program boolean is invalid.") - }; + { + 0 => false, + 1 => true, + _ => throw new InvalidDataException("A graphics program boolean is invalid.") + }; private static void WriteRaster( BinaryWriter writer, @@ -180,8 +203,10 @@ RenderRasterState state || (state.colorWriteMask & ~0xF) != 0 || !Enum.IsDefined(state.blend.colorSource) || !Enum.IsDefined(state.blend.colorDestination) || !Enum.IsDefined(state.blend.colorEquation) || !Enum.IsDefined(state.blend.alphaSource) - || !Enum.IsDefined(state.blend.alphaDestination) || !Enum.IsDefined(state.blend.alphaEquation)) + || !Enum.IsDefined(state.blend.alphaDestination) || !Enum.IsDefined(state.blend.alphaEquation) + ) { throw new InvalidDataException("The graphics program raster state is invalid."); + } writer.Write((int)state.topology); writer.Write((int)state.cull); writer.Write((int)state.frontFace); @@ -209,7 +234,9 @@ private static RenderRasterState ReadRaster(BinaryReader reader) bool depthWrite = ReadBoolean(reader); byte mask = reader.ReadByte(); if ((mask & ~0xF) != 0) + { throw new InvalidDataException("A graphics program color mask is invalid."); + } bool multisampling = ReadBoolean(reader); var blend = new RenderBlendState { diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs index 568aa36ce..8e4a01c68 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs @@ -25,6 +25,4 @@ public ShaderInterface(IReadOnlyList bindings) /// Gets stable expected bindings. /// public IReadOnlyList bindings { get; } - } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs index 9cd80f1af..1dd8ab15a 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs @@ -37,7 +37,7 @@ public sealed class ShaderInterfaceBinding /// Explicit resource slot, or null when the caller assigns an ordered layout. /// public ShaderInterfaceBinding( - ShaderPropertyId id, + ShaderPropertyID id, ShaderPropertyType type, ShaderStage stages, int arrayCount = 1, @@ -48,9 +48,13 @@ public ShaderInterfaceBinding( ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayCount); if (!Enum.IsDefined(bindingKind)) + { throw new ArgumentOutOfRangeException(nameof(bindingKind)); + } if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } this.id = id; this.type = type; this.stages = stages; @@ -60,14 +64,16 @@ public ShaderInterfaceBinding( this.nativeName = nativeName ?? id.value; ArgumentException.ThrowIfNullOrWhiteSpace(this.nativeName); if (location < 0) + { throw new ArgumentOutOfRangeException(nameof(location)); + } this.location = location; } /// /// Gets the stable property ID. /// - public ShaderPropertyId id { get; } + public ShaderPropertyID id { get; } /// /// Gets the expected value or resource type. @@ -98,9 +104,9 @@ public ShaderInterfaceBinding( /// Gets the exact reflected symbol emitted by the adapter, distinct from the logical property ID. /// public string nativeName { get; } + /// /// Gets an explicitly compiled resource slot, or null for a caller-assigned layout. /// public int? location { get; } } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs index 8a6d26a96..db256211f 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -22,4 +22,3 @@ public enum ShaderProgramKind /// Compute } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs index f5de8cdbd..2c80276eb 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -30,4 +30,3 @@ public enum ShaderPropertyBindingKind /// StorageBuffer } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyID.cs similarity index 88% rename from src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs rename to src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyID.cs index 29a9bce4f..19ff7529a 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyID.cs @@ -1,17 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; /// /// Identifies a material property using a stable serialized string. /// -public record struct ShaderPropertyId +public record struct ShaderPropertyID { /// /// Creates a stable shader property identifier. @@ -19,7 +19,7 @@ public record struct ShaderPropertyId /// /// Stable manifest property identifier. /// - public ShaderPropertyId(string value) + public ShaderPropertyID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); this.value = value; @@ -41,6 +41,5 @@ public ShaderPropertyId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs index 8d8c3a10e..805c0d343 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -58,4 +58,3 @@ public enum ShaderPropertyType /// Buffer } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs index 42c27626d..ad3f6de0f 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -31,4 +31,3 @@ public enum ShaderStage /// Compute = 1 << 2 } - diff --git a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs index 80ad08c28..44cddbf07 100644 --- a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs +++ b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs @@ -2,21 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies whether a request renders to the main swapchain or an offscreen target. -/// -public enum RenderTargetKind -{ - /// - /// Main application window swapchain. - /// - Backbuffer, - /// - /// Persistent offscreen render texture. - /// - Texture -} - /// /// Selects one render destination without exposing a swapchain or framebuffer handle. /// @@ -61,3 +46,17 @@ public static RenderTarget FromTexture(RenderTexture texture) } } +/// +/// Identifies whether a request renders to the main swapchain or an offscreen target. +/// +public enum RenderTargetKind +{ + /// + /// Main application window swapchain. + /// + Backbuffer, + /// + /// Persistent offscreen render texture. + /// + Texture +} diff --git a/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs b/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs index 34cc9fade..6de52bd2b 100644 --- a/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs +++ b/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs @@ -61,4 +61,3 @@ public void Resize(RenderTextureDescriptor descriptor) contentRevision++; } } - diff --git a/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs b/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs index 9ba72b94d..ef6118227 100644 --- a/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs +++ b/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs @@ -59,4 +59,3 @@ int height /// public int height { get; } } - diff --git a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs index 5a929d783..5eadce595 100644 --- a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs +++ b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs @@ -1,11 +1,10 @@ -using Inno.Runtime.Contracts; using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - +using Inno.Core.Execution; using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Storage.Runtime; @@ -35,26 +34,32 @@ public StorageRuntime( int maxPendingOperations = 128, int maxWriteBytes = 64 * 1024 * 1024 ) { - m_storage = storage ?? throw new ArgumentNullException(nameof(storage)); + ArgumentNullException.ThrowIfNull(storage); + m_storage = storage; ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxWriteBytes); m_maxWriteBytes = maxWriteBytes; m_operations = lifetime.Own(new LifetimeScope(maxPendingOperations)); if (storage is IDisposable disposable) + { m_operations.Own(disposable); + } } /// /// Gets the storage service owned by this runtime feature. /// public IApplicationStorage storage => this; + /// /// Gets asynchronous operations retained until completion or retirement reporting. /// public int pendingOperations => m_operations.trackedWorkCount; + /// /// Gets operations rejected by finite asynchronous admission capacity. /// public long rejectedOperations => m_operations.rejectedWorkCount; + /// /// Determines whether a value exists. /// @@ -70,8 +75,8 @@ public StorageRuntime( public ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ExistsAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ExistsAsync(key, token), cancellationToken)); + /// /// Reads a complete immutable value. /// @@ -87,8 +92,8 @@ public ValueTask ExistsAsync( public ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ReadAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ReadAsync(key, token), cancellationToken)); + /// /// Atomically replaces a complete value. /// @@ -108,15 +113,19 @@ public ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(async token => + ) => new( + m_operations.RunAsync(async token => { if (value.Length > m_maxWriteBytes) + { throw new ArgumentException("The storage value exceeds its write byte budget.", nameof(value)); + } byte[] snapshot = value.ToArray(); await m_storage.WriteAsync(key, snapshot, token).ConfigureAwait(false); return true; - }, cancellationToken)); + }, cancellationToken) + ); + /// /// Deletes one value without failing when it is already absent. /// @@ -132,8 +141,8 @@ public ValueTask WriteAsync( public ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.DeleteAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.DeleteAsync(key, token), cancellationToken)); + /// /// Lists immutable keys below an optional logical prefix. /// @@ -149,8 +158,7 @@ public ValueTask DeleteAsync( public ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ListAsync(prefix, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ListAsync(prefix, token), cancellationToken)); /// /// Begins a frame-scoped operation and makes queued work visible. @@ -158,15 +166,10 @@ public ValueTask> ListAsync( /// /// The frame consumed by begin frame; ownership remains with the caller unless explicitly stated otherwise. /// - protected override void OnBeginFrame(RuntimeFrame frame) - { - OwnFrameScope(StorageExecutionContext.EnterScope(this)); - } + protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(StorageExecutionContext.EnterScope(this)); + /// /// Releases the storage backend after owned work has quiesced. /// - protected override void OnStop() - { - m_operations.Dispose(); - } + protected override void OnStop() => m_operations.Dispose(); } diff --git a/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs b/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs index e0d468303..aa52d69e8 100644 --- a/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs +++ b/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Storage.Runtime; @@ -20,15 +19,17 @@ public sealed class StorageRuntimeFactory : IRuntimeSubsystemFactory /// public StorageRuntimeFactory(Func storageFactory) { - m_storageFactory = storageFactory ?? throw new ArgumentNullException(nameof(storageFactory)); + ArgumentNullException.ThrowIfNull(storageFactory); + m_storageFactory = storageFactory; } /// /// Gets stable ordering metadata for the frame-scoped storage service. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.storage"), - order: -900); + new RuntimeSubsystemID("inno.runtime.storage"), + order: -900 + ); /// /// Creates a storage feature over a newly allocated application sandbox. @@ -43,7 +44,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); IApplicationStorage storage = m_storageFactory(context) - ?? throw new InvalidOperationException("The application storage factory returned null."); + ?? throw new InvalidOperationException("The application storage factory returned null."); return new StorageRuntime(storage); } } diff --git a/src/services/storage/Inno.Storage/Storage.cs b/src/services/storage/Inno.Storage/Storage.cs index 76aac3262..af231e0a1 100644 --- a/src/services/storage/Inno.Storage/Storage.cs +++ b/src/services/storage/Inno.Storage/Storage.cs @@ -1,4 +1,3 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Threading; @@ -6,38 +5,6 @@ namespace Inno.Storage; -/// -/// Binds application storage to the current asynchronous execution context. -/// -public static class StorageExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("storage"); - - /// - /// Gets the storage service bound to the current execution context. - /// - /// - /// Thrown when no storage scope is active. - /// - public static IApplicationStorage current => S_CURRENT_SCOPE.current; - - /// - /// Binds a storage service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned application storage service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IApplicationStorage storage) - { - ArgumentNullException.ThrowIfNull(storage); - return S_CURRENT_SCOPE.Enter(storage); - } - -} - /// /// Provides script-friendly access to the current application storage sandbox. /// @@ -58,8 +25,7 @@ public static class Storage public static ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ExistsAsync(key, cancellationToken); + ) => StorageExecutionContext.current.ExistsAsync(key, cancellationToken); /// /// Reads a complete value. @@ -76,8 +42,7 @@ public static ValueTask ExistsAsync( public static ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ReadAsync(key, cancellationToken); + ) => StorageExecutionContext.current.ReadAsync(key, cancellationToken); /// /// Atomically replaces a complete value. @@ -98,8 +63,7 @@ public static ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.WriteAsync(key, value, cancellationToken); + ) => StorageExecutionContext.current.WriteAsync(key, value, cancellationToken); /// /// Deletes one value. @@ -116,8 +80,7 @@ public static ValueTask WriteAsync( public static ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.DeleteAsync(key, cancellationToken); + ) => StorageExecutionContext.current.DeleteAsync(key, cancellationToken); /// /// Lists keys below an optional prefix. @@ -134,6 +97,5 @@ public static ValueTask DeleteAsync( public static ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ListAsync(prefix, cancellationToken); + ) => StorageExecutionContext.current.ListAsync(prefix, cancellationToken); } diff --git a/src/services/storage/Inno.Storage/StorageExecutionContext.cs b/src/services/storage/Inno.Storage/StorageExecutionContext.cs new file mode 100644 index 000000000..e68c584b6 --- /dev/null +++ b/src/services/storage/Inno.Storage/StorageExecutionContext.cs @@ -0,0 +1,35 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Storage; + +/// +/// Binds application storage to the current asynchronous execution context. +/// +public static class StorageExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("storage"); + + /// + /// Gets the storage service bound to the current execution context. + /// + /// + /// Thrown when no storage scope is active. + /// + public static IApplicationStorage current => CURRENT_SCOPE.current; + + /// + /// Binds a storage service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned application storage service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IApplicationStorage storage) + { + ArgumentNullException.ThrowIfNull(storage); + return CURRENT_SCOPE.Enter(storage); + } +} diff --git a/src/services/storage/Inno.Storage/StorageKey.cs b/src/services/storage/Inno.Storage/StorageKey.cs index 9f2844a00..68b9f079b 100644 --- a/src/services/storage/Inno.Storage/StorageKey.cs +++ b/src/services/storage/Inno.Storage/StorageKey.cs @@ -21,13 +21,14 @@ public StorageKey(string value) ArgumentException.ThrowIfNullOrWhiteSpace(value); string normalized = value.Replace('\\', '/').Trim('/'); string[] segments = normalized.Split('/'); - if (normalized.Length == 0 || - value.StartsWith('/') || - value.StartsWith('\\') || - segments.Length == 0 || - Array.Exists(segments, static segment => - string.IsNullOrWhiteSpace(segment) || segment is "." or ".." || segment.Contains(':'))) - { + if (normalized.Length == 0 + || value.StartsWith('/') + || value.StartsWith('\\') + || segments.Length == 0 + || Array.Exists(segments, static segment => ( + string.IsNullOrWhiteSpace(segment) || segment is "." or ".." || segment.Contains(':') + )) + ) { throw new ArgumentException("A storage key must be a non-rooted unambiguous sandbox path.", nameof(value)); } this.value = normalized; diff --git a/src/services/storage/Inno.Storage/StorageScope.cs b/src/services/storage/Inno.Storage/StorageScope.cs index a235db24f..76c24313f 100644 --- a/src/services/storage/Inno.Storage/StorageScope.cs +++ b/src/services/storage/Inno.Storage/StorageScope.cs @@ -21,24 +21,30 @@ public StorageScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); if (value[0] == '.' || value[^1] == '.') + { throw new ArgumentException("A storage namespace cannot begin or end with a dot.", nameof(value)); + } foreach (char character in value) { if (!char.IsAsciiLetterOrDigit(character) && character is not '.' and not '_' and not '-') + { throw new ArgumentException("A storage namespace requires portable identifier characters.", nameof(value)); + } } ReadOnlySpan name = value.AsSpan(); int extension = name.IndexOf('.'); if (extension >= 0) + { name = name[..extension]; + } if (name.Equals("CON", StringComparison.OrdinalIgnoreCase) || name.Equals("PRN", StringComparison.OrdinalIgnoreCase) || name.Equals("AUX", StringComparison.OrdinalIgnoreCase) || name.Equals("NUL", StringComparison.OrdinalIgnoreCase) || (name.Length == 4 && name[3] is >= '1' and <= '9' && (name[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) - || name[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase)))) - { + || name[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))) + ) { throw new ArgumentException("A storage namespace cannot use a reserved portable device name.", nameof(value)); } this.value = value; @@ -54,6 +60,6 @@ public StorageScope(string value) /// public bool isValid => value is not null; - /// + /// public override string ToString() => value ?? string.Empty; } diff --git a/src/services/text/Inno.Text.Assets/FontImporter.cs b/src/services/text/Inno.Text.Assets/FontImporter.cs index afa272f65..13d04e7ef 100644 --- a/src/services/text/Inno.Text.Assets/FontImporter.cs +++ b/src/services/text/Inno.Text.Assets/FontImporter.cs @@ -4,7 +4,6 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; namespace Inno.Text.Assets; @@ -45,24 +44,29 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", FontMetadataCodec.Encode(metadata), - cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("font-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken + ).ConfigureAwait(false); + await output.WriteArtifactAsync("font-data", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } private static FontMetadata ReadMetadata(ReadOnlySpan source) { if (source.Length < 12) + { throw new InvalidDataException("The font source is truncated."); + } uint signature = BinaryPrimitives.ReadUInt32BigEndian(source); int faceCount; - if (signature == 0x74746366) + if (signature == 0x7474_6366) { uint count = BinaryPrimitives.ReadUInt32BigEndian(source[8..]); - if (count is 0 or > 65535 || source.Length < checked(12 + ((int)count * 4))) + if (count is 0 or > 65_535 || source.Length < checked(12 + ((int)count * 4))) + { throw new InvalidDataException("The OpenType collection header is invalid."); + } faceCount = (int)count; } - else if (signature is 0x00010000 or 0x4f54544f or 0x74727565 or 0x74797031) + else if (signature is 0x0001_0000 or 0x4F54_544F or 0x7472_7565 or 0x7479_7031) { faceCount = 1; } diff --git a/src/services/text/Inno.Text.Runtime/TextRuntime.cs b/src/services/text/Inno.Text.Runtime/TextRuntime.cs index ea6d75330..a6cc5d253 100644 --- a/src/services/text/Inno.Text.Runtime/TextRuntime.cs +++ b/src/services/text/Inno.Text.Runtime/TextRuntime.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Assets; using Inno.Runtime; using Inno.Runtime.Contracts; @@ -31,18 +30,12 @@ public TextRuntime( ITextBackend backend, IAssetArtifactLookup artifacts ) { - m_backend = backend ?? throw new ArgumentNullException(nameof(backend)); - m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); + ArgumentNullException.ThrowIfNull(backend); + ArgumentNullException.ThrowIfNull(artifacts); + m_backend = backend; + m_artifacts = artifacts; } - /// - /// Binds the script-facing text facade for the complete runtime frame. - /// - /// - /// The current runtime frame. - /// - protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(EnterExecutionScope()); - /// /// Binds this runtime to the current asynchronous execution context. /// @@ -95,7 +88,7 @@ TextShapingOptions options /// /// The zero-based collection face index. /// - /// + /// /// The font-specific glyph identifier. /// /// @@ -107,23 +100,35 @@ TextShapingOptions options public GlyphBitmap Rasterize( FontAsset font, int faceIndex, - uint glyphId, + uint glyphID, float fontSize ) { ArgumentNullException.ThrowIfNull(font); if (!float.IsFinite(fontSize) || fontSize <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSize)); + } ObjectDisposedException.ThrowIf(m_disposed, this); - return m_backend.Rasterize(GetOrLoad(font, faceIndex).handle, glyphId, fontSize); + return m_backend.Rasterize(GetOrLoad(font, faceIndex).handle, glyphID, fontSize); } + /// + /// Binds the script-facing text facade for the complete runtime frame. + /// + /// + /// The current runtime frame. + /// + protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(EnterExecutionScope()); + /// /// Releases every native face and retained immutable artifact before the backend. /// protected override void OnStop() { if (m_disposed) + { return; + } m_disposed = true; List failures = []; foreach (LoadedFont font in m_fonts.Values) @@ -155,7 +160,9 @@ protected override void OnStop() failures.Add(exception); } if (failures.Count > 0) + { throw new AggregateException("Text runtime retirement failed.", failures); + } } private LoadedFont GetOrLoad( @@ -163,22 +170,30 @@ private LoadedFont GetOrLoad( int faceIndex ) { FontMetadata metadata = font.metadata - ?? throw new InvalidOperationException("The font has no imported runtime metadata."); + ?? throw new InvalidOperationException("The font has no imported runtime metadata."); if (font.isMissing) + { throw new InvalidOperationException("The font asset is missing."); + } if ((uint)faceIndex >= (uint)metadata.faceCount) + { throw new ArgumentOutOfRangeException(nameof(faceIndex)); - var key = new FontKey(font.identity.persistentId, font.contentVersion, faceIndex); + } + var key = new FontKey(font.identity.persistentID, font.contentVersion, faceIndex); if (m_fonts.TryGetValue(key, out LoadedFont? loaded)) + { return loaded; + } - ArtifactLease artifact = m_artifacts.AcquireArtifact(font.identity.persistentId, "font-data"); + ArtifactLease artifact = m_artifacts.AcquireArtifact(font.identity.persistentID, "font-data"); try { byte[] bytes = artifact.ReadAllBytes(); TextFontHandle handle = m_backend.LoadFont(bytes, faceIndex); if (!handle.isValid) + { throw new InvalidOperationException("The text backend rejected the imported font face."); + } loaded = new LoadedFont(handle, artifact); m_fonts.Add(key, loaded); return loaded; @@ -191,7 +206,7 @@ int faceIndex } private readonly record struct FontKey( - Guid persistentId, + Guid persistentID, long version, int faceIndex ); diff --git a/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs b/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs index 29067c741..0f8c8ee4b 100644 --- a/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs +++ b/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; using Inno.Runtime.Contracts; @@ -20,15 +19,17 @@ public sealed class TextRuntimeFactory : IRuntimeSubsystemFactory /// public TextRuntimeFactory(Func runtimeFactory) { - m_runtimeFactory = runtimeFactory ?? throw new ArgumentNullException(nameof(runtimeFactory)); + ArgumentNullException.ThrowIfNull(runtimeFactory); + m_runtimeFactory = runtimeFactory; } /// /// Gets stable ordering metadata that makes text available before scene simulation. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.text"), - order: -800); + new RuntimeSubsystemID("inno.runtime.text"), + order: -800 + ); /// /// Creates one session-owned text runtime. @@ -43,6 +44,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); return m_runtimeFactory(context) - ?? throw new InvalidOperationException("The text runtime factory returned null."); + ?? throw new InvalidOperationException("The text runtime factory returned null."); } } diff --git a/src/services/text/Inno.Text/FontAsset.cs b/src/services/text/Inno.Text/FontAsset.cs index 1c8e12c88..c6c2d9875 100644 --- a/src/services/text/Inno.Text/FontAsset.cs +++ b/src/services/text/Inno.Text/FontAsset.cs @@ -1,102 +1,13 @@ using System; -using System.Buffers.Binary; - using Inno.Assets; using Inno.Extensibility.Types; namespace Inno.Text; -/// -/// Describes immutable metadata for an imported OpenType font source. -/// -public readonly record struct FontMetadata -{ - /// - /// Creates validated imported font metadata. - /// - /// - /// The number of faces in the source collection. - /// - /// - /// The encoded source length in bytes. - /// - public FontMetadata( - int faceCount, - long encodedByteLength - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(faceCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(encodedByteLength); - this.faceCount = faceCount; - this.encodedByteLength = encodedByteLength; - } - - /// - /// Gets the number of independently addressable faces in the source. - /// - public int faceCount { get; } - - /// - /// Gets the encoded source length in bytes. - /// - public long encodedByteLength { get; } -} - -/// -/// Encodes the compact runtime payload shared by the font importer and text runtime. -/// -public static class FontMetadataCodec -{ - private const uint C_MAGIC = 0x544E4649; - private const int C_SIZE = 16; - - /// - /// Encodes validated metadata into a deterministic runtime payload. - /// - /// - /// The metadata to encode. - /// - /// - /// The compact runtime payload. - /// - public static byte[] Encode(FontMetadata metadata) - { - byte[] output = new byte[C_SIZE]; - BinaryPrimitives.WriteUInt32LittleEndian(output, C_MAGIC); - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(4), metadata.faceCount); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(8), metadata.encodedByteLength); - return output; - } - - /// - /// Decodes and validates a compact font runtime payload. - /// - /// - /// The complete runtime payload. - /// - /// - /// The decoded metadata. - /// - public static FontMetadata Decode(ReadOnlySpan payload) - { - if (payload.Length != C_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) - throw new InvalidOperationException("The font runtime payload is invalid."); - try - { - return new FontMetadata( - BinaryPrimitives.ReadInt32LittleEndian(payload[4..]), - BinaryPrimitives.ReadInt64LittleEndian(payload[8..])); - } - catch (ArgumentOutOfRangeException exception) - { - throw new InvalidOperationException("The font runtime payload contains invalid metadata.", exception); - } - } -} - /// /// Represents one imported OpenType font file or collection. /// -[StableTypeId("c8c708e2-3fd1-4ee1-9f16-5a47680272af")] +[StableTypeID("c8c708e2-3fd1-4ee1-9f16-5a47680272af")] public sealed class FontAsset : AssetObject { private FontMetadata? m_metadata; @@ -118,7 +29,5 @@ public sealed class FontAsset : AssetObject protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_metadata = currentPayload.IsEmpty ? null : FontMetadataCodec.Decode(currentPayload.Span); - } + ) => m_metadata = currentPayload.IsEmpty ? null : FontMetadataCodec.Decode(currentPayload.Span); } diff --git a/src/services/text/Inno.Text/FontMetadata.cs b/src/services/text/Inno.Text/FontMetadata.cs new file mode 100644 index 000000000..a8937388f --- /dev/null +++ b/src/services/text/Inno.Text/FontMetadata.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Text; + +/// +/// Describes immutable metadata for an imported OpenType font source. +/// +public readonly record struct FontMetadata +{ + /// + /// Creates validated imported font metadata. + /// + /// + /// The number of faces in the source collection. + /// + /// + /// The encoded source length in bytes. + /// + public FontMetadata( + int faceCount, + long encodedByteLength + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(faceCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(encodedByteLength); + this.faceCount = faceCount; + this.encodedByteLength = encodedByteLength; + } + + /// + /// Gets the number of independently addressable faces in the source. + /// + public int faceCount { get; } + + /// + /// Gets the encoded source length in bytes. + /// + public long encodedByteLength { get; } +} diff --git a/src/services/text/Inno.Text/FontMetadataCodec.cs b/src/services/text/Inno.Text/FontMetadataCodec.cs new file mode 100644 index 000000000..d5c9c6519 --- /dev/null +++ b/src/services/text/Inno.Text/FontMetadataCodec.cs @@ -0,0 +1,59 @@ +using System; +using System.Buffers.Binary; + +namespace Inno.Text; + +/// +/// Encodes the compact runtime payload shared by the font importer and text runtime. +/// +public static class FontMetadataCodec +{ + private const uint C_MAGIC = 0x544E_4649; + private const int C_SIZE = 16; + + /// + /// Encodes validated metadata into a deterministic runtime payload. + /// + /// + /// The metadata to encode. + /// + /// + /// The compact runtime payload. + /// + public static byte[] Encode(FontMetadata metadata) + { + var output = new byte[C_SIZE]; + BinaryPrimitives.WriteUInt32LittleEndian(output, C_MAGIC); + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(4), metadata.faceCount); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(8), metadata.encodedByteLength); + return output; + } + + /// + /// Decodes and validates a compact font runtime payload. + /// + /// + /// The complete runtime payload. + /// + /// + /// The decoded metadata. + /// + public static FontMetadata Decode(ReadOnlySpan payload) + { + if (payload.Length != C_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { + throw new InvalidOperationException("The font runtime payload is invalid."); + } + try + { + return new FontMetadata( + BinaryPrimitives.ReadInt32LittleEndian(payload[4..]), + BinaryPrimitives.ReadInt64LittleEndian(payload[8..]) + ); + } + catch (ArgumentOutOfRangeException exception) + { + throw new InvalidOperationException("The font runtime payload contains invalid metadata.", exception); + } + } +} diff --git a/src/services/text/Inno.Text/GlyphBitmap.cs b/src/services/text/Inno.Text/GlyphBitmap.cs new file mode 100644 index 000000000..023edf7a4 --- /dev/null +++ b/src/services/text/Inno.Text/GlyphBitmap.cs @@ -0,0 +1,88 @@ +using System; + +namespace Inno.Text; + +/// +/// Contains one rasterized glyph as tightly packed 8-bit coverage. +/// +public sealed class GlyphBitmap +{ + private readonly byte[] m_pixels; + + /// + /// Creates a validated immutable glyph bitmap. + /// + /// + /// The bitmap width in pixels. + /// + /// + /// The bitmap height in pixels. + /// + /// + /// The horizontal bearing in pixels. + /// + /// + /// The vertical bearing in pixels. + /// + /// + /// The horizontal glyph advance. + /// + /// + /// Tightly packed row-major 8-bit coverage. + /// + public GlyphBitmap( + int width, + int height, + int bearingX, + int bearingY, + float advanceX, + ReadOnlySpan pixels + ) { + ArgumentOutOfRangeException.ThrowIfNegative(width); + ArgumentOutOfRangeException.ThrowIfNegative(height); + if (pixels.Length != checked(width * height)) + { + throw new ArgumentException("Glyph coverage length must match its dimensions.", nameof(pixels)); + } + if (!float.IsFinite(advanceX)) + { + throw new ArgumentOutOfRangeException(nameof(advanceX)); + } + this.width = width; + this.height = height; + this.bearingX = bearingX; + this.bearingY = bearingY; + this.advanceX = advanceX; + m_pixels = pixels.ToArray(); + } + + /// + /// Gets the bitmap width in pixels. + /// + public int width { get; } + + /// + /// Gets the bitmap height in pixels. + /// + public int height { get; } + + /// + /// Gets the horizontal bearing in pixels. + /// + public int bearingX { get; } + + /// + /// Gets the vertical bearing in pixels. + /// + public int bearingY { get; } + + /// + /// Gets the horizontal glyph advance. + /// + public float advanceX { get; } + + /// + /// Gets tightly packed row-major 8-bit coverage. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/text/Inno.Text/ITextBackend.cs b/src/services/text/Inno.Text/ITextBackend.cs index 841f91853..598477580 100644 --- a/src/services/text/Inno.Text/ITextBackend.cs +++ b/src/services/text/Inno.Text/ITextBackend.cs @@ -63,7 +63,7 @@ TextShapingOptions options /// /// The loaded face. /// - /// + /// /// The font-specific glyph identifier. /// /// @@ -74,7 +74,7 @@ TextShapingOptions options /// GlyphBitmap Rasterize( TextFontHandle font, - uint glyphId, + uint glyphID, float fontSize ); } diff --git a/src/services/text/Inno.Text/ITextService.cs b/src/services/text/Inno.Text/ITextService.cs index 40436e3a6..8431226fb 100644 --- a/src/services/text/Inno.Text/ITextService.cs +++ b/src/services/text/Inno.Text/ITextService.cs @@ -39,7 +39,7 @@ TextShapingOptions options /// /// The zero-based collection face index. /// - /// + /// /// The font-specific glyph identifier. /// /// @@ -51,7 +51,7 @@ TextShapingOptions options GlyphBitmap Rasterize( FontAsset font, int faceIndex, - uint glyphId, + uint glyphID, float fontSize ); } diff --git a/src/services/text/Inno.Text/Text.cs b/src/services/text/Inno.Text/Text.cs index 3d002d9ec..9ab9de203 100644 --- a/src/services/text/Inno.Text/Text.cs +++ b/src/services/text/Inno.Text/Text.cs @@ -1,37 +1,5 @@ -using System; - -using Inno.Core.Execution; - namespace Inno.Text; -/// -/// Binds one text service to the current asynchronous execution context. -/// -public static class TextExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("text"); - - /// - /// Gets the text service bound to the current execution context. - /// - public static ITextService current => S_CURRENT_SCOPE.current; - - /// - /// Binds a text service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned text service. - /// - /// - /// The caller-owned binding scope. - /// - public static IDisposable EnterScope(ITextService text) - { - ArgumentNullException.ThrowIfNull(text); - return S_CURRENT_SCOPE.Enter(text); - } -} - /// /// Provides script-friendly access to Unicode shaping and glyph rasterization. /// @@ -56,8 +24,7 @@ public static TextLayout Shape( FontAsset font, string text, TextStyle style - ) - => TextExecutionContext.current.Shape(font, text, style, TextShapingOptions.automatic); + ) => TextExecutionContext.current.Shape(font, text, style, TextShapingOptions.automatic); /// /// Shapes text with explicit language, script, and direction hints. @@ -82,8 +49,7 @@ public static TextLayout Shape( string text, TextStyle style, TextShapingOptions options - ) - => TextExecutionContext.current.Shape(font, text, style, options); + ) => TextExecutionContext.current.Shape(font, text, style, options); /// /// Rasterizes one shaped glyph into immutable 8-bit coverage. @@ -94,7 +60,7 @@ TextShapingOptions options /// /// The zero-based collection face index. /// - /// + /// /// The font-specific glyph identifier. /// /// @@ -106,8 +72,7 @@ TextShapingOptions options public static GlyphBitmap Rasterize( FontAsset font, int faceIndex, - uint glyphId, + uint glyphID, float fontSize - ) - => TextExecutionContext.current.Rasterize(font, faceIndex, glyphId, fontSize); + ) => TextExecutionContext.current.Rasterize(font, faceIndex, glyphID, fontSize); } diff --git a/src/services/text/Inno.Text/TextDirection.cs b/src/services/text/Inno.Text/TextDirection.cs new file mode 100644 index 000000000..01556f3f9 --- /dev/null +++ b/src/services/text/Inno.Text/TextDirection.cs @@ -0,0 +1,28 @@ +namespace Inno.Text; + +/// +/// Selects the logical direction used by the shaping engine. +/// +public enum TextDirection +{ + /// + /// Lets the shaping engine infer direction from the text. + /// + Automatic, + /// + /// Shapes text from left to right. + /// + LeftToRight, + /// + /// Shapes text from right to left. + /// + RightToLeft, + /// + /// Shapes text from top to bottom. + /// + TopToBottom, + /// + /// Shapes text from bottom to top. + /// + BottomToTop +} diff --git a/src/services/text/Inno.Text/TextExecutionContext.cs b/src/services/text/Inno.Text/TextExecutionContext.cs new file mode 100644 index 000000000..0135c3de7 --- /dev/null +++ b/src/services/text/Inno.Text/TextExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Text; + +/// +/// Binds one text service to the current asynchronous execution context. +/// +public static class TextExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("text"); + + /// + /// Gets the text service bound to the current execution context. + /// + public static ITextService current => CURRENT_SCOPE.current; + + /// + /// Binds a text service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned text service. + /// + /// + /// The caller-owned binding scope. + /// + public static IDisposable EnterScope(ITextService text) + { + ArgumentNullException.ThrowIfNull(text); + return CURRENT_SCOPE.Enter(text); + } +} diff --git a/src/services/text/Inno.Text/TextFontHandle.cs b/src/services/text/Inno.Text/TextFontHandle.cs new file mode 100644 index 000000000..6c7a57382 --- /dev/null +++ b/src/services/text/Inno.Text/TextFontHandle.cs @@ -0,0 +1,15 @@ +namespace Inno.Text; + +/// +/// Identifies one font face loaded into a text backend generation. +/// +/// +/// The concrete value read or transformed by this operation. +/// +public readonly record struct TextFontHandle(ulong value) +{ + /// + /// Gets whether this handle identifies a loaded face. + /// + public bool isValid => value != 0; +} diff --git a/src/services/text/Inno.Text/TextFontStyle.cs b/src/services/text/Inno.Text/TextFontStyle.cs new file mode 100644 index 000000000..6ce404519 --- /dev/null +++ b/src/services/text/Inno.Text/TextFontStyle.cs @@ -0,0 +1,20 @@ +namespace Inno.Text; + +/// +/// Selects the typographic slant requested from a font face. +/// +public enum TextFontStyle +{ + /// + /// Uses an upright face. + /// + Normal, + /// + /// Uses an italic face. + /// + Italic, + /// + /// Uses an oblique face. + /// + Oblique +} diff --git a/src/services/text/Inno.Text/TextGlyph.cs b/src/services/text/Inno.Text/TextGlyph.cs new file mode 100644 index 000000000..8e45d7c7c --- /dev/null +++ b/src/services/text/Inno.Text/TextGlyph.cs @@ -0,0 +1,32 @@ +namespace Inno.Text; + +/// +/// Describes one positioned glyph emitted by Unicode shaping. +/// +/// +/// The glyph identifier in the font face that produced this layout. +/// +/// +/// The source cluster index reported by the backend. The FreeType/HarfBuzz backend +/// reports a UTF-8 byte offset, not a UTF-16 character index. +/// +/// +/// The horizontal pen advance in logical pixels, including backend-applied letter spacing. +/// +/// +/// The vertical pen advance in logical pixels, including backend-applied letter spacing. +/// +/// +/// The horizontal placement offset from the pen position in logical pixels. +/// +/// +/// The vertical placement offset from the pen position in logical pixels. +/// +public readonly record struct TextGlyph( + uint glyphID, + uint cluster, + float advanceX, + float advanceY, + float offsetX, + float offsetY +); diff --git a/src/services/text/Inno.Text/TextLayout.cs b/src/services/text/Inno.Text/TextLayout.cs new file mode 100644 index 000000000..329925cbf --- /dev/null +++ b/src/services/text/Inno.Text/TextLayout.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Text; + +/// +/// Contains immutable positioned glyphs and aggregate bounds for one shaped string. +/// +public sealed class TextLayout +{ + private readonly TextGlyph[] m_glyphs; + + /// + /// Creates an immutable text layout. + /// + /// + /// The positioned glyph sequence. + /// + /// + /// The face metrics used by the layout. + /// + /// + /// The logical horizontal advance. + /// + /// + /// The logical line height. + /// + public TextLayout( + IEnumerable glyphs, + TextMetrics metrics, + float width, + float height + ) { + ArgumentNullException.ThrowIfNull(glyphs); + if (!float.IsFinite(width) || width < 0f) + { + throw new ArgumentOutOfRangeException(nameof(width)); + } + if (!float.IsFinite(height) || height < 0f) + { + throw new ArgumentOutOfRangeException(nameof(height)); + } + m_glyphs = [..glyphs]; + this.metrics = metrics; + this.width = width; + this.height = height; + } + + /// + /// Gets the immutable positioned glyph sequence. + /// + public IReadOnlyList glyphs => m_glyphs; + + /// + /// Gets the font metrics used to build this layout. + /// + public TextMetrics metrics { get; } + + /// + /// Gets the aggregate horizontal advance. + /// + public float width { get; } + + /// + /// Gets the aggregate line height. + /// + public float height { get; } +} diff --git a/src/services/text/Inno.Text/TextMetrics.cs b/src/services/text/Inno.Text/TextMetrics.cs new file mode 100644 index 000000000..d59ac4d63 --- /dev/null +++ b/src/services/text/Inno.Text/TextMetrics.cs @@ -0,0 +1,27 @@ +namespace Inno.Text; + +/// +/// Describes scalable metrics for one font face and logical size. +/// +/// +/// The scaled face ascender in logical pixels, using the backend's coordinate convention. +/// +/// +/// The scaled face descender in logical pixels, using the backend's coordinate convention. +/// +/// +/// The recommended line spacing in logical pixels for the selected face and size. +/// +/// +/// The scaled underline position relative to the baseline in logical pixels. +/// +/// +/// The scaled underline thickness in logical pixels. +/// +public readonly record struct TextMetrics( + float ascender, + float descender, + float lineHeight, + float underlinePosition, + float underlineThickness +); diff --git a/src/services/text/Inno.Text/TextShapingOptions.cs b/src/services/text/Inno.Text/TextShapingOptions.cs new file mode 100644 index 000000000..3e37b5c2b --- /dev/null +++ b/src/services/text/Inno.Text/TextShapingOptions.cs @@ -0,0 +1,55 @@ +using System; + +namespace Inno.Text; + +/// +/// Defines language and script hints for one shaping operation. +/// +public readonly record struct TextShapingOptions +{ + /// + /// Creates shaping hints. + /// + /// + /// The logical text direction. + /// + /// + /// An optional BCP 47 language code. + /// + /// + /// An optional ISO 15924 script code. + /// + public TextShapingOptions( + TextDirection direction = TextDirection.Automatic, + string? language = null, + string? script = null + ) { + if (!Enum.IsDefined(direction)) + { + throw new ArgumentOutOfRangeException(nameof(direction)); + } + this.direction = direction; + this.language = string.IsNullOrWhiteSpace(language) ? null : language.Trim(); + this.script = string.IsNullOrWhiteSpace(script) ? null : script.Trim(); + } + + /// + /// Gets automatic shaping hints. + /// + public static TextShapingOptions automatic { get; } = new(); + + /// + /// Gets the requested logical direction. + /// + public TextDirection direction { get; } + + /// + /// Gets the optional BCP 47 language code. + /// + public string? language { get; } + + /// + /// Gets the optional ISO 15924 script code. + /// + public string? script { get; } +} diff --git a/src/services/text/Inno.Text/TextStyle.cs b/src/services/text/Inno.Text/TextStyle.cs new file mode 100644 index 000000000..74a4d14a6 --- /dev/null +++ b/src/services/text/Inno.Text/TextStyle.cs @@ -0,0 +1,88 @@ +using System; + +namespace Inno.Text; + +/// +/// Defines immutable font selection and sizing for one shaping operation. +/// +public readonly record struct TextStyle +{ + /// + /// Creates validated text styling. + /// + /// + /// The positive font size in logical pixels. + /// + /// + /// The zero-based face index within the font collection. + /// + /// + /// The requested CSS-compatible weight from 1 through 1000. + /// + /// + /// The requested face slant. + /// + /// + /// Additional logical pixels inserted after each glyph. + /// + public TextStyle( + float fontSize, + int faceIndex = 0, + int weight = 400, + TextFontStyle style = TextFontStyle.Normal, + float letterSpacing = 0f + ) { + if (!float.IsFinite(fontSize) || fontSize <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(fontSize)); + } + ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); + if (weight is < 1 or > 1000) + { + throw new ArgumentOutOfRangeException(nameof(weight)); + } + if (!Enum.IsDefined(style)) + { + throw new ArgumentOutOfRangeException(nameof(style)); + } + if (!float.IsFinite(letterSpacing)) + { + throw new ArgumentOutOfRangeException(nameof(letterSpacing)); + } + this.fontSize = fontSize; + this.faceIndex = faceIndex; + this.weight = weight; + this.style = style; + this.letterSpacing = letterSpacing; + } + + /// + /// Gets a 16-pixel regular default style. + /// + public static TextStyle defaultValue { get; } = new(16f); + + /// + /// Gets the logical font size. + /// + public float fontSize { get; } + + /// + /// Gets the collection face index. + /// + public int faceIndex { get; } + + /// + /// Gets the CSS-compatible font weight. + /// + public int weight { get; } + + /// + /// Gets the requested face slant. + /// + public TextFontStyle style { get; } + + /// + /// Gets additional spacing appended to each glyph advance. + /// + public float letterSpacing { get; } +} diff --git a/src/services/text/Inno.Text/TextTypes.cs b/src/services/text/Inno.Text/TextTypes.cs deleted file mode 100644 index 3b0ab61f1..000000000 --- a/src/services/text/Inno.Text/TextTypes.cs +++ /dev/null @@ -1,373 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Inno.Text; - -/// -/// Selects the logical direction used by the shaping engine. -/// -public enum TextDirection -{ - /// - /// Lets the shaping engine infer direction from the text. - /// - Automatic, - /// - /// Shapes text from left to right. - /// - LeftToRight, - /// - /// Shapes text from right to left. - /// - RightToLeft, - /// - /// Shapes text from top to bottom. - /// - TopToBottom, - /// - /// Shapes text from bottom to top. - /// - BottomToTop -} - -/// -/// Selects the typographic slant requested from a font face. -/// -public enum TextFontStyle -{ - /// - /// Uses an upright face. - /// - Normal, - /// - /// Uses an italic face. - /// - Italic, - /// - /// Uses an oblique face. - /// - Oblique -} - -/// -/// Identifies one font face loaded into a text backend generation. -/// -/// -/// The concrete value read or transformed by this operation. -/// -public readonly record struct TextFontHandle(ulong value) -{ - /// - /// Gets whether this handle identifies a loaded face. - /// - public bool isValid => value != 0; -} - -/// -/// Defines immutable font selection and sizing for one shaping operation. -/// -public readonly record struct TextStyle -{ - /// - /// Creates validated text styling. - /// - /// - /// The positive font size in logical pixels. - /// - /// - /// The zero-based face index within the font collection. - /// - /// - /// The requested CSS-compatible weight from 1 through 1000. - /// - /// - /// The requested face slant. - /// - /// - /// Additional logical pixels inserted after each glyph. - /// - public TextStyle( - float fontSize, - int faceIndex = 0, - int weight = 400, - TextFontStyle style = TextFontStyle.Normal, - float letterSpacing = 0f - ) { - if (!float.IsFinite(fontSize) || fontSize <= 0f) - throw new ArgumentOutOfRangeException(nameof(fontSize)); - ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); - if (weight is < 1 or > 1000) - throw new ArgumentOutOfRangeException(nameof(weight)); - if (!Enum.IsDefined(style)) - throw new ArgumentOutOfRangeException(nameof(style)); - if (!float.IsFinite(letterSpacing)) - throw new ArgumentOutOfRangeException(nameof(letterSpacing)); - this.fontSize = fontSize; - this.faceIndex = faceIndex; - this.weight = weight; - this.style = style; - this.letterSpacing = letterSpacing; - } - - /// - /// Gets a 16-pixel regular default style. - /// - public static TextStyle defaultValue { get; } = new(16f); - /// - /// Gets the logical font size. - /// - public float fontSize { get; } - /// - /// Gets the collection face index. - /// - public int faceIndex { get; } - /// - /// Gets the CSS-compatible font weight. - /// - public int weight { get; } - /// - /// Gets the requested face slant. - /// - public TextFontStyle style { get; } - /// - /// Gets additional spacing appended to each glyph advance. - /// - public float letterSpacing { get; } -} - -/// -/// Defines language and script hints for one shaping operation. -/// -public readonly record struct TextShapingOptions -{ - /// - /// Creates shaping hints. - /// - /// - /// The logical text direction. - /// - /// - /// An optional BCP 47 language code. - /// - /// - /// An optional ISO 15924 script code. - /// - public TextShapingOptions( - TextDirection direction = TextDirection.Automatic, - string? language = null, - string? script = null - ) { - if (!Enum.IsDefined(direction)) - throw new ArgumentOutOfRangeException(nameof(direction)); - this.direction = direction; - this.language = string.IsNullOrWhiteSpace(language) ? null : language.Trim(); - this.script = string.IsNullOrWhiteSpace(script) ? null : script.Trim(); - } - - /// - /// Gets automatic shaping hints. - /// - public static TextShapingOptions automatic { get; } = new(); - /// - /// Gets the requested logical direction. - /// - public TextDirection direction { get; } - /// - /// Gets the optional BCP 47 language code. - /// - public string? language { get; } - /// - /// Gets the optional ISO 15924 script code. - /// - public string? script { get; } -} - -/// -/// Describes one positioned glyph emitted by Unicode shaping. -/// -/// -/// The glyph identifier in the font face that produced this layout. -/// -/// -/// The source cluster index reported by the backend. The FreeType/HarfBuzz backend -/// reports a UTF-8 byte offset, not a UTF-16 character index. -/// -/// -/// The horizontal pen advance in logical pixels, including backend-applied letter spacing. -/// -/// -/// The vertical pen advance in logical pixels, including backend-applied letter spacing. -/// -/// -/// The horizontal placement offset from the pen position in logical pixels. -/// -/// -/// The vertical placement offset from the pen position in logical pixels. -/// -public readonly record struct TextGlyph( - uint glyphId, - uint cluster, - float advanceX, - float advanceY, - float offsetX, - float offsetY -); - -/// -/// Describes scalable metrics for one font face and logical size. -/// -/// -/// The scaled face ascender in logical pixels, using the backend's coordinate convention. -/// -/// -/// The scaled face descender in logical pixels, using the backend's coordinate convention. -/// -/// -/// The recommended line spacing in logical pixels for the selected face and size. -/// -/// -/// The scaled underline position relative to the baseline in logical pixels. -/// -/// -/// The scaled underline thickness in logical pixels. -/// -public readonly record struct TextMetrics( - float ascender, - float descender, - float lineHeight, - float underlinePosition, - float underlineThickness -); - -/// -/// Contains immutable positioned glyphs and aggregate bounds for one shaped string. -/// -public sealed class TextLayout -{ - private readonly TextGlyph[] m_glyphs; - - /// - /// Creates an immutable text layout. - /// - /// - /// The positioned glyph sequence. - /// - /// - /// The face metrics used by the layout. - /// - /// - /// The logical horizontal advance. - /// - /// - /// The logical line height. - /// - public TextLayout( - IEnumerable glyphs, - TextMetrics metrics, - float width, - float height - ) { - ArgumentNullException.ThrowIfNull(glyphs); - if (!float.IsFinite(width) || width < 0f) - throw new ArgumentOutOfRangeException(nameof(width)); - if (!float.IsFinite(height) || height < 0f) - throw new ArgumentOutOfRangeException(nameof(height)); - m_glyphs = [..glyphs]; - this.metrics = metrics; - this.width = width; - this.height = height; - } - - /// - /// Gets the immutable positioned glyph sequence. - /// - public IReadOnlyList glyphs => m_glyphs; - /// - /// Gets the font metrics used to build this layout. - /// - public TextMetrics metrics { get; } - /// - /// Gets the aggregate horizontal advance. - /// - public float width { get; } - /// - /// Gets the aggregate line height. - /// - public float height { get; } -} - -/// -/// Contains one rasterized glyph as tightly packed 8-bit coverage. -/// -public sealed class GlyphBitmap -{ - private readonly byte[] m_pixels; - - /// - /// Creates a validated immutable glyph bitmap. - /// - /// - /// The bitmap width in pixels. - /// - /// - /// The bitmap height in pixels. - /// - /// - /// The horizontal bearing in pixels. - /// - /// - /// The vertical bearing in pixels. - /// - /// - /// The horizontal glyph advance. - /// - /// - /// Tightly packed row-major 8-bit coverage. - /// - public GlyphBitmap( - int width, - int height, - int bearingX, - int bearingY, - float advanceX, - ReadOnlySpan pixels - ) { - ArgumentOutOfRangeException.ThrowIfNegative(width); - ArgumentOutOfRangeException.ThrowIfNegative(height); - if (pixels.Length != checked(width * height)) - throw new ArgumentException("Glyph coverage length must match its dimensions.", nameof(pixels)); - if (!float.IsFinite(advanceX)) - throw new ArgumentOutOfRangeException(nameof(advanceX)); - this.width = width; - this.height = height; - this.bearingX = bearingX; - this.bearingY = bearingY; - this.advanceX = advanceX; - m_pixels = pixels.ToArray(); - } - - /// - /// Gets the bitmap width in pixels. - /// - public int width { get; } - /// - /// Gets the bitmap height in pixels. - /// - public int height { get; } - /// - /// Gets the horizontal bearing in pixels. - /// - public int bearingX { get; } - /// - /// Gets the vertical bearing in pixels. - /// - public int bearingY { get; } - /// - /// Gets the horizontal glyph advance. - /// - public float advanceX { get; } - /// - /// Gets tightly packed row-major 8-bit coverage. - /// - public ReadOnlyMemory pixels => m_pixels; -} diff --git a/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs new file mode 100644 index 000000000..9e4f0fb4d --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs @@ -0,0 +1,23 @@ +namespace Inno.UI.Assets; + +/// +/// Validates one UI document language without creating runtime UI objects. +/// +public interface IUIDocumentFrontend +{ + /// + /// Gets the open source-language identity. + /// + UIDocumentLanguageID languageID { get; } + + /// + /// Analyzes one immutable source snapshot. + /// + /// + /// Original source snapshot. + /// + /// + /// Canonical text or neutral diagnostics. + /// + UIDocumentAnalysis Analyze(UIDocumentSourceFile source); +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs b/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs new file mode 100644 index 000000000..ad307cc17 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Inno.UI.Assets; + +/// +/// Returns validated text without retaining parser or implementation objects. +/// +public sealed class UIDocumentAnalysis +{ + /// + /// Creates a frozen analysis result. + /// + /// + /// Validated canonical text, or null on failure. + /// + /// + /// Complete frontend diagnostics. + /// + /// + /// Font assets declared by the document. + /// + public UIDocumentAnalysis( + string? text, + IEnumerable diagnostics, + IEnumerable? fonts = null + ) { + this.text = text; + this.diagnostics = new ReadOnlyCollection( + diagnostics?.ToArray() + ?? throw new ArgumentNullException(nameof(diagnostics)) + ); + this.fonts = new ReadOnlyCollection(fonts?.ToArray() ?? []); + } + + /// + /// Gets canonical source text, or null after failure. + /// + public string? text { get; } + + /// + /// Gets frozen diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets font assets declared by the canonical document. + /// + public IReadOnlyList fonts { get; } + + /// + /// Gets whether the frontend accepted the source. + /// + public bool succeeded => text is not null && diagnostics.Count == 0; +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs b/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs new file mode 100644 index 000000000..0cd7520fe --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs @@ -0,0 +1,23 @@ +namespace Inno.UI.Assets; + +/// +/// Reports a language-neutral source problem. +/// +/// +/// Stable diagnostic code. +/// +/// +/// Actionable description. +/// +/// +/// One-based source line. +/// +/// +/// One-based source column. +/// +public sealed record UIDocumentDiagnostic( + string code, + string message, + int line, + int column +); diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs new file mode 100644 index 000000000..a3e36c3a8 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs @@ -0,0 +1,25 @@ +using Inno.Text; + +namespace Inno.UI.Assets; + +/// +/// One font asset declared by a UI document language frontend. +/// +/// +/// Isolated font asset path. +/// +/// +/// Document-private physical family used in canonical text. +/// +/// +/// CSS-compatible face style. +/// +/// +/// CSS-compatible face weight. +/// +public sealed record UIDocumentFontDeclaration( + string assetPath, + string family, + TextFontStyle style, + int weight +); diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs new file mode 100644 index 000000000..8a02df8bc --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI.Assets; + +/// +/// Owns one immutable UI language registration snapshot. +/// +public sealed class UIDocumentFrontendCatalog +{ + private readonly Dictionary m_frontends = []; + + /// + /// Captures a validated provider set. + /// + /// + /// Providers owned by the authoring generation. + /// + public UIDocumentFrontendCatalog(IEnumerable frontends) + { + ArgumentNullException.ThrowIfNull(frontends); + foreach (IUIDocumentFrontend frontend in frontends) + { + if (frontend is null || !frontend.languageID.isValid || !m_frontends.TryAdd(frontend.languageID, frontend)) + { + throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); + } + } + this.languageIDs = new ReadOnlyCollection([.. m_frontends.Keys]); + } + + /// + /// Gets registered language identities. + /// + public IReadOnlyList languageIDs { get; } + + /// + /// Analyzes source using an explicit language. + /// + /// + /// Registered language identity. + /// + /// + /// Immutable source snapshot. + /// + /// + /// Neutral analysis result. + /// + public UIDocumentAnalysis Analyze( + UIDocumentLanguageID language, + UIDocumentSourceFile source + ) => m_frontends.TryGetValue(language, out IUIDocumentFrontend? frontend) + ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") + : throw new NotSupportedException($"UI document language '{language}' is unavailable."); + + internal IEnumerable providers => m_frontends.Values; +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs new file mode 100644 index 000000000..9b3c85c9c --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.UI.Assets; + +/// +/// Discovers UI language frontends through the shared type-generation transaction. +/// +public sealed class UIDocumentFrontendRegistry : TypeRegistry +{ + private readonly TypeCatalog m_types; + + /// + /// Registers with the owner type catalog. + /// + /// + /// Catalog that outlives this registry. + /// + public UIDocumentFrontendRegistry(TypeCatalog types) + : base(types) + { + m_types = types; + } + + /// + /// Analyzes source while preventing provider retirement. + /// + /// + /// Exact language identity. + /// + /// + /// Immutable source snapshot. + /// + /// + /// Detached neutral analysis. + /// + public UIDocumentAnalysis Analyze( + UIDocumentLanguageID language, + UIDocumentSourceFile source + ) { + using IDisposable operation = m_types.AcquireOperation("Analyze UI document source"); + return current.Analyze(language, source); + } + + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The active type catalog generation used for extension resolution. + /// + /// + /// The validated ui document frontend catalog that represents the completed operation. + /// + protected override UIDocumentFrontendCatalog Build(TypeCacheSnapshot types) + { + List providers = []; + foreach (Type type in types.GetTypesImplementing() + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { + providers.Add(CreateExtension(type)); + } + return new UIDocumentFrontendCatalog(providers); + } + + /// + /// Releases the generation lease retained by an immutable registry snapshot. + /// + /// + /// The immutable state snapshot consumed by this operation. + /// + protected override void DisposeSnapshot(UIDocumentFrontendCatalog snapshot) => DisposeExtensions(snapshot.providers); +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs new file mode 100644 index 000000000..dd6be1e8a --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Text; + +namespace Inno.UI.Assets; + +/// +/// Coordinates source analysis, font dependencies, and runtime UI asset emission. +/// +public static class UIDocumentImportPipeline +{ + /// + /// Validates and emits a deterministic runtime payload. + /// + /// + /// Source import context. + /// + /// + /// Candidate writer. + /// + /// + /// Explicit source language. + /// + /// + /// Explicit runtime implementation. + /// + /// + /// Cancellation observed by artifact writes. + /// + /// + /// An operation completing after the payload is staged. + /// + public static async ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + UIDocumentLanguageID language, + string implementationID, + CancellationToken cancellationToken + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); + string text = context.ReadUtf8Text(); + using var frontends = new UIDocumentFrontendRegistry(context.types); + UIDocumentAnalysis analysis = frontends.Analyze( + language, + new UIDocumentSourceFile(context.assetPath.ToString(), text, context.ReadSourceUtf8Text) + ); + if (!analysis.succeeded) + { + throw new InvalidDataException( + string.Join( + "\n", + analysis.diagnostics.Select(static diagnostic => + $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}") + ) + ); + } + var fonts = new List(analysis.fonts.Count); + foreach (UIDocumentFontDeclaration declaration in analysis.fonts) + { + FontAsset font = context.ResolveDependency(AssetPath.Parse(declaration.assetPath)); + if (font.isMissing || font.metadata is not { faceCount: > 0 }) + { + throw new InvalidDataException($"UI font asset '{declaration.assetPath}' has no usable face."); + } + context.DependsOnArtifact(font.identity.persistentID); + fonts.Add( + new UIDocumentFontFace( + font.identity.persistentID, + declaration.family, + declaration.style, + declaration.weight + ) + ); + } + string sourceUri = $"innoasset://{context.assetPath.source.value}/{context.assetPath.localPath}"; + var source = new UIDocumentSource(language, analysis.text!, sourceUri); + output.SetAsset(new UIDocumentAsset()); + await output.WriteArtifactAsync( + "runtime", + UIDocumentAsset.CreateRuntimePayload(implementationID, source, fonts), + cancellationToken: cancellationToken + ).ConfigureAwait(false); + } +} diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImportSettings.cs similarity index 57% rename from src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs rename to src/services/ui/Inno.UI.Assets/UIDocumentImportSettings.cs index 2320f665a..becb50aeb 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImportSettings.cs @@ -6,15 +6,18 @@ namespace Inno.UI.Assets; /// /// Explicitly selects language and runtime implementation for neutral UI source. /// -[StableTypeId("7a56cdb8-eec0-49fd-bdd5-659d24c091b5")] -public sealed class UiDocumentImportSettings : ISerializable +[StableTypeID("7a56cdb8-eec0-49fd-bdd5-659d24c091b5")] +public sealed class UIDocumentImportSettings : ISerializable { /// /// Gets or sets the registered source-language identity. /// - [SerializableProperty] public string languageId { get; set; } = string.Empty; + [SerializableProperty] + public string languageId { get; set; } = string.Empty; + /// /// Gets or sets the exact runtime implementation identity. /// - [SerializableProperty] public string implementationId { get; set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; set; } = string.Empty; } diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs new file mode 100644 index 000000000..c274d57b2 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Inno.Assets.Pipeline; +using Inno.Core.Serialization; + +namespace Inno.UI.Assets; + +/// +/// Imports implementation-neutral UTF-8 UI source using explicit sidecar settings. +/// +[AssetImporter("inno.ui.document")] +public sealed class UIDocumentImporter : AssetImporter +{ + /// + /// Gets the normalized source extensions accepted by this importer. + /// + public override IReadOnlyList supportedExtensions { get; } = [".iuidocument"]; + + /// + /// Creates an import settings using this implementation's validated inputs. + /// + /// + /// The validated iserializable that represents the completed operation. + /// + public override ISerializable CreateImportSettings() => new UIDocumentImportSettings(); + + /// + /// Imports source content into a validated runtime asset and artifact set. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The import output writer that receives runtime data and dependency declarations. + /// + /// + /// The token that cancels the operation before it commits. + /// + /// + /// An asynchronous operation that completes after all requested work has finished. + /// + protected override async ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + UIDocumentImportSettings settings = context.importSettings as UIDocumentImportSettings + ?? throw new InvalidOperationException("UI source requires its standard import settings."); + ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); + ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); + await UIDocumentImportPipeline.ImportAsync( + context, + output, + new UIDocumentLanguageID(settings.languageId), + settings.implementationId, + cancellationToken + ).ConfigureAwait(false); + } +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs b/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs new file mode 100644 index 000000000..df1149031 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Assets; + +namespace Inno.UI.Assets; + +/// +/// Contains immutable source text supplied to a UI language frontend. +/// +/// +/// Original asset mount path. +/// +/// +/// Strictly decoded UTF-8 text. +/// +/// +/// Reads and records an optional isolated source dependency. +/// +public sealed record UIDocumentSourceFile( + string assetPath, + string text, + Func? readSource = null +); diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs deleted file mode 100644 index ec2ca543d..000000000 --- a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs +++ /dev/null @@ -1,241 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -using Inno.Extensibility.Types; - -namespace Inno.UI.Assets; - -/// -/// Contains immutable source text supplied to a UI language frontend. -/// -/// -/// Original asset mount path. -/// -/// -/// Strictly decoded UTF-8 text. -/// -/// -/// Reads and records an optional isolated source dependency. -/// -public sealed record UiDocumentSourceFile( - string assetPath, - string text, - Func? readSource = null -); - -/// -/// Reports a language-neutral source problem. -/// -/// -/// Stable diagnostic code. -/// -/// -/// Actionable description. -/// -/// -/// One-based source line. -/// -/// -/// One-based source column. -/// -public sealed record UiDocumentDiagnostic( - string code, - string message, - int line, - int column -); - -/// -/// One font asset declared by a UI document language frontend. -/// -/// -/// Isolated font asset path. -/// -/// -/// Document-private physical family used in canonical text. -/// -/// -/// CSS-compatible face style. -/// -/// -/// CSS-compatible face weight. -/// -public sealed record UiDocumentFontDeclaration( - string assetPath, - string family, - Inno.Text.TextFontStyle style, - int weight -); - -/// -/// Returns validated text without retaining parser or implementation objects. -/// -public sealed class UiDocumentAnalysis -{ - /// - /// Creates a frozen analysis result. - /// - /// - /// Validated canonical text, or null on failure. - /// - /// - /// Complete frontend diagnostics. - /// - /// - /// Font assets declared by the document. - /// - public UiDocumentAnalysis( - string? text, - IEnumerable diagnostics, - IEnumerable? fonts = null - ) { - this.text = text; - this.diagnostics = new ReadOnlyCollection(diagnostics?.ToArray() - ?? throw new ArgumentNullException(nameof(diagnostics))); - this.fonts = new ReadOnlyCollection(fonts?.ToArray() ?? []); - } - /// - /// Gets canonical source text, or null after failure. - /// - public string? text { get; } - /// - /// Gets frozen diagnostics. - /// - public IReadOnlyList diagnostics { get; } - /// - /// Gets font assets declared by the canonical document. - /// - public IReadOnlyList fonts { get; } - /// - /// Gets whether the frontend accepted the source. - /// - public bool succeeded => text is not null && diagnostics.Count == 0; -} - -/// -/// Validates one UI document language without creating runtime UI objects. -/// -public interface IUiDocumentFrontend -{ - /// - /// Gets the open source-language identity. - /// - UiDocumentLanguageId languageId { get; } - /// - /// Analyzes one immutable source snapshot. - /// - /// - /// Original source snapshot. - /// - /// - /// Canonical text or neutral diagnostics. - /// - UiDocumentAnalysis Analyze(UiDocumentSourceFile source); -} - -/// -/// Owns one immutable UI language registration snapshot. -/// -public sealed class UiDocumentFrontendCatalog -{ - private readonly Dictionary m_frontends = []; - /// - /// Captures a validated provider set. - /// - /// - /// Providers owned by the authoring generation. - /// - public UiDocumentFrontendCatalog(IEnumerable frontends) - { - ArgumentNullException.ThrowIfNull(frontends); - foreach (IUiDocumentFrontend frontend in frontends) - if (frontend is null || !frontend.languageId.isValid || !m_frontends.TryAdd(frontend.languageId, frontend)) - throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); - languageIds = new ReadOnlyCollection([.. m_frontends.Keys]); - } - /// - /// Gets registered language identities. - /// - public IReadOnlyList languageIds { get; } - internal IEnumerable providers => m_frontends.Values; - /// - /// Analyzes source using an explicit language. - /// - /// - /// Registered language identity. - /// - /// - /// Immutable source snapshot. - /// - /// - /// Neutral analysis result. - /// - public UiDocumentAnalysis Analyze( - UiDocumentLanguageId language, - UiDocumentSourceFile source - ) - => m_frontends.TryGetValue(language, out IUiDocumentFrontend? frontend) - ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") - : throw new NotSupportedException($"UI document language '{language}' is unavailable."); -} - -/// -/// Discovers UI language frontends through the shared type-generation transaction. -/// -public sealed class UiDocumentFrontendRegistry : TypeRegistry -{ - private readonly TypeCatalog m_types; - /// - /// Registers with the owner type catalog. - /// - /// - /// Catalog that outlives this registry. - /// - public UiDocumentFrontendRegistry(TypeCatalog types) : base(types) => m_types = types; - /// - /// Analyzes source while preventing provider retirement. - /// - /// - /// Exact language identity. - /// - /// - /// Immutable source snapshot. - /// - /// - /// Detached neutral analysis. - /// - public UiDocumentAnalysis Analyze( - UiDocumentLanguageId language, - UiDocumentSourceFile source - ) { - using IDisposable operation = m_types.AcquireOperation("Analyze UI document source"); - return current.Analyze(language, source); - } - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The active type catalog generation used for extension resolution. - /// - /// - /// The validated ui document frontend catalog that represents the completed operation. - /// - protected override UiDocumentFrontendCatalog Build(TypeCacheSnapshot types) - { - var providers = new List(); - foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - providers.Add(CreateExtension(type)); - return new UiDocumentFrontendCatalog(providers); - } - /// - /// Releases the generation lease retained by an immutable registry snapshot. - /// - /// - /// The immutable state snapshot consumed by this operation. - /// - protected override void DisposeSnapshot(UiDocumentFrontendCatalog snapshot) => DisposeExtensions(snapshot.providers); -} diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs b/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs deleted file mode 100644 index 6d622bda5..000000000 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -using Inno.Assets.Pipeline; -using Inno.Assets; -using Inno.Core.Serialization; -using Inno.Text; - -namespace Inno.UI.Assets; - -/// -/// Imports implementation-neutral UTF-8 UI source using explicit sidecar settings. -/// -[AssetImporter("inno.ui.document")] -public sealed class UiDocumentImporter : AssetImporter -{ - /// - /// Gets the normalized source extensions accepted by this importer. - /// - public override IReadOnlyList supportedExtensions { get; } = [".iuidocument"]; - - /// - /// Creates an import settings using this implementation's validated inputs. - /// - /// - /// The validated iserializable that represents the completed operation. - /// - public override ISerializable CreateImportSettings() => new UiDocumentImportSettings(); - - /// - /// Imports source content into a validated runtime asset and artifact set. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The import output writer that receives runtime data and dependency declarations. - /// - /// - /// The token that cancels the operation before it commits. - /// - /// - /// An asynchronous operation that completes after all requested work has finished. - /// - protected override async ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - var settings = context.importSettings as UiDocumentImportSettings - ?? throw new InvalidOperationException("UI source requires its standard import settings."); - ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); - ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); - await UiDocumentImportPipeline.ImportAsync( - context, - output, - new UiDocumentLanguageId(settings.languageId), - settings.implementationId, - cancellationToken).ConfigureAwait(false); - } -} - -/// -/// Coordinates source analysis, font dependencies, and runtime UI asset emission. -/// -public static class UiDocumentImportPipeline -{ - /// - /// Validates and emits a deterministic runtime payload. - /// - /// - /// Source import context. - /// - /// - /// Candidate writer. - /// - /// - /// Explicit source language. - /// - /// - /// Explicit runtime implementation. - /// - /// - /// Cancellation observed by artifact writes. - /// - /// - /// An operation completing after the payload is staged. - /// - public static async ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - UiDocumentLanguageId language, - string implementationId, - CancellationToken cancellationToken - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); - string text = context.ReadUtf8Text(); - using var frontends = new UiDocumentFrontendRegistry(context.types); - UiDocumentAnalysis analysis = frontends.Analyze(language, - new(context.assetPath.ToString(), text, context.ReadSourceUtf8Text)); - if (!analysis.succeeded) - throw new InvalidDataException(string.Join("\n", analysis.diagnostics.Select(static diagnostic => - $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}"))); - var fonts = new List(analysis.fonts.Count); - foreach (UiDocumentFontDeclaration declaration in analysis.fonts) - { - FontAsset font = context.ResolveDependency(AssetPath.Parse(declaration.assetPath)); - if (font.isMissing || font.metadata is not { faceCount: > 0 }) - throw new InvalidDataException($"UI font asset '{declaration.assetPath}' has no usable face."); - context.DependsOnArtifact(font.identity.persistentId); - fonts.Add(new UiDocumentFontFace(font.identity.persistentId, - declaration.family, declaration.style, declaration.weight)); - } - string sourceUri = $"innoasset://{context.assetPath.source.value}/{context.assetPath.localPath}"; - var source = new UiDocumentSource(language, analysis.text!, sourceUri); - output.SetAsset(new UiDocumentAsset()); - await output.WriteArtifactAsync( - "runtime", - UiDocumentAsset.CreateRuntimePayload(implementationId, source, fonts), - cancellationToken).ConfigureAwait(false); - } -} diff --git a/src/services/ui/Inno.UI.Runtime/UiRuntime.cs b/src/services/ui/Inno.UI.Runtime/UIRuntime.cs similarity index 82% rename from src/services/ui/Inno.UI.Runtime/UiRuntime.cs rename to src/services/ui/Inno.UI.Runtime/UIRuntime.cs index 3057b230e..70d10d73b 100644 --- a/src/services/ui/Inno.UI.Runtime/UiRuntime.cs +++ b/src/services/ui/Inno.UI.Runtime/UIRuntime.cs @@ -3,7 +3,6 @@ using System.Globalization; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Mathematics; using Inno.Input; @@ -16,9 +15,9 @@ namespace Inno.UI.Runtime; /// /// Owns retained UI contexts, imported font leases, and current-frame input for one runtime session. /// -public sealed class UiRuntime : RuntimeSubsystem, IUiService +public sealed class UIRuntime : RuntimeSubsystem, IUIService { - private readonly IUiBackend m_backend; + private readonly IUIBackend m_backend; private readonly IAssetArtifactLookup m_artifacts; private readonly Dictionary m_fonts = []; private readonly Dictionary m_documentFonts = []; @@ -34,24 +33,14 @@ public sealed class UiRuntime : RuntimeSubsystem, IUiService /// /// The immutable asset artifact lookup. /// - public UiRuntime( - IUiBackend backend, + public UIRuntime( + IUIBackend backend, IAssetArtifactLookup artifacts ) { - m_backend = backend ?? throw new ArgumentNullException(nameof(backend)); - m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - } - - /// - /// Captures the input service snapshot and binds script-facing UI for the complete runtime frame. - /// - /// - /// The current runtime frame. - /// - protected override void OnBeginFrame(RuntimeFrame frame) - { - m_input = InputExecutionContext.current.snapshot; - OwnFrameScope(EnterExecutionScope()); + ArgumentNullException.ThrowIfNull(backend); + ArgumentNullException.ThrowIfNull(artifacts); + m_backend = backend; + m_artifacts = artifacts; } /// @@ -63,7 +52,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) public IDisposable EnterExecutionScope() { EnsureActive(); - return UiExecutionContext.EnterScope(this); + return UIExecutionContext.EnterScope(this); } /// @@ -75,7 +64,7 @@ public IDisposable EnterExecutionScope() /// /// The validated ui context handle that represents the completed operation. /// - public UiContextHandle CreateContext(UiContextOptions options) + public UIContextHandle CreateContext(UIContextOptions options) { EnsureActive(); return m_backend.CreateContext(options); @@ -87,7 +76,7 @@ public UiContextHandle CreateContext(UiContextOptions options) /// /// The context that supplies state and services for this operation. /// - public void DestroyContext(UiContextHandle context) + public void DestroyContext(UIContextHandle context) { EnsureActive(); m_backend.DestroyContext(context); @@ -115,7 +104,7 @@ public void DestroyContext(UiContextHandle context) /// The density consumed by set viewport; ownership remains with the caller unless explicitly stated otherwise. /// public void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density = 1f @@ -136,9 +125,9 @@ public void SetViewport( /// /// The validated ui document handle that represents the completed operation. /// - public UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source + public UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source ) { ArgumentNullException.ThrowIfNull(source); EnsureActive(); @@ -158,38 +147,45 @@ UiDocumentSource source /// /// The validated ui document handle that represents the completed operation. /// - public UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentAsset document + public UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentAsset document ) { ArgumentNullException.ThrowIfNull(document); EnsureActive(); if (document.isMissing) + { throw new InvalidOperationException("The UI document asset is missing."); - UiDocumentSource source = document.source - ?? throw new InvalidOperationException("The UI document has no imported runtime payload."); - if (!string.Equals(document.implementationId, m_backend.implementationId, StringComparison.Ordinal)) + } + UIDocumentSource source = document.source + ?? throw new InvalidOperationException("The UI document has no imported runtime payload."); + if (!string.Equals(document.implementationID, m_backend.implementationID, StringComparison.Ordinal)) + { throw new InvalidOperationException( - $"UI document implementation '{document.implementationId}' cannot be loaded by selected backend '{m_backend.implementationId}'."); + $"UI document implementation '{document.implementationID}' cannot be loaded by selected backend '{m_backend.implementationID}'." + ); + } EnsureLanguageSupported(source.language); string text = source.text; var families = new Dictionary(StringComparer.Ordinal); var registrations = new List(document.fonts.Count); try { - foreach (UiDocumentFontFace face in document.fonts) + foreach (UIDocumentFontFace face in document.fonts) { if (!families.TryGetValue(face.family, out string? versionedFamily)) { versionedFamily = face.family + "__v" - + document.contentVersion.ToString("x", CultureInfo.InvariantCulture); + + document.contentVersion.ToString("x", CultureInfo.InvariantCulture); families.Add(face.family, versionedFamily); text = text.Replace(face.family, versionedFamily, StringComparison.Ordinal); } registrations.Add(RegisterDocumentFont(face, document.contentVersion, versionedFamily)); } - UiDocumentHandle handle = m_backend.LoadDocument(context, - new UiDocumentSource(source.language, text, source.sourceUri)); + UIDocumentHandle handle = m_backend.LoadDocument( + context, + new UIDocumentSource(source.language, text, source.sourceUri) + ); if (registrations.Count > 0) { var key = new DocumentKey(context, handle); @@ -218,8 +214,8 @@ UiDocumentAsset document /// The document consumed by show document; ownership remains with the caller unless explicitly stated otherwise. /// public void ShowDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); m_backend.ShowDocument(context, document); @@ -235,8 +231,8 @@ UiDocumentHandle document /// The document consumed by hide document; ownership remains with the caller unless explicitly stated otherwise. /// public void HideDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); m_backend.HideDocument(context, document); @@ -252,14 +248,16 @@ UiDocumentHandle document /// The document consumed by close document; ownership remains with the caller unless explicitly stated otherwise. /// public void CloseDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ) { EnsureActive(); m_backend.CloseDocument(context, document); var key = new DocumentKey(context, document); if (m_documentFonts.Remove(key, out FontRegistration[]? registrations)) + { ReleaseFonts(registrations); + } } /// @@ -271,7 +269,7 @@ UiDocumentHandle document /// /// The document consumed by set text; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set text operation. /// /// @@ -281,13 +279,13 @@ UiDocumentHandle document /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text ) { EnsureActive(); - return m_backend.SetText(context, document, elementId, text); + return m_backend.SetText(context, document, elementID, text); } /// @@ -299,7 +297,7 @@ string text /// /// The document consumed by set content; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set content operation. /// /// @@ -309,14 +307,14 @@ string text /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment content + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment content ) { EnsureActive(); EnsureLanguageSupported(content.language); - return m_backend.SetContent(context, document, elementId, content); + return m_backend.SetContent(context, document, elementID, content); } /// @@ -328,7 +326,7 @@ UiDocumentFragment content /// /// The document consumed by set attribute; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set attribute operation. /// /// @@ -341,14 +339,14 @@ UiDocumentFragment content /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value ) { EnsureActive(); - return m_backend.SetAttribute(context, document, elementId, name, value); + return m_backend.SetAttribute(context, document, elementID, name, value); } /// @@ -360,7 +358,7 @@ string value /// /// The document consumed by set class; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set class operation. /// /// @@ -373,14 +371,14 @@ string value /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active ) { EnsureActive(); - return m_backend.SetClass(context, document, elementId, className, active); + return m_backend.SetClass(context, document, elementID, className, active); } /// @@ -396,9 +394,9 @@ bool active /// The texture consumed by register texture; ownership remains with the caller unless explicitly stated otherwise. /// public void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture + UITextureData texture ) { EnsureActive(); m_backend.RegisterTexture(context, source, texture); @@ -417,7 +415,7 @@ UiTextureData texture /// when the operation succeeds or its condition is satisfied; otherwise, . /// public bool HasElementAtPoint( - UiContextHandle context, + UIContextHandle context, Vector2 position ) { EnsureActive(); @@ -430,18 +428,22 @@ Vector2 position /// /// The context that supplies state and services for this operation. /// - public void Update(UiContextHandle context) + public void Update(UIContextHandle context) { EnsureActive(); - m_backend.Update(context, new UiInputSnapshot( - m_input.mousePosition, - m_input.scrollDelta, - m_input.modifiers, - m_input.keysPressed, - m_input.keysReleased, - m_input.mouseButtonsPressed, - m_input.mouseButtonsReleased, - m_input.textInput)); + m_backend.Update( + context, + new UIInputSnapshot( + m_input.mousePosition, + m_input.scrollDelta, + m_input.modifiers, + m_input.keysPressed, + m_input.keysReleased, + m_input.mouseButtonsPressed, + m_input.mouseButtonsReleased, + m_input.textInput + ) + ); } /// @@ -454,11 +456,12 @@ public void Update(UiContextHandle context) /// Input mapped into the context's local pixel coordinates. /// public void Update( - UiContextHandle context, - UiInputSnapshot input + UIContextHandle context, + UIInputSnapshot input ) { + ArgumentNullException.ThrowIfNull(input); EnsureActive(); - m_backend.Update(context, input ?? throw new ArgumentNullException(nameof(input))); + m_backend.Update(context, input); } /// @@ -470,7 +473,7 @@ UiInputSnapshot input /// /// The validated ui render frame that represents the completed operation. /// - public UiRenderFrame Render(UiContextHandle context) + public UIRenderFrame Render(UIContextHandle context) { EnsureActive(); return m_backend.Render(context); @@ -485,19 +488,33 @@ public UiRenderFrame Render(UiContextHandle context) /// /// An immutable snapshot of the values selected by the operation. /// - public IReadOnlyList DrainEvents(UiContextHandle context) + public IReadOnlyList DrainEvents(UIContextHandle context) { EnsureActive(); return m_backend.DrainEvents(context); } + /// + /// Captures the input service snapshot and binds script-facing UI for the complete runtime frame. + /// + /// + /// The current runtime frame. + /// + protected override void OnBeginFrame(RuntimeFrame frame) + { + m_input = InputExecutionContext.current.snapshot; + OwnFrameScope(EnterExecutionScope()); + } + /// /// Releases native UI state before releasing retained font artifacts. /// protected override void OnStop() { if (m_disposed) + { return; + } List failures = []; try { @@ -521,7 +538,9 @@ protected override void OnStop() } m_documentFonts.Clear(); if (failures.Count > 0) + { throw new AggregateException("UI runtime retirement failed.", failures); + } m_disposed = true; } @@ -530,28 +549,29 @@ protected override void OnStop() private void RegisterBackendFont( ArtifactLease artifact, FontRegistration registration - ) - => m_backend.RegisterFont(new UiFontRegistration( + ) => m_backend.RegisterFont( + new UIFontRegistration( artifact.ReadAllBytes(), registration.faceIndex, registration.family, registration.style, - registration.weight)); + registration.weight + ) + ); private FontRegistration RegisterDocumentFont( - UiDocumentFontFace face, + UIDocumentFontFace face, long documentVersion, string family ) { - var registration = new FontRegistration(face.assetId, documentVersion, 0, - family, face.style, face.weight); + var registration = new FontRegistration(face.assetID, documentVersion, 0, family, face.style, face.weight); if (m_fonts.TryGetValue(registration, out FontResidency? existing)) { RegisterBackendFont(existing.lease, registration); existing.references++; return registration; } - ArtifactLease artifact = m_artifacts.AcquireArtifact(face.assetId, "font-data"); + ArtifactLease artifact = m_artifacts.AcquireArtifact(face.assetID, "font-data"); try { RegisterBackendFont(artifact, registration); @@ -572,7 +592,9 @@ private void ReleaseFonts(IEnumerable registrations) { FontResidency residency = m_fonts[registration]; if (--residency.references > 0) + { continue; + } try { residency.lease.Dispose(); @@ -584,29 +606,35 @@ private void ReleaseFonts(IEnumerable registrations) } } if (failures is not null) + { throw new AggregateException("UI font artifact retirement is incomplete.", failures); + } + } + + private void EnsureLanguageSupported(UIDocumentLanguageID language) + { + if (!m_backend.capabilities.Supports(language)) + { + throw new NotSupportedException( + $"UI document language '{language}' is not supported by selected backend '{m_backend.implementationID}'." + ); + } } private sealed class FontResidency(ArtifactLease lease) { - internal ArtifactLease lease { get; } = lease; internal int references = 1; + + internal ArtifactLease lease { get; } = lease; } private readonly record struct DocumentKey( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); - private void EnsureLanguageSupported(UiDocumentLanguageId language) - { - if (!m_backend.capabilities.Supports(language)) - throw new NotSupportedException( - $"UI document language '{language}' is not supported by selected backend '{m_backend.implementationId}'."); - } - private readonly record struct FontRegistration( - Guid persistentId, + Guid persistentID, long version, int faceIndex, string family, diff --git a/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs b/src/services/ui/Inno.UI.Runtime/UIRuntimeFactory.cs similarity index 68% rename from src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs rename to src/services/ui/Inno.UI.Runtime/UIRuntimeFactory.cs index dfeda8cdf..74e4f4c4c 100644 --- a/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs +++ b/src/services/ui/Inno.UI.Runtime/UIRuntimeFactory.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; using Inno.Runtime.Contracts; @@ -8,9 +7,9 @@ namespace Inno.UI.Runtime; /// /// Creates one UI service for every isolated runtime session. /// -public sealed class UiRuntimeFactory : IRuntimeSubsystemFactory +public sealed class UIRuntimeFactory : IRuntimeSubsystemFactory { - private readonly Func m_runtimeFactory; + private readonly Func m_runtimeFactory; /// /// Creates a reusable UI runtime factory. @@ -18,21 +17,23 @@ public sealed class UiRuntimeFactory : IRuntimeSubsystemFactory /// /// The callback that creates one runtime per session. /// - public UiRuntimeFactory(Func runtimeFactory) + public UIRuntimeFactory(Func runtimeFactory) { - m_runtimeFactory = runtimeFactory ?? throw new ArgumentNullException(nameof(runtimeFactory)); + ArgumentNullException.ThrowIfNull(runtimeFactory); + m_runtimeFactory = runtimeFactory; } /// /// Gets stable ordering metadata that makes UI available before scene simulation. /// public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("inno.runtime.ui"), + new RuntimeSubsystemID("inno.runtime.ui"), order: -700, dependencies: [ - new RuntimeSubsystemId("inno.runtime.input") - ]); + new RuntimeSubsystemID("inno.runtime.input") + ] + ); /// /// Creates one session-owned UI runtime. @@ -47,6 +48,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); return m_runtimeFactory(context) - ?? throw new InvalidOperationException("The UI runtime factory returned null."); + ?? throw new InvalidOperationException("The UI runtime factory returned null."); } } diff --git a/src/services/ui/Inno.UI/IUiBackend.cs b/src/services/ui/Inno.UI/IUIBackend.cs similarity index 84% rename from src/services/ui/Inno.UI/IUiBackend.cs rename to src/services/ui/Inno.UI/IUIBackend.cs index 0e452366d..7d842bb07 100644 --- a/src/services/ui/Inno.UI/IUiBackend.cs +++ b/src/services/ui/Inno.UI/IUIBackend.cs @@ -7,16 +7,18 @@ namespace Inno.UI; /// /// Defines the replaceable document, layout, input, and draw-geometry backend boundary. /// -public interface IUiBackend : IDisposable +public interface IUIBackend : IDisposable { /// /// Gets the stable implementation identity used by imported document artifacts. /// - string implementationId { get; } + string implementationID { get; } + /// /// Gets optional behavior and accepted document languages for this generation. /// - UiBackendCapabilities capabilities { get; } + UIBackendCapabilities capabilities { get; } + /// /// Creates one independent UI context. /// @@ -26,14 +28,16 @@ public interface IUiBackend : IDisposable /// /// A handle owned by the caller until destruction. /// - UiContextHandle CreateContext(UiContextOptions options); + UIContextHandle CreateContext(UIContextOptions options); + /// /// Destroys one UI context and all of its documents. /// /// /// The context that owns the requested document or state. /// - void DestroyContext(UiContextHandle context); + void DestroyContext(UIContextHandle context); + /// /// Changes one UI context's pixel dimensions and density. /// @@ -50,11 +54,12 @@ public interface IUiBackend : IDisposable /// Physical pixels per logical layout pixel. /// void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density ); + /// /// Loads one explicitly tagged in-memory document. /// @@ -67,10 +72,11 @@ float density /// /// A document handle owned by the supplied context. /// - UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source + UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source ); + /// /// Shows one document. /// @@ -81,9 +87,10 @@ UiDocumentSource source /// The document owned by the supplied context. /// void ShowDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Hides one document. /// @@ -94,9 +101,10 @@ UiDocumentHandle document /// The document owned by the supplied context. /// void HideDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Closes one document. /// @@ -107,9 +115,10 @@ UiDocumentHandle document /// The document owned by the supplied context. /// void CloseDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Replaces an element's children with plain Unicode text. /// @@ -119,7 +128,7 @@ UiDocumentHandle document /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -130,11 +139,12 @@ UiDocumentHandle document /// This is not a comparison with the preceding text. /// bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text ); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -144,7 +154,7 @@ string text /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -155,11 +165,12 @@ string text /// This is not a comparison with the preceding content. /// bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment fragment + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment fragment ); + /// /// Sets one element attribute. /// @@ -169,7 +180,7 @@ UiDocumentFragment fragment /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -183,12 +194,13 @@ UiDocumentFragment fragment /// This is not a comparison with the preceding value. /// bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value ); + /// /// Activates or deactivates one element class. /// @@ -198,7 +210,7 @@ string value /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -212,19 +224,21 @@ string value /// This is not a comparison with the preceding state. /// bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active ); + /// /// Registers an encoded font face in the document engine. /// /// /// Font bytes and family metadata to register. /// - void RegisterFont(UiFontRegistration registration); + void RegisterFont(UIFontRegistration registration); + /// /// Registers a named RGBA8 texture source. /// @@ -238,10 +252,11 @@ bool active /// Immutable RGBA texture data. /// void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture + UITextureData texture ); + /// /// Tests whether a visible document element receives pointer events at a pixel location. /// @@ -255,9 +270,10 @@ UiTextureData texture /// True when an interactive visible element occupies the location. /// bool HasElementAtPoint( - UiContextHandle context, + UIContextHandle context, Vector2 position ); + /// /// Processes input and advances document state. /// @@ -268,9 +284,10 @@ Vector2 position /// The input snapshot routed to this context. /// void Update( - UiContextHandle context, - UiInputSnapshot input + UIContextHandle context, + UIInputSnapshot input ); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -280,7 +297,8 @@ UiInputSnapshot input /// /// An immutable frame of ordered UI draws and resources. /// - UiRenderFrame Render(UiContextHandle context); + UIRenderFrame Render(UIContextHandle context); + /// /// Drains document events queued by the preceding updates. /// @@ -290,5 +308,5 @@ UiInputSnapshot input /// /// Events emitted since the preceding drain, in dispatch order. /// - IReadOnlyList DrainEvents(UiContextHandle context); + IReadOnlyList DrainEvents(UIContextHandle context); } diff --git a/src/services/ui/Inno.UI/IUiService.cs b/src/services/ui/Inno.UI/IUIService.cs similarity index 85% rename from src/services/ui/Inno.UI/IUiService.cs rename to src/services/ui/Inno.UI/IUIService.cs index f4b28decb..a2eefde2c 100644 --- a/src/services/ui/Inno.UI/IUiService.cs +++ b/src/services/ui/Inno.UI/IUIService.cs @@ -1,13 +1,12 @@ using System.Collections.Generic; using Inno.Core.Mathematics; - namespace Inno.UI; /// /// Provides retained-mode documents and backend-neutral UI frames to scripts and rendering plugins. /// -public interface IUiService +public interface IUIService { /// /// Creates one independent UI context. @@ -18,14 +17,16 @@ public interface IUiService /// /// A handle owned by the caller until destruction. /// - UiContextHandle CreateContext(UiContextOptions options); + UIContextHandle CreateContext(UIContextOptions options); + /// /// Destroys one UI context and all owned documents. /// /// /// The context that owns the requested document or state. /// - void DestroyContext(UiContextHandle context); + void DestroyContext(UIContextHandle context); + /// /// Changes one context's pixel dimensions and density. /// @@ -42,11 +43,12 @@ public interface IUiService /// Physical pixels per logical layout pixel. /// void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density = 1f ); + /// /// Loads one explicitly tagged in-memory document. /// @@ -59,10 +61,11 @@ void SetViewport( /// /// A document handle owned by the supplied context. /// - UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source + UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source ); + /// /// Loads one imported document compatible with the selected backend. /// @@ -75,10 +78,11 @@ UiDocumentSource source /// /// A document handle owned by the supplied context. /// - UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentAsset document + UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentAsset document ); + /// /// Shows one document. /// @@ -89,9 +93,10 @@ UiDocumentAsset document /// The document owned by the supplied context. /// void ShowDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Hides one document. /// @@ -102,9 +107,10 @@ UiDocumentHandle document /// The document owned by the supplied context. /// void HideDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Closes one document. /// @@ -115,9 +121,10 @@ UiDocumentHandle document /// The document owned by the supplied context. /// void CloseDocument( - UiContextHandle context, - UiDocumentHandle document + UIContextHandle context, + UIDocumentHandle document ); + /// /// Replaces an element's children with plain Unicode text. /// @@ -127,7 +134,7 @@ UiDocumentHandle document /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -138,11 +145,12 @@ UiDocumentHandle document /// This is not a comparison with the preceding text. /// bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text ); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -152,7 +160,7 @@ string text /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -163,11 +171,12 @@ string text /// This is not a comparison with the preceding content. /// bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment fragment + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment fragment ); + /// /// Sets one element attribute. /// @@ -177,7 +186,7 @@ UiDocumentFragment fragment /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -191,12 +200,13 @@ UiDocumentFragment fragment /// This is not a comparison with the preceding value. /// bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value ); + /// /// Activates or deactivates one element class. /// @@ -206,7 +216,7 @@ string value /// /// The document owned by the supplied context. /// - /// + /// /// The target document element ID. /// /// @@ -220,12 +230,13 @@ string value /// This is not a comparison with the preceding state. /// bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active ); + /// /// Registers one named RGBA8 texture source. /// @@ -239,10 +250,11 @@ bool active /// Immutable RGBA texture data. /// void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture + UITextureData texture ); + /// /// Tests whether a visible document element receives pointer events at a pixel location. /// @@ -256,16 +268,18 @@ UiTextureData texture /// True when an interactive visible element occupies the location. /// bool HasElementAtPoint( - UiContextHandle context, + UIContextHandle context, Vector2 position ); + /// /// Processes current-frame input and advances one context. /// /// /// The context that owns the requested document or state. /// - void Update(UiContextHandle context); + void Update(UIContextHandle context); + /// /// Advances one context with explicitly routed viewport-local input. /// @@ -276,9 +290,10 @@ Vector2 position /// The input snapshot routed to this context. /// void Update( - UiContextHandle context, - UiInputSnapshot input + UIContextHandle context, + UIInputSnapshot input ); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -288,7 +303,8 @@ UiInputSnapshot input /// /// An immutable frame of ordered UI draws and resources. /// - UiRenderFrame Render(UiContextHandle context); + UIRenderFrame Render(UIContextHandle context); + /// /// Drains document events queued by preceding updates. /// @@ -298,5 +314,5 @@ UiInputSnapshot input /// /// Events emitted since the preceding drain, in dispatch order. /// - IReadOnlyList DrainEvents(UiContextHandle context); + IReadOnlyList DrainEvents(UIContextHandle context); } diff --git a/src/services/ui/Inno.UI/Properties/ScriptingApi.cs b/src/services/ui/Inno.UI/Properties/ScriptingApi.cs index bc2e7c7a0..7a9df4ed3 100644 --- a/src/services/ui/Inno.UI/Properties/ScriptingApi.cs +++ b/src/services/ui/Inno.UI/Properties/ScriptingApi.cs @@ -3,25 +3,25 @@ [assembly: ScriptingApiNamespace("InnoEngine.UI", "Inno.UI", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(UI), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiExecutionContext), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(IUiService), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiContextHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiContextOptions), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentLanguageId), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentSource), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentFragment), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentAsset), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDocumentFontFace), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiTextureData), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiEventType), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiEvent), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiMeshHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiTextureHandle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiVertex), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiClipRectangle), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiDrawCommand), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiMeshUpdate), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiTextureUpdate), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiRenderFrame), ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport(typeof(UiInputSnapshot), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIExecutionContext), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(IUIService), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIContextHandle), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentHandle), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIContextOptions), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentLanguageID), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentSource), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentFragment), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentAsset), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDocumentFontFace), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UITextureData), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIEventType), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIEvent), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIMeshHandle), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UITextureHandle), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIVertex), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIClipRectangle), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIDrawCommand), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIMeshUpdate), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UITextureUpdate), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIRenderFrame), ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(UIInputSnapshot), ScriptingApiScope.Runtime)] diff --git a/src/services/ui/Inno.UI/UI.cs b/src/services/ui/Inno.UI/UI.cs index 26b522ddc..774e01162 100644 --- a/src/services/ui/Inno.UI/UI.cs +++ b/src/services/ui/Inno.UI/UI.cs @@ -1,38 +1,7 @@ -using System; using System.Collections.Generic; -using Inno.Core.Execution; - namespace Inno.UI; -/// -/// Binds one UI service to the current asynchronous execution context. -/// -public static class UiExecutionContext -{ - private static readonly ExecutionSlot S_CURRENT_SCOPE = new("ui"); - - /// - /// Gets the UI service bound to the current execution context. - /// - public static IUiService current => S_CURRENT_SCOPE.current; - - /// - /// Binds a UI service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned UI service. - /// - /// - /// The caller-owned binding scope. - /// - public static IDisposable EnterScope(IUiService ui) - { - ArgumentNullException.ThrowIfNull(ui); - return S_CURRENT_SCOPE.Enter(ui); - } -} - /// /// Provides script-friendly retained-mode UI operations. /// @@ -47,14 +16,16 @@ public static class UI /// /// The validated ui context handle that represents the completed operation. /// - public static UiContextHandle CreateContext(UiContextOptions options) => UiExecutionContext.current.CreateContext(options); + public static UIContextHandle CreateContext(UIContextOptions options) => UIExecutionContext.current.CreateContext(options); + /// /// Destroys one UI context and all owned documents. /// /// /// The context that supplies state and services for this operation. /// - public static void DestroyContext(UiContextHandle context) => UiExecutionContext.current.DestroyContext(context); + public static void DestroyContext(UIContextHandle context) => UIExecutionContext.current.DestroyContext(context); + /// /// Changes one context's pixel dimensions and density. /// @@ -71,12 +42,12 @@ public static class UI /// The density consumed by set viewport; ownership remains with the caller unless explicitly stated otherwise. /// public static void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density = 1f - ) - => UiExecutionContext.current.SetViewport(context, width, height, density); + ) => UIExecutionContext.current.SetViewport(context, width, height, density); + /// /// Loads one explicitly tagged in-memory document. /// @@ -89,11 +60,11 @@ public static void SetViewport( /// /// The validated ui document handle that represents the completed operation. /// - public static UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source - ) - => UiExecutionContext.current.LoadDocument(context, source); + public static UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source + ) => UIExecutionContext.current.LoadDocument(context, source); + /// /// Loads one imported document compatible with the selected backend. /// @@ -106,11 +77,11 @@ UiDocumentSource source /// /// The validated ui document handle that represents the completed operation. /// - public static UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentAsset document - ) - => UiExecutionContext.current.LoadDocument(context, document); + public static UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentAsset document + ) => UIExecutionContext.current.LoadDocument(context, document); + /// /// Shows one document. /// @@ -121,10 +92,10 @@ UiDocumentAsset document /// The document consumed by show document; ownership remains with the caller unless explicitly stated otherwise. /// public static void ShowDocument( - UiContextHandle context, - UiDocumentHandle document - ) - => UiExecutionContext.current.ShowDocument(context, document); + UIContextHandle context, + UIDocumentHandle document + ) => UIExecutionContext.current.ShowDocument(context, document); + /// /// Hides one document. /// @@ -135,10 +106,10 @@ UiDocumentHandle document /// The document consumed by hide document; ownership remains with the caller unless explicitly stated otherwise. /// public static void HideDocument( - UiContextHandle context, - UiDocumentHandle document - ) - => UiExecutionContext.current.HideDocument(context, document); + UIContextHandle context, + UIDocumentHandle document + ) => UIExecutionContext.current.HideDocument(context, document); + /// /// Closes one document. /// @@ -149,10 +120,10 @@ UiDocumentHandle document /// The document consumed by close document; ownership remains with the caller unless explicitly stated otherwise. /// public static void CloseDocument( - UiContextHandle context, - UiDocumentHandle document - ) - => UiExecutionContext.current.CloseDocument(context, document); + UIContextHandle context, + UIDocumentHandle document + ) => UIExecutionContext.current.CloseDocument(context, document); + /// /// Replaces an element's children with plain Unicode text. /// @@ -162,7 +133,7 @@ UiDocumentHandle document /// /// The document consumed by set text; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set text operation. /// /// @@ -172,12 +143,12 @@ UiDocumentHandle document /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text - ) - => UiExecutionContext.current.SetText(context, document, elementId, text); + ) => UIExecutionContext.current.SetText(context, document, elementID, text); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -187,7 +158,7 @@ string text /// /// The document consumed by set content; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set content operation. /// /// @@ -197,12 +168,12 @@ string text /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment fragment - ) - => UiExecutionContext.current.SetContent(context, document, elementId, fragment); + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment fragment + ) => UIExecutionContext.current.SetContent(context, document, elementID, fragment); + /// /// Sets one element attribute. /// @@ -212,7 +183,7 @@ UiDocumentFragment fragment /// /// The document consumed by set attribute; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set attribute operation. /// /// @@ -225,13 +196,13 @@ UiDocumentFragment fragment /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value - ) - => UiExecutionContext.current.SetAttribute(context, document, elementId, name, value); + ) => UIExecutionContext.current.SetAttribute(context, document, elementID, name, value); + /// /// Activates or deactivates one element class. /// @@ -241,7 +212,7 @@ string value /// /// The document consumed by set class; ownership remains with the caller unless explicitly stated otherwise. /// - /// + /// /// The element id text validated by the set class operation. /// /// @@ -254,13 +225,13 @@ string value /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active - ) - => UiExecutionContext.current.SetClass(context, document, elementId, className, active); + ) => UIExecutionContext.current.SetClass(context, document, elementID, className, active); + /// /// Registers one named RGBA8 texture source. /// @@ -274,18 +245,19 @@ bool active /// The texture consumed by register texture; ownership remains with the caller unless explicitly stated otherwise. /// public static void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture - ) - => UiExecutionContext.current.RegisterTexture(context, source, texture); + UITextureData texture + ) => UIExecutionContext.current.RegisterTexture(context, source, texture); + /// /// Processes current-frame input and advances one context. /// /// /// The context that supplies state and services for this operation. /// - public static void Update(UiContextHandle context) => UiExecutionContext.current.Update(context); + public static void Update(UIContextHandle context) => UIExecutionContext.current.Update(context); + /// /// Advances one context with explicitly routed viewport-local input. /// @@ -296,9 +268,10 @@ UiTextureData texture /// The input consumed by update; ownership remains with the caller unless explicitly stated otherwise. /// public static void Update( - UiContextHandle context, - UiInputSnapshot input - ) => UiExecutionContext.current.Update(context, input); + UIContextHandle context, + UIInputSnapshot input + ) => UIExecutionContext.current.Update(context, input); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -308,7 +281,8 @@ UiInputSnapshot input /// /// The validated ui render frame that represents the completed operation. /// - public static UiRenderFrame Render(UiContextHandle context) => UiExecutionContext.current.Render(context); + public static UIRenderFrame Render(UIContextHandle context) => UIExecutionContext.current.Render(context); + /// /// Drains document events queued by preceding updates. /// @@ -318,5 +292,5 @@ UiInputSnapshot input /// /// An immutable snapshot of the values selected by the operation. /// - public static IReadOnlyList DrainEvents(UiContextHandle context) => UiExecutionContext.current.DrainEvents(context); + public static IReadOnlyList DrainEvents(UIContextHandle context) => UIExecutionContext.current.DrainEvents(context); } diff --git a/src/services/ui/Inno.UI/UiBackendCapabilities.cs b/src/services/ui/Inno.UI/UIBackendCapabilities.cs similarity index 59% rename from src/services/ui/Inno.UI/UiBackendCapabilities.cs rename to src/services/ui/Inno.UI/UIBackendCapabilities.cs index 6205c01ae..afc67e1d3 100644 --- a/src/services/ui/Inno.UI/UiBackendCapabilities.cs +++ b/src/services/ui/Inno.UI/UIBackendCapabilities.cs @@ -8,9 +8,9 @@ namespace Inno.UI; /// /// Describes optional behavior implemented by one UI backend generation. /// -public sealed class UiBackendCapabilities +public sealed class UIBackendCapabilities { - private readonly IReadOnlyList m_documentLanguages; + private readonly IReadOnlyList m_documentLanguages; /// /// Creates an immutable capability description. @@ -21,22 +21,24 @@ public sealed class UiBackendCapabilities /// /// Whether nonzero font collection face indices can be selected. /// - public UiBackendCapabilities( - IEnumerable documentLanguages, + public UIBackendCapabilities( + IEnumerable documentLanguages, bool supportsFontCollectionFaces ) { ArgumentNullException.ThrowIfNull(documentLanguages); - UiDocumentLanguageId[] languages = documentLanguages.Distinct().ToArray(); + UIDocumentLanguageID[] languages = documentLanguages.Distinct().ToArray(); if (languages.Length == 0 || languages.Any(static language => !language.isValid)) + { throw new ArgumentException("A UI backend must declare at least one assigned document language.", nameof(documentLanguages)); - m_documentLanguages = new ReadOnlyCollection(languages); + } + m_documentLanguages = new ReadOnlyCollection(languages); this.supportsFontCollectionFaces = supportsFontCollectionFaces; } /// /// Gets source languages accepted by the backend. /// - public IReadOnlyList documentLanguages => m_documentLanguages; + public IReadOnlyList documentLanguages => m_documentLanguages; /// /// Gets whether the backend can select nonzero faces from a font collection. @@ -52,37 +54,16 @@ bool supportsFontCollectionFaces /// /// True when the language is registered by this backend. /// - public bool Supports(UiDocumentLanguageId language) => m_documentLanguages.Contains(language); + public bool Supports(UIDocumentLanguageID language) => m_documentLanguages.Contains(language); } /// /// Identifies an optional backend behavior requested by a caller. /// -public enum UiBackendCapability +public enum UIBackendCapability { /// /// Selecting an explicit face from a font collection. /// FontCollectionFaceSelection } - -/// -/// Reports that the selected backend cannot perform an explicitly requested optional operation. -/// -public sealed class UiCapabilityUnavailableException : NotSupportedException -{ - /// - /// Creates a capability failure without naming a concrete implementation. - /// - /// - /// Unavailable neutral capability. - /// - public UiCapabilityUnavailableException(UiBackendCapability capability) - : base($"The selected UI backend does not support capability '{capability}'.") - => this.capability = capability; - - /// - /// Gets the unavailable capability. - /// - public UiBackendCapability capability { get; } -} diff --git a/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs b/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs new file mode 100644 index 000000000..effc75fef --- /dev/null +++ b/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.UI; + +/// +/// Reports that the selected backend cannot perform an explicitly requested optional operation. +/// +public sealed class UICapabilityUnavailableException : NotSupportedException +{ + /// + /// Creates a capability failure without naming a concrete implementation. + /// + /// + /// Unavailable neutral capability. + /// + public UICapabilityUnavailableException(UIBackendCapability capability) + : base($"The selected UI backend does not support capability '{capability}'.") + { + this.capability = capability; + } + + /// + /// Gets the unavailable capability. + /// + public UIBackendCapability capability { get; } +} diff --git a/src/services/ui/Inno.UI/UIClipRectangle.cs b/src/services/ui/Inno.UI/UIClipRectangle.cs new file mode 100644 index 000000000..66f37404e --- /dev/null +++ b/src/services/ui/Inno.UI/UIClipRectangle.cs @@ -0,0 +1,23 @@ +namespace Inno.UI; + +/// +/// Defines an integer clipping rectangle in UI surface coordinates. +/// +/// +/// The horizontal or first component. +/// +/// +/// The vertical or second component. +/// +/// +/// The width in logical units or pixels required by this operation. +/// +/// +/// The height in logical units or pixels required by this operation. +/// +public readonly record struct UIClipRectangle( + int x, + int y, + int width, + int height +); diff --git a/src/services/ui/Inno.UI/UIContextHandle.cs b/src/services/ui/Inno.UI/UIContextHandle.cs new file mode 100644 index 000000000..00fbb8783 --- /dev/null +++ b/src/services/ui/Inno.UI/UIContextHandle.cs @@ -0,0 +1,15 @@ +namespace Inno.UI; + +/// +/// Identifies one UI context owned by the active UI service generation. +/// +/// +/// The concrete value read or transformed by this operation. +/// +public readonly record struct UIContextHandle(ulong value) +{ + /// + /// Gets whether this handle identifies a live context candidate. + /// + public bool isValid => value != 0; +} diff --git a/src/services/ui/Inno.UI/UIContextOptions.cs b/src/services/ui/Inno.UI/UIContextOptions.cs new file mode 100644 index 000000000..d9e81517d --- /dev/null +++ b/src/services/ui/Inno.UI/UIContextOptions.cs @@ -0,0 +1,63 @@ +using System; + +namespace Inno.UI; + +/// +/// Defines one independent UI layout and interaction surface. +/// +public readonly record struct UIContextOptions +{ + /// + /// Creates validated context options. + /// + /// + /// A non-empty diagnostic context name. + /// + /// + /// The positive initial width in pixels. + /// + /// + /// The positive initial height in pixels. + /// + /// + /// The positive density-independent pixel ratio. + /// + public UIContextOptions( + string name, + int width, + int height, + float density = 1f + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (!float.IsFinite(density) || density <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(density)); + } + this.name = name.Trim(); + this.width = width; + this.height = height; + this.density = density; + } + + /// + /// Gets the diagnostic context name. + /// + public string name { get; } + + /// + /// Gets the initial width in pixels. + /// + public int width { get; } + + /// + /// Gets the initial height in pixels. + /// + public int height { get; } + + /// + /// Gets the density-independent pixel ratio. + /// + public float density { get; } +} diff --git a/src/services/ui/Inno.UI/UiDocumentAsset.cs b/src/services/ui/Inno.UI/UIDocumentAsset.cs similarity index 71% rename from src/services/ui/Inno.UI/UiDocumentAsset.cs rename to src/services/ui/Inno.UI/UIDocumentAsset.cs index 1a1419449..a65b3bd64 100644 --- a/src/services/ui/Inno.UI/UiDocumentAsset.cs +++ b/src/services/ui/Inno.UI/UIDocumentAsset.cs @@ -1,44 +1,44 @@ using System; -using System.IO; -using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; -using Inno.Text; - +using System.IO; +using System.Text; using Inno.Assets; using Inno.Extensibility.Types; +using Inno.Text; namespace Inno.UI; /// /// Represents one imported, language-tagged UI document source. /// -[StableTypeId("8b34bafb-f34a-4c19-9853-282485c40b78")] -public sealed class UiDocumentAsset : AssetObject +[StableTypeID("8b34bafb-f34a-4c19-9853-282485c40b78")] +public sealed class UIDocumentAsset : AssetObject { - private const uint C_PAYLOAD_MAGIC = 0x44495549; - private UiDocumentSource? m_source; - private IReadOnlyList m_fonts = []; - private string m_implementationId = string.Empty; + private const uint C_PAYLOAD_MAGIC = 0x4449_5549; + private UIDocumentSource? m_source; + private IReadOnlyList m_fonts = []; + private string m_implementationID = string.Empty; /// /// Gets the frozen source, or null before runtime content is loaded. /// - public UiDocumentSource? source => m_source; + public UIDocumentSource? source => m_source; + /// /// Gets font dependencies declared by this document. /// - public IReadOnlyList fonts => m_fonts; + public IReadOnlyList fonts => m_fonts; /// /// Gets the exact backend implementation selected when the source was imported. /// - public string implementationId => m_implementationId; + public string implementationID => m_implementationID; /// /// Encodes an importer-owned runtime payload without exposing an implementation-specific format. /// - /// + /// /// Stable backend implementation identity. /// /// @@ -51,29 +51,31 @@ public sealed class UiDocumentAsset : AssetObject /// Complete deterministic runtime payload bytes. /// public static byte[] CreateRuntimePayload( - string implementationId, - UiDocumentSource source, - IReadOnlyList? fonts = null + string implementationID, + UIDocumentSource source, + IReadOnlyList? fonts = null ) { - ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); ArgumentNullException.ThrowIfNull(source); using var stream = new MemoryStream(); using (var writer = new BinaryWriter(stream, new UTF8Encoding(false, true), leaveOpen: true)) { writer.Write(C_PAYLOAD_MAGIC); - writer.Write(implementationId); + writer.Write(implementationID); writer.Write(source.language.value); writer.Write(source.sourceUri); writer.Write(source.text); writer.Write(fonts?.Count ?? 0); if (fonts is not null) - foreach (UiDocumentFontFace face in fonts) + { + foreach (UIDocumentFontFace face in fonts) { - writer.Write(face.assetId.ToByteArray()); + writer.Write(face.assetID.ToByteArray()); writer.Write(face.family); writer.Write((int)face.style); writer.Write(face.weight); } + } } return stream.ToArray(); } @@ -95,29 +97,43 @@ ReadOnlyMemory currentPayload { m_source = null; m_fonts = []; - m_implementationId = string.Empty; + m_implementationID = string.Empty; return; } using var stream = new MemoryStream(currentPayload.ToArray(), writable: false); using var reader = new BinaryReader(stream, new UTF8Encoding(false, true), leaveOpen: false); if (reader.ReadUInt32() != C_PAYLOAD_MAGIC) + { throw new InvalidDataException("The UI document runtime payload has an invalid header."); + } string implementation = reader.ReadString(); string language = reader.ReadString(); string sourceUri = reader.ReadString(); string text = reader.ReadString(); int count = reader.ReadInt32(); if (count is < 0 or > 256) + { throw new InvalidDataException("The UI document declares an invalid number of font faces."); - var fonts = new List(count); + } + var fonts = new List(count); for (int index = 0; index < count; index++) - fonts.Add(new UiDocumentFontFace(new Guid(reader.ReadBytes(16)), reader.ReadString(), - (TextFontStyle)reader.ReadInt32(), reader.ReadInt32())); + { + fonts.Add( + new UIDocumentFontFace( + new Guid(reader.ReadBytes(16)), + reader.ReadString(), + (TextFontStyle)reader.ReadInt32(), + reader.ReadInt32() + ) + ); + } if (stream.Position != stream.Length) + { throw new InvalidDataException("The UI document runtime payload contains trailing data."); + } ArgumentException.ThrowIfNullOrWhiteSpace(implementation); - m_implementationId = implementation; - m_source = new UiDocumentSource(new UiDocumentLanguageId(language), text, sourceUri); - m_fonts = new ReadOnlyCollection(fonts); + m_implementationID = implementation; + m_source = new UIDocumentSource(new UIDocumentLanguageID(language), text, sourceUri); + m_fonts = new ReadOnlyCollection(fonts); } } diff --git a/src/services/ui/Inno.UI/UiDocumentFontFace.cs b/src/services/ui/Inno.UI/UIDocumentFontFace.cs similarity index 82% rename from src/services/ui/Inno.UI/UiDocumentFontFace.cs rename to src/services/ui/Inno.UI/UIDocumentFontFace.cs index 10a0462d2..300c1697d 100644 --- a/src/services/ui/Inno.UI/UiDocumentFontFace.cs +++ b/src/services/ui/Inno.UI/UIDocumentFontFace.cs @@ -6,12 +6,12 @@ namespace Inno.UI; /// /// Identifies one imported font face owned by a single UI document. /// -public readonly record struct UiDocumentFontFace +public readonly record struct UIDocumentFontFace { /// /// Creates a font dependency with its document-private family. /// - /// + /// /// Persistent font asset identity. /// /// @@ -23,18 +23,22 @@ public readonly record struct UiDocumentFontFace /// /// Declared face weight. /// - public UiDocumentFontFace( - Guid assetId, + public UIDocumentFontFace( + Guid assetID, string family, TextFontStyle style, int weight ) { - if (assetId == Guid.Empty) - throw new ArgumentException("A font asset ID is required.", nameof(assetId)); + if (assetID == Guid.Empty) + { + throw new ArgumentException("A font asset ID is required.", nameof(assetID)); + } ArgumentException.ThrowIfNullOrWhiteSpace(family); if (weight is < 100 or > 1000) + { throw new ArgumentOutOfRangeException(nameof(weight)); - this.assetId = assetId; + } + this.assetID = assetID; this.family = family; this.style = style; this.weight = weight; @@ -43,15 +47,18 @@ int weight /// /// Gets the imported font asset identity. /// - public Guid assetId { get; } + public Guid assetID { get; } + /// /// Gets the family referenced by the document. /// public string family { get; } + /// /// Gets the declared style. /// public TextFontStyle style { get; } + /// /// Gets the declared weight. /// diff --git a/src/services/ui/Inno.UI/UIDocumentFragment.cs b/src/services/ui/Inno.UI/UIDocumentFragment.cs new file mode 100644 index 000000000..a66595a36 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentFragment.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains a language-tagged fragment for a backend-specific document mutation. +/// +public readonly record struct UIDocumentFragment +{ + /// + /// Creates a validated source fragment. + /// + /// + /// Explicit fragment language. + /// + /// + /// Complete fragment text. + /// + public UIDocumentFragment( + UIDocumentLanguageID language, + string text + ) { + if (!language.isValid) + { + throw new ArgumentException("A document fragment requires an assigned language.", nameof(language)); + } + ArgumentNullException.ThrowIfNull(text); + this.language = language; + this.text = text; + } + + /// + /// Gets the explicitly selected fragment language. + /// + public UIDocumentLanguageID language { get; } + + /// + /// Gets the complete fragment text. + /// + public string text { get; } +} diff --git a/src/services/ui/Inno.UI/UIDocumentHandle.cs b/src/services/ui/Inno.UI/UIDocumentHandle.cs new file mode 100644 index 000000000..23e780673 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentHandle.cs @@ -0,0 +1,15 @@ +namespace Inno.UI; + +/// +/// Identifies one document owned by a UI context. +/// +/// +/// The concrete value read or transformed by this operation. +/// +public readonly record struct UIDocumentHandle(ulong value) +{ + /// + /// Gets whether this handle identifies a live document candidate. + /// + public bool isValid => value != 0; +} diff --git a/src/services/ui/Inno.UI/UiIdentifiers.cs b/src/services/ui/Inno.UI/UIDocumentLanguageID.cs similarity index 88% rename from src/services/ui/Inno.UI/UiIdentifiers.cs rename to src/services/ui/Inno.UI/UIDocumentLanguageID.cs index 1ce02c63a..5feb7c6df 100644 --- a/src/services/ui/Inno.UI/UiIdentifiers.cs +++ b/src/services/ui/Inno.UI/UIDocumentLanguageID.cs @@ -5,7 +5,7 @@ namespace Inno.UI; /// /// Identifies a document source language independently from any UI backend implementation. /// -public readonly record struct UiDocumentLanguageId +public readonly record struct UIDocumentLanguageID { /// /// Creates a stable, ordinal language identifier. @@ -13,12 +13,16 @@ public readonly record struct UiDocumentLanguageId /// /// Provider-qualified nonempty identifier without whitespace. /// - public UiDocumentLanguageId(string value) + public UIDocumentLanguageID(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A UI document language identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -47,7 +51,7 @@ public UiDocumentLanguageId(string value) /// /// The concrete value read or transformed by this operation. /// -public readonly record struct UiMeshHandle(ulong value) +public readonly record struct UIMeshHandle(ulong value) { /// /// Gets whether the handle identifies a mesh. @@ -61,7 +65,7 @@ public readonly record struct UiMeshHandle(ulong value) /// /// The concrete value read or transformed by this operation. /// -public readonly record struct UiTextureHandle(ulong value) +public readonly record struct UITextureHandle(ulong value) { /// /// Gets whether the handle identifies a texture; an unassigned handle selects the renderer's white texture. diff --git a/src/services/ui/Inno.UI/UIDocumentSource.cs b/src/services/ui/Inno.UI/UIDocumentSource.cs new file mode 100644 index 000000000..f3b370565 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentSource.cs @@ -0,0 +1,52 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains immutable text in one explicitly selected UI document language. +/// +public sealed class UIDocumentSource +{ + /// + /// Creates a validated in-memory document source. + /// + /// + /// Explicit source language understood by a registered backend. + /// + /// + /// Complete immutable document text. + /// + /// + /// Virtual source address used only for diagnostics and relative dependency identity. + /// + public UIDocumentSource( + UIDocumentLanguageID language, + string text, + string sourceUri = "memory://ui-document" + ) { + if (!language.isValid) + { + throw new ArgumentException("A document source requires an assigned language.", nameof(language)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(text); + ArgumentException.ThrowIfNullOrWhiteSpace(sourceUri); + this.language = language; + this.text = text; + this.sourceUri = sourceUri; + } + + /// + /// Gets the explicitly selected source language. + /// + public UIDocumentLanguageID language { get; } + + /// + /// Gets the complete immutable source text. + /// + public string text { get; } + + /// + /// Gets the virtual source address. + /// + public string sourceUri { get; } +} diff --git a/src/services/ui/Inno.UI/UIDrawCommand.cs b/src/services/ui/Inno.UI/UIDrawCommand.cs new file mode 100644 index 000000000..a7530cf41 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDrawCommand.cs @@ -0,0 +1,23 @@ +namespace Inno.UI; + +/// +/// Describes one draw of a previously published mesh. +/// +/// +/// The ui mesh handle value used to initialize this instance. +/// +/// +/// The ui texture handle value used to initialize this instance. +/// +/// +/// The bool value used to initialize this instance. +/// +/// +/// The ui clip rectangle value used to initialize this instance. +/// +public readonly record struct UIDrawCommand( + UIMeshHandle mesh, + UITextureHandle texture, + bool scissorEnabled, + UIClipRectangle scissor +); diff --git a/src/services/ui/Inno.UI/UIEvent.cs b/src/services/ui/Inno.UI/UIEvent.cs new file mode 100644 index 000000000..1a3bd6e2b --- /dev/null +++ b/src/services/ui/Inno.UI/UIEvent.cs @@ -0,0 +1,83 @@ +using System; +using Inno.Core.Events; + +namespace Inno.UI; + +/// +/// Describes one queued document event after a context update. +/// +public sealed class UIEvent : Event +{ + /// + /// Creates a document event with its source document and target element. + /// + /// + /// The kind of document interaction. + /// + /// + /// The document that produced the event. + /// + /// + /// The target element identifier, which can be empty. + /// + public UIEvent( + UIEventType type, + UIDocumentHandle document, + string targetID + ) { + ArgumentNullException.ThrowIfNull(targetID); + this.type = type; + this.document = document; + this.targetID = targetID; + } + + /// + /// Gets the kind of document interaction. + /// + public UIEventType type { get; } + + /// + /// Gets the source document. + /// + public UIDocumentHandle document { get; } + + /// + /// Gets the target element identifier. + /// + public string targetID { get; } +} + +/// +/// Identifies one document event made visible to game code. +/// +public enum UIEventType +{ + /// + /// The target was clicked. + /// + Click, + /// + /// The target value changed. + /// + Change, + /// + /// A form was submitted. + /// + Submit, + /// + /// The target gained focus. + /// + Focus, + /// + /// The target lost focus. + /// + Blur, + /// + /// A pointer entered the target. + /// + MouseEnter, + /// + /// A pointer left the target. + /// + MouseLeave +} diff --git a/src/services/ui/Inno.UI/UIExecutionContext.cs b/src/services/ui/Inno.UI/UIExecutionContext.cs new file mode 100644 index 000000000..a135c5f97 --- /dev/null +++ b/src/services/ui/Inno.UI/UIExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.UI; + +/// +/// Binds one UI service to the current asynchronous execution context. +/// +public static class UIExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("ui"); + + /// + /// Gets the UI service bound to the current execution context. + /// + public static IUIService current => CURRENT_SCOPE.current; + + /// + /// Binds a UI service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned UI service. + /// + /// + /// The caller-owned binding scope. + /// + public static IDisposable EnterScope(IUIService ui) + { + ArgumentNullException.ThrowIfNull(ui); + return CURRENT_SCOPE.Enter(ui); + } +} diff --git a/src/services/ui/Inno.UI/UiFontRegistration.cs b/src/services/ui/Inno.UI/UIFontRegistration.cs similarity index 94% rename from src/services/ui/Inno.UI/UiFontRegistration.cs rename to src/services/ui/Inno.UI/UIFontRegistration.cs index 9aea57c91..e87bcec21 100644 --- a/src/services/ui/Inno.UI/UiFontRegistration.cs +++ b/src/services/ui/Inno.UI/UIFontRegistration.cs @@ -1,5 +1,4 @@ using System; - using Inno.Text; namespace Inno.UI; @@ -7,7 +6,7 @@ namespace Inno.UI; /// /// Describes one encoded font face registration across the neutral backend boundary. /// -public readonly record struct UiFontRegistration +public readonly record struct UIFontRegistration { /// /// Creates a validated synchronous font registration request. @@ -27,7 +26,7 @@ public readonly record struct UiFontRegistration /// /// CSS-compatible weight from 100 through 1000. /// - public UiFontRegistration( + public UIFontRegistration( ReadOnlyMemory data, int faceIndex, string family, @@ -35,11 +34,15 @@ public UiFontRegistration( int weight ) { if (data.IsEmpty) + { throw new ArgumentException("Font data cannot be empty.", nameof(data)); + } ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); ArgumentException.ThrowIfNullOrWhiteSpace(family); if (weight is < 100 or > 1000) + { throw new ArgumentOutOfRangeException(nameof(weight)); + } this.data = data; this.faceIndex = faceIndex; this.family = family.Trim(); @@ -51,18 +54,22 @@ int weight /// Gets encoded font bytes valid for the synchronous backend call. /// public ReadOnlyMemory data { get; } + /// /// Gets the zero-based collection face index. /// public int faceIndex { get; } + /// /// Gets the logical family. /// public string family { get; } + /// /// Gets the logical style. /// public TextFontStyle style { get; } + /// /// Gets the logical weight. /// diff --git a/src/services/ui/Inno.UI/UIInputSnapshot.cs b/src/services/ui/Inno.UI/UIInputSnapshot.cs new file mode 100644 index 000000000..99c4fe4de --- /dev/null +++ b/src/services/ui/Inno.UI/UIInputSnapshot.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Input; +using Inno.Core.Mathematics; + +namespace Inno.UI; + +/// +/// Carries one immutable input snapshot across the UI backend boundary. +/// +public sealed class UIInputSnapshot +{ + /// + /// Creates one backend-neutral UI input snapshot. + /// + /// + /// Pointer position in surface coordinates. + /// + /// + /// Pointer wheel movement. + /// + /// + /// Active keyboard modifiers. + /// + /// + /// Physical keys pressed this frame. + /// + /// + /// Physical keys released this frame. + /// + /// + /// Pointer buttons pressed this frame. + /// + /// + /// Pointer buttons released this frame. + /// + /// + /// Ordered Unicode text commits. + /// + public UIInputSnapshot( + Vector2 mousePosition, + Vector2 scrollDelta, + KeyModifier modifiers, + IReadOnlyCollection keysPressed, + IReadOnlyCollection keysReleased, + IReadOnlyCollection buttonsPressed, + IReadOnlyCollection buttonsReleased, + IReadOnlyList textInput + ) { + ArgumentNullException.ThrowIfNull(keysPressed); + ArgumentNullException.ThrowIfNull(keysReleased); + ArgumentNullException.ThrowIfNull(buttonsPressed); + ArgumentNullException.ThrowIfNull(buttonsReleased); + ArgumentNullException.ThrowIfNull(textInput); + this.mousePosition = mousePosition; + this.scrollDelta = scrollDelta; + this.modifiers = modifiers; + this.keysPressed = keysPressed; + this.keysReleased = keysReleased; + this.buttonsPressed = buttonsPressed; + this.buttonsReleased = buttonsReleased; + this.textInput = textInput; + } + + /// + /// Gets the pointer position. + /// + public Vector2 mousePosition { get; } + + /// + /// Gets pointer wheel movement. + /// + public Vector2 scrollDelta { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } + + /// + /// Gets physical keys pressed this frame. + /// + public IReadOnlyCollection keysPressed { get; } + + /// + /// Gets physical keys released this frame. + /// + public IReadOnlyCollection keysReleased { get; } + + /// + /// Gets pointer buttons pressed this frame. + /// + public IReadOnlyCollection buttonsPressed { get; } + + /// + /// Gets pointer buttons released this frame. + /// + public IReadOnlyCollection buttonsReleased { get; } + + /// + /// Gets ordered Unicode text commits. + /// + public IReadOnlyList textInput { get; } +} diff --git a/src/services/ui/Inno.UI/UIMeshUpdate.cs b/src/services/ui/Inno.UI/UIMeshUpdate.cs new file mode 100644 index 000000000..92c45b53f --- /dev/null +++ b/src/services/ui/Inno.UI/UIMeshUpdate.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI; + +/// +/// Publishes one immutable mesh generation to a rendering plugin. +/// +public sealed class UIMeshUpdate +{ + private readonly IReadOnlyList m_vertices; + private readonly IReadOnlyList m_indices; + + internal UIMeshUpdate( + UIMeshHandle mesh, + ulong revision, + UIVertex[] vertices, + uint[] indices + ) { + this.mesh = mesh; + this.revision = revision; + m_vertices = new ReadOnlyCollection(vertices); + m_indices = new ReadOnlyCollection(indices); + } + + /// + /// Gets the generation-scoped mesh handle. + /// + public UIMeshHandle mesh { get; } + + /// + /// Gets the monotonically increasing mesh content revision. + /// + public ulong revision { get; } + + /// + /// Gets immutable local-space vertices. + /// + public IReadOnlyList vertices => m_vertices; + + /// + /// Gets immutable triangle indices. + /// + public IReadOnlyList indices => m_indices; +} diff --git a/src/services/ui/Inno.UI/UIRenderFrame.cs b/src/services/ui/Inno.UI/UIRenderFrame.cs new file mode 100644 index 000000000..fde7fc63a --- /dev/null +++ b/src/services/ui/Inno.UI/UIRenderFrame.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI; + +/// +/// Contains incremental resource changes and ordered draw commands for one UI context. +/// +public sealed class UIRenderFrame +{ + private readonly IReadOnlyList m_meshUpdates; + private readonly IReadOnlyList m_releasedMeshes; + private readonly IReadOnlyList m_textureUpdates; + private readonly IReadOnlyList m_releasedTextures; + private readonly IReadOnlyList m_commands; + + internal UIRenderFrame( + UIMeshUpdate[] meshUpdates, + UIMeshHandle[] releasedMeshes, + UITextureUpdate[] textureUpdates, + UITextureHandle[] releasedTextures, + UIDrawCommand[] commands + ) { + m_meshUpdates = new ReadOnlyCollection(meshUpdates); + m_releasedMeshes = new ReadOnlyCollection(releasedMeshes); + m_textureUpdates = new ReadOnlyCollection(textureUpdates); + m_releasedTextures = new ReadOnlyCollection(releasedTextures); + m_commands = new ReadOnlyCollection(commands); + } + + /// + /// Gets an empty resource-delta frame. + /// + public static UIRenderFrame empty { get; } = new([], [], [], [], []); + + /// + /// Gets created or replaced mesh generations. + /// + public IReadOnlyList meshUpdates => m_meshUpdates; + + /// + /// Gets mesh generations that must be retired. + /// + public IReadOnlyList releasedMeshes => m_releasedMeshes; + + /// + /// Gets created or replaced texture generations. + /// + public IReadOnlyList textureUpdates => m_textureUpdates; + + /// + /// Gets texture generations that must be retired. + /// + public IReadOnlyList releasedTextures => m_releasedTextures; + + /// + /// Gets ordered draws referencing published resources. + /// + public IReadOnlyList commands => m_commands; + + /// + /// Creates a command-free frame that deterministically retires plugin-owned resources. + /// + /// + /// Assigned mesh handles to retire. + /// + /// + /// Assigned texture handles to retire. + /// + /// + /// An immutable retirement frame. + /// + public static UIRenderFrame CreateRetirement( + UIMeshHandle[] meshes, + UITextureHandle[] textures + ) { + ArgumentNullException.ThrowIfNull(meshes); + ArgumentNullException.ThrowIfNull(textures); + if (Array.Exists(meshes, static value => !value.isValid)) + { + throw new ArgumentException("Retirement meshes must be assigned.", nameof(meshes)); + } + if (Array.Exists(textures, static value => !value.isValid)) + { + throw new ArgumentException("Retirement textures must be assigned.", nameof(textures)); + } + return new([], (UIMeshHandle[])meshes.Clone(), [], (UITextureHandle[])textures.Clone(), []); + } +} diff --git a/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs b/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs new file mode 100644 index 000000000..fcceec845 --- /dev/null +++ b/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; + +namespace Inno.UI; + +/// +/// Builds one immutable backend-neutral frame while transferring ownership of update arrays. +/// +/// +/// This backend SPI is intentionally not exported to ordinary game scripts. +/// +public sealed class UIRenderFrameBuilder +{ + private readonly List m_meshUpdates = []; + private readonly List m_releasedMeshes = []; + private readonly List m_textureUpdates = []; + private readonly List m_releasedTextures = []; + private readonly List m_commands = []; + private bool m_built; + + /// + /// Adds one mesh update and takes exclusive ownership of both arrays. + /// + /// + /// Assigned mesh handle. + /// + /// + /// Positive content revision. + /// + /// + /// Owned vertex array; the caller must not mutate it afterward. + /// + /// + /// Owned index array; the caller must not mutate it afterward. + /// + public void AddMeshUpdate( + UIMeshHandle mesh, + ulong revision, + UIVertex[] vertices, + uint[] indices + ) { + EnsureMutable(); + if (!mesh.isValid) + { + throw new ArgumentException("A mesh update requires an assigned handle.", nameof(mesh)); + } + ArgumentOutOfRangeException.ThrowIfZero(revision); + ArgumentNullException.ThrowIfNull(vertices); + ArgumentNullException.ThrowIfNull(indices); + if (vertices.Length == 0 || indices.Length == 0) + { + throw new ArgumentException("A mesh update requires nonempty geometry."); + } + foreach (uint index in indices) + { + if (index >= vertices.Length) + { + throw new ArgumentException("A mesh index references a vertex outside the update.", nameof(indices)); + } + } + m_meshUpdates.Add(new UIMeshUpdate(mesh, revision, vertices, indices)); + } + + /// + /// Adds one mesh retirement. + /// + /// + /// Assigned mesh handle. + /// + public void AddReleasedMesh(UIMeshHandle mesh) + { + EnsureMutable(); + if (!mesh.isValid) + { + throw new ArgumentException("A released mesh requires an assigned handle.", nameof(mesh)); + } + m_releasedMeshes.Add(mesh); + } + + /// + /// Adds one texture update and takes exclusive ownership of its pixel array. + /// + /// + /// Assigned texture handle. + /// + /// + /// Positive content revision. + /// + /// + /// Positive pixel width. + /// + /// + /// Positive pixel height. + /// + /// + /// Owned tightly packed premultiplied RGBA8 pixels. + /// + public void AddTextureUpdate( + UITextureHandle texture, + ulong revision, + int width, + int height, + byte[] pixels + ) { + EnsureMutable(); + if (!texture.isValid) + { + throw new ArgumentException("A texture update requires an assigned handle.", nameof(texture)); + } + ArgumentOutOfRangeException.ThrowIfZero(revision); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentNullException.ThrowIfNull(pixels); + if (pixels.Length != checked(width * height * 4)) + { + throw new ArgumentException("Texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } + m_textureUpdates.Add(new UITextureUpdate(texture, revision, width, height, pixels)); + } + + /// + /// Adds one texture retirement. + /// + /// + /// Assigned texture handle. + /// + public void AddReleasedTexture(UITextureHandle texture) + { + EnsureMutable(); + if (!texture.isValid) + { + throw new ArgumentException("A released texture requires an assigned handle.", nameof(texture)); + } + m_releasedTextures.Add(texture); + } + + /// + /// Adds one ordered mesh draw. + /// + /// + /// Draw command referencing an assigned mesh. + /// + public void AddCommand(UIDrawCommand command) + { + EnsureMutable(); + if (!command.mesh.isValid) + { + throw new ArgumentException("A draw command requires an assigned mesh.", nameof(command)); + } + m_commands.Add(command); + } + + /// + /// Freezes the accumulated frame. The builder cannot be reused. + /// + /// + /// An immutable frame owning every supplied array. + /// + public UIRenderFrame Build() + { + EnsureMutable(); + m_built = true; + return new( + m_meshUpdates.ToArray(), + m_releasedMeshes.ToArray(), + m_textureUpdates.ToArray(), + m_releasedTextures.ToArray(), + m_commands.ToArray() + ); + } + + private void EnsureMutable() + { + if (m_built) + { + throw new InvalidOperationException("A UI render-frame builder can only build one frame."); + } + } +} diff --git a/src/services/ui/Inno.UI/UITextureData.cs b/src/services/ui/Inno.UI/UITextureData.cs new file mode 100644 index 000000000..14795d8f2 --- /dev/null +++ b/src/services/ui/Inno.UI/UITextureData.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains immutable RGBA8 texture pixels addressable by a document source name. +/// +public sealed class UITextureData +{ + private readonly byte[] m_pixels; + + /// + /// Creates a validated immutable texture. + /// + /// + /// The positive texture width. + /// + /// + /// The positive texture height. + /// + /// + /// Tightly packed RGBA8 pixels. + /// + public UITextureData( + int width, + int height, + ReadOnlySpan pixels + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (pixels.Length != checked(width * height * 4)) + { + throw new ArgumentException("UI texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } + this.width = width; + this.height = height; + m_pixels = pixels.ToArray(); + } + + /// + /// Gets the texture width. + /// + public int width { get; } + + /// + /// Gets the texture height. + /// + public int height { get; } + + /// + /// Gets the immutable RGBA8 pixels. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/ui/Inno.UI/UITextureUpdate.cs b/src/services/ui/Inno.UI/UITextureUpdate.cs new file mode 100644 index 000000000..ccbb3a821 --- /dev/null +++ b/src/services/ui/Inno.UI/UITextureUpdate.cs @@ -0,0 +1,50 @@ +using System; + +namespace Inno.UI; + +/// +/// Publishes one immutable premultiplied RGBA8 texture generation. +/// +public sealed class UITextureUpdate +{ + private readonly byte[] m_pixels; + + internal UITextureUpdate( + UITextureHandle texture, + ulong revision, + int width, + int height, + byte[] pixels + ) { + this.texture = texture; + this.revision = revision; + this.width = width; + this.height = height; + m_pixels = pixels; + } + + /// + /// Gets the generation-scoped texture handle. + /// + public UITextureHandle texture { get; } + + /// + /// Gets the monotonically increasing content revision. + /// + public ulong revision { get; } + + /// + /// Gets the texture width. + /// + public int width { get; } + + /// + /// Gets the texture height. + /// + public int height { get; } + + /// + /// Gets immutable tightly packed premultiplied RGBA8 pixels. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/ui/Inno.UI/UIVertex.cs b/src/services/ui/Inno.UI/UIVertex.cs new file mode 100644 index 000000000..eaed4ff97 --- /dev/null +++ b/src/services/ui/Inno.UI/UIVertex.cs @@ -0,0 +1,27 @@ +namespace Inno.UI; + +/// +/// Describes one vertex in backend-neutral UI draw geometry. +/// +/// +/// The horizontal or first component. +/// +/// +/// The vertical or second component. +/// +/// +/// The float value used to initialize this instance. +/// +/// +/// The concrete value read or transformed by this operation. +/// +/// +/// The uint value used to initialize this instance. +/// +public readonly record struct UIVertex( + float x, + float y, + float u, + float v, + uint color +); diff --git a/src/services/ui/Inno.UI/UiHandles.cs b/src/services/ui/Inno.UI/UiHandles.cs deleted file mode 100644 index 794ea4b19..000000000 --- a/src/services/ui/Inno.UI/UiHandles.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Inno.UI; - -/// -/// Identifies one UI context owned by the active UI service generation. -/// -/// -/// The concrete value read or transformed by this operation. -/// -public readonly record struct UiContextHandle(ulong value) -{ - /// - /// Gets whether this handle identifies a live context candidate. - /// - public bool isValid => value != 0; -} - -/// -/// Identifies one document owned by a UI context. -/// -/// -/// The concrete value read or transformed by this operation. -/// -public readonly record struct UiDocumentHandle(ulong value) -{ - /// - /// Gets whether this handle identifies a live document candidate. - /// - public bool isValid => value != 0; -} diff --git a/src/services/ui/Inno.UI/UiRendering.cs b/src/services/ui/Inno.UI/UiRendering.cs deleted file mode 100644 index ab68ec1f6..000000000 --- a/src/services/ui/Inno.UI/UiRendering.cs +++ /dev/null @@ -1,388 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace Inno.UI; - -/// -/// Describes one vertex in backend-neutral UI draw geometry. -/// -/// -/// The horizontal or first component. -/// -/// -/// The vertical or second component. -/// -/// -/// The float value used to initialize this instance. -/// -/// -/// The concrete value read or transformed by this operation. -/// -/// -/// The uint value used to initialize this instance. -/// -public readonly record struct UiVertex( - float x, - float y, - float u, - float v, - uint color -); - -/// -/// Defines an integer clipping rectangle in UI surface coordinates. -/// -/// -/// The horizontal or first component. -/// -/// -/// The vertical or second component. -/// -/// -/// The width in logical units or pixels required by this operation. -/// -/// -/// The height in logical units or pixels required by this operation. -/// -public readonly record struct UiClipRectangle( - int x, - int y, - int width, - int height -); - -/// -/// Publishes one immutable mesh generation to a rendering plugin. -/// -public sealed class UiMeshUpdate -{ - private readonly IReadOnlyList m_vertices; - private readonly IReadOnlyList m_indices; - - internal UiMeshUpdate( - UiMeshHandle mesh, - ulong revision, - UiVertex[] vertices, - uint[] indices - ) { - this.mesh = mesh; - this.revision = revision; - m_vertices = new ReadOnlyCollection(vertices); - m_indices = new ReadOnlyCollection(indices); - } - - /// - /// Gets the generation-scoped mesh handle. - /// - public UiMeshHandle mesh { get; } - /// - /// Gets the monotonically increasing mesh content revision. - /// - public ulong revision { get; } - /// - /// Gets immutable local-space vertices. - /// - public IReadOnlyList vertices => m_vertices; - /// - /// Gets immutable triangle indices. - /// - public IReadOnlyList indices => m_indices; -} - -/// -/// Publishes one immutable premultiplied RGBA8 texture generation. -/// -public sealed class UiTextureUpdate -{ - private readonly byte[] m_pixels; - - internal UiTextureUpdate( - UiTextureHandle texture, - ulong revision, - int width, - int height, - byte[] pixels - ) { - this.texture = texture; - this.revision = revision; - this.width = width; - this.height = height; - m_pixels = pixels; - } - - /// - /// Gets the generation-scoped texture handle. - /// - public UiTextureHandle texture { get; } - /// - /// Gets the monotonically increasing content revision. - /// - public ulong revision { get; } - /// - /// Gets the texture width. - /// - public int width { get; } - /// - /// Gets the texture height. - /// - public int height { get; } - /// - /// Gets immutable tightly packed premultiplied RGBA8 pixels. - /// - public ReadOnlyMemory pixels => m_pixels; -} - -/// -/// Describes one draw of a previously published mesh. -/// -/// -/// The ui mesh handle value used to initialize this instance. -/// -/// -/// The ui texture handle value used to initialize this instance. -/// -/// -/// The bool value used to initialize this instance. -/// -/// -/// The ui clip rectangle value used to initialize this instance. -/// -public readonly record struct UiDrawCommand( - UiMeshHandle mesh, - UiTextureHandle texture, - bool scissorEnabled, - UiClipRectangle scissor -); - -/// -/// Contains incremental resource changes and ordered draw commands for one UI context. -/// -public sealed class UiRenderFrame -{ - private readonly IReadOnlyList m_meshUpdates; - private readonly IReadOnlyList m_releasedMeshes; - private readonly IReadOnlyList m_textureUpdates; - private readonly IReadOnlyList m_releasedTextures; - private readonly IReadOnlyList m_commands; - - internal UiRenderFrame( - UiMeshUpdate[] meshUpdates, - UiMeshHandle[] releasedMeshes, - UiTextureUpdate[] textureUpdates, - UiTextureHandle[] releasedTextures, - UiDrawCommand[] commands - ) { - m_meshUpdates = new ReadOnlyCollection(meshUpdates); - m_releasedMeshes = new ReadOnlyCollection(releasedMeshes); - m_textureUpdates = new ReadOnlyCollection(textureUpdates); - m_releasedTextures = new ReadOnlyCollection(releasedTextures); - m_commands = new ReadOnlyCollection(commands); - } - - /// - /// Gets an empty resource-delta frame. - /// - public static UiRenderFrame empty { get; } = new([], [], [], [], []); - - /// - /// Creates a command-free frame that deterministically retires plugin-owned resources. - /// - /// - /// Assigned mesh handles to retire. - /// - /// - /// Assigned texture handles to retire. - /// - /// - /// An immutable retirement frame. - /// - public static UiRenderFrame CreateRetirement( - UiMeshHandle[] meshes, - UiTextureHandle[] textures - ) { - ArgumentNullException.ThrowIfNull(meshes); - ArgumentNullException.ThrowIfNull(textures); - if (Array.Exists(meshes, static value => !value.isValid)) - throw new ArgumentException("Retirement meshes must be assigned.", nameof(meshes)); - if (Array.Exists(textures, static value => !value.isValid)) - throw new ArgumentException("Retirement textures must be assigned.", nameof(textures)); - return new([], (UiMeshHandle[])meshes.Clone(), [], (UiTextureHandle[])textures.Clone(), []); - } - /// - /// Gets created or replaced mesh generations. - /// - public IReadOnlyList meshUpdates => m_meshUpdates; - /// - /// Gets mesh generations that must be retired. - /// - public IReadOnlyList releasedMeshes => m_releasedMeshes; - /// - /// Gets created or replaced texture generations. - /// - public IReadOnlyList textureUpdates => m_textureUpdates; - /// - /// Gets texture generations that must be retired. - /// - public IReadOnlyList releasedTextures => m_releasedTextures; - /// - /// Gets ordered draws referencing published resources. - /// - public IReadOnlyList commands => m_commands; -} - -/// -/// Builds one immutable backend-neutral frame while transferring ownership of update arrays. -/// -/// -/// This backend SPI is intentionally not exported to ordinary game scripts. -/// -public sealed class UiRenderFrameBuilder -{ - private readonly List m_meshUpdates = []; - private readonly List m_releasedMeshes = []; - private readonly List m_textureUpdates = []; - private readonly List m_releasedTextures = []; - private readonly List m_commands = []; - private bool m_built; - - /// - /// Adds one mesh update and takes exclusive ownership of both arrays. - /// - /// - /// Assigned mesh handle. - /// - /// - /// Positive content revision. - /// - /// - /// Owned vertex array; the caller must not mutate it afterward. - /// - /// - /// Owned index array; the caller must not mutate it afterward. - /// - public void AddMeshUpdate( - UiMeshHandle mesh, - ulong revision, - UiVertex[] vertices, - uint[] indices - ) { - EnsureMutable(); - if (!mesh.isValid) - throw new ArgumentException("A mesh update requires an assigned handle.", nameof(mesh)); - if (revision == 0) - throw new ArgumentOutOfRangeException(nameof(revision)); - ArgumentNullException.ThrowIfNull(vertices); - ArgumentNullException.ThrowIfNull(indices); - if (vertices.Length == 0 || indices.Length == 0) - throw new ArgumentException("A mesh update requires nonempty geometry."); - foreach (uint index in indices) - if (index >= vertices.Length) - throw new ArgumentException("A mesh index references a vertex outside the update.", nameof(indices)); - m_meshUpdates.Add(new(mesh, revision, vertices, indices)); - } - - /// - /// Adds one mesh retirement. - /// - /// - /// Assigned mesh handle. - /// - public void AddReleasedMesh(UiMeshHandle mesh) - { - EnsureMutable(); - if (!mesh.isValid) - throw new ArgumentException("A released mesh requires an assigned handle.", nameof(mesh)); - m_releasedMeshes.Add(mesh); - } - - /// - /// Adds one texture update and takes exclusive ownership of its pixel array. - /// - /// - /// Assigned texture handle. - /// - /// - /// Positive content revision. - /// - /// - /// Positive pixel width. - /// - /// - /// Positive pixel height. - /// - /// - /// Owned tightly packed premultiplied RGBA8 pixels. - /// - public void AddTextureUpdate( - UiTextureHandle texture, - ulong revision, - int width, - int height, - byte[] pixels - ) { - EnsureMutable(); - if (!texture.isValid) - throw new ArgumentException("A texture update requires an assigned handle.", nameof(texture)); - if (revision == 0) - throw new ArgumentOutOfRangeException(nameof(revision)); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentNullException.ThrowIfNull(pixels); - if (pixels.Length != checked(width * height * 4)) - throw new ArgumentException("Texture pixels must be tightly packed RGBA8.", nameof(pixels)); - m_textureUpdates.Add(new(texture, revision, width, height, pixels)); - } - - /// - /// Adds one texture retirement. - /// - /// - /// Assigned texture handle. - /// - public void AddReleasedTexture(UiTextureHandle texture) - { - EnsureMutable(); - if (!texture.isValid) - throw new ArgumentException("A released texture requires an assigned handle.", nameof(texture)); - m_releasedTextures.Add(texture); - } - - /// - /// Adds one ordered mesh draw. - /// - /// - /// Draw command referencing an assigned mesh. - /// - public void AddCommand(UiDrawCommand command) - { - EnsureMutable(); - if (!command.mesh.isValid) - throw new ArgumentException("A draw command requires an assigned mesh.", nameof(command)); - m_commands.Add(command); - } - - /// - /// Freezes the accumulated frame. The builder cannot be reused. - /// - /// - /// An immutable frame owning every supplied array. - /// - public UiRenderFrame Build() - { - EnsureMutable(); - m_built = true; - return new( - m_meshUpdates.ToArray(), - m_releasedMeshes.ToArray(), - m_textureUpdates.ToArray(), - m_releasedTextures.ToArray(), - m_commands.ToArray()); - } - - private void EnsureMutable() - { - if (m_built) - throw new InvalidOperationException("A UI render-frame builder can only build one frame."); - } -} diff --git a/src/services/ui/Inno.UI/UiTypes.cs b/src/services/ui/Inno.UI/UiTypes.cs deleted file mode 100644 index fa66e9ac4..000000000 --- a/src/services/ui/Inno.UI/UiTypes.cs +++ /dev/null @@ -1,353 +0,0 @@ -using System; -using System.Collections.Generic; - -using Inno.Core.Input; -using Inno.Core.Mathematics; - -namespace Inno.UI; - -/// -/// Defines one independent UI layout and interaction surface. -/// -public readonly record struct UiContextOptions -{ - /// - /// Creates validated context options. - /// - /// - /// A non-empty diagnostic context name. - /// - /// - /// The positive initial width in pixels. - /// - /// - /// The positive initial height in pixels. - /// - /// - /// The positive density-independent pixel ratio. - /// - public UiContextOptions( - string name, - int width, - int height, - float density = 1f - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - if (!float.IsFinite(density) || density <= 0f) - throw new ArgumentOutOfRangeException(nameof(density)); - this.name = name.Trim(); - this.width = width; - this.height = height; - this.density = density; - } - - /// - /// Gets the diagnostic context name. - /// - public string name { get; } - /// - /// Gets the initial width in pixels. - /// - public int width { get; } - /// - /// Gets the initial height in pixels. - /// - public int height { get; } - /// - /// Gets the density-independent pixel ratio. - /// - public float density { get; } -} - -/// -/// Contains immutable text in one explicitly selected UI document language. -/// -public sealed class UiDocumentSource -{ - /// - /// Creates a validated in-memory document source. - /// - /// - /// Explicit source language understood by a registered backend. - /// - /// - /// Complete immutable document text. - /// - /// - /// Virtual source address used only for diagnostics and relative dependency identity. - /// - public UiDocumentSource( - UiDocumentLanguageId language, - string text, - string sourceUri = "memory://ui-document" - ) { - if (!language.isValid) - throw new ArgumentException("A document source requires an assigned language.", nameof(language)); - ArgumentException.ThrowIfNullOrWhiteSpace(text); - ArgumentException.ThrowIfNullOrWhiteSpace(sourceUri); - this.language = language; - this.text = text; - this.sourceUri = sourceUri; - } - - /// - /// Gets the explicitly selected source language. - /// - public UiDocumentLanguageId language { get; } - /// - /// Gets the complete immutable source text. - /// - public string text { get; } - /// - /// Gets the virtual source address. - /// - public string sourceUri { get; } -} - -/// -/// Contains a language-tagged fragment for a backend-specific document mutation. -/// -public readonly record struct UiDocumentFragment -{ - /// - /// Creates a validated source fragment. - /// - /// - /// Explicit fragment language. - /// - /// - /// Complete fragment text. - /// - public UiDocumentFragment( - UiDocumentLanguageId language, - string text - ) { - if (!language.isValid) - throw new ArgumentException("A document fragment requires an assigned language.", nameof(language)); - ArgumentNullException.ThrowIfNull(text); - this.language = language; - this.text = text; - } - - /// - /// Gets the explicitly selected fragment language. - /// - public UiDocumentLanguageId language { get; } - /// - /// Gets the complete fragment text. - /// - public string text { get; } -} - -/// -/// Contains immutable RGBA8 texture pixels addressable by a document source name. -/// -public sealed class UiTextureData -{ - private readonly byte[] m_pixels; - - /// - /// Creates a validated immutable texture. - /// - /// - /// The positive texture width. - /// - /// - /// The positive texture height. - /// - /// - /// Tightly packed RGBA8 pixels. - /// - public UiTextureData( - int width, - int height, - ReadOnlySpan pixels - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - if (pixels.Length != checked(width * height * 4)) - throw new ArgumentException("UI texture pixels must be tightly packed RGBA8.", nameof(pixels)); - this.width = width; - this.height = height; - m_pixels = pixels.ToArray(); - } - - /// - /// Gets the texture width. - /// - public int width { get; } - /// - /// Gets the texture height. - /// - public int height { get; } - /// - /// Gets the immutable RGBA8 pixels. - /// - public ReadOnlyMemory pixels => m_pixels; -} - -/// -/// Identifies one document event made visible to game code. -/// -public enum UiEventType -{ - /// - /// The target was clicked. - /// - Click, - /// - /// The target value changed. - /// - Change, - /// - /// A form was submitted. - /// - Submit, - /// - /// The target gained focus. - /// - Focus, - /// - /// The target lost focus. - /// - Blur, - /// - /// A pointer entered the target. - /// - MouseEnter, - /// - /// A pointer left the target. - /// - MouseLeave -} - -/// -/// Describes one queued document event after a context update. -/// -public sealed class UiEvent : Inno.Core.Events.Event -{ - /// - /// Creates a document event with its source document and target element. - /// - /// - /// The kind of document interaction. - /// - /// - /// The document that produced the event. - /// - /// - /// The target element identifier, which can be empty. - /// - public UiEvent( - UiEventType type, - UiDocumentHandle document, - string targetId - ) { - this.type = type; - this.document = document; - this.targetId = targetId ?? throw new ArgumentNullException(nameof(targetId)); - } - - /// - /// Gets the kind of document interaction. - /// - public UiEventType type { get; } - - /// - /// Gets the source document. - /// - public UiDocumentHandle document { get; } - - /// - /// Gets the target element identifier. - /// - public string targetId { get; } -} - -/// -/// Carries one immutable input snapshot across the UI backend boundary. -/// -public sealed class UiInputSnapshot -{ - /// - /// Creates one backend-neutral UI input snapshot. - /// - /// - /// Pointer position in surface coordinates. - /// - /// - /// Pointer wheel movement. - /// - /// - /// Active keyboard modifiers. - /// - /// - /// Physical keys pressed this frame. - /// - /// - /// Physical keys released this frame. - /// - /// - /// Pointer buttons pressed this frame. - /// - /// - /// Pointer buttons released this frame. - /// - /// - /// Ordered Unicode text commits. - /// - public UiInputSnapshot( - Vector2 mousePosition, - Vector2 scrollDelta, - KeyModifier modifiers, - IReadOnlyCollection keysPressed, - IReadOnlyCollection keysReleased, - IReadOnlyCollection buttonsPressed, - IReadOnlyCollection buttonsReleased, - IReadOnlyList textInput - ) { - this.mousePosition = mousePosition; - this.scrollDelta = scrollDelta; - this.modifiers = modifiers; - this.keysPressed = keysPressed ?? throw new ArgumentNullException(nameof(keysPressed)); - this.keysReleased = keysReleased ?? throw new ArgumentNullException(nameof(keysReleased)); - this.buttonsPressed = buttonsPressed ?? throw new ArgumentNullException(nameof(buttonsPressed)); - this.buttonsReleased = buttonsReleased ?? throw new ArgumentNullException(nameof(buttonsReleased)); - this.textInput = textInput ?? throw new ArgumentNullException(nameof(textInput)); - } - - /// - /// Gets the pointer position. - /// - public Vector2 mousePosition { get; } - /// - /// Gets pointer wheel movement. - /// - public Vector2 scrollDelta { get; } - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } - /// - /// Gets physical keys pressed this frame. - /// - public IReadOnlyCollection keysPressed { get; } - /// - /// Gets physical keys released this frame. - /// - public IReadOnlyCollection keysReleased { get; } - /// - /// Gets pointer buttons pressed this frame. - /// - public IReadOnlyCollection buttonsPressed { get; } - /// - /// Gets pointer buttons released this frame. - /// - public IReadOnlyCollection buttonsReleased { get; } - /// - /// Gets ordered Unicode text commits. - /// - public IReadOnlyList textInput { get; } -} diff --git a/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs b/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs index 7b025a08f..6d2509075 100644 --- a/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs +++ b/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Animation.Runtime; using Inno.Core.Diagnostics; using Inno.Core.Identity; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Animation.Tests; @@ -20,7 +20,9 @@ public void ProviderIsDiscoveredAndMissingIssuesRecoverOnTheNextBatch() string cache = Path.Combine(Path.GetTempPath(), "InnoAnimationBindings", Guid.NewGuid().ToString("N")); try { - using var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AnimationBindingTests).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AnimationBindingTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var reporter = new Reporter(); using var bindings = new AnimationBindingRuntime(types, reporter); @@ -28,26 +30,38 @@ public void ProviderIsDiscoveredAndMissingIssuesRecoverOnTheNextBatch() var destination = new Destination(); owner.Register(destination); var target = new AnimationTarget(destination.identity); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 3f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingID("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 3f))] + ); Assert.Equal(3f, destination.value); Assert.Empty(reporter.issues); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.missing"), new AnimationValue(AnimationValueKind.Scalar, 3f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingID("test.missing"), new AnimationValue(AnimationValueKind.Scalar, 3f))] + ); Assert.Equal("animation.binding.unavailable", Assert.Single(reporter.issues).code); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 4f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingID("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 4f))] + ); Assert.Empty(reporter.issues); types.Rebuild(); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 5f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingID("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 5f))] + ); Assert.Equal(5f, destination.value); owner.Unregister(destination); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 6f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingID("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 6f))] + ); Assert.Single(reporter.issues); - bindings.Apply([new AnimationSample(AnimationTarget.samplingOnly, new AnimationBindingId("test.missing"), default)]); + bindings.Apply([new AnimationSample(AnimationTarget.samplingOnly, new AnimationBindingID("test.missing"), default)]); Assert.Empty(reporter.issues); } finally { if (Directory.Exists(cache)) + { Directory.Delete(cache, true); + } } } @@ -59,11 +73,15 @@ public sealed class Destination : IdentityObject [AnimationBindingProvider("test.animation.scalar", "test.scalar", AnimationValueKind.Scalar)] public sealed class ScalarProvider : AnimationBindingProvider { - public override bool TryApply(AnimationTarget target, AnimationValue value) - { + public override bool TryApply( + AnimationTarget target, + AnimationValue value + ) { Destination? destination = target.Resolve(); if (destination is null) + { return false; + } destination.value = value.x; return true; } @@ -72,8 +90,15 @@ public override bool TryApply(AnimationTarget target, AnimationValue value) private sealed class Reporter : IDiagnosticReporter { internal Diagnostic[] issues = []; + public void Publish(Diagnostic diagnostic) => issues = [diagnostic]; - public void Resolve(string code, string? semanticId = null, Guid? objectId = null) => issues = []; + + public void Resolve( + string code, + string? semanticID = null, + Guid? objectID = null + ) => issues = []; + public void Replace(IEnumerable diagnostics) => issues = diagnostics.ToArray(); } } diff --git a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs index c4e3431ff..b9b3b3380 100644 --- a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs +++ b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; - +using Xunit; using Inno.Animation.Runtime; using Inno.Core.Events; using Inno.Core.Identity; -using Xunit; namespace Inno.Animation.Tests; @@ -92,7 +91,7 @@ public void MarkerIsQueuedAndNaturalCompletionInvalidatesPlayback() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var markers = new List(); + List markers = []; using IDisposable subscription = hub.Listen(markers.Add); using var runtime = new AnimationRuntime(dispatcher, new RecordingSink()); AnimationPlaybackHandle handle = runtime.Play(CreateClip(), AnimationTarget.samplingOnly); @@ -101,7 +100,7 @@ public void MarkerIsQueuedAndNaturalCompletionInvalidatesPlayback() dispatcher.Flush(); AnimationMarkerEvent marker = Assert.Single(markers); - Assert.Equal("midpoint", marker.eventId); + Assert.Equal("midpoint", marker.eventID); Assert.Equal(handle, marker.playback); Assert.False(runtime.TryGetState(handle, out _, out _)); } @@ -114,9 +113,7 @@ public void ClipValidationRejectsDuplicateBindingsAndInvalidTimes() Assert.Throws(clip.Validate); clip = CreateClip(); - clip.tracks[0].keyframes[1] = new AnimationKeyframe(2f, new AnimationValue( - AnimationValueKind.Scalar, - 1f)); + clip.tracks[0].keyframes[1] = new AnimationKeyframe(2f, new AnimationValue(AnimationValueKind.Scalar, 1f)); Assert.Throws(clip.Validate); } @@ -141,58 +138,57 @@ public void DestinationsDoNotBlendTogetherAndPlaybackFreezesAuthoringData() Assert.Equal(0.25f, sink.lastSamples.Single(sample => sample.target.Equals(firstTarget)).value.x); Assert.Equal(0.75f, sink.lastSamples.Single(sample => sample.target.Equals(secondTarget)).value.x); allocator.Unregister(first); - allocator.Register(new Destination(), firstTarget.persistentId); + allocator.Register(new Destination(), firstTarget.persistentID); Assert.Null(firstTarget.Resolve()); Assert.Throws(() => runtime.Play(clip, default)); } - private sealed class Destination : IdentityObject; - private static AnimationClipAsset CreateClip() => new() - { - duration = 1f, - tracks = - [ - new AnimationTrack( - "visual.opacity", - AnimationInterpolation.Linear, - [ - new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, 0f)), - new AnimationKeyframe(1f, new AnimationValue(AnimationValueKind.Scalar, 1f)) - ]) - ], - events = - [ - new AnimationEventMarker - { - time = 0.5f, - eventId = "midpoint", - payload = [1, 2, 3] - } - ] - }; + { + duration = 1f, + tracks = + [ + new AnimationTrack( + "visual.opacity", + AnimationInterpolation.Linear, + [ + new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, 0f)), + new AnimationKeyframe(1f, new AnimationValue(AnimationValueKind.Scalar, 1f)) + ] + ) + ], + events = + [ + new AnimationEventMarker + { + time = 0.5f, + eventId = "midpoint", + payload = [1, 2, 3] + } + ] + }; private static AnimationClipAsset CreateConstantClip(float value) => new() - { - duration = 1f, - tracks = - [ - new AnimationTrack( - "visual.opacity", - AnimationInterpolation.Step, - [new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, value))]) - ] - }; + { + duration = 1f, + tracks = + [ + new AnimationTrack( + "visual.opacity", + AnimationInterpolation.Step, + [new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, value))] + ) + ] + }; + + private sealed class Destination : IdentityObject; private sealed class RecordingSink : IAnimationBindingSink { - internal IReadOnlyList lastSamples { get; private set; } = []; + public void Apply(ReadOnlySpan samples) => lastSamples = samples.ToArray(); - public void Apply(ReadOnlySpan samples) - { - lastSamples = samples.ToArray(); - } + internal IReadOnlyList lastSamples { get; private set; } = []; } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs new file mode 100644 index 000000000..89a653dc8 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.runtime-dependency-alternate")] +internal sealed class AlternateDependencyAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".depgraph2"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs index 9564b74e0..057a27490 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs @@ -3,18 +3,16 @@ using System.IO; using System.Linq; using System.Threading; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class AssetFileSystemChangeTests { [Fact] - public void Watcher_CoalescesCreateChangeAndDeleteThroughPublicCoordinator() + public void WatcherCoalescesCreateChangeAndDeleteThroughPublicCoordinator() { string root = CreateRoot(); try @@ -22,20 +20,21 @@ public void Watcher_CoalescesCreateChangeAndDeleteThroughPublicCoordinator() using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); string path = Path.Combine(root, "Flow", "item.txt"); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, "one"); - System.IO.File.WriteAllText(path, "two"); + File.WriteAllText(path, "one"); + File.WriteAllText(path, "two"); IReadOnlyList observed = fileSystem.WaitForIdle(); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("Flow/item.txt"), out AssetFileEntry created)); Assert.False(created.isDirectory); - System.IO.File.Delete(path); + File.Delete(path); observed = observed.Concat(fileSystem.WaitForIdle()).ToArray(); Assert.False(fileSystem.TryGetEntry(AssetPath.Project("Flow/item.txt"), out _)); - Assert.Contains(observed, static change => - change.relativePath == "Flow/item.txt" && - change.changeType.HasFlag(WatcherChangeTypes.Deleted)); + Assert.Contains(observed, static change => ( + change.relativePath == "Flow/item.txt" + && change.changeType.HasFlag(WatcherChangeTypes.Deleted) + )); } finally { @@ -44,20 +43,21 @@ public void Watcher_CoalescesCreateChangeAndDeleteThroughPublicCoordinator() } [Fact] - public void Watcher_RenamePreservesOldAndNewRelativePaths() + public void WatcherRenamePreservesOldAndNewRelativePaths() { string root = CreateRoot(); try { string oldPath = Path.Combine(root, "old.txt"); string newPath = Path.Combine(root, "new.txt"); - System.IO.File.WriteAllText(oldPath, "value"); + File.WriteAllText(oldPath, "value"); using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.Move(oldPath, newPath); + File.Move(oldPath, newPath); IReadOnlyList observed = fileSystem.WaitForIdle(); - AssetChangedEvent renamed = Assert.Single(observed.Where(static change => - change.changeType.HasFlag(WatcherChangeTypes.Renamed))); + AssetChangedEvent renamed = Assert.Single( + observed.Where(static change => change.changeType.HasFlag(WatcherChangeTypes.Renamed)) + ); Assert.Equal("old.txt", renamed.oldRelativePath); Assert.Equal("new.txt", renamed.relativePath); Assert.False(fileSystem.Exists(AssetPath.Project("old.txt"))); @@ -76,8 +76,8 @@ public void WatcherPublishesSettingsSidecarChangesWithoutExposingMetadataAsAsset try { using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.WriteAllText(Path.Combine(root, "asset.txt.imeta"), "cache"); - System.IO.File.WriteAllText(Path.Combine(root, "asset.txt.abin"), "generated"); + File.WriteAllText(Path.Combine(root, "asset.txt.imeta"), "cache"); + File.WriteAllText(Path.Combine(root, "asset.txt.abin"), "generated"); Thread.Sleep(100); IReadOnlyList changes = fileSystem.WaitForIdle(); @@ -102,6 +102,8 @@ private static string CreateRoot() private static void DeleteRoot(string root) { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs index a33cf931f..c594d7745 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs @@ -3,11 +3,10 @@ using System.IO; using System.Linq; using System.Threading; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; - -using Xunit; +using Inno.Core.Identity; namespace Inno.Assets.Pipeline.Tests; @@ -23,7 +22,7 @@ public void RefreshPreservesUnchangedEntryInstancesAndRuntimeIdentities() File.WriteAllText(Path.Combine(root, "Folder", "value.txt"), "value"); using var fileSystem = new AssetFileSystem(root, autoStart: false); AssetFileEntry[] previous = fileSystem.GetEntries().ToArray(); - var identities = previous.Select(static entry => entry.identity.runtimeIdentity).ToArray(); + RuntimeIdentity?[] identities = previous.Select(static entry => entry.identity.runtimeIdentity).ToArray(); fileSystem.Refresh(); for (int index = 0; index < previous.Length; index++) { @@ -48,7 +47,7 @@ public void FailedEnumerationKeepsThePreviousCompleteIndexAndItsIdentities() File.WriteAllText(Path.Combine(root, "value.txt"), "value"); using var fileSystem = new AssetFileSystem(root, autoStart: false); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("value.txt"), out AssetFileEntry previous)); - var identity = previous.identity.runtimeIdentity; + RuntimeIdentity? identity = previous.identity.runtimeIdentity; Directory.Move(root, moved); try { @@ -99,7 +98,7 @@ public void RefreshRetiresRemovedEntriesAndPreservesUnaffectedEntries() } [Fact] - public void Queries_RejectRootedAndTraversalPaths() + public void QueriesRejectRootedAndTraversalPaths() { string root = CreateRoot(); try @@ -117,24 +116,24 @@ public void Queries_RejectRootedAndTraversalPaths() } [Fact] - public void Refresh_IndexesDirectoriesAndFiles() + public void RefreshIndexesDirectoriesAndFiles() { string root = CreateRoot(); try { Directory.CreateDirectory(Path.Combine(root, "Config")); - System.IO.File.WriteAllText(Path.Combine(root, "Config", "a.json"), "{}"); - System.IO.File.WriteAllText(Path.Combine(root, "readme.txt"), "hi"); + File.WriteAllText(Path.Combine(root, "Config", "a.json"), "{}"); + File.WriteAllText(Path.Combine(root, "readme.txt"), "hi"); using var fs = new AssetFileSystem(root, autoStart: false); - var entries = fs.GetEntries(includeDirectories: true); + IReadOnlyList entries = fs.GetEntries(includeDirectories: true); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project(string.Empty) && x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("Config") && x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("Config/a.json") && !x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("readme.txt") && !x.isDirectory); - var rootChildren = fs.GetChildren(AssetPath.Project(string.Empty)); + IReadOnlyList rootChildren = fs.GetChildren(AssetPath.Project(string.Empty)); Assert.Equal(2, rootChildren.Count); Assert.Equal(AssetPath.Project("Config"), rootChildren[0].assetPath); Assert.Equal(AssetPath.Project("readme.txt"), rootChildren[1].assetPath); @@ -146,17 +145,17 @@ public void Refresh_IndexesDirectoriesAndFiles() } [Fact] - public void Watcher_PublishesChangesOnlyWhenOwnerPolls() + public void WatcherPublishesChangesOnlyWhenOwnerPolls() { string root = CreateRoot(); try { Directory.CreateDirectory(Path.Combine(root, "Config")); string file = Path.Combine(root, "Config", "watch.txt"); - System.IO.File.WriteAllText(file, "a"); + File.WriteAllText(file, "a"); using var fs = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.WriteAllText(file, "b"); + File.WriteAllText(file, "b"); IReadOnlyList batch = fs.WaitForIdle(); Assert.Contains(batch, static x => x.relativePath == "Config/watch.txt"); @@ -169,20 +168,19 @@ public void Watcher_PublishesChangesOnlyWhenOwnerPolls() } [Fact] - public void Entries_ExposeLastExtensionDisplayNameAndFilterDatabaseNoise() + public void EntriesExposeLastExtensionDisplayNameAndFilterDatabaseNoise() { string root = CreateRoot(); try { Directory.CreateDirectory(Path.Combine(root, "Scripts")); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs"), "class Tool {} "); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs.imeta"), "meta"); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.pdb"), "symbols"); - System.IO.File.WriteAllText(Path.Combine(root, ".DS_Store"), "noise"); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs"), "class Tool {} "); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs.imeta"), "meta"); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.pdb"), "symbols"); + File.WriteAllText(Path.Combine(root, ".DS_Store"), "noise"); using var fileSystem = new AssetFileSystem(root, autoStart: false); - AssetFileEntry entry = Assert.Single( - fileSystem.GetEntries(includeDirectories: false)); + AssetFileEntry entry = Assert.Single(fileSystem.GetEntries(includeDirectories: false)); Assert.Equal("Tool.editor.cs", entry.name); Assert.Equal("Tool.editor", entry.nameWithoutExtension); @@ -195,30 +193,26 @@ public void Entries_ExposeLastExtensionDisplayNameAndFilterDatabaseNoise() } [Fact] - public void Refresh_TreatsProjectTildeDirectoriesAsOrdinaryWritableContent() + public void RefreshTreatsProjectTildeDirectoriesAsOrdinaryWritableContent() { string root = CreateRoot(); try { Directory.CreateDirectory(Path.Combine(root, "~Starter", "Scenes")); - System.IO.File.WriteAllText( - Path.Combine(root, "~Starter", "Scenes", "Game.cs"), - "public sealed class Game { }"); - System.IO.File.WriteAllText(Path.Combine(root, "~Standalone.cs"), "sample-like file"); + File.WriteAllText(Path.Combine(root, "~Starter", "Scenes", "Game.cs"), "public sealed class Game { }"); + File.WriteAllText(Path.Combine(root, "~Standalone.cs"), "sample-like file"); using var fileSystem = new AssetFileSystem(root, autoStart: false); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("~Starter"), out AssetFileEntry tildeRoot)); Assert.False(tildeRoot.isSample); Assert.False(tildeRoot.isSampleContent); - Assert.True(fileSystem.TryGetEntry( - AssetPath.Project("~Starter/Scenes/Game.cs"), - out AssetFileEntry tildeContent)); + Assert.True( + fileSystem.TryGetEntry(AssetPath.Project("~Starter/Scenes/Game.cs"), out AssetFileEntry tildeContent) + ); Assert.False(tildeContent.isSample); Assert.False(tildeContent.isSampleContent); - Assert.True(fileSystem.TryGetEntry( - AssetPath.Project("~Standalone.cs"), - out AssetFileEntry ordinaryFile)); + Assert.True(fileSystem.TryGetEntry(AssetPath.Project("~Standalone.cs"), out AssetFileEntry ordinaryFile)); Assert.False(ordinaryFile.isSample); Assert.False(ordinaryFile.isSampleContent); } @@ -238,37 +232,41 @@ public void MultipleSourcesKeepCanonicalPathsNamesAndReadOnlyStateIsolated() { Directory.CreateDirectory(project); Directory.CreateDirectory(plugin); - System.IO.File.WriteAllText(Path.Combine(project, "same.txt"), "project"); - System.IO.File.WriteAllText(Path.Combine(plugin, "same.txt"), "plugin"); - var pluginId = new AssetSourceId("tests.mount"); + File.WriteAllText(Path.Combine(project, "same.txt"), "project"); + File.WriteAllText(Path.Combine(plugin, "same.txt"), "plugin"); + var pluginID = new AssetSourceID("tests.mount"); using var fileSystem = new AssetFileSystem( [ - new AssetSourceMount(AssetSourceId.project, project, isReadOnly: false), - new AssetSourceMount(pluginId, plugin, isReadOnly: true) + new AssetSourceMount(AssetSourceID.project, project, isReadOnly: false), + new AssetSourceMount(pluginID, plugin, isReadOnly: true) ], - autoStart: false); + autoStart: false + ); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("same.txt"), out AssetFileEntry projectEntry)); - Assert.True(fileSystem.TryGetEntry(new AssetPath(pluginId, "same.txt"), out AssetFileEntry pluginEntry)); + Assert.True(fileSystem.TryGetEntry(new AssetPath(pluginID, "same.txt"), out AssetFileEntry pluginEntry)); Assert.True(fileSystem.TryGetEntry(AssetPath.Project(string.Empty), out AssetFileEntry projectRoot)); - Assert.True(fileSystem.TryGetEntry(new AssetPath(pluginId, string.Empty), out AssetFileEntry pluginRoot)); + Assert.True(fileSystem.TryGetEntry(new AssetPath(pluginID, string.Empty), out AssetFileEntry pluginRoot)); Assert.Equal("same.txt", projectEntry.name); Assert.Equal("same.txt", pluginEntry.name); Assert.Equal("Assets", projectRoot.name); Assert.Equal("tests.mount", pluginRoot.name); Assert.False(projectEntry.isReadOnly); Assert.True(pluginEntry.isReadOnly); - Assert.Equal(AssetSourceId.project, projectEntry.source); - Assert.Equal(pluginId, pluginEntry.source); + Assert.Equal(AssetSourceID.project, projectEntry.source); + Assert.Equal(pluginID, pluginEntry.source); Assert.Contains( fileSystem.GetChildren(AssetPath.Project(string.Empty)), - entry => entry.source == AssetSourceId.project); + entry => entry.source == AssetSourceID.project + ); Assert.Contains( fileSystem.GetChildren(AssetPath.Project(string.Empty)), - entry => entry.assetPath == new AssetPath(pluginId, string.Empty)); + entry => entry.assetPath == new AssetPath(pluginID, string.Empty) + ); Assert.Contains( - fileSystem.GetChildren(new AssetPath(pluginId, string.Empty)), - entry => entry.assetPath == new AssetPath(pluginId, "same.txt")); + fileSystem.GetChildren(new AssetPath(pluginID, string.Empty)), + entry => entry.assetPath == new AssetPath(pluginID, "same.txt") + ); } finally { @@ -277,17 +275,17 @@ public void MultipleSourcesKeepCanonicalPathsNamesAndReadOnlyStateIsolated() } [Fact] - public void Watcher_RenameCarriesOldAndNewPathsThroughOwnerPolling() + public void WatcherRenameCarriesOldAndNewPathsThroughOwnerPolling() { string root = CreateRoot(); try { string oldPath = Path.Combine(root, "old.txt"); string newPath = Path.Combine(root, "new.txt"); - System.IO.File.WriteAllText(oldPath, "value"); + File.WriteAllText(oldPath, "value"); using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.Move(oldPath, newPath); + File.Move(oldPath, newPath); IReadOnlyList changes = fileSystem.WaitForIdle(); AssetChangedEvent moved = Assert.Single(changes, static change => @@ -313,6 +311,8 @@ private static string CreateRoot() private static void DeleteRoot(string root) { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs index 8c39415f8..b94f12f9e 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs @@ -1,35 +1,35 @@ -using Inno.Content.Testing; -using Inno.Content; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Content; +using Inno.Content.Testing; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.References; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class AssetLoaderTests : IDisposable { - private readonly string m_moduleArtifacts = Path.Combine(Path.GetTempPath(), - "AssetImporterModules-" + Guid.NewGuid().ToString("N")); + private readonly string m_moduleArtifacts = Path.Combine( + Path.GetTempPath(), + "AssetImporterModules-" + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -50,7 +50,9 @@ public AssetLoaderTests() m_identityScope = m_identities.EnterScope(); m_diagnosticScope = m_diagnostics.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); SlowAssetImporter.Reset(); @@ -68,14 +70,16 @@ public void Dispose() m_identityScope.Dispose(); m_modules.generations.Wait(); if (Directory.Exists(m_moduleArtifacts)) + { Directory.Delete(m_moduleArtifacts, recursive: true); + } } [Fact] public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordingFailure() { - using TestWorkspace workspace = new(); - using TestWorkspace package = new(); + using var workspace = new TestWorkspace(); + using var package = new TestWorkspace(); package.WriteText("README.md", "Documentation"); byte[] metadata = m_serialization.Serialize(new MountedSourceMetadata { @@ -83,14 +87,23 @@ public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordin sourceKind = (int)AssetSourceKind.File, importerId = "tests.unavailable.importer" }); - System.IO.File.WriteAllBytes(package.SourcePath("README.md.imeta"), metadata); - var source = new AssetSourceId("tests.readonly"); - using var loader = new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs, - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false), - new AssetSourceMount(source, package.assetRoot, true)], workspace.libraryRoot); + File.WriteAllBytes(package.SourcePath("README.md.imeta"), metadata); + var source = new AssetSourceID("tests.readonly"); + using var loader = new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + [ + new AssetSourceMount(AssetSourceID.project, workspace.assetRoot, false), + new AssetSourceMount(source, package.assetRoot, true) + ], + workspace.libraryRoot + ); Assert.False(loader.Import(new AssetPath(source, "README.md"))); - Assert.Equal(metadata, System.IO.File.ReadAllBytes(package.SourcePath("README.md.imeta"))); + Assert.Equal(metadata, File.ReadAllBytes(package.SourcePath("README.md.imeta"))); Assert.True(loader.TryGetInfo(new AssetPath(source, "README.md"), out AssetInfo? failure)); Assert.Equal(AssetImportStatus.Failed, failure!.status); Assert.Contains(failure.diagnostics, value => value.Contains("Read-only source metadata", StringComparison.Ordinal)); @@ -101,7 +114,7 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false), [InlineData(true)] public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool reopen) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("parent.depgraph", "child.deferredasset"); workspace.WriteText("child.deferredasset", "unchanged"); DeferredAssetImporter.isAvailable = false; @@ -109,13 +122,20 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool AssetLoader? loader = null; try { - loader = new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, - m_logs, workspace.assetRoot, workspace.libraryRoot); + loader = new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + workspace.assetRoot, + workspace.libraryRoot + ); loader.Rescan(); AssetPath parent = AssetPath.Project("parent.depgraph"); Assert.True(loader.TryGetInfo(parent, out AssetInfo? failed)); Assert.Equal(AssetImportStatus.Failed, failed!.status); - Guid identity = failed.persistentId; + Guid identity = failed.persistentID; loader.Rescan(); Assert.True(loader.TryGetInfo(parent, out AssetInfo? unchanged)); Assert.Equal(AssetImportStatus.Failed, unchanged!.status); @@ -127,12 +147,19 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool } DeferredAssetImporter.isAvailable = true; m_types.Rebuild(); - loader ??= new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, - m_logs, workspace.assetRoot, workspace.libraryRoot); + loader ??= new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + workspace.assetRoot, + workspace.libraryRoot + ); loader.Rescan(); Assert.True(loader.TryGetInfo(parent, out AssetInfo? recovered)); Assert.Equal(AssetImportStatus.Imported, recovered!.status); - Assert.Equal(identity, recovered.persistentId); + Assert.Equal(identity, recovered.persistentID); Assert.True(loader.TryGetInfo(AssetPath.Project("child.deferredasset"), out AssetInfo? child)); Assert.Equal(AssetImportStatus.Imported, child!.status); } @@ -148,45 +175,70 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool [InlineData(true)] public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompleted(bool available) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("surface.extensionasset", "authored"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); AssetPath path = AssetPath.Project("surface.extensionasset"); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); Assert.Equal(DiagnosticSeverity.Info, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); - byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta")); + byte[] sidecar = File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta")); int attempts = ExtensionDependentImporter.attempts; - for (int i = 0; i < 5; i++) pipeline.Rescan(); + for (int i = 0; i < 5; i++) + { + pipeline.Rescan(); + } Assert.Equal(attempts, ExtensionDependentImporter.attempts); - Assert.Throws(() => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "PendingExport"))); + Assert.Throws( + () => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "PendingExport")) + ); ExtensionDependentImporter.available = available; pipeline.CompleteExtensionDiscovery(); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? completed)); Assert.Equal(available ? AssetImportStatus.Imported : AssetImportStatus.Failed, completed!.status); if (available) + { Assert.Empty(sink.reports); + } else + { Assert.Equal(DiagnosticSeverity.Error, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); - Assert.Equal(pending.persistentId, completed.persistentId); - Assert.Equal(sidecar, System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta"))); - Assert.Equal("authored", System.IO.File.ReadAllText(workspace.SourcePath("surface.extensionasset"))); + } + Assert.Equal(pending.persistentID, completed.persistentID); + Assert.Equal(sidecar, File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta"))); + Assert.Equal("authored", File.ReadAllText(workspace.SourcePath("surface.extensionasset"))); attempts = ExtensionDependentImporter.attempts; - for (int i = 0; i < 5; i++) pipeline.Rescan(); + for (int i = 0; i < 5; i++) + { + pipeline.Rescan(); + } Assert.Equal(attempts, ExtensionDependentImporter.attempts); if (!available) { - Assert.Throws(() => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "MissingExport"))); + Assert.Throws( + () => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "MissingExport")) + ); ExtensionDependentImporter.available = true; Assert.True(pipeline.Import(path)); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? restored)); Assert.Equal(AssetImportStatus.Imported, restored!.status); - Assert.Equal(pending.persistentId, restored.persistentId); + Assert.Equal(pending.persistentID, restored.persistentID); } m_diagnostics.UnregisterSink(sink); } @@ -194,45 +246,69 @@ public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompl [Fact] public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery() { - using TestWorkspace workspace = new(); - using TestWorkspace package = new(); + using var workspace = new TestWorkspace(); + using var package = new TestWorkspace(); package.WriteText("surface.extensionasset", "authored"); byte[] metadata = m_serialization.Serialize(new MountedSourceMetadata { - persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, importerId = "tests.extension-dependent" }); - System.IO.File.WriteAllBytes(package.SourcePath("surface.extensionasset.imeta"), metadata); - var source = new AssetSourceId("tests.readonly-extension"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions + File.WriteAllBytes(package.SourcePath("surface.extensionasset.imeta"), metadata); + var source = new AssetSourceID("tests.readonly-extension"); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { - assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true, - sourceMounts = [new(AssetSourceId.project, workspace.assetRoot, false), new(source, package.assetRoot, true)] - }); + sourceMounts = + [ + new AssetSourceMount(AssetSourceID.project, workspace.assetRoot, false), + new AssetSourceMount(source, package.assetRoot, true) + ] + } + ); var path = new AssetPath(source, "surface.extensionasset"); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); Assert.Throws(pipeline.CompleteExtensionDiscovery); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? failed)); Assert.Equal(AssetImportStatus.Failed, failed!.status); - Assert.Equal(metadata, System.IO.File.ReadAllBytes(package.SourcePath("surface.extensionasset.imeta"))); + Assert.Equal(metadata, File.ReadAllBytes(package.SourcePath("surface.extensionasset.imeta"))); ExtensionDependentImporter.available = true; Assert.True(pipeline.Import(path)); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? recovered)); Assert.Equal(AssetImportStatus.Imported, recovered!.status); - Assert.Equal(pending.persistentId, recovered.persistentId); + Assert.Equal(pending.persistentID, recovered.persistentID); } [Fact] public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHideMissingExtensions() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("bad.mutableasset", "!invalid!"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); Assert.True(pipeline.TryGetInfo(AssetPath.Project("bad.mutableasset"), out AssetInfo? bad)); Assert.Equal(AssetImportStatus.Failed, bad!.status); workspace.WriteText("surface.extensionasset", "authored"); @@ -249,7 +325,7 @@ public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHi m_modules.Rebuild(); Assert.True(pipeline.TryGetInfo(AssetPath.Project("surface.extensionasset"), out AssetInfo? recovered)); Assert.Equal(AssetImportStatus.Imported, recovered!.status); - Assert.Equal(waiting.persistentId, recovered.persistentId); + Assert.Equal(waiting.persistentID, recovered.persistentID); } [Theory] @@ -257,13 +333,24 @@ public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHi [InlineData(true)] public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArtifacts(bool reference) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("surface.extensionasset", "authored"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); Assert.True(pipeline.TryGetInfo(AssetPath.Project("surface.extensionasset"), out AssetInfo? root)); - workspace.WriteText("material.extensiondependent", reference ? root!.persistentId.ToString() : "surface.extensionasset"); + workspace.WriteText("material.extensiondependent", reference ? root!.persistentID.ToString() : "surface.extensionasset"); pipeline.Rescan(); Assert.True(pipeline.TryGetInfo(AssetPath.Project("material.extensiondependent"), out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); @@ -276,7 +363,7 @@ public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArt pipeline.Rescan(); Assert.True(pipeline.TryGetInfo(AssetPath.Project("material.extensiondependent"), out AssetInfo? restored)); Assert.Equal(AssetImportStatus.Imported, restored!.status); - Assert.Equal(pending.persistentId, restored.persistentId); + Assert.Equal(pending.persistentID, restored.persistentID); } [Theory] @@ -284,59 +371,67 @@ public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArt [InlineData(true)] public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingLastGood(bool reject) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); - byte[] previousMeta = System.IO.File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta")); + byte[] previousMeta = File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta")); var observer = new CatalogObserver(); using IDisposable registration = m_modules.RegisterCatalogParticipant(observer); workspace.WriteText("value.hookasset", "candidate"); workspace.WriteText("new.txt", "new candidate source"); observer.prepare = () => { - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); Assert.False(pipeline.TryGetInfo(AssetPath.Project("new.txt"), out _)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); }; observer.activate = () => { - AssetObject published = m_identities.Get(previous.identity.persistentId)!; + AssetObject published = m_identities.Get(previous.identity.persistentID)!; Assert.NotSame(previous, published); Assert.Equal("candidate", Encoding.UTF8.GetString(published.runtimePayload.Span)); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); if (reject) + { throw new InvalidOperationException("Expected later participant rejection."); + } }; if (reject) { Assert.Throws(m_modules.Rebuild); - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); Assert.Equal(0, previous.unloadingCount); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); - Assert.Equal(previousMeta, System.IO.File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta"))); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.Equal(previousMeta, File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); Assert.False(pipeline.TryGetInfo(AssetPath.Project("new.txt"), out _)); } else { m_modules.Rebuild(); - Assert.NotSame(previous, pipeline.Load(previous.identity.persistentId)); + Assert.NotSame(previous, pipeline.Load(previous.identity.persistentID)); Assert.Equal(1, previous.unloadingCount); - Assert.True(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("new.txt.imeta"))); } observer.prepare = null; observer.activate = null; if (reject) { m_modules.Rebuild(); - Assert.NotSame(previous, pipeline.Load(previous.identity.persistentId)); + Assert.NotSame(previous, pipeline.Load(previous.identity.persistentID)); Assert.Equal(1, previous.unloadingCount); - Assert.True(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("new.txt.imeta"))); } } @@ -345,11 +440,17 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL [InlineData(true)] public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublicationOwnership(bool reject) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); var observer = new CatalogObserver(); using IDisposable registration = m_modules.RegisterCatalogParticipant(observer); @@ -358,47 +459,61 @@ public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublica TextAsset replacement = candidate.Load(AssetPath.Project("value.txt")); observer.activate = () => { - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); if (reject) throw new InvalidOperationException("Expected joined candidate rejection."); }; if (reject) + { Assert.Throws(m_modules.Rebuild); + } else + { m_modules.Rebuild(); - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + } + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); Assert.True(candidate.TryGetInfo(AssetPath.Project("value.txt"), out _)); observer.activate = null; if (reject) + { candidate.Rollback(); + } else { candidate.Activate(); candidate.Complete(); - Assert.Equal("candidate", Encoding.UTF8.GetString( - pipeline.Load(replacement.identity.persistentId).runtimePayload.Span)); + Assert.Equal( + "candidate", + Encoding.UTF8.GetString(pipeline.Load(replacement.identity.persistentID).runtimePayload.Span) + ); } } [Fact] public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.mutableasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); MutableAsset previous = pipeline.Load(AssetPath.Project("value.mutableasset")); - byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta")); + byte[] sidecar = File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta")); workspace.WriteText("value.mutableasset", "!invalid!"); Assert.Throws(m_modules.Rebuild); - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); Assert.Equal("previous", previous.value); - Assert.True(pipeline.TryGetInfo(previous.identity.persistentId, out AssetInfo? info)); + Assert.True(pipeline.TryGetInfo(previous.identity.persistentID, out AssetInfo? info)); Assert.Equal(AssetImportStatus.Imported, info!.status); - Assert.Equal(sidecar, System.IO.File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta"))); + Assert.Equal(sidecar, File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta"))); workspace.WriteText("value.mutableasset", "recovered"); m_modules.Rebuild(); - MutableAsset recovered = pipeline.Load(previous.identity.persistentId); + MutableAsset recovered = pipeline.Load(previous.identity.persistentID); Assert.NotSame(previous, recovered); Assert.Equal("recovered", recovered.value); } @@ -406,40 +521,43 @@ public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() [Fact] public void CandidateMetadataRejectsExternalChangesWithoutOverwritingThem() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceID.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); string sidecarPath = workspace.SourcePath("new.txt.imeta"); - Assert.False(System.IO.File.Exists(sidecarPath)); + Assert.False(File.Exists(sidecarPath)); byte[] external = m_serialization.Serialize(new MountedSourceMetadata { - persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, importerId = "external.importer" }); - System.IO.File.WriteAllBytes(sidecarPath, external); + File.WriteAllBytes(sidecarPath, external); Assert.Throws(candidate.Commit); - Assert.Equal(external, System.IO.File.ReadAllBytes(sidecarPath)); + Assert.Equal(external, File.ReadAllBytes(sidecarPath)); } [Fact] public void CandidateMetadataCompensatesEarlierSidecarsWhenALaterWriteFails() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); workspace.WriteText("a.txt", "first"); workspace.WriteText("z.txt", "last"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceID.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); Directory.CreateDirectory(workspace.SourcePath("z.txt.imeta")); Exception failure = Assert.ThrowsAny(candidate.Commit); Assert.True(failure is IOException or UnauthorizedAccessException, failure.ToString()); - Assert.False(System.IO.File.Exists(workspace.SourcePath("a.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("a.txt.imeta"))); Assert.True(Directory.Exists(workspace.SourcePath("z.txt.imeta"))); } @@ -448,13 +566,19 @@ public void CandidateMetadataCompensatesEarlierSidecarsWhenALaterWriteFails() [InlineData(true)] public void CandidateDiagnosticsPublishOnlyWithTheirSourceGenerationAndRetireWithoutErasingAnotherOwner(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); Assert.Single(sink.reports.Values); string previousSource = Assert.Single(sink.reports.Keys); workspace.WriteText("new.mutableasset", "!invalid!"); @@ -481,24 +605,25 @@ public void CandidateDiagnosticsPublishOnlyWithTheirSourceGenerationAndRetireWit [Fact] public void CandidateCommitRestoresCatalogAndSidecarsWhenJournalRetirementFails() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.txt", "last good"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); string snapshotPath = Path.Combine(workspace.libraryRoot, "AssetDatabase", "Catalog.snapshot"); string journalPath = Path.Combine(workspace.libraryRoot, "AssetDatabase", "Catalog.journal"); - byte[] previous = System.IO.File.ReadAllBytes(snapshotPath); + byte[] previous = File.ReadAllBytes(snapshotPath); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceID.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); Directory.CreateDirectory(journalPath); Exception? failure = Record.Exception(candidate.Commit); Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); - Assert.Equal(previous, System.IO.File.ReadAllBytes(snapshotPath)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.Equal(previous, File.ReadAllBytes(snapshotPath)); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); Assert.True(Directory.Exists(journalPath)); Assert.False(loader.TryGetInfo(AssetPath.Project("new.txt"), out _)); } @@ -506,13 +631,19 @@ public void CandidateCommitRestoresCatalogAndSidecarsWhenJournalRetirementFails( [Fact] public void CandidateDiagnosticRecoveryCanRollBackToThePreviousUnresolvedReport() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); DiagnosticReport previous = Assert.Single(sink.reports.Values); workspace.WriteText("value.mutableasset", "fixed"); using AssetSourceMountTransaction candidate = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -522,74 +653,63 @@ public void CandidateDiagnosticRecoveryCanRollBackToThePreviousUnresolvedReport( candidate.Rollback(); DiagnosticReport restored = Assert.Single(sink.reports.Values); Assert.Equal(previous.source.id, restored.source.id); - Assert.Equal(previous.diagnostics.Select(static issue => issue.message), - restored.diagnostics.Select(static issue => issue.message)); + Assert.Equal( + previous.diagnostics.Select(static issue => issue.message), + restored.diagnostics.Select(static issue => issue.message) + ); m_diagnostics.UnregisterSink(sink); } - private sealed class CatalogObserver : IAssemblyCatalogParticipant - { - internal Action? prepare; - internal Action? activate; - - public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) - { - prepare?.Invoke(); - return new Observation(activate); - } - - private sealed class Observation(Action? activate) : IAssemblyCatalogTransaction - { - public object? context => null; - public void Activate() => activate?.Invoke(); - public void Complete() { } - public void Rollback() { } - } - } - [Theory] [InlineData(false)] [InlineData(true)] public void SourceCandidatePublishesCanonicalIdentitiesOnlyDuringSharedRecovery(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "old"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false - }); + } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); RuntimeIdentity previousIdentity = previous.identity.runtimeIdentity!.Value; workspace.WriteText("value.txt", "candidate"); using AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); TextAsset candidate = transaction.Load(AssetPath.Project("value.txt")); - Assert.Equal(previous.identity.persistentId, candidate.identity.persistentId); - Assert.Null(candidate.identity.runtimeId); + Assert.Equal(previous.identity.persistentID, candidate.identity.persistentID); + Assert.Null(candidate.identity.runtimeID); Assert.Same(previous, m_identities.Get(previousIdentity)); Assert.Empty(transaction.recoveryChanges); transaction.Activate(); ReferenceRecoveryChange recovered = Assert.Single(transaction.recoveryChanges); Assert.Equal(ReferenceResolutionState.Resolved, recovered.resolution.state); Assert.Equal(candidate.identity.runtimeIdentity, recovered.resolution.runtimeIdentity); - Assert.Same(candidate, m_identities.Get(previous.identity.persistentId)); + Assert.Same(candidate, m_identities.Get(previous.identity.persistentID)); Assert.Null(m_identities.Get(previousIdentity)); if (commit) { transaction.Complete(); - Assert.Same(candidate, pipeline.Load(candidate.identity.persistentId)); - Assert.NotNull(candidate.identity.runtimeId); + Assert.Same(candidate, pipeline.Load(candidate.identity.persistentID)); + Assert.NotNull(candidate.identity.runtimeID); } else { RuntimeIdentity candidateIdentity = candidate.identity.runtimeIdentity!.Value; transaction.Rollback(); - Assert.Same(previous, pipeline.Load(previous.identity.persistentId)); - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); + Assert.Same(previous, pipeline.Load(previous.identity.persistentID)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); Assert.Null(m_identities.Get(candidateIdentity)); Assert.Empty(transaction.recoveryChanges); } @@ -598,44 +718,59 @@ public void SourceCandidatePublishesCanonicalIdentitiesOnlyDuringSharedRecovery( [Fact] public void SourceCandidateIdentityConflictRestoresThePreviousDomain() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.txt", "old"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("previous.txt")); workspace.WriteText("candidate.txt", "new"); using AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); TextAsset candidate = transaction.Load(AssetPath.Project("candidate.txt")); var unrelated = new IdentityConflict(); - m_identities.Register(unrelated, candidate.identity.persistentId); + m_identities.Register(unrelated, candidate.identity.persistentID); try { Assert.Throws(transaction.Activate); - Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); - Assert.Same(unrelated, m_identities.Get(candidate.identity.persistentId)); + Assert.Same(previous, m_identities.Get(previous.identity.persistentID)); + Assert.Same(unrelated, m_identities.Get(candidate.identity.persistentID)); transaction.Rollback(); - Assert.Same(previous, pipeline.Load(previous.identity.persistentId)); + Assert.Same(previous, pipeline.Load(previous.identity.persistentID)); + } + finally + { + m_identities.Unregister(unrelated); } - finally { m_identities.Unregister(unrelated); } } [Fact] public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "preserved"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); - Guid id = previous.identity.persistentId; - byte[] metadata = System.IO.File.ReadAllBytes(workspace.SourcePath("value.txt.imeta")); - System.IO.File.Delete(workspace.SourcePath("value.txt")); + Guid id = previous.identity.persistentID; + byte[] metadata = File.ReadAllBytes(workspace.SourcePath("value.txt.imeta")); + File.Delete(workspace.SourcePath("value.txt")); using AssetSourceMountTransaction removal = pipeline.PrepareSourceMounts(pipeline.sourceMounts); removal.Activate(); ReferenceRecoveryChange missing = Assert.Single(removal.recoveryChanges); - Assert.Equal(id, missing.resolution.descriptor.targetPersistentId); + Assert.Equal(id, missing.resolution.descriptor.targetPersistentID); Assert.Equal(ReferenceResolutionState.Missing, missing.resolution.state); removal.Complete(); GC.Collect(); @@ -646,7 +781,7 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() Assert.Equal(ReferenceResolutionState.Missing, Assert.Single(stillMissing.recoveryChanges).resolution.state); stillMissing.Complete(); workspace.WriteText("value.txt", "preserved"); - System.IO.File.WriteAllBytes(workspace.SourcePath("value.txt.imeta"), metadata); + File.WriteAllBytes(workspace.SourcePath("value.txt.imeta"), metadata); using AssetSourceMountTransaction recovery = pipeline.PrepareSourceMounts(pipeline.sourceMounts); recovery.Activate(); ReferenceRecoveryChange restored = Assert.Single(recovery.recoveryChanges); @@ -654,7 +789,7 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() Assert.Equal(missing.missingState.payload.ToArray(), restored.missingState.payload.ToArray()); Assert.Equal(ReferenceResolutionState.Resolved, restored.resolution.state); recovery.Complete(); - Assert.Equal(id, pipeline.Load(AssetPath.Project("value.txt")).identity.persistentId); + Assert.Equal(id, pipeline.Load(AssetPath.Project("value.txt")).identity.persistentID); } [Theory] @@ -662,11 +797,17 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() [InlineData(true)] public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); workspace.WriteText("value.hookasset", "candidate"); using AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -676,14 +817,20 @@ public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(boo retiring.pendingUnloads = 2; transaction.Activate(); - if (commit) transaction.Complete(); - else transaction.Rollback(); + if (commit) + { + transaction.Complete(); + } + else + { + transaction.Rollback(); + } Assert.Equal(3, retiring.unloadingCount); Assert.True(retiring.runtimePayload.IsEmpty); - Assert.Null(retiring.identity.runtimeId); - Assert.Same(retained, pipeline.Load(retained.identity.persistentId)); - Assert.Same(retained, m_identities.Get(retained.identity.persistentId)); + Assert.Null(retiring.identity.runtimeID); + Assert.Same(retained, pipeline.Load(retained.identity.persistentID)); + Assert.Same(retained, m_identities.Get(retained.identity.persistentID)); Assert.Equal(0, retained.unloadingCount); Assert.False(retained.runtimePayload.IsEmpty); using AssetSourceMountTransaction next = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -692,9 +839,9 @@ public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(boo [Fact] public void LoaderRetirementRetainsPendingAssetPayloadAndRegistration() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); RuntimeIdentity identity = asset.identity.runtimeIdentity!.Value; asset.pendingUnloads = 1; @@ -713,27 +860,33 @@ public void LoaderRetirementRetainsPendingAssetPayloadAndRegistration() [Fact] public void PipelineShutdownDrainsCanonicalAssetsBeforeReleasingTheirOwners() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); - var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset asset = pipeline.Load(AssetPath.Project("value.hookasset")); asset.pendingUnloads = 1; pipeline.Dispose(); pipeline.Dispose(); Assert.Equal(2, asset.unloadingCount); - Assert.Null(asset.identity.runtimeId); + Assert.Null(asset.identity.runtimeID); Assert.False(pipeline.isInitialized); } [Fact] public void LoaderRetirementKeepsEarlierFailuresAcrossPendingResources() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("a.hookasset", "pending"); workspace.WriteText("b.hookasset", "failure"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset pending = Assert.IsType(loader.Load(AssetPath.Project("a.hookasset"), typeof(HookAsset))); HookAsset failing = Assert.IsType(loader.Load(AssetPath.Project("b.hookasset"), typeof(HookAsset))); pending.pendingUnloads = 1; @@ -745,43 +898,46 @@ public void LoaderRetirementKeepsEarlierFailuresAcrossPendingResources() loader.Dispose(); Assert.Equal(2, pending.unloadingCount); Assert.Equal(1, failing.unloadingCount); - Assert.Null(pending.identity.runtimeId); - Assert.Null(failing.identity.runtimeId); + Assert.Null(pending.identity.runtimeID); + Assert.Null(failing.identity.runtimeID); } [Fact] public void LoaderShutdownIncludesCanonicalTombstones() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); - System.IO.File.Delete(workspace.SourcePath("value.hookasset")); + File.Delete(workspace.SourcePath("value.hookasset")); loader.Rescan(); Assert.True(asset.isMissing); loader.Dispose(); Assert.Equal(1, asset.unloadingCount); - Assert.Null(asset.identity.runtimeId); + Assert.Null(asset.identity.runtimeID); } [Fact] public async Task LoaderDisposalDoesNotBlockAnInFlightLoadOrAdmitNewWork() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.slowasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Task loading = loader.LoadAsync(AssetPath.Project("value.slowasset"), typeof(SlowAsset)).AsTask(); try { - Assert.True(SlowAssetImporter.importStarted.Wait(TimeSpan.FromSeconds(3))); + Assert.True(SlowAssetImporter.IMPORT_STARTED.Wait(TimeSpan.FromSeconds(3))); Assert.Throws(loader.Dispose); Assert.Throws(() => loader.LoadAsync(AssetPath.Project("value.slowasset"), typeof(SlowAsset))); } - finally { SlowAssetImporter.allowImport.Set(); } + finally + { + SlowAssetImporter.ALLOW_IMPORT.Set(); + } AssetObject asset = Assert.IsType(await loading); - Assert.NotNull(asset.identity.runtimeId); + Assert.NotNull(asset.identity.runtimeID); loader.Dispose(); - Assert.Null(asset.identity.runtimeId); + Assert.Null(asset.identity.runtimeID); } [Theory] @@ -789,15 +945,23 @@ public async Task LoaderDisposalDoesNotBlockAnInFlightLoadOrAdmitNewWork() [InlineData(true)] public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); var modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly)}); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) + }); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - var pipeline = new AssetPipeline(modules, types, serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + var pipeline = new AssetPipeline( + modules, + types, + serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); workspace.WriteText("value.hookasset", "candidate"); AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -807,13 +971,19 @@ public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(b retiring.retirementExpired = true; transaction.Activate(); - if (commit) Assert.Throws(transaction.Complete); - else Assert.Throws(transaction.Rollback); + if (commit) + { + Assert.Throws(transaction.Complete); + } + else + { + Assert.Throws(transaction.Rollback); + } Assert.False(retiring.runtimePayload.IsEmpty); Assert.False(retained.runtimePayload.IsEmpty); Assert.Equal(0, retained.unloadingCount); - Assert.ThrowsAny(() => pipeline.Load(retained.identity.persistentId)); + Assert.ThrowsAny(() => pipeline.Load(retained.identity.persistentID)); retiring.retirementExpired = false; Assert.ThrowsAny(transaction.Dispose); Assert.ThrowsAny(pipeline.Dispose); @@ -827,9 +997,9 @@ public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(b [Fact] public void RuntimeDatabaseRetainsPendingPayloadAndRegistrationUntilShutdownCompletes() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "runtime payload"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); @@ -844,7 +1014,7 @@ public void RuntimeDatabaseRetainsPendingPayloadAndRegistrationUntilShutdownComp Assert.Throws(database.Dispose); Assert.Same(asset, identities.Get(identity)); Assert.Equal("runtime payload", Encoding.UTF8.GetString(asset.runtimePayload.Span)); - Assert.Throws(() => database.Load(asset.identity.persistentId)); + Assert.Throws(() => database.Load(asset.identity.persistentID)); database.Dispose(); database.Dispose(); Assert.Null(identities.Get(identity)); @@ -855,10 +1025,10 @@ public void RuntimeDatabaseRetainsPendingPayloadAndRegistrationUntilShutdownComp [Fact] public void OneImporterCanKeepGraphInputsInAuthoringWhileExportingExecutableAssets() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("node.mixedscope", "authoring"); workspace.WriteText("shader.mixedscope", "runtime"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("node.mixedscope"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("shader.mixedscope"), typeof(DependencyAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); @@ -875,28 +1045,36 @@ public void OneImporterCanKeepGraphInputsInAuthoringWhileExportingExecutableAsse [Fact] public async Task RuntimeLeaseRetriesPendingBudgetEvictionWithoutReleasingAnotherLease() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "leased payload"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); using SerializationGeneration serialization = m_serialization.CaptureGeneration(); var identities = new IdentityAllocator(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(contentRoot); - using var database = new AssetDatabase(contentStore, serialization, m_types.current, identities, - residencyBudgetBytes: 0); + using var database = new AssetDatabase( + contentStore, + serialization, + m_types.current, + identities, + residencyBudgetBytes: 0 + ); Task> pending = database.AcquireAsync( - AssetPath.Project("value.hookasset")).AsTask(); - Assert.True(SpinWait.SpinUntil(() => - { - database.CompletePendingLoads(); - return pending.IsCompleted; - }, TimeSpan.FromSeconds(5))); + AssetPath.Project("value.hookasset") + ).AsTask(); + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return pending.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); using AssetLease first = await pending; HookAsset asset = first.asset; RuntimeIdentity identity = asset.identity.runtimeIdentity!.Value; - using AssetLease last = await database.AcquireAsync(asset.identity.persistentId); + using AssetLease last = await database.AcquireAsync(asset.identity.persistentID); asset.pendingUnloads = 1; first.Dispose(); first.Dispose(); @@ -915,32 +1093,22 @@ public async Task RuntimeLeaseRetriesPendingBudgetEvictionWithoutReleasingAnothe Assert.Throws(() => last.asset); } - private sealed class IdentityConflict : IdentityObject; - - private sealed class MountedSourceMetadata : ISerializable - { - [SerializableProperty] public Guid persistentId { get; set; } - [SerializableProperty] public int sourceKind { get; set; } - [SerializableProperty] public string importerId { get; set; } = string.Empty; - [SerializableProperty] public byte[] importerSettingsBytes { get; set; } = []; - } - [Fact] public void MissingReferenceNeverBindsAnotherIdentityAtItsLastKnownPath() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/replaced.txt", "replacement"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); - var replacement = Assert.IsType(loader.Load(AssetPath.Project("Text/replaced.txt"), typeof(TextAsset))); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + TextAsset replacement = Assert.IsType(loader.Load(AssetPath.Project("Text/replaced.txt"), typeof(TextAsset))); Guid intended = Guid.NewGuid(); Assert.True(m_types.TryGetTypeRef(typeof(TextAsset), out TypeRef type)); - AssetObject missing = loader.ResolveReference(intended, type.stableId, "Text/replaced.txt", typeof(TextAsset)); + AssetObject missing = loader.ResolveReference(intended, type.stableID, "Text/replaced.txt", typeof(TextAsset)); Assert.True(missing.isMissing); - Assert.Equal(intended, missing.identity.persistentId); + Assert.Equal(intended, missing.identity.persistentID); Assert.NotSame(replacement, missing); - Assert.Same(missing, loader.ResolveReference(intended, type.stableId, "Text/replaced.txt", typeof(TextAsset))); + Assert.Same(missing, loader.ResolveReference(intended, type.stableID, "Text/replaced.txt", typeof(TextAsset))); } [Fact] @@ -951,19 +1119,19 @@ public void ExtensionContractsUseImplementationIdentityWithoutManualVersions() } [Fact] - public void Import_WritesCacheWithoutCreatingCanonicalInstance() + public void ImportWritesCacheWithoutCreatingCanonicalInstance() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Config/game.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Config/game.txt"))); - Assert.True(System.IO.File.Exists(workspace.SourcePath("Config/game.txt.imeta"))); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Config/game.txt"), out Guid persistentId)); - Assert.NotEqual(Guid.Empty, persistentId); - Assert.True(loader.TryGetArtifact(persistentId, "runtime", out AssetArtifactInfo? artifact)); + Assert.True(File.Exists(workspace.SourcePath("Config/game.txt.imeta"))); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Config/game.txt"), out Guid persistentID)); + Assert.NotEqual(Guid.Empty, persistentID); + Assert.True(loader.TryGetArtifact(persistentID, "runtime", out AssetArtifactInfo? artifact)); Assert.NotNull(artifact); - using ArtifactLease imported = loader.AcquireArtifact(persistentId, "runtime"); + using ArtifactLease imported = loader.AcquireArtifact(persistentID, "runtime"); Assert.NotEmpty(imported.ReadAllBytes()); Assert.True(loader.TryGetAssetType(AssetPath.Project("Config/game.txt"), out Type? assetType)); Assert.Equal(typeof(TextAsset), assetType); @@ -971,14 +1139,15 @@ public void Import_WritesCacheWithoutCreatingCanonicalInstance() } [Fact] - public void AutomaticallyDiscoveredPrivateImporter_LoadsWithoutRegistrationApi() + public void AutomaticallyDiscoveredPrivateImporterLoadsWithoutRegistrationApi() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Private/item.privateasset", "private"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); PrivateConstructorAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Private/item.privateasset"), typeof(PrivateConstructorAsset))); + loader.Load(AssetPath.Project("Private/item.privateasset"), typeof(PrivateConstructorAsset)) + ); Assert.Equal("private", asset.value); m_types.Rebuild(); @@ -986,23 +1155,23 @@ public void AutomaticallyDiscoveredPrivateImporter_LoadsWithoutRegistrationApi() } [Fact] - public void SameAssetType_CanUseMultipleImportersForDifferentExtensions() + public void SameAssetTypeCanUseMultipleImportersForDifferentExtensions() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", string.Empty); workspace.WriteText("Graphs/b.depgraph2", string.Empty); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.IsType(loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset))); Assert.IsType(loader.Load(AssetPath.Project("Graphs/b.depgraph2"), typeof(DependencyAsset))); } [Fact] - public void DuplicateImporterId_IsRejectedDuringAutomaticDiscovery() + public void DuplicateImporterIDIsRejectedDuringAutomaticDiscovery() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Conflict/initialize.txt", "initialize"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Conflict/initialize.txt"))); InvalidOperationException exception = Assert.Throws( () => m_modules.Load(new DotNetModuleSource @@ -1013,59 +1182,66 @@ public void DuplicateImporterId_IsRejectedDuringAutomaticDiscovery() AppContext.BaseDirectory, "Modules", "DuplicateAssetImporters", - "Inno.Assets.Pipeline.DuplicateImporterFixture.dll"), + "Inno.Assets.Pipeline.DuplicateImporterFixture.dll" + ), domain = AssemblyDomain.InnoPlugin, scope = AssemblyScope.Editor - })); + }) + ); Assert.Contains("importer id", exception.Message, StringComparison.OrdinalIgnoreCase); } [Fact] - public void DuplicateImporterExtension_IsRejectedDuringAutomaticDiscovery() + public void DuplicateImporterExtensionIsRejectedDuringAutomaticDiscovery() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Conflict/value.conflict", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); ImporterConflictProbe.duplicateExtension = true; InvalidOperationException exception = Assert.Throws( - () => loader.Import(AssetPath.Project("Conflict/value.conflict"))); + () => loader.Import(AssetPath.Project("Conflict/value.conflict")) + ); Assert.Contains("extension", exception.Message, StringComparison.OrdinalIgnoreCase); } [Fact] - public void PathAndPersistentIdLoads_ReturnCanonicalInstance() + public void PathAndPersistentIDLoadsReturnCanonicalInstance() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/shared.txt", "shared"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset byPath = Assert.IsType(loader.Load(AssetPath.Project("Text/shared.txt"), typeof(TextAsset))); - TextAsset byId = Assert.IsType(loader.Load(byPath.identity.persistentId, typeof(TextAsset))); + TextAsset byID = Assert.IsType(loader.Load(byPath.identity.persistentID, typeof(TextAsset))); - Assert.Same(byPath, byId); + Assert.Same(byPath, byID); Assert.Equal(new[] { AssetPath.Project("Text/shared.txt") }, loader.GetLoadedPaths()); } [Fact] public void BlockedSourceVerificationRetainsLastGoodArtifactAndReportsImportFailure() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/cached.txt", "cached"); using (AssetLoader first = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) + { first.Rescan(); + } using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); using var sourceLock = new FileStream( workspace.SourcePath("Text/cached.txt"), FileMode.Open, FileAccess.ReadWrite, - FileShare.None); + FileShare.None + ); TextAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Text/cached.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/cached.txt"), typeof(TextAsset)) + ); Assert.Equal("cached", asset.content); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/cached.txt"), out AssetInfo? info)); @@ -1074,21 +1250,21 @@ public void BlockedSourceVerificationRetainsLastGoodArtifactAndReportsImportFail } [Fact] - public void ChangedStampWithEqualContent_DoesNotReimportCanonicalAsset() + public void ChangedStampWithEqualContentDoesNotReimportCanonicalAsset() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/touched.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset before = Assert.IsType( - loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) + ); long version = before.contentVersion; string sourcePath = workspace.SourcePath("Text/touched.txt"); - System.IO.File.SetLastWriteTimeUtc( - sourcePath, - System.IO.File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); + File.SetLastWriteTimeUtc(sourcePath, File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); TextAsset after = Assert.IsType( - loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) + ); Assert.Same(before, after); Assert.Equal(version, after.contentVersion); @@ -1097,19 +1273,21 @@ public void ChangedStampWithEqualContent_DoesNotReimportCanonicalAsset() [Fact] public void BlockedDependencyVerificationRetainsLastGoodArtifactAndReportsImportFailure() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/schema.inc", "schema"); workspace.WriteText("Import/root.importgraph", "Import/schema.inc"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Import/root.importgraph"))); using var sourceLock = new FileStream( workspace.SourcePath("Import/schema.inc"), FileMode.Open, FileAccess.ReadWrite, - FileShare.None); + FileShare.None + ); ImportGraphAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); Assert.False(asset.isMissing); Assert.True(loader.TryGetInfo(AssetPath.Project("Import/root.importgraph"), out AssetInfo? info)); @@ -1117,23 +1295,24 @@ public void BlockedDependencyVerificationRetainsLastGoodArtifactAndReportsImport } [Fact] - public async Task ConcurrentAsyncLoads_ShareImportAndCancellationOnlyCancelsOneWaiter() + public async Task ConcurrentAsyncLoadsShareImportAndCancellationOnlyCancelsOneWaiter() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Slow/item.slowasset", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); using var cancellation = new CancellationTokenSource(); ValueTask first = loader.LoadAsync(AssetPath.Project("Slow/item.slowasset"), typeof(SlowAsset)); - Assert.True(SlowAssetImporter.importStarted.Wait(TimeSpan.FromSeconds(3))); + Assert.True(SlowAssetImporter.IMPORT_STARTED.Wait(TimeSpan.FromSeconds(3))); ValueTask second = loader.LoadAsync( AssetPath.Project("Slow/item.slowasset"), typeof(SlowAsset), - cancellation.Token); + cancellation.Token + ); cancellation.Cancel(); await Assert.ThrowsAnyAsync(async () => await second); - SlowAssetImporter.allowImport.Set(); + SlowAssetImporter.ALLOW_IMPORT.Set(); SlowAsset loaded = Assert.IsType(await first); Assert.Equal("value", loaded.value); @@ -1143,20 +1322,22 @@ public async Task ConcurrentAsyncLoads_ShareImportAndCancellationOnlyCancelsOneW [Fact] public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/schema.inc", "first"); workspace.WriteText("Import/root.importgraph", "Import/schema.inc"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); ImportGraphAsset before = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); long version = before.contentVersion; string dependency = workspace.SourcePath("Import/schema.inc"); - DateTime timestamp = System.IO.File.GetLastWriteTimeUtc(dependency); + DateTime timestamp = File.GetLastWriteTimeUtc(dependency); workspace.WriteText("Import/schema.inc", "other"); - System.IO.File.SetLastWriteTimeUtc(dependency, timestamp); + File.SetLastWriteTimeUtc(dependency, timestamp); ImportGraphAsset after = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); Assert.Same(before, after); Assert.Equal(version + 1, after.contentVersion); @@ -1166,38 +1347,41 @@ public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() [Theory] [InlineData(false)] [InlineData(true)] - public void StaleSource_ReimportsAndUpdatesCanonicalInstanceInPlace(bool preserveTimestamp) + public void StaleSourceReimportsAndUpdatesCanonicalInstanceInPlace(bool preserveTimestamp) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/reload.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset before = Assert.IsType(loader.Load(AssetPath.Project("Text/reload.txt"), typeof(TextAsset))); - Guid persistentId = before.identity.persistentId; + Guid persistentID = before.identity.persistentID; long version = before.contentVersion; string sourcePath = workspace.SourcePath("Text/reload.txt"); - DateTime sourceTime = System.IO.File.GetLastWriteTimeUtc(sourcePath); + DateTime sourceTime = File.GetLastWriteTimeUtc(sourcePath); workspace.WriteText("Text/reload.txt", "two"); if (preserveTimestamp) - System.IO.File.SetLastWriteTimeUtc(sourcePath, sourceTime); + { + File.SetLastWriteTimeUtc(sourcePath, sourceTime); + } TextAsset after = Assert.IsType(loader.Load(AssetPath.Project("Text/reload.txt"), typeof(TextAsset))); Assert.Same(before, after); - Assert.Equal(persistentId, after.identity.persistentId); + Assert.Equal(persistentID, after.identity.persistentID); Assert.Equal("two", after.content); Assert.Equal(version + 1, after.contentVersion); } [Fact] - public void RuntimeDependencyCycle_IsAllowedAndLoadsAsOneCanonicalSubgraph() + public void RuntimeDependencyCycleIsAllowedAndLoadsAsOneCanonicalSubgraph() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", "Graphs/b.depgraph"); workspace.WriteText("Graphs/b.depgraph", "Graphs/a.depgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( - loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset))); + loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset)) + ); IReadOnlyList direct = loader.GetDependencies(root); IReadOnlyList recursive = loader.GetDependencies(root, recursive: true); @@ -1213,25 +1397,44 @@ public void RuntimeDependencyCycle_IsAllowedAndLoadsAsOneCanonicalSubgraph() [InlineData("invalid")] public async Task AsyncRuntimeExportReleasesItsGenerationLeaseAfterEveryOutcome(string outcome) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("leaf.buildinput", "original"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + enableFileSystemWatcher = false + } + ); DependencyAsset leaf = pipeline.Load(AssetPath.Project("leaf.buildinput")); - workspace.WriteText("root.buildconsumer", leaf.identity.persistentId.ToString()); + workspace.WriteText("root.buildconsumer", leaf.identity.persistentID.ToString()); _ = pipeline.Load(AssetPath.Project("root.buildconsumer")); if (outcome == "invalid") workspace.WriteText("leaf.buildinput", "changed input"); using var cancellation = new CancellationTokenSource(); if (outcome == "cancel") cancellation.Cancel(); Task export = pipeline.ExportRuntimeArtifactsAsync( - Path.Combine(workspace.libraryRoot, "AsyncRuntime"), cancellation.Token); + Path.Combine(workspace.libraryRoot, "AsyncRuntime"), + cancellation.Token + ); if (outcome == "cancel") + { await Assert.ThrowsAnyAsync(() => export); + } else if (outcome == "invalid") + { await Assert.ThrowsAsync(() => export); + } else + { _ = await export; + } m_modules.generations.EnsureReady("replace the generation after export"); } @@ -1242,23 +1445,27 @@ public void RuntimeExportRejectsTransitiveAuthoringInputsWithoutDiscardingLastGo string change, bool importChange ) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("leaf.buildinput", "original"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("leaf.buildinput"))); AssetObject leaf = Assert.IsType(loader.Load(AssetPath.Project("leaf.buildinput"), typeof(DependencyAsset))); - workspace.WriteText("middle.buildinput", leaf.identity.persistentId.ToString()); + workspace.WriteText("middle.buildinput", leaf.identity.persistentID.ToString()); Assert.True(loader.Import(AssetPath.Project("middle.buildinput"))); AssetObject middle = Assert.IsType(loader.Load(AssetPath.Project("middle.buildinput"), typeof(DependencyAsset))); - workspace.WriteText("root.buildconsumer", middle.identity.persistentId.ToString()); + workspace.WriteText("root.buildconsumer", middle.identity.persistentID.ToString()); Assert.True(loader.Import(AssetPath.Project("root.buildconsumer"))); loader.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "ValidRuntime")); workspace.WriteText("leaf.buildinput", change); if (importChange) + { Assert.False(loader.Import(AssetPath.Project("leaf.buildinput"))); - using (ArtifactLease lastGood = loader.AcquireArtifact(leaf.identity.persistentId, "authoring")) + } + using (ArtifactLease lastGood = loader.AcquireArtifact(leaf.identity.persistentID, "authoring")) + { Assert.Equal("original", Encoding.UTF8.GetString(lastGood.ReadAllBytes())); + } string invalidDestination = Path.Combine(workspace.libraryRoot, "InvalidRuntime"); InvalidOperationException error = Assert.Throws(() => loader.ExportRuntimeArtifacts(invalidDestination)); Assert.Contains("root.buildconsumer -> middle.buildinput -> leaf.buildinput", error.Message); @@ -1278,42 +1485,59 @@ bool importChange [Theory] [InlineData(false)] [InlineData(true)] - public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedCycles(bool cancelFirst) + public async Task ColdRootsShareDependencyIOAndRetireReservationsAcrossRepeatedCycles(bool cancelFirst) { - using TestWorkspace workspace = new(); - workspace.WriteText("Shared.txt", new string('s', 65536)); + using var workspace = new TestWorkspace(); + workspace.WriteText("Shared.txt", new string('s', 65_536)); workspace.WriteText("A.depgraph", "Shared.txt"); workspace.WriteText("B.depgraph", "Shared.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("A.depgraph"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("B.depgraph"), typeof(DependencyAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); using SerializationGeneration serialization = m_serialization.CaptureGeneration(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(contentRoot); - using var database = new AssetDatabase(contentStore, serialization, m_types.current, - new IdentityAllocator(), residencyBudgetBytes: 0, preparationBudgetBytes: 100000); + using var database = new AssetDatabase( + contentStore, + serialization, + m_types.current, + new IdentityAllocator(), + residencyBudgetBytes: 0, + preparationBudgetBytes: 100_000 + ); for (int cycle = 0; cycle < 32; cycle++) { using var cancellation = new CancellationTokenSource(); Task> first = database.AcquireAsync( - AssetPath.Project("A.depgraph"), cancellation.Token).AsTask(); + AssetPath.Project("A.depgraph"), + cancellation.Token + ).AsTask(); long firstBytes = database.preparingBytes; Task> second = database.AcquireAsync( - AssetPath.Project("B.depgraph")).AsTask(); + AssetPath.Project("B.depgraph") + ).AsTask(); Assert.Equal(3, database.preparationStatistics.pendingPayloads); Assert.True(database.preparingBytes < firstBytes * 2); if (cancelFirst) - cancellation.Cancel(); - Assert.True(SpinWait.SpinUntil(() => { - database.CompletePendingLoads(); - return first.IsCompleted && second.IsCompleted; - }, TimeSpan.FromSeconds(5))); + cancellation.Cancel(); + } + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return first.IsCompleted && second.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); if (cancelFirst) + { Assert.True(first.IsCanceled); + } else + { (await first).Dispose(); + } (await second).Dispose(); Assert.Equal(0, database.preparationStatistics.pendingPayloads); Assert.Equal(0, database.preparingBytes); @@ -1324,16 +1548,16 @@ public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedC Assert.Equal(96, statistics.payloadReadsStarted); Assert.Equal(32, statistics.sharedPayloadReads); Assert.Equal(2, statistics.peakPendingRequests); - Assert.InRange(statistics.peakReservedBytes, 65536, 100000); + Assert.InRange(statistics.peakReservedBytes, 65_536, 100_000); Assert.Equal(0, statistics.rejectedRequests); } [Fact] public void ColdAdmissionCountersRemainBoundedAndDisposeDrainsEveryCanceledWaiter() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Shared.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("Shared.txt"), typeof(TextAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); @@ -1357,11 +1581,11 @@ public void ColdAdmissionCountersRemainBoundedAndDisposeDrainsEveryCanceledWaite [Fact] public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublishingAssets() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Shared.txt", "payload"); workspace.WriteText("A.depgraph", "Shared.txt"); workspace.WriteText("B.depgraph", "Shared.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("A.depgraph"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("B.depgraph"), typeof(DependencyAsset))); AssetObject shared = Assert.IsType(loader.Load(AssetPath.Project("Shared.txt"), typeof(TextAsset))); @@ -1370,23 +1594,28 @@ public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublis using SerializationGeneration serialization = m_serialization.CaptureGeneration(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(contentRoot); using var database = new AssetDatabase(contentStore, serialization, m_types.current, new IdentityAllocator()); - using (ArtifactLease artifact = database.AcquireArtifact(shared.identity.persistentId, "runtime")) + using (ArtifactLease artifact = database.AcquireArtifact(shared.identity.persistentID, "runtime")) { - ContentKey key = Assert.Single(contentStore.index.entries.Where(entry => - entry.key.value!.StartsWith("Artifacts/", StringComparison.Ordinal) - && entry.key.value.Contains("/outputs/", StringComparison.Ordinal) - && entry.contentHash == artifact.info.contentHash)).key; + ContentKey key = Assert.Single( + contentStore.index.entries.Where(entry => ( + entry.key.value!.StartsWith("Artifacts/", StringComparison.Ordinal) + && entry.key.value.Contains("/outputs/", StringComparison.Ordinal) + && entry.contentHash == artifact.info.contentHash + )) + ).key; byte[] bytes = artifact.ReadAllBytes(); - bytes[0] ^= 0xff; + bytes[0] ^= 0xFF; contentStore.CorruptPayload(key, bytes); } Task> first = database.AcquireAsync(AssetPath.Project("A.depgraph")).AsTask(); Task> second = database.AcquireAsync(AssetPath.Project("B.depgraph")).AsTask(); - Assert.True(SpinWait.SpinUntil(() => - { - database.CompletePendingLoads(); - return first.IsCompleted && second.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return first.IsCompleted && second.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); Assert.True(first.IsFaulted); Assert.True(second.IsFaulted); Assert.Contains("integrity", first.Exception!.ToString()); @@ -1397,12 +1626,12 @@ public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublis } [Fact] - public void ImportDependencyCycle_IsRejectedWithClosedPathChain() + public void ImportDependencyCycleIsRejectedWithClosedPathChain() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/a.importgraph", "Import/b.importgraph"); workspace.WriteText("Import/b.importgraph", "Import/a.importgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Import/a.importgraph"))); Assert.False(loader.Import(AssetPath.Project("Import/b.importgraph"))); @@ -1417,33 +1646,33 @@ public void ImportDependencyCycle_IsRejectedWithClosedPathChain() } [Fact] - public void RenameAndDelete_UpdateCanonicalInstanceWithoutChangingIdentity() + public void RenameAndDeleteUpdateCanonicalInstanceWithoutChangingIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/old.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/old.txt"), typeof(TextAsset))); - Guid persistentId = asset.identity.persistentId; + Guid persistentID = asset.identity.persistentID; workspace.Move("Text/old.txt", "Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Renamed, "Text/old.txt") + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Renamed, "Text/old.txt") ]); Assert.Equal("Text/new.txt", asset.assetPath.ToString()); - Assert.Same(asset, loader.Load(persistentId, typeof(TextAsset))); + Assert.Same(asset, loader.Load(persistentID, typeof(TextAsset))); workspace.DeleteSource("Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Deleted) ]); Assert.True(asset.isMissing); - Assert.Equal(persistentId, asset.identity.persistentId); + Assert.Equal(persistentID, asset.identity.persistentID); Assert.True(asset.runtimePayload.IsEmpty); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); Assert.False(loader.TryGetInfo(AssetPath.Project("Text/new.txt"), out _)); - Assert.True(loader.TryGetInfo(persistentId, out AssetInfo? tombstone)); + Assert.True(loader.TryGetInfo(persistentID, out AssetInfo? tombstone)); Assert.NotNull(tombstone); Assert.Equal(AssetImportStatus.Missing, tombstone.status); Assert.True(tombstone.artifactKey.isEmpty); @@ -1451,44 +1680,45 @@ public void RenameAndDelete_UpdateCanonicalInstanceWithoutChangingIdentity() } [Fact] - public void RecreatedSourceWithoutMetadata_ReceivesNewIdentity() + public void RecreatedSourceWithoutMetadataReceivesNewIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/recover.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); workspace.DeleteSource("Text/recover.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) ]); workspace.WriteText("Text/recover.txt", "two"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) ]); TextAsset replacement = Assert.IsType( - loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset)) + ); Assert.True(asset.isMissing); Assert.False(replacement.isMissing); Assert.Equal("two", replacement.content); - Assert.NotEqual(asset.identity.persistentId, replacement.identity.persistentId); - Assert.Same(asset, loader.Load(asset.identity.persistentId, typeof(TextAsset))); + Assert.NotEqual(asset.identity.persistentID, replacement.identity.persistentID); + Assert.Same(asset, loader.Load(asset.identity.persistentID, typeof(TextAsset))); } [Fact] - public void Tombstone_SurvivesCatalogRestartWithoutOccupyingItsFormerPath() + public void TombstoneSurvivesCatalogRestartWithoutOccupyingItsFormerPath() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "one"); - Guid oldId; + Guid oldID; using (AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) { loader.Rescan(); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/value.txt"), out oldId)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/value.txt"), out oldID)); workspace.DeleteSource("Text/value.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/value.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/value.txt", WatcherChangeTypes.Deleted) ]); } @@ -1496,68 +1726,86 @@ public void Tombstone_SurvivesCatalogRestartWithoutOccupyingItsFormerPath() using AssetLoader restarted = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); restarted.Rescan(); - Assert.True(restarted.TryGetInfo(oldId, out AssetInfo? tombstone)); + Assert.True(restarted.TryGetInfo(oldID, out AssetInfo? tombstone)); Assert.Equal(AssetImportStatus.Missing, tombstone!.status); - Assert.True(restarted.TryGetPersistentId(AssetPath.Project("Text/value.txt"), out Guid newId)); - Assert.NotEqual(oldId, newId); + Assert.True(restarted.TryGetPersistentID(AssetPath.Project("Text/value.txt"), out Guid newID)); + Assert.NotEqual(oldID, newID); } [Fact] - public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord() + public void CatalogRestartPrefersCurrentSourceIdentityOverHistoricalPathRecord() { - using TestWorkspace workspace = new(); - const string path = "Text/identity.txt"; - workspace.WriteText(path, "value"); - Guid historicalId; + using var workspace = new TestWorkspace(); + const string C_PATH = "Text/identity.txt"; + workspace.WriteText(C_PATH, "value"); + Guid historicalID; using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); - Assert.True(first.TryGetPersistentId(AssetPath.Project(path), out historicalId)); + Assert.True(first.TryGetPersistentID(AssetPath.Project(C_PATH), out historicalID)); } - string sidecarPath = workspace.SourcePath(path + ".imeta"); + string sidecarPath = workspace.SourcePath(C_PATH + ".imeta"); MountedSourceMetadata metadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath)); - Guid currentId = Guid.NewGuid(); - metadata.persistentId = currentId; - System.IO.File.WriteAllBytes(sidecarPath, m_serialization.Serialize(metadata)); + File.ReadAllBytes(sidecarPath) + ); + Guid currentID = Guid.NewGuid(); + metadata.persistentId = currentID; + File.WriteAllBytes(sidecarPath, m_serialization.Serialize(metadata)); using (AssetLoader recovered = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { recovered.Rescan(); - Assert.True(recovered.TryGetPersistentId(AssetPath.Project(path), out Guid indexedId)); - Assert.Equal(currentId, indexedId); - Assert.True(recovered.TryGetInfo(historicalId, out AssetInfo? historical)); + Assert.True(recovered.TryGetPersistentID(AssetPath.Project(C_PATH), out Guid indexedID)); + Assert.Equal(currentID, indexedID); + Assert.True(recovered.TryGetInfo(historicalID, out AssetInfo? historical)); Assert.Equal(AssetImportStatus.Missing, historical!.status); } using AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs); + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + ); restarted.Rescan(); - Assert.True(restarted.TryGetPersistentId(AssetPath.Project(path), out Guid stableId)); - Assert.Equal(currentId, stableId); + Assert.True(restarted.TryGetPersistentID(AssetPath.Project(C_PATH), out Guid stableID)); + Assert.Equal(currentID, stableID); MountedSourceMetadata stableMetadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath)); - Assert.Equal(currentId, stableMetadata.persistentId); + File.ReadAllBytes(sidecarPath) + ); + Assert.Equal(currentID, stableMetadata.persistentId); } [Fact] - public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences() + public void CatalogRestartDoesNotPromoteHistoricalTombstonesToMissingReferences() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/removed.txt", "one"); - Guid removedId; + Guid removedID; using (AssetLoader loader = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { loader.Rescan(); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/removed.txt"), out removedId)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/removed.txt"), out removedID)); workspace.DeleteSource("Text/removed.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent( - "Text/removed.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/removed.txt", WatcherChangeTypes.Deleted) ]); } @@ -1577,32 +1825,35 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false - }); + } + ); - Assert.True(restarted.TryGetInfo(removedId, out AssetInfo? tombstone)); + Assert.True(restarted.TryGetInfo(removedID, out AssetInfo? tombstone)); Assert.Equal(AssetImportStatus.Missing, tombstone!.status); - using AssetSourceMountTransaction generation = - restarted.PrepareSourceMounts(restarted.sourceMounts); + using AssetSourceMountTransaction generation = restarted.PrepareSourceMounts(restarted.sourceMounts); generation.Activate(); Assert.Empty(generation.recoveryChanges); Assert.DoesNotContain( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); generation.Complete(); AssetObject explicitlyResolved = ((IAssetReferenceResolver)restarted).Resolve( - removedId, - tombstone.stableAssetTypeId, + removedID, + tombstone.stableAssetTypeID, "Text/removed.txt", typeof(TextAsset), - "$test.reference"); + "$test.reference" + ); Assert.True(explicitlyResolved.isMissing); Assert.Contains( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } finally { @@ -1611,113 +1862,114 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences } [Fact] - public void RestoredSourceAndMetadata_ReactivatesOriginalIdentityInPlace() + public void RestoredSourceAndMetadataReactivatesOriginalIdentityInPlace() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/recover.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); - Guid id = asset.identity.persistentId; - byte[] metadata = System.IO.File.ReadAllBytes(workspace.SourcePath("Text/recover.txt.imeta")); + Guid id = asset.identity.persistentID; + byte[] metadata = File.ReadAllBytes(workspace.SourcePath("Text/recover.txt.imeta")); workspace.DeleteSource("Text/recover.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) ]); workspace.WriteText("Text/recover.txt", "two"); - System.IO.File.WriteAllBytes(workspace.SourcePath("Text/recover.txt.imeta"), metadata); + File.WriteAllBytes(workspace.SourcePath("Text/recover.txt.imeta"), metadata); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) ]); TextAsset restored = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); Assert.Same(asset, restored); - Assert.Equal(id, restored.identity.persistentId); + Assert.Equal(id, restored.identity.persistentID); Assert.False(restored.isMissing); Assert.Equal("two", restored.content); } [Fact] - public void DeleteCreateRenameFallback_PreservesIdentityOnlyWhenFingerprintMatchIsUnique() + public void DeleteCreateRenameFallbackPreservesIdentityOnlyWhenFingerprintMatchIsUnique() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/old.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/old.txt"), out Guid id)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/old.txt"), out Guid id)); workspace.Move("Text/old.txt", "Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/old.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/old.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) ]); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/new.txt"), out Guid movedId)); - Assert.Equal(id, movedId); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Text/old.txt.imeta"))); - Assert.True(System.IO.File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/new.txt"), out Guid movedID)); + Assert.Equal(id, movedID); + Assert.False(File.Exists(workspace.SourcePath("Text/old.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); } [Fact] - public void AmbiguousDeleteCreateRenameFallback_DoesNotGuessAnIdentity() + public void AmbiguousDeleteCreateRenameFallbackDoesNotGuessAnIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/first.txt", "same"); workspace.WriteText("Text/second.txt", "same"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/first.txt"), out Guid firstId)); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/second.txt"), out Guid secondId)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/first.txt"), out Guid firstID)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/second.txt"), out Guid secondID)); workspace.DeleteSource("Text/first.txt"); workspace.DeleteSource("Text/second.txt"); workspace.WriteText("Text/new.txt", "same"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/first.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/second.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/first.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/second.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) ]); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/new.txt"), out Guid newId)); - Assert.NotEqual(firstId, newId); - Assert.NotEqual(secondId, newId); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("Text/new.txt"), out Guid newID)); + Assert.NotEqual(firstID, newID); + Assert.NotEqual(secondID, newID); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/new.txt"), out AssetInfo? newInfo)); Assert.Contains(newInfo!.diagnostics, diagnostic => diagnostic.Contains("matched 2 removed assets", StringComparison.Ordinal)); - Assert.True(loader.TryGetInfo(firstId, out AssetInfo? firstTombstone)); - Assert.True(loader.TryGetInfo(secondId, out AssetInfo? secondTombstone)); + Assert.True(loader.TryGetInfo(firstID, out AssetInfo? firstTombstone)); + Assert.True(loader.TryGetInfo(secondID, out AssetInfo? secondTombstone)); Assert.Equal(AssetImportStatus.Missing, firstTombstone!.status); Assert.Equal(AssetImportStatus.Missing, secondTombstone!.status); } [Fact] - public void Save_PreservesIdentityIncrementsVersionAndRejectsDifferentPath() + public void SavePreservesIdentityIncrementsVersionAndRejectsDifferentPath() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var asset = new MutableAsset { value = "one" }; Assert.True(loader.Save(AssetPath.Project("Data/value.mutableasset"), asset)); - Guid persistentId = asset.identity.persistentId; + Guid persistentID = asset.identity.persistentID; long version = asset.contentVersion; asset.value = "two"; Assert.True(loader.Save(asset)); - Assert.Equal(persistentId, asset.identity.persistentId); + Assert.Equal(persistentID, asset.identity.persistentID); Assert.Equal(version + 1, asset.contentVersion); Assert.Equal("two", workspace.ReadText("Data/value.mutableasset")); - Assert.Same(asset, loader.Load(persistentId, typeof(MutableAsset))); + Assert.Same(asset, loader.Load(persistentID, typeof(MutableAsset))); Assert.Throws(() => loader.Save(AssetPath.Project("Data/copy.mutableasset"), asset)); } [Fact] - public void FailedReimport_KeepsPreviousCanonicalStateAndVersion() + public void FailedReimportKeepsPreviousCanonicalStateAndVersion() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/stable.mutableasset", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); MutableAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Data/stable.mutableasset"), typeof(MutableAsset))); + loader.Load(AssetPath.Project("Data/stable.mutableasset"), typeof(MutableAsset)) + ); long version = asset.contentVersion; workspace.WriteText("Data/stable.mutableasset", "!invalid!"); @@ -1732,22 +1984,24 @@ public void FailedReimport_KeepsPreviousCanonicalStateAndVersion() } [Fact] - public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() + public void FailedReimportPublishesCurrentDiagnosticUntilSuccessfulRetry() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/diagnostic.mutableasset", "valid"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); try { MutableAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Data/diagnostic.mutableasset"), typeof(MutableAsset))); + loader.Load(AssetPath.Project("Data/diagnostic.mutableasset"), typeof(MutableAsset)) + ); workspace.WriteText("Data/diagnostic.mutableasset", "!invalid!"); Assert.False(loader.Import(AssetPath.Project("Data/diagnostic.mutableasset"))); - DiagnosticReport report = Assert.Single(sink.reports.Values.Where(value => - value.source.displayName == "Data/diagnostic.mutableasset")); + DiagnosticReport report = Assert.Single( + sink.reports.Values.Where(value => (value.source.displayName == "Data/diagnostic.mutableasset")) + ); Diagnostic diagnostic = Assert.Single(report.diagnostics); Assert.Equal("ASSET-IMPORT", diagnostic.code); Assert.Equal(DiagnosticSeverity.Error, diagnostic.severity); @@ -1756,7 +2010,8 @@ public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() Assert.True(loader.Import(AssetPath.Project("Data/diagnostic.mutableasset"))); Assert.DoesNotContain( sink.reports.Values, - value => value.source.displayName == "Data/diagnostic.mutableasset"); + value => value.source.displayName == "Data/diagnostic.mutableasset" + ); Assert.Equal("recovered", asset.value); } finally @@ -1768,14 +2023,16 @@ public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() [Fact] public void UnchangedFailedSourceIsNotRetriedUntilItsInputChanges() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/retry.mutableasset", "!invalid!"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); AssetPath path = AssetPath.Project("Data/retry.mutableasset"); Assert.False(loader.Import(path)); int failedAttempts = MutableAssetImporter.attempts; for (int index = 0; index < 5; index++) + { loader.Rescan(); + } Assert.Equal(failedAttempts, MutableAssetImporter.attempts); workspace.WriteText("Data/retry.mutableasset", "repaired"); @@ -1785,40 +2042,45 @@ public void UnchangedFailedSourceIsNotRetriedUntilItsInputChanges() } [Fact] - public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() + public void FailedSavePreservesCommittedSourceMetaArtifactAndVersion() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var asset = new MutableAsset { value = "one" }; Assert.True(loader.Save(AssetPath.Project("Data/rollback.mutableasset"), asset)); - byte[] sourceBefore = System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset")); - byte[] metaBefore = System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta")); - Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "runtime", out AssetArtifactInfo? artifact)); + byte[] sourceBefore = File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset")); + byte[] metaBefore = File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta")); + Assert.True(loader.TryGetArtifact(asset.identity.persistentID, "runtime", out AssetArtifactInfo? artifact)); Assert.NotNull(artifact); byte[] artifactBefore; - using (ArtifactLease before = loader.AcquireArtifact(asset.identity.persistentId, "runtime")) + using (ArtifactLease before = loader.AcquireArtifact(asset.identity.persistentID, "runtime")) + { artifactBefore = before.ReadAllBytes(); + } long versionBefore = asset.contentVersion; asset.value = "!invalid!"; Assert.Throws(() => loader.Save(asset)); - Assert.Equal(sourceBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset"))); - Assert.Equal(metaBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta"))); - using (ArtifactLease after = loader.AcquireArtifact(asset.identity.persistentId, "runtime")) + Assert.Equal(sourceBefore, File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset"))); + Assert.Equal(metaBefore, File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta"))); + using (ArtifactLease after = loader.AcquireArtifact(asset.identity.persistentID, "runtime")) + { Assert.Equal(artifactBefore, after.ReadAllBytes()); + } Assert.Equal(versionBefore, asset.contentVersion); } [Fact] - public void RuntimeDependencyRetention_KeepsDependencyAliveWhileRootIsReferenced() + public void RuntimeDependencyRetentionKeepsDependencyAliveWhileRootIsReferenced() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/dependency.txt", "dependency"); workspace.WriteText("Graphs/root.depgraph", "Text/dependency.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( - loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset))); + loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset)) + ); Assert.Equal(0, loader.UnloadUnusedAssets()); Assert.Equal(2, loader.GetLoadedPaths().Count); @@ -1826,12 +2088,12 @@ public void RuntimeDependencyRetention_KeepsDependencyAliveWhileRootIsReferenced } [Fact] - public void UnusedRuntimeDependencyCycle_IsCollectedAsAUnit() + public void UnusedRuntimeDependencyCycleIsCollectedAsAUnit() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", "Graphs/b.depgraph"); workspace.WriteText("Graphs/b.depgraph", "Graphs/a.depgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); (WeakReference first, WeakReference second) = LoadCycleWithoutEscaping(loader); int released = loader.UnloadUnusedAssets(); @@ -1843,12 +2105,12 @@ public void UnusedRuntimeDependencyCycle_IsCollectedAsAUnit() } [Fact] - public void ReferenceDiagnostics_DoNotKeepAssetsAlive() + public void ReferenceDiagnosticsDoNotKeepAssetsAlive() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/dependency.txt", "dependency"); workspace.WriteText("Graphs/root.depgraph", "Text/dependency.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); WeakReference weak = LoadAndInspectWithoutEscaping(loader); Assert.Equal(2, loader.UnloadUnusedAssets()); @@ -1856,11 +2118,11 @@ public void ReferenceDiagnostics_DoNotKeepAssetsAlive() } [Fact] - public void Dispose_ReleasesRuntimeResourcesExactlyOnce() + public void DisposeReleasesRuntimeResourcesExactlyOnce() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Hooks/value.hookasset", "value"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Hooks/value.hookasset"), typeof(HookAsset))); loader.Dispose(); @@ -1872,80 +2134,96 @@ public void Dispose_ReleasesRuntimeResourcesExactlyOnce() } [Fact] - public void Rescan_TracksUnsupportedSourcesAndFolderIdentityWithoutFakeArtifacts() + public void RescanTracksUnsupportedSourcesAndFolderIdentityWithoutFakeArtifacts() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); Directory.CreateDirectory(workspace.SourcePath("EmptyFolder")); workspace.WriteText("Unknown/value.unknown", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("EmptyFolder"), out AssetInfo? folder)); Assert.Equal(AssetSourceKind.Directory, folder!.sourceKind); Assert.Equal(AssetImportStatus.Imported, folder.status); - Assert.True(System.IO.File.Exists(workspace.SourcePath("EmptyFolder.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("EmptyFolder.imeta"))); Assert.True(folder.artifactKey.isEmpty); Assert.True(loader.TryGetInfo(AssetPath.Project("Unknown/value.unknown"), out AssetInfo? unsupported)); Assert.Equal(AssetImportStatus.Unsupported, unsupported!.status); - Assert.Equal(Guid.Empty, unsupported.persistentId); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Unknown/value.unknown.imeta"))); + Assert.Equal(Guid.Empty, unsupported.persistentID); + Assert.False(File.Exists(workspace.SourcePath("Unknown/value.unknown.imeta"))); Assert.True(unsupported.artifactKey.isEmpty); } [Fact] - public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMissingWarning() + public void RescanRecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMissingWarning() { - using TestWorkspace workspace = new(); - const string path = "Deferred/value.unavailable"; - workspace.WriteText(path, "source awaiting its module generation"); + using var workspace = new TestWorkspace(); + const string C_PATH = "Deferred/value.unavailable"; + workspace.WriteText(C_PATH, "source awaiting its module generation"); using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); - Assert.True(first.TryGetInfo(AssetPath.Project(path), out AssetInfo? unsupported)); - Assert.Equal(Guid.Empty, unsupported!.persistentId); + Assert.True(first.TryGetInfo(AssetPath.Project(C_PATH), out AssetInfo? unsupported)); + Assert.Equal(Guid.Empty, unsupported!.persistentID); } - Guid persistentId = Guid.NewGuid(); - Guid expectedStableTypeId = Guid.NewGuid(); - System.IO.File.WriteAllBytes( - workspace.SourcePath(path + ".imeta"), + Guid persistentID = Guid.NewGuid(); + Guid expectedStableTypeID = Guid.NewGuid(); + File.WriteAllBytes( + workspace.SourcePath(C_PATH + ".imeta"), m_serialization.Serialize(new MountedSourceMetadata { - persistentId = persistentId, + persistentId = persistentID, sourceKind = (int)AssetSourceKind.File, importerId = "tests.unavailable-generation" - })); + }) + ); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); try { using (AssetLoader recovered = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { recovered.Rescan(); - Assert.True(recovered.TryGetInfo(persistentId, out AssetInfo? pending)); - Assert.Equal(path, pending!.assetPath.ToString()); - Assert.Equal("tests.unavailable-generation", pending.importerId); + Assert.True(recovered.TryGetInfo(persistentID, out AssetInfo? pending)); + Assert.Equal(C_PATH, pending!.assetPath.ToString()); + Assert.Equal("tests.unavailable-generation", pending.importerID); Assert.Equal(AssetImportStatus.Pending, pending.status); AssetObject placeholder = recovered.ResolveReference( - persistentId, - expectedStableTypeId, - path, - typeof(AssetObject)); + persistentID, + expectedStableTypeID, + C_PATH, + typeof(AssetObject) + ); Assert.True(placeholder.isMissing); Assert.DoesNotContain( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } using AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs); + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + ); restarted.Rescan(); - Assert.True(restarted.TryGetInfo(persistentId, out AssetInfo? retained)); - Assert.Equal("tests.unavailable-generation", retained!.importerId); + Assert.True(restarted.TryGetInfo(persistentID, out AssetInfo? retained)); + Assert.Equal("tests.unavailable-generation", retained!.importerID); } finally { @@ -1954,21 +2232,25 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi } [Fact] - public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() + public void RescanPreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() { - using TestWorkspace workspace = new(); - const string path = "Deferred/value.deferredasset"; - workspace.WriteText(path, "last-good source"); - Guid persistentId; - Guid stableTypeId; + using var workspace = new TestWorkspace(); + const string C_PATH = "Deferred/value.deferredasset"; + workspace.WriteText(C_PATH, "last-good source"); + Guid persistentID; + Guid stableTypeID; AssetArtifactKey artifactKey; using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); - Assert.True(first.TryGetInfo(AssetPath.Project(path), out AssetInfo? imported)); - persistentId = imported!.persistentId; - stableTypeId = imported.stableAssetTypeId; + Assert.True(first.TryGetInfo(AssetPath.Project(C_PATH), out AssetInfo? imported)); + persistentID = imported!.persistentID; + stableTypeID = imported.stableAssetTypeID; artifactKey = imported.artifactKey; Assert.False(artifactKey.isEmpty); } @@ -1979,26 +2261,26 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() m_modules.Rebuild(); try { - using (AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { - restarted.Rescan(); - - Assert.True(restarted.TryGetInfo(AssetPath.Project(path), out AssetInfo? preserved)); - Assert.Equal(persistentId, preserved!.persistentId); - Assert.Equal(stableTypeId, preserved.stableAssetTypeId); - Assert.Equal(AssetImportStatus.Imported, preserved.status); - Assert.Equal(artifactKey, preserved.artifactKey); - AssetObject resolved = restarted.ResolveReference( - persistentId, - stableTypeId, - path, - typeof(AssetObject)); - Assert.False(resolved.isMissing); - Assert.DoesNotContain( - sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); - } + using AssetLoader restarted = workspace.CreateLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + ); + restarted.Rescan(); + + Assert.True(restarted.TryGetInfo(AssetPath.Project(C_PATH), out AssetInfo? preserved)); + Assert.Equal(persistentID, preserved!.persistentID); + Assert.Equal(stableTypeID, preserved.stableAssetTypeID); + Assert.Equal(AssetImportStatus.Imported, preserved.status); + Assert.Equal(artifactKey, preserved.artifactKey); + AssetObject resolved = restarted.ResolveReference(persistentID, stableTypeID, C_PATH, typeof(AssetObject)); + Assert.False(resolved.isMissing); + Assert.DoesNotContain( + sink.reports.Values.SelectMany(static report => report.diagnostics), + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } finally { @@ -2009,15 +2291,15 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() } [Fact] - public void SourceMetadata_RestoresPersistentIdentityWhenLibraryIsRebuilt() + public void SourceMetadataRestoresPersistentIdentityWhenLibraryIsRebuilt() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "value"); Guid id; using (AssetLoader first = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) { first.Rescan(); - Assert.True(first.TryGetPersistentId(AssetPath.Project("Text/value.txt"), out id)); + Assert.True(first.TryGetPersistentID(AssetPath.Project("Text/value.txt"), out id)); } Directory.Delete(workspace.libraryRoot, recursive: true); Directory.CreateDirectory(workspace.libraryRoot); @@ -2025,72 +2307,72 @@ public void SourceMetadata_RestoresPersistentIdentityWhenLibraryIsRebuilt() using AssetLoader rebuilt = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); rebuilt.Rescan(); - Assert.True(rebuilt.TryGetPersistentId(AssetPath.Project("Text/value.txt"), out Guid restored)); + Assert.True(rebuilt.TryGetPersistentID(AssetPath.Project("Text/value.txt"), out Guid restored)); Assert.Equal(id, restored); } [Fact] - public void ContentAddressedStore_DeduplicatesEqualImportsAndCollectsUnreachableBundles() + public void ContentAddressedStoreDeduplicatesEqualImportsAndCollectsUnreachableBundles() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/first.txt", "same"); workspace.WriteText("Text/second.txt", "same"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/first.txt"), out AssetInfo? first)); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/second.txt"), out AssetInfo? second)); Assert.Equal(first!.artifactKey, second!.artifactKey); - Assert.True(loader.TryGetArtifact(first.persistentId, "runtime", out AssetArtifactInfo? oldArtifact)); + Assert.True(loader.TryGetArtifact(first.persistentID, "runtime", out AssetArtifactInfo? oldArtifact)); Assert.NotNull(oldArtifact); workspace.WriteText("Text/first.txt", "changed"); Assert.True(loader.Import(AssetPath.Project("Text/first.txt"))); - Assert.True(loader.TryGetArtifact(first.persistentId, "runtime", out AssetArtifactInfo? currentArtifact)); + Assert.True(loader.TryGetArtifact(first.persistentID, "runtime", out AssetArtifactInfo? currentArtifact)); Assert.NotNull(currentArtifact); Assert.NotEqual(oldArtifact.key, currentArtifact.key); string oldPath = workspace.FindArtifactFile(oldArtifact); - Assert.True(System.IO.File.Exists(oldPath)); + Assert.True(File.Exists(oldPath)); Assert.Equal(0, loader.CollectArtifacts(TimeSpan.Zero, maximumSizeBytes: 0)); - Assert.True(System.IO.File.Exists(oldPath)); + Assert.True(File.Exists(oldPath)); workspace.DeleteSource("Text/second.txt"); - System.IO.File.Delete(workspace.SourcePath("Text/second.txt.imeta")); + File.Delete(workspace.SourcePath("Text/second.txt.imeta")); loader.Rescan(); Assert.True(loader.CollectArtifacts(TimeSpan.Zero, maximumSizeBytes: 0) >= 1); - Assert.False(System.IO.File.Exists(oldPath)); - Assert.True(System.IO.File.Exists(workspace.FindArtifactFile(currentArtifact))); + Assert.False(File.Exists(oldPath)); + Assert.True(File.Exists(workspace.FindArtifactFile(currentArtifact))); } [Fact] public void ArtifactLookupRejectsWrongLengthAndExportRejectsSameLengthCorruption() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/value.txt"), out AssetInfo? info)); - Assert.True(loader.TryGetArtifact(info!.persistentId, "runtime", out AssetArtifactInfo? artifact)); + Assert.True(loader.TryGetArtifact(info!.persistentID, "runtime", out AssetArtifactInfo? artifact)); string path = workspace.FindArtifactFile(artifact!); - byte[] original = System.IO.File.ReadAllBytes(path); + byte[] original = File.ReadAllBytes(path); - System.IO.File.WriteAllBytes(path, [1]); - Assert.Throws(() => loader.TryGetArtifact(info.persistentId, "runtime", out _)); + File.WriteAllBytes(path, [1]); + Assert.Throws(() => loader.TryGetArtifact(info.persistentID, "runtime", out _)); byte[] changed = (byte[])original.Clone(); changed[0] ^= 0x01; - System.IO.File.WriteAllBytes(path, changed); - Assert.True(loader.TryGetArtifact(info.persistentId, "runtime", out _)); + File.WriteAllBytes(path, changed); + Assert.True(loader.TryGetArtifact(info.persistentID, "runtime", out _)); Assert.Throws(() => loader.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "CorruptedRuntime"))); - System.IO.File.WriteAllBytes(path, original); - Assert.True(loader.TryGetArtifact(info.persistentId, "runtime", out _)); + File.WriteAllBytes(path, original); + Assert.True(loader.TryGetArtifact(info.persistentID, "runtime", out _)); loader.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "ValidRuntime")); } [Fact] - public async Task AggregateBuildProcessor_ProducesStableContentAddressedOutput() + public async Task AggregateBuildProcessorProducesStableContentAddressedOutput() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/input.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/input.txt"), out AssetInfo? input)); Assert.NotNull(input); @@ -2108,7 +2390,7 @@ private static (WeakReference first, WeakReference second) LoadCycleWithoutEscap { AssetObject first = loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset))!; AssetDependency secondDescriptor = Assert.Single(loader.GetDependencies(first)); - AssetObject second = loader.Load(secondDescriptor.persistentId, typeof(DependencyAsset))!; + AssetObject second = loader.Load(secondDescriptor.persistentID, typeof(DependencyAsset))!; return (new WeakReference(first), new WeakReference(second)); } @@ -2117,19 +2399,60 @@ private static WeakReference LoadAndInspectWithoutEscaping(AssetLoader loader) { AssetObject root = loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset))!; AssetDependency descriptor = Assert.Single(loader.GetDependencies(root)); - AssetObject dependency = loader.Load(descriptor.persistentId, typeof(TextAsset))!; + AssetObject dependency = loader.Load(descriptor.persistentID, typeof(TextAsset))!; AssetReferenceInfo info = loader.GetReferenceInfo(dependency); Assert.Equal(1, info.knownReferenceCount); Assert.Equal(AssetReferenceKind.AssetDependency, info.references[0].kind); return new WeakReference(root); } + private sealed class CatalogObserver : IAssemblyCatalogParticipant + { + internal Action? prepare; + internal Action? activate; + + public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) + { + prepare?.Invoke(); + return new Observation(activate); + } + + private sealed class Observation(Action? activate) : IAssemblyCatalogTransaction + { + public object? context => null; + + public void Activate() => activate?.Invoke(); + + public void Complete() {} + + public void Rollback() {} + } + } + + private sealed class IdentityConflict : IdentityObject; + + private sealed class MountedSourceMetadata : ISerializable + { + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; + } + private sealed class TestWorkspace : IDisposable { private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoAssetLoaderTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); internal TestWorkspace() { @@ -2137,27 +2460,43 @@ internal TestWorkspace() Directory.CreateDirectory(libraryRoot); } + public void Dispose() + { + SlowAssetImporter.ALLOW_IMPORT.Set(); + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: true); + } + } + internal string assetRoot => Path.Combine(m_root, "Assets"); internal string libraryRoot => Path.Combine(m_root, "Library"); + internal AssetLoader CreateLoader( TypeCatalog types, SerializationRegistry serialization, IdentityAllocator identities, DiagnosticHub diagnostics, LogRouter logs - ) - => new(types, serialization, identities, diagnostics, logs, assetRoot, libraryRoot); + ) => new(types, serialization, identities, diagnostics, logs, assetRoot, libraryRoot); + internal string SourcePath(string relativePath) => Path.Combine(assetRoot, relativePath); internal string FindArtifactFile(AssetArtifactInfo artifact) { string key = artifact.key.value; - string directory = Path.Combine(libraryRoot, "Artifacts", key[..2].ToLowerInvariant(), - key[2..4].ToLowerInvariant(), key, "outputs"); - return Directory.EnumerateFiles(directory).Single(path => + string directory = Path.Combine( + libraryRoot, + "Artifacts", + key[..2].ToLowerInvariant(), + key[2..4].ToLowerInvariant(), + key, + "outputs" + ); + return Directory.EnumerateFiles(directory).Single(path => ( new FileInfo(path).Length == artifact.length - && Convert.ToHexString(System.Security.Cryptography.SHA256.HashData( - System.IO.File.ReadAllBytes(path))) == artifact.contentHash); + && Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))) == artifact.contentHash + )); } internal void WriteText( @@ -2166,10 +2505,10 @@ string content ) { string path = SourcePath(relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, content, new UTF8Encoding(false)); + File.WriteAllText(path, content, new UTF8Encoding(false)); } - internal string ReadText(string relativePath) => System.IO.File.ReadAllText(SourcePath(relativePath)); + internal string ReadText(string relativePath) => File.ReadAllText(SourcePath(relativePath)); internal void Move( string oldRelativePath, @@ -2177,422 +2516,25 @@ string newRelativePath ) { string target = SourcePath(newRelativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - System.IO.File.Move(SourcePath(oldRelativePath), target); + File.Move(SourcePath(oldRelativePath), target); } internal void DeleteSource(string relativePath) { string path = SourcePath(relativePath); - if (System.IO.File.Exists(path)) - System.IO.File.Delete(path); - } - - public void Dispose() - { - SlowAssetImporter.allowImport.Set(); - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: true); + if (File.Exists(path)) + { + File.Delete(path); + } } } private sealed class TestDiagnosticSink : IDiagnosticSink { - internal Dictionary reports { get; } = new(StringComparer.Ordinal); - - public void Replace(DiagnosticReport report) - => reports[report.source.id] = report; - - public void Clear(DiagnosticSource source) - => reports.Remove(source.id); - } -} - -[StableTypeId("501988d0-c069-4dcf-97f6-e899b24e5801")] -internal sealed class PrivateConstructorAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.private-constructor")] -internal sealed class PrivateConstructorAssetImporter : AssetImporter -{ - private static readonly IReadOnlyList s_extensions = [".privateasset"]; - - private PrivateConstructorAssetImporter() - { - } - - public override IReadOnlyList supportedExtensions => s_extensions; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new PrivateConstructorAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("8d0d31ab-f9ea-4297-b865-e9014ae82a94")] -internal sealed class DeferredAsset : AssetObject; - -[StableTypeId("79cef88a-3d5a-4c36-8095-a59cae3c641c")] -internal sealed class ExtensionDependentAsset : AssetObject; - -[AssetImporter("tests.extension-dependent")] -internal sealed class ExtensionDependentImporter : AssetImporter -{ - internal static bool available; - internal static int attempts; - public override IReadOnlyList supportedExtensions { get; } = [".extensionasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - attempts++; - if (!available) - throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); - output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("tests.extension-consumer")] -internal sealed class ExtensionConsumerImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".extensiondependent"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string source = context.ReadUtf8Text(); - if (Guid.TryParse(source, out Guid id)) - _ = context.references.Resolve(id, context.services.GetStableTypeId(), - "surface.extensionasset", typeof(ExtensionDependentAsset), "$.shader"); - else - _ = context.ResolveDependency(AssetPath.Project(source)); - output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.deferred")] -internal sealed class DeferredAssetImporter : AssetImporter -{ - private static readonly IReadOnlyList s_extensions = [".deferredasset"]; - - internal static bool isAvailable { get; set; } = true; - - public override IReadOnlyList supportedExtensions - => isAvailable ? s_extensions : Array.Empty(); - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DeferredAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("a49b603c-0f5f-4861-903a-3819513da002")] -internal sealed class DependencyAsset : AssetObject; - -[AssetImporter("inno.tests.runtime-dependency")] -internal sealed class DependencyAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".depgraph"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string dependency = context.ReadUtf8Text().Trim(); - if (!string.IsNullOrWhiteSpace(dependency)) - output.DependsOnAsset(AssetPath.Parse(dependency)); - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.runtime-dependency-alternate")] -internal sealed class AlternateDependencyAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".depgraph2"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.build-input")] -internal sealed class BuildInputAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".buildinput"]; - public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string text = context.ReadUtf8Text(); - if (text == "failed") - throw new InvalidDataException("Required authoring input failed."); - if (Guid.TryParse(text, out Guid dependency)) - context.DependsOnArtifact(dependency); - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("authoring", context.sourceBytes, cancellationToken, AssetDeploymentScope.AuthoringOnly); - } -} - -[AssetImporter("inno.tests.mixed-scope")] -internal sealed class MixedScopeAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".mixedscope"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DependencyAsset()); - if (context.ReadUtf8Text() == "authoring") - { - output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); - return output.WriteArtifactAsync("graph", context.sourceBytes, cancellationToken, - AssetDeploymentScope.AuthoringOnly); - } - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.build-consumer")] -internal sealed class BuildConsumerAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".buildconsumer"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - context.DependsOnArtifact(Guid.Parse(context.ReadUtf8Text())); - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("a80d363f-8e49-4615-89ee-589613b91c03")] -internal sealed class ImportGraphAsset : AssetObject; - -[AssetImporter("inno.tests.import-dependency")] -internal sealed class ImportGraphAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".importgraph"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string dependency = context.ReadUtf8Text().Trim(); - if (!string.IsNullOrWhiteSpace(dependency)) - output.DependsOnSource(AssetPath.Parse(dependency)); - output.SetAsset(new ImportGraphAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("490def27-4cdd-48a0-b324-9b7438600404")] -internal sealed class SlowAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.slow")] -internal sealed class SlowAssetImporter : AssetImporter -{ - internal static readonly ManualResetEventSlim importStarted = new(false); - internal static readonly ManualResetEventSlim allowImport = new(false); - internal static int importCount; - - public override IReadOnlyList supportedExtensions { get; } = [".slowasset"]; - - internal static void Reset() - { - importCount = 0; - importStarted.Reset(); - allowImport.Reset(); - } - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - Interlocked.Increment(ref importCount); - importStarted.Set(); - if (!allowImport.Wait(TimeSpan.FromSeconds(5))) - throw new TimeoutException("The slow importer test gate was not released."); - output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("fa17dc36-b9cc-4187-b5da-72906ad00505")] -internal sealed class MutableAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.mutable")] -internal sealed class MutableAssetImporter : AssetImporter -{ - internal static int attempts; - public override IReadOnlyList supportedExtensions { get; } = [".mutableasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - attempts++; - string value = context.ReadUtf8Text(); - if (value == "!invalid!") - throw new InvalidDataException("The mutable asset source is invalid."); - output.SetAsset(new MutableAsset { value = value }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } - - protected override ValueTask?> ExportAsync( - AssetExportContext context, - MutableAsset asset, - CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); -} - -[StableTypeId("9f9f5f9f-4d86-414f-9ff9-78ad8ec60606")] -internal sealed class HookAsset : AssetObject -{ - internal int payloadChangeCount; - internal int unloadingCount; - internal int pendingUnloads; - internal bool failUnloading; - internal bool retirementExpired; - - protected override void OnRuntimePayloadChanged( - ReadOnlyMemory previousPayload, - ReadOnlyMemory currentPayload - ) - => Interlocked.Increment(ref payloadChangeCount); - - protected override void OnUnloading() - { - Interlocked.Increment(ref unloadingCount); - if (retirementExpired) - throw new RetirementTimeoutException("The test asset work exceeded its retirement deadline."); - if (pendingUnloads > 0) - { - pendingUnloads--; - throw new RetirementPendingException("The test asset still owns unfinished work."); - } - if (failUnloading) - throw new InvalidOperationException("The test asset release failed."); - } -} + public void Replace(DiagnosticReport report) => reports[report.source.id] = report; -[AssetImporter("inno.tests.hook")] -internal sealed class HookAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".hookasset"]; + public void Clear(DiagnosticSource source) => reports.Remove(source.id); - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new HookAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -internal static class ImporterConflictProbe -{ - internal static bool duplicateExtension; -} - -[StableTypeId("da675da1-9276-40c4-9964-0eb4b8ff9a07")] -internal sealed class ImporterConflictAsset : AssetObject; - -[AssetImporter("inno.tests.conflict-a")] -internal sealed class ImporterConflictAssetImporterA : AssetImporter -{ - public override IReadOnlyList supportedExtensions => - ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probea"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.conflict-b")] -internal sealed class ImporterConflictAssetImporterB : AssetImporter -{ - public override IReadOnlyList supportedExtensions => - ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probeb"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeId("8f87f452-203e-4cd4-9c91-c93af4802141")] -internal sealed class TestBuildDefinitionAsset : AssetObject -{ - [SerializableProperty] - internal string label { get; set; } = string.Empty; -} - -[AssetBuildProcessor("inno.tests.aggregate-build")] -internal sealed class TestBuildProcessor : AssetBuildProcessor -{ - protected override ValueTask BuildAsync( - AssetBuildContext context, - AssetArtifactWriter output, - CancellationToken cancellationToken - ) { - string value = context.definition.label + ":" + context.inputs.Count; - return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken); + internal Dictionary reports { get; } = new(StringComparer.Ordinal); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs new file mode 100644 index 000000000..154e90b89 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.build-consumer")] +internal sealed class BuildConsumerAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".buildconsumer"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + context.DependsOnArtifact(Guid.Parse(context.ReadUtf8Text())); + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs new file mode 100644 index 000000000..c9d28fde2 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.build-input")] +internal sealed class BuildInputAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".buildinput"]; + public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string text = context.ReadUtf8Text(); + if (text == "failed") + { + throw new InvalidDataException("Required authoring input failed."); + } + if (Guid.TryParse(text, out Guid dependency)) + { + context.DependsOnArtifact(dependency); + } + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("authoring", context.sourceBytes, AssetDeploymentScope.AuthoringOnly, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs new file mode 100644 index 000000000..e4ab0b97a --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +internal sealed class ClipContribution : ISerializable +{ + [SerializableProperty] + public TextAsset? clip { get; set; } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs new file mode 100644 index 000000000..6a266e1f4 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("2c7288db-eb9e-43a5-9894-bf9d10b22a2d")] +[ProjectSettingDefinition("tests.settings.clip")] +internal sealed class ClipSettings : ClipSettingsBase +{ + internal static readonly Guid TYPE_ID = new("2c7288db-eb9e-43a5-9894-bf9d10b22a2d"); + internal static ProjectSettingID id => new("tests.settings.clip"); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs new file mode 100644 index 000000000..ae837f583 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs @@ -0,0 +1,12 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +internal abstract class ClipSettingsBase : ISerializable +{ + [SerializableProperty] + public TextAsset? clip { get; set; } + + [SerializableProperty] + public string[] labels { get; set; } = []; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs new file mode 100644 index 000000000..c43f842b9 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using Inno.Core.Settings; + +namespace Inno.Assets.Pipeline.Tests; + +[ProjectSettingComposer("tests.settings.composed-clip")] +internal sealed class ClipSettingsComposer : ProjectSettingComposer +{ + protected override ClipContribution CaptureContribution( + ComposedClipSettings baseline, + ComposedClipSettings value + ) => new() { clip = value.clip }; + + protected override bool IsEmpty(ClipContribution contribution) => contribution.clip is null; + + protected override void Compose( + ComposedClipSettings target, + IReadOnlyList> contributions + ) { + foreach (ProjectSettingContribution contribution in contributions) + { + target.clip = contribution.value.clip; + } + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs new file mode 100644 index 000000000..025f6e067 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs @@ -0,0 +1,11 @@ +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("cbeec86a-29da-4894-915f-b6239086ee05")] +[ProjectSettingDefinition("tests.settings.composed-clip")] +internal sealed class ComposedClipSettings : ClipSettingsBase +{ + internal static ProjectSettingID id => new("tests.settings.composed-clip"); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs new file mode 100644 index 000000000..a5f6b2e34 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("bdb3db71-e9cb-4d46-839b-3cbe302c5555")] +internal sealed class ConfiguredAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs new file mode 100644 index 000000000..f86a106ea --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.configured")] +internal sealed class ConfiguredImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".configured"]; + + public override ISerializable CreateImportSettings() => new ConfiguredSettings(); + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + ConfiguredSettings settings = (ConfiguredSettings)context.importSettings!; + if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); + string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; + if (settings.lookup is not null) value += ":" + settings.lookup.content; + output.SetAsset(new ConfiguredAsset { value = value }); + return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs new file mode 100644 index 000000000..7e5a02f82 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("f58eaeea-4bd5-4f3a-a7c0-c5a5414a6bb4")] +internal sealed class ConfiguredSettings : ISerializable +{ + [SerializableProperty] + internal int multiplier { get; set; } = 1; + + [SerializableProperty] + internal TextAsset? lookup { get; set; } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs new file mode 100644 index 000000000..4f721ab56 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("8d0d31ab-f9ea-4297-b865-e9014ae82a94")] +internal sealed class DeferredAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs new file mode 100644 index 000000000..be7792d5d --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.deferred")] +internal sealed class DeferredAssetImporter : AssetImporter +{ + private static readonly IReadOnlyList EXTENSIONS = [".deferredasset"]; + + public override IReadOnlyList supportedExtensions => isAvailable ? EXTENSIONS : []; + + internal static bool isAvailable { get; set; } = true; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DeferredAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs new file mode 100644 index 000000000..16e7c8d3b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("a49b603c-0f5f-4861-903a-3819513da002")] +internal sealed class DependencyAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs new file mode 100644 index 000000000..0e64742c4 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.runtime-dependency")] +internal sealed class DependencyAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".depgraph"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string dependency = context.ReadUtf8Text().Trim(); + if (!string.IsNullOrWhiteSpace(dependency)) + { + output.DependsOnAsset(AssetPath.Parse(dependency)); + } + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs new file mode 100644 index 000000000..cef26d308 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.extension-consumer")] +internal sealed class ExtensionConsumerImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".extensiondependent"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string source = context.ReadUtf8Text(); + if (Guid.TryParse(source, out Guid id)) + { + _ = context.references.Resolve( + id, + context.services.GetStableTypeID(), + "surface.extensionasset", + typeof(ExtensionDependentAsset), + "$.shader" + ); + } + else + { + _ = context.ResolveDependency(AssetPath.Project(source)); + } + output.SetAsset(new ExtensionDependentAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs new file mode 100644 index 000000000..214c3c0b8 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("79cef88a-3d5a-4c36-8095-a59cae3c641c")] +internal sealed class ExtensionDependentAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs new file mode 100644 index 000000000..65800417f --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.extension-dependent")] +internal sealed class ExtensionDependentImporter : AssetImporter +{ + internal static bool available; + internal static int attempts; + public override IReadOnlyList supportedExtensions { get; } = [".extensionasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + attempts++; + if (!available) + { + throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); + } + output.SetAsset(new ExtensionDependentAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs new file mode 100644 index 000000000..a69e57461 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs @@ -0,0 +1,39 @@ +using System; +using System.Threading; +using Inno.Core.Execution; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("9f9f5f9f-4d86-414f-9ff9-78ad8ec60606")] +internal sealed class HookAsset : AssetObject +{ + internal int payloadChangeCount; + internal int unloadingCount; + internal int pendingUnloads; + internal bool failUnloading; + internal bool retirementExpired; + + protected override void OnRuntimePayloadChanged( + ReadOnlyMemory previousPayload, + ReadOnlyMemory currentPayload + ) => Interlocked.Increment(ref payloadChangeCount); + + protected override void OnUnloading() + { + Interlocked.Increment(ref unloadingCount); + if (retirementExpired) + { + throw new RetirementTimeoutException("The test asset work exceeded its retirement deadline."); + } + if (pendingUnloads > 0) + { + pendingUnloads--; + throw new RetirementPendingException("The test asset still owns unfinished work."); + } + if (failUnloading) + { + throw new InvalidOperationException("The test asset release failed."); + } + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs new file mode 100644 index 000000000..294f60729 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.hook")] +internal sealed class HookAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".hookasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new HookAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs new file mode 100644 index 000000000..45cf43c4c --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("a80d363f-8e49-4615-89ee-589613b91c03")] +internal sealed class ImportGraphAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs new file mode 100644 index 000000000..707609198 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.import-dependency")] +internal sealed class ImportGraphAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".importgraph"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string dependency = context.ReadUtf8Text().Trim(); + if (!string.IsNullOrWhiteSpace(dependency)) + { + output.DependsOnSource(AssetPath.Parse(dependency)); + } + output.SetAsset(new ImportGraphAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs index 094818c95..ab88cf065 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs @@ -1,13 +1,8 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Collections.Generic; using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -using Inno.Assets; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Identity; using Inno.Core.Logging; @@ -15,8 +10,6 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class ImportSettingsTests @@ -26,16 +19,16 @@ public void SettingsRoundTripReimportAndResetWithoutChangingSourceOrIdentity() { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); - Guid identity = asset.identity.persistentId; + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + Guid identity = asset.identity.persistentID; AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); - var settings = Assert.IsType(snapshot.value); + ConfiguredSettings settings = Assert.IsType(snapshot.value); Assert.Equal(1, settings.multiplier); settings.multiplier = 7; Assert.Equal(1, Assert.IsType(loader.GetImportSettings(Fixture.path).value).multiplier); Assert.True(loader.SaveImportSettings(Fixture.path, settings, snapshot.fingerprint)); Assert.Equal("7:source", asset.value); - Assert.Equal(identity, asset.identity.persistentId); + Assert.Equal(identity, asset.identity.persistentID); Assert.Equal("source", File.ReadAllText(fixture.sourcePath)); AssetImportSettingsSnapshot updated = loader.GetImportSettings(Fixture.path); Assert.NotEqual(snapshot.fingerprint, updated.fingerprint); @@ -53,12 +46,12 @@ public void SettingsSurviveColdLoaderAndLibraryRecreation() Assert.True(loader.Import(Fixture.path)); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = 12 }, snapshot.fingerprint)); - identity = loader.Load(Fixture.path, typeof(ConfiguredAsset))!.identity.persistentId; + identity = loader.Load(Fixture.path, typeof(ConfiguredAsset))!.identity.persistentID; } using AssetLoader cold = fixture.CreateLoader("OtherLibrary"); - var asset = Assert.IsType(cold.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(cold.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.Equal("12:source", asset.value); - Assert.Equal(identity, asset.identity.persistentId); + Assert.Equal(identity, asset.identity.persistentID); } [Fact] @@ -70,8 +63,11 @@ public void StaleSettingsSnapshotCannotOverwriteNewerSidecar() AssetImportSettingsSnapshot original = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = 2 }, original.fingerprint)); byte[] current = File.ReadAllBytes(fixture.sourcePath + ".imeta"); - Assert.Throws(() => loader.SaveImportSettings(Fixture.path, - new ConfiguredSettings { multiplier = 3 }, original.fingerprint)); + Assert.Throws(() => loader.SaveImportSettings( + Fixture.path, + new ConfiguredSettings { multiplier = 3 }, + original.fingerprint + )); Assert.Equal(current, File.ReadAllBytes(fixture.sourcePath + ".imeta")); } @@ -80,7 +76,7 @@ public void InvalidSettingsPersistWhilePreviousArtifactRemainsLastGood() { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.True(loader.TryGetInfo(Fixture.path, out AssetInfo? original)); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.False(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = -1 }, snapshot.fingerprint)); @@ -97,7 +93,7 @@ public void SidecarChangeInvalidatesArtifactWithoutSourceChangeAndSelfNotificati { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); byte[] first = File.ReadAllBytes(fixture.sourcePath + ".imeta"); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = 2 }, snapshot.fingerprint)); @@ -116,8 +112,8 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() using var fixture = new Fixture(); File.WriteAllText(Path.Combine(fixture.assetRoot, "lookup.txt"), "first"); using AssetLoader loader = fixture.CreateLoader(); - var dependency = Assert.IsType(loader.Load(AssetPath.Project("lookup.txt"), typeof(TextAsset))); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + TextAsset dependency = Assert.IsType(loader.Load(AssetPath.Project("lookup.txt"), typeof(TextAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { lookup = dependency }, snapshot.fingerprint)); Assert.Contains(AssetPath.Project("lookup.txt"), loader.GetImportDependencies(asset)); @@ -125,7 +121,7 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() Assert.Equal("1:source:first", asset.value); File.WriteAllText(Path.Combine(fixture.assetRoot, "lookup.txt"), "second"); Assert.True(loader.Import(AssetPath.Project("lookup.txt"))); - var reloaded = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset reloaded = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.Equal("1:source:second", reloaded.value); } @@ -133,9 +129,12 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() public void ReadOnlySourcesAllowViewingButRejectSettingsWrites() { using var fixture = new Fixture(); - using (AssetLoader writer = fixture.CreateLoader()) Assert.True(writer.Import(Fixture.path)); + using (AssetLoader writer = fixture.CreateLoader()) + { + Assert.True(writer.Import(Fixture.path)); + } byte[] metadata = File.ReadAllBytes(fixture.sourcePath + ".imeta"); - var source = new AssetSourceId("tests.readonly.settings"); + var source = new AssetSourceID("tests.readonly.settings"); using AssetLoader reader = fixture.CreateReadOnlyLoader(source); var path = new AssetPath(source, "value.configured"); AssetImportSettingsSnapshot snapshot = reader.GetImportSettings(path); @@ -150,7 +149,7 @@ public void CorruptSidecarIsNotErasedByFailedImport() using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); Assert.True(loader.Import(Fixture.path)); - byte[] corrupt = [0xff, 0xee, 0xdd]; + byte[] corrupt = [0xFF, 0xEE, 0xDD]; File.WriteAllBytes(fixture.sourcePath + ".imeta", corrupt); Assert.False(loader.Import(Fixture.path)); Assert.Equal(corrupt, File.ReadAllBytes(fixture.sourcePath + ".imeta")); @@ -158,7 +157,6 @@ public void CorruptSidecarIsNotErasedByFailedImport() private sealed class Fixture : IDisposable { - internal static AssetPath path => AssetPath.Project("value.configured"); private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoImportSettingsTests", Guid.NewGuid().ToString("N")); private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; @@ -174,18 +172,13 @@ internal Fixture() Directory.CreateDirectory(Path.Combine(m_root, "EmptyProject")); File.WriteAllText(sourcePath, "source"); m_scope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImportSettingsTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImportSettingsTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } - internal string assetRoot => Path.Combine(m_root, "Assets"); - internal string sourcePath => Path.Combine(assetRoot, "value.configured"); - internal AssetLoader CreateLoader(string library = "Library") - => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, assetRoot, Path.Combine(m_root, library)); - internal AssetLoader CreateReadOnlyLoader(AssetSourceId id) - => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, - [new AssetSourceMount(AssetSourceId.project, Path.Combine(m_root, "EmptyProject"), false), - new AssetSourceMount(id, assetRoot, true)], Path.Combine(m_root, "ReadOnlyLibrary")); + public void Dispose() { m_serialization.Dispose(); @@ -195,34 +188,27 @@ public void Dispose() m_scope.Dispose(); Directory.Delete(m_root, true); } - } -} -[StableTypeId("f58eaeea-4bd5-4f3a-a7c0-c5a5414a6bb4")] -internal sealed class ConfiguredSettings : ISerializable -{ - [SerializableProperty] internal int multiplier { get; set; } = 1; - [SerializableProperty] internal TextAsset? lookup { get; set; } -} + internal static AssetPath path => AssetPath.Project("value.configured"); -[StableTypeId("bdb3db71-e9cb-4d46-839b-3cbe302c5555")] -internal sealed class ConfiguredAsset : AssetObject -{ - [SerializableProperty] internal string value { get; set; } = string.Empty; -} + internal string assetRoot => Path.Combine(m_root, "Assets"); + internal string sourcePath => Path.Combine(assetRoot, "value.configured"); -[AssetImporter("tests.configured")] -internal sealed class ConfiguredImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".configured"]; - public override ISerializable CreateImportSettings() => new ConfiguredSettings(); - protected override ValueTask ImportAsync(AssetImportContext context, AssetImportWriter output, CancellationToken cancellationToken) - { - var settings = (ConfiguredSettings)context.importSettings!; - if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); - string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; - if (settings.lookup is not null) value += ":" + settings.lookup.content; - output.SetAsset(new ConfiguredAsset { value = value }); - return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken); + internal AssetLoader CreateLoader(string library = "Library") + => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, assetRoot, Path.Combine(m_root, library)); + + internal AssetLoader CreateReadOnlyLoader(AssetSourceID id) + => new( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + [ + new AssetSourceMount(AssetSourceID.project, Path.Combine(m_root, "EmptyProject"), false), + new AssetSourceMount(id, assetRoot, true) + ], + Path.Combine(m_root, "ReadOnlyLibrary") + ); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs new file mode 100644 index 000000000..faa294416 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("da675da1-9276-40c4-9964-0eb4b8ff9a07")] +internal sealed class ImporterConflictAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs new file mode 100644 index 000000000..313246a87 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.conflict-a")] +internal sealed class ImporterConflictAssetImporterA : AssetImporter +{ + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probea"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new ImporterConflictAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs new file mode 100644 index 000000000..350acd927 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.conflict-b")] +internal sealed class ImporterConflictAssetImporterB : AssetImporter +{ + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probeb"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new ImporterConflictAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs new file mode 100644 index 000000000..9efe43087 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs @@ -0,0 +1,6 @@ +namespace Inno.Assets.Pipeline.Tests; + +internal static class ImporterConflictProbe +{ + internal static bool duplicateExtension; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs index be8e1b2be..0a60bda7e 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs @@ -1,19 +1,17 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Text; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; - -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline.Tests; @@ -31,7 +29,9 @@ public ImporterIntegrationTests() { m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImporterIntegrationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(ImporterIntegrationTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -52,9 +52,11 @@ public void Dispose() [InlineData("Text/a.yml", "yaml")] [InlineData("Text/a.md", "markdown")] [InlineData("Text/a.xml", "xml")] - public void TextExtensions_AreAutomaticallyDiscovered(string relativePath, string languageHint) - { - using TestWorkspace workspace = new(); + public void TextExtensionsAreAutomaticallyDiscovered( + string relativePath, + string languageHint + ) { + using var workspace = new TestWorkspace(); workspace.Write(relativePath, Encoding.UTF8.GetBytes("content")); using var loader = new AssetLoader( m_types, @@ -63,7 +65,8 @@ public void TextExtensions_AreAutomaticallyDiscovered(string relativePath, strin m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); AssetPath path = AssetPath.Project(relativePath); Assert.True(loader.Import(path)); @@ -73,9 +76,9 @@ public void TextExtensions_AreAutomaticallyDiscovered(string relativePath, strin } [Fact] - public void BinaryImporter_CreatesRuntimeDescriptor() + public void BinaryImporterCreatesRuntimeDescriptor() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.Write("Data/blob.bytes", [1, 2, 3, 4]); using var loader = new AssetLoader( m_types, @@ -84,7 +87,8 @@ public void BinaryImporter_CreatesRuntimeDescriptor() m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); BinaryAsset binary = Assert.IsType(loader.Load(AssetPath.Project("Data/blob.bytes"), typeof(BinaryAsset))); @@ -92,9 +96,9 @@ public void BinaryImporter_CreatesRuntimeDescriptor() } [Fact] - public void ExportableBuiltInAsset_RoundTripsThroughPublicLoaderContract() + public void ExportableBuiltInAssetRoundTripsThroughPublicLoaderContract() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); using var loader = new AssetLoader( m_types, m_serialization, @@ -102,14 +106,15 @@ public void ExportableBuiltInAsset_RoundTripsThroughPublicLoaderContract() m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); var source = new TextAsset("saved", "plain"); Assert.True(loader.Save(AssetPath.Project("Text/saved.txt"), source)); TextAsset loaded = Assert.IsType(loader.Load(AssetPath.Project("Text/saved.txt"), typeof(TextAsset))); Assert.Same(source, loaded); - Assert.Equal("saved", System.IO.File.ReadAllText(Path.Combine(workspace.assetRoot, "Text/saved.txt"))); + Assert.Equal("saved", File.ReadAllText(Path.Combine(workspace.assetRoot, "Text/saved.txt"))); } private sealed class TestWorkspace : IDisposable @@ -117,7 +122,8 @@ private sealed class TestWorkspace : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoAssetsImporterTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); internal TestWorkspace() { @@ -125,20 +131,24 @@ internal TestWorkspace() Directory.CreateDirectory(libraryRoot); } + public void Dispose() + { + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: true); + } + } + internal string assetRoot => Path.Combine(m_root, "Assets"); internal string libraryRoot => Path.Combine(m_root, "Library"); - internal void Write(string relativePath, byte[] bytes) - { + internal void Write( + string relativePath, + byte[] bytes + ) { string path = Path.Combine(assetRoot, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllBytes(path, bytes); - } - - public void Dispose() - { - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: true); + File.WriteAllBytes(path, bytes); } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs new file mode 100644 index 000000000..6e6c03213 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.mixed-scope")] +internal sealed class MixedScopeAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".mixedscope"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DependencyAsset()); + if (context.ReadUtf8Text() == "authoring") + { + output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); + return output.WriteArtifactAsync( + "graph", + context.sourceBytes, + AssetDeploymentScope.AuthoringOnly, + cancellationToken + ); + } + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs new file mode 100644 index 000000000..8d7e28148 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("fa17dc36-b9cc-4187-b5da-72906ad00505")] +internal sealed class MutableAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs new file mode 100644 index 000000000..add48bd87 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.mutable")] +internal sealed class MutableAssetImporter : AssetImporter +{ + internal static int attempts; + public override IReadOnlyList supportedExtensions { get; } = [".mutableasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + attempts++; + string value = context.ReadUtf8Text(); + if (value == "!invalid!") + { + throw new InvalidDataException("The mutable asset source is invalid."); + } + output.SetAsset(new MutableAsset { value = value }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } + + protected override ValueTask?> ExportAsync( + AssetExportContext context, + MutableAsset asset, + CancellationToken cancellationToken + ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs new file mode 100644 index 000000000..483dcf434 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("501988d0-c069-4dcf-97f6-e899b24e5801")] +internal sealed class PrivateConstructorAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs new file mode 100644 index 000000000..9839139c7 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.private-constructor")] +internal sealed class PrivateConstructorAssetImporter : AssetImporter +{ + private static readonly IReadOnlyList EXTENSIONS = [".privateasset"]; + + private PrivateConstructorAssetImporter() {} + + public override IReadOnlyList supportedExtensions => EXTENSIONS; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new PrivateConstructorAsset { value = context.ReadUtf8Text() }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs index 74ef674d1..96d9b9529 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs @@ -1,23 +1,20 @@ -using Inno.Content.Testing; -using Inno.Content; -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using Inno.Assets; -using Inno.Assets.Pipeline; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Content; +using Inno.Content.Testing; using Inno.Core.Diagnostics; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; using Inno.Extensibility.Reload; -using Xunit; +using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline.Tests; @@ -33,7 +30,7 @@ public void SettingsResolveTheCurrentAssetGenerationAndPreserveMissingIntent(boo File.WriteAllText(source, "original"); TextAsset clip = fixture.assets.Load(AssetPath.Project("value.txt")); byte[] metadata = File.ReadAllBytes(source + ".imeta"); - ProjectSettingId id = composed ? ComposedClipSettings.id : ClipSettings.id; + ProjectSettingID id = composed ? ComposedClipSettings.id : ClipSettings.id; ClipSettingsBase value = composed ? new ComposedClipSettings() : new ClipSettings(); value.clip = clip; fixture.settings.SetProjectOverride(id, value, []); @@ -44,7 +41,7 @@ public void SettingsResolveTheCurrentAssetGenerationAndPreserveMissingIntent(boo fixture.assets.ReplaceSourceMounts(fixture.assets.sourceMounts); TextAsset missing = Assert.IsType(fixture.settings.Get(id).clip); Assert.True(missing.isMissing); - Assert.Equal(clip.identity.persistentId, missing.identity.persistentId); + Assert.Equal(clip.identity.persistentID, missing.identity.persistentID); Assert.Equal(document, fixture.settings.CaptureDocument()); File.WriteAllText(source, "restored"); @@ -52,7 +49,7 @@ public void SettingsResolveTheCurrentAssetGenerationAndPreserveMissingIntent(boo fixture.assets.ReplaceSourceMounts(fixture.assets.sourceMounts); TextAsset restored = Assert.IsType(fixture.settings.Get(id).clip); Assert.False(restored.isMissing); - Assert.Equal(clip.identity.persistentId, restored.identity.persistentId); + Assert.Equal(clip.identity.persistentID, restored.identity.persistentID); Assert.Equal("restored", restored.content); Assert.NotSame(clip, restored); Assert.Equal(document, fixture.settings.CaptureDocument()); @@ -68,7 +65,7 @@ public void RuntimeSettingsLoadTheirColdReferencesThroughTheSessionAssetOwner(bo using var fixture = new Fixture(); File.WriteAllText(Path.Combine(fixture.assetRoot, "value.txt"), "deployed"); TextAsset clip = fixture.assets.Load(AssetPath.Project("value.txt")); - ProjectSettingId id = composed ? ComposedClipSettings.id : ClipSettings.id; + ProjectSettingID id = composed ? ComposedClipSettings.id : ClipSettings.id; ClipSettingsBase value = composed ? new ComposedClipSettings() : new ClipSettings(); value.clip = clip; fixture.settings.SetProjectOverride(id, value, []); @@ -80,18 +77,23 @@ public void RuntimeSettingsLoadTheirColdReferencesThroughTheSessionAssetOwner(bo var identities = new IdentityAllocator(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(content); using var database = new AssetDatabase(contentStore, serialization, fixture.types.current, identities); - Assert.Null(identities.Get(clip.identity.persistentId)); + Assert.Null(identities.Get(clip.identity.persistentID)); - using ContentReadLease settingsLease = contentStore.Acquire(new Inno.Content.ContentKey("Settings.Project.inno")); + using ContentReadLease settingsLease = contentStore.Acquire(new ContentKey("Settings.Project.inno")); using Stream settingsInput = settingsLease.OpenRead(); - byte[] settingsBytes = new byte[checked((int)settingsLease.entry.length)]; + var settingsBytes = new byte[checked((int)settingsLease.entry.length)]; settingsInput.ReadExactly(settingsBytes); - using var settings = new ProjectSettingsStore(new ReadOnlyByteDocumentStore("Settings.Project.inno", settingsBytes), fixture.types, fixture.serialization, - new ProjectId("tests.deployed.settings"), AssetSerializationContext.Create(database)); + using var settings = new ProjectSettingsStore( + new ReadOnlyByteDocumentStore("Settings.Project.inno", settingsBytes), + fixture.types, + fixture.serialization, + new ProjectID("tests.deployed.settings"), + AssetSerializationContext.Create(database) + ); TextAsset runtime = Assert.IsType(settings.Get(id).clip); Assert.Equal("deployed", runtime.content); - Assert.Same(runtime, identities.Get(clip.identity.persistentId)); + Assert.Same(runtime, identities.Get(clip.identity.persistentID)); Assert.NotSame(clip, runtime); byte[] previous = settings.CaptureDocument(); ClipSettingsBase changed = composed ? new ComposedClipSettings() : new ClipSettings(); @@ -106,12 +108,16 @@ public void FivePhaseSettingsRollbackRestoresExactEffectiveStateWithoutWritingDo using var fixture = new Fixture(); byte[] first = fixture.serialization.CapturePropertiesData(new ClipSettings { labels = ["previous"] }, fixture.context); byte[] next = fixture.serialization.CapturePropertiesData(new ClipSettings { labels = ["candidate"] }, fixture.context); - fixture.settings.Rebuild([new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, first)])]); + fixture.settings.Rebuild( + [new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.TYPE_ID, first)])] + ); byte[] document = fixture.settings.CaptureDocument(); long revision = fixture.settings.revision; IGenerationChange change = fixture.settings.CreateReloadChange(); change.PrepareForActivation(); - fixture.settings.SetContributors([new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, next)])]); + fixture.settings.SetContributors( + [new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.TYPE_ID, next)])] + ); change.Apply(); Assert.Equal("candidate", Assert.Single(fixture.settings.Get(ClipSettings.id).labels)); change.RollbackStructure(); @@ -129,7 +135,7 @@ public void ContributorPublicationFreezesNestedPayloadsAndKeepsLastGoodOnFailure using var fixture = new Fixture(); var value = new ClipSettings { labels = ["stable"] }; byte[] payload = fixture.serialization.CapturePropertiesData(value, fixture.context); - var record = new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, payload); + var record = new ProjectSettingRecord(ClipSettings.id, ClipSettings.TYPE_ID, payload); string[] dependencies = ["base"]; var contributor = new ProjectSettingsContributor("extension", dependencies, [], [record]); dependencies[0] = "changed"; @@ -143,8 +149,12 @@ public void ContributorPublicationFreezesNestedPayloadsAndKeepsLastGoodOnFailure long revision = fixture.settings.revision; Assert.ThrowsAny(() => fixture.settings.Rebuild([ - new ProjectSettingsContributor("broken", [], [], - [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, [1, 2, 3])])])); + new ProjectSettingsContributor( + "broken", + [], + [], + [new ProjectSettingRecord(ClipSettings.id, ClipSettings.TYPE_ID, [1, 2, 3])] + )])); Assert.Equal(revision, fixture.settings.revision); Assert.Equal("stable", Assert.Single(fixture.settings.Get(ClipSettings.id).labels)); } @@ -167,8 +177,12 @@ public void SettingsRequireAnExplicitOwnerSerializationContext() { using var fixture = new Fixture(); Assert.Throws(() => new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(fixture.root, "Rejected.inno"))), fixture.types, fixture.serialization, - new ProjectId("tests.rejected"), null!)); + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(fixture.root, "Rejected.inno"))), + fixture.types, + fixture.serialization, + new ProjectID("tests.rejected"), + null! + )); } private sealed class Fixture : IDisposable @@ -181,28 +195,34 @@ private sealed class Fixture : IDisposable internal Fixture() { - root = Path.Combine(Path.GetTempPath(), "InnoSettingsReferences", Guid.NewGuid().ToString("N")); - assetRoot = Path.Combine(root, "Assets"); + this.root = Path.Combine(Path.GetTempPath(), "InnoSettingsReferences", Guid.NewGuid().ToString("N")); + this.assetRoot = Path.Combine(root, "Assets"); Directory.CreateDirectory(assetRoot); m_identityScope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SettingsReferenceTests).Assembly)}); - types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - assets = new AssetPipeline(m_modules, types, serialization, m_identities, m_diagnostics, m_logs, - AssetPipelineOptions.Create(assetRoot, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false }); - context = AssetSerializationContext.Create(assets); - settings = new ProjectSettingsStore(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(root, "Settings.Project.inno"))), types, - serialization, new ProjectId("tests.settings.references"), context); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SettingsReferenceTests).Assembly)} + ); + this.types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); + this.assets = new AssetPipeline( + m_modules, + types, + serialization, + m_identities, + m_diagnostics, + m_logs, + AssetPipelineOptions.Create(assetRoot, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false } + ); + this.context = AssetSerializationContext.Create(assets); + this.settings = new ProjectSettingsStore( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(root, "Settings.Project.inno"))), + types, + serialization, + new ProjectID("tests.settings.references"), + context + ); } - internal string root { get; } - internal string assetRoot { get; } - internal TypeCatalog types { get; } - internal SerializationRegistry serialization { get; } - internal AssetPipeline assets { get; } - internal SerializationContext context { get; } - internal ProjectSettingsStore settings { get; } - public void Dispose() { settings.Dispose(); @@ -214,46 +234,13 @@ public void Dispose() m_identityScope.Dispose(); Directory.Delete(root, recursive: true); } - } -} -internal abstract class ClipSettingsBase : ISerializable -{ - [SerializableProperty] public TextAsset? clip { get; set; } - [SerializableProperty] public string[] labels { get; set; } = []; -} - -[StableTypeId("2c7288db-eb9e-43a5-9894-bf9d10b22a2d")] -[ProjectSettingDefinition("tests.settings.clip")] -internal sealed class ClipSettings : ClipSettingsBase -{ - internal static readonly Guid typeId = new("2c7288db-eb9e-43a5-9894-bf9d10b22a2d"); - internal static ProjectSettingId id => new("tests.settings.clip"); -} - -[StableTypeId("cbeec86a-29da-4894-915f-b6239086ee05")] -[ProjectSettingDefinition("tests.settings.composed-clip")] -internal sealed class ComposedClipSettings : ClipSettingsBase -{ - internal static ProjectSettingId id => new("tests.settings.composed-clip"); -} - -internal sealed class ClipContribution : ISerializable -{ - [SerializableProperty] public TextAsset? clip { get; set; } -} - -[ProjectSettingComposer("tests.settings.composed-clip")] -internal sealed class ClipSettingsComposer : ProjectSettingComposer -{ - protected override ClipContribution CaptureContribution(ComposedClipSettings baseline, ComposedClipSettings value) - => new() { clip = value.clip }; - - protected override bool IsEmpty(ClipContribution contribution) => contribution.clip is null; - - protected override void Compose(ComposedClipSettings target, IReadOnlyList> contributions) - { - foreach (ProjectSettingContribution contribution in contributions) - target.clip = contribution.value.clip; + internal string root { get; } + internal string assetRoot { get; } + internal TypeCatalog types { get; } + internal SerializationRegistry serialization { get; } + internal AssetPipeline assets { get; } + internal SerializationContext context { get; } + internal ProjectSettingsStore settings { get; } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs new file mode 100644 index 000000000..36144d3cf --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("490def27-4cdd-48a0-b324-9b7438600404")] +internal sealed class SlowAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs new file mode 100644 index 000000000..7f8db1c64 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.slow")] +internal sealed class SlowAssetImporter : AssetImporter +{ + internal static readonly ManualResetEventSlim IMPORT_STARTED = new(false); + internal static readonly ManualResetEventSlim ALLOW_IMPORT = new(false); + internal static int importCount; + + public override IReadOnlyList supportedExtensions { get; } = [".slowasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + Interlocked.Increment(ref importCount); + IMPORT_STARTED.Set(); + if (!ALLOW_IMPORT.Wait(TimeSpan.FromSeconds(5))) + { + throw new TimeoutException("The slow importer test gate was not released."); + } + output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } + + internal static void Reset() + { + importCount = 0; + IMPORT_STARTED.Reset(); + ALLOW_IMPORT.Reset(); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs new file mode 100644 index 000000000..7fc23c3dc --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("8f87f452-203e-4cd4-9c91-c93af4802141")] +internal sealed class TestBuildDefinitionAsset : AssetObject +{ + [SerializableProperty] + internal string label { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs new file mode 100644 index 000000000..ec2496d3e --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs @@ -0,0 +1,18 @@ +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetBuildProcessor("inno.tests.aggregate-build")] +internal sealed class TestBuildProcessor : AssetBuildProcessor +{ + protected override ValueTask BuildAsync( + AssetBuildContext context, + AssetArtifactWriter output, + CancellationToken cancellationToken + ) { + string value = context.definition.label + ":" + context.inputs.Count; + return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs b/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs index be8cdee55..7556d841c 100644 --- a/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs @@ -1,15 +1,13 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Collections.Generic; - +using Xunit; using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Execution; +using Inno.Extensibility.Types; using Inno.References; -using Xunit; - namespace Inno.Assets.Tests; public sealed class AssetCoreTests @@ -19,22 +17,23 @@ public void ReferenceBridgeDoesNotConvertAnUnfinishedRetirementIntoMissing() { IReferenceResolver resolver = new PendingResolver(); Assert.Throws(() => resolver.Resolve( - new ReferenceDescriptor(AssetReferenceProtocol.id, Guid.NewGuid(), Guid.Empty))); + new ReferenceDescriptor(AssetReferenceProtocol.id, Guid.NewGuid(), Guid.Empty) + )); } [Fact] - public void AssetDependency_UsesPersistentIdentityForEquality() + public void AssetDependencyUsesPersistentIdentityForEquality() { - Guid persistentId = Guid.NewGuid(); - var first = new AssetDependency(persistentId, new TypeRef(Guid.NewGuid()), "A/first.txt"); - var second = new AssetDependency(persistentId, new TypeRef(Guid.NewGuid()), "B/second.txt"); + Guid persistentID = Guid.NewGuid(); + var first = new AssetDependency(persistentID, new TypeRef(Guid.NewGuid()), "A/first.txt"); + var second = new AssetDependency(persistentID, new TypeRef(Guid.NewGuid()), "B/second.txt"); Assert.Equal(first, second); Assert.Equal(first.GetHashCode(), second.GetHashCode()); } [Fact] - public void AssetObject_DefaultRuntimeState_IsDetachedAndEmpty() + public void AssetObjectDefaultRuntimeStateIsDetachedAndEmpty() { var asset = new TextAsset(); @@ -46,7 +45,7 @@ public void AssetObject_DefaultRuntimeState_IsDetachedAndEmpty() } [Fact] - public void AssetDependency_IsAnImmutableValueContract() + public void AssetDependencyIsAnImmutableValueContract() { PropertyInfo[] properties = typeof(AssetDependency).GetProperties(BindingFlags.Instance | BindingFlags.Public); @@ -55,7 +54,7 @@ public void AssetDependency_IsAnImmutableValueContract() } [Fact] - public void AssetObject_PublicSurface_DoesNotExposeSourceHashDependenciesOrSetters() + public void AssetObjectPublicSurfaceDoesNotExposeSourceHashDependenciesOrSetters() { string[] propertyNames = typeof(AssetObject) .GetProperties(BindingFlags.Instance | BindingFlags.Public) @@ -72,7 +71,7 @@ public void AssetObject_PublicSurface_DoesNotExposeSourceHashDependenciesOrSette } [Fact] - public void ArtifactKey_NormalizesAndComparesHexadecimalValues() + public void ArtifactKeyNormalizesAndComparesHexadecimalValues() { var lower = new AssetArtifactKey(" " + new string('a', 64) + " "); var upper = new AssetArtifactKey(new string('A', 64)); @@ -109,17 +108,17 @@ public void DefaultArtifactKeyHasTheSameValueAndEqualityAsAnExplicitEmptyKey() [Fact] public void RuntimeContentSummaryOwnsItsFrozenSourceInventory() { - var sources = new List { AssetSourceId.project }; + List sources = [AssetSourceID.project]; var summary = new AssetRuntimeContentInfo(sources, 2, 1, 4); - sources[0] = new AssetSourceId("replacement"); + sources[0] = new AssetSourceID("replacement"); sources.Clear(); - Assert.Equal(AssetSourceId.project, Assert.Single(summary.sources)); - Assert.Throws(() => ((IList)summary.sources).Clear()); + Assert.Equal(AssetSourceID.project, Assert.Single(summary.sources)); + Assert.Throws(() => ((IList)summary.sources).Clear()); Assert.Throws(() => new AssetRuntimeContentInfo(null!, 0, 0, 0)); } [Fact] - public void AssetInfo_ExposesAnImmutableCatalogSnapshot() + public void AssetInfoExposesAnImmutableCatalogSnapshot() { Guid id = Guid.NewGuid(); var info = new AssetInfo( @@ -131,38 +130,45 @@ public void AssetInfo_ExposesAnImmutableCatalogSnapshot() Guid.NewGuid(), new AssetArtifactKey(new string('A', 64)), new AssetArtifactKey(new string('B', 64)), - new[] { "diagnostic" }); + new[] { "diagnostic" } + ); - Assert.Equal(id, info.persistentId); + Assert.Equal(id, info.persistentID); Assert.Equal(AssetSourceKind.File, info.sourceKind); Assert.Equal(AssetImportStatus.Imported, info.status); Assert.All( typeof(AssetInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public), - static property => Assert.Null(property.SetMethod)); - } - - private sealed class PendingResolver : IAssetReferenceResolver - { - public AssetObject Resolve(Guid persistentId, Guid stableTypeId, string lastKnownPath, - Type expectedType, string propertyPath) - => throw new RetirementPendingException("The asset generation is still retiring."); + static property => Assert.Null(property.SetMethod) + ); } [Fact] - public void ChangeSet_PreservesMoveIdentityAndRevision() + public void ChangeSetPreservesMoveIdentityAndRevision() { Guid id = Guid.NewGuid(); var change = new AssetChange( AssetChangeKind.Moved, id, AssetPath.Project("B/value.txt"), - AssetPath.Project("A/value.txt")); + AssetPath.Project("A/value.txt") + ); var set = new AssetChangeSet(42, new List { change }); Assert.Equal(42, set.revision); Assert.False(set.isEmpty); - Assert.Equal(id, set.changes[0].persistentId); + Assert.Equal(id, set.changes[0].persistentID); Assert.Equal(AssetPath.Project("A/value.txt"), set.changes[0].previousAssetPath); Assert.Equal(AssetPath.Project("B/value.txt"), set.changes[0].assetPath); } + + private sealed class PendingResolver : IAssetReferenceResolver + { + public AssetObject Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ) => throw new RetirementPendingException("The asset generation is still retiring."); + } } diff --git a/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs b/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs index eacf93d8b..6b3b032ee 100644 --- a/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs @@ -1,16 +1,14 @@ using System; using System.Threading.Tasks; - -using Inno.Assets; - using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; public sealed class AssetExecutionContextTests { [Fact] - public void Assets_WithoutAnExecutionScope_FailsExplicitly() + public void AssetsWithoutAnExecutionScopeFailsExplicitly() { InvalidOperationException exception = Assert.Throws(() => Assets.Load(AssetPath.Project("missing.txt"))); @@ -19,7 +17,7 @@ public void Assets_WithoutAnExecutionScope_FailsExplicitly() } [Fact] - public void NestedScopes_RestoreThePreviousLookup() + public void NestedScopesRestoreThePreviousLookup() { var outerAsset = new TextAsset(); var innerAsset = new TextAsset(); @@ -30,13 +28,15 @@ public void NestedScopes_RestoreThePreviousLookup() { Assert.Same(outerAsset, Assets.Load(AssetPath.Project("value.txt"))); using (AssetExecutionContext.EnterScope(inner)) + { Assert.Same(innerAsset, Assets.Load(AssetPath.Project("value.txt"))); + } Assert.Same(outerAsset, Assets.Load(AssetPath.Project("value.txt"))); } } [Fact] - public void Scopes_DisposedOutOfOrder_AreRejectedWithoutLosingTheActiveLookup() + public void ScopesDisposedOutOfOrderAreRejectedWithoutLosingTheActiveLookup() { var outer = new FixedAssetLookup(new TextAsset()); var inner = new FixedAssetLookup(new TextAsset()); @@ -56,7 +56,7 @@ public void Scopes_DisposedOutOfOrder_AreRejectedWithoutLosingTheActiveLookup() } [Fact] - public async Task ParallelAsyncFlows_ResolveTheirOwnLookups() + public async Task ParallelAsyncFlowsResolveTheirOwnLookups() { var firstAsset = new TextAsset(); var secondAsset = new TextAsset(); @@ -79,21 +79,25 @@ private sealed class FixedAssetLookup(AssetObject asset) : IAssetLookup { public TAsset Load(AssetPath path) where TAsset : AssetObject - => Cast(); + => Cast(); - public TAsset Load(Guid persistentId) + public TAsset Load(Guid persistentID) where TAsset : AssetObject - => Cast(); + => Cast(); - public bool TryLoad(AssetPath path, out TAsset? loadedAsset) - where TAsset : AssetObject + public bool TryLoad( + AssetPath path, + out TAsset? loadedAsset + ) where TAsset : AssetObject { loadedAsset = Cast(); return true; } - public bool TryLoad(Guid persistentId, out TAsset? loadedAsset) - where TAsset : AssetObject + public bool TryLoad( + Guid persistentID, + out TAsset? loadedAsset + ) where TAsset : AssetObject { loadedAsset = Cast(); return true; @@ -101,6 +105,6 @@ public bool TryLoad(Guid persistentId, out TAsset? loadedAsset) private TAsset Cast() where TAsset : AssetObject - => Assert.IsType(asset); + => Assert.IsType(asset); } } diff --git a/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs b/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs index c578cb95d..cf7da9bb5 100644 --- a/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs @@ -3,9 +3,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; @@ -15,8 +14,7 @@ public sealed class AssetResidencyTests public async Task AssetLeaseRetainsCanonicalAssetAndReleasesExactlyOnce() { var provider = new FakeResidencyProvider(); - AssetLease lease = await provider.AcquireAsync( - AssetPath.Project("Text/readme.txt")); + AssetLease lease = await provider.AcquireAsync(AssetPath.Project("Text/readme.txt")); Assert.Same(provider.asset, lease.asset); lease.Dispose(); @@ -29,7 +27,7 @@ public async Task AssetLeaseRetainsCanonicalAssetAndReleasesExactlyOnce() [Fact] public void RetentionScopeReleasesChildrenInReverseOrder() { - var order = new List(); + List order = []; using (var scope = new RetentionScope()) { _ = scope.Retain(new CallbackLease(() => order.Add(1))); @@ -49,7 +47,9 @@ public void ArtifactLeaseReadsProviderBytesAndInvalidatesAfterRelease() var provider = new FakeResidencyProvider(path); ArtifactLease lease = provider.AcquireArtifact(Guid.NewGuid(), "runtime"); using (Stream stream = lease.OpenRead()) + { Assert.Equal(3, stream.Length); + } lease.Dispose(); @@ -71,38 +71,35 @@ internal FakeResidencyProvider(string artifactPath = "unused") m_artifactPath = artifactPath; } - internal TextAsset asset { get; } = new(); - - internal int assetReleaseCount { get; private set; } - - internal int artifactReleaseCount { get; private set; } - public ValueTask> AcquireAsync( AssetPath path, - CancellationToken cancellationToken = default) - where TAsset : AssetObject + CancellationToken cancellationToken = default + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); - return ValueTask.FromResult(CreateAssetLease( - (TAsset)(AssetObject)asset, - () => assetReleaseCount++)); + return ValueTask.FromResult(CreateAssetLease((TAsset)(AssetObject)asset, () => assetReleaseCount++)); } public ValueTask> AcquireAsync( - Guid persistentId, - CancellationToken cancellationToken = default) - where TAsset : AssetObject + Guid persistentID, + CancellationToken cancellationToken = default + ) where TAsset : AssetObject => AcquireAsync(AssetPath.Project("Text/readme.txt"), cancellationToken); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - => CreateArtifactLease( - new AssetArtifactInfo( - new AssetArtifactKey(new string('A', 64)), - outputName, - "HASH", - 3), - () => File.OpenRead(m_artifactPath), - () => artifactReleaseCount++); + public ArtifactLease AcquireArtifact( + Guid persistentID, + string outputName + ) => CreateArtifactLease( + new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), outputName, "HASH", 3), + () => File.OpenRead(m_artifactPath), + () => artifactReleaseCount++ + ); + + internal TextAsset asset { get; } = new(); + + internal int assetReleaseCount { get; private set; } + + internal int artifactReleaseCount { get; private set; } } private sealed class CallbackLease(Action callback) : IDisposable diff --git a/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs b/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs index 0526c672b..d26d2b794 100644 --- a/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; @@ -30,7 +30,9 @@ public void FailedPayloadHookDoesNotPublishCandidateState() var asset = new TestAsset(); owner.Initialize(asset, AssetPath.Project("one.bin"), "one", new byte[] { 1 }, false, 1); asset.fail = true; - Assert.Throws(() => owner.Initialize(asset, AssetPath.Project("two.bin"), "two", new byte[] { 2 }, true, 2)); + Assert.Throws( + () => owner.Initialize(asset, AssetPath.Project("two.bin"), "two", new byte[] { 2 }, true, 2) + ); Assert.Equal(1, asset.contentVersion); Assert.False(asset.isMissing); Assert.Equal("one", owner.GetSourceHash(asset)); @@ -58,10 +60,14 @@ private sealed class TestAsset : AssetObject { internal bool fail; internal int unloadCount; - protected override void OnRuntimePayloadChanged(ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload) - { + + protected override void OnRuntimePayloadChanged( + ReadOnlyMemory previousPayload, + ReadOnlyMemory currentPayload + ) { if (fail) throw new InvalidOperationException("Rejected payload."); } + protected override void OnUnloading() => unloadCount++; } } diff --git a/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs b/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs index d9d7e44d0..35a985ce6 100644 --- a/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs @@ -1,13 +1,12 @@ -using Inno.Assets; - using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; public sealed class AssetTypesTests { [Fact] - public void TextAsset_Ctor_AssignsValues() + public void TextAssetCtorAssignsValues() { var asset = new TextAsset("hello", "plain"); Assert.Equal("hello", asset.content); @@ -15,7 +14,7 @@ public void TextAsset_Ctor_AssignsValues() } [Fact] - public void BinaryAsset_Ctor_AssignsValues() + public void BinaryAssetCtorAssignsValues() { var asset = new BinaryAsset(10); Assert.Equal(10, asset.byteLength); diff --git a/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs b/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs index 2f4166584..d18513fbd 100644 --- a/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs +++ b/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs @@ -4,8 +4,8 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; using Xunit; +using Inno.Core.Execution; namespace Inno.Assets.Tests; @@ -23,20 +23,34 @@ public void PendingLeaseRetainsItsValueAndCallbackUntilReleaseCompletes(bool art Action release = () => { if (++attempts == 1) + { throw new RetirementPendingException("Expected residency drain."); + } }; using IDisposable lease = artifact ? provider.Artifact(info, release) : provider.Asset(asset, release); Assert.Throws(lease.Dispose); - if (lease is ArtifactLease artifactLease) Assert.Same(info, artifactLease.info); - else Assert.Same(asset, ((AssetLease)lease).asset); + if (lease is ArtifactLease artifactLease) + { + Assert.Same(info, artifactLease.info); + } + else + { + Assert.Same(asset, ((AssetLease)lease).asset); + } lease.Dispose(); Assert.Equal(2, attempts); lease.Dispose(); Assert.Equal(2, attempts); Assert.Throws(() => { - if (lease is ArtifactLease releasedArtifact) _ = releasedArtifact.info; - else _ = ((AssetLease)lease).asset; + if (lease is ArtifactLease releasedArtifact) + { + _ = releasedArtifact.info; + } + else + { + _ = ((AssetLease)lease).asset; + } }); } @@ -47,7 +61,11 @@ public void OrdinaryReleaseFailureIsTerminalAndNeverInvokesTheCallbackTwice(bool { int attempts = 0; var provider = new TestProvider(); - Action release = () => { attempts++; throw new InvalidOperationException("Expected terminal release failure."); }; + Action release = () => + { + attempts++; + throw new InvalidOperationException("Expected terminal release failure."); + }; IDisposable lease = artifact ? provider.Artifact(Artifact(), release) : provider.Asset(new TextAsset(), release); Assert.Throws(lease.Dispose); lease.Dispose(); @@ -64,12 +82,21 @@ public void WrappedPendingRetainsTheLeaseAndReportsOrdinarySiblingsAfterCompleti var asset = new TextAsset(); var ordinary = new InvalidOperationException("completed sibling"); var pending = new AggregateException(ordinary, new RetirementPendingException("unfinished callback")); - Action release = () => { if (++attempts < 3) throw pending; }; + Action release = () => + { + if (++attempts < 3) throw pending; + }; IDisposable lease = artifact ? provider.Artifact(Artifact(), release) : provider.Asset(asset, release); Assert.Same(pending, Assert.Throws(lease.Dispose)); Assert.Same(pending, Assert.Throws(lease.Dispose)); - if (lease is ArtifactLease artifactLease) Assert.NotNull(artifactLease.info); - else Assert.Same(asset, ((AssetLease)lease).asset); + if (lease is ArtifactLease artifactLease) + { + Assert.NotNull(artifactLease.info); + } + else + { + Assert.Same(asset, ((AssetLease)lease).asset); + } AggregateException completed = Assert.Throws(lease.Dispose); Assert.Same(ordinary, Assert.Single(completed.InnerExceptions)); lease.Dispose(); @@ -92,7 +119,8 @@ public async Task ConcurrentReleaseCannotReportCompletionWhileTheProviderIsStill lease.Dispose, CancellationToken.None, TaskCreationOptions.LongRunning, - TaskScheduler.Default); + TaskScheduler.Default + ); try { Assert.True(started.Wait(TimeSpan.FromSeconds(30))); @@ -100,7 +128,11 @@ public async Task ConcurrentReleaseCannotReportCompletionWhileTheProviderIsStill Assert.NotNull(lease.info); Assert.Equal(1, attempts); } - finally { finish.Set(); await worker; } + finally + { + finish.Set(); + await worker; + } lease.Dispose(); Assert.Equal(1, attempts); Assert.Throws(() => _ = lease.info); @@ -109,20 +141,28 @@ public async Task ConcurrentReleaseCannotReportCompletionWhileTheProviderIsStill [Fact] public void RetentionScopePreservesLifoDependenciesAndEarlierFailuresAcrossPending() { - var order = new List(); + List order = []; int pendingAttempts = 0; var scope = new RetentionScope(); scope.Retain(new ReleaseStep(() => order.Add("dependency"))); - scope.Retain(new ReleaseStep(() => - { - order.Add("pending"); - if (++pendingAttempts == 1) throw new RetirementPendingException("Expected owner drain."); - })); - scope.Retain(new ReleaseStep(() => { order.Add("failure"); throw new InvalidOperationException("Expected release failure."); })); + scope.Retain( + new ReleaseStep(() => + { + order.Add("pending"); + if (++pendingAttempts == 1) throw new RetirementPendingException("Expected owner drain."); + }) + ); + scope.Retain( + new ReleaseStep(() => + { + order.Add("failure"); + throw new InvalidOperationException("Expected release failure."); + }) + ); Assert.Throws(scope.Dispose); Assert.Equal(new[] { "failure", "pending" }, order); - Assert.Throws(() => scope.Retain(new ReleaseStep(() => { }))); + Assert.Throws(() => scope.Retain(new ReleaseStep(() => {}))); AggregateException failure = Assert.Throws(scope.Dispose); Assert.Contains(failure.InnerExceptions, exception => exception.Message == "Expected release failure."); Assert.Equal(new[] { "failure", "pending", "pending", "dependency" }, order); @@ -166,7 +206,11 @@ private static void Collect() private sealed class TestProvider : AssetResidencyProvider { - internal AssetLease Asset(TextAsset asset, Action release) => CreateAssetLease(asset, release); + internal AssetLease Asset( + TextAsset asset, + Action release + ) => CreateAssetLease(asset, release); + internal ArtifactLease Artifact( AssetArtifactInfo info, Action release diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs new file mode 100644 index 000000000..50be9acea --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Deliberately shares its importer identity with to test candidate rejection. +/// +[AssetImporter("inno.tests.duplicate-importer")] +public sealed class DuplicateImporterA : AssetImporter +{ + /// + /// Gets this fixture's extension; distinct extensions do not make duplicate importer identities valid. + /// + public override IReadOnlyList supportedExtensions { get; } = [".duplicateid"]; + + /// + /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. + /// + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DuplicateImporterAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs new file mode 100644 index 000000000..d53e42c4c --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs @@ -0,0 +1,9 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Supplies a stable, field-free asset for conflicting importer registration fixtures. +/// +[StableTypeID("27a0c796-5e7b-4e65-b9e5-2a0ced76675c")] +public sealed class DuplicateImporterAsset : AssetObject; diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs new file mode 100644 index 000000000..420d8bcb6 --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Deliberately conflicts with despite using a different file extension. +/// +[AssetImporter("inno.tests.duplicate-importer")] +public sealed class DuplicateImporterB : AssetImporter +{ + /// + /// Gets the alternate extension used to prove identity conflicts are independent of extension selection. + /// + public override IReadOnlyList supportedExtensions { get; } = [".duplicateid-b"]; + + /// + /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. + /// + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DuplicateImporterAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); + } +} diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs deleted file mode 100644 index 9130f3554..000000000 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; - -namespace Inno.Assets.Pipeline.DuplicateImporterFixture; - -/// -/// Supplies a stable, field-free asset for conflicting importer registration fixtures. -/// -[StableTypeId("27a0c796-5e7b-4e65-b9e5-2a0ced76675c")] -public sealed class DuplicateImporterAsset : AssetObject; - -/// -/// Deliberately shares its importer identity with to test candidate rejection. -/// -[AssetImporter("inno.tests.duplicate-importer")] -public sealed class DuplicateImporterA : AssetImporter -{ - /// - /// Gets this fixture's extension; distinct extensions do not make duplicate importer identities valid. - /// - public override IReadOnlyList supportedExtensions { get; } = [".duplicateid"]; - - /// - /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. - /// - /// The current source snapshot owned by the import operation. - /// The borrowed writer receiving the candidate asset and artifact. - /// Cancels the artifact write without publishing a complete candidate. - /// The artifact write operation, preserving its failure or cancellation. - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken) - { - output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -/// -/// Deliberately conflicts with despite using a different file extension. -/// -[AssetImporter("inno.tests.duplicate-importer")] -public sealed class DuplicateImporterB : AssetImporter -{ - /// - /// Gets the alternate extension used to prove identity conflicts are independent of extension selection. - /// - public override IReadOnlyList supportedExtensions { get; } = [".duplicateid-b"]; - - /// - /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. - /// - /// The current source snapshot owned by the import operation. - /// The borrowed writer receiving the candidate asset and artifact. - /// Cancels the artifact write without publishing a complete candidate. - /// The artifact write operation, preserving its failure or cancellation. - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken) - { - output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} diff --git a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs index 3f28ba053..c6bef062b 100644 --- a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs +++ b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs @@ -1,9 +1,10 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; using System.IO; using System.Reflection; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; @@ -12,7 +13,6 @@ using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Audio.Assets.Tests; @@ -37,7 +37,9 @@ public AudioClipImporterTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioClipImporterTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioClipImporterTests).Assembly) + }); _ = Assembly.Load("Inno.Audio.Assets"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); @@ -52,7 +54,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -67,11 +71,11 @@ public void ImportsWavFlacAndMp3IntoMetadataAndSeparateEncodedArtifacts() AudioClipAsset flac = Load(loader, "tone.flac"); AudioClipAsset mp3 = Load(loader, "tone.mp3"); - Assert.Equal(AudioCodecId.wav, wav.metadata!.Value.codec); + Assert.Equal(AudioCodecID.wav, wav.metadata!.Value.codec); Assert.Equal(4, wav.metadata.Value.frameCount); - Assert.Equal(AudioCodecId.flac, flac.metadata!.Value.codec); - Assert.Equal(48000, flac.metadata.Value.frameCount); - Assert.Equal(AudioCodecId.mp3, mp3.metadata!.Value.codec); + Assert.Equal(AudioCodecID.flac, flac.metadata!.Value.codec); + Assert.Equal(48_000, flac.metadata.Value.frameCount); + Assert.Equal(AudioCodecID.mp3, mp3.metadata!.Value.codec); Assert.Equal(1152, mp3.metadata.Value.frameCount); AssertSeparateArtifact(loader, wav, CreateWav()); AssertSeparateArtifact(loader, flac, CreateFlac()); @@ -85,41 +89,49 @@ public void CorruptEncodedSourceFailsWithoutCommittingAnAsset() using AssetLoader loader = CreateLoader(); Assert.False(loader.Import(AssetPath.Project("broken.wav"))); - Assert.True(loader.TryGetPersistentId(AssetPath.Project("broken.wav"), out Guid persistentId)); - Assert.False(loader.TryGetArtifact(persistentId, "audio-data", out _)); + Assert.True(loader.TryGetPersistentID(AssetPath.Project("broken.wav"), out Guid persistentID)); + Assert.False(loader.TryGetArtifact(persistentID, "audio-data", out _)); } private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static AudioClipAsset Load(AssetLoader loader, string path) - => Assert.IsType(loader.Load(AssetPath.Project(path), typeof(AudioClipAsset))); - - private static void AssertSeparateArtifact(AssetLoader loader, AudioClipAsset asset, byte[] expected) - { - Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "runtime", out AssetArtifactInfo? runtime)); - Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "audio-data", out AssetArtifactInfo? data)); + private void Write( + string path, + byte[] bytes + ) => File.WriteAllBytes(Path.Combine(m_assets, path), bytes); + + private static AudioClipAsset Load( + AssetLoader loader, + string path + ) => Assert.IsType(loader.Load(AssetPath.Project(path), typeof(AudioClipAsset))); + + private static void AssertSeparateArtifact( + AssetLoader loader, + AudioClipAsset asset, + byte[] expected + ) { + Assert.True(loader.TryGetArtifact(asset.identity.persistentID, "runtime", out AssetArtifactInfo? runtime)); + Assert.True(loader.TryGetArtifact(asset.identity.persistentID, "audio-data", out AssetArtifactInfo? data)); Assert.NotNull(runtime); Assert.NotNull(data); Assert.InRange(runtime.length, 1, 127); Assert.NotEqual(runtime.outputName, data.outputName); - using ArtifactLease encoded = loader.AcquireArtifact(asset.identity.persistentId, "audio-data"); + using ArtifactLease encoded = loader.AcquireArtifact(asset.identity.persistentID, "audio-data"); Assert.Equal(expected, encoded.ReadAllBytes()); } - private void Write(string path, byte[] bytes) => File.WriteAllBytes(Path.Combine(m_assets, path), bytes); - private static byte[] CreateWav() { - byte[] bytes = new byte[60]; + var bytes = new byte[60]; "RIFF"u8.CopyTo(bytes); BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4, 4), 52); "WAVEfmt "u8.CopyTo(bytes.AsSpan(8)); BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(16, 4), 16); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(20, 2), 1); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(22, 2), 2); - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(24, 4), 48000); - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(28, 4), 192000); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(24, 4), 48_000); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(28, 4), 192_000); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(32, 2), 4); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(34, 2), 16); "data"u8.CopyTo(bytes.AsSpan(36)); @@ -129,19 +141,19 @@ private static byte[] CreateWav() private static byte[] CreateFlac() { - byte[] bytes = new byte[42]; + var bytes = new byte[42]; "fLaC"u8.CopyTo(bytes); bytes[4] = 0x80; bytes[7] = 34; - ulong packed = ((ulong)48000 << 44) | (1UL << 41) | (15UL << 36) | 48000UL; + ulong packed = ((ulong)48_000 << 44) | (1UL << 41) | (15UL << 36) | 48_000UL; BinaryPrimitives.WriteUInt64BigEndian(bytes.AsSpan(18, 8), packed); return bytes; } private static byte[] CreateMp3() { - byte[] bytes = new byte[417]; - BinaryPrimitives.WriteUInt32BigEndian(bytes, 0xfffb9000); + var bytes = new byte[417]; + BinaryPrimitives.WriteUInt32BigEndian(bytes, 0xFFFB_9000); return bytes; } } diff --git a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs index b38927514..9d27b0613 100644 --- a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs +++ b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs @@ -1,41 +1,62 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; -using Inno.Core.Diagnostics; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Assets; using Inno.Audio.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.References; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; +using Inno.References; namespace Inno.Audio.Runtime.Tests; public sealed class AudioRuntimeTests : IDisposable { + private readonly FakeArtifactLookup m_artifacts = new(); + private readonly EventDispatcher m_events = new(); + private readonly string m_root; + private readonly ModuleHost m_modules; + private readonly TypeCatalog m_types; + + public AudioRuntimeTests() + { + m_root = Path.Combine(Path.GetTempPath(), "InnoAudioRuntimeTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(m_root); + m_modules = new ModuleHost(new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioRuntimeTests).Assembly) + }); + _ = typeof(TestMixerExtension); + m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + m_types.Rebuild(); + } + [Fact] public void ConsumedApplicationLifecycleStillSuspendsAudioAndUnsubscribesOnStop() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension.consumed", "Suspension")); - using var consumer = m_events.CreateHub(int.MaxValue); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter( + new DiagnosticSource("test.suspension.consumed", "Suspension") + ); + using EventHub consumer = m_events.CreateHub(int.MaxValue); consumer.Listen(e => e.HandleInGlobal()); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); var suspension = new ApplicationSuspensionChangedEvent(true); m_events.Emit(suspension); Assert.True(suspension.isGlobalHandled); - Assert.True(device.GetBusPaused(AudioBusId.master)); + Assert.True(device.GetBusPaused(AudioBusID.master)); m_events.Emit(new ApplicationSuspensionChangedEvent(false)); - Assert.False(device.GetBusPaused(AudioBusId.master)); + Assert.False(device.GetBusPaused(AudioBusID.master)); runtime.Dispose(); int callsAfterStop = device.busPauseCalls; m_events.Emit(new ApplicationSuspensionChangedEvent(true)); @@ -46,10 +67,12 @@ public void ConsumedApplicationLifecycleStillSuspendsAudioAndUnsubscribesOnStop( public void FailedSuspensionRollsBackRetainedMixerRootsAndRemainsRetryable() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension.rollback", "Suspension")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter( + new DiagnosticSource("test.suspension.rollback", "Suspension") + ); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); - runtime.Play(CreateClip(480000), new AudioPlayOptions(loop: true)); + runtime.Play(CreateClip(480_000), new AudioPlayOptions(loop: true)); runtime.Update(0); Assert.True(runtime.ApplyMixer(new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" })); device.failBusPauseAt = device.busPauseCalls + 2; @@ -67,26 +90,26 @@ public void FailedSuspensionRollsBackRetainedMixerRootsAndRemainsRetryable() public void ApplicationSuspensionPreservesUserPauseAndReplacementMixerState() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension", "Suspension")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension", "Suspension")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); - Assert.True(runtime.SetBusPaused(AudioBusId.master, true)); + Assert.True(runtime.SetBusPaused(AudioBusID.master, true)); m_events.Emit(new ApplicationSuspensionChangedEvent(true)); m_events.Emit(new ApplicationSuspensionChangedEvent(false)); - Assert.True(device.GetBusPaused(AudioBusId.master)); + Assert.True(device.GetBusPaused(AudioBusID.master)); - Assert.True(runtime.SetBusPaused(AudioBusId.master, false)); + Assert.True(runtime.SetBusPaused(AudioBusID.master, false)); m_events.Emit(new ApplicationSuspensionChangedEvent(true)); - Assert.True(runtime.SetBusPaused(AudioBusId.master, false)); - Assert.True(device.GetBusPaused(AudioBusId.master)); + Assert.True(runtime.SetBusPaused(AudioBusID.master, false)); + Assert.True(device.GetBusPaused(AudioBusID.master)); Assert.True(runtime.ApplyMixer(new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" })); - Assert.True(device.GetBusPaused(AudioBusId.master)); + Assert.True(device.GetBusPaused(AudioBusID.master)); var replacement = new ReadyAudioDevice(); runtime.ReplaceDevice(replacement); - Assert.True(replacement.GetBusPaused(AudioBusId.master)); + Assert.True(replacement.GetBusPaused(AudioBusID.master)); m_events.Emit(new ApplicationSuspensionChangedEvent(false)); - Assert.False(replacement.GetBusPaused(AudioBusId.master)); + Assert.False(replacement.GetBusPaused(AudioBusID.master)); runtime.Dispose(); m_events.Emit(new ApplicationSuspensionChangedEvent(true)); Assert.Equal(1, replacement.disposals); @@ -95,10 +118,10 @@ public void ApplicationSuspensionPreservesUserPauseAndReplacementMixerState() [Fact] public void InvalidPlaybackOptionsDoNotStealOrAcquireAnArtifact() { - using var runtime = CreateRuntime(maxVoices: 1); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + using AudioRuntime runtime = CreateRuntime(maxVoices: 1); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); int acquisitions = m_artifacts.acquisitions; Assert.Throws(() => runtime.Play(next, default)); Assert.Equal(acquisitions, m_artifacts.acquisitions); @@ -112,10 +135,10 @@ public void InvalidPlaybackOptionsDoNotStealOrAcquireAnArtifact() [Fact] public void ArtifactAcquisitionRetirementBarrierDoesNotStealOrBecomeDecodeFailure() { - using var runtime = CreateRuntime(maxVoices: 1); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + using AudioRuntime runtime = CreateRuntime(maxVoices: 1); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); m_artifacts.acquisitionFailure = new RetirementPendingException("Expected artifact retirement barrier."); Assert.Throws(() => runtime.Play(next)); Assert.Equal(0, runtime.statistics.stolenVoiceCount); @@ -130,17 +153,23 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt { var events = new EventDispatcher(queueCapacity: 1); var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.admission", "Admission")); - using var runtime = new AudioRuntime(m_types, device, m_artifacts, events, reporter, - new AudioRuntimeOptions { maxVoices = 1 }); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.admission", "Admission")); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + events, + reporter, + new AudioRuntimeOptions { maxVoices = 1 } + ); using EventHub hub = events.CreateHub(); - var completions = new List(); + List completions = []; hub.Listen(completions.Add); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); events.Enqueue(new AudioVoiceCompletedEvent(new AudioVoiceAllocator().Allocate(), AudioCompletionReason.Stopped)); - m_artifacts.pendingReleaseId = next.identity.persistentId; + m_artifacts.pendingReleaseID = next.identity.persistentID; m_artifacts.pendingReleases = 1; Assert.Throws(() => runtime.Play(next)); Assert.Empty(m_artifacts.retainedKeys); @@ -165,9 +194,9 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt [Fact] public void OrdinaryMissingMetadataStillCompletesThroughTheAsynchronousVoiceProtocol() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); using EventHub hub = m_events.CreateHub(); - var completed = new List(); + List completed = []; hub.Listen(completed.Add); AudioVoiceHandle voice = runtime.Play(new AudioClipAsset()); Assert.True(runtime.TryGetVoiceState(voice, out AudioPlaybackState preparing)); @@ -181,8 +210,8 @@ public void OrdinaryMissingMetadataStillCompletesThroughTheAsynchronousVoiceProt [Fact] public void UndefinedPreloadModeIsRejectedBeforeArtifactAcquisition() { - using var runtime = CreateRuntime(); - AudioClipAsset clip = CreateClip(48000); + using AudioRuntime runtime = CreateRuntime(); + AudioClipAsset clip = CreateClip(48_000); Assert.Throws(() => runtime.PreloadAsync(clip, (AudioClipLoadMode)999)); Assert.Equal(0, m_artifacts.acquisitions); Assert.Equal(0, runtime.statistics.loadedClips); @@ -193,15 +222,22 @@ public void MutedBackendRejectsInvalidValuesWithTheSameAdmissionPolicy() { using var device = new MutedAudioDevice(); IAudioDevice backend = device; - AudioClipAsset asset = CreateClip(48000); - using ArtifactLease artifact = m_artifacts.AcquireArtifact(asset.identity.persistentId, "audio-data"); - AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( AudioCodecId.wav, AudioClipLoadMode.Decode, 2, 48000, 48000, artifact.info.length),new LeaseAudioTestSource(artifact)); + AudioClipAsset asset = CreateClip(48_000); + using ArtifactLease artifact = m_artifacts.AcquireArtifact(asset.identity.persistentID, "audio-data"); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( AudioCodecID.wav, AudioClipLoadMode.Decode, 2, 48_000, 48_000, artifact.info.length), + new LeaseAudioTestSource(artifact) + ); Assert.False(backend.Play(clip, master, default).isValid); foreach (double invalid in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1d }) + { Assert.False(backend.Play(clip, master, AudioPlayOptions.defaultValue, invalid).isValid); + } foreach (float invalid in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity }) + { Assert.False(backend.SetBusVolume(master, invalid)); + } Assert.Equal(0, backend.statistics.activeVoices); AudioDeviceVoiceHandle voice = backend.Play(clip, master, AudioPlayOptions.defaultValue); Assert.False(backend.SetVoiceParameters(voice, default)); @@ -217,7 +253,7 @@ public void ProviderFailureDiscardsItsEntireContributionAndReleasesItsIdentities var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var emitter = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var listener = new AudioListenerSnapshot(Guid.NewGuid(), 0, default, true); content.first = context => @@ -226,14 +262,24 @@ public void ProviderFailureDiscardsItsEntireContributionAndReleasesItsIdentities context.Submit(listener); throw new InvalidOperationException("Expected partial provider failure."); }; - content.second = context => { context.Submit(emitter); context.Submit(listener); }; + content.second = context => + { + context.Submit(emitter); + context.Submit(listener); + }; var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.content", "Content")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.content", "Content")); var device = new ReadyAudioDevice(); - using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.Equal(new AudioContentStatistics(1024, 2, 1), runtime.contentStatistics); @@ -252,15 +298,25 @@ public void CrossProviderDuplicateRejectsTheWholeBatchWithoutClaimingOtherIdenti var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var first = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var second = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); content.first = context => context.Submit(first); - content.second = context => { context.Submit(second); context.Submit(first); }; + content.second = context => + { + context.Submit(second); + context.Submit(first); + }; content.third = context => context.Submit(second); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.duplicate", "Duplicate")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.duplicate", "Duplicate")); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.Equal(new AudioContentStatistics(1024, 2, 1), runtime.contentStatistics); @@ -273,7 +329,7 @@ public void RepeatedOverflowIsBoundedAndCannotBeHiddenByAProviderCatch() var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var first = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var overflow = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var last = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); @@ -281,14 +337,24 @@ public void RepeatedOverflowIsBoundedAndCannotBeHiddenByAProviderCatch() content.second = context => { context.Submit(overflow); - try { context.Submit(last); } + try + { + context.Submit(last); + } catch (InvalidOperationException) { } }; content.third = context => context.Submit(last); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.capacity", "Capacity")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.capacity", "Capacity")); var options = new AudioRuntimeOptions { maxContentSnapshots = 2 }; - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - options, () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + options, + () => new ContentReadScope([content.identity]) + ); options.maxContentSnapshots = 100; for (int frame = 0; frame < 256; frame++) @@ -312,10 +378,20 @@ public void ProviderContextAndContentLookupAreRevokedAfterTheUpdate() identities.Register(content); AudioContentProviderContext? captured = null; ContentReadScope? capturedScope = null; - content.first = context => { captured = context; capturedScope = context.content; }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.scope", "Scope")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + content.first = context => + { + captured = context; + capturedScope = context.content; + }; + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.scope", "Scope")); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.NotNull(captured); Assert.Throws(() => captured!.Submit(default(AudioListenerSnapshot))); @@ -337,9 +413,15 @@ public void ProviderRetirementPendingIsNotConvertedToARejectedContribution() throw new RetirementPendingException("Expected provider work drain."); }; content.second = _ => nextInvoked = true; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending-content", "Pending")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending-content", "Pending")); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); Assert.Throws(() => runtime.Update(0)); Assert.False(nextInvoked); Assert.Equal(0, runtime.contentStatistics.rejectedProviders); @@ -352,63 +434,28 @@ public void ProviderRetirementPendingIsNotConvertedToARejectedContribution() [InlineData(float.PositiveInfinity)] public void InvalidUpdateTimeIsRejectedBeforeProviderExecution(float deltaTime) { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); Assert.Throws(() => runtime.Update(deltaTime)); } - private sealed class TestAudioContent : IdentityObject - { - internal Action? first; - internal Action? second; - internal Action? third; - } - - [AudioContentProviderExtension("tests.content.first", -30)] - private sealed class FirstContentProvider : AudioContentProvider - { - public override void Submit(AudioContentProviderContext context) - { - foreach (TestAudioContent content in context.content.GetValues()) - content.first?.Invoke(context); - } - } - - [AudioContentProviderExtension("tests.content.second", -20)] - private sealed class SecondContentProvider : AudioContentProvider - { - public override void Submit(AudioContentProviderContext context) - { - foreach (TestAudioContent content in context.content.GetValues()) - content.second?.Invoke(context); - } - } - - [AudioContentProviderExtension("tests.content.third", -10)] - private sealed class ThirdContentProvider : AudioContentProvider - { - public override void Submit(AudioContentProviderContext context) - { - foreach (TestAudioContent content in context.content.GetValues()) - content.third?.Invoke(context); - } - } - [Theory] [InlineData(true)] [InlineData(false)] public async Task PendingClipRetirementPreservesDeviceAndRetriesExactlyOnce(bool playing) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending", "Pending")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending", "Pending")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); if (playing) { runtime.Play(clip); runtime.Update(0); } else + { await runtime.PreloadAsync(clip); + } device.pendingClipRetirements = 1; Assert.Throws(runtime.Dispose); @@ -428,7 +475,7 @@ public async Task PendingClipRetirementPreservesDeviceAndRetriesExactlyOnce(bool public void PendingBusRetirementDoesNotDestroyTheDeviceBeforeRetry() { var device = new ReadyAudioDevice { pendingBusRetirements = 1 }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.bus", "Bus")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.bus", "Bus")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); Assert.Throws(runtime.Dispose); Assert.Equal(0, device.disposals); @@ -442,9 +489,9 @@ public void PendingReplacementRetirementDrainsBeforePublishingTheNewDevice() { var previous = new ReadyAudioDevice { pendingBusRetirements = 1 }; var replacement = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replacement", "Replacement")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replacement", "Replacement")); using var runtime = new AudioRuntime(m_types, previous, m_artifacts, m_events, reporter); - AudioVoiceHandle oldVoice = runtime.Play(CreateClip(48000)); + AudioVoiceHandle oldVoice = runtime.Play(CreateClip(48_000)); runtime.ReplaceDevice(replacement); Assert.Equal(2, previous.busRetirements); Assert.Equal(1, previous.disposals); @@ -458,7 +505,7 @@ public void PendingReplacementRetirementDrainsBeforePublishingTheNewDevice() [Fact] public void PendingProviderIsRetriedBeforeItsGenerationIsReleased() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.disposals = 0; RetirementProviderFirst.pendingRetirements = 1; @@ -468,17 +515,20 @@ public void PendingProviderIsRetriedBeforeItsGenerationIsReleased() Assert.Equal(2, RetirementProviderFirst.disposals); Assert.NotEqual("Faulted", m_modules.generations.state.ToString()); } - finally { RetirementProviderFirst.pendingRetirements = 0; } + finally + { + RetirementProviderFirst.pendingRetirements = 0; + } } [Fact] public void CompletionBackpressureRetainsTheVoiceUntilItsEventIsAccepted() { var events = new EventDispatcher(queueCapacity: 1); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.completion", "Completion")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.completion", "Completion")); using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, events, reporter); using EventHub hub = events.CreateHub(); - var completed = new List(); + List completed = []; hub.Listen(completed.Add); AudioVoiceHandle voice = runtime.Play(CreateClip(4800)); events.Enqueue(new AudioVoiceCompletedEvent(voice, AudioCompletionReason.Stopped)); @@ -499,7 +549,7 @@ public void CompletionBackpressureRetainsTheVoiceUntilItsEventIsAccepted() [Fact] public void CandidateCleanupFailureFaultsInsteadOfReportingRecoverableMixerFailure() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.fail = true; RetirementProviderSecond.failConstruction = true; @@ -520,7 +570,7 @@ public void CandidateCleanupFailureFaultsInsteadOfReportingRecoverableMixerFailu public async Task CacheRetirementAttemptsEveryClipBeforeDeviceDisposal() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.retire", "Retire")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.retire", "Retire")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); await runtime.PreloadAsync(CreateClip(4800)); await runtime.PreloadAsync(CreateClip(9600)); @@ -536,7 +586,7 @@ public void FailedOldDeviceRetirementConsumesCandidateAndFaultsWithoutFalseRecov { var previous = new ReadyAudioDevice { failDisposal = true }; var candidate = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replace", "Replace")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replace", "Replace")); var runtime = new AudioRuntime(m_types, previous, m_artifacts, m_events, reporter); Assert.Throws(() => runtime.ReplaceDevice(candidate)); Assert.Equal(1, previous.disposals); @@ -553,7 +603,7 @@ public void RecoveryClearsMutedAndRecoveryFailureDiagnostics() var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.device", "Device")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.device", "Device")); using var runtime = new AudioRuntime(m_types, new MutedAudioDevice(), m_artifacts, m_events, reporter); Assert.Contains(sink.issues, issue => issue.code == "AUDIO_NO_DEVICE"); Assert.False(runtime.TryRecoverDevice(static () => throw new InvalidOperationException("Device unavailable."))); @@ -565,7 +615,7 @@ public void RecoveryClearsMutedAndRecoveryFailureDiagnostics() [Fact] public void ProviderRetirementAttemptsEveryInstanceAndFaultsSharedGeneration() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.disposals = 0; RetirementProviderSecond.disposals = 0; @@ -577,38 +627,10 @@ public void ProviderRetirementAttemptsEveryInstanceAndFaultsSharedGeneration() Assert.Equal(1, RetirementProviderSecond.disposals); Assert.Equal("Faulted", m_modules.generations.state.ToString()); } - finally { RetirementProviderFirst.fail = false; } - } - - [AudioContentProviderExtension("tests.retirement.first", -100)] - private sealed class RetirementProviderFirst : AudioContentProvider - { - internal static bool fail; - internal static int disposals; - internal static int pendingRetirements; - public override void Submit(AudioContentProviderContext context) { } - protected override void Dispose(bool disposing) - { - disposals++; - if (pendingRetirements-- > 0) - throw new RetirementPendingException("Expected provider drain."); - if (fail) - throw new InvalidOperationException("Expected provider retirement failure."); - } - } - - [AudioContentProviderExtension("tests.retirement.second", 100)] - private sealed class RetirementProviderSecond : AudioContentProvider - { - internal static bool failConstruction; - internal static int disposals; - public RetirementProviderSecond() + finally { - if (failConstruction) - throw new InvalidOperationException("Expected provider candidate failure."); + RetirementProviderFirst.fail = false; } - public override void Submit(AudioContentProviderContext context) { } - protected override void Dispose(bool disposing) => disposals++; } [Fact] @@ -617,7 +639,7 @@ public void RecoveredMixerResolvesItsPreviousMissingDiagnostic() var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.mixer", "Mixer")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.mixer", "Mixer")); using var runtime = new AudioRuntime(m_types, new MutedAudioDevice(), m_artifacts, m_events, reporter); var mixer = new AudioMixerAsset { mixerTypeId = "tests.unavailable" }; Assert.False(runtime.ApplyMixer(mixer)); @@ -627,45 +649,23 @@ public void RecoveredMixerResolvesItsPreviousMissingDiagnostic() Assert.DoesNotContain(sink.issues, issue => issue.code == "AUDIO_MIXER_EXTENSION_MISSING"); } - private sealed class RecordingSink : IDiagnosticSink - { - internal IReadOnlyList issues { get; private set; } = []; - public void Replace(DiagnosticReport report) => issues = report.diagnostics; - public void Clear(DiagnosticSource source) => issues = []; - } - - private readonly FakeArtifactLookup m_artifacts = new(); - private readonly EventDispatcher m_events = new(); - private readonly string m_root; - private readonly ModuleHost m_modules; - private readonly TypeCatalog m_types; - - public AudioRuntimeTests() - { - m_root = Path.Combine(Path.GetTempPath(), "InnoAudioRuntimeTests", Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(m_root); - m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioRuntimeTests).Assembly) }); - _ = typeof(TestMixerExtension); - m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - m_types.Rebuild(); - } - public void Dispose() { m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] public void PlayTransitionsFromPreparingToNaturalCompletionOnMainThread() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); using EventHub hub = m_events.CreateHub(); - var completions = new List(); + List completions = []; hub.Listen(completions.Add); AudioVoiceHandle voice = runtime.Play(clip); @@ -688,11 +688,8 @@ public void PlayTransitionsFromPreparingToNaturalCompletionOnMainThread() public void ScheduledLoopingVoiceSupportsPauseResumeAndSeek() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); - AudioVoiceHandle voice = runtime.PlayScheduled( - clip, - 1d, - new AudioPlayOptions(loop: true)); + using AudioRuntime runtime = CreateRuntime(); + AudioVoiceHandle voice = runtime.PlayScheduled(clip, 1d, new AudioPlayOptions(loop: true)); runtime.Update(0.1f); Assert.True(runtime.TryGetVoiceState(voice, out AudioPlaybackState scheduled)); @@ -710,10 +707,10 @@ public void ScheduledLoopingVoiceSupportsPauseResumeAndSeek() [Fact] public void VoiceBudgetStealsLowestPriorityThenOldestVoice() { - AudioClipAsset clip = CreateClip(frameCount: 480000); - using var runtime = CreateRuntime(maxVoices: 2); + AudioClipAsset clip = CreateClip(frameCount: 480_000); + using AudioRuntime runtime = CreateRuntime(maxVoices: 2); using EventHub hub = m_events.CreateHub(); - var completions = new List(); + List completions = []; hub.Listen(completions.Add); AudioVoiceHandle first = runtime.Play(clip, new AudioPlayOptions(priority: 1)); AudioVoiceHandle second = runtime.Play(clip, new AudioPlayOptions(priority: 10)); @@ -736,7 +733,7 @@ public void VoiceBudgetStealsLowestPriorityThenOldestVoice() public async Task PreloadRetainsDistinctDecodeAndStreamEntriesUntilReleased() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); await runtime.PreloadAsync(clip, AudioClipLoadMode.Decode); await runtime.PreloadAsync(clip, AudioClipLoadMode.Stream); @@ -751,9 +748,10 @@ public async Task PreloadRetainsDistinctDecodeAndStreamEntriesUntilReleased() public async Task AutomaticPreparationStreamsWhenDecodedFootprintExceedsBudget() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime( + using AudioRuntime runtime = CreateRuntime( decodedCacheBudgetBytes: 1024, - automaticStreamingThresholdBytes: long.MaxValue); + automaticStreamingThresholdBytes: long.MaxValue + ); await runtime.PreloadAsync(clip); @@ -765,22 +763,22 @@ public async Task AutomaticPreparationStreamsWhenDecodedFootprintExceedsBudget() [Fact] public void MixerExtensionBuildsOpenBusGraphAndMissingCandidateKeepsLastGood() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); var mixer = new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" }; Assert.True(runtime.ApplyMixer(mixer)); - Assert.True(runtime.SetBusVolume(new AudioBusId("tests.audio.bus.music"), 0.5f)); + Assert.True(runtime.SetBusVolume(new AudioBusID("tests.audio.bus.music"), 0.5f)); mixer.mixerTypeId = "tests.audio.missing"; Assert.False(runtime.ApplyMixer(mixer)); - Assert.True(runtime.SetBusMuted(new AudioBusId("tests.audio.bus.music"), true)); + Assert.True(runtime.SetBusMuted(new AudioBusID("tests.audio.bus.music"), true)); } [Fact] public void DeviceReplacementCompletesOldHandlesAndUsesANewGeneration() { - AudioClipAsset clip = CreateClip(frameCount: 480000); - using var runtime = CreateRuntime(); + AudioClipAsset clip = CreateClip(frameCount: 480_000); + using AudioRuntime runtime = CreateRuntime(); AudioVoiceHandle oldVoice = runtime.Play(clip); runtime.Update(0f); @@ -796,10 +794,10 @@ public void DeviceReplacementCompletesOldHandlesAndUsesANewGeneration() [Fact] public void RecoveryCandidatePreservesTheLastGoodMixerGraph() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); var mixer = new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" }; Assert.True(runtime.ApplyMixer(mixer)); - AudioBusId music = new("tests.audio.bus.music"); + var music = new AudioBusID("tests.audio.bus.music"); Assert.True(runtime.SetBusVolume(music, 0.25f)); Assert.True(runtime.SetBusPaused(music, true)); var replacement = new ReadyAudioDevice(); @@ -815,8 +813,13 @@ public void RecoveryCandidatePreservesTheLastGoodMixerGraph() public async Task PreloadCompletesOnlyAfterPreparationAndCancellationReleasesReservation() { var device = new ReadyAudioDevice { clipState = AudioClipState.Preparing }; - using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("test.preload", "Preload"))); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + m_events, + new DiagnosticHub().CreateReporter(new DiagnosticSource("test.preload", "Preload")) + ); AudioClipAsset clip = CreateClip(4800); ValueTask ready = runtime.PreloadAsync(clip); Assert.False(ready.IsCompleted); @@ -840,11 +843,11 @@ public async Task PreloadCompletesOnlyAfterPreparationAndCancellationReleasesRes public async Task PreloadedArtifactRetirementResumesWithoutDestroyingTheNativeClipTwice(bool shutdown) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.artifact", "Artifact")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.artifact", "Artifact")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); - m_artifacts.pendingReleaseId = clip.identity.persistentId; + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; Action release = shutdown ? runtime.Dispose : () => runtime.ReleasePreload(clip); Assert.Throws(release); @@ -852,25 +855,31 @@ public async Task PreloadedArtifactRetirementResumesWithoutDestroyingTheNativeCl Assert.Single(m_artifacts.retainedKeys); Assert.Equal(0, device.disposals); if (shutdown) + { runtime.Dispose(); + } else + { runtime.Update(0); + } Assert.Equal(1, device.clipRetirements); Assert.Empty(m_artifacts.retainedKeys); if (!shutdown) + { Assert.Equal(0, runtime.statistics.loadedClips); + } } [Fact] public void CanceledPreloadDoesNotCompleteBeforeItsPendingArtifactRetires() { var device = new ReadyAudioDevice { clipState = AudioClipState.Preparing }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.cancel", "Cancel")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.cancel", "Cancel")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); using var cancellation = new CancellationTokenSource(); Task pending = runtime.PreloadAsync(clip, cancellationToken: cancellation.Token).AsTask(); - m_artifacts.pendingReleaseId = clip.identity.persistentId; + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; cancellation.Cancel(); Assert.Throws(() => runtime.Update(0)); @@ -888,11 +897,11 @@ public void CanceledPreloadDoesNotCompleteBeforeItsPendingArtifactRetires() public async Task APartiallyRetiredClipCannotBeReusedByANewVoice() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.reuse", "Reuse")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.reuse", "Reuse")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); - m_artifacts.pendingReleaseId = clip.identity.persistentId; + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; Assert.Throws(() => runtime.ReleasePreload(clip)); AudioVoiceHandle voice = runtime.Play(clip, new AudioPlayOptions(loop: true)); @@ -910,10 +919,10 @@ public async Task APartiallyRetiredClipCannotBeReusedByANewVoice() [Fact] public async Task CacheHitRequestRetiresItsExtraArtifactThroughTheSharedGenerationBarrier() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); - m_artifacts.pendingReleaseId = clip.identity.persistentId; + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; await runtime.PreloadAsync(clip); Assert.Equal(2, m_artifacts.releaseAttempts); @@ -926,11 +935,11 @@ public async Task CacheHitRequestRetiresItsExtraArtifactThroughTheSharedGenerati [Fact] public async Task RetryingPreloadReleaseDoesNotConsumeAnotherLoadModeReservation() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip, AudioClipLoadMode.Decode); await runtime.PreloadAsync(clip, AudioClipLoadMode.Stream); - m_artifacts.pendingReleaseId = clip.identity.persistentId; + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; Assert.Throws(() => runtime.ReleasePreload(clip)); runtime.ReleasePreload(clip); @@ -946,19 +955,27 @@ public async Task RetryingPreloadReleaseDoesNotConsumeAnotherLoadModeReservation [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] - public async Task FailedPreloadAdmissionRetiresOnlyItsOwnReservation(bool cached, bool queryThrows) - { + public async Task FailedPreloadAdmissionRetiresOnlyItsOwnReservation( + bool cached, + bool queryThrows + ) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.query", "Query")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.query", "Query")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); if (cached) + { await runtime.PreloadAsync(clip); + } if (queryThrows) + { device.clipQueryFailure = new InvalidOperationException("Expected clip query failure."); + } else + { device.clipState = AudioClipState.Failed; - m_artifacts.pendingReleaseId = clip.identity.persistentId; + } + m_artifacts.pendingReleaseID = clip.identity.persistentID; m_artifacts.pendingReleases = 1; InvalidOperationException failure = Assert.Throws(() => runtime.PreloadAsync(clip)); Assert.Contains(queryThrows ? "query failure" : "preparation failed", failure.Message); @@ -987,7 +1004,7 @@ public void PreloadQueryAndRollbackFailureRetainBothDiagnosticsAndFaultTheGenera clipQueryFailure = new InvalidOperationException("Expected clip query failure."), failClipRetirement = true }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.rollback", "Rollback")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.rollback", "Rollback")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); AggregateException failure = Assert.Throws(() => runtime.PreloadAsync(clip)); @@ -1004,49 +1021,145 @@ public void PreloadQueryAndRollbackFailureRetainBothDiagnosticsAndFaultTheGenera private AudioRuntime CreateRuntime( int maxVoices = 128, long decodedCacheBudgetBytes = 128L * 1024 * 1024, - long automaticStreamingThresholdBytes = 1024) - => new( - m_types, - new MutedAudioDevice(), - m_artifacts, - m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("tests.audio", "Audio")), - options: new AudioRuntimeOptions - { - maxVoices = maxVoices, - decodedCacheBudgetBytes = decodedCacheBudgetBytes, - automaticStreamingThresholdBytes = automaticStreamingThresholdBytes - }); + long automaticStreamingThresholdBytes = 1024 + ) => new( + m_types, + new MutedAudioDevice(), + m_artifacts, + m_events, + new DiagnosticHub().CreateReporter(new DiagnosticSource("tests.audio", "Audio")), + options: new AudioRuntimeOptions + { + maxVoices = maxVoices, + decodedCacheBudgetBytes = decodedCacheBudgetBytes, + automaticStreamingThresholdBytes = automaticStreamingThresholdBytes + } + ); private AudioClipAsset CreateClip(long frameCount) { var clip = new AudioClipAsset(); - byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata( - AudioCodecId.wav, - 2, - 48000, - frameCount, - 256)); + byte[] payload = AudioClipMetadataCodec.Encode( + new AudioClipMetadata(AudioCodecID.wav, 2, 48_000, frameCount, 256) + ); new AssetRuntimeOwner().Initialize( clip, - AssetPath.Project($"Audio/{clip.identity.persistentId:N}.wav"), + AssetPath.Project($"Audio/{clip.identity.persistentID:N}.wav"), "TEST", payload, isMissing: false, - version: 1); - m_artifacts.Add(clip.identity.persistentId, Path.Combine(m_root, $"{clip.identity.persistentId:N}.wav")); + version: 1 + ); + m_artifacts.Add(clip.identity.persistentID, Path.Combine(m_root, $"{clip.identity.persistentID:N}.wav")); return clip; } + private sealed class TestAudioContent : IdentityObject + { + internal Action? first; + internal Action? second; + internal Action? third; + } + + [AudioContentProviderExtension("tests.content.first", -30)] + private sealed class FirstContentProvider : AudioContentProvider + { + public override void Submit(AudioContentProviderContext context) + { + foreach (TestAudioContent content in context.content.GetValues()) + { + content.first?.Invoke(context); + } + } + } + + [AudioContentProviderExtension("tests.content.second", -20)] + private sealed class SecondContentProvider : AudioContentProvider + { + public override void Submit(AudioContentProviderContext context) + { + foreach (TestAudioContent content in context.content.GetValues()) + { + content.second?.Invoke(context); + } + } + } + + [AudioContentProviderExtension("tests.content.third", -10)] + private sealed class ThirdContentProvider : AudioContentProvider + { + public override void Submit(AudioContentProviderContext context) + { + foreach (TestAudioContent content in context.content.GetValues()) + { + content.third?.Invoke(context); + } + } + } + + [AudioContentProviderExtension("tests.retirement.first", -100)] + private sealed class RetirementProviderFirst : AudioContentProvider + { + internal static bool fail; + internal static int disposals; + internal static int pendingRetirements; + + public override void Submit(AudioContentProviderContext context) {} + + protected override void Dispose(bool disposing) + { + disposals++; + if (pendingRetirements-- > 0) + { + throw new RetirementPendingException("Expected provider drain."); + } + if (fail) + { + throw new InvalidOperationException("Expected provider retirement failure."); + } + } + } + + [AudioContentProviderExtension("tests.retirement.second", 100)] + private sealed class RetirementProviderSecond : AudioContentProvider + { + internal static bool failConstruction; + internal static int disposals; + + public RetirementProviderSecond() + { + if (failConstruction) + { + throw new InvalidOperationException("Expected provider candidate failure."); + } + } + + public override void Submit(AudioContentProviderContext context) {} + + protected override void Dispose(bool disposing) => disposals++; + } + + private sealed class RecordingSink : IDiagnosticSink + { + public void Replace(DiagnosticReport report) => issues = report.diagnostics; + + public void Clear(DiagnosticSource source) => issues = []; + + internal IReadOnlyList issues { get; private set; } = []; + } + [AudioMixerExtension("tests.audio.mixer")] private sealed class TestMixerExtension : AudioMixerExtension { - public override void Build(AudioMixerBuilder builder, SerializedAudioExtensionState state) - { - builder.AddBus(new AudioBusId("tests.audio.bus.music"), AudioBusId.master); + public override void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ) { + builder.AddBus(new AudioBusID("tests.audio.bus.music"), AudioBusID.master); builder.AddProcessor( - new AudioBusId("tests.audio.bus.music"), - new AudioProcessorConfiguration(AudioProcessorId.lowPass)); + new AudioBusID("tests.audio.bus.music"), + new AudioProcessorConfiguration(AudioProcessorID.lowPass) + ); } } @@ -1057,41 +1170,40 @@ private sealed class FakeArtifactLookup : AssetResidencyProvider, IAssetArtifact private readonly Dictionary m_paths = []; internal int acquisitions; internal Exception? acquisitionFailure; - internal Guid pendingReleaseId; + internal Guid pendingReleaseID; internal int pendingReleases; internal int releaseAttempts; - internal IReadOnlyList retainedKeys => m_retention.GetRetainedKeys(); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - { + + public ArtifactLease AcquireArtifact( + Guid persistentID, + string outputName + ) { acquisitions++; if (acquisitionFailure is not null) + { throw acquisitionFailure; - ArtifactLease retained = m_retention.Retain(m_artifacts[persistentId], - () => File.OpenRead(m_paths[persistentId])); + } + ArtifactLease retained = m_retention.Retain( + m_artifacts[persistentID], + () => File.OpenRead(m_paths[persistentID]) + ); return CreateArtifactLease(retained.info, retained.OpenRead, () => { releaseAttempts++; - if (persistentId == pendingReleaseId && pendingReleases-- > 0) + if (persistentID == pendingReleaseID && pendingReleases-- > 0) + { throw new RetirementPendingException("Expected admitted artifact drain."); + } retained.Dispose(); }); } - internal void Add(Guid id, string path) - { - byte[] bytes = new byte[256]; - File.WriteAllBytes(path, bytes); - m_paths[id] = path; - m_artifacts[id] = new AssetArtifactInfo( - new AssetArtifactKey(new string('A', 64)), - "audio-data", - Convert.ToHexString(SHA256.HashData(bytes)), - 256); - } - - public bool TryGetArtifact(Guid persistentId, string outputName, out AssetArtifactInfo? artifact) - { - if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentId, out AssetArtifactInfo? found)) + public bool TryGetArtifact( + Guid persistentID, + string outputName, + out AssetArtifactInfo? artifact + ) { + if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentID, out AssetArtifactInfo? found)) { artifact = found; return true; @@ -1099,13 +1211,30 @@ public bool TryGetArtifact(Guid persistentId, string outputName, out AssetArtifa artifact = null; return false; } + + internal IReadOnlyList retainedKeys => m_retention.GetRetainedKeys(); + + internal void Add( + Guid id, + string path + ) { + var bytes = new byte[256]; + File.WriteAllBytes(path, bytes); + m_paths[id] = path; + m_artifacts[id] = new AssetArtifactInfo( + new AssetArtifactKey(new string('A', 64)), + "audio-data", + Convert.ToHexString(SHA256.HashData(bytes)), + 256 + ); + } } private sealed class ReadyAudioDevice : IAudioDevice { - private readonly Dictionary m_busIds = []; - private readonly Dictionary m_busPaused = []; - private readonly Dictionary m_busVolumes = []; + private readonly Dictionary m_busIDs = []; + private readonly Dictionary m_busPaused = []; + private readonly Dictionary m_busVolumes = []; private readonly IAudioDevice m_inner = new MutedAudioDevice(); private readonly Dictionary m_pausedHandles = []; internal int busPauseCalls; @@ -1120,6 +1249,7 @@ private sealed class ReadyAudioDevice : IAudioDevice internal int listenerCreations; internal int stops; internal Exception? clipQueryFailure; + internal AudioClipState clipState = AudioClipState.Ready; public AudioCapabilities capabilities => m_inner.capabilities; @@ -1135,11 +1265,13 @@ public AudioClipHandle CreateClip( AudioClipDescriptor descriptor, IAudioClipSource source ) => m_inner.CreateClip(descriptor, source); - internal AudioClipState clipState = AudioClipState.Ready; + public AudioClipState GetClipState(AudioClipHandle clip) { if (clipQueryFailure is not null) + { throw clipQueryFailure; + } return clipState; } @@ -1147,9 +1279,13 @@ public bool DestroyClip(AudioClipHandle clip) { clipRetirements++; if (pendingClipRetirements-- > 0) + { throw new RetirementPendingException("Expected clip drain."); + } if (failClipRetirement) + { throw new InvalidOperationException("Expected clip retirement failure."); + } return m_inner.DestroyClip(clip); } @@ -1157,8 +1293,8 @@ public AudioDeviceVoiceHandle Play( AudioClipHandle clip, AudioBusHandle bus, AudioPlayOptions options, - double? scheduledDspTime = null) - => m_inner.Play(clip, bus, options, scheduledDspTime); + double? scheduledDspTime = null + ) => m_inner.Play(clip, bus, options, scheduledDspTime); public bool Stop(AudioDeviceVoiceHandle voice) { @@ -1170,20 +1306,29 @@ public bool Stop(AudioDeviceVoiceHandle voice) public bool Resume(AudioDeviceVoiceHandle voice) => m_inner.Resume(voice); - public bool Seek(AudioDeviceVoiceHandle voice, TimeSpan position) => m_inner.Seek(voice, position); - - public bool SetVoiceParameters(AudioDeviceVoiceHandle voice, AudioVoiceParameters parameters) - => m_inner.SetVoiceParameters(voice, parameters); - - public bool TryGetVoiceState(AudioDeviceVoiceHandle voice, out AudioPlaybackState playbackState) - => m_inner.TryGetVoiceState(voice, out playbackState); - - public AudioBusHandle CreateBus(AudioBusId id, AudioBusHandle parent = default) - { + public bool Seek( + AudioDeviceVoiceHandle voice, + TimeSpan position + ) => m_inner.Seek(voice, position); + + public bool SetVoiceParameters( + AudioDeviceVoiceHandle voice, + AudioVoiceParameters parameters + ) => m_inner.SetVoiceParameters(voice, parameters); + + public bool TryGetVoiceState( + AudioDeviceVoiceHandle voice, + out AudioPlaybackState playbackState + ) => m_inner.TryGetVoiceState(voice, out playbackState); + + public AudioBusHandle CreateBus( + AudioBusID id, + AudioBusHandle parent = default + ) { AudioBusHandle handle = m_inner.CreateBus(id, parent); if (handle.isValid) { - m_busIds.Add(handle, id); + m_busIDs.Add(handle, id); m_pausedHandles.Add(handle, false); } return handle; @@ -1193,36 +1338,55 @@ public bool DestroyBus(AudioBusHandle bus) { busRetirements++; if (pendingBusRetirements-- > 0) + { throw new RetirementPendingException("Expected bus drain."); + } bool destroyed = m_inner.DestroyBus(bus); if (destroyed) + { m_pausedHandles.Remove(bus); + } return destroyed; } - public bool SetBusVolume(AudioBusHandle bus, float volume) - { + public bool SetBusVolume( + AudioBusHandle bus, + float volume + ) { if (!m_inner.SetBusVolume(bus, volume)) + { return false; - m_busVolumes[m_busIds[bus]] = volume; + } + m_busVolumes[m_busIDs[bus]] = volume; return true; } - public bool SetBusMuted(AudioBusHandle bus, bool muted) => m_inner.SetBusMuted(bus, muted); + public bool SetBusMuted( + AudioBusHandle bus, + bool muted + ) => m_inner.SetBusMuted(bus, muted); - public bool SetBusPaused(AudioBusHandle bus, bool paused) - { + public bool SetBusPaused( + AudioBusHandle bus, + bool paused + ) { if (++busPauseCalls == failBusPauseAt) + { return false; + } if (!m_inner.SetBusPaused(bus, paused)) + { return false; - m_busPaused[m_busIds[bus]] = paused; + } + m_busPaused[m_busIDs[bus]] = paused; m_pausedHandles[bus] = paused; return true; } - public bool AddBusProcessor(AudioBusHandle bus, AudioProcessorConfiguration processor) - => m_inner.AddBusProcessor(bus, processor); + public bool AddBusProcessor( + AudioBusHandle bus, + AudioProcessorConfiguration processor + ) => m_inner.AddBusProcessor(bus, processor); public AudioListenerHandle CreateListener(AudioListenerState state) { @@ -1230,8 +1394,10 @@ public AudioListenerHandle CreateListener(AudioListenerState state) return m_inner.CreateListener(state); } - public bool SetListener(AudioListenerHandle listener, AudioListenerState state) - => m_inner.SetListener(listener, state); + public bool SetListener( + AudioListenerHandle listener, + AudioListenerState state + ) => m_inner.SetListener(listener, state); public bool DestroyListener(AudioListenerHandle listener) => m_inner.DestroyListener(listener); @@ -1245,14 +1411,18 @@ public void Dispose() disposals++; m_inner.Dispose(); if (failDisposal) + { throw new InvalidOperationException("Expected device retirement failure."); + } } - internal float GetBusVolume(AudioBusId id) => m_busVolumes[id]; + internal float GetBusVolume(AudioBusID id) => m_busVolumes[id]; + + internal bool GetBusPaused(AudioBusID id) => m_busPaused[id]; - internal bool GetBusPaused(AudioBusId id) => m_busPaused[id]; internal IReadOnlyList GetMasterPauses() - => m_pausedHandles.Where(pair => m_busIds[pair.Key] == AudioBusId.master) - .Select(pair => pair.Value).ToArray(); + => m_pausedHandles.Where(pair => m_busIDs[pair.Key] == AudioBusID.master) + .Select(pair => pair.Value) + .ToArray(); } } diff --git a/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs b/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs index 2def5d2e6..3912ac7d3 100644 --- a/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs +++ b/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs @@ -7,5 +7,6 @@ internal sealed class LeaseAudioTestSource(ArtifactLease artifact) : IAudioClipS { public string contentHash => artifact.info.contentHash; public long length => artifact.info.length; + public Stream OpenRead() => artifact.OpenRead(); } diff --git a/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs b/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs index bdd63e501..afa63be37 100644 --- a/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; -using Inno.References; using Xunit; +using Inno.References; namespace Inno.Audio.Tests; @@ -39,9 +39,13 @@ public void DefaultSnapshotsPoisonTheContribution(bool emitter) using ContentReadScope content = ContentReadScope.empty; using var context = new AudioContentProviderContext(content, 0); if (emitter) + { Assert.Throws(() => context.Submit(default(AudioEmitterSnapshot))); + } else + { Assert.Throws(() => context.Submit(default(AudioListenerSnapshot))); + } Assert.Throws(() => _ = context.listeners); } diff --git a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs index 02a07f319..64b2f4ce8 100644 --- a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Audio; using Xunit; +using Inno.Audio; namespace Inno.Audio.Tests; public sealed class AudioContractTests { [Fact] - public void ExecutionContext_ForwardsFacadeAndEnforcesLifoDisposal() + public void ExecutionContextForwardsFacadeAndEnforcesLifoDisposal() { var outer = new FakeAudioService(1); var inner = new FakeAudioService(2); @@ -26,45 +27,46 @@ public void ExecutionContext_ForwardsFacadeAndEnforcesLifoDisposal() } [Fact] - public void MixerBuilder_ProducesParentBeforeChildGraphWithMasterBus() + public void MixerBuilderProducesParentBeforeChildGraphWithMasterBus() { var builder = new AudioMixerBuilder(); - AudioBusId music = new("game.audio.bus.music"); - AudioBusId ambience = new("game.audio.bus.ambience"); + var music = new AudioBusID("game.audio.bus.music"); + var ambience = new AudioBusID("game.audio.bus.ambience"); builder.AddBus(ambience, music); - builder.AddBus(music, AudioBusId.master); + builder.AddBus(music, AudioBusID.master); builder.AddProcessor( music, new AudioProcessorConfiguration( - AudioProcessorId.lowPass, - [new AudioProcessorParameter(new AudioParameterId("frequency"), 12000f)])); + AudioProcessorID.lowPass, + [new AudioProcessorParameter(new AudioParameterID("frequency"), 12000f)] + ) + ); AudioMixer mixer = builder.Build(); - Assert.Equal([AudioBusId.master, music, ambience], - System.Linq.Enumerable.Select(mixer.buses, static bus => bus.id)); + Assert.Equal([AudioBusID.master, music, ambience], Enumerable.Select(mixer.buses, static bus => bus.id)); Assert.Single(mixer.buses[1].processors); } [Fact] - public void MixerBuilder_RejectsMissingParentsAndCycles() + public void MixerBuilderRejectsMissingParentsAndCycles() { var missingParent = new AudioMixerBuilder(); - missingParent.AddBus(new AudioBusId("game.audio.bus.music"), new AudioBusId("missing")); + missingParent.AddBus(new AudioBusID("game.audio.bus.music"), new AudioBusID("missing")); Assert.Throws(missingParent.Build); var cycle = new AudioMixerBuilder(); - AudioBusId first = new("game.audio.bus.first"); - AudioBusId second = new("game.audio.bus.second"); + var first = new AudioBusID("game.audio.bus.first"); + var second = new AudioBusID("game.audio.bus.second"); cycle.AddBus(first, second); cycle.AddBus(second, first); Assert.Throws(cycle.Build); } [Fact] - public void MetadataCodec_RoundTripsCompactRuntimeHeader() + public void MetadataCodecRoundTripsCompactRuntimeHeader() { - var expected = new AudioClipMetadata(AudioCodecId.flac, 2, 48000, 96000, 123456); + var expected = new AudioClipMetadata(AudioCodecID.flac, 2, 48_000, 96_000, 123_456); byte[] payload = AudioClipMetadataCodec.Encode(expected); AudioClipMetadata actual = AudioClipMetadataCodec.Decode(payload); @@ -75,7 +77,7 @@ public void MetadataCodec_RoundTripsCompactRuntimeHeader() } [Fact] - public void DeviceHandleGeneration_RejectsStaleHandles() + public void DeviceHandleGenerationRejectsStaleHandles() { var first = new FakeAudioService(41); var replacement = new FakeAudioService(42); @@ -89,7 +91,7 @@ private sealed class FakeAudioService(uint generation) : IAudioService { private readonly AudioVoiceAllocator m_voices = new(); - public AudioCapabilities capabilities { get; } = new(true, true, true, 4, 48000); + public AudioCapabilities capabilities { get; } = new(true, true, true, 4, 48_000); public AudioDeviceState deviceState => AudioDeviceState.Ready; @@ -99,10 +101,7 @@ private sealed class FakeAudioService(uint generation) : IAudioService public AudioVoiceHandle CreateTestVoice() => m_voices.Allocate(); - public bool Owns(AudioVoiceHandle voice) - { - return voice.isValid && voice.ownerGeneration == m_voices.generation; - } + public bool Owns(AudioVoiceHandle voice) => voice.isValid && voice.ownerGeneration == m_voices.generation; public AudioVoiceHandle Play(AudioClipAsset clip) { @@ -110,14 +109,16 @@ public AudioVoiceHandle Play(AudioClipAsset clip) return CreateTestVoice(); } - public AudioVoiceHandle Play(AudioClipAsset clip, AudioPlayOptions options) - => Play(clip); + public AudioVoiceHandle Play( + AudioClipAsset clip, + AudioPlayOptions options + ) => Play(clip); public AudioVoiceHandle PlayScheduled( AudioClipAsset clip, double scheduledDspTime, - AudioPlayOptions options) - => Play(clip); + AudioPlayOptions options + ) => Play(clip); public bool Stop(AudioVoiceHandle voice) => Owns(voice); @@ -125,27 +126,44 @@ public AudioVoiceHandle PlayScheduled( public bool Resume(AudioVoiceHandle voice) => Owns(voice); - public bool Seek(AudioVoiceHandle voice, TimeSpan position) => Owns(voice) && position >= TimeSpan.Zero; + public bool Seek( + AudioVoiceHandle voice, + TimeSpan position + ) => Owns(voice) && position >= TimeSpan.Zero; - public bool SetVoiceParameters(AudioVoiceHandle voice, AudioVoiceParameters parameters) => Owns(voice); + public bool SetVoiceParameters( + AudioVoiceHandle voice, + AudioVoiceParameters parameters + ) => Owns(voice); - public bool TryGetVoiceState(AudioVoiceHandle voice, out AudioPlaybackState playbackState) - { + public bool TryGetVoiceState( + AudioVoiceHandle voice, + out AudioPlaybackState playbackState + ) { playbackState = Owns(voice) ? AudioPlaybackState.Playing : AudioPlaybackState.Invalid; return playbackState != AudioPlaybackState.Invalid; } - public bool SetBusVolume(AudioBusId bus, float volume) => bus.isValid && volume >= 0f; + public bool SetBusVolume( + AudioBusID bus, + float volume + ) => bus.isValid && volume >= 0f; - public bool SetBusMuted(AudioBusId bus, bool muted) => bus.isValid; + public bool SetBusMuted( + AudioBusID bus, + bool muted + ) => bus.isValid; - public bool SetBusPaused(AudioBusId bus, bool paused) => bus.isValid; + public bool SetBusPaused( + AudioBusID bus, + bool paused + ) => bus.isValid; public ValueTask PreloadAsync( AudioClipAsset clip, AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, - CancellationToken cancellationToken = default) - { + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(clip); cancellationToken.ThrowIfCancellationRequested(); return ValueTask.CompletedTask; diff --git a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs index f4c64dedc..1a9e5b1d7 100644 --- a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs @@ -1,20 +1,22 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using Inno.Assets; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Audio.Runtime; +using Inno.Build; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Settings; using Inno.Plugins; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Audio.Tests; @@ -23,27 +25,28 @@ public sealed class AudioScriptingApiTests [Fact] public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalNamespace() { - string projectRoot = Path.Combine( - Path.GetTempPath(), - "InnoAudioScriptingTests", - Guid.NewGuid().ToString("N")); + string projectRoot = Path.Combine(Path.GetTempPath(), "InnoAudioScriptingTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(Path.Combine(projectRoot, "Assets")); Directory.CreateDirectory(Path.Combine(projectRoot, "Plugins")); Directory.CreateDirectory(Path.Combine(projectRoot, "Library")); try { - _ = typeof(Inno.Audio.Audio); + _ = typeof(Audio); _ = typeof(AudioProjectSettings); var identities = new IdentityAllocator(); using IDisposable identityScope = identities.EnterScope(); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(AudioScriptingApiTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(AudioScriptingApiTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var pluginSources = new PluginSourceService( host.serialization, Path.Combine(projectRoot, "Plugins"), - Path.Combine(projectRoot, "Library")); + Path.Combine(projectRoot, "Library") + ); PluginScanResult scan = pluginSources.Scan(); using var assets = new AssetPipeline( host.modules, @@ -54,16 +57,19 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName host.logs, AssetPipelineOptions.Create( Path.Combine(projectRoot, "Assets"), - Path.Combine(projectRoot, "Library")) with + Path.Combine(projectRoot, "Library") + ) with { enableFileSystemWatcher = false - }); + } + ); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), host.types, host.serialization, - new ProjectId("tests.audio.scripting"), - AssetSerializationContext.Create(assets)); + new ProjectID("tests.audio.scripting"), + AssetSerializationContext.Create(assets) + ); using var plugins = new PluginEnvironment( assets, settings, @@ -71,18 +77,21 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName Path.Combine(projectRoot, "Plugins"), Path.Combine(projectRoot, "Library"), scan, - host.modules.generations); + host.modules.generations + ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); File.WriteAllText(Path.Combine(projectRoot, "Assets", "AudioProbe.cs"), """ using InnoEngine.Audio; @@ -99,7 +108,7 @@ public override void Build( AudioMixerBuilder builder, SerializedAudioExtensionState state) { - builder.AddBus(new AudioBusId("tests.audio.bus"), AudioBusId.master); + builder.AddBus(new AudioBusID("tests.audio.bus"), AudioBusID.master); } } @@ -115,14 +124,20 @@ public override void Submit(AudioContentProviderContext context) ScriptCompilationResult result = await compiler.CompileAuthoringGenerationAsync(); - Assert.True(result.success, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}"))); + Assert.True( + result.success, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") + ) + ); } finally { if (Directory.Exists(projectRoot)) + { Directory.Delete(projectRoot, recursive: true); + } } } } diff --git a/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs b/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs index db516f65e..79470a1fb 100644 --- a/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Core.Mathematics; using Inno.References; -using Xunit; namespace Inno.Audio.Tests; @@ -63,8 +63,18 @@ public void UndefinedModesAreRejectedAndFiniteBoundaryValuesRemainUsable() Assert.Equal(0, options.volume); Assert.Equal(float.Epsilon, options.pitch); Assert.Equal(-1, options.pan); - var spatial = new AudioSpatialOptions(default, default, default, minDistance: 0, maxDistance: 0, - rolloff: 0, coneInnerAngle: 0, coneOuterAngle: 360, coneOuterGain: 0, dopplerFactor: 0); + var spatial = new AudioSpatialOptions( + default, + default, + default, + minDistance: 0, + maxDistance: 0, + rolloff: 0, + coneInnerAngle: 0, + coneOuterAngle: 360, + coneOuterGain: 0, + dopplerFactor: 0 + ); Assert.Equal(360, spatial.coneOuterAngle); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs index d539f185e..3dcefb17a 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.Versioning; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -15,33 +15,46 @@ public sealed class BgfxCompositionProgramProviderTests public void EmbeddedTargetProgramMatchesTheDeviceBackendAndFullscreenLayout(bool outputTransfer) { if (!OperatingSystem.IsMacOS() && !OperatingSystem.IsWindows()) + { return; + } GraphicsApi[] apis = OperatingSystem.IsMacOS() - ? [GraphicsApi.Metal, GraphicsApi.Vulkan, GraphicsApi.OpenGL] - : [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL]; + ? [GraphicsApi.metal, GraphicsApi.vulkan, GraphicsApi.openGL] + : [GraphicsApi.direct3D11, GraphicsApi.direct3D12, GraphicsApi.vulkan, GraphicsApi.openGL]; var layout = new RenderVertexLayout( - [ - new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); var provider = new BgfxCompositionProgramProvider(); foreach (GraphicsApi api in apis) { var capabilities = new GraphicsCapabilities( - api, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false); + api, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); GraphicsPipelineDescriptor descriptor = outputTransfer - ? provider.CreateOutputTransferDescriptor(capabilities, layout) - : provider.CreateDescriptor(capabilities, layout); + ? provider.CreateOutputTransferDescriptor(capabilities, layout) + : provider.CreateDescriptor(capabilities, layout); Assert.Same(layout, descriptor.vertexLayout); Assert.Equal("s_tex", Assert.Single(descriptor.bindings).id.value); Assert.False(descriptor.vertexShader.IsEmpty); Assert.False(descriptor.fragmentShader.IsEmpty); - Assert.Equal(outputTransfer ? RenderBlendState.opaque : RenderBlendState.premultiplied, - descriptor.rasterState.blend); + Assert.Equal( + outputTransfer ? RenderBlendState.opaque : RenderBlendState.premultiplied, + descriptor.rasterState.blend + ); } } } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs new file mode 100644 index 000000000..8d085e9ec --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs @@ -0,0 +1,9 @@ +using Xunit; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +[CollectionDefinition(C_NAME, DisableParallelization = true)] +public sealed class BgfxDeviceCollection : ICollectionFixture +{ + public const string C_NAME = "BGFX device"; +} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs new file mode 100644 index 000000000..7172e57ae --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs @@ -0,0 +1,28 @@ +using System; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +public sealed class BgfxDeviceFixture : IDisposable +{ + public BgfxDeviceFixture() + { + this.device = CreateDevice(); + } + + public BgfxDevice device { get; } + + public void Dispose() => device.Dispose(); + + private static BgfxDevice CreateDevice() + => new(new BgfxDeviceOptions + { + preferredBackend = GraphicsApi.noop, + backbufferWidth = 1, + backbufferHeight = 1, + verticalSync = false, + sRgbBackbuffer = false, + forceSingleThreaded = true, + deferredDestroyFrames = 2 + }); +} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs index 77fef33a4..7515a2382 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs @@ -1,18 +1,17 @@ -using Inno.Adapter.Platform; using System; -using Inno.Rendering; -using Inno.Platform; using Xunit; +using Inno.Adapter.Platform; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; -[Collection(BgfxDeviceCollection.name)] +[Collection(BgfxDeviceCollection.C_NAME)] [Trait("ProcessIsolation", "Required")] public sealed class BgfxDeviceTests { - private static readonly RenderPhaseId C_FIRST = new("tests.first"); - private static readonly RenderPhaseId C_COMPUTE = new("tests.compute"); - private static readonly RenderPhaseId C_LAYERED = new("tests.layered"); + private static readonly RenderPhaseID FIRST = new("tests.first"); + private static readonly RenderPhaseID COMPUTE = new("tests.compute"); + private static readonly RenderPhaseID LAYERED = new("tests.layered"); private readonly BgfxDevice m_device; @@ -22,13 +21,14 @@ public BgfxDeviceTests(BgfxDeviceFixture fixture) } [Fact] - public void NoopDevice_ExecutesOneGraphAndSubmitsOneFrame() + public void NoopDeviceExecutesOneGraphAndSubmitsOneFrame() { - RenderGraphBuilder builder = new(1, m_device.capabilities); - builder.AddRasterPass("Noop Clear", C_FIRST, 0, static ( - _, - _ - ) => { }) + var builder = new RenderGraphBuilder(1, m_device.capabilities); + builder + .AddRasterPass("Noop Clear", FIRST, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -36,13 +36,13 @@ public void NoopDevice_ExecutesOneGraphAndSubmitsOneFrame() m_device.Execute(graph, 1); uint submitted = m_device.EndFrame(); - Assert.Equal(GraphicsApi.Noop, m_device.capabilities.backend); + Assert.Equal(GraphicsApi.noop, m_device.capabilities.backend); Assert.Equal(submitted, m_device.backendFrame); Assert.Single(graph.passes); } [Fact] - public void NoopDevice_ResetsPublicCommandCountersPerFrame() + public void NoopDeviceResetsPublicCommandCountersPerFrame() { m_device.BeginFrame(); Assert.Equal(default, m_device.frameCounters); @@ -53,27 +53,24 @@ public void NoopDevice_ResetsPublicCommandCountersPerFrame() } [Fact] - public void CreateWindowSurface_RejectsUnsupportedPlatformHandlesBeforeNativeCreation() + public void CreateWindowSurfaceRejectsUnsupportedPlatformHandlesBeforeNativeCreation() { m_device.BeginFrame(); Assert.Throws(() => m_device.CreateWindowSurface( - new PlatformNativeHandles(new IntPtr(1), handleKind: default(PlatformNativeHandleId)), + new PlatformNativeHandles(new nint(1), handleKind: default), 32, 32, - "Unsupported")); + "Unsupported" + )); m_device.EndFrame(); } [Fact] - public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() + public void NoopDeviceCreatesAndDefersPersistentTextureDestruction() { - RenderTextureDescriptor descriptor = new( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled); + var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Persistent Test"); @@ -90,13 +87,9 @@ public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() } [Fact] - public void NoopDevice_UploadsCompletePersistentTextureSubresource() + public void NoopDeviceUploadsCompletePersistentTextureSubresource() { - RenderTextureDescriptor descriptor = new( - 4, - 4, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled); + var descriptor = new RenderTextureDescriptor(4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Upload Test"); @@ -106,28 +99,26 @@ public void NoopDevice_UploadsCompletePersistentTextureSubresource() } [Fact] - public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() + public void NoopDeviceCreatesAndUpdatesVolumeAndCubemapSubresources() { Assert.True(m_device.capabilities.Supports(GraphicsCapability.Texture3D)); - Assert.True(m_device.capabilities.SupportsSampled( - RenderTextureFormat.RGBA8, - RenderTextureDimension.Texture3D)); - Assert.True(m_device.capabilities.SupportsSampled( - RenderTextureFormat.RGBA8, - RenderTextureDimension.Cube)); - RenderTextureDescriptor volumeDescriptor = new( + Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Texture3D)); + Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Cube)); + var volumeDescriptor = new RenderTextureDescriptor( 4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 2); - RenderTextureDescriptor cubeDescriptor = new( + depth: 2 + ); + var cubeDescriptor = new RenderTextureDescriptor( 4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, - dimension: RenderTextureDimension.Cube); + dimension: RenderTextureDimension.Cube + ); m_device.BeginFrame(); PersistentTextureHandle volume = m_device.CreateTexture(volumeDescriptor, "Volume"); @@ -140,40 +131,46 @@ public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() } [Fact] - public void NoopDevice_UpdatesDynamicVertexBuffer() + public void NoopDeviceUpdatesDynamicVertexBuffer() { - RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); - PersistentBufferDescriptor descriptor = new( + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), - layout); + layout + ); m_device.BeginFrame(); - PersistentBufferHandle buffer = m_device.CreateBuffer(descriptor, ReadOnlySpan.Empty, "Dynamic"); + PersistentBufferHandle buffer = m_device.CreateBuffer(descriptor, [], "Dynamic"); m_device.UpdateBuffer(buffer, new byte[layout.stride * 3]); m_device.DestroyBuffer(buffer); m_device.EndFrame(); } [Fact] - public void NoopDevice_CreatesVertexBufferWithExplicitPadding() + public void NoopDeviceCreatesVertexBufferWithExplicitPadding() { - RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16) - ], stride: 32); - PersistentBufferDescriptor descriptor = new( + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16) + ], + stride: 32 + ); + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); + layout + ); m_device.BeginFrame(); PersistentBufferHandle buffer = m_device.CreateBuffer( descriptor, new byte[layout.stride * 3], - "Padded Vertices"); + "Padded Vertices" + ); m_device.DestroyBuffer(buffer); m_device.EndFrame(); @@ -181,18 +178,21 @@ public void NoopDevice_CreatesVertexBufferWithExplicitPadding() } [Fact] - public void NoopDevice_CreatesVertexAndIndexBuffersAtFrameSafetyPoint() + public void NoopDeviceCreatesVertexAndIndexBuffersAtFrameSafetyPoint() { - RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); - PersistentBufferDescriptor vertices = new( + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var vertices = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); - PersistentBufferDescriptor indices = new( + layout + ); + var indices = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, sizeof(ushort), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16); + indexFormat: RenderIndexFormat.UInt16 + ); m_device.BeginFrame(); PersistentBufferHandle vertexBuffer = m_device.CreateBuffer(vertices, new byte[36], "Test Vertices"); @@ -206,16 +206,18 @@ public void NoopDevice_CreatesVertexAndIndexBuffersAtFrameSafetyPoint() } [Fact] - public void NoopDevice_AllocatesTransientStorageBufferForCompiledGraph() + public void NoopDeviceAllocatesTransientStorageBufferForCompiledGraph() { - RenderGraphBuilder builder = new(8, m_device.capabilities); + var builder = new RenderGraphBuilder(8, m_device.capabilities); RenderBufferHandle buffer = builder.CreateBuffer( "Cluster Light List", - new RenderBufferDescriptor(64, 16, RenderBufferUsage.Storage)); - builder.AddComputePass("Build Data", C_COMPUTE, 0, static ( - _, - _ - ) => { }) + new RenderBufferDescriptor(64, 16, RenderBufferUsage.Storage) + ); + builder + .AddComputePass("Build Data", COMPUTE, 0, static ( + _, + _ + ) => {}) .WriteStorageBuffer(buffer) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -228,24 +230,20 @@ public void NoopDevice_AllocatesTransientStorageBufferForCompiledGraph() } [Fact] - public void NoopDevice_AllocatesTransientStorageTextureForCompiledGraph() + public void NoopDeviceAllocatesTransientStorageTextureForCompiledGraph() { Assert.True(m_device.capabilities.Supports(GraphicsCapability.StorageTexture)); - Assert.True(m_device.capabilities.SupportsStorage( - RenderTextureFormat.RGBA8, - RenderStorageAccess.Write)); - RenderGraphBuilder builder = new(9, m_device.capabilities); + Assert.True(m_device.capabilities.SupportsStorage(RenderTextureFormat.RGBA8, RenderStorageAccess.Write)); + var builder = new RenderGraphBuilder(9, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Compute Output", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - builder.AddComputePass("Write Image", C_COMPUTE, 0, static ( - _, - _ - ) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + builder + .AddComputePass("Write Image", COMPUTE, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(texture) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -258,7 +256,7 @@ public void NoopDevice_AllocatesTransientStorageTextureForCompiledGraph() } [Fact] - public void NoopDevice_ReusesSteadyStateTransientTextureAndFramebufferAcrossGraphs() + public void NoopDeviceReusesSteadyStateTransientTextureAndFramebufferAcrossGraphs() { CompiledRenderGraph first = BuildColorTargetGraph(101); m_device.BeginFrame(); @@ -278,7 +276,7 @@ public void NoopDevice_ReusesSteadyStateTransientTextureAndFramebufferAcrossGrap } [Fact] - public void NoopDevice_AcceptsBothSynchronizationPoliciesAndKeepsResizeFrameBoundaries() + public void NoopDeviceAcceptsBothSynchronizationPoliciesAndKeepsResizeFrameBoundaries() { IRenderDevice device = m_device; uint generation = device.generation; @@ -294,14 +292,14 @@ public void NoopDevice_AcceptsBothSynchronizationPoliciesAndKeepsResizeFrameBoun } [Fact] - public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() + public void NoopDeviceRetiresSupersededNamedFramebuffersDuringResizeChurn() { - const int passCount = 16; + const int C_PASS_COUNT = 16; for (uint frame = 0; frame < 32; frame++) { - RenderGraphBuilder builder = new(1000 + frame, m_device.capabilities); + var builder = new RenderGraphBuilder(1000 + frame, m_device.capabilities); int extent = 64 + checked((int)frame); - for (int passIndex = 0; passIndex < passCount; passIndex++) + for (int passIndex = 0; passIndex < C_PASS_COUNT; passIndex++) { RenderTextureHandle texture = builder.CreateTexture( $"Resize Target {passIndex}", @@ -309,15 +307,19 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() extent, extent, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - builder.AddRasterPass( + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + builder + .AddRasterPass( $"Resize Pass {passIndex}", - C_FIRST, + FIRST, passIndex, static ( _, _ - ) => { }) + ) => {} + ) .UseColorAttachment(texture, 0, RenderLoadAction.Clear) .HasSideEffect(); } @@ -330,15 +332,17 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() } [Fact] - public void CreateBuffer_WithPartialInitialData_FailsWithoutClosingFrame() + public void CreateBufferWithPartialInitialDataFailsWithoutClosingFrame() { - RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); - PersistentBufferDescriptor descriptor = new( + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); + layout + ); m_device.BeginFrame(); Assert.Throws(() => m_device.CreateBuffer(descriptor, new byte[12], "Partial")); @@ -346,9 +350,9 @@ public void CreateBuffer_WithPartialInitialData_FailsWithoutClosingFrame() } [Fact] - public void NoopDevice_BindsRequestedTextureArrayLayer() + public void NoopDeviceBindsRequestedTextureArrayLayer() { - RenderGraphBuilder builder = new(4, m_device.capabilities); + var builder = new RenderGraphBuilder(4, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Layered Target", new RenderTextureDescriptor( @@ -356,16 +360,15 @@ public void NoopDevice_BindsRequestedTextureArrayLayer() 8, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment, - arrayLayers: 2)); - builder.AddRasterPass("Layer One", C_LAYERED, 0, static ( - _, - _ - ) => { }) - .UseColorAttachment( - texture, - 0, - RenderLoadAction.Clear, - arrayLayer: 1); + arrayLayers: 2 + ) + ); + builder + .AddRasterPass("Layer One", LAYERED, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(texture, 0, RenderLoadAction.Clear, arrayLayer: 1); builder.MarkOutput(texture); CompiledRenderGraph graph = builder.Compile().graph!; @@ -377,10 +380,7 @@ public void NoopDevice_BindsRequestedTextureArrayLayer() } [Fact] - public void EndFrame_WithoutBeginFrame_Throws() - { - Assert.Throws(() => m_device.EndFrame()); - } + public void EndFrameWithoutBeginFrameThrows() => Assert.Throws(() => m_device.EndFrame()); [Fact] public void WindowlessDeviceDoesNotAdvertiseAnInternalBackbufferAsPresentation() @@ -398,7 +398,7 @@ public void SecondDeviceIsRejectedWhileTheProcessRuntimeIsOwned() { var options = new BgfxDeviceOptions { - preferredBackend = GraphicsApi.Noop, + preferredBackend = GraphicsApi.noop, backbufferWidth = 1, backbufferHeight = 1, verticalSync = false, @@ -406,8 +406,7 @@ public void SecondDeviceIsRejectedWhileTheProcessRuntimeIsOwned() forceSingleThreaded = false }; - InvalidOperationException exception = Assert.Throws( - () => new BgfxDevice(options)); + InvalidOperationException exception = Assert.Throws(() => new BgfxDevice(options)); Assert.Contains("Only one BGFX device", exception.Message, StringComparison.Ordinal); } @@ -416,51 +415,23 @@ private CompiledRenderGraph BuildColorTargetGraph( uint generation, string passName = "Stable Color Pass" ) { - RenderGraphBuilder builder = new(generation, m_device.capabilities); + var builder = new RenderGraphBuilder(generation, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Stable Color Target", new RenderTextureDescriptor( 32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - builder.AddRasterPass(passName, C_FIRST, 0, static ( - _, - _ - ) => { }) + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + builder + .AddRasterPass(passName, FIRST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(texture, 0, RenderLoadAction.Clear); builder.MarkOutput(texture); return builder.Compile().graph!; } } - -[CollectionDefinition(name, DisableParallelization = true)] -public sealed class BgfxDeviceCollection : ICollectionFixture -{ - public const string name = "BGFX device"; -} - -public sealed class BgfxDeviceFixture : IDisposable -{ - public BgfxDeviceFixture() - { - device = CreateDevice(); - } - - public BgfxDevice device { get; } - - public void Dispose() - => device.Dispose(); - - private static BgfxDevice CreateDevice() - => new(new BgfxDeviceOptions - { - preferredBackend = GraphicsApi.Noop, - backbufferWidth = 1, - backbufferHeight = 1, - verticalSync = false, - sRgbBackbuffer = false, - forceSingleThreaded = true, - deferredDestroyFrames = 2 - }); -} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs index a187c0320..3ccfe84bf 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.Linq; -using Inno.Adapter.Rendering.Bgfx; +using Xunit; using Inno.Adapter.Presentation.ImGui; +using Inno.Adapter.Rendering.Bgfx; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -28,19 +28,21 @@ public void DefaultBackbufferAndImGuiShaderApplyExactlyOneSrgbEncoding() [Fact] public void DistributedImGuiGraphLoadsTextureAndOutputTransferBindings() { - GraphicsApi api = OperatingSystem.IsMacOS() ? GraphicsApi.Metal : GraphicsApi.Direct3D11; + GraphicsApi api = OperatingSystem.IsMacOS() ? GraphicsApi.metal : GraphicsApi.direct3D11; GraphicsPipelineDescriptor pipeline = BgfxImGuiShaderArtifacts.Load(api); Assert.False(pipeline.vertexShader.IsEmpty); Assert.False(pipeline.fragmentShader.IsEmpty); Assert.Equal(2, pipeline.bindings.Count); - RenderShaderBindingDescriptor texture = Assert.Single(pipeline.bindings.Where( - binding => binding.id.value == "s_tex")); + RenderShaderBindingDescriptor texture = Assert.Single( + pipeline.bindings.Where(binding => binding.id.value == "s_tex") + ); Assert.Equal(RenderShaderBindingKind.Texture, texture.kind); Assert.Equal(0, texture.slot); Assert.InRange(texture.nativeName.Length, 1, 63); - RenderShaderBindingDescriptor output = Assert.Single(pipeline.bindings.Where( - binding => binding.id.value == "outputEncoding")); + RenderShaderBindingDescriptor output = Assert.Single( + pipeline.bindings.Where(binding => binding.id.value == "outputEncoding") + ); Assert.Equal(RenderShaderBindingKind.Uniform, output.kind); Assert.InRange(output.nativeName.Length, 1, 63); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs index 759255972..73f9ddb61 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -12,17 +12,20 @@ public void SingleThreadedRuntimeCannotRestartWithEitherThreadingPolicy() { using (var device = new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = GraphicsApi.Noop, forceSingleThreaded = true - })) - { + preferredBackend = GraphicsApi.noop, + forceSingleThreaded = true + })) { device.BeginFrame(); device.EndFrame(); } foreach (bool inline in new[] { false, true }) + { Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = GraphicsApi.Noop, forceSingleThreaded = inline + preferredBackend = GraphicsApi.noop, + forceSingleThreaded = inline })); + } } [Fact] @@ -30,11 +33,11 @@ public void UnsupportedRendererIsRejectedBeforeTheNativeThreadingModeChanges() { Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = new GraphicsApi("fixture.unsupported"), forceSingleThreaded = true + preferredBackend = new GraphicsApi("fixture.unsupported"), + forceSingleThreaded = true })); - using var device = new BgfxDevice(new BgfxDeviceOptions { preferredBackend = GraphicsApi.Noop }); + using var device = new BgfxDevice(new BgfxDeviceOptions { preferredBackend = GraphicsApi.noop }); device.BeginFrame(); device.EndFrame(); } - } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs index 7fd6e25dc..3fb61c821 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs @@ -1,9 +1,9 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Platform; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -14,17 +14,23 @@ public sealed class BgfxShutdownTests [Fact] public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxShutdownTests) + "." + nameof(ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxShutdownTests) + "." + nameof(ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner) + )) { return; + } string? requestedBackend = Environment.GetEnvironmentVariable("INNO_TEST_GRAPHICS_API"); GraphicsApi backend = requestedBackend is null - ? OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal - : new GraphicsApi(requestedBackend); + ? OperatingSystem.IsWindows() ? GraphicsApi.direct3D11 : GraphicsApi.metal + : new GraphicsApi(requestedBackend); using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Resource retirement", width = 100, height = 90, visible = false + title = "Resource retirement", + width = 100, + height = 90, + visible = false }); var options = new BgfxDeviceOptions { @@ -36,17 +42,19 @@ public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() using (var device = new BgfxDevice(options)) { Assert.Equal(backend, device.capabilities.backend); - RenderGraphBuilder builder = new(1, device.capabilities); - RenderTextureDescriptor descriptor = new( + var builder = new RenderGraphBuilder(1, device.capabilities); + var descriptor = new RenderTextureDescriptor( 32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); RenderTextureHandle target = builder.CreateTexture("Retired target", descriptor); - builder.AddRasterPass("Offscreen clear", new RenderPhaseId("tests.shutdown"), 0, static ( - _, - _ - ) => { }) + builder + .AddRasterPass("Offscreen clear", new RenderPhaseID("tests.shutdown"), 0, static ( + _, + _ + ) => {}) .UseColorAttachment(target, 0, RenderLoadAction.Clear) .HasSideEffect(); RenderGraphCompileResult result = builder.Compile(); diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs index ea1215241..3b3b01fa9 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs @@ -1,9 +1,9 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Integration.BrowserWasm32.Bgfx.Runtime; using Inno.Integration.MacOSArm64.Bgfx.Runtime; using Inno.Integration.WindowsX64.Bgfx.Runtime; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -15,22 +15,43 @@ public void EachIntegrationValidatesItsOwnAbiAndRole() var windows = new WindowsX64BgfxSurfaceIntegration(); var macOS = new MacOSArm64BgfxSurfaceIntegration(); var browser = new BrowserWasm32BgfxSurfaceIntegration(); - Assert.Equal((nint)42, windows.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.win32), - BgfxSurfaceRole.Primary).windowHandle); + Assert.Equal( + (nint)42, + windows.Resolve( + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.win32), + BgfxSurfaceRole.Primary + ).windowHandle + ); Assert.True(windows.supportsAdditionalSurfaces); - Assert.True(macOS.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.cocoa), - BgfxSurfaceRole.Additional).supportsSrgbReset); - Assert.False(browser.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), - BgfxSurfaceRole.Primary).supportsSrgbReset); + Assert.True( + macOS.Resolve( + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.cocoa), + BgfxSurfaceRole.Additional + ).supportsSrgbReset + ); + Assert.False( + browser.Resolve( + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.browserCanvas), + BgfxSurfaceRole.Primary + ).supportsSrgbReset + ); Assert.False(browser.supportsAdditionalSurfaces); Assert.Throws(() => windows.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.cocoa), BgfxSurfaceRole.Primary)); + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.cocoa), + BgfxSurfaceRole.Primary + )); Assert.Throws(() => browser.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), BgfxSurfaceRole.Additional)); + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.browserCanvas), + BgfxSurfaceRole.Additional + )); Assert.Throws(() => windows.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.win32), (BgfxSurfaceRole)99)); + new PlatformNativeHandles((nint)42, handleKind: PlatformNativeHandleID.win32), + (BgfxSurfaceRole)99 + )); Assert.Throws(() => windows.Resolve( - new(0, handleKind: PlatformNativeHandleId.win32), BgfxSurfaceRole.Primary)); + new PlatformNativeHandles(0, handleKind: PlatformNativeHandleID.win32), + BgfxSurfaceRole.Primary + )); } [Fact] diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs index 88a460c76..18596ce1d 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs @@ -1,9 +1,10 @@ using System; +using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Platform; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -14,39 +15,51 @@ public sealed class BgfxSurfaceRetirementTests [Fact] public void MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission) + )) { return; + } VerifyRetirement(false); } [Fact] public void InlineSurfaceUsesTheSameConservativeAcknowledgment() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(InlineSurfaceUsesTheSameConservativeAcknowledgment))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(InlineSurfaceUsesTheSameConservativeAcknowledgment) + )) { return; + } VerifyRetirement(true); } [Fact] public void InvalidIntegrationFailsBeforeTakingTheProcessOwner() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(InvalidIntegrationFailsBeforeTakingTheProcessOwner))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(InvalidIntegrationFailsBeforeTakingTheProcessOwner) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Invalid integration", width = 100, height = 90, visible = false + title = "Invalid integration", + width = 100, + height = 90, + visible = false }); Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal, + preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.direct3D11 : GraphicsApi.metal, window = window, surfaceIntegration = new InvalidIntegration() })); using var device = new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal, + preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.direct3D11 : GraphicsApi.metal, window = window, surfaceIntegration = new FixtureIntegration() }); @@ -57,18 +70,24 @@ public void InvalidIntegrationFailsBeforeTakingTheProcessOwner() private static void VerifyRetirement(bool inline) { using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var primary = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow primary = application.CreateWindow(new PlatformWindowOptions { - title = "Primary surface", width = 100, height = 90, visible = false + title = "Primary surface", + width = 100, + height = 90, + visible = false }); - using var additional = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow additional = application.CreateWindow(new PlatformWindowOptions { - title = "Additional surface", width = 100, height = 90, visible = false + title = "Additional surface", + width = 100, + height = 90, + visible = false }); var integration = new FixtureIntegration(); using var device = new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal, + preferredBackend = OperatingSystem.IsWindows() ? GraphicsApi.direct3D11 : GraphicsApi.metal, window = primary, surfaceIntegration = integration, forceSingleThreaded = inline, @@ -76,11 +95,14 @@ private static void VerifyRetirement(bool inline) }); PlatformNativeHandles native = additional.nativeHandles; var handles = new PlatformNativeHandles( - native.windowHandle, native.displayHandle, new PlatformNativeHandleId("fixture.custom-surface")); + native.windowHandle, + native.displayHandle, + new PlatformNativeHandleID("fixture.custom-surface") + ); RenderSurfaceHandle surface = device.CreateWindowSurface(handles, 100, 90, "Custom surface"); device.ResizeWindowSurface(surface, 110, 95); device.ResizeWindowSurface(surface, 120, 100); - var retirement = device.RetireWindowSurface(surface); + Task retirement = device.RetireWindowSurfaceAsync(surface); Assert.False(retirement.IsCompleted); Assert.Equal(2, integration.resolveCount); Assert.Throws(() => device.ResizeWindowSurface(surface, 120, 100)); @@ -98,7 +120,7 @@ private static void VerifyRetirement(bool inline) for (int cycle = 0; cycle < 8; cycle++) { RenderSurfaceHandle final = device.CreateWindowSurface(handles, 100, 90, "Drained surface"); - var drained = device.RetireWindowSurface(final); + Task drained = device.RetireWindowSurfaceAsync(final); device.DrainWindowSurfaceRetirements(); Assert.True(drained.IsCompletedSuccessfully); Assert.False(primary.isClosed); @@ -113,6 +135,7 @@ private sealed class FixtureIntegration : IBgfxSurfaceIntegration { internal int resolveCount; public bool supportsAdditionalSurfaces => true; + public BgfxSurfaceDescriptor Resolve( PlatformNativeHandles handles, BgfxSurfaceRole role @@ -125,12 +148,10 @@ BgfxSurfaceRole role private sealed class InvalidIntegration : IBgfxSurfaceIntegration { public bool supportsAdditionalSurfaces => true; + public BgfxSurfaceDescriptor Resolve( PlatformNativeHandles handles, BgfxSurfaceRole role ) => default; } } - -[CollectionDefinition("Windowed BGFX", DisableParallelization = true)] -public sealed class WindowedBgfxCollection; diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs index 58521217d..d8a488054 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Adapter.Rendering.Bgfx.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs index eea6397f0..532230111 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs @@ -6,20 +6,27 @@ namespace Inno.Adapter.Rendering.Bgfx.Tests; internal static class NativeWindowTestHost { - private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary + private static readonly IReadOnlyDictionary CONTRACTS = new Dictionary { - ["BgfxShutdownTests.ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner"] = () => new BgfxShutdownTests().ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner(), - ["BgfxSurfaceRetirementTests.MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission"] = () => new BgfxSurfaceRetirementTests().MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission(), - ["BgfxSurfaceRetirementTests.InlineSurfaceUsesTheSameConservativeAcknowledgment"] = () => new BgfxSurfaceRetirementTests().InlineSurfaceUsesTheSameConservativeAcknowledgment(), - ["BgfxSurfaceRetirementTests.InvalidIntegrationFailsBeforeTakingTheProcessOwner"] = () => new BgfxSurfaceRetirementTests().InvalidIntegrationFailsBeforeTakingTheProcessOwner(), + ["BgfxShutdownTests.ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner"] = () => new BgfxShutdownTests() + .ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner(), + ["BgfxSurfaceRetirementTests.MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission"] = () => new BgfxSurfaceRetirementTests() + .MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission(), + ["BgfxSurfaceRetirementTests.InlineSurfaceUsesTheSameConservativeAcknowledgment"] = () => new BgfxSurfaceRetirementTests() + .InlineSurfaceUsesTheSameConservativeAcknowledgment(), + ["BgfxSurfaceRetirementTests.InvalidIntegrationFailsBeforeTakingTheProcessOwner"] = () => new BgfxSurfaceRetirementTests() + .InvalidIntegrationFailsBeforeTakingTheProcessOwner() }; - private static bool m_executingContract; + + private static bool s_executingContract; internal static bool RunIfRequired(string contract) { - if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + if (s_executingContract || !OperatingSystem.IsMacOS() + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -28,10 +35,12 @@ private static int Main(string[] arguments) { try { - if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + if (arguments.Length != 1 || !CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa must create real windows on the process main thread, including isolated renderer tests. - m_executingContract = true; + s_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); contract(); Console.Error.WriteLine($"Native contract completed: {arguments[0]}."); diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs new file mode 100644 index 000000000..9741bddf4 --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +[CollectionDefinition("Windowed BGFX", DisableParallelization = true)] +public sealed class WindowedBgfxCollection; diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs index 3ec8e81bd..b55d02b3d 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs @@ -1,31 +1,32 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; +using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; -using System.Collections.Generic; +using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Rendering.Shaders; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Rendering.Assets; using Inno.Rendering; -using Xunit; +using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; using Inno.Testing.Bgfx; + using static Inno.Testing.Bgfx.ShaderProfileFixture; namespace Inno.Build.Toolchains.Bgfx.Integration.Tests; public sealed class BgfxToolchainTests : IDisposable { - private static readonly byte[] C_KTX_IDENTIFIER = + private static readonly byte[] KTX_IDENTIFIER = [ 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A @@ -34,17 +35,23 @@ public sealed class BgfxToolchainTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoBgfxToolchainTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); - public BgfxToolchainTests() => Directory.CreateDirectory(m_root); + public BgfxToolchainTests() + { + Directory.CreateDirectory(m_root); + } [Fact] [SupportedOSPlatform("windows")] public async Task BrowserProfileCompilesTheCommonGraphOnWindows() { if (!OperatingSystem.IsWindows()) + { return; - using var modules = new ModuleHost(new() + } + using var modules = new ModuleHost(new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderNodeCompilerRegistry).Assembly) }); @@ -52,20 +59,31 @@ public async Task BrowserProfileCompilesTheCommonGraphOnWindows() using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); using var nodes = new ShaderNodeCompilerRegistry(types); GraphDocument graph = ShaderGraphTemplates.CreateRaster(serialization, SerializationContext.empty); - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower(graph, "bgfx", - new Dictionary(), serialization, SerializationContext.empty); + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower( + graph, + "bgfx", + new Dictionary(), + serialization, + SerializationContext.empty + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(ShaderProfileFixture.browser)); ShaderCompilationResult result = await compiler.CompileAsync( ShaderGraphDocument.ReadDefinition(graph, serialization, SerializationContext.empty), program, - compiler.CreateTarget(CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None)), + compiler.CreateTarget(CreateCapabilities(GraphicsApi.openGLES, GraphicsCapability.None)), RenderShaderVariant.empty, - serialization, SerializationContext.empty); + serialization, + SerializationContext.empty + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Single(result.artifact!.passes); } @@ -74,8 +92,10 @@ public async Task BrowserProfileCompilesTheCommonGraphOnWindows() public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() { if (!OperatingSystem.IsWindows()) + { return; - using var modules = new ModuleHost(new() + } + using var modules = new ModuleHost(new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderNodeCompilerRegistry).Assembly) }); @@ -83,20 +103,31 @@ public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); using var nodes = new ShaderNodeCompilerRegistry(types); GraphDocument graph = ShaderGraphTemplates.CreateRaster(serialization, SerializationContext.empty); - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower(graph, "bgfx", - new Dictionary(), serialization, SerializationContext.empty); + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower( + graph, + "bgfx", + new Dictionary(), + serialization, + SerializationContext.empty + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(ShaderProfileFixture.windows)); ShaderCompilationResult result = await compiler.CompileAsync( ShaderGraphDocument.ReadDefinition(graph, serialization, SerializationContext.empty), program, - compiler.CreateTarget(CreateCapabilities(GraphicsApi.Direct3D11, GraphicsCapability.None)), + compiler.CreateTarget(CreateCapabilities(GraphicsApi.direct3D11, GraphicsCapability.None)), RenderShaderVariant.empty, - serialization, SerializationContext.empty); + serialization, + SerializationContext.empty + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Single(result.artifact!.passes); } @@ -108,40 +139,50 @@ public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings(bool browser) { if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { return; - GraphicsApi backend = browser ? GraphicsApi.OpenGLES : GraphicsApi.OpenGL; + } + GraphicsApi backend = browser ? GraphicsApi.openGLES : GraphicsApi.openGL; var builder = new ShaderIrBuilder(); ShaderSourceType colorType = ShaderSourceType.Atomic("float4"); ShaderIrValue color = builder.Input("used-tint", colorType); _ = builder.Input("unused-tint", colorType); ShaderSourceType textureType = ShaderSourceType.Atomic("sampled-texture2d"); ShaderIrValue texture = builder.Input("sampled", textureType); - ShaderIrValue coordinate = builder.Construct(ShaderSourceType.Atomic("float2"), - [builder.Constant(0.5f), builder.Constant(0.5f)]); + ShaderIrValue coordinate = builder.Construct( + ShaderSourceType.Atomic("float2"), + [builder.Constant(0.5f), builder.Constant(0.5f)] + ); ShaderIrValue output = builder.Binary(ShaderIrOperation.Multiply, color, builder.Sample(texture, coordinate)); var stage = new ShaderIrStage( ShaderStage.Fragment, builder.Build(new Dictionary { ["color"] = output }), [ - new("used-tint", colorType, ShaderIrInputKind.Uniform), - new("unused-tint", colorType, ShaderIrInputKind.Uniform), - new("sampled", textureType, ShaderIrInputKind.SampledTexture) + new ShaderIrStageInput("used-tint", colorType, ShaderIrInputKind.Uniform), + new ShaderIrStageInput("unused-tint", colorType, ShaderIrInputKind.Uniform), + new ShaderIrStageInput("sampled", textureType, ShaderIrInputKind.SampledTexture) ], - [new("color", ShaderIrOutputKind.Color)]); - BgfxShaderTargetProfile platform = backend == GraphicsApi.OpenGLES - ? ShaderProfileFixture.browser - : OperatingSystem.IsWindows() - ? ShaderProfileFixture.windows - : ShaderProfileFixture.mac; + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ); + BgfxShaderTargetProfile platform = backend == GraphicsApi.openGLES + ? ShaderProfileFixture.browser + : OperatingSystem.IsWindows() + ? ShaderProfileFixture.windows + : ShaderProfileFixture.mac; var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform)); ShaderStageToolResult result = await compiler.CompileAsync( stage, - compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None))); + compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None)) + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Equal(new[] { "sampled", "used-tint" }, result.bindings.Select(static binding => binding.id).Order().ToArray()); Dictionary uniforms = ReadBinaryUniformTypes(result.bytes.Span); Assert.Equal(2, uniforms.Count); @@ -150,18 +191,16 @@ public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings } [Fact] - public async System.Threading.Tasks.Task TextureCompilerProducesValidatedPortableContainer() + public async Task TextureCompilerProducesValidatedPortableContainer() { string sourcePath = Path.Combine(m_root, "checker.tga"); File.WriteAllBytes(sourcePath, CreateTga()); using FileStream source = File.OpenRead(sourcePath); - byte[] artifact = await new BgfxTextureTargetCompiler().CompileKtxAsync( - source, - TextureColorSpace.Srgb); + byte[] artifact = await new BgfxTextureTargetCompiler().CompileKtxAsync(source, TextureColorSpace.Srgb); - Assert.True(artifact.Length > C_KTX_IDENTIFIER.Length); - Assert.Equal(C_KTX_IDENTIFIER, artifact[..C_KTX_IDENTIFIER.Length]); + Assert.True(artifact.Length > KTX_IDENTIFIER.Length); + Assert.Equal(KTX_IDENTIFIER, artifact[..KTX_IDENTIFIER.Length]); } /// @@ -181,25 +220,41 @@ public async System.Threading.Tasks.Task TextureCompilerProducesValidatedPortabl public async Task GlslFragmentOutputsPreserveSparseAttachmentLocations(bool browser) { if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { return; - GraphicsApi backend = browser ? GraphicsApi.OpenGLES : GraphicsApi.OpenGL; - BgfxShaderTargetProfile platform = browser ? ShaderProfileFixture.browser - : OperatingSystem.IsWindows() ? ShaderProfileFixture.windows : ShaderProfileFixture.mac; + } + GraphicsApi backend = browser ? GraphicsApi.openGLES : GraphicsApi.openGL; + BgfxShaderTargetProfile platform = browser + ? ShaderProfileFixture.browser + : OperatingSystem.IsWindows() ? ShaderProfileFixture.windows : ShaderProfileFixture.mac; var builder = new ShaderIrBuilder(); - ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), - [builder.Constant(0.25f), builder.Constant(0.5f), builder.Constant(0.75f), builder.Constant(1f)]); + ShaderIrValue color = builder.Construct( + ShaderSourceType.Atomic("float4"), + [builder.Constant(0.25f), builder.Constant(0.5f), builder.Constant(0.75f), builder.Constant(1f)] + ); var stage = new ShaderIrStage( ShaderStage.Fragment, builder.Build(new Dictionary { ["first"] = color, ["third"] = color }), [], - [new("first", ShaderIrOutputKind.Color, location: 0), new("third", ShaderIrOutputKind.Color, location: 2)]); + [ + new ShaderIrStageOutput("first", ShaderIrOutputKind.Color, location: 0), + new ShaderIrStageOutput("third", ShaderIrOutputKind.Color, location: 2) + ] + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform)); - ShaderStageToolResult result = await compiler.CompileAsync(stage, - compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None))); + ShaderStageToolResult result = await compiler.CompileAsync( + stage, + compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None)) + ); - Assert.True(result.succeeded, string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); string glsl = Encoding.UTF8.GetString(result.bytes.Span); if (browser) { @@ -217,7 +272,9 @@ public async Task GlslFragmentOutputsPreserveSparseAttachmentLocations(bool brow public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static Dictionary ReadBinaryUniformTypes(ReadOnlySpan binary) @@ -238,7 +295,7 @@ private static Dictionary ReadBinaryUniformTypes(ReadOnlySpan()) + foreach (BgfxTool tool in Enum.GetValues()) { - var toolName = tool.ToString().ToLowerInvariant(); + string toolName = tool.ToString().ToLowerInvariant(); ToolRunResult result = new ToolRunner().Run(tool, ["--help"]); Assert.InRange(result.exitCode, 0, 1); Assert.False(string.IsNullOrWhiteSpace(result.standardOutput + result.standardError)); diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs index faf2c8c61..5d443c0ad 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs @@ -26,7 +26,7 @@ public BgfxNativeProfileTests() public async Task OpenTargetAcceptsItsExplicitSdkInvocationBeforeSourceValidation() { var profile = new FixtureProfile("fixture-new-target"); - NativeBuildContext context = CreateContext(profile.targetId); + NativeBuildContext context = CreateContext(profile.targetID); await Assert.ThrowsAsync(() => BgfxNativeBuild.BuildAsync(context, profile, CancellationToken.None)); @@ -63,14 +63,17 @@ public void InvocationOwnsAnImmutableArgumentSnapshot() public void SourceDeclarationFreezesRuntimeAndToolOptionsBeforeBindingExists(bool tools) { var profile = new FixtureProfile("fixture-new-target"); - NativeBuildContext context = CreateContext(profile.targetId); + NativeBuildContext context = CreateContext(profile.targetID); foreach (string source in new[] { "bgfx", "bx", "bimg" }) + { Directory.CreateDirectory(Path.Combine(m_root, "extern", source)); + } string project = Path.Combine(m_root, BgfxNativeBuild.componentDescriptor.toolchainProject); Directory.CreateDirectory(Path.GetDirectoryName(project)!); File.WriteAllText(project, ""); - NativeBuildRecipe recipe = tools ? BgfxToolsBuild.CreateRecipe(context, profile) - : BgfxNativeBuild.CreateRecipe(context, profile); + NativeBuildRecipe recipe = tools + ? BgfxToolsBuild.CreateRecipe(context, profile) + : BgfxNativeBuild.CreateRecipe(context, profile); Assert.Equal(tools ? "bgfx-tools" : "bgfx", recipe.component); Assert.Equal(tools ? null : BgfxNativeBuild.componentDescriptor.bindingDefinition, recipe.owner.bindingDefinition); Assert.Equal(1, profile.invocationCount); @@ -89,7 +92,10 @@ public async Task OfflineToolsDoNotRequestRuntimeBindings() Assert.Equal(BgfxNativeBuild.componentDescriptor.toolchainProject, tools.toolchainProject); Assert.Null(tools.bindingDefinition); using NativeBindingGenerationResult generations = await NativeBindingPreparation.PrepareAsync( - CreateContext("fixture-new-target"), [tools], CancellationToken.None); + CreateContext("fixture-new-target"), + [tools], + CancellationToken.None + ); Assert.Empty(generations); } @@ -97,24 +103,36 @@ private NativeBuildContext CreateContext(string target) { string compiler = Path.Combine(m_root, "fixture-compiler"); File.WriteAllText(compiler, "Not executable: this fixture stops before source preparation."); - var selection = new NativeToolchainSelection(target, new BuildHostDescriptor("FixtureHost", "fixture-cpu"), - new Dictionary { ["compiler"] = compiler, ["genie"] = compiler }, new Dictionary(), [], [], new NativeLinkPlan(".fixture"), false); - return new NativeBuildContext(m_root, "debug").WithToolchain(selection).WithComponentOptions(BgfxNativeBuild.componentDescriptor, new(NativeLibraryKind.Shared)); + var selection = new NativeToolchainSelection( + target, + new BuildHostDescriptor("FixtureHost", "fixture-cpu"), + new Dictionary { ["compiler"] = compiler, ["genie"] = compiler }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".fixture"), + false + ); + return new NativeBuildContext(m_root, "debug") + .WithToolchain(selection) + .WithComponentOptions(BgfxNativeBuild.componentDescriptor, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); } private sealed class FixtureProfile(string target) : BgfxNativeBuildProfile { + public int invocationCount { get; private set; } + public override string targetID => target; + public override IReadOnlyList generatorArguments => ["fixture-generator"]; + public override string artifactPathToken => "/fixture-cpu/bin/"; + public override IReadOnlyList bindingCmakeArguments => []; + public override NativeToolchainSelection SelectTools( NativeBuildContext context, bool includeTools ) => context.RequireToolchain(); - public int invocationCount { get; private set; } - public override string targetId => target; - public override IReadOnlyList generatorArguments => ["fixture-generator"]; - public override string artifactPathToken => "/fixture-cpu/bin/"; - public override IReadOnlyList bindingCmakeArguments => []; - public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) => (archivePath, []); + public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) + => (archivePath, []); public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs index de43c3d04..e493b3040 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs @@ -1,7 +1,8 @@ using System; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Xunit; +using Inno.Rendering.Assets.Authoring; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -15,44 +16,78 @@ public void NewTargetAndRendererUseThePublicConfigurationBoundary() var profile = new BgfxShaderCompilerProfile(capabilities, "fixture-sdk", "vertex", "fragment", "compute"); var configuration = new BgfxShaderTargetProfile("fixture-console", [profile]); - var target = new BgfxShadercToolchain(configuration).CreateTarget(capabilities); + ShaderCompileTarget target = new BgfxShadercToolchain(configuration).CreateTarget(capabilities); Assert.Same(profile, configuration.Resolve(api)); Assert.Contains("fixture-console", target.profileKey, StringComparison.Ordinal); - Assert.Throws(() => configuration.Resolve(GraphicsApi.Metal)); + Assert.Throws(() => configuration.Resolve(GraphicsApi.metal)); } [Fact] public void DialectDefinesAndCapabilitiesAllParticipateInIdentity() { - GraphicsCapabilities capabilities = BgfxTargetCapabilities.Create(GraphicsApi.Vulkan); + GraphicsCapabilities capabilities = BgfxTargetCapabilities.Create(GraphicsApi.vulkan); string[] defines = ["TEST=1"]; var original = new BgfxShaderCompilerProfile(capabilities, "fixture-sdk", "spirv", "spirv", "spirv", defines); defines[0] = "TEST=2"; Assert.Equal("TEST=1", original.defines[0]); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "fixture-sdk", "spirv", "spirv", "spirv", defines).key); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "other-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "fixture-sdk", "other-dialect", "spirv", "spirv", ["TEST=1"]).key); - var reduced = new GraphicsCapabilities(GraphicsApi.Vulkan, capabilities.features, - new GraphicsLimits(16, 4, 1024, 8), [], [], [], [], false, false); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(reduced, - "fixture-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(capabilities, "fixture-sdk", "spirv", "spirv", "spirv", defines).key + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(capabilities, "other-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile( + capabilities, + "fixture-sdk", + "other-dialect", + "spirv", + "spirv", + ["TEST=1"] + ).key + ); + var reduced = new GraphicsCapabilities( + GraphicsApi.vulkan, + capabilities.features, + new GraphicsLimits(16, 4, 1024, 8), + [], + [], + [], + [], + false, + false + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(reduced, "fixture-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key + ); } [Fact] public void InvalidAndDuplicateProfilesFailBeforeCreatingACompiler() { - var profile = new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.Metal), - "osx", "metal", "metal", "metal"); + var profile = new BgfxShaderCompilerProfile( + BgfxTargetCapabilities.Create(GraphicsApi.metal), + "osx", + "metal", + "metal", + "metal" + ); Assert.Throws(() => new BgfxShaderTargetProfile("fixture", [])); Assert.Throws(() => new BgfxShaderTargetProfile("fixture", [profile, profile])); - Assert.Throws(() => new BgfxShaderCompilerProfile(profile.capabilities, - "osx", "metal", "metal", "")); + Assert.Throws(() => new BgfxShaderCompilerProfile( + profile.capabilities, + "osx", + "metal", + "metal", + string.Empty + )); Assert.Throws(() => new BgfxShadercToolchain(null!)); } } diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs index 46c41dc90..5399c1dd0 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs @@ -1,10 +1,11 @@ using System; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; -using Xunit; using Inno.Testing.Bgfx; + using static Inno.Testing.Bgfx.ShaderProfileFixture; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -14,9 +15,7 @@ public sealed class BgfxShaderTargetTests [Fact] public void MetalProfileIsOwnedByMacBgfxToolchain() { - GraphicsCapabilities capabilities = CreateCapabilities( - GraphicsApi.Metal, - GraphicsCapability.Compute); + GraphicsCapabilities capabilities = CreateCapabilities(GraphicsApi.metal, GraphicsCapability.Compute); var toolchain = new BgfxShadercToolchain(ShaderProfileFixture.mac); ShaderCompileTarget target = toolchain.CreateTarget(capabilities); @@ -30,12 +29,12 @@ public void MetalProfileIsOwnedByMacBgfxToolchain() public void Direct3DAndMetalTargetsSelectProfilesWithoutForkingShaderSource() { ShaderCompileTarget metal = new BgfxShadercToolchain(ShaderProfileFixture.mac) - .CreateTarget(CreateCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute)); + .CreateTarget(CreateCapabilities(GraphicsApi.metal, GraphicsCapability.Compute)); ShaderCompileTarget direct3D = new BgfxShadercToolchain(ShaderProfileFixture.windows) - .CreateTarget(CreateCapabilities(GraphicsApi.Direct3D11, GraphicsCapability.Compute)); + .CreateTarget(CreateCapabilities(GraphicsApi.direct3D11, GraphicsCapability.Compute)); - Assert.Equal(GraphicsApi.Metal, metal.capabilities.backend); - Assert.Equal(GraphicsApi.Direct3D11, direct3D.capabilities.backend); + Assert.Equal(GraphicsApi.metal, metal.capabilities.backend); + Assert.Equal(GraphicsApi.direct3D11, direct3D.capabilities.backend); Assert.NotEqual(metal.profileKey, direct3D.profileKey); } @@ -45,12 +44,15 @@ public void BrowserProfileRequiresWebGlWithoutCompute() var toolchain = new BgfxShadercToolchain(ShaderProfileFixture.browser); ShaderCompileTarget target = toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None)); + CreateCapabilities(GraphicsApi.openGLES, GraphicsCapability.None) + ); Assert.Contains("bgfx-shaderc:fixture-browser:", target.profileKey, StringComparison.Ordinal); Assert.Throws(() => toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.Compute))); + CreateCapabilities(GraphicsApi.openGLES, GraphicsCapability.Compute) + )); Assert.Throws(() => toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGL, GraphicsCapability.None))); + CreateCapabilities(GraphicsApi.openGL, GraphicsCapability.None) + )); } } diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs index e39933d00..84056910f 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs @@ -1,8 +1,6 @@ using System; using System.IO; - using Xunit; - using Inno.Build.Toolchains.Bgfx.Tools; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -10,8 +8,5 @@ namespace Inno.Build.Toolchains.Bgfx.Tests; public sealed class ToolRunnerTests { [Fact] - public void Run_Throws_WhenToolMissing() - { - Assert.Throws(() => new ToolRunner().Run((BgfxTool)999, ["--help"])); - } + public void RunThrowsWhenToolMissing() => Assert.Throws(() => new ToolRunner().Run((BgfxTool)999, ["--help"])); } diff --git a/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs b/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs index f79256c12..2993a5975 100644 --- a/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs +++ b/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs @@ -6,7 +6,7 @@ namespace Inno.Native.Bgfx.Tests; public sealed class BgfxInitTests { [Fact] - public unsafe void InitAndShutdown_ShouldSucceed() + public unsafe void InitAndShutdownShouldSucceed() { bgfx.Init init; bgfx.Raw.init_ctor(&init); @@ -18,7 +18,7 @@ public unsafe void InitAndShutdown_ShouldSucceed() Assert.True(ok); try { - Assert.True(bgfx.Raw.get_caps() != null); + Assert.True(bgfx.Raw.get_caps() is not null); Assert.Equal(bgfx.RendererType.Noop, bgfx.get_renderer_type()); } finally diff --git a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs index 6458e83b7..cb72a6b93 100644 --- a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs +++ b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs @@ -4,41 +4,91 @@ namespace Inno.Testing.Bgfx; -/// Defines explicit shader target fixtures shared by metadata and real compiler tests. +/// +/// Defines explicit shader target fixtures shared by metadata and real compiler tests. +/// public static class ShaderProfileFixture { - /// Gets the explicit windows shader profile used by the tests. - public static BgfxShaderTargetProfile windows { get; } = new("fixture-windows", - [new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "windows", "430", "430", "430"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv")]); - /// Gets the explicit mac shader profile used by the tests. - public static BgfxShaderTargetProfile mac { get; } = new("fixture-mac", - [new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "osx", "430", "430", "430"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"])]); - /// Gets the explicit browser shader profile used by the tests. - public static BgfxShaderTargetProfile browser { get; } = new("fixture-browser", - [new(new GraphicsCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None, - new GraphicsLimits(256, 4, 2048, 0), [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - [], [], true, true), "asm.js", "300_es", "300_es", "")]); + /// + /// Gets the explicit windows shader profile used by the tests. + /// + public static BgfxShaderTargetProfile windows { get; } = new( + "fixture-windows", + [ + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.openGL), "windows", "430", "430", "430"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.vulkan), "windows", "spirv", "spirv", "spirv") + ] + ); - /// Creates the declared rendering capabilities without loading a native runtime. - /// The explicit graphics API. - /// The capabilities required by the test. - /// The immutable capability description. + /// + /// Gets the explicit mac shader profile used by the tests. + /// + public static BgfxShaderTargetProfile mac { get; } = new( + "fixture-mac", + [ + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.metal), "osx", "metal", "metal", "metal"), + new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.openGL), "osx", "430", "430", "430"), + new BgfxShaderCompilerProfile( + BgfxTargetCapabilities.Create(GraphicsApi.vulkan), + "osx", + "spirv", + "spirv", + "spirv", + ["BGFX_SHADER_LANGUAGE_SPIRV=1"] + ) + ] + ); + + /// + /// Gets the explicit browser shader profile used by the tests. + /// + public static BgfxShaderTargetProfile browser { get; } = new( + "fixture-browser", + [new BgfxShaderCompilerProfile( + new GraphicsCapabilities( + GraphicsApi.openGLES, + GraphicsCapability.None, + new GraphicsLimits(256, 4, 2048, 0), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [], + [], + true, + true + ), + "asm.js", + "300_es", + "300_es", + string.Empty + )] + ); + + /// + /// Creates the declared rendering capabilities without loading a native runtime. + /// + /// + /// The explicit graphics API. + /// + /// + /// The capabilities required by the test. + /// + /// + /// The immutable capability description. + /// public static GraphicsCapabilities CreateCapabilities( GraphicsApi backend, GraphicsCapability features ) => new( - backend, - features, - new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), - Enum.GetValues(), - Enum.GetValues(), - Enum.GetValues(), - originBottomLeft: false, - homogeneousDepth: false); + backend, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + originBottomLeft: false, + homogeneousDepth: false + ); } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs index 1d9d4b9ec..c2f34583a 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs @@ -11,16 +11,19 @@ public sealed class ContentCacheCancellationTests [Fact] public async Task CancellationDuringCopyDiscardsCandidateAndPreservesThePreviousPointer() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using (FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options)) { } string previous = fixture.current; File.Delete(Path.Combine(previous, "AssetDatabase", "Catalog.snapshot")); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); fixture.source.onRead = cancellation.Cancel; await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( - fixture.source, fixture.options, cancellation.Token).AsTask()); + fixture.source, + fixture.options, + cancellation.Token + ).AsTask()); Assert.Equal(previous, fixture.current); Assert.Empty(Directory.GetDirectories(Path.Combine(fixture.cache, "staging"))); fixture.source.onRead = null; @@ -31,9 +34,12 @@ await Assert.ThrowsAnyAsync(() => FileContentPrepara [Fact] public async Task PriorCancellationCreatesNoCacheDirectory() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( - fixture.source, fixture.options, new CancellationToken(true)).AsTask()); + fixture.source, + fixture.options, + new CancellationToken(true) + ).AsTask()); Assert.False(Directory.Exists(fixture.root)); } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs index c10298354..bbbbd216f 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs @@ -10,9 +10,11 @@ public sealed class ContentCacheConcurrencyTests [Fact] public async Task ConcurrentPreparationPublishesOneCompleteGeneration() { - using ContentCacheFixture fixture = new(); - FileContentStore[] readers = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => - FileContentPreparation.PrepareAsync(fixture.source, fixture.options).AsTask())); + using var fixture = new ContentCacheFixture(); + FileContentStore[] readers = await Task.WhenAll( + Enumerable.Range(0, 8).Select(_ => + FileContentPreparation.PrepareAsync(fixture.source, fixture.options).AsTask()) + ); try { Assert.Single(Directory.GetDirectories(Path.Combine(fixture.cache, "generations"))); @@ -22,7 +24,9 @@ public async Task ConcurrentPreparationPublishesOneCompleteGeneration() finally { foreach (FileContentStore reader in readers) + { reader.Dispose(); + } } } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs index 40e4e0b28..10d0894a0 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs @@ -11,23 +11,26 @@ namespace Inno.Adapter.Content.FileSystem.Tests; internal sealed class ContentCacheFixture : IDisposable { internal readonly string root = Path.Combine(Path.GetTempPath(), "inno-content-cache-" + Guid.NewGuid().ToString("N")); + internal readonly MemoryContentStore source = new(new Dictionary { ["AssetDatabase/Catalog.snapshot"] = [1, 2, 3], ["Artifacts/aa/bb/data"] = [4, 5, 6] }); - internal string cache => Path.Combine(root, "Content", source.descriptor.contentHash); - internal string current => Path.Combine(cache, "generations", File.ReadAllText(Path.Combine(cache, "current"))); - internal FileContentCacheOptions options => new(root); - public void Dispose() { source.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, true); + } } + internal string cache => Path.Combine(root, "Content", source.descriptor.contentHash); + internal string current => Path.Combine(cache, "generations", File.ReadAllText(Path.Combine(cache, "current"))); + internal FileContentCacheOptions options => new(root); + internal sealed class MemoryContentStore : IRuntimeContentStore { private readonly Dictionary m_content; @@ -37,27 +40,41 @@ internal sealed class MemoryContentStore : IRuntimeContentStore internal MemoryContentStore(Dictionary content) { m_content = content.ToDictionary(static pair => new ContentKey(pair.Key), static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex(m_content.Select(static pair => new ContentEntry(pair.Key, pair.Value.Length, - Convert.ToHexString(SHA256.HashData(pair.Value))))); - string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join(";", - index.entries.Select(static entry => entry.key.value + entry.contentHash))))); - descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); + this.index = new ContentPackIndex( + m_content.Select(static pair => new ContentEntry( + pair.Key, + pair.Value.Length, + Convert.ToHexString(SHA256.HashData(pair.Value)) + )) + ); + string hash = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + string.Join(";", index.entries.Select(static entry => entry.key.value + entry.contentHash)) + ) + ) + ); + this.descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } public ContentPackDescriptor descriptor { get; } public ContentPackIndex index { get; } + public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_closed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException(); + } byte[] bytes = m_content[key]; return new ContentReadLease(entry!, () => { onRead?.Invoke(); return new MemoryStream(bytes, false); - }, static () => { }); + }, static () => {}); } + public void Dispose() => m_closed = true; } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs index d61bd24a0..9d9979c85 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs @@ -1,7 +1,9 @@ +using System; using System.IO; using System.Threading.Tasks; -using Inno.Content; using Xunit; +using Xunit.Sdk; +using Inno.Content; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -16,7 +18,7 @@ public sealed class ContentCacheIntegrityTests [InlineData("missing-lease")] public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fault) { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using (FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options)) { } @@ -34,7 +36,7 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau Directory.CreateDirectory(Path.Combine(original, "unindexed")); break; case "same-length-and-time": - var time = File.GetLastWriteTimeUtc(file); + DateTime time = File.GetLastWriteTimeUtc(file); File.WriteAllBytes(file, [3, 2, 1]); File.SetLastWriteTimeUtc(file, time); break; @@ -49,7 +51,7 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau Assert.NotEqual(original, fixture.current); using ContentReadLease lease = repaired.Acquire(new ContentKey("AssetDatabase/Catalog.snapshot")); using Stream input = lease.OpenRead(); - byte[] bytes = new byte[3]; + var bytes = new byte[3]; input.ReadExactly(bytes); Assert.Equal(new byte[] { 1, 2, 3 }, bytes); Assert.Equal(-1, input.ReadByte()); @@ -68,15 +70,17 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau [Fact] public async Task ContentChangedAfterPreparationFailsReadingAndReleasesTheFailedStreamPin() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using FileContentStore store = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string original = fixture.current; string file = Path.Combine(original, "AssetDatabase", "Catalog.snapshot"); - var time = File.GetLastWriteTimeUtc(file); + DateTime time = File.GetLastWriteTimeUtc(file); File.WriteAllBytes(file, [3, 2, 1]); File.SetLastWriteTimeUtc(file, time); using (ContentReadLease lease = store.Acquire(new ContentKey("AssetDatabase/Catalog.snapshot"))) + { Assert.Throws(() => lease.OpenRead()); + } store.Dispose(); using FileContentStore repaired = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.False(Directory.Exists(original)); @@ -86,10 +90,10 @@ public async Task ContentChangedAfterPreparationFailsReadingAndReleasesTheFailed [Fact] public async Task ValidCacheReusePreservesGenerationAndDoesNotReadSourcePayloads() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string generation = fixture.current; - fixture.source.onRead = () => throw new Xunit.Sdk.XunitException("A verified cache must not recopy payloads."); + fixture.source.onRead = () => throw new XunitException("A verified cache must not recopy payloads."); using FileContentStore second = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.Equal(generation, fixture.current); } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs index 0d5281383..1ef52252c 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs @@ -2,8 +2,8 @@ using System.Diagnostics; using System.IO; using System.Threading.Tasks; -using Inno.Content.Testing; using Xunit; +using Inno.Content.Testing; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -34,21 +34,25 @@ public async Task IndependentProcessesPublishOneGenerationAndPinItUntilBothReade Assert.Single(Directory.GetDirectories(Path.Combine(cache, "generations"))); File.WriteAllBytes(Path.Combine(oldDirectory, "repair.bin"), [6, 5, 4]); - using (FileContentStore repaired = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot))) - { + using (FileContentStore repaired = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + )) { Assert.NotEqual(generation, File.ReadAllText(Path.Combine(cache, "current"))); Assert.True(Directory.Exists(oldDirectory)); } await first.ReleaseAsync(); - using (FileContentStore next = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot))) - { + using (FileContentStore next = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + )) { Assert.True(Directory.Exists(oldDirectory)); } await second.ReleaseAsync(); - using FileContentStore final = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot)); + using FileContentStore final = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + ); Assert.False(Directory.Exists(oldDirectory)); Assert.Single(Directory.GetDirectories(Path.Combine(cache, "generations"))); } @@ -79,12 +83,23 @@ string cacheRoot private sealed class Probe(Process process) : IAsyncDisposable { - internal Process process { get; } = process; private readonly Task m_error = process.StandardError.ReadToEndAsync(); + public async ValueTask DisposeAsync() + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(); + } + process.Dispose(); + } + + internal Process process { get; } = process; + internal async Task ReadLineAsync() => await process.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)) - ?? throw new InvalidOperationException("The cache probe exited before reporting its state."); + ?? throw new InvalidOperationException("The cache probe exited before reporting its state."); internal async Task ReleaseAsync() { @@ -93,15 +108,5 @@ internal async Task ReleaseAsync() await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); Assert.True(process.ExitCode == 0, await m_error); } - - public async ValueTask DisposeAsync() - { - if (!process.HasExited) - { - process.Kill(entireProcessTree: true); - await process.WaitForExitAsync(); - } - process.Dispose(); - } } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs index 5d1059da7..c604a049f 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs @@ -2,9 +2,9 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Content; using Inno.Core.IO; -using Xunit; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -33,10 +33,14 @@ await Assert.ThrowsAsync(() => public async Task AWriterLeaseEnforcesBoundedWaitingAndCancellationWithoutChangingContent() { using var fixture = new ContentCacheFixture(); - using FileLease writer = await FileLease.AcquireAsync(Path.Combine(fixture.cache, "install.lock"), - TimeSpan.Zero); - await Assert.ThrowsAsync(() => FileContentPreparation.PrepareAsync(fixture.source, - new FileContentCacheOptions(fixture.root, TimeSpan.FromMilliseconds(40))).AsTask()); + using FileLease writer = await FileLease.AcquireAsync( + Path.Combine(fixture.cache, "install.lock"), + TimeSpan.Zero + ); + await Assert.ThrowsAsync(() => FileContentPreparation.PrepareAsync( + fixture.source, + new FileContentCacheOptions(fixture.root, TimeSpan.FromMilliseconds(40)) + ).AsTask()); using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(40)); await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync(fixture.source, fixture.options, cancellation.Token).AsTask()); diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs index 800789d02..0dda41fba 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs @@ -1,7 +1,7 @@ using System.IO; using System.Threading.Tasks; -using Inno.Content; using Xunit; +using Inno.Content; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -10,7 +10,7 @@ public sealed class ContentCacheRetirementTests [Fact] public async Task RepairKeepsAnOldReaderGenerationUntilItsLastStreamCloses() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); FileContentStore old = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string oldDirectory = fixture.current; ContentReadLease lease = old.Acquire(new ContentKey("Artifacts/aa/bb/data")); @@ -21,7 +21,7 @@ public async Task RepairKeepsAnOldReaderGenerationUntilItsLastStreamCloses() using FileContentStore replacement = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.NotEqual(oldDirectory, fixture.current); Assert.True(Directory.Exists(oldDirectory)); - byte[] bytes = new byte[3]; + var bytes = new byte[3]; input.ReadExactly(bytes); Assert.Equal(new byte[] { 4, 5, 6 }, bytes); input.Dispose(); diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs index ec1eb0fb3..4655070f9 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs @@ -13,7 +13,7 @@ public void GeneratedVectorStoragePreservesNativeOffsetsAndBorrowedData() Assert.Equal(2 * sizeof(int), Marshal.OffsetOf(nameof(ImVectorInt.Data)).ToInt32()); int* values = stackalloc int[3] { 11, 23, 37 }; - ImVectorInt vector = new() { Size = 2, Capacity = 3, Data = values }; + var vector = new ImVectorInt() { Size = 2, Capacity = 3, Data = values }; Assert.Equal(2, vector.Size); Assert.Equal(3, vector.Capacity); Assert.Equal(11, vector.Data[0]); diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs index d7affd1ff..b5eac99eb 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs @@ -1,5 +1,5 @@ -using System.Numerics; using System; +using System.Numerics; using System.Runtime.InteropServices; using Xunit; using Xunit.Abstractions; @@ -9,30 +9,30 @@ namespace Inno.Native.ImGui.Tests; [Collection("ImGuiContext")] public sealed unsafe class ImGuiInitTests { - private readonly ITestOutputHelper output; + private readonly ITestOutputHelper m_output; public ImGuiInitTests(ITestOutputHelper output) { - this.output = output; + m_output = output; } [Fact] - public void CreateAndDestroyContext_ShouldSucceed() + public void CreateAndDestroyContextShouldSucceed() { - var context = ImGui.Raw.CreateContext(null); - Assert.True(context != null); + ImGuiNativeContext* context = ImGui.Raw.CreateContext(null); + Assert.True(context is not null); - var version = Marshal.PtrToStringUTF8((nint)ImGui.Raw.GetVersion()); - output.WriteLine($"ImGui.GetVersion: {version}"); + string? version = Marshal.PtrToStringUTF8((nint)ImGui.Raw.GetVersion()); + m_output.WriteLine($"ImGui.GetVersion: {version}"); Assert.False(string.IsNullOrWhiteSpace(version)); ImGui.Raw.DestroyContext(context); } [Fact] - public void TextDisabled_UsesTheLoadedCimguiSymbol() + public void TextDisabledUsesTheLoadedCimguiSymbol() { - var context = ImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = ImGui.Raw.CreateContext(null); try { ImGuiIO* io = ImGui.Raw.GetIO(); @@ -47,7 +47,9 @@ public void TextDisabled_UsesTheLoadedCimguiSymbol() _ = ImGui.Begin("Native Text Test", ref open); ReadOnlySpan text = "Plugin status\0"u8; fixed (byte* bytes = text) + { ImGui.Raw.TextDisabled((sbyte*)bytes); + } ImGui.End(); ImGui.Render(); } @@ -56,5 +58,4 @@ public void TextDisabled_UsesTheLoadedCimguiSymbol() ImGui.Raw.DestroyContext(context); } } - } diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs index 6cd2cbb01..e27c6df3b 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs @@ -10,14 +10,6 @@ namespace Inno.Native.ImGui.Tests; [Collection("ImGuiContext")] public sealed unsafe class ImGuiPlatformCallbackTests { - private struct CallbackState - { - internal void* registration; - internal int positions; - internal int sizes; - internal bool invalid; - } - [Fact] public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() { @@ -25,21 +17,21 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() void* registration = null; try { - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(null, &SetPosition, &SetSize) == null); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, null, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(null, &SetPosition, &SetSize) is null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, null, &SetSize) is null); ImGui.Raw.GetIO()->BackendPlatformUserData = (void*)1; - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); Assert.Equal((nint)1, (nint)ImGui.Raw.GetIO()->BackendPlatformUserData); ImGui.Raw.GetIO()->BackendPlatformUserData = null; registration = ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize); - Assert.True(registration != null); + Assert.True(registration is not null); Assert.Equal((nint)registration, (nint)ImGui.Raw.GetIO()->BackendPlatformUserData); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); Assert.Equal(1, ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(registration)); nint address = (nint)registration; int foreignThreadResult = -1; - Thread worker = new(() => foreignThreadResult = ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks((void*)address)) + var worker = new Thread(() => foreignThreadResult = ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks((void*)address)) { IsBackground = true }; @@ -52,12 +44,12 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() { ImGui.Raw.SetCurrentContext(second); Assert.Equal(0, ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(registration)); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); void* other = ImGui.Raw.InnoCreatePlatformWindowCallbacks(second, &SetPosition, &SetSize); - Assert.True(other != null); + Assert.True(other is not null); Assert.NotEqual((nint)registration, (nint)other); ImGui.Raw.InnoDestroyPlatformWindowCallbacks(other); - Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData == null); + Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData is null); } finally { @@ -69,7 +61,7 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() { ImGui.Raw.SetCurrentContext(first); ImGui.Raw.InnoDestroyPlatformWindowCallbacks(registration); - Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData == null); + Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData is null); ImGui.Raw.DestroyContext(first); } } @@ -88,7 +80,7 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall io->ConfigFlags |= (int)ImGuiConfigFlags.ViewportsEnable; io->ConfigViewportsNoAutoMerge = 1; io->BackendFlags |= (int)(ImGuiBackendFlags.PlatformHasViewports - | ImGuiBackendFlags.RendererHasViewports | ImGuiBackendFlags.RendererHasTextures); + | ImGuiBackendFlags.RendererHasViewports | ImGuiBackendFlags.RendererHasTextures); io->Fonts->RendererHasTextures = 1; io->BackendRendererUserData = &state; ImGui.Raw.GetMainViewport()->PlatformHandle = (void*)1; @@ -100,8 +92,8 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall platform->PlatformSetWindowTitle = &SetTitle; ImGui.Raw.PlatformIOSetPlatformGetWindowPos(platform, &GetPosition); ImGui.Raw.PlatformIOSetPlatformGetWindowSize(platform, &GetSize); - var monitor = (ImGuiPlatformMonitor*)ImGui.Raw.MemAlloc((nuint)sizeof(ImGuiPlatformMonitor)); - Assert.True(monitor != null); + ImGuiPlatformMonitor* monitor = (ImGuiPlatformMonitor*)ImGui.Raw.MemAlloc((nuint)sizeof(ImGuiPlatformMonitor)); + Assert.True(monitor is not null); *monitor = new ImGuiPlatformMonitor { MainSize = new ImVec2C { X = 1920, Y = 1080 }, @@ -110,7 +102,7 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall }; platform->Monitors = new ImVectorImGuiPlatformMonitor { Data = monitor, Size = 1, Capacity = 1 }; state.registration = ImGui.Raw.InnoCreatePlatformWindowCallbacks(context, &SetPosition, &SetSize); - Assert.True(state.registration != null); + Assert.True(state.registration is not null); for (int frame = 0; frame < 4; frame++) { @@ -144,10 +136,10 @@ private static void SetPosition( float x, float y ) { - var state = (CallbackState*)viewport->PlatformUserData; + CallbackState* state = (CallbackState*)viewport->PlatformUserData; state->positions++; state->invalid |= x != viewport->Pos.X || y != viewport->Pos.Y - || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; + || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] @@ -156,10 +148,10 @@ private static void SetSize( float width, float height ) { - var state = (CallbackState*)viewport->PlatformUserData; + CallbackState* state = (CallbackState*)viewport->PlatformUserData; state->sizes++; state->invalid |= width != viewport->Size.X || height != viewport->Size.Y - || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; + || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] @@ -177,13 +169,13 @@ private static void DestroyWindow(ImGuiViewport* viewport) } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] - private static void NoOp(ImGuiViewport* viewport) { } + private static void NoOp(ImGuiViewport* viewport) {} [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static void SetTitle( ImGuiViewport* viewport, sbyte* title - ) { } + ) {} [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static void GetPosition( @@ -196,4 +188,12 @@ private static void GetSize( ImGuiViewport* viewport, ImVec2C* size ) => *size = viewport->Size; + + private struct CallbackState + { + internal void* registration; + internal int positions; + internal int sizes; + internal bool invalid; + } } diff --git a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs index 856414a37..fdb2faf87 100644 --- a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs @@ -1,23 +1,23 @@ -using Xunit; using System; +using Xunit; using Xunit.Abstractions; namespace Inno.Native.ImGuizmo.Tests; public sealed class ImGuizmoInitTests { - private readonly ITestOutputHelper output; + private readonly ITestOutputHelper m_output; public ImGuizmoInitTests(ITestOutputHelper output) { - this.output = output; + m_output = output; } [Fact] - public void Init_ShouldLoad() + public void InitShouldLoad() { bool isUsing = ImGuizmo.IsUsing(); - output.WriteLine($"ImGuizmo.IsUsing: {isUsing}"); + m_output.WriteLine($"ImGuizmo.IsUsing: {isUsing}"); Assert.False(isUsing); } @@ -25,9 +25,9 @@ public void Init_ShouldLoad() public unsafe void OwnedStyleCanRetireWithoutReleasingTheGlobalBorrow() { Style* borrowed = ImGuizmo.Raw.GetStyle(); - Assert.True(borrowed != null); + Assert.True(borrowed is not null); Style* owned = ImGuizmo.Raw.StyleStyle(); - Assert.True(owned != null); + Assert.True(owned is not null); Assert.True(owned != borrowed); try { @@ -45,7 +45,7 @@ public unsafe void OwnedStyleCanRetireWithoutReleasingTheGlobalBorrow() } [Fact] - public unsafe void IntegerScopeAndSingleStringIdRestoreTheirParentState() + public unsafe void IntegerScopeAndSingleStringIDRestoreTheirParentState() { ReadOnlySpan text = "gizmo-probe\0"u8; fixed (byte* bytes = text) diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs index cb843ab99..651b3ab72 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs @@ -12,10 +12,11 @@ internal sealed class EncodedAudioTestSource : IAudioClipSource internal EncodedAudioTestSource(byte[] bytes) { m_bytes = (byte[])bytes.Clone(); - contentHash = Convert.ToHexString(SHA256.HashData(m_bytes)); + this.contentHash = Convert.ToHexString(SHA256.HashData(m_bytes)); } public string contentHash { get; } public long length => m_bytes.LongLength; + public Stream OpenRead() => new MemoryStream(m_bytes, writable: false); } diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs index 68155baba..20afa45a1 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs @@ -3,9 +3,9 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Audio; using Inno.Core.Execution; -using Xunit; namespace Inno.Adapter.Audio.MiniAudio.Tests; @@ -36,7 +36,7 @@ public void NativePlaybackUsesOneAsynchronousEncodingPreparationForSharedClips(A Assert.Equal(1, source.opens); Assert.Equal(1, source.closures); Assert.True(backend.DestroyClip(first)); - AudioBusHandle master = backend.CreateBus(AudioBusId.master); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); AudioDeviceVoiceHandle voice = backend.Play(second, master, new AudioPlayOptions(loop: true)); Assert.True(voice.isValid); Assert.True(backend.Stop(voice)); @@ -76,8 +76,9 @@ public void InvalidEncodingIdentityFailsPreparationWithoutLeakingTheSource() using var source = new GatedSource(CreateWave()) { contentHash = new string('A', 64) }; source.Release(); AudioClipHandle clip = backend.CreateClip(Describe(source, AudioClipLoadMode.Decode), source); - Assert.True(SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, - TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, TimeSpan.FromSeconds(5)) + ); Assert.Equal(AudioClipState.Failed, backend.GetClipState(clip)); Assert.Equal(1, source.closures); Assert.True(backend.DestroyClip(clip)); @@ -87,32 +88,33 @@ public void InvalidEncodingIdentityFailsPreparationWithoutLeakingTheSource() private static AudioClipDescriptor Describe( IAudioClipSource source, AudioClipLoadMode mode - ) => new(AudioCodecId.wav, mode, 1, 48000, 4800, source.length); + ) => new(AudioCodecID.wav, mode, 1, 48_000, 4800, source.length); private static void WaitForReady( IAudioDevice backend, AudioClipHandle clip ) { - Assert.True(SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, - TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, TimeSpan.FromSeconds(5)) + ); Assert.Equal(AudioClipState.Ready, backend.GetClipState(clip)); } private static void Retire(Func cleanup) - { - Assert.True(SpinWait.SpinUntil(() => - { - try + => Assert.True( + SpinWait.SpinUntil(() => { - _ = cleanup(); - return true; - } - catch (RetirementPendingException) - { - return false; - } - }, TimeSpan.FromSeconds(5))); - } + try + { + _ = cleanup(); + return true; + } + catch (RetirementPendingException) + { + return false; + } + }, TimeSpan.FromSeconds(5)) + ); private static byte[] CreateWave() { @@ -124,8 +126,8 @@ private static byte[] CreateWave() writer.Write(16); writer.Write((short)1); writer.Write((short)1); - writer.Write(48000); - writer.Write(96000); + writer.Write(48_000); + writer.Write(96_000); writer.Write((short)2); writer.Write((short)16); writer.Write("data"u8); @@ -146,7 +148,7 @@ private sealed class GatedSource : IAudioClipSource, IDisposable internal GatedSource(byte[] bytes) { m_bytes = bytes; - contentHash = Convert.ToHexString(SHA256.HashData(bytes)); + this.contentHash = Convert.ToHexString(SHA256.HashData(bytes)); } public string contentHash { get; init; } @@ -173,7 +175,11 @@ private sealed class GatedStream : MemoryStream private readonly GatedSource m_owner; private bool m_closed; - internal GatedStream(GatedSource owner) : base(owner.m_bytes, writable: false) => m_owner = owner; + internal GatedStream(GatedSource owner) + : base(owner.m_bytes, writable: false) + { + m_owner = owner; + } public override async ValueTask ReadAsync( Memory buffer, diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs index d83d82807..b14306d3f 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Threading; -using Inno.Audio; +using Xunit; using Inno.Adapter.Audio.MiniAudio; +using Inno.Audio; using Inno.Core.Mathematics; -using Xunit; namespace Inno.Adapter.Audio.MiniAudio.Tests; @@ -19,17 +19,24 @@ public void NativeAdmissionIncludesUndeliveredCompletionsAndReopensAfterDrain() { using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { - noDevice = true, limits = new AudioDeviceLimits(clips: 1, voices: 1, buses: 1) + noDevice = true, + limits = new AudioDeviceLimits(clips: 1, voices: 1, buses: 1) }); IAudioDevice backend = device; - var descriptor = new AudioClipDescriptor(AudioCodecId.wav, AudioClipLoadMode.Decode, - 1, 48000, 4800, new FileInfo(path).Length); + var descriptor = new AudioClipDescriptor( + AudioCodecID.wav, + AudioClipLoadMode.Decode, + 1, + 48_000, + 4800, + new FileInfo(path).Length + ); var source = new EncodedAudioTestSource(File.ReadAllBytes(path)); AudioClipHandle clip = backend.CreateClip(descriptor, source); WaitForClip(backend, clip); - AudioBusHandle master = backend.CreateBus(AudioBusId.master); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); Assert.False(backend.CreateClip(descriptor, source).isValid); - Assert.False(backend.CreateBus(new AudioBusId("extra"), master).isValid); + Assert.False(backend.CreateBus(new AudioBusID("extra"), master).isValid); for (int iteration = 0; iteration < 32; iteration++) { AudioDeviceVoiceHandle voice = backend.Play(clip, master, new AudioPlayOptions(loop: true)); @@ -41,7 +48,10 @@ public void NativeAdmissionIncludesUndeliveredCompletionsAndReopensAfterDrain() Assert.Equal(voice, completion.voice); } } - finally { File.Delete(path); } + finally + { + File.Delete(path); + } } [Fact] @@ -52,15 +62,28 @@ public void InvalidInputsDoNotAllocateNativeVoicesOrPoisonExistingPlayback() { using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; - AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor(AudioCodecId.wav, - AudioClipLoadMode.Decode, 1, 48000, 4800, new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecID.wav, + AudioClipLoadMode.Decode, + 1, + 48_000, + 4800, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); Assert.False(backend.Play(clip, master, default).isValid); foreach (double invalid in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1d }) + { Assert.False(backend.Play(clip, master, AudioPlayOptions.defaultValue, invalid).isValid); + } foreach (float invalid in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity }) + { Assert.False(backend.SetBusVolume(master, invalid)); + } Assert.Equal(0, backend.statistics.activeVoices); AudioDeviceVoiceHandle voice = backend.Play(clip, master, new AudioPlayOptions(loop: true)); WaitForVoice(backend, voice); @@ -74,7 +97,10 @@ public void InvalidInputsDoNotAllocateNativeVoicesOrPoisonExistingPlayback() Assert.True(backend.DestroyClip(clip)); Assert.True(backend.DestroyBus(master)); } - finally { File.Delete(clipPath); } + finally + { + File.Delete(clipPath); + } } [Fact] @@ -83,46 +109,49 @@ public void HeadlessDeviceAdvancesNativeGraphAndCompletesVoice() string clipPath = CreateWaveFile(frameCount: 2400); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true, channels = 2, - sampleRate = 48000, + sampleRate = 48_000, listenerCount = 2 }); IAudioDevice backend = device; - AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Decode, - 1, - 48000, - 2400, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecID.wav, + AudioClipLoadMode.Decode, + 1, + 48_000, + 2400, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); - AudioListenerHandle listener = backend.CreateListener(new AudioListenerState( - Vector3.ZERO, - Vector3.FORWARD, - Vector3.UP, - Vector3.ZERO)); + AudioListenerHandle listener = backend.CreateListener( + new AudioListenerState(Vector3.ZERO, Vector3.FORWARD, Vector3.UP, Vector3.ZERO) + ); AudioDeviceVoiceHandle voice = backend.Play( clip, master, - new AudioPlayOptions(spatial: new AudioSpatialOptions( - new Vector3(2f, 0f, 0f), - Vector3.FORWARD, - Vector3.ZERO)), - null); + new AudioPlayOptions( + spatial: new AudioSpatialOptions(new Vector3(2f, 0f, 0f), Vector3.FORWARD, Vector3.ZERO) + ), + null + ); WaitForVoice(backend, voice); Assert.Equal(AudioDeviceState.Muted, backend.state); Assert.Equal(2, backend.capabilities.maxListeners); Assert.True(voice.isValid); - Assert.True(backend.SetListener(listener, new AudioListenerState( - new Vector3(1f, 0f, 0f), - Vector3.FORWARD, - Vector3.UP, - Vector3.ZERO))); + Assert.True( + backend.SetListener( + listener, + new AudioListenerState(new Vector3(1f, 0f, 0f), Vector3.FORWARD, Vector3.UP, Vector3.ZERO) + ) + ); backend.Update(0.1f); @@ -148,26 +177,33 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() string clipPath = CreateWaveFile(frameCount: 4800); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions { noDevice = true }); + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; - AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioBusHandle effects = backend.CreateBus(new AudioBusId("test.effects"), master); - foreach (AudioProcessorId processorId in StandardProcessors()) - Assert.True(backend.AddBusProcessor(effects, CreateProcessor(processorId))); + AudioBusHandle master = backend.CreateBus(AudioBusID.master); + AudioBusHandle effects = backend.CreateBus(new AudioBusID("test.effects"), master); + foreach (AudioProcessorID processorID in StandardProcessors()) + { + Assert.True(backend.AddBusProcessor(effects, CreateProcessor(processorID))); + } - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Stream, - 1, - 48000, - 4800, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecID.wav, + AudioClipLoadMode.Stream, + 1, + 48_000, + 4800, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); AudioDeviceVoiceHandle voice = backend.Play( clip, effects, new AudioPlayOptions(loop: true), - backend.dspTime + 0.05d); + backend.dspTime + 0.05d + ); WaitForVoice(backend, voice); Assert.True(backend.TryGetVoiceState(voice, out AudioPlaybackState scheduled)); @@ -195,29 +231,29 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() [Fact] public void MixerGenerationsCanOverlapUntilOldVoicesReleaseTheirGraph() { - string clipPath = CreateWaveFile(frameCount: 48000); + string clipPath = CreateWaveFile(frameCount: 48_000); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions { noDevice = true }); + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; - AudioBusHandle oldMaster = backend.CreateBus(AudioBusId.master); - AudioBusHandle oldMusic = backend.CreateBus(new AudioBusId("test.music"), oldMaster); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Decode, - 1, - 48000, - 48000, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioBusHandle oldMaster = backend.CreateBus(AudioBusID.master); + AudioBusHandle oldMusic = backend.CreateBus(new AudioBusID("test.music"), oldMaster); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecID.wav, + AudioClipLoadMode.Decode, + 1, + 48_000, + 48_000, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); - AudioDeviceVoiceHandle voice = backend.Play( - clip, - oldMusic, - new AudioPlayOptions(loop: true), - null); + AudioDeviceVoiceHandle voice = backend.Play(clip, oldMusic, new AudioPlayOptions(loop: true), null); - AudioBusHandle newMaster = backend.CreateBus(AudioBusId.master); - AudioBusHandle newMusic = backend.CreateBus(new AudioBusId("test.music"), newMaster); + AudioBusHandle newMaster = backend.CreateBus(AudioBusID.master); + AudioBusHandle newMusic = backend.CreateBus(new AudioBusID("test.music"), newMaster); Assert.True(newMaster.isValid); Assert.True(newMusic.isValid); @@ -246,67 +282,73 @@ AudioClipHandle clip private static void WaitForVoice( IAudioDevice device, AudioDeviceVoiceHandle voice - ) { - Assert.True(SpinWait.SpinUntil(() => device.TryGetVoiceState(voice, out AudioPlaybackState state) - && state != AudioPlaybackState.Preparing, TimeSpan.FromSeconds(5))); - } + ) => Assert.True( + SpinWait.SpinUntil(() => ( + device.TryGetVoiceState(voice, out AudioPlaybackState state) + && state != AudioPlaybackState.Preparing + ), TimeSpan.FromSeconds(5)) + ); - private static IEnumerable StandardProcessors() + private static IEnumerable StandardProcessors() { - yield return AudioProcessorId.lowPass; - yield return AudioProcessorId.highPass; - yield return AudioProcessorId.bandPass; - yield return AudioProcessorId.notch; - yield return AudioProcessorId.peak; - yield return AudioProcessorId.lowShelf; - yield return AudioProcessorId.highShelf; - yield return AudioProcessorId.delay; + yield return AudioProcessorID.lowPass; + yield return AudioProcessorID.highPass; + yield return AudioProcessorID.bandPass; + yield return AudioProcessorID.notch; + yield return AudioProcessorID.peak; + yield return AudioProcessorID.lowShelf; + yield return AudioProcessorID.highShelf; + yield return AudioProcessorID.delay; } - private static AudioProcessorConfiguration CreateProcessor(AudioProcessorId id) + private static AudioProcessorConfiguration CreateProcessor(AudioProcessorID id) { - if (id == AudioProcessorId.delay) + if (id == AudioProcessorID.delay) { - return new AudioProcessorConfiguration(id, - [ - new AudioProcessorParameter(AudioParameterId.delayMilliseconds, 5f), - new AudioProcessorParameter(AudioParameterId.decay, 0.2f) - ]); + return new AudioProcessorConfiguration( + id, + [ + new AudioProcessorParameter(AudioParameterID.delayMilliseconds, 5f), + new AudioProcessorParameter(AudioParameterID.decay, 0.2f) + ] + ); } - return new AudioProcessorConfiguration(id, - [ - new AudioProcessorParameter(AudioParameterId.frequency, 1000f), - new AudioProcessorParameter(AudioParameterId.quality, 0.707f), - new AudioProcessorParameter(AudioParameterId.gainDecibels, 2f), - new AudioProcessorParameter(AudioParameterId.shelfSlope, 1f) - ]); + return new AudioProcessorConfiguration( + id, + [ + new AudioProcessorParameter(AudioParameterID.frequency, 1000f), + new AudioProcessorParameter(AudioParameterID.quality, 0.707f), + new AudioProcessorParameter(AudioParameterID.gainDecibels, 2f), + new AudioProcessorParameter(AudioParameterID.shelfSlope, 1f) + ] + ); } private static string CreateWaveFile(int frameCount) { string path = Path.Combine(Path.GetTempPath(), $"inno-miniaudio-{Guid.NewGuid():N}.wav"); - const int sampleRate = 48000; - const short channels = 1; - const short bitsPerSample = 16; - int dataLength = frameCount * channels * (bitsPerSample / 8); + const int C_SAMPLE_RATE = 48_000; + const short C_CHANNELS = 1; + const short C_BITS_PER_SAMPLE = 16; + int dataLength = frameCount * C_CHANNELS * (C_BITS_PER_SAMPLE / 8); using FileStream stream = File.Create(path); - using BinaryWriter writer = new(stream); + using var writer = new BinaryWriter(stream); writer.Write("RIFF"u8); writer.Write(36 + dataLength); writer.Write("WAVE"u8); writer.Write("fmt "u8); writer.Write(16); writer.Write((short)1); - writer.Write(channels); - writer.Write(sampleRate); - writer.Write(sampleRate * channels * (bitsPerSample / 8)); - writer.Write((short)(channels * (bitsPerSample / 8))); - writer.Write(bitsPerSample); + writer.Write(C_CHANNELS); + writer.Write(C_SAMPLE_RATE); + writer.Write(C_SAMPLE_RATE * C_CHANNELS * (C_BITS_PER_SAMPLE / 8)); + writer.Write((short)(C_CHANNELS * (C_BITS_PER_SAMPLE / 8))); + writer.Write(C_BITS_PER_SAMPLE); writer.Write("data"u8); writer.Write(dataLength); for (int frame = 0; frame < frameCount; frame++) { - double phase = 2d * Math.PI * 440d * frame / sampleRate; + double phase = 2d * Math.PI * 440d * frame / C_SAMPLE_RATE; writer.Write((short)(Math.Sin(phase) * short.MaxValue * 0.1d)); } return path; diff --git a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UIServiceTests.cs similarity index 62% rename from tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs rename to tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UIServiceTests.cs index a7b97d871..c2a094046 100644 --- a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs +++ b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UIServiceTests.cs @@ -1,11 +1,11 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.UI.RmlUi; using Inno.Adapter.UI.RmlUi.Authoring; using Inno.Assets; @@ -22,11 +22,10 @@ using Inno.UI; using Inno.UI.Assets; using Inno.UI.Runtime; -using Xunit; namespace Inno.Adapter.UI.RmlUi.Tests; -public sealed class UiServiceTests : IDisposable +public sealed class UIServiceTests : IDisposable { private readonly DiagnosticHub m_diagnostics = new(); private readonly IdentityAllocator m_identities = new(); @@ -39,7 +38,7 @@ public sealed class UiServiceTests : IDisposable private readonly SerializationRegistry m_serialization; private readonly TypeCatalog m_types; - public UiServiceTests() + public UIServiceTests() { m_root = Path.Combine(Path.GetTempPath(), "InnoUiTests", Guid.NewGuid().ToString("N")); m_assets = Path.Combine(m_root, "Assets"); @@ -47,7 +46,9 @@ public UiServiceTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(UiServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(UIServiceTests).Assembly) + }); _ = Assembly.Load("Inno.UI.Assets"); _ = Assembly.Load("Inno.Text.Assets"); _ = Assembly.Load("Inno.Adapter.UI.RmlUi.Authoring"); @@ -59,38 +60,43 @@ public UiServiceTests() [Fact] public void ImporterPublishesValidatedUtf8Document() { - const string markup = "
Hello
"; - File.WriteAllText(Path.Combine(m_assets, "Hud.rml"), markup); + const string C_MARKUP = "
Hello
"; + File.WriteAllText(Path.Combine(m_assets, "Hud.rml"), C_MARKUP); using AssetLoader loader = CreateLoader(); - UiDocumentAsset document = Assert.IsType( - loader.Load(AssetPath.Project("Hud.rml"), typeof(UiDocumentAsset))); + UIDocumentAsset document = Assert.IsType( + loader.Load(AssetPath.Project("Hud.rml"), typeof(UIDocumentAsset)) + ); - Assert.Equal(markup, Assert.IsType(document.source).text); + Assert.Equal(C_MARKUP, Assert.IsType(document.source).text); Assert.Equal(RmlUiIdentifiers.documentLanguage, document.source.language); - Assert.Equal(RmlUiIdentifiers.backend.value, document.implementationId); + Assert.Equal(RmlUiIdentifiers.backend.value, document.implementationID); } [Fact] public void RmlFrontendScopesFontFamiliesAndHonorsNone() { var frontend = new RmlUiDocumentFrontend(); - UiDocumentAnalysis first = frontend.Analyze(new("Hud.rml", """ + UIDocumentAnalysis first = frontend.Analyze( + new UIDocumentSourceFile("Hud.rml", """ - """)); - UiDocumentAnalysis second = frontend.Analyze(new("Other.rml", """ + """) + ); + UIDocumentAnalysis second = frontend.Analyze( + new UIDocumentSourceFile("Other.rml", """ - """)); + """) + ); Assert.True(first.succeeded); Assert.True(second.succeeded); - UiDocumentFontDeclaration face = Assert.Single(first.fonts); + UIDocumentFontDeclaration face = Assert.Single(first.fonts); Assert.Equal("Lato.ttf", face.assetPath); Assert.Contains("font-family: " + face.family, first.text); Assert.DoesNotContain("@font-face", first.text); @@ -102,12 +108,15 @@ public void RmlFrontendScopesFontFamiliesAndHonorsNone() public void UndeclaredFontFamilyProducesNoGlyphDraw() { using var backend = new RmlUiBackend(); - backend.RegisterFont(new(File.ReadAllBytes(FontPath()), 0, "Declared", TextFontStyle.Normal, 400)); - UiContextHandle context = backend.CreateContext(new UiContextOptions("missing-font", 320, 180)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + backend.RegisterFont(new UIFontRegistration(File.ReadAllBytes(FontPath()), 0, "Declared", TextFontStyle.Normal, 400)); + UIContextHandle context = backend.CreateContext(new UIContextOptions("missing-font", 320, 180)); + UIDocumentHandle document = backend.LoadDocument( + context, + Rml(""" Invisible text - """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.Empty(backend.Render(context).commands); @@ -117,19 +126,22 @@ public void UndeclaredFontFamilyProducesNoGlyphDraw() public void ElementHitTestIgnoresBlankCanvasAndPointerEventsNone() { using var backend = new RmlUiBackend(); - UiContextHandle context = backend.CreateContext(new UiContextOptions("hit-test", 320, 180)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + UIContextHandle context = backend.CreateContext(new UIContextOptions("hit-test", 320, 180)); + UIDocumentHandle document = backend.LoadDocument( + context, + Rml("""
- """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); - Assert.True(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(30f, 30f))); - Assert.False(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(120f, 30f))); - Assert.False(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(200f, 100f))); + Assert.True(backend.HasElementAtPoint(context, new Vector2(30f, 30f))); + Assert.False(backend.HasElementAtPoint(context, new Vector2(120f, 30f))); + Assert.False(backend.HasElementAtPoint(context, new Vector2(200f, 100f))); } [Fact] @@ -138,20 +150,30 @@ public void SwitchingDocumentFamiliesThroughNoneDoesNotReuseOldGlyphs() using var backend = new RmlUiBackend(); var frontend = new RmlUiDocumentFrontend(); byte[] font = File.ReadAllBytes(FontPath()); - UiContextHandle context = backend.CreateContext(new UiContextOptions("font-switch", 320, 180)); + UIContextHandle context = backend.CreateContext(new UIContextOptions("font-switch", 320, 180)); foreach ((string family, bool visible) in new[] { - ("A", true), ("B", true), ("none", false), ("A", true) - }) - { - string face = family == "none" ? string.Empty : - $"@font-face {{ font-family: {family}; src: url(Lato.ttf); font-weight: 400; }}"; - UiDocumentAnalysis analysis = frontend.Analyze(new("FontSwitch.rml", - $"Visible text")); + ("A", true), + ("B", true), + ("none", false), + ("A", true) + } + ) { + string face = family == "none" + ? string.Empty + : $"@font-face {{ font-family: {family}; src: url(Lato.ttf); font-weight: 400; }}"; + UIDocumentAnalysis analysis = frontend.Analyze( + new UIDocumentSourceFile( + "FontSwitch.rml", + $"Visible text" + ) + ); Assert.True(analysis.succeeded); - foreach (UiDocumentFontDeclaration declaration in analysis.fonts) - backend.RegisterFont(new(font, 0, declaration.family, declaration.style, declaration.weight)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(analysis.text!)); + foreach (UIDocumentFontDeclaration declaration in analysis.fonts) + { + backend.RegisterFont(new UIFontRegistration(font, 0, declaration.family, declaration.style, declaration.weight)); + } + UIDocumentHandle document = backend.LoadDocument(context, Rml(analysis.text!)); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.Equal(visible, backend.Render(context).commands.Count > 0); @@ -163,13 +185,20 @@ public void SwitchingDocumentFamiliesThroughNoneDoesNotReuseOldGlyphs() public void CssWeightSelectsDifferentFacesOfOneDeclaredFamily() { using var backend = new RmlUiBackend(); - backend.RegisterFont(new(File.ReadAllBytes(FontPath()), 0, - "WeightFamily", TextFontStyle.Normal, 400)); - backend.RegisterFont(new(File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, - "TestData", "LatoLatin-Bold.ttf")), 0, - "WeightFamily", TextFontStyle.Normal, 700)); - UiContextHandle context = backend.CreateContext(new UiContextOptions("weight-selection", 640, 240)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + backend.RegisterFont(new UIFontRegistration(File.ReadAllBytes(FontPath()), 0, "WeightFamily", TextFontStyle.Normal, 400)); + backend.RegisterFont( + new UIFontRegistration( + File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Bold.ttf")), + 0, + "WeightFamily", + TextFontStyle.Normal, + 700 + ) + ); + UIContextHandle context = backend.CreateContext(new UIContextOptions("weight-selection", 640, 240)); + UIDocumentHandle document = backend.LoadDocument( + context, + Rml(""" HUD """); using AssetLoader loader = CreateLoader(); - UiDocumentAsset document = Assert.IsType( - loader.Load(AssetPath.Project("Hud.rml"), typeof(UiDocumentAsset))); + UIDocumentAsset document = Assert.IsType( + loader.Load(AssetPath.Project("Hud.rml"), typeof(UIDocumentAsset)) + ); var artifacts = new RetainingArtifactLookup(loader); - using var runtime = new UiRuntime(new RmlUiBackend(), artifacts); + using var runtime = new UIRuntime(new RmlUiBackend(), artifacts); runtime.Attach(); - UiContextHandle context = runtime.CreateContext(new UiContextOptions("font-retirement", 320, 180)); - UiDocumentHandle loaded = runtime.LoadDocument(context, document); + UIContextHandle context = runtime.CreateContext(new UIContextOptions("font-retirement", 320, 180)); + UIDocumentHandle loaded = runtime.LoadDocument(context, document); runtime.ShowDocument(context, loaded); - UiContextHandle second = runtime.CreateContext(new UiContextOptions("font-retirement-second", 320, 180)); - UiDocumentHandle secondDocument = runtime.LoadDocument(second, document); + UIContextHandle second = runtime.CreateContext(new UIContextOptions("font-retirement-second", 320, 180)); + UIDocumentHandle secondDocument = runtime.LoadDocument(second, document); runtime.ShowDocument(second, secondDocument); Assert.Single(artifacts.retainedKeys); runtime.DestroyContext(context); @@ -221,14 +256,11 @@ public void DestroyingAContextReleasesItsImportedFontArtifact() public void NativeBackendBuildsGeometryAndDrainsDomEvents() { using var backend = new RmlUiBackend(); - backend.RegisterFont(new( - File.ReadAllBytes(FontPath()), - 0, - "Lato", - TextFontStyle.Normal, - 400)); - UiContextHandle context = backend.CreateContext(new UiContextOptions("test", 640, 360)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + backend.RegisterFont(new UIFontRegistration(File.ReadAllBytes(FontPath()), 0, "Lato", TextFontStyle.Normal, 400)); + UIContextHandle context = backend.CreateContext(new UIContextOptions("test", 640, 360)); + UIDocumentHandle document = backend.LoadDocument( + context, + Rml("""
Panel
- """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.NotEmpty(backend.Render(context).commands); @@ -308,19 +349,20 @@ public void NativeBackendRetiresContextsWithLiveDocumentsAndTextures() [Fact] public void NativeHandlesCannotAliasAfterContextOrBackendRetirement() { - UiContextHandle retired; - UiDocumentHandle retiredDocument; + UIContextHandle retired; + UIDocumentHandle retiredDocument; using (var first = new RmlUiBackend()) { - retired = first.CreateContext(new UiContextOptions("first", 128, 128)); - retiredDocument = first.LoadDocument(retired, Rml( - "
First
")); + retired = first.CreateContext(new UIContextOptions("first", 128, 128)); + retiredDocument = first.LoadDocument(retired, Rml("
First
")); } using var second = new RmlUiBackend(); - UiContextHandle current = second.CreateContext(new UiContextOptions("second", 128, 128)); - UiDocumentHandle currentDocument = second.LoadDocument(current, Rml( - "
Second
")); + UIContextHandle current = second.CreateContext(new UIContextOptions("second", 128, 128)); + UIDocumentHandle currentDocument = second.LoadDocument( + current, + Rml("
Second
") + ); Assert.NotEqual(retired, current); Assert.NotEqual(retiredDocument, currentDocument); @@ -336,32 +378,29 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static UiInputSnapshot EmptyInput() - => new(default, default, KeyModifier.None, [], [], [], [], []); + private static UIInputSnapshot EmptyInput() => new(default, default, KeyModifier.None, [], [], [], [], []); - private static UiDocumentSource Rml(string text) - => new(RmlUiIdentifiers.documentLanguage, text); + private static UIDocumentSource Rml(string text) => new(RmlUiIdentifiers.documentLanguage, text); - private static string FontPath() - => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); + private static string FontPath() => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); private sealed class RetainingArtifactLookup(AssetLoader loader) : AssetResidencyProvider, IAssetArtifactLookup { private readonly ArtifactRetention m_retention = new(); - internal IReadOnlyList retainedKeys => m_retention.GetRetainedKeys(); - public ArtifactLease AcquireArtifact( - Guid persistentId, + Guid persistentID, string outputName ) { - ArtifactLease source = loader.AcquireArtifact(persistentId, outputName); + ArtifactLease source = loader.AcquireArtifact(persistentID, outputName); try { ArtifactLease retained = m_retention.Retain(source.info, source.OpenRead); @@ -379,10 +418,11 @@ string outputName } public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact - ) - => loader.TryGetArtifact(persistentId, outputName, out artifact); + ) => loader.TryGetArtifact(persistentID, outputName, out artifact); + + internal IReadOnlyList retainedKeys => m_retention.GetRetainedKeys(); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs index 818f0df57..4680198be 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs @@ -1,9 +1,9 @@ using System; -using Inno.Integration.WindowsX64.Sdl3; +using Xunit; using Inno.Adapter.Platform; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)] @@ -22,26 +22,41 @@ public void MissingHostIsRejectedBeforeSdkInitialization() public void WrappingFailureDestroysOnlyTheNewlyOwnedWindow() { if (NativeWindowTestHost.RunIfRequired(nameof(HostIntegrationTests) + "." + nameof(WrappingFailureDestroysOnlyTheNewlyOwnedWindow))) + { return; + } var host = new FailingHost(); using var app = new Sdl3PlatformApplication(host); Assert.Throws(() => app.CreateWindow(new PlatformWindowOptions - { title = "Failed surface", width = 40, height = 40, visible = false })); + { + title = "Failed surface", + width = 40, + height = 40, + visible = false + })); Assert.Empty(app.GetWindows()); - Assert.True(SDL.Raw.GetWindowFromId(host.lastId) == null); + Assert.True(SDL.Raw.GetWindowFromId(host.lastID) is null); } [Fact] public void SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain() { - if (NativeWindowTestHost.RunIfRequired(nameof(HostIntegrationTests) + "." + nameof(SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain))) + if (NativeWindowTestHost.RunIfRequired( + nameof(HostIntegrationTests) + "." + nameof(SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain) + )) { return; + } var host = new FailingHost { failSurface = false }; using var app = new Sdl3PlatformApplication(host); - using var window = app.CreateWindow(new PlatformWindowOptions - { title = "Single surface", width = 40, height = 40, visible = false }); + using Sdl3PlatformWindow window = app.CreateWindow(new PlatformWindowOptions + { + title = "Single surface", + width = 40, + height = 40, + visible = false + }); Assert.Throws(() => app.CreateWindow(new PlatformWindowOptions())); Assert.Equal(1, host.calls); } @@ -50,19 +65,25 @@ private sealed class FailingHost : ISdl3HostIntegration { private readonly ISdl3HostIntegration m_inner = NativeHostFixture.Create(); internal bool failSurface = true; - internal uint lastId; + internal uint lastID; internal int calls; public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: false, liveResize: false); + public void ConfigureInitialization() => m_inner.ConfigureInitialization(); + public nint CreateWindow(PlatformWindowOptions options) { calls++; nint handle = m_inner.CreateWindow(options); - lastId = SDL.Raw.GetWindowId((SDLWindow*)handle); + lastID = SDL.Raw.GetWindowId((SDLWindow*)handle); return handle; } - public PlatformNativeHandles ResolveNativeSurface(nint windowHandle) => failSurface - ? throw new InvalidOperationException("Injected surface inspection failure.") : m_inner.ResolveNativeSurface(windowHandle); + + public PlatformNativeHandles ResolveNativeSurface(nint windowHandle) + => failSurface + ? throw new InvalidOperationException("Injected surface inspection failure.") + : m_inner.ResolveNativeSurface(windowHandle); + public bool GetInitialFocus(nint windowHandle) => false; } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs index 47e73b481..605ac5f5c 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Adapter.Platform.Sdl3.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs index 000e3fcd8..af56db4c9 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -10,8 +10,11 @@ public sealed class NativeSurfaceLifetimeTests [Fact] public void DisposedWindowRejectsBorrowingItsNativeSurface() { - if (NativeWindowTestHost.RunIfRequired(nameof(NativeSurfaceLifetimeTests) + "." + nameof(DisposedWindowRejectsBorrowingItsNativeSurface))) + if (NativeWindowTestHost.RunIfRequired( + nameof(NativeSurfaceLifetimeTests) + "." + nameof(DisposedWindowRejectsBorrowingItsNativeSurface) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { @@ -21,8 +24,11 @@ public void DisposedWindowRejectsBorrowingItsNativeSurface() visible = false }); INativeWindowSurface surface = window; - Assert.Equal(OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, surface.nativeHandles.handleKind); - Assert.NotEqual(IntPtr.Zero, surface.nativeHandles.windowHandle); + Assert.Equal( + OperatingSystem.IsWindows() ? PlatformNativeHandleID.win32 : PlatformNativeHandleID.cocoa, + surface.nativeHandles.handleKind + ); + Assert.NotEqual(nint.Zero, surface.nativeHandles.windowHandle); window.Dispose(); Assert.Throws(() => surface.nativeHandles); } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs index adcd65adb..97a6da1d7 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs @@ -6,25 +6,41 @@ namespace Inno.Adapter.Platform.Sdl3.Tests; internal static class NativeWindowTestHost { - private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary + private static readonly IReadOnlyDictionary CONTRACTS = new Dictionary { - ["NativeSurfaceLifetimeTests.DisposedWindowRejectsBorrowingItsNativeSurface"] = () => new NativeSurfaceLifetimeTests().DisposedWindowRejectsBorrowingItsNativeSurface(), - ["HostIntegrationTests.WrappingFailureDestroysOnlyTheNewlyOwnedWindow"] = () => new HostIntegrationTests().WrappingFailureDestroysOnlyTheNewlyOwnedWindow(), - ["HostIntegrationTests.SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain"] = () => new HostIntegrationTests().SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain(), - ["WindowOwnershipTests.ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows"] = () => new WindowOwnershipTests().ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows(), - ["WindowOwnershipTests.AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt"] = () => new WindowOwnershipTests().AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt(), - ["WindowOwnershipTests.CrossApplicationReleaseAndCrossThreadCreationAreRejected"] = () => new WindowOwnershipTests().CrossApplicationReleaseAndCrossThreadCreationAreRejected(), - ["WindowSurfaceTests.OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution"] = () => new WindowSurfaceTests().OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution(), - ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.False.False"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner(false, false), - ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.True.True"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner(true, true), + ["NativeSurfaceLifetimeTests.DisposedWindowRejectsBorrowingItsNativeSurface"] = () => new NativeSurfaceLifetimeTests() + .DisposedWindowRejectsBorrowingItsNativeSurface(), + ["HostIntegrationTests.WrappingFailureDestroysOnlyTheNewlyOwnedWindow"] = () => new HostIntegrationTests() + .WrappingFailureDestroysOnlyTheNewlyOwnedWindow(), + ["HostIntegrationTests.SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain"] = () => new HostIntegrationTests() + .SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain(), + ["WindowOwnershipTests.ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows"] = () => new WindowOwnershipTests() + .ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows(), + ["WindowOwnershipTests.AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt"] = () => new WindowOwnershipTests() + .AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt(), + ["WindowOwnershipTests.CrossApplicationReleaseAndCrossThreadCreationAreRejected"] = () => new WindowOwnershipTests() + .CrossApplicationReleaseAndCrossThreadCreationAreRejected(), + ["WindowSurfaceTests.OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution"] = () => new WindowSurfaceTests() + .OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution(), + ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.False.False"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner( + false, + false + ), + ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.True.True"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner( + true, + true + ) }; - private static bool m_executingContract; + + private static bool s_executingContract; internal static bool RunIfRequired(string contract) { - if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + if (s_executingContract || !OperatingSystem.IsMacOS() + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -33,10 +49,12 @@ private static int Main(string[] arguments) { try { - if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + if (arguments.Length != 1 || !CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa requires the process main thread, rather than an xUnit worker or a new managed thread. - m_executingContract = true; + s_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); contract(); Console.Error.WriteLine($"Native contract completed: {arguments[0]}."); diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs index fe64cfb7e..dc9bae322 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.InteropServices; +using Xunit; using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -16,8 +16,17 @@ public void CreationPreservesOptionsAndLeavesRegistrationToTheOwner( bool resizable, bool highPixelDensity ) { - if (NativeWindowTestHost.RunIfRequired(nameof(Sdl3WindowOperationsTests) + "." + nameof(CreationPreservesOptionsAndLeavesRegistrationToTheOwner) + "." + resizable + "." + highPixelDensity)) + if (NativeWindowTestHost.RunIfRequired( + nameof(Sdl3WindowOperationsTests) + + "." + + nameof(CreationPreservesOptionsAndLeavesRegistrationToTheOwner) + + "." + + resizable + + "." + + highPixelDensity + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); var options = new PlatformWindowOptions @@ -44,21 +53,22 @@ bool highPixelDensity Assert.True((flags & SDLWindowFlags.Hidden) != 0); Assert.Equal(resizable, (flags & SDLWindowFlags.Resizable) != 0); Assert.Equal(highPixelDensity, (flags & SDLWindowFlags.HighPixelDensity) != 0); - Assert.Equal((flags & SDLWindowFlags.InputFocus) != 0, - Sdl3WindowOperations.ReadFocus((nint)native)); + Assert.Equal((flags & SDLWindowFlags.InputFocus) != 0, Sdl3WindowOperations.ReadFocus((nint)native)); } finally { SDL.Raw.DestroyWindow(native); } - Assert.True(SDL.Raw.GetWindowFromId(id) == null); + Assert.True(SDL.Raw.GetWindowFromId(id) is null); } [Fact] public void InvalidInputFailsBeforeCreatingAWindow() { Assert.Throws(() => Sdl3WindowOperations.CreateWindow( - new PlatformWindowOptions { width = 0 }, requireOpenGl: false)); + new PlatformWindowOptions { width = 0 }, + requireOpenGl: false + )); Assert.Throws(() => Sdl3WindowOperations.ReadFocus(0)); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs index 1765ec9b2..63e2a8903 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; +using Xunit; using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -12,36 +12,49 @@ public sealed unsafe class WindowOwnershipTests [Fact] public void ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows) + )) { return; + } using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = first.CreateWindow(new PlatformWindowOptions - { title = "Owned surface", width = 40, height = 40, visible = false }); + using Sdl3PlatformWindow window = first.CreateWindow(new PlatformWindowOptions + { + title = "Owned surface", + width = 40, + height = 40, + visible = false + }); Assert.Single(first.GetWindows()); Assert.Empty(second.GetWindows()); window.Dispose(); Assert.Empty(first.GetWindows()); - Assert.True(SDL.Raw.GetWindowFromId(window.windowId) == null); + Assert.True(SDL.Raw.GetWindowFromId(window.windowID) is null); } [Fact] public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt) + )) { return; + } using var app = new Sdl3PlatformApplication(NativeHostFixture.Create()); ReadOnlySpan title = "Borrowed surface\0"u8; SDLWindow* native; fixed (byte* bytes = title) + { native = SDL.Raw.CreateWindow((sbyte*)bytes, 40, 40, (ulong)SDLWindowFlags.Hidden); - Assert.True(native != null); + } + Assert.True(native is not null); uint id = SDL.Raw.GetWindowId(native); try { - var borrowed = app.AdoptWindow((nint)native); + Sdl3PlatformWindow borrowed = app.AdoptWindow((nint)native); Assert.Single(app.GetWindows()); Assert.Throws(() => app.AdoptWindow((nint)native)); app.ReleaseWindow(borrowed); @@ -49,29 +62,39 @@ public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() Assert.True(borrowed.isClosed); Assert.Equal(0, borrowed.sdlWindowHandle); Assert.Throws(() => borrowed.nativeHandles); - Assert.True(SDL.Raw.GetWindowFromId(id) != null); + Assert.True(SDL.Raw.GetWindowFromId(id) is not null); borrowed.Dispose(); - Assert.True(SDL.Raw.GetWindowFromId(id) != null); + Assert.True(SDL.Raw.GetWindowFromId(id) is not null); } finally { SDL.Raw.DestroyWindow(native); } - Assert.True(SDL.Raw.GetWindowFromId(id) == null); + Assert.True(SDL.Raw.GetWindowFromId(id) is null); } [Fact] public void CrossApplicationReleaseAndCrossThreadCreationAreRejected() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(CrossApplicationReleaseAndCrossThreadCreationAreRejected))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(CrossApplicationReleaseAndCrossThreadCreationAreRejected) + )) { return; + } using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = first.CreateWindow(new PlatformWindowOptions - { title = "Thread owner", width = 40, height = 40, visible = false }); + using Sdl3PlatformWindow window = first.CreateWindow(new PlatformWindowOptions + { + title = "Thread owner", + width = 40, + height = 40, + visible = false + }); Assert.Throws(() => second.ReleaseWindow(window)); - Assert.Throws(() => Task.Run(() => first.CreateWindow(new PlatformWindowOptions())).GetAwaiter().GetResult()); + Assert.Throws( + () => Task.Run(() => first.CreateWindow(new PlatformWindowOptions())).GetAwaiter().GetResult() + ); Assert.Single(first.GetWindows()); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs index 2d11f45b0..76092b4af 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs @@ -1,8 +1,8 @@ using System; -using Inno.Integration.WindowsX64.Sdl3; +using Xunit; using Inno.Adapter.Platform; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -11,15 +11,26 @@ public sealed class WindowSurfaceTests [Fact] public void OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowSurfaceTests) + "." + nameof(OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowSurfaceTests) + "." + nameof(OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution) + )) { return; + } - var host = NativeHostFixture.Create(); + ISdl3HostIntegration host = NativeHostFixture.Create(); using var app = new Sdl3PlatformApplication(host); - using var window = app.CreateWindow(new PlatformWindowOptions - { title = "Surface contract", width = 40, height = 40, visible = false }); + using Sdl3PlatformWindow window = app.CreateWindow(new PlatformWindowOptions + { + title = "Surface contract", + width = 40, + height = 40, + visible = false + }); Assert.Equal(host.ResolveNativeSurface(window.sdlWindowHandle), window.nativeHandles); - Assert.Equal(OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, window.nativeHandles.handleKind); + Assert.Equal( + OperatingSystem.IsWindows() ? PlatformNativeHandleID.win32 : PlatformNativeHandleID.cocoa, + window.nativeHandles.handleKind + ); Assert.True(window.pixelWidth > 0); Assert.True(window.pixelHeight > 0); } diff --git a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs index 38d8a52b7..368d4e41e 100644 --- a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs +++ b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs @@ -3,8 +3,8 @@ using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Inno.Native.LibraryLoading; using Xunit; +using Inno.Native.LibraryLoading; namespace Inno.Native.Sdl3.Tests; @@ -46,7 +46,9 @@ public void ExplicitDeploymentSupportsIndependentLibraryOwners() public void ExplicitDeploymentLoadsSdlNearTheWindowsPathLimit() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(252, extendedRoot: false); + } } [Fact] @@ -55,7 +57,9 @@ public void ExplicitDeploymentLoadsSdlNearTheWindowsPathLimit() public void ExplicitDeploymentLoadsSdlBeyondTheWindowsPathLimit() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(300, extendedRoot: false); + } } [Fact] @@ -64,7 +68,9 @@ public void ExplicitDeploymentLoadsSdlBeyondTheWindowsPathLimit() public void ExplicitDeploymentLoadsSdlWithAnExtendedWindowsRoot() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(300, extendedRoot: true); + } } [Theory] @@ -104,8 +110,11 @@ bool extendedRoot string payload = Path.Combine(directory, fileName); File.Copy(source, payload); Assert.Equal(pathLength, payload.Length); - var deployment = new NativeDeploymentIndex("windows-x64", - new Dictionary { [C_LIBRARY_NAME] = fileName }, new Dictionary()); + var deployment = new NativeDeploymentIndex( + "windows-x64", + new Dictionary { [C_LIBRARY_NAME] = fileName }, + new Dictionary() + ); string selectedRoot = extendedRoot ? @"\\?\" + directory : directory; string library = NativeDeploymentIndex.Decode(deployment.Encode()).ResolveLibrary(selectedRoot, C_LIBRARY_NAME); nint module = NativeLibrary.Load(library, typeof(SDL).Assembly, null); diff --git a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs index c37cedd6a..626caf2d6 100644 --- a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs +++ b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs @@ -6,6 +6,13 @@ namespace Inno.Native.Sdl3.Tests; public sealed class Sdl3InitTests { + private readonly ITestOutputHelper m_output; + + public Sdl3InitTests(ITestOutputHelper output) + { + m_output = output; + } + [Fact] public unsafe void GeneratedFlagWidthsMatchSdlHeaders() { @@ -14,17 +21,10 @@ public unsafe void GeneratedFlagWidthsMatchSdlHeaders() Assert.Equal(2, sizeof(SDLKeymod)); } - private readonly ITestOutputHelper output; - - public Sdl3InitTests(ITestOutputHelper output) - { - this.output = output; - } - [Fact] - public unsafe void InitAndQuit_ShouldSucceed() + public unsafe void InitAndQuitShouldSucceed() { - var initResult = SDL.Init(SDLInitFlags.Events); + bool initResult = SDL.Init(SDLInitFlags.Events); if (!initResult) { string message = Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) ?? "SDL.Init returned false."; @@ -32,14 +32,14 @@ public unsafe void InitAndQuit_ShouldSucceed() } string? platform = Marshal.PtrToStringUTF8((nint)SDL.Raw.GetPlatform()); - output.WriteLine($"SDL.GetPlatform: {platform}"); + m_output.WriteLine($"SDL.GetPlatform: {platform}"); Assert.False(string.IsNullOrWhiteSpace(platform)); - var version = SDL.GetVersion(); - var major = version / 1000000; - var minor = (version / 1000) % 1000; - var patch = version % 1000; - output.WriteLine($"SDL.GetVersion: {major}.{minor}.{patch} ({version})"); + int version = SDL.GetVersion(); + int major = version / 1_000_000; + int minor = (version / 1000) % 1000; + int patch = version % 1000; + m_output.WriteLine($"SDL.GetVersion: {major}.{minor}.{patch} ({version})"); Assert.True(version > 0); SDL.Quit(); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs index cb3c10c64..a7aa801f1 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs @@ -27,8 +27,16 @@ public BindingDefinitionTests() [InlineData("")] public async Task ExecutableOrNonLiteralDefinitionsFailBeforeOutputCreation(string body) { - File.WriteAllText(Path.Combine(m_root, "bindings.props"), "fixture" + body + ""); - var descriptor = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); + File.WriteAllText( + Path.Combine(m_root, "bindings.props"), + "fixture" + body + "" + ); + var descriptor = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); var request = new NativeBindingGenerationRequest([descriptor], "fixture", NativeBindingOutputMode.HostSource); await Assert.ThrowsAsync(async () => await BindingTestProfiles.Generator() .GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); @@ -41,8 +49,17 @@ public async Task UndeclaredTargetNeverFallsBackToTheHostAbi() File.WriteAllText(Path.Combine(m_root, "bindings.props"), """ fixtureconfig.json """); - var descriptor = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([descriptor], "unknown", NativeBindingOutputMode.TargetArtifacts); + var descriptor = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [descriptor], + "unknown", + NativeBindingOutputMode.TargetArtifacts + ); await Assert.ThrowsAsync(async () => await BindingTestProfiles.Generator() .GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); Assert.False(Directory.Exists(Path.Combine(m_root, "obj"))); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs index a9741bb75..ef72f2b6c 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs @@ -30,20 +30,33 @@ public async Task SourceInputIdentityDetectsSelectedInputsWithoutGeneratingOrRea string config = Path.Combine(directory, "bindgen.json"); File.WriteAllText(Path.Combine(directory, "common.json"), "{\"schemaVersion\":2,\"api\":{\"name\":\"UnusedDefault\"}}"); string text = File.ReadAllText(config); - File.WriteAllText(config, text.Replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"extends\":[\"common.json\"]", StringComparison.Ordinal)); + File.WriteAllText( + config, + text.Replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"extends\":[\"common.json\"]", StringComparison.Ordinal) + ); string unselected = Path.Combine(directory, "bindgen.unselected.json"); File.WriteAllText(unselected, "{}"); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); - var generator = BindingTestProfiles.Generator(); - NativeBuildContext initial = new(m_root, "release"); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var initial = new NativeBuildContext(m_root, "release"); string identity = await generator.ComputeInputFingerprintAsync(initial, request, CancellationToken.None); File.WriteAllText(unselected, "{\"changed\":true}"); - Assert.Equal(identity, await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + Assert.Equal( + identity, + await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None) + ); string shared = Path.Combine(m_root, "Source", "shared.h"); DateTime timestamp = File.GetLastWriteTimeUtc(shared); File.WriteAllText(shared, File.ReadAllText(shared).Replace("sample", "change", StringComparison.Ordinal)); File.SetLastWriteTimeUtc(shared, timestamp); - Assert.NotEqual(identity, await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + Assert.NotEqual( + identity, + await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None) + ); Assert.Equal(0, initial.statistics.bindingGenerations); Assert.Equal(0, initial.statistics.bindingBatches); Assert.False(Directory.Exists(Path.Combine(directory, "obj"))); @@ -53,11 +66,15 @@ public async Task SourceInputIdentityDetectsSelectedInputsWithoutGeneratingOrRea [Fact] public async Task OneBatchReusesSharedReadsOnlyWithinEachFreshPhase() { - var components = new[] { CreateComponent("first"), CreateComponent("second") }; + NativeComponentDescriptor[] components = [CreateComponent("first"), CreateComponent("second")]; var context = new NativeBuildContext(m_root, "release"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest(components, "fixture", NativeBindingOutputMode.TargetArtifacts); - using var result = await generator.GenerateAsync(context, request, CancellationToken.None); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + components, + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult result = await generator.GenerateAsync(context, request, CancellationToken.None); Assert.Equal(2, result.Count); Assert.Equal(1, context.statistics.bindingBatches); Assert.Equal(2, context.statistics.bindingGenerations); @@ -66,23 +83,31 @@ public async Task OneBatchReusesSharedReadsOnlyWithinEachFreshPhase() long expectedBytes = File.ReadAllBytes(Path.Combine(m_root, "Source", "shared.h")).Length; Assert.All(context.statistics.phases, phase => Assert.True(phase.bytes >= expectedBytes)); var hot = new NativeBuildContext(m_root, "release"); - using var hotResult = await generator.GenerateAsync(hot, request, CancellationToken.None); + using NativeBindingGenerationResult hotResult = await generator.GenerateAsync(hot, request, CancellationToken.None); Assert.Equal(0, hot.statistics.bindingGenerations); Assert.Equal(1, hot.statistics.bindingBatches); string header = Path.Combine(m_root, "Source", "shared.h"); DateTime timestamp = File.GetLastWriteTimeUtc(header); File.WriteAllText(header, "int change(int value);"); File.SetLastWriteTimeUtc(header, timestamp); - using var changed = await generator.GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + using NativeBindingGenerationResult changed = await generator.GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.All(result, entry => Assert.NotEqual(entry.Value.fingerprint, changed[entry.Key].fingerprint)); } [Fact] public async Task ActiveConsumersBlockReplacementAndReleaseAllowsRepair() { - var component = CreateComponent("reader"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + NativeComponentDescriptor component = CreateComponent("reader"); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); var context = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult first = await generator.GenerateAsync(context, request, CancellationToken.None); NativeBindingGenerationDescriptor descriptor = first[component.nativeProject]; @@ -92,59 +117,97 @@ public async Task ActiveConsumersBlockReplacementAndReleaseAllowsRepair() await Assert.ThrowsAnyAsync(async () => { using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - descriptor.artifactDirectory, descriptor.artifactOwnerDirectory, waiting.Token); + descriptor.artifactDirectory, + descriptor.artifactOwnerDirectory, + waiting.Token + ); }); using NativeBindingGenerationResult concurrent = await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.Equal(descriptor.fingerprint, concurrent[component.nativeProject].fingerprint); first.Dispose(); concurrent.Dispose(); Assert.Throws(() => first[component.nativeProject]); using (BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - descriptor.artifactDirectory, descriptor.artifactOwnerDirectory)) + descriptor.artifactDirectory, + descriptor.artifactOwnerDirectory + )) { File.WriteAllText(descriptor.bindingsPath, "damaged"); + } using NativeBindingGenerationResult repaired = await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.Equal(original, File.ReadAllText(repaired[component.nativeProject].bindingsPath)); } [Fact] public async Task AFailedBatchPublishesNoPartialClosureAndPreservesEarlierOutputs() { - var first = CreateComponent("first"); - var second = CreateComponent("second"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([first, second], "fixture", NativeBindingOutputMode.TargetArtifacts); - using var completed = await generator.GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + NativeComponentDescriptor first = CreateComponent("first"); + NativeComponentDescriptor second = CreateComponent("second"); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [first, second], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult completed = await generator.GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); string original = File.ReadAllText(completed[first.nativeProject].bindingsPath); File.WriteAllText(Path.Combine(m_root, "Source", "shared.h"), "int different(int value);"); File.WriteAllText(Path.Combine(m_root, "second", "broken.h"), "invalid C grammar;"); string config = Path.Combine(m_root, "second", "bindgen.json"); File.WriteAllText(config, File.ReadAllText(config).Replace("../Source/shared.h", "broken.h", StringComparison.Ordinal)); await Assert.ThrowsAnyAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + )); Assert.Equal(original, File.ReadAllText(completed[first.nativeProject].bindingsPath)); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "artifacts", "bindings", "first", "fixture"))); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, cancellation.Token)); + new NativeBuildContext(m_root, "release"), + request, + cancellation.Token + )); } [Fact] public async Task FrozenSdkPathsSelectIndependentHeadersWithoutChangingTheProcessEnvironment() { string variable = "INNO_BINDING_SDK_" + Guid.NewGuid().ToString("N"); - var component = CreateSdkComponent(); + NativeComponentDescriptor component = CreateSdkComponent(); string firstSdk = CreateSdk("sdk-first", "int"); string secondSdk = CreateSdk("sdk-second", "long long"); string? original = Environment.GetEnvironmentVariable(variable); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); - using var first = await generator.GenerateAsync(SdkContext(variable, firstSdk), request, CancellationToken.None); - using var second = await generator.GenerateAsync(SdkContext(variable, secondSdk), request, CancellationToken.None); + using NativeBindingGenerationResult first = await generator.GenerateAsync( + SdkContext(variable, firstSdk), + request, + CancellationToken.None + ); + using NativeBindingGenerationResult second = await generator.GenerateAsync( + SdkContext(variable, secondSdk), + request, + CancellationToken.None + ); Assert.NotEqual(first[component.nativeProject].fingerprint, second[component.nativeProject].fingerprint); Assert.Contains("int Sample(int value)", File.ReadAllText(first[component.nativeProject].bindingsPath)); @@ -156,15 +219,26 @@ public async Task FrozenSdkPathsSelectIndependentHeadersWithoutChangingTheProces public async Task MissingSelectedSdkFailsBeforeCreatingCandidatesAndPreservesPublishedBindings() { string variable = "INNO_BINDING_SDK_" + Guid.NewGuid().ToString("N"); - var component = CreateSdkComponent(); + NativeComponentDescriptor component = CreateSdkComponent(); string sdk = CreateSdk("sdk", "int"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); - using var result = await generator.GenerateAsync(SdkContext(variable, sdk), request, CancellationToken.None); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult result = await generator.GenerateAsync( + SdkContext(variable, sdk), + request, + CancellationToken.None + ); string source = File.ReadAllText(result[component.nativeProject].bindingsPath); - var failure = await Assert.ThrowsAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + InvalidDataException failure = await Assert.ThrowsAsync(async () => await generator.GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + )); Assert.Contains("owned.h", failure.Message); Assert.Equal(source, File.ReadAllText(result[component.nativeProject].bindingsPath)); @@ -176,7 +250,7 @@ public async Task MissingSelectedSdkFailsBeforeCreatingCandidatesAndPreservesPub private NativeComponentDescriptor CreateSdkComponent() { - var component = CreateComponent("sdk-component"); + NativeComponentDescriptor component = CreateComponent("sdk-component"); File.WriteAllText(Path.Combine(m_root, "Source", "shared.h"), "#include \nOWNED_SDK_TYPE sample(OWNED_SDK_TYPE value);"); return component; } @@ -197,9 +271,17 @@ string sdk ) { string executable = Path.Combine(m_root, "sdk-tool.exe"); File.WriteAllText(executable, "Selected SDK tool identity; not executed by this C parser fixture."); - var selection = new NativeToolchainSelection("fixture", new BuildHostDescriptor("Windows", "x64"), + var selection = new NativeToolchainSelection( + "fixture", + new BuildHostDescriptor("Windows", "x64"), new Dictionary { ["fixture"] = executable }, - new Dictionary { [variable] = sdk, ["INCLUDE"] = Path.Combine(sdk, "include") }, [sdk], [], new NativeLinkPlan(".dll"), false, new NativeCompilerInputs(systemIncludeDirectories: [Path.Combine(sdk, "include")])); + new Dictionary { [variable] = sdk, ["INCLUDE"] = Path.Combine(sdk, "include") }, + [sdk], + [], + new NativeLinkPlan(".dll"), + false, + new NativeCompilerInputs(systemIncludeDirectories: [Path.Combine(sdk, "include")]) + ); return new NativeBuildContext(m_root, "release").WithToolchain(selection); } @@ -217,7 +299,11 @@ private NativeComponentDescriptor CreateComponent(string name) "api":{"namespace":"Fixture.Native","name":"Api","naming":{"functions":{"casing":"pascal"}}}, "output":{"root":"Generated","layout":"singleFile"}} """); - return new NativeComponentDescriptor(name, name + "/" + name + ".csproj", name + "/" + name + ".csproj", - bindingDefinition: name + "/bindings.props"); + return new NativeComponentDescriptor( + name, + name + "/" + name + ".csproj", + name + "/" + name + ".csproj", + bindingDefinition: name + "/bindings.props" + ); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs index 51c928f29..e92695480 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs @@ -5,8 +5,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Bindings.Tests; @@ -22,17 +22,31 @@ public sealed class BindingGenerationProcessTests /// /// Keeps unchanged mapping identities stable across processes and rejects a real mapping change. /// - /// A task completing after all independent hosts have exited and their identities agree. + /// + /// A task completing after all independent hosts have exited and their identities agree. + /// [Fact] public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() { string? inherited = Environment.GetEnvironmentVariable(C_ROOT); if (inherited is not null) { - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); string identity = await BindingTestProfiles.Generator().ComputeInputFingerprintAsync( - new NativeBuildContext(inherited, "release"), request, CancellationToken.None); + new NativeBuildContext(inherited, "release"), + request, + CancellationToken.None + ); File.WriteAllText(Environment.GetEnvironmentVariable(C_OUTPUT)!, identity); return; } @@ -43,17 +57,24 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() { File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), string.Empty); File.WriteAllText(Path.Combine(root, "Fixture.csproj"), ""); - File.WriteAllText(Path.Combine(root, "bindings.props"), "fixturebindgen.json"); + File.WriteAllText( + Path.Combine(root, "bindings.props"), + "fixturebindgen.json" + ); Directory.CreateDirectory(Path.Combine(root, "Native")); - File.WriteAllLines(Path.Combine(root, "Native", "fixture.h"), Enumerable.Range(0, 64).Select(static index => $"int sample_{index}(int value);")); - var names = Enumerable.Range(0, 64).ToDictionary(static index => $"sample_{index}", static index => $"Sample{index}", StringComparer.Ordinal); + File.WriteAllLines( + Path.Combine(root, "Native", "fixture.h"), + Enumerable.Range(0, 64).Select(static index => $"int sample_{index}(int value);") + ); + Dictionary names = Enumerable.Range(0, 64) + .ToDictionary(static index => $"sample_{index}", static index => $"Sample{index}", StringComparer.Ordinal); WriteConfiguration(root, names); - string first = await RunHost(root, "first"); - string second = await RunHost(root, "second"); + string first = await RunHostAsync(root, "first"); + string second = await RunHostAsync(root, "second"); Assert.Equal(first, second); names["sample_0"] = "Changed"; WriteConfiguration(root, names); - Assert.NotEqual(first, await RunHost(root, "changed")); + Assert.NotEqual(first, await RunHostAsync(root, "changed")); } finally { @@ -64,29 +85,48 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() private static void WriteConfiguration( string root, Dictionary names - ) => File.WriteAllText(Path.Combine(root, "bindgen.json"), JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Native/fixture.h" }, includeDirectories = new[] { "Native" } }, - api = new { @namespace = "Fixture.Native", name = "Api", names }, - output = new { layout = "singleFile", singleFileName = "Bindings.cs", root = "Generated" } - })); + ) => File.WriteAllText( + Path.Combine(root, "bindgen.json"), + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Native/fixture.h" }, includeDirectories = new[] { "Native" } }, + api = new { @namespace = "Fixture.Native", name = "Api", names }, + output = new { layout = "singleFile", singleFileName = "Bindings.cs", root = "Generated" } + }) + ); - private static async Task RunHost( + private static async Task RunHostAsync( string root, string name ) { string dotnet = ToolchainEnvironment.ResolveExecutable(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); string output = Path.Combine(root, name + ".identity"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(dotnet, - ["test", typeof(BindingGenerationProcessTests).Assembly.Location, - "--filter", "FullyQualifiedName=" + typeof(BindingGenerationProcessTests).FullName + "." + nameof(DictionaryMappingsRemainStableAcrossIndependentProcesses), - "--results-directory", Path.Combine(root, "results"), - "--logger", "trx;LogFileName=" + name + ".trx", - "--environment", C_ROOT + "=" + root, "--environment", C_OUTPUT + "=" + output], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + await ToolchainEnvironment.RunAsync( + dotnet, + [ + "test", + typeof(BindingGenerationProcessTests).Assembly.Location, + "--filter", + "FullyQualifiedName=" + + typeof(BindingGenerationProcessTests).FullName + + "." + + nameof(DictionaryMappingsRemainStableAcrossIndependentProcesses), + "--results-directory", + Path.Combine(root, "results"), + "--logger", + "trx;LogFileName=" + name + ".trx", + "--environment", + C_ROOT + "=" + root, + "--environment", + C_OUTPUT + "=" + output + ], + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); return File.ReadAllText(output); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs index 272c36b99..aea4b987f 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs @@ -39,7 +39,9 @@ public async Task ConsumerCopySurvivesSourceRetirementAndUnchangedCopyKeepsTimes Assert.True(second.Execute()); Assert.Equal(timestamp, File.GetLastWriteTimeUtc(second.MaterializedSource)); using (BuildArtifactWriteLease retirement = await BuildArtifactWriteLease.AcquireAsync(first.ArtifactDirectory, m_root)) + { Directory.Delete(first.ArtifactDirectory, recursive: true); + } Assert.Equal(contents, File.ReadAllText(first.MaterializedSource)); } @@ -82,7 +84,7 @@ public async Task CancellationDoesNotDisturbAnExclusivePublisher() public async Task HostConsumerYieldsItsNodeAndWaitsForThePublicationOwner() { MaterializeBindingsTask task = CreateHostTask(); - using FileLease publisher = await FileLease.AcquireAsync(HostPublicationLock, TimeSpan.FromSeconds(5)); + using FileLease publisher = await FileLease.AcquireAsync(hostPublicationLock, TimeSpan.FromSeconds(5)); Task waiting = Task.Run(task.Execute); try { @@ -110,7 +112,7 @@ public async Task CancelingAHostConsumerRetainsThePublisherAndPreviousConsumerCo Directory.CreateDirectory(Path.Combine(task.IntermediateDirectory, "bindings")); string previous = Path.Combine(task.IntermediateDirectory, "bindings", "Bindings.cs"); File.WriteAllText(previous, "previous"); - using FileLease publisher = await FileLease.AcquireAsync(HostPublicationLock, TimeSpan.FromSeconds(5)); + using FileLease publisher = await FileLease.AcquireAsync(hostPublicationLock, TimeSpan.FromSeconds(5)); Task waiting = Task.Run(task.Execute); await m_engine.yielded.Task.WaitAsync(TimeSpan.FromSeconds(5)); task.Cancel(); @@ -121,7 +123,7 @@ public async Task CancelingAHostConsumerRetainsThePublisherAndPreviousConsumerCo Assert.Equal("public static class HostBinding { }", File.ReadAllText(task.Source)); await Assert.ThrowsAsync(async () => { - using FileLease conflicting = await FileLease.AcquireAsync(HostPublicationLock, TimeSpan.FromMilliseconds(100)); + using FileLease conflicting = await FileLease.AcquireAsync(hostPublicationLock, TimeSpan.FromMilliseconds(100)); }); } @@ -132,11 +134,11 @@ public async Task ReacquiringAFailedBuildNodeReleasesThePublicationOwner() m_engine.failReacquire = true; Assert.False(task.Execute()); Assert.False(Directory.Exists(task.IntermediateDirectory)); - using FileLease next = await FileLease.AcquireAsync(HostPublicationLock, TimeSpan.FromSeconds(5)); + using FileLease next = await FileLease.AcquireAsync(hostPublicationLock, TimeSpan.FromSeconds(5)); Assert.NotEmpty(m_engine.errors); } - private string HostPublicationLock => Path.Combine(m_root, "component", "obj", "bindings", "generation.lock"); + private string hostPublicationLock => Path.Combine(m_root, "component", "obj", "bindings", "generation.lock"); private MaterializeBindingsTask CreateHostTask() { @@ -148,7 +150,8 @@ private MaterializeBindingsTask CreateHostTask() return task; } - private MaterializeBindingsTask CreateTask() => new() + private MaterializeBindingsTask CreateTask() + => new() { Source = Path.Combine(m_root, "artifact", "Generated", "Bindings.cs"), ArtifactDirectory = Path.Combine(m_root, "artifact"), @@ -161,32 +164,38 @@ private MaterializeBindingsTask CreateHostTask() private sealed class RecordingBuildEngine : IBuildEngine3 { - internal List errors { get; } = []; - internal TaskCompletionSource yielded { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal bool reacquired { get; private set; } - internal bool failReacquire { get; set; } public bool ContinueOnError => false; public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => yielded.TrySetResult(); + public void Reacquire() { if (failReacquire) + { throw new InvalidOperationException("The build node is unavailable."); + } reacquired = true; } + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public bool BuildProjectFile( string project, string[] targets, IDictionary properties, IDictionary outputs ) => throw new NotSupportedException(); + public bool BuildProjectFile( string project, string[] targets, @@ -195,23 +204,28 @@ public bool BuildProjectFile( string toolsVersion ) => throw new NotSupportedException(); - public bool BuildProjectFilesInParallel( + public BuildEngineResult BuildProjectFilesInParallel( string[] projects, string[] targets, IDictionary[] properties, - IDictionary[] outputs, + IList[] removedProperties, string[] toolsVersions, - bool useResultsCache, - bool unloadProjects + bool returnTargetOutputs ) => throw new NotSupportedException(); - public BuildEngineResult BuildProjectFilesInParallel( + public bool BuildProjectFilesInParallel( string[] projects, string[] targets, IDictionary[] properties, - IList[] removedProperties, + IDictionary[] outputs, string[] toolsVersions, - bool returnTargetOutputs + bool useResultsCache, + bool unloadProjects ) => throw new NotSupportedException(); + + internal List errors { get; } = []; + internal TaskCompletionSource yielded { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal bool reacquired { get; private set; } + internal bool failReacquire { get; set; } } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs index 1d3a0ca12..3991b5f31 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Bindings.Tests; @@ -22,20 +22,35 @@ public async Task PublicationWithoutItsCompiledSelectionFailsBeforePreparingTheT { File.Copy(Path.Combine(engine, "global.json"), Path.Combine(root, "global.json")); string project = Path.Combine(root, "Fixture.proj"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("PropertyGroup", new XElement("InnoProductId", "player")), - new XElement("Target", new XAttribute("Name", "PrepareInnoBuildTaskHost"), - new XElement("Error", new XAttribute("Text", "An invalid publication prepared the task runtime."))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement("PropertyGroup", new XElement("InnoProductId", "player")), + new XElement( + "Target", + new XAttribute("Name", "PrepareInnoBuildTaskHost"), + new XElement("Error", new XAttribute("Text", "An invalid publication prepared the task runtime.")) + ) + ) + ) .Save(project); - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); - using StringWriter output = new(); - using StringWriter error = new(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(sdk, + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + using var output = new StringWriter(); + using var error = new StringWriter(); + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + sdk, ["msbuild", project, "-t:PublishProductNativeDeployment", "-nodeReuse:false", "-v:minimal"], - root, timeout.Token, null, output, error)); + root, + null, + output, + error, + timeout.Token + )); Assert.NotNull(failure); string messages = output.ToString() + error; Assert.Contains("Native publication requires the exact binding selection", messages); @@ -58,42 +73,78 @@ public async Task SelectionRemainsProductOwnedThroughBuildAndPublish() File.Copy(Path.Combine(engine, "global.json"), Path.Combine(root, "global.json")); File.WriteAllText(Path.Combine(root, "Directory.Build.props"), ""); string selection = Path.Combine(root, "NativeBindingSelection.props"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("PropertyGroup", - new XElement("_InnoOwnedProductBindingSelection", selection), - new XElement("InnoNativeBindingSelection", selection)), - new XElement("Target", new XAttribute("Name", "CreateFixtureSelection"), - new XAttribute("BeforeTargets", "PrepareForBuild"), - new XElement("WriteLinesToFile", new XAttribute("File", selection), - new XAttribute("Lines", ""), new XAttribute("Overwrite", "true"))), - new XElement("Target", new XAttribute("Name", "RequireCompiledSelectionForPublication"), - new XAttribute("BeforeTargets", "Publish"), - new XElement("Error", new XAttribute("Condition", $"!Exists('{selection}')"), - new XAttribute("Text", "Build retired the selection before its publication consumer."))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement( + "PropertyGroup", + new XElement("_InnoOwnedProductBindingSelection", selection), + new XElement("InnoNativeBindingSelection", selection) + ), + new XElement( + "Target", + new XAttribute("Name", "CreateFixtureSelection"), + new XAttribute("BeforeTargets", "PrepareForBuild"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", selection), + new XAttribute("Lines", ""), + new XAttribute("Overwrite", "true") + ) + ), + new XElement( + "Target", + new XAttribute("Name", "RequireCompiledSelectionForPublication"), + new XAttribute("BeforeTargets", "Publish"), + new XElement( + "Error", + new XAttribute("Condition", $"!Exists('{selection}')"), + new XAttribute("Text", "Build retired the selection before its publication consumer.") + ) + ) + ) + ) .Save(Path.Combine(root, "Directory.Build.targets")); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "enable")))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "enable") + ) + ) + ) .Save(project); File.WriteAllText(Path.Combine(root, "Api.cs"), "public static class Api { public static int value => 42; }"); - await Execute("build"); + await ExecuteAsync("build"); Assert.True(File.Exists(selection)); - await Execute("publish"); + await ExecuteAsync("publish"); Assert.True(File.Exists(selection)); - async Task Execute(string command) + async Task ExecuteAsync(string command) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); - using StringWriter output = new(); - using StringWriter error = new(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(sdk, + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + using var output = new StringWriter(); + using var error = new StringWriter(); + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + sdk, [command, project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal"], - root, timeout.Token, null, output, error)); + root, + null, + output, + error, + timeout.Token + )); Assert.True(failure is null, output.ToString() + error + failure); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs index 57840ef10..0275f5bb0 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs @@ -6,6 +6,8 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using BGCS.Configuration; +using BGCS.Core; using Xunit; using Inno.Build.Bindings; using Inno.Build.Toolchains; @@ -15,8 +17,11 @@ namespace Inno.Build.Bindings.Tests; public sealed class NativeBindingGenerationTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), - "InnoNativeBindingTests", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoNativeBindingTests", + Guid.NewGuid().ToString("N") + ); [Fact] [Trait("ExternalDependency", "BGCS")] @@ -24,56 +29,97 @@ public async Task DependencyPackageRetainsBindingsWithoutConsumerGeneration() { CreateConfig("int sample(int value);"); File.WriteAllText(Path.Combine(m_root, ".gitignore"), "artifacts/\nobj/\nconsumer/\n"); - await Git(m_root, "init"); - await Git(m_root, "add", "."); - await Git(m_root, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Binding source"); + await GitAsync(m_root, "init"); + await GitAsync(m_root, "add", "."); + await GitAsync(m_root, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Binding source"); string consumer = Path.Combine(m_root, "consumer"); - await Git(m_root, "clone", "--no-hardlinks", m_root, consumer); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); + await GitAsync(m_root, "clone", "--no-hardlinks", m_root, consumer); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("fixture-host", "fixture-arch"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], - new NativeLinkPlan(sharedLibraryExtension: ".data"), false); - var context = new NativeBuildContext(m_root, "release").WithToolchain(tools) + var tools = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("fixture-host", "fixture-arch"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(sharedLibraryExtension: ".data"), + false + ); + NativeBuildContext context = new NativeBuildContext(m_root, "release").WithToolchain(tools) .WithBindingGenerator(BindingTestProfiles.Generator("fixture-target")); int productions = 0; - NativeBuildRecipe Recipe(NativeBuildContext current) => new(component, "fixture", "fixture-target", - [NativeBuildInput.FromPath(current.engineRoot, Path.Combine(current.engineRoot, "Source"))], ["fixture"]); - var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep("fixture", component, new(NativeLibraryKind.Shared), [], + NativeBuildRecipe Recipe(NativeBuildContext current) + => new( + component, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(current.engineRoot, Path.Combine(current.engineRoot, "Source"))], + ["fixture"] + ); + var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( + "fixture", + component, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], ( current, _, cancellation - ) => NativeArtifactPublisher.PublishAsync(current, Recipe(current), ( - _, - output, - token - ) => - { - productions++; - return File.WriteAllTextAsync(Path.Combine(output, "fixture.data"), "native payload", token); - }, cancellation, describeOutputs: static ( - _, - output - ) => - [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)]), - Recipe, static ( + ) => NativeArtifactPublisher.PublishAsync( + current, + Recipe(current), + ( + _, + output, + token + ) => + { + productions++; + return File.WriteAllTextAsync(Path.Combine(output, "fixture.data"), "native payload", token); + }, + describeOutputs: static ( + _, + output + ) => + [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)], + cancellationToken: cancellation + ), + Recipe, + static ( relative, _ - ) => relative)]); - using ProductNativeBuildResult produced = await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); + ) => relative + )]); + using ProductNativeBuildResult produced = await new ComponentNativeProductExecutor().BuildAsync( + context, + plan, + CancellationToken.None + ); string selection = await NativeDependencyManifest.ExportAsync(context, plan, produced, Path.Combine(m_root, "artifacts", "export")); using JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(selection)); JsonElement asset = manifest.RootElement.GetProperty("assets")[0]; string downloads = Path.Combine(consumer, "artifacts", "fixture-target", "native"); Directory.CreateDirectory(downloads); - File.Copy(Path.Combine(m_root, "artifacts", "export", asset.GetProperty("asset").GetString()!), - Path.Combine(downloads, asset.GetProperty("sha256").GetString() + ".zip")); + File.Copy( + Path.Combine(m_root, "artifacts", "export", asset.GetProperty("asset").GetString()!), + Path.Combine(downloads, asset.GetProperty("sha256").GetString() + ".zip") + ); string selected = Path.Combine(consumer, "artifacts", "selection.json"); File.Copy(selection, selected); string managed = File.ReadAllText(produced[0].bindingGeneration!.bindingsPath); - using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(consumer, selected, "fixture-target", "release", plan)) - { + using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + consumer, + selected, + "fixture-target", + "release", + plan + )) { NativeBindingGenerationDescriptor binding = imported.bindingGenerations[component.nativeProject]; Assert.Equal(produced[0].bindingGeneration!.fingerprint, binding.fingerprint); Assert.Equal(managed, File.ReadAllText(binding.bindingsPath)); @@ -82,40 +128,52 @@ [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtif Assert.NotEmpty(NativeBindingCompilation.Load(binding.nativeDirectory).roots); Assert.Equal(1, productions); } - using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync(consumer, selected, "fixture-target", "release", plan); + using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync( + consumer, + selected, + "fixture-target", + "release", + plan + ); Assert.Equal(managed, File.ReadAllText(warm[0].bindingGeneration!.bindingsPath)); Assert.Equal(1, productions); - static Task Git( + static Task GitAsync( string root, params string[] arguments - ) - => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); + ) => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); } [Fact] public void ManagedSelectionPreservesExactNativeIdentitiesInStableProjectOrder() { string output = Path.Combine(m_root, "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(output, + NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["backends/Text/native/Inno.Native.Text/Inno.Native.Text.csproj"] = SelectedGeneration("text-fingerprint"), ["backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj"] = SelectedGeneration("bgfx-fingerprint") - }, new Dictionary + }, + new Dictionary { ["backends/Text/native/Inno.Native.Text/Inno.Native.Text.csproj"] = NativeLibraryKind.Static, ["backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj"] = NativeLibraryKind.Shared - }); + } + ); XElement[] groups = XDocument.Load(output).Root!.Elements("PropertyGroup").ToArray(); Assert.Equal(2, groups.Length); Assert.Equal("'$(MSBuildProjectName)' == 'Inno.Native.Bgfx'", groups[0].Attribute("Condition")!.Value); Assert.Equal("bgfx-fingerprint", groups[0].Element("BindGenExpectedFingerprint")!.Value); - Assert.Equal(SelectedGeneration("bgfx-fingerprint").artifactOwnerDirectory, - groups[0].Element("BindGenArtifactOwnerDirectory")!.Value); - Assert.Equal(Path.GetDirectoryName(SelectedGeneration("bgfx-fingerprint").bindingsPath), - groups[0].Element("BindGenOutputDirectory")!.Value); + Assert.Equal( + SelectedGeneration("bgfx-fingerprint").artifactOwnerDirectory, + groups[0].Element("BindGenArtifactOwnerDirectory")!.Value + ); + Assert.Equal( + Path.GetDirectoryName(SelectedGeneration("bgfx-fingerprint").bindingsPath), + groups[0].Element("BindGenOutputDirectory")!.Value + ); Assert.Equal("text-fingerprint", groups[1].Element("BindGenExpectedFingerprint")!.Value); Assert.Equal("Shared", groups[0].Element("InnoNativeLibraryKind")!.Value); Assert.Equal("Static", groups[1].Element("InnoNativeLibraryKind")!.Value); @@ -141,11 +199,14 @@ bool runtimeImports Assert.Equal(runtimeImports ? "true" : "false", group.Element("InnoNativeRuntimeImports")!.Value); Assert.Equal(linkage.ToString(), group.Element("InnoNativeLibraryKind")!.Value); NativeBindingGenerationDescriptor.ValidateSelection(output, generations, links); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, new Dictionary { ["Inno.Native.Text.csproj"] = SelectedGeneration("selected", !runtimeImports) - }, links)); + }, + links + )); } [Fact] @@ -156,7 +217,10 @@ public void IdenticalSelectionPreservesTheImportTimestampAndChangedSelectionRepl { ["Inno.Native.Text.csproj"] = SelectedGeneration("selected") }; - var linkage = new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared }; + var linkage = new Dictionary + { + ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared + }; NativeBindingGenerationDescriptor.WriteSelection(output, generations, linkage); DateTime originalTime = DateTime.UtcNow.AddMinutes(-1); File.SetLastWriteTimeUtc(output, originalTime); @@ -179,22 +243,40 @@ public void PublicationRejectsChangedOrIncompleteManagedSelection() { ["Inno.Native.Text.csproj"] = SelectedGeneration("original") }; - var linkage = new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared }; + var linkage = new Dictionary + { + ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared + }; NativeBindingGenerationDescriptor.WriteSelection(output, original, linkage); NativeBindingGenerationDescriptor.ValidateSelection(output, original, linkage); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, new Dictionary { ["Inno.Native.Text.csproj"] = SelectedGeneration("changed") - }, linkage)); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, - new Dictionary(), new Dictionary())); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, original, - new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Static })); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, original, - new Dictionary())); - Assert.Equal("original", XDocument.Load(output).Root!.Element("PropertyGroup")! - .Element("BindGenExpectedFingerprint")!.Value); + }, + linkage + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, + new Dictionary(), + new Dictionary() + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, + original, + new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Static } + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, + original, + new Dictionary() + )); + Assert.Equal( + "original", + XDocument.Load(output).Root!.Element("PropertyGroup")! + .Element("BindGenExpectedFingerprint")!.Value + ); } [Fact] @@ -204,16 +286,19 @@ public void CollidingManagedSelectionDoesNotReplaceAnExistingCompleteSelection() Directory.CreateDirectory(Path.Combine(m_root, "Source")); File.WriteAllText(output, "previous complete selection"); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["first/Inno.Native.Text.csproj"] = SelectedGeneration("first"), ["second/inno.native.text.csproj"] = SelectedGeneration("second") - }, new Dictionary + }, + new Dictionary { ["first/Inno.Native.Text.csproj"] = NativeLibraryKind.Shared, ["second/inno.native.text.csproj"] = NativeLibraryKind.Shared - })); + } + )); Assert.Equal("previous complete selection", File.ReadAllText(output)); } @@ -221,28 +306,46 @@ public void CollidingManagedSelectionDoesNotReplaceAnExistingCompleteSelection() public void UnsafeManagedProjectNameIsRejectedBeforeCreatingSelectionOutput() { string output = Path.Combine(m_root, "BindingSelection.props"); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["Inno'Injected.csproj"] = SelectedGeneration("selected") - }, new Dictionary { ["Inno'Injected.csproj"] = NativeLibraryKind.Shared })); + }, + new Dictionary { ["Inno'Injected.csproj"] = NativeLibraryKind.Shared } + )); Assert.False(Directory.Exists(m_root)); } [Theory] - [InlineData(BGCS.Core.BindingImportMode.LibraryImport)] - [InlineData(BGCS.Core.BindingImportMode.DllImport)] + [InlineData(BindingImportMode.LibraryImport)] + [InlineData(BindingImportMode.DllImport)] [Trait("ExternalDependency", "BGCS")] - public async Task PlatformImportChoiceChangesOfficialGenerationAndFrozenSelection(BGCS.Core.BindingImportMode importMode) + public async Task PlatformImportChoiceChangesOfficialGenerationAndFrozenSelection(BindingImportMode importMode) { CreateConfig("unsigned long long sample(void* value);"); NativeBindingGenerationDescriptor provider = await GenerateAsync(); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); - var profile = new NativeBindingProfile("fixture-target", - new BGCS.Configuration.TargetConfiguration { id = "windows-x64-msvc" }, importMode: importMode); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [component], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); + var profile = new NativeBindingProfile( + "fixture-target", + new TargetConfiguration { id = "windows-x64-msvc" }, + importMode: importMode + ); using NativeBindingGenerationResult result = await new NativeBindingGenerator(profile).GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); NativeBindingGenerationDescriptor imports = result[component.nativeProject]; Assert.False(provider.usesRuntimeImports); Assert.True(imports.usesRuntimeImports); @@ -263,8 +366,13 @@ public async Task SourceChangesSelectIndependentGenerationsAndTamperingIsRepaire string descriptorPath = Path.Combine(m_root, "requests", "descriptor.json"); first.Write(descriptorPath); Assert.Equal(first.bindingsPath, NativeBindingGenerationDescriptor.Load(descriptorPath).bindingsPath); - Assert.True(BuildArtifactManifest.IsComplete(Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))!, - first.fingerprint, ["Native", "Generated"])); + Assert.True( + BuildArtifactManifest.IsComplete( + Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))!, + first.fingerprint, + ["Native", "Generated"] + ) + ); File.WriteAllText(first.bindingsPath, "tampered"); NativeBindingGenerationDescriptor repaired = await GenerateAsync(); @@ -284,8 +392,17 @@ public async Task SourceChangesSelectIndependentGenerationsAndTamperingIsRepaire public async Task UnselectedPlatformDoesNotInvalidateTheSelectedGeneration() { string config = CreateConfig("int sample(int value);"); - var owner = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([owner], "fixture-target", NativeBindingOutputMode.TargetArtifacts); + var owner = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [owner], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); NativeBindingGenerationDescriptor first = await GenerateAsync(); string definitionPath = Path.Combine(m_root, "bindings.props"); XDocument definition = XDocument.Load(definitionPath); @@ -293,14 +410,16 @@ public async Task UnselectedPlatformDoesNotInvalidateTheSelectedGeneration() var unchangedContext = new NativeBuildContext(m_root, "release"); using (NativeBindingGenerationResult unchanged = await BindingTestProfiles.Generator("fixture-target") - .GenerateAsync(unchangedContext, request, CancellationToken.None)) - { + .GenerateAsync(unchangedContext, request, CancellationToken.None) + ) { Assert.Equal(first.fingerprint, unchanged[owner.nativeProject].fingerprint); Assert.Equal(0, unchangedContext.statistics.bindingGenerations); } - File.WriteAllText(Path.Combine(m_root, "selected.json"), - File.ReadAllText(config).Replace("Fixture.Native", "Fixture.Selected", StringComparison.Ordinal)); + File.WriteAllText( + Path.Combine(m_root, "selected.json"), + File.ReadAllText(config).Replace("Fixture.Native", "Fixture.Selected", StringComparison.Ordinal) + ); definition.Root!.Element("PropertyGroup")!.Element("InnoBindingConfig")!.Value = "selected.json"; definition.Save(definitionPath); NativeBindingGenerationDescriptor changed = await GenerateAsync(); @@ -315,14 +434,22 @@ public async Task CppBridgeAndManagedBindingsShareOneCompletedGeneration() { string config = CreateConfig("int sample(int value);"); string facade = Path.Combine(m_root, "Source", "facade.hpp"); - File.WriteAllText(facade, "class Counter { public: explicit Counter(int value) : value_(value) {} int Add(int value) { return value_ + value; } private: int value_; };"); + File.WriteAllText( + facade, + "class Counter { public: explicit Counter(int value) : value_(value) {} int Add(int value) { return value_ + value; } private: int value_; };" + ); WriteCppConfig(config); NativeBindingGenerationDescriptor first = await GenerateAsync(); NativeBindingCompilation compilation = NativeBindingCompilation.Load(first.nativeDirectory); Assert.Contains(compilation.files, file => file.compile && file.rootId == "generated"); - Assert.Contains(compilation.files, file => !file.compile && file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal)); - Assert.Equal(Path.GetDirectoryName(first.nativeDirectory), - Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))); + Assert.Contains( + compilation.files, + file => !file.compile && file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal) + ); + Assert.Equal( + Path.GetDirectoryName(first.nativeDirectory), + Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath)) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "declared"))); string original = File.ReadAllText(first.bindingsPath); File.WriteAllText(facade, "class Counter { invalid C++; };"); @@ -342,11 +469,17 @@ public async Task HostBindingFailurePreservesBothPublishedOutputTrees() NativeBindingGenerationDescriptor initial = await GenerateAsync(mode: NativeBindingOutputMode.HostSource); string source = File.ReadAllText(initial.bindingsPath); NativeBindingCompilation compilation = NativeBindingCompilation.Load(initial.nativeDirectory); - string nativeHeader = Path.Combine(initial.nativeDirectory, compilation.files.First(file => - file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal)).relativePath); + string nativeHeader = Path.Combine( + initial.nativeDirectory, + compilation.files.First(file => ( + file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal) + )).relativePath + ); string header = File.ReadAllText(nativeHeader); - string nativeSource = Path.Combine(initial.nativeDirectory, compilation.files.First(file => - file.rootId == "generated" && file.compile).relativePath); + string nativeSource = Path.Combine( + initial.nativeDirectory, + compilation.files.First(file => (file.rootId == "generated" && file.compile)).relativePath + ); string implementation = File.ReadAllText(nativeSource); File.WriteAllText(facade, "class Counter { public: int Changed() { return 9; } };"); File.WriteAllText(config, File.ReadAllText(config).Replace("facade.hpp", "missing.hpp", StringComparison.Ordinal)); @@ -371,7 +504,7 @@ public async Task FailedOrCanceledGenerationKeepsTheLastCompleteBundle() Assert.Equal(original, File.ReadAllText(first.bindingsPath)); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => GenerateAsync(cancellation: cancellation.Token)); + await Assert.ThrowsAnyAsync(() => GenerateAsync(cancellationToken: cancellation.Token)); Assert.Equal(original, File.ReadAllText(first.bindingsPath)); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "artifacts", "bindings", "fixture", "fixture-target"))); } @@ -393,25 +526,13 @@ public void Dispose() if (Directory.Exists(m_root)) { foreach (string file in Directory.EnumerateFiles(m_root, "*", SearchOption.AllDirectories)) + { File.SetAttributes(file, FileAttributes.Normal); + } Directory.Delete(m_root, recursive: true); } } - private static NativeBindingGenerationDescriptor SelectedGeneration( - string fingerprint, - bool usesRuntimeImports = false - ) - => new() - { - fingerprint = fingerprint, - artifactDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint), - artifactOwnerDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration"), - bindingsPath = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint, "Generated", "Bindings.cs"), - usesRuntimeImports = usesRuntimeImports, - nativeDirectory = string.Empty - }; - private string CreateConfig(string header) { Directory.CreateDirectory(Path.Combine(m_root, "Source")); @@ -420,13 +541,17 @@ private string CreateConfig(string header) File.WriteAllText(Path.Combine(m_root, "Fixture.csproj"), ""); WriteDefinition(); string config = Path.Combine(m_root, "bindgen.json"); - File.WriteAllText(config, JsonSerializer.Serialize(new { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Source/api.h" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); + File.WriteAllText( + config, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Source/api.h" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); return config; } @@ -434,33 +559,62 @@ private async Task GenerateAsync( NativeBindingOutputMode mode = NativeBindingOutputMode.TargetArtifacts, bool checkOnly = false, string? expected = null, - CancellationToken cancellation = default + CancellationToken cancellationToken = default ) { - var owner = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var fingerprints = expected is null ? null : new Dictionary { [owner.nativeProject] = expected }; + var owner = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + Dictionary? fingerprints = expected is null + ? null + : new Dictionary { [owner.nativeProject] = expected }; var request = new NativeBindingGenerationRequest([owner], "fixture-target", mode, checkOnly, fingerprints); - using var result = await BindingTestProfiles.Generator("fixture-target").GenerateAsync( - new NativeBuildContext(m_root, "release"), request, cancellation); + using NativeBindingGenerationResult result = await BindingTestProfiles.Generator("fixture-target").GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + cancellationToken + ); return result[owner.nativeProject]; } private void WriteDefinition() - { - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("InnoNativeComponentId", "fixture"), new XElement("InnoBindingConfig", "bindgen.json")))) + => new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("InnoNativeComponentId", "fixture"), + new XElement("InnoBindingConfig", "bindgen.json") + ) + ) + ) .Save(Path.Combine(m_root, "bindings.props")); - } - private static void WriteCppConfig(string path) + private static NativeBindingGenerationDescriptor SelectedGeneration( + string fingerprint, + bool usesRuntimeImports = false + ) => new() { - File.WriteAllText(path, JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "cpp", languageStandard = "c++20", headers = new[] { "Source/facade.hpp" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); - } + fingerprint = fingerprint, + artifactDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint), + artifactOwnerDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration"), + bindingsPath = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint, "Generated", "Bindings.cs"), + usesRuntimeImports = usesRuntimeImports, + nativeDirectory = string.Empty + }; + private static void WriteCppConfig(string path) + => File.WriteAllText( + path, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "cpp", languageStandard = "c++20", headers = new[] { "Source/facade.hpp" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs index bffe5a1f0..0761ac6df 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs @@ -7,9 +7,9 @@ using BGCS.Core; using BGCS.Core.Targets; using BGCS.Extension.BrowserWasm; +using Xunit; using Inno.Build.Bindings; using Inno.Build.Toolchains; -using Xunit; namespace Inno.Build.Bindings.Tests; @@ -24,41 +24,66 @@ public sealed class NativeBindingProfileTests : IDisposable /// /// Requires an explicit Browser extension and publishes aggregate pointer adapters with remappable inputs. /// - /// The completion of generation, verification and a repeated cache hit. + /// + /// The completion of generation, verification and a repeated cache hit. + /// [Fact] public async Task BrowserAggregateBridgeRequiresExplicitExtensionAndReusesVerifiedGeneration() { Directory.CreateDirectory(Path.Combine(m_root, "Source")); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); File.WriteAllText(Path.Combine(m_root, "Fixture.csproj"), ""); - File.WriteAllText(Path.Combine(m_root, "Source", "api.h"), - "typedef struct Pair { int first; int second; } Pair; Pair swap_pair(Pair value);"); - File.WriteAllText(Path.Combine(m_root, "bindings.props"), - "fixture" + - "bindgen.json"); + File.WriteAllText( + Path.Combine(m_root, "Source", "api.h"), + "typedef struct Pair { int first; int second; } Pair; Pair swap_pair(Pair value);" + ); + File.WriteAllText( + Path.Combine(m_root, "bindings.props"), + "fixture" + + "bindgen.json" + ); File.WriteAllText(Path.Combine(m_root, "bindgen.json"), """ {"schemaVersion":2,"library":{"id":"fixture","nativeName":"fixture"}, "source":{"language":"c","headers":["Source/api.h"]}, "api":{"namespace":"Fixture.Native","name":"Api"}, "output":{"layout":"singleFile","singleFileName":"Bindings.cs"}} """); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [component], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); var target = new TargetConfiguration { id = "emscripten-wasm32-emscripten" }; var runtime = new ManagedRuntimeId("dotnet.mono-wasm"); - var missing = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - importMode: BindingImportMode.LibraryImport)); + var missing = new NativeBindingGenerator( + new NativeBindingProfile("fixture-target", target, runtime, importMode: BindingImportMode.LibraryImport) + ); await Assert.ThrowsAsync(async () => { using NativeBindingGenerationResult rejected = await missing.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); }); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "bindings"))); - var generator = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - configureGenerator: static builder => builder.AddPlugin(), - importMode: BindingImportMode.LibraryImport)); - NativeBuildContext cold = new(m_root, "release"); + var generator = new NativeBindingGenerator( + new NativeBindingProfile( + "fixture-target", + target, + runtime, + configureGenerator: static builder => builder.AddPlugin(), + importMode: BindingImportMode.LibraryImport + ) + ); + var cold = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult first = await generator.GenerateAsync(cold, request, CancellationToken.None); NativeBindingGenerationDescriptor generation = first[component.nativeProject]; NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); @@ -66,22 +91,34 @@ await Assert.ThrowsAsync(async () => Assert.True(generation.usesRuntimeImports); Assert.NotEmpty(compilation.requiredExports); Assert.Empty(compilation.staticExportSymbols); - Assert.All(compilation.roots.Where(static root => root.frozen), static root => Assert.False(Path.IsPathFullyQualified(root.directory))); + Assert.All( + compilation.roots.Where(static root => root.frozen), + static root => Assert.False(Path.IsPathFullyQualified(root.directory)) + ); Assert.Equal(1, cold.statistics.bindingGenerations); byte[] published = File.ReadAllBytes(generation.bindingsPath); - var unsupported = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - configureGenerator: static builder => builder.AddPlugin(), - importMode: BindingImportMode.FunctionTable)); + var unsupported = new NativeBindingGenerator( + new NativeBindingProfile( + "fixture-target", + target, + runtime, + configureGenerator: static builder => builder.AddPlugin(), + importMode: BindingImportMode.FunctionTable + ) + ); InvalidDataException importFailure = await Assert.ThrowsAsync(async () => { using NativeBindingGenerationResult rejected = await unsupported.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); }); Assert.Contains("FunctionTable", importFailure.Message, StringComparison.Ordinal); Assert.Equal(published, File.ReadAllBytes(generation.bindingsPath)); - NativeBuildContext hot = new(m_root, "release"); + var hot = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult repeated = await generator.GenerateAsync(hot, request, CancellationToken.None); Assert.Equal(generation.fingerprint, repeated[component.nativeProject].fingerprint); Assert.Equal(0, hot.statistics.bindingGenerations); @@ -93,6 +130,8 @@ await Assert.ThrowsAsync(async () => public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, true); + } } } diff --git a/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs index d244de35e..5c6bafc5a 100644 --- a/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs @@ -23,7 +23,10 @@ public async Task NativeVerificationRejectsTargetsWithoutAnEditorRunnerBeforeCre File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); Console.SetOut(output); Console.SetError(output); - int result = await BuildApplication.Run(["verify-native", "--engine-root", root, "--target", "browser-wasm"], CancellationToken.None); + int result = await BuildApplication.RunAsync( + ["verify-native", "--engine-root", root, "--target", "browser-wasm"], + CancellationToken.None + ); Assert.Equal(1, result); Assert.Contains("requires a registered Editor test host", output.ToString(), StringComparison.Ordinal); Assert.DoesNotContain("BGCS-CSHARP-ABI-PLAN", output.ToString(), StringComparison.Ordinal); @@ -47,12 +50,14 @@ public async Task VerifyRoutesToTheArchitectureCommandWithoutPreparingAProduct() try { Directory.CreateDirectory(Path.Combine(root, "src", "services", "audio")); - File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), - "Microsoft Visual Studio Solution File, Format Version 12.00"); + File.WriteAllText( + Path.Combine(root, "InnoEngine.sln"), + "Microsoft Visual Studio Solution File, Format Version 12.00" + ); File.WriteAllText(Path.Combine(root, "src", "services", "audio", "Probe.cs"), "global using System;"); Console.SetOut(output); Console.SetError(output); - int result = await BuildApplication.Run(["verify", root], CancellationToken.None); + int result = await BuildApplication.RunAsync(["verify", root], CancellationToken.None); Assert.Equal(1, result); Assert.Contains("global using", output.ToString(), StringComparison.Ordinal); Assert.DoesNotContain("INNO-TASK", output.ToString(), StringComparison.Ordinal); @@ -63,7 +68,9 @@ public async Task VerifyRoutesToTheArchitectureCommandWithoutPreparingAProduct() Console.SetOut(previousOutput); Console.SetError(previousError); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs index dcbb7d676..3ca61c677 100644 --- a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs @@ -1,7 +1,7 @@ using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; namespace Inno.Build.Cli.Tests; @@ -17,16 +17,16 @@ public sealed class DevelopmentEntryCommandTests [InlineData("support-pack", "--clean")] [InlineData("editor", "--dry-run")] [InlineData("editor", "--unrecognized", "value")] - public async Task InvalidCommandsFailBeforeSdkDiscoveryOrCleanup(params string[] arguments) - { - Assert.Equal(1, await BuildApplication.Run(arguments, CancellationToken.None)); - } + public async Task InvalidCommandsFailBeforeSdkDiscoveryOrCleanup(params string[] arguments) => Assert.Equal( + 1, + await BuildApplication.RunAsync(arguments, CancellationToken.None) + ); [Fact] public async Task CancellationReturnsBeforeCreatingBuildState() { using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - Assert.Equal(2, await BuildApplication.Run(["editor", "--clean"], cancellation.Token)); + Assert.Equal(2, await BuildApplication.RunAsync(["editor", "--clean"], cancellation.Token)); } } diff --git a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs index 6fb642317..10b285512 100644 --- a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs @@ -1,10 +1,10 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; +using Inno.Testing.Source; namespace Inno.Build.Cli.Tests; @@ -20,7 +20,7 @@ public async Task InvalidSdkSelectionFailsBeforeCheckoutOwnership(params string[ string root = TestRepository.GetRoot(typeof(DevelopmentEntrySdkSelectionTests).Assembly); string ownership = Path.Combine(root, "artifacts", "entry", "checkout.lock"); DateTime? original = File.Exists(ownership) ? File.GetLastWriteTimeUtc(ownership) : null; - Assert.Equal(1, await BuildApplication.Run(["editor", "--tools-target", "windows-x64", .. options], CancellationToken.None)); + Assert.Equal(1, await BuildApplication.RunAsync(["editor", "--tools-target", "windows-x64", .. options], CancellationToken.None)); Assert.Equal(original, File.Exists(ownership) ? File.GetLastWriteTimeUtc(ownership) : null); } } diff --git a/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs b/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs index 7ff9cc10c..740871869 100644 --- a/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs @@ -4,8 +4,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Cli.Tests; @@ -24,12 +24,27 @@ string products Directory.CreateDirectory(Path.GetDirectoryName(output)!); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT")!, OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - int result = await BuildApplication.Run(["native-dependencies", "--operation", "describe", "--engine-root", root, - "--tools-target", OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64", "--target", target, - "--dotnet", dotnet, "--output", output], CancellationToken.None); + int result = await BuildApplication.RunAsync([ + "native-dependencies", + "--operation", + "describe", + "--engine-root", + root, + "--tools-target", + OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64", + "--target", + target, + "--dotnet", + dotnet, + "--output", + output + ], CancellationToken.None); Assert.Equal(0, result); using JsonDocument description = JsonDocument.Parse(File.ReadAllText(output)); Assert.Equal(target, description.RootElement.GetProperty("target").GetString()); - Assert.Equal(products.Split(','), description.RootElement.GetProperty("products").EnumerateArray().Select(static value => value.GetString())); + Assert.Equal( + products.Split(','), + description.RootElement.GetProperty("products").EnumerateArray().Select(static value => value.GetString()) + ); } } diff --git a/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs b/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs index b5d8d24bf..a3c4d8d6f 100644 --- a/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; namespace Inno.Build.Cli.Tests; @@ -21,10 +21,18 @@ public async Task InvalidExplicitSourceIsRejectedBeforeToolsAndProjectStateAreCr try { Console.SetError(errors); - int result = await BuildApplication.Run( - ["scripts", "--engine-root", owner, - "--project", project, "--output", output], - CancellationToken.None); + int result = await BuildApplication.RunAsync( + [ + "scripts", + "--engine-root", + owner, + "--project", + project, + "--output", + output + ], + CancellationToken.None + ); Assert.Equal(1, result); Assert.Contains("Engine checkout is unavailable", errors.ToString()); diff --git a/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs index a9745b686..c7d484c8f 100644 --- a/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs @@ -17,27 +17,50 @@ public async Task ScriptExportAndIdeProjectionRequireNoNativeSourceOrToolsTarget { Directory.CreateDirectory(Path.Combine(m_root, "Project", "Assets")); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); - File.WriteAllText(Path.Combine(m_root, "Project", "Assets", "Probe.cs"), - "using InnoEngine.Scene; public sealed class Probe : GameBehavior { }"); + File.WriteAllText( + Path.Combine(m_root, "Project", "Assets", "Probe.cs"), + "using InnoEngine.Scene; public sealed class Probe : GameBehavior { }" + ); string unrelatedCatalog = Path.Combine(m_root, "artifacts", "cache-owners"); Directory.CreateDirectory(unrelatedCatalog); File.WriteAllText(Path.Combine(unrelatedCatalog, "unrelated.json"), "unavailable product-cache metadata"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); TextWriter previousError = Console.Error; using var errors = new StringWriter(CultureInfo.InvariantCulture); try { Console.SetError(errors); - int result = await BuildApplication.Run(["scripts", "--engine-root", m_root, - "--project", Path.Combine(m_root, "Project"), "--output", Path.Combine(m_root, "Scripts"), - "--dotnet", host, "--ide"], CancellationToken.None); + int result = await BuildApplication.RunAsync([ + "scripts", + "--engine-root", + m_root, + "--project", + Path.Combine(m_root, "Project"), + "--output", + Path.Combine(m_root, "Scripts"), + "--dotnet", + host, + "--ide" + ], CancellationToken.None); Assert.True(result == 0, errors.ToString()); Assert.DoesNotContain("automatic cache maintenance", errors.ToString(), StringComparison.Ordinal); Assert.True(File.Exists(Path.Combine(m_root, "Scripts", "Inno.GameScripts.dll"))); Assert.True(File.Exists(Path.Combine(m_root, "Project", "Inno.GameScripts.csproj"))); - Assert.NotEmpty(Directory.GetFiles(Path.Combine(m_root, "Project", "Library"), - "Inno.ScriptApi.Runtime.dll", SearchOption.AllDirectories)); + Assert.NotEmpty( + Directory.GetFiles( + Path.Combine(m_root, "Project", "Library"), + "Inno.ScriptApi.Runtime.dll", + SearchOption.AllDirectories + ) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "native"))); Assert.False(Directory.Exists(Path.Combine(m_root, "extern"))); } @@ -52,14 +75,26 @@ public async Task PrecancelledScriptExportCreatesNoWorkspace() { using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - Assert.Equal(2, await BuildApplication.Run(["scripts", "--engine-root", m_root, - "--project", Path.Combine(m_root, "Project"), "--output", Path.Combine(m_root, "Scripts")], cancellation.Token)); + Assert.Equal( + 2, + await BuildApplication.RunAsync([ + "scripts", + "--engine-root", + m_root, + "--project", + Path.Combine(m_root, "Project"), + "--output", + Path.Combine(m_root, "Scripts") + ], cancellation.Token) + ); Assert.False(Directory.Exists(m_root)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs b/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs index b0f1ac4e2..64c661501 100644 --- a/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs @@ -2,10 +2,10 @@ using System.Collections; using System.Collections.Generic; using System.IO; -using Inno.Build.Tasks; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; using Xunit; +using Inno.Build.Tasks; +using Inno.Build.Toolchains; namespace Inno.Build.Integration.Tests; @@ -33,7 +33,9 @@ public void MissingOrCanceledDefinitionCannotCreateGenerationCandidates(bool can DescriptorOutputPath = Path.Combine(m_root, "request.json") }; if (canceled) + { task.Cancel(); + } Assert.False(task.Execute()); Assert.NotEmpty(engine.errors); @@ -52,9 +54,12 @@ private sealed class RecordingBuildEngine : IBuildEngine public string ProjectFileOfTaskNode => "fixture.proj"; public void LogErrorEvent(BuildErrorEventArgs e) => errors.Add(e.Message ?? string.Empty); - public void LogWarningEvent(BuildWarningEventArgs e) { } - public void LogMessageEvent(BuildMessageEventArgs e) { } - public void LogCustomEvent(CustomBuildEventArgs e) { } + + public void LogWarningEvent(BuildWarningEventArgs e) {} + + public void LogMessageEvent(BuildMessageEventArgs e) {} + + public void LogCustomEvent(CustomBuildEventArgs e) {} public bool BuildProjectFile( string projectFileName, diff --git a/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs b/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs index 364c5720a..02f2f18f4 100644 --- a/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs @@ -5,10 +5,10 @@ using System.Security; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; -using Inno.Testing.Source; using Microsoft.Build.Logging; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -26,8 +26,14 @@ public async Task AnalyzerRuntimeAndTransitiveEdgesShareOneCompilerToolBuild(str { File.Copy(Path.Combine(repository, "global.json"), Path.Combine(root, "global.json")); foreach (string suffix in new[] { "props", "targets" }) - File.WriteAllText(Path.Combine(root, "Directory.Build." + suffix), - ""); + { + File.WriteAllText( + Path.Combine(root, "Directory.Build." + suffix), + "" + ); + } WriteProject(root, "Tool", """ true @@ -62,35 +68,62 @@ public async Task AnalyzerRuntimeAndTransitiveEdgesShareOneCompilerToolBuild(str for (int run = 0; run < 3; run++) { if (run == 2) + { File.AppendAllText(Path.Combine(root, "Tool", "Tool.cs"), "\npublic sealed class ChangedToolMarker { }\n"); + } string binlog = Path.Combine(root, run + ".binlog"); - await ToolchainEnvironment.RunAsync(dotnet, - ["build", "Root/Root.csproj", "--nologo", "-m:4", "-nodeReuse:false", "-c", configuration, - "-p:ArtifactsPath=" + Path.Combine(root, "managed"), "-p:InnoNativeTarget=fixture-target", "-bl:" + binlog], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + await ToolchainEnvironment.RunAsync( + dotnet, + [ + "build", + "Root/Root.csproj", + "--nologo", + "-m:4", + "-nodeReuse:false", + "-c", + configuration, + "-p:ArtifactsPath=" + Path.Combine(root, "managed"), + "-p:InnoNativeTarget=fixture-target", + "-bl:" + binlog + ], + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); int compilations = 0; var identities = new HashSet(StringComparer.Ordinal); var events = new BinaryLogReplayEventSource(); events.ProjectStarted += ( _, project - ) => { + ) => + { if (Path.GetFileName(project.ProjectFile) != "Tool.csproj" || !string.IsNullOrEmpty(project.TargetNames)) + { return; + } Assert.NotNull(project.GlobalProperties); Assert.DoesNotContain("InnoNativeTarget", project.GlobalProperties!.Keys); Assert.DoesNotContain("BuildProjectReferences", project.GlobalProperties.Keys); Assert.DoesNotContain("InnoTaskBootstrapOwner", project.GlobalProperties.Keys); Assert.DoesNotContain("BuildingInsideVisualStudio", project.GlobalProperties.Keys); - identities.Add(string.Join(";", project.GlobalProperties.OrderBy(static pair => pair.Key) - .Select(static pair => pair.Key + "=" + pair.Value))); + identities.Add( + string.Join( + ";", + project.GlobalProperties.OrderBy(static pair => pair.Key) + .Select(static pair => pair.Key + "=" + pair.Value) + ) + ); }; events.TaskStarted += ( _, task - ) => { + ) => + { if (task.TaskName == "Csc" && Path.GetFileName(task.ProjectFile) == "Tool.csproj") + { compilations++; + } }; events.Replay(binlog); Assert.Single(identities); diff --git a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs index 80b278f25..4450cfb0d 100644 --- a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs @@ -5,11 +5,11 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Xunit; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -22,28 +22,55 @@ public async Task DirectAppHostUsesItsLoadedRuntimeBeforeAnUnrelatedPath() string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", executable)); Assert.True(File.Exists(host)); // Process claims belong to the temporary owner, not the verified assembly deployment. - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoSdkHostFixtures")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoSdkHostFixtures") + ); string project = Path.Combine(owner.directory, "SdkHostProbe.csproj"); - Type[] references = [typeof(StandardBuildEnvironment), typeof(BuildCompositionContext), typeof(BuildTargetId)]; + Type[] references = [typeof(StandardBuildEnvironment), typeof(BuildCompositionContext), typeof(BuildTargetID)]; var items = new XElement("ItemGroup"); foreach (Type reference in references) - items.Add(new XElement("Reference", new XAttribute("Include", reference.Assembly.GetName().Name!), - new XElement("HintPath", reference.Assembly.Location))); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("OutputType", "Exe"), - new XElement("ImplicitUsings", "disable"), new XElement("UseAppHost", "true")), items)).Save(project); + { + items.Add( + new XElement( + "Reference", + new XAttribute("Include", reference.Assembly.GetName().Name!), + new XElement("HintPath", reference.Assembly.Location) + ) + ); + } + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("OutputType", "Exe"), + new XElement("ImplicitUsings", "disable"), + new XElement("UseAppHost", "true") + ), + items + ) + ).Save(project); await File.WriteAllTextAsync(Path.Combine(owner.directory, "Program.cs"), """ using System; using Inno.Build; using Inno.Build.Distribution.Standard; - Console.Write(StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("sdk-probe")).dotnetHost); + Console.Write(StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID("sdk-probe")).dotnetHost); """); using var buildOutput = new StringWriter(); using var buildErrors = new StringWriter(); try { - await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeReuse:false"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(host), buildOutput, buildErrors); + await ToolchainEnvironment.RunAsync( + host, + ["build", project, "-nologo", "-nodeReuse:false"], + owner.directory, + DotNetSdkEnvironment.Create(host), + buildOutput, + buildErrors, + CancellationToken.None + ); } catch (InvalidOperationException failure) { @@ -51,7 +78,9 @@ await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeRe } string output = Path.Combine(owner.directory, "bin", "Debug", "net10.0"); foreach (string dependency in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.dll")) + { File.Copy(dependency, Path.Combine(output, Path.GetFileName(dependency)), overwrite: true); + } var environment = new Dictionary { ["DOTNET_HOST_PATH"] = null, @@ -59,8 +88,13 @@ await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeRe ["PATH"] = owner.directory }; string appHost = Path.Combine(output, OperatingSystem.IsWindows() ? "SdkHostProbe.exe" : "SdkHostProbe"); - string selected = await ToolchainEnvironment.CaptureOutputAsync(appHost, [], owner.directory, - CancellationToken.None, environment); + string selected = await ToolchainEnvironment.CaptureOutputAsync( + appHost, + [], + owner.directory, + CancellationToken.None, + environment + ); Assert.Equal(host, selected.Trim()); } } diff --git a/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs index bc5f11af1..36aeb127b 100644 --- a/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs @@ -3,9 +3,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -23,32 +23,47 @@ bool designTime string root = TestRepository.GetRoot(typeof(DevelopmentEntryBuildTests).Assembly); string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - string output = await ToolchainEnvironment.CaptureOutputAsync(dotnet, + string output = await ToolchainEnvironment.CaptureOutputAsync( + dotnet, [ - "msbuild", "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", "-nologo", - "-p:BuildProjectReferences=false", "-p:OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration=true", + "msbuild", + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + "-nologo", + "-p:BuildProjectReferences=false", + "-p:OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration=true", "-p:BuildingInsideVisualStudio=true", "-p:NETCoreSdkRuntimeIdentifier=" + sdkHost, "-p:DesignTimeBuild=" + designTime.ToString().ToLowerInvariant(), "-getProperty:BuildProjectReferences,BuildingInsideVisualStudio,OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration", "-getItem:ProjectReference" ], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); Assert.Equal(designTime ? "false" : "true", properties.GetProperty("BuildProjectReferences").GetString()); Assert.Equal(designTime ? "true" : "false", properties.GetProperty("BuildingInsideVisualStudio").GetString()); Assert.Equal("false", properties.GetProperty("OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration").GetString()); - JsonElement[] references = document.RootElement.GetProperty("Items").GetProperty("ProjectReference") - .EnumerateArray().ToArray(); - JsonElement product = Assert.Single(references.Where(reference => reference.GetProperty("Filename").GetString()! - .StartsWith("Inno.Editor.", StringComparison.Ordinal))); - Assert.Equal(sdkHost == "win-x64" ? "Inno.Editor.WindowsX64" : "Inno.Editor.MacOSArm64", - product.GetProperty("Filename").GetString()); + JsonElement[] references = document.RootElement.GetProperty("Items") + .GetProperty("ProjectReference") + .EnumerateArray() + .ToArray(); + JsonElement product = Assert.Single( + references.Where(reference => reference.GetProperty("Filename") + .GetString()! + .StartsWith("Inno.Editor.", StringComparison.Ordinal)) + ); + Assert.Equal( + sdkHost == "win-x64" ? "Inno.Editor.WindowsX64" : "Inno.Editor.MacOSArm64", + product.GetProperty("Filename").GetString() + ); foreach (JsonElement reference in references) { string declarations = reference.TryGetProperty("AdditionalProperties", out JsonElement value) - ? value.GetString() ?? string.Empty : string.Empty; + ? value.GetString() ?? string.Empty + : string.Empty; Assert.Equal(!designTime, declarations.Split(';').Contains("BuildProjectReferences=true", StringComparer.Ordinal)); Assert.Equal(!designTime, declarations.Split(';').Contains("BuildingInsideVisualStudio=false", StringComparer.Ordinal)); } diff --git a/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs b/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs index 3a6271115..b9754e94b 100644 --- a/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs @@ -3,8 +3,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Integration.Tests; @@ -32,19 +32,29 @@ public async Task SelectedSdkIgnoresAnInvokingBuildsSdkIdentityAndPreservesItsNa try { string project = Path.Combine(root, "Sdk.csproj"); - await File.WriteAllTextAsync(project, - "net10.0"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, + await File.WriteAllTextAsync( + project, + "net10.0" + ); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, ["msbuild", project, "-nologo", "-nodeReuse:false", "-getProperty:TargetFramework"], - root, CancellationToken.None, selected); + root, + CancellationToken.None, + selected + ); Assert.Equal("net10.0", output.Trim()); string resolvedHost = ToolchainEnvironment.ResolveExecutable(host); string relativeHost = Path.GetRelativePath(Environment.CurrentDirectory, resolvedHost); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(relativeHost, project); Assert.Equal(resolvedHost, sdk.hostPath); - string sdkVersion = await ToolchainEnvironment.CaptureOutputAsync(sdk.hostPath, - [sdk.cliPath, "--version"], root, CancellationToken.None, - DotNetSdkEnvironment.Create(sdk.hostPath)); + string sdkVersion = await ToolchainEnvironment.CaptureOutputAsync( + sdk.hostPath, + [sdk.cliPath, "--version"], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); Assert.Equal(sdk.sdkIdentity, sdkVersion.Trim()); Assert.Equal(parent, Environment.GetEnvironmentVariable("MSBuildSDKsPath")); } diff --git a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs index c7290a9f1..cf0999923 100644 --- a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs @@ -29,14 +29,24 @@ string nativeFileName string projectRoot = Path.Combine(m_root, new string('p', 70), new string('p', 70), "PlayerLink"); Directory.CreateDirectory(projectRoot); string project = Path.Combine(projectRoot, "Player.csproj"); - File.Copy(Path.Combine(engine, "platforms", platform, "build", "Inno.Build." + platform, - "Templates", platform + "Player.project.xml"), project); + File.Copy( + Path.Combine( + engine, + "platforms", + platform, + "build", + "Inno.Build." + platform, + "Templates", + platform + "Player.project.xml" + ), + project + ); File.Copy(Path.Combine(engine, "global.json"), Path.Combine(m_root, "global.json")); File.WriteAllText(Path.Combine(projectRoot, "Program.cs"), "using System; Console.WriteLine(\"Published\");"); File.WriteAllText(Path.Combine(projectRoot, "PlayerDeploymentDefinition.g.cs"), "// The fixture has no game registrations."); string code = Path.Combine(m_root, "Code"); Directory.CreateDirectory(code); - string sourceAssembly = typeof(ManagedDeploymentId).Assembly.Location; + string sourceAssembly = typeof(ManagedDeploymentID).Assembly.Location; File.Copy(sourceAssembly, Path.Combine(code, Path.GetFileName(sourceAssembly))); string nativeRelative = Path.Combine("native", "fixture", "target", nativeFileName); string nativeInput = Path.Combine(projectRoot, nativeRelative); @@ -45,21 +55,32 @@ string nativeFileName string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); IToolchainWorkspaceProvider workspaces = OperatingSystem.IsWindows() - ? new WindowsToolchainWorkspaceProvider() : new PhysicalToolchainWorkspaceProvider(); - CoreClrDeploymentCompiler compiler = new(host, [RuntimeInformation.RuntimeIdentifier], workspaces); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); + ? new WindowsToolchainWorkspaceProvider() + : new PhysicalToolchainWorkspaceProvider(); + var compiler = new CoreClrDeploymentCompiler(host, [RuntimeInformation.RuntimeIdentifier], workspaces); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); DotNetSdkDescriptor selectedSdk = await DotNetSdkResolver.ResolveAsync(host, project, timeout.Token); XDocument definition = XDocument.Load(project); - definition.Root!.Add(new XElement("Target", - new XAttribute("Name", "VerifySelectedSdk"), - new XAttribute("BeforeTargets", "PrepareForBuild"), - new XElement("Error", - new XAttribute("Condition", $"'$(NETCoreSdkVersion)' != '{selectedSdk.sdkIdentity}'"), - new XAttribute("Text", "Publication changed the project-selected SDK.")))); + definition.Root!.Add( + new XElement( + "Target", + new XAttribute("Name", "VerifySelectedSdk"), + new XAttribute("BeforeTargets", "PrepareForBuild"), + new XElement( + "Error", + new XAttribute("Condition", $"'$(NETCoreSdkVersion)' != '{selectedSdk.sdkIdentity}'"), + new XAttribute("Text", "Publication changed the project-selected SDK.") + ) + ) + ); definition.Save(project); - string evaluated = await ToolchainEnvironment.CaptureOutputAsync(selectedSdk.hostPath, + string evaluated = await ToolchainEnvironment.CaptureOutputAsync( + selectedSdk.hostPath, [selectedSdk.cliPath, "msbuild", project, "-getItem:Content", "-nologo"], - projectRoot, timeout.Token, DotNetSdkEnvironment.Create(selectedSdk.hostPath)); + projectRoot, + timeout.Token, + DotNetSdkEnvironment.Create(selectedSdk.hostPath) + ); using (JsonDocument items = JsonDocument.Parse(evaluated)) { JsonElement content = Assert.Single(items.RootElement.GetProperty("Items").GetProperty("Content").EnumerateArray()); @@ -69,14 +90,22 @@ string nativeFileName ManagedDeploymentResult result; try { - result = await compiler.CompileAsync(new ManagedDeploymentRequest( - project, RuntimeInformation.RuntimeIdentifier, code, output, Path.Combine(m_root, "Logs")), timeout.Token); + result = await compiler.CompileAsync( + new ManagedDeploymentRequest( + project, + RuntimeInformation.RuntimeIdentifier, + code, + output, + Path.Combine(m_root, "Logs") + ), + timeout.Token + ); } catch (InvalidOperationException exception) { string[] observed = Directory.Exists(output) - ? Directory.GetFiles(output, "*", SearchOption.AllDirectories) - : []; + ? Directory.GetFiles(output, "*", SearchOption.AllDirectories) + : []; string layout = string.Join(", ", Array.ConvertAll(observed, file => Path.GetRelativePath(output, file))); throw new InvalidOperationException($"Publication output '{output}' contained [{layout}].", exception); } @@ -84,10 +113,22 @@ string nativeFileName Assert.Contains(nativeRelative, result.files); Assert.Equal(File.ReadAllBytes(nativeInput), File.ReadAllBytes(deployed)); // PublishDir is also supplied by external SDK callers without a trailing separator. - await ToolchainEnvironment.RunAsync(selectedSdk.hostPath, - [selectedSdk.cliPath, "msbuild", project, "-target:ValidateNativePublicationOutput", - "-p:PublishDir=" + output, "-nologo", "-m:1", "-nodeReuse:false"], - projectRoot, timeout.Token, DotNetSdkEnvironment.Create(selectedSdk.hostPath)); + await ToolchainEnvironment.RunAsync( + selectedSdk.hostPath, + [ + selectedSdk.cliPath, + "msbuild", + project, + "-target:ValidateNativePublicationOutput", + "-p:PublishDir=" + output, + "-nologo", + "-m:1", + "-nodeReuse:false" + ], + projectRoot, + timeout.Token, + DotNetSdkEnvironment.Create(selectedSdk.hostPath) + ); string[] executionPaths = File.ReadAllLines(Path.Combine(m_root, "Logs", "managed-working-directory.txt")); Assert.Equal(projectRoot, executionPaths[0]); if (OperatingSystem.IsWindows()) @@ -98,8 +139,16 @@ await ToolchainEnvironment.RunAsync(selectedSdk.hostPath, File.Delete(nativeInput); InvalidOperationException failure = await Assert.ThrowsAsync(async () => - await compiler.CompileAsync(new ManagedDeploymentRequest(project, RuntimeInformation.RuntimeIdentifier, - code, Path.Combine(m_root, "Rejected"), Path.Combine(m_root, "RejectedLogs")), timeout.Token)); + await compiler.CompileAsync( + new ManagedDeploymentRequest( + project, + RuntimeInformation.RuntimeIdentifier, + code, + Path.Combine(m_root, "Rejected"), + Path.Combine(m_root, "RejectedLogs") + ), + timeout.Token + )); Assert.Contains("explicitly deployed native runtime closure", failure.Message); Assert.True(File.Exists(deployed)); } @@ -107,6 +156,8 @@ await compiler.CompileAsync(new ManagedDeploymentRequest(project, RuntimeInforma public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs index df077039e..81f7471e1 100644 --- a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -28,16 +28,27 @@ public async Task CompilerToolsKeepTheirSdkOutputOwnerWhenGivenAnExplicitRuntime { string root = TestRepository.GetRoot(typeof(GeneratorRestoreScopeTests).Assembly); string project = Path.Combine(root, relative); - using Process process = new() { StartInfo = new ProcessStartInfo("dotnet") + using var process = new Process() { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true - } }; + StartInfo = new ProcessStartInfo("dotnet") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; foreach (string argument in new[] { - "msbuild", project, "-getProperty:BaseIntermediateOutputPath,IsRoslynComponent,RuntimeIdentifier", - "-p:InnoNativeTarget=windows-x64", "-p:RuntimeIdentifier=win-x64", "-nodeReuse:false" - }) + "msbuild", + project, + "-getProperty:BaseIntermediateOutputPath,IsRoslynComponent,RuntimeIdentifier", + "-p:InnoNativeTarget=windows-x64", + "-p:RuntimeIdentifier=win-x64", + "-nodeReuse:false" + }) { process.StartInfo.ArgumentList.Add(argument); + } Assert.True(process.Start()); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs index d5abe385a..64503d34e 100644 --- a/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Security; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -25,15 +25,30 @@ public async Task RuntimeDiscoveryReceivesPrivateDependenciesWithoutExposingThei string artifacts = Path.Combine(root, "managed"); try { - string extension = WriteProject(root, "Inno.Fixture.Extension", string.Empty, - "namespace Inno.Fixture.Extension; public sealed class Marker { }"); - string library = WriteProject(root, "Inno.Fixture.Host", + string extension = WriteProject( + root, + "Inno.Fixture.Extension", + string.Empty, + "namespace Inno.Fixture.Extension; public sealed class Marker { }" + ); + string library = WriteProject( + root, + "Inno.Fixture.Host", $"{exposeClosure.ToString().ToLowerInvariant()}" + $"", - "namespace Inno.Fixture.Host; public sealed class Marker { }"); - string adapter = Path.Combine(engine, "backends", "DotNet", "runtime", "Inno.Adapter.Modules.DotNet", - "Inno.Adapter.Modules.DotNet.csproj"); - string application = WriteProject(root, "Host", + "namespace Inno.Fixture.Host; public sealed class Marker { }" + ); + string adapter = Path.Combine( + engine, + "backends", + "DotNet", + "runtime", + "Inno.Adapter.Modules.DotNet", + "Inno.Adapter.Modules.DotNet.csproj" + ); + string application = WriteProject( + root, + "Host", "Exe" + $"" + $"", @@ -48,43 +63,90 @@ private static int Main() return source.GetAssemblies().Any(assembly => assembly.GetName().Name == "Inno.Fixture.Extension") ? 0 : 13; } } - """); + """ + ); string[] properties = ["-p:ArtifactsPath=" + artifacts, "-p:UseSharedCompilation=false"]; - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, ["build", application, "-c", "Release", "--disable-build-servers", "-m:1", "-nr:false", ..properties], - root, CancellationToken.None, DotNetSdkEnvironment.Create(dotnet)); - string executable = (await ToolchainEnvironment.CaptureOutputAsync(dotnet, - ["msbuild", application, "-nologo", "-m:1", "-nr:false", "-p:Configuration=Release", - "-getProperty:TargetPath", ..properties], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet))).Trim(); + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + ); + string executable = (await ToolchainEnvironment.CaptureOutputAsync( + dotnet, + [ + "msbuild", + application, + "-nologo", + "-m:1", + "-nr:false", + "-p:Configuration=Release", + "-getProperty:TargetPath", + ..properties + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )).Trim(); string output = Path.GetDirectoryName(executable)!; Assert.Equal(exposeClosure, File.Exists(Path.Combine(output, "Inno.Fixture.Extension.dll"))); Assert.Equal(exposeClosure, File.Exists(Path.Combine(output, "Inno.Fixture.Host.deps.json"))); if (exposeClosure) - await ToolchainEnvironment.RunAsync(dotnet, [executable], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet)); + { + await ToolchainEnvironment.RunAsync( + dotnet, + [executable], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + ); + } else { InvalidOperationException unavailable = await Assert.ThrowsAsync(() => - ToolchainEnvironment.RunAsync(dotnet, [executable], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet))); + ToolchainEnvironment.RunAsync( + dotnet, + [executable], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )); Assert.EndsWith("exit code 13.", unavailable.Message); } - File.WriteAllText(Path.Combine(Path.GetDirectoryName(application)!, "ForbiddenCompile.cs"), - "internal sealed class ForbiddenCompile { private readonly Inno.Fixture.Extension.Marker m_value = new(); }"); + File.WriteAllText( + Path.Combine(Path.GetDirectoryName(application)!, "ForbiddenCompile.cs"), + "internal sealed class ForbiddenCompile { private readonly Inno.Fixture.Extension.Marker m_value = new(); }" + ); string compilerLog = Path.Combine(root, "negative-compile.log"); await Assert.ThrowsAsync(() => - ToolchainEnvironment.RunAsync(dotnet, - ["build", application, "-c", "Release", "--no-restore", "--disable-build-servers", "-m:1", "-nr:false", - "-flp:logfile=" + compilerLog + ";verbosity=normal", ..properties], - root, CancellationToken.None, DotNetSdkEnvironment.Create(dotnet))); + ToolchainEnvironment.RunAsync( + dotnet, + [ + "build", + application, + "-c", + "Release", + "--no-restore", + "--disable-build-servers", + "-m:1", + "-nr:false", + "-flp:logfile=" + compilerLog + ";verbosity=normal", + ..properties + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )); Assert.Contains("CS0234", File.ReadAllText(compilerLog)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs index b09c63312..49e2d54b4 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs @@ -1,12 +1,15 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -18,17 +21,26 @@ public ManagedBuildInputSnapshotTests() { Directory.CreateDirectory(m_root); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), "fixture"); - Write("Shared/Shared.csproj", "net10.0"); + Write( + "Shared/Shared.csproj", + "net10.0" + ); Write("Shared/Shared.cs", "public sealed class Shared { }"); - Write("App/App.csproj", "net10.0" + Write( + "App/App.csproj", + "net10.0" + "disable" + "" - + ""); + + "" + ); Write("App/Options.props", "FIXTURE"); Write("App/App.cs", "public sealed class App { }"); Write("App/data.txt", "first"); Write("App/input.txt", "first"); - Write("Tool/Tool.csproj", "net10.0"); + Write( + "Tool/Tool.csproj", + "net10.0" + ); Write("Tool/Tool.cs", "public sealed class Tool { }"); } @@ -38,19 +50,39 @@ public ManagedBuildInputSnapshotTests() public async Task FrameworkSelectionUsesTheSdkAndRestoredTargetSemantics(string framework) { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("net10.0", - "" + framework + "", StringComparison.Ordinal)); + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "net10.0", + "" + framework + "", + StringComparison.Ordinal + ) + ); string shared = Path.Combine(m_root, "Shared", "Shared.csproj"); - File.WriteAllText(shared, File.ReadAllText(shared).Replace("net10.0", - "" + framework + "", StringComparison.Ordinal)); + File.WriteAllText( + shared, + File.ReadAllText(shared).Replace( + "net10.0", + "" + framework + "", + StringComparison.Ordinal + ) + ); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); Assert.NotEmpty(snapshot.fingerprint); await snapshot.VerifyAsync(); @@ -75,12 +107,20 @@ public async Task PackageDeclarationsBelongToFrozenCompilationInputs() string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project, cancellation.Token); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "restore", project, "--disable-build-servers", "-v:quiet"], - m_root, cancellation.Token, DotNetSdkEnvironment.Create(sdk.hostPath)); + m_root, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }, cancellation.Token); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" }, + cancellation.Token + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(cancellation.Token); string source = Path.Combine(m_root, "App", "Options.props"); string frozen = Path.Combine(execution.engineRoot, "App", "Options.props"); @@ -94,31 +134,48 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, public async Task RuntimeInputEvaluationDoesNotShareOrdinaryRestoreOutputs() { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("", - "", StringComparison.Ordinal)); - Write("Tool/Tool.csproj", "net10.0" + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "", + "", + StringComparison.Ordinal + ) + ); + Write( + "Tool/Tool.csproj", + "net10.0" + "disable" - + ""); + + "" + ); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await RestoreOrdinary(); + await RestoreOrdinaryAsync(); string assets = Path.Combine(m_root, "App", "obj", "project.assets.json"); byte[] ordinary = File.ReadAllBytes(assets); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, + new NativeBuildContext(m_root, "release"), + sdk, + project, new Dictionary { ["Configuration"] = "Release", ["RuntimeIdentifier"] = RuntimeInformation.RuntimeIdentifier - }); + } + ); Assert.Equal(ordinary, File.ReadAllBytes(assets)); - await Task.WhenAll(RestoreOrdinary(), snapshot.VerifyAsync().AsTask()); + await Task.WhenAll(RestoreOrdinaryAsync(), snapshot.VerifyAsync().AsTask()); Assert.Equal(ordinary, File.ReadAllBytes(assets)); Assert.False(Directory.Exists(Path.Combine(m_root, "App", "bin"))); - Task RestoreOrdinary() => ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + Task RestoreOrdinaryAsync() + => ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); } [Fact] @@ -128,30 +185,56 @@ public async Task CheckoutAliasPreservesOwnedSourcesWhileSharingPhysicalInputRea try { if (OperatingSystem.IsWindows()) - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + m_root + "' | Out-Null"], - m_root, CancellationToken.None); + { + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + m_root + "' | Out-Null" + ], + m_root, + CancellationToken.None + ); + } else + { Directory.CreateSymbolicLink(alias, m_root); + } string project = Path.Combine(alias, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - alias, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + alias, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); var context = new NativeBuildContext(alias, "release"); - ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync(context, sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( + context, + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(); Assert.Contains("class App", File.ReadAllText(Path.Combine(execution.engineRoot, "App", "App.cs")), StringComparison.Ordinal); - Assert.Contains("class Shared", File.ReadAllText(Path.Combine(execution.engineRoot, "Shared", "Shared.cs")), StringComparison.Ordinal); + Assert.Contains( + "class Shared", + File.ReadAllText(Path.Combine(execution.engineRoot, "Shared", "Shared.cs")), + StringComparison.Ordinal + ); await snapshot.VerifyAsync(); await execution.VerifyAsync(); } finally { if (Directory.Exists(alias)) + { Directory.Delete(alias, recursive: false); + } } } @@ -160,34 +243,71 @@ public async Task FixedExecutionCompilesPlannedBytesWhenTheOriginalSourceChanges { Write("Vendor/bin/tool.dat", "owned vendor tool"); string fixture = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(fixture, File.ReadAllText(fixture).Replace("", - "", StringComparison.Ordinal)); + File.WriteAllText( + fixture, + File.ReadAllText(fixture).Replace( + "", + "
", + StringComparison.Ordinal + ) + ); string project = Path.Combine(m_root, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); var context = new NativeBuildContext(m_root, "release"); - ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync(context, sdk, project, - new System.Collections.Generic.Dictionary { ["Configuration"] = "Release" }); + ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( + context, + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(); Assert.Equal("owned vendor tool", File.ReadAllText(Path.Combine(execution.engineRoot, "Vendor", "bin", "tool.dat"))); string original = Path.Combine(m_root, "App", "App.cs"); File.WriteAllText(original, "public sealed class Changed { }"); - Assert.Contains("class App", File.ReadAllText(Path.Combine(Path.GetDirectoryName(execution.project)!, "App.cs")), StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "build", execution.project, "--configuration", "Release", "--disable-build-servers", - "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], execution.engineRoot, CancellationToken.None, - DotNetSdkEnvironment.Create(sdk.hostPath)); + Assert.Contains( + "class App", + File.ReadAllText(Path.Combine(Path.GetDirectoryName(execution.project)!, "App.cs")), + StringComparison.Ordinal + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "build", + execution.project, + "--configuration", + "Release", + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet" + ], + execution.engineRoot, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); File.WriteAllText(original, "public sealed class App { }"); await snapshot.VerifyAsync(); await execution.VerifyAsync(); string output = Path.Combine(Path.GetDirectoryName(execution.project)!, "bin", "Release", "net10.0", "App.dll"); using FileStream stream = File.OpenRead(output); - using var image = new System.Reflection.PortableExecutable.PEReader(stream); - System.Reflection.Metadata.MetadataReader metadata = System.Reflection.Metadata.PEReaderExtensions.GetMetadataReader(image); - string[] names = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(metadata.TypeDefinitions, - handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name))); + using var image = new PEReader(stream); + MetadataReader metadata = PEReaderExtensions.GetMetadataReader(image); + string[] names = Enumerable.ToArray( + Enumerable.Select( + metadata.TypeDefinitions, + handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) + ) + ); Assert.Contains("App", names); Assert.DoesNotContain("Changed", names); } @@ -198,26 +318,48 @@ public async Task SelectedSdkGraphDetectsSameLengthSourceResourceImportAndNewFil string project = Path.Combine(m_root, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", Path.Combine(m_root, "Tool", "Tool.csproj"), "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - File.WriteAllText(project, File.ReadAllText(project).Replace("", - "", StringComparison.Ordinal)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", Path.Combine(m_root, "Tool", "Tool.csproj"), "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "", + "", + StringComparison.Ordinal + ) + ); var properties = new Dictionary { ["Configuration"] = "Release" }; - ManagedBuildInputSnapshot original = await Capture(sdk, project, properties); + ManagedBuildInputSnapshot original = await CaptureAsync(sdk, project, properties); await original.VerifyAsync(); - ManagedBuildInputSnapshot repeated = await Capture(sdk, project, properties); + ManagedBuildInputSnapshot repeated = await CaptureAsync(sdk, project, properties); Assert.Equal(original.fingerprint, repeated.fingerprint); foreach (string path in new[] { "Shared/Shared.cs", "App/data.txt", "App/Options.props", "Tool/Tool.cs" }) { string file = Path.Combine(m_root, path); string previous = File.ReadAllText(file); DateTime timestamp = File.GetLastWriteTimeUtc(file); - File.WriteAllText(file, previous.Replace("first", "other", StringComparison.Ordinal) - .Replace("Shared", "Change", StringComparison.Ordinal).Replace("FIXTURE", "CHANGED", StringComparison.Ordinal)); + File.WriteAllText( + file, + previous.Replace("first", "other", StringComparison.Ordinal) + .Replace("Shared", "Change", StringComparison.Ordinal) + .Replace("FIXTURE", "CHANGED", StringComparison.Ordinal) + ); if (path == "Tool/Tool.cs") + { File.WriteAllText(file, previous.Replace("Tool", "Next", StringComparison.Ordinal)); + } File.SetLastWriteTimeUtc(file, timestamp); await Assert.ThrowsAsync(() => original.VerifyAsync().AsTask()); File.WriteAllText(file, previous); @@ -226,14 +368,16 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", Path. Write("App/Added.cs", "public sealed class Added { }"); await Assert.ThrowsAsync(() => original.VerifyAsync().AsTask()); Assert.False(Directory.Exists(Path.Combine(m_root, "App", "bin"))); - Assert.All(Directory.EnumerateDirectories(Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs")), - static directory => Assert.Contains(Path.GetFileName(directory), new[] { "evaluators", "requests" })); + Assert.All( + Directory.EnumerateDirectories(Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs")), + static directory => Assert.Contains(Path.GetFileName(directory), new[] { "evaluators", "requests" }) + ); string requests = Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs", "requests"); Assert.Empty(ProcessOwnedDirectory.ReadClaims(requests)); Assert.Empty(Directory.EnumerateDirectories(requests)); Assert.Single(Directory.EnumerateDirectories(Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs", "evaluators"))); - Task Capture( + Task CaptureAsync( DotNetSdkDescriptor selected, string entry, IReadOnlyDictionary globals @@ -251,7 +395,10 @@ IReadOnlyDictionary globals public async Task SdkPreparedSymbolsParticipateInTheFrozenInputIdentity() { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("", "", StringComparison.Ordinal)); + File.WriteAllText( + project, + File.ReadAllText(project).Replace("", "", StringComparison.Ordinal) + ); Write("App/Symbols.targets", """ @@ -269,11 +416,19 @@ public async Task SdkPreparedSymbolsParticipateInTheFrozenInputIdentity() Environment.SetEnvironmentVariable("INNO_TEST_COMPILER_SYMBOL", "FIRST_SYMBOL"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); await snapshot.VerifyAsync(); Environment.SetEnvironmentVariable("INNO_TEST_COMPILER_SYMBOL", "SECOND_SYMBOL"); InvalidOperationException failure = await Assert.ThrowsAsync(() => snapshot.VerifyAsync().AsTask()); diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs index cb56e13b2..addd6305b 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs @@ -1,6 +1,3 @@ -using Inno.Build.Toolchains; -using Inno.Core.IO; -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.IO; @@ -9,6 +6,9 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Build.Toolchains; +using Inno.Core.IO; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,8 +21,8 @@ public async Task ProductOutputOwnersRemainStableAcrossCheckoutBindings() string owner = Path.Combine(Path.GetTempPath(), "InnoManagedOutputTests"); string fixture = PathBoundary.Resolve(owner, Guid.NewGuid().ToString("N")); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var outputs = new List>(); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + List> outputs = []; Directory.CreateDirectory(fixture); try { @@ -31,7 +31,9 @@ public async Task ProductOutputOwnersRemainStableAcrossCheckoutBindings() string checkoutRoot = Path.Combine(fixture, checkout); Directory.CreateDirectory(Path.Combine(checkoutRoot, "build", "msbuild")); foreach (string source in new[] { "global.json", "Directory.Build.props", "build/msbuild/Inno.Packages.props" }) + { File.Copy(Path.Combine(root, source), Path.Combine(checkoutRoot, source)); + } await File.WriteAllTextAsync(Path.Combine(checkoutRoot, "Directory.Build.targets"), ""); string productProperties = Path.Combine(checkoutRoot, "Product.props"); await File.WriteAllTextAsync(productProperties, ""); @@ -42,12 +44,14 @@ await File.WriteAllTextAsync(project, """ """); await File.WriteAllTextAsync(Path.Combine(checkoutRoot, "Shared.cs"), "public sealed class Shared { }"); - var properties = new List - { - "-p:Configuration=Debug", "-p:InnoNativeTarget=test-target", "-p:InnoToolTarget=test-host", + List properties = + [ + "-p:Configuration=Debug", + "-p:InnoNativeTarget=test-target", + "-p:InnoToolTarget=test-host", "-p:ArtifactsPath=" + Path.Combine(checkoutRoot, "outputs"), "-p:InnoProductBuildProperties=" + productProperties - }; + ]; Dictionary evaluated = await EvaluateAsync(host, project, properties); await RunAsync(host, checkoutRoot, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", .. properties]); Assert.True(File.Exists(evaluated["TargetPath"])); @@ -95,15 +99,19 @@ await File.WriteAllTextAsync(project, """ """); await File.WriteAllTextAsync(Path.Combine(fixture, "Shared.cs"), "public sealed class Shared { }"); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var common = new List { $"-p:Configuration={configuration}" }; + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + List common = [$"-p:Configuration={configuration}"]; if (artifacts) + { common.Add($"-p:ArtifactsPath={Path.Combine(fixture, "outputs")}"); + } Dictionary neutral = await EvaluateAsync(host, project, common); var productArguments = new List(common) { "-p:InnoNativeTarget=test-target" }; Dictionary product = await EvaluateAsync(host, project, productArguments); foreach (string property in new[] { "ProjectAssetsFile", "IntermediateOutputPath", "TargetPath" }) + { Assert.NotEqual(neutral[property], product[property]); + } var compileArguments = new List(productArguments) { @@ -151,7 +159,9 @@ await File.WriteAllTextAsync(project, """ Assert.NotEqual(product["TargetPath"], rid["TargetPath"]); foreach (List request in new[] { common, productArguments }) + { await RunAsync(host, fixture, ["restore", project, .. request, "-v:quiet"]); + } string driver = Path.Combine(fixture, "Build.proj"); await File.WriteAllTextAsync(driver, $""" @@ -183,13 +193,18 @@ List properties ) { using var output = new StringWriter(); await RunAsync(host, Path.GetDirectoryName(project)!, [ - "msbuild", project, "-nologo", .. properties, + "msbuild", + project, + "-nologo", + .. properties, "-getProperty:ProjectAssetsFile,IntermediateOutputPath,TargetPath,RuntimeIdentifier" ], output); using JsonDocument document = JsonDocument.Parse(output.ToString()); var values = new Dictionary(StringComparer.Ordinal); foreach (JsonProperty property in document.RootElement.GetProperty("Properties").EnumerateObject()) + { values.Add(property.Name, property.Value.GetString()!); + } return values; } @@ -203,7 +218,14 @@ private static async Task RunAsync( using var error = new StringWriter(); using var captured = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( - host, arguments, directory, cancellation.Token, DotNetSdkEnvironment.Create(host), output ?? captured, error)); + host, + arguments, + directory, + DotNetSdkEnvironment.Create(host), + output ?? captured, + error, + cancellation.Token + )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output ?? captured}{Environment.NewLine}{error}"); } } diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs index 236b263d7..4c1ab7482 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs @@ -3,11 +3,12 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Testing.Source; - +using BGCS.Runtime; +using Xunit; using Inno.Build; using Inno.Build.Distribution.Standard; using Inno.Build.MacOSArm64; @@ -15,7 +16,7 @@ using Inno.Build.Toolchains; using Inno.Build.WindowsX64; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -34,74 +35,112 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection File.WriteAllText(Path.Combine(root, "Generated", "Bindings.cs"), "#error Host bindings must not be compiled for this target."); File.WriteAllText(Path.Combine(root, "Source", "api.h"), "int sample(int value);"); string config = Path.Combine(root, "bindgen.json"); - File.WriteAllText(config, JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Source/api.h" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); + File.WriteAllText( + config, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Source/api.h" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); string engine = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly); BuildHostDescriptor host = StandardBuildHosts.Capture(); PlatformTargetDescriptor[] targets = [WindowsX64BuildModule.target, MacOSArm64BuildModule.target]; - string targetId = Assert.Single(targets.Where(target => target.platform == host.system - && target.architecture == host.architecture)).id.value; + string targetID = Assert.Single( + targets.Where(target => (target.platform == host.system && target.architecture == host.architecture)) + ).id.value; IEnumerable profileDirectories = Directory.EnumerateDirectories(Path.Combine(engine, "platforms")) - .Select(platform => Path.Combine(platform, "integrations")).Where(Directory.Exists) + .Select(platform => Path.Combine(platform, "integrations")) + .Where(Directory.Exists) .SelectMany(Directory.EnumerateDirectories) - .Select(integration => Path.Combine(integration, "Bindings")).Where(Directory.Exists); - foreach (string profile in profileDirectories.SelectMany(directory => Directory.EnumerateFiles(directory, "*BindingProfile.cs"))) - { + .Select(integration => Path.Combine(integration, "Bindings")) + .Where(Directory.Exists); + foreach (string profile in profileDirectories.SelectMany( + directory => Directory.EnumerateFiles(directory, "*BindingProfile.cs") + )) { string profileInput = Path.Combine(root, Path.GetRelativePath(engine, profile)); Directory.CreateDirectory(Path.GetDirectoryName(profileInput)!); File.Copy(profile, profileInput); } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), string.Empty); string definition = Path.Combine(root, "bindings.props"); - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("InnoNativeComponentId", "fixture"), new XElement("InnoBindingConfig", "bindgen.json")))) + new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("InnoNativeComponentId", "fixture"), + new XElement("InnoBindingConfig", "bindgen.json") + ) + ) + ) .Save(definition); string sources = Path.Combine(root, "compile-sources.txt"); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", - new XElement("TargetFramework", "net10.0"), - new XElement("LangVersion", "14.0"), - new XElement("AllowUnsafeBlocks", "true"), - new XElement("ImplicitUsings", "disable"), - new XElement("EnableDefaultCompileItems", "false"), - new XElement("Nullable", "enable"), - new XElement("IsTestProject", "true"), - new XElement("BindGenGeneratedBindings", "true"), - new XElement("InnoBindingTargetId", targetId), - new XElement("InnoBindingEngineRoot", root), - new XElement("InnoBindingDefinition", definition), - new XElement("InnoBindingOutputMode", "TargetArtifacts")), - new XElement("Import", new XAttribute("Project", definition)), - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("ItemGroup", new XElement("Reference", new XAttribute("Include", "BGCS.Runtime"), - new XElement("HintPath", typeof(BGCS.Runtime.NativeModuleSession).Assembly.Location))), - new XElement("Target", new XAttribute("Name", "CaptureCompileSources"), - new XAttribute("AfterTargets", "ValidateBindGenBindings"), - new XElement("WriteLinesToFile", new XAttribute("File", sources), - new XAttribute("Lines", "@(Compile->'%(FullPath)')"), new XAttribute("Overwrite", "true"))))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("AllowUnsafeBlocks", "true"), + new XElement("ImplicitUsings", "disable"), + new XElement("EnableDefaultCompileItems", "false"), + new XElement("Nullable", "enable"), + new XElement("IsTestProject", "true"), + new XElement("BindGenGeneratedBindings", "true"), + new XElement("InnoBindingTargetId", targetID), + new XElement("InnoBindingEngineRoot", root), + new XElement("InnoBindingDefinition", definition), + new XElement("InnoBindingOutputMode", "TargetArtifacts") + ), + new XElement("Import", new XAttribute("Project", definition)), + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement( + "ItemGroup", + new XElement( + "Reference", + new XAttribute("Include", "BGCS.Runtime"), + new XElement("HintPath", typeof(NativeModuleSession).Assembly.Location) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "CaptureCompileSources"), + new XAttribute("AfterTargets", "ValidateBindGenBindings"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", sources), + new XAttribute("Lines", "@(Compile->'%(FullPath)')"), + new XAttribute("Overwrite", "true") + ) + ) + ) + ) .Save(project); - (int success, string output) = await Build(project, []); + (int success, string output) = await BuildAsync(project, []); Assert.True(success == 0, output); Assert.Equal(1, output.Split("INNO-TASK-HOST verified", StringSplitOptions.None).Length - 1); - string selected = Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs")); + string selected = Assert.Single( + File.ReadAllLines(sources) + .Where(static path => Path.GetFileName(path) == "Bindings.cs") + ); Assert.Equal(Path.Combine(root, "obj", "Release", "net10.0", "bindings", "Bindings.cs"), selected); Assert.True(File.Exists(selected), output); - string artifact = Assert.Single(Directory.GetDirectories(Path.Combine(root, "artifacts", "bindings", "fixture", targetId))); + string artifact = Assert.Single(Directory.GetDirectories(Path.Combine(root, "artifacts", "bindings", "fixture", targetID))); string publishedSource = Path.Combine(artifact, "Generated", "Bindings.cs"); Assert.Equal(File.ReadAllBytes(publishedSource), File.ReadAllBytes(selected)); Assert.True(File.Exists(Path.Combine(root, "bin", "Release", "net10.0", "Fixture.dll")), output); string selection = Path.Combine(root, "SelectedBindings.props"); - NativeBindingGenerationDescriptor.WriteSelection(selection, + NativeBindingGenerationDescriptor.WriteSelection( + selection, new Dictionary { [project] = new() @@ -113,11 +152,15 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection usesRuntimeImports = false, nativeDirectory = string.Empty } - }, new Dictionary { [project] = NativeLibraryKind.Shared }); - (int reused, string reuseOutput) = await Build(project, ["-p:InnoNativeBindingSelection=" + selection]); + }, + new Dictionary { [project] = NativeLibraryKind.Shared } + ); + (int reused, string reuseOutput) = await BuildAsync(project, ["-p:InnoNativeBindingSelection=" + selection]); Assert.True(reused == 0, reuseOutput); - Assert.Equal(selected, Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs"))); + Assert.Equal( + selected, + Assert.Single(File.ReadAllLines(sources).Where(static path => Path.GetFileName(path) == "Bindings.cs")) + ); Assert.DoesNotContain("INNO-BINDINGS-PREPARE", reuseOutput); Assert.DoesNotContain("INNO-TASK-RUNTIME", reuseOutput); @@ -127,13 +170,14 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection XDocument frozenDefinition = XDocument.Load(project); frozenDefinition.Root!.Element("PropertyGroup")!.Element("InnoBindingEngineRoot")!.Value = frozen; frozenDefinition.Save(frozenProject); - (int frozenExit, string frozenOutput) = await Build(frozenProject, ["-p:InnoNativeBindingSelection=" + selection]); + (int frozenExit, string frozenOutput) = await BuildAsync(frozenProject, ["-p:InnoNativeBindingSelection=" + selection]); Assert.True(frozenExit == 0, frozenOutput); Assert.DoesNotContain("INNO-BINDINGS-PREPARE", frozenOutput); Assert.True(File.Exists(Path.Combine(frozen, "obj", "Release", "net10.0", "bindings", "Bindings.cs"))); string staticSelection = Path.Combine(root, "StaticBindings.props"); - NativeBindingGenerationDescriptor.WriteSelection(staticSelection, + NativeBindingGenerationDescriptor.WriteSelection( + staticSelection, new Dictionary { [project] = new() @@ -145,32 +189,41 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection usesRuntimeImports = false, nativeDirectory = string.Empty } - }, new Dictionary { [project] = NativeLibraryKind.Static }); + }, + new Dictionary { [project] = NativeLibraryKind.Static } + ); string bootstrap = Path.Combine(root, "Bootstrap.cs"); - File.WriteAllText(bootstrap, "#if !INNO_STATIC_NATIVE\n#error The selected static component must omit dynamic initialization.\n#endif"); + File.WriteAllText( + bootstrap, + "#if !INNO_STATIC_NATIVE\n#error The selected static component must omit dynamic initialization.\n#endif" + ); XDocument staticProject = XDocument.Load(project); staticProject.Root!.Add(new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", bootstrap)))); staticProject.Save(project); - (int staticExit, string staticOutput) = await Build(project, ["-p:InnoNativeBindingSelection=" + staticSelection]); + (int staticExit, string staticOutput) = await BuildAsync(project, ["-p:InnoNativeBindingSelection=" + staticSelection]); Assert.True(staticExit == 0, staticOutput); staticProject.Root!.Elements("ItemGroup").Last().Remove(); staticProject.Save(project); - await VerifyTransitiveSelection(root, engine, project, selection, sources, selected); + await VerifyTransitiveSelectionAsync(root, engine, project, selection, sources, selected); - (int rejected, string failure) = await Build(project, - ["-p:InnoNativeBindingSelection=" + Path.Combine(root, "absent-selection.props")]); + (int rejected, string failure) = await BuildAsync( + project, + ["-p:InnoNativeBindingSelection=" + Path.Combine(root, "absent-selection.props")] + ); Assert.NotEqual(0, rejected); Assert.Contains("The selected native binding manifest is missing", failure); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } - private static async Task VerifyTransitiveSelection( + private static async Task VerifyTransitiveSelectionAsync( string root, string engine, string nativeProject, @@ -180,47 +233,88 @@ string selected ) { string middle = Path.Combine(root, "Consumers", "Middle", "Middle.csproj"); string host = Path.Combine(root, "Consumers", "Host", "Host.csproj"); - foreach (var entry in new[] { (path: middle, reference: nativeProject), (path: host, reference: middle) }) + foreach ((string path, string reference) entry in new[] { + (path: middle, reference: nativeProject), + (path: host, reference: middle) + }) { Directory.CreateDirectory(Path.GetDirectoryName(entry.path)!); - var document = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("IsTestProject", "true"), new XElement("EnableDefaultCompileItems", "false"), - new XElement("InnoProductReferenceProperties", "FixtureDeclared=true")), + var document = new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("IsTestProject", "true"), + new XElement("EnableDefaultCompileItems", "false"), + new XElement("InnoProductReferenceProperties", "FixtureDeclared=true") + ), new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("ItemGroup", new XElement("ProjectReference", new XAttribute("Include", entry.reference)))); + new XElement("ItemGroup", new XElement("ProjectReference", new XAttribute("Include", entry.reference))) + ); if (entry.path == host) - document.Add(new XElement("Target", new XAttribute("Name", "SelectOperationBindings"), - new XAttribute("BeforeTargets", "AssignProjectConfiguration"), - new XElement("PropertyGroup", new XElement("InnoNativeBindingSelection", selection)), - new XElement("ItemGroup", new XElement("ProjectReference", - new XElement("AdditionalProperties", "InnoNativeBindingSelection=$(InnoNativeBindingSelection)"))))); + { + document.Add( + new XElement( + "Target", + new XAttribute("Name", "SelectOperationBindings"), + new XAttribute("BeforeTargets", "AssignProjectConfiguration"), + new XElement("PropertyGroup", new XElement("InnoNativeBindingSelection", selection)), + new XElement( + "ItemGroup", + new XElement( + "ProjectReference", + new XElement("AdditionalProperties", "InnoNativeBindingSelection=$(InnoNativeBindingSelection)") + ) + ) + ) + ); + } new XDocument(document).Save(entry.path); } - (int exit, string output) = await Build(host, []); + (int exit, string output) = await BuildAsync(host, []); Assert.True(exit == 0, output); Assert.DoesNotContain("INNO-BINDINGS-PREPARE", output); Assert.DoesNotContain("INNO-TASK-RUNTIME", output); - Assert.Equal(selected, Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs"))); + Assert.Equal( + selected, + Assert.Single(File.ReadAllLines(sources).Where(static path => Path.GetFileName(path) == "Bindings.cs")) + ); } - private static async Task<(int exitCode, string output)> Build( + private static async Task<(int exitCode, string output)> BuildAsync( string project, string[] arguments ) { - string host = Path.Combine(Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(host) { - WorkingDirectory = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly), UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly), + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; // This temporary project owns its fixture component and exercises both generation and explicit selections. start.Environment.Remove("InnoNativeDependencyManifest"); - foreach (string argument in new[] { "build", project, "-c", "Release", "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:normal" } - .Concat(arguments)) + foreach (string argument in new[] + { + "build", + project, + "-c", + "Release", + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "-v:normal" + } + .Concat(arguments) + ) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs index 2347c6050..4ab8f92e0 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs @@ -25,23 +25,30 @@ public sealed class NativeBindingConfigurationTests /// /// Materializes every configured component without invoking native generation or selecting a platform SDK. /// - /// The completion of configuration validation for the declared product closure. + /// + /// The completion of configuration validation for the declared product closure. + /// [Fact] [Trait("ExternalDependency", "BGCS")] public async Task EveryDeclaredComponentConfigurationCanBeReadByTheInstalledSdk() { string root = TestRepository.GetRoot(typeof(NativeBindingConfigurationTests).Assembly); - BuildCompositionContext environment = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64")); - ProductNativeBuildPlan product = StandardBuildDistribution.Create(environment).build.ResolveNativeProduct("windows-x64", "editor").plan; - using HostServices services = new HostServicesProvider().Create(new(root, JsonSerializer.SerializeToElement(new { }))); + BuildCompositionContext environment = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID("windows-x64")); + ProductNativeBuildPlan product = StandardBuildDistribution.Create(environment).build + .ResolveNativeProduct("windows-x64", "editor").plan; + using HostServices services = new HostServicesProvider().Create( + new HostServicesRequest(root, JsonSerializer.SerializeToElement(new { })) + ); foreach (NativeComponentDescriptor owner in product.steps.Select(step => step.component) - .Where(owner => owner.bindingDefinition is not null).DistinctBy(owner => owner.nativeProject)) - { + .Where(owner => owner.bindingDefinition is not null) + .DistinctBy(owner => owner.nativeProject) + ) { string definition = Path.GetFullPath(owner.bindingDefinition!, root); XDocument document = XDocument.Load(definition); string[] configurations = document.Descendants("InnoBindingConfig") .Select(element => Path.GetFullPath(element.Value, Path.GetDirectoryName(definition)!)) - .Distinct(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .ToArray(); Assert.NotEmpty(configurations); foreach (string configuration in configurations) { diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs index ab3fe086b..37a231dc0 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -7,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,8 +21,13 @@ public async Task ANewSelectionDocumentDoesNotRecompileANeutralProject() try { foreach (string name in new[] { "Directory.Build.props", "Directory.Build.targets" }) - File.WriteAllText(Path.Combine(root, name), ""); + { + File.WriteAllText( + Path.Combine(root, name), + "" + ); + } File.WriteAllText(Path.Combine(root, "Probe.csproj"), """ net10.0disable @@ -32,11 +37,11 @@ public async Task ANewSelectionDocumentDoesNotRecompileANeutralProject() string first = Path.Combine(root, "first-selection.props"); string second = Path.Combine(root, "second-selection.props"); File.WriteAllText(first, ""); - await Build(root, first); + await BuildAsync(root, first); string assembly = Path.Combine(root, "bin", "Debug", "net10.0", "Probe.dll"); DateTime written = File.GetLastWriteTimeUtc(assembly); File.WriteAllText(second, ""); - await Build(root, second); + await BuildAsync(root, second); Assert.Equal(written, File.GetLastWriteTimeUtc(assembly)); } finally @@ -45,12 +50,14 @@ public async Task ANewSelectionDocumentDoesNotRecompileANeutralProject() } } - private static async Task Build( + private static async Task BuildAsync( string root, string selection ) { - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -59,9 +66,18 @@ string selection RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "build", "Probe.csproj", "--disable-build-servers", "--nologo", "-m:1", - "-nodeReuse:false", "-p:InnoNativeBindingSelection=" + selection }) + foreach (string argument in new[] + { + "build", + "Probe.csproj", + "--disable-build-servers", + "--nologo", + "-m:1", + "-nodeReuse:false", + "-p:InnoNativeBindingSelection=" + selection + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -73,7 +89,9 @@ string selection catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs b/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs index 836cd853f..af78c538e 100644 --- a/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Linq; @@ -6,8 +5,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,13 +21,25 @@ public async Task RuntimeConsumptionUsesAnExactPackageWithoutARepositorySourceRe { string root = TestRepository.GetRoot(typeof(NuGetBindingDependencyTests).Assembly); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, project), "-nologo", "-nodeReuse:false", "-p:DesignTimeBuild=true", - "-getItem:PackageReference,ProjectReference", "-getProperty:InnoBgcsPackageVersion"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, project), + "-nologo", + "-nodeReuse:false", + "-p:DesignTimeBuild=true", + "-getItem:PackageReference,ProjectReference", + "-getProperty:InnoBgcsPackageVersion" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement items = document.RootElement.GetProperty("Items"); - JsonElement runtime = items.GetProperty("PackageReference").EnumerateArray() + JsonElement runtime = items.GetProperty("PackageReference") + .EnumerateArray() .Single(static item => item.GetProperty("Identity").GetString() == "BGCS.Runtime"); string version = document.RootElement.GetProperty("Properties").GetProperty("InnoBgcsPackageVersion").GetString()!; Assert.Equal("[" + version + "]", runtime.GetProperty("Version").GetString()); @@ -51,36 +63,53 @@ public async Task RestoredRuntimePackageMatchesItsDeclaredVersionAndNuGetContent try { using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, "backends", "ImGui", "native", "Inno.Native.ImGui", "Inno.Native.ImGui.csproj"), - "-t:Restore", "-p:ArtifactsPath=" + workspace, - "-getProperty:ProjectAssetsFile,InnoBgcsPackageVersion", "-nologo", "-nr:false", "-v:quiet"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, "backends", "ImGui", "native", "Inno.Native.ImGui", "Inno.Native.ImGui.csproj"), + "-t:Restore", + "-p:ArtifactsPath=" + workspace, + "-getProperty:ProjectAssetsFile,InnoBgcsPackageVersion", + "-nologo", + "-nr:false", + "-v:quiet" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument evaluation = JsonDocument.Parse(output); JsonElement properties = evaluation.RootElement.GetProperty("Properties"); using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(properties.GetProperty("ProjectAssetsFile").GetString()!)); - JsonProperty runtime = assets.RootElement.GetProperty("libraries").EnumerateObject() + JsonProperty runtime = assets.RootElement.GetProperty("libraries") + .EnumerateObject() .Single(static library => library.Name.StartsWith("BGCS.Runtime/", StringComparison.Ordinal)); string version = properties.GetProperty("InnoBgcsPackageVersion").GetString()!; Assert.Equal("BGCS.Runtime/" + version, runtime.Name); string packagePath = runtime.Value.GetProperty("path").GetString()!; - string archive = assets.RootElement.GetProperty("packageFolders").EnumerateObject() + string archive = assets.RootElement.GetProperty("packageFolders") + .EnumerateObject() .Select(folder => Path.Combine(folder.Name, packagePath, "bgcs.runtime." + version + ".nupkg")) .Single(File.Exists); await using FileStream package = File.OpenRead(archive); string archiveHash = Convert.ToBase64String(await SHA512.HashDataAsync(package)); Assert.Equal(File.ReadAllText(archive + ".sha512").Trim(), archiveHash); // NuGet's content identity excludes signature metadata from the signed archive. - using JsonDocument metadata = JsonDocument.Parse(File.ReadAllBytes( - Path.Combine(Path.GetDirectoryName(archive)!, ".nupkg.metadata"))); - Assert.Equal(runtime.Value.GetProperty("sha512").GetString(), - metadata.RootElement.GetProperty("contentHash").GetString()); + using JsonDocument metadata = JsonDocument.Parse( + File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(archive)!, ".nupkg.metadata")) + ); + Assert.Equal( + runtime.Value.GetProperty("sha512").GetString(), + metadata.RootElement.GetProperty("contentHash").GetString() + ); } finally { if (Directory.Exists(workspace)) + { Directory.Delete(workspace, recursive: true); + } } } - } diff --git a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs index 761707ad2..7d94958f3 100644 --- a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs @@ -10,9 +10,10 @@ using System.Threading.Tasks; using System.Xml.Linq; using BGCS.Runtime; +using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -30,7 +31,7 @@ public sealed class NuGetLoadedIdentityTests public Task SdkOutputScopesMatchTheActuallyLoadedRuntime( bool isolated, bool staleDefault - ) => VerifyScope(isolated, staleDefault); + ) => VerifyScopeAsync(isolated, staleDefault); [Fact] [Trait("ProcessIsolation", "Required")] @@ -38,11 +39,13 @@ public Task IsolatedHostRejectsARealLoadedPayloadMismatch() { string? expected = Environment.GetEnvironmentVariable(C_EXPECTED_RUNTIME); if (expected is null) - return VerifyScope(true, true); + { + return VerifyScopeAsync(true, true); + } string mismatch = Environment.GetEnvironmentVariable(C_MISMATCH_RUNTIME) - ?? throw new InvalidOperationException("The loaded-package probe has no owned mismatch input."); + ?? throw new InvalidOperationException("The loaded-package probe has no owned mismatch input."); string result = Environment.GetEnvironmentVariable(C_PROBE_RESULT) - ?? throw new InvalidOperationException("The loaded-package probe has no result owner."); + ?? throw new InvalidOperationException("The loaded-package probe has no result owner."); (WeakReference retired, WeakReference retiredAssembly) = LoadMismatchedContent(expected, mismatch, typeof(Utf8Codec).Assembly); GC.Collect(); GC.WaitForPendingFinalizers(); @@ -53,7 +56,7 @@ public Task IsolatedHostRejectsARealLoadedPayloadMismatch() return Task.CompletedTask; } - private static async Task VerifyScope( + private static async Task VerifyScopeAsync( bool isolated, bool staleDefault ) { @@ -64,46 +67,85 @@ bool staleDefault string repository = TestRepository.GetRoot(typeof(NuGetLoadedIdentityTests).Assembly); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string version = (await ToolchainEnvironment.CaptureOutputAsync(sdk, - ["msbuild", Path.Combine(repository, "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj"), - "-nologo", "-nr:false", "-getProperty:InnoBgcsPackageVersion"], - repository, cancellation.Token, DotNetSdkEnvironment.Create(sdk))).Trim(); + string version = (await ToolchainEnvironment.CaptureOutputAsync( + sdk, + [ + "msbuild", + Path.Combine(repository, "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj"), + "-nologo", + "-nr:false", + "-getProperty:InnoBgcsPackageVersion" + ], + repository, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk) + )).Trim(); string project = Path.Combine(root, "Consumer.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("LangVersion", "14.0"), new XElement("ImplicitUsings", "disable")), - new XElement("ItemGroup", new XElement("PackageReference", new XAttribute("Include", "BGCS.Runtime"), - new XAttribute("Version", "[" + version + "]"))))).Save(project); + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("ImplicitUsings", "disable") + ), + new XElement( + "ItemGroup", + new XElement( + "PackageReference", + new XAttribute("Include", "BGCS.Runtime"), + new XAttribute("Version", "[" + version + "]") + ) + ) + ) + ).Save(project); string defaultAssets = Path.Combine(root, "obj", "project.assets.json"); - const string stale = "unrelated stale default assets must never be consumed"; + const string C_STALE = "unrelated stale default assets must never be consumed"; if (staleDefault) { Directory.CreateDirectory(Path.GetDirectoryName(defaultAssets)!); - File.WriteAllText(defaultAssets, stale); + File.WriteAllText(defaultAssets, C_STALE); } string[] owner = isolated ? ["-p:ArtifactsPath=" + Path.Combine(root, "owned-output")] : []; - string evaluated = await ToolchainEnvironment.CaptureOutputAsync(sdk, + string evaluated = await ToolchainEnvironment.CaptureOutputAsync( + sdk, ["msbuild", project, "-t:Restore", "-nologo", "-nr:false", "-v:quiet", "-getProperty:ProjectAssetsFile", .. owner], - root, cancellation.Token, DotNetSdkEnvironment.Create(sdk)); + root, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk) + ); string assetsPath = evaluated.Trim(); Assert.True(File.Exists(assetsPath), evaluated); if (isolated) { Assert.StartsWith(Path.Combine(root, "owned-output"), assetsPath, StringComparison.OrdinalIgnoreCase); if (staleDefault) - Assert.Equal(stale, File.ReadAllText(defaultAssets)); + { + Assert.Equal(C_STALE, File.ReadAllText(defaultAssets)); + } else + { Assert.False(File.Exists(defaultAssets)); + } } else + { Assert.Equal(defaultAssets, assetsPath); + } using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(assetsPath)); string library = "BGCS.Runtime/" + version; JsonElement package = assets.RootElement.GetProperty("libraries").GetProperty(library); - string packageRoot = assets.RootElement.GetProperty("packageFolders").EnumerateObject() - .Select(folder => Path.Combine(folder.Name, package.GetProperty("path").GetString()!)).Single(Directory.Exists); + string packageRoot = assets.RootElement.GetProperty("packageFolders") + .EnumerateObject() + .Select(folder => Path.Combine(folder.Name, package.GetProperty("path").GetString()!)) + .Single(Directory.Exists); JsonElement target = assets.RootElement.GetProperty("targets").EnumerateObject().Single().Value.GetProperty(library); - string relative = target.GetProperty("runtime").EnumerateObject().Single(item => item.Name.EndsWith(".dll", StringComparison.Ordinal)).Name; + string relative = target + .GetProperty("runtime") + .EnumerateObject() + .Single(item => item.Name.EndsWith(".dll", StringComparison.Ordinal)).Name; string runtime = Path.Combine(packageRoot, relative); Assembly loaded = typeof(Utf8Codec).Assembly; AssertLoadedContent(runtime, loaded); @@ -111,8 +153,10 @@ bool staleDefault string mismatch = Path.Combine(root, "mismatched", "BGCS.Runtime.dll"); Directory.CreateDirectory(Path.GetDirectoryName(mismatch)!); File.WriteAllBytes(mismatch, File.ReadAllBytes(runtime)); - await using (FileStream altered = new(mismatch, FileMode.Append, FileAccess.Write)) + await using (var altered = new FileStream(mismatch, FileMode.Append, FileAccess.Write)) + { await altered.WriteAsync(new byte[] { 0x49, 0x4E, 0x4E, 0x4F }, cancellation.Token); + } await RunLoadedMismatchProbeAsync(sdk, runtime, mismatch, root, cancellation.Token); } finally @@ -129,15 +173,31 @@ private static async Task RunLoadedMismatchProbeAsync( CancellationToken cancellationToken ) { string result = Path.Combine(root, "loaded-package-probe.txt"); - string output = await ToolchainEnvironment.CaptureOutputAsync(sdk, - ["test", typeof(NuGetLoadedIdentityTests).Assembly.Location, - "--filter", "FullyQualifiedName=" + typeof(NuGetLoadedIdentityTests).FullName + "." + nameof(IsolatedHostRejectsARealLoadedPayloadMismatch), - "--results-directory", Path.Combine(root, "probe-results"), - "--logger", "trx;LogFileName=loaded-package.trx", - "--environment", C_EXPECTED_RUNTIME + "=" + expected, - "--environment", C_MISMATCH_RUNTIME + "=" + mismatch, - "--environment", C_PROBE_RESULT + "=" + result], - root, cancellationToken, DotNetSdkEnvironment.Create(sdk)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + sdk, + [ + "test", + typeof(NuGetLoadedIdentityTests).Assembly.Location, + "--filter", + "FullyQualifiedName=" + + typeof(NuGetLoadedIdentityTests).FullName + + "." + + nameof(IsolatedHostRejectsARealLoadedPayloadMismatch), + "--results-directory", + Path.Combine(root, "probe-results"), + "--logger", + "trx;LogFileName=loaded-package.trx", + "--environment", + C_EXPECTED_RUNTIME + "=" + expected, + "--environment", + C_MISMATCH_RUNTIME + "=" + mismatch, + "--environment", + C_PROBE_RESULT + "=" + result + ], + root, + cancellationToken, + DotNetSdkEnvironment.Create(sdk) + ); Assert.True(File.Exists(result), output); Assert.Equal(C_VERIFIED_PROBE, File.ReadAllText(result)); // The physical image belongs to the probe process; normal cleanup follows its complete exit. @@ -155,7 +215,7 @@ Assembly loaded Assembly different = context.LoadFromAssemblyPath(mismatch); Assert.Equal(loaded.GetName().FullName, different.GetName().FullName); Assert.Equal(loaded.ManifestModule.ModuleVersionId, different.ManifestModule.ModuleVersionId); - Assert.Throws(() => AssertLoadedContent(expected, different)); + Assert.Throws(() => AssertLoadedContent(expected, different)); return (new WeakReference(context), new WeakReference(different)); } finally @@ -167,6 +227,8 @@ Assembly loaded private static void AssertLoadedContent( string expected, Assembly loaded - ) => Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(expected))), - Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(loaded.Location)))); + ) => Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(expected))), + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(loaded.Location))) + ); } diff --git a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs index 6110a6c82..30947ccc6 100644 --- a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs @@ -5,11 +5,13 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.TaskHosting; -using Inno.Core.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xunit; +using Inno.Build.TaskHosting; +using Inno.Core.IO; + +using AsyncTask = System.Threading.Tasks.Task; namespace Inno.Build.Integration.Tests; @@ -28,7 +30,7 @@ public OwnedRestoreTests() public void Dispose() => Directory.Delete(m_root, recursive: true); [Fact] - public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogether() + public async AsyncTask WritersYieldAndNeverEnterRestoreTogether() { using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); @@ -39,9 +41,9 @@ public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogethe return true; }); var secondEngine = new RecordingEngine(static () => true); - Task first = System.Threading.Tasks.Task.Run(Create(firstEngine).Execute); + Task first = AsyncTask.Run(Create(firstEngine).Execute); Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); - Task second = System.Threading.Tasks.Task.Run(Create(secondEngine).Execute); + Task second = AsyncTask.Run(Create(secondEngine).Execute); try { Assert.True(SpinWait.SpinUntil(() => secondEngine.yielded, TimeSpan.FromSeconds(10))); @@ -57,13 +59,13 @@ public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogethe } [Fact] - public async System.Threading.Tasks.Task CancellationDoesNotEnterRestoreOrRemoveAnotherOwnersLock() + public async AsyncTask CancellationDoesNotEnterRestoreOrRemoveAnotherOwnersLock() { var engine = new RecordingEngine(static () => true); RestoreOwnedProjectTask canceled = Create(engine); using (FileLease lease = await FileLease.AcquireAsync(Path.Combine(m_root, "write.lock"), TimeSpan.FromSeconds(5))) { - Task pending = System.Threading.Tasks.Task.Run(canceled.Execute); + Task pending = AsyncTask.Run(canceled.Execute); Assert.True(SpinWait.SpinUntil(() => engine.yielded, TimeSpan.FromSeconds(10))); canceled.Cancel(); Assert.False(await pending); @@ -124,22 +126,24 @@ private sealed class RecordingEngine(Func restore) : IBuildEngine3 { private volatile bool m_yielded; private int m_builds; - internal bool yielded => m_yielded; - internal int builds => m_builds; - internal bool reacquired { get; private set; } - internal IDictionary? properties { get; private set; } - internal IList? removed { get; private set; } + public bool ContinueOnError => false; public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => m_yielded = true; + public void Reacquire() => reacquired = true; - public void LogErrorEvent(BuildErrorEventArgs error) { } - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogErrorEvent(BuildErrorEventArgs error) {} + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} public BuildEngineResult BuildProjectFilesInParallel( string[] projects, @@ -157,6 +161,16 @@ bool returnTargetOutputs return new BuildEngineResult(restore(), []); } + public bool BuildProjectFilesInParallel( + string[] projects, + string[] targets, + IDictionary[] properties, + IDictionary[] outputs, + string[] toolsVersions, + bool useResultsCache, + bool unloadProjects + ) => throw new NotSupportedException(); + public bool BuildProjectFile( string project, string[] targets, @@ -172,14 +186,10 @@ public bool BuildProjectFile( string toolsVersion ) => throw new NotSupportedException(); - public bool BuildProjectFilesInParallel( - string[] projects, - string[] targets, - IDictionary[] properties, - IDictionary[] outputs, - string[] toolsVersions, - bool useResultsCache, - bool unloadProjects - ) => throw new NotSupportedException(); + internal bool yielded => m_yielded; + internal int builds => m_builds; + internal bool reacquired { get; private set; } + internal IDictionary? properties { get; private set; } + internal IList? removed { get; private set; } } } diff --git a/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs b/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs index 541c80bee..57fb3248c 100644 --- a/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs @@ -4,10 +4,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -56,33 +56,62 @@ bool trimmed try { using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", project, "-t:Restore", "-p:ArtifactsPath=" + workspace, - "-p:InnoNativeTarget=" + target, "-p:RuntimeIdentifier=" + runtime, - "-p:PublishAot=" + aheadOfTime, "-p:PublishTrimmed=" + trimmed, - "-getProperty:ProjectAssetsFile", "-nologo", "-nr:false", "-v:quiet"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + project, + "-t:Restore", + "-p:ArtifactsPath=" + workspace, + "-p:InnoNativeTarget=" + target, + "-p:RuntimeIdentifier=" + runtime, + "-p:PublishAot=" + aheadOfTime, + "-p:PublishTrimmed=" + trimmed, + "-getProperty:ProjectAssetsFile", + "-nologo", + "-nr:false", + "-v:quiet" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); string assetsPath = output.Trim(); - Assert.StartsWith(Path.GetFullPath(workspace) + Path.DirectorySeparatorChar, - Path.GetFullPath(assetsPath), StringComparison.Ordinal); + Assert.StartsWith( + Path.GetFullPath(workspace) + Path.DirectorySeparatorChar, + Path.GetFullPath(assetsPath), + StringComparison.Ordinal + ); using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(assetsPath)); JsonProperty[] resolved = assets.RootElement.GetProperty("targets").EnumerateObject().ToArray(); Assert.NotEmpty(resolved); if (runtime.Length != 0) + { Assert.Contains(resolved, entry => entry.Name.EndsWith("/" + runtime, StringComparison.Ordinal)); + } if (aheadOfTime) - Assert.Contains(assets.RootElement.GetProperty("libraries").EnumerateObject(), - static entry => entry.Name.StartsWith("Microsoft.DotNet.ILCompiler/", StringComparison.Ordinal)); + { + Assert.Contains( + assets.RootElement.GetProperty("libraries").EnumerateObject(), + static entry => entry.Name.StartsWith("Microsoft.DotNet.ILCompiler/", StringComparison.Ordinal) + ); + } if (trimmed) - Assert.Contains(assets.RootElement.GetProperty("libraries").EnumerateObject(), - static entry => entry.Name.StartsWith("Microsoft.NET.ILLink.Tasks/", StringComparison.Ordinal)); + { + Assert.Contains( + assets.RootElement.GetProperty("libraries").EnumerateObject(), + static entry => entry.Name.StartsWith("Microsoft.NET.ILLink.Tasks/", StringComparison.Ordinal) + ); + } Assert.Empty(Directory.EnumerateFiles(Path.GetDirectoryName(project)!, "packages*.lock.json")); Assert.Empty(Directory.EnumerateFiles(workspace, "packages*.lock.json", SearchOption.AllDirectories)); } finally { if (Directory.Exists(workspace)) + { Directory.Delete(workspace, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs index 72be287b9..76e66bb66 100644 --- a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Security; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,7 +21,11 @@ public async Task OwnedProductCleanDoesNotPrepareNativeArtifacts( bool explicitlyDisablePreparation ) { string repository = TestRepository.GetRoot(typeof(SolutionBootstrapOwnershipTests).Assembly); - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoProductCleanTests", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoProductCleanTests", + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(root); try { @@ -31,12 +35,25 @@ bool explicitlyDisablePreparation using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(host, - ["clean", Path.Combine(repository, project), - "--artifacts-path", artifacts, "-p:InnoTaskArtifacts=" + tasks, - .. (explicitlyDisablePreparation ? new[] { "-p:InnoPrepareProductNative=false" } : Array.Empty()), - "--disable-build-servers", "-m:1", "-nr:false"], - repository, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + host, + [ + "clean", + Path.Combine(repository, project), + "--artifacts-path", + artifacts, + "-p:InnoTaskArtifacts=" + tasks, + .. (explicitlyDisablePreparation ? ["-p:InnoPrepareProductNative=false"] : Array.Empty()), + "--disable-build-servers", + "-m:1", + "-nr:false" + ], + repository, + DotNetSdkEnvironment.Create(host), + output, + error, + cancellation.Token + )); Assert.True(failure is null, $"{failure}\n{output}\n{error}"); Assert.False(Directory.Exists(tasks), output.ToString()); Assert.Empty(Directory.GetFiles(artifacts, "*.dll", SearchOption.AllDirectories)); @@ -52,7 +69,11 @@ bool explicitlyDisablePreparation public async Task BootstrapClaimsAreSharedWithinOneProcessButCannotCrossExitedProcesses() { string repository = TestRepository.GetRoot(typeof(SolutionBootstrapOwnershipTests).Assembly); - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoBootstrapLifetimeTests", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoBootstrapLifetimeTests", + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(root); try { @@ -85,11 +106,19 @@ async Task InvokeAsync(string owner) using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(host, + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + host, ["msbuild", project, "-t:Build", "-nr:false", "-p:InnoTaskBootstrapOwner=" + owner], - root, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + root, + DotNetSdkEnvironment.Create(host), + output, + error, + cancellation.Token + )); if (failure is not null) + { throw new InvalidOperationException(output.ToString() + error, failure); + } } } finally @@ -108,6 +137,7 @@ public async Task SolutionSharesOneBootstrapOwnerAndRenewsItForTheNextBuild() { File.Copy(Path.Combine(root, "Directory.Solution.targets"), Path.Combine(fixture, "Directory.Solution.targets")); foreach (string name in new[] { "First", "Second" }) + { await File.WriteAllTextAsync(Path.Combine(fixture, name + ".csproj"), """ @@ -117,6 +147,7 @@ await File.WriteAllTextAsync(Path.Combine(fixture, name + ".csproj"), """ """); + } string solution = Path.Combine(fixture, "InnoEngine.sln"); await File.WriteAllTextAsync(solution, """ Microsoft Visual Studio Solution File, Format Version 12.00 @@ -144,8 +175,14 @@ await File.WriteAllTextAsync(solution, """ using var output = new StringWriter(); using var error = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( - host, ["msbuild", solution, "-m:2", "-nodeReuse:false", "-v:quiet"], - fixture, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + host, + ["msbuild", solution, "-m:2", "-nodeReuse:false", "-v:quiet"], + fixture, + DotNetSdkEnvironment.Create(host), + output, + error, + cancellation.Token + )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output}{Environment.NewLine}{error}"); string first = File.ReadAllText(Path.Combine(fixture, "First.owner")).Trim(); Assert.True(Guid.TryParseExact(first, "N", out _)); diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs index ee076e193..c963d963a 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs @@ -24,14 +24,32 @@ private TaskHostPublicationProcess( Task running, CancellationTokenSource budget ) { - loadDirectory = load; - publisherDirectory = publisher; - readyFile = ready; + this.loadDirectory = load; + this.publisherDirectory = publisher; + this.readyFile = ready; m_release = release; m_running = running; m_budget = budget; } + /// + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { + return; + } + File.WriteAllText(m_release, "release"); + try + { + await m_running; + } + finally + { + m_budget.Dispose(); + } + } + internal string loadDirectory { get; } internal string publisherDirectory { get; } internal string readyFile { get; } @@ -48,15 +66,27 @@ internal static async Task StartAsync(string root) string ready = Path.Combine(worker, "ready"); string release = Path.Combine(worker, "release"); string source = Path.Combine(root, "input", "Inno.Build.Tasks.dll"); - var project = new XDocument(new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", "Inno.Build.TaskHosting.PublishTaskHostTask"), - new XAttribute("AssemblyFile", typeof(PublishTaskHostTask).Assembly.Location)), - new XElement("UsingTask", new XAttribute("TaskName", "HoldPublication"), - new XAttribute("TaskFactory", "RoslynCodeTaskFactory"), - new XAttribute("AssemblyFile", "$(MSBuildToolsPath)/Microsoft.Build.Tasks.Core.dll"), - new XElement("ParameterGroup", new XElement("ReleaseFile", new XAttribute("Required", "true"))), - new XElement("Task", new XElement("Code", new XAttribute("Type", "Fragment"), - new XAttribute("Language", "cs"), new XCData(""" + var project = new XDocument( + new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", "Inno.Build.TaskHosting.PublishTaskHostTask"), + new XAttribute("AssemblyFile", typeof(PublishTaskHostTask).Assembly.Location) + ), + new XElement( + "UsingTask", + new XAttribute("TaskName", "HoldPublication"), + new XAttribute("TaskFactory", "RoslynCodeTaskFactory"), + new XAttribute("AssemblyFile", "$(MSBuildToolsPath)/Microsoft.Build.Tasks.Core.dll"), + new XElement("ParameterGroup", new XElement("ReleaseFile", new XAttribute("Required", "true"))), + new XElement( + "Task", + new XElement( + "Code", + new XAttribute("Type", "Fragment"), + new XAttribute("Language", "cs"), + new XCData(""" var elapsed = System.Diagnostics.Stopwatch.StartNew(); while (!System.IO.File.Exists(ReleaseFile)) { @@ -64,26 +94,55 @@ internal static async Task StartAsync(string root) throw new System.TimeoutException("The publication fixture was not released."); System.Threading.Thread.Sleep(10); } - """)))), - new XElement("Target", new XAttribute("Name", "Publish"), - new XElement("ItemGroup", new XElement("RuntimeFile", new XAttribute("Include", source), - new XElement("RelativePath", "Inno.Build.Tasks.dll"), - new XElement("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))))), - new XElement("Inno.Build.TaskHosting.PublishTaskHostTask", - new XAttribute("InputFiles", "@(RuntimeFile)"), - new XAttribute("CacheDirectory", Path.Combine(root, "hosts")), - new XAttribute("LoadDirectory", load), new XAttribute("PublisherDirectory", publisher), - new XElement("Output", new XAttribute("TaskParameter", "PublishedAssembly"), - new XAttribute("PropertyName", "PublishedRuntime"))), - new XElement("WriteLinesToFile", new XAttribute("File", ready), - new XAttribute("Lines", "$(PublishedRuntime)"), new XAttribute("Overwrite", "true")), - new XElement("HoldPublication", new XAttribute("ReleaseFile", release))))); + """) + ) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "Publish"), + new XElement( + "ItemGroup", + new XElement( + "RuntimeFile", + new XAttribute("Include", source), + new XElement("RelativePath", "Inno.Build.Tasks.dll"), + new XElement("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))) + ) + ), + new XElement( + "Inno.Build.TaskHosting.PublishTaskHostTask", + new XAttribute("InputFiles", "@(RuntimeFile)"), + new XAttribute("CacheDirectory", Path.Combine(root, "hosts")), + new XAttribute("LoadDirectory", load), + new XAttribute("PublisherDirectory", publisher), + new XElement( + "Output", + new XAttribute("TaskParameter", "PublishedAssembly"), + new XAttribute("PropertyName", "PublishedRuntime") + ) + ), + new XElement( + "WriteLinesToFile", + new XAttribute("File", ready), + new XAttribute("Lines", "$(PublishedRuntime)"), + new XAttribute("Overwrite", "true") + ), + new XElement("HoldPublication", new XAttribute("ReleaseFile", release)) + ) + ) + ); string path = Path.Combine(worker, "Publication.proj"); project.Save(path); string dotnet = ToolchainEnvironment.ResolveExecutable(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); var budget = new CancellationTokenSource(TimeSpan.FromMinutes(2)); - Task running = ToolchainEnvironment.RunAsync(dotnet, ["msbuild", path, "-t:Publish", "-nologo", "-m:1", "-nr:false"], - worker, budget.Token, DotNetSdkEnvironment.Create(dotnet)); + Task running = ToolchainEnvironment.RunAsync( + dotnet, + ["msbuild", path, "-t:Publish", "-nologo", "-m:1", "-nr:false"], + worker, + budget.Token, + DotNetSdkEnvironment.Create(dotnet) + ); var result = new TaskHostPublicationProcess(load, publisher, ready, release, running, budget); try { @@ -101,20 +160,16 @@ internal static async Task StartAsync(string root) catch { budget.Cancel(); - try { await running; } - catch (Exception) { } + try + { + await running; + } + catch (Exception) + { + // The original failure is rethrown below. The failure of the canceled run is not needed. + } budget.Dispose(); throw; } } - - /// - public async ValueTask DisposeAsync() - { - if (Interlocked.Exchange(ref m_disposed, 1) != 0) - return; - File.WriteAllText(m_release, "release"); - try { await m_running; } - finally { m_budget.Dispose(); } - } } diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs index 25408bf79..c02273e01 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs @@ -5,11 +5,13 @@ using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; -using Inno.Build.TaskHosting; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xunit; +using Inno.Build.TaskHosting; +using Inno.Build.Toolchains; + +using AsyncTask = System.Threading.Tasks.Task; namespace Inno.Build.Integration.Tests; @@ -41,12 +43,11 @@ public void RepeatedPublicationReusesOneVerifiedRuntimeWithoutChangingItsFiles() } [Fact] - public async System.Threading.Tasks.Task ConcurrentReadersShareTheCompleteContentIdentity() + public async AsyncTask ConcurrentReadersShareTheCompleteContentIdentity() { PublishTaskHostTask first = CreateTask(); PublishTaskHostTask second = CreateTask(); - bool[] results = await System.Threading.Tasks.Task.WhenAll( - System.Threading.Tasks.Task.Run(first.Execute), System.Threading.Tasks.Task.Run(second.Execute)); + bool[] results = await AsyncTask.WhenAll(AsyncTask.Run(first.Execute), AsyncTask.Run(second.Execute)); Assert.All(results, result => Assert.True(result)); Assert.Equal(first.PublishedAssembly, second.PublishedAssembly); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "hosts"))); @@ -91,7 +92,7 @@ public void CanceledBootstrapNeverCreatesACacheOrReader() } [Fact] - public async System.Threading.Tasks.Task RetirementKeepsLiveReadersAndReleasesDeadReadersAndTheirUnreferencedRuntime() + public async AsyncTask RetirementKeepsLiveReadersAndReleasesDeadReadersAndTheirUnreferencedRuntime() { TaskHostPublicationProcess old = await TaskHostPublicationProcess.StartAsync(m_root); await using TaskHostPublicationProcess live = await TaskHostPublicationProcess.StartAsync(m_root); @@ -129,7 +130,7 @@ public void InvalidInputIdentityFailsBeforeCreatingOutput(string relative) } [Fact] - public async System.Threading.Tasks.Task BootstrapRetirementPreservesCurrentProcessAndRemovesOnlyConfirmedDeadOwners() + public async AsyncTask BootstrapRetirementPreservesCurrentProcessAndRemovesOnlyConfirmedDeadOwners() { await using TaskHostPublicationProcess previous = await TaskHostPublicationProcess.StartAsync(m_root); await previous.DisposeAsync(); @@ -146,46 +147,60 @@ public async System.Threading.Tasks.Task BootstrapRetirementPreservesCurrentProc private PublishTaskHostTask CreateTask() { string source = Path.Combine(m_root, "input", "Inno.Build.Tasks.dll"); - TaskItem file = new(source); + var file = new TaskItem(source); file.SetMetadata("RelativePath", "Inno.Build.Tasks.dll"); file.SetMetadata("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))); return new PublishTaskHostTask { - InputFiles = [file], CacheDirectory = Path.Combine(m_root, "hosts"), + InputFiles = [file], + CacheDirectory = Path.Combine(m_root, "hosts"), LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), BuildEngine = m_engine }; } - private async System.Threading.Tasks.Task MaintainAsync() + private async AsyncTask MaintainAsync() { BuildCacheOwnerDescriptor[] owners = [ new BuildCachePublisher(Path.Combine(m_root, "hosts"), BuildCacheArtifactRole.ImmutableArtifact).Describe("hosts"), new BuildCachePublisher(Path.Combine(m_root, "loads"), BuildCacheArtifactRole.ProcessWorkingDirectory).Describe("loads"), - new BuildCachePublisher(Path.Combine(m_root, "publishers"), BuildCacheArtifactRole.ProcessWorkingDirectory).Describe("publishers") + new BuildCachePublisher( + Path.Combine(m_root, "publishers"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ).Describe("publishers") ]; - BuildCacheCleanupResult result = await BuildCacheCleanupPlan.Create(m_root, owners, - new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(20)), retireAll: true).ExecuteAsync(); + BuildCacheCleanupResult result = await BuildCacheCleanupPlan.Create( + m_root, + owners, + new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(20)), + retireAll: true + ).ExecuteAsync(); Assert.Empty(result.failures); } private sealed class RecordingBuildEngine : IBuildEngine { - internal ConcurrentBag errors { get; } = []; public bool ContinueOnError => false; public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public bool BuildProjectFile( string project, string[] targets, IDictionary properties, IDictionary outputs ) => throw new NotSupportedException(); + + internal ConcurrentBag errors { get; } = []; } } diff --git a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs index 6fd60bde6..ffe80bb59 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -8,8 +7,9 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Logging; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -25,9 +25,11 @@ public async Task ProjectGraphSharesCompilationButKeepsPrivateLoadsAndFreshBuild Directory.CreateDirectory(root); try { - File.WriteAllText(Path.Combine(root, "Directory.Build.props"), + File.WriteAllText( + Path.Combine(root, "Directory.Build.props"), ""); + + "\" />" + ); File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), $$""" @@ -46,20 +48,27 @@ public async Task ProjectGraphSharesCompilationButKeepsPrivateLoadsAndFreshBuild "Left" or "Right" => ["Shared"], _ => [] }; - string references = string.Join(string.Empty, dependencies.Select(static name => - $"")); + string references = string.Join( + string.Empty, + dependencies.Select(static name => $"") + ); if (name == "Root") - references += ""; - File.WriteAllText(Path.Combine(directory, name + ".csproj"), + { + references += ""; + } + File.WriteAllText( + Path.Combine(directory, name + ".csproj"), "net10.0" + "disablefalse" + "BuildProjectReferences=true;BuildingInsideVisualStudio=false" - + "" + references + ""); + + "" + references + "" + ); } - var first = await Build(root, configuration); + (string output, string binlog) first = await BuildAsync(root, configuration); string firstOwner = Validate(first.output, first.binlog); - var second = await Build(root, configuration); + (string output, string binlog) second = await BuildAsync(root, configuration); string secondOwner = Validate(second.output, second.binlog); Assert.NotEqual(firstOwner, secondOwner); } @@ -95,28 +104,59 @@ string runtimeIdentifier using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); using var output = new StringWriter(); using var errors = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(dotnet, - ["msbuild", project, "-nologo", "-t:Probe", "-nr:false", "-bl:" + binlog, - "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), "-p:ArtifactsPath=" + Path.Combine(root, "caller"), - "-p:TargetFramework=" + framework, "-p:RuntimeIdentifier=" + runtimeIdentifier, - "-p:PublishAot=true", "-p:PublishSingleFile=true", "-p:SelfContained=true", "-p:WasmBuildNative=true"], - repository, timeout.Token, DotNetSdkEnvironment.Create(dotnet), output, errors)); + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + dotnet, + [ + "msbuild", + project, + "-nologo", + "-t:Probe", + "-nr:false", + "-bl:" + binlog, + "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), + "-p:ArtifactsPath=" + Path.Combine(root, "caller"), + "-p:TargetFramework=" + framework, + "-p:RuntimeIdentifier=" + runtimeIdentifier, + "-p:PublishAot=true", + "-p:PublishSingleFile=true", + "-p:SelfContained=true", + "-p:WasmBuildNative=true" + ], + repository, + DotNetSdkEnvironment.Create(dotnet), + output, + errors, + timeout.Token + )); Assert.True(failure is null, $"{failure}\n{output}\n{errors}"); int requests = 0; var events = new BinaryLogReplayEventSource(); events.ProjectStarted += ( _, item - ) => { + ) => + { if (Path.GetFileNameWithoutExtension(item.ProjectFile) != "Inno.Core.IO" - || item.TargetNames != "Restore;Build") + || item.TargetNames != "Restore;Build" + ) { return; + } requests++; Assert.NotNull(item.GlobalProperties); - foreach (string property in new[] { "RuntimeIdentifier", "TargetFramework", "PublishAot", "PublishSingleFile", "SelfContained", "WasmBuildNative" }) + foreach (string property in new[] { + "RuntimeIdentifier", + "TargetFramework", + "PublishAot", + "PublishSingleFile", + "SelfContained", + "WasmBuildNative" + }) { Assert.DoesNotContain(property, item.GlobalProperties!.Keys); - Assert.Equal(Path.Combine(root, "caller", ".inno-task-foundation").Replace('\\', '/'), - item.GlobalProperties!["ArtifactsPath"].Replace('\\', '/')); + } + Assert.Equal( + Path.Combine(root, "caller", ".inno-task-foundation").Replace('\\', '/'), + item.GlobalProperties!["ArtifactsPath"].Replace('\\', '/') + ); }; events.Replay(binlog); Assert.True(requests > 0, "No neutral Foundation bootstrap was inspected."); @@ -133,9 +173,11 @@ private static string Validate( string output, string binlog ) { - string[][] reports = output.Split('\n').Select(static line => line.Trim()) + string[][] reports = output.Split('\n') + .Select(static line => line.Trim()) .Where(static line => line.StartsWith("INNO-PUBLISHER-PROBE|", StringComparison.Ordinal)) - .Select(static line => line.Split('|')).ToArray(); + .Select(static line => line.Split('|')) + .ToArray(); Assert.True(reports.Length == 4, output); Assert.Equal(4, reports.Select(static report => report[1]).Distinct().Count()); Assert.Equal(4, reports.Select(static report => report[3]).Distinct().Count()); @@ -148,11 +190,14 @@ string binlog events.ProjectStarted += ( _, project - ) => { + ) => + { if (Path.GetFileNameWithoutExtension(project.ProjectFile) != "Inno.Core.IO" || project.GlobalProperties is not { } globals - || !globals.TryGetValue("ArtifactsPath", out string? artifacts)) + || !globals.TryGetValue("ArtifactsPath", out string? artifacts) + ) { return; + } if (string.Equals(Path.GetFileName(artifacts), ".inno-task-foundation", StringComparison.Ordinal)) { bootstrapFoundationRequests++; @@ -161,8 +206,10 @@ string binlog return; } if (!string.IsNullOrEmpty(project.TargetNames) - || !string.Equals(Path.GetFileName(artifacts), "managed", StringComparison.Ordinal)) + || !string.Equals(Path.GetFileName(artifacts), "managed", StringComparison.Ordinal) + ) { return; + } sharedFoundationRequests++; Assert.True(globals.TryGetValue("InnoNativeTarget", out string? target)); Assert.Equal("fixture-target", target); @@ -172,30 +219,39 @@ string binlog events.TaskStarted += ( _, task - ) => { + ) => + { if (task.TaskName == "Csc" && Path.GetFileNameWithoutExtension(task.ProjectFile) == "Inno.Build.TaskHosting") + { compilations++; + } }; events.Replay(binlog); Assert.True(sharedFoundationRequests > 0, "The real shared Foundation graph was not exercised."); Assert.True(bootstrapFoundationRequests > 0, "The neutral bootstrap output owner was not exercised."); Assert.True(compilations == 1, $"Expected one bootstrap Csc task, observed {compilations}.\n{output}"); - string[] runtimeReports = output.Split('\n').Select(static line => line.Trim()) - .Where(static line => line.StartsWith("INNO-TASK-RUNTIME ", StringComparison.Ordinal)).ToArray(); + string[] runtimeReports = output.Split('\n') + .Select(static line => line.Trim()) + .Where(static line => line.StartsWith("INNO-TASK-RUNTIME ", StringComparison.Ordinal)) + .ToArray(); Assert.Equal(4, runtimeReports.Length); Assert.Single(runtimeReports.Select(static line => line[(line.LastIndexOf(' ') + 1)..]).Distinct()); Assert.InRange(runtimeReports.Count(static line => line.StartsWith("INNO-TASK-RUNTIME prepared ", StringComparison.Ordinal)), 0, 1); foreach (string[] report in reports) + { Assert.True(File.Exists(report[3]), "The private publisher was not retained for its loading process: " + report[3]); + } return owner; } - private static async Task<(string output, string binlog)> Build( + private static async Task<(string output, string binlog)> BuildAsync( string root, string configuration ) { - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -207,13 +263,21 @@ string configuration string binlog = Path.Combine(root, Guid.NewGuid().ToString("N") + ".binlog"); foreach (string argument in new[] { - "build", "Root/Root.csproj", "--configuration", configuration, "--disable-build-servers", "--nologo", "-m:2", "-nodeReuse:false", + "build", + "Root/Root.csproj", + "--configuration", + configuration, + "--disable-build-servers", + "--nologo", + "-m:2", + "-nodeReuse:false", "-p:InnoNativeTarget=fixture-target", "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), "-p:ArtifactsPath=" + Path.Combine(root, "managed"), "-bl:" + binlog - }) + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -225,7 +289,9 @@ string configuration catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs index 0ded074d5..8392532a2 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs @@ -1,12 +1,13 @@ using System; +using System.Collections.Generic; using System.IO; using System.Security; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -166,16 +167,28 @@ public void Shutdown() { } """); string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(10)); - var environment = DotNetSdkEnvironment.Create(dotnet); - await ToolchainEnvironment.RunAsync(dotnet, + IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(dotnet); + await ToolchainEnvironment.RunAsync( + dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], - repository, timeout.Token, environment); - string sdk = (await ToolchainEnvironment.CaptureOutputAsync(dotnet, + repository, + timeout.Token, + environment + ); + string sdk = (await ToolchainEnvironment.CaptureOutputAsync( + dotnet, ["msbuild", project, "-nologo", "-getProperty:MSBuildBinPath"], - repository, timeout.Token, environment)).Trim(); - await ToolchainEnvironment.RunAsync(dotnet, + repository, + timeout.Token, + environment + )).Trim(); + await ToolchainEnvironment.RunAsync( + dotnet, [Path.Combine(root, "bin/Debug/net10.0/Runner.dll"), fixture, sdk, report, repository], - repository, timeout.Token, environment); + repository, + timeout.Token, + environment + ); using JsonDocument results = JsonDocument.Parse(await File.ReadAllTextAsync(report)); Assert.Equal(2, results.RootElement.GetArrayLength()); string? previous = null; diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs index d3f00c794..0104dcc1b 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs @@ -3,12 +3,10 @@ using System.IO; using System.Threading.Tasks; using System.Xml.Linq; - +using Xunit; using Inno.Build.TaskHosting; using Inno.Build.Toolchains; -using Xunit; - namespace Inno.Build.Integration.Tests; public sealed class TaskRestoreEvaluationTests @@ -27,47 +25,102 @@ public async Task RestoreDoesNotReusePackageContentItemsDuringCompilation(bool o File.WriteAllText(oldPayload, "old-package-content"); File.WriteAllText(newPayload, "new-package-content"); string imports = Path.Combine(root, "restored.props"); - new XDocument(new XElement("Project", new XElement("PropertyGroup", - new XElement("PayloadPath", oldPayload)))).Save(imports); - string updatedImports = new XElement("Project", new XElement("PropertyGroup", - new XElement("PayloadPath", newPayload))).ToString(SaveOptions.DisableFormatting); + new XDocument( + new XElement("Project", new XElement("PropertyGroup", new XElement("PayloadPath", oldPayload))) + ).Save(imports); + string updatedImports = new XElement( + "Project", + new XElement("PropertyGroup", new XElement("PayloadPath", newPayload)) + ).ToString(SaveOptions.DisableFormatting); string project = Path.Combine(root, "Runtime.csproj"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", imports), - new XAttribute("Condition", "'$(ExcludeRestorePackageImports)' != 'true'")), - new XElement("Target", new XAttribute("Name", "Restore"), - new XElement("WriteLinesToFile", new XAttribute("File", imports), - new XAttribute("Lines", updatedImports), new XAttribute("Overwrite", "true"))), - new XElement("Target", new XAttribute("Name", "PublishRuntime"), - new XAttribute("Returns", "@(HashedRuntime)"), - new XElement("MakeDir", new XAttribute("Directories", "$(ArtifactsPath)/bin")), - new XElement("Copy", new XAttribute("SourceFiles", "$(PayloadPath)"), - new XAttribute("DestinationFiles", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll")), - new XElement("ItemGroup", new XElement("RuntimeFile", - new XAttribute("Include", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll"), - new XElement("RelativePath", "Inno.Build.Tasks.dll"))), - new XElement("GetFileHash", new XAttribute("Files", "@(RuntimeFile)"), - new XElement("Output", new XAttribute("TaskParameter", "Items"), - new XAttribute("ItemName", "HashedRuntime")))))).Save(project); + new XDocument( + new XElement( + "Project", + new XElement( + "Import", + new XAttribute("Project", imports), + new XAttribute("Condition", "'$(ExcludeRestorePackageImports)' != 'true'") + ), + new XElement( + "Target", + new XAttribute("Name", "Restore"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", imports), + new XAttribute("Lines", updatedImports), + new XAttribute("Overwrite", "true") + ) + ), + new XElement( + "Target", + new XAttribute("Name", "PublishRuntime"), + new XAttribute("Returns", "@(HashedRuntime)"), + new XElement("MakeDir", new XAttribute("Directories", "$(ArtifactsPath)/bin")), + new XElement( + "Copy", + new XAttribute("SourceFiles", "$(PayloadPath)"), + new XAttribute("DestinationFiles", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll") + ), + new XElement( + "ItemGroup", + new XElement( + "RuntimeFile", + new XAttribute("Include", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll"), + new XElement("RelativePath", "Inno.Build.Tasks.dll") + ) + ), + new XElement( + "GetFileHash", + new XAttribute("Files", "@(RuntimeFile)"), + new XElement( + "Output", + new XAttribute("TaskParameter", "Items"), + new XAttribute("ItemName", "HashedRuntime") + ) + ) + ) + ) + ).Save(project); string artifacts = Path.Combine(root, "workspaces", "shared"); XElement operation = ownedRestore - ? new XElement("Inno.Build.TaskHosting.RestoreOwnedProjectTask", - new XAttribute("Projects", project), new XAttribute("LockPath", artifacts + ".lock"), - new XAttribute("Properties", "ArtifactsPath=" + artifacts)) - : new XElement("Inno.Build.TaskHosting.BuildTaskRuntimeTask", - new XAttribute("ProjectFile", project), new XAttribute("ArtifactsDirectory", artifacts), - new XAttribute("LoadDirectory", Path.Combine(root, "loads", "reader", "Debug")), - new XAttribute("Targets", "Restore;PublishRuntime")); - XElement run = new("Target", new XAttribute("Name", "Run"), operation); + ? new XElement( + "Inno.Build.TaskHosting.RestoreOwnedProjectTask", + new XAttribute("Projects", project), + new XAttribute("LockPath", artifacts + ".lock"), + new XAttribute("Properties", "ArtifactsPath=" + artifacts) + ) + : new XElement( + "Inno.Build.TaskHosting.BuildTaskRuntimeTask", + new XAttribute("ProjectFile", project), + new XAttribute("ArtifactsDirectory", artifacts), + new XAttribute("LoadDirectory", Path.Combine(root, "loads", "reader", "Debug")), + new XAttribute("Targets", "Restore;PublishRuntime") + ); + var run = new XElement("Target", new XAttribute("Name", "Run"), operation); if (ownedRestore) - run.Add(new XElement("MSBuild", new XAttribute("Projects", project), - new XAttribute("Targets", "PublishRuntime"), - new XAttribute("Properties", "ArtifactsPath=" + artifacts))); + { + run.Add( + new XElement( + "MSBuild", + new XAttribute("Projects", project), + new XAttribute("Targets", "PublishRuntime"), + new XAttribute("Properties", "ArtifactsPath=" + artifacts) + ) + ); + } string parent = Path.Combine(root, "Parent.proj"); - new XDocument(new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", operation.Name), - new XAttribute("AssemblyFile", typeof(BuildTaskRuntimeTask).Assembly.Location)), run)).Save(parent); + new XDocument( + new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", operation.Name), + new XAttribute("AssemblyFile", typeof(BuildTaskRuntimeTask).Assembly.Location) + ), + run + ) + ).Save(parent); var start = new ProcessStartInfo(ToolchainEnvironment.ResolveExecutable("dotnet")) { @@ -77,7 +130,9 @@ public async Task RestoreDoesNotReusePackageContentItemsDuringCompilation(bool o WorkingDirectory = root }; foreach (string argument in new[] { "msbuild", parent, "-t:Run", "-m:1", "-nr:false", "-v:minimal" }) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs index 8cf2f75fd..c217668e0 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs @@ -1,19 +1,20 @@ -using System.Security.Cryptography; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using System.Text.Json; +using Microsoft.Build.Framework; +using Xunit; using Inno.Build.TaskHosting; using Inno.Build.Toolchains; using Inno.Core.IO; -using Microsoft.Build.Framework; -using TaskItem = Microsoft.Build.Utilities.TaskItem; -using Xunit; + +using BuildTaskItem = Microsoft.Build.Utilities.TaskItem; namespace Inno.Build.Integration.Tests; @@ -48,8 +49,10 @@ public void MissingSelectedTargetRequiresRestoreBeforePublication() """); File.WriteAllText(assets, """{"targets":{},"libraries":{},"packageFolders":{}}"""); - var engine = new RecordingEngine(() => true, () => File.WriteAllText(assets, - """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}""")); + var engine = new RecordingEngine(() => true, () => File.WriteAllText( + assets, + """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}""" + )); BuildTaskRuntimeTask task = CreateTask(engine); task.Targets = ["PublishInnoBuildTaskHost"]; Assert.True(task.Execute(), string.Join("\n", engine.errors.Select(static error => error.Message))); @@ -73,7 +76,9 @@ public async Task CompletedPreparationProtectsWorkspaceDuringMaintenanceAndCache var engine = new RecordingEngine(static () => true, () => { if (restored) + { return; + } Directory.CreateDirectory(workspace); File.WriteAllText(assets, """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}"""); restored = true; @@ -88,7 +93,8 @@ public async Task CompletedPreparationProtectsWorkspaceDuringMaintenanceAndCache new BuildCachePublisher(Path.Combine(m_root, "hosts"), BuildCacheArtifactRole.ImmutableArtifact).Describe("hosts"), new BuildCachePublisher(Path.Combine(m_root, "loads"), BuildCacheArtifactRole.ProcessWorkingDirectory).Describe("loads") ]; - BuildCacheCleanupResult maintained = await BuildCacheCleanupPlan.Create(m_root, owners, new(), retireAll: true).ExecuteAsync(); + BuildCacheCleanupResult maintained = await BuildCacheCleanupPlan.Create(m_root, owners, new BuildCachePolicy(), retireAll: true) + .ExecuteAsync(); Assert.Empty(maintained.failures); Assert.True(File.Exists(assets)); BuildTaskRuntimeTask repeated = CreateTask(engine); @@ -101,21 +107,30 @@ public async Task CompletedPreparationProtectsWorkspaceDuringMaintenanceAndCache [Fact] public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() { - using ManualResetEventSlim entered = new(); - using ManualResetEventSlim release = new(); - RecordingEngine firstEngine = new(() => { + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var firstEngine = new RecordingEngine(() => + { entered.Set(); Assert.True(release.Wait(TimeSpan.FromSeconds(10))); return true; }); - RecordingEngine secondEngine = new(() => true); + var secondEngine = new RecordingEngine(() => true); BuildTaskRuntimeTask first = CreateTask(firstEngine); BuildTaskRuntimeTask second = CreateTask(secondEngine); - Task firstRun = Task.Factory.StartNew(first.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task firstRun = Task.Factory.StartNew( + first.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); - Task secondRun = Task.Factory.StartNew(second.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task secondRun = Task.Factory.StartNew( + second.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); try { Assert.True(SpinWait.SpinUntil(() => secondEngine.yielded, TimeSpan.FromSeconds(10))); @@ -129,8 +144,10 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() Assert.True(await secondRun, string.Join("\n", secondEngine.errors.Select(static error => error.Message))); Assert.True(firstEngine.reacquired && secondEngine.reacquired); Assert.Single(first.TargetOutputs); - Assert.Equal(Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(m_root, "Inno.Build.Tasks.dll")))), - first.TargetOutputs[0].GetMetadata("FileHash")); + Assert.Equal( + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(m_root, "Inno.Build.Tasks.dll")))), + first.TargetOutputs[0].GetMetadata("FileHash") + ); Assert.Equal("Debug", firstEngine.properties!["Configuration"]); Assert.Equal(Path.Combine(m_root, "bootstrap"), firstEngine.properties["ArtifactsPath"]); Assert.Contains("RuntimeIdentifier", firstEngine.removed!); @@ -139,17 +156,24 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() [Fact] public async Task CancellationReleasesWaitAndAllowsTheNextBuild() { - RecordingEngine engine = new(() => true); + var engine = new RecordingEngine(() => true); BuildTaskRuntimeTask canceled = CreateTask(engine); using (FileLease lease = await FileLease.AcquireAsync( - Path.Combine(m_root, "bootstrap") + ".lock", TimeSpan.FromSeconds(10))) - { - Task execution = Task.Factory.StartNew(canceled.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Path.Combine(m_root, "bootstrap") + ".lock", + TimeSpan.FromSeconds(10) + )) { + Task execution = Task.Factory.StartNew( + canceled.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); try { - Assert.True(SpinWait.SpinUntil(() => engine.yielded || execution.IsCompleted, TimeSpan.FromSeconds(10)), - string.Join("\n", engine.errors.Select(static error => error.Message))); + Assert.True( + SpinWait.SpinUntil(() => engine.yielded || execution.IsCompleted, TimeSpan.FromSeconds(10)), + string.Join("\n", engine.errors.Select(static error => error.Message)) + ); Assert.True(engine.yielded, string.Join("\n", engine.errors.Select(static error => error.Message))); canceled.Cancel(); Assert.False(await execution); @@ -163,14 +187,14 @@ public async Task CancellationReleasesWaitAndAllowsTheNextBuild() } } canceled.Cancel(); - Assert.True(CreateTask(new(() => true)).Execute()); + Assert.True(CreateTask(new RecordingEngine(() => true)).Execute()); } [Fact] public void FailedBuildDoesNotRetainSharedOwnership() { - Assert.False(CreateTask(new(() => false)).Execute()); - Assert.True(CreateTask(new(() => true)).Execute()); + Assert.False(CreateTask(new RecordingEngine(() => false)).Execute()); + Assert.True(CreateTask(new RecordingEngine(() => true)).Execute()); } [Theory] @@ -178,7 +202,7 @@ public void FailedBuildDoesNotRetainSharedOwnership() [InlineData("Configuration=Debug;Configuration=Release")] public void InvalidPropertiesFailBeforeCreatingSharedOutput(string declarations) { - BuildTaskRuntimeTask task = CreateTask(new(() => true)); + BuildTaskRuntimeTask task = CreateTask(new RecordingEngine(() => true)); task.Properties = declarations.Split(';'); Assert.False(task.Execute()); Assert.False(Directory.Exists(Path.Combine(m_root, "bootstrap"))); @@ -189,7 +213,7 @@ public void ValidPublicationIsReusedAcrossBuildsAndRejectsSameLengthSameTimeSour { var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); - var reused = CreateTask(engine); + BuildTaskRuntimeTask reused = CreateTask(engine); Assert.True(reused.Execute(), string.Join("\n", engine.errors)); Assert.Equal(1, engine.builds); Assert.Contains(Path.Combine(m_root, "hosts"), reused.TargetOutputs[0].ItemSpec); @@ -208,10 +232,10 @@ public void ValidPublicationIsReusedAcrossBuildsAndRejectsSameLengthSameTimeSour public void CorruptedImmutableRuntimeIsRepairedBeforeReuse() { var engine = new RecordingEngine(static () => true); - var first = CreateTask(engine); + BuildTaskRuntimeTask first = CreateTask(engine); Assert.True(first.Execute(), string.Join("\n", engine.errors)); File.WriteAllText(first.TargetOutputs[0].ItemSpec, "corrupted"); - var second = CreateTask(engine); + BuildTaskRuntimeTask second = CreateTask(engine); Assert.True(second.Execute(), string.Join("\n", engine.errors)); Assert.Equal(2, engine.builds); Assert.Equal("prepared-runtime", File.ReadAllText(second.TargetOutputs[0].ItemSpec)); @@ -225,8 +249,13 @@ public void BootstrapOwnershipIsForwardedWithoutHidingDerivedCompilerInputs( int expectedBuilds ) { if (affectsCompilation) - File.WriteAllText(m_project, "$(InnoTaskBootstrapOwner)" - + ""); + { + File.WriteAllText( + m_project, + "$(InnoTaskBootstrapOwner)" + + "" + ); + } var engine = new RecordingEngine(static () => true); foreach (string owner in new[] { new string('a', 32), new string('b', 32) }) { @@ -252,8 +281,10 @@ public void CompilerInputChangesCannotReuseThePreviousRuntime(string itemType) { string input = Path.Combine(m_root, "compiler-input.txt"); File.WriteAllText(input, "value=one"); - File.WriteAllText(m_project, - $"<{itemType} Include=\"compiler-input.txt\" />"); + File.WriteAllText( + m_project, + $"<{itemType} Include=\"compiler-input.txt\" />" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); @@ -282,27 +313,39 @@ public void ResolvedPackageBytesCannotReuseThePreviousRuntime(string assetGroup) File.WriteAllText(unrelated, "unselected-one"); var package = new Dictionary { ["type"] = "package" }; if (assetGroup != "analyzers") + { package[assetGroup] = new Dictionary { [relative] = new { } }; + } string assets = Path.Combine(m_root, "project.assets.json"); - File.WriteAllText(assets, JsonSerializer.Serialize(new - { - targets = new Dictionary + File.WriteAllText( + assets, + JsonSerializer.Serialize(new { - ["net10.0"] = new Dictionary + targets = new Dictionary { - ["Fixture/1.0.0"] = package - } - }, - libraries = new Dictionary - { - ["Fixture/1.0.0"] = new { type = "package", path = "fixture/1.0.0", files = new[] { relative, "lib/net8.0/Fixture.dll" } } - }, - packageFolders = new Dictionary { [packageRoot] = new { } } - })); - File.WriteAllText(m_project, + ["net10.0"] = new Dictionary + { + ["Fixture/1.0.0"] = package + } + }, + libraries = new Dictionary + { + ["Fixture/1.0.0"] = new + { + type = "package", + path = "fixture/1.0.0", + files = new[] { relative, "lib/net8.0/Fixture.dll" } + } + }, + packageFolders = new Dictionary { [packageRoot] = new { } } + }) + ); + File.WriteAllText( + m_project, "net10.0" + "" + assets + "" - + ""); + + "" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); File.WriteAllText(unrelated, "unselected-two"); @@ -336,10 +379,13 @@ public void DeclaredIndependentRestoresFinishBeforeCompilationAndAreNotRepeatedO { string dependency = Path.Combine(m_root, "Dependency.csproj"); File.WriteAllText(dependency, ""); - File.WriteAllText(m_project, "" + File.WriteAllText( + m_project, + "" + "" + "OwnedRestore=true" - + ""); + + "" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); Assert.Equal(new[] { m_project + ":Restore", dependency + ":Restore", m_project + ":PublishInnoBuildTaskHost" }, engine.requests); @@ -354,13 +400,13 @@ private BuildTaskRuntimeTask CreateTask(RecordingEngine engine) engine.outputPath = Path.Combine(m_root, "Inno.Build.Tasks.dll"); return new() { - BuildEngine = engine, - ProjectFile = m_project, - ArtifactsDirectory = Path.Combine(m_root, "bootstrap"), - LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), - Targets = ["Restore", "PublishInnoBuildTaskHost"], - Properties = ["Configuration=Debug", "BuildProjectReferences=true"], - RemoveProperties = ["RuntimeIdentifier", "PublishAot"] + BuildEngine = engine, + ProjectFile = m_project, + ArtifactsDirectory = Path.Combine(m_root, "bootstrap"), + LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), + Targets = ["Restore", "PublishInnoBuildTaskHost"], + Properties = ["Configuration=Debug", "BuildProjectReferences=true"], + RemoveProperties = ["RuntimeIdentifier", "PublishAot"] }; } @@ -368,10 +414,10 @@ private sealed class RecordingEngine : IBuildEngine4 { private readonly Func m_build; private readonly ConcurrentDictionary m_registry = new(); + private readonly Action? m_restore; internal string outputPath = string.Empty; private int m_builds; private volatile bool m_yielded; - private readonly Action? m_restore; internal RecordingEngine( Func build, @@ -380,24 +426,25 @@ internal RecordingEngine( m_build = build; m_restore = restore; } - internal int builds => m_builds; - internal bool yielded => m_yielded; - internal bool reacquired { get; private set; } - internal IDictionary? properties { get; private set; } - internal IList? removed { get; private set; } - internal ConcurrentBag errors { get; } = []; - internal List requests { get; } = []; + public bool ContinueOnError => false; public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => m_yielded = true; + public void Reacquire() => reacquired = true; + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public BuildEngineResult BuildProjectFilesInParallel( string[] projects, string[] targets, @@ -409,27 +456,43 @@ bool returnTargetOutputs Assert.True(reacquired); requests.Add(projects[0] + ":" + string.Join(";", targets)); if (returnTargetOutputs) + { Interlocked.Increment(ref m_builds); + } else if (targets.Contains("Restore", StringComparer.Ordinal)) + { m_restore?.Invoke(); + } properties = globalProperties[0]; removed = removeGlobalProperties[0]; - TaskItem output = new(outputPath); + var output = new BuildTaskItem(outputPath); output.SetMetadata("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(outputPath)))); output.SetMetadata("RelativePath", "Inno.Build.Tasks.dll"); return new(!returnTargetOutputs || m_build(), [new Dictionary { [targets[^1]] = [output] }]); } + public bool BuildProjectFilesInParallel( + string[] projects, + string[] targets, + IDictionary[] properties, + IDictionary[] outputs, + string[] toolsVersions, + bool useResultsCache, + bool unloadProjects + ) => throw new NotSupportedException(); + public object GetRegisteredTaskObject( object key, RegisteredTaskObjectLifetime lifetime ) => m_registry.TryGetValue(key, out object? value) ? value : null!; + public void RegisterTaskObject( object key, object value, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection ) => m_registry[key] = value; + public object UnregisterTaskObject( object key, RegisteredTaskObjectLifetime lifetime @@ -450,14 +513,12 @@ public bool BuildProjectFile( string toolsVersion ) => throw new NotSupportedException(); - public bool BuildProjectFilesInParallel( - string[] projects, - string[] targets, - IDictionary[] properties, - IDictionary[] outputs, - string[] toolsVersions, - bool useResultsCache, - bool unloadProjects - ) => throw new NotSupportedException(); + internal int builds => m_builds; + internal bool yielded => m_yielded; + internal bool reacquired { get; private set; } + internal IDictionary? properties { get; private set; } + internal IList? removed { get; private set; } + internal ConcurrentBag errors { get; } = []; + internal List requests { get; } = []; } } diff --git a/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs b/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs index b6ff913eb..978c7750c 100644 --- a/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs @@ -1,8 +1,8 @@ -using Inno.Testing.Source; using System; using System.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -12,12 +12,12 @@ public sealed class ToolchainEnvironmentTests public void NativeBuildRootBelongsToTheToolchainProject() { string engine = TestRepository.GetRoot(typeof(ToolchainEnvironmentTests).Assembly); - string expected = Path.Combine(engine, - "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"); + string expected = Path.Combine(engine, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"); var component = new NativeComponentDescriptor( "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); var context = new NativeBuildContext(engine, "debug"); Assert.Equal(expected, context.GetNativeBuildRoot(component)); diff --git a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs index 5b16cbe76..4b9202774 100644 --- a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs +++ b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs @@ -28,9 +28,10 @@ public ProductNativeCostTests(ITestOutputHelper output) { m_output = output; m_host = new WindowsBuildHostProvider().TryCapture() - ?? throw new PlatformNotSupportedException("Native cost acceptance requires its declared Windows host."); - m_distribution = StandardBuildDistribution.Create(new BuildCompositionContext( - "explicit-sdk", Path.GetTempPath(), m_host, new BuildTargetId("windows-x64"))).build; + ?? throw new PlatformNotSupportedException("Native cost acceptance requires its declared Windows host."); + m_distribution = StandardBuildDistribution.Create( + new BuildCompositionContext("explicit-sdk", Path.GetTempPath(), m_host, new BuildTargetID("windows-x64")) + ).build; } [Fact] @@ -38,12 +39,19 @@ public async Task RealPresentationBuildUsesDeclaredCMakeAndFrozenWindowSource() { string root = TestRepository.GetRoot(typeof(ProductNativeCostTests).Assembly); ProductNativeBuildStep[] steps = m_distribution.ResolveNativeProduct("windows-x64", "editor").plan.steps - .Where(static step => step.id is "cimgui" or "cimguizmo").ToArray(); + .Where(static step => step.id is "cimgui" or "cimguizmo") + .ToArray(); var plan = new ProductNativeBuildPlan("presentation-acceptance", steps); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(15)); - var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); - NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync(context, - m_host, "windows-x64", cancellation.Token); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithBindingGenerator( + m_distribution.ResolveBindingGenerator("windows-x64") + ); + NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( + context, + m_host, + "windows-x64", + cancellation.Token + ); context = context.WithToolchain(sdk); using ProductNativeBuildResult result = await new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token); Assert.Equal(2, result.Count); @@ -61,21 +69,29 @@ public async Task RealHotProductBatchReadsLessThanSequentialPublicProducers(int string root = TestRepository.GetRoot(typeof(ProductNativeCostTests).Assembly); ProductNativeBuildPlan plan = m_distribution.ResolveNativeProduct("windows-x64", "editor").plan; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(20)); - async Task Context() + async Task ContextAsync() { - var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); - NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync(context, - m_host, "windows-x64", cancellation.Token); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithBindingGenerator( + m_distribution.ResolveBindingGenerator("windows-x64") + ); + NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( + context, + m_host, + "windows-x64", + cancellation.Token + ); return context.WithToolchain(sdk); } - NativeBuildContext serial = await Context(); + NativeBuildContext serial = await ContextAsync(); Stopwatch elapsed = Stopwatch.StartNew(); - using (NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync(serial, - plan.steps.Select(static step => step.component).ToArray(), cancellation.Token, + using (NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync( + serial, + plan.steps.Select(static step => step.component).ToArray(), + cancellation.Token, plan.steps.Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal))) - { + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + )) { serial = serial.WithBindings(bindings); var products = new Dictionary(StringComparer.Ordinal); try @@ -83,21 +99,24 @@ async Task Context() foreach (ProductNativeBuildStep step in plan.steps) { NativeBuildContext selected = (step.configuration is string configuration - ? serial.WithConfiguration(configuration) : serial).WithComponentOptions(step.component, step.options); + ? serial.WithConfiguration(configuration) + : serial).WithComponentOptions(step.component, step.options); products.Add(step.id, await step.build!(selected, products, cancellation.Token)); } } finally { foreach (NativeBuildProduct product in products.Values.Reverse()) + { product.Dispose(); + } } } double serialSeconds = elapsed.Elapsed.TotalSeconds; m_output.WriteLine(JsonSerializer.Serialize(new { sample, phase = "serial", seconds = serialSeconds, serial.statistics })); Assert.Equal(0, serial.statistics.nativeProcesses); Assert.Equal(0, serial.statistics.bindingGenerations); - NativeBuildContext batch = await Context(); + NativeBuildContext batch = await ContextAsync(); elapsed.Restart(); using ProductNativeBuildResult result = await new ComponentNativeProductExecutor().BuildAsync(batch, plan, cancellation.Token); double batchSeconds = elapsed.Elapsed.TotalSeconds; diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs index 2fe833db1..82ba762b9 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Linq; @@ -6,9 +5,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -21,40 +21,81 @@ public async Task SdkAddedReferencesRetainTheProductTargetAndShaderProfile() string platform = OperatingSystem.IsWindows() ? "WindowsX64" : "MacOSArm64"; string target = OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64"; string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "EditorProduct.props"); - string backend = Path.Combine(root, "backends", "Sdl3", "runtime", - "Inno.Adapter.Platform.Sdl3", "Inno.Adapter.Platform.Sdl3.csproj"); + string backend = Path.Combine( + root, + "backends", + "Sdl3", + "runtime", + "Inno.Adapter.Platform.Sdl3", + "Inno.Adapter.Platform.Sdl3.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - using ProcessOwnedDirectory outputs = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoShaderReferenceTests")); - string configuration = typeof(EditorShaderProfileTests).Assembly.GetCustomAttribute()!.Configuration; - string[] buildProperties = ["-p:InnoProductBuildProperties=" + profile, "-p:InnoNativeTarget=" + target, - "-p:InnoToolTarget=" + target, "-p:Configuration=" + configuration, "-p:ArtifactsPath=" + outputs.directory]; + using ProcessOwnedDirectory outputs = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoShaderReferenceTests") + ); + string configuration = typeof(EditorShaderProfileTests) + .Assembly + .GetCustomAttribute()! + .Configuration; + string[] buildProperties = + [ + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=" + target, + "-p:InnoToolTarget=" + target, + "-p:Configuration=" + configuration, + "-p:ArtifactsPath=" + outputs.directory + ]; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, ["restore", backend, "--disable-build-servers", "-m:1", "-nr:false", ..buildProperties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-t:IncludeTransitiveProjectReferences", - "-getItem:ProjectReference", ..buildProperties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + await ToolchainEnvironment.RunAsync( + host, + ["restore", backend, "--disable-build-servers", "-m:1", "-nr:false", ..buildProperties], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-t:IncludeTransitiveProjectReferences", + "-getItem:ProjectReference", + ..buildProperties + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement references = document.RootElement.GetProperty("Items").GetProperty("ProjectReference"); Assert.Contains(references.EnumerateArray(), reference => reference.GetProperty("Filename").GetString() == "Inno.Native.Sdl3"); Assert.DoesNotContain(references.EnumerateArray(), reference => reference.GetProperty("Filename").GetString() == "BGCS.Runtime"); - Assert.All(references.EnumerateArray().Where(reference => - !reference.TryGetProperty("OutputItemType", out JsonElement kind) || kind.GetString() != "Analyzer"), reference => + Assert.All( + references.EnumerateArray().Where(reference => ( + !reference.TryGetProperty("OutputItemType", out JsonElement kind) || kind.GetString() != "Analyzer" + )), + reference => { string properties = reference.GetProperty("AdditionalProperties").GetString()!; Assert.Contains("InnoNativeTarget=" + target, properties); Assert.Contains("InnoProductBuildProperties=" + profile, properties); - }); - Assert.All(references.EnumerateArray().Where(reference => - reference.TryGetProperty("OutputItemType", out JsonElement kind) && kind.GetString() == "Analyzer"), reference => + } + ); + Assert.All( + references.EnumerateArray().Where(reference => ( + reference.TryGetProperty("OutputItemType", out JsonElement kind) && kind.GetString() == "Analyzer" + )), + reference => { Assert.Equal("all", reference.GetProperty("PrivateAssets").GetString()); string removed = reference.GetProperty("GlobalPropertiesToRemove").GetString()!; Assert.Contains("InnoNativeTarget", removed); Assert.Contains("InnoProductBuildProperties", removed); Assert.Contains("RuntimeIdentifier", removed); - }); + } + ); } [Theory] @@ -68,16 +109,38 @@ int apiCount ) { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "ProductBuild.props"); - string backend = Path.Combine(root, "backends", "Bgfx", "runtime", - "Inno.Adapter.Rendering.Bgfx", "Inno.Adapter.Rendering.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "Bgfx", + "runtime", + "Inno.Adapter.Rendering.Bgfx", + "Inno.Adapter.Rendering.Bgfx.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-getProperty:InnoBgfxShaderTarget", - "-getItem:_CompositionShaderApi", "-p:InnoProductBuildProperties=" + profile, - "-p:InnoNativeTarget=fixture-new-cpu"], root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-getProperty:InnoBgfxShaderTarget", + "-getItem:_CompositionShaderApi", + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=fixture-new-cpu" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); - Assert.Equal(shaderPlatform, document.RootElement.GetProperty("Properties") - .GetProperty("InnoBgfxShaderTarget").GetString()); + Assert.Equal( + shaderPlatform, + document.RootElement.GetProperty("Properties") + .GetProperty("InnoBgfxShaderTarget") + .GetString() + ); Assert.Equal(apiCount, document.RootElement.GetProperty("Items").GetProperty("_CompositionShaderApi").GetArrayLength()); } @@ -92,37 +155,84 @@ int apiCount ) { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "EditorProduct.props"); - string backend = Path.Combine(root, "backends", "ImGui", "runtime", - "Inno.Adapter.Presentation.ImGui.Bgfx", "Inno.Adapter.Presentation.ImGui.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "ImGui", + "runtime", + "Inno.Adapter.Presentation.ImGui.Bgfx", + "Inno.Adapter.Presentation.ImGui.Bgfx.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-getProperty:InnoImGuiShaderTarget", - "-getItem:_ImGuiShaderApi,ProjectReference", "-p:InnoProductBuildProperties=" + profile, - "-p:InnoNativeTarget=" + nativeTarget], root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-getProperty:InnoImGuiShaderTarget", + "-getItem:_ImGuiShaderApi,ProjectReference", + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=" + nativeTarget + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); - Assert.Equal(shaderPlatform, document.RootElement.GetProperty("Properties") - .GetProperty("InnoImGuiShaderTarget").GetString()); + Assert.Equal( + shaderPlatform, + document.RootElement.GetProperty("Properties") + .GetProperty("InnoImGuiShaderTarget") + .GetString() + ); JsonElement items = document.RootElement.GetProperty("Items"); Assert.Equal(apiCount, items.GetProperty("_ImGuiShaderApi").GetArrayLength()); - Assert.All(items.GetProperty("ProjectReference").EnumerateArray() - .Where(reference => !reference.TryGetProperty("OutputItemType", out JsonElement kind) - || kind.GetString() != "Analyzer"), reference => - Assert.Contains("InnoProductBuildProperties=" + profile, - reference.GetProperty("AdditionalProperties").GetString())); + Assert.All( + items.GetProperty("ProjectReference") + .EnumerateArray() + .Where(reference => ( + !reference.TryGetProperty("OutputItemType", out JsonElement kind) + || kind.GetString() != "Analyzer" + )), + reference => + Assert.Contains( + "InnoProductBuildProperties=" + profile, + reference.GetProperty("AdditionalProperties").GetString() + ) + ); } [Fact] public async Task FrozenProductSourcesKeepTheExplicitOfflineToolOwner() { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); - string backend = Path.Combine(root, "backends", "Bgfx", "runtime", - "Inno.Adapter.Rendering.Bgfx", "Inno.Adapter.Rendering.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "Bgfx", + "runtime", + "Inno.Adapter.Rendering.Bgfx", + "Inno.Adapter.Rendering.Bgfx.csproj" + ); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); string selectedOwner = Path.Combine(root, "artifacts", "fixture-tool-source-owner"); - string selected = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-p:DesignTimeBuild=true", - "-p:InnoShaderToolSourceRoot=" + selectedOwner, "-getProperty:InnoShaderToolSourceRoot"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string selected = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-p:DesignTimeBuild=true", + "-p:InnoShaderToolSourceRoot=" + selectedOwner, + "-getProperty:InnoShaderToolSourceRoot" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); Assert.Equal(selectedOwner, selected.Trim()); } } diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs index 07b04153a..1d8483439 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs @@ -5,8 +5,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -25,8 +25,10 @@ public async Task StandaloneBindingCompilationDeclaresItsDependencyWithoutProduc string product ) { string root = TestRepository.GetRoot(typeof(ProductBindingSelectionTests).Assembly); - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -37,12 +39,16 @@ string product }; foreach (string argument in new[] { - "msbuild", "backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj", "-nologo", + "msbuild", + "backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj", + "-nologo", "-getProperty:InnoBindingProductId,InnoProductId,InnoProductRestoreProject,BindGenGeneratedBindings", - "-p:Configuration=Debug", "-p:InnoNativeTarget=" + target, + "-p:Configuration=Debug", + "-p:InnoNativeTarget=" + target, "-p:InnoProductBuildProperties=" + Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, properties) - }) + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -54,7 +60,9 @@ string product catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs index 547d29b43..9dfd66a7e 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.IO; @@ -7,9 +6,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -37,11 +37,21 @@ string expectedTarget string root = TestRepository.GetRoot(typeof(StaticGraphRestoreTests).Assembly); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(60)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"), + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"), "-p:NETCoreSdkRuntimeIdentifier=" + sdkHost, - "-getProperty:InnoNativeTarget,InnoProductBuildProperties", "-getItem:ProjectReference", "-nologo", "-nr:false"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + "-getProperty:InnoNativeTarget,InnoProductBuildProperties", + "-getItem:ProjectReference", + "-nologo", + "-nr:false" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument evaluation = JsonDocument.Parse(output); JsonElement properties = evaluation.RootElement.GetProperty("Properties"); Assert.Equal(expectedTarget, properties.GetProperty("InnoNativeTarget").GetString()); @@ -50,7 +60,9 @@ string expectedTarget foreach (JsonElement reference in evaluation.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) { if (reference.TryGetProperty("OutputItemType", out JsonElement role) && role.GetString() == "Analyzer") + { continue; + } string context = reference.GetProperty("AdditionalProperties").GetString()!; Assert.Contains("InnoNativeTarget=" + expectedTarget, context); Assert.Contains("InnoProductBuildProperties=" + product, context); @@ -67,7 +79,7 @@ public async Task DevelopmentEntryRestoresItsDirectProductReferenceOwners() try { string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); string entry = Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"); string artifacts = Path.Combine(fixture, "managed"); string[] common = ["-p:Configuration=Debug", "-p:ArtifactsPath=" + artifacts, "-nodeReuse:false"]; @@ -75,23 +87,38 @@ public async Task DevelopmentEntryRestoresItsDirectProductReferenceOwners() JsonElement properties = route.RootElement.GetProperty("Properties"); string product = properties.GetProperty("InnoProductRestoreProject").GetString()!; Assert.True(File.Exists(product)); - string[] productProperties = [.. common, + string[] productProperties = + [ + .. common, "-p:InnoNativeTarget=" + properties.GetProperty("InnoNativeTarget").GetString(), "-p:InnoToolTarget=" + properties.GetProperty("InnoToolTarget").GetString(), - "-p:InnoProductBuildProperties=" + properties.GetProperty("InnoProductBuildProperties").GetString()]; + "-p:InnoProductBuildProperties=" + properties.GetProperty("InnoProductBuildProperties").GetString() + ]; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, + await ToolchainEnvironment.RunAsync( + host, ["msbuild", entry, "-t:RestoreProductTargetGraph", "-v:quiet", .. common], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); var references = new HashSet(StringComparer.Ordinal); foreach (JsonElement reference in route.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) + { references.Add(reference.GetProperty("FullPath").GetString()!); + } using JsonDocument selectedProduct = await EvaluateAsync(host, product, productProperties); - foreach (JsonElement reference in selectedProduct.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) - { - if (!reference.TryGetProperty("PrivateAssets", out JsonElement privateAssets) || string.IsNullOrEmpty(privateAssets.GetString())) + foreach (JsonElement reference in selectedProduct.RootElement + .GetProperty("Items") + .GetProperty("ProjectReference") + .EnumerateArray() + ) { + if (!reference.TryGetProperty("PrivateAssets", out JsonElement privateAssets) + || string.IsNullOrEmpty(privateAssets.GetString()) + ) { references.Add(reference.GetProperty("FullPath").GetString()!); + } } Assert.NotEmpty(references); foreach (string reference in references) @@ -115,14 +142,14 @@ public async Task ProductRestoreAcceptsLargeInheritedProperties(bool inheritSolu { string root = TestRepository.GetRoot(typeof(StaticGraphRestoreTests).Assembly); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(host); string owner = Path.Combine(Path.GetTempPath(), "InnoStaticGraphRestoreTests"); string fixture = PathBoundary.Resolve(owner, Guid.NewGuid().ToString("N")); Directory.CreateDirectory(fixture); string project = Path.Combine(root, "platforms", "WindowsX64", "editor", "Inno.Editor.WindowsX64", "Inno.Editor.WindowsX64.csproj"); string driver = Path.Combine(fixture, "Restore.proj"); - string inheritedMetadata = new('R', 65536); + var inheritedMetadata = new string('R', 65_536); try { await File.WriteAllTextAsync(driver, $""" @@ -136,9 +163,13 @@ await File.WriteAllTextAsync(driver, $""" """); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, + await ToolchainEnvironment.RunAsync( + host, ["msbuild", driver, "-t:Verify", "-m:1", "-nodeReuse:false", "-nologo", "-v:minimal"], - root, cancellation.Token, environment); + root, + cancellation.Token, + environment + ); } finally { @@ -154,11 +185,22 @@ IReadOnlyList properties using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - await ToolchainEnvironment.RunAsync(host, - ["msbuild", project, "-nologo", .. properties, + await ToolchainEnvironment.RunAsync( + host, + [ + "msbuild", + project, + "-nologo", + .. properties, "-getProperty:ProjectAssetsFile,InnoProductRestoreProject,InnoNativeTarget,InnoToolTarget,InnoProductBuildProperties", - "-getItem:ProjectReference"], - Path.GetDirectoryName(project)!, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error); + "-getItem:ProjectReference" + ], + Path.GetDirectoryName(project)!, + DotNetSdkEnvironment.Create(host), + output, + error, + cancellation.Token + ); return JsonDocument.Parse(output.ToString()); } } diff --git a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs index ad2b3c01a..a4becd9d2 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs @@ -5,6 +5,7 @@ using Xunit; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Products.Tests; @@ -15,7 +16,10 @@ public sealed class BuildCachePublisherTests : IDisposable [Fact] public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string old = Create("native", "old"); string current = Create("native", "current"); string unrelated = Create("native", "unregistered"); @@ -24,8 +28,12 @@ public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories( publisher.Record(old, old + ".read.lock", [], "editor", null); publisher.Record(current, current + ".read.lock", [], "editor", null); } - using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(old, Path.Combine(m_root, "artifacts", "native"), "old", ["Outputs"])) - { + using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + old, + Path.Combine(m_root, "artifacts", "native"), + "old", + ["Outputs"] + )) { BuildCacheCleanupResult busy = await Plan().ExecuteAsync(); Assert.Empty(busy.retired); Assert.Contains(old, busy.skipped); @@ -40,8 +48,14 @@ public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories( [Fact] public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() { - var bindings = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); - var native = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var bindings = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); + var native = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string oldBinding = Create("bindings", "old"); string newBinding = Create("bindings", "current"); string oldNative = Create("native", "old"); @@ -52,10 +66,14 @@ public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() bindings.Record(newBinding, newBinding + ".read.lock", [], "component", null); } using (await native.AcquireUseAsync()) + { native.Record(oldNative, oldNative + ".read.lock", [oldBinding], "component", null); + } Assert.Empty(Plan().candidates); using (await native.AcquireUseAsync()) + { native.Record(newNative, newNative + ".read.lock", [newBinding], "component", null); + } BuildCacheCleanupResult result = await Plan().ExecuteAsync(); Assert.Equal(2, result.retired.Count); Assert.Contains(oldNative, result.retired); @@ -67,9 +85,12 @@ public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() [Fact] public async Task ActivePublisherPreventsRetirementDuringReadingHandoff() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string artifact = Create("native", "candidate"); - using var activity = await publisher.AcquireUseAsync(); + using FileLease activity = await publisher.AcquireUseAsync(); publisher.Record(artifact, artifact + ".read.lock", [], null, null); BuildCacheCleanupResult result = await Plan().ExecuteAsync(); Assert.Empty(result.retired); @@ -87,11 +108,15 @@ public async Task ProcessOwnedLoadsProtectTheirExactHostDependency() File.WriteAllText(Path.Combine(load, "runtime.dll"), "private bytes"); var hosts = new BuildCachePublisher(Path.GetDirectoryName(host)!, BuildCacheArtifactRole.ImmutableArtifact); using (await hosts.AcquireUseAsync()) + { hosts.Record(host, host + ".lock", [], null, null); + } string secondHost = Path.Combine(Path.GetDirectoryName(host)!, "second"); Directory.CreateDirectory(secondHost); using (await hosts.AcquireUseAsync()) + { hosts.Record(secondHost, secondHost + ".lock", [], null, null); + } var loads = new BuildCachePublisher(Path.GetDirectoryName(load)!, BuildCacheArtifactRole.ProcessWorkingDirectory); loads.RecordProcessUse(load, load + ".lock", [host]); loads.RecordProcessUse(load, load + ".lock", [secondHost]); @@ -105,27 +130,36 @@ public async Task ProcessOwnedLoadsProtectTheirExactHostDependency() [Fact] public async Task SizeAccountingIsRecordedByTheProducerWithoutServingAsIntegrityValidation() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string artifact = Create("native", "owned"); using (await publisher.AcquireUseAsync()) + { publisher.Record(artifact, artifact + ".read.lock", [], null, null); + } long recorded = Plan().totalBytes; File.WriteAllText(Path.Combine(artifact, "Outputs", "payload"), "corrupted and larger"); Assert.Equal(recorded, Plan().totalBytes); Assert.False(BuildArtifactManifest.IsComplete(artifact, "owned", ["Outputs"])); using (await publisher.AcquireUseAsync()) + { publisher.Record(artifact, artifact + ".read.lock", [], null, null); + } Assert.True(Plan().totalBytes > recorded); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private BuildCacheCleanupPlan Plan() - => BuildCacheCleanupPlan.Create(m_root, StandardBuildCaches.CreateOwners(m_root, []), new(0, 0), retireAll: true); + => BuildCacheCleanupPlan.Create(m_root, StandardBuildCaches.CreateOwners(m_root, []), new BuildCachePolicy(0, 0), retireAll: true); private string Create( string owner, diff --git a/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs b/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs index 1223fad7a..8c2596797 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs @@ -26,11 +26,17 @@ public sealed class BuildCompositionTests [InlineData("macos-arm64")] public void EditorAndStandaloneShaderToolsShareTheSameBindingFreeReleaseProducer(string target) { - var context = new BuildCompositionContext("explicit-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "explicit-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ); BuildDistribution distribution = StandardBuildDistribution.Create(context).build; - ProductNativeBuildStep editor = Assert.Single(distribution.ResolveNativeProduct(target, "editor").plan.steps, - static step => step.id == "bgfx-tools"); + ProductNativeBuildStep editor = Assert.Single( + distribution.ResolveNativeProduct(target, "editor").plan.steps, + static step => step.id == "bgfx-tools" + ); ProductNativeBuildStep standalone = Assert.Single(distribution.ResolveNativeProduct(target, "shader-tools").plan.steps); Assert.Equal("release", editor.configuration); Assert.Equal(editor.configuration, standalone.configuration); @@ -43,7 +49,12 @@ public void EditorAndStandaloneShaderToolsShareTheSameBindingFreeReleaseProducer [Fact] public void EveryHostObtainsTheSameFrozenBuiltInDistribution() { - var context = new BuildCompositionContext("explicit-sdk", Path.GetFullPath(Path.GetTempPath()), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "explicit-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ); BuildDistribution editor = StandardBuildDistribution.Create(context).build; BuildDistribution cli = StandardBuildDistribution.Create(context).build; BuildDistribution msbuild = StandardBuildDistribution.Create(context).build; @@ -52,29 +63,64 @@ public void EveryHostObtainsTheSameFrozenBuiltInDistribution() Assert.Equal(3, editor.availableTargets.Count); Assert.Equal(editor.managedDeployments.availableDeployments, msbuild.managedDeployments.availableDeployments); Assert.Equal(4, editor.managedDeployments.availableDeployments.Count); - Assert.Equal(editor.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id), - msbuild.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id)); + Assert.Equal( + editor.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id), + msbuild.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id) + ); Assert.Throws(() => editor.ResolveNativeProduct("browser-wasm", "editor")); - Assert.Throws(() => new BuildCompositionContext("sdk", "relative", new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64"))); + Assert.Throws( + () => new BuildCompositionContext( + "sdk", + "relative", + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ) + ); } [Fact] public void TargetsContributeDistinctImmutableProductClosuresWithoutChangingTheInvokingHost() { - var first = new FixtureTarget(new BuildTargetId("fixture-a")); - var second = new FixtureTarget(new BuildTargetId("fixture-b")); + var first = new FixtureTarget(new BuildTargetID("fixture-a")); + var second = new FixtureTarget(new BuildTargetID("fixture-b")); ProductNativeBuildPlan complete = BuildTestProducts.Player(); var reduced = new ProductNativeBuildPlan("player", [complete.steps[0]]); - NativeProductContribution[] products = [new(complete, new ComponentNativeProductExecutor())]; - var firstContribution = new BuildPlatformContribution(Descriptor(first), () => first, first, new FixtureToolchain(), nativeProducts: products); - var secondContribution = new BuildPlatformContribution(Descriptor(second), () => second, second, new FixtureToolchain(), nativeProducts: [new(reduced, new ComponentNativeProductExecutor())]); - var distribution = new BuildDistribution([Game(firstContribution, first), Game(secondContribution, second)], [new FixtureCompiler()]); + NativeProductContribution[] products = [new NativeProductContribution(complete, new ComponentNativeProductExecutor())]; + var firstContribution = new BuildPlatformContribution( + Descriptor(first), + () => first, + first, + new FixtureToolchain(), + nativeProducts: products + ); + var secondContribution = new BuildPlatformContribution( + Descriptor(second), + () => second, + second, + new FixtureToolchain(), + nativeProducts: [new NativeProductContribution(reduced, new ComponentNativeProductExecutor())] + ); + var distribution = new BuildDistribution( + [Game(firstContribution, first), Game(secondContribution, second)], + [new FixtureCompiler()] + ); products[0] = null!; Assert.Same(complete, distribution.ResolveNativeProduct("fixture-a", "player").plan); Assert.Same(reduced, distribution.ResolveNativeProduct("fixture-b", "player").plan); Assert.Throws(() => distribution.ResolveNativeProduct("fixture-a", "editor")); Assert.Throws(() => distribution.ResolveNativeProduct("absent-target", "player")); - Assert.Throws(() => new BuildPlatformContribution(Descriptor(first), () => first, first, new FixtureToolchain(), nativeProducts: [new(complete, new ComponentNativeProductExecutor()), new(reduced, new ComponentNativeProductExecutor())])); + Assert.Throws( + () => new BuildPlatformContribution( + Descriptor(first), + () => first, + first, + new FixtureToolchain(), + nativeProducts: [ + new NativeProductContribution(complete, new ComponentNativeProductExecutor()), + new NativeProductContribution(reduced, new ComponentNativeProductExecutor()) + ] + ) + ); } [Fact] @@ -87,12 +133,22 @@ public void CustomTargetComposesAndRejectsInconsistentDefaultsBeforePublication( using EngineHost engine = new EngineHostBuilder() .UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(BuildCompositionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); using var assets = new AssetPipeline( - engine.modules, engine.types, engine.serialization, new IdentityAllocator(), engine.diagnostics, engine.logs, + engine.modules, + engine.types, + engine.serialization, + new IdentityAllocator(), + engine.diagnostics, + engine.logs, AssetPipelineOptions.Create(Path.Combine(root, "Assets"), Path.Combine(root, "Library")) with - { enableFileSystemWatcher = false }); + { + enableFileSystemWatcher = false + } + ); var target = new FixtureTarget(); BuildTargetFactory factory = () => target; GameBuildContribution[] platforms = [Contribution(target, factory)]; @@ -100,11 +156,15 @@ public void CustomTargetComposesAndRejectsInconsistentDefaultsBeforePublication( platforms[0] = null!; Assert.Same(target, Assert.Single(distribution.CreateBindings(assets, engine.serialization, engine.types)).packager); distribution.ValidateDeployment(target, target.defaultManagedDeployment); - Assert.Throws(() => distribution.ValidateDeployment(target, ManagedDeploymentId.coreClr)); + Assert.Throws(() => distribution.ValidateDeployment(target, ManagedDeploymentID.coreClr)); Assert.Throws(() => new BuildPlatformContribution( - Descriptor(target), factory, new FixtureTarget(new BuildTargetId("different")), new FixtureToolchain())); + Descriptor(target), + factory, + new FixtureTarget(new BuildTargetID("different")), + new FixtureToolchain() + )); var invalid = new BuildDistribution([Contribution(target, () => - new FixtureTarget(new BuildTargetId("different")))], [new FixtureCompiler()]); + new FixtureTarget(new BuildTargetID("different")))], [new FixtureCompiler()]); Assert.Throws(() => invalid.CreateBindings(assets, engine.serialization, engine.types)); var unsupported = new BuildDistribution([Contribution(target, factory)], [new FixtureCompiler("wrong-rid")]); Assert.Throws(() => unsupported.CreateBindings(assets, engine.serialization, engine.types)); @@ -121,17 +181,19 @@ public void DistributionRejectsAmbiguousOrIncompleteRegistrationSets() var target = new FixtureTarget(); BuildTargetFactory factory = () => target; Assert.Throws(() => new BuildDistribution([], [new FixtureCompiler()])); - Assert.Throws(() => new BuildDistribution([Contribution(target, factory), Contribution(target, factory)], [new FixtureCompiler()])); + Assert.Throws( + () => new BuildDistribution([Contribution(target, factory), Contribution(target, factory)], [new FixtureCompiler()]) + ); Assert.Throws(() => new BuildDistribution([Contribution(target, factory), null!], [new FixtureCompiler()])); } - private static PlatformTargetDescriptor Descriptor(FixtureTarget target) => - new(target.id, "Fixture", "fixture-cpu", "fixture-abi", target.runtimeIdentifier, supportsEditor: false); + private static PlatformTargetDescriptor Descriptor(FixtureTarget target) + => new(target.id, "Fixture", "fixture-cpu", "fixture-abi", target.runtimeIdentifier, supportsEditor: false); private static GameBuildContribution Contribution( FixtureTarget target, BuildTargetFactory factory - ) => Game(new(Descriptor(target), factory, target, new FixtureToolchain()), target); + ) => Game(new BuildPlatformContribution(Descriptor(target), factory, target, new FixtureToolchain()), target); private static GameBuildContribution Game( BuildPlatformContribution platform, @@ -147,16 +209,21 @@ private sealed class FixtureToolchain : INativeToolchainProvider public ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, - string targetId, + string targetID, CancellationToken cancellationToken ) => throw new InvalidOperationException("Composition must not resolve an SDK."); } private sealed class FixtureCompiler(string runtimeIdentifier = "fixture-rid") : IManagedDeploymentCompiler { - public ManagedDeploymentId id => new("fixture-managed"); + public ManagedDeploymentID id => new("fixture-managed"); + public ManagedDeploymentCapabilities capabilities { get; } = new( - [runtimeIdentifier], dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + [runtimeIdentifier], + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); public ValueTask CompileAsync( ManagedDeploymentRequest request, @@ -164,22 +231,26 @@ public ValueTask CompileAsync( ) => throw new InvalidOperationException("Composition must not start publication."); } - private sealed class FixtureTarget(BuildTargetId? identity = null) : IGameBuildTarget, IPlayerSupportPackSource, IGameContentCompiler + private sealed class FixtureTarget(BuildTargetID? identity = null) : IGameBuildTarget, IPlayerSupportPackSource, IGameContentCompiler { - public BuildTargetId id { get; } = identity ?? new BuildTargetId("fixture-platform"); - public BuildTargetId target => id; - public ManagedDeploymentId defaultManagedDeployment => new("fixture-managed"); + public BuildTargetID id { get; } = identity ?? new BuildTargetID("fixture-platform"); + public BuildTargetID target => id; + public ManagedDeploymentID defaultManagedDeployment => new("fixture-managed"); public string runtimeIdentifier => "fixture-rid"; public string displayName => "Fixture"; + public void Validate(string directory) => throw new InvalidOperationException("Composition must not read a pack."); + public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => throw new InvalidOperationException("Composition must not prepare a pack."); + public ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default ) => throw new InvalidOperationException("Composition must not compile content."); + public ValueTask PackageAsync( GameBuildPackageContext context, CancellationToken cancellationToken = default diff --git a/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs b/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs index 2dc252359..c19cc76e5 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs @@ -9,29 +9,27 @@ namespace Inno.Build.Products.Tests; public sealed class BuildTargetCatalogTests : BuildPipelineFixture { - [Fact] public void ProjectSettingsUseTheHostSuppliedInitialIdentity() { - Assert.Equal("tests.build", m_settings.projectId.value); - Assert.False(m_settings.HasProjectOverride(ProjectIdentitySettings.settingId)); + Assert.Equal("tests.build", m_settings.projectID.value); + Assert.False(m_settings.HasProjectOverride(ProjectIdentitySettings.settingID)); } - - [Fact] - public void BuildTargetsAreOpenIdsOwnedByTheRegisteredAdapterCatalog() + public void BuildTargetsAreOpenIDsOwnedByTheRegisteredAdapterCatalog() { Assert.Equal( - [new BuildTargetId("macos-arm64"), new BuildTargetId("windows-x64")], - m_pipeline.availableGameTargets); - Assert.True(m_pipeline.TryGetGameTargetDisplayName( - new BuildTargetId("macos-arm64"), - out string macOSDisplayName)); + [new BuildTargetID("macos-arm64"), new BuildTargetID("windows-x64")], + m_pipeline.availableGameTargets + ); + Assert.True( + m_pipeline.TryGetGameTargetDisplayName(new BuildTargetID("macos-arm64"), out string macOSDisplayName) + ); Assert.Equal("macOS (Apple silicon)", macOSDisplayName); - Assert.False(m_pipeline.TryGetGameTargetDisplayName( - new BuildTargetId("linux-x64"), - out string missingDisplayName)); + Assert.False( + m_pipeline.TryGetGameTargetDisplayName(new BuildTargetID("linux-x64"), out string missingDisplayName) + ); Assert.Empty(missingDisplayName); var profile = new BuildProfile @@ -39,21 +37,18 @@ public void BuildTargetsAreOpenIdsOwnedByTheRegisteredAdapterCatalog() applicationId = "tests.open-target", productName = "Open Target", startupScene = "Scenes/Startup.iscene", - target = new BuildTargetId("linux-x64") + target = new BuildTargetID("linux-x64") }; profile.Validate(); } - - [Fact] public void BuildTargetInventoryCannotBeMutatedThroughItsCollectionView() { - IList targets = Assert.IsAssignableFrom>(m_pipeline.availableGameTargets); + IList targets = Assert.IsAssignableFrom>(m_pipeline.availableGameTargets); Assert.True(targets.IsReadOnly); - Assert.Throws(() => targets[0] = new BuildTargetId("unknown-target")); - Assert.Equal([new BuildTargetId("macos-arm64"), new BuildTargetId("windows-x64")], m_pipeline.availableGameTargets); + Assert.Throws(() => targets[0] = new BuildTargetID("unknown-target")); + Assert.Equal([new BuildTargetID("macos-arm64"), new BuildTargetID("windows-x64")], m_pipeline.availableGameTargets); } - } diff --git a/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs b/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs index 3b80a91c8..5fb85b3d8 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs @@ -9,13 +9,23 @@ namespace Inno.Build.Products.Tests; internal static class BuildTestProducts { - internal static BuildHostDescriptor WindowsHost() => new WindowsBuildHostProvider().TryCapture() - ?? throw new PlatformNotSupportedException("This native fixture requires a Windows build host."); - internal static BuildDistribution Distribution() => StandardBuildDistribution.Create(new BuildCompositionContext( - "explicit-sdk", Path.GetTempPath(), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64"))).build; + internal static BuildHostDescriptor WindowsHost() + => new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("This native fixture requires a Windows build host."); + + internal static BuildDistribution Distribution() + => StandardBuildDistribution.Create( + new BuildCompositionContext( + "explicit-sdk", + Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ) + ).build; internal static ProductNativeBuildPlan Player() => Distribution().ResolveNativeProduct("windows-x64", "player").plan; + internal static ProductNativeBuildPlan Editor() => Distribution().ResolveNativeProduct("windows-x64", "editor").plan; - internal static ProductNativeBuildPlan StaticPlayer() => Distribution().ResolveNativeProduct("browser-wasm", "player").plan; + internal static ProductNativeBuildPlan StaticPlayer() => Distribution().ResolveNativeProduct("browser-wasm", "player").plan; } diff --git a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs index d18a3ce77..9ce16905b 100644 --- a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs +++ b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs @@ -1,48 +1,41 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Modules; using Inno.Extensibility.Types; - - - - using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.Build; namespace Inno.Build.Products.Tests; public sealed class GameBuildWorkflowTests : BuildPipelineFixture { - [Theory] [InlineData("macos-arm64")] [InlineData("windows-x64")] @@ -50,7 +43,7 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies { SaveStartupScene(); TypeCacheSnapshot runtimeTypes = m_engine.types.current; - BuildTargetId target = new(targetValue); + var target = new BuildTargetID(targetValue); using SerializationGeneration serialization = m_engine.serialization.CaptureGeneration(); BuildProfile profile = CreateProfile(target); profile.persistentDataPath = "studio/testgame"; @@ -64,34 +57,49 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies Assert.True(result.succeeded); string outputPath = Assert.IsType(result.outputPath); string contentHash = Assert.IsType(result.contentHash); - string packagedContent = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "Resources", "Content") - : Path.Combine(outputPath, "Content"); - string executable = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS", "Test Game") - : Path.Combine(outputPath, "Test Game.exe"); + string packagedContent = target == new BuildTargetID("macos-arm64") + ? Path.Combine(outputPath, "Contents", "Resources", "Content") + : Path.Combine(outputPath, "Content"); + string executable = target == new BuildTargetID("macos-arm64") + ? Path.Combine(outputPath, "Contents", "MacOS", "Test Game") + : Path.Combine(outputPath, "Test Game.exe"); Assert.True(File.Exists(executable)); - string playerRoot = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS") - : outputPath; + string playerRoot = target == new BuildTargetID("macos-arm64") + ? Path.Combine(outputPath, "Contents", "MacOS") + : outputPath; Assert.False(Directory.Exists(Path.Combine(playerRoot, "References"))); - string deployedNative = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS", "native") - : Path.Combine(outputPath, "native"); - Assert.True(File.Exists(Path.Combine(deployedNative, target == new BuildTargetId("macos-arm64") - ? "libinno-text-release.dylib" - : "inno-text-release.dll"))); - Assert.True(File.Exists(Path.Combine(deployedNative, target == new BuildTargetId("macos-arm64") - ? "libinno-ui-release.dylib" - : "inno-ui-release.dll"))); + string deployedNative = target == new BuildTargetID("macos-arm64") + ? Path.Combine(outputPath, "Contents", "MacOS", "native") + : Path.Combine(outputPath, "native"); + Assert.True( + File.Exists( + Path.Combine( + deployedNative, + target == new BuildTargetID("macos-arm64") + ? "libinno-text-release.dylib" + : "inno-text-release.dll" + ) + ) + ); + Assert.True( + File.Exists( + Path.Combine( + deployedNative, + target == new BuildTargetID("macos-arm64") + ? "libinno-ui-release.dylib" + : "inno-ui-release.dll" + ) + ) + ); Assert.Equal( ["catalog.inno", $"content-{contentHash}.pack", "runtime.manifest"], Directory.EnumerateFiles(packagedContent) .Select(Path.GetFileName) - .Order(StringComparer.Ordinal)); + .Order(StringComparer.Ordinal) + ); byte[] envelope = File.ReadAllBytes(Path.Combine(packagedContent, "runtime.manifest")); - Assert.Equal("tests.game", RuntimeManifestEnvelope.ReadApplicationId(envelope)); + Assert.Equal("tests.game", RuntimeManifestEnvelope.ReadApplicationID(envelope)); Assert.Equal("studio/testgame", RuntimeManifestEnvelope.ReadPersistentDataPath(envelope)); GameRuntimeManifest manifest = RuntimeManifestEnvelope.Decode(envelope, serialization); Assert.Equal("studio/testgame", manifest.persistentDataPath); @@ -99,67 +107,95 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies GameRuntimeModule runtimeModule = Assert.Single(manifest.modules); Assert.Equal("RuntimeScripts", runtimeModule.name); Assert.Equal("Inno.GameScripts", Assert.Single(runtimeModule.assemblies).name); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoScripting, runtimeModule.domain); + Assert.Equal(AssemblyDomain.InnoScripting, runtimeModule.domain); string persistentRoot = Path.Combine(m_root, "Persistent", manifest.applicationId); RuntimeContentCatalog contentCatalog = serialization.Deserialize( - File.ReadAllBytes(Path.Combine(packagedContent, "catalog.inno"))); + File.ReadAllBytes(Path.Combine(packagedContent, "catalog.inno")) + ); contentCatalog.Validate(); using PackContentStore packStore = ContentPackReader.Open( File.OpenRead(Path.Combine(packagedContent, contentCatalog.packFileName)), - new ContentPackDescriptor(contentCatalog.contentHash, contentCatalog.packFileName), serialization); - using FileContentStore contentStore = await FileContentPreparation.PrepareAsync(packStore, - new FileContentCacheOptions(persistentRoot)); + new ContentPackDescriptor(contentCatalog.contentHash, contentCatalog.packFileName), + serialization + ); + using FileContentStore contentStore = await FileContentPreparation.PrepareAsync( + packStore, + new FileContentCacheOptions(persistentRoot) + ); using var runtimeAssets = new AssetDatabase( contentStore, serialization, runtimeTypes, new IdentityAllocator(), - residencyBudgetBytes: 0); + residencyBudgetBytes: 0 + ); Task> coldLoad = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene")).AsTask(); + AssetPath.Project("Scenes/Startup.iscene") + ).AsTask(); long preparingBytes = runtimeAssets.preparingBytes; Assert.True(preparingBytes > 0); using var coalescedCancellation = new CancellationTokenSource(); Task> coalesced = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"), coalescedCancellation.Token).AsTask(); + AssetPath.Project("Scenes/Startup.iscene"), + coalescedCancellation.Token + ).AsTask(); Assert.Equal(preparingBytes, runtimeAssets.preparingBytes); coalescedCancellation.Cancel(); Assert.False(coldLoad.IsCompleted); - Assert.True(SpinWait.SpinUntil(() => - { - runtimeAssets.CompletePendingLoads(); - return coldLoad.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + runtimeAssets.CompletePendingLoads(); + return coldLoad.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); using (AssetLease lease = await coldLoad) + { Assert.NotNull(lease.asset); + } Assert.True(coalesced.IsCanceled); Assert.Equal(0, runtimeAssets.preparingBytes); Assert.Equal(0, runtimeAssets.residencyStatistics.residentAssetCount); - using (var limited = new AssetDatabase(contentStore, serialization, runtimeTypes, - new IdentityAllocator(), preparationBudgetBytes: 1)) - { + using (var limited = new AssetDatabase( + contentStore, + serialization, + runtimeTypes, + new IdentityAllocator(), + preparationBudgetBytes: 1 + )) { Assert.Throws(() => limited.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"))); + AssetPath.Project("Scenes/Startup.iscene") + )); Assert.Equal(0, limited.preparingBytes); } using var loadCancellation = new CancellationTokenSource(); Task> canceledLoad = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"), loadCancellation.Token).AsTask(); + AssetPath.Project("Scenes/Startup.iscene"), + loadCancellation.Token + ).AsTask(); loadCancellation.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - runtimeAssets.CompletePendingLoads(); - return canceledLoad.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + runtimeAssets.CompletePendingLoads(); + return canceledLoad.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); Assert.True(canceledLoad.IsCanceled); Assert.True(contentStore.index.TryGetEntry(new ContentKey("AssetDatabase/Catalog.snapshot"), out _)); - Assert.DoesNotContain(contentStore.index.entries, static entry => entry.key.value!.StartsWith("Managed/", StringComparison.Ordinal)); Assert.DoesNotContain( contentStore.index.entries, - static entry => entry.key.value!.EndsWith(".iscene", StringComparison.OrdinalIgnoreCase) - || entry.key.value.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) - || entry.key.value.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)); + static entry => entry.key.value!.StartsWith("Managed/", StringComparison.Ordinal) + ); + Assert.DoesNotContain( + contentStore.index.entries, + static entry => ( + entry.key.value!.EndsWith(".iscene", StringComparison.OrdinalIgnoreCase) + || entry.key.value.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + || entry.key.value.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + ) + ); Assert.Equal(1, result.assetCount); Assert.Equal(1, result.runtimeAssemblyCount); } @@ -170,9 +206,7 @@ public async Task GameBuildWaitsForPendingStartupSceneImportBeforeValidation() AssetPath stagedPath = AssetPath.Project("Staged/Startup.iscene"); var scene = new GameScene("Startup"); scene.CreateObject("Player"); - Assert.True(m_assets.Save( - stagedPath, - SceneAsset.Capture(scene, m_engine.serialization, m_assets))); + Assert.True(m_assets.Save(stagedPath, SceneAsset.Capture(scene, m_engine.serialization, m_assets))); string stagedSource = Path.Combine(m_projectRoot, "Assets", "Staged", "Startup.iscene"); string destinationDirectory = Path.Combine(m_projectRoot, "Assets", "Scenes"); string destinationSource = Path.Combine(destinationDirectory, "Startup.iscene"); @@ -183,7 +217,7 @@ public async Task GameBuildWaitsForPendingStartupSceneImportBeforeValidation() BuildResult result = await m_pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = Path.Combine(m_root, "Builds", "PendingImport") }); @@ -207,10 +241,9 @@ public async Task BackgroundArtifactExportUsesAnOwnerThreadSerializationSnapshot public async Task BackgroundArtifactExportRejectsACorruptCurrentFormatManifest() { SaveStartupScene(); - string manifest = Assert.Single(Directory.EnumerateFiles( - m_assets.artifactRoot, - "manifest", - SearchOption.AllDirectories)); + string manifest = Assert.Single( + Directory.EnumerateFiles(m_assets.artifactRoot, "manifest", SearchOption.AllDirectories) + ); File.WriteAllBytes(manifest, [0x42, 0x41, 0x44]); InvalidDataException failure = await Assert.ThrowsAsync(() => @@ -233,17 +266,16 @@ public async Task ChangedAuthoringGenerationCannotCommitAMixedBuildSnapshot() m_compiler, m_supportPackRoot, [new GameBuildTargetBinding(target, target)], - CreateManagedDeployments()); + CreateManagedDeployments() + ); string outputRoot = Path.Combine(m_root, "Builds", "MixedGeneration"); Task build = pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = outputRoot }).AsTask(); - Assert.True(SpinWait.SpinUntil( - () => target.started.Task.IsCompleted, - TimeSpan.FromSeconds(2))); + Assert.True(SpinWait.SpinUntil(() => target.started.Task.IsCompleted, TimeSpan.FromSeconds(2))); Assert.True(m_assets.Save(AssetPath.Project("Changed.txt"), new TextAsset("new generation"))); target.release.SetResult(); @@ -265,21 +297,17 @@ public async Task CompilationFailureLeavesNoProductOrStagingDirectory() BuildResult result = await m_pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = outputRoot }); Assert.False(result.succeeded); Assert.Null(result.outputPath); - Assert.Contains(result.diagnostics, static diagnostic => - diagnostic.severity == BuildDiagnosticSeverity.Error); + Assert.Contains(result.diagnostics, static diagnostic => diagnostic.severity == BuildDiagnosticSeverity.Error); Assert.False(Directory.Exists(Path.Combine(outputRoot, "Test Game.app"))); if (Directory.Exists(outputRoot)) { - Assert.Empty(Directory.EnumerateDirectories( - outputRoot, - ".inno-build-*", - SearchOption.TopDirectoryOnly)); + Assert.Empty(Directory.EnumerateDirectories(outputRoot, ".inno-build-*", SearchOption.TopDirectoryOnly)); } } @@ -288,11 +316,13 @@ public async Task CompilationFailureLeavesNoProductOrStagingDirectory() public async Task CommittedGameReportsBackupCleanupAsAWarningWithoutLosingSuccess() { if (!OperatingSystem.IsWindows()) + { return; + } SaveStartupScene(); var request = new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("windows-x64")), + profile = CreateProfile(new BuildTargetID("windows-x64")), outputDirectory = Path.Combine(m_root, "Builds", "CleanupFailure") }; string previous = Path.Combine(request.outputDirectory, request.profile.productName + "-Windows-x64"); @@ -307,13 +337,20 @@ public async Task CommittedGameReportsBackupCleanupAsAWarningWithoutLosingSucces Assert.Equal(previous, current.outputPath); Assert.True(File.Exists(Path.Combine(current.outputPath!, "Test Game.exe"))); Assert.False(File.Exists(locked)); - Assert.Contains(current.diagnostics, static diagnostic => diagnostic.code == "INNO-BUILD-CLEANUP" - && diagnostic.severity == BuildDiagnosticSeverity.Warning); + Assert.Contains(current.diagnostics, static diagnostic => ( + diagnostic.code == "INNO-BUILD-CLEANUP" + && diagnostic.severity == BuildDiagnosticSeverity.Warning + )); } finally { - foreach (string retained in Directory.EnumerateFiles(request.outputDirectory, "retained-readonly.txt", SearchOption.AllDirectories)) + foreach (string retained in Directory.EnumerateFiles( + request.outputDirectory, + "retained-readonly.txt", + SearchOption.AllDirectories + )) { File.SetAttributes(retained, FileAttributes.Normal); + } } } @@ -323,13 +360,15 @@ public async Task CommittedGameRemainsSuccessfulWhenItsFinalProgressObserverThro SaveStartupScene(); BuildResult result = await m_pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("windows-x64")), + profile = CreateProfile(new BuildTargetID("windows-x64")), outputDirectory = Path.Combine(m_root, "Builds", "ProgressFailure") }, new CommitFailingProgress()); Assert.True(result.succeeded); Assert.True(File.Exists(Path.Combine(result.outputPath!, "Test Game.exe"))); - Assert.Contains(result.diagnostics, static diagnostic => diagnostic.code == "INNO-BUILD-PROGRESS" - && diagnostic.severity == BuildDiagnosticSeverity.Warning); + Assert.Contains(result.diagnostics, static diagnostic => ( + diagnostic.code == "INNO-BUILD-PROGRESS" + && diagnostic.severity == BuildDiagnosticSeverity.Warning + )); } [Fact] @@ -344,18 +383,16 @@ await Assert.ThrowsAnyAsync(() => m_pipeline.BuildGameAsync( new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = outputRoot }, - cancellationToken: cancellation.Token).AsTask()); + cancellationToken: cancellation.Token + ).AsTask()); Assert.False(Directory.Exists(Path.Combine(outputRoot, "Test Game.app"))); if (Directory.Exists(outputRoot)) { - Assert.Empty(Directory.EnumerateDirectories( - outputRoot, - ".inno-build-*", - SearchOption.TopDirectoryOnly)); + Assert.Empty(Directory.EnumerateDirectories(outputRoot, ".inno-build-*", SearchOption.TopDirectoryOnly)); } } @@ -368,7 +405,7 @@ public async Task GameBuildRejectsManagedProjectOutputWithoutLeavingAProduct() InvalidOperationException exception = await Assert.ThrowsAsync(() => m_pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = output }).AsTask()); @@ -380,21 +417,19 @@ public async Task GameBuildRejectsManagedProjectOutputWithoutLeavingAProduct() public async Task PluginBuildIsDeterministicSourceOnlyAndUsesTheInstallContract() { m_assets.CreateDirectory(AssetPath.Project("Content")); - Assert.True(m_assets.Save( - AssetPath.Project("Content/value.txt"), - new TextAsset("deterministic"))); + Assert.True(m_assets.Save(AssetPath.Project("Content/value.txt"), new TextAsset("deterministic"))); string firstPath = Path.Combine(m_root, "first.iplugin"); string secondPath = Path.Combine(m_root, "second.iplugin"); ValueTask firstBuild = m_pipeline.BuildPluginAsync(new PluginBuildRequest { - pluginId = "tests.export", + pluginID = "tests.export", displayName = "Export Test", outputPath = firstPath }); ValueTask secondBuild = m_pipeline.BuildPluginAsync(new PluginBuildRequest { - pluginId = "tests.export", + pluginID = "tests.export", displayName = "Export Test", outputPath = secondPath }); @@ -421,7 +456,8 @@ public async Task PluginBuildIsDeterministicSourceOnlyAndUsesTheInstallContract( PluginScanResult scan = new PluginSourceService( m_engine.serialization, installRoot, - Path.Combine(m_root, "InstallLibrary")).Scan(); + Path.Combine(m_root, "InstallLibrary") + ).Scan(); Assert.Empty(scan.diagnostics); PluginCandidate candidate = Assert.Single(scan.candidates); Assert.Equal("tests.export", candidate.manifest.pluginId); @@ -441,11 +477,12 @@ await Assert.ThrowsAnyAsync(() => m_pipeline.BuildPluginAsync( new PluginBuildRequest { - pluginId = "tests.canceled", + pluginID = "tests.canceled", displayName = "Canceled", outputPath = output }, - cancellationToken: cancellation.Token).AsTask()); + cancellationToken: cancellation.Token + ).AsTask()); Assert.False(File.Exists(output)); Assert.Empty(Directory.EnumerateFiles(m_root, "Canceled.iplugin.staging-*", SearchOption.TopDirectoryOnly)); diff --git a/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs b/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs index ae77d371e..9bb06eec2 100644 --- a/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs +++ b/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Managed; using Xunit; +using Inno.Build.Managed; namespace Inno.Build.Products.Tests; @@ -18,7 +18,9 @@ public void BindingRejectsMissingOrMismatchedComponentsBeforeAnyWork() Assert.Same(compiler, binding.compiler); Assert.Throws(() => new GameBuildTargetBinding(null!, compiler)); Assert.Throws(() => new GameBuildTargetBinding(packager, null!)); - Assert.Throws(() => new GameBuildTargetBinding(packager, new FixtureCompiler(new("other-target")))); + Assert.Throws( + () => new GameBuildTargetBinding(packager, new FixtureCompiler(new BuildTargetID("other-target"))) + ); } [Fact] @@ -41,10 +43,9 @@ public async Task ContentCompilerCanBeReplacedWithoutChangingPlatformPackaging() Assert.Equal(1, second.calls); } - private sealed class FixtureCompiler(BuildTargetId target) : IGameContentCompiler + private sealed class FixtureCompiler(BuildTargetID target) : IGameContentCompiler { - public BuildTargetId target { get; } = target; - internal int calls { get; private set; } + public BuildTargetID target { get; } = target; public ValueTask CompileAsync( GameBuildContentContext context, @@ -54,15 +55,17 @@ public ValueTask CompileAsync( calls++; return ValueTask.CompletedTask; } + + internal int calls { get; private set; } } private sealed class FixturePackager : IGameBuildTarget { - public BuildTargetId id => new("fixture-platform"); - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; + public BuildTargetID id => new("fixture-platform"); + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.coreClr; public string runtimeIdentifier => "fixture-rid"; public string displayName => "Fixture"; - internal int calls { get; private set; } + public void Validate(string directory) => throw new InvalidOperationException("Binding must not inspect output."); public ValueTask PackageAsync( @@ -72,5 +75,7 @@ public ValueTask PackageAsync( calls++; throw new InvalidOperationException("Content compilation must not call platform packaging."); } + + internal int calls { get; private set; } } } diff --git a/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs b/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs index 42f97ea40..f8f9556dc 100644 --- a/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs @@ -2,10 +2,10 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Managed; using Inno.Build.Managed.DotNet; using Inno.Build.Toolchains; -using Xunit; namespace Inno.Build.Products.Tests; @@ -28,7 +28,9 @@ public void DotNetProvidersConsumeAnOpenFrozenTargetSelection() Assert.Equal(4, catalog.GetSupportedDeployments("fixture-runtime").Count); Assert.Empty(catalog.GetSupportedDeployments("changed")); foreach (IManagedDeploymentCompiler compiler in compilers) + { Assert.Same(compiler, catalog.Resolve(compiler.id, "fixture-runtime")); + } } [Fact] @@ -36,9 +38,9 @@ public void OpenProviderCatalogDispatchesCustomIdentityWithoutPlatformBranches() { var compiler = new CustomCompiler(); var catalog = new ManagedDeploymentCatalog([compiler]); - Assert.Same(compiler, catalog.Resolve(new ManagedDeploymentId("custom-runtime"), "custom-target")); + Assert.Same(compiler, catalog.Resolve(new ManagedDeploymentID("custom-runtime"), "custom-target")); Assert.Throws(() => catalog.Resolve(compiler.id, "unsupported")); - Assert.Throws(() => catalog.Resolve(new ManagedDeploymentId("absent"), "custom-target")); + Assert.Throws(() => catalog.Resolve(new ManagedDeploymentID("absent"), "custom-target")); Assert.Throws(() => new ManagedDeploymentCatalog([compiler, compiler])); } @@ -46,24 +48,41 @@ public void OpenProviderCatalogDispatchesCustomIdentityWithoutPlatformBranches() public void CapabilityInputsAndPublicationArtifactsAreImmutable() { string[] targets = ["custom-target"]; - var capabilities = new ManagedDeploymentCapabilities(targets, - dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + var capabilities = new ManagedDeploymentCapabilities( + targets, + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); targets[0] = "replaced"; Assert.Equal("custom-target", Assert.Single(capabilities.runtimeIdentifiers)); string[] files = ["game.wasm"]; - var result = new ManagedDeploymentResult(new ManagedDeploymentId("custom-runtime"), - Path.GetTempPath(), "selected-sdk", files); + var result = new ManagedDeploymentResult( + new ManagedDeploymentID("custom-runtime"), + Path.GetTempPath(), + "selected-sdk", + files + ); files[0] = "replaced.wasm"; Assert.Equal("game.wasm", Assert.Single(result.files)); - Assert.Throws(() => new ManagedDeploymentResult(result.deployment, - result.outputDirectory, result.sdkIdentity, ["../outside"])); + Assert.Throws(() => new ManagedDeploymentResult( + result.deployment, + result.outputDirectory, + result.sdkIdentity, + ["../outside"] + )); } private sealed class CustomCompiler : IManagedDeploymentCompiler { - public ManagedDeploymentId id => new("custom-runtime"); + public ManagedDeploymentID id => new("custom-runtime"); + public ManagedDeploymentCapabilities capabilities { get; } = new( - ["custom-target"], dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + ["custom-target"], + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); public ValueTask CompileAsync( ManagedDeploymentRequest request, diff --git a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs index 563780a6f..2ef809273 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs @@ -22,10 +22,11 @@ public void EquivalentCheckoutSpellingsHaveOneRecipeIdentity() var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj"); Directory.CreateDirectory(Path.Combine(m_root, "build")); File.WriteAllText(Path.Combine(m_root, "build", "fixture.csproj"), ""); - NativeBuildContext Context(string path) => new NativeBuildContext(path, "release") - .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); - var plain = Context(m_root); - var separated = Context(m_root + Path.DirectorySeparatorChar); + NativeBuildContext Context(string path) + => new NativeBuildContext(path, "release") + .WithComponentOptions(owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + NativeBuildContext plain = Context(m_root); + NativeBuildContext separated = Context(m_root + Path.DirectorySeparatorChar); Assert.Equal(plain.engineRoot, separated.engineRoot); NativeBuildRecipe first = NativeBuildRecipe.CreateForComponent(plain, owner, "fixture", "fixture-target", [], [], []); NativeBuildRecipe second = NativeBuildRecipe.CreateForComponent(separated, owner, "fixture", "fixture-target", [], [], []); @@ -37,7 +38,9 @@ public void EquivalentCheckoutSpellingsHaveOneRecipeIdentity() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -51,8 +54,16 @@ public void SelectedCheckoutOwnsIntermediatesEvenWhenTheToolRunsFromAnotherCheck Assert.Equal(new PhysicalPathResolver().Resolve(m_root), context.engineRoot); Assert.Equal("release", context.configuration); - Assert.Equal(Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"), - context.GetNativeBuildRoot(new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"))); + Assert.Equal( + Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"), + context.GetNativeBuildRoot( + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ) + ) + ); Assert.NotEqual(TestRepository.GetRoot(typeof(NativeBuildContextTests).Assembly), context.engineRoot); Assert.False(Directory.Exists(Path.Combine(owner, "obj"))); } @@ -77,9 +88,11 @@ public async Task CanceledBuildDoesNotStartAComponentOrCreateIntermediates(bool cancellation.Cancel(); var context = new NativeBuildContext(m_root, "debug"); - await Assert.ThrowsAnyAsync(() => editor + await Assert.ThrowsAnyAsync(() => ( + editor ? new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Editor(), cancellation.Token) - : new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), cancellation.Token)); + : new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), cancellation.Token) + )); Assert.Single(Directory.EnumerateFileSystemEntries(m_root)); } @@ -90,7 +103,8 @@ public async Task UnresolvedToolchainsFailBeforeIntermediatesOrSourceDiscovery() CreateCheckout(); var context = new NativeBuildContext(m_root, "release"); InvalidOperationException failure = await Assert.ThrowsAsync( - () => new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), CancellationToken.None)); + () => new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), CancellationToken.None) + ); Assert.Contains("explicit target toolchain", failure.Message, StringComparison.Ordinal); Assert.Single(Directory.EnumerateFileSystemEntries(m_root)); } diff --git a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs index 1191a7f0b..8f4067fe9 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs @@ -24,11 +24,17 @@ public void OptionsFreezeOrderedDefinitionsAndRejectAmbiguousSdkOverrides() Assert.Equal("-DA=one", options.cmakeArguments[0]); Assert.Equal("config/profile.cs", Assert.Single(options.inputPaths)); Assert.Throws(() => new NativeComponentBuildOptions((NativeLibraryKind)99)); - foreach (string[] invalid in new[] { - new[] { "-DCMAKE_TOOLCHAIN_FILE=other" }, new[] { "-DINNO_COMPONENT_BRIDGE=other" }, new[] { "-DINNO_LIBRARY_KIND=SHARED" }, - new[] { "-DA=one", "-DA:STRING=two" }, new[] { "--build" }, new[] { "-DA=one\0two" } - }) + foreach (string[] invalid in new[] + { + new[] { "-DCMAKE_TOOLCHAIN_FILE=other" }, + ["-DINNO_COMPONENT_BRIDGE=other"], + ["-DINNO_LIBRARY_KIND=SHARED"], + ["-DA=one", "-DA:STRING=two"], + ["--build"], + ["-DA=one\0two"] + }) { Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Shared, invalid)); + } Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Static, inputPaths: ["../escape"])); Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Static, inputPaths: ["C:/absolute"])); } @@ -44,12 +50,28 @@ public async Task RecipeOwnedDefinitionsCannotBeReplacedBeforeAnyToolStarts() string tool = Path.Combine(root, "unexecutable.fixture"); File.WriteAllText(tool, "This file must never execute."); var owner = new NativeComponentDescriptor("fixture", "Native.csproj", "Build.csproj"); - var selection = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("Windows", "x64"), - new Dictionary { ["cmake"] = tool }, new Dictionary(), [], [], new NativeLinkPlan(".dll"), false); - var context = new NativeBuildContext(root, "debug").WithToolchain(selection).WithComponentOptions( - owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DLINKAGE:BOOL=OFF"])); - await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync(context, owner, root, - "fixture", ["-DLINKAGE=ON"], CancellationToken.None)); + var selection = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("Windows", "x64"), + new Dictionary { ["cmake"] = tool }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithToolchain(selection).WithComponentOptions( + owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DLINKAGE:BOOL=OFF"]) + ); + await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync( + context, + owner, + root, + "fixture", + ["-DLINKAGE=ON"], + CancellationToken.None + )); Assert.Equal(0, context.statistics.nativeProcesses); Assert.False(Directory.Exists(Path.Combine(root, "obj"))); } @@ -62,19 +84,28 @@ await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync [Fact] public void StaticRecipesDeclareOnlyNativeSourceRootsThatTheyActuallyConsume() { - var source = new NativeStaticBuildDefinition("build/Static.cmake", ["native/include", "native/src"], - ["fixture"], "native"); + var source = new NativeStaticBuildDefinition( + "build/Static.cmake", + ["native/include", "native/src"], + ["fixture"], + "native" + ); Assert.Equal("native", source.nativeSourceDirectory); Assert.Null(new NativeStaticBuildDefinition("build/Static.cmake", ["vendor"], ["fixture"]).nativeSourceDirectory); - Assert.Throws(() => new NativeStaticBuildDefinition("build/Static.cmake", ["vendor"], - ["fixture"], "undeclared/native")); + Assert.Throws(() => new NativeStaticBuildDefinition( + "build/Static.cmake", + ["vendor"], + ["fixture"], + "undeclared/native" + )); } [Fact] public void ProductPlanDeclaresStaticArchivesAndDoesNotGuessLinkageFromTheHost() { ProductNativeBuildPlan plan = BuildTestProducts.StaticPlayer(); - Assert.All(plan.steps, static step => { + Assert.All(plan.steps, static step => + { Assert.Equal(NativeLibraryKind.Static, step.options.libraryKind); Assert.NotEmpty(step.component.staticBuild!.logicalOutputs); }); @@ -94,26 +125,50 @@ public void LinkageOrderedArgumentsAndConfigurationBytesAllChangeRecipeIdentity( File.WriteAllText(Path.Combine(root, "component/Toolchain.csproj"), ""); string config = Path.Combine(root, "component/Profile.cs"); File.WriteAllText(config, "one"); - var owner = new NativeComponentDescriptor("fixture", "component/Native.csproj", "component/Toolchain.csproj"); + var owner = new NativeComponentDescriptor( + "fixture", + "component/Native.csproj", + "component/Toolchain.csproj" + ); string Identity(NativeComponentBuildOptions options) { - var context = new NativeBuildContext(root, "debug").WithComponentOptions(owner, options); - NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent(context, owner, "fixture", "fixture-target", [], [], [config]); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithComponentOptions(owner, options); + NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( + context, + owner, + "fixture", + "fixture-target", + [], + [], + [config] + ); foreach (NativeBuildInput input in recipe.inputs) { if (File.Exists(input.physicalPath) || Directory.Exists(input.physicalPath)) + { continue; + } Directory.CreateDirectory(Path.GetDirectoryName(input.physicalPath)!); File.WriteAllText(input.physicalPath, "executor"); } return NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs); } - var options = new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DA=one", "-DB=two"], ["component/Profile.cs"]); + var options = new NativeComponentBuildOptions( + NativeLibraryKind.Shared, + ["-DA=one", "-DB=two"], + ["component/Profile.cs"] + ); string identity = Identity(options); - Assert.NotEqual(identity, Identity(new(NativeLibraryKind.Static, options.cmakeArguments, options.inputPaths))); - Assert.NotEqual(identity, Identity(new(NativeLibraryKind.Shared, ["-DB=two", "-DA=one"], options.inputPaths))); + Assert.NotEqual( + identity, + Identity(new NativeComponentBuildOptions(NativeLibraryKind.Static, options.cmakeArguments, options.inputPaths)) + ); + Assert.NotEqual( + identity, + Identity(new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DB=two", "-DA=one"], options.inputPaths)) + ); DateTime timestamp = File.GetLastWriteTimeUtc(config); File.WriteAllText(config, "two"); File.SetLastWriteTimeUtc(config, timestamp); diff --git a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs index 5e3e08ced..2e3066008 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Build.Toolchains.MiniAudio; using Inno.Build.Toolchains.Sdl3; @@ -16,8 +18,13 @@ namespace Inno.Build.Products.Tests; public sealed class NativeRecipeClosureTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoRecipeClosureTests", Guid.NewGuid().ToString("N")); - private readonly NativeComponentDescriptor m_owner = new("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + + private readonly NativeComponentDescriptor m_owner = new( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); public NativeRecipeClosureTests() { @@ -47,17 +54,22 @@ public void BackendDeclarationUsesItsProducerOptionsWithoutGeneratingBindings(bo { NativeComponentDescriptor owner = audio ? MiniAudioToolchain.componentDescriptor : Sdl3Toolchain.componentDescriptor; Write(owner.toolchainProject, ""); - NativeBuildContext context = Context().WithComponentOptions(owner, new(NativeLibraryKind.Shared)); + NativeBuildContext context = Context().WithComponentOptions(owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); NativeBuildRecipe recipe = audio ? MiniAudioToolchain.CreateRecipe(context) : Sdl3Toolchain.CreateRecipe(context); Assert.Equal(owner.id, recipe.component); - Assert.Equal("fixture-target", recipe.targetId); + Assert.Equal("fixture-target", recipe.targetID); Assert.Contains(recipe.declarations, value => value == (audio ? "-DBUILD_SHARED_LIBS=ON" : "-DSDL_SHARED=ON")); - Assert.DoesNotContain(recipe.inputs, input => input.physicalPath.Contains("BuildUtils", StringComparison.Ordinal) - || input.physicalPath.Contains("BuildConstants", StringComparison.Ordinal)); + Assert.DoesNotContain(recipe.inputs, input => ( + input.physicalPath.Contains("BuildUtils", StringComparison.Ordinal) + || input.physicalPath.Contains("BuildConstants", StringComparison.Ordinal) + )); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); - NativeBuildContext staticContext = context.WithComponentOptions(owner, new(NativeLibraryKind.Static)); - Assert.Throws(() => audio - ? MiniAudioToolchain.CreateRecipe(staticContext) : Sdl3Toolchain.CreateRecipe(staticContext)); + NativeBuildContext staticContext = context.WithComponentOptions(owner, new NativeComponentBuildOptions(NativeLibraryKind.Static)); + Assert.Throws(() => ( + audio + ? MiniAudioToolchain.CreateRecipe(staticContext) + : Sdl3Toolchain.CreateRecipe(staticContext) + )); } [Theory] @@ -65,15 +77,17 @@ public void BackendDeclarationUsesItsProducerOptionsWithoutGeneratingBindings(bo [InlineData(true)] public void BridgeBackendDeclarationExcludesHostGeneratedOutput(bool ui) { - NativeComponentDescriptor owner = ui ? UiToolchain.componentDescriptor : TextToolchain.componentDescriptor; + NativeComponentDescriptor owner = ui ? UIToolchain.componentDescriptor : TextToolchain.componentDescriptor; Write(owner.toolchainProject, ""); Write(Path.GetDirectoryName(owner.nativeProject)! + "/Native/Generated/unused.cpp", "unselected host output"); - NativeBuildContext context = Context().WithComponentOptions(owner, new(NativeLibraryKind.Shared)); - NativeBuildRecipe recipe = ui ? UiToolchain.CreateRecipe(context) : TextToolchain.CreateRecipe(context); + NativeBuildContext context = Context().WithComponentOptions(owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + NativeBuildRecipe recipe = ui ? UIToolchain.CreateRecipe(context) : TextToolchain.CreateRecipe(context); Assert.Equal(owner.id, recipe.component); Assert.DoesNotContain(recipe.declarations, value => value.Contains("BRIDGE_ROOT", StringComparison.Ordinal)); - Assert.DoesNotContain(recipe.inputs, input => input.physicalPath.EndsWith("Native", StringComparison.Ordinal) - || input.physicalPath.Contains("Generated", StringComparison.Ordinal)); + Assert.DoesNotContain(recipe.inputs, input => ( + input.physicalPath.EndsWith("Native", StringComparison.Ordinal) + || input.physicalPath.Contains("Generated", StringComparison.Ordinal) + )); Assert.Contains(recipe.inputs, input => input.physicalPath.EndsWith("CMakeLists.txt", StringComparison.Ordinal)); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } @@ -82,58 +96,82 @@ public void BridgeBackendDeclarationExcludesHostGeneratedOutput(bool ui) public void ProductSourceDeclarationUsesEachSelectedOwnerWithoutExecutingProducers() { int declarations = 0; - var steps = new List(); + List steps = []; foreach (string id in new[] { "first", "second" }) { var owner = new NativeComponentDescriptor(id, m_owner.nativeProject, m_owner.toolchainProject); - steps.Add(new ProductNativeBuildStep(id, owner, new(NativeLibraryKind.Shared), id == "first" ? [] : ["first"], - static ( - context, - completed, - cancellation - ) => throw new Xunit.Sdk.XunitException("Input declaration must not compile."), - context => { - declarations++; - Assert.Equal(NativeLibraryKind.Shared, context.RequireComponentOptions(owner).libraryKind); - return new NativeBuildRecipe(owner, id, context.RequireToolchain().targetId, - [NativeBuildInput.FromPath(m_root, "input.cpp")], ["selected=" + id]); - }, - static ( - relative, - target - ) => relative)); + steps.Add( + new ProductNativeBuildStep( + id, + owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + id == "first" ? [] : ["first"], + static ( + context, + completed, + cancellation + ) => throw new XunitException("Input declaration must not compile."), + context => + { + declarations++; + Assert.Equal(NativeLibraryKind.Shared, context.RequireComponentOptions(owner).libraryKind); + return new NativeBuildRecipe( + owner, + id, + context.RequireToolchain().targetID, + [NativeBuildInput.FromPath(m_root, "input.cpp")], + ["selected=" + id] + ); + }, + static ( + relative, + target + ) => relative + ) + ); } var plan = new ProductNativeBuildPlan("fixture", steps); IReadOnlyList recipes = plan.CreateRecipes(Context()); Assert.Equal(2, declarations); - Assert.Equal(new[] { "first", "second" }, System.Linq.Enumerable.Select(recipes, static recipe => recipe.component)); + Assert.Equal(new[] { "first", "second" }, Enumerable.Select(recipes, static recipe => recipe.component)); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } [Fact] public void StandaloneStepsRejectMissingDeclarationsAndForeignRecipes() { - Assert.Throws(() => new ProductNativeBuildStep("fixture", m_owner, new(NativeLibraryKind.Shared), [], + Assert.Throws(() => new ProductNativeBuildStep( + "fixture", + m_owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], static ( context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), null, + ) => throw new XunitException("Validation must not compile."), + null, static ( relative, target - ) => relative)); - var step = new ProductNativeBuildStep("fixture", m_owner, new(NativeLibraryKind.Shared), [], + ) => relative + )); + var step = new ProductNativeBuildStep( + "fixture", + m_owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], static ( context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), - context => new NativeBuildRecipe(m_owner, "foreign", context.RequireToolchain().targetId, [], []), + ) => throw new XunitException("Validation must not compile."), + context => new NativeBuildRecipe(m_owner, "foreign", context.RequireToolchain().targetID, [], []), static ( relative, target - ) => relative); + ) => relative + ); Assert.Throws(() => new ProductNativeBuildPlan("fixture", [step]).CreateRecipes(Context())); } @@ -142,15 +180,19 @@ public async Task MissingGenerationPreventsPublicationBeforeProducerOrStaging() { NativeBuildContext context = Context(); bool produced = false; - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, Recipe(context), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), ( @scoped, output, cancellation - ) => { + ) => + { produced = true; return Task.CompletedTask; - })); + } + )); Assert.False(produced); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } @@ -165,33 +207,39 @@ public async Task PublisherBindsActualGenerationBytesAndIdentityAfterSourceDecla using NativeBindingGenerationResult firstGeneration = Generation("generation-a", generated, Path.GetDirectoryName(bridge)!); NativeBuildContext firstContext = Context().WithBindings(firstGeneration); int productions = 0; - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { productions++; - return File.WriteAllTextAsync(Path.Combine(output, "fixture.native"), File.ReadAllText(generated), cancellation); + return File.WriteAllTextAsync(Path.Combine(output, "fixture.native"), File.ReadAllText(generated), cancellationToken); } - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(firstContext, Recipe(firstContext), Produce); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(firstContext, Recipe(firstContext), ProduceAsync); DateTime timestamp = File.GetLastWriteTimeUtc(generated); if (changeBytes) { File.WriteAllText(generated, "other"); File.SetLastWriteTimeUtc(generated, timestamp); } - using NativeBindingGenerationResult nextGeneration = Generation(changeBytes ? "generation-a" : "generation-b", - generated, Path.GetDirectoryName(bridge)!); + using NativeBindingGenerationResult nextGeneration = Generation( + changeBytes ? "generation-a" : "generation-b", + generated, + Path.GetDirectoryName(bridge)! + ); NativeBuildContext nextContext = Context().WithBindings(nextGeneration); - using NativeBuildProduct next = await NativeArtifactPublisher.PublishAsync(nextContext, Recipe(nextContext), Produce); + using NativeBuildProduct next = await NativeArtifactPublisher.PublishAsync(nextContext, Recipe(nextContext), ProduceAsync); Assert.NotEqual(first.fingerprint, next.fingerprint); Assert.Equal(2, productions); Assert.Equal("first", File.ReadAllText(first.files[0])); Assert.Equal(changeBytes ? "other" : "first", File.ReadAllText(next.files[0])); - using NativeBindingGenerationResult hotGeneration = Generation(changeBytes ? "generation-a" : "generation-b", - generated, Path.GetDirectoryName(bridge)!); + using NativeBindingGenerationResult hotGeneration = Generation( + changeBytes ? "generation-a" : "generation-b", + generated, + Path.GetDirectoryName(bridge)! + ); NativeBuildContext hotContext = Context().WithBindings(hotGeneration); - using NativeBuildProduct hot = await NativeArtifactPublisher.PublishAsync(hotContext, Recipe(hotContext), Produce); + using NativeBuildProduct hot = await NativeArtifactPublisher.PublishAsync(hotContext, Recipe(hotContext), ProduceAsync); Assert.Equal(next.fingerprint, hot.fingerprint); Assert.Equal(2, productions); } @@ -199,22 +247,45 @@ CancellationToken cancellation public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } - private NativeBuildContext Context() => new NativeBuildContext(m_root, "release") - .WithToolchain(new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("Windows", "x64"), - new Dictionary { ["compiler"] = Path.Combine(m_root, "tools", "compiler") }, - new Dictionary(), [], [], new NativeLinkPlan(".dll"), false)) - .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); + private NativeBuildContext Context() + => new NativeBuildContext(m_root, "release") + .WithToolchain( + new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("Windows", "x64"), + new Dictionary { ["compiler"] = Path.Combine(m_root, "tools", "compiler") }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ) + ) + .WithComponentOptions(m_owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); private NativeBuildRecipe Recipe(NativeBuildContext context) { - NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent(context, m_owner, "fixture", "fixture-target", - [Path.Combine(m_root, "input.cpp")], ["compiler-options"], [Path.Combine(m_root, "build", "Producer.cs")]); + NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( + context, + m_owner, + "fixture", + "fixture-target", + [Path.Combine(m_root, "input.cpp")], + ["compiler-options"], + [Path.Combine(m_root, "build", "Producer.cs")] + ); foreach (NativeBuildInput input in recipe.inputs) + { if (!File.Exists(input.physicalPath) && !Directory.Exists(input.physicalPath)) + { Write(Path.GetRelativePath(m_root, input.physicalPath), "common executor"); + } + } return recipe; } @@ -223,18 +294,33 @@ private NativeBindingGenerationResult Generation( string generated, string bridge ) { - File.WriteAllText(Path.Combine(bridge, "compilation.json"), JsonSerializer.Serialize(new NativeBindingCompilation - { - roots = [new("generated", "", true, true)], files = [], includeDirectories = [], defines = [], compilerDefines = [], - cxxStandard = 0, cStandard = 0, requiredExports = [], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] - })); + File.WriteAllText( + Path.Combine(bridge, "compilation.json"), + JsonSerializer.Serialize(new NativeBindingCompilation + { + roots = [new NativeBindingSourceRoot("generated", string.Empty, true, true)], + files = [], + includeDirectories = [], + defines = [], + compilerDefines = [], + cxxStandard = 0, + cStandard = 0, + requiredExports = [], + staticExportSymbols = [], + staticExportAbi = string.Empty, + staticExportNames = [] + }) + ); return new(new Dictionary { [m_owner.nativeProject] = new() { - fingerprint = fingerprint, bindingsPath = generated, nativeDirectory = bridge, + fingerprint = fingerprint, + bindingsPath = generated, + nativeDirectory = bridge, usesRuntimeImports = false, - artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty + artifactDirectory = string.Empty, + artifactOwnerDirectory = string.Empty } }, []); } diff --git a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs index ea8f308bd..5aa778fec 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Xunit; using Inno.Build.Bindings; using Inno.Build.Composition; @@ -15,13 +16,17 @@ public sealed class PlatformBackendIntegrationTests [Fact] public void IntegrationsPreserveExactShaderAndNativeTargetIdentities() { - Assert.Equal("windows-x64", WindowsX64BgfxIntegration.nativeProfile.targetId); - Assert.Equal("macos-arm64", MacOSArm64BgfxIntegration.nativeProfile.targetId); - var context = new BuildCompositionContext("explicit-sdk", System.IO.Path.GetTempPath(), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); - var standard = StandardBuildDistribution.Create(context); - Assert.Same(WindowsX64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("windows-x64"))); - Assert.Same(MacOSArm64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("macos-arm64"))); - Assert.Same(BrowserWasm32BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("browser-wasm"))); + Assert.Equal("windows-x64", WindowsX64BgfxIntegration.nativeProfile.targetID); + Assert.Equal("macos-arm64", MacOSArm64BgfxIntegration.nativeProfile.targetID); + var context = new BuildCompositionContext( + "explicit-sdk", + Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ); + StandardBuildDistribution standard = StandardBuildDistribution.Create(context); + Assert.Same(WindowsX64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetID("windows-x64"))); + Assert.Same(MacOSArm64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetID("macos-arm64"))); + Assert.Same(BrowserWasm32BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetID("browser-wasm"))); } } diff --git a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs index 43249737d..abdf17be2 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs @@ -1,10 +1,12 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.Bindings; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; @@ -27,15 +29,24 @@ public void HostedTargetsCoverTheDistributionAndDeclareOneProducerHost() using JsonDocument packages = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(root, ".github", "native-targets.json"))); using JsonDocument hosts = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(root, ".github", "validation-hosts.json"))); JsonElement[] targets = packages.RootElement.EnumerateArray().ToArray(); - var runners = hosts.RootElement.EnumerateArray().ToDictionary(host => host.GetProperty("runner").GetString()!); - var distribution = BuildTestProducts.Distribution(); - Assert.Equal(distribution.availableTargets.Select(id => id.value), targets.Select(target => target.GetProperty("target").GetString()).Order(StringComparer.Ordinal)); + Dictionary runners = hosts.RootElement + .EnumerateArray() + .ToDictionary(host => host.GetProperty("runner").GetString()!); + BuildDistribution distribution = BuildTestProducts.Distribution(); + Assert.Equal( + distribution.availableTargets.Select(id => id.value), + targets.Select(target => target.GetProperty("target").GetString()).Order(StringComparer.Ordinal) + ); Assert.All(targets, target => { string runner = target.GetProperty("runner").GetString()!; string host = runners[runner].GetProperty("target").GetString()!; - Assert.Single(targets.Where(candidate => candidate.GetProperty("target").GetString() == host - && candidate.GetProperty("runner").GetString() == runner)); + Assert.Single( + targets.Where(candidate => ( + candidate.GetProperty("target").GetString() == host + && candidate.GetProperty("runner").GetString() == runner + )) + ); Assert.NotEmpty(target.GetProperty("configurations").EnumerateArray()); }); } @@ -52,8 +63,12 @@ public void SharedBackendSourcesKeepDistinctRuntimeBindingAndOfflineToolOwners(s Assert.NotEqual(runtime.id, tools.id); Assert.NotNull(runtime.bindingDefinition); Assert.Null(tools.bindingDefinition); - Assert.Single(editor.steps.Where(step => step.component.id == runtime.id - && step.component.nativeProject == runtime.nativeProject)); + Assert.Single( + editor.steps.Where(step => ( + step.component.id == runtime.id + && step.component.nativeProject == runtime.nativeProject + )) + ); } [Theory] @@ -63,19 +78,36 @@ public async Task RealPlatformPreflightRejectsUnavailableSdkOrHostWithoutCreatin { string output = Path.Combine(Path.GetTempPath(), "InnoPlatformPreflight", Guid.NewGuid().ToString("N")); string sdk = Path.Combine(output, "unavailable-dotnet.exe"); - var host = unsupportedHost ? new BuildHostDescriptor("MacOS", "arm64") - : new BuildHostDescriptor("Windows", "x64"); + BuildHostDescriptor host = unsupportedHost + ? new BuildHostDescriptor("MacOS", "arm64") + : new BuildHostDescriptor("Windows", "x64"); var source = new WindowsX64PlayerSupportPackSource( BuildTestProducts.Distribution().ResolveNativeProduct("windows-x64", "player"), - host, sdk, BuildTestProducts.Distribution().ResolveBindingGenerator("windows-x64"), new WindowsX64SupportPackValidator()); + host, + sdk, + BuildTestProducts.Distribution().ResolveBindingGenerator("windows-x64"), + new WindowsX64SupportPackValidator() + ); var publisher = new PlayerSupportPackPublisher([source]); if (unsupportedHost) + { await Assert.ThrowsAsync(() => publisher.PublishAsync( - TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), output, new BuildTargetId("windows-x64"), sdk).AsTask()); + TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), + output, + new BuildTargetID("windows-x64"), + sdk + ).AsTask()); + } else + { await Assert.ThrowsAsync(() => publisher.PublishAsync( - TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), output, new BuildTargetId("windows-x64"), sdk).AsTask()); + TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), + output, + new BuildTargetID("windows-x64"), + sdk + ).AsTask()); + } Assert.False(Directory.Exists(output)); } @@ -85,46 +117,70 @@ public void StaticComponentsHaveOneAggregateOwnerAndNoUnusedStandaloneProducer() { ProductNativeBuildPlan plan = BuildTestProducts.StaticPlayer(); - Assert.All(plan.steps, static step => { + Assert.All(plan.steps, static step => + { Assert.Null(step.build); Assert.NotNull(step.component.staticBuild); }); - Assert.Throws(() => new ProductNativeBuildStep("fixture", Step("fixture", []).component, new(NativeLibraryKind.Static), - [], null, null, static ( + Assert.Throws(() => new ProductNativeBuildStep( + "fixture", + Step("fixture", []).component, + new NativeComponentBuildOptions(NativeLibraryKind.Static), + [], + null, + null, + static ( relative, target - ) => relative)); + ) => relative + )); } [Fact] public void StandardShaderTargetIsIndependentOfTheOfflineToolTarget() { - var context = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ); StandardBuildDistribution distribution = StandardBuildDistribution.Create(context); - Assert.Same(BrowserWasm32BgfxShaderProfiles.target, - distribution.ResolveShaderTarget(new BuildTargetId("browser-wasm"))); + Assert.Same( + BrowserWasm32BgfxShaderProfiles.target, + distribution.ResolveShaderTarget(new BuildTargetID("browser-wasm")) + ); Assert.Throws(() => distribution.build.ResolveNativeProduct("linux-arm64", "shader-tools")); - Assert.Throws(() => distribution.ResolveShaderTarget(new("unregistered-target"))); + Assert.Throws(() => distribution.ResolveShaderTarget(new BuildTargetID("unregistered-target"))); Assert.Throws(() => distribution.build.ResolveNativeProduct("browser-wasm", "shader-tools")); } [Fact] public void DistributionDoesNotDeriveProductTargetsFromTheToolHost() { - var windows = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); - var apple = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("MacOS", "arm64"), new BuildTargetId("macos-arm64")); + var windows = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("windows-x64") + ); + var apple = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("MacOS", "arm64"), + new BuildTargetID("macos-arm64") + ); BuildDistribution first = StandardBuildDistribution.Create(windows).build; BuildDistribution second = StandardBuildDistribution.Create(apple).build; Assert.Equal(first.availableTargets, second.availableTargets); - Assert.Contains(new BuildTargetId("browser-wasm"), first.availableTargets); + Assert.Contains(new BuildTargetID("browser-wasm"), first.availableTargets); ProductNativeBuildPlan browser = first.ResolveNativeProduct("browser-wasm", "player").plan; - Assert.Equal(browser.steps.Select(static step => step.component.id), - second.ResolveNativeProduct("browser-wasm", "player").plan.steps.Select(static step => step.component.id)); + Assert.Equal( + browser.steps.Select(static step => step.component.id), + second.ResolveNativeProduct("browser-wasm", "player").plan.steps.Select(static step => step.component.id) + ); Assert.All(browser.steps, static step => { Assert.Equal(NativeLibraryKind.Static, step.options.libraryKind); @@ -132,8 +188,8 @@ public void DistributionDoesNotDeriveProductTargetsFromTheToolHost() Assert.NotNull(step.component.staticBuild); }); Assert.Throws(() => first.ResolveNativeProduct("browser-wasm", "editor")); - Assert.DoesNotContain(new BuildTargetId("desktop"), first.availableTargets); - Assert.DoesNotContain(new BuildTargetId("linux-x64"), first.availableTargets); + Assert.DoesNotContain(new BuildTargetID("desktop"), first.availableTargets); + Assert.DoesNotContain(new BuildTargetID("linux-x64"), first.availableTargets); Assert.Throws(() => first.ResolveNativeToolchain("linux-x64")); Assert.Throws(() => first.ResolveNativeToolchain("fixture-unregistered")); Assert.Equal("x64", WindowsX64BuildModule.target.architecture); @@ -157,8 +213,8 @@ string target var context = new NativeBuildContext(root, "debug"); var host = new BuildHostDescriptor(system, architecture); INativeToolchainProvider provider = target == "macos-arm64" - ? new MacOSArm64NativeToolchainProvider("deliberately-unavailable-sdk") - : new WindowsX64NativeToolchainProvider("deliberately-unavailable-sdk"); + ? new MacOSArm64NativeToolchainProvider("deliberately-unavailable-sdk") + : new WindowsX64NativeToolchainProvider("deliberately-unavailable-sdk"); await Assert.ThrowsAsync(() => provider.ResolveAsync(context, host, target, CancellationToken.None).AsTask()); @@ -196,10 +252,14 @@ public async Task UnselectedToolchainAndCancellationNeverRunAComponentProducer() { var context = new NativeBuildContext(root, "debug"); var plan = new ProductNativeBuildPlan("fixture-product", [Step("first", [])]); - await Assert.ThrowsAsync(() => new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None)); + await Assert.ThrowsAsync( + () => new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None) + ); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token) + ); Assert.False(Directory.Exists(Path.Combine(root, "artifacts"))); } finally @@ -211,17 +271,24 @@ public async Task UnselectedToolchainAndCancellationNeverRunAComponentProducer() private static ProductNativeBuildStep Step( string id, string[] dependencies - ) => new(id, new NativeComponentDescriptor(id, - "backends/Fixture/native/Inno.Native.Fixture/Inno.Native.Fixture.csproj", - "backends/Fixture/build/Inno.Build.Toolchains.Fixture/Inno.Build.Toolchains.Fixture.csproj"), new(NativeLibraryKind.Shared), dependencies, + ) => new( + id, + new NativeComponentDescriptor( + id, + "backends/Fixture/native/Inno.Native.Fixture/Inno.Native.Fixture.csproj", + "backends/Fixture/build/Inno.Build.Toolchains.Fixture/Inno.Build.Toolchains.Fixture.csproj" + ), + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + dependencies, static ( context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Preflight must not execute a component producer."), - static context => throw new Xunit.Sdk.XunitException("Preflight must reject missing tools before source declaration."), + ) => throw new XunitException("Preflight must not execute a component producer."), + static context => throw new XunitException("Preflight must reject missing tools before source declaration."), static ( relative, target - ) => relative); + ) => relative + ); } diff --git a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs index e25ce32e4..9090b14d6 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs @@ -3,14 +3,14 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Assets.Pipeline; -using Inno.Build.Toolchains; using Inno.Build.Distribution.Standard; +using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx.Shaders; using Inno.Core.IO; using Inno.Integration.WindowsX64.Bgfx; using Inno.Rendering; -using Xunit; namespace Inno.Build.Products.Tests; @@ -18,7 +18,10 @@ public sealed class ShaderBuildInputsTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoShaderInputs", Guid.NewGuid().ToString("N")); - public ShaderBuildInputsTests() => Directory.CreateDirectory(m_root); + public ShaderBuildInputsTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void LivePublicationIsNotAnAssetButPermanentImportSettingsAreBuildInputs() @@ -30,7 +33,7 @@ public void LivePublicationIsNotAnAssetButPermanentImportSettingsAreBuildInputs( ShaderBuildInputs baseline = ShaderBuildInputs.Capture(m_root); string fingerprint = baseline.fingerprint; string candidate = source + ".imeta.staging-" + Guid.NewGuid().ToString("N"); - using (FileStream publication = new(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var publication = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { publication.Write("not yet published"u8); Assert.True(AssetSourcePolicy.defaultPolicy.IsIgnored(Path.GetFileName(candidate), false)); @@ -73,7 +76,7 @@ public void SourceNoiseDoesNotWeakenExplicitNativeInputDeclarations() { string candidate = Path.Combine(m_root, "source.staging-" + Guid.NewGuid().ToString("N")); File.WriteAllText(candidate, "first"); - NativeBuildInput[] explicitInputs = [new("explicit-input", candidate)]; + NativeBuildInput[] explicitInputs = [new NativeBuildInput("explicit-input", candidate)]; string before = NativeBuildFingerprint.Create([], explicitInputs); File.WriteAllText(candidate, "other"); Assert.NotEqual(before, NativeBuildFingerprint.Create([], explicitInputs)); @@ -109,7 +112,13 @@ public async Task FailedImportDoesNotWriteTheAuthoringTreeOrReplaceAnExistingArt ShaderBuildInputs inputs = ShaderBuildInputs.Capture(sources); using ProcessOwnedDirectory compilation = await ProcessOwnedDirectory.CreateAsync(Path.Combine(m_root, "requests")); Assert.Throws(() => ShaderArtifactBuilder.CompileGraphicsProgram( - inputs, compilation, "invalid.ishader", WindowsX64BgfxIntegration.shaderProfile, GraphicsApi.Direct3D12, output)); + inputs, + compilation, + "invalid.ishader", + WindowsX64BgfxIntegration.shaderProfile, + GraphicsApi.direct3D12, + output + )); Assert.Equal(original, Directory.GetFiles(sources)); Assert.Equal(bytes, File.ReadAllBytes(original.Single())); Assert.Equal("last good artifact", File.ReadAllText(output)); @@ -127,8 +136,14 @@ public async Task CancellationCannotPublishAnArtifact() File.WriteAllText(output, "last good artifact"); using ProcessOwnedDirectory compilation = await ProcessOwnedDirectory.CreateAsync(Path.Combine(m_root, "requests")); Assert.Throws(() => ShaderArtifactBuilder.CompileGraphicsProgram( - inputs, compilation, "graph.ishader", WindowsX64BgfxIntegration.shaderProfile, GraphicsApi.Direct3D12, output, - cancellationToken: canceled.Token)); + inputs, + compilation, + "graph.ishader", + WindowsX64BgfxIntegration.shaderProfile, + GraphicsApi.direct3D12, + output, + cancellationToken: canceled.Token + )); Assert.Equal("last good artifact", File.ReadAllText(output)); } @@ -140,7 +155,7 @@ public async Task CompilationWorkspaceMetadataUsesTheExistingRegisteredRetiremen { directory = workspace.directory; Assert.True(Directory.Exists(directory)); - var registration = Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); + BuildCacheOwnerDescriptor registration = Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); Assert.Equal("shader-requests", registration.id); Assert.Equal(Path.GetDirectoryName(directory), registration.directory); } diff --git a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs index b8f6c5ec4..4e3b17149 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs @@ -20,21 +20,49 @@ public void OfflineToolsExcludeCmakeWhileRuntimeBindingsKeepTheSelectedSdk() string owner = Path.Combine(root, "platforms", "WindowsX64", "integrations", "Inno.Integration.WindowsX64.Bgfx"); Directory.CreateDirectory(owner); foreach (string file in new[] { "WindowsX64BgfxToolContribution.cs", "WindowsX64BgfxBuildProfile.cs" }) + { File.WriteAllText(Path.Combine(owner, file), "declared integration input"); + } var tools = new Dictionary(); foreach (string name in new[] { "cl", "msbuild", "genie", "cmake", "dotnet" }) { tools[name] = Path.Combine(root, name + ".exe"); File.WriteAllText(tools[name], "frozen executable input"); } - var sdk = new NativeToolchainSelection("windows-x64", new BuildHostDescriptor("Windows", "x64"), - tools, new Dictionary(), [], ["-G", "Fixture"], new NativeLinkPlan(".dll"), true); - NativeToolchainSelection first = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(sdk), true); - NativeToolchainSelection runtime = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(sdk), false); + var sdk = new NativeToolchainSelection( + "windows-x64", + new BuildHostDescriptor("Windows", "x64"), + tools, + new Dictionary(), + [], + ["-G", "Fixture"], + new NativeLinkPlan(".dll"), + true + ); + NativeToolchainSelection first = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(sdk), + true + ); + NativeToolchainSelection runtime = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(sdk), + false + ); tools["dotnet"] = Path.Combine(root, "another-dotnet.exe"); File.WriteAllText(tools["dotnet"], "another managed SDK"); - var otherSdk = new NativeToolchainSelection("windows-x64", sdk.host, tools, sdk.environment, [], sdk.cmakeArguments, new NativeLinkPlan(".dll"), true); - NativeToolchainSelection second = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(otherSdk), true); + var otherSdk = new NativeToolchainSelection( + "windows-x64", + sdk.host, + tools, + sdk.environment, + [], + sdk.cmakeArguments, + new NativeLinkPlan(".dll"), + true + ); + NativeToolchainSelection second = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(otherSdk), + true + ); Assert.Equal(first.declarations, second.declarations); Assert.Equal(first.inputPaths, second.inputPaths); @@ -47,7 +75,9 @@ public void OfflineToolsExcludeCmakeWhileRuntimeBindingsKeepTheSelectedSdk() Assert.Equal(sdk.cmakeArguments, runtime.cmakeArguments); Assert.False(runtime.TryResolveExecutable("dotnet", out _)); string archive = Path.Combine(root, "bridge.lib"); - var linking = WindowsX64BgfxIntegration.nativeProfile.CreateBindingLinkSettings(archive); + (string reference, IReadOnlyList arguments) linking = WindowsX64BgfxIntegration.nativeProfile.CreateBindingLinkSettings( + archive + ); Assert.Equal(Path.Combine(root, "bridge"), linking.reference); Assert.Equal(["/WHOLEARCHIVE:\"" + archive + "\""], linking.arguments); } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs index 91ec81caf..3153a2b8b 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.Text; -using Inno.Build.SupportPacks; using Xunit; +using Inno.Build.SupportPacks; namespace Inno.Build.SupportPacks.Tests; @@ -15,8 +15,13 @@ public void ACustomBackendUsesItsDeclaredGroupWithoutStandardLibraryNames() { Write("PlayerLink/References/Custom.Runtime.dll"); Write("native/custom/fixture-target/arbitrary-name.fixture"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/References/Custom.Runtime.dll"], "native", ["custom/fixture-target"], ".fixture"); + var requirements = new PlayerSupportPackRequirements( + new BuildTargetID("fixture-target"), + ["PlayerLink/References/Custom.Runtime.dll"], + "native", + ["custom/fixture-target"], + ".fixture" + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); validator.Validate(m_root); Write("native/unselected/fixture-target/another.fixture"); @@ -27,8 +32,13 @@ public void ACustomBackendUsesItsDeclaredGroupWithoutStandardLibraryNames() public void MissingDeclaredArchiveFailsEvenWhenItsGroupContainsAnotherArchive() { Write("PlayerLink/Native/custom/fixture-target/other.a"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/Native/custom/fixture-target/required.a"], "PlayerLink/Native", ["custom/fixture-target"], ".a"); + var requirements = new PlayerSupportPackRequirements( + new BuildTargetID("fixture-target"), + ["PlayerLink/Native/custom/fixture-target/required.a"], + "PlayerLink/Native", + ["custom/fixture-target"], + ".a" + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); InvalidDataException missing = Assert.Throws(() => validator.Validate(m_root)); Assert.Contains("required.a", missing.Message); @@ -40,9 +50,14 @@ public void MissingDeclaredArchiveFailsEvenWhenItsGroupContainsAnotherArchive() public void StaticClosureRejectsAnAdditionalArchive(string extra) { Write("PlayerLink/Native/custom/fixture-target/required.a"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/Native/custom/fixture-target/required.a"], "PlayerLink/Native", - ["custom/fixture-target"], ".a", ["custom/fixture-target/required.a"]); + var requirements = new PlayerSupportPackRequirements( + new BuildTargetID("fixture-target"), + ["PlayerLink/Native/custom/fixture-target/required.a"], + "PlayerLink/Native", + ["custom/fixture-target"], + ".a", + ["custom/fixture-target/required.a"] + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); validator.Validate(m_root); Write("PlayerLink/Native/" + extra); @@ -54,13 +69,20 @@ public void StaticClosureRejectsAnAdditionalArchive(string extra) [InlineData("native/../outside")] [InlineData("C:/outside")] public void RequirementPathsCannotEscapeTheirOwner(string path) - => Assert.Throws(() => new PlayerSupportPackRequirements(new("fixture-target"), - [path], "native", ["custom"], ".fixture")); + => Assert.Throws(() => new PlayerSupportPackRequirements( + new BuildTargetID("fixture-target"), + [path], + "native", + ["custom"], + ".fixture" + )); public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private void Write(string relative) diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs index 1f2eec3bd..6b11afc12 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs @@ -1,19 +1,19 @@ using System; using System.IO; -using System.Runtime.Versioning; using System.Linq; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.SupportPacks; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.SupportPacks.Tests; public sealed class SupportPackPreparationCacheTests : IDisposable { - private static readonly BuildTargetId S_TARGET = new("fixture-target"); + private static readonly BuildTargetID TARGET = new("fixture-target"); private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoPackPreparationCache", Guid.NewGuid().ToString("N")); private readonly Source m_source; @@ -31,25 +31,33 @@ public async Task IdenticalPreparationSkipsProducerAndDamagedOutputsRequireRepai string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); string directory; - using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { directory = first.directory; - string current = Path.Combine(output, S_TARGET.value, "current"); + } + string current = Path.Combine(output, TARGET.value, "current"); File.SetLastWriteTimeUtc(current, DateTime.UtcNow.AddDays(-1)); DateTime selectedAt = File.GetLastWriteTimeUtc(current); - using (PlayerSupportPackPublication repeated = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication repeated = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { Assert.Equal(directory, repeated.directory); + } Assert.Equal(selectedAt, File.GetLastWriteTimeUtc(current)); Assert.Equal(1, m_source.preparations); string file = Path.Combine(directory, "References", "Inno.Fixture.dll"); DateTime timestamp = File.GetLastWriteTimeUtc(file); File.WriteAllText(file, "other"); File.SetLastWriteTimeUtc(file, timestamp); - using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { Assert.Equal("first", File.ReadAllText(Path.Combine(repaired.directory, "References", "Inno.Fixture.dll"))); + } Assert.Equal(2, m_source.preparations); File.WriteAllText(Path.Combine(directory, "References", "Extra.dll"), "extra"); - using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { Assert.Single(Directory.EnumerateFiles(Path.Combine(repaired.directory, "References"))); + } Assert.Equal(3, m_source.preparations); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } @@ -60,17 +68,25 @@ public async Task RetiringAnOldPackAlsoRetiresItsPreparationIndex() string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); string previous; - using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { previous = first.directory; - string indexes = Path.Combine(output, S_TARGET.value, ".preparations"); + } + string indexes = Path.Combine(output, TARGET.value, ".preparations"); string oldIndex = Assert.Single(Directory.GetFiles(indexes)); File.WriteAllText(Path.Combine(m_root, "input.txt"), "changed"); string current; - using (PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { current = second.directory; + } - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, - [new BuildCachePublisher(output, BuildCacheArtifactRole.ImmutableArtifact).Describe("packs")], new(), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [new BuildCachePublisher(output, BuildCacheArtifactRole.ImmutableArtifact).Describe("packs")], + new BuildCachePolicy(), + retireAll: true + ); Assert.Empty((await plan.ExecuteAsync()).failures); Assert.False(Directory.Exists(previous)); Assert.False(File.Exists(oldIndex)); @@ -83,8 +99,10 @@ public async Task ConcurrentIdenticalRequestsPrepareOnlyOneCandidate() { string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); - PlayerSupportPackPublication[] readers = await Task.WhenAll(Enumerable.Range(0, 4) - .Select(_ => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask())); + PlayerSupportPackPublication[] readers = await Task.WhenAll( + Enumerable.Range(0, 4) + .Select(_ => publisher.PublishAsync(m_root, output, TARGET, "unused").AsTask()) + ); try { Assert.All(readers, reader => Assert.Equal(readers[0].directory, reader.directory)); @@ -93,7 +111,9 @@ public async Task ConcurrentIdenticalRequestsPrepareOnlyOneCandidate() finally { foreach (PlayerSupportPackPublication reader in readers) + { reader.Dispose(); + } } } @@ -106,12 +126,12 @@ public async Task InputMutationDuringOutputValidationRejectsSelectionAndPreserve var publisher = new PlayerSupportPackPublisher([m_source]); if (cacheHit) { - using PlayerSupportPackPublication prior = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication prior = await publisher.PublishAsync(m_root, output, TARGET, "unused"); } - string current = Path.Combine(output, S_TARGET.value, "current"); + string current = Path.Combine(output, TARGET.value, "current"); string? previous = File.Exists(current) ? File.ReadAllText(current) : null; m_source.onValidate = () => File.WriteAllText(Path.Combine(m_root, "input.txt"), "other"); - await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, TARGET, "unused").AsTask()); Assert.Equal(1, m_source.preparations); Assert.Equal(previous, File.Exists(current) ? File.ReadAllText(current) : null); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); @@ -122,22 +142,24 @@ public async Task PreparationIndexFailureReportsCommittedPublicationWithoutThrow { string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); - using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, TARGET, "unused")) + { Assert.Empty(first.diagnostics); - string current = Path.Combine(output, S_TARGET.value, "current"); + } + string current = Path.Combine(output, TARGET.value, "current"); string previous = File.ReadAllText(current); File.WriteAllText(Path.Combine(m_root, "input.txt"), "other"); m_source.onPrepared = _ => { - string index = Path.Combine(output, S_TARGET.value, ".preparations"); + string index = Path.Combine(output, TARGET.value, ".preparations"); Directory.Move(index, index + ".saved"); File.WriteAllText(index, "blocked"); }; - using PlayerSupportPackPublication published = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication published = await publisher.PublishAsync(m_root, output, TARGET, "unused"); Assert.NotEqual(previous, File.ReadAllText(current)); Assert.Contains(published.diagnostics, static message => message.Contains("preparation index", StringComparison.Ordinal)); Assert.Equal("other", File.ReadAllText(Path.Combine(published.directory, "References", "Inno.Fixture.dll"))); - using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(S_TARGET, m_source); + using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(TARGET, m_source); Assert.Equal(published.directory, selected.directory); } @@ -146,7 +168,9 @@ public async Task PreparationIndexFailureReportsCommittedPublicationWithoutThrow public async Task PostCommitStagingCleanupFailurePreservesReadingOwnership() { if (!OperatingSystem.IsWindows()) + { return; + } string output = Path.Combine(m_root, "Packs"); FileStream? blocker = null; m_source.onPrepared = staging => @@ -157,7 +181,7 @@ public async Task PostCommitStagingCleanupFailurePreservesReadingOwnership() try { using PlayerSupportPackPublication published = await new PlayerSupportPackPublisher([m_source]) - .PublishAsync(m_root, output, S_TARGET, "unused"); + .PublishAsync(m_root, output, TARGET, "unused"); Assert.Contains(published.diagnostics, static message => message.Contains("could not be removed", StringComparison.Ordinal)); Assert.True(File.Exists(Path.Combine(published.directory, "References", "Inno.Fixture.dll"))); ProcessOwnedDirectoryDescriptor retained = Assert.Single(ProcessOwnedDirectory.ReadClaims(output)); @@ -177,9 +201,9 @@ public async Task ChangedInputAfterOwnershipWaitNeverEntersPreparation() var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); m_source.onPlan = entered.SetResult; Task waiting; - using (FileLease owner = await FileLease.AcquireAsync(Path.Combine(output, S_TARGET.value + ".lock"), TimeSpan.FromSeconds(5))) + using (FileLease owner = await FileLease.AcquireAsync(Path.Combine(output, TARGET.value + ".lock"), TimeSpan.FromSeconds(5))) { - waiting = new PlayerSupportPackPublisher([m_source]).PublishAsync(m_root, output, S_TARGET, "unused").AsTask(); + waiting = new PlayerSupportPackPublisher([m_source]).PublishAsync(m_root, output, TARGET, "unused").AsTask(); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); DateTime timestamp = File.GetLastWriteTimeUtc(Path.Combine(m_root, "input.txt")); File.WriteAllText(Path.Combine(m_root, "input.txt"), "other"); @@ -187,7 +211,7 @@ public async Task ChangedInputAfterOwnershipWaitNeverEntersPreparation() } await Assert.ThrowsAsync(() => waiting); Assert.Equal(0, m_source.preparations); - Assert.False(File.Exists(Path.Combine(output, S_TARGET.value, "current"))); + Assert.False(File.Exists(Path.Combine(output, TARGET.value, "current"))); } public void Dispose() => Directory.Delete(m_root, recursive: true); @@ -199,7 +223,7 @@ private sealed class Source(string input) : IPlayerSupportPackSource public Action? onPlan { get; set; } public Action? onValidate { get; set; } public Action? onPrepared { get; set; } - public BuildTargetId target => S_TARGET; + public BuildTargetID target => TARGET; public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, @@ -223,12 +247,15 @@ private sealed class Plan( Source owner, string identity, string content - ) : PlayerSupportPackPlan(S_TARGET, identity) { + ) : PlayerSupportPackPlan(TARGET, identity) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (owner.Identity() != preparationIdentity) + { throw new InvalidOperationException("Fixture source input changed after planning."); + } return ValueTask.CompletedTask; } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs index 455eb1a72..f32683d21 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs @@ -1,17 +1,21 @@ using System; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; -using Inno.Build.SupportPacks; using Xunit; +using Xunit.Sdk; +using Inno.Build.SupportPacks; namespace Inno.Build.SupportPacks.Tests; public sealed class SupportPackPublisherTests : IDisposable { + private static readonly BuildTargetID TARGET = new("tests-target"); + private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoPackTransactionTests", Guid.NewGuid().ToString("N")); - private static readonly BuildTargetId S_TARGET = new("tests-target"); public SupportPackPublisherTests() { @@ -24,7 +28,13 @@ public SupportPackPublisherTests() [Fact] public async Task SourceProvisioningRetainsConsumeOnlySelectionBeforePublication() { - string declaration = Path.Combine(m_root, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj"); + string declaration = Path.Combine( + m_root, + "build", + "distributions", + "Inno.Build.Distribution.Standard", + "Inno.Build.Distribution.Standard.csproj" + ); Directory.CreateDirectory(Path.GetDirectoryName(declaration)!); File.WriteAllText(declaration, ""); string selection = Path.Combine(m_root, "selection.json"); @@ -33,15 +43,21 @@ public async Task SourceProvisioningRetainsConsumeOnlySelectionBeforePublication var source = new PlanningSource(( context, token - ) => { + ) => + { attempts++; Assert.Equal(selection, context.nativeDependencies); throw new FileNotFoundException("The selected dependency package is unavailable."); }); - var provisioner = new SourcePlayerSupportPackProvisioner(m_root, new PlayerSupportPackPublisher([source]), - "unused", static diagnostic => throw new InvalidOperationException(diagnostic), selection); + var provisioner = new SourcePlayerSupportPackProvisioner( + m_root, + new PlayerSupportPackPublisher([source]), + "unused", + static diagnostic => throw new InvalidOperationException(diagnostic), + selection + ); - await Assert.ThrowsAsync(() => provisioner.ProvisionAsync(S_TARGET, output).AsTask()); + await Assert.ThrowsAsync(() => provisioner.ProvisionAsync(TARGET, output).AsTask()); Assert.Equal(1, attempts); Assert.False(Directory.Exists(output)); @@ -57,19 +73,25 @@ public async Task PreflightFailuresLeaveNoPublicationDirectory(string failure) var source = new PlanningSource(( context, token - ) => { + ) => + { Assert.False(Directory.Exists(output)); if (failure == "missing-sdk") + { throw new FileNotFoundException("The selected SDK is absent."); - return ValueTask.FromResult(failure == "null-plan" - ? null! : new ForeignPlan()); + } + return ValueTask.FromResult(failure == "null-plan" ? null! : new ForeignPlan()); }); var publisher = new PlayerSupportPackPublisher([source]); if (failure == "missing-sdk") - await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + { + await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, TARGET, "unused").AsTask()); + } else - await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + { + await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, TARGET, "unused").AsTask()); + } Assert.False(Directory.Exists(output)); } @@ -81,13 +103,15 @@ public async Task CancellationDuringPlanningLeavesNoOutputAndExecutesNoPlan() var source = new PlanningSource(( context, token - ) => { + ) => + { cancellation.Cancel(); - return ValueTask.FromResult(new ForeignPlan(S_TARGET)); + return ValueTask.FromResult(new ForeignPlan(TARGET)); }); await Assert.ThrowsAnyAsync(() => new PlayerSupportPackPublisher([source]) - .PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + .PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token) + .AsTask()); Assert.False(Directory.Exists(output)); } @@ -100,13 +124,19 @@ public async Task PreparedPlanIsExecutedOnceWithoutRepeatingDiscovery() var source = new PlanningSource(async ( context, token - ) => { + ) => + { Assert.False(Directory.Exists(output)); planningCount++; return await new TestSource(null, payload: "frozen").CreatePlanAsync(context, token); }); - using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([source]).PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([source]).PublishAsync( + m_root, + output, + TARGET, + "unused" + ); string installed = installedLease.directory; Assert.Equal(1, planningCount); @@ -117,7 +147,12 @@ public async Task PreparedPlanIsExecutedOnceWithoutRepeatingDiscovery() public async Task RegisteredCustomTargetInstallsWithoutCorePlatformBranches() { var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); - using PlayerSupportPackPublication installedLease = await publisher.PublishAsync(m_root, Path.Combine(m_root, "Packs"), S_TARGET, "unused"); + using PlayerSupportPackPublication installedLease = await publisher.PublishAsync( + m_root, + Path.Combine(m_root, "Packs"), + TARGET, + "unused" + ); string installed = installedLease.directory; Assert.True(File.Exists(Path.Combine(installed, "References", "Inno.Test.dll"))); Assert.Single(Directory.EnumerateDirectories(Path.Combine(m_root, "Packs"))); @@ -128,10 +163,14 @@ public async Task FailedPreparationPreservesInstalledPackAndRemovesStaging() { string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + TARGET, + "unused" + ); string installed = installedLease.directory; var publisher = new PlayerSupportPackPublisher([new TestSource(new InvalidDataException("invalid candidate"))]); - await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, TARGET, "unused").AsTask()); Assert.Equal("candidate", File.ReadAllText(Path.Combine(installed, "References", "Inno.Test.dll"))); Assert.Single(Directory.EnumerateDirectories(output)); } @@ -144,7 +183,8 @@ public async Task CancellationRejectsCandidateBeforeInstallation() var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); string output = Path.Combine(m_root, "Packs"); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token).AsTask() + ); Assert.False(Directory.Exists(output)); } @@ -158,12 +198,17 @@ public async Task CancellationDuringValidationPreservesTheInstalledPack() using var cancellation = new CancellationTokenSource(); string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + TARGET, + "unused" + ); string installed = installedLease.directory; var publisher = new PlayerSupportPackPublisher([new TestSource(null, cancellation.Cancel)]); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token).AsTask() + ); Assert.Equal("candidate", File.ReadAllText(Path.Combine(installed, "References", "Inno.Test.dll"))); Assert.Single(Directory.EnumerateDirectories(output)); @@ -174,18 +219,23 @@ public async Task NewPublicationRetainsTheImmutableInputsHeldByEarlierReaders() { string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication previousLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + TARGET, + "unused" + ); string previous = previousLease.directory; using FileStream reader = File.OpenRead(Path.Combine(previous, "References", "Inno.Test.dll")); - using PlayerSupportPackPublication currentLease = await new PlayerSupportPackPublisher([new TestSource(null, payload: "updated")]).PublishAsync( - m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication currentLease = await new PlayerSupportPackPublisher( + [new TestSource(null, payload: "updated")] + ).PublishAsync(m_root, output, TARGET, "unused"); string current = currentLease.directory; Assert.NotEqual(previous, current); Assert.Equal("candidate", File.ReadAllText(Path.Combine(previous, "References", "Inno.Test.dll"))); Assert.Equal("updated", File.ReadAllText(Path.Combine(current, "References", "Inno.Test.dll"))); - using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(S_TARGET, new TestSource(null)); + using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(TARGET, new TestSource(null)); Assert.Equal(current, selected.directory); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } @@ -195,13 +245,15 @@ public async Task IdenticalPublicationReusesTheExistingImmutableDirectory() { string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); - using PlayerSupportPackPublication firstLease = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication firstLease = await publisher.PublishAsync(m_root, output, TARGET, "unused"); string first = firstLease.directory; - using PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, TARGET, "unused"); Assert.Equal(first, second.directory); - Assert.Single(Directory.EnumerateDirectories(Path.Combine(output, S_TARGET.value)) - .Where(static directory => Path.GetFileName(directory) != ".preparations")); + Assert.Single( + Directory.EnumerateDirectories(Path.Combine(output, TARGET.value)) + .Where(static directory => Path.GetFileName(directory) != ".preparations") + ); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } @@ -210,21 +262,26 @@ public async Task DamagedInstalledArtifactCannotBeSilentlyReplacedWhileReadersHo { string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); - using PlayerSupportPackPublication installedLease = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication installedLease = await publisher.PublishAsync(m_root, output, TARGET, "unused"); string installed = installedLease.directory; string file = Path.Combine(installed, "References", "Inno.Test.dll"); File.WriteAllText(file, "changed externally"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(150)); await Assert.ThrowsAnyAsync(() => publisher.PublishAsync( - m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + m_root, + output, + TARGET, + "unused", + cancellationToken: cancellation.Token + ).AsTask()); Assert.Equal("changed externally", File.ReadAllText(file)); - Assert.Throws(() => new PlayerSupportPackCatalog(output).Acquire(S_TARGET, new TestSource(null))); + Assert.Throws(() => new PlayerSupportPackCatalog(output).Acquire(TARGET, new TestSource(null))); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); installedLease.Dispose(); Assert.Throws(() => installedLease.directory); - using PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, TARGET, "unused"); Assert.Equal(installed, repaired.directory); Assert.Equal("candidate", File.ReadAllText(Path.Combine(repaired.directory, "References", "Inno.Test.dll"))); } @@ -236,11 +293,15 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var first = new PlayerSupportPackPublisher([new PendingSource(entered, release)]); - Task publishing = first.PublishAsync(m_root, output, S_TARGET, "unused").AsTask(); + Task publishing = first.PublishAsync(m_root, output, TARGET, "unused").AsTask(); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); using var cancellation = new CancellationTokenSource(); - var second = new PlayerSupportPackPublisher([new TestSource(new InvalidOperationException("Preparation must not run."))]); - Task waiting = second.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask(); + var second = new PlayerSupportPackPublisher( + [new TestSource(new InvalidOperationException("Preparation must not run."))] + ); + Task waiting = second + .PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token) + .AsTask(); try { cancellation.Cancel(); @@ -252,30 +313,33 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh } using PlayerSupportPackPublication installedLease = await publishing; string installed = installedLease.directory; - using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(S_TARGET, new TestSource(null)); + using PlayerSupportPackLease selected = new PlayerSupportPackCatalog(output).Acquire(TARGET, new TestSource(null)); Assert.Equal(installed, selected.directory); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } - private static string InputIdentity(string input) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input))); + private static string InputIdentity(string input) + => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(input))); private sealed class PendingSource( TaskCompletionSource entered, TaskCompletionSource release - ) : IPlayerSupportPackSource { - public BuildTargetId target => S_TARGET; + ) : IPlayerSupportPackSource + { + public BuildTargetID target => TARGET; public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken - ) { - return ValueTask.FromResult(new PendingPlan(entered, release)); - } + ) => ValueTask.FromResult(new PendingPlan(entered, release)); + + public void Validate(string directory) => new TestSource(null).Validate(directory); private sealed class PendingPlan( TaskCompletionSource entered, TaskCompletionSource release - ) : PlayerSupportPackPlan(S_TARGET, InputIdentity("pending")) { + ) : PlayerSupportPackPlan(TARGET, InputIdentity("pending")) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public override async ValueTask PrepareAsync( @@ -285,18 +349,19 @@ CancellationToken cancellationToken entered.SetResult(); await release.Task.WaitAsync(cancellationToken); PlayerSupportPackPlan plan = await new TestSource(null).CreatePlanAsync( - new PlayerSupportPackPlanningContext("unused", "unused"), cancellationToken); + new PlayerSupportPackPlanningContext("unused", "unused"), + cancellationToken + ); await plan.PrepareAsync(stagingDirectory, cancellationToken); } } - - public void Validate(string directory) => new TestSource(null).Validate(directory); } private sealed class PlanningSource( Func> createPlan - ) : IPlayerSupportPackSource { - public BuildTargetId target => S_TARGET; + ) : IPlayerSupportPackSource + { + public BuildTargetID target => TARGET; public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, @@ -306,32 +371,46 @@ CancellationToken cancellationToken public void Validate(string directory) => new TestSource(null).Validate(directory); } - private sealed class ForeignPlan(BuildTargetId? target = null) : PlayerSupportPackPlan(target ?? new("foreign-target"), InputIdentity("foreign")) + private sealed class ForeignPlan(BuildTargetID? target = null) : PlayerSupportPackPlan( + target ?? new BuildTargetID("foreign-target"), + InputIdentity("foreign") + ) { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => throw new Xunit.Sdk.XunitException("An unaccepted plan must never execute."); + ) => throw new XunitException("An unaccepted plan must never execute."); } private sealed class TestSource( Exception? failure, Action? afterValidation = null, string payload = "candidate" - ) : IPlayerSupportPackSource { - public BuildTargetId target => S_TARGET; + ) : IPlayerSupportPackSource + { + public BuildTargetID target => TARGET; public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => ValueTask.FromResult(new TestPlan(failure, payload)); + public void Validate(string directory) + { + if (!File.Exists(Path.Combine(directory, "References", "Inno.Test.dll"))) + { + throw new InvalidDataException("Candidate is incomplete."); + } + afterValidation?.Invoke(); + } + private sealed class TestPlan( Exception? failure, string payload - ) : PlayerSupportPackPlan(S_TARGET, InputIdentity(payload + failure?.GetType().FullName)) { + ) : PlayerSupportPackPlan(TARGET, InputIdentity(payload + failure?.GetType().FullName)) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public override ValueTask PrepareAsync( @@ -343,17 +422,11 @@ CancellationToken cancellationToken Directory.CreateDirectory(references); File.WriteAllText(Path.Combine(references, "Inno.Test.dll"), payload); if (failure is not null) + { throw failure; + } return ValueTask.CompletedTask; } - - } - - public void Validate(string directory) - { - if (!File.Exists(Path.Combine(directory, "References", "Inno.Test.dll"))) - throw new InvalidDataException("Candidate is incomplete."); - afterValidation?.Invoke(); } } } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs index 216bd040d..3d75b5d3c 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs @@ -1,48 +1,40 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; - - - - using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.Build; namespace Inno.Build.SupportPacks.Tests; public sealed class SupportPackWorkflowTests : BuildPipelineFixture { - [Fact] public async Task UnknownManagedDeploymentNeverStartsSupportPackPreparation() { @@ -52,7 +44,9 @@ public async Task UnknownManagedDeploymentNeverStartsSupportPackPreparation() InvalidOperationException failure = await Assert.ThrowsAsync(() => pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("windows-x64"), new ManagedDeploymentId("unregistered")).AsTask()); + new BuildTargetID("windows-x64"), + new ManagedDeploymentID("unregistered") + ).AsTask()); Assert.Contains("unregistered", failure.Message, StringComparison.Ordinal); Assert.Equal(0, provisioner.callCount); @@ -63,13 +57,14 @@ public async Task UnsupportedPlatformDeploymentPairNeverStartsSupportPackPrepara { var provisioner = new TestSupportPackProvisioner(_ => throw new InvalidOperationException("Unsupported platforms must not prepare a Pack.")); - var deployments = new ManagedDeploymentCatalog( - [new FixtureManagedDeploymentCompiler(["browser-wasm"])]); + var deployments = new ManagedDeploymentCatalog([new FixtureManagedDeploymentCompiler(["browser-wasm"])]); BuildPipeline pipeline = CreatePipeline(provisioner, deployments); InvalidOperationException failure = await Assert.ThrowsAsync(() => pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("windows-x64"), ManagedDeploymentId.coreClr).AsTask()); + new BuildTargetID("windows-x64"), + ManagedDeploymentID.coreClr + ).AsTask()); Assert.Contains("win-x64", failure.Message, StringComparison.Ordinal); Assert.Equal(0, provisioner.callCount); @@ -79,39 +74,44 @@ public async Task UnsupportedPlatformDeploymentPairNeverStartsSupportPackPrepara public async Task MissingSupportPackIsPreparedBeforeTheOwnerThreadExport() { SaveStartupScene(); - Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value), recursive: true); - var provisioner = new TestSupportPackProvisioner(target => - CreateSupportPack(target, "Inno.Player.MacOSArm64")); + Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetID("macos-arm64").value), recursive: true); + var provisioner = new TestSupportPackProvisioner(target => CreateSupportPack(target, "Inno.Player.MacOSArm64")); BuildPipeline pipeline = CreatePipeline(provisioner); - using PlayerSupportPackLease prepared = await pipeline.EnsurePlayerSupportPackAsync(new BuildTargetId("macos-arm64"), deployment: null); + using PlayerSupportPackLease prepared = await pipeline.EnsurePlayerSupportPackAsync( + new BuildTargetID("macos-arm64"), + deployment: null + ); BuildResult result = await pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = Path.Combine(m_root, "Builds", "Provisioned") }); Assert.True(result.succeeded); Assert.Equal(1, provisioner.callCount); - Assert.True(Directory.Exists(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value))); + Assert.True(Directory.Exists(Path.Combine(m_supportPackRoot, new BuildTargetID("macos-arm64").value))); } [Fact] public async Task MissingPackFailsPromptlyWhileAsynchronousPreparationIsPending() { SaveStartupScene(); - Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value), recursive: true); + Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetID("macos-arm64").value), recursive: true); using var cancellation = new CancellationTokenSource(); var provisioner = new PendingSupportPackProvisioner(); BuildPipeline pipeline = CreatePipeline(provisioner); Task preparation = pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("macos-arm64"), deployment: null, cancellation.Token).AsTask(); + new BuildTargetID("macos-arm64"), + deployment: null, + cancellation.Token + ).AsTask(); try { Assert.False(preparation.IsCompleted); Task build = pipeline.BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = Path.Combine(m_root, "Builds", "Pending") }).AsTask(); @@ -131,15 +131,19 @@ public async Task MissingPackFailsPromptlyWhileAsynchronousPreparationIsPending( public async Task InvalidInstalledSupportPackDoesNotTriggerProvisioning() { SaveStartupScene(); - File.Delete(Path.Combine(GetSupportPackDirectory(new BuildTargetId("macos-arm64")), - "native", "libminiaudio-release.dylib")); - var provisioner = new TestSupportPackProvisioner(target => - CreateSupportPack(target, "Inno.Player.MacOSArm64")); + File.Delete( + Path.Combine( + GetSupportPackDirectory(new BuildTargetID("macos-arm64")), + "native", + "libminiaudio-release.dylib" + ) + ); + var provisioner = new TestSupportPackProvisioner(target => CreateSupportPack(target, "Inno.Player.MacOSArm64")); await Assert.ThrowsAsync(() => CreatePipeline(provisioner).BuildGameAsync(new GameBuildRequest { - profile = CreateProfile(new BuildTargetId("macos-arm64")), + profile = CreateProfile(new BuildTargetID("macos-arm64")), outputDirectory = Path.Combine(m_root, "Builds", "InvalidPack") }).AsTask()); diff --git a/tests/build/Inno.Build.Tests/BuildProfileTests.cs b/tests/build/Inno.Build.Tests/BuildProfileTests.cs index c400c98e2..da84840aa 100644 --- a/tests/build/Inno.Build.Tests/BuildProfileTests.cs +++ b/tests/build/Inno.Build.Tests/BuildProfileTests.cs @@ -16,8 +16,11 @@ public sealed class BuildProfileTests : IDisposable public BuildProfileTests() { Directory.CreateDirectory(m_projectRoot); - m_engine = new EngineHostBuilder().UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildProfile).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + m_engine = new EngineHostBuilder().UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildProfile).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); } public void Dispose() @@ -26,28 +29,17 @@ public void Dispose() Directory.Delete(m_projectRoot, recursive: true); } - private static BuildProfile CreateProfile( - BuildTargetId target, - string productName = "Test Game" - ) => new() - { - applicationId = "tests.game", productName = productName, startupScene = "Scenes/Startup.iscene", target = target - }; - - [Theory] [InlineData("../other-game")] [InlineData("C:/absolute")] [InlineData("studio//game")] public void ProfileRejectsPersistentDataPathsOutsidePortableApplicationFolders(string path) { - BuildProfile profile = CreateProfile(new BuildTargetId("windows-x64")); + BuildProfile profile = CreateProfile(new BuildTargetID("windows-x64")); profile.persistentDataPath = path; Assert.Throws(profile.Validate); } - - [Theory] [InlineData("CON")] [InlineData("nul.txt")] @@ -56,19 +48,17 @@ public void ProfileRejectsPersistentDataPathsOutsidePortableApplicationFolders(s [InlineData("Bad:Name")] public void BuildProfileRejectsNamesThatAreInvalidOnEitherTarget(string productName) { - BuildProfile profile = CreateProfile(new BuildTargetId("macos-arm64"), productName); + BuildProfile profile = CreateProfile(new BuildTargetID("macos-arm64"), productName); Assert.Throws(profile.Validate); } - - [Fact] public void BuildProfileStoreRoundTripsGeneratedCurrentFormat() { string path = Path.Combine(m_projectRoot, "BuildProfile.inno"); var store = new BuildProfileStore(path, m_engine.serialization); - BuildProfile source = CreateProfile(new BuildTargetId("windows-x64"), "Stored Game"); + BuildProfile source = CreateProfile(new BuildTargetID("windows-x64"), "Stored Game"); source.windowWidth = 1920; source.windowHeight = 1080; @@ -79,22 +69,20 @@ public void BuildProfileStoreRoundTripsGeneratedCurrentFormat() Assert.Equal(source.applicationId, restored.applicationId); Assert.Equal(source.productName, restored.productName); Assert.Equal(source.startupScene, restored.startupScene); - Assert.Equal(new BuildTargetId("windows-x64"), restored.target); + Assert.Equal(new BuildTargetID("windows-x64"), restored.target); Assert.Equal(1920, restored.windowWidth); Assert.Equal(1080, restored.windowHeight); } - - [Fact] public void BuildProfileStorePreservesCommittedDocumentWhenCandidateIsInvalid() { string path = Path.Combine(m_projectRoot, "BuildProfile.inno"); var store = new BuildProfileStore(path, m_engine.serialization); - BuildProfile committed = CreateProfile(new BuildTargetId("macos-arm64"), "Committed Game"); + BuildProfile committed = CreateProfile(new BuildTargetID("macos-arm64"), "Committed Game"); store.Save(committed); byte[] committedBytes = File.ReadAllBytes(path); - BuildProfile invalid = CreateProfile(new BuildTargetId("windows-x64"), "Invalid/Game"); + BuildProfile invalid = CreateProfile(new BuildTargetID("windows-x64"), "Invalid/Game"); Assert.Throws(() => store.Save(invalid)); @@ -102,8 +90,6 @@ public void BuildProfileStorePreservesCommittedDocumentWhenCandidateIsInvalid() Assert.Empty(Directory.EnumerateFiles(m_projectRoot, "BuildProfile.inno.staging-*")); } - - [Fact] public void BuildProfileStoreRejectsCorruptCurrentFormatWithoutFallback() { @@ -116,4 +102,14 @@ public void BuildProfileStoreRejectsCorruptCurrentFormatWithoutFallback() Assert.Contains("current-format", failure.Message, StringComparison.Ordinal); } + private static BuildProfile CreateProfile( + BuildTargetID target, + string productName = "Test Game" + ) => new() + { + applicationId = "tests.game", + productName = productName, + startupScene = "Scenes/Startup.iscene", + target = target + }; } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs index efd19a9d4..91908b8c4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs @@ -5,18 +5,23 @@ using System.Security.Cryptography; using System.Text.Json; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; public sealed class BackendPrebuiltArchiveTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoBackendPackages", Guid.NewGuid().ToString("N")); - private string Inventory => Path.Combine(m_root, "inventory.json"); - private string Archive => Path.Combine(m_root, "platform.zip"); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoBackendPackages", + Guid.NewGuid().ToString("N") + ); - public BackendPrebuiltArchiveTests() => Directory.CreateDirectory(m_root); + public BackendPrebuiltArchiveTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public async Task RepackingOneHundredRevisionsIncludesOnlyTheSelectedCurrentFiles() @@ -26,19 +31,19 @@ public async Task RepackingOneHundredRevisionsIncludesOnlyTheSelectedCurrentFile string path = $"library-{revision}.dll"; File.WriteAllText(Path.Combine(m_root, path), revision.ToString()); Select(path); - BackendPrebuiltArchive.Create(m_root, Inventory, Archive); - using ZipArchive zip = ZipFile.OpenRead(Archive); + BackendPrebuiltArchive.Create(m_root, inventory, archive); + using ZipArchive zip = ZipFile.OpenRead(archive); Assert.Equal(new[] { "manifest.json", path }, zip.Entries.Select(entry => entry.FullName)); } - string digest = Digest(Archive); - BackendPrebuiltArchive.Create(m_root, Inventory, Archive); - Assert.Equal(digest, Digest(Archive)); + string digest = Digest(archive); + BackendPrebuiltArchive.Create(m_root, inventory, archive); + Assert.Equal(digest, Digest(archive)); string output = Path.Combine(m_root, "consumer"); - await BackendPrebuiltArchive.ExtractAsync(Archive, digest, "fixture-target", output); + await BackendPrebuiltArchive.ExtractAsync(archive, digest, "fixture-target", output); Assert.Equal("99", File.ReadAllText(Path.Combine(output, "library-99.dll"))); Assert.Equal(3, Directory.GetFiles(output).Length); Assert.Contains(digest, File.ReadAllText(Path.Combine(output, "receipt.json"))); - await Assert.ThrowsAnyAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "fixture-target", output)); + await Assert.ThrowsAnyAsync(() => BackendPrebuiltArchive.ExtractAsync(archive, digest, "fixture-target", output)); Assert.Equal("99", File.ReadAllText(Path.Combine(output, "library-99.dll"))); } @@ -48,25 +53,41 @@ public async Task ChangedInputsAndExtraArchiveEntriesCannotReplaceCertifiedOutpu string payload = Path.Combine(m_root, "library.dll"); File.WriteAllText(payload, "certified"); Select("library.dll"); - BackendPrebuiltArchive.Create(m_root, Inventory, Archive); - string digest = Digest(Archive); + BackendPrebuiltArchive.Create(m_root, inventory, archive); + string digest = Digest(archive); File.WriteAllText(payload, "unexpected change"); - Assert.Throws(() => BackendPrebuiltArchive.Create(m_root, Inventory, Archive)); - Assert.Equal(digest, Digest(Archive)); + Assert.Throws(() => BackendPrebuiltArchive.Create(m_root, inventory, archive)); + Assert.Equal(digest, Digest(archive)); string output = Path.Combine(m_root, "consumer"); - await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "other-target", output)); - using (ZipArchive zip = ZipFile.Open(Archive, ZipArchiveMode.Update)) + await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(archive, digest, "other-target", output)); + using (ZipArchive zip = ZipFile.Open(archive, ZipArchiveMode.Update)) + { zip.CreateEntry("undeclared"); - await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "fixture-target", output)); - await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, Digest(Archive), "fixture-target", output)); + } + await Assert.ThrowsAsync( + () => BackendPrebuiltArchive.ExtractAsync(archive, digest, "fixture-target", output) + ); + await Assert.ThrowsAsync( + () => BackendPrebuiltArchive.ExtractAsync(archive, Digest(archive), "fixture-target", output) + ); Assert.False(Directory.Exists(output)); } + public void Dispose() => Directory.Delete(m_root, recursive: true); + + private string inventory => Path.Combine(m_root, "inventory.json"); + private string archive => Path.Combine(m_root, "platform.zip"); + private void Select(string path) { string digest = Digest(Path.Combine(m_root, path)); - var inventory = new { version = 1, target = "fixture-target", files = new[] { new { owner = "Fixture", configuration = "Debug", input = digest, path, sha256 = digest } } }; - File.WriteAllBytes(Inventory, JsonSerializer.SerializeToUtf8Bytes(inventory)); + var manifest = new + { + version = 1, + target = "fixture-target", + files = new[] { new { owner = "Fixture", configuration = "Debug", input = digest, path, sha256 = digest } } + }; + File.WriteAllBytes(inventory, JsonSerializer.SerializeToUtf8Bytes(manifest)); } private static string Digest(string path) @@ -74,6 +95,4 @@ private static string Digest(string path) using FileStream stream = File.OpenRead(path); return Convert.ToHexStringLower(SHA256.HashData(stream)); } - - public void Dispose() => Directory.Delete(m_root, recursive: true); } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs index 553fd5af0..f69613504 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs @@ -1,12 +1,13 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -38,7 +39,7 @@ public async Task ANewWriterInvalidatesItsMeasurementWithoutDiscardingOtherShard await PrepareAsync("second", "second payload"); await MaintainAsync(); string[] checkpoints = Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory"); - var before = checkpoints.ToDictionary(static path => path, File.ReadAllText); + Dictionary before = checkpoints.ToDictionary(static path => path, File.ReadAllText); await PrepareAsync("first", "a longer changed payload"); await MaintainAsync(); Assert.Single(checkpoints.Where(path => before[path] != File.ReadAllText(path))); @@ -76,7 +77,9 @@ public async Task ActiveReadersKeepTheirInventoryUntilRetirementActuallyComplete await PrepareAsync("first", "first payload"); await MaintainAsync(); string directory = Path.Combine(m_root, "cache", "first"); - string checkpoint = Assert.Single(Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory")); + string checkpoint = Assert.Single( + Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory") + ); using (FileLease reader = await FileLease.AcquireSharedAsync(directory + ".lock", TimeSpan.FromSeconds(5))) { await MaintainAsync(retireAll: true); @@ -93,7 +96,9 @@ public async Task InterruptedInventoryResumesCompletedShardsBeforeRetiringAnyArt { const int C_COUNT = 64; for (int index = 0; index < C_COUNT; index++) + { await PrepareAsync("shard-" + index.ToString("D3"), new string('x', 4096)); + } string directory = Path.Combine(m_root, "artifacts", "cache-owners", "inventory"); Directory.CreateDirectory(directory); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); @@ -118,8 +123,14 @@ public async Task InterruptedInventoryResumesCompletedShardsBeforeRetiringAnyArt { Assert.True(observing.Wait(TimeSpan.FromSeconds(30)), "The checkpoint observer did not start."); await Assert.ThrowsAnyAsync(() => Task.Run(() => - BuildMaintenanceApplication.CleanAsync(m_root, new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), - true, false, null, cancellation.Token))); + BuildMaintenanceApplication.CleanAsync( + m_root, + new BuildCachePolicy(long.MaxValue, 0, TimeSpan.FromMinutes(2)), + true, + false, + null, + cancellation.Token + ))); } finally { @@ -128,12 +139,18 @@ await Assert.ThrowsAnyAsync(() => Task.Run(() => } string[] completed = Directory.GetFiles(directory, "*.inventory"); Assert.NotEmpty(completed); - Assert.True(completed.Length < C_COUNT, "The first checkpoint must interrupt discovery before the complete protection graph exists."); - var snapshots = completed.ToDictionary(static path => path, static path => (File.ReadAllText(path), File.GetLastWriteTimeUtc(path))); + Assert.True( + completed.Length < C_COUNT, + "The first checkpoint must interrupt discovery before the complete protection graph exists." + ); + Dictionary snapshots = completed.ToDictionary( + static path => path, + static path => (File.ReadAllText(path), File.GetLastWriteTimeUtc(path)) + ); Assert.Equal(C_COUNT, Directory.GetDirectories(Path.Combine(m_root, "cache")).Length); await MaintainAsync(); Assert.Equal(C_COUNT, Directory.GetFiles(directory, "*.inventory").Length); - foreach (var snapshot in snapshots) + foreach (KeyValuePair snapshot in snapshots) { Assert.Equal(snapshot.Value.Item1, File.ReadAllText(snapshot.Key)); Assert.Equal(snapshot.Value.Item2, File.GetLastWriteTimeUtc(snapshot.Key)); @@ -143,8 +160,23 @@ await Assert.ThrowsAnyAsync(() => Task.Run(() => Assert.Empty(Directory.GetFiles(directory, "*.inventory")); } - private async Task PrepareAsync(string name, string content) + public void Dispose() { + string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoInventoryProgress")) + Path.DirectorySeparatorChar; + if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("The inventory fixture escaped its owner."); + } + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: true); + } + } + + private async Task PrepareAsync( + string name, + string content + ) { string root = Path.Combine(m_root, "cache"); var publisher = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); BuildCacheOwnerCatalog.Register(m_root, root, "fixture", publisher.role); @@ -158,18 +190,14 @@ private async Task PrepareAsync(string name, string content) private Task MaintainAsync( bool dryRun = false, bool retireAll = false - ) { + ) => // Full inventory and retirement assertions are foreground work, not a five-second automatic maintenance slice. - return BuildMaintenanceApplication.CleanAsync(m_root, new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), - retireAll, dryRun, null, CancellationToken.None); - } - - public void Dispose() - { - string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoInventoryProgress")) + Path.DirectorySeparatorChar; - if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) - throw new InvalidOperationException("The inventory fixture escaped its owner."); - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: true); - } + BuildMaintenanceApplication.CleanAsync( + m_root, + new BuildCachePolicy(long.MaxValue, 0, TimeSpan.FromMinutes(2)), + retireAll, + dryRun, + null, + CancellationToken.None + ); } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs index cd5f5b90e..b7b146066 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs @@ -20,8 +20,14 @@ public async Task OwnerCatalogWaitParticipatesInTheCompleteMaintenanceBudget() string coordination = Path.Combine(m_root, "artifacts", "cache-owners", "owner.lock"); using FileLease writer = await FileLease.AcquireAsync(coordination, TimeSpan.FromSeconds(5)); Stopwatch elapsed = Stopwatch.StartNew(); - await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync(m_root, - new(timeBudget: TimeSpan.FromMilliseconds(100)), false, false, null, default)); + await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync( + m_root, + new BuildCachePolicy(timeBudget: TimeSpan.FromMilliseconds(100)), + false, + false, + null, + default + )); Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(5)); } @@ -34,9 +40,16 @@ public async Task RetiredPublicationsReleaseTheirMetadataAndLeafWhilePreservingO Directory.CreateDirectory(Path.Combine(output, "Outputs")); File.WriteAllText(Path.Combine(output, "Outputs", "file"), "payload"); using (await publisher.AcquireUseAsync()) + { publisher.Record(output, output + ".read.lock", [], null, null); + } File.WriteAllText(Path.Combine(cache, "unknown.lock"), "user-owned"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [publisher.Describe("fixture")], + new BuildCachePolicy(0, 0), + retireAll: true + ); Assert.Empty((await plan.ExecuteAsync()).failures); Assert.False(Directory.Exists(output)); Assert.False(File.Exists(output + ".read.lock")); @@ -60,7 +73,7 @@ public async Task MetadataConvergesWithoutBytePressureAndDryRunDoesNotRetireClai Assert.Empty(Directory.GetFiles(cache, "*.work.json")); Assert.Empty(Directory.GetFiles(cache, "*.work.lock")); - BuildCacheCleanupPlan Plan() => BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new()); + BuildCacheCleanupPlan Plan() => BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new BuildCachePolicy()); } [Fact] @@ -82,13 +95,15 @@ public async Task StableCurrentPointersAreNotRewrittenAndCorruptionIsReported() Assert.Equal(stamp, File.GetLastWriteTimeUtc(pointer)); File.WriteAllText(pointer, "../escaped"); } - Assert.ThrowsAny(() => BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new())); + Assert.ThrowsAny(() => BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new BuildCachePolicy())); Assert.True(Directory.Exists(output)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs index 6fe60b130..3804546f1 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -26,11 +26,20 @@ public async Task MaintenanceUsesPublisherInventoryWithoutAdoptingUnrecordedDire File.WriteAllText(Path.Combine(owned, "value"), "owned"); File.WriteAllText(Path.Combine(unknown, "value"), "user"); using (await publisher.AcquireUseAsync()) + { publisher.Record(owned, owned + ".read.lock", [], null, "windows-x64"); + } Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); - await BuildMaintenanceApplication.CleanAsync(m_root, new(0, 0), true, true, "windows-x64", CancellationToken.None); + await BuildMaintenanceApplication.CleanAsync(m_root, new BuildCachePolicy(0, 0), true, true, "windows-x64", CancellationToken.None); Assert.True(Directory.Exists(owned)); - await BuildMaintenanceApplication.CleanAsync(m_root, new(0, 0), true, false, "windows-x64", CancellationToken.None); + await BuildMaintenanceApplication.CleanAsync( + m_root, + new BuildCachePolicy(0, 0), + true, + false, + "windows-x64", + CancellationToken.None + ); Assert.False(Directory.Exists(owned)); Assert.True(Directory.Exists(unknown)); } @@ -39,12 +48,24 @@ public async Task MaintenanceUsesPublisherInventoryWithoutAdoptingUnrecordedDire public async Task EmptyCheckoutAndInvalidRequestsDoNotPrepareGeneratorsOrClaimArtifacts() { Assert.Empty(BuildCacheOwnerCatalog.ReadOwners(m_root)); - Assert.Equal(0, await BuildMaintenanceApplication.Run(["clean", "--scope", "cache", "--engine-root", m_root, "--dry-run"], CancellationToken.None)); + Assert.Equal( + 0, + await BuildMaintenanceApplication.RunAsync( + ["clean", "--scope", "cache", "--engine-root", m_root, "--dry-run"], + CancellationToken.None + ) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "native"))); - Assert.Equal(1, await BuildMaintenanceApplication.Run(["clean", "--scope", "cache", "--scope", "cache", "--engine-root", m_root], CancellationToken.None)); + Assert.Equal( + 1, + await BuildMaintenanceApplication.RunAsync( + ["clean", "--scope", "cache", "--scope", "cache", "--engine-root", m_root], + CancellationToken.None + ) + ); using var canceled = new CancellationTokenSource(); canceled.Cancel(); - Assert.Equal(2, await BuildMaintenanceApplication.Run(["clean"], canceled.Token)); + Assert.Equal(2, await BuildMaintenanceApplication.RunAsync(["clean"], canceled.Token)); } [Fact] @@ -52,7 +73,9 @@ public void CorruptRegistrationOrChangedRoleIsRejectedBeforeRetirement() { string ownerRoot = Path.Combine(m_root, "artifacts", "fixture"); BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ImmutableArtifact); - Assert.Throws(() => BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ReusableWorkspace)); + Assert.Throws( + () => BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ReusableWorkspace) + ); string registration = Directory.EnumerateFiles(Path.Combine(m_root, "artifacts", "cache-owners"), "*.json").Single(); File.WriteAllText(registration, "{}"); Assert.Throws(() => BuildCacheOwnerCatalog.ReadOwners(m_root)); @@ -61,6 +84,8 @@ public void CorruptRegistrationOrChangedRoleIsRejectedBeforeRetirement() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs index 8a58cb643..4171340b5 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Text.Json.Nodes; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -32,10 +32,16 @@ public async Task UnverifiableMetadataPreservesClaimsAndReportsCompletedRetireme Directory.CreateDirectory(output); File.WriteAllBytes(Path.Combine(output, "payload"), [1, 2, 3]); using (await healthy.AcquireUseAsync()) + { healthy.Record(output, output + ".read.lock", [], null, null); + } - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, - [invalid.Describe("invalid"), healthy.Describe("healthy")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [invalid.Describe("invalid"), healthy.Describe("healthy")], + new BuildCachePolicy(0, 0), + retireAll: true + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Equal(3, result.retiredBytes); @@ -61,14 +67,22 @@ public async Task ExplicitMaintenanceStillFailsWhenMetadataCannotBeCertified() File.WriteAllText(claim + ".invalid.process", "unverifiable"); await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync( - m_root, new(timeBudget: TimeSpan.FromSeconds(30)), true, false, null, default)); + m_root, + new BuildCachePolicy(timeBudget: TimeSpan.FromSeconds(30)), + true, + false, + null, + default + )); Assert.True(File.Exists(claim)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static void MarkOwnerExited(string claim) diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs index f2f16d3e7..6224f584e 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs @@ -20,10 +20,17 @@ public async Task UnprotectedProcessWorkIsRetiredWithoutEvictingReusablePayloads { OwnedCache owner = AddOwner("process-work"); BuildCacheArtifactDescriptor process = owner.Add("exited-process", 2); - owner.artifacts[0] = new(process.directory, process.leasePath, process.targetId, - process.bytes, process.lastUseUtc, [], BuildCacheArtifactRole.ProcessWorkingDirectory); + owner.artifacts[0] = new( + process.directory, + process.leasePath, + process.targetID, + process.bytes, + process.lastUseUtc, + [], + BuildCacheArtifactRole.ProcessWorkingDirectory + ); BuildCacheArtifactDescriptor reusable = owner.Add("reusable", 3); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(long.MaxValue, 0)); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new BuildCachePolicy(long.MaxValue, 0)); Assert.Equal(process.directory, Assert.Single(plan.candidates).directory); Assert.Equal(process.directory, Assert.Single((await plan.ExecuteAsync()).retired)); Assert.True(Directory.Exists(reusable.directory)); @@ -34,11 +41,16 @@ public async Task TargetCleanupPreservesOtherTargetsSharedArtifactsAndTheirDepen { OwnedCache owner = AddOwner("targeted"); BuildCacheArtifactDescriptor shared = owner.Add("shared", 2); - BuildCacheArtifactDescriptor requiredByMac = owner.Add("windows-dependency", 3, targetId: "windows-x64"); + BuildCacheArtifactDescriptor requiredByMac = owner.Add("windows-dependency", 3, targetID: "windows-x64"); BuildCacheArtifactDescriptor mac = owner.Add("mac", 4, [requiredByMac.directory], "macos-arm64"); - BuildCacheArtifactDescriptor obsoleteWindows = owner.Add("windows-obsolete", 5, targetId: "windows-x64"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(0, 0), - retireAll: true, targetId: "windows-x64"); + BuildCacheArtifactDescriptor obsoleteWindows = owner.Add("windows-obsolete", 5, targetID: "windows-x64"); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new BuildCachePolicy(0, 0), + retireAll: true, + targetID: "windows-x64" + ); Assert.Equal(obsoleteWindows.directory, Assert.Single(plan.candidates).directory); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Equal(obsoleteWindows.directory, Assert.Single(result.retired)); @@ -51,11 +63,23 @@ public async Task TargetCleanupPreservesOtherTargetsSharedArtifactsAndTheirDepen public async Task FreshTargetChangePreventsRetiringAnOriginalCandidate() { OwnedCache owner = AddOwner("retargeted"); - BuildCacheArtifactDescriptor original = owner.Add("candidate", 2, targetId: "windows-x64"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(0, 0), - retireAll: true, targetId: "windows-x64"); - owner.artifacts[0] = new(original.directory, original.leasePath, "macos-arm64", - original.bytes, original.lastUseUtc, original.dependencies, BuildCacheArtifactRole.ImmutableArtifact); + BuildCacheArtifactDescriptor original = owner.Add("candidate", 2, targetID: "windows-x64"); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new BuildCachePolicy(0, 0), + retireAll: true, + targetID: "windows-x64" + ); + owner.artifacts[0] = new( + original.directory, + original.leasePath, + "macos-arm64", + original.bytes, + original.lastUseUtc, + original.dependencies, + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Empty(result.retired); Assert.True(Directory.Exists(original.directory)); @@ -95,8 +119,12 @@ public async Task ActiveReaderPreventsRetirementUntilItReleasesOwnership() BuildCacheArtifactDescriptor artifact = owner.Add("generation", 6); BuildArtifactManifest.Write(artifact.directory, "fixture", ["Outputs"]); BuildCacheCleanupPlan plan = CreatePlan(); - using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(artifact.directory, Path.GetDirectoryName(artifact.directory)!, "fixture", ["Outputs"])) - { + using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + artifact.directory, + Path.GetDirectoryName(artifact.directory)!, + "fixture", + ["Outputs"] + )) { BuildCacheCleanupResult blocked = await plan.ExecuteAsync(); Assert.Empty(blocked.retired); Assert.Contains(artifact.directory, blocked.skipped); @@ -114,7 +142,15 @@ public async Task WorkspaceRetirementUsesTheActualProducerLease() OwnedCache owner = AddOwner("workspaces"); BuildCacheArtifactDescriptor artifact = owner.Add("workspace", 6); string producerLease = Path.Combine(owner.descriptor.directory, "producer.lock"); - owner.artifacts[0] = new(artifact.directory, producerLease, artifact.targetId, artifact.bytes, artifact.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + artifact.directory, + producerLease, + artifact.targetID, + artifact.bytes, + artifact.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupPlan plan = CreatePlan(); using (FileLease producer = await FileLease.AcquireAsync(producerLease, TimeSpan.Zero)) { @@ -134,11 +170,26 @@ public void PersistentLeasesCannotBeInsideRetiredDirectoriesOrSharedByEntries() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor first = owner.Add("first", 2); BuildCacheArtifactDescriptor second = owner.Add("second", 2); - owner.artifacts[0] = new(first.directory, Path.Combine(first.directory, "inside.lock"), - first.targetId, first.bytes, first.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + Path.Combine(first.directory, "inside.lock"), + first.targetID, + first.bytes, + first.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); owner.artifacts[0] = first; - owner.artifacts[1] = new(second.directory, first.leasePath, second.targetId, second.bytes, second.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[1] = new( + second.directory, + first.leasePath, + second.targetID, + second.bytes, + second.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); Assert.True(Directory.Exists(first.directory)); Assert.True(Directory.Exists(second.directory)); @@ -151,9 +202,14 @@ public async Task ActiveParentOutsideTheProposalProtectsItsDependency() BuildCacheArtifactDescriptor dependency = owner.Add("old-dependency", 6); BuildCacheArtifactDescriptor parent = owner.Add("new-parent", 8, [dependency.directory]); BuildArtifactManifest.Write(parent.directory, "parent", ["Outputs"]); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(13, 0)); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new BuildCachePolicy(13, 0)); Assert.Equal(dependency.directory, Assert.Single(plan.candidates).directory); - using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(parent.directory, Path.GetDirectoryName(parent.directory)!, "parent", ["Outputs"]); + using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + parent.directory, + Path.GetDirectoryName(parent.directory)!, + "parent", + ["Outputs"] + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); @@ -174,7 +230,9 @@ public async Task PreviewAndExecutionUseTheSameProposalAndFreshRoots() Assert.Contains(artifact.directory, preview.skipped); Assert.True(Directory.Exists(artifact.directory)); using (FileLease update = await FileLease.AcquireAsync(owner.descriptor.coordinationPath, TimeSpan.Zero)) + { owner.roots.Add(artifact.directory); + } BuildCacheCleanupResult actual = await plan.ExecuteAsync(); @@ -207,7 +265,15 @@ public async Task ChangedInventoryDoesNotDeleteTheEarlierGeneration() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor artifact = owner.Add("generation", 3); BuildCacheCleanupPlan plan = CreatePlan(); - owner.artifacts[0] = new(artifact.directory, artifact.leasePath, artifact.targetId, 4, artifact.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + artifact.directory, + artifact.leasePath, + artifact.targetID, + 4, + artifact.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); @@ -234,12 +300,17 @@ public async Task CancellationAndDurationLimitPreserveUnprocessedArtifacts() { OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor artifact = owner.Add("generation", 3); - Assert.Throws(() => BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], - new(0, 0, TimeSpan.FromTicks(1)), retireAll: true)); + Assert.Throws(() => BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new BuildCachePolicy(0, 0, TimeSpan.FromTicks(1)), + retireAll: true + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync( - () => CreatePlan().ExecuteAsync(cancellationToken: cancellation.Token).AsTask()); + () => CreatePlan().ExecuteAsync(cancellationToken: cancellation.Token).AsTask() + ); Assert.True(Directory.Exists(artifact.directory)); } @@ -249,9 +320,25 @@ public void InvalidOwnershipAndDependencyCyclesFailBeforeRemoval() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor first = owner.Add("first", 2); BuildCacheArtifactDescriptor second = owner.Add("second", 2, [first.directory]); - owner.artifacts[0] = new(first.directory, first.leasePath, first.targetId, first.bytes, first.lastUseUtc, [second.directory], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + first.leasePath, + first.targetID, + first.bytes, + first.lastUseUtc, + [second.directory], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); - owner.artifacts[0] = new(first.directory, first.leasePath, first.targetId, first.bytes, first.lastUseUtc, [Path.Combine(m_root, "unregistered")], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + first.leasePath, + first.targetID, + first.bytes, + first.lastUseUtc, + [Path.Combine(m_root, "unregistered")], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); owner.artifacts[0] = new(m_root, first.leasePath, null, 2, DateTime.UtcNow, [], BuildCacheArtifactRole.ImmutableArtifact); Assert.Throws(() => CreatePlan()); @@ -280,7 +367,7 @@ public void ProtectedArtifactsCanExceedTheBudgetWithoutBecomingCandidates() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor artifact = owner.Add("generation", 3); owner.roots.Add(artifact.directory); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(0, 0)); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new BuildCachePolicy(0, 0)); Assert.Equal(3, plan.totalBytes); Assert.Equal(3, plan.protectedBytes); Assert.Empty(plan.candidates); @@ -289,7 +376,9 @@ public void ProtectedArtifactsCanExceedTheBudgetWithoutBecomingCandidates() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private OwnedCache AddOwner(string name) @@ -299,8 +388,13 @@ private OwnedCache AddOwner(string name) return owner; } - private BuildCacheCleanupPlan CreatePlan() => BuildCacheCleanupPlan.Create(m_root, - m_owners.Select(static owner => owner.descriptor).ToArray(), new(0, 0), retireAll: true); + private BuildCacheCleanupPlan CreatePlan() + => BuildCacheCleanupPlan.Create( + m_root, + m_owners.Select(static owner => owner.descriptor).ToArray(), + new BuildCachePolicy(0, 0), + retireAll: true + ); private sealed class OwnedCache { @@ -309,7 +403,10 @@ internal OwnedCache( string id ) { Directory.CreateDirectory(directory); - descriptor = new(id, directory, Path.Combine(directory, "owner.lock"), + this.descriptor = new( + id, + directory, + Path.Combine(directory, "owner.lock"), token => { token.ThrowIfCancellationRequested(); @@ -319,7 +416,8 @@ string id { token.ThrowIfCancellationRequested(); return roots.ToArray(); - }); + } + ); } internal List artifacts { get; } = []; @@ -330,13 +428,21 @@ internal BuildCacheArtifactDescriptor Add( string name, int bytes, IReadOnlyList? dependencies = null, - string? targetId = null + string? targetID = null ) { string directory = Path.Combine(descriptor.directory, name); Directory.CreateDirectory(Path.Combine(directory, "Outputs")); File.WriteAllBytes(Path.Combine(directory, "Outputs", "payload.bin"), new byte[bytes]); - var used = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(artifacts.Count); - var artifact = new BuildCacheArtifactDescriptor(directory, directory + ".read.lock", targetId, bytes, used, dependencies ?? [], BuildCacheArtifactRole.ImmutableArtifact); + DateTime used = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(artifacts.Count); + var artifact = new BuildCacheArtifactDescriptor( + directory, + directory + ".read.lock", + targetID, + bytes, + used, + dependencies ?? [], + BuildCacheArtifactRole.ImmutableArtifact + ); artifacts.Add(artifact); return artifact; } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs index b1ddcbcb9..7bacb7a05 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs @@ -4,9 +4,9 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -31,12 +31,23 @@ public async Task WorkspaceLibraryAliasesAreCountedOnceAndRetiredWithoutFollowin File.CreateSymbolicLink(Path.Combine(workspace, "libsample.1.dylib"), "libsample.1.0.dylib"); File.CreateSymbolicLink(Path.Combine(workspace, "libsample.dylib"), "libsample.1.dylib"); long bytes = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories) - .Where(path => new FileInfo(path).LinkTarget is null).Sum(path => new FileInfo(path).Length); + .Where(path => new FileInfo(path).LinkTarget is null) + .Sum(path => new FileInfo(path).Length); publisher.Record(workspace, producer, [], null, "macos-arm64"); - BuildCacheCleanupPlan measured = BuildCacheCleanupPlan.Create(root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan measured = BuildCacheCleanupPlan.Create( + root, + [publisher.Describe("fixture")], + new BuildCachePolicy(0, 0), + retireAll: true + ); Assert.Equal(bytes, measured.totalBytes); } - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + root, + [publisher.Describe("fixture")], + new BuildCachePolicy(0, 0), + retireAll: true + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Equal(workspace, Assert.Single(result.retired)); Assert.Empty(result.failures); @@ -50,7 +61,9 @@ public async Task WorkspaceLibraryAliasesAreCountedOnceAndRetiredWithoutFollowin [SupportedOSPlatform("linux")] public async Task FileAliasesCannotEscapeCycleDangleOrEnterImmutableArtifacts() { - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoCacheLinkBoundary")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoCacheLinkBoundary") + ); string root = owner.directory; string cache = Path.Combine(root, "cache"); string workspace = Path.Combine(cache, "workspace"); @@ -75,7 +88,9 @@ public async Task FileAliasesCannotEscapeCycleDangleOrEnterImmutableArtifacts() [Fact] public async Task WorkspacesRejectDirectoryLinksEvenWhenTheTargetIsOwned() { - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoCacheDirectoryLinks")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoCacheDirectoryLinks") + ); string root = owner.directory; string cache = Path.Combine(root, "cache"); string workspace = Path.Combine(cache, "workspace"); @@ -86,12 +101,22 @@ public async Task WorkspacesRejectDirectoryLinksEvenWhenTheTargetIsOwned() { string escapedLink = link.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = target.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", "New-Item -ItemType Junction -Path '" + escapedLink + "' -Target '" + escapedTarget + "' | Out-Null"], - root, CancellationToken.None); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + escapedLink + "' -Target '" + escapedTarget + "' | Out-Null" + ], + root, + CancellationToken.None + ); } else + { Directory.CreateSymbolicLink(link, target); + } try { var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ReusableWorkspace); diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs index 8da45cfe0..9bb68edbe 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -6,8 +5,8 @@ using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; - using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Toolchains.Tests; @@ -21,21 +20,34 @@ public async Task ConcurrentSdkRequestsKeepExplicitOutputOwnersForTheSameTarget( Directory.CreateDirectory(root); try { - new XDocument(new XElement("Project", new XElement("Import", - new XAttribute("Project", Path.Combine(engine, "Directory.Build.props"))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.props"))) + ) + ) .Save(Path.Combine(root, "Directory.Build.props")); File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), ""); File.WriteAllText(Path.Combine(root, "Api.cs"), "public static class Api { public static int value => 42; }"); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "enable"), - new XElement("EnableDefaultCompileItems", "false")), - new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", "Api.cs"))))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "enable"), + new XElement("EnableDefaultCompileItems", "false") + ), + new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", "Api.cs"))) + ) + ) .Save(project); string first = Path.Combine(root, "requests", "first"); string second = Path.Combine(root, "requests", "second"); - string[][] outputs = await Task.WhenAll(Build(project, first), Build(project, second)); + string[][] outputs = await Task.WhenAll(BuildAsync(project, first), BuildAsync(project, second)); for (int index = 0; index < outputs.Length; index++) { string owner = Path.GetFullPath(index == 0 ? first : second) + Path.DirectorySeparatorChar; @@ -56,24 +68,43 @@ public async Task ConcurrentSdkRequestsKeepExplicitOutputOwnersForTheSameTarget( } } - private static async Task Build( + private static async Task BuildAsync( string project, string outputOwner ) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(sdk) { - WorkingDirectory = Path.GetDirectoryName(project)!, UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = Path.GetDirectoryName(project)!, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; string evaluated = Path.Combine(Path.GetDirectoryName(outputOwner)!, Path.GetFileName(outputOwner) + ".json"); Directory.CreateDirectory(Path.GetDirectoryName(evaluated)!); - foreach (string argument in new[] { "build", project, "--artifacts-path", outputOwner, - "-p:InnoNativeTarget=fixture-target", "-p:InnoNativeBuildFingerprint=fixture-fingerprint", - "-target:Build", "-getProperty:TargetPath,ProjectAssetsFile", "-getItem:IntermediateAssembly", "-getResultOutputFile:" + evaluated, - "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal" }) + foreach (string argument in new[] + { + "build", + project, + "--artifacts-path", + outputOwner, + "-p:InnoNativeTarget=fixture-target", + "-p:InnoNativeBuildFingerprint=fixture-fingerprint", + "-target:Build", + "-getProperty:TargetPath,ProjectAssetsFile", + "-getItem:IntermediateAssembly", + "-getResultOutputFile:" + evaluated, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "-v:minimal" + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("The SDK did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); @@ -92,7 +123,9 @@ string outputOwner Assert.True(process.ExitCode == 0, await output + await error); using JsonDocument result = JsonDocument.Parse(File.ReadAllText(evaluated)); JsonElement properties = result.RootElement.GetProperty("Properties"); - JsonElement intermediate = Assert.Single(result.RootElement.GetProperty("Items").GetProperty("IntermediateAssembly").EnumerateArray()); + JsonElement intermediate = Assert.Single( + result.RootElement.GetProperty("Items").GetProperty("IntermediateAssembly").EnumerateArray() + ); return [ Path.GetFullPath(properties.GetProperty("TargetPath").GetString()!), diff --git a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs index 6505ea21a..127b7a0e9 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs @@ -28,19 +28,30 @@ bool continuousIntegration string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoDevelopmentBuildTests")); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit SDK host is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - DirectoryInfo? repository = new(Directory.GetCurrentDirectory()); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit SDK host is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + var repository = new DirectoryInfo(Directory.GetCurrentDirectory()); while (repository is not null && !File.Exists(Path.Combine(repository.FullName, "InnoEngine.sln"))) + { repository = repository.Parent; + } Assert.NotNull(repository); try { Directory.CreateDirectory(Path.Combine(root, "build", "msbuild")); File.Copy(Path.Combine(repository.FullName, "Directory.Build.props"), Path.Combine(root, "Directory.Build.props")); File.Copy(Path.Combine(repository.FullName, "Directory.Build.targets"), Path.Combine(root, "Directory.Build.targets")); - File.Copy(Path.Combine(repository.FullName, "build", "msbuild", "Inno.Packages.props"), Path.Combine(root, "build", "msbuild", "Inno.Packages.props")); - File.Copy(Path.Combine(repository.FullName, "build", "msbuild", "Inno.Build.Tasks.targets"), Path.Combine(root, "build", "msbuild", "Inno.Build.Tasks.targets")); + File.Copy( + Path.Combine(repository.FullName, "build", "msbuild", "Inno.Packages.props"), + Path.Combine(root, "build", "msbuild", "Inno.Packages.props") + ); + File.Copy( + Path.Combine(repository.FullName, "build", "msbuild", "Inno.Build.Tasks.targets"), + Path.Combine(root, "build", "msbuild", "Inno.Build.Tasks.targets") + ); File.Copy(Path.Combine(repository.FullName, "global.json"), Path.Combine(root, "global.json")); await File.WriteAllTextAsync(Path.Combine(root, ".gitignore"), "bin/\nobj/\n"); await File.WriteAllTextAsync(Path.Combine(root, "Fixture.csproj"), """ @@ -72,13 +83,21 @@ await File.WriteAllTextAsync(Path.Combine(root, "Fixture.csproj"), """ Assert.Equal(beforeSymbols, afterSymbols); Assert.Equal(beforeTimestamp, File.GetLastWriteTimeUtc(assembly)); Assert.Equal(C_SOURCE, ReadEmbeddedSource(symbols, "Contract.cs")); - Assert.DoesNotContain(commit, await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), StringComparison.Ordinal); + Assert.DoesNotContain( + commit, + await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), + StringComparison.Ordinal + ); } else { Assert.False(beforeAssembly.SequenceEqual(afterAssembly)); Assert.False(beforeSymbols.SequenceEqual(afterSymbols)); - Assert.Contains(commit, await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), StringComparison.Ordinal); + Assert.Contains( + commit, + await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), + StringComparison.Ordinal + ); Assert.Contains(commit, ReadSourceLink(symbols), StringComparison.Ordinal); } @@ -88,9 +107,16 @@ async Task CommitAsync(string message) await RunAsync("git", "-c", "user.name=Aaron Liao", "-c", "user.email=hsuankailiao@gmail.com", "commit", "-m", message); } - Task BuildAsync() => RunAsync(dotnet, ["build", "Fixture.csproj", - ..configuration.Length == 0 ? Array.Empty() : ["-c", configuration], - "-p:ContinuousIntegrationBuild=" + continuousIntegration, "-m:1", "-nr:false", "--disable-build-servers"]); + Task BuildAsync() + => RunAsync(dotnet, [ + "build", + "Fixture.csproj", + ..configuration.Length == 0 ? Array.Empty() : ["-c", configuration], + "-p:ContinuousIntegrationBuild=" + continuousIntegration, + "-m:1", + "-nr:false", + "--disable-build-servers" + ]); async Task RunAsync( string executable, @@ -98,11 +124,16 @@ params string[] arguments ) { var start = new ProcessStartInfo(executable) { - WorkingDirectory = root, UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = root, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -115,11 +146,15 @@ params string[] arguments finally { if (!Path.GetFullPath(root).StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The development-build fixture escaped its temporary owner."); + } if (Directory.Exists(root)) { foreach (string file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) + { File.SetAttributes(file, FileAttributes.Normal); + } Directory.Delete(root, recursive: true); } } @@ -129,15 +164,22 @@ private static string ReadEmbeddedSource( string symbols, string fileName ) { - using var stream = File.OpenRead(symbols); + using FileStream stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); - DocumentHandle document = Assert.Single(reader.Documents.Where(handle => reader.GetString(reader.GetDocument(handle).Name).EndsWith(fileName, StringComparison.Ordinal))); - CustomDebugInformation source = Assert.Single(reader.GetCustomDebugInformation(document).Select(reader.GetCustomDebugInformation) - .Where(info => reader.GetGuid(info.Kind) == new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE"))); + DocumentHandle document = Assert.Single( + reader.Documents.Where(handle => reader.GetString(reader.GetDocument(handle).Name).EndsWith(fileName, StringComparison.Ordinal)) + ); + CustomDebugInformation source = Assert.Single( + reader.GetCustomDebugInformation(document) + .Select(reader.GetCustomDebugInformation) + .Where(info => reader.GetGuid(info.Kind) == new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE")) + ); byte[] data = reader.GetBlobBytes(source.Value); if (BitConverter.ToInt32(data, 0) == 0) + { return Encoding.UTF8.GetString(data, 4, data.Length - 4); + } using var compressed = new MemoryStream(data, 4, data.Length - 4, writable: false); using var decoder = new DeflateStream(compressed, CompressionMode.Decompress); using var decoded = new MemoryStream(); @@ -148,11 +190,13 @@ string fileName private static string ReadSourceLink(string symbols) { - using var stream = File.OpenRead(symbols); + using FileStream stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); - CustomDebugInformation source = Assert.Single(reader.CustomDebugInformation.Select(reader.GetCustomDebugInformation) - .Where(info => reader.GetGuid(info.Kind) == new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A"))); + CustomDebugInformation source = Assert.Single( + reader.CustomDebugInformation.Select(reader.GetCustomDebugInformation) + .Where(info => reader.GetGuid(info.Kind) == new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A")) + ); return Encoding.UTF8.GetString(reader.GetBlobBytes(source.Value)); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs index b2be55240..fc003a9c4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs @@ -2,9 +2,9 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -31,8 +31,12 @@ public async Task ConfirmationRetainsPublicationMetadataAndCurrentDependencyProt Assert.Equal(time, File.GetLastWriteTimeUtc(record)); publisher.Record(generation, generation + ".lock", [page], "selected", null); } - BuildCacheCleanupPlan protectedPlan = BuildCacheCleanupPlan.Create(Path.GetDirectoryName(m_root)!, - [publisher.Describe("documentation")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan protectedPlan = BuildCacheCleanupPlan.Create( + Path.GetDirectoryName(m_root)!, + [publisher.Describe("documentation")], + new BuildCachePolicy(0, 0), + retireAll: true + ); Assert.Empty((await protectedPlan.ExecuteAsync()).retired); Assert.True(Directory.Exists(page)); } @@ -53,11 +57,15 @@ public async Task ConfirmationRejectsChangedOwnershipWithoutRepairingItsRecord(s string record = Assert.Single(Directory.GetFiles(m_root, "*.cache.json")); byte[] bytes = File.ReadAllBytes(record); if (change == "payload") + { File.WriteAllText(Path.Combine(page, "extra"), "unaccounted bytes"); - Assert.Throws(() => publisher.EnsureImmutableRegistration(page, + } + Assert.Throws(() => publisher.EnsureImmutableRegistration( + page, change == "lease" ? page + ".other.lock" : page + ".lock", change == "dependency" ? [Path.Combine(m_root, "dependency")] : [], - change == "target" ? "another-target" : null)); + change == "target" ? "another-target" : null + )); Assert.Equal(bytes, File.ReadAllBytes(record)); } } @@ -73,19 +81,30 @@ public async Task CanceledRegistrationDoesNotCreateOwnershipAndWorkspacesCannotO using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); Assert.Throws(() => publisher.EnsureImmutableRegistration( - page, page + ".lock", [], null, cancellation.Token)); + page, + page + ".lock", + [], + null, + cancellation.Token + )); Assert.Empty(Directory.GetFiles(m_root, "*.cache.json")); var workspace = new BuildCachePublisher(m_root, BuildCacheArtifactRole.ReusableWorkspace); Assert.Throws(() => workspace.EnsureImmutableRegistration(page, page + ".lock", [], null)); Assert.Throws(() => publisher.EnsureImmutableRegistration( - Path.Combine(m_root, "..", "foreign"), page + ".lock", [], null)); + Path.Combine(m_root, "..", "foreign"), + page + ".lock", + [], + null + )); } } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private string Create(string name) diff --git a/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs index 03e056ede..e10721fbd 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs @@ -5,8 +5,8 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -18,8 +18,11 @@ public async Task RootOutputsBelongToTheEvaluatedInstanceEvenWithNonrepeatablePr string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { Directory.CreateDirectory(root); @@ -33,19 +36,33 @@ public async Task RootOutputsBelongToTheEvaluatedInstanceEvenWithNonrepeatablePr """); - using JsonDocument graph = JsonDocument.Parse(await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [project], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true" })); + using JsonDocument graph = JsonDocument.Parse( + await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [project], + new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true" } + ) + ); JsonElement owner = Assert.Single(graph.RootElement.EnumerateArray()); JsonElement instance = Assert.Single(owner.GetProperty("Instances").EnumerateArray()); - Assert.Equal(instance.GetProperty("TargetPath").GetString(), owner.GetProperty("Properties").GetProperty("TargetPath").GetString()); + Assert.Equal( + instance.GetProperty("TargetPath").GetString(), + owner.GetProperty("Properties").GetProperty("TargetPath").GetString() + ); Assert.Empty(owner.GetProperty("Variants").EnumerateArray()); } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -60,33 +77,57 @@ bool explicitVersion string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); string project = Path.Combine(root, "Example.csproj"); - File.WriteAllText(project, "" + framework + "" + File.WriteAllText( + project, + "" + framework + "" + (explicitVersion ? "" : string.Empty) - + ""); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [project], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false" }); + + "" + ); + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [project], + new Dictionary + { + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false" + } + ); using JsonDocument graph = JsonDocument.Parse(captured); JsonElement owner = Assert.Single(graph.RootElement.EnumerateArray()); string pack = Assert.Single(owner.GetProperty("FrameworkPacks").EnumerateArray()).GetString()!; Assert.Equal("Microsoft.NETCore.App.Ref", Path.GetFileName(Path.GetDirectoryName(pack))); if (explicitVersion) + { Assert.Equal("99.0.1", Path.GetFileName(pack)); + } else + { Assert.True(Directory.Exists(pack)); + } } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -96,12 +137,17 @@ public async Task EquivalentVariantInputsSharePayloadWhileConditionalInputsAndPr string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { foreach (string name in new[] { "A", "B", "C" }) + { Directory.CreateDirectory(Path.Combine(root, name)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); File.WriteAllText(Path.Combine(root, "Extra.cs"), "namespace Example; public class Extra { }"); string first = Path.Combine(root, "A", "A.csproj"); @@ -110,36 +156,64 @@ public async Task EquivalentVariantInputsSharePayloadWhileConditionalInputsAndPr """); foreach ((string name, string flavor) in new[] { ("B", "one"), ("C", "two") }) - File.WriteAllText(Path.Combine(root, name, name + ".csproj"), + { + File.WriteAllText( + Path.Combine(root, name, name + ".csproj"), "net10.0" - + ""); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, + + "" + ); + } + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, [first, Path.Combine(root, "B", "B.csproj"), Path.Combine(root, "C", "C.csproj")], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false" }); + new Dictionary + { + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false" + } + ); using JsonDocument graph = JsonDocument.Parse(captured); JsonElement owner = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == first); - Assert.Contains(owner.GetProperty("EquivalentGlobalProperties").EnumerateArray(), - properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "one"); + Assert.Contains( + owner.GetProperty("EquivalentGlobalProperties").EnumerateArray(), + properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "one" + ); JsonElement variant = Assert.Single(owner.GetProperty("Variants").EnumerateArray()); - Assert.Contains(variant.GetProperty("EquivalentGlobalProperties").EnumerateArray(), - properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "two"); - Assert.Contains(variant.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs")); - Assert.DoesNotContain(owner.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs")); + Assert.Contains( + variant.GetProperty("EquivalentGlobalProperties").EnumerateArray(), + properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "two" + ); + Assert.Contains( + variant.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs") + ); + Assert.DoesNotContain( + owner.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs") + ); foreach ((string name, string flavor) in new[] { ("B", "one"), ("C", "two") }) { - JsonElement consumer = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == Path.Combine(root, name, name + ".csproj")); + JsonElement consumer = graph.RootElement + .EnumerateArray() + .Single(node => node.GetProperty("Path").GetString() == Path.Combine(root, name, name + ".csproj")); JsonElement instance = Assert.Single(consumer.GetProperty("Instances").EnumerateArray()); string reference = Assert.Single(instance.GetProperty("References").EnumerateArray()).GetString()!; - JsonElement selected = owner.GetProperty("Instances").EnumerateArray().Single(node => node.GetProperty("Identity").GetString() == reference); + JsonElement selected = owner + .GetProperty("Instances") + .EnumerateArray() + .Single(node => node.GetProperty("Identity").GetString() == reference); Assert.Equal(flavor, selected.GetProperty("GlobalProperties").GetProperty("Flavor").GetString()); } } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } Directory.Delete(root, recursive: true); } } @@ -152,8 +226,11 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); Directory.CreateDirectory(Path.Combine(root, "A")); Directory.CreateDirectory(Path.Combine(root, "B")); try @@ -161,14 +238,31 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); string first = Path.Combine(root, "A", "A.csproj"); string second = Path.Combine(root, "B", "B.csproj"); - File.WriteAllText(first, "net10.0"); + File.WriteAllText( + first, + "net10.0" + ); File.WriteAllText(Path.Combine(root, "A", "Contract.cs"), "namespace Contracts; public class Contract { }"); File.WriteAllText(Path.Combine(root, "Imported.cs"), "namespace Consumers; public class Consumer : Contracts.Contract { }"); - File.WriteAllText(Path.Combine(root, "Imported.props"), "$(DefineConstants);IMPORTED"); - File.WriteAllText(second, "net10.0true"); - var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; + File.WriteAllText( + Path.Combine(root, "Imported.props"), + "$(DefineConstants);IMPORTED" + ); + File.WriteAllText( + second, + "net10.0true" + ); + var start = new ProcessStartInfo(dotnet) + { + WorkingDirectory = root, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; foreach (string argument in new[] { "build", second, "-m:1", "-nr:false", "--disable-build-servers" }) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -181,28 +275,45 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo """); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [first, second], + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [first, second], new Dictionary { - ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = buildReferences.ToString(), ["InnoProductRestore"] = "false" - }, resolveReferences: true); + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = buildReferences.ToString(), + ["InnoProductRestore"] = "false" + }, + resolveReferences: true + ); using JsonDocument graph = JsonDocument.Parse(captured); Assert.Equal(2, graph.RootElement.GetArrayLength()); JsonElement consumer = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == second); string[] defines = consumer.GetProperty("Properties").GetProperty("DefineConstants").GetString()!.Split(';'); Assert.Contains("IMPORTED", defines); Assert.Contains("NET10_0", defines); - Assert.Contains(consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), - item => Path.GetFileName(item.GetProperty("FullPath").GetString()) == "A.dll"); - Assert.Contains(consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), - item => item.TryGetProperty("FrameworkReferenceName", out JsonElement value) && value.GetString() == "Microsoft.NETCore.App"); - Assert.Contains(consumer.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Imported.cs")); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), + item => Path.GetFileName(item.GetProperty("FullPath").GetString()) == "A.dll" + ); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), + item => item.TryGetProperty("FrameworkReferenceName", out JsonElement value) && value.GetString() == "Microsoft.NETCore.App" + ); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Imported.cs") + ); } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs index 0c0c03643..4893cd090 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -14,11 +14,11 @@ public void PythonBytecodeIsDerivedWhileSourceAndExplicitCompilerInputsRemainVer { string script = Write("sdk/compiler.py", "print('one')"); string compiler = Write("sdk/bin/clang", "compiler-one"); - var inputs = new[] - { + NativeBuildInput[] inputs = + [ new NativeBuildInput("sdk", Path.GetDirectoryName(script)!), new NativeBuildInput("sdk/bin", Path.GetDirectoryName(compiler)!) - }; + ]; string original = NativeBuildFingerprint.Create(["wasm32"], inputs); Write("sdk/__pycache__/compiler.cpython-311.pyc", "derived-bytecode"); Assert.Equal(original, NativeBuildFingerprint.Create(["wasm32"], inputs)); @@ -36,14 +36,31 @@ public void MultipurposeRecipeOwnerIncludesOnlyItsDeclaredImplementationClosure( string project = Write("platforms/Fixture/Inno.Build.Fixture.csproj", ""); string builder = Write("platforms/Fixture/NativeBuilder.cs", "builder"); string packaging = Write("platforms/Fixture/Packaging.cs", "packaging"); - var owner = new NativeComponentDescriptor("fixture", - Path.GetRelativePath(m_root, project), Path.GetRelativePath(m_root, project)); - var context = new NativeBuildContext(m_root, "release").WithComponentOptions(owner, new(NativeLibraryKind.Shared)); + var owner = new NativeComponentDescriptor( + "fixture", + Path.GetRelativePath(m_root, project), + Path.GetRelativePath(m_root, project) + ); + NativeBuildContext context = new NativeBuildContext(m_root, "release").WithComponentOptions( + owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared) + ); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( - context, owner, "fixture", "fixture-target", [], [], [builder]); + context, + owner, + "fixture", + "fixture-target", + [], + [], + [builder] + ); foreach (NativeBuildInput input in recipe.inputs) + { if (!File.Exists(input.physicalPath) && !Directory.Exists(input.physicalPath)) + { Write(Path.GetRelativePath(m_root, input.physicalPath), "common executor"); + } + } string identity = NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs); File.WriteAllText(packaging, "unrelated packaging changed"); Assert.Equal(identity, NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs)); @@ -56,12 +73,43 @@ public void FingerprintPreservesDeclarationOrderAndChangesForSourceOrSdkIdentity { string header = Write("include/api.h", "int sample(void);"); string compiler = Write("tools/clang", "compiler"); - string first = NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)]); - Assert.Equal(first, NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("tools/clang", compiler), new NativeBuildInput("include/api.h", header), new NativeBuildInput("include/api.h", header)])); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["sdk-b", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["wasm32", "sdk-a"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); + string first = NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ); + Assert.Equal( + first, + NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [ + new NativeBuildInput("tools/clang", compiler), + new NativeBuildInput("include/api.h", header), + new NativeBuildInput("include/api.h", header) + ] + ) + ); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["sdk-b", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["wasm32", "sdk-a"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); File.WriteAllText(header, "long sample(void);"); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); Assert.Throws(() => new NativeBuildInput("include/api.h", "relative.h")); } @@ -71,15 +119,19 @@ public void LogicalInputsCanMoveWithoutChangingIdentityAndSameTimestampTampering string first = Write("checkout-a/include/api.h", "int one(void);"); string relocated = Write("checkout-b/include/api.h", "int one(void);"); string fingerprint = NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", first)]); - Assert.Equal(fingerprint, - NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)])); + Assert.Equal( + fingerprint, + NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)]) + ); DateTime timestamp = File.GetLastWriteTimeUtc(relocated); long length = new FileInfo(relocated).Length; File.WriteAllText(relocated, "int two(void);"); File.SetLastWriteTimeUtc(relocated, timestamp); Assert.Equal(length, new FileInfo(relocated).Length); - Assert.NotEqual(fingerprint, - NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)])); + Assert.NotEqual( + fingerprint, + NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)]) + ); } [Fact] @@ -115,10 +167,14 @@ public void RequestDescriptorRejectsUnavailableOutputs() { string bindings = Write("Generated/Bindings.cs", "generated"); string descriptor = Path.Combine(m_root, "request.json"); - new NativeBindingGenerationDescriptor { - fingerprint = "identity", bindingsPath = bindings, nativeDirectory = string.Empty, + new NativeBindingGenerationDescriptor + { + fingerprint = "identity", + bindingsPath = bindings, + nativeDirectory = string.Empty, usesRuntimeImports = false, - artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty + artifactDirectory = string.Empty, + artifactOwnerDirectory = string.Empty }.Write(descriptor); Assert.Equal(bindings, NativeBindingGenerationDescriptor.Load(descriptor).bindingsPath); File.Delete(bindings); @@ -128,7 +184,9 @@ public void RequestDescriptorRejectsUnavailableOutputs() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private string Write( diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs index 436e023b9..e357cc37c 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs @@ -1,18 +1,25 @@ using System; +using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; public sealed class NativeArtifactImportTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoNativeImport", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_owner = new("fixture", "component/Fixture.csproj", "component/Fixture.csproj"); [Fact] @@ -24,7 +31,14 @@ public async Task ImportedImmutableContentIsVerifiedAndRegisteredWithoutCopyingS string imported = Import(source, producer, consumer); Assert.False(File.Exists(imported + ".read.lock")); Assert.Empty(BuildCacheOwnerCatalog.ReadOwners(consumer)); - using NativeBuildProduct selected = await PublishAsync(consumer, static (_, _, _) => throw new InvalidOperationException("A valid import must not compile again.")); + using NativeBuildProduct selected = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("A valid import must not compile again.") + ); Assert.Equal(source.fingerprint, selected.fingerprint); Assert.Equal("result", File.ReadAllText(selected.files.Single())); Assert.Contains(BuildCacheOwnerCatalog.ReadOwners(consumer), owner => owner.id == "native"); @@ -52,17 +66,32 @@ public async Task DamagedImportedContentsCannotBypassTheRealProducer(string dama File.SetLastWriteTimeUtc(output, timestamp); } else if (damage == "missing") + { File.Delete(output); + } else if (damage == "additional") + { File.WriteAllText(Path.Combine(imported, "Outputs", "unexpected"), "extra"); + } else - File.WriteAllText(Path.Combine(imported, "generation-manifest.json"), System.Text.Json.JsonSerializer.Serialize(new - { - fingerprint = damage == "wrong-identity" ? new string('0', 64) : source.fingerprint, - files = new System.Collections.Generic.Dictionary { ["../escape"] = new string('0', 64) } - })); - await Assert.ThrowsAsync(() => PublishAsync(consumer, - static (_, _, _) => throw new InvalidOperationException("Retain the first real producer failure."))); + { + File.WriteAllText( + Path.Combine(imported, "generation-manifest.json"), + JsonSerializer.Serialize(new + { + fingerprint = damage == "wrong-identity" ? new string('0', 64) : source.fingerprint, + files = new Dictionary { ["../escape"] = new string('0', 64) } + }) + ); + } + await Assert.ThrowsAsync(() => PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("Retain the first real producer failure.") + )); Assert.Empty(Directory.GetFiles(Path.Combine(consumer, "artifacts", "native"), "*.current")); using NativeBuildProduct repaired = await PublishAsync(consumer, ProduceAsync); Assert.True(BuildArtifactManifest.IsComplete(repaired.directory, source.fingerprint, ["Outputs", "Metadata"])); @@ -83,11 +112,20 @@ public async Task TransportExcludesUnadoptedCandidatesAndReimportsWithoutProduce string archive = Path.Combine(producer, "artifacts", "transfer.zip"); Assert.Equal(1, await NativeArtifactTransfer.ExportAsync(producer, archive)); using (ZipArchive zip = ZipFile.OpenRead(archive)) + { Assert.All(zip.Entries, entry => Assert.DoesNotContain(other.fingerprint, entry.FullName)); + } Assert.Equal(1, await NativeArtifactTransfer.ImportAsync(consumer, archive)); Assert.DoesNotContain(BuildCacheOwnerCatalog.ReadOwners(consumer), owner => owner.id == "native"); Assert.Empty(Directory.GetFiles(Path.Combine(consumer, "artifacts", "native"), "*.cache.json")); - using NativeBuildProduct selected = await PublishAsync(consumer, static (_, _, _) => throw new InvalidOperationException("The imported candidate must be reusable.")); + using NativeBuildProduct selected = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("The imported candidate must be reusable.") + ); Assert.Equal(source.fingerprint, selected.fingerprint); Assert.Equal(0, await NativeArtifactTransfer.ImportAsync(consumer, archive)); } @@ -105,13 +143,29 @@ public async Task ExportAllowsRegisteredPublishersThatHaveNotProducedAnyGenerati using NativeBuildProduct source = await PublishAsync(producer, ProduceAsync); string archive = Path.Combine(producer, "artifacts", "transfer.zip"); string relative = Path.GetRelativePath(Path.Combine(producer, "artifacts"), source.directory).Replace('\\', '/'); - Assert.Equal(1, await NativeArtifactTransfer.ExportAsync(producer, archive, - selectedArtifacts: exactSelection ? new System.Collections.Generic.HashSet(StringComparer.Ordinal) { relative } : null)); + Assert.Equal( + 1, + await NativeArtifactTransfer.ExportAsync( + producer, + archive, + selectedArtifacts: exactSelection + ? new HashSet(StringComparer.Ordinal) { relative } + : null + ) + ); using (ZipArchive zip = ZipFile.OpenRead(archive)) + { Assert.All(zip.Entries, entry => Assert.StartsWith(relative + "/", entry.FullName)); + } Assert.Equal(1, await NativeArtifactTransfer.ImportAsync(consumer, archive)); - using NativeBuildProduct imported = await PublishAsync(consumer, - static (_, _, _) => throw new InvalidOperationException("The transferred generation must not compile again.")); + using NativeBuildProduct imported = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("The transferred generation must not compile again.") + ); Assert.Equal(source.fingerprint, imported.fingerprint); Assert.Equal("result", File.ReadAllText(imported.files.Single())); } @@ -132,14 +186,18 @@ public async Task TransportRejectsIncompleteOrUnsafeArchivesBeforeInstallingAnyC { ZipArchiveEntry output = zip.Entries.Single(entry => entry.FullName.EndsWith("result.fixture", StringComparison.Ordinal)); if (damage == "missing") + { output.Delete(); + } else if (damage == "tamper") { using var writer = new StreamWriter(output.Open()); writer.Write("broken"); } else if (damage == "link") - output.ExternalAttributes = 0xa000 << 16; + { + output.ExternalAttributes = 0xA000 << 16; + } else { using var writer = new StreamWriter(zip.CreateEntry("../escape").Open()); @@ -161,11 +219,27 @@ public async Task CanceledExportPreservesThePreviousTransport() byte[] before = File.ReadAllBytes(archive); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => NativeArtifactTransfer.ExportAsync(producer, archive, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => NativeArtifactTransfer.ExportAsync(producer, archive, cancellationToken: cancellation.Token) + ); Assert.Equal(before, File.ReadAllBytes(archive)); Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(archive)!, "*.staging-*")); } + public void Dispose() + { + string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport") + + Path.DirectorySeparatorChar; + if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("The import fixture escaped its owner."); + } + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: true); + } + } + private string Prepare(string name) { string root = Path.Combine(m_root, name); @@ -177,15 +251,32 @@ private string Prepare(string name) return root; } - private Task PublishAsync(string root, Func produce) - => NativeArtifactPublisher.PublishAsync(new(root, "debug"), new(m_owner, "fixture", "fixture-target", - [NativeBuildInput.FromPath(root, "Source")], ["debug", "fixture-recipe"]), produce); + private Task PublishAsync( + string root, + Func produce + ) => NativeArtifactPublisher.PublishAsync( + new NativeBuildContext(root, "debug"), + new NativeBuildRecipe( + m_owner, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(root, "Source")], + ["debug", "fixture-recipe"] + ), + produce + ); - private static Task ProduceAsync(NativeBuildContext context, string directory, CancellationToken cancellation) - => File.WriteAllTextAsync(Path.Combine(directory, "result.fixture"), "result", cancellation); + private static Task ProduceAsync( + NativeBuildContext context, + string directory, + CancellationToken cancellationToken + ) => File.WriteAllTextAsync(Path.Combine(directory, "result.fixture"), "result", cancellationToken); - private static string Import(NativeBuildProduct source, string producer, string consumer) - { + private static string Import( + NativeBuildProduct source, + string producer, + string consumer + ) { string sourceDirectory = PathBoundary.RequireUnlinkedPath(producer, source.directory); string destination = PathBoundary.Resolve(consumer, Path.GetRelativePath(producer, sourceDirectory)); foreach (string file in Directory.GetFiles(source.directory, "*", SearchOption.AllDirectories)) @@ -196,13 +287,4 @@ private static string Import(NativeBuildProduct source, string producer, string } return destination; } - - public void Dispose() - { - string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport") + Path.DirectorySeparatorChar; - if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) - throw new InvalidOperationException("The import fixture escaped its owner."); - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: true); - } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs index b5e29592f..043c3679f 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs @@ -1,21 +1,19 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; using Inno.Build.Toolchains; - using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; public sealed class NativeArtifactPublicationTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoNativePublication", Guid.NewGuid().ToString("N")); [Fact] @@ -24,25 +22,34 @@ public async Task RepairWaitsForReadersAndCancellationPreservesThePinnedDirector NativeBuildContext context = CreateContext(); string source = Path.Combine(m_root, "repair.h"); File.WriteAllText(source, "input"); - var owner = new NativeComponentDescriptor("fixture", + var owner = new NativeComponentDescriptor( + "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); NativeBuildRecipe recipe = CreateRecipe(context, owner, "fixture", "fixture-x64", [source], []); var prepared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); int calls = 0; - async Task Produce( + async Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { - await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellation); + await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellationToken); if (Interlocked.Increment(ref calls) > 1) + { prepared.TrySetResult(); + } } - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, recipe, Produce); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, recipe, ProduceAsync); File.WriteAllText(first.files[0], "damaged"); using var cancellation = new CancellationTokenSource(); - Task waiting = NativeArtifactPublisher.PublishAsync(CreateContext(), recipe, Produce, cancellation.Token); + Task waiting = NativeArtifactPublisher.PublishAsync( + CreateContext(), + recipe, + ProduceAsync, + cancellationToken: cancellation.Token + ); await prepared.Task.WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(80); Assert.False(waiting.IsCompleted); @@ -50,7 +57,7 @@ CancellationToken cancellation await Assert.ThrowsAnyAsync(() => waiting); Assert.Equal("damaged", File.ReadAllText(first.files[0])); first.Dispose(); - using NativeBuildProduct repaired = await NativeArtifactPublisher.PublishAsync(CreateContext(), recipe, Produce); + using NativeBuildProduct repaired = await NativeArtifactPublisher.PublishAsync(CreateContext(), recipe, ProduceAsync); Assert.Equal("complete", File.ReadAllText(repaired.files[0])); } @@ -61,30 +68,60 @@ public async Task MaterializationPreservesIdenticalTimestampsAndRejectsChangesAf string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "int first;"); string intermediate = Path.Combine(m_root, "Intermediate", "input.h"); - using NativeBuildProduct result1 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct result1 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { Assert.True(await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation)); DateTime original = File.GetLastWriteTimeUtc(intermediate); Assert.False(await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation)); Assert.Equal(original, File.GetLastWriteTimeUtc(intermediate)); File.WriteAllText(Path.Combine(output, "result.native"), "complete"); - }); + } + ); context = CreateContext(); File.WriteAllText(source, "int newer;"); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { File.WriteAllText(source, "int wrong;"); await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation); - })); + } + )); Assert.Equal("int first;", File.ReadAllText(intermediate)); Assert.Empty(Directory.EnumerateFiles(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -97,18 +134,33 @@ public async Task CanceledMaterializationPreservesTheOwnedIntermediate() string intermediate = Path.Combine(m_root, "input.h"); File.WriteAllText(source, "source"); File.WriteAllText(intermediate, "previous"); - using NativeBuildProduct result2 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct result2 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { using var canceled = new CancellationTokenSource(); canceled.Cancel(); await Assert.ThrowsAnyAsync(() => NativeInputMaterializer.CopyAsync(scoped, source, intermediate, canceled.Token).AsTask()); File.WriteAllText(Path.Combine(output, "result.native"), "complete"); - }); + } + ); Assert.Equal("previous", File.ReadAllText(intermediate)); } @@ -123,28 +175,42 @@ public async Task SdkDirectoryAliasesContributeContentAndDirectoryCyclesFailBefo string header = Path.Combine(headers, "api.h"); File.WriteAllText(header, "first declaration"); string alias = Path.Combine(source, "include"); - await CreateDirectoryAlias(alias, headers); + await CreateDirectoryAliasAsync(alias, headers); string cycle = Path.Combine(source, "cycle"); try { - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation - ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); - Task Publish() + CancellationToken cancellationToken + ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellationToken); + Task PublishAsync() { NativeBuildContext operation = CreateContext(); - return NativeArtifactPublisher.PublishAsync(operation, - CreateRecipe(operation, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), Produce); + return NativeArtifactPublisher.PublishAsync( + operation, + CreateRecipe( + operation, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + ProduceAsync + ); } - using NativeBuildProduct first = await Publish(); + using NativeBuildProduct first = await PublishAsync(); File.WriteAllText(header, "changed declaration"); - using NativeBuildProduct changed = await Publish(); + using NativeBuildProduct changed = await PublishAsync(); Assert.NotEqual(first.fingerprint, changed.fingerprint); - await CreateDirectoryAlias(cycle, source); - IOException failure = await Assert.ThrowsAsync(() => Publish()); + await CreateDirectoryAliasAsync(cycle, source); + IOException failure = await Assert.ThrowsAsync(() => PublishAsync()); Assert.Contains("cycle", failure.Message, StringComparison.OrdinalIgnoreCase); Assert.Equal("complete", File.ReadAllText(first.files[0])); @@ -154,7 +220,9 @@ Task Publish() finally { if (Directory.Exists(cycle)) + { Directory.Delete(cycle, recursive: false); + } Directory.Delete(alias, recursive: false); } } @@ -168,23 +236,44 @@ public async Task ConcurrentRequestsShareOneCompleteProductAndTamperingIsRepaire File.WriteAllText(Path.Combine(source, "api.h"), "source"); int builds = 0; string? toolDirectory = null; - async Task Produce( + async Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { Interlocked.Increment(ref builds); - string intermediate = scoped.GetNativeBuildRoot(new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj")); + string intermediate = scoped.GetNativeBuildRoot( + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ) + ); string physical = new DirectoryInfo(intermediate).LinkTarget ?? intermediate; Assert.Contains(Path.Combine("obj", "native", "fixture-x64"), physical); toolDirectory = intermediate; Assert.True(Directory.Exists(intermediate)); - await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); + await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellationToken); } - Task Publish() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], ["sdk"]), Produce); + Task PublishAsync() + => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + ["sdk"] + ), + ProduceAsync + ); - NativeBuildProduct[] products = await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Publish())); + NativeBuildProduct[] products = await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => PublishAsync())); Assert.Equal(1, builds); Assert.True(Directory.Exists(toolDirectory)); Assert.All(products, product => Assert.Equal(products[0].directory, product.directory)); @@ -192,8 +281,10 @@ Task Publish() => NativeArtifactPublisher.PublishAsync(conte File.WriteAllText(products[0].files[0], "tampered"); foreach (NativeBuildProduct product in products) + { product.Dispose(); - using NativeBuildProduct repaired = await Publish(); + } + using NativeBuildProduct repaired = await PublishAsync(); Assert.Equal(2, builds); Assert.Equal(products[0].fingerprint, repaired.fingerprint); Assert.Equal("complete", File.ReadAllText(repaired.files[0])); @@ -206,23 +297,65 @@ public async Task SharedInitialInputsAreHashedOnceButEveryPublicationRechecksThe NativeBuildContext context = CreateContext(); string source = Path.Combine(m_root, "shared.h"); File.WriteAllText(source, "shared"); - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation - ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); - using NativeBuildProduct result3 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "first", "fixture-x64", [source], []), Produce); - using NativeBuildProduct result4 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "second", "fixture-x64", [source], []), Produce); + CancellationToken cancellationToken + ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellationToken); + using NativeBuildProduct result3 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "first", + "fixture-x64", + [source], + [] + ), + ProduceAsync + ); + using NativeBuildProduct result4 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "second", + "fixture-x64", + [source], + [] + ), + ProduceAsync + ); Assert.Equal(5, context.statistics.hashedFiles); Assert.Equal(30, context.statistics.hashedBytes); DateTime timestamp = File.GetLastWriteTimeUtc(source); File.WriteAllText(source, "unsafe"); File.SetLastWriteTimeUtc(source, timestamp); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "third", "fixture-x64", [source], []), Produce)); + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "third", + "fixture-x64", + [source], + [] + ), + ProduceAsync + )); } [Fact] @@ -232,35 +365,77 @@ public async Task ChangedClosureAndFailedPreparationPreserveEarlierProducts() string source = Path.Combine(m_root, "Source"); Directory.CreateDirectory(source); File.WriteAllText(Path.Combine(source, "api.h"), "source"); - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation - ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), Produce); + CancellationToken cancellationToken + ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellationToken); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + ProduceAsync + ); File.WriteAllText(Path.Combine(source, "added.h"), "new closure"); context = CreateContext(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), ( @scoped, output, cancellation - ) => throw new IOException("Compiler failed."))); + ) => throw new IOException("Compiler failed.") + )); Assert.Equal("complete", File.ReadAllText(first.files[0])); context = CreateContext(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { - await Produce(scoped, output, cancellation); + ) => + { + await ProduceAsync(scoped, output, cancellation); File.WriteAllText(Path.Combine(source, "changed-during-build.h"), "changed"); - })); + } + )); Assert.Equal("complete", File.ReadAllText(first.files[0])); Assert.Empty(Directory.GetDirectories(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -271,33 +446,61 @@ public async Task DeploymentUsesExactProductsAndPreservesThePriorTreeOnCancellat NativeBuildContext context = CreateContext(); string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "source"); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); string link = Path.Combine(output, "Link"); Directory.CreateDirectory(link); await File.WriteAllTextAsync(Path.Combine(link, "api.lib"), "build-only", cancellation); - }); + } + ); var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( - "fixture", new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), new(NativeLibraryKind.Shared), [], + "fixture", + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], ( context, dependencies, token ) => Task.FromResult(product), - selected => CreateRecipe(selected, productOwner(), "fixture", "fixture-x64", [source], []), + selected => CreateRecipe(selected, ProductOwner(), "fixture", "fixture-x64", [source], []), ( relative, target - ) => relative.Split(Path.DirectorySeparatorChar)[0] == "Link" - ? null : Path.Combine("fixture", target, relative))]); + ) => ( + relative.Split(Path.DirectorySeparatorChar)[0] == "Link" + ? null + : Path.Combine("fixture", target, relative) + ) + )]); string application = Path.Combine(m_root, "Application"); - await Task.WhenAll(Enumerable.Range(0, 3) - .Select(_ => ProductNativeDeployment.InstallAsync([product], plan, application).AsTask())); + await Task.WhenAll( + Enumerable.Range(0, 3) + .Select(_ => ProductNativeDeployment.InstallAsync([product], plan, application).AsTask()) + ); string deployed = Path.Combine(application, "native", "fixture", "fixture-x64", "api.native"); Assert.Equal("complete", File.ReadAllText(deployed)); Assert.Single(Directory.EnumerateFiles(Path.Combine(application, "native"), "*", SearchOption.AllDirectories)); @@ -334,9 +537,12 @@ await Assert.ThrowsAsync(() => Assert.Empty(Directory.EnumerateFileSystemEntries(canceledCandidate)); Assert.Empty(Directory.EnumerateDirectories(application, "*.staging-*")); - static NativeComponentDescriptor productOwner() => new("fixture", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + static NativeComponentDescriptor ProductOwner() + => new( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); } [Fact] @@ -346,15 +552,31 @@ public async Task CanceledProducerCannotPublishItsCandidate() string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "source"); using var cancellation = new CancellationTokenSource(); - await Assert.ThrowsAnyAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAnyAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, token - ) => { + ) => + { await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "candidate", token); cancellation.Cancel(); - }, cancellation.Token)); + }, + cancellationToken: cancellation.Token + )); Assert.Empty(Directory.EnumerateFiles(Path.Combine(m_root, "artifacts"), "api.native", SearchOption.AllDirectories)); Assert.Empty(Directory.GetDirectories(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -362,22 +584,39 @@ await Assert.ThrowsAnyAsync(() => NativeArtifactPubl public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } + } + + private NativeBuildContext CreateContext() + { + Directory.CreateDirectory(m_root); + File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); + string projectName = "Inno.Build.Toolchains"; + string owner = Path.Combine(m_root, "build", "toolchains", projectName); + Directory.CreateDirectory(owner); + File.WriteAllText(Path.Combine(owner, projectName + ".csproj"), ""); + return new(m_root, "release"); } private static NativeBuildRecipe CreateRecipe( NativeBuildContext context, NativeComponentDescriptor owner, string component, - string targetId, + string targetID, IReadOnlyList inputPaths, IReadOnlyList declarations - ) => new(owner, component, targetId, + ) => new( + owner, + component, + targetID, inputPaths.Concat(context.toolchain?.inputPaths ?? []) .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), - declarations.Concat(context.toolchain?.declarations ?? [])); + declarations.Concat(context.toolchain?.declarations ?? []) + ); - private static async Task CreateDirectoryAlias( + private static async Task CreateDirectoryAliasAsync( string path, string target ) { @@ -388,20 +627,16 @@ string target } string escapedPath = path.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = target.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedPath}' -Target '{escapedTarget}' | Out-Null"], - Path.GetDirectoryName(path)!, CancellationToken.None); - } - - private NativeBuildContext CreateContext() - { - Directory.CreateDirectory(m_root); - File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); - string projectName = "Inno.Build.Toolchains"; - string owner = Path.Combine(m_root, "build", "toolchains", projectName); - Directory.CreateDirectory(owner); - File.WriteAllText(Path.Combine(owner, projectName + ".csproj"), ""); - return new(m_root, "release"); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedPath}' -Target '{escapedTarget}' | Out-Null" + ], + Path.GetDirectoryName(path)!, + CancellationToken.None + ); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs index 9f987c92b..3573cd951 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs @@ -4,8 +4,8 @@ using System.Text; using System.Text.Json; using System.Threading; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -77,8 +77,11 @@ public void MissingRootSemanticsAndUnknownFieldsAreRejected() Directory.CreateDirectory(m_root); string json = JsonSerializer.Serialize(Create()); string path = Path.Combine(m_root, "compilation.json"); - File.WriteAllText(path, json.Replace("\"frozen\":true,", string.Empty, StringComparison.Ordinal) - .Replace(",\"frozen\":true", string.Empty, StringComparison.Ordinal)); + File.WriteAllText( + path, + json.Replace("\"frozen\":true,", string.Empty, StringComparison.Ordinal) + .Replace(",\"frozen\":true", string.Empty, StringComparison.Ordinal) + ); Assert.Throws(() => NativeBindingCompilation.Load(m_root)); File.WriteAllText(path, json.Insert(1, "\"unrecognized\":true,")); Assert.Throws(() => NativeBindingCompilation.Load(m_root)); @@ -87,7 +90,9 @@ public void MissingRootSemanticsAndUnknownFieldsAreRejected() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, true); + } } private static NativeBindingCompilation Create() @@ -95,11 +100,30 @@ private static NativeBindingCompilation Create() string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("verified"))); return new NativeBindingCompilation { - roots = [new("user", "source", false, true), new("nested", "source/nested", false, true), new("generated", "", true, true)], - files = [new("user", "nested/api.hpp", 8, hash, false), new("nested", "api.hpp", 8, hash, true)], - includeDirectories = [new("user", "", false, false), new("nested", "", false, false)], - defines = ["first", "second"], compilerDefines = ["__COMPILER_FACT=1"], cxxStandard = 20, cStandard = 0, - requiredExports = ["exported"], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] + roots = + [ + new NativeBindingSourceRoot("user", "source", false, true), + new NativeBindingSourceRoot("nested", "source/nested", false, true), + new NativeBindingSourceRoot("generated", string.Empty, true, true) + ], + files = + [ + new NativeBindingSourceFile("user", "nested/api.hpp", 8, hash, false), + new NativeBindingSourceFile("nested", "api.hpp", 8, hash, true) + ], + includeDirectories = + [ + new NativeBindingIncludeDirectory("user", string.Empty, false, false), + new NativeBindingIncludeDirectory("nested", string.Empty, false, false) + ], + defines = ["first", "second"], + compilerDefines = ["__COMPILER_FACT=1"], + cxxStandard = 20, + cStandard = 0, + requiredExports = ["exported"], + staticExportSymbols = [], + staticExportAbi = string.Empty, + staticExportNames = [] }; } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs index ae1ef12dc..ec406a9d4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs @@ -5,24 +5,43 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; + public sealed class NativeDependencyManifestTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoDependencyTests", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoDependencyTests", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_component = new("fixture", "component/Native.csproj", "component/Toolchain.csproj"); private int m_productions; + [Fact] public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdoptedByItsOwner() { - var fixture = await PrepareAsync(); - using ProductNativeBuildResult result = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); + using ProductNativeBuildResult result = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal("payload", File.ReadAllText(Assert.Single(result).files.Single())); Assert.Equal(1, m_productions); Assert.Single(Directory.GetFiles(Path.Combine(fixture.consumer, "artifacts", "native"), "*.cache.json")); - using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal(result[0].fingerprint, warm[0].fingerprint); Assert.Equal(1, m_productions); } @@ -30,8 +49,14 @@ public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdopt [Fact] public async Task AggregateProductsRetainTheirExplicitLayoutWithoutPlatformBranches() { - var fixture = await PrepareAsync(aggregate: true); - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(aggregate: true); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal(Path.Combine(imported[0].directory, "Outputs"), imported.aggregateDirectory); Assert.Equal("payload", File.ReadAllText(Assert.Single(imported).files.Single())); Assert.Empty(imported.bindingGenerations); @@ -43,11 +68,19 @@ public async Task AggregateProductsRetainTheirExplicitLayoutWithoutPlatformBranc [InlineData(true)] public async Task SelectionIsReadOnlyAndRequiresNoArchive(bool aggregate) { - var fixture = await PrepareAsync(aggregate); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(aggregate); string downloads = Path.Combine(fixture.consumer, "artifacts", "fixture-target", "native"); foreach (string archive in Directory.GetFiles(downloads)) + { File.Delete(archive); - IReadOnlyList selected = await NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + } + IReadOnlyList selected = await NativeDependencyManifest.SelectAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Single(selected); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); @@ -59,9 +92,11 @@ public async Task SelectionIsReadOnlyAndRequiresNoArchive(bool aggregate) [InlineData("{\"assets\": [null], \"aggregates\": []}")] public async Task MalformedSelectionFailsBeforeTouchingArtifacts(string json) { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); File.WriteAllText(fixture.selection, json); - await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + await Assert.ThrowsAsync( + () => NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); } @@ -75,10 +110,16 @@ public async Task MalformedSelectionFailsBeforeTouchingArtifacts(string json) [InlineData("added-recipe")] public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damage) { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); JsonObject selection = JsonNode.Parse(File.ReadAllText(fixture.selection))!.AsObject(); JsonObject asset = selection["assets"]![0]!.AsObject(); - string archive = Path.Combine(fixture.consumer, "artifacts", "fixture-target", "native", asset["sha256"]!.GetValue() + ".zip"); + string archive = Path.Combine( + fixture.consumer, + "artifacts", + "fixture-target", + "native", + asset["sha256"]!.GetValue() + ".zip" + ); switch (damage) { case "missing": @@ -105,23 +146,38 @@ public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damag } File.WriteAllText(fixture.selection, selection.ToJsonString()); - Exception? failure = await Record.ExceptionAsync(() => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + Exception? failure = await Record.ExceptionAsync( + () => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); if (damage == "missing") + { Assert.IsType(failure); + } else + { Assert.IsType(failure); + } Assert.Equal(1, m_productions); } [Fact] public async Task ModifiedInstalledArtifactFailsWithoutRepairOrProduction() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); string output; - using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)) + using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )) { output = imported[0].files.Single(); + } File.WriteAllText(output, "changed"); - await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + await Assert.ThrowsAsync( + () => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); Assert.Equal("changed", File.ReadAllText(output)); Assert.Equal(1, m_productions); } @@ -129,14 +185,24 @@ public async Task ModifiedInstalledArtifactFailsWithoutRepairOrProduction() [Fact] public async Task ForeignDependencyClosureIsRejectedBeforeDownloadOrInstallation() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); JsonObject selection = JsonNode.Parse(File.ReadAllText(fixture.selection))!.AsObject(); selection["assets"]![0]!["dependencies"] = new JsonObject { ["foreign"] = new string('a', 64) }; File.WriteAllText(fixture.selection, selection.ToJsonString()); await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); } @@ -144,16 +210,21 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac [Fact] public async Task IndexFlagsCannotHideChangedConsumerSourceBytes() { - var fixture = await PrepareAsync(); - const string relative = "component/Source/source.h"; - await Git(fixture.consumer, "update-index", "--assume-unchanged", relative); - string source = Path.Combine(fixture.consumer, relative); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); + const string C_RELATIVE = "component/Source/source.h"; + await GitAsync(fixture.consumer, "update-index", "--assume-unchanged", C_RELATIVE); + string source = Path.Combine(fixture.consumer, C_RELATIVE); DateTime timestamp = File.GetLastWriteTimeUtc(source); File.WriteAllText(source, "native other"); File.SetLastWriteTimeUtc(source, timestamp); - Assert.Equal(string.Empty, (await Git(fixture.consumer, "status", "--porcelain")).Trim()); + Assert.Equal(string.Empty, (await GitAsync(fixture.consumer, "status", "--porcelain")).Trim()); await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); } @@ -161,20 +232,44 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Se [Fact] public async Task PinnedSubmoduleNeedsNoConsumerCheckoutButMutableCheckoutCannotHideChanges() { - var fixture = await PrepareAsync(submodule: true); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(submodule: true); using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)) + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )) { Assert.Equal("payload", File.ReadAllText(imported[0].files.Single())); + } Assert.False(File.Exists(Path.Combine(fixture.consumer, "component", "Source", "source.h"))); - await Git(fixture.consumer, "-c", "protocol.file.allow=always", "submodule", "update", "--init"); + await GitAsync(fixture.consumer, "-c", "protocol.file.allow=always", "submodule", "update", "--init"); string sourceRoot = Path.Combine(fixture.consumer, "component", "Source"); - await Git(sourceRoot, "update-index", "--assume-unchanged", "source.h"); + await GitAsync(sourceRoot, "update-index", "--assume-unchanged", "source.h"); File.WriteAllText(Path.Combine(sourceRoot, "source.h"), "hidden changed input"); await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.Equal(1, m_productions); } + public void Dispose() + { + if (!Directory.Exists(m_root)) + { + return; + } + foreach (string file in Directory.EnumerateFiles(m_root, "*", SearchOption.AllDirectories)) + { + File.SetAttributes(file, FileAttributes.Normal); + } + Directory.Delete(m_root, recursive: true); + } + private async Task<(string consumer, string selection, ProductNativeBuildPlan plan)> PrepareAsync( bool aggregate = false, bool submodule = false @@ -187,64 +282,114 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac File.WriteAllText(Path.Combine(producer, ".gitignore"), "artifacts/\n**/obj/\n"); File.WriteAllText(Path.Combine(producer, "component", "Native.csproj"), ""); File.WriteAllText(Path.Combine(producer, "component", "Toolchain.csproj"), ""); - await Git(producer, "init"); + await GitAsync(producer, "init"); if (submodule) { string source = Path.Combine(producer, "component", "Source"); - await Git(source, "init"); - await Git(source, "add", "."); - await Git(source, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Native submodule"); - await Git(producer, "-c", "protocol.file.allow=always", "submodule", "add", source.Replace('\\', '/'), "component/Source"); + await GitAsync(source, "init"); + await GitAsync(source, "add", "."); + await GitAsync( + source, + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-m", + "Native submodule" + ); + await GitAsync(producer, "-c", "protocol.file.allow=always", "submodule", "add", source.Replace('\\', '/'), "component/Source"); } - await Git(producer, "add", "."); - await Git(producer, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Native source"); - await Git(m_root, "clone", "--no-hardlinks", producer, consumer); + await GitAsync(producer, "add", "."); + await GitAsync(producer, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Native source"); + await GitAsync(m_root, "clone", "--no-hardlinks", producer, consumer); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("fixture-host", "fixture-arch"), new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], new NativeLinkPlan(staticLibraryExtension: ".data"), false); - var context = new NativeBuildContext(producer, "release").WithToolchain(tools); - var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep("fixture", m_component, new(NativeLibraryKind.Static), [], Produce, Recipe, static ( - relative, - _ - ) => relative)]); - NativeBuildProduct? aggregateProduct = aggregate ? await Produce(context, new Dictionary(), CancellationToken.None) : null; - using ProductNativeBuildResult products = aggregateProduct is not null ? new ProductNativeBuildResult([aggregateProduct], new NativeBindingGenerationResult(new Dictionary(), []), Path.Combine(aggregateProduct.directory, "Outputs"), Recipe(context)) : await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); - string selection = await NativeDependencyManifest.ExportAsync(context, plan, products, Path.Combine(producer, "artifacts", "export")); - var asset = JsonNode.Parse(File.ReadAllText(selection))![aggregate ? "aggregates" : "assets"]![0]!; + var tools = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("fixture-host", "fixture-arch"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".data"), + false + ); + NativeBuildContext context = new NativeBuildContext(producer, "release").WithToolchain(tools); + var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( + "fixture", + m_component, + new NativeComponentBuildOptions(NativeLibraryKind.Static), + [], + ProduceAsync, + Recipe, + static ( + relative, + _ + ) => relative + )]); + NativeBuildProduct? aggregateProduct = aggregate + ? await ProduceAsync(context, new Dictionary(), CancellationToken.None) + : null; + using ProductNativeBuildResult products = aggregateProduct is not null + ? new ProductNativeBuildResult( + [aggregateProduct], + new NativeBindingGenerationResult(new Dictionary(), []), + Path.Combine(aggregateProduct.directory, "Outputs"), + Recipe(context) + ) + : await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); + string selection = await NativeDependencyManifest.ExportAsync( + context, + plan, + products, + Path.Combine(producer, "artifacts", "export") + ); + JsonNode asset = JsonNode.Parse(File.ReadAllText(selection))![aggregate ? "aggregates" : "assets"]![0]!; string downloads = Path.Combine(consumer, "artifacts", "fixture-target", "native"); Directory.CreateDirectory(downloads); - File.Copy(Path.Combine(producer, "artifacts", "export", asset["asset"]!.GetValue()), Path.Combine(downloads, asset["sha256"]!.GetValue() + ".zip")); + File.Copy( + Path.Combine(producer, "artifacts", "export", asset["asset"]!.GetValue()), + Path.Combine(downloads, asset["sha256"]!.GetValue() + ".zip") + ); string consumerSelection = Path.Combine(consumer, "artifacts", "selection.json"); File.Copy(selection, consumerSelection); return (consumer, consumerSelection, plan); } - private NativeBuildRecipe Recipe(NativeBuildContext context) => new(m_component, "fixture", "fixture-target", [NativeBuildInput.FromPath(context.engineRoot, Path.Combine(context.engineRoot, "component", "Source"))], ["fixture"]); - private Task Produce( + private NativeBuildRecipe Recipe(NativeBuildContext context) + => new( + m_component, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(context.engineRoot, Path.Combine(context.engineRoot, "component", "Source"))], + ["fixture"] + ); + + private Task ProduceAsync( NativeBuildContext context, IReadOnlyDictionary dependencies, - CancellationToken cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context), ( - _, - output, - token - ) => - { - m_productions++; - return File.WriteAllTextAsync(Path.Combine(output, "output.data"), "payload", token); - }, cancellation, describeOutputs: static ( - _, - output - ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)]); - private static Task Git( + CancellationToken cancellationToken + ) => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), + ( + _, + output, + token + ) => + { + m_productions++; + return File.WriteAllTextAsync(Path.Combine(output, "output.data"), "payload", token); + }, + describeOutputs: static ( + _, + output + ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)], + cancellationToken: cancellationToken + ); + + private static Task GitAsync( string root, params string[] arguments ) => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); - public void Dispose() - { - if (!Directory.Exists(m_root)) - return; - foreach (string file in Directory.EnumerateFiles(m_root, "*", SearchOption.AllDirectories)) - File.SetAttributes(file, FileAttributes.Normal); - Directory.Delete(m_root, recursive: true); - } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs index 9bb5bcdbf..5fb1581b2 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using Inno.Native.LibraryLoading; using Xunit; +using Inno.Native.LibraryLoading; namespace Inno.Build.Toolchains.Tests; @@ -10,7 +10,10 @@ public sealed class NativeDeploymentIndexTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDeploymentIndex", Guid.NewGuid().ToString("N")); - public NativeDeploymentIndexTests() => Directory.CreateDirectory(m_root); + public NativeDeploymentIndexTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void UnknownSystemAndSuffixResolveThroughExplicitMappings() @@ -24,7 +27,7 @@ public void UnknownSystemAndSuffixResolveThroughExplicitMappings() libraries.Clear(); files.Clear(); NativeDeploymentIndex decoded = NativeDeploymentIndex.Decode(source.Encode()); - Assert.Equal("new-system-custom-abi", decoded.targetId); + Assert.Equal("new-system-custom-abi", decoded.targetID); Assert.Equal(OperatingSystem.IsWindows() ? @"\\?\" + payload : payload, decoded.ResolveLibrary(m_root, "renderer")); Assert.Equal(payload, decoded.ResolveFile(m_root, "compiler")); Assert.Throws(() => decoded.ResolveLibrary(m_root, "not-registered")); @@ -38,15 +41,19 @@ public void UnknownSystemAndSuffixResolveThroughExplicitMappings() [InlineData("C:/outside.bin")] [InlineData("part\\wrong.bin")] public void InvalidDeploymentPathsFailBeforeResolution(string path) - => Assert.Throws(() => new NativeDeploymentIndex("fixture", - new Dictionary { ["library"] = path }, new Dictionary())); + => Assert.Throws(() => new NativeDeploymentIndex( + "fixture", + new Dictionary { ["library"] = path }, + new Dictionary() + )); [Fact] public void MissingAndUnknownIndexFieldsAreRejected() { Assert.Throws(() => NativeDeploymentIndex.Decode("{}"u8)); Assert.Throws(() => NativeDeploymentIndex.Decode( - "{\"targetId\":\"fixture\",\"libraries\":{},\"files\":{},\"oldLayout\":true}"u8)); + "{\"targetId\":\"fixture\",\"libraries\":{},\"files\":{},\"oldLayout\":true}"u8 + )); } public void Dispose() => Directory.Delete(m_root, recursive: true); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs index dfd646acd..981334962 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs @@ -4,9 +4,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -23,14 +23,16 @@ public NativeInputBatchTests() Directory.CreateDirectory(m_source); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); for (int index = 0; index < 64; index++) + { File.WriteAllText(Path.Combine(m_source, index.ToString("D2") + ".h"), new string((char)('A' + index % 26), 16 * 1024)); + } } [Fact] public void AliasesShareReadsWhileFreshPhasesObserveAllBytes() { var context = new NativeBuildContext(m_root, "debug"); - NativeBuildInput[] inputs = [new("first", m_source), new("second", m_source)]; + NativeBuildInput[] inputs = [new NativeBuildInput("first", m_source), new NativeBuildInput("second", m_source)]; string initial = NativeBuildFingerprint.Create(context, ["fixture"], inputs); Assert.Equal(initial, NativeBuildFingerprint.Create(["fixture"], inputs.Reverse())); NativeBuildPhaseStatistics first = Assert.Single(context.statistics.phases); @@ -55,9 +57,11 @@ public void AliasesShareReadsWhileFreshPhasesObserveAllBytes() public async Task FailedBatchDrainsReadersAndDoesNotFreezePartialContent() { var context = new NativeBuildContext(m_root, "debug"); - NativeBuildInput[] inputs = [new("source", m_source)]; + NativeBuildInput[] inputs = [new NativeBuildInput("source", m_source)]; using (var locked = new FileStream(Path.Combine(m_source, "63.h"), FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { await Assert.ThrowsAnyAsync(() => Task.Run(() => NativeBuildFingerprint.Create(context, [], inputs))); + } foreach (string path in Directory.EnumerateFiles(m_source)) { using var exclusive = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None); @@ -70,7 +74,7 @@ public async Task FailedBatchDrainsReadersAndDoesNotFreezePartialContent() public void CancellationAfterInventoryCannotReturnSuccessfulPartialSnapshot() { var context = new NativeBuildContext(m_root, "debug"); - NativeBuildInput[] inputs = [new("source", m_source)]; + NativeBuildInput[] inputs = [new NativeBuildInput("source", m_source)]; using var cancellation = new CancellationTokenSource(); Assert.ThrowsAny(() => NativeBuildFingerprint.Create(context, [], CancelAfterInventory(), cancellation.Token)); @@ -91,7 +95,9 @@ IEnumerable CancelAfterInventory() public void Dispose() { if (!Path.GetFullPath(m_root).StartsWith(m_parent + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { throw new InvalidOperationException("The native input fixture escaped its owner."); + } Directory.Delete(m_root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs index 53491054c..8dae4fc07 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs @@ -19,18 +19,25 @@ public sealed class NativeProductExecutorTests : IDisposable public async Task NewTargetAndBackendUseTheSameExecutorAndStaticLinkageCanUseAStandaloneProducer() { NativeBuildContext context = Context(); - var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep("probe", m_owner, - new(NativeLibraryKind.Static), [], Produce, Recipe, static ( + var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep( + "probe", + m_owner, + new NativeComponentBuildOptions(NativeLibraryKind.Static), + [], + ProduceAsync, + Recipe, + static ( relative, target - ) => relative)]); + ) => relative + )]); var executor = new SelectedExecutor(); var contribution = new NativeProductContribution(plan, executor); using (ProductNativeBuildResult first = await contribution.BuildAsync(context, CancellationToken.None)) { NativeArtifact artifact = Assert.Single(Assert.Single(first).artifacts); Assert.Equal(NativeArtifactRole.StaticArchive, artifact.role); - Assert.Equal("probe-target", first[0].targetId); + Assert.Equal("probe-target", first[0].targetID); Assert.Equal("probe-output.data", Path.GetFileName(artifact.file)); } using ProductNativeBuildResult hot = await contribution.BuildAsync(Context(), CancellationToken.None); @@ -43,14 +50,28 @@ public async Task UnsupportedLinkageIsRejectedBeforeBindingOrStaging() { NativeBuildContext context = Context(); string sdk = ToolchainEnvironment.ResolveExecutable("dotnet"); - var selection = new NativeToolchainSelection("probe-target", new BuildHostDescriptor("ProbeHost", "processor"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], - new NativeLinkPlan(staticLibraryExtension: ".archive"), false); - var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep("probe", m_owner, - new(NativeLibraryKind.Shared), [], Produce, Recipe, static ( + var selection = new NativeToolchainSelection( + "probe-target", + new BuildHostDescriptor("ProbeHost", "processor"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".archive"), + false + ); + var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep( + "probe", + m_owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], + ProduceAsync, + Recipe, + static ( relative, target - ) => relative)]); + ) => relative + )]); await Assert.ThrowsAsync(() => new ComponentNativeProductExecutor() .BuildAsync(context.WithToolchain(selection), plan, CancellationToken.None)); Assert.Equal(0, m_productions); @@ -62,7 +83,9 @@ public async Task UnsupportedLinkageIsRejectedBeforeBindingOrStaging() public async Task IncompleteRoleInventoryIsRejectedBeforePublication() { NativeBuildContext context = Context(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, Recipe(context), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), static ( operation, output, @@ -71,14 +94,19 @@ await Assert.ThrowsAsync(() => NativeArtifactPublisher.Pub describeOutputs: static ( operation, output - ) => [])); - Assert.Empty(Directory.GetFiles(Path.Combine(m_root, "artifacts", "native"), "generation-manifest.json", SearchOption.AllDirectories)); + ) => [] + )); + Assert.Empty( + Directory.GetFiles(Path.Combine(m_root, "artifacts", "native"), "generation-manifest.json", SearchOption.AllDirectories) + ); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private NativeBuildContext Context() @@ -88,34 +116,53 @@ private NativeBuildContext Context() File.WriteAllText(Path.Combine(m_root, "component", "Native.csproj"), ""); File.WriteAllText(Path.Combine(m_root, "component", "Toolchain.csproj"), ""); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("probe-target", new BuildHostDescriptor("ProbeHost", "processor"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], new NativeLinkPlan(".shared", staticLibraryExtension: ".data"), false); + var tools = new NativeToolchainSelection( + "probe-target", + new BuildHostDescriptor("ProbeHost", "processor"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".shared", staticLibraryExtension: ".data"), + false + ); return new NativeBuildContext(m_root, "release").WithToolchain(tools); } - private NativeBuildRecipe Recipe(NativeBuildContext context) => new(m_owner, "probe", "probe-target", - [NativeBuildInput.FromPath(m_root, Path.Combine(m_root, "component", "Native.csproj"))], ["probe-recipe"]); + private NativeBuildRecipe Recipe(NativeBuildContext context) + => new( + m_owner, + "probe", + "probe-target", + [NativeBuildInput.FromPath(m_root, Path.Combine(m_root, "component", "Native.csproj"))], + ["probe-recipe"] + ); - private Task Produce( + private Task ProduceAsync( NativeBuildContext context, IReadOnlyDictionary dependencies, - CancellationToken cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context), ( - operation, - output, - token - ) => { - m_productions++; - return File.WriteAllTextAsync(Path.Combine(output, "probe-output.data"), "archive", token); - }, cancellation, describeOutputs: static ( - operation, - output - ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)]); + CancellationToken cancellationToken + ) => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), + ( + operation, + output, + token + ) => + { + m_productions++; + return File.WriteAllTextAsync(Path.Combine(output, "probe-output.data"), "archive", token); + }, + describeOutputs: static ( + operation, + output + ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)], + cancellationToken: cancellationToken + ); private sealed class SelectedExecutor : INativeProductExecutor { - internal int executions { get; private set; } - public Task BuildAsync( NativeBuildContext context, ProductNativeBuildPlan plan, @@ -124,5 +171,7 @@ CancellationToken cancellationToken executions++; return new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellationToken); } + + internal int executions { get; private set; } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs index dfa0115d6..7d889d52b 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs @@ -5,8 +5,8 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; @@ -22,8 +22,11 @@ public sealed class NativeToolchainPreparationTests private static async Task VerifyInstallationInputsAsync(bool executableAlias) { - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), - "InnoCMakeInputs", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoCMakeInputs", + Guid.NewGuid().ToString("N") + ); string prefix = Path.Combine(root, "prefix"); string installation = Path.Combine(root, "installation"); string physicalBin = Path.Combine(installation, "bin"); @@ -51,18 +54,33 @@ private static async Task VerifyInstallationInputsAsync(bool executableAlias) { string escapedAlias = aliasBin.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = physicalBin.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedAlias}' -Target '{escapedTarget}' | Out-Null"], - root, CancellationToken.None); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedAlias}' -Target '{escapedTarget}' | Out-Null" + ], + root, + CancellationToken.None + ); } else + { Directory.CreateSymbolicLink(aliasBin, physicalBin); + } - NativeToolchainSelection selection = NativeToolchainPreparation.Freeze("fixture-x64", + NativeToolchainSelection selection = NativeToolchainPreparation.Freeze( + "fixture-x64", new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["cmake"] = selected }, - new Dictionary(), [], [], new NativeLinkPlan(staticLibraryExtension: ".a"), false); + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".a"), + false + ); Assert.Contains(modules, selection.inputPaths); Assert.DoesNotContain(Path.GetDirectoryName(unrelated)!, selection.inputPaths); string initial = Capture(); @@ -76,16 +94,24 @@ await ToolchainEnvironment.RunAsync("powershell.exe", File.WriteAllText(executable, "tool-two"); Assert.NotEqual(changedModule, Capture()); - string Capture() => NativeBuildFingerprint.Create(new NativeBuildContext(root, "release"), - selection.declarations, selection.inputPaths.Select(path => NativeBuildInput.FromPath(root, path)), - CancellationToken.None); + string Capture() + => NativeBuildFingerprint.Create( + new NativeBuildContext(root, "release"), + selection.declarations, + selection.inputPaths.Select(path => NativeBuildInput.FromPath(root, path)), + CancellationToken.None + ); } finally { if (executableAlias && File.Exists(selected)) + { File.Delete(selected); + } else if (!executableAlias && Directory.Exists(aliasBin)) + { Directory.Delete(aliasBin, recursive: false); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs index daf25b0c4..78cccf965 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -23,12 +23,30 @@ public async Task DifferentDirectoryAliasesKeepLogicalMappingsButShareOnePhysica Directory.CreateDirectory(physical); File.WriteAllText(Path.Combine(physical, "input.h"), "bytes"); if (OperatingSystem.IsWindows()) - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + physical + "' | Out-Null"], root, CancellationToken.None); + { + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + physical + "' | Out-Null" + ], + root, + CancellationToken.None + ); + } else + { Directory.CreateSymbolicLink(alias, physical); + } var context = new NativeBuildContext(root, "release"); - _ = NativeBuildFingerprint.Create(context, [], [new NativeBuildInput("physical", physical), new NativeBuildInput("alias", alias)], CancellationToken.None); + _ = NativeBuildFingerprint.Create( + context, + [], + [new NativeBuildInput("physical", physical), new NativeBuildInput("alias", alias)], + CancellationToken.None + ); Assert.Equal(1, context.statistics.hashedFiles); Assert.Equal(5, context.statistics.hashedBytes); Assert.True(context.statistics.phases.Single().reusedReads > 0); @@ -36,10 +54,13 @@ await ToolchainEnvironment.RunAsync("powershell.exe", finally { if (Directory.Exists(alias)) + { Directory.Delete(alias, recursive: false); + } Directory.Delete(root, recursive: true); } } + [Fact] public void FreshPhasesDetectSameLengthSameTimestampChangesAndReuseSharedReads() { @@ -51,17 +72,17 @@ public void FreshPhasesDetectSameLengthSameTimestampChangesAndReuseSharedReads() string file = Path.Combine(root, "input.txt"); File.WriteAllText(file, "first"); var context = new NativeBuildContext(root, "release"); - var inputs = new[] { new NativeBuildInput("first-owner", file), new NativeBuildInput("second-owner", file) }; + NativeBuildInput[] inputs = [new NativeBuildInput("first-owner", file), new NativeBuildInput("second-owner", file)]; string initial = NativeBuildFingerprint.Create(context, ["recipe"], inputs, CancellationToken.None); Assert.Equal(1, context.statistics.hashedFiles); DateTime timestamp = File.GetLastWriteTimeUtc(file); File.WriteAllText(file, "other"); File.SetLastWriteTimeUtc(file, timestamp); - var verification = context.BeginInputVerification("after-lock"); + NativeBuildContext verification = context.BeginInputVerification("after-lock"); string verified = NativeBuildFingerprint.Create(verification, ["recipe"], inputs, CancellationToken.None); Assert.NotEqual(initial, verified); Assert.Equal(verified, NativeBuildFingerprint.Create(verification, ["recipe"], inputs, CancellationToken.None)); - var phase = context.statistics.phases.Single(phase => phase.phase == "after-lock"); + NativeBuildPhaseStatistics phase = context.statistics.phases.Single(phase => phase.phase == "after-lock"); Assert.Equal(1, phase.files); Assert.Equal(5, phase.bytes); Assert.Equal(3, phase.reusedReads); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs index fdcf92da7..8c2a5c951 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -13,7 +14,6 @@ namespace Inno.Build.Toolchains.Tests; public sealed class NativeWorkspaceReuseTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoWorkspaceTests", Guid.NewGuid().ToString("N")); private readonly string m_bindingRoot = Path.Combine(Path.GetTempPath(), "InnoWorkspaceBindings", Guid.NewGuid().ToString("N")); private readonly NativeComponentDescriptor m_owner = new("fixture", "native/fixture.csproj", "build/fixture.csproj"); @@ -33,10 +33,10 @@ public async Task SourceChangesReuseTheWorkspaceButPublishDistinctImmutableProdu await File.WriteAllTextAsync(source, "first"); string? workspace = null; int compilations = 0; - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { string current = scoped.GetNativeBuildRoot(m_owner); string physical = new DirectoryInfo(current).LinkTarget ?? current; @@ -48,16 +48,34 @@ CancellationToken cancellation workspace = physical; File.WriteAllText(Path.Combine(current, "retained.object"), "compiler intermediate"); Interlocked.Increment(ref compilations); - return File.WriteAllTextAsync(Path.Combine(output, "result.native"), File.ReadAllText(source), cancellation); + return File.WriteAllTextAsync(Path.Combine(output, "result.native"), File.ReadAllText(source), cancellationToken); } - NativeBuildRecipe Recipe() => new(m_owner, "fixture", "fixture-x64", - [new NativeBuildInput("input.cpp", source)], ["shared", "compiler-flag"]); - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), Recipe(), Produce); + NativeBuildRecipe Recipe() + => new( + m_owner, + "fixture", + "fixture-x64", + [new NativeBuildInput("input.cpp", source)], + ["shared", "compiler-flag"] + ); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync( + new NativeBuildContext(m_root, "release"), + Recipe(), + ProduceAsync + ); DateTime timestamp = File.GetLastWriteTimeUtc(source); await File.WriteAllTextAsync(source, "other"); File.SetLastWriteTimeUtc(source, timestamp); - using NativeBuildProduct changed = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), Recipe(), Produce); - using NativeBuildProduct hit = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), Recipe(), Produce); + using NativeBuildProduct changed = await NativeArtifactPublisher.PublishAsync( + new NativeBuildContext(m_root, "release"), + Recipe(), + ProduceAsync + ); + using NativeBuildProduct hit = await NativeArtifactPublisher.PublishAsync( + new NativeBuildContext(m_root, "release"), + Recipe(), + ProduceAsync + ); Assert.NotEqual(first.fingerprint, changed.fingerprint); Assert.Equal(changed.fingerprint, hit.fingerprint); Assert.Equal(2, compilations); @@ -73,22 +91,29 @@ public async Task IncompatibleCompilerDeclarationsUseSeparateWorkspaces() await File.WriteAllTextAsync(source, "source"); string? first = null; int calls = 0; - Task Produce( + Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { string current = scoped.GetNativeBuildRoot(m_owner); if (calls++ == 0) + { first = current; + } else + { Assert.NotEqual(first, current); - return File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellation); + } + return File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellationToken); } foreach (string argument in new[] { "-O0", "-O2" }) { - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), - new(m_owner, "fixture", "fixture-x64", [new NativeBuildInput("input.cpp", source)], [argument]), Produce); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + new NativeBuildContext(m_root, "release"), + new NativeBuildRecipe(m_owner, "fixture", "fixture-x64", [new NativeBuildInput("input.cpp", source)], [argument]), + ProduceAsync + ); } Assert.Equal(2, calls); } @@ -102,14 +127,25 @@ public async Task BindingGenerationChangesReuseTheWorkspaceAndCopiedInputLocatio bool aggregate, bool externalBindings ) { - var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + var owner = new NativeComponentDescriptor( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); string? workspace = null; string? copiedBridge = null; string? previousProduct = null; - var tools = new NativeToolchainSelection("fixture-x64", new BuildHostDescriptor("Fixture", "x64"), + var tools = new NativeToolchainSelection( + "fixture-x64", + new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["fixture"] = ToolchainEnvironment.ResolveExecutable("dotnet") }, - new Dictionary(), [], [], new NativeLinkPlan(".native"), false); + new Dictionary(), + [], + [], + new NativeLinkPlan(".native"), + false + ); foreach (string generation in new[] { new string('a', 64), new string('b', 64) }) { string artifact = Path.Combine(externalBindings ? m_bindingRoot : m_root, "native", "obj", "fixture-x64", generation); @@ -120,11 +156,23 @@ bool externalBindings string header = Path.Combine(bridge, "fixture.h"); File.WriteAllText(header, generation); File.WriteAllText(managed, generation); - File.WriteAllText(Path.Combine(bridge, "compilation.json"), System.Text.Json.JsonSerializer.Serialize(new NativeBindingCompilation - { - roots = [new("generated", "", true, true)], files = [], includeDirectories = [], defines = [], compilerDefines = [], - cxxStandard = 0, cStandard = 0, requiredExports = [], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] - })); + File.WriteAllText( + Path.Combine(bridge, "compilation.json"), + JsonSerializer.Serialize(new NativeBindingCompilation + { + roots = [new NativeBindingSourceRoot("generated", string.Empty, true, true)], + files = [], + includeDirectories = [], + defines = [], + compilerDefines = [], + cxxStandard = 0, + cStandard = 0, + requiredExports = [], + staticExportSymbols = [], + staticExportAbi = string.Empty, + staticExportNames = [] + }) + ); var descriptor = new NativeBindingGenerationDescriptor { fingerprint = generation, @@ -135,18 +183,29 @@ bool externalBindings artifactOwnerDirectory = externalBindings ? m_bindingRoot : m_root }; using var bindings = new NativeBindingGenerationResult( - new Dictionary { [owner.nativeProject] = descriptor }, []); + new Dictionary { [owner.nativeProject] = descriptor }, + [] + ); NativeBuildContext context = new NativeBuildContext(m_root, "release").WithToolchain(tools).WithBindings(bindings); - var recipe = new NativeBuildRecipe(owner, "fixture", "fixture-x64", + var recipe = new NativeBuildRecipe( + owner, + "fixture", + "fixture-x64", [NativeBuildInput.FromPath(m_root, bridge), NativeBuildInput.FromPath(m_root, managed)], - [(aggregate ? owner.nativeProject + "=" : "bindings=") + generation, - (aggregate ? "componentArgument=" : string.Empty) + "-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge]); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + [ + (aggregate ? owner.nativeProject + "=" : "bindings=") + generation, + (aggregate ? "componentArgument=" : string.Empty) + "-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge + ] + ); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, cancellation - ) => { + ) => + { string current = scoped.GetNativeBuildRoot(owner); string physical = new DirectoryInfo(current).LinkTarget ?? current; NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync(scoped, owner, cancellation); @@ -159,12 +218,17 @@ bool externalBindings workspace = physical; copiedBridge = input; Assert.Equal(generation, File.ReadAllText(input)); - Assert.Equal("-DINNO_FIXTURE_BRIDGE_ROOT=" + Path.GetDirectoryName(input), - sources.ResolveDefinition("-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge)); + Assert.Equal( + "-DINNO_FIXTURE_BRIDGE_ROOT=" + Path.GetDirectoryName(input), + sources.ResolveDefinition("-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge) + ); await File.WriteAllTextAsync(Path.Combine(output, "result.native"), generation, cancellation); - }); + } + ); if (previousProduct is not null) + { Assert.NotEqual(previousProduct, product.fingerprint); + } previousProduct = product.fingerprint; } } @@ -172,9 +236,12 @@ bool externalBindings public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } if (Directory.Exists(m_bindingRoot)) + { Directory.Delete(m_bindingRoot, recursive: true); + } } - } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs index aa3bbdcf1..03e1fa54f 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; @@ -29,7 +29,9 @@ public async Task MalformedSubprocessClaimsPreventRetirement(string malformed) finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -56,7 +58,9 @@ public async Task RegistrationAndRetirementCoordinateThroughTheSamePersistentLea finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -79,9 +83,12 @@ public async Task ProcessParticipantsReuseOnlyTheSameActiveDeclaredOperation() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } + [Fact] public void ProcessIdentityIncludesItsStartTimeAndInvalidIdentityIsConservative() { @@ -115,7 +122,9 @@ public async Task WorkingClaimPrecedesPayloadAndNeverAdoptsUnrecordedDirectories finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -131,9 +140,15 @@ public async Task WorkspacePreferenceDoesNotPermanentlyPinAnIdleWorkspace() File.WriteAllText(Path.Combine(workspace, "payload"), "owned"); var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ReusableWorkspace); using (await publisher.AcquireUseAsync()) + { publisher.Record(workspace, workspace + ".lock", [], "preferred", "fixture"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(root, [publisher.Describe("workspace")], - new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(10)), retireAll: true); + } + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + root, + [publisher.Describe("workspace")], + new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(10)), + retireAll: true + ); Assert.Single(plan.candidates); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Single(result.retired); @@ -142,7 +157,9 @@ public async Task WorkspacePreferenceDoesNotPermanentlyPinAnIdleWorkspace() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -167,7 +184,9 @@ public async Task WorkingRegistrationRefusesToAdoptUnknownExistingPayload() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs index a6587a8d1..1f2e676b9 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs @@ -42,9 +42,18 @@ public async Task CompleteHitUsesOneFreshUnionAndDoesNotInvokeProducers() public async Task DamagedMemberFallsBackWithoutReturningPartialProducts() { ProductNativeBuildPlan plan = Plan(); - using (ProductNativeBuildResult initial = await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None)) + using (ProductNativeBuildResult initial = await new ComponentNativeProductExecutor().BuildAsync( + Context(), + plan, + CancellationToken.None + )) { File.WriteAllText(initial[1].files[0], "damaged"); - using ProductNativeBuildResult repaired = await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None); + } + using ProductNativeBuildResult repaired = await new ComponentNativeProductExecutor().BuildAsync( + Context(), + plan, + CancellationToken.None + ); Assert.Equal(3, m_builds); Assert.All(repaired, static product => Assert.Equal("complete", File.ReadAllText(product.files[0]))); } @@ -55,39 +64,67 @@ public async Task ConcurrentHotRequestsShareReadOwnershipWithoutWorkspaceDeadloc ProductNativeBuildPlan plan = Plan(); using (await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None)) { } using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - ProductNativeBuildResult[] results = await Task.WhenAll(new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token), new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token)); + ProductNativeBuildResult[] results = await Task.WhenAll( + new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token), + new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token) + ); foreach (ProductNativeBuildResult result in results) + { result.Dispose(); + } Assert.Equal(2, m_builds); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } - private NativeBuildContext Context() => new NativeBuildContext(m_root, "release").WithToolchain(new("fixture-x64", - new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["compiler"] = Environment.ProcessPath! }, - new Dictionary(), [], [], new NativeLinkPlan(".dll"), false)); + private NativeBuildContext Context() + => new NativeBuildContext(m_root, "release").WithToolchain( + new NativeToolchainSelection( + "fixture-x64", + new BuildHostDescriptor("Fixture", "x64"), + new Dictionary { ["compiler"] = Environment.ProcessPath! }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ) + ); - private ProductNativeBuildPlan Plan() => new("fixture", new[] { "first", "second" }.Select(id => new ProductNativeBuildStep( - id, m_owner, new(NativeLibraryKind.Shared), [], - ( - context, - dependencies, - cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context, id), async ( - @scoped, - output, - token - ) => { - Interlocked.Increment(ref m_builds); - await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", token); - }, cancellation), context => Recipe(context, id), static ( - relative, - target - ) => relative)).ToArray()); + private ProductNativeBuildPlan Plan() + => new( + "fixture", + new[] { "first", "second" }.Select(id => new ProductNativeBuildStep( + id, + m_owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared), + [], + ( + context, + dependencies, + cancellation + ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context, id), async ( + @scoped, + output, + token + ) => + { + Interlocked.Increment(ref m_builds); + await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", token); + }, cancellationToken: cancellation), + context => Recipe(context, id), + static ( + relative, + target + ) => relative + )).ToArray() + ); private NativeBuildRecipe Recipe( NativeBuildContext context, diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs index 5349315bd..ea7496933 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs @@ -4,15 +4,20 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; public sealed class ProductNativePreparationTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoPreparedNative", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_owner = new("fixture", "component/Fixture.csproj", "component/Fixture.csproj"); private int m_productions; @@ -32,10 +37,16 @@ public async Task EqualRequestsAcquireIndependentReadersWithoutProducingAgain() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = Assert.IsType(ProductNativePreparation.Capture(producer, plan, built, identity)); NativeBuildContext consumer = Context(); - using ProductNativeBuildResult reading = Assert.IsType(await ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity)); + using ProductNativeBuildResult reading = Assert.IsType( + await ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity) + ); NativeBuildPhaseStatistics phase = Assert.Single(consumer.statistics.phases); Assert.Equal("prepared-consumer", phase.phase); Assert.Equal(2, phase.files); @@ -45,8 +56,11 @@ public async Task EqualRequestsAcquireIndependentReadersWithoutProducingAgain() Assert.Equal("result", File.ReadAllText(reading[0].files.Single())); Assert.Equal(1, m_productions); using var cancellation = new CancellationTokenSource(); - Task waiting = BuildArtifactWriteLease.AcquireAsync(reading[0].directory, - Path.Combine(m_root, "artifacts", "native"), cancellation.Token).AsTask(); + Task waiting = BuildArtifactWriteLease.AcquireAsync( + reading[0].directory, + Path.Combine(m_root, "artifacts", "native"), + cancellation.Token + ).AsTask(); Assert.False(waiting.IsCompleted); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => waiting); @@ -70,10 +84,17 @@ public async Task FrozenIdentityChangesWithEveryDeclaredInput(string changed) File.SetLastWriteTimeUtc(path, timestamp); } else if (changed == "membership") + { File.WriteAllText(Path.Combine(m_root, "Source", "added.h"), "new"); + } else if (changed == "sdk") + { File.WriteAllText(Path.Combine(m_root, "sdk-tool"), "tool-b"); - NativeBuildContext after = Context(changed == "configuration" ? "release" : "debug", changed == "target" ? "other-target" : "fixture-target"); + } + NativeBuildContext after = Context( + changed == "configuration" ? "release" : "debug", + changed == "target" ? "other-target" : "fixture-target" + ); Assert.NotEqual(original, await ProductNativePreparation.FreezeAsync(after, Plan())); } @@ -90,7 +111,11 @@ public async Task ConsumerRejectsChangedInputsWithoutASeparatePreliminaryFreeze( NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; built.Dispose(); if (changed is "source" or "sdk") @@ -101,10 +126,16 @@ public async Task ConsumerRejectsChangedInputsWithoutASeparatePreliminaryFreeze( File.SetLastWriteTimeUtc(path, timestamp); } else if (changed == "membership") + { File.WriteAllText(Path.Combine(m_root, "Source", "added.h"), "new"); - NativeBuildContext consumer = Context(changed == "configuration" ? "release" : "debug", changed == "target" ? "other-target" : "fixture-target"); - ProductNativeBuildPlan current = changed == "product" ? new("different-product", plan.steps) - : changed == "recipe" ? Plan(NativeLibraryKind.Static) : plan; + } + NativeBuildContext consumer = Context( + changed == "configuration" ? "release" : "debug", + changed == "target" ? "other-target" : "fixture-target" + ); + ProductNativeBuildPlan current = changed == "product" + ? new ProductNativeBuildPlan("different-product", plan.steps) + : changed == "recipe" ? Plan(NativeLibraryKind.Static) : plan; Assert.Null(await ProductNativePreparation.TryAcquireAsync(consumer, current, rows, identity)); Assert.Equal(1, m_productions); } @@ -115,18 +146,33 @@ public async Task CancellationWhileWaitingReleasesPartialConsumerProtection() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string directory = built[0].directory; built.Dispose(); - using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync(directory, Path.Combine(m_root, "artifacts", "native")); + using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.Combine(m_root, "artifacts", "native") + ); using var cancellation = new CancellationTokenSource(); - Task pending = ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token); + Task pending = ProductNativePreparation.TryAcquireAsync( + Context(), + plan, + rows, + identity, + cancellation.Token + ); Assert.False(pending.IsCompleted); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => pending); writer.Dispose(); - using ProductNativeBuildResult reading = Assert.IsType(await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity)); + using ProductNativeBuildResult reading = Assert.IsType( + await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity) + ); Assert.Equal("result", File.ReadAllText(reading[0].files.Single())); } @@ -136,13 +182,20 @@ public async Task SourceChangesWhileWaitingForProtectionRejectReuse() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string directory = built[0].directory; built.Dispose(); NativeBuildContext consumer = Context(); Assert.Equal(identity, await ProductNativePreparation.FreezeAsync(consumer, plan)); - using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync(directory, Path.Combine(m_root, "artifacts", "native")); + using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.Combine(m_root, "artifacts", "native") + ); Task pending = ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity); Assert.False(pending.IsCompleted); File.WriteAllText(Path.Combine(m_root, "Source", "source.h"), "other"); @@ -156,7 +209,11 @@ public async Task CorruptedPublicationAndPreCancellationCannotReturnSuccessfulRe NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string output = built[0].files.Single(); built.Dispose(); @@ -164,26 +221,47 @@ public async Task CorruptedPublicationAndPreCancellationCannotReturnSuccessfulRe Assert.Null(await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity)); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token) + ); } public void Dispose() { - string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative") + Path.DirectorySeparatorChar; + string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative") + + Path.DirectorySeparatorChar; if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The native fixture escaped its temporary owner."); + } Directory.Delete(m_root, recursive: true); } private NativeBuildContext Context( string configuration = "debug", string target = "fixture-target" - ) => new NativeBuildContext(m_root, configuration).WithToolchain(new NativeToolchainSelection(target, - new BuildHostDescriptor("Fixture", "fixture-cpu"), new Dictionary { ["compiler"] = Path.Combine(m_root, "sdk-tool") }, - new Dictionary(), [], [], new NativeLinkPlan(".fixture", staticLibraryExtension: ".fixture-static"), false)); + ) => new NativeBuildContext(m_root, configuration).WithToolchain( + new NativeToolchainSelection( + target, + new BuildHostDescriptor("Fixture", "fixture-cpu"), + new Dictionary + { + ["compiler"] = Path.Combine(m_root, "sdk-tool") + }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".fixture", staticLibraryExtension: ".fixture-static"), + false + ) + ); private ProductNativeBuildPlan Plan(NativeLibraryKind kind = NativeLibraryKind.Shared) - => new("fixture-product", [new ProductNativeBuildStep("fixture", m_owner, new NativeComponentBuildOptions(kind), [], + => new("fixture-product", [new ProductNativeBuildStep( + "fixture", + m_owner, + new NativeComponentBuildOptions(kind), + [], ( context, dependencies, @@ -192,16 +270,26 @@ private ProductNativeBuildPlan Plan(NativeLibraryKind kind = NativeLibraryKind.S owned, output, token - ) => { + ) => + { Interlocked.Increment(ref m_productions); await File.WriteAllTextAsync(Path.Combine(output, "result.fixture"), "result", token); - }, cancellation), Recipe, ( + }, cancellationToken: cancellation), + Recipe, + ( path, target - ) => path)]); + ) => path + )]); private NativeBuildRecipe Recipe(NativeBuildContext context) - => new(m_owner, "fixture", context.toolchain!.targetId, - new[] { Path.Combine(m_root, "Source") }.Concat(context.toolchain.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), - new[] { context.configuration }.Concat(context.toolchain.declarations)); + => new( + m_owner, + "fixture", + context.toolchain!.targetID, + new[] { Path.Combine(m_root, "Source") } + .Concat(context.toolchain.inputPaths) + .Select(path => NativeBuildInput.FromPath(m_root, path)), + new[] { context.configuration }.Concat(context.toolchain.declarations) + ); } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs index b5c48e5ba..5802998b0 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -15,8 +15,11 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoToolDiagnostics")); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("The test requires its selected SDK."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("The test requires its selected SDK."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); Directory.CreateDirectory(root); try { @@ -30,8 +33,13 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() """); InvalidOperationException failure = await Assert.ThrowsAsync(() => - ToolchainEnvironment.CaptureOutputAsync(host, ["msbuild", project, "-t:Diagnose", "-nologo", "-nr:false"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host))); + ToolchainEnvironment.CaptureOutputAsync( + host, + ["msbuild", project, "-t:Diagnose", "-nologo", "-nr:false"], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + )); Assert.Contains("failed with exit code", failure.Message); Assert.Contains("Original SDK diagnostic before failure.", failure.Message); Assert.Contains("The declared fixture input is unavailable.", failure.Message); @@ -40,7 +48,9 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() finally { if (!Path.GetFullPath(root).StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The diagnostic fixture escaped its owner."); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs index fe4e0e171..68ec9bbcf 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs @@ -5,8 +5,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -21,9 +21,11 @@ public void Dispose() { string root = Path.GetFullPath(m_root); string owner = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoToolchainProcessTests")) - + Path.DirectorySeparatorChar; + + Path.DirectorySeparatorChar; if (!root.StartsWith(owner, StringComparison.Ordinal)) + { throw new InvalidOperationException("The process fixture directory escaped its temporary owner."); + } long started = Stopwatch.GetTimestamp(); while (Directory.Exists(root)) { @@ -32,9 +34,9 @@ public void Dispose() Directory.Delete(root, recursive: true); return; } - catch (IOException exception) when ((exception.HResult is unchecked((int)0x80070020) - or unchecked((int)0x80070021)) - && Stopwatch.GetElapsedTime(started).TotalMilliseconds < C_RETIREMENT_WINDOW_MILLISECONDS) + catch (IOException exception) when ((exception.HResult is unchecked((int)0x8007_0020) + or unchecked((int)0x8007_0021)) + && Stopwatch.GetElapsedTime(started).TotalMilliseconds < C_RETIREMENT_WINDOW_MILLISECONDS) { // Process termination does not promise that filesystem observers have released the directory. // Retry only sharing/lock violations; persistent failures and all other errors remain visible. @@ -79,32 +81,36 @@ sleep 120 & using var cancellation = new CancellationTokenSource(); Task running = rawArguments - ? ToolchainEnvironment.RunAsync(executable, string.Join(' ', arguments.Select(Quote)), m_root, cancellation.Token) - : ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); + ? ToolchainEnvironment.RunAsync(executable, string.Join(' ', arguments.Select(Quote)), m_root, cancellation.Token) + : ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); int[] processes = []; try { DateTime deadline = DateTime.UtcNow.AddSeconds(15); while (!File.Exists(marker) && !running.IsCompleted && DateTime.UtcNow < deadline) + { await Task.Delay(25); + } Assert.True(File.Exists(marker), "The process tree did not reach its waiting stage."); processes = File.ReadAllText(marker).Trim().Split(',').Select(int.Parse).ToArray(); Assert.Equal(2, processes.Length); - Assert.All(processes, processId => Assert.True(IsRunning(processId))); + Assert.All(processes, processID => Assert.True(IsRunning(processID))); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => running.WaitAsync(TimeSpan.FromSeconds(10))); - Assert.All(processes, processId => Assert.False(IsRunning(processId))); + Assert.All(processes, processID => Assert.False(IsRunning(processID))); } finally { cancellation.Cancel(); - foreach (int processId in processes) + foreach (int processID in processes) { - if (!IsRunning(processId)) + if (!IsRunning(processID)) + { continue; - using Process process = Process.GetProcessById(processId); + } + using Process process = Process.GetProcessById(processID); process.Kill(entireProcessTree: true); } } @@ -115,11 +121,19 @@ public async Task RawRunnerRejectsFailedAndAlreadyCanceledTools() { Directory.CreateDirectory(m_root); await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync( - "dotnet", "--inno-invalid-option", m_root, CancellationToken.None)); + "dotnet", + "--inno-invalid-option", + m_root, + CancellationToken.None + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => ToolchainEnvironment.RunAsync( - "inno-missing-tool", string.Empty, m_root, cancellation.Token)); + "inno-missing-tool", + string.Empty, + m_root, + cancellation.Token + )); } [Theory] @@ -167,9 +181,13 @@ sleep 120 & try { if (standardError) + { Console.SetError(failing); + } else + { Console.SetOut(failing); + } running = ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); IOException failure = await Assert.ThrowsAsync(() => running.WaitAsync(TimeSpan.FromSeconds(10))); @@ -178,14 +196,18 @@ sleep 120 & Assert.True(File.Exists(marker), "The process tree did not reach its output stage."); int[] processes = File.ReadAllText(marker).Trim().Split(',').Select(int.Parse).ToArray(); Assert.Equal(2, processes.Length); - Assert.All(processes, processId => Assert.False(IsRunning(processId))); + Assert.All(processes, processID => Assert.False(IsRunning(processID))); } finally { if (standardError) + { Console.SetError(original); + } else + { Console.SetOut(original); + } cancellation.Cancel(); if (running is not null) { @@ -193,7 +215,7 @@ sleep 120 & { await running.WaitAsync(TimeSpan.FromSeconds(10)); } - catch + catch (Exception) { // Observe the failure after requesting cleanup, including a timed-out assertion. } @@ -203,11 +225,11 @@ sleep 120 & private static string Quote(string argument) => '"' + argument.Replace("\"", "\\\"", StringComparison.Ordinal) + '"'; - private static bool IsRunning(int processId) + private static bool IsRunning(int processID) { try { - using Process process = Process.GetProcessById(processId); + using Process process = Process.GetProcessById(processID); return !process.HasExited; } catch (ArgumentException) diff --git a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs index d24d41d9d..34acf2e3a 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs @@ -8,6 +8,8 @@ public sealed class UnixFileLinksFactAttribute : FactAttribute public UnixFileLinksFactAttribute() { if (OperatingSystem.IsWindows()) - Skip = "Unix compiler file-link semantics require a Unix filesystem; Windows directory-link rejection is tested separately."; + { + this.Skip = "Unix compiler file-link semantics require a Unix filesystem; Windows directory-link rejection is tested separately."; + } } } diff --git a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs index bef2465c6..6d3e72916 100644 --- a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs +++ b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs @@ -1,44 +1,41 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; - - - - +using Inno.Integration.MacOSArm64.Bgfx; +using Inno.Integration.WindowsX64.Bgfx; using Inno.Plugins.Authoring; +using Inno.Rendering; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.SupportPacks; - namespace Inno.Testing.Build; public abstract class BuildPipelineFixture : PlayerSupportPackFixture @@ -54,8 +51,12 @@ public abstract class BuildPipelineFixture : PlayerSupportPackFixture protected readonly SceneWorld m_sceneWorld; protected readonly IDisposable m_sceneWorldScope; - protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly) - .Where(static path => !IsAuthoringAssembly(Path.GetFileName(path))).ToArray()) + protected BuildPipelineFixture() + : base( + Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly) + .Where(static path => !IsAuthoringAssembly(Path.GetFileName(path))) + .ToArray() + ) { m_projectRoot = Path.Combine(m_root, "Project"); string assetRoot = Path.Combine(m_projectRoot, "Assets"); @@ -65,8 +66,11 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base Directory.CreateDirectory(pluginRoot); m_engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildPipelineFixture).Assembly, GetType().Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildPipelineFixture).Assembly, GetType().Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); m_sceneWorld = new SceneWorld(m_identities, m_engine.types); m_sceneWorldScope = m_sceneWorld.EnterScope(); @@ -82,13 +86,15 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base AssetPipelineOptions.Create(assetRoot, libraryRoot) with { enableFileSystemWatcher = false - }); + } + ); m_settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(m_projectRoot, "Settings.Project.inno"))), m_engine.types, m_engine.serialization, - new ProjectId("tests.build"), - AssetSerializationContext.Create(m_assets)); + new ProjectID("tests.build"), + AssetSerializationContext.Create(m_assets) + ); m_plugins = new PluginEnvironment( m_assets, m_settings, @@ -96,15 +102,23 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base pluginRoot, libraryRoot, scan, - m_engine.modules.generations); + m_engine.modules.generations + ); m_compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = m_projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(Path.Combine(Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"), m_projectRoot) + compilationEnvironment = new SdkScriptCompilationEnvironment( + Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ), + m_projectRoot + ) }, m_assets, - m_plugins); + m_plugins + ); m_pipeline = CreatePipeline(); } @@ -119,49 +133,72 @@ public override void Dispose() base.Dispose(); } - protected static BuildProfile CreateProfile( - BuildTargetId target, - string productName = "Test Game" - ) - => new() - { - applicationId = "tests.game", - productName = productName, - startupScene = "Scenes/Startup.iscene", - target = target - }; - protected void SaveStartupScene() { var scene = new GameScene("Startup"); scene.CreateObject("Player"); - Assert.True(m_assets.Save( - AssetPath.Project("Scenes/Startup.iscene"), - SceneAsset.Capture(scene, m_engine.serialization, m_assets))); + Assert.True( + m_assets.Save( + AssetPath.Project("Scenes/Startup.iscene"), + SceneAsset.Capture(scene, m_engine.serialization, m_assets) + ) + ); } protected BuildPipeline CreatePipeline( IPlayerSupportPackProvisioner? provisioner = null, ManagedDeploymentCatalog? managedDeployments = null - ) - => new( - m_assets, - m_plugins, - m_settings, - m_engine.serialization, - m_engine.generations, - m_compiler, - m_supportPackRoot, - [ - new GameBuildTargetBinding(new MacOSArm64GameBuildTarget(new MacOSArm64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler(m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxIntegration.shaderProfile, [Inno.Rendering.GraphicsApi.Metal], new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner())), - new GameBuildTargetBinding(new WindowsX64GameBuildTarget(new WindowsX64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler(m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxIntegration.shaderProfile, [Inno.Rendering.GraphicsApi.Direct3D11, Inno.Rendering.GraphicsApi.Direct3D12, Inno.Rendering.GraphicsApi.Vulkan, Inno.Rendering.GraphicsApi.OpenGL], new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner())) - ], - managedDeployments ?? CreateManagedDeployments(), - provisioner); + ) => new( + m_assets, + m_plugins, + m_settings, + m_engine.serialization, + m_engine.generations, + m_compiler, + m_supportPackRoot, + [ + new GameBuildTargetBinding( + new MacOSArm64GameBuildTarget(new MacOSArm64SupportPackValidator()), + new BgfxGameContentCompiler( + m_assets, + m_engine.serialization, + m_engine.types, + MacOSArm64BgfxIntegration.shaderProfile, + [GraphicsApi.metal], + new ToolRunner() + ) + ), + new GameBuildTargetBinding( + new WindowsX64GameBuildTarget(new WindowsX64SupportPackValidator()), + new BgfxGameContentCompiler( + m_assets, + m_engine.serialization, + m_engine.types, + WindowsX64BgfxIntegration.shaderProfile, + [ + GraphicsApi.direct3D11, + GraphicsApi.direct3D12, + GraphicsApi.vulkan, + GraphicsApi.openGL + ], + new ToolRunner() + ) + ) + ], + managedDeployments ?? CreateManagedDeployments(), + provisioner + ); + + protected static BuildProfile CreateProfile( + BuildTargetID target, + string productName = "Test Game" + ) => new() + { + applicationId = "tests.game", + productName = productName, + startupScene = "Scenes/Startup.iscene", + target = target + }; protected static ManagedDeploymentCatalog CreateManagedDeployments() => new([new FixtureManagedDeploymentCompiler()]); @@ -171,7 +208,9 @@ protected sealed class CommitFailingProgress : IProgress public void Report(BuildProgress value) { if (value.stage == "commit") + { throw new InvalidOperationException("Fixture commit observer failed after publication."); + } } } @@ -179,12 +218,15 @@ protected sealed class FixtureManagedDeploymentCompiler : IManagedDeploymentComp { public FixtureManagedDeploymentCompiler(IReadOnlyList? runtimeIdentifiers = null) { - capabilities = new ManagedDeploymentCapabilities( + this.capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers ?? ["win-x64", "osx-arm64"], - dynamicCode: true, aheadOfTime: false, nativeStaticLinking: false); + dynamicCode: true, + aheadOfTime: false, + nativeStaticLinking: false + ); } - public ManagedDeploymentId id => ManagedDeploymentId.coreClr; + public ManagedDeploymentID id => ManagedDeploymentID.coreClr; public ManagedDeploymentCapabilities capabilities { get; } @@ -205,9 +247,16 @@ public ValueTask CompileAsync( Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(native, destination); } - return ValueTask.FromResult(new ManagedDeploymentResult(id, request.outputDirectory, "fixture-sdk", - Directory.EnumerateFiles(request.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(request.outputDirectory, file)).ToArray())); + return ValueTask.FromResult( + new ManagedDeploymentResult( + id, + request.outputDirectory, + "fixture-sdk", + Directory.EnumerateFiles(request.outputDirectory, "*", SearchOption.AllDirectories) + .Select(file => Path.GetRelativePath(request.outputDirectory, file)) + .ToArray() + ) + ); } } @@ -216,7 +265,7 @@ protected sealed class PendingSupportPackProvisioner : IPlayerSupportPackProvisi private readonly TaskCompletionSource m_completion = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask ProvisionAsync( - BuildTargetId target, + BuildTargetID target, string supportPackRoot, CancellationToken cancellationToken = default ) => new(m_completion.Task.WaitAsync(cancellationToken)); @@ -230,7 +279,7 @@ protected sealed class DrainingSupportPackProvisioner : IPlayerSupportPackProvis public bool completed { get; private set; } public async ValueTask ProvisionAsync( - BuildTargetId target, + BuildTargetID target, string supportPackRoot, CancellationToken cancellationToken = default ) { @@ -242,13 +291,12 @@ public async ValueTask ProvisionAsync( } } - protected sealed class TestSupportPackProvisioner(Action provision) - : IPlayerSupportPackProvisioner + protected sealed class TestSupportPackProvisioner(Action provision) : IPlayerSupportPackProvisioner { public int callCount { get; private set; } public ValueTask ProvisionAsync( - BuildTargetId target, + BuildTargetID target, string supportPackRoot, CancellationToken cancellationToken = default ) { @@ -262,22 +310,20 @@ public ValueTask ProvisionAsync( protected sealed class BlockingBuildTarget : IGameBuildTarget, IGameContentCompiler { - public TaskCompletionSource started { get; } = new( - TaskCreationOptions.RunContinuationsAsynchronously); - public TaskCompletionSource release { get; } = new( - TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public void Validate(string directory) => new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator().Validate(directory); + public TaskCompletionSource release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public BuildTargetId id => new BuildTargetId("macos-arm64"); - public BuildTargetId target => id; + public BuildTargetID id => new BuildTargetID("macos-arm64"); + public BuildTargetID target => id; - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.coreClr; public string runtimeIdentifier => "osx-arm64"; public string displayName => "Blocking test target"; + public void Validate(string directory) => new MacOSArm64SupportPackValidator().Validate(directory); public async ValueTask CompileAsync( GameBuildContentContext context, diff --git a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs index 7487b08f4..1a13b083a 100644 --- a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs +++ b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs @@ -2,6 +2,9 @@ using System.IO; using System.Linq; using Inno.Build; +using Inno.Build.MacOSArm64; +using Inno.Build.WindowsX64; +using Inno.Core.Identity; namespace Inno.Testing.SupportPacks; @@ -11,29 +14,36 @@ public abstract class PlayerSupportPackFixture : IDisposable protected readonly string m_supportPackRoot; private readonly string[] m_referenceAssemblies; - protected PlayerSupportPackFixture() : this([typeof(Inno.Core.Identity.IdentityAllocator).Assembly.Location]) - { - } + protected PlayerSupportPackFixture() + : this([typeof(IdentityAllocator).Assembly.Location]) {} protected PlayerSupportPackFixture(string[] referenceAssemblies) { m_referenceAssemblies = referenceAssemblies; m_supportPackRoot = Path.Combine(m_root, "SupportPacks"); Directory.CreateDirectory(m_root); - CreateSupportPack(new BuildTargetId("macos-arm64"), "Inno.Player.MacOSArm64"); - CreateSupportPack(new BuildTargetId("windows-x64"), "Inno.Player.WindowsX64.exe"); + CreateSupportPack(new BuildTargetID("macos-arm64"), "Inno.Player.MacOSArm64"); + CreateSupportPack(new BuildTargetID("windows-x64"), "Inno.Player.WindowsX64.exe"); } public virtual void Dispose() { - if (!Path.GetFullPath(m_root).StartsWith(Path.Combine(Path.GetTempPath(), "InnoBuildTests") + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(m_root) + .StartsWith( + Path.Combine(Path.GetTempPath(), "InnoBuildTests") + Path.DirectorySeparatorChar, + StringComparison.OrdinalIgnoreCase + ) + ) { throw new InvalidOperationException("The support pack fixture escaped its owned directory."); + } if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } protected void CreateSupportPack( - BuildTargetId target, + BuildTargetID target, string executable ) { string directory = Path.Combine(m_root, "pack-candidate-" + Guid.NewGuid().ToString("N")); @@ -47,11 +57,20 @@ string executable File.WriteAllBytes(Path.Combine(directory, executable), [0x49, 0x4E, 0x4E, 0x4F]); string link = Path.Combine(directory, "PlayerLink"); Directory.CreateDirectory(link); - string platform = target == new BuildTargetId("macos-arm64") ? "MacOSArm64" : "WindowsX64"; - File.WriteAllText(Path.Combine(link, "Player.csproj"), - "Inno.Player." + platform + ""); - foreach (string source in new[] { "Program.cs", platform + "PlayerComposition.cs", platform + "PlayerContentSource.cs", "global.json" }) + string platform = target == new BuildTargetID("macos-arm64") ? "MacOSArm64" : "WindowsX64"; + File.WriteAllText( + Path.Combine(link, "Player.csproj"), + "Inno.Player." + platform + "" + ); + foreach (string source in new[] + { + "Program.cs", + platform + "PlayerComposition.cs", + platform + "PlayerContentSource.cs", + "global.json" + }) { File.WriteAllText(Path.Combine(link, source), "fixture input"); + } string analyzers = Path.Combine(link, "Analyzers"); Directory.CreateDirectory(analyzers); File.WriteAllText(Path.Combine(analyzers, "Inno.Runtime.Generators.dll"), "fixture analyzer"); @@ -59,17 +78,19 @@ string executable string linkReferences = Path.Combine(link, "References"); Directory.CreateDirectory(linkReferences); foreach (string source in Directory.EnumerateFiles(references, "*.dll")) + { File.Copy(source, Path.Combine(linkReferences, Path.GetFileName(source))); + } File.WriteAllText(Path.Combine(linkReferences, "Inno.Player.Runtime.dll"), "fixture runtime"); File.WriteAllText(Path.Combine(linkReferences, "BGCS.Runtime.dll"), "fixture interop"); File.WriteAllBytes(Path.Combine(link, executable), [0x49, 0x4E, 0x4E, 0x4F]); string native = Path.Combine(directory, "native"); Directory.CreateDirectory(native); - string[] required = target == new BuildTargetId("macos-arm64") - ? ["libbgfx-shared-lib-release.dylib", "SDL3-release.dylib", "libminiaudio-release.dylib", - "libinno-text-release.dylib", "libinno-ui-release.dylib"] - : ["bgfx-shared-lib-release.dll", "SDL3-release.dll", "miniaudio-release.dll", - "inno-text-release.dll", "inno-ui-release.dll"]; + string[] required = target == new BuildTargetID("macos-arm64") + ? ["libbgfx-shared-lib-release.dylib", "SDL3-release.dylib", "libminiaudio-release.dylib", + "libinno-text-release.dylib", "libinno-ui-release.dylib"] + : ["bgfx-shared-lib-release.dll", "SDL3-release.dll", "miniaudio-release.dll", + "inno-text-release.dll", "inno-ui-release.dll"]; string linkNative = Path.Combine(link, "native"); Directory.CreateDirectory(linkNative); foreach (string file in required) @@ -77,41 +98,44 @@ string executable File.WriteAllBytes(Path.Combine(native, file), CreateNativeImage(target)); File.WriteAllBytes(Path.Combine(linkNative, file), CreateNativeImage(target)); } - IPlayerSupportPackValidator validator = target == new BuildTargetId("macos-arm64") - ? new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator() - : new Inno.Build.WindowsX64.WindowsX64SupportPackValidator(); + IPlayerSupportPackValidator validator = target == new BuildTargetID("macos-arm64") + ? new MacOSArm64SupportPackValidator() + : new WindowsX64SupportPackValidator(); using PlayerSupportPackLease published = new PlayerSupportPackCatalog(m_supportPackRoot).PublishAsync( - target, directory, validator).AsTask().GetAwaiter().GetResult(); + target, + directory, + validator + ).AsTask().GetAwaiter().GetResult(); } - protected string GetSupportPackDirectory(BuildTargetId target) + protected string GetSupportPackDirectory(BuildTargetID target) { string targetRoot = Path.Combine(m_supportPackRoot, target.value); return Path.Combine(targetRoot, File.ReadAllText(Path.Combine(targetRoot, "current"))); } - protected static byte[] CreateNativeImage(BuildTargetId target) + protected static byte[] CreateNativeImage(BuildTargetID target) { using var output = new MemoryStream(); using var writer = new BinaryWriter(output); - if (target == new BuildTargetId("macos-arm64")) + if (target == new BuildTargetID("macos-arm64")) { - writer.Write(0xfeedfacfu); - writer.Write(0x0100000cu); + writer.Write(0xFEED_FACFu); + writer.Write(0x0100_000Cu); writer.Write(0u); writer.Write(6u); writer.Write(new byte[16]); } else { - writer.Write((ushort)0x5a4d); + writer.Write((ushort)0x5A4D); writer.Write(new byte[58]); writer.Write(64); - writer.Write(0x00004550u); + writer.Write(0x0000_4550u); writer.Write((ushort)0x8664); writer.Write(new byte[16]); writer.Write((ushort)0x2000); - writer.Write((ushort)0x020b); + writer.Write((ushort)0x020B); } return output.ToArray(); } @@ -122,5 +146,4 @@ protected static bool IsAuthoringAssembly(string name) || name.Contains("Inno.Scripting.Compiler", StringComparison.OrdinalIgnoreCase) || name.Contains("Inno.Assets.Pipeline", StringComparison.OrdinalIgnoreCase) || name.Contains("Inno.Plugins.Authoring", StringComparison.OrdinalIgnoreCase); - } diff --git a/tests/ci/ProductJourney.Tests.ps1 b/tests/ci/ProductJourney.Tests.ps1 index 2892c1342..de05e8f98 100644 --- a/tests/ci/ProductJourney.Tests.ps1 +++ b/tests/ci/ProductJourney.Tests.ps1 @@ -12,7 +12,7 @@ try { [IO.File]::WriteAllText((Join-Path $root 'Program.cs'), @' using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using EditorUiAcceptance; +using EditorUIAcceptance; if (args is ["memory-sampling"]) { diff --git a/tests/ci/Test-AgentRules.Tests.ps1 b/tests/ci/Test-AgentRules.Tests.ps1 index c4eb08cf0..cf87aa710 100644 --- a/tests/ci/Test-AgentRules.Tests.ps1 +++ b/tests/ci/Test-AgentRules.Tests.ps1 @@ -2,292 +2,101 @@ param([string]$DocsRoot) $ErrorActionPreference = 'Stop' $repository = [IO.Path]::GetFullPath('../..', $PSScriptRoot) $entry = Join-Path $PSScriptRoot 'Test-AgentRules.ps1' -$root = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion) -join "`n" -Push-Location (Join-Path $repository 'tools') -try { $nested = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion) -join "`n" } -finally { Pop-Location } -if ($root -cne $nested) { throw 'Root and nested invocation selected different instruction units.' } -if ($root -notmatch 'Preserved mapping: 241 rules') { throw 'Original rule coverage is incomplete.' } -foreach ($path in @('Directory.Build.targets', 'Directory.Solution.targets')) { - $selection = @(& $entry -Paths $path) -join "`n" - foreach ($required in @('build-host', 'platform-products', 'backend-build', 'solution')) { - if (-not $selection.Contains($required)) { throw "Shared build input $path did not route to $required." } - } + +function Assert-Rejected([string]$message, [scriptblock]$action) { + $failure = $null + try { & $action | Out-Null } catch { $failure = $_.Exception.Message } + if ($null -eq $failure -or -not $failure.Contains($message)) { throw "Expected a rejection containing '$message' but got: $failure" } } -foreach ($scenario in @(@{ Rules = 'unknown-unit' }, @{ Behaviors = 'unknown-behavior' }, @{ Stage = 999 })) { - $rejected = $false - try { & $entry @scenario | Out-Null } catch { $rejected = $true } - if (-not $rejected) { throw 'Invalid rule selection was accepted.' } +function Assert-Selection([string]$output, [string[]]$includes, [string[]]$excludes = @()) { + foreach ($file in $includes) { if (-not $output.Contains($file + ' |')) { throw "Expected rule file $file in: $output" } } + foreach ($file in $excludes) { if ($output.Contains($file + ' |')) { throw "Unexpected rule file $file in: $output" } } } -$manifest = Get-Content -LiteralPath (Join-Path $repository '.agents/rulebook/coverage.json') -Raw | ConvertFrom-Json -foreach ($unit in $manifest.units) { - if (-not $unit.sourceHash -or -not $unit.check -or -not $unit.reviewer) { throw "Incomplete rule responsibility: $($unit.id)" } -} -$all = @(& $entry -Rules @($manifest.units | Where-Object { -not $_.repository } | ForEach-Object id)) -join "`n" -foreach ($match in [regex]::Matches($all, 'Stage \d+: (\d+) bytes')) { - if ([int]$match.Groups[1].Value -gt 16384) { throw 'A staged instruction set exceeds its complete-read budget.' } -} -$first = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion -Stage 1 -ShowInstructions) -join "`n" -if (-not $first.Contains('# InnoEngine agent instructions') -or -not $first.Contains('Define clear assembly/domain boundaries')) { throw 'Actual instruction bodies were not emitted.' } -$fixtureParent = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()) -$fixture = Join-Path $fixtureParent ('InnoRuleTests-' + [guid]::NewGuid().ToString('N')) + +# The repository rules load identically from any working directory and in both list forms. +$root = @(& $entry -Paths 'src/services/input/Example.cs' -Rules validation) -join "`n" +Push-Location (Join-Path $repository 'tools') +try { $nested = @(& $entry -Paths 'src/services/input/Example.cs' -Rules validation) -join "`n" } +finally { Pop-Location } +if ($root -cne $nested) { throw 'Root and nested invocation selected different rule files.' } +Assert-Selection $root @('.agents/rulebook/coding.md', '.agents/rulebook/validation.md', '.agents/rulebook/csharp-style/README.md') +$joined = @(& $entry -Paths 'Directory.Build.targets,Directory.Solution.targets') -join "`n" +if ($joined -cne (@(& $entry -Paths 'Directory.Build.targets', 'Directory.Solution.targets') -join "`n")) { throw 'Comma-joined and array selections differ.' } +Assert-Selection $joined @('.agents/rulebook/projects.md', '.agents/rulebook/domains/build-native/hosts.md', + '.agents/rulebook/domains/build-native/platform-products.md', '.agents/rulebook/domains/build-native/backend-integration.md') +Assert-Selection (@(& $entry -Paths (Join-Path $repository 'AGENTS.md')) -join "`n") @('.agents/rulebook/validation.md') +Assert-Rejected 'Unknown rule: unknown-rule' { & $entry -Rules unknown-rule } +Assert-Rejected 'Unknown tag: unknown-tag' { & $entry -Tags unknown-tag } +Assert-Rejected 'Path is outside the repository' { & $entry -Paths '../outside.cs' } +if ($DocsRoot) { Assert-Selection (@(& $entry -DocsRoot $DocsRoot -Tags documentation) -join "`n") @('.agents/rulebook/documentation.md') } + +$fixture = Join-Path ([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) ('InnoRuleTests-' + [guid]::NewGuid().ToString('N')) try { - & git clone --quiet --shared --no-checkout $repository $fixture - if ($LASTEXITCODE -ne 0) { throw 'Cannot create the isolated rule provenance fixture.' } - # A clone of a shallow CI checkout does not inherit separately fetched provenance objects. - # Acquire only missing original revisions from the explicit local owner, never the network. - $provenance = @("$($manifest.baseline):AGENTS.md") + @($manifest.units | ForEach-Object source) + - @($manifest.units | Where-Object { $_.approvedAddition.translation } | ForEach-Object { $_.approvedAddition.translation.source }) - foreach ($source in @($provenance | Sort-Object -Unique)) { - & git -C $fixture cat-file -e $source 2>$null - if ($LASTEXITCODE -eq 0) { continue } - $revision = ($source -split ':', 2)[0] - if ($revision -cnotmatch '^[a-f0-9]{40}$') { throw 'The rule fixture requires immutable local provenance.' } - & git -C $fixture fetch --quiet --no-tags --depth=1 $repository $revision - if ($LASTEXITCODE -ne 0) { throw 'Cannot prepare original rule provenance from the local checkout.' } - & git -C $fixture cat-file -e $source 2>$null - if ($LASTEXITCODE -ne 0) { throw "Original rule provenance is unavailable in the fixture: $source" } - } - [void][IO.Directory]::CreateDirectory((Join-Path $fixture 'tests/ci')) - [void][IO.Directory]::CreateDirectory((Join-Path $fixture '.agents')) - Copy-Item -LiteralPath (Join-Path $repository '.agents/rulebook') -Destination (Join-Path $fixture '.agents/rulebook') -Recurse - Copy-Item -LiteralPath (Join-Path $repository 'AGENTS.md') -Destination $fixture - Copy-Item -LiteralPath $entry -Destination (Join-Path $fixture 'tests/ci/Test-AgentRules.ps1') - foreach ($instruction in @((Join-Path $repository 'AGENTS.md')) + @(Get-ChildItem (Join-Path $repository '.agents/rulebook') -Recurse -Filter '*.md' | ForEach-Object FullName)) { - foreach ($link in [regex]::Matches([IO.File]::ReadAllText($instruction), '\]\(([^)#]+)(?:#[^)]*)?\)')) { - $relative = $link.Groups[1].Value - if ($relative -match '^[a-z]+:') { continue } - $sourceFile = [IO.Path]::GetFullPath($relative, (Split-Path $instruction)) - $target = Join-Path $fixture ([IO.Path]::GetRelativePath($repository, $sourceFile)) - if (-not [IO.Path]::GetFullPath($target).StartsWith($fixture + [IO.Path]::DirectorySeparatorChar, [StringComparison]::Ordinal)) { - throw 'Instruction fixture link escaped its isolated owner.' - } - [void][IO.Directory]::CreateDirectory((Split-Path $target)) - Copy-Item -LiteralPath $sourceFile -Destination $target - } - } - foreach ($review in @($manifest.units | Where-Object translation | ForEach-Object { ($_.translation.review -split '#')[0] } | Sort-Object -Unique)) { - $reviewTarget = Join-Path $fixture $review - [void][IO.Directory]::CreateDirectory((Split-Path $reviewTarget)) - Copy-Item -LiteralPath (Join-Path $repository $review) -Destination $reviewTarget - } - foreach ($review in @($manifest.units | ForEach-Object { $_.translation.amendments } | Where-Object { $null -ne $_ } | ForEach-Object review | Sort-Object -Unique)) { - $reviewTarget = Join-Path $fixture $review - [void][IO.Directory]::CreateDirectory((Split-Path $reviewTarget)) - Copy-Item -LiteralPath (Join-Path $repository $review) -Destination $reviewTarget + $rules = Join-Path $fixture '.agents/rulebook' + $docs = Join-Path $fixture 'docs-checkout' + foreach ($directory in @((Join-Path $fixture 'tests/ci'), (Join-Path $rules 'domains'), (Join-Path $docs '.agents/rulebook'))) { + [void][IO.Directory]::CreateDirectory($directory) } $fixtureEntry = Join-Path $fixture 'tests/ci/Test-AgentRules.ps1' - $registry = Join-Path $fixture '.agents/rulebook/coverage.json' - $originalRegistry = [IO.File]::ReadAllText($registry) - foreach ($scenario in @('missing-original', 'non-file-original', 'injected-source-line')) { - $copy = $originalRegistry | ConvertFrom-Json - $revision = ($copy.units[0].source -split ':', 2)[0] - $expected = 'Unavailable rule source' - switch ($scenario) { - 'missing-original' { $copy.units[0].source = $revision + ':missing-rule-original.md' } - 'non-file-original' { $copy.units[0].source = $revision + ':docs' } - 'injected-source-line' { - $copy.units[0].source += "`n" + $copy.units[1].source - $expected = 'Invalid immutable rule source' - } - } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong source rejection for ${scenario}: $failure" } + $examples = Join-Path $fixture 'tests/ci/Test-AgentRules.examples.json' + Copy-Item -LiteralPath $entry -Destination $fixtureEntry + function Write-Fixture([string]$path, [string]$text) { [IO.File]::WriteAllText((Join-Path $fixture $path), $text) } + Write-Fixture 'AGENTS.md' "# Entry`n" + Write-Fixture '.agents/rulebook/README.md' "# Index without front matter`n" + Write-Fixture '.agents/rulebook/coding.md' "---`npaths: [`"**/*.cs`", `"src/*.txt`"]`ntags: [coding, shared]`n---`n# Coding`n" + Write-Fixture '.agents/rulebook/domains/editor.md' "---`npaths: [`"src/editor/**`"]`n---`n# Editor`n" + Write-Fixture '.agents/rulebook/delivery.md' "---`ntags: [delivery, shared]`n---`n# Delivery`n" + Write-Fixture 'docs-checkout/.agents/rulebook/README.md' "# Docs index`n" + Write-Fixture 'docs-checkout/.agents/rulebook/writing.md' "---`npaths: [`"content/**`"]`ntags: [writing]`n---`n# Writing`n" + Write-Fixture 'tests/ci/Test-AgentRules.examples.json' '[{ "path": "src/editor/State.cs", "includes": ["coding", "domains/editor"], "excludes": ["delivery"] }]' + + # Globs match the whole path, `*` stays inside one name and matching is case-sensitive. + $valid = @(& $fixtureEntry) -join "`n" + if (-not $valid.Contains('Rules are valid: 3 files.')) { throw "Unexpected fixture summary: $valid" } + Assert-Selection (@(& $fixtureEntry -Paths 'Root.cs') -join "`n") @('.agents/rulebook/coding.md') @('.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Paths 'src/editor/panels/Panel.cs') -join "`n") @('.agents/rulebook/coding.md', '.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Paths 'src/note.txt') -join "`n") @('.agents/rulebook/coding.md') + foreach ($unmatched in @('src/nested/note.txt', 'src/Editor/note.md', 'tools/editor/note.md', 'Root.CS')) { + if ((@(& $fixtureEntry -Paths $unmatched) -join "`n").Contains(' | ')) { throw "Path must not select a rule: $unmatched" } } - [IO.File]::WriteAllText($registry, $originalRegistry) - foreach ($scenario in @('missing-amendment-approval', 'changed-amendment-hash', 'unmapped-amendment', 'duplicate-amendment')) { - $copy = $originalRegistry | ConvertFrom-Json - $translation = ($copy.units | Where-Object id -CEQ 'directories').translation - switch ($scenario) { - 'missing-amendment-approval' { $translation.amendments[0].approval = ''; $expected = 'Invalid approved rule amendment' } - 'changed-amendment-hash' { $translation.amendments[0].currentHash = '0' * 64; $expected = 'Changed or unmapped translation clause' } - 'unmapped-amendment' { $translation.amendments += [pscustomobject]@{ ordinal = 999 }; $expected = 'Unmapped approved rule amendment' } - 'duplicate-amendment' { $translation.amendments += $translation.amendments[0]; $expected = 'Duplicate approved rule amendment' } + Assert-Selection (@(& $fixtureEntry -Tags shared) -join "`n") @('.agents/rulebook/coding.md', '.agents/rulebook/delivery.md') @('.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Rules 'domains/editor') -join "`n") @('.agents/rulebook/domains/editor.md') + + # An explicit Docs checkout adds its own rule files; its paths never select engine rules. + Assert-Rejected 'Unknown tag: writing' { & $fixtureEntry -Tags writing } + $writing = Join-Path $docs '.agents/rulebook/writing.md' + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Tags writing) -join "`n") @($writing) + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Rules 'docs/writing') -join "`n") @($writing) + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Paths (Join-Path $docs 'content/Guide.cs')) -join "`n") @($writing) @('.agents/rulebook/coding.md') + + $cases = @( + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "# No front matter`n" }, + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "---`ntags:`n - block-list`n---`n# Rule`n" }, + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "---`n---`n# Rule`n" }, + @{ message = 'Unknown or repeated front matter field'; path = '.agents/rulebook/broken.md'; text = "---`nrequires: [coding]`n---`n# Rule`n" }, + @{ message = 'Unknown or repeated front matter field'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [one]`ntags: [two]`n---`n# Rule`n" }, + @{ message = 'Empty front matter value'; path = '.agents/rulebook/broken.md'; text = "---`ntags: []`n---`n# Rule`n" }, + @{ message = 'Invalid rule tag'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [Not Valid]`n---`n# Rule`n" }, + @{ message = 'not a repository-relative glob'; path = '.agents/rulebook/broken.md'; text = "---`npaths: [`"/src/**`"]`n---`n# Rule`n" }, + @{ message = 'not a repository-relative glob'; path = '.agents/rulebook/broken.md'; text = "---`npaths: [`"src/../**`"]`n---`n# Rule`n" }, + @{ message = 'exceeds 16384 bytes'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [large]`n---`n" + ('x' * 16384) }, + @{ message = 'Root instructions exceed 8192 bytes'; path = 'AGENTS.md'; text = 'x' * 8193 }, + @{ message = 'must select delivery'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "includes": ["delivery"] }]' }, + @{ message = 'must not select coding'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "excludes": ["coding"] }]' }, + @{ message = 'names an unknown rule: retired'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "excludes": ["retired"] }]' } + ) + foreach ($case in $cases) { + $target = Join-Path $fixture $case.path + $original = if (Test-Path -LiteralPath $target) { [IO.File]::ReadAllText($target) } else { $null } + try { + [IO.File]::WriteAllText($target, $case.text) + Assert-Rejected $case.message { & $fixtureEntry } + } finally { + if ($null -eq $original) { Remove-Item -LiteralPath $target } else { [IO.File]::WriteAllText($target, $original) } } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong amendment rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($registry, $originalRegistry) - # Use one real preserved engine unit as an isolated external-authority fixture. No network, - # sibling checkout or copied current Docs tree is needed by engine-only regression execution. - $authorityRoot = Join-Path $fixture 'external-authority' - $authorityRules = Join-Path $authorityRoot '.agents/rulebook' - [void][IO.Directory]::CreateDirectory($authorityRules) - $externalCopy = $originalRegistry | ConvertFrom-Json - $externalUnit = $externalCopy.units | Where-Object id -CEQ 'style' - $localAuthority = Join-Path $fixture $externalUnit.path - $localText = [IO.File]::ReadAllText($localAuthority) - $unitPattern = '(?s).*?' - $externalText = [regex]::Match($localText, $unitPattern).Value - $externalUnit | Add-Member repository 'Wolfiora/InnoEngine.Docs' - $externalUnit.path = '.agents/rulebook/imported.md' - foreach ($row in $externalCopy.rules | Where-Object unit -CEQ 'style') { - $row | Add-Member repository 'Wolfiora/InnoEngine.Docs' - $row.path = $externalUnit.path - } - $externalPath = Join-Path $authorityRoot $externalUnit.path - [IO.File]::WriteAllText($externalPath, $externalText) - [IO.File]::WriteAllText($localAuthority, [regex]::Replace($localText, $unitPattern, '')) - [IO.File]::WriteAllText($registry, ($externalCopy | ConvertTo-Json -Depth 50)) - # Other migrated units are not part of this single-authority fixture; selecting a missing - # authority must fail before any complete instruction output can be claimed. - $failure = '' - try { & $fixtureEntry -Rules style | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Supply -DocsRoot')) { throw "Missing explicit external rule authority was accepted: $failure" } - foreach ($scenario in @('unknown-repository', 'escaped-authority')) { - $originalPath = $externalUnit.path - if ($scenario -eq 'unknown-repository') { $externalUnit.repository = 'Other/Rules' } - else { $externalUnit.path = '../../escaped.md' } - [IO.File]::WriteAllText($registry, ($externalCopy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - $expected = if ($scenario -eq 'unknown-repository') { 'Unknown rule repository' } else { 'Rule path escapes owner' } - if (-not $failure.Contains($expected)) { throw "Wrong external authority rejection for ${scenario}: $failure" } - $externalUnit.repository = 'Wolfiora/InnoEngine.Docs' - $externalUnit.path = $originalPath - } - [IO.File]::WriteAllText($registry, $originalRegistry) - [IO.File]::WriteAllText($localAuthority, $localText) - if ($DocsRoot) { - foreach ($path in @($manifest.units | Where-Object repository | ForEach-Object path | Sort-Object -Unique)) { - $target = Join-Path $authorityRoot $path - [void][IO.Directory]::CreateDirectory((Split-Path $target)) - Copy-Item -LiteralPath (Join-Path $DocsRoot $path) -Destination $target - } - $complete = @(& $fixtureEntry -DocsRoot $authorityRoot -Rules wiki -ShowInstructions) -join "`n" - if (-not $complete.Contains('External authority verified: 8 complete units') -or -not $complete.Contains('Canonical source and example verification')) { - throw 'Explicit external authority did not load complete current requirements.' - } - Push-Location (Join-Path $fixture 'tests') - try { $nestedExternal = @(& $fixtureEntry -DocsRoot $authorityRoot -Rules wiki -ShowInstructions) -join "`n" } - finally { Pop-Location } - if ($complete -cne $nestedExternal) { throw 'Nested invocation changed external authority or rule bodies.' } - $authority = Join-Path $authorityRoot '.agents/rulebook/documentation.md' - $originalAuthority = [IO.File]::ReadAllText($authority) - [IO.File]::WriteAllText($authority, $originalAuthority.Replace('## API reference and source', '## Weakened contract')) - $failure = '' - try { & $fixtureEntry -DocsRoot $authorityRoot | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Changed or unmapped translation clause')) { throw 'Changed external rule body passed provenance validation.' } - [IO.File]::WriteAllText($authority, $originalAuthority) - [IO.File]::WriteAllText($authority, $originalAuthority + "`n`n") - $failure = '' - try { & $fixtureEntry -DocsRoot $authorityRoot | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Unregistered external rule authority')) { throw 'Unregistered external rule authority passed validation.' } - [IO.File]::WriteAllText($authority, $originalAuthority) - } - foreach ($scenario in @('cycle', 'missing-section', 'unregistered-section')) { - [IO.File]::WriteAllText($registry, $originalRegistry) - $copy = $originalRegistry | ConvertFrom-Json - $unitPath = Join-Path $fixture $copy.units[0].path - $originalUnit = [IO.File]::ReadAllText($unitPath) - $expected = switch ($scenario) { - 'cycle' { - $copy.units[0].requires = @($copy.units[0].id) - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - 'Cyclic rule dependency' - } - 'missing-section' { - [IO.File]::WriteAllText($unitPath, $originalUnit.Replace('', '')) - 'Missing or repeated complete rule unit' - } - 'unregistered-section' { - [IO.File]::WriteAllText($unitPath, $originalUnit + "`n`n") - 'Unregistered rule unit' - } - } - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - [IO.File]::WriteAllText($unitPath, $originalUnit) - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($registry, $originalRegistry) - $translationUnit = ($originalRegistry | ConvertFrom-Json).units | Where-Object id -CEQ 'delivery' - $translationPath = Join-Path $fixture $translationUnit.path - $originalTranslation = [IO.File]::ReadAllText($translationPath) - foreach ($scenario in @('changed-translation', 'missing-clause', 'changed-source-map', 'missing-review', 'escaped-review', 'lost-original-rule')) { - $copy = $originalRegistry | ConvertFrom-Json - $translated = $copy.units | Where-Object id -CEQ 'delivery' - [IO.File]::WriteAllText($translationPath, $originalTranslation) - $expected = switch ($scenario) { - 'changed-translation' { - [IO.File]::WriteAllText($translationPath, $originalTranslation.Replace('must be entirely in English', 'may be in any language')) - 'Changed or unmapped translation clause' - } - 'missing-clause' { - $translated.translation.lines = @($translated.translation.lines | Select-Object -Skip 1) - 'Incomplete translation coverage' - } - 'changed-source-map' { - $translated.translation.lines[0].sourceHash = 'invalid' - 'Changed or unmapped translation clause' - } - 'missing-review' { - $translated.translation.review = '.agents/records/missing.md' - 'Missing translation review' - } - 'escaped-review' { - $translated.translation.review = '.agents/records/../../AGENTS.md' - 'Missing translation review' - } - 'lost-original-rule' { - ($copy.rules | Where-Object id -CEQ '31.1').translatedHash = 'invalid' - 'Rule translation was lost' - } - } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($translationPath, $originalTranslation) - [IO.File]::WriteAllText($registry, $originalRegistry) - $nestedRulePath = Join-Path $fixture '.agents/rulebook/coding.md' - $nestedRuleText = [IO.File]::ReadAllText($nestedRulePath) - [IO.File]::WriteAllText($nestedRulePath, $nestedRuleText.Replace(' - Types and members', '- Types and members')) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - [IO.File]::WriteAllText($nestedRulePath, $nestedRuleText) - if (-not $failure.Contains('Changed or unmapped translation clause')) { throw 'Nested rule indentation lost its provenance protection.' } - $additionUnit = ($originalRegistry | ConvertFrom-Json).units | Where-Object id -CEQ 'csharp-standard-5' - $additionPath = Join-Path $fixture $additionUnit.path - $originalAddition = [IO.File]::ReadAllText($additionPath) - $loaded = @(& $entry -Rules $additionUnit.id -ShowInstructions) -join "`n" - if (-not $loaded.Contains('Handwritten C# must not use `global::`')) { throw 'Approved addition was not loaded.' } - foreach ($scenario in @('changed-addition', 'missing-addition', 'missing-approval', 'changed-baseline')) { - [IO.File]::WriteAllText($registry, $originalRegistry) - [IO.File]::WriteAllText($additionPath, $originalAddition) - $expected = 'Invalid approved rule addition' - switch ($scenario) { - 'changed-addition' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('Handwritten C# must not use', 'Handwritten C# may use')) - $expected = 'Changed or unmapped translation clause' - } - 'missing-addition' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('', '')) - } - 'missing-approval' { - $copy = $originalRegistry | ConvertFrom-Json - ($copy.units | Where-Object id -CEQ $additionUnit.id).approvedAddition.approval = '' - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - } - 'changed-baseline' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('- Explicitly declare ordinary using directives in every file.', '')) - $expected = 'Incomplete translation coverage' - } - } - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } } + & $fixtureEntry | Out-Null } finally { - $resolved = [IO.Path]::GetFullPath($fixture) - if (-not $resolved.StartsWith($fixtureParent, [StringComparison]::Ordinal) -or (Split-Path $resolved -Leaf) -notmatch '^InnoRuleTests-[a-f0-9]{32}$') { - throw 'Rule fixture cleanup escaped its unique owner.' - } - if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force } + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } } -Write-Output 'Agent rule coverage, actual loading, root/nested routing, staged budgets, invalid selections, missing units, cyclic dependencies, approved additions and English translation provenance passed.' +Write-Output 'Agent rule loading, front matter, glob routing, size limits, invalid selections, routing examples and explicit Docs checkouts passed.' diff --git a/tests/ci/Test-AgentRules.examples.json b/tests/ci/Test-AgentRules.examples.json new file mode 100644 index 000000000..d23f8a436 --- /dev/null +++ b/tests/ci/Test-AgentRules.examples.json @@ -0,0 +1,20 @@ +[ + { "path": "src/foundation/core/Inno.Core.Mathematics/Vector2.cs", "includes": ["coding", "csharp-style/README", "csharp-style/03-naming", "csharp-style/17-example"], "excludes": ["domains/editor/state", "domains/identity-reload", "validation", "projects"] }, + { "path": "src/foundation/core/Inno.Core.Execution/StateMachine.cs", "excludes": ["domains/editor/state", "domains/editor/projects"] }, + { "path": "tools/Inno.Tooling.Validation/ValidationWorkspace.cs", "excludes": ["domains/editor/state"] }, + { "path": "assets/branding/logo.svg", "excludes": ["domains/identity-reload"] }, + { "path": "tools/Inno.Tooling.Validation/AssetsReport.cs", "includes": ["coding"], "excludes": ["domains/identity-reload"] }, + { "path": "src/composition/editor/framework/Inno.Editor.Core/History/UndoStack.cs", "includes": ["coding", "domains/editor/projects", "domains/editor/state"], "excludes": ["domains/editor/ui"] }, + { "path": "src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/Form.cs", "includes": ["domains/editor/projects", "domains/editor/state", "domains/editor/ui"] }, + { "path": "backends/ImGui/runtime/Inno.Backend.ImGui/ImGuiRenderer.cs", "includes": ["domains/editor/ui", "domains/build-native/hosts", "domains/build-native/platform-products", "domains/build-native/backend-integration"] }, + { "path": "src/services/rendering/Inno.Rendering/Inno.Rendering.csproj", "includes": ["projects", "domains/rendering"], "excludes": ["coding"] }, + { "path": "src/services/audio/Inno.Audio/Properties/ScriptingApi.cs", "includes": ["domains/scripting", "domains/identity-reload"], "excludes": ["domains/plugins"] }, + { "path": "src/runtime/plugins/Inno.Plugins/PluginCatalog.cs", "includes": ["domains/plugins", "no-legacy", "domains/identity-reload"] }, + { "path": "src/content/scene/Inno.Scene/Scene.cs", "includes": ["domains/identity-reload"], "excludes": ["domains/rendering", "domains/plugins"] }, + { "path": "tests/rendering/Inno.Rendering.Tests/FrameTests.cs", "includes": ["validation", "coding", "domains/rendering"] }, + { "path": "Directory.Build.props", "includes": ["projects", "domains/build-native/hosts"] }, + { "path": ".github/workflows/validation.yml", "includes": ["domains/build-native/hosts"], "excludes": ["validation"] }, + { "path": ".agents/rulebook/coding.md", "includes": ["validation"], "excludes": ["coding"] }, + { "path": "AGENTS.md", "includes": ["validation"] }, + { "path": ".agents/records/decisions/README.md", "includes": ["validation"] } +] diff --git a/tests/ci/Test-AgentRules.ps1 b/tests/ci/Test-AgentRules.ps1 index 9c2cdd741..38bb89ff4 100644 --- a/tests/ci/Test-AgentRules.ps1 +++ b/tests/ci/Test-AgentRules.ps1 @@ -1,308 +1,104 @@ param( [string[]]$Paths = @(), [string[]]$Rules = @(), - [string[]]$Behaviors = @(), - [switch]$ShowInstructions, - [int]$Stage = 0, + [string[]]$Tags = @(), [string]$DocsRoot ) $ErrorActionPreference = 'Stop' $OutputEncoding = [Text.UTF8Encoding]::new($false) [Console]::OutputEncoding = $OutputEncoding +$rootBudget = 8192 +$fileBudget = 16384 $repository = [IO.Path]::GetFullPath('../..', $PSScriptRoot) -$ruleRoot = Join-Path $repository '.agents/rulebook' -$manifest = Get-Content -LiteralPath (Join-Path $ruleRoot 'coverage.json') -Raw | ConvertFrom-Json -$rootText = Get-Content -LiteralPath (Join-Path $repository 'AGENTS.md') -Raw -$rootBytes = [Text.Encoding]::UTF8.GetByteCount($rootText) -if ($rootBytes -gt $manifest.rootBudgetBytes) { throw 'Root instructions exceed 8 KiB.' } -$sources = @{} -$sourceIdentities = @("$($manifest.baseline):AGENTS.md") + @($manifest.units | ForEach-Object source) + - @($manifest.units | Where-Object { $_.approvedAddition.translation } | ForEach-Object { $_.approvedAddition.translation.source }) -$sourceReader = [Diagnostics.Process]::new() -$sourceReader.StartInfo.FileName = 'git' -foreach ($argument in @('-C', $repository, 'cat-file', '--batch')) { $sourceReader.StartInfo.ArgumentList.Add($argument) } -$sourceReader.StartInfo.UseShellExecute = $false -$sourceReader.StartInfo.CreateNoWindow = $true -$sourceReader.StartInfo.RedirectStandardInput = $true -$sourceReader.StartInfo.RedirectStandardOutput = $true -$sourceReader.StartInfo.RedirectStandardError = $true -$sourceReader.StartInfo.StandardInputEncoding = [Text.UTF8Encoding]::new($false) -# Preparation owns acquisition. Reading rules never hydrates a partial clone over the network. -$sourceReader.StartInfo.Environment['GIT_NO_LAZY_FETCH'] = '1' -$sourceReader.StartInfo.Environment['GIT_TERMINAL_PROMPT'] = '0' -$sourceStarted = $false -$bytes = $null -try { - $sourceStarted = $sourceReader.Start() - if (-not $sourceStarted) { throw 'Cannot read immutable rule provenance.' } - $sourceErrors = $sourceReader.StandardError.ReadToEndAsync() - $bytes = [IO.BinaryReader]::new($sourceReader.StandardOutput.BaseStream) - foreach ($identity in @($sourceIdentities | Sort-Object -Unique)) { - if ($identity -cnotmatch '^[a-f0-9]{40}:[^\r\n\x00]+$') { throw "Invalid immutable rule source: $identity" } - # Exchange one request and its size-delimited response at a time: neither pipe can fill - # while its peer is waiting for the complete batch, even for a large original rulebook. - $sourceReader.StandardInput.WriteLine($identity) - $sourceReader.StandardInput.Flush() - $header = [Text.StringBuilder]::new() - while (($value = $bytes.ReadByte()) -ne 10) { - if ($header.Length -ge 4096) { throw 'Invalid rule provenance response.' } - [void]$header.Append([char]$value) +# `pwsh -File` from another shell passes `a,b` as one value; accept both forms. +$Paths, $Rules, $Tags = @($Paths, $Rules, $Tags | ForEach-Object { , @($_ -split ',' | ForEach-Object Trim | Where-Object { $_ }) }) + +function ConvertTo-PathPattern([string]$glob, [string]$owner) { + # Globs are repository-relative and match the whole path: `**/` spans directories, `*` stays inside one name. + if ($glob -cnotmatch '^[^/\\][^\\]*$' -or $glob -cmatch '(^|/)\.\.?(/|$)') { throw "Rule path is not a repository-relative glob: $owner -> $glob" } + $pattern = [regex]::Escape($glob).Replace('\*\*/', '(?:.*/)?').Replace('\*\*', '.*').Replace('\*', '[^/]*') + return [regex]::new('^' + $pattern + '$') +} +function Read-Rules([string]$root, [string]$prefix) { + $ruleRoot = Join-Path $root '.agents/rulebook' + $index = Join-Path $ruleRoot 'README.md' + foreach ($file in Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse | Sort-Object FullName) { + if ($file.FullName -ceq $index) { continue } + $relative = [IO.Path]::GetRelativePath($ruleRoot, $file.FullName).Replace('\', '/') + $id = $prefix + $relative.Substring(0, $relative.Length - 3) + $text = (Get-Content -LiteralPath $file.FullName -Raw).Replace("`r`n", "`n") + $header = [regex]::Match($text, '\A---\n((?:[a-z]+: \[[^\]\n]*\]\n)+)---\n') + if (-not $header.Success) { throw "Rule file needs front matter with paths or tags: $id" } + $fields = @{ paths = @(); tags = @() } + foreach ($line in $header.Groups[1].Value.TrimEnd("`n") -split "`n") { + $key, $list = $line -split ': ', 2 + if (-not $fields.ContainsKey($key) -or $fields[$key].Count) { throw "Unknown or repeated front matter field: $id -> $key" } + $fields[$key] = @($list.Trim('[', ']') -split ',' | ForEach-Object { $_.Trim().Trim('"') }) + if (-not $fields[$key].Count -or $fields[$key] -contains '') { throw "Empty front matter value: $id -> $key" } } - $match = [regex]::Match($header.ToString(), '^[a-f0-9]{40} blob ([0-9]+)$') - if (-not $match.Success) { throw "Unavailable rule source: $identity" } - $length = [long]::Parse($match.Groups[1].Value) - if ($length -gt 16777216) { throw "Rule provenance exceeds the bounded source size: $identity" } - $content = $bytes.ReadBytes([int]$length) - if ($content.Length -ne $length -or $bytes.ReadByte() -ne 10) { throw "Incomplete rule source: $identity" } - $sources[$identity] = [Text.UTF8Encoding]::new($false, $true).GetString($content).Replace("`r`n", "`n").TrimEnd([char]10) - } - $sourceReader.StandardInput.Close() - $sourceReader.WaitForExit() - $diagnostic = $sourceErrors.GetAwaiter().GetResult() - if ($sourceReader.ExitCode -ne 0) { throw "Cannot read immutable rule provenance: $diagnostic" } -} finally { - if ($sourceStarted -and -not $sourceReader.HasExited) { $sourceReader.Kill(); $sourceReader.WaitForExit() } - if ($bytes) { $bytes.Dispose() } - $sourceReader.Dispose() -} -function Read-Source([string]$identity) { - if (-not $sources.ContainsKey($identity)) { throw "Unavailable rule source: $identity" } - return $sources[$identity] -} -function Get-Hash([string]$value) { - return [Convert]::ToHexStringLower([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($value))) -} -function Normalize-Links([string]$value) { - # Relocated link destinations do not change their labels or surrounding requirements. - return [regex]::Replace($value.Replace("`r`n", "`n").Trim(), '(\]\()[^)]+(\))', '$1$2') -} -function Get-RuleLines([string]$value) { - # Every nonblank line participates, including headings, examples and nested requirements. - return @($value.Replace("`r`n", "`n").Trim() -split "`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -} -function Normalize-RuleLine([string]$value) { - # Indentation expresses nested Markdown obligations and code examples; preserve it. - return [regex]::Replace($value, '(\]\()[^)]+(\))', '$1$2') -} -function Test-Translation($unit, [string]$source, [string]$target) { - $translation = $unit.translation - if ($translation.language -cne 'en' -or [string]::IsNullOrWhiteSpace($translation.approval) -or - [string]::IsNullOrWhiteSpace($translation.review)) { throw "Incomplete translation review: $($unit.id)" } - $reviewRoot = [IO.Path]::GetFullPath('.agents/records/', $repository) - $reviewPath = [IO.Path]::GetFullPath(($translation.review -split '#')[0], $repository) - if (-not $reviewPath.StartsWith($reviewRoot, [StringComparison]::Ordinal) -or - -not (Test-Path -LiteralPath $reviewPath -PathType Leaf)) { throw "Missing translation review: $($unit.id)" } - $sourceLines = @(Get-RuleLines $source) - $targetLines = @(Get-RuleLines $target) - if ($translation.lines.Count -ne $sourceLines.Count -or $targetLines.Count -ne $sourceLines.Count) { - throw "Incomplete translation coverage: $($unit.id)" - } - for ($index = 0; $index -lt $sourceLines.Count; $index++) { - $line = $translation.lines[$index] - $targetHash = $line.targetHash - $amendments = @($translation.amendments | Where-Object { $null -ne $_ -and $_.ordinal -eq $index + 1 }) - if ($amendments.Count -gt 1) { throw "Duplicate approved rule amendment: $($unit.id)" } - if ($amendments.Count -eq 1) { - $amendment = $amendments[0] - if ([string]::IsNullOrWhiteSpace($amendment.approval) -or $amendment.previousHash -cne $line.targetHash -or - $amendment.currentHash -cnotmatch '^[a-f0-9]{64}$' -or [string]::IsNullOrWhiteSpace($amendment.review)) { - throw "Invalid approved rule amendment: $($unit.id)" - } - $amendmentReview = [IO.Path]::GetFullPath($amendment.review, $repository) - if (-not $amendmentReview.StartsWith($reviewRoot, [StringComparison]::Ordinal) -or - -not (Test-Path -LiteralPath $amendmentReview -PathType Leaf)) { throw "Missing amendment review: $($unit.id)" } - $targetHash = $amendment.currentHash - } - if ($line.ordinal -ne $index + 1 -or $line.sourceHash -cne (Get-Hash (Normalize-RuleLine $sourceLines[$index])) -or - $targetHash -cne (Get-Hash (Normalize-RuleLine $targetLines[$index]))) { - throw "Changed or unmapped translation clause: $($unit.id) line $($index + 1)" - } - } - foreach ($amendment in $translation.amendments) { - if ($null -ne $amendment -and ($amendment.ordinal -lt 1 -or $amendment.ordinal -gt $sourceLines.Count)) { - throw "Unmapped approved rule amendment: $($unit.id)" - } - } -} -$units = @{}; $bodies = @{}; $external = @{} -function Resolve-Authority($unit) { - $ownerRoot = $repository - if ($unit.PSObject.Properties.Name -contains 'repository') { - if ($unit.repository -cne 'Wolfiora/InnoEngine.Docs') { throw "Unknown rule repository: $($unit.id)" } - $external[$unit.id] = $true - if ($DocsRoot) { $ownerRoot = [IO.Path]::GetFullPath($DocsRoot) } - } - $ownerRules = [IO.Path]::GetFullPath('.agents/rulebook/', $ownerRoot) - $destination = [IO.Path]::GetFullPath($unit.path, $ownerRoot) - if (-not $destination.StartsWith($ownerRules, [StringComparison]::Ordinal)) { throw "Rule path escapes owner: $($unit.id)" } - if ($external.ContainsKey($unit.id) -and -not $DocsRoot) { return $null } - $currentPath = $destination - while ($currentPath -and $currentPath.Length -ge $ownerRoot.Length) { - if (Test-Path -LiteralPath $currentPath) { - if ((Get-Item -LiteralPath $currentPath -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Rule authority cannot traverse a link: $($unit.id)" } - } - $currentPath = Split-Path $currentPath -Parent - } - return $destination -} -foreach ($unit in $manifest.units) { - if ($units.ContainsKey($unit.id)) { throw "Duplicate rule unit: $($unit.id)" } - $destination = Resolve-Authority $unit - $source = Read-Source $unit.source - if ($unit.PSObject.Properties.Name -contains 'sourceSection') { $source = [regex]::Split($source, '(?m)(?=^## )')[$unit.sourceSection] } - if ((Get-Hash $source.Trim()) -cne $unit.sourceHash) { throw "Changed source identity: $($unit.id)" } - foreach ($replacement in $manifest.pathReplacements) { $source = $source.Replace($replacement.old, $replacement.current) } - if ($null -eq $destination) { - $sourceLines = @(Get-RuleLines $source) - if ($unit.translation.language -cne 'en' -or [string]::IsNullOrWhiteSpace($unit.translation.approval) -or - $unit.translation.lines.Count -ne $sourceLines.Count) { throw "External rule source mapping is incomplete: $($unit.id)" } - for ($index = 0; $index -lt $sourceLines.Count; $index++) { - $line = $unit.translation.lines[$index] - if ($line.ordinal -ne $index + 1 -or $line.sourceHash -cne (Get-Hash (Normalize-RuleLine $sourceLines[$index])) -or - $line.targetHash -cnotmatch '^[a-f0-9]{64}$') { throw "Invalid external rule source clause: $($unit.id)" } - } - $units[$unit.id] = $unit - continue - } - $text = Get-Content -LiteralPath $destination -Raw - $pattern = '(?s)\s*\s*(.*?)\s*' - $matches = [regex]::Matches($text, $pattern) - if ($matches.Count -ne 1) { throw "Missing or repeated complete rule unit: $($unit.id)" } - $body = $matches[0].Groups[1].Value - $preservedBody = $body - if ($unit.PSObject.Properties.Name -contains 'approvedAddition') { - $parts = [regex]::Split($body, '(?m)^\r?$') - if ($parts.Count -ne 2 -or [string]::IsNullOrWhiteSpace($parts[1]) -or - [string]::IsNullOrWhiteSpace($unit.approvedAddition.approval)) { - throw "Invalid approved rule addition: $($unit.id)" - } - if ($unit.approvedAddition.PSObject.Properties.Name -contains 'translation') { - $additionOriginal = Read-Source $unit.approvedAddition.translation.source - $additionOriginal = [regex]::Match($additionOriginal, $pattern).Groups[1].Value - $additionParts = [regex]::Split($additionOriginal, '(?m)^\r?$') - if ($additionParts.Count -ne 2 -or (Get-Hash $additionParts[1].Replace("`r`n", "`n").Trim()) -cne $unit.approvedAddition.hash) { - throw "Invalid approved addition source: $($unit.id)" - } - Test-Translation @{ id = $unit.id + '/addition'; translation = $unit.approvedAddition.translation } $additionParts[1] $parts[1] - } elseif ((Get-Hash $parts[1].Replace("`r`n", "`n").Trim()) -cne $unit.approvedAddition.hash) { - throw "Invalid approved rule addition: $($unit.id)" + foreach ($tag in $fields.tags) { if ($tag -cnotmatch '^[a-z0-9-]+$') { throw "Invalid rule tag: $id -> $tag" } } + $size = [Text.Encoding]::UTF8.GetByteCount($text) + if ($size -gt $fileBudget) { throw "Rule file exceeds $fileBudget bytes; split it by topic: $id" } + [pscustomobject]@{ + id = $id; root = $root; file = $file.FullName; bytes = $size; tags = $fields.tags + patterns = @($fields.paths | ForEach-Object { ConvertTo-PathPattern $_ $id }) } - $preservedBody = $parts[0] } - if ($unit.PSObject.Properties.Name -contains 'translation') { - Test-Translation $unit $source $preservedBody - } elseif ((Normalize-Links $preservedBody) -cne (Normalize-Links $source)) { throw "Lost nested requirements, examples or prose: $($unit.id)" } - $units[$unit.id] = $unit; $bodies[$unit.id] = $body } -$original = Read-Source "$($manifest.baseline):AGENTS.md" + +$rootBytes = [Text.Encoding]::UTF8.GetByteCount((Get-Content -LiteralPath (Join-Path $repository 'AGENTS.md') -Raw)) +if ($rootBytes -gt $rootBudget) { throw "Root instructions exceed $rootBudget bytes." } +$catalog = @(Read-Rules $repository '') +$docs = $null if ($DocsRoot) { - foreach ($path in @($manifest.units | Where-Object repository | ForEach-Object path | Sort-Object -Unique)) { - foreach ($marker in [regex]::Matches([IO.File]::ReadAllText((Join-Path $DocsRoot $path)), '')) { - $id = $marker.Groups[1].Value - if (-not $external.ContainsKey($id) -or $units[$id].path -cne $path) { throw "Unregistered external rule authority: $id" } + $docs = (Resolve-Path -LiteralPath $DocsRoot).Path + $catalog += @(Read-Rules $docs 'docs/') +} +function Select-ByPath([string]$path) { + $full = [IO.Path]::GetFullPath($path, $repository) + $owner = if ($docs -and $full.StartsWith($docs + [IO.Path]::DirectorySeparatorChar, [StringComparison]::Ordinal)) { $docs } else { $repository } + $relative = [IO.Path]::GetRelativePath($owner, $full).Replace('\', '/') + if ($relative -cmatch '^\.\.(/|$)') { throw "Path is outside the repository: $path" } + foreach ($rule in $catalog) { + if ($rule.root -ceq $owner -and @($rule.patterns | Where-Object { $_.IsMatch($relative) }).Count) { [pscustomobject]@{ rule = $rule; reason = "path: $relative" } } + } +} + +$examplesPath = Join-Path $PSScriptRoot 'Test-AgentRules.examples.json' +if (Test-Path -LiteralPath $examplesPath) { + foreach ($example in Get-Content -LiteralPath $examplesPath -Raw | ConvertFrom-Json) { + $actual = @(Select-ByPath $example.path | ForEach-Object { $_.rule.id }) + foreach ($id in @($example.includes) + @($example.excludes)) { + if ($id -and -not @($catalog | Where-Object id -CEQ $id).Count) { throw "Routing example names an unknown rule: $id" } } - } -} -foreach ($file in Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse) { - if ($file.Name -cne 'README.md' -and -not @($manifest.units | Where-Object { -not $_.repository -and [IO.Path]::GetFullPath($_.path, $repository) -ceq $file.FullName }).Count) { - throw "Unregistered rule file: $($file.FullName)" - } - foreach ($marker in [regex]::Matches((Get-Content -LiteralPath $file.FullName -Raw), '')) { - $id = $marker.Groups[1].Value - if (-not $units.ContainsKey($id) -or $units[$id].repository -or [IO.Path]::GetFullPath($units[$id].path, $repository) -cne $file.FullName) { - throw "Unregistered rule unit or authority: $id in $($file.FullName)" - } - } -} -$count = 0 -foreach ($section in [regex]::Matches($original, '(?ms)^## (\d+)\. .*?(?=^## \d+\. |\z)')) { - $number = [int]$section.Groups[1].Value; $ordinal = 0 - foreach ($bullet in [regex]::Matches($section.Value, '(?m)^- .*')) { - $ordinal++; $id = "$number.$ordinal" - $rows = @($manifest.rules | Where-Object id -CEQ $id) - if ($rows.Count -ne 1) { throw "Missing or duplicate rule mapping: $id" } - $row = $rows[0] - if ($row.originalHash -cne (Get-Hash $bullet.Value) -or -not $row.check -or -not $row.reviewer) { throw "Invalid provenance or responsibility: $id" } - if (-not $units.ContainsKey($row.unit) -or $units[$row.unit].path -cne $row.path -or $units[$row.unit].repository -cne $row.repository) { throw "Rule has no unique authority: $id" } - $expected = $bullet.Value - foreach ($replacement in $manifest.pathReplacements) { $expected = $expected.Replace($replacement.old, $replacement.current) } - if ($row.disposition -eq 'preserved') { - if ($units[$row.unit].PSObject.Properties.Name -contains 'translation') { - $mapping = @($units[$row.unit].translation.lines | Where-Object sourceHash -CEQ (Get-Hash (Normalize-RuleLine $expected))) - if ($mapping.Count -ne 1 -or $row.translatedHash -cne $mapping[0].targetHash) { throw "Rule translation was lost: $id" } - } elseif (-not (Normalize-Links $bodies[$row.unit]).Contains((Normalize-Links $expected), [StringComparison]::Ordinal)) { throw "Rule was lost: $id" } - } elseif ($number -ne 8 -or $row.disposition -ne 'superseded-by-approved-plan') { throw "Unapproved replacement: $id" } - $count++ - } -} -if ($count -ne $manifest.rules.Count) { throw 'Unknown baseline rule mappings.' } -$selected = @{} -$active = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) -$checked = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) -function Check-Dependencies([string]$id) { - if (-not $units.ContainsKey($id)) { throw "Unknown rule: $id" } - if ($checked.Contains($id)) { return } - if (-not $active.Add($id)) { throw "Cyclic rule dependency: $id" } - foreach ($dependency in $units[$id].requires) { Check-Dependencies $dependency } - [void]$active.Remove($id); [void]$checked.Add($id) -} -foreach ($id in $units.Keys) { Check-Dependencies $id } -foreach ($route in $manifest.routes) { - [void][regex]::new($route.pattern) - foreach ($id in $route.units) { - if (-not $units.ContainsKey($id)) { throw "Unknown routed rule: $id" } - } -} -function Select-Unit([string]$id, [string]$reason) { - if (-not $units.ContainsKey($id)) { throw "Unknown rule: $id" } - if ($selected.ContainsKey($id)) { $selected[$id].Add($reason); return } - $selected[$id] = [Collections.Generic.List[string]]::new(); $selected[$id].Add($reason) - foreach ($dependency in $units[$id].requires) { Select-Unit $dependency "required by $id" } -} -foreach ($id in $Rules) { Select-Unit $id 'explicit rule' } -foreach ($tag in $Behaviors) { - $matches = @($manifest.units | Where-Object { $tag -cin $_.tags }) - if ($matches.Count -eq 0) { throw "Unknown behavior: $tag" } - foreach ($unit in $matches) { Select-Unit $unit.id "behavior: $tag" } -} -foreach ($path in $Paths) { - $normalized = $path.Replace('\', '/') - if ([IO.Path]::IsPathRooted($path)) { $normalized = [IO.Path]::GetRelativePath($repository, $path).Replace('\', '/') } - foreach ($route in $manifest.routes) { - if ($normalized -match $route.pattern) { foreach ($id in $route.units) { Select-Unit $id "path: $normalized" } } - } -} -foreach ($file in @((Join-Path $repository 'AGENTS.md')) + @(Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse | ForEach-Object FullName)) { - foreach ($link in [regex]::Matches((Get-Content -LiteralPath $file -Raw), '\]\(([^)#]+)(?:#[^)]*)?\)')) { - $target = $link.Groups[1].Value - if ($target -match '^[a-z]+:') { continue } - if (-not (Test-Path -LiteralPath ([IO.Path]::GetFullPath($target, (Split-Path $file))))) { throw "Broken instruction link: $file -> $target" } - } -} -$stages = [Collections.Generic.List[object]]::new() -$current = [Collections.Generic.List[string]]::new(); $bytes = $rootBytes -foreach ($id in ($selected.Keys | Sort-Object)) { - if (-not $bodies.ContainsKey($id)) { throw "Selected rule $id belongs to Wolfiora/InnoEngine.Docs. Supply -DocsRoot with the explicitly selected checkout; no network fetch or sibling-path guess is performed." } - $size = [Text.Encoding]::UTF8.GetByteCount($bodies[$id]) - if ($size + $rootBytes -gt $manifest.taskBudgetBytes) { throw "Unit $id needs smaller complete subchapters; truncation is forbidden." } - if ($bytes + $size -gt $manifest.taskBudgetBytes) { - $stages.Add(@{ ids = $current.ToArray(); bytes = $bytes }); $current.Clear(); $bytes = $rootBytes - } - $current.Add($id); $bytes += $size -} -$stages.Add(@{ ids = $current.ToArray(); bytes = $bytes }) -if ($Stage -lt 0 -or $Stage -gt $stages.Count) { throw 'Invalid instruction stage.' } -Write-Output "Preserved mapping: $count rules; $($units.Count) complete units. Root: $rootBytes bytes. Stages: $($stages.Count)." -if ($external.Count -gt 0) { - if ($DocsRoot) { Write-Output "External authority verified: $($external.Count) complete units in $([IO.Path]::GetFullPath($DocsRoot))." } - else { Write-Output "External authority not read: $($external.Count) source mappings only. Documentation work requires -DocsRoot; this result certifies engine-owned rule bodies only." } -} -for ($index = 0; $index -lt $stages.Count; $index++) { - $entry = $stages[$index] - Write-Output "Stage $($index + 1): $($entry.bytes) bytes; units: $($entry.ids -join ', ')" - foreach ($id in $entry.ids) { Write-Output "$id | $($units[$id].repository)/$($units[$id].path)#$id | source: $($units[$id].source) | $($selected[$id] -join '; ')" } - if ($ShowInstructions -and ($Stage -eq 0 -or $Stage -eq $index + 1)) { - Write-Output $rootText - foreach ($id in $entry.ids) { Write-Output $bodies[$id] } + foreach ($id in $example.includes) { if ($id -cnotin $actual) { throw "Routing example failed: $($example.path) must select $id" } } + foreach ($id in $example.excludes) { if ($id -cin $actual) { throw "Routing example failed: $($example.path) must not select $id" } } + } +} + +$selected = [ordered]@{} +function Add-Selection($rule, [string]$reason) { + if (-not $selected.Contains($rule.id)) { $selected[$rule.id] = @{ rule = $rule; reasons = [Collections.Generic.List[string]]::new() } } + $selected[$rule.id].reasons.Add($reason) +} +foreach ($id in $Rules) { + $rule = @($catalog | Where-Object id -CEQ $id) + if (-not $rule.Count) { throw "Unknown rule: $id" } + Add-Selection $rule[0] 'explicit rule' +} +foreach ($tag in $Tags) { + $tagged = @($catalog | Where-Object { $tag -cin $_.tags }) + if (-not $tagged.Count) { throw "Unknown tag: $tag" } + foreach ($rule in $tagged) { Add-Selection $rule "tag: $tag" } +} +foreach ($path in $Paths) { foreach ($match in Select-ByPath $path) { Add-Selection $match.rule $match.reason } } + +Write-Output "Rules are valid: $($catalog.Count) files. Root: $rootBytes bytes." +if ($selected.Count) { + $total = ($selected.Values | ForEach-Object { $_.rule.bytes } | Measure-Object -Sum).Sum + Write-Output "Read each file completely: $($selected.Count) files, $total bytes." + foreach ($entry in $selected.Values) { + $shown = if ($entry.rule.root -ceq $repository) { [IO.Path]::GetRelativePath($repository, $entry.rule.file).Replace('\', '/') } else { $entry.rule.file } + Write-Output "$shown | $(@($entry.reasons | Select-Object -Unique) -join '; ')" } } diff --git a/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs b/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs index 9a9a82005..56771fba6 100644 --- a/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs +++ b/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs @@ -5,13 +5,13 @@ namespace Inno.Content.Tests; public sealed class ContentPackIndexTests { - private static readonly string Hash = new('A', 64); + private static readonly string HASH = new('A', 64); [Fact] public void IndexCopiesSortsAndRejectsCollisionsAndFileDirectoryConflicts() { ContentEntry[] entries = [Entry("b/file", 2), Entry("a", 1)]; - ContentPackIndex index = new(entries); + var index = new ContentPackIndex(entries); entries[0] = Entry("changed", 7); Assert.Equal("a", index.entries[0].key.value); Assert.Equal(3, index.totalLength); @@ -23,5 +23,5 @@ public void IndexCopiesSortsAndRejectsCollisionsAndFileDirectoryConflicts() private static ContentEntry Entry( string key, long length - ) => new(new ContentKey(key), length, Hash); + ) => new(new ContentKey(key), length, HASH); } diff --git a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs index 1cd2fd605..8d145130a 100644 --- a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs +++ b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs @@ -4,10 +4,11 @@ using System.IO.Compression; using System.Linq; using System.Security.Cryptography; +using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Core.Serialization; using Inno.Runtime; -using Xunit; namespace Inno.Content.Tests; @@ -20,8 +21,10 @@ public async Task IndependentReadersRetainPackAfterStoreAndLeaseClose() using SerializationGeneration generation = host.serialization.CaptureGeneration(); byte[] firstBytes = Enumerable.Range(0, 100_000).Select(static value => (byte)value).ToArray(); byte[] secondBytes = Enumerable.Range(0, 90_000).Select(static value => (byte)(value * 7)).ToArray(); - (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack(generation, - new Dictionary { ["a"] = firstBytes, ["b"] = secondBytes }); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = firstBytes, ["b"] = secondBytes } + ); PackContentStore store = ContentPackReader.Open(pack, descriptor, generation); ContentReadLease first = store.Acquire(new ContentKey("a")); ContentReadLease second = store.Acquire(new ContentKey("b")); @@ -31,8 +34,10 @@ public async Task IndependentReadersRetainPackAfterStoreAndLeaseClose() store.Dispose(); Assert.Throws(() => store.Acquire(new ContentKey("a"))); Assert.Throws(() => first.OpenRead()); - await Task.WhenAll(Task.Run(() => Assert.Equal(firstBytes, Read(inputA))), - Task.Run(() => Assert.Equal(secondBytes, Read(inputB)))); + await Task.WhenAll( + Task.Run(() => Assert.Equal(firstBytes, Read(inputA))), + Task.Run(() => Assert.Equal(secondBytes, Read(inputB))) + ); using Stream anotherB = second.OpenRead(); Assert.Equal(secondBytes, Read(anotherB)); second.Dispose(); @@ -55,8 +60,11 @@ public void MalformedPacksAreRejectedAndTheirInputIsDisposed(string fault) { using EngineHost host = CreateHost(); using SerializationGeneration generation = host.serialization.CaptureGeneration(); - (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack(generation, - new Dictionary { ["a"] = [1, 2, 3] }, fault); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [1, 2, 3] }, + fault + ); Assert.Throws(() => ContentPackReader.Open(pack, descriptor, generation)); Assert.False(pack.CanRead); } @@ -66,18 +74,35 @@ public void BudgetsAndCancellationPrecedeStorePublication() { using EngineHost host = CreateHost(); using SerializationGeneration generation = host.serialization.CaptureGeneration(); - var (pack, descriptor) = CreatePack(generation, new Dictionary { ["a"] = [1, 2, 3] }); - Assert.Throws(() => ContentPackReader.Open(pack, descriptor, generation, - new ContentReadLimits(entryBytes: 2))); - var (canceled, canceledDescriptor) = CreatePack(generation, new Dictionary { ["a"] = [] }); - Assert.Throws(() => ContentPackReader.Open(canceled, canceledDescriptor, generation, - cancellationToken: new System.Threading.CancellationToken(true))); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [1, 2, 3] } + ); + Assert.Throws(() => ContentPackReader.Open( + pack, + descriptor, + generation, + new ContentReadLimits(entryBytes: 2) + )); + (MemoryStream canceled, ContentPackDescriptor canceledDescriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [] } + ); + Assert.Throws(() => ContentPackReader.Open( + canceled, + canceledDescriptor, + generation, + cancellationToken: new CancellationToken(true) + )); Assert.False(canceled.CanRead); } - internal static EngineHost CreateHost() => new EngineHostBuilder().UseMetadataSources( - new StaticAssemblyCatalogSource([], [typeof(object).Assembly]), new StaticTypeCatalogSource([]), - new StaticSerializationMetadataSource([])).Build(); + internal static EngineHost CreateHost() + => new EngineHostBuilder().UseMetadataSources( + new StaticAssemblyCatalogSource([], [typeof(object).Assembly]), + new StaticTypeCatalogSource([]), + new StaticSerializationMetadataSource([]) + ).Build(); internal static ( MemoryStream pack, @@ -87,20 +112,26 @@ ContentPackDescriptor descriptor Dictionary payloads, string fault = "" ) { - List entries = payloads.Select(pair => new ContentEntry(new ContentKey(pair.Key), + List entries = payloads.Select(pair => new ContentEntry( + new ContentKey(pair.Key), pair.Value.Length + (fault == "length" ? 1 : 0), - fault == "payload" ? new string('A', 64) : Convert.ToHexString(SHA256.HashData(pair.Value)))).ToList(); - MemoryStream output = new(); - using (ZipArchive archive = new(output, ZipArchiveMode.Create, true)) + fault == "payload" ? new string('A', 64) : Convert.ToHexString(SHA256.HashData(pair.Value)) + )).ToList(); + var output = new MemoryStream(); + using (var archive = new ZipArchive(output, ZipArchiveMode.Create, true)) { - foreach (var pair in payloads) + foreach (KeyValuePair pair in payloads) { if (fault == "missing") + { continue; + } string name = fault == "traversal" ? "../a" : pair.Key; ZipArchiveEntry entry = archive.CreateEntry(name); if (fault == "link") + { entry.ExternalAttributes = 0xA000 << 16; + } using Stream destination = entry.Open(); destination.Write(pair.Value); } @@ -119,7 +150,7 @@ ContentPackDescriptor descriptor private static byte[] Read(Stream input) { - using MemoryStream output = new(); + using var output = new MemoryStream(); input.CopyTo(output, 137); return output.ToArray(); } diff --git a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs index 218e38ac3..bbedff474 100644 --- a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs +++ b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs @@ -14,16 +14,22 @@ private static async Task Main(string[] arguments) using ContentTestStore source = ContentTestStore.FromDirectory(arguments[0]); Console.WriteLine("ready"); if (await Console.In.ReadLineAsync() != "prepare") + { return 2; - using FileContentStore store = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(arguments[1])); + } + using FileContentStore store = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(arguments[1]) + ); using ContentReadLease lease = store.Acquire(new ContentKey("pinned.bin")); using Stream reader = lease.OpenRead(); string cache = Path.Combine(arguments[1], "Content", source.descriptor.contentHash); Console.WriteLine(File.ReadAllText(Path.Combine(cache, "current"))); if (await Console.In.ReadLineAsync() != "release") + { return 3; - byte[] bytes = new byte[checked((int)lease.entry.length)]; + } + var bytes = new byte[checked((int)lease.entry.length)]; reader.ReadExactly(bytes); Console.WriteLine(Convert.ToHexString(bytes)); return 0; diff --git a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs index 61053e1c7..50a850afc 100644 --- a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs +++ b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs @@ -24,34 +24,27 @@ public sealed class ContentTestStore : IRuntimeContentStore public ContentTestStore(IEnumerable> payloads) { m_payloads = payloads.ToDictionary(static pair => pair.Key, static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex(m_payloads.Select(static pair => new ContentEntry( - pair.Key, pair.Value.LongLength, Convert.ToHexString(SHA256.HashData(pair.Value))))); - string identity = string.Join('\n', index.entries.Select(static entry => - entry.key + ":" + entry.length + ":" + entry.contentHash)); + this.index = new ContentPackIndex( + m_payloads.Select(static pair => new ContentEntry( + pair.Key, + pair.Value.LongLength, + Convert.ToHexString(SHA256.HashData(pair.Value)) + )) + ); + string identity = string.Join( + '\n', + index.entries.Select(static entry => (entry.key + ":" + entry.length + ":" + entry.contentHash)) + ); string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))); - descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); + this.descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } - /// - /// Captures a test's exported directory as independently owned memory content. - /// - /// - /// The fixture output directory; the returned store does not retain its location. - /// - /// - /// A caller-owned memory provider usable after the directory has been removed. - /// - public static ContentTestStore FromDirectory(string directory) - => new(Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).Select(path => - new KeyValuePair(new ContentKey(Path.GetRelativePath(directory, path) - .Replace('\\', '/')), File.ReadAllBytes(path)))); - /// /// Injects a provider corruption while preserving its previously declared inventory. /// @@ -67,24 +60,46 @@ ReadOnlySpan bytes ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_payloads.ContainsKey(key)) + { throw new KeyNotFoundException(key.ToString()); + } m_payloads[key] = bytes.ToArray(); } - /// + /// public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new KeyNotFoundException(key.ToString()); + } byte[] bytes = m_payloads[key]; - return new ContentReadLease(entry!, () => new MemoryStream(bytes, writable: false), static () => { }); + return new ContentReadLease(entry!, () => new MemoryStream(bytes, writable: false), static () => {}); } - /// + /// public void Dispose() { m_disposed = true; m_payloads.Clear(); } + + /// + /// Captures a test's exported directory as independently owned memory content. + /// + /// + /// The fixture output directory; the returned store does not retain its location. + /// + /// + /// A caller-owned memory provider usable after the directory has been removed. + /// + public static ContentTestStore FromDirectory(string directory) + => new( + Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).Select(path => + new KeyValuePair( + new ContentKey(Path.GetRelativePath(directory, path).Replace('\\', '/')), + File.ReadAllBytes(path) + )) + ); } diff --git a/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs b/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs index 0ab73a7c5..15bd5013d 100644 --- a/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs +++ b/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs @@ -2,17 +2,15 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - -using Inno.Core.Collections; - using Xunit; +using Inno.Core.Collections; namespace Inno.Core.Collections.Tests; public sealed class DependencyGraphTests { [Fact] - public void NodesAndEdges_AreIdempotentAndVersionOnlyTracksChanges() + public void NodesAndEdgesAreIdempotentAndVersionOnlyTracksChanges() { var graph = new DependencyGraph(); Assert.True(graph.AddNode("A")); @@ -27,7 +25,7 @@ public void NodesAndEdges_AreIdempotentAndVersionOnlyTracksChanges() } [Fact] - public void ReplaceDependencies_UpdatesForwardAndReverseEdgesAtomically() + public void ReplaceDependenciesUpdatesForwardAndReverseEdgesAtomically() { var graph = new DependencyGraph(); graph.ReplaceDependencies("Root", ["A", "B"]); @@ -43,7 +41,7 @@ public void ReplaceDependencies_UpdatesForwardAndReverseEdgesAtomically() } [Fact] - public void RemoveNode_RemovesAllIncomingAndOutgoingEdges() + public void RemoveNodeRemovesAllIncomingAndOutgoingEdges() { var graph = new DependencyGraph(); graph.AddDependency("C", "B"); @@ -58,7 +56,7 @@ public void RemoveNode_RemovesAllIncomingAndOutgoingEdges() } [Fact] - public void RecursiveQueries_ReturnDeterministicTransitiveSnapshots() + public void RecursiveQueriesReturnDeterministicTransitiveSnapshots() { var graph = new DependencyGraph(); graph.AddDependency("D", "B"); @@ -74,7 +72,7 @@ public void RecursiveQueries_ReturnDeterministicTransitiveSnapshots() } [Fact] - public void TopologicalSort_PlacesEveryDependencyBeforeItsDependent() + public void TopologicalSortPlacesEveryDependencyBeforeItsDependent() { var graph = new DependencyGraph(); graph.AddDependency("C", "B"); @@ -87,7 +85,7 @@ public void TopologicalSort_PlacesEveryDependencyBeforeItsDependent() } [Fact] - public void OrderingComparer_ControlsStableQueryOrder() + public void OrderingComparerControlsStableQueryOrder() { var graph = new DependencyGraph(orderingComparer: StringComparer.Ordinal); graph.ReplaceDependencies("Root", ["Z", "A", "M"]); @@ -95,7 +93,7 @@ public void OrderingComparer_ControlsStableQueryOrder() } [Fact] - public void CycleDetection_ReturnsClosedCompleteCycleAndTopologicalSortReportsIt() + public void CycleDetectionReturnsClosedCompleteCycleAndTopologicalSortReportsIt() { var graph = new DependencyGraph(); graph.AddDependency("A", "B"); @@ -112,7 +110,7 @@ public void CycleDetection_ReturnsClosedCompleteCycleAndTopologicalSortReportsIt } [Fact] - public void SelfCycle_IsDetected() + public void SelfCycleIsDetected() { var graph = new DependencyGraph(); graph.AddDependency(7, 7); @@ -121,7 +119,7 @@ public void SelfCycle_IsDetected() } [Fact] - public void StronglyConnectedComponents_IncludeCyclesAndSingletons() + public void StronglyConnectedComponentsIncludeCyclesAndSingletons() { var graph = new DependencyGraph(); graph.AddDependency("A", "B"); @@ -135,7 +133,7 @@ public void StronglyConnectedComponents_IncludeCyclesAndSingletons() } [Fact] - public void Clear_RemovesAllStateAndOnlyChangesVersionWhenNeeded() + public void ClearRemovesAllStateAndOnlyChangesVersionWhenNeeded() { var graph = new DependencyGraph(); graph.AddDependency(2, 1); @@ -148,7 +146,7 @@ public void Clear_RemovesAllStateAndOnlyChangesVersionWhenNeeded() } [Fact] - public async Task ConcurrentReaders_ObserveOnlyCompleteSnapshots() + public async Task ConcurrentReadersObserveOnlyCompleteSnapshots() { var graph = new DependencyGraph(); graph.ReplaceDependencies(10, [1, 2, 3]); @@ -159,22 +157,29 @@ public async Task ConcurrentReaders_ObserveOnlyCompleteSnapshots() { IReadOnlyList dependencies = graph.GetDependencies(10); Assert.True( - dependencies.SequenceEqual(new[] { 1, 2, 3 }) || - dependencies.SequenceEqual(new[] { 4, 5, 6 })); + dependencies.SequenceEqual(new[] { 1, 2, 3 }) + || dependencies.SequenceEqual(new[] { 4, 5, 6 }) + ); } })) .ToArray(); for (int i = 0; i < 100; i++) + { graph.ReplaceDependencies(10, i % 2 == 0 ? [4, 5, 6] : [1, 2, 3]); + } await Task.WhenAll(readers); } - private static int IndexOf(IReadOnlyList values, string value) - { + private static int IndexOf( + IReadOnlyList values, + string value + ) { for (int i = 0; i < values.Count; i++) { if (values[i] == value) + { return i; + } } return -1; } diff --git a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs index a943014d1..91fcda6c1 100644 --- a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs +++ b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs @@ -1,29 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Core.Collections; - using Xunit; +using Inno.Core.Collections; namespace Inno.Core.Collections.Tests; public sealed class IndexedObjectStoreTests { - private sealed class Item - { - public string name { get; } - public int Category { get; } - - public Item(string name, int category) - { - this.name = name; - Category = category; - } - } - [Fact] - public void Add_Remove_Count_Clear() + public void AddRemoveCountClear() { var store = new IndexedObjectStore(); var a = new Item("A", 1); @@ -42,10 +28,10 @@ public void Add_Remove_Count_Clear() } [Fact] - public void DefineKey_UniqueAndLookup() + public void DefineKeyUniqueAndLookup() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); var b = new Item("B", 2); @@ -53,39 +39,38 @@ public void DefineKey_UniqueAndLookup() store.Add(a).Set(key, 10); store.Add(b).Set(key, 20); - var found = store.First(key, 20); + Item? found = store.First(key, 20); Assert.Same(b, found); - var all = store.Find(key, 10).ToList(); + List all = store.Find(key, 10).ToList(); Assert.Single(all); Assert.Same(a, all[0]); } [Fact] - public void DefineKey_Unique_ThrowsOnDuplicateValueFromDifferentItems() + public void DefineKeyUniqueThrowsOnDuplicateValueFromDifferentItems() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); var b = new Item("B", 2); store.Add(a).Set(key, 10); - InvalidOperationException ex = Assert.Throws(() => - store.Add(b).Set(key, 10)); + InvalidOperationException ex = Assert.Throws(() => store.Add(b).Set(key, 10)); Assert.Contains("Duplicate key", ex.Message); } [Fact] - public void DefineKey_Unique_AllowsResettingSameValueOnSameItem() + public void DefineKeyUniqueAllowsResettingSameValueOnSameItem() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); - + store.Add(a).Set(key, 10); store.Add(a).Set(key, 20); @@ -94,10 +79,10 @@ public void DefineKey_Unique_AllowsResettingSameValueOnSameItem() } [Fact] - public void DefineKey_MultiAndQuery() + public void DefineKeyMultiAndQuery() { var store = new IndexedObjectStore(); - var key = store.DefineKey("category", IndexedObjectKeyFlags.Unordered); + IndexedObjectKey key = store.DefineKey("category", IndexedObjectKeyFlags.Unordered); var a = new Item("A", 1); var b = new Item("B", 1); @@ -107,13 +92,13 @@ public void DefineKey_MultiAndQuery() store.Add(b).Set(key, 1); store.Add(c).Set(key, 2); - var results = store.Find(key, 1).ToList(); + List results = store.Find(key, 1).ToList(); Assert.Equal(2, results.Count); Assert.Contains(a, results); Assert.Contains(b, results); - var query = store.Query().Find(key, 2); - var single = query.First(); + IndexedObjectQuery query = store.Query().Find(key, 2); + Item? single = query.First(); Assert.Same(c, single); } @@ -125,7 +110,8 @@ public void OrderedQueryUsesSmallestIndexedCandidateSetAndReturnsAnIsolatedSnaps IndexedObjectKey orderKey = store.DefineKey( "order", IndexedObjectKeyFlags.Ordered | IndexedObjectKeyFlags.Unique, - Comparer.Default); + Comparer.Default + ); var unrelated = new Item("Unrelated", 2); var last = new Item("Last", 1); var excluded = new Item("Excluded", 1); @@ -175,15 +161,15 @@ public void OrderedQueryUsesSmallestIndexedCandidateSetAndReturnsAnIsolatedSnaps .OrderBy(orderKey) .GetFast() .ToArray(); - Assert.Equal(new[] { excluded, last }, fast); + Assert.Equal([excluded, last], fast); Assert.Equal(2, predicateCalls); } [Fact] - public void OrderBy_UsesSortedKey() + public void OrderByUsesSortedKey() { var store = new IndexedObjectStore(); - var key = store.DefineKey("ordered", IndexedObjectKeyFlags.Ordered, Comparer.Default); + IndexedObjectKey key = store.DefineKey("ordered", IndexedObjectKeyFlags.Ordered, Comparer.Default); var a = new Item("A", 1); var b = new Item("B", 1); @@ -193,7 +179,7 @@ public void OrderBy_UsesSortedKey() store.Add(b).Set(key, 1); store.Add(c).Set(key, 2); - var ordered = store.Query().OrderBy(key).Get().ToList(); + List ordered = store.Query().OrderBy(key).Get().ToList(); Assert.Equal(3, ordered.Count); Assert.Same(b, ordered[0]); Assert.Same(c, ordered[1]); @@ -201,10 +187,10 @@ public void OrderBy_UsesSortedKey() } [Fact] - public void RemoveKey_InvalidatesKey() + public void RemoveKeyInvalidatesKey() { var store = new IndexedObjectStore(); - var key = store.DefineKey("temp"); + IndexedObjectKey key = store.DefineKey("temp"); var item = new Item("A", 1); store.Add(item).Set(key, 1); @@ -215,10 +201,10 @@ public void RemoveKey_InvalidatesKey() } [Fact] - public void TryGetKey_ResolvesByName() + public void TryGetKeyResolvesByName() { var store = new IndexedObjectStore(); - var key = store.DefineKey("resolve"); + IndexedObjectKey key = store.DefineKey("resolve"); Assert.True(store.TryGetKey("resolve", out IndexedObjectKey resolved)); Assert.True(resolved.isValid); @@ -226,7 +212,7 @@ public void TryGetKey_ResolvesByName() } [Fact] - public void PredicateQuery_Works() + public void PredicateQueryWorks() { var store = new IndexedObjectStore(); var a = new Item("A", 1); @@ -235,8 +221,8 @@ public void PredicateQuery_Works() store.Add(a); store.Add(b); - var results = store.Query() - .Where(item => item.Category == 2) + List results = store.Query() + .Where(item => item.category == 2) .Get() .ToList(); @@ -245,13 +231,13 @@ public void PredicateQuery_Works() } [Fact] - public void GetFast_IsFailFast_WhenStoreMutates() + public void GetFastIsFailFastWhenStoreMutates() { var store = new IndexedObjectStore(); store.Add(new Item("A", 1)); store.Add(new Item("B", 2)); - using var enumerator = store.Query().GetFast().GetEnumerator(); + using IEnumerator enumerator = store.Query().GetFast().GetEnumerator(); Assert.True(enumerator.MoveNext()); store.Add(new Item("C", 3)); @@ -260,7 +246,7 @@ public void GetFast_IsFailFast_WhenStoreMutates() } [Fact] - public void Get_ReturnsStableSnapshot_WhenStoreMutates() + public void GetReturnsStableSnapshotWhenStoreMutates() { var store = new IndexedObjectStore(); var a = new Item("A", 1); @@ -277,10 +263,10 @@ public void Get_ReturnsStableSnapshot_WhenStoreMutates() } [Fact] - public void RemoveAll_KeepsKeys() + public void RemoveAllKeepsKeys() { var store = new IndexedObjectStore(); - var key = store.DefineKey("category"); + IndexedObjectKey key = store.DefineKey("category"); var a = new Item("A", 1); store.Add(a).Set(key, 1); @@ -291,7 +277,7 @@ public void RemoveAll_KeepsKeys() } [Fact] - public void All_ReturnsStableSnapshot_WhenStoreMutates() + public void AllReturnsStableSnapshotWhenStoreMutates() { var store = new IndexedObjectStore(); var a = new Item("A", 1); @@ -308,7 +294,7 @@ public void All_ReturnsStableSnapshot_WhenStoreMutates() } [Fact] - public void AllFast_ReturnsAllItems() + public void AllFastReturnsAllItems() { var store = new IndexedObjectStore(); var a = new Item("A", 1); @@ -327,13 +313,13 @@ public void AllFast_ReturnsAllItems() } [Fact] - public void AllFast_IsFailFast_WhenStoreMutates() + public void AllFastIsFailFastWhenStoreMutates() { var store = new IndexedObjectStore(); store.Add(new Item("A", 1)); store.Add(new Item("B", 2)); - using var enumerator = store.AllFast().GetEnumerator(); + using IEnumerator enumerator = store.AllFast().GetEnumerator(); Assert.True(enumerator.MoveNext()); store.Add(new Item("C", 3)); @@ -341,4 +327,17 @@ public void AllFast_IsFailFast_WhenStoreMutates() Assert.Throws(() => enumerator.MoveNext()); } + private sealed class Item + { + public Item( + string name, + int category + ) { + this.name = name; + this.category = category; + } + + public string name { get; } + public int category { get; } + } } diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs index ffd77f6a0..d5f3b33e6 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; - -using Inno.Core.Coroutines; - using Xunit; +using Inno.Core.Coroutines; namespace Inno.Core.Coroutines.Tests; @@ -19,7 +17,7 @@ public void EveryStopPathDisposesNestedEnumeratorsInReverseOrder(string stop) { using var scheduler = new CoroutineScheduler(); var owner = new object(); - var disposed = new List(); + List disposed = []; IEnumerator child = new Probe(() => true, () => null, () => disposed.Add("child")); IEnumerator root = new Probe(() => true, () => child, () => disposed.Add("root")); CoroutineHandle handle = scheduler.StartCoroutine(owner, root); @@ -53,7 +51,7 @@ public void EveryStopPathDisposesNestedEnumeratorsInReverseOrder(string stop) public void NormalCompletionDisposesChildBeforeResumingParent() { using var scheduler = new CoroutineScheduler(); - var order = new List(); + List order = []; var child = new Probe(() => false, () => null, () => order.Add("child")); scheduler.StartCoroutine(Root()); scheduler.Tick(0); @@ -82,12 +80,22 @@ public void PendingEnumeratorIsDisposedWithoutBeingAdvanced(bool ownerStop) var owner = new object(); int moves = 0; int disposed = 0; - CoroutineHandle handle = scheduler.StartCoroutine(owner, - new Probe(() => { moves++; return true; }, () => null, () => disposed++)); + CoroutineHandle handle = scheduler.StartCoroutine( + owner, + new Probe(() => + { + moves++; + return true; + }, () => null, () => disposed++) + ); if (ownerStop) + { scheduler.StopAllCoroutines(owner); + } else + { scheduler.Dispose(); + } Assert.False(handle.isValid); Assert.Equal(0, moves); Assert.Equal(1, disposed); @@ -103,13 +111,18 @@ public void CallbackFaultRetiresItsStackAndDoesNotSkipOtherCoroutines(string sta var failure = new InvalidOperationException(stage); int disposed = 0; int survivorTicks = 0; - CoroutineHandle failed = scheduler.StartCoroutine(new Probe( - () => stage == "move" ? throw failure : true, - () => stage == "current" ? throw failure : new WaitUntil(() => throw failure), - () => disposed++)); + CoroutineHandle failed = scheduler.StartCoroutine( + new Probe( + () => stage == "move" ? throw failure : true, + () => stage == "current" ? throw failure : new WaitUntil(() => throw failure), + () => disposed++ + ) + ); scheduler.StartCoroutine(Loop(() => survivorTicks++)); if (stage == "wait") + { scheduler.Tick(0); + } AggregateException error = Assert.Throws(() => scheduler.Tick(0)); Assert.Contains(failure, error.InnerExceptions); Assert.False(failed.isValid); @@ -125,15 +138,17 @@ public void CallbackFaultRetiresItsStackAndDoesNotSkipOtherCoroutines(string sta public void CleanupFailuresDoNotPreventParentOrOtherCoroutineCleanup(bool dispose) { using var scheduler = new CoroutineScheduler(); - var failures = new[] { new Exception("child"), new Exception("parent"), new Exception("other") }; - var cleaned = new List(); + Exception[] failures = [new Exception("child"), new Exception("parent"), new Exception("other")]; + List cleaned = []; var child = new Probe(() => true, () => null, () => Fail(0)); scheduler.StartCoroutine(new Probe(() => true, () => child, () => Fail(1))); scheduler.StartCoroutine(new Probe(() => true, () => null, () => Fail(2))); scheduler.Tick(0); AggregateException error; if (dispose) + { error = Assert.Throws(scheduler.Dispose); + } else { scheduler.StopAllCoroutines(); @@ -161,17 +176,25 @@ public void SelfOwnerStopDefersDisposeUntilMoveNextReturnsAndPreservesOtherCorou bool moving = false; int disposed = 0; int ticks = 0; - CoroutineHandle self = scheduler.StartCoroutine(owner, new Probe( - () => - { - moving = true; - scheduler.StopAllCoroutines(owner); - Assert.Equal(0, disposed); - moving = false; - return true; - }, - () => throw new Exception("A retired coroutine must not read Current."), - () => { Assert.False(moving); disposed++; })); + CoroutineHandle self = scheduler.StartCoroutine( + owner, + new Probe( + () => + { + moving = true; + scheduler.StopAllCoroutines(owner); + Assert.Equal(0, disposed); + moving = false; + return true; + }, + () => throw new Exception("A retired coroutine must not read Current."), + () => + { + Assert.False(moving); + disposed++; + } + ) + ); CoroutineHandle other = survivor ? scheduler.StartCoroutine(Loop(() => ticks++)) : default; scheduler.Tick(0); scheduler.Tick(0); @@ -187,7 +210,7 @@ public void StopEarlierOwnerDuringCallbackDoesNotSkipFollowingCoroutine() using var scheduler = new CoroutineScheduler(); var owner = new object(); int following = 0; - scheduler.StartCoroutine(owner, Loop(() => { })); + scheduler.StartCoroutine(owner, Loop(() => {})); scheduler.StartCoroutine(Loop(() => scheduler.StopAllCoroutines(owner))); scheduler.StartCoroutine(Loop(() => following++)); scheduler.Tick(0); @@ -201,10 +224,24 @@ public void ReentrantDisposeRetiresExecutingEnumeratorAfterItsCallback() using var scheduler = new CoroutineScheduler(); bool moving = false; int disposed = 0; - scheduler.StartCoroutine(new Probe( - () => { moving = true; scheduler.Dispose(); Assert.Equal(0, disposed); moving = false; return true; }, - () => null, - () => { Assert.False(moving); disposed++; })); + scheduler.StartCoroutine( + new Probe( + () => + { + moving = true; + scheduler.Dispose(); + Assert.Equal(0, disposed); + moving = false; + return true; + }, + () => null, + () => + { + Assert.False(moving); + disposed++; + } + ) + ); scheduler.Tick(0); Assert.Equal(1, disposed); Assert.Throws(() => scheduler.Tick(0)); @@ -216,12 +253,15 @@ public void ReentrantCleanupCommandsAreDrainedWithoutDoubleDisposal() using var scheduler = new CoroutineScheduler(); var owner = new object(); int disposed = 0; - scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => - { - disposed++; - scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => disposed++)); - scheduler.StopAllCoroutines(owner); - })); + scheduler.StartCoroutine( + owner, + new Probe(() => true, () => null, () => + { + disposed++; + scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => disposed++)); + scheduler.StopAllCoroutines(owner); + }) + ); scheduler.StopAllCoroutines(owner); Assert.Equal(2, disposed); scheduler.Tick(0); @@ -233,7 +273,13 @@ public void RecursiveTickIsRejectedBeforeAdvancingAnotherFrame() { using var scheduler = new CoroutineScheduler(); int disposed = 0; - scheduler.StartCoroutine(new Probe(() => { scheduler.Tick(0); return true; }, () => null, () => disposed++)); + scheduler.StartCoroutine( + new Probe(() => + { + scheduler.Tick(0); + return true; + }, () => null, () => disposed++) + ); AggregateException error = Assert.Throws(() => scheduler.Tick(0)); Assert.IsType(Assert.Single(error.InnerExceptions)); Assert.Equal(1, disposed); @@ -261,16 +307,30 @@ public void OwnerStopFromCurrentOrWaitPredicateCannotResumeRetiredState(bool wai var owner = new object(); int disposed = 0; int moves = 0; - CoroutineHandle handle = scheduler.StartCoroutine(owner, new Probe( - () => { moves++; return true; }, - () => - { - if (wait) - return new WaitUntil(() => { scheduler.StopAllCoroutines(owner); return true; }); - scheduler.StopAllCoroutines(owner); - return null; - }, - () => disposed++)); + CoroutineHandle handle = scheduler.StartCoroutine( + owner, + new Probe( + () => + { + moves++; + return true; + }, + () => + { + if (wait) + { + return new WaitUntil(() => + { + scheduler.StopAllCoroutines(owner); + return true; + }); + } + scheduler.StopAllCoroutines(owner); + return null; + }, + () => disposed++ + ) + ); scheduler.Tick(0); scheduler.Tick(0); Assert.False(handle.isValid); @@ -331,17 +391,24 @@ public void QueuedStopFromCoroutineDoesNotCorruptActiveDispatch(string stop) int disposed = 0; int following = 0; CoroutineHandle self = default; - self = scheduler.StartCoroutine(new Probe( - () => - { - if (stop == "handle") - Assert.True(scheduler.StopCoroutine(self)); - else - scheduler.StopAllCoroutines(); - return true; - }, - () => null, - () => disposed++)); + self = scheduler.StartCoroutine( + new Probe( + () => + { + if (stop == "handle") + { + Assert.True(scheduler.StopCoroutine(self)); + } + else + { + scheduler.StopAllCoroutines(); + } + return true; + }, + () => null, + () => disposed++ + ) + ); scheduler.StartCoroutine(Loop(() => following++)); scheduler.Tick(0); Assert.Equal(1, following); @@ -367,8 +434,11 @@ Action dispose ) : IEnumerator, IDisposable { public object? Current => current(); + public bool MoveNext() => move(); + public void Reset() => throw new NotSupportedException(); + public void Dispose() => dispose(); } } diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs index b4884164b..f0bd78b25 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs @@ -3,20 +3,18 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; - -using Inno.Core.Coroutines; - using Xunit; +using Inno.Core.Coroutines; namespace Inno.Core.Coroutines.Tests; public sealed class CoroutineSchedulerTests { [Fact] - public void StartCoroutine_NullYield_RunsOnNextTick() + public void StartCoroutineNullYieldRunsOnNextTick() { using var scheduler = new CoroutineScheduler(); - var ran = false; + bool ran = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -33,10 +31,10 @@ IEnumerator Routine() } [Fact] - public void WaitForSeconds_WaitsByTime() + public void WaitForSecondsWaitsByTime() { using var scheduler = new CoroutineScheduler(); - var ran = false; + bool ran = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.3f); @@ -51,17 +49,17 @@ public void WaitForSeconds_WaitsByTime() IEnumerator Routine() { - yield return new WaitForSeconds(1.0f); + yield return new WaitForSeconds(1f); ran = true; } } [Fact] - public void WaitUntil_And_WaitWhile_Work() + public void WaitUntilAndWaitWhileWork() { using var scheduler = new CoroutineScheduler(); - var flag = false; - var done = false; + bool flag = false; + bool done = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -85,10 +83,10 @@ IEnumerator Routine() } [Fact] - public void StopCoroutine_StopsTarget() + public void StopCoroutineStopsTarget() { using var scheduler = new CoroutineScheduler(); - var count = 0; + int count = 0; CoroutineHandle handle = scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -109,13 +107,13 @@ IEnumerator Routine() } [Fact] - public void StopAllCoroutines_ByOwner_StopsOnlyThatOwner() + public void StopAllCoroutinesByOwnerStopsOnlyThatOwner() { using var scheduler = new CoroutineScheduler(); var ownerA = new object(); var ownerB = new object(); - var a = 0; - var b = 0; + int a = 0; + int b = 0; CoroutineHandle handleA = scheduler.StartCoroutine(ownerA, Loop(() => a++)); scheduler.StartCoroutine(ownerB, Loop(() => b++)); @@ -143,10 +141,10 @@ public void StopAllCoroutinesByOwnerReleasesOwnerAndEnumeratorBeforeReturning() } [Fact] - public void NestedCoroutine_Works() + public void NestedCoroutineWorks() { using var scheduler = new CoroutineScheduler(); - var order = ""; + string order = string.Empty; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -171,11 +169,11 @@ IEnumerator Child() } [Fact] - public void WaitForTask_WaitsCompletion() + public void WaitForTaskWaitsCompletion() { using var scheduler = new CoroutineScheduler(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var completed = false; + bool completed = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -194,10 +192,10 @@ IEnumerator Routine() } [Fact] - public void ListenOnceStyle_YieldCoroutineHandle_WaitsTarget() + public void ListenOnceStyleYieldCoroutineHandleWaitsTarget() { using var scheduler = new CoroutineScheduler(); - var done = false; + bool done = false; CoroutineHandle child = scheduler.StartCoroutine(Child()); scheduler.StartCoroutine(Parent(child)); @@ -220,16 +218,16 @@ IEnumerator Parent(CoroutineHandle handle) } [Fact] - public void ConcurrentStartAndTick_IsStable() + public void ConcurrentStartAndTickIsStable() { using var scheduler = new CoroutineScheduler(); - const int workers = 8; - const int perWorker = 4000; - var count = 0; + const int C_WORKERS = 8; + const int C_PER_WORKER = 4000; + int count = 0; - Parallel.For(0, workers, _ => + Parallel.For(0, C_WORKERS, _ => { - for (int i = 0; i < perWorker; i++) + for (int i = 0; i < C_PER_WORKER; i++) { scheduler.StartCoroutine(Routine()); } @@ -238,7 +236,7 @@ public void ConcurrentStartAndTick_IsStable() scheduler.Tick(0.016f); scheduler.Tick(0.016f); - Assert.Equal(workers * perWorker, count); + Assert.Equal(C_WORKERS * C_PER_WORKER, count); return; IEnumerator Routine() @@ -249,19 +247,22 @@ IEnumerator Routine() } [Fact] - public void ConcurrentStopByHandle_IsStable() + public void ConcurrentStopByHandleIsStable() { using var scheduler = new CoroutineScheduler(); - const int count = 3000; - CoroutineHandle[] handles = new CoroutineHandle[count]; - var ran = 0; + const int C_COUNT = 3000; + var handles = new CoroutineHandle[C_COUNT]; + int ran = 0; - for (int i = 0; i < count; i++) + for (int i = 0; i < C_COUNT; i++) { handles[i] = scheduler.StartCoroutine(Routine()); } - Parallel.For(0, count, i => { scheduler.StopCoroutine(handles[i]); }); + Parallel.For(0, C_COUNT, i => + { + scheduler.StopCoroutine(handles[i]); + }); scheduler.Tick(0.016f); scheduler.Tick(0.016f); @@ -276,7 +277,7 @@ IEnumerator Routine() } [Fact] - public void HandleIsValid_TracksLifecycle() + public void HandleIsValidTracksLifecycle() { using var scheduler = new CoroutineScheduler(); CoroutineHandle handle = scheduler.StartCoroutine(Routine()); @@ -295,10 +296,10 @@ IEnumerator Routine() } [Fact] - public void HandleIsValid_BecomesFalseAfterStop() + public void HandleIsValidBecomesFalseAfterStop() { using var scheduler = new CoroutineScheduler(); - CoroutineHandle handle = scheduler.StartCoroutine(Loop(() => { })); + CoroutineHandle handle = scheduler.StartCoroutine(Loop(() => {})); Assert.True(handle.isValid); Assert.True(scheduler.StopCoroutine(handle)); @@ -307,11 +308,11 @@ public void HandleIsValid_BecomesFalseAfterStop() } [Fact] - public void StopCoroutine_FromOtherScheduler_ReturnsFalseAndDoesNotAffectOwner() + public void StopCoroutineFromOtherSchedulerReturnsFalseAndDoesNotAffectOwner() { using var schedulerA = new CoroutineScheduler(); using var schedulerB = new CoroutineScheduler(); - var count = 0; + int count = 0; CoroutineHandle handleA = schedulerA.StartCoroutine(Loop(() => Interlocked.Increment(ref count))); schedulerA.Tick(0.016f); @@ -323,12 +324,12 @@ public void StopCoroutine_FromOtherScheduler_ReturnsFalseAndDoesNotAffectOwner() } [Fact] - public void StartCoroutine_AfterDispose_ThrowsAndHandleCannotBeCreated() + public void StartCoroutineAfterDisposeThrowsAndHandleCannotBeCreated() { using var scheduler = new CoroutineScheduler(); scheduler.Dispose(); - Assert.Throws(() => scheduler.StartCoroutine(Loop(() => { }))); + Assert.Throws(() => scheduler.StartCoroutine(Loop(() => {}))); } private static IEnumerator Loop(Action onTick) @@ -341,11 +342,10 @@ private static IEnumerator Loop(Action onTick) } [MethodImpl(MethodImplOptions.NoInlining)] - private static (WeakReference owner, WeakReference routine) StopOwnedCoroutine( - CoroutineScheduler scheduler) + private static (WeakReference owner, WeakReference routine) StopOwnedCoroutine(CoroutineScheduler scheduler) { var owner = new object(); - IEnumerator routine = Loop(static () => { }); + IEnumerator routine = Loop(static () => {}); CoroutineHandle handle = scheduler.StartCoroutine(owner, routine); scheduler.Tick(0.016f); diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs new file mode 100644 index 000000000..e13aeb1de --- /dev/null +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Core.Diagnostics.Tests; + +[CollectionDefinition("Diagnose", DisableParallelization = true)] +public sealed class DiagnoseCollection; diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs index 01a4496e4..ec7cbeb27 100644 --- a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs @@ -1,16 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Core.Diagnostics; - using Xunit; namespace Inno.Core.Diagnostics.Tests; -[CollectionDefinition("Diagnose", DisableParallelization = true)] -public sealed class DiagnoseCollection; - [Collection("Diagnose")] public sealed class DiagnosticHubTests : IDisposable { @@ -18,7 +12,7 @@ public sealed class DiagnosticHubTests : IDisposable private const string C_IMPORT_DIAGNOSTICS = "Import"; private const string C_RELOAD_DIAGNOSTICS = "Reload"; - private readonly Guid m_assetId = Guid.NewGuid(); + private readonly Guid m_assetID = Guid.NewGuid(); private readonly DiagnosticHub m_hub = new(); private readonly IDisposable m_scope; @@ -28,7 +22,7 @@ public DiagnosticHubTests() } [Fact] - public void DiagnosticFactories_CreateTheRequestedSeverityAndLocation() + public void DiagnosticFactoriesCreateTheRequestedSeverityAndLocation() { var location = new DiagnosticLocation("Assets/Test.cs", 4, 2); @@ -43,17 +37,15 @@ public void DiagnosticFactories_CreateTheRequestedSeverityAndLocation() } [Fact] - public void Set_ReplacesTheCompleteReportOwnedByOneCallerGroup() + public void SetReplacesTheCompleteReportOwnedByOneCallerGroup() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); Diagnostics.Set( C_COMPILATION_DIAGNOSTICS, - Diagnostic.Error( - "CS1001", - "Expected identifier.", - new DiagnosticLocation("Assets/Test.cs", 4, 2))); + Diagnostic.Error("CS1001", "Expected identifier.", new DiagnosticLocation("Assets/Test.cs", 4, 2)) + ); DiagnosticReport firstReport = Assert.Single(sink.reports); Diagnostic first = Assert.Single(firstReport.diagnostics); Assert.Equal("CS1001", first.code); @@ -61,7 +53,8 @@ public void Set_ReplacesTheCompleteReportOwnedByOneCallerGroup() Diagnostics.Set( C_COMPILATION_DIAGNOSTICS, - Diagnostic.Warning("CS0168", "Variable is declared but never used.")); + Diagnostic.Warning("CS0168", "Variable is declared but never used.") + ); DiagnosticReport replacementReport = Assert.Single(sink.reports); Diagnostic replacement = Assert.Single(replacementReport.diagnostics); @@ -71,14 +64,14 @@ public void Set_ReplacesTheCompleteReportOwnedByOneCallerGroup() } [Fact] - public void Set_EmptyCollectionClearsOnlyItsCallerGroup() + public void SetEmptyCollectionClearsOnlyItsCallerGroup() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, Diagnostic.Error("A", "First")); Diagnostics.Set(C_RELOAD_DIAGNOSTICS, Diagnostic.Warning("B", "Second")); - Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, Array.Empty()); + Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, []); DiagnosticReport remaining = Assert.Single(sink.reports); Assert.Equal(C_RELOAD_DIAGNOSTICS, remaining.source.displayName); @@ -86,32 +79,34 @@ public void Set_EmptyCollectionClearsOnlyItsCallerGroup() } [Fact] - public void Set_TargetedReportsRemainIndependent() + public void SetTargetedReportsRemainIndependent() { var sink = new ProbeSink(); - Guid otherAssetId = Guid.NewGuid(); + Guid otherAssetID = Guid.NewGuid(); m_hub.RegisterSink(sink); Diagnostics.Set( - m_assetId, + m_assetID, C_IMPORT_DIAGNOSTICS, Diagnostic.Error("A", "First asset"), - displayName: "Assets/First.asset"); + displayName: "Assets/First.asset" + ); Diagnostics.Set( - otherAssetId, + otherAssetID, C_IMPORT_DIAGNOSTICS, Diagnostic.Warning("B", "Second asset"), - displayName: "Assets/Second.asset"); + displayName: "Assets/Second.asset" + ); - Diagnostics.Clear(m_assetId, C_IMPORT_DIAGNOSTICS); + Diagnostics.Clear(m_assetID, C_IMPORT_DIAGNOSTICS); DiagnosticReport remaining = Assert.Single(sink.reports); Assert.Equal("Assets/Second.asset", remaining.source.displayName); - Diagnostics.Clear(otherAssetId, C_IMPORT_DIAGNOSTICS); + Diagnostics.Clear(otherAssetID, C_IMPORT_DIAGNOSTICS); m_hub.UnregisterSink(sink); } [Fact] - public void Set_SameGroupNameRemainsIndependentAcrossCallerTypes() + public void SetSameGroupNameRemainsIndependentAcrossCallerTypes() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); @@ -126,7 +121,7 @@ public void Set_SameGroupNameRemainsIndependentAcrossCallerTypes() } [Fact] - public void RegisterSink_ReplaysEveryActiveReport() + public void RegisterSinkReplaysEveryActiveReport() { Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, Diagnostic.Error("A", "First")); Diagnostics.Set(C_RELOAD_DIAGNOSTICS, Diagnostic.Warning("B", "Second")); @@ -139,7 +134,7 @@ public void RegisterSink_ReplaysEveryActiveReport() } [Fact] - public void SinkFailure_DoesNotPreventOtherSinksFromReceivingState() + public void SinkFailureDoesNotPreventOtherSinksFromReceivingState() { var failingSink = new FailingSink(); var sink = new ProbeSink(); @@ -158,12 +153,12 @@ public void ReporterReplacesIssueByIdentityAndResolvesOnlyItsOwnIssue() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.audio", "Audio")); - reporter.Publish(new Diagnostic("LOAD", "First", DiagnosticSeverity.Warning, objectId: m_assetId)); - reporter.Publish(new Diagnostic("LOAD", "Updated", DiagnosticSeverity.Error, objectId: m_assetId)); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.audio", "Audio")); + reporter.Publish(new Diagnostic("LOAD", "First", DiagnosticSeverity.Warning, objectID: m_assetID)); + reporter.Publish(new Diagnostic("LOAD", "Updated", DiagnosticSeverity.Error, objectID: m_assetID)); Assert.Equal("Updated", Assert.Single(Assert.Single(sink.reports).diagnostics).message); reporter.Publish(new Diagnostic("DEVICE", "Muted", DiagnosticSeverity.Warning)); - reporter.Resolve("LOAD", objectId: m_assetId); + reporter.Resolve("LOAD", objectID: m_assetID); Assert.Equal("DEVICE", Assert.Single(Assert.Single(sink.reports).diagnostics).code); reporter.Dispose(); Assert.Empty(sink.reports); @@ -174,7 +169,7 @@ public void ReporterDoesNotRepublishUnchangedIssueOrAlreadyResolvedIdentity() { var sink = new CountingSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.frame", "Frame")); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.frame", "Frame")); reporter.Publish(Diagnostic.Error("FRAME", "Same failure")); int published = sink.replaceCount; @@ -194,9 +189,9 @@ public void OldReporterCannotPublishOrClearReplacementGeneration() var sink = new ProbeSink(); m_hub.RegisterSink(sink); var source = new DiagnosticSource("tests.renderer", "Renderer"); - using var previous = m_hub.CreateReporter(source); + using DiagnosticReporter previous = m_hub.CreateReporter(source); previous.Publish(Diagnostic.Error("OLD", "Old generation")); - using var current = m_hub.CreateReporter(source); + using DiagnosticReporter current = m_hub.CreateReporter(source); current.Publish(Diagnostic.Warning("NEW", "Current generation")); Assert.Throws(() => previous.Publish(Diagnostic.Error("OLD", "Stale"))); previous.Dispose(); @@ -208,7 +203,7 @@ public void ReporterRejectsDuplicateReplacementWithoutChangingLastReport() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.graph", "Graph")); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.graph", "Graph")); reporter.Publish(Diagnostic.Info("GOOD", "Last good")); Diagnostic duplicate = Diagnostic.Error("BAD", "Duplicate"); Assert.Throws(() => reporter.Replace([duplicate, duplicate])); @@ -219,7 +214,7 @@ public void Dispose() { Diagnostics.Clear(C_COMPILATION_DIAGNOSTICS); Diagnostics.Clear(C_RELOAD_DIAGNOSTICS); - Diagnostics.Clear(m_assetId, C_IMPORT_DIAGNOSTICS); + Diagnostics.Clear(m_assetID, C_IMPORT_DIAGNOSTICS); m_scope.Dispose(); } @@ -227,41 +222,34 @@ private sealed class ProbeSink : IDiagnosticSink { private readonly Dictionary m_reports = new(StringComparer.Ordinal); - internal IReadOnlyList reports => m_reports.Values.ToArray(); + public void Replace(DiagnosticReport report) => m_reports[report.source.id] = report; - public void Replace(DiagnosticReport report) - => m_reports[report.source.id] = report; + public void Clear(DiagnosticSource source) => m_reports.Remove(source.id); - public void Clear(DiagnosticSource source) - => m_reports.Remove(source.id); + internal IReadOnlyList reports => m_reports.Values.ToArray(); } private sealed class FailingSink : IDiagnosticSink { - public void Replace(DiagnosticReport report) - => throw new InvalidOperationException("Expected test failure."); + public void Replace(DiagnosticReport report) => throw new InvalidOperationException("Expected test failure."); - public void Clear(DiagnosticSource source) - => throw new InvalidOperationException("Expected test failure."); + public void Clear(DiagnosticSource source) => throw new InvalidOperationException("Expected test failure."); } private sealed class CountingSink : IDiagnosticSink { - internal int replaceCount { get; private set; } - public void Replace(DiagnosticReport report) => replaceCount++; - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} + + internal int replaceCount { get; private set; } } private static class OtherProducer { internal static void SetCompilation() - => Diagnostics.Set( - C_COMPILATION_DIAGNOSTICS, - Diagnostic.Error("B", "Other caller")); + => Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, Diagnostic.Error("B", "Other caller")); - internal static void ClearCompilation() - => Diagnostics.Clear(C_COMPILATION_DIAGNOSTICS); + internal static void ClearCompilation() => Diagnostics.Clear(C_COMPILATION_DIAGNOSTICS); } } diff --git a/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs b/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs index b5f0a16a3..5aca5124f 100644 --- a/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs +++ b/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; - -using Inno.Core.Events; using Xunit; +using Inno.Core.Events; namespace Inno.Core.Events.Tests; @@ -14,7 +13,7 @@ public void ObservationRunsAfterPriorityConsumersIncludingGlobalConsumption() var dispatcher = new EventDispatcher(); using EventHub ui = dispatcher.CreateHub(100); using EventHub game = dispatcher.CreateHub(); - var sequence = new List(); + List sequence = []; using IDisposable uiSubscription = ui.Listen(evnt => { sequence.Add("ui"); @@ -59,12 +58,14 @@ public void RecursivelyQueuedObservationWaitsForTheNextFlush() var dispatcher = new EventDispatcher(); var first = new TestEvent(); var second = new TestEvent(); - var observed = new List(); + List observed = []; dispatcher.dispatched += evnt => { observed.Add(evnt); if (ReferenceEquals(evnt, first)) + { dispatcher.Enqueue(second); + } }; dispatcher.Enqueue(first); diff --git a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs index 63af6e5cf..4565acbc0 100644 --- a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs +++ b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; using System.Threading; - -using Inno.Core.Events; - +using System.Threading.Tasks; using Xunit; +using Inno.Core.Events; namespace Inno.Core.Events.Tests; @@ -35,7 +33,7 @@ public void RoutedMovementSharesGlobalConsumptionAcrossDispatchers(bool consumeR Assert.True(source.isGlobalHandled); Assert.True(routed.isGlobalHandled); Assert.True(routedAgain.isGlobalHandled); - Assert.Equal(17u, routed.windowId); + Assert.Equal(17u, routed.windowID); Assert.Equal(40f, routed.x); Assert.Equal(30f, routed.y); Assert.Equal(240f, source.x); @@ -64,7 +62,7 @@ public void RoutedMovementKeepsHubConsumptionLocalToEachRepresentation() } [Fact] - public void CreateHub_ProducesValidHub() + public void CreateHubProducesValidHub() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); @@ -73,7 +71,7 @@ public void CreateHub_ProducesValidHub() } [Fact] - public void DisposeHub_MakesHubInvalidAndPreventsFurtherListen() + public void DisposeHubMakesHubInvalidAndPreventsFurtherListen() { var dispatcher = new EventDispatcher(); EventHub hub = dispatcher.CreateHub(); @@ -81,15 +79,15 @@ public void DisposeHub_MakesHubInvalidAndPreventsFurtherListen() hub.Dispose(); Assert.False(hub.isValid); - Assert.Throws(() => hub.Listen(_ => { })); + Assert.Throws(() => hub.Listen(_ => {})); } [Fact] - public void ListenTokenDispose_UnsubscribesListener() + public void ListenTokenDisposeUnsubscribesListener() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; IDisposable token = hub.Listen(_ => count++); dispatcher.Emit(new ProbeEvent(1)); @@ -100,11 +98,11 @@ public void ListenTokenDispose_UnsubscribesListener() } [Fact] - public void ListenTokenDispose_ConcurrentDispose_IsSafeAndIdempotent() + public void ListenTokenDisposeConcurrentDisposeIsSafeAndIdempotent() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; IDisposable token = hub.Listen(_ => Interlocked.Increment(ref count)); Parallel.For(0, 64, _ => token.Dispose()); @@ -114,11 +112,11 @@ public void ListenTokenDispose_ConcurrentDispose_IsSafeAndIdempotent() } [Fact] - public void ListenOnce_InvokesOnlyOneTime() + public void ListenOnceInvokesOnlyOneTime() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; hub.ListenOnce(_ => count++); @@ -129,25 +127,28 @@ public void ListenOnce_InvokesOnlyOneTime() } [Fact] - public void ListenOnce_ConcurrentEmit_StillInvokesOnlyOneTime() + public void ListenOnceConcurrentEmitStillInvokesOnlyOneTime() { - const int iterations = 10_000; + const int C_ITERATIONS = 10_000; var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; hub.ListenOnce(_ => Interlocked.Increment(ref count)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, C_ITERATIONS, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); Assert.Equal(1, count); } [Fact] - public void EnqueueAndFlush_DispatchesQueuedEvents() + public void EnqueueAndFlushDispatchesQueuedEvents() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var values = new List(); + List values = []; hub.Listen(e => values.Add(e.value)); @@ -163,7 +164,7 @@ public void QueueCapacityIsExplicitAndRecursiveEventsWaitForAnotherFlush() { var dispatcher = new EventDispatcher(queueCapacity: 2, flushBudget: 1); using EventHub hub = dispatcher.CreateHub(); - var values = new List(); + List values = []; hub.Listen(value => { values.Add(value.value); @@ -183,12 +184,12 @@ public void QueueCapacityIsExplicitAndRecursiveEventsWaitForAnotherFlush() } [Fact] - public void HubOrder_HigherOrderRunsFirst() + public void HubOrderHigherOrderRunsFirst() { var dispatcher = new EventDispatcher(); using EventHub lowHub = dispatcher.CreateHub(order: 0); using EventHub highHub = dispatcher.CreateHub(order: 10); - var order = new List(); + List order = []; lowHub.Listen(_ => order.Add("low")); highHub.Listen(_ => order.Add("high")); @@ -199,13 +200,13 @@ public void HubOrder_HigherOrderRunsFirst() } [Fact] - public void HandledStopsPropagation_WithinHubAndAcrossHubs() + public void HandledStopsPropagationWithinHubAndAcrossHubs() { var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var firstHubSecondListenerCalled = false; - var secondHubCalled = false; + bool firstHubSecondListenerCalled = false; + bool secondHubCalled = false; firstHub.Listen(e => e.HandleInGlobal()); firstHub.Listen(_ => firstHubSecondListenerCalled = true); @@ -218,11 +219,11 @@ public void HandledStopsPropagation_WithinHubAndAcrossHubs() } [Fact] - public void HandledEventBeforeEmit_SkipsDispatch() + public void HandledEventBeforeEmitSkipsDispatch() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var called = false; + bool called = false; hub.Listen(_ => called = true); @@ -234,13 +235,13 @@ public void HandledEventBeforeEmit_SkipsDispatch() } [Fact] - public void HandleInHub_StopsOnlyCurrentHub() + public void HandleInHubStopsOnlyCurrentHub() { var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var firstHubSecondListenerCalled = false; - var secondHubCalled = false; + bool firstHubSecondListenerCalled = false; + bool secondHubCalled = false; firstHub.Listen(e => e.HandleInHub()); firstHub.Listen(_ => firstHubSecondListenerCalled = true); @@ -253,13 +254,13 @@ public void HandleInHub_StopsOnlyCurrentHub() } [Fact] - public void HandleInHub_DoesNotAffectNextHub() + public void HandleInHubDoesNotAffectNextHub() { var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var secondHubFirstListenerCalled = false; - var secondHubSecondListenerCalled = false; + bool secondHubFirstListenerCalled = false; + bool secondHubSecondListenerCalled = false; firstHub.Listen(e => e.HandleInHub()); secondHub.Listen(_ => secondHubFirstListenerCalled = true); @@ -272,34 +273,37 @@ public void HandleInHub_DoesNotAffectNextHub() } [Fact] - public void ConcurrentEmit_AcrossThreads_IsStable() + public void ConcurrentEmitAcrossThreadsIsStable() { - const int iterations = 20_000; + const int C_ITERATIONS = 20_000; var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var countA = 0; - var countB = 0; + int countA = 0; + int countB = 0; hubA.Listen(_ => Interlocked.Increment(ref countA)); hubB.Listen(_ => Interlocked.Increment(ref countB)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, C_ITERATIONS, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); - Assert.Equal(iterations, countA); - Assert.Equal(iterations, countB); + Assert.Equal(C_ITERATIONS, countA); + Assert.Equal(C_ITERATIONS, countB); } [Fact] - public void ConcurrentEmit_WithHandleInHub_StopsOnlyCurrentHub() + public void ConcurrentEmitWithHandleInHubStopsOnlyCurrentHub() { - const int iterations = 20_000; + const int C_ITERATIONS = 20_000; var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubAFirst = 0; - var hubASecond = 0; - var hubBCount = 0; + int hubAFirst = 0; + int hubASecond = 0; + int hubBCount = 0; hubA.Listen(e => { @@ -312,23 +316,26 @@ public void ConcurrentEmit_WithHandleInHub_StopsOnlyCurrentHub() hubA.Listen(_ => Interlocked.Increment(ref hubASecond)); hubB.Listen(_ => Interlocked.Increment(ref hubBCount)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, C_ITERATIONS, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); - Assert.Equal(iterations, hubAFirst); - Assert.Equal(iterations / 2, hubASecond); - Assert.Equal(iterations, hubBCount); + Assert.Equal(C_ITERATIONS, hubAFirst); + Assert.Equal(C_ITERATIONS / 2, hubASecond); + Assert.Equal(C_ITERATIONS, hubBCount); } [Fact] - public void ConcurrentEmit_WithHandleInGlobal_StopsFollowingHubs() + public void ConcurrentEmitWithHandleInGlobalStopsFollowingHubs() { - const int iterations = 20_000; + const int C_ITERATIONS = 20_000; var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubAFirst = 0; - var hubASecond = 0; - var hubBCount = 0; + int hubAFirst = 0; + int hubASecond = 0; + int hubBCount = 0; hubA.Listen(e => { @@ -341,21 +348,24 @@ public void ConcurrentEmit_WithHandleInGlobal_StopsFollowingHubs() hubA.Listen(_ => Interlocked.Increment(ref hubASecond)); hubB.Listen(_ => Interlocked.Increment(ref hubBCount)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, C_ITERATIONS, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); - Assert.Equal(iterations, hubAFirst); - Assert.Equal(iterations / 2, hubASecond); - Assert.Equal(iterations / 2, hubBCount); + Assert.Equal(C_ITERATIONS, hubAFirst); + Assert.Equal(C_ITERATIONS / 2, hubASecond); + Assert.Equal(C_ITERATIONS / 2, hubBCount); } [Fact] - public void Announce_DispatchesImmediately_OnlyInCurrentHub() + public void AnnounceDispatchesImmediatelyOnlyInCurrentHub() { var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubACalled = false; - var hubBCalled = false; + bool hubACalled = false; + bool hubBCalled = false; hubA.Listen(_ => hubACalled = true); hubB.Listen(_ => hubBCalled = true); @@ -367,11 +377,11 @@ public void Announce_DispatchesImmediately_OnlyInCurrentHub() } [Fact] - public void Announce_RespectsHandleInHub_InSameHub() + public void AnnounceRespectsHandleInHubInSameHub() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(e => e.HandleInHub()); hub.Listen(_ => secondCalled = true); @@ -382,11 +392,11 @@ public void Announce_RespectsHandleInHub_InSameHub() } [Fact] - public void DisposeHub_DuringDispatch_StopsRemainingListenersInSameHub() + public void DisposeHubDuringDispatchStopsRemainingListenersInSameHub() { var dispatcher = new EventDispatcher(); EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(_ => hub.Dispose()); hub.Listen(_ => secondCalled = true); @@ -398,11 +408,11 @@ public void DisposeHub_DuringDispatch_StopsRemainingListenersInSameHub() } [Fact] - public void DisposeHub_DuringAnnounce_StopsRemainingListenersInSameHub() + public void DisposeHubDuringAnnounceStopsRemainingListenersInSameHub() { var dispatcher = new EventDispatcher(); EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(_ => hub.Dispose()); hub.Listen(_ => secondCalled = true); diff --git a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs index d4d9cbf86..21c65d747 100644 --- a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; - using Xunit; namespace Inno.Core.Execution.Tests; @@ -12,8 +11,8 @@ public sealed class ExecutionSlotTests public void RetirementIsLifoAndRestoresParent() { var slot = new ExecutionSlot("service"); - object first = new(); - object second = new(); + var first = new object(); + var second = new object(); using IDisposable outer = slot.Enter(first); IDisposable inner = slot.Enter(second); Assert.Throws(outer.Dispose); @@ -45,10 +44,12 @@ public async Task RetiredBindingIsRevokedInInheritedAsyncContext() public void SuspensionMasksAndRestoresParent() { var slot = new ExecutionSlot("service"); - object value = new(); + var value = new object(); using IDisposable outer = slot.Enter(value); using (slot.Suspend()) + { Assert.False(slot.TryGet(out _)); + } Assert.Same(value, slot.current); } diff --git a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs index 339cd21a1..f5ed60545 100644 --- a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs @@ -16,7 +16,16 @@ public async Task CapacityRejectsBeforeUserCodeAndCompletedWorkReleasesAdmission var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Task operation = owner.RunAsync(_ => new ValueTask(ready.Task)); bool invoked = false; - Assert.Throws(() => { _ = owner.RunAsync(_ => { invoked = true; return ValueTask.FromResult(0); }); }); + Assert.Throws( + () => + { + _ = owner.RunAsync(_ => + { + invoked = true; + return ValueTask.FromResult(0); + }); + } + ); Assert.False(invoked); ready.SetResult(iteration); Assert.Equal(iteration, await operation); @@ -30,7 +39,9 @@ public void IdleLifetimeDoesNotRetainSuccessfulOperationResults() { using var owner = new LifetimeScope(); WeakReference result = Complete(owner); - GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); Assert.False(result.IsAlive); Assert.Equal(0, owner.trackedWorkCount); } diff --git a/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs b/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs index 4def07892..8ca2d048c 100644 --- a/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; - using Xunit; namespace Inno.Core.Execution.Tests; @@ -14,12 +13,22 @@ public void FailureBeforePendingRemainsObservableAfterRetry() bool ready = false; int failingReleaseCount = 0; var lifetime = new LifetimeScope(); - lifetime.Own(new Resource(() => - { - if (!ready) - throw new RetirementPendingException("pending"); - })); - lifetime.Own(new Resource(() => { failingReleaseCount++; throw new InvalidOperationException("release failed"); })); + lifetime.Own( + new Resource(() => + { + if (!ready) + { + throw new RetirementPendingException("pending"); + } + }) + ); + lifetime.Own( + new Resource(() => + { + failingReleaseCount++; + throw new InvalidOperationException("release failed"); + }) + ); Assert.Throws(lifetime.Dispose); ready = true; AggregateException error = Assert.Throws(lifetime.Dispose); @@ -33,10 +42,12 @@ public void RetirementDeadlineRemainsFaultedAndDoesNotReleasePendingDependencies { var barrier = new RetirementBarrier("test owner", TimeSpan.FromTicks(1)); Assert.Throws(() => barrier.TryComplete( - () => throw new RetirementPendingException("worker still running"))); + () => throw new RetirementPendingException("worker still running") + )); bool released = false; RetirementTimeoutException error = Assert.Throws( - () => barrier.TryComplete(() => released = true)); + () => barrier.TryComplete(() => released = true) + ); Assert.Contains("test owner", error.Message); Assert.False(released); } @@ -46,7 +57,7 @@ public void RetirementBarrierRetriesOnOwnerThreadAndDoesNotRetainCompletedCallba { var barrier = new RetirementBarrier("test owner"); Assert.False(barrier.TryComplete(() => throw new RetirementPendingException("pending"))); - Assert.True(barrier.TryComplete(() => { })); + Assert.True(barrier.TryComplete(() => {})); Assert.True(barrier.TryComplete(() => throw new InvalidOperationException("must not run"))); } @@ -56,7 +67,13 @@ public void RetirementAttemptsEveryResourceInReverseOrder() List released = []; var lifetime = new LifetimeScope(); lifetime.Own(new Resource(() => released.Add(1))); - lifetime.Own(new Resource(() => { released.Add(2); throw new InvalidOperationException("expected"); })); + lifetime.Own( + new Resource(() => + { + released.Add(2); + throw new InvalidOperationException("expected"); + }) + ); lifetime.Own(new Resource(() => released.Add(3))); Assert.Throws(lifetime.Dispose); Assert.Equal(new[] { 3, 2, 1 }, released); diff --git a/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs b/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs index b099472b5..65c743cab 100644 --- a/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs @@ -37,15 +37,18 @@ public void AsynchronousContinuationsAndSendReturnToTheCallingThread() { int owner = Environment.CurrentManagedThreadId; SynchronizationContext? original = SynchronizationContext.Current; - Assert.Equal(42, OwnerThreadExecution.Run(async () => - { - SynchronizationContext context = SynchronizationContext.Current!; - await Task.Run(() => context.Send(_ => Assert.Equal(owner, Environment.CurrentManagedThreadId), null)); - Assert.Equal(owner, Environment.CurrentManagedThreadId); - await Task.Delay(10); - Assert.Equal(owner, Environment.CurrentManagedThreadId); - return 42; - })); + Assert.Equal( + 42, + OwnerThreadExecution.Run(async () => + { + SynchronizationContext context = SynchronizationContext.Current!; + await Task.Run(() => context.Send(_ => Assert.Equal(owner, Environment.CurrentManagedThreadId), null)); + Assert.Equal(owner, Environment.CurrentManagedThreadId); + await Task.Delay(10); + Assert.Equal(owner, Environment.CurrentManagedThreadId); + return 42; + }) + ); Assert.Same(original, SynchronizationContext.Current); } @@ -55,8 +58,11 @@ public void CompletedOperationsFailuresAndCancellationRestoreThePreviousContext( SynchronizationContext? original = SynchronizationContext.Current; Assert.Equal(1, OwnerThreadExecution.Run(() => Task.FromResult(1))); var failure = new InvalidOperationException("Expected owner failure."); - Assert.Same(failure, Assert.Throws(() => - OwnerThreadExecution.Run(() => Task.FromException(failure)))); + Assert.Same( + failure, + Assert.Throws(() => + OwnerThreadExecution.Run(() => Task.FromException(failure))) + ); Assert.Throws(() => OwnerThreadExecution.Run(() => Task.FromCanceled(new CancellationToken(canceled: true)))); Assert.Throws(() => OwnerThreadExecution.Run(null!)); @@ -67,16 +73,19 @@ public void CompletedOperationsFailuresAndCancellationRestoreThePreviousContext( public void CompletedOperationsDrainCallbacksPostedByAlreadyQueuedWork() { int callbacks = 0; - Assert.Equal(7, OwnerThreadExecution.Run(() => - { - SynchronizationContext context = SynchronizationContext.Current!; - context.Post(_ => + Assert.Equal( + 7, + OwnerThreadExecution.Run(() => { - callbacks++; - context.Post(_ => callbacks++, null); - }, null); - return Task.FromResult(7); - })); + SynchronizationContext context = SynchronizationContext.Current!; + context.Post(_ => + { + callbacks++; + context.Post(_ => callbacks++, null); + }, null); + return Task.FromResult(7); + }) + ); Assert.Equal(2, callbacks); } } diff --git a/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs b/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs index cf7d46c6b..0817a4e04 100644 --- a/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs @@ -19,7 +19,7 @@ public void ClassificationFindsNestedTimeoutWithoutReplacingTheOriginalTree() Assert.Same(timeout, RetirementPendingException.Find(new RetirementPendingException("outer", wrapped))); Assert.Null(RetirementPendingException.Find(ordinary)); Assert.Throws(() => RetirementPendingException.Find(null!)); - var failures = new List(); + List failures = []; RetirementPendingException.CollectCompletedFailures(wrapped, failures); RetirementPendingException.CollectCompletedFailures(wrapped, failures); Assert.Same(ordinary, Assert.Single(failures)); @@ -32,10 +32,20 @@ public void LifetimeRetainsPendingResourceAndEarlierErrorsAcrossWrappedRetries() bool ready = false; bool dependencyReleased = false; var ordinary = new InvalidOperationException("completed sibling"); - var failure = new InvalidOperationException("resource context", new AggregateException( - ordinary, new AggregateException(new RetirementPendingException("callback remains active")))); + var failure = new InvalidOperationException( + "resource context", + new AggregateException( + ordinary, + new AggregateException(new RetirementPendingException("callback remains active")) + ) + ); lifetime.Own(new Resource(() => dependencyReleased = true)); - lifetime.Own(new Resource(() => { if (!ready) throw failure; })); + lifetime.Own( + new Resource(() => + { + if (!ready) throw failure; + }) + ); Assert.Same(failure, Assert.Throws(lifetime.Dispose)); Assert.Same(failure, Assert.Throws(lifetime.Dispose)); Assert.False(dependencyReleased); @@ -54,7 +64,7 @@ public void BarrierRetainsOrdinarySiblingsUntilThePendingWorkCompletes() var failure = new AggregateException(ordinary, new RetirementPendingException("pending")); Assert.False(barrier.TryComplete(() => throw failure)); Assert.False(barrier.TryComplete(() => throw failure)); - AggregateException completed = Assert.Throws(() => barrier.TryComplete(() => { })); + AggregateException completed = Assert.Throws(() => barrier.TryComplete(() => {})); Assert.Same(ordinary, Assert.Single(completed.InnerExceptions)); Assert.True(barrier.TryComplete(() => throw new InvalidOperationException("must not run twice"))); } @@ -66,7 +76,7 @@ public void NestedTimeoutRemainsTerminalAndPreservesEveryFailure() var timeout = new RetirementTimeoutException("inner deadline"); var failure = new AggregateException(new InvalidOperationException("first"), timeout); Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => throw failure))); - Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => { }))); + Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => {}))); } [Fact] @@ -75,9 +85,10 @@ public void NewTimeoutKeepsTheCompleteWrappedCause() var barrier = new RetirementBarrier("deadline", TimeSpan.FromTicks(1)); var failure = new InvalidOperationException("context", new RetirementPendingException("pending callback")); RetirementTimeoutException timeout = Assert.Throws( - () => barrier.TryComplete(() => throw failure)); + () => barrier.TryComplete(() => throw failure) + ); Assert.Same(failure, timeout.InnerException); - Assert.Same(timeout, Assert.Throws(() => barrier.TryComplete(() => { }))); + Assert.Same(timeout, Assert.Throws(() => barrier.TryComplete(() => {}))); } [Theory] @@ -90,9 +101,13 @@ public async Task CompletedTaskOrCancellationPendingDoesNotAuthorizeDependencyRe lifetime.Own(new Resource(() => dependencyReleased = true)); var failure = new AggregateException(new RetirementPendingException("unfinished owner outside completed task")); if (cancellation) + { lifetime.cancellationToken.Register(() => throw failure); + } else + { lifetime.Track(Task.FromException(failure)); + } Exception first = Assert.ThrowsAny(lifetime.Dispose); Assert.NotNull(RetirementPendingException.Find(first)); Assert.Same(first, Assert.ThrowsAny(lifetime.Dispose)); @@ -168,12 +183,14 @@ public async Task ConcurrentDisposalCannotReleaseTheSameResourceTwice() using var finish = new ManualResetEventSlim(); var lifetime = new LifetimeScope(); int released = 0; - lifetime.Own(new Resource(() => - { - Interlocked.Increment(ref released); - started.Set(); - Assert.True(finish.Wait(TimeSpan.FromSeconds(5))); - })); + lifetime.Own( + new Resource(() => + { + Interlocked.Increment(ref released); + started.Set(); + Assert.True(finish.Wait(TimeSpan.FromSeconds(5))); + }) + ); Task disposal = Task.Run(lifetime.Dispose); try { @@ -197,11 +214,13 @@ public void ReentrantDisposalKeepsTheCurrentOwnerUntilItsCallbackReturns() { var lifetime = new LifetimeScope(); int released = 0; - lifetime.Own(new Resource(() => - { - Assert.Throws(lifetime.Dispose); - released++; - })); + lifetime.Own( + new Resource(() => + { + Assert.Throws(lifetime.Dispose); + released++; + }) + ); lifetime.Dispose(); Assert.Equal(1, released); } @@ -218,8 +237,13 @@ public async Task AsyncOperationIsOwnedBeforeItsSynchronousPrefixCanReenter(bool { Assert.False(lifetime.isQuiescent); if (dispose) + { Assert.Throws(lifetime.Dispose); - else lifetime.Cancel(); + } + else + { + lifetime.Cancel(); + } Assert.False(released); return ValueTask.FromResult(42); }); diff --git a/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs b/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs index da198f5d9..4791de76b 100644 --- a/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs +++ b/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Inno.Core.Graphs; using Xunit; +using Inno.Core.Graphs; namespace Inno.Core.Graphs.Tests; @@ -12,13 +12,13 @@ public void NodeLookupTracksAddRemoveAndReplacementWithoutChangingDocumentOrder( { var document = new GraphDocument(); IReadOnlyList view = document.nodes; - var first = new GraphNodeRecord(new("first"), "test.node"); - var second = new GraphNodeRecord(new("second"), "test.node"); + var first = new GraphNodeRecord(new GraphNodeID("first"), "test.node"); + var second = new GraphNodeRecord(new GraphNodeID("second"), "test.node"); document.AddNode(first); document.AddNode(second); Assert.Same(first, document.FindNode(first.id)); Assert.Same(second, document.FindNode(second.id)); - Assert.Throws(() => document.AddNode(new(first.id, "duplicate"))); + Assert.Throws(() => document.AddNode(new GraphNodeRecord(first.id, "duplicate"))); Assert.Equal(2, view.Count); Assert.True(document.RemoveNode(first.id)); Assert.Null(document.FindNode(first.id)); @@ -42,11 +42,15 @@ public void RepeatedLookupAndCollectionAccessDoNotAllocate() { var document = new GraphDocument(); for (int index = 0; index < 2_000; index++) - document.AddNode(new(new("node-" + index), "test.node")); + { + document.AddNode(new GraphNodeRecord(new GraphNodeID("node-" + index), "test.node")); + } GraphNodeRecord node = document.nodes[^1]; - GraphNodeId id = node.id; + GraphNodeID id = node.id; for (int index = 0; index < 1_000; index++) + { _ = document.FindNode(id); + } long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 10_000; index++) diff --git a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs index a34d3e934..b777aa3ef 100644 --- a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs +++ b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs @@ -1,13 +1,13 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; -using Inno.Extensibility.Modules; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Core.Graphs.Tests; @@ -16,7 +16,9 @@ public sealed class GraphValidatorTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoCoreGraphsTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -24,7 +26,9 @@ public sealed class GraphValidatorTests : IDisposable public GraphValidatorTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphValidatorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphValidatorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -35,11 +39,13 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Fact] - public void Validate_WithCompatibleConnection_IsValid() + public void ValidateWithCompatibleConnectionIsValid() { GraphDocument document = CreateConnectedDocument("float", "float"); @@ -50,20 +56,21 @@ public void Validate_WithCompatibleConnection_IsValid() } [Fact] - public void Validate_WithDirectedConversion_IsValid() + public void ValidateWithDirectedConversionIsValid() { GraphDocument document = CreateConnectedDocument("float", "vector3"); GraphValidationResult result = GraphValidator.Validate( document, new Resolver(m_serialization), - new Conversion()); + new Conversion() + ); Assert.True(result.isValid); } [Fact] - public void Validate_WithIncompatibleTypes_ReportsError() + public void ValidateWithIncompatibleTypesReportsError() { GraphDocument document = CreateConnectedDocument("texture2d", "float"); @@ -74,10 +81,10 @@ public void Validate_WithIncompatibleTypes_ReportsError() } [Fact] - public void Validate_WithMissingNodeDefinition_PreservesDocumentAsWarning() + public void ValidateWithMissingNodeDefinitionPreservesDocumentAsWarning() { - GraphDocument document = new(); - GraphNodeRecord node = new(new GraphNodeId("missing"), "plugin.removed"); + var document = new GraphDocument(); + var node = new GraphNodeRecord(new GraphNodeID("missing"), "plugin.removed"); document.AddNode(node); GraphValidationResult result = GraphValidator.Validate(document, new Resolver(m_serialization)); @@ -88,9 +95,9 @@ public void Validate_WithMissingNodeDefinition_PreservesDocumentAsWarning() } [Fact] - public void Validate_WithCycle_ReportsError() + public void ValidateWithCycleReportsError() { - GraphDocument document = new(); + var document = new GraphDocument(); GraphNodeRecord left = CreateNode("left", "float", "float"); GraphNodeRecord right = CreateNode("right", "float", "float"); document.AddNode(left); @@ -105,19 +112,21 @@ public void Validate_WithCycle_ReportsError() } [Fact] - public void RemoveNode_RemovesConnectedEdges() + public void RemoveNodeRemovesConnectedEdges() { GraphDocument document = CreateConnectedDocument("float", "float"); - Assert.True(document.RemoveNode(new GraphNodeId("source"))); + Assert.True(document.RemoveNode(new GraphNodeID("source"))); Assert.Single(document.nodes); Assert.Empty(document.edges); } - private GraphDocument CreateConnectedDocument(string outputType, string inputType) - { - GraphDocument document = new(); + private GraphDocument CreateConnectedDocument( + string outputType, + string inputType + ) { + var document = new GraphDocument(); GraphNodeRecord source = CreateNode("source", outputType, outputType); GraphNodeRecord destination = CreateNode("destination", inputType, inputType); document.AddNode(source); @@ -126,59 +135,71 @@ private GraphDocument CreateConnectedDocument(string outputType, string inputTyp return document; } - private GraphNodeRecord CreateNode(string id, string inputType, string outputType) - { - GraphNodeRecord node = new(new GraphNodeId(id), $"node.{id}"); + private GraphNodeRecord CreateNode( + string id, + string inputType, + string outputType + ) { + var node = new GraphNodeRecord(new GraphNodeID(id), $"node.{id}"); node.SetValue("inputType", GraphSerializedValue.From(inputType, m_serialization)); node.SetValue("outputType", GraphSerializedValue.From(outputType, m_serialization)); return node; } - private static GraphEdgeRecord CreateEdge(string id, GraphNodeId source, GraphNodeId destination) - => new( - new GraphEdgeId(id), - new GraphEndpoint(source, new GraphPortId("out")), - new GraphEndpoint(destination, new GraphPortId("in"))); + private static GraphEdgeRecord CreateEdge( + string id, + GraphNodeID source, + GraphNodeID destination + ) => new( + new GraphEdgeID(id), + new GraphEndpoint(source, new GraphPortID("out")), + new GraphEndpoint(destination, new GraphPortID("in")) + ); private sealed class Resolver(SerializationRegistry serialization) : IGraphNodeDefinitionResolver { - public bool TryResolve(string definitionId, out GraphNodeDefinition? definition) - { - if (!definitionId.StartsWith("node.", System.StringComparison.Ordinal)) + public bool TryResolve( + string definitionID, + out GraphNodeDefinition? definition + ) { + if (!definitionID.StartsWith("node.", StringComparison.Ordinal)) { definition = null; return false; } - definition = new Definition(definitionId, serialization); + definition = new Definition(definitionID, serialization); return true; } } private sealed class Definition( string id, - SerializationRegistry serialization) : GraphNodeDefinition(id, id, "Tests") + SerializationRegistry serialization + ) : GraphNodeDefinition(id, id, "Tests") { public override IReadOnlyList GetPorts(GraphNodeRecord node) { string inputType = node.TryGetValue("inputType", out GraphSerializedValue? input) - ? input!.Deserialize(serialization)! - : "float"; + ? input!.Deserialize(serialization)! + : "float"; string outputType = node.TryGetValue("outputType", out GraphSerializedValue? output) - ? output!.Deserialize(serialization)! - : "float"; + ? output!.Deserialize(serialization)! + : "float"; return [ - new GraphPortDefinition(new GraphPortId("in"), "In", inputType, GraphPortDirection.Input), - new GraphPortDefinition(new GraphPortId("out"), "Out", outputType, GraphPortDirection.Output) + new GraphPortDefinition(new GraphPortID("in"), "In", inputType, GraphPortDirection.Input), + new GraphPortDefinition(new GraphPortID("out"), "Out", outputType, GraphPortDirection.Output) ]; } } private sealed class Conversion : IGraphTypeConversion { - public bool CanConvert(string sourceTypeId, string destinationTypeId) - => sourceTypeId == "float" && destinationTypeId == "vector3"; + public bool CanConvert( + string sourceTypeID, + string destinationTypeID + ) => sourceTypeID == "float" && destinationTypeID == "vector3"; } } diff --git a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs index e9c69367c..96047d320 100644 --- a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs +++ b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; - using Xunit; namespace Inno.Core.IO.Tests; @@ -15,7 +14,10 @@ public sealed class AtomicFilePublicationTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoAtomicPublication", Guid.NewGuid().ToString("N")); - public AtomicFilePublicationTests() => Directory.CreateDirectory(m_root); + public AtomicFilePublicationTests() + { + Directory.CreateDirectory(m_root); + } [Theory] [InlineData("document.imeta.staging-0123456789abcdef0123456789ABCDEF", true)] @@ -67,18 +69,20 @@ public void CreateOnlyRejectsAnExistingDirectoryWithoutConsumingTheCandidate() [Fact] public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() { - const int count = 16; + const int C_COUNT = 16; for (int round = 0; round < 12; round++) { string destination = Path.Combine(m_root, "document-" + round); - string[] candidates = Enumerable.Range(0, count).Select(index => destination + ".candidate-" + index).ToArray(); + string[] candidates = Enumerable.Range(0, C_COUNT).Select(index => destination + ".candidate-" + index).ToArray(); foreach (string candidate in candidates) + { File.WriteAllBytes(candidate, Enumerable.Repeat((byte)Array.IndexOf(candidates, candidate), 64 * 1024).ToArray()); + } int winner = -1; int successes = 0; - using var ready = new CountdownEvent(count); + using var ready = new CountdownEvent(C_COUNT); using var start = new ManualResetEventSlim(); - Task[] writers = Enumerable.Range(0, count).Select(index => Task.Factory.StartNew(() => + Task[] writers = Enumerable.Range(0, C_COUNT).Select(index => Task.Factory.StartNew(() => { ready.Signal(); start.Wait(); @@ -100,8 +104,10 @@ public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() byte[] bytes = File.ReadAllBytes(destination); Assert.Equal(64 * 1024, bytes.Length); Assert.All(bytes, value => Assert.Equal((byte)winner, value)); - for (int index = 0; index < count; index++) + for (int index = 0; index < C_COUNT; index++) + { Assert.Equal(index != winner, File.Exists(candidates[index])); + } } } @@ -109,11 +115,26 @@ public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayload() { string project = Path.Combine(m_root, "Publisher.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("OutputType", "Exe"), - new XElement("ImplicitUsings", "disable")), - new XElement("ItemGroup", new XElement("Reference", new XAttribute("Include", "Inno.Core.IO"), - new XElement("HintPath", typeof(AtomicFile).Assembly.Location))))).Save(project); + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("OutputType", "Exe"), + new XElement("ImplicitUsings", "disable") + ), + new XElement( + "ItemGroup", + new XElement( + "Reference", + new XAttribute("Include", "Inno.Core.IO"), + new XElement("HintPath", typeof(AtomicFile).Assembly.Location) + ) + ) + ) + ).Save(project); File.WriteAllText(Path.Combine(m_root, "Program.cs"), """ using System; using System.IO; @@ -155,16 +176,18 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl Process[] creators = Enumerable.Range(1, 8).Select(index => Start(assembly, destination, gate, index.ToString())).ToArray(); try { - await WaitUntil(() => Directory.GetFiles(m_root, "start.ready-*").Length == creators.Length); + await WaitUntilAsync(() => Directory.GetFiles(m_root, "start.ready-*").Length == creators.Length); File.WriteAllText(gate, "start"); - await WaitUntil(() => File.Exists(destination)); + await WaitUntilAsync(() => File.Exists(destination)); var document = new FileByteDocumentStore(destination); byte[] winner = Assert.IsType(document.Read()); Assert.Equal(1024 * 1024, winner.Length); Assert.InRange(winner[0], (byte)1, (byte)8); Assert.All(winner, value => Assert.Equal(winner[0], value)); for (int read = 0; read < 16; read++) + { Assert.Equal(winner, document.Read()); + } await Task.WhenAll(creators.Select(process => process.WaitForExitAsync())).WaitAsync(TimeSpan.FromSeconds(30)); Assert.Single(creators.Where(process => process.ExitCode == 0)); Assert.All(creators, process => Assert.True(process.ExitCode is 0 or 17)); @@ -175,7 +198,9 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl foreach (Process process in creators) { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); process.Dispose(); } @@ -186,8 +211,10 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl private Process Start(params string[] arguments) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(sdk) { WorkingDirectory = m_root, @@ -197,13 +224,15 @@ private Process Start(params string[] arguments) RedirectStandardError = true }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } return Process.Start(start) ?? throw new InvalidOperationException("The SDK fixture did not start."); } - private static async Task WaitUntil(Func condition) + private static async Task WaitUntilAsync(Func condition) { - long deadline = Environment.TickCount64 + 20000; + long deadline = Environment.TickCount64 + 20_000; while (!condition()) { Assert.True(Environment.TickCount64 < deadline, "The independent publishers did not reach their owned barrier."); diff --git a/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs b/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs index 7b64575b9..a70e1a23e 100644 --- a/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs +++ b/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs @@ -37,7 +37,9 @@ public void FilesDistinguishAbsentAndEmptyAndReplaceCompleteDocuments() finally { if (Directory.Exists(root)) + { Directory.Delete(root, true); + } } } @@ -52,18 +54,22 @@ public void FilesReadTheCompleteDocumentWhileADeleteAccessHandleRemainsOpen() { File.WriteAllBytes(path, expected); using (var renameHandle = new FileStream( - path, - FileMode.Open, - FileAccess.Read, - FileShare.Read | FileShare.Delete, - 4096, - FileOptions.DeleteOnClose)) - { + path, + FileMode.Open, + FileAccess.Read, + FileShare.Read | FileShare.Delete, + 4096, + FileOptions.DeleteOnClose + )) { if (OperatingSystem.IsWindows()) + { Assert.ThrowsAny(() => File.ReadAllBytes(path)); + } var store = new FileByteDocumentStore(path); for (int read = 0; read < 16; read++) + { Assert.Equal(expected, store.Read()); + } Assert.True(File.Exists(path)); } Assert.False(File.Exists(path)); diff --git a/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs b/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs index 21f3f704f..7f109622f 100644 --- a/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs +++ b/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs @@ -18,8 +18,12 @@ public async Task WaitingAndHoldingParticipantsKeepTheOwnerGateUntilTheLeafIsRel string leaf = Path.Combine(m_root, "generation.lock"); using FileLease producer = await FileLease.AcquireAsync(leaf, TimeSpan.Zero); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - Task waiting = CoordinatedFileLease.AcquireAsync(owner, leaf, - Timeout.InfiniteTimeSpan, cancellationToken: cancellation.Token).AsTask(); + Task waiting = CoordinatedFileLease.AcquireAsync( + owner, + leaf, + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation.Token + ).AsTask(); Assert.False(waiting.IsCompleted); await Assert.ThrowsAsync(async () => { @@ -33,7 +37,9 @@ await Assert.ThrowsAsync(async () => }); acquired.Dispose(); using (FileLease retirement = await FileLease.AcquireAsync(owner, TimeSpan.Zero)) + { File.Delete(leaf); + } Assert.True(File.Exists(owner)); using CoordinatedFileLease next = await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero); } @@ -60,8 +66,7 @@ public async Task SharedReadersPreventOwnerRetirementAndExclusiveLeafAccess() using CoordinatedFileLease second = await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero, shared: true); await Assert.ThrowsAsync(async () => await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero)); - await Assert.ThrowsAsync(async () => - await FileLease.AcquireAsync(owner, TimeSpan.Zero)); + await Assert.ThrowsAsync(async () => await FileLease.AcquireAsync(owner, TimeSpan.Zero)); } [Fact] @@ -78,6 +83,8 @@ await Assert.ThrowsAnyAsync(async () => public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs index b0b98ae2d..ac2e22fec 100644 --- a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Core.IO.Tests; @@ -45,7 +45,7 @@ public async Task TimeoutAndCancellationDoNotReleaseAnotherOwner() string path = Path.Combine(m_root, "output.lock"); using FileLease owner = await FileLease.AcquireAsync(path, TimeSpan.Zero); await Assert.ThrowsAsync(() => FileLease.AcquireAsync(path, TimeSpan.Zero).AsTask()); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); Task waiting = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation.Token).AsTask(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => waiting); @@ -58,15 +58,19 @@ public async Task InvalidRequestsAndPriorCancellationHaveNoFilesystemEffects() await Assert.ThrowsAsync(() => FileLease.AcquireAsync("relative.lock", TimeSpan.Zero).AsTask()); string path = Path.Combine(m_root, "output.lock"); await Assert.ThrowsAsync(() => FileLease.AcquireAsync(path, TimeSpan.FromSeconds(-2)).AsTask()); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => FileLease.AcquireAsync(path, TimeSpan.Zero, cancellation.Token).AsTask()); + await Assert.ThrowsAnyAsync( + () => FileLease.AcquireAsync(path, TimeSpan.Zero, cancellation.Token).AsTask() + ); Assert.False(Directory.Exists(m_root)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs index 84c25c5ef..7fedec68b 100644 --- a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs @@ -1,12 +1,11 @@ using System; using System.Diagnostics; using System.IO; -using System.Runtime.ExceptionServices; using System.Linq; +using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using System.Text; using System.Threading; - using Xunit; using Xunit.Abstractions; @@ -14,10 +13,7 @@ namespace Inno.Core.IO.Tests; public sealed class FileSystemSafetyTests : IDisposable { - private readonly string m_root = Path.Combine( - Path.GetTempPath(), - "InnoCoreIoTests", - Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoCoreIoTests", Guid.NewGuid().ToString("N")); private readonly ITestOutputHelper m_output; @@ -74,9 +70,7 @@ public void PathBoundaryRejectsAbsoluteAndParentTraversalPaths() { Assert.Throws(() => PathBoundary.Resolve(m_root, Path.Combine(m_root, "absolute"))); Assert.Throws(() => PathBoundary.Resolve(m_root, "../escape")); - Assert.Equal( - Path.Combine(m_root, "Assets", "item.inno"), - PathBoundary.Resolve(m_root, "Assets/item.inno")); + Assert.Equal(Path.Combine(m_root, "Assets", "item.inno"), PathBoundary.Resolve(m_root, "Assets/item.inno")); } [Fact] @@ -134,7 +128,9 @@ public void DirectoryInstallReplacesACompleteTreeWithoutLeavingBackupDirectories /// /// Rejects canceled installation before creating parents or modifying either owned tree. /// - /// Whether a previous destination is already present. + /// + /// Whether a previous destination is already present. + /// [Theory] [InlineData(false)] [InlineData(true)] @@ -156,9 +152,13 @@ public void DirectoryInstallPriorCancellationPreservesBothOwners(bool existing) Assert.Equal("current", File.ReadAllText(Path.Combine(candidate, "current.txt"))); if (existing) + { Assert.Equal("previous", File.ReadAllText(Path.Combine(destination, "previous.txt"))); + } else + { Assert.False(Directory.Exists(Path.GetDirectoryName(destination))); + } Assert.Empty(Directory.EnumerateDirectories(m_root, "*.backup-*", SearchOption.AllDirectories)); } @@ -168,22 +168,31 @@ public void DirectoryInstallPriorCancellationPreservesBothOwners(bool existing) public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRename() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Directory.CreateDirectory(Path.Combine(m_root, "destination")).FullName; string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "current"); File.WriteAllText(Path.Combine(destination, "previous.txt"), "previous"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); bool evacuated = false; - ObserveBlockedRename(() => { - evacuated = !Directory.Exists(destination); - cancellation.Cancel(); - }, () => { - var failure = Assert.ThrowsAny(() => AtomicDirectory.Install(candidate, destination, cancellation.Token)); - Assert.Equal(cancellation.Token, failure.CancellationToken); - }); + ObserveBlockedRename( + () => + { + evacuated = !Directory.Exists(destination); + cancellation.Cancel(); + }, + () => + { + OperationCanceledException failure = Assert.ThrowsAny( + () => AtomicDirectory.Install(candidate, destination, cancellation.Token) + ); + Assert.Equal(cancellation.Token, failure.CancellationToken); + } + ); Assert.True(evacuated); Assert.Equal("previous", File.ReadAllText(Path.Combine(destination, "previous.txt"))); Assert.Equal("current", File.ReadAllText(file)); @@ -200,41 +209,20 @@ public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRen [Trait("ProcessIsolation", "Required")] public void DirectoryPublicationObservesPendingCancellationAtTheDeadline() => VerifyBlockedCancellation(true); - [SupportedOSPlatform("windows")] - private void VerifyBlockedCancellation(bool expireWindow) - { - if (!OperatingSystem.IsWindows()) - return; - string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; - string destination = Path.Combine(m_root, "published"); - string file = Path.Combine(candidate, "value.txt"); - File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); - using var cancellation = new CancellationTokenSource(); - ObserveBlockedRename(() => { - cancellation.Cancel(); - if (expireWindow) - Thread.Sleep(TimeSpan.FromMilliseconds(2100)); - }, () => { - var failure = Assert.ThrowsAny(() => AtomicDirectory.Publish(candidate, destination, cancellation.Token)); - Assert.Equal(cancellation.Token, failure.CancellationToken); - }); - Assert.Equal("complete", File.ReadAllText(file)); - Assert.False(Directory.Exists(destination)); - } - [Fact] [SupportedOSPlatform("windows")] [Trait("ProcessIsolation", "Required")] public void DirectoryPublicationToleratesATemporaryWindowsReaderWithoutDeleteSharing() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); ObserveBlockedRename(reader.Dispose, () => AtomicDirectory.Publish(candidate, destination, cancellation.Token)); cancellation.Cancel(); @@ -247,12 +235,14 @@ public void DirectoryPublicationToleratesATemporaryWindowsReaderWithoutDeleteSha public void PersistentReaderPreservesCandidateAndReturnsWindowsError() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); Exception? failure = Record.Exception(() => AtomicDirectory.Publish(candidate, destination)); Assert.True(failure is IOException or UnauthorizedAccessException && IsSharingError(failure)); Assert.False(Directory.Exists(destination)); @@ -271,49 +261,14 @@ public void DirectoryPublicationPreservesAnExistingOwner() Assert.Equal("complete", File.ReadAllText(Path.Combine(candidate, "value.txt"))); } - private static bool IsSharingError(Exception exception) - => exception.HResult is unchecked((int)0x80070005) or unchecked((int)0x80070020) or unchecked((int)0x80070021); - - private void ObserveBlockedRename( - Action onBlocked, - Action operation - ) { - // The isolated test intercepts the actual Windows denial before the production catch filter runs. - int thread = Environment.CurrentManagedThreadId; - var clock = Stopwatch.StartNew(); - long blocked = -1; - long resumed = -1; - int hresult = 0; - void Observe( - object? sender, - FirstChanceExceptionEventArgs args - ) { - if (Environment.CurrentManagedThreadId != thread || blocked >= 0 || !IsSharingError(args.Exception)) - return; - blocked = clock.ElapsedMilliseconds; - hresult = args.Exception.HResult; - onBlocked(); - resumed = clock.ElapsedMilliseconds; - } - AppDomain.CurrentDomain.FirstChanceException += Observe; - try - { - operation(); - } - finally - { - AppDomain.CurrentDomain.FirstChanceException -= Observe; - m_output.WriteLine($"Rename worker started at 0 ms, denied at {blocked} ms, intervention completed at {resumed} ms, exited at {clock.ElapsedMilliseconds} ms, HRESULT 0x{hresult:X8}."); - } - Assert.True(blocked >= 0, "Expected an actual Windows sharing failure on the publishing thread."); - } - [Fact] [SupportedOSPlatform("windows")] public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Path.Combine(m_root, "candidate"); string destination = Path.Combine(m_root, "destination"); @@ -325,7 +280,9 @@ public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() File.SetAttributes(lockedFile, FileAttributes.ReadOnly); try { - DirectoryCleanupException failure = Assert.Throws(() => AtomicDirectory.Install(candidate, destination)); + DirectoryCleanupException failure = Assert.Throws( + () => AtomicDirectory.Install(candidate, destination) + ); Assert.Contains("installed", failure.Message, StringComparison.OrdinalIgnoreCase); Assert.Equal("current", File.ReadAllText(Path.Combine(destination, "current.txt"))); @@ -338,7 +295,9 @@ public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() finally { foreach (string retained in Directory.EnumerateFiles(m_root, "locked.txt", SearchOption.AllDirectories)) + { File.SetAttributes(retained, FileAttributes.Normal); + } } } @@ -365,7 +324,9 @@ public void DirectoryInstallRejectsOverlappingTreesBeforeChangingEitherOwner() public void DirectoryInstallRestoresThePreviousTreeWhenTheCandidateCannotMove() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Path.Combine(m_root, "candidate"); string destination = Path.Combine(m_root, "destination"); @@ -398,6 +359,83 @@ public void PathBoundaryAcceptsChildrenOfAVolumeRoot() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } + } + + [SupportedOSPlatform("windows")] + private void VerifyBlockedCancellation(bool expireWindow) + { + if (!OperatingSystem.IsWindows()) + { + return; + } + string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; + string destination = Path.Combine(m_root, "published"); + string file = Path.Combine(candidate, "value.txt"); + File.WriteAllText(file, "complete"); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using var cancellation = new CancellationTokenSource(); + ObserveBlockedRename( + () => + { + cancellation.Cancel(); + if (expireWindow) + { + Thread.Sleep(TimeSpan.FromMilliseconds(2100)); + } + }, + () => + { + OperationCanceledException failure = Assert.ThrowsAny( + () => AtomicDirectory.Publish(candidate, destination, cancellation.Token) + ); + Assert.Equal(cancellation.Token, failure.CancellationToken); + } + ); + Assert.Equal("complete", File.ReadAllText(file)); + Assert.False(Directory.Exists(destination)); + } + + private void ObserveBlockedRename( + Action onBlocked, + Action operation + ) { + // The isolated test intercepts the actual Windows denial before the production catch filter runs. + int thread = Environment.CurrentManagedThreadId; + Stopwatch clock = Stopwatch.StartNew(); + long blocked = -1; + long resumed = -1; + int hresult = 0; + void Observe( + object? sender, + FirstChanceExceptionEventArgs args + ) { + if (Environment.CurrentManagedThreadId != thread || blocked >= 0 || !IsSharingError(args.Exception)) + { + return; + } + blocked = clock.ElapsedMilliseconds; + hresult = args.Exception.HResult; + onBlocked(); + resumed = clock.ElapsedMilliseconds; + } + AppDomain.CurrentDomain.FirstChanceException += Observe; + try + { + operation(); + } + finally + { + AppDomain.CurrentDomain.FirstChanceException -= Observe; + m_output.WriteLine( + $"Rename worker started at 0 ms, denied at {blocked} ms, intervention completed at {resumed} ms, exited at {clock.ElapsedMilliseconds} ms, HRESULT 0x{hresult:X8}." + ); + } + Assert.True(blocked >= 0, "Expected an actual Windows sharing failure on the publishing thread."); } + + private static bool IsSharingError(Exception exception) + => exception.HResult is unchecked((int)0x8007_0005) or unchecked((int)0x8007_0020) or unchecked((int)0x8007_0021); } diff --git a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs index cf9e94fe2..69699f95f 100644 --- a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs +++ b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs @@ -9,7 +9,7 @@ public sealed class OwnedReadStreamTests [Fact] public void ReaderClosesBeforeItsIndependentOwnerAndReleaseCanBeRetried() { - var input = new MemoryStream(new byte[] { 1, 2, 3 }); + var input = new MemoryStream([1, 2, 3]); var pin = new Pin(input); var reader = new OwnedReadStream(input, pin); Assert.Equal(1, reader.ReadByte()); @@ -31,7 +31,9 @@ public void Dispose() { Assert.False(input.CanRead); if (++releases == 1) + { throw new IOException("Expected retryable release."); + } } } } diff --git a/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs b/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs index d164496a2..41ed17369 100644 --- a/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs +++ b/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs @@ -21,7 +21,9 @@ public void ReadingResolutionDoesNotCreateMissingEntriesOrGrantOwnership() Assert.Equal(resolved, resolver.Resolve(file)); Assert.Equal(resolved, new PhysicalPathResolver().Resolve(resolved)); for (string? entry = resolved; entry is not null; entry = Path.GetDirectoryName(entry)) + { Assert.False(File.GetAttributes(entry).HasFlag(FileAttributes.ReparsePoint), entry); + } string owner = Path.Combine(Path.GetDirectoryName(resolved)!, "Owned"); Assert.Throws(() => PathBoundary.RequireContained(owner, resolved)); Assert.False(Directory.Exists(owner)); @@ -34,6 +36,8 @@ public void ReadingResolutionDoesNotCreateMissingEntriesOrGrantOwnership() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs index d927a4932..9ea177edf 100644 --- a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs +++ b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Core.Identity; using Xunit; +using Inno.Core.Identity; namespace Inno.Core.Identity.Tests; @@ -8,88 +8,57 @@ public sealed class IdentityAllocatorTests { private readonly IdentityAllocator m_allocator = new(); - private static void AssertRuntimeIdNotNull(IdentityObject target) - => Assert.NotNull(target.identity.runtimeId); - - private static void AssertRuntimeIdIsNull(IdentityObject target) - => Assert.Null(target.identity.runtimeId); - - private static int UnpackSlot(int runtimeId) - => runtimeId & 0x000F_FFFF; - - private static int UnpackGeneration(int runtimeId) - => (runtimeId >> 20) & 0x0000_0FFF; - - private static Identity GetIdentity(IdentityObject target) - => target.identity; - - private WeakReference CreateRegisteredEntity(out int runtimeId) - { - Entity entity = new(); - m_allocator.Register(entity); - runtimeId = GetIdentity(entity).runtimeId!.Value; - return new WeakReference(entity); - } - - private sealed class Entity : IdentityObject - { - } - - private sealed class UnrelatedEntity : IdentityObject - { - } - [Fact] - public void GetIdentity_DoesNotAutoRegisterObject() + public void GetIdentityDoesNotAutoRegisterObject() { var entity = new Entity(); Identity identity = GetIdentity(entity); - Assert.NotEqual(Guid.Empty, identity.persistentId); - Assert.Null(identity.runtimeId); + Assert.NotEqual(Guid.Empty, identity.persistentID); + Assert.Null(identity.runtimeID); } [Fact] - public void InitializePersistentIdentity_AssignsDetachedIdentityWithoutUnregisterEvent() + public void InitializePersistentIdentityAssignsDetachedIdentityWithoutUnregisterEvent() { var entity = new Entity(); - Guid persistentId = Guid.NewGuid(); + Guid persistentID = Guid.NewGuid(); int unregisteredCount = 0; void OnUnregistered(IdentityObject _) => unregisteredCount++; - m_allocator.ObjectUnregistered += OnUnregistered; + m_allocator.objectUnregistered += OnUnregistered; try { - m_allocator.InitializePersistentIdentity(entity, persistentId); + m_allocator.InitializePersistentIdentity(entity, persistentID); - Assert.Equal(persistentId, GetIdentity(entity).persistentId); - Assert.Null(GetIdentity(entity).runtimeId); + Assert.Equal(persistentID, GetIdentity(entity).persistentID); + Assert.Null(GetIdentity(entity).runtimeID); Assert.Equal(0, unregisteredCount); } finally { - m_allocator.ObjectUnregistered -= OnUnregistered; + m_allocator.objectUnregistered -= OnUnregistered; } } [Fact] - public void Register_AndGet_ByRuntimeId_AndPersistentId_AndExplicitPersistentOverride() + public void RegisterAndGetByRuntimeIDAndPersistentIDAndExplicitPersistentOverride() { var entity = new Entity(); Assert.True(m_allocator.Register(entity, Guid.Parse("11111111-1111-1111-1111-111111111111"))); - AssertRuntimeIdNotNull(entity); + AssertRuntimeIDNotNull(entity); Identity identity = GetIdentity(entity); - Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), identity.persistentId); - int runtimeId = identity.runtimeId!.Value; - Assert.Same(entity, m_allocator.Get(runtimeId)); - Assert.Same(entity, m_allocator.Get(identity.persistentId)); - Assert.Same(entity, m_allocator.Get(runtimeId)); - Assert.Null(m_allocator.Get(runtimeId)); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), identity.persistentID); + int runtimeID = identity.runtimeID!.Value; + Assert.Same(entity, m_allocator.Get(runtimeID)); + Assert.Same(entity, m_allocator.Get(identity.persistentID)); + Assert.Same(entity, m_allocator.Get(runtimeID)); + Assert.Null(m_allocator.Get(runtimeID)); } [Fact] - public void RuntimeIdentity_RejectsAnEqualNumericIdFromAnotherDomain() + public void RuntimeIdentityRejectsAnEqualNumericIDFromAnotherDomain() { var first = new Entity(); var second = new Entity(); @@ -100,38 +69,38 @@ public void RuntimeIdentity_RejectsAnEqualNumericIdFromAnotherDomain() RuntimeIdentity firstIdentity = first.identity.runtimeIdentity!.Value; RuntimeIdentity secondIdentity = second.identity.runtimeIdentity!.Value; - Assert.Equal(firstIdentity.runtimeId, secondIdentity.runtimeId); - Assert.NotEqual(firstIdentity.domainId, secondIdentity.domainId); + Assert.Equal(firstIdentity.runtimeID, secondIdentity.runtimeID); + Assert.NotEqual(firstIdentity.domainID, secondIdentity.domainID); Assert.Same(first, m_allocator.Get(firstIdentity)); Assert.Null(m_allocator.Get(secondIdentity)); } [Fact] - public void Register_ReturnsFalse_WhenAlreadyRegistered() + public void RegisterReturnsFalseWhenAlreadyRegistered() { var entity = new Entity(); Assert.True(m_allocator.Register(entity)); - int firstRuntimeId = GetIdentity(entity).runtimeId!.Value; + int firstRuntimeID = GetIdentity(entity).runtimeID!.Value; Assert.False(m_allocator.Register(entity)); - Assert.Equal(firstRuntimeId, GetIdentity(entity).runtimeId); + Assert.Equal(firstRuntimeID, GetIdentity(entity).runtimeID); } [Fact] - public void Unregister_RemovesRuntimeId_AndGetReturnsNull() + public void UnregisterRemovesRuntimeIDAndGetReturnsNull() { var entity = new Entity(); m_allocator.Register(entity); - int runtimeId = GetIdentity(entity).runtimeId!.Value; + int runtimeID = GetIdentity(entity).runtimeID!.Value; Assert.True(m_allocator.Unregister(entity)); - AssertRuntimeIdIsNull(entity); - Assert.Null(m_allocator.Get(runtimeId)); + AssertRuntimeIDIsNull(entity); + Assert.Null(m_allocator.Get(runtimeID)); Assert.Null(m_allocator.Get(Guid.Empty)); } [Fact] - public void Unregister_EventRunsAfterRemoval_InvokesEveryHandler_AndAggregatesFailures() + public void UnregisterEventRunsAfterRemovalInvokesEveryHandlerAndAggregatesFailures() { var entity = new Entity(); Assert.True(m_allocator.Register(entity)); @@ -141,8 +110,8 @@ public void Unregister_EventRunsAfterRemoval_InvokesEveryHandler_AndAggregatesFa void FailingHandler(IdentityObject removed) { Assert.Same(entity, removed); - Assert.Null(GetIdentity(removed).runtimeId); - Assert.Null(m_allocator.Get(identity.persistentId)); + Assert.Null(GetIdentity(removed).runtimeID); + Assert.Null(m_allocator.Get(identity.persistentID)); throw new InvalidOperationException("expected handler failure"); } @@ -152,69 +121,67 @@ void SuccessfulHandler(IdentityObject removed) successfulHandlers++; } - m_allocator.ObjectUnregistered += FailingHandler; - m_allocator.ObjectUnregistered += SuccessfulHandler; + m_allocator.objectUnregistered += FailingHandler; + m_allocator.objectUnregistered += SuccessfulHandler; try { - AggregateException exception = Assert.Throws( - () => m_allocator.Unregister(entity)); + AggregateException exception = Assert.Throws(() => m_allocator.Unregister(entity)); Assert.Single(exception.InnerExceptions); Assert.Equal(1, successfulHandlers); - Assert.Null(GetIdentity(entity).runtimeId); + Assert.Null(GetIdentity(entity).runtimeID); } finally { - m_allocator.ObjectUnregistered -= FailingHandler; - m_allocator.ObjectUnregistered -= SuccessfulHandler; + m_allocator.objectUnregistered -= FailingHandler; + m_allocator.objectUnregistered -= SuccessfulHandler; } } [Fact] - public void SlotReuse_ChangesGeneration_WhenReRegistered() + public void SlotReuseChangesGenerationWhenReRegistered() { var first = new Entity(); m_allocator.Register(first); - int firstRuntimeId = GetIdentity(first).runtimeId!.Value; + int firstRuntimeID = GetIdentity(first).runtimeID!.Value; Assert.True(m_allocator.Unregister(first)); - Assert.Null(m_allocator.Get(firstRuntimeId)); + Assert.Null(m_allocator.Get(firstRuntimeID)); var second = new Entity(); m_allocator.Register(second); - int secondRuntimeId = GetIdentity(second).runtimeId!.Value; + int secondRuntimeID = GetIdentity(second).runtimeID!.Value; - Assert.Equal(UnpackSlot(firstRuntimeId), UnpackSlot(secondRuntimeId)); - Assert.NotEqual(UnpackGeneration(firstRuntimeId), UnpackGeneration(secondRuntimeId)); - Assert.Same(second, m_allocator.Get(secondRuntimeId)); + Assert.Equal(UnpackSlot(firstRuntimeID), UnpackSlot(secondRuntimeID)); + Assert.NotEqual(UnpackGeneration(firstRuntimeID), UnpackGeneration(secondRuntimeID)); + Assert.Same(second, m_allocator.Get(secondRuntimeID)); } [Fact] - public void Register_RequiresUniquePersistentId() + public void RegisterRequiresUniquePersistentID() { - Guid fixedId = Guid.NewGuid(); + Guid fixedID = Guid.NewGuid(); var first = new Entity(); - Assert.True(m_allocator.Register(first, fixedId)); + Assert.True(m_allocator.Register(first, fixedID)); var second = new Entity(); - Assert.Throws(() => m_allocator.Register(second, fixedId)); + Assert.Throws(() => m_allocator.Register(second, fixedID)); } [Fact] - public void Get_ReturnsNull_ForInvalidLookupKeys() + public void GetReturnsNullForInvalidLookupKeys() { Assert.Null(m_allocator.Get(int.MaxValue)); Assert.Null(m_allocator.Get(Guid.Empty)); } [Fact] - public void RegisteredIdentity_DoesNotPreventGarbageCollection() + public void RegisteredIdentityDoesNotPreventGarbageCollection() { - - int runtimeId; + int runtimeID; WeakReference weakEntity; - weakEntity = CreateRegisteredEntity(out runtimeId); + weakEntity = CreateRegisteredEntity(out runtimeID); for (int i = 0; i < 8; i++) { @@ -231,6 +198,28 @@ public void RegisteredIdentity_DoesNotPreventGarbageCollection() } Assert.False(weakEntity.TryGetTarget(out _)); - Assert.Null(m_allocator.Get(runtimeId)); + Assert.Null(m_allocator.Get(runtimeID)); + } + + private WeakReference CreateRegisteredEntity(out int runtimeID) + { + var entity = new Entity(); + m_allocator.Register(entity); + runtimeID = GetIdentity(entity).runtimeID!.Value; + return new WeakReference(entity); } + + private static void AssertRuntimeIDNotNull(IdentityObject target) => Assert.NotNull(target.identity.runtimeID); + + private static void AssertRuntimeIDIsNull(IdentityObject target) => Assert.Null(target.identity.runtimeID); + + private static int UnpackSlot(int runtimeID) => runtimeID & 0x000F_FFFF; + + private static int UnpackGeneration(int runtimeID) => (runtimeID >> 20) & 0x0000_0FFF; + + private static Identity GetIdentity(IdentityObject target) => target.identity; + + private sealed class Entity : IdentityObject; + + private sealed class UnrelatedEntity : IdentityObject; } diff --git a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs index c4607c1ca..29fa6b49c 100644 --- a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs +++ b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs @@ -2,100 +2,99 @@ using System.Diagnostics; using System.Threading; using Xunit; - using Inno.Core.Jobs; - namespace Inno.Core.JobsSystem.Tests; public sealed class JobSystemPerformanceTests { [Fact] - public void SameScheduleFlow_MoreWorkersIsFasterThanSingleWorker() + public void SameScheduleFlowMoreWorkersIsFasterThanSingleWorker() { Assert.True(Environment.ProcessorCount >= 2, "Worker scaling measurements require at least two logical processors."); - const int jobCount = 64; - const int sleepMilliseconds = 4; - var multiWorkerCount = Math.Min(4, Environment.ProcessorCount); + const int C_JOB_COUNT = 64; + const int C_SLEEP_MILLISECONDS = 4; + int multiWorkerCount = Math.Min(4, Environment.ProcessorCount); - using var oneWorker = CreateWorkStealing(1); - using var multiWorker = CreateWorkStealing(multiWorkerCount); + using JobScheduler oneWorker = CreateWorkStealing(1); + using JobScheduler multiWorker = CreateWorkStealing(multiWorkerCount); _ = MeasureScheduleAndCompleteAll(oneWorker, 8, 1); _ = MeasureScheduleAndCompleteAll(multiWorker, 8, 1); - var oneWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(oneWorker, jobCount, sleepMilliseconds)); - var multiWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multiWorker, jobCount, sleepMilliseconds)); + TimeSpan oneWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(oneWorker, C_JOB_COUNT, C_SLEEP_MILLISECONDS)); + TimeSpan multiWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multiWorker, C_JOB_COUNT, C_SLEEP_MILLISECONDS)); Assert.True( multiWorkerBest < oneWorkerBest, - $"Expected same schedule flow to be faster with more workers. oneWorker={oneWorkerBest.TotalMilliseconds:F2}ms, multiWorker={multiWorkerBest.TotalMilliseconds:F2}ms, workers={multiWorkerCount}"); + $"Expected same schedule flow to be faster with more workers. oneWorker={oneWorkerBest.TotalMilliseconds:F2}ms, multiWorker={multiWorkerBest.TotalMilliseconds:F2}ms, workers={multiWorkerCount}" + ); } [Fact] - public void WorkStealingScheduleCompleteAll_IsFasterThanSingleThread() + public void WorkStealingScheduleCompleteAllIsFasterThanSingleThread() { Assert.True(Environment.ProcessorCount >= 2, "Worker scaling measurements require at least two logical processors."); - const int jobCount = 48; - const int sleepMilliseconds = 4; - var workerCount = Math.Min(4, Environment.ProcessorCount); + const int C_JOB_COUNT = 48; + const int C_SLEEP_MILLISECONDS = 4; + int workerCount = Math.Min(4, Environment.ProcessorCount); using var single = new JobScheduler(JobExecutionMode.SingleThread); - using var multi = CreateWorkStealing(workerCount); + using JobScheduler multi = CreateWorkStealing(workerCount); _ = MeasureScheduleAndCompleteAll(single, 8, 1); _ = MeasureScheduleAndCompleteAll(multi, 8, 1); - var singleBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(single, jobCount, sleepMilliseconds)); - var multiBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multi, jobCount, sleepMilliseconds)); + TimeSpan singleBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(single, C_JOB_COUNT, C_SLEEP_MILLISECONDS)); + TimeSpan multiBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multi, C_JOB_COUNT, C_SLEEP_MILLISECONDS)); Assert.True( multiBest < singleBest, - $"Expected work-stealing to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}"); + $"Expected work-stealing to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}" + ); } [Fact] - public void WorkStealingParallelFor_IsFasterThanSingleThread() + public void WorkStealingParallelForIsFasterThanSingleThread() { Assert.True(Environment.ProcessorCount >= 2, "Worker scaling measurements require at least two logical processors."); - const int length = 48; - const int batchSize = 1; - const int sleepMilliseconds = 4; - var workerCount = Math.Min(4, Environment.ProcessorCount); + const int C_LENGTH = 48; + const int C_BATCH_SIZE = 1; + const int C_SLEEP_MILLISECONDS = 4; + int workerCount = Math.Min(4, Environment.ProcessorCount); using var single = new JobScheduler(JobExecutionMode.SingleThread); - using var multi = CreateWorkStealing(workerCount); + using JobScheduler multi = CreateWorkStealing(workerCount); _ = MeasureParallelFor(single, 8, 1, 1); _ = MeasureParallelFor(multi, 8, 1, 1); - var singleBest = MeasureBestOf(3, () => MeasureParallelFor(single, length, batchSize, sleepMilliseconds)); - var multiBest = MeasureBestOf(3, () => MeasureParallelFor(multi, length, batchSize, sleepMilliseconds)); + TimeSpan singleBest = MeasureBestOf(3, () => MeasureParallelFor(single, C_LENGTH, C_BATCH_SIZE, C_SLEEP_MILLISECONDS)); + TimeSpan multiBest = MeasureBestOf(3, () => MeasureParallelFor(multi, C_LENGTH, C_BATCH_SIZE, C_SLEEP_MILLISECONDS)); Assert.True( multiBest < singleBest, - $"Expected work-stealing parallel-for to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}"); + $"Expected work-stealing parallel-for to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}" + ); } private static JobScheduler CreateWorkStealing(int workerCount) - { - return new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions + => new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { workerCount = workerCount }); - } private static TimeSpan MeasureBestOf( int runs, Func measure ) { - var best = TimeSpan.MaxValue; - for (var i = 0; i < runs; i++) + TimeSpan best = TimeSpan.MaxValue; + for (int i = 0; i < runs; i++) { - var current = measure(); + TimeSpan current = measure(); if (current < best) { best = current; @@ -113,8 +112,8 @@ int sleepMilliseconds jobs.BeginFrame(); var handles = new JobHandle[jobCount]; - var stopwatch = Stopwatch.StartNew(); - for (var i = 0; i < jobCount; i++) + Stopwatch stopwatch = Stopwatch.StartNew(); + for (int i = 0; i < jobCount; i++) { handles[i] = jobs.Schedule(() => Thread.Sleep(sleepMilliseconds)); } @@ -134,8 +133,8 @@ int sleepMilliseconds ) { jobs.BeginFrame(); - var stopwatch = Stopwatch.StartNew(); - var handle = jobs.ParallelFor(length, batchSize, ( + Stopwatch stopwatch = Stopwatch.StartNew(); + JobHandle handle = jobs.ParallelFor(length, batchSize, ( _, _ ) => Thread.Sleep(sleepMilliseconds)); diff --git a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs index 584fad7da..9444180d3 100644 --- a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs +++ b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs @@ -4,10 +4,9 @@ using System.Threading; using System.Threading.Tasks; using Xunit; - +using Inno.Core.Execution; using Inno.Core.Jobs; - namespace Inno.Core.JobsSystem.Tests; public sealed class JobSystemBehaviorTests @@ -22,11 +21,17 @@ public void FrameAdmissionRemainsAtomicUnderRepeatedInvalidAndOversizedRequests( for (int frame = 0; frame < 256; frame++) { jobs.BeginFrame(); - Assert.Throws(() => jobs.Schedule(_ => { }, null, new JobHandle[] { default })); + Assert.Throws(() => jobs.Schedule(_ => {}, null, [default])); Assert.Equal(0, jobs.statistics.frameJobs); - Assert.Throws(() => jobs.ParallelFor(8, 1, (_, _) => Interlocked.Increment(ref completed))); + Assert.Throws(() => jobs.ParallelFor(8, 1, ( + _, + _ + ) => Interlocked.Increment(ref completed))); Assert.Equal(0, jobs.statistics.frameJobs); - for (int index = 0; index < 4; index++) jobs.Schedule(() => Interlocked.Increment(ref completed)); + for (int index = 0; index < 4; index++) + { + jobs.Schedule(() => Interlocked.Increment(ref completed)); + } jobs.EndFrame(); Assert.Equal(0, jobs.statistics.frameJobs); } @@ -42,8 +47,11 @@ public void PendingMainThreadCallbackRemainsOwnedUntilRetry(JobExecutionMode mod { using var jobs = new JobScheduler(mode, new JobSchedulerOptions { workerCount = 1, mainThreadDrainBudget = 1 }); int attempts = 0; - jobs.EnqueueMainThread(() => { if (++attempts == 1) throw new Inno.Core.Execution.RetirementPendingException("pending"); }); - Assert.Throws(jobs.DrainMainThreadQueue); + jobs.EnqueueMainThread(() => + { + if (++attempts == 1) throw new RetirementPendingException("pending"); + }); + Assert.Throws(jobs.DrainMainThreadQueue); Assert.Equal(1, jobs.statistics.mainThreadPending); jobs.DrainMainThreadQueue(); Assert.Equal(2, attempts); @@ -64,33 +72,37 @@ public void CallbackDrainIsBoundedAndDefersRecursivelyEnqueuedWork(JobExecutionM }); int executions = 0; Action? repeat = null; - repeat = () => { executions++; jobs.EnqueueMainThread(repeat!); }; + repeat = () => + { + executions++; + jobs.EnqueueMainThread(repeat!); + }; jobs.EnqueueMainThread(repeat); jobs.EnqueueMainThread(() => executions++); - Assert.Throws(() => jobs.EnqueueMainThread(() => { })); + Assert.Throws(() => jobs.EnqueueMainThread(() => {})); jobs.DrainMainThreadQueue(); Assert.Equal(1, executions); jobs.DrainMainThreadQueue(); Assert.Equal(2, executions); jobs.BeginFrame(); - jobs.Schedule(() => { }); - jobs.Schedule(() => { }); - Assert.Throws(() => jobs.Schedule(() => { })); + jobs.Schedule(() => {}); + jobs.Schedule(() => {}); + Assert.Throws(() => jobs.Schedule(() => {})); jobs.EndFrame(); } [Fact] - public void SingleThread_ExecutesDeterministicallyOnMainThread() + public void SingleThreadExecutesDeterministicallyOnMainThread() { using var jobs = new JobScheduler(JobExecutionMode.SingleThread); jobs.BeginFrame(); - var mainThread = Environment.CurrentManagedThreadId; - var observed = new List(); - var a = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); - var b = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); + int mainThread = Environment.CurrentManagedThreadId; + List observed = []; + JobHandle a = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); + JobHandle b = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); - jobs.CompleteAll(stackalloc[] { a, b }); + jobs.CompleteAll([a, b]); jobs.EndFrame(); Assert.Equal(2, observed.Count); @@ -99,7 +111,7 @@ public void SingleThread_ExecutesDeterministicallyOnMainThread() } [Fact] - public void SingleThread_RejectsCrossThreadUsage() + public void SingleThreadRejectsCrossThreadUsage() { using var jobs = new JobScheduler(JobExecutionMode.SingleThread); jobs.BeginFrame(); @@ -109,7 +121,7 @@ public void SingleThread_RejectsCrossThreadUsage() { try { - _ = jobs.Schedule(() => { }); + _ = jobs.Schedule(() => {}); } catch (Exception ex) { @@ -124,13 +136,13 @@ public void SingleThread_RejectsCrossThreadUsage() } [Fact] - public void WorkStealing_ScheduleAndComplete_RunsJob() + public void WorkStealingScheduleAndCompleteRunsJob() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var value = 0; - var handle = jobs.Schedule(() => value = 7); + int value = 0; + JobHandle handle = jobs.Schedule(() => value = 7); jobs.Complete(handle); jobs.EndFrame(); @@ -138,14 +150,14 @@ public void WorkStealing_ScheduleAndComplete_RunsJob() } [Fact] - public void WorkStealing_ScheduleWithDependencies_RunsInOrder() + public void WorkStealingScheduleWithDependenciesRunsInOrder() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); var order = new ConcurrentQueue(); - var first = jobs.Schedule(() => order.Enqueue(1)); - var second = jobs.Schedule(_ => order.Enqueue(2), null, [first]); + JobHandle first = jobs.Schedule(() => order.Enqueue(1)); + JobHandle second = jobs.Schedule(_ => order.Enqueue(2), null, [first]); jobs.Complete(second); jobs.EndFrame(); @@ -154,15 +166,15 @@ public void WorkStealing_ScheduleWithDependencies_RunsInOrder() } [Fact] - public void WorkStealing_CombineDependencies_CompletesAfterAll() + public void WorkStealingCombineDependenciesCompletesAfterAll() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var sum = 0; - var a = jobs.Schedule(() => Interlocked.Add(ref sum, 3)); - var b = jobs.Schedule(() => Interlocked.Add(ref sum, 4)); - var barrier = jobs.CombineDependencies([a, b]); + int sum = 0; + JobHandle a = jobs.Schedule(() => Interlocked.Add(ref sum, 3)); + JobHandle b = jobs.Schedule(() => Interlocked.Add(ref sum, 4)); + JobHandle barrier = jobs.CombineDependencies([a, b]); jobs.Complete(barrier); jobs.EndFrame(); @@ -171,16 +183,19 @@ public void WorkStealing_CombineDependencies_CompletesAfterAll() } [Fact] - public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() + public void WorkStealingParallelForCoversEveryIndexExactlyOnce() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - const int length = 1024; - var values = new int[length]; - var handle = jobs.ParallelFor(length, 32, (start, end) => + const int C_LENGTH = 1024; + var values = new int[C_LENGTH]; + JobHandle handle = jobs.ParallelFor(C_LENGTH, 32, ( + start, + end + ) => { - for (var i = start; i < end; i++) + for (int i = start; i < end; i++) { Interlocked.Increment(ref values[i]); } @@ -189,33 +204,33 @@ public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() jobs.Complete(handle); jobs.EndFrame(); - for (var i = 0; i < values.Length; i++) + for (int i = 0; i < values.Length; i++) { Assert.Equal(1, values[i]); } } [Fact] - public void WorkStealing_MainThreadQueue_DrainExecutesOnMainThread() + public void WorkStealingMainThreadQueueDrainExecutesOnMainThread() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var mainThread = Environment.CurrentManagedThreadId; - var threadIds = new List(); - jobs.EnqueueMainThread(() => threadIds.Add(Environment.CurrentManagedThreadId)); - jobs.EnqueueMainThread(() => threadIds.Add(Environment.CurrentManagedThreadId)); + int mainThread = Environment.CurrentManagedThreadId; + List threadIDs = []; + jobs.EnqueueMainThread(() => threadIDs.Add(Environment.CurrentManagedThreadId)); + jobs.EnqueueMainThread(() => threadIDs.Add(Environment.CurrentManagedThreadId)); jobs.DrainMainThreadQueue(); jobs.EndFrame(); - Assert.Equal(2, threadIds.Count); - Assert.All(threadIds, id => Assert.Equal(mainThread, id)); + Assert.Equal(2, threadIDs.Count); + Assert.All(threadIDs, id => Assert.Equal(mainThread, id)); } [Fact] - public void WorkStealing_MainThreadQueue_DrainFromWorkerThread_Throws() + public void WorkStealingMainThreadQueueDrainFromWorkerThreadThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); Exception? fault = null; @@ -238,66 +253,66 @@ public void WorkStealing_MainThreadQueue_DrainFromWorkerThread_Throws() } [Fact] - public void WorkStealing_WhenJobThrows_CompleteRethrowsAndEndFrameAggregates() + public void WorkStealingWhenJobThrowsCompleteRethrowsAndEndFrameAggregates() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var handle = jobs.Schedule(() => throw new InvalidOperationException("boom")); - var completeEx = Assert.Throws(() => jobs.Complete(handle)); + JobHandle handle = jobs.Schedule(() => throw new InvalidOperationException("boom")); + InvalidOperationException completeEx = Assert.Throws(() => jobs.Complete(handle)); Assert.IsType(completeEx.InnerException); - var endEx = Assert.Throws(() => jobs.EndFrame()); + AggregateException endEx = Assert.Throws(() => jobs.EndFrame()); Assert.NotEmpty(endEx.InnerExceptions); } [Fact] - public void WorkStealing_EndFrameRecyclesHandle_AndStaleHandleThrows() + public void WorkStealingEndFrameRecyclesHandleAndStaleHandleThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var handle = jobs.Schedule(() => { }); + JobHandle handle = jobs.Schedule(() => {}); jobs.EndFrame(); jobs.BeginFrame(); - var ex = Assert.Throws(() => jobs.Complete(handle)); + InvalidOperationException ex = Assert.Throws(() => jobs.Complete(handle)); jobs.EndFrame(); Assert.Contains("stale", ex.Message, StringComparison.OrdinalIgnoreCase); } [Fact] - public void WorkStealing_ConcurrentSchedulingAcrossThreads_IsStable() + public void WorkStealingConcurrentSchedulingAcrossThreadsIsStable() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); - const int taskCount = 2000; - var count = 0; - Parallel.For(0, taskCount, _ => + const int C_TASK_COUNT = 2000; + int count = 0; + Parallel.For(0, C_TASK_COUNT, _ => { - var handle = jobs.Schedule(() => Interlocked.Increment(ref count)); + JobHandle handle = jobs.Schedule(() => Interlocked.Increment(ref count)); jobs.Complete(handle); }); jobs.EndFrame(); - Assert.Equal(taskCount, count); + Assert.Equal(C_TASK_COUNT, count); } [Fact] - public void WorkStealing_WorkerThreadsParticipateUnderLoad() + public void WorkStealingWorkerThreadsParticipateUnderLoad() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); - var threadIds = new ConcurrentDictionary(); + var threadIDs = new ConcurrentDictionary(); var handles = new JobHandle[256]; - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { handles[i] = jobs.Schedule(() => { - threadIds.TryAdd(Environment.CurrentManagedThreadId, 0); + threadIDs.TryAdd(Environment.CurrentManagedThreadId, 0); Thread.Sleep(1); }); } @@ -305,19 +320,19 @@ public void WorkStealing_WorkerThreadsParticipateUnderLoad() jobs.CompleteAll(handles); jobs.EndFrame(); - Assert.True(threadIds.Count >= 2); + Assert.True(threadIDs.Count >= 2); } [Fact] - public void WorkStealing_NestedScheduleFromWorker_IsSupported() + public void WorkStealingNestedScheduleFromWorkerIsSupported() { - using var jobs = CreateWorkStealing(workerCount: 2); + using JobScheduler jobs = CreateWorkStealing(workerCount: 2); jobs.BeginFrame(); - var value = 0; - var outer = jobs.Schedule(() => + int value = 0; + JobHandle outer = jobs.Schedule(() => { - var inner = jobs.Schedule(() => Interlocked.Add(ref value, 3)); + JobHandle inner = jobs.Schedule(() => Interlocked.Add(ref value, 3)); jobs.Complete(inner); Interlocked.Add(ref value, 2); }); @@ -329,78 +344,80 @@ public void WorkStealing_NestedScheduleFromWorker_IsSupported() } [Fact] - public void WorkStealing_AutoWorkerCount_IsInValidRange() + public void WorkStealingAutoWorkerCountIsInValidRange() { - using var jobs = new JobScheduler( - JobExecutionMode.WorkerPool, - new JobSchedulerOptions { workerCount = 0 }); + using var jobs = new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { workerCount = 0 }); Assert.InRange(jobs.workerCount, 1, 64); } [Fact] - public void WorkStealing_CombineManyDependencies_CompletesReliably() + public void WorkStealingCombineManyDependenciesCompletesReliably() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); - const int count = 300; - var handles = new JobHandle[count]; - var sum = 0; - for (var i = 0; i < count; i++) + const int C_COUNT = 300; + var handles = new JobHandle[C_COUNT]; + int sum = 0; + for (int i = 0; i < C_COUNT; i++) { handles[i] = jobs.Schedule(() => Interlocked.Increment(ref sum)); } - var barrier = jobs.CombineDependencies(handles); + JobHandle barrier = jobs.CombineDependencies(handles); jobs.Complete(barrier); jobs.EndFrame(); - Assert.Equal(count, sum); + Assert.Equal(C_COUNT, sum); } [Fact] - public void CommonApi_EndFrameWithoutBeginFrame_Throws() + public void CommonApiEndFrameWithoutBeginFrameThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); Assert.Throws(() => jobs.EndFrame()); } [Fact] - public void CommonApi_BeginFrameTwice_Throws() + public void CommonApiBeginFrameTwiceThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); Assert.Throws(() => jobs.BeginFrame()); jobs.EndFrame(); } [Fact] - public void CommonApi_ParallelForInvalidArguments_Throws() + public void CommonApiParallelForInvalidArgumentsThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - Assert.Throws(() => jobs.ParallelFor(-1, 8, (_, _) => { })); - Assert.Throws(() => jobs.ParallelFor(1, 0, (_, _) => { })); + Assert.Throws(() => jobs.ParallelFor(-1, 8, ( + _, + _ + ) => {})); + Assert.Throws(() => jobs.ParallelFor(1, 0, ( + _, + _ + ) => {})); jobs.EndFrame(); } [Fact] - public void CommonApi_DisposePreventsFurtherUse() + public void CommonApiDisposePreventsFurtherUse() { - var jobs = CreateWorkStealing(); + JobScheduler jobs = CreateWorkStealing(); jobs.Dispose(); Assert.Throws(() => jobs.BeginFrame()); - Assert.Throws(() => jobs.EnqueueMainThread(() => { })); + Assert.Throws(() => jobs.EnqueueMainThread(() => {})); } private static JobScheduler CreateWorkStealing(int workerCount = 2) + => new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { - return new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions - { - workerCount = workerCount - }); - } + workerCount = workerCount + }); } diff --git a/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs b/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs index 1a7c049d6..cb170c318 100644 --- a/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs +++ b/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs @@ -1,18 +1,16 @@ using System; using System.Collections.Generic; - +using Xunit; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Layers; -using Xunit; - namespace Inno.Core.Layers.Tests; public sealed class LayerStackTests { [Fact] - public void PushLayer_InsertsBelowExistingOverlays() + public void PushLayerInsertsBelowExistingOverlays() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); @@ -31,7 +29,7 @@ public void PushLayer_InsertsBelowExistingOverlays() } [Fact] - public void PushLayer_RejectsDuplicateInstance() + public void PushLayerRejectsDuplicateInstance() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); @@ -45,11 +43,11 @@ public void PushLayer_RejectsDuplicateInstance() } [Fact] - public void EventDispatch_RunsTopmostOverlayFirst() + public void EventDispatchRunsTopmostOverlayFirst() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); - var order = new List(); + List order = []; stack.PushLayer(new ProbeLayer("base", order)); stack.PushOverlay(new ProbeLayer("overlay", order)); @@ -59,11 +57,11 @@ public void EventDispatch_RunsTopmostOverlayFirst() } [Fact] - public void RenderFrame_UnwindsPreparedLayersInReverseOrderAfterFailure() + public void RenderFrameUnwindsPreparedLayersInReverseOrderAfterFailure() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); - var calls = new List(); + List calls = []; stack.PushLayer(new ProbeLayer("first", calls)); stack.PushLayer(new ProbeLayer("second", calls) { throwOnRender = true }); @@ -71,11 +69,12 @@ public void RenderFrame_UnwindsPreparedLayersInReverseOrderAfterFailure() Assert.Equal( ["first.before", "second.before", "first.render", "second.render", "second.after", "first.after"], - calls); + calls + ); } [Fact] - public void PopMethods_RespectBaseAndOverlayRegions() + public void PopMethodsRespectBaseAndOverlayRegions() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); @@ -93,7 +92,7 @@ public void PopMethods_RespectBaseAndOverlayRegions() } [Fact] - public void FailedAttach_ReleasesSubscriptionsAndLeavesStackReusable() + public void FailedAttachReleasesSubscriptionsAndLeavesStackReusable() { var dispatcher = new EventDispatcher(); using var stack = new LayerStack(() => dispatcher.CreateHub()); @@ -177,32 +176,20 @@ public void CrossStackAttachmentDoesNotDetachTheOriginalOwner() Assert.Equal(0, layer.detachCount); } - private sealed class ProbeEvent : Event - { - } + private sealed class ProbeEvent : Event; private sealed class ProbeLayer : Layer { private readonly List? m_calls; - internal ProbeLayer(string name, List? calls = null) - : base(name) + internal ProbeLayer( + string name, + List? calls = null + ) : base(name) { m_calls = calls; } - internal bool throwOnAttach { get; init; } - - internal bool throwOnRender { get; init; } - - internal bool throwOnDetach { get; init; } - - internal int pendingDetaches { get; set; } - - internal int detachCount { get; private set; } - - internal int eventCount { get; private set; } - public override void OnAttach() { _ = Listen(_ => @@ -211,29 +198,47 @@ public override void OnAttach() m_calls?.Add(name); }); if (throwOnAttach) + { throw new InvalidOperationException("Attach failed."); + } } public override void OnDetach() { detachCount++; if (pendingDetaches-- > 0) + { throw new RetirementPendingException("Expected unfinished layer work."); + } if (throwOnDetach) + { throw new InvalidOperationException("Detach failed."); + } } - public override void OnBeforeRender(float deltaTime) - => m_calls?.Add($"{name}.before"); + public override void OnBeforeRender(float deltaTime) => m_calls?.Add($"{name}.before"); public override void OnRender(float deltaTime) { m_calls?.Add($"{name}.render"); if (throwOnRender) + { throw new InvalidOperationException("Render failed."); + } } - public override void OnAfterRender(float deltaTime) - => m_calls?.Add($"{name}.after"); + public override void OnAfterRender(float deltaTime) => m_calls?.Add($"{name}.after"); + + internal bool throwOnAttach { get; init; } + + internal bool throwOnRender { get; init; } + + internal bool throwOnDetach { get; init; } + + internal int pendingDetaches { get; set; } + + internal int detachCount { get; private set; } + + internal int eventCount { get; private set; } } } diff --git a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs index 8c84feef6..78acc778c 100644 --- a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs @@ -2,10 +2,9 @@ using System.IO; using System.Linq; using System.Threading.Tasks; - +using Xunit; using Inno.Core.Logging; using Inno.Extensibility.Modules; -using Xunit; namespace Inno.Core.Logging.Tests; @@ -16,7 +15,9 @@ public sealed class FileLogSinkTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Theory] @@ -28,7 +29,9 @@ public void RouterFlushMakesCompletedFileWritesObservable(LogDeliveryMode mode) using var sink = new FileLogSink(m_root); router.RegisterSink(sink); for (int index = 0; index < 100; index++) + { router.Dispatch(CreateEntry("visible-" + index)); + } router.Flush(); @@ -43,7 +46,9 @@ public void RapidRotationRetainsTheCurrentEntryAndHonorsTheByteLimit() { using var sink = new FileLogSink(m_root, maxFileSizeBytes: 512, maxFiles: 3); for (int index = 0; index < 120; index++) + { sink.Receive(CreateEntry($"entry-{index:D3}-" + new string('★', 80))); + } string[] files = Directory.GetFiles(m_root, "*.log"); Assert.InRange(files.Length, 1, 3); @@ -57,7 +62,7 @@ public void RapidRotationRetainsTheCurrentEntryAndHonorsTheByteLimit() public void OversizedEntriesRemainCompleteAndRotateBeforeTheNextEntry() { using var sink = new FileLogSink(m_root, maxFileSizeBytes: 128, maxFiles: 2); - string oversized = new('x', 2_000); + var oversized = new string('x', 2_000); sink.Receive(CreateEntry(oversized)); sink.Receive(CreateEntry("next-entry")); @@ -75,7 +80,9 @@ public void MultipleSinksOwnDistinctFilesInTheSameDirectory() try { for (int index = 0; index < sinks.Length; index++) + { sinks[index].Receive(CreateEntry("sink-" + index)); + } string[] files = Directory.GetFiles(m_root, "*.log"); Assert.Equal(sinks.Length, files.Length); @@ -84,7 +91,9 @@ public void MultipleSinksOwnDistinctFilesInTheSameDirectory() finally { foreach (FileLogSink sink in sinks) + { sink.Dispose(); + } } } @@ -173,7 +182,16 @@ private static string ReadContent(string file) return reader.ReadToEnd(); } - private static LogEntry CreateEntry(string message) => new( - LogLevel.Info, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - "file-test", message, string.Empty, 0, string.Empty, LogSessionId.none); + private static LogEntry CreateEntry(string message) + => new( + LogLevel.Info, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + "file-test", + message, + string.Empty, + 0, + string.Empty, + LogSessionID.none + ); } diff --git a/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs b/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs index b18a9af85..c9d14d9bf 100644 --- a/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Core.Logging; using Inno.Extensibility.Modules; -using Xunit; namespace Inno.Core.Logging.Tests; @@ -16,11 +16,15 @@ public void NestedEntriesReachEverySinkInQueueOrder() { using var router = new LogRouter(deliveryMode: LogDeliveryMode.Inline); var received = new ConcurrentQueue(); - router.RegisterSink(new CallbackSink(entry => - { - if (entry.message == "first") - router.Dispatch(CreateEntry("nested")); - })); + router.RegisterSink( + new CallbackSink(entry => + { + if (entry.message == "first") + { + router.Dispatch(CreateEntry("nested")); + } + }) + ); router.RegisterSink(new CallbackSink(entry => received.Enqueue(entry.message))); router.Dispatch(CreateEntry("first")); @@ -36,13 +40,17 @@ public void LongNestedChainsDoNotReenterDelivery() int received = 0; int depth = 0; int maximumDepth = 0; - router.RegisterSink(new CallbackSink(_ => - { - maximumDepth = Math.Max(maximumDepth, ++depth); - if (++received < 10_000) - router.Dispatch(CreateEntry("next")); - depth--; - })); + router.RegisterSink( + new CallbackSink(_ => + { + maximumDepth = Math.Max(maximumDepth, ++depth); + if (++received < 10_000) + { + router.Dispatch(CreateEntry("next")); + } + depth--; + }) + ); router.Dispatch(CreateEntry("first")); @@ -57,11 +65,13 @@ public async Task FlushWaitsForAnEntryAlreadyInsideReceive() using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); using var flushing = new ManualResetEventSlim(); - router.RegisterSink(new CallbackSink(_ => - { - entered.Set(); - Assert.True(release.Wait(TimeSpan.FromSeconds(10))); - })); + router.RegisterSink( + new CallbackSink(_ => + { + entered.Set(); + Assert.True(release.Wait(TimeSpan.FromSeconds(10))); + }) + ); Task producer = Task.Run(() => router.Dispatch(CreateEntry("blocked"))); Assert.True(entered.Wait(TimeSpan.FromSeconds(5))); Task flush = Task.Run(() => @@ -89,20 +99,28 @@ public async Task ConcurrentProducersNeverInvokeASinkConcurrently() int active = 0; int overlap = 0; int received = 0; - router.RegisterSink(new CallbackSink(_ => - { - if (Interlocked.Increment(ref active) != 1) - Interlocked.Increment(ref overlap); - Thread.SpinWait(2_000); - Interlocked.Increment(ref received); - Interlocked.Decrement(ref active); - })); - - await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() => - { - for (int entry = 0; entry < 64; entry++) - router.Dispatch(CreateEntry("parallel")); - }))); + router.RegisterSink( + new CallbackSink(_ => + { + if (Interlocked.Increment(ref active) != 1) + { + Interlocked.Increment(ref overlap); + } + Thread.SpinWait(2_000); + Interlocked.Increment(ref received); + Interlocked.Decrement(ref active); + }) + ); + + await Task.WhenAll( + Enumerable.Range(0, 8).Select(_ => Task.Run(() => + { + for (int entry = 0; entry < 64; entry++) + { + router.Dispatch(CreateEntry("parallel")); + } + })) + ); router.Flush(); Assert.Equal(512, received); @@ -122,12 +140,14 @@ public async Task DisposalWaitsForActiveDeliveryBeforeReleasingTheSink() _, exception ) => deliveryFailure = exception; - router.RegisterSink(new DisposableCallbackSink(_ => - { - entered.Set(); - Assert.True(release.Wait(TimeSpan.FromSeconds(10))); - Assert.False(released); - }, () => released = true)); + router.RegisterSink( + new DisposableCallbackSink(_ => + { + entered.Set(); + Assert.True(release.Wait(TimeSpan.FromSeconds(10))); + Assert.False(released); + }, () => released = true) + ); Task producer = Task.Run(() => router.Dispatch(CreateEntry("blocked"))); Assert.True(entered.Wait(TimeSpan.FromSeconds(5))); Task disposal = Task.Run(() => @@ -157,11 +177,13 @@ public async Task DisposalWaitsForActiveDeliveryBeforeReleasingTheSink() public void DeliveryCallbacksCannotFlushOrDisposeTheirOwnRouter(LogDeliveryMode mode) { using var router = new LogRouter(deliveryMode: mode); - router.RegisterSink(new CallbackSink(_ => - { - Assert.Throws(router.Flush); - Assert.Throws(router.Dispose); - })); + router.RegisterSink( + new CallbackSink(_ => + { + Assert.Throws(router.Flush); + Assert.Throws(router.Dispose); + }) + ); Exception? failure = null; router.sinkFailed += ( _, @@ -174,9 +196,18 @@ public void DeliveryCallbacksCannotFlushOrDisposeTheirOwnRouter(LogDeliveryMode Assert.Null(failure); } - private static LogEntry CreateEntry(string message) => new( - LogLevel.Info, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - "inline-test", message, string.Empty, 0, string.Empty, LogSessionId.none); + private static LogEntry CreateEntry(string message) + => new( + LogLevel.Info, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + "inline-test", + message, + string.Empty, + 0, + string.Empty, + LogSessionID.none + ); private sealed class CallbackSink(Action callback) : ILogSink { diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs index 121979d15..682c4f978 100644 --- a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs @@ -5,16 +5,11 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Core.Logging; - using Xunit; +using Inno.Extensibility.Modules; namespace Inno.Core.Logging.Tests; -[CollectionDefinition("Logging", DisableParallelization = true)] -public sealed class LoggingCollection; - [Collection("Logging")] public sealed class LoggingBehaviorTests : IDisposable { @@ -31,7 +26,7 @@ public LoggingBehaviorTests() public void InlineDeliveryIsImmediateAndQuarantinesAFailingSink() { using var router = new LogRouter(deliveryMode: LogDeliveryMode.Inline); - using var scope = router.EnterScope(); + using IDisposable scope = router.EnterScope(); using var healthy = new ProbeSink(); var failing = new FailingSink(); Exception? failure = null; @@ -58,17 +53,15 @@ public void ExplicitOwnershipAcceptsStaticSourcesAndRejectsMissingTypes() Assert.Throws(() => Log.Info(null!, "Missing source")); m_router.Flush(); LogEntry entry = Assert.Single(sink.entries); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoInternal, entry.domain); + Assert.Equal(AssemblyDomain.InnoInternal, entry.domain); Assert.Equal("Explicit static source", entry.message); m_router.UnregisterSink(sink); } - [Fact] - public void UnknownDeliveryPoliciesFailAtConstruction() - { - Assert.Throws(() => new LogRouter(deliveryMode: (LogDeliveryMode)99)); - } + public void UnknownDeliveryPoliciesFailAtConstruction() => Assert.Throws( + () => new LogRouter(deliveryMode: (LogDeliveryMode)99) + ); [Theory] [InlineData("/build/Game/PlayerBehavior.cs")] @@ -98,14 +91,20 @@ public async Task BrokenFailureReportingCannotStopHealthySinkDelivery( bool failingObserver ) { using var router = new LogRouter(deliveryMode: mode); - using var scope = router.EnterScope(); + using IDisposable scope = router.EnterScope(); using var healthy = new ProbeSink(); var failing = new FailingSink(); int reported = 0; if (failingObserver) { - router.sinkFailed += (_, _) => throw new InvalidOperationException("Expected observer failure."); - router.sinkFailed += (_, _) => reported++; + router.sinkFailed += ( + _, + _ + ) => throw new InvalidOperationException("Expected observer failure."); + router.sinkFailed += ( + _, + _ + ) => reported++; } router.RegisterSink(failing); router.RegisterSink(healthy); @@ -130,7 +129,7 @@ bool failingObserver } [Fact] - public void LogRouter_DispatchesToRegisteredSink() + public void LogRouterDispatchesToRegisteredSink() { using var sink = new ProbeSink(); m_router.RegisterSink(sink); @@ -158,7 +157,7 @@ public void CallSiteIsCapturedForPlainAndFormattedMessagesWithoutMethodReflectio Assert.Equal(nameof(LoggingBehaviorTests), entry.category); Assert.Equal("LoggingBehaviorTests.cs", Path.GetFileName(entry.file)); Assert.True(entry.line > 0); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoInternal, entry.domain); + Assert.Equal(AssemblyDomain.InnoInternal, entry.domain); }); Assert.Equal("plain", sink.entries[0].message); Assert.Equal("formatted-73", sink.entries[1].message); @@ -167,7 +166,7 @@ public void CallSiteIsCapturedForPlainAndFormattedMessagesWithoutMethodReflectio } [Fact] - public void LogRouter_RespectsMinimumLevel() + public void LogRouterRespectsMinimumLevel() { using var sink = new ProbeSink(); m_router.RegisterSink(sink); @@ -243,7 +242,10 @@ public void FailingSinkIsReportedQuarantinedAndDoesNotBlockHealthySinks() using var healthy = new ProbeSink(); ILogSink? reportedSink = null; Exception? reportedFailure = null; - m_router.sinkFailed += (sink, failure) => + m_router.sinkFailed += ( + sink, + failure + ) => { reportedSink = sink; reportedFailure = failure; @@ -263,23 +265,25 @@ public void FailingSinkIsReportedQuarantinedAndDoesNotBlockHealthySinks() } [Fact] - public void FileLogSink_WritesEntriesAndRotates() + public void FileLogSinkWritesEntriesAndRotates() { - var dir = Path.Combine(Path.GetTempPath(), "InnoLoggingTests", Guid.NewGuid().ToString("N")); + string dir = Path.Combine(Path.GetTempPath(), "InnoLoggingTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); using var sink = new FileLogSink(dir, maxFileSizeBytes: 256, maxFiles: 3); m_router.RegisterSink(sink); - for (var i = 0; i < 80; i++) + for (int i = 0; i < 80; i++) + { Log.Warn(typeof(LoggingBehaviorTests), "line-{0}", [i]); + } m_router.Flush(); m_router.UnregisterSink(sink); sink.Dispose(); - var files = Directory.GetFiles(dir, FileLogSink.C_LOG_FILE_PREFIX + "*.log"); - var combined = string.Join(Environment.NewLine, files.Select(File.ReadAllText)); + string[] files = Directory.GetFiles(dir, FileLogSink.C_LOG_FILE_PREFIX + "*.log"); + string combined = string.Join(Environment.NewLine, files.Select(File.ReadAllText)); Assert.Contains("line-79", combined); Assert.True(files.Length <= 3); Assert.All(files, static file => Assert.Equal(".log", Path.GetExtension(file))); @@ -304,13 +308,17 @@ public void Receive(LogEntry entry) m_signal.Set(); } - public bool WaitForCount(int count, TimeSpan timeout) - { - var deadline = DateTime.UtcNow + timeout; + public bool WaitForCount( + int count, + TimeSpan timeout + ) { + DateTime deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { if (m_entries.Count >= count) + { return true; + } m_signal.Wait(TimeSpan.FromMilliseconds(20)); m_signal.Reset(); @@ -319,10 +327,7 @@ public bool WaitForCount(int count, TimeSpan timeout) return m_entries.Count >= count; } - public void Dispose() - { - m_signal.Dispose(); - } + public void Dispose() => m_signal.Dispose(); } private sealed class BrokenErrorWriter : TextWriter @@ -334,14 +339,14 @@ private sealed class BrokenErrorWriter : TextWriter private sealed class FailingSink : ILogSink { - internal int receiveCount { get; private set; } - public void Receive(LogEntry entry) { _ = entry; receiveCount++; throw new InvalidOperationException("Expected sink failure."); } + + internal int receiveCount { get; private set; } } private static class StaticLogSource; diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs b/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs new file mode 100644 index 000000000..a2b50da37 --- /dev/null +++ b/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Core.Logging.Tests; + +[CollectionDefinition("Logging", DisableParallelization = true)] +public sealed class LoggingCollection; diff --git a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs index 027d4c371..54c1b1096 100644 --- a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs +++ b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs @@ -1,15 +1,13 @@ using System; - -using Inno.Core.Mathematics; - using Xunit; +using Inno.Core.Mathematics; namespace Inno.Core.Mathematics.Tests; public sealed class VectorMatrixTests { [Fact] - public void Vector2QuaternionTransform_PreservesLengthForZRotation() + public void Vector2QuaternionTransformPreservesLengthForZRotation() { Quaternion rotation = Quaternion.CreateFromAxisAngle(Vector3.FORWARD, MathF.PI * 0.5f); @@ -21,7 +19,7 @@ public void Vector2QuaternionTransform_PreservesLengthForZRotation() } [Fact] - public void EulerAnglesXYZ_RoundTripsCompoundRotation() + public void EulerAnglesXYZRoundTripsCompoundRotation() { var source = new Vector3(0.31f, -0.47f, 0.83f); @@ -32,26 +30,27 @@ public void EulerAnglesXYZ_RoundTripsCompoundRotation() original.x * roundTrip.x + original.y * roundTrip.y + original.z * roundTrip.z - + original.w * roundTrip.w); + + original.w * roundTrip.w + ); Assert.InRange(alignment, 0.99999f, 1.00001f); } [Fact] - public void Vector2_LengthSquared_MatchesDot() + public void Vector2LengthSquaredMatchesDot() { var v = new Vector2(3f, 4f); - var dot = Vector2.Dot(v, v); + float dot = Vector2.Dot(v, v); Assert.True(MathHelper.AlmostEquals(25f, dot)); Assert.True(MathHelper.AlmostEquals(25f, v.LengthSquared())); Assert.True(MathHelper.AlmostEquals(5f, v.Length())); } [Fact] - public void Vector3_Cross_IsOrthogonal() + public void Vector3CrossIsOrthogonal() { var a = new Vector3(1f, 0f, 0f); var b = new Vector3(0f, 1f, 0f); - var c = Vector3.Cross(a, b); + Vector3 c = Vector3.Cross(a, b); Assert.True(MathHelper.AlmostEquals(0f, Vector3.Dot(a, c))); Assert.True(MathHelper.AlmostEquals(0f, Vector3.Dot(b, c))); @@ -61,11 +60,11 @@ public void Vector3_Cross_IsOrthogonal() } [Fact] - public void Vector3_TransformNormal_IgnoresTranslation() + public void Vector3TransformNormalIgnoresTranslation() { var normal = new Vector3(0f, 1f, 0f); - var translation = Matrix.CreateTranslation(10f, 20f, 30f); - var result = Vector3.TransformNormal(normal, translation); + Matrix translation = Matrix.CreateTranslation(10f, 20f, 30f); + Vector3 result = Vector3.TransformNormal(normal, translation); Assert.True(MathHelper.AlmostEquals(normal.x, result.x)); Assert.True(MathHelper.AlmostEquals(normal.y, result.y)); @@ -73,26 +72,26 @@ public void Vector3_TransformNormal_IgnoresTranslation() } [Fact] - public void Vector2_Angle_SignedAngle() + public void Vector2AngleSignedAngle() { var right = new Vector2(1f, 0f); var up = new Vector2(0f, 1f); - var angle = Vector2.Angle(right, up); - var signed = Vector2.SignedAngle(right, up); + float angle = Vector2.Angle(right, up); + float signed = Vector2.SignedAngle(right, up); Assert.True(MathHelper.AlmostEquals(MathF.PI * 0.5f, angle)); Assert.True(MathHelper.AlmostEquals(MathF.PI * 0.5f, signed)); } [Fact] - public void Matrix_Multiply_ColumnVector_Order() + public void MatrixMultiplyColumnVectorOrder() { - var scale = Matrix.CreateScale(2f); - var translate = Matrix.CreateTranslation(1f, 0f, 0f); - var combined = translate * scale; + Matrix scale = Matrix.CreateScale(2f); + Matrix translate = Matrix.CreateTranslation(1f, 0f, 0f); + Matrix combined = translate * scale; var v = new Vector3(1f, 0f, 0f); - var result = Vector3.Transform(v, combined); + Vector3 result = Vector3.Transform(v, combined); Assert.True(MathHelper.AlmostEquals(3f, result.x)); Assert.True(MathHelper.AlmostEquals(0f, result.y)); @@ -100,89 +99,95 @@ public void Matrix_Multiply_ColumnVector_Order() } [Fact] - public void Matrix_Determinant_Invert_Roundtrip() + public void MatrixDeterminantInvertRoundtrip() { - var m = Matrix.CreateTranslation(1f, 2f, 3f) * Matrix.CreateScale(2f, 3f, 4f); - var det = Matrix.Determinant(m); + Matrix m = Matrix.CreateTranslation(1f, 2f, 3f) * Matrix.CreateScale(2f, 3f, 4f); + float det = Matrix.Determinant(m); Assert.True(MathHelper.AlmostEquals(24f, det)); - var inv = Matrix.Invert(m); - var identity = m * inv; + Matrix inv = Matrix.Invert(m); + Matrix identity = m * inv; Assert.True(identity == Matrix.identity); } [Fact] - public void Matrix_Decompose_Roundtrip() + public void MatrixDecomposeRoundtrip() { var scale = new Vector3(2f, 3f, 4f); - var rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); + Quaternion rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); var translation = new Vector3(5f, 6f, 7f); - var m = Matrix.CreateTranslation(translation) * Matrix.CreateFromQuaternion(rotation) * Matrix.CreateScale(scale); + Matrix m = Matrix.CreateTranslation(translation) * Matrix.CreateFromQuaternion(rotation) * Matrix.CreateScale(scale); - var success = Matrix.Decompose(m, out var outScale, out var outRotation, out var outTranslation); + bool success = Matrix.Decompose(m, out Vector3 outScale, out Quaternion outRotation, out Vector3 outTranslation); Assert.True(success); Assert.True(outTranslation == translation); Assert.True(MathHelper.AlmostEquals(scale.x, outScale.x)); Assert.True(MathHelper.AlmostEquals(scale.y, outScale.y)); Assert.True(MathHelper.AlmostEquals(scale.z, outScale.z)); - var rotMatrix = outRotation.ToMatrix(); - var expected = rotation.ToMatrix(); + Matrix rotMatrix = outRotation.ToMatrix(); + Matrix expected = rotation.ToMatrix(); Assert.True(rotMatrix == expected); } [Fact] - public void Matrix_Decompose_PreservesReflectedTransform() + public void MatrixDecomposePreservesReflectedTransform() { var scale = new Vector3(-2f, 3f, 4f); - var rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); + Quaternion rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); var translation = new Vector3(5f, 6f, 7f); Matrix matrix = Matrix.CreateTranslation(translation) - * Matrix.CreateFromQuaternion(rotation) - * Matrix.CreateScale(scale); - - Assert.True(Matrix.Decompose(matrix, out Vector3 resultScale, - out Quaternion resultRotation, out Vector3 resultTranslation)); + * Matrix.CreateFromQuaternion(rotation) + * Matrix.CreateScale(scale); + + Assert.True( + Matrix.Decompose( + matrix, + out Vector3 resultScale, + out Quaternion resultRotation, + out Vector3 resultTranslation + ) + ); Matrix reconstructed = Matrix.CreateTranslation(resultTranslation) - * Matrix.CreateFromQuaternion(resultRotation) - * Matrix.CreateScale(resultScale); + * Matrix.CreateFromQuaternion(resultRotation) + * Matrix.CreateScale(resultScale); Assert.True(matrix == reconstructed); } [Fact] - public void Matrix_LookAtRH_IdentityForMinusZ() + public void MatrixLookAtRHIdentityForMinusZ() { var eye = new Vector3(0f, 0f, 0f); var target = new Vector3(0f, 0f, -1f); var up = new Vector3(0f, 1f, 0f); - var view = Matrix.CreateLookAtRH(eye, target, up); + Matrix view = Matrix.CreateLookAtRH(eye, target, up); Assert.True(view == Matrix.identity); } [Fact] - public void Matrix_PerspectiveRH_MapsNearFar() + public void MatrixPerspectiveRHMapsNearFar() { float near = 0.1f; float far = 10f; - var proj = Matrix.CreatePerspectiveFieldOfViewRH(MathF.PI / 2f, 1f, near, far); + Matrix proj = Matrix.CreatePerspectiveFieldOfViewRH(MathF.PI / 2f, 1f, near, far); var vNear = new Vector4(0f, 0f, -near, 1f); var vFar = new Vector4(0f, 0f, -far, 1f); - var pNear = Vector4.Transform(vNear, proj).ProjectToVector3(); - var pFar = Vector4.Transform(vFar, proj).ProjectToVector3(); + Vector3 pNear = Vector4.Transform(vNear, proj).ProjectToVector3(); + Vector3 pFar = Vector4.Transform(vFar, proj).ProjectToVector3(); Assert.True(MathHelper.AlmostEquals(0f, pNear.z)); Assert.True(MathHelper.AlmostEquals(1f, pFar.z)); } [Fact] - public void Matrix_PerspectiveLH_MapsNearFar() + public void MatrixPerspectiveLHMapsNearFar() { float near = 0.1f; float far = 10f; - var projection = Matrix.CreatePerspectiveFieldOfView(MathF.PI / 2f, 1f, near, far); + Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathF.PI / 2f, 1f, near, far); Vector3 projectedNear = (projection * new Vector4(0f, 0f, near, 1f)).ProjectToVector3(); Vector3 projectedFar = (projection * new Vector4(0f, 0f, far, 1f)).ProjectToVector3(); @@ -192,7 +197,7 @@ public void Matrix_PerspectiveLH_MapsNearFar() } [Fact] - public void Matrix_LookAtLH_RotatesWorldIntoCameraAxes() + public void MatrixLookAtLHRotatesWorldIntoCameraAxes() { Matrix view = Matrix.CreateLookAt(Vector3.ZERO, Vector3.RIGHT, Vector3.UP); @@ -204,27 +209,23 @@ public void Matrix_LookAtLH_RotatesWorldIntoCameraAxes() } [Fact] - public void Matrix_OrthographicOffCenter_MapsEdges() + public void MatrixOrthographicOffCenterMapsEdges() { - var ortho = Matrix.CreateOrthographicOffCenter(-2f, 2f, -1f, 1f, 0f, 10f); + Matrix ortho = Matrix.CreateOrthographicOffCenter(-2f, 2f, -1f, 1f, 0f, 10f); - var left = Vector4.Transform(new Vector4(-2f, 0f, 0f, 1f), ortho).ProjectToVector3(); - var right = Vector4.Transform(new Vector4(2f, 0f, 0f, 1f), ortho).ProjectToVector3(); + Vector3 left = Vector4.Transform(new Vector4(-2f, 0f, 0f, 1f), ortho).ProjectToVector3(); + Vector3 right = Vector4.Transform(new Vector4(2f, 0f, 0f, 1f), ortho).ProjectToVector3(); Assert.True(MathHelper.AlmostEquals(-1f, left.x)); Assert.True(MathHelper.AlmostEquals(1f, right.x)); } [Fact] - public void Matrix_ToColumnMajorArray_Layout() + public void MatrixToColumnMajorArrayLayout() { - var m = new Matrix( - 1f, 2f, 3f, 4f, - 5f, 6f, 7f, 8f, - 9f, 10f, 11f, 12f, - 13f, 14f, 15f, 16f); + var m = new Matrix(1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f); - var data = m.ToColumnMajorArray(); + float[] data = m.ToColumnMajorArray(); Assert.Equal(16, data.Length); Assert.True(MathHelper.AlmostEquals(1f, data[0])); @@ -238,39 +239,34 @@ public void Matrix_ToColumnMajorArray_Layout() } [Fact] - public void Quaternion_Normalize_UnitLength() + public void QuaternionNormalizeUnitLength() { var q = new Quaternion(1f, 2f, 3f, 4f); - var n = Quaternion.Normalize(q); - var len = n.Length(); + Quaternion n = Quaternion.Normalize(q); + float len = n.Length(); Assert.True(MathHelper.AlmostEquals(1f, len)); } [Fact] - public void Quaternion_FromRotationMatrix_Roundtrip() + public void QuaternionFromRotationMatrixRoundtrip() { - var q = Quaternion.FromEulerAnglesXYZ(new Vector3(0.25f, 0.5f, 1.1f)); - var m = q.ToMatrix(); - var q2 = Quaternion.FromRotationMatrix(m); + Quaternion q = Quaternion.FromEulerAnglesXYZ(new Vector3(0.25f, 0.5f, 1.1f)); + Matrix m = q.ToMatrix(); + Quaternion q2 = Quaternion.FromRotationMatrix(m); if (Dot(q, q2) < 0f) { q2 = new Quaternion(-q2.x, -q2.y, -q2.z, -q2.w); } - const float epsilon = 1e-3f; - Assert.True(MathF.Abs(q.x - q2.x) < epsilon); - Assert.True(MathF.Abs(q.y - q2.y) < epsilon); - Assert.True(MathF.Abs(q.z - q2.z) < epsilon); - Assert.True(MathF.Abs(q.w - q2.w) < epsilon); - } - - private static float Dot(Quaternion a, Quaternion b) - { - return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + const float C_EPSILON = 1e-3f; + Assert.True(MathF.Abs(q.x - q2.x) < C_EPSILON); + Assert.True(MathF.Abs(q.y - q2.y) < C_EPSILON); + Assert.True(MathF.Abs(q.z - q2.z) < C_EPSILON); + Assert.True(MathF.Abs(q.w - q2.w) < C_EPSILON); } [Fact] - public void MathHelper_Clamp_Saturate_IsFinite() + public void MathHelperClampSaturateIsFinite() { Assert.True(MathHelper.AlmostEquals(0.5f, MathHelper.Clamp(0.5f, 0f, 1f))); Assert.True(MathHelper.AlmostEquals(1f, MathHelper.Clamp(2f, 0f, 1f))); @@ -278,4 +274,9 @@ public void MathHelper_Clamp_Saturate_IsFinite() Assert.True(MathHelper.IsFinite(1f)); Assert.False(MathHelper.IsFinite(float.PositiveInfinity)); } + + private static float Dot( + Quaternion a, + Quaternion b + ) => a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs new file mode 100644 index 000000000..9a13ea1b4 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousHost : ISerializable +{ + [SerializableProperty] + public AmbiguousValue? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs new file mode 100644 index 000000000..235d9d45a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousLeftConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + IAmbiguousLeft value + ) {} + + public override IAmbiguousLeft Read(SerializationReader reader) => new AmbiguousValue(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs new file mode 100644 index 000000000..647501ee1 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousRightConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + IAmbiguousRight value + ) {} + + public override IAmbiguousRight Read(SerializationReader reader) => new AmbiguousValue(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs new file mode 100644 index 000000000..a53579454 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousValue : IAmbiguousLeft, IAmbiguousRight; diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs new file mode 100644 index 000000000..552f87b66 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRoot : ISerializable +{ + internal List rows = []; + internal Guid scope = Guid.NewGuid(); + internal int mode; + internal int keys; + internal bool allowKeys = true; + internal bool stateful; + internal bool failKey; + internal Action? onWrite; + internal SerializationCaptureKeyBuilder? savedBuilder; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs new file mode 100644 index 000000000..5c85f74c8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs @@ -0,0 +1,54 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureArrayRoot value + ) { + writer.Write("scope", value.scope); + writer.WriteObjectArray( + "rows", + value.rows, + ( + child, + row + ) => + { + row.writes++; + value.onWrite?.Invoke(); + child.Write("number", row.number); + child.Write("mode", value.mode); + if (value.stateful) + { + child.WritePropertiesData("state", row.state); + } + }, + captureKey: ( + row, + key + ) => + { + value.keys++; + value.savedBuilder = key; + if (value.failKey) + { + throw new InvalidOperationException("Array key failure."); + } + if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) + { + return false; + } + key.AddValue(value.scope); + key.AddValue(unchecked((ulong)value.mode)); + key.AddValue(value.stateful ? 1UL : 0UL); + return true; + } + ); + } + + public override CaptureArrayRoot Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs new file mode 100644 index 000000000..3f26c0ec5 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs @@ -0,0 +1,11 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRow : IdentityObject, ISerializable +{ + internal int number; + internal int writes; + internal ulong? revision = 0; + internal ConvertedCaptureProperties state = new(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs new file mode 100644 index 000000000..88b87fa58 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs @@ -0,0 +1,8 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureBlobRoot : IdentityObject, ISerializable +{ + internal byte[] data = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs new file mode 100644 index 000000000..541dbe9db --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureBlobRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureBlobRoot value + ) => writer.Write("data", value.data); + + public override CaptureBlobRoot Read(SerializationReader reader) => throw new NotSupportedException(); + + protected override bool TryCaptureKey( + CaptureBlobRoot value, + SerializationCaptureKeyBuilder key + ) => key.TryAddOwner(value, 0); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs new file mode 100644 index 000000000..39632e4c2 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct CaptureConvertedValue +{ + public int number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs new file mode 100644 index 000000000..310a6c7c8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureConvertedValueConverter : SerializationConverter +{ + internal static readonly List EVENTS = []; + internal static int calls; + + public CaptureConvertedValueConverter() + { + EVENTS.Add("construct"); + } + + public override void Write( + SerializationWriter writer, + CaptureConvertedValue value + ) { + EVENTS.Add("convert-write"); + writer.Write("number", value.number); + writer.Write("call", ++calls); + } + + public override CaptureConvertedValue Read(SerializationReader reader) => new() { number = reader.Read("number") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs new file mode 100644 index 000000000..c2f128d37 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct CaptureGetterStruct +{ + internal static int calls; + + public int value + { + get + { + calls++; + return 1; + } + set {} + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs new file mode 100644 index 000000000..74a6cf4dc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyContext +{ + internal ulong value; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs new file mode 100644 index 000000000..3583cf951 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs @@ -0,0 +1,24 @@ +using System; +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyRoot : IdentityObject, ISerializable +{ + internal ulong? revision = 0; + internal int number; + internal string? text; + internal bool allowKey = true; + internal bool ignoreDecline; + internal bool failKey; + internal bool failWrite; + internal int writeCalls; + internal int keyCalls; + internal ISerializable? properties; + internal CaptureConvertedValue? converted; + internal Action? onWrite; + internal Action? onKey; + internal SerializationCaptureKeyBuilder? savedBuilder; + + internal void Touch() => revision++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs new file mode 100644 index 000000000..5331f7a2d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs @@ -0,0 +1,57 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureKeyRoot value + ) { + value.writeCalls++; + value.onWrite?.Invoke(); + if (value.failWrite) + { + throw new InvalidOperationException("Capture writer failure."); + } + writer.Write("number", value.number); + writer.Write("text", value.text); + writer.Write("context", writer.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); + if (value.properties is not null) + { + writer.WritePropertiesData("properties", value.properties); + } + if (value.converted.HasValue) + { + writer.Write("converted", value.converted.Value); + } + } + + public override CaptureKeyRoot Read(SerializationReader reader) => throw new NotSupportedException(); + + protected override bool TryCaptureKey( + CaptureKeyRoot value, + SerializationCaptureKeyBuilder key + ) { + value.keyCalls++; + value.savedBuilder = key; + if (value.failKey) + { + throw new InvalidOperationException("Capture key failure."); + } + if (!value.allowKey) + { + return false; + } + key.EnsureCapacity(5); + bool complete = key.TryAddOwner(value, value.revision); + key.AddValue(key.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); + if (value.properties is not null) + { + complete &= key.TryAddProperties(value.properties); + } + value.onKey?.Invoke(key); + return complete || value.ignoreDecline; + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs b/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs new file mode 100644 index 000000000..f290780b6 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs @@ -0,0 +1,11 @@ +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CapturePropertyLoadContext() : AssemblyLoadContext(isCollectible: true) +{ + protected override Assembly? Load(AssemblyName name) + => Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs new file mode 100644 index 000000000..c994ab8fd --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs @@ -0,0 +1,35 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +/// +/// Provides a real public extension type for collectible metadata and capture-key acceptance. +/// +[SerializationRevision("m_revision")] +public sealed class CaptureRevisionProperties : IdentityObject, ISerializable +{ + private ulong? m_revision = 0; + private int m_number; + + /// + /// Creates an initially empty tracked property source. + /// + public CaptureRevisionProperties() {} + + /// + /// Gets or sets the serialized number, advancing its complete source-owned revision before mutation. + /// + [SerializableProperty] + public int number + { + get => m_number; + set + { + if (m_revision is { } revision) + { + m_revision = revision == ulong.MaxValue ? null : revision + 1; + } + m_number = value; + } + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs new file mode 100644 index 000000000..23c85fa8f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConcurrentCaptureConverter : SerializationConverter, IDisposable +{ + internal static int constructions; + internal static int disposals; + + /// + /// Records construction of the converter owned by the captured generation. + /// + public ConcurrentCaptureConverter() + { + Interlocked.Increment(ref constructions); + } + + /// + public override void Write( + SerializationWriter writer, + ConcurrentCaptureValue value + ) => writer.Write("count", value.count); + + /// + public override ConcurrentCaptureValue Read(SerializationReader reader) => new(reader.Read("count")); + + /// + public void Dispose() => Interlocked.Increment(ref disposals); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs new file mode 100644 index 000000000..eb253d7c9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConcurrentCaptureValue(int count) : ISerializable +{ + internal int count { get; } = count; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs new file mode 100644 index 000000000..cfbb185e9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs @@ -0,0 +1,12 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class ConvertedCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public CaptureConvertedValue value = new() { number = 1 }; + + private ulong? revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs new file mode 100644 index 000000000..9aa7414a3 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChild +{ + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs new file mode 100644 index 000000000..c7d072d9b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChildConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedChild value + ) => writer.Write("value", value.value); + + public override ConvertedChild Read(SerializationReader reader) => new() { value = reader.Read("value") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs new file mode 100644 index 000000000..61aaae947 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChildHost : ISerializable +{ + [SerializableProperty] + public ConvertedChild? child { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs new file mode 100644 index 000000000..0efe296ff --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs @@ -0,0 +1,11 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedConstructorSample : ISerializable +{ + public ConvertedConstructorSample(int value) + { + this.value = value; + } + + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs new file mode 100644 index 000000000..cbdc1ad40 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedConstructorSampleConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedConstructorSample value + ) => writer.Write("value", value.value); + + public override ConvertedConstructorSample Read(SerializationReader reader) => new(reader.Read("value")); + + public override void Restore( + SerializationReader reader, + ConvertedConstructorSample target + ) => target.value = reader.Read("value"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs new file mode 100644 index 000000000..8ee0188b0 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs @@ -0,0 +1,10 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedHookSample : ISerializable +{ + public int value { get; set; } + public int hookCount { get; private set; } + + [OnSerializableRestored] + private void AfterRestore() => hookCount++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs new file mode 100644 index 000000000..782878178 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedHookSampleConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedHookSample value + ) => writer.Write("value", value.value); + + public override ConvertedHookSample Read(SerializationReader reader) => new() { value = reader.Read("value") }; + + public override void Restore( + SerializationReader reader, + ConvertedHookSample target + ) => target.value = reader.Read("value"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs b/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs new file mode 100644 index 000000000..0b2e9b980 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs @@ -0,0 +1,18 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CurrentSchemaSample : ISerializable +{ + [SerializableProperty] + public string changed { get; set; } = "default"; + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = "new"; + + [SerializableProperty] + public int added { get; set; } = 17; + + public int restoreCount { get; private set; } + + [OnSerializableRestored] + private void AfterRestore() => restoreCount++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs b/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs new file mode 100644 index 000000000..c63087173 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleHost : ISerializable +{ + [SerializableProperty] + public CycleValue? value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs b/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs new file mode 100644 index 000000000..0fd0d250a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleValue +{ + public CycleValue? next { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs new file mode 100644 index 000000000..13068a4c5 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleValueConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CycleValue value + ) => writer.Write("next", value.next); + + public override CycleValue Read(SerializationReader reader) => new() { next = reader.Read("next") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs b/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs new file mode 100644 index 000000000..895302612 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class DefaultSample : ISerializable +{ + [SerializableProperty] + public bool enabled { get; set; } + + [SerializableProperty] + public int count { get; set; } + + [SerializableProperty] + public float ratio { get; set; } + + [SerializableProperty] + public decimal price { get; set; } + + [SerializableProperty] + public string name { get; set; } = string.Empty; + + [SerializableProperty] + public Guid identity { get; set; } + + [SerializableProperty] + public SampleMode mode { get; set; } + + [SerializableProperty] + public int? optional { get; set; } + + [SerializableProperty] + public byte[] bytes { get; set; } = []; + + [SerializableProperty] + public int[] numbers { get; set; } = []; + + [SerializableProperty] + public List values { get; set; } = []; + + [SerializableProperty] + public Dictionary map { get; set; } = []; + + [SerializableProperty] + public StructSample data { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs new file mode 100644 index 000000000..a153c7f34 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: DuplicateKeyDerivedSample derives from it. +internal class DuplicateKeyBaseSample : ISerializable +{ + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs new file mode 100644 index 000000000..58a2e4637 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class DuplicateKeyDerivedSample : DuplicateKeyBaseSample +{ + [SerializableProperty] + public new int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs b/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs new file mode 100644 index 000000000..1cff88419 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: ExactLeaf derives from it for the converter-selection tests. +internal class ExactBase +{ + public int value { get; set; } + public string selectedBy { get; set; } = string.Empty; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs new file mode 100644 index 000000000..b301a253c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactBaseConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ExactBase value + ) => writer.Write("value", value.value); + + public override ExactBase Read(SerializationReader reader) + => new ExactLeaf { value = reader.Read("value"), selectedBy = "base" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs b/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs new file mode 100644 index 000000000..71fdf585d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactHost : ISerializable +{ + [SerializableProperty] + public ExactLeaf? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs b/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs new file mode 100644 index 000000000..b9dc3bfcf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactLeaf : ExactBase; diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs new file mode 100644 index 000000000..72f92f623 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactLeafConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ExactLeaf value + ) => writer.Write("value", value.value); + + public override ExactLeaf Read(SerializationReader reader) + => new() { value = reader.Read("value"), selectedBy = "exact" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs b/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs new file mode 100644 index 000000000..ebfa5304c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs @@ -0,0 +1,15 @@ +using System; +using Inno.Adapter.Serialization.DotNet; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class FreshCaptureMetadataSource : ISerializationMetadataSource +{ + private readonly ReflectionSerializationMetadataSource m_source = new(); + + public SerializationTypeMetadata GetMetadata(Type type) + { + SerializationTypeMetadata original = m_source.GetMetadata(type); + return new(type, original.members, original.CreateInstance, original.restored, original.collection, original.requiresConverter); + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs new file mode 100644 index 000000000..ebb7bdded --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs @@ -0,0 +1,11 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBox +{ + public GenericBox(T value) + { + this.value = value; + } + + public T value { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs new file mode 100644 index 000000000..de443dd7a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBoxConverter : SerializationConverter> +{ + public override void Write( + SerializationWriter writer, + GenericBox value + ) => writer.Write("value", value.value); + + public override GenericBox Read(SerializationReader reader) => new(reader.Read("value")); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs new file mode 100644 index 000000000..ed527643c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBoxHost : ISerializable +{ + [SerializableProperty] + public GenericBox? box { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs new file mode 100644 index 000000000..c869a407e --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs @@ -0,0 +1,12 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class GetterCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public CaptureGetterStruct value = new(); + + private ulong? revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs b/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs new file mode 100644 index 000000000..3faf409fb --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +// Open: HookDerivedSample derives from it to inherit its serialization hooks. +internal class HookBaseSample : ISerializable +{ + [SerializableProperty] + public int value { get; set; } + + public List calls { get; } = []; + + [OnSerializableRestored] + private void AfterBaseRestore() => calls.Add("base"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs b/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs new file mode 100644 index 000000000..08de20ed4 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class HookDerivedSample : HookBaseSample +{ + [OnSerializableRestored] + private void AfterDerivedRestore() => calls.Add("derived"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs new file mode 100644 index 000000000..04e9e1e69 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IAmbiguousLeft; diff --git a/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs new file mode 100644 index 000000000..89c140436 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IAmbiguousRight; diff --git a/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs b/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs new file mode 100644 index 000000000..130c4465e --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface ISampleContext; diff --git a/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs b/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs new file mode 100644 index 000000000..6cbc6032c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IVariantValue +{ + T value { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MapHost.cs b/tests/core/Inno.Core.Serialization.Tests/MapHost.cs new file mode 100644 index 000000000..3ad6e2e0a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MapHost.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MapHost : ISerializable +{ + [SerializableProperty] + public Dictionary values { get; set; } = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs b/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs new file mode 100644 index 000000000..5e815d7dc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingChild +{ + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs b/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs new file mode 100644 index 000000000..52859ad74 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingClassCollectionHost : ISerializable +{ + [SerializableProperty] + public List children { get; set; } = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs b/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs new file mode 100644 index 000000000..d84e5d65a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingClassHost : ISerializable +{ + [SerializableProperty] + public MissingChild? child { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs new file mode 100644 index 000000000..dc066061c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs @@ -0,0 +1,12 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingConstructorSample : ISerializable +{ + public MissingConstructorSample(int value) + { + this.value = value; + } + + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs new file mode 100644 index 000000000..53a8831d7 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs @@ -0,0 +1,4 @@ +namespace Inno.Core.Serialization.Tests; + +[RequiresSerializationConverter] +internal sealed class MissingRequiredConverterSample : ISerializable; diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs new file mode 100644 index 000000000..148d0cbdc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingSetterSample : ISerializable +{ + [SerializableProperty] + public int value { get; } = 1; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs new file mode 100644 index 000000000..422a5a113 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingBinaryCapture : ISerializable +{ + internal byte[] bytes = [1]; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs new file mode 100644 index 000000000..ee7dea70f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs @@ -0,0 +1,16 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingBinaryCaptureConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + MutatingBinaryCapture value + ) { + writer.Write("bytes", value.bytes); + value.bytes[0] = 2; + } + + public override MutatingBinaryCapture Read(SerializationReader reader) => new() { bytes = reader.Read("bytes") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs new file mode 100644 index 000000000..e850eda2b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs @@ -0,0 +1,14 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingPropertyCapture : ISerializable +{ + private readonly byte[] m_bytes = [1]; + + [SerializableProperty(PropertyVisibility.Serialize)] + public byte[] bytes => m_bytes; + + [SerializableProperty(PropertyVisibility.Serialize)] + public int mutate => m_bytes[0] = 2; + + internal void Reset() => m_bytes[0] = 1; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs b/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs new file mode 100644 index 000000000..109df762b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: NearestMid derives from it for the converter-selection tests. +internal class NearestBase +{ + public int value { get; set; } + public string selectedBy { get; set; } = string.Empty; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs b/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs new file mode 100644 index 000000000..7a10a979a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestBaseConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + NearestBase value + ) => writer.Write("value", value.value); + + public override NearestBase Read(SerializationReader reader) + => new NearestLeaf { value = reader.Read("value"), selectedBy = "base" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs b/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs new file mode 100644 index 000000000..9e1fa96d8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestHost : ISerializable +{ + [SerializableProperty] + public NearestLeaf? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs b/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs new file mode 100644 index 000000000..abf9640cf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestLeaf : NearestMid; diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs b/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs new file mode 100644 index 000000000..0923f3360 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs @@ -0,0 +1,4 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: NearestLeaf derives from it for the converter-selection tests. +internal class NearestMid : NearestBase; diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs b/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs new file mode 100644 index 000000000..bcd1454fd --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestMidConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + NearestMid value + ) => writer.Write("value", value.value); + + public override NearestMid Read(SerializationReader reader) + => new NearestLeaf { value = reader.Read("value"), selectedBy = "mid" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs b/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs new file mode 100644 index 000000000..312a675e6 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class OrdinalCapture : ISerializable +{ + internal string[] names = ["first", "second", "third"]; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs new file mode 100644 index 000000000..e1aab966a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class OrdinalCaptureConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + OrdinalCapture value + ) { + foreach (string name in value.names) + { + writer.Write(name, 7); + } + } + + public override OrdinalCapture Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs b/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs new file mode 100644 index 000000000..c928158c9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs @@ -0,0 +1,13 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class PreviousSchemaSample : ISerializable +{ + [SerializableProperty] + public int changed { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = string.Empty; + + [SerializableProperty] + public int removed { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs new file mode 100644 index 000000000..8dd7e5bcf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs @@ -0,0 +1,14 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class PrivateConstructorSample : ISerializable +{ + private PrivateConstructorSample() + { + this.wasConstructed = true; + } + + [SerializableProperty] + public int value { get; set; } + + public bool wasConstructed { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs b/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs new file mode 100644 index 000000000..db712830a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct PureCaptureFields +{ + public float number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs new file mode 100644 index 000000000..0b4a1de16 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs @@ -0,0 +1,21 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("m_revision")] +internal sealed class PureFieldCaptureProperties : IdentityObject, ISerializable +{ + private ulong? m_revision = 0; + private PureCaptureFields m_value; + + [SerializableProperty] + public PureCaptureFields value + { + get => m_value; + set + { + m_revision++; + m_value = value; + } + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs b/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs new file mode 100644 index 000000000..a33376beb --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs @@ -0,0 +1,9 @@ +using System; +using System.IO; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class RejectCaptureStream : MemoryStream +{ + public override void Write(ReadOnlySpan buffer) => throw new IOException("The test destination rejects writes."); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs b/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs new file mode 100644 index 000000000..69aaf781f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class SampleContext : ISampleContext; diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs index 295cf2fd7..a4b79e326 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; -using Inno.Core.Identity; -using Inno.Core.Serialization.Converters; using Xunit; +using Inno.Core.Identity; namespace Inno.Core.Serialization.Tests; @@ -150,86 +148,3 @@ public void DeclinedArrayKeysCannotReuseAnEarlierCertifiedElement() Assert.Equal(m_serialization.Serialize(source), changed.ToArray()); } } - -internal sealed class CaptureArrayRoot : ISerializable -{ - internal List rows = []; - internal Guid scope = Guid.NewGuid(); - internal int mode; - internal int keys; - internal bool allowKeys = true; - internal bool stateful; - internal bool failKey; - internal Action? onWrite; - internal SerializationCaptureKeyBuilder? savedBuilder; -} - -internal sealed class CaptureArrayRow : IdentityObject, ISerializable -{ - internal int number; - internal int writes; - internal ulong? revision = 0; - internal ConvertedCaptureProperties state = new(); -} - -internal sealed class CaptureArrayRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureArrayRoot value - ) { - writer.Write("scope", value.scope); - writer.WriteObjectArray("rows", value.rows, ( - child, - row - ) => { - row.writes++; - value.onWrite?.Invoke(); - child.Write("number", row.number); - child.Write("mode", value.mode); - if (value.stateful) - child.WritePropertiesData("state", row.state); - }, captureKey: ( - row, - key - ) => { - value.keys++; - value.savedBuilder = key; - if (value.failKey) - throw new InvalidOperationException("Array key failure."); - if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) - return false; - key.AddValue(value.scope); - key.AddValue(unchecked((ulong)value.mode)); - key.AddValue(value.stateful ? 1UL : 0UL); - return true; - }); - } - - public override CaptureArrayRoot Read(SerializationReader reader) => throw new NotSupportedException(); -} - -internal sealed class CaptureBlobRoot : IdentityObject, ISerializable -{ - internal byte[] data = []; -} - -internal sealed class CaptureBlobRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureBlobRoot value - ) => writer.Write("data", value.data); - - public override CaptureBlobRoot Read(SerializationReader reader) => throw new NotSupportedException(); - - protected override bool TryCaptureKey( - CaptureBlobRoot value, - SerializationCaptureKeyBuilder key - ) => key.TryAddOwner(value, 0); -} - -internal sealed class RejectCaptureStream : MemoryStream -{ - public override void Write(ReadOnlySpan buffer) => throw new IOException("The test destination rejects writes."); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs index 103574b17..8a8cdf4b0 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs @@ -1,14 +1,10 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; +using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.Loader; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Identity; -using Inno.Core.Serialization.Converters; -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -85,7 +81,7 @@ public void CaptureKeysQualifyIdentityByDomainAndRejectRetiredBindings() var original = new CaptureKeyRoot(); var replacement = new CaptureKeyRoot(); Assert.True(first.Register(original)); - Assert.True(second.Register(replacement, original.identity.persistentId)); + Assert.True(second.Register(replacement, original.identity.persistentID)); SerializationSnapshot before = m_serialization.CaptureSnapshot(original); SerializationSnapshot changed = m_serialization.CaptureSnapshot(replacement, previous: before); Assert.NotSame(before, changed); @@ -169,19 +165,19 @@ public void ProvenPropertyRevisionsInvalidateWithoutPersistingTheirCounter() [Fact] public void CaptureKeyQueriesDoNotConstructOrSkipStatefulConverters() { - CaptureConvertedValueConverter.events.Clear(); + CaptureConvertedValueConverter.EVENTS.Clear(); CaptureConvertedValueConverter.calls = 0; var identities = new IdentityAllocator(); var properties = new ConvertedCaptureProperties(); var value = new CaptureKeyRoot { properties = properties, - onWrite = () => CaptureConvertedValueConverter.events.Add("root-write") + onWrite = () => CaptureConvertedValueConverter.EVENTS.Add("root-write") }; Assert.True(identities.Register(value)); Assert.True(identities.Register(properties)); SerializationSnapshot before = m_serialization.CaptureSnapshot(value); - Assert.Equal(new[] { "root-write", "construct", "convert-write" }, CaptureConvertedValueConverter.events); + Assert.Equal(new[] { "root-write", "construct", "convert-write" }, CaptureConvertedValueConverter.EVENTS); SerializationSnapshot changed = m_serialization.CaptureSnapshot(value, previous: before); Assert.Equal(2, CaptureConvertedValueConverter.calls); Assert.NotEqual(before.ToArray(), changed.ToArray()); @@ -191,17 +187,17 @@ public void CaptureKeyQueriesDoNotConstructOrSkipStatefulConverters() public void PureFieldMetadataPreservesExactFloatBitsAcrossTrackedPropertyChanges() { var identities = new IdentityAllocator(); - var properties = new PureFieldCaptureProperties { value = new PureCaptureFields { number = -0.0f } }; + var properties = new PureFieldCaptureProperties { value = new PureCaptureFields { number = -0f } }; var value = new CaptureKeyRoot { properties = properties }; Assert.True(identities.Register(value)); Assert.True(identities.Register(properties)); _ = m_serialization.CapturePropertiesData(properties); SerializationSnapshot before = m_serialization.CaptureSnapshot(value); Assert.Same(before, m_serialization.CaptureSnapshot(value, previous: before)); - properties.value = new PureCaptureFields { number = 0.0f }; + properties.value = new PureCaptureFields { number = 0f }; SerializationSnapshot zero = m_serialization.CaptureSnapshot(value, previous: before); Assert.NotEqual(before.ToArray(), zero.ToArray()); - foreach (int bits in new[] { 0x7fc00001, 0x7fc00002 }) + foreach (int bits in new[] { 0x7FC0_0001, 0x7FC0_0002 }) { properties.value = new PureCaptureFields { number = BitConverter.Int32BitsToSingle(bits) }; SerializationSnapshot changed = m_serialization.CaptureSnapshot(value, previous: zero); @@ -310,8 +306,12 @@ public void MetadataRevisionDeclarationsRejectCountersInTheSerializedPayload() [Fact] public void RetainedCaptureKeysAndRetiredBuildersDoNotPinACollectiblePropertyAssembly() { - (SerializationSnapshot snapshot, SerializationCaptureKeyBuilder builder, WeakReference assembly, WeakReference context) = - CaptureCollectibleProperties(); + ( + SerializationSnapshot snapshot, + SerializationCaptureKeyBuilder builder, + WeakReference assembly, + WeakReference context + ) = CaptureCollectibleProperties(); for (int index = 0; index < 10 && (assembly.IsAlive || context.IsAlive); index++) { GC.Collect(); @@ -328,9 +328,9 @@ public void RetainedCaptureKeysAndRetiredBuildersDoNotPinACollectiblePropertyAss private (SerializationSnapshot, SerializationCaptureKeyBuilder, WeakReference, WeakReference) CaptureCollectibleProperties() { var context = new CapturePropertyLoadContext(); - var assembly = context.LoadFromAssemblyPath(typeof(CaptureRevisionProperties).Assembly.Location); + Assembly assembly = context.LoadFromAssemblyPath(typeof(CaptureRevisionProperties).Assembly.Location); Type type = assembly.GetType(typeof(CaptureRevisionProperties).FullName!, throwOnError: true)!; - var properties = (ISerializable)Activator.CreateInstance(type)!; + ISerializable properties = (ISerializable)Activator.CreateInstance(type)!; var identities = new IdentityAllocator(); var value = new CaptureKeyRoot { properties = properties }; Assert.True(identities.Register(value)); @@ -348,203 +348,3 @@ public void RetainedCaptureKeysAndRetiredBuildersDoNotPinACollectiblePropertyAss return (snapshot, builder, assemblyReference, contextReference); } } - -internal sealed class CaptureKeyRoot : IdentityObject, ISerializable -{ - internal ulong? revision = 0; - internal int number; - internal string? text; - internal bool allowKey = true; - internal bool ignoreDecline; - internal bool failKey; - internal bool failWrite; - internal int writeCalls; - internal int keyCalls; - internal ISerializable? properties; - internal CaptureConvertedValue? converted; - internal Action? onWrite; - internal Action? onKey; - internal SerializationCaptureKeyBuilder? savedBuilder; - - internal void Touch() => revision++; -} - -internal sealed class CaptureKeyContext -{ - internal ulong value; -} - -internal sealed class CaptureKeyRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureKeyRoot value - ) { - value.writeCalls++; - value.onWrite?.Invoke(); - if (value.failWrite) - throw new InvalidOperationException("Capture writer failure."); - writer.Write("number", value.number); - writer.Write("text", value.text); - writer.Write("context", writer.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); - if (value.properties is not null) - writer.WritePropertiesData("properties", value.properties); - if (value.converted.HasValue) - writer.Write("converted", value.converted.Value); - } - - public override CaptureKeyRoot Read(SerializationReader reader) => throw new NotSupportedException(); - - protected override bool TryCaptureKey( - CaptureKeyRoot value, - SerializationCaptureKeyBuilder key - ) { - value.keyCalls++; - value.savedBuilder = key; - if (value.failKey) - throw new InvalidOperationException("Capture key failure."); - if (!value.allowKey) - return false; - key.EnsureCapacity(5); - bool complete = key.TryAddOwner(value, value.revision); - key.AddValue(key.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); - if (value.properties is not null) - complete &= key.TryAddProperties(value.properties); - value.onKey?.Invoke(key); - return complete || value.ignoreDecline; - } -} - -/// -/// Provides a real public extension type for collectible metadata and capture-key acceptance. -/// -[SerializationRevision("m_revision")] -public sealed class CaptureRevisionProperties : IdentityObject, ISerializable -{ - private ulong? m_revision = 0; - private int m_number; - - /// - /// Creates an initially empty tracked property source. - /// - public CaptureRevisionProperties() { } - - /// - /// Gets or sets the serialized number, advancing its complete source-owned revision before mutation. - /// - [SerializableProperty] - public int number - { - get => m_number; - set - { - if (m_revision is { } revision) - m_revision = revision == ulong.MaxValue ? null : revision + 1; - m_number = value; - } - } -} - -internal sealed class UntrackedCaptureProperties : IdentityObject, ISerializable -{ - [SerializableProperty] public int number; -} - -[SerializationRevision("revision")] -internal sealed class ConvertedCaptureProperties : IdentityObject, ISerializable -{ - private ulong? revision => 0; - [SerializableProperty] public CaptureConvertedValue value = new() { number = 1 }; -} - -[SerializationRevision("m_revision")] -internal sealed class PureFieldCaptureProperties : IdentityObject, ISerializable -{ - private ulong? m_revision = 0; - private PureCaptureFields m_value; - - [SerializableProperty] - public PureCaptureFields value - { - get => m_value; - set - { - m_revision++; - m_value = value; - } - } -} - -internal struct PureCaptureFields -{ - public float number; -} - -[SerializationRevision("revision")] -internal sealed class GetterCaptureProperties : IdentityObject, ISerializable -{ - private ulong? revision => 0; - [SerializableProperty] public CaptureGetterStruct value = new(); -} - -internal struct CaptureGetterStruct -{ - internal static int calls; - - public int value - { - get - { - calls++; - return 1; - } - set { } - } -} - -internal struct CaptureConvertedValue -{ - public int number; -} - -internal sealed class CaptureConvertedValueConverter : SerializationConverter -{ - internal static readonly List events = []; - internal static int calls; - - public CaptureConvertedValueConverter() => events.Add("construct"); - - public override void Write( - SerializationWriter writer, - CaptureConvertedValue value - ) { - events.Add("convert-write"); - writer.Write("number", value.number); - writer.Write("call", ++calls); - } - - public override CaptureConvertedValue Read(SerializationReader reader) => new() { number = reader.Read("number") }; -} - -[SerializationRevision("revision")] -internal sealed class SerializedCaptureCounter : IdentityObject, ISerializable -{ - [SerializableProperty(PropertyVisibility.Serialize)] public ulong revision => 0; -} - -internal sealed class FreshCaptureMetadataSource : ISerializationMetadataSource -{ - private readonly ReflectionSerializationMetadataSource m_source = new(); - - public SerializationTypeMetadata GetMetadata(Type type) - { - SerializationTypeMetadata original = m_source.GetMetadata(type); - return new(type, original.members, original.CreateInstance, original.restored, original.collection, original.requiresConverter); - } -} - -internal sealed class CapturePropertyLoadContext() : AssemblyLoadContext(isCollectible: true) -{ - protected override System.Reflection.Assembly? Load(System.Reflection.AssemblyName name) - => Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs index 520497b77..fc48e9aa6 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs @@ -1,7 +1,5 @@ using System; -using System.Threading; using System.Threading.Tasks; -using Inno.Core.Serialization.Converters; using Xunit; namespace Inno.Core.Serialization.Tests; @@ -34,31 +32,3 @@ public void ConcurrentCapturedOperationsPublishOneConverterAndRetireItAfterTheLa Assert.Throws(() => generation.Serialize(scalar)); } } - -internal sealed class ConcurrentCaptureValue(int count) : ISerializable -{ - internal int count { get; } = count; -} - -internal sealed class ConcurrentCaptureConverter : SerializationConverter, IDisposable -{ - internal static int constructions; - internal static int disposals; - - /// - /// Records construction of the converter owned by the captured generation. - /// - public ConcurrentCaptureConverter() => Interlocked.Increment(ref constructions); - - /// - public override void Write( - SerializationWriter writer, - ConcurrentCaptureValue value - ) => writer.Write("count", value.count); - - /// - public override ConcurrentCaptureValue Read(SerializationReader reader) => new(reader.Read("count")); - - /// - public void Dispose() => Interlocked.Increment(ref disposals); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs index 1b58c184c..96cc02d9d 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using Xunit; using Inno.Adapter.Serialization.DotNet; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -38,17 +38,23 @@ public void PreparedSerializationContextsAvoidRepeatedOwnerCopies() long fresh = Measure(null); long inherited = Measure(prepared); - Assert.True(inherited < fresh && inherited <= 1024, - $"Prepared context allocated {inherited} bytes; fresh context allocated {fresh} bytes."); + Assert.True( + inherited < fresh && inherited <= 1024, + $"Prepared context allocated {inherited} bytes; fresh context allocated {fresh} bytes." + ); long Measure(SerializationContext? context) { for (int index = 0; index < 16; index++) + { _ = m_serialization.CapturePropertyData(source, nameof(DefaultSample.count), context); + } byte[]? actual = null; long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 128; index++) + { actual = m_serialization.CapturePropertyData(source, nameof(DefaultSample.count), context); + } long allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / 128; Assert.Equal(expected, actual); return allocated; @@ -85,12 +91,16 @@ public void BinaryObjectKeysRemainOrdinalAndIndependentOfInsertionOrder() byte[] forward = m_serialization.Encode(writer => { foreach (string key in keys) + { writer.Write(key, key); + } }); byte[] reverse = m_serialization.Encode(writer => { for (int index = keys.Length - 1; index >= 0; index--) + { writer.Write(keys[index], keys[index]); + } }); Assert.Equal(forward, reverse); @@ -101,13 +111,17 @@ public void SmallBinaryDocumentsStayWithinABoundedAllocationBudget() { byte[] expected = m_serialization.Encode(static writer => writer.Write("value", 73)); for (int index = 0; index < 16; index++) + { _ = m_serialization.Encode(static writer => writer.Write("value", 73)); + } const int C_ITERATIONS = 128; byte[]? actual = null; long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < C_ITERATIONS; index++) + { actual = m_serialization.Encode(static writer => writer.Write("value", 73)); + } long allocated = GC.GetAllocatedBytesForCurrentThread() - before; Assert.Equal(expected, actual); @@ -152,7 +166,9 @@ public void BinaryDocumentsRoundTripAcrossBufferGrowthBoundaries(int length) { var payload = new byte[length]; for (int index = 0; index < payload.Length; index++) + { payload[index] = unchecked((byte)index); + } byte[] data = m_serialization.Serialize(new DefaultSample { bytes = payload }); DefaultSample restored = m_serialization.Deserialize(data); @@ -160,6 +176,18 @@ public void BinaryDocumentsRoundTripAcrossBufferGrowthBoundaries(int length) Assert.Equal(payload, restored.bytes); } + [MethodImpl(MethodImplOptions.NoInlining)] + private static (SerializationContext, WeakReference) ReplaceContextService(bool nested) + { + var replaced = new object(); + SerializationContext context = SerializationContext.empty.With(replaced); + if (nested) + { + context = context.With("marker").With>(new[] { 1, 2 }); + } + return (context.With(new object()), new WeakReference(replaced)); + } + private sealed class SelectiveCaptureSample : ISerializable { private int m_unrelatedReads; @@ -175,21 +203,10 @@ public int unrelated m_unrelatedReads++; throw new InvalidOperationException("An unrelated getter must not be evaluated."); } - set { } + set {} } public int ignored { get; set; } public int unrelatedReadCount => m_unrelatedReads; } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static (SerializationContext, WeakReference) ReplaceContextService(bool nested) - { - var replaced = new object(); - SerializationContext context = SerializationContext.empty.With(replaced); - if (nested) - context = context.With("marker").With>(new[] { 1, 2 }); - return (context.With(new object()), new WeakReference(replaced)); - } - } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs index b3c267f72..8033aae38 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs @@ -12,15 +12,42 @@ public void EncodedScalarBytesMatchTheBinaryWriterContract() { object?[] values = [ - null, false, true, byte.MaxValue, sbyte.MinValue, short.MinValue, ushort.MaxValue, - int.MinValue, uint.MaxValue, long.MinValue, ulong.MaxValue, - float.NegativeInfinity, float.PositiveInfinity, float.NaN, -0f, float.Epsilon, - double.NegativeInfinity, double.PositiveInfinity, double.NaN, -0d, double.Epsilon, - decimal.MinValue, decimal.MaxValue, new decimal(0, 0, 0, true, 28), - string.Empty, "English / 中文 / 🧪", Guid.Empty, Guid.Parse("62ce926a-e339-493d-bb74-743ed44ef37a") + null, + false, + true, + byte.MaxValue, + sbyte.MinValue, + short.MinValue, + ushort.MaxValue, + int.MinValue, + uint.MaxValue, + long.MinValue, + ulong.MaxValue, + float.NegativeInfinity, + float.PositiveInfinity, + float.NaN, + -0f, + float.Epsilon, + double.NegativeInfinity, + double.PositiveInfinity, + double.NaN, + -0d, + double.Epsilon, + decimal.MinValue, + decimal.MaxValue, + new decimal(0, 0, 0, true, 28), + string.Empty, + "English / 中文 / 🧪", + Guid.Empty, + Guid.Parse("62ce926a-e339-493d-bb74-743ed44ef37a") ]; foreach (object? value in values) - Assert.Equal(EncodeWithBinaryWriter(value), m_serialization.Encode(writer => writer.Write("value", value, value?.GetType() ?? typeof(string)))); + { + Assert.Equal( + EncodeWithBinaryWriter(value), + m_serialization.Encode(writer => writer.Write("value", value, value?.GetType() ?? typeof(string))) + ); + } } [Theory] @@ -35,11 +62,15 @@ public void EncodedStringsKeepUtf8AndSevenBitLengthSemantics(int length) { string[] values = [ - new string('a', length), new string('中', length), - new string((char)0xD800, length), "🧪" + new string('a', length) + new string('a', length), + new string('中', length), + new string((char)0xD800, length), + "🧪" + new string('a', length) ]; foreach (string value in values) + { Assert.Equal(EncodeWithBinaryWriter(value), m_serialization.Encode(writer => writer.Write("value", value))); + } } [Fact] @@ -49,13 +80,17 @@ public void LargeBinaryEncodingAllocatesOnlyTheOwnedCaptureAndResult() source[0] = 73; source[^1] = 19; for (int index = 0; index < 4; index++) + { _ = m_serialization.Encode(writer => writer.Write("value", source)); + } long before = GC.GetAllocatedBytesForCurrentThread(); byte[] data = []; - const int repetitions = 16; - for (int index = 0; index < repetitions; index++) + const int C_REPETITIONS = 16; + for (int index = 0; index < C_REPETITIONS; index++) + { data = m_serialization.Encode(writer => writer.Write("value", source)); - long allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / repetitions; + } + long allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / C_REPETITIONS; // Retain the per-call bound while amortizing one-time runtime/catalog admission during the suite. Assert.InRange(allocated, source.Length * 2, source.Length * 2 + 8192); source[0] = 0; @@ -133,7 +168,8 @@ private static byte[] EncodeWithBinaryWriter(object? value) writer.Write((byte)14); writer.Write(scalar.ToByteArray()); break; - default: throw new InvalidOperationException("The independent byte oracle received an unsupported scalar."); + default: + throw new InvalidOperationException("The independent byte oracle received an unsupported scalar."); } writer.Flush(); return stream.ToArray(); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs index f333958a3..9ae889ed5 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs @@ -1,5 +1,4 @@ using System; -using Inno.Core.Serialization.Converters; using Xunit; namespace Inno.Core.Serialization.Tests; @@ -23,21 +22,3 @@ public void ReusedScalarKeysPreserveCanonicalBytesAndRejectOutOfOrderDuplicates( Assert.Same(before, m_serialization.CaptureSnapshot(value, previous: before)); } } - -internal sealed class OrdinalCapture : ISerializable -{ - internal string[] names = ["first", "second", "third"]; -} - -internal sealed class OrdinalCaptureConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - OrdinalCapture value - ) { - foreach (string name in value.names) - writer.Write(name, 7); - } - - public override OrdinalCapture Read(SerializationReader reader) => throw new NotSupportedException(); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs index 5aaf3fe51..79f2c7b5e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; -using Inno.Core.Serialization.Converters; using Xunit; namespace Inno.Core.Serialization.Tests; @@ -97,7 +95,7 @@ public void SnapshotCapturePreservesOrdinaryBytesAndEveryDirectValueChange() for (int index = 0; index < 12; index++) { value.count++; - value.ratio = BitConverter.Int32BitsToSingle(index % 2 == 0 ? unchecked((int)0x80000000) : 0x7fc00001 + index); + value.ratio = BitConverter.Int32BitsToSingle(index % 2 == 0 ? unchecked((int)0x8000_0000) : 0x7FC0_0001 + index); value.bytes[index % 2]++; value.values.Add(index); SerializationSnapshot next = m_serialization.CaptureSnapshot(value, previous: snapshot); @@ -117,7 +115,9 @@ public void SnapshotObjectCaptureHandlesReplacementRemovalAndEmptyObjects(int co { var value = new SnapshotEnvelope { omitState = true }; for (int index = 0; index < count; index++) + { value.fields.Add("item-" + index, index); + } SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(value); value.fields.Remove("item-0"); value.fields.Add("replacement", 91); @@ -139,8 +139,10 @@ public void SnapshotStateBlobsUseTheExistingPropertyWireFormatAndDetectArrayShri value.state.count = 42; SerializationSnapshot before = m_serialization.CaptureSnapshot(value); byte[] bytes = before.ToArray(); - Assert.Equal(m_serialization.CapturePropertiesData(value.state), - m_serialization.Decode(bytes, reader => reader.Read("state"))); + Assert.Equal( + m_serialization.CapturePropertiesData(value.state), + m_serialization.Decode(bytes, reader => reader.Read("state")) + ); value.items.RemoveAt(1); value.state.name = "changed"; SerializationSnapshot after = m_serialization.CaptureSnapshot(value, previous: before); @@ -208,10 +210,14 @@ public void UnchangedLargeBinaryCaptureDoesNotCopyItsPayload() source.state.bytes = new byte[1024 * 1024]; SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(source); for (int index = 0; index < 8; index++) + { Assert.Same(snapshot, m_serialization.CaptureSnapshot(source, previous: snapshot)); + } long started = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 16; index++) + { Assert.Same(snapshot, m_serialization.CaptureSnapshot(source, previous: snapshot)); + } long allocated = (GC.GetAllocatedBytesForCurrentThread() - started) / 16; Assert.True(allocated < 16_384, $"An unchanged 1 MiB payload allocated {allocated} bytes per capture."); source.state.bytes[500] = 12; @@ -227,73 +233,3 @@ public void UnchangedLargeBinaryCaptureDoesNotCopyItsPayload() return (m_serialization.CaptureSnapshot(value), new WeakReference(value)); } } - -internal sealed class MutatingBinaryCapture : ISerializable -{ - internal byte[] bytes = [1]; -} - -internal sealed class MutatingBinaryCaptureConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - MutatingBinaryCapture value - ) { - writer.Write("bytes", value.bytes); - value.bytes[0] = 2; - } - - public override MutatingBinaryCapture Read(SerializationReader reader) => new() { bytes = reader.Read("bytes") }; -} - -internal sealed class MutatingPropertyCapture : ISerializable -{ - private readonly byte[] m_bytes = [1]; - - [SerializableProperty(PropertyVisibility.Serialize)] public byte[] bytes => m_bytes; - [SerializableProperty(PropertyVisibility.Serialize)] public int mutate => m_bytes[0] = 2; - - internal void Reset() => m_bytes[0] = 1; -} - -internal sealed class SnapshotEnvelope : ISerializable -{ - internal Dictionary fields { get; } = []; - internal List items { get; } = []; - internal DefaultSample state { get; } = new(); - internal bool omitState; - internal bool fail; - internal bool duplicate; - internal int writeCalls; - internal long observedTypeGeneration; -} - -internal sealed class SnapshotEnvelopeConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - SnapshotEnvelope value - ) { - value.writeCalls++; - value.observedTypeGeneration = writer.typeSnapshot.version; - foreach (var pair in value.fields) - writer.Write(pair.Key, pair.Value); - if (value.duplicate) - { - writer.Write("duplicate", 1); - writer.Write("duplicate", 2); - } - if (!value.omitState) - { - writer.WritePropertiesData("state", value.state); - writer.WriteObjectArray("items", value.items, static ( - child, - number - ) => child.Write("value", number)); - } - if (value.fail) - throw new InvalidOperationException("Capture rejected by its source converter."); - } - - public override SnapshotEnvelope Read(SerializationReader reader) => throw new NotSupportedException(); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs index c1727e205..d12f8496e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs @@ -1,16 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Threading.Tasks; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Core.Serialization.Converters; - -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -19,7 +17,9 @@ public sealed partial class SerializationBehaviorTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoSerializationTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private ModuleHost m_modules; private TypeCatalog m_types; private SerializationRegistry m_serialization; @@ -27,7 +27,9 @@ public sealed partial class SerializationBehaviorTests : IDisposable public SerializationBehaviorTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -38,59 +40,62 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Fact] public void IdentityRemapperRewritesNestedSerializedValuesWithoutChangingRawBinary() { - Guid oldId = Guid.Parse("ad68b7e0-62aa-47ba-ab94-1b0509d67560"); - Guid newId = Guid.Parse("02809cba-0be5-4ac4-a690-78e116fc26c1"); + Guid oldID = Guid.Parse("ad68b7e0-62aa-47ba-ab94-1b0509d67560"); + Guid newID = Guid.Parse("02809cba-0be5-4ac4-a690-78e116fc26c1"); byte[] nested = m_serialization.Serialize(new DefaultSample { - identity = oldId, + identity = oldID, name = "plugin::~Samples/Document.rml", bytes = [1, 2, 3] }); byte[] source = m_serialization.Serialize(new DefaultSample { - identity = oldId, + identity = oldID, bytes = nested }); - byte[] rewritten = SerializedIdentityRemapper.Rewrite(source, - new Dictionary { [oldId] = newId }, - new Dictionary { ["plugin::~Samples/Document.rml"] = "plugin-Samples/Document.rml" }); + byte[] rewritten = SerializedIdentityRemapper.Rewrite( + source, + new Dictionary { [oldID] = newID }, + new Dictionary { ["plugin::~Samples/Document.rml"] = "plugin-Samples/Document.rml" } + ); DefaultSample outer = m_serialization.Deserialize(rewritten); DefaultSample inner = m_serialization.Deserialize(outer.bytes); - Assert.Equal(newId, outer.identity); - Assert.Equal(newId, inner.identity); + Assert.Equal(newID, outer.identity); + Assert.Equal(newID, inner.identity); Assert.Equal("plugin-Samples/Document.rml", inner.name); Assert.Equal(new byte[] { 1, 2, 3 }, inner.bytes); } [Fact] - public void ISerializable_IsPureMarkerInterface() + public void ISerializableIsPureMarkerInterface() { Assert.Empty(typeof(ISerializable).GetMethods()); Assert.Empty(typeof(ISerializable).GetProperties()); } [Fact] - public void PublicOperations_RejectDisposedRegistry() + public void PublicOperationsRejectDisposedRegistry() { m_serialization.Dispose(); - Assert.Throws( - () => m_serialization.Serialize(new DefaultSample())); + Assert.Throws(() => m_serialization.Serialize(new DefaultSample())); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); Assert.NotEmpty(m_serialization.Serialize(new DefaultSample())); } [Fact] - public async Task CapturedGeneration_RemainsUsableAcrossRefreshAndWorkerContinuation() + public async Task CapturedGenerationRemainsUsableAcrossRefreshAndWorkerContinuation() { var source = new DefaultSample { count = 73, name = "Pinned" }; SerializationGeneration generation = m_serialization.CaptureGeneration(); @@ -106,7 +111,7 @@ public async Task CapturedGeneration_RemainsUsableAcrossRefreshAndWorkerContinua } [Fact] - public void TypeCatalogConstructor_RequiresActiveModuleHost() + public void TypeCatalogConstructorRequiresActiveModuleHost() { m_serialization.Dispose(); m_types.Dispose(); @@ -115,13 +120,15 @@ public void TypeCatalogConstructor_RequiresActiveModuleHost() Assert.Throws(() => new TypeCatalog(m_modules, new ReflectionTypeCatalogSource())); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } [Fact] - public void SerializeDeserialize_RoundTripsSupportedDefaultValues() + public void SerializeDeserializeRoundTripsSupportedDefaultValues() { var source = new DefaultSample { @@ -173,18 +180,18 @@ public void TypeRefSerializationPersistsOnlyStableIdentity() { SerializationReader type = reader.ReadObject("type"); Assert.True(type.Contains("stableId")); - Assert.False(type.Contains("runtimeId")); + Assert.False(type.Contains("runtimeID")); Assert.False(type.Contains("isValid")); return reader.Read("type"); }); Assert.Equal(active, restored); - Assert.Equal(0, restored.runtimeId); + Assert.Equal(0, restored.runtimeID); Assert.Equal(active.Resolve(m_types), restored.Resolve(m_types)); } [Fact] - public void Restore_UpdatesExistingInstance() + public void RestoreUpdatesExistingInstance() { var source = new DefaultSample { count = 77, name = "Restored" }; var target = new DefaultSample { count = 1, name = "Old" }; @@ -196,7 +203,7 @@ public void Restore_UpdatesExistingInstance() } [Fact] - public void CollectingPropertyRestore_CollectsInvalidMembersAndPreservesDefaults() + public void CollectingPropertyRestoreCollectsInvalidMembersAndPreservesDefaults() { var previous = new PreviousSchemaSample { @@ -204,14 +211,14 @@ public void CollectingPropertyRestore_CollectsInvalidMembersAndPreservesDefaults compatible = "preserved", removed = 9 }; - IReadOnlyList snapshots = - m_serialization.CaptureProperties(previous); + IReadOnlyList snapshots = m_serialization.CaptureProperties(previous); var current = new CurrentSchemaSample(); SerializationPropertyRestoreResult result = m_serialization.RestoreProperties( current, snapshots, - SerializationPropertyRestoreMode.CollectFailures); + SerializationPropertyRestoreMode.CollectFailures + ); Assert.False(result.success); Assert.Equal(1, result.restoredCount); @@ -227,23 +234,25 @@ public void CollectingPropertyRestore_CollectsInvalidMembersAndPreservesDefaults } [Fact] - public void StrictPropertyRestore_ThrowsForAnIncompatibleMember() + public void StrictPropertyRestoreThrowsForAnIncompatibleMember() { - IReadOnlyList snapshots = - m_serialization.CaptureProperties(new PreviousSchemaSample { changed = 42 }); + IReadOnlyList snapshots = m_serialization.CaptureProperties( + new PreviousSchemaSample { changed = 42 } + ); var current = new CurrentSchemaSample(); Assert.Throws(() => m_serialization.RestoreProperties( current, snapshots, - SerializationPropertyRestoreMode.Strict)); + SerializationPropertyRestoreMode.Strict + )); Assert.Equal("default", current.changed); Assert.Equal(0, current.restoreCount); } [Fact] - public void PropertyData_CapturesAndRestoresOnlyTheRequestedMember() + public void PropertyDataCapturesAndRestoresOnlyTheRequestedMember() { var source = new DefaultSample { @@ -266,7 +275,7 @@ public void PropertyData_CapturesAndRestoresOnlyTheRequestedMember() } [Fact] - public void PropertyData_RoundTripsAllPersistentMembersWithoutTheOwningObject() + public void PropertyDataRoundTripsAllPersistentMembersWithoutTheOwningObject() { var source = new PreviousSchemaSample { @@ -287,24 +296,21 @@ public void PropertyData_RoundTripsAllPersistentMembersWithoutTheOwningObject() } [Fact] - public void PropertyData_RejectsMalformedOrTrailingBytes() + public void PropertyDataRejectsMalformedOrTrailingBytes() { byte[] data = m_serialization.CapturePropertyData( new DefaultSample { count = 12 }, - nameof(DefaultSample.count)); - byte[] trailing = new byte[data.Length + 1]; + nameof(DefaultSample.count) + ); + var trailing = new byte[data.Length + 1]; data.CopyTo(trailing, 0); - Assert.Throws(() => m_serialization.RestorePropertiesData( - new DefaultSample(), - trailing)); - Assert.ThrowsAny(() => m_serialization.RestorePropertiesData( - new DefaultSample(), - new byte[] { 1, 2, 3 })); + Assert.Throws(() => m_serialization.RestorePropertiesData(new DefaultSample(), trailing)); + Assert.ThrowsAny(() => m_serialization.RestorePropertiesData(new DefaultSample(), [1, 2, 3])); } [Fact] - public void Deserialize_UsesNonPublicParameterlessConstructor() + public void DeserializeUsesNonPublicParameterlessConstructor() { byte[] bytes = m_serialization.Encode(static writer => writer.Write("value", 9)); @@ -315,52 +321,56 @@ public void Deserialize_UsesNonPublicParameterlessConstructor() } [Fact] - public void Deserialize_WithoutParameterlessConstructor_RequiresConverter() + public void DeserializeWithoutParameterlessConstructorRequiresConverter() { byte[] bytes = m_serialization.Encode(static writer => writer.Write("value", 5)); InvalidOperationException exception = Assert.Throws( - () => m_serialization.Deserialize(bytes)); + () => m_serialization.Deserialize(bytes) + ); Assert.Contains(typeof(MissingConstructorSample).FullName!, exception.Message); Assert.Contains("parameterless constructor", exception.Message); } [Fact] - public void Deserialize_UsesConverterWhenNoParameterlessConstructorExists() + public void DeserializeUsesConverterWhenNoParameterlessConstructorExists() { var source = new ConvertedConstructorSample(31); ConvertedConstructorSample restored = m_serialization.Deserialize( - m_serialization.Serialize(source)); + m_serialization.Serialize(source) + ); Assert.Equal(31, restored.value); } [Fact] - public void Deserialize_PreservesConstructorFailureAsInnerException() + public void DeserializePreservesConstructorFailureAsInnerException() { - byte[] bytes = m_serialization.Encode(static _ => { }); + byte[] bytes = m_serialization.Encode(static _ => {}); InvalidOperationException exception = Assert.Throws( - () => m_serialization.Deserialize(bytes)); + () => m_serialization.Deserialize(bytes) + ); Assert.IsType(exception.InnerException); Assert.Equal("constructor failure", exception.InnerException!.Message); } [Fact] - public void RequiredConverter_Missing_ThrowsClearError() + public void RequiredConverterMissingThrowsClearError() { InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(new MissingRequiredConverterSample())); + () => m_serialization.Serialize(new MissingRequiredConverterSample()) + ); Assert.Contains(typeof(MissingRequiredConverterSample).FullName!, exception.Message); Assert.Contains("requires an explicit serialization converter", exception.Message); } [Fact] - public void Visibility_ControlsPersistenceAndRuntimeMetadataStrictly() + public void VisibilityControlsPersistenceAndRuntimeMetadataStrictly() { var source = new VisibilitySample { @@ -408,28 +418,27 @@ public void Visibility_ControlsPersistenceAndRuntimeMetadataStrictly() } [Fact] - public void MetadataValidation_RejectsInvalidMembersAndDuplicateKeys() + public void MetadataValidationRejectsInvalidMembersAndDuplicateKeys() { - Assert.Throws( - () => m_serialization.GetProperties(new MissingSetterSample())); - Assert.Throws( - () => m_serialization.GetProperties(new DuplicateKeyDerivedSample())); + Assert.Throws(() => m_serialization.GetProperties(new MissingSetterSample())); + Assert.Throws(() => m_serialization.GetProperties(new DuplicateKeyDerivedSample())); } [Fact] - public void ClassMemberWithoutConverter_FailsWithCompletePath() + public void ClassMemberWithoutConverterFailsWithCompletePath() { var source = new MissingClassHost { child = new MissingChild { value = 1 } }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("$.child", exception.Message); Assert.Contains("SerializationConverter", exception.Message); } [Fact] - public void ClassCollectionElementWithoutConverter_FailsWithIndexedPath() + public void ClassCollectionElementWithoutConverterFailsWithIndexedPath() { var source = new MissingClassCollectionHost { @@ -437,13 +446,14 @@ public void ClassCollectionElementWithoutConverter_FailsWithIndexedPath() }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("$.children[0]", exception.Message); } [Fact] - public void ExplicitConverter_RoundTripsNestedClass() + public void ExplicitConverterRoundTripsNestedClass() { var source = new ConvertedChildHost { @@ -451,21 +461,23 @@ public void ExplicitConverter_RoundTripsNestedClass() }; ConvertedChildHost restored = m_serialization.Deserialize( - m_serialization.Serialize(source)); + m_serialization.Serialize(source) + ); Assert.NotNull(restored.child); Assert.Equal(14, restored.child!.value); } [Fact] - public void ExplicitConverter_CycleFailsWithBothPaths() + public void ExplicitConverterCycleFailsWithBothPaths() { var cycle = new CycleValue(); cycle.next = cycle; var source = new CycleHost { value = cycle }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("Serialization cycle detected", exception.Message); Assert.Contains("$.value", exception.Message); @@ -497,8 +509,7 @@ public void DeclaredTypeValueOperationsMatchGenericBytesAndPreserveNullableValue Assert.Throws(() => reader.Read("number", null!)); return true; }); - Assert.Throws(() => - m_serialization.Encode(writer => writer.Write("value", 1, null!))); + Assert.Throws(() => m_serialization.Encode(writer => writer.Write("value", 1, null!))); } [Fact] @@ -513,7 +524,7 @@ public void MetadataLookupExposesTheCurrentGenerationAndRejectsInvalidOwners() } [Fact] - public void ConverterSelection_PrefersNearestBaseThenExactType() + public void ConverterSelectionPrefersNearestBaseThenExactType() { var nearestSource = new NearestHost { item = new NearestLeaf { value = 21 } }; NearestHost nearest = m_serialization.Deserialize(m_serialization.Serialize(nearestSource)); @@ -527,12 +538,13 @@ public void ConverterSelection_PrefersNearestBaseThenExactType() } [Fact] - public void ConverterSelection_RejectsEqualDistanceAmbiguity() + public void ConverterSelectionRejectsEqualDistanceAmbiguity() { var source = new AmbiguousHost { item = new AmbiguousValue() }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("ambiguous converters", exception.Message); Assert.Contains(typeof(AmbiguousValue).FullName!, exception.Message); @@ -547,7 +559,7 @@ public void ConverterSelectionRanksVariantInterfacesAsAssignableInterfaces() } [Fact] - public void OpenGenericConverter_IsClosedFromRequestedType() + public void OpenGenericConverterIsClosedFromRequestedType() { var source = new GenericBoxHost { box = new GenericBox(45) }; @@ -558,7 +570,7 @@ public void OpenGenericConverter_IsClosedFromRequestedType() } [Fact] - public void SerializationContext_IsImmutableAndUsesExactTypeKeys() + public void SerializationContextIsImmutableAndUsesExactTypeKeys() { var service = new SampleContext(); SerializationContext original = SerializationContext.empty; @@ -573,7 +585,7 @@ public void SerializationContext_IsImmutableAndUsesExactTypeKeys() } [Fact] - public void ReaderWriter_ReportDuplicateMissingAndTypePaths() + public void ReaderWriterReportDuplicateMissingAndTypePaths() { InvalidOperationException duplicate = Assert.Throws(() => m_serialization.Encode(writer => @@ -585,7 +597,10 @@ public void ReaderWriter_ReportDuplicateMissingAndTypePaths() Assert.Contains("value", duplicate.Message); byte[] arrayBytes = m_serialization.Encode(writer => - writer.WriteObjectArray("items", new[] { 1 }, static (_, _) => { })); + writer.WriteObjectArray("items", new[] { 1 }, static ( + _, + _ + ) => {})); InvalidOperationException missing = Assert.Throws(() => m_serialization.Decode(arrayBytes, static reader => reader.ReadObjectArray("items")[0].Read("missing"))); @@ -603,7 +618,7 @@ public void ReaderWriter_ReportDuplicateMissingAndTypePaths() } [Fact] - public void ReaderWriter_AreInvalidOutsideTheirOperation() + public void ReaderWriterAreInvalidOutsideTheirOperation() { SerializationWriter? capturedWriter = null; _ = m_serialization.Encode(writer => capturedWriter = writer); @@ -620,7 +635,7 @@ public void ReaderWriter_AreInvalidOutsideTheirOperation() } [Fact] - public void RestoreHooks_RunOnceBaseToDerivedForDefaultAndConverterPaths() + public void RestoreHooksRunOnceBaseToDerivedForDefaultAndConverterPaths() { byte[] bytes = m_serialization.Encode(static writer => writer.Write("value", 3)); var target = new HookDerivedSample(); @@ -634,7 +649,8 @@ public void RestoreHooks_RunOnceBaseToDerivedForDefaultAndConverterPaths() var converted = new ConvertedHookSample { value = 8 }; ConvertedHookSample restored = m_serialization.Deserialize( - m_serialization.Serialize(converted)); + m_serialization.Serialize(converted) + ); Assert.Equal(1, restored.hookCount); var existing = new ConvertedHookSample(); @@ -644,10 +660,10 @@ public void RestoreHooks_RunOnceBaseToDerivedForDefaultAndConverterPaths() } [Fact] - public void CompletionCallbacks_RunOnlyAfterSuccessfulDecode() + public void CompletionCallbacksRunOnlyAfterSuccessfulDecode() { byte[] bytes = m_serialization.Encode(static writer => writer.Write("value", 1)); - var calls = new List(); + List calls = []; int value = m_serialization.Decode(bytes, reader => { reader.OnCompleted(() => calls.Add("completed")); @@ -667,7 +683,7 @@ public void CompletionCallbacks_RunOnlyAfterSuccessfulDecode() } [Fact] - public void NonStringMapEncoding_IsDeterministic() + public void NonStringMapEncodingIsDeterministic() { var left = new MapHost { values = new Dictionary { [9] = "nine", [1] = "one" } }; var right = new MapHost { values = new Dictionary { [1] = "one", [9] = "nine" } }; @@ -676,14 +692,17 @@ public void NonStringMapEncoding_IsDeterministic() } [Fact] - public void ForeignFormatHeader_IsRejected() + public void ForeignFormatHeaderIsRejected() { using var stream = new MemoryStream(); - using (var writer = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true)) + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { writer.Write("FOREIGN"); + } InvalidDataException exception = Assert.Throws( - () => m_serialization.Decode(stream.ToArray(), static _ => true)); + () => m_serialization.Decode(stream.ToArray(), static _ => true) + ); Assert.Contains("Invalid serialization magic", exception.Message); } } @@ -693,371 +712,3 @@ internal enum SampleMode Easy, Hard } - -internal sealed class PreviousSchemaSample : ISerializable -{ - [SerializableProperty] public int changed { get; set; } - [SerializableProperty(PropertyVisibility.Hide)] public string compatible { get; set; } = string.Empty; - [SerializableProperty] public int removed { get; set; } -} - -internal sealed class CurrentSchemaSample : ISerializable -{ - [SerializableProperty] public string changed { get; set; } = "default"; - [SerializableProperty(PropertyVisibility.Hide)] public string compatible { get; set; } = "new"; - [SerializableProperty] public int added { get; set; } = 17; - public int restoreCount { get; private set; } - - [OnSerializableRestored] - private void AfterRestore() => restoreCount++; -} - -internal sealed class DefaultSample : ISerializable -{ - [SerializableProperty] public bool enabled { get; set; } - [SerializableProperty] public int count { get; set; } - [SerializableProperty] public float ratio { get; set; } - [SerializableProperty] public decimal price { get; set; } - [SerializableProperty] public string name { get; set; } = string.Empty; - [SerializableProperty] public Guid identity { get; set; } - [SerializableProperty] public SampleMode mode { get; set; } - [SerializableProperty] public int? optional { get; set; } - [SerializableProperty] public byte[] bytes { get; set; } = []; - [SerializableProperty] public int[] numbers { get; set; } = []; - [SerializableProperty] public List values { get; set; } = []; - [SerializableProperty] public Dictionary map { get; set; } = []; - [SerializableProperty] public StructSample data { get; set; } -} - -internal struct StructSample -{ - public int x; - public int y { get; set; } - public readonly int readOnly; - [SerializableProperty] private int m_hidden; - public readonly int computed => x + m_hidden; - public readonly int hidden => m_hidden; - - private StructSample(int x, int y, int hidden) - { - this.x = x; - this.y = y; - readOnly = 99; - m_hidden = hidden; - } - - internal static StructSample Create(int x, int y, int hidden) => new(x, y, hidden); -} - -internal sealed class PrivateConstructorSample : ISerializable -{ - [SerializableProperty] public int value { get; set; } - public bool wasConstructed { get; } - - private PrivateConstructorSample() - { - wasConstructed = true; - } -} - -internal sealed class MissingConstructorSample : ISerializable -{ - [SerializableProperty] public int value { get; set; } - - public MissingConstructorSample(int value) - { - this.value = value; - } -} - -internal sealed class ConvertedConstructorSample : ISerializable -{ - public int value { get; set; } - - public ConvertedConstructorSample(int value) - { - this.value = value; - } -} - -internal sealed class ConvertedConstructorSampleConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, ConvertedConstructorSample value) - => writer.Write("value", value.value); - - public override ConvertedConstructorSample Read(SerializationReader reader) - => new(reader.Read("value")); - - public override void Restore(SerializationReader reader, ConvertedConstructorSample target) - => target.value = reader.Read("value"); -} - -internal sealed class ThrowingConstructorSample : ISerializable -{ - private ThrowingConstructorSample() - { - throw new ApplicationException("constructor failure"); - } -} - -[RequiresSerializationConverter] -internal sealed class MissingRequiredConverterSample : ISerializable; - -internal sealed class VisibilitySample : ISerializable -{ - [SerializableProperty] public int shown { get; set; } - [SerializableProperty(PropertyVisibility.Hide)] public int hidden { get; set; } - [SerializableProperty(PropertyVisibility.Readonly)] public int readOnly { get; set; } - [SerializableProperty(PropertyVisibility.Transient)] public int transient { get; set; } - [SerializableProperty(PropertyVisibility.SerializeOnly)] public int serializeOnly { get; set; } - [SerializableProperty(PropertyVisibility.DeserializeOnly)] public int deserializeOnly { get; set; } -} - -internal sealed class MissingSetterSample : ISerializable -{ - [SerializableProperty] - public int value { get; } = 1; -} - -internal class DuplicateKeyBaseSample : ISerializable -{ - [SerializableProperty] - public int value { get; set; } -} - -internal sealed class DuplicateKeyDerivedSample : DuplicateKeyBaseSample -{ - [SerializableProperty] - public new int value { get; set; } -} - -internal sealed class MissingChild -{ - public int value { get; set; } -} - -internal sealed class MissingClassHost : ISerializable -{ - [SerializableProperty] public MissingChild? child { get; set; } -} - -internal sealed class MissingClassCollectionHost : ISerializable -{ - [SerializableProperty] public List children { get; set; } = []; -} - -internal sealed class ConvertedChild -{ - public int value { get; set; } -} - -internal sealed class ConvertedChildHost : ISerializable -{ - [SerializableProperty] public ConvertedChild? child { get; set; } -} - -internal sealed class CycleValue -{ - public CycleValue? next { get; set; } -} - -internal sealed class CycleHost : ISerializable -{ - [SerializableProperty] public CycleValue? value { get; set; } -} - -internal sealed class CycleValueConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, CycleValue value) - => writer.Write("next", value.next); - - public override CycleValue Read(SerializationReader reader) - => new() { next = reader.Read("next") }; -} - -internal sealed class ConvertedChildConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, ConvertedChild value) - => writer.Write("value", value.value); - - public override ConvertedChild Read(SerializationReader reader) - => new() { value = reader.Read("value") }; -} - -internal class NearestBase -{ - public int value { get; set; } - public string selectedBy { get; set; } = string.Empty; -} - -internal class NearestMid : NearestBase; - -internal sealed class NearestLeaf : NearestMid; - -internal sealed class NearestHost : ISerializable -{ - [SerializableProperty] public NearestLeaf? item { get; set; } -} - -internal sealed class NearestBaseConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, NearestBase value) - => writer.Write("value", value.value); - - public override NearestBase Read(SerializationReader reader) - => new NearestLeaf { value = reader.Read("value"), selectedBy = "base" }; -} - -internal sealed class NearestMidConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, NearestMid value) - => writer.Write("value", value.value); - - public override NearestMid Read(SerializationReader reader) - => new NearestLeaf { value = reader.Read("value"), selectedBy = "mid" }; -} - -internal class ExactBase -{ - public int value { get; set; } - public string selectedBy { get; set; } = string.Empty; -} - -internal sealed class ExactLeaf : ExactBase; - -internal sealed class ExactHost : ISerializable -{ - [SerializableProperty] public ExactLeaf? item { get; set; } -} - -internal sealed class ExactBaseConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, ExactBase value) - => writer.Write("value", value.value); - - public override ExactBase Read(SerializationReader reader) - => new ExactLeaf { value = reader.Read("value"), selectedBy = "base" }; -} - -internal sealed class ExactLeafConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, ExactLeaf value) - => writer.Write("value", value.value); - - public override ExactLeaf Read(SerializationReader reader) - => new() { value = reader.Read("value"), selectedBy = "exact" }; -} - -internal interface IAmbiguousLeft; - -internal interface IAmbiguousRight; - -internal sealed class AmbiguousValue : IAmbiguousLeft, IAmbiguousRight; - -internal sealed class AmbiguousHost : ISerializable -{ - [SerializableProperty] public AmbiguousValue? item { get; set; } -} - -internal sealed class AmbiguousLeftConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, IAmbiguousLeft value) { } - public override IAmbiguousLeft Read(SerializationReader reader) => new AmbiguousValue(); -} - -internal sealed class AmbiguousRightConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, IAmbiguousRight value) { } - public override IAmbiguousRight Read(SerializationReader reader) => new AmbiguousValue(); -} - -internal sealed class GenericBox -{ - public T value { get; } - - public GenericBox(T value) - { - this.value = value; - } -} - -internal sealed class GenericBoxHost : ISerializable -{ - [SerializableProperty] public GenericBox? box { get; set; } -} - -internal sealed class GenericBoxConverter : SerializationConverter> -{ - public override void Write(SerializationWriter writer, GenericBox value) - => writer.Write("value", value.value); - - public override GenericBox Read(SerializationReader reader) - => new(reader.Read("value")); -} - -internal interface IVariantValue -{ - T value { get; } -} - -internal sealed class VariantValue(string value) : IVariantValue -{ - public string value { get; } = value; -} - -internal sealed class VariantValueConverter : SerializationConverter> -{ - public override void Write( - SerializationWriter writer, - IVariantValue value - ) => writer.Write("value", (string)value.value); - - public override IVariantValue Read(SerializationReader reader) - => new VariantValue(reader.Read("value")); -} - -internal interface ISampleContext; - -internal sealed class SampleContext : ISampleContext; - -internal class HookBaseSample : ISerializable -{ - [SerializableProperty] public int value { get; set; } - public List calls { get; } = []; - - [OnSerializableRestored] - private void AfterBaseRestore() => calls.Add("base"); -} - -internal sealed class HookDerivedSample : HookBaseSample -{ - [OnSerializableRestored] - private void AfterDerivedRestore() => calls.Add("derived"); -} - -internal sealed class ConvertedHookSample : ISerializable -{ - public int value { get; set; } - public int hookCount { get; private set; } - - [OnSerializableRestored] - private void AfterRestore() => hookCount++; -} - -internal sealed class ConvertedHookSampleConverter : SerializationConverter -{ - public override void Write(SerializationWriter writer, ConvertedHookSample value) - => writer.Write("value", value.value); - - public override ConvertedHookSample Read(SerializationReader reader) - => new() { value = reader.Read("value") }; - - public override void Restore(SerializationReader reader, ConvertedHookSample target) - => target.value = reader.Read("value"); -} - -internal sealed class MapHost : ISerializable -{ - [SerializableProperty] - public Dictionary values { get; set; } = []; -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs b/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs new file mode 100644 index 000000000..478efbbe0 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs @@ -0,0 +1,10 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class SerializedCaptureCounter : IdentityObject, ISerializable +{ + [SerializableProperty(PropertyVisibility.Serialize)] + public ulong revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs new file mode 100644 index 000000000..c6a6d1953 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class SnapshotEnvelope : ISerializable +{ + internal bool omitState; + internal bool fail; + internal bool duplicate; + internal int writeCalls; + internal long observedTypeGeneration; + + internal Dictionary fields { get; } = []; + internal List items { get; } = []; + internal DefaultSample state { get; } = new(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs new file mode 100644 index 000000000..216eee285 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class SnapshotEnvelopeConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + SnapshotEnvelope value + ) { + value.writeCalls++; + value.observedTypeGeneration = writer.typeSnapshot.version; + foreach (KeyValuePair pair in value.fields) + { + writer.Write(pair.Key, pair.Value); + } + if (value.duplicate) + { + writer.Write("duplicate", 1); + writer.Write("duplicate", 2); + } + if (!value.omitState) + { + writer.WritePropertiesData("state", value.state); + writer.WriteObjectArray("items", value.items, static ( + child, + number + ) => child.Write("value", number)); + } + if (value.fail) + { + throw new InvalidOperationException("Capture rejected by its source converter."); + } + } + + public override SnapshotEnvelope Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/StructSample.cs b/tests/core/Inno.Core.Serialization.Tests/StructSample.cs new file mode 100644 index 000000000..1f1286e91 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/StructSample.cs @@ -0,0 +1,31 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct StructSample +{ + public int x; + public int y { get; set; } + public readonly int readOnly; + + [SerializableProperty] + private int m_hidden; + + public readonly int computed => x + m_hidden; + public readonly int hidden => m_hidden; + + private StructSample( + int x, + int y, + int hidden + ) { + this.x = x; + this.y = y; + this.readOnly = 99; + m_hidden = hidden; + } + + internal static StructSample Create( + int x, + int y, + int hidden + ) => new(x, y, hidden); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs new file mode 100644 index 000000000..bc2d4d33a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs @@ -0,0 +1,11 @@ +using System; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ThrowingConstructorSample : ISerializable +{ + private ThrowingConstructorSample() + { + throw new ApplicationException("constructor failure"); + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs new file mode 100644 index 000000000..51174051c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs @@ -0,0 +1,9 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class UntrackedCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public int number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs b/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs new file mode 100644 index 000000000..2d7252b44 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class VariantValue(string value) : IVariantValue +{ + public string value { get; } = value; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs new file mode 100644 index 000000000..e6b87741d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class VariantValueConverter : SerializationConverter> +{ + public override void Write( + SerializationWriter writer, + IVariantValue value + ) => writer.Write("value", (string)value.value); + + public override IVariantValue Read(SerializationReader reader) + => new VariantValue(reader.Read("value")); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs b/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs new file mode 100644 index 000000000..b0b728f4a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs @@ -0,0 +1,22 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class VisibilitySample : ISerializable +{ + [SerializableProperty] + public int shown { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public int hidden { get; set; } + + [SerializableProperty(PropertyVisibility.Readonly)] + public int readOnly { get; set; } + + [SerializableProperty(PropertyVisibility.Transient)] + public int transient { get; set; } + + [SerializableProperty(PropertyVisibility.SerializeOnly)] + public int serializeOnly { get; set; } + + [SerializableProperty(PropertyVisibility.DeserializeOnly)] + public int deserializeOnly { get; set; } +} diff --git a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs index f90984c9a..73243d39c 100644 --- a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs +++ b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs @@ -1,15 +1,17 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; +using Inno.Core.Logging; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; + +using RuntimeAudio = Inno.Audio.Audio; namespace Inno.Editor.Audio.Tests; @@ -24,8 +26,11 @@ public EditorAudioHostTests() m_root = Path.Combine(Path.GetTempPath(), "InnoEditorAudioTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(m_root); m_engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(EditorAudioHostTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(EditorAudioHostTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); } @@ -33,7 +38,9 @@ public void Dispose() { m_engine.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -43,20 +50,27 @@ public void EditAndPlaySessionsOwnIndependentExecutionScopesAndLifetimes() m_engine.types, m_artifacts, m_engine.diagnostics, - deviceFactory: static () => new MutedAudioDevice()); + deviceFactory: static () => new MutedAudioDevice() + ); using RuntimeSession edit = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Edit, "edit")); using (host.EnterExecutionScope(edit)) - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + { + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); + } using (RuntimeSession play = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Play, "play"))) { using (host.EnterExecutionScope(play)) - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + { + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); + } play.Tick(0.016f); } using (host.EnterExecutionScope(edit)) - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + { + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); + } edit.Tick(0.016f); } @@ -67,11 +81,14 @@ public void PreviewUsesTheRealAudioServiceAndRejectsPlaySessionPreview() m_engine.types, m_artifacts, m_engine.diagnostics, - deviceFactory: static () => new MutedAudioDevice()); + deviceFactory: static () => new MutedAudioDevice() + ); using RuntimeSession edit = m_engine.CreateSession( - CreateOptions(host, RuntimeSessionKind.Edit, "preview-edit")); + CreateOptions(host, RuntimeSessionKind.Edit, "preview-edit") + ); using RuntimeSession play = m_engine.CreateSession( - CreateOptions(host, RuntimeSessionKind.Play, "preview-play")); + CreateOptions(host, RuntimeSessionKind.Play, "preview-play") + ); AudioClipAsset clip = CreateClip(); AudioVoiceHandle voice = host.PlayPreview(edit, clip); @@ -84,60 +101,50 @@ public void PreviewUsesTheRealAudioServiceAndRejectsPlaySessionPreview() private RuntimeSessionOptions CreateOptions( IEditorAudioHost host, RuntimeSessionKind kind, - string name) - => new() - { - kind = kind, - applicationId = name, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", name), "Logs")), - jobExecutionMode = RuntimeJobExecutionMode.SingleThread, - createSubsystems = owner => [host.CreateRuntimeSubsystemFactory(owner)] - }; + string name + ) => new() + { + kind = kind, + applicationID = name, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", name), "Logs")), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread, + createSubsystems = owner => [host.CreateRuntimeSubsystemFactory(owner)] + }; private AudioClipAsset CreateClip() { var clip = new AudioClipAsset(); - byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata( - AudioCodecId.wav, - 1, - 48000, - 480000, - 128)); + byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata(AudioCodecID.wav, 1, 48_000, 480_000, 128)); new AssetRuntimeOwner().Initialize( clip, AssetPath.Project("Audio/Preview.wav"), "TEST", payload, isMissing: false, - version: 1); + version: 1 + ); string path = Path.Combine(m_root, "preview.wav"); File.WriteAllBytes(path, new byte[128]); - m_artifacts.Add(clip.identity.persistentId, path); + m_artifacts.Add(clip.identity.persistentID, path); return clip; } private sealed class FakeArtifactLookup : IAssetArtifactLookup { private readonly ArtifactRetention m_retention = new(); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - => m_retention.Retain(m_artifacts[persistentId].info, - () => File.OpenRead(m_artifacts[persistentId].path)); private readonly Dictionary m_artifacts = []; - internal void Add( - Guid id, - string path - ) - => m_artifacts.Add( - id, - (new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), "audio-data", "TEST", 128), path)); + public ArtifactLease AcquireArtifact( + Guid persistentID, + string outputName + ) => m_retention.Retain(m_artifacts[persistentID].info, () => File.OpenRead(m_artifacts[persistentID].path)); public bool TryGetArtifact( - Guid persistentId, + Guid persistentID, string outputName, out AssetArtifactInfo? artifact ) { - if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentId, out var found)) + if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentID, out (AssetArtifactInfo info, string path) found)) { artifact = found.info; return true; @@ -145,5 +152,13 @@ out AssetArtifactInfo? artifact artifact = null; return false; } + + internal void Add( + Guid id, + string path + ) => m_artifacts.Add( + id, + (new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), "audio-data", "TEST", 128), path) + ); } } diff --git a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs index c1af81397..250f95fb3 100644 --- a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs @@ -1,82 +1,88 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using BGCS.Runtime; +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Exporting; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Native.ImGui; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; -using Xunit; -using NativeImGui = Inno.Native.ImGui.ImGui; -using ImGuiEditorRuntime = Inno.Editor.ImGui.ImGuiEditorRuntime; -using Inno.Core.Input; -using Inno.Core.Logging; -using NativeGui = Inno.Native.ImGui.ImGui; -using EditorUiSession = Inno.Editor.ImGui.EditorUiSession; -using Inno.Build; using Inno.Testing.Build; +using GuiSession = Inno.Editor.ImGui.EditorUISession; +using NativeGui = Inno.Native.ImGui.ImGui; +using UIRuntime = Inno.Editor.ImGui.ImGuiEditorRuntime; + namespace Inno.Editor.Exporting.Native.Tests; public sealed class ExportPresentationTests : BuildPipelineFixture { - [Fact] [Trait("ExternalDependency", "NativeProduct")] public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportServices() { SaveStartupScene(); - Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value), recursive: true); + Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetID("macos-arm64").value), recursive: true); var provisioner = new DrainingSupportPackProvisioner(); BuildPipeline pipeline = CreatePipeline(provisioner); - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetID("macos-arm64")); var buildSettings = new BuildSettingsStore( - Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); m_engine.modules.Register("Tests.Exporting", [ typeof(EditorExportService).Assembly, Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) ]); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); using var runtime = new EditorInteractionRuntime( - context, m_engine.types, m_engine.logs, [pipeline, buildSettings, m_settings]); + context, + m_engine.types, + m_engine.logs, + [pipeline, buildSettings, m_settings] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/game")); EditorModalExtension modal = Assert.Single(runtime.modals.Where(static item => item.id == "export.game")); EditorModalExtension progress = Assert.Single(runtime.modals.Where(static item => item.id == "export.game.progress")); - ImGuiNativeContext* imgui = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* imgui = NativeGui.Raw.CreateContext(null); try { - NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + NativeGui.Raw.GetIO()->IniFilename = null; + using var uiSession = new GuiSession(); using IDisposable uiScope = uiSession.Enter(); - ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = 1200f, Y = 900f }; io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -87,19 +93,21 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe { if (frame == 2) { - NativeImGui.Raw.AddMousePosEvent(io, exportCenter.X, exportCenter.Y); - NativeImGui.Raw.AddMouseButtonEvent(io, 0, 1); + NativeGui.Raw.AddMousePosEvent(io, exportCenter.X, exportCenter.Y); + NativeGui.Raw.AddMouseButtonEvent(io, 0, 1); } if (frame == 3) - NativeImGui.Raw.AddMouseButtonEvent(io, 0, 0); - NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f), (int)ImGuiCond.Always); - NativeImGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); - _ = NativeImGui.Raw.Begin((sbyte*)title.pointer, null, (int)ImGuiWindowFlags.NoSavedSettings); + { + NativeGui.Raw.AddMouseButtonEvent(io, 0, 0); + } + NativeGui.NewFrame(); + NativeGui.SetNextWindowPos(new Vector2(20f), (int)ImGuiCond.Always); + NativeGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); + _ = NativeGui.Raw.Begin((sbyte*)title.pointer, null, (int)ImGuiWindowFlags.NoSavedSettings); Assert.True(modal.Draw(context)); - exportCenter = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; - NativeImGui.End(); - NativeImGui.Render(); + exportCenter = (NativeGui.GetItemRectMin() + NativeGui.GetItemRectMax()) * 0.5f; + NativeGui.End(); + NativeGui.Render(); } Assert.True(provisioner.started); Assert.True(progress.TryGetPresentation(out EditorModalExtension.Presentation presentation)); @@ -116,7 +124,7 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe Assert.True(provisioner.canceled.Task.IsCompletedSuccessfully); Assert.False(provisioner.completed); provisioner.cleanup.SetResult(); - var retirement = System.Diagnostics.Stopwatch.StartNew(); + Stopwatch retirement = Stopwatch.StartNew(); while (true) { try @@ -127,7 +135,9 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (retirement.Elapsed >= TimeSpan.FromSeconds(5)) + { throw; + } Thread.Sleep(1); } } @@ -137,22 +147,36 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe finally { provisioner.cleanup.TrySetResult(); - NativeImGui.Raw.DestroyContext(imgui); + NativeGui.Raw.DestroyContext(imgui); } } + [Fact] [Trait("ExternalDependency", "NativeProduct")] public unsafe void ExportFormBalancesItsTablesWhenARegisteredTargetLabelFails() { var target = new ExportLabelTarget(); - var pipeline = new BuildPipeline(m_assets, m_plugins, m_settings, m_engine.serialization, - m_engine.generations, m_compiler, m_supportPackRoot, - [new GameBuildTargetBinding(target, target)], CreateManagedDeployments()); - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", target.id); - var settings = new BuildSettingsStore(System.IO.Path.Combine(m_projectRoot, "Settings.Build.inno"), - m_engine.serialization, defaults); - m_engine.modules.Register("Tests.Exporting", [typeof(EditorExportService).Assembly, - Assembly.Load(new AssemblyName("Inno.Editor.Workbench"))]); + var pipeline = new BuildPipeline( + m_assets, + m_plugins, + m_settings, + m_engine.serialization, + m_engine.generations, + m_compiler, + m_supportPackRoot, + [new GameBuildTargetBinding(target, target)], + CreateManagedDeployments() + ); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", target.id); + var settings = new BuildSettingsStore( + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); + m_engine.modules.Register("Tests.Exporting", [ + typeof(EditorExportService).Assembly, + Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) + ]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); var logs = new ExportLogSink(); ImGuiNativeContext* native = NativeGui.Raw.CreateContext(null); @@ -160,10 +184,14 @@ public unsafe void ExportFormBalancesItsTablesWhenARegisteredTargetLabelFails() { NativeGui.Raw.GetIO()->IniFilename = null; m_engine.logs.RegisterSink(logs); - using var session = new EditorUiSession(); + using var session = new GuiSession(); using IDisposable scope = session.Enter(); - using var runtime = new EditorInteractionRuntime(context, m_engine.types, m_engine.logs, - [pipeline, settings, m_settings, session]); + using var runtime = new EditorInteractionRuntime( + context, + m_engine.types, + m_engine.logs, + [pipeline, settings, m_settings, session] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/game")); EditorModalExtension modal = Assert.Single(runtime.modals, item => item.id == "export.game"); @@ -202,21 +230,31 @@ public unsafe void ExportPresentationUsesTheDeclaredWidthAndRealOverflow( int height, float dpi ) { - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); - var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); - m_engine.modules.Register("Tests.ExportPresentation", [typeof(EditorExportService).Assembly, - Assembly.Load(new AssemblyName("Inno.Editor.Workbench"))]); - var native = NativeGui.Raw.CreateContext(null); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetID("macos-arm64")); + var settings = new BuildSettingsStore( + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); + m_engine.modules.Register("Tests.ExportPresentation", [ + typeof(EditorExportService).Assembly, + Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) + ]); + ImGuiNativeContext* native = NativeGui.Raw.CreateContext(null); try { NativeGui.Raw.GetIO()->IniFilename = null; - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = width, Y = height }; io->DeltaTime = 0.2f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - using var runtime = new ImGuiEditorRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), - m_engine.types, m_engine.logs, [m_pipeline, settings, m_settings]); + using var runtime = new UIRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), + m_engine.types, + m_engine.logs, + [m_pipeline, settings, m_settings] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/plugin")); NativeGui.Raw.GetStyle()->FontScaleDpi = dpi; @@ -227,9 +265,12 @@ float dpi runtime.Draw(); NativeGui.Render(); } - using var title = BGCS.Runtime.Utf8Codec.EncodeNullTerminated("Export as Plugin##export.plugin", allowsNull: false); - var window = NativeGui.Raw.FindWindowByName((sbyte*)title.pointer); - Assert.True(window != null && window->WasActive != 0); + using NativeStringLease title = Utf8Codec.EncodeNullTerminated( + "Export as Plugin##export.plugin", + allowsNull: false + ); + ImGuiWindow* window = NativeGui.Raw.FindWindowByName((sbyte*)title.pointer); + Assert.True(window is not null && window->WasActive != 0); Assert.True(window->Size.X <= width && window->Size.Y <= height); if (width == 1280) { @@ -238,8 +279,10 @@ float dpi Assert.InRange(window->ScrollMax.Y, 0f, 0.01f); } else + { Assert.True(window->ScrollMax.Y > 0f); - Assert.True(runtime.interactions.TryGetModule(out var exports)); + } + Assert.True(runtime.interactions.TryGetModule(out EditorExportService? exports)); Assert.False(exports!.progress.isBusy); } finally @@ -260,10 +303,12 @@ EditorModalExtension modal try { bool drawn = modal.Draw(context); - bool leaked = NativeGui.Raw.GetCurrentTable() != null; + bool leaked = NativeGui.Raw.GetCurrentTable() is not null; // Retire only a table opened by this fixture's modal before reporting a failed regression. if (leaked) + { NativeGui.EndTable(); + } Assert.False(leaked, "A modal failure left its own native Table active."); return drawn; } @@ -276,19 +321,21 @@ EditorModalExtension modal private sealed class ExportLogSink : ILogSink { - internal List messages { get; } = []; public void Receive(LogEntry entry) => messages.Add(entry.message); + + internal List messages { get; } = []; } private sealed class ExportLabelTarget : IGameBuildTarget, IGameContentCompiler { - internal bool reject { get; set; } - public BuildTargetId id => new("fixture-export"); - public BuildTargetId target => id; - public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; + public BuildTargetID id => new("fixture-export"); + public BuildTargetID target => id; + public ManagedDeploymentID defaultManagedDeployment => ManagedDeploymentID.coreClr; public string runtimeIdentifier => "fixture"; public string displayName => reject ? throw new InvalidOperationException("Export target label failed.") : "Fixture target"; - public void Validate(string directory) => throw new InvalidOperationException("This presentation fixture cannot validate products."); + + public void Validate(string directory) + => throw new InvalidOperationException("This presentation fixture cannot validate products."); public ValueTask PackageAsync( GameBuildPackageContext context, @@ -299,5 +346,7 @@ public ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default ) => throw new InvalidOperationException("This presentation fixture cannot compile content."); + + internal bool reject { get; set; } } } diff --git a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs index b7419ec19..0290f6e2f 100644 --- a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs @@ -1,35 +1,46 @@ using System.IO; +using Xunit; using Inno.Build; using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.Exporting; +using Inno.Editor.Interactions; using Inno.Testing.Build; -using Xunit; namespace Inno.Editor.Exporting.Tests; public sealed class ExportWorkflowTests : BuildPipelineFixture { - [Fact] public void ExportPresentationKeepsUnknownProgressAndRejectsStaleCancellation() { - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); - var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetID("macos-arm64")); + var settings = new BuildSettingsStore( + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); m_engine.modules.Register("Tests.ExportProgress", [typeof(EditorExportService).Assembly]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); - using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime(context, m_engine.types, m_engine.logs, - [m_pipeline, settings, m_settings]); + using var runtime = new EditorInteractionRuntime( + context, + m_engine.types, + m_engine.logs, + [m_pipeline, settings, m_settings] + ); runtime.Start(); - Assert.True(runtime.interactions.TryGetModule(out var exports)); - exports!.StartGame(new GameBuildRequest { profile = CreateProfile(new BuildTargetId("macos-arm64")), - outputDirectory = Path.Combine(m_root, "ProgressOutput") }); - var observed = exports.progress; + Assert.True(runtime.interactions.TryGetModule(out EditorExportService? exports)); + exports!.StartGame(new GameBuildRequest + { + profile = CreateProfile(new BuildTargetID("macos-arm64")), + outputDirectory = Path.Combine(m_root, "ProgressOutput") + }); + EditorExportProgress observed = exports.progress; Assert.Null(observed.fraction); Assert.True(observed.isBusy); - exports.Cancel(observed.operationId - 1); + exports.Cancel(observed.operationID - 1); Assert.False(exports.progress.cancellationRequested); - exports.Cancel(observed.operationId); + exports.Cancel(observed.operationID); Assert.True(exports.progress.cancellationRequested); Assert.False(observed.cancellationRequested); exports.Stop(context); diff --git a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs index b6c9d4bfb..f86accd73 100644 --- a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs +++ b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs @@ -1,19 +1,21 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; +using System.Text; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; +using Inno.Core.Input; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Interactions; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; namespace Inno.Editor.Graph.Tests; @@ -22,7 +24,9 @@ public sealed class GraphDocumentControllerTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoEditorGraphTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -35,14 +39,17 @@ public GraphDocumentControllerTests() { _ = typeof(GraphEditorModule); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphDocumentControllerTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphDocumentControllerTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_testRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_testRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, - [m_serialization, m_sink, m_reloads]); + [m_serialization, m_sink, m_reloads] + ); m_runtime.Start(); } @@ -57,7 +64,9 @@ public void Dispose() GC.WaitForPendingFinalizers(); GC.Collect(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Theory] @@ -80,13 +89,20 @@ public void AssemblyPublicationPreservesNeutralGraphAndRollsBackLaterParticipant using (AssemblyReloadSession reload = m_modules.BeginReload([new DotNetModuleSource { artifactRootDirectory = Path.Combine(m_testRoot, "Assemblies"), - moduleName = "GraphRecovery", domain = AssemblyDomain.InnoPlugin, scope = AssemblyScope.Runtime, + moduleName = "GraphRecovery", + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime, mainAssemblyPath = Path.Combine(directory, "Inno.Extensibility.Modules.TestModule.dll"), preloadAssemblyPaths = [Path.Combine(directory, "Reloadable.PrivateDependency.dll")] - }])) - { - if (reject) Assert.Throws(() => m_reloads.Execute(reload)); - else _ = m_reloads.Execute(reload); + }])) { + if (reject) + { + Assert.Throws(() => m_reloads.Execute(reload)); + } + else + { + _ = m_reloads.Execute(reload); + } } m_modules.generations.Wait(); Assert.Equal(GenerationState.Ready, m_modules.generations.state); @@ -109,13 +125,15 @@ public void OneHundredDocumentCyclesReleasePayloadsAndRejectRetiredControllers() { GraphEditorModule module = Assert.IsType(m_sink.module); Guid identity = Guid.NewGuid(); - var retired = new List<(GraphDocumentController controller, WeakReference document)>(); + List<(GraphDocumentController controller, WeakReference document)> retired = []; for (int iteration = 0; iteration < 100; iteration++) + { retired.Add(OpenAndClose()); + } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); - foreach (var entry in retired) + foreach ((GraphDocumentController controller, WeakReference document) entry in retired) { Assert.False(entry.controller.isAvailable); Assert.False(entry.document.TryGetTarget(out _)); @@ -128,23 +146,12 @@ public void OneHundredDocumentCyclesReleasePayloadsAndRejectRetiredControllers() { var document = new GraphDocument(); GraphDocumentController controller = module.OpenDocument(identity, document, m_runtime.interactions.history); - controller.AddNode("missing.example", new(7f, 9f)); + controller.AddNode("missing.example", new GraphPosition(7f, 9f)); Assert.True(module.CloseDocument(identity)); return (controller, new WeakReference(document)); } } - private sealed class RejectionParticipant(bool reject) : IEditorReloadParticipant, IGenerationChange - { - public IGenerationChange Capture(AssemblyReloadContext context) => this; - public void RefreshDiagnostics() { } - public void PrepareForActivation() { } - public void Apply() { if (reject) throw new InvalidOperationException("Later recovery participant rejected the candidate."); } - public void Complete() { } - public void RollbackStructure() { } - public void RestorePreviousState() { } - } - [Fact] public void MissingGraphHistoryRecoversWithoutLosingDirtyStateOrReusingStaleController() { @@ -177,38 +184,38 @@ public void MissingGraphHistoryRecoversWithoutLosingDirtyStateOrReusingStaleCont } [Fact] - public void AddNode_RecordsNeutralHistoryPayload() + public void AddNodeRecordsNeutralHistoryPayload() { GraphEditorModule module = Assert.IsType(m_sink.module); var history = new RecordingHistory(); var document = new GraphDocument(); GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), document, history); - GraphNodeId nodeId = controller.AddNode("test.node", new GraphPosition(2f, 3f)); + GraphNodeID nodeID = controller.AddNode("test.node", new GraphPosition(2f, 3f)); EditorHistoryChange change = Assert.Single(history.changes); - Assert.Equal(nodeId, Assert.Single(document.nodes).id); + Assert.Equal(nodeID, Assert.Single(document.nodes).id); Assert.True(change.payload.length > 0); change.Dispose(); } [Fact] - public void ReplaceDocument_IsAtomicUndoableAndDoesNotRetainTheCallerDocument() + public void ReplaceDocumentIsAtomicUndoableAndDoesNotRetainTheCallerDocument() { GraphEditorModule module = Assert.IsType(m_sink.module); var history = new RecordingHistory(); var document = new GraphDocument(); - document.AddNode(new GraphNodeRecord(new GraphNodeId("old"), "test.old")); + document.AddNode(new GraphNodeRecord(new GraphNodeID("old"), "test.old")); GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), document, history); var replacement = new GraphDocument(); - var replacementNode = new GraphNodeRecord(new GraphNodeId("new"), "test.new"); + var replacementNode = new GraphNodeRecord(new GraphNodeID("new"), "test.new"); replacement.AddNode(replacementNode); controller.ReplaceDocument(replacement, "Replace Test Graph"); replacementNode.position = new GraphPosition(99f, 99f); GraphNodeRecord current = Assert.Single(controller.document.nodes); - Assert.Equal(new GraphNodeId("new"), current.id); + Assert.Equal(new GraphNodeID("new"), current.id); Assert.Equal(default, current.position); Assert.Equal(1UL, controller.revision); Assert.True(controller.isDirty); @@ -217,20 +224,21 @@ public void ReplaceDocument_IsAtomicUndoableAndDoesNotRetainTheCallerDocument() } [Fact] - public void CopyPaste_RemapsNodesAndPreservesInternalConnections() + public void CopyPasteRemapsNodesAndPreservesInternalConnections() { GraphEditorModule module = Assert.IsType(m_sink.module); var history = new RecordingHistory(); var document = new GraphDocument(); GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), document, history); - GraphNodeId first = controller.AddNode("test.first", new GraphPosition(1f, 2f)); - GraphNodeId second = controller.AddNode("test.second", new GraphPosition(3f, 4f)); + GraphNodeID first = controller.AddNode("test.first", new GraphPosition(1f, 2f)); + GraphNodeID second = controller.AddNode("test.second", new GraphPosition(3f, 4f)); controller.Connect( - new GraphEndpoint(first, new GraphPortId("out")), - new GraphEndpoint(second, new GraphPortId("in"))); + new GraphEndpoint(first, new GraphPortID("out")), + new GraphEndpoint(second, new GraphPortID("in")) + ); GraphClipboardData clipboard = controller.Copy([first, second]); - IReadOnlyList pasted = controller.Paste(clipboard, new GraphPosition(10f, 20f)); + IReadOnlyList pasted = controller.Paste(clipboard, new GraphPosition(10f, 20f)); Assert.Equal(2, pasted.Count); Assert.DoesNotContain(first, pasted); @@ -243,7 +251,7 @@ public void CopyPaste_RemapsNodesAndPreservesInternalConnections() } [Fact] - public void CanvasZoom_PreservesGraphPointUnderPivot() + public void CanvasZoomPreservesGraphPointUnderPivot() { var canvas = new GraphCanvasState(); canvas.SetViewport(new GraphPosition(10f, 20f), 1f); @@ -259,21 +267,21 @@ public void SeparateDragsOfTheSameSelectionUndoIndependentlyAfterAutosave() { GraphEditorModule module = Assert.IsType(m_sink.module); IEditorHistory history = m_runtime.interactions.history; - GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), new(), history); - GraphNodeId node = controller.AddNode("test.node", default); - controller.MoveNodes(new Dictionary { [node] = new(10, 20) }); + GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), new GraphDocument(), history); + GraphNodeID node = controller.AddNode("test.node", default); + controller.MoveNodes(new Dictionary { [node] = new(10, 20) }); controller.MarkSaved(); - controller.MoveNodes(new Dictionary { [node] = new(30, 40) }); + controller.MoveNodes(new Dictionary { [node] = new(30, 40) }); controller.MarkSaved(); Assert.True(history.Undo().succeeded); - Assert.Equal(new(10, 20), controller.document.FindNode(node)!.position); + Assert.Equal(new GraphPosition(10, 20), controller.document.FindNode(node)!.position); Assert.True(controller.isDirty); controller.MarkSaved(); Assert.True(history.Undo().succeeded); Assert.Equal(default, controller.document.FindNode(node)!.position); Assert.True(controller.isDirty); Assert.True(history.Redo().succeeded); - Assert.Equal(new(10, 20), controller.document.FindNode(node)!.position); + Assert.Equal(new GraphPosition(10, 20), controller.document.FindNode(node)!.position); } [Fact] @@ -281,16 +289,19 @@ public void PasteRemapRunsInsideTheSameAtomicHistoryOperation() { GraphEditorModule module = Assert.IsType(m_sink.module); IEditorHistory history = m_runtime.interactions.history; - GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), new(), history); - GraphNodeId owner = controller.AddNode("test.owner", default); - GraphNodeId child = controller.AddNode("test.child", default); + GraphDocumentController controller = module.OpenDocument(Guid.NewGuid(), new GraphDocument(), history); + GraphNodeID owner = controller.AddNode("test.owner", default); + GraphNodeID child = controller.AddNode("test.child", default); GraphClipboardData copy = controller.Copy([owner, child]); - IReadOnlyList created = controller.Paste(copy, new(10, 10), ( + IReadOnlyList created = controller.Paste(copy, new GraphPosition(10, 10), ( node, remap ) => - node.SetValue("owner", new(System.Text.Encoding.UTF8.GetBytes(remap[owner].value)))); - Assert.Equal(created[0].value, System.Text.Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span)); + node.SetValue("owner", new GraphSerializedValue(Encoding.UTF8.GetBytes(remap[owner].value)))); + Assert.Equal( + created[0].value, + Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span) + ); Assert.True(history.Undo().succeeded); Assert.Equal(2, controller.document.nodes.Count); byte[] before = GraphDocumentCodec.Encode(controller.document, m_serialization); @@ -301,6 +312,26 @@ public void PasteRemapRunsInsideTheSameAtomicHistoryOperation() Assert.Equal(before, GraphDocumentCodec.Encode(controller.document, m_serialization)); } + private sealed class RejectionParticipant(bool reject) : IEditorReloadParticipant, IGenerationChange + { + public IGenerationChange Capture(AssemblyReloadContext context) => this; + + public void RefreshDiagnostics() {} + + public void PrepareForActivation() {} + + public void Apply() + { + if (reject) throw new InvalidOperationException("Later recovery participant rejected the candidate."); + } + + public void Complete() {} + + public void RollbackStructure() {} + + public void RestorePreviousState() {} + } + private sealed class RecordingHistory : IEditorHistory { public List changes { get; } = []; @@ -314,11 +345,14 @@ private sealed class RecordingHistory : IEditorHistory public string? faultReason => null; public long residentBytes => 0; public long diskBytes => 0; + public EditorHistoryTransaction BeginTransaction(string name) => throw new NotSupportedException(); + public EditorHistoryResult Execute( string name, EditorHistoryChange change ) => throw new NotSupportedException(); + public void RecordApplied( string name, EditorHistoryChange change @@ -326,8 +360,11 @@ EditorHistoryChange change _ = name; changes.Add(change); } + public EditorHistoryResult Undo() => throw new NotSupportedException(); + public EditorHistoryResult Redo() => throw new NotSupportedException(); + public void DisposeChanges() { foreach (EditorHistoryChange change in changes) diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs index 29592c88e..5ee5fb142 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs @@ -6,7 +6,12 @@ using Inno.Adapter; using Inno.Adapter.Authoring.Default; using Inno.Adapter.Default; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation; +using Inno.Adapter.Presentation.ImGui; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; @@ -17,6 +22,8 @@ using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.Hosting; +using Inno.Integration.WindowsX64.Bgfx.Runtime; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Shell; namespace Inno.Editor.Hosting.Tests; @@ -35,7 +42,7 @@ public async Task CancellationBeforeStartupDoesNotCreateProjectOrAcquireProductR } [Fact] - public async Task MissingBackendSelectionFailsBeforeProjectIoOrNativeInitialization() + public async Task MissingBackendSelectionFailsBeforeProjectIOOrNativeInitialization() { EditorLaunchOptions options = CreateOptions(selection: new AdapterSelection()); @@ -46,7 +53,7 @@ public async Task MissingBackendSelectionFailsBeforeProjectIoOrNativeInitializat [Fact] public async Task UnregisteredDefaultTargetIsRejectedBeforeProductOwnershipBegins() { - EditorLaunchOptions options = CreateOptions(target: new BuildTargetId("fixture-unregistered")); + EditorLaunchOptions options = CreateOptions(target: new BuildTargetID("fixture-unregistered")); await Assert.ThrowsAsync(() => EditorApplication.RunAsync(options)); Assert.False(Directory.Exists(options.projectDirectory)); @@ -74,7 +81,7 @@ public async Task MissingKeyboardPolicyCannotSilentlyUseTheExecutingOperatingSys private static EditorLaunchOptions CreateOptions( AdapterSelection? selection = null, - BuildTargetId? target = null, + BuildTargetID? target = null, int? frameLimit = null, bool keyboard = true ) { @@ -83,25 +90,33 @@ private static EditorLaunchOptions CreateOptions( "dotnet", AppContext.BaseDirectory, new BuildHostDescriptor("Windows", "x64"), - new BuildTargetId("windows-x64")); + new BuildTargetID("windows-x64") + ); StandardBuildDistribution standard = StandardBuildDistribution.Create(build); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new Inno.Adapter.Platform.PlatformBackendCatalog([new Inno.Adapter.Platform.Sdl3.Sdl3PlatformBackendProvider(new Inno.Integration.WindowsX64.Sdl3.WindowsX64Sdl3HostIntegration())]), - rendering = new Inno.Adapter.Rendering.RenderingBackendCatalog([new Inno.Adapter.Rendering.Bgfx.BgfxRenderingBackendProvider(new Inno.Integration.WindowsX64.Bgfx.Runtime.WindowsX64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(Path.Combine(project, "Data"))]) - }, [new BgfxAuthoringProvider(standard.ResolveShaderTarget(new BuildTargetId("windows-x64")))], - [new Inno.Adapter.Presentation.ImGui.ImGuiPresentationProvider(new Inno.Adapter.Presentation.ImGui.ImGuiInteractionOptions(false, 1))]); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new PlatformBackendCatalog( + [new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())] + ), + rendering = new RenderingBackendCatalog( + [new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())] + ), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(Path.Combine(project, "Data"))]) + }, + [new BgfxAuthoringProvider(standard.ResolveShaderTarget(new BuildTargetID("windows-x64")))], + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(false, 1))] + ); return new EditorLaunchOptions { projectDirectory = project, keyboard = keyboard ? new EditorKeyboardPolicy(KeyModifier.Control, "Super") : null!, adapterCatalog = adapters, - shell = new ShellOptions { adapters = selection ?? StandardAdapterSelection.Create(StorageBackendId.fileSystem) }, - presentation = PresentationBackendId.imGui, + shell = new ShellOptions { adapters = selection ?? StandardAdapterSelection.Create(StorageBackendID.fileSystem) }, + presentation = PresentationBackendID.imGui, frameDriver = new PollingShellFrameDriver(), distribution = standard.build, - defaultBuildTarget = target ?? new BuildTargetId("windows-x64"), + defaultBuildTarget = target ?? new BuildTargetID("windows-x64"), buildContext = build, supportPackRoot = Path.Combine(project, "SupportPacks"), createEngineHost = () => throw new InvalidOperationException("Preflight must not acquire an engine."), diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs index 00f17913f..caa1fb9fa 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using Inno.Editor.Hosting; using Xunit; +using Inno.Editor.Hosting; namespace Inno.Editor.Hosting.Tests; @@ -14,8 +14,10 @@ public void DependencySelectionRemainsExplicitAndCannotFallBackToSourcePreparati Assert.Equal(selection, EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection]).nativeDependencies); Assert.Null(EditorCommandLineOptions.Parse(["project"]).nativeDependencies); Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", "relative.json"])); - Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", ""])); - Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection, "--native-dependencies", selection])); + Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", string.Empty])); + Assert.Throws( + () => EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection, "--native-dependencies", selection]) + ); } [Fact] @@ -35,5 +37,7 @@ public void InvalidVisibilityIsRejectedBeforeComposition(string value) [Fact] public void RepeatedVisibilityIsRejectedBeforeComposition() - => Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--window-visible", "false", "--window-visible", "true"])); + => Assert.Throws( + () => EditorCommandLineOptions.Parse(["project", "--window-visible", "false", "--window-visible", "true"]) + ); } diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs index 35c415d5d..c316ef91e 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs @@ -3,6 +3,4 @@ namespace Inno.Editor.Hosting.Tests; [CollectionDefinition("Editor script projection", DisableParallelization = true)] -public sealed class EditorScriptProjectionCollection -{ -} +public sealed class EditorScriptProjectionCollection; diff --git a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs index 38e3da9dd..b438fe70e 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs @@ -2,22 +2,25 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.Cli; using Inno.Build.Toolchains; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Settings; using Inno.Editor.Hosting; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Editor.Hosting.Tests; @@ -32,8 +35,11 @@ public void CliLogicalRuntimeReferencesIncludeAnimation() try { GenerateReferences(project, typeof(BuildApplication).Assembly); - string assembly = Directory.EnumerateFiles(Path.Combine(project, "Library", "ScriptApi"), - "Inno.ScriptApi.Runtime.dll", SearchOption.AllDirectories).Single(); + string assembly = Directory.EnumerateFiles( + Path.Combine(project, "Library", "ScriptApi"), + "Inno.ScriptApi.Runtime.dll", + SearchOption.AllDirectories + ).Single(); using FileStream stream = File.OpenRead(assembly); using var image = new PEReader(stream); MetadataReader metadata = image.GetMetadataReader(); @@ -44,8 +50,8 @@ public void CliLogicalRuntimeReferencesIncludeAnimation() }).ToArray(); Assert.Contains("InnoEngine.Animation.Animation", types); Assert.Contains("InnoEngine.Animation.AnimationClipAsset", types); - Assert.Contains("InnoEngine.UI.UiVertex", types); - Assert.Contains("InnoEngine.Rendering.RenderPersistentResourceId", types); + Assert.Contains("InnoEngine.UI.UIVertex", types); + Assert.Contains("InnoEngine.Rendering.RenderPersistentResourceID", types); } finally { @@ -60,10 +66,17 @@ public void LogicalEditorReferencesIncludeTheSharedProductFeatures() Directory.CreateDirectory(project); try { - GenerateReferences(project, typeof(RepositoryWikiTests).Assembly, - typeof(EditorApplication).Assembly, typeof(BuildApplication).Assembly); - string assembly = Directory.EnumerateFiles(Path.Combine(project, "Library", "ScriptApi"), - "Inno.ScriptApi.Editor.dll", SearchOption.AllDirectories).Single(); + GenerateReferences( + project, + typeof(RepositoryWikiTests).Assembly, + typeof(EditorApplication).Assembly, + typeof(BuildApplication).Assembly + ); + string assembly = Directory.EnumerateFiles( + Path.Combine(project, "Library", "ScriptApi"), + "Inno.ScriptApi.Editor.dll", + SearchOption.AllDirectories + ).Single(); using FileStream stream = File.OpenRead(assembly); using var image = new PEReader(stream); MetadataReader metadata = image.GetMetadataReader(); @@ -85,7 +98,7 @@ public void LogicalEditorReferencesIncludeTheSharedProductFeatures() private static void GenerateReferences( string project, - params System.Reflection.Assembly[] roots + params Assembly[] roots ) { string assetsRoot = Path.Combine(project, "Assets"); string pluginsRoot = Path.Combine(project, "Plugins"); @@ -97,29 +110,51 @@ params System.Reflection.Assembly[] roots using IDisposable identityScope = identities.EnterScope(); using EngineHost host = new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(roots), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); using IDisposable diagnostics = host.diagnostics.EnterScope(); var sources = new PluginSourceService(host.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); - using var assets = new AssetPipeline(host.modules, host.types, host.serialization, identities, - host.diagnostics, host.logs, AssetPipelineOptions.Create(assetsRoot, libraryRoot) - with { enableFileSystemWatcher = false }); + using var assets = new AssetPipeline( + host.modules, + host.types, + host.serialization, + identities, + host.diagnostics, + host.logs, + AssetPipelineOptions.Create(assetsRoot, libraryRoot) + with { enableFileSystemWatcher = false } + ); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.Combine(project, "Settings.Project.inno")), - host.types, host.serialization, new ProjectId("wiki.contract.validation"), - AssetSerializationContext.Create(assets)); - using var plugins = new PluginEnvironment(assets, settings, host.serialization, pluginsRoot, - libraryRoot, scan, host.modules.generations); + host.types, + host.serialization, + new ProjectID("wiki.contract.validation"), + AssetSerializationContext.Create(assets) + ); + using var plugins = new PluginEnvironment( + assets, + settings, + host.serialization, + pluginsRoot, + libraryRoot, + scan, + host.modules.generations + ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = project, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, project) - }, assets, plugins); + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, project) + }, + assets, + plugins + ); compiler.GenerateProjectFiles(); } - } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs new file mode 100644 index 000000000..a14d85f5a --- /dev/null +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs @@ -0,0 +1,34 @@ +using System.Numerics; +using Inno.Editor.ImGui.ImGuiWidget; + +namespace Inno.Editor.ImGui.Tests; + +public sealed class DynamicModalState +{ + public string message = "Short"; + public float zoom = 1f; + public bool showAction = true; + public bool showProgress = true; + public bool indeterminate; + public string? details; + public Vector2 initialSize; + public bool resizable; + public bool visible = true; + public bool rejectPreparation; + public bool rejectDraw; + public bool canceled; + public int actions; + public bool popupOpen; + public Vector2 actionMin; + public float scrollMaxX; + public float wrapWidth; + public float bodyHeight; + public float bodyContentHeight; + public int preparations; + public int draws; + public DialogPresentation content; + public DialogLayout layout; + public Vector2 windowSize; + public Vector2 windowMax; + public Vector2 actionMax; +} diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs index 5cdff697f..28277d249 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs @@ -1,26 +1,32 @@ using System; using System.IO; using System.Numerics; +using System.Text.Json; using System.Threading; +using Xunit; +using Xunit.Abstractions; using Inno.Adapter.Modules.DotNet; using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; -using Xunit; -using Xunit.Abstractions; -using System.Text.Json; + using NativeGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.Tests; public sealed unsafe class DynamicModalTests { private readonly ITestOutputHelper m_output; - public DynamicModalTests(ITestOutputHelper output) => m_output = output; + + public DynamicModalTests(ITestOutputHelper output) + { + m_output = output; + } + [Fact] [Trait("Acceptance", "Visual")] public void ChangedContentFitsOnTheTransitionFrameThroughTheActualRenderer() @@ -49,6 +55,7 @@ public void ScaleMatrixBoundsCurrentTextAndActions( int height ) { foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) + { foreach (float dpi in new[] { 1f, 1.25f, 1.5f, 2f }) { using var host = new ModalHost(width, height); @@ -56,30 +63,51 @@ int height NativeGui.Raw.GetStyle()->FontScaleDpi = dpi; host.Frame(); host.Frame(); - string[] messages = ["Short", "First\nSecond", new string('W', 600), "中文状态 / café / Ελληνικά\n" + new string('x', 4000), "", "Short"]; + string[] messages = + [ + "Short", + "First\nSecond", + new string('W', 600), + "中文状态 / café / Ελληνικά\n" + new string('x', 4000), + string.Empty, + "Short" + ]; foreach (string text in messages) { host.state.message = text; host.Frame(); - m_output.WriteLine(JsonSerializer.Serialize(new - { - width, height, zoom, dpi, messageLength = text.Length, - wrapWidth = host.state.wrapWidth, bodyHeight = host.state.bodyHeight, - bodyContentHeight = host.state.bodyContentHeight, - windowWidth = host.state.windowSize.X, windowHeight = host.state.windowSize.Y, - actionMinimumX = host.state.actionMin.X, actionMinimumY = host.state.actionMin.Y, - actionMaximumX = host.state.actionMax.X, actionMaximumY = host.state.actionMax.Y, - scrollMaxX = host.state.scrollMaxX - })); + m_output.WriteLine( + JsonSerializer.Serialize(new + { + width, + height, + zoom, + dpi, + messageLength = text.Length, + wrapWidth = host.state.wrapWidth, + bodyHeight = host.state.bodyHeight, + bodyContentHeight = host.state.bodyContentHeight, + windowWidth = host.state.windowSize.X, + windowHeight = host.state.windowSize.Y, + actionMinimumX = host.state.actionMin.X, + actionMinimumY = host.state.actionMin.Y, + actionMaximumX = host.state.actionMax.X, + actionMaximumY = host.state.actionMax.Y, + scrollMaxX = host.state.scrollMaxX + }) + ); Assert.True(host.state.windowSize.X <= width && host.state.windowSize.Y <= height); - Assert.True(host.state.actionMax.Y <= host.state.windowMax.Y + 1f, - $"Action exceeded the window: zoom={zoom}, dpi={dpi}, message length={text.Length}."); + Assert.True( + host.state.actionMax.Y <= host.state.windowMax.Y + 1f, + $"Action exceeded the window: zoom={zoom}, dpi={dpi}, message length={text.Length}." + ); Assert.InRange(host.state.scrollMaxX, 0f, 0.01f); Vector2 first = host.state.windowSize; host.Frame(); Assert.Equal(first, host.state.windowSize); } } + } } [Fact] @@ -123,7 +151,7 @@ public void CurrentActionRectangleCancelsOnceAndBecomesDisabled() host.state.message = "Line one\nLine two\nLine three"; host.Frame(); Vector2 hit = (host.state.actionMin + host.state.actionMax) * 0.5f; - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); NativeGui.Raw.AddMousePosEvent(io, hit.X, hit.Y); NativeGui.Raw.AddMouseButtonEvent(io, 0, 1); host.Frame(); @@ -159,10 +187,10 @@ public void DetailsActivityAndActionChangesUseTheCurrentFrameLayout() host.state.showAction = true; host.state.message = "Cancel using the keyboard"; host.Frame(); - var io = NativeGui.Raw.GetIO(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Escape, 1); + ImGuiIO* io = NativeGui.Raw.GetIO(); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Escape, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Escape, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Escape, 0); host.Frame(); Assert.Equal(1, host.state.actions); } @@ -172,17 +200,17 @@ public void DetailsActivityAndActionChangesUseTheCurrentFrameLayout() public void TabAndEnterActivateTheCurrentEnabledAction() { using var host = new ModalHost(); - var io = NativeGui.Raw.GetIO(); - io->ConfigFlags |= (int)Inno.Native.ImGui.ImGuiConfigFlags.NavEnableKeyboard; + ImGuiIO* io = NativeGui.Raw.GetIO(); + io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; host.Frame(); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Tab, 1); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Tab, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Tab, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Tab, 0); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Enter, 1); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Enter, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Enter, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Enter, 0); host.Frame(); Assert.Equal(1, host.state.actions); } @@ -221,14 +249,14 @@ public void FontAndZoomChangesInvalidatePreparedMeasurementsInTheSameSession() host.Frame(); float originalActionWidth = host.state.actionMax.X - host.state.actionMin.X; float originalHeight = host.state.layout.size.Y; - var io = NativeGui.Raw.GetIO(); - var configuration = NativeGui.Raw.ImFontConfig(); + ImGuiIO* io = NativeGui.Raw.GetIO(); + ImFontConfig* configuration = NativeGui.Raw.ImFontConfig(); try { configuration->SizePixels = 16f; configuration->GlyphExtraAdvanceX = 8f; io->FontDefault = NativeGui.Raw.AddFontDefault(io->Fonts, configuration); - Assert.True(io->FontDefault != null); + Assert.True(io->FontDefault is not null); } finally { @@ -309,31 +337,25 @@ internal ModalHost( Directory.CreateDirectory(m_root); m_native = NativeGui.Raw.CreateContext(null); NativeGui.Raw.SetCurrentContext(m_native); - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = width, Y = height }; io->DeltaTime = 0.2f; io->IniFilename = null; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(DynamicModalTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(DynamicModalTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - m_runtime = new ImGuiEditorRuntime(new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), - m_types, m_logs, [state]); + m_runtime = new ImGuiEditorRuntime( + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), + m_types, + m_logs, + [state] + ); m_runtime.Start(); } - internal void Refresh() => m_types.Rebuild(); - - internal void Frame() - { - NativeGui.Raw.SetCurrentContext(m_native); - m_runtime.PrepareFrame(); - NativeGui.NewFrame(); - m_runtime.Draw(); - state.popupOpen = NativeGui.IsPopupOpen("Dynamic Modal##tests.dynamic-modal"); - NativeGui.Render(); - } - public void Dispose() { NativeGui.Raw.SetCurrentContext(m_native); @@ -344,83 +366,17 @@ public void Dispose() NativeGui.Raw.DestroyContext(m_native); Directory.Delete(m_root, true); } - } -} -public sealed class DynamicModalState -{ - public string message = "Short"; - public float zoom = 1f; - public bool showAction = true; - public bool showProgress = true; - public bool indeterminate; - public string? details; - public Vector2 initialSize; - public bool resizable; - public bool visible = true; - public bool rejectPreparation; - public bool rejectDraw; - public bool canceled; - public int actions; - public bool popupOpen; - public Vector2 actionMin; - public float scrollMaxX; - public float wrapWidth; - public float bodyHeight; - public float bodyContentHeight; - public int preparations; - public int draws; - public DialogPresentation content; - public DialogLayout layout; - public Vector2 windowSize; - public Vector2 windowMax; - public Vector2 actionMax; -} - -[EditorModal("tests.dynamic-modal", "Dynamic Modal")] -public sealed unsafe class DynamicTestModal(DynamicModalState state) : EditorModal -{ - public override bool isVisible => state.visible; - public override bool allowScrolling => false; - public override Vector2 initialSize => state.initialSize; - public override bool canResize => state.resizable; - protected override Vector2? OnPrepare( - EditorContext context, - Vector2 availableContentSize - ) { - state.preparations++; - if (state.rejectPreparation) throw new InvalidOperationException("Rejected modal measurement."); - EditorUiSession.current.widgets.style.SetZoom(state.zoom); - state.content = new(state.message, state.showProgress ? 0.5f : null, state.indeterminate, - actionLabel: state.showAction ? "Cancel" : null, actionEnabled: !state.canceled, details: state.details, cancelOnEscape: true); - state.layout = EditorUiSession.current.widgets.MeasureDialog(state.content, availableContentSize); - return state.layout.size; - } + internal void Refresh() => m_types.Rebuild(); - protected override void OnDraw(EditorContext context) - { - state.draws++; - state.windowSize = NativeGui.GetWindowSize(); - state.windowMax = NativeGui.GetWindowPos() + state.windowSize; - if (EditorUiSession.current.widgets.DrawDialog(state.content, state.layout)) - { - state.actions++; - state.canceled = true; - } - state.actionMin = NativeGui.GetItemRectMin(); - state.scrollMaxX = NativeGui.GetScrollMaxX(); - var window = NativeGui.Raw.GetCurrentWindow(); - state.wrapWidth = NativeGui.GetContentRegionAvail().X; - state.bodyHeight = state.message.Length == 0 ? 0f : NativeGui.CalcTextSize(state.message, false, state.wrapWidth).Y; - state.bodyContentHeight = state.bodyHeight; - if (window->DC.ChildWindows.Size > 0) + internal void Frame() { - var child = window->DC.ChildWindows.Data[0]; - state.wrapWidth = child->WorkRect.Max.X - child->WorkRect.Min.X; - state.bodyHeight = child->Size.Y; - state.bodyContentHeight = child->ContentSize.Y; + NativeGui.Raw.SetCurrentContext(m_native); + m_runtime.PrepareFrame(); + NativeGui.NewFrame(); + m_runtime.Draw(); + state.popupOpen = NativeGui.IsPopupOpen("Dynamic Modal##tests.dynamic-modal"); + NativeGui.Render(); } - if (state.rejectDraw) throw new InvalidOperationException("Rejected modal drawing."); - state.actionMax = NativeGui.GetItemRectMax(); } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs new file mode 100644 index 000000000..69d6bfa93 --- /dev/null +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs @@ -0,0 +1,64 @@ +using System; +using System.Numerics; +using Inno.Editor.Core; +using Inno.Native.ImGui; + +using NativeGui = Inno.Native.ImGui.ImGui; + +namespace Inno.Editor.ImGui.Tests; + +[EditorModal("tests.dynamic-modal", "Dynamic Modal")] +public sealed unsafe class DynamicTestModal(DynamicModalState state) : EditorModal +{ + public override bool isVisible => state.visible; + public override bool allowScrolling => false; + public override Vector2 initialSize => state.initialSize; + public override bool canResize => state.resizable; + + protected override Vector2? OnPrepare( + EditorContext context, + Vector2 availableContentSize + ) { + state.preparations++; + if (state.rejectPreparation) throw new InvalidOperationException("Rejected modal measurement."); + EditorUISession.current.widgets.style.SetZoom(state.zoom); + state.content = new( + state.message, + state.showProgress ? 0.5f : null, + state.indeterminate, + actionLabel: state.showAction ? "Cancel" : null, + actionEnabled: !state.canceled, + details: state.details, + cancelOnEscape: true + ); + state.layout = EditorUISession.current.widgets.MeasureDialog(state.content, availableContentSize); + return state.layout.size; + } + + protected override void OnDraw(EditorContext context) + { + state.draws++; + state.windowSize = NativeGui.GetWindowSize(); + state.windowMax = NativeGui.GetWindowPos() + state.windowSize; + if (EditorUISession.current.widgets.DrawDialog(state.content, state.layout)) + { + state.actions++; + state.canceled = true; + } + state.actionMin = NativeGui.GetItemRectMin(); + state.scrollMaxX = NativeGui.GetScrollMaxX(); + ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); + state.wrapWidth = NativeGui.GetContentRegionAvail().X; + state.bodyHeight = state.message.Length == 0 ? 0f : NativeGui.CalcTextSize(state.message, false, state.wrapWidth).Y; + state.bodyContentHeight = state.bodyHeight; + if (window->DC.ChildWindows.Size > 0) + { + ImGuiWindow* child = window->DC.ChildWindows.Data[0]; + state.wrapWidth = child->WorkRect.Max.X - child->WorkRect.Min.X; + state.bodyHeight = child->Size.Y; + state.bodyContentHeight = child->ContentSize.Y; + } + if (state.rejectDraw) throw new InvalidOperationException("Rejected modal drawing."); + state.actionMax = NativeGui.GetItemRectMax(); + } +} diff --git a/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/EditorUISessionTests.cs similarity index 75% rename from tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs rename to tests/editor/Inno.Editor.ImGui.Tests/EditorUISessionTests.cs index 1e30dca5e..222bdfaac 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/EditorUISessionTests.cs @@ -1,16 +1,17 @@ using System; using System.Threading; -using Inno.Editor.ImGui; using Xunit; +using Inno.Editor.ImGui; namespace Inno.Editor.ImGui.Tests; -public sealed class EditorUiSessionTests + +public sealed class EditorUISessionTests { [Fact] public void StyleAndControlsBelongToOneSession() { - using var first = new EditorUiSession(); - using var second = new EditorUiSession(); + using var first = new EditorUISession(); + using var second = new EditorUISession(); first.widgets.style.SetZoom(1.5f); second.widgets.style.SetCompactMode(true); Assert.NotSame(first.widgets, second.widgets); @@ -23,23 +24,23 @@ public void StyleAndControlsBelongToOneSession() [Fact] public void RejectedScopeRetirementPreservesTheActiveSession() { - using var first = new EditorUiSession(); - using var second = new EditorUiSession(); + using var first = new EditorUISession(); + using var second = new EditorUISession(); IDisposable outer = first.Enter(); IDisposable inner = second.Enter(); Assert.Throws(outer.Dispose); - Assert.Same(second, EditorUiSession.current); + Assert.Same(second, EditorUISession.current); Assert.Throws(first.Dispose); inner.Dispose(); - Assert.Same(first, EditorUiSession.current); + Assert.Same(first, EditorUISession.current); outer.Dispose(); - Assert.Throws(() => EditorUiSession.current); + Assert.Throws(() => EditorUISession.current); } [Fact] public void RetiredSessionsRejectActivationAndControlUse() { - var session = new EditorUiSession(); + var session = new EditorUISession(); session.Dispose(); Assert.True(session.isDisposed); Assert.Throws(() => session.Enter()); @@ -49,7 +50,7 @@ public void RetiredSessionsRejectActivationAndControlUse() [Fact] public void ASessionCannotBeActivatedFromAnotherThread() { - using var session = new EditorUiSession(); + using var session = new EditorUISession(); Exception? failure = null; var thread = new Thread(() => failure = Record.Exception(() => session.Enter())); thread.Start(); diff --git a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs index 3e9a56636..476c7c09c 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs @@ -1,18 +1,19 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; using Inno.Native.ImGui; using Inno.Platform; -using Xunit; -using NativeImGui = Inno.Native.ImGui.ImGui; + using BackendFont = Inno.Adapter.Presentation.ImGui.ImGuiFont; using BackendFontScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; using BackendFontStyle = Inno.Adapter.Presentation.ImGui.ImGuiFontStyle; +using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.Tests; @@ -26,12 +27,25 @@ public sealed unsafe class FontCoverageTests [Trait("Acceptance", "Visual")] public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float zoom) { - string contract = nameof(FontCoverageTests) + "." + nameof(EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback) + "." + zoom.ToString(CultureInfo.InvariantCulture); + string contract = nameof(FontCoverageTests) + + "." + + nameof(EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback) + + "." + + zoom.ToString(CultureInfo.InvariantCulture); if (NativeWindowTestHost.RunIfRequired(contract)) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Glyph coverage", width = 640, height = 480, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Glyph coverage", width = 640, height = 480, visible = false } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); context.RenderFrame(() => { @@ -40,8 +54,13 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float _ = NativeImGui.Begin("Glyph coverage", ref open, 0); try { - foreach (BackendFontStyle style in new[] { BackendFontStyle.Regular, BackendFontStyle.Bold, BackendFontStyle.Italic, BackendFontStyle.Bold | BackendFontStyle.Italic }) + foreach (BackendFontStyle style in new[] { + BackendFontStyle.Regular, + BackendFontStyle.Bold, + BackendFontStyle.Italic, + BackendFontStyle.Bold | BackendFontStyle.Italic + }) { Assert.True(BackendFont.IsAvailable(style)); using BackendFontScope scope = BackendFont.PushStyle(style); ImFont* font = NativeImGui.Raw.GetFont(); @@ -53,17 +72,17 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float Assert.Equal((uint)value, glyph->Codepoint); Assert.Equal(0u, glyph->SourceIdx); } - ImFontGlyph* icon = NativeImGui.Raw.FindGlyphNoFallback(baked, 0xf0e2); + ImFontGlyph* icon = NativeImGui.Raw.FindGlyphNoFallback(baked, 0xF0E2); Assert.True(icon is not null); Assert.InRange(icon->SourceIdx, 1u, 2u); - ImFontGlyph* logo = NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.Inno[0]); + ImFontGlyph* logo = NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.C_INNO[0]); Assert.True(logo is not null); - Assert.Equal((uint)ImGuiIcon.Inno[0], logo->Codepoint); + Assert.Equal((uint)ImGuiIcon.C_INNO[0], logo->Codepoint); Assert.Equal(3u, logo->SourceIdx); Assert.True(logo->AdvanceX > 0 && logo->X1 > logo->X0 && logo->Y1 > logo->Y0); Assert.Equal(4, font->Sources.Size); - Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6f22) is null); - NativeImGui.TextUnformatted(ImGuiIcon.Inno + " English / undo"); + Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6F22) is null); + NativeImGui.TextUnformatted(ImGuiIcon.C_INNO + " English / undo"); } } finally @@ -77,18 +96,33 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float [Trait("Acceptance", "Lifecycle")] public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() { - if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow))) + if (NativeWindowTestHost.RunIfRequired( + nameof(FontCoverageTests) + "." + nameof(SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Replacement context", width = 320, height = 240, visible = false }); - var original = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Replacement context", width = 320, height = 240, visible = false } + ); + PlatformImGuiContext original = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); original.SetIniFile(null); _ = CaptureSource(original); original.Dispose(); - using var replacement = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using PlatformImGuiContext replacement = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); replacement.SetIniFile(null); _ = CaptureSource(replacement); - Assert.Throws(() => original.RenderFrame(static () => { })); + Assert.Throws(() => original.RenderFrame(static () => {})); } [Fact] @@ -96,34 +130,60 @@ public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() public void ApplicationShutdownRetiresBothRegisteredContexts() { if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(ApplicationShutdownRetiresBothRegisteredContexts))) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var firstWindow = application.CreateWindow(new PlatformWindowOptions { title = "First context", width = 320, height = 240, visible = false }); - using var secondWindow = application.CreateWindow(new PlatformWindowOptions { title = "Second context", width = 320, height = 240, visible = false }); - var first = application.CreateImGuiContext(firstWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow firstWindow = application.CreateWindow( + new PlatformWindowOptions { title = "First context", width = 320, height = 240, visible = false } + ); + using Sdl3PlatformWindow secondWindow = application.CreateWindow( + new PlatformWindowOptions { title = "Second context", width = 320, height = 240, visible = false } + ); + PlatformImGuiContext first = application.CreateImGuiContext( + firstWindow, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); first.SetIniFile(null); - var second = application.CreateImGuiContext(secondWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + PlatformImGuiContext second = application.CreateImGuiContext( + secondWindow, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); second.SetIniFile(null); _ = CaptureSource(first); _ = CaptureSource(second); application.Dispose(); - Assert.Throws(() => first.RenderFrame(static () => { })); - Assert.Throws(() => second.RenderFrame(static () => { })); + Assert.Throws(() => first.RenderFrame(static () => {})); + Assert.Throws(() => second.RenderFrame(static () => {})); } [Fact] [Trait("Acceptance", "Lifecycle")] public void RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext() { - if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext))) + if (NativeWindowTestHost.RunIfRequired( + nameof(FontCoverageTests) + "." + nameof(RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Retained font context", width = 320, height = 240, visible = false }); - using var retained = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Retained font context", width = 320, height = 240, visible = false } + ); + using PlatformImGuiContext retained = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); retained.SetIniFile(null); nint source = CaptureSource(retained); long baseline = CollectLiveManagedBytes(); - var retired = new List>(); + List> retired = []; for (int cycle = 0; cycle < 10; cycle++) { retired.Add(CreateAndRetire(application, source)); @@ -139,10 +199,19 @@ public void RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext() public void CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons() { if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons))) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Custom font", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Custom font", width = 320, height = 240, visible = false } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); string fontPath = Path.Combine(AppContext.BaseDirectory, "BuiltIn", "Fonts", "JetBrainsMono-Bold.ttf"); Assert.Throws(() => context.RegisterFontStyle(BackendFontStyle.Regular, fontPath + ".missing")); @@ -156,8 +225,8 @@ public void CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons() Assert.Equal(new FileInfo(fontPath).Length, font->Sources.Data[0]->FontDataSize); Assert.Equal(24f, font->Sources.Data[0]->SizePixels); Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 'A') is not null); - Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.Inno[0]) is not null); - Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6f22) is null); + Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.C_INNO[0]) is not null); + Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6F22) is null); }); Assert.Throws(() => context.RegisterFontStyle(BackendFontStyle.Regular, fontPath)); } @@ -183,8 +252,15 @@ private static WeakReference CreateAndRetire( Sdl3PlatformApplication application, nint retainedSource ) { - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Retired font context", width = 320, height = 240, visible = false }); - var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Retired font context", width = 320, height = 240, visible = false } + ); + PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); Assert.NotEqual(retainedSource, CaptureSource(context)); context.Dispose(); @@ -208,20 +284,29 @@ private sealed class NoOutputRenderer : IPlatformImGuiRenderer { public bool supportsViewports => false; public bool supportsVertexOffsets => false; - public void RenderMain(IntPtr drawData) { } + + public void RenderMain(nint drawData) {} + public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { } + ) {} + public void CreateViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); + public void ResizeViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); + public void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData + nint drawData ) => throw new NotSupportedException(); + public void PresentViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); - public Task RetireViewport(PlatformImGuiViewportTarget target) => Task.CompletedTask; - public void DrainViewportRetirements() { } - public void Dispose() { } + + public Task RetireViewportAsync(PlatformImGuiViewportTarget target) => Task.CompletedTask; + + public void DrainViewportRetirements() {} + + public void Dispose() {} } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs index 5d99b3183..a60532a0f 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Adapter.Presentation.ImGui; using Xunit; +using Inno.Adapter.Presentation.ImGui; namespace Inno.Editor.ImGui.Tests; @@ -22,8 +22,7 @@ int wheelDirection [InlineData(0)] [InlineData(2)] [InlineData(-2)] - public void WheelDirectionCannotSilentlyDisableOrAmplifyInput(int direction) - { - Assert.Throws(() => new ImGuiInteractionOptions(false, direction)); - } + public void WheelDirectionCannotSilentlyDisableOrAmplifyInput(int direction) => Assert.Throws( + () => new ImGuiInteractionOptions(false, direction) + ); } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs b/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs index 77f5f7122..b8c77c349 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Editor.ImGui.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs b/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs index 10a23aed0..261480334 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs @@ -6,39 +6,73 @@ namespace Inno.Editor.ImGui.Tests; internal static class NativeWindowTestHost { - private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary + private static readonly IReadOnlyDictionary CONTRACTS = new Dictionary { - ["ViewportMetricsTests.FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations"] = () => new ViewportMetricsTests().FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations(), - ["ViewportMetricsTests.FailedPreparationDoesNotBeginOrPublishANativeFrame"] = () => new ViewportMetricsTests().FailedPreparationDoesNotBeginOrPublishANativeFrame(), - ["ViewportMetricsTests.AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest"] = () => new ViewportMetricsTests().AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest(), - ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.False"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(false), - ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.True"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(true), - ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.False"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(false), - ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.True"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(true), - ["ViewportMetricsTests.MetricRefreshPreservesRequestedViewportGeometry"] = () => new ViewportMetricsTests().MetricRefreshPreservesRequestedViewportGeometry(), - ["ViewportMetricsTests.DetachedWindowAppliesRequestsAfterPlatformEventReconciliation"] = () => new ViewportMetricsTests().DetachedWindowAppliesRequestsAfterPlatformEventReconciliation(), - ["ViewportMetricsTests.LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame"] = () => new ViewportMetricsTests().LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame(), - ["ViewportMetricsTests.ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction"] = () => new ViewportMetricsTests().ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction(), - ["ViewportRetirementTests.FaultedRetirementRetainsWindowRendererAndApplicationOwners"] = () => new ViewportRetirementTests().FaultedRetirementRetainsWindowRendererAndApplicationOwners(), - ["ViewportRetirementTests.DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement"] = () => new ViewportRetirementTests().DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement(), - ["ViewportRetirementTests.IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint"] = () => new ViewportRetirementTests().IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint(), - ["ViewportRetirementTests.CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup"] = () => new ViewportRetirementTests().CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup(), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.0.75"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(0.75f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(1f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1.5"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(1.5f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.2"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(2f), - ["FontCoverageTests.CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons"] = () => new FontCoverageTests().CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons(), - ["FontCoverageTests.RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext"] = () => new FontCoverageTests().RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext(), - ["FontCoverageTests.SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow"] = () => new FontCoverageTests().SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow(), - ["FontCoverageTests.ApplicationShutdownRetiresBothRegisteredContexts"] = () => new FontCoverageTests().ApplicationShutdownRetiresBothRegisteredContexts(), + ["ViewportMetricsTests.FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations"] = () => new ViewportMetricsTests() + .FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations(), + ["ViewportMetricsTests.FailedPreparationDoesNotBeginOrPublishANativeFrame"] = () => new ViewportMetricsTests() + .FailedPreparationDoesNotBeginOrPublishANativeFrame(), + ["ViewportMetricsTests.AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest"] = () => new ViewportMetricsTests() + .AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest(), + ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.False"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability( + false + ), + ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.True"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability( + true + ), + ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.False"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback( + false + ), + ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.True"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback( + true + ), + ["ViewportMetricsTests.MetricRefreshPreservesRequestedViewportGeometry"] = () => new ViewportMetricsTests() + .MetricRefreshPreservesRequestedViewportGeometry(), + ["ViewportMetricsTests.DetachedWindowAppliesRequestsAfterPlatformEventReconciliation"] = () => new ViewportMetricsTests() + .DetachedWindowAppliesRequestsAfterPlatformEventReconciliation(), + ["ViewportMetricsTests.LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame"] = () => new ViewportMetricsTests() + .LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame(), + ["ViewportMetricsTests.ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction"] = () => new ViewportMetricsTests() + .ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction(), + ["ViewportRetirementTests.FaultedRetirementRetainsWindowRendererAndApplicationOwners"] = () => new ViewportRetirementTests() + .FaultedRetirementRetainsWindowRendererAndApplicationOwners(), + ["ViewportRetirementTests.DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement"] = () => new ViewportRetirementTests() + .DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement(), + ["ViewportRetirementTests.IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint"] = () => new ViewportRetirementTests() + .IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint(), + ["ViewportRetirementTests.CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup"] = () => new ViewportRetirementTests() + .CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup(), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.0.75"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 0.75f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 1f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1.5"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 1.5f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.2"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 2f + ), + ["FontCoverageTests.CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons"] = () => new FontCoverageTests() + .CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons(), + ["FontCoverageTests.RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext"] = () => new FontCoverageTests() + .RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext(), + ["FontCoverageTests.SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow"] = () => new FontCoverageTests() + .SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow(), + ["FontCoverageTests.ApplicationShutdownRetiresBothRegisteredContexts"] = () => new FontCoverageTests() + .ApplicationShutdownRetiresBothRegisteredContexts() }; - private static bool m_executingContract; + + private static bool s_executingContract; internal static bool RunIfRequired(string contract) { - if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + if (s_executingContract || !OperatingSystem.IsMacOS() + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -47,10 +81,12 @@ private static int Main(string[] arguments) { try { - if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + if (arguments.Length != 1 || !CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa requires the process main thread, rather than an xUnit worker or a new managed thread. - m_executingContract = true; + s_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); contract(); Console.Error.WriteLine($"Native contract completed: {arguments[0]}."); diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs index 9e4ca602d..9d9d21bd8 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs @@ -1,10 +1,9 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using System.Threading.Tasks; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using BGCS.Runtime; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; @@ -12,46 +11,63 @@ using Inno.Native.ImGui; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; + +using GuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; [assembly: CollectionBehavior(DisableTestParallelization = true)] + namespace Inno.Editor.ImGui.Tests; + public sealed unsafe class ViewportMetricsTests { [Fact] public void FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Prepared presentation frame", width = 320, height = 240, visible = false + title = "Prepared presentation frame", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); - using var ui = new EditorUiSession(); + using var ui = new EditorUISession(); context.SetIniFile(null); int phase = 0; - context.RenderFrame(() => - { - Assert.Equal(1, phase); - Assert.Equal(1, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - Assert.Equal(ui.widgets.style.fontScale, NativeImGui.Raw.GetStyle()->FontScaleMain); - phase = 2; - }, () => - { - using IDisposable scope = ui.Enter(); - Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - Assert.Equal(new Vector2(320f, 240f), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); - Assert.True(ui.widgets.style.SetZoom(1.25f)); - ui.widgets.SetupStyle(); - Assert.Throws(() => context.RenderFrame(static () => { })); - Assert.Throws(() => context.Dispose()); - phase = 1; - }); + context.RenderFrame( + () => + { + Assert.Equal(1, phase); + Assert.Equal(1, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); + Assert.Equal(ui.widgets.style.fontScale, NativeImGui.Raw.GetStyle()->FontScaleMain); + phase = 2; + }, + () => + { + using IDisposable scope = ui.Enter(); + Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); + Assert.Equal(new Vector2(320f, 240f), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); + Assert.True(ui.widgets.style.SetZoom(1.25f)); + ui.widgets.SetupStyle(); + Assert.Throws(() => context.RenderFrame(static () => {})); + Assert.Throws(() => context.Dispose()); + phase = 1; + } + ); Assert.Equal(2, phase); Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); } @@ -59,16 +75,26 @@ public void FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperation [Fact] public void FailedPreparationDoesNotBeginOrPublishANativeFrame() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FailedPreparationDoesNotBeginOrPublishANativeFrame))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FailedPreparationDoesNotBeginOrPublishANativeFrame) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed frame preparation", width = 320, height = 240, visible = false + title = "Failed frame preparation", + width = 320, + height = 240, + visible = false }); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), renderer); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); bool drawn = false; var failure = new InvalidOperationException("Frame preparation failed."); @@ -82,27 +108,39 @@ public void FailedPreparationDoesNotBeginOrPublishANativeFrame() [Fact] public void AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed presentation frame", width = 320, height = 240, visible = false + title = "Failed presentation frame", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); var failure = new InvalidOperationException("The frame extension failed."); try { Assert.Same(failure, Assert.Throws(() => context.RenderFrame(() => throw failure))); Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); } finally { if (NativeImGui.Raw.GetCurrentContext()->WithinFrameScope != 0) + { NativeImGui.Raw.EndFrame(); + } } } @@ -111,18 +149,30 @@ public void AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest() [InlineData(true)] public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool supported) { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability) + "." + supported)) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability) + "." + supported + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Renderer capability", width = 320, height = 240, visible = false + title = "Renderer capability", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer { supportsVertexOffsets = supported }); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer { supportsVertexOffsets = supported } + ); context.SetIniFile(null); - context.RenderFrame(() => Assert.Equal(supported, - (NativeImGui.Raw.GetIO()->BackendFlags & (int)Inno.Native.ImGui.ImGuiBackendFlags.RendererHasVtxOffset) != 0)); + context.RenderFrame(() => Assert.Equal( + supported, + (NativeImGui.Raw.GetIO()->BackendFlags & (int)ImGuiBackendFlags.RendererHasVtxOffset) != 0 + )); } [Theory] @@ -130,11 +180,21 @@ public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool [InlineData(true)] public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool commandKeys) { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback) + "." + commandKeys)) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback) + "." + commandKeys + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport metrics", width = 320, height = 240, visible = false, highPixelDensity = true }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(commandKeys, 1), new FixtureRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport metrics", width = 320, height = 240, visible = false, highPixelDensity = true } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(commandKeys, 1), + new FixtureRenderer() + ); context.SetIniFile(null); context.RenderFrame(() => { @@ -146,26 +206,42 @@ public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool comm int pixelHeight = 0; SDL.Raw.GetWindowSize((SDLWindow*)window.sdlWindowHandle, &logicalWidth, &logicalHeight); SDL.Raw.GetWindowSizeInPixels((SDLWindow*)window.sdlWindowHandle, &pixelWidth, &pixelHeight); - Vector2 expected = new(pixelWidth / (float)logicalWidth, pixelHeight / (float)logicalHeight); + var expected = new Vector2(pixelWidth / (float)logicalWidth, pixelHeight / (float)logicalHeight); Assert.Equal(expected, Unsafe.BitCast(NativeImGui.Raw.GetMainViewport()->FramebufferScale)); Assert.Equal( - SDL.Raw.GetWindowDisplayScale((SDLWindow*)window.sdlWindowHandle) / SDL.Raw.GetWindowPixelDensity((SDLWindow*)window.sdlWindowHandle), + SDL.Raw.GetWindowDisplayScale((SDLWindow*)window.sdlWindowHandle) + / SDL.Raw.GetWindowPixelDensity((SDLWindow*)window.sdlWindowHandle), NativeImGui.Raw.GetMainViewport()->DpiScale ); - Assert.Equal(new Vector2(logicalWidth, logicalHeight), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); + Assert.Equal( + new Vector2(logicalWidth, logicalHeight), + Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize) + ); }); SDL.Raw.SetWindowSize((SDLWindow*)window.sdlWindowHandle, 450, 300); - context.RenderFrame(() => Assert.Equal(new Vector2(450, 300), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize))); + context.RenderFrame( + () => Assert.Equal(new Vector2(450, 300), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)) + ); } [Fact] public void MetricRefreshPreservesRequestedViewportGeometry() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(MetricRefreshPreservesRequestedViewportGeometry))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(MetricRefreshPreservesRequestedViewportGeometry) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport geometry owner", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport geometry owner", width = 320, height = 240, visible = false } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); var viewport = new ImGuiViewport { @@ -173,18 +249,16 @@ public void MetricRefreshPreservesRequestedViewportGeometry() Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); try { // A drag owns a requested position before UpdatePlatformWindows applies it to SDL. - Vector2 requestedPosition = new(180, 140); - Vector2 requestedSize = new(140, 110); + var requestedPosition = new Vector2(180, 140); + var requestedSize = new Vector2(140, 110); viewport.Pos = viewport.WorkPos = Unsafe.BitCast(requestedPosition); viewport.Size = viewport.WorkSize = Unsafe.BitCast(requestedSize); - context.RenderFrame(() => - { - }); + context.RenderFrame(() => {}); Assert.Equal(requestedPosition, Unsafe.BitCast(viewport.Pos)); Assert.Equal(requestedPosition, Unsafe.BitCast(viewport.WorkPos)); Assert.Equal(requestedSize, Unsafe.BitCast(viewport.Size)); @@ -202,32 +276,42 @@ public void MetricRefreshPreservesRequestedViewportGeometry() [Fact] public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(DetachedWindowAppliesRequestsAfterPlatformEventReconciliation))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(DetachedWindowAppliesRequestsAfterPlatformEventReconciliation) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport movement", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport movement", width = 320, height = 240, visible = false } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); - var io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->ConfigViewportsNoAutoMerge = (true ? (byte)1 : (byte)0); for (int frame = 0; frame < 24; frame++) { - Vector2 requested = new(500 + frame * 7, 200 + frame * 3); - uint viewportId = 0; + var requested = new Vector2(500 + frame * 7, 200 + frame * 3); + uint viewportID = 0; context.RenderFrame(() => { NativeImGui.SetNextWindowPos(requested); NativeImGui.SetNextWindowSize(new Vector2(200, 120)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Detached movement", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, (int)(ImGuiWindowFlags.NoFocusOnAppearing)); - viewportId = NativeImGui.Raw.GetWindowViewport()->ID; + NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, (int)(GuiWindowFlags.NoFocusOnAppearing)); + viewportID = NativeImGui.Raw.GetWindowViewport()->ID; NativeImGui.TextUnformatted("Moving viewport"); NativeImGui.End(); }); - Assert.True(context.TryGetWindowId(viewportId, out uint windowId)); + Assert.True(context.TryGetWindowID(viewportID, out uint windowID)); int x = 0; int y = 0; - Assert.True(SDL.Raw.GetWindowPosition(SDL.Raw.GetWindowFromId(windowId), &x, &y) != 0); + Assert.True(SDL.Raw.GetWindowPosition(SDL.Raw.GetWindowFromId(windowID), &x, &y) != 0); Assert.Equal(requested, new Vector2(x, y)); // A real OS move acknowledgement owns reconciliation in the following frame. // Complete that frame before submitting the next application position request. @@ -238,7 +322,7 @@ public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() context.RenderFrame(() => { using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Detached movement", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(ImGuiWindowFlags.NoFocusOnAppearing)); + NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(GuiWindowFlags.NoFocusOnAppearing)); Assert.Equal(requested, NativeImGui.GetWindowPos()); NativeImGui.TextUnformatted("Moving viewport"); NativeImGui.End(); @@ -249,18 +333,30 @@ public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() [Fact] public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Logical DPI transition", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Logical DPI transition", width = 320, height = 240, visible = false } + ); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); float previous = 0f; context.RenderFrame(() => previous = NativeImGui.Raw.GetMainViewport()->DpiScale); - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); Assert.True(io->Monitors.Size > 0); for (int index = 0; index < io->Monitors.Size; index++) + { io->Monitors.Data[index].DpiScale = previous * 2f; + } Assert.Equal(previous, NativeImGui.Raw.GetMainViewport()->DpiScale); context.RenderFrame(() => Assert.Equal(previous * 2f, NativeImGui.Raw.GetMainViewport()->DpiScale)); } @@ -268,12 +364,22 @@ public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame( [Fact] public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport ownership", width = 320, height = 240, visible = false }); + using Sdl3PlatformWindow window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport ownership", width = 320, height = 240, visible = false } + ); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { @@ -281,14 +387,14 @@ public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestructi Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); try { Assert.Equal(2, application.GetWindows().Count); - var target = Assert.IsType(renderer.target); - Assert.True(context.TryGetWindowId(viewport.ID, out uint id)); - Assert.Equal(target.windowId, id); + PlatformImGuiViewportTarget target = Assert.IsType(renderer.target); + Assert.True(context.TryGetWindowID(viewport.ID, out uint id)); + Assert.Equal(target.windowID, id); Assert.Equal(target.nativeHandles.windowHandle, (nint)viewport.PlatformHandleRaw); Assert.Equal(window.nativeHandles.handleKind, target.nativeHandles.handleKind); } @@ -299,7 +405,7 @@ public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestructi Assert.Single(application.GetWindows()); Assert.Null(renderer.target); - Assert.True(viewport.PlatformUserData == null); + Assert.True(viewport.PlatformUserData is null); } private sealed class FixtureRenderer : IPlatformImGuiRenderer @@ -308,43 +414,32 @@ private sealed class FixtureRenderer : IPlatformImGuiRenderer public bool supportsViewports => true; public bool supportsVertexOffsets { get; init; } - public void RenderMain(IntPtr drawData) - { - } + public void RenderMain(nint drawData) {} public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { - } + ) {} public void CreateViewport(PlatformImGuiViewportTarget target) => this.target = target; - public void ResizeViewport(PlatformImGuiViewportTarget target) - { - } + + public void ResizeViewport(PlatformImGuiViewportTarget target) {} public void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData - ) { - } + nint drawData + ) {} - public void PresentViewport(PlatformImGuiViewportTarget target) - { - } + public void PresentViewport(PlatformImGuiViewportTarget target) {} - public Task RetireViewport(PlatformImGuiViewportTarget target) + public Task RetireViewportAsync(PlatformImGuiViewportTarget target) { this.target = null; return Task.CompletedTask; } - public void DrainViewportRetirements() - { - } + public void DrainViewportRetirements() {} - public void Dispose() - { - } + public void Dispose() {} } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs index 636fed6f8..00f923e3e 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs @@ -1,8 +1,8 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; using System; using System.Numerics; +using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; using Inno.Core.Execution; @@ -10,8 +10,9 @@ using Inno.Native.ImGui; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.ImGui.Tests; @@ -21,31 +22,41 @@ public sealed unsafe class ViewportRetirementTests [Trait("ProcessIsolation", "Required")] public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(FaultedRetirementRetainsWindowRendererAndApplicationOwners))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(FaultedRetirementRetainsWindowRendererAndApplicationOwners) + )) { return; + } // A failed retirement intentionally retains dependencies until the host process restarts. // Run this contract in its own test process, rather than forcing unsafe cleanup. var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - var window = application.CreateWindow(new PlatformWindowOptions + Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Faulted retirement", width = 320, height = 240, visible = false + title = "Faulted retirement", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); - var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { ID = 4221, Size = Unsafe.BitCast(new Vector2(100, 90)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); - uint id = renderer.target!.windowId; + uint id = renderer.target!.windowID; io->PlatformDestroyWindow(&viewport); renderer.Fail(); - Assert.Throws(() => context.RenderFrame(static () => { })); + Assert.Throws(() => context.RenderFrame(static () => {})); Assert.Throws(() => application.DestroyImGuiContext(window)); Assert.Throws(() => application.Dispose()); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(0, renderer.disposeCount); GC.KeepAlive(context); GC.KeepAlive(application); @@ -54,70 +65,104 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() [Fact] public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Retirement owner", width = 320, height = 240, visible = false + title = "Retirement owner", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); - using var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); - var viewport = new ImGuiViewport { ID = 4218, Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + var viewport = new ImGuiViewport + { + ID = 4218, + Size = Unsafe.BitCast(new Vector2(100, 90)), + Pos = Unsafe.BitCast(new Vector2(30, 30)) + }; + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); - uint id = renderer.target!.windowId; + uint id = renderer.target!.windowID; io->PlatformDestroyWindow(&viewport); Assert.Single(application.GetWindows()); - Assert.False(context.TryGetWindowId(viewport.ID, out _)); - Assert.True(viewport.PlatformUserData == null); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False(context.TryGetWindowID(viewport.ID, out _)); + Assert.True(viewport.PlatformUserData is null); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); + context.RenderFrame(static () => {}); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(1, renderer.retireCount); renderer.Complete(); - context.RenderFrame(static () => { }); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); + context.RenderFrame(static () => {}); Assert.Equal(1, renderer.retireCount); } [Fact] public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Pending drain", width = 320, height = 240, visible = false + title = "Pending drain", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); - var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); - var viewport = new ImGuiViewport { ID = 4219, Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; + var viewport = new ImGuiViewport + { + ID = 4219, + Size = Unsafe.BitCast(new Vector2(100, 90)), + Pos = Unsafe.BitCast(new Vector2(30, 30)) + }; NativeImGui.Raw.GetPlatformIO()->PlatformCreateWindow(&viewport); - uint id = renderer.target!.windowId; + uint id = renderer.target!.windowID; Assert.Throws(() => application.DestroyImGuiContext(window)); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(0, renderer.disposeCount); var replacement = new PendingRenderer(); Assert.Throws(() => application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), replacement)); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + replacement + )); Assert.Equal(0, replacement.disposeCount); renderer.Complete(); application.DestroyImGuiContext(window); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(1, renderer.disposeCount); context.Dispose(); application.DestroyImGuiContext(window); @@ -128,28 +173,38 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi [Fact] public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed creation", width = 320, height = 240, visible = false + title = "Failed creation", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer { failCreation = true }; - using var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + using PlatformImGuiContext context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { ID = 4220, Size = Unsafe.BitCast(new Vector2(100, 90)) }; NativeImGui.Raw.GetPlatformIO()->PlatformCreateWindow(&viewport); - uint id = renderer.target!.windowId; + uint id = renderer.target!.windowID; Assert.Single(application.GetWindows()); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); renderer.Complete(); - Assert.Throws(() => context.RenderFrame(static () => { })); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); + Assert.Throws(() => context.RenderFrame(static () => {})); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); + context.RenderFrame(static () => {}); } private sealed class PendingRenderer : IPlatformImGuiRenderer @@ -162,35 +217,50 @@ private sealed class PendingRenderer : IPlatformImGuiRenderer public bool supportsViewports => true; public bool supportsVertexOffsets => false; - public void RenderMain(IntPtr drawData) { } + + public void RenderMain(nint drawData) {} + public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { } + ) {} + public void CreateViewport(PlatformImGuiViewportTarget target) { this.target = target; if (failCreation) + { throw new InvalidOperationException("The fixture rejected viewport creation."); + } } - public void ResizeViewport(PlatformImGuiViewportTarget target) { } + + public void ResizeViewport(PlatformImGuiViewportTarget target) {} + public void RenderViewport( PlatformImGuiViewportTarget target, - IntPtr drawData - ) { } - public void PresentViewport(PlatformImGuiViewportTarget target) { } - public Task RetireViewport(PlatformImGuiViewportTarget target) + nint drawData + ) {} + + public void PresentViewport(PlatformImGuiViewportTarget target) {} + + public Task RetireViewportAsync(PlatformImGuiViewportTarget target) { retireCount++; return m_retirement.Task; } + public void DrainViewportRetirements() { if (retireCount != 0 && !m_retirement.Task.IsCompletedSuccessfully) + { throw new RetirementPendingException("The fixture still borrows the SDL window."); + } } + public void Dispose() => disposeCount++; + internal void Complete() => m_retirement.TrySetResult(); + internal void Fail() => m_retirement.TrySetException(new InvalidOperationException("The renderer failed to retire its window.")); } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs index 4a087a20f..29fe3321f 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs @@ -1,48 +1,69 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; +using System.IO; using System.Numerics; -using Inno.Native.ImGui; +using System.Runtime.CompilerServices; +using BGCS.Runtime; using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Core.Diagnostics; +using Inno.Core.Input; +using Inno.Core.Logging; +using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Native.ImGui; + +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using GuiCond = Inno.Editor.ImGui.ImGuiCond; +using GuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using GuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; using Widget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.ImGui.Tests; + public sealed unsafe class WidgetLayoutTests { [Fact] public void PackedColorConversionMatchesNativeSaturationRoundingAndChannelOrder() { - using (NativeContext context = new(1f)) + using (var context = new NativeContext(1f)) { context.Frame(() => { - BeginWindow("Color format contract", new(400f, 300f)); + BeginWindow("Color format contract", new Vector2(400f, 300f)); try { float[] boundaries = [float.NegativeInfinity, -1f, -0f, 0f, 0.5f, 1f, 2f, float.PositiveInfinity, float.NaN]; foreach (float value in boundaries) { - Verify(new(value, 0f, 0f, 0f)); - Verify(new(0f, value, 0f, 0f)); - Verify(new(0f, 0f, value, 0f)); - Verify(new(0f, 0f, 0f, value)); + Verify(new Vector4(value, 0f, 0f, 0f)); + Verify(new Vector4(0f, value, 0f, 0f)); + Verify(new Vector4(0f, 0f, value, 0f)); + Verify(new Vector4(0f, 0f, 0f, value)); } for (int channel = 0; channel < 255; channel++) { float half = (channel + 0.5f) / 255f; - Verify(new(MathF.BitDecrement(half), half, MathF.BitIncrement(half), 1f)); + Verify(new Vector4(MathF.BitDecrement(half), half, MathF.BitIncrement(half), 1f)); } var random = new Random(0x2DCA); for (int index = 0; index < 4096; index++) - Verify(new(random.NextSingle() * 3f - 1f, random.NextSingle() * 3f - 1f, - random.NextSingle() * 3f - 1f, random.NextSingle() * 3f - 1f)); + { + Verify( + new Vector4( + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f + ) + ); + } } finally { @@ -75,14 +96,14 @@ public void StandaloneMetricsApplyImmediatelyAndRetainedMetricsDoNotRootTheirRet [Fact] public void StyleRequestsDoNotChangeTheActiveNativeFrame() { - using NativeContext context = new(1f); - var widgets = EditorUI.current.widgets; + using var context = new NativeContext(1f); + Widget widgets = EditorUI.current.widgets; for (int frame = 0; frame < 2; frame++) { context.Frame(() => { widgets.SetupStyle(); - BeginWindow("Stable style input", new(400f, 300f)); + BeginWindow("Stable style input", new Vector2(400f, 300f)); try { if (frame == 0) @@ -114,12 +135,12 @@ public void StyleRequestsDoNotChangeTheActiveNativeFrame() [Fact] public void AForeignNativeContextCannotPublishChangesIntoASuspendedOwnerFrame() { - using NativeContext context = new(1f); - var widgets = EditorUI.current.widgets; + using var context = new NativeContext(1f); + Widget widgets = EditorUI.current.widgets; context.Frame(() => { widgets.SetupStyle(); - BeginWindow("Suspended style owner", new(400f, 300f)); + BeginWindow("Suspended style owner", new Vector2(400f, 300f)); try { ImGuiNativeContext* own = NativeImGui.Raw.GetCurrentContext(); @@ -154,15 +175,15 @@ public void AForeignNativeContextCannotPublishChangesIntoASuspendedOwnerFrame() [Fact] public void CopiedWindowGeometryRequiresAnActiveNativeFrame() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Assert.Throws(() => EditorImGui.GetClipBounds()); Assert.Throws(() => EditorImGui.GetWindowBounds()); context.Frame(() => { - BeginWindow("Geometry owner", new(400f, 300f)); + BeginWindow("Geometry owner", new Vector2(400f, 300f)); try { - var clip = EditorImGui.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = EditorImGui.GetClipBounds(); Assert.True(clip.maximum.X > clip.minimum.X && clip.maximum.Y > clip.minimum.Y); Assert.True(EditorImGui.GetWindowBounds().maximumX > EditorImGui.GetWindowBounds().minimumX); } @@ -178,28 +199,41 @@ public void CopiedWindowGeometryRequiresAnActiveNativeFrame() [Fact] public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 3; frame++) { context.Frame(() => { - BeginWindow("Flattened tree", new(400f, 300f)); + BeginWindow("Flattened tree", new Vector2(400f, 300f)); try { - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; widgets.SetTreeNodeOpen("root", true); ulong revision = widgets.treeExpansionRevision; widgets.SetTreeNodeOpen("root", true); Assert.Equal(revision, widgets.treeExpansionRevision); int nativeDepth = NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth; - var root = widgets.TreeNode("root", _ => NativeImGui.TextUnformatted("Root"), new() { depth = 0 }); + TreeNodeResult root = widgets.TreeNode( + "root", + _ => NativeImGui.TextUnformatted("Root"), + new TreeNodeOptions() { depth = 0 } + ); Assert.True(root.isOpen); Assert.True(widgets.IsTreeNodeOpen("root")); Assert.Equal(nativeDepth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); - var child = widgets.TreeNode("child", _ => NativeImGui.TextUnformatted("Deep child"), new() { depth = 7, isLeaf = true }); + TreeNodeResult child = widgets.TreeNode( + "child", + _ => NativeImGui.TextUnformatted("Deep child"), + new TreeNodeOptions() { depth = 7, isLeaf = true } + ); Assert.True(child.contentMin.X > root.contentMin.X); var failure = new InvalidOperationException("Rejected flat content"); - Assert.Same(failure, Assert.Throws(() => widgets.TreeNode("failed", _ => throw failure, new() { depth = 2 }))); + Assert.Same( + failure, + Assert.Throws( + () => widgets.TreeNode("failed", _ => throw failure, new TreeNodeOptions() { depth = 2 }) + ) + ); Assert.Equal(nativeDepth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); widgets.SetTreeNodeOpen("root", false); Assert.True(widgets.treeExpansionRevision > revision); @@ -216,23 +250,27 @@ public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() [Fact] public void TenThousandTreeRowsSubmitCustomContentOnlyWithinTheViewport() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 3; frame++) { context.Frame(() => { - BeginWindow("Large tree", new(400f, 300f)); + BeginWindow("Large tree", new Vector2(400f, 300f)); int drawn = 0; - Action draw = _ => + Action draw = _ => { drawn++; NativeImGui.TextUnformatted("Visible content"); }; for (int row = 0; row < 10_000; row++) - _ = EditorUI.current.widgets.TreeNode("row-" + row, draw, new() { isLeaf = true }); + { + _ = EditorUI.current.widgets.TreeNode("row-" + row, draw, new TreeNodeOptions() { isLeaf = true }); + } Assert.InRange(drawn, 1, 64); if (frame == 1) + { NativeImGui.SetScrollY(100_000f); + } NativeImGui.End(); }); } @@ -241,10 +279,10 @@ public void TenThousandTreeRowsSubmitCustomContentOnlyWithinTheViewport() [Fact] public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); context.Frame(() => { - BeginWindow("Clipped rows", new(400f, 300f)); + BeginWindow("Clipped rows", new Vector2(400f, 300f)); int submitted = 0; bool preserved = false; float height = NativeImGui.GetTextLineHeightWithSpacing(); @@ -257,7 +295,9 @@ public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() submitted += end - start; preserved |= start <= 9999 && end > 9999; for (int row = start; row < end; row++) - NativeImGui.Dummy(new(100f, NativeImGui.GetTextLineHeight())); + { + NativeImGui.Dummy(new Vector2(100f, NativeImGui.GetTextLineHeight())); + } }, [9999]); Assert.InRange(submitted, 1, 64); Assert.True(preserved); @@ -268,20 +308,27 @@ public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() [Fact] public void FixedRowFailureReleasesTheClipperBeforeTheNextFrame() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 2; frame++) { context.Frame(() => { - BeginWindow("Clipper failure", new(400f, 300f)); + BeginWindow("Clipper failure", new Vector2(400f, 300f)); int before = NativeImGui.Raw.GetCurrentContext()->ClipperTempDataStacked; var failure = new InvalidOperationException("Row extension rejected drawing."); - Assert.Same(failure, Assert.Throws(() => EditorUI.current.widgets.ClippedRows( - 10_000, NativeImGui.GetTextLineHeightWithSpacing(), 0, ( - state, - start, - end - ) => throw failure))); + Assert.Same( + failure, + Assert.Throws(() => EditorUI.current.widgets.ClippedRows( + 10_000, + NativeImGui.GetTextLineHeightWithSpacing(), + 0, + ( + state, + start, + end + ) => throw failure + )) + ); Assert.Equal(before, NativeImGui.Raw.GetCurrentContext()->ClipperTempDataStacked); NativeImGui.End(); }); @@ -294,23 +341,23 @@ public void FixedRowFailureReleasesTheClipperBeforeTheNextFrame() [InlineData(1.5f)] public void TrendUsesOneBoundedRegionAndFiniteGeometry(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); context.Frame(() => { BeginWindow("Trend bounds", new Vector2(400f, 400f)); - var widgets = EditorUI.current.widgets; - widgets.Trend("Finite extremes", new[] { float.MinValue, 0f, float.MaxValue }, offset: 1); + Widget widgets = EditorUI.current.widgets; + widgets.Trend("Finite extremes", [float.MinValue, 0f, float.MaxValue], offset: 1); Assert.Equal(widgets.style.trendHeight, NativeImGui.GetItemRectSize().Y, 3); Assert.True(NativeImGui.GetItemRectSize().X <= 400f); - var draw = NativeImGui.Raw.GetWindowDrawList(); + ImDrawList* draw = NativeImGui.Raw.GetWindowDrawList(); for (int index = 0; index < draw->VtxBuffer.Size; index++) { Vector2 point = Unsafe.BitCast(draw->VtxBuffer.Data[index].Pos); Assert.True(float.IsFinite(point.X) && float.IsFinite(point.Y)); } - widgets.Trend("Empty", ReadOnlySpan.Empty); - Assert.Throws(() => widgets.Trend("Offset", new[] { 1f }, offset: 1)); - Assert.Throws(() => widgets.Trend("Invalid", new[] { float.NaN })); + widgets.Trend("Empty", []); + Assert.Throws(() => widgets.Trend("Offset", [1f], offset: 1)); + Assert.Throws(() => widgets.Trend("Invalid", [float.NaN])); NativeImGui.End(); }); } @@ -318,31 +365,32 @@ public void TrendUsesOneBoundedRegionAndFiniteGeometry(float zoom) [Fact] public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() { - string root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "InnoListNavigation", Guid.NewGuid().ToString("N")); - System.IO.Directory.CreateDirectory(root); + string root = Path.Combine(Path.GetTempPath(), "InnoListNavigation", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); try { - var diagnostics = new Inno.Core.Diagnostics.DiagnosticHub(); + var diagnostics = new DiagnosticHub(); using IDisposable diagnosticScope = diagnostics.EnterScope(); - using var modules = new Inno.Extensibility.Modules.ModuleHost(new() + using var modules = new ModuleHost(new ModuleHostOptions() { - catalogSource = new Inno.Adapter.Modules.DotNet.DotNetAssemblyCatalogSource(typeof(WidgetLayoutTests).Assembly) + catalogSource = new DotNetAssemblyCatalogSource(typeof(WidgetLayoutTests).Assembly) }); - using var types = new Inno.Extensibility.Types.TypeCatalog(modules, new Inno.Adapter.Modules.DotNet.ReflectionTypeCatalogSource()); - using var logs = new Inno.Core.Logging.LogRouter(); - using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime( + using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + using var logs = new LogRouter(); + using var runtime = new EditorInteractionRuntime( root, types, logs, - new Inno.Editor.Core.EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + new EditorKeyboardPolicy(KeyModifier.Control, "Super") + ); runtime.Start(); - using NativeContext context = new(1f); - NativeImGui.Raw.GetIO()->ConfigFlags |= (int)Inno.Native.ImGui.ImGuiConfigFlags.NavEnableKeyboard; + using var context = new NativeContext(1f); + NativeImGui.Raw.GetIO()->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; int focused = 4; bool textInput = false; bool popup = false; string query = string.Empty; - Inno.Editor.ImGui.ImGuiWidget.ListNavigationResult observed = default; + ListNavigationResult observed = default; Action draw = () => { BeginWindow("List navigation", new Vector2(500f, 400f)); @@ -366,40 +414,40 @@ public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() }; context.Frame(draw); context.Frame(draw); - var io = NativeImGui.Raw.GetIO(); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.PageDown, 1); + ImGuiIO* io = NativeImGui.Raw.GetIO(); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.PageDown, 1); context.Frame(draw); Assert.Equal(14, focused); Assert.True(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.PageDown, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.PageDown, 0); context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.End, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.End, 1); context.Frame(draw); Assert.Equal(99, focused); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.End, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.End, 0); context.Frame(draw); textInput = true; context.Frame(draw); context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Home, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.Home, 1); context.Frame(draw); Assert.Equal(99, focused); Assert.False(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Home, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.Home, 0); context.Frame(draw); textInput = false; popup = true; context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.UpArrow, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.UpArrow, 1); context.Frame(draw); Assert.Equal(99, focused); Assert.False(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.UpArrow, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.UpArrow, 0); context.Frame(draw); } finally { - System.IO.Directory.Delete(root, recursive: true); + Directory.Delete(root, recursive: true); } } @@ -411,7 +459,7 @@ public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() [InlineData("tree-overlay")] public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 2; frame++) { context.Frame(() => @@ -420,7 +468,7 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) nint window = (nint)NativeImGui.Raw.GetCurrentWindow(); int depth = NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth; Vector2 padding = Unsafe.BitCast(NativeImGui.Raw.GetStyle()->FramePadding); - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; Action rejected = () => throw new InvalidOperationException("Rejected extension draw"); Assert.Throws(() => { @@ -432,7 +480,8 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) drawLeadingControl: failure == "card-leading" ? rejected : null, drawTrailingControl: failure == "card-trailing" ? rejected : null, dimmed: true, - drawContextMenu: failure == "card-menu" ? rejected : null); + drawContextMenu: failure == "card-menu" ? rejected : null + ); } else { @@ -440,19 +489,21 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) _ = widgets.TreeNode("failed-tree", _ => { if (failure == "tree-content") + { rejected(); + } EditorImGui.Text("Extension"); - }, new() { drawViewportOverlay = failure == "tree-overlay" ? rejected : null }); + }, new TreeNodeOptions() { drawViewportOverlay = failure == "tree-overlay" ? rejected : null }); } }); Assert.Equal(window, (nint)NativeImGui.Raw.GetCurrentWindow()); Assert.Equal(depth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); Assert.Equal(padding, Unsafe.BitCast(NativeImGui.Raw.GetStyle()->FramePadding)); widgets.SetNextTreeNodeOpen(true); - var next = widgets.TreeNode("next-tree", _ => EditorImGui.Text("Next valid row"), new()); + TreeNodeResult next = widgets.TreeNode("next-tree", _ => EditorImGui.Text("Next valid row"), new TreeNodeOptions()); Assert.True(next.isOpen); NativeImGui.TreePop(); - EditorImGui.GetDrawList().Line(new(30f, 30f), new(60f, 60f), uint.MaxValue); + EditorImGui.GetDrawList().Line(new Vector2(30f, 30f), new Vector2(60f, 60f), uint.MaxValue); NativeImGui.End(); }); } @@ -461,13 +512,13 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) [Fact] public void DrawingBorrowRejectsAnotherWindowOrFrame() { - using NativeContext context = new(1f); - Inno.Editor.ImGui.EditorDrawList borrow = default; + using var context = new NativeContext(1f); + EditorDrawList borrow = default; context.Frame(() => { BeginWindow("Drawing owner", new Vector2(400f, 300f)); borrow = EditorImGui.GetDrawList(); - borrow.Line(new(30f, 30f), new(60f, 60f), uint.MaxValue); + borrow.Line(new Vector2(30f, 30f), new Vector2(60f, 60f), uint.MaxValue); _ = EditorImGui.BeginChild("Other owner", new Vector2(100f, 100f)); Assert.Throws(() => borrow.Line(Vector2.Zero, Vector2.One, 0)); EditorImGui.EndChild(); @@ -479,13 +530,13 @@ public void DrawingBorrowRejectsAnotherWindowOrFrame() Assert.Throws(() => borrow.Line(Vector2.Zero, Vector2.One, 0)); NativeImGui.End(); }); - Assert.Throws(() => default(Inno.Editor.ImGui.EditorDrawList).Line(Vector2.Zero, Vector2.One, 0)); + Assert.Throws(() => default(EditorDrawList).Line(Vector2.Zero, Vector2.One, 0)); } [Fact] public void BoundedTextControlsDoNotAllocateOneBufferAndEncoderPerSubmission() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); string value = "Unicode: 漢字 😀"; long allocated = 0; Action draw = () => @@ -494,9 +545,9 @@ public void BoundedTextControlsDoNotAllocateOneBufferAndEncoderPerSubmission() long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 128; index++) { - EditorImGui.PushId(index); + EditorImGui.PushID(index); _ = EditorImGui.InputText("Value", ref value, 1024); - EditorImGui.PopId(); + EditorImGui.PopID(); } allocated = GC.GetAllocatedBytesForCurrentThread() - before; @@ -509,9 +560,9 @@ public void BoundedTextControlsDoNotAllocateOneBufferAndEncoderPerSubmission() } [Fact] - public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() + public void TimelineWorkspaceUsesOneBoundedChildScrollOwner() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); float childScroll = 0f; float parentScroll = 0f; for (int frame = 0; frame < 4; frame++) @@ -529,7 +580,9 @@ public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() if (EditorUI.current.widgets.SectionHeader("Frames")) { for (int index = 0; index < 40; index++) + { EditorImGui.Text("Frame " + index); + } } }); } @@ -551,9 +604,9 @@ public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() } [Fact] - public void TimelinePointer_UsesCumulativeUiDragUntilRelease() + public void TimelinePointerUsesCumulativeUIDragUntilRelease() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Vector2 hit = default; Vector2 drag = default; bool held = false; @@ -565,7 +618,7 @@ public void TimelinePointer_UsesCumulativeUiDragUntilRelease() hit = (EditorImGui.GetItemMinimum() + EditorImGui.GetItemMaximum()) * 0.5f; active = EditorImGui.IsItemActive(); held = EditorImGui.IsMouseButtonDown(); - drag = EditorImGui.GetMouseDragDelta(ImGuiMouseButton.Left, 0f); + drag = EditorImGui.GetMouseDragDelta(GuiMouseButton.Left, 0f); NativeImGui.End(); }; context.Frame(draw); @@ -592,9 +645,9 @@ public void TimelinePointer_UsesCumulativeUiDragUntilRelease() [InlineData(0.75f)] [InlineData(1f)] [InlineData(1.5f)] - public void PropertyRows_WrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom) + public void PropertyRowsWrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 labelSize = default; float labelWidth = 0f; float valueWidth = 0f; @@ -606,17 +659,21 @@ public void PropertyRows_WrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom { BeginWindow("Property layout", new Vector2(320f, 270f)); fontHeight = NativeImGui.GetTextLineHeight(); - EditorUI.current.widgets.PropertyRow("persistence", () => - { - labelWidth = NativeImGui.GetContentRegionAvail().X; - EditorUI.current.widgets.PropertyLabel("Persistent data directory for this exported application"); - labelSize = NativeImGui.GetItemRectSize(); - }, () => - { - valueWidth = NativeImGui.GetContentRegionAvail().X; - string value = "Application data"; - EditorUI.current.widgets.SearchInput("directory", "Directory", ref value); - }); + EditorUI.current.widgets.PropertyRow( + "persistence", + () => + { + labelWidth = NativeImGui.GetContentRegionAvail().X; + EditorUI.current.widgets.PropertyLabel("Persistent data directory for this exported application"); + labelSize = NativeImGui.GetItemRectSize(); + }, + () => + { + valueWidth = NativeImGui.GetContentRegionAvail().X; + string value = "Application data"; + EditorUI.current.widgets.SearchInput("directory", "Directory", ref value); + } + ); scroll = new Vector2(NativeImGui.GetScrollMaxX(), NativeImGui.GetScrollMaxY()); NativeImGui.End(); }); @@ -637,12 +694,12 @@ public void PropertyRows_WrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom [InlineData(2, false, 1.5f)] [InlineData(100, true, 1f)] [InlineData(100, true, 1.5f)] - public void BoundedSelectors_OpenDownwardAndScrollOnlyWhenRequired( + public void BoundedSelectorsOpenDownwardAndScrollOnlyWhenRequired( int itemCount, bool shouldScroll, float zoom ) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 popupPosition = default; @@ -658,7 +715,9 @@ float zoom { opened = true; for (int index = 0; index < itemCount; index++) + { NativeImGui.Selectable($"Tag {index}"); + } popupPosition = NativeImGui.GetWindowPos(); popupSize = NativeImGui.GetWindowSize(); scroll = new Vector2(NativeImGui.GetScrollMaxX(), NativeImGui.GetScrollMaxY()); @@ -675,7 +734,9 @@ float zoom context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 0, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(popupPosition.Y, controlMaximum.Y - 1f, controlMaximum.Y + 1f); Assert.True(popupPosition.X >= 20f); @@ -689,9 +750,9 @@ float zoom [Theory] [InlineData(280f)] [InlineData(320f)] - public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float verticalOffset) + public void SelectorsNearWindowBottomUseOnlyRemainingDownwardSpace(float verticalOffset) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 popupPosition = default; @@ -706,7 +767,9 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic { opened = true; for (int index = 0; index < 100; index++) + { NativeImGui.Selectable($"Object {index}"); + } popupPosition = NativeImGui.GetWindowPos(); popupSize = NativeImGui.GetWindowSize(); EditorUI.current.widgets.EndBoundedCombo(); @@ -722,7 +785,9 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 0, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(popupPosition.Y, controlMaximum.Y - 1f, controlMaximum.Y + 1f); Assert.True(popupPosition.Y + popupSize.Y <= 381f); @@ -733,9 +798,9 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic [InlineData(0.9f)] [InlineData(1f)] [InlineData(1.1f)] - public void ContextMenu_SearchFillsItsActualContentWidthWithoutScrollbars(float zoom) + public void ContextMenuSearchFillsItsActualContentWidthWithoutScrollbars(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 scroll = default; @@ -768,16 +833,18 @@ public void ContextMenu_SearchFillsItsActualContentWidthWithoutScrollbars(float context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 1, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(availableWidth - searchWidth, 0f, 1.1f); Assert.Equal(Vector2.Zero, scroll); } [Fact] - public void OverlappingWindows_OnlyForegroundClickableTextReceivesPress() + public void OverlappingWindowsOnlyForegroundClickableTextReceivesPress() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int backgroundPresses = 0; int foregroundPresses = 0; Vector2 hit = default; @@ -786,12 +853,16 @@ public void OverlappingWindows_OnlyForegroundClickableTextReceivesPress() BeginWindow("Background panel", new Vector2(400f, 300f)); NativeImGui.SetCursorScreenPos(new Vector2(100f, 100f)); if (EditorUI.current.widgets.ClickableText("close", "X", new Vector2(40f, 40f))) + { backgroundPresses++; + } NativeImGui.End(); BeginWindow("Foreground shader", new Vector2(400f, 300f)); NativeImGui.SetCursorScreenPos(new Vector2(100f, 100f)); if (EditorUI.current.widgets.ClickableText("action", "Edit", new Vector2(40f, 40f))) + { foregroundPresses++; + } hit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; NativeImGui.End(); }; @@ -807,31 +878,39 @@ public void OverlappingWindows_OnlyForegroundClickableTextReceivesPress() [InlineData(false, 1f)] [InlineData(true, 1.5f)] [InlineData(false, 1.5f)] - public void TreeRows_ContentClickIsDeliveredOnce( + public void TreeRowsContentClickIsDeliveredOnce( bool isLeaf, float zoom ) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); int presses = 0; Vector2 hit = default; Action draw = () => { BeginWindow("Tree content", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode($"content-{isLeaf}-{zoom}", _ => EditorUI.current.widgets.IconText( - "O", - "Selected object", - false - ), new() { isLeaf = isLeaf, drawViewportOverlay = () => - { - float rowY = NativeImGui.GetItemRectMin().Y; - NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); - _ = EditorUI.current.widgets.ClickableIcon("visibility", "V", "Visibility"); - } }); + TreeNodeResult result = EditorUI.current.widgets.TreeNode( + $"content-{isLeaf}-{zoom}", + _ => EditorUI.current.widgets.IconText("O", "Selected object", false), + new TreeNodeOptions() + { + isLeaf = isLeaf, + drawViewportOverlay = () => + { + float rowY = NativeImGui.GetItemRectMin().Y; + NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); + _ = EditorUI.current.widgets.ClickableIcon("visibility", "V", "Visibility"); + } + } + ); hit = new Vector2(result.contentMin.X + 80f, (result.min.Y + result.max.Y) * 0.5f); if (result.isClicked) + { presses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -841,22 +920,30 @@ float zoom } [Fact] - public void TreeRows_DisclosureClickExpandsWithoutSelectingContent() + public void TreeRowsDisclosureClickExpandsWithoutSelectingContent() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int presses = 0; bool opened = false; Vector2 hit = default; Action draw = () => { BeginWindow("Tree disclosure", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode("disclosure", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false }); + TreeNodeResult result = EditorUI.current.widgets.TreeNode( + "disclosure", + _ => NativeImGui.TextUnformatted("Parent"), + new TreeNodeOptions() { isLeaf = false } + ); hit = new Vector2(result.contentMin.X - NativeImGui.GetTreeNodeToLabelSpacing() * 0.5f, (result.min.Y + result.max.Y) * 0.5f); opened = result.isOpen; if (result.isClicked) + { presses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -870,25 +957,37 @@ public void TreeRows_DisclosureClickExpandsWithoutSelectingContent() [Theory] [InlineData(true)] [InlineData(false)] - public void TreeRows_OverlayConsumesItsOwnClick(bool settleHover) + public void TreeRowsOverlayConsumesItsOwnClick(bool settleHover) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int rowPresses = 0; int overlayPresses = 0; Vector2 overlayHit = default; Action draw = () => { BeginWindow("Tree overlay", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode($"overlay-{settleHover}", _ => NativeImGui.TextUnformatted("Object"), new() { isLeaf = true, drawViewportOverlay = () => - { - float rowY = NativeImGui.GetItemRectMin().Y; - NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); - if (NativeImGui.SmallButton("Eye")) - overlayPresses++; - overlayHit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; - } }); + TreeNodeResult result = EditorUI.current.widgets.TreeNode( + $"overlay-{settleHover}", + _ => NativeImGui.TextUnformatted("Object"), + new TreeNodeOptions() + { + isLeaf = true, + drawViewportOverlay = () => + { + float rowY = NativeImGui.GetItemRectMin().Y; + NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); + if (NativeImGui.SmallButton("Eye")) + { + overlayPresses++; + } + overlayHit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; + } + } + ); if (result.isClicked) + { rowPresses++; + } NativeImGui.End(); }; context.Frame(draw); @@ -899,9 +998,9 @@ public void TreeRows_OverlayConsumesItsOwnClick(bool settleHover) } [Fact] - public void TreeRows_ContentDoubleClickExpandsOnce() + public void TreeRowsContentDoubleClickExpandsOnce() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int presses = 0; int doublePresses = 0; bool opened = false; @@ -909,15 +1008,25 @@ public void TreeRows_ContentDoubleClickExpandsOnce() Action draw = () => { BeginWindow("Tree double click", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode("double-click", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false }); + TreeNodeResult result = EditorUI.current.widgets.TreeNode( + "double-click", + _ => NativeImGui.TextUnformatted("Parent"), + new TreeNodeOptions() { isLeaf = false } + ); hit = new Vector2(result.contentMin.X + 80f, (result.min.Y + result.max.Y) * 0.5f); opened = result.isOpen; if (result.isClicked) + { presses++; + } if (result.isDoubleClicked) + { doublePresses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -933,11 +1042,11 @@ public void TreeRows_ContentDoubleClickExpandsOnce() [Fact] public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); context.Frame(() => { BeginWindow("Mixed scope", new Vector2(400f, 300f)); - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; Assert.False(widgets.isMixedValue); widgets.MixedValue(true, () => { @@ -946,7 +1055,9 @@ public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() Assert.True(widgets.isMixedValue); }); Assert.False(widgets.isMixedValue); - Assert.Throws(() => widgets.MixedValue(true, () => throw new InvalidOperationException("rejected draw"))); + Assert.Throws( + () => widgets.MixedValue(true, () => throw new InvalidOperationException("rejected draw")) + ); Assert.False(widgets.isMixedValue); NativeImGui.End(); }); @@ -955,7 +1066,7 @@ public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() [MethodImpl(MethodImplOptions.NoInlining)] private static EditorStyleMetrics RetireStyleOwner(out WeakReference owner) { - using var session = new EditorUiSession(); + using EditorUI session = new EditorUISession(); owner = new WeakReference(session); return session.widgets.style; } @@ -964,21 +1075,22 @@ private static void BeginWindow( string name, Vector2 size ) { - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(size, (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(size, (int)(GuiCond.Always)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated(name, allowsNull: false); NativeImGui.Raw.Begin( (sbyte*)nativeTestText0.pointer, null, - (int)(ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings) + (int)(GuiWindowFlags.NoTitleBar | GuiWindowFlags.NoResize | GuiWindowFlags.NoMove | GuiWindowFlags.NoSavedSettings) ); } private sealed class NativeContext : IDisposable { private readonly ImGuiNativeContext* m_context; - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUI m_ui = new(); private readonly IDisposable m_uiScope; + public NativeContext(float zoom) { m_context = NativeImGui.Raw.CreateContext(null); @@ -1009,7 +1121,9 @@ public void Click( ImGuiIO* io = NativeImGui.Raw.GetIO(); NativeImGui.Raw.AddMousePosEvent(io, position.X, position.Y); if (settleHover) + { Frame(draw); + } NativeImGui.Raw.AddMouseButtonEvent(io, button, (true ? (byte)1 : (byte)0)); Frame(draw); NativeImGui.Raw.AddMouseButtonEvent(io, button, (false ? (byte)1 : (byte)0)); diff --git a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs index 85d9cbbab..83e5aa4c2 100644 --- a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs +++ b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs @@ -1,18 +1,21 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using Inno.Editor.Annotations; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; +using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Editor.Inspection.Tests; + public sealed class ConditionalInspectionTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "inno-inspection-" + Guid.NewGuid().ToString("N")); @@ -21,13 +24,21 @@ public sealed class ConditionalInspectionTests : IDisposable private readonly SerializationRegistry m_serialization; private readonly LogRouter m_logs = new(); private readonly EditorInteractionRuntime m_runtime; + public ConditionalInspectionTests() { Directory.CreateDirectory(m_root); - m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConditionalInspectionTests).Assembly) }); + m_modules = new( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConditionalInspectionTests).Assembly) } + ); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); - m_runtime = new(new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization]); + m_runtime = new( + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), + m_types, + m_logs, + [m_types, m_serialization] + ); m_runtime.Start(); } @@ -35,43 +46,95 @@ public ConditionalInspectionTests() public void ConditionalInspectorPeersResolveByPredicateAndRejectActualAmbiguity() { using var properties = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(properties, attributes, m_runtime.interactions, new ProbePropertyEdits(), m_logs); - using var inspectors = new InspectionDrawerRegistry(m_runtime.interactions, CreateDrawer, m_types, m_serialization); - Assert.True(inspectors.TryResolve(m_runtime.context, new ConditionalTarget(1, false), renderer, out var first, out _)); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + properties, + attributes, + m_runtime.interactions, + new ProbePropertyEdits(), + m_logs + ); + using var inspectors = new InspectionDrawerRegistry( + m_runtime.interactions, + CreateDrawer, + m_types, + m_serialization + ); + Assert.True( + inspectors.TryResolve(m_runtime.context, new ConditionalTarget(1, false), renderer, out IInspectionDrawer? first, out _) + ); Assert.IsType(first); - Assert.True(inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, false), renderer, out var second, out _)); + Assert.True( + inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, false), renderer, out IInspectionDrawer? second, out _) + ); Assert.IsType(second); - InvalidOperationException error = Assert.Throws(() => inspectors.TryResolve(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _)); + InvalidOperationException error = Assert.Throws( + () => inspectors.TryResolve(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _) + ); Assert.Contains("both accept", error.Message); - Assert.Throws(() => inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _)); + Assert.Throws( + () => inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _) + ); IInspectionDrawer CreateDrawer(Type type) => (IInspectionDrawer)Activator.CreateInstance(type, nonPublic: true)!; } [Fact] - public void PropertyAvailabilityUsesCurrentOwnerConditionsWithoutRequiringNativeUi() + public void PropertyAvailabilityUsesCurrentOwnerConditionsWithoutRequiringNativeUI() { using var properties = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(properties, attributes, m_runtime.interactions, new ProbePropertyEdits(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + properties, + attributes, + m_runtime.interactions, + new ProbePropertyEdits(), + m_logs + ); var target = new AvailabilityTarget(); - var values = m_serialization.GetProperties(target); + IReadOnlyList values = m_serialization.GetProperties(target); SerializedProperty conditional = values.Single(value => value.name == nameof(AvailabilityTarget.value)); Assert.False(renderer.GetPropertyAvailability(target, conditional).isVisible); target.visible = true; Assert.True(renderer.GetPropertyAvailability(target, conditional).isVisible); - Assert.True(renderer.GetPropertyAvailability(target, values.Single(value => value.name == nameof(AvailabilityTarget.readOnlyValue))).isReadOnly); + Assert.True( + renderer.GetPropertyAvailability( + target, + values.Single(value => value.name == nameof(AvailabilityTarget.readOnlyValue)) + ).isReadOnly + ); } - [StableTypeId("eeeb7c59-2af3-4cc3-81d2-c853feef3874")] + public void Dispose() + { + m_runtime.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + m_logs.Dispose(); + Directory.Delete(m_root, true); + } + + [StableTypeID("eeeb7c59-2af3-4cc3-81d2-c853feef3874")] public sealed class AvailabilityTarget : ISerializable { public bool visible { get; set; } - [SerializableProperty, ShowIf(nameof(visible))] + [SerializableProperty] + [ShowIf(nameof(visible))] public int value { get; set; } - [SerializableProperty, InspectorReadOnly] + [SerializableProperty] + [InspectorReadOnly] public int readOnlyValue { get; set; } } @@ -79,55 +142,59 @@ public sealed record ConditionalTarget( int kind, bool ambiguous ); + [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalFirst : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.kind == 1; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("First", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalSecond : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.kind == 2; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("Second", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalOverlap : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.ambiguous; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("Overlap", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } private sealed class ProbePropertyEdits : IInspectionPropertyEditService @@ -141,14 +208,4 @@ public bool ChangeProperty( string? componentName ) => throw new InvalidOperationException("Resolution must not edit a property."); } - - public void Dispose() - { - m_runtime.Dispose(); - m_serialization.Dispose(); - m_types.Dispose(); - m_modules.Dispose(); - m_logs.Dispose(); - Directory.Delete(m_root, true); - } } diff --git a/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs new file mode 100644 index 000000000..21fe80399 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs @@ -0,0 +1,25 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("9ea6d04d-4ed3-48f3-ac3a-b09372a575ab")] +internal sealed class BatchValidationComponent : GameComponent +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public bool rejectAnswer { get; set; } + + [OnSerializableRestored] + private void Validate() + { + if (rejectAnswer && value == 42) + { + throw new InvalidOperationException("The current owner rejected this batch value."); + } + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs new file mode 100644 index 000000000..cd89937cd --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs @@ -0,0 +1,33 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("f25d91a5-df87-4ed6-a383-12a9071af66e")] +internal sealed class CoupledHistoryComponent : GameBehavior +{ + private bool m_primary = true; + private CoupledHistoryMode m_mode; + + [SerializableProperty] + public bool primary + { + get => m_primary; + set => m_primary = value && mode == CoupledHistoryMode.Base; + } + + [SerializableProperty] + public CoupledHistoryMode mode + { + get => m_mode; + set + { + m_mode = value; + if (value == CoupledHistoryMode.Overlay) + { + m_primary = false; + } + } + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs index 73c4c5b5e..bd9050c5c 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs @@ -1,15 +1,15 @@ -using Inno.Adapter.Modules.DotNet; using System; -using System.Collections.Generic; using System.IO; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.Interactions; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions.Tests; + public sealed class EditorHistoryTests { [Fact] @@ -19,7 +19,9 @@ public void SeparateGesturesNeverMergeTheSamePropertyAcrossCommitBoundaries() for (int step = 0; step < 2; step++) { using var gesture = new EditorEditGesture(fixture.history, "Drag Value"); - Assert.True(fixture.history.Execute("Update", NeutralValueHistoryHandler.CreateChange(1, step, step + 1, gesture.mergeKey)).succeeded); + Assert.True( + fixture.history.Execute("Update", NeutralValueHistoryHandler.CreateChange(1, step, step + 1, gesture.mergeKey)).succeeded + ); gesture.Commit(); } @@ -87,7 +89,10 @@ public void RejectedOutOfOrderCompletionPreservesBothTransactions(string complet public void ExecuteUndoAndRedoMoveNeutralChangeBetweenStacks() { using var fixture = new HistoryFixture(); - EditorHistoryResult applied = fixture.history.Execute("Change Value", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 10)); + EditorHistoryResult applied = fixture.history.Execute( + "Change Value", + NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 10) + ); Assert.True(applied.succeeded); Assert.Equal(10, NeutralValueHistoryHandler.GetValue(1)); Assert.Equal("Change Value", fixture.history.undoName); @@ -102,7 +107,9 @@ public void ExecuteUndoAndRedoMoveNeutralChangeBetweenStacks() public void FailedTransitionRemainsAvailableForRetry() { using var fixture = new HistoryFixture(); - Assert.True(fixture.history.Execute("Conditional", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 1)).succeeded); + Assert.True( + fixture.history.Execute("Conditional", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 1)).succeeded + ); NeutralValueHistoryHandler.Block(slot: 1, EditorHistoryDirection.Undo); Assert.False(fixture.history.Undo().succeeded); Assert.True(fixture.history.canUndo); @@ -230,7 +237,10 @@ public void CompensationFailureFaultsHistoryAndRejectsFurtherTransactions() public void MissingHandlerCreatesAnExplicitAvailabilityBarrier() { using var fixture = new HistoryFixture(); - fixture.history.RecordApplied("Unavailable Change", new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3]))); + fixture.history.RecordApplied( + "Unavailable Change", + new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3])) + ); Assert.False(fixture.history.canUndo); Assert.Contains("tests/missing-history-handler", fixture.history.undoUnavailableReason); Assert.False(fixture.history.Undo().succeeded); @@ -241,12 +251,15 @@ public void MissingHandlerCreatesAnExplicitAvailabilityBarrier() public void LargePayloadUsesTheBoundedSessionDiskStore() { using var fixture = new HistoryFixture(); - byte[] payload = new byte[128 * 1024]; + var payload = new byte[128 * 1024]; BitConverter.GetBytes(1).CopyTo(payload, 0); BitConverter.GetBytes(9).CopyTo(payload, sizeof(int)); BitConverter.GetBytes(32).CopyTo(payload, sizeof(int) * 2); NeutralValueHistoryHandler.SetValue(slot: 1, value: 32); - fixture.history.RecordApplied("Large Neutral Change", new EditorHistoryChange(NeutralValueHistoryHandler.KIND, EditorHistoryPayload.FromBytes(payload))); + fixture.history.RecordApplied( + "Large Neutral Change", + new EditorHistoryChange(NeutralValueHistoryHandler.C_KIND, EditorHistoryPayload.FromBytes(payload)) + ); Assert.Equal(0, fixture.history.residentBytes); Assert.Equal(payload.LongLength, fixture.history.diskBytes); Assert.True(fixture.history.Undo().succeeded); @@ -272,14 +285,17 @@ private sealed class HistoryFixture : IDisposable private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorHistoryTests", Guid.NewGuid().ToString("N")); private readonly ModuleHost m_modules; private readonly LogRouter m_logs = new(); + internal HistoryFixture() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); NeutralValueHistoryHandler.Reset(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorHistoryTests).Assembly) }); - types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorHistoryTests).Assembly) } + ); + this.types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + this.runtime = new EditorInteractionRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, m_logs, [types] @@ -287,10 +303,6 @@ internal HistoryFixture() runtime.Start(); } - internal TypeCatalog types { get; } - internal EditorInteractionRuntime runtime { get; } - internal IEditorHistory history => runtime.interactions.history; - public void Dispose() { runtime.Dispose(); @@ -298,83 +310,13 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); - } - } -} - -[EditorHistoryHandler(NeutralValueHistoryHandler.KIND)] -public sealed class NeutralValueHistoryHandler : EditorHistoryHandler -{ - public const string KIND = "tests/neutral-values"; - private static readonly HashSet<(int Slot, EditorHistoryDirection Direction)> S_BLOCKED = []; - private static readonly Dictionary S_VALUES = []; - public static EditorHistoryChange CreateChange( - int slot, - int before, - int after, - string? mergeKey = null - ) { - byte[] bytes = new byte[sizeof(int) * 3]; - BitConverter.GetBytes(slot).CopyTo(bytes, 0); - BitConverter.GetBytes(before).CopyTo(bytes, sizeof(int)); - BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int) * 2); - return new EditorHistoryChange(KIND, EditorHistoryPayload.FromBytes(bytes), mergeKey); - } - - public static int GetValue(int slot) => S_VALUES.TryGetValue(slot, out int value) ? value : 0; - public static void SetValue( - int slot, - int value - ) => S_VALUES[slot] = value; - public static void Block( - int slot, - EditorHistoryDirection direction - ) => S_BLOCKED.Add((slot, direction)); - public static void Unblock( - int slot, - EditorHistoryDirection direction - ) => S_BLOCKED.Remove((slot, direction)); - public static void Reset() - { - S_BLOCKED.Clear(); - S_VALUES.Clear(); - } - - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 3 ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] bytes = change.payload.ReadBytes(); - int slot = BitConverter.ToInt32(bytes, 0); - if (S_BLOCKED.Contains((slot, direction))) - return EditorHistoryResult.Failure($"Slot {slot} is blocked for {direction}."); - int offset = direction == EditorHistoryDirection.Undo ? sizeof(int) : sizeof(int) * 2; - S_VALUES[slot] = BitConverter.ToInt32(bytes, offset); - return EditorHistoryResult.Success(); - } - - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) { - byte[] olderBytes = older.payload.ReadBytes(); - byte[] newerBytes = newer.payload.ReadBytes(); - int slot = BitConverter.ToInt32(olderBytes, 0); - if (slot != BitConverter.ToInt32(newerBytes, 0)) - { - merged = null; - return false; + } } - merged = CreateChange(slot, BitConverter.ToInt32(olderBytes, sizeof(int)), BitConverter.ToInt32(newerBytes, sizeof(int) * 2), older.mergeKey); - return true; + internal TypeCatalog types { get; } + internal EditorInteractionRuntime runtime { get; } + internal IEditorHistory history => runtime.interactions.history; } } diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs index e243462ec..d34bcd8f1 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs @@ -30,7 +30,8 @@ public void AltOrbitDoesNotStealPanAndCancelReleasesCapture() [Fact] public void ZoomPreservesPointerAnchorAndIsIndependentOfDisplayDensity() { - Vector2 origin = new(50, 30), pivot = new(110, 150); + var origin = new Vector2(50, 30); + var pivot = new Vector2(110, 150); float scale = EditorPlanarNavigation.WheelFactor(3); Vector2 updated = EditorPlanarNavigation.ZoomOrigin(origin, pivot, 1, scale); Assert.True(Vector2.Distance(pivot - origin, (pivot - updated) / scale) < 0.0001f); diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs new file mode 100644 index 000000000..90ef3b0f1 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs @@ -0,0 +1,14 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("edbd3940-a94c-499e-8f03-b0e232a39b21")] +[AllowMultipleComponent] +internal sealed class HistoryAssetReferenceComponent : GameComponent +{ + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs new file mode 100644 index 000000000..3bfb8f5d3 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("267e77d8-1112-4cf9-a9f1-01d9a1e59bbc")] +[AllowMultipleComponent] +internal sealed class HistoryComponent : GameBehavior +{ + [SerializableProperty] + public int value { get; set; } + + protected override void Reset() => value = 7; +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs new file mode 100644 index 000000000..09f86fcde --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("b269c970-8afe-46a0-a4a0-f44f737d059a")] +internal sealed class HistoryReferenceComponent : GameComponent +{ + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public GameComponent? targetComponent { get; set; } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs new file mode 100644 index 000000000..a0863ccd4 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("f00d5950-1136-4393-b246-644b69948f90")] +[AllowMultipleSystem] +internal sealed class HistorySystem : GameSystem +{ + [SerializableProperty] + public int value { get; set; } + + protected override void Reset() => value = 11; +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs b/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs new file mode 100644 index 000000000..08046849a --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Editor.Interactions.Tests; + +[EditorHistoryHandler(NeutralValueHistoryHandler.C_KIND)] +public sealed class NeutralValueHistoryHandler : EditorHistoryHandler +{ + public const string C_KIND = "tests/neutral-values"; + private static readonly HashSet<(int slot, EditorHistoryDirection direction)> BLOCKED = []; + private static readonly Dictionary VALUES = []; + + public static EditorHistoryChange CreateChange( + int slot, + int before, + int after, + string? mergeKey = null + ) { + var bytes = new byte[sizeof(int) * 3]; + BitConverter.GetBytes(slot).CopyTo(bytes, 0); + BitConverter.GetBytes(before).CopyTo(bytes, sizeof(int)); + BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int) * 2); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes), mergeKey); + } + + public static int GetValue(int slot) => VALUES.TryGetValue(slot, out int value) ? value : 0; + + public static void SetValue( + int slot, + int value + ) => VALUES[slot] = value; + + public static void Block( + int slot, + EditorHistoryDirection direction + ) => BLOCKED.Add((slot, direction)); + + public static void Unblock( + int slot, + EditorHistoryDirection direction + ) => BLOCKED.Remove((slot, direction)); + + public static void Reset() + { + BLOCKED.Clear(); + VALUES.Clear(); + } + + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) => change.payload.length >= sizeof(int) * 3 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] bytes = change.payload.ReadBytes(); + int slot = BitConverter.ToInt32(bytes, 0); + if (BLOCKED.Contains((slot, direction))) + { + return EditorHistoryResult.Failure($"Slot {slot} is blocked for {direction}."); + } + int offset = direction == EditorHistoryDirection.Undo ? sizeof(int) : sizeof(int) * 2; + VALUES[slot] = BitConverter.ToInt32(bytes, offset); + return EditorHistoryResult.Success(); + } + + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) { + byte[] olderBytes = older.payload.ReadBytes(); + byte[] newerBytes = newer.payload.ReadBytes(); + int slot = BitConverter.ToInt32(olderBytes, 0); + if (slot != BitConverter.ToInt32(newerBytes, 0)) + { + merged = null; + return false; + } + + merged = CreateChange( + slot, + BitConverter.ToInt32(olderBytes, sizeof(int)), + BitConverter.ToInt32(newerBytes, sizeof(int) * 2), + older.mergeKey + ); + return true; + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs new file mode 100644 index 000000000..257102391 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs @@ -0,0 +1,17 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("71cc27da-2c47-47f2-a037-c9bc29615358")] +[AllowMultipleComponent] +internal sealed class RestoreCleanupFailureComponent : GameBehavior +{ + [SerializableProperty] + public int value { get; set; } = 5; + + [OnSerializableRestored] + private void OnRestored() => throw new InvalidOperationException("Injected restore callback failure."); +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs new file mode 100644 index 000000000..07bc9c94c --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs @@ -0,0 +1,25 @@ +using Inno.Editor.Core; +using Inno.Editor.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[EditorModule("tests.scene-history-probe", order: 220)] +public sealed class SceneHistoryProbe : EditorModule +{ + public SceneHistoryProbe( + SceneEdits sceneEdits, + IEditorSceneWorkspace workspace + ) { + edits = sceneEdits; + documents = workspace; + } + + public static SceneEdits? edits { get; private set; } + public static IEditorSceneWorkspace? documents { get; private set; } + + public static void Reset() + { + edits = null; + documents = null; + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs index f544b02d9..e7f57070c 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs @@ -1,20 +1,20 @@ using System; +using Xunit; using Inno.Core.Identity; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; +using Inno.Core.Mathematics; using Inno.Scene; using Inno.Scene.Components; -using Xunit; namespace Inno.Editor.Interactions.Tests; + public sealed partial class SceneHistoryTests { [Fact] public void BatchPropertyEditPreservesIndependentBeforeValuesInOneUndo() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").AddComponent(); - var second = scene.CreateObject("Second").AddComponent(); + HistoryComponent first = scene.CreateObject("First").AddComponent(); + HistoryComponent second = scene.CreateObject("Second").AddComponent(); first.value = 12; second.value = 34; Assert.False(m_edits.HaveSamePropertyValues([first, second], "value")); @@ -34,26 +34,42 @@ public void BatchPropertyEditPreservesIndependentBeforeValuesInOneUndo() public void BatchAxisEditPreservesUneditedComponentsIncludingEqualPrimarySamples() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").transform; - var second = scene.CreateObject("Second").transform; + Transform first = scene.CreateObject("First").transform; + Transform second = scene.CreateObject("Second").transform; first.localPosition = new(1, 2, 3); second.localPosition = new(4, 5, 6); - Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => first.localPosition = new(9, 2, 3), "Edit X", componentName: "x")); - Assert.Equal(new Inno.Core.Mathematics.Vector3(9, 5, 6), second.localPosition); + Assert.True( + m_edits.ChangeProperties( + [first, second], + "localPosition", + () => first.localPosition = new(9, 2, 3), + "Edit X", + componentName: "x" + ) + ); + Assert.Equal(new Vector3(9, 5, 6), second.localPosition); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal(new Inno.Core.Mathematics.Vector3(4, 5, 6), second.localPosition); - Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => { }, "Use Primary X", componentName: "x")); - Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 5, 6), second.localPosition); - Assert.Throws(() => m_edits.ChangeProperties([first, second], "localPosition", () => first.localPosition = default, "Rejected Component", componentName: "notAComponent")); - Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 2, 3), first.localPosition); + Assert.Equal(new Vector3(4, 5, 6), second.localPosition); + Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => {}, "Use Primary X", componentName: "x")); + Assert.Equal(new Vector3(1, 5, 6), second.localPosition); + Assert.Throws( + () => m_edits.ChangeProperties( + [first, second], + "localPosition", + () => first.localPosition = default, + "Rejected Component", + componentName: "notAComponent" + ) + ); + Assert.Equal(new Vector3(1, 2, 3), first.localPosition); } [Fact] public void LaterBatchSetterFailureRestoresAllEarlierTargets() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").AddComponent(); - var second = scene.CreateObject("Second").AddComponent(); + BatchValidationComponent first = scene.CreateObject("First").AddComponent(); + BatchValidationComponent second = scene.CreateObject("Second").AddComponent(); first.value = 12; second.value = 34; second.rejectAnswer = true; @@ -71,20 +87,20 @@ public void BatchDeleteNormalizesSelectedAncestorsAndRestoresEverySubtree() GameObject child = scene.CreateObject("Child"); GameObject other = scene.CreateObject("Other"); child.transform.SetParent(root.transform); - Guid rootId = root.identity.persistentId; - Guid childId = child.identity.persistentId; - Guid otherId = other.identity.persistentId; + Guid rootID = root.identity.persistentID; + Guid childID = child.identity.persistentID; + Guid otherID = other.identity.persistentID; m_edits.DeleteGameObjects([child, root, other]); - Assert.Null(IdentityAllocator.current.Get(rootId)); - Assert.Null(IdentityAllocator.current.Get(childId)); - Assert.Null(IdentityAllocator.current.Get(otherId)); + Assert.Null(IdentityAllocator.current.Get(rootID)); + Assert.Null(IdentityAllocator.current.Get(childID)); + Assert.Null(IdentityAllocator.current.Get(otherID)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - GameObject restoredRoot = Assert.IsType(IdentityAllocator.current.Get(rootId)); - GameObject restoredChild = Assert.IsType(IdentityAllocator.current.Get(childId)); + GameObject restoredRoot = Assert.IsType(IdentityAllocator.current.Get(rootID)); + GameObject restoredChild = Assert.IsType(IdentityAllocator.current.Get(childID)); Assert.Same(restoredRoot.transform, restoredChild.transform.parent); - Assert.NotNull(IdentityAllocator.current.Get(otherId)); + Assert.NotNull(IdentityAllocator.current.Get(otherID)); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Null(IdentityAllocator.current.Get(rootId)); + Assert.Null(IdentityAllocator.current.Get(rootID)); } [Fact] @@ -112,20 +128,3 @@ public void BatchMovePreservesRootOrderAndRestoresIndependentPlacements() Assert.Same(destination.transform, first.transform.parent); } } - -[StableTypeId("9ea6d04d-4ed3-48f3-ac3a-b09372a575ab")] -internal sealed class BatchValidationComponent : GameComponent -{ - [SerializableProperty] - public int value { get; set; } - - [SerializableProperty] - public bool rejectAnswer { get; set; } - - [OnSerializableRestored] - private void Validate() - { - if (rejectAnswer && value == 42) - throw new InvalidOperationException("The current owner rejected this batch value."); - } -} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs index fa569eba9..fabd9c2cf 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs @@ -1,26 +1,27 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; -using System.Linq; using System.Runtime.CompilerServices; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; using Inno.Core.Identity; -using Inno.Extensibility.Types; -using Inno.Core.Serialization; +using Inno.Core.Input; +using Inno.Core.Logging; +using Inno.Core.Mathematics; using Inno.Editor.Core; using Inno.Editor.Scene; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; -using Xunit; namespace Inno.Editor.Interactions.Tests; + public sealed partial class SceneHistoryTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoSceneHistoryTests", Guid.NewGuid().ToString("N")); @@ -31,6 +32,7 @@ public sealed partial class SceneHistoryTests : IDisposable private readonly EditorInteractionRuntime m_runtime; private readonly SceneEdits m_edits; private readonly EditorReloadCoordinator m_reloads = new(); + public SceneHistoryTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); @@ -40,7 +42,17 @@ public SceneHistoryTests() new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource() ).Build(); - m_session = m_host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, applicationId = "inno.tests.scene-history", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_projectRoot, "Library", "PersistentData", "inno.tests.scene-history"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread }); + m_session = m_host.CreateSession( + new RuntimeSessionOptions + { + kind = RuntimeSessionKind.Edit, + applicationID = "inno.tests.scene-history", + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(m_projectRoot, "Library", "PersistentData", "inno.tests.scene-history"), "Logs") + ), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread + } + ); m_executionScope = m_session.EnterExecutionScope(); m_assets = new AssetPipeline( m_host.modules, @@ -49,10 +61,13 @@ public SceneHistoryTests() new IdentityAllocator(), m_host.diagnostics, m_host.logs, - AssetPipelineOptions.Create(Path.Combine(m_projectRoot, "Assets"), Path.Combine(m_projectRoot, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_projectRoot, "Assets"), + Path.Combine(m_projectRoot, "Library") + )with { enableFileSystemWatcher = false } ); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_host.types, m_host.logs, [m_host.types, m_host.serialization, m_session, m_assets, m_reloads] @@ -70,7 +85,9 @@ public void Dispose() m_session.Dispose(); m_host.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -78,19 +95,27 @@ public void PropertyUndoRestoresOnlyThePropertyOnTheExistingSceneGraph() { GameScene scene = CreateScene(); GameObject gameObject = scene.CreateObject("Object"); - var component = gameObject.AddComponent(); + HistoryComponent component = gameObject.AddComponent(); component.value = 10; - Guid sceneId = scene.identity.persistentId; - Guid objectId = gameObject.identity.persistentId; - Guid componentId = component.identity.persistentId; - Assert.True(m_edits.ChangeProperty(component, nameof(HistoryComponent.value), () => component.value = 25, "Change Value", "tests:component-value")); + Guid sceneID = scene.identity.persistentID; + Guid objectID = gameObject.identity.persistentID; + Guid componentID = component.identity.persistentID; + Assert.True( + m_edits.ChangeProperty( + component, + nameof(HistoryComponent.value), + () => component.value = 25, + "Change Value", + "tests:component-value" + ) + ); Assert.Equal(25, component.value); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); Assert.Equal(10, component.value); - Assert.Same(scene, IdentityAllocator.current.Get(sceneId)); - Assert.Same(gameObject, IdentityAllocator.current.Get(objectId)); - Assert.Same(component, IdentityAllocator.current.Get(componentId)); + Assert.Same(scene, IdentityAllocator.current.Get(sceneID)); + Assert.Same(gameObject, IdentityAllocator.current.Get(objectID)); + Assert.Same(component, IdentityAllocator.current.Get(componentID)); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Equal(25, component.value); } @@ -98,10 +123,17 @@ public void PropertyUndoRestoresOnlyThePropertyOnTheExistingSceneGraph() [Fact] public void PropertyUndoRestoresEverySiblingChangedByThePrimarySetter() { - var component = CreateScene().CreateObject("Coupled").AddComponent(); + CoupledHistoryComponent component = CreateScene().CreateObject("Coupled").AddComponent(); Assert.True(component.primary); Assert.Equal(CoupledHistoryMode.Base, component.mode); - Assert.True(m_edits.ChangeProperty(component, nameof(CoupledHistoryComponent.mode), () => component.mode = CoupledHistoryMode.Overlay, "Change Coupled Mode")); + Assert.True( + m_edits.ChangeProperty( + component, + nameof(CoupledHistoryComponent.mode), + () => component.mode = CoupledHistoryMode.Overlay, + "Change Coupled Mode" + ) + ); Assert.Equal(CoupledHistoryMode.Overlay, component.mode); Assert.False(component.primary); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); @@ -119,22 +151,38 @@ public void TransformManipulationTransactionUndoesAllLocalValuesAtomically() { GameObject gameObject = CreateScene().CreateObject("Manipulated"); Transform transform = gameObject.transform; - var position = new Inno.Core.Mathematics.Vector3(3f, -2f, 4f); - Inno.Core.Mathematics.Quaternion rotation = Inno.Core.Mathematics.Quaternion.CreateFromYawPitchRoll(0.2f, 0.3f, 0.4f); - var scale = new Inno.Core.Mathematics.Vector3(2f, 3f, 4f); + var position = new Vector3(3f, -2f, 4f); + Quaternion rotation = Quaternion.CreateFromYawPitchRoll(0.2f, 0.3f, 0.4f); + var scale = new Vector3(2f, 3f, 4f); using (EditorHistoryTransaction transaction = m_runtime.interactions.history.BeginTransaction("Move GameObject")) { - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localPosition), () => transform.localPosition = position, "Move GameObject")); - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localRotation), () => transform.localRotation = rotation, "Move GameObject")); - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localScale), () => transform.localScale = scale, "Move GameObject")); + Assert.True( + m_edits.ChangeProperty( + transform, + nameof(Transform.localPosition), + () => transform.localPosition = position, + "Move GameObject" + ) + ); + Assert.True( + m_edits.ChangeProperty( + transform, + nameof(Transform.localRotation), + () => transform.localRotation = rotation, + "Move GameObject" + ) + ); + Assert.True( + m_edits.ChangeProperty(transform, nameof(Transform.localScale), () => transform.localScale = scale, "Move GameObject") + ); transaction.Commit(); } Assert.Equal("Move GameObject", m_runtime.interactions.history.undoName); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal(Inno.Core.Mathematics.Vector3.ZERO, transform.localPosition); - Assert.Equal(Inno.Core.Mathematics.Quaternion.identity, transform.localRotation); - Assert.Equal(Inno.Core.Mathematics.Vector3.ONE, transform.localScale); + Assert.Equal(Vector3.ZERO, transform.localPosition); + Assert.Equal(Quaternion.identity, transform.localRotation); + Assert.Equal(Vector3.ONE, transform.localScale); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Equal(position, transform.localPosition); Assert.Equal(rotation, transform.localRotation); @@ -146,15 +194,22 @@ public void WorldPositionEditRestoresLocalStorageAndWorldResultThroughHistory() { GameScene scene = CreateScene(); Transform parent = scene.CreateObject("Parent").transform; - parent.localPosition = new Inno.Core.Mathematics.Vector3(3f, -2f, 4f); - parent.localScale = new Inno.Core.Mathematics.Vector3(2f, 3f, 4f); + parent.localPosition = new Vector3(3f, -2f, 4f); + parent.localScale = new Vector3(2f, 3f, 4f); Transform child = scene.CreateObject("Child").transform; child.SetParent(parent); - var beforeLocal = child.localPosition; - var beforeWorld = child.worldPosition; - var requestedWorld = new Inno.Core.Mathematics.Vector3(11f, 7f, 20f); - Assert.True(m_edits.ChangeProperty(child, nameof(Transform.localPosition), () => child.worldPosition = requestedWorld, "Edit World Position")); - var afterLocal = child.localPosition; + Vector3 beforeLocal = child.localPosition; + Vector3 beforeWorld = child.worldPosition; + var requestedWorld = new Vector3(11f, 7f, 20f); + Assert.True( + m_edits.ChangeProperty( + child, + nameof(Transform.localPosition), + () => child.worldPosition = requestedWorld, + "Edit World Position" + ) + ); + Vector3 afterLocal = child.localPosition; Assert.Equal(requestedWorld, child.worldPosition); Assert.NotEqual(beforeLocal, afterLocal); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -170,15 +225,15 @@ public void ComponentAddRemoveResetAndOrderPreserveLogicalIdentity() { GameScene scene = CreateScene(); GameObject gameObject = scene.CreateObject("Object"); - var first = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); - Guid firstId = first.identity.persistentId; + HistoryComponent first = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); + Guid firstID = first.identity.persistentID; Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Null(IdentityAllocator.current.Get(firstId)); + Assert.Null(IdentityAllocator.current.Get(firstID)); Assert.True(m_runtime.interactions.history.Redo().succeeded); - var restoredFirst = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistoryComponent restoredFirst = Assert.IsType(IdentityAllocator.current.Get(firstID)); Assert.NotSame(first, restoredFirst); Assert.Equal(7, restoredFirst.value); - var second = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); + HistoryComponent second = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); m_edits.SetComponentIndex(second, 1); Assert.Equal(1, gameObject.GetComponentIndex(second)); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -188,11 +243,11 @@ public void ComponentAddRemoveResetAndOrderPreserveLogicalIdentity() Assert.Equal(7, restoredFirst.value); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(99, restoredFirst.value); - Assert.Same(restoredFirst, IdentityAllocator.current.Get(firstId)); + Assert.Same(restoredFirst, IdentityAllocator.current.Get(firstID)); Assert.True(m_edits.RemoveComponent(restoredFirst)); - Assert.Null(IdentityAllocator.current.Get(firstId)); + Assert.Null(IdentityAllocator.current.Get(firstID)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - var restoredAgain = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistoryComponent restoredAgain = Assert.IsType(IdentityAllocator.current.Get(firstID)); Assert.Equal(99, restoredAgain.value); } @@ -206,16 +261,18 @@ public void RemovingComponentRestoresSerializedAssetReferences() Assert.True(m_assets.Import(assetPath)); TextAsset asset = m_assets.Load(assetPath); GameObject owner = CreateScene().CreateObject("Audio Source Owner"); - var component = owner.AddComponent(); + HistoryAssetReferenceComponent component = owner.AddComponent(); component.asset = asset; - Guid componentId = component.identity.persistentId; + Guid componentID = component.identity.persistentID; Assert.True(m_edits.RemoveComponent(component)); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); - var restored = Assert.IsType(IdentityAllocator.current.Get(componentId)); + HistoryAssetReferenceComponent restored = Assert.IsType( + IdentityAllocator.current.Get(componentID) + ); Assert.Same(asset, restored.asset); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Null(IdentityAllocator.current.Get(componentId)); + Assert.Null(IdentityAllocator.current.Get(componentID)); } [Fact] @@ -226,30 +283,30 @@ public void UndoMissingPluginComponentRecoversItsAssetAndKeepsTheRedoBranch() File.WriteAllText(sourcePath, "shared recovery content"); m_assets.Import(path); TextAsset asset = m_assets.Load(path); - Guid assetId = asset.identity.persistentId; + Guid assetID = asset.identity.persistentID; byte[] sourceIdentity = File.ReadAllBytes(sourcePath + ".imeta"); ReloadHistoryModule(install: true); GameObject owner = CreateScene().CreateObject("Recovery Owner"); - Guid componentId = AddAndRemoveReloadableComponent(owner, asset, rejectRestore: false); + Guid componentID = AddAndRemoveReloadableComponent(owner, asset, rejectRestore: false); File.Delete(sourcePath); m_assets.Rescan(); ReloadHistoryModule(install: false); m_host.modules.generations.Wait(); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); - MissingGameComponent missing = Assert.IsType(m_session.scenes.Find(componentId)); - int missingRuntimeId = Assert.IsType(missing.identity.runtimeId); - Assert.Equal(componentId, missing.identity.persistentId); + MissingGameComponent missing = Assert.IsType(m_session.scenes.Find(componentID)); + int missingRuntimeID = Assert.IsType(missing.identity.runtimeID); + Assert.Equal(componentID, missing.identity.persistentID); File.WriteAllText(sourcePath, "shared recovery content"); File.WriteAllBytes(sourcePath + ".imeta", sourceIdentity); m_assets.Rescan(); ReloadHistoryModule(install: true); - AssertRecoveredComponent(componentId, assetId, missingRuntimeId); + AssertRecoveredComponent(componentID, assetID, missingRuntimeID); EditorHistoryResult redo = m_runtime.interactions.history.Redo(); Assert.True(redo.succeeded, redo.message); - Assert.Null(m_session.scenes.Find(componentId)); + Assert.Null(m_session.scenes.Find(componentID)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - AssertRecoveredComponent(componentId, assetId, missingRuntimeId); + AssertRecoveredComponent(componentID, assetID, missingRuntimeID); ReloadHistoryModule(install: false); m_host.modules.generations.Wait(); } @@ -259,39 +316,21 @@ public void FailedMissingRecoveryPreservesPlaceholderAndHistoryForRetry() { ReloadHistoryModule(install: true); GameObject owner = CreateScene().CreateObject("Rejected Recovery"); - Guid componentId = AddAndRemoveReloadableComponent(owner, null, rejectRestore: true); + Guid componentID = AddAndRemoveReloadableComponent(owner, null, rejectRestore: true); ReloadHistoryModule(install: false); m_host.modules.generations.Wait(); Assert.True(m_runtime.interactions.history.Undo().succeeded); - MissingGameComponent missing = Assert.IsType(m_session.scenes.Find(componentId)); + MissingGameComponent missing = Assert.IsType(m_session.scenes.Find(componentID)); AssertRejectedHistoryModule(); m_host.modules.generations.Wait(); - Assert.Same(missing, m_session.scenes.Find(componentId)); + Assert.Same(missing, m_session.scenes.Find(componentID)); Assert.False(missing.missingType.IsValid(m_host.types)); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Null(m_session.scenes.Find(componentId)); + Assert.Null(m_session.scenes.Find(componentID)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.IsType(m_session.scenes.Find(componentId)); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private Guid AddAndRemoveReloadableComponent( - GameObject owner, - TextAsset? asset, - bool rejectRestore - ) { - Type type = new TypeRef(Guid.Parse("9f67d41e-082b-46d5-aaf0-dfc76c693182")).Resolve(m_host.types); - GameComponent component = owner.AddComponent(type); - type.GetProperty("value")!.SetValue(component, 73); - type.GetProperty("asset")!.SetValue(component, asset); - type.GetProperty("rejectRestore")!.SetValue(component, rejectRestore); - Guid id = component.identity.persistentId; - Assert.True(m_edits.RemoveComponent(component)); - return id; + Assert.IsType(m_session.scenes.Find(componentID)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private void AssertRejectedHistoryModule() => Assert.ThrowsAny(() => ReloadHistoryModule(install: true)); [Fact] public void MissingComponentEditsPreserveOriginalStateAndRecoveryDoesNotDirtySavedScene() { @@ -323,14 +362,6 @@ public void MissingComponentEditsPreserveOriginalStateAndRecoveryDoesNotDirtySav Assert.False(documents.IsDirty(scene)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private void AssertRecoveredValue(Guid id) - { - GameComponent component = Assert.IsAssignableFrom(m_session.scenes.Find(id)); - Assert.IsNotType(component); - Assert.Equal(73, component.GetType().GetProperty("value")!.GetValue(component)); - } - [Fact] public void MissingSystemUndoAndRemovalKeepItsLogicalTypeForRecovery() { @@ -351,56 +382,6 @@ public void MissingSystemUndoAndRemovalKeepItsLogicalTypeForRecovery() m_host.modules.generations.Wait(); } - [MethodImpl(MethodImplOptions.NoInlining)] - private Guid AddAndRemoveReloadableSystem(GameScene scene) - { - Type type = new TypeRef(Guid.Parse("92dd722d-f4ce-468d-8f6d-056cf5b1f79b")).Resolve(m_host.types); - GameSystem system = scene.AddSystem(type); - type.GetProperty("value")!.SetValue(system, 92); - Guid id = system.identity.persistentId; - Assert.True(m_edits.RemoveSystem(system)); - return id; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void AssertRecoveredSystem(Guid id) - { - GameSystem system = Assert.IsAssignableFrom(m_session.scenes.Find(id)); - Assert.IsNotType(system); - Assert.Equal(92, system.GetType().GetProperty("value")!.GetValue(system)); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void AssertRecoveredComponent( - Guid componentId, - Guid assetId, - int missingRuntimeId - ) { - GameComponent component = Assert.IsAssignableFrom(m_session.scenes.Find(componentId)); - Assert.IsNotType(component); - Assert.NotEqual(missingRuntimeId, component.identity.runtimeId); - Assert.Equal(73, component.GetType().GetProperty("value")!.GetValue(component)); - TextAsset asset = Assert.IsType(component.GetType().GetProperty("asset")!.GetValue(component)); - Assert.False(asset.isMissing); - Assert.Equal(assetId, asset.identity.persistentId); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void ReloadHistoryModule(bool install) - { - DotNetModuleSource request = CreateHistoryRequest(); - using AssemblyReloadSession reload = install ? m_host.modules.BeginReload([request]) : m_host.modules.BeginReload([], [request.moduleName]); - _ = m_reloads.Execute(reload); - } - - private DotNetModuleSource CreateHistoryRequest() => new() - { - moduleName = "SceneHistoryRecovery", - artifactRootDirectory = Path.Combine(m_projectRoot, "Library", "Modules"), - mainAssemblyPath = Path.Combine(AppContext.BaseDirectory, "Modules", "SceneReload", "Inno.Scene.Reload.TestModule.dll"), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; [Fact] public void ExternalResolversAreRestoredBeforeDomainPropertyCompensation() { @@ -408,7 +389,12 @@ public void ExternalResolversAreRestoredBeforeDomainPropertyCompensation() var participant = new ExternalRecoveryOrder(() => externalCandidateActive); using IDisposable registration = m_reloads.Register(participant); using AssemblyReloadSession reload = m_host.modules.BeginReload([CreateHistoryRequest()]); - Assert.Throws(() => m_reloads.Execute(reload, new ExternalContentChange(() => externalCandidateActive = true, () => externalCandidateActive = false))); + Assert.Throws( + () => m_reloads.Execute( + reload, + new ExternalContentChange(() => externalCandidateActive = true, () => externalCandidateActive = false) + ) + ); Assert.True(participant.restored); Assert.False(externalCandidateActive); reload.Dispose(); @@ -416,53 +402,6 @@ public void ExternalResolversAreRestoredBeforeDomainPropertyCompensation() Assert.Equal(GenerationState.Ready, m_host.modules.generations.state); } - private sealed class ExternalContentChange( - Action activate, - Action restore - ) : IGenerationChange - { - public void PrepareForActivation() - { - } - - public void Apply() => activate(); - public void Complete() - { - } - - public void RollbackStructure() - { - } - - public void RestorePreviousState() => restore(); - } - - private sealed class ExternalRecoveryOrder(Func externalCandidateActive) : IEditorReloadParticipant, IGenerationChange - { - internal bool restored { get; private set; } - - public IGenerationChange Capture(AssemblyReloadContext context) => this; - public void RefreshDiagnostics() - { - } - - public void PrepareForActivation() => Assert.False(externalCandidateActive()); - public void Apply() - { - Assert.True(externalCandidateActive()); - throw new InvalidOperationException("Rejected domain candidate."); - } - - public void RollbackStructure() => Assert.True(externalCandidateActive()); - public void RestorePreviousState() - { - Assert.False(externalCandidateActive()); - restored = true; - } - - public void Complete() => Assert.Fail("Failed candidate cannot commit."); - } - [Fact] public void RemovingAnElementAndSubtreeRestoresExternalSceneReferences() { @@ -470,30 +409,30 @@ public void RemovingAnElementAndSubtreeRestoresExternalSceneReferences() GameObject targetObject = scene.CreateObject("Target"); GameObject targetChild = scene.CreateObject("Child"); targetChild.transform.SetParent(targetObject.transform); - var targetComponent = targetChild.AddComponent(); + HistoryComponent targetComponent = targetChild.AddComponent(); targetComponent.value = 41; GameObject referenceObject = scene.CreateObject("References"); - var references = referenceObject.AddComponent(); + HistoryReferenceComponent references = referenceObject.AddComponent(); references.targetComponent = targetComponent; references.targetObject = targetChild; - Guid componentId = targetComponent.identity.persistentId; - Guid rootId = targetObject.identity.persistentId; - Guid childId = targetChild.identity.persistentId; + Guid componentID = targetComponent.identity.persistentID; + Guid rootID = targetObject.identity.persistentID; + Guid childID = targetChild.identity.persistentID; Assert.True(m_edits.RemoveComponent(targetComponent)); EditorHistoryResult restoreComponentResult = m_runtime.interactions.history.Undo(); Assert.True(restoreComponentResult.succeeded, restoreComponentResult.message); - var restoredComponent = Assert.IsType(IdentityAllocator.current.Get(componentId)); + HistoryComponent restoredComponent = Assert.IsType(IdentityAllocator.current.Get(componentID)); Assert.Same(restoredComponent, references.targetComponent); Assert.Equal(41, restoredComponent.value); Assert.True(m_edits.DeleteGameObject(targetObject)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - GameObject restoredRoot = Assert.IsType(IdentityAllocator.current.Get(rootId)); - GameObject restoredChild = Assert.IsType(IdentityAllocator.current.Get(childId)); + GameObject restoredRoot = Assert.IsType(IdentityAllocator.current.Get(rootID)); + GameObject restoredChild = Assert.IsType(IdentityAllocator.current.Get(childID)); Assert.Same(restoredRoot.transform, restoredChild.transform.parent); Assert.Same(restoredChild, references.targetObject); - Assert.Equal(componentId, references.targetComponent?.identity.persistentId); + Assert.Equal(componentID, references.targetComponent?.identity.persistentID); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Null(IdentityAllocator.current.Get(rootId)); + Assert.Null(IdentityAllocator.current.Get(rootID)); } [Fact] @@ -501,19 +440,39 @@ public void ElementRestoreRejectsAnotherLogicalTypesPayloadBeforeAttachingElemen { GameScene scene = CreateScene(); GameObject sourceObject = scene.CreateObject("Source"); - var source = sourceObject.AddComponent(); + HistoryReferenceComponent source = sourceObject.AddComponent(); byte[] incompatibleState = SceneElementSerialization.CaptureState(source, m_host.serialization, m_assets); GameObject owner = scene.CreateObject("Owner"); TypeRef componentType = m_host.types.GetTypeRef(typeof(HistoryComponent)); TypeRef systemType = m_host.types.GetTypeRef(typeof(HistorySystem)); - Guid componentId = Guid.NewGuid(); - Guid systemId = Guid.NewGuid(); - InvalidDataException componentFailure = Assert.Throws(() => SceneElementSerialization.RestoreComponent(owner, componentType, componentId, componentIndex: owner.GetComponents().Count, incompatibleState, m_host.serialization, m_assets)); - InvalidDataException systemFailure = Assert.Throws(() => SceneElementSerialization.RestoreSystem(scene, systemType, systemId, systemIndex: scene.GetSystems().Count, incompatibleState, m_host.serialization, m_assets)); + Guid componentID = Guid.NewGuid(); + Guid systemID = Guid.NewGuid(); + InvalidDataException componentFailure = Assert.Throws( + () => SceneElementSerialization.RestoreComponent( + owner, + componentType, + componentID, + componentIndex: owner.GetComponents().Count, + incompatibleState, + m_host.serialization, + m_assets + ) + ); + InvalidDataException systemFailure = Assert.Throws( + () => SceneElementSerialization.RestoreSystem( + scene, + systemType, + systemID, + systemIndex: scene.GetSystems().Count, + incompatibleState, + m_host.serialization, + m_assets + ) + ); Assert.Contains("type", componentFailure.Message, StringComparison.OrdinalIgnoreCase); Assert.Contains("type", systemFailure.Message, StringComparison.OrdinalIgnoreCase); - Assert.Null(IdentityAllocator.current.Get(componentId)); - Assert.Null(IdentityAllocator.current.Get(systemId)); + Assert.Null(IdentityAllocator.current.Get(componentID)); + Assert.Null(IdentityAllocator.current.Get(systemID)); } [Fact] @@ -521,13 +480,23 @@ public void ElementRestoreRemovesPartialElementWhenRestoreCallbackFails() { GameScene scene = CreateScene(); GameObject sourceOwner = scene.CreateObject("Source"); - var source = sourceOwner.AddComponent(); + RestoreCleanupFailureComponent source = sourceOwner.AddComponent(); byte[] state = SceneElementSerialization.CaptureState(source, m_host.serialization, m_assets); GameObject targetOwner = scene.CreateObject("Target"); TypeRef typeRef = m_host.types.GetTypeRef(typeof(RestoreCleanupFailureComponent)); - Guid persistentId = Guid.NewGuid(); - _ = Assert.ThrowsAny(() => SceneElementSerialization.RestoreComponent(targetOwner, typeRef, persistentId, componentIndex: targetOwner.GetComponents().Count, state, m_host.serialization, m_assets)); - Assert.Null(IdentityAllocator.current.Get(persistentId)); + Guid persistentID = Guid.NewGuid(); + _ = Assert.ThrowsAny( + () => SceneElementSerialization.RestoreComponent( + targetOwner, + typeRef, + persistentID, + componentIndex: targetOwner.GetComponents().Count, + state, + m_host.serialization, + m_assets + ) + ); + Assert.Null(IdentityAllocator.current.Get(persistentID)); } [Fact] @@ -540,13 +509,15 @@ public void FailedSubtreeRestoreRemovesEveryCreatedObjectDespiteDestructionCallb child.transform.SetParent(root.transform); _ = child.AddComponent(); byte[] state = SceneSubtreeSerialization.Capture(root, m_host.serialization, m_assets); - Guid rootId = root.identity.persistentId; - Guid childId = child.identity.persistentId; + Guid rootID = root.identity.persistentID; + Guid childID = child.identity.persistentID; Assert.True(scene.DestroyObject(root)); SubtreeRestoreFailureComponent.throwOnDestroy = true; try { - _ = Assert.ThrowsAny(() => SceneSubtreeSerialization.Restore(scene, state, m_host.serialization, m_assets, parent: null, siblingIndex: 0)); + _ = Assert.ThrowsAny( + () => SceneSubtreeSerialization.Restore(scene, state, m_host.serialization, m_assets, parent: null, siblingIndex: 0) + ); } finally { @@ -554,8 +525,8 @@ public void FailedSubtreeRestoreRemovesEveryCreatedObjectDespiteDestructionCallb } Assert.Equal([retained], scene.GetObjects()); - Assert.Null(IdentityAllocator.current.Get(rootId)); - Assert.Null(IdentityAllocator.current.Get(childId)); + Assert.Null(IdentityAllocator.current.Get(rootID)); + Assert.Null(IdentityAllocator.current.Get(childID)); } [Fact] @@ -567,8 +538,8 @@ public void FailedSubtreeHistoryRestoreReportsPreservedOnlyAfterExactSceneRecove GameObject child = scene.CreateObject("Child"); child.transform.SetParent(root.transform); _ = child.AddComponent(); - Guid rootId = root.identity.persistentId; - Guid childId = child.identity.persistentId; + Guid rootID = root.identity.persistentID; + Guid childID = child.identity.persistentID; Assert.True(m_edits.DeleteGameObject(root)); SubtreeRestoreFailureComponent.throwOnDestroy = true; EditorHistoryResult result; @@ -585,8 +556,8 @@ public void FailedSubtreeHistoryRestoreReportsPreservedOnlyAfterExactSceneRecove Assert.True(result.statePreserved, result.message); Assert.True(m_runtime.interactions.history.canUndo); Assert.Equal([retained], scene.GetObjects()); - Assert.Null(IdentityAllocator.current.Get(rootId)); - Assert.Null(IdentityAllocator.current.Get(childId)); + Assert.Null(IdentityAllocator.current.Get(rootID)); + Assert.Null(IdentityAllocator.current.Get(childID)); } [Fact] @@ -609,10 +580,10 @@ public void HierarchyUndoRestoresOnlyAffectedPlacements() public void SystemHistoryPreservesIdentityStateAndExplicitOrder() { GameScene scene = CreateScene(); - var first = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); - var second = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); + HistorySystem first = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); + HistorySystem second = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); first.value = 30; - Guid firstId = first.identity.persistentId; + Guid firstID = first.identity.persistentID; m_edits.SetSystemIndex(scene, second, 0); Assert.Equal(0, scene.GetSystemIndex(second)); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -623,7 +594,7 @@ public void SystemHistoryPreservesIdentityStateAndExplicitOrder() Assert.Equal(30, first.value); Assert.True(m_edits.RemoveSystem(first)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - var restored = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistorySystem restored = Assert.IsType(IdentityAllocator.current.Get(firstID)); Assert.Equal(30, restored.value); } @@ -632,19 +603,19 @@ public void SceneDocumentUndoRecreatesTheSameLogicalScene() { GameScene scene = m_edits.CreateScene(); scene.CreateObject("Persistent"); - Guid sceneId = scene.identity.persistentId; + Guid sceneID = scene.identity.persistentID; Assert.True(m_edits.CloseScene(scene)); Assert.Empty(SceneManager.loadedScenes); - Assert.Null(IdentityAllocator.current.Get(sceneId)); + Assert.Null(IdentityAllocator.current.Get(sceneID)); Assert.True(m_runtime.interactions.history.canUndo, m_runtime.interactions.history.undoUnavailableReason); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); - GameScene restored = Assert.IsType(IdentityAllocator.current.Get(sceneId)); + GameScene restored = Assert.IsType(IdentityAllocator.current.Get(sceneID)); Assert.True(restored.isLoaded); Assert.Equal("Persistent", Assert.Single(restored.GetObjects()).name); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Empty(SceneManager.loadedScenes); - Assert.Null(IdentityAllocator.current.Get(sceneId)); + Assert.Null(IdentityAllocator.current.Get(sceneID)); } [Fact] @@ -689,7 +660,7 @@ public void GameObjectTagUndoAndRedoRefreshSceneQueries() Assert.Equal("Player", gameObject.tag); Assert.Same(gameObject, scene.FindObjectWithTag("Player")); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal(GameObject.defaultTag, gameObject.tag); + Assert.Equal(GameObject.C_DEFAULT_TAG, gameObject.tag); Assert.Null(scene.FindObjectWithTag("Player")); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Equal("Player", gameObject.tag); @@ -713,125 +684,135 @@ public void GameObjectLayerUndoAndRedoRefreshSceneQueries() Assert.Same(gameObject, scene.FindObjectWithLayer(gameplay)); } - private GameScene CreateScene() => m_session.scenes.LoadNewSceneAdditive(); -} - -[EditorModule("tests.scene-history-probe", order: 220)] -public sealed class SceneHistoryProbe : EditorModule -{ - public SceneHistoryProbe( - SceneEdits sceneEdits, - IEditorSceneWorkspace workspace + [MethodImpl(MethodImplOptions.NoInlining)] + private Guid AddAndRemoveReloadableComponent( + GameObject owner, + TextAsset? asset, + bool rejectRestore ) { - edits = sceneEdits; - documents = workspace; + Type type = new TypeRef(Guid.Parse("9f67d41e-082b-46d5-aaf0-dfc76c693182")).Resolve(m_host.types); + GameComponent component = owner.AddComponent(type); + type.GetProperty("value")!.SetValue(component, 73); + type.GetProperty("asset")!.SetValue(component, asset); + type.GetProperty("rejectRestore")!.SetValue(component, rejectRestore); + Guid id = component.identity.persistentID; + Assert.True(m_edits.RemoveComponent(component)); + return id; } - public static SceneEdits? edits { get; private set; } - public static IEditorSceneWorkspace? documents { get; private set; } + [MethodImpl(MethodImplOptions.NoInlining)] + private void AssertRejectedHistoryModule() => Assert.ThrowsAny(() => ReloadHistoryModule(install: true)); - public static void Reset() + [MethodImpl(MethodImplOptions.NoInlining)] + private void AssertRecoveredValue(Guid id) { - edits = null; - documents = null; + GameComponent component = Assert.IsAssignableFrom(m_session.scenes.Find(id)); + Assert.IsNotType(component); + Assert.Equal(73, component.GetType().GetProperty("value")!.GetValue(component)); } -} - -[StableTypeId("267e77d8-1112-4cf9-a9f1-01d9a1e59bbc")] -[AllowMultipleComponent] -internal sealed class HistoryComponent : GameBehavior -{ - [SerializableProperty] - public int value { get; set; } - protected override void Reset() + [MethodImpl(MethodImplOptions.NoInlining)] + private Guid AddAndRemoveReloadableSystem(GameScene scene) { - value = 7; + Type type = new TypeRef(Guid.Parse("92dd722d-f4ce-468d-8f6d-056cf5b1f79b")).Resolve(m_host.types); + GameSystem system = scene.AddSystem(type); + type.GetProperty("value")!.SetValue(system, 92); + Guid id = system.identity.persistentID; + Assert.True(m_edits.RemoveSystem(system)); + return id; } -} -internal enum CoupledHistoryMode -{ - Base, - Overlay -} + [MethodImpl(MethodImplOptions.NoInlining)] + private void AssertRecoveredSystem(Guid id) + { + GameSystem system = Assert.IsAssignableFrom(m_session.scenes.Find(id)); + Assert.IsNotType(system); + Assert.Equal(92, system.GetType().GetProperty("value")!.GetValue(system)); + } -[StableTypeId("f25d91a5-df87-4ed6-a383-12a9071af66e")] -internal sealed class CoupledHistoryComponent : GameBehavior -{ - private bool m_primary = true; - private CoupledHistoryMode m_mode; - [SerializableProperty] - public bool primary { get => m_primary; set => m_primary = value && mode == CoupledHistoryMode.Base; } + [MethodImpl(MethodImplOptions.NoInlining)] + private void AssertRecoveredComponent( + Guid componentID, + Guid assetID, + int missingRuntimeID + ) { + GameComponent component = Assert.IsAssignableFrom(m_session.scenes.Find(componentID)); + Assert.IsNotType(component); + Assert.NotEqual(missingRuntimeID, component.identity.runtimeID); + Assert.Equal(73, component.GetType().GetProperty("value")!.GetValue(component)); + TextAsset asset = Assert.IsType(component.GetType().GetProperty("asset")!.GetValue(component)); + Assert.False(asset.isMissing); + Assert.Equal(assetID, asset.identity.persistentID); + } - [SerializableProperty] - public CoupledHistoryMode mode + [MethodImpl(MethodImplOptions.NoInlining)] + private void ReloadHistoryModule(bool install) { - get => m_mode; - set - { - m_mode = value; - if (value == CoupledHistoryMode.Overlay) - m_primary = false; - } + DotNetModuleSource request = CreateHistoryRequest(); + using AssemblyReloadSession reload = install + ? m_host.modules.BeginReload([request]) + : m_host.modules.BeginReload([], [request.moduleName]); + _ = m_reloads.Execute(reload); } -} -[StableTypeId("b269c970-8afe-46a0-a4a0-f44f737d059a")] -internal sealed class HistoryReferenceComponent : GameComponent -{ - [SerializableProperty] - public GameObject? targetObject { get; set; } + private DotNetModuleSource CreateHistoryRequest() + => new() + { + moduleName = "SceneHistoryRecovery", + artifactRootDirectory = Path.Combine(m_projectRoot, "Library", "Modules"), + mainAssemblyPath = Path.Combine(AppContext.BaseDirectory, "Modules", "SceneReload", "Inno.Scene.Reload.TestModule.dll"), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; - [SerializableProperty] - public GameComponent? targetComponent { get; set; } -} + private GameScene CreateScene() => m_session.scenes.LoadNewSceneAdditive(); -[StableTypeId("edbd3940-a94c-499e-8f03-b0e232a39b21")] -[AllowMultipleComponent] -internal sealed class HistoryAssetReferenceComponent : GameComponent -{ - [SerializableProperty] - public TextAsset? asset { get; set; } -} + private sealed class ExternalContentChange( + Action activate, + Action restore + ) : IGenerationChange + { + public void PrepareForActivation() {} -[StableTypeId("f00d5950-1136-4393-b246-644b69948f90")] -[AllowMultipleSystem] -internal sealed class HistorySystem : GameSystem -{ - [SerializableProperty] - public int value { get; set; } + public void Apply() => activate(); - protected override void Reset() - { - value = 11; + public void Complete() {} + + public void RollbackStructure() {} + + public void RestorePreviousState() => restore(); } -} -[StableTypeId("71cc27da-2c47-47f2-a037-c9bc29615358")] -[AllowMultipleComponent] -internal sealed class RestoreCleanupFailureComponent : GameBehavior -{ - [SerializableProperty] - public int value { get; set; } = 5; + private sealed class ExternalRecoveryOrder(Func externalCandidateActive) : IEditorReloadParticipant, IGenerationChange + { + public IGenerationChange Capture(AssemblyReloadContext context) => this; - [OnSerializableRestored] - private void OnRestored() => throw new InvalidOperationException("Injected restore callback failure."); -} + public void RefreshDiagnostics() {} -[StableTypeId("8503e97b-1845-4ab2-a116-1ece04934a4b")] -[AllowMultipleComponent] -internal sealed class SubtreeRestoreFailureComponent : GameBehavior -{ - internal static bool throwOnDestroy; - [SerializableProperty] - public int value { get; set; } = 5; + public void PrepareForActivation() => Assert.False(externalCandidateActive()); - [OnSerializableRestored] - private void OnRestored() => throw new InvalidOperationException("Injected subtree restore callback failure."); - protected override void OnDestroy() - { - if (throwOnDestroy) - throw new InvalidOperationException("Injected subtree destruction callback failure."); + public void Apply() + { + Assert.True(externalCandidateActive()); + throw new InvalidOperationException("Rejected domain candidate."); + } + + public void RollbackStructure() => Assert.True(externalCandidateActive()); + + public void RestorePreviousState() + { + Assert.False(externalCandidateActive()); + restored = true; + } + + public void Complete() => Assert.Fail("Failed candidate cannot commit."); + + internal bool restored { get; private set; } } } + +internal enum CoupledHistoryMode +{ + Base, + Overlay +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs new file mode 100644 index 000000000..8497ca25e --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs @@ -0,0 +1,27 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("8503e97b-1845-4ab2-a116-1ece04934a4b")] +[AllowMultipleComponent] +internal sealed class SubtreeRestoreFailureComponent : GameBehavior +{ + internal static bool throwOnDestroy; + + [SerializableProperty] + public int value { get; set; } = 5; + + protected override void OnDestroy() + { + if (throwOnDestroy) + { + throw new InvalidOperationException("Injected subtree destruction callback failure."); + } + } + + [OnSerializableRestored] + private void OnRestored() => throw new InvalidOperationException("Injected subtree restore callback failure."); +} diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs index 1fe85307f..ce9dbc77a 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Numerics; @@ -9,12 +10,13 @@ using System.Runtime.InteropServices; using System.Text.Json; using BGCS.Runtime; +using Xunit; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Scene; using Inno.Scene.Components; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; using NativeVector = Inno.Native.ImGui.ImVec2C; using SceneVector = Inno.Core.Mathematics.Vector3; @@ -31,17 +33,26 @@ public sealed partial class LargePanelPerformanceTests [Trait("Acceptance", "Performance")] public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scenario) { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); bool hierarchy = scenario.StartsWith("hierarchy", StringComparison.Ordinal); GameScene? scene = hierarchy ? LoadInteractionHierarchy(host) : null; if (!hierarchy) { string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); Assert.Equal(10_000, Directory.EnumerateDirectories(Path.Combine(host.projectRoot, "Assets"), "Folder *").Count()); } @@ -54,10 +65,12 @@ public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scen SceneVector initial = scene?.GetObjects()[0].transform.localPosition ?? default; Transform? transform = scene?.GetObjects()[0].transform; using EditorEditGesture? gesture = scenario == "hierarchy-edit" - ? new EditorEditGesture(host.runtime.interactions.history, "Measured continuous edit") - : null; + ? new EditorEditGesture(host.runtime.interactions.history, "Measured continuous edit") + : null; if (scenario == "assets-search") + { FocusAssetSearch(host, panel); + } Action operation = scenario switch { "assets-search" => Search, @@ -75,7 +88,9 @@ public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scen Assert.Equal((float)edits, transform.localPosition.x); } else if (scenario.EndsWith("scroll", StringComparison.Ordinal)) + { Assert.True(maximumScroll > 0f, "Actual wheel input never moved the visible list."); + } void Scroll() { @@ -109,12 +124,84 @@ void Search() void Edit() { int value = ++edits; - Assert.True(host.edits.ChangeProperty(transform!, nameof(Transform.localPosition), - () => transform!.localPosition = new(value, 0f, 0f), "Measured continuous edit", gesture!.mergeKey)); + Assert.True( + host.edits.ChangeProperty( + transform!, + nameof(Transform.localPosition), + () => transform!.localPosition = new(value, 0f, 0f), + "Measured continuous edit", + gesture!.mergeKey + ) + ); host.native.DrawPanel(panel); } } + private void MeasureInteraction( + string scenario, + Action operation + ) { + for (int warmup = 0; warmup < 5; warmup++) + { + operation(); + } + int repetitions = int.Parse( + Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS") ?? "5", + CultureInfo.InvariantCulture + ); + Assert.InRange(repetitions, 1, 5); + using Process process = Process.GetCurrentProcess(); + List samples = []; + for (int repetition = 0; repetition < repetitions; repetition++) + { + var milliseconds = new double[10]; + long before = GC.GetAllocatedBytesForCurrentThread(); + long totalBefore = GC.GetTotalAllocatedBytes(precise: true); + TimeSpan cpuBefore = process.TotalProcessorTime; + int gen0 = GC.CollectionCount(0); + int gen1 = GC.CollectionCount(1); + int gen2 = GC.CollectionCount(2); + for (int frame = 0; frame < milliseconds.Length; frame++) + { + long started = Stopwatch.GetTimestamp(); + operation(); + milliseconds[frame] = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + } + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + double[] sorted = milliseconds.Order().ToArray(); + samples.Add(new + { + repetition, + milliseconds, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, + totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBefore, + cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, + gen0Collections = GC.CollectionCount(0) - gen0, + gen1Collections = GC.CollectionCount(1) - gen1, + gen2Collections = GC.CollectionCount(2) - gen2 + }); + } + output.WriteLine( + JsonSerializer.Serialize(new + { + workload = scenario, + samples, + configuration = typeof(LargePanelPerformanceTests) + .Assembly + .GetCustomAttribute() + ?.Configuration, + viewport = "1000x800", + warmupOperations = 5, + measuredOperationsPerRepetition = 10, + nativeFramesPerOperation = scenario == "assets-search" ? 4 : 1, + consumer = scenario == "hierarchy-edit" ? "continuous-domain-gesture-and-actual-hierarchy-draw" : "actual-native-input-and-panel-draw", + sharedInput = InputDirectory(scenario.StartsWith("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets") + }) + ); + } + private static GameScene LoadInteractionHierarchy(NativeProjectPanelHost host) { string? input = InputDirectory("hierarchy"); @@ -126,7 +213,9 @@ private static GameScene LoadInteractionHierarchy(NativeProjectPanelHost host) } GameScene scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) + { _ = scene.CreateObject("Object " + index.ToString("D5")); + } _ = host.workspace.Save(scene, string.Empty); return scene; } @@ -148,7 +237,9 @@ EditorPanelExtension panel host.native.DrawPanel(panel); ImGuiNativeContext* context = NativeGui.Raw.GetCurrentContext(); if (context->InputTextState.ID != 0 && context->ActiveId == context->InputTextState.ID) + { return; + } } throw new InvalidOperationException("Ordinary pointer input did not focus the existing asset search field."); } @@ -161,57 +252,10 @@ EditorPanelExtension panel ImGuiWindow* window = context->Windows.Data[index]; string? name = Marshal.PtrToStringUTF8((nint)window->Name); if (window->Active != 0 && name?.Contains(fragment, StringComparison.Ordinal) == true) - return window; - } - throw new InvalidOperationException("The drawn native input owner is absent: " + fragment); - } - - private void MeasureInteraction( - string scenario, - Action operation - ) { - for (int warmup = 0; warmup < 5; warmup++) - operation(); - int repetitions = int.Parse(Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS") ?? "5", - System.Globalization.CultureInfo.InvariantCulture); - Assert.InRange(repetitions, 1, 5); - using Process process = Process.GetCurrentProcess(); - var samples = new List(); - for (int repetition = 0; repetition < repetitions; repetition++) - { - var milliseconds = new double[10]; - long before = GC.GetAllocatedBytesForCurrentThread(); - long totalBefore = GC.GetTotalAllocatedBytes(precise: true); - TimeSpan cpuBefore = process.TotalProcessorTime; - int gen0 = GC.CollectionCount(0); - int gen1 = GC.CollectionCount(1); - int gen2 = GC.CollectionCount(2); - for (int frame = 0; frame < milliseconds.Length; frame++) { - long started = Stopwatch.GetTimestamp(); - operation(); - milliseconds[frame] = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + return window; } - long allocated = GC.GetAllocatedBytesForCurrentThread() - before; - double[] sorted = milliseconds.Order().ToArray(); - samples.Add(new - { - repetition, milliseconds, median = (sorted[4] + sorted[5]) / 2, p95 = sorted[9], allocatedBytes = allocated, - totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBefore, - cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, - gen0Collections = GC.CollectionCount(0) - gen0, - gen1Collections = GC.CollectionCount(1) - gen1, - gen2Collections = GC.CollectionCount(2) - gen2 - }); } - output.WriteLine(JsonSerializer.Serialize(new - { - workload = scenario, samples, - configuration = typeof(LargePanelPerformanceTests).Assembly.GetCustomAttribute()?.Configuration, - viewport = "1000x800", warmupOperations = 5, measuredOperationsPerRepetition = 10, - nativeFramesPerOperation = scenario == "assets-search" ? 4 : 1, - consumer = scenario == "hierarchy-edit" ? "continuous-domain-gesture-and-actual-hierarchy-draw" : "actual-native-input-and-panel-draw", - sharedInput = InputDirectory(scenario.StartsWith("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets") - })); + throw new InvalidOperationException("The drawn native input owner is absent: " + fragment); } } diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs index 23fdf7cde..6cfe11b17 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs @@ -1,6 +1,7 @@ using System; using System.IO; using BGCS.Runtime; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; @@ -9,7 +10,7 @@ using Inno.Native.ImGui; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.Performance.Tests; @@ -24,24 +25,35 @@ public sealed partial class LargePanelPerformanceTests [Trait("Acceptance", "Workflows")] public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(string view) { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); bool hierarchy = view == "hierarchy"; GameScene? scene = hierarchy ? LoadInteractionHierarchy(host) : null; if (!hierarchy) { string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); } EditorPanelExtension panel = host.native.GetPanel(hierarchy ? "scene.hierarchy" : "asset.file-browser"); host.native.DrawPanel(panel); host.native.DrawPanel(panel); if (view == "grid") + { SelectGrid(host, panel); + } IdentityObject first = hierarchy ? scene!.GetObjects()[0] : Entry("Folder 00000"); IdentityObject last = hierarchy ? scene!.GetObjects()[^1] : Entry("Folder 09999"); string area = hierarchy ? "panel/scene.hierarchy" : "panel/asset.file-browser"; @@ -51,8 +63,11 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str { SetLargeQuery(host, panel, "Folder 00042"); ImGuiWindow* filtered = FindInteractionWindow(windowName); - NativeGui.Raw.AddMousePosEvent(NativeGui.Raw.GetIO(), filtered->Pos.X + filtered->Size.X - 60f, - filtered->Pos.Y + filtered->Size.Y * 0.7f); + NativeGui.Raw.AddMousePosEvent( + NativeGui.Raw.GetIO(), + filtered->Pos.X + filtered->Size.X - 60f, + filtered->Pos.Y + filtered->Size.Y * 0.7f + ); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 1); host.native.DrawPanel(panel); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 0); @@ -62,8 +77,11 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str NativePanelInput.Key(host.native, panel, ImGuiKey.End); Assert.Same(Entry("Folder 00042"), interactions.selection.selectedTarget); SetLargeQuery(host, panel, string.Empty); - NativeGui.Raw.AddMousePosEvent(NativeGui.Raw.GetIO(), filtered->Pos.X + filtered->Size.X * 0.4f, - filtered->Pos.Y + filtered->Size.Y * 0.7f); + NativeGui.Raw.AddMousePosEvent( + NativeGui.Raw.GetIO(), + filtered->Pos.X + filtered->Size.X * 0.4f, + filtered->Pos.Y + filtered->Size.Y * 0.7f + ); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 1); host.native.DrawPanel(panel); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 0); @@ -79,7 +97,7 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.Same(last, interactions.selection.selectedTarget); Assert.Equal(1, interactions.selection.count); string original = hierarchy ? ((GameObject)last).name : ((AssetFileEntry)last).name; - Guid? objectId = hierarchy ? ((GameObject)last).identity.persistentId : null; + Guid? objectID = hierarchy ? ((GameObject)last).identity.persistentID : null; Assert.True(interactions.For(area, last).Execute(hierarchy ? "hierarchy/rename" : "file-browser/rename")); host.native.DrawPanel(panel); host.native.DrawPanel(panel); @@ -100,18 +118,26 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str if (hierarchy) { Assert.Equal("Renamed last", ((GameObject)last).name); - Assert.Equal(objectId, ((GameObject)last).identity.persistentId); + Assert.Equal(objectID, ((GameObject)last).identity.persistentID); } else + { last = Entry("Renamed last"); + } Assert.True(interactions.history.Undo().succeeded); if (hierarchy) + { Assert.Equal(original, ((GameObject)last).name); + } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", original))); + } Assert.True(interactions.history.Redo().succeeded); if (!hierarchy) + { last = Entry("Renamed last"); + } interactions.SetSelection(last); RuntimeIdentity drag = interactions.For(area, last).BeginDrag(new EditorDragData(last, "Clipped source")); Assert.Equal(hierarchy ? ((GameObject)last).identity.runtimeIdentity : ((AssetFileEntry)last).identity.runtimeIdentity, drag); @@ -125,8 +151,8 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.True(interactions.For(area).TryGetActiveDragIdentity(out RuntimeIdentity retained)); Assert.Equal(drag, retained); EditorInteraction drop = hierarchy - ? interactions.For(area, new HierarchyObjectDropTarget((GameObject)first)) - : interactions.For(area, ((AssetFileEntry)first).assetPath.ToString()); + ? interactions.For(area, new HierarchyObjectDropTarget((GameObject)first)) + : interactions.For(area, ((AssetFileEntry)first).assetPath.ToString()); Assert.True(drop.QueryDrop(drag, EditorDropPlacement.Into).canDrop); Assert.True(drop.Drop(drag, EditorDropPlacement.Into).accepted); if (hierarchy) @@ -135,12 +161,18 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.Equal(10_000, scene!.GetObjects().Count); } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", "Folder 00000", "Renamed last"))); + } Assert.True(interactions.history.Undo().succeeded); if (hierarchy) + { Assert.Null(((GameObject)last).transform.parent); + } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", "Renamed last"))); + } Assert.True(interactions.history.Redo().succeeded); host.native.DrawPanel(panel); @@ -180,7 +212,9 @@ EditorPanelExtension panel host.native.DrawPanel(panel); host.runtime.SaveState(); if (File.ReadAllText(Path.Combine(host.projectRoot, "editor.ini")).Contains("viewMode=\"Grid\"", StringComparison.Ordinal)) + { return; + } } throw new InvalidOperationException("Ordinary pointer input did not select the actual Browser grid."); } diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs index e54283ebd..f107cc114 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs @@ -1,18 +1,21 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using System.Text.Json; using System.Threading; +using Xunit; +using Xunit.Abstractions; using Inno.Assets; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; -using Xunit.Abstractions; namespace Inno.Editor.Performance.Tests; @@ -22,23 +25,34 @@ public sealed partial class LargePanelPerformanceTests(ITestOutputHelper output) [Trait("Acceptance", "Performance")] public void DueDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); - Measure(host, null, "10000-hierarchy-dirty-inspections", - () => Assert.False(host.workspace.IsDirty(scene)), static () => Thread.Sleep(110)); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); + Measure( + host, + null, + "10000-hierarchy-dirty-inspections", + () => Assert.False(host.workspace.IsDirty(scene)), + static () => Thread.Sleep(110) + ); } [Fact] [Trait("Acceptance", "Performance")] public void ChangedDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); GameScene scene = LoadSavedHierarchy(host); GameObject value = scene.GetObjects()[0]; int revision = 0; Measure(host, null, "10000-hierarchy-dirty-edits", () => { - value.transform.localPosition = new Inno.Core.Mathematics.Vector3(++revision % 2 + 1, 0, 0); + value.transform.localPosition = new Vector3(++revision % 2 + 1, 0, 0); Assert.True(host.workspace.IsDirty(scene)); }, static () => Thread.Sleep(110), consumer: "complete-authoritative-dirty-inspection-after-each-owned-write"); } @@ -47,13 +61,23 @@ public void ChangedDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() [Trait("Acceptance", "Performance")] public void NeutralCaptureSeparatesSerializationFromSourceFreshness() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); - SerializationContext context = AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); + SerializationContext context = AssetSerializationContext.Create( + host.assets, + new AssetDependencyCollection(includeLastKnownPaths: false) + ); SerializationSnapshot? previous = null; - Measure(host, null, "10000-hierarchy-neutral-capture", + Measure( + host, + null, + "10000-hierarchy-neutral-capture", () => previous = host.serialization.CaptureSnapshot(scene, context, previous), - consumer: "complete-authoritative-serialization-capture"); + consumer: "complete-authoritative-serialization-capture" + ); Assert.NotNull(previous); } @@ -61,20 +85,30 @@ public void NeutralCaptureSeparatesSerializationFromSourceFreshness() [Trait("Acceptance", "Performance")] public void SourceFreshnessMeasuresTheActualSavedSceneLoadBoundary() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); Assert.True(host.workspace.TryGetSourcePath(scene, out string path)); SceneAsset asset = host.assets.Load(AssetPath.Project(path)); - Measure(host, null, "10000-hierarchy-source-freshness", - () => Assert.Same(asset, host.assets.Load(asset.identity.persistentId)), - consumer: "canonical-source-load-with-freshness-verification"); + Measure( + host, + null, + "10000-hierarchy-source-freshness", + () => Assert.Same(asset, host.assets.Load(asset.identity.persistentID)), + consumer: "canonical-source-load-with-freshness-verification" + ); } [Fact] [Trait("Acceptance", "Performance")] public void SceneMetadataReadsMeasureTheOwnedAttachmentBoundary() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); GameScene scene = LoadSavedHierarchy(host); IReadOnlyList objects = scene.GetObjects(); long checksum = 0; @@ -95,7 +129,10 @@ public void SceneMetadataReadsMeasureTheOwnedAttachmentBoundary() [Trait("Acceptance", "Performance")] public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); string? input = InputDirectory("hierarchy"); if (input is not null && Directory.Exists(input)) { @@ -105,9 +142,11 @@ public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() } else { - var scene = host.CreateScene(); + GameScene scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) + { _ = scene.CreateObject("Object " + index.ToString("D5")); + } if (input is not null) { Assert.Equal("Untitled Scene.iscene", host.workspace.Save(scene, string.Empty)); @@ -122,59 +161,32 @@ public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() [Trait("Acceptance", "Performance")] public void TenThousandAssetRowsProduceRepeatableFrameMeasurements() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); Assert.Equal(10_000, Directory.EnumerateDirectories(Path.Combine(host.projectRoot, "Assets"), "Folder *").Count()); if (input is not null && !Directory.Exists(input)) + { CopyDirectory(Path.Combine(host.projectRoot, "Assets"), input); + } EditorPanelExtension panel = host.native.GetPanel("asset.file-browser"); Measure(host, panel, "10000-asset-directory-rows"); } - private static Inno.Scene.GameScene LoadSavedHierarchy(NativeProjectPanelHost host) - { - string? input = InputDirectory("hierarchy"); - Inno.Scene.GameScene scene; - if (input is not null && Directory.Exists(input)) - { - CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); - host.assets.Rescan(); - scene = host.workspace.Open("Untitled Scene.iscene"); - } - else - { - scene = host.CreateScene(); - for (int index = 0; index < 10_000; index++) - _ = scene.CreateObject("Object " + index.ToString("D5")); - _ = host.workspace.Save(scene, string.Empty); - } - Assert.Equal(10_000, scene.GetObjects().Count); - return scene; - } - - private static string? InputDirectory(string workload) - { - string? owner = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_INPUT_ROOT"); - return owner is null ? null : Path.Combine(Path.GetFullPath(owner), workload); - } - - private static void CopyDirectory( - string source, - string destination - ) { - Directory.CreateDirectory(destination); - foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) - Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); - foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) - File.Copy(file, Path.Combine(destination, Path.GetRelativePath(source, file)), overwrite: false); - } - private void Measure( NativeProjectPanelHost host, EditorPanelExtension? panel, @@ -190,10 +202,10 @@ private void Measure( operation(); } string? requested = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS"); - int repetitions = requested is null ? 5 : int.Parse(requested, System.Globalization.CultureInfo.InvariantCulture); + int repetitions = requested is null ? 5 : int.Parse(requested, CultureInfo.InvariantCulture); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); - var samples = new List(); + List samples = []; for (int repetition = 0; repetition < repetitions; repetition++) { var milliseconds = new double[10]; @@ -214,8 +226,11 @@ private void Measure( double[] sorted = milliseconds.Order().ToArray(); samples.Add(new { - repetition, milliseconds, median = (sorted[4] + sorted[5]) / 2, - p95 = sorted[9], allocatedBytes = allocated, + repetition, + milliseconds, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBytesBefore, cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, gen0Collections = GC.CollectionCount(0) - collectionsBefore, @@ -223,20 +238,73 @@ private void Measure( gen2Collections = GC.CollectionCount(2) - gen2Before }); } - output.WriteLine(JsonSerializer.Serialize(new - { - workload, - configuration = typeof(LargePanelPerformanceTests).Assembly.GetCustomAttribute()?.Configuration - ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), - samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, - viewport = "1000x800", warmupFrames = 5, measuredFramesPerRepetition = 10, - sharedInput = InputDirectory(workload.Contains("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets"), - consumer = consumer ?? (prepare is null ? "native-command-offset-validation" : "complete-authoritative-dirty-inspection"), - preparationExcludedFromFrameTiming = prepare is not null, - supportsVertexOffsets = true - })); + output.WriteLine( + JsonSerializer.Serialize(new + { + workload, + configuration = typeof(LargePanelPerformanceTests) + .Assembly + .GetCustomAttribute() + ?.Configuration + ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), + samples, + framework = RuntimeInformation.FrameworkDescription, + viewport = "1000x800", + warmupFrames = 5, + measuredFramesPerRepetition = 10, + sharedInput = InputDirectory(workload.Contains("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets"), + consumer = consumer ?? (prepare is null ? "native-command-offset-validation" : "complete-authoritative-dirty-inspection"), + preparationExcludedFromFrameTiming = prepare is not null, + supportsVertexOffsets = true + }) + ); if (panel is not null) + { Assert.True(panel.isOpen); + } + } + + private static GameScene LoadSavedHierarchy(NativeProjectPanelHost host) + { + string? input = InputDirectory("hierarchy"); + GameScene scene; + if (input is not null && Directory.Exists(input)) + { + CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + host.assets.Rescan(); + scene = host.workspace.Open("Untitled Scene.iscene"); + } + else + { + scene = host.CreateScene(); + for (int index = 0; index < 10_000; index++) + { + _ = scene.CreateObject("Object " + index.ToString("D5")); + } + _ = host.workspace.Save(scene, string.Empty); + } + Assert.Equal(10_000, scene.GetObjects().Count); + return scene; + } + + private static string? InputDirectory(string workload) + { + string? owner = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_INPUT_ROOT"); + return owner is null ? null : Path.Combine(Path.GetFullPath(owner), workload); + } + + private static void CopyDirectory( + string source, + string destination + ) { + Directory.CreateDirectory(destination); + foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) + { + Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); + } + foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { + File.Copy(file, Path.Combine(destination, Path.GetRelativePath(source, file)), overwrite: false); + } } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs new file mode 100644 index 000000000..45c7d9ab8 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using Inno.Editor.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[EditorSettingPath("Editor/Atomic Editor/Value")] +public sealed class AtomicEditorSetting : EditorSetting +{ + public static readonly List> SNAPSHOTS = []; + public static bool stage; + public static bool throwOnDraw; + public static bool observe; + + public override EditorSettingObject defaultValue + { + get + { + var value = new EditorSettingObject(); + value.SetAsInt32("value", 0); + return value; + } + } + + protected override void OnDraw(EditorSettingObject setting) + { + if (throwOnDraw) + { + throw new InvalidOperationException("Controlled Settings drawer failure."); + } + if (observe + && (SNAPSHOTS.Count == 0 || !SNAPSHOTS[^1].TryGetTarget(out EditorSettingObject? last) || !ReferenceEquals(last, setting)) + ) { + SNAPSHOTS.Add(new WeakReference(setting)); + } + if (!stage) + { + return; + } + setting.SetAsInt32("value", 42); + stage = false; + } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs new file mode 100644 index 000000000..df804951a --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs @@ -0,0 +1,19 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[ProjectSettingPath("Project/Atomic Project/Value")] +public sealed class AtomicProjectEditor : ProjectSettingEditor +{ + public static bool stage; + + protected override void OnDraw(AtomicProjectSetting setting) + { + if (!stage) + { + return; + } + setting.value = 84; + stage = false; + } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs new file mode 100644 index 000000000..f17faca76 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs @@ -0,0 +1,12 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[GenerateSerializationConverter] +[ProjectSettingDefinition("tests.ui.atomic-settings")] +public sealed class AtomicProjectSetting : ISerializable +{ + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs index 42013e6f4..f443d7d84 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs @@ -1,14 +1,12 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System.Collections.Generic; using System.Numerics; - +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Native.ImGui; using NativeImGui = Inno.Native.ImGui.ImGui; - -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; @@ -27,10 +25,10 @@ public void DistinctEntryDomainsDoNotReuseImGuiCardIdentity() using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Console identity test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); - uint logCardId = GetCardId("occurrence/log/1"); - uint diagnosticCardId = GetCardId("occurrence/diagnostic/1"); + uint logCardID = GetCardID("occurrence/log/1"); + uint diagnosticCardID = GetCardID("occurrence/diagnostic/1"); - Assert.NotEqual(logCardId, diagnosticCardId); + Assert.NotEqual(logCardID, diagnosticCardID); NativeImGui.End(); NativeImGui.Render(); } @@ -56,7 +54,7 @@ public void CollapsedCardsUseOneUniformNativeItemSpacing() } } - private static uint GetCardId(string identity) + private static uint GetCardID(string identity) { NativeImGui.PushID(identity); uint result = NativeImGui.GetID("##ConsoleEntryCard"); @@ -77,18 +75,18 @@ private static void DrawCardFrame(bool assertSpacing) "occurrence/diagnostic/1", "occurrence/log/2" ]; - var bounds = new List<(Vector2 minimum, Vector2 maximum)>(); + List<(Vector2 minimum, Vector2 maximum)> bounds = []; for (int i = 0; i < identities.Length; i++) { NativeImGui.PushID(identities[i]); if (NativeImGui.BeginChild( - "##ConsoleEntryCard", - Vector2.Zero, - (int)(ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY), - (int)(ImGuiWindowFlags.NoScrollbar | - ImGuiWindowFlags.NoScrollWithMouse | - ImGuiWindowFlags.NoSavedSettings))) - { + "##ConsoleEntryCard", + Vector2.Zero, + (int)(ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY), + (int)(ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings) + )) { NativeImGui.TextUnformatted($"Entry {i}"); } NativeImGui.EndChild(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs index 399c94683..e6369534e 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs @@ -1,24 +1,28 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using BGCS.Runtime; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.ImGui; using Inno.Editor.Diagnostics; +using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; using ImGuiApi = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; @@ -40,17 +44,20 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; io->IniFilename = null; - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly) }); + using var modules = new ModuleHost( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly) } + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var logs = new LogRouter(); var diagnostics = new DiagnosticHub(); using IDisposable diagnosticScope = diagnostics.EnterScope(); - using var ui = new EditorUiSession(); + using var ui = new EditorUISession(); using var runtime = new EditorInteractionRuntime( - new EditorContext(root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, logs, - [new RejectedConsole()]); + [new RejectedConsole()] + ); runtime.Start(); EditorPanelExtension panel = Assert.Single(runtime.panels, value => value.id == "diagnostics.console"); panel.isOpen = true; @@ -58,7 +65,7 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() for (int frame = 0; frame < 2; frame++) { ImGuiApi.NewFrame(); - ImGuiApi.SetNextWindowSize(new(800f, 600f)); + ImGuiApi.SetNextWindowSize(new Vector2(800f, 600f)); using NativeStringLease title = Utf8Codec.EncodeNullTerminated("Failure parent", allowsNull: false); _ = ImGuiApi.Raw.Begin((sbyte*)title.pointer, null, 0); nint parent = (nint)ImGuiApi.Raw.GetCurrentWindow(); @@ -68,7 +75,7 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() Assert.False(panel.isOpen); } Assert.Equal(parent, (nint)ImGuiApi.Raw.GetCurrentWindow()); - Inno.Editor.ImGui.ImGui.Text("Following valid drawing"); + Gui.Text("Following valid drawing"); ImGuiApi.End(); ImGuiApi.Render(); } @@ -101,16 +108,18 @@ float scale ImGuiApi.Raw.GetIO()->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; ImGuiApi.Raw.GetIO()->Fonts->RendererHasTextures = 1; ImGuiApi.Raw.ScaleAllSizes(ImGuiApi.Raw.GetStyle(), scale); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var logs = new LogRouter(); var hub = new DiagnosticHub(); using var console = new EditorConsole(logs, hub, new InactivePlayMode()); console.Start(); - using var reporter = hub.CreateReporter(new("shader", "Rendering")); - using var ui = new EditorUiSession(); + using DiagnosticReporter reporter = hub.CreateReporter(new DiagnosticSource("shader", "Rendering")); + using var ui = new EditorUISession(); using var runtime = new EditorInteractionRuntime( - new EditorContext(root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, logs, [console] @@ -118,8 +127,16 @@ float scale runtime.Start(); logs.Flush(); console.Clear(); - if (diagnostic) reporter.Publish(new("BGFX_IR_GENERATION", "BGFX has no position builtin for stage Compute.", DiagnosticSeverity.Error)); - else logs.CreateLogger().Write(LogLevel.Error, "BGFX has no position builtin for stage Compute."); + if (diagnostic) + { + reporter.Publish( + new Diagnostic("BGFX_IR_GENERATION", "BGFX has no position builtin for stage Compute.", DiagnosticSeverity.Error) + ); + } + else + { + logs.CreateLogger().Write(LogLevel.Error, "BGFX has no position builtin for stage Compute."); + } logs.Flush(); EditorPanelExtension panel = Assert.Single(runtime.panels, value => value.id == "diagnostics.console"); panel.isOpen = true; @@ -127,8 +144,8 @@ void Draw(float width) { using IDisposable scope = ui.Enter(); ImGuiApi.NewFrame(); - ImGuiApi.SetNextWindowPos(new(0, 0)); - ImGuiApi.SetNextWindowSize(new(width, 700)); + ImGuiApi.SetNextWindowPos(new Vector2(0, 0)); + ImGuiApi.SetNextWindowSize(new Vector2(width, 700)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Console Layout", allowsNull: false); _ = ImGuiApi.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); Assert.True(panel.Draw(runtime.context)); @@ -136,42 +153,59 @@ void Draw(float width) ImGuiApi.Render(); Assert.Single(console.Capture().occurrences); } - Draw(960); Draw(960); + Draw(960); + Draw(960); ImGuiWindow* card = default; for (int i = 0; i < context->Windows.Size; i++) { ImGuiWindow* window = context->Windows.Data[i]; - if (Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) card = window; + if (Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + { + card = window; + } } - Assert.True(card != null); + Assert.True(card is not null); ImGuiTable* header = FindActiveTable(card, 3); - Assert.True(header != null); - Vector2 toggle = new(header->Columns.Data[0].WorkMinX + 6, header->RowPosY1 + ImGuiApi.GetFontSize() / 2); + Assert.True(header is not null); + var toggle = new Vector2(header->Columns.Data[0].WorkMinX + 6, header->RowPosY1 + ImGuiApi.GetFontSize() / 2); ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), toggle.X, toggle.Y); Draw(960); - Assert.True(context->HoveredId != 0, $"No toggle hovered: {toggle}; window {Marshal.PtrToStringUTF8((nint)context->HoveredWindow->Name)}"); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); Draw(960); + Assert.True( + context->HoveredId != 0, + $"No toggle hovered: {toggle}; window {Marshal.PtrToStringUTF8((nint)context->HoveredWindow->Name)}" + ); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); + Draw(960); Assert.True(context->ActiveId != 0, "Toggle did not activate."); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (false ? (byte)1 : (byte)0)); Draw(960); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (false ? (byte)1 : (byte)0)); + Draw(960); // Switching from fixed height to AutoResizeY uses a native measurement frame. Draw(960); foreach (float width in new[] { 960f, 500f, 260f, 140f, 960f }) { Draw(width); ImGuiTable* table = FindActiveTable(card, 2); - bool details = table != null && table->LastFrameActive == ImGuiApi.GetFrameCount(); + bool details = table is not null && table->LastFrameActive == ImGuiApi.GetFrameCount(); if (details) { - ImGuiTableColumn label = table->Columns.Data[0], value = table->Columns.Data[1]; + ImGuiTableColumn label = table->Columns.Data[0]; + ImGuiTableColumn value = table->Columns.Data[1]; Assert.True(label.WidthGiven >= ImGuiApi.CalcTextSize("Session:").X - 1); Assert.True(value.MinX > label.MinX + ImGuiApi.CalcTextSize("Source:").X); Assert.True(label.ClipRect.Max.X >= label.WorkMinX + ImGuiApi.CalcTextSize("Source:").X); } - if (width >= 500) Assert.True(details, $"Width {width}, details {details}, toggle {toggle}, card {card->Pos} / {card->Size}"); + if (width >= 500) + { + Assert.True(details, $"Width {width}, details {details}, toggle {toggle}, card {card->Pos} / {card->Size}"); + } if (width == 140) Assert.False(details); } } - finally { ImGuiApi.Raw.DestroyContext(context); Directory.Delete(root, true); } + finally + { + ImGuiApi.Raw.DestroyContext(context); + Directory.Delete(root, true); + } } private static ImGuiTable* FindActiveTable( @@ -183,7 +217,9 @@ int columns { ImGuiTable* table = &context->Tables.Buf.Data[index]; if (table->OuterWindow == window && table->ColumnsCount == columns && table->LastFrameActive == ImGuiApi.GetFrameCount()) + { return table; + } } return null; } @@ -192,20 +228,25 @@ private sealed class RejectedConsole : IEditorConsole { public int capacity { get; set; } public bool clearOnPlay { get; set; } + public EditorConsoleSnapshot Capture() => throw new InvalidOperationException("Snapshot source failed."); - public void Clear() { } + + public void Clear() {} } private sealed class InactivePlayMode : IEditorPlayMode { + private readonly EventDispatcher m_stateDispatcher = new(); + public EditorPlayModeState state => EditorPlayModeState.Editing; public bool isPlaying => false; public string? lastFailure => null; - public LogSessionId activeSessionId => LogSessionId.none; - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); + public LogSessionID activeSessionID => LogSessionID.none; + public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs index 3bb4a5b56..53f57df38 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs @@ -3,12 +3,13 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using BGCS.Runtime; +using Xunit; using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; @@ -26,17 +27,26 @@ public void ActualConsoleFiltersMessagesFilesSourcesAndLongUnicodeQueries( float height ) { using var host = new NativePanelHost(typeof(ConsoleSearchNativeTests).Assembly, "Inno.Editor.Panel.Logging"); - host.SetDisplayMetrics(new(width, height), density, zoom); + host.SetDisplayMetrics(new Vector2(width, height), density, zoom); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) + { logger.Write(LogLevel.Info, "Needle message"); + } logger.Write(LogLevel.Warn, "Unrelated message"); - string longMessage = new('x', 300); + var longMessage = new string('x', 300); logger.Write(LogLevel.Info, longMessage); host.logs.Flush(); - using var reporter = host.diagnostics.CreateReporter(new("search-source", "SOURCE-NAME")); - reporter.Publish(new("SEARCH_CODE", "A diagnostic", DiagnosticSeverity.Error, location: new DiagnosticLocation("Assets/漢字.shader", 42, 3))); + using DiagnosticReporter reporter = host.diagnostics.CreateReporter(new DiagnosticSource("search-source", "SOURCE-NAME")); + reporter.Publish( + new Diagnostic( + "SEARCH_CODE", + "A diagnostic", + DiagnosticSeverity.Error, + location: new DiagnosticLocation("Assets/漢字.shader", 42, 3) + ) + ); host.DrawPanel(panel); host.DrawPanel(panel); Assert.Equal(5, host.console.Capture().occurrences.Count); @@ -63,11 +73,13 @@ public void FilteredKeyboardTargetCopiesTheSameGroupAndClearReleasesIt( float height ) { using var host = new NativePanelHost(typeof(ConsoleSearchNativeTests).Assembly, "Inno.Editor.Panel.Logging"); - host.SetDisplayMetrics(new(width, height), density, zoom); + host.SetDisplayMetrics(new Vector2(width, height), density, zoom); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) + { logger.Write(LogLevel.Info, "Needle message"); + } logger.Write(LogLevel.Warn, "Other entry"); host.logs.Flush(); host.DrawPanel(panel); @@ -87,7 +99,10 @@ float height Assert.True(card->Size.Y > collapsedHeight + 1f); host.DrawPanel(panel, () => { - var context = host.runtime.interactions.For(host.runtime.interactions.focusedArea, host.runtime.interactions.focusedTarget); + EditorInteraction context = host.runtime.interactions.For( + host.runtime.interactions.focusedArea, + host.runtime.interactions.focusedTarget + ); Assert.True(context.Execute("console/copy-message")); Assert.Equal("Needle message", Marshal.PtrToStringUTF8((nint)NativeImGui.Raw.GetClipboardText())); Assert.True(context.Execute("console/copy-details")); @@ -145,8 +160,11 @@ private static int CountCards() for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { count++; + } } return count; } @@ -161,8 +179,10 @@ private static int CountCards() ImGuiWindow* window = context->Windows.Data[index]; string name = Marshal.PtrToStringUTF8((nint)window->Name) ?? string.Empty; if (window->Active != 0 && name.Contains(containing, StringComparison.Ordinal) - && (excluding is null || !name.Contains(excluding, StringComparison.Ordinal))) + && (excluding is null || !name.Contains(excluding, StringComparison.Ordinal)) + ) { return window; + } } throw new InvalidOperationException("The actual control window was not submitted: " + containing); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs index 7e6b44e38..b2b0e6f7c 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs @@ -1,11 +1,12 @@ using System; using System.Runtime.InteropServices; +using Xunit; +using Xunit.Abstractions; using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; -using Xunit.Abstractions; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -19,7 +20,7 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); logger.Write(LogLevel.Info, "Original context record"); host.logs.Flush(); @@ -30,8 +31,11 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { card = window; + } } Assert.True(card is not null); ImGuiIO* io = NativeGui.Raw.GetIO(); @@ -43,16 +47,22 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) host.DrawPanel(panel); Assert.True(context->OpenPopupStack.Size > 0); if (clear) + { host.console.Clear(); + } else { for (int index = 0; index < host.console.capacity; index++) + { logger.Write(LogLevel.Info, "Replacement context record " + index); + } host.logs.Flush(); } Assert.DoesNotContain(host.console.Capture().occurrences, static entry => entry.message == "Original context record"); for (int frame = 0; frame < 3; frame++) + { host.DrawPanel(panel); + } Assert.Equal(0, context->OpenPopupStack.Size); } @@ -61,7 +71,7 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); ImGuiIO* io = NativeGui.Raw.GetIO(); for (int iteration = 0; iteration < 100; iteration++) @@ -75,8 +85,11 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { card = window; + } } Assert.True(card is not null); NativeGui.Raw.AddMousePosEvent(io, card->Pos.X + 230f, card->Pos.Y + 12f); @@ -88,8 +101,10 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() Assert.True(context->OpenPopupStack.Size > 0); NativePanelInput.Key(host, panel, ImGuiKey.Escape); } - output.WriteLine("Context menus: 100; retained records: " + host.console.Capture().occurrences.Count - + "; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size); + output.WriteLine( + "Context menus: 100; retained records: " + host.console.Capture().occurrences.Count + + "; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size + ); Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 32); } @@ -98,24 +113,30 @@ public void TenThousandOccurrencesSubmitOnlyViewportCardsAndKeepKeyboardNavigati { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 10_000; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int index = 0; index < 10_000; index++) { logger.Write(LogLevel.Info, "Entry " + index.ToString("D5") + "\nDetails / 资源信息"); if (index % 128 == 0) + { host.logs.Flush(); + } } host.logs.Flush(); Assert.Equal(10_000, host.console.Capture().occurrences.Count); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); for (int frame = 0; frame < 4; frame++) + { host.DrawPanel(panel); + } Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 128); NativePanelInput.Focus(host, panel, "ConsoleRegion"); NativePanelInput.Key(host, panel, ImGuiKey.Home); NativePanelInput.Key(host, panel, ImGuiKey.Enter); for (int frame = 0; frame < 3; frame++) + { host.DrawPanel(panel); + } Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 128); } @@ -124,7 +145,7 @@ public void RetiredOccurrencesDoNotAccumulateNativeChildWindows() { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); for (int iteration = 0; iteration < 150; iteration++) { @@ -134,7 +155,9 @@ public void RetiredOccurrencesDoNotAccumulateNativeChildWindows() host.DrawPanel(panel); } Assert.Equal(16, host.console.Capture().occurrences.Count); - output.WriteLine("Retained records: 16; completed updates: 150; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size); + output.WriteLine( + "Retained records: 16; completed updates: 150; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size + ); Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 64); } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs index 63c001948..58cd746af 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs @@ -5,6 +5,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Text; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Input; using Inno.Core.Logging; @@ -15,7 +16,7 @@ using Inno.Extensibility.Types; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -31,24 +32,35 @@ public void StandardDockTreeLoadsAndResizesThroughThePresentationRuntime( float height ) { using var host = new NativePanelHost(typeof(DefaultLayoutNativeTests).Assembly); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(DefaultLayoutNativeTests).Assembly) }); + using var modules = new ModuleHost( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(DefaultLayoutNativeTests).Assembly) } + ); using var types = new TypeCatalog(modules, new EmptyTypeSource()); using var logs = new LogRouter(); - var context = new EditorContext(host.runtime.context.projectDirectory, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); + var context = new EditorContext( + host.runtime.context.projectDirectory, + new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl") + ); using var runtime = new ImGuiEditorRuntime(context, types, logs, []); ImGuiIO* io = NativeGui.Raw.GetIO(); io->ConfigFlags |= (int)ImGuiConfigFlags.DockingEnable; - io->DisplaySize = Unsafe.BitCast(new(1600f, 900f)); - byte[] layout = Encoding.UTF8.GetBytes(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")) + '\0'); + io->DisplaySize = Unsafe.BitCast(new Vector2(1600f, 900f)); + byte[] layout = Encoding.UTF8.GetBytes( + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")) + '\0' + ); fixed (byte* pointer = layout) + { NativeGui.Raw.LoadIniSettingsFromMemory((sbyte*)pointer, (ulong)(layout.Length - 1)); + } runtime.Start(); string[] titles = ["Scene", "Game", "File", "Hierarchy", "Inspector", "Shader Editor", "Console", "Stats"]; var rectangles = new Dictionary(); for (int frame = 0; frame < 12; frame++) { if (frame == 6) - io->DisplaySize = Unsafe.BitCast(new(width, height)); + { + io->DisplaySize = Unsafe.BitCast(new Vector2(width, height)); + } host.Frame(() => { runtime.Draw(); @@ -67,7 +79,7 @@ float height } }); } - foreach (var rectangle in rectangles.Values) + foreach ((Vector2 position, Vector2 size, uint dock) rectangle in rectangles.Values) { Assert.NotEqual(0u, rectangle.dock); Assert.True(rectangle.size.X > 0f && rectangle.size.Y > 0f); @@ -84,19 +96,23 @@ float height Assert.True(rectangles["Inspector"].position.X > rectangles["Hierarchy"].position.X); Assert.True(rectangles["Console"].position.Y > rectangles["Inspector"].position.Y); Assert.InRange(rectangles["File"].size.X / width, 0.43f, 0.49f); - Assert.InRange(rectangles["Hierarchy"].size.X / width, 0.25f, 0.30f); - Assert.InRange(rectangles["Inspector"].size.X / width, 0.25f, 0.30f); + Assert.InRange(rectangles["Hierarchy"].size.X / width, 0.25f, 0.3f); + Assert.InRange(rectangles["Inspector"].size.X / width, 0.25f, 0.3f); } private sealed class EmptyTypeSource : ITypeCatalogSource { public IReadOnlyList GetTypes(Assembly assembly) => []; + public TypeCatalogMetadata GetMetadata(Type type) => throw new NotSupportedException(); + public Type? ConstructGenericType( Type definition, IReadOnlyList arguments ) => throw new NotSupportedException(); + public bool CanCreateInstance(Type type) => false; + public object CreateInstance(Type type) => throw new NotSupportedException(); } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs new file mode 100644 index 000000000..2d4d70d2c --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs @@ -0,0 +1,19 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.PlayMode.Tests; + +[StableTypeID("942e794b-1c53-45a6-80e6-a641d76fdd09")] +[AllowMultipleComponent] +internal sealed class DirtyCaptureComponent : GameComponent +{ + [SerializableProperty] + public int number; + + [SerializableProperty] + public GameObject? target; + + [SerializableProperty] + public DirtyCaptureValue state { get; set; } = new(); +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs new file mode 100644 index 000000000..3215726b2 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs @@ -0,0 +1,8 @@ +namespace Inno.Editor.PlayMode.Tests; + +internal sealed class DirtyCaptureValue +{ + internal int value; + internal bool reject; + internal int reads; +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs new file mode 100644 index 000000000..b706e1493 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Editor.PlayMode.Tests; + +internal sealed class DirtyCaptureValueConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + DirtyCaptureValue value + ) { + value.reads++; + writer.Write("value", value.value); + if (value.reject) + { + throw new InvalidOperationException("The test-owned converter rejected capture."); + } + } + + public override DirtyCaptureValue Read(SerializationReader reader) => new() { value = reader.Read("value") }; +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs index 49da286f5..8c6466dab 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs @@ -1,11 +1,11 @@ +using System; using System.Numerics; - +using Xunit; using Inno.Adapter.Input; using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.ImGui; using Inno.Input; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -23,8 +23,8 @@ public void ConsumedMouseMovementStillUpdatesPointerBounds(bool pressed) Assert.Null(capture.Route(moved)); Event pointer = pressed - ? new MouseButtonPressedEvent(42, MouseButton.Left) - : new MouseScrolledEvent(42, 0f, 1f); + ? new MouseButtonPressedEvent(42, MouseButton.Left) + : new MouseScrolledEvent(42, 0f, 1f); Assert.Null(capture.Route(pointer)); Assert.NotNull(capture.Route(new KeyPressedEvent(42, KeyCode.A))); } @@ -60,7 +60,9 @@ bool consumed capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); Event exit = close ? new WindowCloseEvent(42) : new WindowFocusChangedEvent(42, false); if (consumed) + { exit.HandleInGlobal(); + } Assert.Null(capture.Route(exit)); Assert.Null(capture.Route(new KeyPressedEvent(42, KeyCode.A))); @@ -75,12 +77,16 @@ public void DispatcherRoutesInputOnlyAfterEditorConsumption(bool globalConsumpti { var dispatcher = new EventDispatcher(); using EventHub ui = dispatcher.CreateHub(100); - using System.IDisposable subscription = ui.Listen(evnt => + using IDisposable subscription = ui.Listen(evnt => { if (globalConsumption) + { evnt.HandleInGlobal(); + } else + { evnt.HandleInHub(); + } }); var capture = new EditorGameInputCapture(_ => 42u); capture.BeginFrame(); @@ -94,9 +100,13 @@ public void DispatcherRoutesInputOnlyAfterEditorConsumption(bool globalConsumpti dispatcher.Flush(); if (globalConsumption) + { Assert.Null(routed); + } else + { Assert.Same(pressed, routed); + } } [Fact] @@ -104,7 +114,7 @@ public void ConsumedReleaseResetsInputDuringDispatchBeforeSimulation() { var dispatcher = new EventDispatcher(); using EventHub ui = dispatcher.CreateHub(100); - using System.IDisposable subscription = ui.Listen(evnt => evnt.HandleInGlobal()); + using IDisposable subscription = ui.Listen(evnt => evnt.HandleInGlobal()); var capture = new EditorGameInputCapture(_ => 42u); capture.BeginFrame(); capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); @@ -114,7 +124,9 @@ public void ConsumedReleaseResetsInputDuringDispatchBeforeSimulation() { Event? routed = capture.Route(evnt); if (routed is not null) + { source.ProcessEvent(routed); + } }; dispatcher.Enqueue(new KeyPressedEvent(42, KeyCode.A)); dispatcher.Flush(); @@ -162,13 +174,13 @@ public void ConsumedReleasesResetHeldInputWithoutReplayingTheEvent(string releas "button" => new MouseButtonReleasedEvent(42, MouseButton.Left), "focus" => new WindowFocusChangedEvent(42, false), "close" => new WindowCloseEvent(42), - _ => throw new System.ArgumentException("Unknown release kind.", nameof(releaseKind)) + _ => throw new ArgumentException("Unknown release kind.", nameof(releaseKind)) }; release.HandleInGlobal(); WindowFocusChangedEvent reset = Assert.IsType(capture.Route(release)); Assert.False(reset.isFocused); - Assert.Equal(42u, reset.windowId); + Assert.Equal(42u, reset.windowID); Assert.False(reset.isGlobalHandled); Assert.Null(capture.Route(release)); Assert.Null(capture.Route(new KeyPressedEvent(42, KeyCode.B))); @@ -302,14 +314,14 @@ public void CapturedPointerCanReleaseOutsideImage() [Fact] public void MovingGameViewToAnotherPlatformWindowResetsOldInput() { - uint currentWindowId = 1; - var capture = new EditorGameInputCapture(_ => currentWindowId); + uint currentWindowID = 1; + var capture = new EditorGameInputCapture(_ => currentWindowID); capture.BeginFrame(); capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); capture.CompleteFrame(); Assert.IsType(capture.Route(new KeyPressedEvent(1, KeyCode.A))); - currentWindowId = 42; + currentWindowID = 42; capture.BeginFrame(); capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); Assert.Equal(1u, capture.CompleteFrame()); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs index 6ba5a874a..a439bbb79 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Xunit; using Inno.Core.IO; using Inno.Core.Input; using Inno.Editor.Core; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -29,7 +29,7 @@ public void MissingProjectDocumentReceivesOnlyTheStandardLayout() Assert.Equal(template, File.ReadAllText(context.layoutPath)); Assert.False(context.SaveLayoutIfChanged()); Assert.Equal(["Panels"], context.GetLayoutSectionNames()); - Assert.True(context.TryGetLayoutSection("Panels", out var panels)); + Assert.True(context.TryGetLayoutSection("Panels", out IReadOnlyDictionary panels)); Assert.Equal(8, panels.Count); Assert.All(panels.Values, value => Assert.Equal("true", value)); Assert.DoesNotContain("Module.", template, StringComparison.Ordinal); @@ -47,7 +47,7 @@ public void ExistingDocumentIsAuthoritativeIncludingAnIntentionallyEmptyFile(str { string path = Path.Combine(m_root, "editor.ini"); File.WriteAllText(path, document); - DateTime timestamp = new(2020, 2, 3, 4, 5, 6, DateTimeKind.Utc); + var timestamp = new DateTime(2020, 2, 3, 4, 5, 6, DateTimeKind.Utc); File.SetLastWriteTimeUtc(path, timestamp); byte[] bytes = File.ReadAllBytes(path); EditorContext context = CreateContext(ReadTemplate()); @@ -89,9 +89,9 @@ public void OrdinarySaveAndReopenRetainLayoutAndIndependentStateSections() byte[] saved = File.ReadAllBytes(context.layoutPath); EditorContext reopened = CreateContext(ReadTemplate()); Assert.Contains("[Window][User layout]", reopened.imguiLayout); - Assert.True(reopened.TryGetLayoutSection("Module.fixture", out var values)); + Assert.True(reopened.TryGetLayoutSection("Module.fixture", out IReadOnlyDictionary values)); Assert.Equal("42", values["value"]); - Assert.True(reopened.TryGetLayoutSection("Panels", out var panels)); + Assert.True(reopened.TryGetLayoutSection("Panels", out IReadOnlyDictionary panels)); Assert.Equal(8, panels.Count); Assert.Equal(saved, File.ReadAllBytes(reopened.layoutPath)); Assert.Single(Directory.GetFiles(m_root)); @@ -108,8 +108,8 @@ public void AContextWithoutACompositionDefaultRemainsPassive() public void Dispose() => Directory.Delete(PathBoundary.RequireUnlinkedPath(m_owner, m_root), recursive: true); - private EditorContext CreateContext(string? initialDocument) => new( - m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl"), initialDocument); + private EditorContext CreateContext(string? initialDocument) + => new(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl"), initialDocument); private static string ReadTemplate() => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs index c673db7ed..7d564c47e 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs @@ -1,31 +1,31 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Identity; using Inno.Core.Events; -using Inno.Core.Input; using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Mathematics; -using Inno.Core.Serialization; -using Inno.Editor.Interactions; using Inno.Editor.Core; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Scripting; +using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.References; using Inno.Runtime; using Inno.Runtime.Contracts; using Inno.Scene; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Editor.PlayMode.Tests; + public sealed class EditorPlayModeTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorPlayModeTests", Guid.NewGuid().ToString("N")); @@ -33,6 +33,7 @@ public sealed class EditorPlayModeTests : IDisposable private readonly RuntimeSession m_editSession; private readonly AssetPipeline m_authoringAssets; private readonly IDisposable m_editScope; + public EditorPlayModeTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); @@ -50,7 +51,10 @@ public EditorPlayModeTests() new IdentityAllocator(), m_engineHost.diagnostics, m_engineHost.logs, - AssetPipelineOptions.Create(Path.Combine(m_projectRoot, "Assets"), Path.Combine(m_projectRoot, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_projectRoot, "Assets"), + Path.Combine(m_projectRoot, "Library") + )with { enableFileSystemWatcher = false } ); } @@ -61,13 +65,20 @@ public void Dispose() m_editSession.Dispose(); m_engineHost.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] public void StateSubscriptionsNotifyAllObserversAndReleaseIndependently() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Ready), new FakeScenePlayMode()); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Ready), + new FakeScenePlayMode() + ); int observed = 0; using IDisposable failing = harness.playMode.ListenStateChanges(_ => throw new InvalidOperationException("Rejected observer.")); using IDisposable healthy = harness.playMode.ListenStateChanges(_ => observed++); @@ -87,8 +98,18 @@ public void StateSubscriptionsNotifyAllObserversAndReleaseIndependently() [Fact] public void PlayShortcutStopsTheSessionFromAFocusedGameView() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Ready), new FakeScenePlayMode()); - using var modules = new Inno.Extensibility.Modules.ModuleHost(new Inno.Extensibility.Modules.ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorPlayModeController).Assembly) }); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Ready), + new FakeScenePlayMode() + ); + using var modules = new ModuleHost( + new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorPlayModeController).Assembly) + } + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var interactions = new EditorInteractionRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), @@ -138,7 +159,12 @@ public void ReloadGuardPreservesStartupCompilationAndPinsThePlayingGeneration() [Fact] public void ReleasingGuardRegistrationDoesNotRetainItsBlockingState() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Compiling), new FakeScenePlayMode()); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Compiling), + new FakeScenePlayMode() + ); var reloads = new EditorReloadCoordinator(); IDisposable registration = reloads.RegisterGuard((IEditorReloadGuard)harness.playMode); Assert.True(harness.playMode.EnterPlayMode()); @@ -183,9 +209,17 @@ public void PendingStopRetainsHistoryAndBlocksNewGenerationUntilWorkDrains(bool var scenes = new FakeScenePlayMode(_ => { if (failSceneEntry) + { throw new InvalidOperationException("Scene materialization failed"); + } }); - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, scripting, scenes, new PendingPlayFactory(subsystem)); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + scripting, + scenes, + new PendingPlayFactory(subsystem) + ); try { Assert.True(harness.playMode.EnterPlayMode()); @@ -304,8 +338,8 @@ public void SceneSessionRestoresGraphIdentitySelectionAndEditValues() IEditorSceneWorkspace workspace = workspaceHost.workspace; var editScene = new GameScene("Edit Scene"); GameObject editObject = editScene.CreateObject("Edit Object"); - Guid sceneId = editScene.identity.persistentId; - Guid objectId = editObject.identity.persistentId; + Guid sceneID = editScene.identity.persistentID; + Guid objectID = editObject.identity.persistentID; SceneManager.LoadScene(editScene); selection.SetSelection(editObject); using RuntimeSession runtimeSession = m_engineHost.CreateSession(CreateSessionOptions(RuntimeSessionKind.Play)); @@ -320,8 +354,8 @@ public void SceneSessionRestoresGraphIdentitySelectionAndEditValues() Assert.NotSame(editScene, runtimeScene); Assert.NotSame(editObject, runtimeObject); - Assert.Equal(sceneId, runtimeScene.identity.persistentId); - Assert.Equal(objectId, runtimeObject.identity.persistentId); + Assert.Equal(sceneID, runtimeScene.identity.persistentID); + Assert.Equal(objectID, runtimeObject.identity.persistentID); Assert.Same(runtimeScene, Assert.Single(workspace.scenes)); Assert.Same(runtimeScene, workspace.activeScene); Assert.Same(runtimeObject, selection.selectedTarget); @@ -419,7 +453,7 @@ public void GamePresentationSwitchesFromEditToPlayAndBackWithoutSharingObjects() SceneManager.LoadScene(editScene); using ContentReadScope editing = presentation.Capture(); Assert.Same(editScene, Assert.Single(editing.GetValues())); - Assert.Equal(editScene.identity.persistentId, editing.activeContent); + Assert.Equal(editScene.identity.persistentID, editing.activeContent); using RuntimeSession runtimeSession = m_engineHost.CreateSession(CreateSessionOptions(RuntimeSessionKind.Play)); IDisposable playLease = workspaceHost.playMode.BeginPlayMode(runtimeSession); using ContentReadScope playing = presentation.Capture(); @@ -427,17 +461,21 @@ public void GamePresentationSwitchesFromEditToPlayAndBackWithoutSharingObjects() GameObject runtimeObject = Assert.Single(runtimeScene.GetObjects()); Assert.NotSame(editScene, runtimeScene); Assert.NotSame(editObject, runtimeObject); - Assert.Equal(runtimeScene.identity.persistentId, playing.activeContent); + Assert.Equal(runtimeScene.identity.persistentID, playing.activeContent); runtimeObject.name = "Runtime Object"; runtimeObject.transform.localRotation = Quaternion.FromEulerAnglesXYZDegrees(new Vector3(0f, 0f, 90f)); Assert.Equal("Runtime Object", Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).name); - Assert.Equal(90f, Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).transform.localRotation.ToEulerAnglesXYZDegrees().z, precision: 3); + Assert.Equal( + 90f, + Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).transform.localRotation.ToEulerAnglesXYZDegrees().z, + precision: 3 + ); Assert.Equal("Edit Object", editObject.name); Assert.Equal(Quaternion.identity, editObject.transform.localRotation); playLease.Dispose(); using ContentReadScope restored = presentation.Capture(); Assert.Same(editScene, Assert.Single(restored.GetValues())); - Assert.Equal(editScene.identity.persistentId, restored.activeContent); + Assert.Equal(editScene.identity.persistentID, restored.activeContent); Assert.Equal("Edit Object", Assert.Single(editScene.GetObjects()).name); } @@ -456,11 +494,13 @@ public void RejectedPlayWorldDoesNotReplaceTheEditPresentation() SceneManager.LoadScene(editScene); using RuntimeSession runtimeSession = m_engineHost.CreateSession(CreateSessionOptions(RuntimeSessionKind.Play)); using (runtimeSession.EnterExecutionScope()) + { runtimeSession.scenes.LoadScene(new GameScene("Unexpected Existing Runtime Scene")); + } Assert.Throws(() => workspaceHost.playMode.BeginPlayMode(runtimeSession)); using ContentReadScope snapshot = presentation.Capture(); Assert.Same(editScene, Assert.Single(snapshot.GetValues())); - Assert.Equal(editScene.identity.persistentId, snapshot.activeContent); + Assert.Equal(editScene.identity.persistentID, snapshot.activeContent); Assert.True(workspaceHost.workspace.canPersist); } @@ -480,18 +520,30 @@ public void ScenePresentationScopeRejectsStalePlayRootsAfterStop() IDisposable playLease = workspaceHost.playMode.BeginPlayMode(runtimeSession); using ContentReadScope playing = workspaceHost.gamePresentation.Capture(); Identity captured = Assert.Single(playing.contents); - Assert.Equal(editScene.identity.persistentId, captured.persistentId); + Assert.Equal(editScene.identity.persistentID, captured.persistentID); Assert.NotEqual(editScene.identity.runtimeIdentity, captured.runtimeIdentity); playLease.Dispose(); runtimeSession.Dispose(); Assert.Empty(playing.GetValues()); - Assert.False(playing.TryGetValue(captured.persistentId, out _)); + Assert.False(playing.TryGetValue(captured.persistentID, out _)); using ContentReadScope editing = workspaceHost.gamePresentation.Capture(); Assert.Same(editScene, Assert.Single(editing.GetValues())); playing.Dispose(); Assert.Throws(() => playing.GetValues()); } + private RuntimeSessionOptions CreateSessionOptions(RuntimeSessionKind kind) + { + string applicationID = kind == RuntimeSessionKind.Edit ? "inno.tests.edit" : "inno.tests.play"; + return new RuntimeSessionOptions + { + kind = kind, + applicationID = applicationID, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_projectRoot, "PersistentData", applicationID), "Logs")), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread + }; + } + public sealed class CountingSystem : GameSystem { public int fixedCount { get; private set; } @@ -499,7 +551,9 @@ public sealed class CountingSystem : GameSystem public int lateCount { get; private set; } protected override void OnFixedUpdate() => fixedCount++; + protected override void OnUpdate() => updateCount++; + protected override void OnLateUpdate() => lateCount++; } @@ -512,6 +566,7 @@ private sealed class PlayModeHarness : IDisposable { private readonly EditorPlayModeController m_controller; private readonly FakeHistoryIsolation m_history = new(); + internal PlayModeHarness( string projectRoot, EngineHost engineHost, @@ -521,10 +576,13 @@ internal PlayModeHarness( ) { m_controller = new EditorPlayModeController( engineHost, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, - applicationId = "inno.tests.play", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "PersistentData", "inno.tests.play"), "Logs")), + applicationID = "inno.tests.play", + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(projectRoot, "PersistentData", "inno.tests.play"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createSubsystems = _ => factory is null ? [] : [factory] }, @@ -535,34 +593,23 @@ internal PlayModeHarness( ); } + public void Dispose() => m_controller.Dispose(); + internal IEditorPlayMode playMode => m_controller; internal FakeHistoryIsolation history => m_history; internal void Update() => m_controller.AdvanceTransition(); + internal void Simulate(float deltaTime) => m_controller.Tick(deltaTime); - public void Dispose() - { - m_controller.Dispose(); - } } private sealed class FakeScriptCompilation(EditorScriptCompilationState initialState) : IEditorScriptCompilation { - public bool requiresExclusiveProgress => false; - public EditorScriptCompilationProgress progress => new(0, 0f, "Test script status.", false); - - public void CancelCompilation(long operationId) - { - } - private EditorScriptCompilationState m_state = initialState; private FakeCompilationTicket? m_ticket; - public IScriptCompilationTicket RequestCompilation() - { - m_ticket = new FakeCompilationTicket(); - m_ticket.SetState(m_state); - return m_ticket; - } + + public bool requiresExclusiveProgress => false; + public EditorScriptCompilationProgress progress => new(0, 0f, "Test script status.", false); public IScriptCompilationTicket? currentTicket => m_ticket; @@ -577,48 +624,59 @@ public EditorScriptCompilationState state } public ScriptCompilationResult? lastCompilation => null; + + public void CancelCompilation(long operationID) {} + + public IScriptCompilationTicket RequestCompilation() + { + m_ticket = new FakeCompilationTicket(); + m_ticket.SetState(m_state); + return m_ticket; + } } private sealed class PendingPlayFactory(PendingPlaySubsystem subsystem) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("test.pending-play")); + public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemID("test.pending-play")); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => subsystem; } private sealed class PendingPlaySubsystem : RuntimeSubsystem { + internal bool stopped; + internal TaskCompletionSource work { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal bool stopped; protected override void OnStart() => lifetime.Track(work.Task); + protected override void OnStop() => stopped = true; } private sealed class FakeCompilationTicket : IScriptCompilationTicket { - public long requestId => 1; + public long requestID => 1; public ScriptCompilationTicketState state { get; private set; } public string status => "Test compilation ticket."; public ScriptCompilationResult? result => null; - public bool isCompleted => state is ScriptCompilationTicketState.Succeeded or ScriptCompilationTicketState.Failed or ScriptCompilationTicketState.Canceled or ScriptCompilationTicketState.Superseded; + + public bool isCompleted + => state is ScriptCompilationTicketState.Succeeded + or ScriptCompilationTicketState.Failed + or ScriptCompilationTicketState.Canceled + or ScriptCompilationTicketState.Superseded; internal void SetState(EditorScriptCompilationState value) - { - state = value switch + => state = value switch { EditorScriptCompilationState.Ready => ScriptCompilationTicketState.Succeeded, EditorScriptCompilationState.Failed => ScriptCompilationTicketState.Failed, _ => ScriptCompilationTicketState.Compiling }; - } } private sealed class FakeScenePlayMode(Action? populate = null) : IEditorScenePlayMode { - internal int beginCount { get; private set; } - internal int restoreCount { get; private set; } - public IDisposable BeginPlayMode(RuntimeSession runtimeSession) { beginCount++; @@ -626,13 +684,19 @@ public IDisposable BeginPlayMode(RuntimeSession runtimeSession) return new Session(this); } + internal int beginCount { get; private set; } + internal int restoreCount { get; private set; } + private sealed class Session(FakeScenePlayMode owner) : IDisposable { private bool m_restored; + public void Dispose() { if (m_restored) + { return; + } m_restored = true; owner.restoreCount++; } @@ -641,55 +705,37 @@ public void Dispose() private sealed class FakeSelectionCoordinator : IEditorSelectionCoordinator { - public IDisposable RegisterIdentityDomain(Inno.Core.Identity.IdentityAllocator allocator) => new Inno.Core.Execution.LifetimeScope(); public object? selectedTarget { get; private set; } + public IDisposable RegisterIdentityDomain(IdentityAllocator allocator) => new LifetimeScope(); + public void SetSelection(object? target) => selectedTarget = target; } private sealed class FakeHistoryIsolation : IEditorHistoryIsolation { - internal int beginCount { get; private set; } - internal int disposeCount { get; private set; } - public IDisposable BeginHistoryIsolation() { beginCount++; return new Lease(this); } + internal int beginCount { get; private set; } + internal int disposeCount { get; private set; } + private sealed class Lease(FakeHistoryIsolation owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.disposeCount++; } } } - - private RuntimeSessionOptions CreateSessionOptions(RuntimeSessionKind kind) - { - string applicationId = kind == RuntimeSessionKind.Edit ? "inno.tests.edit" : "inno.tests.play"; - return new RuntimeSessionOptions - { - kind = kind, - applicationId = applicationId, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_projectRoot, "PersistentData", applicationId), "Logs")), - jobExecutionMode = RuntimeJobExecutionMode.SingleThread - }; - } -} - -[StableTypeId("9afec1fd-c1ef-45fa-9bcc-0b3e2877d613")] -internal sealed class PlayModeAssetReferenceBehavior : GameBehavior -{ - /// - /// Gets or sets the asset reference copied into the isolated Play Mode scene. - /// - [SerializableProperty] - public TextAsset? asset { get; set; } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs index e4e83c400..bd7a64ac0 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs @@ -1,15 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; + public sealed unsafe class EditorPopupLayoutTests { [Fact] @@ -18,7 +20,7 @@ public void ContextMenuSearchUsesCompletePopupContentWidth() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); @@ -60,14 +62,14 @@ public void TwoItemSelectorOpensBelowControlWithoutOverflow() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Selector bounds", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); @@ -104,14 +106,14 @@ public void LongSelectorNearWindowBottomScrollsWithoutOpeningUpward() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText2 = Utf8Codec.EncodeNullTerminated("Selector near bottom", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText2.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); @@ -123,7 +125,9 @@ public void LongSelectorNearWindowBottomScrollsWithoutOpeningUpward() Vector2 popupPosition = NativeImGui.GetWindowPos(); Vector2 popupSize = NativeImGui.GetWindowSize(); for (int index = 0; index < 40; index++) + { _ = NativeImGui.Selectable($"Item {index}"); + } if (frame == 2) { Assert.InRange(popupPosition.Y, triggerBottom - 1f, triggerBottom + 1f); @@ -148,14 +152,14 @@ public void SelectorInsideLayoutChildUsesContainingPanelBounds() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText3 = Utf8Codec.EncodeNullTerminated("Panel with layout child", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText3.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); @@ -166,7 +170,9 @@ public void SelectorInsideLayoutChildUsesContainingPanelBounds() Vector2 popupPosition = NativeImGui.GetWindowPos(); Vector2 popupSize = NativeImGui.GetWindowSize(); for (int index = 0; index < 40; index++) + { _ = NativeImGui.Selectable($"Item {index}"); + } if (frame == 2) { Assert.True(popupSize.Y > 55f); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs index 2ad0095d1..957e6f396 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs @@ -1,14 +1,19 @@ using System; using System.Linq; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; +using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + +using Gui = Inno.Editor.ImGui.ImGui; +using GuiDrawList = Inno.Editor.ImGui.EditorDrawList; +using GuiHoveredFlags = Inno.Editor.ImGui.ImGuiHoveredFlags; +using GuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; using NativeGui = Inno.Native.ImGui.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -19,18 +24,18 @@ public void NonShaderPointerWorkflowUsesTheRealDocumentHistory() { using var host = new NativeProjectPanelHost(typeof(GraphCanvasNativeTests).Assembly); var document = new GraphDocument(); - var first = new GraphNodeRecord(new("workflow.first"), "workflow.step") { position = new(20f, 20f) }; - var second = new GraphNodeRecord(new("workflow.second"), "workflow.step") { position = new(300f, 20f) }; + var first = new GraphNodeRecord(new GraphNodeID("workflow.first"), "workflow.step") { position = new(20f, 20f) }; + var second = new GraphNodeRecord(new GraphNodeID("workflow.second"), "workflow.step") { position = new(300f, 20f) }; document.AddNode(first); document.AddNode(second); - var history = host.runtime.interactions.history; - var controller = host.graphs.OpenDocument(Guid.NewGuid(), document, history); + IEditorHistory history = host.runtime.interactions.history; + GraphDocumentController controller = host.graphs.OpenDocument(Guid.NewGuid(), document, history); var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); Vector2 origin = default; - Frame(new(0f, 0f), false); - Frame(new(0f, 0f), false); + Frame(new Vector2(0f, 0f), false); + Frame(new Vector2(0f, 0f), false); Vector2 hit = origin + new Vector2(30f, 25f); Frame(hit, true); Frame(hit + new Vector2(50f, 40f), true); @@ -42,8 +47,8 @@ public void NonShaderPointerWorkflowUsesTheRealDocumentHistory() Frame(origin + new Vector2(270f, 100f), true); Frame(origin + new Vector2(300f, 60f), false); GraphEdgeRecord edge = Assert.Single(controller.document.edges); - Assert.Equal(first.id, edge.output.nodeId); - Assert.Equal(second.id, edge.input.nodeId); + Assert.Equal(first.id, edge.output.nodeID); + Assert.Equal(second.id, edge.input.nodeID); Assert.True(history.Undo().succeeded); Assert.Empty(controller.document.edges); Assert.True(history.Redo().succeeded); @@ -53,7 +58,7 @@ void Frame( Vector2 mouse, bool down ) { - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); NativeGui.Raw.AddMousePosEvent(io, mouse.X, mouse.Y); NativeGui.Raw.AddMouseButtonEvent(io, 0, down ? (byte)1 : (byte)0); host.native.Frame(() => @@ -64,31 +69,60 @@ bool down _ = NativeGui.Begin("Workflow graph", ref open, (int)(ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings)); try { - origin = Ui.GetCursorScreenPosition(); - Vector2 size = Ui.GetContentRegionAvailable(); - _ = Ui.InvisibleButton("workflow-canvas", size); + origin = Gui.GetCursorScreenPosition(); + Vector2 size = Gui.GetContentRegionAvailable(); + _ = Gui.InvisibleButton("workflow-canvas", size); var view = new GraphCanvasView(state, origin, size); - _ = layout.SetNodes(controller.document.nodes.Select(node => new GraphCanvasNode(node.id, node.position, - new(200f, 100f), 24f, "Workflow step", [ - new(new(node.id, new("previous")), GraphPortDirection.Input, new(0f, 40f), "Previous"), - new(new(node.id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Next") - ]))); - GraphCanvasPointerResult result = pointer.Step(view, layout, new() + _ = layout.SetNodes( + controller.document.nodes.Select(node => new GraphCanvasNode( + node.id, + node.position, + new Vector2(200f, 100f), + 24f, + "Workflow step", + [ + new GraphCanvasPort( + new GraphEndpoint(node.id, new GraphPortID("previous")), + GraphPortDirection.Input, + new Vector2(0f, 40f), + "Previous" + ), + new GraphCanvasPort( + new GraphEndpoint(node.id, new GraphPortID("next")), + GraphPortDirection.Output, + new Vector2(200f, 40f), + "Next" + ) + ] + )) + ); + GraphCanvasPointerResult result = pointer.Step(view, layout, new GraphCanvasPointerInput() { - position = Ui.GetMousePos(), - isHovered = Ui.IsItemHovered(Inno.Editor.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByActiveItem), - isPressed = Ui.IsMouseClicked(Inno.Editor.ImGui.ImGuiMouseButton.Left), - isDown = Ui.IsMouseButtonDown(Inno.Editor.ImGui.ImGuiMouseButton.Left), - isReleased = Ui.IsMouseReleased(Inno.Editor.ImGui.ImGuiMouseButton.Left) + position = Gui.GetMousePos(), + isHovered = Gui.IsItemHovered(GuiHoveredFlags.AllowWhenBlockedByActiveItem), + isPressed = Gui.IsMouseClicked(GuiMouseButton.Left), + isDown = Gui.IsMouseButtonDown(GuiMouseButton.Left), + isReleased = Gui.IsMouseReleased(GuiMouseButton.Left) }); if (result.movedNodes is { } positions) + { controller.MoveNodes(positions); + } if (result.output is GraphEndpoint output && result.input is GraphEndpoint input) + { _ = controller.Connect(output, input); - var draw = Ui.GetDrawList(); + } + GuiDrawList draw = Gui.GetDrawList(); foreach (GraphCanvasNode node in layout.nodes) - _ = view.DrawNode(draw, node, 0xFF504030, state.selectedNodes.Contains(node.id), - previewPosition: pointer.previewPositions.TryGetValue(node.id, out GraphPosition position) ? position : null); + { + _ = view.DrawNode( + draw, + node, + 0xFF50_4030, + state.selectedNodes.Contains(node.id), + previewPosition: pointer.previewPositions.TryGetValue(node.id, out GraphPosition position) ? position : null + ); + } } finally { @@ -103,9 +137,21 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() { using var host = new NativePanelHost(typeof(GraphCanvasNativeTests).Assembly); var state = new GraphCanvasState(); - GraphNodeId id = new("workflow.begin"); - var node = new GraphCanvasNode(id, new(10f, 10f), new(200f, 100f), 24f, "Workflow step", - [new(new(id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Continue", labelBounds: (new(0f, 28f), new(200f, 52f)))]); + var id = new GraphNodeID("workflow.begin"); + var node = new GraphCanvasNode( + id, + new GraphPosition(10f, 10f), + new Vector2(200f, 100f), + 24f, + "Workflow step", + [new GraphCanvasPort( + new GraphEndpoint(id, new GraphPortID("next")), + GraphPortDirection.Output, + new Vector2(200f, 40f), + "Continue", + labelBounds: (new Vector2(0f, 28f), new Vector2(200f, 52f)) + )] + ); for (int frame = 0; frame < 3; frame++) { host.Frame(() => @@ -118,18 +164,56 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() { ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); int clipDepth = window->DrawList->ClipRectStack.Size; - var draw = Ui.GetDrawList(); - var view = new GraphCanvasView(state, new(40f, 60f), new(540f, 300f)); + GuiDrawList draw = Gui.GetDrawList(); + var view = new GraphCanvasView(state, new Vector2(40f, 60f), new Vector2(540f, 300f)); var failure = new InvalidOperationException("Workflow node extension failed."); - Assert.Same(failure, Assert.Throws(() => view.DrawNode(draw, node, 0xFF504030, true, - () => throw failure))); + Assert.Same( + failure, + Assert.Throws(() => view.DrawNode( + draw, + node, + 0xFF50_4030, + true, + () => throw failure + )) + ); Assert.Equal(clipDepth, window->DrawList->ClipRectStack.Size); - Assert.True(view.DrawNode(draw, node, 0xFF504030, false)); - var offscreen = new GraphCanvasNode(new("workflow.hidden"), new(5000f, 5000f), new(200f, 100f), 24f, "Hidden", []); - Assert.False(view.DrawNode(draw, offscreen, 0xFF504030, false, () => throw new InvalidOperationException("Culled content must not run."))); - var outsideWindow = new GraphCanvasNode(new("workflow.clipped-parent"), new(900f, 900f), new(200f, 100f), 24f, "Clipped by parent", []); - var oversized = new GraphCanvasView(state, new(40f, 60f), new(1800f, 1800f)); - Assert.False(oversized.DrawNode(draw, outsideWindow, 0xFF504030, false, () => throw new InvalidOperationException("Parent-clipped content must not run."))); + Assert.True(view.DrawNode(draw, node, 0xFF50_4030, false)); + var offscreen = new GraphCanvasNode( + new GraphNodeID("workflow.hidden"), + new GraphPosition(5000f, 5000f), + new Vector2(200f, 100f), + 24f, + "Hidden", + [] + ); + Assert.False( + view.DrawNode( + draw, + offscreen, + 0xFF50_4030, + false, + () => throw new InvalidOperationException("Culled content must not run.") + ) + ); + var outsideWindow = new GraphCanvasNode( + new GraphNodeID("workflow.clipped-parent"), + new GraphPosition(900f, 900f), + new Vector2(200f, 100f), + 24f, + "Clipped by parent", + [] + ); + var oversized = new GraphCanvasView(state, new Vector2(40f, 60f), new Vector2(1800f, 1800f)); + Assert.False( + oversized.DrawNode( + draw, + outsideWindow, + 0xFF50_4030, + false, + () => throw new InvalidOperationException("Parent-clipped content must not run.") + ) + ); Assert.Equal(clipDepth, window->DrawList->ClipRectStack.Size); } finally diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs index 4b9d12299..63840acb4 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Assets.ImGui; @@ -9,7 +10,6 @@ using Inno.Native.ImGui; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -48,7 +48,7 @@ public void HierarchyUsesVisibleRangeAndKeepsTextEditingExclusive( float height ) { using var host = new NativeProjectPanelHost(typeof(ListPanelKeyboardNativeTests).Assembly); - host.native.SetDisplayMetrics(new(width, height), framebufferScale, zoom); + host.native.SetDisplayMetrics(new Vector2(width, height), framebufferScale, zoom); GameScene scene = host.CreateScene(); GameObject[] objects = Enumerable.Range(0, 12).Select(index => scene.CreateObject("Object " + index.ToString("D2"))).ToArray(); GameObject child = scene.CreateObject("Collapsed child"); @@ -96,7 +96,7 @@ public void BrowserUsesTheFocusedVisibleOrderAndActivatesFoldersAfterTraversal( float height ) { using var host = new NativeProjectPanelHost(typeof(ListPanelKeyboardNativeTests).Assembly); - host.native.SetDisplayMetrics(new(width, height), framebufferScale, zoom); + host.native.SetDisplayMetrics(new Vector2(width, height), framebufferScale, zoom); AssetFileEntry[] entries = Enumerable.Range(0, 12).Select(index => { AssetPath path = AssetPath.Project("Folder " + index.ToString("D2")); @@ -130,7 +130,7 @@ float height NativePanelInput.Key(host.native, panel, ImGuiKey.End); Assert.Same(entries[^1], interactions.selection.selectedTarget); NativePanelInput.Key(host.native, panel, ImGuiKey.Enter); - Assert.True(interactions.TryGetModule(out var browser)); + Assert.True(interactions.TryGetModule(out AssetBrowserModule? browser)); Assert.Equal(entries[^1].assetPath.ToString(), browser!.browser.currentDirectory); Assert.False(interactions.history.canUndo); } @@ -138,7 +138,11 @@ float height public static IEnumerable BrowserMetrics() { foreach (bool tree in new[] { false, true }) + { foreach (object[] metric in VisualScaleMatrixTests.Metrics()) + { yield return [tree, .. metric]; + } + } } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs index b216aa125..45feb819f 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.Threading; +using Xunit; using Inno.Assets; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -23,9 +23,11 @@ public void UnavailableSourceKeepsAssignmentEditsAndIdentityUntilRecovery(bool e string physical = Path.Combine(host.projectRoot, "Assets", path); byte[] source = File.ReadAllBytes(physical); byte[] metadata = File.ReadAllBytes(physical + ".imeta"); - Guid id = host.assets.Load(AssetPath.Project(path)).identity.persistentId; + Guid id = host.assets.Load(AssetPath.Project(path)).identity.persistentID; if (edited) + { value.name = "Unsaved edit"; + } File.Delete(physical); Assert.True(host.workspace.TryGetSourcePath(scene, out string pendingPath)); Assert.Equal(path, pendingPath); @@ -42,7 +44,7 @@ public void UnavailableSourceKeepsAssignmentEditsAndIdentityUntilRecovery(bool e Thread.Sleep(120); Assert.True(host.workspace.TryGetSourcePath(scene, out string recovered)); Assert.Equal(path, recovered); - Assert.Equal(id, host.assets.Load(AssetPath.Project(path)).identity.persistentId); + Assert.Equal(id, host.assets.Load(AssetPath.Project(path)).identity.persistentID); Assert.Equal(edited, host.workspace.IsDirty(scene)); host.assets.Move(AssetPath.Project(path), AssetPath.Project("Recovered.iscene")); Assert.True(host.workspace.TryGetSourcePath(scene, out string renamed)); @@ -52,7 +54,7 @@ public void UnavailableSourceKeepsAssignmentEditsAndIdentityUntilRecovery(bool e GameScene reopened = host.workspace.Open("Recovered.iscene"); Assert.Equal(edited ? "Unsaved edit" : "Retained object", Assert.Single(reopened.GetObjects()).name); Assert.False(host.workspace.IsDirty(reopened)); - Assert.Equal(id, host.assets.Load(AssetPath.Project("Recovered.iscene")).identity.persistentId); + Assert.Equal(id, host.assets.Load(AssetPath.Project("Recovered.iscene")).identity.persistentID); } [Fact] @@ -64,7 +66,7 @@ public void ExplicitSaveToAnotherDirectoryDoesNotRecreateTheMissingAssignedSourc GameObject value = scene.CreateObject("Retained object"); string original = host.workspace.Save(scene, string.Empty); string physical = Path.Combine(host.projectRoot, "Assets", original); - Guid originalId = host.assets.Load(AssetPath.Project(original)).identity.persistentId; + Guid originalID = host.assets.Load(AssetPath.Project(original)).identity.persistentID; File.Delete(physical); host.assets.Rescan(); Assert.True(host.workspace.IsDirty(scene)); @@ -75,7 +77,7 @@ public void ExplicitSaveToAnotherDirectoryDoesNotRecreateTheMissingAssignedSourc Assert.False(File.Exists(physical)); Assert.True(host.workspace.TryGetSourcePath(scene, out string assigned)); Assert.Equal(replacement, assigned); - Assert.NotEqual(originalId, host.assets.Load(AssetPath.Project(replacement)).identity.persistentId); + Assert.NotEqual(originalID, host.assets.Load(AssetPath.Project(replacement)).identity.persistentID); Assert.False(host.workspace.IsDirty(scene)); Assert.True(host.edits.CloseScene(scene)); GameScene reopened = host.workspace.Open(replacement); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs new file mode 100644 index 000000000..959d9582a --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs @@ -0,0 +1,16 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.PlayMode.Tests; + +[StableTypeID("9afec1fd-c1ef-45fa-9bcc-0b3e2877d613")] +internal sealed class PlayModeAssetReferenceBehavior : GameBehavior +{ + /// + /// Gets or sets the asset reference copied into the isolated Play Mode scene. + /// + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs index 5cb91fabc..ca9e522ac 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs @@ -1,12 +1,11 @@ using System; using System.Linq; - -using Inno.Extensibility.Modules; +using Xunit; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Logging; using Inno.Editor.Diagnostics; - -using Xunit; +using Inno.Extensibility.Modules; namespace Inno.Editor.PlayMode.Tests; @@ -40,10 +39,11 @@ public void Dispose() public void ClearOnPlayRemovesOldLogsButRetainsCurrentDiagnostics() { Assert.True(m_console.clearOnPlay); - Dispatch(LogLevel.Info, LogSessionId.none, "before-play"); + Dispatch(LogLevel.Info, LogSessionID.none, "before-play"); m_diagnosticHub.Set( new DiagnosticSource("test.compiler", "Test Compiler"), - [Diagnostic.Error("TEST001", "compiler-diagnostic")]); + [Diagnostic.Error("TEST001", "compiler-diagnostic")] + ); m_logRouter.Flush(); _ = m_playMode.Begin(); @@ -57,9 +57,10 @@ public void ClearOnPlayRemovesOldLogsButRetainsCurrentDiagnostics() [Fact] public void ManualClearRemovesHistoryButKeepsCurrentIssuesUntilResolved() { - Dispatch(LogLevel.Error, LogSessionId.none, "old failure"); + Dispatch(LogLevel.Error, LogSessionID.none, "old failure"); using DiagnosticReporter reporter = m_diagnosticHub.CreateReporter( - new DiagnosticSource("tests.current", "Current issue")); + new DiagnosticSource("tests.current", "Current issue") + ); reporter.Publish(Diagnostic.Error("CURRENT", "still failing")); m_logRouter.Flush(); @@ -73,12 +74,12 @@ public void ManualClearRemovesHistoryButKeepsCurrentIssuesUntilResolved() [Fact] public void CompletedPlaySessionRetainsEveryRuntimeSeverity() { - LogSessionId sessionId = m_playMode.Begin(); - Dispatch(LogLevel.Debug, sessionId, "runtime-debug"); - Dispatch(LogLevel.Info, sessionId, "runtime-info"); - Dispatch(LogLevel.Warn, sessionId, "runtime-warning"); - Dispatch(LogLevel.Error, sessionId, "runtime-error"); - Dispatch(LogLevel.Fatal, sessionId, "runtime-fatal"); + LogSessionID sessionID = m_playMode.Begin(); + Dispatch(LogLevel.Debug, sessionID, "runtime-debug"); + Dispatch(LogLevel.Info, sessionID, "runtime-info"); + Dispatch(LogLevel.Warn, sessionID, "runtime-warning"); + Dispatch(LogLevel.Error, sessionID, "runtime-error"); + Dispatch(LogLevel.Fatal, sessionID, "runtime-fatal"); m_playMode.SetState(EditorPlayModeState.Playing); m_playMode.SetState(EditorPlayModeState.Stopping); m_playMode.End(); @@ -96,42 +97,39 @@ public void CompletedPlaySessionRetainsEveryRuntimeSeverity() [Fact] public void FailedEntryRetainsPreparationDiagnosticsBecauseSimulationNeverStarted() { - LogSessionId sessionId = m_playMode.Begin(); - Dispatch(LogLevel.Info, sessionId, "entry-diagnostic"); + LogSessionID sessionID = m_playMode.Begin(); + Dispatch(LogLevel.Info, sessionID, "entry-diagnostic"); m_playMode.SetState(EditorPlayModeState.Failed); m_logRouter.Flush(); - Assert.Contains( - m_console.Capture().occurrences, - static entry => entry.message == "entry-diagnostic"); + Assert.Contains(m_console.Capture().occurrences, static entry => entry.message == "entry-diagnostic"); } [Fact] public void DisabledClearOnPlayRetainsExistingLogs() { m_console.clearOnPlay = false; - Dispatch(LogLevel.Info, LogSessionId.none, "before-play"); + Dispatch(LogLevel.Info, LogSessionID.none, "before-play"); m_logRouter.Flush(); _ = m_playMode.Begin(); - Assert.Contains( - m_console.Capture().occurrences, - static entry => entry.message == "before-play"); + Assert.Contains(m_console.Capture().occurrences, static entry => entry.message == "before-play"); } [Fact] public void CollapseGroupsEquivalentNonConsecutiveOccurrencesGlobally() { - Dispatch(LogLevel.Info, LogSessionId.none, "repeated", file: "A.cs", line: 10); - Dispatch(LogLevel.Warn, LogSessionId.none, "middle", file: "B.cs", line: 20); - Dispatch(LogLevel.Info, LogSessionId.none, "repeated", file: "A.cs", line: 10); - Dispatch(LogLevel.Info, LogSessionId.none, "repeated", file: "C.cs", line: 30); + Dispatch(LogLevel.Info, LogSessionID.none, "repeated", file: "A.cs", line: 10); + Dispatch(LogLevel.Warn, LogSessionID.none, "middle", file: "B.cs", line: 20); + Dispatch(LogLevel.Info, LogSessionID.none, "repeated", file: "A.cs", line: 10); + Dispatch(LogLevel.Info, LogSessionID.none, "repeated", file: "C.cs", line: 30); m_logRouter.Flush(); EditorConsoleSnapshot snapshot = m_console.Capture(); - EditorConsoleGroup repeated = Assert.Single(snapshot.groups.Where( - static group => group.latest.message == "repeated" && group.latest.file == "A.cs")); + EditorConsoleGroup repeated = Assert.Single( + snapshot.groups.Where(static group => group.latest.message == "repeated" && group.latest.file == "A.cs") + ); Assert.Equal(2, repeated.count); Assert.Equal(3, snapshot.groups.Count); @@ -141,24 +139,22 @@ public void CollapseGroupsEquivalentNonConsecutiveOccurrencesGlobally() [Fact] public void CollapseDoesNotMergeEquivalentEntriesAcrossRuntimeSessions() { - LogSessionId first = LogSessionId.Create(); - LogSessionId second = LogSessionId.Create(); + LogSessionID first = LogSessionID.Create(); + LogSessionID second = LogSessionID.Create(); Dispatch(LogLevel.Info, first, "session-entry", file: "A.cs", line: 10); Dispatch(LogLevel.Info, second, "session-entry", file: "A.cs", line: 10); m_logRouter.Flush(); EditorConsoleSnapshot snapshot = m_console.Capture(); - Assert.Equal( - 2, - snapshot.groups.Count(static group => group.latest.message == "session-entry")); + Assert.Equal(2, snapshot.groups.Count(static group => group.latest.message == "session-entry")); } [Fact] public void ConsoleTimelineAppendsTheNewestEntryAtTheBottom() { - Dispatch(LogLevel.Info, LogSessionId.none, "first"); - Dispatch(LogLevel.Error, LogSessionId.none, "latest"); + Dispatch(LogLevel.Info, LogSessionID.none, "first"); + Dispatch(LogLevel.Error, LogSessionID.none, "latest"); m_logRouter.Flush(); EditorConsoleSnapshot snapshot = m_console.Capture(); @@ -171,11 +167,12 @@ public void ConsoleTimelineAppendsTheNewestEntryAtTheBottom() private void Dispatch( LogLevel level, - LogSessionId sessionId, + LogSessionID sessionID, string message, string file = nameof(PlayModeLogRetentionTests), - int line = 0) - => m_logRouter.Dispatch(new LogEntry( + int line = 0 + ) => m_logRouter.Dispatch( + new LogEntry( level, AssemblyDomain.InnoScripting, AssemblyScope.Runtime, @@ -184,44 +181,46 @@ private void Dispatch( file, line, $"at {file}:{line}", - sessionId)); + sessionID + ) + ); private sealed class FakePlayMode : IEditorPlayMode { + private readonly EventDispatcher m_stateDispatcher = new(); + private readonly EventHub m_stateEvents; + + internal FakePlayMode() + { + m_stateEvents = m_stateDispatcher.CreateHub(); + } + public EditorPlayModeState state { get; private set; } public bool isPlaying => state == EditorPlayModeState.Playing; public string? lastFailure => null; - public LogSessionId activeSessionId { get; private set; } - - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); - private readonly Inno.Core.Events.EventHub m_stateEvents; + public LogSessionID activeSessionID { get; private set; } - internal FakePlayMode() => m_stateEvents = m_stateDispatcher.CreateHub(); public IDisposable ListenStateChanges(Action listener) => m_stateEvents.Listen(notification => listener(notification.state)); - private sealed class StateNotification(EditorPlayModeState state) : Inno.Core.Events.Event - { - internal EditorPlayModeState state { get; } = state; - } public bool EnterPlayMode() => false; public bool ExitPlayMode() => false; - internal LogSessionId Begin() + internal LogSessionID Begin() { - activeSessionId = LogSessionId.Create(); + activeSessionID = LogSessionID.Create(); SetState(EditorPlayModeState.Compiling); - return activeSessionId; + return activeSessionID; } internal void End() { SetState(EditorPlayModeState.Editing); - activeSessionId = LogSessionId.none; + activeSessionID = LogSessionID.none; } internal void SetState(EditorPlayModeState value) @@ -229,5 +228,10 @@ internal void SetState(EditorPlayModeState value) state = value; m_stateDispatcher.Emit(new StateNotification(value)); } + + private sealed class StateNotification(EditorPlayModeState state) : Event + { + internal EditorPlayModeState state { get; } = state; + } } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs index a3455ede1..14cc2ba5a 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs @@ -1,14 +1,12 @@ using System; using System.Security.Cryptography; using System.Threading; +using Xunit; using Inno.Assets; -using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; using Inno.Core.Mathematics; -using Inno.Extensibility.Types; +using Inno.Core.Serialization; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -31,8 +29,14 @@ public void OwnedRevisionCaptureKeepsDirtyStateExactAcrossHistoryRestoreAndDirec Check(true); Assert.True(host.runtime.interactions.history.Undo().succeeded); Check(false); - Assert.True(host.edits.ChangeProperty(value.transform, "localPosition", - () => value.transform.localPosition = new Vector3(3, 4, 5), "Move")); + Assert.True( + host.edits.ChangeProperty( + value.transform, + "localPosition", + () => value.transform.localPosition = new Vector3(3, 4, 5), + "Move" + ) + ); Check(true); Assert.True(host.runtime.interactions.history.Undo().succeeded); Check(false); @@ -58,7 +62,10 @@ public void CompleteSceneCapturesReuseOnlyUnchangedNeutralState() GameObject target = scene.CreateObject("Target"); DirtyCaptureComponent component = owner.AddComponent(); component.target = target; - SerializationContext context = AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)); + SerializationContext context = AssetSerializationContext.Create( + host.assets, + new AssetDependencyCollection(includeLastKnownPaths: false) + ); SerializationSnapshot before = host.serialization.CaptureSnapshot(scene, context); Assert.Equal(host.serialization.Serialize(scene, context), before.ToArray()); Assert.Same(before, host.serialization.CaptureSnapshot(scene, context, before)); @@ -168,37 +175,10 @@ public void FailedCapturePreservesTheSavedBaselineAndRecoversWithoutPublishingCl private static byte[] Hash( NativeProjectPanelHost host, GameScene scene - ) => SHA256.HashData(host.serialization.Serialize(scene, - AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)))); -} - -[StableTypeId("942e794b-1c53-45a6-80e6-a641d76fdd09")] -[AllowMultipleComponent] -internal sealed class DirtyCaptureComponent : GameComponent -{ - [SerializableProperty] public int number; - [SerializableProperty] public GameObject? target; - [SerializableProperty] public DirtyCaptureValue state { get; set; } = new(); -} - -internal sealed class DirtyCaptureValue -{ - internal int value; - internal bool reject; - internal int reads; -} - -internal sealed class DirtyCaptureValueConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - DirtyCaptureValue value - ) { - value.reads++; - writer.Write("value", value.value); - if (value.reject) - throw new InvalidOperationException("The test-owned converter rejected capture."); - } - - public override DirtyCaptureValue Read(SerializationReader reader) => new() { value = reader.Read("value") }; + ) => SHA256.HashData( + host.serialization.Serialize( + scene, + AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)) + ) + ); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs index 73aee6ff6..b81737286 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; +using Xunit; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -22,9 +22,11 @@ public void OneHundredSavedSceneCyclesRetireLiveScenesAndPreserveSourceAndHistor byte[] source = File.ReadAllBytes(Path.Combine(host.projectRoot, "Assets", path)); Assert.True(host.edits.CloseScene(original)); EditorPanelExtension panel = host.native.GetPanel("scene.hierarchy"); - var retired = new List>(); + List> retired = []; for (int iteration = 0; iteration < 100; iteration++) + { retired.Add(OpenDrawAndClose(host, panel, path)); + } Assert.Empty(host.workspace.scenes); Assert.True(host.runtime.interactions.history.canUndo); Assert.Equal(source, File.ReadAllBytes(Path.Combine(host.projectRoot, "Assets", path))); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs index eb804f06f..7e9aa6b85 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs @@ -2,16 +2,16 @@ using System.IO; using System.Linq; using System.Numerics; -using System.Collections.Generic; using System.Runtime.CompilerServices; +using Xunit; +using Xunit.Sdk; using Inno.Core.IO; -using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Editor.Interactions; using Inno.Editor.Settings; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -29,7 +29,7 @@ public void FaultedDrawerReleasesReloadAdmissionUntilItsExtensionsRecover() AtomicEditorSetting.throwOnDraw = true; try { - Assert.ThrowsAny(() => driver.Search("Atomic Editor")); + Assert.ThrowsAny(() => driver.Search("Atomic Editor")); } finally { @@ -54,42 +54,31 @@ public void FaultedDrawerReleasesReloadAdmissionUntilItsExtensionsRecover() [Trait("Acceptance", "Lifecycle")] public void OneHundredSettingsCyclesReleaseDrawnValuesAndReloadAdmission() { - AtomicEditorSetting.snapshots.Clear(); + AtomicEditorSetting.SNAPSHOTS.Clear(); AtomicEditorSetting.observe = true; try { - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true + ); for (int cycle = 0; cycle < 100; cycle++) + { OpenAndClose(host); - Assert.True(AtomicEditorSetting.snapshots.Count >= 100); + } + Assert.True(AtomicEditorSetting.SNAPSHOTS.Count >= 100); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); - Assert.All(AtomicEditorSetting.snapshots, snapshot => Assert.False(snapshot.TryGetTarget(out _))); + Assert.All(AtomicEditorSetting.SNAPSHOTS, snapshot => Assert.False(snapshot.TryGetTarget(out _))); } finally { AtomicEditorSetting.observe = false; - AtomicEditorSetting.snapshots.Clear(); + AtomicEditorSetting.SNAPSHOTS.Clear(); } } - [MethodImpl(MethodImplOptions.NoInlining)] - private static void OpenAndClose(NativeProjectPanelHost host) - { - Assert.True(host.reloads.CanRequestReload(out _)); - Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); - var driver = new SettingsInput(host); - driver.Draw(); - Assert.False(host.reloads.CanActivateReload(out string? reason)); - Assert.Contains("Settings", reason); - driver.Search("Atomic Editor"); - driver.CloseClean(); - Assert.False(driver.isVisible); - Assert.True(host.reloads.CanRequestReload(out _)); - Assert.True(host.reloads.CanActivateReload(out _)); - } - [Fact] [Trait("Acceptance", "Workflows")] public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() @@ -98,9 +87,15 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() Directory.CreateDirectory(directory); try { - var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document); - Assert.True(host.runtime.interactions.TryGetModule(out var editor)); + var document = new FailingSettingsDocument( + new FileByteDocumentStore(Path.Combine(directory, "Project.inno")) + ); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true, + settingsDocument: document + ); + Assert.True(host.runtime.interactions.TryGetModule(out EditorSettings? editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); driver.Draw(); @@ -116,7 +111,9 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() using IDisposable listener = editor!.ListenChanges(_ => { if (obstructed) + { return; + } File.Move(editorFile, savedFile); Directory.CreateDirectory(editorFile); obstructed = true; @@ -127,7 +124,7 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() driver.Apply(); Assert.True(obstructed); Assert.Equal(42, editor.Get("Editor/Atomic Editor/Value").GetAsInt32("value")); - Assert.Equal(0, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(0, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); Assert.True(host.runtime.interactions.history.isFaulted); Assert.False(host.runtime.interactions.history.canUndo); Assert.False(host.runtime.interactions.history.canRedo); @@ -144,10 +141,15 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() document.failWrites = false; driver.Apply(); Assert.True(host.runtime.interactions.history.isFaulted); - Assert.Equal(0, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(0, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); driver.Cancel(); host.native.logs.Flush(); - Assert.False(driver.isVisible, driver.diagnostic + Environment.NewLine + string.Join(Environment.NewLine, host.native.console.Capture().occurrences.Select(entry => entry.message))); + Assert.False( + driver.isVisible, + driver.diagnostic + + Environment.NewLine + + string.Join(Environment.NewLine, host.native.console.Capture().occurrences.Select(entry => entry.message)) + ); } finally { @@ -165,9 +167,15 @@ public void FailedSettingsBatchPreservesAllOwnersAndDraftsForRetry() Directory.CreateDirectory(directory); try { - var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document); - Assert.True(host.runtime.interactions.TryGetModule(out var editor)); + var document = new FailingSettingsDocument( + new FileByteDocumentStore(Path.Combine(directory, "Project.inno")) + ); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true, + settingsDocument: document + ); + Assert.True(host.runtime.interactions.TryGetModule(out EditorSettings? editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); driver.Draw(); @@ -180,20 +188,20 @@ public void FailedSettingsBatchPreservesAllOwnersAndDraftsForRetry() document.failWrites = true; driver.Apply(); Assert.Equal(0, editor!.Get("Editor/Atomic Editor/Value").GetAsInt32("value")); - Assert.Equal(0, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(0, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); Assert.False(host.runtime.interactions.history.canUndo); Assert.False(host.runtime.interactions.history.isFaulted); document.failWrites = false; driver.Apply(); Assert.Equal(42, editor.Get("Editor/Atomic Editor/Value").GetAsInt32("value")); - Assert.Equal(84, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(84, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); Assert.True(host.runtime.interactions.history.Undo().succeeded); Assert.Equal(0, editor.Get("Editor/Atomic Editor/Value").GetAsInt32("value")); - Assert.Equal(0, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(0, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); Assert.False(host.runtime.interactions.history.canUndo); Assert.True(host.runtime.interactions.history.Redo().succeeded); Assert.Equal(42, editor.Get("Editor/Atomic Editor/Value").GetAsInt32("value")); - Assert.Equal(84, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); + Assert.Equal(84, host.projectSettings.Get(new ProjectSettingID("tests.ui.atomic-settings")).value); } finally { @@ -203,19 +211,40 @@ public void FailedSettingsBatchPreservesAllOwnersAndDraftsForRetry() } } + [MethodImpl(MethodImplOptions.NoInlining)] + private static void OpenAndClose(NativeProjectPanelHost host) + { + Assert.True(host.reloads.CanRequestReload(out _)); + Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); + var driver = new SettingsInput(host); + driver.Draw(); + Assert.False(host.reloads.CanActivateReload(out string? reason)); + Assert.Contains("Settings", reason); + driver.Search("Atomic Editor"); + driver.CloseClean(); + Assert.False(driver.isVisible); + Assert.True(host.reloads.CanRequestReload(out _)); + Assert.True(host.reloads.CanActivateReload(out _)); + } + private sealed class FailingSettingsDocument(IByteDocumentStore owner) : IByteDocumentStore { - internal bool failWrites { get; set; } public string documentName => owner.documentName; public bool canWrite => owner.canWrite; public bool exists => owner.exists; + public byte[]? Read() => owner.Read(); + public void Write(ReadOnlySpan data) { if (failWrites) + { throw new IOException("Controlled project settings publication failure."); + } owner.Write(data); } + + internal bool failWrites { get; set; } } private sealed class SettingsInput(NativeProjectPanelHost host) @@ -227,8 +256,7 @@ private sealed class SettingsInput(NativeProjectPanelHost host) internal string diagnostic => $"Apply={m_apply}; Cancel={m_cancel}; Search={m_search}"; internal void Draw() - { - host.native.Frame(() => + => host.native.Frame(() => { NativeGui.SetNextWindowPos(new Vector2(20f), (int)ImGuiCond.Always); NativeGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); @@ -239,22 +267,26 @@ internal void Draw() Vector2 content = NativeGui.GetCursorScreenPos(); m_search = content + new Vector2(115f, NativeGui.GetFrameHeight() * 0.5f + 3f); EditorModalExtension modal = Assert.Single(host.runtime.modals, modal => modal.id == "editor.settings"); - Assert.True(modal.TryGetPresentation(out var presentation)); + Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); isVisible = presentation.isVisible; if (!isVisible) + { return; + } Assert.True(modal.Draw(host.runtime.context), "The operational Settings failure must not quarantine the modal."); m_apply = (NativeGui.GetItemRectMin() + NativeGui.GetItemRectMax()) * 0.5f; - var style = NativeGui.Raw.GetStyle(); - m_cancel = new Vector2(NativeGui.GetItemRectMin().X - style->ItemSpacing.X - - NativeGui.CalcTextSize("Cancel").X * 0.5f - style->FramePadding.X, m_apply.Y); + ImGuiStyle* style = NativeGui.Raw.GetStyle(); + m_cancel = new Vector2( + NativeGui.GetItemRectMin().X - style->ItemSpacing.X + - NativeGui.CalcTextSize("Cancel").X * 0.5f - style->FramePadding.X, + m_apply.Y + ); } finally { NativeGui.End(); } }); - } internal void Search(string text) { @@ -267,13 +299,17 @@ internal void Search(string text) NativeGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 0); Draw(); foreach (char character in text) + { NativeGui.Raw.AddInputCharacter(io, character); + } Draw(); Draw(); } internal void Apply() => Click(m_apply); + internal void Cancel() => Click(m_cancel); + internal void CloseClean() => Click(m_apply); private void Click(Vector2 point) @@ -289,53 +325,3 @@ private void Click(Vector2 point) } } } - -[EditorSettingPath("Editor/Atomic Editor/Value")] -public sealed class AtomicEditorSetting : EditorSetting -{ - public static bool stage; - public static bool throwOnDraw; - public static bool observe; - public static readonly List> snapshots = []; - public override EditorSettingObject defaultValue - { - get - { - var value = new EditorSettingObject(); - value.SetAsInt32("value", 0); - return value; - } - } - protected override void OnDraw(EditorSettingObject setting) - { - if (throwOnDraw) - throw new InvalidOperationException("Controlled Settings drawer failure."); - if (observe && (snapshots.Count == 0 || !snapshots[^1].TryGetTarget(out var last) || !ReferenceEquals(last, setting))) - snapshots.Add(new WeakReference(setting)); - if (!stage) - return; - setting.SetAsInt32("value", 42); - stage = false; - } -} - -[GenerateSerializationConverter] -[ProjectSettingDefinition("tests.ui.atomic-settings")] -public sealed class AtomicProjectSetting : ISerializable -{ - [SerializableProperty] - public int value { get; set; } -} - -[ProjectSettingPath("Project/Atomic Project/Value")] -public sealed class AtomicProjectEditor : ProjectSettingEditor -{ - public static bool stage; - protected override void OnDraw(AtomicProjectSetting setting) - { - if (!stage) - return; - setting.value = 84; - stage = false; - } -} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs index 748873b82..a3400822b 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs @@ -1,11 +1,13 @@ using System; using System.Numerics; +using Xunit; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + +using Gui = Inno.Editor.ImGui.ImGui; +using GuiCol = Inno.Editor.ImGui.ImGuiCol; using NativeImGui = Inno.Native.ImGui.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -18,7 +20,9 @@ public void ActualPanelSamplesAtHalfSecondIntervalsAndResetsAfterHiddenFrames() EditorPanelExtension panel = host.GetPanel("diagnostics.stats"); Assert.Equal(0, DrawAndCountTrendVertices(host, panel, 0.1f)); for (int frame = 0; frame < 4; frame++) + { Assert.Equal(0, DrawAndCountTrendVertices(host, panel, 0.1f)); + } int twoSampleVertices = DrawAndCountTrendVertices(host, panel, 0.1f); Assert.True(twoSampleVertices > 0); panel.isOpen = false; @@ -58,13 +62,13 @@ float deltaTime int count = 0; host.Frame(() => { - NativeImGui.SetNextWindowPos(new(20f, 20f), (int)ImGuiCond.Always); - NativeImGui.SetNextWindowSize(new(1000f, 800f), (int)ImGuiCond.Always); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)ImGuiCond.Always); + NativeImGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); bool open = true; _ = NativeImGui.Begin("Statistics acceptance", ref open, (int)ImGuiWindowFlags.NoSavedSettings); - Vector4 color = new(0.93f, 0.17f, 0.73f, 1f); - uint packed = Ui.ToPackedColor(color); - Ui.PushStyleColor(Inno.Editor.ImGui.ImGuiCol.PlotLines, color); + var color = new Vector4(0.93f, 0.17f, 0.73f, 1f); + uint packed = Gui.ToPackedColor(color); + Gui.PushStyleColor(GuiCol.PlotLines, color); try { Assert.True(panel.Draw(host.runtime.context)); @@ -72,13 +76,15 @@ float deltaTime for (int index = 0; index < draw->VtxBuffer.Size; index++) { uint vertex = draw->VtxBuffer.Data[index].Col; - if ((vertex & 0x00ffffff) == (packed & 0x00ffffff) && (vertex >> 24) != 0) + if ((vertex & 0x00FF_FFFF) == (packed & 0x00FF_FFFF) && (vertex >> 24) != 0) + { count++; + } } } finally { - Ui.PopStyleColor(); + Gui.PopStyleColor(); NativeImGui.End(); } }, deltaTime); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs index ca080b306..ef94b0c86 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs @@ -1,13 +1,15 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + +using Gui = Inno.Editor.ImGui.ImGui; +using GuiInput = Inno.Editor.ImGui.EditorUIInput; using NativeImGui = Inno.Native.ImGui.ImGui; -using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -22,7 +24,11 @@ public void ListActivationDoesNotToggleDisclosureOrStealAnOverlayButton( bool commandKeyBehavior, KeyModifier primaryModifier ) { - using var host = new NativePanelHost(typeof(TreeKeyboardOwnershipNativeTests).Assembly, false, new EditorKeyboardPolicy(primaryModifier, "Super")); + using var host = new NativePanelHost( + typeof(TreeKeyboardOwnershipNativeTests).Assembly, + false, + new EditorKeyboardPolicy(primaryModifier, "Super") + ); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->ConfigMacOsxBehaviors = commandKeyBehavior ? (byte)1 : (byte)0; ImGuiKey primaryKey = primaryModifier == KeyModifier.Super ? ImGuiKey.ImGuiModSuper : ImGuiKey.ImGuiModCtrl; @@ -32,7 +38,7 @@ KeyModifier primaryModifier int toggles = 0; int overlayPresses = 0; bool initialize = true; - uint overlayId = 0; + uint overlayID = 0; string overlayState = string.Empty; ListNavigationResult navigation = default; Action draw = () => @@ -47,27 +53,39 @@ KeyModifier primaryModifier host.ui.widgets.SetNextTreeNodeOpen(true); initialize = false; } - TreeNodeResult row = host.ui.widgets.TreeNode("keyboard-row", _ => Ui.Text("A domain-independent row"), new() - { - requestFocus = rowFocus, - drawViewportOverlay = () => + TreeNodeResult row = host.ui.widgets.TreeNode( + "keyboard-row", + _ => Gui.Text("A domain-independent row"), + new TreeNodeOptions() { - NativeImGui.SameLine(0f, -1f); - if (overlayFocus) - Ui.FocusNextItem(); - if (NativeImGui.SmallButton("Overlay")) - overlayPresses++; - overlayId = NativeImGui.Raw.GetCurrentContext()->LastItemData.ID; - ImGuiNativeContext* state = NativeImGui.Raw.GetCurrentContext(); - overlayState = $"id={overlayId:X}, nav={state->NavId:X}, active={state->ActiveId:X}, activate={state->NavActivateId:X}, pressed={state->NavActivatePressedId:X}, keyOwner={NativeImGui.GetKeyOwner(ImGuiKey.Space):X}"; + requestFocus = rowFocus, + drawViewportOverlay = () => + { + NativeImGui.SameLine(0f, -1f); + if (overlayFocus) + { + Gui.FocusNextItem(); + } + if (NativeImGui.SmallButton("Overlay")) + { + overlayPresses++; + } + overlayID = NativeImGui.Raw.GetCurrentContext()->LastItemData.ID; + ImGuiNativeContext* state = NativeImGui.Raw.GetCurrentContext(); + overlayState = $"id={overlayID:X}, nav={state->NavId:X}, active={state->ActiveId:X}, activate={state->NavActivateId:X}, pressed={state->NavActivatePressedId:X}, keyOwner={NativeImGui.GetKeyOwner(ImGuiKey.Space):X}"; + } } - }); + ); open = row.isOpen; if (open) + { NativeImGui.TreePop(); + } navigation = host.ui.widgets.NavigateList(host.runtime.interactions, 1, 0); if (navigation.toggle) + { toggles++; + } } finally { @@ -86,7 +104,7 @@ KeyModifier primaryModifier Assert.Equal(0, overlayPresses); host.Frame(() => { - var input = Ui.GetInput(); + GuiInput input = Gui.GetInput(); Assert.Equal(primaryModifier == KeyModifier.Control, input.control); Assert.Equal(primaryModifier == KeyModifier.Super, input.super); draw(); @@ -98,7 +116,7 @@ KeyModifier primaryModifier host.Frame(draw); overlayFocus = false; host.Frame(draw); - Assert.Equal(overlayId, NativeImGui.Raw.GetCurrentContext()->NavId); + Assert.Equal(overlayID, NativeImGui.Raw.GetCurrentContext()->NavId); // Programmatic focus does not enter native keyboard navigation mode by itself. NativeImGui.SetNavCursorVisible(true); NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.Space, 1); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs index c0d6888c3..30c729b64 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs @@ -2,10 +2,14 @@ using System.Collections.Generic; using System.Numerics; using System.Runtime.CompilerServices; +using Xunit; using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + +using GuiCond = Inno.Editor.ImGui.ImGuiCond; +using GuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeGui = Inno.Native.ImGui.ImGui; using NativeVector = Inno.Native.ImGui.ImVec2C; @@ -13,14 +17,6 @@ namespace Inno.Editor.PlayMode.Tests; public sealed unsafe class VisualScaleMatrixTests { - public static IEnumerable Metrics() - { - foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) - foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) - foreach (Vector2 size in new[] { new Vector2(1280f, 720f), new Vector2(1920f, 1080f) }) - yield return [zoom, density, size.X, size.Y]; - } - [Theory] [MemberData(nameof(Metrics))] [Trait("Acceptance", "Visual")] @@ -32,8 +28,8 @@ float height ) { using var host = new NativePanelHost(typeof(VisualScaleMatrixTests).Assembly); ImGuiIO* io = NativeGui.Raw.GetIO(); - io->DisplaySize = Unsafe.BitCast(new(width, height)); - io->DisplayFramebufferScale = Unsafe.BitCast(new(density)); + io->DisplaySize = Unsafe.BitCast(new Vector2(width, height)); + io->DisplayFramebufferScale = Unsafe.BitCast(new Vector2(density)); host.ui.widgets.style.SetZoom(zoom); float labelWidth = 0f; float valueWidth = 0f; @@ -41,23 +37,27 @@ float height { host.Frame(() => { - NativeGui.SetNextWindowPos(new Vector2(20f, 20f), (int)Inno.Editor.ImGui.ImGuiCond.Always); - NativeGui.SetNextWindowSize(new Vector2(320f, 500f), (int)Inno.Editor.ImGui.ImGuiCond.Always); + NativeGui.SetNextWindowPos(new Vector2(20f, 20f), (int)GuiCond.Always); + NativeGui.SetNextWindowSize(new Vector2(320f, 500f), (int)GuiCond.Always); bool open = true; - _ = NativeGui.Begin("Narrow inspector matrix", ref open, (int)Inno.Editor.ImGui.ImGuiWindowFlags.NoSavedSettings); + _ = NativeGui.Begin("Narrow inspector matrix", ref open, (int)GuiWindowFlags.NoSavedSettings); try { - var widgets = host.ui.widgets; - widgets.PropertyRow("reference", () => - { - labelWidth = NativeGui.GetContentRegionAvail().X; - widgets.PropertyLabel("Resource reference / 资源引用 / Missing"); - }, () => - { - valueWidth = NativeGui.GetContentRegionAvail().X; - string value = "Unassigned / 未指定"; - widgets.Disabled(true, () => NativeGui.TextUnformatted(value)); - }); + ImGuiWidget widgets = host.ui.widgets; + widgets.PropertyRow( + "reference", + () => + { + labelWidth = NativeGui.GetContentRegionAvail().X; + widgets.PropertyLabel("Resource reference / 资源引用 / Missing"); + }, + () => + { + valueWidth = NativeGui.GetContentRegionAvail().X; + string value = "Unassigned / 未指定"; + widgets.Disabled(true, () => NativeGui.TextUnformatted(value)); + } + ); widgets.MixedValue(true, () => Assert.True(widgets.isMixedValue)); Assert.False(widgets.isMixedValue); Assert.Equal(zoom, widgets.style.zoom); @@ -73,4 +73,18 @@ float height Assert.InRange(labelWidth / (labelWidth + valueWidth), 0.37f, 0.42f); Assert.True(float.IsFinite(labelWidth) && float.IsFinite(valueWidth)); } + + public static IEnumerable Metrics() + { + foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) + { + foreach (float density in new[] { 1f, 1.25f, 1.5f, 2f }) + { + foreach (Vector2 size in new[] { new Vector2(1280f, 720f), new Vector2(1920f, 1080f) }) + { + yield return [zoom, density, size.X, size.Y]; + } + } + } + } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs new file mode 100644 index 000000000..f06fbfff5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs @@ -0,0 +1,36 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.dispose-observer", order: 900)] +public sealed class ADisposeObserverModule(EditorInteractions interactions) : EditorModule +{ + public static bool historyAvailableDuringStop; + public static bool historyDisposedDuringDispose; + public static int disposeCount; + + protected override void OnStop(EditorContext context) + { + if (interactions.history.isFaulted) + { + return; + } + using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Shutdown probe"); + historyAvailableDuringStop = transaction.Rollback().succeeded; + } + + protected override void OnDispose() + { + disposeCount++; + try + { + using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Disposed probe"); + } + catch (ObjectDisposedException) + { + historyDisposedDuringDispose = true; + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs new file mode 100644 index 000000000..6fff125a4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.resolve", "tests/special", priority: 100)] +public sealed class AreaResolveAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "area"); + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs index 3518d7454..c7d0d4873 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs @@ -1,28 +1,31 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; -using Inno.Extensibility.Modules; +using Inno.Core.IO; using Inno.Core.Identity; +using Inno.Core.Input; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; +using Inno.Editor.Core; +using Inno.Editor.ImGui; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.Plugins.Authoring; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed class AssetHistoryTests : IDisposable { - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUISession m_ui = new(); private readonly IdentityAllocator m_identities = new(); private readonly IDisposable m_identityScope; private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoAssetHistoryTests", Guid.NewGuid().ToString("N")); @@ -35,6 +38,7 @@ public sealed class AssetHistoryTests : IDisposable private readonly PluginEnvironment m_plugins; private readonly ProjectSettingsStore m_settings; private readonly EditorInteractionRuntime m_runtime; + public AssetHistoryTests() { string assetRoot = Path.Combine(m_projectRoot, "Assets"); @@ -42,7 +46,9 @@ public AssetHistoryTests() m_identityScope = m_identities.EnterScope(); _ = typeof(AssetEditingModule); _ = typeof(TextAsset); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetHistoryTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetHistoryTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); string libraryRoot = Path.Combine(m_projectRoot, "Library"); @@ -59,12 +65,20 @@ public AssetHistoryTests() new FileByteDocumentStore(Path.GetFullPath(Path.Combine(m_projectRoot, "Settings.Project.inno"))), m_types, m_serialization, - new ProjectId("tests.editor"), + new ProjectID("tests.editor"), AssetSerializationContext.Create(m_assets) ); - m_plugins = new PluginEnvironment(m_assets, m_settings, m_serialization, pluginRoot, libraryRoot, pluginScan, m_modules.generations); + m_plugins = new PluginEnvironment( + m_assets, + m_settings, + m_serialization, + pluginRoot, + libraryRoot, + pluginScan, + m_modules.generations + ); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization, m_identities, m_assets, m_plugins, m_ui] @@ -85,7 +99,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -123,15 +139,15 @@ public void DeleteFolderUndoRestoresIdentityMetadataAndEmptyDescendants() { m_assets.CreateDirectory(AssetPath.Project("Folder")); m_assets.CreateDirectory(AssetPath.Project("Folder/Empty")); - Assert.True(m_assets.TryGetPersistentId(AssetPath.Project("Folder"), out Guid folderId)); + Assert.True(m_assets.TryGetPersistentID(AssetPath.Project("Folder"), out Guid folderID)); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("Folder"), out AssetFileEntry folder)); Assert.True(m_runtime.interactions.For("panel/asset.file-browser", folder).Execute("file-browser/delete")); Assert.False(m_assets.TryGetFileSystemEntry(AssetPath.Project("Folder"), out _)); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("Folder/Empty"), out AssetFileEntry restoredEmpty)); Assert.True(restoredEmpty.isDirectory); - Assert.True(m_assets.TryGetPersistentId(AssetPath.Project("Folder"), out Guid restoredId)); - Assert.Equal(folderId, restoredId); + Assert.True(m_assets.TryGetPersistentID(AssetPath.Project("Folder"), out Guid restoredID)); + Assert.Equal(folderID, restoredID); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.False(m_assets.TryGetFileSystemEntry(AssetPath.Project("Folder"), out _)); } @@ -157,7 +173,9 @@ public void FileBrowserDropMovesFilesAndFoldersWithUndoRedo() m_assets.CreateDirectory(AssetPath.Project("To")); Assert.True(m_assets.Save(AssetPath.Project("From/Value.txt"), new TextAsset("value"))); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("From/Value.txt"), out AssetFileEntry file)); - RuntimeIdentity fileToken = m_runtime.interactions.For("panel/asset.file-browser", file).BeginDrag(new EditorDragData(file, "Value.txt")); + RuntimeIdentity fileToken = m_runtime.interactions + .For("panel/asset.file-browser", file) + .BeginDrag(new EditorDragData(file, "Value.txt")); EditorInteraction destination = m_runtime.interactions.For("panel/asset.file-browser", "To"); Assert.True(destination.QueryDrop(fileToken, EditorDropPlacement.Into).canDrop); Assert.True(destination.Drop(fileToken, EditorDropPlacement.Into).accepted); @@ -168,7 +186,9 @@ public void FileBrowserDropMovesFilesAndFoldersWithUndoRedo() Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("To/Value.txt"), out _)); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("From/Folder"), out AssetFileEntry folder)); - RuntimeIdentity folderToken = m_runtime.interactions.For("panel/asset.file-browser", folder).BeginDrag(new EditorDragData(folder, "Folder")); + RuntimeIdentity folderToken = m_runtime.interactions + .For("panel/asset.file-browser", folder) + .BeginDrag(new EditorDragData(folder, "Folder")); Assert.True(destination.QueryDrop(folderToken, EditorDropPlacement.Into).canDrop); Assert.True(destination.Drop(folderToken, EditorDropPlacement.Into).accepted); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("To/Folder/Child"), out _)); @@ -184,9 +204,19 @@ public void FileBrowserDropRejectsAFolderOwnDescendantAndNameCollisions() m_assets.CreateDirectory(AssetPath.Project("Target")); m_assets.CreateDirectory(AssetPath.Project("Target/Source")); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("Source"), out AssetFileEntry source)); - RuntimeIdentity descendantToken = m_runtime.interactions.For("panel/asset.file-browser", source).BeginDrag(new EditorDragData(source, "Source")); - Assert.False(m_runtime.interactions.For("panel/asset.file-browser", "Source/Child").QueryDrop(descendantToken, EditorDropPlacement.Into).canDrop); - RuntimeIdentity collisionToken = m_runtime.interactions.For("panel/asset.file-browser", source).BeginDrag(new EditorDragData(source, "Source")); - Assert.False(m_runtime.interactions.For("panel/asset.file-browser", "Target").QueryDrop(collisionToken, EditorDropPlacement.Into).canDrop); + RuntimeIdentity descendantToken = m_runtime.interactions + .For("panel/asset.file-browser", source) + .BeginDrag(new EditorDragData(source, "Source")); + Assert.False( + m_runtime.interactions + .For("panel/asset.file-browser", "Source/Child") + .QueryDrop(descendantToken, EditorDropPlacement.Into).canDrop + ); + RuntimeIdentity collisionToken = m_runtime.interactions + .For("panel/asset.file-browser", source) + .BeginDrag(new EditorDragData(source, "Source")); + Assert.False( + m_runtime.interactions.For("panel/asset.file-browser", "Target").QueryDrop(collisionToken, EditorDropPlacement.Into).canDrop + ); } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs new file mode 100644 index 000000000..f8b0ece96 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.resolve")] +public sealed class BaseResolveAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "base"); + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs new file mode 100644 index 000000000..b771631d5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs @@ -0,0 +1,4 @@ +namespace Inno.Editor.Presentation.Tests; + +// Open: DerivedTarget derives from it for the action-resolution tests. +public class BaseTarget; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs new file mode 100644 index 000000000..dd7384bc0 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs @@ -0,0 +1,27 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.commit-on-presentation-lost")] +public sealed class CommitOnPresentationLostAction : EditorAction +{ + private InteractionTarget? m_target; + + protected override void Execute(EditorActionContext context) + { + m_target = context.target; + Activate(context); + } + + protected override void OnPresentationLost() + { + if (m_target is not null) + { + m_target.committedValue = "Committed on focus loss"; + } + m_target = null; + Complete(); + } + + protected override void OnCancelled() => m_target = null; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs new file mode 100644 index 000000000..35514c600 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.deferred")] +public sealed class DeferredAction : EditorAction +{ + public static int executeCount; + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs new file mode 100644 index 000000000..fa4f16b89 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class DerivedTarget : BaseTarget; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs new file mode 100644 index 000000000..32cdb2986 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs @@ -0,0 +1,5 @@ +using Inno.Core.Identity; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class DragSource : IdentityObject; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs new file mode 100644 index 000000000..204c3fd8b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs @@ -0,0 +1,6 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class DropTarget +{ + public bool wasDropped { get; set; } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs new file mode 100644 index 000000000..473d26a60 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorMenuSource("tests/menu")] +public sealed class DynamicMenuSource : EditorMenuSource +{ + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + builder.AddGroup("Tools/Create/Libraries", order: 150, separatorBefore: true); + builder.Add("Tools/Create/Libraries/Function", "tests.menu", order: 150); + builder.Add("Tools/Create/Generated", "tests.menu", order: 200); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs index 5d682f6c9..67c7621ac 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs @@ -1,8 +1,8 @@ using System; -using System.Linq; +using Xunit; +using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Interactions; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -12,7 +12,7 @@ public sealed partial class EditorRuntimeTests public void StaticMenuTemplatesKeepAvailabilityLabelsAndReasonsFresh() { var target = new MenuStateTarget(); - var interaction = m_runtime.interactions.For("tests/static-menu", target); + EditorInteraction interaction = m_runtime.interactions.For("tests/static-menu", target); for (int index = 0; index < 3; index++) { target.label = "Current " + index; @@ -37,12 +37,12 @@ public void StaticMenuTemplatesKeepAvailabilityLabelsAndReasonsFresh() public void HiddenHigherOrderPlacementDoesNotEraseTheVisibleAction() { var target = new MenuStateTarget { visible = false }; - var interaction = m_runtime.interactions.For("tests/shared-menu", target); - Assert.Equal("tests.menu-fallback", Assert.Single(interaction.BuildMenu().items).actionId); + EditorInteraction interaction = m_runtime.interactions.For("tests/shared-menu", target); + Assert.Equal("tests.menu-fallback", Assert.Single(interaction.BuildMenu().items).actionID); target.visible = true; - Assert.Equal("tests.menu-conditional", Assert.Single(interaction.BuildMenu().items).actionId); + Assert.Equal("tests.menu-conditional", Assert.Single(interaction.BuildMenu().items).actionID); target.visible = false; - Assert.Equal("tests.menu-fallback", Assert.Single(interaction.BuildMenu().items).actionId); + Assert.Equal("tests.menu-fallback", Assert.Single(interaction.BuildMenu().items).actionID); GC.KeepAlive(target); } @@ -57,61 +57,12 @@ public void FailedDynamicSourceCannotPublishItsPartialMenu() public void ShortcutIndexRefreshPreservesDispatchAndRejectsRepeats() { m_runtime.interactions.For("tests/multiple-shortcuts").Focus(); - m_runtime.HandleKeyPressed(new(0, KeyCode.F3)); + m_runtime.HandleKeyPressed(new KeyPressedEvent(0, KeyCode.F3)); Assert.Equal(1, MultiShortcutAction.executeCount); m_types.Rebuild(); - m_runtime.HandleKeyPressed(new(0, KeyCode.F4)); + m_runtime.HandleKeyPressed(new KeyPressedEvent(0, KeyCode.F4)); Assert.Equal(2, MultiShortcutAction.executeCount); - m_runtime.HandleKeyPressed(new(0, KeyCode.F4, repeat: true)); + m_runtime.HandleKeyPressed(new KeyPressedEvent(0, KeyCode.F4, repeat: true)); Assert.Equal(2, MultiShortcutAction.executeCount); } } - -public sealed class MenuStateTarget -{ - public bool visible = true; - public bool enabled = true; - public bool isChecked; - public string label = "Current"; -} - -[EditorAction("tests.menu-state", "tests/static-menu")] -[EditorMenu("tests/static-menu", "Tools/State")] -public sealed class MenuStateAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) - => context.target is MenuStateTarget target - ? new(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") - : EditorActionState.hidden; - - protected override void Execute(EditorActionContext context) { } -} - -[EditorAction("tests.menu-fallback", "tests/shared-menu")] -[EditorMenu("tests/shared-menu", "Shared", order: 100)] -public sealed class MenuFallbackAction : EditorAction -{ - protected override void Execute(EditorActionContext context) { } -} - -[EditorAction("tests.menu-conditional", "tests/shared-menu")] -[EditorMenu("tests/shared-menu", "Shared", order: 200)] -public sealed class MenuConditionalAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) - => context.target is MenuStateTarget { visible: true } ? EditorActionState.enabled : EditorActionState.hidden; - - protected override void Execute(EditorActionContext context) { } -} - -[EditorMenuSource("tests/failed-menu")] -public sealed class RejectedMenuSource : EditorMenuSource -{ - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - builder.Add("Partial", "tests.menu"); - throw new InvalidOperationException("Candidate menu source failed."); - } -} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs index e45ff0d3d..862e0b126 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs @@ -1,10 +1,11 @@ using System; using System.Diagnostics; using System.Text.Json; +using Xunit; using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Core; -using Xunit; +using Inno.Editor.Interactions; namespace Inno.Editor.Presentation.Tests; @@ -14,7 +15,7 @@ public sealed partial class EditorRuntimeTests [Trait("Category", "Performance")] public void PublicCommandAndStatisticsPathsProduceRepeatableSamples() { - var interaction = m_runtime.interactions.For("tests/menu"); + EditorInteraction interaction = m_runtime.interactions.For("tests/menu"); Measure("menu-open", () => Assert.NotEmpty(interaction.BuildMenu().items)); m_runtime.interactions.For("tests/multiple-shortcuts").Focus(); int beforeDispatch = MultiShortcutAction.executeCount; @@ -25,13 +26,16 @@ public void PublicCommandAndStatisticsPathsProduceRepeatableSamples() var statistics = new EditorStatistics(); for (int index = 0; index < 100; index++) { - statistics.Publish(new EditorStatistic( - new("metric/" + index), - new("group/" + index / 10), - "Group " + index / 10, - "Metric " + index, - index.ToString(), - order: index)); + statistics.Publish( + new EditorStatistic( + new EditorStatisticID("metric/" + index), + new EditorStatisticGroupID("group/" + index / 10), + "Group " + index / 10, + "Metric " + index, + index.ToString(), + order: index + ) + ); } Measure("statistics-unchanged", () => Assert.Equal(100, statistics.GetSnapshot().Count)); } @@ -40,10 +44,12 @@ private static void Measure( string name, Action operation ) { - const int iterations = 2_000; + const int C_ITERATIONS = 2_000; using Process process = Process.GetCurrentProcess(); for (int warmup = 0; warmup < 200; warmup++) + { operation(); + } for (int sample = 0; sample < 5; sample++) { TimeSpan cpu = process.TotalProcessorTime; @@ -52,18 +58,26 @@ Action operation int gen2 = GC.CollectionCount(2); long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); - for (int iteration = 0; iteration < iterations; iteration++) + for (int iteration = 0; iteration < C_ITERATIONS; iteration++) + { operation(); + } double milliseconds = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long bytes = GC.GetAllocatedBytesForCurrentThread() - before; - Console.WriteLine(JsonSerializer.Serialize(new - { - workload = name, sample, iterations, milliseconds, bytes, - cpuMilliseconds = (process.TotalProcessorTime - cpu).TotalMilliseconds, - gen0 = GC.CollectionCount(0) - gen0, - gen1 = GC.CollectionCount(1) - gen1, - gen2 = GC.CollectionCount(2) - gen2 - })); + Console.WriteLine( + JsonSerializer.Serialize(new + { + workload = name, + sample, + C_ITERATIONS, + milliseconds, + bytes, + cpuMilliseconds = (process.TotalProcessorTime - cpu).TotalMilliseconds, + gen0 = GC.CollectionCount(0) - gen0, + gen1 = GC.CollectionCount(1) - gen1, + gen2 = GC.CollectionCount(2) - gen2 + }) + ); } } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs index c7dd30f93..b1b5b8515 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs @@ -1,12 +1,15 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Threading; +using Xunit; +using Inno.Core.Events; using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed partial class EditorRuntimeTests { [Fact] @@ -18,10 +21,12 @@ public void MissingIdentityRejectsTheEntireVisibleRangeWithoutChangingSelection( Assert.True(m_identities.Register(last)); m_runtime.interactions.SetSelection(first); EditorSelectionSnapshot original = m_runtime.interactions.selection.Capture(); - RuntimeIdentity firstId = first.identity.runtimeIdentity!.Value; - RuntimeIdentity missing = new(firstId.domainId, int.MaxValue); + RuntimeIdentity firstID = first.identity.runtimeIdentity!.Value; + var missing = new RuntimeIdentity(firstID.domainID, int.MaxValue); Assert.Throws(() => m_runtime.interactions.SelectRange( - [firstId, missing, last.identity.runtimeIdentity!.Value], last)); + [firstID, missing, last.identity.runtimeIdentity!.Value], + last + )); Assert.Same(original, m_runtime.interactions.selection.Capture()); Assert.Same(first, m_runtime.interactions.selection.selectedTarget); } @@ -42,7 +47,9 @@ public void LargeIdentityRangesKeepOrderedPrimaryAndIndexedMembership() Assert.Equal(targets.Length, m_runtime.interactions.selection.count); Assert.Same(targets[^1], m_runtime.interactions.selection.selectedTarget); foreach (SelectionQueueTarget target in targets) + { Assert.True(m_runtime.interactions.selection.Contains(target)); + } m_runtime.interactions.SetSelection(targets[0]); Assert.False(m_runtime.interactions.selection.Contains(targets[^1])); } @@ -73,19 +80,6 @@ public void NeutralScalarSelectionRemainsAvailableWithoutAnotherOwner() Assert.Equal(value, Assert.IsType(m_runtime.interactions.selection.selectedTarget)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private void SelectScalarTarget(Guid value) => m_runtime.interactions.SetSelection(value); - - [MethodImpl(MethodImplOptions.NoInlining)] - private WeakReference SelectBoxedReferenceTarget() - { - var payload = new object(); - object target = new KeyValuePair("payload", payload); - m_runtime.interactions.SetSelection(target); - m_runtime.interactions.For("tests/boxed-target", target).Focus(); - return new WeakReference(payload); - } - [Fact] public void RejectedDomainRetirementOnAnotherThreadPreservesTheRoutingLease() { @@ -94,7 +88,7 @@ public void RejectedDomainRetirementOnAnotherThreadPreservesTheRoutingLease() Assert.True(allocator.Register(target)); using IDisposable registration = m_runtime.interactions.RegisterIdentityDomain(allocator); Exception? failure = null; - var worker = new System.Threading.Thread(() => failure = Record.Exception(registration.Dispose)); + var worker = new Thread(() => failure = Record.Exception(registration.Dispose)); worker.Start(); Assert.True(worker.Join(TimeSpan.FromSeconds(5))); Assert.IsType(failure); @@ -139,19 +133,20 @@ public void SelectionFinishesPendingEditsBeforeChangingAndPreservesStateWhenPrep Assert.True(m_identities.Register(first)); Assert.True(m_identities.Register(second)); m_runtime.interactions.SetSelection(first); - using var hub = m_runtime.interactions.events.CreateHub(); + using EventHub hub = m_runtime.interactions.events.CreateHub(); using var gesture = new EditorEditGesture(m_runtime.interactions.history, "Pending Input"); using (hub.Listen(_ => { Assert.Same(first, m_runtime.interactions.selection.selectedTarget); gesture.Commit(); - })) - { + })) { m_runtime.interactions.SetSelection(second); } Assert.False(gesture.isActive); ulong revision = m_runtime.interactions.selection.version; - using var rejecting = hub.Listen(_ => throw new InvalidOperationException("Pending edit cannot finish.")); + using IDisposable rejecting = hub.Listen( + _ => throw new InvalidOperationException("Pending edit cannot finish.") + ); Assert.Throws(() => m_runtime.interactions.SetSelection(first)); Assert.Throws(() => m_runtime.interactions.SetSelection([first], first)); Assert.Same(second, m_runtime.interactions.selection.selectedTarget); @@ -188,14 +183,20 @@ public void RangeSelectionUsesVisibleOrderAndTogglePreservesTheAnchor() Assert.True(m_identities.Register(second)); Assert.True(m_identities.Register(third)); m_runtime.interactions.SetSelection(first); - m_runtime.interactions.SelectRange([first.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, third.identity.runtimeIdentity!.Value], third); + m_runtime.interactions.SelectRange( + [first.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, third.identity.runtimeIdentity!.Value], + third + ); Assert.Equal(3, m_runtime.interactions.selection.count); m_runtime.interactions.ToggleSelection(second); Assert.False(m_runtime.interactions.selection.Contains(second)); Assert.Same(first, m_runtime.interactions.selection.anchor); Assert.Same(third, m_runtime.interactions.selection.selectedTarget); - m_runtime.interactions.SelectRange([third.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, first.identity.runtimeIdentity!.Value], second); - var targets = new List(); + m_runtime.interactions.SelectRange( + [third.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, first.identity.runtimeIdentity!.Value], + second + ); + List targets = []; Assert.Equal(2, m_runtime.interactions.selection.CopyTargets(targets)); Assert.Equal([first, second], targets); } @@ -259,6 +260,19 @@ public void QueuedSelectionAndFocusDoNotKeepRetiredIdentityObjectsAlive() m_runtime.Update(new EditorFrame()); } + [MethodImpl(MethodImplOptions.NoInlining)] + private void SelectScalarTarget(Guid value) => m_runtime.interactions.SetSelection(value); + + [MethodImpl(MethodImplOptions.NoInlining)] + private WeakReference SelectBoxedReferenceTarget() + { + var payload = new object(); + object target = new KeyValuePair("payload", payload); + m_runtime.interactions.SetSelection(target); + m_runtime.interactions.For("tests/boxed-target", target).Focus(); + return new WeakReference(payload); + } + [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference QueueAndRetireSelectionTarget() { diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs index d90070537..3e32881d2 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs @@ -1,6 +1,7 @@ +using System.Collections.Generic; using System.Linq; -using Inno.Editor.Core; using Xunit; +using Inno.Editor.Core; namespace Inno.Editor.Presentation.Tests; @@ -10,13 +11,19 @@ public sealed partial class EditorRuntimeTests public void UnchangedStatisticsReuseAnImmutableSnapshot() { var statistics = new EditorStatistics(); - statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "16 ms")); - var first = statistics.GetSnapshot(); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("frame"), new EditorStatisticGroupID("timing"), "Timing", "Frame", "16 ms") + ); + IReadOnlyList first = statistics.GetSnapshot(); Assert.Same(first, statistics.GetSnapshot()); - statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "16 ms")); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("frame"), new EditorStatisticGroupID("timing"), "Timing", "Frame", "16 ms") + ); Assert.Same(first, statistics.GetSnapshot()); - statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "8 ms")); - var changed = statistics.GetSnapshot(); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("frame"), new EditorStatisticGroupID("timing"), "Timing", "Frame", "8 ms") + ); + IReadOnlyList changed = statistics.GetSnapshot(); Assert.NotSame(first, changed); Assert.Equal("16 ms", Assert.Single(first).value); Assert.Equal("8 ms", Assert.Single(changed).value); @@ -26,29 +33,42 @@ public void UnchangedStatisticsReuseAnImmutableSnapshot() public void StatisticFrameHandoffRetainsLateProvidersAndRemovesExpiredContributions() { EditorStatistics statistics = m_runtime.context.statistics; - statistics.Publish(new EditorStatistic(new("first"), new("sampling"), "Sampling", "First", "1")); - var first = statistics.GetSnapshot(); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("first"), new EditorStatisticGroupID("sampling"), "Sampling", "First", "1") + ); + IReadOnlyList first = statistics.GetSnapshot(); m_runtime.Update(new EditorFrame(0.016f, 1f, isFocused: true)); Assert.Same(first, statistics.GetSnapshot()); - statistics.Publish(new EditorStatistic(new("second"), new("sampling"), "Sampling", "Second", "2")); - var combined = statistics.GetSnapshot(); - Assert.Equal(2, combined.Count(value => value.groupId == new EditorStatisticGroupId("sampling"))); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("second"), new EditorStatisticGroupID("sampling"), "Sampling", "Second", "2") + ); + IReadOnlyList combined = statistics.GetSnapshot(); + Assert.Equal(2, combined.Count(value => value.groupID == new EditorStatisticGroupID("sampling"))); m_runtime.Update(new EditorFrame(0.016f, 2f, isFocused: true)); - Assert.Equal("second", Assert.Single(statistics.GetSnapshot().Where(value => value.groupId == new EditorStatisticGroupId("sampling"))).id.value); + Assert.Equal( + "second", + Assert.Single(statistics.GetSnapshot().Where(value => value.groupID == new EditorStatisticGroupID("sampling"))).id.value + ); Assert.Equal(2, combined.Count); m_runtime.Update(new EditorFrame(0.016f, 3f, isFocused: true)); - Assert.DoesNotContain(statistics.GetSnapshot(), value => value.groupId == new EditorStatisticGroupId("sampling")); + Assert.DoesNotContain(statistics.GetSnapshot(), value => value.groupID == new EditorStatisticGroupID("sampling")); } [Fact] public void StatisticGroupingAndOrderChangesInvalidateTheSnapshot() { var statistics = new EditorStatistics(); - statistics.Publish(new EditorStatistic(new("a"), new("old"), "Old", "First", "1", groupOrder: 1)); - statistics.Publish(new EditorStatistic(new("b"), new("second"), "Second", "Second", "2", groupOrder: 2)); - var original = statistics.GetSnapshot(); - statistics.Publish(new EditorStatistic(new("b"), new("new"), "New", "Renamed", "2", groupOrder: 0)); - var changed = statistics.GetSnapshot(); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("a"), new EditorStatisticGroupID("old"), "Old", "First", "1", groupOrder: 1) + ); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("b"), new EditorStatisticGroupID("second"), "Second", "Second", "2", groupOrder: 2) + ); + IReadOnlyList original = statistics.GetSnapshot(); + statistics.Publish( + new EditorStatistic(new EditorStatisticID("b"), new EditorStatisticGroupID("new"), "New", "Renamed", "2", groupOrder: 0) + ); + IReadOnlyList changed = statistics.GetSnapshot(); Assert.NotSame(original, changed); Assert.Equal("b", changed[0].id.value); Assert.Equal("New", changed[0].groupName); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs index e527ee352..af88150f0 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs @@ -1,27 +1,25 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Events; -using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Input; using Inno.Core.Logging; -using Inno.Core.Serialization; -using Inno.Core.Settings; -using Inno.Extensibility.Types; +using Inno.Core.Mathematics; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.Interactions; -using Inno.Editor.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; namespace Inno.Editor.Presentation.Tests; + public sealed partial class EditorRuntimeTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorRuntimeTests", Guid.NewGuid().ToString("N")); @@ -33,11 +31,14 @@ public sealed partial class EditorRuntimeTests : IDisposable private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly EditorInteractionRuntime m_runtime; + public EditorRuntimeTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); m_diagnosticScope = m_diagnostics.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorRuntimeTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorRuntimeTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); TestModule.startCount = 0; TestModule.stopCount = 0; @@ -73,7 +74,7 @@ public EditorRuntimeTests() ZThrowingDisposeModule.disposeCount = 0; ZThrowingDisposeModule.throwOnDispose = false; ShutdownOrder.events.Clear(); - m_runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + m_runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super"))); m_runtime.Start(); } @@ -85,23 +86,21 @@ public void Dispose() m_diagnosticScope.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } - private EditorInteractionRuntime CreateRuntime( - EditorContext context, - params object[] hostServices - ) => new(context, m_types, m_logs, [m_types, m_identities, m_secondaryIdentities, ..hostServices]); [Fact] public void FeatureLookupReturnsOnlyStartedNonQuarantinedModules() { - Assert.True(m_runtime.interactions.TryGetModule(out var first)); + Assert.True(m_runtime.interactions.TryGetModule(out TestModule? first)); Assert.NotNull(first); - Assert.True(m_runtime.interactions.TryGetModule(out var again)); + Assert.True(m_runtime.interactions.TryGetModule(out TestModule? again)); Assert.Same(first, again); UpdateBarrierModule.throwWhenRead = true; m_runtime.Update(new EditorFrame()); - Assert.False(m_runtime.interactions.TryGetModule(out var quarantined)); + Assert.False(m_runtime.interactions.TryGetModule(out UpdateBarrierModule? quarantined)); Assert.Null(quarantined); } @@ -137,7 +136,10 @@ public void InteractionRuntimeInjectsOneStableAssignableHostService() { var service = new TestHostService(); HostServicePanel.current = null; - using EditorInteractionRuntime runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), service); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), + service + ); runtime.Start(); Assert.Contains(runtime.panels, static panel => panel.id == "tests.host-service"); Assert.Same(service, HostServicePanel.current); @@ -147,7 +149,9 @@ public void InteractionRuntimeInjectsOneStableAssignableHostService() public void InteractionRuntimeRejectsExtensionWhenHostServiceIsUnavailable() { HostServicePanel.current = null; - using EditorInteractionRuntime runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) + ); runtime.Start(); Assert.DoesNotContain(runtime.panels, static panel => panel.id == "tests.host-service"); Assert.Null(HostServicePanel.current); @@ -196,17 +200,17 @@ public void DocumentHostOpensOneInstanceAndRequiresExplicitDirtyCloseDecision() IEditorDocumentService documents = m_runtime.interactions.documents; var provider = new TestDocumentProvider(); using IDisposable lease = documents.RegisterProvider(provider); - Guid assetId = Guid.NewGuid(); - EditorDocumentContext opened = documents.Open("./Assets/Hero.ispriteatlas2d", assetId); - EditorDocumentContext focused = documents.Open("Assets/OtherName.ispriteatlas2d", assetId); - documents.SetDirty(opened.documentId); + Guid assetID = Guid.NewGuid(); + EditorDocumentContext opened = documents.Open("./Assets/Hero.ispriteatlas2d", assetID); + EditorDocumentContext focused = documents.Open("Assets/OtherName.ispriteatlas2d", assetID); + documents.SetDirty(opened.documentID); Assert.Same(opened, focused); Assert.Equal("Assets/OtherName.ispriteatlas2d", opened.assetPath); Assert.Equal("OtherName.ispriteatlas2d", opened.title); Assert.True(opened.isDirty); - Assert.False(documents.Close(opened.documentId, EditorDocumentCloseMode.Cancel)); + Assert.False(documents.Close(opened.documentID, EditorDocumentCloseMode.Cancel)); Assert.Single(documents.documents); - Assert.True(documents.Close(opened.documentId, EditorDocumentCloseMode.Save)); + Assert.True(documents.Close(opened.documentID, EditorDocumentCloseMode.Save)); Assert.Empty(documents.documents); Assert.Equal(1, provider.saveCount); Assert.Equal(1, provider.closeCount); @@ -218,14 +222,14 @@ public void DocumentPathReassignmentRetiresOnlyCleanStaleOwner() IEditorDocumentService documents = m_runtime.interactions.documents; var provider = new TestDocumentProvider(); using IDisposable lease = documents.RegisterProvider(provider); - const string path = "Assets/Shared.ispriteatlas2d"; - EditorDocumentContext first = documents.Open(path, Guid.NewGuid()); - EditorDocumentContext replacement = documents.Open(path, Guid.NewGuid()); + const string C_PATH = "Assets/Shared.ispriteatlas2d"; + EditorDocumentContext first = documents.Open(C_PATH, Guid.NewGuid()); + EditorDocumentContext replacement = documents.Open(C_PATH, Guid.NewGuid()); Assert.NotSame(first, replacement); Assert.Single(documents.documents); Assert.Equal(1, provider.closeCount); - documents.SetDirty(replacement.documentId); - InvalidOperationException failure = Assert.Throws(() => documents.Open(path, Guid.NewGuid())); + documents.SetDirty(replacement.documentID); + InvalidOperationException failure = Assert.Throws(() => documents.Open(C_PATH, Guid.NewGuid())); Assert.Contains("unsaved changes", failure.Message, StringComparison.Ordinal); Assert.Same(replacement, Assert.Single(documents.documents)); } @@ -238,10 +242,10 @@ public void DocumentStateSurvivesProviderGenerationReplacement() IDisposable firstLease = documents.RegisterProvider(firstProvider); EditorDocumentContext opened = documents.Open("Assets/World.itilemap2d", Guid.NewGuid()); opened.SetViewParameter("zoom", "2.5"); - documents.SetDirty(opened.documentId); + documents.SetDirty(opened.documentID); firstLease.Dispose(); Assert.False(opened.isProviderAvailable); - Assert.False(documents.Save(opened.documentId)); + Assert.False(documents.Save(opened.documentID)); var replacement = new TestDocumentProvider(); using IDisposable replacementLease = documents.RegisterProvider(replacement); Assert.True(opened.isProviderAvailable); @@ -249,7 +253,7 @@ public void DocumentStateSurvivesProviderGenerationReplacement() EditorDocumentContext restored = Assert.Single(documents.documents); Assert.True(restored.TryGetViewParameter("zoom", out string zoom)); Assert.Equal("2.5", zoom); - Assert.True(documents.Close(opened.documentId, EditorDocumentCloseMode.Discard)); + Assert.True(documents.Close(opened.documentID, EditorDocumentCloseMode.Discard)); } [Fact] @@ -263,14 +267,27 @@ public void ViewportToolCapturesOnePointerAndCommitsOneGestureTransaction() var down = new EditorViewportPointerEvent( 7, EditorViewportPointerPhase.Down, - new Inno.Core.Mathematics.Vector2(2f, 3f), - coordinates.ScreenToWorld(new Inno.Core.Mathematics.Vector2(2f, 3f)), + new Vector2(2f, 3f), + coordinates.ScreenToWorld(new Vector2(2f, 3f)), 0, KeyModifier.None ); Assert.True(session.HandlePointer(down)); - Assert.False(session.HandlePointer(new EditorViewportPointerEvent(8, EditorViewportPointerPhase.Move, default, default, 0, KeyModifier.None))); - Assert.True(session.HandlePointer(new EditorViewportPointerEvent(7, EditorViewportPointerPhase.Up, down.screenPosition, down.worldPosition, 0, KeyModifier.None))); + Assert.False( + session.HandlePointer(new EditorViewportPointerEvent(8, EditorViewportPointerPhase.Move, default, default, 0, KeyModifier.None)) + ); + Assert.True( + session.HandlePointer( + new EditorViewportPointerEvent( + 7, + EditorViewportPointerPhase.Up, + down.screenPosition, + down.worldPosition, + 0, + KeyModifier.None + ) + ) + ); Assert.Equal(1, tool.downCount); Assert.Equal(1, tool.upCount); Assert.True(history.canUndo); @@ -292,10 +309,10 @@ public void RuntimeDiscoversModulesAndPanelsWithoutRegistrationCalls() public void StatisticsUseStableReplacementAndOneFrameOrderHandoff() { EditorStatistics statistics = m_runtime.context.statistics; - var id = new EditorStatisticId("tests.statistics.frame-time"); - var groupId = new EditorStatisticGroupId("tests.statistics"); - statistics.Publish(new EditorStatistic(id, groupId, "Tests", "Frame Time", "10 ms")); - statistics.Publish(new EditorStatistic(id, groupId, "Tests", "Frame Time", "8 ms")); + var id = new EditorStatisticID("tests.statistics.frame-time"); + var groupID = new EditorStatisticGroupID("tests.statistics"); + statistics.Publish(new EditorStatistic(id, groupID, "Tests", "Frame Time", "10 ms")); + statistics.Publish(new EditorStatistic(id, groupID, "Tests", "Frame Time", "8 ms")); Assert.Equal("8 ms", Assert.Single(statistics.GetSnapshot()).value); m_runtime.Update(new EditorFrame(0.016f, 0.016f, isFocused: true)); Assert.Equal("8 ms", Assert.Single(statistics.GetSnapshot()).value); @@ -398,7 +415,10 @@ public void NeutralHistorySurvivesATypeCatalogGenerationChange() [Fact] public void MissingHistoryHandlerCreatesAnExplicitBarrier() { - m_runtime.interactions.history.RecordApplied("Unavailable Change", new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3]))); + m_runtime.interactions.history.RecordApplied( + "Unavailable Change", + new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3])) + ); Assert.False(m_runtime.interactions.history.canUndo); Assert.Contains("tests/missing-history-handler", m_runtime.interactions.history.undoUnavailableReason); Assert.False(m_runtime.interactions.history.Undo().succeeded); @@ -409,10 +429,13 @@ public void MissingHistoryHandlerCreatesAnExplicitBarrier() public void LargeNeutralPayloadSpillsToTheBoundedSessionDiskStore() { NeutralHistoryHandler.value = 32; - byte[] bytes = new byte[128 * 1024]; + var bytes = new byte[128 * 1024]; BitConverter.GetBytes(9).CopyTo(bytes, 0); BitConverter.GetBytes(32).CopyTo(bytes, sizeof(int)); - m_runtime.interactions.history.RecordApplied("Large Neutral Change", new EditorHistoryChange(NeutralHistoryHandler.KIND, EditorHistoryPayload.FromBytes(bytes))); + m_runtime.interactions.history.RecordApplied( + "Large Neutral Change", + new EditorHistoryChange(NeutralHistoryHandler.C_KIND, EditorHistoryPayload.FromBytes(bytes)) + ); Assert.Equal(0, m_runtime.interactions.history.residentBytes); Assert.Equal(bytes.LongLength, m_runtime.interactions.history.diskBytes); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -440,7 +463,7 @@ public void ToolbarResolvesContextualIconTooltipStateAndDispatch() { EditorInteraction interaction = m_runtime.interactions.For("tests/toolbar"); EditorToolbarItem initial = Assert.Single(interaction.BuildToolbar().items); - Assert.Equal("tests.toolbar", initial.actionId); + Assert.Equal("tests.toolbar", initial.actionID); Assert.Equal(EditorToolbarIcon.Play, initial.icon); Assert.Equal("Start Runtime", initial.tooltip); Assert.False(initial.status.isChecked); @@ -449,7 +472,7 @@ public void ToolbarResolvesContextualIconTooltipStateAndDispatch() Assert.Equal(EditorToolbarIcon.Stop, active.icon); Assert.Equal("Stop Runtime", active.tooltip); Assert.True(active.status.isChecked); - interaction.Enqueue(active.actionId); + interaction.Enqueue(active.actionID); m_runtime.Update(new EditorFrame(0.016f, 1f, isFocused: true)); Assert.Equal(1, ToolbarAction.executeCount); } @@ -484,7 +507,9 @@ public void EveryShortcutDeclaredByTheSameActionCanDispatch() [Fact] public void ProductKeyboardPolicyControlsDiscoveryLabelsAndShortcutDispatch() { - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Super, "Cmd"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Super, "Cmd")) + ); runtime.Start(); NeutralHistoryHandler.value = 1; runtime.interactions.history.RecordApplied("Change Test Value", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); @@ -567,15 +592,23 @@ public void IdentityResolutionUsesTheOwningDomain() Assert.Same(primary, primaryResult); Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity, out IdentityObject? secondaryResult)); Assert.Same(secondary, secondaryResult); - Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainId, secondary.identity.persistentId, out IdentityObject? persistentResult)); + Assert.True( + m_runtime.interactions.TryResolveIdentity( + secondaryIdentity.domainID, + secondary.identity.persistentID, + out IdentityObject? persistentResult + ) + ); Assert.Same(secondary, persistentResult); - var crossDomainAlias = new RuntimeIdentity(secondaryIdentity.domainId, primaryIdentity.runtimeId); + var crossDomainAlias = new RuntimeIdentity(secondaryIdentity.domainID, primaryIdentity.runtimeID); Assert.NotSame(primary, m_runtime.interactions.TryResolveIdentity(crossDomainAlias, out IdentityObject? alias) ? alias : null); - Guid persistentId = secondary.identity.persistentId; + Guid persistentID = secondary.identity.persistentID; Assert.True(m_secondaryIdentities.Unregister(secondary)); var replacement = new DragSource(); - Assert.True(m_secondaryIdentities.Register(replacement, persistentId)); - Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainId, persistentId, out IdentityObject? replacementResult)); + Assert.True(m_secondaryIdentities.Register(replacement, persistentID)); + Assert.True( + m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainID, persistentID, out IdentityObject? replacementResult) + ); Assert.Same(replacement, replacementResult); } @@ -586,7 +619,9 @@ public void TypedDropRoutesAndCancelsItsManagedSession() DragSource source = Register(new DragSource()); var target = new DropTarget(); var data = new EditorDragData(source, "source"); - RuntimeIdentity supersededIdentity = m_runtime.interactions.For("tests/other", supersededSource).BeginDrag(new EditorDragData(supersededSource, "superseded")); + RuntimeIdentity supersededIdentity = m_runtime.interactions + .For("tests/other", supersededSource) + .BeginDrag(new EditorDragData(supersededSource, "superseded")); RuntimeIdentity identity = m_runtime.interactions.For("tests/other", source).BeginDrag(data); EditorInteraction dropTarget = m_runtime.interactions.For("tests/drop", target); Assert.NotEqual(supersededIdentity, identity); @@ -609,13 +644,6 @@ public void UnregisteredDragSourceCancelsTheManagedSession() Assert.False(m_runtime.interactions.TryGetDragSource(identity, out _)); } - private TIdentity Register(TIdentity value) - where TIdentity : IdentityObject - { - Assert.True(m_identities.Register(value)); - return value; - } - [Fact] public void ThrowingPanelPresentationPropertyQuarantinesOnlyThatPanel() { @@ -646,7 +674,9 @@ public void FailedModuleStartIsStoppedBeforeCandidateDisposal() m_runtime.Dispose(); int stops = TestModule.stopCount; TestModule.throwOnStart = true; - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) + ); try { Assert.Throws(runtime.Start); @@ -665,7 +695,9 @@ public void FailedPanelAttachmentIsCompensatedBeforeItIsQuarantined() m_runtime.Dispose(); int detaches = TestPanel.detachCount; TestPanel.throwOnAttach = true; - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) + ); try { runtime.Start(); @@ -748,7 +780,9 @@ public void ModuleStateAndPanelVisibilityRestoreForTheSameProject() string document = File.ReadAllText(settingsPath); Assert.Contains("[InnoEditor][Module.tests.state]", document); Assert.DoesNotContain("[InnoEditor][Module.tests.update-barrier]", document); - using EditorInteractionRuntime restored = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime restored = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) + ); restored.Start(); Assert.Equal(42, TestModule.restoredStateValue); Assert.True(Assert.Single(restored.panels.Where(static value => value.id == "tests.panel")).isOpen); @@ -758,7 +792,7 @@ public void ModuleStateAndPanelVisibilityRestoreForTheSameProject() public void MalformedModuleStateValueUsesTheExtensionFallback() { m_runtime.Dispose(); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); context.SetLayoutSection("Module.tests.state", new Dictionary { ["value"] = "not-json" }); context.SaveLayout(); TestModule.restoredStateValue = -1; @@ -768,7 +802,7 @@ public void MalformedModuleStateValueUsesTheExtensionFallback() } [Fact] - public void ExtensionStateCaptureFailure_PublishesCurrentDiagnosticUntilRetrySucceeds() + public void ExtensionStateCaptureFailurePublishesCurrentDiagnosticUntilRetrySucceeds() { var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); @@ -776,7 +810,9 @@ public void ExtensionStateCaptureFailure_PublishesCurrentDiagnosticUntilRetrySuc { TestModule.captureFailure = true; m_runtime.Update(new EditorFrame(0.016f, 3f, isFocused: true)); - DiagnosticReport report = Assert.Single(sink.reports.Values.Where(static value => value.source.displayName == "Editor State Capture")); + DiagnosticReport report = Assert.Single( + sink.reports.Values.Where(static value => value.source.displayName == "Editor State Capture") + ); Assert.Equal("EDITOR-STATE-CAPTURE", Assert.Single(report.diagnostics).code); TestModule.captureFailure = false; m_runtime.Update(new EditorFrame(0.016f, 6f, isFocused: true)); @@ -792,13 +828,13 @@ public void ExtensionStateCaptureFailure_PublishesCurrentDiagnosticUntilRetrySuc [Fact] public void UnifiedEditorIniPreservesLayoutAndExtensionStateSectionsTogether() { - const string layout = "[Window][Hierarchy]\nPos=10,20\nSize=300,400"; - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); - context.SetImGuiLayout(layout); + const string C_LAYOUT = "[Window][Hierarchy]\nPos=10,20\nSize=300,400"; + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); + context.SetImGuiLayout(C_LAYOUT); context.SetLayoutSection("Module.tests", new Dictionary { ["openScenes"] = "[\"Scenes/Test.iscene\"]" }); Assert.True(context.SaveLayoutIfChanged()); - var restored = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); - Assert.Equal(layout, restored.imguiLayout); + var restored = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); + Assert.Equal(C_LAYOUT, restored.imguiLayout); Assert.True(restored.TryGetLayoutSection("Module.tests", out IReadOnlyDictionary values)); Assert.Equal("[\"Scenes/Test.iscene\"]", values["openScenes"]); string document = File.ReadAllText(restored.layoutPath); @@ -812,13 +848,15 @@ public void UnifiedEditorIniPreservesLayoutAndExtensionStateSectionsTogether() public void StartupRegistryRefreshCannotOverwriteModuleStateBeforeRestore() { m_runtime.Dispose(); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); context.SetLayoutSection("Module.tests.state", new Dictionary { ["value"] = "91" }); context.SaveLayout(); TestModule.startCount = 0; TestModule.restoredStateValue = 0; TestModule.rebuildDuringRestore = true; - using EditorInteractionRuntime restored = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime restored = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) + ); restored.Start(); Assert.Equal(91, TestModule.restoredStateValue); TestModule.stateValue = TestModule.restoredStateValue; @@ -830,27 +868,26 @@ public void StartupRegistryRefreshCannotOverwriteModuleStateBeforeRestore() Assert.False(TestModule.rebuildDuringRestore); } - private sealed class TestDiagnosticSink : IDiagnosticSink + private EditorInteractionRuntime CreateRuntime( + EditorContext context, + params object[] hostServices + ) => new(context, m_types, m_logs, [m_types, m_identities, m_secondaryIdentities, ..hostServices]); + + private TIdentity Register(TIdentity value) + where TIdentity : IdentityObject { - internal Dictionary reports { get; } = new(StringComparer.Ordinal); + Assert.True(m_identities.Register(value)); + return value; + } + private sealed class TestDiagnosticSink : IDiagnosticSink + { public void Replace(DiagnosticReport report) => reports[report.source.id] = report; - public void Clear(DiagnosticSource source) => reports.Remove(source.id); - } -} -public class BaseTarget; -public sealed class DerivedTarget : BaseTarget; -public sealed class DragSource : IdentityObject; -public sealed class DropTarget -{ - public bool wasDropped { get; set; } -} + public void Clear(DiagnosticSource source) => reports.Remove(source.id); -public sealed class InteractionTarget -{ - public string? committedValue { get; set; } - public string? validationMessage { get; set; } + internal Dictionary reports { get; } = new(StringComparer.Ordinal); + } } public sealed record InteractionPresentation( @@ -858,456 +895,3 @@ public sealed record InteractionPresentation( bool submit, bool cancel = false ); -[EditorHistoryHandler(NeutralHistoryHandler.KIND)] -public sealed class NeutralHistoryHandler : EditorHistoryHandler -{ - public const string KIND = "tests/neutral-value"; - public static int value; - public static EditorHistoryChange CreateChange( - int before, - int after - ) { - byte[] bytes = new byte[sizeof(int) * 2]; - BitConverter.GetBytes(before).CopyTo(bytes, 0); - BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int)); - return new EditorHistoryChange(KIND, EditorHistoryPayload.FromBytes(bytes)); - } - - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 2 ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] bytes = change.payload.ReadBytes(); - value = BitConverter.ToInt32(bytes, direction == EditorHistoryDirection.Undo ? 0 : sizeof(int)); - return EditorHistoryResult.Success(); - } -} - -public interface ITestHostService; -public sealed class TestHostService : ITestHostService; -[EditorPanel("tests.host-service", "Host Service")] -public sealed class HostServicePanel : EditorPanel -{ - public static ITestHostService? current; - public HostServicePanel(ITestHostService service) - { - current = service; - } - - protected override void OnDraw(EditorContext context) => _ = context; -} - -[EditorModule("tests.state")] -public sealed class TestModule : EditorModule -{ - private readonly TypeCatalog m_types; - public static int startCount; - public static int stopCount; - public static int stateValue; - public static int restoredStateValue; - public static bool rebuildDuringRestore; - public static bool captureFailure; - public static bool throwOnStart; - public static bool throwOnStop; - public static int pendingStops; - public TestModule(TypeCatalog types) - { - m_types = types; - } - - protected override void Capture(EditorState state) - { - if (captureFailure) - throw new InvalidOperationException("The test module state cannot be captured."); - state.Set("value", stateValue); - } - - protected override void Restore(EditorState state) - { - restoredStateValue = state.Get("value", 0); - if (!rebuildDuringRestore) - return; - rebuildDuringRestore = false; - m_types.Rebuild(); - } - - protected override void OnStart(EditorContext context) - { - startCount++; - if (throwOnStart) - throw new InvalidOperationException("Injected module startup failure."); - if (startCount == 1) - m_types.Rebuild(); - } - - protected override void OnStop(EditorContext context) - { - stopCount++; - ShutdownOrder.events.Add("module.stop"); - if (pendingStops-- > 0) - throw new RetirementPendingException("Module-owned work has not drained."); - if (throwOnStop) - throw new InvalidOperationException("Injected module stop failure."); - } -} - -[EditorModule("tests.update-barrier", order: -200)] -public sealed class UpdateBarrierModule : EditorModule -{ - public static bool block; - public static bool throwWhenRead; - public static int barrierReadCount; - public override bool blocksFollowingUpdates - { - get - { - barrierReadCount++; - return throwWhenRead ? throw new InvalidOperationException("Injected module barrier failure.") : block; - } - } -} - -[EditorModule("tests.following-update", order: -199)] -public sealed class FollowingUpdateModule : EditorModule -{ - public static int updateCount; - protected override void OnUpdate(EditorContext context) => updateCount++; -} - -[EditorPanel("tests.panel", "Test", defaultOpen: false, menuPath: "Testing")] -public sealed class TestPanel(TestModule module) : EditorPanel -{ - public static int attachCount; - public static int detachCount; - public static bool firstAttachPrecededModuleStart; - public static bool throwFromWindowPadding; - public static bool throwOnAttach; - public static bool throwOnDetach; - public static int pendingDetaches; - public override bool useWindowPadding => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; - - protected override void OnAttach(EditorContext context) - { - _ = module; - if (attachCount == 0) - firstAttachPrecededModuleStart = TestModule.startCount == 0; - attachCount++; - if (throwOnAttach) - throw new InvalidOperationException("Injected panel attachment failure."); - } - - protected override void OnDetach(EditorContext context) - { - detachCount++; - ShutdownOrder.events.Add("panel.detach"); - if (pendingDetaches-- > 0) - throw new RetirementPendingException("Panel-owned work has not drained."); - if (throwOnDetach) - throw new InvalidOperationException("Injected panel detach failure."); - } - - protected override void OnDraw(EditorContext context) - { - } -} - -[StableTypeId("0fbd66e2-303e-4b35-83a1-fc2b90d58360")] -[ProjectSettingDefinition("tests.editor.multi-presentation")] -public sealed class MultiPresentationSetting : ISerializable -{ - public static ProjectSettingId settingId => new("tests.editor.multi-presentation"); - - [SerializableProperty] - public int value { get; set; } = 7; -} - -[ProjectSettingPath("Project/Tests/Multi/Primary")] -public sealed class PrimaryMultiPresentationEditor : ProjectSettingEditor -{ - protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; -} - -[ProjectSettingPath("Project/Tests/Multi/Secondary")] -public sealed class SecondaryMultiPresentationEditor : ProjectSettingEditor -{ - protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; -} - -[EditorAction("tests.resolve")] -public sealed class BaseResolveAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "base"); - protected override void Execute(EditorActionContext context) - { - } -} - -[EditorAction("tests.resolve", "tests/special", priority: 100)] -public sealed class AreaResolveAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "area"); - protected override void Execute(EditorActionContext context) - { - } -} - -[EditorAction("tests.deferred")] -public sealed class DeferredAction : EditorAction -{ - public static int executeCount; - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.action-metadata", "tests/action-metadata")] -public sealed class MetadataAction : EditorAction -{ - public static int targetTypeReadCount; - public static bool throwWhenRead; - public override Type? targetType - { - get - { - targetTypeReadCount++; - return throwWhenRead ? throw new InvalidOperationException("Action metadata was read at runtime.") : typeof(BaseTarget); - } - } - - protected override void Execute(EditorActionContext context) - { - } -} - -[EditorAction("tests.multiple-shortcuts", "tests/multiple-shortcuts")] -[EditorShortcut("tests/multiple-shortcuts", KeyCode.F3)] -[EditorShortcut("tests/multiple-shortcuts", KeyCode.F4)] -public sealed class MultiShortcutAction : EditorAction -{ - public static int executeCount; - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.toolbar", "tests/toolbar")] -[EditorToolbarItem("tests/toolbar", EditorToolbarIcon.Play, "Start Runtime", activeIcon: EditorToolbarIcon.Stop)] -public sealed class ToolbarAction : EditorAction -{ - public static bool isChecked; - public static int executeCount; - protected override EditorActionState Query(EditorActionContext context) => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.throw-after-activate", "tests/throw-after-activate")] -public sealed class ThrowAfterActivateAction : EditorAction -{ - public static int cancelCount; - protected override void Execute(EditorActionContext context) - { - Activate(context); - throw new InvalidOperationException("Injected action execution failure."); - } - - protected override void OnCancelled() => cancelCount++; -} - -[EditorModule("tests.dispose-observer", order: 900)] -public sealed class ADisposeObserverModule(EditorInteractions interactions) : EditorModule -{ - public static bool historyAvailableDuringStop; - public static bool historyDisposedDuringDispose; - public static int disposeCount; - protected override void OnStop(EditorContext context) - { - if (interactions.history.isFaulted) - return; - using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Shutdown probe"); - historyAvailableDuringStop = transaction.Rollback().succeeded; - } - - protected override void OnDispose() - { - disposeCount++; - try - { - using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Disposed probe"); - } - catch (ObjectDisposedException) - { - historyDisposedDuringDispose = true; - } - } -} - -[EditorModule("tests.throwing-dispose", order: 901)] -public sealed class ZThrowingDisposeModule : EditorModule -{ - public static bool throwOnDispose; - public static int disposeCount; - protected override void OnDispose() - { - disposeCount++; - if (throwOnDispose) - throw new InvalidOperationException("Injected extension disposal failure."); - } -} - -internal static class ShutdownOrder -{ - internal static List events { get; } = []; -} - -[EditorAction("tests.interaction")] -public sealed class InteractionAction : EditorPresentationAction -{ - private string m_value = string.Empty; - protected override void Execute(EditorActionContext context) - { - m_value = "Initial"; - context.target.validationMessage = null; - Activate(context); - } - - protected override bool Present(EditorActionContext context) - { - InteractionPresentation presentation = context.argument; - if (presentation.cancel) - { - Cancel(); - return true; - } - - m_value = presentation.value; - if (!presentation.submit) - return true; - if (string.IsNullOrWhiteSpace(m_value)) - { - context.target.validationMessage = "A name is required."; - return true; - } - - context.target.committedValue = m_value; - context.target.validationMessage = null; - Complete(); - return true; - } - - protected override void OnCancelled() => m_value = string.Empty; -} - -[EditorAction("tests.commit-on-presentation-lost")] -public sealed class CommitOnPresentationLostAction : EditorAction -{ - private InteractionTarget? m_target; - protected override void Execute(EditorActionContext context) - { - m_target = context.target; - Activate(context); - } - - protected override void OnPresentationLost() - { - if (m_target is not null) - m_target.committedValue = "Committed on focus loss"; - m_target = null; - Complete(); - } - - protected override void OnCancelled() => m_target = null; -} - -[EditorAction("tests.menu")] -[EditorMenu("tests/menu", "Tools/Create/Asset", order: 100)] -public sealed class MenuAction : EditorAction -{ - protected override void Execute(EditorActionContext context) - { - } -} - -[EditorMenuSource("tests/menu")] -public sealed class DynamicMenuSource : EditorMenuSource -{ - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - builder.AddGroup("Tools/Create/Libraries", order: 150, separatorBefore: true); - builder.Add("Tools/Create/Libraries/Function", "tests.menu", order: 150); - builder.Add("Tools/Create/Generated", "tests.menu", order: 200); - } -} - -[EditorDrop("tests/drop")] -public sealed class TestDrop : EditorDrop -{ - protected override EditorDropStatus Query(EditorDropContext context) => EditorDropStatus.Accept(); - protected override EditorDropResult Drop(EditorDropContext context) - { - context.target.wasDropped = true; - return EditorDropResult.Accepted(); - } -} - -public sealed class TestDocumentProvider : EditorDocumentProvider -{ - public int openCount { get; private set; } - public int saveCount { get; private set; } - public int closeCount { get; private set; } - public override string id => "tests.documents"; - - public override bool CanOpen(string assetPath) => assetPath.EndsWith( - ".ispriteatlas2d", - StringComparison.Ordinal - ) - || assetPath.EndsWith( - ".itilemap2d", - StringComparison.Ordinal - ); - public override void Open(EditorDocumentContext context) => openCount++; - public override bool Save(EditorDocumentContext context) - { - saveCount++; - return true; - } - - public override void Close(EditorDocumentContext context) => closeCount++; -} - -public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter -{ - public Inno.Core.Mathematics.Vector2 ScreenToWorld(Inno.Core.Mathematics.Vector2 screenPosition) => screenPosition * 2f; - public Inno.Core.Mathematics.Vector2 WorldToScreen(Inno.Core.Mathematics.Vector2 worldPosition) => worldPosition / 2f; -} - -public sealed class TestViewportTool(IEditorHistory history) : EditorViewportTool -{ - public int downCount { get; private set; } - public int upCount { get; private set; } - public override string id => "tests.viewport.paint"; - public override EditorViewportCursor cursor => EditorViewportCursor.Crosshair; - - public override void OnPointerDown( - EditorViewportToolContext context, - EditorViewportPointerEvent pointer - ) { - downCount++; - context.CapturePointer(pointer.pointerId); - context.BeginHistoryGesture("Paint Tile"); - NeutralHistoryHandler.value = 1; - history.RecordApplied("Paint Tile Cell", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); - } - - public override void OnPointerUp( - EditorViewportToolContext context, - EditorViewportPointerEvent pointer - ) { - upCount++; - context.CompleteHistoryGesture(commit: true); - context.ReleasePointer(); - } -} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs index 9585221a0..bbe6c8051 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs @@ -1,12 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; +using System.Reflection; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -14,9 +16,11 @@ using Inno.Editor.Interactions; using Inno.Editor.PlayMode; using Inno.Editor.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Editor.Presentation.Tests; + public sealed class EditorSettingsTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorSettingsTests", Guid.NewGuid().ToString("N")); @@ -29,18 +33,21 @@ public sealed class EditorSettingsTests : IDisposable private readonly DiagnosticHub m_diagnostics = new(); private readonly FakePlayMode m_playMode = new(); private readonly LogRouter m_logs = new(); + public EditorSettingsTests() { Directory.CreateDirectory(m_projectRoot); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorSettingsTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorSettingsTests).Assembly) } + ); _ = typeof(EditorSettings); - _ = System.Reflection.Assembly.Load("Inno.Editor.Panel.Logging"); + _ = Assembly.Load("Inno.Editor.Panel.Logging"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); SettingsCaptureModule.current = null; SettingsCaptureModule.console = null; m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization, m_diagnostics, m_playMode] @@ -60,7 +67,9 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -75,7 +84,11 @@ public void ApplyPersistsObjectsAtTheProjectRootAndPublishesOnlyTheService() }); var value = new EditorSettingObject(); value.SetAsInt32("value", 10); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value } + ) + ); string path = Path.Combine(m_projectRoot, "Settings.Editor.inno"); Assert.True(File.Exists(path)); Assert.False(Directory.Exists(Path.Combine(m_projectRoot, "Settings"))); @@ -92,7 +105,11 @@ public void ChangedSubscriberFailureDoesNotChangeHistoryResultOrSkipLaterSubscri using IDisposable deliveredSubscription = m_settings.ListenChanges(_ => delivered++); var value = new EditorSettingObject(); value.SetAsInt32("value", 11); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value } + ) + ); Assert.Equal(1, delivered); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(2, delivered); @@ -115,12 +132,20 @@ public void GetReturnsIsolatedObjectsAndRejectsPagesOrMissingPaths() [Fact] public void ResetRemovesThePathOverrideAndRestoresTheDefinitionObject() { - EditorSetting definition = Assert.Single(m_settings.definitions, static setting => setting.path == "Editor/Tests/Values/Project Count"); + EditorSetting definition = Assert.Single( + m_settings.definitions, + static setting => setting.path == "Editor/Tests/Values/Project Count" + ); var value = new EditorSettingObject(); value.SetAsInt32("value", 8); Assert.True(m_settings.Apply(new Dictionary { ["Editor/Tests/Values/Project Count"] = value })); Assert.False(definition.IsDefault(m_settings.Get("Editor/Tests/Values/Project Count"))); - Assert.True(m_settings.Apply(new Dictionary(), new HashSet(StringComparer.Ordinal) { "Editor/Tests/Values/Project Count" })); + Assert.True( + m_settings.Apply( + new Dictionary(), + new HashSet(StringComparer.Ordinal) { "Editor/Tests/Values/Project Count" } + ) + ); Assert.Equal(3, m_settings.Get("Editor/Tests/Values/Project Count").GetAsInt32("value")); Assert.True(definition.IsDefault(m_settings.Get("Editor/Tests/Values/Project Count"))); Assert.NotSame(definition.defaultValue, definition.defaultValue); @@ -134,7 +159,15 @@ public void OneApplyCreatesOneSharedHistoryEntryForAllSettings() count.SetAsInt32("value", 7); var toggle = new EditorSettingObject(); toggle.SetAsBoolean("value", false); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = count, ["Editor/Tests/Values/Project Toggle"] = toggle })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) + { + ["Editor/Tests/Values/Project Count"] = count, + ["Editor/Tests/Values/Project Toggle"] = toggle + } + ) + ); Assert.Equal("Apply Settings", m_runtime.interactions.history.undoName); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(3, m_settings.Get("Editor/Tests/Values/Project Count").GetAsInt32("value")); @@ -147,12 +180,12 @@ public void OneApplyCreatesOneSharedHistoryEntryForAllSettings() [Fact] public void ClearOnPlaySettingDefaultsToTrueAndImmediatelyControlsTheConsole() { - const string path = "Editor/Diagnostics/Console/Clear on Play"; - Assert.True(m_settings.Get(path).GetAsBoolean("value")); + const string C_PATH = "Editor/Diagnostics/Console/Clear on Play"; + Assert.True(m_settings.Get(C_PATH).GetAsBoolean("value")); Assert.True(m_console.clearOnPlay); var disabled = new EditorSettingObject(); disabled.SetAsBoolean("value", false); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { [path] = disabled })); + Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { [C_PATH] = disabled })); Assert.False(m_console.clearOnPlay); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.True(m_console.clearOnPlay); @@ -191,7 +224,11 @@ public void SettingObjectRoundTripsSupportedPrimitivesAndArrays() value.SetAsSingleArray("singles", [1.5f, 2.5f]); value.SetAsDoubleArray("doubles", [3.5d, 4.5d]); value.SetAsStringArray("strings", ["first", null, "third"]); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Objects/Primitives"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Objects/Primitives"] = value } + ) + ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.True(m_runtime.interactions.history.Redo().succeeded); EditorSettingObject restored = m_settings.Get("Editor/Tests/Objects/Primitives"); @@ -219,7 +256,10 @@ public void SettingObjectRoundTripsSupportedPrimitivesAndArrays() [Fact] public void DrawTracksDifferenceFromEachStagedObjectsFirstDraw() { - EditorSetting definition = Assert.Single(m_settings.definitions, static setting => setting.path == "Editor/Tests/Objects/Draw Mutation"); + EditorSetting definition = Assert.Single( + m_settings.definitions, + static setting => setting.path == "Editor/Tests/Objects/Draw Mutation" + ); var value = new EditorSettingObject(); Assert.True(definition.Draw(value)); Assert.Equal(42, value.GetAsInt32("value")); @@ -237,6 +277,7 @@ IEditorConsole editorConsole { internal static EditorSettings? current; internal static IEditorConsole? console; + protected override void OnStart(EditorContext context) { current = settings; @@ -246,15 +287,17 @@ protected override void OnStart(EditorContext context) private sealed class FakePlayMode : IEditorPlayMode { + private readonly EventDispatcher m_stateDispatcher = new(); + public EditorPlayModeState state => EditorPlayModeState.Editing; public bool isPlaying => false; public string? lastFailure => null; - public LogSessionId activeSessionId => LogSessionId.none; + public LogSessionID activeSessionID => LogSessionID.none; - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } @@ -271,9 +314,7 @@ private sealed class TestCountSetting : EditorSetting public override string section => "Numbers"; public override string description => "Exercises path-addressed project persistence."; - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} private static EditorSettingObject CreateDefault() { @@ -289,9 +330,7 @@ private sealed class TestToggleSetting : EditorSetting public override EditorSettingObject defaultValue => CreateDefault(); public override string section => "Alpha"; - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} private static EditorSettingObject CreateDefault() { @@ -306,9 +345,7 @@ private sealed class TestPrimitiveObjectSetting : EditorSetting { public override EditorSettingObject defaultValue => new(); - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} } [EditorSettingPath("Editor/Tests/Objects/Draw Mutation")] diff --git a/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs new file mode 100644 index 000000000..af22ed09d --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.following-update", order: -199)] +public sealed class FollowingUpdateModule : EditorModule +{ + public static int updateCount; + + protected override void OnUpdate(EditorContext context) => updateCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs index a01743b1a..9501d3190 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs @@ -1,9 +1,9 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -15,16 +15,24 @@ public void ShiftBoxSelectionKeepsTheExistingSelectionAndAddsIntersectingNodes() var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId original = new("workflow.original"); - GraphNodeId added = new("workflow.added"); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var original = new GraphNodeID("workflow.original"); + var added = new GraphNodeID("workflow.added"); _ = layout.SetNodes([ - new(original, new(500f, 300f), new(100f, 80f), 24f, "Original", []), - new(added, new(50f, 50f), new(100f, 80f), 24f, "Added", []) + new GraphCanvasNode(original, new GraphPosition(500f, 300f), new Vector2(100f, 80f), 24f, "Original", []), + new GraphCanvasNode(added, new GraphPosition(50f, 50f), new Vector2(100f, 80f), 24f, "Added", []) ]); state.SelectNodes([original]); - _ = pointer.Step(view, layout, new() { position = new(10f, 10f), isHovered = true, isPressed = true, isDown = true, shift = true }); - _ = pointer.Step(view, layout, new() { position = new(200f, 200f), isHovered = true, isReleased = true, shift = true }); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(10f, 10f), isHovered = true, isPressed = true, isDown = true, shift = true } + ); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(200f, 200f), isHovered = true, isReleased = true, shift = true } + ); Assert.Equal(2, state.selectedNodes.Count); Assert.Contains(original, state.selectedNodes); Assert.Contains(added, state.selectedNodes); @@ -37,15 +45,37 @@ public void ConnectionReleaseBehindAnotherInputOwnerDoesNotConnect() var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - var output = new GraphEndpoint(new("source"), new("out")); - var input = new GraphEndpoint(new("target"), new("in")); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var output = new GraphEndpoint(new GraphNodeID("source"), new GraphPortID("out")); + var input = new GraphEndpoint(new GraphNodeID("target"), new GraphPortID("in")); _ = layout.SetNodes([ - new(new("source"), new(0f, 0f), new(100f, 100f), 24f, "Source", [new(output, GraphPortDirection.Output, new(100f, 50f), "Output")]), - new(new("target"), new(200f, 0f), new(100f, 100f), 24f, "Target", [new(input, GraphPortDirection.Input, new(0f, 50f), "Input")]) + new GraphCanvasNode( + new GraphNodeID("source"), + new GraphPosition(0f, 0f), + new Vector2(100f, 100f), + 24f, + "Source", + [new GraphCanvasPort(output, GraphPortDirection.Output, new Vector2(100f, 50f), "Output")] + ), + new GraphCanvasNode( + new GraphNodeID("target"), + new GraphPosition(200f, 0f), + new Vector2(100f, 100f), + 24f, + "Target", + [new GraphCanvasPort(input, GraphPortDirection.Input, new Vector2(0f, 50f), "Input")] + ) ]); - _ = pointer.Step(view, layout, new() { position = new(100f, 50f), isHovered = true, isPressed = true, isDown = true }); - GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = new(200f, 50f), isReleased = true, isHovered = false }); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(100f, 50f), isHovered = true, isPressed = true, isDown = true } + ); + GraphCanvasPointerResult result = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(200f, 50f), isReleased = true, isHovered = false } + ); Assert.Null(result.output); Assert.Null(result.input); Assert.Null(state.pendingConnection); @@ -57,20 +87,42 @@ public void DragReturnsOneNeutralEditAndCancelLeavesTheDocumentUntouched() var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - var node = new GraphCanvasNode(new("flow.step"), new(10f, 10f), new(200f, 100f), 24f, "Workflow", []); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var node = new GraphCanvasNode( + new GraphNodeID("flow.step"), + new GraphPosition(10f, 10f), + new Vector2(200f, 100f), + 24f, + "Workflow", + [] + ); _ = layout.SetNodes([node]); - Assert.Equal(node.id, pointer.Step(view, layout, new() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true }).nodePressed); - _ = pointer.Step(view, layout, new() { position = new(70f, 45f), isDown = true }); + Assert.Equal( + node.id, + pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true } + ).nodePressed + ); + _ = pointer.Step(view, layout, new GraphCanvasPointerInput() { position = new(70f, 45f), isDown = true }); Assert.Equal(new GraphPosition(60f, 40f), pointer.previewPositions[node.id]); - GraphCanvasPointerResult completed = pointer.Step(view, layout, new() { position = new(70f, 45f), isReleased = true }); + GraphCanvasPointerResult completed = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(70f, 45f), isReleased = true } + ); Assert.Equal(new GraphPosition(60f, 40f), completed.movedNodes![node.id]); Assert.False(pointer.isMoving); Assert.Empty(pointer.previewPositions); Assert.Equal(new GraphPosition(10f, 10f), node.position); - _ = pointer.Step(view, layout, new() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true }); - _ = pointer.Step(view, layout, new() { position = new(90f, 90f), isDown = true }); - Assert.Null(pointer.Step(view, layout, new() { cancel = true }).movedNodes); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true } + ); + _ = pointer.Step(view, layout, new GraphCanvasPointerInput() { position = new(90f, 90f), isDown = true }); + Assert.Null(pointer.Step(view, layout, new GraphCanvasPointerInput() { cancel = true }).movedNodes); Assert.Empty(pointer.previewPositions); Assert.Equal(new GraphPosition(60f, 40f), completed.movedNodes[node.id]); } @@ -83,16 +135,38 @@ public void ConnectionsAreNeutralIntentsAndMissingEndpointsCannotBeConnected(boo var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphEndpoint output = new(new("flow.source"), new("next")); - GraphEndpoint input = new(new("flow.target"), new("previous")); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var output = new GraphEndpoint(new GraphNodeID("flow.source"), new GraphPortID("next")); + var input = new GraphEndpoint(new GraphNodeID("flow.target"), new GraphPortID("previous")); _ = layout.SetNodes([ - new(output.nodeId, default, new(200f, 100f), 24f, "Source", [new(output, GraphPortDirection.Output, new(200f, 40f), "Next")]), - new(input.nodeId, new(300f, 0f), new(200f, 100f), 24f, "Target", [new(input, GraphPortDirection.Input, new(0f, 40f), "Previous", isMissing: missing)]) + new GraphCanvasNode( + output.nodeID, + default, + new Vector2(200f, 100f), + 24f, + "Source", + [new GraphCanvasPort(output, GraphPortDirection.Output, new Vector2(200f, 40f), "Next")] + ), + new GraphCanvasNode( + input.nodeID, + new GraphPosition(300f, 0f), + new Vector2(200f, 100f), + 24f, + "Target", + [new GraphCanvasPort(input, GraphPortDirection.Input, new Vector2(0f, 40f), "Previous", isMissing: missing)] + ) ]); - _ = pointer.Step(view, layout, new() { position = new(200f, 40f), isHovered = true, isPressed = true, isDown = true }); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(200f, 40f), isHovered = true, isPressed = true, isDown = true } + ); Assert.Equal(output, state.pendingConnection); - GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = new(300f, 40f), isHovered = true, isReleased = true }); + GraphCanvasPointerResult result = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(300f, 40f), isHovered = true, isReleased = true } + ); Assert.Equal(missing ? null : output, result.output); Assert.Equal(missing ? null : input, result.input); Assert.Null(state.pendingConnection); @@ -104,18 +178,34 @@ public void ReadOnlyChangesCancelEditsButStillAllowBoxSelection() var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId id = new("flow.read-only"); - _ = layout.SetNodes([new(id, new(20f, 20f), new(200f, 100f), 24f, "Read only", [])]); - _ = pointer.Step(view, layout, new() { position = new(30f, 25f), isHovered = true, isPressed = true, isDown = true }); - _ = pointer.Step(view, layout, new() { position = new(100f, 100f), isDown = true }); - Assert.Null(pointer.Step(view, layout, new() { position = new(100f, 100f), isReleased = true, readOnly = true }).movedNodes); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var id = new GraphNodeID("flow.read-only"); + _ = layout.SetNodes([new GraphCanvasNode(id, new GraphPosition(20f, 20f), new Vector2(200f, 100f), 24f, "Read only", [])]); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(30f, 25f), isHovered = true, isPressed = true, isDown = true } + ); + _ = pointer.Step(view, layout, new GraphCanvasPointerInput() { position = new(100f, 100f), isDown = true }); + Assert.Null( + pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(100f, 100f), isReleased = true, readOnly = true } + ).movedNodes + ); Assert.False(pointer.isMoving); - _ = pointer.Step(view, layout, new() { position = new(5f, 150f), isHovered = true, isPressed = true, isDown = true, readOnly = true }); + _ = pointer.Step( + view, + layout, + new GraphCanvasPointerInput() { position = new(5f, 150f), isHovered = true, isPressed = true, isDown = true, readOnly = true } + ); Assert.True(pointer.isBoxSelecting); - _ = pointer.Step(view, layout, new() { position = new(240f, 10f), isReleased = true, readOnly = true }); + _ = pointer.Step(view, layout, new GraphCanvasPointerInput() { position = new(240f, 10f), isReleased = true, readOnly = true }); Assert.Equal(id, Assert.Single(state.selectedNodes)); Assert.False(pointer.isBoxSelecting); - Assert.Throws(() => pointer.Step(view, layout, new() { position = new(float.NaN, 0f) })); + Assert.Throws( + () => pointer.Step(view, layout, new GraphCanvasPointerInput() { position = new(float.NaN, 0f) }) + ); } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs index 667329c39..62f301787 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs @@ -1,10 +1,10 @@ using System; using System.Linq; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -14,32 +14,41 @@ public sealed class GraphCanvasPresentationTests public void NonShaderNodesUseTheSameOrderedHitAndBoxGeometry() { var state = new GraphCanvasState(); - state.SetViewport(new(17f, -9f), 1.5f); - var view = new GraphCanvasView(state, new(100f, 200f), new(800f, 600f)); - GraphCanvasNode first = Node("workflow.start", new(0f, 0f)); - GraphCanvasNode second = Node("workflow.finish", new(50f, 0f)); + state.SetViewport(new GraphPosition(17f, -9f), 1.5f); + var view = new GraphCanvasView(state, new Vector2(100f, 200f), new Vector2(800f, 600f)); + GraphCanvasNode first = Node("workflow.start", new GraphPosition(0f, 0f)); + GraphCanvasNode second = Node("workflow.finish", new GraphPosition(50f, 0f)); var layout = new GraphCanvasLayout(); Assert.Equal(2, layout.SetNodes([first, second])); - Assert.Same(second, view.HitNode(layout, view.ToScreen(new(60f, 10f)))); - Assert.Equal(new[] { first.id, second.id }, view.BoxNodes(layout, view.ToScreen(new(-5f, -5f)), view.ToScreen(new(300f, 100f)))); + Assert.Same(second, view.HitNode(layout, view.ToScreen(new GraphPosition(60f, 10f)))); + Assert.Equal( + new[] { first.id, second.id }, + view.BoxNodes(layout, view.ToScreen(new GraphPosition(-5f, -5f)), view.ToScreen(new GraphPosition(300f, 100f))) + ); Assert.Equal(0, layout.SetNodes([second, first])); - Assert.Same(first, view.HitNode(layout, view.ToScreen(new(60f, 10f)))); + Assert.Same(first, view.HitNode(layout, view.ToScreen(new GraphPosition(60f, 10f)))); } [Fact] public void PortHitGeometryPreservesMissingAndExplicitLabelBounds() { var state = new GraphCanvasState(); - var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId id = new("workflow.output"); - var port = new GraphCanvasPort(new(id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Continue", - isMissing: true, labelBounds: (new(100f, 28f), new(200f, 52f))); - var node = new GraphCanvasNode(id, new(10f, 10f), new(200f, 100f), 24f, "Flow step", [port]); + var view = new GraphCanvasView(state, Vector2.Zero, new Vector2(800f, 600f)); + var id = new GraphNodeID("workflow.output"); + var port = new GraphCanvasPort( + new GraphEndpoint(id, new GraphPortID("next")), + GraphPortDirection.Output, + new Vector2(200f, 40f), + "Continue", + isMissing: true, + labelBounds: (new Vector2(100f, 28f), new Vector2(200f, 52f)) + ); + var node = new GraphCanvasNode(id, new GraphPosition(10f, 10f), new Vector2(200f, 100f), 24f, "Flow step", [port]); var layout = new GraphCanvasLayout(); _ = layout.SetNodes([node]); - Assert.Equal(port, view.HitPort(layout, new(210f, 50f))); - Assert.Equal(port, view.HitPort(layout, new(150f, 50f))); - Assert.Null(view.HitPort(layout, new(150f, 90f))); + Assert.Equal(port, view.HitPort(layout, new Vector2(210f, 50f))); + Assert.Equal(port, view.HitPort(layout, new Vector2(150f, 50f))); + Assert.Null(view.HitPort(layout, new Vector2(150f, 90f))); Assert.Throws(() => view.HitPort(layout, Vector2.Zero, -1f)); } @@ -47,11 +56,12 @@ public void PortHitGeometryPreservesMissingAndExplicitLabelBounds() public void ChangingOneOfTwoThousandNodesPreservesOtherGeometry() { GraphCanvasNode[] nodes = Enumerable.Range(0, 2000) - .Select(index => Node("workflow." + index, new(index * 220f, 0f))).ToArray(); + .Select(index => Node("workflow." + index, new GraphPosition(index * 220f, 0f))) + .ToArray(); var layout = new GraphCanvasLayout(); Assert.Equal(2000, layout.SetNodes(nodes)); GraphCanvasNode retained = nodes[999]; - nodes[1000] = Node(nodes[1000].id.value, new(100f, 200f)); + nodes[1000] = Node(nodes[1000].id.value, new GraphPosition(100f, 200f)); Assert.Equal(1, layout.SetNodes(nodes)); Assert.True(layout.TryGetNode(retained.id, out GraphCanvasNode? current)); Assert.Same(retained, current); @@ -66,13 +76,26 @@ public void InvalidCandidatesDoNotReplaceTheCurrentSnapshot() _ = layout.SetNodes([node]); Assert.Throws(() => layout.SetNodes([node, node])); Assert.Same(node, Assert.Single(layout.nodes)); - Assert.Throws(() => new GraphCanvasNode(node.id, default, new(float.NaN, 10f), 2f, "Invalid", [])); - Assert.Throws(() => new GraphCanvasNode(node.id, default, new(200f, 100f), 24f, "Invalid", - [new GraphCanvasPort(new(new("foreign"), new("port")), GraphPortDirection.Input, Vector2.Zero, "Foreign")])); + Assert.Throws( + () => new GraphCanvasNode(node.id, default, new Vector2(float.NaN, 10f), 2f, "Invalid", []) + ); + Assert.Throws(() => new GraphCanvasNode( + node.id, + default, + new Vector2(200f, 100f), + 24f, + "Invalid", + [new GraphCanvasPort( + new GraphEndpoint(new GraphNodeID("foreign"), new GraphPortID("port")), + GraphPortDirection.Input, + Vector2.Zero, + "Foreign" + )] + )); } private static GraphCanvasNode Node( string id, GraphPosition position - ) => new(new(id), position, new(200f, 100f), 24f, id, []); + ) => new(new GraphNodeID(id), position, new Vector2(200f, 100f), 24f, id, []); } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs index f2f939da2..8adc01099 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs @@ -1,23 +1,24 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed class GraphCanvasViewTests { [Fact] public void FrameProjectionDoesNotChangeWhenLaterNavigationMutatesItsSource() { var state = new GraphCanvasState(); - var view = new GraphCanvasView(state, new(100f, 200f), new(800f, 600f)); - state.SetViewport(new(50f, 75f), 2f); - Assert.Equal(new Vector2(110f, 220f), view.ToScreen(new(10f, 20f))); + var view = new GraphCanvasView(state, new Vector2(100f, 200f), new Vector2(800f, 600f)); + state.SetViewport(new GraphPosition(50f, 75f), 2f); + Assert.Equal(new Vector2(110f, 220f), view.ToScreen(new GraphPosition(10f, 20f))); Assert.Equal(1f, view.zoom); - var next = new GraphCanvasView(state, new(100f, 200f), new(800f, 600f)); - Assert.Equal(new Vector2(170f, 315f), next.ToScreen(new(10f, 20f))); + var next = new GraphCanvasView(state, new Vector2(100f, 200f), new Vector2(800f, 600f)); + Assert.Equal(new Vector2(170f, 315f), next.ToScreen(new GraphPosition(10f, 20f))); Assert.Equal(2f, next.zoom); } @@ -28,9 +29,9 @@ public void FrameProjectionDoesNotChangeWhenLaterNavigationMutatesItsSource() public void ViewportRoundTripPreservesTheGraphPoint(float zoom) { var state = new GraphCanvasState(); - state.SetViewport(new(-172f, 38f), zoom); - var view = new GraphCanvasView(state, new(100f, 200f), new(800f, 600f)); - GraphPosition point = new(-21.25f, 90f); + state.SetViewport(new GraphPosition(-172f, 38f), zoom); + var view = new GraphCanvasView(state, new Vector2(100f, 200f), new Vector2(800f, 600f)); + var point = new GraphPosition(-21.25f, 90f); GraphPosition actual = view.ToGraph(view.ToScreen(point)); Assert.Equal(point.x, actual.x, 3); Assert.Equal(point.y, actual.y, 3); @@ -39,16 +40,18 @@ public void ViewportRoundTripPreservesTheGraphPoint(float zoom) [Fact] public void ConnectionHitTestUsesTheDisplayedRouteIncludingEndpoints() { - Assert.True(GraphCanvasView.HitConnection(new(0f, 0f), Vector2.Zero, new(200f, 100f))); - Assert.True(GraphCanvasView.HitConnection(new(100f, 50f), Vector2.Zero, new(200f, 100f))); - Assert.False(GraphCanvasView.HitConnection(new(100f, 120f), Vector2.Zero, new(200f, 100f))); - Assert.True(GraphCanvasView.HitConnection(new(200f, 100f), Vector2.Zero, new(200f, 100f))); + Assert.True(GraphCanvasView.HitConnection(new Vector2(0f, 0f), Vector2.Zero, new Vector2(200f, 100f))); + Assert.True(GraphCanvasView.HitConnection(new Vector2(100f, 50f), Vector2.Zero, new Vector2(200f, 100f))); + Assert.False(GraphCanvasView.HitConnection(new Vector2(100f, 120f), Vector2.Zero, new Vector2(200f, 100f))); + Assert.True(GraphCanvasView.HitConnection(new Vector2(200f, 100f), Vector2.Zero, new Vector2(200f, 100f))); } [Fact] public void InvalidViewportAndHitToleranceAreRejected() { - Assert.Throws(() => new GraphCanvasView(new GraphCanvasState(), Vector2.Zero, new(float.NaN, 100f))); + Assert.Throws( + () => new GraphCanvasView(new GraphCanvasState(), Vector2.Zero, new Vector2(float.NaN, 100f)) + ); Assert.Throws(() => GraphCanvasView.HitConnection(Vector2.Zero, Vector2.Zero, Vector2.One, -1f)); } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs b/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs new file mode 100644 index 000000000..d96f7acf5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorPanel("tests.host-service", "Host Service")] +public sealed class HostServicePanel : EditorPanel +{ + public static ITestHostService? current; + + public HostServicePanel(ITestHostService service) + { + current = service; + } + + protected override void OnDraw(EditorContext context) => _ = context; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs b/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs new file mode 100644 index 000000000..c38437405 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public interface ITestHostService; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs new file mode 100644 index 000000000..9c68bac5b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs @@ -0,0 +1,44 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.interaction")] +public sealed class InteractionAction : EditorPresentationAction +{ + private string m_value = string.Empty; + + protected override void Execute(EditorActionContext context) + { + m_value = "Initial"; + context.target.validationMessage = null; + Activate(context); + } + + protected override bool Present(EditorActionContext context) + { + InteractionPresentation presentation = context.argument; + if (presentation.cancel) + { + Cancel(); + return true; + } + + m_value = presentation.value; + if (!presentation.submit) + { + return true; + } + if (string.IsNullOrWhiteSpace(m_value)) + { + context.target.validationMessage = "A name is required."; + return true; + } + + context.target.committedValue = m_value; + context.target.validationMessage = null; + Complete(); + return true; + } + + protected override void OnCancelled() => m_value = string.Empty; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs new file mode 100644 index 000000000..e96736fda --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs @@ -0,0 +1,7 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class InteractionTarget +{ + public string? committedValue { get; set; } + public string? validationMessage { get; set; } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs new file mode 100644 index 000000000..7bcfb8bf1 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs @@ -0,0 +1,10 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu")] +[EditorMenu("tests/menu", "Tools/Create/Asset", order: 100)] +public sealed class MenuAction : EditorAction +{ + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs new file mode 100644 index 000000000..57338410c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs @@ -0,0 +1,13 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-conditional", "tests/shared-menu")] +[EditorMenu("tests/shared-menu", "Shared", order: 200)] +public sealed class MenuConditionalAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) + => context.target is MenuStateTarget { visible: true } ? EditorActionState.enabled : EditorActionState.hidden; + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs new file mode 100644 index 000000000..d346096b8 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs @@ -0,0 +1,10 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-fallback", "tests/shared-menu")] +[EditorMenu("tests/shared-menu", "Shared", order: 100)] +public sealed class MenuFallbackAction : EditorAction +{ + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs new file mode 100644 index 000000000..86b02ccb5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-state", "tests/static-menu")] +[EditorMenu("tests/static-menu", "Tools/State")] +public sealed class MenuStateAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) + => context.target is MenuStateTarget target + ? new EditorActionState(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") + : EditorActionState.hidden; + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs new file mode 100644 index 000000000..e5b67ba00 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs @@ -0,0 +1,9 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class MenuStateTarget +{ + public bool visible = true; + public bool enabled = true; + public bool isChecked; + public string label = "Current"; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs new file mode 100644 index 000000000..0d404cb07 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.action-metadata", "tests/action-metadata")] +public sealed class MetadataAction : EditorAction +{ + public static int targetTypeReadCount; + public static bool throwWhenRead; + + public override Type? targetType + { + get + { + targetTypeReadCount++; + return throwWhenRead ? throw new InvalidOperationException("Action metadata was read at runtime.") : typeof(BaseTarget); + } + } + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs b/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs new file mode 100644 index 000000000..5181f28d4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Editor.Presentation.Tests; + +[StableTypeID("0fbd66e2-303e-4b35-83a1-fc2b90d58360")] +[ProjectSettingDefinition("tests.editor.multi-presentation")] +public sealed class MultiPresentationSetting : ISerializable +{ + public static ProjectSettingID settingID => new("tests.editor.multi-presentation"); + + [SerializableProperty] + public int value { get; set; } = 7; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs new file mode 100644 index 000000000..b634b40dd --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs @@ -0,0 +1,14 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.multiple-shortcuts", "tests/multiple-shortcuts")] +[EditorShortcut("tests/multiple-shortcuts", KeyCode.F3)] +[EditorShortcut("tests/multiple-shortcuts", KeyCode.F4)] +public sealed class MultiShortcutAction : EditorAction +{ + public static int executeCount; + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs b/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs new file mode 100644 index 000000000..4ca626cab --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs @@ -0,0 +1,39 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorHistoryHandler(NeutralHistoryHandler.C_KIND)] +public sealed class NeutralHistoryHandler : EditorHistoryHandler +{ + public const string C_KIND = "tests/neutral-value"; + public static int value; + + public static EditorHistoryChange CreateChange( + int before, + int after + ) { + var bytes = new byte[sizeof(int) * 2]; + BitConverter.GetBytes(before).CopyTo(bytes, 0); + BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int)); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes)); + } + + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) => change.payload.length >= sizeof(int) * 2 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] bytes = change.payload.ReadBytes(); + value = BitConverter.ToInt32(bytes, direction == EditorHistoryDirection.Undo ? 0 : sizeof(int)); + return EditorHistoryResult.Success(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs b/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs new file mode 100644 index 000000000..8c57dfc6b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs @@ -0,0 +1,9 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Presentation.Tests; + +[ProjectSettingPath("Project/Tests/Multi/Primary")] +public sealed class PrimaryMultiPresentationEditor : ProjectSettingEditor +{ + protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs new file mode 100644 index 000000000..21b1f02f6 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorMenuSource("tests/failed-menu")] +public sealed class RejectedMenuSource : EditorMenuSource +{ + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + builder.Add("Partial", "tests.menu"); + throw new InvalidOperationException("Candidate menu source failed."); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs b/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs new file mode 100644 index 000000000..407a688eb --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs @@ -0,0 +1,9 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Presentation.Tests; + +[ProjectSettingPath("Project/Tests/Multi/Secondary")] +public sealed class SecondaryMultiPresentationEditor : ProjectSettingEditor +{ + protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs b/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs new file mode 100644 index 000000000..73ba0ca74 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace Inno.Editor.Presentation.Tests; + +internal static class ShutdownOrder +{ + internal static List events { get; } = []; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs new file mode 100644 index 000000000..001520a85 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs @@ -0,0 +1,26 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestDocumentProvider : EditorDocumentProvider +{ + public int openCount { get; private set; } + public int saveCount { get; private set; } + public int closeCount { get; private set; } + public override string id => "tests.documents"; + + public override bool CanOpen(string assetPath) + => assetPath.EndsWith(".ispriteatlas2d", StringComparison.Ordinal) + || assetPath.EndsWith(".itilemap2d", StringComparison.Ordinal); + + public override void Open(EditorDocumentContext context) => openCount++; + + public override bool Save(EditorDocumentContext context) + { + saveCount++; + return true; + } + + public override void Close(EditorDocumentContext context) => closeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs new file mode 100644 index 000000000..ea00f846c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorDrop("tests/drop")] +public sealed class TestDrop : EditorDrop +{ + protected override EditorDropStatus Query(EditorDropContext context) => EditorDropStatus.Accept(); + + protected override EditorDropResult Drop(EditorDropContext context) + { + context.target.wasDropped = true; + return EditorDropResult.Accepted(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs new file mode 100644 index 000000000..c184dbbc6 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestHostService : ITestHostService; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs new file mode 100644 index 000000000..998615d4c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs @@ -0,0 +1,74 @@ +using System; +using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Extensibility.Types; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.state")] +public sealed class TestModule : EditorModule +{ + public static int startCount; + public static int stopCount; + public static int stateValue; + public static int restoredStateValue; + public static bool rebuildDuringRestore; + public static bool captureFailure; + public static bool throwOnStart; + public static bool throwOnStop; + public static int pendingStops; + + private readonly TypeCatalog m_types; + + public TestModule(TypeCatalog types) + { + m_types = types; + } + + protected override void Capture(EditorState state) + { + if (captureFailure) + { + throw new InvalidOperationException("The test module state cannot be captured."); + } + state.Set("value", stateValue); + } + + protected override void Restore(EditorState state) + { + restoredStateValue = state.Get("value", 0); + if (!rebuildDuringRestore) + { + return; + } + rebuildDuringRestore = false; + m_types.Rebuild(); + } + + protected override void OnStart(EditorContext context) + { + startCount++; + if (throwOnStart) + { + throw new InvalidOperationException("Injected module startup failure."); + } + if (startCount == 1) + { + m_types.Rebuild(); + } + } + + protected override void OnStop(EditorContext context) + { + stopCount++; + ShutdownOrder.events.Add("module.stop"); + if (pendingStops-- > 0) + { + throw new RetirementPendingException("Module-owned work has not drained."); + } + if (throwOnStop) + { + throw new InvalidOperationException("Injected module stop failure."); + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs new file mode 100644 index 000000000..a7311eb23 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs @@ -0,0 +1,50 @@ +using System; +using Inno.Core.Execution; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorPanel("tests.panel", "Test", defaultOpen: false, menuPath: "Testing")] +public sealed class TestPanel(TestModule module) : EditorPanel +{ + public static int attachCount; + public static int detachCount; + public static bool firstAttachPrecededModuleStart; + public static bool throwFromWindowPadding; + public static bool throwOnAttach; + public static bool throwOnDetach; + public static int pendingDetaches; + + public override bool useWindowPadding + => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; + + protected override void OnAttach(EditorContext context) + { + _ = module; + if (attachCount == 0) + { + firstAttachPrecededModuleStart = TestModule.startCount == 0; + } + attachCount++; + if (throwOnAttach) + { + throw new InvalidOperationException("Injected panel attachment failure."); + } + } + + protected override void OnDetach(EditorContext context) + { + detachCount++; + ShutdownOrder.events.Add("panel.detach"); + if (pendingDetaches-- > 0) + { + throw new RetirementPendingException("Panel-owned work has not drained."); + } + if (throwOnDetach) + { + throw new InvalidOperationException("Injected panel detach failure."); + } + } + + protected override void OnDraw(EditorContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs new file mode 100644 index 000000000..d063a0e99 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs @@ -0,0 +1,11 @@ +using Inno.Core.Mathematics; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter +{ + public Vector2 ScreenToWorld(Vector2 screenPosition) => screenPosition * 2f; + + public Vector2 WorldToScreen(Vector2 worldPosition) => worldPosition / 2f; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs new file mode 100644 index 000000000..3392fddf5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs @@ -0,0 +1,31 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestViewportTool(IEditorHistory history) : EditorViewportTool +{ + public int downCount { get; private set; } + public int upCount { get; private set; } + public override string id => "tests.viewport.paint"; + public override EditorViewportCursor cursor => EditorViewportCursor.Crosshair; + + public override void OnPointerDown( + EditorViewportToolContext context, + EditorViewportPointerEvent pointer + ) { + downCount++; + context.CapturePointer(pointer.pointerID); + context.BeginHistoryGesture("Paint Tile"); + NeutralHistoryHandler.value = 1; + history.RecordApplied("Paint Tile Cell", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); + } + + public override void OnPointerUp( + EditorViewportToolContext context, + EditorViewportPointerEvent pointer + ) { + upCount++; + context.CompleteHistoryGesture(commit: true); + context.ReleasePointer(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs new file mode 100644 index 000000000..13f58da85 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs @@ -0,0 +1,18 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.throw-after-activate", "tests/throw-after-activate")] +public sealed class ThrowAfterActivateAction : EditorAction +{ + public static int cancelCount; + + protected override void Execute(EditorActionContext context) + { + Activate(context); + throw new InvalidOperationException("Injected action execution failure."); + } + + protected override void OnCancelled() => cancelCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs new file mode 100644 index 000000000..4ee053215 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.toolbar", "tests/toolbar")] +[EditorToolbarItem("tests/toolbar", EditorToolbarIcon.Play, "Start Runtime", activeIcon: EditorToolbarIcon.Stop)] +public sealed class ToolbarAction : EditorAction +{ + public static bool isChecked; + public static int executeCount; + + protected override EditorActionState Query(EditorActionContext context) + => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs new file mode 100644 index 000000000..d0d42caa4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs @@ -0,0 +1,21 @@ +using System; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.update-barrier", order: -200)] +public sealed class UpdateBarrierModule : EditorModule +{ + public static bool block; + public static bool throwWhenRead; + public static int barrierReadCount; + + public override bool blocksFollowingUpdates + { + get + { + barrierReadCount++; + return throwWhenRead ? throw new InvalidOperationException("Injected module barrier failure.") : block; + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs new file mode 100644 index 000000000..6285d81d0 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs @@ -0,0 +1,20 @@ +using System; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.throwing-dispose", order: 901)] +public sealed class ZThrowingDisposeModule : EditorModule +{ + public static bool throwOnDispose; + public static int disposeCount; + + protected override void OnDispose() + { + disposeCount++; + if (throwOnDispose) + { + throw new InvalidOperationException("Injected extension disposal failure."); + } + } +} diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs index 9f76c3b1c..21e3784f1 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs @@ -3,6 +3,7 @@ using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Testing.Editor.Native; @@ -23,17 +24,19 @@ internal NativeClipboard(ImGuiNativeContext* context) m_text = Marshal.StringToCoTaskMemUTF8(string.Empty); } - internal void ThrowIfFaulted() => m_failure?.Throw(); - public void Dispose() { if (!m_handle.IsAllocated) + { return; + } Marshal.FreeCoTaskMem(m_text); m_text = 0; m_handle.Free(); } + internal void ThrowIfFaulted() => m_failure?.Throw(); + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static sbyte* Read(ImGuiNativeContext* context) { diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs index 7a9ce7765..2b3a5c8ae 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; @@ -16,10 +17,11 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; + +using NativeCond = Inno.Native.ImGui.ImGuiCond; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using ImGuiCond = Inno.Native.ImGui.ImGuiCond; -using ImGuiWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; +using NativeWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; namespace Inno.Testing.Editor.Native; @@ -45,29 +47,50 @@ public sealed unsafe class NativePanelHost : IDisposable /// /// Creates a panel host with the default keyboard convention and vertex-offset validation disabled. /// - /// The calling test assembly owning the complete discovery closure. - /// Additional declared panel assemblies to load before discovery. - public NativePanelHost(Assembly composition, params string[] assemblies) : this(composition, false, assemblies) { } + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// + public NativePanelHost( + Assembly composition, + params string[] assemblies + ) : this(composition, false, assemblies) {} /// /// Creates a panel host with an explicit vertex-offset capability. /// - /// The calling test assembly owning the complete discovery closure. - /// Whether to advertise and validate native vertex offsets. - /// Additional declared panel assemblies to load before discovery. + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// public NativePanelHost( Assembly composition, bool supportsVertexOffsets, params string[] assemblies - ) : this(composition, supportsVertexOffsets, new EditorKeyboardPolicy(KeyModifier.Control, "Super"), assemblies) { } + ) : this(composition, supportsVertexOffsets, new EditorKeyboardPolicy(KeyModifier.Control, "Super"), assemblies) {} /// /// Creates the owned diagnostics, discovery, interactions and native frame context. /// - /// The calling test assembly owning the complete discovery closure. - /// Whether to advertise and validate native vertex offsets. - /// The explicit keyboard convention used by the test. - /// Additional declared panel assemblies to load before discovery. + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// The explicit keyboard convention used by the test. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// public NativePanelHost( Assembly composition, bool supportsVertexOffsets, @@ -78,17 +101,19 @@ params string[] assemblies m_ownsServices = true; Directory.CreateDirectory(m_root); foreach (string assembly in assemblies) + { _ = Assembly.Load(assembly); - diagnostics = new DiagnosticHub(); + } + this.diagnostics = new DiagnosticHub(); m_diagnosticScope = diagnostics.EnterScope(); - logs = new LogRouter(); - m_modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(composition) }); + this.logs = new LogRouter(); + m_modules = new ModuleHost(new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(composition) }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - console = new EditorConsole(logs, diagnostics, new InactivePlayMode()); + this.console = new EditorConsole(logs, diagnostics, new InactivePlayMode()); console.Start(); - runtime = new EditorInteractionRuntime(new EditorContext(m_root, keyboard), m_types, logs, [console]); + this.runtime = new EditorInteractionRuntime(new EditorContext(m_root, keyboard), m_types, logs, [console]); runtime.Start(); - ui = new EditorUiSession(); + this.ui = new EditorUISession(); m_nativeContext = CreateNativeContext(ui, supportsVertexOffsets); m_clipboard = new NativeClipboard(m_nativeContext); logs.Flush(); @@ -97,7 +122,7 @@ params string[] assemblies internal NativePanelHost( EditorInteractionRuntime runtime, - EditorUiSession ui, + EditorUISession ui, EditorConsole console, LogRouter logs, DiagnosticHub diagnostics, @@ -118,29 +143,39 @@ internal NativePanelHost( /// Gets the borrowed diagnostic hub for this host's lifetime. /// public DiagnosticHub diagnostics { get; } + /// /// Gets the borrowed log router for this host's lifetime. /// public LogRouter logs { get; } + /// /// Gets the borrowed console consuming the host's logs. /// public EditorConsole console { get; } + /// /// Gets the borrowed interaction runtime and discovered panels. /// public EditorInteractionRuntime runtime { get; } + /// /// Gets the borrowed UI session owning the host's frame state. /// - public EditorUiSession ui { get; } + public EditorUISession ui { get; } /// /// Finds and opens exactly one discovered panel. /// - /// The registered panel identity. - /// The borrowed panel, valid until this host is disposed. - /// The identity has no unique discovered panel. + /// + /// The registered panel identity. + /// + /// + /// The borrowed panel, valid until this host is disposed. + /// + /// + /// The identity has no unique discovered panel. + /// public EditorPanelExtension GetPanel(string id) { EditorPanelExtension panel = runtime.panels.Single(value => value.id == id); @@ -151,8 +186,12 @@ public EditorPanelExtension GetPanel(string id) /// /// Executes a real native frame and validates its resulting draw data. /// - /// The drawing operation executed within the UI scope. - /// The explicit elapsed frame time in seconds. + /// + /// The drawing operation executed within the UI scope. + /// + /// + /// The explicit elapsed frame time in seconds. + /// public void Frame( Action draw, float deltaTime = 1f / 60f @@ -170,7 +209,9 @@ public void Frame( { NativeImGui.Render(); if (m_validateVertexOffsets) + { ValidateDrawData(); + } m_clipboard.ThrowIfFaulted(); } } @@ -178,9 +219,15 @@ public void Frame( /// /// Sets the native display dimensions, framebuffer scale and UI zoom. /// - /// The logical display size in UI coordinates. - /// The physical framebuffer scale. - /// The UI style zoom. + /// + /// The logical display size in UI coordinates. + /// + /// + /// The physical framebuffer scale. + /// + /// + /// The UI style zoom. + /// public void SetDisplayMetrics( Vector2 logicalSize, float framebufferScale, @@ -188,8 +235,8 @@ float zoom ) { ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(logicalSize); - io->DisplayFramebufferScale = Unsafe.BitCast(new(framebufferScale)); - m_panelSize = Vector2.Min(new(1000f, 800f), logicalSize - new Vector2(40f)); + io->DisplayFramebufferScale = Unsafe.BitCast(new Vector2(framebufferScale)); + m_panelSize = Vector2.Min(new Vector2(1000f, 800f), logicalSize - new Vector2(40f)); ui.widgets.style.SetZoom(zoom); using IDisposable scope = ui.Enter(); ui.widgets.SetupStyle(); @@ -198,39 +245,48 @@ float zoom /// /// Draws the actual panel inside a bounded native window and completes the frame. /// - /// The borrowed panel belonging to this host's interaction runtime. - /// An optional operation performed after the panel draws and before the window closes. - /// The explicit elapsed frame time in seconds. - /// The panel is quarantined by a real draw failure. + /// + /// The borrowed panel belonging to this host's interaction runtime. + /// + /// + /// An optional operation performed after the panel draws and before the window closes. + /// + /// + /// The explicit elapsed frame time in seconds. + /// + /// + /// The panel is quarantined by a real draw failure. + /// public void DrawPanel( EditorPanelExtension panel, Action? afterDraw = null, float deltaTime = 1f / 60f - ) { - Frame(() => + ) => Frame(() => + { + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)NativeCond.Always); + NativeImGui.SetNextWindowSize(m_panelSize, (int)NativeCond.Always); + bool open = true; + _ = NativeImGui.Begin("Panel acceptance", ref open, (int)NativeWindowFlags.NoSavedSettings); + try { - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)ImGuiCond.Always); - NativeImGui.SetNextWindowSize(m_panelSize, (int)ImGuiCond.Always); - bool open = true; - _ = NativeImGui.Begin("Panel acceptance", ref open, (int)ImGuiWindowFlags.NoSavedSettings); - try + if (panel.isOpen && !panel.Draw(runtime.context)) { - if (panel.isOpen && !panel.Draw(runtime.context)) - { - logs.Flush(); - string failures = string.Join(Environment.NewLine, console.Capture().occurrences + logs.Flush(); + string failures = string.Join( + Environment.NewLine, + console.Capture().occurrences .Where(static entry => entry.level >= LogLevel.Error) - .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace)); - throw new InvalidOperationException("The actual panel was quarantined: " + panel.id + Environment.NewLine + failures); - } - afterDraw?.Invoke(); - } - finally - { - NativeImGui.End(); + .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace) + ); + throw new InvalidOperationException("The actual panel was quarantined: " + panel.id + Environment.NewLine + failures); } - }, deltaTime); - } + afterDraw?.Invoke(); + } + finally + { + NativeImGui.End(); + } + }, deltaTime); /// /// Releases the owned UI, native context and services on their creating thread. @@ -253,11 +309,13 @@ public void Dispose() NativeImGui.Raw.DestroyContext(m_nativeContext); m_clipboard.Dispose(); if (m_ownsServices) + { Directory.Delete(m_root, recursive: true); + } } private static ImGuiNativeContext* CreateNativeContext( - EditorUiSession ui, + EditorUISession ui, bool supportsVertexOffsets ) { ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); @@ -266,14 +324,18 @@ bool supportsVertexOffsets io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; if (supportsVertexOffsets) + { io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasVtxOffset; + } io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; // Fixture input uses an explicit Control convention on every runner. io->ConfigMacOsxBehaviors = 0; io->Fonts->RendererHasTextures = 1; io->IniFilename = null; using (ui.Enter()) + { ui.widgets.SetupStyle(); + } return context; } @@ -288,23 +350,34 @@ private static void ValidateDrawData() ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; ulong lastIndex = (ulong)command.IdxOffset + command.ElemCount; if (lastIndex > (ulong)list->IdxBuffer.Size) + { throw new InvalidOperationException("Native draw data exceeded its index buffer."); + } for (ulong index = command.IdxOffset; index < lastIndex; index++) + { if ((ulong)command.VtxOffset + list->IdxBuffer.Data[index] >= (ulong)list->VtxBuffer.Size) - throw new InvalidOperationException("Native draw data exceeded its vertex buffer after applying the command offset."); + { + throw new InvalidOperationException( + "Native draw data exceeded its vertex buffer after applying the command offset." + ); + } + } } } } internal sealed class InactivePlayMode : IEditorPlayMode { - private readonly Inno.Core.Events.EventDispatcher m_events = new(); + private readonly EventDispatcher m_events = new(); public EditorPlayModeState state => EditorPlayModeState.Editing; public bool isPlaying => false; public string? lastFailure => null; - public LogSessionId activeSessionId => LogSessionId.none; + public LogSessionID activeSessionID => LogSessionID.none; + public IDisposable ListenStateChanges(Action listener) => m_events.CreateHub(); + public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } } diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs index db46f1b8f..c48958ecc 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Inno.Editor.Interactions; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Testing.Editor.Native; @@ -14,40 +15,56 @@ public static unsafe class NativePanelInput /// /// Focuses the actual active native window matching the requested fragment. /// - /// The current thread's live native host. - /// The panel drawn to discover its window. - /// The required fragment of the actual native window name. - /// No active native window matches the fragment. + /// + /// The current thread's live native host. + /// + /// + /// The panel drawn to discover its window. + /// + /// + /// The required fragment of the actual native window name. + /// + /// + /// No active native window matches the fragment. + /// public static void Focus( NativePanelHost host, EditorPanelExtension panel, string windowFragment - ) { - host.DrawPanel(panel, () => + ) => host.DrawPanel(panel, () => + { + ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); + for (int index = 0; index < context->Windows.Size; index++) { - ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - for (int index = 0; index < context->Windows.Size; index++) + ImGuiWindow* window = context->Windows.Data[index]; + string? name = Marshal.PtrToStringUTF8((nint)window->Name); + if (window->Active != 0 && name?.Contains(windowFragment, StringComparison.Ordinal) == true) { - ImGuiWindow* window = context->Windows.Data[index]; - string? name = Marshal.PtrToStringUTF8((nint)window->Name); - if (window->Active != 0 && name?.Contains(windowFragment, StringComparison.Ordinal) == true) - { - NativeImGui.Raw.SetWindowFocus(window->Name); - return; - } + NativeImGui.Raw.SetWindowFocus(window->Name); + return; } - throw new InvalidOperationException("The actual input owner window is absent: " + windowFragment); - }); - } + } + throw new InvalidOperationException("The actual input owner window is absent: " + windowFragment); + }); /// /// Delivers a complete key press and release through actual native frames. /// - /// The current thread's live native host. - /// The panel receiving input. - /// The native key to press. - /// Whether to hold Shift during the key press. - /// Whether to hold the fixture's Control convention during the key press. + /// + /// The current thread's live native host. + /// + /// + /// The panel receiving input. + /// + /// + /// The native key to press. + /// + /// + /// Whether to hold Shift during the key press. + /// + /// + /// Whether to hold the fixture's Control convention during the key press. + /// public static void Key( NativePanelHost host, EditorPanelExtension panel, @@ -57,16 +74,24 @@ public static void Key( ) { ImGuiIO* io = NativeImGui.Raw.GetIO(); if (shift) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModShift, 1); + } if (primary) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 1); + } NativeImGui.Raw.AddKeyEvent(io, key, 1); host.DrawPanel(panel); NativeImGui.Raw.AddKeyEvent(io, key, 0); if (shift) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModShift, 0); + } if (primary) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 0); + } host.DrawPanel(panel); } } diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs index ba4ecd953..59a5ef26d 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs @@ -1,26 +1,26 @@ using System; using System.IO; using System.Reflection; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Input; -using Inno.Core.IO; using Inno.Core.Logging; -using Inno.Core.Settings; using Inno.Core.Serialization; +using Inno.Core.Settings; using Inno.Editor.Core; using Inno.Editor.Diagnostics; -using Inno.Editor.ImGui; using Inno.Editor.Graph; +using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; -using Xunit; namespace Inno.Testing.Editor.Native; @@ -43,10 +43,18 @@ public sealed class NativeProjectPanelHost : IDisposable /// /// Creates the explicit test composition and its isolated project resources. /// - /// The calling test assembly declaring all discovered modules and serialized test types. - /// Whether to advertise and validate native vertex offsets. - /// Whether to compose real project and build settings services. - /// An optional public document-store boundary for settings persistence. + /// + /// The calling test assembly declaring all discovered modules and serialized test types. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// Whether to compose real project and build settings services. + /// + /// + /// An optional public document-store boundary for settings persistence. + /// public NativeProjectPanelHost( Assembly composition, bool supportsVertexOffsets = false, @@ -64,85 +72,127 @@ public NativeProjectPanelHost( m_engine = new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(composition), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); m_session = m_engine.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, - applicationId = "inno.tests.native-panels", + applicationID = "inno.tests.native-panels", createLogSink = _ => new FileLogSink(Path.Combine(library, "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread }); m_execution = m_session.EnterExecutionScope(); var identities = new IdentityAllocator(); - assets = new AssetPipeline(m_engine.modules, m_engine.types, m_engine.serialization, identities, - m_engine.diagnostics, m_engine.logs, AssetPipelineOptions.Create(source, library) with { enableFileSystemWatcher = false }); - m_settings = new ProjectSettingsStore(settingsDocument ?? new FileByteDocumentStore(Path.Combine(m_root, "Settings.Project.inno")), - m_engine.types, m_engine.serialization, new ProjectId("tests.native-panels"), AssetSerializationContext.Create(assets)); + this.assets = new AssetPipeline( + m_engine.modules, + m_engine.types, + m_engine.serialization, + identities, + m_engine.diagnostics, + m_engine.logs, + AssetPipelineOptions.Create(source, library) with { enableFileSystemWatcher = false } + ); + m_settings = new ProjectSettingsStore( + settingsDocument ?? new FileByteDocumentStore(Path.Combine(m_root, "Settings.Project.inno")), + m_engine.types, + m_engine.serialization, + new ProjectID("tests.native-panels"), + AssetSerializationContext.Create(assets) + ); var pluginSources = new PluginSourceService(m_engine.serialization, pluginRoot, library); - m_plugins = new PluginEnvironment(assets, m_settings, m_engine.serialization, pluginRoot, library, pluginSources.Scan(), m_engine.modules.generations); + m_plugins = new PluginEnvironment( + assets, + m_settings, + m_engine.serialization, + pluginRoot, + library, + pluginSources.Scan(), + m_engine.modules.generations + ); m_console = new EditorConsole(m_engine.logs, m_engine.diagnostics, new NativePanelHost.InactivePlayMode()); m_console.Start(); - var ui = new EditorUiSession(); - reloads = new EditorReloadCoordinator(); + var ui = new EditorUISession(); + this.reloads = new EditorReloadCoordinator(); SettingsPanelServices? settingsServices = includeSettings - ? new SettingsPanelServices(m_root, assets, m_plugins, m_settings, m_engine) - : null; + ? new SettingsPanelServices(m_root, assets, m_plugins, m_settings, m_engine) + : null; if (includeSettings) + { _ = Assembly.Load("Inno.Editor.Panel.Settings"); - runtime = new EditorInteractionRuntime( + } + this.runtime = new EditorInteractionRuntime( new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), m_engine.types, m_engine.logs, [ - m_engine.types, m_engine.serialization, m_session, identities, m_session.identities, - assets, m_plugins, m_settings, reloads, ui, m_console, + m_engine.types, + m_engine.serialization, + m_session, + identities, + m_session.identities, + assets, + m_plugins, + m_settings, + reloads, + ui, + m_console, .. (settingsServices?.services ?? []) - ]); + ] + ); runtime.Start(); _ = runtime.panelCount; - Assert.True(runtime.interactions.TryGetModule(out var probe)); - workspace = probe!.workspace; - graphs = probe.graphs; - edits = probe.edits; - native = new NativePanelHost(runtime, ui, m_console, m_engine.logs, m_engine.diagnostics, supportsVertexOffsets); + Assert.True(runtime.interactions.TryGetModule(out NativeProjectPanelProbe? probe)); + this.workspace = probe!.workspace; + this.graphs = probe.graphs; + this.edits = probe.edits; + this.native = new NativePanelHost(runtime, ui, m_console, m_engine.logs, m_engine.diagnostics, supportsVertexOffsets); } /// /// Gets the borrowed reload coordinator. /// public EditorReloadCoordinator reloads { get; } + /// /// Gets the borrowed project settings store. /// public ProjectSettingsStore projectSettings => m_settings; + /// /// Gets the borrowed authoring asset pipeline. /// public AssetPipeline assets { get; } + /// /// Gets the borrowed engine serialization registry. /// public SerializationRegistry serialization => m_engine.serialization; + /// /// Gets the absolute temporary project directory removed during disposal. /// public string projectRoot => m_root; + /// /// Gets the borrowed interaction runtime. /// public EditorInteractionRuntime runtime { get; } + /// /// Gets the borrowed scene workspace resolved through normal module composition. /// public IEditorSceneWorkspace workspace { get; } + /// /// Gets the borrowed graph editor module. /// public GraphEditorModule graphs { get; } + /// /// Gets the borrowed scene editing service. /// public SceneEdits edits { get; } + /// /// Gets the borrowed native panel host. /// @@ -151,8 +201,11 @@ public NativeProjectPanelHost( /// /// Creates and loads an additive scene in the owned Edit session. /// - /// The scene owned by this fixture's session. + /// + /// The scene owned by this fixture's session. + /// public GameScene CreateScene() => m_session.scenes.LoadNewSceneAdditive(); + /// /// Rebuilds the actual type catalog after a declared discovery change. /// diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs index d502b116b..ed7251eaa 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs @@ -1,30 +1,39 @@ using Inno.Editor.Core; +using Inno.Editor.Graph; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Editor.Graph; namespace Inno.Testing.Editor.Native; /// /// Resolves the actual workspace and editing services through public Editor module composition. /// -/// The composed scene workspace. -/// The composed graph editor module. -/// The composed scene editing service. +/// +/// The composed scene workspace. +/// +/// +/// The composed graph editor module. +/// +/// +/// The composed scene editing service. +/// [EditorModule("tests.native-project-panels", order: 2000)] public sealed class NativeProjectPanelProbe( IEditorSceneWorkspace workspace, GraphEditorModule graphs, SceneEdits edits -) : EditorModule { +) : EditorModule +{ /// /// Gets the borrowed scene workspace. /// public IEditorSceneWorkspace workspace { get; } = workspace; + /// /// Gets the borrowed graph editor module. /// public GraphEditorModule graphs { get; } = graphs; + /// /// Gets the borrowed scene editing service. /// diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs index c7d1a8448..fe4871c7a 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs @@ -23,36 +23,52 @@ internal SettingsPanelServices( ProjectSettingsStore settings, EngineHost engine ) { - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler(new ScriptCompilerOptions { projectRootDirectory = root, compilationEnvironment = new SdkScriptCompilationEnvironment(host, root) }, assets, plugins); var target = new FixtureTarget(); - var pipeline = new BuildPipeline(assets, plugins, settings, engine.serialization, engine.modules.generations, - compiler, Path.Combine(root, "SupportPacks"), [new GameBuildTargetBinding(target, target)], - new ManagedDeploymentCatalog([new FixtureDeployment()])); - var build = new BuildSettingsStore(Path.Combine(root, "Settings.Build.inno"), engine.serialization, - BuildSettings.CreateDefault("Settings acceptance", string.Empty, target.id)); - services = [pipeline, build]; + var pipeline = new BuildPipeline( + assets, + plugins, + settings, + engine.serialization, + engine.modules.generations, + compiler, + Path.Combine(root, "SupportPacks"), + [new GameBuildTargetBinding(target, target)], + new ManagedDeploymentCatalog([new FixtureDeployment()]) + ); + var build = new BuildSettingsStore( + Path.Combine(root, "Settings.Build.inno"), + engine.serialization, + BuildSettings.CreateDefault("Settings acceptance", string.Empty, target.id) + ); + this.services = [pipeline, build]; } internal IReadOnlyList services { get; } private sealed class FixtureTarget : IGameBuildTarget, IGameContentCompiler { - public BuildTargetId id => new("tests-ui-settings"); - public BuildTargetId target => id; - public ManagedDeploymentId defaultManagedDeployment => new("tests-ui-managed"); + public BuildTargetID id => new("tests-ui-settings"); + public BuildTargetID target => id; + public ManagedDeploymentID defaultManagedDeployment => new("tests-ui-managed"); public string runtimeIdentifier => "tests-ui-rid"; public string displayName => "Settings fixture"; + public void Validate(string directory) => throw new NotSupportedException("Settings acceptance does not package players."); + public ValueTask PackageAsync( GameBuildPackageContext context, CancellationToken cancellationToken = default ) => throw new NotSupportedException("Settings acceptance does not package players."); + public ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default @@ -61,8 +77,9 @@ public ValueTask CompileAsync( private sealed class FixtureDeployment : IManagedDeploymentCompiler { - public ManagedDeploymentId id => new("tests-ui-managed"); + public ManagedDeploymentID id => new("tests-ui-managed"); public ManagedDeploymentCapabilities capabilities => new(["tests-ui-rid"], true, false, false); + public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs index 5a973a546..64a730b05 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs @@ -3,10 +3,10 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Adapter.Modules.DotNet; -using Xunit; namespace Inno.Extensibility.Modules.Tests; @@ -31,7 +31,9 @@ public void IsolatedHostDiscoversItsOwnTypesAndReleasesItsContext() finally { if (Directory.Exists(cache)) + { Directory.Delete(cache, recursive: true); + } } } @@ -51,11 +53,11 @@ private static WeakReference DiscoverInIsolatedContext(string cache) object options = Activator.CreateInstance(optionsType)!; optionsType.GetProperty(nameof(ModuleHostOptions.catalogSource))!.SetValue(options, source); Type hostType = modules.GetType(typeof(ModuleHost).FullName!, throwOnError: true)!; - using var host = (IDisposable)Activator.CreateInstance(hostType, options)!; + using IDisposable host = (IDisposable)Activator.CreateInstance(hostType, options)!; Type catalogType = types.GetType(typeof(TypeCatalog).FullName!, throwOnError: true)!; Type metadataType = adapter.GetType(typeof(ReflectionTypeCatalogSource).FullName!, throwOnError: true)!; object metadata = Activator.CreateInstance(metadataType)!; - using var catalog = (IDisposable)Activator.CreateInstance(catalogType, host, metadata)!; + using IDisposable catalog = (IDisposable)Activator.CreateInstance(catalogType, host, metadata)!; object snapshot = catalogType.GetProperty(nameof(TypeCatalog.current))!.GetValue(catalog)!; MethodInfo query = snapshot.GetType().GetMethod(nameof(TypeCacheSnapshot.TryGetTypeRef))!; Assert.True((bool)query.Invoke(snapshot, [hostType, null])!); @@ -73,7 +75,9 @@ private sealed class IsolatedHostContext() : AssemblyLoadContext("Inno isolated protected override Assembly? Load(AssemblyName assemblyName) { if (!(assemblyName.Name ?? string.Empty).StartsWith("Inno.", StringComparison.Ordinal)) + { return null; + } string path = Path.Combine(AppContext.BaseDirectory, assemblyName.Name + ".dll"); return File.Exists(path) ? LoadFromAssemblyPath(path) : null; } diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs similarity index 80% rename from tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs rename to tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs index a7f77dc10..7ec6b8bc8 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs @@ -1,4 +1,3 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; @@ -6,24 +5,41 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using System.Runtime.Loader; using System.Runtime.InteropServices; +using System.Runtime.Loader; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Reload; - -using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Modules.Tests; public sealed class ModuleHostTests : IDisposable { + private static readonly AsyncLocal ASYNC_ROOT = new(); + + private static readonly Guid RELOADABLE_TYPE_ID = Guid.Parse("44a4cda2-a03e-4918-8db2-f37048a9e4f1"); + private static object? s_retained; - private static readonly AsyncLocal S_ASYNC_ROOT = new(); - private static event Action? s_signal; + + private readonly string m_cacheDirectory = Path.Combine( + Path.GetTempPath(), + "InnoModuleHostTests", + Guid.NewGuid().ToString("N") + ); + + private readonly ModuleHost m_modules; + private readonly TypeCatalog m_types; + + public ModuleHostTests() + { + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleHostTests).Assembly)} + ); + m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + } [Fact] public void RepeatedReloadCollectsEveryRetiredContextBeforeNextGeneration() @@ -68,92 +84,25 @@ public void RetainedGenerationRootsCannotPassTheUnloadBarrier(string kind) Assert.Throws(() => barrier.Advance()); } - [MethodImpl(MethodImplOptions.NoInlining)] - private IDisposable CreateRetention(string kind) - { - Type type = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); - switch (kind) - { - case "async-local": - S_ASYNC_ROOT.Value = type; - return new Retention(() => S_ASYNC_ROOT.Value = null); - case "static": - s_retained = type; - return new Retention(() => s_retained = null); - case "event": - Action handler = () => GC.KeepAlive(type); - s_signal += handler; - s_signal?.Invoke(); - return new Retention(() => s_signal -= handler); - case "task": - s_retained = Task.FromResult(type); - return new Retention(() => s_retained = null); - case "thread": - var stop = new ManualResetEventSlim(); - var started = new ManualResetEventSlim(); - var thread = new Thread(() => { started.Set(); stop.Wait(); GC.KeepAlive(type); }); - thread.Start(); - started.Wait(); - return new Retention(() => { stop.Set(); thread.Join(); stop.Dispose(); started.Dispose(); }); - case "handle": - GCHandle handle = GCHandle.Alloc(type); - return new Retention(handle.Free); - case "callback": - NativeCallback callback = () => GC.KeepAlive(type); - IntPtr pointer = Marshal.GetFunctionPointerForDelegate(callback); - GCHandle root = GCHandle.Alloc(callback); - InvokeNativeCallback(pointer); - return new Retention(root.Free); - default: - throw new ArgumentOutOfRangeException(nameof(kind)); - } - } - - private static unsafe void InvokeNativeCallback(IntPtr pointer) - => ((delegate* unmanaged[Cdecl])pointer)(); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate void NativeCallback(); - - private sealed class Retention(Action release) : IDisposable - { - private Action? m_release = release; - public void Dispose() => Interlocked.Exchange(ref m_release, null)?.Invoke(); - } - - private static readonly Guid S_RELOADABLE_TYPE_ID = - Guid.Parse("44a4cda2-a03e-4918-8db2-f37048a9e4f1"); - - private readonly string m_cacheDirectory = Path.Combine( - Path.GetTempPath(), - "InnoModuleHostTests", - Guid.NewGuid().ToString("N")); - private readonly ModuleHost m_modules; - private readonly TypeCatalog m_types; - - public ModuleHostTests() - { - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleHostTests).Assembly)}); - m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - } - public void Dispose() { m_types.Dispose(); m_modules.Dispose(); ForceCollection(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } [Fact] public void LoadAndReloadPublishOnlyTheActiveGeneration() { AssemblyModuleHandle handle = LoadVersion("V1"); - TypeRef previousRef = new(S_RELOADABLE_TYPE_ID); + var previousRef = new TypeRef(RELOADABLE_TYPE_ID); Type previous = previousRef.Resolve(m_types); Assert.Equal(1, ReadVersion(previous)); - int previousRuntimeId = m_types.GetTypeRef(previous).runtimeId; + int previousRuntimeID = m_types.GetTypeRef(previous).runtimeID; using AssemblyReloadSession reload = m_modules.BeginReload(handle, CreateRequest("V2")); TypeCacheReloadContext typeReload = reload.context.GetContext(); @@ -163,15 +112,15 @@ public void LoadAndReloadPublishOnlyTheActiveGeneration() Assert.Same(previous, previousRef.Resolve(typeReload.previous)); Assert.Equal(previousRef, candidateRef); Assert.Equal(previousRef.GetHashCode(), candidateRef.GetHashCode()); - Assert.NotEqual(previousRef.runtimeId, candidateRef.runtimeId); + Assert.NotEqual(previousRef.runtimeID, candidateRef.runtimeID); reload.Activate(); Type current = previousRef.Resolve(m_types); Assert.Same(candidate, current); Assert.Equal(2, ReadVersion(current)); - int currentRuntimeId = m_types.GetTypeRef(current).runtimeId; - Assert.NotEqual(previousRuntimeId, currentRuntimeId); + int currentRuntimeID = m_types.GetTypeRef(current).runtimeID; + Assert.NotEqual(previousRuntimeID, currentRuntimeID); _ = reload.Complete(); Assert.Throws(() => _ = typeReload.previous); } @@ -190,19 +139,18 @@ public void RollbackRestoresThePreviousTypeAndRegistrySnapshot() reload.Rollback(); Assert.Same(previous, Assert.Single(registry.types)); - Assert.Same(previous, new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types)); + Assert.Same(previous, new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types)); } [Fact] public void InvalidCandidateLeavesTheActiveGenerationUntouched() { AssemblyModuleHandle handle = LoadVersion("V1"); - Type previous = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); + Type previous = new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types); - Assert.Throws( - () => m_modules.BeginReload(handle, CreateRequest("Invalid"))); + Assert.Throws(() => m_modules.BeginReload(handle, CreateRequest("Invalid"))); - Assert.Same(previous, new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types)); + Assert.Same(previous, new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types)); Assert.Equal(1, m_modules.modules.Single().generation); } @@ -269,27 +217,21 @@ public void ExplicitPluginDependenciesUseSeparateContextsAndRemoveAtomically() _ = addition.Complete(); } - AssemblyModuleInfo consumerInfo = m_modules.modules.Single(module => - module.moduleName == consumer.moduleName); + AssemblyModuleInfo consumerInfo = m_modules.modules.Single(module => module.moduleName == consumer.moduleName); Assert.Equal([dependency.moduleName], consumerInfo.upstreamModuleNames); - Type consumerType = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); + Type consumerType = new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types); Assert.Equal(1, ReadVersion(consumerType)); - Assembly dependencyAssembly = AppDomain.CurrentDomain.GetAssemblies().Single(assembly => - string.Equals( - assembly.GetName().Name, - "Reloadable.PrivateDependency", - StringComparison.Ordinal) && - AssemblyLoadContext.GetLoadContext(assembly)?.IsCollectible == true); + Assembly dependencyAssembly = AppDomain.CurrentDomain.GetAssemblies().Single(assembly => ( + string.Equals(assembly.GetName().Name, "Reloadable.PrivateDependency", StringComparison.Ordinal) + && AssemblyLoadContext.GetLoadContext(assembly)?.IsCollectible == true + )); Assert.NotSame( AssemblyLoadContext.GetLoadContext(consumerType.Assembly), - AssemblyLoadContext.GetLoadContext(dependencyAssembly)); - - Assert.Throws(() => m_modules.BeginReload( - [], - [dependency.moduleName])); - using (AssemblyReloadSession removal = m_modules.BeginReload( - [], - [consumer.moduleName, dependency.moduleName])) + AssemblyLoadContext.GetLoadContext(dependencyAssembly) + ); + + Assert.Throws(() => m_modules.BeginReload([], [dependency.moduleName])); + using (AssemblyReloadSession removal = m_modules.BeginReload([], [consumer.moduleName, dependency.moduleName])) { removal.Activate(); _ = removal.Complete(); @@ -313,7 +255,7 @@ public void CompletedReloadAllowsThePreviousContextToUnload() public void RetainingOnlyTypeRefDoesNotPreventPreviousContextUnload() { AssemblyModuleHandle handle = LoadVersion("V1"); - var retained = new List { new(S_RELOADABLE_TYPE_ID) }; + List retained = [new TypeRef(RELOADABLE_TYPE_ID)]; IAssemblyUnloadProbe monitor = CompleteReload(handle); ForceCollection(); @@ -340,26 +282,27 @@ public void RetainedClrTypeKeepsUnloadPendingUntilTheHostReleasesIt() } [Fact] - public void RolledBackCandidateRuntimeIdsAreNeverReused() + public void RolledBackCandidateRuntimeIDsAreNeverReused() { AssemblyModuleHandle handle = LoadVersion("V1"); using var registry = new ReloadableTypeRegistry(m_types); _ = registry.types; registry.failActivation = true; - Type previous = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); - int previousRuntimeId = m_types.GetTypeRef(previous).runtimeId; + Type previous = new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types); + int previousRuntimeID = m_types.GetTypeRef(previous).runtimeID; using (AssemblyReloadSession failed = m_modules.BeginReload(handle, CreateRequest("V2"))) + { Assert.Throws(failed.Activate); - int rejectedRuntimeId = registry.lastBuiltRef.runtimeId; + } + int rejectedRuntimeID = registry.lastBuiltRef.runtimeID; registry.failActivation = false; using AssemblyReloadSession accepted = m_modules.BeginReload(handle, CreateRequest("V2")); TypeCacheReloadContext context = accepted.context.GetContext(); - TypeRef acceptedRef = context.candidate.GetTypeRef( - new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(context.candidate)); - Assert.NotEqual(previousRuntimeId, rejectedRuntimeId); - Assert.NotEqual(rejectedRuntimeId, acceptedRef.runtimeId); + TypeRef acceptedRef = context.candidate.GetTypeRef(new TypeRef(RELOADABLE_TYPE_ID).Resolve(context.candidate)); + Assert.NotEqual(previousRuntimeID, rejectedRuntimeID); + Assert.NotEqual(rejectedRuntimeID, acceptedRef.runtimeID); accepted.Activate(); _ = accepted.Complete(); } @@ -383,7 +326,7 @@ public void CompletionCleanupFailureDoesNotUndoPublicationOrSkipFollowingPartici Assert.Equal(1, throwing.completeCount); Assert.Equal(1, following.completeCount); Assert.Equal(2, m_modules.modules.Single().generation); - Assert.Equal(Inno.Extensibility.Reload.GenerationState.Faulted, m_modules.generations.state); + Assert.Equal(GenerationState.Faulted, m_modules.generations.state); throwing.throwOnComplete = false; } @@ -397,7 +340,9 @@ public void RejectedCatalogRemainsReadableAndIgnoresNonParticipatingAssemblyLoad Assert.Throws(m_modules.Rebuild); Assert.Same(previous, m_types.current); _ = AssemblyBuilder.DefineDynamicAssembly( - new AssemblyName("Ignored.Dynamic." + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.RunAndCollect); + new AssemblyName("Ignored.Dynamic." + Guid.NewGuid().ToString("N")), + AssemblyBuilderAccess.RunAndCollect + ); m_modules.Refresh(); Assert.Same(previous, m_types.current); rejecting.throwOnActivate = false; @@ -423,7 +368,8 @@ public void RollbackCleanupFailureDoesNotSkipRemainingParticipants() using AssemblyReloadSession reload = m_modules.BeginReload( m_modules.modules.Single().handle, - CreateRequest("V2")); + CreateRequest("V2") + ); Assert.Throws(reload.Activate); activationFailure.throwOnActivate = false; throwing.throwOnRollback = false; @@ -431,15 +377,13 @@ public void RollbackCleanupFailureDoesNotSkipRemainingParticipants() Assert.Equal(1, observer.rollbackCount); Assert.Equal(1, throwing.rollbackCount); Assert.Equal(1, m_modules.modules.Single().generation); - Assert.Equal(Inno.Extensibility.Reload.GenerationState.Faulted, m_modules.generations.state); + Assert.Equal(GenerationState.Faulted, m_modules.generations.state); } [Fact] public void ExternalRegistrationIsNonOwningAndImmediatelyUnloadable() { - AssemblyModuleHandle handle = m_modules.Register( - "ExternalTests", - [typeof(ModuleHostTests).Assembly]); + AssemblyModuleHandle handle = m_modules.Register("ExternalTests", [typeof(ModuleHostTests).Assembly]); AssemblyModuleInfo info = Assert.Single(m_modules.modules); Assert.True(info.externallyOwned); @@ -450,6 +394,60 @@ public void ExternalRegistrationIsNonOwningAndImmediatelyUnloadable() Assert.Empty(m_modules.modules); } + private static event Action? s_signal; + + [MethodImpl(MethodImplOptions.NoInlining)] + private IDisposable CreateRetention(string kind) + { + Type type = new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types); + switch (kind) + { + case "async-local": + ASYNC_ROOT.Value = type; + return new Retention(() => ASYNC_ROOT.Value = null); + case "static": + s_retained = type; + return new Retention(() => s_retained = null); + case "event": + Action handler = () => GC.KeepAlive(type); + s_signal += handler; + s_signal?.Invoke(); + return new Retention(() => s_signal -= handler); + case "task": + s_retained = Task.FromResult(type); + return new Retention(() => s_retained = null); + case "thread": + var stop = new ManualResetEventSlim(); + var started = new ManualResetEventSlim(); + var thread = new Thread(() => + { + started.Set(); + stop.Wait(); + GC.KeepAlive(type); + }); + thread.Start(); + started.Wait(); + return new Retention(() => + { + stop.Set(); + thread.Join(); + stop.Dispose(); + started.Dispose(); + }); + case "handle": + GCHandle handle = GCHandle.Alloc(type); + return new Retention(handle.Free); + case "callback": + NativeCallback callback = () => GC.KeepAlive(type); + nint pointer = Marshal.GetFunctionPointerForDelegate(callback); + GCHandle root = GCHandle.Alloc(callback); + InvokeNativeCallback(pointer); + return new Retention(root.Free); + default: + throw new ArgumentOutOfRangeException(nameof(kind)); + } + } + [MethodImpl(MethodImplOptions.NoInlining)] private IAssemblyUnloadProbe CompleteReload(AssemblyModuleHandle handle) { @@ -460,40 +458,38 @@ private IAssemblyUnloadProbe CompleteReload(AssemblyModuleHandle handle) [MethodImpl(MethodImplOptions.NoInlining)] private StrongTypeHolder CreateStrongTypeHolder() - => new(new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types)); + => new(new TypeRef(RELOADABLE_TYPE_ID).Resolve(m_types)); - [MethodImpl(MethodImplOptions.NoInlining)] - private static void ClearStrongTypeHolder(StrongTypeHolder holder) - => holder.type = null; - - private AssemblyModuleHandle LoadVersion(string version) - => m_modules.Load(CreateRequest(version)); + private AssemblyModuleHandle LoadVersion(string version) => m_modules.Load(CreateRequest(version)); [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference CaptureRejectedCandidateContext(AssemblyModuleHandle handle) { WeakReference? candidateContext = null; - AssemblyLoadEventHandler capture = (_, args) => + AssemblyLoadEventHandler capture = ( + _, + args + ) => { AssemblyLoadContext? context = AssemblyLoadContext.GetLoadContext(args.LoadedAssembly); - if (context is { IsCollectible: true } && - context.Name?.StartsWith("ReloadableTests#2", StringComparison.Ordinal) == true) - { + if (context is { IsCollectible: true } + && context.Name?.StartsWith("ReloadableTests#2", StringComparison.Ordinal) == true + ) { candidateContext = new WeakReference(context); } }; AppDomain.CurrentDomain.AssemblyLoad += capture; try { - Assert.Throws( - () => m_modules.BeginReload(handle, CreateRequest("Invalid"))); + Assert.Throws(() => m_modules.BeginReload(handle, CreateRequest("Invalid"))); } finally { AppDomain.CurrentDomain.AssemblyLoad -= capture; } return candidateContext ?? throw new InvalidOperationException( - "The rejected candidate load context was not observed."); + "The rejected candidate load context was not observed." + ); } private DotNetModuleSource CreateRequest(string version) @@ -511,6 +507,12 @@ private DotNetModuleSource CreateRequest(string version) }; } + private static unsafe void InvokeNativeCallback(nint pointer) => ((delegate* unmanaged[Cdecl])pointer)(); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ClearStrongTypeHolder(StrongTypeHolder holder) + => holder.type = null; + private static int ReadVersion(Type type) { object instance = Activator.CreateInstance(type)!; @@ -526,6 +528,16 @@ private static void ForceCollection() } } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void NativeCallback(); + + private sealed class Retention(Action release) : IDisposable + { + private Action? m_release = release; + + public void Dispose() => Interlocked.Exchange(ref m_release, null)?.Invoke(); + } + private sealed class ReloadableTypeRegistry(TypeCatalog types) : TypeRegistry(types) { internal bool failActivation; @@ -534,21 +546,29 @@ private sealed class ReloadableTypeRegistry(TypeCatalog types) : TypeRegistry - string.Equals( - type.Resolve(types).FullName, - "Inno.Extensibility.Modules.TestModule.ReloadableExtension", - StringComparison.Ordinal)) + TypeRef[] matches = types.types + .Where(type => + string.Equals( + type.Resolve(types).FullName, + "Inno.Extensibility.Modules.TestModule.ReloadableExtension", + StringComparison.Ordinal + )) .ToArray(); if (matches.Length == 1) + { lastBuiltRef = matches[0]; + } return matches.Select(type => type.Resolve(types)).ToArray(); } - protected override void OnActivating(Type[]? previous, Type[] candidate) - { + protected override void OnActivating( + Type[]? previous, + Type[] candidate + ) { if (failActivation) + { throw new InvalidOperationException("Injected assembly registry activation failure."); + } } } @@ -565,8 +585,7 @@ private sealed class CatalogParticipantProbe : IAssemblyCatalogParticipant internal int completeCount; internal int rollbackCount; - public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) - => new Transaction(this); + public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) => new Transaction(this); internal void Reset() { @@ -581,21 +600,27 @@ private sealed class Transaction(CatalogParticipantProbe owner) : IAssemblyCatal public void Activate() { if (owner.throwOnActivate) + { throw new InvalidOperationException("Injected participant activation failure."); + } } public void Complete() { owner.completeCount++; if (owner.throwOnComplete) + { throw new InvalidOperationException("Injected participant completion failure."); + } } public void Rollback() { owner.rollbackCount++; if (owner.throwOnRollback) + { throw new InvalidOperationException("Injected participant rollback failure."); + } } } } diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs index bd16f8c69..720e16709 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs @@ -1,16 +1,14 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; using System.Runtime.Loader; - +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Modules.Tests; public sealed class ModuleRetirementTests @@ -22,13 +20,15 @@ public sealed class ModuleRetirementTests public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoModuleRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = phase; - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); AssemblyLoadContext previous = Context(reload.context.previousCatalog); AssemblyLoadContext candidate = Context(reload.context.candidateCatalog); int unloads = 0; @@ -36,14 +36,20 @@ public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string p candidate.Unloading += _ => unloads++; if (phase == "activate") + { Assert.Throws(reload.Activate); + } else { reload.Activate(); if (phase == "complete") + { Assert.Throws(() => reload.Complete()); + } else + { Assert.Throws(reload.Rollback); + } } Assert.Equal(GenerationState.Faulted, modules.generations.state); @@ -65,28 +71,43 @@ public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string p public void WrappedPendingKeepsBothCollectibleContextsAndPreservesTheOriginalFailure(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoWrappedRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = phase; - participant.failure = new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("native owner", new RetirementTimeoutException("callback still active"))); - var reload = modules.BeginReload(handle, Request("V2", cache)); + participant.failure = new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("native owner", new RetirementTimeoutException("callback still active")) + ); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; if (phase == "activate") + { Assert.Same(participant.failure, Assert.Throws(reload.Activate)); + } else { reload.Activate(); - Assert.Same(participant.failure, Assert.Throws(() => - { - if (phase == "complete") _ = reload.Complete(); - else reload.Rollback(); - })); + Assert.Same( + participant.failure, + Assert.Throws(() => + { + if (phase == "complete") + { + _ = reload.Complete(); + } + else + { + reload.Rollback(); + } + }) + ); } Assert.Equal(GenerationState.Faulted, modules.generations.state); Assert.Same(participant.failure, Assert.Throws(reload.Dispose)); @@ -103,7 +124,9 @@ public void WrappedPendingKeepsBothCollectibleContextsAndPreservesTheOriginalFai public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherContext(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoCatalogRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var ordinary = new Participant { failure = new InvalidOperationException("earlier catalog cleanup") }; @@ -112,15 +135,21 @@ public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherCon using IDisposable second = modules.RegisterCatalogParticipant(phase == "complete" ? pending : ordinary); ordinary.phase = phase; pending.phase = phase; - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; reload.Activate(); AggregateException failure = Assert.Throws(() => { - if (phase == "complete") _ = reload.Complete(); - else reload.Rollback(); + if (phase == "complete") + { + _ = reload.Complete(); + } + else + { + reload.Rollback(); + } }); Assert.Contains(ordinary.failure, failure.Flatten().InnerExceptions); Assert.Same(pending.failure, RetirementPendingException.Find(failure)); @@ -135,14 +164,16 @@ public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherCon public void RejectedCatalogActivationRemainsVisibleWhenItsRollbackIsPending() { string cache = Path.Combine(Path.GetTempPath(), "InnoRejectedRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = "rollback"; participant.activationFailure = new InvalidOperationException("catalog activation rejected"); - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; @@ -158,8 +189,7 @@ public void RejectedCatalogActivationRemainsVisibleWhenItsRollbackIsPending() private static DotNetModuleSource Request( string variant, string artifactRootDirectory - ) - { + ) { string directory = Path.Combine(AppContext.BaseDirectory, "Modules", variant); return new DotNetModuleSource { @@ -173,8 +203,9 @@ string artifactRootDirectory } private static AssemblyLoadContext Context(AssemblyCatalogSnapshot catalog) - => AssemblyLoadContext.GetLoadContext(catalog.assemblies.Single(assembly => - assembly.GetName().Name == "Inno.Extensibility.Modules.TestModule"))!; + => AssemblyLoadContext.GetLoadContext( + catalog.assemblies.Single(assembly => (assembly.GetName().Name == "Inno.Extensibility.Modules.TestModule")) + )!; private sealed class Participant : IAssemblyCatalogParticipant { @@ -197,9 +228,13 @@ private sealed class Transaction(Participant owner) : IAssemblyCatalogTransactio private void ThrowIfPending(string phase) { if (phase == "activate" && owner.activationFailure is not null) + { throw owner.activationFailure; + } if (owner.phase == phase) + { throw owner.failure; + } } } } diff --git a/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs b/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs index aeebd93f3..952177643 100644 --- a/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs +++ b/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs @@ -1,14 +1,14 @@ using System; using System.Threading; -using Inno.Extensibility.Reload; using Xunit; +using Inno.Extensibility.Reload; namespace Inno.Extensibility.Reload.Tests; public sealed class AssemblyUnloadBarrierTests { [Fact] - public void Advance_CompletesOnlyAfterEveryProbeCompletes() + public void AdvanceCompletesOnlyAfterEveryProbeCompletes() { var first = new Probe("first"); var second = new Probe("second"); @@ -18,7 +18,8 @@ public void Advance_CompletesOnlyAfterEveryProbeCompletes() { collectionInterval = TimeSpan.Zero, retentionTimeout = TimeSpan.FromSeconds(2) - }); + } + ); first.isCompleted = true; Assert.False(barrier.Advance()); @@ -30,7 +31,7 @@ public void Advance_CompletesOnlyAfterEveryProbeCompletes() } [Fact] - public void Advance_RetainsFaultAndRejectsEveryLaterSuccessAttempt() + public void AdvanceRetainsFaultAndRejectsEveryLaterSuccessAttempt() { var probe = new Probe("Plugin.Game (InnoPlugin/Runtime, generation 4)"); var barrier = new AssemblyUnloadBarrier( @@ -39,7 +40,8 @@ public void Advance_RetainsFaultAndRejectsEveryLaterSuccessAttempt() { collectionInterval = TimeSpan.Zero, retentionTimeout = TimeSpan.FromMilliseconds(20) - }); + } + ); Thread.Sleep(30); AssemblyUnloadException first = Assert.Throws(() => barrier.Advance()); diff --git a/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs b/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs index 4da0d2efa..5477b8499 100644 --- a/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs +++ b/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading; +using Xunit; using Inno.Core.Execution; using Inno.Extensibility.Reload; -using Xunit; namespace Inno.Extensibility.Reload.Tests; @@ -14,7 +14,7 @@ public void CommitDoesNotReopenAdmissionUntilAllRetirementsComplete() { var owner = new GenerationCoordinator(); var probe = new Probe(); - var events = new List(); + List events = []; owner.Execute("reload", new Publication(probe, events), [new Change("scene", events)]); Assert.Equal(["prepare:scene", "activate", "apply:scene", "commit", "complete:scene"], events); Assert.Equal(GenerationState.AwaitingCollection, owner.state); @@ -29,10 +29,12 @@ public void CommitDoesNotReopenAdmissionUntilAllRetirementsComplete() public void FailedApplyRollsBackStructureBeforePublicationAndThenRestoresValues() { var owner = new GenerationCoordinator(); - var events = new List(); - Assert.Throws(() => owner.Execute("reload", + List events = []; + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("first", events), new Change("second", events, failApply: true)])); + [new Change("first", events), new Change("second", events, failApply: true)] + )); Assert.Equal(["prepare:first", "prepare:second", "activate", "apply:first", "apply:second", "structure:second", "structure:first", "rollback", "restore:second", "restore:first"], events); Assert.Equal(GenerationState.Ready, owner.state); @@ -42,10 +44,12 @@ public void FailedApplyRollsBackStructureBeforePublicationAndThenRestoresValues( public void IrreversibleCleanupFailureFaultsOwnerAndStillAttemptsAllCleanup() { var owner = new GenerationCoordinator(); - var events = new List(); - Assert.Throws(() => owner.Execute("reload", + List events = []; + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("first", events, failComplete: true), new Change("second", events)])); + [new Change("first", events, failComplete: true), new Change("second", events)] + )); Assert.Contains("complete:second", events); Assert.DoesNotContain("rollback", events); Assert.Equal(GenerationState.Faulted, owner.state); @@ -67,10 +71,12 @@ public void BuildReadLeaseBlocksGenerationMutationUntilDisposed() public void RollbackFailureIsTerminalEvenWhenNoCollectibleMonitorExists() { var owner = new GenerationCoordinator(); - var events = new List(); - Assert.Throws(() => owner.Execute("reload", + List events = []; + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("scene", events, failApply: true, failRestore: true)])); + [new Change("scene", events, failApply: true, failRestore: true)] + )); Assert.Equal(GenerationState.Faulted, owner.state); Assert.Throws(() => owner.Advance()); } @@ -101,16 +107,26 @@ public void AutomaticRefreshDefersDuringBuildAndExcludesNewReadersWhilePublishin public void PendingRetirementNeverFallsThroughToLowerCleanupOrReopensAdmission(string phase) { var owner = new GenerationCoordinator(); - var events = new List(); + List events = []; var failure = new RetirementTimeoutException("Pending generation-owned work exceeded its deadline."); var change = new PendingChange(phase, events, failure); - Exception reported = Assert.ThrowsAny(() => owner.Execute("reload", - new Publication(new Probe { isCompleted = true }, events), [change])); + Exception reported = Assert.ThrowsAny(() => owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [change] + )); Assert.Same(failure, RetirementPendingException.Find(reported)); if (phase == "rollback") - Assert.Contains(Assert.IsType(reported).InnerExceptions, - item => item.Message == "Candidate publication failed."); - else Assert.Same(failure, reported); + { + Assert.Contains( + Assert.IsType(reported).InnerExceptions, + item => item.Message == "Candidate publication failed." + ); + } + else + { + Assert.Same(failure, reported); + } Assert.DoesNotContain("rollback", events); Assert.DoesNotContain("restore", events); Assert.Equal(GenerationState.Faulted, owner.state); @@ -140,7 +156,9 @@ public void PublicationMayBorrowAnOperationOnlyOnItsOwnControlThread() var owner = new GenerationCoordinator(); Assert.True(owner.TryAcquireChange("refresh", out IDisposable? publication)); using (owner.AcquireOperation("validate candidate")) + { Assert.Throws(() => owner.AcquireRead("Build")); + } Assert.Equal(GenerationState.Transitioning, owner.state); Exception? failure = null; var thread = new Thread(() => @@ -184,9 +202,12 @@ public void PublishedOperationDoesNotAuthorizeNewWorkWhileOldContextsAwaitCollec public void ExecuteBorrowsOperationAdmissionWithoutReopeningItBetweenDomainPhases() { var owner = new GenerationCoordinator(); - var events = new List(); - owner.Execute("reload", new Publication(new Probe { isCompleted = true }, events), - [new OperationChange(owner, events)]); + List events = []; + owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [new OperationChange(owner, events)] + ); Assert.Equal(["prepare", "activate", "apply", "commit", "complete"], events); owner.EnsureReady("Play"); owner.Fault(new InvalidOperationException("Terminal cleanup failure.")); @@ -215,19 +236,27 @@ public void EarlierOrdinaryFailureDoesNotHideThePendingDependencyBarrier() public void WrappedPendingRetainsTheTransactionWithoutContinuingDependentPhases(string phase) { var owner = new GenerationCoordinator(); - var events = new List(); + List events = []; var pending = new RetirementTimeoutException("unfinished native callback"); - var failure = new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("scope context", pending)); + var failure = new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("scope context", pending) + ); var change = new WrappedChange(phase, failure, events); - AggregateException reported = Assert.Throws(() => owner.Execute("reload", - new Publication(new Probe { isCompleted = true }, events), [change])); + AggregateException reported = Assert.Throws(() => owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [change] + )); if (phase is "rollback" or "restore") { Assert.Contains(failure, reported.InnerExceptions); Assert.Contains(reported.InnerExceptions, item => item.Message == "activation rejected"); } - else Assert.Same(failure, reported); + else + { + Assert.Same(failure, reported); + } Assert.Equal(GenerationState.Faulted, owner.state); Assert.Same(reported, owner.failure); Assert.Same(pending, Assert.Throws(owner.EnsureRetirementSafe)); @@ -239,12 +268,17 @@ public void WrappedPendingRetainsTheTransactionWithoutContinuingDependentPhases( public void CleanupFailureBeforeAPendingParticipantRemainsInTheTerminalReport() { var owner = new GenerationCoordinator(); - var events = new List(); + List events = []; var pending = new RetirementPendingException("unfinished callback"); - AggregateException failure = Assert.Throws(() => owner.Execute("reload", + AggregateException failure = Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("ordinary", events, failComplete: true), new WrappedChange("complete", pending, events), - new Change("dependency", events)])); + [ + new Change("ordinary", events, failComplete: true), + new WrappedChange("complete", pending, events), + new Change("dependency", events) + ] + )); Assert.Same(failure, owner.failure); Assert.Contains(failure.InnerExceptions, item => item.Message == "complete"); Assert.Contains(pending, failure.InnerExceptions); @@ -252,20 +286,27 @@ public void CleanupFailureBeforeAPendingParticipantRemainsInTheTerminalReport() Assert.Same(pending, Assert.Throws(owner.EnsureRetirementSafe)); } - private sealed class PendingChange(string phase, List events, RetirementTimeoutException failure) - : IGenerationChange + private sealed class PendingChange( + string phase, + List events, + RetirementTimeoutException failure + ) : IGenerationChange { public void PrepareForActivation() { events.Add("prepare"); if (phase == "prepare") + { throw failure; + } } public void Apply() { if (phase == "rollback") + { throw new InvalidOperationException("Candidate publication failed."); + } } public void Complete() => throw failure; @@ -275,17 +316,26 @@ public void Apply() public void RestorePreviousState() => events.Add("restore"); } - private sealed class WrappedChange(string phase, Exception failure, List events) : IGenerationChange + private sealed class WrappedChange( + string phase, + Exception failure, + List events + ) : IGenerationChange { public void PrepareForActivation() => Visit("prepare"); + public void Apply() { Visit("apply"); if (phase is "rollback" or "restore") throw new InvalidOperationException("activation rejected"); } + public void Complete() => Visit("complete"); + public void RollbackStructure() => Visit("rollback"); + public void RestorePreviousState() => Visit("restore"); + private void Visit(string current) { events.Add(current); @@ -299,12 +349,19 @@ private sealed class Probe : IAssemblyUnloadProbe public bool isCompleted { get; set; } } - private sealed class OperationChange(GenerationCoordinator owner, List events) : IGenerationChange + private sealed class OperationChange( + GenerationCoordinator owner, + List events + ) : IGenerationChange { public void PrepareForActivation() => Visit("prepare"); + public void Apply() => Visit("apply"); + public void Complete() => Visit("complete"); + public void RollbackStructure() => Visit("rollback"); + public void RestorePreviousState() => Visit("restore"); private void Visit(string phase) @@ -316,20 +373,50 @@ private void Visit(string phase) } } - private sealed class Publication(Probe probe, List events) : IGenerationPublication + private sealed class Publication( + Probe probe, + List events + ) : IGenerationPublication { public void Activate() => events.Add("activate"); + public void Rollback() => events.Add("rollback"); - public Probe Complete() { events.Add("commit"); return probe; } + + public Probe Complete() + { + events.Add("commit"); + return probe; + } } - private sealed class Change(string name, List events, - bool failApply = false, bool failComplete = false, bool failRestore = false) : IGenerationChange + private sealed class Change( + string name, + List events, + bool failApply = false, + bool failComplete = false, + bool failRestore = false + ) : IGenerationChange { public void PrepareForActivation() => events.Add($"prepare:{name}"); - public void Apply() { events.Add($"apply:{name}"); if (failApply) throw new InvalidOperationException("apply"); } - public void Complete() { events.Add($"complete:{name}"); if (failComplete) throw new InvalidOperationException("complete"); } + + public void Apply() + { + events.Add($"apply:{name}"); + if (failApply) throw new InvalidOperationException("apply"); + } + + public void Complete() + { + events.Add($"complete:{name}"); + if (failComplete) throw new InvalidOperationException("complete"); + } + public void RollbackStructure() => events.Add($"structure:{name}"); - public void RestorePreviousState() { events.Add($"restore:{name}"); if (failRestore) throw new InvalidOperationException("restore"); } + + public void RestorePreviousState() + { + events.Add($"restore:{name}"); + if (failRestore) throw new InvalidOperationException("restore"); + } } } diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs new file mode 100644 index 000000000..bac6ace83 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[TestMarker] +public abstract class AbstractAttributedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs index ea262d678..818101692 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs @@ -1,12 +1,10 @@ using System; using System.Reflection; using System.Reflection.Emit; - +using Xunit; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Types.Tests; public sealed class AssemblyExtensionsTests @@ -14,7 +12,7 @@ public sealed class AssemblyExtensionsTests [Fact] public void AssemblyClassificationReadsBothMetadataDimensions() { - var asm = BuildDynamicAssembly("InnoPlugin", "Editor"); + Assembly asm = BuildDynamicAssembly("InnoPlugin", "Editor"); Assert.Equal(AssemblyDomain.InnoPlugin, asm.GetInnoAssemblyDomain()); Assert.Equal(AssemblyScope.Editor, asm.GetInnoAssemblyScope()); } @@ -22,29 +20,27 @@ public void AssemblyClassificationReadsBothMetadataDimensions() [Fact] public void MissingClassificationIsRejected() { - var asm = BuildDynamicAssembly(null, null); + Assembly asm = BuildDynamicAssembly(null, null); Assert.Throws(() => asm.GetInnoAssemblyDomain()); Assert.Throws(() => asm.GetInnoAssemblyScope()); } - private static Assembly BuildDynamicAssembly(string? domainName, string? scopeName) - { + private static Assembly BuildDynamicAssembly( + string? domainName, + string? scopeName + ) { var asmName = new AssemblyName("Inno.Dynamic." + Guid.NewGuid().ToString("N")); - var asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); + AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); if (domainName is not null && scopeName is not null) { - var ctor = typeof(AssemblyMetadataAttribute).GetConstructor(new[] { typeof(string), typeof(string) })!; - asmBuilder.SetCustomAttribute(new CustomAttributeBuilder( - ctor, - new object[] { "Inno.AssemblyDomain", domainName })); - asmBuilder.SetCustomAttribute(new CustomAttributeBuilder( - ctor, - new object[] { "Inno.AssemblyScope", scopeName })); + ConstructorInfo ctor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; + asmBuilder.SetCustomAttribute(new CustomAttributeBuilder(ctor, ["Inno.AssemblyDomain", domainName])); + asmBuilder.SetCustomAttribute(new CustomAttributeBuilder(ctor, ["Inno.AssemblyScope", scopeName])); } - var module = asmBuilder.DefineDynamicModule("main"); - var type = module.DefineType("Inno.Dynamic.Placeholder", TypeAttributes.Public | TypeAttributes.Class); + ModuleBuilder module = asmBuilder.DefineDynamicModule("main"); + TypeBuilder type = module.DefineType("Inno.Dynamic.Placeholder", TypeAttributes.Public | TypeAttributes.Class); _ = type.CreateType(); return asmBuilder; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs index 90530011e..b40fa5b7b 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs @@ -2,8 +2,10 @@ [assembly: AssemblyMetadata( "Inno.StableTypeId", - "44444444-4444-4444-4444-444444444444|Inno.Extensibility.Types.Tests.GeneratedMappedType")] + "44444444-4444-4444-4444-444444444444|Inno.Extensibility.Types.Tests.GeneratedMappedType" +)] [assembly: AssemblyMetadata( "Inno.StableTypeId", - "66666666-6666-6666-6666-666666666666|Inno.Extensibility.Types.Tests.StableAnnotatedTypeA")] + "66666666-6666-6666-6666-666666666666|Inno.Extensibility.Types.Tests.StableAnnotatedTypeA" +)] diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs new file mode 100644 index 000000000..58a139e82 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[TestMarker] +public sealed class AttributedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs new file mode 100644 index 000000000..d568044b6 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class DeterministicStableType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs new file mode 100644 index 000000000..a22e04d59 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class GeneratedMappedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs new file mode 100644 index 000000000..0ab726418 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public interface ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs index 4f162a1e2..9c0ec6716 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs @@ -1,8 +1,3 @@ -using Inno.Extensibility.Types; - namespace ExternalNamespace; public sealed class OutsideNamespaceType; - -[StableTypeId("33333333-3333-3333-3333-333333333333")] -public sealed class OutsideStableAnnotatedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs new file mode 100644 index 000000000..0b6f8d19d --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace ExternalNamespace; + +[StableTypeID("33333333-3333-3333-3333-333333333333")] +public sealed class OutsideStableAnnotatedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs index 4cf4a7427..68d2280a7 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs @@ -1,34 +1,36 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; - +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Types.Tests; -[Collection(TypeCacheCollection.NAME)] +[Collection(TypeCacheCollection.C_NAME)] public sealed class RegistryRetirementTests { [Fact] public void PendingBatchDoesNotRepeatCompletedResourcesOrReleaseLowerDependenciesEarly() { string cache = Path.Combine(Path.GetTempPath(), "InnoRegistryRetirement", Guid.NewGuid().ToString("N")); - using var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - var calls = new List(); + List calls = []; int pendingAttempts = 0; var first = new Resource(() => calls.Add("first")); var second = new Resource(() => { calls.Add("second"); if (++pendingAttempts < 3) + { throw new RetirementPendingException("Pending registry resource."); + } }); var third = new Resource(() => { @@ -52,7 +54,9 @@ public void PendingBatchDoesNotRepeatCompletedResourcesOrReleaseLowerDependencie public void DeadlineFailureRetainsDependenciesAndPermanentlyRejectsFurtherRetirement(bool clear) { string cache = Path.Combine(Path.GetTempPath(), "InnoRegistryRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); int released = 0; int attempts = 0; @@ -81,8 +85,11 @@ public void DeadlineFailureRetainsDependenciesAndPermanentlyRejectsFurtherRetire Assert.Throws(modules.Dispose); } - private sealed class Registry(TypeCatalog types, Func factory, TimeSpan? timeout = null) - : TypeRegistry(types, timeout) + private sealed class Registry( + TypeCatalog types, + Func factory, + TimeSpan? timeout = null + ) : TypeRegistry(types, timeout) { protected override object[] Build(TypeCacheSnapshot types) => factory(); diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs new file mode 100644 index 000000000..454f181d8 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[StableTypeID("11111111-1111-1111-1111-111111111111")] +public sealed class StableAnnotatedTypeA; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs new file mode 100644 index 000000000..747a3435d --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[StableTypeID("22222222-2222-2222-2222-222222222222")] +public readonly struct StableAnnotatedTypeB; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs new file mode 100644 index 000000000..c042d0c37 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public abstract class TestAbstractContractImpl : ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs new file mode 100644 index 000000000..65d598990 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public abstract class TestAbstractDerived : TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs new file mode 100644 index 000000000..c4a2acc85 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +// Open: TestDerived and TestAbstractDerived derive from it for the subtype queries. +public class TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs new file mode 100644 index 000000000..dce36e796 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class TestContractImpl : ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs new file mode 100644 index 000000000..6304a17b6 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class TestDerived : TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs new file mode 100644 index 000000000..20e2c5b04 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs @@ -0,0 +1,6 @@ +using System; + +namespace Inno.Extensibility.Types.Tests; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class TestMarkerAttribute : Attribute; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheCollection.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheCollection.cs index fefc924b3..b0aef51a2 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheCollection.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheCollection.cs @@ -2,8 +2,8 @@ namespace Inno.Extensibility.Types.Tests; -[CollectionDefinition(NAME, DisableParallelization = true)] +[CollectionDefinition(C_NAME, DisableParallelization = true)] public sealed class TypeCacheCollection { - public const string NAME = "TypeCacheCollection"; + public const string C_NAME = "TypeCacheCollection"; } diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs index 0f7e4abb1..d3120acef 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs @@ -1,31 +1,32 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Reflection; - using ExternalNamespace; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; -using Inno.Extensibility.Types; - -using Xunit; namespace Inno.Extensibility.Types.Tests; -[Collection(TypeCacheCollection.NAME)] +[Collection(TypeCacheCollection.C_NAME)] public sealed class TypeCacheTests : IDisposable { private readonly string m_cacheDirectory = Path.Combine( Path.GetTempPath(), "InnoTypeCacheTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; public TypeCacheTests() { - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(TypeCacheTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(TypeCacheTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); } @@ -34,7 +35,9 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } [Fact] @@ -61,35 +64,9 @@ public void CandidateRollbackCleanupFailureFaultsGateAfterEveryResourceIsAttempt Assert.Equal(new[] { 4, 3 }, registry.released); Assert.Equal(GenerationState.Faulted, m_modules.generations.state); } - finally { registry.failCleanup = false; } - } - - private sealed class CandidateOwnershipRegistry(TypeCatalog types) : TypeRegistry(types) - { - private int m_nextId; - internal bool failBuild; - internal bool failCleanup; - internal List released { get; } = []; - - protected override object[] Build(TypeCacheSnapshot types) - { - var first = OwnCandidateExtension(new Resource(this, ++m_nextId)); - var second = OwnCandidateExtension(new Resource(this, ++m_nextId)); - if (failBuild) - throw new InvalidOperationException("Expected candidate validation failure."); - return [first, second, first]; - } - - protected override void DisposeSnapshot(object[] snapshot) => DisposeExtensions(snapshot); - - private sealed class Resource(CandidateOwnershipRegistry owner, int id) : IDisposable + finally { - public void Dispose() - { - owner.released.Add(id); - if (owner.failCleanup) - throw new InvalidOperationException("Expected extension cleanup failure."); - } + registry.failCleanup = false; } } @@ -97,21 +74,20 @@ public void Dispose() public void QueriesReturnOnlyConcreteMatchingTypes() { Assert.Contains(m_types.GetTypeRef(typeof(TestDerived)), m_types.GetSubTypesOf()); - Assert.DoesNotContain( - m_types.GetTypeRef(typeof(TestAbstractDerived)), - m_types.GetSubTypesOf()); - Assert.Contains( - m_types.GetTypeRef(typeof(TestContractImpl)), - m_types.GetTypesImplementing()); + Assert.DoesNotContain(m_types.GetTypeRef(typeof(TestAbstractDerived)), m_types.GetSubTypesOf()); + Assert.Contains(m_types.GetTypeRef(typeof(TestContractImpl)), m_types.GetTypesImplementing()); Assert.DoesNotContain( m_types.GetTypeRef(typeof(TestAbstractContractImpl)), - m_types.GetTypesImplementing()); + m_types.GetTypesImplementing() + ); Assert.Contains( m_types.GetTypeRef(typeof(AttributedType)), - m_types.GetTypesWithAttribute()); + m_types.GetTypesWithAttribute() + ); Assert.DoesNotContain( m_types.GetTypeRef(typeof(AbstractAttributedType)), - m_types.GetTypesWithAttribute()); + m_types.GetTypesWithAttribute() + ); } [Fact] @@ -124,8 +100,8 @@ public void StableAndRuntimeIdentitySurviveOrdinaryRebuild() TypeRef second = m_types.GetTypeRef(typeof(TestDerived)); Assert.Equal(typeof(TestDerived), first.Resolve(m_types)); - Assert.Equal(first.stableId, second.stableId); - Assert.Equal(first.runtimeId, second.runtimeId); + Assert.Equal(first.stableID, second.stableID); + Assert.Equal(first.runtimeID, second.runtimeID); Assert.True(m_types.current.version > previous.version); } @@ -134,23 +110,26 @@ public void ExplicitAndGeneratedStableIdentitiesAreCanonical() { Assert.Equal( Guid.Parse("11111111-1111-1111-1111-111111111111"), - m_types.GetTypeRef(typeof(StableAnnotatedTypeA)).stableId); + m_types.GetTypeRef(typeof(StableAnnotatedTypeA)).stableID + ); Assert.Equal( Guid.Parse("44444444-4444-4444-4444-444444444444"), - m_types.GetTypeRef(typeof(GeneratedMappedType)).stableId); + m_types.GetTypeRef(typeof(GeneratedMappedType)).stableID + ); - Guid first = m_types.GetTypeRef(typeof(DeterministicStableType)).stableId; + Guid first = m_types.GetTypeRef(typeof(DeterministicStableType)).stableID; m_types.Rebuild(); - Assert.Equal(first, m_types.GetTypeRef(typeof(DeterministicStableType)).stableId); + Assert.Equal(first, m_types.GetTypeRef(typeof(DeterministicStableType)).stableID); } [Fact] public void DiscoveryIncludesTypesOutsideInnoNamespace() { - Assert.True(m_types.GetTypeRef(typeof(OutsideNamespaceType)).runtimeId > 0); + Assert.True(m_types.GetTypeRef(typeof(OutsideNamespaceType)).runtimeID > 0); Assert.Equal( Guid.Parse("33333333-3333-3333-3333-333333333333"), - m_types.GetTypeRef(typeof(OutsideStableAnnotatedType)).stableId); + m_types.GetTypeRef(typeof(OutsideStableAnnotatedType)).stableID + ); } [Fact] @@ -159,7 +138,8 @@ public void NewlyLoadedHostAssemblyAppearsAfterCatalogRefresh() Assembly assembly = Assembly.Load("Inno.Extensibility.Types.TestAssemblyA"); Type marked = assembly.GetType( "Inno.Extensibility.Types.TestAssets.A.AssemblyAMarkedType", - throwOnError: true)!; + throwOnError: true + )!; m_types.Rebuild(); @@ -170,7 +150,7 @@ public void NewlyLoadedHostAssemblyAppearsAfterCatalogRefresh() public void UnknownAndEmptyReferencesFailAgainstExplicitCatalog() { TypeRef empty = default; - TypeRef unknown = new(Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")); + var unknown = new TypeRef(Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")); Assert.False(empty.IsValid(m_types)); Assert.False(unknown.IsValid(m_types)); @@ -186,18 +166,18 @@ public void CandidateActivationFailureRestoresEveryRegistrySnapshot() using var second = new TransactionalTestRegistry(m_types); first.Refresh(); second.Refresh(); - int firstPrevious = first.snapshotId; - int secondPrevious = second.snapshotId; + int firstPrevious = first.snapshotID; + int secondPrevious = second.snapshotID; second.failActivation = true; Assert.Throws(m_types.Rebuild); - Assert.Equal(firstPrevious, first.snapshotId); - Assert.Equal(secondPrevious, second.snapshotId); + Assert.Equal(firstPrevious, first.snapshotID); + Assert.Equal(secondPrevious, second.snapshotID); Assert.Equal(1, first.rollbackCount); Assert.Equal(1, second.rollbackCount); - Assert.Contains(firstPrevious + 1, first.disposedSnapshotIds); - Assert.Contains(secondPrevious + 1, second.disposedSnapshotIds); + Assert.Contains(firstPrevious + 1, first.disposedSnapshotIDs); + Assert.Contains(secondPrevious + 1, second.disposedSnapshotIDs); } [Fact] @@ -205,15 +185,15 @@ public void SnapshotCleanupFailureKeepsCommittedCandidateButFaultsGeneration() { using var registry = new TransactionalTestRegistry(m_types); registry.Refresh(); - int previous = registry.snapshotId; + int previous = registry.snapshotID; registry.failSnapshotCleanup = true; Assert.Throws(m_types.Rebuild); - Assert.Equal(previous + 1, registry.snapshotId); + Assert.Equal(previous + 1, registry.snapshotID); Assert.Equal(0, registry.rollbackCount); Assert.Equal(1, registry.cleanupFailureCount); - Assert.Contains(previous, registry.disposedSnapshotIds); + Assert.Contains(previous, registry.disposedSnapshotIDs); Assert.Equal(GenerationState.Faulted, m_modules.generations.state); Assert.Throws(() => m_modules.generations.AcquireRead("build")); registry.failSnapshotCleanup = false; @@ -226,15 +206,15 @@ public void RegistryRetiredAfterCandidatePreparationIsExcludedFromActivation() using var survivor = new TransactionalTestRegistry(m_types); retiring.Refresh(); survivor.Refresh(); - int retiringPrevious = retiring.snapshotId; - int survivorPrevious = survivor.snapshotId; + int retiringPrevious = retiring.snapshotID; + int survivorPrevious = survivor.snapshotID; retiring.disposeOnActivation = survivor; m_types.Rebuild(); - Assert.Equal(retiringPrevious + 1, retiring.snapshotId); - Assert.Contains(survivorPrevious, survivor.disposedSnapshotIds); - Assert.Contains(survivorPrevious + 1, survivor.disposedSnapshotIds); + Assert.Equal(retiringPrevious + 1, retiring.snapshotID); + Assert.Contains(survivorPrevious, survivor.disposedSnapshotIDs); + Assert.Contains(survivorPrevious + 1, survivor.disposedSnapshotIDs); } [Fact] @@ -246,72 +226,91 @@ public void DisposedCatalogRejectsQueriesWithoutAStaticFallback() Assert.Throws(() => m_types.GetSubTypesOf()); } - private sealed class TransactionalTestRegistry(TypeCatalog types) - : TypeRegistry(types) + private sealed class CandidateOwnershipRegistry(TypeCatalog types) : TypeRegistry(types) { - private int m_nextSnapshotId; + private int m_nextID; + internal bool failBuild; + internal bool failCleanup; + internal List released { get; } = []; + + protected override object[] Build(TypeCacheSnapshot types) + { + Resource first = OwnCandidateExtension(new Resource(this, ++m_nextID)); + Resource second = OwnCandidateExtension(new Resource(this, ++m_nextID)); + if (failBuild) + { + throw new InvalidOperationException("Expected candidate validation failure."); + } + return [first, second, first]; + } + + protected override void DisposeSnapshot(object[] snapshot) => DisposeExtensions(snapshot); + + private sealed class Resource( + CandidateOwnershipRegistry owner, + int id + ) : IDisposable + { + public void Dispose() + { + owner.released.Add(id); + if (owner.failCleanup) + { + throw new InvalidOperationException("Expected extension cleanup failure."); + } + } + } + } + + private sealed class TransactionalTestRegistry(TypeCatalog types) : TypeRegistry(types) + { + private int m_nextSnapshotID; internal bool failActivation; internal bool failSnapshotCleanup; internal IDisposable? disposeOnActivation; internal int rollbackCount; internal int cleanupFailureCount; - internal int snapshotId; - internal List disposedSnapshotIds { get; } = []; + internal int snapshotID; + internal List disposedSnapshotIDs { get; } = []; - protected override Snapshot Build(TypeCacheSnapshot types) => new(++m_nextSnapshotId); + protected override Snapshot Build(TypeCacheSnapshot types) => new(++m_nextSnapshotID); - protected override void OnActivating(Snapshot? previous, Snapshot candidate) - { - snapshotId = candidate.id; + protected override void OnActivating( + Snapshot? previous, + Snapshot candidate + ) { + snapshotID = candidate.id; disposeOnActivation?.Dispose(); disposeOnActivation = null; if (failActivation) + { throw new InvalidOperationException("Injected registry activation failure."); + } } - protected override void OnActivationRolledBack(Snapshot? previous, Snapshot candidate) - { - snapshotId = previous?.id ?? 0; + protected override void OnActivationRolledBack( + Snapshot? previous, + Snapshot candidate + ) { + snapshotID = previous?.id ?? 0; rollbackCount++; } protected override void DisposeSnapshot(Snapshot snapshot) { - disposedSnapshotIds.Add(snapshot.id); + disposedSnapshotIDs.Add(snapshot.id); if (failSnapshotCleanup) + { throw new InvalidOperationException("Injected snapshot cleanup failure."); + } } - protected override void OnCleanupFailed(string phase, Exception exception) - => cleanupFailureCount++; + protected override void OnCleanupFailed( + string phase, + Exception exception + ) => cleanupFailureCount++; internal sealed record Snapshot(int id); } } - -public class TestBase; -public sealed class TestDerived : TestBase; -public abstract class TestAbstractDerived : TestBase; - -public interface ITestContract; -public sealed class TestContractImpl : ITestContract; -public abstract class TestAbstractContractImpl : ITestContract; - -[AttributeUsage(AttributeTargets.Class)] -public sealed class TestMarkerAttribute : Attribute; - -[TestMarker] -public sealed class AttributedType; - -[TestMarker] -public abstract class AbstractAttributedType; - -[StableTypeId("11111111-1111-1111-1111-111111111111")] -public sealed class StableAnnotatedTypeA; - -[StableTypeId("22222222-2222-2222-2222-222222222222")] -public struct StableAnnotatedTypeB; - -public sealed class DeterministicStableType; -public sealed class GeneratedMappedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs deleted file mode 100644 index 978717c48..000000000 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Inno.Extensibility.Types; - -namespace Inno.Extensibility.Modules.TestModule; - -/// -/// Declares the first half of an intentional stable-type-identity collision in a rejected candidate module. -/// -[StableTypeId("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] -public sealed class FirstConflictingExtension; - -/// -/// Repeats the first declaration's identity so candidate admission must preserve the previous valid generation. -/// -[StableTypeId("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] -public sealed class SecondConflictingExtension; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs new file mode 100644 index 000000000..03ea205ca --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs @@ -0,0 +1,9 @@ +using Inno.Extensibility.Types; + +namespace Inno.Extensibility.Modules.TestModule; + +/// +/// Declares the first half of an intentional stable-type-identity collision in a rejected candidate module. +/// +[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] +public sealed class FirstConflictingExtension; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs new file mode 100644 index 000000000..ba8fc0fed --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs @@ -0,0 +1,9 @@ +using Inno.Extensibility.Types; + +namespace Inno.Extensibility.Modules.TestModule; + +/// +/// Repeats the first declaration's identity so candidate admission must preserve the previous valid generation. +/// +[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] +public sealed class SecondConflictingExtension; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs index 991d65ac4..349ab1a27 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs @@ -1,12 +1,12 @@ -using Inno.Extensibility.Types; using Reloadable.PrivateDependency; +using Inno.Extensibility.Types; namespace Inno.Extensibility.Modules.TestModule; /// /// Supplies the first collectible implementation of the stable identity shared with the second fixture generation. /// -[StableTypeId("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] +[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] public sealed class ReloadableExtension { /// diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs index f10bc8123..e09f0aa9f 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs @@ -1,12 +1,12 @@ -using Inno.Extensibility.Types; using Reloadable.PrivateDependency; +using Inno.Extensibility.Types; namespace Inno.Extensibility.Modules.TestModule; /// /// Supplies a replacement collectible implementation while retaining the first fixture generation's stable identity. /// -[StableTypeId("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] +[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] public sealed class ReloadableExtension { /// diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs new file mode 100644 index 000000000..0704324b5 --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs @@ -0,0 +1,7 @@ +namespace Inno.Extensibility.Types.TestAssets.A; + +/// +/// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. +/// +[AssemblyAMarker] +public sealed class AssemblyAMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs new file mode 100644 index 000000000..abb010d51 --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace Inno.Extensibility.Types.TestAssets.A; + +/// +/// Marks declarations from fixture assembly A for source-scoped discovery tests. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class AssemblyAMarkerAttribute : Attribute; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs deleted file mode 100644 index b60f4e75c..000000000 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Inno.Extensibility.Types.TestAssets.A -{ - /// - /// Marks declarations from fixture assembly A for source-scoped discovery tests. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class AssemblyAMarkerAttribute : Attribute; - - /// - /// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. - /// - [AssemblyAMarker] - public sealed class AssemblyAMarkedType; -} diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs new file mode 100644 index 000000000..a65d3fd49 --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs @@ -0,0 +1,7 @@ +namespace Inno.Extensibility.Types.TestAssets.B; + +/// +/// Provides a distinct marked declaration for combined-source discovery and source-removal tests. +/// +[AssemblyBMarker] +public sealed class AssemblyBMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs new file mode 100644 index 000000000..c0cb4f16b --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace Inno.Extensibility.Types.TestAssets.B; + +/// +/// Marks declarations from fixture assembly B independently of fixture assembly A. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class AssemblyBMarkerAttribute : Attribute; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs deleted file mode 100644 index ac429e4ce..000000000 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Inno.Extensibility.Types.TestAssets.B -{ - /// - /// Marks declarations from fixture assembly B independently of fixture assembly A. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class AssemblyBMarkerAttribute : Attribute; - - /// - /// Provides a distinct marked declaration for combined-source discovery and source-removal tests. - /// - [AssemblyBMarker] - public sealed class AssemblyBMarkedType; -} diff --git a/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs b/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs index 3d9536665..a2e5adb11 100644 --- a/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs +++ b/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs @@ -1,6 +1,6 @@ using System; -namespace EditorUiAcceptance; +namespace EditorUIAcceptance; internal readonly record struct ManagedMemorySample( long liveBytes, @@ -19,13 +19,22 @@ internal static ManagedMemorySample Capture() GC.WaitForPendingFinalizers(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GCMemoryInfo memory = GC.GetGCMemoryInfo(GCKind.FullBlocking); - if (memory.Index <= previousIndex || memory.Generation != GC.MaxGeneration || memory.Concurrent || !memory.Compacted || - memory.FragmentedBytes < 0 || memory.HeapSizeBytes < memory.FragmentedBytes) + if (memory.Index <= previousIndex || memory.Generation != GC.MaxGeneration || memory.Concurrent || !memory.Compacted + || memory.FragmentedBytes < 0 || memory.HeapSizeBytes < memory.FragmentedBytes + ) { throw new InvalidOperationException("The lifecycle sample requires a fresh compacting full-GC snapshot."); + } // Keep the approximate API as diagnostic data; pinned fragmentation can make it negative. return new ManagedMemorySample( - checked(memory.HeapSizeBytes - memory.FragmentedBytes), GC.GetTotalMemory(forceFullCollection: false), - memory.HeapSizeBytes, memory.FragmentedBytes, memory.Index, memory.Generation, memory.Compacted, memory.Concurrent); + checked(memory.HeapSizeBytes - memory.FragmentedBytes), + GC.GetTotalMemory(forceFullCollection: false), + memory.HeapSizeBytes, + memory.FragmentedBytes, + memory.Index, + memory.Generation, + memory.Compacted, + memory.Concurrent + ); } } diff --git a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs index 432a8e41d..7838fa04a 100644 --- a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs +++ b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs @@ -7,7 +7,7 @@ using InnoEditor.Interactions; using InnoEditor.Scene; -namespace EditorUiAcceptance; +namespace EditorUIAcceptance; /// /// Exercises the normal product panel protocol from an ordinary source Editor extension. @@ -24,11 +24,12 @@ public sealed class PanelLifecycle( IEditorSceneWorkspace workspace ) : EditorModule { - private const string C_RESOURCE_COLUMNS = - "managed-bytes-after-full-gc\tprivate-bytes\tselection-count\tscene-count\thistory-resident-bytes\thistory-disk-bytes\tpending-events" + - "\tgc-index\tgc-generation\tgc-compacted\tgc-concurrent\tgc-heap-bytes\tgc-fragmented-bytes\testimated-managed-bytes"; + private const string C_RESOURCE_COLUMNS = "managed-bytes-after-full-gc\tprivate-bytes\tselection-count\tscene-count\thistory-resident-bytes\thistory-disk-bytes\tpending-events" + + "\tgc-index\tgc-generation\tgc-compacted\tgc-concurrent\tgc-heap-bytes\tgc-fragmented-bytes\testimated-managed-bytes"; + private readonly List m_resources = ["completed-cycles\t" + C_RESOURCE_COLUMNS]; private readonly List m_preparationResources = ["phase\t" + C_RESOURCE_COLUMNS]; + private readonly int m_requiredCycles = ReadRequiredCycles(); private string[] m_panels = []; private bool[] m_originalOpenStates = []; private string? m_undoName; @@ -41,15 +42,16 @@ IEditorSceneWorkspace workspace private int m_preparationFrames; private int m_frame; private int m_cycles; - private readonly int m_requiredCycles = ReadRequiredCycles(); private bool m_baselineCaptured; private bool m_completed; - /// + /// protected override void OnUpdate(EditorContext context) { if (m_completed) + { return; + } if (m_panels.Length == 0 && m_warmup++ < 20) { return; @@ -57,17 +59,23 @@ protected override void OnUpdate(EditorContext context) if (m_panels.Length == 0) { if (workspace.scenes.Count == 0) + { workspace.Open("FlappyBird/FlappyBird.iscene"); + } m_panels = interactions.GetPanelDeclarations().Select(static panel => panel.id).Order(StringComparer.Ordinal).ToArray(); if (m_panels.Length < 8) + { throw new InvalidOperationException("The complete Editor product must expose its eight standard panels."); + } m_originalOpenStates = new bool[m_panels.Length]; m_preparationResources.Add(CaptureResourceRow("before-first-panel-draw")); for (int index = 0; index < m_panels.Length; index++) { string panel = m_panels[index]; if (!interactions.TryGetPanelState(panel, out m_originalOpenStates[index]) || !interactions.OpenPanel(panel)) + { throw new InvalidOperationException("The product could not open panel '" + panel + "' for preparation."); + } } m_preparationFrames = 120; return; @@ -75,10 +83,16 @@ protected override void OnUpdate(EditorContext context) if (m_preparationFrames > 0) { if (--m_preparationFrames > 0) + { return; + } foreach (string panel in m_panels) + { if (!interactions.ClosePanel(panel)) + { throw new InvalidOperationException("The product could not close panel '" + panel + "' after preparation."); + } + } m_preparationResources.Add(CaptureResourceRow("after-120-drawn-frames")); return; } @@ -86,29 +100,45 @@ protected override void OnUpdate(EditorContext context) foreach (string panel in m_panels) { if (!interactions.TryGetPanelState(panel, out bool isOpen) || isOpen != expectedOpen) + { throw new InvalidOperationException("Panel state or native drawing failed for '" + panel + "' at cycle " + m_cycles + "."); + } } if (expectedOpen) + { m_cycles++; + } else { VerifyDocumentState(); if (m_cycles % 10 == 0) + { CaptureResources(); + } } if (m_cycles == m_requiredCycles && !expectedOpen) { for (int index = 0; index < m_panels.Length; index++) { - bool restored = m_originalOpenStates[index] ? interactions.OpenPanel(m_panels[index]) : interactions.ClosePanel(m_panels[index]); + bool restored = m_originalOpenStates[index] + ? interactions.OpenPanel(m_panels[index]) + : interactions.ClosePanel(m_panels[index]); if (!restored) + { throw new InvalidOperationException("The product could not restore panel '" + m_panels[index] + "'."); + } } string directory = Path.Combine(context.projectDirectory, "Library", "Acceptance"); Directory.CreateDirectory(directory); - File.WriteAllLines(Path.Combine(directory, "panel-lifecycle.tsv"), + File.WriteAllLines( + Path.Combine(directory, "panel-lifecycle.tsv"), new[] { "panel\tcompleted-open-close-cycles", "protocol\tpublic EditorInteractions / actual product drawing" } - .Concat(m_panels.Select(panel => panel + "\t" + m_requiredCycles.ToString(System.Globalization.CultureInfo.InvariantCulture)))); + .Concat( + m_panels.Select( + panel => panel + "\t" + m_requiredCycles.ToString(System.Globalization.CultureInfo.InvariantCulture) + ) + ) + ); File.WriteAllLines(Path.Combine(directory, "panel-lifecycle-resources.tsv"), m_resources); File.WriteAllLines(Path.Combine(directory, "panel-lifecycle-preparation.tsv"), m_preparationResources); string completion = Path.Combine(directory, "journey-completed.txt"); @@ -121,7 +151,9 @@ protected override void OnUpdate(EditorContext context) { bool changed = expectedOpen ? interactions.ClosePanel(panel) : interactions.OpenPanel(panel); if (!changed) + { throw new InvalidOperationException("The panel protocol rejected '" + panel + "'."); + } } } @@ -138,29 +170,40 @@ private void VerifyDocumentState() m_sceneCount = workspace.scenes.Count; m_baselineCaptured = true; } - if (history.isFaulted || history.undoName != m_undoName || history.redoName != m_redoName || - history.residentBytes != m_historyResidentBytes || history.diskBytes != m_historyDiskBytes || - interactions.selection.count != m_selectionCount || workspace.scenes.Count != m_sceneCount) - throw new InvalidOperationException("Window-only lifecycle operations changed Edit selection, scenes or committed History state."); + if (history.isFaulted || history.undoName != m_undoName || history.redoName != m_redoName + || history.residentBytes != m_historyResidentBytes || history.diskBytes != m_historyDiskBytes + || interactions.selection.count != m_selectionCount || workspace.scenes.Count != m_sceneCount + ) { + throw new InvalidOperationException( + "Window-only lifecycle operations changed Edit selection, scenes or committed History state." + ); + } } private void CaptureResources() => m_resources.Add(CaptureResourceRow(m_cycles.ToString(System.Globalization.CultureInfo.InvariantCulture))); + private string CaptureResourceRow(string observation) + { + ManagedMemorySample memory = ManagedMemorySample.Capture(); + using Process process = Process.GetCurrentProcess(); + string state = FormattableString.Invariant( + $"{observation}\t{memory.liveBytes}\t{process.PrivateMemorySize64}\t{interactions.selection.count}\t{workspace.scenes.Count}\t{interactions.history.residentBytes}\t{interactions.history.diskBytes}\t{interactions.events.pendingCount}" + ); + return state + + FormattableString.Invariant( + $"\t{memory.collectionIndex}\t{memory.generation}\t{memory.compacted}\t{memory.concurrent}\t{memory.heapBytes}\t{memory.fragmentedBytes}\t{memory.estimatedBytes}" + ); + } + private static int ReadRequiredCycles() { string value = Environment.GetEnvironmentVariable("INNO_ACCEPTANCE_PANEL_CYCLES") ?? "100"; if (!int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int cycles) - || cycles < 100 || cycles > 10000 || cycles % 10 != 0) + || cycles < 100 || cycles > 10_000 || cycles % 10 != 0 + ) { throw new InvalidOperationException("The lifecycle acceptance requires 100–10000 cycles in ten-cycle intervals."); + } return cycles; } - - private string CaptureResourceRow(string observation) - { - ManagedMemorySample memory = ManagedMemorySample.Capture(); - using Process process = Process.GetCurrentProcess(); - string state = FormattableString.Invariant($"{observation}\t{memory.liveBytes}\t{process.PrivateMemorySize64}\t{interactions.selection.count}\t{workspace.scenes.Count}\t{interactions.history.residentBytes}\t{interactions.history.diskBytes}\t{interactions.events.pendingCount}"); - return state + FormattableString.Invariant($"\t{memory.collectionIndex}\t{memory.generation}\t{memory.compacted}\t{memory.concurrent}\t{memory.heapBytes}\t{memory.fragmentedBytes}\t{memory.estimatedBytes}"); - } } diff --git a/tests/fixtures/editor-ui/WorkflowJourney.editor.cs.txt b/tests/fixtures/editor-ui/WorkflowJourney.editor.cs.txt index 0e730c1e5..55c5c07f9 100644 --- a/tests/fixtures/editor-ui/WorkflowJourney.editor.cs.txt +++ b/tests/fixtures/editor-ui/WorkflowJourney.editor.cs.txt @@ -19,11 +19,11 @@ public sealed class WorkflowJourney( ) : EditorModule { private readonly List m_verified = []; - private Guid m_sceneId; - private Guid m_firstId; - private Guid m_secondId; - private Guid m_componentId; - private Guid m_duplicateId; + private Guid m_sceneID; + private Guid m_firstID; + private Guid m_secondID; + private Guid m_componentID; + private Guid m_duplicateID; private string m_scenePath = string.Empty; private int m_step; private int m_playFrames; @@ -71,11 +71,11 @@ public sealed class WorkflowJourney( edits.RenameGameObject(second, "Workflow Second"); first.transform.localPosition = new Vector3(0, 2, 3); second.transform.localPosition = new Vector3(0, 5, 6); - m_sceneId = created.identity.persistentId; - m_firstId = first.identity.persistentId; - m_secondId = second.identity.persistentId; - m_componentId = edits.AddComponent(first, typeof(WorkflowState)).identity.persistentId; - m_duplicateId = edits.AddComponent(first, typeof(WorkflowState)).identity.persistentId; + m_sceneID = created.identity.persistentID; + m_firstID = first.identity.persistentID; + m_secondID = second.identity.persistentID; + m_componentID = edits.AddComponent(first, typeof(WorkflowState)).identity.persistentID; + m_duplicateID = edits.AddComponent(first, typeof(WorkflowState)).identity.persistentID; interactions.SetSelection([first, second], first); m_step++; return; @@ -89,10 +89,10 @@ public sealed class WorkflowJourney( WorkflowState state = first.GetComponents().OfType().Single(value => value.number == 7); Require(first.GetComponents().OfType().Count() == 2 && state.reference == second, "Save and reopen lost component order, values or references."); - m_sceneId = reopened.identity.persistentId; - m_firstId = first.identity.persistentId; - m_secondId = second.identity.persistentId; - m_componentId = state.identity.persistentId; + m_sceneID = reopened.identity.persistentID; + m_firstID = first.identity.persistentID; + m_secondID = second.identity.persistentID; + m_componentID = state.identity.persistentID; interactions.SetSelection(first); m_verified.Add("actual File Browser and Inspector: save, close, reopen and reference restoration"); m_step++; @@ -103,10 +103,10 @@ public sealed class WorkflowJourney( AdvancePlayJourney(context); return; } - GameScene scene = workspace.scenes.Single(value => value.identity.persistentId == m_sceneId); - GameObject? firstObject = scene.GetObjects().SingleOrDefault(value => value.identity.persistentId == m_firstId); - GameObject? secondObject = scene.GetObjects().SingleOrDefault(value => value.identity.persistentId == m_secondId); - WorkflowState? component = FindComponent(scene, m_componentId) as WorkflowState; + GameScene scene = workspace.scenes.Single(value => value.identity.persistentID == m_sceneID); + GameObject? firstObject = scene.GetObjects().SingleOrDefault(value => value.identity.persistentID == m_firstID); + GameObject? secondObject = scene.GetObjects().SingleOrDefault(value => value.identity.persistentID == m_secondID); + WorkflowState? component = FindComponent(scene, m_componentID) as WorkflowState; switch (m_step) { case 1: @@ -188,18 +188,18 @@ public sealed class WorkflowJourney( break; case 13: interactions.SetSelection(firstObject); - edits.SetComponentIndex(FindComponent(scene, m_duplicateId)!, 1); + edits.SetComponentIndex(FindComponent(scene, m_duplicateID)!, 1); break; case 14: - Require(firstObject!.GetComponentIndex(FindComponent(scene, m_duplicateId)!) == 1, + Require(firstObject!.GetComponentIndex(FindComponent(scene, m_duplicateID)!) == 1, "Duplicate component ordering selected the wrong instance."); Require(interactions.history.Undo().succeeded && - firstObject.GetComponentIndex(FindComponent(scene, m_duplicateId)!) == 2, "Component order Undo failed."); - Require(edits.RemoveComponent(FindComponent(scene, m_duplicateId)!), "Component removal failed."); + firstObject.GetComponentIndex(FindComponent(scene, m_duplicateID)!) == 2, "Component order Undo failed."); + Require(edits.RemoveComponent(FindComponent(scene, m_duplicateID)!), "Component removal failed."); break; case 15: - Require(FindComponent(scene, m_duplicateId) is null, "The removed component remained attached."); - Require(interactions.history.Undo().succeeded && FindComponent(scene, m_duplicateId) is WorkflowState, + Require(FindComponent(scene, m_duplicateID) is null, "The removed component remained attached."); + Require(interactions.history.Undo().succeeded && FindComponent(scene, m_duplicateID) is WorkflowState, "Component restoration lost identity or type."); m_verified.Add("actual Inspector: duplicate instance order, removal and identity-preserving restoration"); break; @@ -260,7 +260,7 @@ public sealed class WorkflowJourney( if (play.isPlaying) return; Require(workspace.canPersist, "Stop did not restore Edit persistence."); - Require(workspace.scenes.Single(value => value.identity.persistentId == m_sceneId) + Require(workspace.scenes.Single(value => value.identity.persistentID == m_sceneID) .GetObjects().SelectMany(static value => value.GetComponents()).OfType() .All(static value => value.ticks == 0), "Play mutations leaked into the Edit document."); m_verified.Add("actual Game view: Play, frame advancement, Stop and restored Edit"); @@ -278,9 +278,9 @@ public sealed class WorkflowJourney( private static GameComponent? FindComponent( GameScene scene, - Guid persistentId + Guid persistentID ) => scene.GetObjects().SelectMany(static value => value.GetComponents()) - .SingleOrDefault(value => value.identity.persistentId == persistentId); + .SingleOrDefault(value => value.identity.persistentID == persistentID); private static void Require( bool condition, diff --git a/tests/fixtures/editor-ui/WorkflowState.cs.txt b/tests/fixtures/editor-ui/WorkflowState.cs.txt index 9a33876d6..e015a3279 100644 --- a/tests/fixtures/editor-ui/WorkflowState.cs.txt +++ b/tests/fixtures/editor-ui/WorkflowState.cs.txt @@ -2,7 +2,7 @@ using InnoEngine.Reflection; using InnoEngine.Scene; using InnoEngine.Serialization; -[StableTypeId("e669c627-771a-4d3c-a09d-307dcd6b457e")] +[StableTypeID("e669c627-771a-4d3c-a09d-307dcd6b457e")] [AllowMultipleComponent] public sealed class WorkflowState : GameBehavior { diff --git a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs index 3bbf8ebf9..139c3a5a3 100644 --- a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs +++ b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs @@ -1,17 +1,16 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.IO; - +using Xunit; +using Inno.Adapter.Input; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Events; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Input.Runtime; -using Inno.Adapter.Input; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; namespace Inno.Input.Tests; @@ -32,9 +31,10 @@ public void WindowSourcesRemainIsolatedAcrossTextWheelAndRelease() { using var first = new EventInputSource(7); using var second = new EventInputSource(8); - using var firstBackend = first.CreateBackend(); - using var secondBackend = second.CreateBackend(); - Event[] events = [ + using IInputBackend firstBackend = first.CreateBackend(); + using IInputBackend secondBackend = second.CreateBackend(); + Event[] events = + [ new KeyPressedEvent(7, KeyCode.Space), new TextInputEvent(7, "typed"), new MouseScrolledEvent(7, 2f, 3f) @@ -60,8 +60,8 @@ public void WindowSourcesRemainIsolatedAcrossTextWheelAndRelease() [Fact] public void ApplicationSuspensionClearsTransientInputAndRejectsBackgroundPresses() { - using var source = new EventInputSource(windowId: 7); - using var backend = source.CreateBackend(); + using var source = new EventInputSource(windowID: 7); + using IInputBackend backend = source.CreateBackend(); source.ProcessEvent(new KeyPressedEvent(7, KeyCode.Space)); source.ProcessEvent(new MouseButtonPressedEvent(7, MouseButton.Left)); source.ProcessEvent(new TextInputEvent(7, "x")); @@ -82,8 +82,8 @@ public void ApplicationSuspensionClearsTransientInputAndRejectsBackgroundPresses [Fact] public void GloballyConsumedPlatformEventsNeverReachSessionInput() { - using var source = new EventInputSource(windowId: 0); - using var backend = source.CreateBackend(); + using var source = new EventInputSource(windowID: 0); + using IInputBackend backend = source.CreateBackend(); var consumed = new KeyPressedEvent(42, KeyCode.Space); consumed.HandleInGlobal(); source.ProcessEvent(consumed); @@ -95,9 +95,9 @@ public void GloballyConsumedPlatformEventsNeverReachSessionInput() [Fact] public void DisposingOneSessionDoesNotDisconnectOtherSessionSubscriptions() { - using var source = new EventInputSource(windowId: 0); - var retired = source.CreateBackend(); - using var current = source.CreateBackend(); + using var source = new EventInputSource(windowID: 0); + IInputBackend retired = source.CreateBackend(); + using IInputBackend current = source.CreateBackend(); retired.Dispose(); source.ProcessEvent(new KeyPressedEvent(42, KeyCode.Space)); Assert.True(current.Capture(1).IsKeyDown(KeyCode.Space)); @@ -108,7 +108,7 @@ public void DisposingOneSessionDoesNotDisconnectOtherSessionSubscriptions() [Fact] public void EventBackendCapturesTransitionsAndClearsTransientState() { - using var backend = new EventInputBackend(windowId: 7); + using var backend = new EventInputBackend(windowID: 7); backend.ProcessEvent(new KeyPressedEvent(7, KeyCode.Space)); backend.ProcessEvent(new MouseMovedEvent(7, 10f, 20f)); backend.ProcessEvent(new MouseScrolledEvent(7, 0f, 2f)); @@ -129,8 +129,8 @@ public void EventBackendCapturesTransitionsAndClearsTransientState() [Fact] public void AllWindowSourceAcceptsDetachedWindowAndClearsItOnFocusLoss() { - using var source = new EventInputSource(windowId: 0); - using var backend = source.CreateBackend(); + using var source = new EventInputSource(windowID: 0); + using IInputBackend backend = source.CreateBackend(); source.ProcessEvent(new KeyPressedEvent(42, KeyCode.Space)); source.ProcessEvent(new MouseButtonPressedEvent(42, MouseButton.Left)); @@ -149,16 +149,19 @@ public void AllWindowSourceAcceptsDetachedWindowAndClearsItOnFocusLoss() public void RuntimeSubsystemBindsSnapshotAcrossSimulationPhases() { string root = Path.Combine(Path.GetTempPath(), "InnoInputRuntimeTests", Guid.NewGuid().ToString("N")); - using var source = new EventInputSource(windowId: 1); - var observations = new List(); + using var source = new EventInputSource(windowID: 1); + List observations = []; using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(InputRuntimeTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(InputRuntimeTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var options = new RuntimeSessionOptions { kind = RuntimeSessionKind.Play, - applicationId = "tests.input", + applicationID = "tests.input", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "tests.input"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createSubsystems = owner => @@ -177,22 +180,24 @@ public void RuntimeSubsystemBindsSnapshotAcrossSimulationPhases() Assert.Equal([true, true], observations); Assert.Throws(() => _ = Input.snapshot); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } private sealed class InputProbeFactory(List observations) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("tests.input.probe"), - dependencies: [new RuntimeSubsystemId("inno.runtime.input")]); + new RuntimeSubsystemID("tests.input.probe"), + dependencies: [new RuntimeSubsystemID("inno.runtime.input")] + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new InputProbe(observations); } private sealed class InputProbe(List observations) : RuntimeSubsystem { - protected override void OnUpdate(RuntimeFrame frame) - => observations.Add(Input.IsKeyDown(KeyCode.Enter)); + protected override void OnUpdate(RuntimeFrame frame) => observations.Add(Input.IsKeyDown(KeyCode.Enter)); protected override void OnLateUpdate(RuntimeFrame frame) => observations.Add(Input.WasKeyPressed(KeyCode.Enter)); diff --git a/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs b/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs index bfb256796..f5b5ec38d 100644 --- a/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs +++ b/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Platform; -using Xunit; namespace Inno.Input.Tests; @@ -10,13 +10,12 @@ public sealed class NativeWindowSurfaceTests [Fact] public void NativeSurfaceIdentifiersAreOpenAndRejectWhitespace() { - var thirdParty = new PlatformNativeHandleId("tests.surface.custom"); + var thirdParty = new PlatformNativeHandleID("tests.surface.custom"); Assert.True(thirdParty.isValid); - Assert.Equal(new PlatformNativeHandleId("tests.surface.custom"), thirdParty); - Assert.NotEqual(new PlatformNativeHandleId("tests.surface.Custom"), thirdParty); - Assert.False(default(PlatformNativeHandleId).isValid); - Assert.Throws(() => new PlatformNativeHandleId(" ")); - Assert.Throws(() => new PlatformNativeHandleId("tests. surface")); + Assert.Equal(new PlatformNativeHandleID("tests.surface.custom"), thirdParty); + Assert.NotEqual(new PlatformNativeHandleID("tests.surface.Custom"), thirdParty); + Assert.False(default(PlatformNativeHandleID).isValid); + Assert.Throws(() => new PlatformNativeHandleID(" ")); + Assert.Throws(() => new PlatformNativeHandleID("tests. surface")); } - } diff --git a/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs b/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs index 38539ef9d..7eb995a08 100644 --- a/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs +++ b/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Shell; using Xunit; +using Inno.Shell; namespace Inno.Input.Tests; @@ -71,9 +71,11 @@ public async Task SchedulingAndFrameFailuresPropagateToTheShellOwner() var expected = new InvalidOperationException("frame failed"); var driver = new ScheduledShellFrameDriver(_ => ValueTask.CompletedTask); Exception actual = await Assert.ThrowsAsync( - () => driver.RunAsync(() => throw expected, CancellationToken.None).AsTask()); + () => driver.RunAsync(() => throw expected, CancellationToken.None).AsTask() + ); Assert.Same(expected, actual); Assert.Throws( - () => new PollingShellFrameDriver().RunAsync(() => throw expected, CancellationToken.None)); + () => new PollingShellFrameDriver().RunAsync(() => throw expected, CancellationToken.None) + ); } } diff --git a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs index c0be8999f..bbfe581e2 100644 --- a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs +++ b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -20,7 +21,8 @@ using Inno.Storage; using Inno.Text; using Inno.UI; -using Xunit; + +using ShellHost = Inno.Shell.Shell; namespace Inno.Input.Tests; @@ -30,7 +32,7 @@ public sealed class ShellLifecycleTests public async Task SuspensionReasonsComposeWithoutFramesOrBackgroundClockCatchUp() { var catalog = new TestCatalog(); - var elapsed = Stopwatch.StartNew(); + Stopwatch elapsed = Stopwatch.StartNew(); using var shell = new TestShell(catalog, suspendWhenHidden: true); Assert.Equal(ShellState.Ready, shell.state); int opportunities = 0; @@ -94,7 +96,8 @@ public async Task ExecutionAndStoppingFailuresAreBothRetainedAndCallbacksDetach( stoppingFailure = new InvalidOperationException("stopping failure") }; AggregateException failure = await Assert.ThrowsAsync( - () => shell.RunAsync(new PollingShellFrameDriver(), smokeFrameLimit: 1)); + () => shell.RunAsync(new PollingShellFrameDriver(), smokeFrameLimit: 1) + ); Assert.Contains(shell.frameFailure, failure.InnerExceptions); Assert.Contains(shell.stoppingFailure, failure.InnerExceptions); Assert.Equal(ShellState.Faulted, shell.state); @@ -112,27 +115,36 @@ public async Task CancellationStopsWithoutClaimingSmokeCompletion() using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => shell.RunAsync( - new PollingShellFrameDriver(), smokeFrameLimit: 1, cancellationToken: cancellation.Token)); + new PollingShellFrameDriver(), + smokeFrameLimit: 1, + cancellationToken: cancellation.Token + )); Assert.Equal(ShellState.Stopped, shell.state); Assert.Equal(0, shell.smokeFrames); Assert.Empty(shell.frames); Assert.Equal(0, catalog.application.redrawSubscribers); } - private sealed class TestShell : Inno.Shell.Shell + private sealed class TestShell : ShellHost { public TestShell( TestCatalog catalog, bool suspendWhenHidden - ) : base(catalog, new ShellOptions { adapters = new Inno.Adapter.AdapterSelection { - platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, - input = Inno.Adapter.Input.InputBackendId.events, - rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, - storage = Inno.Adapter.Storage.StorageBackendId.fileSystem, - audio = Inno.Adapter.Audio.AudioBackendId.miniAudio, - text = Inno.Adapter.Text.TextBackendId.freeTypeHarfBuzz, - ui = Inno.Adapter.UI.UiBackendId.rmlUi - }, suspendWhenHidden = suspendWhenHidden }) { + ) : base(catalog, new ShellOptions + { + adapters = new AdapterSelection + { + platform = PlatformBackendID.sdl3, + input = InputBackendID.events, + rendering = RenderingBackendID.bgfx, + storage = StorageBackendID.fileSystem, + audio = AudioBackendID.miniAudio, + text = TextBackendID.freeTypeHarfBuzz, + ui = UIBackendID.rmlUI + }, + suspendWhenHidden = suspendWhenHidden + }) + { InitializeAdapterResources(); } @@ -145,23 +157,33 @@ bool suspendWhenHidden protected override void OnFrame(ShellFrame frame) { if (frameFailure is not null) + { throw frameFailure; + } frames.Add(frame); } protected override void OnSuspensionChanged(bool isSuspended) => suspensions.Add(isSuspended); + protected override void OnSmokeCompleted(int frameCount) => smokeFrames = frameCount; + protected override void OnStopping() { if (stoppingFailure is not null) + { throw stoppingFailure; + } } } private sealed class TestCatalog : IAdapterCatalog, IPlatformBackendFactory, IInputBackendFactory, - IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUiBackendFactory + IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUIBackendFactory { - public TestCatalog() => application = new TestApplication(retired); + public TestCatalog() + { + this.application = new TestApplication(retired); + } + public TestApplication application { get; } public List retired { get; } = []; public IPlatformBackendFactory platform => this; @@ -170,35 +192,43 @@ private sealed class TestCatalog : IAdapterCatalog, IPlatformBackendFactory, IIn public IStorageBackendFactory storage => this; public IAudioBackendFactory audio => this; public ITextBackendFactory text => this; - public IUiBackendFactory ui => this; - IReadOnlyList IPlatformBackendFactory.supportedBackends => [PlatformBackendId.sdl3]; - IReadOnlyList IInputBackendFactory.supportedBackends => [InputBackendId.events]; - IReadOnlyList IRenderingBackendFactory.supportedBackends => [RenderingBackendId.bgfx]; - IReadOnlyList IStorageBackendFactory.supportedBackends => [StorageBackendId.fileSystem]; - IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendId.miniAudio]; - IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendId.freeTypeHarfBuzz]; - IReadOnlyList IUiBackendFactory.supportedBackends => [UiBackendId.rmlUi]; - public IPlatformApplication CreateApplication(PlatformBackendId backend) => application; + public IUIBackendFactory ui => this; + IReadOnlyList IPlatformBackendFactory.supportedBackends => [PlatformBackendID.sdl3]; + IReadOnlyList IInputBackendFactory.supportedBackends => [InputBackendID.events]; + IReadOnlyList IRenderingBackendFactory.supportedBackends => [RenderingBackendID.bgfx]; + IReadOnlyList IStorageBackendFactory.supportedBackends => [StorageBackendID.fileSystem]; + IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendID.miniAudio]; + IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendID.freeTypeHarfBuzz]; + IReadOnlyList IUIBackendFactory.supportedBackends => [UIBackendID.rmlUI]; + + public IPlatformApplication CreateApplication(PlatformBackendID backend) => application; + public IInputEventSource CreateEventSource( - InputBackendId backend, + InputBackendID backend, IPlatformWindow window, bool acceptAllWindows ) => new TestInputSource(retired); + public IRenderDevice CreateDevice( - RenderingBackendId backend, + RenderingBackendID backend, RenderingBackendOptions options ) => new TestRenderDevice(retired); - public IApplicationStorage CreateStorage( - StorageBackendId backend, - StorageScope scope - ) => throw new NotSupportedException(); + public IAudioDevice CreateDevice( - AudioBackendId backend, + AudioBackendID backend, AudioBackendOptions options = default ) => throw new NotSupportedException(); - public ITextBackend CreateBackend(TextBackendId backend) => throw new NotSupportedException(); - public IUiBackend CreateBackend(UiBackendId backend) => throw new NotSupportedException(); - public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) + + public IApplicationStorage CreateStorage( + StorageBackendID backend, + StorageScope scope + ) => throw new NotSupportedException(); + + public ITextBackend CreateBackend(TextBackendID backend) => throw new NotSupportedException(); + + public IUIBackend CreateBackend(UIBackendID backend) => throw new NotSupportedException(); + + public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendID backend) => throw new NotSupportedException(); } @@ -207,21 +237,35 @@ private sealed class TestApplication(List retired) : IPlatformApplicatio private Action? m_redraw; public Queue events { get; } = new(); public int redrawSubscribers { get; private set; } + public event Action? redrawRequested { - add { m_redraw += value; redrawSubscribers++; } - remove { m_redraw -= value; redrawSubscribers--; } + add + { + m_redraw += value; + redrawSubscribers++; + } + remove + { + m_redraw -= value; + redrawSubscribers--; + } } + public IPlatformWindow CreateWindow(PlatformWindowOptions options) => new TestWindow(retired); + public bool PollEvent(out Event? evnt) => events.TryDequeue(out evnt); + public IReadOnlyList GetWindows() => []; + public void RequestRedraw() => m_redraw?.Invoke(1); + public void Dispose() => retired.Add("platform"); } private sealed class TestWindow(List retired) : IPlatformWindow { - public uint windowId => 1; + public uint windowID => 1; public string title => "Lifecycle fixture"; public int width => 32; public int height => 32; @@ -229,15 +273,20 @@ private sealed class TestWindow(List retired) : IPlatformWindow public int pixelHeight => 32; public bool isClosed { get; private set; } public bool isFocused => true; + public void RequestClose() => isClosed = true; + public void Dispose() => retired.Add("window"); } private sealed class TestInputSource(List retired) : IInputEventSource { private readonly EventInputSource m_source = new(1); + public IInputBackend CreateBackend() => m_source.CreateBackend(); + public void ProcessEvent(Event evnt) => m_source.ProcessEvent(evnt); + public void Dispose() { m_source.Dispose(); @@ -251,60 +300,80 @@ private sealed class TestRenderDevice(List retired) : IRenderDevice public uint generation => 1; public RenderPresentationSize? primaryPresentationSize { get; private set; } public bool primaryPresentationEncodesSrgb => true; - public void SetVerticalSync(bool enabled) { } + + public void SetVerticalSync(bool enabled) {} + public void BeginFrame() => throw new NotSupportedException(); + public uint EndFrame() => throw new NotSupportedException(); + public void Execute( CompiledRenderGraph graph, ulong frameIndex ) => throw new NotSupportedException(); + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + public PersistentTextureHandle CreateTexture( RenderTextureDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, int arrayLayer = 0 ) => throw new NotSupportedException(); + public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, ReadOnlySpan data ) => throw new NotSupportedException(); + public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, int mipLevel = 0 ) => throw new NotSupportedException(); + public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, out RenderTextureReadbackResult? result ) => throw new NotSupportedException(); + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => throw new NotSupportedException(); + public void DestroyTexture(PersistentTextureHandle texture) => throw new NotSupportedException(); + public PersistentBufferHandle CreateBuffer( PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name ) => throw new NotSupportedException(); + public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, int startElement = 0 ) => throw new NotSupportedException(); + public void DestroyBuffer(PersistentBufferHandle buffer) => throw new NotSupportedException(); + public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => throw new NotSupportedException(); + public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => throw new NotSupportedException(); + public void Dispose() => retired.Add("render"); } } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs index f12d9aa45..879d6ded6 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs @@ -4,10 +4,11 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.SupportPacks; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.BrowserWasm32.Integration.Tests; @@ -22,12 +23,24 @@ public async Task MatchingStaticDependenciesProduceARealManagedPlayerSupportPack ?? throw new InvalidOperationException("Browser product acceptance requires an explicit consume-only native selection."); Assert.True(File.Exists(manifest), "The selected immutable native dependency manifest must exist."); string dotnet = StandardBuildEnvironment.ResolveManagedHost(); - var context = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64"), dotnet, manifest); - var distribution = StandardBuildDistribution.Create(context).build; - var target = new BuildTargetId("browser-wasm"); + BuildCompositionContext context = StandardBuildEnvironment.Capture( + AppContext.BaseDirectory, + new BuildTargetID("windows-x64"), + dotnet, + manifest + ); + BuildDistribution distribution = StandardBuildDistribution.Create(context).build; + var target = new BuildTargetID("browser-wasm"); string output = Path.Combine(root, "artifacts", "validation", "browser-support-pack"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(20)); - using PlayerSupportPackPublication pack = await distribution.supportPacks.PublishAsync(root, output, target, dotnet, cancellation.Token, manifest); + using PlayerSupportPackPublication pack = await distribution.supportPacks.PublishAsync( + root, + output, + target, + dotnet, + manifest, + cancellation.Token + ); distribution.platforms.Single(platform => platform.descriptor.id == target).supportPackSource.Validate(pack.directory); Assert.True(File.Exists(Path.Combine(pack.directory, "References", "Inno.Player.Runtime.dll"))); Assert.False(File.Exists(Path.Combine(pack.directory, "References", "Inno.Player.BrowserWasm32.dll"))); diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs index f3a952c75..77388317d 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs @@ -18,16 +18,17 @@ public void BrowserPlatformChecksObjectAbiWithoutKnowingTheSelectedBackend() "BrowserWasm32Bridge.cs", "global.json", "Analyzers/Inno.Runtime.Generators.dll", "Analyzers/Inno.Core.Serialization.Generators.dll", "wwwroot/index.html", "wwwroot/main.js", "Native/wasm_sjlj_shim.c", "References/Inno.Player.Runtime.dll" - }) + }) { Write("PlayerLink/" + input); + } string archive = Path.Combine(m_root, "PlayerLink", "Native", "custom.a"); string header = "object.o/".PadRight(16) + "0".PadRight(12) + "0".PadRight(6) - + "0".PadRight(6) + "644".PadRight(8) + "8".PadRight(10) + "`\n"; + + "0".PadRight(6) + "644".PadRight(8) + "8".PadRight(10) + "`\n"; byte[] bytes = [.. Encoding.ASCII.GetBytes("!\n" + header), 0, 97, 115, 109, 1, 0, 0, 0]; File.WriteAllBytes(archive, bytes); - var validator = new Inno.Build.BrowserWasm32.BrowserWasm32SupportPackValidator(); + var validator = new BrowserWasm32SupportPackValidator(); validator.Validate(m_root); - bytes[^8] = 0x7f; + bytes[^8] = 0x7F; File.WriteAllBytes(archive, bytes); Assert.Contains("ABI", Assert.Throws(() => validator.Validate(m_root)).Message); } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs index 233e83b4e..e7bcc146a 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs @@ -1,4 +1,3 @@ -using Inno.Build.Composition; using System; using System.IO; using System.Linq; @@ -6,6 +5,7 @@ using System.Threading.Tasks; using Xunit; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Products.Standard; using Inno.Build.Toolchains; @@ -15,21 +15,35 @@ namespace Inno.Build.BrowserWasm32.Tests; public sealed class BrowserSupportPackTests : IDisposable { private readonly string m_root = Path.Combine( - Path.GetTempPath(), "InnoBrowserPackTests", Guid.NewGuid().ToString("N")); + Path.GetTempPath(), + "InnoBrowserPackTests", + Guid.NewGuid().ToString("N") + ); public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] public async Task BrowserPackRequiresItsStaticGameLinkerClosure() { - ProductNativeBuildPlan plan = StandardBuildDistribution.Create(new BuildCompositionContext("explicit-sdk", Path.GetTempPath(), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("browser-wasm"))).build.ResolveNativeProduct("browser-wasm", "player").plan; + ProductNativeBuildPlan plan = StandardBuildDistribution.Create( + new BuildCompositionContext( + "explicit-sdk", + Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetID("browser-wasm") + ) + ).build + .ResolveNativeProduct("browser-wasm", "player").plan; IPlayerSupportPackValidator validator = StandardBuildDistribution.Create( - StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64"))).build.platforms - .Single(static platform => platform.descriptor.id == new BuildTargetId("browser-wasm")).supportPackSource; + StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID("windows-x64")) + ).build.platforms + .Single(static platform => platform.descriptor.id == new BuildTargetID("browser-wasm")).supportPackSource; string pack = Path.Combine(m_root, "candidate"); Write(pack, "References/Inno.Runtime.dll"); Write(pack, "PlayerLink/Player.csproj"); @@ -48,39 +62,42 @@ public async Task BrowserPackRequiresItsStaticGameLinkerClosure() { "Inno.Native.Bgfx.dll", "Inno.Native.MiniAudio.dll", "Inno.Native.Sdl3.dll", "Inno.Native.Text.dll", "Inno.Native.UI.dll" - }) - { + }) { Write(pack, "PlayerLink/References/" + binding); Write(pack, "References/" + binding); } Write(pack, "PlayerLink/References/BGCS.Runtime.dll"); foreach (ProductNativeBuildStep step in plan.steps) - foreach (string archive in step.component.staticBuild!.logicalOutputs.Select(Inno.Build.BrowserWasm32.BrowserWasm32LinkerSettings.Create().GetStaticFileName)) + { + foreach (string archive in step.component.staticBuild!.logicalOutputs.Select( + BrowserWasm32LinkerSettings.Create().GetStaticFileName + )) { Write(pack, $"PlayerLink/Native/{step.id}/browser-wasm/{archive}"); + } + } var catalog = new PlayerSupportPackCatalog(m_root); Write(pack, "PlayerLink/Native/foreign.dll"); - InvalidDataException foreignBinary = Assert.Throws( - () => validator.Validate(pack)); + InvalidDataException foreignBinary = Assert.Throws(() => validator.Validate(pack)); Assert.Contains("foreign.dll", foreignBinary.Message, StringComparison.Ordinal); File.Delete(Path.Combine(pack, "PlayerLink", "Native", "foreign.dll")); File.Delete(Path.Combine(pack, "PlayerLink", "HttpPlayerContentSource.cs")); - InvalidDataException missingSource = Assert.Throws( - () => validator.Validate(pack)); + InvalidDataException missingSource = Assert.Throws(() => validator.Validate(pack)); Assert.Contains("HttpPlayerContentSource.cs", missingSource.Message, StringComparison.Ordinal); Write(pack, "PlayerLink/HttpPlayerContentSource.cs"); Write(pack, "PlayerLink/Native/extra.a"); Assert.Throws(() => validator.Validate(pack)); File.Delete(Path.Combine(pack, "PlayerLink", "Native", "extra.a")); - using PlayerSupportPackLease published = await catalog.PublishAsync(new BuildTargetId("browser-wasm"), pack, validator); + using PlayerSupportPackLease published = await catalog.PublishAsync(new BuildTargetID("browser-wasm"), pack, validator); pack = published.directory; Assert.True(File.Exists(Path.Combine(pack, "PlayerLink", "References", "BGCS.Runtime.dll"))); - using PlayerSupportPackLease selected = catalog.Acquire(new BuildTargetId("browser-wasm"), validator); + using PlayerSupportPackLease selected = catalog.Acquire(new BuildTargetID("browser-wasm"), validator); Assert.Equal(pack, selected.directory); File.Delete(Path.Combine(pack, "PlayerLink", "Native", "sdl3", "browser-wasm", "libSDL3.a")); InvalidDataException missingArchive = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("browser-wasm"), validator)); + () => catalog.Acquire(new BuildTargetID("browser-wasm"), validator) + ); Assert.Contains("libSDL3.a", missingArchive.Message, StringComparison.Ordinal); } @@ -93,10 +110,12 @@ string relativePath if (relativePath.EndsWith(".a", StringComparison.Ordinal)) { string header = "fixture.o/".PadRight(16) + "0".PadRight(12) + "0".PadRight(6) - + "0".PadRight(6) + "100644".PadRight(8) + "8".PadRight(10) + "`\n"; + + "0".PadRight(6) + "100644".PadRight(8) + "8".PadRight(10) + "`\n"; File.WriteAllBytes(path, [.. Encoding.ASCII.GetBytes("!\n" + header), .. "\0asm\u0001\0\0\0"u8]); } else + { File.WriteAllText(path, "fixture"); + } } } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs index 65b2ab785..929edfc71 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs @@ -4,9 +4,9 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Build.Toolchains; -using Inno.Build.BrowserWasm32; using Xunit; +using Inno.Build.BrowserWasm32; +using Inno.Build.Toolchains; namespace Inno.Build.BrowserWasm32.Tests; @@ -17,7 +17,9 @@ public sealed class BrowserToolchainTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -31,8 +33,12 @@ public async Task EnvironmentUsesTheProjectSelectedToolsWithoutChangingTheParent IReadOnlyDictionary environment = await EmscriptenToolchainResolver.ResolveAsync("dotnet", project); Assert.Equal(Path.Combine(m_root, "selected-sdk", "bin"), environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"]); - Assert.True(File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang.exe" : "clang"))); - Assert.True(File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang++.exe" : "clang++"))); + Assert.True( + File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang.exe" : "clang")) + ); + Assert.True( + File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang++.exe" : "clang++")) + ); Assert.Equal(Path.Combine(m_root, "selected-cache"), environment["EM_CACHE"]); Assert.Equal(Path.Combine(m_root, "selected-node", "bin", NodeFileName()), environment["EMSDK_NODE"]); Assert.False(environment.ContainsKey("EMCC_CORES")); @@ -49,7 +55,8 @@ public async Task EnvironmentRejectsAnIncompleteSelectedToolchain() File.Delete(Path.Combine(m_root, "selected-node", "bin", NodeFileName())); FileNotFoundException failure = await Assert.ThrowsAsync( - () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project)); + () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project) + ); Assert.EndsWith(NodeFileName(), failure.FileName); } @@ -62,7 +69,8 @@ public async Task EnvironmentRejectsAProjectWithoutWorkloadSelection() new XDocument(new XElement("Project")).Save(project); InvalidOperationException failure = await Assert.ThrowsAsync( - () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project)); + () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project) + ); Assert.Contains("EmscriptenSdkToolsPath", failure.Message, StringComparison.Ordinal); } @@ -70,20 +78,25 @@ public async Task EnvironmentRejectsAProjectWithoutWorkloadSelection() [Fact] public async Task CapturePreservesStructuredArgumentsAndChildOnlyEnvironment() { - const string variable = "INNO_TOOLCHAIN_TEST_VALUE"; - const string value = "spaces and `literal` $characters"; - string? parent = Environment.GetEnvironmentVariable(variable); + const string C_VARIABLE = "INNO_TOOLCHAIN_TEST_VALUE"; + const string C_VALUE = "spaces and `literal` $characters"; + string? parent = Environment.GetEnvironmentVariable(C_VARIABLE); Directory.CreateDirectory(m_root); string project = Path.Combine(m_root, "Environment.proj"); - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("Result", "$(" + variable + ")")))).Save(project); + new XDocument( + new XElement("Project", new XElement("PropertyGroup", new XElement("Result", "$(" + C_VARIABLE + ")"))) + ).Save(project); - string output = await ToolchainEnvironment.CaptureOutputAsync("dotnet", + string output = await ToolchainEnvironment.CaptureOutputAsync( + "dotnet", ["msbuild", project, "-nologo", "-nodeReuse:false", "-getProperty:Result"], - m_root, CancellationToken.None, new Dictionary { [variable] = value }); + m_root, + CancellationToken.None, + new Dictionary { [C_VARIABLE] = C_VALUE } + ); - Assert.Equal(value, output.Trim()); - Assert.Equal(parent, Environment.GetEnvironmentVariable(variable)); + Assert.Equal(C_VALUE, output.Trim()); + Assert.Equal(parent, Environment.GetEnvironmentVariable(C_VARIABLE)); } [Fact] @@ -92,7 +105,11 @@ public async Task CaptureRejectsFailedTools() Directory.CreateDirectory(m_root); await Assert.ThrowsAsync(() => ToolchainEnvironment.CaptureOutputAsync( - "dotnet", ["--inno-invalid-option"], m_root, CancellationToken.None)); + "dotnet", + ["--inno-invalid-option"], + m_root, + CancellationToken.None + )); } [Fact] @@ -102,7 +119,11 @@ public async Task CaptureDoesNotStartAnAlreadyCanceledOperation() cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => ToolchainEnvironment.CaptureOutputAsync( - "inno-tool-that-does-not-exist", [], m_root, cancellation.Token)); + "inno-tool-that-does-not-exist", + [], + m_root, + cancellation.Token + )); } private string CreateProject() @@ -120,11 +141,18 @@ private string CreateProject() File.WriteAllText(Path.Combine(node, "bin", NodeFileName()), string.Empty); File.WriteAllText(Path.Combine(python, "python.exe"), string.Empty); string project = Path.Combine(m_root, "SelectedWorkload.proj"); - new XDocument(new XElement("Project", new XElement("PropertyGroup", - new XElement("EmscriptenSdkToolsPath", sdk), - new XElement("EmscriptenNodeToolsPath", node), - new XElement("EmscriptenPythonToolsPath", python), - new XElement("EmscriptenCacheSdkCacheDir", cache)))).Save(project); + new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("EmscriptenSdkToolsPath", sdk), + new XElement("EmscriptenNodeToolsPath", node), + new XElement("EmscriptenPythonToolsPath", python), + new XElement("EmscriptenCacheSdkCacheDir", cache) + ) + ) + ).Save(project); return project; } diff --git a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs index 4a9d507c8..e28cb9fde 100644 --- a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs @@ -1,18 +1,17 @@ using System; using System.IO; +using Xunit; using Inno.Build; using Inno.Testing.SupportPacks; -using Xunit; namespace Inno.Build.MacOSArm64.Tests; public sealed class SupportPackValidationTests : PlayerSupportPackFixture { - [Fact] public void PlatformPackRejectsAMissingContentSource() { - BuildTargetId target = new BuildTargetId("macos-arm64"); + var target = new BuildTargetID("macos-arm64"); string pack = GetSupportPackDirectory(target); string source = "MacOSArm64PlayerContentSource.cs"; File.Delete(Path.Combine(pack, "PlayerLink", source)); @@ -26,12 +25,13 @@ public void PlatformPackRejectsAMissingContentSource() [Fact] public void SupportPackRejectsAuthoringAssetPipelineAssemblies() { - string supportPack = GetSupportPackDirectory(new BuildTargetId("macos-arm64")); + string supportPack = GetSupportPackDirectory(new BuildTargetID("macos-arm64")); File.WriteAllBytes(Path.Combine(supportPack, "Inno.Assets.Pipeline.dll"), [0x49, 0x4E, 0x4E, 0x4F]); var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetID("macos-arm64"), new MacOSArm64SupportPackValidator()) + ); Assert.Contains("forbidden build-time file", exception.Message, StringComparison.OrdinalIgnoreCase); } @@ -39,12 +39,13 @@ public void SupportPackRejectsAuthoringAssetPipelineAssemblies() [Fact] public void SupportPackRejectsMissingMiniAudioRuntime() { - string supportPack = GetSupportPackDirectory(new BuildTargetId("macos-arm64")); + string supportPack = GetSupportPackDirectory(new BuildTargetID("macos-arm64")); File.Delete(Path.Combine(supportPack, "native", "libminiaudio-release.dylib")); var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetID("macos-arm64"), new MacOSArm64SupportPackValidator()) + ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); } @@ -52,11 +53,13 @@ public void SupportPackRejectsMissingMiniAudioRuntime() [Fact] public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() { - BuildTargetId target = new BuildTargetId("macos-arm64"); + var target = new BuildTargetID("macos-arm64"); string directory = GetSupportPackDirectory(target); string library = "libminiaudio-release.dylib"; - File.WriteAllBytes(Path.Combine(directory, "native", library), - CreateNativeImage(new BuildTargetId("windows-x64"))); + File.WriteAllBytes( + Path.Combine(directory, "native", library), + CreateNativeImage(new BuildTargetID("windows-x64")) + ); IPlayerSupportPackValidator validator = new MacOSArm64SupportPackValidator(); InvalidDataException failure = Assert.Throws(() => validator.Validate(directory)); Assert.Contains("ARM64 ABI", failure.Message); @@ -65,12 +68,13 @@ public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() [Fact] public void SupportPackRejectsForeignNativeRuntime() { - string supportPack = GetSupportPackDirectory(new BuildTargetId("macos-arm64")); + string supportPack = GetSupportPackDirectory(new BuildTargetID("macos-arm64")); File.WriteAllBytes(Path.Combine(supportPack, "native", "SDL3-release.so"), [0x49, 0x4E, 0x4E, 0x4F]); var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetID("macos-arm64"), new MacOSArm64SupportPackValidator()) + ); Assert.Contains("foreign native runtime", exception.Message, StringComparison.Ordinal); } @@ -78,16 +82,16 @@ public void SupportPackRejectsForeignNativeRuntime() [Theory] [InlineData("libinno-text-release.dylib")] [InlineData("libinno-ui-release.dylib")] - public void SupportPackRejectsMissingTextOrUiRuntime(string nativeRuntime) + public void SupportPackRejectsMissingTextOrUIRuntime(string nativeRuntime) { - string supportPack = GetSupportPackDirectory(new BuildTargetId("macos-arm64")); + string supportPack = GetSupportPackDirectory(new BuildTargetID("macos-arm64")); File.Delete(Path.Combine(supportPack, "native", nativeRuntime)); var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetID("macos-arm64"), new MacOSArm64SupportPackValidator()) + ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); } - } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs index c313d01e2..01461296d 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs @@ -8,18 +8,16 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Build.WindowsX64; -using Xunit; namespace Inno.Build.WindowsX64.Integration.Tests; [SupportedOSPlatform("windows")] public sealed class NativeBindingCMakeTests { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate int ReadValue(); - [WindowsCompilerFact] public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOfUpstreamSources() { @@ -80,35 +78,69 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf """); var compilation = new NativeBindingCompilation { - roots = [new("generated", "", true, true), new("user", headerRoot, false, true)], + roots = + [ + new NativeBindingSourceRoot("generated", string.Empty, true, true), + new NativeBindingSourceRoot("user", headerRoot, false, true) + ], files = [Input("generated", "binding.c", unit, true), Input("user", "api.h", header, false)], - includeDirectories = [new("user", "", false, false)], - defines = ["INNO_BINDING_ONLY=1"], compilerDefines = [], cxxStandard = 0, cStandard = 17, - requiredExports = ["value", "upstream"], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] + includeDirectories = [new NativeBindingIncludeDirectory("user", string.Empty, false, false)], + defines = ["INNO_BINDING_ONLY=1"], + compilerDefines = [], + cxxStandard = 0, + cStandard = 17, + requiredExports = ["value", "upstream"], + staticExportSymbols = [], + staticExportAbi = string.Empty, + staticExportNames = [] }; File.WriteAllBytes(Path.Combine(native, "compilation.json"), JsonSerializer.SerializeToUtf8Bytes(compilation)); - var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + var owner = new NativeComponentDescriptor( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); var descriptor = new NativeBindingGenerationDescriptor { - fingerprint = new string('a', 64), artifactDirectory = artifact, artifactOwnerDirectory = root, - bindingsPath = managed, nativeDirectory = native, - usesRuntimeImports = false, + fingerprint = new string('a', 64), + artifactDirectory = artifact, + artifactOwnerDirectory = root, + bindingsPath = managed, + nativeDirectory = native, + usesRuntimeImports = false }; using var bindings = new NativeBindingGenerationResult( - new Dictionary { [owner.nativeProject] = descriptor }, []); - var tools = await new WindowsX64NativeToolchainProvider(ToolchainEnvironment.ResolveExecutable("dotnet")) - .ResolveAsync(new(root, "release"), (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); - NativeBuildContext context = new NativeBuildContext(sourceAlias.toolPath, "release").WithToolchain(tools).WithBindings(bindings) - .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); - var recipe = new NativeBuildRecipe(owner, "fixture", "windows-x64", - new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(root, path)), tools.declarations); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + new Dictionary { [owner.nativeProject] = descriptor }, + [] + ); + NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider(ToolchainEnvironment.ResolveExecutable("dotnet")) + .ResolveAsync( + new NativeBuildContext(root, "release"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); + NativeBuildContext context = new NativeBuildContext(sourceAlias.toolPath, "release").WithToolchain(tools) + .WithBindings(bindings) + .WithComponentOptions(owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + var recipe = new NativeBuildRecipe( + owner, + "fixture", + "windows-x64", + new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(root, path)), + tools.declarations + ); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( operation, output, cancellation - ) => { + ) => + { NativeCMakeSource inputs = await NativeCMakeExecutor.PrepareSourceAsync(operation, owner, cancellation); string frozenHeader = inputs.ResolvePath(header); Assert.NotEqual(header, frozenHeader); @@ -121,10 +153,11 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf catch (InvalidOperationException exception) { string requirements = Path.Combine(operation.GetNativeBuildRoot(owner), "CMake", "BindingInputs.cmake"); - throw new Xunit.Sdk.XunitException(exception + Environment.NewLine + File.ReadAllText(requirements)); + throw new XunitException(exception + Environment.NewLine + File.ReadAllText(requirements)); } File.Copy(NativeCMakeExecutor.FindOutput(operation, build, "fixture.dll"), Path.Combine(output, "fixture.dll")); - }); + } + ); Assert.True(File.Exists(header)); Assert.False(File.Exists(hidden)); nint library = NativeLibrary.Load(Assert.Single(product.files)); @@ -141,28 +174,35 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf finally { if (File.Exists(hidden)) + { File.Move(hidden, header, overwrite: true); + } Directory.Delete(root, recursive: true); Directory.Delete(headerRoot, recursive: true); } } private static NativeBindingSourceFile Input( - string rootId, + string rootID, string relative, string path, bool compile ) { byte[] content = File.ReadAllBytes(path); - return new(rootId, relative, content.Length, Convert.ToHexStringLower(SHA256.HashData(content)), compile); + return new(rootID, relative, content.Length, Convert.ToHexStringLower(SHA256.HashData(content)), compile); } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int ReadValue(); + private sealed class WindowsCompilerFactAttribute : FactAttribute { public WindowsCompilerFactAttribute() { if (!OperatingSystem.IsWindows()) - Skip = "Requires the Windows MSVC toolchain and its path-length contract."; + { + this.Skip = "Requires the Windows MSVC toolchain and its path-length contract."; + } } } } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs index 4d56554fa..8c1275727 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs @@ -25,9 +25,14 @@ public async Task ProcessTempDirectoriesSelectCompatibleCMakeWorkspaces() string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); string cmake = OperatingSystem.IsWindows() - ? (await new WindowsX64NativeToolchainProvider(dotnet).ResolveAsync(new(repository, "debug"), - (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", timeout.Token)).ResolveExecutable("cmake") - : ToolchainEnvironment.ResolveExecutable("cmake"); + ? (await new WindowsX64NativeToolchainProvider(dotnet).ResolveAsync( + new NativeBuildContext(repository, "debug"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + timeout.Token + )).ResolveExecutable("cmake") + : ToolchainEnvironment.ResolveExecutable("cmake"); string project = Path.Combine(root, "Runner.csproj"); await File.WriteAllTextAsync(project, $$""" @@ -91,10 +96,14 @@ await File.WriteAllTextAsync(Path.Combine(root, "Program.cs"), """ File.WriteAllText(args[2], execution ?? "cache"); return 0; """); - var environment = DotNetSdkEnvironment.Create(dotnet); - await ToolchainEnvironment.RunAsync(dotnet, + IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(dotnet); + await ToolchainEnvironment.RunAsync( + dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], - repository, timeout.Token, environment); + repository, + timeout.Token, + environment + ); string physical = Path.Combine(root, "Workspace with spaces", new string('x', 70), new string('y', 70), new string('z', 70)); string? firstExecution = null; (string value, string temporary, bool hit)[] calls = @@ -104,7 +113,7 @@ await ToolchainEnvironment.RunAsync(dotnet, ("third", "first-temp", false), ("third", "second-temp", true) ]; - foreach (var call in calls) + foreach ((string value, string temporary, bool hit) call in calls) { string temporary = Path.Combine(root, call.temporary); Directory.CreateDirectory(temporary); @@ -115,18 +124,30 @@ await ToolchainEnvironment.RunAsync(dotnet, ["TMPDIR"] = temporary }; string report = Path.Combine(root, call.value + (call.hit ? "-hit" : string.Empty) + ".txt"); - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, [Path.Combine(root, "bin/Debug/net10.0/Runner.dll"), physical, cmake, report, call.value, call.hit ? "hit" : "build"], - repository, timeout.Token, processEnvironment); + repository, + timeout.Token, + processEnvironment + ); string current = await File.ReadAllTextAsync(report); if (call.hit) + { Assert.Equal("cache", current); + } else if (call.value == "first") + { firstExecution = current; + } else if (call.value == "second" && OperatingSystem.IsWindows()) + { Assert.NotEqual(firstExecution, current); + } else + { Assert.Equal(firstExecution, current); + } } } finally diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs index fe581ff74..18819b685 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -15,9 +15,6 @@ namespace Inno.Build.WindowsX64.Integration.Tests; public sealed class WindowsColdPublicationTests : IDisposable { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate int ReadNativeValue(); - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoNativePublication", Guid.NewGuid().ToString("N")); [Fact] @@ -25,35 +22,68 @@ public sealed class WindowsColdPublicationTests : IDisposable public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytesAreTemporarilyChanged() { if (!OperatingSystem.IsWindows()) + { return; + } NativeBuildContext unresolved = CreateContext(); - NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet")).ResolveAsync( - unresolved, (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); + NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider( + Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet") + ).ResolveAsync( + unresolved, + (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); NativeBuildContext context = unresolved.WithToolchain(tools).WithComponentOptions( - new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), - new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + new NativeComponentBuildOptions(NativeLibraryKind.Shared) + ); string source = Path.Combine(m_root, "Source"); Directory.CreateDirectory(source); - File.WriteAllText(Path.Combine(source, "CMakeLists.txt"), + File.WriteAllText( + Path.Combine(source, "CMakeLists.txt"), "cmake_minimum_required(VERSION 3.20)\nproject(ColdFixture C)\n" + "configure_file(\"${INNO_FIXTURE_INPUT}\" \"${CMAKE_CURRENT_BINARY_DIR}/answer.h\" COPYONLY)\n" + "add_library(fixture SHARED api.c)\n" - + "target_include_directories(fixture PRIVATE \"${CMAKE_CURRENT_BINARY_DIR}\")\n"); - File.WriteAllText(Path.Combine(source, "api.c"), "#include \"answer.h\"\n__declspec(dllexport) int value(void) { return ANSWER; }\n"); + + "target_include_directories(fixture PRIVATE \"${CMAKE_CURRENT_BINARY_DIR}\")\n" + ); + File.WriteAllText( + Path.Combine(source, "api.c"), + "#include \"answer.h\"\n__declspec(dllexport) int value(void) { return ANSWER; }\n" + ); string header = Path.Combine(source, "answer.h"); File.WriteAllText(header, "#define ANSWER 42\n"); DateTime timestamp = File.GetLastWriteTimeUtc(header); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "windows-x64", [source], []), async ( + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "windows-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { - var owner = new NativeComponentDescriptor("fixture", + ) => + { + var owner = new NativeComponentDescriptor( + "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); NativeCMakeSource copied = await NativeCMakeExecutor.PrepareSourceAsync(scoped, owner, cancellation); Assert.Same(copied, await NativeCMakeExecutor.PrepareSourceAsync(scoped.WithToolchain(tools), owner, cancellation)); Assert.NotEqual(source, copied.ResolvePath(source)); @@ -64,8 +94,14 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes try { Assert.Equal("#define ANSWER 42\n", File.ReadAllText(copied.ResolvePath(header))); - string directory = await NativeCMakeExecutor.BuildAsync(scoped, owner, source, - "fixture", ["-DINNO_FIXTURE_INPUT=" + header], cancellation); + string directory = await NativeCMakeExecutor.BuildAsync( + scoped, + owner, + source, + "fixture", + ["-DINNO_FIXTURE_INPUT=" + header], + cancellation + ); File.Copy(NativeCMakeExecutor.FindOutput(scoped, directory, "fixture.dll"), Path.Combine(output, "fixture.dll")); } finally @@ -73,7 +109,8 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes File.WriteAllText(header, "#define ANSWER 42\n"); File.SetLastWriteTimeUtc(header, timestamp); } - }); + } + ); Assert.Single(product.files); Assert.True(new FileInfo(product.files[0]).Length > 0); @@ -94,21 +131,11 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } - private static NativeBuildRecipe CreateRecipe( - NativeBuildContext context, - NativeComponentDescriptor owner, - string component, - string targetId, - IReadOnlyList inputPaths, - IReadOnlyList declarations - ) => new(owner, component, targetId, - inputPaths.Concat(context.toolchain?.inputPaths ?? []) - .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), - declarations.Concat(context.toolchain?.declarations ?? [])); - private NativeBuildContext CreateContext() { Directory.CreateDirectory(m_root); @@ -119,4 +146,23 @@ private NativeBuildContext CreateContext() File.WriteAllText(Path.Combine(owner, projectName + ".csproj"), ""); return new(m_root, "release"); } + + private static NativeBuildRecipe CreateRecipe( + NativeBuildContext context, + NativeComponentDescriptor owner, + string component, + string targetID, + IReadOnlyList inputPaths, + IReadOnlyList declarations + ) => new( + owner, + component, + targetID, + inputPaths.Concat(context.toolchain?.inputPaths ?? []) + .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), + declarations.Concat(context.toolchain?.declarations ?? []) + ); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int ReadNativeValue(); } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs index 40755bb14..8ab79afb9 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -14,9 +14,6 @@ namespace Inno.Build.WindowsX64.Integration.Tests; public sealed class WindowsNativeWorkspaceTests : IDisposable { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate int ReadNativeValue(); - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoWorkspaceTests", Guid.NewGuid().ToString("N")); private readonly string m_bindingRoot = Path.Combine(Path.GetTempPath(), "InnoWorkspaceBindings", Guid.NewGuid().ToString("N")); private readonly NativeComponentDescriptor m_owner = new("fixture", "native/fixture.csproj", "build/fixture.csproj"); @@ -33,14 +30,24 @@ public WindowsNativeWorkspaceTests() public async Task WindowsCMakeReusesUnchangedObjectsAndPublishesChangedSourceBytes() { if (!OperatingSystem.IsWindows()) + { return; + } NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider( - ToolchainEnvironment.ResolveExecutable("dotnet")).ResolveAsync(new(m_root, "release"), - (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); + ToolchainEnvironment.ResolveExecutable("dotnet") + ).ResolveAsync( + new NativeBuildContext(m_root, "release"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); string source = Path.Combine(m_root, "Source"); Directory.CreateDirectory(source); - File.WriteAllText(Path.Combine(source, "CMakeLists.txt"), - "cmake_minimum_required(VERSION 3.20)\nproject(WorkspaceFixture C)\nadd_library(fixture SHARED api.c stable.c)\n"); + File.WriteAllText( + Path.Combine(source, "CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.20)\nproject(WorkspaceFixture C)\nadd_library(fixture SHARED api.c stable.c)\n" + ); string changed = Path.Combine(source, "api.c"); File.WriteAllText(changed, "__declspec(dllexport) int value(void) { return 41; }\n"); File.WriteAllText(Path.Combine(source, "stable.c"), "int stable(void) { return 7; }\n"); @@ -49,17 +56,19 @@ public async Task WindowsCMakeReusesUnchangedObjectsAndPublishesChangedSourceByt string? stableObject = null; DateTime stableTime = default; int compilations = 0; - async Task Produce( + async Task ProduceAsync( NativeBuildContext scoped, string output, - CancellationToken cancellation + CancellationToken cancellationToken ) { string current = scoped.GetNativeBuildRoot(m_owner); string physical = new DirectoryInfo(current).LinkTarget ?? current; if (workspace is not null) + { Assert.Equal(workspace, physical); + } workspace = physical; - string build = await NativeCMakeExecutor.BuildAsync(scoped, m_owner, source, "fixture", [], cancellation); + string build = await NativeCMakeExecutor.BuildAsync(scoped, m_owner, source, "fixture", [], cancellationToken); File.Copy(NativeCMakeExecutor.FindOutput(scoped, build, "fixture.dll"), Path.Combine(output, "fixture.dll")); string objectPath = Directory.EnumerateFiles(physical, "*.obj", SearchOption.AllDirectories) .Single(path => Path.GetFileName(path) is "stable.obj" or "stable.c.obj"); @@ -74,21 +83,27 @@ CancellationToken cancellation Assert.Equal(stableTime, File.GetLastWriteTimeUtc(objectPath)); } } - NativeBuildContext Context() => new NativeBuildContext(m_root, "release").WithToolchain(tools) - .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); - NativeBuildRecipe Recipe() => new(m_owner, "fixture", "windows-x64", - new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), - tools.declarations.Concat(new[] { "shared", "fixture" })); - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(Context(), Recipe(), Produce); + NativeBuildContext Context() + => new NativeBuildContext(m_root, "release").WithToolchain(tools) + .WithComponentOptions(m_owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + NativeBuildRecipe Recipe() + => new( + m_owner, + "fixture", + "windows-x64", + new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), + tools.declarations.Concat(new[] { "shared", "fixture" }) + ); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(Context(), Recipe(), ProduceAsync); Assert.Equal(41, Read(first)); File.WriteAllText(changed, "__declspec(dllexport) int value(void) { return 42; }\n"); File.SetLastWriteTimeUtc(changed, originalTime); - using NativeBuildProduct second = await NativeArtifactPublisher.PublishAsync(Context(), Recipe(), Produce); + using NativeBuildProduct second = await NativeArtifactPublisher.PublishAsync(Context(), Recipe(), ProduceAsync); Assert.NotEqual(first.fingerprint, second.fingerprint); Assert.Equal(42, Read(second)); Assert.Equal(41, Read(first)); NativeBuildContext hitContext = Context(); - using NativeBuildProduct hit = await NativeArtifactPublisher.PublishAsync(hitContext, Recipe(), Produce); + using NativeBuildProduct hit = await NativeArtifactPublisher.PublishAsync(hitContext, Recipe(), ProduceAsync); Assert.Equal(second.fingerprint, hit.fingerprint); Assert.Equal(2, compilations); Assert.Equal(0, hitContext.statistics.nativeProcesses); @@ -97,9 +112,13 @@ CancellationToken cancellation public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } if (Directory.Exists(m_bindingRoot)) + { Directory.Delete(m_bindingRoot, recursive: true); + } } private static int Read(NativeBuildProduct product) @@ -115,4 +134,6 @@ private static int Read(NativeBuildProduct product) } } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int ReadNativeValue(); } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs index df99bfa4b..5138be735 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs @@ -1,18 +1,17 @@ using System; using System.IO; +using Xunit; using Inno.Build; using Inno.Testing.SupportPacks; -using Xunit; namespace Inno.Build.WindowsX64.Tests; public sealed class SupportPackValidationTests : PlayerSupportPackFixture { - [Fact] public void PlatformPackRejectsAMissingContentSource() { - BuildTargetId target = new BuildTargetId("windows-x64"); + var target = new BuildTargetID("windows-x64"); string pack = GetSupportPackDirectory(target); string source = "WindowsX64PlayerContentSource.cs"; File.Delete(Path.Combine(pack, "PlayerLink", source)); @@ -26,14 +25,15 @@ public void PlatformPackRejectsAMissingContentSource() [Fact] public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() { - BuildTargetId target = new BuildTargetId("windows-x64"); + var target = new BuildTargetID("windows-x64"); string directory = GetSupportPackDirectory(target); string library = "miniaudio-release.dll"; - File.WriteAllBytes(Path.Combine(directory, "native", library), - CreateNativeImage(new BuildTargetId("macos-arm64"))); + File.WriteAllBytes( + Path.Combine(directory, "native", library), + CreateNativeImage(new BuildTargetID("macos-arm64")) + ); IPlayerSupportPackValidator validator = new WindowsX64SupportPackValidator(); InvalidDataException failure = Assert.Throws(() => validator.Validate(directory)); Assert.Contains("PE header", failure.Message); } - } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs index ef90a6371..9ff0d38e1 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs @@ -3,9 +3,9 @@ using System.IO; using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Build.WindowsX64; -using Xunit; namespace Inno.Build.WindowsX64.Tests; @@ -16,7 +16,9 @@ public sealed class ToolRunnerPathTests public async Task DeepOwnedExecutableStartsAndRemainsAfterItsAliasIsReleased() { if (!OperatingSystem.IsWindows()) + { return; + } string root = Path.Combine(Path.GetTempPath(), "InnoToolRunner", Guid.NewGuid().ToString("N")); string directory = Path.Combine(root, new string('a', 90), new string('b', 90), new string('c', 50)); Directory.CreateDirectory(directory); @@ -25,8 +27,11 @@ public async Task DeepOwnedExecutableStartsAndRemainsAfterItsAliasIsReleased() { File.Copy(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"), executable); Assert.True(executable.Length > 260); - var runner = new ToolRunner(new Dictionary { [BgfxTool.Shaderc] = executable }, - directory, new WindowsToolchainWorkspaceProvider()); + var runner = new ToolRunner( + new Dictionary { [BgfxTool.Shaderc] = executable }, + directory, + new WindowsToolchainWorkspaceProvider() + ); ToolRunResult result = await runner.RunAsync(BgfxTool.Shaderc, ["/c", "exit", "0"], root); Assert.True(result.exitCode == 0, $"exit={result.exitCode}; stdout={result.standardOutput}; stderr={result.standardError}"); Assert.True(File.Exists(executable)); diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs index d11284cb6..156740122 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs @@ -40,7 +40,9 @@ public async Task BoundedExecutionRetainsFilesAndStableIdentityAcrossOwners() next.Dispose(); next.Dispose(); if (OperatingSystem.IsWindows()) + { Assert.False(Directory.Exists(execution)); + } } [Fact] @@ -50,7 +52,7 @@ public async Task OpeningExistingToolOutputsPreservesThePublishedArtifactFileSet string outputs = Path.Combine(artifact, "Outputs"); Directory.CreateDirectory(outputs); File.WriteAllText(Path.Combine(outputs, "tool.bin"), "immutable"); - string fingerprint = new('c', 64); + var fingerprint = new string('c', 64); BuildArtifactManifest.Write(artifact, fingerprint, ["Outputs"]); Assert.True(BuildArtifactManifest.IsComplete(artifact, fingerprint, ["Outputs"])); using (ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(outputs)) @@ -72,7 +74,7 @@ await Assert.ThrowsAsync(async () => } string physical = Path.Combine(m_root, "Owned"); using ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(physical); - using CancellationTokenSource cancellation = new(TimeSpan.FromMilliseconds(150)); + using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(150)); await Assert.ThrowsAnyAsync(async () => await new WindowsToolchainWorkspaceProvider().OpenAsync(physical, cancellation.Token)); Assert.True(Directory.Exists(owner.toolPath)); @@ -85,16 +87,19 @@ await Assert.ThrowsAnyAsync(async () => public async Task OccupiedAliasFailsWithoutRemovingTheOccupantAndReleasesOwnership() { if (!OperatingSystem.IsWindows()) + { return; + } string physical = Path.Combine(m_root, "Occupied"); string alias; using (ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(physical)) + { alias = owner.toolPath; + } Directory.CreateDirectory(alias); try { - await Assert.ThrowsAsync(async () => - await CreateProvider().OpenAsync(physical)); + await Assert.ThrowsAsync(async () => await CreateProvider().OpenAsync(physical)); Assert.Null(new DirectoryInfo(alias).LinkTarget); } finally @@ -120,12 +125,16 @@ public async Task PhysicalProviderPreservesTheExactOwnerPath() Assert.Equal("retained", File.ReadAllText(Path.Combine(physical, "output.txt"))); } - private static IToolchainWorkspaceProvider CreateProvider() => OperatingSystem.IsWindows() - ? new WindowsToolchainWorkspaceProvider() : new PhysicalToolchainWorkspaceProvider(); - public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } + + private static IToolchainWorkspaceProvider CreateProvider() + => OperatingSystem.IsWindows() + ? new WindowsToolchainWorkspaceProvider() + : new PhysicalToolchainWorkspaceProvider(); } diff --git a/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs b/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs new file mode 100644 index 000000000..9b3c079e7 --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Plugins.Authoring.Tests; + +[StableTypeID("706c1248-478b-43f1-a44d-98a1a8f7b919")] +[ProjectSettingDefinition("tests.plugins.default")] +internal sealed class PluginDefaultTestSetting : ISerializable +{ + [SerializableProperty] + public int value { get; set; } = 1; + + internal static ProjectSettingID id => new("tests.plugins.default"); +} diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs new file mode 100644 index 000000000..a8de2d9fe --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Plugins.Authoring.Tests; + +[CollectionDefinition("Plugin source serialization", DisableParallelization = true)] +public sealed class PluginSourceSerializationCollection; diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs index e65a36668..efcd0b6ab 100644 --- a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs @@ -1,26 +1,25 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Plugins; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Plugins.Authoring.Tests; @@ -52,15 +51,18 @@ public PluginSourceServiceTests() _ = typeof(TextAsset); _ = typeof(PluginSourceService); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(PluginSourceServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(PluginSourceServiceTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(m_root, "Settings.Project.inno"))), m_types, m_serialization, - new ProjectId("tests.plugins"), - SerializationContext.empty); + new ProjectID("tests.plugins"), + SerializationContext.empty + ); } public void Dispose() @@ -74,7 +76,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -85,10 +89,10 @@ public void CorruptedMaterializedCacheIsRejectedAndCanBeRebuiltWithoutChangingPa PluginScanResult first = service.Scan(); PluginCandidate candidate = Assert.Single(first.candidates); string cachedFile = Directory.EnumerateFiles(candidate.sourceMount.rootPath, "*.txt", SearchOption.AllDirectories).Single(); - byte[] original = System.IO.File.ReadAllBytes(cachedFile); + byte[] original = File.ReadAllBytes(cachedFile); byte[] changed = original.ToArray(); changed[0] ^= 1; - System.IO.File.WriteAllBytes(cachedFile, changed); + File.WriteAllBytes(cachedFile, changed); PluginScanResult corrupted = service.Scan(); Assert.Empty(corrupted.candidates); Assert.Contains("invalid bytes", Assert.Single(corrupted.diagnostics).message); @@ -96,7 +100,7 @@ public void CorruptedMaterializedCacheIsRejectedAndCanBeRebuiltWithoutChangingPa PluginScanResult restored = service.Scan(); Assert.Empty(restored.diagnostics); Assert.Equal(candidate.contentHash, Assert.Single(restored.candidates).contentHash); - Assert.Equal(original, System.IO.File.ReadAllBytes(cachedFile)); + Assert.Equal(original, File.ReadAllBytes(cachedFile)); } [Fact] @@ -151,41 +155,36 @@ public void CodePluginActivatesImmediatelyAfterValidation() PluginCandidate active = Assert.Single(PluginSourceService.GetActivatableCandidates(scan)); Assert.True(active.sourceMount.isReadOnly); Assert.Equal("tests.code", active.sourceMount.id.value); - Assert.True(System.IO.File.Exists(Path.Combine(active.sourceMount.rootPath, "Plugin.cs"))); + Assert.True(File.Exists(Path.Combine(active.sourceMount.rootPath, "Plugin.cs"))); } [Fact] public void FolderPluginIsRejectedAsANonPackageInstallation() { - WriteDirectoryPlugin( - "InstalledPlugin", - Manifest("tests.directory"), - TextContent("content")); + WriteDirectoryPlugin("InstalledPlugin", Manifest("tests.directory"), TextContent("content")); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult scan = service.Scan(); Assert.Empty(scan.candidates); PluginDiagnostic diagnostic = Assert.Single(scan.diagnostics); - Assert.Contains( - ".iplugin package", - diagnostic.message, - StringComparison.OrdinalIgnoreCase); + Assert.Contains(".iplugin package", diagnostic.message, StringComparison.OrdinalIgnoreCase); } [Fact] public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemovalCommits() { - const string c_fileName = "active-code.iplugin"; - string sourcePath = Path.Combine(m_plugins, c_fileName); + const string C_FILE_NAME = "active-code.iplugin"; + string sourcePath = Path.Combine(m_plugins, C_FILE_NAME); WritePlugin( - c_fileName, + C_FILE_NAME, Manifest("tests.removed-package"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class RemovedPackageEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult initial = service.Scan(); InitializeProjectAssets(); @@ -193,7 +192,7 @@ public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemova PluginCandidate active = Assert.Single(m_environment!.activePlugins); string activeSnapshotRoot = active.sourceMount.rootPath; - System.IO.File.Delete(sourcePath); + File.Delete(sourcePath); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -214,30 +213,29 @@ public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemova m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); } [Fact] public void StructurallyInvalidActivePluginStagesAnUnavailableGeneration() { - const string c_fileName = "invalidated-code.iplugin"; - string sourcePath = Path.Combine(m_plugins, c_fileName); + const string C_FILE_NAME = "invalidated-code.iplugin"; + string sourcePath = Path.Combine(m_plugins, C_FILE_NAME); WritePlugin( - c_fileName, + C_FILE_NAME, Manifest("tests.invalidated-package"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class InvalidatedPackageEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); InitializeProjectAssets(); StartEnvironment(service.Scan()); Assert.Single(m_environment!.activePlugins); - System.IO.File.WriteAllBytes(sourcePath, [0x49, 0x4E, 0x4E, 0x4F]); + File.WriteAllBytes(sourcePath, [0x49, 0x4E, 0x4E, 0x4F]); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -252,36 +250,36 @@ public void StructurallyInvalidActivePluginStagesAnUnavailableGeneration() m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); } [Fact] public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowing() { - const string c_fileName = "invalid-asset-metadata.iplugin"; + const string C_FILE_NAME = "invalid-asset-metadata.iplugin"; WritePlugin( - c_fileName, + C_FILE_NAME, Manifest("tests.invalid-asset-metadata"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class InvalidAssetMetadataEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); InitializeProjectAssets(); StartEnvironment(service.Scan()); Assert.Single(m_environment!.activePlugins); WritePlugin( - c_fileName, + C_FILE_NAME, Manifest("tests.invalid-asset-metadata"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class InvalidAssetMetadataEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = [1] - }); + } + ); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -296,25 +294,23 @@ public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowi m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); } [Fact] public void OperatingSystemMetadataBesidePackageDoesNotAffectIdentity() { WritePlugin("metadata.iplugin", Manifest("tests.package-metadata"), TextContent("content")); - System.IO.File.WriteAllBytes(Path.Combine(m_plugins, ".DS_Store"), [1, 2, 3]); - System.IO.File.WriteAllBytes(Path.Combine(m_plugins, "Thumbs.db"), [4, 5, 6]); + File.WriteAllBytes(Path.Combine(m_plugins, ".DS_Store"), [1, 2, 3]); + File.WriteAllBytes(Path.Combine(m_plugins, "Thumbs.db"), [4, 5, 6]); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult withMetadata = service.Scan(); Assert.Empty(withMetadata.diagnostics); string contentHash = Assert.Single(withMetadata.candidates).contentHash; - System.IO.File.Delete(Path.Combine(m_plugins, ".DS_Store")); - System.IO.File.Delete(Path.Combine(m_plugins, "Thumbs.db")); + File.Delete(Path.Combine(m_plugins, ".DS_Store")); + File.Delete(Path.Combine(m_plugins, "Thumbs.db")); PluginScanResult withoutMetadata = service.Scan(); Assert.Empty(withoutMetadata.diagnostics); Assert.Equal(contentHash, Assert.Single(withoutMetadata.candidates).contentHash); @@ -334,7 +330,7 @@ public void OperatingSystemMetadataInsidePackageDoesNotInvalidateOrChangeIdentit Assert.Empty(withMetadata.diagnostics); string contentHash = Assert.Single(withMetadata.candidates).contentHash; - System.IO.File.Delete(Path.Combine(m_plugins, "metadata.iplugin")); + File.Delete(Path.Combine(m_plugins, "metadata.iplugin")); WritePlugin("metadata.iplugin", manifest, TextContent("content")); PluginScanResult withoutMetadata = service.Scan(); Assert.Empty(withoutMetadata.diagnostics); @@ -352,10 +348,7 @@ public void FolderManifestCannotConflictWithAValidPackageIdentity() Assert.Equal("tests.same-source-id", Assert.Single(result.candidates).manifest.pluginId); PluginDiagnostic diagnostic = Assert.Single(result.diagnostics); - Assert.Contains( - ".iplugin package", - diagnostic.message, - StringComparison.OrdinalIgnoreCase); + Assert.Contains(".iplugin package", diagnostic.message, StringComparison.OrdinalIgnoreCase); } [Fact] @@ -381,8 +374,10 @@ public void DependencyGraphUsesDeterministicTopologicalOrderAndRejectsCycles() [InlineData("../escape.txt", "non-portable segment")] [InlineData("Assets/missing.txt", "missing its required .imeta sidecar")] [InlineData("Assets/native.dll", "forbidden prebuilt binary")] - public void UnsafeOrIncompleteArchivesAreIsolatedAsDiagnostics(string entryPath, string expectedMessage) - { + public void UnsafeOrIncompleteArchivesAreIsolatedAsDiagnostics( + string entryPath, + string expectedMessage + ) { Dictionary entries = TextContent("safe"); entries.Remove("Assets/content.txt"); entries.Remove("Assets/content.txt.imeta"); @@ -421,8 +416,8 @@ public void PortableCaseCollisionsAreRejectedBeforeExtraction() [InlineData("Assets/e\u0301.txt", "Unicode-normalized")] public void PlatformSpecificAndNonNormalizedPathsAreRejected( string entryPath, - string expectedMessage) - { + string expectedMessage + ) { WritePlugin("portable.iplugin", Manifest("tests.portable"), new Dictionary { [entryPath] = [1], @@ -440,12 +435,12 @@ public void PlatformSpecificAndNonNormalizedPathsAreRejected( public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() { string symbolicLinkPath = Path.Combine(m_plugins, "symbolic-link.iplugin"); - using (FileStream stream = System.IO.File.Create(symbolicLinkPath)) + using (FileStream stream = File.Create(symbolicLinkPath)) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create)) { WriteEntry(archive, "Plugin.inno", m_serialization.Serialize(Manifest("tests.symbolic-link"))); ZipArchiveEntry link = archive.CreateEntry("Assets/link.txt"); - link.ExternalAttributes = unchecked((int)0xA1FF0000); + link.ExternalAttributes = unchecked((int)0xA1FF_0000); WriteEntry(archive, "Assets/link.txt.imeta", [1]); } @@ -455,13 +450,14 @@ public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() Assert.Empty(symbolicLink.candidates); Assert.Contains("symbolic link", Assert.Single(symbolicLink.diagnostics).message, StringComparison.OrdinalIgnoreCase); - System.IO.File.Delete(symbolicLinkPath); + File.Delete(symbolicLinkPath); WritePlugin("entry-count.iplugin", Manifest("tests.entry-count"), TextContent("bounded")); var entryCountService = new PluginSourceService( m_serialization, m_plugins, m_library, - new PluginSourceLimits { maximumEntryCount = 2 }); + new PluginSourceLimits { maximumEntryCount = 2 } + ); PluginScanResult entryCount = entryCountService.Scan(); @@ -473,10 +469,12 @@ public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() [InlineData("file", "file-size limit")] [InlineData("total", "total uncompressed-size limit")] [InlineData("ratio", "compression-ratio limit")] - public void ArchiveLimitsRejectOversizedOrSuspiciousContent(string scenario, string expectedMessage) - { + public void ArchiveLimitsRejectOversizedOrSuspiciousContent( + string scenario, + string expectedMessage + ) { byte[] first = scenario == "ratio" ? new byte[4096] : CreateNoise(1024, seed: 17); - Dictionary entries = new() + var entries = new Dictionary() { ["Assets/first.data"] = first, ["Assets/first.data.imeta"] = [1] @@ -520,10 +518,7 @@ public void ArchiveLimitsRejectOversizedOrSuspiciousContent(string scenario, str [Fact] public void CorruptManifestAndDuplicateEntriesAreIsolated() { - WritePluginWithManifestBytes( - "corrupt.iplugin", - [0x49, 0x4E, 0x4E, 0x4F], - TextContent("corrupt")); + WritePluginWithManifestBytes("corrupt.iplugin", [0x49, 0x4E, 0x4E, 0x4F], TextContent("corrupt")); WriteArchiveWithDuplicateEntry("duplicate.iplugin"); var service = new PluginSourceService(m_serialization, m_plugins, m_library); @@ -536,7 +531,7 @@ public void CorruptManifestAndDuplicateEntriesAreIsolated() } [Fact] - public void MissingDependenciesDuplicateIdsAndInvalidOverridesRejectTheCandidateGeneration() + public void MissingDependenciesDuplicateIDsAndInvalidOverridesRejectTheCandidateGeneration() { WritePlugin("missing.iplugin", Manifest("tests.missing", "tests.absent"), TextContent("missing")); WritePlugin("duplicate-a.iplugin", Manifest("tests.duplicate"), TextContent("first")); @@ -563,16 +558,18 @@ public void SettingsCompositionRejectsPeersAllowsExplicitDependencyOverrideAndKe ProjectSettingRecord first = SettingRecord(10); ProjectSettingRecord second = SettingRecord(20); m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [first]) - ]); + [ + new ProjectSettingsContributor("tests.first", [], [], [first]) + ] + ); Assert.Equal(10, m_settings.Get(PluginDefaultTestSetting.id).value); Assert.Throws(() => m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [first]), - new ProjectSettingsContributor("tests.peer", [], [], [second]) - ])); + [ + new ProjectSettingsContributor("tests.first", [], [], [first]), + new ProjectSettingsContributor("tests.peer", [], [], [second]) + ] + )); Assert.Equal(10, m_settings.Get(PluginDefaultTestSetting.id).value); ProjectSettingsContributor[] overridden = @@ -586,11 +583,13 @@ public void SettingsCompositionRejectsPeersAllowsExplicitDependencyOverrideAndKe m_settings.SetProjectOverride( PluginDefaultTestSetting.id, new PluginDefaultTestSetting { value = 30 }, - overridden); + overridden + ); m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [SettingRecord(40)]) - ]); + [ + new ProjectSettingsContributor("tests.first", [], [], [SettingRecord(40)]) + ] + ); Assert.Equal(30, m_settings.Get(PluginDefaultTestSetting.id).value); } @@ -612,9 +611,7 @@ public void InitialActivationFailureKeepsTheHostOnlyMountAndPublishesDiscoveryDi Assert.Single(m_environment!.discovery.candidates); Assert.Contains(m_environment!.discovery.diagnostics, diagnostic => diagnostic.message.Contains("candidate activation failed", StringComparison.OrdinalIgnoreCase)); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); } [Fact] @@ -626,8 +623,9 @@ public void InitialActivationPublishesPluginSettingDefaultsWithoutAnEditorFronte [ new ProjectSettingRecord( PluginDefaultTestSetting.id, - m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableId, - m_serialization.CapturePropertiesData(contributed)) + m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableID, + m_serialization.CapturePropertiesData(contributed) + ) ]; WritePlugin("settings.iplugin", manifest, new Dictionary { @@ -642,13 +640,14 @@ public void InitialActivationPublishesPluginSettingDefaultsWithoutAnEditorFronte Assert.Equal("tests.settings", Assert.Single(m_environment!.activePlugins).manifest.pluginId); Assert.Equal( - [AssetSourceId.project, new AssetSourceId("tests.settings")], - m_assets!.sourceMounts.Select(static mount => mount.id)); + [AssetSourceID.project, new AssetSourceID("tests.settings")], + m_assets!.sourceMounts.Select(static mount => mount.id) + ); Assert.Equal(42, m_settings.Get(PluginDefaultTestSetting.id).value); } [Fact] - public void CodePluginUpdate_RemainsInvisibleWhileItsCompilationCandidateIsPending() + public void CodePluginUpdateRemainsInvisibleWhileItsCompilationCandidateIsPending() { InitializeProjectAssets(); var service = new PluginSourceService(m_serialization, m_plugins, m_library); @@ -663,23 +662,18 @@ public void CodePluginUpdate_RemainsInvisibleWhileItsCompilationCandidateIsPendi Assert.True(m_environment!.hasPendingActivation); Assert.Empty(m_environment!.activePlugins); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); - Assert.Equal( - "tests.staged-code", - Assert.Single(m_environment!.compilationPlugins).manifest.pluginId); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); + Assert.Equal("tests.staged-code", Assert.Single(m_environment!.compilationPlugins).manifest.pluginId); Assert.Contains( m_environment!.compilationAssets!.GetFileSystemEntries(includeDirectories: false), - entry => entry.assetPath == new AssetPath(new AssetSourceId("tests.staged-code"), "Plugin.cs")); + entry => entry.assetPath == new AssetPath(new AssetSourceID("tests.staged-code"), "Plugin.cs") + ); m_environment!.RollbackPending(); Assert.False(m_environment!.hasPendingActivation); Assert.Empty(m_environment!.activePlugins); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceID.project, mount.id)); } [Theory] @@ -701,9 +695,9 @@ public void CandidateObserverPendingKeepsTheCandidateAndStopsLaterObservers(bool Action first = () => throw ordinary; Action blocked = () => throw pending; Action later = () => laterCalled = true; - if (earlierFailure) m_environment!.ActivationCandidateChanged += first; - m_environment!.ActivationCandidateChanged += blocked; - m_environment.ActivationCandidateChanged += later; + if (earlierFailure) m_environment!.activationCandidateChanged += first; + m_environment!.activationCandidateChanged += blocked; + m_environment.activationCandidateChanged += later; try { AggregateException failure = Assert.Throws(() => m_environment.Refresh()); @@ -712,7 +706,10 @@ public void CandidateObserverPendingKeepsTheCandidateAndStopsLaterObservers(bool Assert.Contains(ordinary, failure.InnerExceptions); Assert.Contains(pending, failure.InnerExceptions); } - else Assert.Same(pending, failure); + else + { + Assert.Same(pending, failure); + } Assert.False(laterCalled); Assert.True(m_environment.hasPendingActivation); Assert.NotNull(m_environment.compilationAssets); @@ -722,9 +719,9 @@ public void CandidateObserverPendingKeepsTheCandidateAndStopsLaterObservers(bool finally { // The simulated observer has quiesced; explicitly retire the retained candidate. - m_environment.ActivationCandidateChanged -= first; - m_environment.ActivationCandidateChanged -= blocked; - m_environment.ActivationCandidateChanged -= later; + m_environment.activationCandidateChanged -= first; + m_environment.activationCandidateChanged -= blocked; + m_environment.activationCandidateChanged -= later; m_environment.RollbackPending(); } Assert.False(m_environment.hasPendingActivation); @@ -744,12 +741,15 @@ public void RollbackObserverPendingKeepsTheOwnerUntilAllRollbackStagesComplete() Assert.True(m_environment!.Refresh()); m_environment.ActivatePending(); AssetSourceMountTransaction candidate = m_environment.compilationAssets!; - var failure = new InvalidOperationException("observer context", new RetirementPendingException("rollback work")); + var failure = new InvalidOperationException( + "observer context", + new RetirementPendingException("rollback work") + ); bool laterCalled = false; Action blocked = () => throw failure; Action later = () => laterCalled = true; - m_environment.Changed += blocked; - m_environment.Changed += later; + m_environment.changed += blocked; + m_environment.changed += later; try { Assert.Same(failure, Assert.Throws(m_environment.RollbackPending)); @@ -759,8 +759,8 @@ public void RollbackObserverPendingKeepsTheOwnerUntilAllRollbackStagesComplete() } finally { - m_environment.Changed -= blocked; - m_environment.Changed -= later; + m_environment.changed -= blocked; + m_environment.changed -= later; m_environment.RollbackPending(); } Assert.False(m_environment.hasPendingActivation); @@ -769,10 +769,10 @@ public void RollbackObserverPendingKeepsTheOwnerUntilAllRollbackStagesComplete() } [Fact] - public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() + public void SourceMountCandidateTransfersLiveIdentitiesOnlyDuringActivation() { - const string c_fileName = "identity-handoff.iplugin"; - WritePlugin(c_fileName, Manifest("tests.identity-handoff"), new Dictionary + const string C_FILE_NAME = "identity-handoff.iplugin"; + WritePlugin(C_FILE_NAME, Manifest("tests.identity-handoff"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class IdentityHandoffV1 { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() @@ -780,12 +780,10 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() InitializeProjectAssets(); var service = new PluginSourceService(m_serialization, m_plugins, m_library); StartEnvironment(service.Scan()); - Assert.True(m_assets!.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry activeEntry)); + Assert.True(m_assets!.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry activeEntry)); Assert.NotNull(activeEntry.identity.runtimeIdentity); - WritePlugin(c_fileName, Manifest("tests.identity-handoff"), new Dictionary + WritePlugin(C_FILE_NAME, Manifest("tests.identity-handoff"), new Dictionary { ["Assets/Plugin.cs"] = "public sealed class IdentityHandoffV2 { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() @@ -793,30 +791,28 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() Assert.True(m_environment!.Refresh()); AssetSourceMountTransaction candidate = Assert.IsType( - m_environment.compilationAssets); + m_environment.compilationAssets + ); AssetFileEntry candidateEntry = Assert.Single( candidate.GetFileSystemEntries(), - static entry => entry.assetPath == AssetPath.Project(string.Empty)); - Assert.Equal(activeEntry.identity.persistentId, candidateEntry.identity.persistentId); + static entry => entry.assetPath == AssetPath.Project(string.Empty) + ); + Assert.Equal(activeEntry.identity.persistentID, candidateEntry.identity.persistentID); Assert.NotNull(activeEntry.identity.runtimeIdentity); Assert.Null(candidateEntry.identity.runtimeIdentity); m_environment.ActivatePending(); Assert.Null(activeEntry.identity.runtimeIdentity); - Assert.True(m_assets.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry activatedEntry)); - Assert.Equal(activeEntry.identity.persistentId, activatedEntry.identity.persistentId); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry activatedEntry)); + Assert.Equal(activeEntry.identity.persistentID, activatedEntry.identity.persistentID); Assert.NotNull(activatedEntry.identity.runtimeIdentity); m_environment.RollbackPending(); Assert.NotNull(activeEntry.identity.runtimeIdentity); Assert.Null(activatedEntry.identity.runtimeIdentity); - Assert.True(m_assets.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry restoredEntry)); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry restoredEntry)); Assert.Same(activeEntry, restoredEntry); } @@ -841,30 +837,17 @@ public void SourceWatcherDebouncesChangesAndActivatesOnTheOwnerThread() Assert.Equal("tests.watched", Assert.Single(m_environment.activePlugins).manifest.pluginId); Assert.Equal( - [AssetSourceId.project, new AssetSourceId("tests.watched")], - m_assets!.sourceMounts.Select(static mount => mount.id)); + [AssetSourceID.project, new AssetSourceID("tests.watched")], + m_assets!.sourceMounts.Select(static mount => mount.id) + ); } - private static PluginManifest Manifest(string id, params string[] dependencies) - => new() - { - pluginId = id, - displayName = id, - dependencies = dependencies - }; - - private static Dictionary TextContent(string value) - => new() - { - ["Assets/content.txt"] = System.Text.Encoding.UTF8.GetBytes(value), - ["Assets/content.txt.imeta"] = [1] - }; - private ProjectSettingRecord SettingRecord(int value) => new( PluginDefaultTestSetting.id, - m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableId, - m_serialization.CapturePropertiesData(new PluginDefaultTestSetting { value = value })); + m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableID, + m_serialization.CapturePropertiesData(new PluginDefaultTestSetting { value = value }) + ); private PluginManifest ReadManifest(ZipArchive archive) { @@ -877,46 +860,44 @@ private PluginManifest ReadManifest(ZipArchive archive) private void WritePlugin( string fileName, PluginManifest manifest, - IReadOnlyDictionary entries) - => WritePluginWithManifestBytes(fileName, m_serialization.Serialize(manifest), entries); + IReadOnlyDictionary entries + ) => WritePluginWithManifestBytes(fileName, m_serialization.Serialize(manifest), entries); private void WritePluginWithManifestBytes( string fileName, byte[] manifestBytes, - IReadOnlyDictionary entries) - { + IReadOnlyDictionary entries + ) { string path = Path.Combine(m_plugins, fileName); - using FileStream stream = System.IO.File.Create(path); + using FileStream stream = File.Create(path); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WriteEntry(archive, "Plugin.inno", manifestBytes); foreach ((string entryPath, byte[] bytes) in entries) + { WriteEntry(archive, entryPath, bytes); + } } private void WriteDirectoryPlugin( string directoryName, PluginManifest manifest, - IReadOnlyDictionary entries) - { + IReadOnlyDictionary entries + ) { string root = Path.Combine(m_plugins, directoryName); Directory.CreateDirectory(root); - System.IO.File.WriteAllBytes( - Path.Combine(root, "Plugin.inno"), - m_serialization.Serialize(manifest)); + File.WriteAllBytes(Path.Combine(root, "Plugin.inno"), m_serialization.Serialize(manifest)); foreach ((string entryPath, byte[] bytes) in entries) { - string physicalPath = Path.Combine( - root, - entryPath.Replace('/', Path.DirectorySeparatorChar)); + string physicalPath = Path.Combine(root, entryPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(physicalPath)!); - System.IO.File.WriteAllBytes(physicalPath, bytes); + File.WriteAllBytes(physicalPath, bytes); } } private void WriteArchiveWithDuplicateEntry(string fileName) { string path = Path.Combine(m_plugins, fileName); - using FileStream stream = System.IO.File.Create(path); + using FileStream stream = File.Create(path); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WriteEntry(archive, "Plugin.inno", m_serialization.Serialize(Manifest("tests.duplicate-entry"))); WriteEntry(archive, "Assets/value.txt", [1]); @@ -924,13 +905,6 @@ private void WriteArchiveWithDuplicateEntry(string fileName) WriteEntry(archive, "Assets/value.txt.imeta", [1]); } - private static byte[] CreateNoise(int length, int seed) - { - var result = new byte[length]; - new Random(seed).NextBytes(result); - return result; - } - private void InitializeProjectAssets() { string assets = Path.Combine(m_root, "RuntimeProject", "Assets"); @@ -947,20 +921,20 @@ private void InitializeProjectAssets() defaults with { enableFileSystemWatcher = false - }); + } + ); } private void StartEnvironment(PluginScanResult scan) - { - m_environment = new PluginEnvironment( + => m_environment = new PluginEnvironment( m_assets ?? throw new InvalidOperationException("Project assets must be initialized first."), m_settings, m_serialization, m_plugins, m_library, scan, - m_modules.generations); - } + m_modules.generations + ); private byte[] CreateTextSourceMeta() => m_serialization.Serialize(new TestAssetSourceMeta @@ -970,40 +944,39 @@ private byte[] CreateTextSourceMeta() importerId = "inno.assets.text" }); - private static void WriteEntry(ZipArchive archive, string path, byte[] bytes) + private static PluginManifest Manifest( + string id, + params string[] dependencies + ) => new() + { + pluginId = id, + displayName = id, + dependencies = dependencies + }; + + private static Dictionary TextContent(string value) + => new() { + ["Assets/content.txt"] = Encoding.UTF8.GetBytes(value), + ["Assets/content.txt.imeta"] = [1] + }; + + private static byte[] CreateNoise( + int length, + int seed + ) { + var result = new byte[length]; + new Random(seed).NextBytes(result); + return result; + } + + private static void WriteEntry( + ZipArchive archive, + string path, + byte[] bytes + ) { ZipArchiveEntry entry = archive.CreateEntry(path, CompressionLevel.Optimal); using Stream output = entry.Open(); output.Write(bytes); } } - -[CollectionDefinition("Plugin source serialization", DisableParallelization = true)] -public sealed class PluginSourceSerializationCollection -{ -} - -[StableTypeId("706c1248-478b-43f1-a44d-98a1a8f7b919")] -[ProjectSettingDefinition("tests.plugins.default")] -internal sealed class PluginDefaultTestSetting : ISerializable -{ - internal static ProjectSettingId id => new("tests.plugins.default"); - - [SerializableProperty] - public int value { get; set; } = 1; -} - -internal sealed class TestAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} diff --git a/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs b/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs new file mode 100644 index 000000000..ec2c97e6a --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Plugins.Authoring.Tests; + +internal sealed class TestAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs index ac58d0f93..7869f22e0 100644 --- a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs +++ b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs @@ -16,36 +16,41 @@ namespace Inno.Testing.Discovery; [FriendlyName("InnoDiscovery")] public sealed class DiscoveryLogger : ITestLoggerWithParameters { - /// /// /// The logger requires the parameterized overload with an explicit receipt path. /// + /// public void Initialize( TestLoggerEvents events, string testRunDirectory - ) => - throw new ArgumentException("Discovery requires an explicit receipt path."); + ) => throw new ArgumentException("Discovery requires an explicit receipt path."); - /// /// /// The Receipt parameter is missing or does not identify an absolute output path. /// + /// public void Initialize( TestLoggerEvents events, Dictionary parameters ) { if (!parameters.TryGetValue("Receipt", out string? receipt) || !Path.IsPathFullyQualified(receipt ?? string.Empty)) + { throw new ArgumentException("Discovery requires an absolute receipt path."); + } - var owners = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); - var errors = new List(); + var owners = new Dictionary( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal + ); + List errors = []; events.DiscoveryMessage += ( _, message ) => { if (message.Level == TestMessageLevel.Error) + { errors.Add(message.Message ?? "Discovery emitted an unspecified error."); + } }; events.DiscoveredTests += ( _, @@ -56,10 +61,14 @@ public void Initialize( { string source = Path.GetFullPath(test.Source); if (!owners.TryGetValue(source, out Owner? owner)) + { owners.Add(source, owner = new Owner()); - owner.Count++; + } + owner.count++; if (test.Traits.Any(trait => trait.Name == "ProcessIsolation" && trait.Value == "Required")) - owner.Contracts.Add(test.FullyQualifiedName); + { + owner.contracts.Add(test.FullyQualifiedName); + } } }; events.DiscoveryComplete += ( @@ -67,23 +76,23 @@ public void Initialize( completion ) => { - using FileStream output = new(receipt!, FileMode.CreateNew, FileAccess.Write, FileShare.None); + using var output = new FileStream(receipt!, FileMode.CreateNew, FileAccess.Write, FileShare.None); JsonSerializer.Serialize(output, new { completed = !completion.IsAborted && errors.Count == 0 - && completion.PartiallyDiscoveredSources?.Count is null or 0 - && completion.NotDiscoveredSources?.Count is null or 0 - && completion.SkippedDiscoveredSources?.Count is null or 0, + && completion.PartiallyDiscoveredSources?.Count is null or 0 + && completion.NotDiscoveredSources?.Count is null or 0 + && completion.SkippedDiscoveredSources?.Count is null or 0, errors, discovered = completion.TotalCount, - owners = owners.Select(pair => new { source = pair.Key, count = pair.Value.Count, contracts = pair.Value.Contracts }) + owners = owners.Select(pair => new { source = pair.Key, count = pair.Value.count, contracts = pair.Value.contracts }) }); }; } private sealed class Owner { - internal int Count { get; set; } - internal SortedSet Contracts { get; } = new(StringComparer.Ordinal); + internal int count { get; set; } + internal SortedSet contracts { get; } = new(StringComparer.Ordinal); } } diff --git a/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs b/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs index f4f622b02..66d87deea 100644 --- a/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs +++ b/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs @@ -9,13 +9,19 @@ internal static class NativeProcessHostFixture private static int Main(string[] arguments) { if (arguments.Length != 1) + { return 2; + } Console.WriteLine("Fixture stdout: " + arguments[0]); Console.Error.WriteLine("Fixture stderr: " + arguments[0]); if (arguments[0] == "success") + { return 0; + } if (arguments[0] == "failure") + { return 3; + } if (arguments[0] == "timeout") { var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") diff --git a/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs b/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs index a60d9d092..fb7837c6c 100644 --- a/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs +++ b/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs @@ -9,7 +9,10 @@ namespace Inno.Testing.Processes.Tests; public sealed class NativeProcessTestHostTests { [Fact] - public void SuccessfulContractDrainsItsOutput() => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success"); + public void SuccessfulContractDrainsItsOutput() => NativeProcessTestHost.Run( + typeof(NativeProcessHostFixture).Assembly.Location, + "success" + ); [Fact] public void FailedContractRetainsBothStreamsAndIdentity() @@ -29,27 +32,29 @@ public void TimeoutRetainsPartialOutputAndTerminatesDescendants() NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "timeout", 3_000)); Assert.Contains("Fixture stdout: timeout", failure.Message); Assert.Contains("Fixture stderr: timeout", failure.Message); - const string childPrefix = "Child PID: "; - int start = failure.Message.IndexOf(childPrefix, StringComparison.Ordinal); + const string C_CHILD_PREFIX = "Child PID: "; + int start = failure.Message.IndexOf(C_CHILD_PREFIX, StringComparison.Ordinal); Assert.True(start >= 0, failure.Message); - ReadOnlySpan identifier = failure.Message.AsSpan(start + childPrefix.Length); + ReadOnlySpan identifier = failure.Message.AsSpan(start + C_CHILD_PREFIX.Length); int end = identifier.IndexOfAny('\r', '\n'); - int childId = int.Parse(end < 0 ? identifier : identifier[..end], CultureInfo.InvariantCulture); - Assert.True(SpinWait.SpinUntil(() => HasExited(childId), TimeSpan.FromSeconds(5)), failure.Message); + int childID = int.Parse(end < 0 ? identifier : identifier[..end], CultureInfo.InvariantCulture); + Assert.True(SpinWait.SpinUntil(() => HasExited(childID), TimeSpan.FromSeconds(5)), failure.Message); } [Fact] public void RelativeAssemblyAndInvalidBudgetFailBeforeStarting() { Assert.Throws(() => NativeProcessTestHost.Run("relative.dll", "success")); - Assert.Throws(() => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success", 0)); + Assert.Throws( + () => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success", 0) + ); } - private static bool HasExited(int processId) + private static bool HasExited(int processID) { try { - using Process child = Process.GetProcessById(processId); + using Process child = Process.GetProcessById(processID); return child.HasExited; } catch (ArgumentException) diff --git a/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs b/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs index 9de53e682..4c797d627 100644 --- a/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs +++ b/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs @@ -44,7 +44,9 @@ public static void Run( ArgumentException.ThrowIfNullOrWhiteSpace(contract); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(timeoutMilliseconds); if (!Path.IsPathFullyQualified(assembly)) + { throw new ArgumentException("A contract assembly requires an absolute path.", nameof(assembly)); + } var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { UseShellExecute = false, @@ -69,7 +71,9 @@ public static void Run( ) => Capture(data, error, errorClosed); Stopwatch elapsed = Stopwatch.StartNew(); if (!process.Start()) + { throw new InvalidOperationException("The native contract host did not start."); + } process.BeginOutputReadLine(); process.BeginErrorReadLine(); bool timedOut = !process.WaitForExit(timeoutMilliseconds); @@ -80,7 +84,9 @@ public static void Run( { process.Kill(entireProcessTree: true); if (!process.WaitForExit(10_000)) + { cleanup = "The process tree did not exit within the cleanup budget."; + } } catch (Exception failure) { @@ -91,12 +97,14 @@ public static void Run( if (timedOut || !drained || process.ExitCode != 0) { string diagnostic = $"Native contract '{contract}', PID {process.Id}, elapsed {elapsed.Elapsed}.\n" - + $"Command: {start.FileName} {assembly} {contract}\n" - + $"TimedOut={timedOut}; OutputDrained={drained}. {cleanup}\n" - + "stdout:\n" + string.Join(Environment.NewLine, output) - + "\nstderr:\n" + string.Join(Environment.NewLine, error); + + $"Command: {start.FileName} {assembly} {contract}\n" + + $"TimedOut={timedOut}; OutputDrained={drained}. {cleanup}\n" + + "stdout:\n" + string.Join(Environment.NewLine, output) + + "\nstderr:\n" + string.Join(Environment.NewLine, error); if (timedOut) + { throw new TimeoutException(diagnostic); + } throw new InvalidOperationException(diagnostic); } } @@ -107,8 +115,12 @@ private static void Capture( TaskCompletionSource closed ) { if (data.Data is string line) + { destination.Enqueue(line); + } else + { closed.TrySetResult(); + } } } diff --git a/tests/references/Inno.References.Tests/ContentReadScopeTests.cs b/tests/references/Inno.References.Tests/ContentReadScopeTests.cs index cbb6310e0..0a7807315 100644 --- a/tests/references/Inno.References.Tests/ContentReadScopeTests.cs +++ b/tests/references/Inno.References.Tests/ContentReadScopeTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using Inno.Core.Identity; using Xunit; +using Inno.Core.Identity; namespace Inno.References.Tests; @@ -14,7 +14,7 @@ public void ScopeResolvesOnlyCapturedGenerationAndRevokesOnDispose() var owner = new IdentityAllocator(); var root = new Root(); owner.Register(root); - Guid id = root.identity.persistentId; + Guid id = root.identity.persistentID; using var scope = new ContentReadScope([root.identity], id); Assert.Same(root, Assert.Single(scope.GetValues())); owner.Unregister(root); diff --git a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs index 90595fe16..743907f61 100644 --- a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs +++ b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs @@ -1,21 +1,21 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Core.Identity; using Inno.Extensibility.Reload; using Inno.References; -using Xunit; namespace Inno.References.Tests; public sealed class ReferenceCatalogTests { - private static readonly ReferenceKindId S_KIND = new("asset"); + private static readonly ReferenceKindID KIND = new("asset"); [Fact] - public void Resolve_PreservesUnassignedAndMissingIntent() + public void ResolvePreservesUnassignedAndMissingIntent() { - var unassigned = new ReferenceDescriptor(S_KIND, Guid.Empty); - var missing = new ReferenceDescriptor(S_KIND, Guid.NewGuid(), lastKnownName: "Portrait"); + var unassigned = new ReferenceDescriptor(KIND, Guid.Empty); + var missing = new ReferenceDescriptor(KIND, Guid.NewGuid(), lastKnownName: "Portrait"); ReferenceResolution unassignedResult = ReferenceCatalog.empty.Resolve(unassigned); ReferenceResolution missingResult = ReferenceCatalog.empty.Resolve(missing); @@ -27,31 +27,26 @@ public void Resolve_PreservesUnassignedAndMissingIntent() } [Fact] - public void Create_RejectsDuplicateReferenceKinds() + public void CreateRejectsDuplicateReferenceKinds() { - var first = new FixedResolver(S_KIND, null); - var second = new FixedResolver(S_KIND, null); + var first = new FixedResolver(KIND, null); + var second = new FixedResolver(KIND, null); Assert.Throws(() => ReferenceCatalog.Create(1, [first, second])); } [Fact] - public void RecoveryTransaction_RollsBackAppliedParticipantsInReverseOrder() + public void RecoveryTransactionRollsBackAppliedParticipantsInReverseOrder() { var allocator = new IdentityAllocator(); var target = new Target(); Assert.True(allocator.Register(target)); - var descriptor = new ReferenceDescriptor(S_KIND, target.identity.persistentId); - var catalog = ReferenceCatalog.Create( - 1, - [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); - var events = new List(); + var descriptor = new ReferenceDescriptor(KIND, target.identity.persistentID); + ReferenceCatalog catalog = ReferenceCatalog.Create(1, [new FixedResolver(KIND, target.identity.runtimeIdentity)]); + List events = []; var first = new RecordingParticipant("first", events); var second = new RecordingParticipant("second", events, failApply: true); - var state = new SerializedMissingState( - new ReferenceKey(Guid.NewGuid(), "portrait"), - descriptor, - [1, 2, 3]); + var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "portrait"), descriptor, [1, 2, 3]); var transaction = new ReferenceRecoveryTransaction(catalog, [state], [first, second]); transaction.PrepareForActivation(); @@ -72,11 +67,15 @@ public void RecoveryResolvesOnlyAfterObjectsExistAndRetainsNeutralResultsAfterCo var allocator = new IdentityAllocator(); var target = new Target(); allocator.Register(target); - var descriptor = new ReferenceDescriptor(S_KIND, target.identity.persistentId); - var catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); - var events = new List(); + var descriptor = new ReferenceDescriptor(KIND, target.identity.persistentID); + ReferenceCatalog catalog = ReferenceCatalog.Create(1, [new FixedResolver(KIND, target.identity.runtimeIdentity)]); + List events = []; var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "asset"), descriptor, [1]); - var transaction = new ReferenceRecoveryTransaction(catalog, [state], [new RecordingParticipant("owner", events)]); + var transaction = new ReferenceRecoveryTransaction( + catalog, + [state], + [new RecordingParticipant("owner", events)] + ); Assert.Empty(events); Assert.Empty(transaction.changes); transaction.PrepareForActivation(); @@ -91,8 +90,11 @@ public void RecoveryResolvesOnlyAfterObjectsExistAndRetainsNeutralResultsAfterCo [Fact] public void RecoveryRejectsDuplicateSlotsAndOutOfOrderPhases() { - var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "asset"), - new ReferenceDescriptor(S_KIND, Guid.NewGuid()), []); + var state = new SerializedMissingState( + new ReferenceKey(Guid.NewGuid(), "asset"), + new ReferenceDescriptor(KIND, Guid.NewGuid()), + [] + ); Assert.Throws(() => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [state, state], [])); var transaction = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [state], []); Assert.Throws(transaction.Apply); @@ -102,27 +104,28 @@ public void RecoveryRejectsDuplicateSlotsAndOutOfOrderPhases() transaction.RestorePreviousState(); } - private sealed class Target : IdentityObject - { - } + private sealed class Target : IdentityObject; - private sealed class FixedResolver(ReferenceKindId kindId, RuntimeIdentity? runtimeIdentity) : IReferenceResolver + private sealed class FixedResolver( + ReferenceKindID kindID, + RuntimeIdentity? runtimeIdentity + ) : IReferenceResolver { - public ReferenceKindId kindId { get; } = kindId; + public ReferenceKindID kindID { get; } = kindID; public ReferenceResolution Resolve(ReferenceDescriptor descriptor) => runtimeIdentity.HasValue - ? new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity) - : new ReferenceResolution(descriptor, ReferenceResolutionState.Missing); + ? new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity) + : new ReferenceResolution(descriptor, ReferenceResolutionState.Missing); } private sealed class RecordingParticipant( string name, ICollection events, - bool failApply = false) : IReferenceRecoveryParticipant + bool failApply = false + ) : IReferenceRecoveryParticipant { - public void Validate(IReadOnlyList changes) - => events.Add($"validate:{name}"); + public void Validate(IReadOnlyList changes) => events.Add($"validate:{name}"); public void PrepareForActivation() => events.Add($"prepare:{name}"); @@ -130,13 +133,15 @@ public void Apply() { events.Add($"apply:{name}"); if (failApply) + { throw new InvalidOperationException("expected apply failure"); + } } - public void RollbackStructure() - => events.Add($"rollback:{name}"); + public void RollbackStructure() => events.Add($"rollback:{name}"); public void RestorePreviousState() => events.Add($"restore:{name}"); + public void Complete() => events.Add($"complete:{name}"); } } diff --git a/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs b/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs index f08ab5dfa..20fc969af 100644 --- a/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs +++ b/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading; +using Xunit; using Inno.Core.Execution; using Inno.Extensibility.Reload; -using Xunit; namespace Inno.References.Tests; @@ -15,7 +15,7 @@ public sealed class ReferenceRecoveryTests [InlineData("validate")] public void CandidateFailureCompensatesAttemptedOwnersAroundPublication(string phase) { - var events = new List(); + List events = []; var first = new Participant("first", events); var second = new Participant("second", events, phase); var third = new Participant("third", events); @@ -43,27 +43,45 @@ public void CandidateFailureCompensatesAttemptedOwnersAroundPublication(string p [InlineData("complete", true)] [InlineData("structure", true)] [InlineData("restore", true)] - public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate(string phase, bool wrapped) - { - var events = new List(); + public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate( + string phase, + bool wrapped + ) { + List events = []; var first = new Participant("first", events); var pending = new Participant("pending", events, phase, pending: true, wrapped: wrapped); var gate = new GenerationCoordinator(); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - phase == "complete" ? [pending, first] : [first, pending]); - Exception failure = Assert.ThrowsAny(() => gate.Execute("recovery", new Publication(events, phase != "complete"), [recovery])); - if (wrapped || phase != "complete") Assert.IsType(failure); - else Assert.IsType(failure); + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + phase == "complete" ? [pending, first] : [first, pending] + ); + Exception failure = Assert.ThrowsAny( + () => gate.Execute("recovery", new Publication(events, phase != "complete"), [recovery]) + ); + if (wrapped || phase != "complete") + { + Assert.IsType(failure); + } + else + { + Assert.IsType(failure); + } Assert.Same(failure, gate.failure); Assert.Equal(GenerationState.Faulted, gate.state); Assert.DoesNotContain($"{phase}:first", events); Exception retained = Assert.ThrowsAny(recovery.Complete); - if (phase == "complete") Assert.Same(failure, retained); + if (phase == "complete") + { + Assert.Same(failure, retained); + } else { Assert.Contains(retained, Assert.IsType(failure).InnerExceptions); - Assert.Contains(Assert.IsType(failure).InnerExceptions, - item => item.Message == "Rejected publication."); + Assert.Contains( + Assert.IsType(failure).InnerExceptions, + item => item.Message == "Rejected publication." + ); } Assert.Same(retained, Assert.ThrowsAny(recovery.RollbackStructure)); Assert.Same(retained, Assert.ThrowsAny(recovery.RestorePreviousState)); @@ -74,9 +92,12 @@ public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate(string phase, boo [Fact] public void OrdinaryCleanupFailureStillRetiresOtherOwnersAndCannotPretendToRollback() { - var events = new List(); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - [new Participant("first", events, "complete"), new Participant("second", events)]); + List events = []; + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + [new Participant("first", events, "complete"), new Participant("second", events)] + ); var gate = new GenerationCoordinator(); Assert.Throws(() => gate.Execute("recovery", new Publication(events), [recovery])); Assert.Contains("complete:second", events); @@ -91,12 +112,15 @@ public void OrdinaryCleanupFailureStillRetiresOtherOwnersAndCannotPretendToRollb [InlineData("restore")] public void EarlierParticipantFailureIsRetainedAlongsidePendingOwnership(string phase) { - var events = new List(); + List events = []; var ordinary = new Participant("ordinary", events, phase); var pending = new Participant("pending", events, phase, pending: true); var dependency = new Participant("dependency", events); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - phase == "complete" ? [ordinary, pending, dependency] : [dependency, pending, ordinary]); + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + phase == "complete" ? [ordinary, pending, dependency] : [dependency, pending, ordinary] + ); recovery.PrepareForActivation(); Action finish; if (phase == "complete") @@ -104,7 +128,10 @@ public void EarlierParticipantFailureIsRetainedAlongsidePendingOwnership(string recovery.Apply(); finish = recovery.Complete; } - else if (phase == "structure") finish = recovery.RollbackStructure; + else if (phase == "structure") + { + finish = recovery.RollbackStructure; + } else { recovery.RollbackStructure(); @@ -120,13 +147,19 @@ public void EarlierParticipantFailureIsRetainedAlongsidePendingOwnership(string [Fact] public void RecoveryRejectsAnotherThreadBeforeInvokingDomainCode() { - var events = new List(); + List events = []; var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], [new Participant("owner", events)]); Exception? failure = null; var thread = new Thread(() => { - try { recovery.PrepareForActivation(); } - catch (Exception exception) { failure = exception; } + try + { + recovery.PrepareForActivation(); + } + catch (Exception exception) + { + failure = exception; + } }); thread.Start(); thread.Join(); @@ -136,41 +169,64 @@ public void RecoveryRejectsAnotherThreadBeforeInvokingDomainCode() recovery.RestorePreviousState(); } - private sealed class Participant(string name, ICollection events, string? failurePhase = null, - bool pending = false, bool wrapped = false) : IReferenceRecoveryParticipant + private sealed class Participant( + string name, + ICollection events, + string? failurePhase = null, + bool pending = false, + bool wrapped = false + ) : IReferenceRecoveryParticipant { public void PrepareForActivation() => Run("prepare"); + public void Apply() => Run("apply"); + public void Validate(IReadOnlyList changes) => Run("validate"); + public void Complete() => Run("complete"); + public void RollbackStructure() => Run("structure"); + public void RestorePreviousState() => Run("restore"); private void Run(string phase) { events.Add($"{phase}:{name}"); if (phase != failurePhase) + { return; + } if (pending) { if (wrapped) - throw new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("owner context", new RetirementPendingException("Pending reference owner."))); + { + throw new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("owner context", new RetirementPendingException("Pending reference owner.")) + ); + } throw new RetirementPendingException("Pending reference owner."); } throw new InvalidOperationException("Rejected reference owner."); } } - private sealed class Publication(ICollection events, bool failApply = false) : IGenerationPublication + private sealed class Publication( + ICollection events, + bool failApply = false + ) : IGenerationPublication { public void Activate() { events.Add("publication:activate"); if (failApply) + { throw new InvalidOperationException("Rejected publication."); + } } + public void Rollback() => events.Add("publication:rollback"); + public Probe Complete() { events.Add("commit"); diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs index 816031b16..59b3d83b9 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs @@ -1,18 +1,11 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.IO; -using System.Text; -using Inno.Assets; -using Inno.Extensibility.Modules; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Rendering; -using Xunit; -using Inno.Rendering.Assets; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -26,7 +19,9 @@ public sealed class MeshAndStateTests : IDisposable public MeshAndStateTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(MeshAndStateTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(MeshAndStateTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -39,13 +34,13 @@ public void Dispose() } [Fact] - public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() + public void MaterialAndPipelineStateRoundTripsThroughAssetSerialization() { - var material = new MaterialAsset { techniqueId = new ShaderTechniqueId("high-quality") }; - material.Set(new ShaderPropertyId("roughness"), MaterialValue.FromFloat(0.4f)); - material.Set(new ShaderPropertyId("transform"), MaterialValue.FromMatrix(Matrix.identity)); + var material = new MaterialAsset { techniqueId = new ShaderTechniqueID("high-quality") }; + material.Set(new ShaderPropertyID("roughness"), MaterialValue.FromFloat(0.4f)); + material.Set(new ShaderPropertyID("transform"), MaterialValue.FromMatrix(Matrix.identity)); material.Set( - new ShaderPropertyId("albedo"), + new ShaderPropertyID("albedo"), new MaterialValue { kind = MaterialValueKind.Texture, @@ -53,8 +48,10 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() RenderSamplerFilter.Point, RenderSamplerAddressMode.Repeat, RenderSamplerAddressMode.Mirror, - RenderSamplerAddressMode.Clamp) - }); + RenderSamplerAddressMode.Clamp + ) + } + ); material.SetKeyword("Cutout", enabled: true); material.SetMetadata("tests.sort", "2450"); byte[] materialState = m_serialization.Encode(writer => writer.WriteProperties(material)); @@ -65,9 +62,9 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() return 0; }); - Assert.True(restoredMaterial.TryGet(new ShaderPropertyId("roughness"), out MaterialValue roughness)); + Assert.True(restoredMaterial.TryGet(new ShaderPropertyID("roughness"), out MaterialValue roughness)); Assert.Equal(0.4f, roughness.vector.x); - Assert.True(restoredMaterial.TryGet(new ShaderPropertyId("albedo"), out MaterialValue albedo)); + Assert.True(restoredMaterial.TryGet(new ShaderPropertyID("albedo"), out MaterialValue albedo)); Assert.Equal(RenderSamplerFilter.Point, albedo.sampler.filter); Assert.Equal(RenderSamplerAddressMode.Mirror, albedo.sampler.addressV); Assert.Contains("Cutout", restoredMaterial.keywords); @@ -84,7 +81,8 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() new RenderFeatureConfiguration( "tests.feature", new SerializedRenderExtensionState(Guid.Empty, [4, 5]), - enabled: true) + enabled: true + ) ]); byte[] pipelineState = m_serialization.Encode(writer => writer.WriteProperties(pipeline)); var restoredPipeline = new RenderPipelineAsset(); @@ -102,58 +100,75 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() } [Fact] - public void MaterialResolver_UsesProviderOwnedContractsRolesAndCapabilities() + public void MaterialResolverUsesProviderOwnedContractsRolesAndCapabilities() { var advancedPass = new ShaderPassDefinition( "advanced-draw", ShaderProgramKind.Raster, - requiredFeatures: GraphicsCapability.Compute); + requiredFeatures: GraphicsCapability.Compute + ); var basicPass = new ShaderPassDefinition("basic-draw", ShaderProgramKind.Raster); var shader = new ShaderAsset(); - shader.SetDefinition(new ShaderDefinition( - "Provider-owned shader", - [], - [], - [advancedPass, basicPass], - [ - new ShaderTechniqueDefinition( - new ShaderTechniqueId("advanced"), - new ShaderContractId("example.2d.sprite"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), advancedPass.name)], - GraphicsCapability.Compute), - new ShaderTechniqueDefinition( - new ShaderTechniqueId("basic"), - new ShaderContractId("example.2d.sprite"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), basicPass.name)]) - ]), m_serialization, SerializationContext.empty); + shader.SetDefinition( + new ShaderDefinition( + "Provider-owned shader", + [], + [], + [advancedPass, basicPass], + [ + new ShaderTechniqueDefinition( + new ShaderTechniqueID("advanced"), + new ShaderContractID("example.2d.sprite"), + [new ShaderTechniquePass(new ShaderPassRoleID("draw"), advancedPass.name)], + GraphicsCapability.Compute + ), + new ShaderTechniqueDefinition( + new ShaderTechniqueID("basic"), + new ShaderContractID("example.2d.sprite"), + [new ShaderTechniquePass(new ShaderPassRoleID("draw"), basicPass.name)] + ) + ] + ), + m_serialization, + SerializationContext.empty + ); var material = new MaterialAsset { shader = shader }; GraphicsCapabilities basicCapabilities = CreateCapabilities(GraphicsCapability.None); GraphicsCapabilities computeCapabilities = CreateCapabilities(GraphicsCapability.Compute); - MaterialPassResolution basic = Assert.IsType(MaterialPassResolver.Resolve( - material, - new ShaderContractId("example.2d.sprite"), - new ShaderPassRoleId("draw"), - basicCapabilities)); - MaterialPassResolution advanced = Assert.IsType(MaterialPassResolver.Resolve( - material, - new ShaderContractId("example.2d.sprite"), - new ShaderPassRoleId("draw"), - computeCapabilities)); + MaterialPassResolution basic = Assert.IsType( + MaterialPassResolver.Resolve( + material, + new ShaderContractID("example.2d.sprite"), + new ShaderPassRoleID("draw"), + basicCapabilities + ) + ); + MaterialPassResolution advanced = Assert.IsType( + MaterialPassResolver.Resolve( + material, + new ShaderContractID("example.2d.sprite"), + new ShaderPassRoleID("draw"), + computeCapabilities + ) + ); Assert.Equal("basic", basic.technique.id.value); Assert.Equal("basic-draw", basic.pass.name); Assert.Equal("advanced", advanced.technique.id.value); Assert.Equal("advanced-draw", advanced.pass.name); - Assert.Null(MaterialPassResolver.Resolve( - material, - new ShaderContractId("unrelated.contract"), - new ShaderPassRoleId("draw"), - computeCapabilities)); + Assert.Null( + MaterialPassResolver.Resolve( + material, + new ShaderContractID("unrelated.contract"), + new ShaderPassRoleID("draw"), + computeCapabilities + ) + ); } [Fact] - public void ShaderRasterState_RoundTripsWithoutLosingProviderChoices() + public void ShaderRasterStateRoundTripsWithoutLosingProviderChoices() { ShaderRenderState sourceState = ShaderRenderState.opaque; sourceState.topology = RenderPrimitiveTopology.LineStrip; @@ -161,16 +176,18 @@ public void ShaderRasterState_RoundTripsWithoutLosingProviderChoices() sourceState.frontFace = RenderFrontFace.Clockwise; sourceState.multisampling = false; var source = new ShaderAsset(); - source.SetDefinition(new ShaderDefinition( - "Tests/RasterState", - [], - [], - [ - new ShaderPassDefinition( - "wire", - ShaderProgramKind.Raster, - renderState: sourceState) - ]), m_serialization, SerializationContext.empty); + source.SetDefinition( + new ShaderDefinition( + "Tests/RasterState", + [], + [], + [ + new ShaderPassDefinition("wire", ShaderProgramKind.Raster, renderState: sourceState) + ] + ), + m_serialization, + SerializationContext.empty + ); byte[] state = m_serialization.Encode(writer => writer.WriteProperties(source)); var restored = new ShaderAsset(); @@ -209,7 +226,7 @@ public void MaterialMetadataRemainsAnOpenProviderProtocol() private static GraphicsCapabilities CreateCapabilities(GraphicsCapability features) => new( - GraphicsApi.Noop, + GraphicsApi.noop, features, new GraphicsLimits(64, 4, 4096, 8), Enum.GetValues(), @@ -217,10 +234,6 @@ private static GraphicsCapabilities CreateCapabilities(GraphicsCapability featur [], [], originBottomLeft: false, - homogeneousDepth: false); -} - -[CollectionDefinition("Rendering assets serialization", DisableParallelization = true)] -public sealed class RenderingAssetsSerializationCollection -{ + homogeneousDepth: false + ); } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs new file mode 100644 index 000000000..9159069a4 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +internal sealed class RenderingAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs new file mode 100644 index 000000000..cd12d037a --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +[CollectionDefinition("Rendering assets serialization", DisableParallelization = true)] +public sealed class RenderingAssetsSerializationCollection; diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs new file mode 100644 index 000000000..cdf7c65e3 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +internal sealed class RenderingImportSettingsEnvelope : ISerializable +{ + [SerializableProperty] + public Guid stableTypeId { get; set; } + + [SerializableProperty] + public byte[] properties { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencies { get; set; } = []; +} diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs index 2ac378e28..fbe53ca61 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs @@ -1,28 +1,26 @@ -using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Content.Testing; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; -using System.Text; using System.Linq; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Core.Graphs; -using Inno.Rendering.Shaders; +using System.Text; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Content.Testing; using Inno.Core.Diagnostics; -using Inno.Extensibility.Modules; +using Inno.Core.Graphs; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Xunit; -using Inno.Rendering.Assets; -using Inno.Rendering.Assets.Authoring; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering.Runtime; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -48,11 +46,13 @@ public RenderingImporterIntegrationTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(RenderingImporterIntegrationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(RenderingImporterIntegrationTests).Assembly) + }); _ = typeof(AssetSerializationServices); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); - _ = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); + _ = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); m_types.Rebuild(); } @@ -64,7 +64,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -73,24 +75,40 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); definition.name = "Tests/Basic"; - definition.properties = [.. definition.properties, new(new("roughness"), "Roughness", ShaderPropertyType.Float, - ShaderStage.Fragment, MaterialValue.FromFloat(0.5f))]; - definition.techniques = [new(new("default"), new("tests.surface"), [new(new("draw"), "Main")])]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + definition.properties = + [ + .. definition.properties, + new ShaderPropertyDefinition( + new ShaderPropertyID("roughness"), + "Roughness", + ShaderPropertyType.Float, + ShaderStage.Fragment, + MaterialValue.FromFloat(0.5f) + ) + ]; + definition.techniques = [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + new ShaderContractID("tests.surface"), + [new ShaderTechniquePass(new ShaderPassRoleID("draw"), "Main")] + )]; + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); WriteBytes("Shaders/basic.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); WriteText("Meshes/triangle.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); - byte[] png = new byte[24]; + var png = new byte[24]; new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }.CopyTo(png, 0); BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(16, 4), 8); BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(20, 4), 4); WriteBytes("Textures/color.png", png); - using (var writer = CreateLoader(m_assets, m_library)) + using (AssetLoader writer = CreateLoader(m_assets, m_library)) { ShaderAsset shader = Assert.IsType(writer.Load(AssetPath.Project("Shaders/basic.ishader"), typeof(ShaderAsset))); var material = new MaterialAsset { shader = shader }; - material.Set(new ShaderPropertyId("roughness"), MaterialValue.FromFloat(0.25f)); + material.Set(new ShaderPropertyID("roughness"), MaterialValue.FromFloat(0.25f)); material.SetMetadata("tests.queue", "opaque"); Assert.True(writer.Save(AssetPath.Project("Materials/basic.imaterial"), material)); @@ -103,28 +121,31 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode Assert.True(writer.Save(AssetPath.Project("Pipelines/default.irenderpipeline"), pipeline)); } - using var loader = CreateLoader(m_assets, m_library); - ShaderAsset loadedShader = Assert.IsType(loader.Load( - AssetPath.Project("Shaders/basic.ishader"), - typeof(ShaderAsset))); - MaterialAsset loadedMaterial = Assert.IsType(loader.Load( - AssetPath.Project("Materials/basic.imaterial"), - typeof(MaterialAsset))); - RenderPipelineAsset loadedPipeline = Assert.IsType(loader.Load( - AssetPath.Project("Pipelines/default.irenderpipeline"), - typeof(RenderPipelineAsset))); - GeometryAsset geometry = Assert.IsType(loader.Load( - AssetPath.Project("Meshes/triangle.obj"), - typeof(GeometryAsset))); - TextureAsset texture = Assert.IsType(loader.Load( - AssetPath.Project("Textures/color.png"), - typeof(TextureAsset))); + using AssetLoader loader = CreateLoader(m_assets, m_library); + ShaderAsset loadedShader = Assert.IsType( + loader.Load(AssetPath.Project("Shaders/basic.ishader"), typeof(ShaderAsset)) + ); + MaterialAsset loadedMaterial = Assert.IsType( + loader.Load(AssetPath.Project("Materials/basic.imaterial"), typeof(MaterialAsset)) + ); + RenderPipelineAsset loadedPipeline = Assert.IsType( + loader.Load(AssetPath.Project("Pipelines/default.irenderpipeline"), typeof(RenderPipelineAsset)) + ); + GeometryAsset geometry = Assert.IsType( + loader.Load(AssetPath.Project("Meshes/triangle.obj"), typeof(GeometryAsset)) + ); + TextureAsset texture = Assert.IsType( + loader.Load(AssetPath.Project("Textures/color.png"), typeof(TextureAsset)) + ); Assert.Equal("Tests/Basic", loadedShader.definition!.name); Assert.True(loadedShader.runtimePayload.IsEmpty); - Assert.Equal(graph.nodes.Count, ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(loadedShader, loader), m_serialization).nodes.Count); + Assert.Equal( + graph.nodes.Count, + ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(loadedShader, loader), m_serialization).nodes.Count + ); Assert.Same(loadedShader, loadedMaterial.shader); - Assert.True(loadedMaterial.TryGet(new ShaderPropertyId("roughness"), out MaterialValue roughness)); + Assert.True(loadedMaterial.TryGet(new ShaderPropertyID("roughness"), out MaterialValue roughness)); Assert.Equal(0.25f, roughness.vector.x); Assert.True(loadedMaterial.TryGetMetadata("tests.queue", out string? queue)); Assert.Equal("opaque", queue); @@ -139,8 +160,8 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode [Fact] public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependencies() { - AssetSourceId providerId = new("tests.provider"); - AssetSourceId consumerId = new("tests.consumer"); + var providerID = new AssetSourceID("tests.provider"); + var consumerID = new AssetSourceID("tests.consumer"); string providerRoot = Path.Combine(m_root, "ProviderPlugin"); string consumerRoot = Path.Combine(m_root, "ConsumerPlugin"); Directory.CreateDirectory(providerRoot); @@ -148,11 +169,15 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc WriteReadOnlyShaderSource( providerRoot, "common.ishadersource", - "vec4 ProviderColor() { return vec4(0.2, 0.4, 0.6, 1.0); }", "ProviderColor"); + "vec4 ProviderColor() { return vec4(0.2, 0.4, 0.6, 1.0); }", + "ProviderColor" + ); WriteReadOnlyShaderSource( consumerRoot, "local.ishadersource", - "float LocalValue() { return 0.5; }", "LocalValue"); + "float LocalValue() { return 0.5; }", + "LocalValue" + ); WriteReadOnlyShaderSource( consumerRoot, "main.ishadersource", @@ -160,51 +185,56 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc #include "local.ishadersource" #include "tests.provider::common.ishadersource" vec4 Evaluate() { return ProviderColor() * LocalValue(); } - """); - AssetSourceMount project = new(AssetSourceId.project, m_assets, isReadOnly: false); - AssetSourceMount provider = new(providerId, providerRoot, isReadOnly: true); - AssetSourceMount undeclaredConsumer = new(consumerId, consumerRoot, isReadOnly: true); - - using (var undeclared = CreateLoader( - [project, provider, undeclaredConsumer], - Path.Combine(m_root, "UndeclaredLibrary"))) - { + """ + ); + var project = new AssetSourceMount(AssetSourceID.project, m_assets, isReadOnly: false); + var provider = new AssetSourceMount(providerID, providerRoot, isReadOnly: true); + var undeclaredConsumer = new AssetSourceMount(consumerID, consumerRoot, isReadOnly: true); + + using (AssetLoader undeclared = CreateLoader( + [project, provider, undeclaredConsumer], + Path.Combine(m_root, "UndeclaredLibrary") + )) { InvalidDataException error = Assert.Throws(() => undeclared.Rescan()); Assert.Contains("did not declare dependency", error.Message, StringComparison.OrdinalIgnoreCase); } - AssetSourceMount declaredConsumer = new( - consumerId, - consumerRoot, - isReadOnly: true, - dependencies: [providerId]); - using var loader = CreateLoader( - [project, provider, declaredConsumer], - Path.Combine(m_root, "DeclaredLibrary")); + var declaredConsumer = new AssetSourceMount(consumerID, consumerRoot, isReadOnly: true, dependencies: [providerID]); + using AssetLoader loader = CreateLoader([project, provider, declaredConsumer], Path.Combine(m_root, "DeclaredLibrary")); loader.Rescan(); - ShaderFunctionAsset shader = Assert.IsType(loader.Load( - new AssetPath(consumerId, "main.ishadersource"), typeof(ShaderFunctionAsset))); - ShaderSourceImplementationRequest request = Assert.Single(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(shader, loader), "Evaluate", m_serialization)); + ShaderFunctionAsset shader = Assert.IsType( + loader.Load(new AssetPath(consumerID, "main.ishadersource"), typeof(ShaderFunctionAsset)) + ); + ShaderSourceImplementationRequest request = Assert.Single( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(shader, loader), "Evaluate", m_serialization) + ); using var frontends = new ShaderSourceFrontendRegistry(m_types); ShaderSourceModuleAnalysis analysis = frontends.AnalyzeModule([request]); Assert.True(analysis.succeeded, string.Join("\n", analysis.diagnostics.Select(static value => value.message))); Assert.Equal("Evaluate", Assert.Single(shader.exports)); Assert.Equal(3, Assert.Single(analysis.implementations).sources.Count); Assert.Equal( - [ - new AssetPath(consumerId, "local.ishadersource"), - new AssetPath(providerId, "common.ishadersource") - ], loader.GetImportDependencies(shader)); + [ + new AssetPath(consumerID, "local.ishadersource"), + new AssetPath(providerID, "common.ishadersource") + ], + loader.GetImportDependencies(shader) + ); } [Fact] public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdentityAndDefinition() { - WriteBytes("Surface.ishader", GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty), m_serialization)); + WriteBytes( + "Surface.ishader", + GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty), m_serialization) + ); WriteReadOnlyShaderSource(m_assets, "Function.ishadersource", "vec4 Evaluate(vec4 color) { return color; }"); - using var loader = CreateLoader(m_assets, m_library); + using AssetLoader loader = CreateLoader(m_assets, m_library); ShaderAsset shader = Assert.IsType(loader.Load(AssetPath.Project("Surface.ishader"), typeof(ShaderAsset))); - ShaderFunctionAsset function = Assert.IsType(loader.Load(AssetPath.Project("Function.ishadersource"), typeof(ShaderFunctionAsset))); + ShaderFunctionAsset function = Assert.IsType( + loader.Load(AssetPath.Project("Function.ishadersource"), typeof(ShaderFunctionAsset)) + ); Assert.NotEmpty(ShaderGraphArtifact.Read(shader, loader)); Assert.NotEmpty(ShaderSourceBundle.Read(function, loader)); string destination = Path.Combine(m_root, "PlayerContent"); @@ -213,12 +243,12 @@ public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdenti using SerializationGeneration generation = m_serialization.CaptureGeneration(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(destination); using var runtime = new AssetDatabase(contentStore, generation, m_types.current, new IdentityAllocator()); - ShaderAsset deployed = runtime.Load(shader.identity.persistentId); - Assert.Equal(shader.identity.persistentId, deployed.identity.persistentId); + ShaderAsset deployed = runtime.Load(shader.identity.persistentID); + Assert.Equal(shader.identity.persistentID, deployed.identity.persistentID); Assert.Equal(shader.definition!.name, deployed.definition!.name); Assert.True(deployed.runtimePayload.IsEmpty); - Assert.False(runtime.TryGetArtifact(shader.identity.persistentId, ShaderGraphArtifact.outputName, out _)); - Assert.False(runtime.TryGetArtifact(function.identity.persistentId, ShaderSourceBundle.outputName, out _)); + Assert.False(runtime.TryGetArtifact(shader.identity.persistentID, ShaderGraphArtifact.C_OUTPUT_NAME, out _)); + Assert.False(runtime.TryGetArtifact(function.identity.persistentID, ShaderSourceBundle.C_OUTPUT_NAME, out _)); foreach (string file in Directory.EnumerateFiles(Path.Combine(destination, "Artifacts"), "*", SearchOption.AllDirectories)) { string bytes = Encoding.UTF8.GetString(File.ReadAllBytes(file)); @@ -230,47 +260,56 @@ public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdenti [Fact] public void OneShaderSourceLibraryExportsMultipleExplicitGraphFunctions() { - WriteReadOnlyShaderSource(m_assets, "Library.ishadersource", + WriteReadOnlyShaderSource( + m_assets, + "Library.ishadersource", "float Exposure(float value) { return value; }\nvec4 Tint(vec4 color) { return color; }", - "Exposure", "Tint"); - using var loader = CreateLoader(m_assets, m_library); - ShaderFunctionAsset library = Assert.IsType(loader.Load( - AssetPath.Project("Library.ishadersource"), typeof(ShaderFunctionAsset))); + "Exposure", + "Tint" + ); + using AssetLoader loader = CreateLoader(m_assets, m_library); + ShaderFunctionAsset library = Assert.IsType( + loader.Load(AssetPath.Project("Library.ishadersource"), typeof(ShaderFunctionAsset)) + ); Assert.Equal(new[] { "Exposure", "Tint" }, library.exports); byte[] bundle = ShaderSourceBundle.Read(library, loader); using var frontends = new ShaderSourceFrontendRegistry(m_types); - Assert.Equal("Exposure", Assert.Single(frontends.AnalyzeModule( - ShaderSourceBundle.Decode(bundle, "Exposure", m_serialization)).implementations).entryPoint); - Assert.Equal("Tint", Assert.Single(frontends.AnalyzeModule( - ShaderSourceBundle.Decode(bundle, "Tint", m_serialization)).implementations).entryPoint); + Assert.Equal( + "Exposure", + Assert.Single( + frontends.AnalyzeModule(ShaderSourceBundle.Decode(bundle, "Exposure", m_serialization)).implementations + ).entryPoint + ); + Assert.Equal( + "Tint", + Assert.Single( + frontends.AnalyzeModule(ShaderSourceBundle.Decode(bundle, "Tint", m_serialization)).implementations + ).entryPoint + ); Assert.Throws(() => ShaderSourceBundle.Decode(bundle, "PrivateHelper", m_serialization)); } - private AssetLoader CreateLoader(string assetRoot, string libraryRoot) - => new( - m_types, - m_serialization, - m_identities, - m_diagnostics, - m_logs, - assetRoot, - libraryRoot); - [Fact] public void InvalidGraphAutosaveSurvivesImportFailureAndRestartWithoutLosingMissingRecords() { AssetPath path = AssetPath.Project("unfinished.ishader"); GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - graph.AddNode(new(new("missing"), "unavailable.shader-node")); - graph.AddEdge(new(new("unresolved"), new(new("missing"), new("old-output")), new(new("fragment"), new("old-input")))); + graph.AddNode(new GraphNodeRecord(new GraphNodeID("missing"), "unavailable.shader-node")); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("unresolved"), + new GraphEndpoint(new GraphNodeID("missing"), new GraphPortID("old-output")), + new GraphEndpoint(new GraphNodeID("fragment"), new GraphPortID("old-input")) + ) + ); byte[] expected = GraphDocumentCodec.Encode(graph, m_serialization); - using (var pipeline = CreatePipeline()) + using (AssetPipeline pipeline = CreatePipeline()) { var store = new ShaderGraphSourceStore(pipeline, m_serialization); _ = store.Save(path, graph, null); Assert.Equal(expected, GraphDocumentCodec.Encode(store.Read(path).document, m_serialization)); } - using var restarted = CreatePipeline(); + using AssetPipeline restarted = CreatePipeline(); var reopened = new ShaderGraphSourceStore(restarted, m_serialization); Assert.Equal(expected, GraphDocumentCodec.Encode(reopened.Read(path).document, m_serialization)); } @@ -278,7 +317,7 @@ public void InvalidGraphAutosaveSurvivesImportFailureAndRestartWithoutLosingMiss [Fact] public void ShaderSaveRejectsExternalEditsDeletionAndNewFileCollisions() { - using var pipeline = CreatePipeline(); + using AssetPipeline pipeline = CreatePipeline(); var store = new ShaderGraphSourceStore(pipeline, m_serialization); AssetPath path = AssetPath.Project("conflict.ishader"); GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); @@ -302,10 +341,19 @@ public void ReadOnlyInstalledGraphCanBeReadButNeverAutosaved() GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); byte[] bytes = GraphDocumentCodec.Encode(graph, m_serialization); File.WriteAllBytes(Path.Combine(installed, "shader.ishader"), bytes); - File.WriteAllBytes(Path.Combine(installed, "shader.ishader.imeta"), m_serialization.Serialize(new RenderingAssetSourceMeta - { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, importerId = "inno.rendering.shader" })); - var id = new AssetSourceId("test.installed"); - using var pipeline = CreatePipeline([new(AssetSourceId.project, m_assets, false), new(id, installed, true)]); + File.WriteAllBytes( + Path.Combine(installed, "shader.ishader.imeta"), + m_serialization.Serialize(new RenderingAssetSourceMeta + { + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.rendering.shader" + }) + ); + var id = new AssetSourceID("test.installed"); + using AssetPipeline pipeline = CreatePipeline( + [new AssetSourceMount(AssetSourceID.project, m_assets, false), new AssetSourceMount(id, installed, true)] + ); var store = new ShaderGraphSourceStore(pipeline, m_serialization); var path = new AssetPath(id, "shader.ishader"); ShaderGraphSourceSnapshot snapshot = store.Read(path); @@ -314,10 +362,6 @@ public void ReadOnlyInstalledGraphCanBeReadButNeverAutosaved() Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(installed, "shader.ishader"))); } - private AssetPipeline CreatePipeline(IReadOnlyList? mounts = null) - => new(m_modules, m_types, m_serialization, m_identities, m_diagnostics, m_logs, - new AssetPipelineOptions { assetRoot = m_assets, libraryRoot = m_library, enableFileSystemWatcher = false, sourceMounts = mounts }); - [Fact] public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirOwner() { @@ -325,15 +369,19 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO WriteBytes("surface.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); using AssetPipeline assets = CreatePipeline(); ShaderAsset shader = assets.Load(AssetPath.Project("surface.ishader")); - SerializedRenderExtensionState state = new(assets.CaptureProperties(new NestedPipelineSettings - { nested = new NestedPipelineReferences { shader = shader } })); - Assert.Equal(shader.identity.persistentId, Assert.Single(state.dependencies).persistentId); + var state = new SerializedRenderExtensionState( + assets.CaptureProperties(new NestedPipelineSettings + { + nested = new NestedPipelineReferences { shader = shader } + }) + ); + Assert.Equal(shader.identity.persistentID, Assert.Single(state.dependencies).persistentID); var pipeline = new RenderPipelineAsset { pipelineTypeId = "tests.pipeline", pipelineState = state }; AssetPath path = AssetPath.Project("configured.irenderpipeline"); Assert.True(assets.Save(path, pipeline)); RenderPipelineAsset loaded = assets.Load(path); var context = new RenderExtensionStateContext(loaded); - Assert.Equal(shader.identity.persistentId, Assert.Single(assets.GetDependencies(loaded)).persistentId); + Assert.Equal(shader.identity.persistentID, Assert.Single(assets.GetDependencies(loaded)).persistentID); var restored = new NestedPipelineSettings(); context.Restore(loaded.pipelineState, restored); Assert.Same(shader, restored.nested.shader); @@ -341,100 +389,117 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO var restoredThroughOwner = new NestedPipelineSettings(); ownedContext.Restore(loaded.pipelineState, restoredThroughOwner); Assert.Same(shader, restoredThroughOwner.nested.shader); - Assert.Throws(() => new RenderPipelineAsset().RestoreProperties(state.stableTypeId, state.propertyData, new NestedPipelineSettings())); + Assert.Throws( + () => new RenderPipelineAsset().RestoreProperties(state.stableTypeId, state.propertyData, new NestedPipelineSettings()) + ); Assert.Throws(() => context.Restore(loaded.pipelineState, new OtherPipelineSettings())); - using (AssetLoader other = new(m_types, m_serialization, new IdentityAllocator(), m_diagnostics, m_logs, - m_assets, Path.Combine(m_root, "IsolatedLibrary"))) - { - var otherPipeline = Assert.IsType(other.Load(path, typeof(RenderPipelineAsset))); - var otherShader = Assert.IsType(other.Load(AssetPath.Project("surface.ishader"), typeof(ShaderAsset))); - Assert.Equal(shader.identity.persistentId, otherShader.identity.persistentId); - Assert.NotSame(shader, otherShader); - var second = new NestedPipelineSettings(); - new RenderExtensionStateContext(otherPipeline).Restore(otherPipeline.pipelineState, second); - Assert.Same(otherShader, second.nested.shader); - var firstAgain = new NestedPipelineSettings(); - ownedContext.Restore(loaded.pipelineState, firstAgain); - Assert.Same(shader, firstAgain.nested.shader); - } - } - - [StableTypeId("5c438963-794a-4fde-bd59-45c00d7479de")] - private sealed class NestedPipelineSettings : ISerializable - { - [SerializableProperty] public NestedPipelineReferences nested { get; set; } - } - - private struct NestedPipelineReferences - { - public ShaderAsset? shader { get; set; } + using var other = new AssetLoader( + m_types, + m_serialization, + new IdentityAllocator(), + m_diagnostics, + m_logs, + m_assets, + Path.Combine(m_root, "IsolatedLibrary") + ); + RenderPipelineAsset otherPipeline = Assert.IsType(other.Load(path, typeof(RenderPipelineAsset))); + ShaderAsset otherShader = Assert.IsType(other.Load(AssetPath.Project("surface.ishader"), typeof(ShaderAsset))); + Assert.Equal(shader.identity.persistentID, otherShader.identity.persistentID); + Assert.NotSame(shader, otherShader); + var second = new NestedPipelineSettings(); + new RenderExtensionStateContext(otherPipeline).Restore(otherPipeline.pipelineState, second); + Assert.Same(otherShader, second.nested.shader); + var firstAgain = new NestedPipelineSettings(); + ownedContext.Restore(loaded.pipelineState, firstAgain); + Assert.Same(shader, firstAgain.nested.shader); } - [StableTypeId("830a7851-bc19-44d4-a6e6-a6c38f6bb972")] - private sealed class OtherPipelineSettings : ISerializable { } + private AssetLoader CreateLoader( + string assetRoot, + string libraryRoot + ) => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, assetRoot, libraryRoot); private AssetLoader CreateLoader( IReadOnlyList mounts, - string libraryRoot) + string libraryRoot + ) => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, mounts, libraryRoot); + + private AssetPipeline CreatePipeline(IReadOnlyList? mounts = null) => new( + m_modules, m_types, m_serialization, m_identities, m_diagnostics, m_logs, - mounts, - libraryRoot); - - private void WriteText(string relativePath, string value) - => WriteBytes(relativePath, Encoding.UTF8.GetBytes(value)); - - private void WriteBytes(string relativePath, byte[] bytes) - { + new AssetPipelineOptions + { + assetRoot = m_assets, + libraryRoot = m_library, + enableFileSystemWatcher = false, + sourceMounts = mounts + } + ); + + private void WriteText( + string relativePath, + string value + ) => WriteBytes(relativePath, Encoding.UTF8.GetBytes(value)); + + private void WriteBytes( + string relativePath, + byte[] bytes + ) { string path = Path.Combine(m_assets, relativePath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllBytes(path, bytes); + File.WriteAllBytes(path, bytes); } - private void WriteReadOnlyShaderSource(string root, string localPath, string content, params string[] exports) - { + private void WriteReadOnlyShaderSource( + string root, + string localPath, + string content, + params string[] exports + ) { if (exports.Length == 0) exports = ["Evaluate"]; string path = Path.Combine(root, localPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, content, Encoding.UTF8); - System.IO.File.WriteAllBytes(path + ".imeta", m_serialization.Serialize( - new RenderingAssetSourceMeta - { - persistentId = Guid.NewGuid(), - sourceKind = (int)AssetSourceKind.File, - importerId = "inno.rendering.shader-function", - importerSettingsBytes = m_serialization.Serialize(new RenderingImportSettingsEnvelope + File.WriteAllText(path, content, Encoding.UTF8); + File.WriteAllBytes( + path + ".imeta", + m_serialization.Serialize( + new RenderingAssetSourceMeta { - stableTypeId = Guid.Parse("59c92a59-ef51-4587-b917-df5d187d2717"), - properties = m_serialization.Encode(writer => writer.WriteProperties(new ShaderSourceImportSettings - { languageId = "inno.shader-language.bgfx-sc", implementationId = "bgfx", exports = exports })) - }) - })); + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.rendering.shader-function", + importerSettingsBytes = m_serialization.Serialize(new RenderingImportSettingsEnvelope + { + stableTypeId = Guid.Parse("59c92a59-ef51-4587-b917-df5d187d2717"), + properties = m_serialization.Encode(writer => writer.WriteProperties(new ShaderSourceImportSettings + { + languageId = "inno.shader-language.bgfx-sc", + implementationId = "bgfx", + exports = exports + })) + }) + } + ) + ); } -} - -internal sealed class RenderingAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; + [StableTypeID("5c438963-794a-4fde-bd59-45c00d7479de")] + private sealed class NestedPipelineSettings : ISerializable + { + [SerializableProperty] + public NestedPipelineReferences nested { get; set; } + } - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} + private struct NestedPipelineReferences + { + public ShaderAsset? shader { get; set; } + } -internal sealed class RenderingImportSettingsEnvelope : ISerializable -{ - [SerializableProperty] public Guid stableTypeId { get; set; } - [SerializableProperty] public byte[] properties { get; set; } = []; - [SerializableProperty] public Guid[] dependencies { get; set; } = []; + [StableTypeID("830a7851-bc19-44d4-a6e6-a6c38f6bb972")] + private sealed class OtherPipelineSettings : ISerializable; } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs index 2f641c31b..ff52b41e7 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs @@ -1,28 +1,31 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Inno.Rendering.Shaders; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; [Collection("Rendering assets serialization")] public sealed class ShaderCompilerTests : IDisposable { - private readonly ModuleHost m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderCompilerTests).Assembly)}); + private readonly ModuleHost m_modules = new( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderCompilerTests).Assembly)} + ); + private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; private readonly ShaderNodeCompilerRegistry m_nodes; @@ -36,18 +39,31 @@ public ShaderCompilerTests() [Fact] public void FailedToolResultsCannotCarrySuccessfulBinaryBytes() - => Assert.Throws(() => new ShaderStageToolResult([1], [], - [new("TEST_ERROR", DiagnosticSeverity.Error, "The adapter rejected its binary.", new("test", 1, 1))])); + => Assert.Throws(() => new ShaderStageToolResult( + [1], + [], + [new ShaderSourceDiagnostic( + "TEST_ERROR", + DiagnosticSeverity.Error, + "The adapter rejected its binary.", + new ShaderSourcePosition("test", 1, 1) + )] + )); [Fact] public void ToolResultsCopyAdapterOwnedBytesBindingsAndDiagnostics() { byte[] bytes = [1, 2, 3]; - ShaderSourceDiagnostic[] diagnostics = [new("TEST", DiagnosticSeverity.Warning, "A warning", new("test", 1, 1))]; - ShaderStageBinding[] bindings = [new("color", "native_color", 0)]; + ShaderSourceDiagnostic[] diagnostics = [new ShaderSourceDiagnostic( + "TEST", + DiagnosticSeverity.Warning, + "A warning", + new ShaderSourcePosition("test", 1, 1) + )]; + ShaderStageBinding[] bindings = [new ShaderStageBinding("color", "native_color", 0)]; var result = new ShaderStageToolResult(bytes, bindings, diagnostics); bytes[0] = 9; - diagnostics[0] = new("CHANGED", DiagnosticSeverity.Error, "Mutated input", new("test", 1, 1)); + diagnostics[0] = new("CHANGED", DiagnosticSeverity.Error, "Mutated input", new ShaderSourcePosition("test", 1, 1)); bindings[0] = new("other", "other", 1); Assert.Equal(1, result.bytes.Span[0]); Assert.Equal("TEST", Assert.Single(result.diagnostics).code); @@ -58,7 +74,7 @@ public void ToolResultsCopyAdapterOwnedBytesBindingsAndDiagnostics() public async Task CompileAsyncUsesGraphLoweringAndTypedStages() { var toolchain = new FakeToolchain(); - ShaderCompilationResult result = await Compile(new(toolchain), Template()); + ShaderCompilationResult result = await CompileAsync(new ShaderCompiler(toolchain), Template()); Assert.True(result.succeeded, Diagnostics(result)); Assert.Equal(2, toolchain.requests.Count); Assert.Equal("color", Assert.Single(result.artifact!.shaderInterface.bindings).id.value); @@ -67,7 +83,7 @@ public async Task CompileAsyncUsesGraphLoweringAndTypedStages() [Fact] public async Task AdapterFailureRetainsOriginalSourceLocationAndNoPartialProgram() { - ShaderCompilationResult result = await Compile(new(new FakeToolchain { reportError = true }), Template()); + ShaderCompilationResult result = await CompileAsync(new ShaderCompiler(new FakeToolchain { reportError = true }), Template()); Assert.False(result.succeeded); Assert.Null(result.artifact); ShaderDiagnostic error = Assert.Single(result.diagnostics.Where(static value => value.severity == DiagnosticSeverity.Error)); @@ -84,75 +100,182 @@ public async Task UnsupportedAlternativePassKeepsSupportedPassAndExactBindingLay GraphDocument alternate = graph.Clone(); foreach (GraphNodeRecord original in alternate.nodes) { - var node = new GraphNodeRecord(new("alternate." + original.id.value), original.definitionId); - foreach ((string key, GraphSerializedValue value) in original.values) node.SetValue(key, value.Clone()); - if (node.definitionId == ShaderGraphDocument.outputDefinitionId) + var node = new GraphNodeRecord(new GraphNodeID("alternate." + original.id.value), original.definitionID); + foreach ((string key, GraphSerializedValue value) in original.values) + { + node.SetValue(key, value.Clone()); + } + if (node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) { - ShaderGraphStageSettings settings = ShaderGraphDocument.Read(node, "settings", null!, m_serialization, SerializationContext.empty); + ShaderGraphStageSettings settings = ShaderGraphDocument.Read( + node, + "settings", + null!, + m_serialization, + SerializationContext.empty + ); node.SetValue("settings", ShaderGraphDocument.Encode(settings, m_serialization, SerializationContext.empty)); } - else node.SetValue("stage", ShaderGraphDocument.Encode("alternate." + ShaderGraphDocument.Read(node, "stage", "", m_serialization, SerializationContext.empty), m_serialization, SerializationContext.empty)); + else + { + node.SetValue( + "stage", + ShaderGraphDocument.Encode( + "alternate." + ShaderGraphDocument.Read(node, "stage", string.Empty, m_serialization, SerializationContext.empty), + m_serialization, + SerializationContext.empty + ) + ); + } graph.AddNode(node); } foreach (GraphEdgeRecord edge in alternate.edges) - graph.AddEdge(new(new("alternate." + edge.id.value), new(new("alternate." + edge.output.nodeId.value), edge.output.portId), new(new("alternate." + edge.input.nodeId.value), edge.input.portId))); - definition.passes = [new("Clustered", ShaderProgramKind.Raster, requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageBuffer), definition.passes[0]]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); - graph = ShaderGraphPrograms.Bind(graph, "Clustered", [new("alternate.vertex"), new("alternate.fragment")], m_serialization, SerializationContext.empty); + { + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("alternate." + edge.id.value), + new GraphEndpoint(new GraphNodeID("alternate." + edge.output.nodeID.value), edge.output.portID), + new GraphEndpoint(new GraphNodeID("alternate." + edge.input.nodeID.value), edge.input.portID) + ) + ); + } + definition.passes = + [ + new ShaderPassDefinition( + "Clustered", + ShaderProgramKind.Raster, + requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageBuffer + ), + definition.passes[0] + ]; + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); + graph = ShaderGraphPrograms.Bind( + graph, + "Clustered", + [new GraphNodeID("alternate.vertex"), new GraphNodeID("alternate.fragment")], + m_serialization, + SerializationContext.empty + ); var toolchain = new FakeToolchain(); - ShaderCompilationResult result = await Compile(new(toolchain), graph); + ShaderCompilationResult result = await CompileAsync(new ShaderCompiler(toolchain), graph); Assert.True(result.succeeded, Diagnostics(result)); Assert.Equal("Main", Assert.Single(result.artifact!.passes).definition.name); Assert.Equal(2, toolchain.requests.Count); - Assert.Contains(result.diagnostics, static value => value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning); + Assert.Contains( + result.diagnostics, + static value => value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning + ); } [Fact] public async Task LastGoodStorePreservesArtifactAfterFailedCandidate() { - Guid shaderId = Guid.NewGuid(); + Guid shaderID = Guid.NewGuid(); var store = new ShaderLastGoodStore(); - ShaderCompilationResult success = await Compile(new(new FakeToolchain()), Template()); - ShaderCompilationResult failure = await Compile(new(new FakeToolchain { reportError = true }), Template()); - ShaderArtifactSelection first = store.Select(shaderId, success.artifact!.targetKey, RenderShaderVariant.empty, success); - ShaderArtifactSelection second = store.Select(shaderId, success.artifact.targetKey, RenderShaderVariant.empty, failure); + ShaderCompilationResult success = await CompileAsync(new ShaderCompiler(new FakeToolchain()), Template()); + ShaderCompilationResult failure = await CompileAsync(new ShaderCompiler(new FakeToolchain { reportError = true }), Template()); + ShaderArtifactSelection first = store.Select(shaderID, success.artifact!.targetKey, RenderShaderVariant.empty, success); + ShaderArtifactSelection second = store.Select(shaderID, success.artifact.targetKey, RenderShaderVariant.empty, failure); Assert.True(first.candidateSucceeded); Assert.False(second.candidateSucceeded); Assert.True(second.usingLastGood); Assert.Same(success.artifact, second.artifact); } - private GraphDocument Template() => ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - private ShaderDefinition Definition(GraphDocument graph) => ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); - private ValueTask Compile(ShaderCompiler compiler, GraphDocument graph) + public void Dispose() { - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(m_nodes).Lower(graph, "tests.fake", new Dictionary(), m_serialization, SerializationContext.empty); + m_nodes.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } + + private GraphDocument Template() => ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); + + private ShaderDefinition Definition(GraphDocument graph) + => ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); + + private ValueTask CompileAsync( + ShaderCompiler compiler, + GraphDocument graph + ) { + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(m_nodes).Lower( + graph, + "tests.fake", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); - return compiler.CompileAsync(Definition(graph), program, compiler.CreateTarget(capabilities), RenderShaderVariant.empty, - m_serialization, SerializationContext.empty); + var capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); + return compiler.CompileAsync( + Definition(graph), + program, + compiler.CreateTarget(capabilities), + RenderShaderVariant.empty, + m_serialization, + SerializationContext.empty + ); } - private static string Diagnostics(ShaderCompilationResult result) => string.Join("\n", result.diagnostics.Select(static value => value.message)); - public void Dispose() { m_nodes.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + private static string Diagnostics(ShaderCompilationResult result) + => string.Join("\n", result.diagnostics.Select(static value => value.message)); private sealed class FakeToolchain : IShaderCompilerToolchain { - public string implementationId => "tests.fake"; - internal bool reportError { get; init; } + public string implementationID => "tests.fake"; + public IReadOnlyList supportedSourceLanguages => []; - internal List requests { get; } = []; - public ShaderCompileTarget CreateTarget(GraphicsCapabilities capabilities, bool optimize = true, bool debugInformation = false) - => new("tests:fake", capabilities, optimize, debugInformation); - public ValueTask CompileAsync(ShaderStageToolRequest request, CancellationToken cancellationToken) - { + + public ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) => new("tests:fake", capabilities, optimize, debugInformation); + + public ValueTask CompileAsync( + ShaderStageToolRequest request, + CancellationToken cancellationToken + ) { cancellationToken.ThrowIfCancellationRequested(); requests.Add(request); - return ValueTask.FromResult(reportError - ? new ShaderStageToolResult([], [], [new("TEST_ERROR", DiagnosticSeverity.Error, "Opaque compiler failure", new("Shaders/function.ishadersource", 2, 3))]) - : new ShaderStageToolResult([1, 2, 3], request.stage.inputs.Where(static input => input.kind == ShaderIrInputKind.Uniform) - .Select(static input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), [])); + return ValueTask.FromResult( + reportError + ? new ShaderStageToolResult( + [], + [], + [new ShaderSourceDiagnostic( + "TEST_ERROR", + DiagnosticSeverity.Error, + "Opaque compiler failure", + new ShaderSourcePosition("Shaders/function.ishadersource", 2, 3) + )] + ) + : new ShaderStageToolResult( + [1, 2, 3], + request.stage.inputs + .Where(static input => input.kind == ShaderIrInputKind.Uniform) + .Select(static input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), + [] + ) + ); } + internal bool reportError { get; init; } + + internal List requests { get; } = []; } } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs index 1ebb2b898..31547a231 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs @@ -1,29 +1,37 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Inno.Rendering.Shaders; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; [Collection("Rendering assets serialization")] public sealed class ShaderGraphArtifactTests : IDisposable { - private readonly ModuleHost m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphArtifactTests).Assembly)}); + private readonly ModuleHost m_modules = new( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphArtifactTests).Assembly)} + ); + private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; - public ShaderGraphArtifactTests() { m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } + + public ShaderGraphArtifactTests() + { + m_types = new(m_modules, new ReflectionTypeCatalogSource()); + m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); + } [Theory] [InlineData("16182a41-f19b-5a28-a66f-5310360f8a32", "ArtifactData")] @@ -32,11 +40,10 @@ public sealed class ShaderGraphArtifactTests : IDisposable [InlineData("3c78ad4e-deb3-547b-984e-18de97667641", "FunctionData")] [InlineData("4f51d0e8-599b-5fd7-b4cc-4694fe18e922", "ImplementationData")] public void FrozenArtifactRecordsKeepTheirPersistentIdentitiesAfterOwnershipMoves( - string stableId, + string stableID, string typeName ) { - TypeRef record = Assert.Single(m_types.current.types, - reference => reference.stableId == Guid.Parse(stableId)); + TypeRef record = Assert.Single(m_types.current.types, reference => reference.stableID == Guid.Parse(stableID)); Assert.Equal(typeName, record.Resolve(m_types).Name); } @@ -44,12 +51,13 @@ string typeName public void SemanticFingerprintIgnoresLayoutButIncludesPropertiesAndFrozenDependencies() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - string Hash(Dictionary sources) => ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, sources, m_serialization), m_serialization); + string Hash(Dictionary sources) + => ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, sources, m_serialization), m_serialization); string initial = Hash([]); graph.nodes[0].position = new(1000, -500); graph.SetMetadata("inno.editor.groups", ShaderGraphDocument.Encode("view-only", m_serialization, SerializationContext.empty)); Assert.Equal(initial, Hash([])); - Assert.NotEqual(initial, Hash(new() { [new("module")] = [1, 2, 3] })); + Assert.NotEqual(initial, Hash(new Dictionary() { [new GraphNodeID("module")] = [1, 2, 3] })); graph.nodes[0].SetValue("semantic-property", ShaderGraphDocument.Encode(7f, m_serialization, SerializationContext.empty)); Assert.NotEqual(initial, Hash([])); } @@ -57,28 +65,55 @@ public void SemanticFingerprintIgnoresLayoutButIncludesPropertiesAndFrozenDepend [Fact] public void ExpandedProgramCompilesWhileAuthoringExportRetainsTheSmallSourceGraph() { - GraphDocument authored = ShaderGraphDocument.Create(new("Surface", [], [], []), m_serialization, SerializationContext.empty); + GraphDocument authored = ShaderGraphDocument.Create( + new ShaderDefinition("Surface", [], [], []), + m_serialization, + SerializationContext.empty + ); ShaderGraphDocument.SetTarget(authored, "example.surface", m_serialization, SerializationContext.empty); GraphDocument expanded = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - byte[] bytes = ShaderGraphArtifact.Encode(authored, new Dictionary(), m_serialization, expanded); + byte[] bytes = ShaderGraphArtifact.Encode(authored, new Dictionary(), m_serialization, expanded); using var nodes = new ShaderNodeCompilerRegistry(m_types); using var sources = new ShaderSourceFrontendRegistry(m_types); - ShaderGraphProgramResult result = ShaderGraphArtifact.Lower(bytes, "bgfx", nodes, sources, m_serialization, SerializationContext.empty); + ShaderGraphProgramResult result = ShaderGraphArtifact.Lower( + bytes, + "bgfx", + nodes, + sources, + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded); - Assert.Equal(GraphDocumentCodec.Encode(authored, m_serialization), GraphDocumentCodec.Encode(ShaderGraphArtifact.ReadDocument(bytes, m_serialization), m_serialization)); + Assert.Equal( + GraphDocumentCodec.Encode(authored, m_serialization), + GraphDocumentCodec.Encode(ShaderGraphArtifact.ReadDocument(bytes, m_serialization), m_serialization) + ); string hash = ShaderGraphArtifact.GetSemanticHash(bytes, m_serialization); - expanded.FindNode(new("color"))!.SetValue("semantic-value", ShaderGraphDocument.Encode(3f, m_serialization, SerializationContext.empty)); - Assert.NotEqual(hash, ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(authored, - new Dictionary(), m_serialization, expanded), m_serialization)); + expanded + .FindNode(new GraphNodeID("color"))! + .SetValue("semantic-value", ShaderGraphDocument.Encode(3f, m_serialization, SerializationContext.empty)); + Assert.NotEqual( + hash, + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(authored, new Dictionary(), m_serialization, expanded), + m_serialization + ) + ); } [Fact] public void TemporarilyEmptyInputNameRetainsItsMaterialDefaultWhileTyping() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - GraphNodeRecord input = graph.FindNode(new("color"))!; - var settings = ShaderGraphDocument.Read(input, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); - settings.id = ""; + GraphNodeRecord input = graph.FindNode(new GraphNodeID("color"))!; + ShaderGraphInputSettings settings = ShaderGraphDocument.Read( + input, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); + settings.id = string.Empty; graph = ShaderGraphBindings.ChangeInput(graph, input.id, settings, m_serialization, SerializationContext.empty); settings.id = "renamed-color"; graph = ShaderGraphBindings.ChangeInput(graph, input.id, settings, m_serialization, SerializationContext.empty); @@ -93,9 +128,13 @@ public void GraphArtifactPreservesProviderOwnedContractAndRoleIdentifiers() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); - definition.techniques = [new(new("default"), new("tests.surface"), [new(new("tests.draw"), "Main")])]; + definition.techniques = [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + new ShaderContractID("tests.surface"), + [new ShaderTechniquePass(new ShaderPassRoleID("tests.draw"), "Main")] + )]; SetDefinition(graph, definition); - byte[] bytes = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); + byte[] bytes = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); GraphDocument restored = ShaderGraphArtifact.ReadDocument(bytes, m_serialization); ShaderDefinition decoded = ShaderGraphDocument.ReadDefinition(restored, m_serialization, SerializationContext.empty); Assert.DoesNotContain(ShaderDefinitionValidator.Validate(decoded), static value => value.severity == DiagnosticSeverity.Error); @@ -108,26 +147,40 @@ public void GraphArtifactPreservesProviderOwnedContractAndRoleIdentifiers() public void GraphArtifactDetachesAuthoredDefinitionNodesAndConnections() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - byte[] committed = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); + byte[] committed = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); graph.RemoveNode(graph.nodes[0].id); GraphDocument restored = ShaderGraphArtifact.ReadDocument(committed, m_serialization); byte[] original = GraphDocumentCodec.Encode(restored, m_serialization); restored.nodes[0].position = new(123, 456); - restored.nodes[0].SetValue("unavailable.extension", new([1, 2, 3])); + restored.nodes[0].SetValue("unavailable.extension", new GraphSerializedValue([1, 2, 3])); Assert.Equal(original, GraphDocumentCodec.Encode(ShaderGraphArtifact.ReadDocument(committed, m_serialization), m_serialization)); } [Fact] public void GraphDefinitionPreservesPipelineOwnedStorageTextureContract() { - var property = new ShaderPropertyDefinition(new("outputImage"), "Output Image", ShaderPropertyType.Texture2D, - ShaderStage.Compute, default, ShaderPropertyBindingKind.StorageTexture, RenderStorageAccess.ReadWrite, ShaderPropertyBindingOwner.RenderPass); - var pass = new ShaderPassDefinition("Compute", ShaderProgramKind.Compute, - requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageTexture); + var property = new ShaderPropertyDefinition( + new ShaderPropertyID("outputImage"), + "Output Image", + ShaderPropertyType.Texture2D, + ShaderStage.Compute, + default, + ShaderPropertyBindingKind.StorageTexture, + RenderStorageAccess.ReadWrite, + ShaderPropertyBindingOwner.RenderPass + ); + var pass = new ShaderPassDefinition( + "Compute", + ShaderProgramKind.Compute, + requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageTexture + ); var definition = new ShaderDefinition("Tests/Storage", [property], [], [pass]); GraphDocument graph = ShaderGraphDocument.Create(definition, m_serialization, SerializationContext.empty); - ShaderDefinition restored = ShaderGraphDocument.ReadDefinition(GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization), - m_serialization, SerializationContext.empty); + ShaderDefinition restored = ShaderGraphDocument.ReadDefinition( + GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization), + m_serialization, + SerializationContext.empty + ); Assert.DoesNotContain(ShaderDefinitionValidator.Validate(restored), static value => value.severity == DiagnosticSeverity.Error); ShaderPropertyDefinition binding = Assert.Single(restored.properties); Assert.Equal(ShaderPropertyBindingKind.StorageTexture, binding.bindingKind); @@ -136,7 +189,18 @@ public void GraphDefinitionPreservesPipelineOwnedStorageTextureContract() Assert.Equal(ShaderProgramKind.Compute, Assert.Single(restored.passes).programKind); } - private void SetDefinition(GraphDocument graph, ShaderDefinition definition) - => graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); - public void Dispose() { m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + public void Dispose() + { + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } + + private void SetDefinition( + GraphDocument graph, + ShaderDefinition definition + ) => graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs index 8a89f456c..c2035170a 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs @@ -1,18 +1,18 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.IO; using System.Collections.Generic; +using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; -using Inno.Rendering.Shaders; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -26,7 +26,9 @@ public sealed class ShaderPublicationTests : IDisposable public ShaderPublicationTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderPublicationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderPublicationTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -82,12 +84,12 @@ public void ShaderGraphRetainsCanonicalInputWhenTheAuthoringDefinitionIsEdited() { ShaderDefinition definition = CreateDefinition(); GraphDocument graph = ShaderGraphDocument.Create(definition, m_serialization, SerializationContext.empty); - byte[] committed = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); + byte[] committed = ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization); Mutate(definition); Mutate(ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty)); AssertOriginal(ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty)); - Assert.Equal(committed, ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization)); + Assert.Equal(committed, ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization)); GraphDocument restored = ShaderGraphArtifact.ReadDocument(committed, m_serialization); Mutate(ShaderGraphDocument.ReadDefinition(restored, m_serialization, SerializationContext.empty)); AssertOriginal(ShaderGraphDocument.ReadDefinition(restored, m_serialization, SerializationContext.empty)); @@ -101,7 +103,7 @@ public void MaterialSelectionAndResolvedPassDoNotPublishTheirMetadataArrays() RenderMaterialPass materialPass = MaterialProvider.Capture(definition.passes[0]); Mutate(definition); - resolution.technique.passes[0] = new ShaderTechniquePass(new ShaderPassRoleId("other"), "other"); + resolution.technique.passes[0] = new ShaderTechniquePass(new ShaderPassRoleID("other"), "other"); resolution.pass.metadata[0] = new ShaderMetadataEntry("sort", "changed"); materialPass.definition.metadata[0] = new ShaderMetadataEntry("sort", "changed"); @@ -112,14 +114,27 @@ public void MaterialSelectionAndResolvedPassDoNotPublishTheirMetadataArrays() } private static ShaderDefinition CreateDefinition() - => new("Original", - [new ShaderPropertyDefinition(new ShaderPropertyId("value"), "Value", ShaderPropertyType.Float, - ShaderStage.Fragment, MaterialValue.FromFloat(1))], + => new( + "Original", + [new ShaderPropertyDefinition( + new ShaderPropertyID("value"), + "Value", + ShaderPropertyType.Float, + ShaderStage.Fragment, + MaterialValue.FromFloat(1) + )], [new ShaderKeywordDefinition("quality", ["high"])], - [new ShaderPassDefinition("main", ShaderProgramKind.Raster, - metadata: [new ShaderMetadataEntry("sort", "opaque")])], - [new ShaderTechniqueDefinition(new ShaderTechniqueId("default"), new ShaderContractId("test.draw"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), "main")])]); + [new ShaderPassDefinition( + "main", + ShaderProgramKind.Raster, + metadata: [new ShaderMetadataEntry("sort", "opaque")] + )], + [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + new ShaderContractID("test.draw"), + [new ShaderTechniquePass(new ShaderPassRoleID("draw"), "main")] + )] + ); private static void Mutate(ShaderDefinition definition) { @@ -127,7 +142,7 @@ private static void Mutate(ShaderDefinition definition) definition.properties[0].displayName = "Changed"; definition.keywords[0].options[0] = "low"; definition.passes[0].metadata[0] = new ShaderMetadataEntry("sort", "changed"); - definition.techniques[0].passes[0] = new ShaderTechniquePass(new ShaderPassRoleId("other"), "other"); + definition.techniques[0].passes[0] = new ShaderTechniquePass(new ShaderPassRoleID("other"), "other"); } private static void AssertOriginal(ShaderDefinition definition) diff --git a/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs b/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs index 04da441bf..62a8e18c0 100644 --- a/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs @@ -1,5 +1,5 @@ -using Inno.Core.Mathematics; using Xunit; +using Inno.Core.Mathematics; namespace Inno.Rendering.Assets.Tests; @@ -8,8 +8,12 @@ public sealed class GeometryArtifactTests [Fact] public void RuntimeGeometryDecodesWithoutAnImporterOrRenderDevice() { - var vertex = new GeometryVertex(new Vector3(1, 2, 3), new Vector3(0, 1, 0), - new Vector4(1, 0, 0, 1), new Vector2(0.5f, 0.25f)); + var vertex = new GeometryVertex( + new Vector3(1, 2, 3), + new Vector3(0, 1, 0), + new Vector4(1, 0, 0, 1), + new Vector2(0.5f, 0.25f) + ); var data = new GeometryData([vertex, vertex, vertex], [0, 1, 2], [new GeometrySection(0, 3)]); GeometryData decoded = GeometryArtifact.Decode(GeometryArtifact.Encode(data)); Assert.Equal(data.vertices, decoded.vertices); diff --git a/tests/rendering/Inno.Rendering.Assets.Tests/MaterialContractTests.cs b/tests/rendering/Inno.Rendering.Assets.Tests/MaterialContractTests.cs index e44efa3c1..0cf356741 100644 --- a/tests/rendering/Inno.Rendering.Assets.Tests/MaterialContractTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Tests/MaterialContractTests.cs @@ -8,7 +8,7 @@ public sealed class MaterialContractTests public void FrameOverridesContainOnlyLogicalValuesAndCanBeCleared() { var block = new MaterialPropertyBlock(); - var id = new ShaderPropertyId("amount"); + var id = new ShaderPropertyID("amount"); block.Set(id, MaterialValue.FromFloat(0.5f)); Assert.True(block.TryGet(id, out MaterialValue value)); Assert.Equal(MaterialValueKind.Float, value.kind); diff --git a/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs b/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs index a5368ba3e..cdafde86b 100644 --- a/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs @@ -1,10 +1,10 @@ using System; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Rendering.Assets.Tests; @@ -18,10 +18,10 @@ public void MovedPersistentTypesKeepTheirRecordedIdentity() catalogSource = new DotNetAssemblyCatalogSource(typeof(RuntimeAssetSerializationTests).Assembly) }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - Assert.Equal(Guid.Parse("5bce7c89-203f-5921-8efc-1bca0f364943"), types.GetTypeRef(typeof(ShaderDefinition)).stableId); - Assert.Equal(Guid.Parse("0f50b92b-4d4b-55f8-a954-953630083303"), types.GetTypeRef(typeof(ShaderPassDefinition)).stableId); - Assert.Equal(Guid.Parse("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f"), types.GetTypeRef(typeof(MaterialValue)).stableId); - Assert.Equal(Guid.Parse("a9af9e77-9a97-5f66-82a0-d720ac5604dc"), types.GetTypeRef(typeof(MaterialValueKind)).stableId); + Assert.Equal(Guid.Parse("5bce7c89-203f-5921-8efc-1bca0f364943"), types.GetTypeRef(typeof(ShaderDefinition)).stableID); + Assert.Equal(Guid.Parse("0f50b92b-4d4b-55f8-a954-953630083303"), types.GetTypeRef(typeof(ShaderPassDefinition)).stableID); + Assert.Equal(Guid.Parse("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f"), types.GetTypeRef(typeof(MaterialValue)).stableID); + Assert.Equal(Guid.Parse("a9af9e77-9a97-5f66-82a0-d720ac5604dc"), types.GetTypeRef(typeof(MaterialValueKind)).stableID); } [Fact] @@ -33,9 +33,16 @@ public void ShaderDeclarationsRoundTripThroughTheCommonSerializationContract() }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - var definition = new ShaderDefinition("Fixture", [], [], - [new ShaderPassDefinition("color", ShaderProgramKind.Raster, - metadata: [new ShaderMetadataEntry("fixture", "value")])]); + var definition = new ShaderDefinition( + "Fixture", + [], + [], + [new ShaderPassDefinition( + "color", + ShaderProgramKind.Raster, + metadata: [new ShaderMetadataEntry("fixture", "value")] + )] + ); byte[] bytes = serialization.Serialize(definition); ShaderDefinition decoded = serialization.Deserialize(bytes); Assert.Equal(definition.name, decoded.name); diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs index 4d9f58159..bce5c738d 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs @@ -1,15 +1,14 @@ -using Inno.Content.Testing; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Content.Testing; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; - -using Inno.Core.Identity; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Runtime; @@ -20,16 +19,19 @@ public sealed class ContentRenderTargetArtifactProviderTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoRenderTargetArtifactProviderTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; public ContentRenderTargetArtifactProviderTests() { - m_modules = new(new() + m_modules = new(new ModuleHostOptions() { - catalogSource = new DotNetAssemblyCatalogSource(typeof(ContentRenderTargetArtifactProviderTests).Assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(typeof(ContentRenderTargetArtifactProviderTests).Assembly) + }); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -40,21 +42,17 @@ public void TextureTargetArtifactLoadsWithoutAnyAuthoringSourceMount() Directory.CreateDirectory(m_root); var identities = new IdentityAllocator(); var texture = new TextureAsset(1, 1, TextureColorSpace.Srgb, "png"); - Guid persistentId = Guid.NewGuid(); - identities.InitializePersistentIdentity(texture, persistentId); + Guid persistentID = Guid.NewGuid(); + identities.InitializePersistentIdentity(texture, persistentID); RenderTextureArtifactReference reference = texture.GetTextureArtifactReference(); - string artifactPath = Path.Combine( - m_root, - RenderTargetArtifactPath.GetTexturePath(reference)); + string artifactPath = Path.Combine(m_root, RenderTargetArtifactPath.GetTexturePath(reference)); Directory.CreateDirectory(Path.GetDirectoryName(artifactPath)!); byte[] expected = [0xAB, 0x4B, 0x54, 0x58]; File.WriteAllBytes(artifactPath, expected); using ContentTestStore content = ContentTestStore.FromDirectory(m_root); var provider = new ContentRenderTargetArtifactProvider(content, m_serialization, SerializationContext.empty); - RenderTargetArtifactStatus status = provider.GetTextureArtifact( - reference, - out ReadOnlyMemory artifact); + RenderTargetArtifactStatus status = provider.GetTextureArtifact(reference, out ReadOnlyMemory artifact); Assert.Equal(RenderTargetArtifactStatus.Ready, status); Assert.Equal(expected, artifact.ToArray()); @@ -72,9 +70,7 @@ public void MissingDeployedTextureArtifactIsReportedAsUnavailable() using ContentTestStore content = ContentTestStore.FromDirectory(m_root); var provider = new ContentRenderTargetArtifactProvider(content, m_serialization, SerializationContext.empty); - RenderTargetArtifactStatus status = provider.GetTextureArtifact( - reference, - out ReadOnlyMemory artifact); + RenderTargetArtifactStatus status = provider.GetTextureArtifact(reference, out ReadOnlyMemory artifact); Assert.Equal(RenderTargetArtifactStatus.Unavailable, status); Assert.True(artifact.IsEmpty); @@ -84,20 +80,17 @@ public void MissingDeployedTextureArtifactIsReportedAsUnavailable() public void IndependentTextureSlotsUseStableDistinctDeploymentPaths() { Directory.CreateDirectory(m_root); - Guid assetId = Guid.NewGuid(); + Guid assetID = Guid.NewGuid(); var firstSlot = new RenderTextureArtifactSlot("page-a", "texture-page-a", TextureColorSpace.Srgb); var secondSlot = new RenderTextureArtifactSlot("page-b", "texture-page-b", TextureColorSpace.Linear); - var first = new RenderTextureArtifactReference(assetId, 4, firstSlot); - var second = new RenderTextureArtifactReference(assetId, 4, secondSlot); + var first = new RenderTextureArtifactReference(assetID, 4, firstSlot); + var second = new RenderTextureArtifactReference(assetID, 4, secondSlot); string firstRelativePath = RenderTargetArtifactPath.GetTexturePath(first); string secondRelativePath = RenderTargetArtifactPath.GetTexturePath(second); Assert.NotEqual(firstRelativePath, secondRelativePath); Assert.Equal(firstRelativePath, RenderTargetArtifactPath.GetTexturePath(first)); - Assert.StartsWith( - "TargetArtifacts/Textures/" + $"{assetId:D}/", - firstRelativePath, - StringComparison.Ordinal); + Assert.StartsWith("TargetArtifacts/Textures/" + $"{assetID:D}/", firstRelativePath, StringComparison.Ordinal); string firstPath = Path.Combine(m_root, firstRelativePath); string secondPath = Path.Combine(m_root, secondRelativePath); @@ -119,6 +112,8 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs index f410dee7f..163035f54 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs @@ -1,26 +1,6 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Extensibility.Reload; -using Inno.Adapter.Modules.DotNet; -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Inno.Assets; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; -using Inno.Rendering; using Xunit; using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Rendering.Runtime.Tests; @@ -30,13 +10,19 @@ public sealed class EmptyRenderingKernelTests public void OutputRouteAssignsEachWorldContentSourceOnlyOnce() { Assert.Throws(() => new RenderOutputRoute( - [new RenderOutputLayer("model-a", ["canvas"]), - new RenderOutputLayer("model-b", ["canvas"])])); + [ + new RenderOutputLayer("model-a", ["canvas"]), + new RenderOutputLayer("model-b", ["canvas"]) + ] + )); var route = new RenderOutputRoute( - [new RenderOutputLayer("model-a", ["canvas"]), - new RenderOutputLayer("model-b", [])]); - Assert.Equal("canvas", Assert.Single(route.layers[0].sourceIds)); - Assert.Empty(route.layers[1].sourceIds); + [ + new RenderOutputLayer("model-a", ["canvas"]), + new RenderOutputLayer("model-b", []) + ] + ); + Assert.Equal("canvas", Assert.Single(route.layers[0].sourceIDs)); + Assert.Empty(route.layers[1].sourceIDs); } [Theory] @@ -54,2265 +40,11 @@ public void ProductionRenderingAssemblyDoesNotDeclareConcreteRenderingWorldviews [Fact] public void OpenShaderProtocolsRemainBackendNeutral() { - Type[] publicTypes = typeof(ShaderContractId).Assembly.GetExportedTypes(); - Assert.DoesNotContain(publicTypes, static type => - type.FullName?.Contains("Bgfx", StringComparison.OrdinalIgnoreCase) == true); - Assert.Contains(publicTypes, static type => type == typeof(ShaderContractId)); - Assert.Contains(publicTypes, static type => type == typeof(ShaderPassRoleId)); - } -} - -public sealed partial class RenderRuntimeGenerationTests : IDisposable -{ - private readonly string m_cacheDirectory = Path.Combine( - Path.GetTempPath(), - "InnoRenderRuntimeTests", - Guid.NewGuid().ToString("N")); - private readonly IdentityAllocator m_identities; - private readonly IDisposable m_identityScope; - private readonly ModuleHost m_modules; - private readonly TypeCatalog m_types; - private readonly SerializationRegistry m_serialization; - - public RenderRuntimeGenerationTests() - { - _ = typeof(TextureAsset); - m_identities = new IdentityAllocator(); - m_identityScope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)}); - m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); - ResourceProbePipeline.action = null; - DisposablePipeline.Reset(); - PendingFeature.Reset(); - TestRequestProvider.Reset(); - FirstTestRenderModel.Reset(); - SecondTestRenderModel.Reset(); - CompositionLayerPipeline.viewports.Clear(); - UploadPipeline.Reset(); - TexturePrewarmPipeline.texture = null; - PendingShaderPipeline.Reset(); - ReadbackPipeline.Reset(); - PresentationPipeline.Reset(); - } - - public void Dispose() - { - ResourceProbePipeline.action = null; - m_serialization.Dispose(); - m_types.Dispose(); - m_modules.Dispose(); - m_identityScope.Dispose(); - if (Directory.Exists(m_cacheDirectory)) - Directory.Delete(m_cacheDirectory, recursive: true); - } - - [Fact] - public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterPartialAllocationFailure() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink()); - var owner = new AssetRuntimeOwner(); - var geometry = new GeometryAsset(3, 3, 1, default, default); - m_identities.Register(geometry); - byte[] bytes = GeometryArtifact.Encode(new GeometryData( - [new(default, default, default, default), new(default, default, default, default), new(default, default, default, default)], - [0, 1, 2], [new GeometrySection(0, 3)])); - owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "first", bytes, false, 1); - RenderGeometry? first = null; - ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out first); - RunResourceFrame(runtime); - Assert.NotNull(first); - Assert.Equal(2, device.createdBuffers.Count); - device.failBufferCreationAt = 4; - owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "second", bytes, false, 2); - RenderGeometry? failed = null; - ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out failed); - RunResourceFrame(runtime); - Assert.NotNull(failed); - Assert.Equal(first!.vertexBuffer, failed!.vertexBuffer); - Assert.Equal(first.indexBuffer, failed.indexBuffer); - Assert.Equal(device.createdBuffers[2], Assert.Single(device.destroyedBuffers)); - device.failBufferCreationAt = 0; - RunResourceFrame(runtime); - Assert.NotEqual(first.vertexBuffer, failed.vertexBuffer); - Assert.NotEqual(first.indexBuffer, failed.indexBuffer); - Assert.Equal(3, device.destroyedBuffers.Count); - runtime.Dispose(); - Assert.Equal(device.createdBuffers.Count, device.destroyedBuffers.Count); - owner.Release(geometry); - m_identities.Unregister(geometry); - ResourceProbePipeline.action = null; - } - - [Fact] - public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 }); - var descriptor = new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 4, RenderBufferUsage.Storage)); - int rejected = 0; - for (int frame = 0; frame < 256; frame++) - { - long revision = frame; - ResourceProbePipeline.action = resources => - { - _ = resources.AcquireBuffer(new RenderPersistentResourceId("owned"), revision, descriptor, new byte[16], "owned"); - try { resources.AcquireBuffer(new RenderPersistentResourceId("overflow"), revision, descriptor, new byte[16], "overflow"); } - catch (InvalidOperationException) { rejected++; } - }; - RunResourceFrame(runtime); - Assert.Equal(1, runtime.resourceStatistics.activeResources); - } - Assert.Equal(256, rejected); - Assert.Equal(256, runtime.resourceStatistics.rejectedResources); - runtime.Dispose(); - Assert.Equal(256, device.createdBuffers.Count); - Assert.Equal(256, device.destroyedBuffers.Count); - ResourceProbePipeline.action = null; - } - - [Fact] - public async Task ReadbackAdmissionIsRejectedBeforeAllocatingASecondNativeOperation() - { - var device = new RecordingRenderDevice(supportsReadback: true); - using var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 }); - Task? readback = null; - bool rejected = false; - ResourceProbePipeline.action = resources => - { - readback = resources.ReadTextureAsync(device.textureHandle).AsTask(); - try { _ = resources.ReadTextureAsync(device.textureHandle); } - catch (InvalidOperationException) { rejected = true; } - }; - RunResourceFrame(runtime); - ResourceProbePipeline.action = null; - Assert.True(rejected); - Assert.Equal(1, runtime.resourceStatistics.pendingReadbacks); - Assert.Equal(1, runtime.resourceStatistics.rejectedReadbacks); - runtime.Dispose(); - await Assert.ThrowsAsync(() => readback!); - Assert.Equal(1, device.cancelReadbackCount); - } - - private static void RunResourceFrame(RenderRuntime runtime) - { - runtime.Submit(CreateRequest("Resource ownership", new RenderPipelineAsset { pipelineTypeId = ResourceProbePipeline.extensionId })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - } - - [RenderPipelineExtension(extensionId)] - private sealed class ResourceProbePipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.resource-owner"; - internal static Action? action; - public override void Build(RenderPipelineContext context) - { - action?.Invoke(context.resourceService); - context.graph.AddRasterPass("Resources", new RenderPhaseId("tests.resources"), 0, static (_, _) => { }).HasSideEffect(); - } - } - - [Fact] - public void SuccessfulTypeCacheChangeRetiresUnrequestedPipelineAtFrameBoundary() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId }; - - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - Assert.Equal(1, DisposablePipeline.createdCount); - Assert.Equal(0, DisposablePipeline.disposedCount); - - m_types.Rebuild(); - BeginRenderFrame(runtime, 0f); - - Assert.Equal(1, DisposablePipeline.disposedCount); - - runtime.AfterRender(default); - runtime.EndFrame(default); - runtime.Detach(); - } - - [Fact] - public void PendingProviderRetirementIsRetriedBeforeTheSnapshotIsReleased() - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId })); - TestRequestProvider.pendingRetirements = 2; - - m_types.Rebuild(); - - Assert.Equal(3, TestRequestProvider.retirementAttempts); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId })); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool duplicate) - { - var contributor = new SideEffectContributor(); - IRenderFrameGraphContributor[] contributors = duplicate ? [contributor, contributor] : [null!]; - Assert.Throws(() => new RenderRuntime( - m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink(), contributors)); - m_types.Rebuild(); - Assert.Equal(0, TestRequestProvider.retirementAttempts); - } - - [Fact] - public void PendingFeatureRetirementKeepsItsPipelineAliveUntilQuiescent() - { - var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset - { - pipelineTypeId = DisposablePipeline.extensionId, - features = [new RenderFeatureConfiguration(PendingFeature.extensionId)] - })); - PendingFeature.pendingRetirements = 2; - DisposablePipeline.pendingRetirements = 1; - - runtime.Dispose(); - runtime.Dispose(); - - Assert.Equal(3, PendingFeature.retirementAttempts); - Assert.Equal(2, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - Assert.Equal(1, device.endFrameCount); - Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); - } - - [Fact] - public void RejectedPipelineWaitsForItsCandidateToRetireBeforeKeepingLastGood() - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId }; - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - DisposablePipeline.rejectConfiguration = true; - DisposablePipeline.pendingRetirements = 2; - asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); - - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - - Assert.Equal(3, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - DisposablePipeline.rejectConfiguration = false; - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ReloadRetirementDrainsPendingBeforeFinishingTheTransaction(bool commit) - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId })); - IRenderRuntimeReloadTransaction transaction = runtime.BeginExtensionReload(); - transaction.Prepare(); - transaction.Activate(); - DisposablePipeline.pendingRetirements = 2; - - if (commit) - transaction.Complete(); - else - transaction.Rollback(); - - Assert.Equal(3, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - runtime.BeginExtensionReload().Rollback(); - } - - [Fact] - public void TargetCapacityRejectsBeforeNativeAllocationAndReopensAfterRelease() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var targets = new RenderTargetStore(backend, capacity: 1); - backend.BeginFrame(); - var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment); - var first = new RenderTexture("First", descriptor); - var second = new RenderTexture("Second", descriptor); - var graph = new RenderGraphBuilder(1, backend.capabilities); - targets.Import(graph, first); - Assert.Throws(() => targets.Import(graph, second)); - Assert.Single(device.createdTextures); - Assert.Equal(1, targets.rejectedCount); - targets.Release(first); - targets.PrepareFrame(); - targets.Import(new RenderGraphBuilder(2, backend.capabilities), second); - Assert.Equal(1, targets.count); - targets.Dispose(); - Assert.Equal(device.createdTextures.Count, device.destroyedTextures.Count); - backend.EndFrame(); - } - - [Fact] - public void UploadAdmissionResetsEachFrameWithoutGrowingResidentPages() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), resourceLimits: - new RenderResourceLimits { uploadPages = 1, uploadResidentBytes = 4096, uploadBytesPerFrame = 36 }); - for (int frame = 0; frame < 256; frame++) - { - runtime.Submit(CreateRequest("Upload budget", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.extensionId })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, runtime.resourceStatistics.uploadPages); - Assert.Equal(36, runtime.resourceStatistics.uploadedFrameBytes); - } - Assert.Equal(256, runtime.resourceStatistics.rejectedUploads); - Assert.Single(device.createdBuffers); - runtime.Dispose(); - Assert.Single(device.destroyedBuffers); - } - - [Fact] - public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var targets = new RenderTargetStore(device); - device.BeginFrame(); - var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment); - var graph = new RenderGraphBuilder(1, device.capabilities); - targets.Import(graph, new RenderTexture("First", descriptor)); - targets.Import(graph, new RenderTexture("Second", descriptor)); - targets.Import(graph, new RenderTexture("Third", descriptor)); - proxy.failFirstTextureRetirement = true; - proxy.pendingTextureRetirement = proxy.createdTextures[1]; - - Assert.Throws(targets.Dispose); - Assert.Equal(2, proxy.textureRetirementAttempts); - Assert.True(proxy.frameOpen); - Assert.Throws(() => targets.Import(graph, new RenderTexture("Late", descriptor))); - Assert.Throws(targets.Dispose); - Assert.Equal(4, proxy.textureRetirementAttempts); - Assert.Equal(proxy.createdTextures.Skip(1), proxy.destroyedTextures); - targets.Dispose(); - Assert.Equal(4, proxy.textureRetirementAttempts); - device.EndFrame(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(bool duringFrame) - { - var modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) }); - var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - var runtime = new RenderRuntime(types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId }; - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - DisposablePipeline.retirementExpired = true; - try - { - if (duringFrame) - { - asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); - DisposablePipeline.rejectConfiguration = true; - runtime.Submit(CreateRequest("Faulting candidate", asset)); - BeginRenderFrame(runtime, 0f); - Assert.Throws(() => runtime.AfterRender(default)); - Assert.True(device.frameOpen); - } - else - Assert.Throws(runtime.Dispose); - Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); - Assert.Throws(() => runtime.RegisterContributor(new SideEffectContributor())); - Assert.Throws(() => runtime.BeginExtensionReload()); - Assert.ThrowsAny(() => types.Rebuild()); - Assert.Equal(1, DisposablePipeline.retirementAttempts); - Assert.Equal(0, TestRequestProvider.retirementAttempts); - Assert.Equal(0, device.endFrameCount); - - DisposablePipeline.retirementExpired = false; - Assert.ThrowsAny(runtime.Dispose); - Assert.ThrowsAny(types.Dispose); - Assert.ThrowsAny(modules.Dispose); - Assert.Equal(1, DisposablePipeline.retirementAttempts); - Assert.Equal(0, device.endFrameCount); - } - finally - { - DisposablePipeline.retirementExpired = false; - DisposablePipeline.rejectConfiguration = false; - } - } - - [Fact] - public void RuntimeKeepsItsMaintenanceFrameOpenUntilTargetsFinishRetiring() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var target = new RenderTexture("Pending Target", new RenderTextureDescriptor( - 16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment)); - runtime.Submit(new RenderRequest("Target", RenderTarget.FromTexture(target), - new RenderViewport(0, 0, 16, 16), new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - proxy.pendingTextureRetirement = Assert.Single(proxy.createdTextures); - - runtime.Dispose(); - - Assert.Equal(2, proxy.textureRetirementAttempts); - Assert.Single(proxy.destroyedTextures); - Assert.False(proxy.frameOpen); - Assert.Equal(2, proxy.endFrameCount); - } - - [Fact] - public void RemovingAndRestoringPluginRenderingCommitsTheSameUnavailableStateAsColdStart() - { - const string extensionId = "tests.runtime.reloadable-plugin"; - DotNetModuleSource plugin = CreateRenderingPluginRequest(); - AssemblyModuleHandle activeModule = m_modules.Load(plugin); - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, device, diagnostics); - var asset = new RenderPipelineAsset { pipelineTypeId = extensionId }; - var featureAsset = new RenderPipelineAsset - { - pipelineTypeId = SideEffectPipeline.extensionId, - features = [new RenderFeatureConfiguration("tests.runtime.reloadable-plugin-feature")] - }; - - runtime.Submit(CreateRequest("Before Removal", asset)); - runtime.Submit(CreateRequest("Feature Before Removal", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, proxy.executeCount); - proxy.ReleaseRecordedGraph(); - - QueueCollectiblePayload(runtime, m_types, asset); - (IAssemblyUnloadProbe removalMonitor, IRenderRuntimeReloadTransaction renderingRemoval) = - RemoveRenderingPlugin(runtime, m_modules, plugin); - - ForceCollection(); - Assert.True(removalMonitor.isCompleted); - GC.KeepAlive(renderingRemoval); - - runtime.Submit(CreateRequest("While Unavailable", asset)); - runtime.Submit(CreateRequest("Feature While Unavailable", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, proxy.executeCount); - Assert.DoesNotContain( - diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED"); - - IRenderRuntimeReloadTransaction renderingRecovery = runtime.BeginExtensionReload(); - using (AssemblyReloadSession recovery = m_modules.BeginReload([plugin])) - { - activeModule = recovery.context.module; - recovery.Activate(); - renderingRecovery.Prepare(); - renderingRecovery.Activate(); - _ = recovery.Complete(); - renderingRecovery.Complete(); - } - - runtime.Submit(CreateRequest("After Recovery", asset)); - runtime.Submit(CreateRequest("Feature After Recovery", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(2, proxy.executeCount); - - proxy.ReleaseRecordedGraph(); - runtime.Detach(); - IAssemblyUnloadProbe recoveryMonitor = m_modules.Unload(activeModule); - ForceCollection(); - Assert.True(recoveryMonitor.isCompleted); - } - - [Fact] - public void RemovingUnusedRenderingPluginReleasesItsAssemblyContext() - { - DotNetModuleSource plugin = CreateRenderingPluginRequest(); - _ = m_modules.Load(plugin); - IAssemblyUnloadProbe monitor = RemoveUnusedPlugin(m_modules, plugin); - - ForceCollection(); - - Assert.True(monitor.isCompleted); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void FrameStatisticsReportBackendCommandsAndGraphCulling(bool reportsAllocations) - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.frameCounters = new RenderDeviceFrameCounters(3, 2); - proxy.allocationCounters = reportsAllocations - ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) - : null; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - using IDisposable executionScope = runtime.EnterExecutionScope(); - var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.extensionId }; - runtime.Attach(); - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - runtime.Submit(new RenderRequest( - "Statistics", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - RenderFrameStatistics statistics = Assert.IsType(GraphicsSettings.frameStatistics); - Assert.Equal(1, statistics.viewCount); - Assert.Equal(3, statistics.drawCount); - Assert.Equal(2, statistics.dispatchCount); - Assert.Equal(1, statistics.culledPassCount); - Assert.Equal(proxy.allocationCounters, statistics.allocationCounters); - proxy.allocationCounters = new RenderDeviceAllocationCounters(device.generation, 19, 25, 13); - Assert.NotEqual(proxy.allocationCounters, statistics.allocationCounters); - runtime.Detach(); - } - - [Fact] - public void DeviceSynchronizationIsRequiredAndUnsupportedDiagnosticsAreExplicitlyUnavailable() - { - Assert.True(typeof(IRenderDevice).GetMethod(nameof(IRenderDevice.SetVerticalSync))!.IsAbstract); - using var backend = new RecordingRenderDevice(); - IRenderDevice device = backend; - device.SetVerticalSync(true); - Assert.True(backend.verticalSync); - device.SetVerticalSync(false); - Assert.False(backend.verticalSync); - Assert.Null(device.allocationCounters); - Assert.Throws(() => new RenderDeviceAllocationCounters(0, 0, 0, 0)); - } - - [Fact] - public void GraphicsFacadeResolvesTheCurrentlyBoundRenderingRuntime() - { - IRenderDevice firstDevice = TestDeviceProxy.Create(out TestDeviceProxy firstProxy); - IRenderDevice secondDevice = TestDeviceProxy.Create(out TestDeviceProxy secondProxy); - firstProxy.frameCounters = new RenderDeviceFrameCounters(2, 0); - secondProxy.frameCounters = new RenderDeviceFrameCounters(7, 1); - using var first = new RenderRuntime(m_types, firstDevice, new TestDiagnosticSink()); - using var second = new RenderRuntime(m_types, secondDevice, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.extensionId }; - - using (first.EnterExecutionScope()) - { - first.Attach(); - Assert.True(first.TryActivateDefaultPipeline(asset)); - first.Submit(CreateRequest("First Runtime", asset)); - BeginRenderFrame(first, 0f); - first.AfterRender(default); - first.EndFrame(default); - Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - - using (second.EnterExecutionScope()) - { - second.Attach(); - Assert.True(second.TryActivateDefaultPipeline(asset)); - second.Submit(CreateRequest("Second Runtime", asset)); - BeginRenderFrame(second, 0f); - second.AfterRender(default); - second.EndFrame(default); - Assert.Equal(7, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - } - - Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - } - - Assert.Null(GraphicsSettings.frameStatistics); - Assert.Throws(() => GraphicsSettings.defaultPipeline = asset); - second.Detach(); - first.Detach(); - } - - [Fact] - public void RequestProviderProducesCurrentFrameWorkThroughPublicPluginApi() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId }; - TestRequestProvider.pipeline = asset; - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Attach(); - - BeginRenderFrame(runtime, 1f / 60f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, TestRequestProvider.submitCount); - Assert.Equal(1, proxy.executeCount); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Request[0] Provider Request/Visible", pass.name); - runtime.Detach(); - } - - [Fact] - public void RequestProviderReceivesExplicitHostContentScope() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - Guid contentId = Guid.Parse("3aee0ced-b598-4366-ab45-a6ef8e0feb30"); - var content = new TestContent(); - var identities = new IdentityAllocator(); - identities.Register(content, contentId); - var scope = new ContentReadScope([content.identity], contentId); - Assert.True(scope.TryGetValue(contentId, out TestContent? resolved)); - Assert.Same(content, resolved); - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - contentScopeProvider: () => scope); - runtime.Attach(); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Same(scope, TestRequestProvider.lastContent); - Assert.Throws(() => scope.TryGetValue(contentId, out TestContent? _)); - runtime.Detach(); - } - - [Fact] - public void PrimaryPresentationViewportIsSharedAndLetterboxSurfaceIsCleared() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.presentationSize = new RenderPresentationSize(1000, 1000); - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - primaryPresentationViewportProvider: static size => new RenderViewport( - 0, - (size.height - 562) / 2, - size.width, - 562)); - runtime.Attach(); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new RenderViewport(0, 219, 1000, 562), TestRequestProvider.lastPresentationViewport); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Primary Presentation Background", pass.name); - Assert.True(pass.clearsPresentationTarget); - Assert.Equal(new RenderClearColor(0f, 0f, 0f, 1f), pass.presentationClearColor); - runtime.Detach(); - } - - [Fact] - public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.presentationSize = new RenderPresentationSize(2560, 1440); - TestRequestProvider.enabled = true; - var snapshot = new Inno.Input.InputSnapshot(1, - mousePosition: new Inno.Core.Mathematics.Vector2(400f, 274f), - mouseButtonsPressed: [Inno.Core.Input.MouseButton.Left]); - using var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), - inputSnapshotProvider: () => snapshot, - primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720)); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new Inno.Core.Mathematics.Vector2(800f, 548f), - TestRequestProvider.lastInput.pointerPosition); - Assert.Single(TestRequestProvider.lastInput.buttonsPressed); - } - - [Fact] - public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - proxy.capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), Enum.GetValues(), - Enum.GetValues(), [], [], originBottomLeft: false, - homogeneousDepth: false); - proxy.presentationSize = new RenderPresentationSize(1000, 1000); - FirstTestRenderModel.enabled = true; - SecondTestRenderModel.enabled = true; - using var runtime = new RenderRuntime(m_types, device, diagnostics, - primaryPresentationViewportProvider: static _ => new RenderViewport(100, 200, 800, 600), - compositionProgramProvider: new TestCompositionProgramProvider()); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(0, FirstTestRenderModel.buildCount); - Assert.Equal(0, SecondTestRenderModel.buildCount); - Assert.Contains(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("Multiple rendering models", StringComparison.Ordinal)); - - runtime.SetPrimaryRoute(new RenderOutputRoute( - [new RenderOutputLayer(SecondTestRenderModel.extensionId, []), - new RenderOutputLayer(FirstTestRenderModel.extensionId, [])])); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, FirstTestRenderModel.buildCount); - Assert.Equal(1, SecondTestRenderModel.buildCount); - Assert.Equal([new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], - CompositionLayerPipeline.viewports); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("independent model targets", StringComparison.Ordinal)); - Assert.True(diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), - string.Join("\n", diagnostics.items.Select(item => item.message))); - Assert.True(proxy.lastGraph is not null, - string.Join("\n", diagnostics.items.Select(item => item.message))); - Assert.Contains(proxy.lastGraph.passes, - pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); - runtime.Detach(); - } - - [Fact] - public void OutputWithoutAnApplicableModelReportsItsMissingRenderer() - { - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Contains(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("No rendering model", StringComparison.Ordinal)); - runtime.Detach(); - } - - [Fact] - public void LinearPresentationReceivesOneTransferAfterAllModelLayers() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.primaryPresentationEncodesSrgb = false; - proxy.presentationSize = new RenderPresentationSize(800, 600); - FirstTestRenderModel.enabled = true; - SecondTestRenderModel.enabled = true; - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime( - m_types, - device, - diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider()); - runtime.SetPrimaryRoute(new RenderOutputRoute( - [ - new RenderOutputLayer(FirstTestRenderModel.extensionId, []), - new RenderOutputLayer(SecondTestRenderModel.extensionId, []) - ])); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); - Assert.NotNull(proxy.lastGraph); - Assert.Single(proxy.lastGraph.passes.Where(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); - Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => - texture.name.EndsWith("/Composition", StringComparison.Ordinal) - && texture.descriptor.width == 800 - && texture.descriptor.height == 600 - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb); - runtime.Detach(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEncodesSrgb) - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.primaryPresentationEncodesSrgb = presentationEncodesSrgb; - proxy.presentationSize = new RenderPresentationSize(800, 600); - FirstTestRenderModel.enabled = true; - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime( - m_types, - device, - diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider()); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, FirstTestRenderModel.buildCount); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); - Assert.NotNull(proxy.lastGraph); - Assert.Equal(presentationEncodesSrgb ? 0 : 1, - proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); - Assert.DoesNotContain(proxy.lastGraph.textures, - texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal)); - if (!presentationEncodesSrgb) - { - Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => - texture.name.Contains("Model Layer 1", StringComparison.Ordinal) - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb); - } - runtime.Detach(); - } - - [Fact] - public void EditorOwnedOffscreenOutputsDoNotReportAnUnusedPrimaryModel() - { - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); - runtime.SetPrimaryModelOutputEnabled(false); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); - runtime.Detach(); - } - - [Fact] - public void MultipleRequestsAndContributorsCompileAndExecuteAsOneFrameGraph() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId }; - var contributor = new SideEffectContributor(); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), [contributor]); - runtime.Submit(CreateRequest("Second", asset, priority: 10)); - runtime.Submit(CreateRequest("First", asset, priority: -10)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, proxy.executeCount); - string[] names = Assert.IsType(proxy.lastGraph).passes - .Select(static pass => pass.name) - .ToArray(); - string[] expectedNames = - [ - "Request[0] First/Visible", - "Request[1] Second/Visible", - "Contributor[0] SideEffectContributor/Overlay" - ]; - Assert.Equal(expectedNames, names); - runtime.Detach(); - } - - [Fact] - public void OverlappingRequestsPreserveEarlierPresentationLayersInSchedulingOrder() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Overlay", asset, priority: 100)); - runtime.Submit(CreateRequest("Base", asset, priority: 0)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal( - new[] - { - new PresentationObservation("Base", false), - new PresentationObservation("Overlay", true) - }, - PresentationPipeline.observations); - Assert.Equal(1, proxy.executeCount); - runtime.Detach(); - } - - [Fact] - public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(new RenderRequest( - "Left", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 32, 64), - asset)); - runtime.Submit(new RenderRequest( - "Right", - RenderTarget.backbuffer, - new RenderViewport(32, 0, 32, 64), - asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal( - new[] - { - new PresentationObservation("Left", false), - new PresentationObservation("Right", false) - }, - PresentationPipeline.observations); - runtime.Detach(); - } - - [Fact] - public void FailedRequestDoesNotClaimThePresentationTarget() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.extensionId }; - var valid = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Failed", failed, priority: 0)); - runtime.Submit(CreateRequest("Recovery", valid, priority: 100)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal( - new[] { new PresentationObservation("Recovery", false) }, - PresentationPipeline.observations); - runtime.Detach(); - } - - [Fact] - public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrames() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var registry = new RenderTargetStore(device); - var target = new RenderTexture( - "Deferred Target", - new RenderTextureDescriptor( - 32, - 32, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = registry.Import(new RenderGraphBuilder(1, device.capabilities), target); - _ = device.EndFrame(); - PersistentTextureHandle first = Assert.Single(proxy.createdTextures); - - target.Resize(new RenderTextureDescriptor( - 64, - 64, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - device.BeginFrame(); - registry.PrepareFrame(); - _ = registry.Import(new RenderGraphBuilder(2, device.capabilities), target); - _ = device.EndFrame(); - PersistentTextureHandle second = proxy.createdTextures[1]; - Assert.Empty(proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - Assert.Empty(proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - Assert.Equal(new[] { first }, proxy.destroyedTextures); - - registry.Release(target); - for (int frame = 0; frame < 2; frame++) - { - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - } - Assert.Equal(new[] { first }, proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - registry.Dispose(); - _ = device.EndFrame(); - Assert.Equal(new[] { first, second }, proxy.destroyedTextures); - } - - [Fact] - public void DetachUsesADeviceSafetyFrameToReleaseResidentTargets() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId }; - var target = new RenderTexture( - "Detach Target", - new RenderTextureDescriptor( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment)); - runtime.Submit(new RenderRequest( - "Detach", - RenderTarget.FromTexture(target), - new RenderViewport(0, 0, 16, 16), - asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - PersistentTextureHandle resident = Assert.Single(proxy.createdTextures); - - runtime.Detach(); - - Assert.Equal(new[] { resident }, proxy.destroyedTextures); - Assert.False(proxy.frameOpen); - Assert.Equal(2, proxy.endFrameCount); - } - - [Fact] - public void FailedRequestRollsBackWithoutDiscardingOtherRequests() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.extensionId }; - var valid = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, diagnostics); - runtime.Submit(CreateRequest("A Failed", failed)); - runtime.Submit(CreateRequest("B Valid", valid)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, proxy.executeCount); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Request[1] B Valid/Visible", pass.name); - Assert.Contains(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.DoesNotContain(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); - runtime.Detach(); - } - - [Fact] - public void FrameUploadsReusePagesAndResetSliceOffsetsBetweenFrames() - { - var device = new RecordingRenderDevice(); - var asset = new RenderPipelineAsset { pipelineTypeId = UploadPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - - runtime.Submit(CreateRequest("Upload A", asset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.createBufferCount); - Assert.Equal(new[] { 0, 3 }, device.bufferUpdateOffsets.ToArray()); - Assert.Equal(0, UploadPipeline.firstSlice.firstElement); - Assert.Equal(3, UploadPipeline.secondSlice.firstElement); - Assert.Equal(3, UploadPipeline.secondSlice.elementCount); - - UploadPipeline.singleUpload = true; - runtime.Submit(CreateRequest("Upload B", asset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.createBufferCount); - Assert.Equal(new[] { 0, 3, 0 }, device.bufferUpdateOffsets.ToArray()); - Assert.Equal(0, UploadPipeline.firstSlice.firstElement); - runtime.Detach(); - } - - [Fact] - public void TexturePrewarmRunsOutsideTheRenderFrameAndDoesNotDelaySubmission() - { - var texture = new TextureAsset(1, 1, TextureColorSpace.Srgb, "png"); - Assert.True(m_identities.Register(texture)); - TexturePrewarmPipeline.texture = texture; - - var compiler = new DelayedTextureArtifactSource(); - var device = new RecordingRenderDevice(); - var asset = new RenderPipelineAsset { pipelineTypeId = TexturePrewarmPipeline.extensionId }; - var artifacts = new DelayedArtifactProvider(compiler); - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - targetArtifacts: artifacts); - runtime.Submit(CreateRequest("Prewarm", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.endFrameCount); - Assert.True(compiler.started.Wait(TimeSpan.FromSeconds(2))); - Assert.False(compiler.isCompleted); - compiler.Complete([1, 2, 3, 4]); - runtime.Detach(); - } - - [Fact] - public void PendingShaderCompilationDoesNotPublishAnUnavailableArtifactError() - { - var contract = new ShaderContractId("tests.pending.contract"); - var role = new ShaderPassRoleId("draw"); - var pass = new ShaderPassDefinition("draw", ShaderProgramKind.Raster); - var shader = new ShaderAsset(); - Assert.True(m_identities.Register(shader)); - shader.SetDefinition( - new ShaderDefinition( - "Pending Shader", - [], - [], - [pass], - [new ShaderTechniqueDefinition( - new ShaderTechniqueId("default"), - contract, - [new ShaderTechniquePass(role, pass.name)])]), - m_serialization, - SerializationContext.empty); - PendingShaderPipeline.material = new MaterialAsset { shader = shader }; - PendingShaderPipeline.contract = contract; - PendingShaderPipeline.role = role; - - var diagnostics = new TestDiagnosticSink(); - var compiler = new DelayedTextureArtifactSource(); - var runtime = new RenderRuntime( - m_types, - new RecordingRenderDevice(), - diagnostics, - targetArtifacts: new DelayedArtifactProvider(compiler)); - var asset = new RenderPipelineAsset { pipelineTypeId = PendingShaderPipeline.extensionId }; - runtime.Submit(CreateRequest("Pending Shader", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.False(PendingShaderPipeline.resolved); - Assert.DoesNotContain( - diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE"); - runtime.Detach(); - } - - [Fact] - public async Task PersistentTextureRegionUpdateAndReadbackCompleteAcrossFrameBoundaries() - { - var device = new RecordingRenderDevice(supportsReadback: true); - ReadbackPipeline.texture = device.textureHandle; - var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Readback", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new RenderTextureRegion(0, 1, 1, 0, 2, 2), device.updatedRegion); - Assert.Equal(Enumerable.Range(0, 16).Select(static value => (byte)value), device.updatedBytes); - Task readback = Assert.IsType>( - ReadbackPipeline.readback); - Assert.False(readback.IsCompleted); - - device.readbackReady = true; - BeginRenderFrame(runtime, 0f); - RenderTextureReadbackResult result = await readback; - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(16, result.rowPitch); - Assert.Equal(64, result.data.Length); - Assert.All(result.data.ToArray(), static value => Assert.Equal((byte)37, value)); - runtime.Detach(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task PendingUploadOrReadbackRetirementPreservesDependentWork(bool pendingReadback) - { - var device = new RecordingRenderDevice(supportsReadback: true); - ReadbackPipeline.texture = device.textureHandle; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Upload", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.extensionId })); - runtime.Submit(CreateRequest("Readback", new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.extensionId })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Task readback = Assert.IsType>(ReadbackPipeline.readback); - device.pendingBufferRetirements = pendingReadback ? 0 : 1; - device.pendingReadbackRetirements = pendingReadback ? 1 : 0; - - runtime.Dispose(); - - Assert.Equal(pendingReadback ? 1 : 2, device.bufferRetirementAttempts); - Assert.Equal(pendingReadback ? 2 : 1, device.cancelReadbackCount); - Assert.Equal(2, device.endFrameCount); - await Assert.ThrowsAsync(async () => await readback); - runtime.Dispose(); - Assert.Equal(2, device.endFrameCount); - } - - [Fact] - public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBoundary() - { - var device = new RecordingRenderDevice(supportsReadback: true); - using var cancellation = new CancellationTokenSource(); - ReadbackPipeline.texture = device.textureHandle; - ReadbackPipeline.cancellationToken = cancellation.Token; - var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.extensionId }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Canceled Readback", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - cancellation.Cancel(); - Task readback = Assert.IsType>( - ReadbackPipeline.readback); - Assert.False(readback.IsCompleted); - BeginRenderFrame(runtime, 0f); - await Assert.ThrowsAnyAsync(async () => await readback); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.cancelReadbackCount); - runtime.Detach(); - } - - private static RenderRequest CreateRequest( - string name, - RenderPipelineAsset pipeline, - int priority = 0) - => new( - name, - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - pipeline, - priority: priority); - - private DotNetModuleSource CreateRenderingPluginRequest() - => new() - { - moduleName = "RenderingRuntimeReloadTests", - artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), - mainAssemblyPath = Path.Combine( - AppContext.BaseDirectory, - "Modules", - "RenderingReload", - "Inno.Rendering.Runtime.Reload.TestModule.dll"), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; - - [MethodImpl(MethodImplOptions.NoInlining)] - private static ( - IAssemblyUnloadProbe monitor, - IRenderRuntimeReloadTransaction transaction) RemoveRenderingPlugin( - RenderRuntime runtime, - ModuleHost modules, - DotNetModuleSource plugin) - { - IRenderRuntimeReloadTransaction rendering = runtime.BeginExtensionReload(); - using AssemblyReloadSession removal = modules.BeginReload( - Array.Empty(), - [plugin.moduleName]); - removal.Activate(); - rendering.Prepare(); - rendering.Activate(); - IAssemblyUnloadProbe monitor = removal.Complete(); - rendering.Complete(); - return (monitor, rendering); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static IAssemblyUnloadProbe RemoveUnusedPlugin( - ModuleHost modules, - DotNetModuleSource plugin) - { - using AssemblyReloadSession removal = modules.BeginReload( - Array.Empty(), - [plugin.moduleName]); - removal.Activate(); - return removal.Complete(); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static void QueueCollectiblePayload( - RenderRuntime runtime, - TypeCatalog types, - RenderPipelineAsset pipeline) - { - Type payloadType = types.current.types - .Select(type => type.Resolve(types)) - .Single(type => string.Equals( - type.FullName, - "Inno.Rendering.Runtime.Reload.TestModule.ReloadableFramePayload", - StringComparison.Ordinal)); - object payload = Activator.CreateInstance(payloadType) - ?? throw new InvalidOperationException("The collectible frame payload could not be created."); - var data = new RenderFrameData(); - data.Set(new RenderDataChannelId("tests.runtime.collectible-payload"), payload); - runtime.Submit(new RenderRequest( - "Collectible Pending Request", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - pipeline, - data)); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static void ForceCollection() - { - for (int attempt = 0; attempt < 8; attempt++) - { - GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true); - GC.WaitForPendingFinalizers(); - } - } - - private static void BeginRenderFrame(RenderRuntime runtime, float deltaTime) - { - if (!runtime.isStarted) - runtime.Attach(); - var frame = new RuntimeFrame(0, deltaTime, deltaTime, 0, 0, 1, false); - runtime.BeginFrame(frame); - runtime.BeforeRender(frame); - } - - private sealed class TestContent : IdentityObject; - - [RenderModelExtension(extensionId)] - private sealed class FirstTestRenderModel : IRenderModel - { - internal const string extensionId = "tests.runtime.model.first"; - internal static bool enabled; - internal static int buildCount; - public bool CanRender(RenderOutputSession session) => enabled; - public RenderModelOutput Build(RenderOutputSession session) - { - buildCount++; - return new RenderModelOutput("First Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, new RenderFrameData()); - } - public void Dispose() { } - internal static void Reset() { enabled = false; buildCount = 0; } - } - - [RenderModelExtension(extensionId)] - private sealed class SecondTestRenderModel : IRenderModel - { - internal const string extensionId = "tests.runtime.model.second"; - internal static bool enabled; - internal static int buildCount; - public bool CanRender(RenderOutputSession session) => enabled; - public RenderModelOutput Build(RenderOutputSession session) - { - buildCount++; - return new RenderModelOutput("Second Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, new RenderFrameData()); - } - public void Dispose() { } - internal static void Reset() { enabled = false; buildCount = 0; } - } - - [RenderPipelineExtension(extensionId)] - private sealed class DisposablePipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.disposable"; - - internal static int createdCount { get; private set; } - internal static int disposedCount { get; private set; } - internal static bool rejectConfiguration { get; set; } - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - internal static bool retirementExpired { get; set; } - - public DisposablePipeline() => createdCount++; - - public override void Build(RenderPipelineContext context) => _ = context; - - protected override void OnConfigure(SerializedRenderExtensionState state, RenderExtensionStateContext settings) - { - _ = state; - if (rejectConfiguration) - throw new InvalidOperationException("Rejected pipeline configuration candidate."); - } - - internal static void Reset() - { - createdCount = 0; - disposedCount = 0; - rejectConfiguration = false; - pendingRetirements = 0; - retirementAttempts = 0; - retirementExpired = false; - } - - protected override void Dispose(bool disposing) - { - _ = disposing; - retirementAttempts++; - if (retirementExpired) - throw new RetirementTimeoutException("The pipeline-owned device work exceeded its deadline."); - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Pipeline work remains active."); - } - disposedCount++; - } - } - - [RenderFeatureExtension(extensionId)] - private sealed class PendingFeature : RenderPipelineFeature, IDisposable - { - internal const string extensionId = "tests.runtime.pending-feature"; - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - - public override void AddRenderPasses(RenderFeatureContext context) { } - - public void Dispose() - { - retirementAttempts++; - Assert.Equal(0, DisposablePipeline.disposedCount); - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Feature work remains active."); - } - } - - internal static void Reset() - { - retirementAttempts = 0; - pendingRetirements = 0; - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class StatisticsPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.statistics"; - - public override void Build(RenderPipelineContext context) - { - context.graph - .AddRasterPass( - "Visible", - new RenderPhaseId("tests.statistics.visible"), - 0, - static (_, _) => { }) - .HasSideEffect(); - context.graph.AddRasterPass( - "Culled", - new RenderPhaseId("tests.statistics.culled"), - 0, - static (_, _) => { }); - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class CompositionLayerPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.composition-layer"; - internal static List viewports { get; } = []; - - public override void Build(RenderPipelineContext context) - { - viewports.Add(context.request.viewport); - RasterPassBuilder pass = context.graph.AddRasterPass("Scene Color", - new RenderPhaseId("tests.runtime.composition-layer"), 0, - static (_, _) => { }); - if (context.outputTexture.isValid) - pass.UseColorAttachment(context.outputTexture, 0, - RenderLoadAction.Clear, RenderStoreAction.Store, - new RenderClearColor(0f, 0f, 0f, 0f)); - else - pass.ClearPresentationTarget(default).HasSideEffect(); - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class SideEffectPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.side-effect"; - - public override void Build(RenderPipelineContext context) - { - context.graph - .AddRasterPass( - "Visible", - new RenderPhaseId("tests.runtime.visible"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class PresentationPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.presentation"; - - internal static List observations { get; } = []; - - public override void Build(RenderPipelineContext context) - { - observations.Add(new PresentationObservation( - context.request.name, - context.preservePresentationTarget)); - context.graph - .AddRasterPass( - "Presentation", - new RenderPhaseId("tests.runtime.presentation"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - - internal static void Reset() => observations.Clear(); - } - - [RenderPipelineExtension(extensionId)] - private sealed class ThrowingPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.throwing"; - - public override void Build(RenderPipelineContext context) - { - context.graph - .AddRasterPass( - "Rolled Back", - new RenderPhaseId("tests.runtime.rolled-back"), - 0, - static (_, _) => { }) - .HasSideEffect(); - throw new InvalidOperationException("Expected request failure."); - } - } - - private readonly record struct PresentationObservation( - string requestName, - bool preserveTarget); - - [RenderPipelineExtension(extensionId)] - private sealed class UploadPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.upload"; - - internal static RenderBufferSlice firstSlice { get; private set; } - internal static RenderBufferSlice secondSlice { get; private set; } - internal static bool singleUpload { get; set; } - - public override void Build(RenderPipelineContext context) - { - var layout = new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); - var descriptor = new RenderBufferUploadDescriptor( - layout.stride, - RenderBufferUsage.Vertex, - layout); - firstSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); - if (!singleUpload) - { - secondSlice = context.uploads.UploadBuffer( - descriptor, - new byte[layout.stride * 3], - "Vertices"); - } - } - - internal static void Reset() - { - firstSlice = default; - secondSlice = default; - singleUpload = false; - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class TexturePrewarmPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.texture-prewarm"; - - internal static TextureAsset? texture { get; set; } - - public override void Build(RenderPipelineContext context) - { - context.resourceService.PrewarmTexture( - texture ?? throw new InvalidOperationException("A test texture is required.")); - context.graph - .AddRasterPass( - "Submit While Prewarming", - new RenderPhaseId("tests.runtime.prewarm"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class PendingShaderPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.pending-shader"; - - internal static MaterialAsset? material { get; set; } - internal static ShaderContractId contract { get; set; } - internal static ShaderPassRoleId role { get; set; } - internal static bool resolved { get; private set; } - - public override void Build(RenderPipelineContext context) - { - resolved = context.resourceService.TryResolveGraphicsMaterial( - material ?? throw new InvalidOperationException("A test material is required."), - contract, - role, - null, - null, - out _); - context.graph - .AddRasterPass( - "Submit While Compiling", - new RenderPhaseId("tests.runtime.pending-shader"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - - internal static void Reset() - { - material = null; - contract = default; - role = default; - resolved = false; - } - } - - [RenderPipelineExtension(extensionId)] - private sealed class ReadbackPipeline : RenderPipeline - { - internal const string extensionId = "tests.runtime.readback"; - - internal static PersistentTextureHandle texture { get; set; } - internal static CancellationToken cancellationToken { get; set; } - internal static Task? readback { get; private set; } - - public override void Build(RenderPipelineContext context) - { - byte[] update = Enumerable.Range(0, 16).Select(static value => (byte)value).ToArray(); - context.resourceService.UpdateTexture( - texture, - new RenderTextureRegion(0, 1, 1, 0, 2, 2), - update); - readback ??= context.resourceService - .ReadTextureAsync(texture, cancellationToken: cancellationToken) - .AsTask(); - context.graph - .AddRasterPass( - "Readback Submission", - new RenderPhaseId("tests.runtime.readback"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - - internal static void Reset() - { - texture = default; - cancellationToken = default; - readback = null; - } - } - - [RenderRequestProviderExtension(extensionId)] - private sealed class TestRequestProvider : RenderRequestProvider - { - internal const string extensionId = "tests.runtime.request-provider"; - - internal static bool enabled { get; set; } - internal static RenderPipelineAsset? pipeline { get; set; } - internal static int submitCount { get; private set; } - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - internal static ContentReadScope? lastContent { get; private set; } - internal static RenderViewport? lastPresentationViewport { get; private set; } - internal static RenderOutputInput lastInput { get; private set; } = RenderOutputInput.empty; - - public override void Submit(RenderRequestProviderContext context) - { - if (!enabled) - return; - submitCount++; - lastContent = context.content; - lastPresentationViewport = context.primaryPresentationViewport; - lastInput = context.input; - if (pipeline is null) - return; - context.requests.Submit(CreateRequest( - "Provider Request", - pipeline)); - } - - internal static void Reset() - { - enabled = false; - pipeline = null; - submitCount = 0; - pendingRetirements = 0; - retirementAttempts = 0; - lastContent = null; - lastPresentationViewport = default; - lastInput = RenderOutputInput.empty; - } - - protected override void Dispose(bool disposing) - { - retirementAttempts++; - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Provider work remains active."); - } - } - } - - private sealed class SideEffectContributor : IRenderFrameGraphContributor - { - public void PrepareFrame(ulong frameIndex) => _ = frameIndex; - - public void AddRenderPasses(RenderGraphBuilder graph, ulong frameIndex) - { - _ = frameIndex; - graph.AddRasterPass( - "Overlay", - new RenderPhaseId("tests.runtime.overlay"), - 0, - static (_, _) => { }) - .HasSideEffect(); - } - } - - private sealed class TestDiagnosticSink : IDiagnosticReporter - { - internal List items { get; } = []; - - public void Publish(Diagnostic diagnostic) => items.Add(diagnostic); - - public void Resolve(string code, string? semanticId = null, Guid? objectId = null) - => items.RemoveAll(diagnostic => - string.Equals(diagnostic.code, code, StringComparison.Ordinal) && - string.Equals(diagnostic.semanticId, semanticId, StringComparison.Ordinal) && diagnostic.objectId == objectId); - - public void Replace(IEnumerable diagnostics) - { - items.Clear(); - items.AddRange(diagnostics); - } - } - - private sealed class TestDeviceProxy : RenderDevice, IRenderDevice - { - private static readonly GraphicsCapabilities S_CAPABILITIES = new( - GraphicsApi.Noop, - GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), - Enum.GetValues(), - Enum.GetValues(), - [], - [], - originBottomLeft: false, - homogeneousDepth: false); - - public RenderDeviceFrameCounters frameCounters { get; internal set; } - public RenderDeviceAllocationCounters? allocationCounters { get; internal set; } - internal bool verticalSync { get; private set; } - public void SetVerticalSync(bool enabled) => verticalSync = enabled; - internal List createdBuffers { get; } = []; - internal List destroyedBuffers { get; } = []; - internal int failBufferCreationAt { get; set; } - private int m_bufferCreationCount; - internal List createdTextures { get; } = []; - internal List destroyedTextures { get; } = []; - internal bool frameOpen { get; private set; } - internal int endFrameCount { get; private set; } - internal int executeCount { get; private set; } - internal int textureRetirementAttempts { get; private set; } - internal bool failFirstTextureRetirement { get; set; } - internal PersistentTextureHandle pendingTextureRetirement { get; set; } - internal CompiledRenderGraph? lastGraph { get; private set; } - - internal static IRenderDevice Create(out TestDeviceProxy proxy) - { - proxy = new TestDeviceProxy(); - return proxy; - } - - internal void ReleaseRecordedGraph() => lastGraph = null; - - public GraphicsCapabilities capabilities { get; internal set; } = S_CAPABILITIES; - public uint generation => 1; - public RenderPresentationSize? presentationSize { get; set; } = new(1, 1); - public RenderPresentationSize? primaryPresentationSize - { - get => presentationSize; - private set => presentationSize = value; - } - public bool primaryPresentationEncodesSrgb { get; set; } = true; - - public void BeginFrame() - { - Assert.False(frameOpen); - frameOpen = true; - } - - public void Execute(CompiledRenderGraph graph, ulong frameIndex) - { - Assert.True(frameOpen); - _ = frameIndex; - executeCount++; - lastGraph = graph; - } - - public uint EndFrame() - { - Assert.True(frameOpen); - frameOpen = false; - endFrameCount++; - return checked((uint)endFrameCount); - } - - public void SetPrimaryPresentationSize(RenderPresentationSize? size) - { - primaryPresentationSize = size; - } - - public PersistentTextureHandle CreateTexture(RenderTextureDescriptor descriptor, string name) - { - Assert.True(frameOpen); - _ = descriptor; - _ = name; - PersistentTextureHandle texture = CreatePersistentTextureHandle( - checked((ulong)createdTextures.Count + 1), - generation); - createdTextures.Add(texture); - return texture; - } - - public void UpdateTexture( - PersistentTextureHandle texture, - ReadOnlySpan data, - int mipLevel = 0, - int arrayLayer = 0) - { - _ = texture; - _ = data; - _ = mipLevel; - _ = arrayLayer; - } - - public void UpdateTextureRegion( - PersistentTextureHandle texture, - RenderTextureRegion region, - ReadOnlySpan data) - { - _ = texture; - _ = region; - _ = data; - } - - public RenderTextureReadbackHandle BeginTextureReadback( - PersistentTextureHandle texture, - int mipLevel = 0) - { - _ = texture; - _ = mipLevel; - return default; - } - - public bool TryGetTextureReadback( - RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result) - { - _ = readback; - result = null; - return false; - } - - public void CancelTextureReadback(RenderTextureReadbackHandle readback) => _ = readback; - - public void DestroyTexture(PersistentTextureHandle texture) - { - Assert.True(frameOpen); - textureRetirementAttempts++; - if (failFirstTextureRetirement) - { - failFirstTextureRetirement = false; - throw new InvalidOperationException("Texture retirement failed."); - } - if (texture == pendingTextureRetirement) - { - pendingTextureRetirement = default; - throw new RetirementPendingException("Texture still has pending work."); - } - destroyedTextures.Add(texture); - } - - public PersistentBufferHandle CreateBuffer(PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name) - { - m_bufferCreationCount++; - if (m_bufferCreationCount == failBufferCreationAt) throw new InvalidOperationException("Native allocation rejected."); - PersistentBufferHandle handle = CreatePersistentBufferHandle((ulong)m_bufferCreationCount, generation); - createdBuffers.Add(handle); - return handle; - } - - public void UpdateBuffer( - PersistentBufferHandle buffer, - ReadOnlySpan data, - int startElement = 0) - { - _ = buffer; - _ = data; - _ = startElement; - } - - public void DestroyBuffer(PersistentBufferHandle buffer) - { - Assert.DoesNotContain(buffer, destroyedBuffers); - destroyedBuffers.Add(buffer); - } - - public GraphicsPipelineHandle CreateGraphicsPipeline( - GraphicsPipelineDescriptor descriptor, - string name) - { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => _ = pipeline; - - public ComputePipelineHandle CreateComputePipeline( - ComputePipelineDescriptor descriptor, - string name) - { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - - public void Dispose() { } - } - - private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice - { - internal List createdPrograms { get; } = []; - internal List destroyedPrograms { get; } = []; - internal List programDescriptors { get; } = []; - internal string? failProgramName { get; set; } - internal int pendingProgramRetirements { get; set; } - internal int failedProgramRetirements { get; set; } - internal int programRetirementAttempts { get; private set; } - internal bool verticalSync { get; private set; } - public void SetVerticalSync(bool enabled) => verticalSync = enabled; - - private readonly RenderTextureDescriptor m_readbackDescriptor = new( - 4, - 4, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Readback); - private readonly RenderTextureReadbackHandle m_readbackHandle; - - internal List bufferUpdateOffsets { get; } = []; - internal PersistentTextureHandle textureHandle { get; } - internal RenderTextureRegion? updatedRegion { get; private set; } - internal byte[] updatedBytes { get; private set; } = []; - internal bool readbackReady { get; set; } - internal int cancelReadbackCount { get; private set; } - internal int pendingReadbackRetirements { get; set; } - internal int pendingBufferRetirements { get; set; } - internal int bufferRetirementAttempts { get; private set; } - internal int createBufferCount { get; private set; } - internal int endFrameCount { get; private set; } - internal int executeCount { get; private set; } - - internal RecordingRenderDevice(bool supportsReadback = false) - { - capabilities = new GraphicsCapabilities( - GraphicsApi.Noop, - supportsReadback ? GraphicsCapability.TextureReadback : GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), - Enum.GetValues(), - Enum.GetValues(), - [], - [], - originBottomLeft: false, - homogeneousDepth: false); - textureHandle = CreatePersistentTextureHandle(1UL, generation); - m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); - } - - public GraphicsCapabilities capabilities { get; } - - public uint generation => 1; - public RenderPresentationSize? primaryPresentationSize { get; private set; } = new(1, 1); - public bool primaryPresentationEncodesSrgb => true; - - public void BeginFrame() { } - - public void Execute(CompiledRenderGraph graph, ulong frameIndex) - { - _ = graph; - _ = frameIndex; - executeCount++; - } - - public uint EndFrame() - { - endFrameCount++; - return checked((uint)endFrameCount); - } - - public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; - - public PersistentTextureHandle CreateTexture(RenderTextureDescriptor descriptor, string name) - { - _ = descriptor; - _ = name; - return default; - } - - public void UpdateTexture( - PersistentTextureHandle texture, - ReadOnlySpan data, - int mipLevel = 0, - int arrayLayer = 0) - { - _ = texture; - _ = data; - _ = mipLevel; - _ = arrayLayer; - } - - public void UpdateTextureRegion( - PersistentTextureHandle texture, - RenderTextureRegion region, - ReadOnlySpan data) - { - Assert.Equal(textureHandle, texture); - updatedRegion = region; - updatedBytes = data.ToArray(); - } - - public RenderTextureReadbackHandle BeginTextureReadback( - PersistentTextureHandle texture, - int mipLevel = 0) - { - Assert.Equal(textureHandle, texture); - _ = mipLevel; - return m_readbackHandle; - } - - public bool TryGetTextureReadback( - RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result) - { - Assert.Equal(m_readbackHandle, readback); - result = readbackReady - ? new RenderTextureReadbackResult( - m_readbackDescriptor, - 0, - 16, - Enumerable.Repeat((byte)37, 64).ToArray()) - : null; - return result is not null; - } - - public void CancelTextureReadback(RenderTextureReadbackHandle readback) - { - Assert.Equal(m_readbackHandle, readback); - cancelReadbackCount++; - if (pendingReadbackRetirements > 0) - { - pendingReadbackRetirements--; - Assert.False(ReadbackPipeline.readback!.IsCompleted); - Assert.Equal(1, endFrameCount); - throw new RetirementPendingException("Readback cancellation remains active."); - } - } - - public void DestroyTexture(PersistentTextureHandle texture) => _ = texture; - - public PersistentBufferHandle CreateBuffer( - PersistentBufferDescriptor descriptor, - ReadOnlySpan initialData, - string name) - { - _ = descriptor; - _ = initialData; - _ = name; - createBufferCount++; - return default; - } - - public void UpdateBuffer( - PersistentBufferHandle buffer, - ReadOnlySpan data, - int startElement = 0) - { - _ = buffer; - _ = data; - bufferUpdateOffsets.Add(startElement); - } - - public void DestroyBuffer(PersistentBufferHandle buffer) - { - bufferRetirementAttempts++; - if (pendingBufferRetirements > 0) - { - pendingBufferRetirements--; - Assert.Equal(0, cancelReadbackCount); - Assert.False(ReadbackPipeline.readback!.IsCompleted); - Assert.Equal(1, endFrameCount); - throw new RetirementPendingException("Upload work remains active."); - } - } - - public GraphicsPipelineHandle CreateGraphicsPipeline( - GraphicsPipelineDescriptor descriptor, - string name) - { - if (name == failProgramName) throw new InvalidOperationException("Injected program allocation failure."); - GraphicsPipelineHandle handle = CreateGraphicsPipelineHandle(checked((ulong)createdPrograms.Count + 1), generation); - createdPrograms.Add(handle); - programDescriptors.Add(descriptor); - return handle; - } - - public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) - { - programRetirementAttempts++; - if (pendingProgramRetirements > 0) - { - pendingProgramRetirements--; - throw new RetirementPendingException("Injected unfinished program retirement."); - } - Assert.DoesNotContain(pipeline, destroyedPrograms); - destroyedPrograms.Add(pipeline); - if (failedProgramRetirements > 0) - { - failedProgramRetirements--; - throw new InvalidOperationException("Injected completed program retirement failure."); - } - } - - public ComputePipelineHandle CreateComputePipeline( - ComputePipelineDescriptor descriptor, - string name) - { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - - public void Dispose() { } - - } - - private sealed class DelayedTextureArtifactSource - { - private readonly TaskCompletionSource m_completion = new( - TaskCreationOptions.RunContinuationsAsynchronously); - - internal ManualResetEventSlim started { get; } = new(initialState: false); - internal bool isCompleted => m_completion.Task.IsCompleted; - - internal Task LoadAsync(CancellationToken cancellationToken = default) - { - started.Set(); - return m_completion.Task.WaitAsync(cancellationToken); - } - - internal void Complete(byte[] data) => m_completion.TrySetResult(data); - } - - private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) - : IRenderTargetArtifactProvider - { - private Task? m_texture; - - public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) - => throw new InvalidOperationException("This pending provider never publishes a shader artifact."); - - public RenderTargetArtifactStatus GetShaderArtifact( - ShaderAsset shader, - RenderShaderVariant variant, - GraphicsCapabilities capabilities, - out RenderShaderArtifact? artifact) - { - _ = shader; - _ = variant; - _ = capabilities; - artifact = null; - return RenderTargetArtifactStatus.Pending; - } - - public RenderTargetArtifactStatus GetTextureArtifact( - RenderTextureArtifactReference texture, - out ReadOnlyMemory artifact) - { - _ = texture; - m_texture ??= compiler.LoadAsync(); - if (m_texture.IsCompletedSuccessfully) - { - artifact = m_texture.Result; - return RenderTargetArtifactStatus.Ready; - } - artifact = ReadOnlyMemory.Empty; - return RenderTargetArtifactStatus.Pending; - } - } - - private sealed class TestCompositionProgramProvider : IRenderLayerCompositionProgramProvider - { - public GraphicsPipelineDescriptor CreateDescriptor( - GraphicsCapabilities capabilities, RenderVertexLayout vertexLayout) - { - _ = capabilities; - return new GraphicsPipelineDescriptor( - [1], [1], - [new RenderShaderBindingDescriptor( - new RenderBindingId("s_tex"), RenderShaderBindingKind.Texture, 0, nativeName: "s_tex")], - vertexLayout); - } - - public GraphicsPipelineDescriptor CreateOutputTransferDescriptor( - GraphicsCapabilities capabilities, RenderVertexLayout vertexLayout) - => CreateDescriptor(capabilities, vertexLayout); + Type[] publicTypes = typeof(ShaderContractID).Assembly.GetExportedTypes(); + Assert.DoesNotContain(publicTypes, static type => ( + type.FullName?.Contains("Bgfx", StringComparison.OrdinalIgnoreCase) == true + )); + Assert.Contains(publicTypes, static type => type == typeof(ShaderContractID)); + Assert.Contains(publicTypes, static type => type == typeof(ShaderPassRoleID)); } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs index 0f5fb659f..9464bfb63 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs @@ -1,15 +1,16 @@ -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Text.Json; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Reload; using Inno.Rendering; -using Xunit; +using Inno.Testing.Source; namespace Inno.Rendering.Runtime.Tests; @@ -22,11 +23,14 @@ public void CompletedOrRejectedFramesReleaseCollectibleSnapshotScratchAndGraphCa { DotNetModuleSource plugin = CreateRenderingPluginRequest(); m_modules.Load(plugin); - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); WeakReference contributor = CompleteCollectibleContributorFrame(runtime, proxy, rejectGraph); - (IAssemblyUnloadProbe monitor, IRenderRuntimeReloadTransaction transaction) = - RemoveRenderingPlugin(runtime, m_modules, plugin); + (IAssemblyUnloadProbe monitor, IRenderRuntimeReloadTransaction transaction) = RemoveRenderingPlugin(runtime, m_modules, plugin); ForceCollection(); Assert.False(contributor.IsAlive); Assert.True(monitor.isCompleted); @@ -38,7 +42,11 @@ public void CompletedOrRejectedFramesReleaseCollectibleSnapshotScratchAndGraphCa [Fact] public void ContributorRegistrationChangesTakeEffectOnTheNextFrame() { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); var first = new CountingContributor(); var next = new CountingContributor(); @@ -110,9 +118,13 @@ public void FrameAllocationMeasurementsUseTheRealPublicLifecycle( int contributorCount, bool fail ) { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); - var contributors = new List(); + List contributors = []; for (int index = 0; index < contributorCount; index++) { var contributor = new CountingContributor { fail = fail }; @@ -120,27 +132,41 @@ bool fail runtime.RegisterContributor(contributor); } for (int frame = 0; frame < 16; frame++) + { CompleteContributorFrame(runtime, proxy); - const int frames = 64; + } + const int C_FRAMES = 64; long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); - for (int frame = 0; frame < frames; frame++) + for (int frame = 0; frame < C_FRAMES; frame++) + { CompleteContributorFrame(runtime, proxy); + } double elapsedMs = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; - Assert.All(contributors, contributor => Assert.Equal(frames + 16, contributor.builds)); - Assert.Equal(frames + 16, proxy.endFrameCount); - Assert.Equal(contributorCount != 0 && !fail ? frames + 16 : 0, proxy.executeCount); - string directory = Path.Combine(TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), "artifacts/acceptance/architecture-cleanup/results"); + Assert.All(contributors, contributor => Assert.Equal(C_FRAMES + 16, contributor.builds)); + Assert.Equal(C_FRAMES + 16, proxy.endFrameCount); + Assert.Equal(contributorCount != 0 && !fail ? C_FRAMES + 16 : 0, proxy.executeCount); + string directory = Path.Combine( + TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), + "artifacts/acceptance/architecture-cleanup/results" + ); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, $"frames-{contributorCount}-{fail}.json"), JsonSerializer.Serialize(new - { - contributorCount, fail, frames, elapsedMs, allocatedBytes, - bytesPerFrame = allocatedBytes / (double)frames, - millisecondsPerFrame = elapsedMs / frames, - graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription - }, new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText( + Path.Combine(directory, $"frames-{contributorCount}-{fail}.json"), + JsonSerializer.Serialize(new + { + contributorCount, + fail, + C_FRAMES, + elapsedMs, + allocatedBytes, + bytesPerFrame = allocatedBytes / (double)C_FRAMES, + millisecondsPerFrame = elapsedMs / C_FRAMES, + graphCompileCount = ReadGraphCompileCount(runtime), + runtime = RuntimeInformation.FrameworkDescription + }, new JsonSerializerOptions { WriteIndented = true }) + ); } [Theory] @@ -150,36 +176,77 @@ bool fail [InlineData(32)] public void ContributorRetirementMeasurementsIncludeRegistrationAndTheFollowingEmptyFrame(int contributorCount) { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); CountingContributor[] contributors = Enumerable.Range(0, contributorCount) - .Select(static _ => new CountingContributor()).ToArray(); + .Select(static _ => new CountingContributor()) + .ToArray(); foreach (CountingContributor contributor in contributors) + { runtime.RegisterContributor(contributor); + } for (int cycle = 0; cycle < 16; cycle++) + { CompleteContributorRetirementCycle(runtime, proxy, contributors); + } - const int cycles = 64; + const int C_CYCLES = 64; long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); - for (int cycle = 0; cycle < cycles; cycle++) + for (int cycle = 0; cycle < C_CYCLES; cycle++) + { CompleteContributorRetirementCycle(runtime, proxy, contributors); + } double elapsedMs = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; - Assert.All(contributors, contributor => Assert.Equal(cycles + 16, contributor.builds)); - Assert.Equal(2 * (cycles + 16), proxy.endFrameCount); - Assert.Equal(contributorCount == 0 ? 0 : cycles + 16, proxy.executeCount); + Assert.All(contributors, contributor => Assert.Equal(C_CYCLES + 16, contributor.builds)); + Assert.Equal(2 * (C_CYCLES + 16), proxy.endFrameCount); + Assert.Equal(contributorCount == 0 ? 0 : C_CYCLES + 16, proxy.executeCount); - string directory = Path.Combine(TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), "artifacts/acceptance/architecture-cleanup/results"); + string directory = Path.Combine( + TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), + "artifacts/acceptance/architecture-cleanup/results" + ); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, $"retirement-{contributorCount}.json"), JsonSerializer.Serialize(new - { - contributorCount, cycles, frames = 2 * cycles, elapsedMs, allocatedBytes, - bytesPerCycle = allocatedBytes / (double)cycles, - millisecondsPerCycle = elapsedMs / cycles, - graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription - }, new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText( + Path.Combine(directory, $"retirement-{contributorCount}.json"), + JsonSerializer.Serialize(new + { + contributorCount, + C_CYCLES, + frames = 2 * C_CYCLES, + elapsedMs, + allocatedBytes, + bytesPerCycle = allocatedBytes / (double)C_CYCLES, + millisecondsPerCycle = elapsedMs / C_CYCLES, + graphCompileCount = ReadGraphCompileCount(runtime), + runtime = RuntimeInformation.FrameworkDescription + }, new JsonSerializerOptions { WriteIndented = true }) + ); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private WeakReference CompleteCollectibleContributorFrame( + RenderRuntime runtime, + TestDeviceProxy proxy, + bool rejectGraph + ) { + Type type = m_types.current.GetTypesImplementing() + .Select(reference => reference.Resolve(m_types)) + .Single(type => type.Name == "ReloadableContributor"); + IRenderFrameGraphContributor contributor = (IRenderFrameGraphContributor)Activator.CreateInstance( + type, + new Action(value => Assert.True(runtime.UnregisterContributor(value))), + rejectGraph + )!; + var weak = new WeakReference(contributor); + runtime.RegisterContributor(contributor); + CompleteContributorFrame(runtime, proxy); + return weak; } private static void CompleteContributorRetirementCycle( @@ -189,10 +256,14 @@ IReadOnlyList contributors ) { CompleteContributorFrame(runtime, proxy); foreach (CountingContributor contributor in contributors) + { Assert.True(runtime.UnregisterContributor(contributor)); + } CompleteContributorFrame(runtime, proxy); foreach (CountingContributor contributor in contributors) + { runtime.RegisterContributor(contributor); + } } private static void CompleteContributorFrame( @@ -212,24 +283,6 @@ private static int ReadGraphCompileCount(RenderRuntime runtime) return GraphicsSettings.frameStatistics!.graphCompileCount; } - [MethodImpl(MethodImplOptions.NoInlining)] - private WeakReference CompleteCollectibleContributorFrame( - RenderRuntime runtime, - TestDeviceProxy proxy, - bool rejectGraph - ) { - Type type = m_types.current.GetTypesImplementing() - .Select(reference => reference.Resolve(m_types)) - .Single(type => type.Name == "ReloadableContributor"); - var contributor = (IRenderFrameGraphContributor)Activator.CreateInstance(type, - new Action(value => Assert.True(runtime.UnregisterContributor(value))), - rejectGraph)!; - var weak = new WeakReference(contributor); - runtime.RegisterContributor(contributor); - CompleteContributorFrame(runtime, proxy); - return weak; - } - private sealed class CountingContributor : IRenderFrameGraphContributor { internal int builds; @@ -243,13 +296,19 @@ public void AddRenderPasses( ulong frameIndex ) { builds++; - graph.AddRasterPass(fail ? "Discarded" : "Accepted", new("tests.contributor"), 0, + graph.AddRasterPass( + fail ? "Discarded" : "Accepted", + new RenderPhaseID("tests.contributor"), + 0, static ( payload, context - ) => { }).HasSideEffect(); + ) => {} + ).HasSideEffect(); if (fail) + { throw new InvalidOperationException("Discard this contributor's complete mutation."); + } } } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs index f3231b6f0..81bde188b 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; namespace Inno.Rendering.Runtime.Tests; @@ -15,11 +15,21 @@ public void UnavailablePrimaryOutputSkipsInputScalingAndKeepsOffscreenWork() TestRequestProvider.enabled = true; FirstTestRenderModel.enabled = true; using var runtime = new RenderRuntime( - m_types, device, new TestDiagnosticSink(), - primaryInputSurfaceSizeProvider: static () => throw new InvalidOperationException("There is no primary input surface.")); - var asset = new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }; - var target = new RenderTexture("Offscreen", new RenderTextureDescriptor( - 32, 24, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + m_types, + device, + new TestDiagnosticSink(), + primaryInputSurfaceSizeProvider: static () => throw new InvalidOperationException("There is no primary input surface.") + ); + var asset = new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }; + var target = new RenderTexture( + "Offscreen", + new RenderTextureDescriptor( + 32, + 24, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); runtime.Submit(new RenderRequest("Offscreen", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 32, 24), asset)); runtime.Submit(new RenderRequest("Unavailable", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 24), asset)); BeginRenderFrame(runtime, 0f); @@ -78,7 +88,11 @@ public void UnavailableLogicalInputSurfaceDoesNotDispatchPrimaryInteraction() proxy.presentationSize = new RenderPresentationSize(1280, 720); TestRequestProvider.enabled = true; using var runtime = new RenderRuntime( - m_types, device, new TestDiagnosticSink(), primaryInputSurfaceSizeProvider: static () => null); + m_types, + device, + new TestDiagnosticSink(), + primaryInputSurfaceSizeProvider: static () => null + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); runtime.AfterRender(default); diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs similarity index 58% rename from tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs rename to tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs index 62b0b9d57..24d263dd0 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Core.Serialization; -using Inno.Rendering; using Xunit; +using Inno.Core.Serialization; using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Rendering.Runtime.Tests; @@ -21,27 +19,71 @@ public void ExplicitArtifactScopesDoNotPublishIntoCanonicalMaterialCachesAndRele var previewDiagnostics = new TestDiagnosticSink(); using var runtime = new RenderRuntime(m_types, device, projectDiagnostics, targetArtifacts: provider); RenderShaderArtifact draft = Publication("draft"); - GraphicsPipelineHandle canonical = default, preview = default; + GraphicsPipelineHandle canonical = default; + GraphicsPipelineHandle preview = default; ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); - Assert.True(resources.TryResolveMaterialArtifact(new("preview/document"), draft, material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, previewDiagnostics, out var edited)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); + Assert.True( + resources.TryResolveMaterialArtifact( + new RenderPersistentResourceID("preview/document"), + draft, + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + ShaderProgramKind.Raster, + null, + null, + previewDiagnostics, + out RenderMaterialPass? edited + ) + ); Assert.Equal("saved", saved!.definition.name); Assert.Equal("draft", edited!.definition.name); - canonical = saved.graphicsPipeline; preview = edited.graphicsPipeline; + canonical = saved.graphicsPipeline; + preview = edited.graphicsPipeline; Assert.NotEqual(canonical, preview); - Assert.True(resources.TryResolveMaterialArtifact(new("preview/document"), Publication("next-frame"), material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, previewDiagnostics, out var sameFrame)); + Assert.True( + resources.TryResolveMaterialArtifact( + new RenderPersistentResourceID("preview/document"), + Publication("next-frame"), + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + ShaderProgramKind.Raster, + null, + null, + previewDiagnostics, + out RenderMaterialPass? sameFrame + ) + ); Assert.Equal(preview, sameFrame!.graphicsPipeline); }; RunResourceFrame(runtime); Assert.Equal(1, provider.requests); - runtime.resources.Release(new("preview/document")); + runtime.resources.Release(new RenderPersistentResourceID("preview/document")); Assert.DoesNotContain(preview, device.destroyedPrograms); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); Assert.Equal(canonical, saved!.graphicsPipeline); }; RunResourceFrame(runtime); @@ -63,8 +105,20 @@ public void InvalidDraftProgramKeepsOnlyItsOwnLastGoodAndReportsOnlyToItsConsume GraphicsPipelineHandle lastGood = default; ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveMaterialArtifact(new("preview/a"), draft, material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, preview, out var pass)); + Assert.True( + resources.TryResolveMaterialArtifact( + new RenderPersistentResourceID("preview/a"), + draft, + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + ShaderProgramKind.Raster, + null, + null, + preview, + out RenderMaterialPass? pass + ) + ); if (lastGood.isValid) Assert.Equal(lastGood, pass!.graphicsPipeline); lastGood = pass!.graphicsPipeline; }; @@ -76,7 +130,16 @@ public void InvalidDraftProgramKeepsOnlyItsOwnLastGoodAndReportsOnlyToItsConsume Assert.Contains(preview.items, issue => issue.code == "RENDER_PROGRAM_CREATE_FAILED"); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); Assert.Equal("saved", saved!.definition.name); Assert.NotEqual(lastGood, saved.graphicsPipeline); }; @@ -87,9 +150,9 @@ public void InvalidDraftProgramKeepsOnlyItsOwnLastGoodAndReportsOnlyToItsConsume [Fact] public void ShaderProgramsFollowPublishedContentNotTheLatestAssetDefinitionOrItsVersion() { - var first = Publication("first"); - var second = Publication("second"); - var shader = PublicationShader("first"); + RenderShaderArtifact first = Publication("first"); + RenderShaderArtifact second = Publication("second"); + ShaderAsset shader = PublicationShader("first"); var material = new MaterialAsset { shader = shader }; var provider = new PublicationProvider(m_serialization) { artifact = first }; var device = new RecordingRenderDevice(); @@ -97,8 +160,16 @@ public void ShaderProgramsFollowPublishedContentNotTheLatestAssetDefinitionOrIts RenderMaterialPass Read() { RenderMaterialPass? pass = null; - ResourceProbePipeline.action = resources => Assert.True(resources.TryResolveGraphicsMaterial(material, - new("test.publication"), new("draw"), null, null, out pass)); + ResourceProbePipeline.action = resources => Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out pass + ) + ); RunResourceFrame(runtime); return Assert.IsType(pass); } @@ -118,18 +189,27 @@ RenderMaterialPass Read() [Fact] public void AllPreviouslyUsedPassesMustBeCreatedBeforeAnyReplacementIsPublished() { - var shader = PublicationShader("main", "shadow"); + ShaderAsset shader = PublicationShader("main", "shadow"); var material = new MaterialAsset { shader = shader }; var provider = new PublicationProvider(m_serialization) { artifact = Publication("main", "shadow") }; var device = new RecordingRenderDevice(); using var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), targetArtifacts: provider); - var resolved = new List(); + List resolved = []; ResourceProbePipeline.action = resources => { resolved.Clear(); foreach (string role in new[] { "draw", "shadow" }) { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out RenderMaterialPass? pass)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID(role), + null, + null, + out RenderMaterialPass? pass + ) + ); resolved.Add(pass!.graphicsPipeline); } }; @@ -151,15 +231,38 @@ public void AllPreviouslyUsedPassesMustBeCreatedBeforeAnyReplacementIsPublished( public void ShaderArtifactChangesCannotSplitTheCurrentExtractionFrame() { var material = new MaterialAsset { shader = PublicationShader("first") }; - var first = Publication("first"); - var second = Publication("second"); + RenderShaderArtifact first = Publication("first"); + RenderShaderArtifact second = Publication("second"); var provider = new PublicationProvider(m_serialization) { artifact = first }; - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), new TestDiagnosticSink(), targetArtifacts: provider); + using var runtime = new RenderRuntime( + m_types, + new RecordingRenderDevice(), + new TestDiagnosticSink(), + targetArtifacts: provider + ); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? a)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out RenderMaterialPass? a + ) + ); provider.artifact = second; - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? b)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID("draw"), + null, + null, + out RenderMaterialPass? b + ) + ); Assert.Equal(a!.graphicsPipeline, b!.graphicsPipeline); }; RunResourceFrame(runtime); @@ -176,7 +279,18 @@ public void CompletedRetirementFailureStillAttemptsEveryProgramExactlyOnce() ResourceProbePipeline.action = resources => { foreach (string role in new[] { "draw", "shadow" }) - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out _)); + { + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID(role), + null, + null, + out _ + ) + ); + } }; RunResourceFrame(runtime); device.failedProgramRetirements = 1; @@ -196,7 +310,18 @@ public void UnfinishedRetirementKeepsProgramOwnershipUntilOwnerDrainCompletes() ResourceProbePipeline.action = resources => { foreach (string role in new[] { "draw", "shadow" }) - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out _)); + { + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new ShaderContractID("test.publication"), + new ShaderPassRoleID(role), + null, + null, + out _ + ) + ); + } }; RunResourceFrame(runtime); device.pendingProgramRetirements = 1; @@ -214,7 +339,11 @@ public void UnfinishedRetirementKeepsProgramOwnershipUntilOwnerDrainCompletes() public void ShaderArtifactCodecRetainsTheExactDetachedRuntimeContract() { RenderShaderArtifact artifact = Publication("main"); - RenderShaderArtifact decoded = RenderShaderArtifactCodec.Decode(RenderShaderArtifactCodec.Encode(artifact), artifact.shaderName, artifact.variant); + RenderShaderArtifact decoded = RenderShaderArtifactCodec.Decode( + RenderShaderArtifactCodec.Encode(artifact), + artifact.shaderName, + artifact.variant + ); Assert.Equal(artifact.contentHash, decoded.contentHash); Assert.Equal(artifact.definitionData.ToArray(), decoded.definitionData.ToArray()); var provider = new PublicationProvider(m_serialization); @@ -232,33 +361,65 @@ private ShaderAsset PublicationShader(params string[] passes) return shader; } - private static ShaderDefinition PublicationDefinition(params string[] passes) - => new("Publication", [], [], passes.Select(name => new ShaderPassDefinition(name, ShaderProgramKind.Raster)), - [new(new("default"), new("test.publication"), passes.Select((name, index) => new ShaderTechniquePass(new(index == 0 ? "draw" : name), name)))]); - private RenderShaderArtifact Publication(params string[] passes) => Publication(passes, 1); - private RenderShaderArtifact Publication(string[] passes, byte marker) - => new("Publication", "test.noop", RenderShaderVariant.empty, new([]), - passes.Select(name => new RenderShaderPassArtifact(name, ShaderProgramKind.Raster, new(), new([]), - [new(ShaderStage.Vertex, [marker]), new(ShaderStage.Fragment, [marker])])).ToArray(), - m_serialization.Serialize(PublicationDefinition(passes), SerializationContext.empty)); + private RenderShaderArtifact Publication( + string[] passes, + byte marker + ) => new( + "Publication", + "test.noop", + RenderShaderVariant.empty, + new ShaderInterface([]), + passes.Select(name => new RenderShaderPassArtifact( + name, + ShaderProgramKind.Raster, + new RenderRasterState(), + new ShaderInterface([]), + [new RenderShaderStageArtifact(ShaderStage.Vertex, [marker]), new RenderShaderStageArtifact(ShaderStage.Fragment, [marker])] + )).ToArray(), + m_serialization.Serialize(PublicationDefinition(passes), SerializationContext.empty) + ); + + private static ShaderDefinition PublicationDefinition(params string[] passes) + => new( + "Publication", + [], + [], + passes.Select(name => new ShaderPassDefinition(name, ShaderProgramKind.Raster)), + [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + new ShaderContractID("test.publication"), + passes.Select(( + name, + index + ) => new ShaderTechniquePass(new ShaderPassRoleID(index == 0 ? "draw" : name), name)) + )] + ); private sealed class PublicationProvider(SerializationRegistry serialization) : IRenderTargetArtifactProvider { internal RenderShaderArtifact? artifact; internal int requests; + public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact value) => serialization.Deserialize(value.definitionData.Span, SerializationContext.empty); - public RenderTargetArtifactStatus GetShaderArtifact(ShaderAsset shader, RenderShaderVariant variant, - GraphicsCapabilities capabilities, out RenderShaderArtifact? value) - { + + public RenderTargetArtifactStatus GetShaderArtifact( + ShaderAsset shader, + RenderShaderVariant variant, + GraphicsCapabilities capabilities, + out RenderShaderArtifact? value + ) { requests++; value = artifact; return value is null ? RenderTargetArtifactStatus.Pending : RenderTargetArtifactStatus.Ready; } - public RenderTargetArtifactStatus GetTextureArtifact(RenderTextureArtifactReference texture, out ReadOnlyMemory value) - { + + public RenderTargetArtifactStatus GetTextureArtifact( + RenderTextureArtifactReference texture, + out ReadOnlyMemory value + ) { value = default; return RenderTargetArtifactStatus.Unavailable; } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs new file mode 100644 index 000000000..cd92fcc53 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs @@ -0,0 +1,2503 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Mathematics; +using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Input; +using Inno.References; +using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; + +namespace Inno.Rendering.Runtime.Tests; + +public sealed partial class RenderRuntimeGenerationTests : IDisposable +{ + private readonly string m_cacheDirectory = Path.Combine( + Path.GetTempPath(), + "InnoRenderRuntimeTests", + Guid.NewGuid().ToString("N") + ); + + private readonly IdentityAllocator m_identities; + private readonly IDisposable m_identityScope; + private readonly ModuleHost m_modules; + private readonly TypeCatalog m_types; + private readonly SerializationRegistry m_serialization; + + public RenderRuntimeGenerationTests() + { + _ = typeof(TextureAsset); + m_identities = new IdentityAllocator(); + m_identityScope = m_identities.EnterScope(); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)} + ); + m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); + ResourceProbePipeline.action = null; + DisposablePipeline.Reset(); + PendingFeature.Reset(); + TestRequestProvider.Reset(); + FirstTestRenderModel.Reset(); + SecondTestRenderModel.Reset(); + CompositionLayerPipeline.viewports.Clear(); + UploadPipeline.Reset(); + TexturePrewarmPipeline.texture = null; + PendingShaderPipeline.Reset(); + ReadbackPipeline.Reset(); + PresentationPipeline.Reset(); + } + + public void Dispose() + { + ResourceProbePipeline.action = null; + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + m_identityScope.Dispose(); + if (Directory.Exists(m_cacheDirectory)) + { + Directory.Delete(m_cacheDirectory, recursive: true); + } + } + + [Fact] + public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterPartialAllocationFailure() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink()); + var owner = new AssetRuntimeOwner(); + var geometry = new GeometryAsset(3, 3, 1, default, default); + m_identities.Register(geometry); + byte[] bytes = GeometryArtifact.Encode( + new GeometryData( + [ + new GeometryVertex(default, default, default, default), + new GeometryVertex(default, default, default, default), + new GeometryVertex(default, default, default, default) + ], + [0, 1, 2], + [new GeometrySection(0, 3)] + ) + ); + owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "first", bytes, false, 1); + RenderGeometry? first = null; + ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out first); + RunResourceFrame(runtime); + Assert.NotNull(first); + Assert.Equal(2, device.createdBuffers.Count); + device.failBufferCreationAt = 4; + owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "second", bytes, false, 2); + RenderGeometry? failed = null; + ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out failed); + RunResourceFrame(runtime); + Assert.NotNull(failed); + Assert.Equal(first!.vertexBuffer, failed!.vertexBuffer); + Assert.Equal(first.indexBuffer, failed.indexBuffer); + Assert.Equal(device.createdBuffers[2], Assert.Single(device.destroyedBuffers)); + device.failBufferCreationAt = 0; + RunResourceFrame(runtime); + Assert.NotEqual(first.vertexBuffer, failed.vertexBuffer); + Assert.NotEqual(first.indexBuffer, failed.indexBuffer); + Assert.Equal(3, device.destroyedBuffers.Count); + runtime.Dispose(); + Assert.Equal(device.createdBuffers.Count, device.destroyedBuffers.Count); + owner.Release(geometry); + m_identities.Unregister(geometry); + ResourceProbePipeline.action = null; + } + + [Fact] + public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime( + m_types, + backend, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 } + ); + var descriptor = new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 4, RenderBufferUsage.Storage)); + int rejected = 0; + for (int frame = 0; frame < 256; frame++) + { + long revision = frame; + ResourceProbePipeline.action = resources => + { + _ = resources.AcquireBuffer(new RenderPersistentResourceID("owned"), revision, descriptor, new byte[16], "owned"); + try + { + resources.AcquireBuffer(new RenderPersistentResourceID("overflow"), revision, descriptor, new byte[16], "overflow"); + } + catch (InvalidOperationException) + { + rejected++; + } + }; + RunResourceFrame(runtime); + Assert.Equal(1, runtime.resourceStatistics.activeResources); + } + Assert.Equal(256, rejected); + Assert.Equal(256, runtime.resourceStatistics.rejectedResources); + runtime.Dispose(); + Assert.Equal(256, device.createdBuffers.Count); + Assert.Equal(256, device.destroyedBuffers.Count); + ResourceProbePipeline.action = null; + } + + [Fact] + public async Task ReadbackAdmissionIsRejectedBeforeAllocatingASecondNativeOperation() + { + var device = new RecordingRenderDevice(supportsReadback: true); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 } + ); + Task? readback = null; + bool rejected = false; + ResourceProbePipeline.action = resources => + { + readback = resources.ReadTextureAsync(device.textureHandle).AsTask(); + try + { + _ = resources.ReadTextureAsync(device.textureHandle); + } + catch (InvalidOperationException) + { + rejected = true; + } + }; + RunResourceFrame(runtime); + ResourceProbePipeline.action = null; + Assert.True(rejected); + Assert.Equal(1, runtime.resourceStatistics.pendingReadbacks); + Assert.Equal(1, runtime.resourceStatistics.rejectedReadbacks); + runtime.Dispose(); + await Assert.ThrowsAsync(() => readback!); + Assert.Equal(1, device.cancelReadbackCount); + } + + [Fact] + public void SuccessfulTypeCacheChangeRetiresUnrequestedPipelineAtFrameBoundary() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + Assert.Equal(1, DisposablePipeline.createdCount); + Assert.Equal(0, DisposablePipeline.disposedCount); + + m_types.Rebuild(); + BeginRenderFrame(runtime, 0f); + + Assert.Equal(1, DisposablePipeline.disposedCount); + + runtime.AfterRender(default); + runtime.EndFrame(default); + runtime.Detach(); + } + + [Fact] + public void PendingProviderRetirementIsRetriedBeforeTheSnapshotIsReleased() + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + TestRequestProvider.pendingRetirements = 2; + + m_types.Rebuild(); + + Assert.Equal(3, TestRequestProvider.retirementAttempts); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool duplicate) + { + var contributor = new SideEffectContributor(); + IRenderFrameGraphContributor[] contributors = duplicate ? [contributor, contributor] : [null!]; + Assert.Throws(() => new RenderRuntime( + m_types, + TestDeviceProxy.Create(out _), + new TestDiagnosticSink(), + contributors + )); + m_types.Rebuild(); + Assert.Equal(0, TestRequestProvider.retirementAttempts); + } + + [Fact] + public void PendingFeatureRetirementKeepsItsPipelineAliveUntilQuiescent() + { + var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); + Assert.True( + runtime.TryActivateDefaultPipeline(new RenderPipelineAsset + { + pipelineTypeId = DisposablePipeline.C_EXTENSION_ID, + features = [new RenderFeatureConfiguration(PendingFeature.C_EXTENSION_ID)] + }) + ); + PendingFeature.pendingRetirements = 2; + DisposablePipeline.pendingRetirements = 1; + + runtime.Dispose(); + runtime.Dispose(); + + Assert.Equal(3, PendingFeature.retirementAttempts); + Assert.Equal(2, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + Assert.Equal(1, device.endFrameCount); + Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); + } + + [Fact] + public void RejectedPipelineWaitsForItsCandidateToRetireBeforeKeepingLastGood() + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + DisposablePipeline.rejectConfiguration = true; + DisposablePipeline.pendingRetirements = 2; + asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); + + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + + Assert.Equal(3, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + DisposablePipeline.rejectConfiguration = false; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReloadRetirementDrainsPendingBeforeFinishingTheTransaction(bool commit) + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + IRenderRuntimeReloadTransaction transaction = runtime.BeginExtensionReload(); + transaction.Prepare(); + transaction.Activate(); + DisposablePipeline.pendingRetirements = 2; + + if (commit) + { + transaction.Complete(); + } + else + { + transaction.Rollback(); + } + + Assert.Equal(3, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + runtime.BeginExtensionReload().Rollback(); + } + + [Fact] + public void TargetCapacityRejectsBeforeNativeAllocationAndReopensAfterRelease() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var targets = new RenderTargetStore(backend, capacity: 1); + backend.BeginFrame(); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); + var first = new RenderTexture("First", descriptor); + var second = new RenderTexture("Second", descriptor); + var graph = new RenderGraphBuilder(1, backend.capabilities); + targets.Import(graph, first); + Assert.Throws(() => targets.Import(graph, second)); + Assert.Single(device.createdTextures); + Assert.Equal(1, targets.rejectedCount); + targets.Release(first); + targets.PrepareFrame(); + targets.Import(new RenderGraphBuilder(2, backend.capabilities), second); + Assert.Equal(1, targets.count); + targets.Dispose(); + Assert.Equal(device.createdTextures.Count, device.destroyedTextures.Count); + backend.EndFrame(); + } + + [Fact] + public void UploadAdmissionResetsEachFrameWithoutGrowingResidentPages() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), resourceLimits: + new RenderResourceLimits { uploadPages = 1, uploadResidentBytes = 4096, uploadBytesPerFrame = 36 }); + for (int frame = 0; frame < 256; frame++) + { + runtime.Submit(CreateRequest("Upload budget", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, runtime.resourceStatistics.uploadPages); + Assert.Equal(36, runtime.resourceStatistics.uploadedFrameBytes); + } + Assert.Equal(256, runtime.resourceStatistics.rejectedUploads); + Assert.Single(device.createdBuffers); + runtime.Dispose(); + Assert.Single(device.destroyedBuffers); + } + + [Fact] + public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var targets = new RenderTargetStore(device); + device.BeginFrame(); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); + var graph = new RenderGraphBuilder(1, device.capabilities); + targets.Import(graph, new RenderTexture("First", descriptor)); + targets.Import(graph, new RenderTexture("Second", descriptor)); + targets.Import(graph, new RenderTexture("Third", descriptor)); + proxy.failFirstTextureRetirement = true; + proxy.pendingTextureRetirement = proxy.createdTextures[1]; + + Assert.Throws(targets.Dispose); + Assert.Equal(2, proxy.textureRetirementAttempts); + Assert.True(proxy.frameOpen); + Assert.Throws(() => targets.Import(graph, new RenderTexture("Late", descriptor))); + Assert.Throws(targets.Dispose); + Assert.Equal(4, proxy.textureRetirementAttempts); + Assert.Equal(proxy.createdTextures.Skip(1), proxy.destroyedTextures); + targets.Dispose(); + Assert.Equal(4, proxy.textureRetirementAttempts); + device.EndFrame(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(bool duringFrame) + { + var modules = new ModuleHost(new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) + }); + var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + var runtime = new RenderRuntime(types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + DisposablePipeline.retirementExpired = true; + try + { + if (duringFrame) + { + asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); + DisposablePipeline.rejectConfiguration = true; + runtime.Submit(CreateRequest("Faulting candidate", asset)); + BeginRenderFrame(runtime, 0f); + Assert.Throws(() => runtime.AfterRender(default)); + Assert.True(device.frameOpen); + } + else + { + Assert.Throws(runtime.Dispose); + } + Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); + Assert.Throws(() => runtime.RegisterContributor(new SideEffectContributor())); + Assert.Throws(() => runtime.BeginExtensionReload()); + Assert.ThrowsAny(() => types.Rebuild()); + Assert.Equal(1, DisposablePipeline.retirementAttempts); + Assert.Equal(0, TestRequestProvider.retirementAttempts); + Assert.Equal(0, device.endFrameCount); + + DisposablePipeline.retirementExpired = false; + Assert.ThrowsAny(runtime.Dispose); + Assert.ThrowsAny(types.Dispose); + Assert.ThrowsAny(modules.Dispose); + Assert.Equal(1, DisposablePipeline.retirementAttempts); + Assert.Equal(0, device.endFrameCount); + } + finally + { + DisposablePipeline.retirementExpired = false; + DisposablePipeline.rejectConfiguration = false; + } + } + + [Fact] + public void RuntimeKeepsItsMaintenanceFrameOpenUntilTargetsFinishRetiring() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var target = new RenderTexture( + "Pending Target", + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest( + "Target", + RenderTarget.FromTexture(target), + new RenderViewport(0, 0, 16, 16), + new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID } + ) + ); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + proxy.pendingTextureRetirement = Assert.Single(proxy.createdTextures); + + runtime.Dispose(); + + Assert.Equal(2, proxy.textureRetirementAttempts); + Assert.Single(proxy.destroyedTextures); + Assert.False(proxy.frameOpen); + Assert.Equal(2, proxy.endFrameCount); + } + + [Fact] + public void RemovingAndRestoringPluginRenderingCommitsTheSameUnavailableStateAsColdStart() + { + const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin"; + DotNetModuleSource plugin = CreateRenderingPluginRequest(); + AssemblyModuleHandle activeModule = m_modules.Load(plugin); + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, device, diagnostics); + var asset = new RenderPipelineAsset { pipelineTypeId = C_EXTENSION_ID }; + var featureAsset = new RenderPipelineAsset + { + pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID, + features = [new RenderFeatureConfiguration("tests.runtime.reloadable-plugin-feature")] + }; + + runtime.Submit(CreateRequest("Before Removal", asset)); + runtime.Submit(CreateRequest("Feature Before Removal", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, proxy.executeCount); + proxy.ReleaseRecordedGraph(); + + QueueCollectiblePayload(runtime, m_types, asset); + (IAssemblyUnloadProbe removalMonitor, IRenderRuntimeReloadTransaction renderingRemoval) = RemoveRenderingPlugin( + runtime, + m_modules, + plugin + ); + + ForceCollection(); + Assert.True(removalMonitor.isCompleted); + GC.KeepAlive(renderingRemoval); + + runtime.Submit(CreateRequest("While Unavailable", asset)); + runtime.Submit(CreateRequest("Feature While Unavailable", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, proxy.executeCount); + Assert.DoesNotContain( + diagnostics.items, + static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED" + ); + + IRenderRuntimeReloadTransaction renderingRecovery = runtime.BeginExtensionReload(); + using (AssemblyReloadSession recovery = m_modules.BeginReload([plugin])) + { + activeModule = recovery.context.module; + recovery.Activate(); + renderingRecovery.Prepare(); + renderingRecovery.Activate(); + _ = recovery.Complete(); + renderingRecovery.Complete(); + } + + runtime.Submit(CreateRequest("After Recovery", asset)); + runtime.Submit(CreateRequest("Feature After Recovery", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(2, proxy.executeCount); + + proxy.ReleaseRecordedGraph(); + runtime.Detach(); + IAssemblyUnloadProbe recoveryMonitor = m_modules.Unload(activeModule); + ForceCollection(); + Assert.True(recoveryMonitor.isCompleted); + } + + [Fact] + public void RemovingUnusedRenderingPluginReleasesItsAssemblyContext() + { + DotNetModuleSource plugin = CreateRenderingPluginRequest(); + _ = m_modules.Load(plugin); + IAssemblyUnloadProbe monitor = RemoveUnusedPlugin(m_modules, plugin); + + ForceCollection(); + + Assert.True(monitor.isCompleted); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FrameStatisticsReportBackendCommandsAndGraphCulling(bool reportsAllocations) + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.frameCounters = new RenderDeviceFrameCounters(3, 2); + proxy.allocationCounters = reportsAllocations + ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) + : null; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + using IDisposable executionScope = runtime.EnterExecutionScope(); + var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; + runtime.Attach(); + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + runtime.Submit( + new RenderRequest("Statistics", RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), asset) + ); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + RenderFrameStatistics statistics = Assert.IsType(GraphicsSettings.frameStatistics); + Assert.Equal(1, statistics.viewCount); + Assert.Equal(3, statistics.drawCount); + Assert.Equal(2, statistics.dispatchCount); + Assert.Equal(1, statistics.culledPassCount); + Assert.Equal(proxy.allocationCounters, statistics.allocationCounters); + proxy.allocationCounters = new RenderDeviceAllocationCounters(device.generation, 19, 25, 13); + Assert.NotEqual(proxy.allocationCounters, statistics.allocationCounters); + runtime.Detach(); + } + + [Fact] + public void DeviceSynchronizationIsRequiredAndUnsupportedDiagnosticsAreExplicitlyUnavailable() + { + Assert.True(typeof(IRenderDevice).GetMethod(nameof(IRenderDevice.SetVerticalSync))!.IsAbstract); + using var backend = new RecordingRenderDevice(); + IRenderDevice device = backend; + device.SetVerticalSync(true); + Assert.True(backend.verticalSync); + device.SetVerticalSync(false); + Assert.False(backend.verticalSync); + Assert.Null(device.allocationCounters); + Assert.Throws(() => new RenderDeviceAllocationCounters(0, 0, 0, 0)); + } + + [Fact] + public void GraphicsFacadeResolvesTheCurrentlyBoundRenderingRuntime() + { + IRenderDevice firstDevice = TestDeviceProxy.Create(out TestDeviceProxy firstProxy); + IRenderDevice secondDevice = TestDeviceProxy.Create(out TestDeviceProxy secondProxy); + firstProxy.frameCounters = new RenderDeviceFrameCounters(2, 0); + secondProxy.frameCounters = new RenderDeviceFrameCounters(7, 1); + using var first = new RenderRuntime(m_types, firstDevice, new TestDiagnosticSink()); + using var second = new RenderRuntime(m_types, secondDevice, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; + + using (first.EnterExecutionScope()) + { + first.Attach(); + Assert.True(first.TryActivateDefaultPipeline(asset)); + first.Submit(CreateRequest("First Runtime", asset)); + BeginRenderFrame(first, 0f); + first.AfterRender(default); + first.EndFrame(default); + Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + + using (second.EnterExecutionScope()) + { + second.Attach(); + Assert.True(second.TryActivateDefaultPipeline(asset)); + second.Submit(CreateRequest("Second Runtime", asset)); + BeginRenderFrame(second, 0f); + second.AfterRender(default); + second.EndFrame(default); + Assert.Equal(7, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + } + + Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + } + + Assert.Null(GraphicsSettings.frameStatistics); + Assert.Throws(() => GraphicsSettings.defaultPipeline = asset); + second.Detach(); + first.Detach(); + } + + [Fact] + public void RequestProviderProducesCurrentFrameWorkThroughPublicPluginApi() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + TestRequestProvider.pipeline = asset; + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Attach(); + + BeginRenderFrame(runtime, 1f / 60f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, TestRequestProvider.submitCount); + Assert.Equal(1, proxy.executeCount); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Request[0] Provider Request/Visible", pass.name); + runtime.Detach(); + } + + [Fact] + public void RequestProviderReceivesExplicitHostContentScope() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + Guid contentID = Guid.Parse("3aee0ced-b598-4366-ab45-a6ef8e0feb30"); + var content = new TestContent(); + var identities = new IdentityAllocator(); + identities.Register(content, contentID); + var scope = new ContentReadScope([content.identity], contentID); + Assert.True(scope.TryGetValue(contentID, out TestContent? resolved)); + Assert.Same(content, resolved); + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), contentScopeProvider: () => scope); + runtime.Attach(); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Same(scope, TestRequestProvider.lastContent); + Assert.Throws(() => scope.TryGetValue(contentID, out TestContent? _)); + runtime.Detach(); + } + + [Fact] + public void PrimaryPresentationViewportIsSharedAndLetterboxSurfaceIsCleared() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.presentationSize = new RenderPresentationSize(1000, 1000); + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + primaryPresentationViewportProvider: static size => new RenderViewport( + 0, + (size.height - 562) / 2, + size.width, + 562 + ) + ); + runtime.Attach(); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new RenderViewport(0, 219, 1000, 562), TestRequestProvider.lastPresentationViewport); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Primary Presentation Background", pass.name); + Assert.True(pass.clearsPresentationTarget); + Assert.Equal(new RenderClearColor(0f, 0f, 0f, 1f), pass.presentationClearColor); + runtime.Detach(); + } + + [Fact] + public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.presentationSize = new RenderPresentationSize(2560, 1440); + TestRequestProvider.enabled = true; + var snapshot = new InputSnapshot( + 1, + mousePosition: new Vector2(400f, 274f), + mouseButtonsPressed: [MouseButton.Left] + ); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + inputSnapshotProvider: () => snapshot, + primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720) + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); + Assert.Single(TestRequestProvider.lastInput.buttonsPressed); + } + + [Fact] + public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + proxy.capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + proxy.presentationSize = new RenderPresentationSize(1000, 1000); + FirstTestRenderModel.enabled = true; + SecondTestRenderModel.enabled = true; + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + primaryPresentationViewportProvider: static _ => new RenderViewport(100, 200, 800, 600), + compositionProgramProvider: new TestCompositionProgramProvider() + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(0, FirstTestRenderModel.buildCount); + Assert.Equal(0, SecondTestRenderModel.buildCount); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("Multiple rendering models", StringComparison.Ordinal) + )); + + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []), + new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []) + ] + ) + ); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, FirstTestRenderModel.buildCount); + Assert.Equal(1, SecondTestRenderModel.buildCount); + Assert.Equal( + [new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], + CompositionLayerPipeline.viewports + ); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); + Assert.DoesNotContain(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("independent model targets", StringComparison.Ordinal) + )); + Assert.True( + diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), + string.Join("\n", diagnostics.items.Select(item => item.message)) + ); + Assert.True(proxy.lastGraph is not null, string.Join("\n", diagnostics.items.Select(item => item.message))); + Assert.Contains(proxy.lastGraph.passes, pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); + runtime.Detach(); + } + + [Fact] + public void OutputWithoutAnApplicableModelReportsItsMissingRenderer() + { + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("No rendering model", StringComparison.Ordinal) + )); + runtime.Detach(); + } + + [Fact] + public void LinearPresentationReceivesOneTransferAfterAllModelLayers() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.primaryPresentationEncodesSrgb = false; + proxy.presentationSize = new RenderPresentationSize(800, 600); + FirstTestRenderModel.enabled = true; + SecondTestRenderModel.enabled = true; + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + compositionProgramProvider: new TestCompositionProgramProvider() + ); + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []), + new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []) + ] + ) + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); + Assert.NotNull(proxy.lastGraph); + Assert.Single(proxy.lastGraph.passes.Where(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); + Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); + Assert.Contains(proxy.lastGraph.textures, texture => ( + texture.name.EndsWith("/Composition", StringComparison.Ordinal) + && texture.descriptor.width == 800 + && texture.descriptor.height == 600 + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); + runtime.Detach(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEncodesSrgb) + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.primaryPresentationEncodesSrgb = presentationEncodesSrgb; + proxy.presentationSize = new RenderPresentationSize(800, 600); + FirstTestRenderModel.enabled = true; + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + compositionProgramProvider: new TestCompositionProgramProvider() + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, FirstTestRenderModel.buildCount); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); + Assert.NotNull(proxy.lastGraph); + Assert.Equal( + presentationEncodesSrgb ? 0 : 1, + proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal)) + ); + Assert.DoesNotContain( + proxy.lastGraph.textures, + texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal) + ); + if (!presentationEncodesSrgb) + { + Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); + Assert.Contains(proxy.lastGraph.textures, texture => ( + texture.name.Contains("Model Layer 1", StringComparison.Ordinal) + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); + } + runtime.Detach(); + } + + [Fact] + public void EditorOwnedOffscreenOutputsDoNotReportAnUnusedPrimaryModel() + { + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); + runtime.SetPrimaryModelOutputEnabled(false); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); + runtime.Detach(); + } + + [Fact] + public void MultipleRequestsAndContributorsCompileAndExecuteAsOneFrameGraph() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var contributor = new SideEffectContributor(); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), [contributor]); + runtime.Submit(CreateRequest("Second", asset, priority: 10)); + runtime.Submit(CreateRequest("First", asset, priority: -10)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, proxy.executeCount); + string[] names = Assert.IsType(proxy.lastGraph).passes + .Select(static pass => pass.name) + .ToArray(); + string[] expectedNames = + [ + "Request[0] First/Visible", + "Request[1] Second/Visible", + "Contributor[0] SideEffectContributor/Overlay" + ]; + Assert.Equal(expectedNames, names); + runtime.Detach(); + } + + [Fact] + public void OverlappingRequestsPreserveEarlierPresentationLayersInSchedulingOrder() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Overlay", asset, priority: 100)); + runtime.Submit(CreateRequest("Base", asset, priority: 0)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal( + new[] + { + new PresentationObservation("Base", false), + new PresentationObservation("Overlay", true) + }, + PresentationPipeline.observations + ); + Assert.Equal(1, proxy.executeCount); + runtime.Detach(); + } + + [Fact] + public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(new RenderRequest("Left", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 64), asset)); + runtime.Submit(new RenderRequest("Right", RenderTarget.backbuffer, new RenderViewport(32, 0, 32, 64), asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal( + new[] + { + new PresentationObservation("Left", false), + new PresentationObservation("Right", false) + }, + PresentationPipeline.observations + ); + runtime.Detach(); + } + + [Fact] + public void FailedRequestDoesNotClaimThePresentationTarget() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; + var valid = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Failed", failed, priority: 0)); + runtime.Submit(CreateRequest("Recovery", valid, priority: 100)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new[] { new PresentationObservation("Recovery", false) }, PresentationPipeline.observations); + runtime.Detach(); + } + + [Fact] + public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrames() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var registry = new RenderTargetStore(device); + var target = new RenderTexture( + "Deferred Target", + new RenderTextureDescriptor( + 32, + 32, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = registry.Import(new RenderGraphBuilder(1, device.capabilities), target); + _ = device.EndFrame(); + PersistentTextureHandle first = Assert.Single(proxy.createdTextures); + + target.Resize( + new RenderTextureDescriptor( + 64, + 64, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + device.BeginFrame(); + registry.PrepareFrame(); + _ = registry.Import(new RenderGraphBuilder(2, device.capabilities), target); + _ = device.EndFrame(); + PersistentTextureHandle second = proxy.createdTextures[1]; + Assert.Empty(proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + Assert.Empty(proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + Assert.Equal(new[] { first }, proxy.destroyedTextures); + + registry.Release(target); + for (int frame = 0; frame < 2; frame++) + { + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + } + Assert.Equal(new[] { first }, proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + registry.Dispose(); + _ = device.EndFrame(); + Assert.Equal(new[] { first, second }, proxy.destroyedTextures); + } + + [Fact] + public void DetachUsesADeviceSafetyFrameToReleaseResidentTargets() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var target = new RenderTexture( + "Detach Target", + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest("Detach", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 16, 16), asset) + ); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + PersistentTextureHandle resident = Assert.Single(proxy.createdTextures); + + runtime.Detach(); + + Assert.Equal(new[] { resident }, proxy.destroyedTextures); + Assert.False(proxy.frameOpen); + Assert.Equal(2, proxy.endFrameCount); + } + + [Fact] + public void FailedRequestRollsBackWithoutDiscardingOtherRequests() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; + var valid = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, diagnostics); + runtime.Submit(CreateRequest("A Failed", failed)); + runtime.Submit(CreateRequest("B Valid", valid)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, proxy.executeCount); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Request[1] B Valid/Visible", pass.name); + Assert.Contains(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.DoesNotContain(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); + runtime.Detach(); + } + + [Fact] + public void FrameUploadsReusePagesAndResetSliceOffsetsBetweenFrames() + { + var device = new RecordingRenderDevice(); + var asset = new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + + runtime.Submit(CreateRequest("Upload A", asset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.createBufferCount); + Assert.Equal(new[] { 0, 3 }, device.bufferUpdateOffsets.ToArray()); + Assert.Equal(0, UploadPipeline.firstSlice.firstElement); + Assert.Equal(3, UploadPipeline.secondSlice.firstElement); + Assert.Equal(3, UploadPipeline.secondSlice.elementCount); + + UploadPipeline.singleUpload = true; + runtime.Submit(CreateRequest("Upload B", asset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.createBufferCount); + Assert.Equal(new[] { 0, 3, 0 }, device.bufferUpdateOffsets.ToArray()); + Assert.Equal(0, UploadPipeline.firstSlice.firstElement); + runtime.Detach(); + } + + [Fact] + public void TexturePrewarmRunsOutsideTheRenderFrameAndDoesNotDelaySubmission() + { + var texture = new TextureAsset(1, 1, TextureColorSpace.Srgb, "png"); + Assert.True(m_identities.Register(texture)); + TexturePrewarmPipeline.texture = texture; + + var compiler = new DelayedTextureArtifactSource(); + var device = new RecordingRenderDevice(); + var asset = new RenderPipelineAsset { pipelineTypeId = TexturePrewarmPipeline.C_EXTENSION_ID }; + var artifacts = new DelayedArtifactProvider(compiler); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), targetArtifacts: artifacts); + runtime.Submit(CreateRequest("Prewarm", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.endFrameCount); + Assert.True(compiler.started.Wait(TimeSpan.FromSeconds(2))); + Assert.False(compiler.isCompleted); + compiler.Complete([1, 2, 3, 4]); + runtime.Detach(); + } + + [Fact] + public void PendingShaderCompilationDoesNotPublishAnUnavailableArtifactError() + { + var contract = new ShaderContractID("tests.pending.contract"); + var role = new ShaderPassRoleID("draw"); + var pass = new ShaderPassDefinition("draw", ShaderProgramKind.Raster); + var shader = new ShaderAsset(); + Assert.True(m_identities.Register(shader)); + shader.SetDefinition( + new ShaderDefinition( + "Pending Shader", + [], + [], + [pass], + [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + contract, + [new ShaderTechniquePass(role, pass.name)] + )] + ), + m_serialization, + SerializationContext.empty + ); + PendingShaderPipeline.material = new MaterialAsset { shader = shader }; + PendingShaderPipeline.contract = contract; + PendingShaderPipeline.role = role; + + var diagnostics = new TestDiagnosticSink(); + var compiler = new DelayedTextureArtifactSource(); + var runtime = new RenderRuntime( + m_types, + new RecordingRenderDevice(), + diagnostics, + targetArtifacts: new DelayedArtifactProvider(compiler) + ); + var asset = new RenderPipelineAsset { pipelineTypeId = PendingShaderPipeline.C_EXTENSION_ID }; + runtime.Submit(CreateRequest("Pending Shader", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.False(PendingShaderPipeline.resolved); + Assert.DoesNotContain( + diagnostics.items, + static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE" + ); + runtime.Detach(); + } + + [Fact] + public async Task PersistentTextureRegionUpdateAndReadbackCompleteAcrossFrameBoundaries() + { + var device = new RecordingRenderDevice(supportsReadback: true); + ReadbackPipeline.texture = device.textureHandle; + var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Readback", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new RenderTextureRegion(0, 1, 1, 0, 2, 2), device.updatedRegion); + Assert.Equal(Enumerable.Range(0, 16).Select(static value => (byte)value), device.updatedBytes); + Task readback = Assert.IsType>( + ReadbackPipeline.readback + ); + Assert.False(readback.IsCompleted); + + device.readbackReady = true; + BeginRenderFrame(runtime, 0f); + RenderTextureReadbackResult result = await readback; + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(16, result.rowPitch); + Assert.Equal(64, result.data.Length); + Assert.All(result.data.ToArray(), static value => Assert.Equal((byte)37, value)); + runtime.Detach(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PendingUploadOrReadbackRetirementPreservesDependentWork(bool pendingReadback) + { + var device = new RecordingRenderDevice(supportsReadback: true); + ReadbackPipeline.texture = device.textureHandle; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Upload", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); + runtime.Submit(CreateRequest("Readback", new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID })); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Task readback = Assert.IsType>(ReadbackPipeline.readback); + device.pendingBufferRetirements = pendingReadback ? 0 : 1; + device.pendingReadbackRetirements = pendingReadback ? 1 : 0; + + runtime.Dispose(); + + Assert.Equal(pendingReadback ? 1 : 2, device.bufferRetirementAttempts); + Assert.Equal(pendingReadback ? 2 : 1, device.cancelReadbackCount); + Assert.Equal(2, device.endFrameCount); + await Assert.ThrowsAsync(async () => await readback); + runtime.Dispose(); + Assert.Equal(2, device.endFrameCount); + } + + [Fact] + public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBoundary() + { + var device = new RecordingRenderDevice(supportsReadback: true); + using var cancellation = new CancellationTokenSource(); + ReadbackPipeline.texture = device.textureHandle; + ReadbackPipeline.cancellationToken = cancellation.Token; + var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Canceled Readback", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + cancellation.Cancel(); + Task readback = Assert.IsType>( + ReadbackPipeline.readback + ); + Assert.False(readback.IsCompleted); + BeginRenderFrame(runtime, 0f); + await Assert.ThrowsAnyAsync(async () => await readback); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.cancelReadbackCount); + runtime.Detach(); + } + + private DotNetModuleSource CreateRenderingPluginRequest() + => new() + { + moduleName = "RenderingRuntimeReloadTests", + artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), + mainAssemblyPath = Path.Combine( + AppContext.BaseDirectory, + "Modules", + "RenderingReload", + "Inno.Rendering.Runtime.Reload.TestModule.dll" + ), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; + + private static void RunResourceFrame(RenderRuntime runtime) + { + runtime.Submit( + CreateRequest("Resource ownership", new RenderPipelineAsset { pipelineTypeId = ResourceProbePipeline.C_EXTENSION_ID }) + ); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + } + + private static RenderRequest CreateRequest( + string name, + RenderPipelineAsset pipeline, + int priority = 0 + ) => new(name, RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), pipeline, priority: priority); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ( + IAssemblyUnloadProbe monitor, + IRenderRuntimeReloadTransaction transaction) RemoveRenderingPlugin( + RenderRuntime runtime, + ModuleHost modules, + DotNetModuleSource plugin + ) { + IRenderRuntimeReloadTransaction rendering = runtime.BeginExtensionReload(); + using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); + removal.Activate(); + rendering.Prepare(); + rendering.Activate(); + IAssemblyUnloadProbe monitor = removal.Complete(); + rendering.Complete(); + return (monitor, rendering); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static IAssemblyUnloadProbe RemoveUnusedPlugin( + ModuleHost modules, + DotNetModuleSource plugin + ) { + using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); + removal.Activate(); + return removal.Complete(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void QueueCollectiblePayload( + RenderRuntime runtime, + TypeCatalog types, + RenderPipelineAsset pipeline + ) { + Type payloadType = types.current.types + .Select(type => type.Resolve(types)) + .Single(type => string.Equals( + type.FullName, + "Inno.Rendering.Runtime.Reload.TestModule.ReloadableFramePayload", + StringComparison.Ordinal + )); + object payload = Activator.CreateInstance(payloadType) + ?? throw new InvalidOperationException("The collectible frame payload could not be created."); + var data = new RenderFrameData(); + data.Set(new RenderDataChannelID("tests.runtime.collectible-payload"), payload); + runtime.Submit( + new RenderRequest( + "Collectible Pending Request", + RenderTarget.backbuffer, + new RenderViewport(0, 0, 64, 64), + pipeline, + data + ) + ); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ForceCollection() + { + for (int attempt = 0; attempt < 8; attempt++) + { + GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + } + } + + private static void BeginRenderFrame( + RenderRuntime runtime, + float deltaTime + ) { + if (!runtime.isStarted) + { + runtime.Attach(); + } + var frame = new RuntimeFrame(0, deltaTime, deltaTime, 0, 0, 1, false); + runtime.BeginFrame(frame); + runtime.BeforeRender(frame); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ResourceProbePipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.resource-owner"; + internal static Action? action; + + public override void Build(RenderPipelineContext context) + { + action?.Invoke(context.resourceService); + context.graph.AddRasterPass("Resources", new RenderPhaseID("tests.resources"), 0, static ( + _, + _ + ) => {}).HasSideEffect(); + } + } + + private sealed class TestContent : IdentityObject; + + [RenderModelExtension(C_EXTENSION_ID)] + private sealed class FirstTestRenderModel : IRenderModel + { + internal const string C_EXTENSION_ID = "tests.runtime.model.first"; + internal static bool enabled; + internal static int buildCount; + + public bool CanRender(RenderOutputSession session) => enabled; + + public RenderModelOutput Build(RenderOutputSession session) + { + buildCount++; + return new RenderModelOutput( + "First Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; + } + } + + [RenderModelExtension(C_EXTENSION_ID)] + private sealed class SecondTestRenderModel : IRenderModel + { + internal const string C_EXTENSION_ID = "tests.runtime.model.second"; + internal static bool enabled; + internal static int buildCount; + + public bool CanRender(RenderOutputSession session) => enabled; + + public RenderModelOutput Build(RenderOutputSession session) + { + buildCount++; + return new RenderModelOutput( + "Second Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class DisposablePipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.disposable"; + + public DisposablePipeline() + { + createdCount++; + } + + public override void Build(RenderPipelineContext context) => _ = context; + + internal static int createdCount { get; private set; } + internal static int disposedCount { get; private set; } + internal static bool rejectConfiguration { get; set; } + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + internal static bool retirementExpired { get; set; } + + protected override void OnConfigure( + SerializedRenderExtensionState state, + RenderExtensionStateContext settings + ) { + _ = state; + if (rejectConfiguration) + { + throw new InvalidOperationException("Rejected pipeline configuration candidate."); + } + } + + protected override void Dispose(bool disposing) + { + _ = disposing; + retirementAttempts++; + if (retirementExpired) + { + throw new RetirementTimeoutException("The pipeline-owned device work exceeded its deadline."); + } + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Pipeline work remains active."); + } + disposedCount++; + } + + internal static void Reset() + { + createdCount = 0; + disposedCount = 0; + rejectConfiguration = false; + pendingRetirements = 0; + retirementAttempts = 0; + retirementExpired = false; + } + } + + [RenderFeatureExtension(C_EXTENSION_ID)] + private sealed class PendingFeature : RenderPipelineFeature, IDisposable + { + internal const string C_EXTENSION_ID = "tests.runtime.pending-feature"; + + public override void AddRenderPasses(RenderFeatureContext context) {} + + public void Dispose() + { + retirementAttempts++; + Assert.Equal(0, DisposablePipeline.disposedCount); + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Feature work remains active."); + } + } + + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + + internal static void Reset() + { + retirementAttempts = 0; + pendingRetirements = 0; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class StatisticsPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.statistics"; + + public override void Build(RenderPipelineContext context) + { + context.graph + .AddRasterPass( + "Visible", + new RenderPhaseID("tests.statistics.visible"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + context.graph.AddRasterPass( + "Culled", + new RenderPhaseID("tests.statistics.culled"), + 0, + static ( + _, + _ + ) => {} + ); + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class CompositionLayerPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.composition-layer"; + + public override void Build(RenderPipelineContext context) + { + viewports.Add(context.request.viewport); + RasterPassBuilder pass = context.graph.AddRasterPass( + "Scene Color", + new RenderPhaseID("tests.runtime.composition-layer"), + 0, + static ( + _, + _ + ) => {} + ); + if (context.outputTexture.isValid) + { + pass.UseColorAttachment( + context.outputTexture, + 0, + RenderLoadAction.Clear, + RenderStoreAction.Store, + new RenderClearColor(0f, 0f, 0f, 0f) + ); + } + else + { + pass.ClearPresentationTarget(default).HasSideEffect(); + } + } + + internal static List viewports { get; } = []; + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class SideEffectPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.side-effect"; + + public override void Build(RenderPipelineContext context) + => context.graph + .AddRasterPass( + "Visible", + new RenderPhaseID("tests.runtime.visible"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class PresentationPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.presentation"; + + public override void Build(RenderPipelineContext context) + { + observations.Add(new PresentationObservation(context.request.name, context.preservePresentationTarget)); + context.graph + .AddRasterPass( + "Presentation", + new RenderPhaseID("tests.runtime.presentation"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static List observations { get; } = []; + + internal static void Reset() => observations.Clear(); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ThrowingPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.throwing"; + + public override void Build(RenderPipelineContext context) + { + context.graph + .AddRasterPass( + "Rolled Back", + new RenderPhaseID("tests.runtime.rolled-back"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + throw new InvalidOperationException("Expected request failure."); + } + } + + private readonly record struct PresentationObservation( + string requestName, + bool preserveTarget + ); + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class UploadPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.upload"; + + public override void Build(RenderPipelineContext context) + { + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var descriptor = new RenderBufferUploadDescriptor(layout.stride, RenderBufferUsage.Vertex, layout); + firstSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); + if (!singleUpload) + { + secondSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); + } + } + + internal static RenderBufferSlice firstSlice { get; private set; } + internal static RenderBufferSlice secondSlice { get; private set; } + internal static bool singleUpload { get; set; } + + internal static void Reset() + { + firstSlice = default; + secondSlice = default; + singleUpload = false; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class TexturePrewarmPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.texture-prewarm"; + + public override void Build(RenderPipelineContext context) + { + context.resourceService.PrewarmTexture( + texture ?? throw new InvalidOperationException("A test texture is required.") + ); + context.graph + .AddRasterPass( + "Submit While Prewarming", + new RenderPhaseID("tests.runtime.prewarm"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static TextureAsset? texture { get; set; } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class PendingShaderPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.pending-shader"; + + public override void Build(RenderPipelineContext context) + { + resolved = context.resourceService.TryResolveGraphicsMaterial( + material ?? throw new InvalidOperationException("A test material is required."), + contract, + role, + null, + null, + out _ + ); + context.graph + .AddRasterPass( + "Submit While Compiling", + new RenderPhaseID("tests.runtime.pending-shader"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static MaterialAsset? material { get; set; } + internal static ShaderContractID contract { get; set; } + internal static ShaderPassRoleID role { get; set; } + internal static bool resolved { get; private set; } + + internal static void Reset() + { + material = null; + contract = default; + role = default; + resolved = false; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ReadbackPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.readback"; + + public override void Build(RenderPipelineContext context) + { + byte[] update = Enumerable.Range(0, 16).Select(static value => (byte)value).ToArray(); + context.resourceService.UpdateTexture(texture, new RenderTextureRegion(0, 1, 1, 0, 2, 2), update); + readback ??= context.resourceService + .ReadTextureAsync(texture, cancellationToken: cancellationToken) + .AsTask(); + context.graph + .AddRasterPass( + "Readback Submission", + new RenderPhaseID("tests.runtime.readback"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static PersistentTextureHandle texture { get; set; } + internal static CancellationToken cancellationToken { get; set; } + internal static Task? readback { get; private set; } + + internal static void Reset() + { + texture = default; + cancellationToken = default; + readback = null; + } + } + + [RenderRequestProviderExtension(C_EXTENSION_ID)] + private sealed class TestRequestProvider : RenderRequestProvider + { + internal const string C_EXTENSION_ID = "tests.runtime.request-provider"; + + public override void Submit(RenderRequestProviderContext context) + { + if (!enabled) + { + return; + } + submitCount++; + lastContent = context.content; + lastPresentationViewport = context.primaryPresentationViewport; + lastInput = context.input; + if (pipeline is null) + { + return; + } + context.requests.Submit(CreateRequest("Provider Request", pipeline)); + } + + internal static bool enabled { get; set; } + internal static RenderPipelineAsset? pipeline { get; set; } + internal static int submitCount { get; private set; } + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + internal static ContentReadScope? lastContent { get; private set; } + internal static RenderViewport? lastPresentationViewport { get; private set; } + internal static RenderOutputInput lastInput { get; private set; } = RenderOutputInput.empty; + + protected override void Dispose(bool disposing) + { + retirementAttempts++; + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Provider work remains active."); + } + } + + internal static void Reset() + { + enabled = false; + pipeline = null; + submitCount = 0; + pendingRetirements = 0; + retirementAttempts = 0; + lastContent = null; + lastPresentationViewport = default; + lastInput = RenderOutputInput.empty; + } + } + + private sealed class SideEffectContributor : IRenderFrameGraphContributor + { + public void PrepareFrame(ulong frameIndex) => _ = frameIndex; + + public void AddRenderPasses( + RenderGraphBuilder graph, + ulong frameIndex + ) { + _ = frameIndex; + graph + .AddRasterPass( + "Overlay", + new RenderPhaseID("tests.runtime.overlay"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + } + + private sealed class TestDiagnosticSink : IDiagnosticReporter + { + public void Publish(Diagnostic diagnostic) => items.Add(diagnostic); + + public void Resolve( + string code, + string? semanticID = null, + Guid? objectID = null + ) => items.RemoveAll(diagnostic => ( + string.Equals(diagnostic.code, code, StringComparison.Ordinal) + && string.Equals(diagnostic.semanticID, semanticID, StringComparison.Ordinal) && diagnostic.objectID == objectID + )); + + public void Replace(IEnumerable diagnostics) + { + items.Clear(); + items.AddRange(diagnostics); + } + + internal List items { get; } = []; + } + + private sealed class TestDeviceProxy : RenderDevice, IRenderDevice + { + private static readonly GraphicsCapabilities CAPABILITIES = new( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + + private int m_bufferCreationCount; + + public RenderDeviceFrameCounters frameCounters { get; internal set; } + public RenderDeviceAllocationCounters? allocationCounters { get; internal set; } + + public GraphicsCapabilities capabilities { get; internal set; } = CAPABILITIES; + public uint generation => 1; + public RenderPresentationSize? presentationSize { get; set; } = new(1, 1); + + public RenderPresentationSize? primaryPresentationSize + { + get => presentationSize; + private set => presentationSize = value; + } + + public bool primaryPresentationEncodesSrgb { get; set; } = true; + + public void SetVerticalSync(bool enabled) => verticalSync = enabled; + + public void BeginFrame() + { + Assert.False(frameOpen); + frameOpen = true; + } + + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { + Assert.True(frameOpen); + _ = frameIndex; + executeCount++; + lastGraph = graph; + } + + public uint EndFrame() + { + Assert.True(frameOpen); + frameOpen = false; + endFrameCount++; + return checked((uint)endFrameCount); + } + + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { + Assert.True(frameOpen); + _ = descriptor; + _ = name; + PersistentTextureHandle texture = CreatePersistentTextureHandle( + checked((ulong)createdTextures.Count + 1), + generation + ); + createdTextures.Add(texture); + return texture; + } + + public void UpdateTexture( + PersistentTextureHandle texture, + ReadOnlySpan data, + int mipLevel = 0, + int arrayLayer = 0 + ) { + _ = texture; + _ = data; + _ = mipLevel; + _ = arrayLayer; + } + + public void UpdateTextureRegion( + PersistentTextureHandle texture, + RenderTextureRegion region, + ReadOnlySpan data + ) { + _ = texture; + _ = region; + _ = data; + } + + public RenderTextureReadbackHandle BeginTextureReadback( + PersistentTextureHandle texture, + int mipLevel = 0 + ) { + _ = texture; + _ = mipLevel; + return default; + } + + public bool TryGetTextureReadback( + RenderTextureReadbackHandle readback, + out RenderTextureReadbackResult? result + ) { + _ = readback; + result = null; + return false; + } + + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => _ = readback; + + public void DestroyTexture(PersistentTextureHandle texture) + { + Assert.True(frameOpen); + textureRetirementAttempts++; + if (failFirstTextureRetirement) + { + failFirstTextureRetirement = false; + throw new InvalidOperationException("Texture retirement failed."); + } + if (texture == pendingTextureRetirement) + { + pendingTextureRetirement = default; + throw new RetirementPendingException("Texture still has pending work."); + } + destroyedTextures.Add(texture); + } + + public PersistentBufferHandle CreateBuffer( + PersistentBufferDescriptor descriptor, + ReadOnlySpan initialData, + string name + ) { + m_bufferCreationCount++; + if (m_bufferCreationCount == failBufferCreationAt) + { + throw new InvalidOperationException("Native allocation rejected."); + } + PersistentBufferHandle handle = CreatePersistentBufferHandle((ulong)m_bufferCreationCount, generation); + createdBuffers.Add(handle); + return handle; + } + + public void UpdateBuffer( + PersistentBufferHandle buffer, + ReadOnlySpan data, + int startElement = 0 + ) { + _ = buffer; + _ = data; + _ = startElement; + } + + public void DestroyBuffer(PersistentBufferHandle buffer) + { + Assert.DoesNotContain(buffer, destroyedBuffers); + destroyedBuffers.Add(buffer); + } + + public GraphicsPipelineHandle CreateGraphicsPipeline( + GraphicsPipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => _ = pipeline; + + public ComputePipelineHandle CreateComputePipeline( + ComputePipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; + + public void Dispose() {} + + internal bool verticalSync { get; private set; } + + internal List createdBuffers { get; } = []; + internal List destroyedBuffers { get; } = []; + internal int failBufferCreationAt { get; set; } + + internal List createdTextures { get; } = []; + internal List destroyedTextures { get; } = []; + internal bool frameOpen { get; private set; } + internal int endFrameCount { get; private set; } + internal int executeCount { get; private set; } + internal int textureRetirementAttempts { get; private set; } + internal bool failFirstTextureRetirement { get; set; } + internal PersistentTextureHandle pendingTextureRetirement { get; set; } + internal CompiledRenderGraph? lastGraph { get; private set; } + + internal void ReleaseRecordedGraph() => lastGraph = null; + + internal static IRenderDevice Create(out TestDeviceProxy proxy) + { + proxy = new TestDeviceProxy(); + return proxy; + } + } + + private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice + { + private readonly RenderTextureDescriptor m_readbackDescriptor = new( + 4, + 4, + RenderTextureFormat.RGBA8, + RenderTextureUsage.Readback + ); + + private readonly RenderTextureReadbackHandle m_readbackHandle; + + internal RecordingRenderDevice(bool supportsReadback = false) + { + this.capabilities = new GraphicsCapabilities( + GraphicsApi.noop, + supportsReadback ? GraphicsCapability.TextureReadback : GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + this.textureHandle = CreatePersistentTextureHandle(1UL, generation); + m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); + } + + public GraphicsCapabilities capabilities { get; } + + public uint generation => 1; + public RenderPresentationSize? primaryPresentationSize { get; private set; } = new(1, 1); + public bool primaryPresentationEncodesSrgb => true; + + public void SetVerticalSync(bool enabled) => verticalSync = enabled; + + public void BeginFrame() {} + + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { + _ = graph; + _ = frameIndex; + executeCount++; + } + + public uint EndFrame() + { + endFrameCount++; + return checked((uint)endFrameCount); + } + + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void UpdateTexture( + PersistentTextureHandle texture, + ReadOnlySpan data, + int mipLevel = 0, + int arrayLayer = 0 + ) { + _ = texture; + _ = data; + _ = mipLevel; + _ = arrayLayer; + } + + public void UpdateTextureRegion( + PersistentTextureHandle texture, + RenderTextureRegion region, + ReadOnlySpan data + ) { + Assert.Equal(textureHandle, texture); + updatedRegion = region; + updatedBytes = data.ToArray(); + } + + public RenderTextureReadbackHandle BeginTextureReadback( + PersistentTextureHandle texture, + int mipLevel = 0 + ) { + Assert.Equal(textureHandle, texture); + _ = mipLevel; + return m_readbackHandle; + } + + public bool TryGetTextureReadback( + RenderTextureReadbackHandle readback, + out RenderTextureReadbackResult? result + ) { + Assert.Equal(m_readbackHandle, readback); + result = readbackReady + ? new RenderTextureReadbackResult( + m_readbackDescriptor, + 0, + 16, + Enumerable.Repeat((byte)37, 64).ToArray() + ) + : null; + return result is not null; + } + + public void CancelTextureReadback(RenderTextureReadbackHandle readback) + { + Assert.Equal(m_readbackHandle, readback); + cancelReadbackCount++; + if (pendingReadbackRetirements > 0) + { + pendingReadbackRetirements--; + Assert.False(ReadbackPipeline.readback!.IsCompleted); + Assert.Equal(1, endFrameCount); + throw new RetirementPendingException("Readback cancellation remains active."); + } + } + + public void DestroyTexture(PersistentTextureHandle texture) => _ = texture; + + public PersistentBufferHandle CreateBuffer( + PersistentBufferDescriptor descriptor, + ReadOnlySpan initialData, + string name + ) { + _ = descriptor; + _ = initialData; + _ = name; + createBufferCount++; + return default; + } + + public void UpdateBuffer( + PersistentBufferHandle buffer, + ReadOnlySpan data, + int startElement = 0 + ) { + _ = buffer; + _ = data; + bufferUpdateOffsets.Add(startElement); + } + + public void DestroyBuffer(PersistentBufferHandle buffer) + { + bufferRetirementAttempts++; + if (pendingBufferRetirements > 0) + { + pendingBufferRetirements--; + Assert.Equal(0, cancelReadbackCount); + Assert.False(ReadbackPipeline.readback!.IsCompleted); + Assert.Equal(1, endFrameCount); + throw new RetirementPendingException("Upload work remains active."); + } + } + + public GraphicsPipelineHandle CreateGraphicsPipeline( + GraphicsPipelineDescriptor descriptor, + string name + ) { + if (name == failProgramName) throw new InvalidOperationException("Injected program allocation failure."); + GraphicsPipelineHandle handle = CreateGraphicsPipelineHandle(checked((ulong)createdPrograms.Count + 1), generation); + createdPrograms.Add(handle); + programDescriptors.Add(descriptor); + return handle; + } + + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) + { + programRetirementAttempts++; + if (pendingProgramRetirements > 0) + { + pendingProgramRetirements--; + throw new RetirementPendingException("Injected unfinished program retirement."); + } + Assert.DoesNotContain(pipeline, destroyedPrograms); + destroyedPrograms.Add(pipeline); + if (failedProgramRetirements > 0) + { + failedProgramRetirements--; + throw new InvalidOperationException("Injected completed program retirement failure."); + } + } + + public ComputePipelineHandle CreateComputePipeline( + ComputePipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; + + public void Dispose() {} + + internal List createdPrograms { get; } = []; + internal List destroyedPrograms { get; } = []; + internal List programDescriptors { get; } = []; + internal string? failProgramName { get; set; } + internal int pendingProgramRetirements { get; set; } + internal int failedProgramRetirements { get; set; } + internal int programRetirementAttempts { get; private set; } + internal bool verticalSync { get; private set; } + + internal List bufferUpdateOffsets { get; } = []; + internal PersistentTextureHandle textureHandle { get; } + internal RenderTextureRegion? updatedRegion { get; private set; } + internal byte[] updatedBytes { get; private set; } = []; + internal bool readbackReady { get; set; } + internal int cancelReadbackCount { get; private set; } + internal int pendingReadbackRetirements { get; set; } + internal int pendingBufferRetirements { get; set; } + internal int bufferRetirementAttempts { get; private set; } + internal int createBufferCount { get; private set; } + internal int endFrameCount { get; private set; } + internal int executeCount { get; private set; } + } + + private sealed class DelayedTextureArtifactSource + { + private readonly TaskCompletionSource m_completion = new( + TaskCreationOptions.RunContinuationsAsynchronously + ); + + internal ManualResetEventSlim started { get; } = new(initialState: false); + internal bool isCompleted => m_completion.Task.IsCompleted; + + internal Task LoadAsync(CancellationToken cancellationToken = default) + { + started.Set(); + return m_completion.Task.WaitAsync(cancellationToken); + } + + internal void Complete(byte[] data) => m_completion.TrySetResult(data); + } + + private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) : IRenderTargetArtifactProvider + { + private Task? m_texture; + + public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) + => throw new InvalidOperationException("This pending provider never publishes a shader artifact."); + + public RenderTargetArtifactStatus GetShaderArtifact( + ShaderAsset shader, + RenderShaderVariant variant, + GraphicsCapabilities capabilities, + out RenderShaderArtifact? artifact + ) { + _ = shader; + _ = variant; + _ = capabilities; + artifact = null; + return RenderTargetArtifactStatus.Pending; + } + + public RenderTargetArtifactStatus GetTextureArtifact( + RenderTextureArtifactReference texture, + out ReadOnlyMemory artifact + ) { + _ = texture; + m_texture ??= compiler.LoadAsync(); + if (m_texture.IsCompletedSuccessfully) + { + artifact = m_texture.Result; + return RenderTargetArtifactStatus.Ready; + } + artifact = ReadOnlyMemory.Empty; + return RenderTargetArtifactStatus.Pending; + } + } + + private sealed class TestCompositionProgramProvider : IRenderLayerCompositionProgramProvider + { + public GraphicsPipelineDescriptor CreateDescriptor( + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) { + _ = capabilities; + return new GraphicsPipelineDescriptor( + [1], + [1], + [new RenderShaderBindingDescriptor( + new RenderBindingID("s_tex"), + RenderShaderBindingKind.Texture, + 0, + nativeName: "s_tex" + )], + vertexLayout + ); + } + + public GraphicsPipelineDescriptor CreateOutputTransferDescriptor( + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) => CreateDescriptor(capabilities, vertexLayout); + } +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs new file mode 100644 index 000000000..9487f1a3a --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs @@ -0,0 +1,15 @@ +using System; +using Xunit; + +namespace Inno.Rendering.Shaders.Tests; + +public sealed class MetalShaderFactAttribute : FactAttribute +{ + public MetalShaderFactAttribute() + { + if (!OperatingSystem.IsMacOS()) + { + this.Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; + } + } +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs new file mode 100644 index 000000000..c9c36b92b --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders.Tests; + +internal sealed class NodeRegistryProbe : IShaderNodeCompiler, IDisposable +{ + internal static int created; + internal static int disposed; + internal static bool conflict; + private readonly string m_id; + + public NodeRegistryProbe() + { + created++; + m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; + } + + public string definitionID => m_id; + + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; + + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); + + public void Dispose() => disposed++; +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs new file mode 100644 index 000000000..04c66036e --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs @@ -0,0 +1,33 @@ +using System; + +namespace Inno.Rendering.Shaders.Tests; + +internal sealed class RegistryFrontendProbe : IShaderSourceFrontend, IDisposable +{ + internal static int created; + internal static int disposed; + internal static bool conflict; + private readonly string m_languageID; + + public RegistryFrontendProbe() + { + created++; + m_languageID = conflict ? "inno.shader-language.bgfx-sc" : "tests.registry.language"; + } + + public string languageID => m_languageID; + + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) + => new( + new ShaderSourceFunction( + request.entryPoint, + ShaderSourceType.Atomic("float"), + [], + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ), + [], + [] + ); + + public void Dispose() => disposed++; +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs index 81aa2ee98..bde39212b 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs @@ -5,4 +5,4 @@ namespace Inno.Rendering.Shaders.Tests; // These fixtures deliberately change process-visible extension declarations. Other tests discover // the same declarations, so fault injection must not overlap another registry's construction. [CollectionDefinition("Shader registry fault injection", DisableParallelization = true)] -public sealed class RegistryLifetimeCollection { } +public sealed class RegistryLifetimeCollection; diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs index 9e96a10ad..f4e4cd427 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs @@ -1,9 +1,9 @@ -using Inno.Integration.WindowsX64.Bgfx; using System; +using Xunit; using Inno.Adapter.Rendering; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.WindowsX64.Bgfx; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -13,42 +13,51 @@ public sealed class RenderingBackendRegistrationTests [Fact] public void RuntimeAndAuthoringRegistrationsAreOpenAndPairedBeforeDeviceCreation() { - var id = new RenderingBackendId("tests.independent-renderer"); + var id = new RenderingBackendID("tests.independent-renderer"); var provider = new RuntimeProvider(id); var runtime = new RenderingBackendCatalog([provider]); var authoring = new RenderingAuthoringBackendCatalog(runtime, [new AuthoringProvider(id)]); Assert.Equal(id, Assert.Single(runtime.supportedBackends)); Assert.Equal(id, Assert.Single(authoring.supportedBackends)); Assert.False(provider.wasCreated); - Assert.Throws(() => runtime.CreateDevice(RenderingBackendId.bgfx, new RenderingBackendOptions())); + Assert.Throws(() => runtime.CreateDevice(RenderingBackendID.bgfx, new RenderingBackendOptions())); Assert.False(provider.wasCreated); } [Fact] public void DuplicateUnassignedAndUnpairedRegistrationsFail() { - var id = new RenderingBackendId("tests.renderer"); + var id = new RenderingBackendID("tests.renderer"); Assert.Throws(() => new RenderingBackendCatalog([new RuntimeProvider(id), new RuntimeProvider(id)])); Assert.Throws(() => new RenderingBackendCatalog([new RuntimeProvider(default)])); var runtime = new RenderingBackendCatalog([new RuntimeProvider(id)]); Assert.Throws(() => new RenderingAuthoringBackendCatalog(runtime, [])); - Assert.Throws(() => new RenderingAuthoringBackendCatalog(runtime, [new AuthoringProvider(RenderingBackendId.bgfx)])); - Assert.Throws(() => new RenderingBackendId("invalid id")); - Assert.False(default(RenderingBackendId).isValid); + Assert.Throws( + () => new RenderingAuthoringBackendCatalog(runtime, [new AuthoringProvider(RenderingBackendID.bgfx)]) + ); + Assert.Throws(() => new RenderingBackendID("invalid id")); + Assert.False(default(RenderingBackendID).isValid); } - private sealed class RuntimeProvider(RenderingBackendId id) : RenderingBackendProvider(id) + private sealed class RuntimeProvider(RenderingBackendID id) : RenderingBackendProvider(id) { public bool wasCreated { get; private set; } + public override IRenderDevice CreateDevice(RenderingBackendOptions options) - { wasCreated = true; throw new InvalidOperationException("These registration tests must not create a GPU device."); } + { + wasCreated = true; + throw new InvalidOperationException("These registration tests must not create a GPU device."); + } + public override IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider() => throw new InvalidOperationException("These registration tests do not create composition programs."); } - private sealed class AuthoringProvider(RenderingBackendId id) : RenderingAuthoringBackendProvider(id) + private sealed class AuthoringProvider(RenderingBackendID id) : RenderingAuthoringBackendProvider(id) { - public override IShaderCompilerToolchain CreateShaderCompilerToolchain() => new BgfxShadercToolchain(Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxShaderProfiles.target); + public override IShaderCompilerToolchain CreateShaderCompilerToolchain() + => new BgfxShadercToolchain(WindowsX64BgfxShaderProfiles.target); + public override ITextureTargetCompiler CreateTextureTargetCompiler() => new BgfxTextureTargetCompiler(); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs index 3093b03e9..5165f5d4a 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs @@ -1,13 +1,13 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.Linq; +using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -21,9 +21,16 @@ public void BranchCapturesOuterValuesButOnlyExposesMergedValues() ShaderIrValue input = builder.Constant(2f); ShaderIrValue? leaked = null; ShaderIrBuilder? retained = null; - IReadOnlyDictionary outputs = builder.Branch(builder.Constant(true), - region => { retained = region; leaked = region.Binary(ShaderIrOperation.Add, input, input); return Values(("result", leaked)); }, - region => Values(("result", region.Constant(3f)))); + IReadOnlyDictionary outputs = builder.Branch( + builder.Constant(true), + region => + { + retained = region; + leaked = region.Binary(ShaderIrOperation.Add, input, input); + return Values(("result", leaked)); + }, + region => Values(("result", region.Constant(3f))) + ); ShaderIrBlock block = builder.Build(outputs); ShaderIrInstruction branch = block.instructions[^1]; Assert.Equal(ShaderIrOperation.Branch, branch.operation); @@ -41,13 +48,22 @@ public void FailedRegionConstructionRollsBackWithoutLeavingInstructionsOrIdentit var builder = new ShaderIrBuilder(); ShaderIrValue condition = builder.Constant(true); ShaderIrValue input = builder.Constant(2f); - Assert.Throws(() => builder.Branch(condition, - region => Values(("first", region.Constant(1f))), region => Values(("renamed", region.Constant(1f))))); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("first", region.Constant(1f))), + region => Values(("renamed", region.Constant(1f))) + )); Assert.Equal(2, builder.Build(Values()).instructions.Count); - Assert.Throws(() => builder.Branch(condition, - region => Values(("result", builder.Constant(1f))), region => Values(("result", input)))); - Assert.Throws(() => builder.Branch(condition, - region => Values(("result", region.Input("hidden-stage-input", input.type))), region => Values(("result", input)))); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("result", builder.Constant(1f))), + region => Values(("result", input)) + )); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("result", region.Input("hidden-stage-input", input.type))), + region => Values(("result", input)) + )); Assert.Equal(2, builder.Constant(4f).index); } @@ -56,9 +72,15 @@ public void SiblingScopesCannotShareUnmergedValues() { var builder = new ShaderIrBuilder(); ShaderIrValue? first = null; - Assert.Throws(() => builder.Branch(builder.Constant(true), - region => { first = region.Constant(1f); return Values(("value", first)); }, - region => Values(("value", first!)))); + Assert.Throws(() => builder.Branch( + builder.Constant(true), + region => + { + first = region.Constant(1f); + return Values(("value", first)); + }, + region => Values(("value", first!)) + )); } [Fact] @@ -67,20 +89,37 @@ public void LoopsHaveExplicitIndicesStateAndSimultaneousNamedOutputs() var builder = new ShaderIrBuilder(); ShaderIrValue first = builder.Constant(1f); ShaderIrValue second = builder.Constant(2f); - IReadOnlyDictionary outputs = builder.Loop(builder.Constant(3u), Values(("b", second), ("a", first)), - (region, index, state) => + IReadOnlyDictionary outputs = builder.Loop( + builder.Constant(3u), + Values(("b", second), ("a", first)), + ( + region, + index, + state + ) => { Assert.Equal("uint", index.type.id); Assert.Equal(["a", "b"], state.Keys); return Values(("a", state["b"]), ("b", state["a"])); - }); + } + ); ShaderIrInstruction loop = builder.Build(outputs).instructions[^1]; Assert.Equal(["iteration", "state.a", "state.b"], loop.regions[0].instructions.Select(static instruction => instruction.inputName)); Assert.Same(first, loop.inputs[1]); Assert.Same(second, loop.inputs[2]); Assert.Equal(["a", "b"], outputs.Keys); - Assert.Throws(() => builder.Loop(builder.Constant(1u), Values(("a", first)), (region, index, state) => Values(("a", index)))); - Assert.Throws(() => builder.Loop(builder.Constant(1), Values(), (region, index, state) => Values())); + Assert.Throws( + () => builder.Loop(builder.Constant(1u), Values(("a", first)), ( + region, + index, + state + ) => Values(("a", index))) + ); + Assert.Throws(() => builder.Loop(builder.Constant(1), Values(), ( + region, + index, + state + ) => Values())); } [Fact] @@ -88,8 +127,19 @@ public void NestedFragmentOnlyEffectsAreStillRejectedByComputeStageValidation() { var builder = new ShaderIrBuilder(); ShaderIrValue condition = builder.Constant(true); - _ = builder.Loop(builder.Constant(1u), Values(), (region, index, state) => region.Branch(condition, - yes => { yes.Discard(condition); return Values(); }, no => Values())); + _ = builder.Loop(builder.Constant(1u), Values(), ( + region, + index, + state + ) => region.Branch( + condition, + yes => + { + yes.Discard(condition); + return Values(); + }, + no => Values() + )); Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(Values()), [], [])); } @@ -98,15 +148,24 @@ public void NestedFragmentOnlyEffectsAreStillRejectedByComputeStageValidation() public async Task NestedBranchLoopAndStorageEffectsCompileThroughTheSameMetalChain() { var builder = new ShaderIrBuilder(); - ShaderSourceType bufferType = ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic("uint"), RenderStorageAccess.ReadWrite)); + ShaderSourceType bufferType = ShaderSourceType.Storage( + ShaderStorageType.Buffer(ShaderSourceType.Atomic("uint"), RenderStorageAccess.ReadWrite) + ); ShaderIrValue buffer = builder.Input("output", bufferType); ShaderIrValue gid = builder.Input("gid", ShaderSourceType.Atomic("uint3")); ShaderIrValue count = builder.Binary(ShaderIrOperation.Add, builder.Extract(gid, 0), builder.Constant(3u)); - IReadOnlyDictionary result = builder.Loop(count, Values(("a", builder.Constant(1u)), ("b", builder.Constant(2u))), - (region, index, state) => + IReadOnlyDictionary result = builder.Loop( + count, + Values(("a", builder.Constant(1u)), ("b", builder.Constant(2u))), + ( + region, + index, + state + ) => { ShaderIrValue condition = region.Binary(ShaderIrOperation.LessThan, index, region.Constant(2u)); - return region.Branch(condition, + return region.Branch( + condition, yes => { _ = yes.AtomicAddStorage(buffer, index, state["a"]); @@ -116,12 +175,24 @@ public async Task NestedBranchLoopAndStorageEffectsCompileThroughTheSameMetalCha { ShaderIrValue loaded = no.LoadStorage(buffer, index); return Values(("a", loaded), ("b", no.Binary(ShaderIrOperation.Add, state["b"], loaded))); - }); - }); + } + ); + } + ); builder.StoreStorage(buffer, builder.Constant(0u), result["a"]); builder.StoreStorage(buffer, builder.Constant(1u), result["b"]); - await Compile(new(ShaderStage.Compute, builder.Build(Values()), - [new("output", bufferType, ShaderIrInputKind.Storage), new("gid", gid.type, ShaderIrInputKind.Builtin, "global-invocation-id")], [], 8)); + await CompileAsync( + new ShaderIrStage( + ShaderStage.Compute, + builder.Build(Values()), + [ + new ShaderIrStageInput("output", bufferType, ShaderIrInputKind.Storage), + new ShaderIrStageInput("gid", gid.type, ShaderIrInputKind.Builtin, "global-invocation-id") + ], + [], + 8 + ) + ); } [MetalShaderFact] @@ -129,25 +200,52 @@ await Compile(new(ShaderStage.Compute, builder.Build(Values()), public async Task AggregateCarriedStateAndZeroIterationLoopsCompileWithoutFlatteningTheirTypes() { var builder = new ShaderIrBuilder(); - ShaderSourceType pair = ShaderSourceType.Structure("Pair", [new("a", ShaderSourceType.Atomic("float")), new("b", ShaderSourceType.Atomic("float"))]); + ShaderSourceType pair = ShaderSourceType.Structure( + "Pair", + [new ShaderSourceField("a", ShaderSourceType.Atomic("float")), new ShaderSourceField("b", ShaderSourceType.Atomic("float"))] + ); ShaderIrValue initial = builder.Construct(pair, builder.Constant(1f), builder.Constant(2f)); - IReadOnlyDictionary result = builder.Loop(builder.Constant(0u), Values(("pair", initial)), - (region, index, state) => Values(("pair", region.Construct(pair, region.Extract(state["pair"], 1), region.Extract(state["pair"], 0))))); + IReadOnlyDictionary result = builder.Loop( + builder.Constant(0u), + Values(("pair", initial)), + ( + region, + index, + state + ) => Values( + ("pair", region.Construct(pair, region.Extract(state["pair"], 1), region.Extract(state["pair"], 0))) + ) + ); ShaderIrValue a = builder.Extract(result["pair"], 0); ShaderIrValue b = builder.Extract(result["pair"], 1); ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f)); - await Compile(new(ShaderStage.Fragment, builder.Build(Values(("color", color))), [], [new("color", ShaderIrOutputKind.Color)])); + await CompileAsync( + new ShaderIrStage( + ShaderStage.Fragment, + builder.Build(Values(("color", color))), + [], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ) + ); } private static Dictionary Values(params (string name, ShaderIrValue value)[] entries) => entries.ToDictionary(static pair => pair.name, static pair => pair.value, StringComparer.Ordinal); - private static async Task Compile(ShaderIrStage stage) + private static async Task CompileAsync(ShaderIrStage stage) { - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, - new GraphicsLimits(256, 8, 8192, 16), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), Enum.GetValues(), false, false); + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); + var capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); ShaderStageToolResult result = await new ShaderCompiler(toolchain).CompileAsync(stage, toolchain.CreateTarget(capabilities)); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs index 0b1525f05..33035bbd2 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -23,9 +23,10 @@ public sealed class ShaderGraphInputDefaultTests : IDisposable public ShaderGraphInputDefaultTests() { - m_modules = new(new() + m_modules = new(new ModuleHostOptions() { - catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphInputDefaultTests).Assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphInputDefaultTests).Assembly) + }); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -34,24 +35,37 @@ public ShaderGraphInputDefaultTests() public void RequiredInputsRejectStoredDefaultsAndAcceptExplicitGraphConstants() { var graph = new GraphDocument(); - var node = new GraphNodeRecord(new("multiply"), "inno.shader.binary"); - var left = new GraphNodeRecord(new("left"), "inno.shader.constant"); - var right = new GraphNodeRecord(new("right"), "inno.shader.constant"); + var node = new GraphNodeRecord(new GraphNodeID("multiply"), "inno.shader.binary"); + var left = new GraphNodeRecord(new GraphNodeID("left"), "inno.shader.constant"); + var right = new GraphNodeRecord(new GraphNodeID("right"), "inno.shader.constant"); graph.AddNode(node); graph.AddNode(left); graph.AddNode(right); - Set(node, "type", "float"); Set(node, "operation", "multiply"); + Set(node, "type", "float"); + Set(node, "operation", "multiply"); ShaderGraphLiteral value = ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("float")); - value.scalarBits = [0x3f800000]; - Set(node, ShaderGraphDocument.inputDefaultPrefix + "left", value); - Set(node, ShaderGraphDocument.inputDefaultPrefix + "right", value); + value.scalarBits = [0x3F80_0000]; + Set(node, ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "left", value); + Set(node, ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "right", value); GraphDocument restored = GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization); var catalog = new ShaderNodeCompilerCatalog([new ShaderBinaryNodeCompiler(), new ShaderConstantNodeCompiler()]); ShaderGraphLoweringResult missing = Lower(restored, catalog); Assert.Equal(2, missing.diagnostics.Count(value => value.code == "SHADER_GRAPH_INPUT_REQUIRED")); - restored.AddEdge(new(new("left-edge"), new(left.id, new("value")), new(node.id, new("left")))); - restored.AddEdge(new(new("right-edge"), new(right.id, new("value")), new(node.id, new("right")))); + restored.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("left-edge"), + new GraphEndpoint(left.id, new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID("left")) + ) + ); + restored.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("right-edge"), + new GraphEndpoint(right.id, new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID("right")) + ) + ); ShaderGraphLoweringResult result = Lower(restored, catalog); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); Assert.Equal(3, restored.nodes.Count); @@ -63,46 +77,65 @@ public void RequiredInputsRejectStoredDefaultsAndAcceptExplicitGraphConstants() public void ConnectedInputsIgnoreButRetainObsoleteStoredDefaults() { var graph = new GraphDocument(); - var node = new GraphNodeRecord(new("multiply"), "inno.shader.binary"); - var constant = new GraphNodeRecord(new("source"), "inno.shader.constant"); - graph.AddNode(node); graph.AddNode(constant); + var node = new GraphNodeRecord(new GraphNodeID("multiply"), "inno.shader.binary"); + var constant = new GraphNodeRecord(new GraphNodeID("source"), "inno.shader.constant"); + graph.AddNode(node); + graph.AddNode(constant); Set(node, "type", "float"); - Set(node, ShaderGraphDocument.inputDefaultPrefix + "left", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("uint"))); - Set(node, ShaderGraphDocument.inputDefaultPrefix + "right", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("float"))); + Set(node, ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "left", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("uint"))); + Set(node, ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "right", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("float"))); var catalog = new ShaderNodeCompilerCatalog([new ShaderBinaryNodeCompiler(), new ShaderConstantNodeCompiler()]); Assert.Equal(2, Lower(graph, catalog).diagnostics.Count(value => value.code == "SHADER_GRAPH_INPUT_REQUIRED")); - graph.AddEdge(new(new("connect-left"), new(constant.id, new("value")), new(node.id, new("left")))); - graph.AddEdge(new(new("connect-right"), new(constant.id, new("value")), new(node.id, new("right")))); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("connect-left"), + new GraphEndpoint(constant.id, new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID("left")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("connect-right"), + new GraphEndpoint(constant.id, new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID("right")) + ) + ); Assert.True(Lower(graph, catalog).succeeded); - Assert.True(node.TryGetValue(ShaderGraphDocument.inputDefaultPrefix + "left", out _)); + Assert.True(node.TryGetValue(ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "left", out _)); } [Fact] public void AggregateDefaultsPreserveExactIntegerBitsAndRejectResourcesOrMalformedValues() { ShaderSourceType type = ShaderSourceType.Structure("Settings", [ - new("index", ShaderSourceType.Atomic("uint")), new("values", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float3"), 2))]); + new ShaderSourceField("index", ShaderSourceType.Atomic("uint")), + new ShaderSourceField("values", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float3"), 2)) + ]); ShaderGraphLiteral value = ShaderGraphLiteral.Zero(type); Assert.Equal(7, value.scalarBits.Length); value.scalarBits[0] = uint.MaxValue; var builder = new ShaderIrBuilder(); ShaderIrValue output = value.Emit(builder, type); - Assert.Equal(uint.MaxValue, builder.Build(new Dictionary { ["value"] = output }).instructions[0].constantBits); + Assert.Equal( + uint.MaxValue, + builder.Build(new Dictionary { ["value"] = output }).instructions[0].constantBits + ); Assert.Throws(() => ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("sampled-texture2d"))); var boolean = new ShaderGraphLiteral { type = new() { id = "bool" }, scalarBits = [2] }; - Assert.Throws(() => boolean.Emit(new(), ShaderSourceType.Atomic("bool"))); + Assert.Throws(() => boolean.Emit(new ShaderIrBuilder(), ShaderSourceType.Atomic("bool"))); value.scalarBits = [0]; - Assert.Throws(() => value.Emit(new(), type)); + Assert.Throws(() => value.Emit(new ShaderIrBuilder(), type)); } [Fact] public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() { - Guid sourceId = Guid.NewGuid(); + Guid sourceID = Guid.NewGuid(); GraphDocument child = ShaderGraphDocument.Create( new ShaderDefinition("Optional Node", [], [], []), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); ShaderGraphNodes.WriteSettings( child, new ShaderGraphNodeSettings @@ -111,9 +144,10 @@ public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() kind = ShaderGraphNodeKind.Function }, m_serialization, - SerializationContext.empty); - var boundaryInput = new GraphNodeRecord(new("node-inputs"), ShaderGraphNodes.inputDefinitionId); - var boundaryOutput = new GraphNodeRecord(new("node-outputs"), ShaderGraphNodes.outputDefinitionId); + SerializationContext.empty + ); + var boundaryInput = new GraphNodeRecord(new GraphNodeID("node-inputs"), ShaderGraphNodes.C_INPUT_DEFINITION_ID); + var boundaryOutput = new GraphNodeRecord(new GraphNodeID("node-outputs"), ShaderGraphNodes.C_OUTPUT_DEFINITION_ID); child.AddNode(boundaryInput); child.AddNode(boundaryOutput); var optional = new ShaderGraphNodePortDefinition @@ -122,98 +156,129 @@ public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() type = new() { id = "float3" }, required = false }; - Set(boundaryInput, ShaderGraphDocument.settingsKey, new ShaderGraphNodeInputSettings + Set(boundaryInput, ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeInputSettings { ports = [optional] }); - Set(boundaryOutput, ShaderGraphDocument.settingsKey, new ShaderGraphNodeOutputSettings + Set(boundaryOutput, ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeOutputSettings { - ports = [new() { id = "value", type = new() { id = "float3" } }] + ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float3" } }] }); - child.AddEdge(new( - new("return"), - new(boundaryInput.id, new("offset")), - new(boundaryOutput.id, new("value")))); + child.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("return"), + new GraphEndpoint(boundaryInput.id, new GraphPortID("offset")), + new GraphEndpoint(boundaryOutput.id, new GraphPortID("value")) + ) + ); GraphDocument parent = ShaderGraphDocument.Create( new ShaderDefinition("Parent", [], [], []), m_serialization, - SerializationContext.empty); - var call = new GraphNodeRecord(new("call"), ShaderGraphNodes.callDefinitionId); + SerializationContext.empty + ); + var call = new GraphNodeRecord(new GraphNodeID("call"), ShaderGraphNodes.C_CALL_DEFINITION_ID); parent.AddNode(call); - Set(call, "sourceId", sourceId); + Set(call, "sourceId", sourceID); Set(call, "sourcePath", "Optional.ishader"); - Set(call, ShaderGraphNodes.interfaceKey, ShaderGraphNodes.ReadInterface( - child, - m_serialization, - SerializationContext.empty)); + Set( + call, + ShaderGraphNodes.C_INTERFACE_KEY, + ShaderGraphNodes.ReadInterface(child, m_serialization, SerializationContext.empty) + ); GraphDocument expanded = ShaderGraphNodes.Expand( parent, - (id, _) => id == sourceId ? child : throw new InvalidOperationException(), + ( + id, + _ + ) => id == sourceID ? child : throw new InvalidOperationException(), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); GraphNodeRecord value = Assert.Single(expanded.nodes); - Assert.Equal("inno.shader.reroute", value.definitionId); - Assert.False(value.TryGetValue(ShaderGraphDocument.inputDefaultPrefix + "input", out _)); - Assert.False(value.TryGetValue(ShaderGraphDocument.inputDefaultPrefix + "value", out _)); + Assert.Equal("inno.shader.reroute", value.definitionID); + Assert.False(value.TryGetValue(ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "input", out _)); + Assert.False(value.TryGetValue(ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "value", out _)); } [Fact] public void OptionalInputsCompileFromTypedZeroWithoutPersistedOverrides() { var graph = new GraphDocument(); - var reroute = new GraphNodeRecord(new("optional"), "inno.shader.reroute"); + var reroute = new GraphNodeRecord(new GraphNodeID("optional"), "inno.shader.reroute"); graph.AddNode(reroute); Set(reroute, "valueType", new ShaderGraphType { id = "float3" }); var catalog = new ShaderNodeCompilerCatalog([new ShaderRerouteNodeCompiler()]); ShaderGraphLoweringResult result = catalog.Lower( - new( + new ShaderGraphLoweringRequest( graph, new Dictionary { - ["value"] = new(reroute.id, new("value")) + ["value"] = new(reroute.id, new GraphPortID("value")) }, - "test.optional-zero"), + "test.optional-zero" + ), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); Assert.Empty(result.diagnostics); - Assert.False(reroute.TryGetValue(ShaderGraphDocument.inputDefaultPrefix + "input", out _)); + Assert.False(reroute.TryGetValue(ShaderGraphDocument.C_INPUT_DEFAULT_PREFIX + "input", out _)); } [Fact] public void OptionalInputsRejectTypesThatCannotHaveAZeroValue() { var graph = new GraphDocument(); - var reroute = new GraphNodeRecord(new("optional-resource"), "inno.shader.reroute"); + var reroute = new GraphNodeRecord(new GraphNodeID("optional-resource"), "inno.shader.reroute"); graph.AddNode(reroute); Set(reroute, "valueType", new ShaderGraphType { id = "sampled-texture2d" }); var catalog = new ShaderNodeCompilerCatalog([new ShaderRerouteNodeCompiler()]); ShaderGraphLoweringResult result = catalog.Lower( - new( + new ShaderGraphLoweringRequest( graph, new Dictionary { - ["value"] = new(reroute.id, new("value")) + ["value"] = new(reroute.id, new GraphPortID("value")) }, - "test.optional-resource"), + "test.optional-resource" + ), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); ShaderGraphDiagnostic diagnostic = Assert.Single(result.diagnostics); Assert.Equal("SHADER_GRAPH_OPTIONAL_TYPE", diagnostic.code); } - private ShaderGraphLoweringResult Lower(GraphDocument graph, ShaderNodeCompilerCatalog catalog) - => catalog.Lower(new(graph, new Dictionary { ["value"] = new(new("multiply"), new("value")) }, "test.defaults"), m_serialization, SerializationContext.empty); + public void Dispose() + { + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + if (Directory.Exists(m_root)) Directory.Delete(m_root, true); + } - private void Set(GraphNodeRecord node, string key, T value) - => node.SetValue(key, ShaderGraphDocument.Encode(value, m_serialization, SerializationContext.empty)); + private ShaderGraphLoweringResult Lower( + GraphDocument graph, + ShaderNodeCompilerCatalog catalog + ) => catalog.Lower( + new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["value"] = new(new GraphNodeID("multiply"), new GraphPortID("value")) }, + "test.defaults" + ), + m_serialization, + SerializationContext.empty + ); - public void Dispose() - { m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) Directory.Delete(m_root, true); } + private void Set( + GraphNodeRecord node, + string key, + T value + ) => node.SetValue(key, ShaderGraphDocument.Encode(value, m_serialization, SerializationContext.empty)); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs index f51f27ca5..2f75bf6a1 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading; +using Xunit; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -21,7 +21,8 @@ public void TypedEdgesRejectMismatchesAndCyclesBeforeInvokingAnyCompiler() Connect(graph, b, "value", a, "left"); Connect(graph, value, "value", a, "right"); Connect(graph, value, "value", b, "right"); - ShaderGraphLoweringRequest Request() => new(graph, new Dictionary { ["result"] = Endpoint(a, "value") }, "metal"); + ShaderGraphLoweringRequest Request() + => new(graph, new Dictionary { ["result"] = Endpoint(a, "value") }, "metal"); ShaderGraphLoweringResult cycle = Catalog().Lower(Request(), m_serialization, SerializationContext.empty); Assert.Contains(cycle.diagnostics, diagnostic => diagnostic.code == "SHADER_GRAPH_CYCLE"); Set(value, "type", "int"); @@ -36,14 +37,21 @@ public void IndependentUnusedSourceEffectsKeepStableDocumentOrder() var graph = new GraphDocument(); GraphNodeRecord first = Add(graph, "first", "inno.shader.source"); GraphNodeRecord second = Add(graph, "second", "inno.shader.source"); - var modules = new Dictionary + var modules = new Dictionary { [first.id] = Source("void Shade() {}", "first.ishadersource"), [second.id] = Source("void Shade() {}", "second.ishadersource") }; - ShaderGraphLoweringResult result = Catalog().Lower(new(graph, new Dictionary(), "metal", modules), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult result = Catalog().Lower( + new ShaderGraphLoweringRequest(graph, new Dictionary(), "metal", modules), + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded, Errors(result)); - Assert.Equal(["first.ishadersource", "second.ishadersource"], result.block!.instructions.Select(static instruction => instruction.source!.sourcePath)); + Assert.Equal( + ["first.ishadersource", "second.ishadersource"], + result.block!.instructions.Select(static instruction => instruction.source!.sourcePath) + ); } [Fact] @@ -53,23 +61,37 @@ public void ExpandedMembersAndAggregateConnectionsCannotSilentlyOverrideEachOthe GraphNodeRecord input = Add(graph, "input", "inno.shader.stage-input"); GraphNodeRecord scalar = Add(graph, "scalar", "inno.shader.constant"); GraphNodeRecord source = Add(graph, "source", "inno.shader.source"); - ShaderSourceModuleAnalysis module = Source("struct Data { float x; float y; }; float Shade(Data value) { return value.x + value.y; }"); + ShaderSourceModuleAnalysis module = Source( + "struct Data { float x; float y; }; float Shade(Data value) { return value.x + value.y; }" + ); Connect(graph, input, "value", source, "input.value"); Connect(graph, scalar, "value", source, "input.value.x"); - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["value"] = Endpoint(source, "return") }, "metal", - new Dictionary { [source.id] = module }, - new Dictionary { [input.id] = new("data", module.function!.parameters[0].type, ShaderIrInputKind.Uniform) }); + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["value"] = Endpoint(source, "return") }, + "metal", + new Dictionary { [source.id] = module }, + new Dictionary + { + [input.id] = new("data", module.function!.parameters[0].type, ShaderIrInputKind.Uniform) + } + ); ShaderGraphLoweringResult result = Catalog().Lower(request, m_serialization, SerializationContext.empty); Assert.False(result.succeeded); - Assert.Contains(result.diagnostics, diagnostic => diagnostic.message.Contains("both its aggregate and a member", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + diagnostic => diagnostic.message.Contains("both its aggregate and a member", StringComparison.Ordinal) + ); } [Fact] public void DuplicateProvidersAndCanceledRequestsAreRejectedWithoutPartialResults() { Assert.Throws(() => Catalog(new DoubleCompiler(), new DoubleCompiler())); - var request = new ShaderGraphLoweringRequest(new(), new Dictionary(), "metal"); - Assert.ThrowsAny(() => Catalog().Lower(request, m_serialization, SerializationContext.empty, new CancellationToken(true))); + var request = new ShaderGraphLoweringRequest(new GraphDocument(), new Dictionary(), "metal"); + Assert.ThrowsAny( + () => Catalog().Lower(request, m_serialization, SerializationContext.empty, new CancellationToken(true)) + ); } [Fact] @@ -79,29 +101,22 @@ public void RegistryDiscoversExtensionsAndRollsBackDuplicateCandidatesWithoutLea NodeRegistryProbe.conflict = false; using (var registry = new ShaderNodeCompilerRegistry(m_types)) { - Assert.Contains("tests.registry.node", registry.definitionIds); - Assert.Contains("inno.shader.source", registry.definitionIds); + Assert.Contains("tests.registry.node", registry.definitionIDs); + Assert.Contains("inno.shader.source", registry.definitionIDs); m_modules.Rebuild(); Assert.Equal(1, NodeRegistryProbe.created - NodeRegistryProbe.disposed); NodeRegistryProbe.conflict = true; - try { Assert.ThrowsAny(m_modules.Rebuild); } - finally { NodeRegistryProbe.conflict = false; } - Assert.Contains("tests.registry.node", registry.definitionIds); + try + { + Assert.ThrowsAny(m_modules.Rebuild); + } + finally + { + NodeRegistryProbe.conflict = false; + } + Assert.Contains("tests.registry.node", registry.definitionIDs); Assert.Equal(1, NodeRegistryProbe.created - NodeRegistryProbe.disposed); } Assert.Equal(NodeRegistryProbe.created, NodeRegistryProbe.disposed); } } - -internal sealed class NodeRegistryProbe : IShaderNodeCompiler, IDisposable -{ - internal static int created; - internal static int disposed; - internal static bool conflict; - private readonly string m_id; - public NodeRegistryProbe() { created++; m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; } - public string definitionId => m_id; - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); - public void Dispose() => disposed++; -} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs index 62b69397b..7caac11cc 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs @@ -1,22 +1,22 @@ -using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -31,7 +31,9 @@ public sealed partial class ShaderGraphLoweringTests : IDisposable public ShaderGraphLoweringTests() { - m_modules = new(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphLoweringTests).Assembly)}); + m_modules = new( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphLoweringTests).Assembly)} + ); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -40,11 +42,20 @@ public ShaderGraphLoweringTests() [SupportedOSPlatform("macos")] public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOneNativeCompilation() { - GraphDocument graph = Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color); + GraphDocument graph = Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ); Set(constant, "value", 0.25f); ShaderSourceModuleAnalysis module = Source("float Shade(float value) { return value * 0.75; }"); - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); Set(constant, "value", 99f); extension.position = new(900, 1200); ShaderGraphLoweringResult lowered = Catalog(new DoubleCompiler()).Lower(request, m_serialization, SerializationContext.empty); @@ -52,11 +63,24 @@ public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOne Assert.Contains(lowered.block!.instructions, instruction => instruction.operation == ShaderIrOperation.SourceCall); Assert.Contains(lowered.block.instructions, instruction => instruction.operation == ShaderIrOperation.Multiply); Assert.Equal(BitConverter.SingleToUInt32Bits(0.25f), lowered.block.instructions[0].constantBits); - var stage = new ShaderIrStage(ShaderStage.Fragment, lowered.block, [], [new("color", ShaderIrOutputKind.Color)]); - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); - var caps = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), false, false); + var stage = new ShaderIrStage( + ShaderStage.Fragment, + lowered.block, + [], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ); + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); + var caps = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); ShaderStageToolResult compiled = await compiler.CompileAsync(stage, compiler.CreateTarget(caps)); Assert.True(compiled.succeeded, string.Join("\n", compiled.diagnostics.Select(static diagnostic => diagnostic.message))); } @@ -64,15 +88,29 @@ public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOne [Fact] public void LayoutOnlyEditsKeepTheSameTypedStageSemanticHash() { - GraphDocument graph = Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color); + GraphDocument graph = Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ); ShaderSourceModuleAnalysis module = Source("float Shade(float value) { return value; }"); string Hash() { - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); ShaderGraphLoweringResult result = Catalog(new DoubleCompiler()).Lower(request, m_serialization, SerializationContext.empty); Assert.True(result.succeeded, Errors(result)); - return new ShaderIrStage(ShaderStage.Fragment, result.block!, [], [new("color", ShaderIrOutputKind.Color)]).contentHash; + return new ShaderIrStage( + ShaderStage.Fragment, + result.block!, + [], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ).contentHash; } string first = Hash(); constant.position = new(912, -8); @@ -91,22 +129,53 @@ public void MissingCompilerAndRenamedSourcePortPreserveEveryOriginalConnection() { GraphDocument graph = Graph(out _, out _, out GraphNodeRecord source, out GraphNodeRecord color); int edgeCount = graph.edges.Count; - ShaderGraphLoweringRequest Request(ShaderSourceModuleAnalysis module) => new(graph, - new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); - ShaderGraphLoweringResult missing = Catalog().Lower(Request(Source("float Shade(float value) { return value; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringRequest Request(ShaderSourceModuleAnalysis module) + => new( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); + ShaderGraphLoweringResult missing = Catalog().Lower( + Request(Source("float Shade(float value) { return value; }")), + m_serialization, + SerializationContext.empty + ); Assert.False(missing.succeeded); Assert.Contains(missing.diagnostics, diagnostic => diagnostic.code == "SHADER_NODE_COMPILER_MISSING"); - ShaderGraphLoweringResult renamed = Catalog(new DoubleCompiler()).Lower(Request(Source("float Shade(float renamed) { return renamed; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult renamed = Catalog(new DoubleCompiler()).Lower( + Request(Source("float Shade(float renamed) { return renamed; }")), + m_serialization, + SerializationContext.empty + ); Assert.False(renamed.succeeded); - Assert.Contains(renamed.diagnostics, diagnostic => diagnostic.code == "SHADER_GRAPH_PORT_MISSING" && diagnostic.portId == "input.value"); + Assert.Contains( + renamed.diagnostics, + diagnostic => diagnostic.code == "SHADER_GRAPH_PORT_MISSING" && diagnostic.portID == "input.value" + ); Assert.Equal(edgeCount, graph.edges.Count); - ShaderGraphLoweringResult restored = Catalog(new DoubleCompiler()).Lower(Request(Source("float Shade(float value) { return value; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult restored = Catalog(new DoubleCompiler()).Lower( + Request(Source("float Shade(float value) { return value; }")), + m_serialization, + SerializationContext.empty + ); Assert.True(restored.succeeded, Errors(restored)); } - private GraphDocument Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color) + public void Dispose() { + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + if (Directory.Exists(m_root)) Directory.Delete(m_root, true); + } + + private GraphDocument Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ) { var graph = new GraphDocument(); constant = Add(graph, "constant", "inno.shader.constant"); extension = Add(graph, "extension", "tests.double"); @@ -114,53 +183,96 @@ private GraphDocument Graph(out GraphNodeRecord constant, out GraphNodeRecord ex color = Add(graph, "color", "inno.shader.construct"); Connect(graph, constant, "value", extension, "input"); Connect(graph, extension, "value", source, "input.value"); - for (int index = 0; index < 4; index++) Connect(graph, source, "return", color, "component." + index); + for (int index = 0; index < 4; index++) + { + Connect(graph, source, "return", color, "component." + index); + } return graph; } - private static ShaderNodeCompilerCatalog Catalog(params IShaderNodeCompiler[] extra) - => new(new IShaderNodeCompiler[] { new ShaderConstantNodeCompiler(), new ShaderBinaryNodeCompiler(), new ShaderConstructNodeCompiler(), - new ShaderStageInputNodeCompiler(), new ShaderSelectNodeCompiler(), new ShaderSourceNodeCompiler() }.Concat(extra)); + private void Set( + GraphNodeRecord node, + string property, + T value + ) => node.SetValue( + property, + new GraphSerializedValue(m_serialization.Encode(writer => writer.Write("value", value), SerializationContext.empty)) + ); - private void Set(GraphNodeRecord node, string property, T value) - => node.SetValue(property, new(m_serialization.Encode(writer => writer.Write("value", value), SerializationContext.empty))); + private static ShaderNodeCompilerCatalog Catalog(params IShaderNodeCompiler[] extra) + => new( + new IShaderNodeCompiler[] + { + new ShaderConstantNodeCompiler(), + new ShaderBinaryNodeCompiler(), + new ShaderConstructNodeCompiler(), + new ShaderStageInputNodeCompiler(), + new ShaderSelectNodeCompiler(), + new ShaderSourceNodeCompiler() + }.Concat(extra) + ); - private static GraphNodeRecord Add(GraphDocument graph, string id, string definition) - { - var node = new GraphNodeRecord(new(id), definition); + private static GraphNodeRecord Add( + GraphDocument graph, + string id, + string definition + ) { + var node = new GraphNodeRecord(new GraphNodeID(id), definition); graph.AddNode(node); return node; } - private static GraphEndpoint Endpoint(GraphNodeRecord node, string port) => new(node.id, new(port)); - private static void Connect(GraphDocument graph, GraphNodeRecord source, string output, GraphNodeRecord target, string input) - => graph.AddEdge(new(new("edge." + graph.edges.Count), Endpoint(source, output), Endpoint(target, input))); + private static GraphEndpoint Endpoint( + GraphNodeRecord node, + string port + ) => new(node.id, new GraphPortID(port)); - private static ShaderSourceModuleAnalysis Source(string text, string path = "module.ishadersource") - => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( - [new("metal", "inno.shader-language.bgfx-sc", new(new(path, text), "Shade", new NoIncludes()))]); + private static void Connect( + GraphDocument graph, + GraphNodeRecord source, + string output, + GraphNodeRecord target, + string input + ) => graph.AddEdge( + new GraphEdgeRecord(new GraphEdgeID("edge." + graph.edges.Count), Endpoint(source, output), Endpoint(target, input)) + ); - private static string Errors(ShaderGraphLoweringResult result) => string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)); + private static ShaderSourceModuleAnalysis Source( + string text, + string path = "module.ishadersource" + ) => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( + [new ShaderSourceImplementationRequest( + "metal", + "inno.shader-language.bgfx-sc", + new ShaderSourceRequest(new ShaderSourceFile(path, text), "Shade", new NoIncludes()) + )] + ); - public void Dispose() - { - m_serialization.Dispose(); - m_types.Dispose(); - m_modules.Dispose(); - if (Directory.Exists(m_root)) Directory.Delete(m_root, true); - } + private static string Errors(ShaderGraphLoweringResult result) + => string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)); private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } private sealed class DoubleCompiler : IShaderNodeCompiler { - public string definitionId => "tests.double"; + public string definitionID => "tests.double"; + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("input", ShaderSourceType.Atomic("float"), GraphPortDirection.Input), new("value", ShaderSourceType.Atomic("float"), GraphPortDirection.Output)]; + => [ + new ShaderNodePort("input", ShaderSourceType.Atomic("float"), GraphPortDirection.Input), + new ShaderNodePort("value", ShaderSourceType.Atomic("float"), GraphPortDirection.Output) + ]; + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Binary(ShaderIrOperation.Multiply, context.Input("input"), context.builder.Constant(2f)) }; + => new Dictionary + { + ["value"] = context.builder.Binary(ShaderIrOperation.Multiply, context.Input("input"), context.builder.Constant(2f)) + }; } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs similarity index 65% rename from tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs rename to tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs index 0df3dcbdd..579d1893d 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs @@ -1,9 +1,8 @@ using System; using System.Linq; +using Xunit; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -34,7 +33,9 @@ public void RemovingOnePassKeepsSharedNodesAndRemovingLastPassReleasesItsParamet Assert.True(Lower(changed).succeeded); Assert.Equal(5, ShaderGraphPrograms.Read(original, m_serialization, SerializationContext.empty).Length); foreach (string pass in new[] { "Premultiplied", "Additive", "Multiply", "Opaque" }) + { changed = ShaderGraphPrograms.RemovePass(changed, pass, m_serialization, SerializationContext.empty); + } Assert.Empty(changed.nodes); Assert.Empty(changed.edges); Assert.Empty(ShaderGraphDocument.ReadDefinition(changed, m_serialization, SerializationContext.empty).properties); @@ -45,9 +46,14 @@ public void RemovingOnePassKeepsSharedNodesAndRemovingLastPassReleasesItsParamet public void RemovingAnOutputRemovesEveryAffectedPassAndItsNowUnreferencedStagePair() { GraphDocument original = SharedGraph(); - GraphDocument changed = ShaderGraphBindings.RemoveNodes(original, [new("fragment")], m_serialization, SerializationContext.empty); - Assert.Null(changed.FindNode(new("vertex"))); - Assert.Null(changed.FindNode(new("fragment"))); + GraphDocument changed = ShaderGraphBindings.RemoveNodes( + original, + [new GraphNodeID("fragment")], + m_serialization, + SerializationContext.empty + ); + Assert.Null(changed.FindNode(new GraphNodeID("vertex"))); + Assert.Null(changed.FindNode(new GraphNodeID("fragment"))); Assert.Empty(ShaderGraphPrograms.Read(changed, m_serialization, SerializationContext.empty)); Assert.Empty(ShaderGraphDocument.ReadDefinition(changed, m_serialization, SerializationContext.empty).passes); Assert.Empty(changed.nodes); @@ -58,19 +64,44 @@ public void PastePreservesSharedProgramsAndTechniqueRolesWithNewIdentities() { GraphDocument graph = SharedGraph(); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); - definition.techniques = [new(new("surface"), new("tests.surface"), definition.passes.Select(pass => new ShaderTechniquePass(new(pass.name.ToLowerInvariant()), pass.name)))]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + definition.techniques = [new ShaderTechniqueDefinition( + new ShaderTechniqueID("surface"), + new ShaderContractID("tests.surface"), + definition.passes.Select(pass => new ShaderTechniquePass(new ShaderPassRoleID(pass.name.ToLowerInvariant()), pass.name)) + )]; + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); byte[] original = GraphDocumentCodec.Encode(graph, m_serialization); - GraphDocument fragment = ShaderGraphClipboard.Copy(graph, [new("vertex"), new("fragment")], m_serialization, SerializationContext.empty); - ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste(graph, fragment, true, null, m_serialization, SerializationContext.empty); + GraphDocument fragment = ShaderGraphClipboard.Copy( + graph, + [new GraphNodeID("vertex"), new GraphNodeID("fragment")], + m_serialization, + SerializationContext.empty + ); + ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste( + graph, + fragment, + true, + null, + m_serialization, + SerializationContext.empty + ); Assert.Equal(original, GraphDocumentCodec.Encode(graph, m_serialization)); Assert.Equal(graph.nodes.Count * 2, pasted.document.nodes.Count); ShaderDefinition result = ShaderGraphDocument.ReadDefinition(pasted.document, m_serialization, SerializationContext.empty); Assert.Equal(2, result.techniques.Length); Assert.NotEqual(result.techniques[0].id, result.techniques[1].id); Assert.All(result.techniques[1].passes, pass => Assert.EndsWith(" 2", pass.passName)); - Assert.Equal(2, ShaderGraphPrograms.Read(pasted.document, m_serialization, SerializationContext.empty) - .Where(program => program.pass.EndsWith(" 2", StringComparison.Ordinal)).SelectMany(program => program.stages).Distinct().Count()); + Assert.Equal( + 2, + ShaderGraphPrograms.Read(pasted.document, m_serialization, SerializationContext.empty) + .Where(program => program.pass.EndsWith(" 2", StringComparison.Ordinal)) + .SelectMany(program => program.stages) + .Distinct() + .Count() + ); Assert.True(Lower(pasted.document).succeeded); } @@ -78,11 +109,18 @@ public void PastePreservesSharedProgramsAndTechniqueRolesWithNewIdentities() public void CopyAndPasteUnknownNodesPreserveTheirUnresolvedData() { var graph = new GraphDocument(); - var node = new GraphNodeRecord(new("unknown"), "uninstalled.node"); - node.SetValue("payload", new([1, 3, 5])); + var node = new GraphNodeRecord(new GraphNodeID("unknown"), "uninstalled.node"); + node.SetValue("payload", new GraphSerializedValue([1, 3, 5])); graph.AddNode(node); GraphDocument fragment = ShaderGraphClipboard.Copy(graph, [node.id], m_serialization, SerializationContext.empty); - ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste(graph, fragment, true, null, m_serialization, SerializationContext.empty); + ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste( + graph, + fragment, + true, + null, + m_serialization, + SerializationContext.empty + ); Assert.Equal(2, pasted.document.nodes.Count); Assert.NotEqual(node.id, Assert.Single(pasted.insertedNodes)); Assert.Equal(GraphDocumentCodec.Encode(fragment, m_serialization), GraphDocumentCodec.Encode(graph, m_serialization)); @@ -98,9 +136,20 @@ private GraphDocument SharedGraph() pass.name = name; return pass; }).ToArray(); - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); foreach (ShaderPassDefinition pass in definition.passes) - graph = ShaderGraphPrograms.Bind(graph, pass.name, [new("vertex"), new("fragment")], m_serialization, SerializationContext.empty); + { + graph = ShaderGraphPrograms.Bind( + graph, + pass.name, + [new GraphNodeID("vertex"), new GraphNodeID("fragment")], + m_serialization, + SerializationContext.empty + ); + } return graph; } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs new file mode 100644 index 000000000..887ffd352 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Versioning; +using System.Threading.Tasks; +using Xunit; +using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Core.Graphs; +using Inno.Core.Serialization; +using Inno.Integration.MacOSArm64.Bgfx; +using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; + +namespace Inno.Rendering.Shaders.Tests; + +public sealed partial class ShaderGraphProgramTests +{ + [Fact] + public void StorageGraphKeepsExplicitEffectsEvenWithoutAValueOutput() + { + ShaderGraphProgramResult lowered = Lower(StorageGraph()); + Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); + ShaderIrStage stage = Assert.Single(Assert.Single(lowered.passes).stages); + Assert.Equal( + new[] { ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd }, + stage.body.instructions.Where(value => value.hasSideEffects).Select(value => value.operation) + ); + } + + [MetalShaderFact] + [SupportedOSPlatform("macos")] + public async Task StorageGraphCompilesThroughTheSameMetalToolchainAsSourceNodes() + { + ShaderGraphProgramResult lowered = Lower(StorageGraph()); + Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); + RenderTextureFormat[] formats = Enum.GetValues(); + var caps = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, + new GraphicsLimits(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false, + formats, + formats, + formats + ); + ShaderStageToolResult result = await compiler.CompileAsync(lowered.passes[0].stages[0], compiler.CreateTarget(caps)); + Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); + } + + [Fact] + public void RerouteRetainsAggregateAndStoragePortContracts() + { + ShaderSourceType aggregate = ShaderSourceType.Structure( + "Payload", + [new ShaderSourceField("points", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float2"), 3))] + ); + foreach (ShaderSourceType type in new[] + { + aggregate, + ShaderSourceType.Storage(ShaderStorageType.Buffer(aggregate, RenderStorageAccess.ReadWrite)) + }) { + var node = new GraphNodeRecord(new GraphNodeID("route"), "inno.shader.reroute"); + node.SetValue( + "valueType", + ShaderGraphDocument.Encode(ShaderGraphType.Capture(type), m_serialization, SerializationContext.empty) + ); + IReadOnlyList ports = m_nodes.DescribePorts(node, m_serialization, SerializationContext.empty); + Assert.Equal(2, ports.Count); + Assert.All(ports, port => Assert.True(type.IsEquivalentTo(port.type))); + } + } + + private GraphDocument StorageGraph() + { + GraphDocument graph = ShaderGraphDocument.Create( + new ShaderDefinition("Compute", [], [], [new ShaderPassDefinition("Main", ShaderProgramKind.Compute)]), + m_serialization, + SerializationContext.empty + ); + GraphNodeRecord stage = Node("compute", ShaderGraphDocument.C_OUTPUT_DEFINITION_ID); + Set(stage, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Compute }); + var resourceType = new ShaderGraphType + { + isStorage = true, + access = RenderStorageAccess.ReadWrite, + storageElement = new() { id = "uint" } + }; + GraphNodeRecord resource = Node("resource", "inno.shader.stage-input"); + var settings = new ShaderGraphInputSettings + { + id = "buffer", + kind = ShaderIrInputKind.Storage, + type = resourceType + }; + Set(resource, "settings", settings); + GraphNodeRecord coordinate = Node("coordinate", "inno.shader.constant"); + Set(coordinate, "type", "uint"); + Set(coordinate, "value", 0u); + GraphNodeRecord value = Node("constant", "inno.shader.constant"); + Set(value, "type", "uint"); + Set(value, "value", 7u); + GraphNodeRecord store = Node("z-store", "inno.shader.storage-store"); + GraphNodeRecord load = Node("m-load", "inno.shader.storage-load"); + GraphNodeRecord atomic = Node("a-atomic", "inno.shader.storage-atomic-add"); + foreach (GraphNodeRecord effect in new[] { store, load, atomic }) + { + Set(effect, "resource", resourceType); + Connect(resource, "value", effect, "resource"); + Connect(coordinate, "value", effect, "coordinate"); + } + Connect(value, "value", store, "value"); + Connect(value, "value", atomic, "value"); + Connect(store, "then", load, "after"); + Connect(load, "then", atomic, "after"); + graph = ShaderGraphPrograms.Bind(graph, "Main", [stage.id], m_serialization, SerializationContext.empty); + return ShaderGraphBindings.ChangeInput(graph, resource.id, settings, m_serialization, SerializationContext.empty); + + GraphNodeRecord Node( + string id, + string type + ) { + var node = new GraphNodeRecord(new GraphNodeID(id), type); + if (id != "compute") Set(node, "stage", "compute"); + graph.AddNode(node); + return node; + } + void Set( + GraphNodeRecord node, + string key, + T data + ) => node.SetValue(key, ShaderGraphDocument.Encode(data, m_serialization, SerializationContext.empty)); + void Connect( + GraphNodeRecord output, + string outputPort, + GraphNodeRecord input, + string inputPort + ) => graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(output.id, new GraphPortID(outputPort)), + new GraphEndpoint(input.id, new GraphPortID(inputPort)) + ) + ); + } +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs index a5c0ff38b..69f90e2a7 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs @@ -1,16 +1,16 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -25,7 +25,9 @@ public sealed partial class ShaderGraphProgramTests : IDisposable public ShaderGraphProgramTests() { - m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphProgramTests).Assembly)}); + m_modules = new( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphProgramTests).Assembly)} + ); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); m_nodes = new(m_types); @@ -40,7 +42,10 @@ public void NativeGraphRoundTripPreservesTheOnlyRasterCreationTemplate() Assert.Equal(bytes, GraphDocumentCodec.Encode(restored, m_serialization)); ShaderGraphProgramResult result = Lower(restored); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); - Assert.Equal(new[] { ShaderStage.Vertex, ShaderStage.Fragment }, Assert.Single(result.passes).stages.Select(static value => value.stage)); + Assert.Equal( + new[] { ShaderStage.Vertex, ShaderStage.Fragment }, + Assert.Single(result.passes).stages.Select(static value => value.stage) + ); } [Fact] @@ -66,16 +71,25 @@ public void NewCompilerRetainsPropertyPassKeywordTechniqueAndStageValidation() property.stages = ShaderStage.None; definition.properties = [property, property]; definition.passes = [definition.passes[0], definition.passes[0]]; - definition.keywords = [new("quality", ["low", "low"])]; - definition.techniques = [new(new("surface"), new("arbitrary.render-model"), [new(new("forward"), "absent")])]; - string[] codes = ShaderDefinitionValidator.Validate(definition).Where(static value => value.severity == DiagnosticSeverity.Error) - .Select(static value => value.code).ToArray(); + definition.keywords = [new ShaderKeywordDefinition("quality", ["low", "low"])]; + definition.techniques = [new ShaderTechniqueDefinition( + new ShaderTechniqueID("surface"), + new ShaderContractID("arbitrary.render-model"), + [new ShaderTechniquePass(new ShaderPassRoleID("forward"), "absent")] + )]; + string[] codes = ShaderDefinitionValidator.Validate(definition) + .Where(static value => value.severity == DiagnosticSeverity.Error) + .Select(static value => value.code) + .ToArray(); Assert.Contains("SHADER_DUPLICATE_PROPERTY", codes); Assert.Contains("SHADER_DUPLICATE_PASS", codes); Assert.Contains("SHADER_PROPERTY_STAGES_INVALID", codes); Assert.Contains("SHADER_DUPLICATE_KEYWORD_OPTION", codes); Assert.Contains("SHADER_UNKNOWN_TECHNIQUE_PASS", codes); - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); Assert.False(Lower(graph).succeeded); } @@ -87,21 +101,35 @@ public void CapabilityValidationReportsUnsupportedPassWithoutMutatingTheDefiniti pass.requiredFeatures = GraphicsCapability.Compute; definition.passes = [pass]; RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Noop, GraphicsCapability.None, new(64, 1, 4096, 0), - formats, formats, formats, formats, false, false); - Assert.Contains(ShaderDefinitionValidator.Validate(definition, capabilities), static value => - value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning); + var capabilities = new GraphicsCapabilities( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(64, 1, 4096, 0), + formats, + formats, + formats, + formats, + false, + false + ); + Assert.Contains(ShaderDefinitionValidator.Validate(definition, capabilities), static value => ( + value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning + )); Assert.Equal(GraphicsCapability.Compute, definition.passes[0].requiredFeatures); } - private GraphDocument Template() => ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - [Fact] public void RenamingAnExposedInputAtomicallyChangesItsParameterAndPreservesTheDefault() { GraphDocument graph = Template(); - GraphNodeRecord color = graph.FindNode(new("color"))!; - ShaderGraphInputSettings input = ShaderGraphDocument.Read(color, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); + GraphNodeRecord color = graph.FindNode(new GraphNodeID("color"))!; + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + color, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); input.id = "tint"; GraphDocument changed = ShaderGraphBindings.ChangeInput(graph, color.id, input, m_serialization, SerializationContext.empty); ShaderDefinition original = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); @@ -116,42 +144,66 @@ public void RenamingAnExposedInputAtomicallyChangesItsParameterAndPreservesTheDe public void PartiallyTypedInputRemainsSerializableInsteadOfDiscardingItsNodeOrEdges() { GraphDocument graph = Template(); - ShaderGraphInputSettings input = ShaderGraphDocument.Read(graph.FindNode(new("color"))!, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); - input.id = ""; - GraphDocument changed = ShaderGraphBindings.ChangeInput(graph, new("color"), input, m_serialization, SerializationContext.empty); + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + graph.FindNode(new GraphNodeID("color"))!, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); + input.id = string.Empty; + GraphDocument changed = ShaderGraphBindings.ChangeInput( + graph, + new GraphNodeID("color"), + input, + m_serialization, + SerializationContext.empty + ); Assert.Equal(graph.nodes.Count, changed.nodes.Count); Assert.Equal(graph.edges.Count, changed.edges.Count); Assert.False(Lower(changed).succeeded); Assert.NotEmpty(GraphDocumentCodec.Encode(changed, m_serialization)); } - private ShaderGraphProgramResult Lower(GraphDocument graph) => new ShaderGraphProgramCompiler(m_nodes).Lower(graph, "bgfx", - new Dictionary(), m_serialization, SerializationContext.empty); [Fact] public void RemovingLastParameterInputRemovesItsDeclarationWithoutMutatingTheOriginal() { GraphDocument graph = Template(); byte[] before = GraphDocumentCodec.Encode(graph, m_serialization); - GraphDocument edited = ShaderGraphBindings.RemoveNodes(graph, [new("color")], m_serialization, SerializationContext.empty); - Assert.Null(edited.FindNode(new("color"))); + GraphDocument edited = ShaderGraphBindings.RemoveNodes( + graph, + [new GraphNodeID("color")], + m_serialization, + SerializationContext.empty + ); + Assert.Null(edited.FindNode(new GraphNodeID("color"))); Assert.Empty(ShaderGraphDocument.ReadDefinition(edited, m_serialization, SerializationContext.empty).properties); Assert.Equal(before, GraphDocumentCodec.Encode(graph, m_serialization)); - Assert.DoesNotContain(edited.edges, edge => edge.output.nodeId.value == "color"); + Assert.DoesNotContain(edited.edges, edge => edge.output.nodeID.value == "color"); } [Fact] public void RemovingOneSharedBindingPreservesItsDefaultAndRemainingStageVisibility() { GraphDocument graph = Template(); - var node = new GraphNodeRecord(new("vertex-color"), "inno.shader.stage-input"); + var node = new GraphNodeRecord(new GraphNodeID("vertex-color"), "inno.shader.stage-input"); node.SetValue("stage", ShaderGraphDocument.Encode("vertex", m_serialization, SerializationContext.empty)); graph.AddNode(node); - var settings = new ShaderGraphInputSettings { id = "color", kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" } }; + var settings = new ShaderGraphInputSettings + { + id = "color", + kind = ShaderIrInputKind.Uniform, + type = new() { id = "float4" } + }; graph = ShaderGraphBindings.ChangeInput(graph, node.id, settings, m_serialization, SerializationContext.empty); - ShaderPropertyDefinition original = Assert.Single(ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty).properties); + ShaderPropertyDefinition original = Assert.Single( + ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty).properties + ); Assert.Equal(ShaderStage.Vertex | ShaderStage.Fragment, original.stages); GraphDocument edited = ShaderGraphBindings.RemoveNodes(graph, [node.id], m_serialization, SerializationContext.empty); - ShaderPropertyDefinition remaining = Assert.Single(ShaderGraphDocument.ReadDefinition(edited, m_serialization, SerializationContext.empty).properties); + ShaderPropertyDefinition remaining = Assert.Single( + ShaderGraphDocument.ReadDefinition(edited, m_serialization, SerializationContext.empty).properties + ); Assert.Equal(ShaderStage.Fragment, remaining.stages); Assert.Equal(original.defaultValue, remaining.defaultValue); Assert.True(Lower(edited).succeeded); @@ -161,15 +213,34 @@ public void RemovingOneSharedBindingPreservesItsDefaultAndRemainingStageVisibili public void RemovingNodesFromAnIncompleteDocumentDoesNotRequireSuccessfulCompilation() { var graph = new GraphDocument(); - graph.AddNode(new(new("unknown"), "tests.uninstalled")); - GraphDocument edited = ShaderGraphBindings.RemoveNodes(graph, [new("unknown")], m_serialization, SerializationContext.empty); + graph.AddNode(new GraphNodeRecord(new GraphNodeID("unknown"), "tests.uninstalled")); + GraphDocument edited = ShaderGraphBindings.RemoveNodes( + graph, + [new GraphNodeID("unknown")], + m_serialization, + SerializationContext.empty + ); Assert.Empty(edited.nodes); Assert.Single(graph.nodes); } public void Dispose() { - m_nodes.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); + m_nodes.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); if (Directory.Exists(m_root)) Directory.Delete(m_root, true); } + + private GraphDocument Template() => ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); + + private ShaderGraphProgramResult Lower(GraphDocument graph) + => new ShaderGraphProgramCompiler(m_nodes).Lower( + graph, + "bgfx", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs deleted file mode 100644 index 9a00108c9..000000000 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Inno.Integration.MacOSArm64.Bgfx; -using System; -using System.Runtime.Versioning; -using System.Linq; -using System.Threading.Tasks; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Core.Graphs; -using Inno.Core.Serialization; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Xunit; -using Inno.Rendering.Assets.Authoring; - -namespace Inno.Rendering.Shaders.Tests; - -public sealed partial class ShaderGraphProgramTests -{ - [Fact] - public void StorageGraphKeepsExplicitEffectsEvenWithoutAValueOutput() - { - ShaderGraphProgramResult lowered = Lower(StorageGraph()); - Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); - ShaderIrStage stage = Assert.Single(Assert.Single(lowered.passes).stages); - Assert.Equal(new[] { ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd }, - stage.body.instructions.Where(value => value.hasSideEffects).Select(value => value.operation)); - } - - [MetalShaderFact] - [SupportedOSPlatform("macos")] - public async Task StorageGraphCompilesThroughTheSameMetalToolchainAsSourceNodes() - { - ShaderGraphProgramResult lowered = Lower(StorageGraph()); - Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); - RenderTextureFormat[] formats = Enum.GetValues(); - var caps = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, new(256, 8, 8192, 16), - formats, formats, formats, formats, false, false, formats, formats, formats); - ShaderStageToolResult result = await compiler.CompileAsync(lowered.passes[0].stages[0], compiler.CreateTarget(caps)); - Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); - } - - [Fact] - public void RerouteRetainsAggregateAndStoragePortContracts() - { - ShaderSourceType aggregate = ShaderSourceType.Structure("Payload", [new("points", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float2"), 3))]); - foreach (ShaderSourceType type in new[] { aggregate, ShaderSourceType.Storage(ShaderStorageType.Buffer(aggregate, RenderStorageAccess.ReadWrite)) }) - { - var node = new GraphNodeRecord(new("route"), "inno.shader.reroute"); - node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(type), m_serialization, SerializationContext.empty)); - var ports = m_nodes.DescribePorts(node, m_serialization, SerializationContext.empty); - Assert.Equal(2, ports.Count); - Assert.All(ports, port => Assert.True(type.IsEquivalentTo(port.type))); - } - } - - private GraphDocument StorageGraph() - { - GraphDocument graph = ShaderGraphDocument.Create(new("Compute", [], [], [new("Main", ShaderProgramKind.Compute)]), m_serialization, SerializationContext.empty); - GraphNodeRecord stage = Node("compute", ShaderGraphDocument.outputDefinitionId); - Set(stage, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Compute }); - var resourceType = new ShaderGraphType { isStorage = true, access = RenderStorageAccess.ReadWrite, storageElement = new() { id = "uint" } }; - GraphNodeRecord resource = Node("resource", "inno.shader.stage-input"); - var settings = new ShaderGraphInputSettings { id = "buffer", kind = ShaderIrInputKind.Storage, type = resourceType }; - Set(resource, "settings", settings); - GraphNodeRecord coordinate = Node("coordinate", "inno.shader.constant"); Set(coordinate, "type", "uint"); Set(coordinate, "value", 0u); - GraphNodeRecord value = Node("constant", "inno.shader.constant"); Set(value, "type", "uint"); Set(value, "value", 7u); - GraphNodeRecord store = Node("z-store", "inno.shader.storage-store"), load = Node("m-load", "inno.shader.storage-load"), atomic = Node("a-atomic", "inno.shader.storage-atomic-add"); - foreach (GraphNodeRecord effect in new[] { store, load, atomic }) - { Set(effect, "resource", resourceType); Connect(resource, "value", effect, "resource"); Connect(coordinate, "value", effect, "coordinate"); } - Connect(value, "value", store, "value"); Connect(value, "value", atomic, "value"); - Connect(store, "then", load, "after"); Connect(load, "then", atomic, "after"); - graph = ShaderGraphPrograms.Bind(graph, "Main", [stage.id], m_serialization, SerializationContext.empty); - return ShaderGraphBindings.ChangeInput(graph, resource.id, settings, m_serialization, SerializationContext.empty); - - GraphNodeRecord Node(string id, string type) - { - var node = new GraphNodeRecord(new(id), type); - if (id != "compute") Set(node, "stage", "compute"); - graph.AddNode(node); return node; - } - void Set(GraphNodeRecord node, string key, T data) => node.SetValue(key, ShaderGraphDocument.Encode(data, m_serialization, SerializationContext.empty)); - void Connect(GraphNodeRecord output, string outputPort, GraphNodeRecord input, string inputPort) - => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(output.id, new(outputPort)), new(input.id, new(inputPort)))); - } -} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs index 742a7f54a..29ba7a552 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Inno.Build.Toolchains.Bgfx.Tools; using Xunit; +using Inno.Build.Toolchains.Bgfx.Tools; namespace Inno.Rendering.Shaders.Tests; @@ -17,10 +17,15 @@ public void NumericGraphLowersToTypedOrderedValuesInsteadOfSourceFragments() ShaderIrValue scaled = builder.Binary(ShaderIrOperation.Multiply, input, builder.Constant(2f)); ShaderIrValue clamped = builder.Binary(ShaderIrOperation.Minimum, scaled, builder.Constant(1f)); ShaderIrBlock block = builder.Build(new Dictionary { ["color"] = clamped }); - Assert.Equal([ShaderIrOperation.Input, ShaderIrOperation.Constant, ShaderIrOperation.Multiply, - ShaderIrOperation.Constant, ShaderIrOperation.Minimum], block.instructions.Select(static value => value.operation)); + Assert.Equal([ + ShaderIrOperation.Input, + ShaderIrOperation.Constant, + ShaderIrOperation.Multiply, + ShaderIrOperation.Constant, + ShaderIrOperation.Minimum + ], block.instructions.Select(static value => value.operation)); Assert.Equal("float", block.outputs["color"].type.id); - Assert.Equal(0x40000000UL, block.instructions[1].constantBits); + Assert.Equal(0x4000_0000UL, block.instructions[1].constantBits); Assert.Same(input, builder.Input("brightness", ShaderSourceType.Atomic("float"))); Assert.Throws(() => builder.Input("brightness", ShaderSourceType.Atomic("int"))); } @@ -34,7 +39,7 @@ public void ScalarConstantsKeepSignedZeroAndFullIntegerPrecision() _ = builder.Constant(int.MinValue); _ = builder.Constant(true); ShaderIrBlock block = builder.Build(new Dictionary()); - Assert.Equal([0x80000000UL, 0xffffffffUL, 0x80000000UL, 1UL], block.instructions.Select(static value => value.constantBits)); + Assert.Equal([0x8000_0000UL, 0xFFFF_FFFFUL, 0x8000_0000UL, 1UL], block.instructions.Select(static value => value.constantBits)); Assert.Throws(() => builder.Constant(float.NaN)); Assert.Throws(() => builder.Constant(float.PositiveInfinity)); } @@ -60,7 +65,10 @@ public void AggregateConstructionAndExtractionKeepFullMemberTypes() ShaderIrValue x = builder.Constant(1f); ShaderIrValue y = builder.Constant(2f); ShaderIrValue vector = builder.Construct(ShaderSourceType.Atomic("float2"), x, y); - ShaderSourceType structure = ShaderSourceType.Structure("Surface", [new("uv", vector.type), new("intensity", x.type)]); + ShaderSourceType structure = ShaderSourceType.Structure( + "Surface", + [new ShaderSourceField("uv", vector.type), new ShaderSourceField("intensity", x.type)] + ); ShaderIrValue surface = builder.Construct(structure, vector, x); ShaderIrValue array = builder.Construct(ShaderSourceType.ArrayOf(structure, 2), surface, surface); Assert.True(structure.IsEquivalentTo(builder.Extract(array, 1).type)); @@ -76,8 +84,10 @@ public void AggregateConstructionAndExtractionKeepFullMemberTypes() public void MatrixConstructionSpecifiesColumnMajorOrderAndExtractionReturnsAColumn() { var builder = new ShaderIrBuilder(); - ShaderIrValue matrix = builder.Construct(ShaderSourceType.Atomic("float2x3"), - Enumerable.Range(1, 6).Select(value => builder.Constant((float)value)).ToArray()); + ShaderIrValue matrix = builder.Construct( + ShaderSourceType.Atomic("float2x3"), + Enumerable.Range(1, 6).Select(value => builder.Constant((float)value)).ToArray() + ); Assert.Equal("float3", builder.Extract(matrix, 1).type.id); Assert.Throws(() => builder.Extract(matrix, 2)); } @@ -101,14 +111,19 @@ public void ComparisonAndSelectionCannotHideTypeOrControlFlowChanges() [Fact] public void MixedArithmeticAndSourceCallDeriveOutAndInOutByName() { - ShaderSourceModuleAnalysis module = Module("float Shade(float gain, out float alpha, inout vec2 uv) { alpha = gain; uv *= gain; return alpha; }"); + ShaderSourceModuleAnalysis module = Module( + "float Shade(float gain, out float alpha, inout vec2 uv) { alpha = gain; uv *= gain; return alpha; }" + ); Assert.True(module.succeeded); var builder = new ShaderIrBuilder(); ShaderIrValue gain = builder.Binary(ShaderIrOperation.Multiply, builder.Constant(0.5f), builder.Constant(2f)); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(1f)); // Dictionary insertion order must not become native function argument order. IReadOnlyDictionary outputs = builder.Call(module, "test", new Dictionary - { ["uv"] = uv, ["gain"] = gain }); + { + ["uv"] = uv, + ["gain"] = gain + }); Assert.Equal(["return", "output.alpha", "output.uv"], outputs.Keys); ShaderIrBlock block = builder.Build(outputs); ShaderIrInstruction call = block.instructions[^1]; @@ -125,7 +140,11 @@ public void CallsWithUnusedOutputsAndVoidCallsRemainInEvaluationOrder() ShaderSourceModuleAnalysis module = Module("void Shade(inout float value) { value *= value; }"); var builder = new ShaderIrBuilder(); ShaderIrValue input = builder.Constant(2f); - IReadOnlyDictionary first = builder.Call(module, "test", new Dictionary { ["value"] = input }); + IReadOnlyDictionary first = builder.Call( + module, + "test", + new Dictionary { ["value"] = input } + ); _ = builder.Call(module, "test", new Dictionary { ["value"] = first["output.value"] }); ShaderSourceModuleAnalysis voidModule = Module("void Shade() { }"); Assert.Empty(builder.Call(voidModule, "test", new Dictionary())); @@ -142,9 +161,16 @@ public void InvalidOrMismatchedSourceModulesNeverEnterAnIntermediateBlock() ShaderSourceModuleAnalysis invalid = Module("float Other(float gain) { return gain; }"); Assert.Throws(() => builder.Call(invalid, "test", new Dictionary())); Assert.Throws(() => builder.Call(module, "not-registered", new Dictionary())); - Assert.Throws(() => builder.Call(module, "test", new Dictionary { ["renamed"] = builder.Constant(1f) })); - Assert.Throws(() => builder.Call(module, "test", new Dictionary { ["gain"] = builder.Constant(1) })); - Assert.DoesNotContain(builder.Build(new Dictionary()).instructions, value => value.operation == ShaderIrOperation.SourceCall); + Assert.Throws( + () => builder.Call(module, "test", new Dictionary { ["renamed"] = builder.Constant(1f) }) + ); + Assert.Throws( + () => builder.Call(module, "test", new Dictionary { ["gain"] = builder.Constant(1) }) + ); + Assert.DoesNotContain( + builder.Build(new Dictionary()).instructions, + value => value.operation == ShaderIrOperation.SourceCall + ); } [Fact] @@ -162,10 +188,17 @@ public void CompletedBlocksAreDetachedFromLaterBuilderAndOutputDictionaryEdits() private static ShaderSourceModuleAnalysis Module(string text) => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([ - new("test", "inno.shader-language.bgfx-sc", new(new("Module.ishadersource", text), "Shade", new NoIncludes()))]); + new ShaderSourceImplementationRequest( + "test", + "inno.shader-language.bgfx-sc", + new ShaderSourceRequest(new ShaderSourceFile("Module.ishadersource", text), "Shade", new NoIncludes()) + )]); private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs index d42b86de8..57d3a8ff0 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Shaders.Tests; @@ -10,8 +10,12 @@ public sealed class ShaderIrStageTests [Fact] public void SemanticHashCoversNestedCodeStorageAccessBindingsAndWorkgroups() { - string Hash(float value, int slot, int threads, RenderStorageAccess access) - { + string Hash( + float value, + int slot, + int threads, + RenderStorageAccess access + ) { var builder = new ShaderIrBuilder(); ShaderSourceType resourceType = ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic("float"), access)); ShaderIrValue resource = builder.Input("resource", resourceType); @@ -21,8 +25,13 @@ string Hash(float value, int slot, int threads, RenderStorageAccess access) region.StoreStorage(resource, region.Constant(0u), region.Constant(value)); return new Dictionary(); }, region => new Dictionary()); - return new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("resource", resourceType, ShaderIrInputKind.Storage, location: slot)], [], threads).contentHash; + return new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new ShaderIrStageInput("resource", resourceType, ShaderIrInputKind.Storage, location: slot)], + [], + threads + ).contentHash; } string first = Hash(1f, 0, 8, RenderStorageAccess.ReadWrite); Assert.Equal(first, Hash(1f, 0, 8, RenderStorageAccess.ReadWrite)); @@ -38,14 +47,23 @@ public void VertexStageRequiresClipPositionAndExactBodyInterface() var builder = new ShaderIrBuilder(); ShaderIrValue position = builder.Input("position", ShaderSourceType.Atomic("float4")); ShaderIrBlock body = builder.Build(new Dictionary { ["clip"] = position }); - ShaderIrStageInput input = new("position", position.type, ShaderIrInputKind.VertexAttribute, "position"); - ShaderIrStageOutput output = new("clip", ShaderIrOutputKind.ClipPosition); + var input = new ShaderIrStageInput("position", position.type, ShaderIrInputKind.VertexAttribute, "position"); + var output = new ShaderIrStageOutput("clip", ShaderIrOutputKind.ClipPosition); var stage = new ShaderIrStage(ShaderStage.Vertex, body, [input], [output]); Assert.Same(body, stage.body); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [], [output])); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [])); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [new("clip", ShaderIrOutputKind.Varying, "texcoord")])); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, body, [input], [new("clip", ShaderIrOutputKind.Color)])); + Assert.Throws( + () => new ShaderIrStage( + ShaderStage.Vertex, + body, + [input], + [new ShaderIrStageOutput("clip", ShaderIrOutputKind.Varying, "texcoord")] + ) + ); + Assert.Throws( + () => new ShaderIrStage(ShaderStage.Fragment, body, [input], [new ShaderIrStageOutput("clip", ShaderIrOutputKind.Color)]) + ); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [output], threadsX: 2)); } @@ -56,9 +74,27 @@ public void AliasedResourceSlotsAndUnmappedOutputsAreRejected() _ = builder.Input("first", ShaderSourceType.Atomic("sampled-texture2d")); _ = builder.Input("second", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrBlock body = builder.Build(new Dictionary()); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, body, - [new("first", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-1", 2), - new("second", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-2", 2)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Fragment, + body, + [ + new ShaderIrStageInput( + "first", + ShaderSourceType.Atomic("sampled-texture2d"), + ShaderIrInputKind.SampledTexture, + "ignored-1", + 2 + ), + new ShaderIrStageInput( + "second", + ShaderSourceType.Atomic("sampled-texture2d"), + ShaderIrInputKind.SampledTexture, + "ignored-2", + 2 + ) + ], + [] + )); } [Fact] @@ -66,10 +102,10 @@ public void ComputeCannotPretendToBeRasterAndStageCopiesInterfaceLists() { var builder = new ShaderIrBuilder(); ShaderIrBlock body = builder.Build(new Dictionary()); - var inputs = new List(); - var outputs = new List(); + List inputs = []; + List outputs = []; var stage = new ShaderIrStage(ShaderStage.Compute, body, inputs, outputs, 8, 4, 2); - inputs.Add(new("late", ShaderSourceType.Atomic("float"), ShaderIrInputKind.Uniform)); + inputs.Add(new ShaderIrStageInput("late", ShaderSourceType.Atomic("float"), ShaderIrInputKind.Uniform)); Assert.Empty(stage.inputs); Assert.Equal(8, stage.threadsX); Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, body, [], [], 0)); diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs index 7aa37e0f1..c97d1c199 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs @@ -1,13 +1,13 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.Linq; +using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -18,18 +18,31 @@ public sealed class ShaderResourceIrTests public void AggregateNamesCannotImpersonateGpuScalarVectorOrResourceTypes() { var builder = new ShaderIrBuilder(); - ShaderSourceType impostor = ShaderSourceType.Structure("uint", [new("field", ShaderSourceType.Atomic("uint"))]); + ShaderSourceType impostor = ShaderSourceType.Structure("uint", [new ShaderSourceField("field", ShaderSourceType.Atomic("uint"))]); ShaderIrValue value = builder.Construct(impostor, builder.Constant(0u)); - ShaderIrValue storage = builder.Input("storage", ShaderSourceType.Storage(ShaderStorageType.Buffer(impostor, RenderStorageAccess.ReadWrite))); + ShaderIrValue storage = builder.Input( + "storage", + ShaderSourceType.Storage(ShaderStorageType.Buffer(impostor, RenderStorageAccess.ReadWrite)) + ); Assert.Throws(() => builder.AtomicAddStorage(storage, builder.Constant(0u), value)); - ShaderSourceType textureType = ShaderSourceType.Structure("sampled-texture2d", [new("field", ShaderSourceType.Atomic("float"))]); + ShaderSourceType textureType = ShaderSourceType.Structure( + "sampled-texture2d", + [new ShaderSourceField("field", ShaderSourceType.Atomic("float"))] + ); ShaderIrValue texture = builder.Input("texture", textureType); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(0f)); Assert.Throws(() => builder.Sample(texture, uv)); var color = new ShaderIrBuilder(); - ShaderIrValue fakeColor = color.Construct(ShaderSourceType.Structure("float4", [new("field", ShaderSourceType.Atomic("float"))]), color.Constant(1f)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, - color.Build(new Dictionary { ["color"] = fakeColor }), [], [new("color", ShaderIrOutputKind.Color)])); + ShaderIrValue fakeColor = color.Construct( + ShaderSourceType.Structure("float4", [new ShaderSourceField("field", ShaderSourceType.Atomic("float"))]), + color.Constant(1f) + ); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Fragment, + color.Build(new Dictionary { ["color"] = fakeColor }), + [], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + )); } [Fact] @@ -40,10 +53,16 @@ public void StorageTypesKeepAccessShapeFormatAndCompleteElementLayout() Assert.False(read.IsEquivalentTo(Buffer("uint", RenderStorageAccess.ReadWrite))); Assert.False(read.IsEquivalentTo(Buffer("int", RenderStorageAccess.Read))); Assert.False(read.IsEquivalentTo(ShaderSourceType.Atomic("storage"))); - Assert.False(Image().IsEquivalentTo(ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite, array: true)))); + Assert.False( + Image().IsEquivalentTo( + ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite, array: true)) + ) + ); Assert.Throws(() => ShaderStorageType.Buffer(read, RenderStorageAccess.Read)); Assert.Throws(() => ShaderStorageType.Image(RenderTextureFormat.RGBA8Srgb, RenderStorageAccess.Read)); - Assert.Throws(() => ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.Read, RenderTextureDimension.Cube)); + Assert.Throws( + () => ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.Read, RenderTextureDimension.Cube) + ); } [Fact] @@ -57,8 +76,15 @@ public void StorageReadsWritesAndAtomicsKeepTheirExactEvaluationOrder() ShaderIrValue second = builder.LoadStorage(resource, index); ShaderIrValue previous = builder.AtomicAddStorage(resource, index, builder.Constant(1u)); ShaderIrBlock block = builder.Build(new Dictionary()); - Assert.Equal([ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd], - block.instructions.Where(static value => value.hasSideEffects).Select(static value => value.operation)); + Assert.Equal( + [ + ShaderIrOperation.StorageLoad, + ShaderIrOperation.StorageStore, + ShaderIrOperation.StorageLoad, + ShaderIrOperation.StorageAtomicAdd + ], + block.instructions.Where(static value => value.hasSideEffects).Select(static value => value.operation) + ); Assert.NotEqual(first.index, second.index); Assert.Equal("uint", previous.type.id); Assert.Single(block.instructions.Where(static value => value.operation == ShaderIrOperation.StorageStore)); @@ -79,8 +105,16 @@ public void ResourceAccessAndCoordinateErrorsFailBeforeNativeCodeGeneration() Assert.Throws(() => builder.Select(builder.Constant(true), read, read)); ShaderIrValue image = builder.Input("image", Image()); Assert.Throws(() => builder.LoadStorage(image, index)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("read", read.type, ShaderIrInputKind.Uniform), new("write", write.type, ShaderIrInputKind.Storage), new("image", image.type, ShaderIrInputKind.Storage, location: 1)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [ + new ShaderIrStageInput("read", read.type, ShaderIrInputKind.Uniform), + new ShaderIrStageInput("write", write.type, ShaderIrInputKind.Storage), + new ShaderIrStageInput("image", image.type, ShaderIrInputKind.Storage, location: 1) + ], + [] + )); } [Fact] @@ -90,13 +124,19 @@ public void ImplicitDerivativesAndDiscardCannotLeakIntoVertexOrComputeStages() ShaderIrValue texture = builder.Input("texture", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(0f)); _ = builder.Sample(texture, uv); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new ShaderIrStageInput("texture", texture.type, ShaderIrInputKind.SampledTexture)], + [] + )); Assert.Throws(() => builder.Sample(texture, builder.Constant(0f))); Assert.Throws(() => builder.SampleLevel(texture, uv, builder.Constant(0))); var discard = new ShaderIrBuilder(); discard.Discard(discard.Constant(false)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, discard.Build(new Dictionary()), [], [])); + Assert.Throws( + () => new ShaderIrStage(ShaderStage.Compute, discard.Build(new Dictionary()), [], []) + ); } [MetalShaderFact] @@ -110,12 +150,20 @@ public async Task TypedStorageBuffersCompileRealLoadsStoresAndAtomics() ShaderIrValue value = builder.LoadStorage(source, index); ShaderIrValue previous = builder.AtomicAddStorage(target, index, value); builder.StoreStorage(target, builder.Constant(1u), previous); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("source", source.type, ShaderIrInputKind.Storage), new("target", target.type, ShaderIrInputKind.Storage, location: 1)], [], 8); - ShaderStageToolResult result = await Compile(stage); + var stage = new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [ + new ShaderIrStageInput("source", source.type, ShaderIrInputKind.Storage), + new ShaderIrStageInput("target", target.type, ShaderIrInputKind.Storage, location: 1) + ], + [], + 8 + ); + ShaderStageToolResult result = await CompileAsync(stage); Success(result); Assert.Equal(2, result.bindings.Count); - Assert.False((await Compile(stage, GraphicsCapability.Compute)).succeeded); + Assert.False((await CompileAsync(stage, GraphicsCapability.Compute)).succeeded); } [MetalShaderFact] @@ -123,20 +171,31 @@ public async Task TypedStorageBuffersCompileRealLoadsStoresAndAtomics() public async Task TypedStorageImagesCompileForTwoDimensionalArraysAndVolumes() { foreach ((RenderTextureDimension dimension, bool array) in new[] - { (RenderTextureDimension.Texture2D, false), (RenderTextureDimension.Texture2D, true), (RenderTextureDimension.Texture3D, false) }) - { + { + (RenderTextureDimension.Texture2D, false), + (RenderTextureDimension.Texture2D, true), + (RenderTextureDimension.Texture3D, false) + } + ) { var builder = new ShaderIrBuilder(); - ShaderSourceType type = ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA16Float, RenderStorageAccess.ReadWrite, dimension, array)); + ShaderSourceType type = ShaderSourceType.Storage( + ShaderStorageType.Image(RenderTextureFormat.RGBA16Float, RenderStorageAccess.ReadWrite, dimension, array) + ); ShaderIrValue image = builder.Input("image", type); ShaderIrValue zero = builder.Constant(0); ShaderIrValue coordinate = array || dimension == RenderTextureDimension.Texture3D - ? builder.Construct(ShaderSourceType.Atomic("int3"), zero, zero, zero) - : builder.Construct(ShaderSourceType.Atomic("int2"), zero, zero); + ? builder.Construct(ShaderSourceType.Atomic("int3"), zero, zero, zero) + : builder.Construct(ShaderSourceType.Atomic("int2"), zero, zero); ShaderIrValue loaded = builder.LoadStorage(image, coordinate); builder.StoreStorage(image, coordinate, builder.Binary(ShaderIrOperation.Add, loaded, loaded)); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), [new("image", type, ShaderIrInputKind.Storage)], []); - Success(await Compile(stage)); - Assert.False((await Compile(stage, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer)).succeeded); + var stage = new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new ShaderIrStageInput("image", type, ShaderIrInputKind.Storage)], + [] + ); + Success(await CompileAsync(stage)); + Assert.False((await CompileAsync(stage, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer)).succeeded); } } @@ -149,29 +208,57 @@ public async Task SamplingAndFragmentDiscardCompileWithoutAHandwrittenModule() var builder = new ShaderIrBuilder(); ShaderIrValue texture = builder.Input("texture", ShaderSourceType.Atomic(kind)); ShaderIrValue zero = builder.Constant(0f); - ShaderIrValue uv = kind == "sampled-texture2d" ? builder.Construct(ShaderSourceType.Atomic("float2"), zero, zero) - : builder.Construct(ShaderSourceType.Atomic("float3"), zero, zero, zero); + ShaderIrValue uv = kind == "sampled-texture2d" + ? builder.Construct(ShaderSourceType.Atomic("float2"), zero, zero) + : builder.Construct(ShaderSourceType.Atomic("float3"), zero, zero, zero); ShaderIrValue sampled = builder.Sample(texture, uv); ShaderIrValue level = builder.SampleLevel(texture, uv, zero); ShaderIrValue color = builder.Binary(ShaderIrOperation.Add, sampled, level); builder.Discard(builder.Binary(ShaderIrOperation.LessThan, builder.Extract(sampled, 3), builder.Constant(0.01f))); - Success(await Compile(new(ShaderStage.Fragment, builder.Build(new Dictionary { ["color"] = color }), - [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], [new("color", ShaderIrOutputKind.Color)]))); + Success( + await CompileAsync( + new ShaderIrStage( + ShaderStage.Fragment, + builder.Build(new Dictionary { ["color"] = color }), + [new ShaderIrStageInput("texture", texture.type, ShaderIrInputKind.SampledTexture)], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ) + ) + ); } } - private static ShaderSourceType Buffer(string element, RenderStorageAccess access) - => ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic(element), access)); - private static ShaderSourceType Image() => ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite)); - private static async Task Compile(ShaderIrStage stage, GraphicsCapability features = GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D) - { - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, features, new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), false, false); + private static ShaderSourceType Buffer( + string element, + RenderStorageAccess access + ) => ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic(element), access)); + + private static ShaderSourceType Image() + => ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite)); + + private static async Task CompileAsync( + ShaderIrStage stage, + GraphicsCapability features = GraphicsCapability.Compute + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Texture3D + ) { + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); + var capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); return await new ShaderCompiler(toolchain).CompileAsync(stage, toolchain.CreateTarget(capabilities)); } + private static void Success(ShaderStageToolResult result) => Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs index 87ec326e1..efd1d4567 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -18,9 +18,9 @@ public void SharedRegistryDiscoversIndependentLanguagesAndRetiresItsProviders() using var fixture = new Fixture(); using (var registry = new ShaderSourceFrontendRegistry(fixture.types)) { - Assert.Contains("inno.shader-language.bgfx-sc", registry.languageIds); - Assert.Contains("tests.registry.language", registry.languageIds); - var request = new ShaderSourceRequest(new("value.ishadersource", "source"), "Value", new NoIncludes()); + Assert.Contains("inno.shader-language.bgfx-sc", registry.languageIDs); + Assert.Contains("tests.registry.language", registry.languageIDs); + var request = new ShaderSourceRequest(new ShaderSourceFile("value.ishadersource", "source"), "Value", new NoIncludes()); Assert.True(registry.Analyze("tests.registry.language", request).succeeded); fixture.modules.Rebuild(); Assert.True(registry.Analyze("tests.registry.language", request).succeeded); @@ -36,54 +36,51 @@ public void DuplicateCandidateReleasesNewProvidersAndKeepsPreviousSnapshotUsable _ = new BgfxShaderSourceFrontend(); using var fixture = new Fixture(); using var registry = new ShaderSourceFrontendRegistry(fixture.types); - Assert.Contains("tests.registry.language", registry.languageIds); + Assert.Contains("tests.registry.language", registry.languageIDs); RegistryFrontendProbe.conflict = true; - try { Assert.ThrowsAny(fixture.modules.Rebuild); } - finally { RegistryFrontendProbe.conflict = false; } - Assert.Contains("tests.registry.language", registry.languageIds); + try + { + Assert.ThrowsAny(fixture.modules.Rebuild); + } + finally + { + RegistryFrontendProbe.conflict = false; + } + Assert.Contains("tests.registry.language", registry.languageIDs); Assert.Equal(1, RegistryFrontendProbe.created - RegistryFrontendProbe.disposed); } private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } private sealed class Fixture : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoShaderRegistry", Guid.NewGuid().ToString("N")); - internal ModuleHost modules { get; } - internal TypeCatalog types { get; } + internal Fixture() { RegistryFrontendProbe.created = 0; RegistryFrontendProbe.disposed = 0; RegistryFrontendProbe.conflict = false; - modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderSourceFrontendRegistryTests).Assembly)}); - types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + this.modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderSourceFrontendRegistryTests).Assembly)} + ); + this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); } + public void Dispose() { types.Dispose(); modules.Dispose(); if (Directory.Exists(m_root)) Directory.Delete(m_root, true); } - } -} -internal sealed class RegistryFrontendProbe : IShaderSourceFrontend, IDisposable -{ - internal static int created; - internal static int disposed; - internal static bool conflict; - private readonly string m_languageId; - public RegistryFrontendProbe() - { - created++; - m_languageId = conflict ? "inno.shader-language.bgfx-sc" : "tests.registry.language"; + internal ModuleHost modules { get; } + internal TypeCatalog types { get; } } - public string languageId => m_languageId; - public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) - => new(new(request.entryPoint, ShaderSourceType.Atomic("float"), [], new(request.source.assetPath, 1, 1)), [], []); - public void Dispose() => disposed++; } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs index 61e730489..0724416ba 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering.Shaders; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -25,7 +25,9 @@ public void SourceModulesCannotReadGeneratedStageBindingsImplicitly(string sourc [Fact] public void ExplicitParametersAndStructureMembersDoNotBecomeImplicitBindings() { - ShaderSourceAnalysis result = Analyze("struct Data { vec4 a_position; }; vec4 Shade(Data value, mat4 u_viewProj) { return mul(u_viewProj, value.a_position); }"); + ShaderSourceAnalysis result = Analyze( + "struct Data { vec4 a_position; }; vec4 Shade(Data value, mat4 u_viewProj) { return mul(u_viewProj, value.a_position); }" + ); Assert.True(result.succeeded, Errors(result)); } @@ -36,8 +38,10 @@ public void SourceFunctionDerivesInputOutputAndInOutFromOneDeclaration() Assert.True(result.succeeded, Errors(result)); Assert.Equal("float3", result.function!.returnType.id); Assert.Equal(["uv", "alpha", "color"], result.function.parameters.Select(static parameter => parameter.name)); - Assert.Equal([ShaderSourceParameterDirection.Input, ShaderSourceParameterDirection.Output, ShaderSourceParameterDirection.InputOutput], - result.function.parameters.Select(static parameter => parameter.direction)); + Assert.Equal( + [ShaderSourceParameterDirection.Input, ShaderSourceParameterDirection.Output, ShaderSourceParameterDirection.InputOutput], + result.function.parameters.Select(static parameter => parameter.direction) + ); } [Fact] @@ -163,10 +167,13 @@ public void PreprocessorHandlesElseIfAndShortCircuitWithoutReadingInactiveInclud [InlineData("#else\nfloat Shade(float v) {}", "Shade")] [InlineData("uniform vec4 global;\nfloat Shade(float v) {}", "Shade")] [InlineData("#define F(a,) a\nfloat Shade(float value) {}", "Shade")] - public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts(string source, string entry) - { + public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts( + string source, + string entry + ) { ShaderSourceAnalysis result = new BgfxShaderSourceFrontend().Analyze( - new(new("bad.ishadersource", source), entry, new Includes([]))); + new ShaderSourceRequest(new ShaderSourceFile("bad.ishadersource", source), entry, new Includes([])) + ); Assert.False(result.succeeded); Assert.NotEmpty(result.diagnostics); Assert.Equal("bad.ishadersource", result.diagnostics[0].location.assetPath); @@ -176,8 +183,10 @@ public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts(string s [Fact] public void IncludedFailureReportsOriginalFileAndKeepsDependency() { - ShaderSourceAnalysis result = Analyze("#include \"bad.inc\"\nfloat Shade(float v) {}", - new Dictionary { ["bad.inc"] = "struct Broken { Undefined x; };" }); + ShaderSourceAnalysis result = Analyze( + "#include \"bad.inc\"\nfloat Shade(float v) {}", + new Dictionary { ["bad.inc"] = "struct Broken { Undefined x; };" } + ); Assert.False(result.succeeded); Assert.Equal("bad.inc", result.diagnostics[0].location.assetPath); Assert.Equal("bad.inc", Assert.Single(result.dependencies)); @@ -186,8 +195,10 @@ public void IncludedFailureReportsOriginalFileAndKeepsDependency() [Fact] public void PragmaOnceBreaksGuardedIncludeCycles() { - ShaderSourceAnalysis result = Analyze("#include \"a.inc\"\nfloat Shade(Data value) { return value.x; }", - new Dictionary { ["a.inc"] = "#pragma once\n#include \"a.inc\"\nstruct Data { float x; };" }); + ShaderSourceAnalysis result = Analyze( + "#include \"a.inc\"\nfloat Shade(Data value) { return value.x; }", + new Dictionary { ["a.inc"] = "#pragma once\n#include \"a.inc\"\nstruct Data { float x; };" } + ); Assert.True(result.succeeded, Errors(result)); } @@ -207,29 +218,47 @@ public void AlternativeImplementationsMustAgreeOnAllPortSemantics() public void LanguageCatalogAcceptsAnIndependentFrontendAndRejectsConflicts() { var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend(), new IndependentFrontend()]); - Assert.Equal(2, catalog.languageIds.Count); - var request = new ShaderSourceRequest(new("custom.ishadersource", "custom"), "custom", new Includes([])); + Assert.Equal(2, catalog.languageIDs.Count); + var request = new ShaderSourceRequest(new ShaderSourceFile("custom.ishadersource", "custom"), "custom", new Includes([])); Assert.True(catalog.Analyze("tests.language", request).succeeded); Assert.Throws(() => catalog.Analyze("missing.language", request)); Assert.Throws(() => new ShaderSourceFrontendCatalog([new IndependentFrontend(), new IndependentFrontend()])); } - private static ShaderSourceAnalysis Analyze(string source, Dictionary? includes = null, - IReadOnlyDictionary? defines = null) - => new BgfxShaderSourceFrontend().Analyze(new(new("module.ishadersource", source), "Shade", new Includes(includes ?? []), defines)); + private static ShaderSourceAnalysis Analyze( + string source, + Dictionary? includes = null, + IReadOnlyDictionary? defines = null + ) => new BgfxShaderSourceFrontend().Analyze( + new ShaderSourceRequest(new ShaderSourceFile("module.ishadersource", source), "Shade", new Includes(includes ?? []), defines) + ); private static string Errors(ShaderSourceAnalysis result) => string.Join("; ", result.diagnostics.Select(static item => item.message)); private sealed class Includes(Dictionary sources) : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) - => sources.TryGetValue(include, out string? source) ? new(include, source) : throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => sources.TryGetValue(include, out string? source) + ? new ShaderSourceFile(include, source) + : throw new FileNotFoundException(include); } private sealed class IndependentFrontend : IShaderSourceFrontend { - public string languageId => "tests.language"; + public string languageID => "tests.language"; + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) - => new(new(request.entryPoint, ShaderSourceType.Atomic("float"), [], new(request.source.assetPath, 1, 1)), [], []); + => new( + new ShaderSourceFunction( + request.entryPoint, + ShaderSourceType.Atomic("float"), + [], + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ), + [], + [] + ); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs index 3a915c584..6d7969b6e 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -19,7 +19,15 @@ public void IndependentLanguagesShareOneInterfaceWithoutTranslatingSource() var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend(), alternate]); ShaderSourceModuleAnalysis result = catalog.AnalyzeModule([ Request("adapter.first", "float Shade(float value) { return value; }"), - new("adapter.second", alternate.languageId, new(new("Other.ishadersource", "native function implementation"), "ShadeOther", new Includes())) + new ShaderSourceImplementationRequest( + "adapter.second", + alternate.languageID, + new ShaderSourceRequest( + new ShaderSourceFile("Other.ishadersource", "native function implementation"), + "ShadeOther", + new Includes() + ) + ) ]); Assert.True(result.succeeded, Errors(result)); Assert.Equal("value", Assert.Single(result.function!.parameters).name); @@ -37,7 +45,8 @@ public void InterfaceChangesInvalidateWholeModuleWithoutSelectingAnArbitraryImpl { var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); ShaderSourceModuleAnalysis result = catalog.AnalyzeModule([ - Request("first", "float Shade(float value) { return value; }"), Request("second", source) + Request("first", "float Shade(float value) { return value; }"), + Request("second", source) ]); Assert.False(result.succeeded); Assert.Null(result.function); @@ -49,7 +58,7 @@ public void InterfaceChangesInvalidateWholeModuleWithoutSelectingAnArbitraryImpl [Fact] public void ConditionalVariantsMustExposeIdenticalPorts() { - const string source = """ + const string C_SOURCE = """ #if COMPACT float Shade(float value) { return value; } #else @@ -58,8 +67,8 @@ public void ConditionalVariantsMustExposeIdenticalPorts() """; var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); ShaderSourceModuleAnalysis result = catalog.AnalyzeModule([ - Request("compact", source, defines: new Dictionary { ["COMPACT"] = "1" }), - Request("full", source, defines: new Dictionary { ["COMPACT"] = "0" }) + Request("compact", C_SOURCE, defines: new Dictionary { ["COMPACT"] = "1" }), + Request("full", C_SOURCE, defines: new Dictionary { ["COMPACT"] = "0" }) ]); Assert.False(result.succeeded); Assert.Contains(result.diagnostics, value => value.code == "SHADER_SOURCE_IMPLEMENTATION_INTERFACE"); @@ -71,9 +80,9 @@ public void SourcesAndDefinesAreFrozenAndIncludedInTheContentHash() var includes = new Includes(); includes.values["data.inc"] = "#pragma once\nconst float Scale = 1.0;"; var defines = new Dictionary { ["FIRST"] = "1", ["SECOND"] = "2" }; - const string source = "#include \"data.inc\"\nfloat Shade(float value) { return value * Scale; }"; + const string C_SOURCE = "#include \"data.inc\"\nfloat Shade(float value) { return value * Scale; }"; var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); - ShaderSourceImplementationRequest request = Request("first", source, includes, defines); + ShaderSourceImplementationRequest request = Request("first", C_SOURCE, includes, defines); defines["FIRST"] = "42"; ShaderSourceImplementationAnalysis first = Assert.Single(catalog.AnalyzeModule([request]).implementations); Assert.True(first.analysis.succeeded); @@ -81,8 +90,14 @@ public void SourcesAndDefinesAreFrozenAndIncludedInTheContentHash() Assert.Equal(2, first.sources.Count); Assert.Equal("data.inc", Assert.Single(first.analysis.dependencies)); - ShaderSourceImplementationAnalysis reordered = Assert.Single(catalog.AnalyzeModule([Request("different-owner-key", source, includes, - new Dictionary { ["SECOND"] = "2", ["FIRST"] = "1" })]).implementations); + ShaderSourceImplementationAnalysis reordered = Assert.Single( + catalog.AnalyzeModule([Request( + "different-owner-key", + C_SOURCE, + includes, + new Dictionary { ["SECOND"] = "2", ["FIRST"] = "1" } + )]).implementations + ); Assert.Equal(first.contentHash, reordered.contentHash); includes.values["data.inc"] = "#pragma once\nconst float Scale = 2.0;"; ShaderSourceImplementationAnalysis changed = Assert.Single(catalog.AnalyzeModule([request]).implementations); @@ -93,7 +108,11 @@ public void SourcesAndDefinesAreFrozenAndIncludedInTheContentHash() [Fact] public void MissingLanguageRetainsSourceAndRecoversWhenItsProviderReturns() { - var implementation = new ShaderSourceImplementationRequest("alternate", "tests.alternate", new(new("Other.ishadersource", "native source"), "Other", new Includes())); + var implementation = new ShaderSourceImplementationRequest( + "alternate", + "tests.alternate", + new ShaderSourceRequest(new ShaderSourceFile("Other.ishadersource", "native source"), "Other", new Includes()) + ); ShaderSourceModuleAnalysis missing = new ShaderSourceFrontendCatalog([]).AnalyzeModule([implementation]); Assert.False(missing.succeeded); Assert.Null(missing.function); @@ -106,8 +125,11 @@ public void MissingLanguageRetainsSourceAndRecoversWhenItsProviderReturns() public void SuccessfulFrontendsCannotClaimDependenciesOutsideTheirFrozenSourceSet() { var alternate = new AlternateFrontend { inventedDependency = true }; - var request = new ShaderSourceImplementationRequest("alternate", alternate.languageId, - new(new("Other.ishadersource", "native source"), "Other", new Includes())); + var request = new ShaderSourceImplementationRequest( + "alternate", + alternate.languageID, + new ShaderSourceRequest(new ShaderSourceFile("Other.ishadersource", "native source"), "Other", new Includes()) + ); ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([alternate]).AnalyzeModule([request]); Assert.False(result.succeeded); Assert.Contains(result.diagnostics, value => value.code == "SHADER_SOURCE_DEPENDENCY_UNCAPTURED"); @@ -117,7 +139,7 @@ public void SuccessfulFrontendsCannotClaimDependenciesOutsideTheirFrozenSourceSe public void DuplicateOrEmptyImplementationSetsAreRejectedBeforeProvidersRun() { var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); - var request = Request("same", "float Shade(float value) { return value; }"); + ShaderSourceImplementationRequest request = Request("same", "float Shade(float value) { return value; }"); Assert.Throws(() => catalog.AnalyzeModule([])); Assert.Throws(() => catalog.AnalyzeModule([request, request])); } @@ -125,8 +147,11 @@ public void DuplicateOrEmptyImplementationSetsAreRejectedBeforeProvidersRun() [Fact] public void IncludeReadsCannotMixDifferentContentsForTheSameSourcePath() { - var request = Request("first", "#include \"data.inc\"\n#include \"data.inc\"\nfloat Shade(float value) { return value; }", - new ChangingIncludes()); + ShaderSourceImplementationRequest request = Request( + "first", + "#include \"data.inc\"\n#include \"data.inc\"\nfloat Shade(float value) { return value; }", + new ChangingIncludes() + ); ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request]); Assert.False(result.succeeded); Assert.Contains(result.diagnostics, value => value.message.Contains("changed during module analysis", StringComparison.Ordinal)); @@ -136,8 +161,14 @@ public void IncludeReadsCannotMixDifferentContentsForTheSameSourcePath() public void SourceErrorsCannotSwallowTheSharedRetirementBarrier() { var failure = new IOException("Source candidate is retiring.", new RetirementPendingException("Pending source owner.")); - var request = Request("first", "#include \"data.inc\"\nfloat Shade(float value) { return value; }", new FailingIncludes(failure)); - IOException actual = Assert.Throws(() => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request])); + ShaderSourceImplementationRequest request = Request( + "first", + "#include \"data.inc\"\nfloat Shade(float value) { return value; }", + new FailingIncludes(failure) + ); + IOException actual = Assert.Throws( + () => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request]) + ); Assert.Same(failure, actual); } @@ -157,50 +188,82 @@ public void AStageMainPrototypeIsNotAnAllowedFunctionModule() [InlineData("struct Data { void values[2]; }; float Shade(float value) { return value; }")] public void VoidCannotBeSmuggledIntoTheValueInterfaceViaAnArrayOrAlias(string source) { - ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([Request("test", source)]); + ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog( + [new BgfxShaderSourceFrontend()] + ).AnalyzeModule([Request("test", source)]); Assert.False(result.succeeded); - Assert.Contains(result.diagnostics, value => value.code == "SHADER_SOURCE_INTERFACE" && value.message.Contains("void", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + value => value.code == "SHADER_SOURCE_INTERFACE" && value.message.Contains("void", StringComparison.Ordinal) + ); Assert.Throws(() => ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("void"), 2)); Assert.Throws(() => new ShaderSourceField("value", ShaderSourceType.Atomic("void"))); - Assert.Throws(() => new ShaderSourceParameter("value", ShaderSourceType.Atomic("void"), ShaderSourceParameterDirection.Output)); + Assert.Throws( + () => new ShaderSourceParameter("value", ShaderSourceType.Atomic("void"), ShaderSourceParameterDirection.Output) + ); } - private static ShaderSourceImplementationRequest Request(string id, string source, IShaderSourceResolver? includes = null, - IReadOnlyDictionary? defines = null) - => new(id, C_SC, new(new("Module.ishadersource", source), "Shade", includes ?? new Includes(), defines)); + private static ShaderSourceImplementationRequest Request( + string id, + string source, + IShaderSourceResolver? includes = null, + IReadOnlyDictionary? defines = null + ) => new( + id, + C_SC, + new ShaderSourceRequest(new ShaderSourceFile("Module.ishadersource", source), "Shade", includes ?? new Includes(), defines) + ); - private static string Errors(ShaderSourceModuleAnalysis result) => string.Join("\n", result.diagnostics.Select(static value => value.message)); + private static string Errors(ShaderSourceModuleAnalysis result) + => string.Join("\n", result.diagnostics.Select(static value => value.message)); private sealed class Includes : IShaderSourceResolver { + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => new(include, values.TryGetValue(include, out string? value) ? value : throw new FileNotFoundException(include)); + internal Dictionary values { get; } = new(StringComparer.Ordinal); - public ShaderSourceFile ReadInclude(string includingFile, string include) - => new(include, values.TryGetValue(include, out string? value) ? value : throw new FileNotFoundException(include)); } private sealed class ChangingIncludes : IShaderSourceResolver { private int m_count; - public ShaderSourceFile ReadInclude(string includingFile, string include) - => new(include, ++m_count == 1 ? "#pragma once\nconst float Scale = 1.0;" : "#pragma once\nconst float Scale = 2.0;"); + + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => new(include, ++m_count == 1 ? "#pragma once\nconst float Scale = 1.0;" : "#pragma once\nconst float Scale = 2.0;"); } private sealed class FailingIncludes(Exception failure) : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw failure; + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw failure; } private sealed class AlternateFrontend : IShaderSourceFrontend { internal int calls; internal bool inventedDependency; - public string languageId => "tests.alternate"; + public string languageID => "tests.alternate"; + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) { calls++; - return new(new(request.entryPoint, ShaderSourceType.Atomic("float"), - [new("value", ShaderSourceType.Atomic("float"), ShaderSourceParameterDirection.Input)], new(request.source.assetPath, 1, 1)), - inventedDependency ? ["unread.inc"] : [], []); + return new( + new ShaderSourceFunction( + request.entryPoint, + ShaderSourceType.Atomic("float"), + [new ShaderSourceParameter("value", ShaderSourceType.Atomic("float"), ShaderSourceParameterDirection.Input)], + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ), + inventedDependency ? ["unread.inc"] : [], + [] + ); } } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs index 88caba897..4230338d7 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs @@ -1,43 +1,70 @@ using System.Linq; -using Inno.Core.Graphs; using Xunit; +using Inno.Core.Graphs; namespace Inno.Rendering.Shaders.Tests; public sealed class ShaderSourceNodeDefinitionTests { - private static readonly GraphNodeRecord S_node = new(new GraphNodeId("test-node"), "inno.shader.source"); + private static readonly GraphNodeRecord NODE = new(new GraphNodeID("test-node"), "inno.shader.source"); [Fact] public void FunctionPortsUseSemanticNamesAndInOutCreatesBothDirections() { - var definition = new ShaderSourceNodeDefinition(new("Shade", ShaderSourceType.Atomic("float4"), - [new("uv", ShaderSourceType.Atomic("float2"), ShaderSourceParameterDirection.Input), - new("color", ShaderSourceType.Atomic("float4"), ShaderSourceParameterDirection.InputOutput)], new("source", 1, 1))); - Assert.Equal(["input.uv", "input.color", "output.color", "return"], definition.GetPorts(S_node).Select(static port => port.id.value)); - Assert.Equal(GraphPortCapacity.Multiple, definition.GetPorts(S_node)[2].capacity); - Assert.Same(definition.GetPorts(S_node), definition.GetPorts(S_node)); + var definition = new ShaderSourceNodeDefinition( + new ShaderSourceFunction( + "Shade", + ShaderSourceType.Atomic("float4"), + [ + new ShaderSourceParameter("uv", ShaderSourceType.Atomic("float2"), ShaderSourceParameterDirection.Input), + new ShaderSourceParameter("color", ShaderSourceType.Atomic("float4"), ShaderSourceParameterDirection.InputOutput) + ], + new ShaderSourcePosition("source", 1, 1) + ) + ); + Assert.Equal( + ["input.uv", "input.color", "output.color", "return"], + definition.GetPorts(NODE).Select(static port => port.id.value) + ); + Assert.Equal(GraphPortCapacity.Multiple, definition.GetPorts(NODE)[2].capacity); + Assert.Same(definition.GetPorts(NODE), definition.GetPorts(NODE)); } [Fact] public void AggregatesExposeMembersWithoutDiscardingTheirWholeValuePorts() { - ShaderSourceType aggregate = ShaderSourceType.Structure("Surface", [new("normal", ShaderSourceType.Atomic("float3"))]); - var definition = new ShaderSourceNodeDefinition(new("Shade", aggregate, - [new("surface", aggregate, ShaderSourceParameterDirection.Input)], new("source", 1, 1))); - Assert.Equal(["input.surface", "input.surface.normal", "return", "return.normal"], - definition.GetPorts(S_node).Select(static port => port.id.value)); - Assert.Equal(definition.GetPorts(S_node)[0].valueTypeId, definition.GetPorts(S_node)[2].valueTypeId); + ShaderSourceType aggregate = ShaderSourceType.Structure( + "Surface", + [new ShaderSourceField("normal", ShaderSourceType.Atomic("float3"))] + ); + var definition = new ShaderSourceNodeDefinition( + new ShaderSourceFunction( + "Shade", + aggregate, + [new ShaderSourceParameter("surface", aggregate, ShaderSourceParameterDirection.Input)], + new ShaderSourcePosition("source", 1, 1) + ) + ); + Assert.Equal( + ["input.surface", "input.surface.normal", "return", "return.normal"], + definition.GetPorts(NODE).Select(static port => port.id.value) + ); + Assert.Equal(definition.GetPorts(NODE)[0].valueTypeID, definition.GetPorts(NODE)[2].valueTypeID); } [Fact] public void ArrayLengthsAndStructureLayoutsCannotAliasGraphValueTypes() { - string FirstPortType(ShaderSourceType type) => new ShaderSourceNodeDefinition(new("Shade", type, [], new("source", 1, 1))) - .GetPorts(S_node)[0].valueTypeId; - Assert.NotEqual(FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2)), - FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 3))); - Assert.NotEqual(FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float3"))])), - FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float4"))]))); + string FirstPortType(ShaderSourceType type) + => new ShaderSourceNodeDefinition(new ShaderSourceFunction("Shade", type, [], new ShaderSourcePosition("source", 1, 1))) + .GetPorts(NODE)[0].valueTypeID; + Assert.NotEqual( + FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2)), + FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 3)) + ); + Assert.NotEqual( + FirstPortType(ShaderSourceType.Structure("Surface", [new ShaderSourceField("a", ShaderSourceType.Atomic("float3"))])), + FirstPortType(ShaderSourceType.Structure("Surface", [new ShaderSourceField("a", ShaderSourceType.Atomic("float4"))])) + ); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs index 2b1e315e5..06de0f6ec 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs @@ -1,15 +1,16 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; +using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -22,7 +23,7 @@ public sealed class ShaderTargetTests : IDisposable public ShaderTargetTests() { - m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderTargetTests).Assembly)}); + m_modules = new(new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderTargetTests).Assembly)}); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); m_targets = new(m_types); @@ -31,13 +32,22 @@ public ShaderTargetTests() [Fact] public void IndependentTargetExpandsIntoTheCommonCompilerWithoutMutatingItsSource() { - GraphDocument authored = ShaderGraphDocument.Create(new("Surface", [], [], []), m_serialization, SerializationContext.empty); + GraphDocument authored = ShaderGraphDocument.Create( + new ShaderDefinition("Surface", [], [], []), + m_serialization, + SerializationContext.empty + ); ShaderGraphDocument.SetTarget(authored, "tests.surface-target", m_serialization, SerializationContext.empty); byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); GraphDocument expanded = m_targets.Expand(authored, m_serialization, SerializationContext.empty); using var nodes = new ShaderNodeCompilerRegistry(m_types); - ShaderGraphProgramResult result = new ShaderGraphProgramCompiler(nodes).Lower(expanded, "bgfx", - new Dictionary(), m_serialization, SerializationContext.empty); + ShaderGraphProgramResult result = new ShaderGraphProgramCompiler(nodes).Lower( + expanded, + "bgfx", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); Assert.Contains("tests.surface-target", m_targets.ids); @@ -50,8 +60,12 @@ public void UnavailableTargetPreservesTheAssignedIdentityAndAllAuthoredData() GraphDocument authored = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); ShaderGraphDocument.SetTarget(authored, "tests.unavailable-target", m_serialization, SerializationContext.empty); byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); - Assert.Contains("tests.unavailable-target", Assert.Throws( - () => m_targets.Expand(authored, m_serialization, SerializationContext.empty)).Message); + Assert.Contains( + "tests.unavailable-target", + Assert.Throws( + () => m_targets.Expand(authored, m_serialization, SerializationContext.empty) + ).Message + ); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); } @@ -60,8 +74,12 @@ public void CancellationCannotPublishAnExpansionOrModifyTheSource() { GraphDocument authored = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); - Assert.Throws(() => m_targets.Expand(authored, m_serialization, - SerializationContext.empty, new CancellationToken(true))); + Assert.Throws(() => m_targets.Expand( + authored, + m_serialization, + SerializationContext.empty, + new CancellationToken(true) + )); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); } @@ -73,27 +91,36 @@ public void TemplatesAreDiscoveredByStableIdentityAndCreateIndependentDocuments( GraphDocument first = templates.Create("tests.surface-template", m_serialization, SerializationContext.empty); GraphDocument second = templates.Create("tests.surface-template", m_serialization, SerializationContext.empty); Assert.Equal("tests.surface-target", ShaderGraphDocument.ReadTarget(first, m_serialization, SerializationContext.empty)); - first.RemoveMetadata(ShaderGraphDocument.targetKey); + first.RemoveMetadata(ShaderGraphDocument.C_TARGET_KEY); Assert.Equal("tests.surface-target", ShaderGraphDocument.ReadTarget(second, m_serialization, SerializationContext.empty)); Assert.Throws(() => templates.Create("missing", m_serialization, SerializationContext.empty)); } public void Dispose() - { m_targets.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + { + m_targets.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } [ShaderTarget("tests.surface-target")] public sealed class SurfaceTarget : ShaderTarget { - public override GraphDocument Expand(ShaderTargetContext context, CancellationToken cancellationToken) - => ShaderGraphTemplates.CreateRaster(context.serialization, context.references); + public override GraphDocument Expand( + ShaderTargetContext context, + CancellationToken cancellationToken + ) => ShaderGraphTemplates.CreateRaster(context.serialization, context.references); } [ShaderGraphTemplate("tests.surface-template", "Test Surface")] public sealed class SurfaceTemplate : ShaderGraphTemplate { - public override GraphDocument Create(SerializationRegistry serialization, SerializationContext context) - { - GraphDocument graph = ShaderGraphDocument.Create(new("Surface", [], [], []), serialization, context); + public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context + ) { + GraphDocument graph = ShaderGraphDocument.Create(new ShaderDefinition("Surface", [], [], []), serialization, context); ShaderGraphDocument.SetTarget(graph, "tests.surface-target", serialization, context); return graph; } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs index 574062cdf..582bb1dff 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs @@ -1,4 +1,3 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; using System.Collections.Generic; using System.IO; @@ -6,23 +5,14 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Xunit; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; -public sealed class MetalShaderFactAttribute : FactAttribute -{ - public MetalShaderFactAttribute() - { - if (!OperatingSystem.IsMacOS()) Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; - } -} - [SupportedOSPlatform("macos")] public sealed class ShaderTypedNativeCompilationTests { @@ -30,16 +20,24 @@ public sealed class ShaderTypedNativeCompilationTests public async Task EveryRectangularMatrixShapeSupportsColumnConstructionAndExtraction() { for (int columns = 2; columns <= 4; columns++) + { for (int rows = 2; rows <= 4; rows++) { - var builder = new ShaderIrBuilder(); - ShaderIrValue matrix = builder.Construct(ShaderSourceType.Atomic($"float{columns}x{rows}"), - Enumerable.Range(1, columns * rows).Select(value => builder.Constant((float)value)).ToArray()); + var builder = new ShaderIrBuilder(); + ShaderIrValue matrix = builder.Construct( + ShaderSourceType.Atomic($"float{columns}x{rows}"), + Enumerable.Range(1, columns * rows).Select(value => builder.Constant((float)value)).ToArray() + ); ShaderIrValue product = builder.Binary(ShaderIrOperation.Multiply, matrix, matrix); ShaderIrValue column = builder.Extract(product, columns - 1); ShaderIrValue first = builder.Extract(column, 0); ShaderIrValue last = builder.Extract(column, rows - 1); - AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), first, last, first, builder.Constant(1f))))); + AssertSuccess( + await CompileAsync( + Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), first, last, first, builder.Constant(1f))) + ) + ); + } } } @@ -50,18 +48,30 @@ public async Task OrdinaryArithmeticAndSelectionCompileWithoutSourceModules() ShaderIrValue a = Color(builder, 0.25f); ShaderIrValue value = builder.Binary(ShaderIrOperation.Multiply, a, a); ShaderIrValue selected = builder.Select(builder.Constant(true), value, a); - AssertSuccess(await Compile(Fragment(builder, selected))); + AssertSuccess(await CompileAsync(Fragment(builder, selected))); } [MetalShaderFact] public async Task SameNamedPrivateHelpersAndPublicFunctionsAreIsolatedPerModule() { - ShaderSourceModuleAnalysis first = Module("First.ishadersource", "float Adjust(float value) { return value * 1e-3; } float Shade(float value) { return Adjust(value) + .25; }"); - ShaderSourceModuleAnalysis second = Module("Second.ishadersource", "float Adjust(float value) { return value * 2.0; } float Shade(float value) { uint bits = 0xFE+1u; bits <<= 1u; return Adjust(value) + float(bits) * 0.0; }"); + ShaderSourceModuleAnalysis first = Module( + "First.ishadersource", + "float Adjust(float value) { return value * 1e-3; } float Shade(float value) { return Adjust(value) + .25; }" + ); + ShaderSourceModuleAnalysis second = Module( + "Second.ishadersource", + "float Adjust(float value) { return value * 2.0; } float Shade(float value) { uint bits = 0xFE+1u; bits <<= 1u; return Adjust(value) + float(bits) * 0.0; }" + ); var builder = new ShaderIrBuilder(); - ShaderIrValue a = builder.Call(first, "metal", new Dictionary { ["value"] = builder.Constant(0.5f) })["return"]; + ShaderIrValue a = builder.Call( + first, + "metal", + new Dictionary { ["value"] = builder.Constant(0.5f) } + )["return"]; ShaderIrValue b = builder.Call(second, "metal", new Dictionary { ["value"] = a })["return"]; - AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f))))); + AssertSuccess( + await CompileAsync(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f)))) + ); } [MetalShaderFact] @@ -78,27 +88,54 @@ Surface Shade(Surface value, float weights[2], out float alpha, inout vec2 uv) { ShaderSourceType surfaceType = module.function!.returnType; ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0.2f), builder.Constant(0.4f)); ShaderIrValue surface = builder.Construct(surfaceType, uv, builder.Constant(0.5f)); - ShaderIrValue weights = builder.Construct(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2), builder.Constant(0.5f), builder.Constant(1f)); + ShaderIrValue weights = builder.Construct( + ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2), + builder.Constant(0.5f), + builder.Constant(1f) + ); IReadOnlyDictionary values = builder.Call(module, "metal", new Dictionary - { ["value"] = surface, ["weights"] = weights, ["uv"] = uv }); + { + ["value"] = surface, + ["weights"] = weights, + ["uv"] = uv + }); ShaderIrValue result = builder.Extract(values["return"], 1); - ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), result, builder.Extract(values["output.uv"], 0), result, values["output.alpha"]); - AssertSuccess(await Compile(Fragment(builder, color))); + ShaderIrValue color = builder.Construct( + ShaderSourceType.Atomic("float4"), + result, + builder.Extract(values["output.uv"], 0), + result, + values["output.alpha"] + ); + AssertSuccess(await CompileAsync(Fragment(builder, color))); } [MetalShaderFact] public async Task SampledTextureAndUniformBindingsAreReturnedWithTheBinary() { - ShaderSourceModuleAnalysis module = Module("Sample.ishadersource", "vec4 Shade(sampler2D image, vec2 uv, vec4 tint) { return texture2D(image, uv) * tint; }"); + ShaderSourceModuleAnalysis module = Module( + "Sample.ishadersource", + "vec4 Shade(sampler2D image, vec2 uv, vec4 tint) { return texture2D(image, uv) * tint; }" + ); var builder = new ShaderIrBuilder(); ShaderIrValue image = builder.Input("texture-id", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrValue tint = builder.Input("tint-id", ShaderSourceType.Atomic("float4")); ShaderIrValue uv = builder.Input("uv-id", ShaderSourceType.Atomic("float2")); - ShaderIrValue color = builder.Call(module, "metal", new Dictionary { ["image"] = image, ["uv"] = uv, ["tint"] = tint })["return"]; - ShaderIrStage stage = Fragment(builder, color, - [new("texture-id", image.type, ShaderIrInputKind.SampledTexture, location: 3), - new("tint-id", tint.type, ShaderIrInputKind.Uniform), new("uv-id", uv.type, ShaderIrInputKind.Varying, "texcoord")]); - ShaderStageToolResult result = await Compile(stage); + ShaderIrValue color = builder.Call( + module, + "metal", + new Dictionary { ["image"] = image, ["uv"] = uv, ["tint"] = tint } + )["return"]; + ShaderIrStage stage = Fragment( + builder, + color, + [ + new ShaderIrStageInput("texture-id", image.type, ShaderIrInputKind.SampledTexture, location: 3), + new ShaderIrStageInput("tint-id", tint.type, ShaderIrInputKind.Uniform), + new ShaderIrStageInput("uv-id", uv.type, ShaderIrInputKind.Varying, "texcoord") + ] + ); + ShaderStageToolResult result = await CompileAsync(stage); AssertSuccess(result); Assert.Equal(2, result.bindings.Count); Assert.Equal(3, result.bindings.Single(binding => binding.id == "texture-id").location); @@ -116,16 +153,38 @@ public async Task VertexInstanceInputAndMrtFragmentCompileAsTypedStages() ShaderIrValue instance = vertex.Input("instance", ShaderSourceType.Atomic("float4")); ShaderIrValue clip = vertex.Binary(ShaderIrOperation.Add, position, instance); ShaderIrBlock vertexBody = vertex.Build(new Dictionary { ["clip"] = clip, ["color"] = instance }); - AssertSuccess(await Compile(new(ShaderStage.Vertex, vertexBody, - [new("position", position.type, ShaderIrInputKind.VertexAttribute, "position"), - new("instance", instance.type, ShaderIrInputKind.VertexAttribute, "instance-data")], - [new("clip", ShaderIrOutputKind.ClipPosition), new("color", ShaderIrOutputKind.Varying, "color")]))); + AssertSuccess( + await CompileAsync( + new ShaderIrStage( + ShaderStage.Vertex, + vertexBody, + [ + new ShaderIrStageInput("position", position.type, ShaderIrInputKind.VertexAttribute, "position"), + new ShaderIrStageInput("instance", instance.type, ShaderIrInputKind.VertexAttribute, "instance-data") + ], + [ + new ShaderIrStageOutput("clip", ShaderIrOutputKind.ClipPosition), + new ShaderIrStageOutput("color", ShaderIrOutputKind.Varying, "color") + ] + ) + ) + ); var fragment = new ShaderIrBuilder(); ShaderIrValue color = fragment.Input("color", ShaderSourceType.Atomic("float4")); ShaderIrBlock fragmentBody = fragment.Build(new Dictionary { ["base"] = color, ["emission"] = color }); - AssertSuccess(await Compile(new(ShaderStage.Fragment, fragmentBody, - [new("color", color.type, ShaderIrInputKind.Varying, "color")], - [new("base", ShaderIrOutputKind.Color), new("emission", ShaderIrOutputKind.Color, location: 1)]))); + AssertSuccess( + await CompileAsync( + new ShaderIrStage( + ShaderStage.Fragment, + fragmentBody, + [new ShaderIrStageInput("color", color.type, ShaderIrInputKind.Varying, "color")], + [ + new ShaderIrStageOutput("base", ShaderIrOutputKind.Color), + new ShaderIrStageOutput("emission", ShaderIrOutputKind.Color, location: 1) + ] + ) + ) + ); } [MetalShaderFact] @@ -135,37 +194,68 @@ public async Task ComputeEntryAndWorkgroupAreGeneratedNotSuppliedByTheSourceModu ShaderIrValue id = builder.Input("invocation", ShaderSourceType.Atomic("uint3")); ShaderSourceModuleAnalysis module = Module("Compute.ishadersource", "void Shade(uvec3 gid) { if (gid.x > 0u) return; }"); _ = builder.Call(module, "metal", new Dictionary { ["gid"] = id }); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("invocation", id.type, ShaderIrInputKind.Builtin, "global-invocation-id")], [], 8, 4, 1); - AssertSuccess(await Compile(stage)); - ShaderStageToolResult unsupported = await Compile(stage, GraphicsCapability.None); + var stage = new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new ShaderIrStageInput("invocation", id.type, ShaderIrInputKind.Builtin, "global-invocation-id")], + [], + 8, + 4, + 1 + ); + AssertSuccess(await CompileAsync(stage)); + ShaderStageToolResult unsupported = await CompileAsync(stage, GraphicsCapability.None); Assert.False(unsupported.succeeded); - Assert.Contains(unsupported.diagnostics, diagnostic => diagnostic.code == "BGFX_IR_GENERATION" && diagnostic.message.Contains("Compute", StringComparison.Ordinal)); + Assert.Contains( + unsupported.diagnostics, + diagnostic => diagnostic.code == "BGFX_IR_GENERATION" && diagnostic.message.Contains("Compute", StringComparison.Ordinal) + ); } [MetalShaderFact] public async Task InvalidNativeFunctionBodyCannotPublishAStageBinary() { - ShaderSourceModuleAnalysis module = Module("Broken.ishadersource", "float Shade(float value) { return ThisFunctionDoesNotExist(value); }"); + ShaderSourceModuleAnalysis module = Module( + "Broken.ishadersource", + "float Shade(float value) { return ThisFunctionDoesNotExist(value); }" + ); var builder = new ShaderIrBuilder(); - ShaderIrValue value = builder.Call(module, "metal", new Dictionary { ["value"] = builder.Constant(1f) })["return"]; - ShaderStageToolResult result = await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value))); + ShaderIrValue value = builder.Call( + module, + "metal", + new Dictionary { ["value"] = builder.Constant(1f) } + )["return"]; + ShaderStageToolResult result = await CompileAsync( + Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value)) + ); Assert.False(result.succeeded); Assert.Empty(result.bytes.ToArray()); Assert.Contains(result.diagnostics, diagnostic => diagnostic.severity == DiagnosticSeverity.Error); - Assert.True(result.diagnostics.Any(diagnostic => diagnostic.location.assetPath.Contains("Broken.ishadersource", StringComparison.Ordinal)), - string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); + Assert.True( + result.diagnostics.Any(diagnostic => diagnostic.location.assetPath.Contains("Broken.ishadersource", StringComparison.Ordinal)), + string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); } [MetalShaderFact] public async Task IncludeAliasesCompileFromFrozenSnapshotsAfterTheOwnerResolverIsGone() { var resolver = new AliasedInclude(); - ShaderSourceModuleAnalysis module = Module("Include.ishadersource", "#include \"@library/math\"\nfloat Shade(float value) { return Scale(value); }", resolver); + ShaderSourceModuleAnalysis module = Module( + "Include.ishadersource", + "#include \"@library/math\"\nfloat Shade(float value) { return Scale(value); }", + resolver + ); resolver.available = false; var builder = new ShaderIrBuilder(); - ShaderIrValue value = builder.Call(module, "metal", new Dictionary { ["value"] = builder.Constant(1f) })["return"]; - AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value)))); + ShaderIrValue value = builder.Call( + module, + "metal", + new Dictionary { ["value"] = builder.Constant(1f) } + )["return"]; + AssertSuccess( + await CompileAsync(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value))) + ); Assert.Single(module.implementations[0].includes); Assert.Equal("plugin:library/scale.ishadersource", module.implementations[0].includes[0].resolvedPath); } @@ -175,40 +265,70 @@ public async Task CancellationIsPreservedBeforeStartingNativeCompilation() { var builder = new ShaderIrBuilder(); ShaderIrStage stage = Fragment(builder, Color(builder, 1f)); - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var target = toolchain.CreateTarget(Capabilities(GraphicsCapability.None)); + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); + ShaderCompileTarget target = toolchain.CreateTarget(Capabilities(GraphicsCapability.None)); await Assert.ThrowsAnyAsync(async () => await toolchain.CompileAsync(new ShaderStageToolRequest(stage, target), new CancellationToken(true))); } - private static ShaderIrValue Color(ShaderIrBuilder builder, float value) - { + private static ShaderIrValue Color( + ShaderIrBuilder builder, + float value + ) { ShaderIrValue scalar = builder.Constant(value); return builder.Construct(ShaderSourceType.Atomic("float4"), scalar, scalar, scalar, scalar); } - private static ShaderIrStage Fragment(ShaderIrBuilder builder, ShaderIrValue color, ShaderIrStageInput[]? inputs = null) - => new(ShaderStage.Fragment, builder.Build(new Dictionary { ["color"] = color }), inputs ?? [], [new("color", ShaderIrOutputKind.Color)]); + private static ShaderIrStage Fragment( + ShaderIrBuilder builder, + ShaderIrValue color, + ShaderIrStageInput[]? inputs = null + ) => new( + ShaderStage.Fragment, + builder.Build(new Dictionary { ["color"] = color }), + inputs ?? [], + [new ShaderIrStageOutput("color", ShaderIrOutputKind.Color)] + ); - private static ShaderSourceModuleAnalysis Module(string path, string source, IShaderSourceResolver? resolver = null) - { + private static ShaderSourceModuleAnalysis Module( + string path, + string source, + IShaderSourceResolver? resolver = null + ) { ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( - [new("metal", "inno.shader-language.bgfx-sc", new(new(path, source), "Shade", resolver ?? new AliasedInclude()))]); + [new ShaderSourceImplementationRequest( + "metal", + "inno.shader-language.bgfx-sc", + new ShaderSourceRequest(new ShaderSourceFile(path, source), "Shade", resolver ?? new AliasedInclude()) + )] + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); return result; } - private static async Task Compile(ShaderIrStage stage, - GraphicsCapability capabilities = GraphicsCapability.Compute | GraphicsCapability.Instancing | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D) - { - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); + private static async Task CompileAsync( + ShaderIrStage stage, + GraphicsCapability capabilities = GraphicsCapability.Compute + | GraphicsCapability.Instancing + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Texture3D + ) { + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); return await compiler.CompileAsync(stage, compiler.CreateTarget(Capabilities(capabilities))); } private static GraphicsCapabilities Capabilities(GraphicsCapability features) - => new(GraphicsApi.Metal, features, new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), originBottomLeft: false, homogeneousDepth: false); + => new( + GraphicsApi.metal, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + originBottomLeft: false, + homogeneousDepth: false + ); private static void AssertSuccess(ShaderStageToolResult result) => Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); @@ -216,8 +336,12 @@ private static void AssertSuccess(ShaderStageToolResult result) private sealed class AliasedInclude : IShaderSourceResolver { internal bool available = true; - public ShaderSourceFile ReadInclude(string includingFile, string include) - => available && include == "@library/math" ? new("plugin:library/scale.ishadersource", "float Scale(float value) { return value * 2.0; }") - : throw new FileNotFoundException(include); + + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => available && include == "@library/math" + ? new ShaderSourceFile("plugin:library/scale.ishadersource", "float Scale(float value) { return value * 2.0; }") + : throw new FileNotFoundException(include); } } diff --git a/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs b/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs index 9e5d14dbf..28fb88a45 100644 --- a/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -17,11 +17,27 @@ public void CustomBackendIdentityCanFlowThroughDeviceCapabilities() Assert.Throws(() => new GraphicsApi("..")); Assert.False(GraphicsApi.TryParse("../other", out _)); Assert.Throws(() => new GraphicsCapabilities( - default, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false)); + default, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + )); var capabilities = new GraphicsCapabilities( - api, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false); + api, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); Assert.Equal(api, capabilities.backend); } } diff --git a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs index 47bf3bab6..9ee970650 100644 --- a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs @@ -12,11 +12,28 @@ public void DeviceProgramRoundTripPreservesBinariesBindingsAndRasterWithoutAutho { byte[] vertex = [1, 2, 3]; byte[] fragment = [4, 5]; - var raster = new RenderRasterState(RenderCullMode.None, RenderFrontFace.CounterClockwise, - RenderDepthCompare.Always, false, RenderBlendState.premultiplied, 0xF, true, RenderPrimitiveTopology.TriangleList); - var descriptor = new GraphicsPipelineDescriptor(vertex, fragment, - [new RenderShaderBindingDescriptor(new RenderBindingId("s_tex"), RenderShaderBindingKind.Texture, - slot: 3, nativeName: "native_sampler")], null, raster); + var raster = new RenderRasterState( + RenderCullMode.None, + RenderFrontFace.CounterClockwise, + RenderDepthCompare.Always, + false, + RenderBlendState.premultiplied, + 0xF, + true, + RenderPrimitiveTopology.TriangleList + ); + var descriptor = new GraphicsPipelineDescriptor( + vertex, + fragment, + [new RenderShaderBindingDescriptor( + new RenderBindingID("s_tex"), + RenderShaderBindingKind.Texture, + slot: 3, + nativeName: "native_sampler" + )], + null, + raster + ); byte[] bytes = GraphicsProgramArtifactCodec.Encode(descriptor); Assert.Equal(bytes, GraphicsProgramArtifactCodec.Encode(descriptor)); GraphicsPipelineDescriptor decoded = GraphicsProgramArtifactCodec.Decode(bytes); @@ -39,13 +56,17 @@ [new RenderShaderBindingDescriptor(new RenderBindingId("s_tex"), RenderShaderBin public void InvalidBindingAndRasterValuesCannotBeEncodedAsValidArtifacts() { Assert.Throws(() => new RenderShaderBindingDescriptor( - new("invalid"), RenderShaderBindingKind.Uniform, uniformType: (RenderUniformType)99)); + new RenderBindingID("invalid"), + RenderShaderBindingKind.Uniform, + uniformType: (RenderUniformType)99 + )); var invalidRaster = new RenderRasterState { colorWriteMask = 0xFF }; var descriptor = new GraphicsPipelineDescriptor([1], [2], [], null, invalidRaster); Assert.Throws(() => GraphicsProgramArtifactCodec.Encode(descriptor)); var invalidBlend = new RenderRasterState { blend = new RenderBlendState { colorSource = (RenderBlendFactor)99 } }; Assert.Throws(() => GraphicsProgramArtifactCodec.Encode( - new GraphicsPipelineDescriptor([1], [2], [], null, invalidBlend))); + new GraphicsPipelineDescriptor([1], [2], [], null, invalidBlend) + )); } [Fact] @@ -53,14 +74,16 @@ public void TruncationOversizedFieldsBadHeadersAndTrailingBytesFailBeforePublica { byte[] bytes = GraphicsProgramArtifactCodec.Encode(new GraphicsPipelineDescriptor([1], [2], [], null)); for (int length = 0; length < bytes.Length; length++) + { Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(bytes.AsSpan(0, length))); + } byte[] excessive = (byte[])bytes.Clone(); BinaryPrimitives.WriteInt32LittleEndian(excessive.AsSpan("INNOGPU"u8.Length), int.MaxValue); Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(excessive)); byte[] header = (byte[])bytes.Clone(); header[0] = 0; Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(header)); - byte[] trailing = new byte[bytes.Length + 1]; + var trailing = new byte[bytes.Length + 1]; bytes.CopyTo(trailing, 0); Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(trailing)); } diff --git a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs index 4b9eb9daf..e2f018de8 100644 --- a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -12,8 +12,12 @@ public sealed class ParallelCommandRecordingTests public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() { RenderGraphBuilder builder = CreateGraph(); - var texture = new RenderTextureDescriptor(32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled | RenderTextureUsage.ColorAttachment); + var texture = new RenderTextureDescriptor( + 32, + 32, + RenderTextureFormat.RGBA8, + RenderTextureUsage.Sampled | RenderTextureUsage.ColorAttachment + ); var buffer = new RenderBufferDescriptor(32, 16, RenderBufferUsage.Vertex | RenderBufferUsage.Storage); var data = new CommandInputs { @@ -22,11 +26,16 @@ public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() buffer = builder.ImportBuffer("buffer", DeviceHandles.buffer, buffer), otherBuffer = builder.ImportBuffer("other-buffer", DeviceHandles.otherBuffer, buffer) }; - builder.AddRasterPass("Commands", new RenderPhaseId("tests.commands"), data, - static ( - inputs, - context - ) => IssueCommands(inputs, context.commands)) + builder + .AddRasterPass( + "Commands", + new RenderPhaseID("tests.commands"), + data, + static ( + inputs, + context + ) => IssueCommands(inputs, context.commands) + ) .AllowParallelRecording() .ReadTexture(data.source) .ReadTexture(data.destination) @@ -53,7 +62,9 @@ public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() graph.Execute(backend, 43); Assert.Equal(expected.calls.Count, backend.encoder.calls.Count); for (int index = 0; index < expected.calls.Count; index++) + { Assert.Equal(expected.calls[index].arguments, backend.encoder.calls[index].arguments); + } } [Theory] @@ -69,20 +80,26 @@ public void RecordedReferencesAreReleasedOnEveryExecutionExit(string phase) { RenderGraphBuilder builder = CreateGraph(); var data = new ReferenceInputs(phase); - builder.AddRasterPass("Lifetime", new RenderPhaseId("tests.lifetime"), data, RecordReferences) + builder.AddRasterPass("Lifetime", new RenderPhaseID("tests.lifetime"), data, RecordReferences) .AllowParallelRecording() .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; var backend = new ProbeBackend(phase, capture: false); if (phase == "success") + { graph.Execute(backend, 1); + } else { Exception failure = Assert.ThrowsAny(() => graph.Execute(backend, 1)); foreach (string expected in phase.Split(',')) + { Assert.Contains(expected, failure.ToString(), StringComparison.Ordinal); + } if (phase.Contains(',', StringComparison.Ordinal)) + { Assert.Equal(phase.Split(',').Length, Assert.IsType(failure).Flatten().InnerExceptions.Count); + } } Assert.True(backend.ended); @@ -96,28 +113,40 @@ public void RecordedReferencesAreReleasedOnEveryExecutionExit(string phase) GC.KeepAlive(data.borrowedCommands); } - private static RenderGraphBuilder CreateGraph() => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, - GraphicsCapability.Compute | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture, - new GraphicsLimits(16, 8, 16384, 16), - [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - originBottomLeft: false, homogeneousDepth: false)); + private static RenderGraphBuilder CreateGraph() + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.noop, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture, + new GraphicsLimits(16, 8, 16_384, 16), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + originBottomLeft: false, + homogeneousDepth: false + ) + ); private static void IssueCommands( CommandInputs data, RenderCommandEncoder commands ) { - var binding = new RenderBindingId("weights.\u03b1"); + var binding = new RenderBindingID("weights.\u03b1"); for (int index = 0; index < 64; index++) { - byte[] uniform = new byte[4097]; + var uniform = new byte[4097]; for (int offset = 0; offset < uniform.Length; offset++) + { uniform[offset] = unchecked((byte)(offset + index)); - float[] transform = new float[16]; + } + var transform = new float[16]; for (int element = 0; element < transform.Length; element++) + { transform[element] = index + element * 0.25f; - var sampler = RenderSamplerState.linearClamp; + } + RenderSamplerState sampler = RenderSamplerState.linearClamp; var sourceRegion = new RenderTextureRegion(0, 1, 2, 0, 3, 4); var destinationRegion = new RenderTextureRegion(0, 5, 6, 0, 3, 4); commands.BindGraphicsPipeline(DeviceHandles.graphics); @@ -167,19 +196,23 @@ RenderPassContext context data.borrowedCommands = context.commands; context.commands.SetRasterState(state); for (int index = 0; index < 32; index++) - context.commands.SetUniform(new RenderBindingId("lifetime"), new byte[257]); + { + context.commands.SetUniform(new RenderBindingID("lifetime"), new byte[257]); + } if (data.phase.Contains("record", StringComparison.Ordinal)) + { throw new InvalidOperationException("record"); + } } private sealed class CommandInputs { + internal readonly RenderRasterState raster = new(); + internal readonly RenderStencilState stencil = new(); internal RenderTextureHandle source; internal RenderTextureHandle destination; internal RenderBufferHandle buffer; internal RenderBufferHandle otherBuffer; - internal readonly RenderRasterState raster = new(); - internal readonly RenderStencilState stencil = new(); } private sealed class ReferenceInputs(string phase) @@ -191,12 +224,12 @@ private sealed class ReferenceInputs(string phase) private sealed class DeviceHandles : RenderDevice { - internal static GraphicsPipelineHandle graphics => CreateGraphicsPipelineHandle(0x123456789, 7); - internal static ComputePipelineHandle compute => CreateComputePipelineHandle(0x987654321, 7); - internal static PersistentTextureHandle texture => CreatePersistentTextureHandle(0x123456781, 7); - internal static PersistentTextureHandle otherTexture => CreatePersistentTextureHandle(0x123456782, 7); - internal static PersistentBufferHandle buffer => CreatePersistentBufferHandle(0x123456783, 7); - internal static PersistentBufferHandle otherBuffer => CreatePersistentBufferHandle(0x123456784, 7); + internal static GraphicsPipelineHandle graphics => CreateGraphicsPipelineHandle(0x1_2345_6789, 7); + internal static ComputePipelineHandle compute => CreateComputePipelineHandle(0x9_8765_4321, 7); + internal static PersistentTextureHandle texture => CreatePersistentTextureHandle(0x1_2345_6781, 7); + internal static PersistentTextureHandle otherTexture => CreatePersistentTextureHandle(0x1_2345_6782, 7); + internal static PersistentBufferHandle buffer => CreatePersistentBufferHandle(0x1_2345_6783, 7); + internal static PersistentBufferHandle otherBuffer => CreatePersistentBufferHandle(0x1_2345_6784, 7); } private sealed class ProbeBackend : IRenderGraphBackend @@ -210,29 +243,35 @@ internal ProbeBackend( bool capture = true ) { m_phase = phase; - encoder = new ProbeEncoder(phase, capture); + this.encoder = new ProbeEncoder(phase, capture); } - public void BeginGraph(CompiledRenderGraph graph) { } + public void BeginGraph(CompiledRenderGraph graph) {} public RenderCommandEncoder BeginPass(CompiledRenderPass pass) { if (m_phase == "begin-pass") + { throw new InvalidOperationException(m_phase); + } return encoder; } public void EndPass(CompiledRenderPass pass) { if (m_phase.Contains("end-pass", StringComparison.Ordinal)) + { throw new InvalidOperationException("end-pass"); + } } public void EndGraph(CompiledRenderGraph graph) { ended = true; if (m_phase.Contains("end-graph", StringComparison.Ordinal)) + { throw new InvalidOperationException("end-graph"); + } } } @@ -256,45 +295,46 @@ internal ProbeEncoder( public override void BindComputePipeline(ComputePipelineHandle pipeline) => Record("BindComputePipeline", pipeline); public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, RenderSamplerState sampler ) => Record("BindTextureGraph", binding, texture, sampler); public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, RenderSamplerState sampler ) => Record("BindTexturePersistent", binding, texture, sampler); public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, int mipLevel = 0 ) => Record("BindStorageTextureGraph", binding, texture, mipLevel); public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, int mipLevel = 0 ) => Record("BindStorageTexturePersistent", binding, texture, mipLevel); public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, RenderBufferHandle buffer ) => Record("BindBufferGraph", binding, buffer); public override void BindBuffer( - RenderBindingId binding, + RenderBindingID binding, PersistentBufferHandle buffer ) => Record("BindBufferPersistent", binding, buffer); public override void SetUniform( - RenderBindingId binding, + RenderBindingID binding, ReadOnlySpan value ) => Record("SetUniform", binding, Convert.ToHexString(value)); - public override void SetTransform(ReadOnlySpan columnMajorMatrix) => Record("SetTransform", Convert.ToHexString(MemoryMarshal.AsBytes(columnMajorMatrix))); + public override void SetTransform(ReadOnlySpan columnMajorMatrix) + => Record("SetTransform", Convert.ToHexString(MemoryMarshal.AsBytes(columnMajorMatrix))); public override void SetRasterState(RenderRasterState state) => Record("SetRasterState", state); @@ -413,9 +453,13 @@ private void Record( params object?[] arguments ) { if (m_phase.Contains("replay", StringComparison.Ordinal)) + { throw new InvalidOperationException("replay"); + } if (m_capture) + { calls.Add(new ObservedCommand(operation, arguments)); + } } } diff --git a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs index 7faee8848..b1d7cb6bb 100644 --- a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs @@ -1,7 +1,8 @@ using System; +using System.Collections.Generic; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -10,16 +11,26 @@ public sealed class PipelineResourceTests [Fact] public void PipelineBindingSnapshotsRejectMutationOfPublishedStorage() { - var binding = new RenderShaderBindingDescriptor(new RenderBindingId("original"), RenderShaderBindingKind.Uniform); - var changed = new RenderShaderBindingDescriptor(new RenderBindingId("changed"), RenderShaderBindingKind.Uniform); + var binding = new RenderShaderBindingDescriptor( + new RenderBindingID("original"), + RenderShaderBindingKind.Uniform + ); + var changed = new RenderShaderBindingDescriptor( + new RenderBindingID("changed"), + RenderShaderBindingKind.Uniform + ); RenderShaderBindingDescriptor[] input = [binding]; var graphics = new GraphicsPipelineDescriptor([1], [2], input, null); var compute = new ComputePipelineDescriptor([1], input); input[0] = changed; Assert.Same(binding, graphics.bindings[0]); Assert.Same(binding, compute.bindings[0]); - Assert.Throws(() => ((System.Collections.Generic.IList)graphics.bindings)[0] = changed); - Assert.Throws(() => ((System.Collections.Generic.IList)compute.bindings)[0] = changed); + Assert.Throws( + () => ((IList)graphics.bindings)[0] = changed + ); + Assert.Throws( + () => ((IList)compute.bindings)[0] = changed + ); } [Fact] @@ -28,40 +39,40 @@ public void VertexLayoutAcceptsAllPortableSemanticChannels() RenderVertexSemantic[] semantics = Enum.GetValues(); var layout = new RenderVertexLayout( semantics.Select(static semantic => - new RenderVertexAttribute(semantic, RenderVertexFormat.Float4)).ToArray()); + new RenderVertexAttribute(semantic, RenderVertexFormat.Float4)).ToArray() + ); Assert.Equal(semantics.Length, layout.attributes.Count); Assert.Equal(semantics.Length * 16, layout.stride); - Assert.Throws(() => - ((System.Collections.Generic.IList)layout.attributes)[0] = default); + Assert.Throws(() => ((IList)layout.attributes)[0] = default); } [Fact] - public void VertexLayout_RejectsDuplicateSemantic() - { - Assert.Throws(() => new RenderVertexLayout( + public void VertexLayoutRejectsDuplicateSemantic() => Assert.Throws(() => new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3), new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2) - ])); - } + ] + )); [Fact] - public void VertexLayout_PreservesExplicitOffsetsAndTrailingPadding() + public void VertexLayoutPreservesExplicitOffsetsAndTrailingPadding() { var layout = new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16), - new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Half2) - ], stride: 32); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Half2) + ], + stride: 32 + ); Assert.Equal([0, 16, 20], layout.attributes.Select(static attribute => attribute.byteOffset)); Assert.Equal(32, layout.stride); } [Fact] - public void VertexLayoutEquality_IncludesTrailingStride() + public void VertexLayoutEqualityIncludesTrailingStride() { RenderVertexAttribute[] attributes = [ @@ -75,33 +86,37 @@ public void VertexLayoutEquality_IncludesTrailingStride() } [Fact] - public void VertexLayout_RejectsOverlappingAttributesAndShortStride() + public void VertexLayoutRejectsOverlappingAttributesAndShortStride() { Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 8) - ])); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 8) + ] + )); Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ], stride: 8)); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ], + stride: 8 + )); } [Fact] - public void PersistentVertexBuffer_RequiresMatchingLayout() + public void PersistentVertexBufferRequiresMatchingLayout() { - RenderBufferDescriptor buffer = new(3, 12, RenderBufferUsage.Vertex); - RenderVertexLayout mismatched = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float4) - ]); + var buffer = new RenderBufferDescriptor(3, 12, RenderBufferUsage.Vertex); + var mismatched = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float4) + ] + ); Assert.Throws(() => new PersistentBufferDescriptor(buffer, mismatched)); } [Fact] - public void TextureDescriptor_ModelsVolumeAndCubemapSubresourcesWithoutBackendTypes() + public void TextureDescriptorModelsVolumeAndCubemapSubresourcesWithoutBackendTypes() { var volume = new RenderTextureDescriptor( 16, @@ -110,37 +125,36 @@ public void TextureDescriptor_ModelsVolumeAndCubemapSubresourcesWithoutBackendTy RenderTextureUsage.Sampled, mipCount: 3, dimension: RenderTextureDimension.Texture3D, - depth: 8); + depth: 8 + ); var cubemapArray = new RenderTextureDescriptor( 32, 32, RenderTextureFormat.RGBA16Float, RenderTextureUsage.Sampled, arrayLayers: 2, - dimension: RenderTextureDimension.Cube); + dimension: RenderTextureDimension.Cube + ); Assert.Equal(8, volume.GetSubresourceLayerCount(0)); Assert.Equal(2, volume.GetSubresourceLayerCount(2)); Assert.Equal(12, cubemapArray.GetSubresourceLayerCount(0)); Assert.NotEqual( volume, - new RenderTextureDescriptor( - 16, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled, - mipCount: 3)); + new RenderTextureDescriptor(16, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, mipCount: 3) + ); } [Fact] - public void TextureDescriptor_RejectsContradictoryDimensions() + public void TextureDescriptorRejectsContradictoryDimensions() { Assert.Throws(() => new RenderTextureDescriptor( 16, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, - dimension: RenderTextureDimension.Cube)); + dimension: RenderTextureDimension.Cube + )); Assert.Throws(() => new RenderTextureDescriptor( 16, 16, @@ -148,7 +162,8 @@ public void TextureDescriptor_RejectsContradictoryDimensions() RenderTextureUsage.Sampled, arrayLayers: 2, dimension: RenderTextureDimension.Texture3D, - depth: 4)); + depth: 4 + )); Assert.Throws(() => new RenderTextureDescriptor( 16, 16, @@ -156,7 +171,8 @@ public void TextureDescriptor_RejectsContradictoryDimensions() RenderTextureUsage.Sampled, sampleCount: 4, dimension: RenderTextureDimension.Texture3D, - depth: 4)); + depth: 4 + )); } [Fact] @@ -171,14 +187,14 @@ public void BlendStateSupportsSeparateColorAlphaEquationsAndConstantFactors() alphaSource = RenderBlendFactor.One, alphaDestination = RenderBlendFactor.DestinationAlpha, alphaEquation = RenderBlendEquation.Maximum, - constantRgba = 0x80402010, + constantRgba = 0x8040_2010, alphaToCoverage = true }; var raster = new RenderRasterState { blend = blend }; Assert.Equal(RenderBlendFactor.Constant, raster.blend.colorSource); Assert.Equal(RenderBlendEquation.Maximum, raster.blend.alphaEquation); - Assert.Equal(0x80402010u, raster.blend.constantRgba); + Assert.Equal(0x8040_2010u, raster.blend.constantRgba); Assert.True(raster.blend.alphaToCoverage); } @@ -189,14 +205,9 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration RenderStencilCompare.NotEqual, RenderStencilOperation.Zero, RenderStencilOperation.IncrementWrap, - RenderStencilOperation.Replace); - var stencil = new RenderStencilState( - true, - 7, - 0x7f, - 0x3f, - face, - face); + RenderStencilOperation.Replace + ); + var stencil = new RenderStencilState(true, 7, 0x7F, 0x3F, face, face); var raster = new RenderRasterState( RenderCullMode.Front, RenderFrontFace.Clockwise, @@ -205,12 +216,13 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration RenderBlendState.premultiplied, 0x07, false, - RenderPrimitiveTopology.LineList); + RenderPrimitiveTopology.LineList + ); Assert.True(stencil.enabled); Assert.Equal((byte)7, stencil.reference); - Assert.Equal((byte)0x7f, stencil.readMask); - Assert.Equal((byte)0x3f, stencil.writeMask); + Assert.Equal((byte)0x7F, stencil.readMask); + Assert.Equal((byte)0x3F, stencil.writeMask); Assert.Equal(RenderStencilCompare.NotEqual, stencil.front.compare); Assert.Equal(RenderStencilOperation.Replace, stencil.back.pass); Assert.Equal(RenderCullMode.Front, raster.cull); @@ -224,21 +236,20 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration } [Fact] - public void ShaderBinding_RejectsDefaultIdentifier() - { - Assert.Throws(() => new RenderShaderBindingDescriptor( - default, - RenderShaderBindingKind.Uniform)); - } + public void ShaderBindingRejectsDefaultIdentifier() => Assert.Throws(() => new RenderShaderBindingDescriptor( + default, + RenderShaderBindingKind.Uniform + )); [Fact] - public void ShaderBinding_ModelsStorageTextureAccessWithoutBackendTypes() + public void ShaderBindingModelsStorageTextureAccessWithoutBackendTypes() { var binding = new RenderShaderBindingDescriptor( - new RenderBindingId("u_output"), + new RenderBindingID("u_output"), RenderShaderBindingKind.StorageTexture, slot: 3, - storageAccess: RenderStorageAccess.ReadWrite); + storageAccess: RenderStorageAccess.ReadWrite + ); Assert.Equal(RenderShaderBindingKind.StorageTexture, binding.kind); Assert.Equal(RenderStorageAccess.ReadWrite, binding.storageAccess); diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs index 5bb8a386c..3abeac302 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs @@ -2,18 +2,18 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; public sealed class RenderGraphCompilerTests { - private static readonly RenderPhaseId C_GEOMETRY = new("tests.geometry"); - private static readonly RenderPhaseId C_PROCESS = new("tests.process"); - private static readonly RenderPhaseId C_TRANSPARENT = new("tests.transparent"); - private static readonly RenderPhaseId C_POST = new("tests.post"); - private static readonly RenderPhaseId C_FINAL = new("tests.final"); + private static readonly RenderPhaseID GEOMETRY = new("tests.geometry"); + private static readonly RenderPhaseID PROCESS = new("tests.process"); + private static readonly RenderPhaseID TRANSPARENT = new("tests.transparent"); + private static readonly RenderPhaseID POST = new("tests.post"); + private static readonly RenderPhaseID FINAL = new("tests.final"); [Fact] public void NameScopesIsolateRepeatedProducerNamesInsideOneFrameGraph() @@ -21,36 +21,50 @@ public void NameScopesIsolateRepeatedProducerNamesInsideOneFrameGraph() RenderGraphBuilder graph = CreateGraph(); using (graph.BeginNameScope("Request[0] First")) { - graph.AddRasterPass("Visible", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Visible", GEOMETRY, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); } using (graph.BeginNameScope("Request[1] Second")) { - graph.AddRasterPass("Visible", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Visible", GEOMETRY, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); } RenderGraphCompileResult result = graph.Compile(); Assert.True(result.succeeded); - Assert.Equal( - ["Request[0] First/Visible", "Request[1] Second/Visible"], - PassNames(result.graph!)); + Assert.Equal(["Request[0] First/Visible", "Request[1] Second/Visible"], PassNames(result.graph!)); } [Fact] - public void MutationScope_Uncommitted_RollsBackPassesResourcesAndOutputs() + public void MutationScopeUncommittedRollsBackPassesResourcesAndOutputs() { RenderGraphBuilder graph = CreateGraph(); using (graph.BeginMutationScope()) { RenderTextureHandle temporary = graph.CreateTexture("Temporary", ColorDescriptor()); - graph.AddRasterPass("Failed Feature", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Failed Feature", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(temporary, 0, RenderLoadAction.Clear); graph.MarkOutput(temporary); } - graph.AddRasterPass("Survivor", C_FINAL, 0, static (_, _) => { }) + graph + .AddRasterPass("Survivor", FINAL, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -59,15 +73,24 @@ public void MutationScope_Uncommitted_RollsBackPassesResourcesAndOutputs() Assert.Equal(["Survivor"], PassNames(result.graph!)); Assert.Empty(result.graph!.textures); } + [Fact] - public void Compile_SchedulesProducerBeforeConsumer() + public void CompileSchedulesProducerBeforeConsumer() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle intermediate = graph.CreateTexture("Intermediate", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("Producer", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Producer", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(intermediate, 0, RenderLoadAction.Clear); - graph.AddRasterPass("Consumer", C_POST, 0, static (_, _) => { }) + graph + .AddRasterPass("Consumer", POST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear) .ReadTexture(intermediate); graph.MarkOutput(output); @@ -79,14 +102,22 @@ public void Compile_SchedulesProducerBeforeConsumer() } [Fact] - public void Compile_CullsUnconsumedPass() + public void CompileCullsUnconsumedPass() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle unused = graph.CreateTexture("Unused", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("Unused Pass", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Unused Pass", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(unused, 0, RenderLoadAction.Clear); - graph.AddRasterPass("Output Pass", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Output Pass", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear); graph.MarkOutput(output); @@ -98,11 +129,15 @@ public void Compile_CullsUnconsumedPass() } [Fact] - public void Compile_WithUninitializedRead_FailsClearly() + public void CompileWithUninitializedReadFailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle input = graph.CreateTexture("Input", SampledDescriptor()); - graph.AddRasterPass("Reader", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Reader", GEOMETRY, 0, static ( + _, + _ + ) => {}) .ReadTexture(input) .HasSideEffect(); @@ -113,7 +148,7 @@ public void Compile_WithUninitializedRead_FailsClearly() } [Fact] - public void Compile_WithReadWriteDeclaredAsSeparateAccess_FailsHazardValidation() + public void CompileWithReadWriteDeclaredAsSeparateAccessFailsHazardValidation() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture( @@ -122,14 +157,24 @@ public void Compile_WithReadWriteDeclaredAsSeparateAccess_FailsHazardValidation( 64, 64, RenderTextureFormat.RGBA16Float, - RenderTextureUsage.Storage | RenderTextureUsage.Sampled)); - graph.AddComputePass("Hazard", C_PROCESS, 0, static (_, _) => { }) + RenderTextureUsage.Storage | RenderTextureUsage.Sampled + ) + ); + graph + .AddComputePass("Hazard", PROCESS, 0, static ( + _, + _ + ) => {}) .ReadTexture(texture); ComputePassBuilder writer = graph.AddComputePass( "Writer", - C_PROCESS, + PROCESS, 0, - static (_, _) => { }); + static ( + _, + _ + ) => {} + ); writer.WriteStorageTexture(texture); writer.ReadTexture(texture); writer.HasSideEffect(); @@ -141,7 +186,7 @@ public void Compile_WithReadWriteDeclaredAsSeparateAccess_FailsHazardValidation( } [Fact] - public void Compile_ReusesCompatibleNonOverlappingTextures() + public void CompileReusesCompatibleNonOverlappingTextures() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle first = graph.CreateTexture("First", ColorDescriptor()); @@ -149,15 +194,31 @@ public void Compile_ReusesCompatibleNonOverlappingTextures() RenderTextureHandle second = graph.CreateTexture("Second", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("A", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("A", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(first, 0, RenderLoadAction.Clear); - graph.AddRasterPass("B", C_PROCESS, 0, static (_, _) => { }) + graph + .AddRasterPass("B", PROCESS, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(middle, 0, RenderLoadAction.Clear) .ReadTexture(first); - graph.AddRasterPass("C", C_TRANSPARENT, 0, static (_, _) => { }) + graph + .AddRasterPass("C", TRANSPARENT, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(second, 0, RenderLoadAction.Clear) .ReadTexture(middle); - graph.AddRasterPass("D", C_POST, 0, static (_, _) => { }) + graph + .AddRasterPass("D", POST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear) .ReadTexture(second); graph.MarkOutput(output); @@ -168,11 +229,17 @@ public void Compile_ReusesCompatibleNonOverlappingTextures() } [Fact] - public void Compile_WhenViewLimitExceeded_FailsClearly() + public void CompileWhenViewLimitExceededFailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 1)); - graph.AddRasterPass("A", C_GEOMETRY, 0, static (_, _) => { }).HasSideEffect(); - graph.AddRasterPass("B", C_TRANSPARENT, 0, static (_, _) => { }).HasSideEffect(); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 1)); + graph.AddRasterPass("A", GEOMETRY, 0, static ( + _, + _ + ) => {}).HasSideEffect(); + graph.AddRasterPass("B", TRANSPARENT, 0, static ( + _, + _ + ) => {}).HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -181,14 +248,20 @@ public void Compile_WhenViewLimitExceeded_FailsClearly() } [Fact] - public void Compile_WithPhaseCycle_FailsClearly() + public void CompileWithPhaseCycleFailsClearly() { - RenderPhaseId left = new("tests.left"); - RenderPhaseId right = new("tests.right"); + var left = new RenderPhaseID("tests.left"); + var right = new RenderPhaseID("tests.right"); RenderGraphBuilder graph = CreateGraph(); - RenderPassBuilder leftPass = graph.AddRasterPass("Left", left, 0, static (_, _) => { }); + RenderPassBuilder leftPass = graph.AddRasterPass("Left", left, 0, static ( + _, + _ + ) => {}); leftPass.Before(right).HasSideEffect(); - RenderPassBuilder rightPass = graph.AddRasterPass("Right", right, 0, static (_, _) => { }); + RenderPassBuilder rightPass = graph.AddRasterPass("Right", right, 0, static ( + _, + _ + ) => {}); rightPass.Before(left).HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -198,7 +271,7 @@ public void Compile_WithPhaseCycle_FailsClearly() } [Fact] - public void Compile_WithInvalidAttachmentSubresource_FailsClearly() + public void CompileWithInvalidAttachmentSubresourceFailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture( @@ -209,14 +282,15 @@ public void Compile_WithInvalidAttachmentSubresource_FailsClearly() RenderTextureFormat.RGBA16Float, RenderTextureUsage.ColorAttachment, mipCount: 2, - arrayLayers: 2)); - graph.AddRasterPass("Invalid Layer", C_GEOMETRY, 0, static (_, _) => { }) - .UseColorAttachment( - texture, - 0, - RenderLoadAction.Clear, - mipLevel: 1, - arrayLayer: 2); + arrayLayers: 2 + ) + ); + graph + .AddRasterPass("Invalid Layer", GEOMETRY, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(texture, 0, RenderLoadAction.Clear, mipLevel: 1, arrayLayer: 2); graph.MarkOutput(texture); RenderGraphCompileResult result = graph.Compile(); @@ -226,17 +300,18 @@ public void Compile_WithInvalidAttachmentSubresource_FailsClearly() } [Fact] - public void Compile_WhenTextureUsageDoesNotMatchPassOperation_FailsClearly() + public void CompileWhenTextureUsageDoesNotMatchPassOperationFailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture( "Not Storage", - new RenderTextureDescriptor( - 64, - 64, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled)); - graph.AddComputePass("Storage Writer", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(64, 64, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled) + ); + graph + .AddComputePass("Storage Writer", PROCESS, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(texture) .HasSideEffect(); @@ -247,16 +322,16 @@ public void Compile_WhenTextureUsageDoesNotMatchPassOperation_FailsClearly() } [Fact] - public void Compile_WhenStoredOutputIsDiscarded_FailsClearly() + public void CompileWhenStoredOutputIsDiscardedFailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle output = graph.CreateTexture("Discarded", ColorDescriptor()); - graph.AddRasterPass("Discard", C_FINAL, 0, static (_, _) => { }) - .UseColorAttachment( - output, - 0, - RenderLoadAction.Clear, - RenderStoreAction.Discard); + graph + .AddRasterPass("Discard", FINAL, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(output, 0, RenderLoadAction.Clear, RenderStoreAction.Discard); graph.MarkOutput(output); RenderGraphCompileResult result = graph.Compile(); @@ -266,105 +341,100 @@ public void Compile_WhenStoredOutputIsDiscarded_FailsClearly() } [Fact] - public void Compile_WhenBufferCopyCapabilityIsMissing_FailsClearly() + public void CompileWhenBufferCopyCapabilityIsMissingFailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderBufferHandle source = graph.CreateBuffer( "Source", - new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopySource)); + new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopySource) + ); RenderBufferHandle destination = graph.CreateBuffer( "Destination", - new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopyDestination)); - graph.AddCopyPass("Copy", C_PROCESS, 0, static (_, _) => { }) + new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopyDestination) + ); + graph + .AddCopyPass("Copy", PROCESS, 0, static ( + _, + _ + ) => {}) .CopyBuffer(source, destination) .HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_CAPABILITY_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_CAPABILITY_UNSUPPORTED"); } [Fact] - public void Compile_WhenSampledFormatIsMissing_FailsClearly() + public void CompileWhenSampledFormatIsMissingFailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, - CreateCapabilities( - maxViews: 64, - sampledFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, sampledFormats: [RenderTextureFormat.RGBA8]) + ); _ = graph.CreateTexture( "Unsupported Sampled Format", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA16Float, - RenderTextureUsage.Sampled)); + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA16Float, RenderTextureUsage.Sampled) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED"); } [Fact] - public void Compile_WhenTextureArrayCapabilityIsMissing_FailsClearly() + public void CompileWhenTextureArrayCapabilityIsMissingFailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, features: GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.StorageTexture - | GraphicsCapability.TextureBlit)); + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.TextureBlit + ) + ); _ = graph.CreateTexture( "Unsupported Array", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled, - arrayLayers: 2)); + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, arrayLayers: 2) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED"); } [Fact] - public void Compile_WhenUnsigned32BitIndexCapabilityIsMissing_FailsClearly() + public void CompileWhenUnsigned32BitIndexCapabilityIsMissingFailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, features: GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.TextureBlit)); + | GraphicsCapability.StorageBuffer + | GraphicsCapability.TextureBlit + ) + ); _ = graph.CreateBuffer( "Unsupported Indices", - new RenderBufferDescriptor(3, sizeof(uint), RenderBufferUsage.Index)); + new RenderBufferDescriptor(3, sizeof(uint), RenderBufferUsage.Index) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_INDEX32_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_INDEX32_UNSUPPORTED"); } [Fact] - public void Compile_WhenVolumeTextureCapabilityIsMissing_FailsClearly() + public void CompileWhenVolumeTextureCapabilityIsMissingFailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 64)); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 64)); _ = graph.CreateTexture( "Unsupported Volume", new RenderTextureDescriptor( @@ -373,26 +443,28 @@ public void Compile_WhenVolumeTextureCapabilityIsMissing_FailsClearly() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 8)); + depth: 8 + ) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED"); } [Fact] - public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() + public void CompileWithSupportedVolumeAndCubemapTexturesSucceeds() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, features: GraphicsCapability.Texture3D | GraphicsCapability.TextureCubeArray, sampled3DFormats: [RenderTextureFormat.RGBA8], - sampledCubeFormats: [RenderTextureFormat.RGBA8])); + sampledCubeFormats: [RenderTextureFormat.RGBA8] + ) + ); _ = graph.CreateTexture( "Volume", new RenderTextureDescriptor( @@ -401,7 +473,9 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 8)); + depth: 8 + ) + ); _ = graph.CreateTexture( "Cubemap Array", new RenderTextureDescriptor( @@ -410,15 +484,17 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, arrayLayers: 2, - dimension: RenderTextureDimension.Cube)); + dimension: RenderTextureDimension.Cube + ) + ); Assert.True(graph.Compile().succeeded); } [Fact] - public void Compile_WhenMultisampleFormatCapabilityIsMissing_FailsClearly() + public void CompileWhenMultisampleFormatCapabilityIsMissingFailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 64)); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 64)); RenderTextureHandle target = graph.CreateTexture( "Unsupported MSAA", new RenderTextureDescriptor( @@ -426,38 +502,50 @@ public void Compile_WhenMultisampleFormatCapabilityIsMissing_FailsClearly() 8, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment, - sampleCount: 4)); - graph.AddRasterPass("MSAA", C_GEOMETRY, 0, static (_, _) => { }) + sampleCount: 4 + ) + ); + graph + .AddRasterPass("MSAA", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(target, 0, RenderLoadAction.Clear); graph.MarkOutput(target); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED"); } [Fact] - public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() + public void CompileStorageTextureAccessHonorsReadAndWriteFormatCapabilities() { - RenderGraphBuilder readGraph = new( + var readGraph = new RenderGraphBuilder( 1, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [RenderTextureFormat.RGBA8], - storageWriteFormats: [])); + CreateCapabilities(maxViews: 64, storageReadFormats: [RenderTextureFormat.RGBA8], storageWriteFormats: []) + ); RenderTextureHandle readTexture = readGraph.CreateTexture( "Read Only", new RenderTextureDescriptor( 8, 8, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Storage)); - readGraph.AddRasterPass("Initialize", C_GEOMETRY, 0, static (_, _) => { }) + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Storage + ) + ); + readGraph + .AddRasterPass("Initialize", GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(readTexture, 0, RenderLoadAction.Clear); - readGraph.AddComputePass("Read", C_PROCESS, 0, static (_, _) => { }) + readGraph + .AddComputePass("Read", PROCESS, 0, static ( + _, + _ + ) => {}) .ReadStorageTexture(readTexture) .HasSideEffect(); @@ -465,20 +553,19 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.True(readResult.succeeded); - RenderGraphBuilder writeGraph = new( + var writeGraph = new RenderGraphBuilder( 2, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [], - storageWriteFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) + ); RenderTextureHandle writeTexture = writeGraph.CreateTexture( "Write Only", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - writeGraph.AddComputePass("Write", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + writeGraph + .AddComputePass("Write", PROCESS, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(writeTexture) .HasSideEffect(); @@ -486,20 +573,19 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.True(writeResult.succeeded); - RenderGraphBuilder readWriteGraph = new( + var readWriteGraph = new RenderGraphBuilder( 3, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [], - storageWriteFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) + ); RenderTextureHandle readWriteTexture = readWriteGraph.CreateTexture( "Read Write", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - readWriteGraph.AddComputePass("Read Write", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + readWriteGraph + .AddComputePass("Read Write", PROCESS, 0, static ( + _, + _ + ) => {}) .ReadWriteStorageTexture(readWriteTexture) .HasSideEffect(); @@ -508,21 +594,27 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.False(readWriteResult.succeeded); Assert.Contains( readWriteResult.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED"); + diagnostic => diagnostic.code == "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED" + ); } [Fact] - public void Execute_WhenPassFails_StillEndsPassAndGraph() + public void ExecuteWhenPassFailsStillEndsPassAndGraph() { RenderGraphBuilder graph = CreateGraph(); - graph.AddRasterPass( + graph + .AddRasterPass( "Failure", - C_GEOMETRY, + GEOMETRY, 0, - static (_, _) => throw new InvalidOperationException("failure")) + static ( + _, + _ + ) => throw new InvalidOperationException("failure") + ) .HasSideEffect(); CompiledRenderGraph compiled = graph.Compile().graph!; - RecordingBackend backend = new(); + var backend = new RecordingBackend(); Assert.Throws(() => compiled.Execute(backend, 12)); @@ -530,7 +622,7 @@ public void Execute_WhenPassFails_StillEndsPassAndGraph() } [Fact] - public void Execute_ParallelRecordingOverlapsEligibleCallbacksAndReplaysInGraphOrder() + public void ExecuteParallelRecordingOverlapsEligibleCallbacksAndReplaysInGraphOrder() { RenderGraphBuilder graph = CreateGraph(); int activeRecorders = 0; @@ -543,27 +635,31 @@ RenderPassContext context int active = Interlocked.Increment(ref activeRecorders); int observed; while (active > (observed = Volatile.Read(ref maximumRecorders))) + { _ = Interlocked.CompareExchange(ref maximumRecorders, active, observed); + } if (drawCount <= 2 && Environment.ProcessorCount > 1) { parallelEntered.Signal(); - Assert.True(parallelEntered.Wait(TimeSpan.FromSeconds(30)), - "Both eligible callbacks must enter before either completes recording."); + Assert.True( + parallelEntered.Wait(TimeSpan.FromSeconds(30)), + "Both eligible callbacks must enter before either completes recording." + ); } context.commands.Draw(drawCount); _ = Interlocked.Decrement(ref activeRecorders); } - graph.AddRasterPass("Parallel A", C_GEOMETRY, 1, Record) + graph.AddRasterPass("Parallel A", GEOMETRY, 1, Record) .AllowParallelRecording() .HasSideEffect(); - graph.AddRasterPass("Parallel B", C_PROCESS, 2, Record) + graph.AddRasterPass("Parallel B", PROCESS, 2, Record) .AllowParallelRecording() .HasSideEffect(); - graph.AddRasterPass("Serial", C_FINAL, 3, Record) + graph.AddRasterPass("Serial", FINAL, 3, Record) .HasSideEffect(); CompiledRenderGraph compiled = graph.Compile().graph!; - RecordingBackend backend = new(); + var backend = new RecordingBackend(); compiled.Execute(backend, 42); @@ -575,12 +671,16 @@ RenderPassContext context "Begin:Serial", "Draw:Serial:3", "End:Serial", "EndGraph" ], - backend.calls); + backend.calls + ); Assert.Equal( [RenderPassRecordingMode.Parallel, RenderPassRecordingMode.Parallel, RenderPassRecordingMode.Serial], - compiled.passes.Select(static pass => pass.recordingMode)); + compiled.passes.Select(static pass => pass.recordingMode) + ); if (Environment.ProcessorCount > 1) + { Assert.True(maximumRecorders > 1, "Parallel pass callbacks did not overlap."); + } } private static RenderGraphBuilder CreateGraph() => new(1, CreateCapabilities(64)); @@ -592,34 +692,36 @@ private static GraphicsCapabilities CreateCapabilities( IReadOnlyList? sampled3DFormats = null, IReadOnlyList? sampledCubeFormats = null, IReadOnlyList? storageReadFormats = null, - IReadOnlyList? storageWriteFormats = null) - => new( - GraphicsApi.Noop, - features - ?? (GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.StorageTexture - | GraphicsCapability.TextureBlit - | GraphicsCapability.Texture2DArray - | GraphicsCapability.Index32), - new GraphicsLimits(maxViews, 8, 16384, 16), - sampledFormats ?? Enum.GetValues(), - Enum.GetValues(), - storageReadFormats ?? - [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], - storageWriteFormats ?? - [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], - false, - false, - sampled3DFormats, - sampledCubeFormats); + IReadOnlyList? storageWriteFormats = null + ) => new( + GraphicsApi.noop, + features + ?? (GraphicsCapability.Compute + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.TextureBlit + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Index32), + new GraphicsLimits(maxViews, 8, 16_384, 16), + sampledFormats ?? Enum.GetValues(), + Enum.GetValues(), + storageReadFormats + ?? [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], + storageWriteFormats + ?? [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], + false, + false, + sampled3DFormats, + sampledCubeFormats + ); private static RenderTextureDescriptor ColorDescriptor() => new( 128, 128, RenderTextureFormat.RGBA16Float, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); private static RenderTextureDescriptor SampledDescriptor() => new(128, 128, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); @@ -661,70 +763,161 @@ internal EmptyEncoder(Action? onDraw = null) m_onDraw = onDraw; } - public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) { } - public override void BindComputePipeline(ComputePipelineHandle pipeline) { } + public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) {} + + public override void BindComputePipeline(ComputePipelineHandle pipeline) {} + public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, - RenderSamplerState sampler) { } + RenderSamplerState sampler + ) {} + public override void BindTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, - RenderSamplerState sampler) { } + RenderSamplerState sampler + ) {} + public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, RenderTextureHandle texture, - int mipLevel = 0) { } + int mipLevel = 0 + ) {} + public override void BindStorageTexture( - RenderBindingId binding, + RenderBindingID binding, PersistentTextureHandle texture, - int mipLevel = 0) { } - public override void BindBuffer(RenderBindingId binding, RenderBufferHandle buffer) { } - public override void BindBuffer(RenderBindingId binding, PersistentBufferHandle buffer) { } - public override void SetUniform(RenderBindingId binding, ReadOnlySpan value) { } - public override void SetTransform(ReadOnlySpan columnMajorMatrix) { } - public override void SetRasterState(RenderRasterState state) { } - public override void SetStencil(RenderStencilState state) { } - public override void SetViewport(int x, int y, int width, int height) { } - public override void SetScissor(int x, int y, int width, int height) { } - public override void BindVertexBuffer(RenderBufferHandle buffer, int firstVertex = 0) { } - public override void BindVertexBuffer(PersistentBufferHandle buffer, int firstVertex = 0) { } - public override void BindIndexBuffer(RenderBufferHandle buffer, int firstIndex = 0) { } - public override void BindIndexBuffer(PersistentBufferHandle buffer, int firstIndex = 0) { } + int mipLevel = 0 + ) {} + + public override void BindBuffer( + RenderBindingID binding, + RenderBufferHandle buffer + ) {} + + public override void BindBuffer( + RenderBindingID binding, + PersistentBufferHandle buffer + ) {} + + public override void SetUniform( + RenderBindingID binding, + ReadOnlySpan value + ) {} + + public override void SetTransform(ReadOnlySpan columnMajorMatrix) {} + + public override void SetRasterState(RenderRasterState state) {} + + public override void SetStencil(RenderStencilState state) {} + + public override void SetViewport( + int x, + int y, + int width, + int height + ) {} + + public override void SetScissor( + int x, + int y, + int width, + int height + ) {} + + public override void BindVertexBuffer( + RenderBufferHandle buffer, + int firstVertex = 0 + ) {} + + public override void BindVertexBuffer( + PersistentBufferHandle buffer, + int firstVertex = 0 + ) {} + + public override void BindIndexBuffer( + RenderBufferHandle buffer, + int firstIndex = 0 + ) {} + + public override void BindIndexBuffer( + PersistentBufferHandle buffer, + int firstIndex = 0 + ) {} + public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, - int instanceCount) { } + int instanceCount + ) {} + public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, - int instanceCount) { } - public override void Draw(int vertexCount, int instanceCount = 1) => m_onDraw?.Invoke(vertexCount); - public override void DrawProcedural(int vertexCount, int instanceCount = 1) { } - public override void DrawIndexed(int indexCount, int instanceCount = 1) { } + int instanceCount + ) {} + + public override void Draw( + int vertexCount, + int instanceCount = 1 + ) => m_onDraw?.Invoke(vertexCount); + + public override void DrawProcedural( + int vertexCount, + int instanceCount = 1 + ) {} + + public override void DrawIndexed( + int indexCount, + int instanceCount = 1 + ) {} + public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } + int commandCount = 1 + ) {} + public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } - public override void Dispatch(int groupCountX, int groupCountY = 1, int groupCountZ = 1) { } + int commandCount = 1 + ) {} + + public override void Dispatch( + int groupCountX, + int groupCountY = 1, + int groupCountZ = 1 + ) {} + public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } + int commandCount = 1 + ) {} + public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } - public override void CopyTexture(RenderTextureHandle source, RenderTextureHandle destination) { } + int commandCount = 1 + ) {} + + public override void CopyTexture( + RenderTextureHandle source, + RenderTextureHandle destination + ) {} + public override void BlitTexture( RenderTextureHandle source, RenderTextureRegion sourceRegion, RenderTextureHandle destination, - RenderTextureRegion destinationRegion) { } - public override void CopyBuffer(RenderBufferHandle source, RenderBufferHandle destination) { } + RenderTextureRegion destinationRegion + ) {} + + public override void CopyBuffer( + RenderBufferHandle source, + RenderBufferHandle destination + ) {} } } diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs index 452bc6b05..6545fab77 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -10,13 +10,13 @@ public sealed class RenderGraphMutationTests [Fact] public void LaterScopeCannotChangeAnyPreviouslyAcceptedPassDeclaration() { - var graph = CreateGraph(); - RasterPassBuilder accepted = graph.AddRasterPass("Accepted", new("first"), 0, Execute); + RenderGraphBuilder graph = CreateGraph(); + RasterPassBuilder accepted = graph.AddRasterPass("Accepted", new RenderPhaseID("first"), 0, Execute); accepted.HasSideEffect(); using (RenderGraphMutationScope mutation = graph.BeginMutationScope()) { - Assert.Throws(() => accepted.Before(new("late"))); - Assert.Throws(() => accepted.After(new("late"))); + Assert.Throws(() => accepted.Before(new RenderPhaseID("late"))); + Assert.Throws(() => accepted.After(new RenderPhaseID("late"))); Assert.Throws(() => accepted.AllowParallelRecording()); Assert.Throws(() => accepted.ClearPresentationTarget(default)); mutation.Commit(); @@ -27,13 +27,13 @@ public void LaterScopeCannotChangeAnyPreviouslyAcceptedPassDeclaration() [Fact] public void InvalidCommitRollsBackOutputsResourcesPhasesAndValidation() { - var graph = CreateGraph(); - graph.AddRasterPass("Accepted", new("first"), 0, Execute).HasSideEffect(); + RenderGraphBuilder graph = CreateGraph(); + graph.AddRasterPass("Accepted", new RenderPhaseID("first"), 0, Execute).HasSideEffect(); RenderGraphValidationResult baseline = graph.Validate(); using (RenderGraphMutationScope mutation = graph.BeginMutationScope()) { RenderTextureHandle texture = graph.CreateTexture("Missing Producer", Descriptor()); - graph.AddRasterPass("Invalid", new("bad"), 0, Execute).ReadTexture(texture).HasSideEffect(); + graph.AddRasterPass("Invalid", new RenderPhaseID("bad"), 0, Execute).ReadTexture(texture).HasSideEffect(); graph.MarkOutput(texture); Assert.False(graph.Validate().isValid); Assert.Throws(() => mutation.Commit()); @@ -50,24 +50,27 @@ public void InvalidCommitRollsBackOutputsResourcesPhasesAndValidation() [Fact] public void RolledBackHandlesAndPassBuildersCannotAliasNewDeclarations() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle retired; RenderBufferHandle retiredBuffer; RasterPassBuilder retiredPass; using (graph.BeginMutationScope()) { retired = graph.CreateTexture("Retired", Descriptor()); - retiredBuffer = graph.CreateBuffer("Retired Buffer", new(16, 4, RenderBufferUsage.Vertex)); - retiredPass = graph.AddRasterPass("Retired", new("retired"), 0, Execute); + retiredBuffer = graph.CreateBuffer("Retired Buffer", new RenderBufferDescriptor(16, 4, RenderBufferUsage.Vertex)); + retiredPass = graph.AddRasterPass("Retired", new RenderPhaseID("retired"), 0, Execute); } RenderTextureHandle current = graph.CreateTexture("Current", Descriptor()); - RenderBufferHandle currentBuffer = graph.CreateBuffer("Current Buffer", new(16, 4, RenderBufferUsage.Vertex)); + RenderBufferHandle currentBuffer = graph.CreateBuffer( + "Current Buffer", + new RenderBufferDescriptor(16, 4, RenderBufferUsage.Vertex) + ); Assert.NotEqual(retired, current); Assert.NotEqual(retiredBuffer, currentBuffer); Assert.Throws(() => graph.MarkOutput(retired)); Assert.Throws(() => graph.MarkOutput(retiredBuffer)); Assert.Throws(() => retiredPass.HasSideEffect()); - graph.AddRasterPass("Current", new("current"), 0, Execute).UseColorAttachment(current, 0, RenderLoadAction.Clear); + graph.AddRasterPass("Current", new RenderPhaseID("current"), 0, Execute).UseColorAttachment(current, 0, RenderLoadAction.Clear); graph.MarkOutput(current); Assert.True(graph.Compile().succeeded); } @@ -75,10 +78,10 @@ public void RolledBackHandlesAndPassBuildersCannotAliasNewDeclarations() [Fact] public void NestedCommitRemainsOwnedByOuterRollbackAndScopesEnforceNesting() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderGraphMutationScope outer = graph.BeginMutationScope(); RenderGraphMutationScope inner = graph.BeginMutationScope(); - graph.AddRasterPass("Nested", new("nested"), 0, Execute).HasSideEffect(); + graph.AddRasterPass("Nested", new RenderPhaseID("nested"), 0, Execute).HasSideEffect(); Assert.Throws(() => outer.Dispose()); Assert.Throws(() => graph.Compile()); inner.Commit(); @@ -91,14 +94,16 @@ public void NestedCommitRemainsOwnedByOuterRollbackAndScopesEnforceNesting() [Fact] public void RollbackRemovesNameScopeWithoutLateDisposalRemovingAnotherScope() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderGraphNameScope retired; using (graph.BeginMutationScope()) + { retired = graph.BeginNameScope("Retired"); + } using (graph.BeginNameScope("Current")) { retired.Dispose(); - graph.AddRasterPass("Visible", new("visible"), 0, Execute).HasSideEffect(); + graph.AddRasterPass("Visible", new RenderPhaseID("visible"), 0, Execute).HasSideEffect(); } Assert.Equal("Current/Visible", Assert.Single(graph.Compile().graph!.passes).name); } @@ -106,36 +111,33 @@ public void RollbackRemovesNameScopeWithoutLateDisposalRemovingAnotherScope() [Fact] public void MutationCannotCloseAnEarlierNameScopeOrChangeItsPrefix() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); using RenderGraphNameScope name = graph.BeginNameScope("Accepted"); using (graph.BeginMutationScope()) + { Assert.Throws(() => name.Dispose()); - graph.AddRasterPass("Visible", new("visible"), 0, Execute).HasSideEffect(); + } + graph.AddRasterPass("Visible", new RenderPhaseID("visible"), 0, Execute).HasSideEffect(); Assert.Equal("Accepted/Visible", Assert.Single(graph.Compile().graph!.passes).name); } - private static RenderGraphBuilder CreateGraph() - => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(64, 8, 16384, 16), - Enum.GetValues(), Enum.GetValues(), - [], [], false, false)); - [Fact] public void AcceptedFuturePhaseOrderingStillDetectsALaterCycleAndRollsBack() { - var graph = CreateGraph(); - graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect().Before(new("future")); + RenderGraphBuilder graph = CreateGraph(); + graph.AddRasterPass("First", new RenderPhaseID("first"), 0, Execute).HasSideEffect().Before(new RenderPhaseID("future")); using (RenderGraphMutationScope accepted = graph.BeginMutationScope()) + { accepted.Commit(); + } using (graph.BeginMutationScope()) { - graph.AddRasterPass("Future", new("future"), 0, Execute).HasSideEffect().Before(new("first")); + graph.AddRasterPass("Future", new RenderPhaseID("future"), 0, Execute).HasSideEffect().Before(new RenderPhaseID("first")); Assert.Contains(graph.Validate().diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_CYCLE"); } using (RenderGraphMutationScope next = graph.BeginMutationScope()) { - graph.AddRasterPass("Valid", new("future"), 0, Execute).HasSideEffect(); + graph.AddRasterPass("Valid", new RenderPhaseID("future"), 0, Execute).HasSideEffect(); next.Commit(); } Assert.Equal(new[] { "First", "Valid" }, graph.Compile().graph!.passes.Select(static pass => pass.name)); @@ -146,14 +148,14 @@ public void IncrementalSharedResourceAnalysisMatchesTheCompleteGraph() { string[] Build(bool incremental) { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture("Shared", Descriptor()); for (int index = 0; index < 12; index++) { using RenderGraphMutationScope? mutation = incremental ? graph.BeginMutationScope() : null; - graph.AddRasterPass("Writer" + index, new("write"), 0, Execute) + graph.AddRasterPass("Writer" + index, new RenderPhaseID("write"), 0, Execute) .UseColorAttachment(texture, 0, index == 0 ? RenderLoadAction.Clear : RenderLoadAction.Load); - graph.AddRasterPass("Reader" + index, new("read"), 0, Execute).ReadTexture(texture).HasSideEffect(); + graph.AddRasterPass("Reader" + index, new RenderPhaseID("read"), 0, Execute).ReadTexture(texture).HasSideEffect(); mutation?.Commit(); } graph.MarkOutput(texture); @@ -165,20 +167,36 @@ string[] Build(bool incremental) [Fact] public void EditingAnUncommittedValidatedPassRebuildsItsAnalysis() { - var graph = CreateGraph(); - RasterPassBuilder first = graph.AddRasterPass("First", new("first"), 0, Execute); + RenderGraphBuilder graph = CreateGraph(); + RasterPassBuilder first = graph.AddRasterPass("First", new RenderPhaseID("first"), 0, Execute); first.HasSideEffect(); - graph.AddRasterPass("Last", new("last"), 0, Execute).HasSideEffect(); + graph.AddRasterPass("Last", new RenderPhaseID("last"), 0, Execute).HasSideEffect(); Assert.True(graph.Validate().isValid); - first.After(new("last")); + first.After(new RenderPhaseID("last")); Assert.Equal(new[] { "Last", "First" }, graph.Compile().graph!.passes.Select(static pass => pass.name)); } + private static RenderGraphBuilder CreateGraph() + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(64, 8, 16_384, 16), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + false, + false + ) + ); + private static RenderTextureDescriptor Descriptor() => new(32, 32, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); private static void Execute( int payload, RenderPassContext context - ) { } + ) {} } diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs index b53004218..ca27fe3a9 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -10,8 +10,8 @@ public sealed class RenderGraphValidationTests [Fact] public void ValidationIsFrozenAndReusedUntilAnyPassDeclarationChanges() { - var graph = CreateGraph(); - RasterPassBuilder pass = graph.AddRasterPass("Visible", new("visible"), 0, Execute); + RenderGraphBuilder graph = CreateGraph(); + RasterPassBuilder pass = graph.AddRasterPass("Visible", new RenderPhaseID("visible"), 0, Execute); RenderGraphValidationResult culled = graph.Validate(); Assert.True(culled.isValid); Assert.Equal(1, culled.culledPassCount); @@ -29,16 +29,16 @@ public void ValidationIsFrozenAndReusedUntilAnyPassDeclarationChanges() Assert.Equal(visible.scheduledPassCount, compiled.graph!.passes.Count); Assert.Equal(visible.diagnostics, compiled.diagnostics); Assert.Throws(() => graph.Compile()); - Assert.Throws(() => pass.Before(new("late"))); + Assert.Throws(() => pass.Before(new RenderPhaseID("late"))); } [Fact] public void LaterPhaseDeclarationInvalidatesCachedScheduleAndDetectsCycle() { - var graph = CreateGraph(); - graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect().After(new("second")); + RenderGraphBuilder graph = CreateGraph(); + graph.AddRasterPass("First", new RenderPhaseID("first"), 0, Execute).HasSideEffect().After(new RenderPhaseID("second")); Assert.True(graph.Validate().isValid); - graph.AddRasterPass("Second", new("second"), 0, Execute).HasSideEffect().After(new("first")); + graph.AddRasterPass("Second", new RenderPhaseID("second"), 0, Execute).HasSideEffect().After(new RenderPhaseID("first")); RenderGraphValidationResult invalid = graph.Validate(); Assert.False(invalid.isValid); @@ -51,9 +51,9 @@ public void LaterPhaseDeclarationInvalidatesCachedScheduleAndDetectsCycle() [Fact] public void ValidationAndCompilationApplyTheSameViewLimit() { - var graph = CreateGraph(1); - graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect(); - graph.AddRasterPass("Second", new("second"), 0, Execute).HasSideEffect(); + RenderGraphBuilder graph = CreateGraph(1); + graph.AddRasterPass("First", new RenderPhaseID("first"), 0, Execute).HasSideEffect(); + graph.AddRasterPass("Second", new RenderPhaseID("second"), 0, Execute).HasSideEffect(); RenderGraphValidationResult validation = graph.Validate(); Assert.False(validation.isValid); Assert.Contains(validation.diagnostics, static item => item.code == "RENDER_GRAPH_VIEW_LIMIT"); @@ -63,29 +63,38 @@ public void ValidationAndCompilationApplyTheSameViewLimit() [Fact] public void ValidationDoesNotInvokeCommandCallbacks() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); int calls = 0; - graph.AddRasterPass("Visible", new("visible"), 0, ( + graph.AddRasterPass("Visible", new RenderPhaseID("visible"), 0, ( payload, context ) => calls++).HasSideEffect(); for (int index = 0; index < 32; index++) + { Assert.True(graph.Validate().isValid); + } Assert.True(graph.Compile().succeeded); Assert.Equal(0, calls); } private static RenderGraphBuilder CreateGraph(int maxViews = 64) - => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, - GraphicsCapability.None, - new GraphicsLimits(maxViews, 8, 16384, 16), - Enum.GetValues(), - Enum.GetValues(), - [], [], false, false)); + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(maxViews, 8, 16_384, 16), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + false, + false + ) + ); private static void Execute( int payload, RenderPassContext context - ) { } + ) {} } diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs index 703082097..3eda20421 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs @@ -28,24 +28,28 @@ bool rejectGraph m_rejectGraph = rejectGraph; } - /// + /// public void PrepareFrame(ulong frameIndex) => m_unregister(this); - /// + /// public void AddRenderPasses( RenderGraphBuilder graph, ulong frameIndex ) { - graph.AddRasterPass("Collectible Callback", new RenderPhaseId("tests.collectible.contributor"), - 0, Encode).HasSideEffect(); + graph.AddRasterPass( + "Collectible Callback", + new RenderPhaseID("tests.collectible.contributor"), + 0, + Encode + ).HasSideEffect(); if (m_rejectGraph) + { throw new InvalidOperationException("Reject the collectible frame mutation."); + } } private void Encode( int payload, RenderPassContext context - ) { - GC.KeepAlive(this); - } + ) => GC.KeepAlive(this); } diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs new file mode 100644 index 000000000..361ba93f0 --- /dev/null +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs @@ -0,0 +1,6 @@ +namespace Inno.Rendering.Runtime.Reload.TestModule; + +/// +/// Provides a collectible value used to verify that frame-data queues release retired plugins. +/// +public sealed class ReloadableFramePayload; diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs new file mode 100644 index 000000000..bb76565c9 --- /dev/null +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering.Runtime.Reload.TestModule; + +[RenderFeatureExtension(C_EXTENSION_ID)] +internal sealed class ReloadableRenderFeature : RenderPipelineFeature +{ + internal const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin-feature"; + + /// + /// Adds observable feature work to the active pipeline graph. + /// + /// + /// The active feature context that owns the frame graph mutation. + /// + public override void AddRenderPasses(RenderFeatureContext context) + => context.graph + .AddRasterPass( + "Reloadable Plugin Feature Pass", + new RenderPhaseID("tests.runtime.reloadable-plugin-feature.visible"), + 1, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); +} diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs index 026895e23..4fbd5a199 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs @@ -1,23 +1,15 @@ -using Inno.Rendering; -using Inno.Rendering.Runtime; - namespace Inno.Rendering.Runtime.Reload.TestModule; -/// -/// Provides a collectible value used to verify that frame-data queues release retired plugins. -/// -public sealed class ReloadableFramePayload; - /// /// Supplies a collectible Plugin-owned pipeline for rendering generation removal tests. /// -[RenderPipelineExtension(extensionId)] +[RenderPipelineExtension(C_EXTENSION_ID)] internal sealed class ReloadableRenderPipeline : RenderPipeline { /// /// Identifies the pipeline independently of its collectible CLR generation. /// - internal const string extensionId = "tests.runtime.reloadable-plugin"; + internal const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin"; /// /// Adds observable render work to the frame graph. @@ -26,36 +18,15 @@ internal sealed class ReloadableRenderPipeline : RenderPipeline /// The active pipeline context that owns the frame graph mutation. /// public override void Build(RenderPipelineContext context) - { - context.graph + => context.graph .AddRasterPass( "Reloadable Plugin Pass", - new RenderPhaseId("tests.runtime.reloadable-plugin.visible"), + new RenderPhaseID("tests.runtime.reloadable-plugin.visible"), 0, - static (_, _) => { }) - .HasSideEffect(); - } -} - -[RenderFeatureExtension(extensionId)] -internal sealed class ReloadableRenderFeature : RenderPipelineFeature -{ - internal const string extensionId = "tests.runtime.reloadable-plugin-feature"; - - /// - /// Adds observable feature work to the active pipeline graph. - /// - /// - /// The active feature context that owns the frame graph mutation. - /// - public override void AddRenderPasses(RenderFeatureContext context) - { - context.graph - .AddRasterPass( - "Reloadable Plugin Feature Pass", - new RenderPhaseId("tests.runtime.reloadable-plugin-feature.visible"), - 1, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); - } } diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs index 912415bac..4ae22aeae 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs @@ -1,15 +1,17 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; -using Inno.Extensibility.Catalogs; -using Inno.Runtime; -using Inno.Runtime.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Xunit; +using Inno.Extensibility.Catalogs; +using Inno.Runtime; +using Inno.Runtime.Generators; namespace Inno.Runtime.Generators.Tests; @@ -18,7 +20,7 @@ public sealed class RuntimeModuleCatalogGeneratorTests [Fact] public void AConverterWithoutAConstructionEntryFailsDuringCompilation() { - const string source = """ + const string C_SOURCE = """ namespace Fixture; public sealed class Box; public sealed class Model : Inno.Core.Serialization.ISerializable @@ -34,11 +36,14 @@ public override void Write(Inno.Core.Serialization.SerializationWriter writer, B } """; string[] paths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.InvalidStaticCatalogFixture", - [CSharpSyntaxTree.ParseText(source)], paths.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.InvalidStaticCatalogFixture", + [CSharpSyntaxTree.ParseText(C_SOURCE)], + paths.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); Diagnostic failure = Assert.Single(diagnostics, static diagnostic => diagnostic.Id == "INNORUN002"); Assert.Equal(DiagnosticSeverity.Error, failure.Severity); Assert.Contains("parameterless constructor", failure.GetMessage()); @@ -47,7 +52,7 @@ public override void Write(Inno.Core.Serialization.SerializationWriter writer, B [Fact] public void GeneratedCatalogCompilesAndPublishesExactMetadataAndFactories() { - const string source = """ + const string C_SOURCE = """ using System; namespace Fixture; [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] @@ -95,15 +100,18 @@ public class RequiredBase { public required string name { get; init; } } public sealed class RequiredChild : RequiredBase { } """; string[] paths = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") - ?? throw new InvalidOperationException("The test host provides no platform closure.")).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.StaticCatalogFixture", - [CSharpSyntaxTree.ParseText(source)], paths.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + ?? throw new InvalidOperationException("The test host provides no platform closure.")).Split(Path.PathSeparator); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.StaticCatalogFixture", + [CSharpSyntaxTree.ParseText(C_SOURCE)], + paths.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out ImmutableArray diagnostics); Assert.Empty(diagnostics.Where(static value => value.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); stream.Position = 0; var lifetime = new AssemblyLoadContext("static-catalog-test", isCollectible: true); @@ -112,16 +120,22 @@ public sealed class RequiredChild : RequiredBase { } Assembly assembly = lifetime.LoadFromStream(stream); MethodInfo entry = assembly.GetType("Inno.StaticCatalogFixture.Generated.RuntimeModuleCatalog", throwOnError: true)! .GetMethod("Register", BindingFlags.Public | BindingFlags.Static)!; - var register = entry.CreateDelegate>(); + Action register = entry.CreateDelegate>(); var catalog = new StaticTypeCatalogSource([register]); Type derivedType = assembly.GetType("Fixture.Derived", throwOnError: true)!; TypeCatalogMetadata derived = catalog.GetMetadata(derivedType); Assert.Equal(derived.type, catalog.CreateInstance(derived.type).GetType()); Assert.Equal("Fixture.Base", Assert.Single(derived.baseTypes).FullName); Assert.Equal(typeof(int), Assert.Single(derived.interfaces).GenericTypeArguments[0]); - Attribute marker = Assert.Single(derived.inheritedAttributes, static attribute => attribute.GetType().Name == "MarkerAttribute"); + Attribute marker = Assert.Single( + derived.inheritedAttributes, + static attribute => attribute.GetType().Name == "MarkerAttribute" + ); Assert.Equal("derived", marker.GetType().GetProperty("name")!.GetValue(marker)); - Assert.Contains(derived.parameterlessOverrides, static slot => slot.name == "Tick" && slot.declaringBase.FullName == "Fixture.Base"); + Assert.Contains( + derived.parameterlessOverrides, + static slot => slot.name == "Tick" && slot.declaringBase.FullName == "Fixture.Base" + ); Assert.False(catalog.CanCreateInstance(assembly.GetType("Fixture.RequiredChild", throwOnError: true)!)); Assert.False(catalog.CanCreateInstance(assembly.GetType("Fixture.Generic`1+Nested", throwOnError: true)!)); Type generic = assembly.GetType("Fixture.Generic`1", throwOnError: true)!; diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs index 6f87a5d61..22d657ddd 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs @@ -1,11 +1,11 @@ using System; using System.IO; using System.Linq; -using Inno.Runtime.Contracts; -using Inno.Runtime.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; +using Inno.Runtime.Contracts; +using Inno.Runtime.Generators; namespace Inno.Runtime.Generators.Tests; @@ -50,9 +50,10 @@ public static class AddedEngineModule } [Fact] - public void DuplicateStableIdsFailDuringCompilation() + public void DuplicateStableIDsFailDuringCompilation() { - (_, GeneratorDriverRunResult result) = Generate(C_CATALOG + """ + (_, GeneratorDriverRunResult result) = Generate( + C_CATALOG + """ public static class DuplicateModule { @@ -61,22 +62,27 @@ public static class DuplicateModule [RuntimeSubsystemRegistration("same")] public static IRuntimeSubsystemFactory Second(HostInputs context) => throw new InvalidOperationException(); } - """); - Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001" && - diagnostic.GetMessage().Contains("duplicated", StringComparison.Ordinal)); + """ + ); + Assert.Contains(result.Diagnostics, static diagnostic => ( + diagnostic.Id == "INNORUN001" + && diagnostic.GetMessage().Contains("duplicated", StringComparison.Ordinal) + )); } [Fact] public void InvalidFactoryBoundaryFailsInsteadOfBeingSilentlyDiscovered() { - (_, GeneratorDriverRunResult result) = Generate(C_CATALOG + """ + (_, GeneratorDriverRunResult result) = Generate( + C_CATALOG + """ public static class InvalidModule { [RuntimeSubsystemRegistration("invalid")] public static object Create(HostInputs context) => new object(); } - """); + """ + ); Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001"); } @@ -92,11 +98,17 @@ public static class AudioModule } """; (Compilation compilation, GeneratorDriverRunResult result) = Generate(source); - Assert.Empty(compilation.GetDiagnostics().Where(static diagnostic => - diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning)); + Assert.Empty( + compilation.GetDiagnostics().Where(static diagnostic => ( + diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning + )) + ); Assert.Empty(result.Diagnostics); - Assert.Contains("Create(inputs)", Assert.Single(Assert.Single(result.Results).GeneratedSources).SourceText.ToString(), - StringComparison.Ordinal); + Assert.Contains( + "Create(inputs)", + Assert.Single(Assert.Single(result.Results).GeneratedSources).SourceText.ToString(), + StringComparison.Ordinal + ); } [Theory] @@ -104,8 +116,10 @@ public static class AudioModule [InlineData("public static partial class Catalog", "public static partial class Catalog")] [InlineData("Build(HostInputs context)", "Build(HostInputs context)")] [InlineData("Build(HostInputs context)", "Build(ref HostInputs context)")] - public void UnsupportedCatalogShapeProducesAnExplicitDiagnostic(string original, string replacement) - { + public void UnsupportedCatalogShapeProducesAnExplicitDiagnostic( + string original, + string replacement + ) { (_, GeneratorDriverRunResult result) = Generate(C_CATALOG.Replace(original, replacement, StringComparison.Ordinal)); Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001"); Assert.Empty(Assert.Single(result.Results).GeneratedSources); @@ -116,10 +130,15 @@ private static (Compilation, GeneratorDriverRunResult) Generate(string source) string[] platformAssemblies = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host has no platform assembly list.")).Split(Path.PathSeparator); MetadataReference[] references = platformAssemblies.Append(typeof(IRuntimeSubsystem).Assembly.Location) - .Distinct(StringComparer.Ordinal).Select(static path => MetadataReference.CreateFromFile(path)).ToArray(); - CSharpCompilation input = CSharpCompilation.Create("GeneratedCompositionTests", - [CSharpSyntaxTree.ParseText(source)], references, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + .Distinct(StringComparer.Ordinal) + .Select(static path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation input = CSharpCompilation.Create( + "GeneratedCompositionTests", + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeSubsystemGenerator().AsSourceGenerator()); driver = driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out _); return (output, driver.GetRunResult()); diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs index 41647eb6b..d607666d2 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs @@ -1,16 +1,18 @@ using System; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Serialization; using Inno.Core.Serialization.Generators; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Xunit; namespace Inno.Runtime.Generators.Tests; @@ -27,7 +29,7 @@ string expectedDiagnostic string source = "using Inno.Core.Serialization; public class State : ISerializable { " + member + " }"; CSharpCompilation input = CreateCompilation("Inno.InvalidSerializationFixture", source, []); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); Assert.Contains(diagnostics, diagnostic => diagnostic.Id == expectedDiagnostic && diagnostic.Severity == DiagnosticSeverity.Error); } @@ -55,8 +57,11 @@ public sealed class Child : Parent { private Child() {} } { lifetime.LoadFromStream(new MemoryStream(parent)); Assembly assembly = lifetime.LoadFromStream(new MemoryStream(child)); - Type catalog = assembly.GetType("Inno.SerializationChildFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Type catalog = assembly.GetType( + "Inno.SerializationChildFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var source = new StaticSerializationMetadataSource([register]); Type declaration = assembly.GetType("Fixture.Child", throwOnError: true)!; @@ -77,7 +82,7 @@ public sealed class Child : Parent { private Child() {} } [Fact] public void GeneratedAccessorsRoundTripPrivateMembersHooksStructsAndClosedCollections() { - const string source = """ + const string C_SOURCE = """ using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -160,30 +165,38 @@ public static bool Run(SerializationRegistry serialization) """; string[] references = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host supplies no platform references.")).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.SerializationMetadataFixture", - [CSharpSyntaxTree.ParseText(source)], references.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.SerializationMetadataFixture", + [CSharpSyntaxTree.ParseText(C_SOURCE)], + references.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out ImmutableArray diagnostics); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); stream.Position = 0; var lifetime = new AssemblyLoadContext("serialization-metadata-fixture", isCollectible: true); try { Assembly assembly = lifetime.LoadFromStream(stream); - Type catalog = assembly.GetType("Inno.SerializationMetadataFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Type catalog = assembly.GetType( + "Inno.SerializationMetadataFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions { - catalogSource = new DotNetAssemblyCatalogSource(assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(assembly) + }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)!.GetMethod("Run")! + Func run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); Assert.Throws(() => metadata.GetMetadata(typeof(DateTime))); @@ -225,16 +238,14 @@ internal static bool Execute(SerializationRegistry serialization) public static bool Run(SerializationRegistry serialization) => __RECEIVER__Execute(serialization); } """; - source = source.Replace("__OPEN__", nested ? "private static partial class Owner {" : "") - .Replace("__CLOSE__", nested ? "}" : "") - .Replace("__RECEIVER__", nested ? "Owner." : ""); + source = source.Replace("__OPEN__", nested ? "private static partial class Owner {" : string.Empty) + .Replace("__CLOSE__", nested ? "}" : string.Empty) + .Replace("__RECEIVER__", nested ? "Owner." : string.Empty); AssertScenario(source); } [Fact] - public void PublicDeclarationCanKeepPrivateSerializedMemberTypes() - { - AssertScenario(""" + public void PublicDeclarationCanKeepPrivateSerializedMemberTypes() => AssertScenario(""" using Inno.Core.Serialization; namespace Fixture; public sealed partial class State : ISerializable @@ -256,7 +267,6 @@ public static bool Run(SerializationRegistry serialization) } } """); - } [Fact] public void PrivateDeclarationsRequireAnExplicitPartialOwner() @@ -266,19 +276,18 @@ public void PrivateDeclarationsRequireAnExplicitPartialOwner() public static class Owner { private sealed class State : ISerializable {} } """, []); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); - Assert.Contains(diagnostics, static diagnostic => diagnostic.Id == "INNOSER012" - && diagnostic.Severity == DiagnosticSeverity.Error); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); + Assert.Contains(diagnostics, static diagnostic => ( + diagnostic.Id == "INNOSER012" + && diagnostic.Severity == DiagnosticSeverity.Error + )); } [Fact] - public void OpenGenericContainingOwnersDoNotEmitUnboundShapes() - { - _ = Compile("Inno.OpenSerializationFixture", """ + public void OpenGenericContainingOwnersDoNotEmitUnboundShapes() => _ = Compile("Inno.OpenSerializationFixture", """ using Inno.Core.Serialization; public sealed class Owner { private sealed class State : ISerializable { } } """, []); - } private static void AssertScenario(string source) { @@ -287,16 +296,21 @@ private static void AssertScenario(string source) try { Assembly assembly = lifetime.LoadFromStream(new MemoryStream(bytes)); - Type catalog = assembly.GetType("Inno.PrivateSerializationFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Type catalog = assembly.GetType( + "Inno.PrivateSerializationFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions { - catalogSource = new DotNetAssemblyCatalogSource(assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(assembly) + }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)!.GetMethod("Run")! + Func run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); } @@ -313,9 +327,12 @@ MetadataReference[] additionalReferences ) { string[] references = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host supplies no platform references.")).Split(Path.PathSeparator); - return CSharpCompilation.Create(assemblyName, [CSharpSyntaxTree.ParseText(source)], + return CSharpCompilation.Create( + assemblyName, + [CSharpSyntaxTree.ParseText(source)], references.Select(static path => MetadataReference.CreateFromFile(path)).Concat(additionalReferences), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); } private static byte[] Compile( @@ -324,11 +341,14 @@ private static byte[] Compile( MetadataReference[] additionalReferences ) { GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(CreateCompilation(assemblyName, source, additionalReferences), - out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation( + CreateCompilation(assemblyName, source, additionalReferences), + out Compilation output, + out ImmutableArray diagnostics + ); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); return stream.ToArray(); } diff --git a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs index 92862f83e..030bbecd8 100644 --- a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs @@ -1,21 +1,21 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Adapter; -using Inno.Adapter.Platform; +using Inno.Adapter.Audio; using Inno.Adapter.Input; +using Inno.Adapter.Platform; +using Inno.Adapter.Presentation; +using Inno.Adapter.Rendering; using Inno.Adapter.Storage; -using Inno.Adapter.Audio; using Inno.Adapter.Text; -using Inno.Adapter.Rendering; using Inno.Adapter.UI; -using Inno.Adapter.Presentation; +using Inno.Audio; using Inno.Platform; +using Inno.Rendering; using Inno.Storage; -using Inno.Audio; using Inno.Text; -using Inno.Rendering; using Inno.UI; -using Xunit; namespace Inno.Runtime.Tests; @@ -24,26 +24,31 @@ public sealed class AdapterCatalogTests [Fact] public void PresentationRegistrationUsesAnImmutableOpenCatalog() { - var first = new TestPresentationProvider(new PresentationBackendId("test.presentation.first")); - var second = new TestPresentationProvider(new PresentationBackendId("test.presentation.second")); + var first = new TestPresentationProvider(new PresentationBackendID("test.presentation.first")); + var second = new TestPresentationProvider(new PresentationBackendID("test.presentation.second")); Assert.Throws(() => new PresentationBackendCatalog([first, first])); Assert.Throws(() => new PresentationBackendCatalog([null!])); Assert.Throws(() => new TestPresentationProvider(default)); - var providers = new List { first }; + List providers = [first]; var catalog = new PresentationBackendCatalog(providers); providers.Clear(); providers.Add(second); Assert.Equal(first.id, Assert.Single(catalog.supportedBackends)); Assert.Equal(0, first.creationCount); // This provider intentionally does not consume host resources; the catalog validates its return contract. - var options = new PresentationBackendOptions { window = null!, platformApplication = null!, renderDevice = null! }; + var options = new PresentationBackendOptions + { + window = null!, + platformApplication = null!, + renderDevice = null! + }; Assert.Throws(() => catalog.CreateContext(second.id, options)); Assert.Throws(() => catalog.CreateContext(first.id, null!)); Assert.Throws(() => catalog.CreateContext(first.id, options)); Assert.Equal(1, first.creationCount); Assert.Equal(0, second.creationCount); Assert.Throws(() => - ((IList)catalog.supportedBackends).Add(second.id)); + ((IList)catalog.supportedBackends).Add(second.id)); } [Fact] @@ -53,49 +58,49 @@ public void CustomIdentitiesAreAcceptedWithoutCreatingServices() catalog.selection.Validate(catalog); Assert.Equal(0, catalog.creationCount); Assert.Throws(() => - new AdapterSelection { platform = new PlatformBackendId("missing.platform") }.Validate(catalog)); + new AdapterSelection { platform = new PlatformBackendID("missing.platform") }.Validate(catalog)); Assert.Equal(0, catalog.creationCount); } [Fact] public void AllDomainsRejectDuplicateAndNullProviders() { - var platform = new TestPlatformProvider(new PlatformBackendId("test.platform")); + var platform = new TestPlatformProvider(new PlatformBackendID("test.platform")); Assert.Throws(() => new PlatformBackendCatalog([platform, platform])); Assert.Throws(() => new PlatformBackendCatalog([null!])); Assert.Throws(() => new TestPlatformProvider(default)); - var input = new TestInputProvider(new InputBackendId("test.input")); + var input = new TestInputProvider(new InputBackendID("test.input")); Assert.Throws(() => new InputBackendCatalog([input, input])); Assert.Throws(() => new InputBackendCatalog([null!])); Assert.Throws(() => new TestInputProvider(default)); - var storage = new TestStorageProvider(new StorageBackendId("test.storage")); + var storage = new TestStorageProvider(new StorageBackendID("test.storage")); Assert.Throws(() => new StorageBackendCatalog([storage, storage])); Assert.Throws(() => new StorageBackendCatalog([null!])); Assert.Throws(() => new TestStorageProvider(default)); - var audio = new TestAudioProvider(new AudioBackendId("test.audio")); + var audio = new TestAudioProvider(new AudioBackendID("test.audio")); Assert.Throws(() => new AudioBackendCatalog([audio, audio])); Assert.Throws(() => new AudioBackendCatalog([null!])); Assert.Throws(() => new TestAudioProvider(default)); - var text = new TestTextProvider(new TextBackendId("test.text")); + var text = new TestTextProvider(new TextBackendID("test.text")); Assert.Throws(() => new TextBackendCatalog([text, text])); Assert.Throws(() => new TextBackendCatalog([null!])); Assert.Throws(() => new TestTextProvider(default)); - var rendering = new TestRenderingProvider(new RenderingBackendId("test.rendering")); + var rendering = new TestRenderingProvider(new RenderingBackendID("test.rendering")); Assert.Throws(() => new RenderingBackendCatalog([rendering, rendering])); Assert.Throws(() => new RenderingBackendCatalog([null!])); Assert.Throws(() => new TestRenderingProvider(default)); - var ui = new TestUiProvider(new UiBackendId("test.ui")); - Assert.Throws(() => new UiBackendCatalog([ui, ui])); - Assert.Throws(() => new UiBackendCatalog([null!])); - Assert.Throws(() => new TestUiProvider(default)); + var ui = new TestUIProvider(new UIBackendID("test.ui")); + Assert.Throws(() => new UIBackendCatalog([ui, ui])); + Assert.Throws(() => new UIBackendCatalog([null!])); + Assert.Throws(() => new TestUIProvider(default)); } [Fact] public void CapturedRegistrationsCannotBeChangedByTheirSourceCollection() { - var first = new TestStorageProvider(new StorageBackendId("test.storage.first")); - var second = new TestStorageProvider(new StorageBackendId("test.storage.second")); - var providers = new List { first }; + var first = new TestStorageProvider(new StorageBackendID("test.storage.first")); + var second = new TestStorageProvider(new StorageBackendID("test.storage.second")); + List providers = [first]; var catalog = new StorageBackendCatalog(providers); providers.Clear(); providers.Add(second); @@ -105,52 +110,52 @@ public void CapturedRegistrationsCannotBeChangedByTheirSourceCollection() Assert.Throws(() => catalog.CreateStorage(first.id, new StorageScope("application"))); Assert.Equal(1, first.creationCount); Assert.Equal(0, second.creationCount); - Assert.Throws(() => - ((IList)catalog.supportedBackends).Add(second.id)); + Assert.Throws(() => ((IList)catalog.supportedBackends).Add(second.id)); } [Fact] public void InvalidIdentifiersAndUnassignedSelectionsFailAtTheBoundary() { - Assert.Throws(() => new PlatformBackendId("invalid id")); - Assert.False(default(PlatformBackendId).isValid); - Assert.Throws(() => new InputBackendId("invalid id")); - Assert.False(default(InputBackendId).isValid); - Assert.Throws(() => new StorageBackendId("invalid id")); - Assert.False(default(StorageBackendId).isValid); - Assert.Throws(() => new AudioBackendId("invalid id")); - Assert.False(default(AudioBackendId).isValid); - Assert.Throws(() => new TextBackendId("invalid id")); - Assert.False(default(TextBackendId).isValid); - Assert.Throws(() => new RenderingBackendId("invalid id")); - Assert.False(default(RenderingBackendId).isValid); - Assert.Throws(() => new UiBackendId("invalid id")); - Assert.False(default(UiBackendId).isValid); + Assert.Throws(() => new PlatformBackendID("invalid id")); + Assert.False(default(PlatformBackendID).isValid); + Assert.Throws(() => new InputBackendID("invalid id")); + Assert.False(default(InputBackendID).isValid); + Assert.Throws(() => new StorageBackendID("invalid id")); + Assert.False(default(StorageBackendID).isValid); + Assert.Throws(() => new AudioBackendID("invalid id")); + Assert.False(default(AudioBackendID).isValid); + Assert.Throws(() => new TextBackendID("invalid id")); + Assert.False(default(TextBackendID).isValid); + Assert.Throws(() => new RenderingBackendID("invalid id")); + Assert.False(default(RenderingBackendID).isValid); + Assert.Throws(() => new UIBackendID("invalid id")); + Assert.False(default(UIBackendID).isValid); Assert.Throws(() => default(AdapterSelection).Validate(new TestCatalog())); } private sealed class TestCatalog : IAdapterCatalog { - private readonly TestPlatformProvider m_platform = new(new PlatformBackendId("test.platform")); - private readonly TestInputProvider m_input = new(new InputBackendId("test.input")); - private readonly TestStorageProvider m_storage = new(new StorageBackendId("test.storage")); - private readonly TestAudioProvider m_audio = new(new AudioBackendId("test.audio")); - private readonly TestTextProvider m_text = new(new TextBackendId("test.text")); - private readonly TestRenderingProvider m_rendering = new(new RenderingBackendId("test.rendering")); - private readonly TestUiProvider m_ui = new(new UiBackendId("test.ui")); + private readonly TestPlatformProvider m_platform = new(new PlatformBackendID("test.platform")); + private readonly TestInputProvider m_input = new(new InputBackendID("test.input")); + private readonly TestStorageProvider m_storage = new(new StorageBackendID("test.storage")); + private readonly TestAudioProvider m_audio = new(new AudioBackendID("test.audio")); + private readonly TestTextProvider m_text = new(new TextBackendID("test.text")); + private readonly TestRenderingProvider m_rendering = new(new RenderingBackendID("test.rendering")); + private readonly TestUIProvider m_ui = new(new UIBackendID("test.ui")); public TestCatalog() { - platform = new PlatformBackendCatalog([m_platform]); - input = new InputBackendCatalog([m_input]); - storage = new StorageBackendCatalog([m_storage]); - audio = new AudioBackendCatalog([m_audio]); - text = new TextBackendCatalog([m_text]); - rendering = new RenderingBackendCatalog([m_rendering]); - ui = new UiBackendCatalog([m_ui]); + this.platform = new PlatformBackendCatalog([m_platform]); + this.input = new InputBackendCatalog([m_input]); + this.storage = new StorageBackendCatalog([m_storage]); + this.audio = new AudioBackendCatalog([m_audio]); + this.text = new TextBackendCatalog([m_text]); + this.rendering = new RenderingBackendCatalog([m_rendering]); + this.ui = new UIBackendCatalog([m_ui]); } - public AdapterSelection selection => new() + public AdapterSelection selection + => new() { platform = m_platform.id, input = m_input.id, @@ -161,7 +166,14 @@ public TestCatalog() ui = m_ui.id }; - public int creationCount => m_platform.creationCount + m_input.creationCount + m_storage.creationCount + m_audio.creationCount + m_text.creationCount + m_rendering.creationCount + m_ui.creationCount; + public int creationCount + => m_platform.creationCount + + m_input.creationCount + + m_storage.creationCount + + m_audio.creationCount + + m_text.creationCount + + m_rendering.creationCount + + m_ui.creationCount; public IPlatformBackendFactory platform { get; } public IInputBackendFactory input { get; } @@ -169,12 +181,13 @@ public TestCatalog() public IAudioBackendFactory audio { get; } public ITextBackendFactory text { get; } public IRenderingBackendFactory rendering { get; } - public IUiBackendFactory ui { get; } + public IUIBackendFactory ui { get; } } private sealed class TestPlatformProvider : PlatformBackendProvider { - public TestPlatformProvider(PlatformBackendId id) : base(id) { } + public TestPlatformProvider(PlatformBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -187,7 +200,8 @@ public override IPlatformApplication CreateApplication() private sealed class TestInputProvider : InputBackendProvider { - public TestInputProvider(InputBackendId id) : base(id) { } + public TestInputProvider(InputBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -202,7 +216,8 @@ bool acceptAllWindows private sealed class TestStorageProvider : StorageBackendProvider { - public TestStorageProvider(StorageBackendId id) : base(id) { } + public TestStorageProvider(StorageBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -215,7 +230,8 @@ public override IApplicationStorage CreateStorage(StorageScope scope) private sealed class TestAudioProvider : AudioBackendProvider { - public TestAudioProvider(AudioBackendId id) : base(id) { } + public TestAudioProvider(AudioBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -228,7 +244,8 @@ public override IAudioDevice CreateDevice(AudioBackendOptions options) private sealed class TestTextProvider : TextBackendProvider { - public TestTextProvider(TextBackendId id) : base(id) { } + public TestTextProvider(TextBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -241,7 +258,8 @@ public override ITextBackend CreateBackend() private sealed class TestRenderingProvider : RenderingBackendProvider { - public TestRenderingProvider(RenderingBackendId id) : base(id) { } + public TestRenderingProvider(RenderingBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -255,13 +273,14 @@ public override IRenderLayerCompositionProgramProvider CreateCompositionProgramP => throw new InvalidOperationException("Registration validation must not create composition programs."); } - private sealed class TestUiProvider : UiBackendProvider + private sealed class TestUIProvider : UIBackendProvider { - public TestUiProvider(UiBackendId id) : base(id) { } + public TestUIProvider(UIBackendID id) + : base(id) {} public int creationCount { get; private set; } - public override IUiBackend CreateBackend() + public override IUIBackend CreateBackend() { creationCount++; return null!; @@ -270,7 +289,8 @@ public override IUiBackend CreateBackend() private sealed class TestPresentationProvider : PresentationBackendProvider { - public TestPresentationProvider(PresentationBackendId id) : base(id) { } + public TestPresentationProvider(PresentationBackendID id) + : base(id) {} public int creationCount { get; private set; } @@ -281,4 +301,3 @@ public override IPresentationContext CreateContext(PresentationBackendOptions op } } } - diff --git a/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs b/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs index 400122481..76d04eec1 100644 --- a/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs @@ -4,8 +4,8 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Inno.Extensibility.Modules; using Xunit; +using Inno.Extensibility.Modules; namespace Inno.Runtime.Tests; @@ -16,11 +16,16 @@ public async Task IndependentModuleHostsCanPublishTheSameStaticAssemblyConcurren { // A separate linked instance keeps the test host's own classification unchanged. Assembly assembly = Assembly.Load(File.ReadAllBytes(typeof(AssemblyClassificationTests).Assembly.Location)); - var source = new StaticModuleSource("Shared", AssemblyDomain.InnoScripting, - AssemblyScope.Runtime, [assembly], []); - const int workerCount = 8; - using var ready = new Barrier(workerCount); - Task[] workers = Enumerable.Range(0, workerCount).Select(workerIndex => Task.Factory.StartNew( + var source = new StaticModuleSource( + "Shared", + AssemblyDomain.InnoScripting, + AssemblyScope.Runtime, + [assembly], + [] + ); + const int C_WORKER_COUNT = 8; + using var ready = new Barrier(C_WORKER_COUNT); + Task[] workers = Enumerable.Range(0, C_WORKER_COUNT).Select(workerIndex => Task.Factory.StartNew( () => { using var modules = new ModuleHost(new ModuleHostOptions @@ -40,7 +45,8 @@ public async Task IndependentModuleHostsCanPublishTheSameStaticAssemblyConcurren }, CancellationToken.None, TaskCreationOptions.LongRunning, - TaskScheduler.Default)).ToArray(); + TaskScheduler.Default + )).ToArray(); await Task.WhenAll(workers).WaitAsync(TimeSpan.FromSeconds(30)); } } diff --git a/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs b/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs index bd12dfe6f..eb6a56c6e 100644 --- a/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs @@ -1,13 +1,12 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; - -using Inno.Core.Settings; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Core.Settings; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -49,27 +48,29 @@ public void PresentationRejectsInvalidReferenceResolution() [Fact] public void RuntimeHostRegistersDefaultPresentationProjectSetting() { - string directory = Path.Combine( - Path.GetTempPath(), - "InnoGamePresentationTests", - Guid.NewGuid().ToString("N")); + string directory = Path.Combine(Path.GetTempPath(), "InnoGamePresentationTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); try { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(GamePresentationSettingsTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(GamePresentationSettingsTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), host.types, host.serialization, - new ProjectId("tests.runtime"), - SerializationContext.empty); + new ProjectID("tests.runtime"), + SerializationContext.empty + ); settings.RebuildCurrent(); GamePresentationSettings presentation = settings.Get( - GamePresentationSettings.settingId); + GamePresentationSettings.settingID + ); Assert.True(presentation.preserveAspectRatio); Assert.Equal(1280, presentation.referenceWidth); diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs index 54396f6c3..ec3b2e979 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs @@ -1,9 +1,10 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -23,7 +24,6 @@ using Inno.Player.Runtime; using Inno.Shell; using Inno.Storage; -using Xunit; namespace Inno.Runtime.Tests; @@ -53,33 +53,49 @@ public async Task PreparedContentIsCheckedAndRetiredBeforeAnyPlatformAdapterStar }; PlayerContentMetadata metadata; using (EngineHost metadataOwner = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build()) using (SerializationGeneration serialization = metadataOwner.serialization.CaptureGeneration()) { - string hash = new string('A', 64); - metadata = new PlayerContentMetadata(RuntimeManifestEnvelope.Encode(manifest, serialization), + var hash = new string('A', 64); + metadata = new PlayerContentMetadata( + RuntimeManifestEnvelope.Encode(manifest, serialization), serialization.Serialize(new RuntimeContentCatalog { - contentHash = hash, packFileName = $"content-{hash}.pack", - snapshotFingerprint = hash, runtimeAssemblyCount = 1 - })); + contentHash = hash, + packFileName = $"content-{hash}.pack", + snapshotFingerprint = hash, + runtimeAssemblyCount = 1 + }) + ); } using var cancellation = new CancellationTokenSource(); var source = new PreparedSource(metadata, failure, cancellation); var modules = new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly); - var activator = new StaticPlayerModuleActivator(GameCodeDeployment.FromManifest(manifest.modules), + var activator = new StaticPlayerModuleActivator( + GameCodeDeployment.FromManifest(manifest.modules), new Dictionary> { ["Game"] = [typeof(PlayerContentSourceTests).Assembly] - }); + } + ); PlayerLaunchOptions options = CreateOptions(modules, source, activator); if (failure == "missing") + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } else if (failure == "mismatch") + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } else + { await Assert.ThrowsAnyAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } Assert.Equal(1, source.preparations); Assert.Equal(failure == "missing" ? 0 : 1, source.store?.disposals ?? 0); Assert.Throws(() => modules.GetAssemblies()); @@ -102,16 +118,19 @@ public void MetadataCopiesBothDocumentsBeforeTheBorrowedSourceCanReuseItsBuffers [Theory] [InlineData(false)] [InlineData(true)] - public async Task MetadataFailureRetiresTheTransferredModuleOwnerBeforeAnyAdapterOrContentPreparation( - bool malformed - ) { + public async Task MetadataFailureRetiresTheTransferredModuleOwnerBeforeAnyAdapterOrContentPreparation(bool malformed) + { var source = new MemorySource { malformed = malformed }; var modules = new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly); PlayerLaunchOptions options = CreateOptions(modules, source); if (malformed) + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options)); + } else + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options)); + } Assert.Equal(1, source.metadataReads); Assert.Equal(0, source.preparations); Assert.Throws(() => modules.GetAssemblies()); @@ -137,15 +156,17 @@ private static PlayerLaunchOptions CreateOptions( IPlayerModuleActivator? activator = null ) => new() { - adapterSelection = new Inno.Adapter.AdapterSelection(), + adapterSelection = new AdapterSelection(), modules = modules, types = new ReflectionTypeCatalogSource(), serializationMetadata = new ReflectionSerializationMetadataSource(), adapters = new RejectedAdapterCatalog(), contentSource = source, createStorage = _ => throw new InvalidOperationException("Storage must not start before content validation."), - moduleActivator = activator ?? new StaticPlayerModuleActivator(new GameCodeDeployment([]), - new Dictionary>()), + moduleActivator = activator ?? new StaticPlayerModuleActivator( + new GameCodeDeployment([]), + new Dictionary>() + ), frameDriver = new PollingShellFrameDriver(), logDeliveryMode = LogDeliveryMode.Inline }; @@ -171,10 +192,14 @@ public ValueTask PrepareAsync( preparations++; Assert.Equal("tests.memory", scope.value); if (failure == "missing") + { return ValueTask.FromResult(null!); + } store = new PreparedStore(failure == "mismatch" ? null : pack); if (failure == "canceled") + { cancellation.Cancel(); + } return ValueTask.FromResult(store); } } @@ -186,7 +211,9 @@ private sealed class PreparedStore(ContentPackDescriptor? expected) : IRuntimeCo public ContentPackDescriptor descriptor => expected ?? m_content.descriptor; public ContentPackIndex index => m_content.index; + public ContentReadLease Acquire(ContentKey key) => m_content.Acquire(key); + public void Dispose() { disposals++; @@ -204,8 +231,8 @@ public ValueTask ReadMetadataAsync(CancellationToken canc { metadataReads++; return malformed - ? ValueTask.FromResult(new PlayerContentMetadata([1], [2])) - : ValueTask.FromException(new IOException("Metadata unavailable.")); + ? ValueTask.FromResult(new PlayerContentMetadata([1], [2])) + : ValueTask.FromException(new IOException("Metadata unavailable.")); } public ValueTask PrepareAsync( @@ -227,7 +254,7 @@ private sealed class RejectedAdapterCatalog : IAdapterCatalog public IRenderingBackendFactory rendering => throw Rejected(); public IAudioBackendFactory audio => throw Rejected(); public ITextBackendFactory text => throw Rejected(); - public IUiBackendFactory ui => throw Rejected(); + public IUIBackendFactory ui => throw Rejected(); private static InvalidOperationException Rejected() => new("An adapter cannot be selected before deployment metadata is validated."); diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs index 39ad3f760..d3bcb4d62 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -13,28 +14,29 @@ using Inno.Audio; using Inno.Audio.Runtime; using Inno.Core.Events; +using Inno.Core.Mathematics; using Inno.Input; using Inno.Platform; using Inno.Rendering; using Inno.Storage; using Inno.Text; using Inno.UI; -using Xunit; namespace Inno.Runtime.Tests; public sealed partial class PlayerWithoutFileSystemTests { private sealed class MemoryAdapters : IAdapterCatalog, IPlatformBackendFactory, IInputBackendFactory, - IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUiBackendFactory + IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUIBackendFactory { private readonly MemoryRenderDevice m_render; + public MemoryAdapters(bool failFrame) { - application = new MemoryApplication(retired); + this.application = new MemoryApplication(retired); m_render = new MemoryRenderDevice(retired, failFrame); } - internal int completedFrames => m_render.completedFrames; + public MemoryApplication application { get; } public List retired { get; } = []; public IPlatformBackendFactory platform => this; @@ -43,36 +45,46 @@ public MemoryAdapters(bool failFrame) public IStorageBackendFactory storage => this; public IAudioBackendFactory audio => this; public ITextBackendFactory text => this; - public IUiBackendFactory ui => this; - IReadOnlyList IPlatformBackendFactory.supportedBackends => [PlatformBackendId.sdl3]; - IReadOnlyList IInputBackendFactory.supportedBackends => [InputBackendId.events]; - IReadOnlyList IRenderingBackendFactory.supportedBackends => [RenderingBackendId.bgfx]; - IReadOnlyList IStorageBackendFactory.supportedBackends => [StorageBackendId.fileSystem]; - IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendId.miniAudio]; - IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendId.freeTypeHarfBuzz]; - IReadOnlyList IUiBackendFactory.supportedBackends => [UiBackendId.rmlUi]; - public IPlatformApplication CreateApplication(PlatformBackendId backend) => application; + public IUIBackendFactory ui => this; + IReadOnlyList IPlatformBackendFactory.supportedBackends => [PlatformBackendID.sdl3]; + IReadOnlyList IInputBackendFactory.supportedBackends => [InputBackendID.events]; + IReadOnlyList IRenderingBackendFactory.supportedBackends => [RenderingBackendID.bgfx]; + IReadOnlyList IStorageBackendFactory.supportedBackends => [StorageBackendID.fileSystem]; + IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendID.miniAudio]; + IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendID.freeTypeHarfBuzz]; + IReadOnlyList IUIBackendFactory.supportedBackends => [UIBackendID.rmlUI]; + + public IPlatformApplication CreateApplication(PlatformBackendID backend) => application; + public IInputEventSource CreateEventSource( - InputBackendId backend, + InputBackendID backend, IPlatformWindow window, bool acceptAllWindows ) => new MemoryInputSource(retired); + public IRenderDevice CreateDevice( - RenderingBackendId backend, + RenderingBackendID backend, RenderingBackendOptions options ) => m_render; - public IApplicationStorage CreateStorage( - StorageBackendId backend, - StorageScope scope - ) => new MemoryStorage(); + public IAudioDevice CreateDevice( - AudioBackendId backend, + AudioBackendID backend, AudioBackendOptions options = default ) => new MutedAudioDevice(); - public ITextBackend CreateBackend(TextBackendId backend) => new MemoryText(retired); - public IUiBackend CreateBackend(UiBackendId backend) => new MemoryUi(retired); - public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) + + public IApplicationStorage CreateStorage( + StorageBackendID backend, + StorageScope scope + ) => new MemoryStorage(); + + public ITextBackend CreateBackend(TextBackendID backend) => new MemoryText(retired); + + public IUIBackend CreateBackend(UIBackendID backend) => new MemoryUI(retired); + + public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendID backend) => new UnusedCompositionPrograms(); + + internal int completedFrames => m_render.completedFrames; } private sealed class MemoryApplication(List retired) : IPlatformApplication @@ -80,21 +92,35 @@ private sealed class MemoryApplication(List retired) : IPlatformApplicat private Action? m_redraw; public Queue events { get; } = new(); public int redrawSubscribers { get; private set; } + public event Action? redrawRequested { - add { m_redraw += value; redrawSubscribers++; } - remove { m_redraw -= value; redrawSubscribers--; } + add + { + m_redraw += value; + redrawSubscribers++; + } + remove + { + m_redraw -= value; + redrawSubscribers--; + } } + public IPlatformWindow CreateWindow(PlatformWindowOptions options) => new MemoryWindow(retired); + public bool PollEvent(out Event? evnt) => events.TryDequeue(out evnt); + public IReadOnlyList GetWindows() => []; + public void RequestRedraw() => m_redraw?.Invoke(1); + public void Dispose() => retired.Add("platform"); } private sealed class MemoryWindow(List retired) : IPlatformWindow { - public uint windowId => 1; + public uint windowID => 1; public string title => "Lifecycle fixture"; public int width => 32; public int height => 32; @@ -102,15 +128,20 @@ private sealed class MemoryWindow(List retired) : IPlatformWindow public int pixelHeight => 32; public bool isClosed { get; private set; } public bool isFocused => true; + public void RequestClose() => isClosed = true; + public void Dispose() => retired.Add("window"); } private sealed class MemoryInputSource(List retired) : IInputEventSource { private readonly EventInputSource m_source = new(1); + public IInputBackend CreateBackend() => m_source.CreateBackend(); + public void ProcessEvent(Event evnt) => m_source.ProcessEvent(evnt); + public void Dispose() { m_source.Dispose(); @@ -125,12 +156,25 @@ bool failFrame { private bool m_rejectedFrame; internal int completedFrames; - public GraphicsCapabilities capabilities { get; } = new(GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 0), [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], [], [], false, false); + + public GraphicsCapabilities capabilities { get; } = new( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 0), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [], + [], + false, + false + ); + public uint generation => 1; public RenderPresentationSize? primaryPresentationSize { get; private set; } public bool primaryPresentationEncodesSrgb => true; - public void SetVerticalSync(bool enabled) { } + + public void SetVerticalSync(bool enabled) {} + public void BeginFrame() { if (failFrame && !m_rejectedFrame) @@ -139,7 +183,9 @@ public void BeginFrame() throw new InvalidOperationException("Expected frame failure."); } } + public uint EndFrame() => 1; + public void Execute( CompiledRenderGraph graph, ulong frameIndex @@ -147,129 +193,163 @@ ulong frameIndex Assert.NotNull(graph); completedFrames++; } + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + public PersistentTextureHandle CreateTexture( RenderTextureDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, int arrayLayer = 0 ) => throw new NotSupportedException(); + public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, ReadOnlySpan data ) => throw new NotSupportedException(); + public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, int mipLevel = 0 ) => throw new NotSupportedException(); + public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, out RenderTextureReadbackResult? result ) => throw new NotSupportedException(); + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => throw new NotSupportedException(); + public void DestroyTexture(PersistentTextureHandle texture) => throw new NotSupportedException(); + public PersistentBufferHandle CreateBuffer( PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name ) => throw new NotSupportedException(); + public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, int startElement = 0 ) => throw new NotSupportedException(); + public void DestroyBuffer(PersistentBufferHandle buffer) => throw new NotSupportedException(); + public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => throw new NotSupportedException(); + public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => throw new NotSupportedException(); + public void Dispose() => retired.Add("render"); } - private sealed class MemoryUi(List retired) : IUiBackend + + private sealed class MemoryUI(List retired) : IUIBackend { - internal UiInputSnapshot? lastInput { get; private set; } + public string implementationID => "tests.ui"; + public UIBackendCapabilities capabilities { get; } = new([new UIDocumentLanguageID("tests.ui-language")], true); + + public UIContextHandle CreateContext(UIContextOptions options) => new(1); - public string implementationId => "tests.ui"; - public UiBackendCapabilities capabilities { get; } = new([new("tests.ui-language")], true); + public void DestroyContext(UIContextHandle context) {} - public UiContextHandle CreateContext(UiContextOptions options) => new(1); - public void DestroyContext(UiContextHandle context) { } public void SetViewport( - UiContextHandle context, + UIContextHandle context, int width, int height, float density - ) { } - public UiDocumentHandle LoadDocument( - UiContextHandle context, - UiDocumentSource source + ) {} + + public UIDocumentHandle LoadDocument( + UIContextHandle context, + UIDocumentSource source ) => new(1); + public void ShowDocument( - UiContextHandle context, - UiDocumentHandle document - ) { } + UIContextHandle context, + UIDocumentHandle document + ) {} + public void HideDocument( - UiContextHandle context, - UiDocumentHandle document - ) { } + UIContextHandle context, + UIDocumentHandle document + ) {} + public void CloseDocument( - UiContextHandle context, - UiDocumentHandle document - ) { } + UIContextHandle context, + UIDocumentHandle document + ) {} + public bool SetText( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string text ) => true; + public bool SetContent( - UiContextHandle context, - UiDocumentHandle document, - string elementId, - UiDocumentFragment content + UIContextHandle context, + UIDocumentHandle document, + string elementID, + UIDocumentFragment content ) => true; + public bool SetAttribute( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string name, string value ) => true; + public bool SetClass( - UiContextHandle context, - UiDocumentHandle document, - string elementId, + UIContextHandle context, + UIDocumentHandle document, + string elementID, string className, bool active ) => true; - public void RegisterFont(UiFontRegistration registration) { } + + public void RegisterFont(UIFontRegistration registration) {} + public void RegisterTexture( - UiContextHandle context, + UIContextHandle context, string source, - UiTextureData texture - ) { } + UITextureData texture + ) {} + public bool HasElementAtPoint( - UiContextHandle context, - Inno.Core.Mathematics.Vector2 position + UIContextHandle context, + Vector2 position ) => false; + public void Update( - UiContextHandle context, - UiInputSnapshot input + UIContextHandle context, + UIInputSnapshot input ) => lastInput = input; - public UiRenderFrame Render(UiContextHandle context) => UiRenderFrame.empty; - public IReadOnlyList DrainEvents(UiContextHandle context) => []; + + public UIRenderFrame Render(UIContextHandle context) => UIRenderFrame.empty; + + public IReadOnlyList DrainEvents(UIContextHandle context) => []; + public void Dispose() => retired.Add("ui"); + + internal UIInputSnapshot? lastInput { get; private set; } } private sealed class UnusedCompositionPrograms : IRenderLayerCompositionProgramProvider @@ -291,18 +371,22 @@ public TextFontHandle LoadFont( ReadOnlySpan data, int faceIndex ) => throw new NotSupportedException(); + public void ReleaseFont(TextFontHandle font) => throw new NotSupportedException(); + public TextLayout Shape( TextFontHandle font, string text, TextStyle style, TextShapingOptions options ) => throw new NotSupportedException(); + public GlyphBitmap Rasterize( TextFontHandle font, - uint glyphId, + uint glyphID, float fontSize ) => throw new NotSupportedException(); + public void Dispose() => retired.Add("text"); } @@ -312,19 +396,23 @@ public ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(false); + public ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(null); + public ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default ) => throw new NotSupportedException(); + public ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(false); + public ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs index 767fcc616..7352045a0 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs @@ -4,15 +4,24 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter; +using Inno.Adapter.Audio; +using Inno.Adapter.Input; using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Platform; +using Inno.Adapter.Rendering; using Inno.Adapter.Serialization.DotNet; +using Inno.Adapter.Storage; +using Inno.Adapter.Text; +using Inno.Adapter.UI; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Content; using Inno.Content.Testing; using Inno.Core.Execution; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -21,7 +30,6 @@ using Inno.Scene; using Inno.Shell; using Inno.Storage; -using Xunit; namespace Inno.Runtime.Tests; @@ -37,17 +45,18 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin MemoryPlayerSource source = CreateDeployment(root); Assert.False(Directory.Exists(root)); var modules = new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly); - var deployment = GameCodeDeployment.FromManifest(source.manifest.modules); + GameCodeDeployment deployment = GameCodeDeployment.FromManifest(source.manifest.modules); var options = new PlayerLaunchOptions { - adapterSelection = new Inno.Adapter.AdapterSelection { - platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, - input = Inno.Adapter.Input.InputBackendId.events, - rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, - storage = Inno.Adapter.Storage.StorageBackendId.fileSystem, - audio = Inno.Adapter.Audio.AudioBackendId.miniAudio, - text = Inno.Adapter.Text.TextBackendId.freeTypeHarfBuzz, - ui = Inno.Adapter.UI.UiBackendId.rmlUi + adapterSelection = new AdapterSelection + { + platform = PlatformBackendID.sdl3, + input = InputBackendID.events, + rendering = RenderingBackendID.bgfx, + storage = StorageBackendID.fileSystem, + audio = AudioBackendID.miniAudio, + text = TextBackendID.freeTypeHarfBuzz, + ui = UIBackendID.rmlUI }, modules = modules, types = new ReflectionTypeCatalogSource(), @@ -55,11 +64,13 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin contentSource = source, adapters = adapters, createStorage = _ => new MemoryStorage(), - moduleActivator = new StaticPlayerModuleActivator(deployment, + moduleActivator = new StaticPlayerModuleActivator( + deployment, new Dictionary> { ["Game"] = [typeof(PlayerWithoutFileSystemTests).Assembly] - }), + } + ), frameDriver = new PollingShellFrameDriver(), smokeFrameLimit = 3, windowVisible = false, @@ -67,10 +78,14 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin logDeliveryMode = LogDeliveryMode.Inline }; if (failFrame) + { Assert.Throws(() => OwnerThreadExecution.Run(() => PlayerApplication.RunAsync(options))); + } else + { Assert.Equal(0, OwnerThreadExecution.Run(() => PlayerApplication.RunAsync(options))); + } Assert.Equal(1, source.metadataReads); Assert.Equal(1, source.preparations); Assert.Equal(1, source.disposals); @@ -90,22 +105,35 @@ private static MemoryPlayerSource CreateDeployment(string root) var identities = new IdentityAllocator(); var world = new SceneWorld(identities, engine.types); using IDisposable sceneScope = world.EnterScope(); - using var assets = new AssetPipeline(engine.modules, engine.types, engine.serialization, - identities, engine.diagnostics, engine.logs, + using var assets = new AssetPipeline( + engine.modules, + engine.types, + engine.serialization, + identities, + engine.diagnostics, + engine.logs, AssetPipelineOptions.Create(assetsDirectory, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false - }); - Assert.True(assets.Save(AssetPath.Project("Startup.iscene"), - SceneAsset.Capture(new GameScene("Memory scene"), engine.serialization, assets))); + } + ); + Assert.True( + assets.Save( + AssetPath.Project("Startup.iscene"), + SceneAsset.Capture(new GameScene("Memory scene"), engine.serialization, assets) + ) + ); using var settings = new ProjectSettingsStore( - new FileByteDocumentStore(Path.Combine(root, SettingsFileNames.project)), - engine.types, engine.serialization, new ProjectId("tests.memory.player"), - AssetSerializationContext.Create(assets)); + new FileByteDocumentStore(Path.Combine(root, SettingsFileNames.C_PROJECT)), + engine.types, + engine.serialization, + new ProjectID("tests.memory.player"), + AssetSerializationContext.Create(assets) + ); string exported = Path.Combine(root, "Exported"); assets.ExportRuntimeArtifacts(exported); - File.WriteAllBytes(Path.Combine(exported, SettingsFileNames.project), settings.CaptureDocument()); - var content = ContentTestStore.FromDirectory(exported); + File.WriteAllBytes(Path.Combine(exported, SettingsFileNames.C_PROJECT), settings.CaptureDocument()); + ContentTestStore content = ContentTestStore.FromDirectory(exported); var manifest = new GameRuntimeManifest { applicationId = "tests.memory.player", @@ -123,15 +151,20 @@ private static MemoryPlayerSource CreateDeployment(string root) }] }; using SerializationGeneration serialization = engine.serialization.CaptureGeneration(); - return new MemoryPlayerSource(manifest, content, - new PlayerContentMetadata(RuntimeManifestEnvelope.Encode(manifest, serialization), + return new MemoryPlayerSource( + manifest, + content, + new PlayerContentMetadata( + RuntimeManifestEnvelope.Encode(manifest, serialization), serialization.Serialize(new RuntimeContentCatalog { contentHash = content.descriptor.contentHash, packFileName = content.descriptor.fileName, snapshotFingerprint = new string('A', 64), runtimeAssemblyCount = 1 - }))); + }) + ) + ); } finally { diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs index 096b9c74f..16c25eafb 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Content; using Inno.Content.Testing; using Inno.Core.Logging; using Inno.Core.Serialization; -using Xunit; namespace Inno.Runtime.Tests; @@ -31,7 +31,7 @@ [new ContentKey("AssetDatabase/Catalog.snapshot")] = catalog using RuntimeSession first = host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Player, - applicationId = "memory.first", + applicationID = "memory.first", contentStore = content, jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createLogSink = _ => firstLog @@ -39,15 +39,19 @@ [new ContentKey("AssetDatabase/Catalog.snapshot")] = catalog using RuntimeSession second = host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Player, - applicationId = "memory.second", + applicationID = "memory.second", contentStore = content, jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createLogSink = _ => secondLog }); using (first.EnterExecutionScope()) + { Log.Info(typeof(PlayerWithoutFileSystemTests), "first"); + } using (second.EnterExecutionScope()) + { Log.Info(typeof(PlayerWithoutFileSystemTests), "second"); + } first.Tick(0.01f); second.Tick(0.02f); Assert.Equal("first", Assert.Single(firstLog.messages)); @@ -68,7 +72,7 @@ public void AFailingHostLogFactoryCompensatesStartupAndKeepsTheHostUsable() Assert.Throws(() => host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Play, - applicationId = "memory.invalid", + applicationID = "memory.invalid", jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createLogSink = _ => null! })); @@ -76,17 +80,21 @@ public void AFailingHostLogFactoryCompensatesStartupAndKeepsTheHostUsable() using RuntimeSession valid = host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Play, - applicationId = "memory.valid", + applicationID = "memory.valid", jobExecutionMode = RuntimeJobExecutionMode.SingleThread }); valid.Tick(0.01f); } - private static EngineHost CreateHost() => new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) - .UseLogDelivery(LogDeliveryMode.Inline) - .Build(); + private static EngineHost CreateHost() + => new EngineHostBuilder() + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .UseLogDelivery(LogDeliveryMode.Inline) + .Build(); private sealed class MemoryLog : ILogSink, IDisposable { @@ -94,6 +102,7 @@ private sealed class MemoryLog : ILogSink, IDisposable internal int disposals; public void Receive(LogEntry entry) => messages.Add(entry.message); + public void Dispose() => disposals++; } } diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs index fd845881a..bdba06285 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs @@ -1,14 +1,14 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Runtime.Contracts; -using Xunit; namespace Inno.Runtime.Tests; @@ -19,26 +19,32 @@ public sealed class RuntimeRetirementTests [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] - public void FailedStartupDrainsBeforeReleasingFactoryResources(bool hostLifetime, bool failAttach) - { + public void FailedStartupDrainsBeforeReleasingFactoryResources( + bool hostLifetime, + bool failAttach + ) { string root = Path.Combine(Path.GetTempPath(), "InnoStartupTests", Guid.NewGuid().ToString("N")); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); var resource = new Resource(); var factory = new FailingFactory(resource, hostLifetime, failAttach); try { Exception error = hostLifetime - ? Assert.Throws(() => host.CreateHostPipeline([factory])) - : Assert.Throws(() => host.CreateSession(new RuntimeSessionOptions - { - applicationId = "startup.test", - kind = RuntimeSessionKind.Play, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "startup.test"), "Logs")), - jobExecutionMode = RuntimeJobExecutionMode.SingleThread, - createSubsystems = _ => [factory] - })); + ? Assert.Throws(() => host.CreateHostPipeline([factory])) + : Assert.Throws(() => host.CreateSession(new RuntimeSessionOptions + { + applicationID = "startup.test", + kind = RuntimeSessionKind.Play, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "startup.test"), "Logs")), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread, + createSubsystems = _ => [factory] + })); Assert.Equal("startup failure", error.Message); Assert.True(factory.observedRetainedResource); Assert.True(resource.disposed); @@ -51,7 +57,9 @@ public void FailedStartupDrainsBeforeReleasingFactoryResources(bool hostLifetime { host.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -60,13 +68,17 @@ public void StopHookPendingRetainsDependenciesWithoutRepeatingCompletedOwners() { string root = Path.Combine(Path.GetTempPath(), "InnoStopTests", Guid.NewGuid().ToString("N")); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); var pending = new StopPendingSubsystem(); var resource = new Resource(); RuntimeSession session = host.CreateSession(new RuntimeSessionOptions { - applicationId = "stop.test", + applicationID = "stop.test", kind = RuntimeSessionKind.Play, createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "stop.test"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, @@ -89,13 +101,17 @@ public void PendingSessionRetainsDependenciesAndCanBeRetriedThroughHost() var pending = new PendingSubsystem(); var resource = new Resource(); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); try { RuntimeSession session = host.CreateSession(new RuntimeSessionOptions { - applicationId = "retirement.test", + applicationID = "retirement.test", kind = RuntimeSessionKind.Play, createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "retirement.test"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, @@ -118,13 +134,19 @@ public void PendingSessionRetainsDependenciesAndCanBeRetriedThroughHost() pending.work.TrySetResult(); host.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } - private sealed class Factory(PendingSubsystem subsystem, Resource resource) : IRuntimeSubsystemFactory + private sealed class Factory( + PendingSubsystem subsystem, + Resource resource + ) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.pending")); + public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemID("tests.pending")); + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); @@ -136,53 +158,80 @@ private sealed class PendingSubsystem : RuntimeSubsystem { internal TaskCompletionSource work { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal bool stopped { get; private set; } + protected override void OnStart() => lifetime.Track(work.Task); + protected override void OnStop() => stopped = true; } private sealed class Resource : IDisposable { + public void Dispose() + { + disposed = true; + disposeCount++; + } + internal bool disposed { get; private set; } internal int disposeCount { get; private set; } - public void Dispose() { disposed = true; disposeCount++; } } - private sealed class FailingFactory(Resource resource, bool hostLifetime, bool failAttach) : IRuntimeSubsystemFactory + private sealed class FailingFactory( + Resource resource, + bool hostLifetime, + bool failAttach + ) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.failure"), - lifetime: hostLifetime ? RuntimeSubsystemLifetime.Host : RuntimeSubsystemLifetime.Session); internal bool observedRetainedResource; + public RuntimeSubsystemDescriptor descriptor { get; } = new( + new RuntimeSubsystemID("tests.failure"), + lifetime: hostLifetime ? RuntimeSubsystemLifetime.Host : RuntimeSubsystemLifetime.Session + ); + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); if (failAttach) + { return new FailingSubsystem(this, resource); - context.resources.Track(Drain(context.resources.cancellationToken)); + } + context.resources.Track(DrainAsync(context.resources.cancellationToken)); throw new InvalidOperationException("startup failure"); } - internal async Task Drain(CancellationToken cancellationToken) + internal async Task DrainAsync(CancellationToken cancellationToken) { - try { await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); } + try + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + } catch (OperationCanceledException) { } observedRetainedResource = !resource.disposed; } - private sealed class FailingSubsystem(FailingFactory factory, Resource resource) : RuntimeSubsystem + private sealed class FailingSubsystem( + FailingFactory factory, + Resource resource + ) : RuntimeSubsystem { protected override void OnStart() { - lifetime.Track(factory.Drain(lifetime.cancellationToken)); + lifetime.Track(factory.DrainAsync(lifetime.cancellationToken)); throw new InvalidOperationException("startup failure"); } + protected override void OnStop() => Assert.False(resource.disposed); } } - private sealed class SimpleFactory(IRuntimeSubsystem subsystem, Resource resource) : IRuntimeSubsystemFactory + private sealed class SimpleFactory( + IRuntimeSubsystem subsystem, + Resource resource + ) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.stop")); + public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemID("tests.stop")); + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); @@ -194,11 +243,14 @@ private sealed class StopPendingSubsystem : RuntimeSubsystem { internal bool ready; internal int stopAttempts; + protected override void OnStop() { stopAttempts++; if (!ready) + { throw new RetirementPendingException("native drain pending"); + } } } } diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs index 53597711a..c31caab2f 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs @@ -1,17 +1,15 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; -using System.IO; using System.Collections.Generic; - -using Inno.References; +using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Logging; +using Inno.References; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; -using Xunit; - namespace Inno.Runtime.Tests; public sealed class RuntimeSessionTests : IDisposable @@ -19,21 +17,27 @@ public sealed class RuntimeSessionTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoRuntimeSessionTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); [Fact] public void InlineHostDeliveryPersistsSessionLogsBeforeTheProducerReturns() { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .UseLogDelivery(LogDeliveryMode.Inline) .Build(); RuntimeSessionOptions options = CreateOptions("inline", RuntimeSessionKind.Play); using RuntimeSession session = host.CreateSession(options); using (session.EnterExecutionScope()) + { Log.Info(typeof(RuntimeSessionTests), "session-inline-delivery"); + } string file = Assert.Single(Directory.GetFiles(Path.Combine(m_root, "Persistent", "inline", "Logs"))); using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); @@ -50,9 +54,13 @@ public void MultipleHostsAndSessionsKeepSceneAndTimeStateIsolated() using RuntimeSession second = secondHost.CreateSession(CreateOptions("second", RuntimeSessionKind.Play)); using (first.EnterExecutionScope()) + { _ = SceneManager.LoadNewScene("First Scene"); + } using (second.EnterExecutionScope()) + { _ = SceneManager.LoadNewScene("Second Scene"); + } first.Tick(0.02f); second.Tick(0.04f); @@ -104,17 +112,14 @@ public void TimeSeparatesScaledUnscaledAndPausedProgress() public void RuntimeSubsystemsFollowDependenciesAndReleaseInReverseOrder() { using EngineHost host = CreateHost("Features"); - var events = new List(); + List events = []; var first = new ProbeFeatureFactory("tests.first", [], events); - var second = new ProbeFeatureFactory( - "tests.second", - [new RuntimeSubsystemId("tests.first")], - events); + var second = new ProbeFeatureFactory("tests.second", [new RuntimeSubsystemID("tests.first")], events); RuntimeSessionOptions baseline = CreateOptions("features", RuntimeSessionKind.Play); var options = new RuntimeSessionOptions { kind = baseline.kind, - applicationId = baseline.applicationId, + applicationID = baseline.applicationID, createLogSink = baseline.createLogSink, fixedDeltaTime = baseline.fixedDeltaTime, jobExecutionMode = baseline.jobExecutionMode, @@ -126,28 +131,30 @@ [new RuntimeSubsystemId("tests.first")], session.Dispose(); Assert.Equal( - [ - "attach:tests.first", - "attach:tests.second", - "begin:tests.first", - "begin:tests.second", - "update:tests.first", - "update:tests.second", - "late:tests.first", - "late:tests.second", - "before-render:tests.first", - "before-render:tests.second", - "render:tests.first", - "render:tests.second", - "after-render:tests.second", - "after-render:tests.first", - "end:tests.second", - "end:tests.first", - "detach:tests.second", - "dispose:tests.second", - "detach:tests.first", - "dispose:tests.first" - ], events); + [ + "attach:tests.first", + "attach:tests.second", + "begin:tests.first", + "begin:tests.second", + "update:tests.first", + "update:tests.second", + "late:tests.first", + "late:tests.second", + "before-render:tests.first", + "before-render:tests.second", + "render:tests.first", + "render:tests.second", + "after-render:tests.second", + "after-render:tests.first", + "end:tests.second", + "end:tests.first", + "detach:tests.second", + "dispose:tests.second", + "detach:tests.first", + "dispose:tests.first" + ], + events + ); } [Fact] @@ -155,12 +162,12 @@ public void SessionPublishesOwnerProvidedReferenceResolversAndPreservesValidated { using EngineHost host = CreateHost("References"); RuntimeSessionOptions baseline = CreateOptions("references", RuntimeSessionKind.Play); - var kind = new ReferenceKindId("tests.runtime.reference"); + var kind = new ReferenceKindID("tests.runtime.reference"); var resolver = new MissingResolver(kind); var options = new RuntimeSessionOptions { kind = baseline.kind, - applicationId = baseline.applicationId, + applicationID = baseline.applicationID, createLogSink = baseline.createLogSink, assetResidencyBudgetBytes = 4096, fixedDeltaTime = baseline.fixedDeltaTime, @@ -185,45 +192,58 @@ public void DisposedHostRejectsNewSessions() host.Dispose(); Assert.Throws( - () => host.CreateSession(CreateOptions("disposed", RuntimeSessionKind.Edit))); + () => host.CreateSession(CreateOptions("disposed", RuntimeSessionKind.Edit)) + ); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private EngineHost CreateHost(string name) => new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); - private RuntimeSessionOptions CreateOptions(string applicationId, RuntimeSessionKind kind) - => new() - { - kind = kind, - applicationId = applicationId, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", applicationId), "Logs")), - fixedDeltaTime = 0.02f, - jobExecutionMode = RuntimeJobExecutionMode.SingleThread - }; + private RuntimeSessionOptions CreateOptions( + string applicationID, + RuntimeSessionKind kind + ) => new() + { + kind = kind, + applicationID = applicationID, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", applicationID), "Logs")), + fixedDeltaTime = 0.02f, + jobExecutionMode = RuntimeJobExecutionMode.SingleThread + }; private sealed class ProbeFeatureFactory( string id, - IReadOnlyList dependencies, - List events) : IRuntimeSubsystemFactory + IReadOnlyList dependencies, + List events + ) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId(id), - dependencies: dependencies); + new RuntimeSubsystemID(id), + dependencies: dependencies + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new ProbeFeature(descriptor.id.value, events); } - private sealed class ProbeFeature(string id, List events) : RuntimeSubsystem + private sealed class ProbeFeature( + string id, + List events + ) : RuntimeSubsystem { protected override void OnStart() => events.Add($"attach:{id}"); @@ -248,9 +268,9 @@ protected override void OnStop() } } - private sealed class MissingResolver(ReferenceKindId kind) : IReferenceResolver + private sealed class MissingResolver(ReferenceKindID kind) : IReferenceResolver { - public ReferenceKindId kindId { get; } = kind; + public ReferenceKindID kindID { get; } = kind; public ReferenceResolution Resolve(ReferenceDescriptor descriptor) => new(descriptor, ReferenceResolutionState.Missing); diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs index 11290dd25..2f63074e8 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Reload; using Inno.Runtime.Contracts; -using Xunit; namespace Inno.Runtime.Tests; @@ -18,21 +18,29 @@ public sealed class RuntimeSubsystemPolicyTests : IDisposable private readonly EngineHost m_host; public RuntimeSubsystemPolicyTests() - => m_host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + { + m_host = new EngineHostBuilder() + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); + } public void Dispose() { m_host.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] public void MissingRequiredCapabilityRejectsBeforeFactoryAllocation() { - var factory = Create("test.required", capabilities: [new RuntimeCapabilityId("test.output")]); + Factory factory = Create("test.required", capabilities: [new RuntimeCapabilityID("test.output")]); InvalidOperationException error = Assert.Throws(() => m_host.CreateHostPipeline([factory])); Assert.Contains("test.output", error.Message); Assert.Equal(0, factory.createCount); @@ -42,14 +50,14 @@ public void MissingRequiredCapabilityRejectsBeforeFactoryAllocation() [Fact] public void SuppliedCapabilitiesAndDescriptorCollectionsAreImmutableSnapshots() { - RuntimeCapabilityId[] required = [new("test.output")]; - var factory = Create("test.ready", capabilities: required); - required[0] = new RuntimeCapabilityId("test.changed"); - RuntimeCapabilityId[] supplied = [new("test.output")]; + RuntimeCapabilityID[] required = [new RuntimeCapabilityID("test.output")]; + Factory factory = Create("test.ready", capabilities: required); + required[0] = new RuntimeCapabilityID("test.changed"); + RuntimeCapabilityID[] supplied = [new RuntimeCapabilityID("test.output")]; RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([factory], supplied); - supplied[0] = new RuntimeCapabilityId("test.changed"); - Assert.Contains(new RuntimeCapabilityId("test.output"), factory.context!.capabilities); - Assert.Equal(new RuntimeCapabilityId("test.output"), factory.descriptor.requiredCapabilities[0]); + supplied[0] = new RuntimeCapabilityID("test.changed"); + Assert.Contains(new RuntimeCapabilityID("test.output"), factory.context!.capabilities); + Assert.Equal(new RuntimeCapabilityID("test.output"), factory.descriptor.requiredCapabilities[0]); Assert.Equal("test.ready", Assert.Single(pipeline.descriptors).id.value); Assert.Empty(pipeline.startupDiagnostics); } @@ -59,12 +67,18 @@ public void SuppliedCapabilitiesAndDescriptorCollectionsAreImmutableSnapshots() [InlineData(true)] public void OptionalUnavailabilityPropagatesToOptionalConsumers(bool missingCapability) { - var unavailable = Create("test.optional", RuntimeSubsystemRequirement.Optional, - capabilities: missingCapability ? [new RuntimeCapabilityId("test.absent")] : []); + Factory unavailable = Create( + "test.optional", + RuntimeSubsystemRequirement.Optional, + capabilities: missingCapability ? [new RuntimeCapabilityID("test.absent")] : [] + ); unavailable.failCreate = !missingCapability; - var consumer = Create("test.consumer", RuntimeSubsystemRequirement.Optional, - dependencies: [unavailable.descriptor.id]); - var available = Create("test.available"); + Factory consumer = Create( + "test.consumer", + RuntimeSubsystemRequirement.Optional, + dependencies: [unavailable.descriptor.id] + ); + Factory available = Create("test.available"); RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([consumer, available, unavailable]); Assert.Equal("test.available", Assert.Single(pipeline.descriptors).id.value); Assert.Equal(2, pipeline.startupDiagnostics.Count); @@ -76,9 +90,9 @@ public void OptionalUnavailabilityPropagatesToOptionalConsumers(bool missingCapa [Fact] public void RequiredConsumerCannotRunWithoutFailedOptionalDependency() { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = true; - var required = Create("test.required", dependencies: [optional.descriptor.id]); + Factory required = Create("test.required", dependencies: [optional.descriptor.id]); Assert.Throws(() => m_host.CreateHostPipeline([required, optional])); Assert.Equal(0, required.createCount); Assert.Equal(1, optional.releaseCount); @@ -89,7 +103,7 @@ public void RequiredConsumerCannotRunWithoutFailedOptionalDependency() [InlineData(true)] public void OptionalStartupIsUnavailableOnlyAfterFactoryResourcesRetire(bool failAttach) { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = !failAttach; optional.failAttach = failAttach; RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([optional]); @@ -103,7 +117,7 @@ public void OptionalStartupIsUnavailableOnlyAfterFactoryResourcesRetire(bool fai [Fact] public void OptionalRetirementFailureFaultsInsteadOfDegrading() { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = true; optional.failRelease = true; Assert.Throws(() => m_host.CreateHostPipeline([optional])); @@ -116,11 +130,14 @@ public void OptionalRetirementFailureFaultsInsteadOfDegrading() [Fact] public void OptionalMissingDependencyIsDiagnosedButCyclesStillReject() { - var missing = Create("test.missing", RuntimeSubsystemRequirement.Optional, - dependencies: [new RuntimeSubsystemId("test.absent")]); + Factory missing = Create( + "test.missing", + RuntimeSubsystemRequirement.Optional, + dependencies: [new RuntimeSubsystemID("test.absent")] + ); Assert.Single(m_host.CreateHostPipeline([missing]).startupDiagnostics); - var a = Create("test.a", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemId("test.b")]); - var b = Create("test.b", RuntimeSubsystemRequirement.Optional, dependencies: [a.descriptor.id]); + Factory a = Create("test.a", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemID("test.b")]); + Factory b = Create("test.b", RuntimeSubsystemRequirement.Optional, dependencies: [a.descriptor.id]); Assert.Throws(() => m_host.CreateHostPipeline([a, b])); Assert.Equal(0, a.createCount); Assert.Equal(0, b.createCount); @@ -131,11 +148,15 @@ public void StartupTimeoutKeepsPendingHostPipelineAndPermanentlyFaultsAdmission( { string root = Path.Combine(m_root, "Timeout"); EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) - .UseRetirementTimeout(TimeSpan.FromTicks(1)).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .UseRetirementTimeout(TimeSpan.FromTicks(1)) + .Build(); var pending = new TaskCompletionSource(); - var factory = Create("test.timeout"); + Factory factory = Create("test.timeout"); factory.pending = pending.Task; factory.failCreate = true; Assert.Throws(() => host.CreateHostPipeline([factory])); @@ -151,14 +172,23 @@ public void StartupTimeoutKeepsPendingHostPipelineAndPermanentlyFaultsAdmission( host.logs.Dispose(); } - private static Factory Create(string id, RuntimeSubsystemRequirement requirement = RuntimeSubsystemRequirement.Required, - IReadOnlyList? dependencies = null, IReadOnlyList? capabilities = null) - => new(new RuntimeSubsystemDescriptor(new RuntimeSubsystemId(id), dependencies: dependencies, - lifetime: RuntimeSubsystemLifetime.Host, requirement: requirement, requiredCapabilities: capabilities)); + private static Factory Create( + string id, + RuntimeSubsystemRequirement requirement = RuntimeSubsystemRequirement.Required, + IReadOnlyList? dependencies = null, + IReadOnlyList? capabilities = null + ) => new( + new RuntimeSubsystemDescriptor( + new RuntimeSubsystemID(id), + dependencies: dependencies, + lifetime: RuntimeSubsystemLifetime.Host, + requirement: requirement, + requiredCapabilities: capabilities + ) + ); private sealed class Factory(RuntimeSubsystemDescriptor descriptor) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = descriptor; internal RuntimeSubsystemContext? context; internal int createCount; internal int releaseCount; @@ -167,15 +197,21 @@ private sealed class Factory(RuntimeSubsystemDescriptor descriptor) : IRuntimeSu internal bool failRelease; internal Task? pending; + public RuntimeSubsystemDescriptor descriptor { get; } = descriptor; + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { this.context = context; createCount++; context.resources.Own(new Resource(this)); if (pending is not null) + { context.resources.Track(pending); + } if (failCreate) + { throw new InvalidOperationException("factory failed"); + } return new Subsystem(this); } @@ -185,7 +221,9 @@ public void Dispose() { factory.releaseCount++; if (factory.failRelease) + { throw new InvalidOperationException("resource retirement failed"); + } } } @@ -194,7 +232,9 @@ private sealed class Subsystem(Factory factory) : RuntimeSubsystem protected override void OnStart() { if (factory.failAttach) + { throw new InvalidOperationException("attach failed"); + } } } } diff --git a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs index 135932cf2..8b6472668 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs @@ -1,8 +1,8 @@ using System; using System.IO; +using Xunit; using Inno.Extensibility.Modules; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -15,8 +15,10 @@ public void ManifestMutationCannotChangeFrozenDeployment() string[] dependencies = []; var module = new GameRuntimeModule { - name = "Game", domain = AssemblyDomain.InnoScripting, - assemblies = [assembly], dependencies = dependencies + name = "Game", + domain = AssemblyDomain.InnoScripting, + assemblies = [assembly], + dependencies = dependencies }; GameCodeDeployment frozen = GameCodeDeployment.FromManifest([module]); assembly.name = "Different.Code"; @@ -31,8 +33,8 @@ public void ManifestMutationCannotChangeFrozenDeployment() [Fact] public void LinkedIdentityRejectsDifferentCodeBeforeModuleActivation() { - GameCodeDeployment linked = new([CreateModule("Game", "Game.Code", 'a')]); - GameCodeDeployment replaced = new([CreateModule("Game", "Game.Code", 'b')]); + var linked = new GameCodeDeployment([CreateModule("Game", "Game.Code", 'a')]); + var replaced = new GameCodeDeployment([CreateModule("Game", "Game.Code", 'b')]); Assert.Throws(() => replaced.ValidateMatches(linked)); linked.ValidateMatches(new GameCodeDeployment([CreateModule("Game", "Game.Code", 'a')])); } @@ -41,10 +43,15 @@ public void LinkedIdentityRejectsDifferentCodeBeforeModuleActivation() public void ClosureRejectsSharedAssemblyOwnersAndMissingUpstreamModules() { Assert.Throws(() => new GameCodeDeployment([ - CreateModule("One", "Shared.Code", 'a'), CreateModule("Two", "Shared.Code", 'a') + CreateModule("One", "Shared.Code", 'a'), + CreateModule("Two", "Shared.Code", 'a') ])); - var missing = new GameCodeModule("Game", AssemblyDomain.InnoScripting, - [new GameCodeAssembly("Game.Code", new string('a', 64))], ["Absent"]); + var missing = new GameCodeModule( + "Game", + AssemblyDomain.InnoScripting, + [new GameCodeAssembly("Game.Code", new string('a', 64))], + ["Absent"] + ); Assert.Throws(() => new GameCodeDeployment([missing])); } @@ -61,6 +68,5 @@ private static GameCodeModule CreateModule( string name, string assembly, char fingerprint - ) => new(name, AssemblyDomain.InnoScripting, - [new GameCodeAssembly(assembly, new string(fingerprint, 64))], []); + ) => new(name, AssemblyDomain.InnoScripting, [new GameCodeAssembly(assembly, new string(fingerprint, 64))], []); } diff --git a/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs index 87900d906..b138e0c1f 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; +using Xunit; using Inno.Extensibility.Catalogs; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -15,7 +15,10 @@ public void FactoriesDoNotIntroduceClosedConstructionsIntoDiscovery() { register.Register(Metadata(typeof(Box<>)), null); register.RegisterFactory(typeof(Box), static () => new Box()); - register.RegisterFactory(typeof(Box), static () => throw new InvalidOperationException("Duplicate factory must not execute.")); + register.RegisterFactory( + typeof(Box), + static () => throw new InvalidOperationException("Duplicate factory must not execute.") + ); }]); Assert.Equal(typeof(Box), source.ConstructGenericType(typeof(Box<>), [typeof(int)])); @@ -57,9 +60,10 @@ public void FailedContributorAlsoRetiresItsRegistrar() [Fact] public void ContributorCannotTransferRegistrationToAnotherThread() - => new StaticTypeCatalogSource([register => Task.Run(() => - Assert.Throws(() => register.Register(Metadata(typeof(Box<>)), null))) - .GetAwaiter().GetResult()]); + => new StaticTypeCatalogSource([register => Task + .Run(() => Assert.Throws(() => register.Register(Metadata(typeof(Box<>)), null))) + .GetAwaiter() + .GetResult()]); [Fact] public void GenericArgumentValidationIsIndependentOfAvailableFactories() diff --git a/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs index a636752d0..f69bd1799 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs @@ -1,19 +1,18 @@ -using Inno.Core.IO; using System; using System.IO; +using Xunit; +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Catalogs; using Inno.Extensibility.Types; using Inno.Runtime; -using Xunit; - -using Inno.Extensibility.Catalogs; namespace Inno.Runtime.Tests; public sealed class StaticProjectSettingsTests { - private static readonly ProjectSettingId SettingId = new("tests.static-setting"); + private static readonly ProjectSettingID SETTING_ID = new("tests.static-setting"); [Fact] public void SettingsUseContributedMetadataAndFactoryWithoutReflectiveDeclarations() @@ -22,15 +21,20 @@ public void SettingsUseContributedMetadataAndFactoryWithoutReflectiveDeclaration try { using EngineHost host = CreateHost(directory, static () => new Setting(17)); - using var settings = new ProjectSettings(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), - host.types, host.serialization, new ProjectId("tests.static"), SerializationContext.empty); + using var settings = new ProjectSettings( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectID("tests.static"), + SerializationContext.empty + ); - Setting first = settings.Get(SettingId); + Setting first = settings.Get(SETTING_ID); Assert.Equal(17, first.value); first.value = 42; - Assert.Equal(17, settings.Get(SettingId).value); - settings.SetProjectOverride(SettingId, first, []); - Assert.Equal(42, settings.Get(SettingId).value); + Assert.Equal(17, settings.Get(SETTING_ID).value); + settings.SetProjectOverride(SETTING_ID, first, []); + Assert.Equal(42, settings.Get(SETTING_ID).value); } finally { @@ -46,8 +50,13 @@ public void SettingsRejectMissingFactoriesDuringCandidatePreparation() { using EngineHost host = CreateHost(directory, factory: null); InvalidOperationException exception = Assert.Throws(() => - new ProjectSettings(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), host.types, - host.serialization, new ProjectId("tests.static"), SerializationContext.empty)); + new ProjectSettings( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectID("tests.static"), + SerializationContext.empty + )); Assert.Contains("factory in the current type catalog", exception.Message); } finally @@ -60,24 +69,39 @@ private static EngineHost CreateHost( string directory, Func? factory ) { - Attribute[] attributes = [new StableTypeIdAttribute("f506944b-bcfa-48e4-b839-a66b4d8f5887"), - new ProjectSettingDefinitionAttribute(SettingId.value)]; - var types = new StaticTypeCatalogSource([register => register.Register(new TypeCatalogMetadata(typeof(Setting), - [], [typeof(ISerializable)], attributes, attributes, []), factory)]); + Attribute[] attributes = + [ + new StableTypeIDAttribute("f506944b-bcfa-48e4-b839-a66b4d8f5887"), + new ProjectSettingDefinitionAttribute(SETTING_ID.value) + ]; + var types = new StaticTypeCatalogSource([register => register.Register( + new TypeCatalogMetadata(typeof(Setting), [], [typeof(ISerializable)], attributes, attributes, []), + factory + )]); var serialization = new StaticSerializationMetadataSource([ - register => register(new SerializationTypeMetadata(typeof(Setting), [ - new SerializationMemberMetadata("value", typeof(int), PropertyVisibility.Show, - static value => ((Setting)value).value, - static ( - target, - value - ) => ((Setting)target).value = (int)value!) - ], static () => new Setting(17))), + register => register( + new SerializationTypeMetadata(typeof(Setting), [ + new SerializationMemberMetadata( + "value", + typeof(int), + PropertyVisibility.Show, + static value => ((Setting)value).value, + static ( + target, + value + ) => ((Setting)target).value = (int)value! + ) + ], static () => new Setting(17)) + ), Inno.Core.Settings.Generated.RuntimeSerializationMetadataCatalog.Register ]); return new EngineHostBuilder() - .UseMetadataSources(new StaticAssemblyCatalogSource([typeof(Setting).Assembly], [typeof(object).Assembly]), - types, serialization).Build(); + .UseMetadataSources( + new StaticAssemblyCatalogSource([typeof(Setting).Assembly], [typeof(object).Assembly]), + types, + serialization + ) + .Build(); } private static string CreateDirectory() diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs b/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs deleted file mode 100644 index beec5cb8c..000000000 --- a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Collections.Generic; - -using Inno.Assets; -using Inno.Extensibility.Types; -using Inno.Core.Serialization; -using Inno.Scene; - -namespace Inno.Scene.Tests; - -[StableTypeId("cc867fe9-866c-4a19-ac69-5e561b20a874")] -internal sealed class EngineAssetReferenceComponent : GameComponent -{ - [SerializableProperty] - public TextAsset? asset { get; set; } -} - -[StableTypeId("b4ada657-2b58-4929-b1c0-616b54bb0939")] -internal sealed class EngineObjectReferenceComponent : GameComponent -{ - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public int value { get; set; } -} - -internal sealed class PrefabInstantiationBehavior : GameBehavior -{ - public PrefabAsset? prefab { get; set; } - - public List instances { get; } = []; - - protected override void Update() - { - if (prefab is not null && instances.Count < 2) - instances.Add(gameObject.scene.InstantiatePrefab(prefab, gameObject.transform)); - } -} diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs index a5e0f5300..bbaef8765 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs @@ -1,5 +1,5 @@ -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Scene.Tests; diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs index d7226ca48..3c835d061 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs @@ -1,27 +1,28 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed partial class EngineAssetIntegrationTests : IDisposable { private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoEngineAssetTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly SceneTestsFixture m_fixture; private readonly AssetPipeline m_assets; private readonly SerializationContext m_assetSerializationContext; @@ -44,7 +45,8 @@ public EngineAssetIntegrationTests(SceneTestsFixture fixture) fixture.identities, fixture.diagnostics, fixture.logs, - options); + options + ); m_assetSerializationContext = AssetSerializationContext.Create(m_assets); } @@ -54,11 +56,13 @@ public void Dispose() m_assets.Dispose(); m_sceneScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] - public void SceneAsset_CaptureSaveLoadInstantiate_PreservesCanonicalIdentity() + public void SceneAssetCaptureSaveLoadInstantiatePreservesCanonicalIdentity() { var source = new GameScene("Captured"); source.CreateObject("Object"); @@ -66,18 +70,19 @@ public void SceneAsset_CaptureSaveLoadInstantiate_PreservesCanonicalIdentity() Assert.True(m_assets.Save(AssetPath.Project("Scenes/sample.iscene"), captured)); SceneAsset byPath = m_assets.Load(AssetPath.Project("Scenes/sample.iscene")); - SceneAsset byId = m_assets.Load(byPath.identity.persistentId); + SceneAsset byID = m_assets.Load(byPath.identity.persistentID); GameScene first = byPath.Instantiate(m_fixture.serialization, m_assets); GameScene second = byPath.Instantiate(m_fixture.serialization, m_assets); Assert.Same(captured, byPath); - Assert.Same(byPath, byId); + Assert.Same(byPath, byID); Assert.Equal("sample", first.name); Assert.Equal("Object", Assert.Single(first.GetObjects()).name); - Assert.NotEqual(first.identity.persistentId, second.identity.persistentId); + Assert.NotEqual(first.identity.persistentID, second.identity.persistentID); Assert.NotEqual( - Assert.Single(first.GetObjects()).identity.persistentId, - Assert.Single(second.GetObjects()).identity.persistentId); + Assert.Single(first.GetObjects()).identity.persistentID, + Assert.Single(second.GetObjects()).identity.persistentID + ); DestroyScene(source); DestroyScene(first); @@ -85,7 +90,7 @@ public void SceneAsset_CaptureSaveLoadInstantiate_PreservesCanonicalIdentity() } [Fact] - public void PrefabAsset_IsSceneIndependentAndRemapsInternalReferences() + public void PrefabAssetIsSceneIndependentAndRemapsInternalReferences() { var sourceScene = new GameScene("Source"); GameObject sourceRoot = sourceScene.CreateObject("Root"); @@ -103,22 +108,24 @@ public void PrefabAsset_IsSceneIndependentAndRemapsInternalReferences() Assert.Same(captured, prefab); Assert.True(first.isPartOfPrefabInstance); Assert.True(first.prefabInstance!.isRoot); - Assert.Equal(prefab.identity.persistentId, first.prefabInstance.sourceAssetId); - Assert.Equal(first.prefabInstance.sourceObjectId, second.prefabInstance!.sourceObjectId); - Assert.NotEqual(first.identity.persistentId, second.identity.persistentId); + Assert.Equal(prefab.identity.persistentID, first.prefabInstance.sourceAssetID); + Assert.Equal(first.prefabInstance.sourceObjectID, second.prefabInstance!.sourceObjectID); + Assert.NotEqual(first.identity.persistentID, second.identity.persistentID); Assert.Same( Assert.Single(first.transform.children).gameObject, - first.GetComponent().targetObject); + first.GetComponent().targetObject + ); Assert.Same( Assert.Single(second.transform.children).gameObject, - second.GetComponent().targetObject); + second.GetComponent().targetObject + ); DestroyScene(sourceScene); DestroyScene(targetScene); } [Fact] - public void LoadedScene_InstantiatesConnectedPrefabsDuringUpdate() + public void LoadedSceneInstantiatesConnectedPrefabsDuringUpdate() { var sourceScene = new GameScene("Source"); GameObject sourceRoot = sourceScene.CreateObject("Root"); @@ -147,7 +154,8 @@ public void LoadedScene_InstantiatesConnectedPrefabsDuringUpdate() Assert.Same(spawner.gameObject.transform, instance.transform.parent); Assert.Same( Assert.Single(instance.transform.children).gameObject, - instance.GetComponent().targetObject); + instance.GetComponent().targetObject + ); } DestroyScene(sourceScene); @@ -155,7 +163,7 @@ public void LoadedScene_InstantiatesConnectedPrefabsDuringUpdate() } [Fact] - public void SceneAsset_DirectAssetReferenceUsesCanonicalInstanceAndDependencyMetadata() + public void SceneAssetDirectAssetReferenceUsesCanonicalInstanceAndDependencyMetadata() { WriteAsset("Text/shared.txt", "shared"); Assert.True(m_assets.Import(AssetPath.Project("Text/shared.txt"))); @@ -174,7 +182,7 @@ public void SceneAsset_DirectAssetReferenceUsesCanonicalInstanceAndDependencyMet .GetComponent() .asset!; - Assert.Equal(text.identity.persistentId, dependency.persistentId); + Assert.Equal(text.identity.persistentID, dependency.persistentID); Assert.Equal("Text/shared.txt", dependency.lastKnownPath); Assert.Same(text, restored); @@ -183,7 +191,7 @@ public void SceneAsset_DirectAssetReferenceUsesCanonicalInstanceAndDependencyMet } [Fact] - public void ConnectedPrefabSceneRoundtrip_PreservesPropertyAndStructureOverrides() + public void ConnectedPrefabSceneRoundtripPreservesPropertyAndStructureOverrides() { var sourceScene = new GameScene("Source"); GameObject sourceRoot = sourceScene.CreateObject("Root"); @@ -242,20 +250,20 @@ public void PrefabInstanceRetainsSourceAssetUntilItsSceneIsUnloaded() } [Fact] - public void MissingPrefabSource_PreservesConnectionAndRecoversInPlace() + public void MissingPrefabSourcePreservesConnectionAndRecoversInPlace() { var sourceScene = new GameScene("Source"); GameObject sourceRoot = sourceScene.CreateObject("Root"); sourceScene.CreateObject("Child").transform.SetParent(sourceRoot.transform); PrefabAsset captured = PrefabAsset.Capture(sourceRoot, m_fixture.serialization, m_assets); - const string relativePath = "Prefabs/missing.iprefab"; - AssetPath assetPath = AssetPath.Project(relativePath); + const string C_RELATIVE_PATH = "Prefabs/missing.iprefab"; + AssetPath assetPath = AssetPath.Project(C_RELATIVE_PATH); Assert.True(m_assets.Save(assetPath, captured)); PrefabAsset prefab = m_assets.Load(assetPath); var targetScene = new GameScene("Target"); _ = prefab.Instantiate(targetScene, m_fixture.serialization, m_assets); byte[] sceneBytes = m_fixture.serialization.Serialize(targetScene, m_assetSerializationContext); - string sourcePath = Path.Combine(m_root, "Assets", relativePath); + string sourcePath = Path.Combine(m_root, "Assets", C_RELATIVE_PATH); string metaPath = sourcePath + ".imeta"; byte[] sourceBytes = File.ReadAllBytes(sourcePath); byte[] metaBytes = File.ReadAllBytes(metaPath); @@ -287,9 +295,9 @@ public void MissingPrefabSource_PreservesConnectionAndRecoversInPlace() } [Fact] - public void EngineImporters_AreDiscoveredWithoutManualRegistration() + public void EngineImportersAreDiscoveredWithoutManualRegistration() { - var importerTypes = m_fixture.types.GetSubTypesOf(); + IReadOnlyList importerTypes = m_fixture.types.GetSubTypesOf(); Assert.Contains(importerTypes, type => type.Resolve(m_fixture.types).Name == "SceneAssetImporter"); Assert.Contains(importerTypes, type => type.Resolve(m_fixture.types).Name == "PrefabAssetImporter"); @@ -297,20 +305,20 @@ public void EngineImporters_AreDiscoveredWithoutManualRegistration() } [Fact] - public void ExternalSceneRename_PreservesIdentityAndUsesFileNameAsSceneName() + public void ExternalSceneRenamePreservesIdentityAndUsesFileNameAsSceneName() { var source = new GameScene("Original Name"); source.CreateObject("Object"); SceneAsset asset = SceneAsset.Capture(source, m_fixture.serialization, m_assets); Assert.True(m_assets.Save(AssetPath.Project("Scenes/old.iscene"), asset)); - Guid id = asset.identity.persistentId; + Guid id = asset.identity.persistentID; string oldPath = Path.Combine(m_root, "Assets", "Scenes", "old.iscene"); string newPath = Path.Combine(m_root, "Assets", "Scenes", "renamed.iscene"); File.Move(oldPath, newPath); m_assets.Rescan(); - Assert.Equal(id, asset.identity.persistentId); + Assert.Equal(id, asset.identity.persistentID); Assert.Equal("Scenes/renamed.iscene", asset.assetPath.ToString()); Assert.Same(asset, m_assets.Load(id)); GameScene instance = asset.Instantiate(m_fixture.serialization, m_assets); @@ -321,14 +329,14 @@ public void ExternalSceneRename_PreservesIdentityAndUsesFileNameAsSceneName() } [Fact] - public void ExternalPrefabRename_PreservesIdentityAndRenamesOnlyTheSourceRoot() + public void ExternalPrefabRenamePreservesIdentityAndRenamesOnlyTheSourceRoot() { var sourceScene = new GameScene("Source"); GameObject root = sourceScene.CreateObject("Old Root"); sourceScene.CreateObject("Child").transform.SetParent(root.transform); PrefabAsset asset = PrefabAsset.Capture(root, m_fixture.serialization, m_assets); Assert.True(m_assets.Save(AssetPath.Project("Prefabs/old.iprefab"), asset)); - Guid id = asset.identity.persistentId; + Guid id = asset.identity.persistentID; string oldPath = Path.Combine(m_root, "Assets", "Prefabs", "old.iprefab"); string newPath = Path.Combine(m_root, "Assets", "Prefabs", "renamed.iprefab"); @@ -337,7 +345,7 @@ public void ExternalPrefabRename_PreservesIdentityAndRenamesOnlyTheSourceRoot() var targetScene = new GameScene("Target"); GameObject instance = asset.Instantiate(targetScene, m_fixture.serialization, m_assets); - Assert.Equal(id, asset.identity.persistentId); + Assert.Equal(id, asset.identity.persistentID); Assert.Equal("Prefabs/renamed.iprefab", asset.assetPath.ToString()); Assert.Equal("renamed", instance.name); Assert.Equal("Child", Assert.Single(instance.transform.children).gameObject.name); @@ -377,6 +385,15 @@ private WeakReference CreateLoadedPrefabInstance() return new WeakReference(loaded); } + private void WriteAsset( + string relativePath, + string content + ) { + string path = Path.Combine(m_root, "Assets", relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + private static void DestroyScene(GameScene scene) { if (scene.isLoaded) @@ -388,14 +405,4 @@ private static void DestroyScene(GameScene scene) SceneManager.LoadScene(scene); SceneManager.UnloadScene(scene); } - - private void WriteAsset(string relativePath, string content) - { - string path = Path.Combine(m_root, "Assets", relativePath); - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText( - path, - content, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); - } } diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs new file mode 100644 index 000000000..3f701db2b --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs @@ -0,0 +1,12 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("cc867fe9-866c-4a19-ac69-5e561b20a874")] +internal sealed class EngineAssetReferenceComponent : GameComponent +{ + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs new file mode 100644 index 000000000..79a6a8495 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("b4ada657-2b58-4929-b1c0-616b54bb0939")] +internal sealed class EngineObjectReferenceComponent : GameComponent +{ + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/GameLayerTests.cs b/tests/scene/Inno.Scene.Tests/GameLayerTests.cs index 4a36b3962..88e54a445 100644 --- a/tests/scene/Inno.Scene.Tests/GameLayerTests.cs +++ b/tests/scene/Inno.Scene.Tests/GameLayerTests.cs @@ -1,18 +1,16 @@ using System; using System.Linq; - +using Xunit; using Inno.Core.Settings; using Inno.Scene; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; /// /// Verifies runtime layer identifiers, masks, stack configuration, and Scene lookup behavior. /// -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed class GameLayerTests : IDisposable { private readonly IDisposable m_sceneScope; @@ -32,7 +30,7 @@ public void Dispose() /// Verifies that layer identifiers accept exactly the thirty-two mask-backed slots. /// [Fact] - public void GameLayer_ValidatesSupportedSlotRange() + public void GameLayerValidatesSupportedSlotRange() { Assert.Equal(0, GameLayer.defaultLayer.index); Assert.Equal(31, new GameLayer(31).index); @@ -44,7 +42,7 @@ public void GameLayer_ValidatesSupportedSlotRange() /// Verifies immutable mask construction and membership operations. /// [Fact] - public void GameLayerMask_ComposesAndFiltersLayers() + public void GameLayerMaskComposesAndFiltersLayers() { var first = new GameLayer(1); var second = new GameLayer(2); @@ -62,7 +60,7 @@ public void GameLayerMask_ComposesAndFiltersLayers() /// Verifies layer naming constraints and symmetric interaction updates. /// [Fact] - public void GameLayerCatalog_EnforcesUniqueDefinitionsAndSymmetricInteractions() + public void GameLayerCatalogEnforcesUniqueDefinitionsAndSymmetricInteractions() { var stack = new GameLayerCatalog(); var player = new GameLayer(1); @@ -89,38 +87,38 @@ public void GameLayerCatalog_EnforcesUniqueDefinitionsAndSymmetricInteractions() /// Verifies that project-scoped identities are resolved from stable local keys at the read boundary. /// [Fact] - public void ProjectScopedIds_FollowProjectIdentityWithoutRewritingDefinitions() + public void ProjectScopedIDsFollowProjectIdentityWithoutRewritingDefinitions() { - var firstProject = new ProjectId("studio.first"); - Assert.Equal("innoengine-rendering2d", ProjectId.FromName("InnoEngine.Rendering2D").value); - Assert.Equal("inno.project", ProjectId.FromName("项目").value); + var firstProject = new ProjectID("studio.first"); + Assert.Equal("innoengine-rendering2d", ProjectID.FromName("InnoEngine.Rendering2D").value); + Assert.Equal("inno.project", ProjectID.FromName("项目").value); - var secondProject = new ProjectId("studio.second"); + var secondProject = new ProjectID("studio.second"); var layer = new GameLayer(1); var layers = new GameLayerCatalog(); layers.Define(layer, "Player"); - Assert.Equal("layer.01", layers.GetLocalId(layer)?.value); - Assert.Equal("studio.first.layer.01", layers.GetId(firstProject, layer)?.value); - Assert.Equal("studio.second.layer.01", layers.GetId(secondProject, layer)?.value); + Assert.Equal("layer.01", layers.GetLocalID(layer)?.value); + Assert.Equal("studio.first.layer.01", layers.GetID(firstProject, layer)?.value); + Assert.Equal("studio.second.layer.01", layers.GetID(secondProject, layer)?.value); layers.Define(layer, "Hero"); - Assert.Equal("layer.01", layers.GetLocalId(layer)?.value); - Assert.Equal("studio.second.layer.01", layers.GetId(secondProject, layer)?.value); + Assert.Equal("layer.01", layers.GetLocalID(layer)?.value); + Assert.Equal("studio.second.layer.01", layers.GetID(secondProject, layer)?.value); var tags = new GameTagCatalog(); Assert.True(tags.Add("Enemy Boss")); - Assert.Equal("enemy-boss", tags.GetLocalId("Enemy Boss").value); - Assert.Equal("studio.first.enemy-boss", tags.GetId(firstProject, "Enemy Boss").value); - Assert.Equal("studio.second.enemy-boss", tags.GetId(secondProject, "Enemy Boss").value); + Assert.Equal("enemy-boss", tags.GetLocalID("Enemy Boss").value); + Assert.Equal("studio.first.enemy-boss", tags.GetID(firstProject, "Enemy Boss").value); + Assert.Equal("studio.second.enemy-boss", tags.GetID(secondProject, "Enemy Boss").value); } /// /// Verifies that Scene layer indexes remain coherent after live metadata changes. /// [Fact] - public void GameScene_LayerQueriesTrackLiveObjectChanges() + public void GameSceneLayerQueriesTrackLiveObjectChanges() { var scene = new GameScene("Layers"); GameObject first = scene.CreateObject("First"); @@ -132,9 +130,7 @@ public void GameScene_LayerQueriesTrackLiveObjectChanges() Assert.Same(first, scene.FindObjectWithLayer(player)); Assert.Equal([first], scene.FindObjectsWithLayer(player)); - Assert.Equal( - [first, second], - scene.FindObjectsWithLayers(GameLayerMask.FromLayers([player, enemy]))); + Assert.Equal([first, second], scene.FindObjectsWithLayers(GameLayerMask.FromLayers([player, enemy]))); first.layer = enemy; diff --git a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs index 578662682..57144d553 100644 --- a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs +++ b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs @@ -1,16 +1,11 @@ using System; using System.Collections.Generic; -using System.Linq; - -using Inno.Extensibility.Types; -using Inno.Core.Serialization; -using Inno.Scene; - using Xunit; +using Inno.Core.Serialization; namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed class GameSystemTests : IDisposable { private readonly SerializationRegistry m_serialization; @@ -88,7 +83,7 @@ public void SceneRoundtripPreservesSystemsStateIdentityOrderAndGraphReferences() system.value = 42; system.component = component; component.system = system; - Guid systemId = system.identity.persistentId; + Guid systemID = system.identity.persistentID; byte[] bytes = m_serialization.Serialize(source, m_serializationContext); SceneManager.LoadScene(source); @@ -98,7 +93,7 @@ public void SceneRoundtripPreservesSystemsStateIdentityOrderAndGraphReferences() StateSystem restoredSystem = Assert.IsType(Assert.Single(restored.GetSystems())); SystemReferenceComponent restoredComponent = Assert.Single(restored.GetObjects()) .GetComponent(); - Assert.Equal(systemId, restoredSystem.identity.persistentId); + Assert.Equal(systemID, restoredSystem.identity.persistentID); Assert.Equal(42, restoredSystem.value); Assert.Equal(0, restoredSystem.resetCount); Assert.Same(restoredComponent, restoredSystem.component); @@ -109,7 +104,7 @@ public void SceneRoundtripPreservesSystemsStateIdentityOrderAndGraphReferences() public void ManualSystemOrderIsIndependentFromExecutionPriorityAndBreaksPriorityTies() { var scene = new GameScene("System Order"); - var execution = new List(); + List execution = []; var highA = new OrderedSystem("High A", 10, execution); var low = new OrderedSystem("Low", -10, execution); var highB = new OrderedSystem("High B", 10, execution); @@ -148,12 +143,19 @@ private sealed class LifecycleSystem : GameSystem internal int lateCount; protected override void Awake() => awakeCount++; + protected override void Start() => startCount++; + protected override void OnEnable() => enableCount++; + protected override void OnDisable() => disableCount++; + protected override void OnDestroy() => destroyCount++; + protected override void OnFixedUpdate() => fixedCount++; + protected override void OnUpdate() => updateCount++; + protected override void OnLateUpdate() => lateCount++; } @@ -161,31 +163,11 @@ private sealed class LifecycleSystem : GameSystem private sealed class OrderedSystem( string label, int executionOrder, - ICollection execution) : GameSystem + ICollection execution + ) : GameSystem { public override int order => executionOrder; protected override void OnUpdate() => execution.Add(label); } } - -[StableTypeId("b469170b-a1f2-4176-b3ad-252d1cb53b90")] -internal sealed class StateSystem : GameSystem -{ - [SerializableProperty] - public int value { get; set; } - - [SerializableProperty] - public SystemReferenceComponent? component { get; set; } - - public int resetCount { get; private set; } - - protected override void Reset() => resetCount++; -} - -[StableTypeId("75344398-ed18-46ae-808b-e0cb45d93850")] -internal sealed class SystemReferenceComponent : GameComponent -{ - [SerializableProperty] - public StateSystem? system { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs b/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs new file mode 100644 index 000000000..2f6546761 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene.Layers; + +namespace Inno.Scene.Tests; + +[StableTypeID("821c7b92-9aeb-40cb-924e-169004199ef0")] +internal sealed class LayerValueComponent : GameComponent +{ + [SerializableProperty] + public GameLayer layer { get; set; } + + [SerializableProperty] + public GameLayerMask mask { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/OrderComponentA.cs b/tests/scene/Inno.Scene.Tests/OrderComponentA.cs new file mode 100644 index 000000000..8103b4f68 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderComponentA.cs @@ -0,0 +1,3 @@ +namespace Inno.Scene.Tests; + +internal sealed class OrderComponentA : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/OrderComponentB.cs b/tests/scene/Inno.Scene.Tests/OrderComponentB.cs new file mode 100644 index 000000000..ed90e7f9e --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderComponentB.cs @@ -0,0 +1,3 @@ +namespace Inno.Scene.Tests; + +internal sealed class OrderComponentB : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs new file mode 100644 index 000000000..a657710ec --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("f7bc9bf3-288a-45b3-9caa-26289d66c181")] +internal sealed class OrderSerializationSystemA : GameSystem; diff --git a/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs new file mode 100644 index 000000000..3aa4e6d83 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("6924359d-798d-4384-bdb2-1b0e34ab3fbb")] +internal sealed class OrderSerializationSystemB : GameSystem; diff --git a/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs b/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs index 7a8b196ff..e6281b0ba 100644 --- a/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs +++ b/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs @@ -1,27 +1,24 @@ -using Inno.Adapter.Modules.DotNet; using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Collections.Generic; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Core.Identity; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; +using Inno.References; using Inno.Scene; using Inno.Scene.Components; -using Inno.Core.Identity; -using Inno.References; - -using Xunit; namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed class PluginSceneReloadTests : IDisposable { - private static readonly Guid S_COMPONENT_TYPE_ID = - Guid.Parse("9f67d41e-082b-46d5-aaf0-dfc76c693182"); + private static readonly Guid COMPONENT_TYPE_ID = Guid.Parse("9f67d41e-082b-46d5-aaf0-dfc76c693182"); private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; @@ -30,7 +27,7 @@ public sealed class PluginSceneReloadTests : IDisposable private readonly IDisposable m_sceneScope; private readonly string m_artifactRoot; private AssemblyModuleHandle? m_activeModule; - private IReadOnlyList m_changes = Array.Empty(); + private IReadOnlyList m_changes = []; public PluginSceneReloadTests(SceneTestsFixture fixture) { @@ -46,11 +43,15 @@ public void Dispose() { m_world.UnloadAllScenes(); if (m_activeModule is AssemblyModuleHandle activeModule) + { _ = m_modules.Unload(activeModule); + } m_sceneScope.Dispose(); m_modules.generations.Wait(); if (Directory.Exists(m_artifactRoot)) + { Directory.Delete(m_artifactRoot, recursive: true); + } } [Fact] @@ -59,28 +60,31 @@ public void RemovingAndRestoringAPluginGenerationPreservesItsComponentAsMissingS m_activeModule = m_modules.Load(CreateRequest()); GameScene scene = m_world.LoadNewScene("Plugin Reload"); GameObject owner = scene.CreateObject("Plugin Owner"); - (Guid componentPersistentId, string typeName) = AttachPluginComponent(owner); + (Guid componentPersistentID, string typeName) = AttachPluginComponent(owner); RemovePlugin(); m_modules.generations.Wait(); m_activeModule = null; MissingGameComponent missing = Assert.IsType( - owner.GetComponents().Single(component => component is not Transform)); - Assert.Equal(componentPersistentId, missing.identity.persistentId); - Assert.Equal(S_COMPONENT_TYPE_ID, missing.missingType.stableId); + owner.GetComponents().Single(component => component is not Transform) + ); + Assert.Equal(componentPersistentID, missing.identity.persistentID); + Assert.Equal(COMPONENT_TYPE_ID, missing.missingType.stableID); Assert.Equal(typeName, missing.missingTypeName); Assert.False(missing.missingType.IsValid(m_types)); - ReferenceRecoveryChange missingChange = Assert.Single(m_changes.Where(change => - change.missingState.descriptor.targetPersistentId == componentPersistentId)); + ReferenceRecoveryChange missingChange = Assert.Single( + m_changes.Where(change => (change.missingState.descriptor.targetPersistentID == componentPersistentID)) + ); Assert.Equal(ReferenceResolutionState.Missing, missingChange.resolution.state); - Assert.Equal(S_COMPONENT_TYPE_ID, missingChange.missingState.descriptor.expectedStableTypeId); + Assert.Equal(COMPONENT_TYPE_ID, missingChange.missingState.descriptor.expectedStableTypeID); Assert.False(missingChange.missingState.payload.IsEmpty); using (AssemblyReloadSession recovery = m_modules.BeginReload([CreateRequest()])) { m_activeModule = recovery.context.module; ISceneReloadStateTransfer transfer = m_reload.Capture( - recovery.context.GetContext()); + recovery.context.GetContext() + ); transfer.PrepareForActivation(); recovery.Activate(); transfer.Apply(); @@ -92,38 +96,16 @@ public void RemovingAndRestoringAPluginGenerationPreservesItsComponentAsMissingS GameComponent recovered = owner.GetComponents().Single(component => component is not Transform); Assert.IsNotType(recovered); - Assert.Equal(S_COMPONENT_TYPE_ID, m_types.GetTypeRef(recovered.GetType()).stableId); - Assert.Equal(componentPersistentId, recovered.identity.persistentId); + Assert.Equal(COMPONENT_TYPE_ID, m_types.GetTypeRef(recovered.GetType()).stableID); + Assert.Equal(componentPersistentID, recovered.identity.persistentID); Assert.Equal(47, GetValue(recovered)); - ReferenceRecoveryChange recoveredChange = Assert.Single(m_changes.Where(change => - change.missingState.descriptor.targetPersistentId == componentPersistentId)); + ReferenceRecoveryChange recoveredChange = Assert.Single( + m_changes.Where(change => (change.missingState.descriptor.targetPersistentID == componentPersistentID)) + ); Assert.Equal(ReferenceResolutionState.Resolved, recoveredChange.resolution.state); Assert.Equal(recovered.identity.runtimeIdentity, recoveredChange.resolution.runtimeIdentity); } - private DotNetModuleSource CreateRequest() - => new() - { - moduleName = "SceneReloadPluginTests", - artifactRootDirectory = m_artifactRoot, - mainAssemblyPath = Path.Combine( - AppContext.BaseDirectory, - "Modules", - "SceneReload", - "Inno.Scene.Reload.TestModule.dll"), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; - - [MethodImpl(MethodImplOptions.NoInlining)] - private (Guid, string) AttachPluginComponent(GameObject owner) - { - Type type = new TypeRef(S_COMPONENT_TYPE_ID).Resolve(m_types); - GameComponent original = owner.AddComponent(type); - SetValue(original, 47); - return (original.identity.persistentId, type.FullName!); - } - [Fact] public void ForeignAllocatorFailsBeforeReplacingAnEditComponentAndRollbackRestoresItsState() { @@ -152,6 +134,30 @@ public void ForeignAllocatorFailsBeforeReplacingAnEditComponentAndRollbackRestor Assert.Equal(47, GetValue(previous)); } + private DotNetModuleSource CreateRequest() + => new() + { + moduleName = "SceneReloadPluginTests", + artifactRootDirectory = m_artifactRoot, + mainAssemblyPath = Path.Combine( + AppContext.BaseDirectory, + "Modules", + "SceneReload", + "Inno.Scene.Reload.TestModule.dll" + ), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; + + [MethodImpl(MethodImplOptions.NoInlining)] + private (Guid, string) AttachPluginComponent(GameObject owner) + { + Type type = new TypeRef(COMPONENT_TYPE_ID).Resolve(m_types); + GameComponent original = owner.AddComponent(type); + SetValue(original, 47); + return (original.identity.persistentID, type.FullName!); + } + [MethodImpl(MethodImplOptions.NoInlining)] private void RemovePlugin() { @@ -165,14 +171,16 @@ private void RemovePlugin() m_changes = transfer.recoveryChanges; } - private static int GetValue(GameComponent component) - => (int)GetValueProperty(component).GetValue(component)!; + private static int GetValue(GameComponent component) => (int)GetValueProperty(component).GetValue(component)!; - private static void SetValue(GameComponent component, int value) - => GetValueProperty(component).SetValue(component, value); + private static void SetValue( + GameComponent component, + int value + ) => GetValueProperty(component).SetValue(component, value); private static PropertyInfo GetValueProperty(GameComponent component) => component.GetType().GetProperty("value", BindingFlags.Instance | BindingFlags.Public) ?? throw new InvalidOperationException( - $"Reload test component '{component.GetType().FullName}' does not expose its public state contract."); + $"Reload test component '{component.GetType().FullName}' does not expose its public state contract." + ); } diff --git a/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs b/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs new file mode 100644 index 000000000..a3b378375 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace Inno.Scene.Tests; + +internal sealed class PrefabInstantiationBehavior : GameBehavior +{ + public PrefabAsset? prefab { get; set; } + + public List instances { get; } = []; + + protected override void Update() + { + if (prefab is not null && instances.Count < 2) + { + instances.Add(gameObject.scene.InstantiatePrefab(prefab, gameObject.transform)); + } + } +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs b/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs new file mode 100644 index 000000000..880951010 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs @@ -0,0 +1,34 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Scene.Tests; + +/// +/// Creates valid and deliberately invalid current element envelopes through the public serializer. +/// +internal sealed class PropertyElementEnvelope : ISerializable +{ + [SerializableProperty] + public Guid typeId { get; set; } + + [SerializableProperty] + public string typeName { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] properties { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencyIds { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencyTypes { get; set; } = []; + + [SerializableProperty] + public string[] dependencyPaths { get; set; } = []; + + [SerializableProperty] + public Guid[] aliasIds { get; set; } = []; + + [SerializableProperty] + public Guid[] aliasTargets { get; set; } = []; +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs b/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs new file mode 100644 index 000000000..d89d5f4bc --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs @@ -0,0 +1,31 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("486290eb-6cc4-4a96-918a-c8022f51ad85")] +internal sealed class PropertyReferenceProbe : GameComponent +{ + [SerializableProperty(order = -1)] + public int trigger + { + get + { + beforeRead?.Invoke(); + return 0; + } + set {} + } + + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public GameComponent? targetComponent { get; set; } + + [SerializableProperty] + public GameSystem? targetSystem { get; set; } + + internal Action? beforeRead { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs b/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs new file mode 100644 index 000000000..0fe05cbf1 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Scene.Tests; + +internal sealed class PropertyReferenceTokenFixture : ISerializable +{ + [SerializableProperty] + public int kind { get; set; } + + [SerializableProperty] + public Guid sourceId { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs new file mode 100644 index 000000000..52c49fdbb --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs @@ -0,0 +1,21 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("09d35197-7161-4fdf-8d60-95ecf3555c0c")] +internal sealed class ReferenceComponent : GameComponent +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public ReferenceComponent? targetComponent { get; set; } + + public int resetCount { get; private set; } + + protected override void Reset() => resetCount++; +} diff --git a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs index 99b515c6c..6c212ae5a 100644 --- a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs @@ -1,18 +1,21 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Scene; -using Inno.Runtime; -using Inno.Scene.Components; - using Xunit; +using Inno.Scene.Components; namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed class SceneFacadeTests : IDisposable { + private readonly IDisposable m_sceneScope; + + public SceneFacadeTests(SceneTestsFixture fixture) + { + m_sceneScope = fixture.world.EnterScope(); + } + [Fact] public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() { @@ -21,10 +24,12 @@ public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() SceneManager.LoadSceneAdditive(scene); SceneManager.LoadSceneAdditive(destination); Transform destinationRoot = destination.CreateObject("Existing").transform; - var roots = new List(); + List roots = []; for (int index = 0; index < 64; index++) + { roots.Add(scene.CreateObject("Root " + index).transform); - var random = new Random(27102026); + } + var random = new Random(27_102_026); for (int iteration = 0; iteration < 200; iteration++) { ulong before = scene.hierarchyRevision; @@ -73,7 +78,9 @@ public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() void Verify() { for (int index = 0; index < roots.Count; index++) + { Assert.Equal(index, roots[index].siblingIndex); + } } } @@ -96,13 +103,6 @@ public void ChildSiblingReorderInvalidatesTheSameSceneHierarchyView() Assert.Equal(before, scene.hierarchyRevision); } - private readonly IDisposable m_sceneScope; - - public SceneFacadeTests(SceneTestsFixture fixture) - { - m_sceneScope = fixture.world.EnterScope(); - } - public void Dispose() { SceneManager.UnloadAllScenes(); @@ -110,7 +110,7 @@ public void Dispose() } [Fact] - public void CreateObject_StoresDataInSceneStore_AndReturnsFacade() + public void CreateObjectStoresDataInSceneStoreAndReturnsFacade() { var scene = new GameScene("Test"); @@ -118,7 +118,7 @@ public void CreateObject_StoresDataInSceneStore_AndReturnsFacade() Assert.True(gameObject.isRuntimeValid); Assert.Equal("Cube", gameObject.name); - Assert.Equal(GameObject.defaultTag, gameObject.tag); + Assert.Equal(GameObject.C_DEFAULT_TAG, gameObject.tag); Assert.True(gameObject.activeSelf); Assert.True(gameObject.HasComponent()); Assert.Single(scene.GetObjects()); @@ -181,17 +181,17 @@ public void TagRejectsEmptyValuesAndTrimsSurroundingWhitespace() } [Fact] - public void GetObjects_ReturnsSceneOwnedObjects() + public void GetObjectsReturnsSceneOwnedObjects() { var scene = new GameScene("Test"); GameObject a = scene.CreateObject("A"); GameObject b = scene.CreateObject("B"); Guid[] ids = [.. scene.GetObjects() - .Select(static o => o.identity.persistentId) + .Select(static o => o.identity.persistentID) .OrderBy(static id => id)]; - Assert.Equal(new[] { a.identity.persistentId, b.identity.persistentId }.OrderBy(static id => id), ids); + Assert.Equal(new[] { a.identity.persistentID, b.identity.persistentID }.OrderBy(static id => id), ids); } [Fact] @@ -223,19 +223,21 @@ public void ComponentsCanBeReorderedIncludingTransform() Assert.Equal( [typeof(Transform), typeof(OrderComponentB), typeof(OrderComponentA)], - gameObject.GetComponents().Select(static component => component.GetType())); + gameObject.GetComponents().Select(static component => component.GetType()) + ); Assert.Equal(1, gameObject.GetComponentIndex(second)); gameObject.SetComponentIndex(gameObject.transform, 2); Assert.Equal( [typeof(OrderComponentB), typeof(OrderComponentA), typeof(Transform)], - gameObject.GetComponents().Select(static component => component.GetType())); + gameObject.GetComponents().Select(static component => component.GetType()) + ); Assert.Equal(2, gameObject.GetComponentIndex(gameObject.transform)); } [Fact] - public void DestroyObject_InvalidatesFacade() + public void DestroyObjectInvalidatesFacade() { var scene = new GameScene("Test"); GameObject gameObject = scene.CreateObject("Cube"); @@ -248,7 +250,7 @@ public void DestroyObject_InvalidatesFacade() } [Fact] - public void DestroyObject_UnlinksTransformHierarchy() + public void DestroyObjectUnlinksTransformHierarchy() { var scene = new GameScene("Test"); GameObject parent = scene.CreateObject("Parent"); @@ -262,7 +264,7 @@ public void DestroyObject_UnlinksTransformHierarchy() } [Fact] - public void GameBehaviorLifecycle_DispatchesLifecycleCallbacks() + public void GameBehaviorLifecycleDispatchesLifecycleCallbacks() { var scene = new GameScene("Test"); GameObject gameObject = scene.CreateObject("Actor"); @@ -288,7 +290,7 @@ public void GameBehaviorLifecycle_DispatchesLifecycleCallbacks() } [Fact] - public void GameBehaviorLifecycle_ReindexesAfterStructuralChanges() + public void GameBehaviorLifecycleReindexesAfterStructuralChanges() { var scene = new GameScene("Dynamic Behaviors"); SceneManager.LoadScene(scene); @@ -311,7 +313,7 @@ public void GameBehaviorLifecycle_ReindexesAfterStructuralChanges() } [Fact] - public void GameBehaviorLifecycle_StartsLateOnlyBehaviorWithoutDispatchingUpdate() + public void GameBehaviorLifecycleStartsLateOnlyBehaviorWithoutDispatchingUpdate() { var scene = new GameScene("Phase-indexed Behaviors"); GameObject gameObject = scene.CreateObject("Late Actor"); @@ -326,7 +328,7 @@ public void GameBehaviorLifecycle_StartsLateOnlyBehaviorWithoutDispatchingUpdate } [Fact] - public void ResetComponent_UsesVirtualDispatchAndExplicitBaseCall() + public void ResetComponentUsesVirtualDispatchAndExplicitBaseCall() { var scene = new GameScene("Test"); GameObject gameObject = scene.CreateObject("Actor"); @@ -343,7 +345,7 @@ public void ResetComponent_UsesVirtualDispatchAndExplicitBaseCall() } [Fact] - public void SceneManager_LoadScene_ReplacesActiveScene() + public void SceneManagerLoadSceneReplacesActiveScene() { var first = new GameScene("First"); var second = new GameScene("Second"); @@ -367,11 +369,17 @@ private sealed class TestBehaviour : GameBehavior public int disableCount; protected override void Awake() => awakeCount++; + protected override void Start() => startCount++; + protected override void Update() => updateCount++; + protected override void FixedUpdate() => fixedUpdateCount++; + protected override void LateUpdate() => lateUpdateCount++; + protected override void OnEnable() => enableCount++; + protected override void OnDisable() => disableCount++; protected override void Reset() @@ -396,14 +404,12 @@ private sealed class LateOnlyBehaviour : GameBehavior protected override void LateUpdate() => lateUpdateCount++; } + // Open: DerivedResetComponent derives from it. private class BaseResetComponent : GameComponent { public int baseResetCount; - protected override void Reset() - { - baseResetCount++; - } + protected override void Reset() => baseResetCount++; } private sealed class DerivedResetComponent : BaseResetComponent @@ -417,7 +423,3 @@ protected override void Reset() } } } - -internal sealed class OrderComponentA : GameComponent; - -internal sealed class OrderComponentB : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs index fdaafdaa9..420c93422 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs @@ -1,10 +1,10 @@ using System; using System.Linq; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Scene.Layers; -using Xunit; namespace Inno.Scene.Tests; @@ -24,7 +24,7 @@ public void StructuralCaptureDoesNotRetainRemovedSystemsWhileTheSceneRemainsAliv GC.Collect(); Assert.False(removed.IsAlive); - var replacement = scene.AddSystem(); + OrderSerializationSystemB replacement = scene.AddSystem(); SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(scene, m_serializationContext); Assert.Same(replacement, Assert.Single(scene.GetSystems())); Assert.Equal(m_serialization.Serialize(scene, m_serializationContext), snapshot.ToArray()); @@ -121,10 +121,11 @@ public void UntrackedPluginPropertiesAndObjectReferencesRemainAuthoritativelyCap SerializationSnapshot restored = m_serialization.CaptureSnapshot(scene, m_serializationContext, changed); Assert.Equal(before.ToArray(), restored.ToArray()); } + [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference CaptureAndRemoveSystem(GameScene scene) { - var system = scene.AddSystem(); + OrderSerializationSystemA system = scene.AddSystem(); SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(scene, m_serializationContext); Assert.Equal(m_serialization.Serialize(scene, m_serializationContext), snapshot.ToArray()); Assert.True(scene.RemoveSystem(system)); diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs index 7cf0551e6..26a41c5cd 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs @@ -1,8 +1,8 @@ using System; using System.Linq; +using Xunit; using Inno.Assets; using Inno.Core.Serialization; -using Xunit; namespace Inno.Scene.Tests; @@ -20,12 +20,12 @@ public void ElementPropertyAliasesResolveThroughTheCurrentSceneIdentityOwner() byte[] source = SceneElementSerialization.CaptureState(probe, m_serialization, assets); // The fixture uses the ordinary serializer and verifies its complete current envelope before mutation. PropertyElementEnvelope envelope = m_serialization.Deserialize(source, m_serializationContext); - Assert.Equal(m_types.GetTypeRef(typeof(PropertyReferenceProbe)).stableId, envelope.typeId); + Assert.Equal(m_types.GetTypeRef(typeof(PropertyReferenceProbe)).stableID, envelope.typeId); probe.targetObject = null; SceneElementSerialization.RestoreState(probe, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets); Assert.Same(original, probe.targetObject); - envelope.aliasIds = [original.identity.persistentId]; - envelope.aliasTargets = [replacement.identity.persistentId]; + envelope.aliasIds = [original.identity.persistentID]; + envelope.aliasTargets = [replacement.identity.persistentID]; scene.DestroyObject(original); probe.targetObject = null; SceneElementSerialization.RestoreState(probe, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets); @@ -43,9 +43,11 @@ public void ElementPropertyAliasesRejectCollisionsMissingTargetsAndMalformedMeta probe.targetObject = original; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); PropertyElementEnvelope envelope = m_serialization.Deserialize( - SceneElementSerialization.CaptureState(probe, m_serialization, assets), m_serializationContext); - envelope.aliasIds = [original.identity.persistentId]; - envelope.aliasTargets = [replacement.identity.persistentId]; + SceneElementSerialization.CaptureState(probe, m_serialization, assets), + m_serializationContext + ); + envelope.aliasIds = [original.identity.persistentID]; + envelope.aliasTargets = [replacement.identity.persistentID]; probe.targetObject = null; Exception collision = Assert.ThrowsAny(Restore); Assert.Contains("Duplicate scene graph local identity", collision.ToString()); @@ -56,13 +58,18 @@ public void ElementPropertyAliasesRejectCollisionsMissingTargetsAndMalformedMeta Assert.Contains("targets missing object", missing.ToString()); Assert.Null(probe.targetObject); envelope.aliasIds = [Guid.Empty]; - envelope.aliasTargets = [replacement.identity.persistentId]; + envelope.aliasTargets = [replacement.identity.persistentID]; Exception malformed = Assert.ThrowsAny(Restore); Assert.Contains("invalid type, dependency or alias metadata", malformed.ToString()); Assert.Null(probe.targetObject); void Restore() - => SceneElementSerialization.RestoreState(probe, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets); + => SceneElementSerialization.RestoreState( + probe, + m_serialization.Serialize(envelope, m_serializationContext), + m_serialization, + assets + ); } [Fact] @@ -75,10 +82,21 @@ public void ElementPropertyRestoreRejectsReferencesOfTheWrongCurrentComponentTyp probe.targetComponent = probe; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); PropertyElementEnvelope envelope = m_serialization.Deserialize( - SceneElementSerialization.CaptureState(target, m_serialization, assets), m_serializationContext); - envelope.properties = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetComponent), m_serialization, assets); + SceneElementSerialization.CaptureState(target, m_serialization, assets), + m_serializationContext + ); + envelope.properties = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetComponent), + m_serialization, + assets + ); Exception failure = Assert.ThrowsAny(() => SceneElementSerialization.RestoreState( - target, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets)); + target, + m_serialization.Serialize(envelope, m_serializationContext), + m_serialization, + assets + )); Assert.Contains("targetComponent", failure.ToString()); Assert.Null(target.targetComponent); } @@ -95,56 +113,24 @@ public void PropertyRestoreRejectsAnInvalidReferenceKindBeforeAssigningTheTarget .Single(value => value.name == nameof(PropertyReferenceProbe.targetComponent)); byte[] original = property.data.ToArray(); PropertyReferenceTokenFixture token = m_serialization.Deserialize(original, m_serializationContext); - Assert.Equal(owner.transform.identity.persistentId, token.sourceId); + Assert.Equal(owner.transform.identity.persistentID, token.sourceId); token.kind = int.MaxValue; byte[] invalid = m_serialization.Serialize(token, m_serializationContext); Assert.Equal(original.Length, invalid.Length); - byte[] payload = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetComponent), m_serialization, assets); + byte[] payload = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetComponent), + m_serialization, + assets + ); int offset = payload.AsSpan().IndexOf(original); Assert.True(offset >= 0, "The public property document did not contain its independently encoded value."); invalid.CopyTo(payload.AsSpan(offset, invalid.Length)); probe.targetComponent = null; - Exception failure = Assert.ThrowsAny(() => ScenePropertySerialization.RestoreProperties(probe, payload, m_serialization, assets)); + Exception failure = Assert.ThrowsAny( + () => ScenePropertySerialization.RestoreProperties(probe, payload, m_serialization, assets) + ); Assert.Contains("not a GameComponent reference", failure.ToString()); Assert.Null(probe.targetComponent); } } - -internal sealed class PropertyReferenceTokenFixture : ISerializable -{ - [SerializableProperty] - public int kind { get; set; } - - [SerializableProperty] - public Guid sourceId { get; set; } -} - -/// -/// Creates valid and deliberately invalid current element envelopes through the public serializer. -/// -internal sealed class PropertyElementEnvelope : ISerializable -{ - [SerializableProperty] - public Guid typeId { get; set; } - - [SerializableProperty] - public string typeName { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] properties { get; set; } = []; - - [SerializableProperty] - public Guid[] dependencyIds { get; set; } = []; - - [SerializableProperty] - public Guid[] dependencyTypes { get; set; } = []; - - [SerializableProperty] - public string[] dependencyPaths { get; set; } = []; - - [SerializableProperty] - public Guid[] aliasIds { get; set; } = []; - - [SerializableProperty] - public Guid[] aliasTargets { get; set; } = []; -} diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs index bf0f24e98..3826b5e40 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs @@ -1,10 +1,8 @@ using System; using System.Linq; +using Xunit; using Inno.Assets; using Inno.Core.Identity; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; -using Xunit; namespace Inno.Scene.Tests; @@ -18,18 +16,26 @@ public void ScalarPropertyPreparationDoesNotAllocateAnIndexOfUnrelatedSceneObjec IAssetReferenceResolver assets = m_serializationContext.GetRequired(); long small = Measure(); for (int index = 0; index < 5_000; index++) + { _ = scene.CreateObject("Unrelated " + index); + } long large = Measure(); - Assert.True(large <= small + 64 * 1024, - $"Ten scalar property captures allocated {small} bytes in a small Scene and {large} with 5,000 unrelated objects."); + Assert.True( + large <= small + 64 * 1024, + $"Ten scalar property captures allocated {small} bytes in a small Scene and {large} with 5,000 unrelated objects." + ); long Measure() { for (int index = 0; index < 10; index++) + { _ = ScenePropertySerialization.CapturePropertySnapshots(owner.transform, m_serialization, assets); + } long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 10; index++) + { Assert.Equal(3, ScenePropertySerialization.CapturePropertySnapshots(owner.transform, m_serialization, assets).Count); + } return GC.GetAllocatedBytesForCurrentThread() - before; } } @@ -53,8 +59,11 @@ public void PropertyReferencesRestoreCurrentObjectComponentAndSystemInstancesAft Assert.True(SceneManager.UnloadScene(scene)); GameScene replacement = m_serialization.Deserialize(graph, m_serializationContext); SceneManager.LoadScene(replacement); - PropertyReferenceProbe restored = replacement.GetObjects().Single(value => value.name == "Owner").GetComponents() - .OfType().Single(); + PropertyReferenceProbe restored = replacement.GetObjects() + .Single(value => value.name == "Owner") + .GetComponents() + .OfType() + .Single(); GameObject current = replacement.GetObjects().Single(value => value.name == "Target"); restored.targetObject = null; restored.targetComponent = null; @@ -63,7 +72,7 @@ public void PropertyReferencesRestoreCurrentObjectComponentAndSystemInstancesAft Assert.Same(current, restored.targetObject); Assert.Same(current.GetComponents().OfType().Single(), restored.targetComponent); Assert.Same(replacement.GetSystems().OfType().Single(), restored.targetSystem); - Assert.Equal(target.identity.persistentId, current.identity.persistentId); + Assert.Equal(target.identity.persistentID, current.identity.persistentID); Assert.NotSame(target, current); Assert.True(target.isDestroyed); } @@ -97,7 +106,12 @@ public void MissingPropertyTargetRejectsRestoreWithoutAssigningTheDestroyedObjec GameObject target = scene.CreateObject("Target"); probe.targetObject = target; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); - byte[] property = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetObject), m_serialization, assets); + byte[] property = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetObject), + m_serialization, + assets + ); scene.DestroyObject(target); probe.targetObject = null; Assert.ThrowsAny(() => ScenePropertySerialization.RestoreProperties(probe, property, m_serialization, assets)); @@ -119,7 +133,12 @@ public void NestedPropertyReadsAndGetterFailuresRestoreTheOuterReferenceScope() IAssetReferenceResolver assets = m_serializationContext.GetRequired(); probe.beforeRead = () => { - byte[] value = ScenePropertySerialization.CaptureProperty(nested, nameof(ReferenceComponent.targetObject), m_serialization, assets); + byte[] value = ScenePropertySerialization.CaptureProperty( + nested, + nameof(ReferenceComponent.targetObject), + m_serialization, + assets + ); nested.targetObject = null; _ = ScenePropertySerialization.RestoreProperties(nested, value, m_serialization, assets); Assert.NotNull(nested.targetObject); @@ -136,29 +155,3 @@ public void NestedPropertyReadsAndGetterFailuresRestoreTheOuterReferenceScope() Assert.NotEmpty(m_serialization.Serialize(nestedScene.CreateObject("Independent prefab"), m_serializationContext)); } } - -[StableTypeId("486290eb-6cc4-4a96-918a-c8022f51ad85")] -internal sealed class PropertyReferenceProbe : GameComponent -{ - internal Action? beforeRead { get; set; } - - [SerializableProperty(order = -1)] - public int trigger - { - get - { - beforeRead?.Invoke(); - return 0; - } - set { } - } - - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public GameComponent? targetComponent { get; set; } - - [SerializableProperty] - public GameSystem? targetSystem { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs index 180d8b25a..9bf0b6087 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs @@ -1,20 +1,17 @@ using System; using System.Linq; using System.Runtime.CompilerServices; - +using Xunit; using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; -using Inno.Scene; +using Inno.Extensibility.Types; using Inno.Scene.Components; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed partial class SceneSerializationTests : IDisposable { private readonly TypeCatalog m_types; @@ -39,17 +36,17 @@ public void Dispose() [Fact] public void MissingSceneTypeDiagnosticPreservesStableIdentity() { - Guid stableTypeId = Guid.Parse("80f1fb70-95f7-4db2-b338-2567cf8bb2c1"); + Guid stableTypeID = Guid.Parse("80f1fb70-95f7-4db2-b338-2567cf8bb2c1"); - var exception = new SceneTypeResolutionException(stableTypeId, "component"); + var exception = new SceneTypeResolutionException(stableTypeID, "component"); - Assert.Equal(stableTypeId, exception.stableTypeId); + Assert.Equal(stableTypeID, exception.stableTypeID); Assert.Equal("component", exception.elementKind); - Assert.Contains(stableTypeId.ToString("D"), exception.Message, StringComparison.Ordinal); + Assert.Contains(stableTypeID.ToString("D"), exception.Message, StringComparison.Ordinal); } [Fact] - public void SceneRoundtrip_PreservesHierarchyOrderStateAndDirectReferences() + public void SceneRoundtripPreservesHierarchyOrderStateAndDirectReferences() { var source = new GameScene("Roundtrip"); GameObject root = source.CreateObject("Root"); @@ -70,32 +67,35 @@ public void SceneRoundtrip_PreservesHierarchyOrderStateAndDirectReferences() childReference.targetObject = root; childReference.targetComponent = rootReference; - Guid sceneId = source.identity.persistentId; - Guid rootId = root.identity.persistentId; - Guid childId = child.identity.persistentId; + Guid sceneID = source.identity.persistentID; + Guid rootID = root.identity.persistentID; + Guid childID = child.identity.persistentID; byte[] bytes = m_serialization.Serialize(source, m_serializationContext); Assert.Contains( m_types.GetSubTypesOf(), - type => type.Resolve(m_types).Name == "GameSceneConverter"); + type => type.Resolve(m_types).Name == "GameSceneConverter" + ); SceneManager.LoadScene(source); Assert.True(SceneManager.UnloadScene(source)); GameScene restored = m_serialization.Deserialize(bytes, m_serializationContext); SceneManager.LoadScene(restored); - Assert.Equal(sceneId, restored.identity.persistentId); + Assert.Equal(sceneID, restored.identity.persistentID); Assert.Equal("Roundtrip", restored.name); Assert.Equal(2, restored.GetObjects().Count); - GameObject restoredRoot = restored.GetObjects().Single(gameObject => gameObject.identity.persistentId == rootId); - GameObject restoredChild = restored.GetObjects().Single(gameObject => gameObject.identity.persistentId == childId); + GameObject restoredRoot = restored.GetObjects().Single(gameObject => gameObject.identity.persistentID == rootID); + GameObject restoredChild = restored.GetObjects().Single(gameObject => gameObject.identity.persistentID == childID); Assert.Equal("Player", restoredRoot.tag); Assert.Equal("Companion", restoredChild.tag); Assert.Equal(new GameLayer(3), restoredRoot.layer); Assert.Equal(new GameLayer(7), restoredChild.layer); Assert.Same(restoredRoot, restored.FindObjectWithLayer(new GameLayer(3))); Assert.Same(restoredRoot, restored.FindObjectWithTag("Player")); - Assert.Equal(new[] { typeof(Transform), typeof(ReferenceComponent) }, - restoredRoot.GetComponents().Select(static component => component.GetType())); + Assert.Equal( + new[] { typeof(Transform), typeof(ReferenceComponent) }, + restoredRoot.GetComponents().Select(static component => component.GetType()) + ); Assert.Same(restoredRoot.transform, restoredChild.transform.parent); Assert.Equal(new Vector3(1, 2, 3), restoredChild.transform.localPosition); Assert.False(restoredChild.activeSelf); @@ -114,7 +114,7 @@ public void SceneRoundtrip_PreservesHierarchyOrderStateAndDirectReferences() } [Fact] - public void PrefabInstantiation_RemapsIdentitiesAndIsolatesInternalReferences() + public void PrefabInstantiationRemapsIdentitiesAndIsolatesInternalReferences() { var sourceScene = new GameScene("PrefabSource"); GameObject sourceRoot = sourceScene.CreateObject("Root"); @@ -138,7 +138,7 @@ public void PrefabInstantiation_RemapsIdentitiesAndIsolatesInternalReferences() SceneManager.LoadSceneAdditive(targetScene); Assert.NotSame(first, second); - Assert.NotEqual(first.identity.persistentId, second.identity.persistentId); + Assert.NotEqual(first.identity.persistentID, second.identity.persistentID); GameObject firstChild = Assert.Single(first.transform.children).gameObject; GameObject secondChild = Assert.Single(second.transform.children).gameObject; Assert.Equal("Spawn", first.tag); @@ -157,8 +157,9 @@ public void PrefabInstantiation_RemapsIdentitiesAndIsolatesInternalReferences() Assert.Same(secondChild.GetComponent(), secondReference.targetComponent); Assert.NotSame(firstReference.targetObject, secondReference.targetObject); Assert.NotEqual( - firstReference.targetComponent!.identity.persistentId, - secondReference.targetComponent!.identity.persistentId); + firstReference.targetComponent!.identity.persistentID, + secondReference.targetComponent!.identity.persistentID + ); } [Fact] @@ -181,14 +182,16 @@ public void SceneRoundtripPreservesManualComponentAndSystemOrder() Assert.Equal( [typeof(OrderComponentB), typeof(OrderComponentA), typeof(Transform)], - Assert.Single(restored.GetObjects()).GetComponents().Select(static component => component.GetType())); + Assert.Single(restored.GetObjects()).GetComponents().Select(static component => component.GetType()) + ); Assert.Equal( [typeof(OrderSerializationSystemB), typeof(OrderSerializationSystemA)], - restored.GetSystems().Select(static system => system.GetType())); + restored.GetSystems().Select(static system => system.GetType()) + ); } [Fact] - public void SerializableLayerValues_RoundtripThroughComponentState() + public void SerializableLayerValuesRoundtripThroughComponentState() { var scene = new GameScene("GameLayer Values"); LayerValueComponent component = scene.CreateObject("Object").AddComponent(); @@ -212,8 +215,8 @@ public void LoadedSceneRestoreKeepsSceneIdentityAndRebuildsItsObjectGraph() { var scene = new GameScene("Before"); GameObject original = scene.CreateObject("Original"); - Guid sceneId = scene.identity.persistentId; - Guid objectId = original.identity.persistentId; + Guid sceneID = scene.identity.persistentID; + Guid objectID = original.identity.persistentID; byte[] before = m_serialization.Serialize(scene, m_serializationContext); SceneManager.LoadScene(scene); @@ -222,16 +225,16 @@ public void LoadedSceneRestoreKeepsSceneIdentityAndRebuildsItsObjectGraph() m_serialization.Restore(scene, before, m_serializationContext); Assert.Same(scene, SceneManager.activeScene); - Assert.Equal(sceneId, scene.identity.persistentId); + Assert.Equal(sceneID, scene.identity.persistentID); Assert.Equal("Before", scene.name); GameObject restored = Assert.Single(scene.GetObjects()); - Assert.Equal(objectId, restored.identity.persistentId); + Assert.Equal(objectID, restored.identity.persistentID); Assert.Equal("Original", restored.name); Assert.True(scene.isLoaded); } [Fact] - public void PrefabCapture_RejectsReferenceOutsideCapturedSubtreeWithDiagnosticContext() + public void PrefabCaptureRejectsReferenceOutsideCapturedSubtreeWithDiagnosticContext() { var scene = new GameScene("Boundary"); GameObject root = scene.CreateObject("Root"); @@ -239,22 +242,26 @@ public void PrefabCapture_RejectsReferenceOutsideCapturedSubtreeWithDiagnosticCo root.AddComponent().targetObject = external; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(root, m_serializationContext)); + () => m_serialization.Serialize(root, m_serializationContext) + ); Assert.Contains(typeof(ReferenceComponent).FullName!, exception.Message); Assert.Contains("targetObject", exception.Message); - Assert.Contains(external.identity.persistentId.ToString(), exception.Message); - Assert.Contains(root.identity.persistentId.ToString(), exception.Message); + Assert.Contains(external.identity.persistentID.ToString(), exception.Message); + Assert.Contains(root.identity.persistentID.ToString(), exception.Message); SceneManager.LoadScene(scene); Assert.True(SceneManager.UnloadScene(scene)); } [Fact] - public void SceneUnload_ReleasesCyclicSceneObjectGraphForGarbageCollection() + public void SceneUnloadReleasesCyclicSceneObjectGraphForGarbageCollection() { - (WeakReference scene, WeakReference gameObject, WeakReference component) = - CreateAndUnloadCyclicGraph(); + ( + WeakReference scene, + WeakReference gameObject, + WeakReference component + ) = CreateAndUnloadCyclicGraph(); for (int i = 0; i < 8; i++) { @@ -292,33 +299,3 @@ private static ( return (sceneReference, objectReference, componentReference); } } - -[StableTypeId("09d35197-7161-4fdf-8d60-95ecf3555c0c")] -internal sealed class ReferenceComponent : GameComponent -{ - [SerializableProperty] public int value { get; set; } - [SerializableProperty] public GameObject? targetObject { get; set; } - [SerializableProperty] public ReferenceComponent? targetComponent { get; set; } - public int resetCount { get; private set; } - - protected override void Reset() - { - resetCount++; - } -} - -[StableTypeId("f7bc9bf3-288a-45b3-9caa-26289d66c181")] -internal sealed class OrderSerializationSystemA : GameSystem; - -[StableTypeId("6924359d-798d-4384-bdb2-1b0e34ab3fbb")] -internal sealed class OrderSerializationSystemB : GameSystem; - -[StableTypeId("821c7b92-9aeb-40cb-924e-169004199ef0")] -internal sealed class LayerValueComponent : GameComponent -{ - [SerializableProperty] - public GameLayer layer { get; set; } - - [SerializableProperty] - public GameLayerMask mask { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs index aa302dda4..3b78f2508 100644 --- a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs +++ b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs @@ -1,75 +1,9 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using System; -using System.IO; - -using Inno.Assets; -using Inno.Extensibility.Modules; -using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Core.Serialization; - using Xunit; namespace Inno.Scene.Tests; -[CollectionDefinition(NAME)] +[CollectionDefinition(C_NAME)] public sealed class SceneTestsCollection : ICollectionFixture { - public const string NAME = nameof(SceneTestsCollection); -} - -public sealed class SceneTestsFixture : IDisposable -{ - private readonly string m_cacheDirectory = Path.Combine( - Path.GetTempPath(), - "InnoSceneTests", - Guid.NewGuid().ToString("N")); - - public ModuleHost modules { get; } - public TypeCatalog types { get; } - public SerializationRegistry serialization { get; } - public IAssetReferenceResolver assets { get; } - public IdentityAllocator identities { get; } = new(); - public DiagnosticHub diagnostics { get; } = new(); - public LogRouter logs { get; } = new(); - public Inno.Scene.SceneWorld world { get; } - public SerializationContext serializationContext { get; } - - public SceneTestsFixture() - { - _ = typeof(Inno.Scene.SceneAsset); - modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) }); - types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - world = new Inno.Scene.SceneWorld(identities, types); - assets = new RejectingAssetReferenceResolver(); - serializationContext = AssetSerializationContext.Create(assets); - } - - public void Dispose() - { - world.Dispose(); - serialization.Dispose(); - types.Dispose(); - modules.Dispose(); - logs.Dispose(); - if (Directory.Exists(m_cacheDirectory)) - Directory.Delete(m_cacheDirectory, recursive: true); - } - - private sealed class RejectingAssetReferenceResolver : IAssetReferenceResolver - { - public AssetObject Resolve( - Guid persistentId, - Guid stableTypeId, - string lastKnownPath, - Type expectedType, - string propertyPath) - => throw new InvalidOperationException( - $"Unexpected asset reference '{persistentId:D}' at '{propertyPath}'."); - } + public const string C_NAME = nameof(SceneTestsCollection); } diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs b/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs new file mode 100644 index 000000000..ddb84d5b9 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Core.Diagnostics; +using Inno.Core.Identity; +using Inno.Core.Logging; +using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +public sealed class SceneTestsFixture : IDisposable +{ + private readonly string m_cacheDirectory = Path.Combine( + Path.GetTempPath(), + "InnoSceneTests", + Guid.NewGuid().ToString("N") + ); + + public SceneTestsFixture() + { + _ = typeof(SceneAsset); + this.modules = new ModuleHost(new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) + }); + this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); + this.world = new SceneWorld(identities, types); + this.assets = new RejectingAssetReferenceResolver(); + this.serializationContext = AssetSerializationContext.Create(assets); + } + + public ModuleHost modules { get; } + public TypeCatalog types { get; } + public SerializationRegistry serialization { get; } + public IAssetReferenceResolver assets { get; } + public IdentityAllocator identities { get; } = new(); + public DiagnosticHub diagnostics { get; } = new(); + public LogRouter logs { get; } = new(); + public SceneWorld world { get; } + public SerializationContext serializationContext { get; } + + public void Dispose() + { + world.Dispose(); + serialization.Dispose(); + types.Dispose(); + modules.Dispose(); + logs.Dispose(); + if (Directory.Exists(m_cacheDirectory)) + { + Directory.Delete(m_cacheDirectory, recursive: true); + } + } + + private sealed class RejectingAssetReferenceResolver : IAssetReferenceResolver + { + public AssetObject Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ) => throw new InvalidOperationException($"Unexpected asset reference '{persistentID:D}' at '{propertyPath}'."); + } +} diff --git a/tests/scene/Inno.Scene.Tests/StateSystem.cs b/tests/scene/Inno.Scene.Tests/StateSystem.cs new file mode 100644 index 000000000..bda23b938 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/StateSystem.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("b469170b-a1f2-4176-b3ad-252d1cb53b90")] +internal sealed class StateSystem : GameSystem +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public SystemReferenceComponent? component { get; set; } + + public int resetCount { get; private set; } + + protected override void Reset() => resetCount++; +} diff --git a/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs new file mode 100644 index 000000000..4ac6a0212 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("75344398-ed18-46ae-808b-e0cb45d93850")] +internal sealed class SystemReferenceComponent : GameComponent +{ + [SerializableProperty] + public StateSystem? system { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/TransformTests.cs b/tests/scene/Inno.Scene.Tests/TransformTests.cs index 94bb15c27..ad38dfb60 100644 --- a/tests/scene/Inno.Scene.Tests/TransformTests.cs +++ b/tests/scene/Inno.Scene.Tests/TransformTests.cs @@ -1,14 +1,12 @@ using System; - +using Xunit; using Inno.Core.Mathematics; using Inno.Scene; using Inno.Scene.Components; -using Xunit; - namespace Inno.Scene.Tests; -[Collection(SceneTestsCollection.NAME)] +[Collection(SceneTestsCollection.C_NAME)] public sealed class TransformTests : IDisposable { private readonly IDisposable m_sceneScope; @@ -25,7 +23,7 @@ public void Dispose() } [Fact] - public void SetParent_PreservesWorldTransform_AndComputesLocalWithNonUniformScale() + public void SetParentPreservesWorldTransformAndComputesLocalWithNonUniformScale() { var scene = new GameScene("SetParentScale"); Transform parent = scene.CreateObject("Parent").GetComponent(); @@ -49,8 +47,8 @@ public void SetParent_PreservesWorldTransform_AndComputesLocalWithNonUniformScal Assert.Equal(worldRotation, child.worldRotation); Assert.Equal(worldScale, child.worldScale); - Vector3 expectedLocalPosition = new Vector3(-0.5f, -0.33333334f, -0.25f); - Vector3 expectedLocalScale = new Vector3(1f, 0.6666667f, 0.5f); + var expectedLocalPosition = new Vector3(-0.5f, -0.33333334f, -0.25f); + var expectedLocalScale = new Vector3(1f, 0.6666667f, 0.5f); AssertEqualWithTolerance(worldPosition, child.worldPosition, 1e-5f); AssertEqualWithTolerance(worldRotation.normalized, child.worldRotation.normalized, 1e-5f); @@ -61,7 +59,7 @@ public void SetParent_PreservesWorldTransform_AndComputesLocalWithNonUniformScal } [Fact] - public void SetParent_WithRotation_PreservesWorldRotation_WithLocalRotationByInverseParent() + public void SetParentWithRotationPreservesWorldRotationWithLocalRotationByInverseParent() { var scene = new GameScene("SetParentRotation"); Transform parent = scene.CreateObject("Parent").GetComponent(); @@ -81,7 +79,7 @@ public void SetParent_WithRotation_PreservesWorldRotation_WithLocalRotationByInv child.SetParent(parent); - Vector3 expectedLocalPosition = new Vector3(0f, 2f, 0f); + var expectedLocalPosition = new Vector3(0f, 2f, 0f); Quaternion expectedLocalRotation = Quaternion.Inverse(parent.localRotation) * worldRotation; Quaternion normalizedExpectedRotation = expectedLocalRotation.normalized; @@ -93,7 +91,7 @@ public void SetParent_WithRotation_PreservesWorldRotation_WithLocalRotationByInv } [Fact] - public void SetParent_UnparentPreservesWorldTransform() + public void SetParentUnparentPreservesWorldTransform() { var scene = new GameScene("Unparent"); Transform parent = scene.CreateObject("Parent").GetComponent(); @@ -124,7 +122,7 @@ public void SetParent_UnparentPreservesWorldTransform() } [Fact] - public void SetParent_RejectsSelfAndDescendantCycle() + public void SetParentRejectsSelfAndDescendantCycle() { var scene = new GameScene("Cycle"); Transform root = scene.CreateObject("Root").GetComponent(); @@ -142,7 +140,7 @@ public void SetParent_RejectsSelfAndDescendantCycle() } [Fact] - public void TransformPoint_UsesExactRotatedNonUniformParentHierarchy() + public void TransformPointUsesExactRotatedNonUniformParentHierarchy() { var scene = new GameScene("ExactHierarchy"); Transform parent = scene.CreateObject("Parent").GetComponent(); @@ -156,10 +154,13 @@ public void TransformPoint_UsesExactRotatedNonUniformParentHierarchy() child.localScale = new Vector3(2f, 1.5f, 1f); var localPoint = new Vector3(0.3f, -0.6f, 0f); - Vector3 expected = Vector3.Transform(localPoint, parent.localToWorldMatrix + Vector3 expected = Vector3.Transform( + localPoint, + parent.localToWorldMatrix * Matrix.CreateTranslation(child.localPosition) * Matrix.CreateFromQuaternion(child.localRotation) - * Matrix.CreateScale(child.localScale)); + * Matrix.CreateScale(child.localScale) + ); Vector3 actual = child.TransformPoint(localPoint); AssertEqualWithTolerance(expected, actual, 1e-5f); @@ -167,7 +168,7 @@ public void TransformPoint_UsesExactRotatedNonUniformParentHierarchy() } [Fact] - public void WorldPosition_UsesExactInverseUnderShearedAncestorHierarchy() + public void WorldPositionUsesExactInverseUnderShearedAncestorHierarchy() { var scene = new GameScene("ExactWorldSetter"); Transform root = scene.CreateObject("Root").transform; @@ -188,7 +189,7 @@ public void WorldPosition_UsesExactInverseUnderShearedAncestorHierarchy() } [Fact] - public void WorldToLocal_RejectsNonInvertibleZeroScaleHierarchy() + public void WorldToLocalRejectsNonInvertibleZeroScaleHierarchy() { var scene = new GameScene("SingularTransform"); Transform transform = scene.CreateObject("Zero Scale").transform; @@ -197,8 +198,11 @@ public void WorldToLocal_RejectsNonInvertibleZeroScaleHierarchy() Assert.Throws(() => transform.InverseTransformPoint(Vector3.ONE)); } - private static void AssertEqualWithTolerance(Vector3 expected, Vector3 actual, float tolerance) - { + private static void AssertEqualWithTolerance( + Vector3 expected, + Vector3 actual, + float tolerance + ) { float deltaX = expected.x - actual.x; float deltaY = expected.y - actual.y; float deltaZ = expected.z - actual.z; @@ -207,8 +211,11 @@ private static void AssertEqualWithTolerance(Vector3 expected, Vector3 actual, f Assert.True(distance <= tolerance); } - private static void AssertEqualWithTolerance(Quaternion expected, Quaternion actual, float tolerance) - { + private static void AssertEqualWithTolerance( + Quaternion expected, + Quaternion actual, + float tolerance + ) { float deltaX = expected.x - actual.x; float deltaY = expected.y - actual.y; float deltaZ = expected.z - actual.z; diff --git a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs index d3c78ca2e..8c0d4e44d 100644 --- a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs +++ b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs @@ -9,7 +9,7 @@ namespace Inno.Scene.Reload.TestModule; /// /// Provides reloadable scene state for validating Plugin generation removal and recovery. /// -[StableTypeId("9f67d41e-082b-46d5-aaf0-dfc76c693182")] +[StableTypeID("9f67d41e-082b-46d5-aaf0-dfc76c693182")] public sealed class ReloadableSceneComponent : GameComponent { /// @@ -34,6 +34,8 @@ public sealed class ReloadableSceneComponent : GameComponent private void ValidateRestoredState() { if (rejectRestore) + { throw new InvalidOperationException("Component state rejected restoration."); + } } } diff --git a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneSystem.cs b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneSystem.cs index 5320c3567..bc60bd39f 100644 --- a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneSystem.cs +++ b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneSystem.cs @@ -7,7 +7,7 @@ namespace Inno.Scene.Reload.TestModule; /// /// Provides persistent system state for exercising missing-system History and reload recovery. /// -[StableTypeId("92dd722d-f4ce-468d-8f6d-056cf5b1f79b")] +[StableTypeID("92dd722d-f4ce-468d-8f6d-056cf5b1f79b")] public sealed class ReloadableSceneSystem : GameSystem { /// diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs new file mode 100644 index 000000000..480904553 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs @@ -0,0 +1,20 @@ +using System; +using Inno.Core.Serialization; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class AttributeOwner : ISerializable +{ + [SerializableProperty] + [Header("Presentation", "Decorators are composed before the property row.")] + [Text("Persistent decorator text remains visible.")] + [Tooltip("Reusable hover guidance.")] + [InspectorName("Friendly Value")] + [Range(2, 8)] + [ShowIf(nameof(showValue))] + [ProbeInspector] + public AttributeValue value { get; set; } = new(); + + internal bool showValue { get; set; } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs new file mode 100644 index 000000000..7f5505c5b --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class AttributeValue; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs new file mode 100644 index 000000000..c3f3c69b5 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(AttributeValue), priority: 10_000)] +internal sealed class AttributeValueDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) + => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs new file mode 100644 index 000000000..ca7321253 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs @@ -0,0 +1,8 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class CapturedScriptPayload(ISerializable payload) : ISerializable +{ + internal ISerializable payload { get; } = payload; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs new file mode 100644 index 000000000..a263b2c35 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class CapturedScriptPayloadConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CapturedScriptPayload value + ) => writer.WritePropertiesData("state", value.payload); + + public override CapturedScriptPayload Read(SerializationReader reader) + => throw new NotSupportedException("This fixture only captures an existing generation."); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs index d25ae3b23..626dd1f92 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -11,22 +10,24 @@ namespace Inno.Editor.Scripting.Tests; [AssetImporter("tests.scripting.controlled-sample-asset")] internal sealed class ControlledSampleAssetImporter : AssetImporter { - private static readonly AsyncLocal m_current = new(); + private static readonly AsyncLocal CURRENT = new(); /// /// Creates a discoverable importer that uses only test-owned synchronization state. /// - public ControlledSampleAssetImporter() - { - } - - internal static Control? current { get => m_current.Value; set => m_current.Value = value; } + public ControlledSampleAssetImporter() {} /// /// Gets the unique source extension used by the real importer cancellation test. /// public override IReadOnlyList supportedExtensions { get; } = [".samplebusy"]; + internal static Control? current + { + get => CURRENT.Value; + set => CURRENT.Value = value; + } + /// /// Suspends a Project clone until the transaction's cancellation reaches its importer. /// @@ -47,8 +48,8 @@ protected override async ValueTask ImportAsync( AssetImportWriter output, CancellationToken cancellationToken ) { - Control? control = m_current.Value; - if (control is not null && context.assetPath.source == AssetSourceId.project) + Control? control = CURRENT.Value; + if (control is not null && context.assetPath.source == AssetSourceID.project) { control.workerThread = Environment.CurrentManagedThreadId; control.started.Set(); @@ -56,15 +57,11 @@ CancellationToken cancellationToken await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); } output.SetAsset(new TextAsset(context.ReadUtf8Text())); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } internal sealed class Control : IDisposable { - internal ManualResetEventSlim started { get; } = new(); - internal ManualResetEventSlim canceled { get; } = new(); - internal int workerThread { get; set; } - /// /// Releases the test-owned synchronization handles after the importer drains. /// @@ -73,5 +70,9 @@ public void Dispose() started.Dispose(); canceled.Dispose(); } + + internal ManualResetEventSlim started { get; } = new(); + internal ManualResetEventSlim canceled { get; } = new(); + internal int workerThread { get; set; } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs index 32129455d..ac71a193f 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Threading; - using Inno.Assets.Pipeline; namespace Inno.Editor.Scripting.Tests; @@ -8,44 +7,50 @@ namespace Inno.Editor.Scripting.Tests; [AssetSampleSourceRewriter("tests.scripting.controlled-sample")] internal sealed class ControlledSampleSourceRewriter : IAssetSampleSourceRewriter { - private static readonly AsyncLocal m_current = new(); - private readonly Control? m_control = m_current.Value; + private static readonly AsyncLocal CURRENT = new(); + private readonly Control? m_control = CURRENT.Value; /// /// Captures the current test-owned control through the real source rewriter discovery contract. /// - public ControlledSampleSourceRewriter() - { - } + public ControlledSampleSourceRewriter() {} - internal static Control? current { get => m_current.Value; set => m_current.Value = value; } - - /// + /// public void Transform(AssetSampleTransformContext context) { if (m_control is null) + { return; + } m_control.workerThread = Environment.CurrentManagedThreadId; m_control.started.Set(); using CancellationTokenRegistration cancellation = context.cancellationToken.Register(m_control.canceled.Set); if (!m_control.release.Wait(TimeSpan.FromSeconds(15))) + { throw new TimeoutException("The test-owned source rewriter was not released."); + } context.cancellationToken.ThrowIfCancellationRequested(); } - internal sealed class Control : IDisposable + internal static Control? current { - internal ManualResetEventSlim started { get; } = new(); - internal ManualResetEventSlim release { get; } = new(); - internal ManualResetEventSlim canceled { get; } = new(); - internal int workerThread { get; set; } + get => CURRENT.Value; + set => CURRENT.Value = value; + } - /// + internal sealed class Control : IDisposable + { + /// public void Dispose() { started.Dispose(); release.Dispose(); canceled.Dispose(); } + + internal ManualResetEventSlim started { get; } = new(); + internal ManualResetEventSlim release { get; } = new(); + internal ManualResetEventSlim canceled { get; } = new(); + internal int workerThread { get; set; } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs index 7515204d2..7039e3804 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs @@ -1,47 +1,51 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using ImGuiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; -using ImGuiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using ImGuiCol = Inno.Editor.ImGui.ImGuiCol; -using ImGuiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui; using Inno.Native.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUISession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using InlineRenameResult = Inno.Editor.ImGui.ImGuiWidget.InlineRenameResult; -using TreeNodeOptions = Inno.Editor.ImGui.ImGuiWidget.TreeNodeOptions; -using TreeNodeResult = Inno.Editor.ImGui.ImGuiWidget.TreeNodeResult; +using GuiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; +using GuiCol = Inno.Editor.ImGui.ImGuiCol; +using GuiCond = Inno.Editor.ImGui.ImGuiCond; +using GuiInlineRenameResult = Inno.Editor.ImGui.ImGuiWidget.InlineRenameResult; +using GuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using GuiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; +using GuiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; +using GuiTreeNodeOptions = Inno.Editor.ImGui.ImGuiWidget.TreeNodeOptions; +using GuiTreeNodeResult = Inno.Editor.ImGui.ImGuiWidget.TreeNodeResult; +using GuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; +using NativeCond = Inno.Native.ImGui.ImGuiCond; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.Scripting.Tests; + public sealed unsafe class EditorStyleMetricsTests { [Fact] public void BrowserLayoutCapturesTheSharedScaleWithoutRetainingMutableMetrics() { var metrics = new EditorStyleMetrics(); - var browser = new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics); + var browser = new AssetBrowserStyle(metrics); Assert.Equal(32f, browser.gridMinimumCellSize); metrics.SetZoom(1.5f); Assert.Equal(32f, browser.gridMinimumCellSize); - var scaled = new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics); + var scaled = new AssetBrowserStyle(metrics); Assert.Equal(48f, scaled.gridMinimumCellSize); Assert.Equal(browser.gridDefaultScale, scaled.gridDefaultScale); Assert.Equal(browser.listNameSeparatorPosition, scaled.listNameSeparatorPosition); - Assert.Equal(32f, default(Inno.Editor.Assets.ImGui.AssetBrowserStyle).gridMinimumCellSize); + Assert.Equal(32f, default(AssetBrowserStyle).gridMinimumCellSize); Assert.Equal(7.5f, metrics.toolbarSectionSpacing); Assert.Equal(24f, metrics.paneMinimumVisibleWidth); - Assert.Throws(() => new Inno.Editor.Assets.ImGui.AssetBrowserStyle(null!)); + Assert.Throws(() => new AssetBrowserStyle(null!)); } [Fact] @@ -55,7 +59,7 @@ public void ZoomScalesDimensionsAndFontWhilePreservingRatios() Assert.Equal(3f, metrics.frameRounding, 3); Assert.Equal(1.8f, metrics.fontScale, 3); Assert.Equal(0.4f, metrics.propertyLabelRatio, 3); - Assert.Equal(3f, new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics).gridDefaultScale, 3); + Assert.Equal(3f, new AssetBrowserStyle(metrics).gridDefaultScale, 3); Assert.Equal(new Vector2(7.5f, 4.5f), metrics.cellPadding); } @@ -77,26 +81,28 @@ public void ZoomCommandsClampAndResetToTheSupportedRange() [Fact] public void WrappedTextRendersThroughTheSafeLiteralTextPath() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(260f, 180f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(260f, 180f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Wrapped Text Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); float lineHeight = NativeImGui.GetTextLineHeight(); - EditorUI.current.widgets.WrappedText("Literal %s text remains safe and wraps. This deliberately long compilation status " + "must stay inside the modal content width instead of extending beyond its right edge."); + EditorUI.current.widgets.WrappedText( + "Literal %s text remains safe and wraps. This deliberately long compilation status " + "must stay inside the modal content width instead of extending beyond its right edge." + ); Assert.True(NativeImGui.GetItemRectSize().Y > lineHeight); - Inno.Native.ImGui.ImDrawList* windowDrawList = NativeImGui.Raw.GetWindowDrawList(); - Inno.Native.ImGui.ImDrawList* foregroundDrawList = NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()); + ImDrawList* windowDrawList = NativeImGui.Raw.GetWindowDrawList(); + ImDrawList* foregroundDrawList = NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()); int windowVertexCount = windowDrawList->VtxBuffer.Size; int foregroundVertexCount = foregroundDrawList->VtxBuffer.Size; EditorUI.current.widgets.DropTargetHighlight(new Vector2(20f, 20f), new Vector2(120f, 80f)); @@ -114,11 +120,11 @@ public void WrappedTextRendersThroughTheSafeLiteralTextPath() [Fact] public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -126,7 +132,7 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(420f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(420f, 260f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Centered Wrapped Text Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); Vector2 origin = NativeImGui.GetCursorScreenPos(); @@ -134,20 +140,22 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() var padding = new Vector2(36f, 24f); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); int vertexStart = drawList->VtxBuffer.Size; - uint textColor = NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + uint textColor = NativeImGui.GetColorU32((int)(GuiCol.Text)); EditorUI.current.widgets.CenteredWrappedText( "A deliberately long viewport diagnostic wraps into several centered lines " + "without touching either horizontal edge of the presentation area.", area, padding ); Assert.Equal(area, NativeImGui.GetItemRectSize()); - Vector2 minimum = new(float.MaxValue); - Vector2 maximum = new(float.MinValue); + var minimum = new Vector2(float.MaxValue); + var maximum = new Vector2(float.MinValue); for (int i = vertexStart; i < drawList->VtxBuffer.Size; i++) { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != textColor) + { continue; + } minimum = Vector2.Min(minimum, Unsafe.BitCast(vertex.Pos)); maximum = Vector2.Max(maximum, Unsafe.BitCast(vertex.Pos)); } @@ -170,13 +178,13 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() [Fact] public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -205,14 +213,18 @@ public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() _ = EditorUI.current.widgets.InlineRename("scene", ref value, ref requestFocus, rowHeight, width: 180f); Vector2 focusedFieldMin = NativeImGui.GetItemRectMin(); Vector2 focusedFieldMax = NativeImGui.GetItemRectMax(); - uint inputId = NativeImGui.GetItemID(); - ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputId); + uint inputID = NativeImGui.GetItemID(); + ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputID); Assert.False(requestFocus); - Assert.False((inputState == null)); + Assert.False((inputState is null)); Assert.Equal(0, NativeImGui.Raw.GetSelectionStart(inputState)); Assert.Equal(value.Length, NativeImGui.Raw.GetSelectionEnd(inputState)); - uint navCursorColor = NativeImGui.GetColorU32((int)(ImGuiCol.NavCursor)); - AssertDrawListDoesNotContainColor(NativeImGui.Raw.GetWindowDrawList(), navCursorColor, "The inline rename focus outline was submitted to the window draw list."); + uint navCursorColor = NativeImGui.GetColorU32((int)(GuiCol.NavCursor)); + AssertDrawListDoesNotContainColor( + NativeImGui.Raw.GetWindowDrawList(), + navCursorColor, + "The inline rename focus outline was submitted to the window draw list." + ); AssertColorBoundsStayCloseToItem( NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()), navCursorColor, @@ -232,11 +244,11 @@ public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() [Fact] public void InlineRenameReleasesFocusBeforeAContextMenuCanOpen() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -245,16 +257,22 @@ public void InlineRenameReleasesFocusBeforeAContextMenuCanOpen() io->Fonts->RendererHasTextures = 1; string value = "Untitled Scene"; bool requestFocus = true; - InlineRenameResult result = InlineRenameResult.None; + GuiInlineRenameResult result = GuiInlineRenameResult.None; Vector2 center = default; void Frame() { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(30f, 30f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(320f, 180f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(30f, 30f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(320f, 180f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText4 = Utf8Codec.EncodeNullTerminated("Inline Rename Context Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, 0); - result = EditorUI.current.widgets.InlineRename("created_asset", ref value, ref requestFocus, NativeImGui.GetFrameHeight(), width: 220f); + result = EditorUI.current.widgets.InlineRename( + "created_asset", + ref value, + ref requestFocus, + NativeImGui.GetFrameHeight(), + width: 220f + ); center = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; NativeImGui.End(); NativeImGui.Render(); @@ -265,11 +283,11 @@ void Frame() Assert.False(requestFocus); Assert.NotEqual(0u, NativeImGui.Raw.GetActiveID()); NativeImGui.Raw.AddMousePosEvent(io, center.X, center.Y); - NativeImGui.Raw.AddMouseButtonEvent(io, (int)ImGuiMouseButton.Right, (true ? (byte)1 : (byte)0)); + NativeImGui.Raw.AddMouseButtonEvent(io, (int)GuiMouseButton.Right, (true ? (byte)1 : (byte)0)); Frame(); - NativeImGui.Raw.AddMouseButtonEvent(io, (int)ImGuiMouseButton.Right, (false ? (byte)1 : (byte)0)); + NativeImGui.Raw.AddMouseButtonEvent(io, (int)GuiMouseButton.Right, (false ? (byte)1 : (byte)0)); Frame(); - Assert.Equal(InlineRenameResult.FocusLost, result); + Assert.Equal(GuiInlineRenameResult.FocusLost, result); Assert.Equal(0u, NativeImGui.Raw.GetActiveID()); } finally @@ -281,11 +299,11 @@ void Frame() [Fact] public void InlineRenameCentersWithinTheNativeTableRowBounds() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -297,15 +315,21 @@ public void InlineRenameCentersWithinTheNativeTableRowBounds() NativeImGui.NewFrame(); using NativeStringLease nativeTestText5 = Utf8Codec.EncodeNullTerminated("Inline Rename Table Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText5.pointer, null, 0); - NativeImGui.PushStyleVar((int)(ImGuiStyleVar.CellPadding), new Vector2(6f, 3f)); - Assert.True(NativeImGui.BeginTable("##rename_table", 1, 0, default(Vector2), 0f)); + NativeImGui.PushStyleVar((int)(GuiStyleVar.CellPadding), new Vector2(6f, 3f)); + Assert.True(NativeImGui.BeginTable("##rename_table", 1, 0, default, 0f)); float rowHeight = NativeImGui.GetTextLineHeight() + NativeImGui.Raw.GetStyle()->CellPadding.Y * 2f; - NativeImGui.TableNextRow((int)(ImGuiTableRowFlags.None), rowHeight); + NativeImGui.TableNextRow((int)(GuiTableRowFlags.None), rowHeight); _ = NativeImGui.TableSetColumnIndex(0); ImGuiTable* table = NativeImGui.Raw.GetCurrentTable(); Vector2 cursor = NativeImGui.GetCursorScreenPos(); NativeImGui.SetCursorScreenPos(new Vector2(cursor.X, table->RowPosY1)); - _ = EditorUI.current.widgets.InlineRename("table_scene", ref value, ref requestFocus, table->RowPosY2 - table->RowPosY1, width: 180f); + _ = EditorUI.current.widgets.InlineRename( + "table_scene", + ref value, + ref requestFocus, + table->RowPosY2 - table->RowPosY1, + width: 180f + ); Vector2 fieldMin = NativeImGui.GetItemRectMin(); Vector2 fieldMax = NativeImGui.GetItemRectMax(); Assert.True(fieldMin.Y >= table->RowPosY1); @@ -325,13 +349,13 @@ public void InlineRenameCentersWithinTheNativeTableRowBounds() [Fact] public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -344,8 +368,7 @@ public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() 1.5f } - ) - { + ) { _ = EditorUI.current.widgets.style.SetZoom(zoom); EditorUI.current.widgets.SetupStyle(); DrawTreeFrame(); @@ -360,13 +383,13 @@ public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() [Fact] public void MenuSelectorPopupIsBoundedAndScrollsLongContent() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -374,29 +397,37 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() for (int frame = 0; frame < 2; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText6 = Utf8Codec.EncodeNullTerminated("Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText6.pointer, null, 0); if (frame == 0) + { NativeImGui.OpenPopup("##menu_selector_popup_test"); + } Assert.True(EditorUI.current.widgets.BeginMenuSelector("test", "Untagged", 180f, 240f)); - ImGuiWindowFlags flags = (ImGuiWindowFlags)NativeImGui.Raw.GetCurrentWindow()->Flags; - Assert.True(flags.HasFlag(ImGuiWindowFlags.AlwaysAutoResize)); - Assert.False(flags.HasFlag(ImGuiWindowFlags.NoScrollbar)); - Assert.False(flags.HasFlag(ImGuiWindowFlags.NoScrollWithMouse)); - Assert.True(flags.HasFlag(ImGuiWindowFlags.NoSavedSettings)); + GuiWindowFlags flags = (GuiWindowFlags)NativeImGui.Raw.GetCurrentWindow()->Flags; + Assert.True(flags.HasFlag(GuiWindowFlags.AlwaysAutoResize)); + Assert.False(flags.HasFlag(GuiWindowFlags.NoScrollbar)); + Assert.False(flags.HasFlag(GuiWindowFlags.NoScrollWithMouse)); + Assert.True(flags.HasFlag(GuiWindowFlags.NoSavedSettings)); Assert.True(NativeImGui.GetWindowSize().X >= 240f); string newTag = string.Empty; NativeImGui.SetNextItemWidth(160f); _ = EditorImGui.InputTextWithHint("##new_tag", "Add tag...", ref newTag, 128); float inputCenterY = (NativeImGui.GetItemRectMin().Y + NativeImGui.GetItemRectMax().Y) * 0.5f; NativeImGui.SameLine(0f, -1f); - _ = EditorUI.current.widgets.ClickableText("add_tag", "+", new Vector2(EditorUI.current.widgets.GetCompactIconSize().X, NativeImGui.GetFrameHeight())); + _ = EditorUI.current.widgets.ClickableText( + "add_tag", + "+", + new Vector2(EditorUI.current.widgets.GetCompactIconSize().X, NativeImGui.GetFrameHeight()) + ); float actionCenterY = (NativeImGui.GetItemRectMin().Y + NativeImGui.GetItemRectMax().Y) * 0.5f; Assert.Equal(inputCenterY, actionCenterY, 3); for (int index = 0; index < 64; index++) + { NativeImGui.Selectable($"Entry {index:D2}"); + } if (frame == 1) { Assert.True(NativeImGui.GetWindowSize().Y <= io->DisplaySize.Y + 1f); @@ -417,11 +448,11 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() [Fact] public void SmallMenuSelectorDoesNotReserveAScrollbar() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -431,15 +462,19 @@ public void SmallMenuSelectorDoesNotReserveAScrollbar() for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText7 = Utf8Codec.EncodeNullTerminated("Small Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText7.pointer, null, 0); if (frame == 0) + { NativeImGui.OpenPopup("##menu_selector_popup_small"); + } Assert.True(EditorUI.current.widgets.BeginMenuSelector("small", "Current", 180f, 240f)); for (int index = 0; index < 3; index++) + { NativeImGui.Selectable($"Entry {index}"); + } if (frame == 2) { Assert.False((NativeImGui.Raw.GetCurrentWindow()->ScrollbarY != 0)); @@ -460,11 +495,11 @@ public void SmallMenuSelectorDoesNotReserveAScrollbar() [Fact] public void SmallContextMenuDoesNotReserveScrollbars() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -478,7 +513,9 @@ public void SmallContextMenuDoesNotReserveScrollbars() _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText8.pointer, null, 0); NativeImGui.Selectable("Target"); if (frame == 0) + { NativeImGui.OpenPopup("context"); + } Assert.True(EditorUI.current.widgets.BeginContextMenu("context")); NativeImGui.MenuItem("Rename", string.Empty, false, true); NativeImGui.MenuItem("Delete", string.Empty, false, true); @@ -502,27 +539,27 @@ public void SmallContextMenuDoesNotReserveScrollbars() [Fact] public void BoundedComboPopupUsesTheSharedScrollingContract() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - var popupWidths = new List(); + List popupWidths = []; int openFrames = 0; for (int frame = 0; frame < 5; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(400f, 340f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(220f, 120f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(400f, 340f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(220f, 120f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText9 = Utf8Codec.EncodeNullTerminated("Bounded Combo Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText9.pointer, null, 0); - uint parentViewportId = NativeImGui.Raw.GetWindowViewport()->ID; + uint parentViewportID = NativeImGui.Raw.GetWindowViewport()->ID; if (frame == 0) { NativeImGui.OpenPopup("##menu_selector_popup_##asset"); @@ -533,11 +570,13 @@ public void BoundedComboPopupUsesTheSharedScrollingContract() if (open) { openFrames++; - Assert.Equal(parentViewportId, NativeImGui.Raw.GetWindowViewport()->ID); + Assert.Equal(parentViewportID, NativeImGui.Raw.GetWindowViewport()->ID); string search = string.Empty; _ = EditorUI.current.widgets.SearchInput("assets", "Search assets...", ref search); for (int index = 0; index < 64; index++) + { NativeImGui.Selectable($"project:Material{index:D2}"); + } popupWidths.Add(NativeImGui.GetWindowSize().X); if (openFrames >= 2) { @@ -572,11 +611,11 @@ public void BoundedComboPopupUsesTheSharedScrollingContract() [Fact] public void TreeRegionScrollsHorizontallyOnlyForRealContentOverflow() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -598,11 +637,11 @@ public void TreeRegionScrollsHorizontallyOnlyForRealContentOverflow() [Fact] public void TreeRegionReleasesViewportWidthAfterItShrinks() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -622,11 +661,11 @@ public void TreeRegionReleasesViewportWidthAfterItShrinks() [Fact] public void TreeGuideSegmentsRemainVisibleAcrossCompactRows() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -646,11 +685,11 @@ public void TreeGuideSegmentsRemainVisibleAcrossCompactRows() [Fact] public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHeight() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -659,14 +698,22 @@ public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHe io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText10 = Utf8Codec.EncodeNullTerminated("Gapped Parent Guide Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText10.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult parent = EditorUI.current.widgets.TreeNode("connected_parent", static _ => NativeImGui.TextUnformatted("Parent"), new TreeNodeOptions()); + GuiTreeNodeResult parent = EditorUI.current.widgets.TreeNode( + "connected_parent", + static _ => NativeImGui.TextUnformatted("Parent"), + new GuiTreeNodeOptions() + ); Assert.True(parent.isOpen); - TreeNodeResult child = EditorUI.current.widgets.TreeNode("connected_child", static _ => NativeImGui.TextUnformatted("Child"), new TreeNodeOptions { isLeaf = true }); + GuiTreeNodeResult child = EditorUI.current.widgets.TreeNode( + "connected_child", + static _ => NativeImGui.TextUnformatted("Child"), + new GuiTreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); Assert.Equal(expectedHeight, parent.max.Y - parent.min.Y, 3); Assert.Equal(expectedHeight, child.max.Y - child.min.Y, 3); @@ -683,11 +730,11 @@ public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHe [Fact] public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -696,16 +743,24 @@ public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText11 = Utf8Codec.EncodeNullTerminated("Dragging Tree Guide Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText11.pointer, null, 0); ImGuiNativeContext* currentContext = NativeImGui.Raw.GetCurrentContext(); currentContext->DragDropActive = 1; EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode("drag_root", static _ => NativeImGui.TextUnformatted("Assets"), new TreeNodeOptions()); + GuiTreeNodeResult root = EditorUI.current.widgets.TreeNode( + "drag_root", + static _ => NativeImGui.TextUnformatted("Assets"), + new GuiTreeNodeOptions() + ); if (root.isOpen) { - _ = EditorUI.current.widgets.TreeNode("drag_child", static _ => NativeImGui.TextUnformatted("Scene"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "drag_child", + static _ => NativeImGui.TextUnformatted("Scene"), + new GuiTreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } @@ -723,11 +778,11 @@ public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() [Fact] public void TreeRowBackgroundsUseCurrentGeometryWhileTheWindowChanges() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -747,11 +802,11 @@ public void TreeRowBackgroundsUseCurrentGeometryWhileTheWindowChanges() [Fact] public void TreeRowsRetainTheirCompactContentHeight() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -760,11 +815,15 @@ public void TreeRowsRetainTheirCompactContentHeight() io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText12 = Utf8Codec.EncodeNullTerminated("Compact Tree Row Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText12.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); - TreeNodeResult row = EditorUI.current.widgets.TreeNode("compact_row", static _ => NativeImGui.TextUnformatted("GameObject"), new TreeNodeOptions { isLeaf = true }); + GuiTreeNodeResult row = EditorUI.current.widgets.TreeNode( + "compact_row", + static _ => NativeImGui.TextUnformatted("GameObject"), + new GuiTreeNodeOptions { isLeaf = true } + ); Assert.Equal(expectedHeight, row.max.Y - row.min.Y, 3); NativeImGui.End(); NativeImGui.Render(); @@ -778,11 +837,11 @@ public void TreeRowsRetainTheirCompactContentHeight() [Fact] public void DoubleClickingTreeContentTogglesNonLeafExpansion() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -790,17 +849,17 @@ public void DoubleClickingTreeContentTogglesNonLeafExpansion() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); - TreeNodeResult initial = DrawDoubleClickTreeFrame(); - Vector2 contentCenter = new(initial.contentMin.X + 20f, (initial.min.Y + initial.max.Y) * 0.5f); + GuiTreeNodeResult initial = DrawDoubleClickTreeFrame(); + var contentCenter = new Vector2(initial.contentMin.X + 20f, (initial.min.Y + initial.max.Y) * 0.5f); NativeImGui.Raw.AddMousePosEvent(io, contentCenter.X, contentCenter.Y); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (true ? (byte)1 : (byte)0)); _ = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (false ? (byte)1 : (byte)0)); _ = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (true ? (byte)1 : (byte)0)); - TreeNodeResult doubleClicked = DrawDoubleClickTreeFrame(); + GuiTreeNodeResult doubleClicked = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (false ? (byte)1 : (byte)0)); - TreeNodeResult expanded = DrawDoubleClickTreeFrame(); + GuiTreeNodeResult expanded = DrawDoubleClickTreeFrame(); Assert.True(doubleClicked.isDoubleClicked); Assert.True(expanded.isOpen); } @@ -813,11 +872,11 @@ public void DoubleClickingTreeContentTogglesNonLeafExpansion() [Fact] public void InspectorContentPreservesStandardPaddingWithoutArtificialHorizontalOverflow() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -837,42 +896,68 @@ public void InspectorContentPreservesStandardPaddingWithoutArtificialHorizontalO private static void DrawTreeFrame(bool assertContinuousGuides = false) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(Inno.Native.ImGui.ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(NativeCond.Always)); using NativeStringLease nativeTestText13 = Utf8Codec.EncodeNullTerminated("Tree Zoom Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText13.pointer, null, 0); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode("root", static _ => NativeImGui.TextUnformatted("Assets"), new TreeNodeOptions()); + GuiTreeNodeResult root = EditorUI.current.widgets.TreeNode( + "root", + static _ => NativeImGui.TextUnformatted("Assets"), + new GuiTreeNodeOptions() + ); if (root.isOpen) { EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult folder = EditorUI.current.widgets.TreeNode("folder", static _ => NativeImGui.TextUnformatted("Scene"), new TreeNodeOptions()); + GuiTreeNodeResult folder = EditorUI.current.widgets.TreeNode( + "folder", + static _ => NativeImGui.TextUnformatted("Scene"), + new GuiTreeNodeOptions() + ); if (folder.isOpen) { - _ = EditorUI.current.widgets.TreeNode("nested-file", static _ => NativeImGui.TextUnformatted("TestScene1.iscene"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "nested-file", + static _ => NativeImGui.TextUnformatted("TestScene1.iscene"), + new GuiTreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } - _ = EditorUI.current.widgets.TreeNode("sibling-folder", static _ => NativeImGui.TextUnformatted("Settings"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "sibling-folder", + static _ => NativeImGui.TextUnformatted("Settings"), + new GuiTreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } if (assertContinuousGuides) + { AssertCurrentDrawListContainsTreeGuideColor(); + } NativeImGui.End(); NativeImGui.Render(); } - private static TreeNodeResult DrawDoubleClickTreeFrame() + private static GuiTreeNodeResult DrawDoubleClickTreeFrame() { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText14 = Utf8Codec.EncodeNullTerminated("Double Click Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText14.pointer, null, 0); - TreeNodeResult result = EditorUI.current.widgets.TreeNode("double_click_parent", static _ => NativeImGui.TextUnformatted("Parent"), new TreeNodeOptions()); + GuiTreeNodeResult result = EditorUI.current.widgets.TreeNode( + "double_click_parent", + static _ => NativeImGui.TextUnformatted("Parent"), + new GuiTreeNodeOptions() + ); if (result.isOpen) { - _ = EditorUI.current.widgets.TreeNode("double_click_child", static _ => NativeImGui.TextUnformatted("Child"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "double_click_child", + static _ => NativeImGui.TextUnformatted("Child"), + new GuiTreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } @@ -884,33 +969,45 @@ private static TreeNodeResult DrawDoubleClickTreeFrame() private static void DrawTreeOverflowFrame(bool assertRanges) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(560f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(560f, 320f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText15 = Utf8Codec.EncodeNullTerminated("Tree Overflow Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText15.pointer, null, 0); - if (NativeImGui.BeginChild("##short_tree", new Vector2(220f, 100f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { - _ = EditorUI.current.widgets.TreeNode("short", static _ => NativeImGui.TextUnformatted("Object"), new TreeNodeOptions { isLeaf = true }); + if (NativeImGui.BeginChild( + "##short_tree", + new Vector2(220f, 100f), + (int)(GuiChildFlags.None), + (int)(GuiWindowFlags.HorizontalScrollbar) + )) { + _ = EditorUI.current.widgets.TreeNode( + "short", + static _ => NativeImGui.TextUnformatted("Object"), + new GuiTreeNodeOptions { isLeaf = true } + ); if (assertRanges) { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); Assert.False((NativeImGui.Raw.GetCurrentWindow()->ScrollbarX != 0)); - Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)ImGuiWindowFlags.HorizontalScrollbar) != 0); + Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)GuiWindowFlags.HorizontalScrollbar) != 0); } } NativeImGui.EndChild(); - if (NativeImGui.BeginChild("##long_tree", new Vector2(220f, 100f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { + if (NativeImGui.BeginChild( + "##long_tree", + new Vector2(220f, 100f), + (int)(GuiChildFlags.None), + (int)(GuiWindowFlags.HorizontalScrollbar) + )) { _ = EditorUI.current.widgets.TreeNode( "long", static _ => NativeImGui.TextUnformatted("Object_With_A_Name_That_Is_Intentionally_Wider_Than_The_Tree_Viewport"), - new TreeNodeOptions { isLeaf = true } + new GuiTreeNodeOptions { isLeaf = true } ); if (assertRanges) { Assert.True(NativeImGui.GetScrollMaxX() > 0f); Assert.True((NativeImGui.Raw.GetCurrentWindow()->ScrollbarX != 0)); - Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)ImGuiWindowFlags.HorizontalScrollbar) != 0); + Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)GuiWindowFlags.HorizontalScrollbar) != 0); } } @@ -924,18 +1021,22 @@ private static void DrawHorizontallyScrolledTreeFrame( bool assertGeometry ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(360f, 220f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(360f, 220f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText16 = Utf8Codec.EncodeNullTerminated("Scrolled Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText16.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); - if (NativeImGui.BeginChild("##scrolled_tree", new Vector2(220f, 120f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { + if (NativeImGui.BeginChild( + "##scrolled_tree", + new Vector2(220f, 120f), + (int)(GuiChildFlags.None), + (int)(GuiWindowFlags.HorizontalScrollbar) + )) { Vector2 contentCursor = default; - TreeNodeResult row = EditorUI.current.widgets.TreeNode("scrolled", _ => + GuiTreeNodeResult row = EditorUI.current.widgets.TreeNode("scrolled", _ => { contentCursor = NativeImGui.GetCursorScreenPos(); NativeImGui.TextUnformatted("Scene_With_A_Name_That_Is_Intentionally_Wider_Than_The_Tree_Viewport"); - }, new TreeNodeOptions { isLeaf = true, showBackground = true, backgroundColor = EditorPalette.title }); + }, new GuiTreeNodeOptions { isLeaf = true, showBackground = true, backgroundColor = EditorPalette.title }); if (assertGeometry) { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); @@ -957,21 +1058,33 @@ private static void DrawResizableTreeFrame( bool assertNoOverflow ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(560f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(560f, 260f), (int)(GuiCond.Always)); using NativeStringLease nativeTestText17 = Utf8Codec.EncodeNullTerminated("Resizable Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText17.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); - if (NativeImGui.BeginChild("##resizable_tree", new Vector2(width, 120f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { - _ = EditorUI.current.widgets.TreeNode("resizable_row", static _ => NativeImGui.TextUnformatted("GameObject"), new TreeNodeOptions { isLeaf = true, drawViewportOverlay = static () => - { - ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); - Vector2 overlaySize = new(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); - NativeImGui.SameLine(0f, -1f); - Vector2 cursor = NativeImGui.GetCursorScreenPos(); - NativeImGui.SetCursorScreenPos(new Vector2(MathF.Max(cursor.X, window->WorkRect.Max.X - overlaySize.X), cursor.Y)); - NativeImGui.Dummy(overlaySize); - } }); + if (NativeImGui.BeginChild( + "##resizable_tree", + new Vector2(width, 120f), + (int)(GuiChildFlags.None), + (int)(GuiWindowFlags.HorizontalScrollbar) + )) { + _ = EditorUI.current.widgets.TreeNode( + "resizable_row", + static _ => NativeImGui.TextUnformatted("GameObject"), + new GuiTreeNodeOptions + { + isLeaf = true, + drawViewportOverlay = static () => + { + ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); + var overlaySize = new Vector2(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); + NativeImGui.SameLine(0f, -1f); + Vector2 cursor = NativeImGui.GetCursorScreenPos(); + NativeImGui.SetCursorScreenPos(new Vector2(MathF.Max(cursor.X, window->WorkRect.Max.X - overlaySize.X), cursor.Y)); + NativeImGui.Dummy(overlaySize); + } + } + ); if (assertNoOverflow) { Assert.Equal(0f, NativeImGui.GetScrollX(), 3); @@ -1010,28 +1123,34 @@ private static void DrawCurrentTreeBackgroundFrame( Vector2 size ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(position, (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(size, (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(position, (int)(GuiCond.Always), default); + NativeImGui.SetNextWindowSize(size, (int)(GuiCond.Always)); using NativeStringLease nativeTestText18 = Utf8Codec.EncodeNullTerminated("Current Tree Background Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText18.pointer, null, 0); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode( + GuiTreeNodeResult root = EditorUI.current.widgets.TreeNode( "current_background_root", static _ => NativeImGui.TextUnformatted("TestScene"), - new TreeNodeOptions { showBackground = true, backgroundColor = EditorPalette.title, suppressHoverHighlight = true } + new GuiTreeNodeOptions { showBackground = true, backgroundColor = EditorPalette.title, suppressHoverHighlight = true } ); if (root.isOpen) { _ = EditorUI.current.widgets.TreeNode( "current_background_child", static _ => NativeImGui.TextUnformatted("GameObject"), - new TreeNodeOptions { isLeaf = true, selected = true } + new GuiTreeNodeOptions { isLeaf = true, selected = true } ); NativeImGui.TreePop(); } - AssertCurrentDrawListContainsColor(NativeImGui.ColorConvertFloat4ToU32(EditorPalette.title), "The current frame did not submit the Scene row background."); - AssertCurrentDrawListContainsColor(NativeImGui.GetColorU32((int)(ImGuiCol.Header)), "The current frame did not submit the selected row highlight."); + AssertCurrentDrawListContainsColor( + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.title), + "The current frame did not submit the Scene row background." + ); + AssertCurrentDrawListContainsColor( + NativeImGui.GetColorU32((int)(GuiCol.Header)), + "The current frame did not submit the selected row highlight." + ); NativeImGui.End(); NativeImGui.Render(); } @@ -1044,7 +1163,9 @@ string failureMessage for (int i = 0; i < drawList->VtxBuffer.Size; i++) { if (drawList->VtxBuffer.Data[i].Col == color) + { return; + } } Assert.Fail(failureMessage); @@ -1058,7 +1179,9 @@ string failureMessage for (int i = 0; i < drawList->VtxBuffer.Size; i++) { if (drawList->VtxBuffer.Data[i].Col == color) + { Assert.Fail(failureMessage); + } } } @@ -1069,13 +1192,15 @@ private static void AssertColorBoundsStayCloseToItem( Vector2 itemMax, float maximumExpansion ) { - Vector2 colorMin = new(float.MaxValue); - Vector2 colorMax = new(float.MinValue); + var colorMin = new Vector2(float.MaxValue); + var colorMax = new Vector2(float.MinValue); for (int i = 0; i < drawList->VtxBuffer.Size; i++) { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != color) + { continue; + } colorMin = Vector2.Min(colorMin, Unsafe.BitCast(vertex.Pos)); colorMax = Vector2.Max(colorMax, Unsafe.BitCast(vertex.Pos)); } @@ -1102,7 +1227,9 @@ uint color { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != color) + { continue; + } minimumX = MathF.Min(minimumX, vertex.Pos.X); maximumX = MathF.Max(maximumX, vertex.Pos.X); } @@ -1115,13 +1242,13 @@ uint color private static void DrawInspectorCardFrame(bool assertHorizontalRange) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(320f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(320f, 260f), (int)(GuiCond.Always)); bool isOpen = true; EditorUI.current.widgets.PanelWindow( "Inspector Width Test", ref isOpen, () => DrawInspectorCardBody(assertHorizontalRange), - ImGuiWindowFlags.NoSavedSettings, + GuiWindowFlags.NoSavedSettings, useWindowPadding: false ); NativeImGui.Render(); @@ -1150,8 +1277,14 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) { if (assertHorizontalRange) { - Assert.Equal(EditorUI.current.widgets.style.windowPadding, Unsafe.BitCast(NativeImGui.Raw.GetCurrentWindow()->WindowPadding)); - Assert.Equal(NativeImGui.GetWindowPos() + EditorUI.current.widgets.style.windowPadding, NativeImGui.GetCursorScreenPos()); + Assert.Equal( + EditorUI.current.widgets.style.windowPadding, + Unsafe.BitCast(NativeImGui.Raw.GetCurrentWindow()->WindowPadding) + ); + Assert.Equal( + NativeImGui.GetWindowPos() + EditorUI.current.widgets.style.windowPadding, + NativeImGui.GetCursorScreenPos() + ); } EditorUI.current.widgets.LabelChip("Tag", new Vector4(0.34f, 0.29f, 0.44f, 1f)); @@ -1159,14 +1292,18 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) NativeImGui.SameLine(0f, 0f); NativeImGui.Dummy(new Vector2(80f, NativeImGui.GetFrameHeight())); if (assertHorizontalRange) + { Assert.Equal(tagMaximumX, NativeImGui.GetItemRectMin().X, 3); + } NativeImGui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); - EditorUI.current.widgets.LabelChip("Layer", new Vector4(0.24f, 0.34f, 0.40f, 1f)); + EditorUI.current.widgets.LabelChip("Layer", new Vector4(0.24f, 0.34f, 0.4f, 1f)); float layerMaximumX = NativeImGui.GetItemRectMax().X; NativeImGui.SameLine(0f, 0f); NativeImGui.Dummy(new Vector2(80f, NativeImGui.GetFrameHeight())); if (assertHorizontalRange) + { Assert.Equal(layerMaximumX, NativeImGui.GetItemRectMin().X, 3); + } bool open = EditorUI.current.widgets.CollapsingCard( "long_behavior", "BehaviorWithAnIntentionallyLongTypeNameThatMustBeClipped", @@ -1182,7 +1319,9 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) static () => EditorUI.current.widgets.PropertyRow( "long_property", "Property With A Very Long Display Name", - static () => NativeImGui.Dummy(new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), NativeImGui.GetFrameHeight())) + static () => NativeImGui.Dummy( + new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), NativeImGui.GetFrameHeight()) + ) ) ); NativeImGui.Indent(); @@ -1191,10 +1330,14 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) } if (assertHorizontalRange) + { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); + } }); if (assertHorizontalRange) + { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); + } } NativeImGui.EndChild(); diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs index d14cf281a..34e8f892b 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; - +using Xunit; using Inno.Editor.Rendering; using Inno.Rendering; - -using Xunit; using Inno.Rendering.Runtime; namespace Inno.Editor.Scripting.Tests; @@ -23,26 +21,29 @@ public void CompositionCanonicalizesModelLayersByOrderAndStableIdentity() 1280, 720, RenderTextureFormat.RGBA8Srgb, - new[] { overlay, baseB, baseA }); + new[] { overlay, baseB, baseA } + ); Assert.Collection( composition.layers, layer => Assert.Same(baseA, layer), layer => Assert.Same(baseB, layer), - layer => Assert.Same(overlay, layer)); + layer => Assert.Same(overlay, layer) + ); } [Fact] public void CompositionSnapshotsTheCallerCollection() { var retained = new EditorViewportLayer("tests.retained", null, new RenderFrameData(), 0); - var source = new List { retained }; + List source = [retained]; var composition = new EditorViewportComposition( "tests.game-view", 640, 360, RenderTextureFormat.RGBA8Srgb, - source); + source + ); source.Clear(); @@ -59,13 +60,15 @@ public void CompositionRejectsEmptyNullAndDuplicateModelLayers() 64, 64, RenderTextureFormat.RGBA8Srgb, - Array.Empty())); + [] + )); Assert.Throws(() => new EditorViewportComposition( "tests.null", 64, 64, RenderTextureFormat.RGBA8Srgb, - new EditorViewportLayer[] { null! })); + new EditorViewportLayer[] { null! } + )); var first = new EditorViewportLayer("tests.duplicate", null, new RenderFrameData(), 0); var second = new EditorViewportLayer("tests.duplicate", null, new RenderFrameData(), 1000); @@ -74,6 +77,7 @@ public void CompositionRejectsEmptyNullAndDuplicateModelLayers() 64, 64, RenderTextureFormat.RGBA8Srgb, - new[] { first, second })); + new[] { first, second } + )); } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs index af3b1c2a4..2b354a929 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs @@ -1,30 +1,30 @@ using System; - +using Xunit; using Inno.Core.Mathematics; using Inno.Editor.Rendering; -using Xunit; - namespace Inno.Editor.Scripting.Tests; public sealed class EditorViewportNavigationTests { [Fact] - public void Profile_RejectsDefaultModeMissingFromCapabilities() + public void ProfileRejectsDefaultModeMissingFromCapabilities() { Assert.Throws(() => new EditorViewportNavigationProfile( - new EditorViewportNavigationProfileId("tests.navigation.invalid-default"), + new EditorViewportNavigationProfileID("tests.navigation.invalid-default"), EditorViewportNavigationCapabilities.Pan, - EditorViewportNavigationMode.Fly)); + EditorViewportNavigationMode.Fly + )); _ = new EditorViewportNavigationProfile( - new EditorViewportNavigationProfileId("tests.navigation.pan-only"), + new EditorViewportNavigationProfileID("tests.navigation.pan-only"), EditorViewportNavigationCapabilities.Pan, - EditorViewportNavigationMode.Planar); + EditorViewportNavigationMode.Planar + ); } [Fact] - public void ConfigurePerspective_IsAtomicWhenValidationFails() + public void ConfigurePerspectiveIsAtomicWhenValidationFails() { var state = new EditorViewportNavigationState(); state.ConfigureOrthographic(new Vector3(2f, 3f, 4f), Quaternion.identity, 8f); @@ -34,7 +34,8 @@ public void ConfigurePerspective_IsAtomicWhenValidationFails() Quaternion.FromEulerAnglesXYZDegrees(new Vector3(10f, 20f, 30f)), 200f, 0.1f, - 1000f)); + 1000f + )); Assert.Equal(EditorViewportProjection.Orthographic, state.projection); Assert.Equal(new Vector3(2f, 3f, 4f), state.position); @@ -43,13 +44,11 @@ public void ConfigurePerspective_IsAtomicWhenValidationFails() } [Fact] - public void State_RejectsUndefinedProjectionAndMode() + public void StateRejectsUndefinedProjectionAndMode() { var state = new EditorViewportNavigationState(); - Assert.Throws(() => - state.projection = (EditorViewportProjection)100); - Assert.Throws(() => - state.mode = (EditorViewportNavigationMode)100); + Assert.Throws(() => state.projection = (EditorViewportProjection)100); + Assert.Throws(() => state.mode = (EditorViewportNavigationMode)100); } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs new file mode 100644 index 000000000..649b208fe --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineFailure; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs new file mode 100644 index 000000000..6365f97d9 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs @@ -0,0 +1,10 @@ +using System; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(InlineFailure), priority: 10_000)] +internal sealed class InlineFailureDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) => throw new InvalidOperationException("Inline drawer failure."); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs new file mode 100644 index 000000000..e270b5aba --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineOwner : ISerializable +{ + [SerializableProperty] + public InlineParent value { get; set; } = new(); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs new file mode 100644 index 000000000..f5891cd60 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs @@ -0,0 +1,6 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineParent +{ + internal InlineFailure child { get; } = new(); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs new file mode 100644 index 000000000..23a29fa7a --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(InlineParent), priority: 10_000)] +internal sealed class InlineParentDrawer : IPropertyDrawer +{ + internal static bool drewAfterFailure; + + public void Draw(PropertyDrawContext context) + { + InlineParent parent = (InlineParent)context.GetValue()!; + context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => {}, readOnly: true); + drewAfterFailure = true; + } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs index 4d75bece3..7a0d2a30a 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs @@ -1,29 +1,27 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using Inno.Native.ImGui; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Numerics; -using Inno.Extensibility.Modules; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Editor.Annotations; using Inno.Editor.Core; -using Inno.Editor.ImGui; -using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using Inno.Editor.Inspection; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.Scripting.Tests; + public sealed class InspectionPipelineTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoInspectionPipelineTests", Guid.NewGuid().ToString("N")); @@ -32,14 +30,17 @@ public sealed class InspectionPipelineTests : IDisposable private readonly SerializationRegistry m_serialization; private readonly LogRouter m_logs = new(); private readonly EditorInteractionRuntime m_runtime; + public InspectionPipelineTests() { Directory.CreateDirectory(m_projectRoot); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(InspectionPipelineTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(InspectionPipelineTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization] @@ -55,7 +56,9 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -63,19 +66,30 @@ public unsafe void InlineChildFailureIsConsumedAndReadonlyDisabledScopeRemainsBa { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); Assert.IsType(drawers.Resolve(typeof(InlineParent))); var owner = new InlineOwner(); SerializedProperty property = Assert.Single(m_serialization.GetProperties(owner)); InlineParentDrawer.drewAfterFailure = false; - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -107,15 +121,21 @@ public unsafe void InlineChildFailureIsConsumedAndReadonlyDisabledScopeRemainsBa [Fact] public unsafe void PanelWindowFailureStillEndsTheWindowAndAllowsLaterContent() { - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); PrepareNativeFrame(); bool isOpen = true; - Assert.Throws(() => EditorUI.current.widgets.PanelWindow("Throwing Panel", ref isOpen, static () => throw new InvalidOperationException("panel"))); + Assert.Throws( + () => EditorUI.current.widgets.PanelWindow( + "Throwing Panel", + ref isOpen, + static () => throw new InvalidOperationException("panel") + ) + ); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Content After Panel Failure", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); NativeImGui.TextUnformatted("Still drawing."); @@ -133,9 +153,26 @@ public unsafe void TextEditStateIsScopedByRendererOwnerAndPropertyPath() { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var firstRenderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); - var secondRenderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var firstRenderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); + var secondRenderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); var firstOwner = new TextStateOwner { value = new TextStateValue("First") @@ -147,11 +184,11 @@ public unsafe void TextEditStateIsScopedByRendererOwnerAndPropertyPath() SerializedProperty firstProperty = Assert.Single(m_serialization.GetProperties(firstOwner)); SerializedProperty secondProperty = Assert.Single(m_serialization.GetProperties(secondOwner)); TextStateDrawer.observations.Clear(); - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); DrawPropertyFrame(firstRenderer, editor, firstOwner, firstProperty); DrawPropertyFrame(firstRenderer, editor, firstOwner, firstProperty); @@ -171,17 +208,31 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); var owner = new AttributeOwner(); - SerializedProperty property = Assert.Single(m_serialization.GetProperties(owner), static candidate => candidate.name == nameof(AttributeOwner.value)); + SerializedProperty property = Assert.Single( + m_serialization.GetProperties(owner), + static candidate => candidate.name == nameof(AttributeOwner.value) + ); AttributeValueDrawer.observations.Clear(); ProbeInspectorAttributeDrawer.observations.Clear(); - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); DrawPropertyFrame(renderer, editor, owner, property); Assert.Empty(AttributeValueDrawer.observations); @@ -194,13 +245,16 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible NativeImGui.Raw.DestroyContext(nativeContext); } - Assert.Equal(["update:Friendly Value:False:2:8", "update:Friendly Value:False:2:8", "before", "after"], ProbeInspectorAttributeDrawer.observations); + Assert.Equal( + ["update:Friendly Value:False:2:8", "update:Friendly Value:False:2:8", "before", "after"], + ProbeInspectorAttributeDrawer.observations + ); Assert.Equal(["Friendly Value:False:2:8"], AttributeValueDrawer.observations); } private static unsafe void PrepareNativeFrame() { - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -245,100 +299,4 @@ public bool ChangeProperty( } } -internal sealed class InlineOwner : ISerializable -{ - [SerializableProperty] - public InlineParent value { get; set; } = new(); -} - -internal sealed class InlineParent -{ - internal InlineFailure child { get; } = new(); -} - -internal sealed class InlineFailure; -internal sealed class TextStateOwner : ISerializable -{ - [SerializableProperty] - public TextStateValue value { get; set; } = new("Unset"); -} - internal sealed record TextStateValue(string id); -internal sealed class AttributeOwner : ISerializable -{ - internal bool showValue { get; set; } - - [SerializableProperty] - [Header("Presentation", "Decorators are composed before the property row.")] - [Text("Persistent decorator text remains visible.")] - [Tooltip("Reusable hover guidance.")] - [InspectorName("Friendly Value")] - [Range(2, 8)] - [ShowIf(nameof(showValue))] - [ProbeInspector] - public AttributeValue value { get; set; } = new(); -} - -internal sealed class AttributeValue; -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] -internal sealed class ProbeInspectorAttribute : InspectorPresentationAttribute; -[InspectorAttributeDrawer(typeof(ProbeInspectorAttribute), priority: 10_000)] -internal sealed class ProbeInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - internal static List observations { get; } = []; - - public void Update(InspectorAttributeDrawContext context) => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); - public void DrawBefore(InspectorAttributeDrawContext context) - { - _ = context; - observations.Add("before"); - } - - public void DrawAfter(InspectorAttributeDrawContext context) - { - _ = context; - observations.Add("after"); - } -} - -[PropertyDrawer(typeof(AttributeValue), priority: 10_000)] -internal sealed class AttributeValueDrawer : IPropertyDrawer -{ - internal static List observations { get; } = []; - - public void Draw(PropertyDrawContext context) => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); -} - -[PropertyDrawer(typeof(TextStateValue), priority: 10_000)] -internal sealed class TextStateDrawer : IPropertyDrawer -{ - internal static List observations { get; } = []; - - public void Draw(PropertyDrawContext context) - { - var value = (TextStateValue)context.GetValue()!; - bool hasState = context.TryGetTextState("editing", out string? state); - observations.Add($"{value.id}:{(hasState ? state : "")}"); - context.SetTextState("editing", value.id); - } -} - -[PropertyDrawer(typeof(InlineParent), priority: 10_000)] -internal sealed class InlineParentDrawer : IPropertyDrawer -{ - internal static bool drewAfterFailure; - public void Draw(PropertyDrawContext context) - { - var parent = (InlineParent)context.GetValue()!; - context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => - { - }, readOnly: true); - drewAfterFailure = true; - } -} - -[PropertyDrawer(typeof(InlineFailure), priority: 10_000)] -internal sealed class InlineFailureDrawer : IPropertyDrawer -{ - public void Draw(PropertyDrawContext context) => throw new InvalidOperationException("Inline drawer failure."); -} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs index e65425f99..da4568534 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs @@ -1,24 +1,27 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using NativeVector4 = Inno.Native.ImGui.ImVec4C; -using BGCS.Runtime; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Editor.ImGui; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; +using GuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using NativeVector4 = Inno.Native.ImGui.ImVec4C; namespace Inno.Editor.Scripting.Tests; + [Trait("Acceptance", "Visual")] public sealed unsafe class InspectorPresentationLayoutTests : IDisposable { private readonly ImGuiNativeContext* m_context = NativeImGui.Raw.CreateContext(null); - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUI m_ui = new(); private readonly IDisposable m_uiScope; + public InspectorPresentationLayoutTests() { m_uiScope = m_ui.Enter(); @@ -80,7 +83,7 @@ float zoom EditorUI.current.widgets.style.SetZoom(zoom); EditorUI.current.widgets.SetupStyle(); Vector2 hover = default; - const string text = "The profile is evaluated after this camera stack is composed. The final words must remain readable."; + const string C_TEXT = "The profile is evaluated after this camera stack is composed. The final words must remain readable."; void Frame() { NativeImGui.NewFrame(); @@ -90,7 +93,7 @@ void Frame() NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); NativeImGui.Button("Hover near edge"); hover = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; - EditorUI.current.widgets.DrawItemTooltip(text); + EditorUI.current.widgets.DrawItemTooltip(C_TEXT); NativeImGui.End(); NativeImGui.Render(); } @@ -99,10 +102,12 @@ void Frame() Frame(); NativeImGui.Raw.AddMousePosEvent(io, hover.X, hover.Y); for (int index = 0; index < 4; index++) + { Frame(); + } using NativeStringLease nativeTestText2 = Utf8Codec.EncodeNullTerminated("##Tooltip_00", allowsNull: false); ImGuiWindow* tooltip = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTestText2.pointer); - Assert.False((tooltip == null)); + Assert.False((tooltip is null)); Assert.True((tooltip->Active != 0)); Assert.InRange(tooltip->Pos.X, 0, width); Assert.InRange(tooltip->Pos.Y, 0, height); @@ -122,7 +127,11 @@ public void HelpBoxUsesWrappedCardHeightWithoutHorizontalOverflow() using NativeStringLease nativeTestText3 = Utf8Codec.EncodeNullTerminated("HelpBox acceptance", allowsNull: false); NativeImGui.Raw.Begin((sbyte*)nativeTestText3.pointer, null, 0); float width = NativeImGui.GetContentRegionAvail().X; - EditorUI.current.widgets.HelpBox("Assign a Sprite to enable atlas geometry, borders, pixel density, and sampling controls.", "i", EditorPalette.warning); + EditorUI.current.widgets.HelpBox( + "Assign a Sprite to enable atlas geometry, borders, pixel density, and sampling controls.", + "i", + EditorPalette.warning + ); Vector2 size = NativeImGui.GetItemRectSize(); Assert.Equal(width, size.X, 2); Assert.True(size.Y > NativeImGui.GetTextLineHeight() * 2); @@ -153,7 +162,7 @@ float framebufferScale NativeImGui.SetNextWindowPos(new Vector2(30, 30)); NativeImGui.SetNextWindowSize(new Vector2(320, 180)); using NativeStringLease nativeTestText4 = Utf8Codec.EncodeNullTerminated("Opaque surface", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, (int)(ImGuiWindowFlags.NoCollapse)); + NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, (int)(GuiWindowFlags.NoCollapse)); NativeImGui.End(); NativeImGui.Render(); } @@ -165,16 +174,22 @@ float framebufferScale // conceal a transparent join between independently anti-aliased background shapes. for (int sample = -10; sample <= 10; sample++) { - Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, seam + sample * 0.1f); + var point = new Vector2(window->Pos.X + window->Size.X * 0.47f, seam + sample * 0.1f); float coverage = CoverageAt(window->DrawList, point); - Assert.True(coverage >= 0.999f, $"Transparent title/body join: zoom={zoom}, scale={framebufferScale}, y={point.Y}, alpha={coverage}"); + Assert.True( + coverage >= 0.999f, + $"Transparent title/body join: zoom={zoom}, scale={framebufferScale}, y={point.Y}, alpha={coverage}" + ); } for (int pixel = -2; pixel <= 2; pixel++) { float y = (MathF.Floor(seam * framebufferScale) + pixel + 0.5f) / framebufferScale; - Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, y); - Assert.True(CoverageAt(window->DrawList, point) >= 0.999f, $"Transparent device pixel: zoom={zoom}, scale={framebufferScale}, y={y}"); + var point = new Vector2(window->Pos.X + window->Size.X * 0.47f, y); + Assert.True( + CoverageAt(window->DrawList, point) >= 0.999f, + $"Transparent device pixel: zoom={zoom}, scale={framebufferScale}, y={y}" + ); } Assert.True(NativeImGui.Raw.GetStyle()->AntiAliasedFill != 0); @@ -191,7 +206,9 @@ Vector2 point ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; Vector4 clip = Unsafe.BitCast(command.ClipRect); if (point.X < clip.X || point.X >= clip.Z || point.Y < clip.Y || point.Y >= clip.W) + { continue; + } for (uint index = command.IdxOffset; index < command.IdxOffset + command.ElemCount; index += 3) { ImDrawVert a = list->VtxBuffer.Data[(int)command.VtxOffset + list->IdxBuffer.Data[(int)index]]; @@ -202,12 +219,16 @@ Vector2 point Vector2 cPosition = Unsafe.BitCast(c.Pos); float area = Cross(bPosition - aPosition, cPosition - aPosition); if (MathF.Abs(area) < 0.000001f) + { continue; + } float wa = Cross(bPosition - point, cPosition - point) / area; float wb = Cross(cPosition - point, aPosition - point) / area; float wc = 1 - wa - wb; if (wa < 0 || wb < 0 || wc < 0) + { continue; + } float alpha = (wa * (a.Col >> 24) + wb * (b.Col >> 24) + wc * (c.Col >> 24)) / 255f; result = alpha + result * (1 - alpha); } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs new file mode 100644 index 000000000..3e5469f50 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs @@ -0,0 +1,7 @@ +using System; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Scripting.Tests; + +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] +internal sealed class ProbeInspectorAttribute : InspectorPresentationAttribute; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs new file mode 100644 index 000000000..375ae54ea --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[InspectorAttributeDrawer(typeof(ProbeInspectorAttribute), priority: 10_000)] +internal sealed class ProbeInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + public void Update(InspectorAttributeDrawContext context) + => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + + public void DrawBefore(InspectorAttributeDrawContext context) + { + _ = context; + observations.Add("before"); + } + + public void DrawAfter(InspectorAttributeDrawContext context) + { + _ = context; + observations.Add("after"); + } + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs index 9b5f2da65..b02486767 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs @@ -1,44 +1,45 @@ using System; using System.Threading.Tasks; - +using Xunit; using Inno.Core.Serialization; using Inno.Core.Settings; -using RuntimeSettings = Inno.Core.Settings.Settings; -using Xunit; +using RuntimeSettings = Inno.Core.Settings.Settings; namespace Inno.Editor.Scripting.Tests; public sealed class ProjectSettingsExecutionContextTests { - private static readonly ProjectSettingId S_SETTING_ID = new("tests.execution-context"); + private static readonly ProjectSettingID SETTING_ID = new("tests.execution-context"); [Fact] - public void Settings_WithoutAnExecutionScope_FailsExplicitly() + public void SettingsWithoutAnExecutionScopeFailsExplicitly() { InvalidOperationException exception = Assert.Throws(() => - RuntimeSettings.Get(S_SETTING_ID)); + RuntimeSettings.Get(SETTING_ID)); Assert.Contains("execution scope is available", exception.Message, StringComparison.Ordinal); } [Fact] - public void NestedScopes_RestoreThePreviousSettingsLookup() + public void NestedScopesRestoreThePreviousSettingsLookup() { var outer = new FixedSettingsLookup(11); var inner = new FixedSettingsLookup(22); using (ProjectSettingsExecutionContext.EnterScope(outer)) { - Assert.Equal(11, RuntimeSettings.Get(S_SETTING_ID).value); + Assert.Equal(11, RuntimeSettings.Get(SETTING_ID).value); using (ProjectSettingsExecutionContext.EnterScope(inner)) - Assert.Equal(22, RuntimeSettings.Get(S_SETTING_ID).value); - Assert.Equal(11, RuntimeSettings.Get(S_SETTING_ID).value); + { + Assert.Equal(22, RuntimeSettings.Get(SETTING_ID).value); + } + Assert.Equal(11, RuntimeSettings.Get(SETTING_ID).value); } } [Fact] - public void Scopes_DisposedOutOfOrder_AreRejectedWithoutLosingTheActiveLookup() + public void ScopesDisposedOutOfOrderAreRejectedWithoutLosingTheActiveLookup() { var outer = new FixedSettingsLookup(11); var inner = new FixedSettingsLookup(22); @@ -58,7 +59,7 @@ public void Scopes_DisposedOutOfOrder_AreRejectedWithoutLosingTheActiveLookup() } [Fact] - public async Task ParallelAsyncFlows_ResolveTheirOwnSettingsLookups() + public async Task ParallelAsyncFlowsResolveTheirOwnSettingsLookups() { Task first = ResolveAsync(new FixedSettingsLookup(11)); Task second = ResolveAsync(new FixedSettingsLookup(22)); @@ -71,24 +72,28 @@ private static async Task ResolveAsync(IProjectSettingsLookup lookup) { using IDisposable scope = ProjectSettingsExecutionContext.EnterScope(lookup); await Task.Yield(); - return RuntimeSettings.Get(S_SETTING_ID).value; + return RuntimeSettings.Get(SETTING_ID).value; } private sealed class FixedSettingsLookup(int value) : IProjectSettingsLookup { - public Guid ownerId { get; } = Guid.NewGuid(); + public Guid ownerID { get; } = Guid.NewGuid(); public long revision => value; - public TSetting Get(ProjectSettingId id) + public TSetting Get(ProjectSettingID id) where TSetting : class, ISerializable { if (typeof(TSetting) != typeof(TestSetting)) + { throw new InvalidOperationException("The requested test setting type is unsupported."); + } return (TSetting)(object)new TestSetting { value = value }; } - public bool TryGet(ProjectSettingId id, out TSetting? setting) - where TSetting : class, ISerializable + public bool TryGet( + ProjectSettingID id, + out TSetting? setting + ) where TSetting : class, ISerializable { setting = Get(id); return true; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs b/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs new file mode 100644 index 000000000..240a13074 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class SampleIdentitySettings : ISerializable +{ + /// + /// Gets or sets one neutral identity stored inside an import settings payload. + /// + [SerializableProperty] + public Guid referenceId { get; set; } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs b/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs new file mode 100644 index 000000000..bcd33e85a --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs @@ -0,0 +1,17 @@ +using Inno.Editor.Core; +using Inno.Editor.Scene; + +namespace Inno.Editor.Scripting.Tests; + +[EditorModule("tests.scene-reload-probe", order: 102)] +public sealed class SceneReloadProbe : EditorModule +{ + public SceneReloadProbe(IEditorSceneWorkspace sceneWorkspace) + { + workspace = sceneWorkspace; + } + + public static IEditorSceneWorkspace? workspace { get; private set; } + + public static void Reset() => workspace = null; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs new file mode 100644 index 000000000..8954ae2f2 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class ScriptingAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs new file mode 100644 index 000000000..253d48fac --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Scripting.Tests; + +[EditorModule("tests.scripting-compilation-probe", order: 101)] +public sealed class ScriptingCompilationProbe : EditorModule +{ + public ScriptingCompilationProbe(IEditorScriptCompilation scripting) + { + compilation = scripting; + } + + public static IEditorScriptCompilation? compilation { get; private set; } + + public static void Reset() => compilation = null; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs new file mode 100644 index 000000000..977fd7ff0 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Build; +using Inno.Core.IO; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Plugins.Authoring; +using Inno.Runtime; +using Inno.Scripting.Compiler; +using Inno.Scripting.Reload; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class ScriptingFixture : IDisposable +{ + private readonly IdentityAllocator m_identities = new(); + private readonly IDisposable m_diagnosticScope; + private readonly IDisposable m_identityScope; + private readonly ProjectSettingsStore m_settings; + private readonly PluginEnvironment m_plugins; + private RuntimeSession? m_editorSession; + private bool m_disposed; + + internal ScriptingFixture( + Action? configureProject = null, + bool enableFileSystemWatcher = false, + int fileWatcherFlushDelayMs = 100 + ) { + this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); + string assetRoot = Path.Combine(projectRoot, "Assets"); + string pluginRoot = Path.Combine(projectRoot, "Plugins"); + string libraryRoot = Path.Combine(projectRoot, "Library"); + Directory.CreateDirectory(assetRoot); + Directory.CreateDirectory(pluginRoot); + Directory.CreateDirectory(libraryRoot); + m_identityScope = m_identities.EnterScope(); + this.host = new EngineHostBuilder().UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(ScriptingPipelineTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); + m_diagnosticScope = host.diagnostics.EnterScope(); + configureProject?.Invoke(projectRoot, host.serialization); + var pluginSources = new PluginSourceService(host.serialization, pluginRoot, libraryRoot); + PluginScanResult scan = pluginSources.Scan(); + AssetPipelineOptions options = AssetPipelineOptions.Create(assetRoot, libraryRoot); + this.assets = new AssetPipeline( + host.modules, + host.types, + host.serialization, + m_identities, + host.diagnostics, + host.logs, + options with + { + enableFileSystemWatcher = enableFileSystemWatcher, + fileWatcherFlushDelayMs = fileWatcherFlushDelayMs, + sourceMounts = [..options.sourceMounts!, ..PluginSourceService.GetActivatableMounts(scan)] + } + ); + m_settings = new ProjectSettingsStore( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectID("tests.scripting"), + AssetSerializationContext.Create(assets) + ); + m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); + string dotnetHost = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + this.compiler = new ScriptCompiler( + new ScriptCompilerOptions + { + projectRootDirectory = projectRoot, + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + }, + assets, + m_plugins + ); + } + + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + m_editorSession?.Dispose(); + m_plugins.Dispose(); + assets.Dispose(); + m_settings.Dispose(); + m_diagnosticScope.Dispose(); + host.Dispose(); + m_identityScope.Dispose(); + if (Directory.Exists(projectRoot)) + { + Directory.Delete(projectRoot, recursive: true); + } + } + + internal string projectRoot { get; } + internal EngineHost host { get; } + internal AssetPipeline assets { get; } + internal ScriptCompiler compiler { get; } + internal IReadOnlyList activePlugins => m_plugins.activePlugins; + + internal RuntimeSession editorSession + => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); + + internal void Write( + string relativePath, + string source + ) { + string path = Path.Combine(projectRoot, "Assets", relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, source); + } + + internal void Move( + string sourceRelativePath, + string destinationRelativePath + ) { + string source = Path.Combine(projectRoot, "Assets", sourceRelativePath); + string destination = Path.Combine(projectRoot, "Assets", destinationRelativePath); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Move(source, destination); + string sourceMetadata = source + ".imeta"; + if (File.Exists(sourceMetadata)) + { + File.Move(sourceMetadata, destination + ".imeta"); + } + } + + internal void WriteVersionedBehavior(int version) + => Write("VersionedBehavior.cs", $$""" + using InnoEngine.Scene; + + public sealed class VersionedBehavior : GameBehavior + { + public int version => {{version}}; + } + """); + + internal void Rescan() => assets.Rescan(); + + internal ScriptCompilationResult Compile( + IProgress? progress = null, + CancellationToken cancellationToken = default + ) { + Rescan(); + return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken: cancellationToken).GetAwaiter().GetResult(); + } + + internal ScriptCompilationResult CompileRuntimeDeployment( + string? targetRuntimeDirectory = null, + IProgress? progress = null, + CancellationToken cancellationToken = default + ) { + Rescan(); + return compiler + .CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken) + .GetAwaiter() + .GetResult(); + } + + internal string CreateDeploymentRuntime() + { + string directory = Path.Combine(projectRoot, "TargetRuntime"); + Directory.CreateDirectory(directory); + foreach (string source in Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly)) + { + File.Copy(source, Path.Combine(directory, Path.GetFileName(source)), overwrite: true); + } + + return directory; + } + + internal ScriptReloadHost CreateReloadHost( + EditorReloadCoordinator? reloads = null, + bool autoCompile = false + ) => new( + new ScriptReloadOptions + { + autoCompile = autoCompile, + debounceMilliseconds = 0, + compilationWarningTimeout = Timeout.InfiniteTimeSpan + }, + compiler, + assets, + m_plugins, + host.modules, + m_settings, + reloads ?? new EditorReloadCoordinator(), + CreateScriptModuleSource + ); + + internal ScriptCompilationResult CompilePending(ScriptReloadHost reload) + { + Rescan(); + reload.RecompileScripting(); + Assert.True(reload.TryCompilePending(out Task? compilation)); + return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); + } + + internal ScriptCompilationResult CompilePendingPluginReload(ScriptReloadHost reload) + { + reload.ReloadPlugins(); + Assert.True(reload.TryCompilePending(out Task? compilation)); + return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); + } + + internal bool RefreshPlugins() => m_plugins.Refresh(); + + internal Type ResolveActiveType(string name) + { + TypeCacheSnapshot snapshot = host.types.current; + return snapshot.types + .Select(typeRef => typeRef.Resolve(snapshot)) + .Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); + } + + internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? reloads = null) + { + ScriptingCompilationProbe.Reset(); + SceneReloadProbe.Reset(); + reloads ??= new EditorReloadCoordinator(); + RuntimeSession editorSession = CreateEditorSession(); + return new EditorInteractionRuntime( + new EditorContext(projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), + host.types, + host.logs, + [ + host.types, + host.serialization, + m_identities, + editorSession.identities, + host.modules, + assets, + m_plugins, + m_settings, + compiler, + new Func(CreateScriptModuleSource), + editorSession, + reloads + ] + ); + } + + internal RuntimeSession CreateEditorSession() + { + m_editorSession ??= host.CreateSession( + new RuntimeSessionOptions + { + kind = RuntimeSessionKind.Edit, + applicationID = "tests.editor", + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), + referenceResolvers = [assets] + } + ); + return m_editorSession; + } + + private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) + => new DotNetModuleSource + { + artifactRootDirectory = Path.Combine(projectRoot, "Library", "Assemblies"), + moduleName = deployment.moduleName, + mainAssemblyPath = deployment.mainAssemblyPath, + domain = deployment.domain, + scope = deployment.scope, + preloadAssemblyPaths = deployment.preloadAssemblyPaths, + upstreamModuleNames = deployment.upstreamModuleNames, + assemblyScopes = deployment.assemblyScopes, + collectible = true + }; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs index 29180f7de..a4368841f 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; +using Xunit; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; @@ -19,8 +19,8 @@ public void SupersededCompilationCannotPublishIntoTheNextProgressOperation() Assert.True(reload.TryCompilePending(out Task? running)); reload.RecompileScripting(); ScriptReloadProgress queued = reload.progress; - Assert.True(queued.operationId > first.operationId); - Assert.False(reload.CancelCompilation(first.operationId)); + Assert.True(queued.operationID > first.operationID); + Assert.False(reload.CancelCompilation(first.operationID)); _ = CompleteCompilationOnOwner(running!); Assert.Same(queued, reload.progress); Assert.Equal(0f, queued.fraction); @@ -29,7 +29,7 @@ public void SupersededCompilationCannotPublishIntoTheNextProgressOperation() Assert.True(reload.TryCompilePending(out Task? replacement)); Assert.True(CompleteCompilationOnOwner(replacement!).success); ScriptReloadProgress compiled = reload.progress; - Assert.Equal(queued.operationId, compiled.operationId); + Assert.Equal(queued.operationID, compiled.operationID); Assert.Equal(0.8f, compiled.fraction); Assert.Contains("waiting for generation activation", compiled.stage); Assert.False(compiled.canCancel); @@ -51,5 +51,6 @@ public void CompilationFailureDoesNotPublishSuccessfulWorkflowCompletion() } // Reload and fixture retirement must remain on their creating owner thread. - private static ScriptCompilationResult CompleteCompilationOnOwner(Task compilation) => compilation.GetAwaiter().GetResult(); + private static ScriptCompilationResult CompleteCompilationOnOwner(Task compilation) + => compilation.GetAwaiter().GetResult(); } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs similarity index 85% rename from tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs rename to tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs index ad47add50..4f5467803 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs @@ -1,12 +1,11 @@ using System; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; @@ -43,14 +42,6 @@ public sealed class SnapshotPayload : ISerializable GC.KeepAlive(snapshot); } - [MethodImpl(MethodImplOptions.NoInlining)] - private static (SerializationSnapshot, WeakReference) CaptureScriptSnapshot(ScriptingFixture fixture) - { - Type type = fixture.ResolveActiveType("SnapshotPayload"); - var payload = (ISerializable)Activator.CreateInstance(type)!; - return (fixture.host.serialization.CaptureSnapshot(new CapturedScriptPayload(payload)), new WeakReference(type)); - } - [Fact] [Trait("Acceptance", "Lifecycle")] [Trait("ProcessIsolation", "Required")] @@ -92,8 +83,7 @@ public void TenActionMenuGenerationsRetireTypesAndPreserveLastGoodAfterFailure() GC.KeepAlive(retainedMenu); void WriteAction(int version) - { - m_fixture.Write("Editor/LifecycleAction.editor.cs", $$""" + => m_fixture.Write("Editor/LifecycleAction.editor.cs", $$""" using InnoEditor.Interactions; [EditorAction("tests.lifecycle.action", "tests/menu-lifecycle")] @@ -106,7 +96,14 @@ protected override EditorActionState Query(EditorActionContext context) protected override void Execute(EditorActionContext context) { } } """); - } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static (SerializationSnapshot, WeakReference) CaptureScriptSnapshot(ScriptingFixture fixture) + { + Type type = fixture.ResolveActiveType("SnapshotPayload"); + ISerializable payload = (ISerializable)Activator.CreateInstance(type)!; + return (fixture.host.serialization.CaptureSnapshot(new CapturedScriptPayload(payload)), new WeakReference(type)); } private static void AssertMenu( @@ -115,23 +112,7 @@ int version ) { EditorMenuItem item = Assert.Single(runtime.interactions.For("tests/menu-lifecycle").BuildMenu().items); Assert.Equal("Generation " + version, item.label); - Assert.Equal("tests.lifecycle.action", item.actionId); + Assert.Equal("tests.lifecycle.action", item.actionID); Assert.True(item.status.isEnabled); } } - -internal sealed class CapturedScriptPayload(ISerializable payload) : ISerializable -{ - internal ISerializable payload { get; } = payload; -} - -internal sealed class CapturedScriptPayloadConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CapturedScriptPayload value - ) => writer.WritePropertiesData("state", value.payload); - - public override CapturedScriptPayload Read(SerializationReader reader) - => throw new NotSupportedException("This fixture only captures an existing generation."); -} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs index becba9147..933f3950b 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs @@ -1,48 +1,50 @@ -using Inno.Core.Logging; -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Core.Diagnostics; -using Inno.Extensibility.Reload; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; -using Inno.Editor.Annotations; using System.IO.Compression; using System.Linq; -using System.Runtime.CompilerServices; +using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; -using Inno.Core.Identity; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.PlayMode; using Inno.Editor.Scene; -using Inno.Editor.Scripting; -using Inno.Plugins.Authoring; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Plugins; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; + public sealed partial class ScriptingPipelineTests : IDisposable { private readonly ScriptingFixture m_fixture = new(); + public void Dispose() => m_fixture.Dispose(); + [Theory] [InlineData(false)] [InlineData(true)] @@ -58,7 +60,7 @@ public static class SourceLocalPathProbe ScriptCompilationResult result = runtimeDeployment ? m_fixture.CompileRuntimeDeployment() : m_fixture.Compile(); Assert.True(result.success, FormatDiagnostics(result)); AssetPath path = InvokePublicPathProbe(Path.Combine(result.outputDirectory!, "Inno.GameScripts.dll")); - Assert.Equal(AssetSourceId.project, path.source); + Assert.Equal(AssetSourceID.project, path.source); Assert.Equal("Materials/Default.imaterial", path.localPath); } @@ -70,21 +72,37 @@ public void SourceLocalAssetPathsFollowInstalledPluginOwnership(bool runtimeDepl using var fixture = new ScriptingFixture(( root, serialization - ) => WritePluginPackage(root, "local-path.iplugin", serialization, new PluginManifest { - pluginId = "tests.local-path", - displayName = "Source Ownership Fixture" - }, new Dictionary { ["Assets/Nested.imeta"] = serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.Directory }), ["Assets/Nested/SourceLocalPathProbe.cs"] = System.Text.Encoding.UTF8.GetBytes(""" + ) => WritePluginPackage( + root, + "local-path.iplugin", + serialization, + new PluginManifest + { + pluginId = "tests.local-path", + displayName = "Source Ownership Fixture" + }, + new Dictionary + { + ["Assets/Nested.imeta"] = serialization.Serialize( + new ScriptingAssetSourceMeta { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.Directory } + ), + ["Assets/Nested/SourceLocalPathProbe.cs"] = Encoding.UTF8.GetBytes(""" using InnoEngine.Assets; public static class SourceLocalPathProbe { public static AssetPath Resolve() => Assets.LocalPath("Materials/Default.imaterial"); } - """), ["Assets/Nested/SourceLocalPathProbe.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) })); + """), + ["Assets/Nested/SourceLocalPathProbe.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) + } + )); ScriptCompilationResult result = runtimeDeployment ? fixture.CompileRuntimeDeployment() : fixture.Compile(); Assert.True(result.success, FormatDiagnostics(result)); - string assemblyPath = Assert.Single(result.runtimeAssemblyPaths.Where(static path => Path.GetFileName(path).StartsWith("Inno.Plugin.", StringComparison.Ordinal))); + string assemblyPath = Assert.Single( + result.runtimeAssemblyPaths.Where(static path => Path.GetFileName(path).StartsWith("Inno.Plugin.", StringComparison.Ordinal)) + ); AssetPath path = InvokePublicPathProbe(assemblyPath); - Assert.Equal(new AssetSourceId("tests.local-path"), path.source); + Assert.Equal(new AssetSourceID("tests.local-path"), path.source); Assert.Equal("Materials/Default.imaterial", path.localPath); } @@ -104,30 +122,10 @@ public static class SourceLocalPathProbe string map = Assert.Single(project.Descendants("PathMap")).Value; Assert.Contains("Nested,,==Folder", map, StringComparison.Ordinal); Assert.Contains("project::./Nested,,==Folder", map, StringComparison.Ordinal); - Assert.Contains(project.Descendants("HintPath"), reference => ContainsCustomAttribute(Path.GetFullPath(reference.Value, m_fixture.projectRoot), "CallerFilePathAttribute")); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static AssetPath InvokePublicPathProbe(string assemblyPath) - { - var lifetime = new System.Runtime.Loader.AssemblyLoadContext("source-local-path-test", isCollectible: true); - try - { - using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); - var assembly = lifetime.LoadFromStream(stream); - Func resolve = assembly.GetType( - "SourceLocalPathProbe", - throwOnError: true - )!.GetMethod( - "Resolve", - System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static - )!.CreateDelegate>(); - return resolve(); - } - finally - { - lifetime.Unload(); - } + Assert.Contains( + project.Descendants("HintPath"), + reference => ContainsCustomAttribute(Path.GetFullPath(reference.Value, m_fixture.projectRoot), "CallerFilePathAttribute") + ); } [Theory] @@ -148,7 +146,10 @@ public sealed class FrameworkReferenceProbe : GameBehavior using FileStream stream = File.OpenRead(Path.Combine(result.outputDirectory!, "Inno.GameScripts.dll")); using var executable = new PEReader(stream); MetadataReader metadata = executable.GetMetadataReader(); - Assert.DoesNotContain(metadata.AssemblyReferences, handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name) == "System.Private.CoreLib"); + Assert.DoesNotContain( + metadata.AssemblyReferences, + handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name) == "System.Private.CoreLib" + ); } [Theory] @@ -165,7 +166,10 @@ public static class IgnoredApiProbe """); ScriptCompilationResult result = runtimeDeployment ? m_fixture.CompileRuntimeDeployment() : m_fixture.Compile(); Assert.False(result.success); - Assert.Contains(result.diagnostics, static diagnostic => diagnostic.id == "CS1061" && diagnostic.message.Contains("CaptureFrom", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + static diagnostic => diagnostic.id == "CS1061" && diagnostic.message.Contains("CaptureFrom", StringComparison.Ordinal) + ); } [Fact] @@ -199,8 +203,7 @@ Action observer "Inno.EditorScripts.csproj" } - ) - { + ) { XDocument document = XDocument.Load(Path.Combine(m_fixture.projectRoot, project)); bool found = false; foreach (XElement reference in document.Descendants("HintPath")) @@ -212,8 +215,12 @@ Action observer { TypeDefinition type = metadata.GetTypeDefinition(handle); if (metadata.GetString(type.Namespace) != "InnoEngine.Events" || metadata.GetString(type.Name) != "EventDispatcher") + { continue; - found = type.GetEvents().Any(eventHandle => metadata.GetString(metadata.GetEventDefinition(eventHandle).Name) == "dispatched"); + } + found = type + .GetEvents() + .Any(eventHandle => metadata.GetString(metadata.GetEventDefinition(eventHandle).Name) == "dispatched"); } } @@ -232,11 +239,11 @@ public void ShaderPreviewOptionalInputsRemainNullableInTheLogicalAndImplementati public sealed class NullablePreviewProbe { public bool Resolve(ShaderPreviewContext preview, IRenderResourceService resources) - => resources.TryResolveMaterialArtifact(preview.resourceId, preview.artifact, preview.material, - new ShaderContractId("test.surface"), new ShaderPassRoleId("test.color"), + => resources.TryResolveMaterialArtifact(preview.resourceID, preview.artifact, preview.material, + new ShaderContractID("test.surface"), new ShaderPassRoleID("test.color"), ShaderProgramKind.Raster, null, null, preview.diagnostics, out _); public void TypedCallback(RenderGraphBuilder graph) - => graph.AddRasterPass("typed", new RenderPhaseId("test"), "payload", + => graph.AddRasterPass("typed", new RenderPhaseID("test"), "payload", static (value, context) => Consume(value)); private static void Consume(string value) { _ = value.Length; } } @@ -279,13 +286,13 @@ public override EditorViewportLayer CreateLayer(ShaderPreviewContext context) return new("tests.preview", null, frame, 0); } public static bool Resolve(IRenderResourceService resources, ShaderPreviewContext context) - => resources.TryResolveMaterialArtifact(context.resourceId, context.artifact, context.material, + => resources.TryResolveMaterialArtifact(context.resourceID, context.artifact, context.material, new("tests.preview"), new("draw"), ShaderProgramKind.Raster, null, null, context.diagnostics, out _); } public sealed class ShaderNodeProbe : IShaderNodeCompiler { - public string definitionId => "tests.shader-node-probe"; + public string definitionID => "tests.shader-node-probe"; public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => [new("value", ShaderSourceType.Atomic("float"), GraphPortDirection.Output)]; public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) @@ -341,9 +348,11 @@ bool ContainsShaderApi(string project) if (metadata.TypeDefinitions.Any(handle => { TypeDefinition type = metadata.GetTypeDefinition(handle); - return metadata.GetString(type.Namespace) == "InnoEditor.Rendering.Shaders" && metadata.GetString(type.Name) == "IShaderNodeCompiler"; - })) + return metadata.GetString(type.Namespace) == "InnoEditor.Rendering.Shaders" + && metadata.GetString(type.Name) == "IShaderNodeCompiler"; + })) { return true; + } } return false; @@ -471,7 +480,10 @@ public void RuntimeDeploymentCompilationDoesNotCompileOrValidateEditorSources() Assert.True(File.Exists(Path.Combine(result.outputDirectory!, "Inno.GameScripts.dll"))); Assert.False(File.Exists(Path.Combine(result.outputDirectory!, "Inno.EditorScripts.dll"))); Assert.DoesNotContain(result.moduleDeployments, static request => request.scope == AssemblyScope.Editor); - Assert.DoesNotContain(result.compiledAssemblyNames.Concat(result.reusedAssemblyNames), static assemblyName => assemblyName.Contains("Editor", StringComparison.Ordinal)); + Assert.DoesNotContain( + result.compiledAssemblyNames.Concat(result.reusedAssemblyNames), + static assemblyName => assemblyName.Contains("Editor", StringComparison.Ordinal) + ); } [Fact] @@ -521,8 +533,14 @@ public sealed class AttributedBehavior : GameBehavior using FileStream stream = File.OpenRead(playerAssembly); using var executable = new PEReader(stream); MetadataReader metadata = executable.GetMetadataReader(); - Assert.DoesNotContain(metadata.AssemblyReferences, handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name).Contains("Editor", StringComparison.Ordinal)); - Assert.DoesNotContain(metadata.TypeDefinitions, handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) == "CustomPresentationAttribute"); + Assert.DoesNotContain( + metadata.AssemblyReferences, + handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name).Contains("Editor", StringComparison.Ordinal) + ); + Assert.DoesNotContain( + metadata.TypeDefinitions, + handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) == "CustomPresentationAttribute" + ); } [Fact] @@ -577,7 +595,7 @@ public sealed class RemovedBehaviorBase : Behavior [Fact] public void RuntimeSourceCannotReferenceEditorApiButEditorSourceCan() { - const string source = """ + const string C_SOURCE = """ using InnoEditor.Core; public sealed class EditorApiProbe @@ -585,7 +603,7 @@ public sealed class EditorApiProbe public EditorContext? context { get; set; } } """; - m_fixture.Write("EditorApiProbe.cs", source); + m_fixture.Write("EditorApiProbe.cs", C_SOURCE); ScriptCompilationResult runtimeResult = m_fixture.Compile(); Assert.False(runtimeResult.success); m_fixture.Move("EditorApiProbe.cs", "EditorApiProbe.editor.cs"); @@ -611,11 +629,10 @@ public sealed class SecondaryProbe : GameBehavior Assert.False(result.success); Assert.Contains( result.diagnostics, - static diagnostic => diagnostic.id == "INNO2001" + static diagnostic => ( + diagnostic.id == "INNO2001" && diagnostic.severity == DiagnosticSeverity.Error - && diagnostic.message.Contains( - "SecondaryProbe", - StringComparison.Ordinal + && diagnostic.message.Contains("SecondaryProbe", StringComparison.Ordinal) ) ); } @@ -628,7 +645,10 @@ public void CachedCompilationReplaysWarningsAndReusesTheGeneration() ScriptCompilationResult second = m_fixture.Compile(); Assert.True(first.success, FormatDiagnostics(first)); Assert.True(second.success, FormatDiagnostics(second)); - ScriptDiagnostic firstWarning = Assert.Single(first.diagnostics, static diagnostic => diagnostic.id == "CS0169" && diagnostic.severity == DiagnosticSeverity.Warning); + ScriptDiagnostic firstWarning = Assert.Single( + first.diagnostics, + static diagnostic => diagnostic.id == "CS0169" && diagnostic.severity == DiagnosticSeverity.Warning + ); Assert.Contains(second.diagnostics, diagnostic => diagnostic == firstWarning); Assert.Equal(first.outputDirectory, second.outputDirectory); Assert.NotEmpty(second.reusedAssemblyNames); @@ -643,10 +663,12 @@ public void CompilerProgressIsMonotonicAndIncludesStageTimings() Assert.True(result.success, FormatDiagnostics(result)); Assert.NotEmpty(progress.values); Assert.All(progress.values, static value => Assert.InRange(value.fraction, 0f, 1f)); - Assert.True(progress.values.Zip(progress.values.Skip(1), static ( - left, - right - ) => right.fraction >= left.fraction).All(static value => value)); + Assert.True( + progress.values.Zip(progress.values.Skip(1), static ( + left, + right + ) => right.fraction >= left.fraction).All(static value => value) + ); Assert.NotEmpty(result.stageTimings); Assert.All(result.stageTimings, static timing => Assert.True(timing.elapsed >= TimeSpan.Zero)); } @@ -667,19 +689,26 @@ public void LogicalDocumentationProjectsNamespacesWithoutLosingMemberDescription { m_fixture.compiler.GenerateProjectFiles(); XDocument project = XDocument.Load(Path.Combine(m_fixture.projectRoot, "Inno.GameScripts.csproj")); - XElement[] members = project.Descendants("HintPath").Select(reference => Path.ChangeExtension(Path.GetFullPath(reference.Value, m_fixture.projectRoot), ".xml")).Where(File.Exists).SelectMany(path => XDocument.Load(path).Descendants("member")).ToArray(); + XElement[] members = project + .Descendants("HintPath") + .Select(reference => Path.ChangeExtension(Path.GetFullPath(reference.Value, m_fixture.projectRoot), ".xml")) + .Where(File.Exists) + .SelectMany(path => XDocument.Load(path).Descendants("member")) + .ToArray(); XElement manager = Assert.Single(members.Where(member => member.Attribute("name")?.Value == "T:InnoEngine.Scene.SceneManager")); Assert.Contains("scene operations", manager.Element("summary")!.Value, StringComparison.Ordinal); Assert.Contains(manager.Descendants("see"), reference => reference.Attribute("cref")?.Value == "T:InnoEngine.Scene.SceneWorld"); Assert.Contains( members, - member => member.Attribute("name")?.Value == "P:InnoEngine.Scene.SceneManager.activeScene" - && member.Element("summary")?.Value.Contains( - "active scene", - StringComparison.Ordinal - ) == true + member => ( + member.Attribute("name")?.Value == "P:InnoEngine.Scene.SceneManager.activeScene" + && member.Element("summary")?.Value.Contains("active scene", StringComparison.Ordinal) == true + ) + ); + Assert.DoesNotContain( + members, + member => member.Attribute("name")?.Value.StartsWith("T:Inno.Scene.", StringComparison.Ordinal) == true ); - Assert.DoesNotContain(members, member => member.Attribute("name")?.Value.StartsWith("T:Inno.Scene.", StringComparison.Ordinal) == true); } [Fact] @@ -723,8 +752,8 @@ public void ProjectTildeDirectoriesRemainBrowsableAndParticipateInAuthoringCompi public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() { using var fixture = new ScriptingFixture(WriteSamplePlugin); - AssetPath source = new(new AssetSourceId("tests.samples"), "~Starter"); - AssetPath sourceFile = new(new AssetSourceId("tests.samples"), "~Starter/StarterBehavior.cs"); + var source = new AssetPath(new AssetSourceID("tests.samples"), "~Starter"); + var sourceFile = new AssetPath(new AssetSourceID("tests.samples"), "~Starter/StarterBehavior.cs"); Assert.True(fixture.assets.TryGetFileSystemEntry(source, out AssetFileEntry sample)); Assert.True(sample.isReadOnly); Assert.True(sample.isSample); @@ -733,11 +762,14 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() Assert.True(sampleContent.isReadOnly); Assert.True(sampleContent.isSampleContent); Assert.True(fixture.assets.TryGetInfo(sourceFile, out AssetInfo? templateInfo)); - Guid sourcePersistentId = Assert.IsType(templateInfo).persistentId; + Guid sourcePersistentID = Assert.IsType(templateInfo).persistentID; ScriptCompilationResult authoring = fixture.Compile(); Assert.True(authoring.success, FormatDiagnostics(authoring)); Assert.Contains(authoring.compiledAssemblyNames, name => name.EndsWith(".Samples", StringComparison.Ordinal)); - Assert.DoesNotContain(authoring.runtimeAssemblyPaths, path => Path.GetFileNameWithoutExtension(path).EndsWith(".Samples", StringComparison.Ordinal)); + Assert.DoesNotContain( + authoring.runtimeAssemblyPaths, + path => Path.GetFileNameWithoutExtension(path).EndsWith(".Samples", StringComparison.Ordinal) + ); ScriptCompilationResult player = fixture.CompileRuntimeDeployment(); Assert.True(player.success, FormatDiagnostics(player)); Assert.DoesNotContain(player.compiledAssemblyNames, name => name.EndsWith(".Samples", StringComparison.Ordinal)); @@ -747,10 +779,13 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() cancellationToken ) => { - ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken, sourceSnapshot: sources); + ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( + sourceSnapshot: sources, + cancellationToken: cancellationToken + ); Assert.True(candidate.success, FormatDiagnostics(candidate)); }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); AssetPath imported = import.target; Assert.Equal(AssetPath.Project("~Starter"), imported); @@ -761,7 +796,7 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() StringComparison.OrdinalIgnoreCase ); Assert.True(fixture.assets.TryGetInfo(AssetPath.Project("~Starter/StarterBehavior.cs"), out AssetInfo? importedInfo)); - Assert.NotEqual(sourcePersistentId, Assert.IsType(importedInfo).persistentId); + Assert.NotEqual(sourcePersistentID, Assert.IsType(importedInfo).persistentID); Assert.True(fixture.assets.TryGetFileSystemEntry(imported, out AssetFileEntry importedDirectory)); Assert.False(importedDirectory.isReadOnly); Assert.False(importedDirectory.isSample); @@ -780,20 +815,25 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() root, serialization ) => WriteSamplePlugin(root, serialization, "public sealed class BrokenSample { this is invalid; }")); - AssetPath source = new(new AssetSourceId("tests.samples"), "~Starter"); + var source = new AssetPath(new AssetSourceID("tests.samples"), "~Starter"); using AssetSampleImportTransaction import = PrepareSample(fixture, source); import.BeginValidation(async ( sources, cancellationToken ) => { - ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken, sourceSnapshot: sources); + ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( + sourceSnapshot: sources, + cancellationToken: cancellationToken + ); if (!candidate.success) + { throw new InvalidOperationException(FormatDiagnostics(candidate)); + } }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); Assert.Throws(() => import.Commit()); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); } @@ -801,13 +841,13 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() [Fact] public void SampleImportPreservesEveryLeadingTildeAndRejectsDestinationCollisions() { - AssetPath source = new(new AssetSourceId("tests.samples"), "Samples/~~~Starter"); + var source = new AssetPath(new AssetSourceID("tests.samples"), "Samples/~~~Starter"); Assert.Equal("~~~Starter", AssetSample.GetImportName(source)); Assert.True(AssetSample.IsRuntimeExcluded(AssetPath.Project("~~~Starter/File.cs"), false)); Assert.False(AssetSample.Contains(AssetPath.Project("~~~Starter/File.cs"), false)); using var fixture = new ScriptingFixture(WriteSamplePlugin); fixture.assets.CreateDirectory(AssetPath.Project("~Starter")); - Assert.Throws(() => fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"))); + Assert.Throws(() => fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceID("tests.samples"), "~Starter"))); fixture.host.modules.generations.EnsureReady("retry after rejected import"); } @@ -816,8 +856,8 @@ public void SampleValidationReturnsToOwnerWhileWorkIsPendingAndPublishesExactlyO { using var fixture = new ScriptingFixture(WriteSamplePlugin); int notifications = 0; - fixture.assets.Changed += _ => notifications++; - using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + fixture.assets.changed += _ => notifications++; + using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceID("tests.samples"), "~Starter")); long revision = fixture.assets.revision; Assert.False(fixture.assets.TryGetFileSystemEntry(import.target, out _)); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -837,7 +877,7 @@ public void SampleValidationReturnsToOwnerWhileWorkIsPendingAndPublishesExactlyO Assert.Throws(() => fixture.assets.CreateDirectory(AssetPath.Project("Concurrent"))); Assert.Throws(() => fixture.host.modules.generations.EnsureReady("reload while importing")); completion.SetResult(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); Assert.Equal(1, notifications); Assert.Equal(revision + 1, fixture.assets.revision); @@ -850,21 +890,21 @@ public void SampleCancellationRetainsDependenciesUntilUncooperativeValidationDra { using var fixture = new ScriptingFixture(WriteSamplePlugin); int notifications = 0; - fixture.assets.Changed += _ => notifications++; - using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + fixture.assets.changed += _ => notifications++; + using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceID("tests.samples"), "~Starter")); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); import.BeginValidation(( _, _ ) => new ValueTask(completion.Task)); import.Cancel(); - Assert.Throws(() => import.Rollback()); - Assert.Throws(() => fixture.assets.Dispose()); + Assert.Throws(() => import.Rollback()); + Assert.Throws(() => fixture.assets.Dispose()); Assert.True(fixture.assets.isInitialized); Assert.Throws(() => fixture.host.modules.generations.EnsureReady("reload before drain")); completion.SetResult(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.False(fixture.assets.TryGetFileSystemEntry(import.target, out _)); Assert.False(File.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta"))); Assert.Equal(0, notifications); @@ -876,15 +916,15 @@ public void SampleHistoryFinalizationFailureRollsBackWithoutPublication() { using var fixture = new ScriptingFixture(WriteSamplePlugin); int notifications = 0; - fixture.assets.Changed += _ => notifications++; - using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + fixture.assets.changed += _ => notifications++; + using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceID("tests.samples"), "~Starter")); import.BeginValidation(( _, _ ) => ValueTask.CompletedTask); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); Assert.Throws(() => import.Commit(_ => throw new IOException("History spill failed."))); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.Equal(0, notifications); Assert.False(fixture.assets.TryGetFileSystemEntry(import.target, out _)); fixture.host.modules.generations.EnsureReady("continue after finalization failure"); @@ -894,20 +934,24 @@ public void SampleHistoryFinalizationFailureRollsBackWithoutPublication() public void SampleCopyCancellationLeavesNoProjectOrTransactionDirectory() { using var fixture = new ScriptingFixture(WriteSamplePlugin); - using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceID("tests.samples"), "~Starter") + ); import.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - try - { - import.Rollback(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, 15000)); + try + { + import.Rollback(); + return true; + } + catch (RetirementPendingException) + { + return false; + } + }, 15_000) + ); Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); string transactions = Path.Combine(fixture.assets.libraryRoot, "AssetDatabase", "Transactions"); Assert.True(!Directory.Exists(transactions) || !Directory.EnumerateFileSystemEntries(transactions).Any()); @@ -920,25 +964,29 @@ public void PendingAutomaticCompilationDefersUntilSampleRollback() using var fixture = new ScriptingFixture(WriteSamplePlugin); using ScriptReloadHost reload = fixture.CreateReloadHost(autoCompile: true); reload.Start(); - using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceID("tests.samples"), "~Starter") + ); Assert.False(reload.TryCompilePending(out Task? pending)); Assert.Null(pending); Assert.True(reload.isCompilationPending); import.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - try - { - import.Rollback(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, 15000)); + try + { + import.Rollback(); + return true; + } + catch (RetirementPendingException) + { + return false; + } + }, 15_000) + ); Assert.True(reload.TryCompilePending(out Task? compilation)); - Assert.True(SpinWait.SpinUntil(() => compilation!.IsCompleted, 15000)); + Assert.True(SpinWait.SpinUntil(() => compilation!.IsCompleted, 15_000)); Assert.True(compilation!.IsCompletedSuccessfully); Assert.True(reload.lastCompilation!.success); } @@ -951,7 +999,9 @@ public void EditorSampleImportUsesSharedModalAndUndoRedo() runtime.Start(); IEditorScriptCompilation scripting = Assert.IsAssignableFrom(ScriptingCompilationProbe.compilation); WaitForInitialScriptCompilation(fixture, runtime, scripting); - Assert.True(fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), out AssetFileEntry sample)); + Assert.True( + fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceID("tests.samples"), "~Starter"), out AssetFileEntry sample) + ); Assert.True(runtime.interactions.For("panel/asset.file-browser", sample).Execute("file-browser/import-sample")); EditorModalExtension modal = runtime.modals.Single(value => value.id == "asset-sample-import.progress"); Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); @@ -961,7 +1011,12 @@ public void EditorSampleImportUsesSharedModalAndUndoRedo() EditorModalExtension compilationModal = runtime.modals.Single(value => value.id == "scripting.compilation"); Assert.True(compilationModal.TryGetPresentation(out EditorModalExtension.Presentation compilationPolicy)); Assert.Equal(compilationPolicy.allowScrolling, presentation.allowScrolling); - PumpEditorUntil(fixture, runtime, () => modal.TryGetPresentation(out EditorModalExtension.Presentation state) && !state.isVisible, () => scripting.progress.status); + PumpEditorUntil( + fixture, + runtime, + () => modal.TryGetPresentation(out EditorModalExtension.Presentation state) && !state.isVisible, + () => scripting.progress.status + ); Assert.True(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); Assert.True(runtime.interactions.history.Undo().succeeded); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); @@ -981,12 +1036,19 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() ControlledSampleSourceRewriter.current = control; try { - Assert.True(fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), out AssetFileEntry sample)); + Assert.True( + fixture.assets.TryGetFileSystemEntry( + new AssetPath(new AssetSourceID("tests.samples"), "~Starter"), + out AssetFileEntry sample + ) + ); Assert.True(runtime.interactions.For("panel/asset.file-browser", sample).Execute("file-browser/import-sample")); Assert.True(control.started.Wait(TimeSpan.FromSeconds(5))); Assert.NotEqual(Environment.CurrentManagedThreadId, control.workerThread); for (int frame = 0; frame < 30; frame++) + { runtime.Update(new EditorFrame(1f / 60f, frame / 60f, true)); + } Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); Task shutdownObserver = Task.Run(() => { @@ -994,7 +1056,9 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() { Assert.True(control.canceled.Wait(TimeSpan.FromSeconds(5))); Assert.True(fixture.assets.isInitialized); - Assert.Throws(() => fixture.host.modules.generations.EnsureReady("retire scripting before sample work")); + Assert.Throws( + () => fixture.host.modules.generations.EnsureReady("retire scripting before sample work") + ); } finally { @@ -1002,25 +1066,27 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() } }); runtime.Dispose(); - Assert.True(SpinWait.SpinUntil(() => shutdownObserver.IsCompleted, 15000)); + Assert.True(SpinWait.SpinUntil(() => shutdownObserver.IsCompleted, 15_000)); Assert.True(shutdownObserver.IsCompletedSuccessfully, shutdownObserver.Exception?.ToString()); } finally { control.release.Set(); ControlledSampleSourceRewriter.current = null; - Assert.True(SpinWait.SpinUntil(() => - { - try - { - runtime.Dispose(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, 15000)); + try + { + runtime.Dispose(); + return true; + } + catch (RetirementPendingException) + { + return false; + } + }, 15_000) + ); } Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); @@ -1031,7 +1097,7 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() [Fact] public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() { - Guid sourceId = Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3"); + Guid sourceID = Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3"); using var fixture = new ScriptingFixture(( root, serialization @@ -1039,28 +1105,39 @@ public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() { WriteSamplePlugin(root, serialization); string package = Path.Combine(root, "Plugins", "samples.iplugin"); - using var archive = ZipFile.Open(package, ZipArchiveMode.Update); + using ZipArchive archive = ZipFile.Open(package, ZipArchiveMode.Update); archive.GetEntry("Assets/~Starter.imeta")!.Delete(); WritePluginPackageEntry( archive, "Assets/~Starter.imeta", - serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), sourceKind = (int)AssetSourceKind.Directory, importerSettingsBytes = serialization.Serialize(new SampleIdentitySettings { referenceId = sourceId }) }) + serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), + sourceKind = (int)AssetSourceKind.Directory, + importerSettingsBytes = serialization.Serialize(new SampleIdentitySettings { referenceId = sourceID }) + } + ) ); }); - using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceID("tests.samples"), "~Starter")); import.BeginValidation(( sources, _ ) => { Assert.True(sources.TryGetInfo(AssetPath.Project("~Starter/StarterBehavior.cs"), out AssetInfo? info)); - ScriptingAssetSourceMeta metadata = fixture.host.serialization.Deserialize(File.ReadAllBytes(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta"))); - SampleIdentitySettings settings = fixture.host.serialization.Deserialize(metadata.importerSettingsBytes); - Assert.Equal(info!.persistentId, settings.referenceId); - Assert.NotEqual(sourceId, settings.referenceId); + ScriptingAssetSourceMeta metadata = fixture.host.serialization.Deserialize( + File.ReadAllBytes(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta")) + ); + SampleIdentitySettings settings = fixture.host.serialization.Deserialize( + metadata.importerSettingsBytes + ); + Assert.Equal(info!.persistentID, settings.referenceId); + Assert.NotEqual(sourceID, settings.referenceId); return ValueTask.CompletedTask; }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); } @@ -1073,24 +1150,35 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() ) => { WriteSamplePlugin(root, serialization); - using var package = ZipFile.Open(Path.Combine(root, "Plugins", "samples.iplugin"), ZipArchiveMode.Update); - WritePluginPackageEntry(package, "Assets/~Starter/Slow.samplebusy", System.Text.Encoding.UTF8.GetBytes("sample")); + using ZipArchive package = ZipFile.Open(Path.Combine(root, "Plugins", "samples.iplugin"), ZipArchiveMode.Update); + WritePluginPackageEntry(package, "Assets/~Starter/Slow.samplebusy", Encoding.UTF8.GetBytes("sample")); WritePluginPackageEntry( package, "Assets/~Starter/Slow.samplebusy.imeta", - serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("587849fc-777c-4501-a1b2-ec042ca40314"), sourceKind = (int)AssetSourceKind.File, importerId = "tests.scripting.controlled-sample-asset" }) + serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("587849fc-777c-4501-a1b2-ec042ca40314"), + sourceKind = (int)AssetSourceKind.File, + importerId = "tests.scripting.controlled-sample-asset" + } + ) ); }); using var control = new ControlledSampleAssetImporter.Control(); ControlledSampleAssetImporter.current = control; - AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceID("tests.samples"), "~Starter") + ); try { - Assert.True(SpinWait.SpinUntil(() => - { - Assert.False(import.Advance()); - return control.started.IsSet; - }, 15000)); + Assert.True( + SpinWait.SpinUntil(() => + { + Assert.False(import.Advance()); + return control.started.IsSet; + }, 15_000) + ); Assert.NotEqual(Environment.CurrentManagedThreadId, control.workerThread); long revision = fixture.assets.revision; for (int frame = 0; frame < 30; frame++) @@ -1106,7 +1194,7 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() } finally { - new Inno.Core.Execution.RetirementBarrier("Test sample preimport").Wait(import.Dispose); + new RetirementBarrier("Test sample preimport").Wait(import.Dispose); ControlledSampleAssetImporter.current = null; } @@ -1119,7 +1207,7 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() public void SampleCompilerReferencePreparationRunsOnWorker() { using var fixture = new ScriptingFixture(WriteSamplePlugin); - using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceID("tests.samples"), "~Starter")); using var progress = new CompilationGate(); try { @@ -1128,7 +1216,11 @@ public void SampleCompilerReferencePreparationRunsOnWorker() cancellationToken ) => { - ScriptCompilationResult result = await fixture.compiler.CompileAuthoringGenerationAsync(progress, cancellationToken, sources).ConfigureAwait(false); + ScriptCompilationResult result = await fixture.compiler.CompileAuthoringGenerationAsync( + progress, + sources, + cancellationToken + ).ConfigureAwait(false); Assert.True(result.success, FormatDiagnostics(result)); }); Assert.True(progress.started.Wait(TimeSpan.FromSeconds(5))); @@ -1143,7 +1235,7 @@ public void SampleCompilerReferencePreparationRunsOnWorker() finally { progress.release.Set(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); } import.Commit(); @@ -1161,8 +1253,14 @@ public void SampleCompilerReferencePreparationRunsOnWorker() [InlineData(true)] public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) { - using var fixture = new ScriptingFixture(WriteSamplePlugin, enableFileSystemWatcher: true, fileWatcherFlushDelayMs: 3000); - AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using var fixture = new ScriptingFixture( + WriteSamplePlugin, + enableFileSystemWatcher: true, + fileWatcherFlushDelayMs: 3000 + ); + AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceID("tests.samples"), "~Starter") + ); try { TimeSpan maximumAdvance = TimeSpan.Zero; @@ -1171,11 +1269,16 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) Stopwatch frame = Stopwatch.StartNew(); bool ready = import.Advance(); if (frame.Elapsed > maximumAdvance) + { maximumAdvance = frame.Elapsed; + } return ready; - }, 15000); + }, 15_000); Assert.True(indexed); - Assert.True(maximumAdvance < TimeSpan.FromSeconds(2), $"Owner-thread Advance waited {maximumAdvance} with a three-second watcher quiet period."); + Assert.True( + maximumAdvance < TimeSpan.FromSeconds(2), + $"Owner-thread Advance waited {maximumAdvance} with a three-second watcher quiet period." + ); fixture.Write("External.txt", "Changed while watching was paused."); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("External.txt"), out _)); if (commit) @@ -1188,26 +1291,19 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) import.Commit(); } else - new Inno.Core.Execution.RetirementBarrier("Test canceled watched sample").Wait(import.Rollback); + { + new RetirementBarrier("Test canceled watched sample").Wait(import.Rollback); + } fixture.assets.Update(); Assert.True(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("External.txt"), out _)); Assert.Equal(commit, fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); } finally { - new Inno.Core.Execution.RetirementBarrier("Test watched sample import").Wait(import.Dispose); + new RetirementBarrier("Test watched sample import").Wait(import.Dispose); } } - private static AssetSampleImportTransaction PrepareSample( - ScriptingFixture fixture, - AssetPath source - ) { - AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(source); - Assert.True(SpinWait.SpinUntil(() => import.Advance(), 15000)); - return import; - } - [Fact] public void IdeProjectionUsesPluginMetadataReferencesWithoutExtraProjects() { @@ -1244,13 +1340,18 @@ public void SourceArtifactsAreCatalogedButRuntimeExportContainsNoSourceFiles() Assert.True(result.success, FormatDiagnostics(result)); Assert.True(m_fixture.assets.TryGetInfo(AssetPath.Project("Scripts/Tracked.cs"), out AssetInfo? info)); Assert.NotNull(info); - Assert.Equal("inno.editor.csharp-script", info.importerId); - Assert.True(m_fixture.assets.TryGetArtifact(info.persistentId, "source", out AssetArtifactInfo? source)); + Assert.Equal("inno.editor.csharp-script", info.importerID); + Assert.True(m_fixture.assets.TryGetArtifact(info.persistentID, "source", out AssetArtifactInfo? source)); Assert.NotNull(source); - using (ArtifactLease encoded = m_fixture.assets.AcquireArtifact(info.persistentId, "source")) + using (ArtifactLease encoded = m_fixture.assets.AcquireArtifact(info.persistentID, "source")) + { Assert.NotEmpty(encoded.ReadAllBytes()); + } Assert.Equal(0, exported.assetCount); - Assert.DoesNotContain(Directory.EnumerateFiles(contentRoot, "*", SearchOption.AllDirectories), static path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain( + Directory.EnumerateFiles(contentRoot, "*", SearchOption.AllDirectories), + static path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + ); } [Fact] @@ -1354,7 +1455,11 @@ public sealed class ReloadableBehavior : GameBehavior Assert.True(secondResult.success, FormatDiagnostics(secondResult)); Assert.True(reload.ApplyPendingReload()); Type currentType = m_fixture.ResolveActiveType("ReloadableBehavior"); - GameComponent current = Assert.Single(gameObject.GetComponents().Where(component => string.Equals(component.GetType().Name, "ReloadableBehavior", StringComparison.Ordinal))); + GameComponent current = Assert.Single( + gameObject + .GetComponents() + .Where(component => string.Equals(component.GetType().Name, "ReloadableBehavior", StringComparison.Ordinal)) + ); Assert.Same(currentType, current.GetType()); Assert.Equal(41, currentType.GetProperty("retained")!.GetValue(current)); Assert.Equal(2, currentType.GetProperty("added")!.GetValue(current)); @@ -1376,7 +1481,7 @@ public void RemovedOrBrokenUpdatedPluginCommitsUnavailableGenerationAndRecovers( using InnoEngine.Serialization; using UnavailabilityPlugin; - [StableTypeId("69e8df54-51f2-40fd-9b47-c4ebdf18052e")] + [StableTypeID("69e8df54-51f2-40fd-9b47-c4ebdf18052e")] public sealed class DependentBehavior : GameBehavior { [SerializableProperty] @@ -1404,7 +1509,11 @@ public sealed class DependentBehavior : GameBehavior { if (updateInPlace) { - WriteUnavailableGenerationPlugin(fixture.projectRoot, fixture.host.serialization, "this Plugin update is deliberately invalid C#"); + WriteUnavailableGenerationPlugin( + fixture.projectRoot, + fixture.host.serialization, + "this Plugin update is deliberately invalid C#" + ); } else { @@ -1416,19 +1525,30 @@ public sealed class DependentBehavior : GameBehavior Assert.False(unavailable.success); Assert.Contains(unavailable.diagnostics, static diagnostic => diagnostic.severity == DiagnosticSeverity.Error); Assert.True(reload.ApplyPendingReload()); - Assert.DoesNotContain(fixture.host.modules.modules, static module => module.domain is AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting); + Assert.DoesNotContain( + fixture.host.modules.modules, + static module => module.domain is AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting + ); Assert.Equal(updateInPlace ? 1 : 0, fixture.activePlugins.Count); - MissingGameComponent missingPlugin = Assert.IsType(state.pluginOwner.GetComponents().Single(component => component is not Transform)); - MissingGameComponent missingScript = Assert.IsType(state.scriptOwner.GetComponents().Single(component => component is not Transform)); - Assert.Equal(state.pluginComponentId, missingPlugin.identity.persistentId); - Assert.Equal(state.scriptComponentId, missingScript.identity.persistentId); + MissingGameComponent missingPlugin = Assert.IsType( + state.pluginOwner.GetComponents().Single(component => component is not Transform) + ); + MissingGameComponent missingScript = Assert.IsType( + state.scriptOwner.GetComponents().Single(component => component is not Transform) + ); + Assert.Equal(state.pluginComponentID, missingPlugin.identity.persistentID); + Assert.Equal(state.scriptComponentID, missingScript.identity.persistentID); Assert.Equal("UnavailabilityPlugin.PluginBehavior", missingPlugin.missingTypeName); Assert.Equal("DependentBehavior", missingScript.missingTypeName); CompleteUnloadVerification(reload); if (updateInPlace) + { File.WriteAllBytes(installedPlugin, validPluginPackage); + } else + { File.Move(detachedPlugin, installedPlugin); + } Assert.True(fixture.RefreshPlugins()); ScriptCompilationResult recoveredCompilation = fixture.CompilePendingPluginReload(reload); Assert.True(recoveredCompilation.success, FormatDiagnostics(recoveredCompilation)); @@ -1439,19 +1559,6 @@ public sealed class DependentBehavior : GameBehavior } } - [MethodImpl(MethodImplOptions.NoInlining)] - private static void AssertRecoveredAvailability(AvailabilitySceneState state) - { - GameComponent recoveredPlugin = state.pluginOwner.GetComponents().Single(component => component is not Transform); - GameComponent recoveredScript = state.scriptOwner.GetComponents().Single(component => component is not Transform); - Assert.IsNotType(recoveredPlugin); - Assert.IsNotType(recoveredScript); - Assert.Equal(state.pluginComponentId, recoveredPlugin.identity.persistentId); - Assert.Equal(state.scriptComponentId, recoveredScript.identity.persistentId); - Assert.Equal(47, recoveredPlugin.GetType().GetProperty("retained")!.GetValue(recoveredPlugin)); - Assert.Equal(73, recoveredScript.GetType().GetProperty("retained")!.GetValue(recoveredScript)); - } - [Fact] public void NeutralSettingsCacheDoesNotPinRetiredScriptTypesWithoutAnExplicitRebuild() { @@ -1466,7 +1573,7 @@ public void NeutralSettingsCacheDoesNotPinRetiredScriptTypesWithoutAnExplicitReb new FileByteDocumentStore(Path.GetFullPath(Path.Combine(fixture.projectRoot, "DetachedSettings.inno"))), fixture.host.types, fixture.host.serialization, - new ProjectId("tests.detached.settings"), + new ProjectID("tests.detached.settings"), AssetSerializationContext.Create(fixture.assets) ); WeakReference previousType = CaptureCachedSettingType(detachedSettings); @@ -1478,27 +1585,17 @@ public void NeutralSettingsCacheDoesNotPinRetiredScriptTypesWithoutAnExplicitReb Assert.False(previousType.IsAlive, "A neutral settings cache must not retain the old script type."); Assert.True(CaptureCachedSettingType(detachedSettings).IsAlive); void WriteSetting(int value) - { - fixture.Write("DetachedSetting.cs", $$""" + => fixture.Write("DetachedSetting.cs", $$""" using InnoEngine.Reflection; using InnoEngine.Serialization; using InnoEngine.Settings; - [StableTypeId("109af64a-a07e-4f84-8b86-7b06a0bce526")] + [StableTypeID("109af64a-a07e-4f84-8b86-7b06a0bce526")] [ProjectSettingDefinition("tests.detached.setting")] public sealed class DetachedSetting : ISerializable { [SerializableProperty] public int value { get; set; } = {{value}}; } """); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static WeakReference CaptureCachedSettingType(ProjectSettingsStore settings) - { - Assert.True(settings.TryClone(new ProjectSettingId("tests.detached.setting"), out ISerializable? value)); - Assert.NotNull(value); - return new WeakReference(value.GetType()); } [Fact] @@ -1537,8 +1634,10 @@ public void PluginRemovalUnloadsTheCommittedMissingGenerationWithoutASecondReloa Assert.False(expectation.retiredComponent.IsAlive, "The retired Plugin component remained strongly reachable."); Assert.False(expectation.retiredType.IsAlive, "The retired Plugin runtime Type remained strongly reachable."); Assert.DoesNotContain(fixture.host.modules.modules, static module => module.domain == AssemblyDomain.InnoPlugin); - MissingGameComponent missing = Assert.IsType(expectation.owner.GetComponents().Single(component => component is not Transform)); - Assert.Equal(expectation.componentId, missing.identity.persistentId); + MissingGameComponent missing = Assert.IsType( + expectation.owner.GetComponents().Single(component => component is not Transform) + ); + Assert.Equal(expectation.componentID, missing.identity.persistentID); Assert.Equal("UnavailabilityPlugin.PluginBehavior", missing.missingTypeName); } @@ -1557,10 +1656,13 @@ public void PluginReloadWaitsForPlaySessionRetirementBeforeActivatingItsAssembly var history = new CountingHistoryIsolation(); using var playMode = new EditorPlayModeController( fixture.host, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, - applicationId = "tests.scripting.play-reload", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.scripting.play-reload"), "Logs")), + applicationID = "tests.scripting.play-reload", + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.scripting.play-reload"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, referenceResolvers = [fixture.assets] }, @@ -1621,7 +1723,7 @@ public void ShutdownPreservesLoadedScriptAssetAsMissingUntilItsTypeReturns() using InnoEngine.Assets; using InnoEngine.Reflection; - [StableTypeId("527df6c8-1373-48c9-9230-805a85590544")] + [StableTypeID("527df6c8-1373-48c9-9230-805a85590544")] public sealed class ShutdownAsset : AssetObject { } @@ -1649,32 +1751,20 @@ protected override async ValueTask ImportAsync( } """); fixture.Write("Content/value.shutdownasset", "last-good"); - (Guid persistentId, Guid stableTypeId) = LoadScriptAssetAndUnloadScripts(fixture); + (Guid persistentID, Guid stableTypeID) = LoadScriptAssetAndUnloadScripts(fixture); Assert.Empty(fixture.host.modules.modules); - Assert.True(fixture.assets.TryGetInfo(persistentId, out AssetInfo? preserved)); + Assert.True(fixture.assets.TryGetInfo(persistentID, out AssetInfo? preserved)); Assert.Equal(AssetImportStatus.Imported, preserved!.status); - Assert.Equal(stableTypeId, preserved.stableAssetTypeId); - AssetObject missing = ((IAssetReferenceResolver)fixture.assets).Resolve(persistentId, stableTypeId, "Content/value.shutdownasset", typeof(AssetObject), "$test"); + Assert.Equal(stableTypeID, preserved.stableAssetTypeID); + AssetObject missing = ((IAssetReferenceResolver)fixture.assets).Resolve( + persistentID, + stableTypeID, + "Content/value.shutdownasset", + typeof(AssetObject), + "$test" + ); Assert.True(missing.isMissing); - Assert.Equal(persistentId, missing.identity.persistentId); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static (Guid persistentId, Guid stableTypeId) LoadScriptAssetAndUnloadScripts(ScriptingFixture fixture) - { - using ScriptReloadHost reload = fixture.CreateReloadHost(new EditorReloadCoordinator()); - reload.Start(); - ScriptCompilationResult compilation = fixture.CompilePending(reload); - Assert.True(compilation.success, FormatDiagnostics(compilation)); - Assert.True(reload.ApplyPendingReload()); - Type assetType = fixture.ResolveActiveType("ShutdownAsset"); - AssetObject loaded = fixture.assets.Load(AssetPath.Project("Content/value.shutdownasset"), assetType); - Assert.True(fixture.assets.TryGetInfo(loaded.identity.persistentId, out AssetInfo? imported)); - Assert.Equal(AssetImportStatus.Imported, imported!.status); - Guid persistentId = loaded.identity.persistentId; - Guid stableTypeId = imported.stableAssetTypeId; - reload.Dispose(); - return (persistentId, stableTypeId); + Assert.Equal(persistentID, missing.identity.persistentID); } [Fact] @@ -1692,10 +1782,13 @@ public void ContentPlayStopReloadPlaySoakRetiresEverySessionBeforeTheNextGenerat var history = new CountingHistoryIsolation(); using var play = new EditorPlayModeController( fixture.host, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, - applicationId = "tests.content-soak", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.content-soak"), "Logs")), + applicationID = "tests.content-soak", + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.content-soak"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, referenceResolvers = [fixture.assets] }, @@ -1712,7 +1805,9 @@ public void ContentPlayStopReloadPlaySoakRetiresEverySessionBeforeTheNextGenerat play.AdvanceTransition(); Assert.True(play.state == EditorPlayModeState.Playing, play.lastFailure); for (int frame = 0; frame < 60; frame++) + { play.Tick(1f / 60f); + } Assert.True(play.ExitPlayMode()); play.AdvanceTransition(); play.AdvanceTransition(); @@ -1739,7 +1834,10 @@ public void AutomaticPublicationDoesNotQueueItselfButExternalMountChangesStillDo reload.Start(); Assert.True(m_fixture.CompilePending(reload).success); Assert.True(reload.ApplyPendingReload()); - Assert.False(reload.isCompilationPending, "Publishing this script generation must not queue another generation from its own catalog notification."); + Assert.False( + reload.isCompilationPending, + "Publishing this script generation must not queue another generation from its own catalog notification." + ); CompleteUnloadVerification(reload); m_fixture.assets.ReplaceSourceMounts(m_fixture.assets.sourceMounts); Assert.True(reload.isCompilationPending, "An external source-mount publication must still invalidate scripting inputs."); @@ -1770,13 +1868,24 @@ public void EditorAutomaticCompilationClosesModalAndTicketWaitsForRetirement() m_fixture.WriteVersionedBehavior(2); m_fixture.Rescan(); IScriptCompilationTicket ticket = scripting.RequestCompilation(); - PumpEditorUntil(m_fixture, runtime, () => m_fixture.host.modules.generations.state == GenerationState.AwaitingCollection, () => scripting.progress.status); + PumpEditorUntil( + m_fixture, + runtime, + () => m_fixture.host.modules.generations.state == GenerationState.AwaitingCollection, + () => scripting.progress.status + ); Assert.Equal(ScriptCompilationTicketState.Compiling, ticket.state); Assert.False(ticket.isCompleted); retained.Clear(); // Publication readiness may be advanced by another host boundary before the next editor update. m_fixture.host.modules.generations.Wait(); - PumpEditorUntil(m_fixture, runtime, () => scripting.state == EditorScriptCompilationState.Ready && ticket.isCompleted, () => scripting.progress.status, focused: false); + PumpEditorUntil( + m_fixture, + runtime, + () => scripting.state == EditorScriptCompilationState.Ready && ticket.isCompleted, + () => scripting.progress.status, + focused: false + ); Assert.Equal(ScriptCompilationTicketState.Succeeded, ticket.state); AssertCompilationModalHidden(runtime); Assert.Equal(2, ReadVersion(m_fixture.ResolveActiveType("VersionedBehavior"))); @@ -1802,7 +1911,7 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile runtime, () => scripting.state == EditorScriptCompilationState.Ready, () => $"{scripting.state}: {scripting.progress.status}; ticket={scripting.currentTicket?.state}", - timeoutMilliseconds: 120000 + timeoutMilliseconds: 120_000 ); ScriptCompilationResult initial = Assert.IsType(scripting.lastCompilation); IScriptCompilationTicket? accepted = scripting.currentTicket; @@ -1820,7 +1929,9 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile { fixture.assets.Update(); using (fixture.editorSession.EnterExecutionScope()) + { runtime.Update(new EditorFrame(1f / 60f, frame / 60f, true)); + } Thread.Sleep(5); } @@ -1836,35 +1947,127 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile runtime, () => scripting.state == EditorScriptCompilationState.Ready && !ReferenceEquals(initial, scripting.lastCompilation), () => $"{scripting.state}: {scripting.progress.status}; ticket={scripting.currentTicket?.state}", - timeoutMilliseconds: 120000 + timeoutMilliseconds: 120_000 ); Assert.Equal(GenerationState.Ready, fixture.host.generations.state); Assert.Equal(3, ReadLatestVersion(fixture)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private static int ReadLatestVersion(ScriptingFixture fixture) => ReadVersion(fixture.ResolveActiveType("VersionedBehavior")); - private sealed class DeferredReloadGuard : IEditorReloadGuard + [Fact] + public void NewCompilationTicketSupersedesTheExactPreviousRequest() { - internal bool isBlocked { get; set; } = true; - public bool canRequestReload => !isBlocked; - public bool canActivateReload => !isBlocked; - public string? blockingReason => isBlocked ? "Waiting for fixture active Play to retire." : null; + using EditorInteractionRuntime runtime = m_fixture.CreateEditorRuntime(); + runtime.Start(); + _ = runtime.panelCount; + IEditorScriptCompilation scripting = Assert.IsAssignableFrom(ScriptingCompilationProbe.compilation); + IScriptCompilationTicket first = scripting.RequestCompilation(); + IScriptCompilationTicket second = scripting.RequestCompilation(); + Assert.Equal(ScriptCompilationTicketState.Superseded, first.state); + Assert.True(first.isCompleted); + Assert.True(second.requestID > first.requestID); + Assert.Same(second, scripting.currentTicket); + Assert.Equal(ScriptCompilationTicketState.Queued, second.state); + } + + [Fact] + public void FailedResultHasNoActivationOrRuntimeArtifacts() + { + ScriptCompilationResult result = ScriptCompilationResult.Failure( + new ScriptDiagnostic("INNO-TEST", DiagnosticSeverity.Error, "Injected compilation failure.", filePath: null, line: 0, column: 0) + ); + Assert.False(result.success); + Assert.Null(result.outputDirectory); + Assert.Empty(result.moduleDeployments); + Assert.Empty(result.runtimeAssemblyPaths); + Assert.Empty(result.compiledAssemblyNames); + Assert.Empty(result.reusedAssemblyNames); } [MethodImpl(MethodImplOptions.NoInlining)] - private static List RetainActiveScriptType(ScriptingFixture fixture) => [fixture.ResolveActiveType("VersionedBehavior")]; - private static void AssertCompilationModalHidden(EditorInteractionRuntime runtime) + private static AssetPath InvokePublicPathProbe(string assemblyPath) { - EditorModalExtension modal = runtime.modals.Single(value => value.id == "scripting.compilation"); - Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); - Assert.False(presentation.isVisible); + var lifetime = new AssemblyLoadContext("source-local-path-test", isCollectible: true); + try + { + using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); + Assembly assembly = lifetime.LoadFromStream(stream); + Func resolve = assembly.GetType("SourceLocalPathProbe", throwOnError: true)!.GetMethod( + "Resolve", + BindingFlags.Public | BindingFlags.Static + )!.CreateDelegate>(); + return resolve(); + } + finally + { + lifetime.Unload(); + } } - private static void WaitForInitialScriptCompilation( + private static AssetSampleImportTransaction PrepareSample( ScriptingFixture fixture, - EditorInteractionRuntime runtime, - IEditorScriptCompilation scripting + AssetPath source + ) { + AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(source); + Assert.True(SpinWait.SpinUntil(() => import.Advance(), 15_000)); + return import; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void AssertRecoveredAvailability(AvailabilitySceneState state) + { + GameComponent recoveredPlugin = state.pluginOwner.GetComponents().Single(component => component is not Transform); + GameComponent recoveredScript = state.scriptOwner.GetComponents().Single(component => component is not Transform); + Assert.IsNotType(recoveredPlugin); + Assert.IsNotType(recoveredScript); + Assert.Equal(state.pluginComponentID, recoveredPlugin.identity.persistentID); + Assert.Equal(state.scriptComponentID, recoveredScript.identity.persistentID); + Assert.Equal(47, recoveredPlugin.GetType().GetProperty("retained")!.GetValue(recoveredPlugin)); + Assert.Equal(73, recoveredScript.GetType().GetProperty("retained")!.GetValue(recoveredScript)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference CaptureCachedSettingType(ProjectSettingsStore settings) + { + Assert.True(settings.TryClone(new ProjectSettingID("tests.detached.setting"), out ISerializable? value)); + Assert.NotNull(value); + return new WeakReference(value.GetType()); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static (Guid persistentID, Guid stableTypeID) LoadScriptAssetAndUnloadScripts(ScriptingFixture fixture) + { + using ScriptReloadHost reload = fixture.CreateReloadHost(new EditorReloadCoordinator()); + reload.Start(); + ScriptCompilationResult compilation = fixture.CompilePending(reload); + Assert.True(compilation.success, FormatDiagnostics(compilation)); + Assert.True(reload.ApplyPendingReload()); + Type assetType = fixture.ResolveActiveType("ShutdownAsset"); + AssetObject loaded = fixture.assets.Load(AssetPath.Project("Content/value.shutdownasset"), assetType); + Assert.True(fixture.assets.TryGetInfo(loaded.identity.persistentID, out AssetInfo? imported)); + Assert.Equal(AssetImportStatus.Imported, imported!.status); + Guid persistentID = loaded.identity.persistentID; + Guid stableTypeID = imported.stableAssetTypeID; + reload.Dispose(); + return (persistentID, stableTypeID); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int ReadLatestVersion(ScriptingFixture fixture) => ReadVersion(fixture.ResolveActiveType("VersionedBehavior")); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static List RetainActiveScriptType(ScriptingFixture fixture) => [fixture.ResolveActiveType("VersionedBehavior")]; + + private static void AssertCompilationModalHidden(EditorInteractionRuntime runtime) + { + EditorModalExtension modal = runtime.modals.Single(value => value.id == "scripting.compilation"); + Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); + Assert.False(presentation.isVisible); + } + + private static void WaitForInitialScriptCompilation( + ScriptingFixture fixture, + EditorInteractionRuntime runtime, + IEditorScriptCompilation scripting ) { // Startup compiles the sample and activates its generation before the import can begin. PumpEditorUntil( @@ -1872,7 +2075,7 @@ IEditorScriptCompilation scripting runtime, () => scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed, DescribeCompilation, - timeoutMilliseconds: 60000 + timeoutMilliseconds: 60_000 ); Assert.True(scripting.state == EditorScriptCompilationState.Ready, DescribeCompilation()); @@ -1889,7 +2092,7 @@ private static void PumpEditorUntil( Func completed, Func status, bool focused = true, - int timeoutMilliseconds = 15000 + int timeoutMilliseconds = 15_000 ) { long started = Environment.TickCount64; int frame = 0; @@ -1898,39 +2101,13 @@ private static void PumpEditorUntil( Assert.True(Environment.TickCount64 - started < timeoutMilliseconds, status()); fixture.assets.Update(); using (fixture.editorSession.EnterExecutionScope()) + { runtime.Update(new EditorFrame(1f / 60f, frame++ / 60f, focused)); + } Thread.Sleep(5); } } - [Fact] - public void NewCompilationTicketSupersedesTheExactPreviousRequest() - { - using EditorInteractionRuntime runtime = m_fixture.CreateEditorRuntime(); - runtime.Start(); - _ = runtime.panelCount; - IEditorScriptCompilation scripting = Assert.IsAssignableFrom(ScriptingCompilationProbe.compilation); - IScriptCompilationTicket first = scripting.RequestCompilation(); - IScriptCompilationTicket second = scripting.RequestCompilation(); - Assert.Equal(ScriptCompilationTicketState.Superseded, first.state); - Assert.True(first.isCompleted); - Assert.True(second.requestId > first.requestId); - Assert.Same(second, scripting.currentTicket); - Assert.Equal(ScriptCompilationTicketState.Queued, second.state); - } - - [Fact] - public void FailedResultHasNoActivationOrRuntimeArtifacts() - { - ScriptCompilationResult result = ScriptCompilationResult.Failure(new ScriptDiagnostic("INNO-TEST", DiagnosticSeverity.Error, "Injected compilation failure.", filePath: null, line: 0, column: 0)); - Assert.False(result.success); - Assert.Null(result.outputDirectory); - Assert.Empty(result.moduleDeployments); - Assert.Empty(result.runtimeAssemblyPaths); - Assert.Empty(result.compiledAssemblyNames); - Assert.Empty(result.reusedAssemblyNames); - } - private static int ReadVersion(Type type) => (int)type.GetProperty("version")!.GetValue(Activator.CreateInstance(type))!; [MethodImpl(MethodImplOptions.NoInlining)] @@ -1979,14 +2156,21 @@ GameScene scene GameComponent scriptComponent = scriptOwner.AddComponent(scriptType); pluginType.GetProperty("retained")!.SetValue(pluginComponent, 47); scriptType.GetProperty("retained")!.SetValue(scriptComponent, 73); - return new AvailabilitySceneState(pluginOwner, scriptOwner, pluginComponent.identity.persistentId, scriptComponent.identity.persistentId); + return new AvailabilitySceneState( + pluginOwner, + scriptOwner, + pluginComponent.identity.persistentID, + scriptComponent.identity.persistentID + ); } private static void CompleteUnloadVerification(ScriptReloadHost reload) { Exception? failure = null; while (!reload.AdvanceUnloadVerification(out failure)) + { Thread.Yield(); + } Assert.Null(failure); } @@ -2000,7 +2184,7 @@ RuntimeSession session GameObject owner = scene.CreateObject("Plugin Owner"); Type pluginType = fixture.ResolveActiveType("PluginBehavior"); GameComponent component = owner.AddComponent(pluginType); - Guid componentId = component.identity.persistentId; + Guid componentID = component.identity.persistentID; string installedPlugin = Path.Combine(fixture.projectRoot, "Plugins", "unavailability.iplugin"); string detachedPlugin = Path.Combine(fixture.projectRoot, "UnavailabilityPlugin.detached"); File.Move(installedPlugin, detachedPlugin); @@ -2015,9 +2199,12 @@ RuntimeSession session Assert.True(reload.ApplyPendingReload()); Assert.DoesNotContain( fixture.host.modules.modules, - static module => module.domain == AssemblyDomain.InnoPlugin || module.upstreamModuleNames.Contains("Plugin.tests.unavailability", StringComparer.Ordinal) + static module => ( + module.domain == AssemblyDomain.InnoPlugin + || module.upstreamModuleNames.Contains("Plugin.tests.unavailability", StringComparer.Ordinal) + ) ); - return new MissingGenerationExpectation(owner, componentId, new WeakReference(component), new WeakReference(pluginType)); + return new MissingGenerationExpectation(owner, componentID, new WeakReference(component), new WeakReference(pluginType)); } private static void ForceFullCollection() @@ -2027,27 +2214,11 @@ private static void ForceFullCollection() GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); } - private readonly record struct MissingGenerationExpectation( - GameObject owner, - Guid componentId, - WeakReference retiredComponent, - WeakReference retiredType - ); - private readonly record struct RetiredScriptObject( - WeakReference type, - WeakReference component - ); - private readonly record struct AvailabilitySceneState( - GameObject pluginOwner, - GameObject scriptOwner, - Guid pluginComponentId, - Guid scriptComponentId - ); private static void WriteProjectionPlugin( string projectRoot, SerializationRegistry serialization ) { - const string c_source = """ + const string C_SOURCE = """ using InnoEngine.Scene; namespace ProjectionPlugin; @@ -2061,8 +2232,9 @@ public sealed class ProjectionRuntime : GameBehavior "projection.iplugin", serialization, new PluginManifest { pluginId = "tests.projection", displayName = "Projection Plugin" }, - new Dictionary { - ["Assets/ProjectionRuntime.cs"] = System.Text.Encoding.UTF8.GetBytes(c_source), + new Dictionary + { + ["Assets/ProjectionRuntime.cs"] = Encoding.UTF8.GetBytes(C_SOURCE), ["Assets/ProjectionRuntime.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) } ); @@ -2078,62 +2250,83 @@ SerializationRegistry serialization namespace UnavailabilityPlugin; - [StableTypeId("a7b5f773-184f-4bd1-bf93-e4b1088d9d68")] + [StableTypeID("a7b5f773-184f-4bd1-bf93-e4b1088d9d68")] public sealed class PluginBehavior : GameBehavior { [SerializableProperty] public int retained { get; set; } = 5; } """); + private static void WriteUnavailableGenerationPlugin( string projectRoot, SerializationRegistry serialization, string source - ) { - WritePluginPackage( - projectRoot, - "unavailability.iplugin", - serialization, - new PluginManifest { pluginId = "tests.unavailability", displayName = "Unavailability Test Plugin" }, - new Dictionary { - ["Assets/PluginBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49")) - } - ); - } + ) => WritePluginPackage( + projectRoot, + "unavailability.iplugin", + serialization, + new PluginManifest { pluginId = "tests.unavailability", displayName = "Unavailability Test Plugin" }, + new Dictionary + { + ["Assets/PluginBehavior.cs"] = Encoding.UTF8.GetBytes(source), + ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49") + ) + } + ); private static void WriteSamplePlugin( string projectRoot, SerializationRegistry serialization ) { - const string c_source = "using InnoEngine.Reflection; using InnoEngine.Scene; " + "[StableTypeId(\"ce3b52c6-2a07-42ea-b632-a307a0ef7407\")] " + "public sealed class StarterBehavior : GameBehavior { }"; - WriteSamplePlugin(projectRoot, serialization, c_source); + const string C_SOURCE = "using InnoEngine.Reflection; using InnoEngine.Scene; " + + "[StableTypeID(\"ce3b52c6-2a07-42ea-b632-a307a0ef7407\")] " + + "public sealed class StarterBehavior : GameBehavior { }"; + WriteSamplePlugin(projectRoot, serialization, C_SOURCE); } private static void WriteSamplePlugin( string projectRoot, SerializationRegistry serialization, string source - ) { - WritePluginPackage( - projectRoot, - "samples.iplugin", - serialization, - new PluginManifest { pluginId = "tests.samples", displayName = "Sample Test Plugin" }, - new Dictionary { - ["Assets/"] = [], - ["Assets/~Starter/"] = [], - ["Assets/~Starter.imeta"] = serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), sourceKind = (int)AssetSourceKind.Directory }), - ["Assets/~Starter/StarterBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3")) - } - ); - } + ) => WritePluginPackage( + projectRoot, + "samples.iplugin", + serialization, + new PluginManifest { pluginId = "tests.samples", displayName = "Sample Test Plugin" }, + new Dictionary + { + ["Assets/"] = [], + ["Assets/~Starter/"] = [], + ["Assets/~Starter.imeta"] = serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), + sourceKind = (int)AssetSourceKind.Directory + } + ), + ["Assets/~Starter/StarterBehavior.cs"] = Encoding.UTF8.GetBytes(source), + ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3") + ) + } + ); private static byte[] CreateScriptSourceMeta( SerializationRegistry serialization, - Guid persistentId - ) => serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = persistentId, sourceKind = (int)AssetSourceKind.File, importerId = "inno.editor.csharp-script" }); + Guid persistentID + ) => serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = persistentID, + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.editor.csharp-script" + } + ); + private static void WritePluginPackage( string projectRoot, string fileName, @@ -2146,7 +2339,9 @@ IReadOnlyDictionary entries using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WritePluginPackageEntry(archive, "Plugin.inno", serialization.Serialize(manifest)); foreach ((string entryPath, byte[] bytes)in entries) + { WritePluginPackageEntry(archive, entryPath, bytes); + } } private static void WritePluginPackageEntry( @@ -2156,15 +2351,19 @@ byte[] bytes ) { ZipArchiveEntry entry = archive.CreateEntry(path, CompressionLevel.Optimal); if (path.EndsWith("/", StringComparison.Ordinal)) + { return; + } using Stream output = entry.Open(); output.Write(bytes); } - private static string FormatDiagnostics(ScriptCompilationResult result) => string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") - ); + private static string FormatDiagnostics(ScriptCompilationResult result) + => string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") + ); + private static bool ContainsCustomAttribute( string assemblyPath, string attributeTypeName @@ -2178,11 +2377,17 @@ string attributeTypeName string? typeName = attribute.Constructor.Kind switch { HandleKind.MemberReference => GetMemberReferenceDeclaringTypeName(metadata, (MemberReferenceHandle)attribute.Constructor), - HandleKind.MethodDefinition => metadata.GetString(metadata.GetTypeDefinition(metadata.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor).GetDeclaringType()).Name), + HandleKind.MethodDefinition => metadata.GetString( + metadata.GetTypeDefinition( + metadata.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor).GetDeclaringType() + ).Name + ), _ => null }; if (string.Equals(typeName, attributeTypeName, StringComparison.Ordinal)) + { return true; + } } return false; @@ -2201,12 +2406,36 @@ MemberReferenceHandle constructorHandle }; } - private sealed class CompilationGate : IProgress, IDisposable + private sealed class DeferredReloadGuard : IEditorReloadGuard { - internal ManualResetEventSlim started { get; } = new(); - internal ManualResetEventSlim release { get; } = new(); - internal int workerThread { get; private set; } + public bool canRequestReload => !isBlocked; + public bool canActivateReload => !isBlocked; + public string? blockingReason => isBlocked ? "Waiting for fixture active Play to retire." : null; + + internal bool isBlocked { get; set; } = true; + } + + private readonly record struct MissingGenerationExpectation( + GameObject owner, + Guid componentID, + WeakReference retiredComponent, + WeakReference retiredType + ); + private readonly record struct RetiredScriptObject( + WeakReference type, + WeakReference component + ); + + private readonly record struct AvailabilitySceneState( + GameObject pluginOwner, + GameObject scriptOwner, + Guid pluginComponentID, + Guid scriptComponentID + ); + + private sealed class CompilationGate : IProgress, IDisposable + { /// /// Suspends reference preparation to verify that no Editor frame waits for the compiler. /// @@ -2216,11 +2445,15 @@ private sealed class CompilationGate : IProgress, IDi public void Report(ScriptCompilationProgress value) { if (value.stage != "Building the script API profile...") + { return; + } workerThread = Environment.CurrentManagedThreadId; started.Set(); if (!release.Wait(TimeSpan.FromSeconds(15))) + { throw new TimeoutException("The test-owned compilation gate was not released."); + } } /// @@ -2231,19 +2464,21 @@ public void Dispose() started.Dispose(); release.Dispose(); } + + internal ManualResetEventSlim started { get; } = new(); + internal ManualResetEventSlim release { get; } = new(); + internal int workerThread { get; private set; } } private sealed class ProgressRecorder : IProgress { - internal List values { get; } = []; - public void Report(ScriptCompilationProgress value) => values.Add(value); + + internal List values { get; } = []; } private sealed class PluginPlayScene(ScriptingFixture fixture) : IEditorScenePlayMode { - internal int restoreCount { get; private set; } - public IDisposable BeginPlayMode(RuntimeSession runtimeSession) { var scene = new GameScene("Plugin Play Reload"); @@ -2253,13 +2488,18 @@ public IDisposable BeginPlayMode(RuntimeSession runtimeSession) return new RestoreLease(this); } + internal int restoreCount { get; private set; } + private sealed class RestoreLease(PluginPlayScene owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.restoreCount++; } @@ -2268,16 +2508,20 @@ public void Dispose() private sealed class CountingHistoryIsolation : IEditorHistoryIsolation { + public IDisposable BeginHistoryIsolation() => new HistoryLease(this); + internal int disposeCount { get; private set; } - public IDisposable BeginHistoryIsolation() => new HistoryLease(this); private sealed class HistoryLease(CountingHistoryIsolation owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.disposeCount++; } @@ -2286,22 +2530,22 @@ public void Dispose() private sealed class ReadyScriptCompilation : IEditorScriptCompilation { + private readonly ReadyCompilationTicket m_ticket = new(); + public bool requiresExclusiveProgress => false; public EditorScriptCompilationProgress progress => new(0, 0f, "Test script status.", false); - public void CancelCompilation(long operationId) - { - } - - private readonly ReadyCompilationTicket m_ticket = new(); - public IScriptCompilationTicket RequestCompilation() => m_ticket; public IScriptCompilationTicket? currentTicket => m_ticket; public EditorScriptCompilationState state => EditorScriptCompilationState.Ready; public ScriptCompilationResult? lastCompilation => null; + public void CancelCompilation(long operationID) {} + + public IScriptCompilationTicket RequestCompilation() => m_ticket; + private sealed class ReadyCompilationTicket : IScriptCompilationTicket { - public long requestId => 1; + public long requestID => 1; public ScriptCompilationTicketState state => ScriptCompilationTicketState.Succeeded; public string status => "The test compilation ticket succeeded."; public ScriptCompilationResult? result => null; @@ -2311,296 +2555,22 @@ private sealed class ReadyCompilationTicket : IScriptCompilationTicket private sealed class TestSceneReloadParticipant(SceneReloadService reload) : IEditorReloadParticipant { - public IGenerationChange Capture(AssemblyReloadContext context) => new TestSceneReloadTransaction(reload.Capture(context.GetContext())); - public void RefreshDiagnostics() - { - } + public IGenerationChange Capture(AssemblyReloadContext context) + => new TestSceneReloadTransaction(reload.Capture(context.GetContext())); + + public void RefreshDiagnostics() {} } private sealed class TestSceneReloadTransaction(ISceneReloadStateTransfer transfer) : IGenerationChange { public void PrepareForActivation() => transfer.PrepareForActivation(); - public void Apply() => transfer.Apply(); - public void Complete() => transfer.Complete(); - public void RollbackStructure() => transfer.RollbackStructure(); - public void RestorePreviousState() => transfer.RestorePreviousState(); - } -} -internal sealed class ScriptingFixture : IDisposable -{ - private readonly IdentityAllocator m_identities = new(); - private readonly IDisposable m_diagnosticScope; - private readonly IDisposable m_identityScope; - private readonly ProjectSettingsStore m_settings; - private readonly PluginEnvironment m_plugins; - private RuntimeSession? m_editorSession; - private bool m_disposed; - internal ScriptingFixture( - Action? configureProject = null, - bool enableFileSystemWatcher = false, - int fileWatcherFlushDelayMs = 100 - ) { - projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); - string assetRoot = Path.Combine(projectRoot, "Assets"); - string pluginRoot = Path.Combine(projectRoot, "Plugins"); - string libraryRoot = Path.Combine(projectRoot, "Library"); - Directory.CreateDirectory(assetRoot); - Directory.CreateDirectory(pluginRoot); - Directory.CreateDirectory(libraryRoot); - m_identityScope = m_identities.EnterScope(); - host = new EngineHostBuilder().UseMetadataSources( - new DotNetAssemblyCatalogSource(typeof(ScriptingPipelineTests).Assembly), - new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource() - ).Build(); - m_diagnosticScope = host.diagnostics.EnterScope(); - configureProject?.Invoke(projectRoot, host.serialization); - var pluginSources = new PluginSourceService(host.serialization, pluginRoot, libraryRoot); - PluginScanResult scan = pluginSources.Scan(); - AssetPipelineOptions options = AssetPipelineOptions.Create(assetRoot, libraryRoot); - assets = new AssetPipeline( - host.modules, - host.types, - host.serialization, - m_identities, - host.diagnostics, - host.logs, - options with { - enableFileSystemWatcher = enableFileSystemWatcher, - fileWatcherFlushDelayMs = fileWatcherFlushDelayMs, - sourceMounts = [..options.sourceMounts!, ..PluginSourceService.GetActivatableMounts(scan)] - } - ); - m_settings = new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), - host.types, - host.serialization, - new ProjectId("tests.scripting"), - AssetSerializationContext.Create(assets) - ); - m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); - string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - compiler = new ScriptCompiler( - new ScriptCompilerOptions - { - projectRootDirectory = projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) - }, assets, m_plugins); - } - - internal string projectRoot { get; } - internal EngineHost host { get; } - internal AssetPipeline assets { get; } - internal ScriptCompiler compiler { get; } - internal IReadOnlyList activePlugins => m_plugins.activePlugins; - internal RuntimeSession editorSession => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); - - internal void Write( - string relativePath, - string source - ) { - string path = Path.Combine(projectRoot, "Assets", relativePath); - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, source); - } - - internal void Move( - string sourceRelativePath, - string destinationRelativePath - ) { - string source = Path.Combine(projectRoot, "Assets", sourceRelativePath); - string destination = Path.Combine(projectRoot, "Assets", destinationRelativePath); - Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - File.Move(source, destination); - string sourceMetadata = source + ".imeta"; - if (File.Exists(sourceMetadata)) - File.Move(sourceMetadata, destination + ".imeta"); - } - - internal void WriteVersionedBehavior(int version) => Write("VersionedBehavior.cs", $$""" - using InnoEngine.Scene; - - public sealed class VersionedBehavior : GameBehavior - { - public int version => {{version}}; - } - """); - internal void Rescan() => assets.Rescan(); - internal ScriptCompilationResult Compile( - IProgress? progress = null, - CancellationToken cancellationToken = default - ) { - Rescan(); - return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken).GetAwaiter().GetResult(); - } - - internal ScriptCompilationResult CompileRuntimeDeployment( - string? targetRuntimeDirectory = null, - IProgress? progress = null, - CancellationToken cancellationToken = default - ) { - Rescan(); - return compiler.CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken).GetAwaiter().GetResult(); - } - - internal string CreateDeploymentRuntime() - { - string directory = Path.Combine(projectRoot, "TargetRuntime"); - Directory.CreateDirectory(directory); - foreach (string source in Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly)) - { - File.Copy(source, Path.Combine(directory, Path.GetFileName(source)), overwrite: true); - } - - return directory; - } - - private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) => new DotNetModuleSource - { - artifactRootDirectory = Path.Combine(projectRoot, "Library", "Assemblies"), - moduleName = deployment.moduleName, - mainAssemblyPath = deployment.mainAssemblyPath, - domain = deployment.domain, - scope = deployment.scope, - preloadAssemblyPaths = deployment.preloadAssemblyPaths, - upstreamModuleNames = deployment.upstreamModuleNames, - assemblyScopes = deployment.assemblyScopes, - collectible = true - }; - internal ScriptReloadHost CreateReloadHost( - EditorReloadCoordinator? reloads = null, - bool autoCompile = false - ) => new( - new ScriptReloadOptions { autoCompile = autoCompile, debounceMilliseconds = 0, compilationWarningTimeout = Timeout.InfiniteTimeSpan }, - compiler, - assets, - m_plugins, - host.modules, - m_settings, - reloads ?? new EditorReloadCoordinator(), - CreateScriptModuleSource - ); - internal ScriptCompilationResult CompilePending(ScriptReloadHost reload) - { - Rescan(); - reload.RecompileScripting(); - Assert.True(reload.TryCompilePending(out Task? compilation)); - return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); - } - - internal ScriptCompilationResult CompilePendingPluginReload(ScriptReloadHost reload) - { - reload.ReloadPlugins(); - Assert.True(reload.TryCompilePending(out Task? compilation)); - return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); - } - - internal bool RefreshPlugins() => m_plugins.Refresh(); - internal Type ResolveActiveType(string name) - { - TypeCacheSnapshot snapshot = host.types.current; - return snapshot.types.Select(typeRef => typeRef.Resolve(snapshot)).Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); - } - - internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? reloads = null) - { - ScriptingCompilationProbe.Reset(); - SceneReloadProbe.Reset(); - reloads ??= new EditorReloadCoordinator(); - RuntimeSession editorSession = CreateEditorSession(); - return new EditorInteractionRuntime( - new EditorContext(projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), - host.types, - host.logs, - [ - host.types, - host.serialization, - m_identities, - editorSession.identities, - host.modules, - assets, - m_plugins, - m_settings, - compiler, - new Func(CreateScriptModuleSource), - editorSession, - reloads - ] - ); - } - - internal RuntimeSession CreateEditorSession() - { - m_editorSession ??= host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, applicationId = "tests.editor", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), referenceResolvers = [assets] }); - return m_editorSession; - } - - public void Dispose() - { - if (m_disposed) - return; - m_disposed = true; - m_editorSession?.Dispose(); - m_plugins.Dispose(); - assets.Dispose(); - m_settings.Dispose(); - m_diagnosticScope.Dispose(); - host.Dispose(); - m_identityScope.Dispose(); - if (Directory.Exists(projectRoot)) - Directory.Delete(projectRoot, recursive: true); - } -} - -internal sealed class SampleIdentitySettings : ISerializable -{ - /// - /// Gets or sets one neutral identity stored inside an import settings payload. - /// - [SerializableProperty] - public Guid referenceId { get; set; } -} - -internal sealed class ScriptingAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} - -[EditorModule("tests.scripting-compilation-probe", order: 101)] -public sealed class ScriptingCompilationProbe : EditorModule -{ - public ScriptingCompilationProbe(IEditorScriptCompilation scripting) - { - compilation = scripting; - } + public void Apply() => transfer.Apply(); - public static IEditorScriptCompilation? compilation { get; private set; } + public void Complete() => transfer.Complete(); - public static void Reset() => compilation = null; -} + public void RollbackStructure() => transfer.RollbackStructure(); -[EditorModule("tests.scene-reload-probe", order: 102)] -public sealed class SceneReloadProbe : EditorModule -{ - public SceneReloadProbe(IEditorSceneWorkspace sceneWorkspace) - { - workspace = sceneWorkspace; + public void RestorePreviousState() => transfer.RestorePreviousState(); } - - public static IEditorSceneWorkspace? workspace { get; private set; } - - public static void Reset() => workspace = null; } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs index 75fb232ad..9b8f3db66 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs @@ -1,19 +1,23 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text.Json; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Editor.Graph; using Inno.Native.ImGui; using Inno.Rendering.Shaders; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.Scripting.Tests; @@ -28,9 +32,11 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() string source = Path.Combine(m_root, "Assets"); string? inputRoot = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_INPUT_ROOT"); string? input = inputRoot is null ? null : Path.Combine(Path.GetFullPath(inputRoot), "shader-graph"); - const string name = "Performance.ishader"; + const string C_NAME = "Performance.ishader"; if (input is not null && Directory.Exists(input)) + { CopyPerformanceInput(input, source); + } else { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)); @@ -38,37 +44,51 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() for (int index = 0; index < remaining; index++) { bool constant = index % 2 == 0; - var node = new GraphNodeRecord(new("performance.node." + index.ToString("D4")), - constant ? "inno.shader.constant" : "inno.shader.construct") + var node = new GraphNodeRecord( + new GraphNodeID("performance.node." + index.ToString("D4")), + constant ? "inno.shader.constant" : "inno.shader.construct" + ) { position = new(index % 20 * 310f, index / 20 * 180f) }; if (!constant) + { node.SetValue("type", ShaderGraphDocument.Encode("float3", m_serialization, SerializationContext.empty)); + } graph.AddNode(node); if (!constant) - graph.AddEdge(new(new("performance.edge." + index.ToString("D4")), - new(new("performance.node." + (index - 1).ToString("D4")), new("value")), - new(node.id, new("component.0")))); + { + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("performance.edge." + index.ToString("D4")), + new GraphEndpoint(new GraphNodeID("performance.node." + (index - 1).ToString("D4")), new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID("component.0")) + ) + ); + } } - File.WriteAllBytes(Path.Combine(source, name), GraphDocumentCodec.Encode(graph, m_serialization)); + File.WriteAllBytes(Path.Combine(source, C_NAME), GraphDocumentCodec.Encode(graph, m_serialization)); } - Assert.True(m_assets.Import(AssetPath.Project(name))); - Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(name), out AssetFileEntry entry)); + Assert.True(m_assets.Import(AssetPath.Project(C_NAME))); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(C_NAME), out AssetFileEntry entry)); if (input is not null && !Directory.Exists(input)) + { CopyPerformanceInput(source, input); - byte[] original = SHA256.HashData(File.ReadAllBytes(Path.Combine(source, name))); + } + byte[] original = SHA256.HashData(File.ReadAllBytes(Path.Combine(source, C_NAME))); SelectAndDraw(entry); - var controller = Controller(entry); + GraphDocumentController controller = Controller(entry); Assert.Equal(2_000, controller.document.nodes.Count); Assert.True(controller.document.edges.Count >= 900); for (int warmup = 0; warmup < 5; warmup++) + { DrawPerformanceCanvas(); + } string? requested = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS"); - int repetitions = requested is null ? 5 : int.Parse(requested, System.Globalization.CultureInfo.InvariantCulture); + int repetitions = requested is null ? 5 : int.Parse(requested, CultureInfo.InvariantCulture); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); - var samples = new List(); + List samples = []; for (int repetition = 0; repetition < repetitions; repetition++) { var milliseconds = new double[10]; @@ -92,8 +112,13 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() double[] sorted = milliseconds.Order().ToArray(); samples.Add(new { - repetition, milliseconds, vertices, indices, median = (sorted[4] + sorted[5]) / 2, - p95 = sorted[9], allocatedBytes = allocated, + repetition, + milliseconds, + vertices, + indices, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBytesBefore, cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, gen0Collections = GC.CollectionCount(0) - gen0, @@ -101,18 +126,28 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() gen2Collections = GC.CollectionCount(2) - gen2 }); } - m_performanceOutput.WriteLine(JsonSerializer.Serialize(new - { - workload = "2000-shader-nodes", nodeCount = controller.document.nodes.Count, - edgeCount = controller.document.edges.Count, - configuration = typeof(ShaderEditorWorkflowTests).Assembly.GetCustomAttribute()?.Configuration - ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), - samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, - viewport = "1200x800", warmupFrames = 5, measuredFramesPerRepetition = 10, - sharedInput = input, consumer = "native-command-offset-validation", supportsVertexOffsets = true - })); - Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(Path.Combine(source, name)))); + m_performanceOutput.WriteLine( + JsonSerializer.Serialize(new + { + workload = "2000-shader-nodes", + nodeCount = controller.document.nodes.Count, + edgeCount = controller.document.edges.Count, + configuration = typeof(ShaderEditorWorkflowTests) + .Assembly + .GetCustomAttribute() + ?.Configuration + ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), + samples, + framework = RuntimeInformation.FrameworkDescription, + viewport = "1200x800", + warmupFrames = 5, + measuredFramesPerRepetition = 10, + sharedInput = input, + consumer = "native-command-offset-validation", + supportsVertexOffsets = true + }) + ); + Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(Path.Combine(source, C_NAME)))); } private unsafe void DrawPerformanceCanvas() @@ -127,10 +162,16 @@ private unsafe void DrawPerformanceCanvas() ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; ulong end = (ulong)command.IdxOffset + command.ElemCount; if (end > (ulong)list->IdxBuffer.Size) + { throw new InvalidOperationException("The shader canvas exceeded its native index buffer."); + } for (ulong index = command.IdxOffset; index < end; index++) + { if ((ulong)command.VtxOffset + list->IdxBuffer.Data[index] >= (ulong)list->VtxBuffer.Size) + { throw new InvalidOperationException("The shader canvas exceeded its native vertex buffer."); + } + } } } } @@ -141,8 +182,12 @@ string destination ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) + { Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); + } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { File.Copy(file, Path.Combine(destination, Path.GetRelativePath(source, file)), overwrite: false); + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs index 80b006866..21c1148ac 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs @@ -6,10 +6,18 @@ public sealed partial class ShaderEditorWorkflowTests { public static IEnumerable CanvasMetrics() { - foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) - foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) + foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) + { + foreach (float density in new[] { 1f, 1.25f, 1.5f, 2f }) + { foreach ((float width, float height) in new[] { (1280f, 720f), (1920f, 1080f) }) + { foreach (bool emptyGraph in new[] { false, true }) + { yield return [zoom, density, width, height, emptyGraph]; + } + } + } + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs index a7ea3b1f2..941e554ec 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs @@ -1,48 +1,52 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Collections.Generic; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using BGCS.Runtime; +using Xunit; +using Xunit.Abstractions; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Graphs; using Inno.Core.Identity; -using Inno.Core.Logging; -using Inno.Core.Events; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Serialization; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Interactions; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; +using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using Inno.Editor.Rendering; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; +using Inno.Native.ImGui; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; -using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using EngineColor = Inno.Core.Mathematics.Color; +using EngineVector4 = Inno.Core.Mathematics.Vector4; using ImGuiApi = Inno.Native.ImGui.ImGui; -using Xunit; -using Xunit.Abstractions; -using Inno.Rendering.Assets.Authoring; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.Scripting.Tests; + public sealed partial class ShaderEditorWorkflowTests : IDisposable { private readonly ITestOutputHelper m_performanceOutput; @@ -61,13 +65,14 @@ public sealed partial class ShaderEditorWorkflowTests : IDisposable private readonly DiagnosticReporter m_reporter; private readonly AssetPipeline m_assets; private readonly EditorRenderTargetArtifactProvider m_artifacts; - private EditorInteractionRuntime m_runtime; private readonly WorkflowSink m_sink = new(); private readonly ShaderGraphSourceStore m_source; private readonly unsafe ImGuiNativeContext* m_imgui; + private EditorInteractionRuntime m_runtime; private Vector2 m_canvasMinimum; private Vector2 m_canvasMaximum; private Vector2 m_probeOffset; + public unsafe ShaderEditorWorkflowTests(ITestOutputHelper output) { m_performanceOutput = output; @@ -77,12 +82,14 @@ public unsafe ShaderEditorWorkflowTests(ITestOutputHelper output) _ = typeof(ShaderNodeDrawer); _ = typeof(ShaderGraphSourceStore); _ = typeof(GraphEditorModule); - m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderEditorWorkflowTests).Assembly) }); + m_modules = new( + new ModuleHostOptions() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderEditorWorkflowTests).Assembly) } + ); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); m_diagnostics = new DiagnosticHub(); m_diagnosticScope = m_diagnostics.EnterScope(); - m_reporter = m_diagnostics.CreateReporter(new("tests.shader-editor", "Shader Editor workflow")); + m_reporter = m_diagnostics.CreateReporter(new DiagnosticSource("tests.shader-editor", "Shader Editor workflow")); m_assets = new( m_modules, m_types, @@ -90,10 +97,20 @@ public unsafe ShaderEditorWorkflowTests(ITestOutputHelper output) m_identities, m_diagnostics, m_logs, - AssetPipelineOptions.Create(Path.Combine(m_root, "Assets"), Path.Combine(m_root, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_root, "Assets"), + Path.Combine(m_root, "Library") + )with { enableFileSystemWatcher = false } ); m_source = new(m_assets, m_serialization); - m_artifacts = new(m_assets, m_serialization, m_types, new ShaderCompiler(new WorkflowCompiler()), new BgfxTextureTargetCompiler(), m_reporter); + m_artifacts = new( + m_assets, + m_serialization, + m_types, + new ShaderCompiler(new WorkflowCompiler()), + new BgfxTextureTargetCompiler(), + m_reporter + ); m_runtime = CreateRuntime(); m_imgui = ImGuiApi.Raw.CreateContext(null); ImGuiIO* io = ImGuiApi.Raw.GetIO(); @@ -111,13 +128,24 @@ public void ParameterPresentationRoundTripsWithoutChangingTheRuntimeDefinitionOr GraphDocument graph = m_source.Read(entry.assetPath).document; SerializationContext context = AssetSerializationContext.Create(m_assets); byte[] beforeDefinition = m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(graph, m_serialization, context), context); - string beforeHash = ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization), m_serialization); - ShaderPropertyId id = new("stable.tint"); + string beforeHash = ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization), + m_serialization + ); + var id = new ShaderPropertyID("stable.tint"); Assert.True(ShaderParameterPresentation.Read(graph, id, m_serialization, context).visible); ShaderParameterPresentation.Write( graph, id, - new() { group = "Surface", description = "Linear tint", visible = false, hasRange = true, minimum = -2, maximum = 8 }, + new ShaderParameterPresentation() + { + group = "Surface", + description = "Linear tint", + visible = false, + hasRange = true, + minimum = -2, + maximum = 8 + }, m_serialization, context ); @@ -131,10 +159,16 @@ public void ParameterPresentationRoundTripsWithoutChangingTheRuntimeDefinitionOr Assert.Equal(8, presentation.maximum); presentation.group = "Detached"; Assert.Equal("Surface", ShaderParameterPresentation.Read(restored, id, m_serialization, context).group); - Assert.Equal(beforeDefinition, m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(restored, m_serialization, context), context)); + Assert.Equal( + beforeDefinition, + m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(restored, m_serialization, context), context) + ); Assert.Equal( beforeHash, - ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(restored, new Dictionary(), m_serialization), m_serialization) + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(restored, new Dictionary(), m_serialization), + m_serialization + ) ); } @@ -144,7 +178,7 @@ public void ParameterPresentationRejectsInvalidBoundsBeforeMutatingTheGraph() GraphDocument graph = m_source.Read(Create("Range.ishader").assetPath).document; byte[] before = GraphDocumentCodec.Encode(graph, m_serialization); SerializationContext context = AssetSerializationContext.Create(m_assets); - foreach (var range in new[] + foreach ((double, double) range in new[] { (double.NaN, 1d), (0d, double.PositiveInfinity), @@ -153,8 +187,17 @@ public void ParameterPresentationRejectsInvalidBoundsBeforeMutatingTheGraph() (0d, 1e100) } - ) - Assert.Throws(() => ShaderParameterPresentation.Write(graph, new("range"), new() { hasRange = true, minimum = range.Item1, maximum = range.Item2 }, m_serialization, context)); + ) { + Assert.Throws( + () => ShaderParameterPresentation.Write( + graph, + new ShaderPropertyID("range"), + new ShaderParameterPresentation() { hasRange = true, minimum = range.Item1, maximum = range.Item2 }, + m_serialization, + context + ) + ); + } Assert.Equal(before, GraphDocumentCodec.Encode(graph, m_serialization)); } @@ -174,8 +217,8 @@ public unsafe void DiagnosticCheckUsesTheStandardTransientModalWithoutChangingFi { using IDisposable uiScope = m_ui.Enter(); ImGuiApi.NewFrame(); - ImGuiApi.SetNextWindowPos(new(0, 0)); - ImGuiApi.SetNextWindowSize(new(1200, 800)); + ImGuiApi.SetNextWindowPos(new Vector2(0, 0)); + ImGuiApi.SetNextWindowSize(new Vector2(1200, 800)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Shader Check Workflow", allowsNull: false); _ = ImGuiApi.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); try @@ -205,16 +248,22 @@ public void SourceSettingsUndoRedoRestoresValidAndInvalidImportStates() AssetPath path = CreateFunction(); var edits = new AssetImportSettingsEdits(m_assets, m_serialization, m_types, m_runtime.interactions); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); - var settings = Assert.IsType(before.value); + ShaderSourceImportSettings settings = Assert.IsType(before.value); settings.exports = ["MissingFunction"]; Assert.False(edits.Apply(path, settings, before.fingerprint)); - Assert.Equal("MissingFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); + Assert.Equal( + "MissingFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) + ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal("Evaluate", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); Assert.True(m_assets.TryGetInfo(path, out AssetInfo? info)); Assert.Equal(AssetImportStatus.Imported, info!.status); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Equal("MissingFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); + Assert.Equal( + "MissingFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) + ); } [Fact] @@ -223,35 +272,18 @@ public void SourceSettingsUndoRefusesToOverwriteAnExternalSidecarEdit() AssetPath path = CreateFunction(); var edits = new AssetImportSettingsEdits(m_assets, m_serialization, m_types, m_runtime.interactions); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); - var settings = Assert.IsType(before.value); + ShaderSourceImportSettings settings = Assert.IsType(before.value); settings.exports = ["MissingFunction"]; _ = edits.Apply(path, settings, before.fingerprint); AssetImportSettingsSnapshot current = m_assets.GetImportSettings(path); - var external = Assert.IsType(current.value); + ShaderSourceImportSettings external = Assert.IsType(current.value); external.exports = ["ExternalFunction"]; _ = m_assets.SaveImportSettings(path, external, current.fingerprint); Assert.False(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal("ExternalFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); - } - - private AssetPath CreateFunction(params string[] exports) - { - if (exports.Length == 0) - exports = ["Evaluate"]; - AssetPath path = AssetPath.Project("Function.ishadersource"); - File.WriteAllText( - Path.Combine(m_root, "Assets", path.localPath), - string.Join("\n", exports.Select(static function => $"float {function}(float input) {{ return input; }}")) + Assert.Equal( + "ExternalFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) ); - _ = m_assets.Import(path); - var settings = new ShaderSourceImportSettings - { - languageId = "inno.shader-language.bgfx-sc", - implementationId = "bgfx", - exports = exports - }; - Assert.True(m_assets.SaveImportSettings(path, settings, m_assets.GetImportSettings(path).fingerprint)); - return path; } [Fact] @@ -260,8 +292,8 @@ public void FileSelectionOpensOnlyTheShaderCanvasAndNonShaderSelectionKeepsItsDo AssetFileEntry entry = Create("Surface.ishader"); SelectAndDraw(entry); EditorDocumentContext document = Assert.Single(m_runtime.interactions.documents.documents); - Assert.Equal(AssetId(entry), document.assetId); - Assert.NotEqual(entry.identity.persistentId, document.assetId); + Assert.Equal(AssetID(entry), document.assetID); + Assert.NotEqual(entry.identity.persistentID, document.assetID); Assert.DoesNotContain(m_runtime.panels, panel => panel.id == "editor.documents" && panel.isOpen); m_runtime.interactions.SetSelection(null); Draw(); @@ -273,7 +305,7 @@ public void FileSelectionOpensOnlyTheShaderCanvasAndNonShaderSelectionKeepsItsDo [Theory] [MemberData(nameof(CanvasMetrics))] [Trait("Acceptance", "Visual")] - public unsafe void NativeCanvasResizeCompletesLayoutAtFractionalUiScales( + public unsafe void NativeCanvasResizeCompletesLayoutAtFractionalUIScales( float zoom, float density, float width, @@ -284,22 +316,38 @@ bool emptyGraph SelectAndDraw(entry); GraphDocumentController controller = Controller(entry); if (emptyGraph) + { controller.ReplaceDocument(new GraphDocument(), "Prepare Empty Canvas"); + } ulong revision = controller.revision; byte[] disk = File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath)); - ImGuiApi.Raw.GetIO()->DisplaySize = Unsafe.BitCast(new(width, height)); - ImGuiApi.Raw.GetIO()->DisplayFramebufferScale = Unsafe.BitCast(new(density)); + ImGuiApi.Raw.GetIO()->DisplaySize = Unsafe.BitCast(new Vector2(width, height)); + ImGuiApi.Raw.GetIO()->DisplayFramebufferScale = Unsafe.BitCast(new Vector2(density)); m_ui.widgets.style.SetZoom(zoom); using (m_ui.Enter()) + { m_ui.widgets.SetupStyle(); - Vector2[] sizes = [new(width, height), new(640, 400), new(280, 220), new(96, 64), new(32, 32), new(width, 32), new(32, height), new(width, height)]; + } + Vector2[] sizes = + [ + new Vector2(width, height), + new Vector2(640, 400), + new Vector2(280, 220), + new Vector2(96, 64), + new Vector2(32, 32), + new Vector2(width, 32), + new Vector2(32, height), + new Vector2(width, height) + ]; for (int cycle = 0; cycle < 3; cycle++) + { foreach (Vector2 size in sizes) { // Run both the resize frame and its settled layout with native assertions enabled. Draw(size); Draw(size); } + } Assert.Equal(revision, controller.revision); Assert.Equal(disk, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); @@ -312,47 +360,48 @@ public void SeparateMovesAndUndoRedoRemainDraftsUntilExplicitSave() AssetFileEntry entry = Create("Moves.ishader"); SelectAndDraw(entry); GraphDocumentController graph = Controller(entry); - GraphNodeId node = graph.document.nodes[0].id; + GraphNodeID node = graph.document.nodes[0].id; GraphPosition original = graph.document.nodes[0].position; - graph.MoveNodes(new Dictionary { [node] = new(111, 222) }); + graph.MoveNodes(new Dictionary { [node] = new(111, 222) }); Tick(); Assert.Equal(original, ReadPosition(entry, node)); Assert.True(Assert.Single(m_runtime.interactions.documents.documents).isDirty); - graph.MoveNodes(new Dictionary { [node] = new(333, 444) }); + graph.MoveNodes(new Dictionary { [node] = new(333, 444) }); Tick(); Assert.Equal(original, ReadPosition(entry, node)); Assert.True(m_runtime.interactions.history.Undo().succeeded); Tick(); - Assert.Equal(new(111, 222), graph.document.FindNode(node)!.position); + Assert.Equal(new GraphPosition(111, 222), graph.document.FindNode(node)!.position); Assert.Equal(original, ReadPosition(entry, node)); Assert.True(m_runtime.interactions.history.Undo().succeeded); Tick(); Assert.Equal(original, ReadPosition(entry, node)); Assert.True(m_runtime.interactions.history.Redo().succeeded); Tick(); - Assert.Equal(new(111, 222), graph.document.FindNode(node)!.position); + Assert.Equal(new GraphPosition(111, 222), graph.document.FindNode(node)!.position); Assert.Equal(original, ReadPosition(entry, node)); Assert.True(m_runtime.interactions.For("panel/rendering.shader-editor", entry).Execute("shader/save")); - Assert.Equal(new(111, 222), ReadPosition(entry, node)); + Assert.Equal(new GraphPosition(111, 222), ReadPosition(entry, node)); Assert.False(Assert.Single(m_runtime.interactions.documents.documents).isDirty); Assert.True(m_runtime.interactions.history.Undo().succeeded); Tick(); Assert.Equal(original, graph.document.FindNode(node)!.position); - Assert.Equal(new(111, 222), ReadPosition(entry, node)); + Assert.Equal(new GraphPosition(111, 222), ReadPosition(entry, node)); } [Fact] public void SwitchingSelectionKeepsAnInvalidDraftAndExplicitCloseSavePersistsIt() { - AssetFileEntry first = Create("Incomplete.ishader"), second = Create("Other.ishader"); + AssetFileEntry first = Create("Incomplete.ishader"); + AssetFileEntry second = Create("Other.ishader"); SelectAndDraw(first); - GraphNodeId missing = Controller(first).AddNode("tests.uninstalled.node", new(32, 64)); + GraphNodeID missing = Controller(first).AddNode("tests.uninstalled.node", new GraphPosition(32, 64)); Tick(); SelectAndDraw(second); Assert.Null(m_source.Read(first.assetPath).document.FindNode(missing)); Assert.NotNull(Controller(first).document.FindNode(missing)); - EditorDocumentContext firstDocument = m_runtime.interactions.documents.documents.Single(value => value.assetId == AssetId(first)); - Assert.True(m_runtime.interactions.documents.Close(firstDocument.documentId, EditorDocumentCloseMode.Save)); + EditorDocumentContext firstDocument = m_runtime.interactions.documents.documents.Single(value => value.assetID == AssetID(first)); + Assert.True(m_runtime.interactions.documents.Close(firstDocument.documentID, EditorDocumentCloseMode.Save)); SelectAndDraw(first); Assert.NotNull(Controller(first).document.FindNode(missing)); } @@ -364,7 +413,7 @@ public void NativeMouseGesturesMoveNodesAndEachReleaseHasItsOwnUndo() SelectAndDraw(entry); GraphDocumentController controller = Controller(entry); var graph = new GraphDocument(); - var node = new GraphNodeRecord(new("probe"), "tests.shader-ui-probe") + var node = new GraphNodeRecord(new GraphNodeID("probe"), "tests.shader-ui-probe") { position = new(0, 0) }; @@ -374,10 +423,10 @@ public void NativeMouseGesturesMoveNodesAndEachReleaseHasItsOwnUndo() Draw(); Draw(); GraphPosition original = controller.document.FindNode(node.id)!.position; - DragProbe(new(52, 37)); + DragProbe(new Vector2(52, 37)); GraphPosition first = controller.document.FindNode(node.id)!.position; Assert.NotEqual(original, first); - DragProbe(new(41, 23)); + DragProbe(new Vector2(41, 23)); GraphPosition second = controller.document.FindNode(node.id)!.position; Assert.NotEqual(first, second); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -397,49 +446,51 @@ public void FormatPlacesOutputsOnTheRightWithoutChangingShaderSemanticsAndIsUndo GraphDocumentController controller = Controller(entry); GraphDocument reversed = controller.document.Clone(); foreach (GraphNodeRecord node in reversed.nodes) - node.position = node.definitionId == ShaderGraphDocument.outputDefinitionId ? new(0, node.position.y) : new(900, node.position.y); + { + node.position = node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + ? new GraphPosition(0, node.position.y) + : new GraphPosition(900, node.position.y); + } controller.ReplaceDocument(reversed, "Reverse Shader Layout"); byte[] before = GraphDocumentCodec.Encode(controller.document, m_serialization); string semantic = ShaderGraphArtifact.GetSemanticHash( - ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), + ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), m_serialization ); Assert.True(m_runtime.interactions.For("panel/rendering.shader-editor", entry).Execute("shader/format")); - GraphNodeRecord[] outputs = controller.document.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).ToArray(); + GraphNodeRecord[] outputs = controller.document.nodes + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .ToArray(); Assert.All( outputs, - output => Assert.True(output.position.x > controller.document.nodes.Where(node => node.id != output.id && ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == output.id.value).Max(static node => node.position.x)) + output => Assert.True( + output.position.x > controller.document.nodes + .Where( + node => ( + node.id != output.id + && ShaderGraphDocument.Read( + node, + "stage", + string.Empty, + m_serialization, + AssetSerializationContext.Create(m_assets) + ) == output.id.value + ) + ) + .Max(static node => node.position.x) + ) ); Assert.Equal( semantic, - ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), m_serialization) + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), + m_serialization + ) ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(before, GraphDocumentCodec.Encode(controller.document, m_serialization)); } - private unsafe void DragProbe(Vector2 distance) - { - BeginDragProbe(distance); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, 0); - Draw(); - Tick(); - m_probeOffset += distance; - } - - private unsafe void BeginDragProbe(Vector2 distance) - { - // A single framed summary-only node is centered in the canvas (82 px tall). - Vector2 start = (m_canvasMinimum + m_canvasMaximum) * 0.5f + new Vector2(0, -25) + m_probeOffset; - Assert.True(start.X > 0 && start.Y > 0); - ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), start.X, start.Y); - Draw(); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); - Draw(); - ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), start.X + distance.X, start.Y + distance.Y); - Draw(); - } - [Fact] public unsafe void SaveDuringANativeDragCompletesOneDomainEditBeforeWriting() { @@ -447,17 +498,17 @@ public unsafe void SaveDuringANativeDragCompletesOneDomainEditBeforeWriting() SelectAndDraw(entry); GraphDocumentController controller = Controller(entry); var graph = new GraphDocument(); - var node = new GraphNodeRecord(new("probe"), "tests.shader-ui-probe") { position = new(0f, 0f) }; + var node = new GraphNodeRecord(new GraphNodeID("probe"), "tests.shader-ui-probe") { position = new(0f, 0f) }; graph.AddNode(node); controller.ReplaceDocument(graph, "Prepare Save Probe"); Assert.True(m_runtime.interactions.For("panel/rendering.shader-editor", entry).Execute("shader/focus")); Draw(); Draw(); GraphPosition original = controller.document.FindNode(node.id)!.position; - BeginDragProbe(new(52f, 37f)); + BeginDragProbe(new Vector2(52f, 37f)); Assert.Equal(original, controller.document.FindNode(node.id)!.position); EditorDocumentContext document = Assert.Single(m_runtime.interactions.documents.documents); - Assert.True(m_runtime.interactions.documents.Save(document.documentId)); + Assert.True(m_runtime.interactions.documents.Save(document.documentID)); GraphPosition saved = controller.document.FindNode(node.id)!.position; Assert.NotEqual(original, saved); Assert.Equal(saved, ReadPosition(entry, node.id)); @@ -479,13 +530,13 @@ public void OneHundredActualShaderDocumentCyclesRetireTheirGraphOwners() { SelectAndDraw(entry); GraphDocumentController controller = Controller(entry); - controller.AddNode("missing.lifecycle", new(iteration, iteration)); + controller.AddNode("missing.lifecycle", new GraphPosition(iteration, iteration)); Tick(); EditorDocumentContext document = Assert.Single(m_runtime.interactions.documents.documents); - Assert.True(m_runtime.interactions.documents.Close(document.documentId, EditorDocumentCloseMode.Discard)); + Assert.True(m_runtime.interactions.documents.Close(document.documentID, EditorDocumentCloseMode.Discard)); Assert.Empty(m_runtime.interactions.documents.documents); Assert.False(controller.isAvailable); - Assert.False(m_sink.graphs!.TryOpenDocument(AssetId(entry), m_runtime.interactions.history, out _)); + Assert.False(m_sink.graphs!.TryOpenDocument(AssetID(entry), m_runtime.interactions.history, out _)); } Assert.Equal(source, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); } @@ -495,28 +546,17 @@ public void ExternalSourceConflictKeepsBothDiskAndUnsavedRecovery() { AssetFileEntry entry = Create("Conflict.ishader"); SelectAndDraw(entry); - GraphNodeId pending = Controller(entry).AddNode("tests.unsaved", new(40, 50)); + GraphNodeID pending = Controller(entry).AddNode("tests.unsaved", new GraphPosition(40, 50)); GraphDocument external = m_source.Read(entry.assetPath).document; - external.AddNode(new(new("external"), "tests.external")); + external.AddNode(new GraphNodeRecord(new GraphNodeID("external"), "tests.external")); byte[] externalBytes = GraphDocumentCodec.Encode(external, m_serialization); File.WriteAllBytes(Path.Combine(m_root, "Assets", "Conflict.ishader"), externalBytes); Tick(); - Assert.False(m_runtime.interactions.documents.Save(Assert.Single(m_runtime.interactions.documents.documents).documentId)); + Assert.False(m_runtime.interactions.documents.Save(Assert.Single(m_runtime.interactions.documents.documents).documentID)); Assert.Equal(externalBytes, File.ReadAllBytes(Path.Combine(m_root, "Assets", "Conflict.ishader"))); Assert.NotNull(Controller(entry).document.FindNode(pending)); Assert.True(Assert.Single(m_runtime.interactions.documents.documents).isDirty); - Assert.True(File.Exists(Path.Combine(m_assets.libraryRoot, "Editor", "ShaderRecovery", AssetId(entry).ToString("N") + ".inno"))); - } - - private AssetFileEntry Create(string name) - { - File.WriteAllBytes( - Path.Combine(m_root, "Assets", name), - GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)), m_serialization) - ); - Assert.True(m_assets.Import(AssetPath.Project(name))); - Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(name), out AssetFileEntry entry)); - return entry; + Assert.True(File.Exists(Path.Combine(m_assets.libraryRoot, "Editor", "ShaderRecovery", AssetID(entry).ToString("N") + ".inno"))); } [Theory] @@ -526,19 +566,19 @@ public void DeleteKeysRemoveTheSelectedComputeStageAndItsDeclarationsAsOneUndo(K { AssetFileEntry entry = Create("Delete.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); Assert.True(interaction.Execute("shader/create-output", "Compute")); Assert.False(interaction.Execute("shader/create-output", "Compute")); GraphDocumentController controller = Controller(entry); GraphNodeRecord output = controller.document.nodes.Last(); - var input = new GraphNodeRecord(new("compute-parameter"), "inno.shader.stage-input"); + var input = new GraphNodeRecord(new GraphNodeID("compute-parameter"), "inno.shader.stage-input"); input.SetValue("stage", ShaderGraphDocument.Encode(output.id.value, m_serialization, AssetSerializationContext.Create(m_assets))); GraphDocument graph = controller.document.Clone(); graph.AddNode(input); graph = ShaderGraphBindings.ChangeInput( graph, input.id, - new() { id = "computeParameter", kind = ShaderIrInputKind.Uniform }, + new ShaderGraphInputSettings() { id = "computeParameter", kind = ShaderIrInputKind.Uniform }, m_serialization, AssetSerializationContext.Create(m_assets) ); @@ -555,17 +595,33 @@ public void DeleteKeysRemoveTheSelectedComputeStageAndItsDeclarationsAsOneUndo(K m_logs.Flush(); Assert.True( controller.document.FindNode(output.id)is null, - "Focus: " + m_runtime.interactions.focusedArea + "; cut: " + interaction.Query("shader/cut").isEnabled + "; undo: " + m_runtime.interactions.history.undoName + "; " + string.Join( - "\n", - m_messages.messages - ) + "Focus: " + + m_runtime.interactions.focusedArea + + "; cut: " + + interaction.Query("shader/cut").isEnabled + + "; undo: " + + m_runtime.interactions.history.undoName + + "; " + + string.Join("\n", m_messages.messages) ); Assert.Null(controller.document.FindNode(input.id)); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + controller.document, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); Assert.Single(definition.passes); Assert.DoesNotContain(definition.properties, property => property.id.value == "computeParameter"); using var nodes = new ShaderNodeCompilerRegistry(m_types); - Assert.True(new ShaderGraphProgramCompiler(nodes).Lower(controller.document, "bgfx", new Dictionary(), m_serialization, AssetSerializationContext.Create(m_assets)).succeeded); + Assert.True( + new ShaderGraphProgramCompiler(nodes).Lower( + controller.document, + "bgfx", + new Dictionary(), + m_serialization, + AssetSerializationContext.Create(m_assets) + ).succeeded + ); Tick(); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(before, GraphDocumentCodec.Encode(controller.document, m_serialization)); @@ -578,38 +634,63 @@ public void CutAndPasteStageKeepsItsContentsAndDoesNotCreateDuplicatePassDeclara { AssetFileEntry entry = Create("Clipboard.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); Assert.True(interaction.Execute("shader/create-output", "Compute")); GraphDocumentController controller = Controller(entry); - GraphNodeId stage = controller.document.nodes.Last().id; - GraphNodeId child = controller.AddNode( + GraphNodeID stage = controller.document.nodes.Last().id; + GraphNodeID child = controller.AddNode( "inno.shader.constant", - new(10, 20), - new Dictionary { ["stage"] = ShaderGraphDocument.Encode(stage.value, m_serialization, AssetSerializationContext.Create(m_assets)) } + new GraphPosition(10, 20), + new Dictionary + { + ["stage"] = ShaderGraphDocument.Encode(stage.value, m_serialization, AssetSerializationContext.Create(m_assets)) + } ); Assert.True(interaction.Execute("shader/cut")); Assert.Null(controller.document.FindNode(child)); Assert.True(interaction.Execute("shader/paste")); Assert.Null(controller.document.FindNode(child)); - Assert.Equal(2, controller.document.nodes.Count(node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage != ShaderStage.Compute)); - GraphNodeRecord pasted = controller.document.nodes.Single(node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage == ShaderStage.Compute); + Assert.Equal( + 2, + controller.document.nodes.Count( + node => node.definitionID == "inno.shader.stage-output" && ReadStage(node).stage != ShaderStage.Compute + ) + ); + GraphNodeRecord pasted = controller.document.nodes.Single( + node => node.definitionID == "inno.shader.stage-output" && ReadStage(node).stage == ShaderStage.Compute + ); Assert.Contains( controller.document.nodes, - node => ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == pasted.id.value + node => ( + ShaderGraphDocument.Read( + node, + "stage", + string.Empty, + m_serialization, + AssetSerializationContext.Create(m_assets) + ) == pasted.id.value + ) ); Assert.False(interaction.Execute("shader/duplicate")); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + controller.document, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); Assert.Equal(2, definition.passes.Length); Assert.Equal(2, definition.passes.Select(pass => pass.name).Distinct().Count()); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Single(ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)).passes); - ShaderGraphStageSettings ReadStage(GraphNodeRecord node) => ShaderGraphDocument.Read( - node, - "settings", - new ShaderGraphStageSettings(), - m_serialization, - AssetSerializationContext.Create(m_assets) + Assert.Single( + ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)).passes ); + ShaderGraphStageSettings ReadStage(GraphNodeRecord node) + => ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + m_serialization, + AssetSerializationContext.Create(m_assets) + ); } [Fact] @@ -618,7 +699,7 @@ public void SourceMenuUsesAssetIdentityAndDisconnectCommitsOneUndoWithoutSaving( AssetPath source = CreateFunction("Evaluate", "Secondary"); AssetFileEntry entry = Create("Source.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); EditorMenuItem create = interaction.BuildMenu().items.Single(item => item.label == "Create"); EditorMenuItem functions = create.children.Single(item => item.label == "Functions"); EditorMenuItem general = Assert.Single(functions.children); @@ -626,23 +707,42 @@ public void SourceMenuUsesAssetIdentityAndDisconnectCommitsOneUndoWithoutSaving( EditorMenuItem library = Assert.Single(general.children); Assert.Equal(["Evaluate", "Secondary"], library.children.Select(static item => item.label)); EditorMenuItem function = library.children.Single(item => item.label == "Evaluate"); - Assert.True(interaction.Execute(function.actionId!, function.argument)); + Assert.True(interaction.Execute(function.actionID!, function.argument)); GraphDocumentController controller = Controller(entry); - GraphNodeRecord node = controller.document.nodes.Single(node => node.definitionId == "inno.shader.source"); + GraphNodeRecord node = controller.document.nodes.Single(node => node.definitionID == "inno.shader.source"); Assert.True(m_assets.TryGetInfo(source, out AssetInfo? info)); - Assert.Equal(info!.persistentId, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, m_serialization, AssetSerializationContext.Create(m_assets))); - Assert.Equal("Evaluate", ShaderGraphDocument.Read(node, "function", "", m_serialization, AssetSerializationContext.Create(m_assets))); + Assert.Equal( + info!.persistentID, + ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, m_serialization, AssetSerializationContext.Create(m_assets)) + ); + Assert.Equal( + "Evaluate", + ShaderGraphDocument.Read(node, "function", string.Empty, m_serialization, AssetSerializationContext.Create(m_assets)) + ); Tick(); using var nodes = new ShaderNodeCompilerRegistry(m_types); using var frontends = new ShaderSourceFrontendRegistry(m_types); ShaderFunctionAsset functionAsset = m_assets.Load(source); - ShaderSourceModuleAnalysis module = frontends.AnalyzeModule(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(functionAsset, m_assets), "Evaluate", m_serialization)); - IReadOnlyList ports = nodes.DescribePorts(node, m_serialization, AssetSerializationContext.Create(m_assets), module, functionAsset.implementationId, null); + ShaderSourceModuleAnalysis module = frontends.AnalyzeModule( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(functionAsset, m_assets), "Evaluate", m_serialization) + ); + IReadOnlyList ports = nodes.DescribePorts( + node, + m_serialization, + AssetSerializationContext.Create(m_assets), + module, + functionAsset.implementationId, + null + ); Assert.Contains(ports, port => port.direction == GraphPortDirection.Input); Assert.Contains(ports, port => port.direction == GraphPortDirection.Output); - GraphNodeId constant = controller.AddNode("inno.shader.constant", new(0, 0)); + GraphNodeID constant = controller.AddNode("inno.shader.constant", new GraphPosition(0, 0)); GraphDocument candidate = controller.document.Clone(); - var edge = new GraphEdgeRecord(new("source-link"), new(constant, new("value")), new(node.id, new(ports.First(port => port.direction == GraphPortDirection.Input).id))); + var edge = new GraphEdgeRecord( + new GraphEdgeID("source-link"), + new GraphEndpoint(constant, new GraphPortID("value")), + new GraphEndpoint(node.id, new GraphPortID(ports.First(port => port.direction == GraphPortDirection.Input).id)) + ); candidate.AddEdge(edge); controller.ReplaceDocument(candidate, "Connect Source"); Assert.True(interaction.Execute("shader/disconnect")); @@ -663,7 +763,10 @@ public void SourceLibrariesOwnTheirNestedCreationCatalogWithoutLeakingSeparators Assert.True(m_assets.SaveImportSettings(source, settings, snapshot.fingerprint)); AssetFileEntry entry = Create("Catalog.ishader"); SelectAndDraw(entry); - EditorMenuItem create = m_runtime.interactions.For("panel/rendering.shader-editor", entry).BuildMenu().items.Single(item => item.label == "Create"); + EditorMenuItem create = m_runtime.interactions + .For("panel/rendering.shader-editor", entry) + .BuildMenu().items + .Single(item => item.label == "Create"); EditorMenuItem functions = create.children.Single(item => item.label == "Functions"); EditorMenuItem rendering2D = functions.children.Single(item => item.label == "Rendering 2D"); Assert.True(rendering2D.separatorBefore); @@ -679,7 +782,10 @@ public void PluginNodePresentationOwnsItsCreationGroupAndSeparator() { AssetFileEntry entry = Create("NodeCatalog.ishader"); SelectAndDraw(entry); - EditorMenuItem create = m_runtime.interactions.For("panel/rendering.shader-editor", entry).BuildMenu().items.Single(item => item.label == "Create"); + EditorMenuItem create = m_runtime.interactions + .For("panel/rendering.shader-editor", entry) + .BuildMenu().items + .Single(item => item.label == "Create"); EditorMenuItem domain = create.children.Single(item => item.label == "Domain"); EditorMenuItem extension = domain.children.Single(item => item.label == "Test Extension"); Assert.True(extension.separatorBefore); @@ -695,24 +801,24 @@ public void FormatOrdersSourcesByDestinationPortsToAvoidInputWireCrossings() AssetFileEntry entry = Create("Crossings.ishader"); SelectAndDraw(entry); var graph = new GraphDocument(); - var top = new GraphNodeRecord(new("top"), "inno.shader.constant") + var top = new GraphNodeRecord(new GraphNodeID("top"), "inno.shader.constant") { position = new(800, 600) }; - var middle = new GraphNodeRecord(new("middle"), "inno.shader.constant") + var middle = new GraphNodeRecord(new GraphNodeID("middle"), "inno.shader.constant") { position = new(800, 400) }; - var bottom = new GraphNodeRecord(new("bottom"), "inno.shader.constant") + var bottom = new GraphNodeRecord(new GraphNodeID("bottom"), "inno.shader.constant") { position = new(800, 200) }; - var evaluate = new GraphNodeRecord(new("evaluate"), "inno.shader.construct") + var evaluate = new GraphNodeRecord(new GraphNodeID("evaluate"), "inno.shader.construct") { position = new(400, 300) }; evaluate.SetValue("type", ShaderGraphDocument.Encode("float3", m_serialization, SerializationContext.empty)); - var output = new GraphNodeRecord(new("output"), "tests-output") + var output = new GraphNodeRecord(new GraphNodeID("output"), "tests-output") { position = new(0, 300) }; @@ -725,12 +831,37 @@ public void FormatOrdersSourcesByDestinationPortsToAvoidInputWireCrossings() output } - ) + ) { graph.AddNode(node); - graph.AddEdge(new(new("top-edge"), new(top.id, new("value")), new(evaluate.id, new("component.0")))); - graph.AddEdge(new(new("middle-edge"), new(middle.id, new("value")), new(evaluate.id, new("component.1")))); - graph.AddEdge(new(new("bottom-edge"), new(bottom.id, new("value")), new(evaluate.id, new("component.2")))); - graph.AddEdge(new(new("result-edge"), new(evaluate.id, new("value")), new(output.id, new("color")))); + } + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("top-edge"), + new GraphEndpoint(top.id, new GraphPortID("value")), + new GraphEndpoint(evaluate.id, new GraphPortID("component.0")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("middle-edge"), + new GraphEndpoint(middle.id, new GraphPortID("value")), + new GraphEndpoint(evaluate.id, new GraphPortID("component.1")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("bottom-edge"), + new GraphEndpoint(bottom.id, new GraphPortID("value")), + new GraphEndpoint(evaluate.id, new GraphPortID("component.2")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("result-edge"), + new GraphEndpoint(evaluate.id, new GraphPortID("value")), + new GraphEndpoint(output.id, new GraphPortID("color")) + ) + ); GraphDocumentController controller = Controller(entry); controller.ReplaceDocument(graph, "Prepare crossing layout"); Assert.True(m_runtime.interactions.For("panel/rendering.shader-editor", entry).Execute("shader/format")); @@ -746,14 +877,18 @@ public void SavingAppliesTheGraphWithoutDependingOnFileWatcherAndUndoStaysDraftO { AssetFileEntry entry = Create("Apply.ishader"); SelectAndDraw(entry); - ShaderAsset asset = m_assets.Load(AssetId(entry)); + ShaderAsset asset = m_assets.Load(AssetID(entry)); long before = asset.contentVersion; GraphDocumentController controller = Controller(entry); GraphDocument graph = controller.document.Clone(); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + graph, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); definition.name = "Saved Change"; graph.SetMetadata( - ShaderGraphDocument.definitionKey, + ShaderGraphDocument.C_DEFINITION_KEY, ShaderGraphDocument.Encode( m_serialization.Serialize(definition, AssetSerializationContext.Create(m_assets)), m_serialization, @@ -763,12 +898,12 @@ public void SavingAppliesTheGraphWithoutDependingOnFileWatcherAndUndoStaysDraftO controller.ReplaceDocument(graph, "Rename Shader"); Tick(); Assert.Equal(before, asset.contentVersion); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); interaction.Focus(); HotKeyGesture save = HotKeyGesture.Primary(KeyCode.S, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); m_runtime.HandleKeyPressed(new KeyPressedEvent(0, save.key, save.modifiers)); Tick(); - Assert.True(m_assets.TryLoad(AssetId(entry), out ShaderAsset? saved)); + Assert.True(m_assets.TryLoad(AssetID(entry), out ShaderAsset? saved)); Assert.Equal("Saved Change", saved!.definition!.name); Assert.True(saved.contentVersion > before); long savedVersion = saved.contentVersion; @@ -778,7 +913,7 @@ public void SavingAppliesTheGraphWithoutDependingOnFileWatcherAndUndoStaysDraftO Assert.Equal(savedVersion, saved.contentVersion); Assert.True(interaction.Execute("shader/save")); Tick(); - Assert.True(m_assets.TryLoad(AssetId(entry), out ShaderAsset? undone)); + Assert.True(m_assets.TryLoad(AssetID(entry), out ShaderAsset? undone)); Assert.NotEqual("Saved Change", undone!.definition!.name); } @@ -787,12 +922,12 @@ public void CancelKeepsDraftAndDiscardRestoresDiskWithoutApplyingIt() { AssetFileEntry entry = Create("Close.ishader"); SelectAndDraw(entry); - GraphNodeId node = Controller(entry).AddNode("tests.unsaved", new(0, 0)); + GraphNodeID node = Controller(entry).AddNode("tests.unsaved", new GraphPosition(0, 0)); Tick(); EditorDocumentContext document = Assert.Single(m_runtime.interactions.documents.documents); - Assert.False(m_runtime.interactions.documents.Close(document.documentId, EditorDocumentCloseMode.Cancel)); + Assert.False(m_runtime.interactions.documents.Close(document.documentID, EditorDocumentCloseMode.Cancel)); Assert.NotNull(Controller(entry).document.FindNode(node)); - Assert.True(m_runtime.interactions.documents.Close(document.documentId, EditorDocumentCloseMode.Discard)); + Assert.True(m_runtime.interactions.documents.Close(document.documentID, EditorDocumentCloseMode.Discard)); SelectAndDraw(entry); Assert.Null(Controller(entry).document.FindNode(node)); Assert.Null(m_source.Read(entry.assetPath).document.FindNode(node)); @@ -806,10 +941,12 @@ public void RestartRecoversOnlyTheLatestDraftAndNeverAppliesIt(bool undo) AssetFileEntry entry = Create("Recovery.ishader"); SelectAndDraw(entry); byte[] saved = File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath)); - GraphNodeId node = Controller(entry).AddNode("tests.unsaved", new(0, 0)); + GraphNodeID node = Controller(entry).AddNode("tests.unsaved", new GraphPosition(0, 0)); Tick(); if (undo) + { Assert.True(m_runtime.interactions.history.Undo().succeeded); + } // Shutdown must capture even the final undo that has not had an update frame yet. m_runtime.Dispose(); Assert.Equal(saved, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); @@ -826,7 +963,17 @@ public void DraftCompilationNeverReplacesTheCanonicalArtifactAndLayoutChangesDoN ShaderAsset shader = m_assets.Load(entry.assetPath); byte[] disk = File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath)); RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); + var capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); var compilation = new EditorShaderCompilation(m_artifacts, capabilities); RenderShaderArtifact? canonical = null; for (int i = 0; i < 100 && canonical is null; i++) @@ -837,61 +984,50 @@ public void DraftCompilationNeverReplacesTheCanonicalArtifactAndLayoutChangesDoN Assert.NotNull(canonical); GraphDocument draft = m_source.Read(entry.assetPath).document; - var context = AssetSerializationContext.Create(m_assets); + SerializationContext context = AssetSerializationContext.Create(m_assets); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(draft, m_serialization, context); ShaderPropertyDefinition property = definition.properties[0]; - property.defaultValue = MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.23f, 1, 1, 1)); + property.defaultValue = MaterialValue.FromColor(new EngineColor(0.23f, 1, 1, 1)); definition.properties[0] = property; - draft.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition, context), m_serialization, context)); - Guid previewId = Guid.NewGuid(); + draft.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition, context), m_serialization, context) + ); + Guid previewID = Guid.NewGuid(); EditorShaderDraftCompilationSnapshot Poll(ulong revision) { - EditorShaderDraftCompilationSnapshot result = compilation.RequestDraft(previewId, draft, revision, RenderShaderVariant.empty); + EditorShaderDraftCompilationSnapshot result = compilation.RequestDraft(previewID, draft, revision, RenderShaderVariant.empty); for (int i = 0; i < 100 && result.state == EditorShaderCompilationState.Compiling; i++) { Thread.Sleep(1); - result = compilation.RequestDraft(previewId, draft, revision, RenderShaderVariant.empty); + result = compilation.RequestDraft(previewID, draft, revision, RenderShaderVariant.empty); } return result; } - var preview = Poll(1); + EditorShaderDraftCompilationSnapshot preview = Poll(1); Assert.Equal(EditorShaderCompilationState.Succeeded, preview.state); Assert.NotNull(preview.artifact); Assert.NotEqual(canonical!.contentHash, preview.artifact!.contentHash); draft.nodes[0].position = new(123, 456); Assert.Same(preview.artifact, Poll(2).artifact); - GraphNodeRecord output = draft.nodes.First(value => value.definitionId == ShaderGraphDocument.outputDefinitionId); + GraphNodeRecord output = draft.nodes.First(value => value.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID); draft.RemoveNode(output.id); - var failed = Poll(3); + EditorShaderDraftCompilationSnapshot failed = Poll(3); Assert.Equal(EditorShaderCompilationState.Failed, failed.state); Assert.True(failed.usingLastGood); Assert.Same(preview.artifact, failed.artifact); - _ = m_artifacts.GetShaderArtifact(shader, RenderShaderVariant.empty, capabilities, out var unchanged); + _ = m_artifacts.GetShaderArtifact(shader, RenderShaderVariant.empty, capabilities, out RenderShaderArtifact? unchanged); Assert.Same(canonical, unchanged); Assert.Equal(disk, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); - compilation.ReleaseDraft(previewId); - } - - private EditorInteractionRuntime CreateRuntime() - { - RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); - var runtime = new EditorInteractionRuntime( - new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), - m_types, - m_logs, - [m_types, m_serialization, m_identities, m_assets, m_sink, m_ui, new EditorReloadCoordinator(), new EditorShaderCompilation(m_artifacts, capabilities), new EmptyPreviews()] - ); - runtime.Start(); - return runtime; + compilation.ReleaseDraft(previewID); } [Fact] public void MaterialGesturesAreIndependentAndOnlySavePublishesTheDraft() { - (AssetPath path, ShaderPropertyId property) = CreateMaterial(); + (AssetPath path, ShaderPropertyID property) = CreateMaterial(); MaterialDocuments documents = Assert.IsType(m_sink.materials); Guid id = documents.Open(path); byte[] original = File.ReadAllBytes(Path.Combine(m_root, "Assets", path.localPath)); @@ -901,7 +1037,7 @@ void Set( string? mergeKey = null ) { MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); documents.Replace(id, candidate, mergeKey); } @@ -929,13 +1065,13 @@ void Set( Assert.False(Assert.Single(m_runtime.interactions.documents.documents).isDirty); Assert.True(m_runtime.interactions.history.Redo().succeeded); EditorDocumentContext context = Assert.Single(m_runtime.interactions.documents.documents); - Assert.True(m_runtime.interactions.documents.Save(context.documentId)); + Assert.True(m_runtime.interactions.documents.Save(context.documentID)); Assert.False(canonical.TryGet(property, out _)); Tick(); Assert.True(canonical.TryGet(property, out value)); Assert.Equal(0.2f, value.vector.x); Set(0.8f); - Assert.True(m_runtime.interactions.documents.Revert(context.documentId)); + Assert.True(m_runtime.interactions.documents.Revert(context.documentID)); Assert.True(documents.Read(id).TryGet(property, out value)); Assert.Equal(0.2f, value.vector.x); } @@ -943,13 +1079,13 @@ void Set( [Fact] public void CancelledMaterialGestureRestoresDraftDirtyStateAndLeavesNoUndoEntry() { - (AssetPath path, ShaderPropertyId property) = CreateMaterial(); + (AssetPath path, ShaderPropertyID property) = CreateMaterial(); MaterialDocuments documents = Assert.IsType(m_sink.materials); Guid id = documents.Open(path); Assert.False(m_runtime.interactions.history.canUndo); using var gesture = new EditorEditGesture(m_runtime.interactions.history, "Cancelled Material Edit"); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.7f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.7f, 1, 1, 1))); documents.Replace(id, candidate, gesture.mergeKey); Assert.True(Assert.Single(m_runtime.interactions.documents.documents).isDirty); Assert.True(gesture.Cancel().succeeded); @@ -961,20 +1097,20 @@ public void CancelledMaterialGestureRestoresDraftDirtyStateAndLeavesNoUndoEntry( [Fact] public void MaterialSaveConflictKeepsDiskAndRecoveredDraftDistinct() { - (AssetPath path, ShaderPropertyId property) = CreateMaterial(); + (AssetPath path, ShaderPropertyID property) = CreateMaterial(); MaterialDocuments documents = Assert.IsType(m_sink.materials); Guid id = documents.Open(path); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.3f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.3f, 1, 1, 1))); documents.Replace(id, candidate); AssetSourceStore sources = m_assets.CreateSourceStore(); AssetSourceSnapshot before = sources.Read(path); MaterialAsset external = sources.Decode(before.bytes); - external.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.9f, 1, 1, 1))); + external.Set(property, MaterialValue.FromColor(new EngineColor(0.9f, 1, 1, 1))); byte[] externalBytes = sources.Encode(external); sources.Save(path, externalBytes, before.contentHash); EditorDocumentContext context = Assert.Single(m_runtime.interactions.documents.documents); - Assert.False(m_runtime.interactions.documents.Save(context.documentId)); + Assert.False(m_runtime.interactions.documents.Save(context.documentID)); Assert.Equal(externalBytes, sources.Read(path).bytes); m_runtime.Dispose(); m_runtime = CreateRuntime(); @@ -988,7 +1124,7 @@ public void MaterialSaveConflictKeepsDiskAndRecoveredDraftDistinct() [Fact] public void CleanMaterialFollowsExternalSourceButDirtyMaterialKeepsItsDraft() { - (AssetPath path, ShaderPropertyId property) = CreateMaterial(); + (AssetPath path, ShaderPropertyID property) = CreateMaterial(); MaterialDocuments documents = Assert.IsType(m_sink.materials); Guid id = documents.Open(path); void External(float value) @@ -996,7 +1132,7 @@ void External(float value) AssetSourceStore sources = m_assets.CreateSourceStore(); AssetSourceSnapshot captured = sources.Read(path); MaterialAsset material = sources.Decode(captured.bytes); - material.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + material.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); sources.Save(path, sources.Encode(material), captured.contentHash); Assert.True(m_assets.Import(path)); Tick(); @@ -1007,25 +1143,26 @@ void External(float value) Assert.Equal(0.2f, inherited.vector.x); Assert.False(Assert.Single(m_runtime.interactions.documents.documents).isDirty); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.5f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.5f, 1, 1, 1))); documents.Replace(id, candidate); External(0.8f); Assert.True(documents.Read(id).TryGet(property, out MaterialValue draft)); Assert.Equal(0.5f, draft.vector.x); Assert.True(Assert.Single(m_runtime.interactions.documents.documents).isDirty); - Assert.False(m_runtime.interactions.documents.Save(Assert.Single(m_runtime.interactions.documents.documents).documentId)); + Assert.False(m_runtime.interactions.documents.Save(Assert.Single(m_runtime.interactions.documents.documents).documentID)); } [Fact] public void MultipleMaterialSamplesCommitAsOneIndependentUndoWithoutPublishing() { - (AssetPath firstPath, ShaderPropertyId property) = CreateMaterial(); + (AssetPath firstPath, ShaderPropertyID property) = CreateMaterial(); AssetPath secondPath = AssetPath.Project("SecondSurface.imaterial"); AssetSourceStore sources = m_assets.CreateSourceStore(); sources.Save(secondPath, sources.Read(firstPath).bytes, null); Assert.True(m_assets.Import(secondPath)); MaterialDocuments documents = Assert.IsType(m_sink.materials); - Guid first = documents.Open(firstPath), second = documents.Open(secondPath); + Guid first = documents.Open(firstPath); + Guid second = documents.Open(secondPath); byte[] original = sources.Read(firstPath).bytes; void Sample( float value, @@ -1038,10 +1175,9 @@ void Sample( second } - ) - { + ) { MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); candidates.Add(id, candidate); } @@ -1069,8 +1205,7 @@ void Sample( second } - ) - { + ) { Assert.True(documents.Read(id).TryGet(property, out MaterialValue value)); Assert.Equal(0.4f, value.vector.x); } @@ -1082,8 +1217,9 @@ void Sample( second } - ) + ) { Assert.False(documents.Read(id).TryGet(property, out _)); + } Assert.All(m_runtime.interactions.documents.documents, document => Assert.False(document.isDirty)); Assert.Equal(original, sources.Read(firstPath).bytes); Assert.Equal(original, sources.Read(secondPath).bytes); @@ -1094,23 +1230,29 @@ void Sample( second } - ) + ) { Assert.True(documents.Read(id).TryGet(property, out _)); + } } [Fact] public void CommonMaterialEditingPreservesUntouchedMixedComponentsAndTextureReferences() { - var first = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(1, 2, 3, 4)); - var edited = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(8, 2, 3, 4)); - var other = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(5, 6, 7, 9)); + MaterialValue first = MaterialValue.FromVector(new EngineVector4(1, 2, 3, 4)); + MaterialValue edited = MaterialValue.FromVector(new EngineVector4(8, 2, 3, 4)); + MaterialValue other = MaterialValue.FromVector(new EngineVector4(5, 6, 7, 9)); MaterialValue result = ShaderPropertyInspector.ApplyEdit(ShaderPropertyType.Vector4, first, edited, other); - Assert.Equal(new Inno.Core.Mathematics.Vector4(8, 6, 7, 9), result.vector); + Assert.Equal(new EngineVector4(8, 6, 7, 9), result.vector); var firstTexture = new TextureAsset(1, 1, TextureColorSpace.Linear, "first"); var secondTexture = new TextureAsset(1, 1, TextureColorSpace.Linear, "second"); first = MaterialValue.FromTexture(firstTexture); edited = first; - edited.sampler = new(RenderSamplerFilter.Point, RenderSamplerAddressMode.Clamp, RenderSamplerAddressMode.Clamp, RenderSamplerAddressMode.Clamp); + edited.sampler = new( + RenderSamplerFilter.Point, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp + ); other = MaterialValue.FromTexture(secondTexture); result = ShaderPropertyInspector.ApplyEdit(ShaderPropertyType.Texture2D, first, edited, other); Assert.Same(secondTexture, result.texture); @@ -1148,17 +1290,17 @@ public void PipelineSettingsDraftsPreserveReferencesAndPublishOnlyAfterSave() Assert.Equal(1, Read(documents.Read(id)).exposure); Assert.True(m_runtime.interactions.history.Redo().succeeded); RenderPipelineAsset draft = documents.Read(id); - Assert.Equal(material.identity.persistentId, Assert.Single(draft.pipelineState.dependencies).persistentId); + Assert.Equal(material.identity.persistentID, Assert.Single(draft.pipelineState.dependencies).persistentID); EditorDocumentContext document = Assert.Single(m_runtime.interactions.documents.documents); - Assert.True(m_runtime.interactions.documents.Save(document.documentId)); + Assert.True(m_runtime.interactions.documents.Save(document.documentID)); Assert.Equal(1, Read(canonical).exposure); Tick(); Assert.Equal(3, Read(canonical).exposure); Assert.Same(material, Read(canonical).material); Assert.True(m_assets.TryGetInfo(path, out AssetInfo? info)); - Assert.Contains(m_assets.GetDependencies(canonical), value => value.persistentId == material.identity.persistentId); + Assert.Contains(m_assets.GetDependencies(canonical), value => value.persistentID == material.identity.persistentID); documents.ReplaceSettings(id, new WorkflowPipelineSettings { material = null, exposure = 8 }); - Assert.True(m_runtime.interactions.documents.Revert(document.documentId)); + Assert.True(m_runtime.interactions.documents.Revert(document.documentID)); Assert.Same(material, Read(documents.Read(id)).material); Assert.Equal(3, Read(documents.Read(id)).exposure); WorkflowPipelineSettings Read(RenderPipelineAsset pipeline) @@ -1172,7 +1314,7 @@ WorkflowPipelineSettings Read(RenderPipelineAsset pipeline) [Fact] public void PipelineMissingSettingsKeepOpaqueBytesThroughHistoryAndRecovery() { - var unknown = new SerializedRenderExtensionState(Guid.NewGuid(), new byte[] { 19, 42, 7 }); + var unknown = new SerializedRenderExtensionState(Guid.NewGuid(), [19, 42, 7]); var source = new RenderPipelineAsset { pipelineTypeId = "tests.missing-pipeline", @@ -1185,7 +1327,7 @@ public void PipelineMissingSettingsKeepOpaqueBytesThroughHistoryAndRecovery() PipelineDocuments documents = Assert.IsType(m_sink.pipelines); Guid id = documents.Open(path); RenderPipelineAsset draft = documents.Read(id); - draft.features = [new("tests.optional", unknown, false)]; + draft.features = [new RenderFeatureConfiguration("tests.optional", unknown, false)]; documents.Replace(id, draft); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Empty(documents.Read(id).features); @@ -1201,17 +1343,116 @@ public void PipelineMissingSettingsKeepOpaqueBytesThroughHistoryAndRecovery() Assert.Empty(sources.Decode(sources.Read(path).bytes).features); } - [StableTypeId("8c096b6f-92c3-48ed-917e-955858d6a65c")] - public sealed unsafe class WorkflowPipelineSettings : ISerializable + public unsafe void Dispose() { - [SerializableProperty] - public MaterialAsset? material { get; set; } + m_runtime.Dispose(); + m_ui.Dispose(); + ImGuiApi.Raw.DestroyContext(m_imgui); + m_artifacts.Dispose(); + m_assets.Dispose(); + m_reporter.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + m_logs.Dispose(); + m_diagnosticScope.Dispose(); + m_identityScope.Dispose(); + Directory.Delete(m_root, true); + } - [SerializableProperty] - public float exposure { get; set; } + private AssetPath CreateFunction(params string[] exports) + { + if (exports.Length == 0) + { + exports = ["Evaluate"]; + } + AssetPath path = AssetPath.Project("Function.ishadersource"); + File.WriteAllText( + Path.Combine(m_root, "Assets", path.localPath), + string.Join("\n", exports.Select(static function => $"float {function}(float input) {{ return input; }}")) + ); + _ = m_assets.Import(path); + var settings = new ShaderSourceImportSettings + { + languageId = "inno.shader-language.bgfx-sc", + implementationId = "bgfx", + exports = exports + }; + Assert.True(m_assets.SaveImportSettings(path, settings, m_assets.GetImportSettings(path).fingerprint)); + return path; } - private (AssetPath, ShaderPropertyId) CreateMaterial() + private unsafe void DragProbe(Vector2 distance) + { + BeginDragProbe(distance); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, 0); + Draw(); + Tick(); + m_probeOffset += distance; + } + + private unsafe void BeginDragProbe(Vector2 distance) + { + // A single framed summary-only node is centered in the canvas (82 px tall). + Vector2 start = (m_canvasMinimum + m_canvasMaximum) * 0.5f + new Vector2(0, -25) + m_probeOffset; + Assert.True(start.X > 0 && start.Y > 0); + ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), start.X, start.Y); + Draw(); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); + Draw(); + ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), start.X + distance.X, start.Y + distance.Y); + Draw(); + } + + private AssetFileEntry Create(string name) + { + File.WriteAllBytes( + Path.Combine(m_root, "Assets", name), + GraphDocumentCodec.Encode( + ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)), + m_serialization + ) + ); + Assert.True(m_assets.Import(AssetPath.Project(name))); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(name), out AssetFileEntry entry)); + return entry; + } + + private EditorInteractionRuntime CreateRuntime() + { + RenderTextureFormat[] formats = Enum.GetValues(); + var capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); + var runtime = new EditorInteractionRuntime( + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), + m_types, + m_logs, + [ + m_types, + m_serialization, + m_identities, + m_assets, + m_sink, + m_ui, + new EditorReloadCoordinator(), + new EditorShaderCompilation(m_artifacts, capabilities), + new EmptyPreviews() + ] + ); + runtime.Start(); + return runtime; + } + + private (AssetPath, ShaderPropertyID) CreateMaterial() { AssetFileEntry shaderEntry = Create("MaterialSurface.ishader"); ShaderAsset shader = m_assets.Load(shaderEntry.assetPath); @@ -1225,18 +1466,19 @@ public sealed unsafe class WorkflowPipelineSettings : ISerializable private GraphDocumentController Controller(AssetFileEntry entry) { Assert.NotNull(m_sink.graphs); - Assert.True(m_sink.graphs.TryOpenDocument(AssetId(entry), m_runtime.interactions.history, out GraphDocumentController? controller)); + Assert.True(m_sink.graphs.TryOpenDocument(AssetID(entry), m_runtime.interactions.history, out GraphDocumentController? controller)); return controller!; } private GraphPosition ReadPosition( AssetFileEntry entry, - GraphNodeId id + GraphNodeID id ) => m_source.Read(entry.assetPath).document.FindNode(id)!.position; - private Guid AssetId(AssetFileEntry entry) + + private Guid AssetID(AssetFileEntry entry) { Assert.True(m_assets.TryGetInfo(entry.assetPath, out AssetInfo? info)); - return info!.persistentId; + return info!.persistentID; } private void SelectAndDraw(AssetFileEntry entry) @@ -1248,7 +1490,7 @@ private void SelectAndDraw(AssetFileEntry entry) private void Tick() { - m_runtime.Update(new(1f / 60, 0, true)); + m_runtime.Update(new EditorFrame(1f / 60, 0, true)); Draw(); } @@ -1258,8 +1500,8 @@ private unsafe void Draw(Vector2? size = null) panel.isOpen = true; using IDisposable uiScope = m_ui.Enter(); ImGuiApi.NewFrame(); - ImGuiApi.SetNextWindowPos(new(0, 0)); - ImGuiApi.SetNextWindowSize(size ?? new(1200, 800)); + ImGuiApi.SetNextWindowPos(new Vector2(0, 0)); + ImGuiApi.SetNextWindowSize(size ?? new Vector2(1200, 800)); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Shader Editor Workflow", allowsNull: false); _ = ImGuiApi.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); try @@ -1275,21 +1517,14 @@ private unsafe void Draw(Vector2? size = null) } } - public unsafe void Dispose() + [StableTypeID("8c096b6f-92c3-48ed-917e-955858d6a65c")] + public sealed unsafe class WorkflowPipelineSettings : ISerializable { - m_runtime.Dispose(); - m_ui.Dispose(); - ImGuiApi.Raw.DestroyContext(m_imgui); - m_artifacts.Dispose(); - m_assets.Dispose(); - m_reporter.Dispose(); - m_serialization.Dispose(); - m_types.Dispose(); - m_modules.Dispose(); - m_logs.Dispose(); - m_diagnosticScope.Dispose(); - m_identityScope.Dispose(); - Directory.Delete(m_root, true); + [SerializableProperty] + public MaterialAsset? material { get; set; } + + [SerializableProperty] + public float exposure { get; set; } } public sealed unsafe class WorkflowSink @@ -1302,6 +1537,7 @@ public sealed unsafe class WorkflowSink private sealed class WorkflowLogs : ILogSink { internal readonly ConcurrentQueue messages = new(); + public void Receive(LogEntry entry) => messages.Enqueue(entry.message); } @@ -1309,6 +1545,7 @@ private sealed class WorkflowLogs : ILogSink public sealed unsafe class CanvasProbeDrawer : ShaderNodeDrawer { public static Vector2 header; + public override void Draw(ShaderNodeDrawContext context) { float zoom = ImGuiApi.GetWindowSize().X / 246f; @@ -1319,10 +1556,12 @@ public override void Draw(ShaderNodeDrawContext context) public sealed unsafe class CanvasProbeCompiler : IShaderNodeCompiler { - public string definitionId => "tests.shader-ui-probe"; + public string definitionID => "tests.shader-ui-probe"; public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); + + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary(); } [EditorModule("tests.shader-workflow", order: 160)] @@ -1342,7 +1581,7 @@ WorkflowSink sink private sealed class WorkflowCompiler : IShaderCompilerToolchain { - public string implementationId => "tests.workflow"; + public string implementationID => "tests.workflow"; public IReadOnlyList supportedSourceLanguages => []; public ShaderCompileTarget CreateTarget( @@ -1350,14 +1589,25 @@ public ShaderCompileTarget CreateTarget( bool optimize = true, bool debugInformation = false ) => new("tests:workflow", capabilities, optimize, debugInformation); + public ValueTask CompileAsync( ShaderStageToolRequest request, CancellationToken cancellationToken - ) => ValueTask.FromResult(new ShaderStageToolResult([1, 2, 3], request.stage.inputs.Where(input => input.kind == ShaderIrInputKind.Uniform).Select(input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), [])); + ) => ValueTask.FromResult( + new ShaderStageToolResult( + [1, 2, 3], + request.stage.inputs + .Where(input => input.kind == ShaderIrInputKind.Uniform) + .Select(input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), + [] + ) + ); } private sealed class EmptyPreviews : IEditorPreviewService { + public uint deviceGeneration => 1; + public bool TryRender( EditorViewportComposition composition, out EditorPreviewHandle handle @@ -1366,11 +1616,7 @@ out EditorPreviewHandle handle return false; } - public void ReleaseRendered(string viewportId) - { - } - - public uint deviceGeneration => 1; + public void ReleaseRendered(string viewportID) {} public bool TryGetTexture( TextureAsset texture, @@ -1394,9 +1640,9 @@ public void Draw( EditorPreviewHandle handle, Vector2 logicalSize ) => throw new InvalidOperationException("No texture was requested by this workflow."); + public bool Release(EditorPreviewHandle handle) => false; - public void ReleaseAll() - { - } + + public void ReleaseAll() {} } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs new file mode 100644 index 000000000..b27338c95 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(TextStateValue), priority: 10_000)] +internal sealed class TextStateDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) + { + TextStateValue value = (TextStateValue)context.GetValue()!; + bool hasState = context.TryGetTextState("editing", out string? state); + observations.Add($"{value.id}:{(hasState ? state : "")}"); + context.SetTextState("editing", value.id); + } + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs new file mode 100644 index 000000000..8048a3fef --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class TextStateOwner : ISerializable +{ + [SerializableProperty] + public TextStateValue value { get; set; } = new("Unset"); +} diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs index 079252a05..5a3e70065 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs @@ -2,20 +2,22 @@ using System.IO; using System.IO.Compression; using System.Linq; -using System.Runtime.InteropServices; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Runtime.Loader; -using System.Reflection; +using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Text; using System.Xml.Linq; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.Toolchains; using Inno.Plugins; +using Inno.Scene; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Scripting.Compiler.Tests; @@ -38,14 +40,27 @@ string value fixture.Rescan(); fixture.compiler.GenerateProjectFiles(); string project = Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(host, project); using var output = new StringWriter(); using var errors = new StringWriter(); - await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync(sdk.hostPath, + await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:" + property + "=" + value], - fixture.projectRoot, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, errors)); + fixture.projectRoot, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors, + CancellationToken.None + )); Assert.Contains("IDE compiler input '" + property + "' differs", output.ToString() + errors, StringComparison.Ordinal); } @@ -61,17 +76,24 @@ public async Task InstalledPluginExtensionMembersAreAvailableInIdeReferences() using var fixture = new CompilerFixture(( root, serialization - ) => { + ) => + { using FileStream stream = File.Create(Path.Combine(root, "Plugins", "language.iplugin")); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); using (Stream manifest = archive.CreateEntry("Plugin.inno").Open()) - manifest.Write(serialization.Serialize(new PluginManifest - { - pluginId = "tests.csharp14", - displayName = "CSharp14 source plugin" - })); + { + manifest.Write( + serialization.Serialize(new PluginManifest + { + pluginId = "tests.csharp14", + displayName = "CSharp14 source plugin" + }) + ); + } using (Stream source = archive.CreateEntry("Assets/PluginLanguage.cs").Open()) - source.Write(Encoding.UTF8.GetBytes(""" + { + source.Write( + Encoding.UTF8.GetBytes(""" namespace LanguagePlugin; public sealed class Counter { @@ -84,14 +106,18 @@ public static class CounterExtensions public bool hasCount => counter.count > 0; } } - """)); + """) + ); + } using Stream metadata = archive.CreateEntry("Assets/PluginLanguage.cs.imeta").Open(); - metadata.Write(serialization.Serialize(new ScriptingAssetSourceMeta - { - persistentId = Guid.NewGuid(), - sourceKind = (int)AssetSourceKind.File, - importerId = "inno.editor.csharp-script" - })); + metadata.Write( + serialization.Serialize(new ScriptingAssetSourceMeta + { + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.editor.csharp-script" + }) + ); }); fixture.Write("Consumer.cs", """ using LanguagePlugin; @@ -126,7 +152,7 @@ public async Task AuthoringAndIdeAcceptTheSameCSharp14Source() using InnoEngine.Scene; using InnoEngine.Serialization; - [StableTypeId("bf92a310-7446-4a19-81f3-0a02bd32f087")] + [StableTypeID("bf92a310-7446-4a19-81f3-0a02bd32f087")] public sealed class LanguageProbe : GameBehavior { [SerializableProperty] @@ -233,46 +259,6 @@ int Produce() Assert.DoesNotContain("CS8032", output, StringComparison.Ordinal); } - private static async Task BuildIdeAsync( - DotNetSdkDescriptor sdk, - string project, - string directory - ) { - using var output = new StringWriter(); - using var errors = new StringWriter(); - try - { - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, errors); - return output.ToString(); - } - catch (InvalidOperationException failure) - { - throw new InvalidOperationException(output + Environment.NewLine + errors, failure); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static WeakReference InvokePublicSemantics(string assemblyPath) - { - var lifetime = new AssemblyLoadContext("csharp14-semantics", isCollectible: true); - var retired = new WeakReference(lifetime); - try - { - using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); - Assembly assembly = lifetime.LoadFromStream(stream); - Func evaluate = assembly.GetType("LanguageSemantics", throwOnError: true)! - .GetMethod("Evaluate", BindingFlags.Public | BindingFlags.Static)!.CreateDelegate>(); - Assert.True(evaluate()); - } - finally - { - lifetime.Unload(); - } - return retired; - } - /// /// Invalidates reference and script artifacts when framework bytes change without changing the public contract. /// @@ -283,21 +269,30 @@ public void FrameworkContentChangesSelectNewArtifacts() using var fixture = new CompilerFixture(compilationEnvironment: environment); fixture.Write("Counter.cs", "public sealed class Counter { public int count { get; set; } }"); fixture.Rescan(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - ScriptCompilationInputs selected = new Inno.Build.SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + ScriptCompilationInputs selected = new SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); string destination = Path.Combine(fixture.projectRoot, "Framework"); Directory.CreateDirectory(destination); foreach (string path in selected.frameworkReferences) + { File.Copy(path, Path.Combine(destination, Path.GetFileName(path))); - environment.inputs = new ScriptCompilationInputs(selected.sdkIdentity, - Directory.EnumerateFiles(destination, "*.dll"), selected.predefinedSymbols); + } + environment.inputs = new ScriptCompilationInputs( + selected.sdkIdentity, + Directory.EnumerateFiles(destination, "*.dll"), + selected.predefinedSymbols + ); ScriptCompilationResult first = fixture.Compile(); Assert.True(first.success, string.Join(Environment.NewLine, first.diagnostics)); string referenceRoot = Path.Combine(fixture.projectRoot, "Library", "ScriptApi", "Runtime"); string[] references = Directory.GetDirectories(referenceRoot); - using (FileStream changed = new(Path.Combine(destination, "System.Runtime.dll"), FileMode.Append)) + using (var changed = new FileStream(Path.Combine(destination, "System.Runtime.dll"), FileMode.Append)) + { changed.WriteByte(0); + } ScriptCompilationResult second = fixture.Compile(); Assert.True(second.success, string.Join(Environment.NewLine, second.diagnostics)); Assert.NotEqual(first.outputDirectory, second.outputDirectory); @@ -312,7 +307,7 @@ public void FrameworkContentChangesSelectNewArtifacts() public void SourceDocumentationContentSelectsANewReferenceGeneration() { // This suite is serial. Only its own deployed XML sidecar is changed, and it is restored on failure. - string source = Path.ChangeExtension(typeof(Inno.Scene.SceneManager).Assembly.Location, ".xml"); + string source = Path.ChangeExtension(typeof(SceneManager).Assembly.Location, ".xml"); Assert.StartsWith(Path.GetFullPath(AppContext.BaseDirectory), Path.GetFullPath(source), StringComparison.OrdinalIgnoreCase); byte[] original = File.ReadAllBytes(source); DateTime timestamp = File.GetLastWriteTimeUtc(source); @@ -321,7 +316,8 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() try { XDocument document = XDocument.Parse(Encoding.UTF8.GetString(original)); - XElement member = document.Root!.Element("members")!.Elements("member") + XElement member = document.Root!.Element("members")! + .Elements("member") .Single(value => (string?)value.Attribute("name") == "T:Inno.Scene.SceneManager"); member.SetElementValue("summary", "Documentation generation Alpha."); document.Save(source); @@ -338,7 +334,8 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() Assert.NotEqual(first, second); Assert.Contains("generation Bravo.", File.ReadAllText(second), StringComparison.Ordinal); Assert.Equal(frozen, File.ReadAllBytes(first)); - XElement origin = XDocument.Load(second).Root!.Element("provenance")!.Elements("type") + XElement origin = XDocument.Load(second).Root!.Element("provenance")! + .Elements("type") .Single(value => (string?)value.Attribute("source") == "T:Inno.Scene.SceneManager"); Assert.Equal("T:InnoEngine.Scene.SceneManager", (string?)origin.Attribute("id")); } @@ -351,20 +348,68 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() string ReferenceDocumentation() { string project = Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj"); - XElement reference = XDocument.Load(project).Descendants("Reference") + XElement reference = XDocument.Load(project) + .Descendants("Reference") .Single(value => (string?)value.Attribute("Include") == "Inno.ScriptApi.Runtime"); return Path.ChangeExtension(Path.GetFullPath(reference.Element("HintPath")!.Value, fixture.projectRoot), ".xml"); } } - private sealed class MutableCompilationEnvironment : IScriptCompilationEnvironmentProvider + private static async Task BuildIdeAsync( + DotNetSdkDescriptor sdk, + string project, + string directory + ) { + using var output = new StringWriter(); + using var errors = new StringWriter(); + try + { + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], + directory, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors, + CancellationToken.None + ); + return output.ToString(); + } + catch (InvalidOperationException failure) + { + throw new InvalidOperationException(output + Environment.NewLine + errors, failure); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference InvokePublicSemantics(string assemblyPath) { - internal ScriptCompilationInputs inputs { get; set; } = null!; + var lifetime = new AssemblyLoadContext("csharp14-semantics", isCollectible: true); + var retired = new WeakReference(lifetime); + try + { + using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); + Assembly assembly = lifetime.LoadFromStream(stream); + Func evaluate = assembly.GetType("LanguageSemantics", throwOnError: true)! + .GetMethod("Evaluate", BindingFlags.Public | BindingFlags.Static)! + .CreateDelegate>(); + Assert.True(evaluate()); + } + finally + { + lifetime.Unload(); + } + return retired; + } + private sealed class MutableCompilationEnvironment : IScriptCompilationEnvironmentProvider + { public ScriptCompilationInputs Capture(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return inputs; } + + internal ScriptCompilationInputs inputs { get; set; } = null!; } } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs index 7eccaa4ca..b69cafa11 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs @@ -1,11 +1,13 @@ using System; using System.IO; +using System.Runtime.InteropServices; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Identity; +using Inno.Build; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Plugins.Authoring; @@ -27,9 +29,8 @@ internal sealed class CompilerFixture : IDisposable internal CompilerFixture( Action? configure = null, IScriptCompilationEnvironmentProvider? compilationEnvironment = null - ) - { - projectRoot = Path.Combine(Path.GetTempPath(), "InnoCompilerTests", Guid.NewGuid().ToString("N")); + ) { + this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoCompilerTests", Guid.NewGuid().ToString("N")); string assetsRoot = Path.Combine(projectRoot, "Assets"); string pluginsRoot = Path.Combine(projectRoot, "Plugins"); string libraryRoot = Path.Combine(projectRoot, "Library"); @@ -38,42 +39,64 @@ internal CompilerFixture( Directory.CreateDirectory(libraryRoot); m_identityScope = m_identities.EnterScope(); m_host = new EngineHostBuilder().UseMetadataSources( - new DotNetAssemblyCatalogSource(typeof(CompilerFixture).Assembly, - typeof(GameBehavior).Assembly, typeof(ScriptCompiler).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + new DotNetAssemblyCatalogSource( + typeof(CompilerFixture).Assembly, + typeof(GameBehavior).Assembly, + typeof(ScriptCompiler).Assembly + ), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); m_diagnosticScope = m_host.diagnostics.EnterScope(); configure?.Invoke(projectRoot, m_host.serialization); var sources = new PluginSourceService(m_host.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); AssetPipelineOptions options = AssetPipelineOptions.Create(assetsRoot, libraryRoot); - m_assets = new AssetPipeline(m_host.modules, m_host.types, m_host.serialization, - m_identities, m_host.diagnostics, m_host.logs, options with + m_assets = new AssetPipeline( + m_host.modules, + m_host.types, + m_host.serialization, + m_identities, + m_host.diagnostics, + m_host.logs, + options with { enableFileSystemWatcher = false, sourceMounts = [.. options.sourceMounts!, .. PluginSourceService.GetActivatableMounts(scan)] - }); + } + ); m_settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.Combine(projectRoot, "Settings.Project.inno")), - m_host.types, m_host.serialization, new ProjectId("tests.compiler"), - AssetSerializationContext.Create(m_assets)); - m_plugins = new PluginEnvironment(m_assets, m_settings, m_host.serialization, - pluginsRoot, libraryRoot, scan, m_host.modules.generations); + m_host.types, + m_host.serialization, + new ProjectID("tests.compiler"), + AssetSerializationContext.Create(m_assets) + ); + m_plugins = new PluginEnvironment( + m_assets, + m_settings, + m_host.serialization, + pluginsRoot, + libraryRoot, + scan, + m_host.modules.generations + ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - compiler = new ScriptCompiler( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + this.compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, - compilationEnvironment = compilationEnvironment ?? new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) - }, m_assets, m_plugins); + compilationEnvironment = compilationEnvironment ?? new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + }, + m_assets, + m_plugins + ); } - internal string projectRoot { get; } - - internal ScriptCompiler compiler { get; } - - /// + /// public void Dispose() { m_plugins.Dispose(); @@ -85,6 +108,10 @@ public void Dispose() Directory.Delete(projectRoot, recursive: true); } + internal string projectRoot { get; } + + internal ScriptCompiler compiler { get; } + internal void Write( string relativePath, string source diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs index 836f60248..22d325775 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs @@ -1,11 +1,11 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Scripting.Compiler.Tests; @@ -37,10 +37,14 @@ public async Task GeneratedProjectsIgnoreAmbientBuildConfiguration() """); } - DotNetSdkDescriptor sdk = await ResolveSdk(Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj")); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + DotNetSdkDescriptor sdk = await ResolveSdkAsync(Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj")); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "build", "InnoProject.sln", "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - fixture.projectRoot, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + fixture.projectRoot, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); } /// @@ -54,7 +58,8 @@ public async Task NestedSolutionRestoresOnlyItsOwnProjects() { string repository = TestRepository.GetRoot(typeof(IdeProjectIsolationTests).Assembly); using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( - Path.Combine(repository, "artifacts", "acceptance", "nested-solution-tests")); + Path.Combine(repository, "artifacts", "acceptance", "nested-solution-tests") + ); string project = Path.Combine(owner.directory, "Nested.csproj"); File.WriteAllText(project, """ @@ -71,20 +76,32 @@ public async Task NestedSolutionRestoresOnlyItsOwnProjects() """); - DotNetSdkDescriptor sdk = await ResolveSdk(project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + DotNetSdkDescriptor sdk = await ResolveSdkAsync(project); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "new", "sln", "--format", "sln", "--name", "Nested"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "sln", "Nested.sln", "add", "Nested.csproj"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "restore", "Nested.sln", "--disable-build-servers", "-m:1", "-nr:false"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); Assert.True(File.Exists(Path.Combine(owner.directory, "obj", "project.assets.json"))); } - private static ValueTask ResolveSdk(string project) + private static ValueTask ResolveSdkAsync(string project) { string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); return DotNetSdkResolver.ResolveAsync(host, project); diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs index 46ed5432b..192f253b0 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs @@ -18,7 +18,9 @@ public sealed class ScriptCachePublicationTests /// /// Publishes a complete generation after a temporary filesystem reader releases its staging borrow. /// - /// The completed public compiler and artifact-equivalence checks. + /// + /// The completed public compiler and artifact-equivalence checks. + /// [WindowsDirectorySharingFact] public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThem() { @@ -31,16 +33,23 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe Dictionary expected = Directory.EnumerateFiles(previous, "*.dll") .ToDictionary(static path => Path.GetFileName(path)!, File.ReadAllBytes, StringComparer.Ordinal); string root = Path.GetDirectoryName(previous)!; - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(previous), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(previous), + StringComparison.OrdinalIgnoreCase + ); Directory.Delete(previous, recursive: true); HashSet existing = Directory.EnumerateFiles(root, "*.dll", SearchOption.AllDirectories) .ToHashSet(StringComparer.OrdinalIgnoreCase); - using var observer = new StagingReader(root, existing, - $"Reused cached {baseline.compiledAssemblyNames[^1]} assembly artifact."); + using var observer = new StagingReader( + root, + existing, + $"Reused cached {baseline.compiledAssemblyNames[^1]} assembly artifact." + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token).AsTask(); + .CompileAuthoringGenerationAsync(observer, cancellationToken: cancellation.Token) + .AsTask(); Exception? compilationFailure = null; bool captured = false; try @@ -48,15 +57,22 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe await observer.captured.WaitAsync(TimeSpan.FromSeconds(20)); captured = true; await Task.Delay(150); - Assert.False(compilation.IsCompleted, - compilation.Exception?.ToString() ?? "A staged assembly borrow must delay publication."); + Assert.False( + compilation.IsCompleted, + compilation.Exception?.ToString() ?? "A staged assembly borrow must delay publication." + ); } finally { if (!captured) + { cancellation.Cancel(); + } observer.Dispose(); - compilationFailure = await Record.ExceptionAsync(async () => { _ = await compilation; }); + compilationFailure = await Record.ExceptionAsync(async () => + { + _ = await compilation; + }); } Assert.Null(compilationFailure); ScriptCompilationResult result = await compilation; @@ -65,13 +81,17 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe Assert.Empty(result.compiledAssemblyNames); Assert.Equal(baseline.compiledAssemblyNames, result.reusedAssemblyNames); foreach ((string name, byte[] bytes) in expected) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(result.outputDirectory!, name))); + } } /// /// Cancels a blocked publication without changing another completed generation. /// - /// The completed failure, previous-generation and explicit retry checks. + /// + /// The completed failure, previous-generation and explicit retry checks. + /// [WindowsDirectorySharingFact] public Task CanceledPublicationPreservesThePreviousGenerationAndAllowsAnotherRequest() => Task.Run(() => VerifyRejectedPublication(cancel: true)); @@ -79,7 +99,9 @@ public Task CanceledPublicationPreservesThePreviousGenerationAndAllowsAnotherReq /// /// Reports a persistent filesystem block without publishing incomplete or replacing previous artifacts. /// - /// The completed failure, previous-generation and explicit retry checks. + /// + /// The completed failure, previous-generation and explicit retry checks. + /// [WindowsDirectorySharingFact] public Task BlockedPublicationPreservesThePreviousGenerationAndAllowsAnotherRequest() => Task.Run(() => VerifyRejectedPublication(cancel: false)); @@ -87,7 +109,9 @@ public Task BlockedPublicationPreservesThePreviousGenerationAndAllowsAnotherRequ /// /// Preserves a rejected cache tree until its reader releases ownership and an explicit repair commits. /// - /// The completed replacement failure, byte-preservation and repair checks. + /// + /// The completed replacement failure, byte-preservation and repair checks. + /// [WindowsDirectorySharingFact] public Task BlockedReplacementPreservesTheEntireExistingTreeAndAllowsRepair() => Task.Run(VerifyRejectedReplacement); @@ -99,8 +123,11 @@ private static void VerifyRejectedReplacement() ScriptCompilationResult baseline = fixture.Compile(); Assert.True(baseline.success, string.Join(Environment.NewLine, baseline.diagnostics)); string publication = Assert.IsType(baseline.outputDirectory); - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(publication), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(publication), + StringComparison.OrdinalIgnoreCase + ); Dictionary original = Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) .ToDictionary(path => Path.GetRelativePath(publication, path), File.ReadAllBytes, StringComparer.Ordinal); string assembly = Directory.EnumerateFiles(publication, "*.dll").First(); @@ -111,22 +138,32 @@ private static void VerifyRejectedReplacement() { Exception? failure = Record.Exception(() => fixture.Compile()); Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); - Assert.Equal(rejected.Keys.Order(StringComparer.Ordinal), + Assert.Equal( + rejected.Keys.Order(StringComparer.Ordinal), Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) - .Select(path => Path.GetRelativePath(publication, path)).Order(StringComparer.Ordinal)); + .Select(path => Path.GetRelativePath(publication, path)) + .Order(StringComparer.Ordinal) + ); foreach ((string path, byte[] bytes) in rejected) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(publication, path))); + } } ScriptCompilationResult repaired = fixture.Compile(); Assert.True(repaired.success, string.Join(Environment.NewLine, repaired.diagnostics)); Assert.Equal(publication, repaired.outputDirectory); Assert.Empty(repaired.compiledAssemblyNames); - Assert.Equal(original.Keys.Order(StringComparer.Ordinal), + Assert.Equal( + original.Keys.Order(StringComparer.Ordinal), Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) - .Select(path => Path.GetRelativePath(publication, path)).Order(StringComparer.Ordinal)); + .Select(path => Path.GetRelativePath(publication, path)) + .Order(StringComparer.Ordinal) + ); foreach ((string path, byte[] bytes) in original) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(publication, path))); + } } private static void VerifyRejectedPublication(bool cancel) @@ -144,27 +181,40 @@ private static void VerifyRejectedPublication(bool cancel) string publication = Assert.IsType(candidate.outputDirectory); Assert.NotEqual(lastGood, publication); Assert.NotEmpty(candidate.compiledAssemblyNames); - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(publication), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(publication), + StringComparison.OrdinalIgnoreCase + ); string root = Path.GetDirectoryName(publication)!; Directory.Delete(publication, recursive: true); HashSet existing = Directory.EnumerateFiles(root, "*.dll", SearchOption.AllDirectories) .ToHashSet(StringComparer.OrdinalIgnoreCase); - using var observer = new StagingReader(root, existing, - $"Reused cached {candidate.compiledAssemblyNames[^1]} assembly artifact."); + using var observer = new StagingReader( + root, + existing, + $"Reused cached {candidate.compiledAssemblyNames[^1]} assembly artifact." + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token).AsTask(); + .CompileAuthoringGenerationAsync(observer, cancellationToken: cancellation.Token) + .AsTask(); try { observer.captured.WaitAsync(TimeSpan.FromSeconds(20)).GetAwaiter().GetResult(); if (cancel) + { cancellation.Cancel(); + } Exception? failure = Record.Exception(() => compilation.WaitAsync(TimeSpan.FromSeconds(10)).GetAwaiter().GetResult()); if (cancel) + { Assert.IsAssignableFrom(failure); + } else + { Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); + } } finally { @@ -175,13 +225,17 @@ private static void VerifyRejectedPublication(bool cancel) Assert.False(Directory.Exists(publication)); foreach ((string path, byte[] bytes) in saved) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(lastGood, path))); + } ScriptCompilationResult recovered = fixture.Compile(); Assert.True(recovered.success, string.Join(Environment.NewLine, recovered.diagnostics)); Assert.Equal(publication, recovered.outputDirectory); Assert.Empty(recovered.compiledAssemblyNames); foreach ((string path, byte[] bytes) in saved) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(lastGood, path))); + } } private sealed class StagingReader : IProgress, IDisposable @@ -204,17 +258,20 @@ string stage m_stage = stage; } - /// + /// public void Report(ScriptCompilationProgress value) { lock (m_sync) { if (m_retired || m_reader is not null || value.stage != m_stage) + { return; + } try { string[] candidates = Directory.EnumerateFiles(m_root, "*.dll", SearchOption.AllDirectories) - .Where(path => !m_existing.Contains(path)).ToArray(); + .Where(path => !m_existing.Contains(path)) + .ToArray(); Assert.NotEmpty(candidates); m_reader = new FileStream(candidates[0], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); m_captured.TrySetResult(true); @@ -227,7 +284,7 @@ public void Report(ScriptCompilationProgress value) } } - /// + /// public void Dispose() { lock (m_sync) @@ -243,11 +300,15 @@ public void Dispose() private sealed class WindowsDirectorySharingFactAttribute : FactAttribute { - /// Marks the Windows directory-sharing fixture as unexecuted on other hosts. + /// + /// Marks the Windows directory-sharing fixture as unexecuted on other hosts. + /// public WindowsDirectorySharingFactAttribute() { if (!OperatingSystem.IsWindows()) - Skip = "This fixture requires Windows directory rename sharing semantics."; + { + this.Skip = "This fixture requires Windows directory rename sharing semantics."; + } } } } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs index a3da3069f..d509d9456 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading; -using Inno.Build; using Xunit; +using Inno.Build; namespace Inno.Scripting.Compiler.Tests; @@ -14,8 +14,10 @@ public sealed class SdkCompilationInputsTests public void SelectedSdkSuppliesFrameworkSymbolsAndIdeReferences() { using var fixture = new CompilerFixture(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); ScriptCompilationInputs inputs = new SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); Assert.Contains("NET10_0", inputs.predefinedSymbols); Assert.Contains("NET10_0_OR_GREATER", inputs.predefinedSymbols); @@ -37,8 +39,12 @@ public sealed class FrameworkSymbols { } Assert.Contains("ValidateInnoScriptSdk", project, StringComparison.Ordinal); Assert.Contains("true", project, StringComparison.Ordinal); foreach (string path in inputs.frameworkReferences) + { Assert.Contains(path.Replace("&", "&", StringComparison.Ordinal), project, StringComparison.Ordinal); - Assert.Empty(Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library", "Scripting"), "*.csproj", SearchOption.AllDirectories)); + } + Assert.Empty( + Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library", "Scripting"), "*.csproj", SearchOption.AllDirectories) + ); } [Fact] @@ -61,8 +67,10 @@ public void CancelledSdkEvaluationCreatesNoPublishedInputs() using var fixture = new CompilerFixture(); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var provider = new SdkScriptCompilationEnvironment(host, fixture.projectRoot); Assert.ThrowsAny(() => provider.Capture(cancellation.Token)); Assert.Empty(Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library"), "*.csproj", SearchOption.AllDirectories)); diff --git a/tests/source/Inno.Testing.Source/TestRepository.cs b/tests/source/Inno.Testing.Source/TestRepository.cs index 05545bc85..57345e4dc 100644 --- a/tests/source/Inno.Testing.Source/TestRepository.cs +++ b/tests/source/Inno.Testing.Source/TestRepository.cs @@ -35,13 +35,19 @@ public static class TestRepository AssemblyMetadataAttribute? declaration = testAssembly.GetCustomAttributes() .SingleOrDefault(static attribute => attribute.Key == C_ARTIFACTS_METADATA); if (declaration is null) + { return null; + } string? directory = declaration.Value; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the absolute SDK artifacts owner recorded by their project."); + } directory = GetProcessBinding(testAssembly, "INNO_TESTING_ARTIFACTS_PATH") ?? directory; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the absolute SDK artifacts owner recorded by their project."); + } return Path.GetFullPath(directory); } @@ -68,11 +74,13 @@ public static string GetRoot(Assembly testAssembly) string? directory = testAssembly.GetCustomAttributes() .SingleOrDefault(static attribute => attribute.Key == C_ROOT_METADATA)?.Value; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the source checkout declared by their SDK project."); + } directory = GetProcessBinding(testAssembly, "INNO_TESTING_REPOSITORY_ROOT") ?? directory; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory) - || !File.Exists(Path.Combine(directory, "InnoEngine.sln"))) - { + || !File.Exists(Path.Combine(directory, "InnoEngine.sln")) + ) { throw new InvalidOperationException("Tests require the source checkout declared by their SDK project."); } @@ -85,12 +93,18 @@ string variable ) { string? owner = Environment.GetEnvironmentVariable("INNO_TESTING_ARTIFACTS_PATH"); if (owner is null || testAssembly.IsDynamic || string.IsNullOrWhiteSpace(testAssembly.Location)) + { return null; + } if (string.IsNullOrWhiteSpace(owner) || !Path.IsPathFullyQualified(owner)) + { throw new InvalidOperationException("The test process must declare an absolute output owner before rebinding inputs."); + } string prefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(owner)) + Path.DirectorySeparatorChar; if (!Path.GetFullPath(testAssembly.Location).StartsWith(prefix, StringComparison.Ordinal)) + { return null; + } return Environment.GetEnvironmentVariable(variable); } } diff --git a/tests/storage/Inno.Storage.Tests/StorageTests.cs b/tests/storage/Inno.Storage.Tests/StorageTests.cs index fdf72b13f..9c3abd09a 100644 --- a/tests/storage/Inno.Storage.Tests/StorageTests.cs +++ b/tests/storage/Inno.Storage.Tests/StorageTests.cs @@ -1,18 +1,17 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.Storage.FileSystem; -using Inno.Storage.Runtime; +using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; +using Inno.Storage.Runtime; namespace Inno.Storage.Tests; @@ -85,7 +84,9 @@ public async Task DirectAdapterDisposalDoesNotDestroyAnActiveWritesSemaphore() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -110,7 +111,9 @@ public async Task FileSystemAdapterAtomicallyStoresAndListsValues() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -143,9 +146,13 @@ public void ExecutionScopesRequireLastInFirstOutDisposal() finally { if (Directory.Exists(firstRoot)) + { Directory.Delete(firstRoot, recursive: true); + } if (Directory.Exists(secondRoot)) + { Directory.Delete(secondRoot, recursive: true); + } } } @@ -156,34 +163,39 @@ public void RuntimeSubsystemBindsStorageForTheCompleteFrame() try { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(StorageTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(StorageTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var options = new RuntimeSessionOptions { kind = RuntimeSessionKind.Play, - applicationId = "tests.storage", + applicationID = "tests.storage", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "tests.storage"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createSubsystems = owner => [ new StorageRuntimeFactory(context => - new FileSystemApplicationStorage(Path.Combine( - root, "tests.storage", - "Storage"))), + new FileSystemApplicationStorage(Path.Combine(root, "tests.storage", "Storage"))), new StorageProbeFactory() ] }; using (RuntimeSession session = host.CreateSession(options)) + { session.Tick(0.01f); + } Assert.Throws(() => _ = StorageExecutionContext.current); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -193,35 +205,55 @@ private static string CreateTemporaryRoot() private sealed class StorageProbeFactory : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( - new RuntimeSubsystemId("tests.storage.probe"), - dependencies: [new RuntimeSubsystemId("inno.runtime.storage")]); + new RuntimeSubsystemID("tests.storage.probe"), + dependencies: [new RuntimeSubsystemID("inno.runtime.storage")] + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new StorageProbe(); } private sealed class StorageProbe : RuntimeSubsystem { - protected override void OnUpdate(RuntimeFrame frame) - => Assert.NotNull(StorageExecutionContext.current); + protected override void OnUpdate(RuntimeFrame frame) => Assert.NotNull(StorageExecutionContext.current); } private sealed class PendingStorage : IApplicationStorage, IDisposable { - internal TaskCompletionSource completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal CancellationToken token { get; private set; } - internal bool disposed { get; private set; } - internal ReadOnlyMemory value { get; private set; } - public ValueTask WriteAsync(StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default) - { + public ValueTask WriteAsync( + StorageKey key, + ReadOnlyMemory value, + CancellationToken cancellationToken = default + ) { token = cancellationToken; this.value = value; return new ValueTask(completion.Task); } - public ValueTask ExistsAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(false); - public ValueTask ReadAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(null); - public ValueTask DeleteAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(false); - public ValueTask> ListAsync(StorageKey? prefix = null, CancellationToken cancellationToken = default) - => ValueTask.FromResult>(Array.Empty()); + + public ValueTask ExistsAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(false); + + public ValueTask ReadAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(null); + + public ValueTask DeleteAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(false); + + public ValueTask> ListAsync( + StorageKey? prefix = null, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult>([]); + public void Dispose() => disposed = true; + + internal TaskCompletionSource completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal CancellationToken token { get; private set; } + internal bool disposed { get; private set; } + internal ReadOnlyMemory value { get; private set; } } } diff --git a/tests/text/Inno.Text.Tests/TextServiceTests.cs b/tests/text/Inno.Text.Tests/TextServiceTests.cs index 22ff57dac..e5e40aece 100644 --- a/tests/text/Inno.Text.Tests/TextServiceTests.cs +++ b/tests/text/Inno.Text.Tests/TextServiceTests.cs @@ -1,9 +1,9 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Reflection; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.Text.FreeTypeHarfBuzz; using Inno.Assets; using Inno.Assets.Pipeline; @@ -14,7 +14,6 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Text.Assets; -using Xunit; namespace Inno.Text.Tests; @@ -39,7 +38,9 @@ public TextServiceTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(TextServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(TextServiceTests).Assembly) + }); _ = Assembly.Load("Inno.Text.Assets"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); @@ -62,14 +63,13 @@ public void ImporterPublishesMetadataAndSeparateEncodedFont() File.WriteAllBytes(Path.Combine(m_assets, "Interface.ttf"), source); using AssetLoader loader = CreateLoader(); - FontAsset font = Assert.IsType( - loader.Load(AssetPath.Project("Interface.ttf"), typeof(FontAsset))); + FontAsset font = Assert.IsType(loader.Load(AssetPath.Project("Interface.ttf"), typeof(FontAsset))); Assert.Equal(1, font.metadata!.Value.faceCount); Assert.Equal(source.Length, font.metadata.Value.encodedByteLength); - Assert.True(loader.TryGetArtifact(font.identity.persistentId, "font-data", out AssetArtifactInfo? data)); + Assert.True(loader.TryGetArtifact(font.identity.persistentID, "font-data", out AssetArtifactInfo? data)); Assert.NotNull(data); - using ArtifactLease encoded = loader.AcquireArtifact(font.identity.persistentId, "font-data"); + using ArtifactLease encoded = loader.AcquireArtifact(font.identity.persistentID, "font-data"); Assert.Equal(source, encoded.ReadAllBytes()); } @@ -79,16 +79,12 @@ public void NativeBackendShapesAndRasterizesUnicodeText() using var backend = new FreeTypeHarfBuzzTextBackend(); TextFontHandle font = backend.LoadFont(File.ReadAllBytes(FontPath()), 0); - TextLayout layout = backend.Shape( - font, - "Hello, UI!", - new TextStyle(28f), - TextShapingOptions.automatic); + TextLayout layout = backend.Shape(font, "Hello, UI!", new TextStyle(28f), TextShapingOptions.automatic); Assert.NotEmpty(layout.glyphs); Assert.True(layout.width > 0f); Assert.True(layout.metrics.lineHeight > 0f); - GlyphBitmap bitmap = backend.Rasterize(font, layout.glyphs[0].glyphId, 28f); + GlyphBitmap bitmap = backend.Rasterize(font, layout.glyphs[0].glyphID, 28f); Assert.True(bitmap.width > 0); Assert.True(bitmap.height > 0); Assert.Equal(bitmap.width * bitmap.height, bitmap.pixels.Length); @@ -103,12 +99,13 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static string FontPath() - => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); + private static string FontPath() => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs index 72db4003a..7b0bf2195 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs @@ -13,8 +13,14 @@ public AgentDocumentTests() { Directory.CreateDirectory(m_root); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); - foreach (string category in new[] { "rulebook", "records", "records/plans", "records/decisions", "records/acceptance", "records/history" }) - { + foreach (string category in new[] { + "rulebook", + "records", + "records/plans", + "records/decisions", + "records/acceptance", + "records/history" + }) { string directory = Path.Combine(m_root, ".agents", category); Directory.CreateDirectory(directory); File.WriteAllText(Path.Combine(directory, "README.md"), "# Category\n"); @@ -24,17 +30,34 @@ public AgentDocumentTests() [Fact] public void AgentLinksUseParsedHeadingsReferencesAndExplicitAnchorsWithoutReadingCodeLinks() { - File.WriteAllText(Path.Combine(m_root, "AGENTS.md"), "# Entry\n\n[Guide][guide]\n\n[guide]: .agents/rulebook/README.md#hello-world\n\n[Explicit](.agents/rulebook/README.md#contract)\n\n~~~text\n[missing](missing.md)\n~~~\n"); + File.WriteAllText( + Path.Combine(m_root, "AGENTS.md"), + "# Entry\n\n[Guide][guide]\n\n[guide]: .agents/rulebook/README.md#hello-world\n\n[Explicit](.agents/rulebook/README.md#contract)\n\n~~~text\n[missing](missing.md)\n~~~\n" + ); File.WriteAllText(Path.Combine(m_root, ".agents/rulebook/README.md"), "# Hello *World*\n\n\n"); Assert.Equal(0, ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").exitCode); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n[Broken](.agents/rulebook/README.md#absent)\n"); - var rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); + (int exitCode, string output) rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); Assert.Equal(1, rejected.exitCode); Assert.Contains("missing anchor", rejected.output); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n[Missing](absent.md)\n"); Assert.Contains("missing path", ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").output); } + [Fact] + public void SkillsAreListedInTheRootInstructions() + { + string skill = Path.Combine(m_root, ".agents/skills/example"); + Directory.CreateDirectory(skill); + File.WriteAllText(Path.Combine(skill, "SKILL.md"), "---\nname: example\ndescription: Example workflow.\n---\n\nSteps.\n"); + File.WriteAllText(Path.Combine(m_root, "AGENTS.md"), "# Entry\n"); + (int exitCode, string output) rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); + Assert.Equal(1, rejected.exitCode); + Assert.Contains("Skill is not listed in AGENTS.md: example", rejected.output); + File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n- [example](.agents/skills/example/SKILL.md): example workflow.\n"); + Assert.Equal(0, ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").exitCode); + } + [Theory] [InlineData("--wiki")] [InlineData("--wiki-only")] diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs index eb3ab9956..8cfdb466a 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs @@ -22,9 +22,11 @@ bool rejected File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string project = Path.Combine(root, projectLocation); Directory.CreateDirectory(project); - File.WriteAllText(Path.Combine(project, Path.GetFileName(project) + ".csproj"), + File.WriteAllText( + Path.Combine(project, Path.GetFileName(project) + ".csproj"), "net10.0" - + ""); + + "" + ); (_, string output) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, output.Contains("the interop runtime dependency belongs", StringComparison.Ordinal)); Assert.DoesNotContain("does not resolve to a repository project", output, StringComparison.Ordinal); @@ -32,7 +34,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -50,23 +54,27 @@ string expected Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string relative = scenario == "target" - ? "platforms/WindowsX64/player/Inno.Player.WindowsX64" - : "src/foundation/core/Inno.Core.Probe"; + ? "platforms/WindowsX64/player/Inno.Player.WindowsX64" + : "src/foundation/core/Inno.Core.Probe"; string project = Path.Combine(root, relative); Directory.CreateDirectory(project); string properties = scenario == "target" ? "Exeplayerwindows-x64windows-x64" : string.Empty; - File.WriteAllText(Path.Combine(project, Path.GetFileName(project) + ".csproj"), + File.WriteAllText( + Path.Combine(project, Path.GetFileName(project) + ".csproj"), "net10.0" - + properties + ""); + + properties + "" + ); string imported; if (scenario == "reference") { string upper = Path.Combine(root, "platforms/MacOSArm64/runtime/Probe"); Directory.CreateDirectory(upper); - File.WriteAllText(Path.Combine(upper, "Probe.csproj"), - "net10.0"); + File.WriteAllText( + Path.Combine(upper, "Probe.csproj"), + "net10.0" + ); imported = ""; } else if (scenario == "source") @@ -77,11 +85,15 @@ string expected imported = ""; } else + { imported = "macos-arm64"; + } File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), "" + imported + ""); string dotnet = Path.GetFullPath("../../../dotnet", RuntimeEnvironment.GetRuntimeDirectory()); if (OperatingSystem.IsWindows()) + { dotnet += ".exe"; + } string graph = Path.Combine(root, "evaluated.json"); (int code, string output) = ArchitectureCommandFixture.Run(root, "--dotnet", dotnet, "--project-graph", graph); Assert.Equal(1, code); @@ -93,7 +105,9 @@ string expected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -101,7 +115,7 @@ string expected [InlineData("internal sealed class Probe { void Apply(int first, int second) { } }", true)] [InlineData("internal sealed class Probe(int first, int second) { }", true)] [InlineData("internal sealed class Probe { System.Func factory = (first, second) => first + second; }", true)] - [InlineData("internal sealed class Probe\n{\n void Apply(\n int first,\n int second\n ) { }\n}", false)] + [InlineData("internal sealed class Probe\n{\n private void Apply(\n int first,\n int second\n ) { }\n}", false)] public void CliChecksHandwrittenMultiParameterDeclarations( string source, bool rejected @@ -110,28 +124,42 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); File.WriteAllText(Path.Combine(root, "src", "Probe.cs"), source); (_, string output) = ArchitectureCommandFixture.Run(root); - Assert.Equal(rejected, output.Contains("place each parameter", StringComparison.Ordinal)); + Assert.Equal(rejected, output.Contains("P-01: Expand the parameter list", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } [Theory] - [InlineData("Directory.Build.props", "true", "implicit usings", true)] + [InlineData( + "Directory.Build.props", + "true", + "implicit usings", + true + )] [InlineData("build/Probe.targets", "", "MSBuild Using", true)] [InlineData("tests/Probe.cs", "global using System;", "global using", true)] [InlineData("build/Probe.cs.txt", "global using System;", "global using", true)] - [InlineData("tests/Probe.cs", "using System; // global using is prohibited\ninternal class Probe { }", "global using", false)] - [InlineData("tests/Probe.cs", "internal class Probe { const string Message = \"global using System;\"; }", "global using", false)] + [InlineData("tests/Probe.cs", "using System; // global using is prohibited\n\ninternal class Probe;\n", "global using", false)] + [InlineData( + "tests/Probe.cs", + "internal sealed class Probe\n{\n const string Message = \"global using System;\";\n}\n", + "global using", + false + )] public void CliRejectsCompilationWideImportsAcrossSourceAndBuildInputs( string relative, string content, @@ -152,27 +180,99 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } [Theory] [InlineData("src/services/audio/Probe.cs", "global using System;", "global using", true)] - [InlineData("src/composition/player/Inno.Player.Runtime/Probe.cs", "internal class Probe { private BgfxDevice device; }", "backend-neutral", true)] - [InlineData("src/content/assets/Probe.cs", "internal class Probe { void Read() { context.With(resolver); } }", "owner-complete", true)] + [InlineData( + "src/composition/player/Inno.Player.Runtime/Probe.cs", + "internal class Probe { private BgfxDevice device; }", + "backend-neutral", + true + )] + [InlineData( + "src/content/assets/Probe.cs", + "internal class Probe { void Read() { context.With(resolver); } }", + "owner-complete", + true + )] [InlineData("src/services/audio/Probe.cs", "public class Probe { public MaEngine engine; }", "native implementation", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { OnCleanupFailed(phase, failure); } }", "diagnostic-only", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); DrawRow(); if (i == 1) break; Ui.PopId(); } } }", "presentation loop ID scopes", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); try { DrawRow(); if (i == 1) break; } finally { Ui.PopId(); } } } }", "presentation loop ID scopes", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; using Other = Inno.Editor.ImGui.ImGui; internal class Probe { }", "multiple presentation aliases", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; using NativeUi = Inno.Native.ImGui.ImGui; internal class Probe { }", "multiple presentation aliases", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "/// \n/// Removed identity.\n/// \n/// \n/// Actual section.\n/// \ninternal class Probe { }", "multiple XML summary elements", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "/// \n/// Actual section.\n/// \ninternal class Probe { }", "multiple XML summary elements", false)] - [InlineData("src/services/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); DrawRow(); Ui.PopId(); } } }", "presentation loop ID scopes", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { collector.PushId(i); DrawRow(); collector.PopId(); } } }", "presentation loop ID scopes", false)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (RetirementPendingException) { throw; } } }", "wrapped pending ownership", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (Inno.Core.Execution.RetirementTimeoutException failure) { throw; } } }", "wrapped pending ownership", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (Exception error) when (RetirementPendingException.Find(error) is not null) { throw; } } }", "wrapped pending ownership", false)] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { OnCleanupFailed(phase, failure); } }", + "diagnostic-only", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushID(i); DrawRow(); if (i == 1) break; Ui.PopID(); } } }", + "presentation loop ID scopes", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui;\n\ninternal sealed class Probe\n{\n private void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n Ui.PushID(i);\n try\n {\n DrawRow();\n if (i == 1) break;\n }\n finally\n {\n Ui.PopID();\n }\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui; using Other = Inno.Editor.ImGui.ImGui; internal class Probe { }", + "multiple presentation aliases", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using NativeUi = Inno.Native.ImGui.ImGui;\nusing Ui = Inno.Editor.ImGui.ImGui;\n\ninternal sealed class Probe;\n", + "multiple presentation aliases", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "/// \n/// Removed identity.\n/// \n/// \n/// Actual section.\n/// \ninternal class Probe { }", + "multiple XML summary elements", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "/// \n/// Actual section.\n/// \ninternal sealed class Probe;\n", + "multiple XML summary elements", + false + )] + [InlineData( + "src/services/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui;\n\ninternal sealed class Probe\n{\n private void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n Ui.PushID(i);\n DrawRow();\n Ui.PopID();\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "internal sealed class Probe\n{\n private void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n collector.PushID(i);\n DrawRow();\n collector.PopID();\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { try { } catch (RetirementPendingException) { throw; } } }", + "wrapped pending ownership", + true + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { try { } catch (Inno.Core.Execution.RetirementTimeoutException failure) { throw; } } }", + "wrapped pending ownership", + true + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal sealed class Probe\n{\n private void Release()\n {\n try\n {\n Run();\n }\n catch (Exception error) when (RetirementPendingException.Find(error) is not null)\n {\n throw;\n }\n }\n}\n", + "wrapped pending ownership", + false + )] public void CliValidatesSourceContracts( string relative, string source, @@ -183,7 +283,9 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{BBD55508-6095-4D53-B0E4-59B04BFB9376}" @@ -204,7 +306,9 @@ bool rejected (int code, string output) = ArchitectureCommandFixture.Run(root); Assert.Equal(1, code); if (rejected) + { Assert.Contains(expected, output, StringComparison.OrdinalIgnoreCase); + } else { Assert.DoesNotContain(expected, output, StringComparison.OrdinalIgnoreCase); @@ -214,7 +318,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -236,7 +342,9 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Global @@ -244,11 +352,13 @@ bool rejected """); string bindings = Path.Combine(root, "backends", "Probe", "native", "Inno.Native.Probe", "Bindings"); Directory.CreateDirectory(bindings); - File.WriteAllText(Path.Combine(Path.GetDirectoryName(bindings)!, "Inno.Native.Probe.csproj"), + File.WriteAllText( + Path.Combine(Path.GetDirectoryName(bindings)!, "Inno.Native.Probe.csproj"), "net10.0" + "true" + (scenario == "missing-import" ? string.Empty : "") - + ""); + + "" + ); File.WriteAllText(Path.Combine(bindings, "bindgen.json"), "{}"); string definition = """ @@ -262,13 +372,23 @@ bool rejected { "escaped-input" => definition.Replace("bindgen.json", "../outside.json", StringComparison.Ordinal), "missing-input" => definition.Replace("bindgen.json", "missing.json", StringComparison.Ordinal), - "unknown-property" => definition.Replace("", "bridge.json", StringComparison.Ordinal), - "conditional" => definition.Replace("", "", StringComparison.Ordinal), + "unknown-property" => definition.Replace( + "", + "bridge.json", + StringComparison.Ordinal + ), + "conditional" => definition.Replace( + "", + "", + StringComparison.Ordinal + ), "platform-table" => definition.Replace("", "", StringComparison.Ordinal), _ => definition }; if (scenario != "missing-definition") + { File.WriteAllText(Path.Combine(bindings, "bindings.props"), definition); + } (int code, string output) = ArchitectureCommandFixture.Run(root); @@ -278,8 +398,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } - } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs index 0c5e3084c..bd3e0f68a 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs @@ -4,8 +4,8 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Tooling.Architecture.Tests; @@ -16,8 +16,15 @@ public sealed class ArchitectureOutputOwnerTests public async Task PublicContractsUseTheEvaluatedOutputOwnerInsteadOfStaleDefaultAssemblies() { string root = Path.Combine(Path.GetTempPath(), "InnoArchitectureOutputTests", Guid.NewGuid().ToString("N")); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(2)); try { @@ -42,57 +49,139 @@ public async Task PublicContractsUseTheEvaluatedOutputOwnerInsteadOfStaleDefault """); string source = Path.Combine(editor, "Probe.cs"); File.WriteAllText(source, "namespace Inno.Editor.Probe; public sealed class Probe { }"); - await Build([]); - File.WriteAllText(source, "namespace Inno.Editor.Probe; public sealed class Probe { public Inno.Core.Contract.Contract value { get; } = new(); }"); + await BuildAsync([]); + File.WriteAllText( + source, + "namespace Inno.Editor.Probe; public sealed class Probe { public Inno.Core.Contract.Contract value { get; } = new(); }" + ); string artifacts = Path.Combine(root, "owned-output"); - await Build(["-p:ArtifactsPath=" + artifacts]); + await BuildAsync(["-p:ArtifactsPath=" + artifacts]); string graph = Path.Combine(root, "graph.json"); - string correct = ArchitectureCommandFixture.Run(root, "--dotnet", host, - "--artifacts-path", artifacts, "--project-graph", graph).output; + string correct = ArchitectureCommandFixture.Run( + root, + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--project-graph", + graph + ).output; Assert.DoesNotContain("Inno.Core.Contract is an implementation dependency", correct, StringComparison.Ordinal); - Assert.Contains(artifacts.Replace('\\', '/'), File.ReadAllText(graph).Replace('\\', '/').Replace("//", "/"), StringComparison.OrdinalIgnoreCase); + Assert.Contains( + artifacts.Replace('\\', '/'), + File.ReadAllText(graph).Replace('\\', '/').Replace("//", "/"), + StringComparison.OrdinalIgnoreCase + ); string selectedOwner = Path.GetRelativePath(root, project).Replace('\\', '/'); - string selected = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner).output; + string selected = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner + ).output; Assert.DoesNotContain("unresolved public signature type", selected, StringComparison.Ordinal); Assert.DoesNotContain("output is missing", selected, StringComparison.Ordinal); string snapshot = Path.Combine(root, "sdk-graph.json"); - File.WriteAllText(snapshot, await ManagedProjectGraphCapture.CaptureAsync(root, host, - [project, Path.Combine(contract, "Inno.Core.Contract.csproj")], new Dictionary - { - ["Configuration"] = "Debug", ["ArtifactsPath"] = artifacts, - ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false", ["InnoProductRestore"] = "false" - }, cancellation.Token)); - string captured = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner, "--sdk-snapshot", snapshot).output; + File.WriteAllText( + snapshot, + await ManagedProjectGraphCapture.CaptureAsync( + root, + host, + [project, Path.Combine(contract, "Inno.Core.Contract.csproj")], + new Dictionary + { + ["Configuration"] = "Debug", + ["ArtifactsPath"] = artifacts, + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false", + ["InnoProductRestore"] = "false" + }, + cancellationToken: cancellation.Token + ) + ); + string captured = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner, + "--sdk-snapshot", + snapshot + ).output; Assert.DoesNotContain("unresolved public signature type", captured, StringComparison.Ordinal); Assert.DoesNotContain("output is missing", captured, StringComparison.Ordinal); string reference = Path.Combine(root, "api-reference.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", root, "--dotnet", host, - "--project", selectedOwner, "--output", reference])); - Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(["--engine-root", root, - "--dotnet", host, "--artifacts-path", artifacts, "--reference", reference, - "--output", Path.Combine(root, "api-validation.json")], cancellation.Token)); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + root, + "--dotnet", + host, + "--project", + selectedOwner, + "--output", + reference + ]) + ); + Assert.Equal( + 0, + await DocumentationReferences.ValidateApiAsync([ + "--engine-root", + root, + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--reference", + reference, + "--output", + Path.Combine(root, "api-validation.json") + ], cancellation.Token) + ); - File.WriteAllText(project, File.ReadAllText(project).Replace("Include=", "PrivateAssets=\"compile\" Include=", StringComparison.Ordinal)); - string rejected = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner).output; + File.WriteAllText( + project, + File.ReadAllText(project).Replace("Include=", "PrivateAssets=\"compile\" Include=", StringComparison.Ordinal) + ); + string rejected = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner + ).output; Assert.Contains("public/protected API exposes Inno.Core.Contract", rejected, StringComparison.Ordinal); - async Task Build(string[] properties) - { - await ToolchainEnvironment.RunAsync(host, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet", .. properties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); - } + async Task BuildAsync(string[] properties) + => await ToolchainEnvironment.RunAsync( + host, + ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet", .. properties], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs index b9b1962e5..a6a5f585b 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs @@ -5,6 +5,7 @@ using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -16,8 +17,8 @@ public sealed class ArchitectureSymbolTests public void SourceOnlyDefersInheritedXmlButCompiledAcceptanceStillRejectsAnUnrelatedMethod() { using var fixture = new SymbolFixture(); - const string project = "src/foundation/core/Inno.Core.Probe"; - const string source = """ + const string C_PROJECT = "src/foundation/core/Inno.Core.Probe"; + const string C_SOURCE = """ namespace Inno.Core.Probe; public sealed class Probe { @@ -25,21 +26,27 @@ public sealed class Probe public int Read() => 1; } """; - fixture.Compile(project, "Inno.Core.Probe", source); - fixture.WriteSource(project, source); - Assert.DoesNotContain("inheritdoc requires a documented overridden or implemented contract", - fixture.Run("--source-only"), StringComparison.Ordinal); - Assert.Contains("inheritdoc requires a documented overridden or implemented contract", - fixture.Run("--metadata-only", "--api-project", project + "/Inno.Core.Probe.csproj"), StringComparison.Ordinal); + fixture.Compile(C_PROJECT, "Inno.Core.Probe", C_SOURCE); + fixture.WriteSource(C_PROJECT, C_SOURCE); + Assert.DoesNotContain( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run("--source-only"), + StringComparison.Ordinal + ); + Assert.Contains( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run("--metadata-only", "--api-project", C_PROJECT + "/Inno.Core.Probe.csproj"), + StringComparison.Ordinal + ); } [Fact] public void InheritedDocumentationUsesTheOwningProjectInsteadOfACopiedDependency() { using var fixture = new SymbolFixture(); - const string contractProject = "src/foundation/core/Inno.Core.Contract"; - const string consumerProject = "src/composition/editor/framework/Inno.Editor.Probe"; - string contract = fixture.Compile(contractProject, "Inno.Core.Contract", """ + const string C_CONTRACT_PROJECT = "src/foundation/core/Inno.Core.Contract"; + const string C_CONSUMER_PROJECT = "src/composition/editor/framework/Inno.Editor.Probe"; + string contract = fixture.Compile(C_CONTRACT_PROJECT, "Inno.Core.Contract", """ namespace Inno.Core.Contract; public interface IContract { @@ -60,14 +67,17 @@ public class Probe : Inno.Core.Contract.IContract public int Read() => 1; } """; - string consumer = fixture.Compile(consumerProject, "Inno.Editor.Probe", source, contract); - fixture.WriteSource(consumerProject, source); + string consumer = fixture.Compile(C_CONSUMER_PROJECT, "Inno.Editor.Probe", source, contract); + fixture.WriteSource(C_CONSUMER_PROJECT, source); string copied = Path.Combine(Path.GetDirectoryName(consumer)!, Path.GetFileName(contract)); File.Copy(contract, copied); File.WriteAllText(Path.ChangeExtension(copied, ".xml"), ""); - Assert.DoesNotContain("inheritdoc requires a documented overridden or implemented contract", - fixture.Run(), StringComparison.Ordinal); + Assert.DoesNotContain( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run(), + StringComparison.Ordinal + ); } [Theory] @@ -98,17 +108,17 @@ public void InheritedDocumentationRequiresACompleteImplementedContract( bool accepted ) { using var fixture = new SymbolFixture(); - string summary = scenario == "missing-summary" ? "" : """ + string summary = scenario == "missing-summary" ? string.Empty : """ /// /// Combines two values using the implementation's operation. /// """; - string right = scenario == "missing-parameter" ? "" : """ + string right = scenario == "missing-parameter" ? string.Empty : """ /// /// The second value supplied to the operation. /// """; - string returns = scenario == "missing-returns" ? "" : """ + string returns = scenario == "missing-returns" ? string.Empty : """ /// /// The combined value produced by the operation. /// @@ -122,42 +132,50 @@ bool accepted if (scenario is "override" or "chain") { source = "namespace Inno.Editor.Probe; public class Base {\n" + contract - + "public virtual int Combine(int left, int right) => left + right; }\n"; + + "public virtual int Combine(int left, int right) => left + right; }\n"; if (scenario == "chain") { source += "public class Middle : Base {\n/// \n" - + "public override int Combine(int left, int right) => base.Combine(left, right); }\n"; + + "public override int Combine(int left, int right) => base.Combine(left, right); }\n"; } source += "public class Probe : " + (scenario == "chain" ? "Middle" : "Base") - + " {\n/// \npublic override int Combine(int left, int right) => left + right; }"; + + " {\n/// \npublic override int Combine(int left, int right) => left + right; }"; } else { source = "namespace Inno.Editor.Probe; public interface IContract {\n" + contract - + "int Combine(int left, int right); }\npublic class Probe" - + (scenario == "standalone" ? "" : " : IContract") + " {\n" - + (scenario == "wrong-cref" ? "/// \n" : "/// \n") - + "public int Combine(int left, int right) => left + right; }"; + + "int Combine(int left, int right); }\npublic class Probe" + + (scenario == "standalone" ? string.Empty : " : IContract") + " {\n" + + (scenario == "wrong-cref" ? "/// \n" : "/// \n") + + "public int Combine(int left, int right) => left + right; }"; } string relative = "src/composition/editor/framework/Inno.Editor.Probe"; fixture.Compile(relative, "Inno.Editor.Probe", source); fixture.WriteSource(relative, source); string output = fixture.Run(); - Assert.Equal(!accepted, output.Contains( - "inheritdoc requires a documented overridden or implemented contract", StringComparison.Ordinal)); + Assert.Equal( + !accepted, + output.Contains( + "inheritdoc requires a documented overridden or implemented contract", + StringComparison.Ordinal + ) + ); } [Theory] [InlineData("public enum InputBackend { BuiltIn }", true)] - [InlineData("public readonly record struct InputBackendId(string value);", false)] + [InlineData("public readonly record struct InputBackendID(string value);", false)] public void ReplaceableBackendContractsUseOpenIdentifiers( string declaration, bool rejected ) { using var fixture = new SymbolFixture(); - fixture.Compile("src/adapters/input/Inno.Adapter.Input", "Inno.Adapter.Input", - "namespace Inno.Adapter.Input; " + declaration); + fixture.Compile( + "src/adapters/input/Inno.Adapter.Input", + "Inno.Adapter.Input", + "namespace Inno.Adapter.Input; " + declaration + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("replaceable backend selections require open IDs", StringComparison.Ordinal)); } @@ -197,13 +215,18 @@ public struct MaEngine { public int value; } public class MaBase { } public interface IMaBackend { } """); - fixture.Compile("src/services/audio/Inno.Audio", "Inno.Audio", """ + fixture.Compile( + "src/services/audio/Inno.Audio", + "Inno.Audio", + """ using System; using System.Collections.Generic; using System.Threading.Tasks; using Raw = Inno.Native.MiniAudio.MaEngine; namespace Inno.Audio; - """ + declaration, native); + """ + declaration, + native + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("exposes native symbol", StringComparison.Ordinal)); @@ -217,10 +240,17 @@ namespace Inno.Audio; public void NativePolicyUsesAssemblyIdentityRatherThanSourceTypeNames(string assemblyName) { using var fixture = new SymbolFixture(); - string native = fixture.Compile("backends/" + assemblyName["Inno.Native.".Length..] + "/native/" + assemblyName, assemblyName, - "namespace Renamed; public struct NeutralLookingName { public int value; }"); - fixture.Compile("src/services/audio/Inno.Audio", "Inno.Audio", - "namespace Inno.Audio; public class Probe { public Renamed.NeutralLookingName value; }", native); + string native = fixture.Compile( + "backends/" + assemblyName["Inno.Native.".Length..] + "/native/" + assemblyName, + assemblyName, + "namespace Renamed; public struct NeutralLookingName { public int value; }" + ); + fixture.Compile( + "src/services/audio/Inno.Audio", + "Inno.Audio", + "namespace Inno.Audio; public class Probe { public Renamed.NeutralLookingName value; }", + native + ); Assert.Contains("exposes native symbol Renamed.NeutralLookingName", fixture.Run(), StringComparison.Ordinal); } @@ -235,10 +265,17 @@ public void CompositionOnlyExposesNeutralAdapterContracts( bool rejected ) { using var fixture = new SymbolFixture(); - string implementation = fixture.Compile("src/adapters/audio/" + adapter, adapter, - "namespace Backend; public class Device { }"); - fixture.Compile("src/composition/" + owner, owner, - "namespace Product; public class Probe { public Backend.Device device; }", implementation); + string implementation = fixture.Compile( + "src/adapters/audio/" + adapter, + adapter, + "namespace Backend; public class Device { }" + ); + fixture.Compile( + "src/composition/" + owner, + owner, + "namespace Product; public class Probe { public Backend.Device device; }", + implementation + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("exposes concrete adapter", StringComparison.Ordinal)); } @@ -254,12 +291,22 @@ public void EditorPublicReferencePolicyFollowsCompiledVisibility( bool rejected ) { using var fixture = new SymbolFixture(); - string dependency = fixture.Compile("src/foundation/core/Inno.Core.Values", "Inno.Core.Values", - "namespace Values; public class Value { }"); - fixture.Compile("src/composition/editor/framework/Inno.Editor.Probe", "Inno.Editor.Probe", - "using Values; namespace Inno.Editor.Probe; " + declaration, dependency); - fixture.AddReference("src/composition/editor/framework/Inno.Editor.Probe/Inno.Editor.Probe.csproj", - "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", privateReference); + string dependency = fixture.Compile( + "src/foundation/core/Inno.Core.Values", + "Inno.Core.Values", + "namespace Values; public class Value { }" + ); + fixture.Compile( + "src/composition/editor/framework/Inno.Editor.Probe", + "Inno.Editor.Probe", + "using Values; namespace Inno.Editor.Probe; " + declaration, + dependency + ); + fixture.AddReference( + "src/composition/editor/framework/Inno.Editor.Probe/Inno.Editor.Probe.csproj", + "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", + privateReference + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("declare a direct public ProjectReference", StringComparison.Ordinal)); } @@ -277,7 +324,11 @@ bool rejected string native = fixture.Compile("backends/Sdl3/native/Inno.Native.Sdl3", "Inno.Native.Sdl3", "public struct Raw { }"); string projectName = Path.GetFileName(relative); fixture.Compile(relative, projectName, "internal class Probe { private Raw value; }", native); - fixture.AddReference(relative + "/" + projectName + ".csproj", "backends/Sdl3/native/Inno.Native.Sdl3/Inno.Native.Sdl3.csproj", true); + fixture.AddReference( + relative + "/" + projectName + ".csproj", + "backends/Sdl3/native/Inno.Native.Sdl3/Inno.Native.Sdl3.csproj", + true + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("SDL3 native code is restricted", StringComparison.Ordinal)); } @@ -290,13 +341,23 @@ public void EditorImplementationReferencesRequireCompilePrivacy( bool rejected ) { using var fixture = new SymbolFixture(); - string dependency = fixture.Compile("src/foundation/core/Inno.Core.Values", "Inno.Core.Values", - "namespace Values; public class Value { }"); + string dependency = fixture.Compile( + "src/foundation/core/Inno.Core.Values", + "Inno.Core.Values", + "namespace Values; public class Value { }" + ); string relative = "src/composition/editor/framework/Inno.Editor.Probe"; - fixture.Compile(relative, "Inno.Editor.Probe", - "using Values; namespace Inno.Editor.Probe; public class Probe { private Value value; }", dependency); - fixture.AddReference(relative + "/Inno.Editor.Probe.csproj", - "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", privateReference); + fixture.Compile( + relative, + "Inno.Editor.Probe", + "using Values; namespace Inno.Editor.Probe; public class Probe { private Value value; }", + dependency + ); + fixture.AddReference( + relative + "/Inno.Editor.Probe.csproj", + "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", + privateReference + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("is an implementation dependency", StringComparison.Ordinal)); } @@ -310,14 +371,24 @@ public void EditorReferenceGroupsKeepImplementationBeforePublicApi( bool rejected ) { using var fixture = new SymbolFixture(); - string hidden = fixture.Compile("src/foundation/core/Inno.Core.Hidden", "Inno.Core.Hidden", - "namespace Hidden; public class Value { }"); - string visible = fixture.Compile("src/foundation/core/Inno.Core.Visible", "Inno.Core.Visible", - "namespace Visible; public class Value { }"); + string hidden = fixture.Compile( + "src/foundation/core/Inno.Core.Hidden", + "Inno.Core.Hidden", + "namespace Hidden; public class Value { }" + ); + string visible = fixture.Compile( + "src/foundation/core/Inno.Core.Visible", + "Inno.Core.Visible", + "namespace Visible; public class Value { }" + ); string relative = "src/composition/editor/framework/Inno.Editor.Probe"; - fixture.Compile(relative, "Inno.Editor.Probe", + fixture.Compile( + relative, + "Inno.Editor.Probe", "namespace Inno.Editor.Probe; public class Probe { private Hidden.Value hidden; public Visible.Value visible; }", - hidden, visible); + hidden, + visible + ); string owner = relative + "/Inno.Editor.Probe.csproj"; if (layout == 1) { @@ -348,15 +419,15 @@ bool rejected [InlineData("new System.IO.FileStream(\"payload\", System.IO.FileMode.Open);", true)] [InlineData("throw new System.IO.InvalidDataException(\"Invalid payload\");", false)] [InlineData("new System.IO.MemoryStream(new byte[] { 1 });", false)] - public void SharedContentIoChecksResolvedSymbolsInsteadOfIoNamespaceText( + public void SharedContentIOChecksResolvedSymbolsInsteadOfIONamespaceText( string operation, bool rejected ) { using var fixture = new SymbolFixture(); - const string relative = "src/content/deployment/Inno.Content"; + const string C_RELATIVE = "src/content/deployment/Inno.Content"; string source = "internal class Probe { void Read() { " + operation + " } }"; - fixture.Compile(relative, "Inno.Content", source); - fixture.WriteSource(relative, source); + fixture.Compile(C_RELATIVE, "Inno.Content", source); + fixture.WriteSource(C_RELATIVE, source); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("shared content owners must receive reading contracts", StringComparison.Ordinal)); } @@ -368,7 +439,9 @@ private sealed class SymbolFixture : IDisposable internal SymbolFixture() { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(m_root, folder)); + } File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Global @@ -376,6 +449,14 @@ internal SymbolFixture() """); } + public void Dispose() + { + if (Directory.Exists(m_root)) + { + Directory.Delete(m_root, recursive: true); + } + } + internal string Compile( string relative, string assemblyName, @@ -385,16 +466,26 @@ params string[] dependencies string directory = Path.Combine(m_root, relative); string output = Path.Combine(directory, "bin", "Debug", "net10.0", assemblyName + ".dll"); Directory.CreateDirectory(Path.GetDirectoryName(output)!); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0")))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0")) + ) + ) .Save(Path.Combine(directory, assemblyName + ".csproj")); string[] platform = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); - MetadataReference[] references = platform.Concat(dependencies).Distinct(StringComparer.OrdinalIgnoreCase) - .Select(path => MetadataReference.CreateFromFile(path)).ToArray(); - CSharpCompilation compilation = CSharpCompilation.Create(assemblyName, - [CSharpSyntaxTree.ParseText(source)], references, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); - var result = compilation.Emit(output, xmlDocumentationPath: Path.ChangeExtension(output, ".xml")); + MetadataReference[] references = platform.Concat(dependencies) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + assemblyName, + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true) + ); + EmitResult result = compilation.Emit(output, xmlDocumentationPath: Path.ChangeExtension(output, ".xml")); Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics)); return output; } @@ -406,10 +497,17 @@ bool privateReference ) { string path = Path.Combine(m_root, owner); XDocument document = XDocument.Load(path); - var reference = new XElement("ProjectReference", new XAttribute("Include", - Path.GetRelativePath(Path.GetDirectoryName(path)!, Path.Combine(m_root, target)))); + var reference = new XElement( + "ProjectReference", + new XAttribute( + "Include", + Path.GetRelativePath(Path.GetDirectoryName(path)!, Path.Combine(m_root, target)) + ) + ); if (privateReference) + { reference.Add(new XAttribute("PrivateAssets", "compile")); + } document.Root!.Add(new XElement("ItemGroup", reference)); document.Save(path); } @@ -428,11 +526,5 @@ internal string Run(params string[] arguments) Assert.Equal(1, exitCode); return output; } - - public void Dispose() - { - if (Directory.Exists(m_root)) - Directory.Delete(m_root, recursive: true); - } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs index ab236becb..74045bc2f 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs @@ -10,12 +10,12 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; -using Inno.Testing.Source; -using Inno.Tooling.Documentation; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Architecture.Tests; @@ -23,10 +23,6 @@ namespace Inno.Tooling.Architecture.Tests; public sealed class DocumentationExampleTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDocumentationExamples", Guid.NewGuid().ToString("N")); - private string cache => Path.Combine(m_root, "cache"); - private string source => Path.Combine(m_root, "documentation"); - private string host => Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); public DocumentationExampleTests() { @@ -48,12 +44,18 @@ public DocumentationExampleTests() new { name = "Inno.Probe", path = "src/Inno.Probe/Inno.Probe.csproj", surfaces = Array.Empty() } }); Write("documentation/reference/projects.json", Encoding.UTF8.GetString(projects)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - projectManifest = "reference/projects.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), - toolingRevision = new string('a', 40) - })); + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new + { + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + projectManifest = "reference/projects.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), + toolingRevision = new string('a', 40) + }) + ); } [Fact] @@ -61,10 +63,15 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont { var start = new ProcessStartInfo(host) { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in new[] { "build", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "-v:quiet" }) + { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -84,7 +91,8 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont Assert.Equal("inno-documentation-examples/1", report.RootElement.GetProperty("schema").GetString()); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("validatorIdentity").GetString()!); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("compilerIdentity").GetString()!); - var results = report.RootElement.GetProperty("results").EnumerateArray() + Dictionary results = report.RootElement.GetProperty("results") + .EnumerateArray() .ToDictionary(static group => group.GetProperty("page").GetString()!); Assert.Equal("Passed", results["working"].GetProperty("status").GetString()); Assert.Equal("Inno.Probe", Assert.Single(results["working"].GetProperty("projects").EnumerateArray()).GetString()); @@ -95,11 +103,21 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont Assert.Equal("Blocked", results["unspecified"].GetProperty("status").GetString()); Assert.Equal("Unverified", report.RootElement.GetProperty("sourceApiStatus").GetString()); string graphPath = Path.Combine(m_root, "resolved-graph.json"); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, [Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")], - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + [Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")], + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); await File.WriteAllTextAsync(graphPath, graph); Write("src/Inno.Probe/no-resolve", "References are frozen for this execution boundary."); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "working", "--sdk-snapshot", graphPath])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "working", "--sdk-snapshot", graphPath] + ) + ); } [Fact] @@ -113,11 +131,14 @@ public async Task EmptyDiscoveryCancellationAndUnknownPagesCannotProduceGreenEvi Assert.Equal("Blocked", report.RootElement.GetProperty("status").GetString()); byte[] previous = File.ReadAllBytes(output); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..Arguments(index.snapshot, output), "--page", "missing"])); + [..Arguments(index.snapshot, output), "--page", "missing"] + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationExamples.ExecuteAsync( - Arguments(index.snapshot, output), cancellation.Token)); + Arguments(index.snapshot, output), + cancellation.Token + )); Assert.Equal(previous, File.ReadAllBytes(output)); } @@ -136,25 +157,35 @@ public async Task ExamplePlanningUsesActualOwnersWithoutStartingSdkAndPreservesP { Assert.Equal("inno-example-plan/1", plan.RootElement.GetProperty("schema").GetString()); Assert.True(plan.RootElement.GetProperty("needsScriptProjection").GetBoolean()); - Assert.Equal("src/Inno.Probe/Inno.Probe.csproj", Assert.Single(plan.RootElement.GetProperty("projects").EnumerateArray()).GetString()); + Assert.Equal( + "src/Inno.Probe/Inno.Probe.csproj", + Assert.Single(plan.RootElement.GetProperty("projects").EnumerateArray()).GetString() + ); Assert.Equal(2, plan.RootElement.GetProperty("pages").GetArrayLength()); } Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..arguments, "--operation", "plan", "--page", "host"])); using (JsonDocument plan = JsonDocument.Parse(File.ReadAllBytes(output))) + { Assert.False(plan.RootElement.GetProperty("needsScriptProjection").GetBoolean()); + } byte[] previous = File.ReadAllBytes(output); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan", "--page", "empty"])); + [..arguments, "--operation", "plan", "--page", "empty"] + )); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan", "--page", "absent"])); + [..arguments, "--operation", "plan", "--page", "absent"] + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan"], cancellation.Token)); + [..arguments, "--operation", "plan"], + cancellation.Token + )); Assert.Equal(previous, File.ReadAllBytes(output)); File.Delete(Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan"])); + [..arguments, "--operation", "plan"] + )); Assert.Equal(previous, File.ReadAllBytes(output)); Assert.False(Directory.Exists(Path.Combine(m_root, "src/Inno.Probe/obj"))); } @@ -162,7 +193,9 @@ await Assert.ThrowsAsync(() => DocumentationExamples.Execu public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -170,11 +203,32 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc { string directory = Path.Combine(m_root, "src/Inno.Probe/bin/Debug/net10.0"); Directory.CreateDirectory(directory); - File.Copy(EmitReference("Inno.Probe", "namespace Inno.Probe; public static class Probe { public static int Read() => 42; }"), Path.Combine(directory, "Inno.Probe.dll")); + File.Copy( + EmitReference("Inno.Probe", "namespace Inno.Probe; public static class Probe { public static int Read() => 42; }"), + Path.Combine(directory, "Inno.Probe.dll") + ); File.WriteAllText(Path.Combine(directory, "Inno.Probe.xml"), "

"); - File.Copy(EmitReference("Foreign", "public static class Foreign { public static int Read() => 7; }"), Path.Combine(directory, "Foreign.dll")); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }) start.ArgumentList.Add(argument); + File.Copy( + EmitReference("Foreign", "public static class Foreign { public static int Read() => 7; }"), + Path.Combine(directory, "Foreign.dll") + ); + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }) { + start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -182,7 +236,11 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc await process.WaitForExitAsync(); Assert.True(process.ExitCode == 0, await stdout + await stderr); } - Page("valid", "host", "public static class Example { public static int Read() => Inno.Probe.Probe.Read(); public static int Count(params System.ReadOnlySpan values) => values.Length; }"); + Page( + "valid", + "host", + "public static class Example { public static int Read() => Inno.Probe.Probe.Read(); public static int Count(params System.ReadOnlySpan values) => values.Length; }" + ); Page("foreign", "host", "public static class Example { public static int Read() => Foreign.Read(); }"); Page("tilde", "host", "int value = missing;"); Page("long-fence", "host", "int value = missing;"); @@ -197,17 +255,41 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc string output = Path.Combine(m_root, "fences.json"); Assert.Equal(1, await DocumentationExamples.ExecuteAsync(Arguments(index.snapshot, output))); using JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(output)); - var results = report.RootElement.GetProperty("results").EnumerateArray().ToDictionary(static item => item.GetProperty("page").GetString()!); - foreach (string id in new[] { "valid", "text" }) Assert.Equal("Passed", results[id].GetProperty("status").GetString()); - foreach (string id in new[] { "foreign", "tilde", "long-fence" }) Assert.Equal("Failed", results[id].GetProperty("status").GetString()); + Dictionary results = report.RootElement + .GetProperty("results") + .EnumerateArray() + .ToDictionary(static item => item.GetProperty("page").GetString()!); + foreach (string id in new[] { "valid", "text" }) + { + Assert.Equal("Passed", results[id].GetProperty("status").GetString()); + } + foreach (string id in new[] { "foreign", "tilde", "long-fence" }) + { + Assert.Equal("Failed", results[id].GetProperty("status").GetString()); + } Assert.Contains("CS0103", results["foreign"].GetProperty("errors")[0].GetString()); } [Fact] public async Task LogicalExamplesRetainBothScriptSurfacesAndNeverBorrowHostImplementation() { - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }) start.ArgumentList.Add(argument); + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }) { + start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -215,34 +297,76 @@ public async Task LogicalExamplesRetainBothScriptSurfacesAndNeverBorrowHostImple await process.WaitForExitAsync(); Assert.True(process.ExitCode == 0, await stdout + await stderr); } - string runtime = EmitReference("Inno.ScriptApi.Runtime", "namespace InnoEngine.Probe; public static class Value { public static int Read() => 7; }"); - string editor = EmitReference("Inno.ScriptApi.Editor", "namespace InnoEditor.Probe; public static class Action { public static int Read() => 9; }"); + string runtime = EmitReference( + "Inno.ScriptApi.Runtime", + "namespace InnoEngine.Probe; public static class Value { public static int Read() => 7; }" + ); + string editor = EmitReference( + "Inno.ScriptApi.Editor", + "namespace InnoEditor.Probe; public static class Action { public static int Read() => 9; }" + ); string unrelated = EmitReference("Unrelated", "public class Unrelated { }"); Page("runtime", "runtime-script", "public class Example { public int Read() => InnoEngine.Probe.Value.Read(); }"); - Page("editor", "editor-script", "public class Example { public int Read() => InnoEngine.Probe.Value.Read() + InnoEditor.Probe.Action.Read(); }"); + Page( + "editor", + "editor-script", + "public class Example { public int Read() => InnoEngine.Probe.Value.Read() + InnoEditor.Probe.Action.Read(); }" + ); Page("host-leak", "runtime-script", "public class Example { public int Read() => Inno.Probe.Probe.Read(); }"); DocumentationResult index = await DocumentationStore.IndexAsync(m_root, source, cache); string output = Path.Combine(m_root, "scripts.json"); Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime"])); Assert.Contains("Blocked", File.ReadAllText(output)); - int runtimeResult = await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", runtime]); + int runtimeResult = await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", runtime] + ); Assert.True(runtimeResult == 0, File.ReadAllText(output)); await AssertReceiptAsync(index.snapshot, output, "runtime"); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime] + ) + ); Assert.Contains("Blocked", File.ReadAllText(output)); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime, "--editor-reference", editor])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime, "--editor-reference", editor] + ) + ); using (JsonDocument evidence = JsonDocument.Parse(File.ReadAllBytes(output))) { JsonElement references = evidence.RootElement.GetProperty("results")[0].GetProperty("references"); - Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(runtime))), references.GetProperty("Inno.ScriptApi.Runtime").GetString()); - Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(editor))), references.GetProperty("Inno.ScriptApi.Editor").GetString()); + Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(runtime))), + references.GetProperty("Inno.ScriptApi.Runtime").GetString() + ); + Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(editor))), + references.GetProperty("Inno.ScriptApi.Editor").GetString() + ); } await AssertReceiptAsync(index.snapshot, output, "editor"); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "host-leak", "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "host-leak", "--runtime-reference", runtime] + ) + ); Assert.Contains("CS0103", File.ReadAllText(output)); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", unrelated])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", unrelated] + ) + ); Assert.Contains("Expected the Inno.ScriptApi.Runtime", File.ReadAllText(output)); - await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--editor-reference", editor])); + await Assert.ThrowsAsync( + () => DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--editor-reference", editor] + ) + ); } [Fact] @@ -266,9 +390,22 @@ public static class EditorProbe { public static int Inspect() => 1; } public sealed class Owned { private Owned() { } } } """); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-nr:false", "-v:quiet" }) + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-nr:false", + "-v:quiet" + }) { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -277,10 +414,27 @@ public sealed class Owned { private Owned() { } } Assert.True(process.ExitCode == 0, await stdout + await stderr); } string facts = Path.Combine(m_root, "host.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", m_root, "--dotnet", host, - "--project", "src/Inno.Probe/Inno.Probe.csproj", "--output", facts])); - string runtime = EmitReference("Inno.ScriptApi.Runtime", "namespace Logical; public static class Renamed { public static int Read(int value) => value; public static int Read(string value) => value.Length; private static int Hidden() => 0; } public sealed class Owned { }"); - string editor = EmitReference("Inno.ScriptApi.Editor", "namespace Logical; public static class Tools { public static int Inspect() => 1; }"); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + m_root, + "--dotnet", + host, + "--project", + "src/Inno.Probe/Inno.Probe.csproj", + "--output", + facts + ]) + ); + string runtime = EmitReference( + "Inno.ScriptApi.Runtime", + "namespace Logical; public static class Renamed { public static int Read(int value) => value; public static int Read(string value) => value.Length; private static int Hidden() => 0; } public sealed class Owned { }" + ); + string editor = EmitReference( + "Inno.ScriptApi.Editor", + "namespace Logical; public static class Tools { public static int Inspect() => 1; }" + ); const string C_XML = """ ASSEMBLY @@ -288,14 +442,39 @@ public sealed class Owned { private Owned() { } }

Reads the supplied value.The value.The supplied value. Must not become a projected declaration. """; - File.WriteAllText(Path.ChangeExtension(runtime, ".xml"), C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Runtime", StringComparison.Ordinal) - .Replace("", "", StringComparison.Ordinal)); - File.WriteAllText(Path.ChangeExtension(editor, ".xml"), C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Editor", StringComparison.Ordinal) - .Replace("Logical.Renamed", "Logical.Tools", StringComparison.Ordinal).Replace("T:Inno.Probe.Probe", "T:Inno.Probe.EditorProbe", StringComparison.Ordinal)); + File.WriteAllText( + Path.ChangeExtension(runtime, ".xml"), + C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Runtime", StringComparison.Ordinal) + .Replace( + "", + "", + StringComparison.Ordinal + ) + ); + File.WriteAllText( + Path.ChangeExtension(editor, ".xml"), + C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Editor", StringComparison.Ordinal) + .Replace("Logical.Renamed", "Logical.Tools", StringComparison.Ordinal) + .Replace("T:Inno.Probe.Probe", "T:Inno.Probe.EditorProbe", StringComparison.Ordinal) + ); string output = Path.Combine(m_root, "projected.json"); - string[] arguments = ["--engine-root", m_root, "--dotnet", host, "--source-reference", facts, - "--runtime-reference", runtime, "--editor-reference", editor, "--output", output, - "--framework-project", "src/Inno.Probe/Inno.Probe.csproj"]; + string[] arguments = + [ + "--engine-root", + m_root, + "--dotnet", + host, + "--source-reference", + facts, + "--runtime-reference", + runtime, + "--editor-reference", + editor, + "--output", + output, + "--framework-project", + "src/Inno.Probe/Inno.Probe.csproj" + ]; Assert.Equal(0, DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"])); byte[] runtimeFacts = File.ReadAllBytes(output); using (JsonDocument captured = JsonDocument.Parse(File.ReadAllBytes(output))) @@ -304,10 +483,16 @@ public sealed class Owned { private Owned() { } } Assert.Single(captured.RootElement.GetProperty("projectionIdentities").EnumerateObject()); JsonElement project = captured.RootElement.GetProperty("projects")[0]; Assert.Equal("Inno.Probe", project.GetProperty("name").GetString()); - var symbols = project.GetProperty("symbols").EnumerateArray().ToDictionary(static symbol => symbol.GetProperty("id").GetString()!); + Dictionary symbols = project + .GetProperty("symbols") + .EnumerateArray() + .ToDictionary(static symbol => symbol.GetProperty("id").GetString()!); Assert.Contains("M:Logical.Renamed.Read(System.Int32)", symbols.Keys); Assert.Contains("M:Logical.Renamed.Read(System.String)", symbols.Keys); - Assert.DoesNotContain(symbols.Keys, static id => id.Contains("Hidden", StringComparison.Ordinal) || id.Contains("HostOnly", StringComparison.Ordinal)); + Assert.DoesNotContain( + symbols.Keys, + static id => id.Contains("Hidden", StringComparison.Ordinal) || id.Contains("HostOnly", StringComparison.Ordinal) + ); Assert.Contains("supplied value", symbols["M:Logical.Renamed.Read(System.Int32)"].GetProperty("documentation").GetString()); Assert.Equal("Runtime", symbols["M:Logical.Renamed.Read(System.Int32)"].GetProperty("scriptingScope").GetString()); Assert.Equal("Authoring", symbols["T:Logical.Owned"].GetProperty("scriptingScope").GetString()); @@ -318,14 +503,23 @@ public sealed class Owned { private Owned() { } } using (JsonDocument captured = JsonDocument.Parse(File.ReadAllBytes(output))) { Assert.Equal(2, captured.RootElement.GetProperty("projectionIdentities").EnumerateObject().Count()); - Assert.Contains(captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), - static symbol => symbol.GetProperty("id").GetString() == "M:Logical.Tools.Inspect"); + Assert.Contains( + captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), + static symbol => symbol.GetProperty("id").GetString() == "M:Logical.Tools.Inspect" + ); } - Page("projected-contract", "runtime-script", "public static class Example { public static int Read() => Logical.Renamed.Read(7); }"); + Page( + "projected-contract", + "runtime-script", + "public static class Example { public static int Read() => Logical.Renamed.Read(7); }" + ); Bind(runtimeFacts); DocumentationResult prepared = await DocumentationStore.IndexAsync(m_root, source, cache); string comparison = Path.Combine(m_root, "comparison.json"); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(prepared.snapshot, comparison), "--runtime-reference", runtime])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync([..Arguments(prepared.snapshot, comparison), "--runtime-reference", runtime]) + ); using (JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(comparison))) { Assert.Equal("Passed", report.RootElement.GetProperty("scriptReferences")[0].GetProperty("status").GetString()); @@ -335,7 +529,10 @@ public sealed class Owned { private Owned() { } } changedFacts["projects"]![0]!["symbols"]![0]!["signature"] = "public int ChangedContract"; Bind(JsonSerializer.SerializeToUtf8Bytes(changedFacts)); DocumentationResult changed = await DocumentationStore.IndexAsync(m_root, source, cache); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(changed.snapshot, comparison), "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync([..Arguments(changed.snapshot, comparison), "--runtime-reference", runtime]) + ); using (JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(comparison))) { Assert.Equal("Passed", report.RootElement.GetProperty("results")[0].GetProperty("status").GetString()); @@ -349,14 +546,20 @@ public sealed class Owned { private Owned() { } } string conflictPath = Path.Combine(m_root, "conflicting-source.json"); File.WriteAllBytes(conflictPath, JsonSerializer.SerializeToUtf8Bytes(conflicting)); Assert.Throws(() => DocumentationReferences.ExportApi( - [..arguments, "--source-reference", conflictPath, "--surface", "runtime-script"])); + [..arguments, "--source-reference", conflictPath, "--surface", "runtime-script"] + )); Assert.Equal(previous, File.ReadAllBytes(output)); - File.WriteAllText(Path.ChangeExtension(runtime, ".xml"), C_XML.Replace("T:Inno.Probe.Probe", "T:Missing.Owner", StringComparison.Ordinal)); + File.WriteAllText( + Path.ChangeExtension(runtime, ".xml"), + C_XML.Replace("T:Inno.Probe.Probe", "T:Missing.Owner", StringComparison.Ordinal) + ); Assert.Throws(() => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"])); Assert.Equal(previous, File.ReadAllBytes(output)); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - Assert.ThrowsAny(() => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"], cancellation.Token)); + Assert.ThrowsAny( + () => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"], cancellation.Token) + ); Assert.Equal(previous, File.ReadAllBytes(output)); void Bind(byte[] projectedFacts) @@ -369,22 +572,62 @@ void Bind(byte[] projectedFacts) Write("documentation/reference/projects.json", Encoding.UTF8.GetString(inventory)); Write("documentation/reference/host.json", Encoding.UTF8.GetString(hostFacts)); Write("documentation/reference/runtime.json", Encoding.UTF8.GetString(projectedFacts)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - projectManifest = "reference/projects.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), - toolingRevision = new string('a', 40), apiManifests = new[] + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new { - new { path = "reference/host.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(hostFacts)), model = "source-clr", configuration = "Debug", sourceRevision = new string('a', 40), sourceTree = new string('b', 40) }, - new { path = "reference/runtime.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(projectedFacts)), model = "runtime-script", configuration = "Debug", sourceRevision = new string('a', 40), sourceTree = new string('b', 40) } - } - })); + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + projectManifest = "reference/projects.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), + toolingRevision = new string('a', 40), + apiManifests = new[] + { + new + { + path = "reference/host.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(hostFacts)), + model = "source-clr", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + }, + new + { + path = "reference/runtime.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(projectedFacts)), + model = "runtime-script", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + } + } + }) + ); } } - private async Task AssertReceiptAsync(string snapshotId, string reportPath, string pageId) - { - using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, snapshotId); + private string cache => Path.Combine(m_root, "cache"); + private string source => Path.Combine(m_root, "documentation"); + + private string host + => Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); + + private async Task AssertReceiptAsync( + string snapshotID, + string reportPath, + string pageID + ) { + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, snapshotID); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); Write("receipt/documentation-catalog.json", JsonSerializer.Serialize(catalog)); File.Copy(reportPath, Path.Combine(m_root, "receipt/managed-documentation-examples.json"), overwrite: true); @@ -406,10 +649,23 @@ private async Task AssertReceiptAsync(string snapshotId, string reportPath, stri } "Reconciled $Page against the actual example compiler report." """); - var start = new ProcessStartInfo("pwsh") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "-NoProfile", "-File", Path.Combine(m_root, "receipt/check.ps1"), - TestRepository.GetRoot(typeof(DocumentationExampleTests).Assembly), pageId }) + var start = new ProcessStartInfo("pwsh") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "-NoProfile", + "-File", + Path.Combine(m_root, "receipt/check.ps1"), + TestRepository.GetRoot(typeof(DocumentationExampleTests).Assembly), + pageID + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task stdout = process.StandardOutput.ReadToEndAsync(); Task stderr = process.StandardError.ReadToEndAsync(); @@ -417,14 +673,19 @@ private async Task AssertReceiptAsync(string snapshotId, string reportPath, stri Assert.True(process.ExitCode == 0, await stdout + await stderr); } - private string EmitReference(string name, string sourceText) - { + private string EmitReference( + string name, + string sourceText + ) { string output = Path.Combine(m_root, name + ".dll"); string[] references = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory, "DocumentationFrameworkReferences.txt")); Assert.NotEmpty(references); - var compilation = CSharpCompilation.Create(name, [CSharpSyntaxTree.ParseText(sourceText)], + CSharpCompilation compilation = CSharpCompilation.Create( + name, + [CSharpSyntaxTree.ParseText(sourceText)], references.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(output).Success); return output; } @@ -438,9 +699,12 @@ private void Page( string id, string? mode, string? code - ) => Write("documentation/content/en/" + id + ".md", "---\nuid: " + id + "\nkind: tutorial\n" - + (mode is null ? "" : "exampleMode: " + mode + "\nexampleProjects: [Inno.Probe]\n") - + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? "" : "\n```csharp\n" + code + "\n```\n")); + ) => Write( + "documentation/content/en/" + id + ".md", + "---\nuid: " + id + "\nkind: tutorial\n" + + (mode is null ? string.Empty : "exampleMode: " + mode + "\nexampleProjects: [Inno.Probe]\n") + + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? string.Empty : "\n```csharp\n" + code + "\n```\n") + ); private void Write( string path, diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs index de52aed41..50422f9fa 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.IO; using System.Diagnostics; +using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -10,9 +10,9 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Tooling.Documentation; -using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -24,7 +24,9 @@ public sealed class DocumentationReferenceTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -35,61 +37,125 @@ public async Task ExportPlanningUsesActualTargetsAndExcludesNonProductOwnersWith net10.014.0 fixture-host """); - foreach (string owner in new[] { "src/Local", "build/Foreign", "build/Empty", "entry/Hidden", "platforms/Hidden", "backends/Hidden", "tests/Hidden", "tools/Hidden", "src/Fixture" }) - { - string product = owner.StartsWith("build/", StringComparison.Ordinal) ? "fixture-foreign" : ""; - string test = owner == "src/Fixture" ? "true" : ""; - Write(owner + "/" + Path.GetFileName(owner) + ".csproj", "" + product + test - + ""); + foreach (string owner in new[] { + "src/Local", + "build/Foreign", + "build/Empty", + "entry/Hidden", + "platforms/Hidden", + "backends/Hidden", + "tests/Hidden", + "tools/Hidden", + "src/Fixture" + }) { + string product = owner.StartsWith("build/", StringComparison.Ordinal) + ? "fixture-foreign" + : string.Empty; + string test = owner == "src/Fixture" ? "true" : string.Empty; + Write( + owner + "/" + Path.GetFileName(owner) + ".csproj", + "" + product + test + + "" + ); Write(owner + "/Probe.cs", owner == "build/Empty" ? "internal sealed class Probe { }" : "public sealed class Probe { }"); } - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); string output = Path.Combine(m_root, "plan.json"); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using JsonDocument plan = JsonDocument.Parse(File.ReadAllBytes(output)); Assert.Equal(3, plan.RootElement.GetProperty("projects").GetArrayLength()); Assert.Equal("src/Local/Local.csproj", plan.RootElement.GetProperty("buildProjects").EnumerateArray().Single().GetString()); - Assert.Equal("build/Foreign/Foreign.csproj", plan.RootElement.GetProperty("foreignOwners").EnumerateArray().Single().GetProperty("path").GetString()); + Assert.Equal( + "build/Foreign/Foreign.csproj", + plan.RootElement.GetProperty("foreignOwners").EnumerateArray().Single().GetProperty("path").GetString() + ); Assert.Equal(2, plan.RootElement.GetProperty("captures").GetArrayLength()); string localIdentity = plan.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()!; string foreignIdentity = plan.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString()!; Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument repeated = JsonDocument.Parse(File.ReadAllBytes(output))) - Assert.Equal(localIdentity, repeated.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()); + { + Assert.Equal( + localIdentity, + repeated.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString() + ); + } // Register a completed immutable owner payload, then plan again without running // any Build/Restore/ResolveReferences target in this fixture. - string facts = JsonSerializer.Serialize(new { projects = new[] { new { project = "src/Local/Local.csproj", name = "Local", symbols = Array.Empty() } } }); + string facts = JsonSerializer.Serialize( + new { projects = new[] { new { project = "src/Local/Local.csproj", name = "Local", symbols = Array.Empty() } } } + ); Write("completed/source.json", facts); Write("completed/plan.json", File.ReadAllText(output)); - Write("completed/producer.json", JsonSerializer.Serialize(new - { - configuration = "Debug", revision = new string('a', 40), - captures = new[] { new { path = "source.json", model = "source-clr", target = "fixture-host", - sha256 = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(facts))) } } - })); - Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, - "--record-completed", Path.Combine(m_root, "completed")])); + Write( + "completed/producer.json", + JsonSerializer.Serialize(new + { + configuration = "Debug", + revision = new string('a', 40), + captures = new[] + { + new + { + path = "source.json", + model = "source-clr", + target = "fixture-host", + sha256 = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(facts))) + } + } + }) + ); + Assert.Equal( + 0, + await DocumentationReferences.PlanExportAsync([ + "--engine-root", + m_root, + "--record-completed", + Path.Combine(m_root, "completed") + ]) + ); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument reused = JsonDocument.Parse(File.ReadAllBytes(output))) { Assert.Empty(reused.RootElement.GetProperty("buildProjects").EnumerateArray()); - Assert.Equal(new string('a', 40), reused.RootElement.GetProperty("reusedOwners").GetProperty("fixture-host") - .GetProperty("src/Local/Local.csproj").GetProperty("producerRevision").GetString()); + Assert.Equal( + new string('a', 40), + reused.RootElement.GetProperty("reusedOwners") + .GetProperty("fixture-host") + .GetProperty("src/Local/Local.csproj") + .GetProperty("producerRevision") + .GetString() + ); } Write("src/Local/Added.cs", "public sealed class Added { }"); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument changed = JsonDocument.Parse(File.ReadAllBytes(output))) { - Assert.NotEqual(localIdentity, changed.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()); - Assert.Equal(foreignIdentity, changed.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString()); + Assert.NotEqual( + localIdentity, + changed.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString() + ); + Assert.Equal( + foreignIdentity, + changed.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString() + ); Assert.Equal("src/Local/Local.csproj", changed.RootElement.GetProperty("buildProjects").EnumerateArray().Single().GetString()); } byte[] original = File.ReadAllBytes(output); using var canceled = new CancellationTokenSource(); canceled.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationReferences.PlanExportAsync( - ["--engine-root", m_root, "--dotnet", host, "--output", output], canceled.Token)); + ["--engine-root", m_root, "--dotnet", host, "--output", output], + canceled.Token + )); Assert.Equal(original, File.ReadAllBytes(output)); } @@ -110,14 +176,42 @@ public async Task ResolvedUnionSupportsIndependentSelectedSourceOwners() """); - Write("src/" + name + "/Probe.cs", "namespace " + name + ";\n/// Supplies this source owner's public contract.\npublic sealed class Probe { }\n"); + Write( + "src/" + name + "/Probe.cs", + "namespace " + name + ";\n/// Supplies this source owner's public contract.\npublic sealed class Probe { }\n" + ); } - Write("projects.slnx", ""); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "projects.slnx"), "--nologo", "-v:quiet", "-m:1", "-nr:false", "--disable-parallel" }) + Write( + "projects.slnx", + "" + ); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "projects.slnx"), + "--nologo", + "-v:quiet", + "-m:1", + "-nr:false", + "--disable-parallel" + }) { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -127,20 +221,56 @@ public async Task ResolvedUnionSupportsIndependentSelectedSourceOwners() } string[] projects = ["src/First/First.csproj", "src/Second/Second.csproj"]; string facts = Path.Combine(m_root, "facts.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", m_root, "--dotnet", host, "--output", facts, - ..projects.SelectMany(static project => new[] { "--project", project })])); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, projects.Select(project => Path.Combine(m_root, project)).ToArray(), - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + m_root, + "--dotnet", + host, + "--output", + facts, + ..projects.SelectMany(static project => new[] { "--project", project }) + ]) + ); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + projects.Select(project => Path.Combine(m_root, project)).ToArray(), + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); string graphPath = Path.Combine(m_root, "resolved.json"); await File.WriteAllTextAsync(graphPath, graph); - foreach (string name in new[] { "First", "Second" }) Write("src/" + name + "/no-resolve", "frozen"); + foreach (string name in new[] { "First", "Second" }) + { + Write("src/" + name + "/no-resolve", "frozen"); + } foreach (string project in projects) { string output = Path.Combine(m_root, Path.GetFileNameWithoutExtension(project) + "-comparison.json"); - Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(["--engine-root", m_root, "--dotnet", host, - "--reference", facts, "--project", project, "--sdk-snapshot", graphPath, "--output", output])); + Assert.Equal( + 0, + await DocumentationReferences.ValidateApiAsync([ + "--engine-root", + m_root, + "--dotnet", + host, + "--reference", + facts, + "--project", + project, + "--sdk-snapshot", + graphPath, + "--output", + output + ]) + ); using JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(output)); - Assert.Equal(project, Assert.Single(report.RootElement.GetProperty("projects").EnumerateArray()).GetProperty("project").GetString()); + Assert.Equal( + project, + Assert.Single(report.RootElement.GetProperty("projects").EnumerateArray()).GetProperty("project").GetString() + ); } } @@ -175,14 +305,26 @@ public class Probe protected virtual void OnRead() { } } """); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); var start = new ProcessStartInfo(host) { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in new[] { "restore", Path.Combine(m_root, C_PROJECT), "--nologo", "-v:quiet" }) + { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -198,16 +340,22 @@ protected virtual void OnRead() { } Assert.Equal("source-clr", inventory.RootElement.GetProperty("model").GetString()); Assert.Equal("Unverified", inventory.RootElement.GetProperty("sourceApiStatus").GetString()); JsonElement[] symbols = inventory.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray().ToArray(); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.String)" + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.String)" && symbol.GetProperty("signature").GetString()!.Contains("string? text = null", StringComparison.Ordinal) - && symbol.GetProperty("documentation").GetString()!.Contains("Borrowed text", StringComparison.Ordinal)); + && symbol.GetProperty("documentation").GetString()!.Contains("Borrowed text", StringComparison.Ordinal) + )); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.Int32)"); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead"); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "T:Inno.Probe.Probe" + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "T:Inno.Probe.Probe" && symbol.GetProperty("baseType").GetString() == "object" - && symbol.GetProperty("kind").GetString() == "NamedType"); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead" - && symbol.GetProperty("containingType").GetString() == "T:Inno.Probe.Probe"); + && symbol.GetProperty("kind").GetString() == "NamedType" + )); + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead" + && symbol.GetProperty("containingType").GetString() == "T:Inno.Probe.Probe" + )); string comparison = Path.Combine(m_root, "comparison.json"); string[] comparisonArguments = ["--engine-root", m_root, "--dotnet", host, "--reference", output, "--output", comparison]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(comparisonArguments)); @@ -217,8 +365,13 @@ protected virtual void OnRead() { } Assert.Equal("Unverified", matched.RootElement.GetProperty("sourceApiStatus").GetString()); } string graphPath = Path.Combine(m_root, "resolved-graph.json"); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, [Path.Combine(m_root, C_PROJECT)], - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + [Path.Combine(m_root, C_PROJECT)], + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); await File.WriteAllTextAsync(graphPath, graph); Write("src/Inno.Probe/no-resolve", "Reference resolution has already completed for this execution boundary."); Assert.Equal(0, await DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); @@ -228,31 +381,55 @@ protected virtual void OnRead() { } JsonNode wrongContext = JsonNode.Parse(graph)!; wrongContext[0]!["GlobalProperties"]!["Configuration"] = "Release"; await File.WriteAllTextAsync(graphPath, wrongContext.ToJsonString()); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); Assert.Throws(() => DocumentationReferences.ExportApi([..arguments, "--sdk-snapshot", graphPath])); Assert.Equal(originalCapture, File.ReadAllBytes(output)); JsonNode missingOwner = JsonNode.Parse(graph)!; missingOwner[0]!["Path"] = Path.Combine(m_root, "src/Inno.Other/Inno.Other.csproj"); await File.WriteAllTextAsync(graphPath, missingOwner.ToJsonString()); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); await File.WriteAllTextAsync(graphPath, "[]"); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); File.Delete(Path.Combine(m_root, "src/Inno.Probe/no-resolve")); const string C_UNRELATED = "src/Inno.Unrelated/Inno.Unrelated.csproj"; Write(C_UNRELATED, ""); JsonNode combined = JsonNode.Parse(File.ReadAllBytes(output))!; - combined["projects"]!.AsArray().Add(JsonSerializer.SerializeToNode(new - { - project = C_UNRELATED, name = "Inno.Unrelated", symbols = Array.Empty() - })); + combined["projects"]!.AsArray().Add( + JsonSerializer.SerializeToNode(new + { + project = C_UNRELATED, + name = "Inno.Unrelated", + symbols = Array.Empty() + }) + ); byte[] frozen = JsonSerializer.SerializeToUtf8Bytes(combined); string cache = Path.Combine(m_root, "artifacts", "documentation"); string documentation = PrepareDocumentation(frozen, C_PROJECT, C_UNRELATED); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, documentation, cache); Directory.Move(documentation, documentation + "-unavailable"); - string[] preparedArguments = ["--engine-root", m_root, "--dotnet", host, "--cache-root", cache, - "--snapshot", indexed.snapshot!, "--reference", "reference/api/probe.json", "--project", C_PROJECT, - "--output", comparison]; + string[] preparedArguments = + [ + "--engine-root", + m_root, + "--dotnet", + host, + "--cache-root", + cache, + "--snapshot", + indexed.snapshot!, + "--reference", + "reference/api/probe.json", + "--project", + C_PROJECT, + "--output", + comparison + ]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(preparedArguments)); using (JsonDocument matched = JsonDocument.Parse(File.ReadAllBytes(comparison))) { @@ -266,7 +443,9 @@ protected virtual void OnRead() { } string[] unknownOwner = preparedArguments.Select(argument => argument == C_PROJECT ? "src/Missing.csproj" : argument).ToArray(); await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(unknownOwner)); Assert.Equal(protectedResult, File.ReadAllBytes(comparison)); - string[] overwriteCache = preparedArguments.Select(argument => argument == comparison ? Path.Combine(cache, "current.json") : argument).ToArray(); + string[] overwriteCache = preparedArguments + .Select(argument => argument == comparison ? Path.Combine(cache, "current.json") : argument) + .ToArray(); await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(overwriteCache)); string source = File.ReadAllText(Path.Combine(m_root, "src/Inno.Probe/Probe.cs")); Write("src/Inno.Probe/Probe.cs", source.Replace("Borrowed text.", "Caller must release the text lease.", StringComparison.Ordinal)); @@ -283,7 +462,9 @@ protected virtual void OnRead() { } Assert.Contains("Missing current declaration", File.ReadAllText(comparison)); File.WriteAllBytes(output, fullReference); byte[] firstFailure = File.ReadAllBytes(comparison); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(comparisonArguments, new CancellationToken(true))); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync(comparisonArguments, new CancellationToken(true)) + ); Assert.Equal(firstFailure, File.ReadAllBytes(comparison)); byte[] previous = File.ReadAllBytes(output); Write("src/Inno.Probe/Probe.cs", "namespace Inno.Probe; public class Probe { public MissingContract Read() => null; }"); @@ -295,15 +476,24 @@ protected virtual void OnRead() { } [InlineData("[]")] [InlineData("[{\"project\":\"../escape.csproj\",\"name\":\"Escape\",\"symbols\":[]}]")] [InlineData("[{\"project\":\"src/./Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]")] - [InlineData("[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]},{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]")] + [InlineData( + "[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]},{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]" + )] [InlineData("[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[{\"id\":\"T:Probe\"},{\"id\":\"T:Probe\"}]}]")] public async Task InvalidReferenceDiscoveryCannotReplaceEvidence(string projects) { Write("reference.json", "{\"model\":\"source-clr\",\"configuration\":\"Debug\",\"projects\":" + projects + "}"); Write("report.json", "first failure"); Exception? failure = await Record.ExceptionAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", Path.Combine(m_root, "reference.json"), - "--output", Path.Combine(m_root, "report.json")])); + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + Path.Combine(m_root, "reference.json"), + "--output", + Path.Combine(m_root, "report.json") + ])); Assert.NotNull(failure); Assert.True(failure is InvalidDataException or IOException, failure.ToString()); Assert.Equal("first failure", File.ReadAllText(Path.Combine(m_root, "report.json"))); @@ -318,12 +508,24 @@ public async Task DifferentEvaluatedContextsCannotShareOneBatch( ) { const string C_PROJECTS = "[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]"; Write("first.json", "{\"model\":\"source-clr\",\"configuration\":\"Debug\",\"projects\":" + C_PROJECTS + "}"); - Write("second.json", "{\"model\":\"source-clr\",\"configuration\":" + JsonSerializer.Serialize(configuration) - + ",\"target\":" + JsonSerializer.Serialize(target) + ",\"projects\":" + C_PROJECTS + "}"); + Write( + "second.json", + "{\"model\":\"source-clr\",\"configuration\":" + JsonSerializer.Serialize(configuration) + + ",\"target\":" + JsonSerializer.Serialize(target) + ",\"projects\":" + C_PROJECTS + "}" + ); Write("report.json", "original result"); InvalidDataException failure = await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", Path.Combine(m_root, "first.json"), - "--reference", Path.Combine(m_root, "second.json"), "--output", Path.Combine(m_root, "report.json")])); + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + Path.Combine(m_root, "first.json"), + "--reference", + Path.Combine(m_root, "second.json"), + "--output", + Path.Combine(m_root, "report.json") + ])); Assert.Contains("separate evaluated batches", failure.Message); Assert.Equal("original result", File.ReadAllText(Path.Combine(m_root, "report.json"))); } @@ -331,12 +533,20 @@ public async Task DifferentEvaluatedContextsCannotShareOneBatch( [Theory] [InlineData("--cache-root")] [InlineData("--snapshot")] - public async Task IncompleteSnapshotSelectionDoesNotOpenLocalFiles(string option) - { - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", "absent.json", "--output", "report.json", - option, "missing"])); - } + public async Task IncompleteSnapshotSelectionDoesNotOpenLocalFiles( + string option + ) => await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + "absent.json", + "--output", + "report.json", + option, + "missing" + ])); [Fact] public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() @@ -345,7 +555,9 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() const string C_UNRELATED = "src/Inno.Unrelated/Inno.Unrelated.csproj"; byte[] facts = JsonSerializer.SerializeToUtf8Bytes(new { - model = "source-clr", configuration = "Debug", projects = new[] + model = "source-clr", + configuration = "Debug", + projects = new[] { new { project = C_SELECTED, name = "Inno.Probe", symbols = Array.Empty() } } @@ -361,15 +573,23 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() PrepareDocumentation(JsonSerializer.SerializeToUtf8Bytes(changed), C_SELECTED, C_UNRELATED); DocumentationResult second = await DocumentationStore.IndexAsync(m_root, documentation, cache); Assert.NotEqual(first.snapshot, second.snapshot); - BuildCacheCleanupPlan retirement = BuildCacheCleanupPlan.Create(m_root, - BuildCacheOwnerCatalog.ReadOwners(m_root), new(0, 0), retireAll: true); + BuildCacheCleanupPlan retirement = BuildCacheCleanupPlan.Create( + m_root, + BuildCacheOwnerCatalog.ReadOwners(m_root), + new BuildCachePolicy(0, 0), + retireAll: true + ); BuildCacheCleanupResult result = await retirement.ExecuteAsync(); Assert.Empty(result.failures); Assert.DoesNotContain(payload, result.retired); Assert.Equal(facts, await reader.ReadReferenceAsync("reference/api/probe.json")); } - BuildCacheCleanupResult released = await BuildCacheCleanupPlan.Create(m_root, - BuildCacheOwnerCatalog.ReadOwners(m_root), new(0, 0), retireAll: true).ExecuteAsync(); + BuildCacheCleanupResult released = await BuildCacheCleanupPlan.Create( + m_root, + BuildCacheOwnerCatalog.ReadOwners(m_root), + new BuildCachePolicy(0, 0), + retireAll: true + ).ExecuteAsync(); Assert.Empty(released.failures); Assert.Contains(payload, released.retired); using DocumentationSnapshot current = await DocumentationStore.OpenAsync(cache); @@ -380,7 +600,10 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() public void ExportUsesTheActualSourceInventoryWithoutInferringApiSurfaces() { Write("src/Inno.Probe/Inno.Probe.csproj", ""); - Write("tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj", "true"); + Write( + "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj", + "true" + ); Write("src/Inno.Probe/obj/Ignored.csproj", ""); Write("extern/ThirdParty/ThirdParty.csproj", ""); string output = Path.Combine(m_root, "output", "projects.json"); @@ -426,21 +649,38 @@ string unrelated new { name = "Inno.Probe", path = selected, entry = "probe", surfaces = new[] { "source-clr" } }, new { name = "Inno.Unrelated", path = unrelated, entry = "unrelated", surfaces = new[] { "source-clr" } } }); - string revision = new('a', 40); - string tree = new('b', 40); + var revision = new string('a', 40); + var tree = new string('b', 40); Write("documentation/reference/projects/catalog.json", Encoding.UTF8.GetString(projects)); Write("documentation/reference/api/probe.json", Encoding.UTF8.GetString(facts)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision, sourceTree = tree, toolingRevision = revision, - projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), - apiManifests = new[] { new + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new { - path = "reference/api/probe.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), model = "source-clr", - configuration = "Debug", sourceRevision = revision, sourceTree = tree - } } - })); - Write("documentation/content/en/probe.md", "---\nuid: probe\nkind: project\nowners: [Inno.Probe]\n---\n# Probe\n\nUse the declared source contract.\n"); + repository = "https://github.com/Wolfiora/InnoEngine", + revision, + sourceTree = tree, + toolingRevision = revision, + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), + apiManifests = new[] + { + new + { + path = "reference/api/probe.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), + model = "source-clr", + configuration = "Debug", + sourceRevision = revision, + sourceTree = tree + } + } + }) + ); + Write( + "documentation/content/en/probe.md", + "---\nuid: probe\nkind: project\nowners: [Inno.Probe]\n---\n# Probe\n\nUse the declared source contract.\n" + ); return Path.Combine(m_root, "documentation"); } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs index f8d062e4e..91ab927ca 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; @@ -15,15 +16,20 @@ namespace Inno.Tooling.Architecture.Tests; [Collection("Architecture diagnostics")] public sealed class DocumentationSourceContractTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDocumentationSourceContracts", Guid.NewGuid().ToString("N")); private const string C_PROJECT = "tests/support/Contract/Contract.csproj"; + + private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDocumentationSourceContracts", Guid.NewGuid().ToString("N")); + private readonly string m_host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? throw new InvalidOperationException("The source contract fixture requires its selected SDK host."); + ?? throw new InvalidOperationException("The source contract fixture requires its selected SDK host."); public DocumentationSourceContractTests() { Write("InnoEngine.sln", "Microsoft Visual Studio Solution File, Format Version 12.00\n"); - Write(C_PROJECT, "net10.0enable"); + Write( + C_PROJECT, + "net10.0enable" + ); } [Fact] @@ -51,7 +57,9 @@ public class NotExported { } string facts = Path.Combine(m_root, "scope.json"); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(facts))); using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(facts)); - var symbols = document.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray() + Dictionary symbols = document.RootElement.GetProperty("projects")[0] + .GetProperty("symbols") + .EnumerateArray() .ToDictionary(symbol => symbol.GetProperty("id").GetString()!); Assert.Equal("Runtime", symbols["M:Contract.Outer.Read"].GetProperty("scriptingScope").GetString()); Assert.Equal("Editor", symbols["T:Contract.Outer.Inner"].GetProperty("scriptingScope").GetString()); @@ -91,7 +99,8 @@ public sealed class Probe Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(facts))); using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(facts)); JsonElement[] symbols = document.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray().ToArray(); - string Signature(string id) => symbols.Single(symbol => symbol.GetProperty("id").GetString() == id).GetProperty("signature").GetString()!; + string Signature(string id) + => symbols.Single(symbol => symbol.GetProperty("id").GetString() == id).GetProperty("signature").GetString()!; Assert.Contains("sealed", Signature("T:Contract.Probe")); Assert.Contains("readonly", Signature("T:Contract.Token")); Assert.Contains("delegate string", Signature("T:Contract.Transform")); @@ -103,14 +112,23 @@ public sealed class Probe Assert.Contains("IReader", Signature("T:Contract.Snapshot")); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.#ctor(System.String)"); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "P:Contract.Snapshot.Value"); - Assert.Contains("borrowed value", symbols.Single(symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.Read").GetProperty("documentation").GetString()); + Assert.Contains( + "borrowed value", + symbols + .Single(symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.Read") + .GetProperty("documentation") + .GetString() + ); Assert.DoesNotContain(symbols, symbol => symbol.GetProperty("id").GetString()!.Contains("m_value", StringComparison.Ordinal)); string comparison = Path.Combine(m_root, "comparison.json"); string[] arguments = ["--engine-root", m_root, "--dotnet", m_host, "--reference", facts, "--output", comparison]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(arguments)); - Write("tests/support/Contract/Contract.cs", C_SOURCE.Replace("sealed class Probe", "class Probe", StringComparison.Ordinal) - .Replace("ref readonly int Read()", "ref int Read()", StringComparison.Ordinal) - .Replace("string? name = null", "string name = \"default\"", StringComparison.Ordinal)); + Write( + "tests/support/Contract/Contract.cs", + C_SOURCE.Replace("sealed class Probe", "class Probe", StringComparison.Ordinal) + .Replace("ref readonly int Read()", "ref int Read()", StringComparison.Ordinal) + .Replace("string? name = null", "string name = \"default\"", StringComparison.Ordinal) + ); Assert.Equal(1, await DocumentationReferences.ValidateApiAsync(arguments)); string failures = File.ReadAllText(comparison); Assert.Contains("T:Contract.Probe", failures); @@ -122,22 +140,33 @@ public sealed class Probe public async Task CompileOnlyPackageContractsNeedNoRuntimeDeploymentAndCannotDisappear() { string reference = Path.Combine(m_root, "PackageContract.dll"); - var compilation = CSharpCompilation.Create("PackageContract", + CSharpCompilation compilation = CSharpCompilation.Create( + "PackageContract", [CSharpSyntaxTree.ParseText("namespace PackageContract; public abstract class BaseContract { }")], - ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator).Select(static file => MetadataReference.CreateFromFile(file)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Select(static file => MetadataReference.CreateFromFile(file)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(reference).Success); string feed = Path.Combine(m_root, "feed"); Directory.CreateDirectory(feed); using (ZipArchive package = ZipFile.Open(Path.Combine(feed, "ContractFixture.1.0.0.nupkg"), ZipArchiveMode.Create)) { using (var writer = new StreamWriter(package.CreateEntry("ContractFixture.nuspec").Open(), new UTF8Encoding(false))) - writer.Write("ContractFixture1.0.0InnoEngineCompile-only fixture."); + { + writer.Write( + "ContractFixture1.0.0InnoEngineCompile-only fixture." + ); + } package.CreateEntryFromFile(reference, "ref/net10.0/PackageContract.dll"); using Stream empty = package.CreateEntry("lib/net10.0/_._").Open(); } - Write(C_PROJECT, "net10.0" - + ""); + Write( + C_PROJECT, + "net10.0" + + "" + ); Write("tests/support/Contract/Contract.cs", "namespace Contract; public abstract class Probe : PackageContract.BaseContract;"); await RestoreAsync("--source", feed, "--packages", Path.Combine(m_root, "packages")); string output = Path.Combine(m_root, "facts.json"); @@ -155,14 +184,23 @@ public async Task CompileOnlyPackageContractsNeedNoRuntimeDeploymentAndCannotDis [Fact] public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceContract() { - Write("tests/support/Contract/Framework.props", "net10.0"); + Write( + "tests/support/Contract/Framework.props", + "net10.0" + ); const string C_PROJECT_TEXT = "" + "SELECTED_CONTRACT" + ""; Write(C_PROJECT, C_PROJECT_TEXT); - Write("tests/support/Contract/Contract.cs", "namespace Contract;\n#if SELECTED_CONTRACT\npublic sealed class Selected;\n#else\npublic sealed class WrongBranch;\n#endif\n"); + Write( + "tests/support/Contract/Contract.cs", + "namespace Contract;\n#if SELECTED_CONTRACT\npublic sealed class Selected;\n#else\npublic sealed class WrongBranch;\n#endif\n" + ); Write("tests/support/Contract/Excluded.cs", "public sealed class Excluded;"); - Write("tests/support/Contract/obj/Selected.cs", "namespace Contract; public sealed class Generated { public enum Kind { None, Present } }"); + Write( + "tests/support/Contract/obj/Selected.cs", + "namespace Contract; public sealed class Generated { public enum Kind { None, Present } }" + ); Write("tests/support/Contract/obj/Unselected.cs", "public sealed class Unselected;"); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); @@ -170,13 +208,30 @@ public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceCont string facts = File.ReadAllText(output); Assert.Contains("T:Contract.Selected", facts); Assert.Contains("F:Contract.Generated.Kind.Present", facts); - foreach (string excluded in new[] { "WrongBranch", "Excluded", "Unselected" }) Assert.DoesNotContain(excluded, facts); - Write(C_PROJECT, C_PROJECT_TEXT.Replace("", "99.0", StringComparison.Ordinal)); - InvalidDataException language = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + foreach (string excluded in new[] { "WrongBranch", "Excluded", "Unselected" }) + { + Assert.DoesNotContain(excluded, facts); + } + Write( + C_PROJECT, + C_PROJECT_TEXT.Replace("", "99.0", StringComparison.Ordinal) + ); + InvalidDataException language = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("unsupported C# language version", language.Message); Assert.Equal(facts, File.ReadAllText(output)); - Write(C_PROJECT, C_PROJECT_TEXT.Replace("", "", StringComparison.Ordinal)); - InvalidDataException missing = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + Write( + C_PROJECT, + C_PROJECT_TEXT.Replace( + "", + "", + StringComparison.Ordinal + ) + ); + InvalidDataException missing = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("requires its evaluated compile reference", missing.Message); Assert.Equal(facts, File.ReadAllText(output)); } @@ -184,7 +239,9 @@ public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceCont [Fact] public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiledDependencies() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ @@ -192,7 +249,8 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); const string C_SOURCE = "namespace Contract; internal sealed class Entry : UnavailableBase { public void Run() { } }"; Write("tests/support/Contract/Entry.cs", C_SOURCE); await RestoreAsync(); @@ -208,7 +266,9 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled } Assert.False(File.Exists(Path.Combine(m_root, "tests/support/Contract/bin/Debug/net10.0/Contract.dll"))); Write("tests/support/Contract/Entry.cs", C_SOURCE.Replace("internal sealed", "public sealed", StringComparison.Ordinal)); - InvalidDataException failure = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException failure = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("requires its evaluated compile reference", failure.Message); Assert.Equal(original, File.ReadAllBytes(output)); } @@ -216,11 +276,14 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled [Fact] public async Task EmptySurfaceUsesSelectedConditionalAndGeneratedSourceInputs() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ EXPOSE_CONTRACT - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); Write("tests/support/Contract/Entry.cs", "namespace Contract; internal sealed class Entry;"); Write("tests/support/Contract/obj/Selected.cs", """ namespace Contract; @@ -236,11 +299,15 @@ namespace Contract; Assert.Contains("T:Contract.GeneratedContract", File.ReadAllText(output)); byte[] previous = File.ReadAllBytes(output); Write("tests/support/Contract/obj/Selected.cs", "internal class Broken {"); - InvalidDataException invalid = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException invalid = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("invalid C# syntax", invalid.Message); Assert.Equal(previous, File.ReadAllBytes(output)); File.Delete(Path.Combine(m_root, "tests/support/Contract/obj/Selected.cs")); - InvalidDataException missing = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException missing = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("source is missing", missing.Message); Assert.Equal(previous, File.ReadAllBytes(output)); } @@ -248,13 +315,21 @@ namespace Contract; [Fact] public async Task ForeignProductSelectionCannotBorrowHostReferences() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", - "foreign-fixture", StringComparison.Ordinal)); + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace( + "", + "foreign-fixture", + StringComparison.Ordinal + ) + ); Write("tests/support/Contract/Contract.cs", "namespace Contract; public sealed class Probe;"); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); File.WriteAllText(output, "retain prior evidence"); - Assert.Throws(() => DocumentationReferences.ExportApi([..ExportArguments(output), "--target", "host-fixture"])); + Assert.Throws( + () => DocumentationReferences.ExportApi([..ExportArguments(output), "--target", "host-fixture"]) + ); Assert.Equal("retain prior evidence", File.ReadAllText(output)); } @@ -264,7 +339,10 @@ public async Task ExtractionReusesOwnersAndInvalidatesSameLengthSourceWithPreser const string C_OTHER = "src/Other/Other.csproj"; const string C_SOURCE = "namespace Contract;\n/// Alpha contract.\npublic sealed class Probe;"; Write("tests/support/Contract/Contract.cs", C_SOURCE); - Write(C_OTHER, "net10.0"); + Write( + C_OTHER, + "net10.0" + ); Write("src/Other/Other.cs", "namespace Other; public sealed class Independent;"); await RestoreAsync(); await RestoreProjectAsync(C_OTHER, []); @@ -274,9 +352,11 @@ public async Task ExtractionReusesOwnersAndInvalidatesSameLengthSourceWithPreser string cache = Path.Combine(m_root, "artifacts/documentation-export/extraction-cache/entries"); string[] originals = Directory.GetFiles(cache, "project.json", SearchOption.AllDirectories); Assert.Equal(2, originals.Length); - DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var retainedTime = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); foreach (string file in originals) + { File.SetLastWriteTimeUtc(file, retainedTime); + } byte[] previous = File.ReadAllBytes(output); Write("notes.md", "A report does not alter compiler inputs."); Assert.Equal(0, DocumentationReferences.ExportApi(arguments)); @@ -308,7 +388,9 @@ public async Task CorruptExtractionIsQuarantinedBeforeARealReplacementIsReturned File.SetLastWriteTimeUtc(payload, timestamp); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(output))); Assert.Equal(previous, File.ReadAllBytes(output)); - string quarantine = Assert.Single(Directory.GetFiles(Path.Combine(cache, "quarantine"), "project.json", SearchOption.AllDirectories)); + string quarantine = Assert.Single( + Directory.GetFiles(Path.Combine(cache, "quarantine"), "project.json", SearchOption.AllDirectories) + ); Assert.Equal(corrupt, File.ReadAllText(quarantine)); } @@ -328,14 +410,18 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( foreach (string file in Directory.GetFiles(entries, "*", SearchOption.AllDirectories)) { string relative = Path.GetRelativePath(entries, file); - Assert.True(relative.EndsWith("project.json", StringComparison.Ordinal) - || relative.EndsWith("generation-manifest.json", StringComparison.Ordinal)); + Assert.True( + relative.EndsWith("project.json", StringComparison.Ordinal) + || relative.EndsWith("generation-manifest.json", StringComparison.Ordinal) + ); string destination = Path.Combine(consumer.m_root, C_ENTRIES, relative); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(file, destination); } - string payload = Assert.Single(Directory.GetFiles(Path.Combine(consumer.m_root, C_ENTRIES), "project.json", SearchOption.AllDirectories)); - DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + string payload = Assert.Single( + Directory.GetFiles(Path.Combine(consumer.m_root, C_ENTRIES), "project.json", SearchOption.AllDirectories) + ); + var retainedTime = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); File.SetLastWriteTimeUtc(payload, retainedTime); string result = Path.Combine(consumer.m_root, "facts.json"); Assert.Equal(0, DocumentationReferences.ExportApi(consumer.ExportArguments(result))); @@ -350,18 +436,26 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( public async Task ExtractionInvalidatesInheritedXmlWithoutChangingTheReferenceAssembly() { string reference = Path.Combine(m_root, "BaseContract.dll"); - var compilation = CSharpCompilation.Create("BaseContract", + CSharpCompilation compilation = CSharpCompilation.Create( + "BaseContract", [CSharpSyntaxTree.ParseText("namespace BaseContract; public abstract class Parent { public abstract void Read(); }")], ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) .Select(static file => MetadataReference.CreateFromFile(file)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(reference).Success); string xml = Path.ChangeExtension(reference, ".xml"); const string C_XML = "Alpha obligation."; File.WriteAllText(xml, C_XML); - Write(C_PROJECT, "net10.0" - + "../../../BaseContract.dll"); - Write("tests/support/Contract/Contract.cs", "namespace Contract; public sealed class Probe : BaseContract.Parent {\n/// \npublic override void Read() {} }"); + Write( + C_PROJECT, + "net10.0" + + "../../../BaseContract.dll" + ); + Write( + "tests/support/Contract/Contract.cs", + "namespace Contract; public sealed class Probe : BaseContract.Parent {\n/// \npublic override void Read() {} }" + ); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(output))); @@ -376,11 +470,15 @@ public async Task ExtractionInvalidatesInheritedXmlWithoutChangingTheReferenceAs public void Dispose() { string boundary = Path.Combine(Path.GetTempPath(), "InnoDocumentationSourceContracts") + Path.DirectorySeparatorChar; - if (!Path.GetFullPath(m_root).StartsWith(boundary, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Fixture ownership escaped."); + if (!Path.GetFullPath(m_root).StartsWith(boundary, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Fixture ownership escaped."); + } Directory.Delete(m_root, recursive: true); } - private string[] ExportArguments(string output) => ["--engine-root", m_root, "--dotnet", m_host, "--project", C_PROJECT, "--output", output]; + private string[] ExportArguments(string output) + => ["--engine-root", m_root, "--dotnet", m_host, "--project", C_PROJECT, "--output", output]; private Task RestoreAsync(params string[] arguments) => RestoreProjectAsync(C_PROJECT, arguments); @@ -388,8 +486,25 @@ private async Task RestoreProjectAsync( string project, string[] arguments ) { - var start = new ProcessStartInfo(m_host) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, project), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }.Concat(arguments)) start.ArgumentList.Add(argument); + var start = new ProcessStartInfo(m_host) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, project), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }.Concat(arguments) + ) { + start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task stdout = process.StandardOutput.ReadToEndAsync(); Task stderr = process.StandardError.ReadToEndAsync(); @@ -397,8 +512,10 @@ string[] arguments Assert.True(process.ExitCode == 0, await stdout + await stderr); } - private void Write(string relative, string text) - { + private void Write( + string relative, + string text + ) { string file = Path.Combine(m_root, relative); Directory.CreateDirectory(Path.GetDirectoryName(file)!); File.WriteAllText(file, text); diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs index 801b59ffe..3a38b82e7 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs @@ -4,6 +4,7 @@ using Xunit; namespace Inno.Tooling.Architecture.Tests; + [Collection("Architecture diagnostics")] public sealed class IntegrationBoundaryTests { @@ -19,19 +20,36 @@ public void ImportedTestDeclarationsCannotEscapeRootOwnership(string declaration Directory.CreateDirectory(owner); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); File.WriteAllText(Path.Combine(root, "TestSupport.props"), "" + declaration + ""); - File.WriteAllText(Path.Combine(owner, "Probe.csproj"), + File.WriteAllText( + Path.Combine(owner, "Probe.csproj"), "" - + "net10.0disable"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); - (_, string report) = ArchitectureCommandFixture.Run(root, "--source-only", "--dotnet", host, - "--artifacts-path", Path.Combine(root, "artifacts")); + + "net10.0disable" + ); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); + (_, string report) = ArchitectureCommandFixture.Run( + root, + "--source-only", + "--dotnet", + host, + "--artifacts-path", + Path.Combine(root, "artifacts") + ); Assert.Contains("effective test projects must belong to the root tests directory", report, StringComparison.Ordinal); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -54,15 +72,19 @@ bool rejected string directory = Path.Combine(root, owner); Directory.CreateDirectory(directory); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); - File.WriteAllText(Path.Combine(directory, "Probe.csproj"), - "" + properties + "" + items + ""); + File.WriteAllText( + Path.Combine(directory, "Probe.csproj"), + "" + properties + "" + items + "" + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, report.Contains("engine-owned tests and test support must belong", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -70,21 +92,76 @@ bool rejected [InlineData("src/services/Probe", "tests/core/Probe.Tests", "production code cannot reference test support", true)] [InlineData("tests/build/Probe.Tests", "tests/build/fixtures/Probe.Support", "production code cannot reference test support", false)] [InlineData("platforms/WindowsX64/build/Probe", "backends/Bgfx/build/ProbeBackend", "platform base modules cannot select", true)] - [InlineData("platforms/WindowsX64/integrations/Probe", "backends/Bgfx/build/ProbeBackend", "platform base modules cannot select", false)] + [InlineData( + "platforms/WindowsX64/integrations/Probe", + "backends/Bgfx/build/ProbeBackend", + "platform base modules cannot select", + false + )] [InlineData("backends/Bgfx/build/ProbeBackend", "platforms/WindowsX64/integrations/Probe", "reusable backends cannot depend", true)] - [InlineData("platforms/BrowserWasm32/integrations/Probe", "platforms/WindowsX64/integrations/ProbeWindows", "one concrete platform cannot depend", true)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx", "runtime surface integrations cannot depend", false)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx", "runtime surface integrations cannot depend", true)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "backends/Bgfx/native/Inno.Native.Bgfx", "runtime surface integrations cannot depend", true)] + [InlineData( + "platforms/BrowserWasm32/integrations/Probe", + "platforms/WindowsX64/integrations/ProbeWindows", + "one concrete platform cannot depend", + true + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx", + "runtime surface integrations cannot depend", + false + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx", + "runtime surface integrations cannot depend", + true + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "backends/Bgfx/native/Inno.Native.Bgfx", + "runtime surface integrations cannot depend", + true + )] [InlineData("build/toolchains/Probe", "build/bindings/Inno.Build.Bindings", "neutral toolchains cannot depend", true)] [InlineData("build/bindings/Inno.Build.Bindings", "build/tasks/Inno.Build.Tasks", "binding generation cannot depend", true)] [InlineData("platforms/WindowsX64/build/Probe", "build/bindings/Inno.Build.Bindings", "platform modules must borrow", true)] - [InlineData("src/composition/editor/features/Inno.Editor.TestFeature", "src/composition/editor/presentation/Inno.Editor.ImGui", "Editor feature editing must be presentation-independent", true)] - [InlineData("src/composition/editor/features/Inno.Editor.TestFeature", "src/composition/editor/framework/Inno.Editor.Interactions", "Editor feature editing must be presentation-independent", false)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "src/composition/editor/panels/Inno.Editor.Panel.B", "Panels cannot depend on other Panels", true)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "src/composition/editor/presentation/Inno.Editor.Assets.ImGui", "Panels cannot depend on other Panels", false)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "backends/ImGui/native/Inno.Native.ImGui", "native UI access belongs", true)] - [InlineData("src/composition/editor/presentation/Inno.Editor.Graph.ImGui", "src/composition/editor/features/Inno.Editor.Shaders", "reusable Graph mechanisms cannot depend", true)] + [InlineData( + "src/composition/editor/features/Inno.Editor.TestFeature", + "src/composition/editor/presentation/Inno.Editor.ImGui", + "Editor feature editing must be presentation-independent", + true + )] + [InlineData( + "src/composition/editor/features/Inno.Editor.TestFeature", + "src/composition/editor/framework/Inno.Editor.Interactions", + "Editor feature editing must be presentation-independent", + false + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "src/composition/editor/panels/Inno.Editor.Panel.B", + "Panels cannot depend on other Panels", + true + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "src/composition/editor/presentation/Inno.Editor.Assets.ImGui", + "Panels cannot depend on other Panels", + false + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "backends/ImGui/native/Inno.Native.ImGui", + "native UI access belongs", + true + )] + [InlineData( + "src/composition/editor/presentation/Inno.Editor.Graph.ImGui", + "src/composition/editor/features/Inno.Editor.Shaders", + "reusable Graph mechanisms cannot depend", + true + )] public void CliChecksActualPlatformIntegrationProjectReferences( string owner, string dependency, @@ -97,7 +174,12 @@ bool rejected Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string destination = CreateProject(dependency, string.Empty); - CreateProject(owner, ""); + CreateProject( + owner, + "" + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, report.Contains(expected, StringComparison.Ordinal)); Assert.DoesNotContain("explicit project dependency is missing", report); @@ -108,14 +190,19 @@ string references string directory = Path.Combine(root, relative); Directory.CreateDirectory(directory); string path = Path.Combine(directory, Path.GetFileName(directory) + ".csproj"); - File.WriteAllText(path, "net10.0" + references + ""); + File.WriteAllText( + path, + "net10.0" + references + "" + ); return path; } } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -133,20 +220,30 @@ public void ScriptSdkReferencesPanelContractsOnlyWhenThePanelActuallyExportsThem Directory.CreateDirectory(Path.Combine(panel, "Properties")); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string panelProject = Path.Combine(panel, "Inno.Editor.Panel.Probe.csproj"); - File.WriteAllText(panelProject, "net10.0"); + File.WriteAllText( + panelProject, + "net10.0" + ); string include = Path.GetRelativePath(host, panelProject).Replace('\\', '/'); - File.WriteAllText(Path.Combine(host, "Inno.Build.Cli.csproj"), + File.WriteAllText( + Path.Combine(host, "Inno.Build.Cli.csproj"), "net10.0"); + + include + "\" />" + ); const string C_EXPORT_DECLARATION = "[assembly: Inno.Scripting.Api.ScriptingApiExport(typeof(System.String), Inno.Scripting.Api.ScriptingApiScope.Editor)]"; - File.WriteAllText(Path.Combine(panel, "Properties/ScriptingApi.cs"), exportsContract ? C_EXPORT_DECLARATION : "// " + C_EXPORT_DECLARATION); + File.WriteAllText( + Path.Combine(panel, "Properties/ScriptingApi.cs"), + exportsContract ? C_EXPORT_DECLARATION : "// " + C_EXPORT_DECLARATION + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(!exportsContract, report.Contains("script SDK host must reference API owners", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs index 04a3dba82..b37f6580f 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs @@ -17,9 +17,7 @@ public sealed class NativePlatformPolicyTests public void ComponentConfigurationCannotOwnPlatformPolicy( string configuration, bool rejected - ) { - Run(configuration, false, rejected); - } + ) => Run(configuration, false, rejected); [Fact] public void ComponentCannotKeepAnAdditionalTargetPreset() => Run("{}", true, true); @@ -39,17 +37,21 @@ bool rejected File.WriteAllText(Path.Combine(bindings, "bindings.props"), ""); File.WriteAllText(Path.Combine(bindings, "bindgen.json"), configuration); if (targetPreset) + { File.WriteAllText(Path.Combine(bindings, "bindgen.probe-target.json"), "{}"); + } (_, string output) = ArchitectureCommandFixture.Run(root); bool violation = output.Contains("belongs to a platform Profile", StringComparison.Ordinal) - || output.Contains("must be supplied by the platform provider", StringComparison.Ordinal) - || output.Contains("platform binding presets belong", StringComparison.Ordinal); + || output.Contains("must be supplied by the platform provider", StringComparison.Ordinal) + || output.Contains("platform binding presets belong", StringComparison.Ordinal); Assert.Equal(rejected, violation); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs index b29d1425e..849e3561b 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Reflection; using System.Reflection.Emit; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Tooling.Architecture.Tests; @@ -11,7 +11,10 @@ public sealed class RepositoryInputTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoRepositoryInputs", Guid.NewGuid().ToString("N")); - public RepositoryInputTests() => Directory.CreateDirectory(m_root); + public RepositoryInputTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void EachAssemblyUsesItsOwnDeclaredSource() @@ -25,10 +28,7 @@ public void EachAssemblyUsesItsOwnDeclaredSource() } [Fact] - public void NullAssemblyIsRejectedBeforeReadingMetadata() - { - Assert.Throws(() => TestRepository.GetRoot(null!)); - } + public void NullAssemblyIsRejectedBeforeReadingMetadata() => Assert.Throws(() => TestRepository.GetRoot(null!)); [Fact] public void MissingRelativeAndUnavailableDeclarationsAreRejected() @@ -39,8 +39,7 @@ public void MissingRelativeAndUnavailableDeclarationsAreRejected() CreateAssembly("relative-checkout"), CreateAssembly(Path.Combine(m_root, "absent")), CreateAssembly(m_root) - }) - { + }) { Assert.Throws(() => TestRepository.GetRoot(assembly)); } } @@ -70,7 +69,9 @@ private static Assembly CreateAssembly(params string[] directories) AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); ConstructorInfo constructor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; foreach (string directory in directories) + { assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, ["Inno.Testing.RepositoryRoot", directory])); + } return assembly; } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs new file mode 100644 index 000000000..ac7293ba8 --- /dev/null +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -0,0 +1,2273 @@ +using System; +using System.IO; +using System.Text.RegularExpressions; +using Xunit; + +namespace Inno.Tooling.Architecture.Tests; + +public sealed class StyleCommandTests +{ + [Theory] + [MemberData(nameof(Fixes))] + public void FixRewritesTheReportedViolationAndLeavesNoFinding( + string rule, + string before, + string after + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string report = Path.Combine(root, "report.tsv"); + File.WriteAllText(path, before); + + Assert.Equal(1, StyleCommand.Execute(["check", root, "--rule", rule, "--report", report])); + Assert.StartsWith(rule + "\tsrc/Probe.cs\t", File.ReadAllText(report), StringComparison.Ordinal); + Assert.Equal(before, File.ReadAllText(path)); + + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(after, File.ReadAllText(path)); + Assert.Equal(0, StyleCommand.Execute(["check", root])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [MemberData(nameof(Kept))] + public void ExemptConstructsAreNeitherReportedNorRewritten( + string rule, + string text + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", FirstTypeName(text) + ".cs"); + string report = Path.Combine(root, "report.tsv"); + File.WriteAllText(path, text); + + Assert.Equal(0, StyleCommand.Execute(["check", root, "--rule", rule])); + StyleCommand.Execute(["fix", root, "--report", report]); + Assert.Equal(text, File.ReadAllText(path)); + + // A probe may declare several types to cover one rule; no other rule reports it. + Assert.All(File.ReadAllLines(report), static line => Assert.StartsWith("F-02\t", line, StringComparison.Ordinal)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("T-03", "internal class Probe;")] + [InlineData("T-03", "internal record Probe(int value);")] + [InlineData("T-04", "internal record struct Probe(int value);")] + [InlineData("T-01", "partial class Probe;")] + [InlineData("N-01", "namespace Probe\n{\n internal sealed class Sample;\n}")] + [InlineData("N-03", "global using System;")] + [InlineData("N-03", "namespace Probe;\n\nusing System;")] + [InlineData("N-03", "internal sealed class Probe\n{\n private readonly global::System.Text.StringBuilder m_text = new();\n}")] + [InlineData("NM-01", "internal sealed class probe;")] + [InlineData("NM-02", "internal interface Probe;")] + [InlineData("NM-02", "internal sealed class Probe;")] + [InlineData("NM-03", "internal sealed class Probe\n{\n internal void run() {}\n}")] + [InlineData("NM-04", "internal sealed class Probe\n{\n internal Task Run() => Task.CompletedTask;\n}")] + [InlineData("NM-05", "internal sealed class Probe\n{\n internal int Count => 0;\n}")] + [InlineData("NM-06", "internal sealed class Probe\n{\n private int count;\n}")] + [InlineData("NM-06", "internal sealed class Probe\n{\n internal int m_count;\n}")] + [InlineData("NM-06", "internal sealed class Probe\n{\n private int m_first, m_second;\n}")] + [InlineData("NM-07", "internal sealed class Probe\n{\n private const int LIMIT = 1;\n}")] + [InlineData("NM-07", "internal sealed class Probe\n{\n internal void Run()\n {\n const int limit = 1;\n }\n}")] + [InlineData("NM-08", "internal sealed class Probe\n{\n private static readonly int[] S_SIZES = [];\n}")] + [InlineData("NM-08", "internal sealed class Probe\n{\n private static readonly int[] sizes = [];\n}")] + [InlineData("NM-09", "internal sealed class Probe\n{\n private static int m_next;\n}")] + [InlineData("NM-10", "internal sealed class Probe\n{\n internal event Action Changed;\n}")] + [InlineData("NM-11", "internal enum Probe\n{\n first\n}")] + [InlineData("NM-12", "internal sealed class Probe\n{\n internal void Run(int Count) {}\n}")] + [InlineData("NM-12", "internal sealed class Probe\n{\n internal (int Width, int height) size => (0, 0);\n}")] + [InlineData("NM-13", "internal sealed class UiProbe;")] + [InlineData("NM-13", "internal sealed class Probe\n{\n internal int assetId => 0;\n}")] + [InlineData("NM-13", "internal sealed class Probe\n{\n internal void Run(int[] assetIds) {}\n}")] + [InlineData( + "E-08", + "internal sealed class Probe\n{\n internal Probe()\n {\n count = 1;\n }\n\n internal int count { get; }\n}" + )] + [InlineData( + "E-08", + "internal sealed class Probe\n{\n internal int count { get; set; }\n\n internal int Read() => this.count;\n}" + )] + [InlineData("N-05", "internal sealed class Probe\n{\n internal System.Text.StringBuilder text => new();\n}")] + [InlineData("N-05", "internal sealed class Probe\n{\n internal bool Has(string path) => System.IO.File.Exists(path);\n}")] + [InlineData("N-06", "using Path = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("N-06", "using nativePath = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("N-06", "using FilePath = System.IO.Path;\nusing NativePath = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("E-04", "internal sealed class Probe\n{\n internal bool Has(object? value) => !(value is null);\n}")] + [InlineData( + "E-06", + "internal sealed class Probe\n{\n internal void Run()\n {\n Use(new());\n }\n\n private void Use(object value) {}\n}" + )] + [InlineData("E-06", "internal sealed class Probe\n{\n internal void Run()\n {\n object value = new();\n }\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly int[] m_values = new[] { 1, 2 };\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly int[] m_values = Array.Empty();\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly List m_values = new();\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n internal void Run()\n {\n var values = new List();\n }\n}")] + [InlineData( + "E-05", + "internal sealed class Probe\n{\n internal void Run(object value)\n {\n if (value is null) throw new ArgumentNullException(nameof(value));\n }\n}" + )] + [InlineData( + "E-05", + "internal sealed class Probe\n{\n internal object Run(object value)\n {\n return value ?? throw new ArgumentNullException(nameof(value));\n }\n}" + )] + [InlineData("P-03", "internal sealed class Probe\n{\n internal void Run(CancellationToken token) {}\n}")] + [InlineData("P-03", "internal sealed class Probe\n{\n internal void Run(CancellationToken cancellationToken, int count) {}\n}")] + [InlineData( + "P-03", + "internal sealed class Probe\n{\n internal void Run(CancellationToken cancellationToken = default, int count = 0) {}\n}" + )] + [InlineData("D-06", "internal sealed class Probe\n{\n #region State\n internal int count => 0;\n #endregion\n}")] + [InlineData("D-06", "#nullable disable\ninternal sealed class Probe;")] + [InlineData("D-06", "internal sealed class Probe\n{\n /* The count. */\n internal int count => 0;\n}")] + [InlineData("E-09", "internal sealed class Probe\n{\n internal string Name(int value) => string.Format(\"item-{0}\", value);\n}")] + [InlineData( + "E-09", + "internal sealed class Probe\n{\n internal string Name(string first, string second) => string.Concat(first, second);\n}" + )] + [InlineData("M-02", "internal sealed class Probe\n{\n internal int Read()\n {\n return 1;\n }\n}")] + [InlineData("M-02", "internal sealed class Probe\n{\n private int m_count;\n\n internal Probe() => m_count = 1;\n}")] + [InlineData("F-02", "internal sealed class Sample;")] + [InlineData("F-02", "internal enum ProbeKind\n{\n First\n}\n\ninternal sealed class Probe;")] + [InlineData("F-02", "internal sealed class Probe;\n\ninternal sealed class Sample;")] + [InlineData("F-02", "internal sealed class Probe;\n\ninternal sealed record ProbeOptions\n{\n internal int value { get; init; }\n}")] + public void FindingsThatNeedTheAuthorAreReportedAndLeftUnchanged( + string rule, + string text + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string report = Path.Combine(root, "report.tsv"); + File.WriteAllText(path, Source(text)); + + Assert.Equal(1, StyleCommand.Execute(["check", root, "--rule", rule, "--report", report])); + Assert.StartsWith(rule + "\tsrc/Probe.cs\t", File.ReadAllText(report), StringComparison.Ordinal); + Assert.Equal(1, StyleCommand.Execute(["fix", root, "--rule", rule])); + Assert.Equal(Source(text), File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("src/Generated/Probe.cs", "internal sealed class Probe { }\n")] + [InlineData("src/Probe.cs", "// \ninternal sealed class Probe { }\n")] + [InlineData("src/Probe.cs", "[GeneratedCode(\"Tool\", \"1\")]\ninternal sealed class Probe { }\n")] + [InlineData("extern/Probe.cs", "internal sealed class Probe { }\n")] + [InlineData("src/obj/Probe.cs", "internal sealed class Probe { }\n")] + public void GeneratedAndThirdPartySourcesAreNeitherReportedNorRewritten( + string relativePath, + string content + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + + Assert.Equal(0, StyleCommand.Execute(["check", root])); + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("// ")] + [InlineData("[GeneratedCode(\\\"Tool\\\", \\\"1\\\")]")] + public void SourcesThatOnlyWriteAGeneratedMarkerAreHandwritten(string marker) + { + string content = "internal sealed class Probe\n{\n internal string Run() { return \"" + marker + "\"; }\n}\n"; + + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + + Assert.Equal(1, StyleCommand.Execute(["check", root])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void ARuleFilterReportsOnlyTheRequestedRuleOfARuleFamily() + { + string root = CreateRoot(); + try + { + string report = Path.Combine(root, "report.tsv"); + File.WriteAllText( + Path.Combine(root, "src", "Probe.cs"), + Source("internal sealed class Probe\n{\n internal int Count => 0;\n\n internal int assetId => 0;\n}") + ); + + Assert.Equal(1, StyleCommand.Execute(["check", root, "--rule", "NM-13", "--report", report])); + string line = Assert.Single(File.ReadAllLines(report)); + Assert.StartsWith("NM-13\tsrc/Probe.cs\t5\t", line, StringComparison.Ordinal); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("Probe.Observation.cs", "internal sealed partial class Probe;\n", 0)] + [InlineData("Probe.Observation.cs", "internal sealed partial class Observation;\n", 1)] + [InlineData("Usings.cs", "using System;\n", 0)] + public void APartFileIsNamedAfterTheTypeItExtends( + string name, + string text, + int expected + ) { + string root = CreateRoot(); + try + { + File.WriteAllText(Path.Combine(root, "src", name), text); + + Assert.Equal(expected, StyleCommand.Execute(["check", root, "--rule", "F-02"])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void FixKeepsTextInsideMultiLineStrings() + { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string content = "internal sealed class Probe\n{\n internal string Text() => \"\"\"\n if (first) { \n second();\n \"\"\";\n}\n"; + File.WriteAllText(path, content); + + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void FixLeavesASourceWithSyntaxErrorsUnchangedAndFails() + { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string content = "internal sealed class Probe {\n internal void Run( {\n}\n"; + File.WriteAllText(path, content); + + Assert.Equal(1, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void PathsFromLimitsTheRunToTheListedSources() + { + string root = CreateRoot(); + try + { + string listed = Path.Combine(root, "src", "Listed.cs"); + string other = Path.Combine(root, "src", "Other.cs"); + string paths = Path.Combine(root, "paths.txt"); + File.WriteAllText(listed, "internal sealed class Listed { }\n"); + File.WriteAllText(other, "internal sealed class Other { }\n"); + File.WriteAllText(paths, "src/Listed.cs\n"); + + Assert.Equal(0, StyleCommand.Execute(["fix", root, "--paths-from", paths])); + Assert.Equal("internal sealed class Listed;\n", File.ReadAllText(listed)); + Assert.Equal("internal sealed class Other { }\n", File.ReadAllText(other)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData] + [InlineData("check")] + [InlineData("format", ".")] + [InlineData("check", ".", "--rule")] + [InlineData("check", ".", "--unknown", "value")] + public void InvalidArgumentsAreRejected(params string[] arguments) => Assert.Throws( + () => StyleCommand.Execute(arguments) + ); + + public static TheoryData Fixes() + => new() + { + { + "F-01", + "internal sealed class Probe; \r\n\r\n", + Source( + """ + internal sealed class Probe; + """ + ) + }, + { + "N-04", + Source( + """ + using Inno.Core; + using static System.Math; + using System; + + namespace Probe; + """ + ), + Source( + """ + using System; + using Inno.Core; + + using static System.Math; + + namespace Probe; + """ + ) + }, + { + "F-03", + "\nusing System;\nnamespace Probe;\ninternal sealed class Probe;\n", + Source( + """ + using System; + + namespace Probe; + + internal sealed class Probe; + """ + ) + }, + { + "S-03", + Source( + """ + internal sealed class Probe + { + internal void First() {} + internal void Second() {} + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void First() {} + + internal void Second() {} + } + """ + ) + }, + { + "S-04", + Source( + """ + internal sealed class Probe + { + + internal void First() {} + + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void First() {} + } + """ + ) + }, + { + "A-01", + Source( + """ + internal sealed class Probe + { + internal int Run() => Add(1, + 2); + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() => Add(1, 2); + } + """ + ) + }, + { + "A-02", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, + fourthArgumentWithALongName, fifthArgumentWithALongName); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Register( + firstArgumentWithALongName, + secondArgumentWithALongName, + thirdArgumentWithALongName, + fourthArgumentWithALongName, + fifthArgumentWithALongName + ); + } + } + """ + ) + }, + { + "P-01", + Source( + """ + internal sealed class Probe + { + internal void Run(int first, int second) {} + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) {} + } + """ + ) + }, + { + "P-02", + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) + { + Begin(); + Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) { + Begin(); + Step(); + } + } + """ + ) + }, + { + "B-03", + Source( + """ + internal sealed class Probe : Base + { + internal Probe(int value) : base(value) {} + } + """ + ), + Source( + """ + internal sealed class Probe : Base + { + internal Probe(int value) + : base(value) {} + } + """ + ) + }, + { + "M-03", + Source( + """ + internal sealed class Probe + { + internal int Run() => + m_value; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() => m_value; + } + """ + ) + }, + { + "W-01", + Source( + """ + internal sealed class Probe + { + internal bool Run() => m_first && + m_second; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal bool Run() + => m_first + && m_second; + } + """ + ) + }, + { + "W-03", + Source( + """ + internal sealed class Probe + { + internal int Run() + { + Begin(); + return m_values.Where(static value => value > 0).Select(static value => value * 2). + Sum(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() + { + Begin(); + return m_values.Where(static value => value > 0) + .Select(static value => value * 2) + .Sum(); + } + } + """ + ) + }, + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal Probe() { Step(); } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal Probe() + { + Step(); + } + } + """ + ) + }, + { + "B-04", + Source( + """ + internal sealed class Probe + { + internal bool Run() => m_entries.All(static entry => entry.isReadyForPresentation && entry.owner.isVisibleInHierarchy + && entry.isVisible); + + internal Func Count() => () => m_first.TryGetValue( + m_key, + out int value + ) && value > 0 + ? value + : 0; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal bool Run() + => m_entries.All(static entry => ( + entry.isReadyForPresentation && entry.owner.isVisibleInHierarchy + && entry.isVisible + )); + + internal Func Count() + => () => ( + m_first.TryGetValue(m_key, out int value) && value > 0 + ? value + : 0 + ); + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_width >= 500) Assert.True(m_details, "The details column is expected to be visible once the panel is at least five hundred wide."); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_width >= 500) + { + Assert.True(m_details, "The details column is expected to be visible once the panel is at least five hundred wide."); + } + } + } + """ + ) + }, + { + "B-01", + Source( + """ + internal sealed class Probe { + internal Probe() { + Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal Probe() + { + Step(); + } + } + """ + ) + }, + { + "B-07", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + } + + private sealed class Empty { } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() {} + + private sealed class Empty; + } + """ + ) + }, + { + "W-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first + && m_second) + { + Step(); + } + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first + && m_second + ) { + Step(); + } + } + } + """ + ) + }, + { + "B-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first) + Step(); + foreach (int value in m_values) Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first) + { + Step(); + } + foreach (int value in m_values) + { + Step(); + } + } + } + """ + ) + }, + { + "F-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool both = m_first + && m_second; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool both = m_first + && m_second; + } + } + """ + ) + }, + { + "I-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new Options { + first = 1, second = 2 }; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new Options + { + first = 1, + second = 2 + }; + } + } + """ + ) + }, + { + "I-05", + Source( + """ + internal enum Probe + { + First, + Second, + } + """ + ), + Source( + """ + internal enum Probe + { + First, + Second + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, fourthArgumentWithALongName, fifthArgumentWithALongName); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Register( + firstArgumentWithALongName, + secondArgumentWithALongName, + thirdArgumentWithALongName, + fourthArgumentWithALongName, + fifthArgumentWithALongName + ); + } + } + """ + ) + }, + { + "M-03", + Source( + """ + internal sealed class Probe + { + internal string Label() => m_isMissing ? "The asset is missing from the project." : + m_displayName; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal string Label() + => m_isMissing + ? "The asset is missing from the project." + : m_displayName; + } + """ + ) + }, + { + "I-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new ProbeOptions + { first = 1, second = 2 }; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new ProbeOptions { first = 1, second = 2 }; + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + List names = m_entries.Where(static entry => !entry.isMissing && entry.isVisible).Select(static entry => entry.displayName).OrderBy(static name => name).ToList(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + List names = m_entries + .Where(static entry => !entry.isMissing && entry.isVisible) + .Select(static entry => entry.displayName) + .OrderBy(static name => name) + .ToList(); + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool changed = previous.width != current.width || previous.height != current.height || previous.format != current.format || previous.depth != current.depth; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format + || previous.depth != current.depth; + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Report($"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'."); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Begin(); + Report( + $"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'." + ); + } + } + """ + ) + }, + { + "E-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Probe value = new Probe(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var value = new Probe(); + } + } + """ + ) + }, + { + "M-04", + Source( + """ + internal sealed class Probe + { + private readonly StringBuilder m_values = new StringBuilder(); + private int m_first = 1, m_second = 2; + } + """ + ), + Source( + """ + internal sealed class Probe + { + private readonly StringBuilder m_values = new(); + private int m_first = 1; + private int m_second = 2; + } + """ + ) + }, + { + "E-07", + Source( + """ + internal sealed class Probe + { + internal string Run(string value = "") + { + string text = ""; + return text + value; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal string Run(string value = "") + { + string text = string.Empty; + return text + value; + } + } + """ + ) + }, + { + "E-11", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Func twice = (value) => value * 2; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Func twice = value => value * 2; + } + } + """ + ) + }, + { + "E-10", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + float ratio = 1.0F; + uint mask = 0XFFu; + int count = 1000000; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + float ratio = 1f; + uint mask = 0xFFu; + int count = 1_000_000; + } + } + """ + ) + }, + { + "M-05", + Source( + """ + [Serializable, Obsolete()] + internal sealed class Probe + { + [ObsoleteAttribute] internal void Run() {} + } + """ + ), + Source( + """ + [Serializable] + [Obsolete] + internal sealed class Probe + { + [Obsolete] + internal void Run() {} + } + """ + ) + }, + { + "D-02", + Source( + """ + /// Runs the probe. + internal sealed class Probe + { + /// The value. + /// The input. + /// + /// + /// Returns null. + /// + internal object Run(object value) => null; + } + """ + ), + Source( + """ + /// + /// Runs the probe. + /// + internal sealed class Probe + { + /// + /// Returns . + /// + /// + /// The input. + /// + /// + /// The value. + /// + internal object Run(object value) => null; + } + """ + ) + }, + { + "D-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + int value = 1; //The first value. + Use(value); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + // The first value. + int value = 1; + Use(value); + } + } + """ + ) + }, + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal void Run(int kind) + { + int first = 1; int second = 2; + switch (kind) + { + case 0: Use(first); break; + default: Use(second); break; + } + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run(int kind) + { + int first = 1; + int second = 2; + switch (kind) + { + case 0: + Use(first); + break; + default: + Use(second); + break; + } + } + } + """ + ) + }, + { + "T-01", + Source( + """ + sealed class Probe + { + int m_count; + + [Obsolete] + static void Run() {} + + interface IProbe + { + public void Run(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + private int m_count; + + [Obsolete] + private static void Run() {} + + private interface IProbe + { + void Run(); + } + } + """ + ) + }, + { + "T-02", + Source( + """ + internal abstract class Probe + { + readonly static private int[] VALUES = []; + + override public string ToString() => string.Empty; + + async static internal Task RunAsync() => await Task.Yield(); + } + """ + ), + Source( + """ + internal abstract class Probe + { + private static readonly int[] VALUES = []; + + public override string ToString() => string.Empty; + + internal static async Task RunAsync() => await Task.Yield(); + } + """ + ) + }, + { + "E-03", + Source( + """ + using System; + + internal sealed class Probe + { + private readonly Int32 m_count = Int32.Parse("1"); + + internal String Name(Object value) => String.Join("-", value, m_count); + } + """ + ), + Source( + """ + using System; + + internal sealed class Probe + { + private readonly int m_count = int.Parse("1"); + + internal string Name(object value) => string.Join("-", value, m_count); + } + """ + ) + }, + { + "O-01", + Source( + """ + internal sealed class Probe + { + internal Probe() + { + m_items = []; + } + + private void Notify() => changed?.Invoke(); + + private readonly int[] m_items; + + internal int count => m_items.Length; + + private sealed class Entry; + + private bool m_isDirty; + private const int C_LIMIT = 4; + + internal event Action? changed; + + private static readonly int[] EMPTY = []; + } + """ + ), + Source( + """ + internal sealed class Probe + { + private const int C_LIMIT = 4; + + private static readonly int[] EMPTY = []; + + private readonly int[] m_items; + private bool m_isDirty; + + internal Probe() + { + m_items = []; + } + + internal int count => m_items.Length; + + internal event Action? changed; + + private void Notify() => changed?.Invoke(); + + private sealed class Entry; + } + """ + ) + }, + { + "O-01", + Source( + """ + internal sealed class Probe + { + public void Draw( + int mesh, + int material + ) { + Begin(); + Submit(mesh + material); + } + + private void Submit(int item) {} + + public static Probe Create() => new(); + + public void Clear() {} + + public void Draw(int mesh) => Draw(mesh, 0); + + void IDisposable.Dispose() {} + + protected void Reset() {} + + public int count => 0; + } + """ + ), + Source( + """ + internal sealed class Probe + { + public int count => 0; + + public void Draw(int mesh) => Draw(mesh, 0); + + public void Draw( + int mesh, + int material + ) { + Begin(); + Submit(mesh + material); + } + + public void Clear() {} + + void IDisposable.Dispose() {} + + public static Probe Create() => new(); + + protected void Reset() {} + + private void Submit(int item) {} + } + """ + ) + }, + { + "W-04", + Source( + """ + internal sealed class Probe + { + internal int Read(int first) + { + int total = + first + 1; + total + = total + 2; + return total; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Read(int first) + { + int total = first + 1; + total = total + 2; + return total; + } + } + """ + ) + }, + { + "E-12", + Source( + """ + using System.IO; + + internal sealed class Probe + { + internal int Read(string path) + { + int offset = 1; + using (FileStream stream = File.OpenRead(path)) + { + int value = stream.ReadByte(); + return value + offset; + } + } + } + """ + ), + Source( + """ + using System.IO; + + internal sealed class Probe + { + internal int Read(string path) + { + int offset = 1; + using FileStream stream = File.OpenRead(path); + int value = stream.ReadByte(); + return value + offset; + } + } + """ + ) + } + }; + + public static TheoryData Kept() + => new() + { + { + "F-02", + Source( + """ + internal sealed class Probe; + + internal sealed class Probe; + + internal enum ProbeKind + { + First + } + + internal delegate void ProbeChanged(ProbeKind kind); + + internal sealed record ProbeOptions(ProbeKind kind); + """ + ) + }, + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal Probe( + float m11, + float m12, + float m21, + float m22 + ) { + this.m11 = m11; this.m12 = m12; + this.m21 = m21; this.m22 = m22; + } + } + """ + ) + }, + { + "E-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var pair = new { name = "probe", count = 1 }; + var values = new int[4]; + int count = values.Length; + } + } + """ + ) + }, + { + "E-07", + Source( + """ + internal sealed class Probe + { + private const string C_NONE = ""; + + internal string Run(string value = "") + => value switch + { + "" => C_NONE, + _ => value + }; + } + """ + ) + }, + { + "E-10", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + decimal price = 1.50m; + double ratio = 1.0; + int year = 2026; + } + } + """ + ) + }, + { + "T-01", + Source( + """ + using System; + + internal sealed partial class Probe : IDisposable + { + static Probe() {} + + ~Probe() {} + + void IDisposable.Dispose() {} + + partial void Changed(); + + private enum Mode + { + None, + Active + } + + private interface IProbe + { + void Run(); + + protected void Reset(); + } + } + + file sealed class Local; + """ + ) + }, + { + "T-02", + Source( + """ + internal abstract class Probe + { + private const int C_LIMIT = 1; + + private static readonly int[] VALUES = []; + + public sealed override string ToString() => string.Empty; + + protected internal static new unsafe partial void Run(); + } + """ + ) + }, + { + "T-03", + Source( + """ + internal static class Helpers; + + internal abstract class Shape; + + /// + /// Describes a node. Derive from it to add a node kind. + /// + internal class Node; + + internal sealed class Leaf : Node; + + internal partial class Generated; + """ + ) + }, + { + "T-04", + Source( + """ + internal readonly record struct ProbeID(int value); + + internal record struct SerializedProbe + { + public string value { get; set; } + } + """ + ) + }, + { + "E-03", + Source( + """ + using System; + + internal sealed class Probe + { + internal object String() => this; + + internal string Describe() => nameof(Int32) + nameof(String); + + /// + /// Returns a . + /// + internal TypeCode Code() => TypeCode.Int32; + } + """ + ) + }, + { + "O-01", + Source( + """ + internal struct Vertex + { + public float x; + + public float length => x; + + public readonly float y; + } + + [StructLayout(LayoutKind.Sequential)] + internal sealed class NativeHeader + { + public int size; + public readonly int version = 1; + } + + internal sealed class Settings + { + [SerializableProperty] + public string name { get; set; } = string.Empty; + + [SerializableProperty] + private int m_revision; + } + + internal sealed class Registry + { + private static int s_next = 1; + private static readonly int FIRST = s_next++; + } + + internal sealed class Platform + { + internal void Run() {} + + #if DEBUG + private const int C_LIMIT = 1; + #endif + } + """ + ) + }, + { + "NM-03", + Source( + """ + internal static partial class NativeProbe + { + [LibraryImport("probe")] + internal static partial int probe_open(int Handle); + } + """ + ) + }, + { + "NM-04", + Source( + """ + internal sealed class ProbeTests + { + [Fact] + public Task RunCompletes() => Task.CompletedTask; + + [MetalShaderFact] + public Task ShaderCompiles() => Task.CompletedTask; + } + + internal sealed class Worker : IWorker + { + public Task Run() => Task.CompletedTask; + } + """ + ) + }, + { + "NM-05", + Source( + """ + internal sealed class ProbeList : ICollection + { + public int Count => 0; + } + """ + ) + }, + { + "NM-06", + Source( + """ + internal sealed class Probe + { + [SerializableProperty] + internal string m_targetId = string.Empty; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct NativeProbe + { + public int Width; + public int Height; + } + """ + ) + }, + { + "NM-11", + Source( + """ + internal enum ProbeKey + { + _0, + _1, + A + } + """ + ) + }, + { + "NM-12", + Source( + """ + internal sealed class Probe + { + internal Func zero => static _ => 0; + } + """ + ) + }, + { + "NM-13", + Source( + """ + internal sealed class ImGuiProbe + { + [SerializableProperty] + internal Guid persistentId { get; set; } + + internal Guid stableTypeId { get; set; } + + internal RmlUiHandle rmlUiHandle { get; set; } + } + + internal sealed record PageReference(string pageId); + """ + ) + }, + { + "N-05", + Source( + """ + using System.IO; + + using NativePath = System.IO.Path; + + namespace Inno.Probe; + + internal sealed class Probe + { + internal static string Name(string path) => NativePath.GetFileName(path) + Path.DirectorySeparatorChar; + } + """ + ) + }, + { + "N-06", + Source( + """ + using NativePath = System.IO.Path; + using TextBuffer = System.Text.StringBuilder; + + internal sealed class Probe + { + internal static string Name(string path) => new TextBuffer(NativePath.GetFileName(path)).ToString(); + } + """ + ) + }, + { + "E-04", + Source( + """ + internal sealed class Probe + { + internal bool Has(object? value) => value is not null && !(value is string); + + internal bool Lacks(Probe? value) => value == null; + } + """ + ) + }, + { + "E-08", + Source( + """ + internal sealed class Probe + { + private readonly int m_seed; + + internal Probe(int count) + { + m_seed = count; + this.count = count; + } + + internal int count { get; private set; } + + internal int seed => m_seed; + + internal void Reset(int count) + { + this.count = count; + Notify(); + } + } + """ + ) + }, + { + "W-04", + Source( + """ + internal sealed class Probe + { + internal int[] Read() + { + int[] values = + [ + 1, + 2 + ]; + return values; + } + } + """ + ) + }, + { + "E-12", + Source( + """ + using System; + using System.IO; + + internal sealed class Probe + { + internal int Read( + string path, + IDisposable scope + ) { + using (FileStream first = File.OpenRead(path)) + { + int value = first.ReadByte(); + if (value < 0) return value; + } + using (scope) + { + return 0; + } + } + + internal int ReadTwice(string path) + { + { + int value = 1; + if (value < 0) return value; + } + using (FileStream stream = File.OpenRead(path)) + { + int value = stream.ReadByte(); + return value; + } + } + } + """ + ) + }, + { + "E-06", + Source( + """ + using System.Collections.Generic; + using System.Text; + + internal sealed class Probe + { + private readonly StringBuilder m_text = new(); + + internal List values { get; set; } = new(4); + + internal StringBuilder Create() => new(); + + internal StringBuilder Reset() + { + var text = new StringBuilder(); + values = new(8); + Append(new StringBuilder()); + return new(); + } + + private void Append(StringBuilder text) {} + } + """ + ) + }, + { + "I-02", + Source( + """ + using System.Collections.Generic; + using System.Linq; + + internal sealed class Probe + { + private readonly List m_sized = new(16); + private readonly int[] m_buffer = new int[4]; + + internal int[] values { get; } = [1, 2]; + + internal int Count(IEnumerable source) + { + var copy = new List(source); + List empty = []; + return copy.Count + empty.Count + new[] { 1, 2 }.Sum(); + } + } + """ + ) + }, + { + "E-05", + Source( + """ + using System; + + internal sealed class Probe + { + private readonly string m_name; + + internal Probe(string name) + { + ArgumentNullException.ThrowIfNull(name); + m_name = name; + } + + internal string Name(string? other) => other ?? throw new ArgumentNullException(nameof(other)); + + internal string Require(string? value) + { + if (value is null) throw new InvalidOperationException("The value is missing."); + return m_name + value; + } + } + """ + ) + }, + { + "P-03", + Source( + """ + using System; + using System.Threading; + using System.Threading.Tasks; + + internal sealed class Probe + { + internal Task RunAsync(CancellationToken cancellationToken) + { + Func step = token => Task.Delay(1, token); + return step(cancellationToken); + } + + internal Task WaitAsync( + int count, + CancellationToken cancellationToken, + string? label = null + ) => Task.Delay(count, cancellationToken); + + internal Task WaitAllAsync( + CancellationToken cancellationToken, + params int[] counts + ) => Task.Delay(counts.Length, cancellationToken); + } + """ + ) + }, + { + "D-06", + Source( + """ + // A line comment that mentions #region and /* text */ is not a directive. + internal sealed class Probe + { + #if DEBUG + internal string text => "#nullable /* kept */"; + #endif + } + """ + ) + }, + { + "E-09", + Source( + """ + using System.Collections.Generic; + using System.Globalization; + + internal sealed class Probe + { + internal string Join(IEnumerable parts) => string.Concat(parts); + + internal string Format( + string template, + int value + ) => string.Format(CultureInfo.InvariantCulture, template, value); + + internal string Name(int value) => $"item-{value}"; + } + """ + ) + }, + { + "M-02", + Source( + """ + using System; + + internal sealed class Probe + { + private int m_count; + + internal Probe() + { + m_count = 1; + } + + internal int count + { + get => m_count; + set => m_count = value; + } + + internal int Next() => m_count + 1; + + internal void Reset() + { + // The first frame starts from one. + m_count = 1; + } + + internal void Clear() + { + if (m_count == 0) throw new InvalidOperationException("The probe is empty."); + m_count = 0; + } + } + """ + ) + } + }; + + private static string CreateRoot() + { + string root = Path.Combine(Path.GetTempPath(), "InnoStyleCommandTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(root, "src")); + return root; + } + + // Names the probe file after its first type, as F-02 requires. + private static string FirstTypeName(string text) + { + Match match = Regex.Match(text, @"\b(?:class|struct|interface|enum|record)\s+(?!struct\b|class\b)(\w+)"); + return match.Success ? match.Groups[1].Value : "Probe"; + } + + private static string Source(string text) => text + "\n"; +} diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs index 490d976de..00444699f 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs @@ -1,16 +1,16 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Reflection; using System.Reflection.Emit; -using System.Linq; -using System.Collections.Generic; -using System.Text.Json; using System.Security; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -38,26 +38,45 @@ await File.WriteAllTextAsync(project, $""" """); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var arguments = new List - { - "msbuild", project, "-nologo", "-nr:false", "-t:GetAssemblyAttributes", - "-getProperty:ArtifactsPath", "-getItem:AssemblyAttribute", + List arguments = + [ + "msbuild", + project, + "-nologo", + "-nr:false", + "-t:GetAssemblyAttributes", + "-getProperty:ArtifactsPath", + "-getItem:AssemblyAttribute", "-p:UseArtifactsOutput=" + useArtifacts.ToString().ToLowerInvariant() - }; + ]; if (explicitOwner) + { arguments.Add("-p:ArtifactsPath=" + Path.Combine(root, "independent")); + } using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - string output = await ToolchainEnvironment.CaptureOutputAsync(dotnet, arguments, - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + dotnet, + arguments, + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); using JsonDocument result = JsonDocument.Parse(output); string? artifacts = result.RootElement.GetProperty("Properties").GetProperty("ArtifactsPath").GetString(); - JsonElement[] declarations = result.RootElement.GetProperty("Items").GetProperty("AssemblyAttribute").EnumerateArray() - .Where(item => item.TryGetProperty("_Parameter1", out var key) && key.GetString() == "Inno.Testing.ArtifactsPath").ToArray(); + JsonElement[] declarations = result.RootElement.GetProperty("Items") + .GetProperty("AssemblyAttribute") + .EnumerateArray() + .Where(item => item.TryGetProperty("_Parameter1", out JsonElement key) && key.GetString() == "Inno.Testing.ArtifactsPath") + .ToArray(); if (useArtifacts) { Assert.False(string.IsNullOrWhiteSpace(artifacts)); - Assert.Equal(Path.GetFullPath(artifacts!), Path.TrimEndingDirectorySeparator( - Assert.Single(declarations).GetProperty("_Parameter2").GetString()!)); + Assert.Equal( + Path.GetFullPath(artifacts!), + Path.TrimEndingDirectorySeparator( + Assert.Single(declarations).GetProperty("_Parameter2").GetString()! + ) + ); } else { @@ -94,10 +113,14 @@ public void RelativeEmptyOrDuplicateArtifactsDeclarationsAreRejected() private static Assembly CreateAssembly(params string[] owners) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly( - new AssemblyName("RepositoryInputs." + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.RunAndCollect); + new AssemblyName("RepositoryInputs." + Guid.NewGuid().ToString("N")), + AssemblyBuilderAccess.RunAndCollect + ); ConstructorInfo constructor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; foreach (string owner in owners) + { assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, ["Inno.Testing.ArtifactsPath", owner])); + } return assembly; } } diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs index 373ea4b1d..6d2122daf 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs @@ -1,24 +1,31 @@ using System; using System.IO; using System.Linq; +using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; +using System.Xml; +using Markdig; using Xunit; +using Inno.Core.IO; namespace Inno.Tooling.Documentation.Tests; public sealed class DocumentationApiSynchronizationTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoApiSynchronization", Guid.NewGuid().ToString("N")); private const string C_TYPE = "T:Inno.Probe.Value"; private const string C_MEMBER = "P:Inno.Probe.Value.count"; - public DocumentationApiSynchronizationTests() => Bind(); + private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoApiSynchronization", Guid.NewGuid().ToString("N")); + + public DocumentationApiSynchronizationTests() + { + Bind(); + } public void Dispose() => Directory.Delete(m_root, recursive: true); @@ -26,39 +33,53 @@ public sealed class DocumentationApiSynchronizationTests : IDisposable public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChanges() { const string C_PAGE = "content/en/architecture/projects/probe.md"; - Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", - entries = new[] { new { path = C_PAGE, uid = "project.probe", project = "Inno.Probe" } } })); - Write(C_PAGE, "---\nuid: project.probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners: [Inno.Probe]\nsource: xml\n---\n"); + Write( + "reference/projects/content.json", + JsonSerializer.Serialize(new + { + schema = "inno-project-guides/1", + entries = new[] { new { path = C_PAGE, uid = "project.probe", project = "Inno.Probe" } } + }) + ); + Write( + C_PAGE, + "---\nuid: project.probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners: [Inno.Probe]\nsource: xml\n---\n" + ); Bind(description: "The value\ncontract."); - await Sync(); + await SyncAsync(); string path = Path.Combine(m_root, C_PAGE); Assert.Contains("The value contract.", File.ReadAllText(path)); string first = File.ReadAllText(path); - await Sync(); + await SyncAsync(); Assert.Equal(first, File.ReadAllText(path)); string manual = first.Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nIndependent lifetime guidance.\n"; + + "\nIndependent lifetime guidance.\n"; File.WriteAllText(path, manual); - await Sync(); + await SyncAsync(); Assert.Equal(manual, File.ReadAllText(path)); string cache = Path.Combine(m_root, "artifacts/project-query"); - var initial = await DocumentationStore.IndexAsync(m_root, m_root, cache); - using (var initialSnapshot = await DocumentationStore.OpenAsync(cache, initial.snapshot)) - Assert.Contains("[!AUTHORED]", (await initialSnapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe").markdown); + DocumentationResult initial = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using (DocumentationSnapshot initialSnapshot = await DocumentationStore.OpenAsync(cache, initial.snapshot)) + { + Assert.Contains( + "[!AUTHORED]", + (await initialSnapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe").markdown + ); + } string original = File.ReadAllText(path); Bind(description: "The value\r\ncontract."); - await Sync(); + await SyncAsync(); Assert.Equal(original, File.ReadAllText(path)); Bind(description: "Changed XML contract."); - await Sync(); + await SyncAsync(); Assert.Equal(Body(manual), Body(File.ReadAllText(path))); Assert.Contains("outdatedFor:", File.ReadAllText(path)); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); File.AppendAllText(path, "\nUpdated explanation.\n"); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); - var indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); - using var snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - var page = (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe"); + DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); + DocumentationPageInfo page = (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe"); Assert.Contains("[!AUTHORED]", page.markdown); Assert.Contains("Independent lifetime guidance.", page.markdown); Assert.Contains("src/Inno.Probe.csproj", page.markdown); @@ -68,33 +89,133 @@ public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChan public async Task ProjectGuideRegistryCannotClaimUnrelatedManualPages() { Write("content/en/manual/keep.md", "Preserve this unrelated guide."); - Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", - entries = new[] { new { path = "content/en/manual/keep.md", uid = "manual.keep", project = "Inno.Probe" } } })); - await Assert.ThrowsAsync(() => Sync(CancellationToken.None)); + Write( + "reference/projects/content.json", + JsonSerializer.Serialize(new + { + schema = "inno-project-guides/1", + entries = new[] { new { path = "content/en/manual/keep.md", uid = "manual.keep", project = "Inno.Probe" } } + }) + ); + await Assert.ThrowsAsync(() => SyncAsync(CancellationToken.None)); Assert.Equal("Preserve this unrelated guide.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/keep.md"))); } + [Fact] + public async Task NewProjectsReceiveSynchronizedGuidesBesideTheirOwnerKind() + { + const string C_AUTHORED = "content/en/contributing/testing/projects/authored.md"; + const string C_AUTHORED_TEXT = "---\nuid: project.authored\ntitle: Authored\nkind: project\nowners:\n - Inno.Authored.Tests\n---\n# Authored\n"; + WriteGuideRegistry(); + Write(C_AUTHORED, C_AUTHORED_TEXT); + SetProjects( + ("Inno.Probe", "src/Inno.Probe.csproj"), + ("Inno.Probe.Tests", "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj"), + ("Inno.Adapter.Probe", "backends/Probe/Inno.Adapter.Probe.csproj"), + ("Inno.Platform.Probe", "platforms/Probe/Inno.Platform.Probe.csproj"), + ("Inno.Authored.Tests", "tests/Inno.Authored.Tests/Inno.Authored.Tests.csproj") + ); + await SyncAsync(); + string source = File.ReadAllText(Path.Combine(m_root, "content/en/architecture/projects/inno-probe.md")); + Assert.Contains( + "uid: project.inno-probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners:\n- Inno.Probe\n", + source + ); + Assert.Contains("source: xml", source); + Assert.Contains("The value contract.", source); + Assert.Contains( + "source: xml", + File.ReadAllText(Path.Combine(m_root, "content/en/contributing/testing/projects/inno-probe-tests.md")) + ); + Assert.Contains("source: xml", File.ReadAllText(Path.Combine(m_root, "content/en/backends/projects/inno-adapter-probe.md"))); + string[] expected = ["content/en/architecture/projects/inno-probe.md", "content/en/backends/projects/inno-adapter-probe.md", + "content/en/contributing/testing/projects/inno-probe-tests.md"]; + Assert.Equal(expected, GuideRegistry()); + Assert.Equal(C_AUTHORED_TEXT, File.ReadAllText(Path.Combine(m_root, C_AUTHORED))); + Assert.Single( + Directory.GetFiles(Path.Combine(m_root, "content/en/contributing/testing/projects")), + path => path.EndsWith("inno-probe-tests.md", StringComparison.Ordinal) + ); + Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); + string cache = Path.Combine(m_root, "artifacts/project-query"); + DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); + Assert.Contains( + "[!SYNCED]", + (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.inno-probe-tests").markdown + ); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RemovedProjectsDeleteSynchronizedGuidesAndPreserveAuthoredGuides(bool manual) + { + const string C_PAGE = "content/en/architecture/projects/inno-retired.md"; + WriteGuideRegistry(); + SetProjects(("Inno.Probe", "src/Inno.Probe.csproj"), ("Inno.Retired", "tools/Inno.Retired/Inno.Retired.csproj")); + await SyncAsync(); + string path = Path.Combine(m_root, C_PAGE); + if (manual) + { + File.WriteAllText( + path, + File.ReadAllText(path).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + "\nRetained guidance.\n" + ); + } + SetProjects(("Inno.Probe", "src/Inno.Probe.csproj")); + await SyncAsync(); + Assert.Equal(manual, File.Exists(path)); + Assert.Equal(manual, GuideRegistry().Contains(C_PAGE)); + if (manual) Assert.Contains("Retained guidance.", File.ReadAllText(path)); + Assert.Contains("content/en/architecture/projects/inno-probe.md", GuideRegistry()); + Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); + } + + [Fact] + public async Task NewProjectGuidesCannotOverwriteUnregisteredFiles() + { + const string C_PAGE = "content/en/architecture/projects/inno-probe.md"; + WriteGuideRegistry(); + Write(C_PAGE, "Preserve this unregistered page."); + await Assert.ThrowsAsync(() => SyncAsync(CancellationToken.None)); + Assert.Equal("Preserve this unregistered page.", File.ReadAllText(Path.Combine(m_root, C_PAGE))); + Assert.Empty(GuideRegistry()); + } + + [Fact] + public async Task CheckoutsWithoutAGuideRegistryDoNotManageProjectGuides() + { + await SyncAsync(); + Assert.False(File.Exists(Path.Combine(m_root, "reference/projects/content.json"))); + Assert.False(Directory.Exists(Path.Combine(m_root, "content/en/architecture/projects"))); + } + [Theory] [InlineData("T:Inno.Probe.Value`1", "public class Inno.Probe.Value", "Value")] [InlineData("T:Inno.Probe.Value`2", "public class Inno.Probe.Value", "Value")] [InlineData("T:Inno.Probe.Outer`1.Value`1", "public class Inno.Probe.Outer.Value", "Value")] [InlineData("T:Inno.Probe.Outer`1.Value", "public class Inno.Probe.Outer.Value", "Value")] [InlineData("T:Inno.Probe.class`1", "public class Inno.Probe.@class", "@class")] - [InlineData("T:Inno.Probe.Factory`2", "public delegate TResult Inno.Probe.Factory(TValue value)", "Factory")] + [InlineData( + "T:Inno.Probe.Factory`2", + "public delegate TResult Inno.Probe.Factory(TValue value)", + "Factory" + )] public async Task GenericTitlesUseDeclaredNamesAndRenderAsText( string id, string signature, string expected ) { SetTypes((id, signature)); - await Sync(); + await SyncAsync(); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api")); Assert.Equal(expected, page.title); - Assert.Contains("

" + System.Net.WebUtility.HtmlEncode(expected) + "

", Markdig.Markdown.ToHtml(page.markdown)); - Assert.Contains(expected, (await snapshot.QueryAsync(new("symbol", id, "Inno.Probe"))).hits.Single().text); + Assert.Contains("

" + WebUtility.HtmlEncode(expected) + "

", Markdown.ToHtml(page.markdown)); + Assert.Contains(expected, (await snapshot.QueryAsync(new DocumentationRequest("symbol", id, "Inno.Probe"))).hits.Single().text); } [Fact] @@ -103,21 +224,25 @@ public async Task GenericParameterRenamesPreserveAddressesAndManualProseWithRead const string C_ONE = "T:Inno.Probe.Value`1"; const string C_TWO = "T:Inno.Probe.Value`2"; const string C_OTHER = "T:Other.Value`1"; - SetTypes((C_TYPE, "public class Inno.Probe.Value"), + SetTypes( + (C_TYPE, "public class Inno.Probe.Value"), (C_ONE, "public class Inno.Probe.Value"), (C_TWO, "public class Inno.Probe.Value"), - (C_OTHER, "public class Other.Value")); - await Sync(); + (C_OTHER, "public class Other.Value") + ); + await SyncAsync(); string[] paths = new[] { C_TYPE, C_ONE, C_TWO, C_OTHER }.Select(Fragment).ToArray(); Assert.Equal(4, paths.Distinct().Count()); string manual = File.ReadAllText(paths[2]).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nKeep the target alive while the operation runs.\n"; + + "\nKeep the target alive while the operation runs.\n"; File.WriteAllText(paths[2], manual); - SetTypes((C_TYPE, "public class Inno.Probe.Value"), + SetTypes( + (C_TYPE, "public class Inno.Probe.Value"), (C_ONE, "public class Inno.Probe.Value"), (C_TWO, "public class Inno.Probe.Value"), - (C_OTHER, "public class Other.Value")); - await Sync(); + (C_OTHER, "public class Other.Value") + ); + await SyncAsync(); Assert.Equal(paths, new[] { C_TYPE, C_ONE, C_TWO, C_OTHER }.Select(Fragment)); Assert.Equal(Body(manual), Body(File.ReadAllText(paths[2]))); Assert.Contains("outdatedFor:", File.ReadAllText(paths[2])); @@ -141,13 +266,14 @@ public async Task GenericParameterRenamesPreserveAddressesAndManualProseWithRead public async Task SynchronizationIsDeterministicAndNeverTouchesManualGuides() { Write("content/en/manual/task.md", "A hand-written guide without source metadata."); - await Sync(); + await SyncAsync(); string[] paths = Directory.GetFiles(Path.Combine(m_root, "content/en/api"), "*.md", SearchOption.AllDirectories) - .Where(path => File.ReadAllText(path).Contains("symbol:", StringComparison.Ordinal)).ToArray(); + .Where(path => File.ReadAllText(path).Contains("symbol:", StringComparison.Ordinal)) + .ToArray(); Assert.Equal(2, paths.Length); Assert.All(paths, path => Assert.Contains("source: xml", File.ReadAllText(path))); DateTime[] times = paths.Select(File.GetLastWriteTimeUtc).ToArray(); - await Sync(); + await SyncAsync(); Assert.Equal(times, paths.Select(File.GetLastWriteTimeUtc)); Assert.Equal("A hand-written guide without source metadata.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/task.md"))); } @@ -155,13 +281,13 @@ public async Task SynchronizationIsDeterministicAndNeverTouchesManualGuides() [Fact] public async Task ManualMemberSurvivesXmlChangesWhileItsSiblingUpdates() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nUse this count after the owner has published the snapshot.\n"; + + "\nUse this count after the owner has published the snapshot.\n"; File.WriteAllText(member, manual); Bind(description: "Updated source documentation."); - await Sync(); + await SyncAsync(); Assert.Equal(Body(manual), Body(File.ReadAllText(member))); Assert.Contains("outdatedFor:", File.ReadAllText(member)); Assert.True(string.IsNullOrWhiteSpace(Body(File.ReadAllText(Fragment(C_TYPE))))); @@ -171,8 +297,10 @@ public async Task ManualMemberSurvivesXmlChangesWhileItsSiblingUpdates() DocumentationPageInfo[] pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); Assert.All(pages, page => Assert.Contains("Updated source documentation.", page.markdown)); DocumentationPageInfo memberPage = Assert.Single(pages.Where(page => page.symbols.ContainsKey(C_MEMBER))); - Assert.True(memberPage.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) - < memberPage.markdown.IndexOf("Updated source documentation.", StringComparison.Ordinal)); + Assert.True( + memberPage.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) + < memberPage.markdown.IndexOf("Updated source documentation.", StringComparison.Ordinal) + ); Assert.Contains("Use this count after the owner has published the snapshot.", memberPage.markdown); Assert.Contains("Updated source documentation.", File.ReadAllText(Path.Combine(m_root, "content/en/api/engine/probe/index.md"))); Assert.Contains("| Updated source documentation. |", Assert.Single(pages.Where(page => page.symbols.ContainsKey(C_TYPE))).markdown); @@ -181,28 +309,34 @@ public async Task ManualMemberSurvivesXmlChangesWhileItsSiblingUpdates() [Fact] public async Task EditingADescriptionClearsAutomaticStalenessUntilTheNextSourceChange() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada", StringComparison.Ordinal)); Bind(description: "A changed\ncontract."); - await Sync(); + await SyncAsync(); string path = Path.Combine(m_root, "artifacts/query"); - async Task AssertStatus(string status) + async Task AssertStatusAsync(string status) { - var index = await DocumentationStore.IndexAsync(m_root, m_root, path); - using var snapshot = await DocumentationStore.OpenAsync(path, index.snapshot); - Assert.Contains("> [!" + status + "]", (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits.Single().text); + DocumentationResult index = await DocumentationStore.IndexAsync(m_root, m_root, path); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(path, index.snapshot); + Assert.Contains( + "> [!" + status + "]", + (await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe"))).hits.Single().text + ); } - await AssertStatus("OUTDATED"); - File.WriteAllText(member, File.ReadAllText(member).Replace("description: null", "description:\n- An updated explanation.", StringComparison.Ordinal)); + await AssertStatusAsync("OUTDATED"); + File.WriteAllText( + member, + File.ReadAllText(member).Replace("description: null", "description:\n- An updated explanation.", StringComparison.Ordinal) + ); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); - await AssertStatus("AUTHORED"); + await AssertStatusAsync("AUTHORED"); Bind(description: "A changed\r\ncontract."); - await Sync(); - await AssertStatus("AUTHORED"); + await SyncAsync(); + await AssertStatusAsync("AUTHORED"); Bind(description: "A newer contract."); - await Sync(); - await AssertStatus("OUTDATED"); + await SyncAsync(); + await AssertStatusAsync("OUTDATED"); } [Theory] @@ -210,37 +344,37 @@ async Task AssertStatus(string status) [InlineData("[true]")] public async Task InvalidOutdatedMetadataCannotBeOverwritten(string value) { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); string invalid = File.ReadAllText(member).Replace("outdated: false", "outdated: " + value, StringComparison.Ordinal); File.WriteAllText(member, invalid); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal(invalid, File.ReadAllText(member)); } [Fact] public async Task LegacyStaleApiRetainsOutdatedStatusDuringMigration() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); - string legacy = File.ReadAllText(member).Replace("sourceFingerprint:", "reviewed:", StringComparison.Ordinal) - .Replace("source: xml", "source: Ada", StringComparison.Ordinal).Replace("outdated: false", "outdated: true", StringComparison.Ordinal); + string legacy = File.ReadAllText(member) + .Replace("sourceFingerprint:", "reviewed:", StringComparison.Ordinal) + .Replace("source: xml", "source: Ada", StringComparison.Ordinal) + .Replace("outdated: false", "outdated: true", StringComparison.Ordinal); File.WriteAllText(member, legacy); - await Sync(); + await SyncAsync(); Assert.Contains("outdatedFor:", File.ReadAllText(member)); Assert.DoesNotContain("reviewed:", File.ReadAllText(member)); } - private static string Body(string text) => text[(text.IndexOf("\n---", 4, StringComparison.Ordinal) + 4)..]; - [Fact] public async Task MissingSourceRemainsGeneratorOwned() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); - File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml\n", "", StringComparison.Ordinal)); + File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml\n", string.Empty, StringComparison.Ordinal)); Bind(description: "A fresh description."); - await Sync(); + await SyncAsync(); Assert.Contains("source: xml", File.ReadAllText(member)); Assert.True(string.IsNullOrWhiteSpace(Body(File.ReadAllText(member)))); Assert.Contains("A fresh description.", File.ReadAllText(Path.Combine(m_root, "content/en/api/engine/probe/index.md"))); @@ -251,12 +385,15 @@ public async Task MissingSourceRemainsGeneratorOwned() [InlineData(true)] public async Task RemovalDeletesXmlAndPreservesManualProse(bool manual) { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); - if (manual) File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal)); + if (manual) + { + File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal)); + } string before = File.ReadAllText(member); Bind(member: false); - await Sync(); + await SyncAsync(); Assert.Equal(manual, File.Exists(member)); if (manual) Assert.Equal(before, File.ReadAllText(member)); } @@ -264,36 +401,36 @@ public async Task RemovalDeletesXmlAndPreservesManualProse(bool manual) [Fact] public async Task BlankAuthorCannotOverwriteAnyContent() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); string invalid = File.ReadAllText(member).Replace("source: xml", "source: \"\"", StringComparison.Ordinal); File.WriteAllText(member, invalid); Bind(description: "New XML."); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal(invalid, File.ReadAllText(member)); } [Fact] public async Task CorruptCaptureAndPrecancellationCannotChangeContent() { - await Sync(); + await SyncAsync(); string type = File.ReadAllText(Fragment(C_TYPE)); - await Assert.ThrowsAnyAsync(() => Sync(new CancellationToken(true))); + await Assert.ThrowsAnyAsync(() => SyncAsync(new CancellationToken(true))); File.AppendAllText(Path.Combine(m_root, "reference/api/probe.json"), " "); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal(type, File.ReadAllText(Fragment(C_TYPE))); } [Fact] public async Task RegisteredPathCannotEscapeApiOwnership() { - await Sync(); + await SyncAsync(); string path = Path.Combine(m_root, "reference/api/content.json"); JsonNode registry = JsonNode.Parse(File.ReadAllText(path))!; registry["entries"]![0]!["path"] = "content/en/manual/task.md"; Write("content/en/manual/task.md", "Preserve this independent guide."); File.WriteAllText(path, registry.ToJsonString()); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal("Preserve this independent guide.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/task.md"))); } @@ -301,38 +438,38 @@ public async Task RegisteredPathCannotEscapeApiOwnership() public async Task UnregisteredFilesAreNotSilentlyClaimed() { Write("content/en/api/engine/probe/value/index.md", "Unregistered authored prose."); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal("Unregistered authored prose.", File.ReadAllText(Path.Combine(m_root, "content/en/api/engine/probe/value/index.md"))); } [Fact] public async Task AnApiPrefixCannotAuthorizeTraversalIntoManualContent() { - await Sync(); + await SyncAsync(); string path = Path.Combine(m_root, "reference/api/content.json"); JsonNode registry = JsonNode.Parse(File.ReadAllText(path))!; registry["entries"]![0]!["path"] = "content/en/api/engine/../../manual/task.md"; Write("content/en/manual/task.md", "Preserve the independent guide."); File.WriteAllText(path, registry.ToJsonString()); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal("Preserve the independent guide.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/task.md"))); } [Fact] public async Task EditorialWarningsDoNotFailButStaleGeneratedContentDoes() { - await Sync(); + await SyncAsync(); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); Bind(description: "Changed XML must be synchronized."); Assert.Equal(1, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); - await Sync(); + await SyncAsync(); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); } [Fact] public async Task MissingProjectCaptureCannotBePresentedAsACompleteApiSet() { - await Sync(); + await SyncAsync(); string path = Path.Combine(m_root, "reference/projects/catalog.json"); JsonArray inventory = JsonNode.Parse(File.ReadAllText(path))!.AsArray(); inventory.Add(new JsonObject { ["name"] = "Inno.Missing", ["path"] = "src/Inno.Missing.csproj", ["isTest"] = false }); @@ -341,7 +478,7 @@ public async Task MissingProjectCaptureCannotBePresentedAsACompleteApiSet() JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/engine.lock.json")))!; binding["projectManifestIdentity"] = Hash(text); Write("reference/engine.lock.json", binding.ToJsonString()); - InvalidDataException failure = await Assert.ThrowsAsync(Sync); + InvalidDataException failure = await Assert.ThrowsAsync(SyncAsync); Assert.Contains("Inno.Missing", failure.Message); } @@ -357,7 +494,10 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica { JsonNode projected = host.DeepClone(); projected["model"] = surface; - foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) symbol!["scriptingScope"] = scope; + foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) + { + symbol!["scriptingScope"] = scope; + } string text = projected.ToJsonString(); string file = "reference/api/" + surface + ".json"; Write(file, text); @@ -372,12 +512,14 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica Write("reference/projects/catalog.json", inventory.ToJsonString()); binding["projectManifestIdentity"] = Hash(inventory.ToJsonString()); Write("reference/engine.lock.json", binding.ToJsonString()); - await Sync(); + await SyncAsync(); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); - DocumentationPageInfo script = Assert.Single(catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo script = Assert.Single( + catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Contains("scripting/" + scope.ToLowerInvariant(), script.path); string scopeDirectory = "content/en/api/scripting/" + scope.ToLowerInvariant(); DocumentationPageInfo scopePage = catalog.pages.Single(page => page.path == scopeDirectory + "/index.md"); @@ -385,33 +527,52 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica DocumentationPageInfo projectPage = catalog.pages.Single(page => page.path == scopeDirectory + "/_projects/probe/index.md"); Assert.Contains("## Types", projectPage.markdown); Assert.Contains("| [Value]", projectPage.markdown); - DocumentationPageInfo typePage = Assert.Single(catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo typePage = Assert.Single( + catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_TYPE)) + ); string typeLink = Path.GetRelativePath(Path.GetDirectoryName(projectPage.path)!, typePage.path).Replace('\\', '/'); Assert.Contains("](" + typeLink + ")", projectPage.markdown); Assert.DoesNotContain("/_projects/", script.path); foreach (string surface in new[] { "runtime-script", "editor-script" }) { - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", surface, scope: scope))).hits); + DocumentationHit hit = Assert.Single( + (await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe", surface, scope: scope))).hits + ); Assert.Equal(script.id, hit.pageId); Assert.Equal(scope, hit.scope); Assert.Equal(new[] { "editor-script", "runtime-script" }, hit.surfaces); } - Assert.Empty((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", scope: scope == "Editor" ? "Runtime" : "Editor"))).hits); + Assert.Empty( + (await snapshot.QueryAsync( + new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe", scope: scope == "Editor" ? "Runtime" : "Editor") + )).hits + ); } [Fact] public async Task WebsiteCatalogAndSymbolReadsShareComposedDeclarationsAndManualProse() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nRead the count only after publication.\n"; + + "\nRead the count only after publication.\n"; File.WriteAllText(member, manual); Bind(description: "Updated XML.", countType: "long"); - await Sync(); - Write("content/en/manual/ownership.md", "---\nuid: manual.ownership\ntitle: Ownership and retirement\nkind: explanation\n---\n\n# Ownership and retirement\n\n## Release\n\nKeep the owner alive until all borrows end.\n"); + await SyncAsync(); + Write( + "content/en/manual/ownership.md", + "---\nuid: manual.ownership\ntitle: Ownership and retirement\nkind: explanation\n---\n\n# Ownership and retirement\n\n## Release\n\nKeep the owner alive until all borrows end.\n" + ); string typePath = Fragment(C_TYPE); - File.WriteAllText(typePath, File.ReadAllText(typePath).Replace("contracts: []", "contracts: [manual.ownership#release]\nexampleMode: host\nexampleProjects: [Inno.Probe]", StringComparison.Ordinal)); + File.WriteAllText( + typePath, + File.ReadAllText(typePath) + .Replace( + "contracts: []", + "contracts: [manual.ownership#release]\nexampleMode: host\nexampleProjects: [Inno.Probe]", + StringComparison.Ordinal + ) + ); string cache = Path.Combine(m_root, "artifacts", "query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); @@ -427,16 +588,22 @@ public async Task WebsiteCatalogAndSymbolReadsShareComposedDeclarationsAndManual Assert.DoesNotContain("Edit this explanation", page.markdown); Assert.Contains("reference/api/content.json", catalog.sourceFiles.Keys); Assert.Contains(Path.GetRelativePath(m_root, member).Replace('\\', '/'), catalog.sourceFiles.Keys); - DocumentationResult result = await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", "source-clr")); + DocumentationResult result = await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe", "source-clr")); DocumentationHit hit = Assert.Single(result.hits); Assert.Equal("Ada Example", hit.contentSourceKind); Assert.Contains("public long Inno.Probe.Value.count", hit.text); Assert.Contains("Read the count only after publication.", hit.text); Assert.Equal(Body(manual), Body(File.ReadAllText(member))); Assert.Contains("outdatedFor:", File.ReadAllText(member)); - Assert.Contains(hit.text, Assert.Single((await snapshot.QueryAsync(new("read", hit.contentSource))).hits).text); + Assert.Contains( + hit.text, + Assert.Single((await snapshot.QueryAsync(new DocumentationRequest("read", hit.contentSource))).hits).text + ); Directory.Move(Path.Combine(m_root, "content"), Path.Combine(m_root, "unavailable-content")); - Assert.Equal(hit.text, Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits).text); + Assert.Equal( + hit.text, + Assert.Single((await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe"))).hits).text + ); } [Fact] @@ -456,14 +623,19 @@ public async Task AllTargetDeclarationsRemainFactsWhileAuthoredExamplesRemainExe capture["sha256"] = Hash(text); binding["apiManifests"]!.AsArray().Add(capture); Write("reference/engine.lock.json", binding.ToJsonString()); - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); - File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\n```csharp\nvar count = value.count;\n```\n"); + File.WriteAllText( + member, + File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + + "\n```csharp\nvar count = value.count;\n```\n" + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api" && page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api" && page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Equal(2, page.codeBlocks.Count(block => block.declarationSymbols.Count != 0)); Assert.Equal("var count = value.count;", Assert.Single(page.codeBlocks.Where(block => block.declarationSymbols.Count == 0)).text); Assert.Contains(C_VARIANT, page.symbols[C_MEMBER].code); @@ -473,18 +645,33 @@ public async Task AllTargetDeclarationsRemainFactsWhileAuthoredExamplesRemainExe [InlineData("xml", true)] [InlineData("Ada Example", false)] [InlineData("", true)] - public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage(string source, bool notice) - { - await Sync(); + public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage( + string source, + bool notice + ) { + await SyncAsync(); string member = Fragment(C_MEMBER); string original = File.ReadAllText(member); - File.WriteAllText(member, original.Replace("source: xml", source.Length == 0 ? "" : "source: " + source, StringComparison.Ordinal)); + File.WriteAllText( + member, + original.Replace("source: xml", source.Length == 0 ? string.Empty : "source: " + source, StringComparison.Ordinal) + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Equal(notice, page.markdown.Contains("> [!SYNCED]", StringComparison.Ordinal)); - if (notice) Assert.True(page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("## Required contracts", StringComparison.Ordinal)); + if (notice) + { + Assert.True( + page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf( + "## Required contracts", + StringComparison.Ordinal + ) + ); + } Assert.DoesNotContain("Available in:", page.markdown); Assert.DoesNotContain("XML-synced", page.markdown); Assert.DoesNotContain("Edit this explanation", page.markdown); @@ -492,8 +679,6 @@ public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage(string Assert.EndsWith(")", page.markdown.TrimEnd()); } - private Task Sync() => Sync(CancellationToken.None); - [Fact] public async Task ElementsAreIndependentPagesWithNestedContainmentAndOverloadLinks() { @@ -507,11 +692,11 @@ public async Task ElementsAreIndependentPagesWithNestedContainmentAndOverloadLin Add("M:Inno.Probe.Value.Read(System.Int32)", "Method", "public void Inno.Probe.Value.Read(int value)", C_TYPE); Add("M:Inno.Probe.Value.Read(System.String)", "Method", "public void Inno.Probe.Value.Read(string value)", C_TYPE); SaveFacts(facts); - await Sync(); + await SyncAsync(); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - var pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); + DocumentationPageInfo[] pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); Assert.Equal(7, pages.Length); Assert.All(pages, page => Assert.Single(page.symbols)); DocumentationPageInfo outer = pages.Single(page => page.symbols.ContainsKey(C_TYPE)); @@ -528,11 +713,18 @@ public async Task ElementsAreIndependentPagesWithNestedContainmentAndOverloadLin Assert.Contains(pages.Single(page => page.symbols.ContainsKey(C_DEEP)).id, field.contracts); Assert.DoesNotContain("_members", field.path); - void Add(string id, string kind, string signature, string parent) - { + void Add( + string id, + string kind, + string signature, + string parent + ) { JsonNode symbol = symbols[0]!.DeepClone(); - symbol["id"] = id; symbol["kind"] = kind; symbol["signature"] = signature; - symbol["signatureHash"] = Hash(signature); symbol["containingType"] = parent; + symbol["id"] = id; + symbol["kind"] = kind; + symbol["signature"] = signature; + symbol["signatureHash"] = Hash(signature); + symbol["containingType"] = parent; symbols.Add(symbol); } } @@ -540,22 +732,30 @@ void Add(string id, string kind, string signature, string parent) [Fact] public async Task MovingLegacyMembersRepairsIncomingAnchorsAndManualRelativeLinks() { - await Sync(); + await SyncAsync(); string current = Fragment(C_MEMBER); string legacy = Path.Combine(Path.GetDirectoryName(current)!, "_members/count.md"); Directory.CreateDirectory(Path.GetDirectoryName(legacy)!); string text = File.ReadAllText(current).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nKeep the original explanation. [Owner](../index.md).\n"; + + "\nKeep the original explanation. [Owner](../index.md).\n"; File.WriteAllText(legacy, text); File.Delete(current); string registryPath = Path.Combine(m_root, "reference/api/content.json"); JsonNode registry = JsonNode.Parse(File.ReadAllText(registryPath))!; - registry["entries"]!.AsArray().Single(entry => entry!["symbol"]!.GetValue().EndsWith(C_MEMBER, StringComparison.Ordinal))!["path"] - = Path.GetRelativePath(m_root, legacy).Replace('\\', '/'); + registry["entries"]! + .AsArray() + .Single( + entry => entry!["symbol"]!.GetValue().EndsWith(C_MEMBER, StringComparison.Ordinal) + )!["path"] = Path.GetRelativePath(m_root, legacy).Replace('\\', '/'); File.WriteAllText(registryPath, registry.ToJsonString()); - Write("content/en/manual/count.md", "---\nuid: manual.count\ntitle: Count\nkind: how-to\n---\n\n# Count\n\n" - + "[Old member](../api/engine/probe/value/_members/count.md) and [exact member](../api/engine/probe/value/index.md#api-" + Hash(C_MEMBER)[..16] + ").\n"); - await Sync(); + Write( + "content/en/manual/count.md", + "---\nuid: manual.count\ntitle: Count\nkind: how-to\n---\n\n# Count\n\n" + + "[Old member](../api/engine/probe/value/_members/count.md) and [exact member](../api/engine/probe/value/index.md#api-" + + Hash(C_MEMBER)[..16] + + ").\n" + ); + await SyncAsync(); Assert.False(File.Exists(legacy)); Assert.Contains("Keep the original explanation. [Owner](index.md).", File.ReadAllText(current)); Assert.Contains("source: Ada Example", File.ReadAllText(current)); @@ -565,28 +765,24 @@ public async Task MovingLegacyMembersRepairsIncomingAnchorsAndManualRelativeLink string cache = Path.Combine(m_root, "artifacts/query"); await DocumentationStore.IndexAsync(m_root, m_root, cache); string after = File.ReadAllText(current); - await Sync(); + await SyncAsync(); Assert.Equal(after, File.ReadAllText(current)); } - private void SaveFacts(JsonNode facts) - { - string text = facts.ToJsonString(); - Write("reference/api/probe.json", text); - JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/engine.lock.json")))!; - binding["apiManifests"]![0]!["sha256"] = Hash(text); - Write("reference/engine.lock.json", binding.ToJsonString()); - } - [Fact] public async Task XmlRefreshPreservesAuthoredContractAndExampleAssociations() { - await Sync(); + await SyncAsync(); string type = Fragment(C_TYPE); - string text = File.ReadAllText(type).Replace("contracts: []", "contracts: [manual.ownership#release]\naliases: [persistent value]\nexampleMode: host\nexampleProjects: [Inno.Probe]", StringComparison.Ordinal); + string text = File.ReadAllText(type) + .Replace( + "contracts: []", + "contracts: [manual.ownership#release]\naliases: [persistent value]\nexampleMode: host\nexampleProjects: [Inno.Probe]", + StringComparison.Ordinal + ); File.WriteAllText(type, text); Bind(description: "Fresh XML still needs shared ownership guidance."); - await Sync(); + await SyncAsync(); string updated = File.ReadAllText(type); Assert.Contains("manual.ownership#release", updated); Assert.Contains("persistent value", updated); @@ -594,7 +790,7 @@ public async Task XmlRefreshPreservesAuthoredContractAndExampleAssociations() Assert.Contains("exampleProjects:", updated); Assert.DoesNotContain("Fresh XML still needs", updated); Assert.Contains("Fresh XML still needs", File.ReadAllText(Path.Combine(m_root, "content/en/api/engine/probe/index.md"))); - await Sync(); + await SyncAsync(); Assert.Equal(updated, File.ReadAllText(type)); } @@ -617,7 +813,7 @@ public async Task XmlRenderingPreservesFormulaListsAndExecutableExampleBoundarie JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/engine.lock.json")))!; binding["apiManifests"]![0]!["sha256"] = Hash(text); Write("reference/engine.lock.json", binding.ToJsonString()); - await Sync(); + await SyncAsync(); string prose = File.ReadAllText(Fragment(C_TYPE)); Assert.Contains("`left + (right - left) * amount`", prose); Assert.Contains("- Retain the owner.", prose); @@ -641,7 +837,10 @@ public async Task RuntimeAvailabilityInEditorRequiresTheSameActualProjection(boo ["Inno.ScriptApi.Runtime"] = new string(mismatch && surface == "editor-script" ? 'f' : 'e', 64), ["Inno.ScriptApi.Editor"] = new string('d', 64) }; - foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) symbol!["scriptingScope"] = "Runtime"; + foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) + { + symbol!["scriptingScope"] = "Runtime"; + } if (surface == "editor-script") projected["projects"]![0]!["symbols"] = new JsonArray(); string file = "reference/api/" + surface + ".json"; string text = projected.ToJsonString(); @@ -659,25 +858,27 @@ public async Task RuntimeAvailabilityInEditorRequiresTheSameActualProjection(boo Write("reference/engine.lock.json", binding.ToJsonString()); if (mismatch) { - InvalidDataException failure = await Assert.ThrowsAsync(Sync); + InvalidDataException failure = await Assert.ThrowsAsync(SyncAsync); Assert.Contains("different Runtime projection", failure.Message); return; } - await Sync(); + await SyncAsync(); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", "editor-script", scope: "Runtime"))).hits); + DocumentationHit hit = Assert.Single( + (await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe", "editor-script", scope: "Runtime"))).hits + ); Assert.Equal(new[] { "editor-script", "runtime-script" }, hit.surfaces); } [Fact] public async Task PackageImportPreservesManualProseAndSkipsRevisionOnlyChanges() { - await Sync(); + await SyncAsync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nRead this value only after publication.\n"; + + "\nRead this value only after publication.\n"; File.WriteAllText(member, manual); Bind(description: "Updated package XML."); string package = Path.Combine(m_root, "artifacts/api-package.json"); @@ -691,7 +892,9 @@ public async Task PackageImportPreservesManualProseAndSkipsRevisionOnlyChanges() JsonNode next = JsonNode.Parse(File.ReadAllText(package))!; next["revision"] = new string('c', 40); JsonNode bindingFile = next["files"]!.AsArray().Single(file => file!["path"]!.GetValue() == "reference/engine.lock.json")!; - string revised = bindingFile["text"]!.GetValue().Replace(new string('a', 40), new string('c', 40), StringComparison.Ordinal); + string revised = bindingFile["text"]! + .GetValue() + .Replace(new string('a', 40), new string('c', 40), StringComparison.Ordinal); bindingFile["text"] = revised; bindingFile["sha256"] = Hash(revised); next["toolingRevision"] = new string('c', 40); @@ -709,19 +912,24 @@ public async Task PackageImportPreservesManualProseAndSkipsRevisionOnlyChanges() [InlineData("mixed-revisions")] public async Task InvalidPackagesCannotModifyTheCheckout(string corruption) { - await Sync(); + await SyncAsync(); string package = Path.Combine(m_root, "artifacts/api-package.json"); await DocumentationCommand.ExecuteAsync(["api-package", "--docs-root", m_root, "--package", package]); JsonNode packet = JsonNode.Parse(File.ReadAllText(package))!; JsonArray files = packet["files"]!.AsArray(); if (corruption == "tampered") files[0]!["text"] = "{}"; - if (corruption == "extra-file") files.Add(new JsonObject { ["path"] = "content/en/manual/task.md", ["text"] = "replace", ["sha256"] = Hash("replace") }); + if (corruption == "extra-file") + { + files.Add(new JsonObject { ["path"] = "content/en/manual/task.md", ["text"] = "replace", ["sha256"] = Hash("replace") }); + } if (corruption == "escape") files[0]!["path"] = "reference/api/../../AGENTS.md"; if (corruption == "mixed-revisions") packet["revision"] = new string('d', 40); File.WriteAllText(package, packet.ToJsonString()); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); string before = File.ReadAllText(Fragment(C_TYPE)); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package])); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package]) + ); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(before, File.ReadAllText(Fragment(C_TYPE))); } @@ -729,17 +937,22 @@ public async Task InvalidPackagesCannotModifyTheCheckout(string corruption) [Fact] public async Task ImportWaitsForTheSharedWriterBeforeChangingFactsAndCancellationPreservesInputs() { - await Sync(); + await SyncAsync(); Bind(description: "New import contract."); string package = Path.Combine(m_root, "artifacts/api-package.json"); await DocumentationCommand.ExecuteAsync(["api-package", "--docs-root", m_root, "--package", package]); Bind(); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); byte[] facts = File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json")); - using (FileLease writer = await FileLease.AcquireAsync(Path.Combine(m_root, "artifacts/api-sync/writer.lock"), Timeout.InfiniteTimeSpan)) - { + using (FileLease writer = await FileLease.AcquireAsync( + Path.Combine(m_root, "artifacts/api-sync/writer.lock"), + Timeout.InfiniteTimeSpan + )) { using var cancellation = new CancellationTokenSource(); - Task import = DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package], cancellation.Token); + Task import = DocumentationCommand.ExecuteAsync( + ["api-import", "--docs-root", m_root, "--package", package], + cancellation.Token + ); Assert.False(import.IsCompleted); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(facts, File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json"))); @@ -754,7 +967,7 @@ public async Task ImportWaitsForTheSharedWriterBeforeChangingFactsAndCancellatio [Fact] public async Task ImportRestoresFactsWhenAuthoredContentRejectsSynchronization() { - await Sync(); + await SyncAsync(); Bind(description: "Changed package XML."); string package = Path.Combine(m_root, "artifacts/api-package.json"); await DocumentationCommand.ExecuteAsync(["api-package", "--docs-root", m_root, "--package", package]); @@ -764,7 +977,9 @@ public async Task ImportRestoresFactsWhenAuthoredContentRejectsSynchronization() File.WriteAllText(member, invalid); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); byte[] facts = File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json")); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package])); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package]) + ); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(facts, File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json"))); Assert.Equal(invalid, File.ReadAllText(member)); @@ -782,7 +997,7 @@ public async Task XmlSummaryAndSectionsHaveTheSameReadingOrderInMarkdownAndQueri JsonNode facts = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/api/probe.json")))!; facts["projects"]![0]!["symbols"]![0]!["baseType"] = "System.Object"; SaveFacts(facts); - await Sync(); + await SyncAsync(); string prose = File.ReadAllText(Fragment(C_TYPE)); Assert.DoesNotContain("Owns a value.", prose); Assert.DoesNotContain("Release it when finished.", prose); @@ -793,14 +1008,23 @@ public async Task XmlSummaryAndSectionsHaveTheSameReadingOrderInMarkdownAndQueri string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); Assert.Contains("# Value\n\n> - Owns a value.\n> \n> Release it when finished.", page.markdown); Assert.Contains("> - Owns", page.markdown); - Assert.True(page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal) + ); Assert.Contains("**API:** engine \n**Inherits:** `System.Object` \n**Project:** `Inno.Probe`", page.markdown); - Assert.True(page.markdown.IndexOf("## Declaration", StringComparison.Ordinal) < page.markdown.IndexOf("## Remarks", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf( + "## Declaration", + StringComparison.Ordinal + ) < page.markdown.IndexOf("## Remarks", StringComparison.Ordinal) + ); Assert.DoesNotContain("#### Remarks", page.markdown); - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_TYPE, "Inno.Probe"))).hits); + DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new DocumentationRequest("symbol", C_TYPE, "Inno.Probe"))).hits); Assert.Contains("Owns a value.", hit.text); Assert.Contains("Keep the owner alive.", hit.text); Assert.Equal(1, page.markdown.Split("Owns a value.", StringSplitOptions.None).Length - 1); @@ -809,21 +1033,28 @@ public async Task XmlSummaryAndSectionsHaveTheSameReadingOrderInMarkdownAndQueri [Fact] public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries() { - await Sync(); + await SyncAsync(); string typePath = Fragment(C_TYPE); string memberPath = Fragment(C_MEMBER); - File.WriteAllText(typePath, File.ReadAllText(typePath).Replace("description: null", "description: [Custom type introduction, Second type paragraph]", StringComparison.Ordinal)); - string original = File.ReadAllText(memberPath).Replace("source: xml", "source: Ada Lovelace", StringComparison.Ordinal) + File.WriteAllText( + typePath, + File.ReadAllText(typePath) + .Replace("description: null", "description: [Custom type introduction, Second type paragraph]", StringComparison.Ordinal) + ); + string original = File.ReadAllText(memberPath) + .Replace("source: xml", "source: Ada Lovelace", StringComparison.Ordinal) .Replace("description: null", "description: [Custom member introduction, Second member paragraph]", StringComparison.Ordinal); string body = "\n\n## Remarks\n\nKeep this author explanation byte for byte.\n"; File.WriteAllText(memberPath, original[..(original.Length - Body(original).Length)] + body); Bind(description: "Changed XML.", countType: "long"); - await Sync(); + await SyncAsync(); string saved = File.ReadAllText(memberPath); Assert.Contains("source: Ada Lovelace", saved); Assert.Contains("outdatedFor:", saved); Assert.Equal(body, Body(saved)); - Assert.True(saved.IndexOf("contracts:", StringComparison.Ordinal) < saved.IndexOf("# Authoring metadata", StringComparison.Ordinal)); + Assert.True( + saved.IndexOf("contracts:", StringComparison.Ordinal) < saved.IndexOf("# Authoring metadata", StringComparison.Ordinal) + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); @@ -834,8 +1065,11 @@ public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries( Assert.Contains("Custom member introduction

Second member paragraph", type.markdown); Assert.Contains("> - Second member paragraph", member.markdown); Assert.Contains("public long", member.markdown); - Assert.Contains(catalog.pages, page => page.markdown.Contains("Custom type introduction

Second type paragraph", StringComparison.Ordinal)); - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits); + Assert.Contains( + catalog.pages, + page => page.markdown.Contains("Custom type introduction

Second type paragraph", StringComparison.Ordinal) + ); + DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new DocumentationRequest("symbol", C_MEMBER, "Inno.Probe"))).hits); Assert.Contains("Custom member introduction", hit.text); Assert.DoesNotContain("Changed XML.", member.markdown); } @@ -846,11 +1080,11 @@ public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries( [InlineData("[null]")] public async Task InvalidDescriptionDoesNotOverwriteContent(string value) { - await Sync(); + await SyncAsync(); string path = Fragment(C_TYPE); string invalid = File.ReadAllText(path).Replace("description: null", "description: " + value, StringComparison.Ordinal); File.WriteAllText(path, invalid); - await Assert.ThrowsAsync(Sync); + await Assert.ThrowsAsync(SyncAsync); Assert.Equal(invalid, File.ReadAllText(path)); } @@ -861,20 +1095,25 @@ public async Task PartialSummariesRemainSeparateQuotedItemsWithoutSplittingTheir First declaration.Still the first summary. Second declaration with Value.Shared lifetime. """); - await Sync(); + await SyncAsync(); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); - Assert.Contains("> - First declaration.\n> \n> Still the first summary.\n> \n> - Second declaration with `Value`.", page.markdown); - string html = Markdig.Markdown.ToHtml(page.markdown); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); + Assert.Contains( + "> - First declaration.\n> \n> Still the first summary.\n> \n> - Second declaration with `Value`.", + page.markdown + ); + string html = Markdown.ToHtml(page.markdown); string summaryHtml = html[html.IndexOf("
\n
    ", StringComparison.Ordinal)..]; summaryHtml = summaryHtml[..summaryHtml.IndexOf("
", StringComparison.Ordinal)]; Assert.Equal(2, summaryHtml.Split("
  • ", StringSplitOptions.None).Length - 1); Assert.Contains("
    \n
      ", html); Assert.Contains("## Remarks\n\nShared lifetime.", File.ReadAllText(Fragment(C_TYPE))); Assert.DoesNotContain("First declaration.", File.ReadAllText(Fragment(C_TYPE))); - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_TYPE, "Inno.Probe"))).hits); + DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new DocumentationRequest("symbol", C_TYPE, "Inno.Probe"))).hits); Assert.Contains("> - Second declaration with `Value`.", hit.text); } @@ -882,21 +1121,25 @@ public async Task PartialSummariesRemainSeparateQuotedItemsWithoutSplittingTheir public async Task ManualBodySectionsRemainEditableWhileSummaryFollowsSource() { SetTypeDocumentation("Original summary.Original remarks."); - await Sync(); + await SyncAsync(); string path = Fragment(C_TYPE); string text = File.ReadAllText(path).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal); string body = "\n\n## Remarks\n\nMy independently maintained ownership explanation.\n"; File.WriteAllText(path, text[..(text.Length - Body(text).Length)] + body); SetTypeDocumentation("Updated source summary.Changed source remarks."); - await Sync(); + await SyncAsync(); Assert.Equal(body, Body(File.ReadAllText(path))); Assert.DoesNotContain("Updated source summary.", File.ReadAllText(path)); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); Assert.Contains("# Value\n\n> - Updated source summary.", page.markdown); - Assert.True(page.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal) + ); Assert.Contains("## Remarks\n\nMy independently maintained ownership explanation.", page.markdown); Assert.DoesNotContain("#### Remarks", page.markdown); Assert.DoesNotContain("Changed source remarks.", page.markdown); @@ -915,7 +1158,7 @@ public async Task NestedXmlListsAndFollowingContractsSurviveComposition() Retain the owner. After the list, observe failure. """); - await Sync(); + await SyncAsync(); string prose = File.ReadAllText(Fragment(C_TYPE)); Assert.Contains("- **Borrow** the value.", prose); Assert.Contains(" Do not release it.", prose); @@ -930,12 +1173,12 @@ public async Task NestedXmlListsAndFollowingContractsSurviveComposition() [InlineData("]>&injected;")] public async Task InvalidXmlCannotDiscardConstraintsOrReplaceLastGoodProse(string xml) { - await Sync(); + await SyncAsync(); string previous = File.ReadAllText(Fragment(C_TYPE)); SetTypeDocumentation(xml); - Exception? failure = await Record.ExceptionAsync(Sync); + Exception? failure = await Record.ExceptionAsync(SyncAsync); Assert.NotNull(failure); - Assert.True(failure is InvalidDataException or System.Xml.XmlException); + Assert.True(failure is InvalidDataException or XmlException); Assert.Equal(previous, File.ReadAllText(Fragment(C_TYPE))); } @@ -950,7 +1193,7 @@ public async Task XmlExampleFencesPreserveIndentationAndMarkupAsCode() } Observe failure after this example. """); - await Sync(); + await SyncAsync(); string prose = File.ReadAllText(Fragment(C_TYPE)); Assert.Contains("````csharp\nif (ready)\n{\n string marker = \"```